{"commit":"0821cd7dde18519044f251381d0393d9419ef0e7","subject":"Moved prelude","message":"Moved prelude\n","repos":"AshleyF\/Forthkit,AshleyF\/Forthkit,AshleyF\/Forthkit","old_file":"turtle\/prelude.4th","new_file":"turtle\/prelude.4th","new_contents":"","old_contents":"( : over ; )\n( : rot ; )\n( : nip swap drop ; )\n( : -rot rot rot ; )\n( : tuck swap over ; )\n\n( : sq dup * ; )\n\n: 2dup over over ;\n: 3dup 2dup dup ;\n: 2drop drop drop ;\n: 3drop 2drop drop ;\n\n: min 2dup > if swap then drop ; ( not used? )\n: max 2dup < if swap then drop ; ( not used? )\n: between rot swap over >= -rot <= and ;\n: +! dup @ rot + swap ! ;\n3.14159265359 const pi\npi 2 * const 2pi ( not used? )\npi 180 \/ const d2r\n: deg2rad d2r * ;\n\n: repeat 0 do ;\n\n: neg -1 * ;\n: abs dup 0 < if neg then ;\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"22a0d49328be13d522f6a843f1ec298e0a259c51","subject":"in reverse() for empty list, return a copy insead of self","message":"in reverse() for empty list, return a copy insead of self\n","repos":"cooper\/ferret","old_file":"std\/Extension\/List.frt","new_file":"std\/Extension\/List.frt","new_contents":"class List \n\n#> Represents a list with an event number of elements, treated as pairs.\n#| This is similar to a hash with ordered keys.\ntype Pairs {\n isa *class\n satisfies .length.even\n}\n\n#> True if the list is empty.\n.empty -> @length == 0\n\n#> Returns a copy of the list by mapping each element to another value based on\n#| a transformation code.\n.map {\n need $code: Code\n -> gather for $el in *self {\n take $code($el)\n }\n}\n\n#> Returns a copy of the list containing only the elements that satisfy a code.\n.grep {\n need $code: Code\n -> gather for $el in *self {\n if $code($el): take $el\n }\n}\n\n#> Returns a flattened copy of the list.\nmethod flatten {\n $new = []\n for $el in *self {\n if $el.*isa(List)\n $new.push(items: $el.flatten())\n else\n $new.push($el)\n }\n -> $new\n}\n\n#> Returns a reversed copy of the list.\nmethod reverse {\n if @empty\n -> @copy()\n -> gather for $i in @lastIndex..0:\n take *self[$i]\n}\n\n#> Copies the list, ignoring all possible occurrences of a specified value.\nmethod withoutAll {\n need $what\n -> @grep! { -> $what != $_ }\n # -> @grep(func { -> $what != $_ })\n}\n\n#> Copies the list, ignoring the first occurrence of a specified value.\nmethod without {\n need $what\n var $found\n -> gather for ($i, $el) in *self {\n if !$found && $what == $el {\n $found = true\n next\n }\n take $el\n }\n}\n\n#> Removes the first element equal to a specified value.\nmethod remove {\n need $what\n removed -> false\n for ($i, $el) in *self {\n if $what != $el\n next\n @splice($i, 1)\n removed -> true\n last\n }\n}\n\n#> Removes all elements equal to a specified value.\nmethod removeAll {\n need $what\n\n # find the indices at which the value occurs\n $indices = gather for ($i, $el) in *self {\n if $what != $el\n next\n take $i\n }\n\n # remove\n for $i in $indices.reverse!\n @splice($i, 1)\n\n removed -> $indices.length #< number of removed elements\n}\n\n#> Returns true if the list contains at least one occurrence of the provided\n#| value.\nmethod contains {\n need $what\n -> @any! { -> $what == $_ }\n}\n\n#> Finds the first element to satisfy a code.\nmethod first {\n need $code: Code\n for $el in *self {\n if $code($el): -> $el\n }\n -> undefined\n}\n\n#> Returns the index of the first occurrence of the given value\nmethod indexOf {\n need $what\n for ($i, $el) in *self {\n if $what == $el: -> $i\n }\n -> undefined\n}\n\n#> Returns true if at least one element satisfies a code.\nmethod any {\n need $code: Code\n for $el in *self {\n if $code($el): -> true\n }\n -> false\n}\n\n#> Returns true if all elements satisfy a code.\nmethod all {\n need $code: Code\n for $el in *self {\n if !$code($el): -> false\n }\n -> true\n}\n\n#> Returns the sum of all elements in the list or `undefined` if the list is\n#| empty.\n.sum {\n if @empty\n -> undefined\n $c = *self[0]\n for $i in 1 .. @lastIndex {\n $c = $c + *self[$i]\n }\n -> $c\n}\n\n#> Returns the sum of all elements in the list or `0` (zero) if the list is\n#| empty. Useful for lists of numbers.\n.sum0 {\n $c = 0\n for $el in *self {\n $c = $c + $el\n }\n -> $c\n}\n\n#> Returns the first element in the list.\n.firstItem -> *self[0]\n\n#> Returns the last element in the list.\n.lastItem -> *self[@lastIndex]\n\n#> If the list has length one, returns an empty string, otherwise `\"s\"`\n.s {\n if @length == 1\n -> \"\"\n -> \"s\"\n}\n\n#> Returns an iterator for the list. This allows lists to be used in a for loop.\n.iterator -> ListIterator(*self) : Iterator\n\n#> Adding lists together results in an ordered consolidation of the lists.\nop + {\n need $rhs: List\n $new = @copy()\n $new.push(items: $rhs)\n -> $new\n}\n\n#> Subtracting list B from list A results in a new list containing all elements\n#| found in A but not found in B. Example: `[1,2,3,4,5] - [3,5]` -> `[1,2,4]`.\nop - {\n need $rhs: List\n $new = @copy()\n for $remove in $rhs:\n $new.removeAll($remove)\n -> $new\n}\n\n#> Lists are equal if all the elements are equal and in the same order.\nop == {\n need $ehs: List\n\n # first check if length is same\n if @length != $ehs.length\n -> false\n\n # check each item\n for ($i, $val) in *self {\n if $ehs[$i] != $val\n -> false\n }\n\n -> true\n}\n\n#> Lists are equal to their numerical length.\nop == {\n need $ehs: Num\n -> @length == $ehs\n}\n\n#> Lists are greater than numbers smaller than their length.\nop > {\n need $rhs: Num\n -> @length > $rhs\n}\n\n#> Lists are smaller than numbers greater than their length.\nop < {\n need $rhs: Num\n -> @length < $rhs\n}\n\n#> Lists are greater than numbers smaller than their length.\nop > {\n need $lhs: Num\n -> @length < $lhs\n}\n\n#> Lists are smaller than numbers greater than their length.\nop < {\n need $lhs: Num\n -> @length > $lhs\n}\n\n# Iterator methods\n\n.iterator -> *self\n\nmethod reset {\n @i = -1\n}\n\n.more -> @i < (@lastIndex || -1)\n\n.nextElement {\n @i += 1\n -> *self[@i]\n}\n\n.nextElements {\n @i += 1\n -> [ @i, *self[@i] ]\n}","old_contents":"class List \n\n#> Represents a list with an event number of elements, treated as pairs.\n#| This is similar to a hash with ordered keys.\ntype Pairs {\n isa *class\n satisfies .length.even\n}\n\n#> True if the list is empty.\n.empty -> @length == 0\n\n#> Returns a copy of the list by mapping each element to another value based on\n#| a transformation code.\n.map {\n need $code: Code\n -> gather for $el in *self {\n take $code($el)\n }\n}\n\n#> Returns a copy of the list containing only the elements that satisfy a code.\n.grep {\n need $code: Code\n -> gather for $el in *self {\n if $code($el): take $el\n }\n}\n\n#> Returns a flattened copy of the list.\nmethod flatten {\n $new = []\n for $el in *self {\n if $el.*isa(List)\n $new.push(items: $el.flatten())\n else\n $new.push($el)\n }\n -> $new\n}\n\n#> Returns a reversed copy of the list.\nmethod reverse {\n if @empty\n -> *self\n -> gather for $i in @lastIndex..0:\n take *self[$i]\n}\n\n#> Copies the list, ignoring all possible occurrences of a specified value.\nmethod withoutAll {\n need $what\n -> @grep! { -> $what != $_ }\n # -> @grep(func { -> $what != $_ })\n}\n\n#> Copies the list, ignoring the first occurrence of a specified value.\nmethod without {\n need $what\n var $found\n -> gather for ($i, $el) in *self {\n if !$found && $what == $el {\n $found = true\n next\n }\n take $el\n }\n}\n\n#> Removes the first element equal to a specified value.\nmethod remove {\n need $what\n removed -> false\n for ($i, $el) in *self {\n if $what != $el\n next\n @splice($i, 1)\n removed -> true\n last\n }\n}\n\n#> Removes all elements equal to a specified value.\nmethod removeAll {\n need $what\n\n # find the indices at which the value occurs\n $indices = gather for ($i, $el) in *self {\n if $what != $el\n next\n take $i\n }\n\n # remove\n for $i in $indices.reverse!\n @splice($i, 1)\n\n removed -> $indices.length #< number of removed elements\n}\n\n#> Returns true if the list contains at least one occurrence of the provided\n#| value.\nmethod contains {\n need $what\n -> @any! { -> $what == $_ }\n}\n\n#> Finds the first element to satisfy a code.\nmethod first {\n need $code: Code\n for $el in *self {\n if $code($el): -> $el\n }\n -> undefined\n}\n\n#> Returns the index of the first occurrence of the given value\nmethod indexOf {\n need $what\n for ($i, $el) in *self {\n if $what == $el: -> $i\n }\n -> undefined\n}\n\n#> Returns true if at least one element satisfies a code.\nmethod any {\n need $code: Code\n for $el in *self {\n if $code($el): -> true\n }\n -> false\n}\n\n#> Returns true if all elements satisfy a code.\nmethod all {\n need $code: Code\n for $el in *self {\n if !$code($el): -> false\n }\n -> true\n}\n\n#> Returns the sum of all elements in the list or `undefined` if the list is\n#| empty.\n.sum {\n if @empty\n -> undefined\n $c = *self[0]\n for $i in 1 .. @lastIndex {\n $c = $c + *self[$i]\n }\n -> $c\n}\n\n#> Returns the sum of all elements in the list or `0` (zero) if the list is\n#| empty. Useful for lists of numbers.\n.sum0 {\n $c = 0\n for $el in *self {\n $c = $c + $el\n }\n -> $c\n}\n\n#> Returns the first element in the list.\n.firstItem -> *self[0]\n\n#> Returns the last element in the list.\n.lastItem -> *self[@lastIndex]\n\n#> If the list has length one, returns an empty string, otherwise `\"s\"`\n.s {\n if @length == 1\n -> \"\"\n -> \"s\"\n}\n\n#> Returns an iterator for the list. This allows lists to be used in a for loop.\n.iterator -> ListIterator(*self) : Iterator\n\n#> Adding lists together results in an ordered consolidation of the lists.\nop + {\n need $rhs: List\n $new = @copy()\n $new.push(items: $rhs)\n -> $new\n}\n\n#> Subtracting list B from list A results in a new list containing all elements\n#| found in A but not found in B. Example: `[1,2,3,4,5] - [3,5]` -> `[1,2,4]`.\nop - {\n need $rhs: List\n $new = @copy()\n for $remove in $rhs:\n $new.removeAll($remove)\n -> $new\n}\n\n#> Lists are equal if all the elements are equal and in the same order.\nop == {\n need $ehs: List\n\n # first check if length is same\n if @length != $ehs.length\n -> false\n\n # check each item\n for ($i, $val) in *self {\n if $ehs[$i] != $val\n -> false\n }\n\n -> true\n}\n\n#> Lists are equal to their numerical length.\nop == {\n need $ehs: Num\n -> @length == $ehs\n}\n\n#> Lists are greater than numbers smaller than their length.\nop > {\n need $rhs: Num\n -> @length > $rhs\n}\n\n#> Lists are smaller than numbers greater than their length.\nop < {\n need $rhs: Num\n -> @length < $rhs\n}\n\n#> Lists are greater than numbers smaller than their length.\nop > {\n need $lhs: Num\n -> @length < $lhs\n}\n\n#> Lists are smaller than numbers greater than their length.\nop < {\n need $lhs: Num\n -> @length > $lhs\n}\n\n# Iterator methods\n\n.iterator -> *self\n\nmethod reset {\n @i = -1\n}\n\n.more -> @i < (@lastIndex || -1)\n\n.nextElement {\n @i += 1\n -> *self[@i]\n}\n\n.nextElements {\n @i += 1\n -> [ @i, *self[@i] ]\n}","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"015c0f85e38f73e3f52e3c09afc3e795572c33d8","subject":"?NOT-TWO-ADJACENT-1-BITS tests added","message":"?NOT-TWO-ADJACENT-1-BITS tests added\n","repos":"bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas","old_file":"KataDiversion_tests.fth","new_file":"KataDiversion_tests.fth","new_contents":"\\ KataDiversion tests, in Forth\n\\ running tests:\n\\ gforth KataDiversion_tests.fth -e bye\n\nREQUIRE KataDiversion.fth\n\nVARIABLE ASSERT-COUNT\n\n: ASSERTS-INIT ( -- )\n 0 ASSERT-COUNT ! ;\n\n: ASSERTS-RESULT ( -- )\n ASSERT-COUNT @ . .\" assertions successfully passed.\" CR ;\n\n\\ destructive assert-equal\n: ASSERT-EQUAL-D ( n1 n2 -- )\n <> IF 1 ABORT\" AssertEqual: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-equal\n: ASSERT-EQUAL ( n1 n2 -- n1 n2 )\n 2DUP ASSERT-EQUAL-D ;\n\n\\ destructive assert-true\n: ASSERT-TRUE-D ( n -- )\n 0 = IF 1 ABORT\" AssertTrue: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-true\n: ASSERT-TRUE ( n -- n )\n DUP ASSERT-TRUE-D ;\n\n\\ destructive assert-false\n: ASSERT-False-D ( n -- )\n 0 <> IF 1 ABORT\" AssertFalse: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-false\n: ASSERT-FALSE ( n -- n )\n DUP ASSERT-FALSE-D ;\n\n\\ ---- tests ----\n\nASSERTS-INIT\n\n\\ ?EMPTY\nEMPTY DEPTH 0 ASSERT-EQUAL-D\nEMPTY EMPTY DEPTH 0 ASSERT-EQUAL-D\n0 EMPTY DEPTH 0 ASSERT-EQUAL-D\n1 2 3 4 EMPTY DEPTH 0 ASSERT-EQUAL-D\n\n\\ ?MAX-NB\n-1 ?MAX-NB 0 ASSERT-EQUAL-D\n 0 ?MAX-NB 0 ASSERT-EQUAL-D\n 1 ?MAX-NB 2 ASSERT-EQUAL-D\n 2 ?MAX-NB 4 ASSERT-EQUAL-D\n 3 ?MAX-NB 8 ASSERT-EQUAL-D\n\n\\ MAXPOW2\n 1 MAXPOW2 1 ASSERT-EQUAL-D\n 2 MAXPOW2 2 ASSERT-EQUAL-D\n 3 MAXPOW2 2 ASSERT-EQUAL-D\n 4 MAXPOW2 4 ASSERT-EQUAL-D\n 5 MAXPOW2 4 ASSERT-EQUAL-D\n 8 MAXPOW2 8 ASSERT-EQUAL-D\n 42 MAXPOW2 32 ASSERT-EQUAL-D\n2000 MAXPOW2 1024 ASSERT-EQUAL-D\n\n\n\\ ?TWO-ADJACENT-1-BITS\n 1 ?TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n 2 ?TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n 3 ?TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n 6 ?TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n 7 ?TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n 8 ?TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n 11 ?TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n 65 ?TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n3072 ?TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n\n\n\\ ?NOT-TWO-ADJACENT-1-BITS\n 1 ?NOT-TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n 2 ?NOT-TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n 3 ?NOT-TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n 6 ?NOT-TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n 7 ?NOT-TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n 8 ?NOT-TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n 11 ?NOT-TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n 65 ?NOT-TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n3072 ?NOT-TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n\nASSERTS-RESULT\n\\ ---------\n\n\n","old_contents":"\\ KataDiversion tests, in Forth\n\\ running tests:\n\\ gforth KataDiversion_tests.fth -e bye\n\nREQUIRE KataDiversion.fth\n\nVARIABLE ASSERT-COUNT\n\n: ASSERTS-INIT ( -- )\n 0 ASSERT-COUNT ! ;\n\n: ASSERTS-RESULT ( -- )\n ASSERT-COUNT @ . .\" assertions successfully passed.\" CR ;\n\n\\ destructive assert-equal\n: ASSERT-EQUAL-D ( n1 n2 -- )\n <> IF 1 ABORT\" AssertEqual: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-equal\n: ASSERT-EQUAL ( n1 n2 -- n1 n2 )\n 2DUP ASSERT-EQUAL-D ;\n\n\\ destructive assert-true\n: ASSERT-TRUE-D ( n -- )\n 0 = IF 1 ABORT\" AssertTrue: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-true\n: ASSERT-TRUE ( n -- n )\n DUP ASSERT-TRUE-D ;\n\n\\ destructive assert-false\n: ASSERT-False-D ( n -- )\n 0 <> IF 1 ABORT\" AssertFalse: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-false\n: ASSERT-FALSE ( n -- n )\n DUP ASSERT-FALSE-D ;\n\n\\ ---- tests ----\n\nASSERTS-INIT\n\n\\ ?EMPTY\nEMPTY DEPTH 0 ASSERT-EQUAL-D\nEMPTY EMPTY DEPTH 0 ASSERT-EQUAL-D\n0 EMPTY DEPTH 0 ASSERT-EQUAL-D\n1 2 3 4 EMPTY DEPTH 0 ASSERT-EQUAL-D\n\n\\ ?MAX-NB\n-1 ?MAX-NB 0 ASSERT-EQUAL-D\n 0 ?MAX-NB 0 ASSERT-EQUAL-D\n 1 ?MAX-NB 2 ASSERT-EQUAL-D\n 2 ?MAX-NB 4 ASSERT-EQUAL-D\n 3 ?MAX-NB 8 ASSERT-EQUAL-D\n\n\\ MAXPOW2\n 1 MAXPOW2 1 ASSERT-EQUAL-D\n 2 MAXPOW2 2 ASSERT-EQUAL-D\n 3 MAXPOW2 2 ASSERT-EQUAL-D\n 4 MAXPOW2 4 ASSERT-EQUAL-D\n 5 MAXPOW2 4 ASSERT-EQUAL-D\n 8 MAXPOW2 8 ASSERT-EQUAL-D\n 42 MAXPOW2 32 ASSERT-EQUAL-D\n2000 MAXPOW2 1024 ASSERT-EQUAL-D\n\n\n\\ ?TWO-ADJACENT-1-BITS\n 1 ?TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n 2 ?TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n 3 ?TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n 6 ?TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n 7 ?TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n 8 ?TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n 11 ?TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n 65 ?TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n3072 ?TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n\nASSERTS-RESULT\n\\ ---------\n\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"66958609ef4808566ca9a29d899deff2ef9d73c7","subject":"Cleanup.","message":"Cleanup.","repos":"rbsexton\/sockpuppet,rbsexton\/sockpuppet","old_file":"forth\/serCM3_sapi_p.fth","new_file":"forth\/serCM3_sapi_p.fth","new_contents":"\\ serCM3_sapi_p.fth - SAPI polled RX, polled TX, serial communication drivers\n\\ Written to run against the SockPuppet API.\n\n((\nAdapted from: the LPC polled driver.\n))\n\nonly forth definitions\nvariable cnt.pause \n\n\\ ==============\n\\ *! serCM3_sapi_p\n\\ *T SAPI polled serial driver\n\\ ==============\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\n\\ ** using the internal UARTs via the SAPI call layer.\n\n\n\\ ****************\n\\ *S Configuration\n\\ ****************\n\\ *P Configuration is managed by the SAPI\n\n\\ ********\n\\ *S Tools\n\\ ********\n\ntarget\n\n\\ ********************\n\\ *S Serial primitives\n\\ ********************\n\n0 value sercallback \n\ninternal\n\n: +FaultConsole\t( -- ) ;\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\n\\ ** for more details.\n\ntarget\n\nCODE (seremitfc)\t\\ char base --\n\\ *G Service call for a single char - just fill in the registers\n\\ from the stack and make the call, and get back the flow control feedback\n\\ Put TOS into r0, pull r1 off the stack, and refresh the stack.\n\tmov r0, tos\n\tldr r1, [ psp ], # 4\t\n\tsvc # SAPI_VEC_PUTCHAR\t\n\tmov tos, r0\n next,\nEND-CODE\n\n: (seremit)\t\\ char base -- \n\\ *G Wrapped call that checks for throttling, and if so,\n\\ calls PAUSE to let another task run. Count these events for debugging purposes.\n\t(seremitfc)\n\t0<> IF 1 cnt.pause +! #5 ms THEN\n\t;\n\n: (sertype)\t\\ caddr len base --\n\\ *G Transmit a string on the given UART.\n -rot bounds\n ?do i c@ over (seremit) loop\n drop\n;\n\n: (sercr)\t\\ base --\n\\ *G Transmit a CR\/LF pair on the given UART.\n $0D over (seremit) $0A swap (seremit)\n;\n\nCODE (sergetchar) \\ base -- c\n\\ *G Get a character from the port\n\tmov r0, tos\t\n\tsvc # SAPI_VEC_GETCHAR\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE (serkey?) \\ base -- t\/f\n\\ *G Return true if the given UART has a character avilable to read.\n\\ The call returns 0 or 1. \n\tmov r0, tos\n\tsvc # SAPI_VEC_CHARSAVAIL\t\t\n\tmov tos, r0\n\tnext,\t\nEND-CODE\n\n: (serkey-basic)\n\tbegin pause \n\tdup (serkey?) until \n\t(sergetchar)\n;\n\n: (serkey-sleep?)\n\tself tcb.bbstatus @ over 1 setiocallback drop ( base oldcb )\n\tself halt \n\tdup (serkey?) IF self restart ELSE PAUSE THEN \\ We are now armed and ready to block\n (serkey?)\n;\n\n\\ *G Wait for a character to come available on the given UART and\n\\ ** return the character.\n\\ Advanced usage - Register a callback. \n\\ The tricky part is not screwing things up by missing a character\n\\ in the window between when you register, and when you pick up your\n\\ character. The way to do that is by registering, then self \n\\ halting, and then checking for a new character. That ensures that\n\\ if a character has slipped in, you will catch it.\n: (serkey)\t\\ base -- char\n\tbegin dup (serkey-sleep?) until (sergetchar)\n;\n\nexternal \n\n: seremit0\t\\ char --\n\\ *G Transmit a character on UART0.\n 0 (seremit) ;\n: sertype0\t\\ c-addr len --\n\\ *G Transmit a string on UART0.\n 0 (sertype) ;\n: sercr0\t\\ --\n\\ *G Issue a CR\/LF pair to UART0.\n 0 (sercr) ;\n: serkey?0\t\\ -- flag\n\\ *G Return true if UART0 has a character available.\n 0 (serkey?) ;\n: serkey0\t\\ -- char\n\\ *G Wait for a character on UART0.\n 0 (serkey) ;\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\n\\ *G Generic I\/O device for UART0.\n ' serkey0 ,\t\t\\ -- char ; receive char\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\n ' seremit0 ,\t\t\\ -- char ; display char\n ' sertype0 ,\t\t\\ caddr len -- ; display string\n ' sercr0 ,\t\t\\ -- ; display new line\n\n\\ UART2\n: seremit2 #2 (seremit) ;\n: sertype2\t#2 (sertype) ;\n: sercr2\t#2 (sercr) ;\n: serkey?2\t#2 (serkey?) ;\n: serkey2\t#2 (serkey) ;\ncreate Console2 ' serkey2 , ' serkey?2 , ' seremit2 , ' sertype2 , ' sercr2 ,\t\n\n\\ Versions for use with the TCP Port (10)\n: seremit10 #10 (seremit) ;\n: sertype10\t#10 (sertype) ;\n: sercr10\t#10 (sercr) ;\n: serkey?10\t#10 (serkey?) ;\n: serkey10\t#10 (serkey) ;\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\n\nconsole-port 0 = [if]\n console0 constant console\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\n\\ ** It may be changed by one of the phrases of the form:\n\\ *C dup opvec ! ipvec !\n\\ *C SetConsole\n[then]\n\nconsole-port #1 = [if]\n console1 constant console\n[then]\n\nconsole-port #10 = [if]\n console10 constant console\n[then]\n\n\\ ************************\n\\ *S System initialisation\n\\ ************************\n\n\\ This is a NOP in the SAPI environment\n: init-ser ;\t\\ --\n\\ *G Initialise all serial ports\n\n\n\\ ======\n\\ *> ###\n\\ ======\n\ndecimal\n","old_contents":"\\ serCM3_sapi_p.fth - SAPI polled RX, polled TX, serial communication drivers\n\\ Written to run against the SockPuppet API.\n\n((\nAdapted from: the LPC polled driver.\n))\n\nonly forth definitions\nvariable cnt.pause \n\n\\ ==============\n\\ *! serCM3_sapi_p\n\\ *T SAPI polled serial driver\n\\ ==============\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\n\\ ** using the internal UARTs via the SAPI call layer.\n\n\n\\ ****************\n\\ *S Configuration\n\\ ****************\n\\ *P Configuration is managed by the SAPI\n\n\\ ********\n\\ *S Tools\n\\ ********\n\ntarget\n\n\\ ********************\n\\ *S Serial primitives\n\\ ********************\n\n0 value sercallback \n\ninternal\n\n: +FaultConsole\t( -- ) ;\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\n\\ ** for more details.\n\ntarget\n\nCODE (seremitfc)\t\\ char base --\n\\ *G Service call for a single char - just fill in the registers\n\\ from the stack and make the call, and get back the flow control feedback\n\\ Put TOS into r0, pull r1 off the stack, and refresh the stack.\n\tmov r0, tos\n\tldr r1, [ psp ], # 4\t\n\tsvc # SAPI_VEC_PUTCHAR\t\n\tmov tos, r0\n next,\nEND-CODE\n\n: (seremit)\t\\ char base -- \n\\ *G Wrapped call that checks for throttling, and if so,\n\\ calls PAUSE to let another task run. Count these events for debugging purposes.\n\t(seremitfc)\n\t0<> IF 1 cnt.pause +! #5 ms THEN\n\t;\n\n: (sertype)\t\\ caddr len base --\n\\ *G Transmit a string on the given UART.\n -rot bounds\n ?do i c@ over (seremit) loop\n drop\n;\n\n: (sercr)\t\\ base --\n\\ *G Transmit a CR\/LF pair on the given UART.\n $0D over (seremit) $0A swap (seremit)\n;\n\nCODE (sergetchar) \\ base -- c\n\\ *G Get a character from the port\n\tmov r0, tos\t\n\tsvc # SAPI_VEC_GETCHAR\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE (serkey?) \\ base -- t\/f\n\\ *G Return true if the given UART has a character avilable to read.\n\\ The call returns 0 or 1. \n\tmov r0, tos\n\tsvc # SAPI_VEC_CHARSAVAIL\t\t\n\tmov tos, r0\n\tnext,\t\nEND-CODE\n\n: (serkey-basic)\n\tbegin pause \n\tdup (serkey?) until \n\t(sergetchar)\n;\n\n: (serkey-sleep?)\n\tself tcb.bbstatus @ over 1 setiocallback drop ( base oldcb )\n\tself halt \n\tdup (serkey?) IF self restart ELSE PAUSE THEN \\ We are now armed and ready to block\n;\n\n\\ Advanced usage - Register a callback. \n\\ The tricky part is not screwing things up by missing a character\n\\ in the window between when you register, and when you pick up your\n\\ character. The way to do that is by registering, then self \n\\ halting, and then checking for a new character. That ensures that\n\\ if a character has slipped in, you will catch it.\n: (serkey-callback)\n\tbegin dup (serkey-sleep?) until (sergetchar)\n;\n\n: (serkey)\t\\ base -- char\n\\ *G Wait for a character to come available on the given UART and\n\\ ** return the character.\n\tsercallback IF (serkey-callback) ELSE (serkey-basic) THEN\n;\n\nexternal \n\n: seremit0\t\\ char --\n\\ *G Transmit a character on UART0.\n 0 (seremit) ;\n: sertype0\t\\ c-addr len --\n\\ *G Transmit a string on UART0.\n 0 (sertype) ;\n: sercr0\t\\ --\n\\ *G Issue a CR\/LF pair to UART0.\n 0 (sercr) ;\n: serkey?0\t\\ -- flag\n\\ *G Return true if UART0 has a character available.\n 0 (serkey?) ;\n: serkey0\t\\ -- char\n\\ *G Wait for a character on UART0.\n 0 (serkey) ;\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\n\\ *G Generic I\/O device for UART0.\n ' serkey0 ,\t\t\\ -- char ; receive char\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\n ' seremit0 ,\t\t\\ -- char ; display char\n ' sertype0 ,\t\t\\ caddr len -- ; display string\n ' sercr0 ,\t\t\\ -- ; display new line\n\n\\ UART2\n: seremit2 #2 (seremit) ;\n: sertype2\t#2 (sertype) ;\n: sercr2\t#2 (sercr) ;\n: serkey?2\t#2 (serkey?) ;\n: serkey2\t#2 (serkey) ;\ncreate Console2 ' serkey2 , ' serkey?2 , ' seremit2 , ' sertype2 , ' sercr2 ,\t\n\n\\ Versions for use with the TCP Port (10)\n: seremit10 #10 (seremit) ;\n: sertype10\t#10 (sertype) ;\n: sercr10\t#10 (sercr) ;\n: serkey?10\t#10 (serkey?) ;\n: serkey10\t#10 (serkey) ;\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\n\nconsole-port 0 = [if]\n console0 constant console\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\n\\ ** It may be changed by one of the phrases of the form:\n\\ *C dup opvec ! ipvec !\n\\ *C SetConsole\n[then]\n\nconsole-port #1 = [if]\n console1 constant console\n[then]\n\nconsole-port #10 = [if]\n console10 constant console\n[then]\n\n\\ ************************\n\\ *S System initialisation\n\\ ************************\n\n\\ This is a NOP in the SAPI environment\n: init-ser ;\t\\ --\n\\ *G Initialise all serial ports\n\n\n\\ ======\n\\ *> ###\n\\ ======\n\ndecimal\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"01a854a8fd52202659ae5326e96715cc3162cfba","subject":"?TWO-ADJACENT-1-BITS removed","message":"?TWO-ADJACENT-1-BITS removed\n","repos":"bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas","old_file":"KataDiversion.fth","new_file":"KataDiversion.fth","new_contents":"\\ KataDiversion in Forth\n\n\\ -- utils\n\n\\ empty the stack\n: EMPTY\n DEPTH 0 <> IF BEGIN\n DROP DEPTH 0 =\n UNTIL\n THEN ;\n\n\\ power\n: ** ( n1 n2 -- n1_pow_n2 ) 1 SWAP ?DUP IF 0 DO OVER * LOOP THEN NIP ;\n\n\\ compute the highest power of 2 below N.\n\\ e.g. : 31 -> 16, 4 -> 4\n: MAXPOW2 ( n -- log2_n ) DUP 1 < IF 1 ABORT\" Maxpow2 need a positive value.\"\n ELSE DUP 1 = IF 1\n ELSE\n 1 >R\n BEGIN ( n |R: i=1)\n DUP DUP I - 2 *\n ( n n 2*[n-i])\n R> 2 * >R ( \u2026 |R: i*2)\n > ( n n>2*[n-i] )\n UNTIL\n R> 2 \/\n THEN\n THEN NIP ;\n\n\\ -- kata\n\n\\ test if the given N has two adjacent 1 bits\n\\ e.g. : 11 -> 1011 -> -1\n\\ 9 -> 1001 -> 0\n: ?NOT-TWO-ADJACENT-1-BITS ( n -- bool )\n \\ the word uses the following algorithm :\n \\ (stack|return stack)\n \\ ( A N | X ) A: 0, X: N LOG2\n \\ loop: if N-X > 0 then A++ else A=0 ; X \/= 2\n \\ return 0 if A=2\n \\ if X=1 end loop and return -1\n 0 SWAP DUP DUP 0 <> IF\n MAXPOW2 >R\n BEGIN\n DUP I - 0 >= IF \n SWAP DUP 1 = IF 1+ SWAP\n ELSE 1+ SWAP I -\n THEN\n ELSE NIP 0 SWAP\n THEN\n OVER\n 2 =\n I 1 = OR\n R> 2 \/ >R\n UNTIL\n R> 2DROP\n 2 <>\n THEN ;\n\n\\ return the maximum number which can be made with N (given number) bits\n: ?MAX-NB ( n -- m ) DUP 1 < IF DROP 0 ( 0 )\n ELSE \n DUP IF DUP 2 SWAP ** NIP ( 2**n )\n THEN\n THEN ;\n\n\n\\ return the number of numbers which can be made with N (given number) bits\n\\ or less, and which have not two adjacent 1 bits.\n\\ see http:\/\/www.codekata.com\/2007\/01\/code_kata_fifte.html\n: ?HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS ( n -- m ) ( TODO ) ;\n","old_contents":"\\ KataDiversion in Forth\n\n\\ -- utils\n\n\\ empty the stack\n: EMPTY\n DEPTH 0 <> IF BEGIN\n DROP DEPTH 0 =\n UNTIL\n THEN ;\n\n\\ power\n: ** ( n1 n2 -- n1_pow_n2 ) 1 SWAP ?DUP IF 0 DO OVER * LOOP THEN NIP ;\n\n\\ compute the highest power of 2 below N.\n\\ e.g. : 31 -> 16, 4 -> 4\n: MAXPOW2 ( n -- log2_n ) DUP 1 < IF 1 ABORT\" Maxpow2 need a positive value.\"\n ELSE DUP 1 = IF 1\n ELSE\n 1 >R\n BEGIN ( n |R: i=1)\n DUP DUP I - 2 *\n ( n n 2*[n-i])\n R> 2 * >R ( \u2026 |R: i*2)\n > ( n n>2*[n-i] )\n UNTIL\n R> 2 \/\n THEN\n THEN NIP ;\n\n\\ -- kata\n\n\\ test if the given N has two adjacent 1 bits\n\\ e.g. : 11 -> 1011 -> -1\n\\ 9 -> 1001 -> 0\n: ?TWO-ADJACENT-1-BITS ( n -- bool )\n \\ the word uses the following algorithm :\n \\ (stack|return stack)\n \\ ( A N | X ) A: 0, X: N LOG2\n \\ loop: if N-X > 0 then A++ else A=0 ; X \/= 2\n \\ return -1 if A=2\n \\ if X=1 end loop and return 0\n 0 SWAP DUP DUP 0 <> IF\n MAXPOW2 >R\n BEGIN\n DUP I - 0 >= IF \n SWAP DUP 1 = IF 1+ SWAP\n ELSE 1+ SWAP I -\n THEN\n ELSE NIP 0 SWAP\n THEN\n OVER\n 2 =\n I 1 = OR\n R> 2 \/ >R\n UNTIL\n R> 2DROP\n 2 =\n THEN ;\n\n: ?NOT-TWO-ADJACENT-1-BITS ( n -- bool ) ?TWO-ADJACENT-1-BITS INVERT ;\n\n\\ return the maximum number which can be made with N (given number) bits\n: ?MAX-NB ( n -- m ) DUP 1 < IF DROP 0 ( 0 )\n ELSE \n DUP IF DUP 2 SWAP ** NIP ( 2**n )\n THEN\n THEN ;\n\n\n\\ return the number of numbers which can be made with N (given number) bits\n\\ or less, and which have not two adjacent 1 bits.\n\\ see http:\/\/www.codekata.com\/2007\/01\/code_kata_fifte.html\n: ?HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS ( n -- m ) ( TODO ) ;\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"6b8e2edb12a94058d978301bf0f699c72a889e9a","subject":"Pull an unused value.","message":"Pull an unused value.","repos":"rbsexton\/sockpuppet,rbsexton\/sockpuppet","old_file":"forth\/serCM3_sapi_p.fth","new_file":"forth\/serCM3_sapi_p.fth","new_contents":"\\ serCM3_sapi_p.fth - SAPI polled RX, polled TX, serial communication drivers\n\\ Written to run against the SockPuppet API.\n\n((\nAdapted from: the LPC polled driver.\n))\n\nonly forth definitions\nvariable cnt.pause \n\n\\ ==============\n\\ *! serCM3_sapi_p\n\\ *T SAPI polled serial driver\n\\ ==============\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\n\\ ** using the internal UARTs via the SAPI call layer.\n\n\n\\ ****************\n\\ *S Configuration\n\\ ****************\n\\ *P Configuration is managed by the SAPI\n\n\\ ********\n\\ *S Tools\n\\ ********\n\ntarget\n\n\\ ********************\n\\ *S Serial primitives\n\\ ********************\ninternal\n\n: +FaultConsole\t( -- ) ;\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\n\\ ** for more details.\n\ntarget\n\nCODE (seremitfc)\t\\ char base --\n\\ *G Service call for a single char - just fill in the registers\n\\ from the stack and make the call, and get back the flow control feedback\n\\ Put TOS into r0, pull r1 off the stack, and refresh the stack.\n\tmov r0, tos\n\tldr r1, [ psp ], # 4\t\n\tsvc # SAPI_VEC_PUTCHAR\t\n\tmov tos, r0\n next,\nEND-CODE\n\n: (seremit)\t\\ char base -- \n\\ *G Wrapped call that checks for throttling, and if so,\n\\ calls PAUSE to let another task run. Count these events for debugging purposes.\n\t(seremitfc)\n\t0<> IF 1 cnt.pause +! #5 ms THEN\n\t;\n\n: (sertype)\t\\ caddr len base --\n\\ *G Transmit a string on the given UART.\n -rot bounds\n ?do i c@ over (seremit) loop\n drop\n;\n\n: (sercr)\t\\ base --\n\\ *G Transmit a CR\/LF pair on the given UART.\n $0D over (seremit) $0A swap (seremit)\n;\n\nCODE (sergetchar) \\ base -- c\n\\ *G Get a character from the port\n\tmov r0, tos\t\n\tsvc # SAPI_VEC_GETCHAR\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE (serkey?) \\ base -- t\/f\n\\ *G Return true if the given UART has a character avilable to read.\n\\ The call returns 0 or 1. \n\tmov r0, tos\n\tsvc # SAPI_VEC_CHARSAVAIL\t\t\n\tmov tos, r0\n\tnext,\t\nEND-CODE\n\n: (serkey-basic)\n\tbegin pause \n\tdup (serkey?) until \n\t(sergetchar)\n;\n\n: (serkey-sleep?)\n\tself tcb.bbstatus @ over 1 setiocallback drop ( base )\n\tself halt \n\tdup (serkey?) IF self restart ELSE PAUSE THEN \\ We are now armed and ready to block\n (serkey?) \n;\n\n\\ *G Wait for a character to come available on the given UART and\n\\ ** return the character.\n\\ Advanced usage - Register a callback. \n\\ The tricky part is not screwing things up by missing a character\n\\ in the window between when you register, and when you pick up your\n\\ character. The way to do that is by registering, then self \n\\ halting, and then checking for a new character. That ensures that\n\\ if a character has slipped in, you will catch it.\n: (serkey)\t\\ base -- char\n\tbegin dup (serkey-sleep?) until (sergetchar)\n;\n\nexternal \n\n: seremit0\t\\ char --\n\\ *G Transmit a character on UART0.\n 0 (seremit) ;\n: sertype0\t\\ c-addr len --\n\\ *G Transmit a string on UART0.\n 0 (sertype) ;\n: sercr0\t\\ --\n\\ *G Issue a CR\/LF pair to UART0.\n 0 (sercr) ;\n: serkey?0\t\\ -- flag\n\\ *G Return true if UART0 has a character available.\n 0 (serkey?) ;\n: serkey0\t\\ -- char\n\\ *G Wait for a character on UART0.\n 0 (serkey) ;\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\n\\ *G Generic I\/O device for UART0.\n ' serkey0 ,\t\t\\ -- char ; receive char\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\n ' seremit0 ,\t\t\\ -- char ; display char\n ' sertype0 ,\t\t\\ caddr len -- ; display string\n ' sercr0 ,\t\t\\ -- ; display new line\n\n\\ UART2\n: seremit2 #2 (seremit) ;\n: sertype2\t#2 (sertype) ;\n: sercr2\t#2 (sercr) ;\n: serkey?2\t#2 (serkey?) ;\n: serkey2\t#2 (serkey) ;\ncreate Console2 ' serkey2 , ' serkey?2 , ' seremit2 , ' sertype2 , ' sercr2 ,\t\n\n\\ Versions for use with the TCP Port (10)\n: seremit10 #10 (seremit) ;\n: sertype10\t#10 (sertype) ;\n: sercr10\t#10 (sercr) ;\n: serkey?10\t#10 (serkey?) ;\n: serkey10\t#10 (serkey) ;\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\n\nconsole-port 0 = [if]\n console0 constant console\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\n\\ ** It may be changed by one of the phrases of the form:\n\\ *C dup opvec ! ipvec !\n\\ *C SetConsole\n[then]\n\nconsole-port #1 = [if]\n console1 constant console\n[then]\n\nconsole-port #10 = [if]\n console10 constant console\n[then]\n\n\\ ************************\n\\ *S System initialisation\n\\ ************************\n\n\\ This is a NOP in the SAPI environment\n: init-ser ;\t\\ --\n\\ *G Initialise all serial ports\n\n\n\\ ======\n\\ *> ###\n\\ ======\n\ndecimal\n","old_contents":"\\ serCM3_sapi_p.fth - SAPI polled RX, polled TX, serial communication drivers\n\\ Written to run against the SockPuppet API.\n\n((\nAdapted from: the LPC polled driver.\n))\n\nonly forth definitions\nvariable cnt.pause \n\n\\ ==============\n\\ *! serCM3_sapi_p\n\\ *T SAPI polled serial driver\n\\ ==============\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\n\\ ** using the internal UARTs via the SAPI call layer.\n\n\n\\ ****************\n\\ *S Configuration\n\\ ****************\n\\ *P Configuration is managed by the SAPI\n\n\\ ********\n\\ *S Tools\n\\ ********\n\ntarget\n\n\\ ********************\n\\ *S Serial primitives\n\\ ********************\n\n0 value sercallback \n\ninternal\n\n: +FaultConsole\t( -- ) ;\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\n\\ ** for more details.\n\ntarget\n\nCODE (seremitfc)\t\\ char base --\n\\ *G Service call for a single char - just fill in the registers\n\\ from the stack and make the call, and get back the flow control feedback\n\\ Put TOS into r0, pull r1 off the stack, and refresh the stack.\n\tmov r0, tos\n\tldr r1, [ psp ], # 4\t\n\tsvc # SAPI_VEC_PUTCHAR\t\n\tmov tos, r0\n next,\nEND-CODE\n\n: (seremit)\t\\ char base -- \n\\ *G Wrapped call that checks for throttling, and if so,\n\\ calls PAUSE to let another task run. Count these events for debugging purposes.\n\t(seremitfc)\n\t0<> IF 1 cnt.pause +! #5 ms THEN\n\t;\n\n: (sertype)\t\\ caddr len base --\n\\ *G Transmit a string on the given UART.\n -rot bounds\n ?do i c@ over (seremit) loop\n drop\n;\n\n: (sercr)\t\\ base --\n\\ *G Transmit a CR\/LF pair on the given UART.\n $0D over (seremit) $0A swap (seremit)\n;\n\nCODE (sergetchar) \\ base -- c\n\\ *G Get a character from the port\n\tmov r0, tos\t\n\tsvc # SAPI_VEC_GETCHAR\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE (serkey?) \\ base -- t\/f\n\\ *G Return true if the given UART has a character avilable to read.\n\\ The call returns 0 or 1. \n\tmov r0, tos\n\tsvc # SAPI_VEC_CHARSAVAIL\t\t\n\tmov tos, r0\n\tnext,\t\nEND-CODE\n\n: (serkey-basic)\n\tbegin pause \n\tdup (serkey?) until \n\t(sergetchar)\n;\n\n: (serkey-sleep?)\n\tself tcb.bbstatus @ over 1 setiocallback drop ( base )\n\tself halt \n\tdup (serkey?) IF self restart ELSE PAUSE THEN \\ We are now armed and ready to block\n (serkey?) \n;\n\n\\ *G Wait for a character to come available on the given UART and\n\\ ** return the character.\n\\ Advanced usage - Register a callback. \n\\ The tricky part is not screwing things up by missing a character\n\\ in the window between when you register, and when you pick up your\n\\ character. The way to do that is by registering, then self \n\\ halting, and then checking for a new character. That ensures that\n\\ if a character has slipped in, you will catch it.\n: (serkey)\t\\ base -- char\n\tbegin dup (serkey-sleep?) until (sergetchar)\n;\n\nexternal \n\n: seremit0\t\\ char --\n\\ *G Transmit a character on UART0.\n 0 (seremit) ;\n: sertype0\t\\ c-addr len --\n\\ *G Transmit a string on UART0.\n 0 (sertype) ;\n: sercr0\t\\ --\n\\ *G Issue a CR\/LF pair to UART0.\n 0 (sercr) ;\n: serkey?0\t\\ -- flag\n\\ *G Return true if UART0 has a character available.\n 0 (serkey?) ;\n: serkey0\t\\ -- char\n\\ *G Wait for a character on UART0.\n 0 (serkey) ;\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\n\\ *G Generic I\/O device for UART0.\n ' serkey0 ,\t\t\\ -- char ; receive char\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\n ' seremit0 ,\t\t\\ -- char ; display char\n ' sertype0 ,\t\t\\ caddr len -- ; display string\n ' sercr0 ,\t\t\\ -- ; display new line\n\n\\ UART2\n: seremit2 #2 (seremit) ;\n: sertype2\t#2 (sertype) ;\n: sercr2\t#2 (sercr) ;\n: serkey?2\t#2 (serkey?) ;\n: serkey2\t#2 (serkey) ;\ncreate Console2 ' serkey2 , ' serkey?2 , ' seremit2 , ' sertype2 , ' sercr2 ,\t\n\n\\ Versions for use with the TCP Port (10)\n: seremit10 #10 (seremit) ;\n: sertype10\t#10 (sertype) ;\n: sercr10\t#10 (sercr) ;\n: serkey?10\t#10 (serkey?) ;\n: serkey10\t#10 (serkey) ;\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\n\nconsole-port 0 = [if]\n console0 constant console\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\n\\ ** It may be changed by one of the phrases of the form:\n\\ *C dup opvec ! ipvec !\n\\ *C SetConsole\n[then]\n\nconsole-port #1 = [if]\n console1 constant console\n[then]\n\nconsole-port #10 = [if]\n console10 constant console\n[then]\n\n\\ ************************\n\\ *S System initialisation\n\\ ************************\n\n\\ This is a NOP in the SAPI environment\n: init-ser ;\t\\ --\n\\ *G Initialise all serial ports\n\n\n\\ ======\n\\ *> ###\n\\ ======\n\ndecimal\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"05e76aeb43097757afe85e90bbafdac1f4b8ac56","subject":"list comparison to number checks against length","message":"list comparison to number checks against length\n","repos":"cooper\/ferret","old_file":"std\/Extension\/List.frt","new_file":"std\/Extension\/List.frt","new_contents":"class List \n\n#> Represents a list with an event number of elements, treated as pairs.\n#| This is similar to a hash with ordered keys.\ntype Pairs {\n isa *class\n satisfies .length.even\n}\n\n#> True if the list is empty.\n.empty -> @length == 0\n\n#> Returns a copy of the list by mapping each element to another value based on\n#| a transformation code.\n.map {\n need $code: Code\n -> gather for $el in *self {\n take $code($el)\n }\n}\n\n#> Returns a copy of the list containing only the elements that satisfy a code.\n.grep {\n need $code: Code\n -> gather for $el in *self {\n if $code($el): take $el\n }\n}\n\n#> Returns a flattened copy of the list.\nmethod flatten {\n $new = []\n for $el in *self {\n if $el.*isa(List)\n $new.push(items: $el.flatten())\n else\n $new.push($el)\n }\n -> $new\n}\n\n#> Returns a reversed copy of the list.\nmethod reverse {\n if @empty\n -> *self\n -> gather for $i in @lastIndex..0:\n take *self[$i]\n}\n\n#> Copies the list, ignoring all possible occurrences of a specified value.\nmethod withoutAll {\n need $what\n -> @grep! { -> $what != $_ }\n # -> @grep(func { -> $what != $_ })\n}\n\n#> Copies the list, ignoring the first occurrence of a specified value.\nmethod without {\n need $what\n var $found\n -> gather for ($i, $el) in *self {\n if !$found && $what == $el {\n $found = true\n next\n }\n take $el\n }\n}\n\n#> Removes the first element equal to a specified value.\nmethod remove {\n need $what\n removed -> false\n for ($i, $el) in *self {\n if $what != $el\n next\n @splice($i, 1)\n removed -> true\n last\n }\n}\n\n#> Removes all elements equal to a specified value.\nmethod removeAll {\n need $what\n\n # find the indices at which the value occurs\n $indices = gather for ($i, $el) in *self {\n if $what != $el\n next\n take $i\n }\n\n # remove\n for $i in $indices.reverse!\n @splice($i, 1)\n\n removed -> $indices.length #< number of removed elements\n}\n\n#> Returns true if the list contains at least one occurrence of the provided\n#| value.\nmethod contains {\n need $what\n -> @any! { -> $what == $_ }\n}\n\n#> Finds the first element to satisfy a code.\nmethod first {\n need $code: Code\n for $el in *self {\n if $code($el): -> $el\n }\n -> undefined\n}\n\n#> Returns the index of the first occurrence of the given value\nmethod indexOf {\n need $what\n for ($i, $el) in *self {\n if $what == $el: -> $i\n }\n -> undefined\n}\n\n#> Returns true if at least one element satisfies a code.\nmethod any {\n need $code: Code\n for $el in *self {\n if $code($el): -> true\n }\n -> false\n}\n\n#> Returns true if all elements satisfy a code.\nmethod all {\n need $code: Code\n for $el in *self {\n if !$code($el): -> false\n }\n -> true\n}\n\n#> Returns the sum of all elements in the list or `undefined` if the list is\n#| empty.\n.sum {\n if @empty\n -> undefined\n $c = *self[0]\n for $i in 1 .. @lastIndex {\n $c = $c + *self[$i]\n }\n -> $c\n}\n\n#> Returns the sum of all elements in the list or `0` (zero) if the list is\n#| empty. Useful for lists of numbers.\n.sum0 {\n $c = 0\n for $el in *self {\n $c = $c + $el\n }\n -> $c\n}\n\n#> Returns the first element in the list.\n.firstItem -> *self[0]\n\n#> Returns the last element in the list.\n.lastItem -> *self[@lastIndex]\n\n#> If the list has length one, returns an empty string, otherwise `\"s\"`\n.s {\n if @length == 1\n -> \"\"\n -> \"s\"\n}\n\n#> Returns an iterator for the list. This allows lists to be used in a for loop.\n.iterator -> ListIterator(*self) : Iterator\n\n#> Adding lists together results in an ordered consolidation of the lists.\nop + {\n need $rhs: List\n $new = @copy()\n $new.push(items: $rhs)\n -> $new\n}\n\n#> Subtracting list B from list A results in a new list containing all elements\n#| found in A but not found in B. Example: `[1,2,3,4,5] - [3,5]` -> `[1,2,4]`.\nop - {\n need $rhs: List\n $new = @copy()\n for $remove in $rhs:\n $new.removeAll($remove)\n -> $new\n}\n\n#> Lists are equal if all the elements are equal and in the same order.\nop == {\n need $ehs: List\n\n # first check if length is same\n if @length != $ehs.length\n -> false\n\n # check each item\n for ($i, $val) in *self {\n if $ehs[$i] != $val\n -> false\n }\n\n -> true\n}\n\n#> Lists are equal to their numerical length.\nop == {\n need $ehs: Num\n -> @length == $ehs\n}\n\n#> Lists are greater than numbers smaller than their length.\nop > {\n need $rhs: Num\n -> @length > $rhs\n}\n\n#> Lists are smaller than numbers greater than their length.\nop < {\n need $rhs: Num\n -> @length < $rhs\n}\n\n# Iterator methods\n\n.iterator -> *self\n\nmethod reset {\n @i = -1\n}\n\n.more -> @i < (@lastIndex || -1)\n\n.nextElement {\n @i += 1\n -> *self[@i]\n}\n\n.nextElements {\n @i += 1\n -> [ @i, *self[@i] ]\n}","old_contents":"class List \n\n#> Represents a list with an event number of elements, treated as pairs.\n#| This is similar to a hash with ordered keys.\ntype Pairs {\n isa *class\n satisfies .length.even\n}\n\n#> True if the list is empty.\n.empty -> @length == 0\n\n#> Returns a copy of the list by mapping each element to another value based on\n#| a transformation code.\n.map {\n need $code: Code\n -> gather for $el in *self {\n take $code($el)\n }\n}\n\n#> Returns a copy of the list containing only the elements that satisfy a code.\n.grep {\n need $code: Code\n -> gather for $el in *self {\n if $code($el): take $el\n }\n}\n\n#> Returns a flattened copy of the list.\nmethod flatten {\n $new = []\n for $el in *self {\n if $el.*isa(List)\n $new.push(items: $el.flatten())\n else\n $new.push($el)\n }\n -> $new\n}\n\n#> Returns a reversed copy of the list.\nmethod reverse {\n if @empty\n -> *self\n -> gather for $i in @lastIndex..0:\n take *self[$i]\n}\n\n#> Copies the list, ignoring all possible occurrences of a specified value.\nmethod withoutAll {\n need $what\n -> @grep! { -> $what != $_ }\n # -> @grep(func { -> $what != $_ })\n}\n\n#> Copies the list, ignoring the first occurrence of a specified value.\nmethod without {\n need $what\n var $found\n -> gather for ($i, $el) in *self {\n if !$found && $what == $el {\n $found = true\n next\n }\n take $el\n }\n}\n\n#> Removes the first element equal to a specified value.\nmethod remove {\n need $what\n removed -> false\n for ($i, $el) in *self {\n if $what != $el\n next\n @splice($i, 1)\n removed -> true\n last\n }\n}\n\n#> Removes all elements equal to a specified value.\nmethod removeAll {\n need $what\n\n # find the indices at which the value occurs\n $indices = gather for ($i, $el) in *self {\n if $what != $el\n next\n take $i\n }\n\n # remove\n for $i in $indices.reverse!\n @splice($i, 1)\n\n removed -> $indices.length #< number of removed elements\n}\n\n#> Returns true if the list contains at least one occurrence of the provided\n#| value.\nmethod contains {\n need $what\n -> @any! { -> $what == $_ }\n}\n\n#> Finds the first element to satisfy a code.\nmethod first {\n need $code: Code\n for $el in *self {\n if $code($el): -> $el\n }\n -> undefined\n}\n\n#> Returns the index of the first occurrence of the given value\nmethod indexOf {\n need $what\n for ($i, $el) in *self {\n if $what == $el: -> $i\n }\n -> undefined\n}\n\n#> Returns true if at least one element satisfies a code.\nmethod any {\n need $code: Code\n for $el in *self {\n if $code($el): -> true\n }\n -> false\n}\n\n#> Returns true if all elements satisfy a code.\nmethod all {\n need $code: Code\n for $el in *self {\n if !$code($el): -> false\n }\n -> true\n}\n\n#> Returns the sum of all elements in the list or `undefined` if the list is\n#| empty.\n.sum {\n if @empty\n -> undefined\n $c = *self[0]\n for $i in 1 .. @lastIndex {\n $c = $c + *self[$i]\n }\n -> $c\n}\n\n#> Returns the sum of all elements in the list or `0` (zero) if the list is\n#| empty. Useful for lists of numbers.\n.sum0 {\n $c = 0\n for $el in *self {\n $c = $c + $el\n }\n -> $c\n}\n\n#> Returns the first element in the list.\n.firstItem -> *self[0]\n\n#> Returns the last element in the list.\n.lastItem -> *self[@lastIndex]\n\n#> If the list has length one, returns an empty string, otherwise `\"s\"`\n.s {\n if @length == 1\n -> \"\"\n -> \"s\"\n}\n\n#> Returns an iterator for the list. This allows lists to be used in a for loop.\n.iterator -> ListIterator(*self) : Iterator\n\n#> Adding lists together results in an ordered consolidation of the lists.\nop + {\n need $rhs: List\n $new = @copy()\n $new.push(items: $rhs)\n -> $new\n}\n\n#> Subtracting list B from list A results in a new list containing all elements\n#| found in A but not found in B. Example: `[1,2,3,4,5] - [3,5]` -> `[1,2,4]`.\nop - {\n need $rhs: List\n $new = @copy()\n for $remove in $rhs:\n $new.removeAll($remove)\n -> $new\n}\n\n#> Lists are equal if all the elements are equal and in the same order.\nop == {\n need $ehs: List\n\n # first check if length is same\n if @length != $ehs.length\n -> false\n\n # check each item\n for ($i, $val) in *self {\n if $ehs[$i] != $val\n -> false\n }\n\n -> true\n}\n\n# Iterator methods\n\n.iterator -> *self\n\nmethod reset {\n @i = -1\n}\n\n.more -> @i < (@lastIndex || -1)\n\n.nextElement {\n @i += 1\n -> *self[@i]\n}\n\n.nextElements {\n @i += 1\n -> [ @i, *self[@i] ]\n}","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"1d1ba3da6b5ec30cbcedd719bde3804b22e2d947","subject":"Count Pauses.","message":"Count Pauses.","repos":"rbsexton\/sockpuppet,rbsexton\/sockpuppet","old_file":"forth\/serCM3_sapi_p.fth","new_file":"forth\/serCM3_sapi_p.fth","new_contents":"\\ serCM3_sapi_p.fth - SAPI polled RX, polled TX, serial communication drivers\r\n\\ Written to run against the SockPuppet API.\r\n\r\n((\r\nAdapted from: the LPC polled driver.\r\n))\r\n\r\nonly forth definitions\r\nvariable cnt.pause \r\n\r\n\\ ==============\r\n\\ *! serCM3_sapi_p\r\n\\ *T SAPI polled serial driver\r\n\\ ==============\r\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\r\n\\ ** using the internal UARTs via the SAPI call layer.\r\n\r\n\r\n\\ ****************\r\n\\ *S Configuration\r\n\\ ****************\r\n\\ *P Configuration is managed by the SAPI\r\n\r\n\\ ********\r\n\\ *S Tools\r\n\\ ********\r\n\r\ntarget\r\n\r\n\\ ********************\r\n\\ *S Serial primitives\r\n\\ ********************\r\n\r\ninternal\r\n\r\n: +FaultConsole\t( -- ) ;\r\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\r\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\r\n\\ ** for more details.\r\n\r\ntarget\r\n\r\nCODE (seremitfc)\t\\ char base --\r\n\\ *G Service call for a single char - just fill in the registers\r\n\\ from the stack and make the call, and get back the flow control feedback\r\n\\ Put TOS into r0, pull r1 off the stack, and refresh the stack.\r\n\tmov r0, tos\r\n\tldr r1, [ psp ], # 4\t\r\n\tsvc # SAPI_VEC_PUTCHAR\t\r\n\tmov tos, r0\r\n next,\r\nEND-CODE\r\n\r\n: (seremit)\t\\ char base -- \r\n\\ *G Wrapped call that checks for throttling, and if so,\r\n\\ calls PAUSE to let another task run. Count these events for debugging purposes.\r\n\t(seremitfc)\r\n\t0<> IF 1 cnt.pause +! PAUSE THEN\r\n\t;\r\n\r\n: (sertype)\t\\ caddr len base --\r\n\\ *G Transmit a string on the given UART.\r\n -rot bounds\r\n ?do i c@ over (seremit) loop\r\n drop\r\n;\r\n\r\n: (sercr)\t\\ base --\r\n\\ *G Transmit a CR\/LF pair on the given UART.\r\n $0D over (seremit) $0A swap (seremit)\r\n;\r\n\r\nCODE (sergetchar) \\ base -- c\r\n\\ *G Get a character from the port\r\n\tmov r0, tos\t\r\n\tsvc # SAPI_VEC_GETCHAR\r\n\tmov tos, r0\r\n\tnext,\r\nEND-CODE\r\n\r\nCODE (serkey?) \\ base -- t\/f\r\n\\ *G Return true if the given UART has a character avilable to read.\r\n\\ The call returns 0 or 1. If 1, subtract 2.\r\n\tmov r0, tos\r\n\tsvc # SAPI_VEC_CHARSAVAIL\t\t\r\n\tmov tos, r0\r\n\tnext,\t\r\nEND-CODE\r\n\r\n: (serkey)\t\\ base -- char\r\n\\ *G Wait for a character to come available on the given UART and\r\n\\ ** return the character.\r\n begin\r\n[ tasking? ] [if] pause [else] wfi [then] \r\n dup (serkey?)\r\n until\r\n (sergetchar) \r\n;\r\n\r\nexternal \r\n\r\n: seremit0\t\\ char --\r\n\\ *G Transmit a character on UART0.\r\n 0 (seremit) ;\r\n: sertype0\t\\ c-addr len --\r\n\\ *G Transmit a string on UART0.\r\n 0 (sertype) ;\r\n: sercr0\t\\ --\r\n\\ *G Issue a CR\/LF pair to UART0.\r\n 0 (sercr) ;\r\n: serkey?0\t\\ -- flag\r\n\\ *G Return true if UART0 has a character available.\r\n 0 (serkey?) ;\r\n: serkey0\t\\ -- char\r\n\\ *G Wait for a character on UART0.\r\n 0 (serkey) ;\r\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\r\n\\ *G Generic I\/O device for UART0.\r\n ' serkey0 ,\t\t\\ -- char ; receive char\r\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\r\n ' seremit0 ,\t\t\\ -- char ; display char\r\n ' sertype0 ,\t\t\\ caddr len -- ; display string\r\n ' sercr0 ,\t\t\\ -- ; display new line\r\n\r\n\\ UART1\r\n: seremit1 #1 (seremit) ;\r\n: sertype1\t#1 (sertype) ;\r\n: sercr1\t#1 (sercr) ;\r\n: serkey?1\t#1 (serkey?) ;\r\n: serkey1\t#1 (serkey) ;\r\ncreate Console1 ' serkey1 , ' serkey?1 , ' seremit1 , ' sertype1 , ' sercr1 ,\t\r\n\r\n\\ Versions for use with the TCP Port (10)\r\n: seremit10 #10 (seremit) ;\r\n: sertype10\t#10 (sertype) ;\r\n: sercr10\t#10 (sercr) ;\r\n: serkey?10\t#10 (serkey?) ;\r\n: serkey10\t#10 (serkey) ;\r\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\r\n\r\nconsole-port 0 = [if]\r\n console0 constant console\r\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\r\n\\ ** It may be changed by one of the phrases of the form:\r\n\\ *C dup opvec ! ipvec !\r\n\\ *C SetConsole\r\n[then]\r\n\r\nconsole-port #1 = [if]\r\n console1 constant console\r\n[then]\r\n\r\nconsole-port #10 = [if]\r\n console10 constant console\r\n[then]\r\n\r\n\\ ************************\r\n\\ *S System initialisation\r\n\\ ************************\r\n\r\n\\ This is a NOP in the SAPI environment\r\n: init-ser ;\t\\ --\r\n\\ *G Initialise all serial ports\r\n\r\n\r\n\\ ======\r\n\\ *> ###\r\n\\ ======\r\n\r\ndecimal\r\n","old_contents":"\\ serCM3_sapi_p.fth - SAPI polled RX, polled TX, serial communication drivers\r\n\\ Written to run against the SockPuppet API.\r\n\r\n((\r\n\r\nAdapted from: the LPC polled driver.\r\n\r\n))\r\n\r\nonly forth definitions\r\n\r\n\r\n\\ ==============\r\n\\ *! serCM3_sapi_p\r\n\\ *T SAPI polled serial driver\r\n\\ ==============\r\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\r\n\\ ** using the internal UARTs via the SAPI call layer.\r\n\r\n\r\n\\ ****************\r\n\\ *S Configuration\r\n\\ ****************\r\n\\ *P Configuration is managed by the SAPI\r\n\r\n\\ ********\r\n\\ *S Tools\r\n\\ ********\r\n\r\ntarget\r\n\r\n\\ ********************\r\n\\ *S Serial primitives\r\n\\ ********************\r\n\r\ninternal\r\n\r\n: +FaultConsole\t( -- ) ;\r\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\r\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\r\n\\ ** for more details.\r\n\r\ntarget\r\n\r\nCODE (seremitfc)\t\\ char base --\r\n\\ *G Service call for a single char - just fill in the registers\r\n\\ from the stack and make the call, and get back the flow control feedback\r\n\\ Put TOS into r0, pull r1 off the stack, and refresh the stack.\r\n\tmov r0, tos\r\n\tldr r1, [ psp ], # 4\t\r\n\tsvc # SAPI_VEC_PUTCHAR\t\r\n\tmov tos, r0\r\n next,\r\nEND-CODE\r\n\r\n: (seremit)\t\\ char base -- \r\n\\ *G Wrapped call that checks for throttling, and if so,\r\n\\ calls PAUSE to let another task run.\r\n\t(seremitfc)\r\n\t0<> IF PAUSE THEN\r\n\t;\r\n\r\n: (sertype)\t\\ caddr len base --\r\n\\ *G Transmit a string on the given UART.\r\n -rot bounds\r\n ?do i c@ over (seremit) loop\r\n drop\r\n;\r\n\r\n: (sercr)\t\\ base --\r\n\\ *G Transmit a CR\/LF pair on the given UART.\r\n $0D over (seremit) $0A swap (seremit)\r\n;\r\n\r\nCODE (sergetchar) \\ base -- c\r\n\\ *G Get a character from the port\r\n\tmov r0, tos\t\r\n\tsvc # SAPI_VEC_GETCHAR\r\n\tmov tos, r0\r\n\tnext,\r\nEND-CODE\r\n\r\nCODE (serkey?) \\ base -- t\/f\r\n\\ *G Return true if the given UART has a character avilable to read.\r\n\\ The call returns 0 or 1. If 1, subtract 2.\r\n\tmov r0, tos\r\n\tsvc # SAPI_VEC_CHARSAVAIL\t\t\r\n\tmov tos, r0\r\n\tnext,\t\r\nEND-CODE\r\n\r\n: (serkey)\t\\ base -- char\r\n\\ *G Wait for a character to come available on the given UART and\r\n\\ ** return the character.\r\n begin\r\n[ tasking? ] [if] pause [else] wfi [then] \r\n dup (serkey?)\r\n until\r\n (sergetchar) \r\n;\r\n\r\nexternal \r\n\r\n: seremit0\t\\ char --\r\n\\ *G Transmit a character on UART0.\r\n 0 (seremit) ;\r\n: sertype0\t\\ c-addr len --\r\n\\ *G Transmit a string on UART0.\r\n 0 (sertype) ;\r\n: sercr0\t\\ --\r\n\\ *G Issue a CR\/LF pair to UART0.\r\n 0 (sercr) ;\r\n: serkey?0\t\\ -- flag\r\n\\ *G Return true if UART0 has a character available.\r\n 0 (serkey?) ;\r\n: serkey0\t\\ -- char\r\n\\ *G Wait for a character on UART0.\r\n 0 (serkey) ;\r\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\r\n\\ *G Generic I\/O device for UART0.\r\n ' serkey0 ,\t\t\\ -- char ; receive char\r\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\r\n ' seremit0 ,\t\t\\ -- char ; display char\r\n ' sertype0 ,\t\t\\ caddr len -- ; display string\r\n ' sercr0 ,\t\t\\ -- ; display new line\r\n\r\n\\ UART1\r\n: seremit1 #1 (seremit) ;\r\n: sertype1\t#1 (sertype) ;\r\n: sercr1\t#1 (sercr) ;\r\n: serkey?1\t#1 (serkey?) ;\r\n: serkey1\t#1 (serkey) ;\r\ncreate Console1 ' serkey1 , ' serkey?1 , ' seremit1 , ' sertype1 , ' sercr1 ,\t\r\n\r\n\\ Versions for use with the TCP Port (10)\r\n: seremit10 #10 (seremit) ;\r\n: sertype10\t#10 (sertype) ;\r\n: sercr10\t#10 (sercr) ;\r\n: serkey?10\t#10 (serkey?) ;\r\n: serkey10\t#10 (serkey) ;\r\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\r\n\r\nconsole-port 0 = [if]\r\n console0 constant console\r\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\r\n\\ ** It may be changed by one of the phrases of the form:\r\n\\ *C dup opvec ! ipvec !\r\n\\ *C SetConsole\r\n[then]\r\n\r\nconsole-port #1 = [if]\r\n console1 constant console\r\n[then]\r\n\r\nconsole-port #10 = [if]\r\n console10 constant console\r\n[then]\r\n\r\n\\ ************************\r\n\\ *S System initialisation\r\n\\ ************************\r\n\r\n\\ This is a NOP in the SAPI environment\r\n: init-ser ;\t\\ --\r\n\\ *G Initialise all serial ports\r\n\r\n\r\n\\ ======\r\n\\ *> ###\r\n\\ ======\r\n\r\ndecimal\r\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"9f08b58c856da8896ab7fecc475a194fe3578793","subject":"Support the full version of TICKS.","message":"Support the full version of TICKS.","repos":"rbsexton\/gecko,rbsexton\/gecko,rbsexton\/gecko","old_file":"leopard\/usbforth\/SysCalls.fth","new_file":"leopard\/usbforth\/SysCalls.fth","new_contents":"\\ Wrappers for SAPI functions, ABI 4.0\n\n\\ Note that the system call number is embedded into the instruction,\n\\ so this is not so easily parameterized.\n\n#0 equ SAPI_VEC_VERSION\n#1 equ SAPI_VEC_01_GetRuntimeLinks\n#2 equ SAPI_VEC_02_PutChar\n#3 equ SAPI_VEC_03_GetChar\n#4 equ SAPI_VEC_04_GetCharAvail\n#5 equ SAPI_VEC_05_PutString\n#6 equ SAPI_VEC_06_EOL\n#14 equ SAPI_VEC_14_PetWatchdog\n#15 equ SAPI_VEC_15_GetTimeMS\n\nCODE SAPI-Version \\ -- n\n\\ *G Get the version of the binary ABI in use. \n\tsvc # SAPI_VEC_VERSION \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE GETRUNTIMELINKS \\ type -- n\n\\ *G Get the runtime linking information. Type 0 - A Dynamic linking \n\\ ** table with name, address pairs. Type 1 - A Zero-Terminated Jump table.\n\tmov r0, tos\n\tsvc # SAPI_VEC_01_GetRuntimeLinks \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE (seremitfc) \\ char base --\n\\ *G Service call for a single char - This one has a special name because\n\\ ** It'll be wrapped by something that can respond to the flow control \n\\ ** return code and PAUSE + Retry \n\tmov r0, tos\n\tldr r1, [ psp ], # 4\n\tmov r2, # 0 \\ Don't request a wake.\n\tsvc # SAPI_VEC_02_PutChar\t\n\tmov tos, r0\n next,\nEND-CODE\n\nCODE (serkeyfc) \\ base -- char \n\\ *G Get a character from the port, or -1 for fail\n\tmov r0, tos\t\n\tmov r1, # 0 \\ No blocking.\n\tsvc # SAPI_VEC_03_GetChar\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE (serkey?) \\ base -- t\/f\n\\ *G Return true if the given stream has a character avilable to read.\n\\ The call returns the number of chars available. \n\tmov r0, tos\n\tsvc # SAPI_VEC_04_GetCharAvail\n\tmov tos, r0\n\tnext,\nEND-CODE\n \n\\ These two can be created from simpler things, and are optional.\n\\ CODE (type) \n\\ END-CODE\n\n\\ CODE (cr) \n\\ END-CODE\n\nCODE PetWatchDog \\ n --\n\\ *G Refresh the watchdog. Pass in a platform-specific number\n\\ ** To specify a timerout (if supported), or zero for the default value. \n\tmov r0, tos\n\tldr r1, [ psp ], # 4\n\tsvc # SAPI_VEC_14_PetWatchdog\n\tldr tos, [ psp ], # 4\n\tnext,\nEND-CODE\n\nCODE TICKS \\ -- n \n\\ *G The current value of the millisecond ticker.\n mov r0, # 0 \\ We want the actual value.\n\tsvc # SAPI_VEC_15_GetTimeMS\n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\n\n\n","old_contents":"\\ Wrappers for SAPI functions, ABI 4.0\n\n\\ Note that the system call number is embedded into the instruction,\n\\ so this is not so easily parameterized.\n\n#0 equ SAPI_VEC_VERSION\n#1 equ SAPI_VEC_01_GetRuntimeLinks\n#2 equ SAPI_VEC_02_PutChar\n#3 equ SAPI_VEC_03_GetChar\n#4 equ SAPI_VEC_04_GetCharAvail\n#5 equ SAPI_VEC_05_PutString\n#6 equ SAPI_VEC_06_EOL\n#14 equ SAPI_VEC_14_PetWatchdog\n#15 equ SAPI_VEC_15_GetTimeMS\n\nCODE SAPI-Version \\ -- n\n\\ *G Get the version of the binary ABI in use. \n\tsvc # SAPI_VEC_VERSION \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE GETRUNTIMELINKS \\ type -- n\n\\ *G Get the runtime linking information. Type 0 - A Dynamic linking \n\\ ** table with name, address pairs. Type 1 - A Zero-Terminated Jump table.\n\tmov r0, tos\n\tsvc # SAPI_VEC_01_GetRuntimeLinks \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE (seremitfc) \\ char base --\n\\ *G Service call for a single char - This one has a special name because\n\\ ** It'll be wrapped by something that can respond to the flow control \n\\ ** return code and PAUSE + Retry \n\tmov r0, tos\n\tldr r1, [ psp ], # 4\n\tmov r2, # 0 \\ Don't request a wake.\n\tsvc # SAPI_VEC_02_PutChar\t\n\tmov tos, r0\n next,\nEND-CODE\n\nCODE (serkeyfc) \\ base -- char \n\\ *G Get a character from the port, or -1 for fail\n\tmov r0, tos\t\n\tmov r1, # 0 \\ No blocking.\n\tsvc # SAPI_VEC_03_GetChar\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE (serkey?) \\ base -- t\/f\n\\ *G Return true if the given stream has a character avilable to read.\n\\ The call returns the number of chars available. \n\tmov r0, tos\n\tsvc # SAPI_VEC_04_GetCharAvail\n\tmov tos, r0\n\tnext,\nEND-CODE\n \n\\ These two can be created from simpler things, and are optional.\n\\ CODE (type) \n\\ END-CODE\n\n\\ CODE (cr) \n\\ END-CODE\n\nCODE PetWatchDog \\ n --\n\\ *G Refresh the watchdog. Pass in a platform-specific number\n\\ ** To specify a timerout (if supported), or zero for the default value. \n\tmov r0, tos\n\tldr r1, [ psp ], # 4\n\tsvc # SAPI_VEC_14_PetWatchdog\n\tldr tos, [ psp ], # 4\n\tnext,\nEND-CODE\n\nCODE TICKS \\ -- n \n\\ *G The current value of the millisecond ticker.\n\tsvc # SAPI_VEC_15_GetTimeMS\n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\n\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"d490b4d53e52dc0c9da4f826b6ca77c3cf85cd0a","subject":"Setup the other UART.","message":"Setup the other UART.","repos":"rbsexton\/sockpuppet,rbsexton\/sockpuppet","old_file":"forth\/serCM3_sapi_p.fth","new_file":"forth\/serCM3_sapi_p.fth","new_contents":"\\ serCM3_sapi_p.fth - SAPI polled RX, polled TX, serial communication drivers\r\n\\ Written to run against the SockPuppet API.\r\n\r\n((\r\nAdapted from: the LPC polled driver.\r\n))\r\n\r\nonly forth definitions\r\nvariable cnt.pause \r\n\r\n\\ ==============\r\n\\ *! serCM3_sapi_p\r\n\\ *T SAPI polled serial driver\r\n\\ ==============\r\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\r\n\\ ** using the internal UARTs via the SAPI call layer.\r\n\r\n\r\n\\ ****************\r\n\\ *S Configuration\r\n\\ ****************\r\n\\ *P Configuration is managed by the SAPI\r\n\r\n\\ ********\r\n\\ *S Tools\r\n\\ ********\r\n\r\ntarget\r\n\r\n\\ ********************\r\n\\ *S Serial primitives\r\n\\ ********************\r\n\r\ninternal\r\n\r\n: +FaultConsole\t( -- ) ;\r\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\r\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\r\n\\ ** for more details.\r\n\r\ntarget\r\n\r\nCODE (seremitfc)\t\\ char base --\r\n\\ *G Service call for a single char - just fill in the registers\r\n\\ from the stack and make the call, and get back the flow control feedback\r\n\\ Put TOS into r0, pull r1 off the stack, and refresh the stack.\r\n\tmov r0, tos\r\n\tldr r1, [ psp ], # 4\t\r\n\tsvc # SAPI_VEC_PUTCHAR\t\r\n\tmov tos, r0\r\n next,\r\nEND-CODE\r\n\r\n: (seremit)\t\\ char base -- \r\n\\ *G Wrapped call that checks for throttling, and if so,\r\n\\ calls PAUSE to let another task run. Count these events for debugging purposes.\r\n\t(seremitfc)\r\n\t0<> IF 1 cnt.pause +! PAUSE THEN\r\n\t;\r\n\r\n: (sertype)\t\\ caddr len base --\r\n\\ *G Transmit a string on the given UART.\r\n -rot bounds\r\n ?do i c@ over (seremit) loop\r\n drop\r\n;\r\n\r\n: (sercr)\t\\ base --\r\n\\ *G Transmit a CR\/LF pair on the given UART.\r\n $0D over (seremit) $0A swap (seremit)\r\n;\r\n\r\nCODE (sergetchar) \\ base -- c\r\n\\ *G Get a character from the port\r\n\tmov r0, tos\t\r\n\tsvc # SAPI_VEC_GETCHAR\r\n\tmov tos, r0\r\n\tnext,\r\nEND-CODE\r\n\r\nCODE (serkey?) \\ base -- t\/f\r\n\\ *G Return true if the given UART has a character avilable to read.\r\n\\ The call returns 0 or 1. \r\n\tmov r0, tos\r\n\tsvc # SAPI_VEC_CHARSAVAIL\t\t\r\n\tmov tos, r0\r\n\tnext,\t\r\nEND-CODE\r\n\r\n: (serkey)\t\\ base -- char\r\n\\ *G Wait for a character to come available on the given UART and\r\n\\ ** return the character.\r\n begin\r\n[ tasking? ] [if] pause [then] \r\n dup (serkey?)\r\n until\r\n (sergetchar) \r\n;\r\n\r\nexternal \r\n\r\n: seremit0\t\\ char --\r\n\\ *G Transmit a character on UART0.\r\n 0 (seremit) ;\r\n: sertype0\t\\ c-addr len --\r\n\\ *G Transmit a string on UART0.\r\n 0 (sertype) ;\r\n: sercr0\t\\ --\r\n\\ *G Issue a CR\/LF pair to UART0.\r\n 0 (sercr) ;\r\n: serkey?0\t\\ -- flag\r\n\\ *G Return true if UART0 has a character available.\r\n 0 (serkey?) ;\r\n: serkey0\t\\ -- char\r\n\\ *G Wait for a character on UART0.\r\n 0 (serkey) ;\r\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\r\n\\ *G Generic I\/O device for UART0.\r\n ' serkey0 ,\t\t\\ -- char ; receive char\r\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\r\n ' seremit0 ,\t\t\\ -- char ; display char\r\n ' sertype0 ,\t\t\\ caddr len -- ; display string\r\n ' sercr0 ,\t\t\\ -- ; display new line\r\n\r\n\\ UART2\r\n: seremit2 #2 (seremit) ;\r\n: sertype2\t#2 (sertype) ;\r\n: sercr2\t#2 (sercr) ;\r\n: serkey?2\t#2 (serkey?) ;\r\n: serkey2\t#2 (serkey) ;\r\ncreate Console2 ' serkey2 , ' serkey?2 , ' seremit2 , ' sertype2 , ' sercr2 ,\t\r\n\r\n\\ Versions for use with the TCP Port (10)\r\n: seremit10 #10 (seremit) ;\r\n: sertype10\t#10 (sertype) ;\r\n: sercr10\t#10 (sercr) ;\r\n: serkey?10\t#10 (serkey?) ;\r\n: serkey10\t#10 (serkey) ;\r\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\r\n\r\nconsole-port 0 = [if]\r\n console0 constant console\r\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\r\n\\ ** It may be changed by one of the phrases of the form:\r\n\\ *C dup opvec ! ipvec !\r\n\\ *C SetConsole\r\n[then]\r\n\r\nconsole-port #1 = [if]\r\n console1 constant console\r\n[then]\r\n\r\nconsole-port #10 = [if]\r\n console10 constant console\r\n[then]\r\n\r\n\\ ************************\r\n\\ *S System initialisation\r\n\\ ************************\r\n\r\n\\ This is a NOP in the SAPI environment\r\n: init-ser ;\t\\ --\r\n\\ *G Initialise all serial ports\r\n\r\n\r\n\\ ======\r\n\\ *> ###\r\n\\ ======\r\n\r\ndecimal\r\n","old_contents":"\\ serCM3_sapi_p.fth - SAPI polled RX, polled TX, serial communication drivers\r\n\\ Written to run against the SockPuppet API.\r\n\r\n((\r\nAdapted from: the LPC polled driver.\r\n))\r\n\r\nonly forth definitions\r\nvariable cnt.pause \r\n\r\n\\ ==============\r\n\\ *! serCM3_sapi_p\r\n\\ *T SAPI polled serial driver\r\n\\ ==============\r\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\r\n\\ ** using the internal UARTs via the SAPI call layer.\r\n\r\n\r\n\\ ****************\r\n\\ *S Configuration\r\n\\ ****************\r\n\\ *P Configuration is managed by the SAPI\r\n\r\n\\ ********\r\n\\ *S Tools\r\n\\ ********\r\n\r\ntarget\r\n\r\n\\ ********************\r\n\\ *S Serial primitives\r\n\\ ********************\r\n\r\ninternal\r\n\r\n: +FaultConsole\t( -- ) ;\r\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\r\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\r\n\\ ** for more details.\r\n\r\ntarget\r\n\r\nCODE (seremitfc)\t\\ char base --\r\n\\ *G Service call for a single char - just fill in the registers\r\n\\ from the stack and make the call, and get back the flow control feedback\r\n\\ Put TOS into r0, pull r1 off the stack, and refresh the stack.\r\n\tmov r0, tos\r\n\tldr r1, [ psp ], # 4\t\r\n\tsvc # SAPI_VEC_PUTCHAR\t\r\n\tmov tos, r0\r\n next,\r\nEND-CODE\r\n\r\n: (seremit)\t\\ char base -- \r\n\\ *G Wrapped call that checks for throttling, and if so,\r\n\\ calls PAUSE to let another task run. Count these events for debugging purposes.\r\n\t(seremitfc)\r\n\t0<> IF 1 cnt.pause +! PAUSE THEN\r\n\t;\r\n\r\n: (sertype)\t\\ caddr len base --\r\n\\ *G Transmit a string on the given UART.\r\n -rot bounds\r\n ?do i c@ over (seremit) loop\r\n drop\r\n;\r\n\r\n: (sercr)\t\\ base --\r\n\\ *G Transmit a CR\/LF pair on the given UART.\r\n $0D over (seremit) $0A swap (seremit)\r\n;\r\n\r\nCODE (sergetchar) \\ base -- c\r\n\\ *G Get a character from the port\r\n\tmov r0, tos\t\r\n\tsvc # SAPI_VEC_GETCHAR\r\n\tmov tos, r0\r\n\tnext,\r\nEND-CODE\r\n\r\nCODE (serkey?) \\ base -- t\/f\r\n\\ *G Return true if the given UART has a character avilable to read.\r\n\\ The call returns 0 or 1. If 1, subtract 2.\r\n\tmov r0, tos\r\n\tsvc # SAPI_VEC_CHARSAVAIL\t\t\r\n\tmov tos, r0\r\n\tnext,\t\r\nEND-CODE\r\n\r\n: (serkey)\t\\ base -- char\r\n\\ *G Wait for a character to come available on the given UART and\r\n\\ ** return the character.\r\n begin\r\n[ tasking? ] [if] pause [else] wfi [then] \r\n dup (serkey?)\r\n until\r\n (sergetchar) \r\n;\r\n\r\nexternal \r\n\r\n: seremit0\t\\ char --\r\n\\ *G Transmit a character on UART0.\r\n 0 (seremit) ;\r\n: sertype0\t\\ c-addr len --\r\n\\ *G Transmit a string on UART0.\r\n 0 (sertype) ;\r\n: sercr0\t\\ --\r\n\\ *G Issue a CR\/LF pair to UART0.\r\n 0 (sercr) ;\r\n: serkey?0\t\\ -- flag\r\n\\ *G Return true if UART0 has a character available.\r\n 0 (serkey?) ;\r\n: serkey0\t\\ -- char\r\n\\ *G Wait for a character on UART0.\r\n 0 (serkey) ;\r\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\r\n\\ *G Generic I\/O device for UART0.\r\n ' serkey0 ,\t\t\\ -- char ; receive char\r\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\r\n ' seremit0 ,\t\t\\ -- char ; display char\r\n ' sertype0 ,\t\t\\ caddr len -- ; display string\r\n ' sercr0 ,\t\t\\ -- ; display new line\r\n\r\n\\ UART1\r\n: seremit1 #1 (seremit) ;\r\n: sertype1\t#1 (sertype) ;\r\n: sercr1\t#1 (sercr) ;\r\n: serkey?1\t#1 (serkey?) ;\r\n: serkey1\t#1 (serkey) ;\r\ncreate Console1 ' serkey1 , ' serkey?1 , ' seremit1 , ' sertype1 , ' sercr1 ,\t\r\n\r\n\\ Versions for use with the TCP Port (10)\r\n: seremit10 #10 (seremit) ;\r\n: sertype10\t#10 (sertype) ;\r\n: sercr10\t#10 (sercr) ;\r\n: serkey?10\t#10 (serkey?) ;\r\n: serkey10\t#10 (serkey) ;\r\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\r\n\r\nconsole-port 0 = [if]\r\n console0 constant console\r\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\r\n\\ ** It may be changed by one of the phrases of the form:\r\n\\ *C dup opvec ! ipvec !\r\n\\ *C SetConsole\r\n[then]\r\n\r\nconsole-port #1 = [if]\r\n console1 constant console\r\n[then]\r\n\r\nconsole-port #10 = [if]\r\n console10 constant console\r\n[then]\r\n\r\n\\ ************************\r\n\\ *S System initialisation\r\n\\ ************************\r\n\r\n\\ This is a NOP in the SAPI environment\r\n: init-ser ;\t\\ --\r\n\\ *G Initialise all serial ports\r\n\r\n\r\n\\ ======\r\n\\ *> ###\r\n\\ ======\r\n\r\ndecimal\r\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"ec6c8b8ac52a32afd1c8b291cc9fac0c3e80522c","subject":"Nearly working, all tests pass, for compiling-bit feature.","message":"Nearly working, all tests pass, for compiling-bit feature.\n\nNeed to sort out what 'cfa' should do, and whether or not it should be\nremoved. There are still words that need correcting, like 'see', and\na few others.\n","repos":"howerj\/libforth","old_file":"forth.fth","new_file":"forth.fth","new_contents":"#!.\/forth \n( ==================================================================== )\n( ==================================================================== )\n( ==================================================================== )\n( \n\tTHIS CODE IS CURRENTLY NON FUNCTIONAL\n\tTHIS CODE IS CURRENTLY NON FUNCTIONAL\n\tTHIS CODE IS CURRENTLY NON FUNCTIONAL\n\tTHIS CODE IS CURRENTLY NON FUNCTIONAL\n\tTHIS CODE IS CURRENTLY NON FUNCTIONAL\n\n\tThis is due to a large change in the interpreter, it will\n\ttake time to fix this, however it will be an improvement.\n)\n( ==================================================================== )\n( ==================================================================== )\n( ==================================================================== )\n( ==================================================================== )\n( \nWelcome to libforth, A dialect of Forth. Like all versions of Forth this\nversion is a little idiosyncratic, but how the interpreter works is\ndocumented here and in various other files.\n\nThis file contains most of the start up code, some basic start up code\nis executed in the C file as well which makes programming at least bearable.\nMost of Forth is programmed in itself, which may seem odd if your back\nground in programming comes from more traditional language [such as C],\nalthough less so if you know already know lisp.\n\nFor more information about this interpreter and Forth see:\n\thttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\treadme.md : for a manual for this interpreter\n\tlibforth.h : for information about the C API\n\tlibforth.c : for the interpreter itself\n\tunit.c : a series of unit tests against libforth.c\n\tunit.fth : a series of unit tests against this file\n\nThe interpreter and this code originally descend from a Forth interpreter\nwritten in 1992 for the International obfuscated C Coding Competition\n\nSee:\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\nThe manual for the interpreter should be read first before looking into this\ncode. It is important to understand the execution model of Forth, especially\nthe differences between command and compile mode, and how immediate and compiling\nwords work.\n\nThe structure of this file is as follows:\n\n * Basic Word Set\n * Extended Word Set\n * CREATE DOES>\n * DO...LOOP\n * CASE statements\n * Conditional Compilation\n * Endian Words\n * Misc words\n * Random Numbers\n * ANSI Escape Codes\n * Prime Numbers\n * Debugging info\n * Files\n * Blocks\n * Matcher\n * Cons Cells\n * Miscellaneous\n * Core utilities\n\nEach of these sections is clearly labeled and they are generally in dependency order.\n\nUnfortunately the code in this file is not as portable as it could be, it makes\nassumptions about the size of cells provided by the virtual machine, which will\ntake time to rectify. Some of the constructs are subtly different from the\nDPANs Forth specification, which is usually noted. Eventually this should\nalso be fixed.)\n\n( ========================== Basic Word Set ================================== )\n\n( \nWe'll begin by defining very simple words we can use later, these a very\nbasic words, that perform simple tasks, they will not require much explanation.\n\nEven though the words are simple, their stack comment and a description for\nthem will still be included so external tools can process and automatically\nextract the document string for a given work.\n)\n\n: 1+ ( x -- x : increment a number ) \n\t1 + ;\n\n: 1- ( x -- x : decrement a number ) \n\t1 - ;\n\n: chars ( c-addr -- addr : convert a character address to an address )\n\tsize \/ ; \n\n: chars> ( addr -- c-addr: convert an address to a character address )\n\tsize * ; \n\n: tab ( -- : print a tab character to current output device )\n\t9 emit ;\n\n: 0= ( x -- bool : is 'x' equal to zero? )\n\t0 = ;\n\n: not ( x -- bool : is 'x' true? )\n\t0= ;\n\n: <> ( x x -- bool : not equal )\n\t= 0= ;\n\n: logical ( x -- bool : turn a value into a boolean ) \n\tnot not ;\n\n: :: ( -- : compiling version of ':' )\n\t[ find : , ] ;\n\n: '\\n' ( -- n : push the newline character )\n\t10 ;\n\n: cr ( -- : emit a newline character )\n\t'\\n' emit ;\n\n: hidden-mask ( -- x : pushes mask for the hide bit in a words MISC field )\n\t0x80 ;\n\n: instruction-mask ( -- x : pushes mask for the first code word in a words MISC field )\n\t0x1f ;\n\n: hidden? ( PWD -- PWD bool : is a word hidden, given the words PWD field ) \n\tdup 1+ @ hidden-mask and logical ;\n\n: compile-instruction ( -- instruction : compile code word, threaded code interpreter instruction )\n\t1 ; \n\n: dolist ( -- x : run code word, threaded code interpreter instruction )\n\t2 ; \n\n: dolit ( -- x : location of special \"push\" word )\n\t2 ;\n\n: 2, ( x x -- : write two values into the dictionary )\n\t, , ;\n\n: [literal] ( x -- : write a literal into the dictionary )\n\tdolit 2, ; \n\n: literal ( x -- : immediately write a literal into the dictionary )\n\timmediate [literal] ;\n\n: sliteral immediate ( I: c-addr u --, Run: -- c-addr u )\n\tswap [literal] [literal] ;\n\n( space saving measure )\n-1 : -1 literal ;\n 0 : 0 literal ;\n 1 : 1 literal ;\n 2 : 2 literal ;\n 3 : 3 literal ;\n\n: min-signed-integer ( -- x : push the minimum signed integer value )\n\t[ -1 -1 1 rshift invert and ] literal ;\n\n: max-signed-integer ( -- x : push the maximum signed integer value )\n\t[ min-signed-integer invert ] literal ;\n\n: < ( x1 x2 -- bool : signed less than comparison )\n\t- dup if max-signed-integer u> else logical then ;\n\n: > ( x1 x2 -- bool : signed greater than comparison )\n\t- dup if max-signed-integer u< else logical then ;\n\n: 2literal immediate ( x x -- : immediate write two literals into the dictionary )\n\tswap [literal] [literal] ;\n\n: latest ( get latest defined word )\n\tpwd @ ; \n\n: stdin ( -- fileid : push the fileid for the standard input channel ) \n\t`stdin @ ;\n\n: stdout ( -- fileid : push the fileid for the standard output channel ) \n\t`stdout @ ;\n\n: stderr ( -- fileid : push the fileid for the standard error channel ) \n\t`stderr @ ;\n\n: stdin? ( -- bool : are we reading from standard input )\n\t`fin @ stdin = ;\n\n: false ( -- x : push the value representing false )\n\t0 ;\n\n: true ( -- x : push the value representing true )\n\t-1 ;\n\n: *+ ( x1 x2 x3 -- x ) \n\t* + ;\n\t\n: 2- ( x -- x : decrement by two )\n\t2 - ( x -- x ) ;\n\n: 2+ ( x -- x : increment by two )\n\t2 + ( x -- x ) ;\n\n: 3+ ( x -- x : increment by three )\n\t3 + ( x -- x ) ;\n\n: 2* ( x -- x : multiply by two )\n\t1 lshift ( x -- x ) ;\n\n: 2\/ ( x -- x : divide by two )\n\t1 rshift ( x -- x ) ;\n\n: 4* ( x -- x : multiply by four )\n\t2 lshift ( x -- x ) ;\n\n: 4\/ ( x -- x : divide by four )\n\t2 rshift ( x -- x ) ;\n\n: 8* ( x -- x : multiply by eight )\n\t3 lshift ( x -- x ) ;\n\n: 8\/ ( x -- x : divide by eight )\n\t3 rshift ( x -- x ) ;\n\n: 256* ( x -- x : multiply by 256 )\n\t8 lshift ( x -- x ) ;\n\n: 256\/ ( x -- x : divide by 256 )\n\t8 rshift ( x -- x ) ;\n\n: 2dup ( x1 x2 -- x1 x2 x1 x2 : duplicate two values )\n\tover over ;\n\n: mod ( x u -- x : calculate the remainder of x divided by u ) \n\t2dup \/ * - ;\n\n( @todo implement um\/mod in the VM, then use this to implement \/ and mod )\n: um\/mod ( x1 x2 -- rem quot : calculate the remainder and quotient of x1 divided by x2 ) \n\t2dup \/ >r mod r> ;\n\n: *\/ ( x1 x2 x3 -- x4 : multiply then divide, @warning this does not use a double cell for the multiply )\n\t * \/ ; \n\n: char ( -- x : read in a character from the input steam )\n\tkey drop key ;\n\n: [char] ( -- x : immediately read in a character from the input stream )\n\timmediate char [literal] ;\n\n: postpone ( -- : postpone execution of the following immediate word )\n\timmediate find , ;\n\n: compose ( xt1 xt2 -- xt3 : create a new function from two xt-tokens )\n\t>r >r ( save execution tokens )\n\tpostpone :noname ( )\n\tr> , ( write first token )\n\tr> , ( write second token )\n\tpostpone ; ; ( terminate new :noname )\n\n: unless ( bool -- : like 'if' but execute clause if false )\n\timmediate ' 0= , postpone if ;\n\n: endif ( synonym for 'then' ) \n\timmediate postpone then ;\n\n: cell+ ( a-addr1 -- a-addr2 ) \n\t1+ ;\n\n: cells ( n1 -- n2 ) \n\timmediate ;\n\n: cell ( -- u : defined as 1 cells )\n\t1 cells ;\n\n: address-unit-bits ( -- x : push the number of bits in an address )\n\t[ cell size 8* * ] literal ;\n\n: negative? ( x -- bool : is a number negative? )\n\t[ 1 address-unit-bits 1- lshift ] literal and logical ;\n\n: mask-byte ( x -- x : generate mask byte ) \n\t8* 255 swap lshift ;\n\n: select-byte ( u i -- c ) \n\t8* rshift 0xff and ;\n\n: char+ ( c-addr -- c-addr : increment a character address by the size of one character ) \n\t1+ ;\n\n: 2chars ( c-addr1 c-addr2 -- addr addr : convert two character addresses to two cell addresses ) \n\tchars swap chars swap ;\n\n: 2chars> ( addr addr -- c-addr c-addr: convert two cell addresses to two character addresses )\n\tchars> swap chars> swap ;\n\n: hex ( -- : print out hex ) \n\t16 base ! ;\n\n: octal ( -- : print out octal ) \n\t8 base ! ;\n\n: binary ( -- : print out binary ) \n\t2 base ! ;\n\n: decimal ( -- : print out decimal ) \n\t0 base ! ;\n\n: negate ( x -- x ) \n\t-1 * ;\n\n: abs ( x -- u : return the absolute value of a number )\n\tdup negative? if negate then ;\n\n: square ( x -- x ) \n\tdup * ;\n\n: sum-of-squares ( a b -- c : compute a^2 + b^2 to get c )\n\tsquare swap square + ;\n\n: drup ( x y -- x x ) \n\tdrop dup ;\n\n: +! ( x addr -- : add x to a value stored at addr ) \n\ttuck @ + swap ! ;\n\n: 1+! ( addr -- : increment a value at an address ) \n\t1 swap +! ;\n\n: 1-! ( addr -- : decrement a value at an address ) \n\t-1 swap +! ;\n\n: toggle ( addr u -- : complement the value at address with the bit pattern u ) \n\tover @ xor swap ! ;\n\n: lsb ( x -- x : mask off the least significant byte of a cell ) \n\t255 and ;\n\n: \\ ( -- : immediate word, used for single line comments )\n\timmediate begin key '\\n' = until ;\n\n: ?dup ( x -- ? ) \n\tdup if dup then ;\n\n: min ( x y -- min : return the minimum of two integers ) \n\t2dup < if drop else swap drop then ;\n\n: max ( x y -- max : return the maximum of two integers ) \n\t2dup > if drop else swap drop then ;\n\n: limit ( x min max -- x : limit x with a minimum and maximum )\n\trot min max ;\n\n: >= ( x y -- bool ) \n\t< not ;\n\n: <= ( x y -- bool ) \n\t> not ;\n\n: 2@ ( a-addr -- x1 x2 : load two consecutive memory cells )\n\tdup 1+ @ swap @ ;\n\n: 2! ( x1 x2 a-addr -- : store two values as two consecutive memory cells )\n\t2dup ! nip 1+ ! ;\n\n: r@ ( -- x, R: x -- )\n\tr> r @ swap >r ;\n\n: rp@ ( -- x, R: x -- )\n\tr> r @ swap >r ;\n\n( @todo r!, rp! )\n\n: 0> ( x -- bool )\n\t0 > ;\n\n: 0< ( x -- bool )\n\t0 < ;\n\n: 0<> ( x -- bool )\n\t0 <> ;\n\n: signum ( x -- -1 | 0 | 1 : )\n\tdup 0< if drop -1 exit then\n\t 0> if 1 exit then\n\t0 ;\n\n: nand ( x x -- x : bitwise NAND ) \n\tand invert ;\n\n: odd ( x -- bool : is 'x' odd? )\n\t1 and ;\n\n: even ( x -- bool : is 'x' even? )\n\todd not ;\n\n: nor ( x x -- x : bitwise NOR ) \n\tor invert ;\n\n: ms ( u -- : wait at least 'u' milliseconds ) \n\tclock + begin dup clock u< until drop ;\n\n: sleep ( u -- : sleep for 'u' seconds )\n\t1000 * ms ;\n\n: align ( addr -- addr : align an address, nop in this implemented )\n\timmediate ; \n\n: ) ( -- : do nothing, this allows easy commenting out of code )\n\timmediate ;\n\n: bell ( -- : emit an ASCII BEL character ) \n\t7 emit ;\n\n: b\/buf ( -- u : bytes per buffer ) \n\t1024 ;\n\n: .d ( x -- x : debug print ) \n\tdup . ;\n\n: compile, ( x -- : )\n\t, ;\n\n: >mark ( -- : write a hole into the dictionary and push a pointer to it ) \n\there 0 , ;\n\n: r - r> u< ;\n\n: invalidate ( -- : invalidate this Forth core )\n\t1 `invalid ! ;\n\n: signed ( x -- bool : return true if sign bit set ) \n\t[ 1 size 8 * 1- lshift ] literal and logical ;\n\n: u>= ( x y -- bool : unsigned greater than or equal to )\n\t2dup u> >r = r> or ;\n\n: u<= ( x y -- bool : unsigned less than or equal to )\n\tu>= not ;\n: rdrop ( R: x -- : drop a value from the return stack )\n\tr> ( get caller's return address )\n\tr> ( get value to drop )\n\tdrop ( drop it like it's hot )\n\t>r ; ( return return address )\n\n: rdup\n\tr> ( get caller's return address )\n\tr> ( get value to duplicate )\n\tdup ( ... )\n\t>r >r >r ; ( make it all work )\n\n: again immediate\n\t( loop unconditionally in a begin-loop:\n\t\tbegin ... again )\n\t' branch , ;\n\n: source ( -- c-addr u )\n\t#tib ( size of input buffer, in characters )\n\ttib ; ( start of input buffer, in characters )\n\n: stdin?\n\t`fin @ `stdin @ = ;\n\n: source-id ( -- 0 | -1 | file-id )\n\t( \t\n\tValue Input Source\n\t-1 String\n\t0 Reading from user input \/ standard in\n\tfile-id )\n\t`source-id @ \n\t0= if\n\t\tstdin? if 0 else `fin @ then\n\telse\n\t\t-1\n\tthen ;\n\n: under ( x1 x2 -- x1 x1 x2 )\n\t>r dup r> ;\n\n: 2nip ( n1 n2 n3 n4 -- n3 n4 ) \n\t>r >r 2drop r> r> ;\n\n: 2over ( n1 n2 n3 n4 \u2013 n1 n2 n3 n4 n1 n2 )\n\t>r >r 2dup r> swap >r swap r> r> -rot ;\n\n: 2swap ( n1 n2 n3 n4 \u2013 n3 n4 n1 n2 )\n\t>r -rot r> -rot ;\n\n: 2tuck ( n1 n2 n3 n4 \u2013 n3 n4 n1 n2 n3 n4 )\n\t2swap 2over ;\n\n: nos1+ ( x1 x2 -- x1+1 x2 : increment the next variable on that stack )\n\tswap 1+ swap ;\n\n: ?dup-if immediate ( x -- x | - : ?dup and if rolled into one! )\n\t' ?dup , postpone if ;\n\n: ?if ( -- : non destructive if ) \n\timmediate ' dup , postpone if ;\n\n: hide ( token -- hide-token : this hides a word from being found by the interpreter )\n\t?dup-if\n\t\tdup @ hidden-mask or swap tuck ! exit\n\tthen 0 ;\n\n: hider ( WORD -- : hide with drop ) \n\tfind dup if hide then drop ;\n\n: reveal ( hide-token -- : reveal a hidden word ) \n\tdup @ hidden-mask invert and swap ! ;\n\n: original-exit \n\t[ find exit ] literal ;\n\n: exit\n\t( this will define a second version of exit, ';' will\n\tuse the original version, whilst everything else will\n\tuse this version, allowing us to distinguish between\n\tthe end of a word definition and an early exit by other\n\tmeans in \"see\" )\n\t[ find exit hide ] rdrop exit [ reveal ] ;\n\n: ?exit ( x -- : exit current definition if not zero ) \n\tif rdrop exit then ;\n\n: number? ( c -- f : is character a number? )\n\t[char] 0 [ char 9 1+ ] literal within ;\n\n: lowercase? ( c -- f : is character lower case? )\n\t[char] a [ char z 1+ ] literal within ;\n\n: uppercase? ( C -- f : is character upper case? )\n\t[char] A [ char Z 1+ ] literal within ;\n\n: alpha? ( C -- f : is character part of the alphabet? )\n\tdup lowercase? swap uppercase? or ;\n\n: alphanumeric? ( C -- f : is character alphabetic or a number ? )\n\tdup alpha? swap number? or ;\n\n: printable? ( c -- bool : is printable, excluding new lines and tables )\n\t32 127 within ;\n\n: >upper ( c -- C : convert char to uppercase iff lower case )\n\tdup lowercase? if bl xor then ;\n\n: >lower ( C -- c : convert char to lowercase iff upper case )\n\tdup uppercase? if bl xor then ;\n\n: <=> ( x y -- z : spaceship operator! )\n\t2dup\n\t> if 2drop -1 exit then\n\t< ;\n\n: start-address ( -- c-addr : push the start address )\n\t`start-address @ ;\n\n: >real-address ( c-addr -- c-addr : convert an interpreter address to a real address )\n\tstart-address - ;\n\n: real-address> ( c-addr -- c-addr : convert a real address to an interpreter address )\n\tstart-address + ;\n\n: peek ( c-addr -- char : peek at real memory )\n\t>real-address c@ ;\n\n: poke ( char c-addr -- : poke a real memory address )\n\t>real-address c! ;\n\n: die! ( x -- : controls actions when encountering certain errors )\n\t`error-handler ! ;\n\n: start! ( cfa -- : set the word to execute at startup )\n\t`instruction ! ;\t\n\n: warm ( -- : restart the interpreter, warm restart )\n\t1 restart ;\n\n: trip ( x -- x x x : triplicate a number ) \n\tdup dup ;\n\n: roll ( xu xu-1 ... x0 u -- xu-1 ... x0 xu : move u+1 items on the top of the stack by u )\n\tdup 0 >\n\tif\n\t\tswap >r 1- roll r> swap\n\telse\n\t\tdrop\n\tthen ;\n\n: 2rot ( n1 n2 n3 n4 n5 n6 \u2013 n3 n4 n5 n6 n1 n2 )\n\t5 roll 5 roll ;\n\n: s>d ( x -- d : convert a signed value to a double width cell )\n\t( @note the if...else...then is only necessary as this Forths\n\tbooleans are 0 and 1, not 0 and -1 as it usually is )\n\tdup 0< if -1 else 0 then ;\n\n: trace ( level -- : set tracing level )\n\t`debug ! ;\n\n: verbose ( -- : get the log level )\n\t`debug @ ;\n\n: #pad ( -- u : offset into pad area )\n\t64 ;\n\n: pad\n\t( the pad is used for temporary storage, and moves\n\talong with dictionary pointer, always in front of it )\n\there #pad + ;\n\n: count ( c-addr1 -- c-addr2 u : get a string whose first char is its length )\n\tdup c@ nos1+ ;\n\n: bounds ( x y -- y+x x : make an upper and lower bound )\n\tover + swap ;\n\n: aligned ( unaligned -- aligned : align a pointer )\n\t[ size 1- ] literal + \n\t[ size 1- ] literal invert and ;\n\n\n( ================================== DUMP ================================== )\n: newline ( x -- x+1 : print a new line every fourth value )\n\tdup 3 and 0= if cr then 1+ ;\n\n: address ( num count -- count : print current address we are dumping every fourth value )\n\tdup >r\n\t1- 3 and 0= if . [char] : emit space else drop then\n\tr> ;\n\n: dump ( start count -- : print the contents of a section of memory )\n\tbase @ >r ( save current base )\n\thex ( switch to hex mode )\n\t1 >r ( save counter on return stack )\n\tover + swap ( calculate limits: start start+count )\n\tbegin \n\t\t2dup u> ( stop if gone past limits )\n\twhile \n\t\tdup r> address >r\n\t\tdup @ . 1+ \n\t\tr> newline >r\n\trepeat \n\tr> drop\n\tr> base !\n\t2drop ;\n\nhider newline\nhider address \n( ================================== DUMP ================================== )\n\n: cfa immediate ( find-address -- cfa )\n\t( Given the address of the PWD field of a word this\n\tfunction will return an execution token for the word )\n\t( @todo if < dictionary start PWD is invalid )\n\t ;\n\n: >body ( xt -- a-addr : a-addr is data field of a CREATEd word )\n\tcfa 5 + ;\n\n( @todo non-compliant, fix )\n: ['] immediate find cfa [literal] ;\n\n: execute ( xt -- : given an execution token, execute the word )\n\t( create a word that pushes the address of a hole to write to\n\ta literal takes up two words, '!' takes up one, that's right,\n\tsome self modifying code! )\n\t\\ 1- ( execution token expects pointer to PWD field, it does not\n\t\\ \tcare about that field however, and increments past it )\n\tcfa\n\t[ here 3+ literal ] ( calculate place to write to )\n\t! ( write an execution token to a hole )\n\t[ 0 , ] ; ( this is the hole we write )\n\n( See: http:\/\/lars.nocrew.org\/dpans\/dpans9.htm\n Code Reserved for\n ---- ------------\n -1 ABORT\n -2 ABORT\"\n -3 stack overflow\n -4 stack underflow\n -5 return stack overflow\n -6 return stack underflow\n -7 do-loops nested too deeply during execution\n -8 dictionary overflow\n -9 invalid memory address\n -10 division by zero\n -11 result out of range\n -12 argument type mismatch\n -13 undefined word\n -14 interpreting a compile-only word\n -15 invalid FORGET\n -16 attempt to use zero-length string as a name\n -17 pictured numeric output string overflow\n -18 parsed string overflow\n -19 definition name too long\n -20 write to a read-only location\n -21 unsupported operation [e.g., AT-XY on a\n too-dumb terminal]\n -22 control structure mismatch\n -23 address alignment exception\n -24 invalid numeric argument\n -25 return stack imbalance\n -26 loop parameters unavailable\n -27 invalid recursion\n -28 user interrupt\n -29 compiler nesting\n -30 obsolescent feature\n -31 >BODY used on non-CREATEd definition\n -32 invalid name argument [e.g., TO xxx]\n -33 block read exception\n -34 block write exception\n -35 invalid block number\n -36 invalid file position\n -37 file I\/O exception\n -38 non-existent file\n -39 unexpected end of file\n -40 invalid BASE for floating point conversion\n -41 loss of precision\n -42 floating-point divide by zero\n -43 floating-point result out of range\n -44 floating-point stack overflow\n -45 floating-point stack underflow\n -46 floating-point invalid argument\n -47 compilation word list deleted\n -48 invalid POSTPONE\n -49 search-order overflow\n -50 search-order underflow\n -51 compilation word list changed\n -52 control-flow stack overflow\n -53 exception stack overflow\n -54 floating-point underflow\n -55 floating-point unidentified fault\n -56 QUIT\n -57 exception in sending or receiving a character\n -58 [IF], [ELSE], or [THEN] exception )\n\n( @todo integrate catch\/throw into the interpreter as primitives )\n: catch ( xt -- exception# | 0 : return addr on stack )\n\tsp@ >r ( xt : save data stack pointer )\n\t`handler @ >r ( xt : and previous handler )\n\tr@ `handler ! ( xt : set current handler )\n\texecute ( execute returns if no throw )\n\tr> `handler ! ( restore previous handler )\n\tr> drop ( discard saved stack ptr )\n\t0 ; ( 0 : normal completion )\n\n( @todo use this everywhere )\n: throw ( ??? exception# -- ??? exception# )\n\t?dup-if ( exc# \\ 0 throw is no-op )\n\t\t`handler @ r ! ( exc# : restore prev return stack )\n\t\tr> `handler ! ( exc# : restore prev handler )\n\t\tr> swap >r ( saved-sp : exc# on return stack )\n\t\tsp! drop r> ( exc# : restore stack )\n\t\t( return to the caller of catch because return )\n\t\t( stack is restored to the state that existed )\n\t\t( when catch began execution )\n\tthen ; \n\n( @bug replacing \"drop drop\" with \"2drop\" causes a stack underflow in\n\"T{\" on a 32-bit platform, \"2drop\" can be used, but only if 3drop is defined\nafter \"interpret\" - something is ever so subtly going wrong. The code fails\nin \"T{\" when \"evaluate\" is called - which does lots of magic in the virtual\nmachine. This is the kind of bug that is difficult to find and reproduce, I\nhave not given up on it yet, however I am going to apply the \"fix\" for now,\nwhich is to change the definitions of 3drop to \"drop drop drop\"... for future\nreference the bug is present in git commit ccd802f9b6151da4c213465a72dacb1f7c22b0ac )\n\n: 3drop ( x1 x2 x3 -- )\n\tdrop drop drop ;\n\n: interpret \n\tbegin \n\t' read catch \n\t?dup-if [char] ! emit tab . cr then ( exception handler of last resort )\n\tagain ;\n\n: [interpret] \n\timmediate interpret ;\n\n( ============================================================================= )\n( WORKS UP TO HERE )\n( WORKS UP TO HERE )\n( WORKS UP TO HERE )\n( WORKS UP TO HERE )\n( WORKS UP TO HERE )\n( NB. It does not crash that is, previously defined words might be incorrect )\n( ============================================================================= )\n\n\n\\ interpret ( use the new interpret word, which can catch exceptions )\n\n\n\n\\ find [interpret] cfa start! ( the word executed on restart is now our new word )\n\n\n( ========================== Basic Word Set ================================== )\n\n( ========================== Extended Word Set =============================== )\n\n: log2 ( x -- log2 )\n\t( Computes the binary integer logarithm of a number,\n\tzero however returns itself instead of reporting an error )\n\t0 swap\n\tbegin\n\t\tnos1+ 2\/ dup 0=\n\tuntil\n\tdrop 1- ;\n\n: time ( \" ccc\" -- n : time the number of milliseconds it takes to execute a word )\n\tclock >r\n\tfind execute\n\tclock r> - ;\n\n: rdepth\n\tmax-core `stack-size @ - r @ swap - ;\n\n( defer...is is probably not standards compliant, it is still neat! Also, there\n is no error handling if \"find\" fails... )\n: (do-defer) ( -- self : pushes the location into which it is compiled )\n\tr> dup >r 1- ;\n\n: defer ( \" ccc\" -- , Run Time -- location : \n\tcreates a word that pushes a location to write an execution token into )\n\t:: ' (do-defer) , postpone ; ;\n\n: is ( location \" ccc\" -- : make a deferred word execute a word ) \n\tfind cfa swap ! ;\n\n\nhider (do-defer)\n\n( The \"tail\" function implements tail calls, which is just a jump\nto the beginning of the words definition, for example this\nword will never overflow the stack and will print \"1\" followed\nby a new line forever,\n\n\t: forever 1 . cr tail ;\n\nWhereas\n\n\t: forever 1 . cr recurse ;\n\nor\n\n\t: forever 1 . cr forever ;\n\nWould overflow the return stack. )\n\nhider tail\n: tail ( -- : perform tail recursion in current word definition )\n\timmediate\n\tlatest cell+\n\t' branch ,\n\there - cell+ , ;\n\n: recurse immediate\n\t( This function implements recursion, although this interpreter\n\tallows calling a word directly. If used incorrectly this will\n\tblow up the return stack.\n\n\tWe can test \"recurse\" with this factorial function:\n\t : factorial dup 2 < if drop 1 exit then dup 1- recurse * ; )\n\tlatest cell+ , ;\n\n: factorial ( x -- x : compute the factorial of a number )\n\tdup 2 < if drop 1 exit then dup 1- recurse * ;\n\n: myself ( -- : myself is a synonym for recurse ) \n\timmediate postpone recurse ;\n\n: gcd ( x1 x2 -- x : greatest common divisor )\n\tdup if tuck mod tail then drop ;\n\n( ========================== Extended Word Set =============================== )\n\n( The words described here on out get more complex and will require more\nof an explanation as to how they work. )\n\n( ========================== CREATE DOES> ==================================== )\n\n( The following section defines a pair of words \"create\" and \"does>\" which\nare a powerful set of words that can be used to make words that can create\nother words. \"create\" has both run time and compile time behavior, whilst\n\"does>\" only works at compile time in conjunction with \"create\". These two\nwords can be used to add constants, variables and arrays to the language,\namongst other things.\n\nA simple version of create is as follows\n\n\t: create :: 2 , here 2 + , ' exit , 0 state ! ;\n\nBut this version is much more limited.\n\n\"create\"...\"does>\" is one of the constructs that makes Forth Forth, it\nallows the creation of words which can define new words in themselves,\nand thus allows us to extend the language easily.\n)\n\n: write-quote ( -- : A word that writes ' into the dictionary )\n\t['] ' , ; \n\n: write-exit ( -- : A word that write exit into the dictionary )\n\t['] exit , ; \n\n: write-compile, ( -- : A word that writes , into the dictionary ) \n\t' , , ;\n\n: state! ( bool -- : set the compilation state variable ) \n\tstate ! ;\n\n: command-mode ( -- : put the interpreter into command mode )\n\tfalse state! ;\n\n: command-mode-create ( create a new work that pushes its data field )\n\t:: ( compile a word )\n\tdolit , ( write push into new word )\n\there 2+ , ( push a pointer to data field )\n\tpostpone ; ; ( write exit and switch to command mode )\n\n: mark write-compile, ( Write in a place holder 0 and push a pointer to to be used by does> )\n\twrite-quote write-exit write-compile, ( Write in an exit in the word we're compiling. )\n\t['] command-mode , ; ( Make sure to change the state back to command mode )\n\n: create immediate ( create word is quite a complex forth word )\n\tstate @ \n\tif \n\t\tpostpone ( hole-to-patch -- )\n\timmediate\n\twrite-exit ( we don't want the defining to exit, but the *defined* word to )\n\there swap ! ( patch in the code fields to point to )\n\tdolist , ; ( write a run in )\n\nhider write-quote\nhider write-compile,\n\n( Now that we have create...does> we can use it to create arrays, variables\nand constants, as we mentioned before. )\n\n: array ( u c\" xxx\" -- : create a named array of length u ) \n\tcreate allot does> + ;\n\n\n: variable ( x c\" xxx\" -- : create a variable will initial value of x )\n\tcreate , does> ;\n\n: constant ( x c\" xxx\" -- : create a constant with value of x ) \n\tcreate , does> @ ;\n\n: table ( u c\" xxx\" --, Run Time: -- addr u : create a named table )\n\tcreate dup , allot does> dup @ ;\n\n: string ( u c\" xxx\" --, Run Time: -- addr u : create a named table )\n\tcreate dup , chars allot does> dup @ swap 1+ chars> swap ;\n\n\\ : +field \\ n <\"name\"> -- ; exec: addr -- 'addr\n\\ create over , +\n\\ does> @ + ;\n\\ \n\\ : begin-structure \\ -- addr 0 ; -- size\n\\ \tcreate\n\\ \there 0 0 , \\ mark stack, lay dummy\n\\ \tdoes> @ ; \\ -- rec-len\n\\ \n\\ : end-structure \\ addr n --\n\\ swap ! ; \\ set len \n\\ \n\\ begin-structure point\n\\ \tpoint +field p.x\n\\ \tpoint +field p.y\n\\ end-structure\n\\ \n\\ This should work...\n\\ : buffer: ( u c\" xxx\" --, Run Time: -- addr )\n\\\tcreate allot ;\n\n: 2constant \n\tcreate , , does> dup 1+ @ swap @ ;\n\n: 2variable \n\tcreate , , does> ;\n\n: enum ( x \" ccc\" -- x+1 : define a series of enumerations )\n\tdup constant 1+ ; \n\n( ========================== CREATE DOES> ==================================== )\n\n( ========================== DO...LOOP ======================================= )\n\n( The following section implements Forth's do...loop constructs, the\nword definitions are quite complex as it involves a lot of juggling of\nthe return stack. Along with begin...until do loops are one of the\nmain looping constructs. \n\nUnlike begin...until do accepts two values a limit and a starting value,\nthey are also words only to be used within a word definition, some Forths\nextend the semantics so looping constructs operate in command mode, this\nForth does not do that as it complicates things unnecessarily.\n\nExample:\n\t\n\t: example-1 10 1 do i . i 5 > if cr leave then loop 100 . cr ; \n\texample-1\n\nPrints:\n\t1 2 3 4 5 6\n\nIn \"example-1\" we can see the following:\n\n1. A limit, 10, and a start value, 1, passed to \"do\".\n2. A word called 'i', which is the current count of the loop\n3. If the count is greater than 5, we call a word call 'leave', this\nword exits the current loop context as well as the current calling\nword.\n4. \"100 . cr\" is never called. This should be changed in future\nrevision, but this version of leave exits the calling word as well.\n\n'i', 'j', and 'leave' *must* be used within a do...loop construct. \n\nIn order to remedy point 4. loop should not use branch but instead \nshould use a value to return to which it pushes to the return stack )\n\n: (do)\n\tswap ( swap the limit and start )\n\tr> ( save our return stack to temporary variable )\n\t-rot ( limit start return -- return start limit )\n\t>r ( push limit onto return stack )\n\t>r ( push start onto return stack )\n\t>r ; ( restore our return address )\n\n: do immediate ( Run time: high low -- : begin do...loop construct )\n\t' (do) ,\n\tpostpone begin ; \n\n: (unloop) ( -- , R: i limit -- : remove limit and i from )\n\tr> ( save our return address )\n\trdrop ( pop off i )\n\trdrop ( pop off limit )\n\t>r ; ( restore our return stack )\n\n: (+loop) ( x -- bool : increment loop variable by x and test it )\n\tr@ 1- ( get the pointer to i )\n\t+! ( add value to it )\n\tr@ 1- @ ( find i again )\n\tr@ 2- @ ( find the limit value )\n\tu>= ;\n\n: (loop) ( -- bool : increment loop variable by 1 and test it )\n\tr@ 1- ( get the pointer to i )\n\t1+! ( add one to it )\n\tr@ 1- @ ( find the value again )\n\tr@ 2- @ ( find the limit value )\n\tu>= ;\n\n: loop ( -- : end do...loop construct )\n\timmediate ' (loop) , postpone until ' (unloop) , ;\n\n: +loop ( x -- : end do...+loop loop construct )\n\timmediate ' (+loop) , postpone until ' (unloop) , ;\n\n: leave ( -- , R: i limit return -- : break out of a do-loop construct )\n\t(unloop)\n\trdrop ; ( return to the caller's caller routine )\n\n: ?leave ( x -- , R: i limit return -- | i limit return : conditional leave )\n\tif\n\t\t(unloop)\n\t\trdrop ( return to the caller's caller routine )\n\tthen ;\n\n: i ( -- i : Get current, or innermost, loop index in do...loop construct )\n\tr> r> ( pop off return address and i )\n\ttuck ( tuck i away )\n\t>r >r ; ( restore return stack )\n\n: j ( -- j : Get outermost loop index in do...loop construct )\n\t4 rpick ;\n\n( This is a simple test function for the looping, for interactive\ntesting and debugging:\n : mm 5 1 do i . cr 4 1 do j . tab i . cr loop loop ; )\n\n: range ( nX nY -- nX nX+1 ... nY ) \n\tnos1+ do i loop ;\n\n: repeater ( n0 X -- n0 ... nX ) \n\t1 do dup loop ;\n\n: sum ( n0 ... nX X -- sum<0..X> ) \n\t1 do + loop ;\n\n: mul ( n0 ... nX X -- mul<0..X> ) \n\t1 do * loop ;\n\n: reverse ( x1 ... xn n -- xn ... x1 : reverse n items on the stack )\n\t0 do i roll loop ;\n\n\n( ========================== DO...LOOP ======================================= )\n0 variable column-counter\n4 variable column-width\n\n: column ( i -- )\t\n\tcolumn-width @ mod not if cr then ;\n\n: reset-column\t\t\n\t0 column-counter ! ;\n\n: auto-column\t\t\n\tcolumn-counter dup @ column 1+! ;\n\n: alignment-bits \n\t[ 1 size log2 lshift 1- literal ] and ;\n\n: name ( PWD -- c-addr : given a pointer to the PWD field of a word get a pointer to the name of the word )\n\tdup 1+ @ 256\/ 127 and lsb - chars> ;\n\n0 variable x\n: x! ( x -- ) \n\tx ! ;\n\n: x@ ( -- x ) \n\tx @ ;\n\n: 2>r ( x1 x2 -- R: x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tswap\n\t\t>r\n\t\t>r\n\tx@ >r ; ( restore return address )\n\n: 2r> ( R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tr>\n\t\tr>\n\t\tswap\n\tx@ >r ; ( restore return address )\n\n: 2r@ ( -- x1 x2 , R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\tr> r>\n\t2dup\n\t>r >r\n\tswap\n\tx@ >r ; ( restore return address )\n\n: unused ( -- u : push the amount of core left ) \n\tmax-core here - ;\n\n: accumulator ( initial \" ccc\" -- : make a word that increments by a value and pushes the result )\n\tcreate , does> tuck +! @ ;\n\n: counter ( \" ccc\" --, Run Time: -- x : make a word that increments itself by one, starting from zero )\n\tcreate -1 , does> dup 1+! @ ;\n\n0 variable delim\n: accepter ( c-addr max delimiter -- i )\n\t( store a \"max\" number of chars at c-addr until \"delimiter\" encountered,\n\tthe number of characters stored is returned )\n\tdelim ! ( store delimiter used to stop string storage when encountered)\n\t0\n\tdo\n\t\tkey dup delim @ <>\n\t\tif\n\t\t\tover c! 1+\n\t\telse ( terminate string )\n\t\t\tdrop 0 swap c! \n\t\t\ti \n\t\t\tleave\n\t\tthen\n\tloop\n\t-11 throw ; ( read in too many chars )\nhider delim\n\n: skip\n\tkey drop >r 0 begin drop key dup rdup r> <> until rdrop ;\n\n: word ( c -- c-addr : parse until 'c' is encountered, push transient counted string )\n\tdup skip chere 1+ c!\n\t>r\n\tchere 2+\n\tpad here - chars>\n\tr> accepter 1+\n\tchere c!\n\tchere ;\n\nhider skip\n\n: accept ( c-addr +n1 -- +n2 : see accepter definition ) \n\t'\\n' accepter ;\n\n0xFFFF constant max-string-length\n\n: (.\") ( char -- c-addr u )\n\t( @todo This really needs simplifying, to do this\n\ta set of words that operate on a temporary buffer can\n\tbe used )\n\t( Write a string into word being currently defined, this\n\tcode has to jump over the string it has just put into the\n\tdictionary so normal execution of a word can continue. The\n\tlength and character address of the string are left on the\n\tstack )\n\t>r ( save delimiter )\n\t' branch , ( write in jump, this will jump past the string )\n\t>mark ( make hole )\n\tdup 1+ chars> ( calculate address to write to )\n\tmax-string-length \n\tr> ( restore delimiter )\n\taccepter dup >r ( write string into dictionary, save index )\n\taligned 2dup size \/ ( stack: length hole char-len hole )\n\t1+ dup allot ( update dictionary pointer with string length )\n\t1+ swap ! ( write place to jump to )\n\tdrop ( do not need string length anymore )\n\t1+ chars> ( calculate place to print )\n\tr> ; ( restore index and address of string )\n\n: length ( c-addr u -- u : push the length of an ASCIIZ string )\n tuck 0 do dup c@ 0= if 2drop i leave then 1+ loop ;\n\n: asciiz? ( c-addr u -- : is a Forth string also a ASCIIZ string )\n\ttuck length <> ;\n\n: asciiz ( c-addr u -- : trim a string until NUL terminator )\n\t2dup length nip ;\n\n: type ( c-addr u -- : print out 'u' characters at c-addr )\n\t0 do dup c@ emit 1+ loop drop ;\n\n: do-string ( char -- : write a string into the dictionary reading it until char is encountered )\n\t(.\") \n\tstate @ if swap [literal] [literal] then ;\n\n: fill ( c-addr u char -- : fill in an area of memory with a character, only if u is greater than zero )\n\t-rot\n\t0 do 2dup i + c! loop\n\t2drop ;\n\n: \/string ( c-addr1 u1 n -- c-addr2 u2 : advance a string by n characters )\n\tover min rot over + -rot - ;\n\n: compare ( c-addr1 u1 c-addr2 u2 -- n : compare two strings, not quite compliant yet )\n\t>r swap r> min >r\n\tstart-address + swap start-address + r>\n\tmemory-compare ;\n\n128 string sbuf\n: s\" ( \"ccc\" --, Run Time -- c-addr u )\n\tkey drop sbuf 0 fill sbuf [char] \" accepter sbuf drop swap ;\nhider sbuf\n\n( @todo these strings really need rethinking, state awareness needs to be removed... )\n: type, \n\tstate @ if ' type , else type then ;\n\n: c\" \n\timmediate key drop [char] \" do-string ;\n\n: \" \n\timmediate key drop [char] \" do-string type, ;\n\n: sprint ( c -- : print out chars until 'c' is encountered )\n\tkey drop ( drop next space )\n\t>r ( save delimiter )\n\tbegin\n\t\tkey dup ( get next character )\n\t\trdup r> ( get delimiter )\n\t\t<> if emit 0 then\n\tuntil rdrop ;\n\n: .( \n\timmediate [char] ) sprint ;\nhider sprint\n\n: .\" \n\timmediate key drop [char] \" do-string type, ;\n\nhider type,\n\n( This word really should be removed along with any usages of this word, it\nis not a very \"Forth\" like word, it accepts a pointer to an ASCIIZ string and\nprints it out, it also does not checking of the returned values from write-file )\n: print ( c-addr -- : print out a string to the standard output )\n\t-1 over >r length r> swap stdout write-file 2drop ;\n\n: ok \n\t\" ok\" cr ;\n\n: empty-stack ( x-n ... x-0 -- : empty the variable stack )\n\tbegin depth while drop repeat ;\n\n: (quit) ( -- : do the work of quit, without the restart )\n\t0 `source-id ! ( set source to read from file )\n\t`stdin @ `fin ! ( read from stdin )\n\tpostpone [ ( back into command mode )\n\t' interpret start! ; ( set interpreter starting word )\n\n: quit ( -- : Empty return stack, go back to command mode, read from stdin, interpret input )\n\t(quit)\n\t-1 restart ; ( restart the interpreter )\n\n: abort\n\t-1 throw ;\n\n: (abort\") ( do the work of abort )\n\t(quit)\n\t-2 throw ;\n\n: abort\" immediate \n\tpostpone \"\n\t' cr , ' (abort\") , ;\n\n( ==================== CASE statements ======================== )\n\n( for a simpler case statement:\n\tsee Volume 2, issue 3, page 48 of Forth Dimensions at\n\thttp:\/\/www.forth.org\/fd\/contents.html )\n\n( These case statements need improving, it is not standards compliant )\n: case immediate\n\t' branch , 3 , ( branch over the next branch )\n\there ' branch , ( mark: place endof branches back to with again )\n\t>mark swap ; ( mark: place endcase writes jump to with then )\n\n: over= ( x y -- x bool : over ... then = )\n\tover = ;\n\n: of\n\timmediate ' over= , postpone if ;\n\n: endof\n\timmediate over postpone again postpone then ;\n\n: endcase\n\timmediate 1+ postpone then drop ;\n\n( ==================== CASE statements ======================== )\n\n( ==================== Hiding Words =========================== )\n\n: }hide ( should only be matched with 'hide{' )\n\timmediate -22 throw ;\n\n: hide{ ( -- : hide a list of words, the list is terminated with \"}hide\" )\n\tbegin\n\t\tfind ( find next word )\n\t\tdup [ find }hide ] literal = if\n\t\t\tdrop exit ( terminate hide{ )\n\t\tthen\n\t\tdup 0= if -15 throw then\n\t\thide drop\n\tagain ;\n\n( ==================== Hiding Words =========================== )\n\n: spaces ( n -- : print n spaces ) \n\t0 do space loop ;\n\n: erase ( addr u : erase a block of memory )\n\t2chars> 0 fill ;\n\n: blank ( c-addr u : fills a string with spaces )\n\tbl fill ;\n\n( move should check that u is not negative )\n: move ( addr1 addr2 u -- : copy u words of memory from 'addr2' to 'addr1' )\n\t0 do\n\t\t2dup i + @ swap i + !\n\tloop\n\t2drop ;\n\n( It would be nice if move and cmove could share more code, as they do exactly\n the same thing but with different load and store functions, cmove> )\n: cmove ( c-addr1 c-addr2 u -- : copy u characters of memory from 'c-addr2' to 'c-addr1' )\n\t0 do\n\t\t2dup i + c@ swap i + c!\n\tloop\n\t2drop ;\n\n( ==================== Conditional Compilation ================ )\n\n( The words \"[if]\", \"[else]\" and \"[then]\" implement conditional compilation,\nthey can be nested as well\n\nSee http:\/\/lars.nocrew.org\/dpans\/dpans15.htm for more information\n\nA much simpler conditional compilation method is the following\nsingle word definition:\n\n : compile-line? 0= if [ find \\\\ , ] then ;\n\nWhich will skip a line if a conditional is false, and compile it\nif true )\n\n( These words really, really need refactoring, I could use the newly defined \n \"defer\" to help out with this )\n0 variable nest ( level of [if] nesting )\n0 variable [if]-word ( populated later with \"find [if]\" )\n0 variable [else]-word ( populated later with \"find [else]\")\n: [then] immediate ;\n: reset-nest 1 nest ! ;\n: unnest? [ find [then] ] literal = if nest 1-! then ;\n: nest? [if]-word @ = if nest 1+! then ;\n: end-nest? nest @ 0= ;\n: match-[else]? [else]-word @ = nest @ 1 = and ;\n\n: [if] ( bool -- : conditional execution )\n\tunless\n\t\treset-nest\n\t\tbegin\n\t\t\tfind\n\t\t\tdup nest?\n\t\t\tdup match-[else]? if drop exit then\n\t\t\t unnest?\n\t\t\tend-nest?\n\t\tuntil\n\tthen ;\n\n: [else] ( discard input until [then] encounter, nesting for [if] )\n\treset-nest\n\tbegin\n\t\tfind\n\t\tdup nest? unnest?\n\t\tend-nest?\n\tuntil ;\n\nfind [if] [if]-word !\nfind [else] [else]-word !\n\nhide{ \n[if]-word [else]-word nest reset-nest unnest? match-[else]? end-nest? nest? }hide\n\n( ==================== Conditional Compilation ================ )\n\n( ==================== Endian Words =========================== )\n\nsize 2 = [if] 0x0123 variable endianess [then]\nsize 4 = [if] 0x01234567 variable endianess [then]\nsize 8 = [if] 0x01234567abcdef variable endianess [then]\n\n: endian ( -- bool : returns the endianess of the processor, little = 0, big = 1 )\n\t[ endianess chars> c@ 0x01 = ] literal ;\nhider endianess\n\n: swap16 ( x -- x : swap the byte order a 16 bit number )\n\tdup 256* 0xff00 and >r 256\/ lsb r> or ;\n\nsize 4 >= [if] \n\t: swap32 \n\t\tdup 0xffff and swap16 16 lshift swap\n\t\t16 rshift 0xffff and swap16 or ;\n[then]\n\nsize 8 >= [if]\n\t: swap64 ( x -- x : swap the byte order of a 64 bit number )\n\t\t dup 0xffffffff and swap32 32 lshift swap\n\t\t 32 rshift 0xffffffff and swap32 or ;\n[then]\n\nsize 2 = [if]\n\tendian \n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\tswap16 ;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\t;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\tswap16 ;\n\t[then]\n[then]\n\nsize 4 = [if]\n\tendian \n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\tswap32 ;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\t;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\tswap32 ;\n\t[then]\n[then]\n\nsize 8 = [if]\n\tendian \n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\tswap64 ;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\t;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\tswap64 ;\n\t[then]\n[then]\n\n( ==================== Endian Words =========================== )\n\n( ==================== Misc words ============================= )\n\n0 variable counter\n\n: counted-column ( index -- : special column printing for dump )\n\tcounter @ column-width @ mod\n\tnot if cr . \" :\" space else drop then\n\tcounter 1+! ;\n\n: as-chars ( x n -- : print a cell out as characters, upto n chars )\n\t0 ( from zero to the size of a cell )\n\tdo\n\t\tdup ( copy variable to print out )\n\t\tsize i 1+ - select-byte ( select correct byte )\n\t\tdup printable? not ( is it not printable )\n\t\tif drop [char] . then ( print a '.' if it is not )\n\t\temit ( otherwise print it out )\n\tloop\n\tspace ( print out space after )\n\tdrop ; ( drop cell we have printed out )\n\n: lister ( addr u addr -- )\n\t0 counter ! 1- swap \n\tdo \n\t\tdup counted-column 1+ i ? i @ size as-chars \n\tloop ;\n\n( @todo this function should make use of 'defer' and 'is', then different\nversion of dump could be made that swapped out 'lister' )\n: dump ( addr u -- : dump out 'u' cells of memory starting from 'addr' )\n\tbase @ >r hex 1+ over + under lister drop r> base ! cr ;\n\nhide{ counted-column counter as-chars }hide\n\n: forgetter ( pwd-token -- : forget a found word and everything after it )\n\tdup @ pwd ! h ! ;\n\n( @bug will not work for immediate defined words \n@note Fig Forth had a word FENCE, if anything before this word was\nattempted to be forgotten then an exception is throw )\n: forget ( WORD -- : forget word and every word defined after it )\n\tfind dup 0= if -15 throw then 1- forgetter ;\n\n: marker ( WORD -- : make word the forgets itself and words after it)\n\t:: latest [literal] ' forgetter , postpone ; ;\nhider forgetter\n\n: ** ( b e -- x : exponent, raise 'b' to the power of 'e')\n\t?dup-if\n\t\tover swap\n\t\t1 do over * loop \n\t\tnip\n\telse\n\t\tdrop 1\n\tendif ;\n\n0 variable a\n0 variable b\n0 variable m\n: equal ( a1...an b1...bn n -- a1...an b1...bn bool : determine if two lists are equal )\n\t( example: \n\t\t1 2 3 \n\t\t1 2 3 \n\t\t3 equal \n\treturns: 1 )\n\tdup m ! 1+ 1 ( store copy of length and use as loop index )\n\tdo \n\t\ti 1- pick b ! ( store ith element of list in b1...bn )\n\t\ti m @ + 1- pick a ! ( store ith element of list in a1...an )\n\t\ta @ b @ <> ( compare a and b for equality )\n\t\tif 0 leave then ( unequal, finish early )\n\tloop 1 ; ( lists must be equal )\n\nhide{ a b m }hide\n\n: ndrop ( drop n items )\n\t?dup-if 0 do drop loop then ;\n\n( ==================== Misc words ============================= )\n\n( ==================== Pictured Numeric Output ================ )\n\n0 variable hld\n\n: overflow ( -- : )\n \there chars> pad chars> hld @ - u> if -17 throw then ;\n\n: hold ( char -- : add a character to the numeric output string )\n\toverflow pad chars> hld @ - c! hld 1+! ;\n\n: holds ( addr u -- )\n begin dup while 1- 2dup + c@ hold repeat 2drop ;\n\n: nbase ( -- base : in this forth 0 is a special base, push 10 is base is zero )\n\tbase @ dup 0= if drop 10 then ;\n\n: <# ( -- : setup pictured numeric output )\n\t0 hld ! ;\n\n: sign ( -- : add a sign to the pictured numeric output string )\n\t[char] - hold ;\n\n: # ( x -- x : divide x by base, turn into a character, put in pictured output string )\n\tnbase um\/mod swap \n \tdup 9 u>\n \tif 7 + then\n \t48 + hold ;\n\n: #s ( x -- 0 : repeatedly call # on x until x is zero )\n\tbegin # dup 0= until ; \n\n: #> ( -- c-addr u : end pictured output conversion, push output string to stack )\n\t0 hold ( NUL terminate string, just in case )\n\thld 1-! ( but do not include that in the count )\n\tpad chars> hld @ \n\ttuck - 1+ swap ;\n\n: u. ( u -- : display number in base 10 )\n\tbase @ >r decimal <# #s #> type drop r> base ! ;\n\nhide{ nbase overflow }hide\n\n( ==================== Pictured Numeric Output ================ )\n\n( ==================== ANSI Escape Codes ====================== )\n( Terminal colorization module, via ANSI Escape Codes\n \nsee: https:\/\/en.wikipedia.org\/wiki\/ANSI_escape_code\nThese codes will provide a relatively portable means of\nmanipulating a terminal )\n\n27 constant 'escape'\n: CSI 'escape' emit .\" [\" ;\n0 constant black\n1 constant red\n2 constant green\n3 constant yellow\n4 constant blue\n5 constant magenta\n6 constant cyan\n7 constant white\n: foreground 30 + ;\n: background 40 + ;\n0 constant dark\n1 constant bright\nfalse variable colorize \n\n: color ( brightness color-code -- : set the terminal color )\n\t( set color on an ANSI compliant terminal,\n\tfor example:\n\t\tbright red foreground color\n\tsets the foreground text to bright red )\n\tcolorize @ 0= if 2drop exit then \n\tCSI u. if .\" ;1\" then .\" m\" ;\n\n: at-xy ( x y -- : set ANSI terminal cursor position to x y )\n\tCSI u. [char] ; emit u. .\" H\" ;\n\n: page ( -- : clear ANSI terminal screen and move cursor to beginning ) \n\tCSI .\" 2J\" 1 1 at-xy ;\n\n: hide-cursor ( -- : hide the cursor from view ) \n\tCSI .\" ?25l\" ;\n\n: show-cursor ( -- : show the cursor ) \n\tCSI .\" ?25h\" ;\n\n: save-cursor ( -- : save cursor position ) \n\tCSI .\" s\" ;\n\n: restore-cursor ( -- : restore saved cursor position ) \n\tCSI .\" u\" ;\n\n: reset-color ( -- : reset terminal color to its default value)\n\tcolorize @ 0= if exit then\n\tCSI .\" 0m\" ;\n\nhide{ CSI }hide\n( ==================== ANSI Escape Codes ====================== )\n\n( ==================== Unit test framework =================== )\n\n256 string estring ( string to test )\n0 variable #estring ( actual string length )\n0 variable start ( starting depth )\n0 variable result ( result depth )\n0 variable check ( only check depth if -> is called )\n0 variable dictionary ( dictionary pointer on entering { )\n0 variable previous ( PWD register on entering { )\n\n: T ; ( hack until T{ can process words )\n\n: -> ( -- : save depth in variable ) \n\t1 check ! depth result ! ; \n\n: test estring drop #estring @ ; \n\n: fail ( -- : invalidate the forth interpreter and exit )\n\tinvalidate bye ;\n\n: neutral ( -- : neutral color )\n\t;\n\n: bad ( -- : bad color )\n\tdark red foreground color ;\n\n: good ( -- : good color )\n\tdark green foreground color ;\n\n: die bad test type reset-color cr fail ;\n\n: evaluate? ( bool -- : test if evaluation has failed )\n\tif .\" evaluation failed\" cr fail then ;\n\n: failed bad .\" failed\" reset-color cr ;\n\n: adjust ( x -- x : adjust a depth to take into account starting depth ) \n\tstart @ - ;\n\n: no-check? ( -- bool : if true we need to check the depth )\n\tcheck @ 0= ;\n\n: depth? ( -- : check if depth is correct )\n\tno-check? if exit then\n\tdepth adjust ( get depth and adjust for starting depth )\n\tresult @ adjust 2* = ( get results depth, same adjustment, should be\n\t half size of the depth ) \n\tif exit then ( pass )\n\tfailed\n\t.\" Unequal depths:\" cr\n\t.\" depth: \" depth . cr\n\t.\" result: \" result @ . cr\n\tdie ;\n\n: equal? ( -- : determine if results equals expected )\n\tno-check? if exit then\n\tresult @ adjust equal\n\tif exit then\n\tfailed\n\t.\" Result is not equal to expected values. \" cr \n\t.\" Stack: \" cr .s cr\n\tdie ;\n\n: display ( c-addr u -- : print out testing message in estring )\n\tverbose if neutral type else 2drop then ;\n\n: pass ( -- : print out passing message )\n\tverbose if good .\" ok \" cr reset-color then ;\n\n: save ( -- : save current dictionary )\n\tpwd @ previous !\n\there dictionary ! ;\n\n: restore ( -- : restore dictionary )\n\tprevious @ pwd ! \n\tdictionary @ h ! ;\n\n\n: T{ ( -- : perform a unit test )\n\tdepth start ! ( save start of stack depth )\n\t0 result ! ( reset result variable )\n\t0 check ! ( reset check variable )\n\testring 0 fill ( zero input string )\n\tsave ( save dictionary state )\n\tkey drop ( drop next character, which is a space )\n\testring [char] } accepter #estring ! ( read in string to test )\n\ttest display ( print which string we are testing )\n\ttest evaluate ( perform test )\n\tevaluate? ( evaluate successfully? )\n\tdepth? ( correct depth )\n\tequal? ( results equal to expected values? )\n\tpass ( print pass message )\n\tresult @ adjust 2* ndrop ( remove items on stack generated by test )\n\trestore ; ( restore dictionary to previous state )\n\nT{ }T\nT{ -> }T\nT{ 1 -> 1 }T\nT{ 1 2 -> 1 2 }T\nT{ : c 1 2 ; c -> 1 2 }T\nT{ :noname 2 ; :noname 3 + ; compose execute -> 5 }T\n\nhide{ \n\tpass test display\n\tadjust start save restore dictionary previous \n\tevaluate? equal? depth? estring #estring result\n\tcheck no-check? die neutral bad good failed\n}hide\n\n( ==================== Unit test framework =================== )\n\n\n( ==================== Random Numbers ========================= )\n\n( \nSee:\nuses xorshift\nhttps:\/\/en.wikipedia.org\/wiki\/Xorshift\nhttp:\/\/excamera.com\/sphinx\/article-xorshift.html\nhttp:\/\/www.arklyffe.com\/main\/2010\/08\/29\/xorshift-pseudorandom-number-generator\/\nthese constants have be collected from the web \n)\n\nsize 2 = [if] 13 constant a 9 constant b 7 constant c [then]\nsize 4 = [if] 13 constant a 17 constant b 5 constant c [then]\nsize 8 = [if] 12 constant a 25 constant b 27 constant c [then]\n\n7 variable seed ( must not be zero )\n\n: seed! ( x -- : set the value of the PRNG seed )\n\tdup 0= if drop 7 ( zero not allowed ) then seed ! ;\n\n: random ( -- x : assumes word size is 32 bit )\n\tseed @\n\tdup a lshift xor\n\tdup b rshift xor\n\tdup c lshift xor\n\tdup seed! ;\n\nhide{ a b c seed }hide\n\n( ==================== Random Numbers ========================= )\n\n( ==================== Prime Numbers ========================== )\n( From original \"third\" code from the IOCCC at \nhttp:\/\/www.ioccc.org\/1992\/buzzard.2.design, the module works out\nand prints prime numbers. )\n\n: prime? ( u -- u | 0 : return number if it is prime, zero otherwise )\n\tdup 1 = if 1- exit then\n\tdup 2 = if exit then\n\tdup 2 \/ 2 ( loop from 2 to n\/2 )\n\tdo\n\t\tdup ( value to check if prime )\n\t\ti mod ( mod by divisor )\n\t\tnot if\n\t\t\tdrop 0 leave\n\t\tthen\n\tloop ;\n\n0 variable counter\n\n: primes ( x1 x2 -- : print the primes from x2 to x1 )\n\t0 counter !\n\t\" The primes from \" dup . \" to \" over . \" are: \"\n\tcr\n\treset-column\n\tdo\n\t\ti prime?\n\t\tif\n\t\t\ti . counter @ column counter 1+!\n\t\tthen\n\tloop\n\tcr\n\t\" There are \" counter @ . \" primes.\"\n\tcr ;\n\nhide{ counter }hide\n( ==================== Prime Numbers ========================== )\n\n( ==================== Debugging info ========================= )\n\n( string handling should really be done with PARSE, and CMOVE )\n\nhide{ .s }hide\n: .s ( -- : print out the stack for debugging )\n\t\" <\" depth u. \" >\" space\n\tdepth if\n\t\tdepth 0 do i column tab depth i 1+ - pick u. loop\n\tthen\n\tcr ;\n\n1 variable hide-words ( do we want to hide hidden words or not )\n( This function prints out all of the defined words, excluding hidden words.\nAn understanding of the layout of a Forth word helps here. The dictionary\ncontains a linked list of words, each forth word has a pointer to the previous\nword until the first word. The layout of a Forth word looks like this:\n\nNAME: Forth Word - A variable length ASCII NUL terminated string\nPWD: Previous Word Pointer, points to the previous word\nMISC: Flags, code word and offset from previous word pointer to start of Forth word string\nCODE\/DATA: The body of the forth word definition, not interested in this.\n\nThere is a register which stores the latest defined word which can be\naccessed with the code \"pwd @\". In order to print out a word we need to\naccess a words MISC field, the offset to the NAME is stored here in bits\n8 to 15 and the offset is calculated from the PWD field.\n\n\"print\" expects a character address, so we need to multiply any calculated\naddress by the word size in bytes. )\n\n: words ( -- : print out all defined an visible words )\n\tlatest\n\tbegin\n\t\tdup\n\t\thidden? hide-words @ and\n\t\tnot if\n\t\t\tname\n\t\t\tprint space\n\t\telse\n\t\t\tdrop\n\t\tthen\n\t\t@ ( Get pointer to previous word )\n\t\tdup dictionary-start u< ( stop if pwd no longer points to a word )\n\tuntil\n\tdrop cr ;\nhider hide-words\n\n: TrueFalse ( -- : print true or false )\n\tif \" true\" else \" false\" then ;\n\n: registers ( -- : print out important registers and information about the virtual machine )\n\t\" return stack pointer: \" r@ . cr\n\t\" dictionary pointer \" here . cr\n\t\" previous word: \" pwd ? cr\n\t\" state: \" state ? cr\n\t\" base: \" base ? cr\n\t\" depth: \" depth . cr\n\t\" cell size (in bytes): \" size . cr\n\t\" last cell address: \" max-core . cr\n\t\" unused cells: \" unused . cr\n\t\" invalid: \" `invalid @ TrueFalse cr\n\t\" size of variable stack: \" `stack-size ? cr\n\t\" size of return stack: \" `stack-size ? cr\n\t\" start of variable stack: \" max-core `stack-size @ 2* - . cr\n\t\" start of return stack: \" max-core `stack-size @ - . cr\n\t\" current input source: \" source-id -1 = if \" string\" else \" file\" then cr\n\t\" reading from stdin: \" source-id 0 = stdin? and TrueFalse cr\n\t\" tracing on: \" `debug @ TrueFalse cr\n\t\" starting word: \" `instruction ? cr\n\t\" real start address: \" `start-address ? cr\n\t\" error handling: \" `error-handler ? cr ;\n( `sin `sidx `slen `fout\n `stdout `stderr `argc `argv )\n\n\n: y\/n? ( -- bool : ask a yes or no question )\n\tkey drop\n\t\" y\/n? \"\n\tbegin\n\t\tkey\n\t\tdup\n\t\t[char] y = if true exit then\n\t\t[char] n = if false exit then\n\t\t\" y\/n? \"\n\tagain ;\n\n: >instruction ( MISC -- Instruction : extract instruction from instruction field ) \n\t0x7f and ;\n\n: step\n\t( step through a word: this word could be augmented\n\twith commands such as \"dump\", \"halt\", and optional\n\t\".s\" and \"registers\" )\n\tregisters\n\t\" .s: \" .s cr\n\t\" -- press any key to continue -- \"\n\tkey drop ;\n\n: more ( -- : wait for more input )\n\t\" -- press any key to continue -- \" key drop cr page ;\n\n: debug-help ( -- : this is not quite ready for prime time )\n \" debug mode commands\n\th - print help\n\tq - exit containing word\n\tr - print registers\n\ts - print stack\n\tc - continue on with execution\n\" ;\n\n: debug-prompt \n\t.\" debug> \" ;\n\n: debug ( a work in progress, debugging support, needs parse-word )\n\tkey drop\n\tcr\n\tbegin\n\t\tdebug-prompt\n\t\t'\\n' word count drop c@\n\t\tcase\n\t\t\t[char] h of debug-help endof\n\t\t\t[char] q of bye endof\n\t\t\t[char] r of registers endof\n\t\t\t[char] s of >r .s r> endof\n\t\t\t[char] c of drop exit endof\n\t\tendcase drop\n\tagain ;\nhider debug-prompt\n\n: code>pwd ( CODE -- PWD\/0 : calculate PWD from code address )\n\tdup dictionary-start here within not if drop 0 exit then\n\t>r\n\tlatest dup @ ( p1 p2 )\n\tbegin\n\t\tover ( p1 p2 p1 )\n\t\trdup r> u<= swap rdup r> > and if rdrop exit then\n\t\tdup 0= if rdrop exit then\n\t\tdup @ swap\n\tagain ;\n\n: end-print ( x -- )\n\t\"\t\t=> \" . \" ]\" ;\n\n: word-printer\n\t( attempt to print out a word given a words code field\n\tWARNING: This is a dirty hack at the moment\n\tNOTE: given a pointer to somewhere in a word it is possible\n\tto work out the PWD by looping through the dictionary to\n\tfind the PWD below it )\n\t1- dup @ -1 = if \" [ noname\" end-print exit then\n\t dup \" [ \" code>pwd ?dup-if name print else drop \" data\" then\n\t end-print ;\nhider end-print\nhider code>pwd\n\n( these words push the execution tokens for various special cases for decompilation )\n: get-branch [ find branch cfa ] literal ;\n: get-?branch [ find ?branch cfa ] literal ;\n: get-original-exit [ original-exit cfa ] literal ;\n: get-quote [ find ' cfa ] literal ;\n\n: branch-increment ( addr branch -- increment : calculate decompile increment for \"branch\" )\n\t1+ dup negative? if drop 2 else 2dup dump then ;\n\n( these words take a code field to a primitive they implement, decompile it\nand any data belonging to that operation, and push a number to increment the\ndecompilers code stream pointer by )\n\n: decompile-literal ( code -- increment )\n\t\" [ literal\t=> \" 1+ ? \" ]\" 2 ;\n: decompile-branch ( code -- increment )\n\t\" [ branch\t=> \" 1+ ? \" ]\" dup 1+ @ branch-increment ;\n: decompile-quote ( code -- increment )\n\t\" [ '\t=> \" 1+ @ word-printer \" ]\" 2 ;\n: decompile-?branch ( code -- increment )\n\t\" [ ?branch\t=> \" 1+ ? \" ]\" 2 ;\n\n( The decompile word expects a pointer to the code field of a word, it\ndecompiles a words code field, it needs a lot of work however.\nThere are several complications to implementing this decompile\nfunction.\n\n\t' The next cell should be pushed\n\t:noname This has a marker before its code field of -1 which\n\t\t cannot occur normally, this is handles in word-printer\n\tbranch branches are used to skip over data, but also for\n\t\t some branch constructs, any data in between can only\n\t\t be printed out generally speaking\n\texit There are two definitions of exit, the one used in\n\t\t ';' and the one everything else uses, this is used\n\t\t to determine the actual end of the word\n\tliterals Literals can be distinguished by their low value,\n\t\t which cannot possibly be a word with a name, the\n\t\t next field is the actual literal\n\nOf special difficult is processing 'if' 'else' 'then' statements,\nthis will require keeping track of '?branch'.\n\nAlso of note, a number greater than \"here\" must be data )\n\n: decompile ( code-field-ptr -- : decompile a word )\n\tbegin\n\t\ttab\n\t\tdup @\n\t\tcase\n\t\t\tdolit of drup decompile-literal endof\n\t\t\tget-branch of drup decompile-branch endof\n\t\t\tget-quote of drup decompile-quote endof\n\t\t\tget-?branch of drup decompile-?branch endof\n\t\t\tget-original-exit of 2drop \" [ exit ]\" cr exit endof\n\t\t\tword-printer 1\n\t\tendcase\n\t\t+\n\t\tcr\n\tagain ;\n\nhide{\n\tword-printer get-branch get-?branch get-original-exit \n\tget-quote branch-increment decompile-literal \n\tdecompile-branch decompile-?branch decompile-quote\n}hide\n\n: xt-instruction ( extract instruction from execution token )\n\tcfa @ >instruction ;\n\n( these words expect a pointer to the PWD field of a word )\n: defined-word? xt-instruction dolist = ;\n: print-name \" name: \" name print cr ;\n: print-start \" word start: \" name chars . cr ;\n: print-previous \" previous word: \" @ . cr ;\n: print-immediate \" immediate: \" cell+ @ >instruction compile-instruction <> TrueFalse cr ;\n: print-instruction \" instruction: \" xt-instruction . cr ;\n: print-defined \" defined: \" defined-word? TrueFalse cr ;\n\n: print-header ( PWD -- is-immediate-word? )\n\tdup print-name\n\tdup print-start\n\tdup print-previous\n\tdup print-immediate\n\tdup print-instruction ( @todo look up instruction name )\n\tprint-defined ;\n\n: see ( -- : decompile the next word in the input stream )\n\tfind\n\tdup 0= if -32 throw then\n\t1- ( move to PWD field )\n\tdup print-header\n\tdup defined-word?\n\tif ( decompile if a compiled word )\n\t\tcfa cell+ ( move to code field )\n\t\t\" code field:\" cr\n\t\tdecompile\n\telse ( the instruction describes the word if it is not a compiled word )\n\t\tdrop\n\tthen ;\n\n( These help messages could be moved to blocks, the blocks could then\nbe loaded from disk and printed instead of defining the help here,\nthis would allow much larger help )\n\n: help ( -- : print out a short help message )\n\tpage\n\tkey drop\n\" Welcome to Forth, an imperative stack based language. It is both a low\nlevel and a high level language, with a very small memory footprint. Most\nof Forth is defined as a combination of various primitives.\n\nA short description of the available function (or Forth words) follows,\nwords marked (1) are immediate and cannot be used in command mode, words\nmarked with (2) define new words. Words marked with (3) have both command\nand compile functionality.\n\n\"\nmore \" The built in words that accessible are:\n\n(1,2)\t: define a new word, switching to compile mode\n\timmediate make latest defined word immediate\n\tread read in a word, execute in command mode else compile\n\t@ ! fetch, store\n\tc@ c! character based fetch and store\n\t- + * \/ standard arithmetic operations,\n\tand or xor invert standard bitwise operations\n\tlshift rshift left and right bit shift\n\tu< u> < > = comparison predicates\n\texit exit from a word\n\temit print character from top of stack\n\tkey get a character from input\n\tr> >r pop a value from or to the return stack\n\tfind find a word in the dictionary and push the location\n\t' store the address of the following word on the stack\n\t, write the top of the stack to the dictionary\n\tswap swap first two values on the stack\n\tdup duplicate the top of the stack\n\tdrop pop and drop a value\n\tover copy the second stack value over the first\n\t. pop the top of the stack and print it\n\" \nmore \" \n\tprint print a NUL terminated string at a character address\n\tdepth get the current stack depth\n\tclock get the time since execution start in milliseconds\n\tevaluate evaluate a string\n\tsystem execute a system command\n\tclose-file close a file handle\n\topen-file open a file handle\n\tdelete-file delete a file off disk given a string\n\tread-file read in characters from a file\n\twrite-file write characters to a file\n\tfile-position get the file offset\n\treposition-file reposition the file pointer\n\tflush-file flush a file to disk\n\trename-file rename a file on disk\n \"\n\nmore \" All of the other words in the interpreter are built from these\nprimitive words. A few examples:\n\n(1)\tif...else...then FORTH branching construct\n(1)\tbegin...until loop until top of stack is non zero\n(1)\tbegin...again infinite loop\n(1)\tdo...loop FORTH looping construct\n(2,3)\tcreate create a new word that pushes its location\n(1)\tdoes> declare a created words run time behaviour\n(1,2)\tvariable declare variable with initial value from top of stack\n(1,2)\tconstant declare a constant, taken from top of stack\n(1,2)\tarray declare an array with size taken from top of stack\n(1)\t; terminate a word definition and return to command mode\n\twords print out a list of all the defined words\n\thelp this help message\n\tdump print out memory contents starting at an address\n\tregisters print out the contents of the registers\n\tsee decompile a word, viewing what words compose it\n\t.s print out the contents of the stack\n\n\"\n\nmore \" Some more advanced words:\n\n\there push the dictionary pointer\n\th push the address of the dictionary pointer\n\tr push the return stack pointer\n\tallot allocate space in the dictionary\n(1)\t[ switch to command mode\n\t] switch to compile mode\n\t:: compile ':' into the dictionary\n\n\" more \"\nFor more information either consult the manual pages forth(1) and libforth(1)\nor consult the following sources:\n\n\thttps:\/\/github.com\/howerj\/libforth\n\thttp:\/\/work.anapnea.net\/html\/html\/projects.html\n\nAnd for a larger tutorial:\n\n\thttps:\/\/github.com\/howerj\/libforth\/blob\/master\/readme.md\n\nFor resources on Forth:\n\n\thttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\thttps:\/\/rwmj.wordpress.com\/2010\/08\/07\/jonesforth-git-repository\/\n\n -- end --\n\" cr\n;\n\n( ==================== Files ================================== )\n\n( @todo implement the other file access methods in terms of the\n built in ones [see http:\/\/forth.sourceforge.net\/std\/dpans\/dpans11.htm]\n @todo read-line and write-line need their flag and ior setting correctly\n\n\tFILE-SIZE [ use file-positions ]\n\n Also of note:\t\n * Source ID needs extending. )\n\n: read-char ( c-addr fileid -- ior : read a char )\n\t1 swap read-file 0<> swap 1 <> or ;\n\n0 variable x\n\n: getchar ( fileid -- char ior )\n\tx chars> swap read-char x chars> c@ swap ;\n\n: write-char ( c-addr fileid -- ior : write a char )\n\t1 swap write-file 0<> swap 1 <> or ;\n\n: putchar ( char fileid -- ior )\n\tswap x chars> c! x chars> swap write-char ;\n\nhide{ x }hide\n\n: rewind-file ( file-id -- : rewind a file to the beginning )\n\t0 reposition-file throw ;\n\n: read-line ( c-addr u1 fileid -- u2 flag ior : read in a line of text )\n\t-rot bounds\n\tdo\n\t\tdup i swap read-char drop\n\t\ti c@ '\\n' = if drop i 0 0 leave then\n\tloop drop ;\n\n: write-line ( c-addr u fileid -- u2 flag ior : write a line of text )\n\t-rot bounds\n\tdo\n\t\tdup i swap write-char drop\n\t\ti c@ '\\n' = if drop i 0 0 leave then\n\tloop ;\n\n: resize-file ( ud fileid -- ior : attempt to resize a file )\n\t( There is no portable way to truncate a file :C )\n\t2drop -1 ( -1 to indicate failure ) ;\n\n: create-file ( c-addr u fam -- fileid ior )\n\t>r 2dup w\/o open-file throw close-file throw\n\tr> open-file ;\n\n: include-file ( file-id -- : evaluate a file ) \n\tdup >r 0 1 evaluator r> close-file throw throw ;\n\n: included ( c-addr u -- : attempt to open up a name file and evaluate it )\n\tr\/o open-file throw \n\tinclude-file ;\n\n: include ( c\" ccc\" -- : attempt to evaluate a named file )\n\t( @bug requires trailing space, should use parse-name )\n\tbl word count included ;\n\n: bin ( fam1 -- fam2 : modify a file access method to be binary not line oriented ) \n\t( Do nothing, all file access methods are binary )\n\t;\n\n( ==================== Files ================================== )\n\n( ==================== Blocks ================================= )\n( \n0 variable dirty\nb\/buf string buf\n0 variable loaded\n0 variable blk\n0 variable scr\n\n: update 1 dirty ! ;\n: empty-buffers 0 loaded ! ;\n: ?update dup loaded @ <> dirty @ or ;\n: ?invalid dup 0= if empty-buffers -35 throw then ;\n: write dup >r write-file r> close-file throw ;\n: read dup >r read-file r> close-file throw ;\n: name >r <# #s #> rot drop r> create-file throw ; \\ @todo add .blk with holds, also create file deletes file first...\n: update! >r buf r> w\/o name write throw drop empty-buffers ;\n: get >r buf r> r\/o name read throw drop ;\n: block ?invalid ?update if dup update! then dup get loaded ! buf drop ;\n\nhide{ dirty ?update update! loaded name get ?invalid write read }hide\n\n: c \n\t1 block update drop\n\t2 block update drop\n\t3 block update drop\n\t4 block update drop ;\nc )\n\n( ==================== Blocks ================================= )\n\n( ==================== Matcher ================================ )\n( The following section implements a very simple regular expression\nengine, which expects an ASCIIZ Forth string. It is translated from C\ncode and performs an identical function.\n\nThe regular expression language is as follows:\n\n\tc\tmatch a literal character\n\t.\tmatch any character\n\t*\tmatch any characters\n\nThe \"*\" operator performs the same function as \".*\" does in most\nother regular expression engines. Most other regular expression engines\nalso do not anchor their selections to the beginning and the end of\nthe string to match, instead using the operators '^' and '$' to do\nso, to emulate this behavior '*' can be added as either a suffix,\nor a prefix, or both, to the matching expression.\n\nAs an example \"*, World!\" matches both \"Hello, World!\" and\n\"Good bye, cruel World!\". \"Hello, ....\" matches \"Hello, Bill\"\nand \"Hello, Fred\" but not \"Hello, Tim\" as there are two few\ncharacters in the last string.\n\n@todo make a matcher that expects a Forth string, which do not\nhave to be NUL terminated\n)\n\n\\ Translated from http:\/\/c-faq.com\/lib\/regex.html\n\\ int match(char *pat, char *str)\n\\ {\n\\ \tswitch(*pat) {\n\\ \tcase '\\0': return !*str;\n\\ \tcase '*': return match(pat+1, str) || *str && match(pat, str+1);\n\\ \tcase '.': return *str && match(pat+1, str+1);\n\\ \tdefault: return *pat == *str && match(pat+1, str+1);\n\\ \t}\n\\ }\n\n: *pat ( regex -- regex char : grab next character of pattern ) \n\tdup c@ ;\n\n: *str ( string regex -- string regex char : grab next character string to match )\n\tover c@ ;\n\n: pass ( c-addr1 c-addr2 -- bool : pass condition, characters matched ) \n\t2drop 1 ;\n\n: reject ( c-addr1 c-addr2 -- bool : fail condition, character not matched ) \n\t2drop 0 ;\n\n: *pat==*str ( c-addr1 c-addr2 -- c-addr1 c-addr2 bool )\n\t2dup c@ swap c@ = ;\n\n: ++ ( u1 u2 u3 u4 -- u1+u3 u2+u4 : not quite d+ [does no carry] )\n\tswap >r + swap r> + swap ;\n\ndefer matcher\n\n: advance ( string regex char -- bool : advance both regex and string )\n\tif 1 1 ++ matcher else reject then ;\n\n: advance-string ( string regex char -- bool : advance only the string )\n\tif 1 0 ++ matcher else reject then ;\n\n: advance-regex ( string regex -- bool : advance matching )\n\t2dup 0 1 ++ matcher if pass else *str advance-string then ;\n\n: match ( string regex -- bool : match a ASCIIZ pattern against an ASCIIZ string )\n\t( @todo Add limits and accept two Forth strings, making sure they are both\n\t ASCIIZ strings as well \n\t @warning This uses a non-standards compliant version of case! )\n\t*pat\n\tcase\n\t\t 0 of drop drop c@ not exit endof\n\t\t[char] * of drop advance-regex exit endof\n\t\t[char] . of drop *str advance exit endof\n\t\t drop *pat==*str advance exit\n\tendcase ;\n\nmatcher is match\n\nhide{ \n\t*str *pat *pat==*str pass reject advance \n\tadvance-string advance-regex matcher ++ \n}hide\n\n( ==================== Matcher ================================ )\n\n\n( ==================== Cons Cells ============================= )\n\n( From http:\/\/sametwice.com\/cons.fs, this could be improved if the optional\nmemory allocation words were added to the interpreter. This provides\na simple \"cons cell\" data structure. There is currently no way to\nfree allocated cells )\n\n: car! ( value cons-addr -- : store a value in the car cell of a cons cell ) \n\t! ;\n\n: cdr! ( value cons-addr -- : store a value in the cdr cell of a cons cell )\n\tcell+ ! ;\n\n: car@ ( cons-addr -- car-val : retrieve car value from cons cell )\n\t@ ;\n\n: cdr@ ( cons-addr -- cdr-val : retrieve cdr value from cons cell )\n\tcell+ @ ;\n\n: cons ( car-val cdr-val -- cons-addr : allocate a new cons cell )\n\tswap here >r , , r> ;\n\n: cons0 0 0 cons ;\n\nmarker cleanup\n77 987 cons constant x\nT{ x car@ -> 77 }T\nT{ x cdr@ -> 987 }T\nT{ 55 x cdr! x car@ x cdr@ -> 77 55 }T\nT{ 44 x car! x car@ x cdr@ -> 44 55 }T\ncleanup\n\n( ==================== Cons Cells ============================= )\n\n( ==================== Miscellaneous ========================== )\n\n: license ( -- : print out license information )\n\" \nThe MIT License (MIT)\n\nCopyright (c) 2016 Richard James Howe\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the 'Software'),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand\/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\nTHE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\nOTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\nARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE. \n\n\" \n;\n\n( ==================== Version information =================== )\n\n4 constant version\n\n( ==================== Version information =================== )\n\n( ==================== Core utilities ======================== )\n( Read the header of a core file and process it, printing the\nresults out )\n\n8 constant header-size ( size of Forth core file header )\n8 constant size-field-size ( the size in bytes of the size field in the core file )\n0 variable core-file ( core fileid we are reading in )\n0 variable core-cell-size ( cell size of Forth core )\n0 variable core-version ( version of core file )\n0 variable core-endianess ( endianess of core we are reading in )\n\n( save space to read in header )\ncreate header header-size chars allot\n: cheader ( -- c-addr : header char address )\n\theader chars> ;\ncreate size-field size-field-size chars allot\n: csize-field ( -- c-addr : address of place size field is stored in )\n\tsize-field chars> ;\n\n0\nenum header-magic0 ( magic number 0 : FF ) \nenum header-magic1 ( magic number 1 : '4' )\nenum header-magic2 ( magic number 2 : 'T' )\nenum header-magic3 ( magic number 3 : 'H' )\nenum header-cell-size ( size of a forth cell, either 2, 4 or 8 bytes )\nenum header-version ( version of the forth core )\nenum header-endianess ( endianess of the core )\nenum header-log2size ( binary logarithm of the core size )\n\n: cleanup ( -- : cleanup before abort )\n\tcore-file @ ?dup 0<> if close-file drop then ;\n\n: invalid-header ( bool -- : abort if header is invalid )\n\t<> if cleanup abort\" invalid header\" then ;\n\n: save-core-cell-size ( char -- : save the core file cell size, checking if it is valid )\n\tcore-cell-size !\n\t\" cell size:\" tab\n\tcore-cell-size @ 2 = if 2 . cr exit then\n\tcore-cell-size @ 4 = if 4 . cr exit then\n\tcore-cell-size @ 8 = if 8 . cr exit then\n\tcleanup core-cell-size @ . abort\" : invalid cell size\" ;\n\n: check-version-compatibility ( char -- : checks the version compatibility of the core file ) \n\tcore-version !\n\tcore-version @ version = if \" version: \" version . cr exit then\n\tcleanup core-version @ . abort\" : unknown version number\" ;\n\n: save-endianess ( char -- : save the endianess, checking if it is valid )\n\tcore-endianess !\n\t\" endianess:\" tab\n\tcore-endianess @ 0 = if \" big\" cr exit then\n\tcore-endianess @ 1 = if \" little\" cr exit then\n\tcleanup core-endianess @ . abort\" invalid endianess\" then ;\n\n: read-or-abort ( c-addr size fileid -- : )\n\tover >r read-file \n\t 0<> if cleanup abort\" file read failed\" then\n\tr> <> if cleanup abort\" header too small\" then ;\n\n: header? ( -- : print out header information )\n\tcheader header-size core-file @ read-or-abort\n\t( \" raw header:\" header 2 dump )\n\tcheader header-magic0 + c@ 255 invalid-header\n\tcheader header-magic1 + c@ [char] 4 invalid-header\n\tcheader header-magic2 + c@ [char] T invalid-header\n\tcheader header-magic3 + c@ [char] H invalid-header\n\tcheader header-cell-size + c@ save-core-cell-size\n\tcheader header-version + c@ check-version-compatibility\n\tcheader header-endianess + c@ save-endianess\n\t\" valid header\" cr ;\n\n: size? ( -- : print out core file size )\n\t\" size: \" cheader header-log2size + c@ 1 swap lshift . cr ;\n\n: core ( c-addr u -- : analyze a Forth core file from disk given its file name )\n\t2dup \" core file:\" tab type cr\n\tr\/o open-file throw core-file ! \n\theader?\n\tsize?\n\tcore-file @ close-file drop ;\n\n( s\" forth.core\" core )\n\nhide{ \nheader-size header? \nheader-magic0 header-magic1 header-magic2 header-magic3\nheader-version header-cell-size header-endianess header-log2size\nheader \ncore-file save-core-cell-size check-version-compatibility\ncore-cell-size cheader\ncore-endianess core-version save-endianess invalid-header\ncleanup size-field csize-field size-field-size\nread-or-abort size?\n}hide\n\n( ==================== Core utilities ======================== )\n\n( ==================== RLE =================================== )\n\n( These set of words implement Run Length Compression, which can be used for\nsaving space when compressing the core files generated by Forth programs, which\ncontain mostly runs of NUL characters. \n\nThe format of the encoded data is quite simple, there is a command byte\nfollowed by data. The command byte encodes only two commands; encode a run of\nliteral data and repeat the next character. \n\nIf the command byte is greater than X the command is a run of characters, \nX is then subtracted from the command byte and this is the number of \ncharacters that is to be copied verbatim when decompressing.\n\nIf the command byte is less than or equal to X then this number, plus one, is \nused to repeat the next data byte in the input stream.\n\nX is 128 for this application, but could be adjusted for better compression\ndepending on what the data looks like. \n\nExample:\n\t\n\t2 'a' 130 'b' 'c' 3 'd'\n\nBecomes:\n\n\taabcddd \n\nExample usage:\n\n\t: extract\n\t\tc\" forth.core\" w\/o open-file throw\n\t\tc\" forth.core.rle\" r\/o open-file throw\n\t\tdecompress ;\n\textract\n\n@note file redirection could be used for the input as well\n@todo compression, and reading\/writing to strings )\n\n: cpad pad chars> ;\n\n0 variable out\n128 constant run-length\n\n: more ( file-id -- char : read in a single character )\n\t>r cpad r> read-char throw cpad c@ ;\n\n: repeated ( count file-id -- : repeat a character count times )\n\tmore swap 0 do dup emit loop drop ;\n\n: literals ( count file-id -- : extract a literal run )\n\t>r cpad swap r> read-file throw cpad swap type ;\n\n: command ( file-id -- : process an RLE command )\n\tdup \n\t>r more \n\tdup run-length u> \n\tif \n\t\trun-length - r> literals \n\telse \n\t\t1+ r> repeated \n\tthen ;\n\n: redirect ( file-id-out -- : save current output pointer, redirect to output )\n\t`fout @ out ! `fout ! ;\n\n: restore ( -- : restore previous output pointer )\n\tout @ `fout ! ;\n\n: decompress ( file-id-out file-id-in -- : decompress an RLE encoded file )\n\tswap\n\tredirect\n\tbegin dup ' command catch until ( process commands until input exhausted )\n\t2drop ( drop twice because catch will restore stack before 'command' )\n\trestore ; ( restore input stream )\n\nhide{ literals repeated more out run-length command }hide\n\n( ==================== RLE =================================== )\n\n( ==================== Generate C Core file ================== )\n( The word core2c reads in a core file and turns it into a C file which \ncan then be compiled into the forth interpreter in a bootstrapping like\nprocess.\n\nUsage:\n c\" forth.core\" c\" core.gen.c\" core2c )\n\n0 variable count\n\n: wbyte ( u char -- : write a byte )\n\tpnum drop\n\t[char] , emit\n\t16 mod 0= if cr then ;\n\n: advance ( char -- : advance counter and print byte )\n\tcount 1+! count @ swap wbyte ;\n\n: hexify ( fileid -- fileid : turn core file into C numbers in array )\n\t0 count !\n\tbegin dup getchar 0= while advance repeat drop ;\n\n: quote ( -- : emit a quote character )\n\t[char] \" emit ;\n\n: core2c ( c-addr u c-addr u -- ior : generate a C file from a core file )\n\tw\/o open-file throw >r\n\tr\/o open-file ?dup-if r> close-file throw throw then\n\tr> redirect\n\t\" #include \" quote \" libforth.h\" quote cr\n\t\" unsigned char forth_core_data[] = {\" cr\n\thexify \n\t\" };\" cr\n\t\" forth_cell_t forth_core_size = \" count @ . \" ;\" cr cr\n\tclose-file\n\t`fout @ close-file \n\trestore or ;\n\nhide{ wbyte hexify count quote advance }hide\n \n( ==================== Generate C Core file ================== )\n\n: wc ( c-addr u -- u : count the bytes in a file )\n\tr\/o open-file throw\n\t0 swap\n\tbegin dup getchar nip 0= while nos1+ repeat close-file throw ;\n\n( ==================== Save Core file ======================== )\n\n( The following functionality allows the user to save the core file\nfrom within the running interpreter. The Forth core files have a very simple\nformat which means the words for doing this do not have to be too long, a header\nhas to emitted with a few calculated values and then the contents of the\nForths memory after this )\n\n( This write the header out to the current output device, this\nwill be redirected to a file )\n: header ( -- : write the header out )\n\t0xff emit ( magic 0 )\n\t[char] 4 emit ( magic 1 )\n\t[char] T emit ( magic 2 )\n\t[char] H emit ( magic 3 )\n\tsize emit ( cell size in bytes )\n\tversion emit ( core version )\n\tendian not emit ( endianess )\n\tmax-core log2 emit ; ( size field )\n\n: data ( -- : write the data out )\n\t0 max-core chars> `fout @ write-file throw drop ;\n\n: encore ( -- : write the core file out )\n\theader\n\tdata ;\n\n: save-core ( c-addr u -- : save core file or throw error ) \n\tw\/o open-file throw dup\n\tredirect \n\t\t' encore catch swap close-file throw \n\trestore ;\n\n( The following code illustrates an example of setting up a\nForth core file to execute a word when the core file is loaded.\nIn the example the word \"hello-world\" will be executed, which will\nalso quit the interpreter:\n\n\t\\ Only works for immediate words for now, we define\n\t\\ the word we wish to be executed when the forth core\n\t\\ is loaded\n\t: hello-world immediate\n\t\t\" Hello, World!\" cr bye ;\n\n\t\\ The following sets the starting word to our newly\n\t\\ defined word:\n\tfind hello-world cfa start!\n\n\t\\ Now we can save the core file out:\n\ts\" forth.core\" save-core \n\nThis can be used, in conjunction with aspects of the build system,\nto produce a standalone executable that will run only a single Forth\nword. )\n\nhide{ redirect restore data encore header }hide\n\n( ==================== Save Core file ======================== )\n\n( ==================== Hex dump ============================== )\n\n( @todo hexdump can read in too many characters and it does not\nprint out the correct address\n@todo utilities for easy redirecting of file input\/output )\n: input >r cpad 128 r> read-file ; ( file-id -- u 0 | error )\n: clean cpad 128 0 fill ; ( -- )\n: cdump cpad chars swap aligned chars dump ; ( u -- )\n: hexdump ( file-id -- : [hex]dump a file to the screen )\n\tdup \n\tclean\n\tinput if 2drop exit then\n\t?dup-if cdump else drop exit then\n\ttail ; \n\nhide{ more cpad clean cdump input }hide\n\n( ==================== Hex dump ============================== )\n\n( ==================== Date ================================== )\n\n( Rather annoyingly months are start from 1 but weekdays from 0 )\n\n: >month ( month -- )\n\tcase\n\t\t 1 of \" Jan \" endof\n\t\t 2 of \" Feb \" endof\n\t\t 3 of \" Mar \" endof\n\t\t 4 of \" Apr \" endof\n\t\t 5 of \" May \" endof\n\t\t 6 of \" Jun \" endof\n\t\t 7 of \" Jul \" endof\n\t\t 8 of \" Aug \" endof\n\t\t 9 of \" Sep \" endof\n\t\t10 of \" Oct \" endof\n\t\t11 of \" Nov \" endof\n\t\t12 of \" Dec \" endof\n\tendcase drop ;\n\n: .day ( day -- : add ordinal to day )\n\t10 mod\n\tcase\n\t\t1 of \" st \" drop exit endof\n\t\t2 of \" nd \" drop exit endof\n\t\t3 of \" rd \" drop exit endof\n\t\t\" th \" \n\tendcase drop ;\n\n: >day ( day -- : add ordinal to day of month )\n\tdup u.\n\tdup 1 10 within if .day exit then\n\tdup 10 20 within if \" th\" drop exit then\n\t.day ;\n\n: >weekday ( weekday -- : print the weekday )\n\tcase\n\t\t0 of \" Sun \" endof\n\t\t1 of \" Mon \" endof\n\t\t2 of \" Tue \" endof\n\t\t3 of \" Wed \" endof\n\t\t4 of \" Thu \" endof\n\t\t5 of \" Fri \" endof\n\t\t6 of \" Sat \" endof\n\tendcase drop ;\n\n: padded ( u -- : print out a run of zero characters )\n\t0 do [char] 0 emit loop ;\n\n: 0u. ( u -- : print a zero padded number )\n\tdup 10 u< if 1 padded then u. space ;\n\n: .date ( date -- : print the date )\n\tif \" DST \" else \" GMT \" then \n\tdrop ( no need for days of year)\n\t>weekday\n\t. ( year ) \n\t>month \n\t>day \n\t0u. ( hour )\n\t0u. ( minute )\n\t0u. ( second ) cr ;\n\n: time&date ( -- second minute hour day month year )\n\tdate\n\t3drop ;\n\nhide{ 0u. >weekday .day >day >month padded }hide\n\n( ==================== Date ================================== )\n\n( Looking at most Forths dictionary with \"words\" command they tend\nto have a lot of words that do not mean anything but to the implementers\nof that specific Forth, here we clean up as many non standard words as\npossible. )\nhide{ \n do-string ')' alignment-bits \n compile-instruction dictionary-start hidden? hidden-mask instruction-mask\n max-core dolist x x! x@ write-exit\n max-string-length \n original-exit\n pnum evaluator \n TrueFalse >instruction print-header\n print-name print-start print-previous print-immediate\n print-instruction xt-instruction defined-word? print-defined\n `state\n `source-id `sin `sidx `slen `start-address `fin `fout `stdin\n `stdout `stderr `argc `argv `debug `invalid `top `instruction\n `stack-size `error-handler `x `y `handler _emit\n}hide\n\n( \n## Forth To List\n\nThe following is a To-Do list for the Forth code itself, along with any\nother ideas.\n\n* FORTH, VOCABULARY\n* \"Value\", \"To\", \"Is\"\n* Double cell words and floating point library\n* The interpreter should use character based addresses, instead of\nword based, and use values that are actual valid pointers, this\nwill allow easier interaction with the world outside the virtual machine\n* common words and actions should be factored out to simplify\ndefinitions of other words, their standards compliant version found\nif any\n* Allow the processing of argc and argv, the mechanism by which that\nthis can be achieved needs to be worked out. However all processing that\nis currently done in \"main.c\" should be done within the Forth interpreter\ninstead.\n* A built in version of \"dump\" and \"words\" should be added to the Forth\nstarting vocabulary, simplified versions that can be hidden.\n* Here documents, string literals. Examples of these can be found online\nat Rosetta Code, although the Forth versions online will need adapting.\n* Document the words in this file and built in words better, also turn this\ndocument into a literate Forth file.\n* Sort out \"'\", \"[']\", \"find\", \"compile,\" \n* Proper booleans should be used throughout, that is -1 is true, and 0 is\nfalse.\n* File operation primitives that close the file stream [and possibly restore\nI\/O to stdin\/stdout] if an error occurs, and then re-throws, should be made.\n* Implement as many things from http:\/\/lars.nocrew.org\/forth2012\/implement.html\nas is sensible. \n* CASE Statements http:\/\/dxforth.netbay.com.au\/miser.html\n* The current words that implement I\/O redirection need to be improved, and documented,\nI think this is quite a useful and powerful mechanism to use within Forth that simplifies\nprograms. This is a must and will make writing utilities in Forth a *lot* easier \n)\n\n( \nThe following will not work as we might actually be reading from a string [`sin]\nnot `fin. \n: key 32 chars> 1 `fin @ read-file drop 0 = if 0 else 32 chars> c@ then ; )\n\nverbose [if] \n\t.( FORTH: libforth successfully loaded.) cr\n\t.( Type 'help' and press return for a basic introduction.) cr\n\t.( Core: ) here . \" \/ \" here unused + . cr\n\t \n\t.( The MIT License ) cr\n\t.( ) cr\n\t.( Copyright 2016 Richard James Howe) cr\n\t.( ) cr\n\t.( Permission is hereby granted, free of charge, to any person obtaining a) cr\n\t.( copy of this software and associated documentation files [the \"Software\"],) cr\n\t.( to deal in the Software without restriction, including without limitation) cr\n\t.( the rights to use, copy, modify, merge, publish, distribute, sublicense,) cr\n\t.( and\/or sell copies of the Software, and to permit persons to whom the) cr\n\t.( Software is furnished to do so, subject to the following conditions:) cr\n\t.( ) cr\n\t.( The above copyright notice and this permission notice shall be included) cr\n\t.( in all copies or substantial portions of the Software.) cr\n\t.( ) cr\n\t.( THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR) cr\n\t.( IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,) cr\n\t.( FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL) cr\n\t.( THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR) cr\n\t.( OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,) cr\n\t.( ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR) cr\n\t.( OTHER DEALINGS IN THE SOFTWARE. ) cr\n[then]\n\n( \\ integrate simple 'dump' and 'words' into initial forth program \n: nl dup 3 and not ;\n: ?? \\ addr1 \n nl if dup cr . [char] : emit space then ? ;\n: dump \\ addr n --\n\tbase @ >r hex over + swap 1- begin 1+ 2dup dup ?? 2+ u< until r> base ! ; )\n\n\n\n","old_contents":"#!.\/forth \n( ==================================================================== )\n( ==================================================================== )\n( ==================================================================== )\n( \n\tTHIS CODE IS CURRENTLY NON FUNCTIONAL\n\tTHIS CODE IS CURRENTLY NON FUNCTIONAL\n\tTHIS CODE IS CURRENTLY NON FUNCTIONAL\n\tTHIS CODE IS CURRENTLY NON FUNCTIONAL\n\tTHIS CODE IS CURRENTLY NON FUNCTIONAL\n\n\tThis is due to a large change in the interpreter, it will\n\ttake time to fix this, however it will be an improvement.\n)\n( ==================================================================== )\n( ==================================================================== )\n( ==================================================================== )\n( ==================================================================== )\n( \nWelcome to libforth, A dialect of Forth. Like all versions of Forth this\nversion is a little idiosyncratic, but how the interpreter works is\ndocumented here and in various other files.\n\nThis file contains most of the start up code, some basic start up code\nis executed in the C file as well which makes programming at least bearable.\nMost of Forth is programmed in itself, which may seem odd if your back\nground in programming comes from more traditional language [such as C],\nalthough less so if you know already know lisp.\n\nFor more information about this interpreter and Forth see:\n\thttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\treadme.md : for a manual for this interpreter\n\tlibforth.h : for information about the C API\n\tlibforth.c : for the interpreter itself\n\tunit.c : a series of unit tests against libforth.c\n\tunit.fth : a series of unit tests against this file\n\nThe interpreter and this code originally descend from a Forth interpreter\nwritten in 1992 for the International obfuscated C Coding Competition\n\nSee:\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\nThe manual for the interpreter should be read first before looking into this\ncode. It is important to understand the execution model of Forth, especially\nthe differences between command and compile mode, and how immediate and compiling\nwords work.\n\nThe structure of this file is as follows:\n\n * Basic Word Set\n * Extended Word Set\n * CREATE DOES>\n * DO...LOOP\n * CASE statements\n * Conditional Compilation\n * Endian Words\n * Misc words\n * Random Numbers\n * ANSI Escape Codes\n * Prime Numbers\n * Debugging info\n * Files\n * Blocks\n * Matcher\n * Cons Cells\n * Miscellaneous\n * Core utilities\n\nEach of these sections is clearly labeled and they are generally in dependency order.\n\nUnfortunately the code in this file is not as portable as it could be, it makes\nassumptions about the size of cells provided by the virtual machine, which will\ntake time to rectify. Some of the constructs are subtly different from the\nDPANs Forth specification, which is usually noted. Eventually this should\nalso be fixed.)\n\n( ========================== Basic Word Set ================================== )\n\n( \nWe'll begin by defining very simple words we can use later, these a very\nbasic words, that perform simple tasks, they will not require much explanation.\n\nEven though the words are simple, their stack comment and a description for\nthem will still be included so external tools can process and automatically\nextract the document string for a given work.\n)\n\n: 1+ ( x -- x : increment a number ) \n\t1 + ;\n\n: 1- ( x -- x : decrement a number ) \n\t1 - ;\n\n: chars ( c-addr -- addr : convert a character address to an address )\n\tsize \/ ; \n\n: chars> ( addr -- c-addr: convert an address to a character address )\n\tsize * ; \n\n: tab ( -- : print a tab character to current output device )\n\t9 emit ;\n\n: 0= ( x -- bool : is 'x' equal to zero? )\n\t0 = ;\n\n: not ( x -- bool : is 'x' true? )\n\t0= ;\n\n: <> ( x x -- bool : not equal )\n\t= 0= ;\n\n: logical ( x -- bool : turn a value into a boolean ) \n\tnot not ;\n\n: :: ( -- : compiling version of ':' )\n\t[ find : , ] ;\n\n: '\\n' ( -- n : push the newline character )\n\t10 ;\n\n: cr ( -- : emit a newline character )\n\t'\\n' emit ;\n\n: hidden-mask ( -- x : pushes mask for the hide bit in a words MISC field )\n\t0x80 ;\n\n: instruction-mask ( -- x : pushes mask for the first code word in a words MISC field )\n\t0x1f ;\n\n: hidden? ( PWD -- PWD bool : is a word hidden, given the words PWD field ) \n\tdup 1+ @ hidden-mask and logical ;\n\n: compile-instruction ( -- instruction : compile code word, threaded code interpreter instruction )\n\t1 ; \n\n: dolist ( -- x : run code word, threaded code interpreter instruction )\n\t2 ; \n\n: dolit ( -- x : location of special \"push\" word )\n\t2 ;\n\n: 2, ( x x -- : write two values into the dictionary )\n\t, , ;\n\n: [literal] ( x -- : write a literal into the dictionary )\n\tdolit 2, ; \n\n: literal ( x -- : immediately write a literal into the dictionary )\n\timmediate [literal] ;\n\n: sliteral immediate ( I: c-addr u --, Run: -- c-addr u )\n\tswap [literal] [literal] ;\n\n( space saving measure )\n-1 : -1 literal ;\n 0 : 0 literal ;\n 1 : 1 literal ;\n 2 : 2 literal ;\n 3 : 3 literal ;\n\n: min-signed-integer ( -- x : push the minimum signed integer value )\n\t[ -1 -1 1 rshift invert and ] literal ;\n\n: max-signed-integer ( -- x : push the maximum signed integer value )\n\t[ min-signed-integer invert ] literal ;\n\n: < ( x1 x2 -- bool : signed less than comparison )\n\t- dup if max-signed-integer u> else logical then ;\n\n: > ( x1 x2 -- bool : signed greater than comparison )\n\t- dup if max-signed-integer u< else logical then ;\n\n: 2literal immediate ( x x -- : immediate write two literals into the dictionary )\n\tswap [literal] [literal] ;\n\n: latest ( get latest defined word )\n\tpwd @ ; \n\n: stdin ( -- fileid : push the fileid for the standard input channel ) \n\t`stdin @ ;\n\n: stdout ( -- fileid : push the fileid for the standard output channel ) \n\t`stdout @ ;\n\n: stderr ( -- fileid : push the fileid for the standard error channel ) \n\t`stderr @ ;\n\n: stdin? ( -- bool : are we reading from standard input )\n\t`fin @ stdin = ;\n\n: false ( -- x : push the value representing false )\n\t0 ;\n\n: true ( -- x : push the value representing true )\n\t-1 ;\n\n: *+ ( x1 x2 x3 -- x ) \n\t* + ;\n\t\n: 2- ( x -- x : decrement by two )\n\t2 - ( x -- x ) ;\n\n: 2+ ( x -- x : increment by two )\n\t2 + ( x -- x ) ;\n\n: 3+ ( x -- x : increment by three )\n\t3 + ( x -- x ) ;\n\n: 2* ( x -- x : multiply by two )\n\t1 lshift ( x -- x ) ;\n\n: 2\/ ( x -- x : divide by two )\n\t1 rshift ( x -- x ) ;\n\n: 4* ( x -- x : multiply by four )\n\t2 lshift ( x -- x ) ;\n\n: 4\/ ( x -- x : divide by four )\n\t2 rshift ( x -- x ) ;\n\n: 8* ( x -- x : multiply by eight )\n\t3 lshift ( x -- x ) ;\n\n: 8\/ ( x -- x : divide by eight )\n\t3 rshift ( x -- x ) ;\n\n: 256* ( x -- x : multiply by 256 )\n\t8 lshift ( x -- x ) ;\n\n: 256\/ ( x -- x : divide by 256 )\n\t8 rshift ( x -- x ) ;\n\n: 2dup ( x1 x2 -- x1 x2 x1 x2 : duplicate two values )\n\tover over ;\n\n: mod ( x u -- x : calculate the remainder of x divided by u ) \n\t2dup \/ * - ;\n\n( @todo implement um\/mod in the VM, then use this to implement \/ and mod )\n: um\/mod ( x1 x2 -- rem quot : calculate the remainder and quotient of x1 divided by x2 ) \n\t2dup \/ >r mod r> ;\n\n: *\/ ( x1 x2 x3 -- x4 : multiply then divide, @warning this does not use a double cell for the multiply )\n\t * \/ ; \n\n: char ( -- x : read in a character from the input steam )\n\tkey drop key ;\n\n: [char] ( -- x : immediately read in a character from the input stream )\n\timmediate char [literal] ;\n\n: postpone ( -- : postpone execution of the following immediate word )\n\timmediate find , ;\n\n: compose ( xt1 xt2 -- xt3 : create a new function from two xt-tokens )\n\t>r >r ( save execution tokens )\n\tpostpone :noname ( )\n\tr> , ( write first token )\n\tr> , ( write second token )\n\tpostpone ; ; ( terminate new :noname )\n\n: unless ( bool -- : like 'if' but execute clause if false )\n\timmediate ' 0= , postpone if ;\n\n: endif ( synonym for 'then' ) \n\timmediate postpone then ;\n\n: cell+ ( a-addr1 -- a-addr2 ) \n\t1+ ;\n\n: cells ( n1 -- n2 ) \n\timmediate ;\n\n: cell ( -- u : defined as 1 cells )\n\t1 cells ;\n\n: address-unit-bits ( -- x : push the number of bits in an address )\n\t[ cell size 8* * ] literal ;\n\n: negative? ( x -- bool : is a number negative? )\n\t[ 1 address-unit-bits 1- lshift ] literal and logical ;\n\n: mask-byte ( x -- x : generate mask byte ) \n\t8* 255 swap lshift ;\n\n: select-byte ( u i -- c ) \n\t8* rshift 0xff and ;\n\n: char+ ( c-addr -- c-addr : increment a character address by the size of one character ) \n\t1+ ;\n\n: 2chars ( c-addr1 c-addr2 -- addr addr : convert two character addresses to two cell addresses ) \n\tchars swap chars swap ;\n\n: 2chars> ( addr addr -- c-addr c-addr: convert two cell addresses to two character addresses )\n\tchars> swap chars> swap ;\n\n: hex ( -- : print out hex ) \n\t16 base ! ;\n\n: octal ( -- : print out octal ) \n\t8 base ! ;\n\n: binary ( -- : print out binary ) \n\t2 base ! ;\n\n: decimal ( -- : print out decimal ) \n\t0 base ! ;\n\n: negate ( x -- x ) \n\t-1 * ;\n\n: abs ( x -- u : return the absolute value of a number )\n\tdup negative? if negate then ;\n\n: square ( x -- x ) \n\tdup * ;\n\n: sum-of-squares ( a b -- c : compute a^2 + b^2 to get c )\n\tsquare swap square + ;\n\n: drup ( x y -- x x ) \n\tdrop dup ;\n\n: +! ( x addr -- : add x to a value stored at addr ) \n\ttuck @ + swap ! ;\n\n: 1+! ( addr -- : increment a value at an address ) \n\t1 swap +! ;\n\n: 1-! ( addr -- : decrement a value at an address ) \n\t-1 swap +! ;\n\n: toggle ( addr u -- : complement the value at address with the bit pattern u ) \n\tover @ xor swap ! ;\n\n: lsb ( x -- x : mask off the least significant byte of a cell ) \n\t255 and ;\n\n: \\ ( -- : immediate word, used for single line comments )\n\timmediate begin key '\\n' = until ;\n\n: ?dup ( x -- ? ) \n\tdup if dup then ;\n\n: min ( x y -- min : return the minimum of two integers ) \n\t2dup < if drop else swap drop then ;\n\n: max ( x y -- max : return the maximum of two integers ) \n\t2dup > if drop else swap drop then ;\n\n: limit ( x min max -- x : limit x with a minimum and maximum )\n\trot min max ;\n\n: >= ( x y -- bool ) \n\t< not ;\n\n: <= ( x y -- bool ) \n\t> not ;\n\n: 2@ ( a-addr -- x1 x2 : load two consecutive memory cells )\n\tdup 1+ @ swap @ ;\n\n: 2! ( x1 x2 a-addr -- : store two values as two consecutive memory cells )\n\t2dup ! nip 1+ ! ;\n\n: r@ ( -- x, R: x -- )\n\tr> r @ swap >r ;\n\n: rp@ ( -- x, R: x -- )\n\tr> r @ swap >r ;\n\n( @todo r!, rp! )\n\n: 0> ( x -- bool )\n\t0 > ;\n\n: 0< ( x -- bool )\n\t0 < ;\n\n: 0<> ( x -- bool )\n\t0 <> ;\n\n: signum ( x -- -1 | 0 | 1 : )\n\tdup 0< if drop -1 exit then\n\t 0> if 1 exit then\n\t0 ;\n\n: nand ( x x -- x : bitwise NAND ) \n\tand invert ;\n\n: odd ( x -- bool : is 'x' odd? )\n\t1 and ;\n\n: even ( x -- bool : is 'x' even? )\n\todd not ;\n\n: nor ( x x -- x : bitwise NOR ) \n\tor invert ;\n\n: ms ( u -- : wait at least 'u' milliseconds ) \n\tclock + begin dup clock u< until drop ;\n\n: sleep ( u -- : sleep for 'u' seconds )\n\t1000 * ms ;\n\n: align ( addr -- addr : align an address, nop in this implemented )\n\timmediate ; \n\n: ) ( -- : do nothing, this allows easy commenting out of code )\n\timmediate ;\n\n: bell ( -- : emit an ASCII BEL character ) \n\t7 emit ;\n\n: b\/buf ( -- u : bytes per buffer ) \n\t1024 ;\n\n: .d ( x -- x : debug print ) \n\tdup . ;\n\n: compile, ( x -- : )\n\t, ;\n\n: >mark ( -- : write a hole into the dictionary and push a pointer to it ) \n\there 0 , ;\n\n: r - r> u< ;\n\n: invalidate ( -- : invalidate this Forth core )\n\t1 `invalid ! ;\n\n: signed ( x -- bool : return true if sign bit set ) \n\t[ 1 size 8 * 1- lshift ] literal and logical ;\n\n: u>= ( x y -- bool : unsigned greater than or equal to )\n\t2dup u> >r = r> or ;\n\n: u<= ( x y -- bool : unsigned less than or equal to )\n\tu>= not ;\n: rdrop ( R: x -- : drop a value from the return stack )\n\tr> ( get caller's return address )\n\tr> ( get value to drop )\n\tdrop ( drop it like it's hot )\n\t>r ; ( return return address )\n\n: rdup\n\tr> ( get caller's return address )\n\tr> ( get value to duplicate )\n\tdup ( ... )\n\t>r >r >r ; ( make it all work )\n\n: again immediate\n\t( loop unconditionally in a begin-loop:\n\t\tbegin ... again )\n\t' branch , ;\n\n: source ( -- c-addr u )\n\t#tib ( size of input buffer, in characters )\n\ttib ; ( start of input buffer, in characters )\n\n: stdin?\n\t`fin @ `stdin @ = ;\n\n: source-id ( -- 0 | -1 | file-id )\n\t( \t\n\tValue Input Source\n\t-1 String\n\t0 Reading from user input \/ standard in\n\tfile-id )\n\t`source-id @ \n\t0= if\n\t\tstdin? if 0 else `fin @ then\n\telse\n\t\t-1\n\tthen ;\n\n: under ( x1 x2 -- x1 x1 x2 )\n\t>r dup r> ;\n\n: 2nip ( n1 n2 n3 n4 -- n3 n4 ) \n\t>r >r 2drop r> r> ;\n\n: 2over ( n1 n2 n3 n4 \u2013 n1 n2 n3 n4 n1 n2 )\n\t>r >r 2dup r> swap >r swap r> r> -rot ;\n\n: 2swap ( n1 n2 n3 n4 \u2013 n3 n4 n1 n2 )\n\t>r -rot r> -rot ;\n\n: 2tuck ( n1 n2 n3 n4 \u2013 n3 n4 n1 n2 n3 n4 )\n\t2swap 2over ;\n\n: nos1+ ( x1 x2 -- x1+1 x2 : increment the next variable on that stack )\n\tswap 1+ swap ;\n\n: ?dup-if immediate ( x -- x | - : ?dup and if rolled into one! )\n\t' ?dup , postpone if ;\n\n: ?if ( -- : non destructive if ) \n\timmediate ' dup , postpone if ;\n\n: hide ( token -- hide-token : this hides a word from being found by the interpreter )\n\t?dup-if\n\t\tdup @ hidden-mask or swap tuck ! exit\n\tthen 0 ;\n\n: hider ( WORD -- : hide with drop ) \n\tfind dup if hide then drop ;\n\n: reveal ( hide-token -- : reveal a hidden word ) \n\tdup @ hidden-mask invert and swap ! ;\n\n: original-exit \n\t[ find exit ] literal ;\n\n: exit\n\t( this will define a second version of exit, ';' will\n\tuse the original version, whilst everything else will\n\tuse this version, allowing us to distinguish between\n\tthe end of a word definition and an early exit by other\n\tmeans in \"see\" )\n\t[ find exit hide ] rdrop exit [ reveal ] ;\n\n: ?exit ( x -- : exit current definition if not zero ) \n\tif rdrop exit then ;\n\n: number? ( c -- f : is character a number? )\n\t[char] 0 [ char 9 1+ ] literal within ;\n\n: lowercase? ( c -- f : is character lower case? )\n\t[char] a [ char z 1+ ] literal within ;\n\n: uppercase? ( C -- f : is character upper case? )\n\t[char] A [ char Z 1+ ] literal within ;\n\n: alpha? ( C -- f : is character part of the alphabet? )\n\tdup lowercase? swap uppercase? or ;\n\n: alphanumeric? ( C -- f : is character alphabetic or a number ? )\n\tdup alpha? swap number? or ;\n\n: printable? ( c -- bool : is printable, excluding new lines and tables )\n\t32 127 within ;\n\n: >upper ( c -- C : convert char to uppercase iff lower case )\n\tdup lowercase? if bl xor then ;\n\n: >lower ( C -- c : convert char to lowercase iff upper case )\n\tdup uppercase? if bl xor then ;\n\n: <=> ( x y -- z : spaceship operator! )\n\t2dup\n\t> if 2drop -1 exit then\n\t< ;\n\n: start-address ( -- c-addr : push the start address )\n\t`start-address @ ;\n\n: >real-address ( c-addr -- c-addr : convert an interpreter address to a real address )\n\tstart-address - ;\n\n: real-address> ( c-addr -- c-addr : convert a real address to an interpreter address )\n\tstart-address + ;\n\n: peek ( c-addr -- char : peek at real memory )\n\t>real-address c@ ;\n\n: poke ( char c-addr -- : poke a real memory address )\n\t>real-address c! ;\n\n: die! ( x -- : controls actions when encountering certain errors )\n\t`error-handler ! ;\n\n: start! ( cfa -- : set the word to execute at startup )\n\t`instruction ! ;\t\n\n: warm ( -- : restart the interpreter, warm restart )\n\t1 restart ;\n\n: trip ( x -- x x x : triplicate a number ) \n\tdup dup ;\n\n: roll ( xu xu-1 ... x0 u -- xu-1 ... x0 xu : move u+1 items on the top of the stack by u )\n\tdup 0 >\n\tif\n\t\tswap >r 1- roll r> swap\n\telse\n\t\tdrop\n\tthen ;\n\n: 2rot ( n1 n2 n3 n4 n5 n6 \u2013 n3 n4 n5 n6 n1 n2 )\n\t5 roll 5 roll ;\n\n: s>d ( x -- d : convert a signed value to a double width cell )\n\t( @note the if...else...then is only necessary as this Forths\n\tbooleans are 0 and 1, not 0 and -1 as it usually is )\n\tdup 0< if -1 else 0 then ;\n\n: trace ( level -- : set tracing level )\n\t`debug ! ;\n\n: verbose ( -- : get the log level )\n\t`debug @ ;\n\n: #pad ( -- u : offset into pad area )\n\t64 ;\n\n: pad\n\t( the pad is used for temporary storage, and moves\n\talong with dictionary pointer, always in front of it )\n\there #pad + ;\n\n: count ( c-addr1 -- c-addr2 u : get a string whose first char is its length )\n\tdup c@ nos1+ ;\n\n: bounds ( x y -- y+x x : make an upper and lower bound )\n\tover + swap ;\n\n: aligned ( unaligned -- aligned : align a pointer )\n\t[ size 1- ] literal + \n\t[ size 1- ] literal invert and ;\n\n: cfa ( previous-word-address -- cfa )\n\t( Given the address of the PWD field of a word this\n\tfunction will return an execution token for the word )\n\t ( MISC field ) ;\n\n: >body ( xt -- a-addr : a-addr is data field of a CREATEd word )\n\tcfa 5 + ;\n\n( @todo non-compliant, fix )\n: ['] immediate find cfa [literal] ;\n\n: execute ( xt -- : given an execution token, execute the word )\n\t( create a word that pushes the address of a hole to write to\n\ta literal takes up two words, '!' takes up one, that's right,\n\tsome self modifying code! )\n\t1- ( execution token expects pointer to PWD field, it does not\n\t\tcare about that field however, and increments past it )\n\tcfa\n\t[ here 3+ literal ] ( calculate place to write to )\n\t! ( write an execution token to a hole )\n\t[ 0 , ] ; ( this is the hole we write )\n\n( See: http:\/\/lars.nocrew.org\/dpans\/dpans9.htm\n Code Reserved for\n ---- ------------\n -1 ABORT\n -2 ABORT\"\n -3 stack overflow\n -4 stack underflow\n -5 return stack overflow\n -6 return stack underflow\n -7 do-loops nested too deeply during execution\n -8 dictionary overflow\n -9 invalid memory address\n -10 division by zero\n -11 result out of range\n -12 argument type mismatch\n -13 undefined word\n -14 interpreting a compile-only word\n -15 invalid FORGET\n -16 attempt to use zero-length string as a name\n -17 pictured numeric output string overflow\n -18 parsed string overflow\n -19 definition name too long\n -20 write to a read-only location\n -21 unsupported operation [e.g., AT-XY on a\n too-dumb terminal]\n -22 control structure mismatch\n -23 address alignment exception\n -24 invalid numeric argument\n -25 return stack imbalance\n -26 loop parameters unavailable\n -27 invalid recursion\n -28 user interrupt\n -29 compiler nesting\n -30 obsolescent feature\n -31 >BODY used on non-CREATEd definition\n -32 invalid name argument [e.g., TO xxx]\n -33 block read exception\n -34 block write exception\n -35 invalid block number\n -36 invalid file position\n -37 file I\/O exception\n -38 non-existent file\n -39 unexpected end of file\n -40 invalid BASE for floating point conversion\n -41 loss of precision\n -42 floating-point divide by zero\n -43 floating-point result out of range\n -44 floating-point stack overflow\n -45 floating-point stack underflow\n -46 floating-point invalid argument\n -47 compilation word list deleted\n -48 invalid POSTPONE\n -49 search-order overflow\n -50 search-order underflow\n -51 compilation word list changed\n -52 control-flow stack overflow\n -53 exception stack overflow\n -54 floating-point underflow\n -55 floating-point unidentified fault\n -56 QUIT\n -57 exception in sending or receiving a character\n -58 [IF], [ELSE], or [THEN] exception )\n\n( @todo integrate catch\/throw into the interpreter as primitives )\n: catch ( xt -- exception# | 0 : return addr on stack )\n\tsp@ >r ( xt : save data stack pointer )\n\t`handler @ >r ( xt : and previous handler )\n\tr@ `handler ! ( xt : set current handler )\n\texecute ( execute returns if no throw )\n\tr> `handler ! ( restore previous handler )\n\tr> drop ( discard saved stack ptr )\n\t0 ; ( 0 : normal completion )\n\n( @todo use this everywhere )\n: throw ( ??? exception# -- ??? exception# )\n\t?dup-if ( exc# \\ 0 throw is no-op )\n\t\t`handler @ r ! ( exc# : restore prev return stack )\n\t\tr> `handler ! ( exc# : restore prev handler )\n\t\tr> swap >r ( saved-sp : exc# on return stack )\n\t\tsp! drop r> ( exc# : restore stack )\n\t\t( return to the caller of catch because return )\n\t\t( stack is restored to the state that existed )\n\t\t( when catch began execution )\n\tthen ; \n\n( @bug replacing \"drop drop\" with \"2drop\" causes a stack underflow in\n\"T{\" on a 32-bit platform, \"2drop\" can be used, but only if 3drop is defined\nafter \"interpret\" - something is ever so subtly going wrong. The code fails\nin \"T{\" when \"evaluate\" is called - which does lots of magic in the virtual\nmachine. This is the kind of bug that is difficult to find and reproduce, I\nhave not given up on it yet, however I am going to apply the \"fix\" for now,\nwhich is to change the definitions of 3drop to \"drop drop drop\"... for future\nreference the bug is present in git commit ccd802f9b6151da4c213465a72dacb1f7c22b0ac )\n\n: 3drop ( x1 x2 x3 -- )\n\tdrop drop drop ;\n\n\n: interpret \n\tbegin \n\t' read catch \n\t?dup-if [char] ! emit tab . cr then ( exception handler of last resort )\n\tagain ;\n\n: [interpret] \n\timmediate interpret ;\n\n( ============================================================================= )\n( WORKS UP TO HERE )\n( WORKS UP TO HERE )\n( WORKS UP TO HERE )\n( WORKS UP TO HERE )\n( WORKS UP TO HERE )\n( NB. It does not crash that is, previously defined words might be incorrect )\n( ============================================================================= )\nhere . cr\n\n: newline ( x -- x+1 : print a new line every fourth value )\n\tdup 3 and 0= if cr then 1+ ;\n\n: address ( num count -- count : print current address we are dumping every fourth value )\n\tdup >r\n\t1- 3 and 0= if . [char] : emit space else drop then\n\tr> ;\n\n: dump ( start count -- : print the contents of a section of memory )\n\tbase @ >r ( save current base )\n\thex ( switch to hex mode )\n\t1 >r ( save counter on return stack )\n\tover + swap ( calculate limits: start start+count )\n\tbegin \n\t\t2dup u> ( stop if gone past limits )\n\twhile \n\t\tdup r> address >r\n\t\tdup @ . 1+ \n\t\tr> newline >r\n\trepeat \n\tr> drop\n\tr> base !\n\t2drop ;\n\nhider newline\nhider address \n\nexit ( 'bye' does not work :C )\ninterpret ( use the new interpret word, which can catch exceptions )\n\nfind [interpret] cfa start! ( the word executed on restart is now our new word )\n\n( ========================== Basic Word Set ================================== )\n\n( ========================== Extended Word Set =============================== )\n\n: log2 ( x -- log2 )\n\t( Computes the binary integer logarithm of a number,\n\tzero however returns itself instead of reporting an error )\n\t0 swap\n\tbegin\n\t\tnos1+ 2\/ dup 0=\n\tuntil\n\tdrop 1- ;\n\n: time ( \" ccc\" -- n : time the number of milliseconds it takes to execute a word )\n\tclock >r\n\tfind execute\n\tclock r> - ;\n\n: rdepth\n\tmax-core `stack-size @ - r @ swap - ;\n\n( defer...is is probably not standards compliant, it is still neat! Also, there\n is no error handling if \"find\" fails... )\n: (do-defer) ( -- self : pushes the location into which it is compiled )\n\tr> dup >r 1- ;\n\n: defer ( \" ccc\" -- , Run Time -- location : \n\tcreates a word that pushes a location to write an execution token into )\n\t:: ' (do-defer) , postpone ; ;\n\n: is ( location \" ccc\" -- : make a deferred word execute a word ) \n\tfind cfa swap ! ;\n\nhere . cr\nhider (do-defer)\n\n( The \"tail\" function implements tail calls, which is just a jump\nto the beginning of the words definition, for example this\nword will never overflow the stack and will print \"1\" followed\nby a new line forever,\n\n\t: forever 1 . cr tail ;\n\nWhereas\n\n\t: forever 1 . cr recurse ;\n\nor\n\n\t: forever 1 . cr forever ;\n\nWould overflow the return stack. )\n\nhider tail\n: tail ( -- : perform tail recursion in current word definition )\n\timmediate\n\tlatest cfa\n\t' branch ,\n\there - 1+ , ;\n\n: recurse immediate\n\t( This function implements recursion, although this interpreter\n\tallows calling a word directly. If used incorrectly this will\n\tblow up the return stack.\n\n\tWe can test \"recurse\" with this factorial function:\n\t : factorial dup 2 < if drop 1 exit then dup 1- recurse * ; )\n\tlatest cfa , ;\n\n: factorial ( x -- x : compute the factorial of a number )\n\tdup 2 < if drop 1 exit then dup 1- recurse * ;\n\n: myself ( -- : myself is a synonym for recurse ) \n\timmediate postpone recurse ;\n\n: gcd ( x1 x2 -- x : greatest common divisor )\n\tdup if tuck mod tail then drop ;\n\n( ========================== Extended Word Set =============================== )\n\n( The words described here on out get more complex and will require more\nof an explanation as to how they work. )\n\n( ========================== CREATE DOES> ==================================== )\n\n( The following section defines a pair of words \"create\" and \"does>\" which\nare a powerful set of words that can be used to make words that can create\nother words. \"create\" has both run time and compile time behavior, whilst\n\"does>\" only works at compile time in conjunction with \"create\". These two\nwords can be used to add constants, variables and arrays to the language,\namongst other things.\n\nA simple version of create is as follows\n\n\t: create :: 2 , here 2 + , ' exit , 0 state ! ;\n\nBut this version is much more limited.\n\n\"create\"...\"does>\" is one of the constructs that makes Forth Forth, it\nallows the creation of words which can define new words in themselves,\nand thus allows us to extend the language easily.\n)\n\n: write-quote ( -- : A word that writes ' into the dictionary )\n\t['] ' , ; \n\n: write-exit ( -- : A word that write exit into the dictionary )\n\t['] exit , ; \n\n: write-compile, ( -- : A word that writes , into the dictionary ) \n\t' , , ;\n\n: state! ( bool -- : set the compilation state variable ) \n\tstate ! ;\n\n: command-mode ( -- : put the interpreter into command mode )\n\tfalse state! ;\n\n: command-mode-create ( create a new work that pushes its data field )\n\t:: ( compile a word )\n\tdolit , ( write push into new word )\n\there 2+ , ( push a pointer to data field )\n\tpostpone ; ; ( write exit and switch to command mode )\n\n: mark write-compile, ( Write in a place holder 0 and push a pointer to to be used by does> )\n\twrite-quote write-exit write-compile, ( Write in an exit in the word we're compiling. )\n\t['] command-mode , ; ( Make sure to change the state back to command mode )\n\n: create immediate ( create word is quite a complex forth word )\n\tstate @ \n\tif \n\t\tpostpone ( hole-to-patch -- )\n\timmediate\n\twrite-exit ( we don't want the defining to exit, but the *defined* word to )\n\there swap ! ( patch in the code fields to point to )\n\tdolist , ; ( write a run in )\n\nhider write-quote\nhider write-compile,\n\n( Now that we have create...does> we can use it to create arrays, variables\nand constants, as we mentioned before. )\n\n: array ( u c\" xxx\" -- : create a named array of length u ) \n\tcreate allot does> + ;\n\n: variable ( x c\" xxx\" -- : create a variable will initial value of x )\n\tcreate , does> ;\n\n: constant ( x c\" xxx\" -- : create a constant with value of x ) \n\tcreate , does> @ ;\n\n: table ( u c\" xxx\" --, Run Time: -- addr u : create a named table )\n\tcreate dup , allot does> dup @ ;\n\n: string ( u c\" xxx\" --, Run Time: -- addr u : create a named table )\n\tcreate dup , chars allot does> dup @ swap 1+ chars> swap ;\n\n\\ : +field \\ n <\"name\"> -- ; exec: addr -- 'addr\n\\ create over , +\n\\ does> @ + ;\n\\ \n\\ : begin-structure \\ -- addr 0 ; -- size\n\\ \tcreate\n\\ \there 0 0 , \\ mark stack, lay dummy\n\\ \tdoes> @ ; \\ -- rec-len\n\\ \n\\ : end-structure \\ addr n --\n\\ swap ! ; \\ set len \n\\ \n\\ begin-structure point\n\\ \tpoint +field p.x\n\\ \tpoint +field p.y\n\\ end-structure\n\\ \n\\ This should work...\n\\ : buffer: ( u c\" xxx\" --, Run Time: -- addr )\n\\\tcreate allot ;\n\n: 2constant \n\tcreate , , does> dup 1+ @ swap @ ;\n\n: 2variable \n\tcreate , , does> ;\n\n: enum ( x \" ccc\" -- x+1 : define a series of enumerations )\n\tdup constant 1+ ; \n\n( ========================== CREATE DOES> ==================================== )\n\n( ========================== DO...LOOP ======================================= )\n\n( The following section implements Forth's do...loop constructs, the\nword definitions are quite complex as it involves a lot of juggling of\nthe return stack. Along with begin...until do loops are one of the\nmain looping constructs. \n\nUnlike begin...until do accepts two values a limit and a starting value,\nthey are also words only to be used within a word definition, some Forths\nextend the semantics so looping constructs operate in command mode, this\nForth does not do that as it complicates things unnecessarily.\n\nExample:\n\t\n\t: example-1 10 1 do i . i 5 > if cr leave then loop 100 . cr ; \n\texample-1\n\nPrints:\n\t1 2 3 4 5 6\n\nIn \"example-1\" we can see the following:\n\n1. A limit, 10, and a start value, 1, passed to \"do\".\n2. A word called 'i', which is the current count of the loop\n3. If the count is greater than 5, we call a word call 'leave', this\nword exits the current loop context as well as the current calling\nword.\n4. \"100 . cr\" is never called. This should be changed in future\nrevision, but this version of leave exits the calling word as well.\n\n'i', 'j', and 'leave' *must* be used within a do...loop construct. \n\nIn order to remedy point 4. loop should not use branch but instead \nshould use a value to return to which it pushes to the return stack )\n\n: (do)\n\tswap ( swap the limit and start )\n\tr> ( save our return stack to temporary variable )\n\t-rot ( limit start return -- return start limit )\n\t>r ( push limit onto return stack )\n\t>r ( push start onto return stack )\n\t>r ; ( restore our return address )\n\n: do immediate ( Run time: high low -- : begin do...loop construct )\n\t' (do) ,\n\tpostpone begin ; \n\n: (unloop) ( -- , R: i limit -- : remove limit and i from )\n\tr> ( save our return address )\n\trdrop ( pop off i )\n\trdrop ( pop off limit )\n\t>r ; ( restore our return stack )\n\n: (+loop) ( x -- bool : increment loop variable by x and test it )\n\tr@ 1- ( get the pointer to i )\n\t+! ( add value to it )\n\tr@ 1- @ ( find i again )\n\tr@ 2- @ ( find the limit value )\n\tu>= ;\n\n: (loop) ( -- bool : increment loop variable by 1 and test it )\n\tr@ 1- ( get the pointer to i )\n\t1+! ( add one to it )\n\tr@ 1- @ ( find the value again )\n\tr@ 2- @ ( find the limit value )\n\tu>= ;\n\n: loop ( -- : end do...loop construct )\n\timmediate ' (loop) , postpone until ' (unloop) , ;\n\n: +loop ( x -- : end do...+loop loop construct )\n\timmediate ' (+loop) , postpone until ' (unloop) , ;\n\n: leave ( -- , R: i limit return -- : break out of a do-loop construct )\n\t(unloop)\n\trdrop ; ( return to the caller's caller routine )\n\n: ?leave ( x -- , R: i limit return -- | i limit return : conditional leave )\n\tif\n\t\t(unloop)\n\t\trdrop ( return to the caller's caller routine )\n\tthen ;\n\n: i ( -- i : Get current, or innermost, loop index in do...loop construct )\n\tr> r> ( pop off return address and i )\n\ttuck ( tuck i away )\n\t>r >r ; ( restore return stack )\n\n: j ( -- j : Get outermost loop index in do...loop construct )\n\t4 rpick ;\n\n( This is a simple test function for the looping, for interactive\ntesting and debugging:\n : mm 5 1 do i . cr 4 1 do j . tab i . cr loop loop ; )\n\n: range ( nX nY -- nX nX+1 ... nY ) \n\tnos1+ do i loop ;\n\n: repeater ( n0 X -- n0 ... nX ) \n\t1 do dup loop ;\n\n: sum ( n0 ... nX X -- sum<0..X> ) \n\t1 do + loop ;\n\n: mul ( n0 ... nX X -- mul<0..X> ) \n\t1 do * loop ;\n\n: reverse ( x1 ... xn n -- xn ... x1 : reverse n items on the stack )\n\t0 do i roll loop ;\n\n( ========================== DO...LOOP ======================================= )\n\n0 variable column-counter\n4 variable column-width\n\n: column ( i -- )\t\n\tcolumn-width @ mod not if cr then ;\n\n: reset-column\t\t\n\t0 column-counter ! ;\n\n: auto-column\t\t\n\tcolumn-counter dup @ column 1+! ;\n\n: alignment-bits \n\t[ 1 size log2 lshift 1- literal ] and ;\n\n: name ( PWD -- c-addr : given a pointer to the PWD field of a word get a pointer to the name of the word )\n\tdup 1+ @ 256\/ lsb - chars> ;\n\n0 variable x\n: x! ( x -- ) \n\tx ! ;\n\n: x@ ( -- x ) \n\tx @ ;\n\n: 2>r ( x1 x2 -- R: x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tswap\n\t\t>r\n\t\t>r\n\tx@ >r ; ( restore return address )\n\n: 2r> ( R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tr>\n\t\tr>\n\t\tswap\n\tx@ >r ; ( restore return address )\n\n: 2r@ ( -- x1 x2 , R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\tr> r>\n\t2dup\n\t>r >r\n\tswap\n\tx@ >r ; ( restore return address )\n\n: unused ( -- u : push the amount of core left ) \n\tmax-core here - ;\n\n: accumulator ( initial \" ccc\" -- : make a word that increments by a value and pushes the result )\n\tcreate , does> tuck +! @ ;\n\n: counter ( \" ccc\" --, Run Time: -- x : make a word that increments itself by one, starting from zero )\n\tcreate -1 , does> dup 1+! @ ;\n\n0 variable delim\n: accepter ( c-addr max delimiter -- i )\n\t( store a \"max\" number of chars at c-addr until \"delimiter\" encountered,\n\tthe number of characters stored is returned )\n\tdelim ! ( store delimiter used to stop string storage when encountered)\n\t0\n\tdo\n\t\tkey dup delim @ <>\n\t\tif\n\t\t\tover c! 1+\n\t\telse ( terminate string )\n\t\t\tdrop 0 swap c! \n\t\t\ti \n\t\t\tleave\n\t\tthen\n\tloop\n\t-11 throw ; ( read in too many chars )\nhider delim\n\n: skip\n\tkey drop >r 0 begin drop key dup rdup r> <> until rdrop ;\n\n: word ( c -- c-addr : parse until 'c' is encountered, push transient counted string )\n\tdup skip chere 1+ c!\n\t>r\n\tchere 2+\n\tpad here - chars>\n\tr> accepter 1+\n\tchere c!\n\tchere ;\n\nhider skip\n\n: accept ( c-addr +n1 -- +n2 : see accepter definition ) \n\t'\\n' accepter ;\n\n0xFFFF constant max-string-length\n\n: (.\") ( char -- c-addr u )\n\t( @todo This really needs simplifying, to do this\n\ta set of words that operate on a temporary buffer can\n\tbe used )\n\t( Write a string into word being currently defined, this\n\tcode has to jump over the string it has just put into the\n\tdictionary so normal execution of a word can continue. The\n\tlength and character address of the string are left on the\n\tstack )\n\t>r ( save delimiter )\n\t' branch , ( write in jump, this will jump past the string )\n\t>mark ( make hole )\n\tdup 1+ chars> ( calculate address to write to )\n\tmax-string-length \n\tr> ( restore delimiter )\n\taccepter dup >r ( write string into dictionary, save index )\n\taligned 2dup size \/ ( stack: length hole char-len hole )\n\t1+ dup allot ( update dictionary pointer with string length )\n\t1+ swap ! ( write place to jump to )\n\tdrop ( do not need string length anymore )\n\t1+ chars> ( calculate place to print )\n\tr> ; ( restore index and address of string )\n\n: length ( c-addr u -- u : push the length of an ASCIIZ string )\n tuck 0 do dup c@ 0= if 2drop i leave then 1+ loop ;\n\n: asciiz? ( c-addr u -- : is a Forth string also a ASCIIZ string )\n\ttuck length <> ;\n\n: asciiz ( c-addr u -- : trim a string until NUL terminator )\n\t2dup length nip ;\n\n: type ( c-addr u -- : print out 'u' characters at c-addr )\n\t0 do dup c@ emit 1+ loop drop ;\n\n: do-string ( char -- : write a string into the dictionary reading it until char is encountered )\n\t(.\") \n\tstate @ if swap [literal] [literal] then ;\n\n: fill ( c-addr u char -- : fill in an area of memory with a character, only if u is greater than zero )\n\t-rot\n\t0 do 2dup i + c! loop\n\t2drop ;\n\n: \/string ( c-addr1 u1 n -- c-addr2 u2 : advance a string by n characters )\n\tover min rot over + -rot - ;\n\n: compare ( c-addr1 u1 c-addr2 u2 -- n : compare two strings, not quite compliant yet )\n\t>r swap r> min >r\n\tstart-address + swap start-address + r>\n\tmemory-compare ;\n\n128 string sbuf\n: s\" ( \"ccc\" --, Run Time -- c-addr u )\n\tkey drop sbuf 0 fill sbuf [char] \" accepter sbuf drop swap ;\nhider sbuf\n\n( @todo these strings really need rethinking, state awareness needs to be removed... )\n: type, \n\tstate @ if ' type , else type then ;\n\n: c\" \n\timmediate key drop [char] \" do-string ;\n\n: \" \n\timmediate key drop [char] \" do-string type, ;\n\n: sprint ( c -- : print out chars until 'c' is encountered )\n\tkey drop ( drop next space )\n\t>r ( save delimiter )\n\tbegin\n\t\tkey dup ( get next character )\n\t\trdup r> ( get delimiter )\n\t\t<> if emit 0 then\n\tuntil rdrop ;\n\n: .( \n\timmediate [char] ) sprint ;\nhider sprint\n\n: .\" \n\timmediate key drop [char] \" do-string type, ;\n\nhider type,\n\n( This word really should be removed along with any usages of this word, it\nis not a very \"Forth\" like word, it accepts a pointer to an ASCIIZ string and\nprints it out, it also does not checking of the returned values from write-file )\n: print ( c-addr -- : print out a string to the standard output )\n\t-1 over >r length r> swap stdout write-file 2drop ;\n\n: ok \n\t\" ok\" cr ;\n\n: empty-stack ( x-n ... x-0 -- : empty the variable stack )\n\tbegin depth while drop repeat ;\n\n: (quit) ( -- : do the work of quit, without the restart )\n\t0 `source-id ! ( set source to read from file )\n\t`stdin @ `fin ! ( read from stdin )\n\tpostpone [ ( back into command mode )\n\t' interpret start! ; ( set interpreter starting word )\n\n: quit ( -- : Empty return stack, go back to command mode, read from stdin, interpret input )\n\t(quit)\n\t-1 restart ; ( restart the interpreter )\n\n: abort\n\t-1 throw ;\n\n: (abort\") ( do the work of abort )\n\t(quit)\n\t-2 throw ;\n\n: abort\" immediate \n\tpostpone \"\n\t' cr , ' (abort\") , ;\n\n( ==================== CASE statements ======================== )\n\n( for a simpler case statement:\n\tsee Volume 2, issue 3, page 48 of Forth Dimensions at\n\thttp:\/\/www.forth.org\/fd\/contents.html )\n\n( These case statements need improving, it is not standards compliant )\n: case immediate\n\t' branch , 3 , ( branch over the next branch )\n\there ' branch , ( mark: place endof branches back to with again )\n\t>mark swap ; ( mark: place endcase writes jump to with then )\n\n: over= ( x y -- x bool : over ... then = )\n\tover = ;\n\n: of\n\timmediate ' over= , postpone if ;\n\n: endof\n\timmediate over postpone again postpone then ;\n\n: endcase\n\timmediate 1+ postpone then drop ;\n\n( ==================== CASE statements ======================== )\n\n( ==================== Hiding Words =========================== )\n\n: }hide ( should only be matched with 'hide{' )\n\timmediate -22 throw ;\n\n: hide{ ( -- : hide a list of words, the list is terminated with \"}hide\" )\n\tbegin\n\t\tfind ( find next word )\n\t\tdup [ find }hide ] literal = if\n\t\t\tdrop exit ( terminate hide{ )\n\t\tthen\n\t\tdup 0= if -15 throw then\n\t\thide drop\n\tagain ;\n\n( ==================== Hiding Words =========================== )\n\n: spaces ( n -- : print n spaces ) \n\t0 do space loop ;\n\n: erase ( addr u : erase a block of memory )\n\t2chars> 0 fill ;\n\n: blank ( c-addr u : fills a string with spaces )\n\tbl fill ;\n\n( move should check that u is not negative )\n: move ( addr1 addr2 u -- : copy u words of memory from 'addr2' to 'addr1' )\n\t0 do\n\t\t2dup i + @ swap i + !\n\tloop\n\t2drop ;\n\n( It would be nice if move and cmove could share more code, as they do exactly\n the same thing but with different load and store functions, cmove> )\n: cmove ( c-addr1 c-addr2 u -- : copy u characters of memory from 'c-addr2' to 'c-addr1' )\n\t0 do\n\t\t2dup i + c@ swap i + c!\n\tloop\n\t2drop ;\n\n( ==================== Conditional Compilation ================ )\n\n( The words \"[if]\", \"[else]\" and \"[then]\" implement conditional compilation,\nthey can be nested as well\n\nSee http:\/\/lars.nocrew.org\/dpans\/dpans15.htm for more information\n\nA much simpler conditional compilation method is the following\nsingle word definition:\n\n : compile-line? 0= if [ find \\\\ , ] then ;\n\nWhich will skip a line if a conditional is false, and compile it\nif true )\n\n( These words really, really need refactoring, I could use the newly defined \n \"defer\" to help out with this )\n0 variable nest ( level of [if] nesting )\n0 variable [if]-word ( populated later with \"find [if]\" )\n0 variable [else]-word ( populated later with \"find [else]\")\n: [then] immediate ;\n: reset-nest 1 nest ! ;\n: unnest? [ find [then] ] literal = if nest 1-! then ;\n: nest? [if]-word @ = if nest 1+! then ;\n: end-nest? nest @ 0= ;\n: match-[else]? [else]-word @ = nest @ 1 = and ;\n\n: [if] ( bool -- : conditional execution )\n\tunless\n\t\treset-nest\n\t\tbegin\n\t\t\tfind\n\t\t\tdup nest?\n\t\t\tdup match-[else]? if drop exit then\n\t\t\t unnest?\n\t\t\tend-nest?\n\t\tuntil\n\tthen ;\n\n: [else] ( discard input until [then] encounter, nesting for [if] )\n\treset-nest\n\tbegin\n\t\tfind\n\t\tdup nest? unnest?\n\t\tend-nest?\n\tuntil ;\n\nfind [if] [if]-word !\nfind [else] [else]-word !\n\nhide{ \n[if]-word [else]-word nest reset-nest unnest? match-[else]? end-nest? nest? }hide\n\n( ==================== Conditional Compilation ================ )\n\n( ==================== Endian Words =========================== )\n\nsize 2 = [if] 0x0123 variable endianess [then]\nsize 4 = [if] 0x01234567 variable endianess [then]\nsize 8 = [if] 0x01234567abcdef variable endianess [then]\n\n: endian ( -- bool : returns the endianess of the processor, little = 0, big = 1 )\n\t[ endianess chars> c@ 0x01 = ] literal ;\nhider endianess\n\n: swap16 ( x -- x : swap the byte order a 16 bit number )\n\tdup 256* 0xff00 and >r 256\/ lsb r> or ;\n\nsize 4 >= [if] \n\t: swap32 \n\t\tdup 0xffff and swap16 16 lshift swap\n\t\t16 rshift 0xffff and swap16 or ;\n[then]\n\nsize 8 >= [if]\n\t: swap64 ( x -- x : swap the byte order of a 64 bit number )\n\t\t dup 0xffffffff and swap32 32 lshift swap\n\t\t 32 rshift 0xffffffff and swap32 or ;\n[then]\n\nsize 2 = [if]\n\tendian \n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\tswap16 ;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\t;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\tswap16 ;\n\t[then]\n[then]\n\nsize 4 = [if]\n\tendian \n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\tswap32 ;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\t;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\tswap32 ;\n\t[then]\n[then]\n\nsize 8 = [if]\n\tendian \n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\tswap64 ;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\t;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\tswap64 ;\n\t[then]\n[then]\n\n( ==================== Endian Words =========================== )\n\n( ==================== Misc words ============================= )\n\n0 variable counter\n\n: counted-column ( index -- : special column printing for dump )\n\tcounter @ column-width @ mod\n\tnot if cr . \" :\" space else drop then\n\tcounter 1+! ;\n\n: as-chars ( x n -- : print a cell out as characters, upto n chars )\n\t0 ( from zero to the size of a cell )\n\tdo\n\t\tdup ( copy variable to print out )\n\t\tsize i 1+ - select-byte ( select correct byte )\n\t\tdup printable? not ( is it not printable )\n\t\tif drop [char] . then ( print a '.' if it is not )\n\t\temit ( otherwise print it out )\n\tloop\n\tspace ( print out space after )\n\tdrop ; ( drop cell we have printed out )\n\n: lister ( addr u addr -- )\n\t0 counter ! 1- swap \n\tdo \n\t\tdup counted-column 1+ i ? i @ size as-chars \n\tloop ;\n\n( @todo this function should make use of 'defer' and 'is', then different\nversion of dump could be made that swapped out 'lister' )\n: dump ( addr u -- : dump out 'u' cells of memory starting from 'addr' )\n\tbase @ >r hex 1+ over + under lister drop r> base ! cr ;\n\nhide{ counted-column counter as-chars }hide\n\n: forgetter ( pwd-token -- : forget a found word and everything after it )\n\tdup @ pwd ! h ! ;\n\n( @bug will not work for immediate defined words \n@note Fig Forth had a word FENCE, if anything before this word was\nattempted to be forgotten then an exception is throw )\n: forget ( WORD -- : forget word and every word defined after it )\n\tfind dup 0= if -15 throw then 1- forgetter ;\n\n: marker ( WORD -- : make word the forgets itself and words after it)\n\t:: latest [literal] ' forgetter , postpone ; ;\nhider forgetter\n\n: ** ( b e -- x : exponent, raise 'b' to the power of 'e')\n\t?dup-if\n\t\tover swap\n\t\t1 do over * loop \n\t\tnip\n\telse\n\t\tdrop 1\n\tendif ;\n\n0 variable a\n0 variable b\n0 variable m\n: equal ( a1...an b1...bn n -- a1...an b1...bn bool : determine if two lists are equal )\n\t( example: \n\t\t1 2 3 \n\t\t1 2 3 \n\t\t3 equal \n\treturns: 1 )\n\tdup m ! 1+ 1 ( store copy of length and use as loop index )\n\tdo \n\t\ti 1- pick b ! ( store ith element of list in b1...bn )\n\t\ti m @ + 1- pick a ! ( store ith element of list in a1...an )\n\t\ta @ b @ <> ( compare a and b for equality )\n\t\tif 0 leave then ( unequal, finish early )\n\tloop 1 ; ( lists must be equal )\n\nhide{ a b m }hide\n\n: ndrop ( drop n items )\n\t?dup-if 0 do drop loop then ;\n\n( ==================== Misc words ============================= )\n\n( ==================== Pictured Numeric Output ================ )\n\n0 variable hld\n\n: overflow ( -- : )\n \there chars> pad chars> hld @ - u> if -17 throw then ;\n\n: hold ( char -- : add a character to the numeric output string )\n\toverflow pad chars> hld @ - c! hld 1+! ;\n\n: holds ( addr u -- )\n begin dup while 1- 2dup + c@ hold repeat 2drop ;\n\n: nbase ( -- base : in this forth 0 is a special base, push 10 is base is zero )\n\tbase @ dup 0= if drop 10 then ;\n\n: <# ( -- : setup pictured numeric output )\n\t0 hld ! ;\n\n: sign ( -- : add a sign to the pictured numeric output string )\n\t[char] - hold ;\n\n: # ( x -- x : divide x by base, turn into a character, put in pictured output string )\n\tnbase um\/mod swap \n \tdup 9 u>\n \tif 7 + then\n \t48 + hold ;\n\n: #s ( x -- 0 : repeatedly call # on x until x is zero )\n\tbegin # dup 0= until ; \n\n: #> ( -- c-addr u : end pictured output conversion, push output string to stack )\n\t0 hold ( NUL terminate string, just in case )\n\thld 1-! ( but do not include that in the count )\n\tpad chars> hld @ \n\ttuck - 1+ swap ;\n\n: u. ( u -- : display number in base 10 )\n\tbase @ >r decimal <# #s #> type drop r> base ! ;\n\nhide{ nbase overflow }hide\n\n( ==================== Pictured Numeric Output ================ )\n\n( ==================== ANSI Escape Codes ====================== )\n( Terminal colorization module, via ANSI Escape Codes\n \nsee: https:\/\/en.wikipedia.org\/wiki\/ANSI_escape_code\nThese codes will provide a relatively portable means of\nmanipulating a terminal )\n\n27 constant 'escape'\n: CSI 'escape' emit .\" [\" ;\n0 constant black\n1 constant red\n2 constant green\n3 constant yellow\n4 constant blue\n5 constant magenta\n6 constant cyan\n7 constant white\n: foreground 30 + ;\n: background 40 + ;\n0 constant dark\n1 constant bright\nfalse variable colorize \n\n: color ( brightness color-code -- : set the terminal color )\n\t( set color on an ANSI compliant terminal,\n\tfor example:\n\t\tbright red foreground color\n\tsets the foreground text to bright red )\n\tcolorize @ 0= if 2drop exit then \n\tCSI u. if .\" ;1\" then .\" m\" ;\n\n: at-xy ( x y -- : set ANSI terminal cursor position to x y )\n\tCSI u. [char] ; emit u. .\" H\" ;\n\n: page ( -- : clear ANSI terminal screen and move cursor to beginning ) \n\tCSI .\" 2J\" 1 1 at-xy ;\n\n: hide-cursor ( -- : hide the cursor from view ) \n\tCSI .\" ?25l\" ;\n\n: show-cursor ( -- : show the cursor ) \n\tCSI .\" ?25h\" ;\n\n: save-cursor ( -- : save cursor position ) \n\tCSI .\" s\" ;\n\n: restore-cursor ( -- : restore saved cursor position ) \n\tCSI .\" u\" ;\n\n: reset-color ( -- : reset terminal color to its default value)\n\tcolorize @ 0= if exit then\n\tCSI .\" 0m\" ;\n\nhide{ CSI }hide\n( ==================== ANSI Escape Codes ====================== )\n\n( ==================== Unit test framework =================== )\n\n256 string estring ( string to test )\n0 variable #estring ( actual string length )\n0 variable start ( starting depth )\n0 variable result ( result depth )\n0 variable check ( only check depth if -> is called )\n0 variable dictionary ( dictionary pointer on entering { )\n0 variable previous ( PWD register on entering { )\n\n: T ; ( hack until T{ can process words )\n\n: -> ( -- : save depth in variable ) \n\t1 check ! depth result ! ; \n\n: test estring drop #estring @ ; \n\n: fail ( -- : invalidate the forth interpreter and exit )\n\tinvalidate bye ;\n\n: neutral ( -- : neutral color )\n\t;\n\n: bad ( -- : bad color )\n\tdark red foreground color ;\n\n: good ( -- : good color )\n\tdark green foreground color ;\n\n: die bad test type reset-color cr fail ;\n\n: evaluate? ( bool -- : test if evaluation has failed )\n\tif .\" evaluation failed\" cr fail then ;\n\n: failed bad .\" failed\" reset-color cr ;\n\n: adjust ( x -- x : adjust a depth to take into account starting depth ) \n\tstart @ - ;\n\n: no-check? ( -- bool : if true we need to check the depth )\n\tcheck @ 0= ;\n\n: depth? ( -- : check if depth is correct )\n\tno-check? if exit then\n\tdepth adjust ( get depth and adjust for starting depth )\n\tresult @ adjust 2* = ( get results depth, same adjustment, should be\n\t half size of the depth ) \n\tif exit then ( pass )\n\tfailed\n\t.\" Unequal depths:\" cr\n\t.\" depth: \" depth . cr\n\t.\" result: \" result @ . cr\n\tdie ;\n\n: equal? ( -- : determine if results equals expected )\n\tno-check? if exit then\n\tresult @ adjust equal\n\tif exit then\n\tfailed\n\t.\" Result is not equal to expected values. \" cr \n\t.\" Stack: \" cr .s cr\n\tdie ;\n\n: display ( c-addr u -- : print out testing message in estring )\n\tverbose if neutral type else 2drop then ;\n\n: pass ( -- : print out passing message )\n\tverbose if good .\" ok \" cr reset-color then ;\n\n: save ( -- : save current dictionary )\n\tpwd @ previous !\n\there dictionary ! ;\n\n: restore ( -- : restore dictionary )\n\tprevious @ pwd ! \n\tdictionary @ h ! ;\n\n\n: T{ ( -- : perform a unit test )\n\tdepth start ! ( save start of stack depth )\n\t0 result ! ( reset result variable )\n\t0 check ! ( reset check variable )\n\testring 0 fill ( zero input string )\n\tsave ( save dictionary state )\n\tkey drop ( drop next character, which is a space )\n\testring [char] } accepter #estring ! ( read in string to test )\n\ttest display ( print which string we are testing )\n\ttest evaluate ( perform test )\n\tevaluate? ( evaluate successfully? )\n\tdepth? ( correct depth )\n\tequal? ( results equal to expected values? )\n\tpass ( print pass message )\n\tresult @ adjust 2* ndrop ( remove items on stack generated by test )\n\trestore ; ( restore dictionary to previous state )\n\nT{ }T\nT{ -> }T\nT{ 1 -> 1 }T\nT{ 1 2 -> 1 2 }T\nT{ : c 1 2 ; c -> 1 2 }T\nT{ :noname 2 ; :noname 3 + ; compose execute -> 5 }T\n\nhide{ \n\tpass test display\n\tadjust start save restore dictionary previous \n\tevaluate? equal? depth? estring #estring result\n\tcheck no-check? die neutral bad good failed\n}hide\n\n( ==================== Unit test framework =================== )\n\n\n( ==================== Random Numbers ========================= )\n\n( \nSee:\nuses xorshift\nhttps:\/\/en.wikipedia.org\/wiki\/Xorshift\nhttp:\/\/excamera.com\/sphinx\/article-xorshift.html\nhttp:\/\/www.arklyffe.com\/main\/2010\/08\/29\/xorshift-pseudorandom-number-generator\/\nthese constants have be collected from the web \n)\n\nsize 2 = [if] 13 constant a 9 constant b 7 constant c [then]\nsize 4 = [if] 13 constant a 17 constant b 5 constant c [then]\nsize 8 = [if] 12 constant a 25 constant b 27 constant c [then]\n\n7 variable seed ( must not be zero )\n\n: seed! ( x -- : set the value of the PRNG seed )\n\tdup 0= if drop 7 ( zero not allowed ) then seed ! ;\n\n: random ( -- x : assumes word size is 32 bit )\n\tseed @\n\tdup a lshift xor\n\tdup b rshift xor\n\tdup c lshift xor\n\tdup seed! ;\n\nhide{ a b c seed }hide\n\n( ==================== Random Numbers ========================= )\n\n( ==================== Prime Numbers ========================== )\n( From original \"third\" code from the IOCCC at \nhttp:\/\/www.ioccc.org\/1992\/buzzard.2.design, the module works out\nand prints prime numbers. )\n\n: prime? ( u -- u | 0 : return number if it is prime, zero otherwise )\n\tdup 1 = if 1- exit then\n\tdup 2 = if exit then\n\tdup 2 \/ 2 ( loop from 2 to n\/2 )\n\tdo\n\t\tdup ( value to check if prime )\n\t\ti mod ( mod by divisor )\n\t\tnot if\n\t\t\tdrop 0 leave\n\t\tthen\n\tloop ;\n\n0 variable counter\n\n: primes ( x1 x2 -- : print the primes from x2 to x1 )\n\t0 counter !\n\t\" The primes from \" dup . \" to \" over . \" are: \"\n\tcr\n\treset-column\n\tdo\n\t\ti prime?\n\t\tif\n\t\t\ti . counter @ column counter 1+!\n\t\tthen\n\tloop\n\tcr\n\t\" There are \" counter @ . \" primes.\"\n\tcr ;\n\nhide{ counter }hide\n( ==================== Prime Numbers ========================== )\n\n( ==================== Debugging info ========================= )\n\n( string handling should really be done with PARSE, and CMOVE )\n\nhide{ .s }hide\n: .s ( -- : print out the stack for debugging )\n\t\" <\" depth u. \" >\" space\n\tdepth if\n\t\tdepth 0 do i column tab depth i 1+ - pick u. loop\n\tthen\n\tcr ;\n\n1 variable hide-words ( do we want to hide hidden words or not )\n( This function prints out all of the defined words, excluding hidden words.\nAn understanding of the layout of a Forth word helps here. The dictionary\ncontains a linked list of words, each forth word has a pointer to the previous\nword until the first word. The layout of a Forth word looks like this:\n\nNAME: Forth Word - A variable length ASCII NUL terminated string\nPWD: Previous Word Pointer, points to the previous word\nMISC: Flags, code word and offset from previous word pointer to start of Forth word string\nCODE\/DATA: The body of the forth word definition, not interested in this.\n\nThere is a register which stores the latest defined word which can be\naccessed with the code \"pwd @\". In order to print out a word we need to\naccess a words MISC field, the offset to the NAME is stored here in bits\n8 to 15 and the offset is calculated from the PWD field.\n\n\"print\" expects a character address, so we need to multiply any calculated\naddress by the word size in bytes. )\n\n: words ( -- : print out all defined an visible words )\n\tlatest\n\tbegin\n\t\tdup\n\t\thidden? hide-words @ and\n\t\tnot if\n\t\t\tname\n\t\t\tprint space\n\t\telse\n\t\t\tdrop\n\t\tthen\n\t\t@ ( Get pointer to previous word )\n\t\tdup dictionary-start u< ( stop if pwd no longer points to a word )\n\tuntil\n\tdrop cr ;\nhider hide-words\n\n: TrueFalse ( -- : print true or false )\n\tif \" true\" else \" false\" then ;\n\n: registers ( -- : print out important registers and information about the virtual machine )\n\t\" return stack pointer: \" r@ . cr\n\t\" dictionary pointer \" here . cr\n\t\" previous word: \" pwd ? cr\n\t\" state: \" state ? cr\n\t\" base: \" base ? cr\n\t\" depth: \" depth . cr\n\t\" cell size (in bytes): \" size . cr\n\t\" last cell address: \" max-core . cr\n\t\" unused cells: \" unused . cr\n\t\" invalid: \" `invalid @ TrueFalse cr\n\t\" size of variable stack: \" `stack-size ? cr\n\t\" size of return stack: \" `stack-size ? cr\n\t\" start of variable stack: \" max-core `stack-size @ 2* - . cr\n\t\" start of return stack: \" max-core `stack-size @ - . cr\n\t\" current input source: \" source-id -1 = if \" string\" else \" file\" then cr\n\t\" reading from stdin: \" source-id 0 = stdin? and TrueFalse cr\n\t\" tracing on: \" `debug @ TrueFalse cr\n\t\" starting word: \" `instruction ? cr\n\t\" real start address: \" `start-address ? cr\n\t\" error handling: \" `error-handler ? cr ;\n( `sin `sidx `slen `fout\n `stdout `stderr `argc `argv )\n\n\n: y\/n? ( -- bool : ask a yes or no question )\n\tkey drop\n\t\" y\/n? \"\n\tbegin\n\t\tkey\n\t\tdup\n\t\t[char] y = if true exit then\n\t\t[char] n = if false exit then\n\t\t\" y\/n? \"\n\tagain ;\n\n: >instruction ( extract instruction from instruction field ) 0x7f and ;\n\n: step\n\t( step through a word: this word could be augmented\n\twith commands such as \"dump\", \"halt\", and optional\n\t\".s\" and \"registers\" )\n\tregisters\n\t\" .s: \" .s cr\n\t\" -- press any key to continue -- \"\n\tkey drop ;\n\n: more ( -- : wait for more input )\n\t\" -- press any key to continue -- \" key drop cr page ;\n\n: debug-help ( -- : this is not quite ready for prime time )\n \" debug mode commands\n\th - print help\n\tq - exit containing word\n\tr - print registers\n\ts - print stack\n\tc - continue on with execution\n\" ;\n\n: debug-prompt \n\t.\" debug> \" ;\n\n: debug ( a work in progress, debugging support, needs parse-word )\n\tkey drop\n\tcr\n\tbegin\n\t\tdebug-prompt\n\t\t'\\n' word count drop c@\n\t\tcase\n\t\t\t[char] h of debug-help endof\n\t\t\t[char] q of bye endof\n\t\t\t[char] r of registers endof\n\t\t\t[char] s of >r .s r> endof\n\t\t\t[char] c of drop exit endof\n\t\tendcase drop\n\tagain ;\nhider debug-prompt\n\n: code>pwd ( CODE -- PWD\/0 : calculate PWD from code address )\n\tdup dictionary-start here within not if drop 0 exit then\n\t>r\n\tlatest dup @ ( p1 p2 )\n\tbegin\n\t\tover ( p1 p2 p1 )\n\t\trdup r> u<= swap rdup r> > and if rdrop exit then\n\t\tdup 0= if rdrop exit then\n\t\tdup @ swap\n\tagain ;\n\n: end-print ( x -- )\n\t\"\t\t=> \" . \" ]\" ;\n\n: word-printer\n\t( attempt to print out a word given a words code field\n\tWARNING: This is a dirty hack at the moment\n\tNOTE: given a pointer to somewhere in a word it is possible\n\tto work out the PWD by looping through the dictionary to\n\tfind the PWD below it )\n\t1- dup @ -1 = if \" [ noname\" end-print exit then\n\t dup \" [ \" code>pwd ?dup-if name print else drop \" data\" then\n\t end-print ;\nhider end-print\nhider code>pwd\n\n( these words push the execution tokens for various special cases for decompilation )\n: get-branch [ find branch cfa ] literal ;\n: get-?branch [ find ?branch cfa ] literal ;\n: get-original-exit [ original-exit cfa ] literal ;\n: get-quote [ find ' cfa ] literal ;\n\n: branch-increment ( addr branch -- increment : calculate decompile increment for \"branch\" )\n\t1+ dup negative? if drop 2 else 2dup dump then ;\n\n( these words take a code field to a primitive they implement, decompile it\nand any data belonging to that operation, and push a number to increment the\ndecompilers code stream pointer by )\n\n: decompile-literal ( code -- increment )\n\t\" [ literal\t=> \" 1+ ? \" ]\" 2 ;\n: decompile-branch ( code -- increment )\n\t\" [ branch\t=> \" 1+ ? \" ]\" dup 1+ @ branch-increment ;\n: decompile-quote ( code -- increment )\n\t\" [ '\t=> \" 1+ @ word-printer \" ]\" 2 ;\n: decompile-?branch ( code -- increment )\n\t\" [ ?branch\t=> \" 1+ ? \" ]\" 2 ;\n\n( The decompile word expects a pointer to the code field of a word, it\ndecompiles a words code field, it needs a lot of work however.\nThere are several complications to implementing this decompile\nfunction.\n\n\t' The next cell should be pushed\n\t:noname This has a marker before its code field of -1 which\n\t\t cannot occur normally, this is handles in word-printer\n\tbranch branches are used to skip over data, but also for\n\t\t some branch constructs, any data in between can only\n\t\t be printed out generally speaking\n\texit There are two definitions of exit, the one used in\n\t\t ';' and the one everything else uses, this is used\n\t\t to determine the actual end of the word\n\tliterals Literals can be distinguished by their low value,\n\t\t which cannot possibly be a word with a name, the\n\t\t next field is the actual literal\n\nOf special difficult is processing 'if' 'else' 'then' statements,\nthis will require keeping track of '?branch'.\n\nAlso of note, a number greater than \"here\" must be data )\n\n: decompile ( code-field-ptr -- : decompile a word )\n\tbegin\n\t\ttab\n\t\tdup @\n\t\tcase\n\t\t\tdolit of drup decompile-literal endof\n\t\t\tget-branch of drup decompile-branch endof\n\t\t\tget-quote of drup decompile-quote endof\n\t\t\tget-?branch of drup decompile-?branch endof\n\t\t\tget-original-exit of 2drop \" [ exit ]\" cr exit endof\n\t\t\tword-printer 1\n\t\tendcase\n\t\t+\n\t\tcr\n\tagain ;\n\nhide{\n\tword-printer get-branch get-?branch get-original-exit \n\tget-quote branch-increment decompile-literal \n\tdecompile-branch decompile-?branch decompile-quote\n}hide\n\n: xt-instruction ( extract instruction from execution token )\n\tcfa @ >instruction ;\n\n( these words expect a pointer to the PWD field of a word )\n: defined-word? xt-instruction dolist = ;\n: print-name \" name: \" name print cr ;\n: print-start \" word start: \" name chars . cr ;\n: print-previous \" previous word: \" @ . cr ;\n: print-immediate \" immediate: \" 1+ @ >instruction compile-instruction <> TrueFalse cr ;\n: print-instruction \" instruction: \" xt-instruction . cr ;\n: print-defined \" defined: \" defined-word? TrueFalse cr ;\n\n: print-header ( PWD -- is-immediate-word? )\n\tdup print-name\n\tdup print-start\n\tdup print-previous\n\tdup print-immediate\n\tdup print-instruction ( @todo look up instruction name )\n\tprint-defined ;\n\n: see ( -- : decompile the next word in the input stream )\n\tfind\n\tdup 0= if -32 throw then\n\t1- ( move to PWD field )\n\tdup print-header\n\tdup defined-word?\n\tif ( decompile if a compiled word )\n\t\tcfa 1+ ( move to code field )\n\t\t\" code field:\" cr\n\t\tdecompile\n\telse ( the instruction describes the word if it is not a compiled word )\n\t\tdrop\n\tthen ;\n\n( These help messages could be moved to blocks, the blocks could then\nbe loaded from disk and printed instead of defining the help here,\nthis would allow much larger help )\n\n: help ( -- : print out a short help message )\n\tpage\n\tkey drop\n\" Welcome to Forth, an imperative stack based language. It is both a low\nlevel and a high level language, with a very small memory footprint. Most\nof Forth is defined as a combination of various primitives.\n\nA short description of the available function (or Forth words) follows,\nwords marked (1) are immediate and cannot be used in command mode, words\nmarked with (2) define new words. Words marked with (3) have both command\nand compile functionality.\n\n\"\nmore \" The built in words that accessible are:\n\n(1,2)\t: define a new word, switching to compile mode\n\timmediate make latest defined word immediate\n\tread read in a word, execute in command mode else compile\n\t@ ! fetch, store\n\tc@ c! character based fetch and store\n\t- + * \/ standard arithmetic operations,\n\tand or xor invert standard bitwise operations\n\tlshift rshift left and right bit shift\n\tu< u> < > = comparison predicates\n\texit exit from a word\n\temit print character from top of stack\n\tkey get a character from input\n\tr> >r pop a value from or to the return stack\n\tfind find a word in the dictionary and push the location\n\t' store the address of the following word on the stack\n\t, write the top of the stack to the dictionary\n\tswap swap first two values on the stack\n\tdup duplicate the top of the stack\n\tdrop pop and drop a value\n\tover copy the second stack value over the first\n\t. pop the top of the stack and print it\n\" \nmore \" \n\tprint print a NUL terminated string at a character address\n\tdepth get the current stack depth\n\tclock get the time since execution start in milliseconds\n\tevaluate evaluate a string\n\tsystem execute a system command\n\tclose-file close a file handle\n\topen-file open a file handle\n\tdelete-file delete a file off disk given a string\n\tread-file read in characters from a file\n\twrite-file write characters to a file\n\tfile-position get the file offset\n\treposition-file reposition the file pointer\n\tflush-file flush a file to disk\n\trename-file rename a file on disk\n \"\n\nmore \" All of the other words in the interpreter are built from these\nprimitive words. A few examples:\n\n(1)\tif...else...then FORTH branching construct\n(1)\tbegin...until loop until top of stack is non zero\n(1)\tbegin...again infinite loop\n(1)\tdo...loop FORTH looping construct\n(2,3)\tcreate create a new word that pushes its location\n(1)\tdoes> declare a created words run time behaviour\n(1,2)\tvariable declare variable with initial value from top of stack\n(1,2)\tconstant declare a constant, taken from top of stack\n(1,2)\tarray declare an array with size taken from top of stack\n(1)\t; terminate a word definition and return to command mode\n\twords print out a list of all the defined words\n\thelp this help message\n\tdump print out memory contents starting at an address\n\tregisters print out the contents of the registers\n\tsee decompile a word, viewing what words compose it\n\t.s print out the contents of the stack\n\n\"\n\nmore \" Some more advanced words:\n\n\there push the dictionary pointer\n\th push the address of the dictionary pointer\n\tr push the return stack pointer\n\tallot allocate space in the dictionary\n(1)\t[ switch to command mode\n\t] switch to compile mode\n\t:: compile ':' into the dictionary\n\n\" more \"\nFor more information either consult the manual pages forth(1) and libforth(1)\nor consult the following sources:\n\n\thttps:\/\/github.com\/howerj\/libforth\n\thttp:\/\/work.anapnea.net\/html\/html\/projects.html\n\nAnd for a larger tutorial:\n\n\thttps:\/\/github.com\/howerj\/libforth\/blob\/master\/readme.md\n\nFor resources on Forth:\n\n\thttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\thttps:\/\/rwmj.wordpress.com\/2010\/08\/07\/jonesforth-git-repository\/\n\n -- end --\n\" cr\n;\n\n( ==================== Files ================================== )\n\n( @todo implement the other file access methods in terms of the\n built in ones [see http:\/\/forth.sourceforge.net\/std\/dpans\/dpans11.htm]\n @todo read-line and write-line need their flag and ior setting correctly\n\n\tFILE-SIZE [ use file-positions ]\n\n Also of note:\t\n * Source ID needs extending. )\n\n: read-char ( c-addr fileid -- ior : read a char )\n\t1 swap read-file 0<> swap 1 <> or ;\n\n0 variable x\n\n: getchar ( fileid -- char ior )\n\tx chars> swap read-char x chars> c@ swap ;\n\n: write-char ( c-addr fileid -- ior : write a char )\n\t1 swap write-file 0<> swap 1 <> or ;\n\n: putchar ( char fileid -- ior )\n\tswap x chars> c! x chars> swap write-char ;\n\nhide{ x }hide\n\n: rewind-file ( file-id -- : rewind a file to the beginning )\n\t0 reposition-file throw ;\n\n: read-line ( c-addr u1 fileid -- u2 flag ior : read in a line of text )\n\t-rot bounds\n\tdo\n\t\tdup i swap read-char drop\n\t\ti c@ '\\n' = if drop i 0 0 leave then\n\tloop drop ;\n\n: write-line ( c-addr u fileid -- u2 flag ior : write a line of text )\n\t-rot bounds\n\tdo\n\t\tdup i swap write-char drop\n\t\ti c@ '\\n' = if drop i 0 0 leave then\n\tloop ;\n\n: resize-file ( ud fileid -- ior : attempt to resize a file )\n\t( There is no portable way to truncate a file :C )\n\t2drop -1 ( -1 to indicate failure ) ;\n\n: create-file ( c-addr u fam -- fileid ior )\n\t>r 2dup w\/o open-file throw close-file throw\n\tr> open-file ;\n\n: include-file ( file-id -- : evaluate a file ) \n\tdup >r 0 1 evaluator r> close-file throw throw ;\n\n: included ( c-addr u -- : attempt to open up a name file and evaluate it )\n\tr\/o open-file throw \n\tinclude-file ;\n\n: include ( c\" ccc\" -- : attempt to evaluate a named file )\n\t( @bug requires trailing space, should use parse-name )\n\tbl word count included ;\n\n: bin ( fam1 -- fam2 : modify a file access method to be binary not line oriented ) \n\t( Do nothing, all file access methods are binary )\n\t;\n\n( ==================== Files ================================== )\n\n( ==================== Blocks ================================= )\n( \n0 variable dirty\nb\/buf string buf\n0 variable loaded\n0 variable blk\n0 variable scr\n\n: update 1 dirty ! ;\n: empty-buffers 0 loaded ! ;\n: ?update dup loaded @ <> dirty @ or ;\n: ?invalid dup 0= if empty-buffers -35 throw then ;\n: write dup >r write-file r> close-file throw ;\n: read dup >r read-file r> close-file throw ;\n: name >r <# #s #> rot drop r> create-file throw ; \\ @todo add .blk with holds, also create file deletes file first...\n: update! >r buf r> w\/o name write throw drop empty-buffers ;\n: get >r buf r> r\/o name read throw drop ;\n: block ?invalid ?update if dup update! then dup get loaded ! buf drop ;\n\nhide{ dirty ?update update! loaded name get ?invalid write read }hide\n\n: c \n\t1 block update drop\n\t2 block update drop\n\t3 block update drop\n\t4 block update drop ;\nc )\n\n( ==================== Blocks ================================= )\n\n( ==================== Matcher ================================ )\n( The following section implements a very simple regular expression\nengine, which expects an ASCIIZ Forth string. It is translated from C\ncode and performs an identical function.\n\nThe regular expression language is as follows:\n\n\tc\tmatch a literal character\n\t.\tmatch any character\n\t*\tmatch any characters\n\nThe \"*\" operator performs the same function as \".*\" does in most\nother regular expression engines. Most other regular expression engines\nalso do not anchor their selections to the beginning and the end of\nthe string to match, instead using the operators '^' and '$' to do\nso, to emulate this behavior '*' can be added as either a suffix,\nor a prefix, or both, to the matching expression.\n\nAs an example \"*, World!\" matches both \"Hello, World!\" and\n\"Good bye, cruel World!\". \"Hello, ....\" matches \"Hello, Bill\"\nand \"Hello, Fred\" but not \"Hello, Tim\" as there are two few\ncharacters in the last string.\n\n@todo make a matcher that expects a Forth string, which do not\nhave to be NUL terminated\n)\n\n\\ Translated from http:\/\/c-faq.com\/lib\/regex.html\n\\ int match(char *pat, char *str)\n\\ {\n\\ \tswitch(*pat) {\n\\ \tcase '\\0': return !*str;\n\\ \tcase '*': return match(pat+1, str) || *str && match(pat, str+1);\n\\ \tcase '.': return *str && match(pat+1, str+1);\n\\ \tdefault: return *pat == *str && match(pat+1, str+1);\n\\ \t}\n\\ }\n\n: *pat ( regex -- regex char : grab next character of pattern ) \n\tdup c@ ;\n\n: *str ( string regex -- string regex char : grab next character string to match )\n\tover c@ ;\n\n: pass ( c-addr1 c-addr2 -- bool : pass condition, characters matched ) \n\t2drop 1 ;\n\n: reject ( c-addr1 c-addr2 -- bool : fail condition, character not matched ) \n\t2drop 0 ;\n\n: *pat==*str ( c-addr1 c-addr2 -- c-addr1 c-addr2 bool )\n\t2dup c@ swap c@ = ;\n\n: ++ ( u1 u2 u3 u4 -- u1+u3 u2+u4 : not quite d+ [does no carry] )\n\tswap >r + swap r> + swap ;\n\ndefer matcher\n\n: advance ( string regex char -- bool : advance both regex and string )\n\tif 1 1 ++ matcher else reject then ;\n\n: advance-string ( string regex char -- bool : advance only the string )\n\tif 1 0 ++ matcher else reject then ;\n\n: advance-regex ( string regex -- bool : advance matching )\n\t2dup 0 1 ++ matcher if pass else *str advance-string then ;\n\n: match ( string regex -- bool : match a ASCIIZ pattern against an ASCIIZ string )\n\t( @todo Add limits and accept two Forth strings, making sure they are both\n\t ASCIIZ strings as well \n\t @warning This uses a non-standards compliant version of case! )\n\t*pat\n\tcase\n\t\t 0 of drop drop c@ not exit endof\n\t\t[char] * of drop advance-regex exit endof\n\t\t[char] . of drop *str advance exit endof\n\t\t drop *pat==*str advance exit\n\tendcase ;\n\nmatcher is match\n\nhide{ \n\t*str *pat *pat==*str pass reject advance \n\tadvance-string advance-regex matcher ++ \n}hide\n\n( ==================== Matcher ================================ )\n\n\n( ==================== Cons Cells ============================= )\n\n( From http:\/\/sametwice.com\/cons.fs, this could be improved if the optional\nmemory allocation words were added to the interpreter. This provides\na simple \"cons cell\" data structure. There is currently no way to\nfree allocated cells )\n\n: car! ( value cons-addr -- : store a value in the car cell of a cons cell ) \n\t! ;\n\n: cdr! ( value cons-addr -- : store a value in the cdr cell of a cons cell )\n\tcell+ ! ;\n\n: car@ ( cons-addr -- car-val : retrieve car value from cons cell )\n\t@ ;\n\n: cdr@ ( cons-addr -- cdr-val : retrieve cdr value from cons cell )\n\tcell+ @ ;\n\n: cons ( car-val cdr-val -- cons-addr : allocate a new cons cell )\n\tswap here >r , , r> ;\n\n: cons0 0 0 cons ;\n\nmarker cleanup\n77 987 cons constant x\nT{ x car@ -> 77 }T\nT{ x cdr@ -> 987 }T\nT{ 55 x cdr! x car@ x cdr@ -> 77 55 }T\nT{ 44 x car! x car@ x cdr@ -> 44 55 }T\ncleanup\n\n( ==================== Cons Cells ============================= )\n\n( ==================== Miscellaneous ========================== )\n\n: license ( -- : print out license information )\n\" \nThe MIT License (MIT)\n\nCopyright (c) 2016 Richard James Howe\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the 'Software'),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand\/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\nTHE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\nOTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\nARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE. \n\n\" \n;\n\n( ==================== Version information =================== )\n\n4 constant version\n\n( ==================== Version information =================== )\n\n( ==================== Core utilities ======================== )\n( Read the header of a core file and process it, printing the\nresults out )\n\n8 constant header-size ( size of Forth core file header )\n8 constant size-field-size ( the size in bytes of the size field in the core file )\n0 variable core-file ( core fileid we are reading in )\n0 variable core-cell-size ( cell size of Forth core )\n0 variable core-version ( version of core file )\n0 variable core-endianess ( endianess of core we are reading in )\n\n( save space to read in header )\ncreate header header-size chars allot\n: cheader ( -- c-addr : header char address )\n\theader chars> ;\ncreate size-field size-field-size chars allot\n: csize-field ( -- c-addr : address of place size field is stored in )\n\tsize-field chars> ;\n\n0\nenum header-magic0 ( magic number 0 : FF ) \nenum header-magic1 ( magic number 1 : '4' )\nenum header-magic2 ( magic number 2 : 'T' )\nenum header-magic3 ( magic number 3 : 'H' )\nenum header-cell-size ( size of a forth cell, either 2, 4 or 8 bytes )\nenum header-version ( version of the forth core )\nenum header-endianess ( endianess of the core )\nenum header-log2size ( binary logarithm of the core size )\n\n: cleanup ( -- : cleanup before abort )\n\tcore-file @ ?dup 0<> if close-file drop then ;\n\n: invalid-header ( bool -- : abort if header is invalid )\n\t<> if cleanup abort\" invalid header\" then ;\n\n: save-core-cell-size ( char -- : save the core file cell size, checking if it is valid )\n\tcore-cell-size !\n\t\" cell size:\" tab\n\tcore-cell-size @ 2 = if 2 . cr exit then\n\tcore-cell-size @ 4 = if 4 . cr exit then\n\tcore-cell-size @ 8 = if 8 . cr exit then\n\tcleanup core-cell-size @ . abort\" : invalid cell size\" ;\n\n: check-version-compatibility ( char -- : checks the version compatibility of the core file ) \n\tcore-version !\n\tcore-version @ version = if \" version: \" version . cr exit then\n\tcleanup core-version @ . abort\" : unknown version number\" ;\n\n: save-endianess ( char -- : save the endianess, checking if it is valid )\n\tcore-endianess !\n\t\" endianess:\" tab\n\tcore-endianess @ 0 = if \" big\" cr exit then\n\tcore-endianess @ 1 = if \" little\" cr exit then\n\tcleanup core-endianess @ . abort\" invalid endianess\" then ;\n\n: read-or-abort ( c-addr size fileid -- : )\n\tover >r read-file \n\t 0<> if cleanup abort\" file read failed\" then\n\tr> <> if cleanup abort\" header too small\" then ;\n\n: header? ( -- : print out header information )\n\tcheader header-size core-file @ read-or-abort\n\t( \" raw header:\" header 2 dump )\n\tcheader header-magic0 + c@ 255 invalid-header\n\tcheader header-magic1 + c@ [char] 4 invalid-header\n\tcheader header-magic2 + c@ [char] T invalid-header\n\tcheader header-magic3 + c@ [char] H invalid-header\n\tcheader header-cell-size + c@ save-core-cell-size\n\tcheader header-version + c@ check-version-compatibility\n\tcheader header-endianess + c@ save-endianess\n\t\" valid header\" cr ;\n\n: size? ( -- : print out core file size )\n\t\" size: \" cheader header-log2size + c@ 1 swap lshift . cr ;\n\n: core ( c-addr u -- : analyze a Forth core file from disk given its file name )\n\t2dup \" core file:\" tab type cr\n\tr\/o open-file throw core-file ! \n\theader?\n\tsize?\n\tcore-file @ close-file drop ;\n\n( s\" forth.core\" core )\n\nhide{ \nheader-size header? \nheader-magic0 header-magic1 header-magic2 header-magic3\nheader-version header-cell-size header-endianess header-log2size\nheader \ncore-file save-core-cell-size check-version-compatibility\ncore-cell-size cheader\ncore-endianess core-version save-endianess invalid-header\ncleanup size-field csize-field size-field-size\nread-or-abort size?\n}hide\n\n( ==================== Core utilities ======================== )\n\n( ==================== RLE =================================== )\n\n( These set of words implement Run Length Compression, which can be used for\nsaving space when compressing the core files generated by Forth programs, which\ncontain mostly runs of NUL characters. \n\nThe format of the encoded data is quite simple, there is a command byte\nfollowed by data. The command byte encodes only two commands; encode a run of\nliteral data and repeat the next character. \n\nIf the command byte is greater than X the command is a run of characters, \nX is then subtracted from the command byte and this is the number of \ncharacters that is to be copied verbatim when decompressing.\n\nIf the command byte is less than or equal to X then this number, plus one, is \nused to repeat the next data byte in the input stream.\n\nX is 128 for this application, but could be adjusted for better compression\ndepending on what the data looks like. \n\nExample:\n\t\n\t2 'a' 130 'b' 'c' 3 'd'\n\nBecomes:\n\n\taabcddd \n\nExample usage:\n\n\t: extract\n\t\tc\" forth.core\" w\/o open-file throw\n\t\tc\" forth.core.rle\" r\/o open-file throw\n\t\tdecompress ;\n\textract\n\n@note file redirection could be used for the input as well\n@todo compression, and reading\/writing to strings )\n\n: cpad pad chars> ;\n\n0 variable out\n128 constant run-length\n\n: more ( file-id -- char : read in a single character )\n\t>r cpad r> read-char throw cpad c@ ;\n\n: repeated ( count file-id -- : repeat a character count times )\n\tmore swap 0 do dup emit loop drop ;\n\n: literals ( count file-id -- : extract a literal run )\n\t>r cpad swap r> read-file throw cpad swap type ;\n\n: command ( file-id -- : process an RLE command )\n\tdup \n\t>r more \n\tdup run-length u> \n\tif \n\t\trun-length - r> literals \n\telse \n\t\t1+ r> repeated \n\tthen ;\n\n: redirect ( file-id-out -- : save current output pointer, redirect to output )\n\t`fout @ out ! `fout ! ;\n\n: restore ( -- : restore previous output pointer )\n\tout @ `fout ! ;\n\n: decompress ( file-id-out file-id-in -- : decompress an RLE encoded file )\n\tswap\n\tredirect\n\tbegin dup ' command catch until ( process commands until input exhausted )\n\t2drop ( drop twice because catch will restore stack before 'command' )\n\trestore ; ( restore input stream )\n\nhide{ literals repeated more out run-length command }hide\n\n( ==================== RLE =================================== )\n\n( ==================== Generate C Core file ================== )\n( The word core2c reads in a core file and turns it into a C file which \ncan then be compiled into the forth interpreter in a bootstrapping like\nprocess.\n\nUsage:\n c\" forth.core\" c\" core.gen.c\" core2c )\n\n0 variable count\n\n: wbyte ( u char -- : write a byte )\n\tpnum drop\n\t[char] , emit\n\t16 mod 0= if cr then ;\n\n: advance ( char -- : advance counter and print byte )\n\tcount 1+! count @ swap wbyte ;\n\n: hexify ( fileid -- fileid : turn core file into C numbers in array )\n\t0 count !\n\tbegin dup getchar 0= while advance repeat drop ;\n\n: quote ( -- : emit a quote character )\n\t[char] \" emit ;\n\n: core2c ( c-addr u c-addr u -- ior : generate a C file from a core file )\n\tw\/o open-file throw >r\n\tr\/o open-file ?dup-if r> close-file throw throw then\n\tr> redirect\n\t\" #include \" quote \" libforth.h\" quote cr\n\t\" unsigned char forth_core_data[] = {\" cr\n\thexify \n\t\" };\" cr\n\t\" forth_cell_t forth_core_size = \" count @ . \" ;\" cr cr\n\tclose-file\n\t`fout @ close-file \n\trestore or ;\n\nhide{ wbyte hexify count quote advance }hide\n \n( ==================== Generate C Core file ================== )\n\n: wc ( c-addr u -- u : count the bytes in a file )\n\tr\/o open-file throw\n\t0 swap\n\tbegin dup getchar nip 0= while nos1+ repeat close-file throw ;\n\n( ==================== Save Core file ======================== )\n\n( The following functionality allows the user to save the core file\nfrom within the running interpreter. The Forth core files have a very simple\nformat which means the words for doing this do not have to be too long, a header\nhas to emitted with a few calculated values and then the contents of the\nForths memory after this )\n\n( This write the header out to the current output device, this\nwill be redirected to a file )\n: header ( -- : write the header out )\n\t0xff emit ( magic 0 )\n\t[char] 4 emit ( magic 1 )\n\t[char] T emit ( magic 2 )\n\t[char] H emit ( magic 3 )\n\tsize emit ( cell size in bytes )\n\tversion emit ( core version )\n\tendian not emit ( endianess )\n\tmax-core log2 emit ; ( size field )\n\n: data ( -- : write the data out )\n\t0 max-core chars> `fout @ write-file throw drop ;\n\n: encore ( -- : write the core file out )\n\theader\n\tdata ;\n\n: save-core ( c-addr u -- : save core file or throw error ) \n\tw\/o open-file throw dup\n\tredirect \n\t\t' encore catch swap close-file throw \n\trestore ;\n\n( The following code illustrates an example of setting up a\nForth core file to execute a word when the core file is loaded.\nIn the example the word \"hello-world\" will be executed, which will\nalso quit the interpreter:\n\n\t\\ Only works for immediate words for now, we define\n\t\\ the word we wish to be executed when the forth core\n\t\\ is loaded\n\t: hello-world immediate\n\t\t\" Hello, World!\" cr bye ;\n\n\t\\ The following sets the starting word to our newly\n\t\\ defined word:\n\tfind hello-world cfa start!\n\n\t\\ Now we can save the core file out:\n\ts\" forth.core\" save-core \n\nThis can be used, in conjunction with aspects of the build system,\nto produce a standalone executable that will run only a single Forth\nword. )\n\nhide{ redirect restore data encore header }hide\n\n( ==================== Save Core file ======================== )\n\n( ==================== Hex dump ============================== )\n\n( @todo hexdump can read in too many characters and it does not\nprint out the correct address\n@todo utilities for easy redirecting of file input\/output )\n: input >r cpad 128 r> read-file ; ( file-id -- u 0 | error )\n: clean cpad 128 0 fill ; ( -- )\n: cdump cpad chars swap aligned chars dump ; ( u -- )\n: hexdump ( file-id -- : [hex]dump a file to the screen )\n\tdup \n\tclean\n\tinput if 2drop exit then\n\t?dup-if cdump else drop exit then\n\ttail ; \n\nhide{ more cpad clean cdump input }hide\n\n( ==================== Hex dump ============================== )\n\n( ==================== Date ================================== )\n\n( Rather annoyingly months are start from 1 but weekdays from 0 )\n\n: >month ( month -- )\n\tcase\n\t\t 1 of \" Jan \" endof\n\t\t 2 of \" Feb \" endof\n\t\t 3 of \" Mar \" endof\n\t\t 4 of \" Apr \" endof\n\t\t 5 of \" May \" endof\n\t\t 6 of \" Jun \" endof\n\t\t 7 of \" Jul \" endof\n\t\t 8 of \" Aug \" endof\n\t\t 9 of \" Sep \" endof\n\t\t10 of \" Oct \" endof\n\t\t11 of \" Nov \" endof\n\t\t12 of \" Dec \" endof\n\tendcase drop ;\n\n: .day ( day -- : add ordinal to day )\n\t10 mod\n\tcase\n\t\t1 of \" st \" drop exit endof\n\t\t2 of \" nd \" drop exit endof\n\t\t3 of \" rd \" drop exit endof\n\t\t\" th \" \n\tendcase drop ;\n\n: >day ( day -- : add ordinal to day of month )\n\tdup u.\n\tdup 1 10 within if .day exit then\n\tdup 10 20 within if \" th\" drop exit then\n\t.day ;\n\n: >weekday ( weekday -- : print the weekday )\n\tcase\n\t\t0 of \" Sun \" endof\n\t\t1 of \" Mon \" endof\n\t\t2 of \" Tue \" endof\n\t\t3 of \" Wed \" endof\n\t\t4 of \" Thu \" endof\n\t\t5 of \" Fri \" endof\n\t\t6 of \" Sat \" endof\n\tendcase drop ;\n\n: padded ( u -- : print out a run of zero characters )\n\t0 do [char] 0 emit loop ;\n\n: 0u. ( u -- : print a zero padded number )\n\tdup 10 u< if 1 padded then u. space ;\n\n: .date ( date -- : print the date )\n\tif \" DST \" else \" GMT \" then \n\tdrop ( no need for days of year)\n\t>weekday\n\t. ( year ) \n\t>month \n\t>day \n\t0u. ( hour )\n\t0u. ( minute )\n\t0u. ( second ) cr ;\n\n: time&date ( -- second minute hour day month year )\n\tdate\n\t3drop ;\n\nhide{ 0u. >weekday .day >day >month padded }hide\n\n( ==================== Date ================================== )\n\n( Looking at most Forths dictionary with \"words\" command they tend\nto have a lot of words that do not mean anything but to the implementers\nof that specific Forth, here we clean up as many non standard words as\npossible. )\nhide{ \n do-string ')' alignment-bits \n compile-instruction dictionary-start hidden? hidden-mask instruction-mask\n max-core dolist x x! x@ write-exit\n max-string-length \n original-exit\n pnum evaluator \n TrueFalse >instruction print-header\n print-name print-start print-previous print-immediate\n print-instruction xt-instruction defined-word? print-defined\n `state\n `source-id `sin `sidx `slen `start-address `fin `fout `stdin\n `stdout `stderr `argc `argv `debug `invalid `top `instruction\n `stack-size `error-handler `x `y `handler _emit\n}hide\n\n( \n## Forth To List\n\nThe following is a To-Do list for the Forth code itself, along with any\nother ideas.\n\n* FORTH, VOCABULARY\n* \"Value\", \"To\", \"Is\"\n* Double cell words and floating point library\n* The interpreter should use character based addresses, instead of\nword based, and use values that are actual valid pointers, this\nwill allow easier interaction with the world outside the virtual machine\n* common words and actions should be factored out to simplify\ndefinitions of other words, their standards compliant version found\nif any\n* Allow the processing of argc and argv, the mechanism by which that\nthis can be achieved needs to be worked out. However all processing that\nis currently done in \"main.c\" should be done within the Forth interpreter\ninstead.\n* A built in version of \"dump\" and \"words\" should be added to the Forth\nstarting vocabulary, simplified versions that can be hidden.\n* Here documents, string literals. Examples of these can be found online\nat Rosetta Code, although the Forth versions online will need adapting.\n* Document the words in this file and built in words better, also turn this\ndocument into a literate Forth file.\n* Sort out \"'\", \"[']\", \"find\", \"compile,\" \n* Proper booleans should be used throughout, that is -1 is true, and 0 is\nfalse.\n* File operation primitives that close the file stream [and possibly restore\nI\/O to stdin\/stdout] if an error occurs, and then re-throws, should be made.\n* Implement as many things from http:\/\/lars.nocrew.org\/forth2012\/implement.html\nas is sensible. \n* CASE Statements http:\/\/dxforth.netbay.com.au\/miser.html\n* The current words that implement I\/O redirection need to be improved, and documented,\nI think this is quite a useful and powerful mechanism to use within Forth that simplifies\nprograms. This is a must and will make writing utilities in Forth a *lot* easier \n)\n\n( \nThe following will not work as we might actually be reading from a string [`sin]\nnot `fin. \n: key 32 chars> 1 `fin @ read-file drop 0 = if 0 else 32 chars> c@ then ; )\n\nverbose [if] \n\t.( FORTH: libforth successfully loaded.) cr\n\t.( Type 'help' and press return for a basic introduction.) cr\n\t.( Core: ) here . \" \/ \" here unused + . cr\n\t \n\t.( The MIT License ) cr\n\t.( ) cr\n\t.( Copyright 2016 Richard James Howe) cr\n\t.( ) cr\n\t.( Permission is hereby granted, free of charge, to any person obtaining a) cr\n\t.( copy of this software and associated documentation files [the \"Software\"],) cr\n\t.( to deal in the Software without restriction, including without limitation) cr\n\t.( the rights to use, copy, modify, merge, publish, distribute, sublicense,) cr\n\t.( and\/or sell copies of the Software, and to permit persons to whom the) cr\n\t.( Software is furnished to do so, subject to the following conditions:) cr\n\t.( ) cr\n\t.( The above copyright notice and this permission notice shall be included) cr\n\t.( in all copies or substantial portions of the Software.) cr\n\t.( ) cr\n\t.( THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR) cr\n\t.( IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,) cr\n\t.( FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL) cr\n\t.( THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR) cr\n\t.( OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,) cr\n\t.( ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR) cr\n\t.( OTHER DEALINGS IN THE SOFTWARE. ) cr\n[then]\n\n( \\ integrate simple 'dump' and 'words' into initial forth program \n: nl dup 3 and not ;\n: ?? \\ addr1 \n nl if dup cr . [char] : emit space then ? ;\n: dump \\ addr n --\n\tbase @ >r hex over + swap 1- begin 1+ 2dup dup ?? 2+ u< until r> base ! ; )\n\n\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"317c5e945e1521401ac17e03fc46cdc188887d90","subject":"Man, I'm not on the ball. 4th does not need to escape '\\' chars. This should make our beloved friend look less like he has a massive head wound.","message":"Man, I'm not on the ball. 4th does not need to escape '\\' chars. This\nshould make our beloved friend look less like he has a massive head wound.\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/beastie.4th","new_file":"sys\/boot\/forth\/beastie.4th","new_contents":"\\ Copyright (c) 2003 Scott Long \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\nmarker task-beastie.4th\n\ninclude \/boot\/screen.4th\ninclude \/boot\/frames.4th\n\nhide\n\nvariable menuidx\nvariable menubllt\nvariable menuX\nvariable menuY\nvariable promptwidth\n\nvariable bootkey\nvariable bootacpikey\nvariable bootsafekey\nvariable bootverbosekey\nvariable bootsinglekey\nvariable escapekey\nvariable rebootkey\n\n46 constant dot\n\n\\ The BSD Daemon. He is 19 rows high and 34 columns wide\n: print-beastie ( x y -- )\n\t2dup at-xy .\" , ,\" 1+\n\t2dup at-xy .\" \/( )`\" 1+\n\t2dup at-xy .\" \\ \\___ \/ |\" 1+\n\t2dup at-xy .\" \/- _ `-\/ '\" 1+\n\t2dup at-xy .\" (\/\\\/ \\ \\ \/\\\" 1+\n\t2dup at-xy .\" \/ \/ | ` \\\" 1+\n\t2dup at-xy .\" O O ) \/ |\" 1+\n\t2dup at-xy .\" `-^--'`< '\" 1+\n\t2dup at-xy .\" (_.) _ ) \/\" 1+\n\t2dup at-xy .\" `.___\/` \/\" 1+\n\t2dup at-xy .\" `-----' \/\" 1+\n\t2dup at-xy .\" <----. __ \/ __ \\\" 1+\n\t2dup at-xy .\" <----|====O)))==) \\) \/====\" 1+\n\t2dup at-xy .\" <----' `--' `.__,' \\\" 1+\n\t2dup at-xy .\" | |\" 1+\n\t2dup at-xy .\" \\ \/ \/\\\" 1+\n\t2dup at-xy .\" ______( (_ \/ \\______\/\" 1+\n\t2dup at-xy .\" ,' ,-----' |\" 1+\n\t at-xy .\" `--{__________)\"\n;\n\n: acpienabled? ( -- flag )\n\ts\" acpi_load\" getenv\n\tdup -1 = if\n\t\tdrop false exit\n\tthen\n\ts\" YES\" compare-insensitive 0<> if\n\t\tfalse exit\n\tthen\n\ts\" hint.acpi.0.disabled\" getenv\n\tdup -1 <> if\n\t\ts\" 0\" compare 0<> if\n\t\t\tfalse exit\n\t\tthen\n\tthen\n\ttrue\n;\n\n: printmenuitem ( -- n )\n\tmenuidx @\n\t1+ dup\n\tmenuidx !\n\tmenuY @ + dup menuX @ swap at-xy\n\tmenuidx @ .\n\tmenuX @ 1+ swap at-xy\n\tmenubllt @ emit\n\tmenuidx @ 48 +\n;\n\n: beastie-menu ( -- )\n\t0 menuidx !\n\tdot menubllt !\n\t8 menuY !\n\t5 menuX !\n\tclear\n\t46 4 print-beastie\n\t42 20 2 2 box\n\t13 6 at-xy .\" Welcome to FreeBSD!\"\n\tprintmenuitem .\" Boot FreeBSD [default]\" bootkey !\n\ts\" arch-i386\" environment? if\n\t\tprintmenuitem .\" Boot FreeBSD with ACPI \" bootacpikey !\n\t\tacpienabled? if\n\t\t\t.\" disabled\"\n\t\telse\n\t\t\t.\" enabled\"\n\t\tthen\n\telse\n\t\t-2 bootacpikey !\n\tthen\n\tprintmenuitem .\" Boot FreeBSD in Safe Mode\" bootsafekey !\n\tprintmenuitem .\" Boot FreeBSD in single user mode\" bootsinglekey !\n\tprintmenuitem .\" Boot FreeBSD with verbose logging\" bootverbosekey !\n\tprintmenuitem .\" Escape to loader prompt\" escapekey !\n\tprintmenuitem .\" Reboot\" rebootkey !\n\tmenuX @ 20 at-xy\n\t.\" Select option, [Enter] for default\"\n\tmenuX @ 21 at-xy\n\ts\" or [Space] to pause timer \" dup 2 - promptwidth !\n\ttype\n;\n\n: tkey\n\tdup\n\tseconds +\n\tbegin 1 while\n\t\tover 0<> if\n\t\t\tdup seconds u< if\n\t\t\t\tdrop\n\t\t\t\t-1\n\t\t\t\texit\n\t\t\tthen\n\t\t\tmenuX @ promptwidth @ + 21 at-xy dup seconds - .\n\t\tthen\n\t\tkey? if\n\t\t\tdrop\n\t\t\tkey\n\t\t\texit\n\t\tthen\n\t50 ms\n\trepeat\n;\n\nset-current\n\n: beastie-start\n\tbeastie-menu\n\ts\" autoboot_delay\" getenv\n\tdup -1 = if\n\t\tdrop\n\t\t10\n\telse\n\t\t0 0 2swap >number drop drop drop\n\tthen\n\tbegin true while\n\t\tdup tkey\n\t\t0 25 at-xy\n\t\tdup 32 = if nip 0 swap then\n\t\tdup -1 = if s\" boot\" evaluate then\n\t\tdup 13 = if s\" boot\" evaluate then\n\t\tdup bootkey @ = if s\" boot\" evaluate then\n\t\tdup bootacpikey @ = if\n\t\t\tacpienabled? if\n\t\t\t\ts\" acpi_load\" unsetenv\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\telse\n\t\t\t\ts\" YES\" s\" acpi_load\" setenv\n\t\t\t\ts\" 0\" s\" hint.acpi.0.disabled\" setenv\n\t\t\tthen\n\t\t\ts\" boot\" evaluate\n\t\tthen\n\t\tdup bootsafekey @ = if\n\t\t\ts\" arch-i386\" environment? if\n\t\t\t\ts\" acpi_load\" unsetenv\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\tthen\n\t\t\ts\" 0\" s\" hw.ata.ata_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.atapi_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.wc\" setenv\n\t\t\ts\" 0\" s\" hw.eisa_slots\" setenv\n\t\t\ts\" boot\" evaluate\n\t\tthen\n\t\tdup bootverbosekey @ = if\n\t\t\ts\" YES\" s\" boot_verbose\" setenv\n\t\t\ts\" boot\" evaluate\n\t\tthen\n\t\tdup bootsinglekey @ = if\n\t\t\ts\" YES\" s\" boot_single\" setenv\n\t\t\ts\" boot\" evaluate\n\t\tthen\n\t\tdup escapekey @ = if 2drop exit then\n\t\trebootkey @ = if s\" reboot\" evaluate then\n\trepeat\n;\n\nprevious\n","old_contents":"\\ Copyright (c) 2003 Scott Long \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\nmarker task-beastie.4th\n\ninclude \/boot\/screen.4th\ninclude \/boot\/frames.4th\n\nhide\n\nvariable menuidx\nvariable menubllt\nvariable menuX\nvariable menuY\nvariable promptwidth\n\nvariable bootkey\nvariable bootacpikey\nvariable bootsafekey\nvariable bootverbosekey\nvariable bootsinglekey\nvariable escapekey\nvariable rebootkey\n\n46 constant dot\n\n\\ The BSD Daemon. He is 19 rows high and 34 columns wide\n: print-beastie ( x y -- )\n\t2dup at-xy .\" , ,\" 1+\n\t2dup at-xy .\" \/( )`\" 1+\n\t2dup at-xy .\" \\\\ \\\\___ \/ |\" 1+\n\t2dup at-xy .\" \/- _ `-\/ '\" 1+\n\t2dup at-xy .\" (\/\\\\\/ \\\\ \\\\ \/\\\\\" 1+\n\t2dup at-xy .\" \/ \/ | ` \\\\\" 1+\n\t2dup at-xy .\" O O ) \/ |\" 1+\n\t2dup at-xy .\" `-^--'`< '\" 1+\n\t2dup at-xy .\" (_.) _ ) \/\" 1+\n\t2dup at-xy .\" `.___\/` \/\" 1+\n\t2dup at-xy .\" `-----' \/\" 1+\n\t2dup at-xy .\" <----. __ \/ __ \\\\\" 1+\n\t2dup at-xy .\" <----|====O)))==) \\\\) \/====\" 1+\n\t2dup at-xy .\" <----' `--' `.__,' \\\\\" 1+\n\t2dup at-xy .\" | |\" 1+\n\t2dup at-xy .\" \\\\ \/ \/\\\\\" 1+\n\t2dup at-xy .\" ______( (_ \/ \\\\______\/\" 1+\n\t2dup at-xy .\" ,' ,-----' |\" 1+\n\t at-xy .\" `--{__________)\"\n;\n\n: acpienabled? ( -- flag )\n\ts\" acpi_load\" getenv\n\tdup -1 = if\n\t\tdrop false exit\n\tthen\n\ts\" YES\" compare-insensitive 0<> if\n\t\tfalse exit\n\tthen\n\ts\" hint.acpi.0.disabled\" getenv\n\tdup -1 <> if\n\t\ts\" 0\" compare 0<> if\n\t\t\tfalse exit\n\t\tthen\n\tthen\n\ttrue\n;\n\n: printmenuitem ( -- n )\n\tmenuidx @\n\t1+ dup\n\tmenuidx !\n\tmenuY @ + dup menuX @ swap at-xy\n\tmenuidx @ .\n\tmenuX @ 1+ swap at-xy\n\tmenubllt @ emit\n\tmenuidx @ 48 +\n;\n\n: beastie-menu ( -- )\n\t0 menuidx !\n\tdot menubllt !\n\t8 menuY !\n\t5 menuX !\n\tclear\n\t46 4 print-beastie\n\t42 20 2 2 box\n\t13 6 at-xy .\" Welcome to FreeBSD!\"\n\tprintmenuitem .\" Boot FreeBSD [default]\" bootkey !\n\ts\" arch-i386\" environment? if\n\t\tprintmenuitem .\" Boot FreeBSD with ACPI \" bootacpikey !\n\t\tacpienabled? if\n\t\t\t.\" disabled\"\n\t\telse\n\t\t\t.\" enabled\"\n\t\tthen\n\telse\n\t\t-2 bootacpikey !\n\tthen\n\tprintmenuitem .\" Boot FreeBSD in Safe Mode\" bootsafekey !\n\tprintmenuitem .\" Boot FreeBSD in single user mode\" bootsinglekey !\n\tprintmenuitem .\" Boot FreeBSD with verbose logging\" bootverbosekey !\n\tprintmenuitem .\" Escape to loader prompt\" escapekey !\n\tprintmenuitem .\" Reboot\" rebootkey !\n\tmenuX @ 20 at-xy\n\t.\" Select option, [Enter] for default\"\n\tmenuX @ 21 at-xy\n\ts\" or [Space] to pause timer \" dup 2 - promptwidth !\n\ttype\n;\n\n: tkey\n\tdup\n\tseconds +\n\tbegin 1 while\n\t\tover 0<> if\n\t\t\tdup seconds u< if\n\t\t\t\tdrop\n\t\t\t\t-1\n\t\t\t\texit\n\t\t\tthen\n\t\t\tmenuX @ promptwidth @ + 21 at-xy dup seconds - .\n\t\tthen\n\t\tkey? if\n\t\t\tdrop\n\t\t\tkey\n\t\t\texit\n\t\tthen\n\t50 ms\n\trepeat\n;\n\nset-current\n\n: beastie-start\n\tbeastie-menu\n\ts\" autoboot_delay\" getenv\n\tdup -1 = if\n\t\tdrop\n\t\t10\n\telse\n\t\t0 0 2swap >number drop drop drop\n\tthen\n\tbegin true while\n\t\tdup tkey\n\t\t0 25 at-xy\n\t\tdup 32 = if nip 0 swap then\n\t\tdup -1 = if s\" boot\" evaluate then\n\t\tdup 13 = if s\" boot\" evaluate then\n\t\tdup bootkey @ = if s\" boot\" evaluate then\n\t\tdup bootacpikey @ = if\n\t\t\tacpienabled? if\n\t\t\t\ts\" acpi_load\" unsetenv\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\telse\n\t\t\t\ts\" YES\" s\" acpi_load\" setenv\n\t\t\t\ts\" 0\" s\" hint.acpi.0.disabled\" setenv\n\t\t\tthen\n\t\t\ts\" boot\" evaluate\n\t\tthen\n\t\tdup bootsafekey @ = if\n\t\t\ts\" arch-i386\" environment? if\n\t\t\t\ts\" acpi_load\" unsetenv\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\tthen\n\t\t\ts\" 0\" s\" hw.ata.ata_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.atapi_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.wc\" setenv\n\t\t\ts\" 0\" s\" hw.eisa_slots\" setenv\n\t\t\ts\" boot\" evaluate\n\t\tthen\n\t\tdup bootverbosekey @ = if\n\t\t\ts\" YES\" s\" boot_verbose\" setenv\n\t\t\ts\" boot\" evaluate\n\t\tthen\n\t\tdup bootsinglekey @ = if\n\t\t\ts\" YES\" s\" boot_single\" setenv\n\t\t\ts\" boot\" evaluate\n\t\tthen\n\t\tdup escapekey @ = if 2drop exit then\n\t\trebootkey @ = if s\" reboot\" evaluate then\n\trepeat\n;\n\nprevious\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"c13b39a728203d7f003dc4dbf133cf62c217f82c","subject":"Enhance boot-conf.","message":"Enhance boot-conf.\n\nNow boot-conf can also receive parameters to be passed to the kernel\nbeing booted. The syntax is the same as in the boot command, so one\nboots \/kernel.OLD in single-user mode by typing:\n\nboot-conf \/kernel.OLD -s instead of\nboot-conf -s \/kernel.OLD\n\nThe syntax still supports use of directory instead of file name, so\n\nboot-conf kernel.OLD -s\n\nmay be used to boot \/boot\/kernel.OLD\/kernel.ko in single-user mode.\n\nNotice that if one passes a flag to boot-conf, it will override the\nflags set in .conf files, but only for that invocation. If the user\naborts the countdown and tries again without passing any flags, the\nflags set in .conf files will be used.\n\nSome factorization was done in the process of enhancing boot-conf,\nas it has been growing steadly as features are getting added, becoming\ntoo big for a Forth word. It still could do with more factorization,\nas a matter of fact.\n\nOverride the builtin \"boot\" with something based on boot-conf. It will\nbehave exactly like boot-conf, but booting directly instead of going\nthrough autoboot.\n\nSince we are now pairing kernel and module set in the same directory,\nthis change to boot makes sense.\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/loader.4th","new_file":"sys\/boot\/forth\/loader.4th","new_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\ns\" arch-alpha\" environment? [if] [if]\n\ts\" loader_version\" environment? [if]\n\t\t3 < [if]\n\t\t\t.( Loader version 0.3+ required) cr\n\t\t\tabort\n\t\t[then]\n\t[else]\n\t\t.( Could not get loader version!) cr\n\t\tabort\n\t[then]\n[then] [then]\n\ns\" arch-i386\" environment? [if] [if]\n\ts\" loader_version\" environment? [if]\n\t\t8 < [if]\n\t\t\t.( Loader version 0.8+ required) cr\n\t\t\tabort\n\t\t[then]\n\t[else]\n\t\t.( Could not get loader version!) cr\n\t\tabort\n\t[then]\n[then] [then]\n\ninclude \/boot\/support.4th\n\nonly forth definitions also support-functions\n\n\\ ***** boot-conf\n\\\n\\\tPrepares to boot as specified by loaded configuration files.\n\nalso support-functions definitions\n\n: bootpath s\" \/boot\/\" ;\n: modulepath s\" module_path\" ;\n\n: saveenv ( addr len | 0 -1 -- addr' len | 0 -1 )\n dup -1 = if exit then\n dup allocate abort\" Out of memory\"\n swap 2dup 2>r\n move\n 2r>\n;\n\n: freeenv ( addr len | 0 -1 )\n -1 = if drop else free abort\" Freeing error\" then\n;\n\n: restoreenv ( addr len | 0 -1 -- )\n dup -1 = if ( it wasn't set )\n 2drop\n modulepath unsetenv\n else\n over >r\n modulepath setenv\n r> free abort\" Freeing error\"\n then\n;\n\n: set-tempoptions ( addrN lenN ... addr1 len1 N -- addr len 1 | 0 )\n \\ No options, set the default ones\n dup 0= if\n s\" kernel_options\" getenv dup -1 = if\n drop\n else\n s\" temp_options\" setenv\n then\n exit\n then\n\n \\ Skip filename\n 2 pick\n c@\n [char] - <> if\n swap >r swap >r\n 1 >r \\ Filename present\n 1 - \\ One less argument\n else\n 0 >r \\ Filename not present\n then\n\n \\ If no other arguments exist, use default options\n ?dup 0= if\n s\" kernel_options\" getenv dup -1 = if\n drop\n else\n s\" temp_options\" setenv\n then\n \\ Put filename back on the stack, if necessary\n r> if r> r> 1 else 0 then\n exit\n then\n\n \\ Concatenate remaining arguments into a single string\n >r strdup r>\n 1 ?do\n \\ Allocate new buffer\n 2over nip over + 1+\n allocate if out_of_memory throw then\n \\ Copy old buffer over\n 0 2swap over >r strcat\n \\ Free old buffer\n r> free if free_error throw then\n \\ Copy a space\n s\" \" strcat\n \\ Copy next string (do not free)\n 2swap strcat\n loop\n\n \\ Set temp_options variable, free whatever memory that needs freeing\n over >r\n s\" temp_options\" setenv\n r> free if free_error throw then\n\n \\ Put filename back on the stack, if necessary\n r> if r> r> 1 else 0 then\n;\n\n: get-arguments ( -- addrN lenN ... addr1 len1 N )\n 0\n begin\n \\ Get next word on the command line\n parse-word\n ?dup while\n 2>r ( push to the rstack, so we can retrieve in the correct order )\n 1+\n repeat\n drop ( empty string )\n dup\n begin\n dup\n while\n 2r> rot\n >r rot r>\n 1 -\n repeat\n drop\n;\n\nalso builtins\n\n: load-kernel ( addr len -- addr len error? )\n s\" temp_options\" getenv dup -1 = if\n drop 2dup 1\n else\n 2over 2\n then\n\n 1 load\n;\n\n: load-conf ( args 1 | 0 \"args\" -- flag )\n 0 1 unload drop\n\n 0= if ( interpreted ) get-arguments then\n set-tempoptions\n\n if ( there are arguments )\n load-kernel if ( load command failed )\n \\ Set the environment variable module_path, and try loading\n \\ the kernel again.\n\n \\ First, save module_path value\n modulepath getenv saveenv dup -1 = if 0 swap then 2>r\n\n \\ Sets the new value\n 2dup modulepath setenv\n\n \\ Try to load the kernel\n s\" load ${kernel} ${temp_options}\" ['] evaluate catch\n if ( load failed yet again )\n\t\\ Remove garbage from the stack\n\t2drop\n\n\t\\ Try prepending \/boot\/\n\tbootpath 2over nip over + allocate\n\tif ( out of memory )\n\t 2drop 2drop\n\t 2r> restoreenv\n\t 100 exit\n\tthen\n\n\t0 2swap strcat 2swap strcat\n\t2dup modulepath setenv\n\n\tdrop free if ( freeing memory error )\n\t 2drop\n\t 2r> restoreenv\n\t 100 exit\n\tthen\n \n\t\\ Now, once more, try to load the kernel\n\ts\" load ${kernel} ${temp_options}\" ['] evaluate catch\n\tif ( failed once more )\n\t 2drop\n\t 2r> restoreenv\n\t 100 exit\n\tthen\n\n else ( we found the kernel on the path passed )\n\n\t2drop ( discard command line arguments )\n\n then ( could not load kernel from directory passed )\n\n \\ Load the remaining modules, if the kernel was loaded at all\n ['] load_modules catch if 2r> restoreenv 100 exit then\n\n \\ Return 0 to indicate success\n 0\n\n \\ Keep new module_path\n 2r> freeenv\n\n exit\n then ( could not load kernel with name passed )\n\n 2drop ( discard command line arguments )\n\n else ( try just a straight-forward kernel load )\n s\" load ${kernel} ${temp_options}\" ['] evaluate catch\n if ( kernel load failed ) 2drop 100 exit then\n\n then ( there are command line arguments )\n\n \\ Load the remaining modules, if the kernel was loaded at all\n ['] load_modules catch if 100 exit then\n\n \\ Return 0 to indicate success\n 0\n;\n\nonly forth also support-functions also builtins definitions\n\n: boot\n load-conf\n ?dup 0= if 0 1 boot then\n;\n\n: boot-conf\n load-conf\n ?dup 0= if 0 1 autoboot then\n;\n\nalso forth definitions also builtins\nbuiltin: boot\nbuiltin: boot-conf\nonly forth definitions also support-functions\n\n\\ ***** check-password\n\\\n\\\tIf a password was defined, execute autoboot and ask for\n\\\tpassword if autoboot returns.\n\n: check-password\n password .addr @ if\n 0 autoboot\n false >r\n begin\n bell emit bell emit\n .\" Password: \"\n password .len @ read-password\n dup password .len @ = if\n 2dup password .addr @ password .len @\n compare 0= if r> drop true >r then\n then\n drop free drop\n r@\n until\n r> drop\n then\n;\n\n\\ ***** start\n\\\n\\ Initializes support.4th global variables, sets loader_conf_files,\n\\ process conf files, and, if any one such file was succesfully\n\\ read to the end, load kernel and modules.\n\n: start ( -- ) ( throws: abort & user-defined )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n \\ Will *NOT* try to load kernel and modules if no configuration file\n \\ was succesfully loaded!\n any_conf_read? if\n load_kernel\n load_modules\n then\n;\n\n\\ ***** initialize\n\\\n\\\tOverrides support.4th initialization word with one that does\n\\\teverything start one does, short of loading the kernel and\n\\\tmodules. Returns a flag\n\n: initialize ( -- flag )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n any_conf_read?\n;\n\n\\ ***** read-conf\n\\\n\\\tRead a configuration file, whose name was specified on the command\n\\\tline, if interpreted, or given on the stack, if compiled in.\n\n: (read-conf) ( addr len -- )\n conf_files .addr @ ?dup if free abort\" Fatal error freeing memory\" then\n strdup conf_files .len ! conf_files .addr !\n include_conf_files \\ Will recurse on new loader_conf_files definitions\n;\n\n: read-conf ( | addr len -- ) ( throws: abort & user-defined )\n state @ if\n \\ Compiling\n postpone (read-conf)\n else\n \\ Interpreting\n bl parse (read-conf)\n then\n; immediate\n\n\\ ***** enable-module\n\\\n\\ Turn a module loading on.\n\n: enable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n true r> module.flag !\n .\" will be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** disable-module\n\\\n\\ Turn a module loading off.\n\n: disable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n false r> module.flag !\n .\" will not be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** toggle-module\n\\\n\\ Turn a module loading on\/off.\n\n: toggle-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n r@ module.flag @ 0= dup r> module.flag !\n if\n .\" will be loaded.\" cr\n else\n .\" will not be loaded.\" cr\n then\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** show-module\n\\\n\\\tShow loading information about a module.\n\n: show-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n .\" Name: \" r@ module.name dup .addr @ swap .len @ type cr\n .\" Path: \" r@ module.loadname dup .addr @ swap .len @ type cr\n .\" Type: \" r@ module.type dup .addr @ swap .len @ type cr\n .\" Flags: \" r@ module.args dup .addr @ swap .len @ type cr\n .\" Before load: \" r@ module.beforeload dup .addr @ swap .len @ type cr\n .\" After load: \" r@ module.afterload dup .addr @ swap .len @ type cr\n .\" Error: \" r@ module.loaderror dup .addr @ swap .len @ type cr\n .\" Status: \" r> module.flag @ if .\" Load\" else .\" Don't load\" then cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ Words to be used inside configuration files\n\n: retry false ; \\ For use in load error commands\n: ignore true ; \\ For use in load error commands\n\n\\ Return to strict forth vocabulary\n\nonly forth also\n\n","old_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\ns\" arch-alpha\" environment? [if] [if]\n\ts\" loader_version\" environment? [if]\n\t\t3 < [if]\n\t\t\t.( Loader version 0.3+ required) cr\n\t\t\tabort\n\t\t[then]\n\t[else]\n\t\t.( Could not get loader version!) cr\n\t\tabort\n\t[then]\n[then] [then]\n\ns\" arch-i386\" environment? [if] [if]\n\ts\" loader_version\" environment? [if]\n\t\t8 < [if]\n\t\t\t.( Loader version 0.8+ required) cr\n\t\t\tabort\n\t\t[then]\n\t[else]\n\t\t.( Could not get loader version!) cr\n\t\tabort\n\t[then]\n[then] [then]\n\ninclude \/boot\/support.4th\n\nonly forth definitions also support-functions\n\n\\ ***** boot-conf\n\\\n\\\tPrepares to boot as specified by loaded configuration files.\n\nalso support-functions definitions\n\n: bootpath s\" \/boot\/\" ;\n: modulepath s\" module_path\" ;\n: saveenv ( addr len | 0 -1 -- addr' len | 0 -1 )\n dup -1 = if exit then\n dup allocate abort\" Out of memory\"\n swap 2dup 2>r\n move\n 2r>\n;\n: freeenv ( addr len | 0 -1 )\n -1 = if drop else free abort\" Freeing error\" then\n;\n: restoreenv ( addr len | 0 -1 -- )\n dup -1 = if ( it wasn't set )\n 2drop\n modulepath unsetenv\n else\n over >r\n modulepath setenv\n r> free abort\" Freeing error\"\n then\n;\n\nonly forth also support-functions also builtins definitions\n\n: boot-conf ( args 1 | 0 \"args\" -- flag )\n 0 1 unload drop\n\n 0= if ( interpreted )\n \\ Get next word on the command line\n bl word count\n ?dup 0= if ( there wasn't anything )\n drop 0\n else ( put in the number of strings )\n 1\n then\n then ( interpreted )\n\n if ( there are arguments )\n \\ Try to load the kernel\n s\" kernel_options\" getenv dup -1 = if drop 2dup 1 else 2over 2 then\n\n 1 load if ( load command failed )\n \\ Remove garbage from the stack\n\n \\ Set the environment variable module_path, and try loading\n \\ the kernel again.\n\n \\ First, save module_path value\n modulepath getenv saveenv dup -1 = if 0 swap then 2>r\n\n \\ Sets the new value\n 2dup modulepath setenv\n\n \\ Try to load the kernel\n s\" load ${kernel} ${kernel_options}\" ['] evaluate catch\n if ( load failed yet again )\n\t\\ Remove garbage from the stack\n\t2drop\n\n\t\\ Try prepending \/boot\/\n\tbootpath 2over nip over + allocate\n\tif ( out of memory )\n\t 2drop 2drop\n\t 2r> restoreenv\n\t 100 exit\n\tthen\n\n\t0 2swap strcat 2swap strcat\n\t2dup modulepath setenv\n\n\tdrop free if ( freeing memory error )\n\t 2drop\n\t 2r> restoreenv\n\t 100 exit\n\tthen\n \n\t\\ Now, once more, try to load the kernel\n\ts\" load ${kernel} ${kernel_options}\" ['] evaluate catch\n\tif ( failed once more )\n\t 2drop\n\t 2r> restoreenv\n\t 100 exit\n\tthen\n\n else ( we found the kernel on the path passed )\n\n\t2drop ( discard command line arguments )\n\n then ( could not load kernel from directory passed )\n\n \\ Load the remaining modules, if the kernel was loaded at all\n ['] load_modules catch if 2r> restoreenv 100 exit then\n\n \\ Call autoboot to perform the booting\n 0 1 autoboot\n\n \\ Keep new module_path\n 2r> freeenv\n\n exit\n then ( could not load kernel with name passed )\n\n 2drop ( discard command line arguments )\n\n else ( try just a straight-forward kernel load )\n s\" load ${kernel} ${kernel_options}\" ['] evaluate catch\n if ( kernel load failed ) 2drop 100 exit then\n\n then ( there are command line arguments )\n\n \\ Load the remaining modules, if the kernel was loaded at all\n ['] load_modules catch if 100 exit then\n\n \\ Call autoboot to perform the booting\n 0 1 autoboot\n;\n\nalso forth definitions\nbuiltin: boot-conf\nonly forth definitions also support-functions\n\n\\ ***** check-password\n\\\n\\\tIf a password was defined, execute autoboot and ask for\n\\\tpassword if autoboot returns.\n\n: check-password\n password .addr @ if\n 0 autoboot\n false >r\n begin\n bell emit bell emit\n .\" Password: \"\n password .len @ read-password\n dup password .len @ = if\n 2dup password .addr @ password .len @\n compare 0= if r> drop true >r then\n then\n drop free drop\n r@\n until\n r> drop\n then\n;\n\n\\ ***** start\n\\\n\\ Initializes support.4th global variables, sets loader_conf_files,\n\\ process conf files, and, if any one such file was succesfully\n\\ read to the end, load kernel and modules.\n\n: start ( -- ) ( throws: abort & user-defined )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n \\ Will *NOT* try to load kernel and modules if no configuration file\n \\ was succesfully loaded!\n any_conf_read? if\n load_kernel\n load_modules\n then\n;\n\n\\ ***** initialize\n\\\n\\\tOverrides support.4th initialization word with one that does\n\\\teverything start one does, short of loading the kernel and\n\\\tmodules. Returns a flag\n\n: initialize ( -- flag )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n any_conf_read?\n;\n\n\\ ***** read-conf\n\\\n\\\tRead a configuration file, whose name was specified on the command\n\\\tline, if interpreted, or given on the stack, if compiled in.\n\n: (read-conf) ( addr len -- )\n conf_files .addr @ ?dup if free abort\" Fatal error freeing memory\" then\n strdup conf_files .len ! conf_files .addr !\n include_conf_files \\ Will recurse on new loader_conf_files definitions\n;\n\n: read-conf ( | addr len -- ) ( throws: abort & user-defined )\n state @ if\n \\ Compiling\n postpone (read-conf)\n else\n \\ Interpreting\n bl parse (read-conf)\n then\n; immediate\n\n\\ ***** enable-module\n\\\n\\ Turn a module loading on.\n\n: enable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n true r> module.flag !\n .\" will be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** disable-module\n\\\n\\ Turn a module loading off.\n\n: disable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n false r> module.flag !\n .\" will not be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** toggle-module\n\\\n\\ Turn a module loading on\/off.\n\n: toggle-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n r@ module.flag @ 0= dup r> module.flag !\n if\n .\" will be loaded.\" cr\n else\n .\" will not be loaded.\" cr\n then\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** show-module\n\\\n\\\tShow loading information about a module.\n\n: show-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n .\" Name: \" r@ module.name dup .addr @ swap .len @ type cr\n .\" Path: \" r@ module.loadname dup .addr @ swap .len @ type cr\n .\" Type: \" r@ module.type dup .addr @ swap .len @ type cr\n .\" Flags: \" r@ module.args dup .addr @ swap .len @ type cr\n .\" Before load: \" r@ module.beforeload dup .addr @ swap .len @ type cr\n .\" After load: \" r@ module.afterload dup .addr @ swap .len @ type cr\n .\" Error: \" r@ module.loaderror dup .addr @ swap .len @ type cr\n .\" Status: \" r> module.flag @ if .\" Load\" else .\" Don't load\" then cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ Words to be used inside configuration files\n\n: retry false ; \\ For use in load error commands\n: ignore true ; \\ For use in load error commands\n\n\\ Return to strict forth vocabulary\n\nonly forth also\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"3be5fb23de0736b11f7353c468fea8354ac1ce5f","subject":"Define a new SVC for restarting forth.","message":"Define a new SVC for restarting forth.","repos":"rbsexton\/sockpuppet,rbsexton\/sockpuppet","old_file":"forth\/SAPI-core.fth","new_file":"forth\/SAPI-core.fth","new_contents":"\\ Wrappers for SAPI Core functions\n\\ SVC 0: Return the version of the API in use.\n\\ SVC 1: Return the address of the shared variables table\n\\ SVC 2: putchar\n\\ SVC 3: getchar\n\\ SVC 4: charsavail\n\n\\ SVC 5: LaunchUserApp\n\\ SVC 6: Reserved\n\\ SVC 7: Reserved\n\n\\ SVC 8: Watchdog Refresh\n\\ SVC 9: Return Millisecond ticker value.\n\\ SVC 10: The number of CPU cycles consumed in the last second.\n\n\\ 2-4 are for use by the serial io routines, and are \n\\ defined elsewhere.\n\n\\ Note that the system call number is embedded into the instruction,\n\\ so this is not so easily parameterized.\n\n#0 equ SAPI_VEC_VERSION\n#1 equ SAPI_VEC_VARS\n#2 equ SAPI_VEC_PUTCHAR\n#3 equ SAPI_VEC_GETCHAR\n#4 equ SAPI_VEC_CHARSAVAIL\n#5 equ SAPI_VEC_STARTAPP\n\n#8 equ SAPI_VEC_PETWATCHDOG\n#9 equ SAPI_VEC_USAGE\n#10 equ SAPI_VEC_GETMS\n\n\\ **********************************************************************\n\\ SVC 0: Return the version of the API in use.\n\\ **********************************************************************\nCODE SAPI-Version \\ -- n \n\t\\ Push TOS, and place the result there.\t\n\tsvc # SAPI_VEC_VERSION \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 1: Get the address of the shared variable list\n\\ **********************************************************************\nCODE GetSharedVars \\ -- n \n\tsvc # SAPI_VEC_VARS \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 5: Do a stack switch and startup the user App.\n\\ **********************************************************************\nCODE StartForth \\ -- \n\tsvc # SAPI_VEC_STARTAPP\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 8: Refresh the watchdog\n\\ **********************************************************************\nCODE PetWatchDog \\ -- \n\tsvc # SAPI_VEC_PETWATCHDOG\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 9: Return Millisecond ticker value.\n\\ **********************************************************************\nCODE Ticks \\ -- n \n\tsvc # SAPI_VEC_GETMS\n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 10: The number of CPU cycles consumed in the last second.\n\\ **********************************************************************\nCODE GetUsage \\ -- n \n\tsvc # SAPI_VEC_USAGE\n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n","old_contents":"\\ Wrappers for SAPI Core functions\n\\ SVC 0: Return the version of the API in use.\n\\ SVC 1: Return the address of the shared variables table\n\\ SVC 2: putchar\n\\ SVC 3: getchar\n\\ SVC 4: charsavail\n\n\\ SVC 5: Reserved\n\\ SVC 6: Reserved\n\\ SVC 7: Reserved\n\n\\ SVC 8: Watchdog Refresh\n\\ SVC 9: Return Millisecond ticker value.\n\\ SVC 10: The number of CPU cycles consumed in the last second.\n\n\\ 2-4 are for use by the serial io routines, and are \n\\ defined elsewhere.\n\n\\ Note that the system call number is embedded into the instruction,\n\\ so this is not so easily parameterized.\n\n#0 equ SAPI_VEC_VERSION\n#1 equ SAPI_VEC_VARS\n#2 equ SAPI_VEC_PUTCHAR\n#3 equ SAPI_VEC_GETCHAR\n#4 equ SAPI_VEC_CHARSAVAIL\n\n#8 equ SAPI_VEC_PETWATCHDOG\n#9 equ SAPI_VEC_USAGE\n#10 equ SAPI_VEC_GETMS\n\n\\ **********************************************************************\n\\ SVC 0: Return the version of the API in use.\n\\ **********************************************************************\nCODE SAPI-Version \\ -- n \n\t\\ Push TOS, and place the result there.\t\n\tsvc # SAPI_VEC_VERSION \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 1: Get the address of the shared variable list\n\\ **********************************************************************\nCODE GetSharedVars \\ -- n \n\tsvc # SAPI_VEC_VARS \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 8: Refresh the watchdog\n\\ **********************************************************************\nCODE PetWatchDog \\ -- \n\tsvc # SAPI_VEC_PETWATCHDOG\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 9: Return Millisecond ticker value.\n\\ **********************************************************************\nCODE Ticks \\ -- n \n\tsvc # SAPI_VEC_GETMS\n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 10: The number of CPU cycles consumed in the last second.\n\\ **********************************************************************\nCODE GetUsage \\ -- n \n\tsvc # SAPI_VEC_USAGE\n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"7da86fa04ce770ab0d2c00d8afee7af6ae97106e","subject":"Modify boot-conf so it can take a kernel or directory name as a parameter and dtrt.","message":"Modify boot-conf so it can take a kernel or directory name as\na parameter and dtrt.\n\nAlso, make boot-conf always unload first. There wasn't really any\npoint in not doing this, as the kernel _has_ to be loaded before\nany other modules.\n\nTested by: dwhite\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/loader.4th","new_file":"sys\/boot\/forth\/loader.4th","new_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\ninclude \/boot\/support.4th\n\nonly forth definitions also support-functions\n\n\\ ***** boot-conf\n\\\n\\\tPrepares to boot as specified by loaded configuration files.\n\nalso support-functions definitions\n\n: bootpath s\" \/boot\/\" ;\n: modulepath s\" module_path\" ;\n: saveenv ( addr len | 0 -1 -- addr' len | 0 -1 )\n dup -1 = if exit then\n dup allocate abort\" Out of memory\"\n swap 2dup 2>r\n move\n 2r>\n;\n: freeenv ( addr len | 0 -1 )\n -1 = if drop else free abort\" Freeing error\" then\n;\n: restoreenv ( addr len | 0 -1 -- )\n dup -1 = if ( it wasn't set )\n 2drop\n modulepath unsetenv\n else\n over >r\n modulepath setenv\n r> free abort\" Freeing error\"\n then\n;\n\nonly forth also support-functions also builtins definitions\n\n: boot-conf ( args 1 | 0 \"args\" -- flag )\n 0 1 unload drop\n\n 0= if ( interpreted )\n \\ Get next word on the command line\n bl word count\n ?dup 0= if ( there wasn't anything )\n drop 0\n else ( put in the number of strings )\n 1\n then\n then ( interpreted )\n\n if ( there are arguments )\n \\ Try to load the kernel\n s\" kernel_options\" getenv dup -1 = if drop 2dup 1 else 2over 2 then\n\n 1 load if ( load command failed )\n \\ Remove garbage from the stack\n\n \\ Set the environment variable module_path, and try loading\n \\ the kernel again.\n\n \\ First, save module_path value\n modulepath getenv saveenv dup -1 = if 0 swap then 2>r\n\n \\ Sets the new value\n 2dup modulepath setenv\n\n \\ Try to load the kernel\n s\" load ${kernel} ${kernel_options}\" ['] evaluate catch\n if ( load failed yet again )\n\t\\ Remove garbage from the stack\n\t2drop\n\n\t\\ Try prepending \/boot\/\n\tbootpath 2over nip over + allocate\n\tif ( out of memory )\n\t 2drop 2drop\n\t 2r> restoreenv\n\t 100 exit\n\tthen\n\n\t0 2swap strcat 2swap strcat\n\t2dup modulepath setenv\n\n\tdrop free if ( freeing memory error )\n\t 2drop\n\t 2r> restoreenv\n\t 100 exit\n\tthen\n \n\t\\ Now, once more, try to load the kernel\n\ts\" load ${kernel} ${kernel_options}\" ['] evaluate catch\n\tif ( failed once more )\n\t 2drop\n\t 2r> restoreenv\n\t 100 exit\n\tthen\n\n else ( we found the kernel on the path passed )\n\n\t2drop ( discard command line arguments )\n\n then ( could not load kernel from directory passed )\n\n \\ Load the remaining modules, if the kernel was loaded at all\n ['] load_modules catch if 2r> restoreenv 100 exit then\n\n \\ Call autoboot to perform the booting\n 0 1 autoboot\n\n \\ Keep new module_path\n 2r> freeenv\n\n exit\n then ( could not load kernel with name passed )\n\n 2drop ( discard command line arguments )\n\n else ( try just a straight-forward kernel load )\n s\" load ${kernel} ${kernel_options}\" ['] evaluate catch\n if ( kernel load failed ) 2drop 100 exit then\n\n then ( there are command line arguments )\n\n \\ Load the remaining modules, if the kernel was loaded at all\n ['] load_modules catch if 100 exit then\n\n \\ Call autoboot to perform the booting\n 0 1 autoboot\n;\n\nalso forth definitions\nbuiltin: boot-conf\nonly forth definitions also support-functions\n\n\\ ***** check-password\n\\\n\\\tIf a password was defined, execute autoboot and ask for\n\\\tpassword if autoboot returns.\n\n: check-password\n password .addr @ if\n 0 autoboot\n false >r\n begin\n bell emit bell emit\n .\" Password: \"\n password .len @ read-password\n dup password .len @ = if\n 2dup password .addr @ password .len @\n compare 0= if r> drop true >r then\n then\n drop free drop\n r@\n until\n r> drop\n then\n;\n\n\\ ***** start\n\\\n\\ Initializes support.4th global variables, sets loader_conf_files,\n\\ process conf files, and, if any one such file was succesfully\n\\ read to the end, load kernel and modules.\n\n: start ( -- ) ( throws: abort & user-defined )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n \\ Will *NOT* try to load kernel and modules if no configuration file\n \\ was succesfully loaded!\n any_conf_read? if\n load_kernel\n load_modules\n then\n;\n\n\\ ***** initialize\n\\\n\\\tOverrides support.4th initialization word with one that does\n\\\teverything start one does, short of loading the kernel and\n\\\tmodules. Returns a flag\n\n: initialize ( -- flag )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n any_conf_read?\n;\n\n\\ ***** read-conf\n\\\n\\\tRead a configuration file, whose name was specified on the command\n\\\tline, if interpreted, or given on the stack, if compiled in.\n\n: (read-conf) ( addr len -- )\n conf_files .addr @ ?dup if free abort\" Fatal error freeing memory\" then\n strdup conf_files .len ! conf_files .addr !\n include_conf_files \\ Will recurse on new loader_conf_files definitions\n;\n\n: read-conf ( | addr len -- ) ( throws: abort & user-defined )\n state @ if\n \\ Compiling\n postpone (read-conf)\n else\n \\ Interpreting\n bl parse (read-conf)\n then\n; immediate\n\n\\ ***** enable-module\n\\\n\\ Turn a module loading on.\n\n: enable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n true r> module.flag !\n .\" will be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** disable-module\n\\\n\\ Turn a module loading off.\n\n: disable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n false r> module.flag !\n .\" will not be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** toggle-module\n\\\n\\ Turn a module loading on\/off.\n\n: toggle-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n r@ module.flag @ 0= dup r> module.flag !\n if\n .\" will be loaded.\" cr\n else\n .\" will not be loaded.\" cr\n then\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** show-module\n\\\n\\\tShow loading information about a module.\n\n: show-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n .\" Name: \" r@ module.name dup .addr @ swap .len @ type cr\n .\" Path: \" r@ module.loadname dup .addr @ swap .len @ type cr\n .\" Type: \" r@ module.type dup .addr @ swap .len @ type cr\n .\" Flags: \" r@ module.args dup .addr @ swap .len @ type cr\n .\" Before load: \" r@ module.beforeload dup .addr @ swap .len @ type cr\n .\" After load: \" r@ module.afterload dup .addr @ swap .len @ type cr\n .\" Error: \" r@ module.loaderror dup .addr @ swap .len @ type cr\n .\" Status: \" r> module.flag @ if .\" Load\" else .\" Don't load\" then cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ Words to be used inside configuration files\n\n: retry false ; \\ For use in load error commands\n: ignore true ; \\ For use in load error commands\n\n\\ Return to strict forth vocabulary\n\nonly forth also\n\n","old_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\ninclude \/boot\/support.4th\n\nonly forth definitions also support-functions\n\n\\ ***** boot-conf\n\\\n\\\tPrepares to boot as specified by loaded configuration files.\n\n: boot-conf\n load_kernel\n load_modules\n 0 autoboot\n;\n\n\\ ***** check-password\n\\\n\\\tIf a password was defined, execute autoboot and ask for\n\\\tpassword if autoboot returns.\n\n: check-password\n password .addr @ if\n 0 autoboot\n false >r\n begin\n bell emit bell emit\n .\" Password: \"\n password .len @ read-password\n dup password .len @ = if\n 2dup password .addr @ password .len @\n compare 0= if r> drop true >r then\n then\n drop free drop\n r@\n until\n r> drop\n then\n;\n\n\\ ***** start\n\\\n\\ Initializes support.4th global variables, sets loader_conf_files,\n\\ process conf files, and, if any one such file was succesfully\n\\ read to the end, load kernel and modules.\n\n: start ( -- ) ( throws: abort & user-defined )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n \\ Will *NOT* try to load kernel and modules if no configuration file\n \\ was succesfully loaded!\n any_conf_read? if\n load_kernel\n load_modules\n then\n;\n\n\\ ***** initialize\n\\\n\\\tOverrides support.4th initialization word with one that does\n\\\teverything start one does, short of loading the kernel and\n\\\tmodules. Returns a flag\n\n: initialize ( -- flag )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n any_conf_read?\n;\n\n\\ ***** read-conf\n\\\n\\\tRead a configuration file, whose name was specified on the command\n\\\tline, if interpreted, or given on the stack, if compiled in.\n\n: (read-conf) ( addr len -- )\n conf_files .addr @ ?dup if free abort\" Fatal error freeing memory\" then\n strdup conf_files .len ! conf_files .addr !\n include_conf_files \\ Will recurse on new loader_conf_files definitions\n;\n\n: read-conf ( | addr len -- ) ( throws: abort & user-defined )\n state @ if\n \\ Compiling\n postpone (read-conf)\n else\n \\ Interpreting\n bl parse (read-conf)\n then\n; immediate\n\n\\ ***** enable-module\n\\\n\\ Turn a module loading on.\n\n: enable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n true r> module.flag !\n .\" will be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** disable-module\n\\\n\\ Turn a module loading off.\n\n: disable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n false r> module.flag !\n .\" will not be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** toggle-module\n\\\n\\ Turn a module loading on\/off.\n\n: toggle-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n r@ module.flag @ 0= dup r> module.flag !\n if\n .\" will be loaded.\" cr\n else\n .\" will not be loaded.\" cr\n then\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** show-module\n\\\n\\\tShow loading information about a module.\n\n: show-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n .\" Name: \" r@ module.name dup .addr @ swap .len @ type cr\n .\" Path: \" r@ module.loadname dup .addr @ swap .len @ type cr\n .\" Type: \" r@ module.type dup .addr @ swap .len @ type cr\n .\" Flags: \" r@ module.args dup .addr @ swap .len @ type cr\n .\" Before load: \" r@ module.beforeload dup .addr @ swap .len @ type cr\n .\" After load: \" r@ module.afterload dup .addr @ swap .len @ type cr\n .\" Error: \" r@ module.loaderror dup .addr @ swap .len @ type cr\n .\" Status: \" r> module.flag @ if .\" Load\" else .\" Don't load\" then cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ Words to be used inside configuration files\n\n: retry false ; \\ For use in load error commands\n: ignore true ; \\ For use in load error commands\n\n\\ Return to strict forth vocabulary\n\nonly forth also\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"3331fc39570ef05111a9db5e5ddf1a8cb8495174","subject":"Move defn. of SEE further up in event of failure","message":"Move defn. of SEE further up in event of failure","repos":"rm-hull\/byok,rm-hull\/byok,rm-hull\/byok,rm-hull\/byok","old_file":"forth\/src\/forth\/system.fth","new_file":"forth\/src\/forth\/system.fth","new_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\ \n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n \n: COUNT dup 1+ swap c@ ;\n\n\\ Miscellaneous support words\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: CELL+ ( n -- n+cell ) cell + ;\n: CELL- ( n -- n-cell ) cell - ;\n: CELL* ( n -- n*cell ) cells ;\n\n: CHAR+ ( n -- n+size_of_char ) 1+\n\\ : CHARS ( n -- n*size_of_char, don't do anything ) ; immediate\n\n\\ useful stack manipulation words\n: -ROT ( a b c -- c a b ) rot rot ;\n: 3DUP ( a b c -- a b c a b c ) 2 pick 2 pick 2 pick ;\n\n\\ ------------------------------------------------------------------\n: ID. ( nfa -- ) count 31 and type ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: PAD ( -- addr ) here 128 + ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: ? ( -- ) @ . ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ ' (lit) , cell 1- , ] +\n [ ' (lit) , cell 1- invert , ] and ;\n\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n: ALLOT ( nbytes -- , allot space in dictionary ) dp +! align ;\n\n: C, ( c -- ) here c! 1 dp +! ;\n\\ : W, ( w -- ) dp @ even-up dup dp ! w! 2 dp +! ;\n\\ : , ( n -- , lay into dictionary ) align here ! cell allot ;\n\n: SEE ( -- )\n ' dup\n 16 + @ \\ offset in execution token for alloc size\n cells swap >body swap\n disassemble ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token )\n [compile] literal ( compile a call to literal )\n ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n: :NONAME ( -- xt , begin compilation of headerless secondary ) align here ] ;\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick ) \n ?comp ' [compile] literal \n; immediate\n\n: RECURSE ( ? -- ? , call the word currently being defined ) \n latest compile, \n; immediate\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 ) swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 ) dup cell+ @ swap @ ;\n\n: \/STRING ( addr len n -- addr' len' ) over min rot over + -rot - ;\n: PLACE ( addr len to -- , move string ) 3dup 1+ swap cmove c! drop ;\n\n: ASCII ( -- char, state smart )\n bl parse drop c@\n state @ 1 =\n IF [compile] literal\n ELSE \n THEN \n; immediate\n\n: CHAR ( -- char , interpret mode ) bl parse drop c@ ;\n: [CHAR] ( -- char , for compile mode )\n char [compile] literal \n; immediate\n\n: 'word ( -- addr ) here ;\n\n: (C\") ( -- $addr ) r> dup count + aligned >r ;\n: (S\") ( -- c-addr cnt ) r> count 2dup + aligned >r ;\n: (.\") ( -- , type following string ) r> count 2dup + aligned >r type ;\n: \", ( addr len -- , place string into dict ) tuck 'word place 1+ allot align ;\n: ,\" ( -- ) 34 parse \", ;\n\n: .( ( --, type string delimited by parens )\n 41 parse type\n; immediate\n\n: .\" ( -- , type string )\n state @ 1 =\n IF compile (.\") ,\"\n ELSE 34 parse type\n THEN \n; immediate\n\n: CLEARSTACK ( i*x -- )\n BEGIN depth\n WHILE drop\n REPEAT ;\n\nvariable pictured_output \\ hidden?\nvariable pictured_output_len \\ hidden?\n\n: <# ( -- ) pad pictured_output ! 0 pictured_output_len ! ;\n: #> ( -- addr n ) drop pictured_output @ pictured_output_len @ ;\n\n: HOLD ( c -- )\n pictured_output @ dup dup 1+ pictured_output_len @ cmove c!\n 1 pictured_output_len +!\n;\n\n: DIGIT ( n -- ascii )\n dup 10 < IF 48 ELSE 87 THEN + ;\n\n: SIGN ( n -- ) < 0 IF 45 hold THEN\n;\n: # ( n -- n )\n base @ \/mod swap digit hold ;\n\n: #S ( n -- )\n BEGIN base @ \/mod dup \n WHILE swap digit hold \n REPEAT \n digit hold ;\n\n","old_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\ \n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n \n: COUNT dup 1+ swap c@ ;\n\n\\ Miscellaneous support words\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: CELL+ ( n -- n+cell ) cell + ;\n: CELL- ( n -- n-cell ) cell - ;\n: CELL* ( n -- n*cell ) cells ;\n\n: CHAR+ ( n -- n+size_of_char ) 1+\n\\ : CHARS ( n -- n*size_of_char, don't do anything ) ; immediate\n\n\\ useful stack manipulation words\n: -ROT ( a b c -- c a b ) rot rot ;\n: 3DUP ( a b c -- a b c a b c ) 2 pick 2 pick 2 pick ;\n\n\\ ------------------------------------------------------------------\n: ID. ( nfa -- ) count 31 and type ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: PAD ( -- addr ) here 128 + ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: ? ( -- ) @ . ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ ' (lit) , cell 1- , ] +\n [ ' (lit) , cell 1- invert , ] and ;\n\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n: ALLOT ( nbytes -- , allot space in dictionary ) dp +! align ;\n\n: C, ( c -- ) here c! 1 dp +! ;\n\\ : W, ( w -- ) dp @ even-up dup dp ! w! 2 dp +! ;\n\\ : , ( n -- , lay into dictionary ) align here ! cell allot ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token ) \n [compile] literal ( compile a call to literal )\n ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n: :NONAME ( -- xt , begin compilation of headerless secondary ) align here ] ;\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick ) \n ?comp ' [compile] literal \n; immediate\n\n: RECURSE ( ? -- ? , call the word currently being defined ) \n latest compile, \n; immediate\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 ) swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 ) dup cell+ @ swap @ ;\n\n: \/STRING ( addr len n -- addr' len' ) over min rot over + -rot - ;\n: PLACE ( addr len to -- , move string ) 3dup 1+ swap cmove c! drop ;\n\n: ASCII ( -- char, state smart )\n bl parse drop c@\n state @ 1 =\n IF [compile] literal\n ELSE \n THEN \n; immediate\n\n: CHAR ( -- char , interpret mode ) bl parse drop c@ ;\n: [CHAR] ( -- char , for compile mode )\n char [compile] literal \n; immediate\n\n: 'word ( -- addr ) here ;\n\n: (C\") ( -- $addr ) r> dup count + aligned >r ;\n: (S\") ( -- c-addr cnt ) r> count 2dup + aligned >r ;\n: (.\") ( -- , type following string ) r> count 2dup + aligned >r type ;\n: \", ( addr len -- , place string into dict ) tuck 'word place 1+ allot align ;\n: ,\" ( -- ) 34 parse \", ;\n\n: .( ( --, type string delimited by parens )\n 41 parse type\n; immediate\n\n: .\" ( -- , type string )\n state @ 1 =\n IF compile (.\") ,\"\n ELSE 34 parse type\n THEN \n; immediate\n\n: SEE ( -- )\n ' dup\n 16 + @ \\ offset in execution token for alloc size\n cells swap >body swap\n disassemble ;\n \n: CLEARSTACK ( i*x -- )\n BEGIN depth\n WHILE drop\n REPEAT ;\n\nvariable pictured_output \\ hidden?\nvariable pictured_output_len \\ hidden?\n\n: <# ( -- ) pad pictured_output ! 0 pictured_output_len ! ;\n: #> ( -- addr n ) drop pictured_output @ pictured_output_len @ ;\n\n: HOLD ( c -- )\n pictured_output @ dup dup 1+ pictured_output_len @ cmove c!\n 1 pictured_output_len +!\n;\n\n: DIGIT ( n -- ascii )\n dup 10 < IF 48 ELSE 87 THEN + ;\n\n: SIGN ( n -- ) < 0 IF 45 hold THEN\n;\n: # ( n -- n )\n base @ \/mod swap digit hold ;\n\n: #S ( n -- )\n BEGIN base @ \/mod dup \n WHILE swap digit hold \n REPEAT \n digit hold ;\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"30e376702e3a86ade252dc4de3abf44fd1067a8c","subject":"Not needed.","message":"Not needed.","repos":"rbsexton\/sockpuppet,rbsexton\/sockpuppet","old_file":"forth\/serCM3_sapi_p.fth","new_file":"forth\/serCM3_sapi_p.fth","new_contents":"\\ serCM3_sapi_p.fth - SAPI polled RX, polled TX, serial communication drivers\n\\ Written to run against the SockPuppet API.\n\n((\nAdapted from: the LPC polled driver.\n))\n\nonly forth definitions\nvariable cnt.pause \n\n\\ ==============\n\\ *! serCM3_sapi_p\n\\ *T SAPI polled serial driver\n\\ ==============\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\n\\ ** using the internal UARTs via the SAPI call layer.\n\n\n\\ ****************\n\\ *S Configuration\n\\ ****************\n\\ *P Configuration is managed by the SAPI\n\n\\ ********\n\\ *S Tools\n\\ ********\n\ntarget\n\n\\ ********************\n\\ *S Serial primitives\n\\ ********************\n\n0 value sercallback \n\ninternal\n\n: +FaultConsole\t( -- ) ;\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\n\\ ** for more details.\n\ntarget\n\nCODE (seremitfc)\t\\ char base --\n\\ *G Service call for a single char - just fill in the registers\n\\ from the stack and make the call, and get back the flow control feedback\n\\ Put TOS into r0, pull r1 off the stack, and refresh the stack.\n\tmov r0, tos\n\tldr r1, [ psp ], # 4\t\n\tsvc # SAPI_VEC_PUTCHAR\t\n\tmov tos, r0\n next,\nEND-CODE\n\n: (seremit)\t\\ char base -- \n\\ *G Wrapped call that checks for throttling, and if so,\n\\ calls PAUSE to let another task run. Count these events for debugging purposes.\n\t(seremitfc)\n\t0<> IF 1 cnt.pause +! #5 ms THEN\n\t;\n\n: (sertype)\t\\ caddr len base --\n\\ *G Transmit a string on the given UART.\n -rot bounds\n ?do i c@ over (seremit) loop\n drop\n;\n\n: (sercr)\t\\ base --\n\\ *G Transmit a CR\/LF pair on the given UART.\n $0D over (seremit) $0A swap (seremit)\n;\n\nCODE (sergetchar) \\ base -- c\n\\ *G Get a character from the port\n\tmov r0, tos\t\n\tsvc # SAPI_VEC_GETCHAR\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE (serkey?) \\ base -- t\/f\n\\ *G Return true if the given UART has a character avilable to read.\n\\ The call returns 0 or 1. \n\tmov r0, tos\n\tsvc # SAPI_VEC_CHARSAVAIL\t\t\n\tmov tos, r0\n\tnext,\t\nEND-CODE\n\n: (serkey-basic)\n\tbegin pause \n\tdup (serkey?) until \n\t(sergetchar)\n;\n\n: (serkey-sleep?)\n\tself tcb.bbstatus @ over 1 setiocallback drop ( base oldcb )\n\tself halt \n\tdup (serkey?) IF self restart ELSE PAUSE THEN \\ We are now armed and ready to block\n;\n\n\\ Advanced usage - Register a callback. \n\\ The tricky part is not screwing things up by missing a character\n\\ in the window between when you register, and when you pick up your\n\\ character. The way to do that is by registering, then self \n\\ halting, and then checking for a new character. That ensures that\n\\ if a character has slipped in, you will catch it.\n: (serkey-callback)\n\tbegin dup (serkey-sleep?) until (sergetchar)\n;\n\n: (serkey)\t\\ base -- char\n\\ *G Wait for a character to come available on the given UART and\n\\ ** return the character.\n\tsercallback IF (serkey-callback) ELSE (serkey-basic) THEN\n;\n\nexternal \n\n: seremit0\t\\ char --\n\\ *G Transmit a character on UART0.\n 0 (seremit) ;\n: sertype0\t\\ c-addr len --\n\\ *G Transmit a string on UART0.\n 0 (sertype) ;\n: sercr0\t\\ --\n\\ *G Issue a CR\/LF pair to UART0.\n 0 (sercr) ;\n: serkey?0\t\\ -- flag\n\\ *G Return true if UART0 has a character available.\n 0 (serkey?) ;\n: serkey0\t\\ -- char\n\\ *G Wait for a character on UART0.\n 0 (serkey) ;\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\n\\ *G Generic I\/O device for UART0.\n ' serkey0 ,\t\t\\ -- char ; receive char\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\n ' seremit0 ,\t\t\\ -- char ; display char\n ' sertype0 ,\t\t\\ caddr len -- ; display string\n ' sercr0 ,\t\t\\ -- ; display new line\n\n\\ UART2\n: seremit2 #2 (seremit) ;\n: sertype2\t#2 (sertype) ;\n: sercr2\t#2 (sercr) ;\n: serkey?2\t#2 (serkey?) ;\n: serkey2\t#2 (serkey) ;\ncreate Console2 ' serkey2 , ' serkey?2 , ' seremit2 , ' sertype2 , ' sercr2 ,\t\n\n\\ Versions for use with the TCP Port (10)\n: seremit10 #10 (seremit) ;\n: sertype10\t#10 (sertype) ;\n: sercr10\t#10 (sercr) ;\n: serkey?10\t#10 (serkey?) ;\n: serkey10\t#10 (serkey) ;\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\n\nconsole-port 0 = [if]\n console0 constant console\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\n\\ ** It may be changed by one of the phrases of the form:\n\\ *C dup opvec ! ipvec !\n\\ *C SetConsole\n[then]\n\nconsole-port #1 = [if]\n console1 constant console\n[then]\n\nconsole-port #10 = [if]\n console10 constant console\n[then]\n\n\\ ************************\n\\ *S System initialisation\n\\ ************************\n\n\\ This is a NOP in the SAPI environment\n: init-ser ;\t\\ --\n\\ *G Initialise all serial ports\n\n\n\\ ======\n\\ *> ###\n\\ ======\n\ndecimal\n","old_contents":"\\ serCM3_sapi_p.fth - SAPI polled RX, polled TX, serial communication drivers\n\\ Written to run against the SockPuppet API.\n\n((\nAdapted from: the LPC polled driver.\n))\n\nonly forth definitions\nvariable cnt.pause \n\n\\ ==============\n\\ *! serCM3_sapi_p\n\\ *T SAPI polled serial driver\n\\ ==============\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\n\\ ** using the internal UARTs via the SAPI call layer.\n\n\n\\ ****************\n\\ *S Configuration\n\\ ****************\n\\ *P Configuration is managed by the SAPI\n\n\\ ********\n\\ *S Tools\n\\ ********\n\ntarget\n\n\\ ********************\n\\ *S Serial primitives\n\\ ********************\n\n0 value sercallback \n\ninternal\n\n: +FaultConsole\t( -- ) ;\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\n\\ ** for more details.\n\ntarget\n\nCODE (seremitfc)\t\\ char base --\n\\ *G Service call for a single char - just fill in the registers\n\\ from the stack and make the call, and get back the flow control feedback\n\\ Put TOS into r0, pull r1 off the stack, and refresh the stack.\n\tmov r0, tos\n\tldr r1, [ psp ], # 4\t\n\tsvc # SAPI_VEC_PUTCHAR\t\n\tmov tos, r0\n next,\nEND-CODE\n\n: (seremit)\t\\ char base -- \n\\ *G Wrapped call that checks for throttling, and if so,\n\\ calls PAUSE to let another task run. Count these events for debugging purposes.\n\t(seremitfc)\n\t0<> IF 1 cnt.pause +! #5 ms THEN\n\t;\n\n: (sertype)\t\\ caddr len base --\n\\ *G Transmit a string on the given UART.\n -rot bounds\n ?do i c@ over (seremit) loop\n drop\n;\n\n: (sercr)\t\\ base --\n\\ *G Transmit a CR\/LF pair on the given UART.\n $0D over (seremit) $0A swap (seremit)\n;\n\nCODE (sergetchar) \\ base -- c\n\\ *G Get a character from the port\n\tmov r0, tos\t\n\tsvc # SAPI_VEC_GETCHAR\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE (serkey?) \\ base -- t\/f\n\\ *G Return true if the given UART has a character avilable to read.\n\\ The call returns 0 or 1. \n\tmov r0, tos\n\tsvc # SAPI_VEC_CHARSAVAIL\t\t\n\tmov tos, r0\n\tnext,\t\nEND-CODE\n\n: (serkey-basic)\n\tbegin pause \n\tdup (serkey?) until \n\t(sergetchar)\n;\n\n: (serkey-sleep?)\n\tself tcb.bbstatus @ over 1 setiocallback drop ( base oldcb )\n\tself halt \n\tdup (serkey?) IF self restart ELSE PAUSE THEN \\ We are now armed and ready to block\n\t(serkey?)\n;\n\n\\ Advanced usage - Register a callback. \n\\ The tricky part is not screwing things up by missing a character\n\\ in the window between when you register, and when you pick up your\n\\ character. The way to do that is by registering, then self \n\\ halting, and then checking for a new character. That ensures that\n\\ if a character has slipped in, you will catch it.\n: (serkey-callback)\n\tbegin dup (serkey-sleep?) until (sergetchar)\n;\n\n: (serkey)\t\\ base -- char\n\\ *G Wait for a character to come available on the given UART and\n\\ ** return the character.\n\tsercallback IF (serkey-callback) ELSE (serkey-basic) THEN\n;\n\nexternal \n\n: seremit0\t\\ char --\n\\ *G Transmit a character on UART0.\n 0 (seremit) ;\n: sertype0\t\\ c-addr len --\n\\ *G Transmit a string on UART0.\n 0 (sertype) ;\n: sercr0\t\\ --\n\\ *G Issue a CR\/LF pair to UART0.\n 0 (sercr) ;\n: serkey?0\t\\ -- flag\n\\ *G Return true if UART0 has a character available.\n 0 (serkey?) ;\n: serkey0\t\\ -- char\n\\ *G Wait for a character on UART0.\n 0 (serkey) ;\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\n\\ *G Generic I\/O device for UART0.\n ' serkey0 ,\t\t\\ -- char ; receive char\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\n ' seremit0 ,\t\t\\ -- char ; display char\n ' sertype0 ,\t\t\\ caddr len -- ; display string\n ' sercr0 ,\t\t\\ -- ; display new line\n\n\\ UART2\n: seremit2 #2 (seremit) ;\n: sertype2\t#2 (sertype) ;\n: sercr2\t#2 (sercr) ;\n: serkey?2\t#2 (serkey?) ;\n: serkey2\t#2 (serkey) ;\ncreate Console2 ' serkey2 , ' serkey?2 , ' seremit2 , ' sertype2 , ' sercr2 ,\t\n\n\\ Versions for use with the TCP Port (10)\n: seremit10 #10 (seremit) ;\n: sertype10\t#10 (sertype) ;\n: sercr10\t#10 (sercr) ;\n: serkey?10\t#10 (serkey?) ;\n: serkey10\t#10 (serkey) ;\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\n\nconsole-port 0 = [if]\n console0 constant console\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\n\\ ** It may be changed by one of the phrases of the form:\n\\ *C dup opvec ! ipvec !\n\\ *C SetConsole\n[then]\n\nconsole-port #1 = [if]\n console1 constant console\n[then]\n\nconsole-port #10 = [if]\n console10 constant console\n[then]\n\n\\ ************************\n\\ *S System initialisation\n\\ ************************\n\n\\ This is a NOP in the SAPI environment\n: init-ser ;\t\\ --\n\\ *G Initialise all serial ports\n\n\n\\ ======\n\\ *> ###\n\\ ======\n\ndecimal\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"f3050d463ad9f84081d59ebd527cf6cbb7c02552","subject":"Upon reflection, I decided that bootfile must have priority over kernel as the kernel name. The one very unfortunate consequence is that kernel as an absolute path loses the priority. It will only be tried after \/boot\/${kernel}\/${bootfile}. I'll see what can be done about it later.","message":"Upon reflection, I decided that bootfile must have priority over kernel\nas the kernel name. The one very unfortunate consequence is that kernel\nas an absolute path loses the priority. It will only be tried after\n\/boot\/${kernel}\/${bootfile}. I'll see what can be done about it later.\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/support.4th","new_file":"sys\/boot\/forth\/support.4th","new_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\ \n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\n\\ Loader.rc support functions:\n\\\n\\ initialize_support ( -- )\tinitialize global variables\n\\ initialize ( addr len -- )\tas above, plus load_conf_files\n\\ load_conf ( addr len -- )\tload conf file given\n\\ include_conf_files ( -- )\tload all conf files in load_conf_files\n\\ print_syntax_error ( -- )\tprint line and marker of where a syntax\n\\\t\t\t\terror was detected\n\\ print_line ( -- )\t\tprint last line processed\n\\ load_kernel ( -- )\t\tload kernel\n\\ load_modules ( -- )\t\tload modules flagged\n\\\n\\ Exported structures:\n\\\n\\ string\t\t\tcounted string structure\n\\\tcell .addr\t\t\tstring address\n\\\tcell .len\t\t\tstring length\n\\ module\t\t\tmodule loading information structure\n\\\tcell module.flag\t\tshould we load it?\n\\\tstring module.name\t\tmodule's name\n\\\tstring module.loadname\t\tname to be used in loading the module\n\\\tstring module.type\t\tmodule's type\n\\\tstring module.args\t\tflags to be passed during load\n\\\tstring module.beforeload\tcommand to be executed before load\n\\\tstring module.afterload\t\tcommand to be executed after load\n\\\tstring module.loaderror\t\tcommand to be executed if load fails\n\\\tcell module.next\t\tlist chain\n\\\n\\ Exported global variables;\n\\\n\\ string conf_files\t\tconfiguration files to be loaded\n\\ string password\t\tpassword\n\\ cell modules_options\t\tpointer to first module information\n\\ value verbose?\t\tindicates if user wants a verbose loading\n\\ value any_conf_read?\t\tindicates if a conf file was succesfully read\n\\\n\\ Other exported words:\n\\\n\\ strdup ( addr len -- addr' len)\t\t\tsimilar to strdup(3)\n\\ strcat ( addr len addr' len' -- addr len+len' )\tsimilar to strcat(3)\n\\ strlen ( addr -- len )\t\t\t\tsimilar to strlen(3)\n\\ s' ( | string' -- addr len | )\t\t\tsimilar to s\"\n\\ rudimentary structure support\n\n\\ Exception values\n\n1 constant syntax_error\n2 constant out_of_memory\n3 constant free_error\n4 constant set_error\n5 constant read_error\n6 constant open_error\n7 constant exec_error\n8 constant before_load_error\n9 constant after_load_error\n\n\\ Crude structure support\n\n: structure:\n create here 0 , ['] drop , 0\n does> create here swap dup @ allot cell+ @ execute\n;\n: member: create dup , over , + does> cell+ @ + ;\n: ;structure swap ! ;\n: constructor! >body cell+ ! ;\n: constructor: over :noname ;\n: ;constructor postpone ; swap cell+ ! ; immediate\n: sizeof ' >body @ state @ if postpone literal then ; immediate\n: offsetof ' >body cell+ @ state @ if postpone literal then ; immediate\n: ptr 1 cells member: ;\n: int 1 cells member: ;\n\n\\ String structure\n\nstructure: string\n\tptr .addr\n\tint .len\n\tconstructor:\n\t 0 over .addr !\n\t 0 swap .len !\n\t;constructor\n;structure\n\n\n\\ Module options linked list\n\nstructure: module\n\tint module.flag\n\tsizeof string member: module.name\n\tsizeof string member: module.loadname\n\tsizeof string member: module.type\n\tsizeof string member: module.args\n\tsizeof string member: module.beforeload\n\tsizeof string member: module.afterload\n\tsizeof string member: module.loaderror\n\tptr module.next\n;structure\n\n\\ Internal loader structures\nstructure: preloaded_file\n\tptr pf.name\n\tptr pf.type\n\tptr pf.args\n\tptr pf.metadata\t\\ file_metadata\n\tint pf.loader\n\tint pf.addr\n\tint pf.size\n\tptr pf.modules\t\\ kernel_module\n\tptr pf.next\t\\ preloaded_file\n;structure\n\nstructure: kernel_module\n\tptr km.name\n\t\\ ptr km.args\n\tptr km.fp\t\\ preloaded_file\n\tptr km.next\t\\ kernel_module\n;structure\n\nstructure: file_metadata\n\tint\t\tmd.size\n\t2 member:\tmd.type\t\\ this is not ANS Forth compatible (XXX)\n\tptr\t\tmd.next\t\\ file_metadata\n\t0 member:\tmd.data\t\\ variable size\n;structure\n\nstructure: config_resource\n\tptr cf.name\n\tint cf.type\n0 constant RES_INT\n1 constant RES_STRING\n2 constant RES_LONG\n\t2 cells member: u\n;structure\n\nstructure: config_device\n\tptr cd.name\n\tint cd.unit\n\tint cd.resource_count\n\tptr cd.resources\t\\ config_resource\n;structure\n\nstructure: STAILQ_HEAD\n\tptr stqh_first\t\\ type*\n\tptr stqh_last\t\\ type**\n;structure\n\nstructure: STAILQ_ENTRY\n\tptr stqe_next\t\\ type*\n;structure\n\nstructure: pnphandler\n\tptr pnph.name\n\tptr pnph.enumerate\n;structure\n\nstructure: pnpident\n\tptr pnpid.ident\t\t\t\t\t\\ char*\n\tsizeof STAILQ_ENTRY cells member: pnpid.link\t\\ pnpident\n;structure\n\nstructure: pnpinfo\n\tptr pnpi.desc\n\tint pnpi.revision\n\tptr pnpi.module\t\t\t\t\\ (char*) module args\n\tint pnpi.argc\n\tptr pnpi.argv\n\tptr pnpi.handler\t\t\t\\ pnphandler\n\tsizeof STAILQ_HEAD member: pnpi.ident\t\\ pnpident\n\tsizeof STAILQ_ENTRY member: pnpi.link\t\\ pnpinfo\n;structure\n\n\\ Global variables\n\nstring conf_files\nstring password\ncreate module_options sizeof module.next allot 0 module_options !\ncreate last_module_option sizeof module.next allot 0 last_module_option !\n0 value verbose?\n\n\\ Support string functions\n\n: strdup ( addr len -- addr' len )\n >r r@ allocate if out_of_memory throw then\n tuck r@ move\n r>\n;\n\n: strcat { addr len addr' len' -- addr len+len' }\n addr' addr len + len' move\n addr len len' +\n;\n\n: strlen ( addr -- len )\n 0 >r\n begin\n dup c@ while\n 1+ r> 1+ >r repeat\n drop r>\n;\n\n: s' \n [char] ' parse\n state @ if\n postpone sliteral\n then\n; immediate\n\n: 2>r postpone >r postpone >r ; immediate\n: 2r> postpone r> postpone r> ; immediate\n\n\\ Private definitions\n\nvocabulary support-functions\nonly forth also support-functions definitions\n\n\\ Some control characters constants\n\n7 constant bell\n8 constant backspace\n9 constant tab\n10 constant lf\n13 constant \n\n\\ Read buffer size\n\n80 constant read_buffer_size\n\n\\ Standard suffixes\n\n: load_module_suffix s\" _load\" ;\n: module_loadname_suffix s\" _name\" ;\n: module_type_suffix s\" _type\" ;\n: module_args_suffix s\" _flags\" ;\n: module_beforeload_suffix s\" _before\" ;\n: module_afterload_suffix s\" _after\" ;\n: module_loaderror_suffix s\" _error\" ;\n\n\\ Support operators\n\n: >= < 0= ;\n: <= > 0= ;\n\n\\ Assorted support funcitons\n\n: free-memory free if free_error throw then ;\n\n\\ Assignment data temporary storage\n\nstring name_buffer\nstring value_buffer\n\n\\ Line by line file reading functions\n\\\n\\ exported:\n\\\tline_buffer\n\\\tend_of_file?\n\\\tfd\n\\\tread_line\n\\\treset_line_reading\n\nvocabulary line-reading\nalso line-reading definitions also\n\n\\ File data temporary storage\n\nstring read_buffer\n0 value read_buffer_ptr\n\n\\ File's line reading function\n\nsupport-functions definitions\n\nstring line_buffer\n0 value end_of_file?\nvariable fd\n\nline-reading definitions\n\n: skip_newlines\n begin\n read_buffer .len @ read_buffer_ptr >\n while\n read_buffer .addr @ read_buffer_ptr + c@ lf = if\n read_buffer_ptr char+ to read_buffer_ptr\n else\n exit\n then\n repeat\n;\n\n: scan_buffer ( -- addr len )\n read_buffer_ptr >r\n begin\n read_buffer .len @ r@ >\n while\n read_buffer .addr @ r@ + c@ lf = if\n read_buffer .addr @ read_buffer_ptr + ( -- addr )\n r@ read_buffer_ptr - ( -- len )\n r> to read_buffer_ptr\n exit\n then\n r> char+ >r\n repeat\n read_buffer .addr @ read_buffer_ptr + ( -- addr )\n r@ read_buffer_ptr - ( -- len )\n r> to read_buffer_ptr\n;\n\n: line_buffer_resize ( len -- len )\n >r\n line_buffer .len @ if\n line_buffer .addr @\n line_buffer .len @ r@ +\n resize if out_of_memory throw then\n else\n r@ allocate if out_of_memory throw then\n then\n line_buffer .addr !\n r>\n;\n \n: append_to_line_buffer ( addr len -- )\n line_buffer .addr @ line_buffer .len @\n 2swap strcat\n line_buffer .len !\n drop\n;\n\n: read_from_buffer\n scan_buffer ( -- addr len )\n line_buffer_resize ( len -- len )\n append_to_line_buffer ( addr len -- )\n;\n\n: refill_required?\n read_buffer .len @ read_buffer_ptr =\n end_of_file? 0= and\n;\n\n: refill_buffer\n 0 to read_buffer_ptr\n read_buffer .addr @ 0= if\n read_buffer_size allocate if out_of_memory throw then\n read_buffer .addr !\n then\n fd @ read_buffer .addr @ read_buffer_size fread\n dup -1 = if read_error throw then\n dup 0= if true to end_of_file? then\n read_buffer .len !\n;\n\n: reset_line_buffer\n line_buffer .addr @ ?dup if\n free-memory\n then\n 0 line_buffer .addr !\n 0 line_buffer .len !\n;\n\nsupport-functions definitions\n\n: reset_line_reading\n 0 to read_buffer_ptr\n;\n\n: read_line\n reset_line_buffer\n skip_newlines\n begin\n read_from_buffer\n refill_required?\n while\n refill_buffer\n repeat\n;\n\nonly forth also support-functions definitions\n\n\\ Conf file line parser:\n\\ ::= '='[] |\n\\ []\n\\ ::= {||'_'}\n\\ ::= '\"'{|'\\'}'\"' | \n\\ ::= ASCII 32 to 126, except '\\' and '\"'\n\\ ::= '#'{}\n\\\n\\ exported:\n\\\tline_pointer\n\\\tprocess_conf\n\n0 value line_pointer\n\nvocabulary file-processing\nalso file-processing definitions\n\n\\ parser functions\n\\\n\\ exported:\n\\\tget_assignment\n\nvocabulary parser\nalso parser definitions also\n\n0 value parsing_function\n0 value end_of_line\n\n: end_of_line?\n line_pointer end_of_line =\n;\n\n: letter?\n line_pointer c@ >r\n r@ [char] A >=\n r@ [char] Z <= and\n r@ [char] a >=\n r> [char] z <= and\n or\n;\n\n: digit?\n line_pointer c@ >r\n r@ [char] 0 >=\n r> [char] 9 <= and\n;\n\n: quote?\n line_pointer c@ [char] \" =\n;\n\n: assignment_sign?\n line_pointer c@ [char] = =\n;\n\n: comment?\n line_pointer c@ [char] # =\n;\n\n: space?\n line_pointer c@ bl =\n line_pointer c@ tab = or\n;\n\n: backslash?\n line_pointer c@ [char] \\ =\n;\n\n: underscore?\n line_pointer c@ [char] _ =\n;\n\n: dot?\n line_pointer c@ [char] . =\n;\n\n: skip_character\n line_pointer char+ to line_pointer\n;\n\n: skip_to_end_of_line\n end_of_line to line_pointer\n;\n\n: eat_space\n begin\n space?\n while\n skip_character\n end_of_line? if exit then\n repeat\n;\n\n: parse_name ( -- addr len )\n line_pointer\n begin\n letter? digit? underscore? dot? or or or\n while\n skip_character\n end_of_line? if \n line_pointer over -\n strdup\n exit\n then\n repeat\n line_pointer over -\n strdup\n;\n\n: remove_backslashes { addr len | addr' len' -- addr' len' }\n len allocate if out_of_memory throw then\n to addr'\n addr >r\n begin\n addr c@ [char] \\ <> if\n addr c@ addr' len' + c!\n len' char+ to len'\n then\n addr char+ to addr\n r@ len + addr =\n until\n r> drop\n addr' len'\n;\n\n: parse_quote ( -- addr len )\n line_pointer\n skip_character\n end_of_line? if syntax_error throw then\n begin\n quote? 0=\n while\n backslash? if\n skip_character\n end_of_line? if syntax_error throw then\n then\n skip_character\n end_of_line? if syntax_error throw then \n repeat\n skip_character\n line_pointer over -\n remove_backslashes\n;\n\n: read_name\n parse_name\t\t( -- addr len )\n name_buffer .len !\n name_buffer .addr !\n;\n\n: read_value\n quote? if\n parse_quote\t\t( -- addr len )\n else\n parse_name\t\t( -- addr len )\n then\n value_buffer .len !\n value_buffer .addr !\n;\n\n: comment\n skip_to_end_of_line\n;\n\n: white_space_4\n eat_space\n comment? if ['] comment to parsing_function exit then\n end_of_line? 0= if syntax_error throw then\n;\n\n: variable_value\n read_value\n ['] white_space_4 to parsing_function\n;\n\n: white_space_3\n eat_space\n letter? digit? quote? or or if\n ['] variable_value to parsing_function exit\n then\n syntax_error throw\n;\n\n: assignment_sign\n skip_character\n ['] white_space_3 to parsing_function\n;\n\n: white_space_2\n eat_space\n assignment_sign? if ['] assignment_sign to parsing_function exit then\n syntax_error throw\n;\n\n: variable_name\n read_name\n ['] white_space_2 to parsing_function\n;\n\n: white_space_1\n eat_space\n letter? if ['] variable_name to parsing_function exit then\n comment? if ['] comment to parsing_function exit then\n end_of_line? 0= if syntax_error throw then\n;\n\nfile-processing definitions\n\n: get_assignment\n line_buffer .addr @ line_buffer .len @ + to end_of_line\n line_buffer .addr @ to line_pointer\n ['] white_space_1 to parsing_function\n begin\n end_of_line? 0=\n while\n parsing_function execute\n repeat\n parsing_function ['] comment =\n parsing_function ['] white_space_1 =\n parsing_function ['] white_space_4 =\n or or 0= if syntax_error throw then\n;\n\nonly forth also support-functions also file-processing definitions also\n\n\\ Process line\n\n: assignment_type? ( addr len -- flag )\n name_buffer .addr @ name_buffer .len @\n compare 0=\n;\n\n: suffix_type? ( addr len -- flag )\n name_buffer .len @ over <= if 2drop false exit then\n name_buffer .len @ over - name_buffer .addr @ +\n over compare 0=\n;\n\n: loader_conf_files?\n s\" loader_conf_files\" assignment_type?\n;\n\n: verbose_flag?\n s\" verbose_loading\" assignment_type?\n;\n\n: execute?\n s\" exec\" assignment_type?\n;\n\n: password?\n s\" password\" assignment_type?\n;\n\n: module_load?\n load_module_suffix suffix_type?\n;\n\n: module_loadname?\n module_loadname_suffix suffix_type?\n;\n\n: module_type?\n module_type_suffix suffix_type?\n;\n\n: module_args?\n module_args_suffix suffix_type?\n;\n\n: module_beforeload?\n module_beforeload_suffix suffix_type?\n;\n\n: module_afterload?\n module_afterload_suffix suffix_type?\n;\n\n: module_loaderror?\n module_loaderror_suffix suffix_type?\n;\n\n: set_conf_files\n conf_files .addr @ ?dup if\n free-memory\n then\n value_buffer .addr @ c@ [char] \" = if\n value_buffer .addr @ char+ value_buffer .len @ 2 chars -\n else\n value_buffer .addr @ value_buffer .len @\n then\n strdup\n conf_files .len ! conf_files .addr !\n;\n\n: append_to_module_options_list ( addr -- )\n module_options @ 0= if\n dup module_options !\n last_module_option !\n else\n dup last_module_option @ module.next !\n last_module_option !\n then\n;\n\n: set_module_name ( addr -- )\n name_buffer .addr @ name_buffer .len @\n strdup\n >r over module.name .addr !\n r> swap module.name .len !\n;\n\n: yes_value?\n value_buffer .addr @ value_buffer .len @\n 2dup s' \"YES\"' compare >r\n 2dup s' \"yes\"' compare >r\n 2dup s\" YES\" compare >r\n s\" yes\" compare r> r> r> and and and 0=\n;\n\n: find_module_option ( -- addr | 0 )\n module_options @\n begin\n dup\n while\n dup module.name dup .addr @ swap .len @\n name_buffer .addr @ name_buffer .len @\n compare 0= if exit then\n module.next @\n repeat\n;\n\n: new_module_option ( -- addr )\n sizeof module allocate if out_of_memory throw then\n dup sizeof module erase\n dup append_to_module_options_list\n dup set_module_name\n;\n\n: get_module_option ( -- addr )\n find_module_option\n ?dup 0= if new_module_option then\n;\n\n: set_module_flag\n name_buffer .len @ load_module_suffix nip - name_buffer .len !\n yes_value? get_module_option module.flag !\n;\n\n: set_module_args\n name_buffer .len @ module_args_suffix nip - name_buffer .len !\n get_module_option module.args\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_loadname\n name_buffer .len @ module_loadname_suffix nip - name_buffer .len !\n get_module_option module.loadname\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_type\n name_buffer .len @ module_type_suffix nip - name_buffer .len !\n get_module_option module.type\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_beforeload\n name_buffer .len @ module_beforeload_suffix nip - name_buffer .len !\n get_module_option module.beforeload\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_afterload\n name_buffer .len @ module_afterload_suffix nip - name_buffer .len !\n get_module_option module.afterload\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_loaderror\n name_buffer .len @ module_loaderror_suffix nip - name_buffer .len !\n get_module_option module.loaderror\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_environment_variable\n name_buffer .len @\n value_buffer .len @ +\n 5 chars +\n allocate if out_of_memory throw then\n dup 0 ( addr -- addr addr len )\n s\" set \" strcat\n name_buffer .addr @ name_buffer .len @ strcat\n s\" =\" strcat\n value_buffer .addr @ value_buffer .len @ strcat\n ['] evaluate catch if\n 2drop free drop\n set_error throw\n else\n free-memory\n then\n;\n\n: set_verbose\n yes_value? to verbose?\n;\n\n: execute_command\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 - swap char+ swap\n then\n ['] evaluate catch if exec_error throw then\n;\n\n: set_password\n password .addr @ ?dup if free if free_error throw then then\n value_buffer .addr @ c@ [char] \" = if\n value_buffer .addr @ char+ value_buffer .len @ 2 - strdup\n value_buffer .addr @ free if free_error throw then\n else\n value_buffer .addr @ value_buffer .len @\n then\n password .len ! password .addr !\n 0 value_buffer .addr !\n;\n\n: process_assignment\n name_buffer .len @ 0= if exit then\n loader_conf_files?\tif set_conf_files exit then\n verbose_flag?\t\tif set_verbose exit then\n execute?\t\tif execute_command exit then\n password?\t\tif set_password exit then\n module_load?\t\tif set_module_flag exit then\n module_loadname?\tif set_module_loadname exit then\n module_type?\t\tif set_module_type exit then\n module_args?\t\tif set_module_args exit then\n module_beforeload?\tif set_module_beforeload exit then\n module_afterload?\tif set_module_afterload exit then\n module_loaderror?\tif set_module_loaderror exit then\n set_environment_variable\n;\n\n\\ free_buffer ( -- )\n\\\n\\ Free some pointers if needed. The code then tests for errors\n\\ in freeing, and throws an exception if needed. If a pointer is\n\\ not allocated, it's value (0) is used as flag.\n\n: free_buffers\n name_buffer .addr @ dup if free then\n value_buffer .addr @ dup if free then\n or if free_error throw then\n;\n\n: reset_assignment_buffers\n 0 name_buffer .addr !\n 0 name_buffer .len !\n 0 value_buffer .addr !\n 0 value_buffer .len !\n;\n\n\\ Higher level file processing\n\nsupport-functions definitions\n\n: process_conf\n begin\n end_of_file? 0=\n while\n reset_assignment_buffers\n read_line\n get_assignment\n ['] process_assignment catch\n ['] free_buffers catch\n swap throw throw\n repeat\n;\n\nonly forth also support-functions definitions\n\n: create_null_terminated_string { addr len -- addr' len }\n len char+ allocate if out_of_memory throw then\n >r\n addr r@ len move\n 0 r@ len + c!\n r> len\n;\n\n\\ Interface to loading conf files\n\n: load_conf ( addr len -- )\n 0 to end_of_file?\n reset_line_reading\n create_null_terminated_string\n over >r\n fopen fd !\n r> free-memory\n fd @ -1 = if open_error throw then\n ['] process_conf catch\n fd @ fclose\n throw\n;\n\n: print_line\n line_buffer .addr @ line_buffer .len @ type cr\n;\n\n: print_syntax_error\n line_buffer .addr @ line_buffer .len @ type cr\n line_buffer .addr @\n begin\n line_pointer over <>\n while\n bl emit\n char+\n repeat\n drop\n .\" ^\" cr\n;\n\n\\ Depuration support functions\n\nonly forth definitions also support-functions\n\n: test-file \n ['] load_conf catch dup .\n syntax_error = if cr print_syntax_error then\n;\n\n: show-module-options\n module_options @\n begin\n ?dup\n while\n .\" Name: \" dup module.name dup .addr @ swap .len @ type cr\n .\" Path: \" dup module.loadname dup .addr @ swap .len @ type cr\n .\" Type: \" dup module.type dup .addr @ swap .len @ type cr\n .\" Flags: \" dup module.args dup .addr @ swap .len @ type cr\n .\" Before load: \" dup module.beforeload dup .addr @ swap .len @ type cr\n .\" After load: \" dup module.afterload dup .addr @ swap .len @ type cr\n .\" Error: \" dup module.loaderror dup .addr @ swap .len @ type cr\n .\" Status: \" dup module.flag @ if .\" Load\" else .\" Don't load\" then cr\n module.next @\n repeat\n;\n\nonly forth also support-functions definitions\n\n\\ Variables used for processing multiple conf files\n\nstring current_file_name\nvariable current_conf_files\n\n\\ Indicates if any conf file was succesfully read\n\n0 value any_conf_read?\n\n\\ loader_conf_files processing support functions\n\n: set_current_conf_files\n conf_files .addr @ current_conf_files !\n;\n\n: get_conf_files\n conf_files .addr @ conf_files .len @ strdup\n;\n\n: recurse_on_conf_files?\n current_conf_files @ conf_files .addr @ <>\n;\n\n: skip_leading_spaces { addr len pos -- addr len pos' }\n begin\n pos len = if addr len pos exit then\n addr pos + c@ bl =\n while\n pos char+ to pos\n repeat\n addr len pos\n;\n\n: get_file_name { addr len pos -- addr len pos' addr' len' || 0 }\n pos len = if \n addr free abort\" Fatal error freeing memory\"\n 0 exit\n then\n pos >r\n begin\n addr pos + c@ bl <>\n while\n pos char+ to pos\n pos len = if\n addr len pos addr r@ + pos r> - exit\n then\n repeat\n addr len pos addr r@ + pos r> -\n;\n\n: get_next_file ( addr len ptr -- addr len ptr' addr' len' | 0 )\n skip_leading_spaces\n get_file_name\n;\n\n: set_current_file_name\n over current_file_name .addr !\n dup current_file_name .len !\n;\n\n: print_current_file\n current_file_name .addr @ current_file_name .len @ type\n;\n\n: process_conf_errors\n dup 0= if true to any_conf_read? drop exit then\n >r 2drop r>\n dup syntax_error = if\n .\" Warning: syntax error on file \" print_current_file cr\n print_syntax_error drop exit\n then\n dup set_error = if\n .\" Warning: bad definition on file \" print_current_file cr\n print_line drop exit\n then\n dup read_error = if\n .\" Warning: error reading file \" print_current_file cr drop exit\n then\n dup open_error = if\n verbose? if .\" Warning: unable to open file \" print_current_file cr then\n drop exit\n then\n dup free_error = abort\" Fatal error freeing memory\"\n dup out_of_memory = abort\" Out of memory\"\n throw \\ Unknown error -- pass ahead\n;\n\n\\ Process loader_conf_files recursively\n\\ Interface to loader_conf_files processing\n\n: include_conf_files\n set_current_conf_files\n get_conf_files 0\n begin\n get_next_file ?dup\n while\n set_current_file_name\n ['] load_conf catch\n process_conf_errors\n recurse_on_conf_files? if recurse then\n repeat\n;\n\n\\ Module loading functions\n\n: load_module?\n module.flag @\n;\n\n: load_parameters ( addr -- addr addrN lenN ... addr1 len1 N )\n dup >r\n r@ module.args .addr @ r@ module.args .len @\n r@ module.loadname .len @ if\n r@ module.loadname .addr @ r@ module.loadname .len @\n else\n r@ module.name .addr @ r@ module.name .len @\n then\n r@ module.type .len @ if\n r@ module.type .addr @ r@ module.type .len @\n s\" -t \"\n 4 ( -t type name flags )\n else\n 2 ( name flags )\n then\n r> drop\n;\n\n: before_load ( addr -- addr )\n dup module.beforeload .len @ if\n dup module.beforeload .addr @ over module.beforeload .len @\n ['] evaluate catch if before_load_error throw then\n then\n;\n\n: after_load ( addr -- addr )\n dup module.afterload .len @ if\n dup module.afterload .addr @ over module.afterload .len @\n ['] evaluate catch if after_load_error throw then\n then\n;\n\n: load_error ( addr -- addr )\n dup module.loaderror .len @ if\n dup module.loaderror .addr @ over module.loaderror .len @\n evaluate \\ This we do not intercept so it can throw errors\n then\n;\n\n: pre_load_message ( addr -- addr )\n verbose? if\n dup module.name .addr @ over module.name .len @ type\n .\" ...\"\n then\n;\n\n: load_error_message verbose? if .\" failed!\" cr then ;\n\n: load_succesful_message verbose? if .\" ok\" cr then ;\n\n: load_module\n load_parameters load\n;\n\n: process_module ( addr -- addr )\n pre_load_message\n before_load\n begin\n ['] load_module catch if\n dup module.loaderror .len @ if\n load_error\t\t\t\\ Command should return a flag!\n else \n load_error_message true\t\t\\ Do not retry\n then\n else\n after_load\n load_succesful_message true\t\\ Succesful, do not retry\n then\n until\n;\n\n: process_module_errors ( addr ior -- )\n dup before_load_error = if\n drop\n .\" Module \"\n dup module.name .addr @ over module.name .len @ type\n dup module.loadname .len @ if\n .\" (\" dup module.loadname .addr @ over module.loadname .len @ type .\" )\"\n then\n cr\n .\" Error executing \"\n dup module.beforeload .addr @ over module.afterload .len @ type cr\n abort\n then\n\n dup after_load_error = if\n drop\n .\" Module \"\n dup module.name .addr @ over module.name .len @ type\n dup module.loadname .len @ if\n .\" (\" dup module.loadname .addr @ over module.loadname .len @ type .\" )\"\n then\n cr\n .\" Error executing \"\n dup module.afterload .addr @ over module.afterload .len @ type cr\n abort\n then\n\n throw \\ Don't know what it is all about -- pass ahead\n;\n\n\\ Module loading interface\n\n: load_modules ( -- ) ( throws: abort & user-defined )\n module_options @\n begin\n ?dup\n while\n dup load_module? if\n ['] process_module catch\n process_module_errors\n then\n module.next @\n repeat\n;\n\n\\ h00h00 magic used to try loading either a kernel with a given name,\n\\ or a kernel with the default name in a directory of a given name\n\\ (the pain!)\n\n: bootpath s\" \/boot\/\" ;\n: modulepath s\" module_path\" ;\n\n\\ Functions used to save and restore module_path's value.\n: saveenv ( addr len | -1 -- addr' len | 0 -1 )\n dup -1 = if 0 swap exit then\n strdup\n;\n: freeenv ( addr len | 0 -1 )\n -1 = if drop else free abort\" Freeing error\" then\n;\n: restoreenv ( addr len | 0 -1 -- )\n dup -1 = if ( it wasn't set )\n 2drop\n modulepath unsetenv\n else\n over >r\n modulepath setenv\n r> free abort\" Freeing error\"\n then\n;\n\n: clip_args \\ Drop second string if only one argument is passed\n 1 = if\n 2swap 2drop\n 1\n else\n 2\n then\n;\n\nalso builtins\n\n\\ Parse filename from a comma-separated list\n\n: parse-; ( addr len -- addr' len-x addr x )\n over 0 2swap\n begin\n dup 0 <>\n while\n over c@ [char] ; <>\n while\n 1- swap 1+ swap\n 2swap 1+ 2swap\n repeat then\n dup 0 <> if\n 1- swap 1+ swap\n then\n 2swap\n;\n\n\\ Try loading one of multiple kernels specified\n\n: try_multiple_kernels ( addr len addr' len' args -- flag )\n >r\n begin\n parse-; 2>r\n 2over 2r>\n r@ clip_args 1 load\n while\n dup 0=\n until\n 1 >r \\ Failure\n else\n 0 >r \\ Success\n then\n 2drop 2drop\n r>\n r> drop\n;\n\n\\ Try to load a kernel; the kernel name is taken from one of\n\\ the following lists, as ordered:\n\\\n\\ 1. The \"bootfile\" environment variable\n\\ 2. The \"kernel\" environment variable\n\\\n\\ Flags are passed, if available. The parameter args must be 2\n\\ if flags are being passed, or 1 if they should be ignored.\n\\ Dummy flags and len must be passed in the latter case.\n\\\n\\ The kernel gets loaded from the current module_path.\n\n: load_a_kernel ( flags len args -- flag )\n local args\n 2local flags\n 0 0 2local kernel\n end-locals\n\n \\ Check if a default kernel name exists at all, exits if not\n s\" bootfile\" getenv dup -1 <> if\n to kernel\n flags kernel args try_multiple_kernels\n dup 0= if exit then\n then\n drop\n\n s\" kernel\" getenv dup -1 <> if\n to kernel\n else\n drop\n 1 exit \\ Failure\n then\n\n \\ Try all default kernel names\n flags kernel args try_multiple_kernels\n;\n\n\\ Try to load a kernel; the kernel name is taken from one of\n\\ the following lists, as ordered:\n\\\n\\ 1. The \"bootfile\" environment variable\n\\ 2. The \"kernel\" environment variable\n\\\n\\ Flags are passed, if provided.\n\\\n\\ The kernel will be loaded from a directory computed from the\n\\ path given. Two directories will be tried in the following order:\n\\\n\\ 1. \/boot\/path\n\\ 2. path\n\\\n\\ The module_path variable is overridden if load is succesful, by\n\\ prepending the successful path.\n\n: load_from_directory ( path len 1 | flags len' path len 2 -- flag )\n local args\n 2local path\n args 1 = if 0 0 then\n 2local flags\n 0 0 2local oldmodulepath\n 0 0 2local newmodulepath\n end-locals\n\n \\ Set the environment variable module_path, and try loading\n \\ the kernel again.\n modulepath getenv saveenv to oldmodulepath\n\n \\ Try prepending \/boot\/ first\n bootpath nip path nip + \n oldmodulepath nip dup -1 = if\n drop\n else\n 1+ +\n then\n allocate\n if ( out of memory )\n 1 exit\n then\n\n 0\n bootpath strcat\n path strcat\n 2dup to newmodulepath\n modulepath setenv\n\n \\ Try all default kernel names\n flags args load_a_kernel\n 0= if ( success )\n oldmodulepath nip -1 <> if\n newmodulepath s\" ;\" strcat\n oldmodulepath strcat\n modulepath setenv\n newmodulepath drop free-memory\n oldmodulepath drop free-memory\n then\n 0 exit\n then\n\n \\ Well, try without the prepended \/boot\/\n path newmodulepath drop swap move\n path nip\n 2dup to newmodulepath\n modulepath setenv\n\n \\ Try all default kernel names\n flags args load_a_kernel\n if ( failed once more )\n oldmodulepath restoreenv\n newmodulepath drop free-memory\n 1\n else\n oldmodulepath nip -1 <> if\n newmodulepath s\" ;\" strcat\n oldmodulepath strcat\n modulepath setenv\n newmodulepath drop free-memory\n oldmodulepath drop free-memory\n then\n 0\n then\n;\n\n\\ Try to load a kernel; the kernel name is taken from one of\n\\ the following lists, as ordered:\n\\\n\\ 1. The \"bootfile\" environment variable\n\\ 2. The \"kernel\" environment variable\n\\ 3. The \"path\" argument\n\\\n\\ Flags are passed, if provided.\n\\\n\\ The kernel will be loaded from a directory computed from the\n\\ path given. Two directories will be tried in the following order:\n\\\n\\ 1. \/boot\/path\n\\ 2. path\n\\\n\\ Unless \"path\" is meant to be kernel name itself. In that case, it\n\\ will first be tried as a full path, and, next, search on the\n\\ directories pointed by module_path.\n\\\n\\ The module_path variable is overridden if load is succesful, by\n\\ prepending the successful path.\n\n: load_directory_or_file ( path len 1 | flags len' path len 2 -- flag )\n local args\n 2local path\n args 1 = if 0 0 then\n 2local flags\n end-locals\n\n \\ First, assume path is an absolute path to a directory\n flags path args clip_args load_from_directory\n dup 0= if exit else drop then\n\n \\ Next, assume path points to the kernel\n flags path args try_multiple_kernels\n;\n\n: load_kernel_and_modules ( flags len path len' 2 | path len' 1 -- flag )\n load_directory_or_file\n 0= if ['] load_modules catch then\n;\n\n: initialize ( addr len -- )\n strdup conf_files .len ! conf_files .addr !\n;\n\n: kernel_options ( -- addr len 2 | 0 0 1 )\n s\" kernel_options\" getenv\n dup -1 = if 0 0 1 else 2 then\n;\n\n: kernel_and_options\n kernel_options\n s\" kernel\" getenv\n rot\n;\n\n: load_kernel ( -- ) ( throws: abort )\n s\" kernel\" getenv\n dup -1 = if\n \\ If unset, try any kernel\n drop\n kernel_options load_a_kernel\n else\n \\ If set, try first directory, next file name\n kernel_options >r 2swap r> clip_args load_from_directory\n dup if\n drop\n kernel_and_options try_multiple_kernels\n then\n then\n abort\" Unable to load a kernel!\"\n;\n \n: read-password { size | buf len -- }\n size allocate if out_of_memory throw then\n to buf\n 0 to len\n begin\n key\n dup backspace = if\n drop\n len if\n backspace emit bl emit backspace emit\n len 1 - to len\n else\n bell emit\n then\n else\n dup = if cr drop buf len exit then\n [char] * emit\n len size < if\n buf len chars + c!\n else\n drop\n then\n len 1+ to len\n then\n again\n;\n\n\\ Go back to straight forth vocabulary\n\nonly forth also definitions\n\n","old_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\ \n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\n\\ Loader.rc support functions:\n\\\n\\ initialize_support ( -- )\tinitialize global variables\n\\ initialize ( addr len -- )\tas above, plus load_conf_files\n\\ load_conf ( addr len -- )\tload conf file given\n\\ include_conf_files ( -- )\tload all conf files in load_conf_files\n\\ print_syntax_error ( -- )\tprint line and marker of where a syntax\n\\\t\t\t\terror was detected\n\\ print_line ( -- )\t\tprint last line processed\n\\ load_kernel ( -- )\t\tload kernel\n\\ load_modules ( -- )\t\tload modules flagged\n\\\n\\ Exported structures:\n\\\n\\ string\t\t\tcounted string structure\n\\\tcell .addr\t\t\tstring address\n\\\tcell .len\t\t\tstring length\n\\ module\t\t\tmodule loading information structure\n\\\tcell module.flag\t\tshould we load it?\n\\\tstring module.name\t\tmodule's name\n\\\tstring module.loadname\t\tname to be used in loading the module\n\\\tstring module.type\t\tmodule's type\n\\\tstring module.args\t\tflags to be passed during load\n\\\tstring module.beforeload\tcommand to be executed before load\n\\\tstring module.afterload\t\tcommand to be executed after load\n\\\tstring module.loaderror\t\tcommand to be executed if load fails\n\\\tcell module.next\t\tlist chain\n\\\n\\ Exported global variables;\n\\\n\\ string conf_files\t\tconfiguration files to be loaded\n\\ string password\t\tpassword\n\\ cell modules_options\t\tpointer to first module information\n\\ value verbose?\t\tindicates if user wants a verbose loading\n\\ value any_conf_read?\t\tindicates if a conf file was succesfully read\n\\\n\\ Other exported words:\n\\\n\\ strdup ( addr len -- addr' len)\t\t\tsimilar to strdup(3)\n\\ strcat ( addr len addr' len' -- addr len+len' )\tsimilar to strcat(3)\n\\ strlen ( addr -- len )\t\t\t\tsimilar to strlen(3)\n\\ s' ( | string' -- addr len | )\t\t\tsimilar to s\"\n\\ rudimentary structure support\n\n\\ Exception values\n\n1 constant syntax_error\n2 constant out_of_memory\n3 constant free_error\n4 constant set_error\n5 constant read_error\n6 constant open_error\n7 constant exec_error\n8 constant before_load_error\n9 constant after_load_error\n\n\\ Crude structure support\n\n: structure:\n create here 0 , ['] drop , 0\n does> create here swap dup @ allot cell+ @ execute\n;\n: member: create dup , over , + does> cell+ @ + ;\n: ;structure swap ! ;\n: constructor! >body cell+ ! ;\n: constructor: over :noname ;\n: ;constructor postpone ; swap cell+ ! ; immediate\n: sizeof ' >body @ state @ if postpone literal then ; immediate\n: offsetof ' >body cell+ @ state @ if postpone literal then ; immediate\n: ptr 1 cells member: ;\n: int 1 cells member: ;\n\n\\ String structure\n\nstructure: string\n\tptr .addr\n\tint .len\n\tconstructor:\n\t 0 over .addr !\n\t 0 swap .len !\n\t;constructor\n;structure\n\n\n\\ Module options linked list\n\nstructure: module\n\tint module.flag\n\tsizeof string member: module.name\n\tsizeof string member: module.loadname\n\tsizeof string member: module.type\n\tsizeof string member: module.args\n\tsizeof string member: module.beforeload\n\tsizeof string member: module.afterload\n\tsizeof string member: module.loaderror\n\tptr module.next\n;structure\n\n\\ Internal loader structures\nstructure: preloaded_file\n\tptr pf.name\n\tptr pf.type\n\tptr pf.args\n\tptr pf.metadata\t\\ file_metadata\n\tint pf.loader\n\tint pf.addr\n\tint pf.size\n\tptr pf.modules\t\\ kernel_module\n\tptr pf.next\t\\ preloaded_file\n;structure\n\nstructure: kernel_module\n\tptr km.name\n\t\\ ptr km.args\n\tptr km.fp\t\\ preloaded_file\n\tptr km.next\t\\ kernel_module\n;structure\n\nstructure: file_metadata\n\tint\t\tmd.size\n\t2 member:\tmd.type\t\\ this is not ANS Forth compatible (XXX)\n\tptr\t\tmd.next\t\\ file_metadata\n\t0 member:\tmd.data\t\\ variable size\n;structure\n\nstructure: config_resource\n\tptr cf.name\n\tint cf.type\n0 constant RES_INT\n1 constant RES_STRING\n2 constant RES_LONG\n\t2 cells member: u\n;structure\n\nstructure: config_device\n\tptr cd.name\n\tint cd.unit\n\tint cd.resource_count\n\tptr cd.resources\t\\ config_resource\n;structure\n\nstructure: STAILQ_HEAD\n\tptr stqh_first\t\\ type*\n\tptr stqh_last\t\\ type**\n;structure\n\nstructure: STAILQ_ENTRY\n\tptr stqe_next\t\\ type*\n;structure\n\nstructure: pnphandler\n\tptr pnph.name\n\tptr pnph.enumerate\n;structure\n\nstructure: pnpident\n\tptr pnpid.ident\t\t\t\t\t\\ char*\n\tsizeof STAILQ_ENTRY cells member: pnpid.link\t\\ pnpident\n;structure\n\nstructure: pnpinfo\n\tptr pnpi.desc\n\tint pnpi.revision\n\tptr pnpi.module\t\t\t\t\\ (char*) module args\n\tint pnpi.argc\n\tptr pnpi.argv\n\tptr pnpi.handler\t\t\t\\ pnphandler\n\tsizeof STAILQ_HEAD member: pnpi.ident\t\\ pnpident\n\tsizeof STAILQ_ENTRY member: pnpi.link\t\\ pnpinfo\n;structure\n\n\\ Global variables\n\nstring conf_files\nstring password\ncreate module_options sizeof module.next allot 0 module_options !\ncreate last_module_option sizeof module.next allot 0 last_module_option !\n0 value verbose?\n\n\\ Support string functions\n\n: strdup ( addr len -- addr' len )\n >r r@ allocate if out_of_memory throw then\n tuck r@ move\n r>\n;\n\n: strcat { addr len addr' len' -- addr len+len' }\n addr' addr len + len' move\n addr len len' +\n;\n\n: strlen ( addr -- len )\n 0 >r\n begin\n dup c@ while\n 1+ r> 1+ >r repeat\n drop r>\n;\n\n: s' \n [char] ' parse\n state @ if\n postpone sliteral\n then\n; immediate\n\n: 2>r postpone >r postpone >r ; immediate\n: 2r> postpone r> postpone r> ; immediate\n\n\\ Private definitions\n\nvocabulary support-functions\nonly forth also support-functions definitions\n\n\\ Some control characters constants\n\n7 constant bell\n8 constant backspace\n9 constant tab\n10 constant lf\n13 constant \n\n\\ Read buffer size\n\n80 constant read_buffer_size\n\n\\ Standard suffixes\n\n: load_module_suffix s\" _load\" ;\n: module_loadname_suffix s\" _name\" ;\n: module_type_suffix s\" _type\" ;\n: module_args_suffix s\" _flags\" ;\n: module_beforeload_suffix s\" _before\" ;\n: module_afterload_suffix s\" _after\" ;\n: module_loaderror_suffix s\" _error\" ;\n\n\\ Support operators\n\n: >= < 0= ;\n: <= > 0= ;\n\n\\ Assorted support funcitons\n\n: free-memory free if free_error throw then ;\n\n\\ Assignment data temporary storage\n\nstring name_buffer\nstring value_buffer\n\n\\ Line by line file reading functions\n\\\n\\ exported:\n\\\tline_buffer\n\\\tend_of_file?\n\\\tfd\n\\\tread_line\n\\\treset_line_reading\n\nvocabulary line-reading\nalso line-reading definitions also\n\n\\ File data temporary storage\n\nstring read_buffer\n0 value read_buffer_ptr\n\n\\ File's line reading function\n\nsupport-functions definitions\n\nstring line_buffer\n0 value end_of_file?\nvariable fd\n\nline-reading definitions\n\n: skip_newlines\n begin\n read_buffer .len @ read_buffer_ptr >\n while\n read_buffer .addr @ read_buffer_ptr + c@ lf = if\n read_buffer_ptr char+ to read_buffer_ptr\n else\n exit\n then\n repeat\n;\n\n: scan_buffer ( -- addr len )\n read_buffer_ptr >r\n begin\n read_buffer .len @ r@ >\n while\n read_buffer .addr @ r@ + c@ lf = if\n read_buffer .addr @ read_buffer_ptr + ( -- addr )\n r@ read_buffer_ptr - ( -- len )\n r> to read_buffer_ptr\n exit\n then\n r> char+ >r\n repeat\n read_buffer .addr @ read_buffer_ptr + ( -- addr )\n r@ read_buffer_ptr - ( -- len )\n r> to read_buffer_ptr\n;\n\n: line_buffer_resize ( len -- len )\n >r\n line_buffer .len @ if\n line_buffer .addr @\n line_buffer .len @ r@ +\n resize if out_of_memory throw then\n else\n r@ allocate if out_of_memory throw then\n then\n line_buffer .addr !\n r>\n;\n \n: append_to_line_buffer ( addr len -- )\n line_buffer .addr @ line_buffer .len @\n 2swap strcat\n line_buffer .len !\n drop\n;\n\n: read_from_buffer\n scan_buffer ( -- addr len )\n line_buffer_resize ( len -- len )\n append_to_line_buffer ( addr len -- )\n;\n\n: refill_required?\n read_buffer .len @ read_buffer_ptr =\n end_of_file? 0= and\n;\n\n: refill_buffer\n 0 to read_buffer_ptr\n read_buffer .addr @ 0= if\n read_buffer_size allocate if out_of_memory throw then\n read_buffer .addr !\n then\n fd @ read_buffer .addr @ read_buffer_size fread\n dup -1 = if read_error throw then\n dup 0= if true to end_of_file? then\n read_buffer .len !\n;\n\n: reset_line_buffer\n line_buffer .addr @ ?dup if\n free-memory\n then\n 0 line_buffer .addr !\n 0 line_buffer .len !\n;\n\nsupport-functions definitions\n\n: reset_line_reading\n 0 to read_buffer_ptr\n;\n\n: read_line\n reset_line_buffer\n skip_newlines\n begin\n read_from_buffer\n refill_required?\n while\n refill_buffer\n repeat\n;\n\nonly forth also support-functions definitions\n\n\\ Conf file line parser:\n\\ ::= '='[] |\n\\ []\n\\ ::= {||'_'}\n\\ ::= '\"'{|'\\'}'\"' | \n\\ ::= ASCII 32 to 126, except '\\' and '\"'\n\\ ::= '#'{}\n\\\n\\ exported:\n\\\tline_pointer\n\\\tprocess_conf\n\n0 value line_pointer\n\nvocabulary file-processing\nalso file-processing definitions\n\n\\ parser functions\n\\\n\\ exported:\n\\\tget_assignment\n\nvocabulary parser\nalso parser definitions also\n\n0 value parsing_function\n0 value end_of_line\n\n: end_of_line?\n line_pointer end_of_line =\n;\n\n: letter?\n line_pointer c@ >r\n r@ [char] A >=\n r@ [char] Z <= and\n r@ [char] a >=\n r> [char] z <= and\n or\n;\n\n: digit?\n line_pointer c@ >r\n r@ [char] 0 >=\n r> [char] 9 <= and\n;\n\n: quote?\n line_pointer c@ [char] \" =\n;\n\n: assignment_sign?\n line_pointer c@ [char] = =\n;\n\n: comment?\n line_pointer c@ [char] # =\n;\n\n: space?\n line_pointer c@ bl =\n line_pointer c@ tab = or\n;\n\n: backslash?\n line_pointer c@ [char] \\ =\n;\n\n: underscore?\n line_pointer c@ [char] _ =\n;\n\n: dot?\n line_pointer c@ [char] . =\n;\n\n: skip_character\n line_pointer char+ to line_pointer\n;\n\n: skip_to_end_of_line\n end_of_line to line_pointer\n;\n\n: eat_space\n begin\n space?\n while\n skip_character\n end_of_line? if exit then\n repeat\n;\n\n: parse_name ( -- addr len )\n line_pointer\n begin\n letter? digit? underscore? dot? or or or\n while\n skip_character\n end_of_line? if \n line_pointer over -\n strdup\n exit\n then\n repeat\n line_pointer over -\n strdup\n;\n\n: remove_backslashes { addr len | addr' len' -- addr' len' }\n len allocate if out_of_memory throw then\n to addr'\n addr >r\n begin\n addr c@ [char] \\ <> if\n addr c@ addr' len' + c!\n len' char+ to len'\n then\n addr char+ to addr\n r@ len + addr =\n until\n r> drop\n addr' len'\n;\n\n: parse_quote ( -- addr len )\n line_pointer\n skip_character\n end_of_line? if syntax_error throw then\n begin\n quote? 0=\n while\n backslash? if\n skip_character\n end_of_line? if syntax_error throw then\n then\n skip_character\n end_of_line? if syntax_error throw then \n repeat\n skip_character\n line_pointer over -\n remove_backslashes\n;\n\n: read_name\n parse_name\t\t( -- addr len )\n name_buffer .len !\n name_buffer .addr !\n;\n\n: read_value\n quote? if\n parse_quote\t\t( -- addr len )\n else\n parse_name\t\t( -- addr len )\n then\n value_buffer .len !\n value_buffer .addr !\n;\n\n: comment\n skip_to_end_of_line\n;\n\n: white_space_4\n eat_space\n comment? if ['] comment to parsing_function exit then\n end_of_line? 0= if syntax_error throw then\n;\n\n: variable_value\n read_value\n ['] white_space_4 to parsing_function\n;\n\n: white_space_3\n eat_space\n letter? digit? quote? or or if\n ['] variable_value to parsing_function exit\n then\n syntax_error throw\n;\n\n: assignment_sign\n skip_character\n ['] white_space_3 to parsing_function\n;\n\n: white_space_2\n eat_space\n assignment_sign? if ['] assignment_sign to parsing_function exit then\n syntax_error throw\n;\n\n: variable_name\n read_name\n ['] white_space_2 to parsing_function\n;\n\n: white_space_1\n eat_space\n letter? if ['] variable_name to parsing_function exit then\n comment? if ['] comment to parsing_function exit then\n end_of_line? 0= if syntax_error throw then\n;\n\nfile-processing definitions\n\n: get_assignment\n line_buffer .addr @ line_buffer .len @ + to end_of_line\n line_buffer .addr @ to line_pointer\n ['] white_space_1 to parsing_function\n begin\n end_of_line? 0=\n while\n parsing_function execute\n repeat\n parsing_function ['] comment =\n parsing_function ['] white_space_1 =\n parsing_function ['] white_space_4 =\n or or 0= if syntax_error throw then\n;\n\nonly forth also support-functions also file-processing definitions also\n\n\\ Process line\n\n: assignment_type? ( addr len -- flag )\n name_buffer .addr @ name_buffer .len @\n compare 0=\n;\n\n: suffix_type? ( addr len -- flag )\n name_buffer .len @ over <= if 2drop false exit then\n name_buffer .len @ over - name_buffer .addr @ +\n over compare 0=\n;\n\n: loader_conf_files?\n s\" loader_conf_files\" assignment_type?\n;\n\n: verbose_flag?\n s\" verbose_loading\" assignment_type?\n;\n\n: execute?\n s\" exec\" assignment_type?\n;\n\n: password?\n s\" password\" assignment_type?\n;\n\n: module_load?\n load_module_suffix suffix_type?\n;\n\n: module_loadname?\n module_loadname_suffix suffix_type?\n;\n\n: module_type?\n module_type_suffix suffix_type?\n;\n\n: module_args?\n module_args_suffix suffix_type?\n;\n\n: module_beforeload?\n module_beforeload_suffix suffix_type?\n;\n\n: module_afterload?\n module_afterload_suffix suffix_type?\n;\n\n: module_loaderror?\n module_loaderror_suffix suffix_type?\n;\n\n: set_conf_files\n conf_files .addr @ ?dup if\n free-memory\n then\n value_buffer .addr @ c@ [char] \" = if\n value_buffer .addr @ char+ value_buffer .len @ 2 chars -\n else\n value_buffer .addr @ value_buffer .len @\n then\n strdup\n conf_files .len ! conf_files .addr !\n;\n\n: append_to_module_options_list ( addr -- )\n module_options @ 0= if\n dup module_options !\n last_module_option !\n else\n dup last_module_option @ module.next !\n last_module_option !\n then\n;\n\n: set_module_name ( addr -- )\n name_buffer .addr @ name_buffer .len @\n strdup\n >r over module.name .addr !\n r> swap module.name .len !\n;\n\n: yes_value?\n value_buffer .addr @ value_buffer .len @\n 2dup s' \"YES\"' compare >r\n 2dup s' \"yes\"' compare >r\n 2dup s\" YES\" compare >r\n s\" yes\" compare r> r> r> and and and 0=\n;\n\n: find_module_option ( -- addr | 0 )\n module_options @\n begin\n dup\n while\n dup module.name dup .addr @ swap .len @\n name_buffer .addr @ name_buffer .len @\n compare 0= if exit then\n module.next @\n repeat\n;\n\n: new_module_option ( -- addr )\n sizeof module allocate if out_of_memory throw then\n dup sizeof module erase\n dup append_to_module_options_list\n dup set_module_name\n;\n\n: get_module_option ( -- addr )\n find_module_option\n ?dup 0= if new_module_option then\n;\n\n: set_module_flag\n name_buffer .len @ load_module_suffix nip - name_buffer .len !\n yes_value? get_module_option module.flag !\n;\n\n: set_module_args\n name_buffer .len @ module_args_suffix nip - name_buffer .len !\n get_module_option module.args\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_loadname\n name_buffer .len @ module_loadname_suffix nip - name_buffer .len !\n get_module_option module.loadname\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_type\n name_buffer .len @ module_type_suffix nip - name_buffer .len !\n get_module_option module.type\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_beforeload\n name_buffer .len @ module_beforeload_suffix nip - name_buffer .len !\n get_module_option module.beforeload\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_afterload\n name_buffer .len @ module_afterload_suffix nip - name_buffer .len !\n get_module_option module.afterload\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_loaderror\n name_buffer .len @ module_loaderror_suffix nip - name_buffer .len !\n get_module_option module.loaderror\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_environment_variable\n name_buffer .len @\n value_buffer .len @ +\n 5 chars +\n allocate if out_of_memory throw then\n dup 0 ( addr -- addr addr len )\n s\" set \" strcat\n name_buffer .addr @ name_buffer .len @ strcat\n s\" =\" strcat\n value_buffer .addr @ value_buffer .len @ strcat\n ['] evaluate catch if\n 2drop free drop\n set_error throw\n else\n free-memory\n then\n;\n\n: set_verbose\n yes_value? to verbose?\n;\n\n: execute_command\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 - swap char+ swap\n then\n ['] evaluate catch if exec_error throw then\n;\n\n: set_password\n password .addr @ ?dup if free if free_error throw then then\n value_buffer .addr @ c@ [char] \" = if\n value_buffer .addr @ char+ value_buffer .len @ 2 - strdup\n value_buffer .addr @ free if free_error throw then\n else\n value_buffer .addr @ value_buffer .len @\n then\n password .len ! password .addr !\n 0 value_buffer .addr !\n;\n\n: process_assignment\n name_buffer .len @ 0= if exit then\n loader_conf_files?\tif set_conf_files exit then\n verbose_flag?\t\tif set_verbose exit then\n execute?\t\tif execute_command exit then\n password?\t\tif set_password exit then\n module_load?\t\tif set_module_flag exit then\n module_loadname?\tif set_module_loadname exit then\n module_type?\t\tif set_module_type exit then\n module_args?\t\tif set_module_args exit then\n module_beforeload?\tif set_module_beforeload exit then\n module_afterload?\tif set_module_afterload exit then\n module_loaderror?\tif set_module_loaderror exit then\n set_environment_variable\n;\n\n\\ free_buffer ( -- )\n\\\n\\ Free some pointers if needed. The code then tests for errors\n\\ in freeing, and throws an exception if needed. If a pointer is\n\\ not allocated, it's value (0) is used as flag.\n\n: free_buffers\n name_buffer .addr @ dup if free then\n value_buffer .addr @ dup if free then\n or if free_error throw then\n;\n\n: reset_assignment_buffers\n 0 name_buffer .addr !\n 0 name_buffer .len !\n 0 value_buffer .addr !\n 0 value_buffer .len !\n;\n\n\\ Higher level file processing\n\nsupport-functions definitions\n\n: process_conf\n begin\n end_of_file? 0=\n while\n reset_assignment_buffers\n read_line\n get_assignment\n ['] process_assignment catch\n ['] free_buffers catch\n swap throw throw\n repeat\n;\n\nonly forth also support-functions definitions\n\n: create_null_terminated_string { addr len -- addr' len }\n len char+ allocate if out_of_memory throw then\n >r\n addr r@ len move\n 0 r@ len + c!\n r> len\n;\n\n\\ Interface to loading conf files\n\n: load_conf ( addr len -- )\n 0 to end_of_file?\n reset_line_reading\n create_null_terminated_string\n over >r\n fopen fd !\n r> free-memory\n fd @ -1 = if open_error throw then\n ['] process_conf catch\n fd @ fclose\n throw\n;\n\n: print_line\n line_buffer .addr @ line_buffer .len @ type cr\n;\n\n: print_syntax_error\n line_buffer .addr @ line_buffer .len @ type cr\n line_buffer .addr @\n begin\n line_pointer over <>\n while\n bl emit\n char+\n repeat\n drop\n .\" ^\" cr\n;\n\n\\ Depuration support functions\n\nonly forth definitions also support-functions\n\n: test-file \n ['] load_conf catch dup .\n syntax_error = if cr print_syntax_error then\n;\n\n: show-module-options\n module_options @\n begin\n ?dup\n while\n .\" Name: \" dup module.name dup .addr @ swap .len @ type cr\n .\" Path: \" dup module.loadname dup .addr @ swap .len @ type cr\n .\" Type: \" dup module.type dup .addr @ swap .len @ type cr\n .\" Flags: \" dup module.args dup .addr @ swap .len @ type cr\n .\" Before load: \" dup module.beforeload dup .addr @ swap .len @ type cr\n .\" After load: \" dup module.afterload dup .addr @ swap .len @ type cr\n .\" Error: \" dup module.loaderror dup .addr @ swap .len @ type cr\n .\" Status: \" dup module.flag @ if .\" Load\" else .\" Don't load\" then cr\n module.next @\n repeat\n;\n\nonly forth also support-functions definitions\n\n\\ Variables used for processing multiple conf files\n\nstring current_file_name\nvariable current_conf_files\n\n\\ Indicates if any conf file was succesfully read\n\n0 value any_conf_read?\n\n\\ loader_conf_files processing support functions\n\n: set_current_conf_files\n conf_files .addr @ current_conf_files !\n;\n\n: get_conf_files\n conf_files .addr @ conf_files .len @ strdup\n;\n\n: recurse_on_conf_files?\n current_conf_files @ conf_files .addr @ <>\n;\n\n: skip_leading_spaces { addr len pos -- addr len pos' }\n begin\n pos len = if addr len pos exit then\n addr pos + c@ bl =\n while\n pos char+ to pos\n repeat\n addr len pos\n;\n\n: get_file_name { addr len pos -- addr len pos' addr' len' || 0 }\n pos len = if \n addr free abort\" Fatal error freeing memory\"\n 0 exit\n then\n pos >r\n begin\n addr pos + c@ bl <>\n while\n pos char+ to pos\n pos len = if\n addr len pos addr r@ + pos r> - exit\n then\n repeat\n addr len pos addr r@ + pos r> -\n;\n\n: get_next_file ( addr len ptr -- addr len ptr' addr' len' | 0 )\n skip_leading_spaces\n get_file_name\n;\n\n: set_current_file_name\n over current_file_name .addr !\n dup current_file_name .len !\n;\n\n: print_current_file\n current_file_name .addr @ current_file_name .len @ type\n;\n\n: process_conf_errors\n dup 0= if true to any_conf_read? drop exit then\n >r 2drop r>\n dup syntax_error = if\n .\" Warning: syntax error on file \" print_current_file cr\n print_syntax_error drop exit\n then\n dup set_error = if\n .\" Warning: bad definition on file \" print_current_file cr\n print_line drop exit\n then\n dup read_error = if\n .\" Warning: error reading file \" print_current_file cr drop exit\n then\n dup open_error = if\n verbose? if .\" Warning: unable to open file \" print_current_file cr then\n drop exit\n then\n dup free_error = abort\" Fatal error freeing memory\"\n dup out_of_memory = abort\" Out of memory\"\n throw \\ Unknown error -- pass ahead\n;\n\n\\ Process loader_conf_files recursively\n\\ Interface to loader_conf_files processing\n\n: include_conf_files\n set_current_conf_files\n get_conf_files 0\n begin\n get_next_file ?dup\n while\n set_current_file_name\n ['] load_conf catch\n process_conf_errors\n recurse_on_conf_files? if recurse then\n repeat\n;\n\n\\ Module loading functions\n\n: load_module?\n module.flag @\n;\n\n: load_parameters ( addr -- addr addrN lenN ... addr1 len1 N )\n dup >r\n r@ module.args .addr @ r@ module.args .len @\n r@ module.loadname .len @ if\n r@ module.loadname .addr @ r@ module.loadname .len @\n else\n r@ module.name .addr @ r@ module.name .len @\n then\n r@ module.type .len @ if\n r@ module.type .addr @ r@ module.type .len @\n s\" -t \"\n 4 ( -t type name flags )\n else\n 2 ( name flags )\n then\n r> drop\n;\n\n: before_load ( addr -- addr )\n dup module.beforeload .len @ if\n dup module.beforeload .addr @ over module.beforeload .len @\n ['] evaluate catch if before_load_error throw then\n then\n;\n\n: after_load ( addr -- addr )\n dup module.afterload .len @ if\n dup module.afterload .addr @ over module.afterload .len @\n ['] evaluate catch if after_load_error throw then\n then\n;\n\n: load_error ( addr -- addr )\n dup module.loaderror .len @ if\n dup module.loaderror .addr @ over module.loaderror .len @\n evaluate \\ This we do not intercept so it can throw errors\n then\n;\n\n: pre_load_message ( addr -- addr )\n verbose? if\n dup module.name .addr @ over module.name .len @ type\n .\" ...\"\n then\n;\n\n: load_error_message verbose? if .\" failed!\" cr then ;\n\n: load_succesful_message verbose? if .\" ok\" cr then ;\n\n: load_module\n load_parameters load\n;\n\n: process_module ( addr -- addr )\n pre_load_message\n before_load\n begin\n ['] load_module catch if\n dup module.loaderror .len @ if\n load_error\t\t\t\\ Command should return a flag!\n else \n load_error_message true\t\t\\ Do not retry\n then\n else\n after_load\n load_succesful_message true\t\\ Succesful, do not retry\n then\n until\n;\n\n: process_module_errors ( addr ior -- )\n dup before_load_error = if\n drop\n .\" Module \"\n dup module.name .addr @ over module.name .len @ type\n dup module.loadname .len @ if\n .\" (\" dup module.loadname .addr @ over module.loadname .len @ type .\" )\"\n then\n cr\n .\" Error executing \"\n dup module.beforeload .addr @ over module.afterload .len @ type cr\n abort\n then\n\n dup after_load_error = if\n drop\n .\" Module \"\n dup module.name .addr @ over module.name .len @ type\n dup module.loadname .len @ if\n .\" (\" dup module.loadname .addr @ over module.loadname .len @ type .\" )\"\n then\n cr\n .\" Error executing \"\n dup module.afterload .addr @ over module.afterload .len @ type cr\n abort\n then\n\n throw \\ Don't know what it is all about -- pass ahead\n;\n\n\\ Module loading interface\n\n: load_modules ( -- ) ( throws: abort & user-defined )\n module_options @\n begin\n ?dup\n while\n dup load_module? if\n ['] process_module catch\n process_module_errors\n then\n module.next @\n repeat\n;\n\n\\ h00h00 magic used to try loading either a kernel with a given name,\n\\ or a kernel with the default name in a directory of a given name\n\\ (the pain!)\n\n: bootpath s\" \/boot\/\" ;\n: modulepath s\" module_path\" ;\n\n\\ Functions used to save and restore module_path's value.\n: saveenv ( addr len | -1 -- addr' len | 0 -1 )\n dup -1 = if 0 swap exit then\n strdup\n;\n: freeenv ( addr len | 0 -1 )\n -1 = if drop else free abort\" Freeing error\" then\n;\n: restoreenv ( addr len | 0 -1 -- )\n dup -1 = if ( it wasn't set )\n 2drop\n modulepath unsetenv\n else\n over >r\n modulepath setenv\n r> free abort\" Freeing error\"\n then\n;\n\n: clip_args \\ Drop second string if only one argument is passed\n 1 = if\n 2swap 2drop\n 1\n else\n 2\n then\n;\n\nalso builtins\n\n\\ Parse filename from a comma-separated list\n\n: parse-; ( addr len -- addr' len-x addr x )\n over 0 2swap\n begin\n dup 0 <>\n while\n over c@ [char] ; <>\n while\n 1- swap 1+ swap\n 2swap 1+ 2swap\n repeat then\n dup 0 <> if\n 1- swap 1+ swap\n then\n 2swap\n;\n\n\\ Try loading one of multiple kernels specified\n\n: try_multiple_kernels ( addr len addr' len' args -- flag )\n >r\n begin\n parse-; 2>r\n 2over 2r>\n r@ clip_args 1 load\n while\n dup 0=\n until\n 1 >r \\ Failure\n else\n 0 >r \\ Success\n then\n 2drop 2drop\n r>\n r> drop\n;\n\n\\ Try to load a kernel; the kernel name is taken from one of\n\\ the following lists, as ordered:\n\\\n\\ 1. The \"kernel\" environment variable\n\\ 2. The \"bootfile\" environment variable\n\\\n\\ Flags are passed, if available. The parameter args must be 2\n\\ if flags are being passed, or 1 if they should be ignored.\n\\ Dummy flags and len must be passed in the latter case.\n\\\n\\ The kernel gets loaded from the current module_path.\n\n: load_a_kernel ( flags len args -- flag )\n local args\n 2local flags\n 0 0 2local kernel\n end-locals\n\n \\ Check if a default kernel name exists at all, exits if not\n s\" kernel\" getenv dup -1 <> if\n to kernel\n flags kernel args try_multiple_kernels\n dup 0= if exit then\n then\n drop\n\n s\" bootfile\" getenv dup -1 <> if\n to kernel\n else\n drop\n 1 exit \\ Failure\n then\n\n \\ Try all default kernel names\n flags kernel args try_multiple_kernels\n;\n\n\\ Try to load a kernel; the kernel name is taken from one of\n\\ the following lists, as ordered:\n\\\n\\ 1. The \"kernel\" environment variable\n\\ 2. The \"bootfile\" environment variable\n\\\n\\ Flags are passed, if provided.\n\\\n\\ The kernel will be loaded from a directory computed from the\n\\ path given. Two directories will be tried in the following order:\n\\\n\\ 1. \/boot\/path\n\\ 2. path\n\\\n\\ The module_path variable is overridden if load is succesful, by\n\\ prepending the successful path.\n\n: load_from_directory ( path len 1 | flags len' path len 2 -- flag )\n local args\n 2local path\n args 1 = if 0 0 then\n 2local flags\n 0 0 2local oldmodulepath\n 0 0 2local newmodulepath\n end-locals\n\n \\ Set the environment variable module_path, and try loading\n \\ the kernel again.\n modulepath getenv saveenv to oldmodulepath\n\n \\ Try prepending \/boot\/ first\n bootpath nip path nip + \n oldmodulepath nip dup -1 = if\n drop\n else\n 1+ +\n then\n allocate\n if ( out of memory )\n 1 exit\n then\n\n 0\n bootpath strcat\n path strcat\n 2dup to newmodulepath\n modulepath setenv\n\n \\ Try all default kernel names\n flags args load_a_kernel\n 0= if ( success )\n oldmodulepath nip -1 <> if\n newmodulepath s\" ;\" strcat\n oldmodulepath strcat\n modulepath setenv\n newmodulepath drop free-memory\n oldmodulepath drop free-memory\n then\n 0 exit\n then\n\n \\ Well, try without the prepended \/boot\/\n path newmodulepath drop swap move\n path nip\n 2dup to newmodulepath\n modulepath setenv\n\n \\ Try all default kernel names\n flags args load_a_kernel\n if ( failed once more )\n oldmodulepath restoreenv\n newmodulepath drop free-memory\n 1\n else\n oldmodulepath nip -1 <> if\n newmodulepath s\" ;\" strcat\n oldmodulepath strcat\n modulepath setenv\n newmodulepath drop free-memory\n oldmodulepath drop free-memory\n then\n 0\n then\n;\n\n\\ Try to load a kernel; the kernel name is taken from one of\n\\ the following lists, as ordered:\n\\\n\\ 1. The \"kernel\" environment variable\n\\ 2. The \"bootfile\" environment variable\n\\ 3. The \"path\" argument\n\\\n\\ Flags are passed, if provided.\n\\\n\\ The kernel will be loaded from a directory computed from the\n\\ path given. Two directories will be tried in the following order:\n\\\n\\ 1. \/boot\/path\n\\ 2. path\n\\\n\\ Unless \"path\" is meant to be kernel name itself. In that case, it\n\\ will first be tried as a full path, and, next, search on the\n\\ directories pointed by module_path.\n\\\n\\ The module_path variable is overridden if load is succesful, by\n\\ prepending the successful path.\n\n: load_directory_or_file ( path len 1 | flags len' path len 2 -- flag )\n local args\n 2local path\n args 1 = if 0 0 then\n 2local flags\n end-locals\n\n \\ First, assume path is an absolute path to a directory\n flags path args clip_args load_from_directory\n dup 0= if exit else drop then\n\n \\ Next, assume path points to the kernel\n flags path args try_multiple_kernels\n;\n\n: load_kernel_and_modules ( flags len path len' 2 | path len' 1 -- flag )\n load_directory_or_file\n 0= if ['] load_modules catch then\n;\n\n: initialize ( addr len -- )\n strdup conf_files .len ! conf_files .addr !\n;\n\n: kernel_options ( -- addr len 2 | 0 0 1 )\n s\" kernel_options\" getenv\n dup -1 = if 0 0 1 else 2 then\n;\n\n: kernel_and_options\n kernel_options\n s\" kernel\" getenv\n rot\n;\n\n: load_kernel ( -- ) ( throws: abort )\n s\" kernel\" getenv\n dup -1 = if\n \\ If unset, try any kernel\n drop\n kernel_options load_a_kernel\n else\n \\ If set, try first directory, next file name\n kernel_options >r 2swap r> clip_args load_from_directory\n dup if\n drop\n kernel_and_options try_multiple_kernels\n then\n then\n abort\" Unable to load a kernel!\"\n;\n \n: read-password { size | buf len -- }\n size allocate if out_of_memory throw then\n to buf\n 0 to len\n begin\n key\n dup backspace = if\n drop\n len if\n backspace emit bl emit backspace emit\n len 1 - to len\n else\n bell emit\n then\n else\n dup = if cr drop buf len exit then\n [char] * emit\n len size < if\n buf len chars + c!\n else\n drop\n then\n len 1+ to len\n then\n again\n;\n\n\\ Go back to straight forth vocabulary\n\nonly forth also definitions\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"e81c5ece2694e20a720709011a82582f5e01387e","subject":"More tools for working with the dynamic linking","message":"More tools for working with the dynamic linking\n","repos":"rbsexton\/sockpuppet,rbsexton\/sockpuppet","old_file":"forth\/dylink.fth","new_file":"forth\/dylink.fth","new_contents":"\\ Code to support runtime\/dynamic into the C side via SAPI.\n\n\\ ************************************************************************\n\\ ************************************************************************\n\\ Secondary support functions \n\\ ************************************************************************\n\\ ************************************************************************\n\n\\ *********************************************\n\\ Accessors - Tightly tied the data structure\n\\ *********************************************\n: dy.val @ ; \n: dy.size #4 + w@ ; \n: dy.count #6 + w@ ; \n: dy.type #8 + c@ ;\n: dy.namelen #9 + c@ ;\n: dy.name #12 + @ ;\n\n\\ Return the recordlength. Its the first thing.\n: dy-recordlen getsharedvars @ ;\n\n\\ Retrieve the string.\n: dy-string ( addr -- caddr n ) \n dup dy.name swap dy.namelen \n; \n\n\\ Heres some assembly code to use as a template.\n\\ I experimented a bit, and the simplest thing in the MPE\n\\ Forth environment is to lay down the assembly\n((\nCODE rawconstant\n\tstr tos, [ psp, # -4 ] ! \\ register push\n ldr tos, L$1\n\tbx lr\nL$1: str tos, [ psp, # -4 ] ! \\ 32-bit dummy instruction\nEND-CODE\n))\n\n\\ Create a constant from scratch by laying down some assembly\n\\ A key trick is that we have to lay down a pointer to \n\\ the first character of the defintion after we finish\n\\ See the definition above for the template\n: make-const \\ n s-addr c --\n\there 4+ >r \\ This should point to the newly-created header.\n\tmakeheader \\\n\t\n\\ ( 0002:0270 4CF8047D Lx.} ) str r7, [ r12, # $-04 ]!\n\\ ( 0002:0274 004F .O ) ldr r7, [ PC, # $00 ] ( @$20278=$7D04F84C )\n\\ ( 0002:0276 7047 pG ) bx LR\n\n\t$7D04F84C , \\ str r7, [ r12, # $-04 ]!\n\t$4f00 w, \\ ldr r7, [ PC, # $00 ]\n\t$4770 w, \\ bx LR\n\t, \t \\ Lay down the payload\n\n\tr> , \\ lay down the link field for the next word - required\n\t;\n\t\n\\ Dump out an entry as a set of constants\n: dy-print \\ c-addr --\n S\" $\" type\n DUP dy.val . \\ Fetch the value\n \n DUP dy.type [CHAR] V = \\ check the type \n \n IF\n \tS\" VALUE \"\n ELSE\n \tS\" CONSTANT \"\n THEN\n TYPE \\ Display the result\n DUP dy.size . S\" x\" DUP dy.count .\n dy-string TYPE\n CR\n ; \n\n\\ Take a pointer to a dynamic link record, and add a constant to the dictionary\n: dy-create \\ addr --\n\tDUP \\ addr addr \n\tdy.val \\ c-addr n \n\tSWAP dy-string \\ n c-addr b\n make-const\n ;\n\n\\ Given a record address and a string, figure out\n\\ if thats the one we're looking for\n: dy-compare ( caddr n addr -- n ) \n dy-string compare \n;\n\n\\ Find the record in the list to go with a string\n: dy-find ( c-addr n -- addr|0 ) \n getsharedvars dy-recordlen + \\ Skip over the empty first record\n >R \\ Put it onto the return stack\n BEGIN\n R@ dy.val 0<>\n WHILE \n 2DUP R@ dy-compare\n \\ If we find it, clean the stack and leave the address on R\n 0= IF 2DROP R> EXIT THEN\n R> dy-recordlen + >R\n REPEAT\n \\ If we fall out, there will be a string caddr\/n on the stack\n 2DROP R> DROP \n 0 \\ Leave behind a zero to indicate failure\n;\n\n\\ Walk the table and make the constants.\n: dy-populate\n getsharedvars dy-recordlen + \\ Skip over the empty first record\n BEGIN \n dup dy.val 0<> \n WHILE\n dup dy-create\n dy-recordlen +\n REPEAT\n 2DROP R> DROP 0\n ; \n \n","old_contents":"\\ Code to support runtime\/dynamic into the C side via SAPI.\n\n\\ ************************************************************************\n\\ ************************************************************************\n\\ Secondary support functions \n\\ ************************************************************************\n\\ ************************************************************************\n\n\\ *********************************************\n\\ Accessors - Tightly tied the data structure\n\\ *********************************************\n: dy.val @ ; \n: dy.size #4 + w@ ; \n: dy.count #6 + w@ ; \n: dy.type #8 + c@ ;\n: dy.namelen #9 + c@ ;\n: dy.name #12 + @ ;\n\n\\ Return the recordlength. Its the first thing.\n: dy-recordlen getsharedvars @ ;\n\n\\ Heres some assembly code to use as a template.\n\\ I experimented a bit, and the simplest thing in the MPE\n\\ Forth environment is to lay down the assembly\n((\nCODE rawconstant\n\tstr tos, [ psp, # -4 ] ! \\ register push\n ldr tos, L$1\n\tbx lr\nL$1: str tos, [ psp, # -4 ] ! \\ 32-bit dummy instruction\nEND-CODE\n))\n\n\\ Create a constant from scratch by laying down some assembly\n\\ A key trick is that we have to lay down a pointer to \n\\ the first character of the defintion after we finish\n\\ See the definition above for the template\n: make-const \\ n s-addr c --\n\there 4+ >r \\ This should point to the newly-created header.\n\tmakeheader \\\n\t\n\\ ( 0002:0270 4CF8047D Lx.} ) str r7, [ r12, # $-04 ]!\n\\ ( 0002:0274 004F .O ) ldr r7, [ PC, # $00 ] ( @$20278=$7D04F84C )\n\\ ( 0002:0276 7047 pG ) bx LR\n\n\t$7D04F84C , \\ str r7, [ r12, # $-04 ]!\n\t$4f00 w, \\ ldr r7, [ PC, # $00 ]\n\t$4770 w, \\ bx LR\n\t, \t \\ Lay down the payload\n\n\tr> , \\ lay down the link field for the next word - required\n\t;\n\t\n\\ Dump out an entry as a set of constants\n: dy-print \\ c-addr --\n S\" $\" type\n DUP dy.val . \\ Fetch the value\n \n DUP dy.type [CHAR] V = \\ check the type \n \n IF\n \tS\" VALUE \"\n ELSE\n \tS\" CONSTANT \"\n THEN\n TYPE \\ Display the result\n DUP dy.size . S\" x\" DUP dy.count .\n dy-string TYPE\n CR\n ; \n\n\\ Take a pointer to a dynamic link record, and add a constant to the dictionary\n: dy-create \\ addr --\n\tDUP \\ addr addr \n\tdy.val \\ c-addr n \n\tSWAP dy-string \\ n c-addr b\n make-const\n ;\n\n\n\\ Walk the table and make the constants.\n: dy-populate\n getsharedvars dy-recordlen + \\ Skip over the empty first record\n BEGIN \n dup dy.val 0<> \n WHILE\n dup dy-create\n dy-recordlen +\n REPEAT\n 2DROP R> DROP 0\n ; \n \n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"88038f520e7e26a7c69977547707757f9f32b7c7","subject":"?NEG & ?EMPTY added, ?MAX-NB refactored","message":"?NEG & ?EMPTY added, ?MAX-NB refactored\n","repos":"bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas","old_file":"KataDiversion.fth","new_file":"KataDiversion.fth","new_contents":"\\ KataDiversion in Forth\n\n\\ -- utils\n\n\\ empty the stack\n: EMPTY\n DEPTH 0 <> IF BEGIN\n DROP DEPTH 0 =\n UNTIL\n THEN ;\n\n\\ power\n: ** ( n1 n2 -- n1_pow_n2 ) 1 SWAP ?DUP IF 0 DO OVER * LOOP THEN NIP ;\n\n\\ test if the top is a negative number\n: ?NEG ( n -- bool ) DUP 0= IF -1 ELSE DUP ABS <> THEN ;\n\n\\ -- kata\n\n\\ test if the given N has two adjacent 1 bits\n\\ e.g. : 1011 -> -1\n\\ 1001 -> 0\n: ?TWO-ADJACENT-1-BITS ( n -- bool ) ( TODO ) ;\n\n\\ return the maximum number which can be made with N (given number) bits\n: ?MAX-NB ( n -- m ) DUP ?NEG IF DROP 0 ( 0 )\n ELSE \n DUP IF DUP 2 SWAP ** NIP ( 2**n )\n THEN\n THEN ;\n\n\n\\ return the number of numbers which can be made with N (given number) bits\n\\ or less, and which have not two adjacent 1 bits.\n\\ see http:\/\/www.codekata.com\/2007\/01\/code_kata_fifte.html\n: ?HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS ( n -- m ) ( TODO ) ;\n","old_contents":"\\ KataDiversion in Forth\n\n\\ power\n: ** ( n1 n2 -- n1_pow_n2 ) 1 SWAP ?DUP IF 0 DO OVER * LOOP THEN NIP ;\n\n\\ test if the given N has two adjacent 1 bits\n\\ e.g. : 1011 -> -1\n\\ 1001 -> 0\n: ?TWO-ADJACENT-1-BITS ( n -- bool ) ( TODO ) ;\n\n\\ return the maximum number which can be made with N (given number) bits\n: ?MAX-NB ( n -- m ) DUP 2DUP ABS <> IF 0 NIP\n ELSE \n IF 2 SWAP ** NIP\n THEN\n THEN ;\n\n\\ return the number of numbers which can be made with N (given number) bits\n\\ or less, and which have not two adjacent 1 bits.\n\\ see http:\/\/www.codekata.com\/2007\/01\/code_kata_fifte.html\n: ?HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS ( n -- m ) ( TODO ) ;\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"def895c22534e72152f729ec32b14d2560a76e28","subject":"Renamed 'hider' to hide","message":"Renamed 'hider' to hide\n\nThat is all.\n","repos":"howerj\/libforth","old_file":"forth.fth","new_file":"forth.fth","new_contents":"#!.\/forth \n( Welcome to libforth, A dialect of Forth. Like all versions of Forth this\nversion is a little idiosyncratic, but how the interpreter works is\ndocumented here and in various other files.\n\nThis file contains most of the start up code, some basic start up code\nis executed in the C file as well which makes programming at least bearable.\nMost of Forth is programmed in itself, which may seem odd if your back\nground in programming comes from more traditional language [such as C],\nalthough less so if you know already know lisp.\n\nFor more information about this interpreter and Forth see:\n\thttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\treadme.md : for a manual for this interpreter\n\tlibforth.h : for information about the C API\n\tlibforth.c : for the interpreter itself\n\tunit.c : a series of unit tests against libforth.c\n\tunit.fth : a series of unit tests against this file\n\nThe interpreter and this code originally descend from a Forth interpreter\nwritten in 1992 for the International obfuscated C Coding Competition\n\nSee:\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\nThe manual for the interpreter should be read first before looking into this\ncode. It is important to understand the execution model of Forth, especially\nthe differences between command and compile mode, and how immediate and compiling\nwords work.\n\n@todo Restructure and describe structure of this file.\n\nEach of these sections is clearly labeled and they are generally in dependency order.\n\nUnfortunately the code in this file is not as portable as it could be, it makes\nassumptions about the size of cells provided by the virtual machine, which will\ntake time to rectify. Some of the constructs are subtly different from the\nDPANs Forth specification, which is usually noted. Eventually this should\nalso be fixed.)\n\n( ========================== Basic Word Set ================================== )\n\n( \nWe'll begin by defining very simple words we can use later, these a very\nbasic words, that perform simple tasks, they will not require much explanation.\n\nEven though the words are simple, their stack comment and a description for\nthem will still be included so external tools can process and automatically\nextract the document string for a given work.\n)\n\n: postpone ( -- : postpone execution of the following immediate word )\n\timmediate find , ;\n\n: :: ( -- : compiling version of ':' )\n\t[ find : , ] ;\n\n: constant \n\t:: ( compile word header )\n\there 1 - h ! ( decrement dictionary pointer )\n\there @ instruction-mask invert and doconst or here ! ( change instruction to CONST )\n\there 1 + h ! ( increment dictionary pointer )\n\t, ( write in value )\n\tpostpone [ ; ( back into command mode )\n\n( space saving measure )\n-1 constant -1\n 0 constant 0 \n 1 constant 1\n 2 constant 2\n 3 constant 3\n\n0 constant false\n1 constant true ( @warning not standards compliant )\n\n( Confusingly the word 'cr' prints a line feed )\n10 constant lf ( line feed )\nlf constant nl ( new line - line feed on Unixen )\n13 constant cret ( carriage return )\n\n1 hidden-bit lshift constant hidden-mask ( mask for the hide bit in a words CODE field )\n\n-1 -1 1 rshift invert and constant min-signed-integer\n\nmin-signed-integer invert constant max-signed-integer\n\n1 constant cell ( size of a cell in address units )\n\ncell size 8 * * constant address-unit-bits ( the number of bits in an address )\n\n-1 -1 1 rshift and invert constant sign-bit ( bit corresponding to the sign in a number )\n\n( @todo test by how much, if at all, making words like 1+, 1-, <>, and other\nsimple words, part of the interpreter would speed things up )\n\n: 1+ ( x -- x : increment a number ) \n\t1 + ;\n\n: 1- ( x -- x : decrement a number ) \n\t1 - ;\n\n: chars ( c-addr -- addr : convert a character address to an address )\n\tsize \/ ; \n\n: chars> ( addr -- c-addr: convert an address to a character address )\n\tsize * ; \n\n: tab ( -- : print a tab character to current output device )\n\t9 emit ;\n\n: 0= ( x -- bool : is 'x' equal to zero? )\n\t0 = ;\n\n: not ( x -- bool : is 'x' true? )\n\t0= ;\n\n: <> ( x x -- bool : not equal )\n\t= 0= ;\n\n: logical ( x -- bool : turn a value into a boolean ) \n\tnot not ;\n\n( @todo \": dolit ' ' ;\" works but does not interact well with \n'decompile', if this was fixed the special work could be removed,\nwith some extra effort in libforth.c as well )\n: dolit ( -- x : location of special \"push\" word )\n\t2 ; \n\n: 2, ( x x -- : write two values into the dictionary )\n\t, , ;\n\n: [literal] ( x -- : write a literal into the dictionary )\n\tdolit 2, ; \n\n: literal ( x -- : immediately write a literal into the dictionary )\n\timmediate [literal] ;\n\n: sliteral immediate ( I: c-addr u --, Run: -- c-addr u )\n\tswap [literal] [literal] ;\n\n( @todo throw if not found )\n: ['] ( I: c\" xxx\", Run: -- xt )\n\timmediate find [literal] ;\n\n: >instruction ( CODE -- Instruction : extract instruction from instruction field ) \n\tinstruction-mask and ;\n\n: immediate-mask ( -- x : pushes the mask for the compile bit in a words CODE field )\n\t[ 1 compile-bit lshift ] literal ;\n\n: hidden? ( PWD -- PWD bool : is a word hidden, given the words PWD field ) \n\tdup 1+ @ hidden-mask and logical ;\n\n: compiling? ( PWD -- PWD bool : is a word immediate, given the words PWD field )\n\tdup 1+ @ immediate-mask and logical ;\n\n\n: cr ( -- : emit a newline character )\n\tnl emit ;\n\n: < ( x1 x2 -- bool : signed less than comparison )\n\t- dup if max-signed-integer u> else logical then ;\n\n: > ( x1 x2 -- bool : signed greater than comparison )\n\t- dup if max-signed-integer u< else logical then ;\n\n: #pad ( -- u : offset into pad area )\n\t64 ;\n\n: pad\n\t( the pad is used for temporary storage, and moves\n\talong with dictionary pointer, always in front of it )\n\there #pad + ;\n\n( @todo this can be improved a lot, currently it uses more\nspace than it has to, 4 cells instead of three.\n\nIt does:\n\n\tpush value\n\tpush value\n\nInstead of:\n\n\tmagic-2literal-word\n\tvalue\n\tvalue\n\n)\n: 2literal immediate ( x x -- : immediate write two literals into the dictionary )\n\tswap [literal] [literal] ;\n\n: latest ( get latest defined word )\n\tpwd @ ; \n\n: stdin ( -- fileid : push the fileid for the standard input channel ) \n\t`stdin @ ;\n\n: stdout ( -- fileid : push the fileid for the standard output channel ) \n\t`stdout @ ;\n\n: stderr ( -- fileid : push the fileid for the standard error channel ) \n\t`stderr @ ;\n\n: stdin? ( -- bool : are we reading from standard input )\n\t`fin @ stdin = ;\n\n: *+ ( x1 x2 x3 -- x ) \n\t* + ;\n\t\n: 2- ( x -- x : decrement by two )\n\t2 - ( x -- x ) ;\n\n: 2+ ( x -- x : increment by two )\n\t2 + ( x -- x ) ;\n\n: 3+ ( x -- x : increment by three )\n\t3 + ( x -- x ) ;\n\n: 2* ( x -- x : multiply by two )\n\t1 lshift ( x -- x ) ;\n\n: 2\/ ( x -- x : divide by two )\n\t1 rshift ( x -- x ) ;\n\n: 4* ( x -- x : multiply by four )\n\t2 lshift ( x -- x ) ;\n\n: 4\/ ( x -- x : divide by four )\n\t2 rshift ( x -- x ) ;\n\n: 8* ( x -- x : multiply by eight )\n\t3 lshift ( x -- x ) ;\n\n: 8\/ ( x -- x : divide by eight )\n\t3 rshift ( x -- x ) ;\n\n: 256* ( x -- x : multiply by 256 )\n\t8 lshift ( x -- x ) ;\n\n: 256\/ ( x -- x : divide by 256 )\n\t8 rshift ( x -- x ) ;\n\n: 2dup ( x1 x2 -- x1 x2 x1 x2 : duplicate two values )\n\tover over ;\n\n: mod ( x u -- x : calculate the remainder of x divided by u ) \n\t2dup \/ * - ;\n\n( @todo implement um\/mod in the VM, then use this to implement \/ and mod )\n: um\/mod ( x1 x2 -- rem quot : calculate the remainder and quotient of x1 divided by x2 ) \n\t2dup \/ >r mod r> ;\n\n: *\/ ( x1 x2 x3 -- x4 : multiply then divide, @warning this does not use a double cell for the multiply )\n\t * \/ ; \n\n: char ( -- x : read in a character from the input steam )\n\tkey drop key ;\n\n: [char] ( -- x : immediately read in a character from the input stream )\n\timmediate char [literal] ;\n\n: compose ( xt1 xt2 -- xt3 : create a new function from two xt-tokens )\n\t>r >r ( save execution tokens )\n\tpostpone :noname ( create a new :noname word for our xt-tokens )\n\tr> , ( write first token )\n\tr> , ( write second token )\n\tpostpone ; ; ( terminate new :noname )\n\n: unless ( bool -- : like 'if' but execute clause if false )\n\timmediate ['] 0= , postpone if ;\n\n: endif ( synonym for 'then' ) \n\timmediate postpone then ;\n\n: cells ( n1 -- n2 : convert a number of cells into a number of cells in address units ) \n\timmediate ;\n\n: cell+ ( a-addr1 -- a-addr2 ) \n\tcell + ;\n\n: negative? ( x -- bool : is a number negative? )\n\tsign-bit and logical ;\n\n: mask-byte ( x -- x : generate mask byte ) \n\t8* 255 swap lshift ;\n\n: select-byte ( u i -- c ) \n\t8* rshift 0xff and ;\n\n: xt-instruction ( extract instruction from execution token )\n\tcell+ @ >instruction ;\n\n: defined-word? ( CODE -- bool : is a word a defined or a built in words )\n\txt-instruction dolist = ;\n\n: char+ ( c-addr -- c-addr : increment a character address by the size of one character ) \n\t1+ ;\n\n: 2chars ( c-addr1 c-addr2 -- addr addr : convert two character addresses to two cell addresses ) \n\tchars swap chars swap ;\n\n: 2chars> ( addr addr -- c-addr c-addr: convert two cell addresses to two character addresses )\n\tchars> swap chars> swap ;\n\n: hex ( -- : print out hex ) \n\t16 base ! ;\n\n: octal ( -- : print out octal ) \n\t8 base ! ;\n\n: binary ( -- : print out binary ) \n\t2 base ! ;\n\n: decimal ( -- : print out decimal ) \n\t0 base ! ;\n\n: negate ( x -- x ) \n\t-1 * ;\n\n: abs ( x -- u : return the absolute value of a number )\n\tdup negative? if negate then ;\n\n: square ( x -- x ) \n\tdup * ;\n\n: sum-of-squares ( a b -- c : compute a^2 + b^2 to get c )\n\tsquare swap square + ;\n\n: drup ( x y -- x x ) \n\tdrop dup ;\n\n: +! ( x addr -- : add x to a value stored at addr ) \n\ttuck @ + swap ! ;\n\n: 1+! ( addr -- : increment a value at an address ) \n\t1 swap +! ;\n\n: 1-! ( addr -- : decrement a value at an address ) \n\t-1 swap +! ;\n\n: c+! ( x c-addr -- : add x to a value stored at c-addr )\n\ttuck c@ + swap c! ;\n\n: toggle ( addr u -- : complement the value at address with the bit pattern u ) \n\tover @ xor swap ! ;\n\n: lsb ( x -- x : mask off the least significant byte of a cell ) \n\t255 and ;\n\n: \\ ( -- : immediate word, used for single line comments )\n\timmediate begin key nl = until ;\n\n: ?dup ( x -- ? ) \n\tdup if dup then ;\n\n: min ( x y -- min : return the minimum of two integers ) \n\t2dup < if drop else swap drop then ;\n\n: max ( x y -- max : return the maximum of two integers ) \n\t2dup > if drop else swap drop then ;\n\n: limit ( x min max -- x : limit x with a minimum and maximum )\n\trot min max ;\n\n: >= ( x y -- bool ) \n\t< not ;\n\n: <= ( x y -- bool ) \n\t> not ;\n\n: 2@ ( a-addr -- x1 x2 : load two consecutive memory cells )\n\tdup 1+ @ swap @ ;\n\n: 2! ( x1 x2 a-addr -- : store two values as two consecutive memory cells )\n\t2dup ! nip 1+ ! ;\n\n: r@ ( -- x, R: x -- )\n\tr> r @ swap >r ;\n\n: rp@ ( -- x, R: x -- )\n\tr> r @ swap >r ;\n\n( @todo r!, rp! )\n\n: 0> ( x -- bool )\n\t0 > ;\n\n: 0< ( x -- bool )\n\t0 < ;\n\n: 0<> ( x -- bool )\n\t0 <> ;\n\n: signum ( x -- -1 | 0 | 1 : )\n\tdup 0< if drop -1 exit then\n\t 0> if 1 exit then\n\t0 ;\n\n: nand ( x x -- x : bitwise NAND ) \n\tand invert ;\n\n: odd ( x -- bool : is 'x' odd? )\n\t1 and ;\n\n: even ( x -- bool : is 'x' even? )\n\todd not ;\n\n: nor ( x x -- x : bitwise NOR ) \n\tor invert ;\n\n: ms ( u -- : wait at least 'u' milliseconds ) \n\tclock + begin dup clock u< until drop ;\n\n: sleep ( u -- : sleep for 'u' seconds )\n\t1000 * ms ;\n\n: align ( addr -- addr : align an address, nop in this implemented )\n\timmediate ; \n\n: ) ( -- : do nothing, this allows easy commenting out of code )\n\timmediate ;\n\n: bell ( -- : emit an ASCII BEL character ) \n\t7 emit ;\n\n: b\/buf ( -- u : bytes per buffer ) \n\t1024 ;\n\n: .d ( x -- x : debug print ) \n\tdup . ;\n\n: compile, ( x -- : )\n\t, ;\n\n: >mark ( -- : write a hole into the dictionary and push a pointer to it ) \n\there 0 , ;\n\n: r - r> u< ;\n\n: invalidate ( -- : invalidate this Forth core )\n\t1 `invalid ! ;\n\n: signed ( x -- bool : return true if sign bit set ) \n\t[ 1 size 8 * 1- lshift ] literal and logical ;\n\n: u>= ( x y -- bool : unsigned greater than or equal to )\n\t2dup u> >r = r> or ;\n\n: u<= ( x y -- bool : unsigned less than or equal to )\n\tu>= not ;\n\n: rdrop ( R: x -- : drop a value from the return stack )\n\tr> ( get caller's return address )\n\tr> ( get value to drop )\n\tdrop ( drop it like it's hot )\n\t>r ; ( return return address )\n\n: rdup\n\tr> ( get caller's return address )\n\tr> ( get value to duplicate )\n\tdup ( ... )\n\t>r >r >r ; ( make it all work )\n\n: again immediate\n\t( loop unconditionally in a begin-loop:\n\t\tbegin ... again )\n\t' branch , ;\n\n: source ( -- c-addr u )\n\t#tib ( size of input buffer, in characters )\n\ttib ; ( start of input buffer, in characters )\n\n: stdin? ( -- bool : are we reading from standard in? )\n\t`fin @ `stdin @ = ;\n\n: source-id ( -- 0 | -1 | file-id )\n\t( \t\n\tValue Input Source\n\t-1 String\n\t0 Reading from user input \/ standard in\n\tfile-id )\n\t`source-id @ \n\t0= if\n\t\tstdin? if 0 else `fin @ then\n\telse\n\t\t-1\n\tthen ;\n\n: under ( x1 x2 -- x1 x1 x2 )\n\t>r dup r> ;\n\n: 2nip ( n1 n2 n3 n4 -- n3 n4 ) \n\t>r >r 2drop r> r> ;\n\n: 2over ( n1 n2 n3 n4 \u2013 n1 n2 n3 n4 n1 n2 )\n\t>r >r 2dup r> swap >r swap r> r> -rot ;\n\n: 2swap ( n1 n2 n3 n4 \u2013 n3 n4 n1 n2 )\n\t>r -rot r> -rot ;\n\n: 2tuck ( n1 n2 n3 n4 \u2013 n3 n4 n1 n2 n3 n4 )\n\t2swap 2over ;\n\n: 3drop ( x1 x2 x3 -- )\n\t2drop ;\n\n: nos1+ ( x1 x2 -- x1+1 x2 : increment the next variable on that stack )\n\tswap 1+ swap ;\n\n: ?dup-if immediate ( x -- x | - : ?dup and if rolled into one! )\n\t['] ?dup , postpone if ;\n\n: ?if ( -- : non destructive if ) \n\timmediate ['] dup , postpone if ;\n\n: (hide) ( token -- hide-token : this hides a word from being found by the interpreter )\n\t?dup-if\n\t\tdup @ hidden-mask or swap tuck ! exit\n\tthen 0 ;\n\n: hide ( WORD -- : hide with drop ) \n\tfind dup if (hide) then drop ;\n\n: reveal ( hide-token -- : reveal a hidden word ) \n\tdup @ hidden-mask invert and swap ! ;\n\n: ?exit ( x -- : exit current definition if not zero ) \n\tif rdrop exit then ;\n\n: decimal? ( c -- f : is character a number? )\n\t[char] 0 [ char 9 1+ ] literal within ;\n\n: lowercase? ( c -- f : is character lower case? )\n\t[char] a [ char z 1+ ] literal within ;\n\n: uppercase? ( C -- f : is character upper case? )\n\t[char] A [ char Z 1+ ] literal within ;\n\n: alpha? ( C -- f : is character part of the alphabet? )\n\tdup lowercase? swap uppercase? or ;\n\n: alphanumeric? ( C -- f : is character alphabetic or a number ? )\n\tdup alpha? swap decimal? or ;\n\n: printable? ( c -- bool : is printable, excluding new lines and tables )\n\t32 127 within ;\n\n: >upper ( c -- C : convert char to uppercase iff lower case )\n\tdup lowercase? if bl xor then ;\n\n: >lower ( C -- c : convert char to lowercase iff upper case )\n\tdup uppercase? if bl xor then ;\n\n: <=> ( x y -- z : spaceship operator! )\n\t2dup\n\t> if 2drop -1 exit then\n\t< ;\n\n: start-address ( -- c-addr : push the start address )\n\t`start-address @ ;\n\n: >real-address ( c-addr -- r-addr : convert an interpreter address to a real address )\n\tstart-address + ;\n\n: real-address> ( c-addr -- r-addr : convert a real address to an interpreter address )\n\tstart-address - ;\n\n: peek ( r-addr -- n : )\n\tpad chars> >real-address swap size memory-copy pad @ ;\n\n: poke ( n r-addr -- : )\n\tswap pad ! pad chars> >real-address size memory-copy ;\n\n: die! ( x -- : controls actions when encountering certain errors )\n\t`error-handler ! ;\n\n: start! ( cfa -- : set the word to execute at startup )\n\t`instruction ! ;\t\n\n: warm ( -- : restart the interpreter, warm restart )\n\t1 restart ;\n\n: trip ( x -- x x x : triplicate a number ) \n\tdup dup ;\n\n: roll ( xu xu-1 ... x0 u -- xu-1 ... x0 xu : move u+1 items on the top of the stack by u )\n\tdup 0 >\n\tif\n\t\tswap >r 1- roll r> swap\n\telse\n\t\tdrop\n\tthen ;\n\n: 2rot ( n1 n2 n3 n4 n5 n6 \u2013 n3 n4 n5 n6 n1 n2 )\n\t5 roll 5 roll ;\n\n: s>d ( x -- d : convert a signed value to a double width cell )\n\t( @note the if...else...then is only necessary as this Forths\n\tbooleans are 0 and 1, not 0 and -1 as it usually is )\n\tdup 0< if -1 else 0 then ;\n\n: trace ( level -- : set tracing level )\n\t`debug ! ;\n\n: verbose ( -- : get the log level )\n\t`debug @ ;\n\n: count ( c-addr1 -- c-addr2 u : get a string whose first char is its length )\n\tdup c@ nos1+ ;\n\n: bounds ( x y -- y+x x : make an upper and lower bound )\n\tover + swap ;\n\n: aligned ( unaligned -- aligned : align a pointer )\n\t[ size 1- ] literal + \n\t[ size 1- ] literal invert and ;\n\n: rdepth\n\tmax-core `stack-size @ - r @ swap - ;\n\n: r.s ( -- : print the contents of the return stack )\n\tr> \n\t[char] < emit rdepth . [char] > emit\n\tspace\n\trdepth dup 0> if dup\n\tbegin dup while r> -rot 1- repeat drop dup\n\tbegin dup while rot dup . >r 1- repeat drop\n\tthen drop cr \n\t>r ;\n\n: argv ( -- r-addr : push pointer to array of string pointers to program )\n\t`argv @ ;\n\n: argc ( -- u : push the number of arguments in the argv array )\n\t`argc @ ;\n\n: +- ( x1 x2 -- x3 : copy the sign of x1 to x2 giving x3 )\n\t[ sign-bit 1- ] literal and\n\tswap\n\tsign-bit and or ;\n\n\nhide stdin?\n\n( ================================== DUMP ================================== )\n\\ : newline ( x -- x+1 : print a new line every fourth value )\n\\ \tdup 3 and 0= if cr then 1+ ;\n\\ \n\\ : address ( num count -- count : print current address we are dumping every fourth value )\n\\ \tdup >r\n\\ \t1- 3 and 0= if . [char] : emit space else drop then\n\\ \tr> ;\n\\ \n\\ : dump ( start count -- : print the contents of a section of memory )\n\\ \\\thex ( switch to hex mode )\n\\ \t1 >r ( save counter on return stack )\n\\ \tover + swap ( calculate limits: start start+count )\n\\ \tbegin \n\\ \t\t2dup u> ( stop if gone past limits )\n\\ \twhile \n\\ \t\tdup r> address >r\n\\ \t\tdup @ . 1+ \n\\ \t\tr> newline >r\n\\ \trepeat \n\\ \tr> drop\n\\ \t2drop ;\n\\ \n\\ hide newline\n\\ hide address \n( ================================== DUMP ================================== )\n\n: cfa immediate ( find-address -- cfa )\n\t( Given the address of the PWD field of a word this\n\tfunction will return an execution token for the word )\n\t( @todo if < dictionary start PWD is invalid )\n\t ;\n\n\\ : >body ( xt -- a-addr : a-addr is data field of a CREATEd word )\n\\\tcfa 5 + ;\n\n\n: execute ( xt -- : given an execution token, execute the word )\n\t( create a word that pushes the address of a hole to write to.\n\tA literal takes up two words, '!' takes up one, that's right,\n\tsome self modifying code! )\n\t[ here 3 cells + literal ] ( calculate place to write to )\n\t! ( write an execution token to a hole )\n\t[ 0 , ] ; ( this is the hole we write )\n\n( See: http:\/\/lars.nocrew.org\/dpans\/dpans9.htm\n@todo turn this into a lookup table of strings\n\n Code Reserved for\n ---- ------------\n -1 ABORT\n -2 ABORT\"\n -3 stack overflow\n -4 stack underflow\n -5 return stack overflow\n -6 return stack underflow\n -7 do-loops nested too deeply during execution\n -8 dictionary overflow\n -9 invalid memory address\n -10 division by zero\n -11 result out of range\n -12 argument type mismatch\n -13 undefined word\n -14 interpreting a compile-only word\n -15 invalid FORGET\n -16 attempt to use zero-length string as a name\n -17 pictured numeric output string overflow\n -18 parsed string overflow\n -19 definition name too long\n -20 write to a read-only location\n -21 unsupported operation [e.g., AT-XY on a\n too-dumb terminal]\n -22 control structure mismatch\n -23 address alignment exception\n -24 invalid numeric argument\n -25 return stack imbalance\n -26 loop parameters unavailable\n -27 invalid recursion\n -28 user interrupt\n -29 compiler nesting\n -30 obsolescent feature\n -31 >BODY used on non-CREATEd definition\n -32 invalid name argument [e.g., TO xxx]\n -33 block read exception\n -34 block write exception\n -35 invalid block number\n -36 invalid file position\n -37 file I\/O exception\n -38 non-existent file\n -39 unexpected end of file\n -40 invalid BASE for floating point conversion\n -41 loss of precision\n -42 floating-point divide by zero\n -43 floating-point result out of range\n -44 floating-point stack overflow\n -45 floating-point stack underflow\n -46 floating-point invalid argument\n -47 compilation word list deleted\n -48 invalid POSTPONE\n -49 search-order overflow\n -50 search-order underflow\n -51 compilation word list changed\n -52 control-flow stack overflow\n -53 exception stack overflow\n -54 floating-point underflow\n -55 floating-point unidentified fault\n -56 QUIT\n -57 exception in sending or receiving a character\n -58 [IF], [ELSE], or [THEN] exception )\n\n( @todo integrate catch\/throw into the interpreter as primitives )\n: catch ( xt -- exception# | 0 : return addr on stack )\n\tsp@ >r ( xt : save data stack pointer )\n\t`handler @ >r ( xt : and previous handler )\n\tr@ `handler ! ( xt : set current handler )\n\texecute ( execute returns if no throw )\n\tr> `handler ! ( restore previous handler )\n\tr> drop ( discard saved stack ptr )\n\t0 ; ( 0 : normal completion )\n\n( @todo use this everywhere )\n: throw ( ??? exception# -- ??? exception# )\n\t?dup-if ( exc# \\ 0 throw is no-op )\n\t\t`handler @ r ! ( exc# : restore prev return stack )\n\t\tr> `handler ! ( exc# : restore prev handler )\n\t\tr> swap >r ( saved-sp : exc# on return stack )\n\t\tsp! drop r> ( exc# : restore stack )\n\t\t( return to the caller of catch because return )\n\t\t( stack is restored to the state that existed )\n\t\t( when catch began execution )\n\tthen ; \n\n: interpret ( c1\" xxx\" ... cn\" xxx\" -- : This word implements the interpreter loop )\n\tbegin \n\t' read catch \n\t?dup-if [char] ! emit tab . cr then ( exception handler of last resort )\n\tagain ;\n\n: [interpret] ( c1\" xxx\" ... cn\" xxx\" -- : immediate version of interpret )\n\timmediate interpret ;\n\ninterpret ( use the new interpret word, which can catch exceptions )\n\nfind [interpret] cell+ start! ( the word executed on restart is now our new word )\n\n\n( ========================== Basic Word Set ================================== )\n\n( ========================== DOER\/MAKE ======================================= )\n( DOER\/MAKE is a word set that is quite powerful and is described in Leo Brodie's\nbook \"Thinking Forth\". It can be used to make words whose behavior can change\nafter they are defined. It essentially makes the structured use of self-modifying\ncode possible, along with the more common definitions of \"defer\/is\".\n\nAccording to \"Thinking Forth\", it has two purposes:\n\n1. To change the state of a function.\n2. To factor out common phrases of a words definition.\n\nAn example of the first instance:\n\n\tdoer say\n\t: sad \" Good bye, cruel World!\" cr ;\n\t: happy \" Hello, World!\" cr ;\n\n\t: person say ;\n\n\tmake person happy\n\tperson \\ prints \"Good bye, cruel World!\"\n\n\tmake person sad \n\tperson \\ prints \"Hello, World!\" \n\nAn example of the second:\n\n\tdoer op\n\n\t: sum \\ n0 ... nX X -- sum<0..X> \n\t\tmake op + 1 do op loop ;\n\n\t: mul \\ n0 ... nX X -- mul<0..X> \n\t\tmake op * 1 do op loop ;\n\nThe above example is a bit contrived, the definitions and functionality\nare too simple for this to be worth factoring out, but it shows how you\ncan use DOER\/MAKE. )\n\n: noop ; ( -- : default word to execute for doer )\n\n: doer ( c\" xxx\" -- : )\n\t:: ['] noop , postpone ; ;\n\n: found? ( xt -- xt : thrown an exception if the execution token is zero [not found] ) \n\tdup 0= if -13 throw then ;\n\n( It would be nice to provide a MAKE that worked with execution tokens\nas well, although \"defer\" and \"is\" can be used for that. MAKE expects\ntwo word names to be given as arguments. It will then change the behavior \nof the first word to use the second. MAKE is a state aware word. )\n\n: make immediate ( c1\" xxx\" c2\" xxx\" : change parsed word c1 to execute c2 )\n\tfind found? cell+\n\tfind found?\n\tstate @ if ( compiling )\n\t\tswap postpone 2literal ['] ! ,\n\telse ( command mode )\n\t\tswap !\n\tthen ;\n\nhide noop\n\n( ========================== DOER\/MAKE ======================================= )\n\n( ========================== Extended Word Set =============================== )\n\n: log ( u base -- u : command the logarithm of u in base )\n\t>r \n\tdup 0= if -11 throw then ( logarithm of zero is an error )\n\t0 swap\n\tbegin\n\t\tnos1+ rdup r> \/ dup 0= ( keep dividing until 'u' is zero )\n\tuntil\n\tdrop 1- rdrop ;\n\n: log2 ( u -- u : compute the logarithm of u )\n\t2 log ;\n\n: time ( \" ccc\" -- n : time the number of milliseconds it takes to execute a word )\n\tclock >r\n\tfind execute\n\tclock r> - ;\n\n( defer...is is probably not standards compliant, it is still neat! )\n: (do-defer) ( -- self : pushes the location into which it is compiled )\n\tr> dup >r 1- ;\n\n: defer ( \" ccc\" -- , Run Time -- location : \n\tcreates a word that pushes a location to write an execution token into )\n\t:: ' (do-defer) , postpone ; ;\n\n: is ( location \" ccc\" -- : make a deferred word execute a word ) \n\tfind found? swap ! ;\n\nhide (do-defer)\nhide found?\n\n( The \"tail\" function implements tail calls, which is just a jump\nto the beginning of the words definition, for example this\nword will never overflow the stack and will print \"1\" followed\nby a new line forever,\n\n\t: forever 1 . cr tail ;\n\nWhereas\n\n\t: forever 1 . cr recurse ;\n\nor\n\n\t: forever 1 . cr forever ;\n\nWould overflow the return stack. )\n\nhide tail\n: tail ( -- : perform tail recursion in current word definition )\n\timmediate\n\tlatest cell+\n\t' branch ,\n\there - cell+ , ;\n\n: recurse immediate\n\t( This function implements recursion, although this interpreter\n\tallows calling a word directly. If used incorrectly this will\n\tblow up the return stack.\n\n\tWe can test \"recurse\" with this factorial function:\n\t : factorial dup 2 < if drop 1 exit then dup 1- recurse * ; )\n\tlatest cell+ , ;\n\n: factorial ( x -- x : compute the factorial of a number )\n\tdup 2 < if drop 1 exit then dup 1- recurse * ;\n\n: myself ( -- : myself is a synonym for recurse ) \n\timmediate postpone recurse ;\n\n: gcd ( x1 x2 -- x : greatest common divisor )\n\tdup if tuck mod tail then drop ;\n\n( ========================== Extended Word Set =============================== )\n\n( The words described here on out get more complex and will require more\nof an explanation as to how they work. )\n\n( ========================== CREATE DOES> ==================================== )\n\n( The following section defines a pair of words \"create\" and \"does>\" which\nare a powerful set of words that can be used to make words that can create\nother words. \"create\" has both run time and compile time behavior, whilst\n\"does>\" only works at compile time in conjunction with \"create\". These two\nwords can be used to add constants, variables and arrays to the language,\namongst other things.\n\nA simple version of create is as follows\n\n\t: create :: dolist , here 2 cells + , ' exit , 0 state ! ;\n\nBut this version is much more limited.\n\n\"create\"...\"does>\" is one of the constructs that makes Forth Forth, it\nallows the creation of words which can define new words in themselves,\nand thus allows us to extend the language easily.\n)\n\n: write-quote ( -- : A word that writes ' into the dictionary )\n\t['] ' , ; \n\n: write-exit ( -- : A word that write exit into the dictionary )\n\t['] _exit , ;\n\n: write-compile, ( -- : A word that writes , into the dictionary ) \n\t' , , ;\n\n: state! ( bool -- : set the compilation state variable ) \n\tstate ! ;\n\n: command-mode ( -- : put the interpreter into command mode )\n\tfalse state! ;\n\n: command-mode-create ( create a new work that pushes its data field )\n\t:: ( compile a word )\n\tdolit , ( write push into new word )\n\there 2 cells + , ( push a pointer to data field )\n\tpostpone ; ; ( write exit and switch to command mode )\n\n: mark write-compile, ( Write in a place holder 0 and push a pointer to to be used by does> )\n\twrite-quote write-exit write-compile, ( Write in an exit in the word we're compiling. )\n\t['] command-mode , ; ( Make sure to change the state back to command mode )\n\n: create immediate ( create word is quite a complex forth word )\n\tstate @ \n\tif \n\t\tpostpone ( hole-to-patch -- )\n\timmediate\n\twrite-exit ( we don't want the defining word to exit, but the *defined* word to )\n\there swap ! ( patch in the code fields to point to )\n\tdolist , ; ( write a run in )\n\nhide write-quote\nhide write-compile,\nhide write-exit\n\n( Now that we have create...does> we can use it to create arrays, variables\nand constants, as we mentioned before. )\n\n: array ( u c\" xxx\" -- : create a named array of length u ) \n\tcreate allot does> + ;\n\n: variable ( x c\" xxx\" -- : create a variable will initial value of x )\n\tcreate , does> ;\n\n\\ : constant ( x c\" xxx\" -- : create a constant with value of x ) \n\\\tcreate , does> @ ;\n\n: table ( u c\" xxx\" --, Run Time: -- addr u : create a named table )\n\tcreate dup , allot does> dup @ ;\n\n: string ( u c\" xxx\" --, Run Time: -- c-addr u : create a named string )\n\tcreate dup , chars allot does> dup @ swap 1+ chars> swap ;\n\n\\ : +field \\ n <\"name\"> -- ; exec: addr -- 'addr\n\\ create over , +\n\\ does> @ + ;\n\\ \n\\ : begin-structure \\ -- addr 0 ; -- size\n\\ \tcreate\n\\ \there 0 0 , \\ mark stack, lay dummy\n\\ \tdoes> @ ; \\ -- rec-len\n\\ \n\\ : end-structure \\ addr n --\n\\ swap ! ; \\ set len \n\\ \n\\ begin-structure point\n\\ \tpoint +field p.x\n\\ \tpoint +field p.y\n\\ end-structure\n\\ \n\\ This should work...\n\\ : buffer: ( u c\" xxx\" --, Run Time: -- addr )\n\\\tcreate allot ;\n\n: 2constant \n\tcreate , , does> dup 1+ @ swap @ ;\n\n: 2variable \n\tcreate , , does> ;\n\n: enum ( x \" ccc\" -- x+1 : define a series of enumerations )\n\tdup constant 1+ ; \n\n( ========================== CREATE DOES> ==================================== )\n\n( ========================== DO...LOOP ======================================= )\n\n( The following section implements Forth's do...loop constructs, the\nword definitions are quite complex as it involves a lot of juggling of\nthe return stack. Along with begin...until do loops are one of the\nmain looping constructs. \n\nUnlike begin...until do accepts two values a limit and a starting value,\nthey are also words only to be used within a word definition, some Forths\nextend the semantics so looping constructs operate in command mode, this\nForth does not do that as it complicates things unnecessarily.\n\nExample:\n\t\n\t: example-1 10 1 do i . i 5 > if cr leave then loop 100 . cr ; \n\texample-1\n\nPrints:\n\t1 2 3 4 5 6\n\nIn \"example-1\" we can see the following:\n\n1. A limit, 10, and a start value, 1, passed to \"do\".\n2. A word called 'i', which is the current count of the loop\n3. If the count is greater than 5, we call a word call 'leave', this\nword exits the current loop context as well as the current calling\nword.\n4. \"100 . cr\" is never called. This should be changed in future\nrevision, but this version of leave exits the calling word as well.\n\n'i', 'j', and 'leave' *must* be used within a do...loop construct. \n\nIn order to remedy point 4. loop should not use branch but instead \nshould use a value to return to which it pushes to the return stack )\n\n: (do)\n\tswap ( swap the limit and start )\n\tr> ( save our return stack to temporary variable )\n\t-rot ( limit start return -- return start limit )\n\t>r ( push limit onto return stack )\n\t>r ( push start onto return stack )\n\t>r ; ( restore our return address )\n\n: do immediate ( Run time: high low -- : begin do...loop construct )\n\t' (do) ,\n\tpostpone begin ; \n\n: (unloop) ( -- , R: i limit -- : remove limit and i from )\n\tr> ( save our return address )\n\trdrop ( pop off i )\n\trdrop ( pop off limit )\n\t>r ; ( restore our return stack )\n\n: (+loop) ( x -- bool : increment loop variable by x and test it )\n\tr@ 1- ( get the pointer to i )\n\t+! ( add value to it )\n\tr@ 1- @ ( find i again )\n\tr@ 2- @ ( find the limit value )\n\tu>= ;\n\n: (loop) ( -- bool : increment loop variable by 1 and test it )\n\tr@ 1- ( get the pointer to i )\n\t1+! ( add one to it )\n\tr@ 1- @ ( find the value again )\n\tr@ 2- @ ( find the limit value )\n\tu>= ;\n\n: loop ( -- : end do...loop construct )\n\timmediate ' (loop) , postpone until ' (unloop) , ;\n\n: +loop ( x -- : end do...+loop loop construct )\n\timmediate ' (+loop) , postpone until ' (unloop) , ;\n\n: leave ( -- , R: i limit return -- : break out of a do-loop construct )\n\t(unloop)\n\trdrop ; ( return to the caller's caller routine )\n\n: ?leave ( x -- , R: i limit return -- | i limit return : conditional leave )\n\tif\n\t\t(unloop)\n\t\trdrop ( return to the caller's caller routine )\n\tthen ;\n\n: i ( -- i : Get current, or innermost, loop index in do...loop construct )\n\tr> r> ( pop off return address and i )\n\ttuck ( tuck i away )\n\t>r >r ; ( restore return stack )\n\n: j ( -- j : Get outermost loop index in do...loop construct )\n\t4 rpick ;\n\n( This is a simple test function for the looping, for interactive\ntesting and debugging:\n : mm 5 1 do i . cr 4 1 do j . tab i . cr loop loop ; )\n\n: range ( nX nY -- nX nX+1 ... nY ) \n\tnos1+ do i loop ;\n\n: repeater ( n0 X -- n0 ... nX ) \n\t1 do dup loop ;\n\n: sum ( n0 ... nX X -- sum<0..X> ) \n\t1 do + loop ;\n\n: mul ( n0 ... nX X -- mul<0..X> ) \n\t1 do * loop ;\n\n: reverse ( x1 ... xn n -- xn ... x1 : reverse n items on the stack )\n\t0 do i roll loop ;\n\n( ========================== DO...LOOP ======================================= )\n\n0 variable column-counter\n4 variable column-width\n\n: column ( i -- )\t\n\tcolumn-width @ mod not if cr then ;\n\n: column.reset\t\t\n\t0 column-counter ! ;\n\n: auto-column\t\t\n\tcolumn-counter dup @ column 1+! ;\n\n: alignment-bits \n\t[ 1 size log2 lshift 1- literal ] and ;\n\n0 variable x\n: x! ( x -- ) \n\tx ! ;\n\n: x@ ( -- x ) \n\tx @ ;\n\n: 2>r ( x1 x2 -- R: x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tswap\n\t\t>r\n\t\t>r\n\tx@ >r ; ( restore return address )\n\n: 2r> ( R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tr>\n\t\tr>\n\t\tswap\n\tx@ >r ; ( restore return address )\n\n: 2r@ ( -- x1 x2 , R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\tr> r>\n\t2dup\n\t>r >r\n\tswap\n\tx@ >r ; ( restore return address )\n\n: unused ( -- u : push the amount of core left ) \n\tmax-core here - ;\n\n: accumulator ( initial \" ccc\" -- : make a word that increments by a value and pushes the result )\n\tcreate , does> tuck +! @ ;\n\n: counter ( \" ccc\" --, Run Time: -- x : make a word that increments itself by one, starting from zero )\n\tcreate -1 , does> dup 1+! @ ;\n\n0 variable delim\n: accepter ( c-addr max delimiter -- i )\n\t( store a \"max\" number of chars at c-addr until \"delimiter\" encountered,\n\tthe number of characters stored is returned )\n\tdelim ! ( store delimiter used to stop string storage when encountered)\n\t0\n\tdo\n\t\tkey dup delim @ <>\n\t\tif\n\t\t\tover c! 1+\n\t\telse ( terminate string )\n\t\t\tdrop 0 swap c! \n\t\t\ti \n\t\t\tleave\n\t\tthen\n\tloop\n\t-18 throw ; ( read in too many chars )\nhide delim\n\n: skip ( char -- : read input until string is reached )\n\tkey drop >r 0 begin drop key dup rdup r> <> until rdrop ;\n\n: word ( c -- c-addr : parse until 'c' is encountered, push transient counted string )\n\tdup skip chere 1+ c!\n\t>r\n\tchere 2+\n\tpad here - chars>\n\tr> accepter 1+\n\tchere c!\n\tchere ;\nhide skip\n\n( This foreach mechanism needs thinking about, what is the best information to\npresent to the word to be executed? At the moment only the contents of the\ncell that it should be processing is.\n\nAt the moment foreach uses a do...loop construct, which means that the\nfollowing cannot be used to exit from the foreach loop:\n\n\t: return [ : exit early from a foreach loop ]\n\t\tr> rdrop >r ;\n\nAlthough this can be remedied, we know that it puts a loop onto the return\nstack.\n\nIt also uses a variable 'xt', which means that foreach loops cannot be\nnested. This word really needs thinking about.\n\nThis seems to be a useful, general, mechanism that is missing from\nmost Forths. More words like this should be made, they are powerful\nlike the word 'compose', but they need to be created correctly. )\n\n0 variable xt\n: foreach ( addr u xt -- : execute xt for each cell in addr-u )\n\txt !\n\tbounds do i xt @ execute 1 cell +loop ;\n\n: foreach-char ( c-addr u xt -- : execute xt for each cell in c-addr u )\n\txt !\n\tbounds do i xt @ execute loop ;\nhide xt\n\n: accept ( c-addr +n1 -- +n2 : see accepter definition ) \n\tnl accepter ;\n\n: (subst) ( char1 char2 c-addr )\n\t3dup ( char1 char2 c-addr char1 char2 c-addr )\n\tc@ = if ( char1 char2 c-addr char1 )\n\t\tswap c! ( match, substitute character )\n\telse ( char1 char2 c-addr char1 )\n\t\t2drop ( no match )\n\tthen ;\n\n: subst ( c-addr u char1 char2 -- replace all char1 with char2 in string )\n\tswap\n\t2swap\n\t['] (subst) foreach-char 2drop ;\nhide (subst)\n\n0xFFFF constant max-string-length\n\n: (.\") ( char -- c-addr u )\n\t( @todo This really needs simplifying, to do this\n\ta set of words that operate on a temporary buffer can\n\tbe used )\n\t( Write a string into word being currently defined, this\n\tcode has to jump over the string it has just put into the\n\tdictionary so normal execution of a word can continue. The\n\tlength and character address of the string are left on the\n\tstack )\n\t>r ( save delimiter )\n\t' branch , ( write in jump, this will jump past the string )\n\t>mark ( make hole )\n\tdup 1+ chars> ( calculate address to write to )\n\tmax-string-length \n\tr> ( restore delimiter )\n\taccepter dup >r ( write string into dictionary, save index )\n\taligned 2dup size \/ ( stack: length hole char-len hole )\n\t1+ dup allot ( update dictionary pointer with string length )\n\t1+ swap ! ( write place to jump to )\n\tdrop ( do not need string length anymore )\n\t1+ chars> ( calculate place to print )\n\tr> ; ( restore index and address of string )\n\n: length ( c-addr u -- u : push the length of an ASCIIZ string )\n tuck 0 do dup c@ 0= if 2drop i leave then 1+ loop ;\n\n: asciiz? ( c-addr u -- : is a Forth string also a ASCIIZ string )\n\ttuck length <> ;\n\n: asciiz ( c-addr u -- : trim a string until NUL terminator )\n\t2dup length nip ;\n\n\n: (type) ( c-addr -- ) \n\tc@ emit ;\n\n: type ( c-addr u -- : print out 'u' characters at c-addr )\n\t['] (type) foreach-char ;\nhide (type)\n\n: do-string ( char -- : write a string into the dictionary reading it until char is encountered )\n\t(.\") \n\tstate @ if swap [literal] [literal] then ;\n\n: fill ( c-addr u char -- : fill in an area of memory with a character, only if u is greater than zero )\n\t-rot\n\t0 do 2dup i + c! loop\n\t2drop ;\n\n: \/string ( c-addr1 u1 n -- c-addr2 u2 : advance a string by n characters )\n\tover min rot over + -rot - ;\n\n: compare ( c-addr1 u1 c-addr2 u2 -- n : compare two strings, not quite compliant yet )\n\t>r swap r> min >r\n\tstart-address + swap start-address + r>\n\tmemory-compare ;\n\n128 string sbuf\n: s\" ( \"ccc\" --, Run Time -- c-addr u )\n\tkey drop sbuf 0 fill sbuf [char] \" accepter sbuf drop swap ;\nhide sbuf\n\n( @todo these strings really need rethinking, state awareness needs to be removed... )\n: type, \n\tstate @ if ' type , else type then ;\n\n: c\" \n\timmediate key drop [char] \" do-string ;\n\n: \" \n\timmediate key drop [char] \" do-string type, ;\n\n: sprint ( c -- : print out chars until 'c' is encountered )\n\tkey drop ( drop next space )\n\t>r ( save delimiter )\n\tbegin\n\t\tkey dup ( get next character )\n\t\trdup r> ( get delimiter )\n\t\t<> if emit 0 then\n\tuntil rdrop ;\n\n: .( \n\timmediate [char] ) sprint ;\nhide sprint\n\n: .\" \n\timmediate key drop [char] \" do-string type, ;\n\nhide type,\n\n( This word really should be removed along with any usages of this word, it\nis not a very \"Forth\" like word, it accepts a pointer to an ASCIIZ string and\nprints it out, it also does not checking of the returned values from write-file )\n: print ( c-addr -- : print out a string to the standard output )\n\t-1 over >r length r> swap stdout write-file 2drop ;\n\n: ok \n\t\" ok\" cr ;\n\n: empty-stack ( x-n ... x-0 -- : empty the variable stack )\n\tbegin depth while drop repeat ;\n\n: (quit) ( -- : do the work of quit, without the restart )\n\t0 `source-id ! ( set source to read from file )\n\t`stdin @ `fin ! ( read from stdin )\n\tpostpone [ ( back into command mode )\n\t' interpret start! ; ( set interpreter starting word )\n\n: quit ( -- : Empty return stack, go back to command mode, read from stdin, interpret input )\n\t(quit)\n\t-1 restart ; ( restart the interpreter )\n\n: abort\n\t-1 throw ;\n\n: (abort\") ( do the work of abort )\n\t(quit)\n\t-2 throw ;\n\n: abort\" immediate \n\tpostpone \"\n\t' cr , ' (abort\") , ;\n\n( ==================== CASE statements ======================== )\n\n( for a simpler case statement:\n\tsee Volume 2, issue 3, page 48 of Forth Dimensions at\n\thttp:\/\/www.forth.org\/fd\/contents.html )\n\n( These case statements need improving, it is not standards compliant )\n: case immediate\n\t' branch , 3 , ( branch over the next branch )\n\there ' branch , ( mark: place endof branches back to with again )\n\t>mark swap ; ( mark: place endcase writes jump to with then )\n\n: over= ( x y -- x bool : over ... then = )\n\tover = ;\n\n: of\n\timmediate ' over= , postpone if ;\n\n: endof\n\timmediate over postpone again postpone then ;\n\n: endcase\n\timmediate 1+ postpone then drop ;\n\n( ==================== CASE statements ======================== )\n\n( ==================== Hiding Words =========================== )\n\n: }hide ( should only be matched with 'hide{' )\n\timmediate -22 throw ;\n\n: hide{ ( -- : hide a list of words, the list is terminated with \"}hide\" )\n\tbegin\n\t\tfind ( find next word )\n\t\tdup [ find }hide ] literal = if\n\t\t\tdrop exit ( terminate hide{ )\n\t\tthen\n\t\tdup 0= if -15 throw then\n\t\t(hide) drop\n\tagain ;\n\nhide (hide)\n\n( ==================== Hiding Words =========================== )\n\n: spaces ( n -- : print n spaces ) \n\t0 do space loop ;\n\n: erase ( addr u : erase a block of memory )\n\t2chars> 0 fill ;\n\n: blank ( c-addr u : fills a string with spaces )\n\tbl fill ;\n\n( move should check that u is not negative )\n: move ( addr1 addr2 u -- : copy u words of memory from 'addr2' to 'addr1' )\n\t0 do\n\t\t2dup i + @ swap i + !\n\tloop\n\t2drop ;\n\n( It would be nice if move and cmove could share more code, as they do exactly\n the same thing but with different load and store functions, cmove> )\n: cmove ( c-addr1 c-addr2 u -- : copy u characters of memory from 'c-addr2' to 'c-addr1' )\n\t0 do\n\t\t2dup i + c@ swap i + c!\n\tloop\n\t2drop ;\n\n( ==================== Conditional Compilation ================ )\n\n( The words \"[if]\", \"[else]\" and \"[then]\" implement conditional compilation,\nthey can be nested as well\n\nSee http:\/\/lars.nocrew.org\/dpans\/dpans15.htm for more information\n\nA much simpler conditional compilation method is the following\nsingle word definition:\n\n : compile-line? 0= if [ find \\\\ , ] then ;\n\nWhich will skip a line if a conditional is false, and compile it\nif true )\n\n( These words really, really need refactoring, I could use the newly defined \n \"defer\" to help out with this )\n0 variable nest ( level of [if] nesting )\n0 variable [if]-word ( populated later with \"find [if]\" )\n0 variable [else]-word ( populated later with \"find [else]\")\n: [then] immediate ;\n: reset-nest 1 nest ! ;\n: unnest? [ find [then] ] literal = if nest 1-! then ;\n: nest? [if]-word @ = if nest 1+! then ;\n: end-nest? nest @ 0= ;\n: match-[else]? [else]-word @ = nest @ 1 = and ;\n\n: [if] ( bool -- : conditional execution )\n\tunless\n\t\treset-nest\n\t\tbegin\n\t\t\tfind\n\t\t\tdup nest?\n\t\t\tdup match-[else]? if drop exit then\n\t\t\t unnest?\n\t\t\tend-nest?\n\t\tuntil\n\tthen ;\n\n: [else] ( discard input until [then] encounter, nesting for [if] )\n\treset-nest\n\tbegin\n\t\tfind\n\t\tdup nest? unnest?\n\t\tend-nest?\n\tuntil ;\n\nfind [if] [if]-word !\nfind [else] [else]-word !\n\n: ?( if postpone ( then ; \\ conditionally read until ')'\n: ?\\ if postpone \\ then ;\n: 16bit\\ size 2 <> if postpone \\ then ;\n: 32bit\\ size 4 <> if postpone \\ then ;\n: 64bit\\ size 8 <> if postpone \\ then ;\n\nhide{ \n\t[if]-word [else]-word nest \n\treset-nest unnest? match-[else]? \n\tend-nest? nest? \n}hide\n\n( ==================== Conditional Compilation ================ )\n\n( ==================== Endian Words =========================== )\n\nsize 2 = [if] 0x0123 `x ! [then]\nsize 4 = [if] 0x01234567 `x ! [then]\nsize 8 = [if] 0x01234567abcdef `x ! [then]\n\n: endian ( -- bool : returns the endianess of the processor, little = 0, big = 1 )\n\t[ `x chars> c@ 0x01 = ] literal ;\n\n: swap16 ( x -- x : swap the byte order a 16 bit number )\n\tdup 256* 0xff00 and >r 256\/ lsb r> or ;\n\nsize 4 >= [if] \n\t: swap32 \n\t\tdup 0xffff and swap16 16 lshift swap\n\t\t16 rshift 0xffff and swap16 or ;\n[then]\n\nsize 8 >= [if]\n\t: swap64 ( x -- x : swap the byte order of a 64 bit number )\n\t\t dup 0xffffffff and swap32 32 lshift swap\n\t\t 32 rshift 0xffffffff and swap32 or ;\n[then]\n\nsize 2 = [if]\n\tendian \n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\tswap16 ;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\t;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\tswap16 ;\n\t[then]\n[then]\n\nsize 4 = [if]\n\tendian \n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\tswap32 ;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\t;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\tswap32 ;\n\t[then]\n[then]\n\nsize 8 = [if]\n\tendian \n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\tswap64 ;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\t;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\tswap64 ;\n\t[then]\n[then]\n\n( ==================== Endian Words =========================== )\n\n( ==================== Misc words ============================= )\n\n: (base) ( -- base : unmess up libforth's base variable )\n\tbase @ 0= if 10 else base @ then ;\n\n: #digits ( u -- u : number of characters needed to represent 'u' in current base )\n\tdup 0= if 1+ exit then\n\t(base) log 1+ ;\n\n: digits ( -- u : number of characters needed to represent largest unsigned number in current base )\n\t-1 #digits ;\n\n: print-number ( u -- print a number taking up a fixed amount of space on the screen )\n\tbase @ 16 = if . exit then ( @todo this is a hack related to libforth printing out hex specially)\n\tdup #digits digits swap - dup 0<> if spaces else drop then . ;\n\n: address ( u -- : print out and address )\n\t@ print-number ;\n\n0 variable counter\n\n: counted-column ( index -- : special column printing for dump )\n\tcounter @ column-width @ mod\n\tnot if cr print-number \" :\" space else drop then\n\tcounter 1+! ;\n\n: as-chars ( x n -- : print a cell out as characters, upto n chars )\n\t0 ( from zero to the size of a cell )\n\tdo\n\t\tdup ( copy variable to print out )\n\t\tsize i 1+ - select-byte ( select correct byte )\n\t\tdup printable? not ( is it not printable )\n\t\tif drop [char] . then ( print a '.' if it is not )\n\t\temit ( otherwise print it out )\n\tloop\n\tspace ( print out space after )\n\tdrop ; ( drop cell we have printed out )\n\n: lister ( addr u addr -- )\n\t0 counter ! 1- swap \n\tdo \n\t\tdup counted-column 1+ i address i @ size as-chars \n\tloop ;\n\n( @todo this function should make use of 'defer' and 'is', then different\nversion of dump could be made that swapped out 'lister' )\n: dump ( addr u -- : dump out 'u' cells of memory starting from 'addr' )\n\t1+ over + under lister drop \n\tcr ;\n\nhide{ counted-column counter as-chars address print-number }hide\n\n( Fence can be used to prevent any word defined before it from being forgotten \nUsage:\n\there fence ! )\n0 variable fence\n\n: forgetter ( pwd-token -- : forget a found word and everything after it )\n\tdup 0= if -15 throw then ( word not found! )\n\tdup fence @ u< if -15 throw then ( forgetting a word before fence! )\n\tdup @ pwd ! h ! ;\n\n: forget ( WORD -- : forget word and every word defined after it )\n\tfind 1- forgetter ;\n\n: marker ( WORD -- : make word the forgets itself and words after it)\n\t:: latest [literal] ' forgetter , postpone ; ;\nhide forgetter\n\n: ** ( b e -- x : exponent, raise 'b' to the power of 'e')\n\t?dup-if\n\t\tover swap\n\t\t1 do over * loop \n\t\tnip\n\telse\n\t\tdrop 1\n\tendif ;\n\n0 variable a\n0 variable b\n0 variable m\n: equal ( a1...an b1...bn n -- a1...an b1...bn bool : determine if two lists are equal )\n\t( example: \n\t\t1 2 3 \n\t\t1 2 3 \n\t\t3 equal \n\treturns: 1 )\n\tdup m ! 1+ 1 ( store copy of length and use as loop index )\n\tdo \n\t\ti 1- pick b ! ( store ith element of list in b1...bn )\n\t\ti m @ + 1- pick a ! ( store ith element of list in a1...an )\n\t\ta @ b @ <> ( compare a and b for equality )\n\t\tif 0 leave then ( unequal, finish early )\n\tloop 1 ; ( lists must be equal )\n\nhide{ a b m }hide\n\n: ndrop ( drop n items )\n\t?dup-if 0 do drop loop then ;\n\n: caesar ( c key -- o : encode a alphabetic character with a key using a generalization of the Caesar cipher )\n\t>r\n\tdup uppercase? if [char] A - r> + 26 mod [char] A + exit then\n\tdup lowercase? if [char] a - r> + 26 mod [char] a + exit then\n\trdrop ; ( it goes without saying that this should not be used for anything serious! )\n\n: caesar-type ( c-addr u key : type out encoded text with a Caesar cipher )\n\t-rot bounds do i c@ over caesar emit loop drop ;\n\n: rot13 ( c -- c : encode a character with ROT-13 )\n\t13 caesar ;\n\n: rot13-type ( c-addr u : print string in ROT-13 encoded form )\n\t13 caesar-type ;\n\n\\ s\" abcdefghijklmnopqrstuvwxyz\" rot13-type -> nopqrstuvwxyzabcdefghijklm\n\\ s\" hello\" rot13-type -> uryyb\n\n( ==================== Misc words ============================= )\n\n( ==================== Pictured Numeric Output ================ )\n( Pictured numeric output is what Forths use to display numbers\nto the screen, this Forth has number output methods built into\nthe Forth kernel and mostly uses them instead, but the mechanism\nis still useful so it has been added.\n\n@todo Pictured number output should act on a double cell number\nnot a single cell number )\n\n0 variable hld\n\n: overflow ( -- : check if we overflow the hold area )\n \there chars> pad chars> hld @ - u> if -17 throw then ;\n\n: hold ( char -- : add a character to the numeric output string )\n\toverflow pad chars> hld @ - c! hld 1+! ;\n\n: holds ( addr u -- )\n begin dup while 1- 2dup + c@ hold repeat 2drop ;\n\n: nbase ( -- base : in this forth 0 is a special base, push 10 is base is zero )\n\tbase @ dup 0= if drop 10 then ;\n\n: <# ( -- : setup pictured numeric output )\n\t0 hld ! ;\n\n: sign ( -- : add a sign to the pictured numeric output string )\n\t[char] - hold ;\n\n: # ( x -- x : divide x by base, turn into a character, put in pictured output string )\n\tnbase um\/mod swap \n \tdup 9 u>\n \tif 7 + then\n \t48 + hold ;\n\n: #s ( x -- 0 : repeatedly call # on x until x is zero )\n\tbegin # dup 0= until ; \n\n: #> ( -- c-addr u : end pictured output conversion, push output string to stack )\n\t0 hold ( NUL terminate string, just in case )\n\thld 1-! ( but do not include that in the count )\n\tpad chars> hld @ \n\ttuck - 1+ swap ;\n\n: u. ( u -- : display number in base 10 )\n\tbase @ >r decimal <# #s #> type drop r> base ! ;\n\nhide{ nbase overflow }hide\n\n( ==================== Pictured Numeric Output ================ )\n\n( ==================== Numeric Input ========================= )\n( The Forth executable can handle numeric input and does not need\nthe routines defined here, however the user might want to write\nroutines that use >NUMBER. >NUMBER is a generic word, but it\nis a bit difficult to use on its own. )\n\n: map ( char -- n|-1 : convert character in 0-9 a-z range to number )\n\tdup lowercase? if [char] a - 10 + exit then\n\tdup decimal? if [char] 0 - exit then\n\tdrop -1 ;\n\n: number? ( char -- bool : is a character a number in the current base )\n\t>lower map (base) u< ;\n\n: >number ( n c-addr u -- n c-addr u : convert string )\n\tbegin\n\t\t( get next character )\n\t\t2dup >r >r drop c@ dup number? ( n char bool, R: c-addr u )\n\t\tif ( n char )\n\t\t\tswap (base) * swap map + ( accumulate number )\n\t\telse ( n char )\n\t\t\tdrop\n\t\t\tr> r> ( restore string )\n\t\t\texit\n\t\tthen\n\t\tr> r> ( restore string )\n\t\t1 \/string dup 0= ( advance string and test for end )\n\tuntil ;\n\nhide{ map }hide\n\n( ==================== Numeric Input ========================= )\n\n( ==================== ANSI Escape Codes ====================== )\n( Terminal colorization module, via ANSI Escape Codes\n \nsee: https:\/\/en.wikipedia.org\/wiki\/ANSI_escape_code\nThese codes will provide a relatively portable means of\nmanipulating a terminal )\n\n27 constant 'escape'\n: CSI 'escape' emit .\" [\" ;\n0 constant black\n1 constant red\n2 constant green\n3 constant yellow\n4 constant blue\n5 constant magenta\n6 constant cyan\n7 constant white\n: foreground 30 + ;\n: background 40 + ;\n0 constant dark\n1 constant bright\nfalse variable colorize \n\n: color ( brightness color-code -- : set the terminal color )\n\t( set color on an ANSI compliant terminal,\n\tfor example:\n\t\tbright red foreground color\n\tsets the foreground text to bright red )\n\tcolorize @ 0= if 2drop exit then \n\tCSI u. if .\" ;1\" then .\" m\" ;\n\n: at-xy ( x y -- : set ANSI terminal cursor position to x y )\n\tCSI u. [char] ; emit u. .\" H\" ;\n\n: page ( -- : clear ANSI terminal screen and move cursor to beginning ) \n\tCSI .\" 2J\" 1 1 at-xy ;\n\n: hide-cursor ( -- : hide the cursor from view ) \n\tCSI .\" ?25l\" ;\n\n: show-cursor ( -- : show the cursor ) \n\tCSI .\" ?25h\" ;\n\n: save-cursor ( -- : save cursor position ) \n\tCSI .\" s\" ;\n\n: restore-cursor ( -- : restore saved cursor position ) \n\tCSI .\" u\" ;\n\n: reset-color ( -- : reset terminal color to its default value)\n\tcolorize @ 0= if exit then\n\tCSI .\" 0m\" ;\n\nhide{ CSI }hide\n( ==================== ANSI Escape Codes ====================== )\n\n( ==================== Unit test framework =================== )\n\n256 string estring ( string to test )\n0 variable #estring ( actual string length )\n0 variable start ( starting depth )\n0 variable result ( result depth )\n0 variable check ( only check depth if -> is called )\n0 variable dictionary ( dictionary pointer on entering { )\n0 variable previous ( PWD register on entering { )\n\n: T ; ( hack until T{ can process words )\n\n: -> ( -- : save depth in variable ) \n\t1 check ! depth result ! ; \n\n: test estring drop #estring @ ; \n\n: fail ( -- : invalidate the forth interpreter and exit )\n\tinvalidate bye ;\n\n: neutral ( -- : neutral color )\n\t;\n\n: bad ( -- : bad color )\n\tdark red foreground color ;\n\n: good ( -- : good color )\n\tdark green foreground color ;\n\n: die bad test type reset-color cr fail ;\n\n: evaluate? ( bool -- : test if evaluation has failed )\n\tif .\" evaluation failed\" cr fail then ;\n\n: failed bad .\" failed\" reset-color cr ;\n\n: adjust ( x -- x : adjust a depth to take into account starting depth ) \n\tstart @ - ;\n\n: no-check? ( -- bool : if true we need to check the depth )\n\tcheck @ 0= ;\n\n: depth? ( -- : check if depth is correct )\n\tno-check? if exit then\n\tdepth adjust ( get depth and adjust for starting depth )\n\tresult @ adjust 2* = ( get results depth, same adjustment, should be\n\t half size of the depth ) \n\tif exit then ( pass )\n\tfailed\n\t.\" Unequal depths:\" cr\n\t.\" depth: \" depth . cr\n\t.\" result: \" result @ . cr\n\tdie ;\n\n: equal? ( -- : determine if results equals expected )\n\tno-check? if exit then\n\tresult @ adjust equal\n\tif exit then\n\tfailed\n\t.\" Result is not equal to expected values. \" cr \n\t.\" Stack: \" cr .s cr\n\tdie ;\n\n: display ( c-addr u -- : print out testing message in estring )\n\tverbose if neutral type else 2drop then ;\n\n: pass ( -- : print out passing message )\n\tverbose if good .\" ok \" cr reset-color then ;\n\n: save ( -- : save current dictionary )\n\tpwd @ previous !\n\there dictionary ! ;\n\n: restore ( -- : restore dictionary )\n\tprevious @ pwd ! \n\tdictionary @ h ! ;\n\n\n: T{ ( -- : perform a unit test )\n\tdepth start ! ( save start of stack depth )\n\t0 result ! ( reset result variable )\n\t0 check ! ( reset check variable )\n\testring 0 fill ( zero input string )\n\tsave ( save dictionary state )\n\tkey drop ( drop next character, which is a space )\n\testring [char] } accepter #estring ! ( read in string to test )\n\ttest display ( print which string we are testing )\n\ttest evaluate ( perform test )\n\tevaluate? ( evaluate successfully? )\n\tdepth? ( correct depth )\n\tequal? ( results equal to expected values? )\n\tpass ( print pass message )\n\tresult @ adjust 2* ndrop ( remove items on stack generated by test )\n\trestore ; ( restore dictionary to previous state )\n\nT{ }T\nT{ -> }T\nT{ 1 -> 1 }T\nT{ 1 2 -> 1 2 }T\nT{ : c 1 2 ; c -> 1 2 }T\nT{ :noname 2 ; :noname 3 + ; compose execute -> 5 }T\n\nhide{ \n\tpass test display\n\tadjust start save restore dictionary previous \n\tevaluate? equal? depth? estring #estring result\n\tcheck no-check? die neutral bad good failed\n}hide\n\n( ==================== Unit test framework =================== )\n\n\n( ==================== Random Numbers ========================= )\n\n( \nSee:\nuses xorshift\nhttps:\/\/en.wikipedia.org\/wiki\/Xorshift\nhttp:\/\/excamera.com\/sphinx\/article-xorshift.html\nhttp:\/\/www.arklyffe.com\/main\/2010\/08\/29\/xorshift-pseudorandom-number-generator\/\nthese constants have be collected from the web \n)\n\nsize 2 = [if] 13 constant a 9 constant b 7 constant c [then]\nsize 4 = [if] 13 constant a 17 constant b 5 constant c [then]\nsize 8 = [if] 12 constant a 25 constant b 27 constant c [then]\n\n7 variable seed ( must not be zero )\n\n: seed! ( x -- : set the value of the PRNG seed )\n\tdup 0= if drop 7 ( zero not allowed ) then seed ! ;\n\n: random ( -- x : assumes word size is 32 bit )\n\tseed @\n\tdup a lshift xor\n\tdup b rshift xor\n\tdup c lshift xor\n\tdup seed! ;\n\nhide{ a b c seed }hide\n\n( ==================== Random Numbers ========================= )\n\n( ==================== Prime Numbers ========================== )\n( From original \"third\" code from the IOCCC at \nhttp:\/\/www.ioccc.org\/1992\/buzzard.2.design, the module works out\nand prints prime numbers. )\n\n: prime? ( u -- u | 0 : return number if it is prime, zero otherwise )\n\tdup 1 = if 1- exit then\n\tdup 2 = if exit then\n\tdup 2\/ 2 ( loop from 2 to n\/2 )\n\tdo\n\t\tdup ( value to check if prime )\n\t\ti mod ( mod by divisor )\n\t\tnot if\n\t\t\tdrop 0 leave\n\t\tthen\n\tloop ;\n\n0 variable counter\n\n: primes ( x1 x2 -- : print the primes from x2 to x1 )\n\t0 counter !\n\t\" The primes from \" dup . \" to \" over . \" are: \"\n\tcr\n\tcolumn.reset\n\tdo\n\t\ti prime?\n\t\tif\n\t\t\ti . counter @ column counter 1+!\n\t\tthen\n\tloop\n\tcr\n\t\" There are \" counter @ . \" primes.\"\n\tcr ;\n\nhide{ counter }hide\n( ==================== Prime Numbers ========================== )\n\n( ==================== Debugging info ========================= )\n\n( string handling should really be done with PARSE, and CMOVE )\n\n: sh ( cnl -- ior : execute a line as a system command )\n\tnl word count system ;\n\nhide{ .s }hide\n: .s ( -- : print out the stack for debugging )\n\t[char] < emit depth u. [char] > emit space\n\tdepth if\n\t\tdepth 0 do i column tab depth i 1+ - pick . loop\n\tthen\n\tcr ;\n\n1 variable hide-words ( do we want to hide hidden words or not )\n\n: name ( PWD -- c-addr : given a pointer to the PWD field of a word get a pointer to the name of the word )\n\tdup 1+ @ 256\/ word-mask and lsb - chars> ;\n\n( This function prints out all of the defined words, excluding hidden words.\nAn understanding of the layout of a Forth word helps here. The dictionary\ncontains a linked list of words, each forth word has a pointer to the previous\nword until the first word. The layout of a Forth word looks like this:\n\nNAME: Forth Word - A variable length ASCII NUL terminated string\nPWD: Previous Word Pointer, points to the previous word\nCODE: Flags, code word and offset from previous word pointer to start of Forth word string\nDATA: The body of the forth word definition, not interested in this.\n\nThere is a register which stores the latest defined word which can be\naccessed with the code \"pwd @\". In order to print out a word we need to\naccess a words CODE field, the offset to the NAME is stored here in bits\n8 to 14 and the offset is calculated from the PWD field.\n\n\"print\" expects a character address, so we need to multiply any calculated\naddress by the word size in bytes. )\n\n: words.immediate ( bool -- : emit or mark a word being printed as being immediate )\n\tnot if dark red foreground color then ;\n\n: words.defined ( bool -- : emit or mark a word being printed as being a built in word )\n\tnot if bright green background color then ;\n\n: words.hidden ( bool -- : emit or mark a word being printed as being a hidden word )\n\tif dark magenta foreground color then ;\n\n: words ( -- : print out all defined an visible words )\n\tlatest\n\tspace\n\tbegin\n\t\tdup\n\t\thidden? hide-words @ and\n\t\tnot if\n\t\t\thidden? words.hidden\n\t\t\tcompiling? words.immediate\n\t\t\tdup defined-word? words.defined\n\t\t\tname\n\t\t\tprint space\n\t\t\treset-color\n\t\telse\n\t\t\tdrop\n\t\tthen\n\t\t@ ( Get pointer to previous word )\n\t\tdup dictionary-start u< ( stop if pwd no longer points to a word )\n\tuntil\n\tdrop cr ;\n\n( Simpler version of words\n: words\n\tpwd @ \n\tbegin\n\t\tdup name print space @ dup dictionary-start u<\n\tuntil drop cr ; )\n\nhide{ words.immediate words.defined words.hidden hidden? hidden-bit }hide\n\n: TrueFalse ( -- : print true or false )\n\tif \" true\" else \" false\" then ;\n\n: registers ( -- : print out important registers and information about the virtual machine )\n\t\" return stack pointer: \" r@ . cr\n\t\" dictionary pointer \" here . cr\n\t\" previous word: \" pwd ? cr\n\t\" state: \" state ? cr\n\t\" base: \" base ? cr\n\t\" depth: \" depth . cr\n\t\" cell size (in bytes): \" size . cr\n\t\" last cell address: \" max-core . cr\n\t\" unused cells: \" unused . cr\n\t\" invalid: \" `invalid @ TrueFalse cr\n\t\" size of variable stack: \" `stack-size ? cr\n\t\" size of return stack: \" `stack-size ? cr\n\t\" start of variable stack: \" max-core `stack-size @ 2* - . cr\n\t\" start of return stack: \" max-core `stack-size @ - . cr\n\t\" current input source: \" source-id -1 = if \" string\" else \" file\" then cr\n\t\" tracing on: \" `debug @ TrueFalse cr\n\t\" starting word: \" `instruction ? cr\n\t\" real start address: \" `start-address ? cr\n\t\" error handling: \" `error-handler ? cr \n\t\" throw handler: \" `handler ? cr\n\t\" signal recieved: \" `signal ? cr ;\n\t\n( `sin `sidx `slen `fout\n `stdout `stderr `argc `argv )\n\n\n: y\/n? ( -- bool : ask a yes or no question )\n\tkey drop\n\t\" y\/n? \"\n\tbegin\n\t\tkey\n\t\tdup\n\t\t[char] y = if true exit then\n\t\t[char] n = if false exit then\n\t\t\" y\/n? \"\n\tagain ;\n\n: step\n\t( step through a word: this word could be augmented\n\twith commands such as \"dump\", \"halt\", and optional\n\t\".s\" and \"registers\" )\n\tregisters\n\t\" .s: \" .s cr\n\t\" -- press any key to continue -- \"\n\tkey drop ;\n\n: more ( -- : wait for more input )\n\t\" -- press any key to continue -- \" key drop cr page ;\n\n: debug-help ( -- : print out the help for the debug command )\n \" debug mode commands\n\th - print help\n\tq - exit interpreter word\n\tr - print registers\n\ts - print stack\n\tR - print return stack\n\tc - continue on with execution\n\" ;\n\ndoer debug-prompt\n: prompt-default\n\t.\" debug> \" ;\n\nmake debug-prompt prompt-default\n\n: debug ( -- : enter interactive debug prompt )\n\tcr\n\t\" Entered Debug Prompt. Type 'h' for help. \" cr \n\tbegin\n\t\tkey\n\t\tcase\n\t\t\tnl of debug-prompt endof\n\t\t\t[char] h of debug-help endof\n\t\t\t[char] q of bye endof\n\t\t\t[char] r of registers endof\n\t\t\t[char] s of >r .s r> endof\n\t\t\t[char] R of r> r.s >r endof\n\t\t\t[char] c of drop exit endof\n\t\t\t( @todo add throw here )\n\t\tendcase drop\n\tagain ;\nhide debug-prompt\n\n: code>pwd ( CODE -- PWD\/0 : calculate PWD from code address )\n\tdup dictionary-start here within not if drop 0 exit then\n\t1 cells - ;\n\n: word-printer ( CODE -- : print out a words name given its code field )\n\tdup 1 cells - @ -1 = if . \" noname\" exit then ( nonames are marked by a -1 before its code field )\n\tdup code>pwd ?dup-if .d name print else drop \" data\" then\n\t drop ;\n\nhide{ code>pwd }hide\n\n( these words push the execution tokens for various special cases for decompilation )\n: get-branch [ find branch ] literal ;\n: get-?branch [ find ?branch ] literal ;\n: get-original-exit [ find _exit ] literal ;\n: get-quote [ find ' ] literal ;\n\n( @todo replace 2- nos1+ nos1+ with appropriate word, like the string word \nthat increments a string by an amount, but that operates on CELLS )\n: branch-increment ( addr branch -- increment : calculate decompile increment for \"branch\" )\n\t1+ dup negative? \n\tif \n\t\tover cr . [char] : emit space . cr 2 \n\telse \n\t\t2dup 2- nos1+ nos1+ dump \n\tthen ;\n\n( these words take a code field to a primitive they implement, decompile it\nand any data belonging to that operation, and push a number to increment the\ndecompilers code stream pointer by )\n\n: decompile-literal ( code -- increment )\n\t1+ ? \" literal\" 2 ;\n\n: decompile-branch ( code -- increment )\n\tdark red foreground color\n\t1+ ? \" branch \" dup 1+ @ branch-increment ;\n\n: decompile-quote ( code -- increment )\n\tdark green foreground color\n\tdup\n\t[char] ' emit 1+ @ word-printer 2 reset-color ;\n\n: decompile-?branch ( code -- increment )\n\t1+ ? \" ?branch\" 2 ;\n\n: decompile-exit ( code -- 0 )\n\t\" _exit\" cr \" End of word: \" . 0 ;\n\n( The decompile word expects a pointer to the code field of a word, it\ndecompiles a words code field, it needs a lot of work however.\nThere are several complications to implementing this decompile\nfunction.\n\n\t' The next cell should be pushed\n\t:noname This has a marker before its code field of -1 which\n\t\t cannot occur normally, this is handled in word-printer\n\tbranch branches are used to skip over data, but also for\n\t\t some branch constructs, any data in between can only\n\t\t be printed out generally speaking\n\texit There are two definitions of exit, the one used in\n\t\t ';' and the one everything else uses, this is used\n\t\t to determine the actual end of the word\n\tliterals Literals can be distinguished by their low value,\n\t\t which cannot possibly be a word with a name, the\n\t\t next field is the actual literal\n\nOf special difficult is processing 'if' 'else' 'then' statements,\nthis will require keeping track of '?branch'.\n\nAlso of note, a number greater than \"here\" must be data )\n\n: decompile ( code-pointer -- code-pointer increment|0 : )\n\t.d [char] : emit space dup @\n\tcase\n\t\tdolit of drup decompile-literal cr endof\n\t\tget-branch of drup decompile-branch endof\n\t\tget-quote of drup decompile-quote cr endof\n\t\tget-?branch of drup decompile-?branch cr endof\n\t\tget-original-exit of drup decompile-exit endof\n\t\tword-printer 1 cr\n\tendcase reset-color ;\n\n: decompiler ( code-field-ptr -- : decompile a word in its entirety )\n\tbegin decompile over + tuck = until drop ;\n\nhide{\n\tword-printer get-branch get-?branch get-original-exit \n\tget-quote branch-increment decompile-literal \n\tdecompile-branch decompile-?branch decompile-quote\n\tdecompile-exit\n}hide\n\n( these words expect a pointer to the PWD field of a word )\n: see.name \" name: \" name print cr ;\n: see.start \" word start: \" name chars . cr ;\n: see.previous \" previous word: \" @ . cr ;\n: see.immediate \" immediate: \" compiling? swap drop not TrueFalse cr ;\n: see.instruction \" instruction: \" xt-instruction . cr ;\n: see.defined \" defined: \" defined-word? TrueFalse cr ;\n\n: see.header ( PWD -- is-immediate-word? )\n\tdup see.name\n\tdup see.start\n\tdup see.previous\n\tdup see.immediate\n\tdup see.instruction ( @todo look up instruction name )\n\tsee.defined ;\n\n( @todo This does not work for all words, so needs fixing. \n Specifically: \n\t2variable\n\t2constant\n\ttable\n\tconstant\n\tvariable\n\tarray \nWhich are all complex CREATE words\n\nA good way to test decompilation is with the following Unix pipe: \n\n\t.\/forth -f forth.fth -e words \n\t\t| sed 's\/ \/ see \/g' \n\t\t| .\/forth -t forth.fth &> decompiled.log\n)\n\n( @todo refactor into word that takes a PWD pointer and one that attempts to parse\/find name )\n: see ( c\" xxx\" -- : decompile the next word in the input stream )\n\tfind\n\tdup 0= if -32 throw then\n\t-1 cells + ( move to PWD field )\n\tdup see.header\n\tdup defined-word?\n\tif ( decompile if a compiled word )\n\t\t2 cells + ( move to code field )\n\t\t\" code field:\" cr\n\t\tdecompiler\n\telse ( the instruction describes the word if it is not a compiled word )\n\t\tdup 1 cells + @ instruction-mask and doconst = if ( special case for constants )\n\t\t\t\" constant: \" 2 cells + @ .\n\t\telse\n\t\t\tdrop\n\t\tthen\n\tthen cr ;\n\nhide{ \n\tsee.header see.name see.start see.previous see.immediate \n\tsee.instruction defined-word? see.defined\n}hide\n\n( These help messages could be moved to blocks, the blocks could then\nbe loaded from disk and printed instead of defining the help here,\nthis would allow much larger help )\n\n: help ( -- : print out a short help message )\n\tpage\n\tkey drop\n\" Welcome to Forth, an imperative stack based language. It is both a low\nlevel and a high level language, with a very small memory footprint. Most\nof Forth is defined as a combination of various primitives.\n\nA short description of the available function (or Forth words) follows,\nwords marked (1) are immediate and cannot be used in command mode, words\nmarked with (2) define new words. Words marked with (3) have both command\nand compile functionality.\n\n\"\nmore \" Some of the built in words that accessible are:\n\n(1,2)\t: define a new word, switching to compile mode\n\timmediate make latest defined word immediate\n\tread read in a word, execute in command mode else compile\n\t@ ! fetch, store\n\tc@ c! character based fetch and store\n\t- + * \/ standard arithmetic operations,\n\tand or xor invert standard bitwise operations\n\tlshift rshift left and right bit shift\n\tu< u> < > = comparison predicates\n\texit exit from a word\n\temit print character from top of stack\n\tkey get a character from input\n\tr> >r pop a value from or to the return stack\n\tfind find a word in the dictionary and push the location\n\t' store the address of the following word on the stack\n\t, write the top of the stack to the dictionary\n\tswap swap first two values on the stack\n\tdup duplicate the top of the stack\n\tdrop pop and drop a value\n\tover copy the second stack value over the first\n\t. pop the top of the stack and print it\n\" \nmore \" \n\tprint print a NUL terminated string at a character address\n\tdepth get the current stack depth\n\tclock get the time since execution start in milliseconds\n\tevaluate evaluate a string\n\tsystem execute a system command\n\tclose-file close a file handle\n\topen-file open a file handle\n\tdelete-file delete a file off disk given a string\n\tread-file read in characters from a file\n\twrite-file write characters to a file\n\tfile-position get the file offset\n\treposition-file reposition the file pointer\n\tflush-file flush a file to disk\n\trename-file rename a file on disk\n \"\n\nmore \" All of the other words in the interpreter are built from these\nprimitive words. A few examples:\n\n(1)\tif...else...then FORTH branching construct\n(1)\tbegin...until loop until top of stack is non zero\n(1)\tbegin...again infinite loop\n(1)\tdo...loop FORTH looping construct\n(2,3)\tcreate create a new word that pushes its location\n(1)\tdoes> declare a created words run time behaviour\n(1,2)\tvariable declare variable with initial value from top of stack\n(1,2)\tconstant declare a constant, taken from top of stack\n(1,2)\tarray declare an array with size taken from top of stack\n(1)\t; terminate a word definition and return to command mode\n\twords print out a list of all the defined words\n\thelp this help message\n\tdump print out memory contents starting at an address\n\tregisters print out the contents of the registers\n\tsee decompile a word, viewing what words compose it\n\t.s print out the contents of the stack\n\n\"\n\nmore \" Some more advanced words:\n\n\there push the dictionary pointer\n\th push the address of the dictionary pointer\n\tr push the return stack pointer\n\tallot allocate space in the dictionary\n(1)\t[ switch to command mode\n\t] switch to compile mode\n\t:: compile ':' into the dictionary\n\n\" more \"\nFor more information either consult the manual pages forth(1) and libforth(1)\nor consult the following sources:\n\n\thttps:\/\/github.com\/howerj\/libforth\n\thttp:\/\/work.anapnea.net\/html\/html\/projects.html\n\nAnd for a larger tutorial:\n\n\thttps:\/\/github.com\/howerj\/libforth\/blob\/master\/readme.md\n\nFor resources on Forth:\n\n\thttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\thttps:\/\/rwmj.wordpress.com\/2010\/08\/07\/jonesforth-git-repository\/\n\n -- end --\n\" cr\n;\n\n( ==================== Debugging info ========================= )\n\n( ==================== Files ================================== )\n\n( @todo implement the other file access methods in terms of the\n built in ones [see http:\/\/forth.sourceforge.net\/std\/dpans\/dpans11.htm]\n @todo read-line and write-line need their flag and ior setting correctly\n\n\tFILE-SIZE [ use file-positions ]\n\n Also of note:\t\n * Source ID needs extending. )\n\n: read-char ( c-addr fileid -- ior : read a char )\n\t1 swap read-file 0<> swap 1 <> or ;\n\n0 variable x\n\n: getchar ( fileid -- char ior )\n\tx chars> swap read-char x chars> c@ swap ;\n\n: write-char ( c-addr fileid -- ior : write a char )\n\t1 swap write-file 0<> swap 1 <> or ;\n\n: putchar ( char fileid -- ior )\n\tswap x chars> c! x chars> swap write-char ;\n\nhide{ x }hide\n\n: rewind-file ( file-id -- : rewind a file to the beginning )\n\t0 reposition-file throw ;\n\n: read-line ( c-addr u1 fileid -- u2 flag ior : read in a line of text )\n\t-rot bounds\n\tdo\n\t\tdup i swap read-char drop\n\t\ti c@ nl = if drop i 0 0 leave then\n\tloop drop ;\n\n: write-line ( c-addr u fileid -- u2 flag ior : write a line of text )\n\t-rot bounds\n\tdo\n\t\tdup i swap write-char drop\n\t\ti c@ nl = if drop i 0 0 leave then\n\tloop ;\n\n: resize-file ( ud fileid -- ior : attempt to resize a file )\n\t( There is no portable way to truncate a file :C )\n\t2drop -1 ( -1 to indicate failure ) ;\n\n: create-file ( c-addr u fam -- fileid ior )\n\t>r 2dup w\/o open-file throw close-file throw\n\tr> open-file ;\n\n: include-file ( file-id -- : evaluate a file ) \n\tdup >r 0 1 evaluator r> close-file throw throw ;\n\n: included ( c-addr u -- : attempt to open up a name file and evaluate it )\n\tr\/o open-file throw \n\tinclude-file ;\n\n: include ( c\" ccc\" -- : attempt to evaluate a named file )\n\t( @bug requires trailing space, should use parse-name )\n\tbl word count included ;\n\n: bin ( fam1 -- fam2 : modify a file access method to be binary not line oriented ) \n\t( Do nothing, all file access methods are binary )\n\t;\n\n( ==================== Files ================================== )\n\n( ==================== Matcher ================================ )\n( The following section implements a very simple regular expression\nengine, which expects an ASCIIZ Forth string. It is translated from C\ncode and performs an identical function.\n\nThe regular expression language is as follows:\n\n\tc\tmatch a literal character\n\t.\tmatch any character\n\t*\tmatch any characters\n\nThe \"*\" operator performs the same function as \".*\" does in most\nother regular expression engines. Most other regular expression engines\nalso do not anchor their selections to the beginning and the end of\nthe string to match, instead using the operators '^' and '$' to do\nso, to emulate this behavior '*' can be added as either a suffix,\nor a prefix, or both, to the matching expression.\n\nAs an example \"*, World!\" matches both \"Hello, World!\" and\n\"Good bye, cruel World!\". \"Hello, ....\" matches \"Hello, Bill\"\nand \"Hello, Fred\" but not \"Hello, Tim\" as there are two few\ncharacters in the last string.\n\n@todo make a matcher that expects a Forth string, which do not\nhave to be NUL terminated\n)\n\n\\ Translated from http:\/\/c-faq.com\/lib\/regex.html\n\\ int match(char *pat, char *str)\n\\ {\n\\ \tswitch(*pat) {\n\\ \tcase '\\0': return !*str;\n\\ \tcase '*': return match(pat+1, str) || *str && match(pat, str+1);\n\\ \tcase '.': return *str && match(pat+1, str+1);\n\\ \tdefault: return *pat == *str && match(pat+1, str+1);\n\\ \t}\n\\ }\n\n: *pat ( regex -- regex char : grab next character of pattern ) \n\tdup c@ ;\n\n: *str ( string regex -- string regex char : grab next character string to match )\n\tover c@ ;\n\n: pass ( c-addr1 c-addr2 -- bool : pass condition, characters matched ) \n\t2drop 1 ;\n\n: reject ( c-addr1 c-addr2 -- bool : fail condition, character not matched ) \n\t2drop 0 ;\n\n: *pat==*str ( c-addr1 c-addr2 -- c-addr1 c-addr2 bool )\n\t2dup c@ swap c@ = ;\n\n: ++ ( u1 u2 u3 u4 -- u1+u3 u2+u4 : not quite d+ [does no carry] )\n\tswap >r + swap r> + swap ;\n\ndefer matcher\n\n: advance ( string regex char -- bool : advance both regex and string )\n\tif 1 1 ++ matcher else reject then ;\n\n: advance-string ( string regex char -- bool : advance only the string )\n\tif 1 0 ++ matcher else reject then ;\n\n: advance-regex ( string regex -- bool : advance matching )\n\t2dup 0 1 ++ matcher if pass else *str advance-string then ;\n\n: match ( string regex -- bool : match a ASCIIZ pattern against an ASCIIZ string )\n\t( @todo Add limits and accept two Forth strings, making sure they are both\n\t ASCIIZ strings as well \n\t @warning This uses a non-standards compliant version of case! )\n\t*pat\n\tcase\n\t\t 0 of drop drop c@ not exit endof\n\t\t[char] * of drop advance-regex exit endof\n\t\t[char] . of drop *str advance exit endof\n\t\t drop *pat==*str advance exit\n\tendcase ;\n\nmatcher is match\n\nhide{ \n\t*str *pat *pat==*str pass reject advance \n\tadvance-string advance-regex matcher ++ \n}hide\n\n( ==================== Matcher ================================ )\n\n\n( ==================== Cons Cells ============================= )\n\n( From http:\/\/sametwice.com\/cons.fs, this could be improved if the optional\nmemory allocation words were added to the interpreter. This provides\na simple \"cons cell\" data structure. There is currently no way to\nfree allocated cells )\n\n: car! ( value cons-addr -- : store a value in the car cell of a cons cell ) \n\t! ;\n\n: cdr! ( value cons-addr -- : store a value in the cdr cell of a cons cell )\n\tcell+ ! ;\n\n: car@ ( cons-addr -- car-val : retrieve car value from cons cell )\n\t@ ;\n\n: cdr@ ( cons-addr -- cdr-val : retrieve cdr value from cons cell )\n\tcell+ @ ;\n\n: cons ( car-val cdr-val -- cons-addr : allocate a new cons cell )\n\tswap here >r , , r> ;\n\n: cons0 0 0 cons ;\n\nmarker cleanup\n77 987 cons constant x\nT{ x car@ -> 77 }T\nT{ x cdr@ -> 987 }T\nT{ 55 x cdr! x car@ x cdr@ -> 77 55 }T\nT{ 44 x car! x car@ x cdr@ -> 44 55 }T\ncleanup\n\n( ==================== Cons Cells ============================= )\n\n( ==================== Miscellaneous ========================== )\n\n: license ( -- : print out license information )\n\" \nThe MIT License (MIT)\n\nCopyright (c) 2016, 2017 Richard James Howe\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the 'Software'),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand\/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\nTHE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\nOTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\nARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE. \n\n\" \n;\n\n( ==================== Version information =================== )\n\n4 constant version\n\n( ==================== Version information =================== )\n\n( ==================== Core utilities ======================== )\n( Read the header of a core file and process it, printing the\nresults out )\n\n8 constant header-size ( size of Forth core file header )\n8 constant size-field-size ( the size in bytes of the size field in the core file )\n0 variable core-file ( core fileid we are reading in )\n0 variable core-cell-size ( cell size of Forth core )\n0 variable core-version ( version of core file )\n0 variable core-endianess ( endianess of core we are reading in )\n\n( save space to read in header )\ncreate header header-size chars allot\n: cheader ( -- c-addr : header char address )\n\theader chars> ;\ncreate size-field size-field-size chars allot\n: csize-field ( -- c-addr : address of place size field is stored in )\n\tsize-field chars> ;\n\n0\nenum header-magic0 ( magic number 0 : FF ) \nenum header-magic1 ( magic number 1 : '4' )\nenum header-magic2 ( magic number 2 : 'T' )\nenum header-magic3 ( magic number 3 : 'H' )\nenum header-cell-size ( size of a forth cell, either 2, 4 or 8 bytes )\nenum header-version ( version of the forth core )\nenum header-endianess ( endianess of the core )\nenum header-log2size ( binary logarithm of the core size )\n\n: cleanup ( -- : cleanup before abort )\n\tcore-file @ ?dup 0<> if close-file drop then ;\n\n: invalid-header ( bool -- : abort if header is invalid )\n\t<> if cleanup abort\" invalid header\" then ;\n\n: save-core-cell-size ( char -- : save the core file cell size, checking if it is valid )\n\tcore-cell-size !\n\t\" cell size:\" tab\n\tcore-cell-size @ 2 = if 2 . cr exit then\n\tcore-cell-size @ 4 = if 4 . cr exit then\n\tcore-cell-size @ 8 = if 8 . cr exit then\n\tcleanup core-cell-size @ . abort\" : invalid cell size\" ;\n\n: check-version-compatibility ( char -- : checks the version compatibility of the core file ) \n\tcore-version !\n\tcore-version @ version = if \" version: \" version . cr exit then\n\tcleanup core-version @ . abort\" : unknown version number\" ;\n\n: save-endianess ( char -- : save the endianess, checking if it is valid )\n\tcore-endianess !\n\t\" endianess:\" tab\n\tcore-endianess @ 0 = if \" big\" cr exit then\n\tcore-endianess @ 1 = if \" little\" cr exit then\n\tcleanup core-endianess @ . abort\" invalid endianess\" then ;\n\n: read-or-abort ( c-addr size fileid -- : )\n\tover >r read-file \n\t 0<> if cleanup abort\" file read failed\" then\n\tr> <> if cleanup abort\" header too small\" then ;\n\n: header? ( -- : print out header information )\n\tcheader header-size core-file @ read-or-abort\n\t( \" raw header:\" header 2 dump )\n\tcheader header-magic0 + c@ 255 invalid-header\n\tcheader header-magic1 + c@ [char] 4 invalid-header\n\tcheader header-magic2 + c@ [char] T invalid-header\n\tcheader header-magic3 + c@ [char] H invalid-header\n\tcheader header-cell-size + c@ save-core-cell-size\n\tcheader header-version + c@ check-version-compatibility\n\tcheader header-endianess + c@ save-endianess\n\t\" valid header\" cr ;\n\n: size? ( -- : print out core file size )\n\t\" size: \" cheader header-log2size + c@ 1 swap lshift . cr ;\n\n: core ( c-addr u -- : analyze a Forth core file from disk given its file name )\n\t2dup \" core file:\" tab type cr\n\tr\/o open-file throw core-file ! \n\theader?\n\tsize?\n\tcore-file @ close-file drop ;\n\n( s\" forth.core\" core )\n\nhide{ \nheader-size header? \nheader-magic0 header-magic1 header-magic2 header-magic3\nheader-version header-cell-size header-endianess header-log2size\nheader \ncore-file save-core-cell-size check-version-compatibility\ncore-cell-size cheader\ncore-endianess core-version save-endianess invalid-header\ncleanup size-field csize-field size-field-size\nread-or-abort size?\n}hide\n\n( ==================== Core utilities ======================== )\n\n( ==================== RLE =================================== )\n\n( These set of words implement Run Length Compression, which can be used for\nsaving space when compressing the core files generated by Forth programs, which\ncontain mostly runs of NUL characters. \n\nThe format of the encoded data is quite simple, there is a command byte\nfollowed by data. The command byte encodes only two commands; encode a run of\nliteral data and repeat the next character. \n\nIf the command byte is greater than X the command is a run of characters, \nX is then subtracted from the command byte and this is the number of \ncharacters that is to be copied verbatim when decompressing.\n\nIf the command byte is less than or equal to X then this number, plus one, is \nused to repeat the next data byte in the input stream.\n\nX is 128 for this application, but could be adjusted for better compression\ndepending on what the data looks like. \n\nExample:\n\t\n\t2 'a' 130 'b' 'c' 3 'd'\n\nBecomes:\n\n\taabcddd \n\nExample usage:\n\n\t: extract\n\t\tc\" forth.core\" w\/o open-file throw\n\t\tc\" forth.core.rle\" r\/o open-file throw\n\t\tdecompress ;\n\textract\n\n@note file redirection could be used for the input as well\n@todo compression, and reading\/writing to strings )\n\n: cpad pad chars> ;\n\n0 variable out\n128 constant run-length\n\n: next.char ( file-id -- char : read in a single character )\n\t>r cpad r> read-char throw cpad c@ ;\n\n: repeated ( count file-id -- : repeat a character count times )\n\tnext.char swap 0 do dup emit loop drop ;\n\n: literals ( count file-id -- : extract a literal run )\n\t>r cpad swap r> read-file throw cpad swap type ;\n\n: command ( file-id -- : process an RLE command )\n\tdup \n\t>r next.char\n\tdup run-length u> \n\tif \n\t\trun-length - r> literals \n\telse \n\t\t1+ r> repeated \n\tthen ;\n\n: redirect ( file-id-out -- : save current output pointer, redirect to output )\n\t`fout @ out ! `fout ! ;\n\n: restore ( -- : restore previous output pointer )\n\tout @ `fout ! ;\n\n: decompress ( file-id-out file-id-in -- : decompress an RLE encoded file )\n\tswap\n\tredirect\n\tbegin dup ' command catch until ( process commands until input exhausted )\n\t2drop ( drop twice because catch will restore stack before 'command' )\n\trestore ; ( restore input stream )\n\nhide{ literals repeated next.char out run-length command }hide\n\n( ==================== RLE =================================== )\n\n( ==================== Generate C Core file ================== )\n( The word core2c reads in a core file and turns it into a C file which \ncan then be compiled into the forth interpreter in a bootstrapping like\nprocess.\n\nUsage:\n c\" forth.core\" c\" core.gen.c\" core2c )\n\n0 variable count\n\n: wbyte ( u char -- : write a byte )\n\tpnum drop\n\t[char] , emit\n\t16 mod 0= if cr then ;\n\n: advance ( char -- : advance counter and print byte )\n\tcount 1+! count @ swap wbyte ;\n\n: hexify ( fileid -- fileid : turn core file into C numbers in array )\n\t0 count !\n\tbegin dup getchar 0= while advance repeat drop ;\n\n: quote ( -- : emit a quote character )\n\t[char] \" emit ;\n\n: core2c ( c-addr u c-addr u -- ior : generate a C file from a core file )\n\tw\/o open-file throw >r\n\tr\/o open-file ?dup-if r> close-file throw throw then\n\tr> redirect\n\t\" #include \" quote \" libforth.h\" quote cr\n\t\" unsigned char forth_core_data[] = {\" cr\n\thexify \n\t\" };\" cr\n\t\" forth_cell_t forth_core_size = \" count @ . \" ;\" cr cr\n\tclose-file\n\t`fout @ close-file \n\trestore or ;\n\nhide{ wbyte hexify count quote advance }hide\n \n( ==================== Generate C Core file ================== )\n\n: wc ( c-addr u -- u : count the bytes in a file )\n\tr\/o open-file throw\n\t0 swap\n\tbegin dup getchar nip 0= while nos1+ repeat close-file throw ;\n\n( ==================== Save Core file ======================== )\n\n( The following functionality allows the user to save the core file\nfrom within the running interpreter. The Forth core files have a very simple\nformat which means the words for doing this do not have to be too long, a header\nhas to emitted with a few calculated values and then the contents of the\nForths memory after this )\n\n( This write the header out to the current output device, this\nwill be redirected to a file )\n: header ( -- : write the header out )\n\t0xff emit ( magic 0 )\n\t[char] 4 emit ( magic 1 )\n\t[char] T emit ( magic 2 )\n\t[char] H emit ( magic 3 )\n\tsize emit ( cell size in bytes )\n\tversion emit ( core version )\n\tendian not emit ( endianess )\n\tmax-core log2 emit ; ( size field )\n\n: data ( -- : write the data out )\n\t0 max-core chars> `fout @ write-file throw drop ;\n\n: encore ( -- : write the core file out )\n\theader\n\tdata ;\n\n: save-core ( c-addr u -- : save core file or throw error ) \n\tw\/o open-file throw dup\n\tredirect \n\t\t' encore catch swap close-file throw \n\trestore ;\n\n( The following code illustrates an example of setting up a\nForth core file to execute a word when the core file is loaded.\nIn the example the word \"hello-world\" will be executed, which will\nalso quit the interpreter:\n\n\t\\ Only works for immediate words for now, we define\n\t\\ the word we wish to be executed when the forth core\n\t\\ is loaded\n\t: hello-world immediate\n\t\t\" Hello, World!\" cr bye ;\n\n\t\\ The following sets the starting word to our newly\n\t\\ defined word:\n\tfind hello-world cfa start!\n\n\t\\ Now we can save the core file out:\n\ts\" forth.core\" save-core \n\nThis can be used, in conjunction with aspects of the build system,\nto produce a standalone executable that will run only a single Forth\nword. )\n\nhide{ redirect restore data encore header }hide\n\n( ==================== Save Core file ======================== )\n\n( ==================== Hex dump ============================== )\n\n( @todo hexdump can read in too many characters and it does not\nprint out the correct address\n@todo utilities for easy redirecting of file input\/output )\n: input >r cpad 128 r> read-file ; ( file-id -- u 0 | error )\n: clean cpad 128 0 fill ; ( -- )\n: cdump cpad chars swap aligned chars dump ; ( u -- )\n: hexdump ( file-id -- : [hex]dump a file to the screen )\n\tdup \n\tclean\n\tinput if 2drop exit then\n\t?dup-if cdump else drop exit then\n\ttail ; \n\nhide{ cpad clean cdump input }hide\n\n( ==================== Hex dump ============================== )\n\n( ==================== Date ================================== )\n\n( Rather annoyingly months are start from 1 but weekdays from 0 )\n\n: >month ( month -- )\n\tcase\n\t\t 1 of \" Jan \" endof\n\t\t 2 of \" Feb \" endof\n\t\t 3 of \" Mar \" endof\n\t\t 4 of \" Apr \" endof\n\t\t 5 of \" May \" endof\n\t\t 6 of \" Jun \" endof\n\t\t 7 of \" Jul \" endof\n\t\t 8 of \" Aug \" endof\n\t\t 9 of \" Sep \" endof\n\t\t10 of \" Oct \" endof\n\t\t11 of \" Nov \" endof\n\t\t12 of \" Dec \" endof\n\tendcase drop ;\n\n: .day ( day -- : add ordinal to day )\n\t10 mod\n\tcase\n\t\t1 of \" st \" drop exit endof\n\t\t2 of \" nd \" drop exit endof\n\t\t3 of \" rd \" drop exit endof\n\t\t\" th \" \n\tendcase drop ;\n\n: >day ( day -- : add ordinal to day of month )\n\tdup u.\n\tdup 1 10 within if .day exit then\n\tdup 10 20 within if \" th\" drop exit then\n\t.day ;\n\n: >weekday ( weekday -- : print the weekday )\n\tcase\n\t\t0 of \" Sun \" endof\n\t\t1 of \" Mon \" endof\n\t\t2 of \" Tue \" endof\n\t\t3 of \" Wed \" endof\n\t\t4 of \" Thu \" endof\n\t\t5 of \" Fri \" endof\n\t\t6 of \" Sat \" endof\n\tendcase drop ;\n\n: padded ( u -- : print out a run of zero characters )\n\t0 do [char] 0 emit loop ;\n\n: 0u. ( u -- : print a zero padded number )\n\tdup 10 u< if 1 padded then u. space ;\n\n: .date ( date -- : print the date )\n\tif \" DST \" else \" GMT \" then \n\tdrop ( no need for days of year)\n\t>weekday\n\t. ( year ) \n\t>month \n\t>day \n\t0u. ( hour )\n\t0u. ( minute )\n\t0u. ( second ) cr ;\n\n: time&date ( -- second minute hour day month year )\n\tdate\n\t3drop ;\n\nhide{ 0u. >weekday .day >day >month padded }hide\n\n( ==================== Date ================================== )\n\n\n( ==================== CRC =================================== )\n\n( @todo implement all common CRC algorithms, but only if\nthe word size allows it [ie. 32 bit CRCs on a 32 or 64 bit\nmachine, 64 bit CRCs on a 64 bit machine] )\n\n( Make a word to limit arithmetic to a 16-bit value )\nsize 2 = [if] \n\t: limit immediate ; ( do nothing, no need to limit )\n[else] \n\t: limit 0xffff and ; ( limit to 16-bit value )\n[then]\n\n: ccitt ( crc c-addr -- crc : calculate polynomial 0x1021 AKA \"x16 + x12 + x5 + 1\" )\n\tc@ ( get char )\n\tlimit over 256\/ xor ( crc x )\n\tdup 4 rshift xor ( crc x )\n\tdup 5 lshift limit xor ( crc x )\n\tdup 12 lshift limit xor ( crc x )\n\tswap 8 lshift limit xor ; ( crc )\n\n( see http:\/\/stackoverflow.com\/questions\/10564491\/function-to-calculate-a-crc16-checksum\n and https:\/\/www.lammertbies.nl\/comm\/info\/crc-calculation.html )\n: crc16-ccitt ( c-addr u -- u )\n\t0xFFFF -rot\n\t['] ccitt\n\tforeach-char ;\nhide{ limit ccitt }hide\n\n( ==================== CRC =================================== )\n\n( ==================== Rational Data Type ==================== )\n( This word set allows the manipulation of a rational data type,\nwhich are basically fractions. This allows numbers like 1\/3 to\nbe represented without any loss of precision. Conversion to and\nfrom the data type to an integer type is trivial, although \ninformation can be lost during the conversion.\n\nTo convert to a rational, use 'dup', to convert from a rational,\nuse '\/'. \n\nThe denominator is the first number on the stack, the numerator the\nsecond number. Fractions are simplified after any rational operation,\nand all rational words can accept unsimplified arguments. For example\nthe fraction 1\/3 can be represented as 6\/18, they are equivalent, so\nthe rational equality operator \"=rat\" can accept both and returns\ntrue.\n\n\tT{ 1 3 6 18 =rat -> 1 }T\n\nSee: https:\/\/en.wikipedia.org\/wiki\/Rational_data_type \nFor more information.\n\nThis set of words use two cells to represent a fraction, however\na single cell could be used, with the numerator and the denominator\nstored in upper and lower half of a single cell. )\n\n: simplify ( a b -- a\/gcd{a,b} b\/gcd{a\/b} : simplify a rational )\n 2dup\n gcd\n tuck\n \/\n -rot\n \/\n swap ; \\ ? check this\n\n: crossmultiply ( a b c d -- a*d b*d c*b d*b )\n rot ( a c d b )\n 2dup ( a c d b d b )\n * ( a c d b d*b )\n >r ( a c d b , d*b )\n rot ( a d b c , d*b )\n * ( a d b*c , d*b )\n -rot ( b*c a d , d*b )\n * ( b*c a*d , d*b )\n r> ( b*c a*d d*b )\n tuck ( b*c d*b a*d d*b )\n 2swap ; ( done! )\n\n: *rat ( a\/b c\/d -- a\/b : multiply two rationals together )\n rot * -rot * swap simplify ;\n\n: \/rat ( a\/b c\/d -- a\/b : divide one rational by another )\n swap *rat ;\n\n: +rat ( a\/b c\/d -- a\/b : add two rationals together )\n crossmultiply\n rot\n drop ( or check if equal, if not there is an error )\n -rot\n +\n swap\n simplify ;\n\n: -rat ( a\/b c\/d -- a\/b : subtract one rational from another )\n crossmultiply \n rot\n drop ( or check if equal, if not there is an error )\n -rot\n -\n swap\n simplify ;\n\n: .rat ( a\/b -- : print out a rational number )\n simplify swap . [char] \/ emit space . ;\n\n: =rat ( a\/b c\/d -- bool : rational equal )\n crossmultiply rot = -rot = = ;\n\n: >rat ( a\/b c\/d -- bool : rational greater than )\n crossmultiply rot 2drop > ;\n\n: <=rat ( a\/b c\/d -- bool : rational less than or equal to )\n\t>rat not ;\n\n: =rat ( a\/b c\/d -- bool : rational greater or equal to )\n\t0 block number stored in buf)\n\n: invalid? ( n -- : throw if block number is invalid )\n\t0= if -35 throw then ;\n\n: update ( -- : mark currently loaded block buffer as dirty )\n\ttrue dirty ! ;\n\n: updated?\n\tdirty @ ;\n\n: block.name ( n -- c-addr u : make a block name )\n\tc\" .blk\" <# holds #s #> rot drop ;\n\n( @warning this will not work if we do not have permission,\nor in various other cases where we cannot open the file, for\nwhatever reason )\n: file-exists ( c-addr u : does a file exist? )\n\tr\/o open-file if drop 0 else close-file throw 1 then ;\n\n: buffer.exists ( n -- bool : does a block buffer exist on disk? )\n\tblock.name file-exists ;\n\n( @note block.write and block.read do not check if they have\nwrote or read in 1024 bytes, nor do they check that they can\nonly write or read 1024 and not a byte more )\n\n: block.read ( file-id -- file-id : read in buffer )\n\tdup >r buf r> read-file nip if close-file -33 throw then ;\n\n: block.write ( file-id -- file-id : write out buffer )\n\tdup >r buf r> write-file nip if close-file -34 throw then ;\n\n: block.open ( n fam -- file-id )\n\t>r block.name r> open-file throw ;\n\n: save-buffers \n\tblk @ 0= if exit then ( not a valid block number, exit )\n\tdirty @ not if exit then ( not dirty, no need to save )\n\tblk @ w\/o block.open ( open file backing block buffer )\n\tblock.write ( write it out )\n\tclose-file throw ( close it )\n\tfalse dirty ! ; ( but only mark it clean if everything succeeded )\n\n: empty-buffers ( -- : deallocate any saved buffers )\n\t0 blk ! ;\n\n: flush ( -- : perform save-buffers followed by empty-buffers )\n\tsave-buffers\n\tempty-buffers ;\n\n( Block is a complex word that does a lot, although it has a simple\ninterface. It does the following given a block number:\n\n1. Checks the provided block buffer number to make sure it is valid\n2. If the block is already loaded from the disk, then return the\naddress of the block buffer it is loaded into.\n3. If not, it checks to see if the currently loaded block buffer is\ndirty, if it is then it flushes the buffer to disk.\n4. If the block buffer does not exists on disk then it creates it.\n5. It then stores the block number in blk and returns an address to\nthe block buffer. )\n: block ( n -- c-addr : load a block )\n\tdup invalid? \n\tdup blk @ = if drop buf drop exit then\n\tflush\n\tdup buffer.exists if ( if the buffer exits on disk load it in )\n\t\tdup r\/o block.open \n\t\tblock.read \n\t\tclose-file throw \n\telse ( else it does not exist )\n\t\tbuf 0 fill ( clean the buffer )\n\tthen \n\tblk ! ( save the block number )\n\tbuf drop ;\n\n: buffer block ;\n\n( @warning uses hack, block buffer is NUL terminated, and evaluate requires\na NUL terminated string, evaluate checks that the last character is NUL, \nhence the 1+ )\n: load ( n -- : load and execute a block )\n\tblock b\/buf 1+ evaluate throw ;\n\nhide{ \n\tblock.name invalid? block.write \n\tblock.read buffer.exists block.open dirty\n}hide\n\n( ==================== Block Layer =========================== )\n\n( ==================== List ================================== )\n1 variable fancy-list\n0 variable scr\n64 constant c\/l ( characters per line )\n\n: line.number ( n -- : print line number )\n\tfancy-list @ if\n\t\tdup 10 < (base) 10 = and if space then ( leading space: works up to c\/l = 99)\n\t\t. [char] | emit ( print \" line-number : \")\n\telse\n\t\tdrop\n\tthen ;\n\n: line ( c-addr -- c-addr u : given a line number, display that line )\n\tdup \n\tline.number ( display line number )\n\tc\/l * + ( calculate offset )\n\tc\/l ; ( add line length )\n\n: list.end\n\tfancy-list @ not if exit then\n\t[char] | emit ;\n\n: list.type ( c-addr u -- : list a block )\n\tb\/buf c\/l \/ 0 do dup i line type list.end cr loop drop ;\n\n: list.border \" +---|---\" ;\n\n: list.box\n\tfancy-list @ not if exit then\n\t4 spaces\n\t8 0 do list.border loop cr ;\n\n: list ( n -- : display a block number and update scr )\n\tdup >r block r> scr ! list.box list.type list.box ;\n\n: thru\n\tkey drop\n\t1+ swap do i list more loop ;\n\n: make-blocks ( n1 n2 -- : make blocks on disk from n1 to n2 inclusive )\n\t1+ swap do i block b\/buf bl fill update loop save-buffers ;\n\nhide{ buf line line.number list.type fancy-list (base) }hide\n\n( ==================== List ================================== )\n\n( ==================== Signal Handling ======================= )\n( Signal handling at the moment is quite primitive. When a signal\noccurs it has to be explicitly tested for by the programmer, this\ncould be improved on quite a bit. One way of doing this would be\nto check for signals in the virtual machine and cause a THROW\nfrom within it. )\n\n( signals are biased to fall outside the range of the error numbers\ndefined in the ANS Forth standard. )\n-512 constant signal-bias \n\n: signal ( -- signal\/0 : push the results of the signal register ) \n\t`signal @\n \t0 `signal ! ;\n\n( ==================== Signal Handling ======================= )\n\n( Looking at most Forths dictionary with \"words\" command they tend\nto have a lot of words that do not mean anything but to the implementers\nof that specific Forth, here we clean up as many non standard words as\npossible. )\nhide{ \n do-string ')' alignment-bits \n dictionary-start hidden-mask instruction-mask immediate-mask compiling?\n compile-bit\n max-core dolist doconst x x! x@ \n max-string-length \n _exit\n pnum evaluator \n TrueFalse >instruction \n xt-instruction\n `state\n `source-id `sin `sidx `slen `start-address `fin `fout `stdin\n `stdout `stderr `argc `argv `debug `invalid `top `instruction\n `stack-size `error-handler `x `handler _emit `signal \n}hide\n\n( \n## Forth To List\n\nThe following is a To-Do list for the Forth code itself, along with any\nother ideas.\n\n* FORTH, VOCABULARY\n* \"Value\", \"To\", \"Is\"\n* Double cell words \n* The interpreter should use character based addresses, instead of\nword based, and use values that are actual valid pointers, this\nwill allow easier interaction with the world outside the virtual machine\n* common words and actions should be factored out to simplify\ndefinitions of other words, their standards compliant version found\nif any\n* A soft floating point library would be useful which could be used\nto optionally implement floats [which is not something I really want\nto add to the virtual machine]. If floats were to be added, only the\nminimal set of functions should be added [f+,f-,f\/,f*,f<,f>,>float,...]\n* Allow the processing of argc and argv, the mechanism by which that\nthis can be achieved needs to be worked out. However all processing that\nis currently done in \"main.c\" should be done within the Forth interpreter\ninstead. Words for manipulating rationals and double width cells should\nbe made first.\n* A built in version of \"dump\" and \"words\" should be added to the Forth\nstarting vocabulary, simplified versions that can be hidden.\n* Here documents, string literals. Examples of these can be found online\n* Document the words in this file and built in words better, also turn this\ndocument into a literate Forth file.\n* Sort out \"'\", \"[']\", \"find\", \"compile,\" \n* Proper booleans should be used throughout, that is -1 is true, and 0 is\nfalse.\n* Attempt to add crypto primitives, not for serious use, like TEA, XTEA,\nXXTEA, RC4, MD5, ...\n* Add hash functions: CRC-32, CRC-16, ...\nhttp:\/\/stackoverflow.com\/questions\/10564491\/function-to-calculate-a-crc16-checksum\n* File operation primitives that close the file stream [and possibly restore\nI\/O to stdin\/stdout] if an error occurs, and then re-throws, should be made.\n* Implement as many things from http:\/\/lars.nocrew.org\/forth2012\/implement.html\nas is sensible. \n* CASE Statements http:\/\/dxforth.netbay.com.au\/miser.html\n* The current words that implement I\/O redirection need to be improved, and documented,\nI think this is quite a useful and powerful mechanism to use within Forth that simplifies\nprograms. This is a must and will make writing utilities in Forth a *lot* easier \n* Words for manipulating words should be added, for navigating to different\nfields within them, to the end of the word, etcetera.\n* The data structure used for parsing Forth words needs changing in libforth so a\ncounted string is produced. Counted strings should be used more often. The current\nlayout of a Forth word prevents a counted string being used and uses a byte more\nthan it has to.\n* Whether certain simple words [such as '1+', '1-', '>', '<', '<>', 'not', '<=',\n'>='] should be added as virtual machine instructions for speed [and size] reasons\nshould be investigated.\n* An analysis of the interpreter and the code it executes could be done to find\nthe most commonly executed words and instructions, as well as the most common two and\nthree sequences of words and instructions. This could be used to use to optimize the\ninterpreter, in terms of both speed and size.\n\n### libforth.c todo\n\n* A halt, a parse, and a print\/type instruction could be added to the Forth virtual\nmachine.\n* Throw\/Catch need to be added and used in the virtual machine\n* Various edge cases and exceptions should be removed [for example counted strings\nare not used internally, and '0x' can be used as a prefix only when base is zero].\n* A potential optimization is to order the words in the dictionary by frequency order,\nthis would mean chaning the X Macro that contains the list of words, after collecting\nstatistics. This should make find faster.\n* Investigate adding operating system specific code into the interpreter and\nisolating it to make it semi-portable.\n* Make equivalents for various Unix utilities in Forth, like a CRC check, cat,\ntr, etcetera.\n\n )\n\nverbose [if] \n\t.( FORTH: libforth successfully loaded.) cr\n\t.( Type 'help' and press return for a basic introduction.) cr\n\t.( Core: ) here . \" \/ \" here unused + . cr\n\t license\n[then]\n\n\n( ==================== Test Code ============================= )\n\n( The following will not work as we might actually be reading from a string [`sin]\nnot `fin. \n: key 32 chars> 1 `fin @ read-file drop 0 = if 0 else 32 chars> c@ then ; )\n\n\\ : ' immediate state @ if postpone ['] else find then ;\n\n( This really does not implement a correct FORTH\/VOCABULARY, for that\nwordlists will need to be introduced and used in libforth.c. The best\nthat this word set can do is to hide and reveal words to the user, this\nwas just an experiment. \n\n\t: forth \n\t\t[ find forth 1- @ ] literal\n\t\t[ find forth 1- ] literal ! ;\n\n\t: vocabulary\n\t\tcreate does> drop 0 [ find forth 1- ] literal ! ; )\n\n\\ @todo The built in primitives should be redefined so to make sure\n\\ they are called and nested correctly, using the following words\n\\ 0 variable csp\n\\ : !csp sp@ csp ! ;\n\\ : ?csp sp@ csp @ <> if -22 throw then ;\n\\ \\ Is there a better throw value than -11?\n\\ : ?comp state @ 0= if -11 throw then ; \\ Error if not compiling\n\\ : ?exec state @ if -11 throw then ; \\ Error if not executing\n\n\n( ==================== Test Code ============================= )\n\n( ==================== Block Editor ========================== )\n( Experimental block editor Mark II \n\n@todo Improve the block editor \n\n- '\\' needs extending to work with the block editor, for now, \nuse parenthesis for comments \n- make an 'm' word for forgetting all words defined since the\neditor was invoked.\n- add multi line insertion mode\n- Add to an editor vocabulary, which will need the vocabulary\nsystem to exist.\n- Using 'page' should be optional as not all terminals support\nANSI escape codes - thanks to CMD.EXE. Damned Windows.\n- How line numbers are printed out should be investigated,\nalso I should refactor 'dump' to use a similar line number system.\n- Format the output of list better, put a nice box around it.\n\nAdapted from http:\/\/retroforth.org\/pages\/?PortsOfRetroEditor )\n\n \n: help ( @todo renamed to 'h' once vocabularies are implemented )\npage cr\n\" Block Editor Help Menu\n\n n move to next block\n p move to previous block\n # d delete line in current block\n x erase current block\n e evaluate current block\n # i insert line\n # #2 ia insert at line #2 at column #\n q quit editor loop\n # b set block number\n s save block and write it out\n\n -- press any key to continue -- \" cr ( \" )\nchar drop ;\n\n: (block) blk @ block ; \n: (line) c\/l * (block) + ; ( n -- c-addr : push current line address )\n: (clean) \n\t(block) b\/buf\n\t2dup nl bl subst\n\t2dup cret bl subst\n\t 0 bl subst ;\n: n blk @ 1+ block ;\n: p blk @ 1- block ;\n: d (line) c\/l bl fill ; \n: x (block) b\/buf bl fill ;\n: s update save-buffers ;\n: q rdrop rdrop ;\n: e blk @ load char drop ;\n: ia c\/l * + dup b\/buf swap - >r (block) + r> accept (clean) ; \n: i 0 swap ia ;\n: editor\n\t1 block\n\tbegin\n\t\tpostpone [ ( need to be in command mode )\n\t\tpage cr\n\t\t\" BLOCK EDITOR: TYPE 'HELP' FOR A LIST OF COMMANDS\" cr\n\t\tblk @ list\n\t\t\" CURRENT BLOCK: \" blk @ . cr\n\t\tread\n\tagain ;\n\n( Extra niceties )\nc\/l string yank\nyank bl fill\n: u update ;\n: b block ;\n: l blk @ list ;\n: y (line) yank >r swap r> cmove ;\n: c (line) yank cmove ;\n: ct swap y c ;\n\nhide{ (block) (line) (clean) yank }hide\n\n( ==================== Block Editor ========================== )\n\nhere fence !\n\n\n","old_contents":"#!.\/forth \n( Welcome to libforth, A dialect of Forth. Like all versions of Forth this\nversion is a little idiosyncratic, but how the interpreter works is\ndocumented here and in various other files.\n\nThis file contains most of the start up code, some basic start up code\nis executed in the C file as well which makes programming at least bearable.\nMost of Forth is programmed in itself, which may seem odd if your back\nground in programming comes from more traditional language [such as C],\nalthough less so if you know already know lisp.\n\nFor more information about this interpreter and Forth see:\n\thttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\treadme.md : for a manual for this interpreter\n\tlibforth.h : for information about the C API\n\tlibforth.c : for the interpreter itself\n\tunit.c : a series of unit tests against libforth.c\n\tunit.fth : a series of unit tests against this file\n\nThe interpreter and this code originally descend from a Forth interpreter\nwritten in 1992 for the International obfuscated C Coding Competition\n\nSee:\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\nThe manual for the interpreter should be read first before looking into this\ncode. It is important to understand the execution model of Forth, especially\nthe differences between command and compile mode, and how immediate and compiling\nwords work.\n\n@todo Restructure and describe structure of this file.\n\nEach of these sections is clearly labeled and they are generally in dependency order.\n\nUnfortunately the code in this file is not as portable as it could be, it makes\nassumptions about the size of cells provided by the virtual machine, which will\ntake time to rectify. Some of the constructs are subtly different from the\nDPANs Forth specification, which is usually noted. Eventually this should\nalso be fixed.)\n\n( ========================== Basic Word Set ================================== )\n\n( \nWe'll begin by defining very simple words we can use later, these a very\nbasic words, that perform simple tasks, they will not require much explanation.\n\nEven though the words are simple, their stack comment and a description for\nthem will still be included so external tools can process and automatically\nextract the document string for a given work.\n)\n\n: postpone ( -- : postpone execution of the following immediate word )\n\timmediate find , ;\n\n: :: ( -- : compiling version of ':' )\n\t[ find : , ] ;\n\n: constant \n\t:: ( compile word header )\n\there 1 - h ! ( decrement dictionary pointer )\n\there @ instruction-mask invert and doconst or here ! ( change instruction to CONST )\n\there 1 + h ! ( increment dictionary pointer )\n\t, ( write in value )\n\tpostpone [ ; ( back into command mode )\n\n( space saving measure )\n-1 constant -1\n 0 constant 0 \n 1 constant 1\n 2 constant 2\n 3 constant 3\n\n0 constant false\n1 constant true ( @warning not standards compliant )\n\n10 constant lf ( line feed )\nlf constant nl ( new line - line feed on Unixen )\n13 constant cret ( carriage return )\n\n1 hidden-bit lshift constant hidden-mask ( mask for the hide bit in a words CODE field )\n\n-1 -1 1 rshift invert and constant min-signed-integer\n\nmin-signed-integer invert constant max-signed-integer\n\n1 constant cell ( size of a cell in address units )\n\ncell size 8 * * constant address-unit-bits ( the number of bits in an address )\n\n-1 -1 1 rshift and invert constant sign-bit ( bit corresponding to the sign in a number )\n\n( @todo test by how much, if at all, making words like 1+, 1-, <>, and other\nsimple words, part of the interpreter would speed things up )\n\n: 1+ ( x -- x : increment a number ) \n\t1 + ;\n\n: 1- ( x -- x : decrement a number ) \n\t1 - ;\n\n: chars ( c-addr -- addr : convert a character address to an address )\n\tsize \/ ; \n\n: chars> ( addr -- c-addr: convert an address to a character address )\n\tsize * ; \n\n: tab ( -- : print a tab character to current output device )\n\t9 emit ;\n\n: 0= ( x -- bool : is 'x' equal to zero? )\n\t0 = ;\n\n: not ( x -- bool : is 'x' true? )\n\t0= ;\n\n: <> ( x x -- bool : not equal )\n\t= 0= ;\n\n: logical ( x -- bool : turn a value into a boolean ) \n\tnot not ;\n\n( @todo \": dolit ' ' ;\" works but does not interact well with \n'decompile', if this was fixed the special work could be removed,\nwith some extra effort in libforth.c as well )\n: dolit ( -- x : location of special \"push\" word )\n\t2 ; \n\n: 2, ( x x -- : write two values into the dictionary )\n\t, , ;\n\n: [literal] ( x -- : write a literal into the dictionary )\n\tdolit 2, ; \n\n: literal ( x -- : immediately write a literal into the dictionary )\n\timmediate [literal] ;\n\n: sliteral immediate ( I: c-addr u --, Run: -- c-addr u )\n\tswap [literal] [literal] ;\n\n( @todo throw if not found )\n: ['] ( I: c\" xxx\", Run: -- xt )\n\timmediate find [literal] ;\n\n: >instruction ( CODE -- Instruction : extract instruction from instruction field ) \n\tinstruction-mask and ;\n\n: immediate-mask ( -- x : pushes the mask for the compile bit in a words CODE field )\n\t[ 1 compile-bit lshift ] literal ;\n\n: hidden? ( PWD -- PWD bool : is a word hidden, given the words PWD field ) \n\tdup 1+ @ hidden-mask and logical ;\n\n: compiling? ( PWD -- PWD bool : is a word immediate, given the words PWD field )\n\tdup 1+ @ immediate-mask and logical ;\n\n\n: cr ( -- : emit a newline character )\n\tnl emit ;\n\n: < ( x1 x2 -- bool : signed less than comparison )\n\t- dup if max-signed-integer u> else logical then ;\n\n: > ( x1 x2 -- bool : signed greater than comparison )\n\t- dup if max-signed-integer u< else logical then ;\n\n: #pad ( -- u : offset into pad area )\n\t64 ;\n\n: pad\n\t( the pad is used for temporary storage, and moves\n\talong with dictionary pointer, always in front of it )\n\there #pad + ;\n\n( @todo this can be improved a lot, currently it uses more\nspace than it has to, 4 cells instead of three.\n\nIt does:\n\n\tpush value\n\tpush value\n\nInstead of:\n\n\tmagic-2literal-word\n\tvalue\n\tvalue\n\n)\n: 2literal immediate ( x x -- : immediate write two literals into the dictionary )\n\tswap [literal] [literal] ;\n\n: latest ( get latest defined word )\n\tpwd @ ; \n\n: stdin ( -- fileid : push the fileid for the standard input channel ) \n\t`stdin @ ;\n\n: stdout ( -- fileid : push the fileid for the standard output channel ) \n\t`stdout @ ;\n\n: stderr ( -- fileid : push the fileid for the standard error channel ) \n\t`stderr @ ;\n\n: stdin? ( -- bool : are we reading from standard input )\n\t`fin @ stdin = ;\n\n: *+ ( x1 x2 x3 -- x ) \n\t* + ;\n\t\n: 2- ( x -- x : decrement by two )\n\t2 - ( x -- x ) ;\n\n: 2+ ( x -- x : increment by two )\n\t2 + ( x -- x ) ;\n\n: 3+ ( x -- x : increment by three )\n\t3 + ( x -- x ) ;\n\n: 2* ( x -- x : multiply by two )\n\t1 lshift ( x -- x ) ;\n\n: 2\/ ( x -- x : divide by two )\n\t1 rshift ( x -- x ) ;\n\n: 4* ( x -- x : multiply by four )\n\t2 lshift ( x -- x ) ;\n\n: 4\/ ( x -- x : divide by four )\n\t2 rshift ( x -- x ) ;\n\n: 8* ( x -- x : multiply by eight )\n\t3 lshift ( x -- x ) ;\n\n: 8\/ ( x -- x : divide by eight )\n\t3 rshift ( x -- x ) ;\n\n: 256* ( x -- x : multiply by 256 )\n\t8 lshift ( x -- x ) ;\n\n: 256\/ ( x -- x : divide by 256 )\n\t8 rshift ( x -- x ) ;\n\n: 2dup ( x1 x2 -- x1 x2 x1 x2 : duplicate two values )\n\tover over ;\n\n: mod ( x u -- x : calculate the remainder of x divided by u ) \n\t2dup \/ * - ;\n\n( @todo implement um\/mod in the VM, then use this to implement \/ and mod )\n: um\/mod ( x1 x2 -- rem quot : calculate the remainder and quotient of x1 divided by x2 ) \n\t2dup \/ >r mod r> ;\n\n: *\/ ( x1 x2 x3 -- x4 : multiply then divide, @warning this does not use a double cell for the multiply )\n\t * \/ ; \n\n: char ( -- x : read in a character from the input steam )\n\tkey drop key ;\n\n: [char] ( -- x : immediately read in a character from the input stream )\n\timmediate char [literal] ;\n\n: compose ( xt1 xt2 -- xt3 : create a new function from two xt-tokens )\n\t>r >r ( save execution tokens )\n\tpostpone :noname ( create a new :noname word for our xt-tokens )\n\tr> , ( write first token )\n\tr> , ( write second token )\n\tpostpone ; ; ( terminate new :noname )\n\n: unless ( bool -- : like 'if' but execute clause if false )\n\timmediate ['] 0= , postpone if ;\n\n: endif ( synonym for 'then' ) \n\timmediate postpone then ;\n\n: cells ( n1 -- n2 : convert a number of cells into a number of cells in address units ) \n\timmediate ;\n\n: cell+ ( a-addr1 -- a-addr2 ) \n\tcell + ;\n\n: negative? ( x -- bool : is a number negative? )\n\tsign-bit and logical ;\n\n: mask-byte ( x -- x : generate mask byte ) \n\t8* 255 swap lshift ;\n\n: select-byte ( u i -- c ) \n\t8* rshift 0xff and ;\n\n: xt-instruction ( extract instruction from execution token )\n\tcell+ @ >instruction ;\n\n: defined-word? ( CODE -- bool : is a word a defined or a built in words )\n\txt-instruction dolist = ;\n\n: char+ ( c-addr -- c-addr : increment a character address by the size of one character ) \n\t1+ ;\n\n: 2chars ( c-addr1 c-addr2 -- addr addr : convert two character addresses to two cell addresses ) \n\tchars swap chars swap ;\n\n: 2chars> ( addr addr -- c-addr c-addr: convert two cell addresses to two character addresses )\n\tchars> swap chars> swap ;\n\n: hex ( -- : print out hex ) \n\t16 base ! ;\n\n: octal ( -- : print out octal ) \n\t8 base ! ;\n\n: binary ( -- : print out binary ) \n\t2 base ! ;\n\n: decimal ( -- : print out decimal ) \n\t0 base ! ;\n\n: negate ( x -- x ) \n\t-1 * ;\n\n: abs ( x -- u : return the absolute value of a number )\n\tdup negative? if negate then ;\n\n: square ( x -- x ) \n\tdup * ;\n\n: sum-of-squares ( a b -- c : compute a^2 + b^2 to get c )\n\tsquare swap square + ;\n\n: drup ( x y -- x x ) \n\tdrop dup ;\n\n: +! ( x addr -- : add x to a value stored at addr ) \n\ttuck @ + swap ! ;\n\n: 1+! ( addr -- : increment a value at an address ) \n\t1 swap +! ;\n\n: 1-! ( addr -- : decrement a value at an address ) \n\t-1 swap +! ;\n\n: c+! ( x c-addr -- : add x to a value stored at c-addr )\n\ttuck c@ + swap c! ;\n\n: toggle ( addr u -- : complement the value at address with the bit pattern u ) \n\tover @ xor swap ! ;\n\n: lsb ( x -- x : mask off the least significant byte of a cell ) \n\t255 and ;\n\n: \\ ( -- : immediate word, used for single line comments )\n\timmediate begin key nl = until ;\n\n: ?dup ( x -- ? ) \n\tdup if dup then ;\n\n: min ( x y -- min : return the minimum of two integers ) \n\t2dup < if drop else swap drop then ;\n\n: max ( x y -- max : return the maximum of two integers ) \n\t2dup > if drop else swap drop then ;\n\n: limit ( x min max -- x : limit x with a minimum and maximum )\n\trot min max ;\n\n: >= ( x y -- bool ) \n\t< not ;\n\n: <= ( x y -- bool ) \n\t> not ;\n\n: 2@ ( a-addr -- x1 x2 : load two consecutive memory cells )\n\tdup 1+ @ swap @ ;\n\n: 2! ( x1 x2 a-addr -- : store two values as two consecutive memory cells )\n\t2dup ! nip 1+ ! ;\n\n: r@ ( -- x, R: x -- )\n\tr> r @ swap >r ;\n\n: rp@ ( -- x, R: x -- )\n\tr> r @ swap >r ;\n\n( @todo r!, rp! )\n\n: 0> ( x -- bool )\n\t0 > ;\n\n: 0< ( x -- bool )\n\t0 < ;\n\n: 0<> ( x -- bool )\n\t0 <> ;\n\n: signum ( x -- -1 | 0 | 1 : )\n\tdup 0< if drop -1 exit then\n\t 0> if 1 exit then\n\t0 ;\n\n: nand ( x x -- x : bitwise NAND ) \n\tand invert ;\n\n: odd ( x -- bool : is 'x' odd? )\n\t1 and ;\n\n: even ( x -- bool : is 'x' even? )\n\todd not ;\n\n: nor ( x x -- x : bitwise NOR ) \n\tor invert ;\n\n: ms ( u -- : wait at least 'u' milliseconds ) \n\tclock + begin dup clock u< until drop ;\n\n: sleep ( u -- : sleep for 'u' seconds )\n\t1000 * ms ;\n\n: align ( addr -- addr : align an address, nop in this implemented )\n\timmediate ; \n\n: ) ( -- : do nothing, this allows easy commenting out of code )\n\timmediate ;\n\n: bell ( -- : emit an ASCII BEL character ) \n\t7 emit ;\n\n: b\/buf ( -- u : bytes per buffer ) \n\t1024 ;\n\n: .d ( x -- x : debug print ) \n\tdup . ;\n\n: compile, ( x -- : )\n\t, ;\n\n: >mark ( -- : write a hole into the dictionary and push a pointer to it ) \n\there 0 , ;\n\n: r - r> u< ;\n\n: invalidate ( -- : invalidate this Forth core )\n\t1 `invalid ! ;\n\n: signed ( x -- bool : return true if sign bit set ) \n\t[ 1 size 8 * 1- lshift ] literal and logical ;\n\n: u>= ( x y -- bool : unsigned greater than or equal to )\n\t2dup u> >r = r> or ;\n\n: u<= ( x y -- bool : unsigned less than or equal to )\n\tu>= not ;\n\n: rdrop ( R: x -- : drop a value from the return stack )\n\tr> ( get caller's return address )\n\tr> ( get value to drop )\n\tdrop ( drop it like it's hot )\n\t>r ; ( return return address )\n\n: rdup\n\tr> ( get caller's return address )\n\tr> ( get value to duplicate )\n\tdup ( ... )\n\t>r >r >r ; ( make it all work )\n\n: again immediate\n\t( loop unconditionally in a begin-loop:\n\t\tbegin ... again )\n\t' branch , ;\n\n: source ( -- c-addr u )\n\t#tib ( size of input buffer, in characters )\n\ttib ; ( start of input buffer, in characters )\n\n: stdin? ( -- bool : are we reading from standard in? )\n\t`fin @ `stdin @ = ;\n\n: source-id ( -- 0 | -1 | file-id )\n\t( \t\n\tValue Input Source\n\t-1 String\n\t0 Reading from user input \/ standard in\n\tfile-id )\n\t`source-id @ \n\t0= if\n\t\tstdin? if 0 else `fin @ then\n\telse\n\t\t-1\n\tthen ;\n\n: under ( x1 x2 -- x1 x1 x2 )\n\t>r dup r> ;\n\n: 2nip ( n1 n2 n3 n4 -- n3 n4 ) \n\t>r >r 2drop r> r> ;\n\n: 2over ( n1 n2 n3 n4 \u2013 n1 n2 n3 n4 n1 n2 )\n\t>r >r 2dup r> swap >r swap r> r> -rot ;\n\n: 2swap ( n1 n2 n3 n4 \u2013 n3 n4 n1 n2 )\n\t>r -rot r> -rot ;\n\n: 2tuck ( n1 n2 n3 n4 \u2013 n3 n4 n1 n2 n3 n4 )\n\t2swap 2over ;\n\n: 3drop ( x1 x2 x3 -- )\n\t2drop ;\n\n: nos1+ ( x1 x2 -- x1+1 x2 : increment the next variable on that stack )\n\tswap 1+ swap ;\n\n: ?dup-if immediate ( x -- x | - : ?dup and if rolled into one! )\n\t['] ?dup , postpone if ;\n\n: ?if ( -- : non destructive if ) \n\timmediate ['] dup , postpone if ;\n\n: (hide) ( token -- hide-token : this hides a word from being found by the interpreter )\n\t?dup-if\n\t\tdup @ hidden-mask or swap tuck ! exit\n\tthen 0 ;\n\n: hider ( WORD -- : hide with drop ) \n\tfind dup if (hide) then drop ;\n\n: reveal ( hide-token -- : reveal a hidden word ) \n\tdup @ hidden-mask invert and swap ! ;\n\n: ?exit ( x -- : exit current definition if not zero ) \n\tif rdrop exit then ;\n\n: decimal? ( c -- f : is character a number? )\n\t[char] 0 [ char 9 1+ ] literal within ;\n\n: lowercase? ( c -- f : is character lower case? )\n\t[char] a [ char z 1+ ] literal within ;\n\n: uppercase? ( C -- f : is character upper case? )\n\t[char] A [ char Z 1+ ] literal within ;\n\n: alpha? ( C -- f : is character part of the alphabet? )\n\tdup lowercase? swap uppercase? or ;\n\n: alphanumeric? ( C -- f : is character alphabetic or a number ? )\n\tdup alpha? swap decimal? or ;\n\n: printable? ( c -- bool : is printable, excluding new lines and tables )\n\t32 127 within ;\n\n: >upper ( c -- C : convert char to uppercase iff lower case )\n\tdup lowercase? if bl xor then ;\n\n: >lower ( C -- c : convert char to lowercase iff upper case )\n\tdup uppercase? if bl xor then ;\n\n: <=> ( x y -- z : spaceship operator! )\n\t2dup\n\t> if 2drop -1 exit then\n\t< ;\n\n: start-address ( -- c-addr : push the start address )\n\t`start-address @ ;\n\n: >real-address ( c-addr -- r-addr : convert an interpreter address to a real address )\n\tstart-address + ;\n\n: real-address> ( c-addr -- r-addr : convert a real address to an interpreter address )\n\tstart-address - ;\n\n: peek ( r-addr -- n : )\n\tpad chars> >real-address swap size memory-copy pad @ ;\n\n: poke ( n r-addr -- : )\n\tswap pad ! pad chars> >real-address size memory-copy ;\n\n: die! ( x -- : controls actions when encountering certain errors )\n\t`error-handler ! ;\n\n: start! ( cfa -- : set the word to execute at startup )\n\t`instruction ! ;\t\n\n: warm ( -- : restart the interpreter, warm restart )\n\t1 restart ;\n\n: trip ( x -- x x x : triplicate a number ) \n\tdup dup ;\n\n: roll ( xu xu-1 ... x0 u -- xu-1 ... x0 xu : move u+1 items on the top of the stack by u )\n\tdup 0 >\n\tif\n\t\tswap >r 1- roll r> swap\n\telse\n\t\tdrop\n\tthen ;\n\n: 2rot ( n1 n2 n3 n4 n5 n6 \u2013 n3 n4 n5 n6 n1 n2 )\n\t5 roll 5 roll ;\n\n: s>d ( x -- d : convert a signed value to a double width cell )\n\t( @note the if...else...then is only necessary as this Forths\n\tbooleans are 0 and 1, not 0 and -1 as it usually is )\n\tdup 0< if -1 else 0 then ;\n\n: trace ( level -- : set tracing level )\n\t`debug ! ;\n\n: verbose ( -- : get the log level )\n\t`debug @ ;\n\n: count ( c-addr1 -- c-addr2 u : get a string whose first char is its length )\n\tdup c@ nos1+ ;\n\n: bounds ( x y -- y+x x : make an upper and lower bound )\n\tover + swap ;\n\n: aligned ( unaligned -- aligned : align a pointer )\n\t[ size 1- ] literal + \n\t[ size 1- ] literal invert and ;\n\n: rdepth\n\tmax-core `stack-size @ - r @ swap - ;\n\n: r.s ( -- : print the contents of the return stack )\n\tr> \n\t[char] < emit rdepth . [char] > emit\n\tspace\n\trdepth dup 0> if dup\n\tbegin dup while r> -rot 1- repeat drop dup\n\tbegin dup while rot dup . >r 1- repeat drop\n\tthen drop cr \n\t>r ;\n\n: argv ( -- r-addr : push pointer to array of string pointers to program )\n\t`argv @ ;\n\n: argc ( -- u : push the number of arguments in the argv array )\n\t`argc @ ;\n\n: +- ( x1 x2 -- x3 : copy the sign of x1 to x2 giving x3 )\n\t[ sign-bit 1- ] literal and\n\tswap\n\tsign-bit and or ;\n\n\nhider stdin?\n\n( ================================== DUMP ================================== )\n\\ : newline ( x -- x+1 : print a new line every fourth value )\n\\ \tdup 3 and 0= if cr then 1+ ;\n\\ \n\\ : address ( num count -- count : print current address we are dumping every fourth value )\n\\ \tdup >r\n\\ \t1- 3 and 0= if . [char] : emit space else drop then\n\\ \tr> ;\n\\ \n\\ : dump ( start count -- : print the contents of a section of memory )\n\\ \\\thex ( switch to hex mode )\n\\ \t1 >r ( save counter on return stack )\n\\ \tover + swap ( calculate limits: start start+count )\n\\ \tbegin \n\\ \t\t2dup u> ( stop if gone past limits )\n\\ \twhile \n\\ \t\tdup r> address >r\n\\ \t\tdup @ . 1+ \n\\ \t\tr> newline >r\n\\ \trepeat \n\\ \tr> drop\n\\ \t2drop ;\n\\ \n\\ hider newline\n\\ hider address \n( ================================== DUMP ================================== )\n\n: cfa immediate ( find-address -- cfa )\n\t( Given the address of the PWD field of a word this\n\tfunction will return an execution token for the word )\n\t( @todo if < dictionary start PWD is invalid )\n\t ;\n\n\\ : >body ( xt -- a-addr : a-addr is data field of a CREATEd word )\n\\\tcfa 5 + ;\n\n\n: execute ( xt -- : given an execution token, execute the word )\n\t( create a word that pushes the address of a hole to write to.\n\tA literal takes up two words, '!' takes up one, that's right,\n\tsome self modifying code! )\n\t[ here 3 cells + literal ] ( calculate place to write to )\n\t! ( write an execution token to a hole )\n\t[ 0 , ] ; ( this is the hole we write )\n\n( See: http:\/\/lars.nocrew.org\/dpans\/dpans9.htm\n@todo turn this into a lookup table of strings\n\n Code Reserved for\n ---- ------------\n -1 ABORT\n -2 ABORT\"\n -3 stack overflow\n -4 stack underflow\n -5 return stack overflow\n -6 return stack underflow\n -7 do-loops nested too deeply during execution\n -8 dictionary overflow\n -9 invalid memory address\n -10 division by zero\n -11 result out of range\n -12 argument type mismatch\n -13 undefined word\n -14 interpreting a compile-only word\n -15 invalid FORGET\n -16 attempt to use zero-length string as a name\n -17 pictured numeric output string overflow\n -18 parsed string overflow\n -19 definition name too long\n -20 write to a read-only location\n -21 unsupported operation [e.g., AT-XY on a\n too-dumb terminal]\n -22 control structure mismatch\n -23 address alignment exception\n -24 invalid numeric argument\n -25 return stack imbalance\n -26 loop parameters unavailable\n -27 invalid recursion\n -28 user interrupt\n -29 compiler nesting\n -30 obsolescent feature\n -31 >BODY used on non-CREATEd definition\n -32 invalid name argument [e.g., TO xxx]\n -33 block read exception\n -34 block write exception\n -35 invalid block number\n -36 invalid file position\n -37 file I\/O exception\n -38 non-existent file\n -39 unexpected end of file\n -40 invalid BASE for floating point conversion\n -41 loss of precision\n -42 floating-point divide by zero\n -43 floating-point result out of range\n -44 floating-point stack overflow\n -45 floating-point stack underflow\n -46 floating-point invalid argument\n -47 compilation word list deleted\n -48 invalid POSTPONE\n -49 search-order overflow\n -50 search-order underflow\n -51 compilation word list changed\n -52 control-flow stack overflow\n -53 exception stack overflow\n -54 floating-point underflow\n -55 floating-point unidentified fault\n -56 QUIT\n -57 exception in sending or receiving a character\n -58 [IF], [ELSE], or [THEN] exception )\n\n( @todo integrate catch\/throw into the interpreter as primitives )\n: catch ( xt -- exception# | 0 : return addr on stack )\n\tsp@ >r ( xt : save data stack pointer )\n\t`handler @ >r ( xt : and previous handler )\n\tr@ `handler ! ( xt : set current handler )\n\texecute ( execute returns if no throw )\n\tr> `handler ! ( restore previous handler )\n\tr> drop ( discard saved stack ptr )\n\t0 ; ( 0 : normal completion )\n\n( @todo use this everywhere )\n: throw ( ??? exception# -- ??? exception# )\n\t?dup-if ( exc# \\ 0 throw is no-op )\n\t\t`handler @ r ! ( exc# : restore prev return stack )\n\t\tr> `handler ! ( exc# : restore prev handler )\n\t\tr> swap >r ( saved-sp : exc# on return stack )\n\t\tsp! drop r> ( exc# : restore stack )\n\t\t( return to the caller of catch because return )\n\t\t( stack is restored to the state that existed )\n\t\t( when catch began execution )\n\tthen ; \n\n: interpret ( c1\" xxx\" ... cn\" xxx\" -- : This word implements the interpreter loop )\n\tbegin \n\t' read catch \n\t?dup-if [char] ! emit tab . cr then ( exception handler of last resort )\n\tagain ;\n\n: [interpret] ( c1\" xxx\" ... cn\" xxx\" -- : immediate version of interpret )\n\timmediate interpret ;\n\ninterpret ( use the new interpret word, which can catch exceptions )\n\nfind [interpret] cell+ start! ( the word executed on restart is now our new word )\n\n\n( ========================== Basic Word Set ================================== )\n\n( ========================== DOER\/MAKE ======================================= )\n( DOER\/MAKE is a word set that is quite powerful and is described in Leo Brodie's\nbook \"Thinking Forth\". It can be used to make words whose behavior can change\nafter they are defined. It essentially makes the structured use of self-modifying\ncode possible, along with the more common definitions of \"defer\/is\".\n\nAccording to \"Thinking Forth\", it has two purposes:\n\n1. To change the state of a function.\n2. To factor out common phrases of a words definition.\n\nAn example of the first instance:\n\n\tdoer say\n\t: sad \" Good bye, cruel World!\" cr ;\n\t: happy \" Hello, World!\" cr ;\n\n\t: person say ;\n\n\tmake person happy\n\tperson \\ prints \"Good bye, cruel World!\"\n\n\tmake person sad \n\tperson \\ prints \"Hello, World!\" \n\nAn example of the second:\n\n\tdoer op\n\n\t: sum \\ n0 ... nX X -- sum<0..X> \n\t\tmake op + 1 do op loop ;\n\n\t: mul \\ n0 ... nX X -- mul<0..X> \n\t\tmake op * 1 do op loop ;\n\nThe above example is a bit contrived, the definitions and functionality\nare too simple for this to be worth factoring out, but it shows how you\ncan use DOER\/MAKE. )\n\n: noop ; ( -- : default word to execute for doer )\n\n: doer ( c\" xxx\" -- : )\n\t:: ['] noop , postpone ; ;\n\n: found? ( xt -- xt : thrown an exception if the execution token is zero [not found] ) \n\tdup 0= if -13 throw then ;\n\n( It would be nice to provide a MAKE that worked with execution tokens\nas well, although \"defer\" and \"is\" can be used for that. MAKE expects\ntwo word names to be given as arguments. It will then change the behavior \nof the first word to use the second. MAKE is a state aware word. )\n\n: make immediate ( c1\" xxx\" c2\" xxx\" : change parsed word c1 to execute c2 )\n\tfind found? cell+\n\tfind found?\n\tstate @ if ( compiling )\n\t\tswap postpone 2literal ['] ! ,\n\telse ( command mode )\n\t\tswap !\n\tthen ;\n\nhider noop\n\n( ========================== DOER\/MAKE ======================================= )\n\n( ========================== Extended Word Set =============================== )\n\n: log ( u base -- u : command the logarithm of u in base )\n\t>r \n\tdup 0= if -11 throw then ( logarithm of zero is an error )\n\t0 swap\n\tbegin\n\t\tnos1+ rdup r> \/ dup 0= ( keep dividing until 'u' is zero )\n\tuntil\n\tdrop 1- rdrop ;\n\n: log2 ( u -- u : compute the logarithm of u )\n\t2 log ;\n\n: time ( \" ccc\" -- n : time the number of milliseconds it takes to execute a word )\n\tclock >r\n\tfind execute\n\tclock r> - ;\n\n( defer...is is probably not standards compliant, it is still neat! )\n: (do-defer) ( -- self : pushes the location into which it is compiled )\n\tr> dup >r 1- ;\n\n: defer ( \" ccc\" -- , Run Time -- location : \n\tcreates a word that pushes a location to write an execution token into )\n\t:: ' (do-defer) , postpone ; ;\n\n: is ( location \" ccc\" -- : make a deferred word execute a word ) \n\tfind found? swap ! ;\n\nhider (do-defer)\nhider found?\n\n( The \"tail\" function implements tail calls, which is just a jump\nto the beginning of the words definition, for example this\nword will never overflow the stack and will print \"1\" followed\nby a new line forever,\n\n\t: forever 1 . cr tail ;\n\nWhereas\n\n\t: forever 1 . cr recurse ;\n\nor\n\n\t: forever 1 . cr forever ;\n\nWould overflow the return stack. )\n\nhider tail\n: tail ( -- : perform tail recursion in current word definition )\n\timmediate\n\tlatest cell+\n\t' branch ,\n\there - cell+ , ;\n\n: recurse immediate\n\t( This function implements recursion, although this interpreter\n\tallows calling a word directly. If used incorrectly this will\n\tblow up the return stack.\n\n\tWe can test \"recurse\" with this factorial function:\n\t : factorial dup 2 < if drop 1 exit then dup 1- recurse * ; )\n\tlatest cell+ , ;\n\n: factorial ( x -- x : compute the factorial of a number )\n\tdup 2 < if drop 1 exit then dup 1- recurse * ;\n\n: myself ( -- : myself is a synonym for recurse ) \n\timmediate postpone recurse ;\n\n: gcd ( x1 x2 -- x : greatest common divisor )\n\tdup if tuck mod tail then drop ;\n\n( ========================== Extended Word Set =============================== )\n\n( The words described here on out get more complex and will require more\nof an explanation as to how they work. )\n\n( ========================== CREATE DOES> ==================================== )\n\n( The following section defines a pair of words \"create\" and \"does>\" which\nare a powerful set of words that can be used to make words that can create\nother words. \"create\" has both run time and compile time behavior, whilst\n\"does>\" only works at compile time in conjunction with \"create\". These two\nwords can be used to add constants, variables and arrays to the language,\namongst other things.\n\nA simple version of create is as follows\n\n\t: create :: dolist , here 2 cells + , ' exit , 0 state ! ;\n\nBut this version is much more limited.\n\n\"create\"...\"does>\" is one of the constructs that makes Forth Forth, it\nallows the creation of words which can define new words in themselves,\nand thus allows us to extend the language easily.\n)\n\n: write-quote ( -- : A word that writes ' into the dictionary )\n\t['] ' , ; \n\n: write-exit ( -- : A word that write exit into the dictionary )\n\t['] _exit , ;\n\n: write-compile, ( -- : A word that writes , into the dictionary ) \n\t' , , ;\n\n: state! ( bool -- : set the compilation state variable ) \n\tstate ! ;\n\n: command-mode ( -- : put the interpreter into command mode )\n\tfalse state! ;\n\n: command-mode-create ( create a new work that pushes its data field )\n\t:: ( compile a word )\n\tdolit , ( write push into new word )\n\there 2 cells + , ( push a pointer to data field )\n\tpostpone ; ; ( write exit and switch to command mode )\n\n: mark write-compile, ( Write in a place holder 0 and push a pointer to to be used by does> )\n\twrite-quote write-exit write-compile, ( Write in an exit in the word we're compiling. )\n\t['] command-mode , ; ( Make sure to change the state back to command mode )\n\n: create immediate ( create word is quite a complex forth word )\n\tstate @ \n\tif \n\t\tpostpone ( hole-to-patch -- )\n\timmediate\n\twrite-exit ( we don't want the defining word to exit, but the *defined* word to )\n\there swap ! ( patch in the code fields to point to )\n\tdolist , ; ( write a run in )\n\nhider write-quote\nhider write-compile,\nhider write-exit\n\n( Now that we have create...does> we can use it to create arrays, variables\nand constants, as we mentioned before. )\n\n: array ( u c\" xxx\" -- : create a named array of length u ) \n\tcreate allot does> + ;\n\n: variable ( x c\" xxx\" -- : create a variable will initial value of x )\n\tcreate , does> ;\n\n\\ : constant ( x c\" xxx\" -- : create a constant with value of x ) \n\\\tcreate , does> @ ;\n\n: table ( u c\" xxx\" --, Run Time: -- addr u : create a named table )\n\tcreate dup , allot does> dup @ ;\n\n: string ( u c\" xxx\" --, Run Time: -- c-addr u : create a named string )\n\tcreate dup , chars allot does> dup @ swap 1+ chars> swap ;\n\n\\ : +field \\ n <\"name\"> -- ; exec: addr -- 'addr\n\\ create over , +\n\\ does> @ + ;\n\\ \n\\ : begin-structure \\ -- addr 0 ; -- size\n\\ \tcreate\n\\ \there 0 0 , \\ mark stack, lay dummy\n\\ \tdoes> @ ; \\ -- rec-len\n\\ \n\\ : end-structure \\ addr n --\n\\ swap ! ; \\ set len \n\\ \n\\ begin-structure point\n\\ \tpoint +field p.x\n\\ \tpoint +field p.y\n\\ end-structure\n\\ \n\\ This should work...\n\\ : buffer: ( u c\" xxx\" --, Run Time: -- addr )\n\\\tcreate allot ;\n\n: 2constant \n\tcreate , , does> dup 1+ @ swap @ ;\n\n: 2variable \n\tcreate , , does> ;\n\n: enum ( x \" ccc\" -- x+1 : define a series of enumerations )\n\tdup constant 1+ ; \n\n( ========================== CREATE DOES> ==================================== )\n\n( ========================== DO...LOOP ======================================= )\n\n( The following section implements Forth's do...loop constructs, the\nword definitions are quite complex as it involves a lot of juggling of\nthe return stack. Along with begin...until do loops are one of the\nmain looping constructs. \n\nUnlike begin...until do accepts two values a limit and a starting value,\nthey are also words only to be used within a word definition, some Forths\nextend the semantics so looping constructs operate in command mode, this\nForth does not do that as it complicates things unnecessarily.\n\nExample:\n\t\n\t: example-1 10 1 do i . i 5 > if cr leave then loop 100 . cr ; \n\texample-1\n\nPrints:\n\t1 2 3 4 5 6\n\nIn \"example-1\" we can see the following:\n\n1. A limit, 10, and a start value, 1, passed to \"do\".\n2. A word called 'i', which is the current count of the loop\n3. If the count is greater than 5, we call a word call 'leave', this\nword exits the current loop context as well as the current calling\nword.\n4. \"100 . cr\" is never called. This should be changed in future\nrevision, but this version of leave exits the calling word as well.\n\n'i', 'j', and 'leave' *must* be used within a do...loop construct. \n\nIn order to remedy point 4. loop should not use branch but instead \nshould use a value to return to which it pushes to the return stack )\n\n: (do)\n\tswap ( swap the limit and start )\n\tr> ( save our return stack to temporary variable )\n\t-rot ( limit start return -- return start limit )\n\t>r ( push limit onto return stack )\n\t>r ( push start onto return stack )\n\t>r ; ( restore our return address )\n\n: do immediate ( Run time: high low -- : begin do...loop construct )\n\t' (do) ,\n\tpostpone begin ; \n\n: (unloop) ( -- , R: i limit -- : remove limit and i from )\n\tr> ( save our return address )\n\trdrop ( pop off i )\n\trdrop ( pop off limit )\n\t>r ; ( restore our return stack )\n\n: (+loop) ( x -- bool : increment loop variable by x and test it )\n\tr@ 1- ( get the pointer to i )\n\t+! ( add value to it )\n\tr@ 1- @ ( find i again )\n\tr@ 2- @ ( find the limit value )\n\tu>= ;\n\n: (loop) ( -- bool : increment loop variable by 1 and test it )\n\tr@ 1- ( get the pointer to i )\n\t1+! ( add one to it )\n\tr@ 1- @ ( find the value again )\n\tr@ 2- @ ( find the limit value )\n\tu>= ;\n\n: loop ( -- : end do...loop construct )\n\timmediate ' (loop) , postpone until ' (unloop) , ;\n\n: +loop ( x -- : end do...+loop loop construct )\n\timmediate ' (+loop) , postpone until ' (unloop) , ;\n\n: leave ( -- , R: i limit return -- : break out of a do-loop construct )\n\t(unloop)\n\trdrop ; ( return to the caller's caller routine )\n\n: ?leave ( x -- , R: i limit return -- | i limit return : conditional leave )\n\tif\n\t\t(unloop)\n\t\trdrop ( return to the caller's caller routine )\n\tthen ;\n\n: i ( -- i : Get current, or innermost, loop index in do...loop construct )\n\tr> r> ( pop off return address and i )\n\ttuck ( tuck i away )\n\t>r >r ; ( restore return stack )\n\n: j ( -- j : Get outermost loop index in do...loop construct )\n\t4 rpick ;\n\n( This is a simple test function for the looping, for interactive\ntesting and debugging:\n : mm 5 1 do i . cr 4 1 do j . tab i . cr loop loop ; )\n\n: range ( nX nY -- nX nX+1 ... nY ) \n\tnos1+ do i loop ;\n\n: repeater ( n0 X -- n0 ... nX ) \n\t1 do dup loop ;\n\n: sum ( n0 ... nX X -- sum<0..X> ) \n\t1 do + loop ;\n\n: mul ( n0 ... nX X -- mul<0..X> ) \n\t1 do * loop ;\n\n: reverse ( x1 ... xn n -- xn ... x1 : reverse n items on the stack )\n\t0 do i roll loop ;\n\n( ========================== DO...LOOP ======================================= )\n\n0 variable column-counter\n4 variable column-width\n\n: column ( i -- )\t\n\tcolumn-width @ mod not if cr then ;\n\n: column.reset\t\t\n\t0 column-counter ! ;\n\n: auto-column\t\t\n\tcolumn-counter dup @ column 1+! ;\n\n: alignment-bits \n\t[ 1 size log2 lshift 1- literal ] and ;\n\n0 variable x\n: x! ( x -- ) \n\tx ! ;\n\n: x@ ( -- x ) \n\tx @ ;\n\n: 2>r ( x1 x2 -- R: x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tswap\n\t\t>r\n\t\t>r\n\tx@ >r ; ( restore return address )\n\n: 2r> ( R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tr>\n\t\tr>\n\t\tswap\n\tx@ >r ; ( restore return address )\n\n: 2r@ ( -- x1 x2 , R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\tr> r>\n\t2dup\n\t>r >r\n\tswap\n\tx@ >r ; ( restore return address )\n\n: unused ( -- u : push the amount of core left ) \n\tmax-core here - ;\n\n: accumulator ( initial \" ccc\" -- : make a word that increments by a value and pushes the result )\n\tcreate , does> tuck +! @ ;\n\n: counter ( \" ccc\" --, Run Time: -- x : make a word that increments itself by one, starting from zero )\n\tcreate -1 , does> dup 1+! @ ;\n\n0 variable delim\n: accepter ( c-addr max delimiter -- i )\n\t( store a \"max\" number of chars at c-addr until \"delimiter\" encountered,\n\tthe number of characters stored is returned )\n\tdelim ! ( store delimiter used to stop string storage when encountered)\n\t0\n\tdo\n\t\tkey dup delim @ <>\n\t\tif\n\t\t\tover c! 1+\n\t\telse ( terminate string )\n\t\t\tdrop 0 swap c! \n\t\t\ti \n\t\t\tleave\n\t\tthen\n\tloop\n\t-18 throw ; ( read in too many chars )\nhider delim\n\n: skip ( char -- : read input until string is reached )\n\tkey drop >r 0 begin drop key dup rdup r> <> until rdrop ;\n\n: word ( c -- c-addr : parse until 'c' is encountered, push transient counted string )\n\tdup skip chere 1+ c!\n\t>r\n\tchere 2+\n\tpad here - chars>\n\tr> accepter 1+\n\tchere c!\n\tchere ;\nhider skip\n\n( This foreach mechanism needs thinking about, what is the best information to\npresent to the word to be executed? At the moment only the contents of the\ncell that it should be processing is.\n\nAt the moment foreach uses a do...loop construct, which means that the\nfollowing cannot be used to exit from the foreach loop:\n\n\t: return [ : exit early from a foreach loop ]\n\t\tr> rdrop >r ;\n\nAlthough this can be remedied, we know that it puts a loop onto the return\nstack.\n\nIt also uses a variable 'xt', which means that foreach loops cannot be\nnested. This word really needs thinking about.\n\nThis seems to be a useful, general, mechanism that is missing from\nmost Forths. More words like this should be made, they are powerful\nlike the word 'compose', but they need to be created correctly. )\n\n0 variable xt\n: foreach ( addr u xt -- : execute xt for each cell in addr-u )\n\txt !\n\tbounds do i xt @ execute 1 cell +loop ;\n\n: foreach-char ( c-addr u xt -- : execute xt for each cell in c-addr u )\n\txt !\n\tbounds do i xt @ execute loop ;\nhider xt\n\n: accept ( c-addr +n1 -- +n2 : see accepter definition ) \n\tnl accepter ;\n\n: (subst) ( char1 char2 c-addr )\n\t3dup ( char1 char2 c-addr char1 char2 c-addr )\n\tc@ = if ( char1 char2 c-addr char1 )\n\t\tswap c! ( match, substitute character )\n\telse ( char1 char2 c-addr char1 )\n\t\t2drop ( no match )\n\tthen ;\n\n: subst ( c-addr u char1 char2 -- replace all char1 with char2 in string )\n\tswap\n\t2swap\n\t['] (subst) foreach-char 2drop ;\nhider (subst)\n\n0xFFFF constant max-string-length\n\n: (.\") ( char -- c-addr u )\n\t( @todo This really needs simplifying, to do this\n\ta set of words that operate on a temporary buffer can\n\tbe used )\n\t( Write a string into word being currently defined, this\n\tcode has to jump over the string it has just put into the\n\tdictionary so normal execution of a word can continue. The\n\tlength and character address of the string are left on the\n\tstack )\n\t>r ( save delimiter )\n\t' branch , ( write in jump, this will jump past the string )\n\t>mark ( make hole )\n\tdup 1+ chars> ( calculate address to write to )\n\tmax-string-length \n\tr> ( restore delimiter )\n\taccepter dup >r ( write string into dictionary, save index )\n\taligned 2dup size \/ ( stack: length hole char-len hole )\n\t1+ dup allot ( update dictionary pointer with string length )\n\t1+ swap ! ( write place to jump to )\n\tdrop ( do not need string length anymore )\n\t1+ chars> ( calculate place to print )\n\tr> ; ( restore index and address of string )\n\n: length ( c-addr u -- u : push the length of an ASCIIZ string )\n tuck 0 do dup c@ 0= if 2drop i leave then 1+ loop ;\n\n: asciiz? ( c-addr u -- : is a Forth string also a ASCIIZ string )\n\ttuck length <> ;\n\n: asciiz ( c-addr u -- : trim a string until NUL terminator )\n\t2dup length nip ;\n\n\n: (type) ( c-addr -- ) \n\tc@ emit ;\n\n: type ( c-addr u -- : print out 'u' characters at c-addr )\n\t['] (type) foreach-char ;\nhider (type)\n\n: do-string ( char -- : write a string into the dictionary reading it until char is encountered )\n\t(.\") \n\tstate @ if swap [literal] [literal] then ;\n\n: fill ( c-addr u char -- : fill in an area of memory with a character, only if u is greater than zero )\n\t-rot\n\t0 do 2dup i + c! loop\n\t2drop ;\n\n: \/string ( c-addr1 u1 n -- c-addr2 u2 : advance a string by n characters )\n\tover min rot over + -rot - ;\n\n: compare ( c-addr1 u1 c-addr2 u2 -- n : compare two strings, not quite compliant yet )\n\t>r swap r> min >r\n\tstart-address + swap start-address + r>\n\tmemory-compare ;\n\n128 string sbuf\n: s\" ( \"ccc\" --, Run Time -- c-addr u )\n\tkey drop sbuf 0 fill sbuf [char] \" accepter sbuf drop swap ;\nhider sbuf\n\n( @todo these strings really need rethinking, state awareness needs to be removed... )\n: type, \n\tstate @ if ' type , else type then ;\n\n: c\" \n\timmediate key drop [char] \" do-string ;\n\n: \" \n\timmediate key drop [char] \" do-string type, ;\n\n: sprint ( c -- : print out chars until 'c' is encountered )\n\tkey drop ( drop next space )\n\t>r ( save delimiter )\n\tbegin\n\t\tkey dup ( get next character )\n\t\trdup r> ( get delimiter )\n\t\t<> if emit 0 then\n\tuntil rdrop ;\n\n: .( \n\timmediate [char] ) sprint ;\nhider sprint\n\n: .\" \n\timmediate key drop [char] \" do-string type, ;\n\nhider type,\n\n( This word really should be removed along with any usages of this word, it\nis not a very \"Forth\" like word, it accepts a pointer to an ASCIIZ string and\nprints it out, it also does not checking of the returned values from write-file )\n: print ( c-addr -- : print out a string to the standard output )\n\t-1 over >r length r> swap stdout write-file 2drop ;\n\n: ok \n\t\" ok\" cr ;\n\n: empty-stack ( x-n ... x-0 -- : empty the variable stack )\n\tbegin depth while drop repeat ;\n\n: (quit) ( -- : do the work of quit, without the restart )\n\t0 `source-id ! ( set source to read from file )\n\t`stdin @ `fin ! ( read from stdin )\n\tpostpone [ ( back into command mode )\n\t' interpret start! ; ( set interpreter starting word )\n\n: quit ( -- : Empty return stack, go back to command mode, read from stdin, interpret input )\n\t(quit)\n\t-1 restart ; ( restart the interpreter )\n\n: abort\n\t-1 throw ;\n\n: (abort\") ( do the work of abort )\n\t(quit)\n\t-2 throw ;\n\n: abort\" immediate \n\tpostpone \"\n\t' cr , ' (abort\") , ;\n\n( ==================== CASE statements ======================== )\n\n( for a simpler case statement:\n\tsee Volume 2, issue 3, page 48 of Forth Dimensions at\n\thttp:\/\/www.forth.org\/fd\/contents.html )\n\n( These case statements need improving, it is not standards compliant )\n: case immediate\n\t' branch , 3 , ( branch over the next branch )\n\there ' branch , ( mark: place endof branches back to with again )\n\t>mark swap ; ( mark: place endcase writes jump to with then )\n\n: over= ( x y -- x bool : over ... then = )\n\tover = ;\n\n: of\n\timmediate ' over= , postpone if ;\n\n: endof\n\timmediate over postpone again postpone then ;\n\n: endcase\n\timmediate 1+ postpone then drop ;\n\n( ==================== CASE statements ======================== )\n\n( ==================== Hiding Words =========================== )\n\n: }hide ( should only be matched with 'hide{' )\n\timmediate -22 throw ;\n\n: hide{ ( -- : hide a list of words, the list is terminated with \"}hide\" )\n\tbegin\n\t\tfind ( find next word )\n\t\tdup [ find }hide ] literal = if\n\t\t\tdrop exit ( terminate hide{ )\n\t\tthen\n\t\tdup 0= if -15 throw then\n\t\t(hide) drop\n\tagain ;\n\nhider (hide)\n\n( ==================== Hiding Words =========================== )\n\n: spaces ( n -- : print n spaces ) \n\t0 do space loop ;\n\n: erase ( addr u : erase a block of memory )\n\t2chars> 0 fill ;\n\n: blank ( c-addr u : fills a string with spaces )\n\tbl fill ;\n\n( move should check that u is not negative )\n: move ( addr1 addr2 u -- : copy u words of memory from 'addr2' to 'addr1' )\n\t0 do\n\t\t2dup i + @ swap i + !\n\tloop\n\t2drop ;\n\n( It would be nice if move and cmove could share more code, as they do exactly\n the same thing but with different load and store functions, cmove> )\n: cmove ( c-addr1 c-addr2 u -- : copy u characters of memory from 'c-addr2' to 'c-addr1' )\n\t0 do\n\t\t2dup i + c@ swap i + c!\n\tloop\n\t2drop ;\n\n( ==================== Conditional Compilation ================ )\n\n( The words \"[if]\", \"[else]\" and \"[then]\" implement conditional compilation,\nthey can be nested as well\n\nSee http:\/\/lars.nocrew.org\/dpans\/dpans15.htm for more information\n\nA much simpler conditional compilation method is the following\nsingle word definition:\n\n : compile-line? 0= if [ find \\\\ , ] then ;\n\nWhich will skip a line if a conditional is false, and compile it\nif true )\n\n( These words really, really need refactoring, I could use the newly defined \n \"defer\" to help out with this )\n0 variable nest ( level of [if] nesting )\n0 variable [if]-word ( populated later with \"find [if]\" )\n0 variable [else]-word ( populated later with \"find [else]\")\n: [then] immediate ;\n: reset-nest 1 nest ! ;\n: unnest? [ find [then] ] literal = if nest 1-! then ;\n: nest? [if]-word @ = if nest 1+! then ;\n: end-nest? nest @ 0= ;\n: match-[else]? [else]-word @ = nest @ 1 = and ;\n\n: [if] ( bool -- : conditional execution )\n\tunless\n\t\treset-nest\n\t\tbegin\n\t\t\tfind\n\t\t\tdup nest?\n\t\t\tdup match-[else]? if drop exit then\n\t\t\t unnest?\n\t\t\tend-nest?\n\t\tuntil\n\tthen ;\n\n: [else] ( discard input until [then] encounter, nesting for [if] )\n\treset-nest\n\tbegin\n\t\tfind\n\t\tdup nest? unnest?\n\t\tend-nest?\n\tuntil ;\n\nfind [if] [if]-word !\nfind [else] [else]-word !\n\n: ?( if postpone ( then ; \\ conditionally read until ')'\n: ?\\ if postpone \\ then ;\n: 16bit\\ size 2 <> if postpone \\ then ;\n: 32bit\\ size 4 <> if postpone \\ then ;\n: 64bit\\ size 8 <> if postpone \\ then ;\n\nhide{ \n\t[if]-word [else]-word nest \n\treset-nest unnest? match-[else]? \n\tend-nest? nest? \n}hide\n\n( ==================== Conditional Compilation ================ )\n\n( ==================== Endian Words =========================== )\n\nsize 2 = [if] 0x0123 `x ! [then]\nsize 4 = [if] 0x01234567 `x ! [then]\nsize 8 = [if] 0x01234567abcdef `x ! [then]\n\n: endian ( -- bool : returns the endianess of the processor, little = 0, big = 1 )\n\t[ `x chars> c@ 0x01 = ] literal ;\n\n: swap16 ( x -- x : swap the byte order a 16 bit number )\n\tdup 256* 0xff00 and >r 256\/ lsb r> or ;\n\nsize 4 >= [if] \n\t: swap32 \n\t\tdup 0xffff and swap16 16 lshift swap\n\t\t16 rshift 0xffff and swap16 or ;\n[then]\n\nsize 8 >= [if]\n\t: swap64 ( x -- x : swap the byte order of a 64 bit number )\n\t\t dup 0xffffffff and swap32 32 lshift swap\n\t\t 32 rshift 0xffffffff and swap32 or ;\n[then]\n\nsize 2 = [if]\n\tendian \n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\tswap16 ;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\t;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\tswap16 ;\n\t[then]\n[then]\n\nsize 4 = [if]\n\tendian \n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\tswap32 ;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\t;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\tswap32 ;\n\t[then]\n[then]\n\nsize 8 = [if]\n\tendian \n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\tswap64 ;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\t;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\tswap64 ;\n\t[then]\n[then]\n\n( ==================== Endian Words =========================== )\n\n( ==================== Misc words ============================= )\n\n: (base) ( -- base : unmess up libforth's base variable )\n\tbase @ 0= if 10 else base @ then ;\n\n: #digits ( u -- u : number of characters needed to represent 'u' in current base )\n\tdup 0= if 1+ exit then\n\t(base) log 1+ ;\n\n: digits ( -- u : number of characters needed to represent largest unsigned number in current base )\n\t-1 #digits ;\n\n: print-number ( u -- print a number taking up a fixed amount of space on the screen )\n\tbase @ 16 = if . exit then ( @todo this is a hack related to libforth printing out hex specially)\n\tdup #digits digits swap - dup 0<> if spaces else drop then . ;\n\n: address ( u -- : print out and address )\n\t@ print-number ;\n\n0 variable counter\n\n: counted-column ( index -- : special column printing for dump )\n\tcounter @ column-width @ mod\n\tnot if cr print-number \" :\" space else drop then\n\tcounter 1+! ;\n\n: as-chars ( x n -- : print a cell out as characters, upto n chars )\n\t0 ( from zero to the size of a cell )\n\tdo\n\t\tdup ( copy variable to print out )\n\t\tsize i 1+ - select-byte ( select correct byte )\n\t\tdup printable? not ( is it not printable )\n\t\tif drop [char] . then ( print a '.' if it is not )\n\t\temit ( otherwise print it out )\n\tloop\n\tspace ( print out space after )\n\tdrop ; ( drop cell we have printed out )\n\n: lister ( addr u addr -- )\n\t0 counter ! 1- swap \n\tdo \n\t\tdup counted-column 1+ i address i @ size as-chars \n\tloop ;\n\n( @todo this function should make use of 'defer' and 'is', then different\nversion of dump could be made that swapped out 'lister' )\n: dump ( addr u -- : dump out 'u' cells of memory starting from 'addr' )\n\t1+ over + under lister drop \n\tcr ;\n\nhide{ counted-column counter as-chars address print-number }hide\n\n( Fence can be used to prevent any word defined before it from being forgotten \nUsage:\n\there fence ! )\n0 variable fence\n\n: forgetter ( pwd-token -- : forget a found word and everything after it )\n\tdup 0= if -15 throw then ( word not found! )\n\tdup fence @ u< if -15 throw then ( forgetting a word before fence! )\n\tdup @ pwd ! h ! ;\n\n: forget ( WORD -- : forget word and every word defined after it )\n\tfind 1- forgetter ;\n\n: marker ( WORD -- : make word the forgets itself and words after it)\n\t:: latest [literal] ' forgetter , postpone ; ;\nhider forgetter\n\n: ** ( b e -- x : exponent, raise 'b' to the power of 'e')\n\t?dup-if\n\t\tover swap\n\t\t1 do over * loop \n\t\tnip\n\telse\n\t\tdrop 1\n\tendif ;\n\n0 variable a\n0 variable b\n0 variable m\n: equal ( a1...an b1...bn n -- a1...an b1...bn bool : determine if two lists are equal )\n\t( example: \n\t\t1 2 3 \n\t\t1 2 3 \n\t\t3 equal \n\treturns: 1 )\n\tdup m ! 1+ 1 ( store copy of length and use as loop index )\n\tdo \n\t\ti 1- pick b ! ( store ith element of list in b1...bn )\n\t\ti m @ + 1- pick a ! ( store ith element of list in a1...an )\n\t\ta @ b @ <> ( compare a and b for equality )\n\t\tif 0 leave then ( unequal, finish early )\n\tloop 1 ; ( lists must be equal )\n\nhide{ a b m }hide\n\n: ndrop ( drop n items )\n\t?dup-if 0 do drop loop then ;\n\n: caesar ( c key -- o : encode a alphabetic character with a key using a generalization of the Caesar cipher )\n\t>r\n\tdup uppercase? if [char] A - r> + 26 mod [char] A + exit then\n\tdup lowercase? if [char] a - r> + 26 mod [char] a + exit then\n\trdrop ; ( it goes without saying that this should not be used for anything serious! )\n\n: caesar-type ( c-addr u key : type out encoded text with a Caesar cipher )\n\t-rot bounds do i c@ over caesar emit loop drop ;\n\n: rot13 ( c -- c : encode a character with ROT-13 )\n\t13 caesar ;\n\n: rot13-type ( c-addr u : print string in ROT-13 encoded form )\n\t13 caesar-type ;\n\n\\ s\" abcdefghijklmnopqrstuvwxyz\" rot13-type -> nopqrstuvwxyzabcdefghijklm\n\\ s\" hello\" rot13-type -> uryyb\n\n( ==================== Misc words ============================= )\n\n( ==================== Pictured Numeric Output ================ )\n( Pictured numeric output is what Forths use to display numbers\nto the screen, this Forth has number output methods built into\nthe Forth kernel and mostly uses them instead, but the mechanism\nis still useful so it has been added.\n\n@todo Pictured number output should act on a double cell number\nnot a single cell number )\n\n0 variable hld\n\n: overflow ( -- : check if we overflow the hold area )\n \there chars> pad chars> hld @ - u> if -17 throw then ;\n\n: hold ( char -- : add a character to the numeric output string )\n\toverflow pad chars> hld @ - c! hld 1+! ;\n\n: holds ( addr u -- )\n begin dup while 1- 2dup + c@ hold repeat 2drop ;\n\n: nbase ( -- base : in this forth 0 is a special base, push 10 is base is zero )\n\tbase @ dup 0= if drop 10 then ;\n\n: <# ( -- : setup pictured numeric output )\n\t0 hld ! ;\n\n: sign ( -- : add a sign to the pictured numeric output string )\n\t[char] - hold ;\n\n: # ( x -- x : divide x by base, turn into a character, put in pictured output string )\n\tnbase um\/mod swap \n \tdup 9 u>\n \tif 7 + then\n \t48 + hold ;\n\n: #s ( x -- 0 : repeatedly call # on x until x is zero )\n\tbegin # dup 0= until ; \n\n: #> ( -- c-addr u : end pictured output conversion, push output string to stack )\n\t0 hold ( NUL terminate string, just in case )\n\thld 1-! ( but do not include that in the count )\n\tpad chars> hld @ \n\ttuck - 1+ swap ;\n\n: u. ( u -- : display number in base 10 )\n\tbase @ >r decimal <# #s #> type drop r> base ! ;\n\nhide{ nbase overflow }hide\n\n( ==================== Pictured Numeric Output ================ )\n\n( ==================== Numeric Input ========================= )\n( The Forth executable can handle numeric input and does not need\nthe routines defined here, however the user might want to write\nroutines that use >NUMBER. >NUMBER is a generic word, but it\nis a bit difficult to use on its own. )\n\n: map ( char -- n|-1 : convert character in 0-9 a-z range to number )\n\tdup lowercase? if [char] a - 10 + exit then\n\tdup decimal? if [char] 0 - exit then\n\tdrop -1 ;\n\n: number? ( char -- bool : is a character a number in the current base )\n\t>lower map (base) u< ;\n\n: >number ( n c-addr u -- n c-addr u : convert string )\n\tbegin\n\t\t( get next character )\n\t\t2dup >r >r drop c@ dup number? ( n char bool, R: c-addr u )\n\t\tif ( n char )\n\t\t\tswap (base) * swap map + ( accumulate number )\n\t\telse ( n char )\n\t\t\tdrop\n\t\t\tr> r> ( restore string )\n\t\t\texit\n\t\tthen\n\t\tr> r> ( restore string )\n\t\t1 \/string dup 0= ( advance string and test for end )\n\tuntil ;\n\nhide{ map }hide\n\n( ==================== Numeric Input ========================= )\n\n( ==================== ANSI Escape Codes ====================== )\n( Terminal colorization module, via ANSI Escape Codes\n \nsee: https:\/\/en.wikipedia.org\/wiki\/ANSI_escape_code\nThese codes will provide a relatively portable means of\nmanipulating a terminal )\n\n27 constant 'escape'\n: CSI 'escape' emit .\" [\" ;\n0 constant black\n1 constant red\n2 constant green\n3 constant yellow\n4 constant blue\n5 constant magenta\n6 constant cyan\n7 constant white\n: foreground 30 + ;\n: background 40 + ;\n0 constant dark\n1 constant bright\nfalse variable colorize \n\n: color ( brightness color-code -- : set the terminal color )\n\t( set color on an ANSI compliant terminal,\n\tfor example:\n\t\tbright red foreground color\n\tsets the foreground text to bright red )\n\tcolorize @ 0= if 2drop exit then \n\tCSI u. if .\" ;1\" then .\" m\" ;\n\n: at-xy ( x y -- : set ANSI terminal cursor position to x y )\n\tCSI u. [char] ; emit u. .\" H\" ;\n\n: page ( -- : clear ANSI terminal screen and move cursor to beginning ) \n\tCSI .\" 2J\" 1 1 at-xy ;\n\n: hide-cursor ( -- : hide the cursor from view ) \n\tCSI .\" ?25l\" ;\n\n: show-cursor ( -- : show the cursor ) \n\tCSI .\" ?25h\" ;\n\n: save-cursor ( -- : save cursor position ) \n\tCSI .\" s\" ;\n\n: restore-cursor ( -- : restore saved cursor position ) \n\tCSI .\" u\" ;\n\n: reset-color ( -- : reset terminal color to its default value)\n\tcolorize @ 0= if exit then\n\tCSI .\" 0m\" ;\n\nhide{ CSI }hide\n( ==================== ANSI Escape Codes ====================== )\n\n( ==================== Unit test framework =================== )\n\n256 string estring ( string to test )\n0 variable #estring ( actual string length )\n0 variable start ( starting depth )\n0 variable result ( result depth )\n0 variable check ( only check depth if -> is called )\n0 variable dictionary ( dictionary pointer on entering { )\n0 variable previous ( PWD register on entering { )\n\n: T ; ( hack until T{ can process words )\n\n: -> ( -- : save depth in variable ) \n\t1 check ! depth result ! ; \n\n: test estring drop #estring @ ; \n\n: fail ( -- : invalidate the forth interpreter and exit )\n\tinvalidate bye ;\n\n: neutral ( -- : neutral color )\n\t;\n\n: bad ( -- : bad color )\n\tdark red foreground color ;\n\n: good ( -- : good color )\n\tdark green foreground color ;\n\n: die bad test type reset-color cr fail ;\n\n: evaluate? ( bool -- : test if evaluation has failed )\n\tif .\" evaluation failed\" cr fail then ;\n\n: failed bad .\" failed\" reset-color cr ;\n\n: adjust ( x -- x : adjust a depth to take into account starting depth ) \n\tstart @ - ;\n\n: no-check? ( -- bool : if true we need to check the depth )\n\tcheck @ 0= ;\n\n: depth? ( -- : check if depth is correct )\n\tno-check? if exit then\n\tdepth adjust ( get depth and adjust for starting depth )\n\tresult @ adjust 2* = ( get results depth, same adjustment, should be\n\t half size of the depth ) \n\tif exit then ( pass )\n\tfailed\n\t.\" Unequal depths:\" cr\n\t.\" depth: \" depth . cr\n\t.\" result: \" result @ . cr\n\tdie ;\n\n: equal? ( -- : determine if results equals expected )\n\tno-check? if exit then\n\tresult @ adjust equal\n\tif exit then\n\tfailed\n\t.\" Result is not equal to expected values. \" cr \n\t.\" Stack: \" cr .s cr\n\tdie ;\n\n: display ( c-addr u -- : print out testing message in estring )\n\tverbose if neutral type else 2drop then ;\n\n: pass ( -- : print out passing message )\n\tverbose if good .\" ok \" cr reset-color then ;\n\n: save ( -- : save current dictionary )\n\tpwd @ previous !\n\there dictionary ! ;\n\n: restore ( -- : restore dictionary )\n\tprevious @ pwd ! \n\tdictionary @ h ! ;\n\n\n: T{ ( -- : perform a unit test )\n\tdepth start ! ( save start of stack depth )\n\t0 result ! ( reset result variable )\n\t0 check ! ( reset check variable )\n\testring 0 fill ( zero input string )\n\tsave ( save dictionary state )\n\tkey drop ( drop next character, which is a space )\n\testring [char] } accepter #estring ! ( read in string to test )\n\ttest display ( print which string we are testing )\n\ttest evaluate ( perform test )\n\tevaluate? ( evaluate successfully? )\n\tdepth? ( correct depth )\n\tequal? ( results equal to expected values? )\n\tpass ( print pass message )\n\tresult @ adjust 2* ndrop ( remove items on stack generated by test )\n\trestore ; ( restore dictionary to previous state )\n\nT{ }T\nT{ -> }T\nT{ 1 -> 1 }T\nT{ 1 2 -> 1 2 }T\nT{ : c 1 2 ; c -> 1 2 }T\nT{ :noname 2 ; :noname 3 + ; compose execute -> 5 }T\n\nhide{ \n\tpass test display\n\tadjust start save restore dictionary previous \n\tevaluate? equal? depth? estring #estring result\n\tcheck no-check? die neutral bad good failed\n}hide\n\n( ==================== Unit test framework =================== )\n\n\n( ==================== Random Numbers ========================= )\n\n( \nSee:\nuses xorshift\nhttps:\/\/en.wikipedia.org\/wiki\/Xorshift\nhttp:\/\/excamera.com\/sphinx\/article-xorshift.html\nhttp:\/\/www.arklyffe.com\/main\/2010\/08\/29\/xorshift-pseudorandom-number-generator\/\nthese constants have be collected from the web \n)\n\nsize 2 = [if] 13 constant a 9 constant b 7 constant c [then]\nsize 4 = [if] 13 constant a 17 constant b 5 constant c [then]\nsize 8 = [if] 12 constant a 25 constant b 27 constant c [then]\n\n7 variable seed ( must not be zero )\n\n: seed! ( x -- : set the value of the PRNG seed )\n\tdup 0= if drop 7 ( zero not allowed ) then seed ! ;\n\n: random ( -- x : assumes word size is 32 bit )\n\tseed @\n\tdup a lshift xor\n\tdup b rshift xor\n\tdup c lshift xor\n\tdup seed! ;\n\nhide{ a b c seed }hide\n\n( ==================== Random Numbers ========================= )\n\n( ==================== Prime Numbers ========================== )\n( From original \"third\" code from the IOCCC at \nhttp:\/\/www.ioccc.org\/1992\/buzzard.2.design, the module works out\nand prints prime numbers. )\n\n: prime? ( u -- u | 0 : return number if it is prime, zero otherwise )\n\tdup 1 = if 1- exit then\n\tdup 2 = if exit then\n\tdup 2\/ 2 ( loop from 2 to n\/2 )\n\tdo\n\t\tdup ( value to check if prime )\n\t\ti mod ( mod by divisor )\n\t\tnot if\n\t\t\tdrop 0 leave\n\t\tthen\n\tloop ;\n\n0 variable counter\n\n: primes ( x1 x2 -- : print the primes from x2 to x1 )\n\t0 counter !\n\t\" The primes from \" dup . \" to \" over . \" are: \"\n\tcr\n\tcolumn.reset\n\tdo\n\t\ti prime?\n\t\tif\n\t\t\ti . counter @ column counter 1+!\n\t\tthen\n\tloop\n\tcr\n\t\" There are \" counter @ . \" primes.\"\n\tcr ;\n\nhide{ counter }hide\n( ==================== Prime Numbers ========================== )\n\n( ==================== Debugging info ========================= )\n\n( string handling should really be done with PARSE, and CMOVE )\n\n: sh ( cnl -- ior : execute a line as a system command )\n\tnl word count system ;\n\nhide{ .s }hide\n: .s ( -- : print out the stack for debugging )\n\t[char] < emit depth u. [char] > emit space\n\tdepth if\n\t\tdepth 0 do i column tab depth i 1+ - pick . loop\n\tthen\n\tcr ;\n\n1 variable hide-words ( do we want to hide hidden words or not )\n\n: name ( PWD -- c-addr : given a pointer to the PWD field of a word get a pointer to the name of the word )\n\tdup 1+ @ 256\/ word-mask and lsb - chars> ;\n\n( This function prints out all of the defined words, excluding hidden words.\nAn understanding of the layout of a Forth word helps here. The dictionary\ncontains a linked list of words, each forth word has a pointer to the previous\nword until the first word. The layout of a Forth word looks like this:\n\nNAME: Forth Word - A variable length ASCII NUL terminated string\nPWD: Previous Word Pointer, points to the previous word\nCODE: Flags, code word and offset from previous word pointer to start of Forth word string\nDATA: The body of the forth word definition, not interested in this.\n\nThere is a register which stores the latest defined word which can be\naccessed with the code \"pwd @\". In order to print out a word we need to\naccess a words CODE field, the offset to the NAME is stored here in bits\n8 to 14 and the offset is calculated from the PWD field.\n\n\"print\" expects a character address, so we need to multiply any calculated\naddress by the word size in bytes. )\n\n: words.immediate ( bool -- : emit or mark a word being printed as being immediate )\n\tnot if dark red foreground color then ;\n\n: words.defined ( bool -- : emit or mark a word being printed as being a built in word )\n\tnot if bright green background color then ;\n\n: words.hidden ( bool -- : emit or mark a word being printed as being a hidden word )\n\tif dark magenta foreground color then ;\n\n: words ( -- : print out all defined an visible words )\n\tlatest\n\tspace\n\tbegin\n\t\tdup\n\t\thidden? hide-words @ and\n\t\tnot if\n\t\t\thidden? words.hidden\n\t\t\tcompiling? words.immediate\n\t\t\tdup defined-word? words.defined\n\t\t\tname\n\t\t\tprint space\n\t\t\treset-color\n\t\telse\n\t\t\tdrop\n\t\tthen\n\t\t@ ( Get pointer to previous word )\n\t\tdup dictionary-start u< ( stop if pwd no longer points to a word )\n\tuntil\n\tdrop cr ;\n\n( Simpler version of words\n: words\n\tpwd @ \n\tbegin\n\t\tdup name print space @ dup dictionary-start u<\n\tuntil drop cr ; )\n\nhide{ words.immediate words.defined words.hidden hidden? hidden-bit }hide\n\n: TrueFalse ( -- : print true or false )\n\tif \" true\" else \" false\" then ;\n\n: registers ( -- : print out important registers and information about the virtual machine )\n\t\" return stack pointer: \" r@ . cr\n\t\" dictionary pointer \" here . cr\n\t\" previous word: \" pwd ? cr\n\t\" state: \" state ? cr\n\t\" base: \" base ? cr\n\t\" depth: \" depth . cr\n\t\" cell size (in bytes): \" size . cr\n\t\" last cell address: \" max-core . cr\n\t\" unused cells: \" unused . cr\n\t\" invalid: \" `invalid @ TrueFalse cr\n\t\" size of variable stack: \" `stack-size ? cr\n\t\" size of return stack: \" `stack-size ? cr\n\t\" start of variable stack: \" max-core `stack-size @ 2* - . cr\n\t\" start of return stack: \" max-core `stack-size @ - . cr\n\t\" current input source: \" source-id -1 = if \" string\" else \" file\" then cr\n\t\" tracing on: \" `debug @ TrueFalse cr\n\t\" starting word: \" `instruction ? cr\n\t\" real start address: \" `start-address ? cr\n\t\" error handling: \" `error-handler ? cr \n\t\" throw handler: \" `handler ? cr\n\t\" signal recieved: \" `signal ? cr ;\n\t\n( `sin `sidx `slen `fout\n `stdout `stderr `argc `argv )\n\n\n: y\/n? ( -- bool : ask a yes or no question )\n\tkey drop\n\t\" y\/n? \"\n\tbegin\n\t\tkey\n\t\tdup\n\t\t[char] y = if true exit then\n\t\t[char] n = if false exit then\n\t\t\" y\/n? \"\n\tagain ;\n\n: step\n\t( step through a word: this word could be augmented\n\twith commands such as \"dump\", \"halt\", and optional\n\t\".s\" and \"registers\" )\n\tregisters\n\t\" .s: \" .s cr\n\t\" -- press any key to continue -- \"\n\tkey drop ;\n\n: more ( -- : wait for more input )\n\t\" -- press any key to continue -- \" key drop cr page ;\n\n: debug-help ( -- : print out the help for the debug command )\n \" debug mode commands\n\th - print help\n\tq - exit interpreter word\n\tr - print registers\n\ts - print stack\n\tR - print return stack\n\tc - continue on with execution\n\" ;\n\ndoer debug-prompt\n: prompt-default\n\t.\" debug> \" ;\n\nmake debug-prompt prompt-default\n\n: debug ( -- : enter interactive debug prompt )\n\tcr\n\t\" Entered Debug Prompt. Type 'h' for help. \" cr \n\tbegin\n\t\tkey\n\t\tcase\n\t\t\tnl of debug-prompt endof\n\t\t\t[char] h of debug-help endof\n\t\t\t[char] q of bye endof\n\t\t\t[char] r of registers endof\n\t\t\t[char] s of >r .s r> endof\n\t\t\t[char] R of r> r.s >r endof\n\t\t\t[char] c of drop exit endof\n\t\t\t( @todo add throw here )\n\t\tendcase drop\n\tagain ;\nhider debug-prompt\n\n: code>pwd ( CODE -- PWD\/0 : calculate PWD from code address )\n\tdup dictionary-start here within not if drop 0 exit then\n\t1 cells - ;\n\n: word-printer ( CODE -- : print out a words name given its code field )\n\tdup 1 cells - @ -1 = if . \" noname\" exit then ( nonames are marked by a -1 before its code field )\n\tdup code>pwd ?dup-if .d name print else drop \" data\" then\n\t drop ;\n\nhide{ code>pwd }hide\n\n( these words push the execution tokens for various special cases for decompilation )\n: get-branch [ find branch ] literal ;\n: get-?branch [ find ?branch ] literal ;\n: get-original-exit [ find _exit ] literal ;\n: get-quote [ find ' ] literal ;\n\n( @todo replace 2- nos1+ nos1+ with appropriate word, like the string word \nthat increments a string by an amount, but that operates on CELLS )\n: branch-increment ( addr branch -- increment : calculate decompile increment for \"branch\" )\n\t1+ dup negative? \n\tif \n\t\tover cr . [char] : emit space . cr 2 \n\telse \n\t\t2dup 2- nos1+ nos1+ dump \n\tthen ;\n\n( these words take a code field to a primitive they implement, decompile it\nand any data belonging to that operation, and push a number to increment the\ndecompilers code stream pointer by )\n\n: decompile-literal ( code -- increment )\n\t1+ ? \" literal\" 2 ;\n\n: decompile-branch ( code -- increment )\n\tdark red foreground color\n\t1+ ? \" branch \" dup 1+ @ branch-increment ;\n\n: decompile-quote ( code -- increment )\n\tdark green foreground color\n\tdup\n\t[char] ' emit 1+ @ word-printer 2 reset-color ;\n\n: decompile-?branch ( code -- increment )\n\t1+ ? \" ?branch\" 2 ;\n\n: decompile-exit ( code -- 0 )\n\t\" _exit\" cr \" End of word: \" . 0 ;\n\n( The decompile word expects a pointer to the code field of a word, it\ndecompiles a words code field, it needs a lot of work however.\nThere are several complications to implementing this decompile\nfunction.\n\n\t' The next cell should be pushed\n\t:noname This has a marker before its code field of -1 which\n\t\t cannot occur normally, this is handled in word-printer\n\tbranch branches are used to skip over data, but also for\n\t\t some branch constructs, any data in between can only\n\t\t be printed out generally speaking\n\texit There are two definitions of exit, the one used in\n\t\t ';' and the one everything else uses, this is used\n\t\t to determine the actual end of the word\n\tliterals Literals can be distinguished by their low value,\n\t\t which cannot possibly be a word with a name, the\n\t\t next field is the actual literal\n\nOf special difficult is processing 'if' 'else' 'then' statements,\nthis will require keeping track of '?branch'.\n\nAlso of note, a number greater than \"here\" must be data )\n\n: decompile ( code-pointer -- code-pointer increment|0 : )\n\t.d [char] : emit space dup @\n\tcase\n\t\tdolit of drup decompile-literal cr endof\n\t\tget-branch of drup decompile-branch endof\n\t\tget-quote of drup decompile-quote cr endof\n\t\tget-?branch of drup decompile-?branch cr endof\n\t\tget-original-exit of drup decompile-exit endof\n\t\tword-printer 1 cr\n\tendcase reset-color ;\n\n: decompiler ( code-field-ptr -- : decompile a word in its entirety )\n\tbegin decompile over + tuck = until drop ;\n\nhide{\n\tword-printer get-branch get-?branch get-original-exit \n\tget-quote branch-increment decompile-literal \n\tdecompile-branch decompile-?branch decompile-quote\n\tdecompile-exit\n}hide\n\n( these words expect a pointer to the PWD field of a word )\n: see.name \" name: \" name print cr ;\n: see.start \" word start: \" name chars . cr ;\n: see.previous \" previous word: \" @ . cr ;\n: see.immediate \" immediate: \" compiling? swap drop not TrueFalse cr ;\n: see.instruction \" instruction: \" xt-instruction . cr ;\n: see.defined \" defined: \" defined-word? TrueFalse cr ;\n\n: see.header ( PWD -- is-immediate-word? )\n\tdup see.name\n\tdup see.start\n\tdup see.previous\n\tdup see.immediate\n\tdup see.instruction ( @todo look up instruction name )\n\tsee.defined ;\n\n( @todo This does not work for all words, so needs fixing. \n Specifically: \n\t2variable\n\t2constant\n\ttable\n\tconstant\n\tvariable\n\tarray \nWhich are all complex CREATE words\n\nA good way to test decompilation is with the following Unix pipe: \n\n\t.\/forth -f forth.fth -e words \n\t\t| sed 's\/ \/ see \/g' \n\t\t| .\/forth -t forth.fth &> decompiled.log\n)\n\n( @todo refactor into word that takes a PWD pointer and one that attempts to parse\/find name )\n: see ( c\" xxx\" -- : decompile the next word in the input stream )\n\tfind\n\tdup 0= if -32 throw then\n\t-1 cells + ( move to PWD field )\n\tdup see.header\n\tdup defined-word?\n\tif ( decompile if a compiled word )\n\t\t2 cells + ( move to code field )\n\t\t\" code field:\" cr\n\t\tdecompiler\n\telse ( the instruction describes the word if it is not a compiled word )\n\t\tdup 1 cells + @ instruction-mask and doconst = if ( special case for constants )\n\t\t\t\" constant: \" 2 cells + @ .\n\t\telse\n\t\t\tdrop\n\t\tthen\n\tthen cr ;\n\nhide{ \n\tsee.header see.name see.start see.previous see.immediate \n\tsee.instruction defined-word? see.defined\n}hide\n\n( These help messages could be moved to blocks, the blocks could then\nbe loaded from disk and printed instead of defining the help here,\nthis would allow much larger help )\n\n: help ( -- : print out a short help message )\n\tpage\n\tkey drop\n\" Welcome to Forth, an imperative stack based language. It is both a low\nlevel and a high level language, with a very small memory footprint. Most\nof Forth is defined as a combination of various primitives.\n\nA short description of the available function (or Forth words) follows,\nwords marked (1) are immediate and cannot be used in command mode, words\nmarked with (2) define new words. Words marked with (3) have both command\nand compile functionality.\n\n\"\nmore \" Some of the built in words that accessible are:\n\n(1,2)\t: define a new word, switching to compile mode\n\timmediate make latest defined word immediate\n\tread read in a word, execute in command mode else compile\n\t@ ! fetch, store\n\tc@ c! character based fetch and store\n\t- + * \/ standard arithmetic operations,\n\tand or xor invert standard bitwise operations\n\tlshift rshift left and right bit shift\n\tu< u> < > = comparison predicates\n\texit exit from a word\n\temit print character from top of stack\n\tkey get a character from input\n\tr> >r pop a value from or to the return stack\n\tfind find a word in the dictionary and push the location\n\t' store the address of the following word on the stack\n\t, write the top of the stack to the dictionary\n\tswap swap first two values on the stack\n\tdup duplicate the top of the stack\n\tdrop pop and drop a value\n\tover copy the second stack value over the first\n\t. pop the top of the stack and print it\n\" \nmore \" \n\tprint print a NUL terminated string at a character address\n\tdepth get the current stack depth\n\tclock get the time since execution start in milliseconds\n\tevaluate evaluate a string\n\tsystem execute a system command\n\tclose-file close a file handle\n\topen-file open a file handle\n\tdelete-file delete a file off disk given a string\n\tread-file read in characters from a file\n\twrite-file write characters to a file\n\tfile-position get the file offset\n\treposition-file reposition the file pointer\n\tflush-file flush a file to disk\n\trename-file rename a file on disk\n \"\n\nmore \" All of the other words in the interpreter are built from these\nprimitive words. A few examples:\n\n(1)\tif...else...then FORTH branching construct\n(1)\tbegin...until loop until top of stack is non zero\n(1)\tbegin...again infinite loop\n(1)\tdo...loop FORTH looping construct\n(2,3)\tcreate create a new word that pushes its location\n(1)\tdoes> declare a created words run time behaviour\n(1,2)\tvariable declare variable with initial value from top of stack\n(1,2)\tconstant declare a constant, taken from top of stack\n(1,2)\tarray declare an array with size taken from top of stack\n(1)\t; terminate a word definition and return to command mode\n\twords print out a list of all the defined words\n\thelp this help message\n\tdump print out memory contents starting at an address\n\tregisters print out the contents of the registers\n\tsee decompile a word, viewing what words compose it\n\t.s print out the contents of the stack\n\n\"\n\nmore \" Some more advanced words:\n\n\there push the dictionary pointer\n\th push the address of the dictionary pointer\n\tr push the return stack pointer\n\tallot allocate space in the dictionary\n(1)\t[ switch to command mode\n\t] switch to compile mode\n\t:: compile ':' into the dictionary\n\n\" more \"\nFor more information either consult the manual pages forth(1) and libforth(1)\nor consult the following sources:\n\n\thttps:\/\/github.com\/howerj\/libforth\n\thttp:\/\/work.anapnea.net\/html\/html\/projects.html\n\nAnd for a larger tutorial:\n\n\thttps:\/\/github.com\/howerj\/libforth\/blob\/master\/readme.md\n\nFor resources on Forth:\n\n\thttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\thttps:\/\/rwmj.wordpress.com\/2010\/08\/07\/jonesforth-git-repository\/\n\n -- end --\n\" cr\n;\n\n( ==================== Debugging info ========================= )\n\n( ==================== Files ================================== )\n\n( @todo implement the other file access methods in terms of the\n built in ones [see http:\/\/forth.sourceforge.net\/std\/dpans\/dpans11.htm]\n @todo read-line and write-line need their flag and ior setting correctly\n\n\tFILE-SIZE [ use file-positions ]\n\n Also of note:\t\n * Source ID needs extending. )\n\n: read-char ( c-addr fileid -- ior : read a char )\n\t1 swap read-file 0<> swap 1 <> or ;\n\n0 variable x\n\n: getchar ( fileid -- char ior )\n\tx chars> swap read-char x chars> c@ swap ;\n\n: write-char ( c-addr fileid -- ior : write a char )\n\t1 swap write-file 0<> swap 1 <> or ;\n\n: putchar ( char fileid -- ior )\n\tswap x chars> c! x chars> swap write-char ;\n\nhide{ x }hide\n\n: rewind-file ( file-id -- : rewind a file to the beginning )\n\t0 reposition-file throw ;\n\n: read-line ( c-addr u1 fileid -- u2 flag ior : read in a line of text )\n\t-rot bounds\n\tdo\n\t\tdup i swap read-char drop\n\t\ti c@ nl = if drop i 0 0 leave then\n\tloop drop ;\n\n: write-line ( c-addr u fileid -- u2 flag ior : write a line of text )\n\t-rot bounds\n\tdo\n\t\tdup i swap write-char drop\n\t\ti c@ nl = if drop i 0 0 leave then\n\tloop ;\n\n: resize-file ( ud fileid -- ior : attempt to resize a file )\n\t( There is no portable way to truncate a file :C )\n\t2drop -1 ( -1 to indicate failure ) ;\n\n: create-file ( c-addr u fam -- fileid ior )\n\t>r 2dup w\/o open-file throw close-file throw\n\tr> open-file ;\n\n: include-file ( file-id -- : evaluate a file ) \n\tdup >r 0 1 evaluator r> close-file throw throw ;\n\n: included ( c-addr u -- : attempt to open up a name file and evaluate it )\n\tr\/o open-file throw \n\tinclude-file ;\n\n: include ( c\" ccc\" -- : attempt to evaluate a named file )\n\t( @bug requires trailing space, should use parse-name )\n\tbl word count included ;\n\n: bin ( fam1 -- fam2 : modify a file access method to be binary not line oriented ) \n\t( Do nothing, all file access methods are binary )\n\t;\n\n( ==================== Files ================================== )\n\n( ==================== Matcher ================================ )\n( The following section implements a very simple regular expression\nengine, which expects an ASCIIZ Forth string. It is translated from C\ncode and performs an identical function.\n\nThe regular expression language is as follows:\n\n\tc\tmatch a literal character\n\t.\tmatch any character\n\t*\tmatch any characters\n\nThe \"*\" operator performs the same function as \".*\" does in most\nother regular expression engines. Most other regular expression engines\nalso do not anchor their selections to the beginning and the end of\nthe string to match, instead using the operators '^' and '$' to do\nso, to emulate this behavior '*' can be added as either a suffix,\nor a prefix, or both, to the matching expression.\n\nAs an example \"*, World!\" matches both \"Hello, World!\" and\n\"Good bye, cruel World!\". \"Hello, ....\" matches \"Hello, Bill\"\nand \"Hello, Fred\" but not \"Hello, Tim\" as there are two few\ncharacters in the last string.\n\n@todo make a matcher that expects a Forth string, which do not\nhave to be NUL terminated\n)\n\n\\ Translated from http:\/\/c-faq.com\/lib\/regex.html\n\\ int match(char *pat, char *str)\n\\ {\n\\ \tswitch(*pat) {\n\\ \tcase '\\0': return !*str;\n\\ \tcase '*': return match(pat+1, str) || *str && match(pat, str+1);\n\\ \tcase '.': return *str && match(pat+1, str+1);\n\\ \tdefault: return *pat == *str && match(pat+1, str+1);\n\\ \t}\n\\ }\n\n: *pat ( regex -- regex char : grab next character of pattern ) \n\tdup c@ ;\n\n: *str ( string regex -- string regex char : grab next character string to match )\n\tover c@ ;\n\n: pass ( c-addr1 c-addr2 -- bool : pass condition, characters matched ) \n\t2drop 1 ;\n\n: reject ( c-addr1 c-addr2 -- bool : fail condition, character not matched ) \n\t2drop 0 ;\n\n: *pat==*str ( c-addr1 c-addr2 -- c-addr1 c-addr2 bool )\n\t2dup c@ swap c@ = ;\n\n: ++ ( u1 u2 u3 u4 -- u1+u3 u2+u4 : not quite d+ [does no carry] )\n\tswap >r + swap r> + swap ;\n\ndefer matcher\n\n: advance ( string regex char -- bool : advance both regex and string )\n\tif 1 1 ++ matcher else reject then ;\n\n: advance-string ( string regex char -- bool : advance only the string )\n\tif 1 0 ++ matcher else reject then ;\n\n: advance-regex ( string regex -- bool : advance matching )\n\t2dup 0 1 ++ matcher if pass else *str advance-string then ;\n\n: match ( string regex -- bool : match a ASCIIZ pattern against an ASCIIZ string )\n\t( @todo Add limits and accept two Forth strings, making sure they are both\n\t ASCIIZ strings as well \n\t @warning This uses a non-standards compliant version of case! )\n\t*pat\n\tcase\n\t\t 0 of drop drop c@ not exit endof\n\t\t[char] * of drop advance-regex exit endof\n\t\t[char] . of drop *str advance exit endof\n\t\t drop *pat==*str advance exit\n\tendcase ;\n\nmatcher is match\n\nhide{ \n\t*str *pat *pat==*str pass reject advance \n\tadvance-string advance-regex matcher ++ \n}hide\n\n( ==================== Matcher ================================ )\n\n\n( ==================== Cons Cells ============================= )\n\n( From http:\/\/sametwice.com\/cons.fs, this could be improved if the optional\nmemory allocation words were added to the interpreter. This provides\na simple \"cons cell\" data structure. There is currently no way to\nfree allocated cells )\n\n: car! ( value cons-addr -- : store a value in the car cell of a cons cell ) \n\t! ;\n\n: cdr! ( value cons-addr -- : store a value in the cdr cell of a cons cell )\n\tcell+ ! ;\n\n: car@ ( cons-addr -- car-val : retrieve car value from cons cell )\n\t@ ;\n\n: cdr@ ( cons-addr -- cdr-val : retrieve cdr value from cons cell )\n\tcell+ @ ;\n\n: cons ( car-val cdr-val -- cons-addr : allocate a new cons cell )\n\tswap here >r , , r> ;\n\n: cons0 0 0 cons ;\n\nmarker cleanup\n77 987 cons constant x\nT{ x car@ -> 77 }T\nT{ x cdr@ -> 987 }T\nT{ 55 x cdr! x car@ x cdr@ -> 77 55 }T\nT{ 44 x car! x car@ x cdr@ -> 44 55 }T\ncleanup\n\n( ==================== Cons Cells ============================= )\n\n( ==================== Miscellaneous ========================== )\n\n: license ( -- : print out license information )\n\" \nThe MIT License (MIT)\n\nCopyright (c) 2016, 2017 Richard James Howe\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the 'Software'),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand\/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\nTHE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\nOTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\nARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE. \n\n\" \n;\n\n( ==================== Version information =================== )\n\n4 constant version\n\n( ==================== Version information =================== )\n\n( ==================== Core utilities ======================== )\n( Read the header of a core file and process it, printing the\nresults out )\n\n8 constant header-size ( size of Forth core file header )\n8 constant size-field-size ( the size in bytes of the size field in the core file )\n0 variable core-file ( core fileid we are reading in )\n0 variable core-cell-size ( cell size of Forth core )\n0 variable core-version ( version of core file )\n0 variable core-endianess ( endianess of core we are reading in )\n\n( save space to read in header )\ncreate header header-size chars allot\n: cheader ( -- c-addr : header char address )\n\theader chars> ;\ncreate size-field size-field-size chars allot\n: csize-field ( -- c-addr : address of place size field is stored in )\n\tsize-field chars> ;\n\n0\nenum header-magic0 ( magic number 0 : FF ) \nenum header-magic1 ( magic number 1 : '4' )\nenum header-magic2 ( magic number 2 : 'T' )\nenum header-magic3 ( magic number 3 : 'H' )\nenum header-cell-size ( size of a forth cell, either 2, 4 or 8 bytes )\nenum header-version ( version of the forth core )\nenum header-endianess ( endianess of the core )\nenum header-log2size ( binary logarithm of the core size )\n\n: cleanup ( -- : cleanup before abort )\n\tcore-file @ ?dup 0<> if close-file drop then ;\n\n: invalid-header ( bool -- : abort if header is invalid )\n\t<> if cleanup abort\" invalid header\" then ;\n\n: save-core-cell-size ( char -- : save the core file cell size, checking if it is valid )\n\tcore-cell-size !\n\t\" cell size:\" tab\n\tcore-cell-size @ 2 = if 2 . cr exit then\n\tcore-cell-size @ 4 = if 4 . cr exit then\n\tcore-cell-size @ 8 = if 8 . cr exit then\n\tcleanup core-cell-size @ . abort\" : invalid cell size\" ;\n\n: check-version-compatibility ( char -- : checks the version compatibility of the core file ) \n\tcore-version !\n\tcore-version @ version = if \" version: \" version . cr exit then\n\tcleanup core-version @ . abort\" : unknown version number\" ;\n\n: save-endianess ( char -- : save the endianess, checking if it is valid )\n\tcore-endianess !\n\t\" endianess:\" tab\n\tcore-endianess @ 0 = if \" big\" cr exit then\n\tcore-endianess @ 1 = if \" little\" cr exit then\n\tcleanup core-endianess @ . abort\" invalid endianess\" then ;\n\n: read-or-abort ( c-addr size fileid -- : )\n\tover >r read-file \n\t 0<> if cleanup abort\" file read failed\" then\n\tr> <> if cleanup abort\" header too small\" then ;\n\n: header? ( -- : print out header information )\n\tcheader header-size core-file @ read-or-abort\n\t( \" raw header:\" header 2 dump )\n\tcheader header-magic0 + c@ 255 invalid-header\n\tcheader header-magic1 + c@ [char] 4 invalid-header\n\tcheader header-magic2 + c@ [char] T invalid-header\n\tcheader header-magic3 + c@ [char] H invalid-header\n\tcheader header-cell-size + c@ save-core-cell-size\n\tcheader header-version + c@ check-version-compatibility\n\tcheader header-endianess + c@ save-endianess\n\t\" valid header\" cr ;\n\n: size? ( -- : print out core file size )\n\t\" size: \" cheader header-log2size + c@ 1 swap lshift . cr ;\n\n: core ( c-addr u -- : analyze a Forth core file from disk given its file name )\n\t2dup \" core file:\" tab type cr\n\tr\/o open-file throw core-file ! \n\theader?\n\tsize?\n\tcore-file @ close-file drop ;\n\n( s\" forth.core\" core )\n\nhide{ \nheader-size header? \nheader-magic0 header-magic1 header-magic2 header-magic3\nheader-version header-cell-size header-endianess header-log2size\nheader \ncore-file save-core-cell-size check-version-compatibility\ncore-cell-size cheader\ncore-endianess core-version save-endianess invalid-header\ncleanup size-field csize-field size-field-size\nread-or-abort size?\n}hide\n\n( ==================== Core utilities ======================== )\n\n( ==================== RLE =================================== )\n\n( These set of words implement Run Length Compression, which can be used for\nsaving space when compressing the core files generated by Forth programs, which\ncontain mostly runs of NUL characters. \n\nThe format of the encoded data is quite simple, there is a command byte\nfollowed by data. The command byte encodes only two commands; encode a run of\nliteral data and repeat the next character. \n\nIf the command byte is greater than X the command is a run of characters, \nX is then subtracted from the command byte and this is the number of \ncharacters that is to be copied verbatim when decompressing.\n\nIf the command byte is less than or equal to X then this number, plus one, is \nused to repeat the next data byte in the input stream.\n\nX is 128 for this application, but could be adjusted for better compression\ndepending on what the data looks like. \n\nExample:\n\t\n\t2 'a' 130 'b' 'c' 3 'd'\n\nBecomes:\n\n\taabcddd \n\nExample usage:\n\n\t: extract\n\t\tc\" forth.core\" w\/o open-file throw\n\t\tc\" forth.core.rle\" r\/o open-file throw\n\t\tdecompress ;\n\textract\n\n@note file redirection could be used for the input as well\n@todo compression, and reading\/writing to strings )\n\n: cpad pad chars> ;\n\n0 variable out\n128 constant run-length\n\n: next.char ( file-id -- char : read in a single character )\n\t>r cpad r> read-char throw cpad c@ ;\n\n: repeated ( count file-id -- : repeat a character count times )\n\tnext.char swap 0 do dup emit loop drop ;\n\n: literals ( count file-id -- : extract a literal run )\n\t>r cpad swap r> read-file throw cpad swap type ;\n\n: command ( file-id -- : process an RLE command )\n\tdup \n\t>r next.char\n\tdup run-length u> \n\tif \n\t\trun-length - r> literals \n\telse \n\t\t1+ r> repeated \n\tthen ;\n\n: redirect ( file-id-out -- : save current output pointer, redirect to output )\n\t`fout @ out ! `fout ! ;\n\n: restore ( -- : restore previous output pointer )\n\tout @ `fout ! ;\n\n: decompress ( file-id-out file-id-in -- : decompress an RLE encoded file )\n\tswap\n\tredirect\n\tbegin dup ' command catch until ( process commands until input exhausted )\n\t2drop ( drop twice because catch will restore stack before 'command' )\n\trestore ; ( restore input stream )\n\nhide{ literals repeated next.char out run-length command }hide\n\n( ==================== RLE =================================== )\n\n( ==================== Generate C Core file ================== )\n( The word core2c reads in a core file and turns it into a C file which \ncan then be compiled into the forth interpreter in a bootstrapping like\nprocess.\n\nUsage:\n c\" forth.core\" c\" core.gen.c\" core2c )\n\n0 variable count\n\n: wbyte ( u char -- : write a byte )\n\tpnum drop\n\t[char] , emit\n\t16 mod 0= if cr then ;\n\n: advance ( char -- : advance counter and print byte )\n\tcount 1+! count @ swap wbyte ;\n\n: hexify ( fileid -- fileid : turn core file into C numbers in array )\n\t0 count !\n\tbegin dup getchar 0= while advance repeat drop ;\n\n: quote ( -- : emit a quote character )\n\t[char] \" emit ;\n\n: core2c ( c-addr u c-addr u -- ior : generate a C file from a core file )\n\tw\/o open-file throw >r\n\tr\/o open-file ?dup-if r> close-file throw throw then\n\tr> redirect\n\t\" #include \" quote \" libforth.h\" quote cr\n\t\" unsigned char forth_core_data[] = {\" cr\n\thexify \n\t\" };\" cr\n\t\" forth_cell_t forth_core_size = \" count @ . \" ;\" cr cr\n\tclose-file\n\t`fout @ close-file \n\trestore or ;\n\nhide{ wbyte hexify count quote advance }hide\n \n( ==================== Generate C Core file ================== )\n\n: wc ( c-addr u -- u : count the bytes in a file )\n\tr\/o open-file throw\n\t0 swap\n\tbegin dup getchar nip 0= while nos1+ repeat close-file throw ;\n\n( ==================== Save Core file ======================== )\n\n( The following functionality allows the user to save the core file\nfrom within the running interpreter. The Forth core files have a very simple\nformat which means the words for doing this do not have to be too long, a header\nhas to emitted with a few calculated values and then the contents of the\nForths memory after this )\n\n( This write the header out to the current output device, this\nwill be redirected to a file )\n: header ( -- : write the header out )\n\t0xff emit ( magic 0 )\n\t[char] 4 emit ( magic 1 )\n\t[char] T emit ( magic 2 )\n\t[char] H emit ( magic 3 )\n\tsize emit ( cell size in bytes )\n\tversion emit ( core version )\n\tendian not emit ( endianess )\n\tmax-core log2 emit ; ( size field )\n\n: data ( -- : write the data out )\n\t0 max-core chars> `fout @ write-file throw drop ;\n\n: encore ( -- : write the core file out )\n\theader\n\tdata ;\n\n: save-core ( c-addr u -- : save core file or throw error ) \n\tw\/o open-file throw dup\n\tredirect \n\t\t' encore catch swap close-file throw \n\trestore ;\n\n( The following code illustrates an example of setting up a\nForth core file to execute a word when the core file is loaded.\nIn the example the word \"hello-world\" will be executed, which will\nalso quit the interpreter:\n\n\t\\ Only works for immediate words for now, we define\n\t\\ the word we wish to be executed when the forth core\n\t\\ is loaded\n\t: hello-world immediate\n\t\t\" Hello, World!\" cr bye ;\n\n\t\\ The following sets the starting word to our newly\n\t\\ defined word:\n\tfind hello-world cfa start!\n\n\t\\ Now we can save the core file out:\n\ts\" forth.core\" save-core \n\nThis can be used, in conjunction with aspects of the build system,\nto produce a standalone executable that will run only a single Forth\nword. )\n\nhide{ redirect restore data encore header }hide\n\n( ==================== Save Core file ======================== )\n\n( ==================== Hex dump ============================== )\n\n( @todo hexdump can read in too many characters and it does not\nprint out the correct address\n@todo utilities for easy redirecting of file input\/output )\n: input >r cpad 128 r> read-file ; ( file-id -- u 0 | error )\n: clean cpad 128 0 fill ; ( -- )\n: cdump cpad chars swap aligned chars dump ; ( u -- )\n: hexdump ( file-id -- : [hex]dump a file to the screen )\n\tdup \n\tclean\n\tinput if 2drop exit then\n\t?dup-if cdump else drop exit then\n\ttail ; \n\nhide{ cpad clean cdump input }hide\n\n( ==================== Hex dump ============================== )\n\n( ==================== Date ================================== )\n\n( Rather annoyingly months are start from 1 but weekdays from 0 )\n\n: >month ( month -- )\n\tcase\n\t\t 1 of \" Jan \" endof\n\t\t 2 of \" Feb \" endof\n\t\t 3 of \" Mar \" endof\n\t\t 4 of \" Apr \" endof\n\t\t 5 of \" May \" endof\n\t\t 6 of \" Jun \" endof\n\t\t 7 of \" Jul \" endof\n\t\t 8 of \" Aug \" endof\n\t\t 9 of \" Sep \" endof\n\t\t10 of \" Oct \" endof\n\t\t11 of \" Nov \" endof\n\t\t12 of \" Dec \" endof\n\tendcase drop ;\n\n: .day ( day -- : add ordinal to day )\n\t10 mod\n\tcase\n\t\t1 of \" st \" drop exit endof\n\t\t2 of \" nd \" drop exit endof\n\t\t3 of \" rd \" drop exit endof\n\t\t\" th \" \n\tendcase drop ;\n\n: >day ( day -- : add ordinal to day of month )\n\tdup u.\n\tdup 1 10 within if .day exit then\n\tdup 10 20 within if \" th\" drop exit then\n\t.day ;\n\n: >weekday ( weekday -- : print the weekday )\n\tcase\n\t\t0 of \" Sun \" endof\n\t\t1 of \" Mon \" endof\n\t\t2 of \" Tue \" endof\n\t\t3 of \" Wed \" endof\n\t\t4 of \" Thu \" endof\n\t\t5 of \" Fri \" endof\n\t\t6 of \" Sat \" endof\n\tendcase drop ;\n\n: padded ( u -- : print out a run of zero characters )\n\t0 do [char] 0 emit loop ;\n\n: 0u. ( u -- : print a zero padded number )\n\tdup 10 u< if 1 padded then u. space ;\n\n: .date ( date -- : print the date )\n\tif \" DST \" else \" GMT \" then \n\tdrop ( no need for days of year)\n\t>weekday\n\t. ( year ) \n\t>month \n\t>day \n\t0u. ( hour )\n\t0u. ( minute )\n\t0u. ( second ) cr ;\n\n: time&date ( -- second minute hour day month year )\n\tdate\n\t3drop ;\n\nhide{ 0u. >weekday .day >day >month padded }hide\n\n( ==================== Date ================================== )\n\n\n( ==================== CRC =================================== )\n\n( @todo implement all common CRC algorithms, but only if\nthe word size allows it [ie. 32 bit CRCs on a 32 or 64 bit\nmachine, 64 bit CRCs on a 64 bit machine] )\n\n( Make a word to limit arithmetic to a 16-bit value )\nsize 2 = [if] \n\t: limit immediate ; ( do nothing, no need to limit )\n[else] \n\t: limit 0xffff and ; ( limit to 16-bit value )\n[then]\n\n: ccitt ( crc c-addr -- crc : calculate polynomial 0x1021 AKA \"x16 + x12 + x5 + 1\" )\n\tc@ ( get char )\n\tlimit over 256\/ xor ( crc x )\n\tdup 4 rshift xor ( crc x )\n\tdup 5 lshift limit xor ( crc x )\n\tdup 12 lshift limit xor ( crc x )\n\tswap 8 lshift limit xor ; ( crc )\n\n( see http:\/\/stackoverflow.com\/questions\/10564491\/function-to-calculate-a-crc16-checksum\n and https:\/\/www.lammertbies.nl\/comm\/info\/crc-calculation.html )\n: crc16-ccitt ( c-addr u -- u )\n\t0xFFFF -rot\n\t['] ccitt\n\tforeach-char ;\nhide{ limit ccitt }hide\n\n( ==================== CRC =================================== )\n\n( ==================== Rational Data Type ==================== )\n( This word set allows the manipulation of a rational data type,\nwhich are basically fractions. This allows numbers like 1\/3 to\nbe represented without any loss of precision. Conversion to and\nfrom the data type to an integer type is trivial, although \ninformation can be lost during the conversion.\n\nTo convert to a rational, use 'dup', to convert from a rational,\nuse '\/'. \n\nThe denominator is the first number on the stack, the numerator the\nsecond number. Fractions are simplified after any rational operation,\nand all rational words can accept unsimplified arguments. For example\nthe fraction 1\/3 can be represented as 6\/18, they are equivalent, so\nthe rational equality operator \"=rat\" can accept both and returns\ntrue.\n\n\tT{ 1 3 6 18 =rat -> 1 }T\n\nSee: https:\/\/en.wikipedia.org\/wiki\/Rational_data_type \nFor more information.\n\nThis set of words use two cells to represent a fraction, however\na single cell could be used, with the numerator and the denominator\nstored in upper and lower half of a single cell. )\n\n: simplify ( a b -- a\/gcd{a,b} b\/gcd{a\/b} : simplify a rational )\n 2dup\n gcd\n tuck\n \/\n -rot\n \/\n swap ; \\ ? check this\n\n: crossmultiply ( a b c d -- a*d b*d c*b d*b )\n rot ( a c d b )\n 2dup ( a c d b d b )\n * ( a c d b d*b )\n >r ( a c d b , d*b )\n rot ( a d b c , d*b )\n * ( a d b*c , d*b )\n -rot ( b*c a d , d*b )\n * ( b*c a*d , d*b )\n r> ( b*c a*d d*b )\n tuck ( b*c d*b a*d d*b )\n 2swap ; ( done! )\n\n: *rat ( a\/b c\/d -- a\/b : multiply two rationals together )\n rot * -rot * swap simplify ;\n\n: \/rat ( a\/b c\/d -- a\/b : divide one rational by another )\n swap *rat ;\n\n: +rat ( a\/b c\/d -- a\/b : add two rationals together )\n crossmultiply\n rot\n drop ( or check if equal, if not there is an error )\n -rot\n +\n swap\n simplify ;\n\n: -rat ( a\/b c\/d -- a\/b : subtract one rational from another )\n crossmultiply \n rot\n drop ( or check if equal, if not there is an error )\n -rot\n -\n swap\n simplify ;\n\n: .rat ( a\/b -- : print out a rational number )\n simplify swap . [char] \/ emit space . ;\n\n: =rat ( a\/b c\/d -- bool : rational equal )\n crossmultiply rot = -rot = = ;\n\n: >rat ( a\/b c\/d -- bool : rational greater than )\n crossmultiply rot 2drop > ;\n\n: <=rat ( a\/b c\/d -- bool : rational less than or equal to )\n\t>rat not ;\n\n: =rat ( a\/b c\/d -- bool : rational greater or equal to )\n\t0 block number stored in buf)\n\n: invalid? ( n -- : throw if block number is invalid )\n\t0= if -35 throw then ;\n\n: update ( -- : mark currently loaded block buffer as dirty )\n\ttrue dirty ! ;\n\n: updated?\n\tdirty @ ;\n\n: block.name ( n -- c-addr u : make a block name )\n\tc\" .blk\" <# holds #s #> rot drop ;\n\n( @warning this will not work if we do not have permission,\nor in various other cases where we cannot open the file, for\nwhatever reason )\n: file-exists ( c-addr u : does a file exist? )\n\tr\/o open-file if drop 0 else close-file throw 1 then ;\n\n: buffer.exists ( n -- bool : does a block buffer exist on disk? )\n\tblock.name file-exists ;\n\n( @note block.write and block.read do not check if they have\nwrote or read in 1024 bytes, nor do they check that they can\nonly write or read 1024 and not a byte more )\n\n: block.read ( file-id -- file-id : read in buffer )\n\tdup >r buf r> read-file nip if close-file -33 throw then ;\n\n: block.write ( file-id -- file-id : write out buffer )\n\tdup >r buf r> write-file nip if close-file -34 throw then ;\n\n: block.open ( n fam -- file-id )\n\t>r block.name r> open-file throw ;\n\n: save-buffers \n\tblk @ 0= if exit then ( not a valid block number, exit )\n\tdirty @ not if exit then ( not dirty, no need to save )\n\tblk @ w\/o block.open ( open file backing block buffer )\n\tblock.write ( write it out )\n\tclose-file throw ( close it )\n\tfalse dirty ! ; ( but only mark it clean if everything succeeded )\n\n: empty-buffers ( -- : deallocate any saved buffers )\n\t0 blk ! ;\n\n: flush ( -- : perform save-buffers followed by empty-buffers )\n\tsave-buffers\n\tempty-buffers ;\n\n( Block is a complex word that does a lot, although it has a simple\ninterface. It does the following given a block number:\n\n1. Checks the provided block buffer number to make sure it is valid\n2. If the block is already loaded from the disk, then return the\naddress of the block buffer it is loaded into.\n3. If not, it checks to see if the currently loaded block buffer is\ndirty, if it is then it flushes the buffer to disk.\n4. If the block buffer does not exists on disk then it creates it.\n5. It then stores the block number in blk and returns an address to\nthe block buffer. )\n: block ( n -- c-addr : load a block )\n\tdup invalid? \n\tdup blk @ = if drop buf drop exit then\n\tflush\n\tdup buffer.exists if ( if the buffer exits on disk load it in )\n\t\tdup r\/o block.open \n\t\tblock.read \n\t\tclose-file throw \n\telse ( else it does not exist )\n\t\tbuf 0 fill ( clean the buffer )\n\tthen \n\tblk ! ( save the block number )\n\tbuf drop ;\n\n: buffer block ;\n\n( @warning uses hack, block buffer is NUL terminated, and evaluate requires\na NUL terminated string, evaluate checks that the last character is NUL, \nhence the 1+ )\n: load ( n -- : load and execute a block )\n\tblock b\/buf 1+ evaluate throw ;\n\nhide{ \n\tblock.name invalid? block.write \n\tblock.read buffer.exists block.open dirty\n}hide\n\n( ==================== Block Layer =========================== )\n\n( ==================== List ================================== )\n1 variable fancy-list\n0 variable scr\n64 constant c\/l ( characters per line )\n\n: line.number ( n -- : print line number )\n\tfancy-list @ if\n\t\tdup 10 < (base) 10 = and if space then ( leading space: works up to c\/l = 99)\n\t\t. [char] | emit ( print \" line-number : \")\n\telse\n\t\tdrop\n\tthen ;\n\n: line ( c-addr -- c-addr u : given a line number, display that line )\n\tdup \n\tline.number ( display line number )\n\tc\/l * + ( calculate offset )\n\tc\/l ; ( add line length )\n\n: list.end\n\tfancy-list @ not if exit then\n\t[char] | emit ;\n\n: list.type ( c-addr u -- : list a block )\n\tb\/buf c\/l \/ 0 do dup i line type list.end cr loop drop ;\n\n: list.border \" +---|---\" ;\n\n: list.box\n\tfancy-list @ not if exit then\n\t4 spaces\n\t8 0 do list.border loop cr ;\n\n: list ( n -- : display a block number and update scr )\n\tdup >r block r> scr ! list.box list.type list.box ;\n\n: thru\n\tkey drop\n\t1+ swap do i list more loop ;\n\n: make-blocks ( n1 n2 -- : make blocks on disk from n1 to n2 inclusive )\n\t1+ swap do i block b\/buf bl fill update loop save-buffers ;\n\nhide{ buf line line.number list.type fancy-list (base) }hide\n\n( ==================== List ================================== )\n\n( ==================== Signal Handling ======================= )\n( Signal handling at the moment is quite primitive. When a signal\noccurs it has to be explicitly tested for by the programmer, this\ncould be improved on quite a bit. One way of doing this would be\nto check for signals in the virtual machine and cause a THROW\nfrom within it. )\n\n( signals are biased to fall outside the range of the error numbers\ndefined in the ANS Forth standard. )\n-512 constant signal-bias \n\n: signal ( -- signal\/0 : push the results of the signal register ) \n\t`signal @\n \t0 `signal ! ;\n\n( ==================== Signal Handling ======================= )\n\n( Looking at most Forths dictionary with \"words\" command they tend\nto have a lot of words that do not mean anything but to the implementers\nof that specific Forth, here we clean up as many non standard words as\npossible. )\nhide{ \n do-string ')' alignment-bits \n dictionary-start hidden-mask instruction-mask immediate-mask compiling?\n compile-bit\n max-core dolist doconst x x! x@ \n max-string-length \n _exit\n pnum evaluator \n TrueFalse >instruction \n xt-instruction\n `state\n `source-id `sin `sidx `slen `start-address `fin `fout `stdin\n `stdout `stderr `argc `argv `debug `invalid `top `instruction\n `stack-size `error-handler `x `handler _emit `signal \n}hide\n\n( \n## Forth To List\n\nThe following is a To-Do list for the Forth code itself, along with any\nother ideas.\n\n* FORTH, VOCABULARY\n* \"Value\", \"To\", \"Is\"\n* Double cell words \n* The interpreter should use character based addresses, instead of\nword based, and use values that are actual valid pointers, this\nwill allow easier interaction with the world outside the virtual machine\n* common words and actions should be factored out to simplify\ndefinitions of other words, their standards compliant version found\nif any\n* A soft floating point library would be useful which could be used\nto optionally implement floats [which is not something I really want\nto add to the virtual machine]. If floats were to be added, only the\nminimal set of functions should be added [f+,f-,f\/,f*,f<,f>,>float,...]\n* Allow the processing of argc and argv, the mechanism by which that\nthis can be achieved needs to be worked out. However all processing that\nis currently done in \"main.c\" should be done within the Forth interpreter\ninstead. Words for manipulating rationals and double width cells should\nbe made first.\n* A built in version of \"dump\" and \"words\" should be added to the Forth\nstarting vocabulary, simplified versions that can be hidden.\n* Here documents, string literals. Examples of these can be found online\n* Document the words in this file and built in words better, also turn this\ndocument into a literate Forth file.\n* Sort out \"'\", \"[']\", \"find\", \"compile,\" \n* Proper booleans should be used throughout, that is -1 is true, and 0 is\nfalse.\n* Attempt to add crypto primitives, not for serious use, like TEA, XTEA,\nXXTEA, RC4, MD5, ...\n* Add hash functions: CRC-32, CRC-16, ...\nhttp:\/\/stackoverflow.com\/questions\/10564491\/function-to-calculate-a-crc16-checksum\n* File operation primitives that close the file stream [and possibly restore\nI\/O to stdin\/stdout] if an error occurs, and then re-throws, should be made.\n* Implement as many things from http:\/\/lars.nocrew.org\/forth2012\/implement.html\nas is sensible. \n* CASE Statements http:\/\/dxforth.netbay.com.au\/miser.html\n* The current words that implement I\/O redirection need to be improved, and documented,\nI think this is quite a useful and powerful mechanism to use within Forth that simplifies\nprograms. This is a must and will make writing utilities in Forth a *lot* easier \n* Words for manipulating words should be added, for navigating to different\nfields within them, to the end of the word, etcetera.\n* The data structure used for parsing Forth words needs changing in libforth so a\ncounted string is produced. Counted strings should be used more often. The current\nlayout of a Forth word prevents a counted string being used and uses a byte more\nthan it has to.\n* Whether certain simple words [such as '1+', '1-', '>', '<', '<>', 'not', '<=',\n'>='] should be added as virtual machine instructions for speed [and size] reasons\nshould be investigated.\n* An analysis of the interpreter and the code it executes could be done to find\nthe most commonly executed words and instructions, as well as the most common two and\nthree sequences of words and instructions. This could be used to use to optimize the\ninterpreter, in terms of both speed and size.\n\n### libforth.c todo\n\n* A halt, a parse, and a print\/type instruction could be added to the Forth virtual\nmachine.\n* Throw\/Catch need to be added and used in the virtual machine\n* Various edge cases and exceptions should be removed [for example counted strings\nare not used internally, and '0x' can be used as a prefix only when base is zero].\n* A potential optimization is to order the words in the dictionary by frequency order,\nthis would mean chaning the X Macro that contains the list of words, after collecting\nstatistics. This should make find faster.\n* Investigate adding operating system specific code into the interpreter and\nisolating it to make it semi-portable.\n* Make equivalents for various Unix utilities in Forth, like a CRC check, cat,\ntr, etcetera.\n\n )\n\nverbose [if] \n\t.( FORTH: libforth successfully loaded.) cr\n\t.( Type 'help' and press return for a basic introduction.) cr\n\t.( Core: ) here . \" \/ \" here unused + . cr\n\t license\n[then]\n\n\n( ==================== Test Code ============================= )\n\n( The following will not work as we might actually be reading from a string [`sin]\nnot `fin. \n: key 32 chars> 1 `fin @ read-file drop 0 = if 0 else 32 chars> c@ then ; )\n\n\\ : ' immediate state @ if postpone ['] else find then ;\n\n( This really does not implement a correct FORTH\/VOCABULARY, for that\nwordlists will need to be introduced and used in libforth.c. The best\nthat this word set can do is to hide and reveal words to the user, this\nwas just an experiment. \n\n\t: forth \n\t\t[ find forth 1- @ ] literal\n\t\t[ find forth 1- ] literal ! ;\n\n\t: vocabulary\n\t\tcreate does> drop 0 [ find forth 1- ] literal ! ; )\n\n\\ @todo The built in primitives should be redefined so to make sure\n\\ they are called and nested correctly, using the following words\n\\ 0 variable csp\n\\ : !csp sp@ csp ! ;\n\\ : ?csp sp@ csp @ <> if -22 throw then ;\n\\ \\ Is there a better throw value than -11?\n\\ : ?comp state @ 0= if -11 throw then ; \\ Error if not compiling\n\\ : ?exec state @ if -11 throw then ; \\ Error if not executing\n\n\n( ==================== Test Code ============================= )\n\n( ==================== Block Editor ========================== )\n( Experimental block editor Mark II \n\n@todo Improve the block editor \n\n- '\\' needs extending to work with the block editor, for now, \nuse parenthesis for comments \n- make an 'm' word for forgetting all words defined since the\neditor was invoked.\n- add multi line insertion mode\n- Add to an editor vocabulary, which will need the vocabulary\nsystem to exist.\n- Using 'page' should be optional as not all terminals support\nANSI escape codes - thanks to CMD.EXE. Damned Windows.\n- How line numbers are printed out should be investigated,\nalso I should refactor 'dump' to use a similar line number system.\n- Format the output of list better, put a nice box around it.\n\nAdapted from http:\/\/retroforth.org\/pages\/?PortsOfRetroEditor )\n\n \n: help ( @todo renamed to 'h' once vocabularies are implemented )\npage cr\n\" Block Editor Help Menu\n\n n move to next block\n p move to previous block\n # d delete line in current block\n x erase current block\n e evaluate current block\n # i insert line\n # #2 ia insert at line #2 at column #\n q quit editor loop\n # b set block number\n s save block and write it out\n\n -- press any key to continue -- \" cr ( \" )\nchar drop ;\n\n: (block) blk @ block ; \n: (line) c\/l * (block) + ; ( n -- c-addr : push current line address )\n: (clean) \n\t(block) b\/buf\n\t2dup nl bl subst\n\t2dup cret bl subst\n\t 0 bl subst ;\n: n blk @ 1+ block ;\n: p blk @ 1- block ;\n: d (line) c\/l bl fill ; \n: x (block) b\/buf bl fill ;\n: s update save-buffers ;\n: q rdrop rdrop ;\n: e blk @ load char drop ;\n: ia c\/l * + dup b\/buf swap - >r (block) + r> accept (clean) ; \n: i 0 swap ia ;\n: editor\n\t1 block\n\tbegin\n\t\tpostpone [ ( need to be in command mode )\n\t\tpage cr\n\t\t\" BLOCK EDITOR: TYPE 'HELP' FOR A LIST OF COMMANDS\" cr\n\t\tblk @ list\n\t\t\" CURRENT BLOCK: \" blk @ . cr\n\t\tread\n\tagain ;\n\n( Extra niceties )\nc\/l string yank\nyank bl fill\n: u update ;\n: b block ;\n: l blk @ list ;\n: y (line) yank >r swap r> cmove ;\n: c (line) yank cmove ;\n: ct swap y c ;\n\nhide{ (block) (line) (clean) yank }hide\n\n( ==================== Block Editor ========================== )\n\nhere fence !\n\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"c86aea4b146f24cb259f6b20b337cf36ae6b814e","subject":"Update outer.4th","message":"Update outer.4th","repos":"AshleyF\/Forthkit,AshleyF\/Forthkit,AshleyF\/Forthkit","old_file":"hardware\/register\/outer.4th","new_file":"hardware\/register\/outer.4th","new_contents":"( outer interpreter - reads tokens, compiles headers, literals, ... )\n( requires assembler )\n\n( --- register allocation\/init ----------------------------------------------- )\n\n 0 const c ( char last read )\n 1 const sp ( space 32 ASCII )\n 2 const tib ( terminal input buffer )\n 3 const len ( token length )\n 4 const len' ( name length )\n 5 const zero ( constant 0 )\n 6 const d ( dictionary pointer )\n 7 const nm ( match flag for search )\n 8 const p ( pointer )\n 9 const c ( char being compared )\n 10 const p' ( pointer )\n 11 const c' ( char being compared )\n 12 const cur ( cursor )\n 13 const lnk ( link pointer )\n 14 const true ( truth value )\n 15 const false ( false value )\n 16 const n ( parsed number )\n 17 const zeroch ( '0' ASCII )\n 18 const base ( number base )\n 19 const s ( stack pointer )\n 20 const nreg ( register n number )\n 21 const ldc ( ldc instruction [0] )\n 22 const call ( call instruction [27] )\n 23 const ret ( return instruction [29] )\n 24 const two ( constant 2 )\n 25 const comp ( compiling flag )\n 26 const x ( temp )\n 27 const y ( temp )\n 28 const z ( temp - reserved bootstrap )\n\n 32 sp ldc, ( space ASCII )\n 48 zeroch ldc, ( '0' ASCII )\n -1 true ldc, ( all bits set [logical\/bitwise equivalent] )\n 10 base ldc, ( decimal by default )\n 32767 s ldc, ( top of data stack )\n n nreg ldc, ( register number of n )\n 27 call ldc, ( call instruction )\n 28 ret ldc, ( ret instruction )\n 2 two ldc, ( constant 2 )\n\nleap,\n\n( --- tokenization ----------------------------------------------------------- )\n\n label &skipws ( skip until non-whitespace )\n c in, ( read char )\n c sp &skipws ble, ( keep skipping whitespace )\n ret,\n \n label &name ( read input name into buffer )\n c tib st, ( append char )\n tib tib inc, ( advance tib )\n len len inc, ( increment length )\n c in, ( read char )\n c sp &name bgt, ( continue until whitespace )\n len tib st, ( append length )\n ret,\n \n label &token ( read token into buffer )\n d tib cp, ( end of dictionary as buffer )\n zero len cp, ( initial zero length )\n &skipws call, ( skip initial whitespace )\n &name jump, ( append name )\n\n( --- dictionary search ------------------------------------------------------ )\n \n label &nomatch\n true nm cp, ( set no-match flag )\n ret,\n \n label &compcs ( compare chars to input word )\n p c ld, ( get char of input word )\n p' c' ld, ( get char of dictionary word )\n c c' &nomatch bne, ( don't match? )\n p' p' inc, ( next char of dictionary word )\n p p inc, ( next char of input word )\n p tib &compcs blt, ( not end of word? continue... )\n ret, ( we have a match! )\n \n label &nextw ( advance to next word )\n cur cur ld, ( follow link address )\n ( fall through to &comp )\n \n label &comp\nzero cur &nomatch beq, ( no match if start of dict )\n tib len p sub, ( point p at start of token )\n cur p' dec, ( point p' at length field )\n p' len' ld, ( get length )\n len' len &nextw bne, ( lengths don't match? )\n p' len p' sub, ( move to beginning of word )\n false nm cp, ( reset no-match flag )\n &compcs call, ( compare characters )\n true nm &nextw beq, ( if no match, try next word )\n ret, ( we have a match! )\n \n label &find ( find word [tib within dictionary] )\n lnk cur cp, ( initialize cursor to last )\n &comp jump, ( compare with tib )\n \n( --- number processing ------------------------------------------------------ )\n\n label &digits\n p c ld, ( get char )\n c zeroch c sub, ( convert to digit )\n n base n mul, ( base shift left )\n n c n add, ( add in one's place )\n p p inc, ( next char )\n p tib &digits blt, ( not end? continue... )\n ret,\n \n label &parsenum ( parse token as number )\n tib len p sub, ( point p at start of word )\n zero n cp, ( init number )\n &digits jump,\n \n label &pushn ( push interactive number )\n n s st, ( store n at stack pointer )\n s s dec, ( adjust stack pointer )\n ret,\n \n label &popn ( pop number )\n s s inc, ( adjust stack pointer )\n s n ld, ( load value )\n ret,\n\n( --- literals --------------------------------------------------------------- )\n\n: append, d st, d d inc, ; ( macro: append and advance d )\n\n label &litn ( compile literal )\n ldc append, ( append ldc instruction )\n nreg append, ( append n register number )\n n append, ( append value )\n call append, ( append call instruction )\n &pushn x ldc, ( load address of &pushn )\n x append, ( append pushn address )\n ret,\n \n label &num ( process token as number )\n &parsenum call, ( parse number )\n true comp &litn beq, ( if compiling, compile literal )\n &pushn jump, ( else, push literal )\n \n( --- word processing -------------------------------------------------------- )\n\n label &exec ( execute word )\n two cur x add, ( point to code field )\n x exec, ( exec word )\n ret,\n \n label &compw ( compile word )\n cur x inc, ( point to immediate flag )\n x y ld, ( read immediate flag )\n true y &exec beq, ( execute if immediate )\n call append, ( append call instruction )\n x x inc, ( point to code field )\n x append, ( append code field address )\n ret,\n \n label &word ( process potential word token )\n true comp &compw beq, ( if compiling, compile word )\n &exec jump, ( else, execute word )\n \n label &eval ( process input tokens )\n &find call, ( try to find in dictionary )\n true nm &num beq, ( if not found, assume number )\n &word jump, ( else, process as a word )\n \n( --- REPL ------------------------------------------------------------------- )\n\n label &repl ( loop forever )\n &token call, ( read a token )\n &eval call, ( evaluate it )\n &repl jump, ( forever )\n \n( --- initial dictionary ----------------------------------------------------- )\n\nvar link\n: header, dup 0 do swap , loop , link @ here link ! , , ;\n\n 0 sym create header, ( word to create words )\n &token call, ( read a token )\n tib d cp, ( move dict ptr to end of name )\n d d inc, ( move past length field )\n lnk d st, ( append link address )\n d lnk cp, ( update link to here )\n d d inc, ( advance dictionary pointer )\n zero append, ( append 0 immediate flag ) \n ret,\n\n 0 sym immediate header, ( set immediate flag )\n lnk x inc, ( point to immediate flag )\n true x st, ( set immediate flag )\n ret,\n\n 0 sym compile header, ( switch to compiling mode )\n true comp cp, ( set comp flag )\n ret,\n\n 0 sym interact header, ( switch to interactive mode )\n label &interact\n false comp ldc, ( reset comp flag )\n ret,\n\n -1 sym ; header, ( return )\n ret append, ( append ret instruction )\n &interact jump, ( switch out of compiling mode )\n \n 0 sym pushn, header, ( push number [n] to stack from )\n &pushn jump, ( jump to push )\n \n 0 sym popn, header, ( pop number from stack to n )\n &popn jump, ( jump pop )\n \n 0 sym , header, ( append value from stack )\n &popn call, ( pop value from stack )\n n append, ( append n ) \n ret,\n \n 0 sym find header, ( find word )\n &token call, ( read a token )\n &find call, ( find token )\n cur n cp, ( prep to push cursor )\n two n n add, ( address of code field )\n &pushn jump, ( push cursor )\n \n 0 sym dump header, ( dump core to boot.bin )\n dump, ( TODO: build outside of outer interpreter )\n\nahead,\n\n( --- set `lnk` to within last header and `d` to just past this code --------- )\n\nlink @ lnk ldc, ( compile-time link ptr to runtime )\nhere 5 + d ldc, ( compile-time dict ptr to runtime [advance over init code below] )\n\n&repl jump, ( start the REPL )\n\nassemble\n\n","old_contents":"( outer interpreter - reads tokens, compiles headers, literals, ... )\n( requires assembler )\n\n( --- register allocation\/init ----------------------------------------------- )\n\n 0 const c ( char last read )\n 1 const sp ( space 32 ASCII )\n 2 const tib ( terminal input buffer )\n 3 const len ( token length )\n 4 const len' ( name length )\n 5 const zero ( constant 0 )\n 6 const d ( dictionary pointer )\n 7 const nm ( match flag for search )\n 8 const p ( pointer )\n 9 const c ( char being compared )\n 10 const p' ( pointer )\n 11 const c' ( char being compared )\n 12 const cur ( cursor )\n 13 const lnk ( link pointer )\n 14 const true ( truth value )\n 15 const false ( false value )\n 16 const n ( parsed number )\n 17 const zeroch ( '0' ASCII )\n 18 const base ( number base )\n 19 const s ( stack pointer )\n 20 const nreg ( register n number )\n 21 const ldc ( ldc instruction [0] )\n 22 const call ( call instruction [27] )\n 23 const ret ( return instruction [29] )\n 24 const two ( constant 2 )\n 25 const comp ( compiling flag )\n 26 const x ( temp )\n 27 const y ( temp )\n 28 const z ( temp - reserved bootstrap )\n\n 32 sp ldc, ( space ASCII )\n 48 zeroch ldc, ( '0' ASCII )\n -1 true ldc, ( all bits set [logical\/bitwise equivalent] )\n 10 base ldc, ( decimal by default )\n 32767 s ldc, ( top of data stack )\n n nreg ldc, ( register number of n )\n 27 call ldc, ( call instruction )\n 28 ret ldc, ( ret instruction )\n 2 two ldc, ( constant 2 )\n\nleap,\n\n( --- tokenization ----------------------------------------------------------- )\n\n label &skipws ( skip until non-whitespace )\n c in, ( read char )\n c sp &skipws ble, ( keep skipping whitespace )\n ret,\n \n label &name ( read input name into buffer )\n c tib st, ( append char )\n tib tib inc, ( advance tib )\n len len inc, ( increment length )\n c in, ( read char )\n c sp &name bgt, ( continue until whitespace )\n len tib st, ( append length )\n ret,\n \n label &token ( read token into buffer )\n d tib cp, ( end of dictionary as buffer )\n zero len cp, ( initial zero length )\n &skipws call, ( skip initial whitespace )\n &name jump, ( append name )\n\n( --- dictionary search ------------------------------------------------------ )\n \n label &nomatch\n true nm cp, ( set no-match flag )\n ret,\n \n label &compcs ( compare chars to input word )\n p c ld, ( get char of input word )\n p' c' ld, ( get char of dictionary word )\n c c' &nomatch bne, ( don't match? )\n p' p' inc, ( next char of dictionary word )\n p p inc, ( next char of input word )\n p tib &compcs blt, ( not end of word? continue... )\n ret, ( we have a match! )\n \n label &nextw ( advance to next word )\n cur cur ld, ( follow link address )\n ( fall through to &comp )\n \n label &comp\nzero cur &nomatch beq, ( no match if start of dict )\n tib len p sub, ( point p at start of token )\n cur p' dec, ( point p' at length field )\n p' len' ld, ( get length )\n len' len &nextw bne, ( lengths don't match? )\n p' len p' sub, ( move to beginning of word )\n false nm cp, ( reset no-match flag )\n &compcs call, ( compare characters )\n true nm &nextw beq, ( if no match, try next word )\n ret, ( we have a match! )\n \n label &find ( find word [tib within dictionary] )\n lnk cur cp, ( initialize cursor to last )\n &comp jump, ( compare with tib )\n \n( --- number processing ------------------------------------------------------ )\n\n label &digits\n p c ld, ( get char )\n c zeroch c sub, ( convert to digit )\n n base n mul, ( base shift left )\n n c n add, ( add in one's place )\n p p inc, ( next char )\n p tib &digits blt, ( not end? continue... )\n ret,\n \n label &parsenum ( parse token as number )\n tib len p sub, ( point p at start of word )\n zero n cp, ( init number )\n &digits jump,\n \n label &pushn ( push interactive number )\n n s st, ( store n at stack pointer )\n s s dec, ( adjust stack pointer )\n ret,\n \n label &popn ( pop number )\n s s inc, ( adjust stack pointer )\n s n ld, ( load value )\n ret,\n\n( --- literals --------------------------------------------------------------- )\n\n: append, d st, d d inc, ; ( macro: append and advance d )\n\n label &litn ( compile literal )\n ldc append, ( append ldc instruction )\n nreg append, ( append n register number )\n n append, ( append value )\n call append, ( append call instruction )\n &pushn x ldc, ( load address of &pushn )\n x append, ( append pushn address )\n ret,\n \n label &num ( process token as number )\n &parsenum call, ( parse number )\n true comp &litn beq, ( if compiling, compile literal )\n &pushn jump, ( else, push literal )\n \n( --- word processing -------------------------------------------------------- )\n\n label &exec ( execute word )\n two cur x add, ( point to code field )\n x exec, ( exec word )\n ret,\n \n label &compw ( compile word )\n cur x inc, ( point to immediate flag )\n x y ld, ( read immediate flag )\n true y &exec beq, ( execute if immediate )\n call append, ( append call instruction )\n x x inc, ( point to code field )\n x append, ( append code field address )\n ret,\n \n label &word ( process potential word token )\n true comp &compw beq, ( if compiling, compile word )\n &exec jump, ( else, execute word )\n \n label &eval ( process input tokens )\n &find call, ( try to find in dictionary )\n true nm &num beq, ( if not found, assume number )\n &word jump, ( else, process as a word )\n \n( --- REPL ------------------------------------------------------------------- )\n\n label &repl ( loop forever )\n &token call, ( read a token )\n &eval call, ( evaluate it )\n &repl jump, ( forever )\n \n( --- initial dictionary ----------------------------------------------------- )\n\nvar link\n: header, dup 0 do swap , loop , link @ here link ! , , ;\n\n 0 sym create header, ( word to create words )\n &token call, ( read a token )\n tib d cp, ( move dict ptr to end of name )\n d d inc, ( move past length field )\n lnk d st, ( append link address )\n d lnk cp, ( update link to here )\n d d inc, ( advance dictionary pointer )\n zero append, ( append 0 immediate flag ) \n ret,\n\n 0 sym immediate header, ( set immediate flag )\n lnk x inc, ( point to immediate flag )\n true x st, ( set immediate flag )\n ret,\n\n 0 sym compile header, ( switch to compiling mode )\n true comp cp, ( set comp flag )\n ret,\n\n 0 sym interact header, ( switch to interactive mode )\n label &interact\n false comp ldc, ( reset comp flag )\n ret,\n\n -1 sym ; header, ( return )\n ret append, ( append ret instruction )\n &interact jump, ( switch out of compiling mode )\n \n 0 sym pushn, header, ( push number [n] to stack from )\n &pushn jump, ( jump to push )\n \n 0 sym popn, header, ( pop number from stack to n )\n &popn jump, ( jump pop )\n \n 0 sym , header, ( append value from stack )\n &popn call, ( pop value from stack )\n n append, ( append n ) \n ret,\n \n 0 sym find header, ( find word )\n &token call, ( read a token )\n &find call, ( find token )\n cur n cp, ( prep to push cursor )\n two n n add, ( address of code field )\n &pushn jump, ( push cursor )\n \n 0 sym dump header, ( dump core to boot.bin )\n dump, ( TODO: build outside of outer interpreter )\n\nahead,\n\n( --- set `lnk` to within last header and `d` to just past this code --------- )\n\nlink @ lnk ldc, ( compile-time link ptr to runtime )\nhere 5 + d ldc, ( compile-time dict ptr to runtime [advance over init code below] )\n\n&repl jump, ( start the REPL )\n\nassemble\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"a2b3ce9271c9b4e1de9711aebf24a7e990bab5c0","subject":"Rewording.","message":"Rewording.\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"share\/examples\/bootforth\/menuconf.4th","new_file":"share\/examples\/bootforth\/menuconf.4th","new_contents":"\\ Simple greeting screen, presenting basic options.\n\\ XXX This is far too trivial - I don't have time now to think\n\\ XXX about something more fancy... :-\/\n\\ $Id$\n\n: title\n\tf_single\n\t60 11 10 4 box\n\t29 4 at-xy 15 fg 7 bg\n\t.\" Welcome to BootFORTH!\"\n\tme\n;\n\n: menu\n\t2 fg\n\t20 7 at-xy \n\t.\" 1. Start FreeBSD with \/boot\/stable.conf.\"\n 20 8 at-xy\n .\" 2. Start FreeBSD with \/boot\/current.conf.\"\n\t20 9 at-xy\n\t.\" 3. Start FreeBSD with standard configuration. \"\n\t20 10 at-xy\n\t.\" 4. Reboot.\"\n\tme\n;\n\n: tkey\t( d -- flag | char )\n\tseconds +\n\tbegin 1 while\n\t dup seconds u< if\n\t\tdrop\n\t\t-1\n\t\texit\n\t then\n\t key? if\n\t\tdrop\n\t\tkey\n\t\texit\n\t then\n\trepeat\n;\n\n: prompt\n\t14 fg\n\t20 12 at-xy\n\t.\" Enter your option (1,2,3,4): \"\n\t10 tkey\n\tdup 32 = if\n\t drop key\n\tthen\n\tdup 0< if\n\t drop 51\n\tthen\n\tdup emit\n\tme\n;\n\n: help_text\n 10 18 at-xy .\" * Choose 1 or 2 to run special configuration file.\"\n\t10 19 at-xy .\" * Choose 3 to proceed with standard bootstrapping.\"\n\t12 20 at-xy .\" See '?' for available commands, and 'words' for\"\n\t12 21 at-xy .\" complete list of Forth words.\"\n\t10 22 at-xy .\" * Choose 4 in order to warm boot your machine.\"\n;\n\n: (reboot) 0 reboot ;\n\n: main_menu\n\tbegin 1 while\n\t\tclear\n\t\tf_double\n\t\t79 23 1 1 box\n\t\ttitle\n\t\tmenu\n\t\thelp_text\n\t\tprompt\n\t\tcr cr cr\n\t\tdup 49 = if\n\t\t\tdrop\n\t\t\t1 25 at-xy cr\n\t\t\t.\" Loading \/boot\/stable.conf. Please wait...\" cr\n\t\t\ts\" \/boot\/stable.conf\" read-conf\n\t\t\tboot-conf\n\t\tthen\n\t\tdup 50 = if\n\t\t\tdrop\n\t\t\t1 25 at-xy cr\n\t\t\t.\" Loading \/boot\/current.conf. Please wait...\" cr\n\t\t\ts\" \/boot\/current.conf\" read-conf\n\t\t\tboot-conf\n\t\tthen\n\t\tdup 51 = if\n\t\t\tdrop\n\t\t\t1 25 at-xy cr\n\t\t\t.\" Proceeding with standard boot. Please wait...\" cr\n\t\t\tboot-conf\n\t\tthen\n\t\tdup 52 = if\n\t\t\tdrop\n\t\t\t1 25 at-xy cr\n\t\t\t['] (reboot) catch abort\" Error rebooting\"\n\t\tthen\n\t\t20 12 at-xy\n\t\t.\" Key \" emit .\" is not a valid option!\"\n\t\t20 13 at-xy\n\t\t.\" Press any key to continue...\"\n\t\tkey drop\n\trepeat\n;\n\n","old_contents":"\\ Simple greeting screen, presenting basic options.\n\\ XXX This is far too trivial - I don't have time now to think\n\\ XXX about something more fancy... :-\/\n\\ $Id$\n\n: title\n\tf_single\n\t60 11 10 4 box\n\t29 4 at-xy 15 fg 7 bg\n\t.\" Welcome to BootFORTH!\"\n\tme\n;\n\n: menu\n\t2 fg\n\t20 7 at-xy \n\t.\" 1. Start FreeBSD \/boot\/stable.conf.\"\n 20 8 at-xy\n .\" 2. Start FreeBSD \/boot\/current.conf.\"\n\t20 9 at-xy\n\t.\" 3. Start FreeBSD \/boot\/loader.rc.\"\n\t20 10 at-xy\n\t.\" 4. Reboot.\"\n\tme\n;\n\n: tkey\t( d -- flag | char )\n\tseconds +\n\tbegin 1 while\n\t dup seconds u< if\n\t\tdrop\n\t\t-1\n\t\texit\n\t then\n\t key? if\n\t\tdrop\n\t\tkey\n\t\texit\n\t then\n\trepeat\n;\n\n: prompt\n\t14 fg\n\t20 12 at-xy\n\t.\" Enter your option (1,2,3,4): \"\n\t10 tkey\n\tdup 32 = if\n\t drop key\n\tthen\n\tdup 0< if\n\t drop 51\n\tthen\n\tdup emit\n\tme\n;\n\n: help_text\n 10 18 at-xy .\" * Choose 1 or 2 to run special configuration file.\"\n\t10 19 at-xy .\" * Choose 3 to proceed with standard bootstrapping.\"\n\t12 20 at-xy .\" See '?' for available commands, and 'words' for\"\n\t12 21 at-xy .\" complete list of Forth words.\"\n\t10 22 at-xy .\" * Choose 4 in order to warm boot your machine.\"\n;\n\n: (reboot) 0 reboot ;\n\n: main_menu\n\tbegin 1 while\n\t\tclear\n\t\tf_double\n\t\t79 23 1 1 box\n\t\ttitle\n\t\tmenu\n\t\thelp_text\n\t\tprompt\n\t\tcr cr cr\n\t\tdup 49 = if\n\t\t\tdrop\n\t\t\t1 25 at-xy cr\n\t\t\t.\" Loading \/boot\/stable.conf. Please wait...\" cr\n\t\t\ts\" \/boot\/stable.conf\" read-conf\n\t\t\tboot-conf\n\t\tthen\n\t\tdup 50 = if\n\t\t\tdrop\n\t\t\t1 25 at-xy cr\n\t\t\t.\" Loading \/boot\/current.conf. Please wait...\" cr\n\t\t\ts\" \/boot\/current.conf\" read-conf\n\t\t\tboot-conf\n\t\tthen\n\t\tdup 51 = if\n\t\t\tdrop\n\t\t\t1 25 at-xy cr\n\t\t\t.\" Proceeding with standard boot. Please wait...\" cr\n\t\t\tboot-conf\n\t\tthen\n\t\tdup 52 = if\n\t\t\tdrop\n\t\t\t1 25 at-xy cr\n\t\t\t['] (reboot) catch abort\" Error rebooting\"\n\t\tthen\n\t\t20 12 at-xy\n\t\t.\" Key \" emit .\" is not a valid option!\"\n\t\t20 13 at-xy\n\t\t.\" Press any key to continue...\"\n\t\tkey drop\n\trepeat\n;\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"0787a80d9c0e01bee57514fa5e591b94aa7ae0df","subject":"Added , , , , , and rudamentary","message":"Added , , , , , and rudamentary\n","repos":"AshleyF\/Forthkit,AshleyF\/Forthkit,AshleyF\/Forthkit","old_file":"hardware\/register\/bootstrap.4th","new_file":"hardware\/register\/bootstrap.4th","new_contents":"( bootstrap remainder of interpreter )\n( load into machine running outer interpreter image )\n\ncreate : compile create compile ; ( magic! )\n\n( assembler )\n\n: x 1 ; ( shared by outer interpreter )\n: d 2 ; ( dictionary pointer - shared by outer interpreter )\n: zero 4 ; ( shared by outer interpreter )\n: y 30 ; \n: z 31 ; \n\n: [ interact ; immediate\n: ] compile ;\n\n: cp, 3 , , , ; \n: popxy popx [ x y cp, ] popx ;\n: pushxy pushx [ y x cp, ] pushx ;\n\n: xor, 15 , , , , ; \n: swap popxy [ x y x xor, x y y xor, x y x xor, ] pushxy ;\n\n: ldc, 0 , , , ;\n: ld, 1 , , , ;\n: st, 2 , , , ;\n: in, 4 , , ;\n: out, 5 , , ;\n: inc, 6 , , , ;\n: dec, 7 , , , ;\n: add, 8 , , , , ;\n: sub, 9 , , swap , , ;\n: mul, 10 , , , , ;\n: div, 11 , , swap , , ;\n: mod, 12 , , swap , , ;\n: and, 13 , , , , ;\n: or, 14 , , , , ;\n: not, 16 , , , ;\n: shr, 17 , , swap , , ;\n: shl, 18 , , swap , , ;\n: beq, 19 , , , , ;\n: bne, 20 , , , , ;\n: bgt, 21 , , swap , , ;\n: bge, 22 , , swap , , ;\n: blt, 23 , , swap , , ;\n: ble, 24 , , swap , , ;\n: exec, 25 , , ;\n: jump, 26 , , ;\n: call, 27 , , ;\n: ret, 28 , ;\n: halt, 29 , ;\n: dump, 30 , ;\n\n( instruction words )\n\n: + popxy [ x y x add, ] pushx ;\n: - popxy [ x y x sub, ] pushx ;\n: * popxy [ x y x mul, ] pushx ;\n: \/ popxy [ x y x div, ] pushx ;\n: mod popxy [ x y x mod, ] pushx ;\n: 2\/ popxy [ x y x shr, ] pushx ;\n: 2* popxy [ x y x shl, ] pushx ;\n: and popxy [ x y x and, ] pushx ;\n: or popxy [ x y x or, ] pushx ;\n: xor popxy [ x y x xor, ] pushx ;\n: not popx [ x x not, ] pushx ;\n: 1+ popx [ x x inc, ] pushx ;\n: 1- popx [ x x dec, ] pushx ;\n: exec popx [ x exec, ] ;\n: dump [ dump, ] ;\n: exit [ halt, ] ;\n\n( stack manipulation )\n\n: drop ( a- ) popx ;\n: 2drop ( ab- ) drop drop ;\n: dup ( a-aa ) popx pushx pushx ;\n: over ( ab-aba ) popxy pushx pushx [ y x cp, ] pushx swap ;\n: 2dup ( ab-abab ) over over ;\n: nip ( ab-b ) swap drop ;\n: tuck ( ab-bab ) swap over ;\n: -rot ( abc-cab ) swap popxy pushx [ y z cp, ] swap [ z x cp, ] pushx ;\n\n( vocabulary )\n\n: true -1 ;\n: false 0 ;\n\n: key [ x in, ] pushx ;\n: emit popx [ x out, ] ;\n: cr 10 emit ;\n: space 32 emit ;\n\n: @ popx [ x x ld, ] pushx ;\n: ! popxy [ x y st, ] ;\n\n: allot [ d x cp, ] pushx swap popx [ x d d add, ] ;\n\n: here@ [ d x cp, ] pushx ;\n: here! popx [ x d cp, ] ;\n\n: >dfa 2 + ;\n: ' find >dfa ;\n\n: if [ ' popxy literal ] call, here@ 1+ zero x 0 beq, ; immediate\n: else here@ 1+ 0 jump, swap here@ swap ! ; immediate\n: then here@ swap ! ; immediate\n\n: = popxy 0 [ x y here@ 6 + bne, ] not ;\n: <> popxy 0 [ x y here@ 6 + beq, ] not ;\n: > popxy 0 [ x y here@ 6 + ble, ] not ;\n: < popxy 0 [ x y here@ 6 + bge, ] not ;\n: >= popxy 0 [ x y here@ 6 + blt, ] not ;\n: <= popxy 0 [ x y here@ 6 + bgt, ] not ;\n\n: sign 0 < if -1 else 1 then ;\n: \/mod 2dup \/ -rot mod ;\n\n: .sign dup sign -1 * 44 + emit ; ( happens 44 +\/- 1 is ASCII '-'\/'+' )\n: .dig 10 \/mod swap ;\n: .digemit 48 + emit ; ( 48 is ASCII '0' )\n: . .sign .dig .dig .dig .dig .dig drop .digemit .digemit .digemit .digemit .digemit cr ;\n","old_contents":"( bootstrap remainder of interpreter )\n( load into machine running outer interpreter image )\n\ncreate : compile create compile ; ( magic! )\n\n( assembler )\n\n: x 1 ; ( shared by outer interpreter )\n: d 2 ; ( dictionary pointer - shared by outer interpreter )\n: zero 4 ; ( shared by outer interpreter )\n: y 31 ; \n\n: [ interact ; immediate\n: ] compile ;\n\n: cp, 3 , , , ; \n: popxy popx [ x y cp, ] popx ;\n: pushxy pushx [ y x cp, ] pushx ;\n\n: xor, 15 , , , , ; \n: swap popxy [ x y x xor, x y y xor, x y x xor, ] pushxy ;\n\n: ldc, 0 , , , ;\n: ld, 1 , , , ;\n: st, 2 , , , ;\n: in, 4 , , ;\n: out, 5 , , ;\n: inc, 6 , , , ;\n: dec, 7 , , , ;\n: add, 8 , , , , ;\n: sub, 9 , , swap , , ;\n: mul, 10 , , , , ;\n: div, 11 , , swap , , ;\n: mod, 12 , , swap , , ;\n: and, 13 , , , , ;\n: or, 14 , , , , ;\n: not, 16 , , , ;\n: shr, 17 , , swap , , ;\n: shl, 18 , , swap , , ;\n: beq, 19 , , , , ;\n: bne, 20 , , , , ;\n: bgt, 21 , , swap , , ;\n: bge, 22 , , swap , , ;\n: blt, 23 , , swap , , ;\n: ble, 24 , , swap , , ;\n: exec, 25 , , ;\n: jump, 26 , , ;\n: call, 27 , , ;\n: ret, 28 , ;\n: halt, 29 , ;\n: dump, 30 , ;\n\n( instruction words )\n\n: + popxy [ x y x add, ] pushx ;\n: - popxy [ x y x sub, ] pushx ;\n: * popxy [ x y x mul, ] pushx ;\n: \/ popxy [ x y x div, ] pushx ;\n: mod popxy [ x y x mod, ] pushx ;\n: 2\/ popxy [ x y x shr, ] pushx ;\n: 2* popxy [ x y x shl, ] pushx ;\n: and popxy [ x y x and, ] pushx ;\n: or popxy [ x y x or, ] pushx ;\n: xor popxy [ x y x xor, ] pushx ;\n: not popx [ x x not, ] pushx ;\n: 1+ popx [ x x inc, ] pushx ;\n: 1- popx [ x x dec, ] pushx ;\n: exec popx [ x exec, ] ;\n: dump [ dump, ] ;\n: exit [ halt, ] ;\n\n( stack manipulation )\n\n: drop popx ;\n: dup popx pushx pushx ;\n\n( vocabulary )\n\n: true -1 ;\n: false 0 ;\n\n: key [ x in, ] pushx ;\n: emit popx [ x out, ] ;\n: cr 10 emit ;\n: space 32 emit ;\n\n: @ popx [ x x ld, ] pushx ;\n: ! popxy [ x y st, ] ;\n\n: allot [ d x cp, ] pushx swap popx [ x d d add, ] ;\n\n: here@ [ d x cp, ] pushx ;\n: here! popx [ x d cp, ] ;\n\n: >dfa 2 + ;\n: ' find >dfa ;\n\n: if [ ' popx literal ] call, here@ 1+ zero x 0 beq, ; immediate\n: else here@ 1+ 0 jump, swap here@ swap ! ; immediate\n: then here@ swap ! ; immediate\n\n: = popxy 0 [ x y here@ 6 + bne, ] not ;\n: <> popxy 0 [ x y here@ 6 + beq, ] not ;\n: > popxy 0 [ x y here@ 6 + ble, ] not ;\n: < popxy 0 [ x y here@ 6 + bge, ] not ;\n: >= popxy 0 [ x y here@ 6 + blt, ] not ;\n: <= popxy 0 [ x y here@ 6 + bgt, ] not ;\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"fe520e719ff2a5ff71e5503195774051fcee3e5c","subject":"LOG2 added","message":"LOG2 added\n","repos":"bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas","old_file":"KataDiversion.fth","new_file":"KataDiversion.fth","new_contents":"\\ KataDiversion in Forth\n\n\\ -- utils\n\n\\ empty the stack\n: EMPTY\n DEPTH 0 <> IF BEGIN\n DROP DEPTH 0 =\n UNTIL\n THEN ;\n\n\\ power\n: ** ( n1 n2 -- n1_pow_n2 ) 1 SWAP ?DUP IF 0 DO OVER * LOOP THEN NIP ;\n\n\\ test if the top is a negative number\n: ?NEG ( n -- bool ) DUP 0= IF -1 ELSE DUP ABS <> THEN ;\n\n\\ log2 (integer)\n: LOG2 ( n -- n log2_n ) DUP 1 < IF 1 ABORT\" Log2 need a positive value.\"\n ELSE DUP 1 = IF 0\n ELSE\n 1 >R\n BEGIN ( n |R: i)\n DUP DUP 2 I ( n n n 2 i |R: i)\n ** ( n n n 2**i )\n - ( n n n-2**i )\n 2 * ( n n 2*[n-2**i])\n R> 1 + >R ( \u2026 |R: i+1)\n > ( n n>2*[n-2**i] )\n UNTIL\n R> 1 -\n THEN\n THEN ;\n \n\n\\ -- kata\n\n\\ test if the given N has two adjacent 1 bits\n\\ e.g. : 1011 -> -1\n\\ 1001 -> 0\n: ?TWO-ADJACENT-1-BITS ( n -- bool ) ( TODO ) ;\n\n\\ return the maximum number which can be made with N (given number) bits\n: ?MAX-NB ( n -- m ) DUP ?NEG IF DROP 0 ( 0 )\n ELSE \n DUP IF DUP 2 SWAP ** NIP ( 2**n )\n THEN\n THEN ;\n\n\n\\ return the number of numbers which can be made with N (given number) bits\n\\ or less, and which have not two adjacent 1 bits.\n\\ see http:\/\/www.codekata.com\/2007\/01\/code_kata_fifte.html\n: ?HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS ( n -- m ) ( TODO ) ;\n","old_contents":"\\ KataDiversion in Forth\n\n\\ -- utils\n\n\\ empty the stack\n: EMPTY\n DEPTH 0 <> IF BEGIN\n DROP DEPTH 0 =\n UNTIL\n THEN ;\n\n\\ power\n: ** ( n1 n2 -- n1_pow_n2 ) 1 SWAP ?DUP IF 0 DO OVER * LOOP THEN NIP ;\n\n\\ test if the top is a negative number\n: ?NEG ( n -- bool ) DUP 0= IF -1 ELSE DUP ABS <> THEN ;\n\n\\ -- kata\n\n\\ test if the given N has two adjacent 1 bits\n\\ e.g. : 1011 -> -1\n\\ 1001 -> 0\n: ?TWO-ADJACENT-1-BITS ( n -- bool ) ( TODO ) ;\n\n\\ return the maximum number which can be made with N (given number) bits\n: ?MAX-NB ( n -- m ) DUP ?NEG IF DROP 0 ( 0 )\n ELSE \n DUP IF DUP 2 SWAP ** NIP ( 2**n )\n THEN\n THEN ;\n\n\n\\ return the number of numbers which can be made with N (given number) bits\n\\ or less, and which have not two adjacent 1 bits.\n\\ see http:\/\/www.codekata.com\/2007\/01\/code_kata_fifte.html\n: ?HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS ( n -- m ) ( TODO ) ;\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"a3b24fc4eaa19decec8de49029f53e33637f63fb","subject":"Make the time advance code general-purpose.","message":"Make the time advance code general-purpose.","repos":"rbsexton\/gecko,rbsexton\/gecko,rbsexton\/gecko","old_file":"zero\/clock-umb\/forth\/Clock.fth","new_file":"zero\/clock-umb\/forth\/Clock.fth","new_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( n -- ) \n icroot inter.rtcsem 0 over ! \\ Reset the free-running counter.\n swap \\ addr n -- \n 0 do \n dup @resetex! ?dup if advance else [asm wfi asm] then\n loop\n drop\n;\n\n: CLOCKINIT ( -- )\n #1000 needlemax\n 2dup ! 4 + 2dup ! 4 + ! \n;\n \n\\ Heres where we advance any needles.\n: ADVANCE ( n -- )\n pwm0@ + pwm0! \n;\n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nudata\ncreate NEEDLEMAX 3 cells allot\ncdata\n\n: ++NEEDLE_S ; \\ Called ever time.\n: ++NEEDLE_M ; \\ Every time we roll the seconds.\n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxsec \\ Max Value for secs+minutes\n\tint hms.maxhour \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_m \\ increment the minutes + hours\nend-struct\n\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_s , ' ++needle_m , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n\\ UNTESTED\n: ADVANCETIME ( struct-addr -- )\n dup hms.w_s @ execute \\ Invoke the official update word.\n 1 over hms.subsec +! \\ Increment\n dup hms.subsec @\n over hms.maxsubsec @ < if drop exit then \\ If less then max, we're done\n 0 over hms.subsec ! \\ Reset the subsecs \n\n dup hms.w_m @ execute\n 1 over hms.s +!\n dup hms.s @ over hms.maxsec @ < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n 1 over hms.m +!\n dup hms.m @ over hms.maxsec @ < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ over hms.maxhour @ < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ============================ UNTESTED =======================\n\\ VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n\n","old_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( n -- ) \n icroot inter.rtcsem 0 over ! \\ Reset the free-running counter.\n swap \\ addr n -- \n 0 do \n dup @resetex! ?dup if advance else [asm wfi asm] then\n loop\n drop\n;\n\n: CLOCKINIT ( -- )\n #1000 needlemax\n 2dup ! 4 + 2dup ! 4 + ! \n;\n \n\\ Heres where we advance any needles.\n: ADVANCE ( n -- )\n pwm0@ + pwm0! \n;\n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nudata\ncreate NEEDLEMAX 3 cells allot\ncdata\n\n: ++NEEDLE_S ; \\ Called ever time.\n: ++NEEDLE_M ; \\ Every time we roll the seconds.\n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxs+m \\ Max Value for secs+minutes\n\tint hms.maxh \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_mh \\ increment the minutes + hours\nend-struct\n\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_s , ' ++needle_m , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n: ADVANCETIME ( struct-addr -- )\n ++needle_s 1 over hms.subsec +!\n dup hms.subsec @ #16 < if drop exit then\n 0 over hms.subsec ! \\ Reset the subsecs \n\n ++needle_m 1 over hms.s +!\n dup hms.s @ #60 < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n 1 over hms.m +!\n dup hms.m @ #60 < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ #24 < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ============================ UNTESTED =======================\n\\ VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"c23a84fa5b97e937facbad16c3f420217f29bac5","subject":"Checkin some old stuff for working with values.","message":"Checkin some old stuff for working with values.","repos":"rbsexton\/sockpuppet,rbsexton\/sockpuppet","old_file":"forth\/dylink.fth","new_file":"forth\/dylink.fth","new_contents":"\\ Code to support runtime\/dynamic into the C side via SAPI.\n\\\n\\ In the MPE environment, VALUEs work very well for this.\n\\ values are defined at compile time and can be updated at runtime.\n\n\\ So the basic logic is - walk the dynamic list, and if you find something\n\\ that is already defined, assume its a VALUE\n\\ otherwise, generate a constant.\n\n\\ Walk the table and make the constants.\n: dy-populate\n dy-first@ \n begin \n dup dy.val 0<> \n while\n dup dy-create\n dy-recordlen +\n repeat\n drop\n ; \n\n\\ The key bit. Look for an entry and if its a value, update it.\n\\ otherwise, add a constant to the dictionary.\n: dy-create ( c-addr -- )\n \\ Start by looking it up\n DUP dy-cstring \\ Make a counted string out of it.\n\n dy.buf find \n 0= IF \\ If failure, cleanup and make-const \n DROP\n dup dy.val \\ c-addr n \n swap dup dy.name swap dy.namelen \\ n c-addr b\n make-const\n ELSE \\ If Success, get the value and stuff it in there.\n SWAP dy.val \\ Fetch the value\n SWAP dy-stuff\n THEN\n ;\n\n\n\n\n: dy-first@ ( -- c-addr ) getsharedvars dy-recordlen + ; \n: dy-cstring ( c-addr -- ) dy.name OVER dy.namelen dy.buf place ; \n\n\\ ************************************************************************\n\\ ************************************************************************\n\\ Secondary support functions \n\\ ************************************************************************\n\\ ************************************************************************\n\n\\ *********************************************\n\\ Accessors - Tightly tied the data structure\n\\ *********************************************\n: dy.val @ ; \n: dy.size #4 + w@ ; \n: dy.count #6 + w@ ; \n: dy.type #8 + c@ ;\n: dy.namelen #9 + c@ ;\n: dy.name #12 + @ ;\n\nUDATA \\ We need a scratch buffer.\ncreate dy.buf $20 allot\nCDATA\n\n\\ Return the recordlength. Its the first thing.\n: dy-recordlen getsharedvars @ ;\n\n\\ Retrieve the string.\n: dy-string ( addr -- caddr n ) \n dup dy.name swap dy.namelen \n; \n\n\\ Create a constant from scratch by laying down some assembly\n\\ A key trick is that we have to lay down a pointer to \n\\ the first character of the defintion after we finish\n\\ See the definition above for the template\n: make-const \\ n s-addr c --\n\there 4+ >r \\ This should point to the newly-created header.\n\tmakeheader \\\n\n\\ This is what a constant looks like after emerging from the compiler.\t\n\\ ( 0002:0270 4CF8047D Lx.} ) str r7, [ r12, # $-04 ]!\n\\ ( 0002:0274 004F .O ) ldr r7, [ PC, # $00 ] ( @$20278=$7D04F84C )\n\\ ( 0002:0276 7047 pG ) bx LR\n\n\t$7D04F84C , \\ str r7, [ r12, # $-04 ]!\n\t$4f00 w, \\ ldr r7, [ PC, # $00 ]\n\t$4770 w, \\ bx LR\n\t, \t \\ Lay down the payload\n\n\tr> , \\ lay down the link field for the next word - required\n\t;\n\n\\ Take an XT of a VALUE, and stuff something in there.\n: dy-stuff ( n xt -- ) 8 + @ ! ; \n\n\\ Dump out an entry as a set of constants\n: dy-print \\ c-addr --\n S\" $\" type\n DUP dy.val . \\ Fetch the value\n \n DUP dy.type [CHAR] V = \\ check the type \n \n IF\n \tS\" VALUE \"\n ELSE\n \tS\" CONSTANT \"\n THEN\n TYPE \\ Display the result\n DUP dy.size . S\" x\" DUP dy.count .\n dy-string TYPE\n CR\n ; \n\n\\ Take a pointer to a dynamic link record, and add a constant to the dictionary\n: dy-create \\ addr --\n\tDUP \\ addr addr \n\tdy.val \\ c-addr n \n\tSWAP dy-string \\ n c-addr b\n make-const\n ;\n\n\\ Given a record address and a string, figure out\n\\ if thats the one we're looking for\n: dy-compare ( caddr n addr -- n ) \n dy-string compare \n;\n\n\\ Find the record in the list to go with a string\n: dy-find ( c-addr n -- addr|0 ) \n getsharedvars dy-recordlen + \\ Skip over the empty first record\n >R \\ Put it onto the return stack\n BEGIN\n R@ dy.val 0<>\n WHILE \n 2DUP R@ dy-compare\n \\ If we find it, clean the stack and leave the address on R\n 0= IF 2DROP R> EXIT THEN\n R> dy-recordlen + >R\n REPEAT\n \\ If we fall out, there will be a string caddr\/n on the stack\n 2DROP R> DROP \n 0 \\ Leave behind a zero to indicate failure\n;\n\n\\ Walk the table and make the constants.\n: dy-populate\n getsharedvars dy-recordlen + \\ Skip over the empty first record\n BEGIN \n dup dy.val 0<> \n WHILE\n dup dy-create\n dy-recordlen +\n REPEAT\n 2DROP R> DROP 0\n ; \n \n","old_contents":"\\ Code to support runtime\/dynamic into the C side via SAPI.\n\\\n\\ In the MPE environment, VALUEs work very well for this.\n\\ values are defined at compile time and can be updated at runtime.\n\n\n\\ ************************************************************************\n\\ ************************************************************************\n\\ Secondary support functions \n\\ ************************************************************************\n\\ ************************************************************************\n\n\\ *********************************************\n\\ Accessors - Tightly tied the data structure\n\\ *********************************************\n: dy.val @ ; \n: dy.size #4 + w@ ; \n: dy.count #6 + w@ ; \n: dy.type #8 + c@ ;\n: dy.namelen #9 + c@ ;\n: dy.name #12 + @ ;\n\n\\ Return the recordlength. Its the first thing.\n: dy-recordlen getsharedvars @ ;\n\n\\ Retrieve the string.\n: dy-string ( addr -- caddr n ) \n dup dy.name swap dy.namelen \n; \n\n\\ Create a constant from scratch by laying down some assembly\n\\ A key trick is that we have to lay down a pointer to \n\\ the first character of the defintion after we finish\n\\ See the definition above for the template\n: make-const \\ n s-addr c --\n\there 4+ >r \\ This should point to the newly-created header.\n\tmakeheader \\\n\n\\ This is what a constant looks like after emerging from the compiler.\t\n\\ ( 0002:0270 4CF8047D Lx.} ) str r7, [ r12, # $-04 ]!\n\\ ( 0002:0274 004F .O ) ldr r7, [ PC, # $00 ] ( @$20278=$7D04F84C )\n\\ ( 0002:0276 7047 pG ) bx LR\n\n\t$7D04F84C , \\ str r7, [ r12, # $-04 ]!\n\t$4f00 w, \\ ldr r7, [ PC, # $00 ]\n\t$4770 w, \\ bx LR\n\t, \t \\ Lay down the payload\n\n\tr> , \\ lay down the link field for the next word - required\n\t;\n\t\n\\ Dump out an entry as a set of constants\n: dy-print \\ c-addr --\n S\" $\" type\n DUP dy.val . \\ Fetch the value\n \n DUP dy.type [CHAR] V = \\ check the type \n \n IF\n \tS\" VALUE \"\n ELSE\n \tS\" CONSTANT \"\n THEN\n TYPE \\ Display the result\n DUP dy.size . S\" x\" DUP dy.count .\n dy-string TYPE\n CR\n ; \n\n\\ Take a pointer to a dynamic link record, and add a constant to the dictionary\n: dy-create \\ addr --\n\tDUP \\ addr addr \n\tdy.val \\ c-addr n \n\tSWAP dy-string \\ n c-addr b\n make-const\n ;\n\n\\ Given a record address and a string, figure out\n\\ if thats the one we're looking for\n: dy-compare ( caddr n addr -- n ) \n dy-string compare \n;\n\n\\ Find the record in the list to go with a string\n: dy-find ( c-addr n -- addr|0 ) \n getsharedvars dy-recordlen + \\ Skip over the empty first record\n >R \\ Put it onto the return stack\n BEGIN\n R@ dy.val 0<>\n WHILE \n 2DUP R@ dy-compare\n \\ If we find it, clean the stack and leave the address on R\n 0= IF 2DROP R> EXIT THEN\n R> dy-recordlen + >R\n REPEAT\n \\ If we fall out, there will be a string caddr\/n on the stack\n 2DROP R> DROP \n 0 \\ Leave behind a zero to indicate failure\n;\n\n\\ Walk the table and make the constants.\n: dy-populate\n getsharedvars dy-recordlen + \\ Skip over the empty first record\n BEGIN \n dup dy.val 0<> \n WHILE\n dup dy-create\n dy-recordlen +\n REPEAT\n 2DROP R> DROP 0\n ; \n \n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"37638f528ccd9c7f2beb640f694f7a2ccedb919d","subject":"use lex vars in (Math::Vector).cross","message":"use lex vars in (Math::Vector).cross\n","repos":"cooper\/ferret","old_file":"std\/Math\/Vector.frt","new_file":"std\/Math\/Vector.frt","new_contents":"package Math\nclass Vector\n#< Represents a [vector](https:\/\/en.wikipedia.org\/wiki\/Vector_space) of any\n#| dimension.\n\n$docOption_instanceName = \"v\"\n\n#> Creates a vector with the given components.\ninit {\n want @items: Num...\n if @dimension < 1\n throw Error(:DimensionError, \"Need dimension >= 1D\")\n}\n\n#> dimension of the vector\n.dimension -> @items.length\n\n#> human-readable dimension of the vector\n.dimensionHR -> @dimension + \"D\"\n\n#> magnitude of the vector\n.magnitude -> @items.map! { -> $_ ^ 2 }.sum.sqrt\n\n#> unit vector in the direction of this vector\n.unitVector -> *self \/ @magnitude\n\n#> returns the unit vector in the direction of the given axis\n.axisUnitVector {\n need $axis: VectorAxis #< axis number or letter, starting at 1 or \"i\"\n -> Vector.axisUnitVector(@dimension, $axis)\n}\n\n.x -> *self[0] #< for a >=1D vector, the first comonent\n.y -> *self[1] #< for a >=2D vector, the second component\n.z -> *self[2] #< for a >=3D vector, the third component\n\n#> for a 2D vector, its direction, measured in radians\n.direction {\n if @dimension != 2\n throw Error(:DimensionError, \"Direction only exists in 2D\")\n -> Math.atan2(@y, @x)\n}\n\n#> addition of two vectors\nop + {\n need $ehs: Vector\n if $ehs.dimension != @dimension\n throw Error(:DimensionError, \"Dimension mismatch $ehs.dimensionHR != @dimensionHR\")\n $items = gather for $i in 0..@items.lastIndex {\n take *self[$i] + $ehs[$i]\n }\n -> Vector(items: $items)\n}\n\n#> allows you to take the opposite vector `-$u`\nop - {\n need $lhs: Num\n if $lhs != 0\n throw(:InvalidOperation, \"Unsupported operation\")\n -> Vector(items: gather for $x in @items {\n take -$x\n })\n}\n\n#> subtraction of a vector from another\nop - {\n need $rhs: Vector\n if $rhs.dimension != @dimension\n throw Error(:DimensionError, \"Dimension mismatch $rhs.dimensionHR != @dimensionHR\")\n $items = gather for $i in 0..@items.lastIndex {\n take *self[$i] - $rhs[$i]\n }\n -> Vector(items: $items)\n}\n\n#> scalar multiplication of the vector\nop * {\n need $ehs: Num\n -> Vector(items: @items.map! { -> $_ * $ehs })\n}\n\n#> scalar division of the vector\nop \/ {\n need $rhs: Num\n -> *self * (1 \/ $rhs)\n}\n\n#> dot product of two vectors\nop * {\n need $ehs: Vector\n -> @dot($ehs)\n}\n\n#> vector equality\nop == {\n need $ehs: Vector\n if $ehs.dimension != @dimension\n -> false\n for $i in 0..@items.lastIndex {\n if *self[$i] == $ehs[$i]\n next\n -> false\n }\n -> true\n}\n\n#> dot product of this vector and another of the same dimension\n.dot {\n need $ehs: Vector\n if $ehs.dimension != @dimension\n throw Error(:DimensionError, \"Dimension mismatch $ehs.dimensionHR != @dimensionHR\")\n $dot = 0\n for $i in 0..@items.lastIndex {\n $dot += *self[$i] * $ehs[$i]\n }\n -> $dot\n}\n\n#> cross product of two 3D vectors\n.cross {\n need $ehs: Vector\n if $ehs.dimension != 3 || @dimension != 3\n throw Error(:DimensionError, \"Cross product only exists in 3D\")\n $a = *self[1] * $ehs[2] - *self[2] * $ehs[1]\n $b = *self[2] * $ehs[0] - *self[0] * $ehs[2]\n $c = *self[0] * $ehs[1] - *self[1] * $ehs[0]\n -> Vector($a, $b, $c)\n}\n\n#> angle between this vector and another of the same dimension, measured in\n#| radians\n.angleBetween {\n need $ehs: Vector\n # a\u00b7b = |a||b|cos\u03b8\n $cos\u03b8 = @dot($ehs) \/ (@magnitude * $ehs.magnitude)\n -> Math.acos($cos\u03b8)\n}\n\n#> true if this vector is orthogonal to another of the same dimension\n# consider: the dot product is also zero if either is a zero vector. should\n# we still -> true in that case?\n.orthogonalTo {\n need $ehs: Vector\n -> @dot($ehs) == 0\n}\n\n#> true if this vector is parallel to another of the same dimension\n.parallelTo {\n need $ehs: Vector\n if $ehs.dimension != @dimension\n throw Error(:DimensionError, \"Dimension mismatch $ehs.dimensionHR != @dimensionHR\")\n $u1 = @unitVector\n $u2 = $ehs.unitVector\n if $u1 == $u2 || -$u1 == $u2\n -> true\n -> false\n}\n\n#> fetches the component at the given index. Allows Vector to conform to\n#| IndexedRead such that `$vector[N]` is the N+1th component.\n.getValue {\n need $index: Num\n $n = $index + 1\n if @dimension < $n\n throw Error(:DimensionError, \"@dimensionHR vector has no component $n\")\n -> @items[$index]\n}\n\n#> returns a copy of the vector\nmethod copy -> Vector(items: @items.copy!)\n\n.description -> \"<\" + @items.join(\", \") + \">\"\n\n#> returns the zero vector in the given dimension\nfunc zeroVector {\n need $dimension: Num\n if $dimension < 1\n throw Error(:DimensionError, \"Need dimension >= 1D\")\n -> Vector(items: gather for $i in 1..$dimension { take 0 })\n}\n\n#> returns the unit vector for the given dimension and axis\nfunc axisUnitVector {\n need $dimension: Num\n need $axis: VectorAxis #< axis number or letter, starting at 1 or \"i\"\n if $dimension < 1\n throw Error(:DimensionError, \"Need dimension >= 1D\")\n $items = gather for $i in 1..$dimension {\n if $i == $axis {\n take 1\n next\n }\n take 0\n }\n -> Vector(items: $items)\n}\n\nfunc _axisToNumber {\n need $axis: Num | Char\n if $axis.*isa(Num)\n -> $axis\n $o = $axis.ord\n if $o > 119\n -> $o - 119\n -> $o - 104\n}\n\n#> An interface which accepts an axis letter starting at \"i\" or number starting\n#| at 1. For instance, a 3D vector is represented by axes i, j, and k, which\n#| correspond to the numbers 1, 2, and 3, respectively.\ntype VectorAxis {\n #> converts letters starting at 'i' to axis numbers\n transform _axisToNumber($_)\n}\n","old_contents":"package Math\nclass Vector\n#< Represents a [vector](https:\/\/en.wikipedia.org\/wiki\/Vector_space) of any\n#| dimension.\n\n$docOption_instanceName = \"v\"\n\n#> Creates a vector with the given components.\ninit {\n want @items: Num...\n if @dimension < 1\n throw Error(:DimensionError, \"Need dimension >= 1D\")\n}\n\n#> dimension of the vector\n.dimension -> @items.length\n\n#> human-readable dimension of the vector\n.dimensionHR -> @dimension + \"D\"\n\n#> magnitude of the vector\n.magnitude -> @items.map! { -> $_ ^ 2 }.sum.sqrt\n\n#> unit vector in the direction of this vector\n.unitVector -> *self \/ @magnitude\n\n#> returns the unit vector in the direction of the given axis\n.axisUnitVector {\n need $axis: VectorAxis #< axis number or letter, starting at 1 or \"i\"\n -> Vector.axisUnitVector(@dimension, $axis)\n}\n\n.x -> *self[0] #< for a >=1D vector, the first comonent\n.y -> *self[1] #< for a >=2D vector, the second component\n.z -> *self[2] #< for a >=3D vector, the third component\n\n#> for a 2D vector, its direction, measured in radians\n.direction {\n if @dimension != 2\n throw Error(:DimensionError, \"Direction only exists in 2D\")\n -> Math.atan2(@y, @x)\n}\n\n#> addition of two vectors\nop + {\n need $ehs: Vector\n if $ehs.dimension != @dimension\n throw Error(:DimensionError, \"Dimension mismatch $ehs.dimensionHR != @dimensionHR\")\n $items = gather for $i in 0..@items.lastIndex {\n take *self[$i] + $ehs[$i]\n }\n -> Vector(items: $items)\n}\n\n#> allows you to take the opposite vector `-$u`\nop - {\n need $lhs: Num\n if $lhs != 0\n throw(:InvalidOperation, \"Unsupported operation\")\n -> Vector(items: gather for $x in @items {\n take -$x\n })\n}\n\n#> subtraction of a vector from another\nop - {\n need $rhs: Vector\n if $rhs.dimension != @dimension\n throw Error(:DimensionError, \"Dimension mismatch $rhs.dimensionHR != @dimensionHR\")\n $items = gather for $i in 0..@items.lastIndex {\n take *self[$i] - $rhs[$i]\n }\n -> Vector(items: $items)\n}\n\n#> scalar multiplication of the vector\nop * {\n need $ehs: Num\n -> Vector(items: @items.map! { -> $_ * $ehs })\n}\n\n#> scalar division of the vector\nop \/ {\n need $rhs: Num\n -> *self * (1 \/ $rhs)\n}\n\n#> dot product of two vectors\nop * {\n need $ehs: Vector\n -> @dot($ehs)\n}\n\n#> vector equality\nop == {\n need $ehs: Vector\n if $ehs.dimension != @dimension\n -> false\n for $i in 0..@items.lastIndex {\n if *self[$i] == $ehs[$i]\n next\n -> false\n }\n -> true\n}\n\n#> dot product of this vector and another of the same dimension\n.dot {\n need $ehs: Vector\n if $ehs.dimension != @dimension\n throw Error(:DimensionError, \"Dimension mismatch $ehs.dimensionHR != @dimensionHR\")\n $dot = 0\n for $i in 0..@items.lastIndex {\n $dot += *self[$i] * $ehs[$i]\n }\n -> $dot\n}\n\n#> cross product of two 3D vectors\n.cross {\n need $ehs: Vector\n if $ehs.dimension != 3 || @dimension != 3\n throw Error(:DimensionError, \"Cross product only exists in 3D\")\n @a = *self[1] * $ehs[2] - *self[2] * $ehs[1]\n @b = *self[2] * $ehs[0] - *self[0] * $ehs[2]\n @c = *self[0] * $ehs[1] - *self[1] * $ehs[0]\n -> Vector(@a, @b, @c)\n}\n\n#> angle between this vector and another of the same dimension, measured in\n#| radians\n.angleBetween {\n need $ehs: Vector\n # a\u00b7b = |a||b|cos\u03b8\n $cos\u03b8 = @dot($ehs) \/ (@magnitude * $ehs.magnitude)\n -> Math.acos($cos\u03b8)\n}\n\n#> true if this vector is orthogonal to another of the same dimension\n# consider: the dot product is also zero if either is a zero vector. should\n# we still -> true in that case?\n.orthogonalTo {\n need $ehs: Vector\n -> @dot($ehs) == 0\n}\n\n#> true if this vector is parallel to another of the same dimension\n.parallelTo {\n need $ehs: Vector\n if $ehs.dimension != @dimension\n throw Error(:DimensionError, \"Dimension mismatch $ehs.dimensionHR != @dimensionHR\")\n $u1 = @unitVector\n $u2 = $ehs.unitVector\n if $u1 == $u2 || -$u1 == $u2\n -> true\n -> false\n}\n\n#> fetches the component at the given index. Allows Vector to conform to\n#| IndexedRead such that `$vector[N]` is the N+1th component.\n.getValue {\n need $index: Num\n $n = $index + 1\n if @dimension < $n\n throw Error(:DimensionError, \"@dimensionHR vector has no component $n\")\n -> @items[$index]\n}\n\n#> returns a copy of the vector\nmethod copy -> Vector(items: @items.copy!)\n\n.description -> \"<\" + @items.join(\", \") + \">\"\n\n#> returns the zero vector in the given dimension\nfunc zeroVector {\n need $dimension: Num\n if $dimension < 1\n throw Error(:DimensionError, \"Need dimension >= 1D\")\n -> Vector(items: gather for $i in 1..$dimension { take 0 })\n}\n\n#> returns the unit vector for the given dimension and axis\nfunc axisUnitVector {\n need $dimension: Num\n need $axis: VectorAxis #< axis number or letter, starting at 1 or \"i\"\n if $dimension < 1\n throw Error(:DimensionError, \"Need dimension >= 1D\")\n $items = gather for $i in 1..$dimension {\n if $i == $axis {\n take 1\n next\n }\n take 0\n }\n -> Vector(items: $items)\n}\n\nfunc _axisToNumber {\n need $axis: Num | Char\n if $axis.*isa(Num)\n -> $axis\n $o = $axis.ord\n if $o > 119\n -> $o - 119\n -> $o - 104\n}\n\n#> An interface which accepts an axis letter starting at \"i\" or number starting\n#| at 1. For instance, a 3D vector is represented by axes i, j, and k, which\n#| correspond to the numbers 1, 2, and 3, respectively.\ntype VectorAxis {\n #> converts letters starting at 'i' to axis numbers\n transform _axisToNumber($_)\n}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"32c36fe2d287624f1f39b60fd29ffc4798d79850","subject":"boot: update copyright like done on stable branch","message":"boot: update copyright like done on stable branch\n","repos":"opnsense\/core,opnsense\/core,opnsense\/core,opnsense\/core,opnsense\/core,opnsense\/core","old_file":"src\/boot\/logo-hourglass.4th","new_file":"src\/boot\/logo-hourglass.4th","new_contents":"\\ Copyright (c) 2006-2015 Devin Teske \n\\ Copyright (c) 2016-2017 Deciso B.V.\n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\n48 logoX ! 9 logoY ! \\ Initialize logo placement defaults\n\n: logo+ ( x y c-addr\/u -- x y' )\n\t2swap 2dup at-xy 2swap \\ position the cursor\n\t[char] # escc! \\ replace # with Esc\n\ttype \\ print to the screen\n\t1+ \\ increase y for next time we're called\n;\n\n: logo ( x y -- ) \\ color hourglass logo (15 rows x 32 columns)\n\n\ts\" #[37;1m @@@@@@@@@@@@@@@@@@@@@@@@@@@@\" logo+\n\ts\" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\" logo+\n\ts\" @@@@@ @@@@@\" logo+\n\ts\" @@@@@ @@@@@ \" logo+\n\ts\" @@@@@@@@@@@ @@@@@@@@@@@\" logo+\n\ts\" #[31;1m\\\\\\\\\\ \/\/\/\/\/ \" logo+\n\ts\" )))))))))))) (((((((((((\" logo+\n\ts\" \/\/\/\/\/ \\\\\\\\\\ #[m\" logo+\n\ts\" #[37;1m @@@@@@@@@@@ @@@@@@@@@@@\" logo+\n\ts\" @@@@@ @@@@@ \" logo+\n\ts\" @@@@@ @@@@@\" logo+\n\ts\" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\" logo+\n\ts\" @@@@@@@@@@@@@@@@@@@@@@@@@@@@ \" logo+\n\ts\" #[m \" logo+\n\ts\" 17.7 ``Insert Name Here'' #[m\" logo+\n\n\t2drop\n;\n","old_contents":"\\ Copyright (c) 2006-2015 Devin Teske \n\\ Copyright (c) 2016 Deciso B.V.\n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\n48 logoX ! 9 logoY ! \\ Initialize logo placement defaults\n\n: logo+ ( x y c-addr\/u -- x y' )\n\t2swap 2dup at-xy 2swap \\ position the cursor\n\t[char] # escc! \\ replace # with Esc\n\ttype \\ print to the screen\n\t1+ \\ increase y for next time we're called\n;\n\n: logo ( x y -- ) \\ color hourglass logo (15 rows x 32 columns)\n\n\ts\" #[37;1m @@@@@@@@@@@@@@@@@@@@@@@@@@@@\" logo+\n\ts\" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\" logo+\n\ts\" @@@@@ @@@@@\" logo+\n\ts\" @@@@@ @@@@@ \" logo+\n\ts\" @@@@@@@@@@@ @@@@@@@@@@@\" logo+\n\ts\" #[31;1m\\\\\\\\\\ \/\/\/\/\/ \" logo+\n\ts\" )))))))))))) (((((((((((\" logo+\n\ts\" \/\/\/\/\/ \\\\\\\\\\ #[m\" logo+\n\ts\" #[37;1m @@@@@@@@@@@ @@@@@@@@@@@\" logo+\n\ts\" @@@@@ @@@@@ \" logo+\n\ts\" @@@@@ @@@@@\" logo+\n\ts\" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\" logo+\n\ts\" @@@@@@@@@@@@@@@@@@@@@@@@@@@@ \" logo+\n\ts\" #[m \" logo+\n\ts\" 17.7 ``Insert Name Here'' #[m\" logo+\n\n\t2drop\n;\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"cbc2eb5fe4403d8a643131f9726896bf7857ed90","subject":"Move things around a little.","message":"Move things around a little.","repos":"rbsexton\/gecko,rbsexton\/gecko,rbsexton\/gecko","old_file":"zero\/clock-umb\/forth\/Clock.fth","new_file":"zero\/clock-umb\/forth\/Clock.fth","new_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( -- ) \n init-idata\n load-defaults \n icroot 0 over inter.rtcsem ! \\ Reset the free-running counters.\n 0 over inter.rtcdsem ! \\ Reset the free-running counters.\n\n begin \n \tdup inter.rtcsem @offex! ?dup if advancehms then\n \tdup inter.rtcdsem @offex! ?dup if advancedhms then\n [asm wfi asm]\n uiupdate if use-uivals else use-clockvals then \n key? until drop\n;\n \n\\ These two contain loops to ensure that we don't\n\\ drop any timer ticks on the floor.\n: ADVANCEHMS ( n -- ) 0 do hms advancetime loop ;\n: ADVANCEDHMS ( n -- ) 0 do dhms advancetime loop ;\n \n: LOAD-DEFAULTS ( -- )\n nvramvalid? if _nvramload then \n interp-init\n;\n\n\\ ----------------------------------------------------------\n\\ Define the structures before they get used.\n\\ ----------------------------------------------------------\nstruct ODN \\ On-Deck Needle \n\tint odn.s\n\tint odn.m\n\tint odn.h\nend-struct\n\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxsec \\ Max Value for secs+minutes\n\tint hms.maxhour \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_m \\ increment the minutes + hours\nend-struct\n\nstruct _interp_set\n\t4 cells field interp.a\n\t4 cells field interp.b\n\t4 cells field interp.c\nend-struct\n\n\\ ----------------------------------------------------------\n\\ Defaults get saved in the user data page.\n\\ ----------------------------------------------------------\n: NVRAMVALID? ( -- t\/f ) \n\\ *G See if there is valid data in the NVRAM.\n\\ ** It consists of 3 words. If any of them are \n\\ ** set to 0xffff:ffff, we go with the defaults.\n _USERDATA\n dup @ -1 <> \n over 4 + @ -1 <> and\n swap 8 + @ -1 <> and\n;\n\n: _NVRAMLOAD ( -- ) \n\\ *G Pull the needle maximums from flash.\n $C 0 do I ud@ needle_max I + ! 4 +loop \n; \n\n: NVRAM! ( addr -- )\n\\ *G Save the contents of the needle cal values.\n 0 UDPAGE_ERASE\n ( addr )\n $C 0 do dup I + @ I ud! 4 +loop\n drop \n;\n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nidata\ncreate ODN_HMS odn allot \\ On-Deck, HMS\ncreate ODN_DHMS odn allot \\ On-Deck, DHMS\ncreate ODN_UI odn allot \\ On-Deck, Generated by the UI.\ncdata\n\nidata \\ Has to match an odn.\ncreate NEEDLE_MAX #850 , #850 , #850 ,\ncdata\n\n(( \n: interp-next drop 1 ; \n: interp-reset drop .\" Reset\" ; \n\t\n))\n\n: RANGECHECK ( max n -- n or zero ) 2dup <= if 2drop 0 else swap drop then ; \n: QUADCLIP ( n -- n) \\ Force the contents to be legal ( 0-999 )\n dup 0 < if drop 0 exit then \n dup #999 > if drop #999 then \n;\n \n: INTER-BUMP ( max old interp -- new )\n\\ *G Get the next value from the interpolator, and \n\\ ** reset the interpolator if it wraps around to zero.\n >R R@ interp-next \\ Get the max \n + rangecheck \n dup 0= if R> interp-reset else R> drop then \n ; \n\n: NFETCH ( odn off -- max old )\n\\ *G Combine the current value with the maximum.\n >R R@ \\ stash the offset.\n + @ \\ Calculate the offset address, get the current val.\n needle_max R> + @\n swap \n;\n\n: ++NEEDLE_S \\ Called every time.\n odn_hms 0 odn.s nfetch ( max old )\n\tinterp_hms interp.a inter-bump ( new )\n\todn_hms odn.s ! \n\t;\n\n: ++NEEDLE_M ( -- )\n\\ *G Every time we roll the seconds, bump the minutes and the hour\n\todn_hms 0 odn.m nfetch ( max old )\n\tinterp_hms interp.b inter-bump \n\todn_hms odn.m ! \n\n\todn_hms 0 odn.h nfetch ( max old )\n\tinterp_hms interp.c inter-bump \n\todn_hms odn.h ! \n\t;\n\n: ++NEEDLE_DS ; \\ Called every time.\n: ++NEEDLE_DM ; \\ Every time we roll the seconds.\n\n: _USE ( odn-addr -- ) \n dup odn.s w@ pwm0!\n dup odn.m w@ pwm1!\n odn.h w@ pwm2!\n ;\n\n: USE-CLOCKVALS odn_hms _use ; \n: USE-UIVALS odn_ui _use ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Quadrature\n\\ ----------------------------------------------------------\n\n_timer1 $24 + equ QUAD-IN\n\n\\ The Quadrature encoder produces two per detent.\n: QUAD@ ( -- n ) \\ Fetch and zero\n quad-in @off \n [asm sxth tos, tos asm]\n [asm asr .s tos, tos, # 1 asm] \\ Divide by two,\n ;\n \n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_ds , ' ++needle_dm , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n: ADVANCETIME ( struct-addr -- )\n dup hms.w_s @ execute \\ Invoke the official update word.\n 1 over hms.subsec +! \\ Increment\n dup hms.subsec @\n over hms.maxsubsec @ < if drop exit then \\ If less then max, we're done\n 0 over hms.subsec ! \\ Reset the subsecs \n\n 1 over hms.s +!\n dup hms.s @ over hms.maxsec @ < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n dup hms.w_m @ execute\n 1 over hms.m +!\n dup hms.m @ over hms.maxsec @ < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ over hms.maxhour @ < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ----------------------------------------------------------\n\\ The interpolator. \n\\ Implement bresenhams algorithm. All of this code already\n\\ exists in C, but we'll own the data structures. They contain\n\\ A total of 4 words - fixed, err, num, & denom\n\\ ----------------------------------------------------------\nudata \ncreate interp_hms _interp_set allot\ncreate interp_dhms _interp_set allot \ncdata\n\n#16 #60 * equ raw_sec\n#10 #100 * equ raw_dsec\n\n: INTERP-INIT ( -- )\n (interp_init) interp_hms\n 2dup interp.a needle_max @ raw_sec call3-- \n 2dup interp.b needle_max 4 + @ #60 call3-- \n interp.c needle_max 8 + @ #24 #60 * call3--\n\n (interp_init) interp_dhms\n 2dup interp.a needle_max @ raw_dsec call3-- \n 2dup interp.b needle_max 4 + @ #100 call3-- \n interp.c needle_max 8 + @ #10 #100 * call3--\n;\n\n\\ Call the reset fn.\n: INTERP-RESET ( interp_addr -- )\n (interp_reset) swap call1-- \n;\n\n: INTERP-NEXT ( addr -- n )\n (interp_next) swap call1--n\n;\n\n\\ ----------------------------------------------------------\n\\ ----------------------------------------------------------\n\\ User Interface\n\\ ----------------------------------------------------------\n\\ ----------------------------------------------------------\nvariable uistate\nvariable uicount \n\n_GPIO $64 + equ _BUTTONIO\n: BUTTONUP? ( -- t\/f ) _buttonio @ 1 and ; \n: BUTTONDOWN? ( -- t\/f ) buttonup? 1 xor ; \n\n\\ The wrapper for all of the UI stuff.\n\\ Returns true if the UI is active - ie, use the values generated by the UI.\n: UIUPDATE ( -- t\/f )\n StateHandlers uistate @ + @ execute \n; \n\n: uitest \n uistate @ 4 \/ . .\" ->\" uiupdate uistate @ 4 \/ .\n uicount @ . if .\" True\" else .\" False\" then \n; \n\n\\ -----------------------------------------------\n\\ State numbers. These are defined x4 so that\n\\ we can just use the state number as an index \n\\ into a table of words.\n\\ -----------------------------------------------\n0 4 * equ _s_init\n1 4 * equ _s_b1\n2 4 * equ _s_1sec\n\n3 4 * equ _s_shSetH\n4 4 * equ _s_pendset_m\n5 4 * equ _s_setmin\n\n6 4 * equ _s_pendcal0\n7 4 * equ _s_cal0\n8 4 * equ _s_pendcalh\n9 4 * equ _s_calh\n10 4 * equ _s_pendcalm\n11 4 * equ _s_calm\n12 4 * equ _s_pendcals\n13 4 * equ _s_cals\n\n4 equ downcount_1s\n16 equ downcount_3s \n\n\\ All of the state handlers.\n\\ Everybody needs to know the state of the button, so that must\n\\ get passed in, thus they all look like this:\n\\ state ( t\/f -- t\/f )\n: shInit false \n buttondown? if \n _s_b1 uistate !\n uicount off \\ Reset this.\n then\n ;\n\n\\ Waiting for a full second to go by.\n: shB1 false\n buttonup? if _s_init uistate ! exit then\n \\ The Button is down. \n uicount @ downcount_1s >= if\n _s_1sec uistate !\n else \n 1 uicount +!\n\tthen\n ;\n\n\\ We're in the 1 second state\n: sh1sec true \n buttonup? if shseth_entry exit then\n uicount @ downcount_3s >= if\n _s_pendcal0 uistate !\n else \n 1 uicount +!\n\tthen \n;\n\n\\ -------------------------------------------------\n\\ Setting the time\n\\ -------------------------------------------------\n: shSetH_entry \n _s_shseth uistate ! \n adj_i off \\ Set the index to zero\n needle_max odn.h @ #24 make-set-list \n; \n\n: shSetH true buttondown? if shPendSetM_entry exit then\n adj_i @ quad@ - 24 mod \\ Now we have the next index.\n dup 0< if #24 + then \\ Negative wrap-around isn't cool\n dup adj_i ! \\ Save it.\n adj_points[]@ \\ Get the new value.\n odn_ui odn.h ! \n ;\n\n\n: shPendSetM_entry _s_pendset_m uistate ! ;\n\n: shPendSetM true buttonup? if _s_setmin uistate ! then ;\n: shSetMin true buttondown? if _s_init uistate ! exit then ;\n\n\\ -------------------------------------------------\n\\ Calibration\n\\ -------------------------------------------------\n: shPendCal0 true buttonup? if _s_cal0 uistate ! helpODNClear then ;\n: shCal0 true buttondown? if _s_pendcalh uistate ! exit then ;\n\n: shPendCalH true buttonup? if _s_calh uistate ! helpODNMid then ; \n: shCalH true buttondown? if _s_pendcalm uistate ! exit then \n odn_ui odn.h helpQuad@ ; \n\n: shPendCalM true buttonup? if _s_calm uistate ! then ; \n: shCalM true buttondown? if _s_pendcals uistate ! exit then \n odn_ui odn.m helpQuad@ ; \n\n: shPendCalS true buttonup? if _s_cals uistate ! then ; \n: shCalS true buttondown? if \n _s_init uistate !\n odn_ui nvram! exit then \n \n odn_ui odn.s helpQuad@ ; \n\n\\ -------------------------------------------------\n\\ Helpers\n\\ -------------------------------------------------\n: helpODNClear ( -- ) \\ Set them all to zero\n odn_ui odn bounds do I off 4 +loop ; \n: helpODNMid ( -- ) \\ Set them all to 500\n odn_ui odn bounds do #750 I ! 4 +loop ; \n: helpQuad@ ( addr -- ) \\ update a location with the quadrature value\n dup @ quad@ + quadclip swap ! ;\n\n\ncreate StateHandlers \n' shInit , \n' shB1 ,\n' sh1sec ,\n\n' shSetH ,\n' shPendSetM , ' shSetMin ,\n\n' shPendCal0 , ' shCal0 ,\n' shPendCalH , ' shCalH , \n' shPendCalM , ' shCalM , \n' shPendCalS , ' shCalS , \n\n\\ -------------------------------------------------\n\\ Setting the time.\n\\ -------------------------------------------------\nvariable adj_i \\ THe working index into the points array.\n\nudata \ncreate adj_points #50 cells allot \\ 100 16-bit words. \ncreate interp_set _interp_set allot\ncdata \n\n\\ Generate a list of points.\n: MAKE-SET-LIST ( max steps ) \n 2dup \n >R (interp_init) swap interp_set swap R> call3--\n\n \\ Since zero is first, do the w! first.\n swap drop 0 swap \\ Keep a running counter.\n 0 do\n dup I adj_points[]! \\ Save the existing value\n interp_set interp-next + \n loop\n drop\n ;\n\n: ADJ_POINTS[]! ( data index -- ) 2* adj_points + w! ;\n: ADJ_POINTS[]@ ( index -- n ) 2* adj_points + w@ ;\n","old_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( -- ) \n init-idata\n load-defaults \n icroot 0 over inter.rtcsem ! \\ Reset the free-running counters.\n 0 over inter.rtcdsem ! \\ Reset the free-running counters.\n\n begin \n \tdup inter.rtcsem @offex! ?dup if advancehms then\n \tdup inter.rtcdsem @offex! ?dup if advancedhms then\n [asm wfi asm]\n uiupdate if use-uivals else use-clockvals then \n key? until drop\n;\n \n\\ These two contain loops to ensure that we don't\n\\ drop any timer ticks on the floor.\n: ADVANCEHMS ( n -- ) 0 do hms advancetime loop ;\n: ADVANCEDHMS ( n -- ) 0 do dhms advancetime loop ;\n \n: LOAD-DEFAULTS ( -- )\n nvramvalid? if _nvramload then \n interp-init\n;\n\n\\ ----------------------------------------------------------\n\\ Define the structures before they get used.\n\\ ----------------------------------------------------------\nstruct ODN \\ On-Deck Needle \n\tint odn.s\n\tint odn.m\n\tint odn.h\nend-struct\n\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxsec \\ Max Value for secs+minutes\n\tint hms.maxhour \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_m \\ increment the minutes + hours\nend-struct\n\nstruct _interp_set\n\t4 cells field interp.a\n\t4 cells field interp.b\n\t4 cells field interp.c\nend-struct\n\n\\ ----------------------------------------------------------\n\\ Defaults get saved in the user data page.\n\\ ----------------------------------------------------------\n: NVRAMVALID? ( -- t\/f ) \n\\ *G See if there is valid data in the NVRAM.\n\\ ** It consists of 3 words. If any of them are \n\\ ** set to 0xffff:ffff, we go with the defaults.\n _USERDATA\n dup @ -1 <> \n over 4 + @ -1 <> and\n swap 8 + @ -1 <> and\n;\n\n: _NVRAMLOAD ( -- ) \n\\ *G Pull the needle maximums from flash.\n $C 0 do I ud@ needle_max I + ! 4 +loop \n; \n\n: NVRAM! ( addr -- )\n\\ *G Save the contents of the needle cal values.\n 0 UDPAGE_ERASE\n ( addr )\n $C 0 do dup I + @ I ud! 4 +loop\n drop \n;\n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nidata\ncreate ODN_HMS odn allot \\ On-Deck, HMS\ncreate ODN_DHMS odn allot \\ On-Deck, DHMS\ncreate ODN_UI odn allot \\ On-Deck, Generated by the UI.\ncdata\n\nidata \\ Has to match an odn.\ncreate NEEDLE_MAX #850 , #850 , #850 ,\ncdata\n\n(( \n: interp-next drop 1 ; \n: interp-reset drop .\" Reset\" ; \n\t\n))\n\n: RANGECHECK ( max n -- n or zero ) 2dup <= if 2drop 0 else swap drop then ; \n: QUADCLIP ( n -- n) \\ Force the contents to be legal ( 0-999 )\n dup 0 < if drop 0 exit then \n dup #999 > if drop #999 then \n;\n \n: INTER-BUMP ( max old interp -- new )\n\\ *G Get the next value from the interpolator, and \n\\ ** reset the interpolator if it wraps around to zero.\n >R R@ interp-next \\ Get the max \n + rangecheck \n dup 0= if R> interp-reset else R> drop then \n ; \n\n: NFETCH ( odn off -- max old )\n\\ *G Combine the current value with the maximum.\n >R R@ \\ stash the offset.\n + @ \\ Calculate the offset address, get the current val.\n needle_max R> + @\n swap \n;\n\n: ++NEEDLE_S \\ Called every time.\n odn_hms 0 odn.s nfetch ( max old )\n\tinterp_hms interp.a inter-bump ( new )\n\todn_hms odn.s ! \n\t;\n\n: ++NEEDLE_M ( -- )\n\\ *G Every time we roll the seconds, bump the minutes and the hour\n\todn_hms 0 odn.m nfetch ( max old )\n\tinterp_hms interp.b inter-bump \n\todn_hms odn.m ! \n\n\todn_hms 0 odn.h nfetch ( max old )\n\tinterp_hms interp.c inter-bump \n\todn_hms odn.h ! \n\t;\n\n: ++NEEDLE_DS ; \\ Called every time.\n: ++NEEDLE_DM ; \\ Every time we roll the seconds.\n\n: _USE ( odn-addr -- ) \n dup odn.s w@ pwm0!\n dup odn.m w@ pwm1!\n odn.h w@ pwm2!\n ;\n\n: USE-CLOCKVALS odn_hms _use ; \n: USE-UIVALS odn_ui _use ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Quadrature\n\\ ----------------------------------------------------------\n\n_timer1 $24 + equ QUAD-IN\n\n\\ The Quadrature encoder produces two per detent.\n: QUAD@ ( -- n ) \\ Fetch and zero\n quad-in @off \n [asm sxth tos, tos asm]\n [asm asr .s tos, tos, # 1 asm] \\ Divide by two,\n ;\n \n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_ds , ' ++needle_dm , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n: ADVANCETIME ( struct-addr -- )\n dup hms.w_s @ execute \\ Invoke the official update word.\n 1 over hms.subsec +! \\ Increment\n dup hms.subsec @\n over hms.maxsubsec @ < if drop exit then \\ If less then max, we're done\n 0 over hms.subsec ! \\ Reset the subsecs \n\n 1 over hms.s +!\n dup hms.s @ over hms.maxsec @ < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n dup hms.w_m @ execute\n 1 over hms.m +!\n dup hms.m @ over hms.maxsec @ < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ over hms.maxhour @ < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ----------------------------------------------------------\n\\ The interpolator. \n\\ Implement bresenhams algorithm. All of this code already\n\\ exists in C, but we'll own the data structures. They contain\n\\ A total of 4 words - fixed, err, num, & denom\n\\ ----------------------------------------------------------\nudata \ncreate interp_hms _interp_set allot\ncreate interp_dhms _interp_set allot \ncdata\n\n#16 #60 * equ raw_sec\n#10 #100 * equ raw_dsec\n\n: INTERP-INIT ( -- )\n (interp_init) interp_hms\n 2dup interp.a needle_max @ raw_sec call3-- \n 2dup interp.b needle_max 4 + @ #60 call3-- \n interp.c needle_max 8 + @ #24 #60 * call3--\n\n (interp_init) interp_dhms\n 2dup interp.a needle_max @ raw_dsec call3-- \n 2dup interp.b needle_max 4 + @ #100 call3-- \n interp.c needle_max 8 + @ #10 #100 * call3--\n;\n\n\\ Call the reset fn.\n: INTERP-RESET ( interp_addr -- )\n (interp_reset) swap call1-- \n;\n\n: INTERP-NEXT ( addr -- n )\n (interp_next) swap call1--n\n;\n\n\\ ----------------------------------------------------------\n\\ ----------------------------------------------------------\n\\ User Interface\n\\ ----------------------------------------------------------\n\\ ----------------------------------------------------------\nvariable uistate\nvariable uicount \n\n_GPIO $64 + equ _BUTTONIO\n: BUTTONUP? ( -- t\/f ) _buttonio @ 1 and ; \n: BUTTONDOWN? ( -- t\/f ) buttonup? 1 xor ; \n\n\\ The wrapper for all of the UI stuff.\n\\ Returns true if the UI is active - ie, use the values generated by the UI.\n: UIUPDATE ( -- t\/f )\n StateHandlers uistate @ + @ execute \n; \n\n: uitest \n uistate @ 4 \/ . .\" ->\" uiupdate uistate @ 4 \/ .\n uicount @ . if .\" True\" else .\" False\" then \n; \n\n\\ -----------------------------------------------\n\\ State numbers. These are defined x4 so that\n\\ we can just use the state number as an index \n\\ into a table of words.\n\\ -----------------------------------------------\n0 4 * equ _s_init\n1 4 * equ _s_b1\n2 4 * equ _s_1sec\n\n3 4 * equ _s_shSetH\n4 4 * equ _s_pendset_m\n5 4 * equ _s_setmin\n\n6 4 * equ _s_pendcal0\n7 4 * equ _s_cal0\n8 4 * equ _s_pendcalh\n9 4 * equ _s_calh\n10 4 * equ _s_pendcalm\n11 4 * equ _s_calm\n12 4 * equ _s_pendcals\n13 4 * equ _s_cals\n\n4 equ downcount_1s\n16 equ downcount_3s \n\n\\ All of the state handlers.\n\\ Everybody needs to know the state of the button, so that must\n\\ get passed in, thus they all look like this:\n\\ state ( t\/f -- t\/f )\n: shInit false \n buttondown? if \n _s_b1 uistate !\n uicount off \\ Reset this.\n then\n ;\n\n\\ Waiting for a full second to go by.\n: shB1 false\n buttonup? if _s_init uistate ! exit then\n \\ The Button is down. \n uicount @ downcount_1s >= if\n _s_1sec uistate !\n else \n 1 uicount +!\n\tthen\n ;\n\n\\ We're in the 1 second state\n: sh1sec true \n buttonup? if shseth_entry _s_shseth uistate ! exit then\n uicount @ downcount_3s >= if\n _s_pendcal0 uistate !\n else \n 1 uicount +!\n\tthen \n;\n\n\\ -------------------------------------------------\n\\ Setting the time\n\\ -------------------------------------------------\n: shSetH_entry \n adj_i off \\ Set the index to zero\n needle_max odn.h @ #24 make-set-list \n; \n\n: shSetH true buttondown? if _s_pendset_m uistate ! exit then\n adj_i @ quad@ - 24 mod \\ Now we have the next index.\n dup 0< if #24 + then \\ Negative wrap-around isn't cool\n dup adj_i ! \\ Save it.\n adj_points[]@ \\ Get the new value.\n odn_ui odn.h ! \n ;\n\n: shPendSetM true buttonup? if _s_setmin uistate ! then ;\n: shSetMin true buttondown? if _s_init uistate ! exit then ;\n\n\\ -------------------------------------------------\n\\ Calibration\n\\ -------------------------------------------------\n: shPendCal0 true buttonup? if _s_cal0 uistate ! helpODNClear then ;\n: shCal0 true buttondown? if _s_pendcalh uistate ! exit then ;\n\n: shPendCalH true buttonup? if _s_calh uistate ! helpODNMid then ; \n: shCalH true buttondown? if _s_pendcalm uistate ! exit then \n odn_ui odn.h helpQuad@ ; \n\n: shPendCalM true buttonup? if _s_calm uistate ! then ; \n: shCalM true buttondown? if _s_pendcals uistate ! exit then \n odn_ui odn.m helpQuad@ ; \n\n: shPendCalS true buttonup? if _s_cals uistate ! then ; \n: shCalS true buttondown? if \n _s_init uistate !\n odn_ui nvram! exit then \n \n odn_ui odn.s helpQuad@ ; \n\n\\ -------------------------------------------------\n\\ Helpers\n\\ -------------------------------------------------\n: helpODNClear ( -- ) \\ Set them all to zero\n odn_ui odn bounds do I off 4 +loop ; \n: helpODNMid ( -- ) \\ Set them all to 500\n odn_ui odn bounds do #750 I ! 4 +loop ; \n: helpQuad@ ( addr -- ) \\ update a location with the quadrature value\n dup @ quad@ + quadclip swap ! ;\n\n\ncreate StateHandlers \n' shInit , \n' shB1 ,\n' sh1sec ,\n\n' shSetH ,\n' shPendSetM , ' shSetMin ,\n\n' shPendCal0 , ' shCal0 ,\n' shPendCalH , ' shCalH , \n' shPendCalM , ' shCalM , \n' shPendCalS , ' shCalS , \n\n\\ -------------------------------------------------\n\\ Setting the time.\n\\ -------------------------------------------------\nvariable adj_i \\ THe working index into the points array.\n\nudata \ncreate adj_points #50 cells allot \\ 100 16-bit words. \ncreate interp_set _interp_set allot\ncdata \n\n\\ Generate a list of points.\n: MAKE-SET-LIST ( max steps ) \n 2dup \n >R (interp_init) swap interp_set swap R> call3--\n\n \\ Since zero is first, do the w! first.\n swap drop 0 swap \\ Keep a running counter.\n 0 do\n dup I adj_points[]! \\ Save the existing value\n interp_set interp-next + \n loop\n drop\n ;\n\n: ADJ_POINTS[]! ( data index -- ) 2* adj_points + w! ;\n: ADJ_POINTS[]@ ( index -- n ) 2* adj_points + w@ ;\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"a59ec771f93e5b93924a99207da714a01900d2fa","subject":"refactoring","message":"refactoring\n","repos":"bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas","old_file":"KataDiversion.fth","new_file":"KataDiversion.fth","new_contents":"\\ KataDiversion in Forth\n\n\\ -- utils\n\n\\ empty the stack\n: EMPTY\n DEPTH 0 <> IF BEGIN\n DROP DEPTH 0 =\n UNTIL\n THEN ;\n\n\\ power\n: ** ( n1 n2 -- n1_pow_n2 ) 1 SWAP ?DUP IF 0 DO OVER * LOOP THEN NIP ;\n\n\\ test if the top is a negative number\n: ?NEG ( n -- bool ) DUP 0= IF -1 ELSE DUP ABS <> THEN ;\n\n\\ log2 (integer)\n\\ TODO remove this word, and add a new word\n\\ which compute the value of ( n LOG2 2 SWAP ** )\n: LOG2 ( n -- log2_n ) DUP 1 < IF 1 ABORT\" Log2 need a positive value.\"\n ELSE DUP 1 = IF 0\n ELSE\n 1 >R\n BEGIN ( n |R: i=1)\n DUP DUP 2 I ** - 2 *\n ( n n 2*[n-2**i])\n R> 1 + >R ( \u2026 |R: i+1)\n > ( n n>2*[n-2**i] )\n UNTIL\n R> 1 -\n THEN\n THEN NIP ;\n\n\\ -- kata\n\n\\ test if the given N has two adjacent 1 bits\n\\ e.g. : 11 -> 1011 -> -1\n\\ 9 -> 1001 -> 0\n: ?TWO-ADJACENT-1-BITS ( n -- bool )\n \\ the word uses the following algorithm :\n \\ (stack|return stack)\n \\ ( A N | X ) A: 0, X: N LOG2\n \\ loop: if N-X > 0 then A++ else A=0 ; X \/= 2\n \\ return -1 if A=2\n \\ if X=1 end loop and return 0\n 0 SWAP DUP DUP 0 <> IF\n LOG2 2 SWAP ** >R\n BEGIN\n DUP I - 0 >= IF \n SWAP DUP 1 = IF 1+ SWAP\n ELSE 1+ SWAP I -\n THEN\n ELSE NIP 0 SWAP\n THEN\n OVER\n 2 =\n I 1 = OR\n R> 2 \/ >R\n UNTIL\n R> 2DROP\n 2 =\n THEN ;\n\n\\ return the maximum number which can be made with N (given number) bits\n: ?MAX-NB ( n -- m ) DUP ?NEG IF DROP 0 ( 0 )\n ELSE \n DUP IF DUP 2 SWAP ** NIP ( 2**n )\n THEN\n THEN ;\n\n\n\\ return the number of numbers which can be made with N (given number) bits\n\\ or less, and which have not two adjacent 1 bits.\n\\ see http:\/\/www.codekata.com\/2007\/01\/code_kata_fifte.html\n: ?HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS ( n -- m ) ( TODO ) ;\n","old_contents":"\\ KataDiversion in Forth\n\n\\ -- utils\n\n\\ empty the stack\n: EMPTY\n DEPTH 0 <> IF BEGIN\n DROP DEPTH 0 =\n UNTIL\n THEN ;\n\n\\ power\n: ** ( n1 n2 -- n1_pow_n2 ) 1 SWAP ?DUP IF 0 DO OVER * LOOP THEN NIP ;\n\n\\ test if the top is a negative number\n: ?NEG ( n -- bool ) DUP 0= IF -1 ELSE DUP ABS <> THEN ;\n\n\\ log2 (integer)\n: LOG2 ( n -- log2_n ) DUP 1 < IF 1 ABORT\" Log2 need a positive value.\"\n ELSE DUP 1 = IF 0\n ELSE\n 1 >R\n BEGIN ( n |R: i=1)\n DUP DUP 2 I ** - 2 *\n ( n n 2*[n-2**i])\n R> 1 + >R ( \u2026 |R: i+1)\n > ( n n>2*[n-2**i] )\n UNTIL\n R> 1 -\n THEN\n THEN NIP ;\n\n\\ decimal to binary\n\\ e.g. : ( 11 -- 1 0 1 1 )\n: DEC2BIN ( n -- n1 n2 n3 \u2026 ) DUP DUP 0 <> IF\n LOG2 2 SWAP ** >R ( n |R: X=2 ** n.log2 )\n BEGIN\n DUP I - 0 >= IF 1 SWAP I - ( 1 n-X )\n ELSE 0 SWAP ( 0 n )\n THEN\n I 1 =\n R> 2 \/ >R ( \u2026 | X\/2 )\n UNTIL\n R> 2DROP\n THEN\n ;\n\n\n\\ -- kata\n\n\\ test if the given N has two adjacent 1 bits\n\\ e.g. : 11 -> 1011 -> -1\n\\ 9 -> 1001 -> 0\n: ?TWO-ADJACENT-1-BITS ( n -- bool ) 0 SWAP DUP DUP 0 <> IF ( _ n n )\n LOG2 2 SWAP ** >R ( _ n |R: X=2 ** n.log2 )\n BEGIN\n DUP I - ( _ n n-X ) 0 >= IF \n SWAP DUP 1 = IF ( n _ ) 1+ SWAP ( 2 n )\n ELSE ( n _ ) 1+ SWAP ( _ n ) I -\n THEN\n ELSE NIP 0 SWAP ( 0 n ) \n THEN\n ( _ n )\n OVER ( _ n _ )\n 2 = \n I 1 = OR\n R> 2 \/ >R ( \u2026 | X\/2 )\n UNTIL\n R> 2DROP\n 2 =\n THEN ;\n\n\\ return the maximum number which can be made with N (given number) bits\n: ?MAX-NB ( n -- m ) DUP ?NEG IF DROP 0 ( 0 )\n ELSE \n DUP IF DUP 2 SWAP ** NIP ( 2**n )\n THEN\n THEN ;\n\n\n\\ return the number of numbers which can be made with N (given number) bits\n\\ or less, and which have not two adjacent 1 bits.\n\\ see http:\/\/www.codekata.com\/2007\/01\/code_kata_fifte.html\n: ?HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS ( n -- m ) ( TODO ) ;\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"b4be0fe906ea26c2dc8f6e3f0f43124585924123","subject":"Added pictured numeric output.","message":"Added pictured numeric output.\n\nPictured numeric output has been added as a series of Forth words to\n\"forth.fth\".\n","repos":"howerj\/libforth","old_file":"forth.fth","new_file":"forth.fth","new_contents":"( \nWelcome to libforth, A dialect of Forth. Like all versions of Forth this\nversion is a little idiosyncratic, but how the interpreter works is\ndocumented here and in various other files.\n\nThis file contains most of the start up code, some basic start up code\nis executed in the C file as well which makes programming at least bearable.\nMost of Forth is programmed in itself, which may seem odd if your back\nground in programming comes from more traditional language [such as C],\nalthough less so if you know already know lisp.\n\nFor more information about this interpreter and Forth see:\n\thttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\treadme.md : for a manual for this interpreter\n\tlibforth.h : for information about the C API\n\tlibforth.3 : for limited information about the C API\n\tlibforth.c : for the interpreter itself\n\tunit.c : a series of unit tests against libforth.c\n\tunit.fth : a series of unit tests against this file\n\nThe interpreter and this code originally descend from a Forth interpreter\nwritten in 1992 for the International obfuscated C Coding Competition\n\nSee:\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\nThe manual for the interpreter should be read first before looking into this\ncode. It is important to understand the execution model of Forth, especially\nthe differences between command and compile mode, and how immediate and compiling\nwords work.\n\nThe structure of this file is as follows:\n\n1. Basic Word Set\n2. Extended Word Set\n3. CREATE DOES>\n4. CASE statements\n5. Conditional Compilation\n6. Endian Words\n7. Misc words\n8. Random Numbers\n9. ANSI Escape Codes\n10. Prime Numbers\n11. Debugging info\n12. Files\n13. Blocks\n14. Matcher\n15. Cons Cells\n16. Miscellaneous\n17. Core utilities\n\nEach of these sections is clearly labeled and they are generally in dependency order.\n)\n\n( ========================== Basic Word Set ================================== )\n\n( \nWe'll begin by defining very simple words we can use later, these a very\nbasic words, that perform simple tasks, they will not require much explanation.\n\nEven though the words are simple, their stack comment and a description for\nthem will still be included so external tools can process and automatically\nextract the document string for a given work.\n)\n\n: 1+ ( x -- x : increment a number )\n\t1 + ;\n\n: 1- ( x -- x : decrement a number )\n\t1 - ;\n\n: chars ( c-addr -- addr : convert a character address to an address )\n\tsize \/ ; \n\n: chars> ( addr -- c-addr: convert an address to a character address )\n\tsize * ; \n\n: tab ( -- : print a tab character to current output device )\n\t9 emit ;\n\n: 0= ( x -- bool : is 'x' equal to zero? )\n\t0 = ;\n\n: not ( x -- bool : is 'x' true? )\n\t0= ;\n\n: <> ( x x -- bool : not equal )\n\t= 0= ;\n\n: logical ( x -- bool : turn a value into a boolean ) \n\tnot not ;\n\n: :: ( -- : compiling version of ':' )\n\t[ find : , ] ;\n\n: '\\n' ( -- n : push the newline character )\n\t10 ;\n\n: cr ( -- : emit a newline character )\n\t'\\n' emit ;\n\n: hidden-mask ( -- x : pushes mask for the hide bit in a words MISC field )\n\t0x80 ;\n\n: instruction-mask ( -- x : pushes mask for the first code word in a words MISC field )\n\t0x1f ;\n\n: hidden? ( PWD -- PWD bool : is a word hidden, given the words PWD field ) \n\tdup 1+ @ hidden-mask and logical ;\n\n: compile-instruction ( -- instruction : compile code word, threaded code interpreter instruction )\n\t1 ; \n\n: dolist ( -- x : run code word, threaded code interpreter instruction )\n\t2 ; \n\n: dolit ( -- x : location of special \"push\" word )\n\t2 ;\n\n: 2, ( x x -- : write two values into the dictionary )\n\t, , ;\n\n: [literal] ( x -- : write a literal into the dictionary )\n\tdolit 2, ; \n\n: literal ( x -- : immediately write a literal into the dictionary )\n\timmediate [literal] ;\n\n: min-signed-integer ( -- x : push the minimum signed integer value )\n\t[ -1 -1 1 rshift invert and ] literal ;\n\n: max-signed-integer ( -- x : push the maximum signed integer value )\n\t[ min-signed-integer invert ] literal ;\n\n: < ( x1 x2 -- bool : signed less than comparison )\n\t- dup if max-signed-integer u> else logical then ;\n\n: > ( x1 x2 -- bool : signed greater than comparison )\n\t< not ;\n\n: 2literal immediate ( x x -- : immediate write two literals into the dictionary )\n\tswap [literal] [literal] ;\n\n: latest ( get latest defined word )\n\tpwd @ ; \n\n: stdin ( -- fileid : push the fileid for the standard input channel ) \n\t`stdin @ ;\n\n: stdout ( -- fileid : push the fileid for the standard output channel ) \n\t`stdout @ ;\n\n: stderr ( -- fileid : push the fileid for the standard error channel ) \n\t`stderr @ ;\n\n: stdin? ( -- bool : are we reading from standard input )\n\t`fin @ stdin = ;\n\n: false ( -- x : push the value representing false )\n\t0 ;\n\n: true ( -- x : push the value representing true )\n\t-1 ;\n\n: *+ ( x1 x2 x3 -- x ) \n\t* + ;\n\t\n: 2- ( x -- x : decrement by two )\n\t2 - ( x -- x ) ;\n\n: 2+ ( x -- x : increment by two )\n\t2 + ( x -- x ) ;\n\n: 3+ ( x -- x : increment by three )\n\t3 + ( x -- x ) ;\n\n: 2* ( x -- x : multiply by two )\n\t1 lshift ( x -- x ) ;\n\n: 2\/ ( x -- x : divide by two )\n\t1 rshift ( x -- x ) ;\n\n: 4* ( x -- x : multiply by four )\n\t2 lshift ( x -- x ) ;\n\n: 4\/ ( x -- x : divide by four )\n\t2 rshift ( x -- x ) ;\n\n: 8* ( x -- x : multiply by eight )\n\t3 lshift ( x -- x ) ;\n\n: 8\/ ( x -- x : divide by eight )\n\t3 rshift ( x -- x ) ;\n\n: 256* ( x -- x : multiply by 256 )\n\t8 lshift ( x -- x ) ;\n\n: 256\/ ( x -- x : divide by 256 )\n\t8 rshift ( x -- x ) ;\n\n: 2dup ( x1 x2 -- x1 x2 x1 x2 : duplicate two values )\n\tover over ;\n\n: mod ( x u -- x : calculate the remainder of x divided by u ) \n\t2dup \/ * - ;\n\n: um\/mod ( x1 x2 -- rem quot : calculate the remainder and quotient of x1 divided by x2 ) \n\t2dup \/ >r mod r> ;\n\n: *\/ ( x1 x2 x3 -- x4 : multiply then divide, @warning this does not use a double cell for the multiply )\n\t * \/ ; \n\n: char ( -- x : read in a character from the input steam )\n\tkey drop key ;\n\n: [char] ( -- x : immediately read in a character from the input stream )\n\timmediate char [literal] ;\n\n: postpone ( -- : postpone execution of the following immediate word )\n\timmediate find , ;\n\n: unless ( bool -- : like 'if' but execute clause if false )\n\timmediate ' 0= , postpone if ;\n\n: endif ( synonym for 'then' ) \n\timmediate postpone then ;\n\n: cell+ ( a-addr1 -- a-addr2 ) \n\t1+ ;\n\n: cells ( n1 -- n2 ) \n\timmediate ;\n\n: cell ( -- u : defined as 1 cells )\n\t1 cells ;\n\n: address-unit-bits ( -- x : push the number of bits in an address )\n\t[ cell size 8* * ] literal ;\n\n: negative? ( x -- bool : is a number negative? )\n\t[ 1 address-unit-bits 1- lshift ] literal and logical ;\n\n: mask-byte ( x -- x : mask off a ) \n\t8* 0xff swap lshift ;\n\n: select-byte ( u i -- c ) \n\t8* rshift 0xff and ;\n\n: char+ ( c-addr -- c-addr : increment a character address by the size of one character ) \n\t1+ ;\n\n: 2chars ( c-addr1 c-addr2 -- addr addr : convert two character addresses to two cell addresses ) \n\tchars swap chars swap ;\n\n: 2chars> ( addr addr -- c-addr c-addr: convert two cell addresses to two character addresses )\n\tchars> swap chars> swap ;\n\n: hex ( -- : print out hex ) \n\t16 base ! ;\n\n: octal ( -- : print out octal ) \n\t8 base ! ;\n\n: binary ( -- : print out binary ) \n\t2 base ! ;\n\n: decimal ( -- : print out decimal ) \n\t0 base ! ;\n\n: negate ( x -- x ) \n\t-1 * ;\n\n: square ( x -- x ) \n\tdup * ;\n\n: drup ( x y -- x x ) \n\tdrop dup ;\n\n: +! ( x addr -- : add x to a value stored at addr ) \n\ttuck @ + swap ! ;\n\n: 1+! ( addr -- : increment a value at an address ) \n\t1 swap +! ;\n\n: 1-! ( addr -- : decrement a value at an address ) \n\t-1 swap +! ;\n\n: lsb ( x -- x : mask off the least significant byte of a cell ) \n\t255 and ;\n\n: \\ ( -- : immediate word, used for single line comments )\n\timmediate begin key '\\n' = until ;\n\n: ?dup ( x -- ? ) \n\tdup if dup then ;\n\n: min ( x y -- min ) \n\t2dup < if drop else swap drop then ;\n\n: max ( x y -- max ) \n\t2dup > if drop else swap drop then ;\n\n: >= ( x y -- bool ) \n\t< not ;\n\n: <= ( x y -- bool ) \n\t> not ;\n\n: 2@ ( a-addr -- x1 x2 : load two consecutive memory cells )\n\tdup 1+ @ swap @ ;\n\n: 2! ( x1 x2 a-addr -- : store two values as two consecutive memory cells )\n\t2dup ! nip 1+ ! ;\n\n: r@ ( -- x, R: x -- )\n\tr> r @ swap >r ;\n\n: 0> ( x -- bool )\n\t0 < ;\n\n: 0< ( x -- bool )\n\t0 > ;\n\n: 0<> ( x -- bool )\n\t0 <> ;\n\n: nand ( x x -- x : Logical NAND ) \n\tand not ;\n\n: odd ( x -- bool : is 'x' odd? )\n\t1 and ;\n\n: even ( x -- bool : is 'x' even? )\n\todd not ;\n\n: nor ( x x -- x : Logical NOR ) \n\tor not ;\n\n: ms ( u -- : wait at least 'u' milliseconds ) \n\tclock + begin dup clock u< until drop ;\n\n: sleep ( u -- : sleep for 'u' seconds )\n\t1000 * ms ;\n\n: align ( addr -- addr : align and address, nop in this implemented )\n\timmediate ; \n\n: ) ( -- : do nothing, this allows easy commenting out of code )\n\timmediate ;\n\n: ? ( a-addr -- : view value at address ) \n\t@ . ;\n\n: bell ( -- : emit an ASCII BEL character ) \n\t7 emit ;\n\n: b\/buf ( -- u : bytes per buffer ) \n\t1024 ;\n\n: .d ( x -- x : debug print ) \n\tdup . ;\n\n: compile, ( -- : A word that writes , into the dictionary ) \n\t' , , ; \n\n: >mark ( -- : write a hole into the dictionary and push a pointer to it ) \n\there 0 , ;\n\n: r - r> u< ;\n\n: invalidate-forth ( -- : invalidate this Forth core )\n\t1 `invalid ! ;\n\n: signed ( x -- bool : return true if sign bit set ) \n\t[ 1 size 8 * 1- lshift ] literal and logical ;\n\n: u>= ( x y -- bool : unsigned greater than or equal to )\n\t2dup u> >r = r> or ;\n\n: u<= ( x y -- bool : unsigned less than or equal to )\n\tu>= not ;\n\n: rdrop ( R: x -- : drop a value from the return stack )\n\tr> ( get caller's return address )\n\tr> ( get value to drop )\n\tdrop ( drop it like it's hot )\n\t>r ; ( return return address )\n\n: again immediate\n\t( loop unconditionally in a begin-loop:\n\t\tbegin ... again )\n\t' branch , ] literal ( size of input buffer, in characters )\n\t>in ; ( start of input buffer, in characters )\n\n: stdin?\n\t`fin @ `stdin @ = ;\n\n: source-id ( -- 0 | -1 | file-id )\n\t( \t\n\tValue Input Source\n\t-1 String\n\t0 Reading from user input \/ standard in\n\tfile-id )\n\t`source-id @ \n\t0= if\n\t\tstdin? if 0 else `fin @ then\n\telse\n\t\t-1\n\tthen\n\t;\n\n: 2nip ( n1 n2 n3 n4 -- n3 n4) \n\t>r >r 2drop r> r> ;\n\n: 2over ( n1 n2 n3 n4 \u2013 n1 n2 n3 n4 n1 n2 )\n\t>r >r 2dup r> swap >r swap r> r> -rot ;\n\n: 2swap ( n1 n2 n3 n4 \u2013 n3 n4 n1 n2 )\n\t>r -rot r> -rot ;\n\n: 2tuck ( n1 n2 n3 n4 \u2013 n3 n4 n1 n2 n3 n4 )\n\t2swap 2over ;\n\n: hide ( token -- hide-token : this hides a word from being found by the interpreter )\n\tdup\n\tif\n\t\tdup @ hidden-mask or swap tuck !\n\telse\n\t\tdrop 0\n\tthen ;\n\n: hider ( WORD -- ) \n\t( hide with drop ) \n\tfind dup if hide then drop ;\n\n: unhide ( hide-token -- ) \n\tdup @ hidden-mask invert and swap ! ;\n\n: original-exit \n\t[ find exit ] literal ;\n\n: exit\n\t( this will define a second version of exit, ';' will\n\tuse the original version, whilst everything else will\n\tuse this version, allowing us to distinguish between\n\tthe end of a word definition and an early exit by other\n\tmeans in \"see\" )\n\t[ find exit hide ] rdrop exit [ unhide ] ;\n\n: ?exit ( x -- : exit current definition if not zero ) \n\tif rdrop exit then ;\n\n: number? ( c -- f : is character a number? )\n\t[char] 0 [ char 9 1+ ] literal within ;\n\n: lowercase? ( c -- f : is character lower case? )\n\t[char] a [ char z 1+ ] literal within ;\n\n: uppercase? ( C -- f : is character upper case? )\n\t[char] A [ char Z 1+ ] literal within ;\n\n: alpha? ( C -- f : is character part of the alphabet? )\n\tdup lowercase? swap uppercase? or ;\n\n: alphanumeric? ( C -- f : is character alphabetic or a number ? )\n\tdup alpha? swap number? or ;\n\n: printable? ( c -- bool : is printable, excluding new lines and tables )\n\t32 127 within ;\n\n: >upper ( c -- C : convert char to uppercase iff lower case )\n\tdup lowercase? if bl xor then ;\n\n: >lower ( C -- c : convert char to lowercase iff upper case )\n\tdup uppercase? if bl xor then ;\n\n: <=> ( x y -- z : spaceship operator! )\n\t2dup\n\t> if 2drop -1 exit then\n\t< ;\n\n: start-address ( -- c-addr : push the start address )\n\t`start-address @ ;\n\n: >real-address ( c-addr -- c-addr : convert an interpreter address to a real address )\n\tstart-address - ;\n\n: real-address> ( c-addr -- c-addr : convert a real address to an interpreter address )\n\tstart-address + ;\n\n: peek ( c-addr -- char : peek at real memory )\n\t>real-address c@ ;\n\n: poke ( char c-addr -- : poke a real memory address )\n\t>real-address c! ;\n\n: die? ( x -- : controls actions when encountering certain errors )\n\t`error-handler ! ;\n\n: start! ( cfa -- : set the word to execute at startup )\n\t`instruction ! ;\t\n\n: warm ( -- : restart the interpreter, warm restart )\n\t1 restart ;\n\n: trip ( x -- x x x : triplicate a number ) \n\tdup dup ;\n\n( ========================== Basic Word Set ================================== )\n\n( ========================== Extended Word Set =============================== )\n\n: gcd ( x1 x2 -- x : greatest common divisor )\n\tbegin\n\t\tdup\n\t\tif\n\t\t\ttuck mod 0\n\t\telse\n\t\t\t1\n\t\tthen\n\tuntil\n\tdrop ;\n\n: log2 ( x -- log2 )\n\t( Computes the binary integer logarithm of a number,\n\tzero however returns itself instead of reporting an error )\n\t0 swap\n\tbegin\n\t\tswap 1+ swap 2\/ dup 0=\n\tuntil\n\tdrop 1- ;\n\n: cfa ( previous-word-address -- cfa )\n\t( Given the address of the PWD field of a word this\n\tfunction will return an execution token for the word )\n\t1+ ( MISC field )\n\tdup\n\t@ ( Contents of MISC field )\n\tinstruction-mask and ( Mask off the instruction )\n\t( If the word is not an immediate word, execution token pointer )\n\tcompile-instruction = + ;\n\n: ['] immediate find cfa [literal] ;\n\n: execute ( cfa -- )\n\t( given an execution token, execute the word )\n\n\t( create a word that pushes the address of a hole to write to\n\ta literal takes up two words, '!' takes up one )\n\t1- ( execution token expects pointer to PWD field, it does not\n\t\tcare about that field however, and increments past it )\n\tcfa\n\t[ here 3+ literal ]\n\t! ( write an execution token to a hole )\n\t[ 0 , ] ( this is the hole we write )\n;\n\n: time ( \" ccc\" -- n : time the number of milliseconds it takes to execute a word )\n\tclock >r\n\tfind execute\n\tclock r> - ;\n\n: rdepth\n\tmax-core `stack-size @ - r @ swap - ;\n\n( defer...is is probably not standards compliant, it is still neat! Also, there\n is no error handling if \"find\" fails... )\n: (do-defer) ( -- self : pushes the location into which it is compiled )\n\tr> dup >r 1- ;\n\n: defer ( \" ccc\" -- , Run Time -- location : \n\tcreates a word that pushes a location to write an execution token into )\n\t:: ' (do-defer) , postpone ; ;\n\n: is ( location \" ccc\" -- : make a deferred word execute a word ) \n\tfind cfa swap ! ;\n\nhider (do-defer)\n\n( ========================== Extended Word Set =============================== )\n\n( \nThe words described here on out get more complex and will require more\nof an explanation as to how they work.\n)\n\n( ========================== CREATE DOES> ==================================== )\n\n( The following section defines a pair of words \"create\" and \"does>\" which\nare a powerful set of words that can be used to make words that can create\nother words. \"create\" has both run time and compile time behavior, whilst\n\"does>\" only works at compile time in conjunction with \"create\". These two\nwords can be used to add constants, variables and arrays to the language,\namongst other things.\n\nA simple version of create is as follows\n\t: create :: 2 , here 2 + , ' exit , 0 state ! ;\nBut this version is much more limited )\n\n: write-quote ( A word that writes ' into the dictionary )\n\t['] ' , ; \n\n: write-exit ( A word that write exit into the dictionary )\n\t['] exit , ; \n\n: state! ( bool -- : set the compilation state variable ) \n\tstate ! ;\n\n: command-mode ( -- : put the interpreter into command mode )\n\tfalse state! ;\n\n: command-mode-create ( create a new work that pushes its data field )\n\t:: ( compile a word )\n\tdolit , ( write push into new word )\n\there 2+ , ( push a pointer to data field )\n\tpostpone ; ; ( write exit and switch to command mode )\n\n: mark compile, ( Write in a place holder 0 and push a pointer to to be used by does> )\n\twrite-quote write-exit compile, ( Write in an exit in the word we're compiling. )\n\t['] command-mode , ( Make sure to change the state back to command mode )\n;\n\n: create immediate ( create word is quite a complex forth word )\n\tstate @ \n\tif \n\t\tpostpone ( hole-to-patch -- )\n\timmediate\n\twrite-exit ( we don't want the defining to exit, but the *defined* word to )\n\there swap ! ( patch in the code fields to point to )\n\tdolist , ( write a run in )\n;\n\n: >body ( xt -- a-addr : a-addr is data field of a CREATEd word )\n\tcfa 5 + ;\nhider write-quote\n\n( ========================== CREATE DOES> ==================================== )\n\n: limit ( x min max -- x : limit x with a minimum and maximum )\n\trot min max ;\n\n: array ( x c\" xxx\" -- : create a named array ) \n\tcreate allot does> + ;\n\n: table \n\tcreate allot does> ;\n\n: variable \n\tcreate , does> ;\n\n: constant \n\tcreate , does> @ ;\n\n( @todo replace all instances of table with itable )\n: itable \n\tcreate dup , allot does> dup @ ;\n\n: char-table \n\tcreate dup , chars allot does> dup @ swap 1+ chars> swap ;\n\n: 2constant \n\tcreate , , does> dup 1+ @ swap @ ;\n\n: 2variable \n\tcreate , , does> ;\n\n( do...loop could be improved by not using the return stack so much )\n\n: do immediate\n\t' swap , ( compile 'swap' to swap the limit and start )\n\t' >r , ( compile to push the limit onto the return stack )\n\t' >r , ( compile to push the start on the return stack )\n\tpostpone begin ; ( save this address so we can branch back to it )\n\n: addi\n\t( @todo simplify )\n\tr@ 1- ( get the pointer to i )\n\t+! ( add value to it )\n\tr@ 1- @ ( find the value again )\n\tr@ 2- @ ( find the limit value )\n\tu<\n\tif\n\t\tr@ @ @ r@ @ + r@ ! exit ( branch )\n\tthen\n\tr> 1+\n\trdrop\n\trdrop\n\t>r ;\n\n: loop \n\timmediate 1 [literal] ' addi , r> ( pop off return address and i )\n\ttuck ( tuck i away )\n\t>r >r ( restore return stack )\n;\n\n: range ( nX nY -- nX nX+1 ... nY ) \n\tswap 1+ swap do i loop ;\n\n: repeater ( n0 X -- n0 ... nX ) \n\t1 do dup loop ;\n\n: sum ( n0 ... nX X -- sum<0..X> ) \n\t1 do + loop ;\n\n: mul ( n0 ... nX X -- mul<0..X> ) \n\t1 do * loop ;\n\n: factorial ( n -- n! )\n\t( This factorial is only here to test range, mul, do and loop )\n\tdup 1 <=\n\tif\n\t\tdrop\n\t\t1\n\telse ( This is obviously super space inefficient )\n \t\tdup >r 1 range r> mul\n\tthen ;\n\nhider tail\n\n( \nThe \"tail\" function implements tail calls, which is just a jump\nto the beginning of the words definition, for example this\nword will never overflow the stack and will print \"1\" followed\nby a new line forever,\n\n\t: forever 1 . cr tail ;\n\nWhereas\n\n\t: forever 1 . cr recurse ;\n\nor\n\n\t: forever 1 . cr forever ;\n\nWould overflow the return stack. \n)\n: tail ( -- )\n\timmediate\n\tlatest cfa\n\t' branch ,\n\there - 1+ , ;\n\n: recurse immediate\n\t( This function implements recursion, although this interpreter\n\tallows calling a word directly. If used incorrectly this will\n\tblow up the return stack.\n\n\tWe can test \"recurse\" with this factorial function:\n\t : factorial dup 2 < if drop 1 exit then dup 1- recurse * ;)\n\tlatest cfa , ;\n\n: myself ( -- : myself is a synonym for recurse ) \n\timmediate postpone recurse ;\n\n0 variable column-counter\n4 variable column-width\n\n: column ( i -- )\t\n\tcolumn-width @ mod not if cr then ;\n\n: reset-column\t\t\n\t0 column-counter ! ;\n\n: auto-column\t\t\n\tcolumn-counter dup @ column 1+! ;\n\n: alignment-bits \n\t[ 1 size log2 lshift 1- literal ] and ;\n\n: name ( PWD -- c-addr : given a pointer to the PWD field of a word get a pointer to the name of the word )\n\tdup 1+ @ 256\/ lsb - chars> ;\n\n0 variable x\n: x! ( x -- ) \n\tx ! ;\n\n: x@ ( -- x ) \n\tx @ ;\n\n: 2>r ( x1 x2 -- R: x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tswap\n\t\t>r\n\t\t>r\n\tx@ >r ; ( restore return address )\n\n: 2r> ( R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tr>\n\t\tr>\n\t\tswap\n\tx@ >r ; ( restore return address )\n\n: 2r@ ( -- x1 x2 , R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\tr> r>\n\t2dup\n\t>r >r\n\tswap\n\tx@ >r ; ( restore return address )\n\n: unused ( -- u : push the amount of core left ) \n\tmax-core here - ;\n\n: roll\n\t( xu xu-1 ... x0 u -- xu-1 ... x0 xu )\n\t( remove u and rotate u+1 items on the top of the stack,\n\tthis could be replaced with a move on the stack and\n\tsome magic so the return stack is used less )\n\tdup 0 >\n\tif\n\t\tswap >r 1- roll r> swap\n\telse\n\t\tdrop\n\tthen ;\n\n: accumulator ( \" ccc\" -- : make a word that increments by a value and pushes the result )\n\tcreate , does> tuck +! @ ;\n\n0 variable delim\n: accepter\n\t( c-addr max delimiter -- i )\n\t( store a \"max\" number of chars at c-addr until \"delimiter\" encountered,\n\tthe number of characters stored is returned )\n\tkey drop ( drop first key after word )\n\tdelim ! ( store delimiter used to stop string storage when encountered)\n\t0\n\tdo\n\t\tkey dup delim @ <>\n\t\tif\n\t\t\tover c! 1+\n\t\telse ( terminate string )\n\t\t\tdrop 0 swap c! \n\t\t\ti 1+\n\t\t\tleave\n\t\tthen\n\tloop\n\tbegin ( read until delimiter )\n\t\tkey delim @ =\n\tuntil \n;\nhider delim\n\n: accept ( c-addr +n1 -- +n2 : see accepter definition ) \n\t'\\n' accepter ;\n\n0xFFFF constant max-string-length\n\n0 variable delim\n: print-string\n\t( delimiter -- : print out the next characters in the input stream until a\n\t\"delimiter\" character is reached )\n\tkey drop\n\tdelim !\n\tbegin\n\t\tkey dup delim @ =\n\t\tif\n\t\t\tdrop exit\n\t\tthen\n\t\temit 0\n\tuntil ;\nhider delim\n\nsize 1- constant aligner\n: aligned ( unaligned -- aligned : align a pointer )\n\taligner + aligner invert and ;\nhider aligner\n\n0 variable delim\n: write-string ( char -- c-addr u )\n\t( @todo This really needs simplifying, to do this\n\ta set of words that operate on a temporary buffer can\n\tbe used )\n\t( Write a string into word being currently defined, this\n\tcode has to jump over the string it has just put into the\n\tdictionary so normal execution of a word can continue. The\n\tlength and character address of the string are left on the\n\tstack )\n\tdelim ! ( save delimiter )\n\t' branch , ( write in jump, this will jump past the string )\n\t>mark ( make hole )\n\tdup 1+ chars> ( calculate address to write to )\n\tmax-string-length delim @ accepter dup >r ( write string into dictionary, save index )\n\taligned 2dup size \/ ( stack: length hole char-len hole )\n\t1+ dup allot ( update dictionary pointer with string length )\n\t1+ swap ! ( write place to jump to )\n\tdrop ( do not need string length anymore )\n\t1+ chars> ( calculate place to print )\n\tr> ( restore index and address of string )\n\t1-\n;\nhider delim\n\n: length ( c-addr u -- u : push the length of an ASCIIZ string )\n tuck 0 do dup c@ 0= if 2drop i leave then 1+ loop ;\n\n: asciiz? ( c-addr u -- : is a Forth string also a ASCIIZ string )\n\ttuck length <> ;\n\n: asciiz ( c-addr u -- : trim a string until NUL terminator )\n\t2dup length nip ;\n\n: type ( c-addr u -- : print out 'u' characters at c-addr )\n\t0 do dup c@ emit 1+ loop drop ;\n\n: do-string ( char -- : write a string into the dictionary reading it until char is encountered )\n\twrite-string state @ if swap [literal] [literal] then ;\n\n: fill ( c-addr u char -- : fill in an area of memory with a character, only if u is greater than zero )\n\t-rot\n\t0 do 2dup i + c! loop\n\t2drop ;\n\n: \/string ( c-addr1 u1 n -- c-addr2 u2 : advance a string by n characters )\n\tover min rot over + -rot - ;\n\n128 char-table sbuf\n: s\" ( \"ccc\" --, Run Time -- c-addr u )\n\tsbuf 0 fill sbuf [char] \" accepter sbuf drop swap ;\nhider sbuf\n\n( @todo these strings really need rethinking, state awareness needs to be removed... )\n: type, \n\tstate @ if ' type , else type then ;\n\n: c\" \n\timmediate [char] \" do-string ;\n\n: \" \n\timmediate [char] \" do-string type, ;\n\n: .( \n\timmediate [char] ) print-string ;\n\n: .\" \n\timmediate [char] \" do-string type, ;\n\nhider type,\n\n( This word really should be removed along with any usages of this word, it\nis not a very \"Forth\" like word, it accepts a pointer to an ASCIIZ string and\nprints it out, it also does not checking of the returned values from write-file )\n: print ( c-addr -- : print out a string to the standard output )\n\t-1 over >r length r> swap stdout write-file 2drop ;\n\n: ok \n\t\" ok\" cr ;\n\n: empty-stack ( x-n ... x-0 -- : empty the variable stack )\n\tbegin depth while drop repeat ;\n\n: quit\n\t0 `source-id ! ( set source to read from file )\n\t`stdin @ `fin ! ( read from stdin )\n\tpostpone [ ( back into command mode )\n\t1 restart ( restart the interpreter ) ; \n\n: abort\n\tempty-stack quit ;\n\n: abort\" immediate postpone \"\n\t' cr , ' abort , ;\n\n( ==================== CASE statements ======================== )\n\n( for a simpler case statement:\n\tsee Volume 2, issue 3, page 48 of Forth Dimensions at\n\thttp:\/\/www.forth.org\/fd\/contents.html )\n\n( These case statements need improving, it is not standards compliant )\n: case immediate\n\t' branch , 3 , ( branch over the next branch )\n\there ' branch , ( mark: place endof branches back to with again )\n\t>mark swap ; ( mark: place endcase writes jump to with then )\n\n: over= ( x y -- x bool : over ... then = )\n\tover = ;\n\n: of\n\timmediate ' over= , postpone if ;\n\n: endof\n\timmediate over postpone again postpone then ;\n\n: endcase\n\timmediate 1+ postpone then drop ;\n\n( ==================== CASE statements ======================== )\n\n: error-no-word ( print error indicating last read in word as source )\n\t\" error: word '\" source drop print \" ' not found\" cr ;\n\n: ;hide ( should only be matched with ':hide' )\n\timmediate \" error: ';hide' without ':hide'\" cr ;\n\n: :hide ( -- : hide a list of words, the list is terminated with \";hide\" )\n\tbegin\n\t\tfind ( find next word )\n\t\tdup [ find ;hide ] literal = if\n\t\t\tdrop exit ( terminate :hide )\n\t\tthen\n\t\tdup 0= if ( word not found )\n\t\t\tdrop\n\t\t\terror-no-word\n\t\t\texit\n\t\tthen\n\t\thide drop\n\tagain ;\n\n: count ( c-addr1 -- c-addr2 u : advance string pointer ) \n\tdup c@ swap 1+ swap ;\n\n: bounds ( x y -- y+x x : make an upper and lower bound )\n\tover + swap ;\n\n: spaces ( n -- : print n spaces ) \n\t0 do space loop ;\n\n: erase ( addr u : erase a block of memory )\n\t2chars> 0 fill ;\n\n: blank ( c-addr u : fills a string with spaces )\n\tbl fill ;\n\n( move should check that u is not negative )\n: move ( addr1 addr2 u -- : copy u words of memory from 'addr2' to 'addr1' )\n\t0 do\n\t\t2dup i + @ swap i + !\n\tloop\n\t2drop ;\n\n( It would be nice if move and cmove could share more code, as they do exactly\n the same thing but with different load and store functions, cmove> )\n: cmove ( c-addr1 c-addr2 u -- : copy u characters of memory from 'c-addr2' to 'c-addr1' )\n\t0 do\n\t\t2dup i + c@ swap i + c!\n\tloop\n\t2drop ;\n\n( ==================== Conditional Compilation ================ )\n\n( The words \"[if]\", \"[else]\" and \"[then]\" implement conditional compilation,\nthey can be nested as well\n\nSee http:\/\/lars.nocrew.org\/dpans\/dpans15.htm for more information\n\nA much simpler conditional compilation method is the following\nsingle word definition:\n\n : compile-line? 0= if [ find \\\\ , ] then ;\n\nWhich will skip a line if a conditional is false, and compile it\nif true )\n\n( These words really, really need refactoring, I could use the newly defined \n \"defer\" to help out with this )\n0 variable nest ( level of [if] nesting )\n0 variable [if]-word ( populated later with \"find [if]\" )\n0 variable [else]-word ( populated later with \"find [else]\")\n: [then] immediate ;\n: reset-nest 1 nest ! ;\n: unnest? [ find [then] ] literal = if nest 1-! then ;\n: nest? [if]-word @ = if nest 1+! then ;\n: end-nest? nest @ 0= ;\n: match-[else]? [else]-word @ = nest @ 1 = and ;\n\n: [if] ( bool -- : conditional execution )\n\tunless\n\t\treset-nest\n\t\tbegin\n\t\t\tfind\n\t\t\tdup nest?\n\t\t\tdup match-[else]? if drop exit then\n\t\t\t unnest?\n\t\t\tend-nest?\n\t\tuntil\n\tthen ;\n\n: [else] ( discard input until [then] encounter, nesting for [if] )\n\treset-nest\n\tbegin\n\t\tfind\n\t\tdup nest? unnest?\n\t\tend-nest?\n\tuntil ;\n\nfind [if] [if]-word !\nfind [else] [else]-word !\n\n:hide [if]-word [else]-word nest reset-nest unnest? match-[else]? ;hide\n\n( ==================== Conditional Compilation ================ )\n\n( ==================== Endian Words =========================== )\n\nsize 2 = [if] 0x0123 variable endianess [then]\nsize 4 = [if] 0x01234567 variable endianess [then]\nsize 8 = [if] 0x01234567abcdef variable endianess [then]\n\n: endian ( -- bool : returns the endianess of the processor, little = 0, big = 1 )\n\t[ endianess chars> c@ 0x01 = ] literal ;\nhider endianess\n\n: swap16 ( x -- x : swap the byte order a 16 bit number )\n\tdup 256* 0xff00 and >r 256\/ lsb r> or ;\n\nsize 4 >= [if] \n\t: swap32 \n\t\tdup 0xffff and swap16 16 lshift swap\n\t\t16 rshift 0xffff and swap16 or ;\n[then]\n\nsize 8 >= [if]\n\t: swap64 ( x -- x : swap the byte order of a 64 bit number )\n\t\t dup 0xffffffff and swap32 32 lshift swap\n\t\t 32 rshift 0xffffffff and swap32 or ;\n[then]\n\nsize 2 = [if]\n\tendian \n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\tswap16 ;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\t;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\tswap16 ;\n\t[then]\n[then]\n\nsize 4 = [if]\n\tendian \n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\tswap32 ;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\t;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\tswap32 ;\n\t[then]\n[then]\n\nsize 8 = [if]\n\tendian \n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\tswap64 ;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\t;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\tswap64 ;\n\t[then]\n[then]\n\n( ==================== Endian Words =========================== )\n\n( ==================== Misc words ============================= )\n\n: trace ( flag -- : turn tracing on\/off )\n\t`debug ! ;\n\n: #pad ( -- u : offset into pad area )\n\t64 ;\n\n: pad\n\t( the pad is used for temporary storage, and moves\n\talong with dictionary pointer, always in front of it )\n\there #pad + ;\n\n0 variable counter\n\n: counted-column ( index -- : special column printing for dump )\n\tcounter @ column-width @ mod\n\tnot if cr . \" :\" space else drop then\n\tcounter 1+! ;\n\n: as-chars ( x -- : print a cell out as characters )\n\tsize 0\n\tdo\n\t\tdup\n\t\tsize i 1+ - select-byte ( @todo adjust for endianess )\n\t\tdup printable? not\n\t\tif\n\t\t\tdrop [char] .\n\t\tthen\n\t\temit\n\tloop\n\tspace\n\tdrop ;\n\n: lister \n\t0 counter ! 1- swap \n\tdo \n\t\ti counted-column i ? i @ as-chars \n\tloop ;\n\n: dump ( addr u -- : dump out 'u' cells of memory starting from 'addr' )\n\tbase @ >r hex 1+ over + lister r> base ! cr ;\n\n:hide counted-column counter lister as-chars ;hide\n\n: forgetter ( pwd-token -- : forget a found word and everything after it )\n\tdup @ pwd ! h ! ;\n\n( @bug will not work for immediate defined words )\n: forget ( WORD -- : forget word and every word defined after it )\n\tfind 1- forgetter ;\n\n: marker ( WORD -- : make word the forgets itself and words after it)\n\t:: latest [literal] ' forgetter , postpone ; ;\nhider forgetter\n\n: ?dup-if immediate ( x -- x | - : ?dup and if rolled into one! )\n\t' ?dup , postpone if ;\n\n: ** ( b e -- x : exponent, raise 'b' to the power of 'e')\n\tdup\n\tif\n\t\tdup\n\t\t1\n\t\tdo over * loop\n\telse\n\t\tdrop\n\t\t1\n\tendif ;\n\n( ==================== Misc words ============================= )\n\n( ==================== Random Numbers ========================= )\n\n( \nSee:\nuses xorshift\nhttps:\/\/en.wikipedia.org\/wiki\/Xorshift\nhttp:\/\/excamera.com\/sphinx\/article-xorshift.html\nhttp:\/\/www.arklyffe.com\/main\/2010\/08\/29\/xorshift-pseudorandom-number-generator\/\nthese constants have be collected from the web \n)\n\nsize 2 = [if] 13 constant a 9 constant b 7 constant c [then]\nsize 4 = [if] 13 constant a 17 constant b 5 constant c [then]\nsize 8 = [if] 12 constant a 25 constant b 27 constant c [then]\n\n7 variable seed ( must not be zero )\n\n: seed! ( x -- : set the value of the PRNG seed )\n\tdup 0= if drop 7 ( zero not allowed ) then seed ! ;\n\n: random ( -- x : assumes word size is 32 bit )\n\tseed @\n\tdup a lshift xor\n\tdup b rshift xor\n\tdup c lshift xor\n\tdup seed! ;\n\n:hide a b c seed ;hide\n\n( ==================== Random Numbers ========================= )\n\n( ==================== Pictured Numeric Output ================ )\n\n0 variable hld\n\n: hold ( char -- : add a character to the numeric output string )\n\tpad chars> hld @ - c! hld 1+! ;\n\n: nbase ( -- base : in this forth 0 is a special base, push 10 is base is zero )\n\tbase @ dup 0= if drop 10 then ;\n\n: <# ( -- : setup pictured numeric output )\n\t1 hld ! ;\n\n: sign ( -- : add a sign to the pictured numeric output string )\n\t[char] - hold ;\n\n: # ( x -- x : divide x by base, turn into a character, put in pictured output string )\n\tnbase um\/mod swap\n \tnbase 10 u>\n \tif 7 + then\n \t48 + hold ;\n\n: #s ( x -- 0 : repeatedly call # on x until x is zero )\n\tbegin # dup 0= until ; \n\n: #> ( -- c-addr u : end pictured output conversion, push output string to stack )\n\t0 hold pad chars> hld @ tuck - swap ;\n\n: u. ( u -- : display number in base 10 )\n\tbase @ >r decimal <# #s #> type drop r> base ! ;\n\n:hide nbase ;hide\n\n( ==================== Pictured Numeric Output ================ )\n\n( ==================== ANSI Escape Codes ====================== )\n( \nTerminal colorization module, via ANSI Escape Codes\n \nsee: https:\/\/en.wikipedia.org\/wiki\/ANSI_escape_code\nThese codes will provide a relatively portable means of\nmanipulating a terminal\n)\n\n27 constant 'escape'\n: CSI 'escape' emit .\" [\" ;\n0 constant black\n1 constant red\n2 constant green\n3 constant yellow\n4 constant blue\n5 constant magenta\n6 constant cyan\n7 constant white\n: foreground 30 + ;\n: background 40 + ;\n0 constant dark\n1 constant bright\n\n: color ( brightness color-code -- : set the terminal color )\n\t( set color on an ANSI compliant terminal,\n\tfor example:\n\t\tbright red foreground color\n\tsets the foreground text to bright red )\n\tCSI u. if .\" ;1\" then .\" m\" ;\n\n: at-xy ( x y -- : set ANSI terminal cursor position to x y )\n\tCSI u. [char] ; emit u. .\" H\" ;\n\n: page ( -- : clear ANSI terminal screen and move cursor to beginning ) \n\tCSI .\" 2J\" 1 1 at-xy ;\n\n: hide-cursor ( -- : hide the cursor from view ) \n\tCSI .\" ?25l\" ;\n\n: show-cursor ( -- : show the cursor ) \n\tCSI .\" ?25h\" ;\n\n: save-cursor ( -- : save cursor position ) \n\tCSI .\" s\" ;\n\n: restore-cursor ( -- : restore saved cursor position ) \n\tCSI .\" u\" ;\n\n: reset-color ( -- : reset terminal color to its default value)\n\tCSI .\" 0m\" ;\n\n:hide CSI ;hide\n( ==================== ANSI Escape Codes ====================== )\n\n( ==================== Prime Numbers ========================== )\n( From original \"third\" code from the IOCCC at \nhttp:\/\/www.ioccc.org\/1992\/buzzard.2.design, the module works out\nand prints prime numbers. )\n\n: prime? ( x -- x\/0 : return number if it is prime, zero otherwise )\n\tdup 1 = if 1- exit then\n\tdup 2 = if exit then\n\tdup 2 \/ 2 ( loop from 2 to n\/2 )\n\tdo\n\t\tdup ( value to check if prime )\n\t\ti mod ( mod by divisor )\n\t\tnot if\n\t\t\tdrop 0 leave\n\t\tthen\n\tloop\n;\n\n0 variable counter\n: primes ( x1 x2 -- : print the primes from x2 to x1 )\n\t0 counter !\n\t\" The primes from \" dup . \" to \" over . \" are: \"\n\tcr\n\treset-column\n\tdo\n\t\ti prime?\n\t\tif\n\t\t\ti . counter @ column counter 1+!\n\t\tthen\n\tloop\n\tcr\n\t\" There are \" counter @ . \" primes.\"\n\tcr ;\nhider counter\n( ==================== Prime Numbers ========================== )\n\n( ==================== Debugging info ========================= )\n\n( string handling should really be done with PARSE, and CMOVE )\n\nhider .s\n: .s ( -- : print out the stack for debugging )\n\t\" <\" depth u. \" >\" space\n\tdepth if\n\t\tdepth 0 do i column tab depth i 1+ - pick u. loop\n\tthen\n\tcr ;\n\n1 variable hide-words ( do we want to hide hidden words or not )\n\n( This function prints out all of the defined words, excluding hidden words.\nAn understanding of the layout of a Forth word helps here. The dictionary\ncontains a linked list of words, each forth word has a pointer to the previous\nword until the first word. The layout of a Forth word looks like this:\n\nNAME: Forth Word - A variable length ASCII NUL terminated string\nPWD: Previous Word Pointer, points to the previous word\nMISC: Flags, code word and offset from previous word pointer to start of Forth word string\nCODE\/DATA: The body of the forth word definition, not interested in this.\n\nThere is a register which stores the latest defined word which can be\naccessed with the code \"pwd @\". In order to print out a word we need to\naccess a words MISC field, the offset to the NAME is stored here in bits\n8 to 15 and the offset is calculated from the PWD field.\n\n\"print\" expects a character address, so we need to multiply any calculated\naddress by the word size in bytes. )\n\n: words ( -- : print out all defined an visible words )\n\tlatest\n\tbegin\n\t\tdup\n\t\thidden? hide-words @ and\n\t\tnot if\n\t\t\tname\n\t\t\tprint space\n\t\telse\n\t\t\tdrop\n\t\tthen\n\t\t@ ( Get pointer to previous word )\n\t\tdup dictionary-start u< ( stop if pwd no longer points to a word )\n\tuntil\n\tdrop cr\n;\nhider hide-words\n\n: TrueFalse ( -- : print true or false )\n\tif \" true\" else \" false\" then ;\n\n: registers ( -- : print out important registers and information about the virtual machine )\n\t\" return stack pointer: \" r@ . cr\n\t\" dictionary pointer \" here . cr\n\t\" previous word: \" pwd ? cr\n\t\" state: \" state ? cr\n\t\" base: \" base ? cr\n\t\" depth: \" depth . cr\n\t\" cell size (in bytes): \" size . cr\n\t\" last cell address: \" max-core . cr\n\t\" unused cells: \" unused . cr\n\t\" invalid: \" `invalid @ TrueFalse cr\n\t\" size of variable stack: \" `stack-size ? cr\n\t\" size of return stack: \" `stack-size ? cr\n\t\" start of variable stack: \" max-core `stack-size @ 2* - . cr\n\t\" start of return stack: \" max-core `stack-size @ - . cr\n\t\" current input source: \" source-id -1 = if \" string\" else \" file\" then cr\n\t\" reading from stdin: \" source-id 0 = stdin? and TrueFalse cr\n\t\" tracing on: \" `debug @ TrueFalse cr\n\t\" starting word: \" `instruction ? cr\n\t\" real start address: \" `start-address ? cr\n\t\" error handling: \" `error-handler ? cr\n(\n `sin `sidx `slen `fout\n `stdout `stderr `argc `argv )\n;\n\n: y\/n? ( -- bool : ask a yes or no question )\n\tkey drop\n\t\" y\/n? \"\n\tbegin\n\t\tkey\n\t\tdup\n\t\t[char] y = if true exit then\n\t\t[char] n = if false exit then\n\t\t\" y\/n? \"\n\tagain ;\n\n: >instruction ( extract instruction from instruction field ) 0x1f and ;\n\n: step\n\t( step through a word: this word could be augmented\n\twith commands such as \"dump\", \"halt\", and optional\n\t\".s\" and \"registers\" )\n\tregisters\n\t\" .s: \" .s cr\n\t\" -- press any key to continue -- \"\n\tkey drop ;\n\n: more ( -- : wait for more input )\n\t\" -- press any key to continue -- \" key drop cr page ;\n\n: debug-help ( -- : this is not quite ready for prime time )\n \" debug mode commands\n\th - print help\n\tq - exit containing word\n\tr - print registers\n\ts - print stack\n\tc - continue on with execution\n\" ;\n: debug-prompt \n\t.\" debug> \" ;\n\n: debug ( a work in progress, debugging support, needs parse-word )\n\tkey drop\n\tcr\n\tbegin\n\t\tdebug-prompt\n\t\tkey dup '\\n' <> if source accept drop then\n\t\tcase\n\t\t\t[char] h of debug-help endof\n\t\t\t[char] q of bye endof\n\t\t\t[char] r of registers endof\n\t\t\t[char] s of >r .s r> endof\n\t\t\t[char] c of drop exit endof\n\t\tendcase drop\n\tagain ;\nhider debug-prompt\n\n0 variable cf\n: code>pwd ( CODE -- PWD\/0 )\n\t( @todo simplify using \"within\"\n\t given a pointer to a executable code field\n\tthis words attempts to find the PWD field for\n\tthat word, or return zero )\n\tdup dictionary-start here within not if drop 0 exit then\n\tcf !\n\tlatest dup @ ( p1 p2 )\n\tbegin\n\t\tover ( p1 p2 p1 )\n\t\tcf @ u<= swap cf @ > and if exit then\n\t\tdup 0= if exit then\n\t\tdup @ swap\n\tagain\n;\nhider cf\n\n: end-print ( x -- )\n\t\"\t\t=> \" . \" ]\" ;\n\n: word-printer\n\t( attempt to print out a word given a words code field\n\tWARNING: This is a dirty hack at the moment\n\tNOTE: given a pointer to somewhere in a word it is possible\n\tto work out the PWD by looping through the dictionary to\n\tfind the PWD below it )\n\t1- dup @ -1 = if \" [ noname\" end-print exit then\n\t dup \" [ \" code>pwd dup if name print else drop \" data\" then\n\t end-print ;\nhider end-print\n\n( these words push the execution tokens for various special cases for decompilation )\n: get-branch [ find branch cfa ] literal ;\n: get-?branch [ find ?branch cfa ] literal ;\n: get-original-exit [ original-exit cfa ] literal ;\n: get-quote [ find ' cfa ] literal ;\n\n: branch-increment ( addr branch -- increment : calculate decompile increment for \"branch\" )\n\t1+ dup negative? if drop 2 else 2dup dump then ;\n\n( these words take a code field to a primitive they implement, decompile it\nand any data belonging to that operation, and push a number to increment the\ndecompilers code stream pointer by )\n: decompile-literal ( code -- increment )\n\t\" [ literal\t=> \" 1+ ? \" ]\" 2 ;\n: decompile-branch ( code -- increment )\n\t\" [ branch\t=> \" 1+ ? \" ]\" dup 1+ @ branch-increment ;\n: decompile-quote ( code -- increment )\n\t\" [ '\t=> \" 1+ @ word-printer \" ]\" 2 ;\n: decompile-?branch ( code -- increment )\n\t\" [ ?branch\t=> \" 1+ ? \" ]\" 2 ;\n\n( @todo decompile :noname, make the output look better\n\nThe decompile word expects a pointer to the code field of a word, it\ndecompiles a words code field, it needs a lot of work however.\nThere are several complications to implementing this decompile\nfunction.\n\n\t' The next cell should be pushed\n\t:noname This has a marker before its code field of -1 which\n\t\t cannot occur normally, this is handles in word-printer\n\tbranch branches are used to skip over data, but also for\n\t\t some branch constructs, any data in between can only\n\t\t be printed out generally speaking\n\texit There are two definitions of exit, the one used in\n\t\t ';' and the one everything else uses, this is used\n\t\t to determine the actual end of the word\n\tliterals Literals can be distinguished by their low value,\n\t\t which cannot possibly be a word with a name, the\n\t\t next field is the actual literal\n\n@todo addi also needs handling, it is another special case used by\n\"do...loop\" [which should be replaced].\n\nOf special difficult is processing 'if' 'else' 'then' statements,\nthis will require keeping track of '?branch'.\n\nAlso of note, a number greater than \"here\" must be data )\n\n: decompile ( code-field-ptr -- : decompile a word )\n\tbegin\n\t\ttab\n\t\tdup @\n\t\tcase\n\t\t\tdolit of drup decompile-literal endof\n\t\t\tget-branch of drup decompile-branch endof\n\t\t\tget-quote of drup decompile-quote endof\n\t\t\tget-?branch of drup decompile-?branch endof\n\t\t\tget-original-exit of 2drop \" [ exit ]\" cr exit endof\n\t\t\tword-printer 1\n\t\tendcase\n\t\t+\n\t\tcr\n\tagain ;\n\n:hide\n\tword-printer get-branch get-?branch get-original-exit \n\tget-quote branch-increment decompile-literal \n\tdecompile-branch decompile-?branch decompile-quote\n;hide\n\n: xt-instruction ( extract instruction from execution token )\n\tcfa @ >instruction ;\n\n( these words expect a pointer to the PWD field of a word )\n: defined-word? xt-instruction dolist = ;\n: print-name \" name: \" name print cr ;\n: print-start \" word start: \" name chars . cr ;\n: print-previous \" previous word: \" @ . cr ;\n: print-immediate \" immediate: \" 1+ @ >instruction compile-instruction <> TrueFalse cr ;\n: print-instruction \" instruction: \" xt-instruction . cr ;\n: print-defined \" defined: \" defined-word? TrueFalse cr ;\n\n: print-header ( PWD -- is-immediate-word? )\n\tdup print-name\n\tdup print-start\n\tdup print-previous\n\tdup print-immediate\n\tdup print-instruction ( @todo look up instruction name )\n\tprint-defined ;\n\n: see ( -- : decompile the next word in the input stream )\n\t( decompile a word )\n\tfind\n\tdup 0= if drop error-no-word exit then\n\t1- ( move to PWD field )\n\tdup print-header\n\tdup defined-word?\n\tif ( decompile if a compiled word )\n\t\tcfa 1+ ( move to code field )\n\t\t\" code field:\" cr\n\t\tdecompile\n\telse ( the instruction describes the word if it is not a compiled word )\n\t\tdrop\n\tthen ;\n\n( These help messages could be moved to blocks, the blocks could then\nbe loaded from disk and printed instead of defining the help here,\nthis would allow much larger help )\n\n: help ( -- : print out a short help message )\n\tpage\n\tkey drop\n\" Welcome to Forth, an imperative stack based language. It is both a low\nlevel and a high level language, with a very small memory footprint. Most\nof Forth is defined as a combination of various primitives.\n\nA short description of the available function (or Forth words) follows,\nwords marked (1) are immediate and cannot be used in command mode, words\nmarked with (2) define new words. Words marked with (3) have both command\nand compile functionality.\n\n\"\nmore \" The built in words that accessible are:\n\n(1,2)\t: define a new word, switching to compile mode\n\timmediate make latest defined word immediate\n\tread read in a word, execute in command mode else compile\n\t@ ! fetch, store\n\tc@ c! character based fetch and store\n\t- + * \/ standard arithmetic operations,\n\tand or xor invert standard bitwise operations\n\tlshift rshift left and right bit shift\n\tu< u> < > = comparison predicates\n\texit exit from a word\n\temit print character from top of stack\n\tkey get a character from input\n\tr> >r pop a value from or to the return stack\n\tfind find a word in the dictionary and push the location\n\t' store the address of the following word on the stack\n\t, write the top of the stack to the dictionary\n\tbsave bload save or load a block at address to indexed file\n\tswap swap first two values on the stack\n\tdup duplicate the top of the stack\n\tdrop pop and drop a value\n\tover copy the second stack value over the first\n\t. pop the top of the stack and print it\n\" \nmore \" \n\tprint print a NUL terminated string at a character address\n\tdepth get the current stack depth\n\tclock get the time since execution start in milliseconds\n\tevaluate evaluate a string\n\tsystem execute a system command\n\tclose-file close a file handle\n\topen-file open a file handle\n\tdelete-file delete a file off disk given a string\n\tread-file read in characters from a file\n\twrite-file write characters to a file\n\tfile-position get the file offset\n\treposition-file reposition the file pointer\n\tflush-file flush a file to disk\n\trename-file rename a file on disk\n \"\n\nmore \" All of the other words in the interpreter are built from these\nprimitive words. A few examples:\n\n(1)\tif...else...then FORTH branching construct\n(1)\tbegin...until loop until top of stack is non zero\n(1)\tbegin...again infinite loop\n(1)\tdo...loop FORTH looping construct\n(2,3)\tcreate create a new word that pushes its location\n(1)\tdoes> declare a created words run time behaviour\n(1,2)\tvariable declare variable with initial value from top of stack\n(1,2)\tconstant declare a constant, taken from top of stack\n(1,2)\tarray declare an array with size taken from top of stack\n(1)\t; terminate a word definition and return to command mode\n\twords print out a list of all the defined words\n\thelp this help message\n\tdump print out memory contents starting at an address\n\tregisters print out the contents of the registers\n\tsee decompile a word, viewing what words compose it\n\t.s print out the contents of the stack\n\n\"\n\nmore \" Some more advanced words:\n\n\there push the dictionary pointer\n\th push the address of the dictionary pointer\n\tr push the return stack pointer\n\tallot allocate space in the dictionary\n(1)\t[ switch to command mode\n\t] switch to compile mode\n\t:: compile ':' into the dictionary\n\n\" more \"\nFor more information either consult the manual pages forth(1) and libforth(1)\nor consult the following sources:\n\n\thttps:\/\/github.com\/howerj\/libforth\n\thttp:\/\/work.anapnea.net\/html\/html\/projects.html\n\nAnd for a larger tutorial:\n\n\thttps:\/\/github.com\/howerj\/libforth\/blob\/master\/readme.md\n\nFor resources on Forth:\n\n\thttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\thttps:\/\/rwmj.wordpress.com\/2010\/08\/07\/jonesforth-git-repository\/\n\n -- end --\n\" cr\n;\n\n( ==================== Files ================================== )\n\n( @todo implement the other file access methods in terms of the\n built in ones [see http:\/\/forth.sourceforge.net\/std\/dpans\/dpans11.htm]\n @todo read-line and write-line need their flag and ior setting correctly\n\n\tFILE-SIZE [ use file-positions ]\n\tINCLUDE-FILE \n\tINCLUDED\n\tFILE-STATUS\n\n Also of note:\t\n * Source ID needs extending. )\n\n: read-char ( c-addr fileid -- ior : read a char )\n\t1 swap read-file swap 1 = if drop -1 then ;\n\n: write-char ( c-addr fileid -- ior : write a char )\n\t1 swap write-file swap 1 = if drop -1 then ;\n\n: read-line ( c-addr u1 fileid -- u2 flag ior : read in a line of text )\n\t-rot bounds\n\tdo\n\t\tdup i swap read-char drop\n\t\ti c@ '\\n' = if drop i 0 0 leave then\n\tloop drop ;\n\n: write-line ( c-addr u fileid -- u2 flag ior : write a line of text )\n\t-rot bounds\n\tdo\n\t\tdup i swap write-char drop\n\t\ti c@ '\\n' = if drop i 0 0 leave then\n\tloop ;\n\n: resize-file ( ud fileid -- ior : attempt to resize a file )\n\t( There is no portable way to truncate a file :C )\n\t2drop -1 ( -1 to indicate failure ) ;\n\n: create-file ( c-addr u fam -- fileid ior )\n\topen-file ;\n\n: bin ( fam1 -- fam2 : modify a file access method to be binary not line oriented ) \n\t( Do nothing, all file access methods are binary, although of note\n\tthe already opened files stdin, stdout and stderr are opened in text\n\tmode on Windows platforms, but they are not file access methods, they\n\tare fileids )\n\t;\n\n( ==================== Files ================================== )\n\n( ==================== Blocks ================================= )\n\n( @todo process invalid blocks [anything greater or equal to 0xFFFF] )\n( @todo only already created blocks can be loaded, this should be\n corrected so one is created if needed )\n( @todo better error handling )\n( @todo Use char-table )\n( @todo Fix this! )\n\n-1 variable scr-var\nfalse variable dirty ( has the buffer been modified? )\n: scr ( -- x : last screen used ) scr-var @ ;\nb\/buf char-table block-buffer ( block buffer - enough to store one block )\n\n: update ( -- : mark block buffer as dirty, so it will be flushed if needed )\n\ttrue dirty ! ;\n: clean ( -- : mark buffers as clean, even if they are dirty )\n\tfalse dirty ! ;\n\n0 variable make-block-char ( the character buffers are filled with in make-block )\n\n: erase-buffer\n\tblock-buffer make-block-char @ fill ;\n\n: empty-buffers ( -- : discard any buffers )\n\tclean block-buffer erase-buffer ;\n\n: invalid ( block-buffer -- : check if the block buffer is invalid )\n\t-1 = if abort\" invalid block buffer (-1)\" then ;\n\n: flush ( -- : flush dirty block buffers )\n\tdirty @ if scr invalid block-buffer drop scr bsave drop clean then ;\n\n: list ( block-number -- : display a block )\n\tflush \n\ttrip scr <> if\n\t\tblock-buffer drop swap bload ( load buffer into block buffer )\n\t\tswap scr-var !\n\telse\n\t\t2drop 0\n\tthen\n\t-1 = if exit then ( failed to load )\n\tblock-buffer type ; ( print buffer )\n\n: block ( u -- addr : load block 'u' and push address to block )\n\tdup invalid\n\ttrip scr <> if flush block-buffer drop swap bload then\n\t-1 = if -1 else scr-var ! block-buffer drop chars then ;\n\n: save-buffers ( -- : save all updated buffers )\n\tflush ;\n\n: list-thru ( x y -- : list blocks x through to y )\n\t1+ swap\n\tkey drop\n\tdo i invalid \" screen no: \" i . cr i list cr more loop ;\n\n: open-file-or-abort\n\t>r 2dup r> open-file ?dup 0= if type \" : \" abort\" file open failed\" else >r 2drop r> then ;\n\n: make-block ( c-addr u -- : make a block on disk, named after a string )\n\tw\/o open-file-or-abort\n\tflush -1 scr-var !\n\terase-buffer\n\tblock-buffer rot dup >r write-file r> close-file drop\n\t0<> if drop abort\" write failed\" then\n\tb\/buf <> if abort\" could not write buffer out\" then ;\n\n:hide scr-var block-buffer clean invalid erase-buffer make-block-char ;hide\n\n( ==================== Blocks ================================= )\n\n( ==================== Matcher ================================ )\n\\ Translated from http:\/\/c-faq.com\/lib\/regex.html\n\\ int match(char *pat, char *str)\n\\ {\n\\ \tswitch(*pat) {\n\\ \tcase '\\0': return !*str;\n\\ \tcase '*': return match(pat+1, str) || *str && match(pat, str+1);\n\\ \tcase '?': return *str && match(pat+1, str+1);\n\\ \tdefault: return *pat == *str && match(pat+1, str+1);\n\\ \t}\n\\ }\n\n: *pat ( regex -- regex char ) \n\tdup c@ ;\n\n: *str ( string regex -- string regex char )\n\tover c@ ;\n\n: pass ( c-addr1 c-addr2 -- : bool ) \n\t2drop 1 ;\n: fail ( c-addr1 c-addr2 -- : bool ) \n\t2drop 0 ;\n\n: *pat==*str ( c-addr1 c-addr2 -- c-addr1 c-addr2 bool )\n\t2dup c@ swap c@ = ;\n\n: ++ ( u1 u2 u3 u4 -- u1+u3 u2+u4 : not quite d+ [does no carry] )\n\tswap >r + swap r> + swap ;\n\ndefer matcher\n\n: advance ( string regex char -- bool : advance both regex and string )\n\tif 1 1 ++ matcher else fail then ;\n: advance-string ( string regex char -- bool : advance only the string )\n\tif 1 0 ++ matcher else fail then ;\n: advance-regex ( string regex -- bool : advance matching )\n\t2dup 0 1 ++ matcher if pass else *str advance-string then ;\n\n: match ( string regex -- bool : match a ASCIIZ pattern against an ASCIIZ string )\n\t( @todo Add limits and accept two Forth strings, making sure they are both\n\t ASCIIZ strings as well \n\t @todo Case insensitive version\n\t @warning This uses a non-standards compliant version of case! )\n\t*pat\n\tcase\n\t\t 0 of drop drop c@ not exit endof\n\t\t[char] * of drop advance-regex exit endof\n\t\t[char] ? of drop *str advance exit endof\n\t\t drop *pat==*str advance exit\n\tendcase ;\n\nmatcher is match\n\n:hide \n\t*str *pat *pat==*str pass fail advance \n\tadvance-string advance-regex matcher ++ \n;hide\n\n( ==================== Matcher ================================ )\n\n\n( ==================== Cons Cells ============================= )\n\n( \nFrom http:\/\/sametwice.com\/cons.fs, this could be improved if the optional\nmemory allocation words were added to the interpreter. This provides\na simple \"cons cell\" data structure. There is currently no way to\nfree allocated cells \n)\n\n: car! ( cons-addr -- : store a value in the car cell of a cons cell ) \n\t! ;\n: cdr! ( cons-addr -- : store a value in the cdr cell of a cons cell )\n\tcell+ ! ;\n: car@ ( cons-addr -- car-val : retrieve car value from cons cell )\n\t@ ;\n: cdr@ ( cons-addr -- cdr-val : retrieve cdr value from cons cell )\n\tcell+ @ ;\n: cons ( car-val cdr-val -- cons-addr : allocate a new cons cell )\n\tswap here >r , , r> ;\n: cons0 0 0 cons ;\n\n( ==================== Cons Cells ============================= )\n\n( ==================== Miscellaneous ========================== )\n\n( @todo use check-within in various primitives like \"array\" )\n: check-within ( x min max -- : abort if x is not within a range )\n\twithin not if abort\" limit exceeded\" then ;\n\n: enum ( x \" ccc\" -- x+1 : define a series of enumerations )\n\tdup constant 1+ ; ( better would be a :enum ;enum syntax )\n\n: compare ( c-addr1 u1 c-addr2 u2 -- n : compare two strings, assumes strings are NUL terminated )\n\trot min\n\t0 do ( should be ?do )\n\t\t2dup\n\t\ti + c@ swap i + c@\n\t\t<=> dup if leave else drop then\n\tloop\n\t2drop ;\n\n: 2rot ( n1 n2 n3 n4 n5 n6 \u2013 n3 n4 n5 n6 n1 n2 )\n\t5 roll 5 roll ;\n\n: license ( -- : print out license information )\n\" \nThe MIT License (MIT)\n\nCopyright (c) 2016 Richard James Howe\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the 'Software'),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand\/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\nTHE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\nOTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\nARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE. \n\n\" \n;\n\n: welcome ( -- : print out a stupid welcome message which most interpreters seems insistent on)\n\t\" FORTH: libforth successfully loaded.\" cr\n\t\" Type 'help' and press return for a basic introduction.\" cr\n\t\" Type 'license' and press return to see the license. (MIT license).\" cr\n\t\" Core: \" here . \" \/ \" here unused + . cr\n\tok ;\n\n( @todo Improve this function! )\n: reader immediate \n\twelcome\n\tbegin read \" ok\" cr again ;\n( find reader start! warm )\n\n( ==================== Core utilities ======================== )\n\n( @todo Implement an equivalent to \"core.c\" here )\n( @todo Process a Forth core file and spit out a C structure\n containing information that describes the core file )\n( @todo Implement a series of words for manipulating cell sizes\n that are larger or smaller, and possibly of a different endianess\n to the currently running virtual machine )\n\n8 constant header-size ( size of Forth core file header )\n8 constant size-field-size ( the size in bytes of the size field in the core file )\n0 variable core-file ( core fileid we are reading in )\n0 variable core-cell-size ( cell size of Forth core )\n0 variable core-version ( version of core file )\n0 variable core-endianess ( endianess of core we are reading in )\n\n( save space to read in header )\ncreate header header-size chars allot\n: cheader ( -- c-addr : header char address )\n\theader chars> ;\ncreate size-field size-field-size chars allot\n: csize-field ( -- c-addr : address of place size field is stored in )\n\tsize-field chars> ;\n\n0\nenum header-magic0\nenum header-magic1\nenum header-magic2\nenum header-magic3\nenum header-cell-size\nenum header-version\nenum header-endianess\nenum header-magic4 \n\n: cleanup ( -- : cleanup before abort )\n\tcore-file @ ?dup 0<> if close-file drop then ;\n\n: invalid-header ( bool -- : abort if header is invalid )\n\t<> if cleanup abort\" invalid header\" then ;\n\n: save-core-cell-size ( char -- : save the core file cell size, checking if it is valid )\n\tcore-cell-size !\n\t\" cell size:\" tab\n\tcore-cell-size @ 2 = if 2 . cr exit then\n\tcore-cell-size @ 4 = if 4 . cr exit then\n\tcore-cell-size @ 8 = if 8 . cr exit then\n\tcleanup core-cell-size @ . abort\" : invalid cell size\" ;\n\n: check-version-compatibility ( char -- : checks the version compatibility of the core file ) \n\tcore-version !\n\tcore-version @ 2 = if \" core ver:\t2\" cr exit then\n\tcleanup core-version @ . abort\" : unknown version number\" ;\n\n: save-endianess ( char -- : save the endianess, checking if it is valid )\n\tcore-endianess !\n\t\" endianess:\" tab\n\tcore-endianess @ 0 = if \" big\" cr exit then\n\tcore-endianess @ 1 = if \" little\" cr exit then\n\tcleanup core-endianess @ . abort\" invalid endianess\" then ;\n\n: read-or-abort ( c-addr size fileid -- : )\n\tover >r read-file \n\t 0<> if cleanup abort\" file read failed\" then\n\tr> <> if cleanup abort\" header too small\" then ;\n\n: header? ( -- : print out header information )\n\tcheader header-size core-file @ read-or-abort\n\t( \" raw header:\" header 2 dump )\n\tcheader header-magic0 + c@ 255 invalid-header\n\tcheader header-magic1 + c@ [char] 4 invalid-header\n\tcheader header-magic2 + c@ [char] T invalid-header\n\tcheader header-magic3 + c@ [char] H invalid-header\n\tcheader header-cell-size + c@ save-core-cell-size\n\tcheader header-version + c@ check-version-compatibility\n\tcheader header-endianess + c@ save-endianess\n\tcheader header-magic4 + c@ 255 invalid-header\n\t\" valid header\" cr ;\n\n: size? ( -- : print out core file size )\n\tcsize-field size-field-size core-file @ read-or-abort\n\t( @todo improve method for printing out size )\n\t\" size: \" size-field size-field-size chars dump ;\n\n\n: core ( c-addr u -- : )\n\t2dup \" core file:\" tab type cr\n\tr\/o open-file-or-abort core-file ! \n\theader?\n\tsize?\n\tcore-file @ close-file drop ;\n\n( s\" forth.core\" core )\n\n:hide \nheader-size header? \nheader-magic0 header-magic1 header-magic2 header-magic3\nheader-version header-cell-size header-endianess header-magic4\nheader \ncore-file save-core-cell-size check-version-compatibility\ncore-cell-size cheader\ncore-endianess core-version save-endianess invalid-header\ncleanup size-field csize-field size-field-size\nread-or-abort size?\n;hide\n\n( ==================== Core utilities ======================== )\n\n( \nLooking at most Forths dictionary with \"words\" command they tend\nto have a lot of words that do not mean anything but to the implementers\nof that specific Forth, here we clean up as many non standard words as\npossible.\n)\n:hide\n write-string do-string ')' alignment-bits print-string\n compile-instruction dictionary-start hidden? hidden-mask instruction-mask\n max-core dolist x x! x@ write-exit\n max-string-length error-no-word\n original-exit\n pnum\n TrueFalse >instruction print-header\n print-name print-start print-previous print-immediate\n print-instruction xt-instruction defined-word? print-defined\n `state\n `source-id `sin `sidx `slen `start-address `fin `fout `stdin\n `stdout `stderr `argc `argv `debug `invalid `top `instruction\n `stack-size `error-handler\n open-file-or-abort\n;hide\n\n( \n## Forth To List\n\nThe following is a To-Do list for the Forth code itself, along with any\nother ideas.\n\n* Rewrite starting word using \"restart-word!\"\n* Word, Parse, other forth words\n* add \"j\" if possible to get outer loop context\n* FORTH, VOCABULARY\n* \"Value\", \"To\", \"Is\"\n* Double cell words and floating point library\n* The interpreter should use character based addresses, instead of\nword based, and use values that are actual valid pointers, this\nwill allow easier interaction with the world outside the virtual machine\n* Abort\", this could be used to implement words such\nas \"abort if in compile mode\", or \"abort if in command mode\".\n* common words and actions should be factored out to simplify\ndefinitions of other words, their standards compliant version found\nif any\n* throw and exception\n* here documents, string literals\n* A set of words for navigating around word definitions would be\nhelp debugging words, for example:\n\tcompile-field code-field field-translate\nwould take a pointer to a compile field for a word and translate\nthat into the code field\n* proper booleans should be used throughout\n* virtual machines could be made in other languages than C that will\nrun the core files generated...The virtual machine has higher level\nfunctions in it that it probably should not have, like \"read\" and\n\"system\", these belong elsewhere - but where?\n* It would be interesting to see which Unix utilities could easily\nbe implemented as Forth programs, such as \"head\", \"tail\", \"cat\", \"tr\",\n\"grep\", etcetera.\n* A utility for compressing core files could be made in Forth, it would mimic\nthe \"rle.c\" program previously present in the repository - that is it would\nuse run length encoding.\n* The manual pages, and various PDF files, should be generated using pandoc.\nThe manual page for the forth library can be generated from the header file, which\nwill need special preparation [a markdown file will have to be generated from the\nheader file, that file can the be used for the manual page].\n\nSome interesting links:\n\t* http:\/\/www.figuk.plus.com\/build\/heart.htm\n\t* https:\/\/groups.google.com\/forum\/#!msg\/comp.lang.forth\/NS2icrCj1jQ\/1btBCkOWr9wJ\n\t* http:\/\/newsgroups.derkeiler.com\/Archive\/Comp\/comp.lang.forth\/2005-09\/msg00337.html\n\t* https:\/\/stackoverflow.com\/questions\/407987\/what-are-the-primitive-forth-operators\n)\n\n\n( \nThe following will not work as we might actually be reading from a string [`sin]\nnot `fin. \n: key 32 chars> 1 `fin @ read-file drop 0 = if 0 else 32 chars> c@ then ;\n\n: s>d \\ x -- d : convert a signed value to a double width cell \n\tdup 0< if true else false then ;\n)\n\n","old_contents":"( \nWelcome to libforth, A dialect of Forth. Like all versions of Forth this\nversion is a little idiosyncratic, but how the interpreter works is\ndocumented here and in various other files.\n\nThis file contains most of the start up code, some basic start up code\nis executed in the C file as well which makes programming at least bearable.\nMost of Forth is programmed in itself, which may seem odd if your back\nground in programming comes from more traditional language [such as C],\nalthough less so if you know already know lisp.\n\nFor more information about this interpreter and Forth see:\n\thttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\treadme.md : for a manual for this interpreter\n\tlibforth.h : for information about the C API\n\tlibforth.3 : for limited information about the C API\n\tlibforth.c : for the interpreter itself\n\tunit.c : a series of unit tests against libforth.c\n\tunit.fth : a series of unit tests against this file\n\nThe interpreter and this code originally descend from a Forth interpreter\nwritten in 1992 for the International obfuscated C Coding Competition\n\nSee:\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\nThe manual for the interpreter should be read first before looking into this\ncode. It is important to understand the execution model of Forth, especially\nthe differences between command and compile mode, and how immediate and compiling\nwords work.\n\nThe structure of this file is as follows:\n\n1. Basic Word Set\n2. Extended Word Set\n3. CREATE DOES>\n4. CASE statements\n5. Conditional Compilation\n6. Endian Words\n7. Misc words\n8. Random Numbers\n9. ANSI Escape Codes\n10. Prime Numbers\n11. Debugging info\n12. Files\n13. Blocks\n14. Matcher\n15. Cons Cells\n16. Miscellaneous\n17. Core utilities\n\nEach of these sections is clearly labeled and they are generally in dependency order.\n)\n\n( ========================== Basic Word Set ================================== )\n\n( \nWe'll begin by defining very simple words we can use later, these a very\nbasic words, that perform simple tasks, they will not require much explanation.\n\nEven though the words are simple, their stack comment and a description for\nthem will still be included so external tools can process and automatically\nextract the document string for a given work.\n)\n\n: 1+ ( x -- x : increment a number )\n\t1 + ;\n\n: 1- ( x -- x : decrement a number )\n\t1 - ;\n\n: chars ( c-addr -- addr : convert a character address to an address )\n\tsize \/ ; \n\n: chars> ( addr -- c-addr: convert an address to a character address )\n\tsize * ; \n\n: tab ( -- : print a tab character to current output device )\n\t9 emit ;\n\n: 0= ( x -- bool : is 'x' equal to zero? )\n\t0 = ;\n\n: not ( x -- bool : is 'x' true? )\n\t0= ;\n\n: <> ( x x -- bool : not equal )\n\t= 0= ;\n\n: logical ( x -- bool : turn a value into a boolean ) \n\tnot not ;\n\n: :: ( -- : compiling version of ':' )\n\t[ find : , ] ;\n\n: '\\n' ( -- n : push the newline character )\n\t10 ;\n\n: cr ( -- : emit a newline character )\n\t'\\n' emit ;\n\n: hidden-mask ( -- x : pushes mask for the hide bit in a words MISC field )\n\t0x80 ;\n\n: instruction-mask ( -- x : pushes mask for the first code word in a words MISC field )\n\t0x1f ;\n\n: hidden? ( PWD -- PWD bool : is a word hidden, given the words PWD field ) \n\tdup 1+ @ hidden-mask and logical ;\n\n: compile-instruction ( -- instruction : compile code word, threaded code interpreter instruction )\n\t1 ; \n\n: dolist ( -- x : run code word, threaded code interpreter instruction )\n\t2 ; \n\n: dolit ( -- x : location of special \"push\" word )\n\t2 ;\n\n: 2, ( x x -- : write two values into the dictionary )\n\t, , ;\n\n: [literal] ( x -- : write a literal into the dictionary )\n\tdolit 2, ; \n\n: literal ( x -- : immediately write a literal into the dictionary )\n\timmediate [literal] ;\n\n: min-signed-integer ( -- x : push the minimum signed integer value )\n\t[ -1 -1 1 rshift invert and ] literal ;\n\n: max-signed-integer ( -- x : push the maximum signed integer value )\n\t[ min-signed-integer invert ] literal ;\n\n: < ( x1 x2 -- bool : signed less than comparison )\n\t- dup if max-signed-integer u> else logical then ;\n\n: > ( x1 x2 -- bool : signed greater than comparison )\n\t< not ;\n\n: 2literal immediate ( x x -- : immediate write two literals into the dictionary )\n\tswap [literal] [literal] ;\n\n: latest ( get latest defined word )\n\tpwd @ ; \n\n: stdin ( -- fileid : push the fileid for the standard input channel ) \n\t`stdin @ ;\n\n: stdout ( -- fileid : push the fileid for the standard output channel ) \n\t`stdout @ ;\n\n: stderr ( -- fileid : push the fileid for the standard error channel ) \n\t`stderr @ ;\n\n: stdin? ( -- bool : are we reading from standard input )\n\t`fin @ stdin = ;\n\n: false ( -- x : push the value representing false )\n\t0 ;\n\n: true ( -- x : push the value representing true )\n\t1 ;\n\n: *+ ( x1 x2 x3 -- x ) \n\t* + ;\n\t\n: 2- ( x -- x : decrement by two )\n\t2 - ( x -- x ) ;\n\n: 2+ ( x -- x : increment by two )\n\t2 + ( x -- x ) ;\n\n: 3+ ( x -- x : increment by three )\n\t3 + ( x -- x ) ;\n\n: 2* ( x -- x : multiply by two )\n\t1 lshift ( x -- x ) ;\n\n: 2\/ ( x -- x : divide by two )\n\t1 rshift ( x -- x ) ;\n\n: 4* ( x -- x : multiply by four )\n\t2 lshift ( x -- x ) ;\n\n: 4\/ ( x -- x : divide by four )\n\t2 rshift ( x -- x ) ;\n\n: 8* ( x -- x : multiply by eight )\n\t3 lshift ( x -- x ) ;\n\n: 8\/ ( x -- x : divide by eight )\n\t3 rshift ( x -- x ) ;\n\n: 256* ( x -- x : multiply by 256 )\n\t8 lshift ( x -- x ) ;\n\n: 256\/ ( x -- x : divide by 256 )\n\t8 rshift ( x -- x ) ;\n\n: 2dup ( x1 x2 -- x1 x2 x1 x2 : duplicate two values )\n\tover over ;\n\n: mod ( x u -- x : calculate the remainder of x divided by u ) \n\t2dup \/ * - ;\n\n: *\/ ( x1 x2 x3 -- x4 : multiply then divide, @warning this does not use a double cell for the multiply )\n\t * \/ ; \n\n: char ( -- x : read in a character from the input steam )\n\tkey drop key ;\n\n: [char] ( -- x : immediately read in a character from the input stream )\n\timmediate char [literal] ;\n\n: postpone ( -- : postpone execution of the following immediate word )\n\timmediate find , ;\n\n: unless ( bool -- : like 'if' but execute clause if false )\n\timmediate ' 0= , postpone if ;\n\n: endif ( synonym for 'then' ) \n\timmediate postpone then ;\n\n: cell+ ( a-addr1 -- a-addr2 ) \n\t1+ ;\n\n: cells ( n1 -- n2 ) \n\timmediate ;\n\n: cell ( -- u : defined as 1 cells )\n\t1 cells ;\n\n: address-unit-bits ( -- x : push the number of bits in an address )\n\t[ cell size 8* * ] literal ;\n\n: negative? ( x -- bool : is a number negative? )\n\t[ 1 address-unit-bits 1- lshift ] literal and logical ;\n\n: mask-byte ( x -- x : mask off a ) \n\t8* 0xff swap lshift ;\n\n: select-byte ( u i -- c ) \n\t8* rshift 0xff and ;\n\n: char+ ( c-addr -- c-addr : increment a character address by the size of one character ) \n\t1+ ;\n\n: 2chars ( c-addr1 c-addr2 -- addr addr : convert two character addresses to two cell addresses ) \n\tchars swap chars swap ;\n\n: 2chars> ( addr addr -- c-addr c-addr: convert two cell addresses to two character addresses )\n\tchars> swap chars> swap ;\n\n: hex ( -- : print out hex ) \n\t16 base ! ;\n\n: octal ( -- : print out octal ) \n\t8 base ! ;\n\n: binary ( -- : print out binary ) \n\t2 base ! ;\n\n: decimal ( -- : print out decimal ) \n\t0 base ! ;\n\n: negate ( x -- x ) \n\t-1 * ;\n\n: square ( x -- x ) \n\tdup * ;\n\n: drup ( x y -- x x ) \n\tdrop dup ;\n\n: +! ( x addr -- : add x to a value stored at addr ) \n\ttuck @ + swap ! ;\n\n: 1+! ( addr -- : increment a value at an address ) \n\t1 swap +! ;\n\n: 1-! ( addr -- : decrement a value at an address ) \n\t-1 swap +! ;\n\n: lsb ( x -- x : mask off the least significant byte of a cell ) \n\t255 and ;\n\n: \\ ( -- : immediate word, used for single line comments )\n\timmediate begin key '\\n' = until ;\n\n: ?dup ( x -- ? ) \n\tdup if dup then ;\n\n: min ( x y -- min ) \n\t2dup < if drop else swap drop then ;\n\n: max ( x y -- max ) \n\t2dup > if drop else swap drop then ;\n\n: >= ( x y -- bool ) \n\t< not ;\n\n: <= ( x y -- bool ) \n\t> not ;\n\n: 2@ ( a-addr -- x1 x2 : load two consecutive memory cells )\n\tdup 1+ @ swap @ ;\n\n: 2! ( x1 x2 a-addr -- : store two values as two consecutive memory cells )\n\t2dup ! nip 1+ ! ;\n\n: r@ ( -- x, R: x -- )\n\tr> r @ swap >r ;\n\n: 0> ( x -- bool )\n\t0 < ;\n\n: 0< ( x -- bool )\n\t0 > ;\n\n: 0<> ( x -- bool )\n\t0 <> ;\n\n: nand ( x x -- x : Logical NAND ) \n\tand not ;\n\n: odd ( x -- bool : is 'x' odd? )\n\t1 and ;\n\n: even ( x -- bool : is 'x' even? )\n\todd not ;\n\n: nor ( x x -- x : Logical NOR ) \n\tor not ;\n\n: ms ( u -- : wait at least 'u' milliseconds ) \n\tclock + begin dup clock u< until drop ;\n\n: sleep ( u -- : sleep for 'u' seconds )\n\t1000 * ms ;\n\n: align ( addr -- addr : align and address, nop in this implemented )\n\timmediate ; \n\n: ) ( -- : do nothing, this allows easy commenting out of code )\n\timmediate ;\n\n: ? ( a-addr -- : view value at address ) \n\t@ . ;\n\n: bell ( -- : emit an ASCII BEL character ) \n\t7 emit ;\n\n: b\/buf ( -- u : bytes per buffer ) \n\t1024 ;\n\n: # ( x -- x : debug print ) \n\tdup . ;\n\n: compile, ( -- : A word that writes , into the dictionary ) \n\t' , , ; \n\n: >mark ( -- : write a hole into the dictionary and push a pointer to it ) \n\there 0 , ;\n\n: r - r> u< ;\n\n: u. ( u -- : display number in base 10, although signed for now )\n\tbase @ >r decimal pnum drop r> base ! ;\n\n: invalidate-forth ( -- : invalidate this Forth core )\n\t1 `invalid ! ;\n\n: signed ( x -- bool : return true if sign bit set ) \n\t[ 1 size 8 * 1- lshift ] literal and logical ;\n\n: u>= ( x y -- bool : unsigned greater than or equal to )\n\t2dup u> >r = r> or ;\n\n: u<= ( x y -- bool : unsigned less than or equal to )\n\tu>= not ;\n\n: rdrop ( R: x -- : drop a value from the return stack )\n\tr> ( get caller's return address )\n\tr> ( get value to drop )\n\tdrop ( drop it like it's hot )\n\t>r ; ( return return address )\n\n: again immediate\n\t( loop unconditionally in a begin-loop:\n\t\tbegin ... again )\n\t' branch , ] literal ( size of input buffer, in characters )\n\t>in ; ( start of input buffer, in characters )\n\n: stdin?\n\t`fin @ `stdin @ = ;\n\n: source-id ( -- 0 | -1 | file-id )\n\t( \t\n\tValue Input Source\n\t-1 String\n\t0 Reading from user input \/ standard in\n\tfile-id )\n\t`source-id @ \n\t0= if\n\t\tstdin? if 0 else `fin @ then\n\telse\n\t\t-1\n\tthen\n\t;\n\n: 2nip ( n1 n2 n3 n4 -- n3 n4) \n\t>r >r 2drop r> r> ;\n\n: 2over ( n1 n2 n3 n4 \u2013 n1 n2 n3 n4 n1 n2 )\n\t>r >r 2dup r> swap >r swap r> r> -rot ;\n\n: 2swap ( n1 n2 n3 n4 \u2013 n3 n4 n1 n2 )\n\t>r -rot r> -rot ;\n\n: 2tuck ( n1 n2 n3 n4 \u2013 n3 n4 n1 n2 n3 n4 )\n\t2swap 2over ;\n\n: hide ( token -- hide-token : this hides a word from being found by the interpreter )\n\tdup\n\tif\n\t\tdup @ hidden-mask or swap tuck !\n\telse\n\t\tdrop 0\n\tthen ;\n\n: hider ( WORD -- ) \n\t( hide with drop ) \n\tfind dup if hide then drop ;\n\n: unhide ( hide-token -- ) \n\tdup @ hidden-mask invert and swap ! ;\n\n: original-exit \n\t[ find exit ] literal ;\n\n: exit\n\t( this will define a second version of exit, ';' will\n\tuse the original version, whilst everything else will\n\tuse this version, allowing us to distinguish between\n\tthe end of a word definition and an early exit by other\n\tmeans in \"see\" )\n\t[ find exit hide ] rdrop exit [ unhide ] ;\n\n: ?exit ( x -- : exit current definition if not zero ) \n\tif rdrop exit then ;\n\n: number? ( c -- f : is character a number? )\n\t[char] 0 [ char 9 1+ ] literal within ;\n\n: lowercase? ( c -- f : is character lower case? )\n\t[char] a [ char z 1+ ] literal within ;\n\n: uppercase? ( C -- f : is character upper case? )\n\t[char] A [ char Z 1+ ] literal within ;\n\n: alpha? ( C -- f : is character part of the alphabet? )\n\tdup lowercase? swap uppercase? or ;\n\n: alphanumeric? ( C -- f : is character alphabetic or a number ? )\n\tdup alpha? swap number? or ;\n\n: printable? ( c -- bool : is printable, excluding new lines and tables )\n\t32 127 within ;\n\n: >upper ( c -- C : convert char to uppercase iff lower case )\n\tdup lowercase? if bl xor then ;\n\n: >lower ( C -- c : convert char to lowercase iff upper case )\n\tdup uppercase? if bl xor then ;\n\n: <=> ( x y -- z : spaceship operator! )\n\t2dup\n\t> if 2drop -1 exit then\n\t< ;\n\n: start-address ( -- c-addr : push the start address )\n\t`start-address @ ;\n\n: >real-address ( c-addr -- c-addr : convert an interpreter address to a real address )\n\tstart-address - ;\n\n: real-address> ( c-addr -- c-addr : convert a real address to an interpreter address )\n\tstart-address + ;\n\n: peek ( c-addr -- char : peek at real memory )\n\t>real-address c@ ;\n\n: poke ( char c-addr -- : poke a real memory address )\n\t>real-address c! ;\n\n: die? ( x -- : controls actions when encountering certain errors )\n\t`error-handler ! ;\n\n: start! ( cfa -- : set the word to execute at startup )\n\t`instruction ! ;\t\n\n: warm ( -- : restart the interpreter, warm restart )\n\t1 restart ;\n\n: trip ( x -- x x x : triplicate a number ) \n\tdup dup ;\n\n( ========================== Basic Word Set ================================== )\n\n( ========================== Extended Word Set =============================== )\n\n: gcd ( x1 x2 -- x : greatest common divisor )\n\tbegin\n\t\tdup\n\t\tif\n\t\t\ttuck mod 0\n\t\telse\n\t\t\t1\n\t\tthen\n\tuntil\n\tdrop ;\n\n: log2 ( x -- log2 )\n\t( Computes the binary integer logarithm of a number,\n\tzero however returns itself instead of reporting an error )\n\t0 swap\n\tbegin\n\t\tswap 1+ swap 2\/ dup 0=\n\tuntil\n\tdrop 1- ;\n\n: cfa ( previous-word-address -- cfa )\n\t( Given the address of the PWD field of a word this\n\tfunction will return an execution token for the word )\n\t1+ ( MISC field )\n\tdup\n\t@ ( Contents of MISC field )\n\tinstruction-mask and ( Mask off the instruction )\n\t( If the word is not an immediate word, execution token pointer )\n\tcompile-instruction = + ;\n\n: ['] immediate find cfa [literal] ;\n\n: execute ( cfa -- )\n\t( given an execution token, execute the word )\n\n\t( create a word that pushes the address of a hole to write to\n\ta literal takes up two words, '!' takes up one )\n\t1- ( execution token expects pointer to PWD field, it does not\n\t\tcare about that field however, and increments past it )\n\tcfa\n\t[ here 3+ literal ]\n\t! ( write an execution token to a hole )\n\t[ 0 , ] ( this is the hole we write )\n;\n\n: time ( \" ccc\" -- n : time the number of milliseconds it takes to execute a word )\n\tclock >r\n\tfind execute\n\tclock r> - ;\n\n: rdepth\n\tmax-core `stack-size @ - r @ swap - ;\n\n( defer...is is probably not standards compliant, it is still neat! Also, there\n is no error handling if \"find\" fails... )\n: (do-defer) ( -- self : pushes the location into which it is compiled )\n\tr> dup >r 1- ;\n\n: defer ( \" ccc\" -- , Run Time -- location : \n\tcreates a word that pushes a location to write an execution token into )\n\t:: ' (do-defer) , postpone ; ;\n\n: is ( location \" ccc\" -- : make a deferred word execute a word ) \n\tfind cfa swap ! ;\n\nhider (do-defer)\n\n( ========================== Extended Word Set =============================== )\n\n( \nThe words described here on out get more complex and will require more\nof an explanation as to how they work.\n)\n\n( ========================== CREATE DOES> ==================================== )\n\n( The following section defines a pair of words \"create\" and \"does>\" which\nare a powerful set of words that can be used to make words that can create\nother words. \"create\" has both run time and compile time behavior, whilst\n\"does>\" only works at compile time in conjunction with \"create\". These two\nwords can be used to add constants, variables and arrays to the language,\namongst other things.\n\nA simple version of create is as follows\n\t: create :: 2 , here 2 + , ' exit , 0 state ! ;\nBut this version is much more limited )\n\n: write-quote ( A word that writes ' into the dictionary )\n\t['] ' , ; \n\n: write-exit ( A word that write exit into the dictionary )\n\t['] exit , ; \n\n: state! ( bool -- : set the compilation state variable ) \n\tstate ! ;\n\n: command-mode ( -- : put the interpreter into command mode )\n\tfalse state! ;\n\n: command-mode-create ( create a new work that pushes its data field )\n\t:: ( compile a word )\n\tdolit , ( write push into new word )\n\there 2+ , ( push a pointer to data field )\n\tpostpone ; ; ( write exit and switch to command mode )\n\n: mark compile, ( Write in a place holder 0 and push a pointer to to be used by does> )\n\twrite-quote write-exit compile, ( Write in an exit in the word we're compiling. )\n\t['] command-mode , ( Make sure to change the state back to command mode )\n;\n\n: create immediate ( create word is quite a complex forth word )\n\tstate @ \n\tif \n\t\tpostpone ( hole-to-patch -- )\n\timmediate\n\twrite-exit ( we don't want the defining to exit, but the *defined* word to )\n\there swap ! ( patch in the code fields to point to )\n\tdolist , ( write a run in )\n;\n\n: >body ( xt -- a-addr : a-addr is data field of a CREATEd word )\n\tcfa 5 + ;\nhider write-quote\n\n( ========================== CREATE DOES> ==================================== )\n\n: limit ( x min max -- x : limit x with a minimum and maximum )\n\trot min max ;\n\n: array ( x c\" xxx\" -- : create a named array ) \n\tcreate allot does> + ;\n\n: table \n\tcreate allot does> ;\n\n: variable \n\tcreate , does> ;\n\n: constant \n\tcreate , does> @ ;\n\n( @todo replace all instances of table with itable )\n: itable \n\tcreate dup , allot does> dup @ ;\n\n: char-table \n\tcreate dup , chars allot does> dup @ swap 1+ chars> swap ;\n\n: 2constant \n\tcreate , , does> dup 1+ @ swap @ ;\n\n: 2variable \n\tcreate , , does> ;\n\n( do...loop could be improved by not using the return stack so much )\n\n: do immediate\n\t' swap , ( compile 'swap' to swap the limit and start )\n\t' >r , ( compile to push the limit onto the return stack )\n\t' >r , ( compile to push the start on the return stack )\n\tpostpone begin ; ( save this address so we can branch back to it )\n\n: addi\n\t( @todo simplify )\n\tr@ 1- ( get the pointer to i )\n\t+! ( add value to it )\n\tr@ 1- @ ( find the value again )\n\tr@ 2- @ ( find the limit value )\n\tu<\n\tif\n\t\tr@ @ @ r@ @ + r@ ! exit ( branch )\n\tthen\n\tr> 1+\n\trdrop\n\trdrop\n\t>r ;\n\n: loop \n\timmediate 1 [literal] ' addi , r> ( pop off return address and i )\n\ttuck ( tuck i away )\n\t>r >r ( restore return stack )\n;\n\n: range ( nX nY -- nX nX+1 ... nY ) \n\tswap 1+ swap do i loop ;\n\n: repeater ( n0 X -- n0 ... nX ) \n\t1 do dup loop ;\n\n: sum ( n0 ... nX X -- sum<0..X> ) \n\t1 do + loop ;\n\n: mul ( n0 ... nX X -- mul<0..X> ) \n\t1 do * loop ;\n\n: factorial ( n -- n! )\n\t( This factorial is only here to test range, mul, do and loop )\n\tdup 1 <=\n\tif\n\t\tdrop\n\t\t1\n\telse ( This is obviously super space inefficient )\n \t\tdup >r 1 range r> mul\n\tthen ;\n\nhider tail\n\n( \nThe \"tail\" function implements tail calls, which is just a jump\nto the beginning of the words definition, for example this\nword will never overflow the stack and will print \"1\" followed\nby a new line forever,\n\n\t: forever 1 . cr tail ;\n\nWhereas\n\n\t: forever 1 . cr recurse ;\n\nor\n\n\t: forever 1 . cr forever ;\n\nWould overflow the return stack. \n)\n: tail ( -- )\n\timmediate\n\tlatest cfa\n\t' branch ,\n\there - 1+ , ;\n\n: recurse immediate\n\t( This function implements recursion, although this interpreter\n\tallows calling a word directly. If used incorrectly this will\n\tblow up the return stack.\n\n\tWe can test \"recurse\" with this factorial function:\n\t : factorial dup 2 < if drop 1 exit then dup 1- recurse * ;)\n\tlatest cfa , ;\n\n: myself ( -- : myself is a synonym for recurse ) \n\timmediate postpone recurse ;\n\n0 variable column-counter\n4 variable column-width\n\n: column ( i -- )\t\n\tcolumn-width @ mod not if cr then ;\n\n: reset-column\t\t\n\t0 column-counter ! ;\n\n: auto-column\t\t\n\tcolumn-counter dup @ column 1+! ;\n\n: alignment-bits \n\t[ 1 size log2 lshift 1- literal ] and ;\n\n: name ( PWD -- c-addr : given a pointer to the PWD field of a word get a pointer to the name of the word )\n\tdup 1+ @ 256\/ lsb - chars> ;\n\n0 variable x\n: x! ( x -- ) \n\tx ! ;\n\n: x@ ( -- x ) \n\tx @ ;\n\n: 2>r ( x1 x2 -- R: x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tswap\n\t\t>r\n\t\t>r\n\tx@ >r ; ( restore return address )\n\n: 2r> ( R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tr>\n\t\tr>\n\t\tswap\n\tx@ >r ; ( restore return address )\n\n: 2r@ ( -- x1 x2 , R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\tr> r>\n\t2dup\n\t>r >r\n\tswap\n\tx@ >r ; ( restore return address )\n\n: unused ( -- u : push the amount of core left ) \n\tmax-core here - ;\n\n: roll\n\t( xu xu-1 ... x0 u -- xu-1 ... x0 xu )\n\t( remove u and rotate u+1 items on the top of the stack,\n\tthis could be replaced with a move on the stack and\n\tsome magic so the return stack is used less )\n\tdup 0 >\n\tif\n\t\tswap >r 1- roll r> swap\n\telse\n\t\tdrop\n\tthen ;\n\n: accumulator ( \" ccc\" -- : make a word that increments by a value and pushes the result )\n\tcreate , does> tuck +! @ ;\n\n0 variable delim\n: accepter\n\t( c-addr max delimiter -- i )\n\t( store a \"max\" number of chars at c-addr until \"delimiter\" encountered,\n\tthe number of characters stored is returned )\n\tkey drop ( drop first key after word )\n\tdelim ! ( store delimiter used to stop string storage when encountered)\n\t0\n\tdo\n\t\tkey dup delim @ <>\n\t\tif\n\t\t\tover c! 1+\n\t\telse ( terminate string )\n\t\t\tdrop 0 swap c! \n\t\t\ti 1+\n\t\t\tleave\n\t\tthen\n\tloop\n\tbegin ( read until delimiter )\n\t\tkey delim @ =\n\tuntil \n;\nhider delim\n\n: accept ( c-addr +n1 -- +n2 : see accepter definition ) \n\t'\\n' accepter ;\n\n0xFFFF constant max-string-length\n\n0 variable delim\n: print-string\n\t( delimiter -- : print out the next characters in the input stream until a\n\t\"delimiter\" character is reached )\n\tkey drop\n\tdelim !\n\tbegin\n\t\tkey dup delim @ =\n\t\tif\n\t\t\tdrop exit\n\t\tthen\n\t\temit 0\n\tuntil ;\nhider delim\n\nsize 1- constant aligner\n: aligned ( unaligned -- aligned : align a pointer )\n\taligner + aligner invert and ;\nhider aligner\n\n0 variable delim\n: write-string ( char -- c-addr u )\n\t( @todo This really needs simplifying, to do this\n\ta set of words that operate on a temporary buffer can\n\tbe used )\n\t( Write a string into word being currently defined, this\n\tcode has to jump over the string it has just put into the\n\tdictionary so normal execution of a word can continue. The\n\tlength and character address of the string are left on the\n\tstack )\n\tdelim ! ( save delimiter )\n\t' branch , ( write in jump, this will jump past the string )\n\t>mark ( make hole )\n\tdup 1+ chars> ( calculate address to write to )\n\tmax-string-length delim @ accepter dup >r ( write string into dictionary, save index )\n\taligned 2dup size \/ ( stack: length hole char-len hole )\n\t1+ dup allot ( update dictionary pointer with string length )\n\t1+ swap ! ( write place to jump to )\n\tdrop ( do not need string length anymore )\n\t1+ chars> ( calculate place to print )\n\tr> ( restore index and address of string )\n\t1-\n;\nhider delim\n\n: length ( c-addr u -- u : push the length of an ASCIIZ string )\n tuck 0 do dup c@ 0= if 2drop i leave then 1+ loop ;\n\n: asciiz? ( c-addr u -- : is a Forth string also a ASCIIZ string )\n\ttuck length <> ;\n\n: asciiz ( c-addr u -- : trim a string until NUL terminator )\n\t2dup length nip ;\n\n: type ( c-addr u -- : print out 'u' characters at c-addr )\n\t0 do dup c@ emit 1+ loop drop ;\n\n: do-string ( char -- : write a string into the dictionary reading it until char is encountered )\n\twrite-string state @ if swap [literal] [literal] then ;\n\n: fill ( c-addr u char -- : fill in an area of memory with a character, only if u is greater than zero )\n\t-rot\n\t0 do 2dup i + c! loop\n\t2drop ;\n\n: \/string ( c-addr1 u1 n -- c-addr2 u2 : advance a string by n characters )\n\tover min rot over + -rot - ;\n\n128 char-table sbuf\n: s\" ( \"ccc\" --, Run Time -- c-addr u )\n\tsbuf 0 fill sbuf [char] \" accepter sbuf drop swap ;\nhider sbuf\n\n( @todo these strings really need rethinking, state awareness needs to be removed... )\n: type, \n\tstate @ if ' type , else type then ;\n\n: c\" \n\timmediate [char] \" do-string ;\n\n: \" \n\timmediate [char] \" do-string type, ;\n\n: .( \n\timmediate [char] ) print-string ;\n\n: .\" \n\timmediate [char] \" do-string type, ;\n\nhider type,\n\n( This word really should be removed along with any usages of this word, it\nis not a very \"Forth\" like word, it accepts a pointer to an ASCIIZ string and\nprints it out, it also does not checking of the returned values from write-file )\n: print ( c-addr -- : print out a string to the standard output )\n\t-1 over >r length r> swap stdout write-file 2drop ;\n\n: ok \n\t\" ok\" cr ;\n\n: empty-stack ( x-n ... x-0 -- : empty the variable stack )\n\tbegin depth while drop repeat ;\n\n: quit\n\t0 `source-id ! ( set source to read from file )\n\t`stdin @ `fin ! ( read from stdin )\n\tpostpone [ ( back into command mode )\n\t1 restart ( restart the interpreter ) ; \n\n: abort\n\tempty-stack quit ;\n\n: abort\" immediate postpone \"\n\t' cr , ' abort , ;\n\n( ==================== CASE statements ======================== )\n\n( for a simpler case statement:\n\tsee Volume 2, issue 3, page 48 of Forth Dimensions at\n\thttp:\/\/www.forth.org\/fd\/contents.html )\n\n( These case statements need improving, it is not standards compliant )\n: case immediate\n\t' branch , 3 , ( branch over the next branch )\n\there ' branch , ( mark: place endof branches back to with again )\n\t>mark swap ; ( mark: place endcase writes jump to with then )\n\n: over= ( x y -- x bool : over ... then = )\n\tover = ;\n\n: of\n\timmediate ' over= , postpone if ;\n\n: endof\n\timmediate over postpone again postpone then ;\n\n: endcase\n\timmediate 1+ postpone then drop ;\n\n( ==================== CASE statements ======================== )\n\n: error-no-word ( print error indicating last read in word as source )\n\t\" error: word '\" source drop print \" ' not found\" cr ;\n\n: ;hide ( should only be matched with ':hide' )\n\timmediate \" error: ';hide' without ':hide'\" cr ;\n\n: :hide ( -- : hide a list of words, the list is terminated with \";hide\" )\n\tbegin\n\t\tfind ( find next word )\n\t\tdup [ find ;hide ] literal = if\n\t\t\tdrop exit ( terminate :hide )\n\t\tthen\n\t\tdup 0= if ( word not found )\n\t\t\tdrop\n\t\t\terror-no-word\n\t\t\texit\n\t\tthen\n\t\thide drop\n\tagain ;\n\n: count ( c-addr1 -- c-addr2 u : advance string pointer ) \n\tdup c@ swap 1+ swap ;\n\n: bounds ( x y -- y+x x : make an upper and lower bound )\n\tover + swap ;\n\n: spaces ( n -- : print n spaces ) \n\t0 do space loop ;\n\n: erase ( addr u : erase a block of memory )\n\t2chars> 0 fill ;\n\n: blank ( c-addr u : fills a string with spaces )\n\tbl fill ;\n\n( move should check that u is not negative )\n: move ( addr1 addr2 u -- : copy u words of memory from 'addr2' to 'addr1' )\n\t0 do\n\t\t2dup i + @ swap i + !\n\tloop\n\t2drop ;\n\n( It would be nice if move and cmove could share more code, as they do exactly\n the same thing but with different load and store functions, cmove> )\n: cmove ( c-addr1 c-addr2 u -- : copy u characters of memory from 'c-addr2' to 'c-addr1' )\n\t0 do\n\t\t2dup i + c@ swap i + c!\n\tloop\n\t2drop ;\n\n( ==================== Conditional Compilation ================ )\n\n( The words \"[if]\", \"[else]\" and \"[then]\" implement conditional compilation,\nthey can be nested as well\n\nSee http:\/\/lars.nocrew.org\/dpans\/dpans15.htm for more information\n\nA much simpler conditional compilation method is the following\nsingle word definition:\n\n : compile-line? 0= if [ find \\\\ , ] then ;\n\nWhich will skip a line if a conditional is false, and compile it\nif true )\n\n( These words really, really need refactoring, I could use the newly defined \n \"defer\" to help out with this )\n0 variable nest ( level of [if] nesting )\n0 variable [if]-word ( populated later with \"find [if]\" )\n0 variable [else]-word ( populated later with \"find [else]\")\n: [then] immediate ;\n: reset-nest 1 nest ! ;\n: unnest? [ find [then] ] literal = if nest 1-! then ;\n: nest? [if]-word @ = if nest 1+! then ;\n: end-nest? nest @ 0= ;\n: match-[else]? [else]-word @ = nest @ 1 = and ;\n\n: [if] ( bool -- : conditional execution )\n\tunless\n\t\treset-nest\n\t\tbegin\n\t\t\tfind\n\t\t\tdup nest?\n\t\t\tdup match-[else]? if drop exit then\n\t\t\t unnest?\n\t\t\tend-nest?\n\t\tuntil\n\tthen ;\n\n: [else] ( discard input until [then] encounter, nesting for [if] )\n\treset-nest\n\tbegin\n\t\tfind\n\t\tdup nest? unnest?\n\t\tend-nest?\n\tuntil ;\n\nfind [if] [if]-word !\nfind [else] [else]-word !\n\n:hide [if]-word [else]-word nest reset-nest unnest? match-[else]? ;hide\n\n( ==================== Conditional Compilation ================ )\n\n( ==================== Endian Words =========================== )\n\nsize 2 = [if] 0x0123 variable endianess [then]\nsize 4 = [if] 0x01234567 variable endianess [then]\nsize 8 = [if] 0x01234567abcdef variable endianess [then]\n\n: endian ( -- bool : returns the endianess of the processor, little = 0, big = 1 )\n\t[ endianess chars> c@ 0x01 = ] literal ;\nhider endianess\n\n: swap16 ( x -- x : swap the byte order a 16 bit number )\n\tdup 256* 0xff00 and >r 256\/ lsb r> or ;\n\nsize 4 >= [if] \n\t: swap32 \n\t\tdup 0xffff and swap16 16 lshift swap\n\t\t16 rshift 0xffff and swap16 or ;\n[then]\n\nsize 8 >= [if]\n\t: swap64 ( x -- x : swap the byte order of a 64 bit number )\n\t\t dup 0xffffffff and swap32 32 lshift swap\n\t\t 32 rshift 0xffffffff and swap32 or ;\n[then]\n\nsize 2 = [if]\n\tendian \n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\tswap16 ;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\t;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\tswap16 ;\n\t[then]\n[then]\n\nsize 4 = [if]\n\tendian \n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\tswap32 ;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\t;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\tswap32 ;\n\t[then]\n[then]\n\nsize 8 = [if]\n\tendian \n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\tswap64 ;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\t;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\tswap64 ;\n\t[then]\n[then]\n\n( ==================== Endian Words =========================== )\n\n( ==================== Misc words ============================= )\n\n: trace ( flag -- : turn tracing on\/off )\n\t`debug ! ;\n\n: #pad ( -- u : offset into pad area )\n\t64 ;\n\n: pad\n\t( the pad is used for temporary storage, and moves\n\talong with dictionary pointer, always in front of it )\n\there #pad + ;\n\n0 variable counter\n\n: counted-column ( index -- : special column printing for dump )\n\tcounter @ column-width @ mod\n\tnot if cr . \" :\" space else drop then\n\tcounter 1+! ;\n\n: as-chars ( x -- : print a cell out as characters )\n\tsize 0\n\tdo\n\t\tdup\n\t\tsize i 1+ - select-byte ( @todo adjust for endianess )\n\t\tdup printable? not\n\t\tif\n\t\t\tdrop [char] .\n\t\tthen\n\t\temit\n\tloop\n\tspace\n\tdrop ;\n\n: lister \n\t0 counter ! 1- swap \n\tdo \n\t\ti counted-column i ? i @ as-chars \n\tloop ;\n\n: dump ( addr u -- : dump out 'u' cells of memory starting from 'addr' )\n\tbase @ >r hex 1+ over + lister r> base ! cr ;\n\n:hide counted-column counter lister as-chars ;hide\n\n: forgetter ( pwd-token -- : forget a found word and everything after it )\n\tdup @ pwd ! h ! ;\n\n( @bug will not work for immediate defined words )\n: forget ( WORD -- : forget word and every word defined after it )\n\tfind 1- forgetter ;\n\n: marker ( WORD -- : make word the forgets itself and words after it)\n\t:: latest [literal] ' forgetter , postpone ; ;\nhider forgetter\n\n: ?dup-if immediate ( x -- x | - : ?dup and if rolled into one! )\n\t' ?dup , postpone if ;\n\n: ** ( b e -- x : exponent, raise 'b' to the power of 'e')\n\tdup\n\tif\n\t\tdup\n\t\t1\n\t\tdo over * loop\n\telse\n\t\tdrop\n\t\t1\n\tendif ;\n\n( ==================== Misc words ============================= )\n\n( ==================== Random Numbers ========================= )\n\n( \nSee:\nuses xorshift\nhttps:\/\/en.wikipedia.org\/wiki\/Xorshift\nhttp:\/\/excamera.com\/sphinx\/article-xorshift.html\nhttp:\/\/www.arklyffe.com\/main\/2010\/08\/29\/xorshift-pseudorandom-number-generator\/\nthese constants have be collected from the web \n)\n\nsize 2 = [if] 13 constant a 9 constant b 7 constant c [then]\nsize 4 = [if] 13 constant a 17 constant b 5 constant c [then]\nsize 8 = [if] 12 constant a 25 constant b 27 constant c [then]\n\n7 variable seed ( must not be zero )\n\n: seed! ( x -- : set the value of the PRNG seed )\n\tdup 0= if drop 7 ( zero not allowed ) then seed ! ;\n\n: random ( -- x : assumes word size is 32 bit )\n\tseed @\n\tdup a lshift xor\n\tdup b rshift xor\n\tdup c lshift xor\n\tdup seed! ;\n\n:hide a b c seed ;hide\n\n( ==================== Random Numbers ========================= )\n\n( ==================== ANSI Escape Codes ====================== )\n( \nTerminal colorization module, via ANSI Escape Codes\n \nsee: https:\/\/en.wikipedia.org\/wiki\/ANSI_escape_code\nThese codes will provide a relatively portable means of\nmanipulating a terminal\n)\n\n27 constant 'escape'\nchar ; constant ';'\n: CSI 'escape' emit .\" [\" ;\n0 constant black\n1 constant red\n2 constant green\n3 constant yellow\n4 constant blue\n5 constant magenta\n6 constant cyan\n7 constant white\n: foreground 30 + ;\n: background 40 + ;\n0 constant dark\n1 constant bright\n\n: color ( brightness color-code -- : set the terminal color )\n\t( set color on an ANSI compliant terminal,\n\tfor example:\n\t\tbright red foreground color\n\tsets the foreground text to bright red )\n\tCSI u. if .\" ;1\" then .\" m\" ;\n\n: at-xy ( x y -- : set ANSI terminal cursor position to x y )\n\tCSI u. ';' emit u. .\" H\" ;\n\n: page ( -- : clear ANSI terminal screen and move cursor to beginning ) \n\tCSI .\" 2J\" 1 1 at-xy ;\n\n: hide-cursor ( -- : hide the cursor from view ) \n\tCSI .\" ?25l\" ;\n\n: show-cursor ( -- : show the cursor ) \n\tCSI .\" ?25h\" ;\n\n: save-cursor ( -- : save cursor position ) \n\tCSI .\" s\" ;\n\n: restore-cursor ( -- : restore saved cursor position ) \n\tCSI .\" u\" ;\n\n: reset-color ( -- : reset terminal color to its default value)\n\tCSI .\" 0m\" ;\n\nhider CSI\n( ==================== ANSI Escape Codes ====================== )\n\n\n( ==================== Prime Numbers ========================== )\n( \nFrom original \"third\" code from the IOCCC at \nhttp:\/\/www.ioccc.org\/1992\/buzzard.2.design, the module works out\nand prints prime numbers.\n)\n: prime? ( x -- x\/0 : return number if it is prime, zero otherwise )\n\tdup 1 = if 1- exit then\n\tdup 2 = if exit then\n\tdup 2 \/ 2 ( loop from 2 to n\/2 )\n\tdo\n\t\tdup ( value to check if prime )\n\t\ti mod ( mod by divisor )\n\t\tnot if\n\t\t\tdrop 0 leave\n\t\tthen\n\tloop\n;\n\n0 variable counter\n: primes ( x1 x2 -- : print the primes from x2 to x1 )\n\t0 counter !\n\t\" The primes from \" dup . \" to \" over . \" are: \"\n\tcr\n\treset-column\n\tdo\n\t\ti prime?\n\t\tif\n\t\t\ti . counter @ column counter 1+!\n\t\tthen\n\tloop\n\tcr\n\t\" There are \" counter @ . \" primes.\"\n\tcr ;\nhider counter\n( ==================== Prime Numbers ========================== )\n\n( ==================== Debugging info ========================= )\n\n( string handling should really be done with PARSE, and CMOVE )\n\nhider .s\n: .s ( -- : print out the stack for debugging )\n\t\" <\" depth u. \" >\" space\n\tdepth if\n\t\tdepth 0 do i column tab depth i 1+ - pick u. loop\n\tthen\n\tcr ;\n\n1 variable hide-words ( do we want to hide hidden words or not )\n\n( \nThis function prints out all of the defined words, excluding hidden words.\nAn understanding of the layout of a Forth word helps here. The dictionary\ncontains a linked list of words, each forth word has a pointer to the previous\nword until the first word. The layout of a Forth word looks like this:\n\nNAME: Forth Word - A variable length ASCII NUL terminated string\nPWD: Previous Word Pointer, points to the previous word\nMISC: Flags, code word and offset from previous word pointer to start of Forth word string\nCODE\/DATA: The body of the forth word definition, not interested in this.\n\nThere is a register which stores the latest defined word which can be\naccessed with the code \"pwd @\". In order to print out a word we need to\naccess a words MISC field, the offset to the NAME is stored here in bits\n8 to 15 and the offset is calculated from the PWD field.\n\n\"print\" expects a character address, so we need to multiply any calculated\naddress by the word size in bytes. \n)\n\n: words ( -- : print out all defined an visible words )\n\tlatest\n\tbegin\n\t\tdup\n\t\thidden? hide-words @ and\n\t\tnot if\n\t\t\tname\n\t\t\tprint space\n\t\telse\n\t\t\tdrop\n\t\tthen\n\t\t@ ( Get pointer to previous word )\n\t\tdup dictionary-start u< ( stop if pwd no longer points to a word )\n\tuntil\n\tdrop cr\n;\nhider hide-words\n\n: TrueFalse ( -- : print true or false )\n\tif \" true\" else \" false\" then ;\n\n: registers ( -- : print out important registers and information about the virtual machine )\n\t\" return stack pointer: \" r@ . cr\n\t\" dictionary pointer \" here . cr\n\t\" previous word: \" pwd ? cr\n\t\" state: \" state ? cr\n\t\" base: \" base ? cr\n\t\" depth: \" depth . cr\n\t\" cell size (in bytes): \" size . cr\n\t\" last cell address: \" max-core . cr\n\t\" unused cells: \" unused . cr\n\t\" invalid: \" `invalid @ TrueFalse cr\n\t\" size of variable stack: \" `stack-size ? cr\n\t\" size of return stack: \" `stack-size ? cr\n\t\" start of variable stack: \" max-core `stack-size @ 2* - . cr\n\t\" start of return stack: \" max-core `stack-size @ - . cr\n\t\" current input source: \" source-id -1 = if \" string\" else \" file\" then cr\n\t\" reading from stdin: \" source-id 0 = stdin? and TrueFalse cr\n\t\" tracing on: \" `debug @ TrueFalse cr\n\t\" starting word: \" `instruction ? cr\n\t\" real start address: \" `start-address ? cr\n\t\" error handling: \" `error-handler ? cr\n(\n `sin `sidx `slen `fout\n `stdout `stderr `argc `argv )\n;\n\n: y\/n? ( -- bool : ask a yes or no question )\n\tkey drop\n\t\" y\/n? \"\n\tbegin\n\t\tkey\n\t\tdup\n\t\t[char] y = if true exit then\n\t\t[char] n = if false exit then\n\t\t\" y\/n? \"\n\tagain ;\n\n: >instruction ( extract instruction from instruction field ) 0x1f and ;\n\n: step\n\t( step through a word: this word could be augmented\n\twith commands such as \"dump\", \"halt\", and optional\n\t\".s\" and \"registers\" )\n\tregisters\n\t\" .s: \" .s cr\n\t\" -- press any key to continue -- \"\n\tkey drop ;\n\n: more ( -- : wait for more input )\n\t\" -- press any key to continue -- \" key drop cr page ;\n\n: debug-help ( -- : this is not quite ready for prime time )\n \" debug mode commands\n\th - print help\n\tq - exit containing word\n\tr - print registers\n\ts - print stack\n\tc - continue on with execution\n\" ;\n: debug-prompt \n\t.\" debug> \" ;\n\n: debug ( a work in progress, debugging support, needs parse-word )\n\tkey drop\n\tcr\n\tbegin\n\t\tdebug-prompt\n\t\tkey dup '\\n' <> if source accept drop then\n\t\tcase\n\t\t\t[char] h of debug-help endof\n\t\t\t[char] q of bye endof\n\t\t\t[char] r of registers endof\n\t\t\t[char] s of >r .s r> endof\n\t\t\t[char] c of drop exit endof\n\t\tendcase drop\n\tagain ;\nhider debug-prompt\n\n0 variable cf\n: code>pwd ( CODE -- PWD\/0 )\n\t( @todo simplify using \"within\"\n\t given a pointer to a executable code field\n\tthis words attempts to find the PWD field for\n\tthat word, or return zero )\n\tdup dictionary-start here within not if drop 0 exit then\n\tcf !\n\tlatest dup @ ( p1 p2 )\n\tbegin\n\t\tover ( p1 p2 p1 )\n\t\tcf @ u<= swap cf @ > and if exit then\n\t\tdup 0= if exit then\n\t\tdup @ swap\n\tagain\n;\nhider cf\n\n: end-print ( x -- )\n\t\"\t\t=> \" . \" ]\" ;\n\n: word-printer\n\t( attempt to print out a word given a words code field\n\tWARNING: This is a dirty hack at the moment\n\tNOTE: given a pointer to somewhere in a word it is possible\n\tto work out the PWD by looping through the dictionary to\n\tfind the PWD below it )\n\t1- dup @ -1 = if \" [ noname\" end-print exit then\n\t dup \" [ \" code>pwd dup if name print else drop \" data\" then\n\t end-print ;\nhider end-print\n\n( these words push the execution tokens for various special cases for decompilation )\n: get-branch [ find branch cfa ] literal ;\n: get-?branch [ find ?branch cfa ] literal ;\n: get-original-exit [ original-exit cfa ] literal ;\n: get-quote [ find ' cfa ] literal ;\n\n: branch-increment ( addr branch -- increment : calculate decompile increment for \"branch\" )\n\t1+ dup negative? if drop 2 else 2dup dump then ;\n\n( these words take a code field to a primitive they implement, decompile it\nand any data belonging to that operation, and push a number to increment the\ndecompilers code stream pointer by )\n: decompile-literal ( code -- increment )\n\t\" [ literal\t=> \" 1+ ? \" ]\" 2 ;\n: decompile-branch ( code -- increment )\n\t\" [ branch\t=> \" 1+ ? \" ]\" dup 1+ @ branch-increment ;\n: decompile-quote ( code -- increment )\n\t\" [ '\t=> \" 1+ @ word-printer \" ]\" 2 ;\n: decompile-?branch ( code -- increment )\n\t\" [ ?branch\t=> \" 1+ ? \" ]\" 2 ;\n\n( @todo decompile :noname, make the output look better\n\nThe decompile word expects a pointer to the code field of a word, it\ndecompiles a words code field, it needs a lot of work however.\nThere are several complications to implementing this decompile\nfunction.\n\n\t' The next cell should be pushed\n\t:noname This has a marker before its code field of -1 which\n\t\t cannot occur normally, this is handles in word-printer\n\tbranch branches are used to skip over data, but also for\n\t\t some branch constructs, any data in between can only\n\t\t be printed out generally speaking\n\texit There are two definitions of exit, the one used in\n\t\t ';' and the one everything else uses, this is used\n\t\t to determine the actual end of the word\n\tliterals Literals can be distinguished by their low value,\n\t\t which cannot possibly be a word with a name, the\n\t\t next field is the actual literal\n\n@todo addi also needs handling, it is another special case used by\n\"do...loop\" [which should be replaced].\n\nOf special difficult is processing 'if' 'else' 'then' statements,\nthis will require keeping track of '?branch'.\n\nAlso of note, a number greater than \"here\" must be data )\n\n: decompile ( code-field-ptr -- : decompile a word )\n\tbegin\n\t\ttab\n\t\tdup @\n\t\tcase\n\t\t\tdolit of drup decompile-literal endof\n\t\t\tget-branch of drup decompile-branch endof\n\t\t\tget-quote of drup decompile-quote endof\n\t\t\tget-?branch of drup decompile-?branch endof\n\t\t\tget-original-exit of 2drop \" [ exit ]\" cr exit endof\n\t\t\tword-printer 1\n\t\tendcase\n\t\t+\n\t\tcr\n\tagain ;\n\n:hide\n\tword-printer get-branch get-?branch get-original-exit \n\tget-quote branch-increment decompile-literal \n\tdecompile-branch decompile-?branch decompile-quote\n;hide\n\n: xt-instruction ( extract instruction from execution token )\n\tcfa @ >instruction ;\n\n( these words expect a pointer to the PWD field of a word )\n: defined-word? xt-instruction dolist = ;\n: print-name \" name: \" name print cr ;\n: print-start \" word start: \" name chars . cr ;\n: print-previous \" previous word: \" @ . cr ;\n: print-immediate \" immediate: \" 1+ @ >instruction compile-instruction <> TrueFalse cr ;\n: print-instruction \" instruction: \" xt-instruction . cr ;\n: print-defined \" defined: \" defined-word? TrueFalse cr ;\n\n: print-header ( PWD -- is-immediate-word? )\n\tdup print-name\n\tdup print-start\n\tdup print-previous\n\tdup print-immediate\n\tdup print-instruction ( @todo look up instruction name )\n\tprint-defined ;\n\n: see ( -- : decompile the next word in the input stream )\n\t( decompile a word )\n\tfind\n\tdup 0= if drop error-no-word exit then\n\t1- ( move to PWD field )\n\tdup print-header\n\tdup defined-word?\n\tif ( decompile if a compiled word )\n\t\tcfa 1+ ( move to code field )\n\t\t\" code field:\" cr\n\t\tdecompile\n\telse ( the instruction describes the word if it is not a compiled word )\n\t\tdrop\n\tthen ;\n\n( \nThese help messages could be moved to blocks, the blocks could then\nbe loaded from disk and printed instead of defining the help here,\nthis would allow much larger help \n)\n\n: help ( -- : print out a short help message )\n\tpage\n\tkey drop\n\" Welcome to Forth, an imperative stack based language. It is both a low\nlevel and a high level language, with a very small memory footprint. Most\nof Forth is defined as a combination of various primitives.\n\nA short description of the available function (or Forth words) follows,\nwords marked (1) are immediate and cannot be used in command mode, words\nmarked with (2) define new words. Words marked with (3) have both command\nand compile functionality.\n\n\"\nmore \" The built in words that accessible are:\n\n(1,2)\t: define a new word, switching to compile mode\n\timmediate make latest defined word immediate\n\tread read in a word, execute in command mode else compile\n\t@ ! fetch, store\n\tc@ c! character based fetch and store\n\t- + * \/ standard arithmetic operations,\n\tand or xor invert standard bitwise operations\n\tlshift rshift left and right bit shift\n\tu< u> < > = comparison predicates\n\texit exit from a word\n\temit print character from top of stack\n\tkey get a character from input\n\tr> >r pop a value from or to the return stack\n\tfind find a word in the dictionary and push the location\n\t' store the address of the following word on the stack\n\t, write the top of the stack to the dictionary\n\tbsave bload save or load a block at address to indexed file\n\tswap swap first two values on the stack\n\tdup duplicate the top of the stack\n\tdrop pop and drop a value\n\tover copy the second stack value over the first\n\t. pop the top of the stack and print it\n\" \nmore \" \n\tprint print a NUL terminated string at a character address\n\tdepth get the current stack depth\n\tclock get the time since execution start in milliseconds\n\tevaluate evaluate a string\n\tsystem execute a system command\n\tclose-file close a file handle\n\topen-file open a file handle\n\tdelete-file delete a file off disk given a string\n\tread-file read in characters from a file\n\twrite-file write characters to a file\n\tfile-position get the file offset\n\treposition-file reposition the file pointer\n\tflush-file flush a file to disk\n\trename-file rename a file on disk\n \"\n\nmore \" All of the other words in the interpreter are built from these\nprimitive words. A few examples:\n\n(1)\tif...else...then FORTH branching construct\n(1)\tbegin...until loop until top of stack is non zero\n(1)\tbegin...again infinite loop\n(1)\tdo...loop FORTH looping construct\n(2,3)\tcreate create a new word that pushes its location\n(1)\tdoes> declare a created words run time behaviour\n(1,2)\tvariable declare variable with initial value from top of stack\n(1,2)\tconstant declare a constant, taken from top of stack\n(1,2)\tarray declare an array with size taken from top of stack\n(1)\t; terminate a word definition and return to command mode\n\twords print out a list of all the defined words\n\thelp this help message\n\tdump print out memory contents starting at an address\n\tregisters print out the contents of the registers\n\tsee decompile a word, viewing what words compose it\n\t.s print out the contents of the stack\n\n\"\n\nmore \" Some more advanced words:\n\n\there push the dictionary pointer\n\th push the address of the dictionary pointer\n\tr push the return stack pointer\n\tallot allocate space in the dictionary\n(1)\t[ switch to command mode\n\t] switch to compile mode\n\t:: compile ':' into the dictionary\n\n\" more \"\nFor more information either consult the manual pages forth(1) and libforth(1)\nor consult the following sources:\n\n\thttps:\/\/github.com\/howerj\/libforth\n\thttp:\/\/work.anapnea.net\/html\/html\/projects.html\n\nAnd for a larger tutorial:\n\n\thttps:\/\/github.com\/howerj\/libforth\/blob\/master\/readme.md\n\nFor resources on Forth:\n\n\thttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\thttps:\/\/rwmj.wordpress.com\/2010\/08\/07\/jonesforth-git-repository\/\n\n -- end --\n\" cr\n;\n\n( ==================== Files ================================== )\n\n( @todo implement the other file access methods in terms of the\n built in ones [see http:\/\/forth.sourceforge.net\/std\/dpans\/dpans11.htm]\n @todo read-line and write-line need their flag and ior setting correctly\n\n\tFILE-SIZE [ use file-positions ]\n\tINCLUDE-FILE \n\tINCLUDED\n\tFILE-STATUS\n\n Also of note:\t\n * Source ID needs extending. )\n\n: read-char ( c-addr fileid -- ior : read a char )\n\t1 swap read-file swap 1 = if drop -1 then ;\n\n: write-char ( c-addr fileid -- ior : write a char )\n\t1 swap write-file swap 1 = if drop -1 then ;\n\n: read-line ( c-addr u1 fileid -- u2 flag ior : read in a line of text )\n\t-rot bounds\n\tdo\n\t\tdup i swap read-char drop\n\t\ti c@ '\\n' = if drop i 0 0 leave then\n\tloop drop ;\n\n: write-line ( c-addr u fileid -- u2 flag ior : write a line of text )\n\t-rot bounds\n\tdo\n\t\tdup i swap write-char drop\n\t\ti c@ '\\n' = if drop i 0 0 leave then\n\tloop ;\n\n: resize-file ( ud fileid -- ior : attempt to resize a file )\n\t( There is no portable way to truncate a file :C )\n\t2drop -1 ( -1 to indicate failure ) ;\n\n: create-file ( c-addr u fam -- fileid ior )\n\topen-file ;\n\n: bin ( fam1 -- fam2 : modify a file access method to be binary not line oriented ) \n\t( Do nothing, all file access methods are binary, although of note\n\tthe already opened files stdin, stdout and stderr are opened in text\n\tmode on Windows platforms, but they are not file access methods, they\n\tare fileids )\n\t;\n\n( ==================== Files ================================== )\n\n( ==================== Blocks ================================= )\n\n( @todo process invalid blocks [anything greater or equal to 0xFFFF] )\n( @todo only already created blocks can be loaded, this should be\n corrected so one is created if needed )\n( @todo better error handling )\n( @todo Use char-table )\n( @todo Fix this! )\n\n-1 variable scr-var\nfalse variable dirty ( has the buffer been modified? )\n: scr ( -- x : last screen used ) scr-var @ ;\nb\/buf char-table block-buffer ( block buffer - enough to store one block )\n\n: update ( -- : mark block buffer as dirty, so it will be flushed if needed )\n\ttrue dirty ! ;\n: clean ( -- : mark buffers as clean, even if they are dirty )\n\tfalse dirty ! ;\n\n0 variable make-block-char ( the character buffers are filled with in make-block )\n\n: erase-buffer\n\tblock-buffer make-block-char @ fill ;\n\n: empty-buffers ( -- : discard any buffers )\n\tclean block-buffer erase-buffer ;\n\n: invalid ( block-buffer -- : check if the block buffer is invalid )\n\t-1 = if abort\" invalid block buffer (-1)\" then ;\n\n: flush ( -- : flush dirty block buffers )\n\tdirty @ if scr invalid block-buffer drop scr bsave drop clean then ;\n\n: list ( block-number -- : display a block )\n\tflush \n\ttrip scr <> if\n\t\tblock-buffer drop swap bload ( load buffer into block buffer )\n\t\tswap scr-var !\n\telse\n\t\t2drop 0\n\tthen\n\t-1 = if exit then ( failed to load )\n\tblock-buffer type ; ( print buffer )\n\n: block ( u -- addr : load block 'u' and push address to block )\n\tdup invalid\n\ttrip scr <> if flush block-buffer drop swap bload then\n\t-1 = if -1 else scr-var ! block-buffer drop chars then ;\n\n: save-buffers ( -- : save all updated buffers )\n\tflush ;\n\n: list-thru ( x y -- : list blocks x through to y )\n\t1+ swap\n\tkey drop\n\tdo i invalid \" screen no: \" i . cr i list cr more loop ;\n\n: open-file-or-abort\n\t>r 2dup r> open-file ?dup 0= if type \" : \" abort\" file open failed\" else >r 2drop r> then ;\n\n: make-block ( c-addr u -- : make a block on disk, named after a string )\n\tw\/o open-file-or-abort\n\tflush -1 scr-var !\n\terase-buffer\n\tblock-buffer rot dup >r write-file r> close-file drop\n\t0<> if drop abort\" write failed\" then\n\tb\/buf <> if abort\" could not write buffer out\" then ;\n\n:hide scr-var block-buffer clean invalid erase-buffer make-block-char ;hide\n\n( ==================== Blocks ================================= )\n\n( ==================== Matcher ================================ )\n\\ Translated from http:\/\/c-faq.com\/lib\/regex.html\n\\ int match(char *pat, char *str)\n\\ {\n\\ \tswitch(*pat) {\n\\ \tcase '\\0': return !*str;\n\\ \tcase '*': return match(pat+1, str) || *str && match(pat, str+1);\n\\ \tcase '?': return *str && match(pat+1, str+1);\n\\ \tdefault: return *pat == *str && match(pat+1, str+1);\n\\ \t}\n\\ }\n\n: *pat ( regex -- regex char ) \n\tdup c@ ;\n\n: *str ( string regex -- string regex char )\n\tover c@ ;\n\n: pass ( c-addr1 c-addr2 -- : bool ) \n\t2drop 1 ;\n: fail ( c-addr1 c-addr2 -- : bool ) \n\t2drop 0 ;\n\n: *pat==*str ( c-addr1 c-addr2 -- c-addr1 c-addr2 bool )\n\t2dup c@ swap c@ = ;\n\n: ++ ( u1 u2 u3 u4 -- u1+u3 u2+u4 : not quite d+ [does no carry] )\n\tswap >r + swap r> + swap ;\n\ndefer matcher\n\n: advance ( string regex char -- bool : advance both regex and string )\n\tif 1 1 ++ matcher else fail then ;\n: advance-string ( string regex char -- bool : advance only the string )\n\tif 1 0 ++ matcher else fail then ;\n: advance-regex ( string regex -- bool : advance matching )\n\t2dup 0 1 ++ matcher if pass else *str advance-string then ;\n\n: match ( string regex -- bool : match a ASCIIZ pattern against an ASCIIZ string )\n\t( @todo Add limits and accept two Forth strings, making sure they are both\n\t ASCIIZ strings as well \n\t @todo Case insensitive version\n\t @warning This uses a non-standards compliant version of case! )\n\t*pat\n\tcase\n\t\t 0 of drop drop c@ not exit endof\n\t\t[char] * of drop advance-regex exit endof\n\t\t[char] ? of drop *str advance exit endof\n\t\t drop *pat==*str advance exit\n\tendcase ;\n\nmatcher is match\n\n:hide \n\t*str *pat *pat==*str pass fail advance \n\tadvance-string advance-regex matcher ++ \n;hide\n\n( ==================== Matcher ================================ )\n\n( ==================== Cons Cells ============================= )\n\n( \nFrom http:\/\/sametwice.com\/cons.fs, this could be improved if the optional\nmemory allocation words were added to the interpreter. This provides\na simple \"cons cell\" data structure. There is currently no way to\nfree allocated cells \n)\n\n: car! ( cons-addr -- : store a value in the car cell of a cons cell ) \n\t! ;\n: cdr! ( cons-addr -- : store a value in the cdr cell of a cons cell )\n\tcell+ ! ;\n: car@ ( cons-addr -- car-val : retrieve car value from cons cell )\n\t@ ;\n: cdr@ ( cons-addr -- cdr-val : retrieve cdr value from cons cell )\n\tcell+ @ ;\n: cons ( car-val cdr-val -- cons-addr : allocate a new cons cell )\n\tswap here >r , , r> ;\n: cons0 0 0 cons ;\n\n( ==================== Cons Cells ============================= )\n\n( ==================== Miscellaneous ========================== )\n\n( @todo use check-within in various primitives like \"array\" )\n: check-within ( x min max -- : abort if x is not within a range )\n\twithin not if abort\" limit exceeded\" then ;\n\n: enum ( x \" ccc\" -- x+1 : define a series of enumerations )\n\tdup constant 1+ ; ( better would be a :enum ;enum syntax )\n\n: compare ( c-addr1 u1 c-addr2 u2 -- n : compare two strings, assumes strings are NUL terminated )\n\trot min\n\t0 do ( should be ?do )\n\t\t2dup\n\t\ti + c@ swap i + c@\n\t\t<=> dup if leave else drop then\n\tloop\n\t2drop ;\n\n: 2rot ( n1 n2 n3 n4 n5 n6 \u2013 n3 n4 n5 n6 n1 n2 )\n\t5 roll 5 roll ;\n\n: license ( -- : print out license information )\n\" \nThe MIT License (MIT)\n\nCopyright (c) 2016 Richard James Howe\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the 'Software'),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand\/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\nTHE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\nOTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\nARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE. \n\n\" \n;\n\n: welcome ( -- : print out a stupid welcome message which most interpreters seems insistent on)\n\t\" FORTH: libforth successfully loaded.\" cr\n\t\" Type 'help' and press return for a basic introduction.\" cr\n\t\" Type 'license' and press return to see the license. (MIT license).\" cr\n\t\" Core: \" here . \" \/ \" here unused + . cr\n\tok ;\n\n( @todo Improve this function! )\n: reader immediate \n\twelcome\n\tbegin read \" ok\" cr again ;\n( find reader start! warm )\n\n( ==================== Core utilities ======================== )\n\n( @todo Implement an equivalent to \"core.c\" here )\n( @todo Process a Forth core file and spit out a C structure\n containing information that describes the core file )\n( @todo Implement a series of words for manipulating cell sizes\n that are larger or smaller, and possibly of a different endianess\n to the currently running virtual machine )\n\n8 constant header-size ( size of Forth core file header )\n8 constant size-field-size ( the size in bytes of the size field in the core file )\n0 variable core-file ( core fileid we are reading in )\n0 variable core-cell-size ( cell size of Forth core )\n0 variable core-version ( version of core file )\n0 variable core-endianess ( endianess of core we are reading in )\n\n( save space to read in header )\ncreate header header-size chars allot\n: cheader ( -- c-addr : header char address )\n\theader chars> ;\ncreate size-field size-field-size chars allot\n: csize-field ( -- c-addr : address of place size field is stored in )\n\tsize-field chars> ;\n\n0\nenum header-magic0\nenum header-magic1\nenum header-magic2\nenum header-magic3\nenum header-cell-size\nenum header-version\nenum header-endianess\nenum header-magic4 \n\n: cleanup ( -- : cleanup before abort )\n\tcore-file @ ?dup 0<> if close-file drop then ;\n\n: invalid-header ( bool -- : abort if header is invalid )\n\t<> if cleanup abort\" invalid header\" then ;\n\n: save-core-cell-size ( char -- : save the core file cell size, checking if it is valid )\n\tcore-cell-size !\n\t\" cell size:\" tab\n\tcore-cell-size @ 2 = if 2 . cr exit then\n\tcore-cell-size @ 4 = if 4 . cr exit then\n\tcore-cell-size @ 8 = if 8 . cr exit then\n\tcleanup core-cell-size @ . abort\" : invalid cell size\" ;\n\n: check-version-compatibility ( char -- : checks the version compatibility of the core file ) \n\tcore-version !\n\tcore-version @ 2 = if \" core ver:\t2\" cr exit then\n\tcleanup core-version @ . abort\" : unknown version number\" ;\n\n: save-endianess ( char -- : save the endianess, checking if it is valid )\n\tcore-endianess !\n\t\" endianess:\" tab\n\tcore-endianess @ 0 = if \" big\" cr exit then\n\tcore-endianess @ 1 = if \" little\" cr exit then\n\tcleanup core-endianess @ . abort\" invalid endianess\" then ;\n\n: read-or-abort ( c-addr size fileid -- : )\n\tover >r read-file \n\t 0<> if cleanup abort\" file read failed\" then\n\tr> <> if cleanup abort\" header too small\" then ;\n\n: header? ( -- : print out header information )\n\tcheader header-size core-file @ read-or-abort\n\t( \" raw header:\" header 2 dump )\n\tcheader header-magic0 + c@ 255 invalid-header\n\tcheader header-magic1 + c@ [char] 4 invalid-header\n\tcheader header-magic2 + c@ [char] T invalid-header\n\tcheader header-magic3 + c@ [char] H invalid-header\n\tcheader header-cell-size + c@ save-core-cell-size\n\tcheader header-version + c@ check-version-compatibility\n\tcheader header-endianess + c@ save-endianess\n\tcheader header-magic4 + c@ 255 invalid-header\n\t\" valid header\" cr ;\n\n: size? ( -- : print out core file size )\n\tcsize-field size-field-size core-file @ read-or-abort\n\t( @todo improve method for printing out size )\n\t\" size: \" size-field size-field-size chars dump ;\n\n\n: core ( c-addr u -- : )\n\t2dup \" core file:\" tab type cr\n\tr\/o open-file-or-abort core-file ! \n\theader?\n\tsize?\n\tcore-file @ close-file drop ;\n\n( s\" forth.core\" core )\n\n:hide \nheader-size header? \nheader-magic0 header-magic1 header-magic2 header-magic3\nheader-version header-cell-size header-endianess header-magic4\nheader \ncore-file save-core-cell-size check-version-compatibility\ncore-cell-size cheader\ncore-endianess core-version save-endianess invalid-header\ncleanup size-field csize-field size-field-size\nread-or-abort size?\n;hide\n\n( ==================== Core utilities ======================== )\n\n( \nLooking at most Forths dictionary with \"words\" command they tend\nto have a lot of words that do not mean anything but to the implementers\nof that specific Forth, here we clean up as many non standard words as\npossible.\n)\n:hide\n write-string do-string ')' alignment-bits print-string\n compile-instruction dictionary-start hidden? hidden-mask instruction-mask\n max-core dolist x x! x@ write-exit\n max-string-length error-no-word\n original-exit\n pnum\n TrueFalse >instruction print-header\n print-name print-start print-previous print-immediate\n print-instruction xt-instruction defined-word? print-defined\n `state\n `source-id `sin `sidx `slen `start-address `fin `fout `stdin\n `stdout `stderr `argc `argv `debug `invalid `top `instruction\n `stack-size `error-handler\n open-file-or-abort\n;hide\n\n( \n## Forth To List\n\nThe following is a To-Do list for the Forth code itself, along with any\nother ideas.\n\n* Rewrite starting word using \"restart-word!\"\n* Word, Parse, other forth words\n* add \"j\" if possible to get outer loop context\n* FORTH, VOCABULARY\n* \"Value\", \"To\", \"Is\"\n* Double cell words and floating point library\n* The interpreter should use character based addresses, instead of\nword based, and use values that are actual valid pointers, this\nwill allow easier interaction with the world outside the virtual machine\n* Abort\", this could be used to implement words such\nas \"abort if in compile mode\", or \"abort if in command mode\".\n* common words and actions should be factored out to simplify\ndefinitions of other words, their standards compliant version found\nif any\n* throw and exception\n* here documents, string literals\n* A set of words for navigating around word definitions would be\nhelp debugging words, for example:\n\tcompile-field code-field field-translate\nwould take a pointer to a compile field for a word and translate\nthat into the code field\n* proper booleans should be used throughout\n* virtual machines could be made in other languages than C that will\nrun the core files generated...The virtual machine has higher level\nfunctions in it that it probably should not have, like \"read\" and\n\"system\", these belong elsewhere - but where?\n* It would be interesting to see which Unix utilities could easily\nbe implemented as Forth programs, such as \"head\", \"tail\", \"cat\", \"tr\",\n\"grep\", etcetera.\n* A utility for compressing core files could be made in Forth, it would mimic\nthe \"rle.c\" program previously present in the repository - that is it would\nuse run length encoding.\n* The manual pages, and various PDF files, should be generated using pandoc.\nThe manual page for the forth library can be generated from the header file, which\nwill need special preparation [a markdown file will have to be generated from the\nheader file, that file can the be used for the manual page].\n\nSome interesting links:\n\t* http:\/\/www.figuk.plus.com\/build\/heart.htm\n\t* https:\/\/groups.google.com\/forum\/#!msg\/comp.lang.forth\/NS2icrCj1jQ\/1btBCkOWr9wJ\n\t* http:\/\/newsgroups.derkeiler.com\/Archive\/Comp\/comp.lang.forth\/2005-09\/msg00337.html\n\t* https:\/\/stackoverflow.com\/questions\/407987\/what-are-the-primitive-forth-operators\n)\n\n\n(\nThe following will not work as we might actually be reading from a string [`sin]\nnot `fin. \n: key 32 chars> 1 `fin @ read-file drop 0 = if 0 else 32 chars> c@ then ;\n)\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"4f03b770cfe86e0177841c6a27602ffc2ff0a340","subject":"more list\/number op implementations","message":"more list\/number op implementations\n","repos":"cooper\/ferret","old_file":"std\/Extension\/List.frt","new_file":"std\/Extension\/List.frt","new_contents":"class List \n\n#> Represents a list with an event number of elements, treated as pairs.\n#| This is similar to a hash with ordered keys.\ntype Pairs {\n isa *class\n satisfies .length.even\n}\n\n#> True if the list is empty.\n.empty -> @length == 0\n\n#> Returns a copy of the list by mapping each element to another value based on\n#| a transformation code.\n.map {\n need $code: Code\n -> gather for $el in *self {\n take $code($el)\n }\n}\n\n#> Returns a copy of the list containing only the elements that satisfy a code.\n.grep {\n need $code: Code\n -> gather for $el in *self {\n if $code($el): take $el\n }\n}\n\n#> Returns a flattened copy of the list.\nmethod flatten {\n $new = []\n for $el in *self {\n if $el.*isa(List)\n $new.push(items: $el.flatten())\n else\n $new.push($el)\n }\n -> $new\n}\n\n#> Returns a reversed copy of the list.\nmethod reverse {\n if @empty\n -> *self\n -> gather for $i in @lastIndex..0:\n take *self[$i]\n}\n\n#> Copies the list, ignoring all possible occurrences of a specified value.\nmethod withoutAll {\n need $what\n -> @grep! { -> $what != $_ }\n # -> @grep(func { -> $what != $_ })\n}\n\n#> Copies the list, ignoring the first occurrence of a specified value.\nmethod without {\n need $what\n var $found\n -> gather for ($i, $el) in *self {\n if !$found && $what == $el {\n $found = true\n next\n }\n take $el\n }\n}\n\n#> Removes the first element equal to a specified value.\nmethod remove {\n need $what\n removed -> false\n for ($i, $el) in *self {\n if $what != $el\n next\n @splice($i, 1)\n removed -> true\n last\n }\n}\n\n#> Removes all elements equal to a specified value.\nmethod removeAll {\n need $what\n\n # find the indices at which the value occurs\n $indices = gather for ($i, $el) in *self {\n if $what != $el\n next\n take $i\n }\n\n # remove\n for $i in $indices.reverse!\n @splice($i, 1)\n\n removed -> $indices.length #< number of removed elements\n}\n\n#> Returns true if the list contains at least one occurrence of the provided\n#| value.\nmethod contains {\n need $what\n -> @any! { -> $what == $_ }\n}\n\n#> Finds the first element to satisfy a code.\nmethod first {\n need $code: Code\n for $el in *self {\n if $code($el): -> $el\n }\n -> undefined\n}\n\n#> Returns the index of the first occurrence of the given value\nmethod indexOf {\n need $what\n for ($i, $el) in *self {\n if $what == $el: -> $i\n }\n -> undefined\n}\n\n#> Returns true if at least one element satisfies a code.\nmethod any {\n need $code: Code\n for $el in *self {\n if $code($el): -> true\n }\n -> false\n}\n\n#> Returns true if all elements satisfy a code.\nmethod all {\n need $code: Code\n for $el in *self {\n if !$code($el): -> false\n }\n -> true\n}\n\n#> Returns the sum of all elements in the list or `undefined` if the list is\n#| empty.\n.sum {\n if @empty\n -> undefined\n $c = *self[0]\n for $i in 1 .. @lastIndex {\n $c = $c + *self[$i]\n }\n -> $c\n}\n\n#> Returns the sum of all elements in the list or `0` (zero) if the list is\n#| empty. Useful for lists of numbers.\n.sum0 {\n $c = 0\n for $el in *self {\n $c = $c + $el\n }\n -> $c\n}\n\n#> Returns the first element in the list.\n.firstItem -> *self[0]\n\n#> Returns the last element in the list.\n.lastItem -> *self[@lastIndex]\n\n#> If the list has length one, returns an empty string, otherwise `\"s\"`\n.s {\n if @length == 1\n -> \"\"\n -> \"s\"\n}\n\n#> Returns an iterator for the list. This allows lists to be used in a for loop.\n.iterator -> ListIterator(*self) : Iterator\n\n#> Adding lists together results in an ordered consolidation of the lists.\nop + {\n need $rhs: List\n $new = @copy()\n $new.push(items: $rhs)\n -> $new\n}\n\n#> Subtracting list B from list A results in a new list containing all elements\n#| found in A but not found in B. Example: `[1,2,3,4,5] - [3,5]` -> `[1,2,4]`.\nop - {\n need $rhs: List\n $new = @copy()\n for $remove in $rhs:\n $new.removeAll($remove)\n -> $new\n}\n\n#> Lists are equal if all the elements are equal and in the same order.\nop == {\n need $ehs: List\n\n # first check if length is same\n if @length != $ehs.length\n -> false\n\n # check each item\n for ($i, $val) in *self {\n if $ehs[$i] != $val\n -> false\n }\n\n -> true\n}\n\n#> Lists are equal to their numerical length.\nop == {\n need $ehs: Num\n -> @length == $ehs\n}\n\n#> Lists are greater than numbers smaller than their length.\nop > {\n need $rhs: Num\n -> @length > $rhs\n}\n\n#> Lists are smaller than numbers greater than their length.\nop < {\n need $rhs: Num\n -> @length < $rhs\n}\n\n#> Lists are greater than numbers smaller than their length.\nop > {\n need $lhs: Num\n -> @length < $lhs\n}\n\n#> Lists are smaller than numbers greater than their length.\nop < {\n need $lhs: Num\n -> @length > $lhs\n}\n\n# Iterator methods\n\n.iterator -> *self\n\nmethod reset {\n @i = -1\n}\n\n.more -> @i < (@lastIndex || -1)\n\n.nextElement {\n @i += 1\n -> *self[@i]\n}\n\n.nextElements {\n @i += 1\n -> [ @i, *self[@i] ]\n}","old_contents":"class List \n\n#> Represents a list with an event number of elements, treated as pairs.\n#| This is similar to a hash with ordered keys.\ntype Pairs {\n isa *class\n satisfies .length.even\n}\n\n#> True if the list is empty.\n.empty -> @length == 0\n\n#> Returns a copy of the list by mapping each element to another value based on\n#| a transformation code.\n.map {\n need $code: Code\n -> gather for $el in *self {\n take $code($el)\n }\n}\n\n#> Returns a copy of the list containing only the elements that satisfy a code.\n.grep {\n need $code: Code\n -> gather for $el in *self {\n if $code($el): take $el\n }\n}\n\n#> Returns a flattened copy of the list.\nmethod flatten {\n $new = []\n for $el in *self {\n if $el.*isa(List)\n $new.push(items: $el.flatten())\n else\n $new.push($el)\n }\n -> $new\n}\n\n#> Returns a reversed copy of the list.\nmethod reverse {\n if @empty\n -> *self\n -> gather for $i in @lastIndex..0:\n take *self[$i]\n}\n\n#> Copies the list, ignoring all possible occurrences of a specified value.\nmethod withoutAll {\n need $what\n -> @grep! { -> $what != $_ }\n # -> @grep(func { -> $what != $_ })\n}\n\n#> Copies the list, ignoring the first occurrence of a specified value.\nmethod without {\n need $what\n var $found\n -> gather for ($i, $el) in *self {\n if !$found && $what == $el {\n $found = true\n next\n }\n take $el\n }\n}\n\n#> Removes the first element equal to a specified value.\nmethod remove {\n need $what\n removed -> false\n for ($i, $el) in *self {\n if $what != $el\n next\n @splice($i, 1)\n removed -> true\n last\n }\n}\n\n#> Removes all elements equal to a specified value.\nmethod removeAll {\n need $what\n\n # find the indices at which the value occurs\n $indices = gather for ($i, $el) in *self {\n if $what != $el\n next\n take $i\n }\n\n # remove\n for $i in $indices.reverse!\n @splice($i, 1)\n\n removed -> $indices.length #< number of removed elements\n}\n\n#> Returns true if the list contains at least one occurrence of the provided\n#| value.\nmethod contains {\n need $what\n -> @any! { -> $what == $_ }\n}\n\n#> Finds the first element to satisfy a code.\nmethod first {\n need $code: Code\n for $el in *self {\n if $code($el): -> $el\n }\n -> undefined\n}\n\n#> Returns the index of the first occurrence of the given value\nmethod indexOf {\n need $what\n for ($i, $el) in *self {\n if $what == $el: -> $i\n }\n -> undefined\n}\n\n#> Returns true if at least one element satisfies a code.\nmethod any {\n need $code: Code\n for $el in *self {\n if $code($el): -> true\n }\n -> false\n}\n\n#> Returns true if all elements satisfy a code.\nmethod all {\n need $code: Code\n for $el in *self {\n if !$code($el): -> false\n }\n -> true\n}\n\n#> Returns the sum of all elements in the list or `undefined` if the list is\n#| empty.\n.sum {\n if @empty\n -> undefined\n $c = *self[0]\n for $i in 1 .. @lastIndex {\n $c = $c + *self[$i]\n }\n -> $c\n}\n\n#> Returns the sum of all elements in the list or `0` (zero) if the list is\n#| empty. Useful for lists of numbers.\n.sum0 {\n $c = 0\n for $el in *self {\n $c = $c + $el\n }\n -> $c\n}\n\n#> Returns the first element in the list.\n.firstItem -> *self[0]\n\n#> Returns the last element in the list.\n.lastItem -> *self[@lastIndex]\n\n#> If the list has length one, returns an empty string, otherwise `\"s\"`\n.s {\n if @length == 1\n -> \"\"\n -> \"s\"\n}\n\n#> Returns an iterator for the list. This allows lists to be used in a for loop.\n.iterator -> ListIterator(*self) : Iterator\n\n#> Adding lists together results in an ordered consolidation of the lists.\nop + {\n need $rhs: List\n $new = @copy()\n $new.push(items: $rhs)\n -> $new\n}\n\n#> Subtracting list B from list A results in a new list containing all elements\n#| found in A but not found in B. Example: `[1,2,3,4,5] - [3,5]` -> `[1,2,4]`.\nop - {\n need $rhs: List\n $new = @copy()\n for $remove in $rhs:\n $new.removeAll($remove)\n -> $new\n}\n\n#> Lists are equal if all the elements are equal and in the same order.\nop == {\n need $ehs: List\n\n # first check if length is same\n if @length != $ehs.length\n -> false\n\n # check each item\n for ($i, $val) in *self {\n if $ehs[$i] != $val\n -> false\n }\n\n -> true\n}\n\n#> Lists are equal to their numerical length.\nop == {\n need $ehs: Num\n -> @length == $ehs\n}\n\n#> Lists are greater than numbers smaller than their length.\nop > {\n need $rhs: Num\n -> @length > $rhs\n}\n\n#> Lists are smaller than numbers greater than their length.\nop < {\n need $rhs: Num\n -> @length < $rhs\n}\n\n# Iterator methods\n\n.iterator -> *self\n\nmethod reset {\n @i = -1\n}\n\n.more -> @i < (@lastIndex || -1)\n\n.nextElement {\n @i += 1\n -> *self[@i]\n}\n\n.nextElements {\n @i += 1\n -> [ @i, *self[@i] ]\n}","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"2d74f67d8c35129cd4fd30ea05ac6ded4835a907","subject":"Update the label for the new name.","message":"Update the label for the new name.","repos":"rbsexton\/sockpuppet,rbsexton\/sockpuppet","old_file":"forth\/serCM3_sapi_p.fth","new_file":"forth\/serCM3_sapi_p.fth","new_contents":"\\ serCM3_sapi_p.fth - SAPI polled RX, polled TX, serial communication drivers\n\\ Written to run against the SockPuppet API.\n\n((\nAdapted from: the LPC polled driver.\n))\n\nonly forth definitions\nvariable cnt.pause \n\n\\ ==============\n\\ *! serCM3_sapi_p\n\\ *T SAPI polled serial driver\n\\ ==============\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\n\\ ** using the internal UARTs via the SAPI call layer.\n\n\n\\ ****************\n\\ *S Configuration\n\\ ****************\n\\ *P Configuration is managed by the SAPI\n\n\\ ********\n\\ *S Tools\n\\ ********\n\ntarget\n\n\\ ********************\n\\ *S Serial primitives\n\\ ********************\ninternal\n\n: +FaultConsole\t( -- ) ;\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\n\\ ** for more details.\n\ntarget\n\nCODE (seremitfc)\t\\ char base --\n\\ *G Service call for a single char - just fill in the registers\n\\ from the stack and make the call, and get back the flow control feedback\n\\ Put TOS into r0, pull r1 off the stack, and refresh the stack.\n\tmov r0, tos\n\tldr r1, [ psp ], # 4\t\n\tsvc # SAPI_VEC_PUTCHAR\t\n\tmov tos, r0\n next,\nEND-CODE\n\n: (seremit)\t\\ char base -- \n\\ *G Wrapped call that checks for throttling, and if so,\n\\ calls PAUSE to let another task run. Count these events for debugging purposes.\n\tDUP >R (seremitfc)\n\t0<> IF 1 cnt.pause +!\n\t\tself tcb.bbstatus @ R> 0 setiocallback drop stop \n\t\telse R> DROP then\n\t;\n\n: (sertype)\t\\ caddr len base --\n\\ *G Transmit a string on the given UART.\n -rot bounds\n ?do i c@ over (seremit) loop\n drop\n;\n\n: (sercr)\t\\ base --\n\\ *G Transmit a CR\/LF pair on the given UART.\n $0D over (seremit) $0A swap (seremit)\n;\n\nCODE (sergetchar) \\ base -- c\n\\ *G Get a character from the port\n\tmov r0, tos\t\n\tsvc # SAPI_VEC_GETCHAR\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE (serkey?) \\ base -- t\/f\n\\ *G Return true if the given UART has a character avilable to read.\n\\ The call returns 0 or 1. \n\tmov r0, tos\n\tsvc # SAPI_VEC_GETCHARAVAIL\t\t\n\tmov tos, r0\n\tnext,\t\nEND-CODE\n\n: (serkey-basic)\n\tbegin pause \n\tdup (serkey?) until \n\t(sergetchar)\n;\n\n: (serkey-sleep?)\n\tself tcb.bbstatus @ over 1 setiocallback drop ( base )\n\tself halt \n\tdup (serkey?) IF self restart ELSE PAUSE THEN \\ We are now armed and ready to block\n (serkey?) \n;\n\n\\ *G Wait for a character to come available on the given UART and\n\\ ** return the character.\n\\ Advanced usage - Register a callback. \n\\ The tricky part is not screwing things up by missing a character\n\\ in the window between when you register, and when you pick up your\n\\ character. The way to do that is by registering, then self \n\\ halting, and then checking for a new character. That ensures that\n\\ if a character has slipped in, you will catch it.\n: (serkey)\t\\ base -- char\n\tbegin dup (serkey-sleep?) until (sergetchar)\n;\n\nexternal \n\n: seremit0\t\\ char --\n\\ *G Transmit a character on UART0.\n 0 (seremit) ;\n: sertype0\t\\ c-addr len --\n\\ *G Transmit a string on UART0.\n 0 (sertype) ;\n: sercr0\t\\ --\n\\ *G Issue a CR\/LF pair to UART0.\n 0 (sercr) ;\n: serkey?0\t\\ -- flag\n\\ *G Return true if UART0 has a character available.\n 0 (serkey?) ;\n: serkey0\t\\ -- char\n\\ *G Wait for a character on UART0.\n 0 (serkey) ;\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\n\\ *G Generic I\/O device for UART0.\n ' serkey0 ,\t\t\\ -- char ; receive char\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\n ' seremit0 ,\t\t\\ -- char ; display char\n ' sertype0 ,\t\t\\ caddr len -- ; display string\n ' sercr0 ,\t\t\\ -- ; display new line\n\n\\ UART2\n: seremit2 #2 (seremit) ;\n: sertype2\t#2 (sertype) ;\n: sercr2\t#2 (sercr) ;\n: serkey?2\t#2 (serkey?) ;\n: serkey2\t#2 (serkey) ;\ncreate Console2 ' serkey2 , ' serkey?2 , ' seremit2 , ' sertype2 , ' sercr2 ,\t\n\n\\ Versions for use with the TCP Port (10)\n: seremit10 #10 (seremit) ;\n: sertype10\t#10 (sertype) ;\n: sercr10\t#10 (sercr) ;\n: serkey?10\t#10 (serkey?) ;\n: serkey10\t#10 (serkey) ;\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\n\nconsole-port 0 = [if]\n console0 constant console\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\n\\ ** It may be changed by one of the phrases of the form:\n\\ *C dup opvec ! ipvec !\n\\ *C SetConsole\n[then]\n\nconsole-port #1 = [if]\n console1 constant console\n[then]\n\nconsole-port #10 = [if]\n console10 constant console\n[then]\n\n\\ ************************\n\\ *S System initialisation\n\\ ************************\n\n\\ This is a NOP in the SAPI environment\n: init-ser ;\t\\ --\n\\ *G Initialise all serial ports\n\n\n\\ ======\n\\ *> ###\n\\ ======\n\ndecimal\n","old_contents":"\\ serCM3_sapi_p.fth - SAPI polled RX, polled TX, serial communication drivers\n\\ Written to run against the SockPuppet API.\n\n((\nAdapted from: the LPC polled driver.\n))\n\nonly forth definitions\nvariable cnt.pause \n\n\\ ==============\n\\ *! serCM3_sapi_p\n\\ *T SAPI polled serial driver\n\\ ==============\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\n\\ ** using the internal UARTs via the SAPI call layer.\n\n\n\\ ****************\n\\ *S Configuration\n\\ ****************\n\\ *P Configuration is managed by the SAPI\n\n\\ ********\n\\ *S Tools\n\\ ********\n\ntarget\n\n\\ ********************\n\\ *S Serial primitives\n\\ ********************\ninternal\n\n: +FaultConsole\t( -- ) ;\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\n\\ ** for more details.\n\ntarget\n\nCODE (seremitfc)\t\\ char base --\n\\ *G Service call for a single char - just fill in the registers\n\\ from the stack and make the call, and get back the flow control feedback\n\\ Put TOS into r0, pull r1 off the stack, and refresh the stack.\n\tmov r0, tos\n\tldr r1, [ psp ], # 4\t\n\tsvc # SAPI_VEC_PUTCHAR\t\n\tmov tos, r0\n next,\nEND-CODE\n\n: (seremit)\t\\ char base -- \n\\ *G Wrapped call that checks for throttling, and if so,\n\\ calls PAUSE to let another task run. Count these events for debugging purposes.\n\tDUP >R (seremitfc)\n\t0<> IF 1 cnt.pause +!\n\t\tself tcb.bbstatus @ R> 0 setiocallback drop stop \n\t\telse R> DROP then\n\t;\n\n: (sertype)\t\\ caddr len base --\n\\ *G Transmit a string on the given UART.\n -rot bounds\n ?do i c@ over (seremit) loop\n drop\n;\n\n: (sercr)\t\\ base --\n\\ *G Transmit a CR\/LF pair on the given UART.\n $0D over (seremit) $0A swap (seremit)\n;\n\nCODE (sergetchar) \\ base -- c\n\\ *G Get a character from the port\n\tmov r0, tos\t\n\tsvc # SAPI_VEC_GETCHAR\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE (serkey?) \\ base -- t\/f\n\\ *G Return true if the given UART has a character avilable to read.\n\\ The call returns 0 or 1. \n\tmov r0, tos\n\tsvc # SAPI_VEC_CHARSAVAIL\t\t\n\tmov tos, r0\n\tnext,\t\nEND-CODE\n\n: (serkey-basic)\n\tbegin pause \n\tdup (serkey?) until \n\t(sergetchar)\n;\n\n: (serkey-sleep?)\n\tself tcb.bbstatus @ over 1 setiocallback drop ( base )\n\tself halt \n\tdup (serkey?) IF self restart ELSE PAUSE THEN \\ We are now armed and ready to block\n (serkey?) \n;\n\n\\ *G Wait for a character to come available on the given UART and\n\\ ** return the character.\n\\ Advanced usage - Register a callback. \n\\ The tricky part is not screwing things up by missing a character\n\\ in the window between when you register, and when you pick up your\n\\ character. The way to do that is by registering, then self \n\\ halting, and then checking for a new character. That ensures that\n\\ if a character has slipped in, you will catch it.\n: (serkey)\t\\ base -- char\n\tbegin dup (serkey-sleep?) until (sergetchar)\n;\n\nexternal \n\n: seremit0\t\\ char --\n\\ *G Transmit a character on UART0.\n 0 (seremit) ;\n: sertype0\t\\ c-addr len --\n\\ *G Transmit a string on UART0.\n 0 (sertype) ;\n: sercr0\t\\ --\n\\ *G Issue a CR\/LF pair to UART0.\n 0 (sercr) ;\n: serkey?0\t\\ -- flag\n\\ *G Return true if UART0 has a character available.\n 0 (serkey?) ;\n: serkey0\t\\ -- char\n\\ *G Wait for a character on UART0.\n 0 (serkey) ;\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\n\\ *G Generic I\/O device for UART0.\n ' serkey0 ,\t\t\\ -- char ; receive char\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\n ' seremit0 ,\t\t\\ -- char ; display char\n ' sertype0 ,\t\t\\ caddr len -- ; display string\n ' sercr0 ,\t\t\\ -- ; display new line\n\n\\ UART2\n: seremit2 #2 (seremit) ;\n: sertype2\t#2 (sertype) ;\n: sercr2\t#2 (sercr) ;\n: serkey?2\t#2 (serkey?) ;\n: serkey2\t#2 (serkey) ;\ncreate Console2 ' serkey2 , ' serkey?2 , ' seremit2 , ' sertype2 , ' sercr2 ,\t\n\n\\ Versions for use with the TCP Port (10)\n: seremit10 #10 (seremit) ;\n: sertype10\t#10 (sertype) ;\n: sercr10\t#10 (sercr) ;\n: serkey?10\t#10 (serkey?) ;\n: serkey10\t#10 (serkey) ;\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\n\nconsole-port 0 = [if]\n console0 constant console\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\n\\ ** It may be changed by one of the phrases of the form:\n\\ *C dup opvec ! ipvec !\n\\ *C SetConsole\n[then]\n\nconsole-port #1 = [if]\n console1 constant console\n[then]\n\nconsole-port #10 = [if]\n console10 constant console\n[then]\n\n\\ ************************\n\\ *S System initialisation\n\\ ************************\n\n\\ This is a NOP in the SAPI environment\n: init-ser ;\t\\ --\n\\ *G Initialise all serial ports\n\n\n\\ ======\n\\ *> ###\n\\ ======\n\ndecimal\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"69476650b01e5cc62995be596266e694642e4694","subject":"midifile: fix mf.seek","message":"midifile: fix mf.seek\n\nreposition-file takes a double word, not a single word\n\nFixes #128\n","repos":"philburk\/hmsl,philburk\/hmsl,philburk\/hmsl","old_file":"hmsl\/tools\/midifile.fth","new_file":"hmsl\/tools\/midifile.fth","new_contents":"\\ MIDI File Standard Support\n\\\n\\ This code allows the sharing of music data between applications.\n\\\n\\ Author: Phil Burk\n\\ Copyright 1989 Phil Burk\n\\\n\\ MOD: PLB 6\/11\/90 Added SWAP to $MF.LOAD.SHAPE\n\\ MOD: PLB 10\/23\/90 Added $MF.OPEN.VR\n\\ MOD: PLB 6\/91 Add MIDIFILE1{\n\\ 00001 PLB 9\/5\/91 Fix MIDIFILE1{ by c\/i\/j\/\n\\ 00002 PLB 3\/17\/92 Changed MF.WRITE.REL.SHAPE to make notes legato\n\\ for notation programs. Add $SAVE.REL.SHAPE and $..ABS..\n\nANEW TASK-MIDIFILE\ndecimal\n\n\\ Variable Length Number Conversion\nvariable VLN-PAD ( accumulator for variable length number )\nvariable VLN-COUNT ( number of bytes )\n\n: BYTE>VLN ( byte -- , add byte to VLN buffer )\n vln-count @ 0>\n IF $ 80 or ( set continuation bit )\n THEN\n vln-pad 4+ vln-count @ 1+ dup vln-count !\n - c!\n;\n\n: NUMBER->VLN ( N -- address count , convert )\n dup $ 0FFFFFFF >\n IF .\" NUMBER->VL - Number too big for MIDI File! = \"\n dup .hex cr\n $ 0FFFFFFF and\n THEN\n dup 0<\n IF .\" NUMBER->VL - Negative length or time! = \"\n dup .hex cr\n drop 0\n THEN\n vln-count off\n BEGIN dup $ 7F and byte>vln\n -7 shift dup 0=\n UNTIL drop\n vln-pad 4+ vln-count @ dup>r - r>\n;\n\n: VLN.CLEAR ( -- , clear for read )\n vln-count off vln-pad off\n;\n\n: VLN.ACCUM ( byte -- accumulate another byte )\n $ 7F and\n vln-pad @ 7 shift or vln-pad !\n;\n\n\\ -------------------------------------------------\nvariable MF-BYTESLEFT\nvariable MF-EVENT-TIME\nvariable MF-#DATA\n\n: CHKID ( -- , define chkid )\n 32 lword count drop be@ constant\n;\n\nchkid MThd 'MThd'\nchkid MTrk 'MTrk'\n\nvariable mf-FILEID\n16 constant MF_PAD_SIZE\nvariable mf-PAD mf_pad_size allot\n\nDEFER MF.PROCESS.TRACK ( size track# -- )\nDEFER MF.ERROR\n\n' abort is mf.error\n\n: .CHKID ( 'chkid' -- , print chunk id )\n pad be! pad 4 type\n;\n\n: $MF.OPEN ( $filename -- )\n dup c@ 0=\n IF drop .\" $MF.OPEN - No filename given!\" cr mf.error\n THEN\n dup count r\/o bin open-file\n IF drop .\" Couldn't open file: \" $type cr mf.error\n THEN\n mf-fileid !\n drop\n;\n\n: $MF.CREATE ( $filename -- , create new file )\n dup c@ 0=\n IF drop .\" $MF.OPEN - No filename given!\" cr mf.error\n THEN\n dup count w\/o bin create-file\n IF drop .\" Couldn't create file: \" $type cr mf.error\n THEN\n mf-fileid !\n drop\n;\n: MF.SET.FILE ( fileid -- )\n mf-fileid !\n;\n\n: MF.READ ( addr #bytes -- #bytes , read from open mf file)\n dup negate mf-bytesleft +!\n mf-fileid @ read-file abort\" Could not read MIDI file.\"\n;\n\n: MF.READ.CHKID ( -- size chkid )\n dup>r mf-pad 8 mf.read\n 8 -\n IF .\" Truncated chunk \" r@ .chkid cr mf.error\n THEN\n rdrop\n mf-pad cell+ be@\n mf-pad be@\n;\n\n\n: MF.WRITE ( addr #bytes -- #bytes , write to open mf file)\n dup>r mf-fileid @ write-file abort\" Could not write MIDI file.\"\n r>\n;\n\n: MF.WRITE? ( addr #bytes -- , write to open mf file or mf.ERROR)\n mf-fileid @ write-file abort\" Could not write MIDI file.\"\n;\n\n: MF.READ.BYTE ( -- byte )\n mf-pad 1 mf.read 1-\n IF .\" MF.READ.BYTE - Unexpected EOF!\" cr mf.error\n THEN\n mf-pad c@\n;\n\n: MF.WRITE.BYTE ( byte -- )\n mf-pad c! mf-pad 1 mf.write?\n;\n\n: MF.WRITE.WORD ( 16word -- )\n mf-pad w! mf-pad 2 mf.write?\n;\n\n: MF.READ.WORD ( -- 16word )\n mf-pad 2 mf.read 2-\n IF .\" MF.READ.WORD - Unexpected EOF!\" cr mf.error\n THEN\n mf-pad w@\n;\n\n: MF.WRITE.CHKID ( size chkid -- , write chunk header )\n mf-pad be!\n mf-pad cell+ be!\n mf-pad 8 mf.write?\n;\n\n: MF.WRITE.CHUNK ( address size chkid -- , write complete chunk )\n over >r mf.write.chkid\n r> mf.write?\n;\n\n: MF.READ.TYPE ( -- typeid )\n mf-pad 4 mf.read\n 4 -\n IF .\" Truncated type!\" cr mf.error\n THEN\n mf-pad be@\n;\n\n: MF.WHERE ( -- current_pos , in file )\n mf-fileid @ file-position abort\" file-position failed\"\n d>s \\ file-position returns a double word\n;\n\n: MF.SEEK ( position -- , in file )\n s>d \\ reposition-file takes a double word\n mf-fileid @ reposition-file abort\" reposition-file failed\"\n;\n\n: MF.SKIP ( n -- , skip n bytes in file )\n dup negate mf-bytesleft +!\n mf.where + mf.seek\n;\n\n: MF.CLOSE\n mf-fileid @ ?dup\n IF close-file abort\" close-file failed\"\n 0 mf-fileid !\n THEN\n;\n\nvariable MF-NTRKS \\ number of tracks in file\nvariable MF-FORMAT \\ file format = 0 | 1 | 2\nvariable MF-DIVISION \\ packed division\n\n: MF.PROCESS.HEADER ( size -- )\n dup mf_pad_size >\n IF .\" MF.PROCESS.HEADER - Bad Header Size = \"\n dup . cr mf.error\n THEN\n mf-pad swap mf.read drop\n mf-pad bew@ mf-format w!\n mf-pad 2+ bew@ mf-ntrks !\n mf-pad 4+ bew@ mf-division !\n;\n\n: MF.SCAN.HEADER ( -- , read header )\n mf.read.chkid ( -- size chkid)\n 'MThd' =\n IF mf.process.header\n ELSE .\" MF.SCAN - Headerless MIDIFile!\" cr mf.error\n THEN\n;\n\n: MF.SCAN.TRACKS ( -- , read tracks )\n\\ This word leaves the file position just after the chunk data.\n mf-ntrks @ 0\n DO mf.read.chkid 'MTrk' =\n IF dup mf.where + >r\n i mf.process.track\n r> mf.seek ( move past chunk)\n ELSE .\" MF.SCAN - Unexpected CHKID!\" cr mf.error\n THEN\n LOOP\n;\n\n: MF.SCAN ( -- , read header then tracks)\n mf.scan.header\n mf.scan.tracks\n;\n\n: MF.VALIDATE ( -- ok? , make sure open file has header chunk )\n mf.where\n 0 mf.seek\n mf.read.type 'MThd' =\n swap mf.seek\n;\n\n: (MF.DOFILE) ( -- ,process current file )\n mf.validate\n IF mf.scan\n ELSE .\" Not a MIDIFile!\" cr\n mf.close mf.error\n THEN\n mf.close\n;\n\n: $MF.DOFILE ( $filename -- , process file using deferred words)\n $mf.open (mf.dofile)\n;\n\n: MF.DOFILE ( -- )\n fileword $mf.dofile\n;\n\n: MF.READ.VLN ( -- vln , read vln from file )\n vln.clear\n BEGIN mf.read.byte dup $ 80 and\n WHILE vln.accum\n REPEAT vln.accum\n vln-pad @\n;\n\ndefer MF.PROCESS.META ( size metaID -- , process Meta event )\ndefer MF.PROCESS.SYSEX\ndefer MF.PROCESS.ESCAPE\n\nvariable MF-SEQUENCE#\nvariable MF-CHANNEL\n: MF.LOOK.TEXT ( size metaID -- , read and show text )\n >newline .\" MetaEvent = \" . cr\n pad swap mf.read\n pad swap type cr\n;\n\n: MF.HANDLE.META ( size MetaID -- default Meta event handler )\n dup $ 01 $ 0f within?\n IF mf.look.text\n ELSE CASE\n $ 00 OF drop mf.read.word mf-sequence# ! ENDOF\n $ 20 OF drop mf.read.byte 1+ mf-channel ! ENDOF\n .\" MetaEvent = \" dup . cr\n swap mf.skip ( skip over other event types )\n ENDCASE\n THEN\n;\n\n' mf.handle.meta is MF.PROCESS.META\n' mf.skip is MF.PROCESS.SYSEX\n' mf.skip is MF.PROCESS.ESCAPE\n\n: MF.PARSE.EVENT ( -- , parse MIDI event )\n mf.read.byte dup $ 80 and ( is it a command or running status data )\n IF CASE\n $ FF OF mf.read.byte ( get type )\n mf.read.vln ( get size ) swap mf.process.meta ENDOF\n $ F0 OF .\" F0 byte\" cr mf.read.vln mf.process.sysex ENDOF\n $ F7 OF .\" F7 byte\" cr mf.read.vln mf.process.escape ENDOF\n\\ Regular command.\n dup mp.#bytes mf-#data !\n dup mp.handle.command\n mf-#data @ 0\n DO mf.read.byte mp.handle.data\n LOOP\n ENDCASE\n ELSE\n mp.handle.data ( call MIDI parser with byte read )\n mf-#data @ 1- 0 max 0\n DO mf.read.byte mp.handle.data\n LOOP\n THEN\n;\n\n: MF.PARSE.TRACK ( size track# -- )\n drop mf-bytesleft !\n 0 mf-event-time !\n BEGIN mf.read.vln mf-event-time +!\n mf.parse.event\n mf-bytesleft @ 1 <\n UNTIL\n;\n\n\\ Some Track Handlers\n: MF.PRINT.NOTEON ( note velocity -- )\n ?pause\n mf-event-time @ 4 .r .\" , \"\n .\" ON N,V = \" swap . . cr\n;\n: MF.PRINT.NOTEOFF ( note velocity -- )\n ?pause\n mf-event-time @ 4 .r .\" , \"\n .\" OFF N,V = \" swap . . cr\n;\n\n: MF.PRINT.TRACK ( size track# -- )\n 2dup\n >newline dup 0=\n IF .\" MIDIFile Format = \" mf-format @ . cr\n .\" Division = $\" mf-division @ dup .hex . cr\n THEN\n .\" Track# \" . .\" is \" . .\" bytes.\" cr\n 'c mf.print.noteon mp-on-vector !\n 'c mf.print.noteoff mp-off-vector !\n mf.parse.track\n mp.reset\n;\n\n' mf.print.track is mf.process.track\n\n: MF.CHECK ( -- , print chunks )\n what's mf.process.track\n ' mf.print.track is mf.process.track\n mf.dofile\n is mf.process.track\n;\n\n\\ Track Handler that loads a shape -----------------------\nvariable MF-TRACK-CHOSEN\nob.shape MF-SHAPE\n\n: MF.LOAD.NOTEON ( note velocity -- )\n mf-shape ensure.room\n mf-event-time @ -rot add: mf-shape\n;\n\n: MF.LOAD.NOTEOFF ( note velocity -- )\n mf-shape ensure.room\n drop mf-event-time @ swap 0 add: mf-shape\n;\n\n: MF.LOAD.TRACK ( size track# -- )\n max.elements: mf-shape 0=\n IF 64 3 new: mf-shape\n ELSE clear: mf-shape\n THEN\n 'c mf.load.noteon mp-on-vector !\n 'c mf.load.noteoff mp-off-vector !\n mf.parse.track\n;\n\n: MF.PICK.TRACK ( size track# -- )\n dup mf-track-chosen @ =\n IF mf.load.track\n ELSE 2drop\n THEN\n;\n\n: $MF.LOAD.SHAPE ( track# $filename -- , load track into mf-shape )\n swap mf-track-chosen !\n what's mf.process.track SWAP ( -- oldcfa $filename )\n 'c mf.pick.track is mf.process.track\n $mf.dofile\n is mf.process.track\n;\n\n: MF.LOAD.SHAPE ( track# -- , load track into mf-shape )\n fileword $mf.load.shape\n;\n\n: LOAD.ABS.SHAPE ( shape -- )\n 0 mf.load.shape\n clone: mf-shape\n free: mf-shape\n;\n\n\\ -------------------------------------------------\n\n\\ Tools for writing a MIDIFile.\n: MF.WRITE.HEADER ( format ntrks division -- )\n 6 'MThd' mf.write.chkid\n mf-pad 4+ bew! ( division )\n over 0=\n IF drop 1 ( force NTRKS to 1 for format zero )\n THEN\n mf-pad 2+ bew! ( ntrks )\n mf-pad bew! ( format )\n mf-pad 6 mf.write?\n;\n\n: MF.BEGIN.TRACK ( -- curpos , write track start )\n 0 'MTrk' mf.write.chkid\n mf.where\n 0 mf-event-time !\n;\n\n: MF.WRITE.VLN ( n -- , write variable length quantity )\n number->vln mf.write?\n;\n\n: MF.WRITE.TIME ( time -- , write time as vln delta )\n dup mf-event-time @ - mf.write.vln\n mf-event-time !\n;\n\n: MF.WRITE.EVENT ( addr count time -- , write MIDI event )\n\\ This might be called from custom MIDI.FLUSH\n mf.write.time\n mf.write?\n;\n\nvariable MF-EVENT-PAD\n\n: MF.WRITE.META ( addr count event-type -- )\n mf-event-time @ mf.write.time\n $ FF mf.write.byte\n mf.write.byte ( event type )\n dup mf.write.vln ( len )\n mf.write?\n;\n\n: MF.WRITE.SYSEX ( addr count -- )\n mf-event-time @ mf.write.time\n $ F0 mf.write.byte\n dup mf.write.vln ( len )\n mf.write?\n;\n\n: MF.WRITE.ESCAPE ( addr count -- )\n mf-event-time @ mf.write.time\n $ F7 mf.write.byte\n dup mf.write.vln ( len )\n mf.write?\n;\n\n: MF.WRITE.SEQ# ( seq# -- )\n mf-event-pad w!\n mf-event-pad 2 0 mf.write.meta\n;\n\n: MF.WRITE.END ( -- , write end of track )\n mf-event-pad 0\n $ 2F mf.write.meta\n;\n\n: MF.END.TRACK ( startpos -- , write length to track beginning )\n mf.where dup>r ( so we can return )\n over - ( -- start #bytes )\n swap cell- mf.seek\n mf-pad be! mf-pad 4 mf.write?\n r> mf.seek\n;\n\n: MF.CVM+2D ( time d1 d2 cvm -- )\n mf-event-pad c!\n mf-event-pad 2+ c!\n mf-event-pad 1+ c!\n mf-event-pad 3 rot mf.write.event\n;\n\n: MF.WRITE.NOTEON ( time note velocity -- )\n $ 90 mf.cvm+2d\n;\n\n: MF.WRITE.NOTEOFF ( time note velocity -- )\n $ 80 mf.cvm+2d\n;\n\n: $MF.BEGIN.FORMAT0 ( $name -- pos , begin format0 file )\n $mf.create\n 0 1 ticks\/beat @ mf.write.header\n mf.begin.track ( startpos )\n;\n\n: MF.BEGIN.FORMAT0 ( -- pos , begin format0 file )\n fileword $mf.begin.format0\n;\n\n: MF.END.FORMAT0 ( pos -- , end format0 file )\n mf.write.end\n mf.end.track\n mf.close\n;\n\n: MF.WRITE.ABS.SHAPE { shape -- , assume shape Nx3+ absolute time }\n\\ Assume separate note on\/off in shape\n shape reset: []\n shape many: [] 0\n DO i 0 shape ed.at: [] ( -- time )\n i 1 shape ed.at: [] ( -- time note )\n i 2 shape ed.at: [] ( -- time note vel )\n dup 0=\n IF mf.write.noteoff\n ELSE mf.write.noteon\n THEN\n LOOP\n;\n\nvariable MF-SHAPE-TIME\n\n: MF.WRITE.REL.SHAPE { shape | note vel -- , assume shape Nx3 relative time }\n 0 mf-shape-time !\n shape reset: []\n shape many: [] 0\n DO\n i 1 shape ed.at: [] -> note ( -- time note )\n i 2 shape ed.at: [] -> vel ( -- time note vel )\n mf-shape-time @ note vel mf.write.noteon\n\\\n\\ add to shape time so OFF occurs right before next notes ON 00002\n i 0 shape ed.at: [] ( -- reltime )\n mf-shape-time @ +\n dup mf-shape-time !\n note vel mf.write.noteoff\n LOOP\n;\n\n: $SAVE.REL.SHAPE ( shape $filename -- , complete file output )\n\\ This word writes out a relative time, 1 event\/note shape\n\\ as note on,off\n $mf.begin.format0\n swap mf.write.rel.shape\n mf.end.format0\n;\n\n: $SAVE.ABS.SHAPE ( shape $filename -- , complete file output )\n\\ This word writes out a shape as note on,off\n $mf.begin.format0\n swap mf.write.abs.shape\n mf.end.format0\n;\n\n: SAVE.REL.SHAPE ( shape -- , complete file output )\n fileword $save.rel.shape\n;\n\n: SAVE.ABS.SHAPE ( shape -- , complete file output )\n fileword $save.abs.shape\n;\n\n: MF.WRITE.TIMESIG ( nn dd cc bb -- )\n mf-event-pad 3 + c! ( time sig, numerator )\n mf-event-pad 2+ c! ( denom log2 )\n mf-event-pad 1+ c! ( MIDI clocks\/metronome click )\n mf-event-pad c! ( 32nd notes in 24 clocks )\n mf-event-pad 4 $ 58 mf.write.meta\n;\n\n: MF.WRITE.TEMPO ( mics\/beat -- )\n mf-event-pad !\n mf-event-pad 1+ 3 $ 51 mf.write.meta\n;\n\n\\ Capture all MIDI output to a Format0 file\nvariable MF-START-POS\nvariable MF-FIRST-WRITE\n\n: (MF.CAPTURED>FILE0) ( -- write captured MIDI to file format 0)\n 0 0 ed.at: captured-midi mf-event-time !\n many: captured-midi 0\n DO i get: captured-midi midi.unpack\n rot mf.write.event\n LOOP\n mf-start-pos @ mf.end.format0\n;\n\n: }MIDIFILE0 ( -- )\n if-capturing @\n IF (mf.captured>file0)\n }capture\n THEN\n;\n\n: $CAPTURED>MIDIFILE0 ( $filename -- )\n $mf.begin.format0 mf-start-pos ! ( use filename while still valid )\n (mf.captured>file0)\n;\n\n: $MIDIFILE0{ ( $filename -- , start capturing MIDI data )\n }midifile0\n $mf.begin.format0 mf-start-pos ! ( use filename while still valid )\n capture{\n;\n\n: MIDIFILE0{ ( -- )\n fileword $midifile0{\n;\n\nCREATE MF-COUNT-CAPS 16 allot\n\n: CAP.GET.CHAN ( status-byte -- channel# )\n $ 0F and 1+\n;\n\n: CAP.COUNT.CHANS ( -- #channels , count captured track\/channels )\n 16 0\n DO 0 i mf-count-caps + c!\n LOOP\n\\\n many: captured-midi 0\n DO i get: captured-midi midi.unpack drop c@\n cap.get.chan 1-\n nip\n mf-count-caps + 1 swap c! ( set flag in array )\n LOOP\n\\\n 0\n 16 0\n DO i mf-count-caps + c@ +\n LOOP\n;\n\n: (MF.CAPTURED>FILE1) ( -- , write tracks with data to metafile )\n cap.count.chans ( #chans )\n \\ write a track zero that should contain tempo maps\n 1+ \\ for track zero\n mf.begin.track ( -- pos )\n mf.write.end\n mf.end.track\n \\ Write each track with sequence number\n 16 0\n DO i mf-count-caps + c@\n IF\n mf.begin.track ( -- pos )\n 0 0 ed.at: captured-midi mf-event-time !\n i 1+ mf.write.seq#\n many: captured-midi 0\n DO\n i get: captured-midi midi.unpack\n over c@ cap.get.chan 1- j = \\ 00001\n IF\n ( time addr count -- )\n rot mf.write.event\n ELSE 2drop drop\n THEN\n LOOP\n mf.write.end\n mf.end.track\n THEN\n LOOP\n 0 mf.seek\n 1 swap ticks\/beat @ mf.write.header\n mf.close\n;\n\n: }MIDIFILE1 ( -- )\n if-capturing @\n IF (mf.captured>file1)\n }capture\n THEN\n;\n\n: $CAPTURED>MIDIFILE1 ( $filename -- )\n $mf.create\n 1 1 ticks\/beat @ mf.write.header\n (mf.captured>file1)\n;\n\n: $MIDIFILE1{ ( $filename -- , start capturing MIDI data )\n }midifile1\n $mf.create\n 1 1 ticks\/beat @ mf.write.header\n capture{\n;\n\n: MIDIFILE1{ ( -- )\n fileword $midifile1{\n;\n\n\\ set aliases to format 0 for compatibility with old code\n: MIDIFILE{ midifile0{ ;\n: $MIDIFILE{ $midifile0{ ;\n: }MIDIFILE }midifile0 ;\n\nif.forgotten }midifile0\n\n\n: tmf\n \" testzz5.mid\" $midifile0{\n rnow 55 60 midi.noteon\n 200 vtime+!\n 55 0 midi.noteoff\n }midifile0\n;\n\n","old_contents":"\\ MIDI File Standard Support\n\\\n\\ This code allows the sharing of music data between applications.\n\\\n\\ Author: Phil Burk\n\\ Copyright 1989 Phil Burk\n\\\n\\ MOD: PLB 6\/11\/90 Added SWAP to $MF.LOAD.SHAPE\n\\ MOD: PLB 10\/23\/90 Added $MF.OPEN.VR\n\\ MOD: PLB 6\/91 Add MIDIFILE1{\n\\ 00001 PLB 9\/5\/91 Fix MIDIFILE1{ by c\/i\/j\/\n\\ 00002 PLB 3\/17\/92 Changed MF.WRITE.REL.SHAPE to make notes legato\n\\ for notation programs. Add $SAVE.REL.SHAPE and $..ABS..\n\nANEW TASK-MIDIFILE\ndecimal\n\n\\ Variable Length Number Conversion\nvariable VLN-PAD ( accumulator for variable length number )\nvariable VLN-COUNT ( number of bytes )\n\n: BYTE>VLN ( byte -- , add byte to VLN buffer )\n vln-count @ 0>\n IF $ 80 or ( set continuation bit )\n THEN\n vln-pad 4+ vln-count @ 1+ dup vln-count !\n - c!\n;\n\n: NUMBER->VLN ( N -- address count , convert )\n dup $ 0FFFFFFF >\n IF .\" NUMBER->VL - Number too big for MIDI File! = \"\n dup .hex cr\n $ 0FFFFFFF and\n THEN\n dup 0<\n IF .\" NUMBER->VL - Negative length or time! = \"\n dup .hex cr\n drop 0\n THEN\n vln-count off\n BEGIN dup $ 7F and byte>vln\n -7 shift dup 0=\n UNTIL drop\n vln-pad 4+ vln-count @ dup>r - r>\n;\n\n: VLN.CLEAR ( -- , clear for read )\n vln-count off vln-pad off\n;\n\n: VLN.ACCUM ( byte -- accumulate another byte )\n $ 7F and\n vln-pad @ 7 shift or vln-pad !\n;\n\n\\ -------------------------------------------------\nvariable MF-BYTESLEFT\nvariable MF-EVENT-TIME\nvariable MF-#DATA\n\n: CHKID ( -- , define chkid )\n 32 lword count drop be@ constant\n;\n\nchkid MThd 'MThd'\nchkid MTrk 'MTrk'\n\nvariable mf-FILEID\n16 constant MF_PAD_SIZE\nvariable mf-PAD mf_pad_size allot\n\nDEFER MF.PROCESS.TRACK ( size track# -- )\nDEFER MF.ERROR\n\n' abort is mf.error\n\n: .CHKID ( 'chkid' -- , print chunk id )\n pad be! pad 4 type\n;\n\n: $MF.OPEN ( $filename -- )\n dup c@ 0=\n IF drop .\" $MF.OPEN - No filename given!\" cr mf.error\n THEN\n dup count r\/o bin open-file\n IF drop .\" Couldn't open file: \" $type cr mf.error\n THEN\n mf-fileid !\n drop\n;\n\n: $MF.CREATE ( $filename -- , create new file )\n dup c@ 0=\n IF drop .\" $MF.OPEN - No filename given!\" cr mf.error\n THEN\n dup count w\/o bin create-file\n IF drop .\" Couldn't create file: \" $type cr mf.error\n THEN\n mf-fileid !\n drop\n;\n: MF.SET.FILE ( fileid -- )\n mf-fileid !\n;\n\n: MF.READ ( addr #bytes -- #bytes , read from open mf file)\n dup negate mf-bytesleft +!\n mf-fileid @ read-file abort\" Could not read MIDI file.\"\n;\n\n: MF.READ.CHKID ( -- size chkid )\n dup>r mf-pad 8 mf.read\n 8 -\n IF .\" Truncated chunk \" r@ .chkid cr mf.error\n THEN\n rdrop\n mf-pad cell+ be@\n mf-pad be@\n;\n\n\n: MF.WRITE ( addr #bytes -- #bytes , write to open mf file)\n dup>r mf-fileid @ write-file abort\" Could not write MIDI file.\"\n r>\n;\n\n: MF.WRITE? ( addr #bytes -- , write to open mf file or mf.ERROR)\n mf-fileid @ write-file abort\" Could not write MIDI file.\"\n;\n\n: MF.READ.BYTE ( -- byte )\n mf-pad 1 mf.read 1-\n IF .\" MF.READ.BYTE - Unexpected EOF!\" cr mf.error\n THEN\n mf-pad c@\n;\n\n: MF.WRITE.BYTE ( byte -- )\n mf-pad c! mf-pad 1 mf.write?\n;\n\n: MF.WRITE.WORD ( 16word -- )\n mf-pad w! mf-pad 2 mf.write?\n;\n\n: MF.READ.WORD ( -- 16word )\n mf-pad 2 mf.read 2-\n IF .\" MF.READ.WORD - Unexpected EOF!\" cr mf.error\n THEN\n mf-pad w@\n;\n\n: MF.WRITE.CHKID ( size chkid -- , write chunk header )\n mf-pad be!\n mf-pad cell+ be!\n mf-pad 8 mf.write?\n;\n\n: MF.WRITE.CHUNK ( address size chkid -- , write complete chunk )\n over >r mf.write.chkid\n r> mf.write?\n;\n\n: MF.READ.TYPE ( -- typeid )\n mf-pad 4 mf.read\n 4 -\n IF .\" Truncated type!\" cr mf.error\n THEN\n mf-pad be@\n;\n\n: MF.WHERE ( -- current_pos , in file )\n mf-fileid @ file-position abort\" file-position failed\"\n;\n\n: MF.SEEK ( position -- , in file )\n mf-fileid @ reposition-file abort\" reposition-file failed\"\n;\n\n: MF.SKIP ( n -- , skip n bytes in file )\n dup negate mf-bytesleft +!\n mf.where + mf.seek\n;\n\n: MF.CLOSE\n mf-fileid @ ?dup\n IF close-file abort\" close-file failed\"\n 0 mf-fileid !\n THEN\n;\n\nvariable MF-NTRKS \\ number of tracks in file\nvariable MF-FORMAT \\ file format = 0 | 1 | 2\nvariable MF-DIVISION \\ packed division\n\n: MF.PROCESS.HEADER ( size -- )\n dup mf_pad_size >\n IF .\" MF.PROCESS.HEADER - Bad Header Size = \"\n dup . cr mf.error\n THEN\n mf-pad swap mf.read drop\n mf-pad bew@ mf-format w!\n mf-pad 2+ bew@ mf-ntrks !\n mf-pad 4+ bew@ mf-division !\n;\n\n: MF.SCAN.HEADER ( -- , read header )\n mf.read.chkid ( -- size chkid)\n 'MThd' =\n IF mf.process.header\n ELSE .\" MF.SCAN - Headerless MIDIFile!\" cr mf.error\n THEN\n;\n\n: MF.SCAN.TRACKS ( -- , read tracks )\n\\ This word leaves the file position just after the chunk data.\n mf-ntrks @ 0\n DO mf.read.chkid 'MTrk' =\n IF dup mf.where + >r\n i mf.process.track\n r> mf.seek ( move past chunk)\n ELSE .\" MF.SCAN - Unexpected CHKID!\" cr mf.error\n THEN\n LOOP\n;\n\n: MF.SCAN ( -- , read header then tracks)\n mf.scan.header\n mf.scan.tracks\n;\n\n: MF.VALIDATE ( -- ok? , make sure open file has header chunk )\n mf.where\n 0 mf.seek\n mf.read.type 'MThd' =\n swap mf.seek\n;\n\n: (MF.DOFILE) ( -- ,process current file )\n mf.validate\n IF mf.scan\n ELSE .\" Not a MIDIFile!\" cr\n mf.close mf.error\n THEN\n mf.close\n;\n\n: $MF.DOFILE ( $filename -- , process file using deferred words)\n $mf.open (mf.dofile)\n;\n\n: MF.DOFILE ( -- )\n fileword $mf.dofile\n;\n\n: MF.READ.VLN ( -- vln , read vln from file )\n vln.clear\n BEGIN mf.read.byte dup $ 80 and\n WHILE vln.accum\n REPEAT vln.accum\n vln-pad @\n;\n\ndefer MF.PROCESS.META ( size metaID -- , process Meta event )\ndefer MF.PROCESS.SYSEX\ndefer MF.PROCESS.ESCAPE\n\nvariable MF-SEQUENCE#\nvariable MF-CHANNEL\n: MF.LOOK.TEXT ( size metaID -- , read and show text )\n >newline .\" MetaEvent = \" . cr\n pad swap mf.read\n pad swap type cr\n;\n\n: MF.HANDLE.META ( size MetaID -- default Meta event handler )\n dup $ 01 $ 0f within?\n IF mf.look.text\n ELSE CASE\n $ 00 OF drop mf.read.word mf-sequence# ! ENDOF\n $ 20 OF drop mf.read.byte 1+ mf-channel ! ENDOF\n .\" MetaEvent = \" dup . cr\n swap mf.skip ( skip over other event types )\n ENDCASE\n THEN\n;\n\n' mf.handle.meta is MF.PROCESS.META\n' mf.skip is MF.PROCESS.SYSEX\n' mf.skip is MF.PROCESS.ESCAPE\n\n: MF.PARSE.EVENT ( -- , parse MIDI event )\n mf.read.byte dup $ 80 and ( is it a command or running status data )\n IF CASE\n $ FF OF mf.read.byte ( get type )\n mf.read.vln ( get size ) swap mf.process.meta ENDOF\n $ F0 OF .\" F0 byte\" cr mf.read.vln mf.process.sysex ENDOF\n $ F7 OF .\" F7 byte\" cr mf.read.vln mf.process.escape ENDOF\n\\ Regular command.\n dup mp.#bytes mf-#data !\n dup mp.handle.command\n mf-#data @ 0\n DO mf.read.byte mp.handle.data\n LOOP\n ENDCASE\n ELSE \n mp.handle.data ( call MIDI parser with byte read )\n mf-#data @ 1- 0 max 0\n DO mf.read.byte mp.handle.data\n LOOP\n THEN\n;\n\n: MF.PARSE.TRACK ( size track# -- )\n drop mf-bytesleft !\n 0 mf-event-time !\n BEGIN mf.read.vln mf-event-time +!\n mf.parse.event\n mf-bytesleft @ 1 <\n UNTIL\n;\n\n\\ Some Track Handlers\n: MF.PRINT.NOTEON ( note velocity -- )\n ?pause\n mf-event-time @ 4 .r .\" , \"\n .\" ON N,V = \" swap . . cr\n;\n: MF.PRINT.NOTEOFF ( note velocity -- )\n ?pause\n mf-event-time @ 4 .r .\" , \"\n .\" OFF N,V = \" swap . . cr\n;\n\n: MF.PRINT.TRACK ( size track# -- )\n 2dup\n >newline dup 0=\n IF .\" MIDIFile Format = \" mf-format @ . cr\n .\" Division = $\" mf-division @ dup .hex . cr\n THEN\n .\" Track# \" . .\" is \" . .\" bytes.\" cr\n 'c mf.print.noteon mp-on-vector !\n 'c mf.print.noteoff mp-off-vector !\n mf.parse.track\n mp.reset\n;\n\n' mf.print.track is mf.process.track\n\n: MF.CHECK ( -- , print chunks )\n what's mf.process.track\n ' mf.print.track is mf.process.track\n mf.dofile\n is mf.process.track\n;\n\n\\ Track Handler that loads a shape -----------------------\nvariable MF-TRACK-CHOSEN\nob.shape MF-SHAPE\n\n: MF.LOAD.NOTEON ( note velocity -- )\n mf-shape ensure.room\n mf-event-time @ -rot add: mf-shape\n;\n\n: MF.LOAD.NOTEOFF ( note velocity -- )\n mf-shape ensure.room\n drop mf-event-time @ swap 0 add: mf-shape\n;\n\n: MF.LOAD.TRACK ( size track# -- )\n max.elements: mf-shape 0=\n IF 64 3 new: mf-shape\n ELSE clear: mf-shape\n THEN\n 'c mf.load.noteon mp-on-vector !\n 'c mf.load.noteoff mp-off-vector !\n mf.parse.track\n;\n\n: MF.PICK.TRACK ( size track# -- )\n dup mf-track-chosen @ =\n IF mf.load.track\n ELSE 2drop\n THEN\n;\n\n: $MF.LOAD.SHAPE ( track# $filename -- , load track into mf-shape )\n swap mf-track-chosen !\n what's mf.process.track SWAP ( -- oldcfa $filename )\n 'c mf.pick.track is mf.process.track\n $mf.dofile\n is mf.process.track\n;\n\n: MF.LOAD.SHAPE ( track# -- , load track into mf-shape )\n fileword $mf.load.shape\n;\n\n: LOAD.ABS.SHAPE ( shape -- )\n 0 mf.load.shape\n clone: mf-shape\n free: mf-shape\n;\n\n\\ -------------------------------------------------\n\n\\ Tools for writing a MIDIFile.\n: MF.WRITE.HEADER ( format ntrks division -- )\n 6 'MThd' mf.write.chkid\n mf-pad 4+ bew! ( division )\n over 0=\n IF drop 1 ( force NTRKS to 1 for format zero )\n THEN\n mf-pad 2+ bew! ( ntrks )\n mf-pad bew! ( format )\n mf-pad 6 mf.write?\n;\n\n: MF.BEGIN.TRACK ( -- curpos , write track start )\n 0 'MTrk' mf.write.chkid\n mf.where\n 0 mf-event-time !\n;\n\n: MF.WRITE.VLN ( n -- , write variable length quantity )\n number->vln mf.write?\n;\n\n: MF.WRITE.TIME ( time -- , write time as vln delta )\n dup mf-event-time @ - mf.write.vln\n mf-event-time !\n;\n\n: MF.WRITE.EVENT ( addr count time -- , write MIDI event )\n\\ This might be called from custom MIDI.FLUSH\n mf.write.time\n mf.write?\n;\n\nvariable MF-EVENT-PAD\n\n: MF.WRITE.META ( addr count event-type -- )\n mf-event-time @ mf.write.time\n $ FF mf.write.byte\n mf.write.byte ( event type )\n dup mf.write.vln ( len )\n mf.write?\n;\n\n: MF.WRITE.SYSEX ( addr count -- )\n mf-event-time @ mf.write.time\n $ F0 mf.write.byte\n dup mf.write.vln ( len )\n mf.write?\n;\n\n: MF.WRITE.ESCAPE ( addr count -- )\n mf-event-time @ mf.write.time\n $ F7 mf.write.byte\n dup mf.write.vln ( len )\n mf.write?\n;\n\n: MF.WRITE.SEQ# ( seq# -- )\n mf-event-pad w!\n mf-event-pad 2 0 mf.write.meta\n;\n\n: MF.WRITE.END ( -- , write end of track )\n mf-event-pad 0\n $ 2F mf.write.meta\n;\n\n: MF.END.TRACK ( startpos -- , write length to track beginning )\n mf.where dup>r ( so we can return )\n over - ( -- start #bytes )\n swap cell- mf.seek\n mf-pad be! mf-pad 4 mf.write?\n r> mf.seek\n;\n\n: MF.CVM+2D ( time d1 d2 cvm -- )\n mf-event-pad c!\n mf-event-pad 2+ c!\n mf-event-pad 1+ c!\n mf-event-pad 3 rot mf.write.event\n;\n\n: MF.WRITE.NOTEON ( time note velocity -- )\n $ 90 mf.cvm+2d\n;\n\n: MF.WRITE.NOTEOFF ( time note velocity -- )\n $ 80 mf.cvm+2d\n;\n\n: $MF.BEGIN.FORMAT0 ( $name -- pos , begin format0 file )\n $mf.create\n 0 1 ticks\/beat @ mf.write.header\n mf.begin.track ( startpos )\n;\n\n: MF.BEGIN.FORMAT0 ( -- pos , begin format0 file )\n fileword $mf.begin.format0\n;\n\n: MF.END.FORMAT0 ( pos -- , end format0 file )\n mf.write.end\n mf.end.track\n mf.close\n;\n\n: MF.WRITE.ABS.SHAPE { shape -- , assume shape Nx3+ absolute time }\n\\ Assume separate note on\/off in shape\n shape reset: []\n shape many: [] 0\n DO i 0 shape ed.at: [] ( -- time )\n i 1 shape ed.at: [] ( -- time note )\n i 2 shape ed.at: [] ( -- time note vel )\n dup 0=\n IF mf.write.noteoff\n ELSE mf.write.noteon\n THEN\n LOOP\n;\n\nvariable MF-SHAPE-TIME\n\n: MF.WRITE.REL.SHAPE { shape | note vel -- , assume shape Nx3 relative time }\n 0 mf-shape-time !\n shape reset: []\n shape many: [] 0\n DO\n i 1 shape ed.at: [] -> note ( -- time note )\n i 2 shape ed.at: [] -> vel ( -- time note vel )\n mf-shape-time @ note vel mf.write.noteon\n\\\n\\ add to shape time so OFF occurs right before next notes ON 00002\n i 0 shape ed.at: [] ( -- reltime )\n mf-shape-time @ +\n dup mf-shape-time !\n note vel mf.write.noteoff\n LOOP\n;\n\n: $SAVE.REL.SHAPE ( shape $filename -- , complete file output )\n\\ This word writes out a relative time, 1 event\/note shape\n\\ as note on,off\n $mf.begin.format0\n swap mf.write.rel.shape\n mf.end.format0\n;\n\n: $SAVE.ABS.SHAPE ( shape $filename -- , complete file output )\n\\ This word writes out a shape as note on,off\n $mf.begin.format0\n swap mf.write.abs.shape\n mf.end.format0\n;\n\n: SAVE.REL.SHAPE ( shape -- , complete file output )\n fileword $save.rel.shape\n;\n\n: SAVE.ABS.SHAPE ( shape -- , complete file output )\n fileword $save.abs.shape\n;\n\n: MF.WRITE.TIMESIG ( nn dd cc bb -- )\n mf-event-pad 3 + c! ( time sig, numerator )\n mf-event-pad 2+ c! ( denom log2 )\n mf-event-pad 1+ c! ( MIDI clocks\/metronome click )\n mf-event-pad c! ( 32nd notes in 24 clocks )\n mf-event-pad 4 $ 58 mf.write.meta\n;\n \n: MF.WRITE.TEMPO ( mics\/beat -- )\n mf-event-pad !\n mf-event-pad 1+ 3 $ 51 mf.write.meta\n;\n\n\\ Capture all MIDI output to a Format0 file\nvariable MF-START-POS\nvariable MF-FIRST-WRITE\n\n: (MF.CAPTURED>FILE0) ( -- write captured MIDI to file format 0)\n 0 0 ed.at: captured-midi mf-event-time !\n many: captured-midi 0\n DO i get: captured-midi midi.unpack\n rot mf.write.event\n LOOP\n mf-start-pos @ mf.end.format0\n;\n\n: }MIDIFILE0 ( -- )\n if-capturing @\n IF (mf.captured>file0)\n }capture\n THEN\n;\n\n: $CAPTURED>MIDIFILE0 ( $filename -- )\n $mf.begin.format0 mf-start-pos ! ( use filename while still valid )\n (mf.captured>file0)\n;\n\n: $MIDIFILE0{ ( $filename -- , start capturing MIDI data )\n }midifile0\n $mf.begin.format0 mf-start-pos ! ( use filename while still valid )\n capture{\n;\n\n: MIDIFILE0{ ( -- )\n fileword $midifile0{\n;\n\nCREATE MF-COUNT-CAPS 16 allot\n\n: CAP.GET.CHAN ( status-byte -- channel# )\n $ 0F and 1+\n;\n\n: CAP.COUNT.CHANS ( -- #channels , count captured track\/channels )\n 16 0\n DO 0 i mf-count-caps + c!\n LOOP\n\\\n many: captured-midi 0\n DO i get: captured-midi midi.unpack drop c@\n cap.get.chan 1-\n nip\n mf-count-caps + 1 swap c! ( set flag in array )\n LOOP\n\\\n 0\n 16 0\n DO i mf-count-caps + c@ +\n LOOP\n;\n\n: (MF.CAPTURED>FILE1) ( -- , write tracks with data to metafile )\n cap.count.chans ( #chans )\n \\ write a track zero that should contain tempo maps\n 1+ \\ for track zero\n mf.begin.track ( -- pos )\n mf.write.end\n mf.end.track\n \\ Write each track with sequence number\n 16 0\n DO i mf-count-caps + c@\n IF\n mf.begin.track ( -- pos )\n 0 0 ed.at: captured-midi mf-event-time !\n i 1+ mf.write.seq#\n many: captured-midi 0\n DO\n i get: captured-midi midi.unpack\n over c@ cap.get.chan 1- j = \\ 00001\n IF\n ( time addr count -- )\n rot mf.write.event\n ELSE 2drop drop\n THEN\n LOOP\n mf.write.end\n mf.end.track\n THEN\n LOOP\n 0 mf.seek\n 1 swap ticks\/beat @ mf.write.header\n mf.close\n;\n\n: }MIDIFILE1 ( -- )\n if-capturing @\n IF (mf.captured>file1)\n }capture\n THEN\n;\n\n: $CAPTURED>MIDIFILE1 ( $filename -- )\n $mf.create\n 1 1 ticks\/beat @ mf.write.header\n (mf.captured>file1)\n;\n\n: $MIDIFILE1{ ( $filename -- , start capturing MIDI data )\n }midifile1\n $mf.create\n 1 1 ticks\/beat @ mf.write.header\n capture{\n;\n\n: MIDIFILE1{ ( -- )\n fileword $midifile1{\n;\n\n\\ set aliases to format 0 for compatibility with old code\n: MIDIFILE{ midifile0{ ;\n: $MIDIFILE{ $midifile0{ ;\n: }MIDIFILE }midifile0 ;\n\nif.forgotten }midifile0\n\n\n: tmf\n \" testzz5.mid\" $midifile0{\n rnow 55 60 midi.noteon\n 200 vtime+!\n 55 0 midi.noteoff\n }midifile0\n;\n\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Forth"} {"commit":"f0722371f719069f3d53d9bd88ba691ee0f1a4b4","subject":"Fix for 32-bit ism in core test","message":"Fix for 32-bit ism in core test\n","repos":"GuzTech\/swapforth,GuzTech\/swapforth,zuloloxi\/swapforth,uho\/swapforth,jamesbowman\/swapforth,RGD2\/swapforth,RGD2\/swapforth,zuloloxi\/swapforth,GuzTech\/swapforth,GuzTech\/swapforth,jamesbowman\/swapforth,uho\/swapforth,RGD2\/swapforth,zuloloxi\/swapforth,jamesbowman\/swapforth,zuloloxi\/swapforth,uho\/swapforth,uho\/swapforth,jamesbowman\/swapforth,RGD2\/swapforth","old_file":"anstests\/coreplustest.fth","new_file":"anstests\/coreplustest.fth","new_contents":"\\ Additional tests on the the ANS Forth Core word set\r\n\r\n\\ This program was written by Gerry Jackson in 2007, with contributions from\r\n\\ others where indicated, and is in the public domain - it can be distributed\r\n\\ and\/or modified in any way but please retain this notice.\r\n\r\n\\ This program is distributed in the hope that it will be useful,\r\n\\ but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n\\ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\r\n\r\n\\ The tests are not claimed to be comprehensive or correct \r\n\r\n\\ ------------------------------------------------------------------------------\r\n\\ Version 0.11 25 April 2015 Number prefixes # $ % and 'c' character input tested\r\n\\ 0.10 3 August 2014 Test IMMEDIATE doesn't toggle an immediate flag\r\n\\ 0.3 1 April 2012 Tests placed in the public domain.\r\n\\ Testing multiple ELSE's.\r\n\\ Further tests on DO +LOOPs.\r\n\\ Ackermann function added to test RECURSE.\r\n\\ >IN manipulation in interpreter mode\r\n\\ Immediate CONSTANTs, VARIABLEs and CREATEd words tests.\r\n\\ :NONAME with RECURSE moved to core extension tests.\r\n\\ Parsing behaviour of S\" .\" and ( tested\r\n\\ 0.2 6 March 2009 { and } replaced with T{ and }T\r\n\\ Added extra RECURSE tests\r\n\\ 0.1 20 April 2007 Created\r\n\\ ------------------------------------------------------------------------------\r\n\\ The tests are based on John Hayes test program for the core word set\r\n\\\r\n\\ This file provides some more tests on Core words where the original Hayes\r\n\\ tests are thought to be incomplete\r\n\\\r\n\\ Words tested in this file are:\r\n\\ DO +LOOP RECURSE ELSE >IN IMMEDIATE\r\n\\ ------------------------------------------------------------------------------\r\n\\ Assumptions and dependencies:\r\n\\ - tester.fr or ttester.fs has been loaded prior to this file\r\n\\ - core.fr has been loaded so that constants MAX-INT, MIN-INT and\r\n\\ MAX-UINT are defined\r\n\\ ------------------------------------------------------------------------------\r\n\r\nDECIMAL\r\n\r\nTESTING DO +LOOP with run-time increment, negative increment, infinite loop\r\n\\ Contributed by Reinhold Straub\r\n\r\nVARIABLE ITERATIONS\r\nVARIABLE INCREMENT\r\n: GD7 ( LIMIT START INCREMENT -- )\r\n INCREMENT !\r\n 0 ITERATIONS !\r\n DO\r\n 1 ITERATIONS +!\r\n I\r\n ITERATIONS @ 6 = IF LEAVE THEN\r\n INCREMENT @\r\n +LOOP ITERATIONS @\r\n;\r\n\r\nT{ 4 4 -1 GD7 -> 4 1 }T\r\nT{ 1 4 -1 GD7 -> 4 3 2 1 4 }T\r\nT{ 4 1 -1 GD7 -> 1 0 -1 -2 -3 -4 6 }T\r\nT{ 4 1 0 GD7 -> 1 1 1 1 1 1 6 }T\r\nT{ 0 0 0 GD7 -> 0 0 0 0 0 0 6 }T\r\nT{ 1 4 0 GD7 -> 4 4 4 4 4 4 6 }T\r\nT{ 1 4 1 GD7 -> 4 5 6 7 8 9 6 }T\r\nT{ 4 1 1 GD7 -> 1 2 3 3 }T\r\nT{ 4 4 1 GD7 -> 4 5 6 7 8 9 6 }T\r\nT{ 2 -1 -1 GD7 -> -1 -2 -3 -4 -5 -6 6 }T\r\nT{ -1 2 -1 GD7 -> 2 1 0 -1 4 }T\r\nT{ 2 -1 0 GD7 -> -1 -1 -1 -1 -1 -1 6 }T\r\nT{ -1 2 0 GD7 -> 2 2 2 2 2 2 6 }T\r\nT{ -1 2 1 GD7 -> 2 3 4 5 6 7 6 }T\r\nT{ 2 -1 1 GD7 -> -1 0 1 3 }T\r\nT{ -20 30 -10 GD7 -> 30 20 10 0 -10 -20 6 }T\r\nT{ -20 31 -10 GD7 -> 31 21 11 1 -9 -19 6 }T\r\nT{ -20 29 -10 GD7 -> 29 19 9 -1 -11 5 }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING DO +LOOP with large and small increments\r\n\r\n\\ Contributed by Andrew Haley\r\n\r\nMAX-UINT 8 RSHIFT 1+ CONSTANT USTEP\r\nUSTEP NEGATE CONSTANT -USTEP\r\nMAX-INT 7 RSHIFT 1+ CONSTANT STEP\r\nSTEP NEGATE CONSTANT -STEP\r\n\r\nVARIABLE BUMP\r\n\r\nT{ : GD8 BUMP ! DO 1+ BUMP @ +LOOP ; -> }T\r\n\r\nT{ 0 MAX-UINT 0 USTEP GD8 -> 256 }T\r\nT{ 0 0 MAX-UINT -USTEP GD8 -> 256 }T\r\n\r\nT{ 0 MAX-INT MIN-INT STEP GD8 -> 256 }T\r\nT{ 0 MIN-INT MAX-INT -STEP GD8 -> 256 }T\r\n\r\n\\ Two's complement arithmetic, wraps around modulo wordsize\r\n\\ Only tested if the Forth system does wrap around, use of conditional\r\n\\ compilation deliberately avoided\r\n\r\nMAX-INT 1+ MIN-INT = CONSTANT +WRAP?\r\nMIN-INT 1- MAX-INT = CONSTANT -WRAP?\r\nMAX-UINT 1+ 0= CONSTANT +UWRAP?\r\n0 1- MAX-UINT = CONSTANT -UWRAP?\r\n\r\n: GD9 ( n limit start step f result -- )\r\n >R IF GD8 ELSE 2DROP 2DROP R@ THEN -> R> }T\r\n;\r\n\r\nT{ 0 0 0 USTEP +UWRAP? 256 GD9\r\nT{ 0 0 0 -USTEP -UWRAP? 1 GD9\r\nT{ 0 MIN-INT MAX-INT STEP +WRAP? 1 GD9\r\nT{ 0 MAX-INT MIN-INT -STEP -WRAP? 1 GD9\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING DO +LOOP with maximum and minimum increments\r\n\r\n: (-MI) MAX-INT DUP NEGATE + 0= IF MAX-INT NEGATE ELSE -32767 THEN ;\r\n(-MI) CONSTANT -MAX-INT\r\n\r\nT{ 0 1 0 MAX-INT GD8 -> 1 }T\r\nT{ 0 -MAX-INT NEGATE -MAX-INT OVER GD8 -> 2 }T\r\n\r\nT{ 0 MAX-INT 0 MAX-INT GD8 -> 1 }T\r\nT{ 0 MAX-INT 1 MAX-INT GD8 -> 1 }T\r\nT{ 0 MAX-INT -1 MAX-INT GD8 -> 2 }T\r\nT{ 0 MAX-INT DUP 1- MAX-INT GD8 -> 1 }T\r\n\r\nT{ 0 MIN-INT 1+ 0 MIN-INT GD8 -> 1 }T\r\nT{ 0 MIN-INT 1+ -1 MIN-INT GD8 -> 1 }T\r\nT{ 0 MIN-INT 1+ 1 MIN-INT GD8 -> 2 }T\r\nT{ 0 MIN-INT 1+ DUP MIN-INT GD8 -> 1 }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING multiple RECURSEs in one colon definition\r\n\r\n: ACK ( m n -- u ) \\ Ackermann function, from Rosetta Code\r\n OVER 0= IF NIP 1+ EXIT THEN \\ ack(0, n) = n+1\r\n SWAP 1- SWAP ( -- m-1 n )\r\n DUP 0= IF 1+ RECURSE EXIT THEN \\ ack(m, 0) = ack(m-1, 1)\r\n 1- OVER 1+ SWAP RECURSE RECURSE \\ ack(m, n) = ack(m-1, ack(m,n-1))\r\n;\r\n\r\nT{ 0 0 ACK -> 1 }T\r\nT{ 3 0 ACK -> 5 }T\r\nT{ 2 4 ACK -> 11 }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING multiple ELSE's in an IF statement\r\n\\ Discussed on comp.lang.forth and accepted as valid ANS Forth\r\n\r\n: MELSE IF 1 ELSE 2 ELSE 3 ELSE 4 ELSE 5 THEN ;\r\nT{ 0 MELSE -> 2 4 }T\r\nT{ -1 MELSE -> 1 3 5 }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING manipulation of >IN in interpreter mode\r\n\r\n.( Start ) cr\r\nT{ 12345 DEPTH OVER 9 < 34 AND + 3 + >IN ! -> 12345 2345 345 45 5 }T\r\nT{ 14145 8115 ?DUP 0= 34 AND >IN +! TUCK MOD 14 >IN ! GCD CALCULATION -> 15 }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING IMMEDIATE with CONSTANT VARIABLE and CREATE [ ... DOES> ]\r\n\r\nT{ 123 CONSTANT IW1 IMMEDIATE IW1 -> 123 }T\r\nT{ : IW2 IW1 LITERAL ; IW2 -> 123 }T\r\nT{ VARIABLE IW3 IMMEDIATE 234 IW3 ! IW3 @ -> 234 }T\r\nT{ : IW4 IW3 [ @ ] LITERAL ; IW4 -> 234 }T\r\nT{ :NONAME [ 345 ] IW3 [ ! ] ; DROP IW3 @ -> 345 }T\r\nT{ CREATE IW5 456 , IMMEDIATE -> }T\r\nT{ :NONAME IW5 [ @ IW3 ! ] ; DROP IW3 @ -> 456 }T\r\nT{ : IW6 CREATE , IMMEDIATE DOES> @ 1+ ; -> }T\r\nT{ 111 IW6 IW7 IW7 -> 112 }T\r\nT{ : IW8 IW7 LITERAL 1+ ; IW8 -> 113 }T\r\nT{ : IW9 CREATE , DOES> @ 2 + IMMEDIATE ; -> }T\r\n: FIND-IW BL WORD FIND NIP ; ( -- 0 | 1 | -1 )\r\nT{ 222 IW9 IW10 FIND-IW IW10 -> -1 }T \\ IW10 is not immediate\r\nT{ IW10 FIND-IW IW10 -> 224 1 }T \\ IW10 becomes immediate\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING that IMMEDIATE doesn't toggle a flag\r\n\r\nVARIABLE IT1 0 IT1 !\r\n: IT2 1234 IT1 ! ; IMMEDIATE IMMEDIATE\r\nT{ : IT3 IT2 ; IT1 @ -> 1234 }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING parsing behaviour of S\" .\" and (\r\n\\ which should parse to just beyond the terminating character no space needed\r\n\r\nT{ : GC5 S\" A string\"2DROP ; GC5 -> }T\r\nT{ ( A comment)1234 -> 1234 }T\r\nT{ : PB1 CR .\" You should see 2345: \".\" 2345\"( A comment) CR ; PB1 -> }T\r\n \r\n\\ ------------------------------------------------------------------------------\r\nTESTING number prefixes # $ % and 'c' character input\r\n\\ Adapted from the Forth 200X Draft 14.5 document\r\n\r\nVARIABLE OLD-BASE\r\nDECIMAL BASE @ OLD-BASE !\r\nT{ #1289 -> 1289 }T\r\nT{ #12346789. -> 12346789. }T\r\nT{ #-1289 -> -1289 }T\r\nT{ #-12346789. -> -12346789. }T\r\nT{ $12eF -> 4847 }T\r\nT{ $12aBcDeF. -> 313249263. }T\r\nT{ $-12eF -> -4847 }T\r\nT{ $-12AbCdEf. -> -313249263. }T\r\nT{ %10010110 -> 150 }T\r\nT{ %10010110. -> 150. }T\r\nT{ %-10010110 -> -150 }T\r\nT{ %-10010110. -> -150. }T\r\nT{ 'z' -> 122 }T\r\n\\ Check BASE is unchanged\r\nT{ BASE @ OLD-BASE @ = -> TRUE }T\r\n\r\n\\ Repeat in Hex mode\r\n16 OLD-BASE ! 16 BASE !\r\nT{ #1289 -> 509 }T \\ 2\r\nT{ #12346789. -> BC65A5. }T \\ 2\r\nT{ #-1289 -> -509 }T \\ 2\r\nT{ #-12346789. -> -BC65A5. }T \\ 2\r\nT{ $12eF -> 12EF }T \\ 2\r\nT{ $12aBcDeF. -> 12AbCdeF. }T \\ 2\r\nT{ $-12eF -> -12EF }T \\ 2\r\nT{ $-12AbCdEf. -> -12ABCDef. }T \\ 2\r\nT{ %10010110 -> 96 }T \\ 2\r\nT{ %10010110. -> 96. }T \\ 2\r\nT{ %-10010110 -> -96 }T \\ 2\r\nT{ %-10010110. -> -96. }T \\ 2\r\nT{ 'z' -> 7a }T \\ 2\r\n\\ Check BASE is unchanged\r\nT{ BASE @ OLD-BASE @ = -> TRUE }T \\ 2\r\n\r\nDECIMAL\r\n\\ Check number prefixes in compile mode\r\nT{ : nmp #8327. $-2cbe %011010111 ''' ; nmp -> 8327. -11454 215 39 }T\r\n\r\n\r\n\\ ------------------------------------------------------------------------------\r\n\r\nCR .( End of additional Core tests) CR\r\n","old_contents":"\\ Additional tests on the the ANS Forth Core word set\r\n\r\n\\ This program was written by Gerry Jackson in 2007, with contributions from\r\n\\ others where indicated, and is in the public domain - it can be distributed\r\n\\ and\/or modified in any way but please retain this notice.\r\n\r\n\\ This program is distributed in the hope that it will be useful,\r\n\\ but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n\\ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\r\n\r\n\\ The tests are not claimed to be comprehensive or correct \r\n\r\n\\ ------------------------------------------------------------------------------\r\n\\ Version 0.11 25 April 2015 Number prefixes # $ % and 'c' character input tested\r\n\\ 0.10 3 August 2014 Test IMMEDIATE doesn't toggle an immediate flag\r\n\\ 0.3 1 April 2012 Tests placed in the public domain.\r\n\\ Testing multiple ELSE's.\r\n\\ Further tests on DO +LOOPs.\r\n\\ Ackermann function added to test RECURSE.\r\n\\ >IN manipulation in interpreter mode\r\n\\ Immediate CONSTANTs, VARIABLEs and CREATEd words tests.\r\n\\ :NONAME with RECURSE moved to core extension tests.\r\n\\ Parsing behaviour of S\" .\" and ( tested\r\n\\ 0.2 6 March 2009 { and } replaced with T{ and }T\r\n\\ Added extra RECURSE tests\r\n\\ 0.1 20 April 2007 Created\r\n\\ ------------------------------------------------------------------------------\r\n\\ The tests are based on John Hayes test program for the core word set\r\n\\\r\n\\ This file provides some more tests on Core words where the original Hayes\r\n\\ tests are thought to be incomplete\r\n\\\r\n\\ Words tested in this file are:\r\n\\ DO +LOOP RECURSE ELSE >IN IMMEDIATE\r\n\\ ------------------------------------------------------------------------------\r\n\\ Assumptions and dependencies:\r\n\\ - tester.fr or ttester.fs has been loaded prior to this file\r\n\\ - core.fr has been loaded so that constants MAX-INT, MIN-INT and\r\n\\ MAX-UINT are defined\r\n\\ ------------------------------------------------------------------------------\r\n\r\nDECIMAL\r\n\r\nTESTING DO +LOOP with run-time increment, negative increment, infinite loop\r\n\\ Contributed by Reinhold Straub\r\n\r\nVARIABLE ITERATIONS\r\nVARIABLE INCREMENT\r\n: GD7 ( LIMIT START INCREMENT -- )\r\n INCREMENT !\r\n 0 ITERATIONS !\r\n DO\r\n 1 ITERATIONS +!\r\n I\r\n ITERATIONS @ 6 = IF LEAVE THEN\r\n INCREMENT @\r\n +LOOP ITERATIONS @\r\n;\r\n\r\nT{ 4 4 -1 GD7 -> 4 1 }T\r\nT{ 1 4 -1 GD7 -> 4 3 2 1 4 }T\r\nT{ 4 1 -1 GD7 -> 1 0 -1 -2 -3 -4 6 }T\r\nT{ 4 1 0 GD7 -> 1 1 1 1 1 1 6 }T\r\nT{ 0 0 0 GD7 -> 0 0 0 0 0 0 6 }T\r\nT{ 1 4 0 GD7 -> 4 4 4 4 4 4 6 }T\r\nT{ 1 4 1 GD7 -> 4 5 6 7 8 9 6 }T\r\nT{ 4 1 1 GD7 -> 1 2 3 3 }T\r\nT{ 4 4 1 GD7 -> 4 5 6 7 8 9 6 }T\r\nT{ 2 -1 -1 GD7 -> -1 -2 -3 -4 -5 -6 6 }T\r\nT{ -1 2 -1 GD7 -> 2 1 0 -1 4 }T\r\nT{ 2 -1 0 GD7 -> -1 -1 -1 -1 -1 -1 6 }T\r\nT{ -1 2 0 GD7 -> 2 2 2 2 2 2 6 }T\r\nT{ -1 2 1 GD7 -> 2 3 4 5 6 7 6 }T\r\nT{ 2 -1 1 GD7 -> -1 0 1 3 }T\r\nT{ -20 30 -10 GD7 -> 30 20 10 0 -10 -20 6 }T\r\nT{ -20 31 -10 GD7 -> 31 21 11 1 -9 -19 6 }T\r\nT{ -20 29 -10 GD7 -> 29 19 9 -1 -11 5 }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING DO +LOOP with large and small increments\r\n\r\n\\ Contributed by Andrew Haley\r\n\r\nMAX-UINT 8 RSHIFT 1+ CONSTANT USTEP\r\nUSTEP NEGATE CONSTANT -USTEP\r\nMAX-INT 7 RSHIFT 1+ CONSTANT STEP\r\nSTEP NEGATE CONSTANT -STEP\r\n\r\nVARIABLE BUMP\r\n\r\nT{ : GD8 BUMP ! DO 1+ BUMP @ +LOOP ; -> }T\r\n\r\nT{ 0 MAX-UINT 0 USTEP GD8 -> 256 }T\r\nT{ 0 0 MAX-UINT -USTEP GD8 -> 256 }T\r\n\r\nT{ 0 MAX-INT MIN-INT STEP GD8 -> 256 }T\r\nT{ 0 MIN-INT MAX-INT -STEP GD8 -> 256 }T\r\n\r\n\\ Two's complement arithmetic, wraps around modulo wordsize\r\n\\ Only tested if the Forth system does wrap around, use of conditional\r\n\\ compilation deliberately avoided\r\n\r\nMAX-INT 1+ MIN-INT = CONSTANT +WRAP?\r\nMIN-INT 1- MAX-INT = CONSTANT -WRAP?\r\nMAX-UINT 1+ 0= CONSTANT +UWRAP?\r\n0 1- MAX-UINT = CONSTANT -UWRAP?\r\n\r\n: GD9 ( n limit start step f result -- )\r\n >R IF GD8 ELSE 2DROP 2DROP R@ THEN -> R> }T\r\n;\r\n\r\nT{ 0 0 0 USTEP +UWRAP? 256 GD9\r\nT{ 0 0 0 -USTEP -UWRAP? 1 GD9\r\nT{ 0 MIN-INT MAX-INT STEP +WRAP? 1 GD9\r\nT{ 0 MAX-INT MIN-INT -STEP -WRAP? 1 GD9\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING DO +LOOP with maximum and minimum increments\r\n\r\n: (-MI) MAX-INT DUP NEGATE + 0= IF MAX-INT NEGATE ELSE -32767 THEN ;\r\n(-MI) CONSTANT -MAX-INT\r\n\r\nT{ 0 1 0 MAX-INT GD8 -> 1 }T\r\nT{ 0 -MAX-INT NEGATE -MAX-INT OVER GD8 -> 2 }T\r\n\r\nT{ 0 MAX-INT 0 MAX-INT GD8 -> 1 }T\r\nT{ 0 MAX-INT 1 MAX-INT GD8 -> 1 }T\r\nT{ 0 MAX-INT -1 MAX-INT GD8 -> 2 }T\r\nT{ 0 MAX-INT DUP 1- MAX-INT GD8 -> 1 }T\r\n\r\nT{ 0 MIN-INT 1+ 0 MIN-INT GD8 -> 1 }T\r\nT{ 0 MIN-INT 1+ -1 MIN-INT GD8 -> 1 }T\r\nT{ 0 MIN-INT 1+ 1 MIN-INT GD8 -> 2 }T\r\nT{ 0 MIN-INT 1+ DUP MIN-INT GD8 -> 1 }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING multiple RECURSEs in one colon definition\r\n\r\n: ACK ( m n -- u ) \\ Ackermann function, from Rosetta Code\r\n OVER 0= IF NIP 1+ EXIT THEN \\ ack(0, n) = n+1\r\n SWAP 1- SWAP ( -- m-1 n )\r\n DUP 0= IF 1+ RECURSE EXIT THEN \\ ack(m, 0) = ack(m-1, 1)\r\n 1- OVER 1+ SWAP RECURSE RECURSE \\ ack(m, n) = ack(m-1, ack(m,n-1))\r\n;\r\n\r\nT{ 0 0 ACK -> 1 }T\r\nT{ 3 0 ACK -> 5 }T\r\nT{ 2 4 ACK -> 11 }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING multiple ELSE's in an IF statement\r\n\\ Discussed on comp.lang.forth and accepted as valid ANS Forth\r\n\r\n: MELSE IF 1 ELSE 2 ELSE 3 ELSE 4 ELSE 5 THEN ;\r\nT{ 0 MELSE -> 2 4 }T\r\nT{ -1 MELSE -> 1 3 5 }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING manipulation of >IN in interpreter mode\r\n\r\nT{ 123456 DEPTH OVER 9 < 35 AND + 3 + >IN ! -> 123456 23456 3456 456 56 6 }T\r\nT{ 14145 8115 ?DUP 0= 34 AND >IN +! TUCK MOD 14 >IN ! GCD CALCULATION -> 15 }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING IMMEDIATE with CONSTANT VARIABLE and CREATE [ ... DOES> ]\r\n\r\nT{ 123 CONSTANT IW1 IMMEDIATE IW1 -> 123 }T\r\nT{ : IW2 IW1 LITERAL ; IW2 -> 123 }T\r\nT{ VARIABLE IW3 IMMEDIATE 234 IW3 ! IW3 @ -> 234 }T\r\nT{ : IW4 IW3 [ @ ] LITERAL ; IW4 -> 234 }T\r\nT{ :NONAME [ 345 ] IW3 [ ! ] ; DROP IW3 @ -> 345 }T\r\nT{ CREATE IW5 456 , IMMEDIATE -> }T\r\nT{ :NONAME IW5 [ @ IW3 ! ] ; DROP IW3 @ -> 456 }T\r\nT{ : IW6 CREATE , IMMEDIATE DOES> @ 1+ ; -> }T\r\nT{ 111 IW6 IW7 IW7 -> 112 }T\r\nT{ : IW8 IW7 LITERAL 1+ ; IW8 -> 113 }T\r\nT{ : IW9 CREATE , DOES> @ 2 + IMMEDIATE ; -> }T\r\n: FIND-IW BL WORD FIND NIP ; ( -- 0 | 1 | -1 )\r\nT{ 222 IW9 IW10 FIND-IW IW10 -> -1 }T \\ IW10 is not immediate\r\nT{ IW10 FIND-IW IW10 -> 224 1 }T \\ IW10 becomes immediate\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING that IMMEDIATE doesn't toggle a flag\r\n\r\nVARIABLE IT1 0 IT1 !\r\n: IT2 1234 IT1 ! ; IMMEDIATE IMMEDIATE\r\nT{ : IT3 IT2 ; IT1 @ -> 1234 }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING parsing behaviour of S\" .\" and (\r\n\\ which should parse to just beyond the terminating character no space needed\r\n\r\nT{ : GC5 S\" A string\"2DROP ; GC5 -> }T\r\nT{ ( A comment)1234 -> 1234 }T\r\nT{ : PB1 CR .\" You should see 2345: \".\" 2345\"( A comment) CR ; PB1 -> }T\r\n \r\n\\ ------------------------------------------------------------------------------\r\nTESTING number prefixes # $ % and 'c' character input\r\n\\ Adapted from the Forth 200X Draft 14.5 document\r\n\r\nVARIABLE OLD-BASE\r\nDECIMAL BASE @ OLD-BASE !\r\nT{ #1289 -> 1289 }T\r\nT{ #12346789. -> 12346789. }T\r\nT{ #-1289 -> -1289 }T\r\nT{ #-12346789. -> -12346789. }T\r\nT{ $12eF -> 4847 }T\r\nT{ $12aBcDeF. -> 313249263. }T\r\nT{ $-12eF -> -4847 }T\r\nT{ $-12AbCdEf. -> -313249263. }T\r\nT{ %10010110 -> 150 }T\r\nT{ %10010110. -> 150. }T\r\nT{ %-10010110 -> -150 }T\r\nT{ %-10010110. -> -150. }T\r\nT{ 'z' -> 122 }T\r\n\\ Check BASE is unchanged\r\nT{ BASE @ OLD-BASE @ = -> TRUE }T\r\n\r\n\\ Repeat in Hex mode\r\n16 OLD-BASE ! 16 BASE !\r\nT{ #1289 -> 509 }T \\ 2\r\nT{ #12346789. -> BC65A5. }T \\ 2\r\nT{ #-1289 -> -509 }T \\ 2\r\nT{ #-12346789. -> -BC65A5. }T \\ 2\r\nT{ $12eF -> 12EF }T \\ 2\r\nT{ $12aBcDeF. -> 12AbCdeF. }T \\ 2\r\nT{ $-12eF -> -12EF }T \\ 2\r\nT{ $-12AbCdEf. -> -12ABCDef. }T \\ 2\r\nT{ %10010110 -> 96 }T \\ 2\r\nT{ %10010110. -> 96. }T \\ 2\r\nT{ %-10010110 -> -96 }T \\ 2\r\nT{ %-10010110. -> -96. }T \\ 2\r\nT{ 'z' -> 7a }T \\ 2\r\n\\ Check BASE is unchanged\r\nT{ BASE @ OLD-BASE @ = -> TRUE }T \\ 2\r\n\r\nDECIMAL\r\n\\ Check number prefixes in compile mode\r\nT{ : nmp #8327. $-2cbe %011010111 ''' ; nmp -> 8327. -11454 215 39 }T\r\n\r\n\r\n\\ ------------------------------------------------------------------------------\r\n\r\nCR .( End of additional Core tests) CR\r\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"9dfb8b6e13f05d19533fa203776a55d7a0629005","subject":"Now I see the error of my ways.","message":"Now I see the error of my ways.\n\nPrevious revision of this file changed the \"boot\" commands to take\nno arguments from the stack. This is only valid in the case where\na kernel has not been loaded. In that case, load_kernel_and_modules\nwill be called, which takes a list of arguments from the stack.\n\nWhen a kernel is presently loaded, though, the list of arguments must\nbe passed to the boot command, which was the behaviour before the last\nrevision.\n\nFix things for both cases.\n\nNoticed by: S-Max and others on that chat room\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/loader.4th","new_file":"sys\/boot\/forth\/loader.4th","new_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\ns\" arch-alpha\" environment? [if] [if]\n\ts\" loader_version\" environment? [if]\n\t\t11 < [if]\n\t\t\t.( Loader version 1.1+ required) cr\n\t\t\tabort\n\t\t[then]\n\t[else]\n\t\t.( Could not get loader version!) cr\n\t\tabort\n\t[then]\n[then] [then]\n\ns\" arch-i386\" environment? [if] [if]\n\ts\" loader_version\" environment? [if]\n\t\t10 < [if]\n\t\t\t.( Loader version 1.0+ required) cr\n\t\t\tabort\n\t\t[then]\n\t[else]\n\t\t.( Could not get loader version!) cr\n\t\tabort\n\t[then]\n[then] [then]\n\ninclude \/boot\/support.4th\n\n\\ ***** boot-conf\n\\\n\\\tPrepares to boot as specified by loaded configuration files.\n\nonly forth also support-functions also builtins definitions\n\n: boot\n 0= if ( interpreted ) get_arguments then\n\n \\ Unload only if a path was passed\n dup if\n >r over r> swap\n c@ [char] - <> if\n 0 1 unload drop\n else\n s\" kernelname\" getenv? if ( a kernel has been loaded )\n 1 boot exit\n then\n load_kernel_and_modules\n ?dup if exit then\n 0 1 boot exit\n then\n else\n s\" kernelname\" getenv? if ( a kernel has been loaded )\n 1 boot exit\n then\n load_kernel_and_modules\n ?dup if exit then\n 0 1 boot exit\n then\n load_kernel_and_modules\n ?dup 0= if 0 1 boot then\n;\n\n: boot-conf\n 0= if ( interpreted ) get_arguments then\n 0 1 unload drop\n load_kernel_and_modules\n ?dup 0= if 0 1 autoboot then\n;\n\nalso forth definitions also builtins\n\nbuiltin: boot\nbuiltin: boot-conf\n\nonly forth definitions also support-functions\n\n\\ ***** check-password\n\\\n\\\tIf a password was defined, execute autoboot and ask for\n\\\tpassword if autoboot returns.\n\n: check-password\n password .addr @ if\n 0 autoboot\n false >r\n begin\n bell emit bell emit\n .\" Password: \"\n password .len @ read-password\n dup password .len @ = if\n 2dup password .addr @ password .len @\n compare 0= if r> drop true >r then\n then\n drop free drop\n r@\n until\n r> drop\n then\n;\n\n\\ ***** start\n\\\n\\ Initializes support.4th global variables, sets loader_conf_files,\n\\ process conf files, and, if any one such file was succesfully\n\\ read to the end, load kernel and modules.\n\n: start ( -- ) ( throws: abort & user-defined )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n \\ Will *NOT* try to load kernel and modules if no configuration file\n \\ was succesfully loaded!\n any_conf_read? if\n load_kernel\n load_modules\n then\n;\n\n\\ ***** initialize\n\\\n\\\tOverrides support.4th initialization word with one that does\n\\\teverything start one does, short of loading the kernel and\n\\\tmodules. Returns a flag\n\n: initialize ( -- flag )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n any_conf_read?\n;\n\n\\ ***** read-conf\n\\\n\\\tRead a configuration file, whose name was specified on the command\n\\\tline, if interpreted, or given on the stack, if compiled in.\n\n: (read-conf) ( addr len -- )\n conf_files .addr @ ?dup if free abort\" Fatal error freeing memory\" then\n strdup conf_files .len ! conf_files .addr !\n include_conf_files \\ Will recurse on new loader_conf_files definitions\n;\n\n: read-conf ( | addr len -- ) ( throws: abort & user-defined )\n state @ if\n \\ Compiling\n postpone (read-conf)\n else\n \\ Interpreting\n bl parse (read-conf)\n then\n; immediate\n\n\\ ***** enable-module\n\\\n\\ Turn a module loading on.\n\n: enable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n true r> module.flag !\n .\" will be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** disable-module\n\\\n\\ Turn a module loading off.\n\n: disable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n false r> module.flag !\n .\" will not be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** toggle-module\n\\\n\\ Turn a module loading on\/off.\n\n: toggle-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n r@ module.flag @ 0= dup r> module.flag !\n if\n .\" will be loaded.\" cr\n else\n .\" will not be loaded.\" cr\n then\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** show-module\n\\\n\\\tShow loading information about a module.\n\n: show-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n .\" Name: \" r@ module.name dup .addr @ swap .len @ type cr\n .\" Path: \" r@ module.loadname dup .addr @ swap .len @ type cr\n .\" Type: \" r@ module.type dup .addr @ swap .len @ type cr\n .\" Flags: \" r@ module.args dup .addr @ swap .len @ type cr\n .\" Before load: \" r@ module.beforeload dup .addr @ swap .len @ type cr\n .\" After load: \" r@ module.afterload dup .addr @ swap .len @ type cr\n .\" Error: \" r@ module.loaderror dup .addr @ swap .len @ type cr\n .\" Status: \" r> module.flag @ if .\" Load\" else .\" Don't load\" then cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ Words to be used inside configuration files\n\n: retry false ; \\ For use in load error commands\n: ignore true ; \\ For use in load error commands\n\n\\ Return to strict forth vocabulary\n\n: #type\n over - >r\n type\n r> spaces\n;\n\n: .? 2 spaces 2swap 15 #type 2 spaces type cr ;\n\n: ?\n ['] ? execute\n s\" boot-conf\" s\" load kernel and modules, then autoboot\" .?\n s\" read-conf\" s\" read a configuration file\" .?\n s\" enable-module\" s\" enable loading of a module\" .?\n s\" disable-module\" s\" disable loading of a module\" .?\n s\" toggle-module\" s\" toggle loading of a module\" .?\n s\" show-module\" s\" show module load data\" .?\n;\n\nonly forth also\n\n","old_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\ns\" arch-alpha\" environment? [if] [if]\n\ts\" loader_version\" environment? [if]\n\t\t11 < [if]\n\t\t\t.( Loader version 1.1+ required) cr\n\t\t\tabort\n\t\t[then]\n\t[else]\n\t\t.( Could not get loader version!) cr\n\t\tabort\n\t[then]\n[then] [then]\n\ns\" arch-i386\" environment? [if] [if]\n\ts\" loader_version\" environment? [if]\n\t\t10 < [if]\n\t\t\t.( Loader version 1.0+ required) cr\n\t\t\tabort\n\t\t[then]\n\t[else]\n\t\t.( Could not get loader version!) cr\n\t\tabort\n\t[then]\n[then] [then]\n\ninclude \/boot\/support.4th\n\n\\ ***** boot-conf\n\\\n\\\tPrepares to boot as specified by loaded configuration files.\n\nonly forth also support-functions also builtins definitions\n\n: boot\n 0= if ( interpreted ) get_arguments then\n\n \\ Unload only if a path was passed\n dup if\n >r over r> swap\n c@ [char] - <> if\n 0 1 unload drop\n else\n s\" kernelname\" getenv? 0= if ( no kernel has been loaded )\n\tload_kernel_and_modules\n\t?dup if exit then\n then\n 0 1 boot exit\n then\n else\n s\" kernelname\" getenv? 0= if ( no kernel has been loaded )\n load_kernel_and_modules\n ?dup if exit then\n then\n 0 1 boot exit\n then\n load_kernel_and_modules\n ?dup 0= if 0 1 boot then\n;\n\n: boot-conf\n 0= if ( interpreted ) get_arguments then\n 0 1 unload drop\n load_kernel_and_modules\n ?dup 0= if 0 1 autoboot then\n;\n\nalso forth definitions also builtins\n\nbuiltin: boot\nbuiltin: boot-conf\n\nonly forth definitions also support-functions\n\n\\ ***** check-password\n\\\n\\\tIf a password was defined, execute autoboot and ask for\n\\\tpassword if autoboot returns.\n\n: check-password\n password .addr @ if\n 0 autoboot\n false >r\n begin\n bell emit bell emit\n .\" Password: \"\n password .len @ read-password\n dup password .len @ = if\n 2dup password .addr @ password .len @\n compare 0= if r> drop true >r then\n then\n drop free drop\n r@\n until\n r> drop\n then\n;\n\n\\ ***** start\n\\\n\\ Initializes support.4th global variables, sets loader_conf_files,\n\\ process conf files, and, if any one such file was succesfully\n\\ read to the end, load kernel and modules.\n\n: start ( -- ) ( throws: abort & user-defined )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n \\ Will *NOT* try to load kernel and modules if no configuration file\n \\ was succesfully loaded!\n any_conf_read? if\n load_kernel\n load_modules\n then\n;\n\n\\ ***** initialize\n\\\n\\\tOverrides support.4th initialization word with one that does\n\\\teverything start one does, short of loading the kernel and\n\\\tmodules. Returns a flag\n\n: initialize ( -- flag )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n any_conf_read?\n;\n\n\\ ***** read-conf\n\\\n\\\tRead a configuration file, whose name was specified on the command\n\\\tline, if interpreted, or given on the stack, if compiled in.\n\n: (read-conf) ( addr len -- )\n conf_files .addr @ ?dup if free abort\" Fatal error freeing memory\" then\n strdup conf_files .len ! conf_files .addr !\n include_conf_files \\ Will recurse on new loader_conf_files definitions\n;\n\n: read-conf ( | addr len -- ) ( throws: abort & user-defined )\n state @ if\n \\ Compiling\n postpone (read-conf)\n else\n \\ Interpreting\n bl parse (read-conf)\n then\n; immediate\n\n\\ ***** enable-module\n\\\n\\ Turn a module loading on.\n\n: enable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n true r> module.flag !\n .\" will be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** disable-module\n\\\n\\ Turn a module loading off.\n\n: disable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n false r> module.flag !\n .\" will not be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** toggle-module\n\\\n\\ Turn a module loading on\/off.\n\n: toggle-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n r@ module.flag @ 0= dup r> module.flag !\n if\n .\" will be loaded.\" cr\n else\n .\" will not be loaded.\" cr\n then\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** show-module\n\\\n\\\tShow loading information about a module.\n\n: show-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n .\" Name: \" r@ module.name dup .addr @ swap .len @ type cr\n .\" Path: \" r@ module.loadname dup .addr @ swap .len @ type cr\n .\" Type: \" r@ module.type dup .addr @ swap .len @ type cr\n .\" Flags: \" r@ module.args dup .addr @ swap .len @ type cr\n .\" Before load: \" r@ module.beforeload dup .addr @ swap .len @ type cr\n .\" After load: \" r@ module.afterload dup .addr @ swap .len @ type cr\n .\" Error: \" r@ module.loaderror dup .addr @ swap .len @ type cr\n .\" Status: \" r> module.flag @ if .\" Load\" else .\" Don't load\" then cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ Words to be used inside configuration files\n\n: retry false ; \\ For use in load error commands\n: ignore true ; \\ For use in load error commands\n\n\\ Return to strict forth vocabulary\n\n: #type\n over - >r\n type\n r> spaces\n;\n\n: .? 2 spaces 2swap 15 #type 2 spaces type cr ;\n\n: ?\n ['] ? execute\n s\" boot-conf\" s\" load kernel and modules, then autoboot\" .?\n s\" read-conf\" s\" read a configuration file\" .?\n s\" enable-module\" s\" enable loading of a module\" .?\n s\" disable-module\" s\" disable loading of a module\" .?\n s\" toggle-module\" s\" toggle loading of a module\" .?\n s\" show-module\" s\" show module load data\" .?\n;\n\nonly forth also\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"1847901005fd01b6252104a851b615847d361ea0","subject":"Fix a stack leak in [unused] cycle_menuitem function while we're here (required misconfiguration and\/or missing environment vars to occur).","message":"Fix a stack leak in [unused] cycle_menuitem function while we're here\n(required misconfiguration and\/or missing environment vars to occur).\n\nReviewed by:\tpeterj, adrian (co-mentor)\nApproved by:\tadrian (co-mentor)\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/menu.4th","new_file":"sys\/boot\/forth\/menu.4th","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"bsd-3-clause","lang":"Forth"} {"commit":"58878de74c5eb6225ca5fcc2472c571c0c686e47","subject":"Added unless, rot, ?dup","message":"Added unless, rot, ?dup\n","repos":"AshleyF\/Forthkit,AshleyF\/Forthkit,AshleyF\/Forthkit","old_file":"hardware\/register\/bootstrap.4th","new_file":"hardware\/register\/bootstrap.4th","new_contents":"( bootstrap remainder of interpreter )\n( load into machine running outer interpreter image )\n\ncreate : compile create compile ; ( magic! )\n\n( assembler )\n\n: x 1 ; ( shared by outer interpreter )\n: d 2 ; ( dictionary pointer - shared by outer interpreter )\n: zero 4 ; ( shared by outer interpreter )\n: y 30 ; \n: z 31 ; \n\n: [ interact ; immediate\n: ] compile ;\n\n: cp, 3 , , , ; \n: popxy popx [ x y cp, ] popx ;\n: pushxy pushx [ y x cp, ] pushx ;\n\n: xor, 15 , , , , ; \n: swap popxy [ x y x xor, x y y xor, x y x xor, ] pushxy ;\n\n: ldc, 0 , , , ;\n: ld, 1 , , , ;\n: st, 2 , , , ;\n: in, 4 , , ;\n: out, 5 , , ;\n: inc, 6 , , , ;\n: dec, 7 , , , ;\n: add, 8 , , , , ;\n: sub, 9 , , swap , , ;\n: mul, 10 , , , , ;\n: div, 11 , , swap , , ;\n: mod, 12 , , swap , , ;\n: and, 13 , , , , ;\n: or, 14 , , , , ;\n: not, 16 , , , ;\n: shr, 17 , , swap , , ;\n: shl, 18 , , swap , , ;\n: beq, 19 , , , , ;\n: bne, 20 , , , , ;\n: bgt, 21 , , swap , , ;\n: bge, 22 , , swap , , ;\n: blt, 23 , , swap , , ;\n: ble, 24 , , swap , , ;\n: exec, 25 , , ;\n: jump, 26 , , ;\n: call, 27 , , ;\n: ret, 28 , ;\n: halt, 29 , ;\n: dump, 30 , ;\n\n( instruction words )\n\n: + popxy [ x y x add, ] pushx ;\n: - popxy [ x y x sub, ] pushx ;\n: * popxy [ x y x mul, ] pushx ;\n: \/ popxy [ x y x div, ] pushx ;\n: mod popxy [ x y x mod, ] pushx ;\n: 2\/ popxy [ x y x shr, ] pushx ;\n: 2* popxy [ x y x shl, ] pushx ;\n: and popxy [ x y x and, ] pushx ;\n: or popxy [ x y x or, ] pushx ;\n: xor popxy [ x y x xor, ] pushx ;\n: not popx [ x x not, ] pushx ;\n: 1+ popx [ x x inc, ] pushx ;\n: 1- popx [ x x dec, ] pushx ;\n: exec popx [ x exec, ] ;\n: dump [ dump, ] ;\n: exit [ halt, ] ;\n\n( stack manipulation )\n\n: drop ( a- ) popx ;\n: 2drop ( ab- ) drop drop ;\n: dup ( a-aa ) popx pushx pushx ;\n: over ( ab-aba ) popxy pushx pushx [ y x cp, ] pushx swap ;\n: 2dup ( ab-abab ) over over ;\n: nip ( ab-b ) swap drop ;\n: tuck ( ab-bab ) swap over ;\n: -rot ( abc-cab ) swap popxy pushx [ y z cp, ] swap [ z x cp, ] pushx ;\n: rot ( abs-bca ) -rot -rot ;\n\n( vocabulary )\n\n: true -1 ;\n: false 0 ;\n\n: key [ x in, ] pushx ;\n: emit popx [ x out, ] ;\n: cr 10 emit ;\n: space 32 emit ;\n\n: @ popx [ x x ld, ] pushx ;\n: ! popxy [ x y st, ] ;\n\n: allot [ d x cp, ] pushx swap popx [ x d d add, ] ;\n\n: here@ [ d x cp, ] pushx ;\n: here! popx [ x d cp, ] ;\n\n: >dfa 2 + ;\n: ' find >dfa ;\n\n: if [ ' popxy literal ] call, here@ 1+ zero x 0 beq, ; immediate\n: unless [ ' popxy literal ] call, here@ 1+ zero x 0 bne, ; immediate\n: else here@ 1+ 0 jump, swap here@ swap ! ; immediate\n: then here@ swap ! ; immediate\n\n: = popxy 0 [ x y here@ 6 + bne, ] not ;\n: <> popxy 0 [ x y here@ 6 + beq, ] not ;\n: > popxy 0 [ x y here@ 6 + ble, ] not ;\n: < popxy 0 [ x y here@ 6 + bge, ] not ;\n: >= popxy 0 [ x y here@ 6 + blt, ] not ;\n: <= popxy 0 [ x y here@ 6 + bgt, ] not ;\n\n: sign 0 < if -1 else 1 then ;\n: \/mod 2dup \/ -rot mod ;\n\n: min 2dup > if swap then drop ;\n: max 2dup < if swap then drop ;\n\n: negate -1 * ;\n: abs dup 0 < if negate then ;\n\n: .sign dup sign negate 44 + emit ; ( happens 44 +\/- 1 is ASCII '-'\/'+' )\n: .dig 10 \/mod swap ;\n: .digemit 48 + emit ; ( 48 is ASCII '0' )\n: . .sign .dig .dig .dig .dig .dig drop .digemit .digemit .digemit .digemit .digemit cr ;\n\n: ?dup dup unless drop then ;\n","old_contents":"( bootstrap remainder of interpreter )\n( load into machine running outer interpreter image )\n\ncreate : compile create compile ; ( magic! )\n\n( assembler )\n\n: x 1 ; ( shared by outer interpreter )\n: d 2 ; ( dictionary pointer - shared by outer interpreter )\n: zero 4 ; ( shared by outer interpreter )\n: y 30 ; \n: z 31 ; \n\n: [ interact ; immediate\n: ] compile ;\n\n: cp, 3 , , , ; \n: popxy popx [ x y cp, ] popx ;\n: pushxy pushx [ y x cp, ] pushx ;\n\n: xor, 15 , , , , ; \n: swap popxy [ x y x xor, x y y xor, x y x xor, ] pushxy ;\n\n: ldc, 0 , , , ;\n: ld, 1 , , , ;\n: st, 2 , , , ;\n: in, 4 , , ;\n: out, 5 , , ;\n: inc, 6 , , , ;\n: dec, 7 , , , ;\n: add, 8 , , , , ;\n: sub, 9 , , swap , , ;\n: mul, 10 , , , , ;\n: div, 11 , , swap , , ;\n: mod, 12 , , swap , , ;\n: and, 13 , , , , ;\n: or, 14 , , , , ;\n: not, 16 , , , ;\n: shr, 17 , , swap , , ;\n: shl, 18 , , swap , , ;\n: beq, 19 , , , , ;\n: bne, 20 , , , , ;\n: bgt, 21 , , swap , , ;\n: bge, 22 , , swap , , ;\n: blt, 23 , , swap , , ;\n: ble, 24 , , swap , , ;\n: exec, 25 , , ;\n: jump, 26 , , ;\n: call, 27 , , ;\n: ret, 28 , ;\n: halt, 29 , ;\n: dump, 30 , ;\n\n( instruction words )\n\n: + popxy [ x y x add, ] pushx ;\n: - popxy [ x y x sub, ] pushx ;\n: * popxy [ x y x mul, ] pushx ;\n: \/ popxy [ x y x div, ] pushx ;\n: mod popxy [ x y x mod, ] pushx ;\n: 2\/ popxy [ x y x shr, ] pushx ;\n: 2* popxy [ x y x shl, ] pushx ;\n: and popxy [ x y x and, ] pushx ;\n: or popxy [ x y x or, ] pushx ;\n: xor popxy [ x y x xor, ] pushx ;\n: not popx [ x x not, ] pushx ;\n: 1+ popx [ x x inc, ] pushx ;\n: 1- popx [ x x dec, ] pushx ;\n: exec popx [ x exec, ] ;\n: dump [ dump, ] ;\n: exit [ halt, ] ;\n\n( stack manipulation )\n\n: drop ( a- ) popx ;\n: 2drop ( ab- ) drop drop ;\n: dup ( a-aa ) popx pushx pushx ;\n: over ( ab-aba ) popxy pushx pushx [ y x cp, ] pushx swap ;\n: 2dup ( ab-abab ) over over ;\n: nip ( ab-b ) swap drop ;\n: tuck ( ab-bab ) swap over ;\n: -rot ( abc-cab ) swap popxy pushx [ y z cp, ] swap [ z x cp, ] pushx ;\n\n( vocabulary )\n\n: true -1 ;\n: false 0 ;\n\n: key [ x in, ] pushx ;\n: emit popx [ x out, ] ;\n: cr 10 emit ;\n: space 32 emit ;\n\n: @ popx [ x x ld, ] pushx ;\n: ! popxy [ x y st, ] ;\n\n: allot [ d x cp, ] pushx swap popx [ x d d add, ] ;\n\n: here@ [ d x cp, ] pushx ;\n: here! popx [ x d cp, ] ;\n\n: >dfa 2 + ;\n: ' find >dfa ;\n\n: if [ ' popxy literal ] call, here@ 1+ zero x 0 beq, ; immediate\n: else here@ 1+ 0 jump, swap here@ swap ! ; immediate\n: then here@ swap ! ; immediate\n\n: = popxy 0 [ x y here@ 6 + bne, ] not ;\n: <> popxy 0 [ x y here@ 6 + beq, ] not ;\n: > popxy 0 [ x y here@ 6 + ble, ] not ;\n: < popxy 0 [ x y here@ 6 + bge, ] not ;\n: >= popxy 0 [ x y here@ 6 + blt, ] not ;\n: <= popxy 0 [ x y here@ 6 + bgt, ] not ;\n\n: sign 0 < if -1 else 1 then ;\n: \/mod 2dup \/ -rot mod ;\n\n: min 2dup > if swap then drop ;\n: max 2dup < if swap then drop ;\n\n: negate -1 * ;\n: abs dup 0 < if negate then ;\n\n: .sign dup sign negate 44 + emit ; ( happens 44 +\/- 1 is ASCII '-'\/'+' )\n: .dig 10 \/mod swap ;\n: .digemit 48 + emit ; ( 48 is ASCII '0' )\n: . .sign .dig .dig .dig .dig .dig drop .digemit .digemit .digemit .digemit .digemit cr ;\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"8b30d268330336ee9d8180bbf2b78b48fb6f7fe9","subject":"Fix SEE","message":"Fix SEE\n","repos":"rm-hull\/byok3,rm-hull\/byok3","old_file":"core\/src\/main\/resources\/forth\/system.fth","new_file":"core\/src\/main\/resources\/forth\/system.fth","new_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\\n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n\n: COUNT dup 1+ swap c@ ;\n\n\\ Miscellaneous support words\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: <= ( a b -- f , true if A <= b ) > 0= ;\n: >= ( a b -- f , true if A >= b ) < 0= ;\n: NOT ( n -- !n , logical negation ) 0= ;\n: DNEGATE ( d -- -d , negate by doing 0-d )\n 0 swap -\n;\n: CELL+ ( n -- n+cell ) cell + ;\n: CELL- ( n -- n-cell ) cell - ;\n: CELL* ( n -- n*cell ) cells ;\n\n: CHAR+ ( n -- n+size_of_char ) 1+ ;\n\\ : CHARS ( n -- n*size_of_char, don't do anything ) ; immediate\n\n\\ useful stack manipulation words\n: -ROT ( a b c -- c a b ) rot rot ;\n: 3DUP ( a b c -- a b c a b c ) 2 pick 2 pick 2 pick ;\n\n\\ ------------------------------------------------------------------\n: ID. ( nfa -- ) count 31 and type ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: PAD ( -- addr ) here 128 + ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n\n: BETWEEN ( n lo hi -- flag , true if between lo & hi )\n >r over r> > >r\n < r> or 0=\n;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: ? ( -- ) @ . ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ ' (lit) , cell 1- , ] +\n [ ' (lit) , cell 1- invert , ] and ;\n\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n: ALLOT ( nbytes -- , allot space in dictionary ) dp +! align ;\n\n: C, ( c -- ) here c! 1 dp +! ;\n\\ : W, ( w -- ) dp @ even-up dup dp ! w! 2 dp +! ;\n\\ : , ( n -- , lay into dictionary ) align here ! cell allot ;\n\n: SEE ( -- )\n ' dup\n >body swap >size\n disassemble ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token )\n [compile] literal ( compile a call to literal )\n ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n: :NONAME ( -- xt , begin compilation of headerless secondary ) align here ] ;\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick )\n ?comp ' [compile] literal\n; immediate\n\n\n: (DOES>) ( xt -- , modify previous definition to execute code at xt )\n latest >body \\ get address of code for new word\n cell + \\ offset to second cell in create word\n ! \\ store execution token of DOES> code in new word\n;\n\n: DOES> ( -- , define execution code for CREATE word )\n 0 [compile] literal \\ dummy literal to hold xt\n here cell- \\ address of zero in literal\n compile (does>) \\ call (DOES>) from new creation word\n\t\t>r \\ move addrz to return stack so ; doesn't see stack garbage\n [compile] ; \\ terminate part of code before does>\n\t\tr>\n :noname ( addrz xt )\n swap ! \\ save execution token in literal\n; immediate\n\n0 1- constant -1\n0 2- constant -2\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 )\n swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 )\n dup cell+ @ swap @ ;\n\n: 2* ( n -- n*2 )\n 2 *\n;\n: 2\/ ( n -- n\/2 )\n 2 \/\n;\n\n\n\\ define some useful constants ------------------------------\n1 0= constant FALSE\n0 0= constant TRUE\n32 constant BL\n\n\\ Stack data structure ----------------------------------------\n\\ This is a general purpose stack utility used to implement necessary\n\\ stacks for the compiler or the user. Not real fast.\n\\ These stacks grow up which is different then normal.\n\\ cell 0 - stack pointer, offset from pfa of word\n\\ cell 1 - limit for range checking\n\\ cell 2 - first data location\n\n: :STACK ( #cells -- )\n CREATE 2 cells , ( offset of first data location )\n dup , ( limit for range checking, not currently used )\n cells cell+ allot ( allot an extra cell for safety )\n;\n\n: >STACK ( n stack -- , push onto stack, postincrement )\n dup @ 2dup cell+ swap ! ( -- n stack offset )\n + !\n;\n\n: STACK> ( stack -- n , pop , predecrement )\n dup @ cell- 2dup swap !\n + @\n;\n\n: STACK@ ( stack -- n , copy )\n dup @ cell- + @\n;\n\n: STACK.PICK ( index stack -- n , grab Nth from top of stack )\n dup @ cell- +\n swap cells - \\ offset for index\n @\n;\n: STACKP ( stack -- ptr , to next empty location on stack )\n\tdup @ +\n;\n\n: 0STACKP ( stack -- , clear stack)\n 8 swap !\n;\n\n32 :stack ustack\nustack 0stackp\n\n\\ Define JForth like words.\n: >US ustack >stack ;\n: US> ustack stack> ;\n: US@ ustack stack@ ;\n: 0USP ustack 0stackp ;\n\n\n\n\\ DO LOOP ------------------------------------------------\n\n3 constant do_flag\n4 constant leave_flag\n5 constant ?do_flag\n\n: DO ( -- , loop-back do_flag jump-from ?do_flag )\n ?comp\n compile (do)\n here >us do_flag >us ( for backward branch )\n; immediate\n\n: ?DO ( -- , loop-back do_flag jump-from ?do_flag , on user stack )\n ?comp\n ( leave address to set for forward branch )\n compile (?do)\n here 0 ,\n here >us do_flag >us ( for backward branch )\n >us ( for forward branch ) ?do_flag >us\n; immediate\n\n: LEAVE ( -- addr leave_flag )\n compile (leave)\n here 0 , >us\n leave_flag >us\n; immediate\n\n: LOOP-FORWARD ( -us- jump-from ?do_flag -- )\n BEGIN\n us@ leave_flag =\n us@ ?do_flag =\n OR\n WHILE\n us> leave_flag =\n IF\n us> here over - cell+ swap !\n ELSE\n us> dup\n here swap -\n cell+ swap !\n THEN\n REPEAT\n;\n\n: LOOP-BACK ( loop-addr do_flag -us- )\n us> do_flag ?pairs\n us> here - here\n !\n cell allot\n;\n\n: LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (loop)\n loop-forward loop-back\n; immediate\n\n\\ : DOTEST 5 0 do 333 . loop 888 . ;\n\\ : ?DOTEST0 0 0 ?do 333 . loop 888 . ;\n\\ : ?DOTEST1 5 0 ?do 333 . loop 888 . ;\n\n: +LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (+loop)\n loop-forward loop-back\n; immediate\n\n: UNLOOP ( loop-sys -r- )\n r> \\ save return pointer\n rdrop rdrop\n >r\n;\n\n\n: RECURSE ( ? -- ? , call the word currently being defined )\n latest compile,\n; immediate\n\n: SPACE bl emit ;\n: SPACES 512 min 0 max 0 ?DO space LOOP ;\n: 0SP depth 0 ?do drop loop ;\n\n\\ : >NEWLINE ( -- , CR if needed )\n\\ out @ 0>\n\\ IF cr\n\\ THEN\n\\ ;\n\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 ) swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 ) dup cell+ @ swap @ ;\n\n: DABS ( d -- |d| )\n dup 0<\n IF dnegate\n THEN\n;\n\n: S>D ( s -- d , extend signed single precision to double )\n dup 0<\n IF -1\n ELSE 0\n THEN\n;\n\n: D>S ( d -- s ) drop ;\n\n: PARSE-WORD ( \"name\" -- c-addr u ) bl parse ;\n: \/STRING ( addr len n -- addr' len' ) over min rot over + -rot - ;\n: PLACE ( addr len to -- , move string ) 3dup 1+ swap cmove c! drop ;\n\n: ASCII ( -- char, state smart )\n bl parse drop c@\n state @ 1 =\n IF [compile] literal\n ELSE\n THEN\n; immediate\n\n: CHAR ( -- char , interpret mode ) bl parse drop c@ ;\n: [CHAR] ( -- char , for compile mode )\n char [compile] literal\n; immediate\n\n: $TYPE ( $string -- ) count type ;\n: 'word ( -- addr ) here ;\n\n: EVEN ( addr -- addr' ) dup 1 and + ;\n\n: (C\") ( -- $addr ) r> dup count + aligned >r ;\n: (S\") ( -- c-addr cnt ) r> count 2dup + aligned >r ;\n: (.\") ( -- , type following string ) r> count 2dup + aligned >r type ;\n: \", ( addr len -- , place string into dict ) tuck 'word place 1+ allot align ;\n: ,\" ( -- ) [char] \" parse \", ;\n\n: .( ( --, type string delimited by parens )\n [char] ) parse type\n; immediate\n\n: .\" ( -- , type string )\n state @ 1 =\n IF compile (.\") ,\"\n ELSE [char] \" parse type\n THEN\n; immediate\n\n: .' ( -- , type string delimited by single quote )\n state @\n IF compile (.\") [char] ' parse \",\n ELSE [char] ' parse type\n THEN\n; immediate\n\n: C\" ( -- addr , return string address, ANSI )\n state @\n IF compile (c\") ,\"\n ELSE [char] \" parse pad place pad\n THEN\n; immediate\n\n: S\" ( -- , -- addr , return string address, ANSI )\n state @\n IF compile (s\") ,\"\n ELSE [char] \" parse pad place pad count\n THEN\n; immediate\n\n: \" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n: P\" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n\n\\ : \"\" ( -- addr )\n\\ state @\n\\ IF\n\\ compile (C\")\n\\ bl parse-word \",\n\\ ELSE\n\\ bl parse-word pad place pad\n\\ THEN\n\\ ; immediate\n\n: SLITERAL ( addr cnt -- , compile string )\n\tcompile (S\")\n\t\",\n; IMMEDIATE\n\n: $APPEND ( addr count $1 -- , append text to $1 )\n over >r\n dup >r\n count + ( -- a2 c2 end1 )\n swap cmove\n r> dup c@ ( a1 c1 )\n r> + ( -- a1 totalcount )\n swap c!\n;\n\n\\ ANSI word to replace [COMPILE] and COMPILE ----------------\n\\ : POSTPONE ( -- )\n\\\tbl word find\n\\\tdup 0=\n\\\tIF\n\\\t\t.\" Postpone could not find \" count type cr abort\n\\\tELSE\n\\\t\t0>\n\\\t\tIF compile, \\ immediate\n\\\t\tELSE (compile) \\ normal\n\\\t\tTHEN\n\\\tTHEN\n\\ ; immediate\n\n\\ -----------------------------------------------------------------\n\\ Auto Initialization\n: AUTO.INIT ( -- )\n\\ Kernel finds AUTO.INIT and executes it after loading dictionary.\n\\\t.\" Begin AUTO.INIT ------\" cr\n;\n: AUTO.TERM ( -- )\n\\ Kernel finds AUTO.TERM and executes it on bye.\n\\\t.\" End AUTO.TERM ------\" cr\n;\n\n\n: CLEARSTACK ( i*x -- )\n BEGIN depth\n WHILE drop\n REPEAT ;\n\nvariable pictured_output \\ hidden?\nvariable pictured_output_len \\ hidden?\n\n: <# ( -- ) pad pictured_output ! 0 pictured_output_len ! ;\n: #> ( -- addr n ) drop pictured_output @ pictured_output_len @ ;\n\n: HOLD ( c -- )\n pictured_output @ dup dup 1+ pictured_output_len @ cmove c!\n 1 pictured_output_len +!\n;\n\n\\ ------------------------ INPUT -------------------------------\n\n: SIGN ( n -- ) < 0 IF 45 hold THEN\n;\n\n: DIGIT ( n -- ascii )\n dup 10 < IF 48 ELSE 87 THEN + ;\n\n: # ( n -- n )\n base @ \/mod swap digit hold ;\n\n: #S ( n -- )\n BEGIN base @ \/mod dup\n WHILE swap digit hold\n REPEAT\n digit hold ;","old_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\\n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n\n: COUNT dup 1+ swap c@ ;\n\n\\ Miscellaneous support words\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: <= ( a b -- f , true if A <= b ) > 0= ;\n: >= ( a b -- f , true if A >= b ) < 0= ;\n: NOT ( n -- !n , logical negation ) 0= ;\n: DNEGATE ( d -- -d , negate by doing 0-d )\n 0 swap -\n;\n: CELL+ ( n -- n+cell ) cell + ;\n: CELL- ( n -- n-cell ) cell - ;\n: CELL* ( n -- n*cell ) cells ;\n\n: CHAR+ ( n -- n+size_of_char ) 1+ ;\n\\ : CHARS ( n -- n*size_of_char, don't do anything ) ; immediate\n\n\\ useful stack manipulation words\n: -ROT ( a b c -- c a b ) rot rot ;\n: 3DUP ( a b c -- a b c a b c ) 2 pick 2 pick 2 pick ;\n\n\\ ------------------------------------------------------------------\n: ID. ( nfa -- ) count 31 and type ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: PAD ( -- addr ) here 128 + ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n\n: BETWEEN ( n lo hi -- flag , true if between lo & hi )\n >r over r> > >r\n < r> or 0=\n;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: ? ( -- ) @ . ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ ' (lit) , cell 1- , ] +\n [ ' (lit) , cell 1- invert , ] and ;\n\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n: ALLOT ( nbytes -- , allot space in dictionary ) dp +! align ;\n\n: C, ( c -- ) here c! 1 dp +! ;\n\\ : W, ( w -- ) dp @ even-up dup dp ! w! 2 dp +! ;\n\\ : , ( n -- , lay into dictionary ) align here ! cell allot ;\n\n: SEE ( -- )\n ' dup\n 16 + @ \\ offset in execution token for alloc size\n cells swap >body swap\n disassemble ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token )\n [compile] literal ( compile a call to literal )\n ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n: :NONAME ( -- xt , begin compilation of headerless secondary ) align here ] ;\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick )\n ?comp ' [compile] literal\n; immediate\n\n\n: (DOES>) ( xt -- , modify previous definition to execute code at xt )\n latest >body \\ get address of code for new word\n cell + \\ offset to second cell in create word\n ! \\ store execution token of DOES> code in new word\n;\n\n: DOES> ( -- , define execution code for CREATE word )\n 0 [compile] literal \\ dummy literal to hold xt\n here cell- \\ address of zero in literal\n compile (does>) \\ call (DOES>) from new creation word\n\t\t>r \\ move addrz to return stack so ; doesn't see stack garbage\n [compile] ; \\ terminate part of code before does>\n\t\tr>\n :noname ( addrz xt )\n swap ! \\ save execution token in literal\n; immediate\n\n0 1- constant -1\n0 2- constant -2\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 )\n swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 )\n dup cell+ @ swap @ ;\n\n: 2* ( n -- n*2 )\n 2 *\n;\n: 2\/ ( n -- n\/2 )\n 2 \/\n;\n\n\n\\ define some useful constants ------------------------------\n1 0= constant FALSE\n0 0= constant TRUE\n32 constant BL\n\n\\ Stack data structure ----------------------------------------\n\\ This is a general purpose stack utility used to implement necessary\n\\ stacks for the compiler or the user. Not real fast.\n\\ These stacks grow up which is different then normal.\n\\ cell 0 - stack pointer, offset from pfa of word\n\\ cell 1 - limit for range checking\n\\ cell 2 - first data location\n\n: :STACK ( #cells -- )\n CREATE 2 cells , ( offset of first data location )\n dup , ( limit for range checking, not currently used )\n cells cell+ allot ( allot an extra cell for safety )\n;\n\n: >STACK ( n stack -- , push onto stack, postincrement )\n dup @ 2dup cell+ swap ! ( -- n stack offset )\n + !\n;\n\n: STACK> ( stack -- n , pop , predecrement )\n dup @ cell- 2dup swap !\n + @\n;\n\n: STACK@ ( stack -- n , copy )\n dup @ cell- + @\n;\n\n: STACK.PICK ( index stack -- n , grab Nth from top of stack )\n dup @ cell- +\n swap cells - \\ offset for index\n @\n;\n: STACKP ( stack -- ptr , to next empty location on stack )\n\tdup @ +\n;\n\n: 0STACKP ( stack -- , clear stack)\n 8 swap !\n;\n\n32 :stack ustack\nustack 0stackp\n\n\\ Define JForth like words.\n: >US ustack >stack ;\n: US> ustack stack> ;\n: US@ ustack stack@ ;\n: 0USP ustack 0stackp ;\n\n\n\n\\ DO LOOP ------------------------------------------------\n\n3 constant do_flag\n4 constant leave_flag\n5 constant ?do_flag\n\n: DO ( -- , loop-back do_flag jump-from ?do_flag )\n ?comp\n compile (do)\n here >us do_flag >us ( for backward branch )\n; immediate\n\n: ?DO ( -- , loop-back do_flag jump-from ?do_flag , on user stack )\n ?comp\n ( leave address to set for forward branch )\n compile (?do)\n here 0 ,\n here >us do_flag >us ( for backward branch )\n >us ( for forward branch ) ?do_flag >us\n; immediate\n\n: LEAVE ( -- addr leave_flag )\n compile (leave)\n here 0 , >us\n leave_flag >us\n; immediate\n\n: LOOP-FORWARD ( -us- jump-from ?do_flag -- )\n BEGIN\n us@ leave_flag =\n us@ ?do_flag =\n OR\n WHILE\n us> leave_flag =\n IF\n us> here over - cell+ swap !\n ELSE\n us> dup\n here swap -\n cell+ swap !\n THEN\n REPEAT\n;\n\n: LOOP-BACK ( loop-addr do_flag -us- )\n us> do_flag ?pairs\n us> here - here\n !\n cell allot\n;\n\n: LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (loop)\n loop-forward loop-back\n; immediate\n\n\\ : DOTEST 5 0 do 333 . loop 888 . ;\n\\ : ?DOTEST0 0 0 ?do 333 . loop 888 . ;\n\\ : ?DOTEST1 5 0 ?do 333 . loop 888 . ;\n\n: +LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (+loop)\n loop-forward loop-back\n; immediate\n\n: UNLOOP ( loop-sys -r- )\n r> \\ save return pointer\n rdrop rdrop\n >r\n;\n\n\n: RECURSE ( ? -- ? , call the word currently being defined )\n latest compile,\n; immediate\n\n: SPACE bl emit ;\n: SPACES 512 min 0 max 0 ?DO space LOOP ;\n: 0SP depth 0 ?do drop loop ;\n\n\\ : >NEWLINE ( -- , CR if needed )\n\\ out @ 0>\n\\ IF cr\n\\ THEN\n\\ ;\n\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 ) swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 ) dup cell+ @ swap @ ;\n\n: DABS ( d -- |d| )\n dup 0<\n IF dnegate\n THEN\n;\n\n: S>D ( s -- d , extend signed single precision to double )\n dup 0<\n IF -1\n ELSE 0\n THEN\n;\n\n: D>S ( d -- s ) drop ;\n\n: PARSE-WORD ( \"name\" -- c-addr u ) bl parse ;\n: \/STRING ( addr len n -- addr' len' ) over min rot over + -rot - ;\n: PLACE ( addr len to -- , move string ) 3dup 1+ swap cmove c! drop ;\n\n: ASCII ( -- char, state smart )\n bl parse drop c@\n state @ 1 =\n IF [compile] literal\n ELSE\n THEN\n; immediate\n\n: CHAR ( -- char , interpret mode ) bl parse drop c@ ;\n: [CHAR] ( -- char , for compile mode )\n char [compile] literal\n; immediate\n\n: $TYPE ( $string -- ) count type ;\n: 'word ( -- addr ) here ;\n\n: EVEN ( addr -- addr' ) dup 1 and + ;\n\n: (C\") ( -- $addr ) r> dup count + aligned >r ;\n: (S\") ( -- c-addr cnt ) r> count 2dup + aligned >r ;\n: (.\") ( -- , type following string ) r> count 2dup + aligned >r type ;\n: \", ( addr len -- , place string into dict ) tuck 'word place 1+ allot align ;\n: ,\" ( -- ) [char] \" parse \", ;\n\n: .( ( --, type string delimited by parens )\n [char] ) parse type\n; immediate\n\n: .\" ( -- , type string )\n state @ 1 =\n IF compile (.\") ,\"\n ELSE [char] \" parse type\n THEN\n; immediate\n\n: .' ( -- , type string delimited by single quote )\n state @\n IF compile (.\") [char] ' parse \",\n ELSE [char] ' parse type\n THEN\n; immediate\n\n: C\" ( -- addr , return string address, ANSI )\n state @\n IF compile (c\") ,\"\n ELSE [char] \" parse pad place pad\n THEN\n; immediate\n\n: S\" ( -- , -- addr , return string address, ANSI )\n state @\n IF compile (s\") ,\"\n ELSE [char] \" parse pad place pad count\n THEN\n; immediate\n\n: \" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n: P\" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n\n\\ : \"\" ( -- addr )\n\\ state @\n\\ IF\n\\ compile (C\")\n\\ bl parse-word \",\n\\ ELSE\n\\ bl parse-word pad place pad\n\\ THEN\n\\ ; immediate\n\n: SLITERAL ( addr cnt -- , compile string )\n\tcompile (S\")\n\t\",\n; IMMEDIATE\n\n: $APPEND ( addr count $1 -- , append text to $1 )\n over >r\n dup >r\n count + ( -- a2 c2 end1 )\n swap cmove\n r> dup c@ ( a1 c1 )\n r> + ( -- a1 totalcount )\n swap c!\n;\n\n\\ ANSI word to replace [COMPILE] and COMPILE ----------------\n\\ : POSTPONE ( -- )\n\\\tbl word find\n\\\tdup 0=\n\\\tIF\n\\\t\t.\" Postpone could not find \" count type cr abort\n\\\tELSE\n\\\t\t0>\n\\\t\tIF compile, \\ immediate\n\\\t\tELSE (compile) \\ normal\n\\\t\tTHEN\n\\\tTHEN\n\\ ; immediate\n\n\\ -----------------------------------------------------------------\n\\ Auto Initialization\n: AUTO.INIT ( -- )\n\\ Kernel finds AUTO.INIT and executes it after loading dictionary.\n\\\t.\" Begin AUTO.INIT ------\" cr\n;\n: AUTO.TERM ( -- )\n\\ Kernel finds AUTO.TERM and executes it on bye.\n\\\t.\" End AUTO.TERM ------\" cr\n;\n\n\n: CLEARSTACK ( i*x -- )\n BEGIN depth\n WHILE drop\n REPEAT ;\n\nvariable pictured_output \\ hidden?\nvariable pictured_output_len \\ hidden?\n\n: <# ( -- ) pad pictured_output ! 0 pictured_output_len ! ;\n: #> ( -- addr n ) drop pictured_output @ pictured_output_len @ ;\n\n: HOLD ( c -- )\n pictured_output @ dup dup 1+ pictured_output_len @ cmove c!\n 1 pictured_output_len +!\n;\n\n\\ ------------------------ INPUT -------------------------------\n\n: SIGN ( n -- ) < 0 IF 45 hold THEN\n;\n\n: DIGIT ( n -- ascii )\n dup 10 < IF 48 ELSE 87 THEN + ;\n\n: # ( n -- n )\n base @ \/mod swap digit hold ;\n\n: #S ( n -- )\n BEGIN base @ \/mod dup\n WHILE swap digit hold\n REPEAT\n digit hold ;","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"c5722b2f14f090611ecd61cf73ed9468fca23092","subject":"Update test.4th","message":"Update test.4th","repos":"AshleyF\/Forthkit,AshleyF\/Forthkit,AshleyF\/Forthkit","old_file":"hardware\/register\/test.4th","new_file":"hardware\/register\/test.4th","new_contents":"( simple assembler\/VM test - capitalize [-32] console input )\n( requires assembler )\n\n0 const u\n1 const c\n\n 32 u ldc,\n label &start\n c in,\n c u c sub,\n c out,\n&start jump,\n\nassemble\n","old_contents":"( simple assembler\/VM test - capitalize [-32] console input )\n( requires assembler )\n\n0 const u ( to upper )\n1 const c ( char )\n\n 32 u ldc,\n label &start\n c in,\n c u c sub,\n c out,\n&start jump,\n\nassemble\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"4e2bfb4de70b87d15afdcf0c6adc9e0a7f587948","subject":"Pictured output","message":"Pictured output","repos":"rm-hull\/byok,rm-hull\/byok,rm-hull\/byok,rm-hull\/byok","old_file":"forth\/src\/forth\/system.fth","new_file":"forth\/src\/forth\/system.fth","new_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\ \n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n \n: COUNT dup 1+ swap c@ ;\n\n\\ Miscellaneous support words\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: CELL+ ( n -- n+cell ) cell + ;\n: CELL- ( n -- n-cell ) cell - ;\n: CELL* ( n -- n*cell ) cells ;\n\n: CHAR+ ( n -- n+size_of_char ) 1+\n\\ : CHARS ( n -- n*size_of_char, don't do anything ) ; immediate\n\n\\ useful stack manipulation words\n: -ROT ( a b c -- c a b ) rot rot ;\n: 3DUP ( a b c -- a b c a b c ) 2 pick 2 pick 2 pick ;\n\n\\ ------------------------------------------------------------------\n: ID. ( nfa -- ) count 31 and type ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: PAD ( -- addr ) here 128 + ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: ? ( -- ) @ . ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ ' (lit) , cell 1- , ] +\n [ ' (lit) , cell 1- invert , ] and ;\n\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n: ALLOT ( nbytes -- , allot space in dictionary ) dp +! align ;\n\n: C, ( c -- ) here c! 1 dp +! ;\n\\ : W, ( w -- ) dp @ even-up dup dp ! w! 2 dp +! ;\n\\ : , ( n -- , lay into dictionary ) align here ! cell allot ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token ) \n [compile] literal ( compile a call to literal )\n ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n: :NONAME ( -- xt , begin compilation of headerless secondary ) align here ] ;\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick ) \n ?comp ' [compile] literal \n; immediate\n\n: RECURSE ( ? -- ? , call the word currently being defined ) \n latest compile, \n; immediate\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 ) swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 ) dup cell+ @ swap @ ;\n\n: \/STRING ( addr len n -- addr' len' ) over min rot over + -rot - ;\n: PLACE ( addr len to -- , move string ) 3dup 1+ swap cmove c! drop ;\n\n: ASCII ( -- char, state smart )\n bl parse drop c@\n state @ 1 =\n IF [compile] literal\n ELSE \n THEN \n; immediate\n\n: CHAR ( -- char , interpret mode ) bl parse drop c@ ;\n: [CHAR] ( -- char , for compile mode )\n char [compile] literal \n; immediate\n\n: 'word ( -- addr ) here ;\n\n: (C\") ( -- $addr ) r> dup count + aligned >r ;\n: (S\") ( -- c-addr cnt ) r> count 2dup + aligned >r ;\n: (.\") ( -- , type following string ) r> count 2dup + aligned >r type ;\n: \", ( addr len -- , place string into dict ) tuck 'word place 1+ allot align ;\n: ,\" ( -- ) 34 parse \", ;\n\n: .( ( --, type string delimited by parens )\n 41 parse type\n; immediate\n\n: .\" ( -- , type string )\n state @ 1 =\n IF compile (.\") ,\"\n ELSE 34 parse type\n THEN \n; immediate\n\n: SEE ( -- )\n ' dup\n 16 + @ \\ offset in execution token for alloc size\n cells swap >body swap\n disassemble ;\n \n: CLEARSTACK ( i*x -- )\n BEGIN depth\n WHILE drop\n REPEAT ;\n\nvariable pictured_output \\ hidden?\nvariable pictured_output_len \\ hidden?\n\n: <# ( -- ) pad pictured_output ! 0 pictured_output_len ! ;\n: #> ( -- addr n ) drop pictured_output @ pictured_output_len @ ;\n\n: HOLD ( c -- )\n pictured_output @ dup dup 1+ pictured_output_len @ cmove c!\n 1 pictured_output_len +!\n;\n\n: DIGIT ( n -- ascii )\n dup 10 < IF 48 ELSE 87 THEN + ;\n\n: SIGN ( n -- ) < 0 IF 45 hold THEN\n;\n: # ( n -- n )\n base @ \/mod swap digit hold ;\n\n: #S ( n -- )\n BEGIN base @ \/mod dup \n WHILE swap digit hold \n REPEAT \n digit hold ;\n\n","old_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\ \n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n \n: COUNT dup 1+ swap c@ ;\n\n\\ Miscellaneous support words\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: CELL+ ( n -- n+cell ) cell + ;\n: CELL- ( n -- n-cell ) cell - ;\n: CELL* ( n -- n*cell ) cells ;\n\n: CHAR+ ( n -- n+size_of_char ) 1+\n\\ : CHARS ( n -- n*size_of_char, don't do anything ) ; immediate\n\n\\ useful stack manipulation words\n: -ROT ( a b c -- c a b ) rot rot ;\n: 3DUP ( a b c -- a b c a b c ) 2 pick 2 pick 2 pick ;\n\n\\ ------------------------------------------------------------------\n: ID. ( nfa -- ) count 31 and type ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: PAD ( -- addr ) here 128 + ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: ? ( -- ) @ . ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ ' (lit) , cell 1- , ] +\n [ ' (lit) , cell 1- invert , ] and ;\n\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n: ALLOT ( nbytes -- , allot space in dictionary ) dp +! align ;\n\n: C, ( c -- ) here c! 1 dp +! ;\n\\ : W, ( w -- ) dp @ even-up dup dp ! w! 2 dp +! ;\n\\ : , ( n -- , lay into dictionary ) align here ! cell allot ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token ) \n [compile] literal ( compile a call to literal )\n ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n: :NONAME ( -- xt , begin compilation of headerless secondary ) align here ] ;\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick ) \n ?comp ' [compile] literal \n; immediate\n\n: RECURSE ( ? -- ? , call the word currently being defined ) \n latest compile, \n; immediate\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 ) swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 ) dup cell+ @ swap @ ;\n\n: \/STRING ( addr len n -- addr' len' ) over min rot over + -rot - ;\n: PLACE ( addr len to -- , move string ) 3dup 1+ swap cmove c! drop ;\n\n: ASCII ( -- char, state smart )\n bl parse drop c@\n state @ 1 =\n IF [compile] literal\n ELSE \n THEN \n; immediate\n\n: CHAR ( -- char , interpret mode ) bl parse drop c@ ;\n: [CHAR] ( -- char , for compile mode )\n char [compile] literal \n; immediate\n\n: 'word ( -- addr ) here ;\n\n: (C\") ( -- $addr ) r> dup count + aligned >r ;\n: (S\") ( -- c-addr cnt ) r> count 2dup + aligned >r ;\n: (.\") ( -- , type following string ) r> count 2dup + aligned >r type ;\n: \", ( addr len -- , place string into dict ) tuck 'word place 1+ allot align ;\n: ,\" ( -- ) 34 parse \", ;\n\n: .( ( --, type string delimited by parens )\n 41 parse type\n; immediate\n\n: .\" ( -- , type string )\n state @ 1 =\n IF compile (.\") ,\"\n ELSE 34 parse type\n THEN \n; immediate\n\n: SEE ( -- )\n ' dup\n 16 + @ \\ offset in execution token for alloc size\n cells swap >body swap\n disassemble ;\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"e3a2b3dcc33d46d57366aaff6869489b1d571ca2","subject":"Improved block editor slightly","message":"Improved block editor slightly\n\nThe block editor has been improved and a few things have been\nrenamed as other Forth interpreters name words.\n","repos":"howerj\/libforth","old_file":"forth.fth","new_file":"forth.fth","new_contents":"#!.\/forth \n( Welcome to libforth, A dialect of Forth. Like all versions of Forth this\nversion is a little idiosyncratic, but how the interpreter works is\ndocumented here and in various other files.\n\nThis file contains most of the start up code, some basic start up code\nis executed in the C file as well which makes programming at least bearable.\nMost of Forth is programmed in itself, which may seem odd if your back\nground in programming comes from more traditional language [such as C],\nalthough less so if you know already know lisp.\n\nFor more information about this interpreter and Forth see:\n\thttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\treadme.md : for a manual for this interpreter\n\tlibforth.h : for information about the C API\n\tlibforth.c : for the interpreter itself\n\tunit.c : a series of unit tests against libforth.c\n\tunit.fth : a series of unit tests against this file\n\nThe interpreter and this code originally descend from a Forth interpreter\nwritten in 1992 for the International obfuscated C Coding Competition\n\nSee:\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\nThe manual for the interpreter should be read first before looking into this\ncode. It is important to understand the execution model of Forth, especially\nthe differences between command and compile mode, and how immediate and compiling\nwords work.\n\n@todo Restructure and describe structure of this file.\n\nEach of these sections is clearly labeled and they are generally in dependency order.\n\nUnfortunately the code in this file is not as portable as it could be, it makes\nassumptions about the size of cells provided by the virtual machine, which will\ntake time to rectify. Some of the constructs are subtly different from the\nDPANs Forth specification, which is usually noted. Eventually this should\nalso be fixed.)\n\n( ========================== Basic Word Set ================================== )\n\n( \nWe'll begin by defining very simple words we can use later, these a very\nbasic words, that perform simple tasks, they will not require much explanation.\n\nEven though the words are simple, their stack comment and a description for\nthem will still be included so external tools can process and automatically\nextract the document string for a given work.\n)\n\n: postpone ( -- : postpone execution of the following immediate word )\n\timmediate find , ;\n\n: :: ( -- : compiling version of ':' )\n\t[ find : , ] ;\n\n: constant \n\t:: ( compile word header )\n\there 1 - h ! ( decrement dictionary pointer )\n\there @ instruction-mask invert and doconst or here ! ( change instruction to CONST )\n\there 1 + h ! ( increment dictionary pointer )\n\t, ( write in value )\n\tpostpone [ ; ( back into command mode )\n\n( space saving measure )\n-1 constant -1\n 0 constant 0 \n 1 constant 1\n 2 constant 2\n 3 constant 3\n\n0 constant false\n1 constant true ( @warning not standards compliant )\n\n10 constant nl ( new line )\n\n1 hidden-bit lshift constant hidden-mask ( mask for the hide bit in a words CODE field )\n\n-1 -1 1 rshift invert and constant min-signed-integer\n\nmin-signed-integer invert constant max-signed-integer\n\n1 constant cell ( size of a cell in address units )\n\ncell size 8 * * constant address-unit-bits ( the number of bits in an address )\n\n-1 -1 1 rshift and invert constant sign-bit ( bit corresponding to the sign in a number )\n\n( @todo test by how much, if at all, making words like 1+, 1-, <>, and other\nsimple words, part of the interpreter would speed things up )\n\n: 1+ ( x -- x : increment a number ) \n\t1 + ;\n\n: 1- ( x -- x : decrement a number ) \n\t1 - ;\n\n: chars ( c-addr -- addr : convert a character address to an address )\n\tsize \/ ; \n\n: chars> ( addr -- c-addr: convert an address to a character address )\n\tsize * ; \n\n: tab ( -- : print a tab character to current output device )\n\t9 emit ;\n\n: 0= ( x -- bool : is 'x' equal to zero? )\n\t0 = ;\n\n: not ( x -- bool : is 'x' true? )\n\t0= ;\n\n: <> ( x x -- bool : not equal )\n\t= 0= ;\n\n: logical ( x -- bool : turn a value into a boolean ) \n\tnot not ;\n\n( @todo \": dolit ' ' ;\" works but does not interact well with \n'decompile', if this was fixed the special work could be removed,\nwith some extra effort in libforth.c as well )\n: dolit ( -- x : location of special \"push\" word )\n\t2 ; \n\n: 2, ( x x -- : write two values into the dictionary )\n\t, , ;\n\n: [literal] ( x -- : write a literal into the dictionary )\n\tdolit 2, ; \n\n: literal ( x -- : immediately write a literal into the dictionary )\n\timmediate [literal] ;\n\n: sliteral immediate ( I: c-addr u --, Run: -- c-addr u )\n\tswap [literal] [literal] ;\n\n( @todo throw if not found )\n: ['] ( I: c\" xxx\", Run: -- xt )\n\timmediate find [literal] ;\n\n: >instruction ( CODE -- Instruction : extract instruction from instruction field ) \n\tinstruction-mask and ;\n\n: immediate-mask ( -- x : pushes the mask for the compile bit in a words CODE field )\n\t[ 1 compile-bit lshift ] literal ;\n\n: hidden? ( PWD -- PWD bool : is a word hidden, given the words PWD field ) \n\tdup 1+ @ hidden-mask and logical ;\n\n: compiling? ( PWD -- PWD bool : is a word immediate, given the words PWD field )\n\tdup 1+ @ immediate-mask and logical ;\n\n\n: cr ( -- : emit a newline character )\n\tnl emit ;\n\n: < ( x1 x2 -- bool : signed less than comparison )\n\t- dup if max-signed-integer u> else logical then ;\n\n: > ( x1 x2 -- bool : signed greater than comparison )\n\t- dup if max-signed-integer u< else logical then ;\n\n: #pad ( -- u : offset into pad area )\n\t64 ;\n\n: pad\n\t( the pad is used for temporary storage, and moves\n\talong with dictionary pointer, always in front of it )\n\there #pad + ;\n\n( @todo this can be improved a lot, currently it uses more\nspace than it has to, 4 cells instead of three.\n\nIt does:\n\n\tpush value\n\tpush value\n\nInstead of:\n\n\tmagic-2literal-word\n\tvalue\n\tvalue\n\n)\n: 2literal immediate ( x x -- : immediate write two literals into the dictionary )\n\tswap [literal] [literal] ;\n\n: latest ( get latest defined word )\n\tpwd @ ; \n\n: stdin ( -- fileid : push the fileid for the standard input channel ) \n\t`stdin @ ;\n\n: stdout ( -- fileid : push the fileid for the standard output channel ) \n\t`stdout @ ;\n\n: stderr ( -- fileid : push the fileid for the standard error channel ) \n\t`stderr @ ;\n\n: stdin? ( -- bool : are we reading from standard input )\n\t`fin @ stdin = ;\n\n: *+ ( x1 x2 x3 -- x ) \n\t* + ;\n\t\n: 2- ( x -- x : decrement by two )\n\t2 - ( x -- x ) ;\n\n: 2+ ( x -- x : increment by two )\n\t2 + ( x -- x ) ;\n\n: 3+ ( x -- x : increment by three )\n\t3 + ( x -- x ) ;\n\n: 2* ( x -- x : multiply by two )\n\t1 lshift ( x -- x ) ;\n\n: 2\/ ( x -- x : divide by two )\n\t1 rshift ( x -- x ) ;\n\n: 4* ( x -- x : multiply by four )\n\t2 lshift ( x -- x ) ;\n\n: 4\/ ( x -- x : divide by four )\n\t2 rshift ( x -- x ) ;\n\n: 8* ( x -- x : multiply by eight )\n\t3 lshift ( x -- x ) ;\n\n: 8\/ ( x -- x : divide by eight )\n\t3 rshift ( x -- x ) ;\n\n: 256* ( x -- x : multiply by 256 )\n\t8 lshift ( x -- x ) ;\n\n: 256\/ ( x -- x : divide by 256 )\n\t8 rshift ( x -- x ) ;\n\n: 2dup ( x1 x2 -- x1 x2 x1 x2 : duplicate two values )\n\tover over ;\n\n: mod ( x u -- x : calculate the remainder of x divided by u ) \n\t2dup \/ * - ;\n\n( @todo implement um\/mod in the VM, then use this to implement \/ and mod )\n: um\/mod ( x1 x2 -- rem quot : calculate the remainder and quotient of x1 divided by x2 ) \n\t2dup \/ >r mod r> ;\n\n: *\/ ( x1 x2 x3 -- x4 : multiply then divide, @warning this does not use a double cell for the multiply )\n\t * \/ ; \n\n: char ( -- x : read in a character from the input steam )\n\tkey drop key ;\n\n: [char] ( -- x : immediately read in a character from the input stream )\n\timmediate char [literal] ;\n\n: compose ( xt1 xt2 -- xt3 : create a new function from two xt-tokens )\n\t>r >r ( save execution tokens )\n\tpostpone :noname ( create a new :noname word for our xt-tokens )\n\tr> , ( write first token )\n\tr> , ( write second token )\n\tpostpone ; ; ( terminate new :noname )\n\n: unless ( bool -- : like 'if' but execute clause if false )\n\timmediate ['] 0= , postpone if ;\n\n: endif ( synonym for 'then' ) \n\timmediate postpone then ;\n\n: cells ( n1 -- n2 : convert a number of cells into a number of cells in address units ) \n\timmediate ;\n\n: cell+ ( a-addr1 -- a-addr2 ) \n\tcell + ;\n\n: negative? ( x -- bool : is a number negative? )\n\tsign-bit and logical ;\n\n: mask-byte ( x -- x : generate mask byte ) \n\t8* 255 swap lshift ;\n\n: select-byte ( u i -- c ) \n\t8* rshift 0xff and ;\n\n: xt-instruction ( extract instruction from execution token )\n\tcell+ @ >instruction ;\n\n: defined-word? ( CODE -- bool : is a word a defined or a built in words )\n\txt-instruction dolist = ;\n\n: char+ ( c-addr -- c-addr : increment a character address by the size of one character ) \n\t1+ ;\n\n: 2chars ( c-addr1 c-addr2 -- addr addr : convert two character addresses to two cell addresses ) \n\tchars swap chars swap ;\n\n: 2chars> ( addr addr -- c-addr c-addr: convert two cell addresses to two character addresses )\n\tchars> swap chars> swap ;\n\n: hex ( -- : print out hex ) \n\t16 base ! ;\n\n: octal ( -- : print out octal ) \n\t8 base ! ;\n\n: binary ( -- : print out binary ) \n\t2 base ! ;\n\n: decimal ( -- : print out decimal ) \n\t0 base ! ;\n\n: negate ( x -- x ) \n\t-1 * ;\n\n: abs ( x -- u : return the absolute value of a number )\n\tdup negative? if negate then ;\n\n: square ( x -- x ) \n\tdup * ;\n\n: sum-of-squares ( a b -- c : compute a^2 + b^2 to get c )\n\tsquare swap square + ;\n\n: drup ( x y -- x x ) \n\tdrop dup ;\n\n: +! ( x addr -- : add x to a value stored at addr ) \n\ttuck @ + swap ! ;\n\n: 1+! ( addr -- : increment a value at an address ) \n\t1 swap +! ;\n\n: 1-! ( addr -- : decrement a value at an address ) \n\t-1 swap +! ;\n\n: c+! ( x c-addr -- : add x to a value stored at c-addr )\n\ttuck c@ + swap c! ;\n\n: toggle ( addr u -- : complement the value at address with the bit pattern u ) \n\tover @ xor swap ! ;\n\n: lsb ( x -- x : mask off the least significant byte of a cell ) \n\t255 and ;\n\n: \\ ( -- : immediate word, used for single line comments )\n\timmediate begin key nl = until ;\n\n: ?dup ( x -- ? ) \n\tdup if dup then ;\n\n: min ( x y -- min : return the minimum of two integers ) \n\t2dup < if drop else swap drop then ;\n\n: max ( x y -- max : return the maximum of two integers ) \n\t2dup > if drop else swap drop then ;\n\n: limit ( x min max -- x : limit x with a minimum and maximum )\n\trot min max ;\n\n: >= ( x y -- bool ) \n\t< not ;\n\n: <= ( x y -- bool ) \n\t> not ;\n\n: 2@ ( a-addr -- x1 x2 : load two consecutive memory cells )\n\tdup 1+ @ swap @ ;\n\n: 2! ( x1 x2 a-addr -- : store two values as two consecutive memory cells )\n\t2dup ! nip 1+ ! ;\n\n: r@ ( -- x, R: x -- )\n\tr> r @ swap >r ;\n\n: rp@ ( -- x, R: x -- )\n\tr> r @ swap >r ;\n\n( @todo r!, rp! )\n\n: 0> ( x -- bool )\n\t0 > ;\n\n: 0< ( x -- bool )\n\t0 < ;\n\n: 0<> ( x -- bool )\n\t0 <> ;\n\n: signum ( x -- -1 | 0 | 1 : )\n\tdup 0< if drop -1 exit then\n\t 0> if 1 exit then\n\t0 ;\n\n: nand ( x x -- x : bitwise NAND ) \n\tand invert ;\n\n: odd ( x -- bool : is 'x' odd? )\n\t1 and ;\n\n: even ( x -- bool : is 'x' even? )\n\todd not ;\n\n: nor ( x x -- x : bitwise NOR ) \n\tor invert ;\n\n: ms ( u -- : wait at least 'u' milliseconds ) \n\tclock + begin dup clock u< until drop ;\n\n: sleep ( u -- : sleep for 'u' seconds )\n\t1000 * ms ;\n\n: align ( addr -- addr : align an address, nop in this implemented )\n\timmediate ; \n\n: ) ( -- : do nothing, this allows easy commenting out of code )\n\timmediate ;\n\n: bell ( -- : emit an ASCII BEL character ) \n\t7 emit ;\n\n: b\/buf ( -- u : bytes per buffer ) \n\t1024 ;\n\n: .d ( x -- x : debug print ) \n\tdup . ;\n\n: compile, ( x -- : )\n\t, ;\n\n: >mark ( -- : write a hole into the dictionary and push a pointer to it ) \n\there 0 , ;\n\n: r - r> u< ;\n\n: invalidate ( -- : invalidate this Forth core )\n\t1 `invalid ! ;\n\n: signed ( x -- bool : return true if sign bit set ) \n\t[ 1 size 8 * 1- lshift ] literal and logical ;\n\n: u>= ( x y -- bool : unsigned greater than or equal to )\n\t2dup u> >r = r> or ;\n\n: u<= ( x y -- bool : unsigned less than or equal to )\n\tu>= not ;\n\n: rdrop ( R: x -- : drop a value from the return stack )\n\tr> ( get caller's return address )\n\tr> ( get value to drop )\n\tdrop ( drop it like it's hot )\n\t>r ; ( return return address )\n\n: rdup\n\tr> ( get caller's return address )\n\tr> ( get value to duplicate )\n\tdup ( ... )\n\t>r >r >r ; ( make it all work )\n\n: again immediate\n\t( loop unconditionally in a begin-loop:\n\t\tbegin ... again )\n\t' branch , ;\n\n: source ( -- c-addr u )\n\t#tib ( size of input buffer, in characters )\n\ttib ; ( start of input buffer, in characters )\n\n: stdin? ( -- bool : are we reading from standard in? )\n\t`fin @ `stdin @ = ;\n\n: source-id ( -- 0 | -1 | file-id )\n\t( \t\n\tValue Input Source\n\t-1 String\n\t0 Reading from user input \/ standard in\n\tfile-id )\n\t`source-id @ \n\t0= if\n\t\tstdin? if 0 else `fin @ then\n\telse\n\t\t-1\n\tthen ;\n\n: under ( x1 x2 -- x1 x1 x2 )\n\t>r dup r> ;\n\n: 2nip ( n1 n2 n3 n4 -- n3 n4 ) \n\t>r >r 2drop r> r> ;\n\n: 2over ( n1 n2 n3 n4 \u2013 n1 n2 n3 n4 n1 n2 )\n\t>r >r 2dup r> swap >r swap r> r> -rot ;\n\n: 2swap ( n1 n2 n3 n4 \u2013 n3 n4 n1 n2 )\n\t>r -rot r> -rot ;\n\n: 2tuck ( n1 n2 n3 n4 \u2013 n3 n4 n1 n2 n3 n4 )\n\t2swap 2over ;\n\n: 3drop ( x1 x2 x3 -- )\n\t2drop ;\n\n: nos1+ ( x1 x2 -- x1+1 x2 : increment the next variable on that stack )\n\tswap 1+ swap ;\n\n: ?dup-if immediate ( x -- x | - : ?dup and if rolled into one! )\n\t['] ?dup , postpone if ;\n\n: ?if ( -- : non destructive if ) \n\timmediate ['] dup , postpone if ;\n\n: hide ( token -- hide-token : this hides a word from being found by the interpreter )\n\t?dup-if\n\t\tdup @ hidden-mask or swap tuck ! exit\n\tthen 0 ;\n\n: hider ( WORD -- : hide with drop ) \n\tfind dup if hide then drop ;\n\n: reveal ( hide-token -- : reveal a hidden word ) \n\tdup @ hidden-mask invert and swap ! ;\n\n: ?exit ( x -- : exit current definition if not zero ) \n\tif rdrop exit then ;\n\n: number? ( c -- f : is character a number? )\n\t[char] 0 [ char 9 1+ ] literal within ;\n\n: lowercase? ( c -- f : is character lower case? )\n\t[char] a [ char z 1+ ] literal within ;\n\n: uppercase? ( C -- f : is character upper case? )\n\t[char] A [ char Z 1+ ] literal within ;\n\n: alpha? ( C -- f : is character part of the alphabet? )\n\tdup lowercase? swap uppercase? or ;\n\n: alphanumeric? ( C -- f : is character alphabetic or a number ? )\n\tdup alpha? swap number? or ;\n\n: printable? ( c -- bool : is printable, excluding new lines and tables )\n\t32 127 within ;\n\n: >upper ( c -- C : convert char to uppercase iff lower case )\n\tdup lowercase? if bl xor then ;\n\n: >lower ( C -- c : convert char to lowercase iff upper case )\n\tdup uppercase? if bl xor then ;\n\n: <=> ( x y -- z : spaceship operator! )\n\t2dup\n\t> if 2drop -1 exit then\n\t< ;\n\n: start-address ( -- c-addr : push the start address )\n\t`start-address @ ;\n\n: >real-address ( c-addr -- r-addr : convert an interpreter address to a real address )\n\tstart-address + ;\n\n: real-address> ( c-addr -- r-addr : convert a real address to an interpreter address )\n\tstart-address - ;\n\n: peek ( r-addr -- n : )\n\tpad chars> >real-address swap size memory-copy pad @ ;\n\n: poke ( n r-addr -- : )\n\tswap pad ! pad chars> >real-address size memory-copy ;\n\n: die! ( x -- : controls actions when encountering certain errors )\n\t`error-handler ! ;\n\n: start! ( cfa -- : set the word to execute at startup )\n\t`instruction ! ;\t\n\n: warm ( -- : restart the interpreter, warm restart )\n\t1 restart ;\n\n: trip ( x -- x x x : triplicate a number ) \n\tdup dup ;\n\n: roll ( xu xu-1 ... x0 u -- xu-1 ... x0 xu : move u+1 items on the top of the stack by u )\n\tdup 0 >\n\tif\n\t\tswap >r 1- roll r> swap\n\telse\n\t\tdrop\n\tthen ;\n\n: 2rot ( n1 n2 n3 n4 n5 n6 \u2013 n3 n4 n5 n6 n1 n2 )\n\t5 roll 5 roll ;\n\n: s>d ( x -- d : convert a signed value to a double width cell )\n\t( @note the if...else...then is only necessary as this Forths\n\tbooleans are 0 and 1, not 0 and -1 as it usually is )\n\tdup 0< if -1 else 0 then ;\n\n: trace ( level -- : set tracing level )\n\t`debug ! ;\n\n: verbose ( -- : get the log level )\n\t`debug @ ;\n\n: count ( c-addr1 -- c-addr2 u : get a string whose first char is its length )\n\tdup c@ nos1+ ;\n\n: bounds ( x y -- y+x x : make an upper and lower bound )\n\tover + swap ;\n\n: aligned ( unaligned -- aligned : align a pointer )\n\t[ size 1- ] literal + \n\t[ size 1- ] literal invert and ;\n\n: rdepth\n\tmax-core `stack-size @ - r @ swap - ;\n\n: r.s ( -- : print the contents of the return stack )\n\tr> \n\t[char] < emit rdepth . [char] > emit\n\tspace\n\trdepth dup 0> if dup\n\tbegin dup while r> -rot 1- repeat drop dup\n\tbegin dup while rot dup . >r 1- repeat drop\n\tthen drop cr \n\t>r ;\n\n: argv ( -- r-addr : push pointer to array of string pointers to program )\n\t`argv @ ;\n\n: argc ( -- u : push the number of arguments in the argv array )\n\t`argc @ ;\n\n: +- ( x1 x2 -- x3 : copy the sign of x1 to x2 giving x3 )\n\t[ sign-bit 1- ] literal and\n\tswap\n\tsign-bit and or\n\t;\n\nhider stdin?\n\n( ================================== DUMP ================================== )\n\\ : newline ( x -- x+1 : print a new line every fourth value )\n\\ \tdup 3 and 0= if cr then 1+ ;\n\\ \n\\ : address ( num count -- count : print current address we are dumping every fourth value )\n\\ \tdup >r\n\\ \t1- 3 and 0= if . [char] : emit space else drop then\n\\ \tr> ;\n\\ \n\\ : dump ( start count -- : print the contents of a section of memory )\n\\ \\\thex ( switch to hex mode )\n\\ \t1 >r ( save counter on return stack )\n\\ \tover + swap ( calculate limits: start start+count )\n\\ \tbegin \n\\ \t\t2dup u> ( stop if gone past limits )\n\\ \twhile \n\\ \t\tdup r> address >r\n\\ \t\tdup @ . 1+ \n\\ \t\tr> newline >r\n\\ \trepeat \n\\ \tr> drop\n\\ \t2drop ;\n\\ \n\\ hider newline\n\\ hider address \n( ================================== DUMP ================================== )\n\n: cfa immediate ( find-address -- cfa )\n\t( Given the address of the PWD field of a word this\n\tfunction will return an execution token for the word )\n\t( @todo if < dictionary start PWD is invalid )\n\t ;\n\n\\ : >body ( xt -- a-addr : a-addr is data field of a CREATEd word )\n\\\tcfa 5 + ;\n\n\n: execute ( xt -- : given an execution token, execute the word )\n\t( create a word that pushes the address of a hole to write to.\n\tA literal takes up two words, '!' takes up one, that's right,\n\tsome self modifying code! )\n\t[ here 3 cells + literal ] ( calculate place to write to )\n\t! ( write an execution token to a hole )\n\t[ 0 , ] ; ( this is the hole we write )\n\n( See: http:\/\/lars.nocrew.org\/dpans\/dpans9.htm\n@todo turn this into a lookup table of strings\n\n Code Reserved for\n ---- ------------\n -1 ABORT\n -2 ABORT\"\n -3 stack overflow\n -4 stack underflow\n -5 return stack overflow\n -6 return stack underflow\n -7 do-loops nested too deeply during execution\n -8 dictionary overflow\n -9 invalid memory address\n -10 division by zero\n -11 result out of range\n -12 argument type mismatch\n -13 undefined word\n -14 interpreting a compile-only word\n -15 invalid FORGET\n -16 attempt to use zero-length string as a name\n -17 pictured numeric output string overflow\n -18 parsed string overflow\n -19 definition name too long\n -20 write to a read-only location\n -21 unsupported operation [e.g., AT-XY on a\n too-dumb terminal]\n -22 control structure mismatch\n -23 address alignment exception\n -24 invalid numeric argument\n -25 return stack imbalance\n -26 loop parameters unavailable\n -27 invalid recursion\n -28 user interrupt\n -29 compiler nesting\n -30 obsolescent feature\n -31 >BODY used on non-CREATEd definition\n -32 invalid name argument [e.g., TO xxx]\n -33 block read exception\n -34 block write exception\n -35 invalid block number\n -36 invalid file position\n -37 file I\/O exception\n -38 non-existent file\n -39 unexpected end of file\n -40 invalid BASE for floating point conversion\n -41 loss of precision\n -42 floating-point divide by zero\n -43 floating-point result out of range\n -44 floating-point stack overflow\n -45 floating-point stack underflow\n -46 floating-point invalid argument\n -47 compilation word list deleted\n -48 invalid POSTPONE\n -49 search-order overflow\n -50 search-order underflow\n -51 compilation word list changed\n -52 control-flow stack overflow\n -53 exception stack overflow\n -54 floating-point underflow\n -55 floating-point unidentified fault\n -56 QUIT\n -57 exception in sending or receiving a character\n -58 [IF], [ELSE], or [THEN] exception )\n\n( @todo integrate catch\/throw into the interpreter as primitives )\n: catch ( xt -- exception# | 0 : return addr on stack )\n\tsp@ >r ( xt : save data stack pointer )\n\t`handler @ >r ( xt : and previous handler )\n\tr@ `handler ! ( xt : set current handler )\n\texecute ( execute returns if no throw )\n\tr> `handler ! ( restore previous handler )\n\tr> drop ( discard saved stack ptr )\n\t0 ; ( 0 : normal completion )\n\n( @todo use this everywhere )\n: throw ( ??? exception# -- ??? exception# )\n\t?dup-if ( exc# \\ 0 throw is no-op )\n\t\t`handler @ r ! ( exc# : restore prev return stack )\n\t\tr> `handler ! ( exc# : restore prev handler )\n\t\tr> swap >r ( saved-sp : exc# on return stack )\n\t\tsp! drop r> ( exc# : restore stack )\n\t\t( return to the caller of catch because return )\n\t\t( stack is restored to the state that existed )\n\t\t( when catch began execution )\n\tthen ; \n\n: interpret ( c1\" xxx\" ... cn\" xxx\" -- : This word implements the interpreter loop )\n\tbegin \n\t' read catch \n\t?dup-if [char] ! emit tab . cr then ( exception handler of last resort )\n\tagain ;\n\n: [interpret] ( c1\" xxx\" ... cn\" xxx\" -- : immediate version of interpret )\n\timmediate interpret ;\n\ninterpret ( use the new interpret word, which can catch exceptions )\n\nfind [interpret] cell+ start! ( the word executed on restart is now our new word )\n\n\n( ========================== Basic Word Set ================================== )\n\n( ========================== DOER\/MAKE ======================================= )\n( DOER\/MAKE is a word set that is quite powerful and is described in Leo Brodie's\nbook \"Thinking Forth\". It can be used to make words whose behavior can change\nafter they are defined. It essentially makes the structured use of self-modifying\ncode possible, along with the more common definitions of \"defer\/is\".\n\nAccording to \"Thinking Forth\", it has two purposes:\n\n1. To change the state of a function.\n2. To factor out common phrases of a words definition.\n\nAn example of the first instance:\n\n\tdoer say\n\t: sad \" Good bye, cruel World!\" cr ;\n\t: happy \" Hello, World!\" cr ;\n\n\t: person say ;\n\n\tmake person happy\n\tperson \\ prints \"Good bye, cruel World!\"\n\n\tmake person sad \n\tperson \\ prints \"Hello, World!\" \n\nAn example of the second:\n\n\tdoer op\n\n\t: sum \\ n0 ... nX X -- sum<0..X> \n\t\tmake op + 1 do op loop ;\n\n\t: mul \\ n0 ... nX X -- mul<0..X> \n\t\tmake op * 1 do op loop ;\n\nThe above example is a bit contrived, the definitions and functionality\nare too simple for this to be worth factoring out, but it shows how you\ncan use DOER\/MAKE. )\n\n: noop ; ( -- : default word to execute for doer )\n\n: doer ( c\" xxx\" -- : )\n\t:: ['] noop , postpone ; ;\n\n: found? ( xt -- xt : thrown an exception if the execution token is zero [not found] ) \n\tdup 0= if -13 throw then ;\n\n( It would be nice to provide a MAKE that worked with execution tokens\nas well, although \"defer\" and \"is\" can be used for that. MAKE expects\ntwo word names to be given as arguments. It will then change the behavior \nof the first word to use the second. MAKE is a state aware word. )\n\n: make immediate ( c1\" xxx\" c2\" xxx\" : change parsed word c1 to execute c2 )\n\tfind found? cell+\n\tfind found?\n\tstate @ if ( compiling )\n\t\tswap postpone 2literal ['] ! ,\n\telse ( command mode )\n\t\tswap !\n\tthen ;\n\nhider noop\n\n( ========================== DOER\/MAKE ======================================= )\n\n( ========================== Extended Word Set =============================== )\n\n: log2 ( x -- log2 )\n\t( Computes the binary integer logarithm of a number,\n\tzero however returns itself instead of reporting an error )\n\t0 swap\n\tbegin\n\t\tnos1+ 2\/ dup 0=\n\tuntil\n\tdrop 1- ;\n\n: time ( \" ccc\" -- n : time the number of milliseconds it takes to execute a word )\n\tclock >r\n\tfind execute\n\tclock r> - ;\n\n( defer...is is probably not standards compliant, it is still neat! )\n: (do-defer) ( -- self : pushes the location into which it is compiled )\n\tr> dup >r 1- ;\n\n: defer ( \" ccc\" -- , Run Time -- location : \n\tcreates a word that pushes a location to write an execution token into )\n\t:: ' (do-defer) , postpone ; ;\n\n: is ( location \" ccc\" -- : make a deferred word execute a word ) \n\tfind found? swap ! ;\n\nhider (do-defer)\nhider found?\n\n( The \"tail\" function implements tail calls, which is just a jump\nto the beginning of the words definition, for example this\nword will never overflow the stack and will print \"1\" followed\nby a new line forever,\n\n\t: forever 1 . cr tail ;\n\nWhereas\n\n\t: forever 1 . cr recurse ;\n\nor\n\n\t: forever 1 . cr forever ;\n\nWould overflow the return stack. )\n\nhider tail\n: tail ( -- : perform tail recursion in current word definition )\n\timmediate\n\tlatest cell+\n\t' branch ,\n\there - cell+ , ;\n\n: recurse immediate\n\t( This function implements recursion, although this interpreter\n\tallows calling a word directly. If used incorrectly this will\n\tblow up the return stack.\n\n\tWe can test \"recurse\" with this factorial function:\n\t : factorial dup 2 < if drop 1 exit then dup 1- recurse * ; )\n\tlatest cell+ , ;\n\n: factorial ( x -- x : compute the factorial of a number )\n\tdup 2 < if drop 1 exit then dup 1- recurse * ;\n\n: myself ( -- : myself is a synonym for recurse ) \n\timmediate postpone recurse ;\n\n: gcd ( x1 x2 -- x : greatest common divisor )\n\tdup if tuck mod tail then drop ;\n\n( ========================== Extended Word Set =============================== )\n\n( The words described here on out get more complex and will require more\nof an explanation as to how they work. )\n\n( ========================== CREATE DOES> ==================================== )\n\n( The following section defines a pair of words \"create\" and \"does>\" which\nare a powerful set of words that can be used to make words that can create\nother words. \"create\" has both run time and compile time behavior, whilst\n\"does>\" only works at compile time in conjunction with \"create\". These two\nwords can be used to add constants, variables and arrays to the language,\namongst other things.\n\nA simple version of create is as follows\n\n\t: create :: dolist , here 2 cells + , ' exit , 0 state ! ;\n\nBut this version is much more limited.\n\n\"create\"...\"does>\" is one of the constructs that makes Forth Forth, it\nallows the creation of words which can define new words in themselves,\nand thus allows us to extend the language easily.\n)\n\n: write-quote ( -- : A word that writes ' into the dictionary )\n\t['] ' , ; \n\n: write-exit ( -- : A word that write exit into the dictionary )\n\t['] _exit , ;\n\n: write-compile, ( -- : A word that writes , into the dictionary ) \n\t' , , ;\n\n: state! ( bool -- : set the compilation state variable ) \n\tstate ! ;\n\n: command-mode ( -- : put the interpreter into command mode )\n\tfalse state! ;\n\n: command-mode-create ( create a new work that pushes its data field )\n\t:: ( compile a word )\n\tdolit , ( write push into new word )\n\there 2 cells + , ( push a pointer to data field )\n\tpostpone ; ; ( write exit and switch to command mode )\n\n: mark write-compile, ( Write in a place holder 0 and push a pointer to to be used by does> )\n\twrite-quote write-exit write-compile, ( Write in an exit in the word we're compiling. )\n\t['] command-mode , ; ( Make sure to change the state back to command mode )\n\n: create immediate ( create word is quite a complex forth word )\n\tstate @ \n\tif \n\t\tpostpone ( hole-to-patch -- )\n\timmediate\n\twrite-exit ( we don't want the defining word to exit, but the *defined* word to )\n\there swap ! ( patch in the code fields to point to )\n\tdolist , ; ( write a run in )\n\nhider write-quote\nhider write-compile,\nhider write-exit\n\n( Now that we have create...does> we can use it to create arrays, variables\nand constants, as we mentioned before. )\n\n: array ( u c\" xxx\" -- : create a named array of length u ) \n\tcreate allot does> + ;\n\n: variable ( x c\" xxx\" -- : create a variable will initial value of x )\n\tcreate , does> ;\n\n\\ : constant ( x c\" xxx\" -- : create a constant with value of x ) \n\\\tcreate , does> @ ;\n\n: table ( u c\" xxx\" --, Run Time: -- addr u : create a named table )\n\tcreate dup , allot does> dup @ ;\n\n: string ( u c\" xxx\" --, Run Time: -- c-addr u : create a named string )\n\tcreate dup , chars allot does> dup @ swap 1+ chars> swap ;\n\n\\ : +field \\ n <\"name\"> -- ; exec: addr -- 'addr\n\\ create over , +\n\\ does> @ + ;\n\\ \n\\ : begin-structure \\ -- addr 0 ; -- size\n\\ \tcreate\n\\ \there 0 0 , \\ mark stack, lay dummy\n\\ \tdoes> @ ; \\ -- rec-len\n\\ \n\\ : end-structure \\ addr n --\n\\ swap ! ; \\ set len \n\\ \n\\ begin-structure point\n\\ \tpoint +field p.x\n\\ \tpoint +field p.y\n\\ end-structure\n\\ \n\\ This should work...\n\\ : buffer: ( u c\" xxx\" --, Run Time: -- addr )\n\\\tcreate allot ;\n\n: 2constant \n\tcreate , , does> dup 1+ @ swap @ ;\n\n: 2variable \n\tcreate , , does> ;\n\n: enum ( x \" ccc\" -- x+1 : define a series of enumerations )\n\tdup constant 1+ ; \n\n( ========================== CREATE DOES> ==================================== )\n\n( ========================== DO...LOOP ======================================= )\n\n( The following section implements Forth's do...loop constructs, the\nword definitions are quite complex as it involves a lot of juggling of\nthe return stack. Along with begin...until do loops are one of the\nmain looping constructs. \n\nUnlike begin...until do accepts two values a limit and a starting value,\nthey are also words only to be used within a word definition, some Forths\nextend the semantics so looping constructs operate in command mode, this\nForth does not do that as it complicates things unnecessarily.\n\nExample:\n\t\n\t: example-1 10 1 do i . i 5 > if cr leave then loop 100 . cr ; \n\texample-1\n\nPrints:\n\t1 2 3 4 5 6\n\nIn \"example-1\" we can see the following:\n\n1. A limit, 10, and a start value, 1, passed to \"do\".\n2. A word called 'i', which is the current count of the loop\n3. If the count is greater than 5, we call a word call 'leave', this\nword exits the current loop context as well as the current calling\nword.\n4. \"100 . cr\" is never called. This should be changed in future\nrevision, but this version of leave exits the calling word as well.\n\n'i', 'j', and 'leave' *must* be used within a do...loop construct. \n\nIn order to remedy point 4. loop should not use branch but instead \nshould use a value to return to which it pushes to the return stack )\n\n: (do)\n\tswap ( swap the limit and start )\n\tr> ( save our return stack to temporary variable )\n\t-rot ( limit start return -- return start limit )\n\t>r ( push limit onto return stack )\n\t>r ( push start onto return stack )\n\t>r ; ( restore our return address )\n\n: do immediate ( Run time: high low -- : begin do...loop construct )\n\t' (do) ,\n\tpostpone begin ; \n\n: (unloop) ( -- , R: i limit -- : remove limit and i from )\n\tr> ( save our return address )\n\trdrop ( pop off i )\n\trdrop ( pop off limit )\n\t>r ; ( restore our return stack )\n\n: (+loop) ( x -- bool : increment loop variable by x and test it )\n\tr@ 1- ( get the pointer to i )\n\t+! ( add value to it )\n\tr@ 1- @ ( find i again )\n\tr@ 2- @ ( find the limit value )\n\tu>= ;\n\n: (loop) ( -- bool : increment loop variable by 1 and test it )\n\tr@ 1- ( get the pointer to i )\n\t1+! ( add one to it )\n\tr@ 1- @ ( find the value again )\n\tr@ 2- @ ( find the limit value )\n\tu>= ;\n\n: loop ( -- : end do...loop construct )\n\timmediate ' (loop) , postpone until ' (unloop) , ;\n\n: +loop ( x -- : end do...+loop loop construct )\n\timmediate ' (+loop) , postpone until ' (unloop) , ;\n\n: leave ( -- , R: i limit return -- : break out of a do-loop construct )\n\t(unloop)\n\trdrop ; ( return to the caller's caller routine )\n\n: ?leave ( x -- , R: i limit return -- | i limit return : conditional leave )\n\tif\n\t\t(unloop)\n\t\trdrop ( return to the caller's caller routine )\n\tthen ;\n\n: i ( -- i : Get current, or innermost, loop index in do...loop construct )\n\tr> r> ( pop off return address and i )\n\ttuck ( tuck i away )\n\t>r >r ; ( restore return stack )\n\n: j ( -- j : Get outermost loop index in do...loop construct )\n\t4 rpick ;\n\n( This is a simple test function for the looping, for interactive\ntesting and debugging:\n : mm 5 1 do i . cr 4 1 do j . tab i . cr loop loop ; )\n\n: range ( nX nY -- nX nX+1 ... nY ) \n\tnos1+ do i loop ;\n\n: repeater ( n0 X -- n0 ... nX ) \n\t1 do dup loop ;\n\n: sum ( n0 ... nX X -- sum<0..X> ) \n\t1 do + loop ;\n\n: mul ( n0 ... nX X -- mul<0..X> ) \n\t1 do * loop ;\n\n: reverse ( x1 ... xn n -- xn ... x1 : reverse n items on the stack )\n\t0 do i roll loop ;\n\n( ========================== DO...LOOP ======================================= )\n\n0 variable column-counter\n4 variable column-width\n\n: column ( i -- )\t\n\tcolumn-width @ mod not if cr then ;\n\n: column.reset\t\t\n\t0 column-counter ! ;\n\n: auto-column\t\t\n\tcolumn-counter dup @ column 1+! ;\n\n: alignment-bits \n\t[ 1 size log2 lshift 1- literal ] and ;\n\n\n0 variable x\n: x! ( x -- ) \n\tx ! ;\n\n: x@ ( -- x ) \n\tx @ ;\n\n: 2>r ( x1 x2 -- R: x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tswap\n\t\t>r\n\t\t>r\n\tx@ >r ; ( restore return address )\n\n: 2r> ( R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tr>\n\t\tr>\n\t\tswap\n\tx@ >r ; ( restore return address )\n\n: 2r@ ( -- x1 x2 , R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\tr> r>\n\t2dup\n\t>r >r\n\tswap\n\tx@ >r ; ( restore return address )\n\n: unused ( -- u : push the amount of core left ) \n\tmax-core here - ;\n\n: accumulator ( initial \" ccc\" -- : make a word that increments by a value and pushes the result )\n\tcreate , does> tuck +! @ ;\n\n: counter ( \" ccc\" --, Run Time: -- x : make a word that increments itself by one, starting from zero )\n\tcreate -1 , does> dup 1+! @ ;\n\n0 variable delim\n: accepter ( c-addr max delimiter -- i )\n\t( store a \"max\" number of chars at c-addr until \"delimiter\" encountered,\n\tthe number of characters stored is returned )\n\tdelim ! ( store delimiter used to stop string storage when encountered)\n\t0\n\tdo\n\t\tkey dup delim @ <>\n\t\tif\n\t\t\tover c! 1+\n\t\telse ( terminate string )\n\t\t\tdrop 0 swap c! \n\t\t\ti \n\t\t\tleave\n\t\tthen\n\tloop\n\t-18 throw ; ( read in too many chars )\nhider delim\n\n: skip\n\tkey drop >r 0 begin drop key dup rdup r> <> until rdrop ;\n\n: word ( c -- c-addr : parse until 'c' is encountered, push transient counted string )\n\tdup skip chere 1+ c!\n\t>r\n\tchere 2+\n\tpad here - chars>\n\tr> accepter 1+\n\tchere c!\n\tchere ;\n\nhider skip\n\n: accept ( c-addr +n1 -- +n2 : see accepter definition ) \n\tnl accepter ;\n\n0xFFFF constant max-string-length\n\n: (.\") ( char -- c-addr u )\n\t( @todo This really needs simplifying, to do this\n\ta set of words that operate on a temporary buffer can\n\tbe used )\n\t( Write a string into word being currently defined, this\n\tcode has to jump over the string it has just put into the\n\tdictionary so normal execution of a word can continue. The\n\tlength and character address of the string are left on the\n\tstack )\n\t>r ( save delimiter )\n\t' branch , ( write in jump, this will jump past the string )\n\t>mark ( make hole )\n\tdup 1+ chars> ( calculate address to write to )\n\tmax-string-length \n\tr> ( restore delimiter )\n\taccepter dup >r ( write string into dictionary, save index )\n\taligned 2dup size \/ ( stack: length hole char-len hole )\n\t1+ dup allot ( update dictionary pointer with string length )\n\t1+ swap ! ( write place to jump to )\n\tdrop ( do not need string length anymore )\n\t1+ chars> ( calculate place to print )\n\tr> ; ( restore index and address of string )\n\n: length ( c-addr u -- u : push the length of an ASCIIZ string )\n tuck 0 do dup c@ 0= if 2drop i leave then 1+ loop ;\n\n: asciiz? ( c-addr u -- : is a Forth string also a ASCIIZ string )\n\ttuck length <> ;\n\n: asciiz ( c-addr u -- : trim a string until NUL terminator )\n\t2dup length nip ;\n\n( This foreach mechanism needs thinking about, what is the best information to\npresent to the word to be executed? At the moment only the contents of the\ncell that it should be processing is.\n\nAt the moment foreach uses a do...loop construct, which means that the\nfollowing cannot be used to exit from the foreach loop:\n\n\t: return [ : exit early from a foreach loop ]\n\t\tr> rdrop >r ;\n\nAlthough this can be remedied, we know that it puts a loop onto the return\nstack.\n\nIt also uses a variable 'xt', which means that foreach loops cannot be\nnested. This word really needs thinking about.\n\nIt might be more useful to present the word with only the address of the\ncell it will act on.\n\nThis seems to be a useful, general, mechanism that is missing from\nmost Forths. More words like this should be made, they are powerful\nlike the word 'compose', but they need to be created correctly. )\n\n0 variable xt\n: foreach ( addr u xt -- : execute xt for each cell in addr-u )\n\txt !\n\tbounds do i @ xt @ execute loop ;\n\n: foreach-char ( c-addr u xt -- : execute xt for each cell in c-addr u )\n\txt !\n\tbounds do i c@ xt @ execute loop ;\nhider xt\n\n: type ( c-addr u -- : print out 'u' characters at c-addr )\n\t\\ 0 do dup c@ emit 1+ loop drop ;\n\t['] emit foreach-char ;\n\n: do-string ( char -- : write a string into the dictionary reading it until char is encountered )\n\t(.\") \n\tstate @ if swap [literal] [literal] then ;\n\n: fill ( c-addr u char -- : fill in an area of memory with a character, only if u is greater than zero )\n\t-rot\n\t0 do 2dup i + c! loop\n\t2drop ;\n\n: \/string ( c-addr1 u1 n -- c-addr2 u2 : advance a string by n characters )\n\tover min rot over + -rot - ;\n\n: compare ( c-addr1 u1 c-addr2 u2 -- n : compare two strings, not quite compliant yet )\n\t>r swap r> min >r\n\tstart-address + swap start-address + r>\n\tmemory-compare ;\n\n128 string sbuf\n: s\" ( \"ccc\" --, Run Time -- c-addr u )\n\tkey drop sbuf 0 fill sbuf [char] \" accepter sbuf drop swap ;\nhider sbuf\n\n( @todo these strings really need rethinking, state awareness needs to be removed... )\n: type, \n\tstate @ if ' type , else type then ;\n\n: c\" \n\timmediate key drop [char] \" do-string ;\n\n: \" \n\timmediate key drop [char] \" do-string type, ;\n\n: sprint ( c -- : print out chars until 'c' is encountered )\n\tkey drop ( drop next space )\n\t>r ( save delimiter )\n\tbegin\n\t\tkey dup ( get next character )\n\t\trdup r> ( get delimiter )\n\t\t<> if emit 0 then\n\tuntil rdrop ;\n\n: .( \n\timmediate [char] ) sprint ;\nhider sprint\n\n: .\" \n\timmediate key drop [char] \" do-string type, ;\n\nhider type,\n\n( This word really should be removed along with any usages of this word, it\nis not a very \"Forth\" like word, it accepts a pointer to an ASCIIZ string and\nprints it out, it also does not checking of the returned values from write-file )\n: print ( c-addr -- : print out a string to the standard output )\n\t-1 over >r length r> swap stdout write-file 2drop ;\n\n: ok \n\t\" ok\" cr ;\n\n: empty-stack ( x-n ... x-0 -- : empty the variable stack )\n\tbegin depth while drop repeat ;\n\n: (quit) ( -- : do the work of quit, without the restart )\n\t0 `source-id ! ( set source to read from file )\n\t`stdin @ `fin ! ( read from stdin )\n\tpostpone [ ( back into command mode )\n\t' interpret start! ; ( set interpreter starting word )\n\n: quit ( -- : Empty return stack, go back to command mode, read from stdin, interpret input )\n\t(quit)\n\t-1 restart ; ( restart the interpreter )\n\n: abort\n\t-1 throw ;\n\n: (abort\") ( do the work of abort )\n\t(quit)\n\t-2 throw ;\n\n: abort\" immediate \n\tpostpone \"\n\t' cr , ' (abort\") , ;\n\n( ==================== CASE statements ======================== )\n\n( for a simpler case statement:\n\tsee Volume 2, issue 3, page 48 of Forth Dimensions at\n\thttp:\/\/www.forth.org\/fd\/contents.html )\n\n( These case statements need improving, it is not standards compliant )\n: case immediate\n\t' branch , 3 , ( branch over the next branch )\n\there ' branch , ( mark: place endof branches back to with again )\n\t>mark swap ; ( mark: place endcase writes jump to with then )\n\n: over= ( x y -- x bool : over ... then = )\n\tover = ;\n\n: of\n\timmediate ' over= , postpone if ;\n\n: endof\n\timmediate over postpone again postpone then ;\n\n: endcase\n\timmediate 1+ postpone then drop ;\n\n( ==================== CASE statements ======================== )\n\n( ==================== Hiding Words =========================== )\n\n: }hide ( should only be matched with 'hide{' )\n\timmediate -22 throw ;\n\n: hide{ ( -- : hide a list of words, the list is terminated with \"}hide\" )\n\tbegin\n\t\tfind ( find next word )\n\t\tdup [ find }hide ] literal = if\n\t\t\tdrop exit ( terminate hide{ )\n\t\tthen\n\t\tdup 0= if -15 throw then\n\t\thide drop\n\tagain ;\n\n( ==================== Hiding Words =========================== )\n\n: spaces ( n -- : print n spaces ) \n\t0 do space loop ;\n\n: erase ( addr u : erase a block of memory )\n\t2chars> 0 fill ;\n\n: blank ( c-addr u : fills a string with spaces )\n\tbl fill ;\n\n( move should check that u is not negative )\n: move ( addr1 addr2 u -- : copy u words of memory from 'addr2' to 'addr1' )\n\t0 do\n\t\t2dup i + @ swap i + !\n\tloop\n\t2drop ;\n\n( It would be nice if move and cmove could share more code, as they do exactly\n the same thing but with different load and store functions, cmove> )\n: cmove ( c-addr1 c-addr2 u -- : copy u characters of memory from 'c-addr2' to 'c-addr1' )\n\t0 do\n\t\t2dup i + c@ swap i + c!\n\tloop\n\t2drop ;\n\n( ==================== Conditional Compilation ================ )\n\n( The words \"[if]\", \"[else]\" and \"[then]\" implement conditional compilation,\nthey can be nested as well\n\nSee http:\/\/lars.nocrew.org\/dpans\/dpans15.htm for more information\n\nA much simpler conditional compilation method is the following\nsingle word definition:\n\n : compile-line? 0= if [ find \\\\ , ] then ;\n\nWhich will skip a line if a conditional is false, and compile it\nif true )\n\n( These words really, really need refactoring, I could use the newly defined \n \"defer\" to help out with this )\n0 variable nest ( level of [if] nesting )\n0 variable [if]-word ( populated later with \"find [if]\" )\n0 variable [else]-word ( populated later with \"find [else]\")\n: [then] immediate ;\n: reset-nest 1 nest ! ;\n: unnest? [ find [then] ] literal = if nest 1-! then ;\n: nest? [if]-word @ = if nest 1+! then ;\n: end-nest? nest @ 0= ;\n: match-[else]? [else]-word @ = nest @ 1 = and ;\n\n: [if] ( bool -- : conditional execution )\n\tunless\n\t\treset-nest\n\t\tbegin\n\t\t\tfind\n\t\t\tdup nest?\n\t\t\tdup match-[else]? if drop exit then\n\t\t\t unnest?\n\t\t\tend-nest?\n\t\tuntil\n\tthen ;\n\n: [else] ( discard input until [then] encounter, nesting for [if] )\n\treset-nest\n\tbegin\n\t\tfind\n\t\tdup nest? unnest?\n\t\tend-nest?\n\tuntil ;\n\nfind [if] [if]-word !\nfind [else] [else]-word !\n\n: ?( if postpone ( then ; \\ conditionally read until ')'\n: ?\\ if postpone \\ then ;\n: 16bit\\ size 2 <> if postpone \\ then ;\n: 32bit\\ size 4 <> if postpone \\ then ;\n: 64bit\\ size 8 <> if postpone \\ then ;\n\nhide{ \n\t[if]-word [else]-word nest \n\treset-nest unnest? match-[else]? \n\tend-nest? nest? \n}hide\n\n( ==================== Conditional Compilation ================ )\n\n( ==================== Endian Words =========================== )\n\nsize 2 = [if] 0x0123 `x ! [then]\nsize 4 = [if] 0x01234567 `x ! [then]\nsize 8 = [if] 0x01234567abcdef `x ! [then]\n\n: endian ( -- bool : returns the endianess of the processor, little = 0, big = 1 )\n\t[ `x chars> c@ 0x01 = ] literal ;\n\n: swap16 ( x -- x : swap the byte order a 16 bit number )\n\tdup 256* 0xff00 and >r 256\/ lsb r> or ;\n\nsize 4 >= [if] \n\t: swap32 \n\t\tdup 0xffff and swap16 16 lshift swap\n\t\t16 rshift 0xffff and swap16 or ;\n[then]\n\nsize 8 >= [if]\n\t: swap64 ( x -- x : swap the byte order of a 64 bit number )\n\t\t dup 0xffffffff and swap32 32 lshift swap\n\t\t 32 rshift 0xffffffff and swap32 or ;\n[then]\n\nsize 2 = [if]\n\tendian \n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\tswap16 ;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\t;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\tswap16 ;\n\t[then]\n[then]\n\nsize 4 = [if]\n\tendian \n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\tswap32 ;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\t;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\tswap32 ;\n\t[then]\n[then]\n\nsize 8 = [if]\n\tendian \n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\tswap64 ;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\t;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\tswap64 ;\n\t[then]\n[then]\n\n( ==================== Endian Words =========================== )\n\n( ==================== Misc words ============================= )\n\n0 variable counter\n\n: counted-column ( index -- : special column printing for dump )\n\tcounter @ column-width @ mod\n\tnot if cr . \" :\" space else drop then\n\tcounter 1+! ;\n\n: as-chars ( x n -- : print a cell out as characters, upto n chars )\n\t0 ( from zero to the size of a cell )\n\tdo\n\t\tdup ( copy variable to print out )\n\t\tsize i 1+ - select-byte ( select correct byte )\n\t\tdup printable? not ( is it not printable )\n\t\tif drop [char] . then ( print a '.' if it is not )\n\t\temit ( otherwise print it out )\n\tloop\n\tspace ( print out space after )\n\tdrop ; ( drop cell we have printed out )\n\n: lister ( addr u addr -- )\n\t0 counter ! 1- swap \n\tdo \n\t\tdup counted-column 1+ i ? i @ size as-chars \n\tloop ;\n\n( @todo this function should make use of 'defer' and 'is', then different\nversion of dump could be made that swapped out 'lister' )\n: dump ( addr u -- : dump out 'u' cells of memory starting from 'addr' )\n\t1+ over + under lister drop \n\tcr ;\n\nhide{ counted-column counter as-chars }hide\n\n( Fence can be used to prevent any word defined before it from being forgotten \nUsage:\n\there fence ! )\n0 variable fence\n\n: forgetter ( pwd-token -- : forget a found word and everything after it )\n\tdup 0= if -15 throw then ( word not found! )\n\tdup fence @ u< if -15 throw then ( forgetting a word before fence! )\n\tdup @ pwd ! h ! ;\n\n: forget ( WORD -- : forget word and every word defined after it )\n\tfind 1- forgetter ;\n\n: marker ( WORD -- : make word the forgets itself and words after it)\n\t:: latest [literal] ' forgetter , postpone ; ;\nhider forgetter\n\n: ** ( b e -- x : exponent, raise 'b' to the power of 'e')\n\t?dup-if\n\t\tover swap\n\t\t1 do over * loop \n\t\tnip\n\telse\n\t\tdrop 1\n\tendif ;\n\n0 variable a\n0 variable b\n0 variable m\n: equal ( a1...an b1...bn n -- a1...an b1...bn bool : determine if two lists are equal )\n\t( example: \n\t\t1 2 3 \n\t\t1 2 3 \n\t\t3 equal \n\treturns: 1 )\n\tdup m ! 1+ 1 ( store copy of length and use as loop index )\n\tdo \n\t\ti 1- pick b ! ( store ith element of list in b1...bn )\n\t\ti m @ + 1- pick a ! ( store ith element of list in a1...an )\n\t\ta @ b @ <> ( compare a and b for equality )\n\t\tif 0 leave then ( unequal, finish early )\n\tloop 1 ; ( lists must be equal )\n\nhide{ a b m }hide\n\n: ndrop ( drop n items )\n\t?dup-if 0 do drop loop then ;\n\n: caesar ( c key -- o : encode a alphabetic character with a key using a generalization of the Caesar cipher )\n\t>r\n\tdup uppercase? if [char] A - r> + 26 mod [char] A + exit then\n\tdup lowercase? if [char] a - r> + 26 mod [char] a + exit then\n\trdrop ; ( it goes without saying that this should not be used for anything serious! )\n\n: caesar-type ( c-addr u key : type out encoded text with a Caesar cipher )\n\t-rot bounds do i c@ over caesar emit loop drop ;\n\n: rot13 ( c -- c : encode a character with ROT-13 )\n\t13 caesar ;\n\n: rot13-type ( c-addr u : print string in ROT-13 encoded form )\n\t13 caesar-type ;\n\n\\ s\" abcdefghijklmnopqrstuvwxyz\" rot13-type -> nopqrstuvwxyzabcdefghijklm\n\\ s\" hello\" rot13-type -> uryyb\n\n( ==================== Misc words ============================= )\n\n( ==================== Pictured Numeric Output ================ )\n( Pictured numeric output is what Forths use to display numbers\nto the screen, this Forth has number output methods built into\nthe Forth kernel and mostly uses them instead, but the mechanism\nis still useful so it has been added.\n\n\n@todo characters are added in reverse order, is this the best\nway of doing things? It makes use of hold awkward \n@todo Pictured number output should act on a double cell number\nnot a single cell number )\n\n0 variable hld\n\n: overflow ( -- : check if we overflow the hold area )\n \there chars> pad chars> hld @ - u> if -17 throw then ;\n\n: hold ( char -- : add a character to the numeric output string )\n\toverflow pad chars> hld @ - c! hld 1+! ;\n\n: holds ( addr u -- )\n begin dup while 1- 2dup + c@ hold repeat 2drop ;\n\n: nbase ( -- base : in this forth 0 is a special base, push 10 is base is zero )\n\tbase @ dup 0= if drop 10 then ;\n\n: <# ( -- : setup pictured numeric output )\n\t0 hld ! ;\n\n: sign ( -- : add a sign to the pictured numeric output string )\n\t[char] - hold ;\n\n: # ( x -- x : divide x by base, turn into a character, put in pictured output string )\n\tnbase um\/mod swap \n \tdup 9 u>\n \tif 7 + then\n \t48 + hold ;\n\n: #s ( x -- 0 : repeatedly call # on x until x is zero )\n\tbegin # dup 0= until ; \n\n: #> ( -- c-addr u : end pictured output conversion, push output string to stack )\n\t0 hold ( NUL terminate string, just in case )\n\thld 1-! ( but do not include that in the count )\n\tpad chars> hld @ \n\ttuck - 1+ swap ;\n\n: u. ( u -- : display number in base 10 )\n\tbase @ >r decimal <# #s #> type drop r> base ! ;\n\nhide{ nbase overflow }hide\n\n( ==================== Pictured Numeric Output ================ )\n\n( ==================== ANSI Escape Codes ====================== )\n( Terminal colorization module, via ANSI Escape Codes\n \nsee: https:\/\/en.wikipedia.org\/wiki\/ANSI_escape_code\nThese codes will provide a relatively portable means of\nmanipulating a terminal )\n\n27 constant 'escape'\n: CSI 'escape' emit .\" [\" ;\n0 constant black\n1 constant red\n2 constant green\n3 constant yellow\n4 constant blue\n5 constant magenta\n6 constant cyan\n7 constant white\n: foreground 30 + ;\n: background 40 + ;\n0 constant dark\n1 constant bright\nfalse variable colorize \n\n: color ( brightness color-code -- : set the terminal color )\n\t( set color on an ANSI compliant terminal,\n\tfor example:\n\t\tbright red foreground color\n\tsets the foreground text to bright red )\n\tcolorize @ 0= if 2drop exit then \n\tCSI u. if .\" ;1\" then .\" m\" ;\n\n: at-xy ( x y -- : set ANSI terminal cursor position to x y )\n\tCSI u. [char] ; emit u. .\" H\" ;\n\n: page ( -- : clear ANSI terminal screen and move cursor to beginning ) \n\tCSI .\" 2J\" 1 1 at-xy ;\n\n: hide-cursor ( -- : hide the cursor from view ) \n\tCSI .\" ?25l\" ;\n\n: show-cursor ( -- : show the cursor ) \n\tCSI .\" ?25h\" ;\n\n: save-cursor ( -- : save cursor position ) \n\tCSI .\" s\" ;\n\n: restore-cursor ( -- : restore saved cursor position ) \n\tCSI .\" u\" ;\n\n: reset-color ( -- : reset terminal color to its default value)\n\tcolorize @ 0= if exit then\n\tCSI .\" 0m\" ;\n\nhide{ CSI }hide\n( ==================== ANSI Escape Codes ====================== )\n\n( ==================== Unit test framework =================== )\n\n256 string estring ( string to test )\n0 variable #estring ( actual string length )\n0 variable start ( starting depth )\n0 variable result ( result depth )\n0 variable check ( only check depth if -> is called )\n0 variable dictionary ( dictionary pointer on entering { )\n0 variable previous ( PWD register on entering { )\n\n: T ; ( hack until T{ can process words )\n\n: -> ( -- : save depth in variable ) \n\t1 check ! depth result ! ; \n\n: test estring drop #estring @ ; \n\n: fail ( -- : invalidate the forth interpreter and exit )\n\tinvalidate bye ;\n\n: neutral ( -- : neutral color )\n\t;\n\n: bad ( -- : bad color )\n\tdark red foreground color ;\n\n: good ( -- : good color )\n\tdark green foreground color ;\n\n: die bad test type reset-color cr fail ;\n\n: evaluate? ( bool -- : test if evaluation has failed )\n\tif .\" evaluation failed\" cr fail then ;\n\n: failed bad .\" failed\" reset-color cr ;\n\n: adjust ( x -- x : adjust a depth to take into account starting depth ) \n\tstart @ - ;\n\n: no-check? ( -- bool : if true we need to check the depth )\n\tcheck @ 0= ;\n\n: depth? ( -- : check if depth is correct )\n\tno-check? if exit then\n\tdepth adjust ( get depth and adjust for starting depth )\n\tresult @ adjust 2* = ( get results depth, same adjustment, should be\n\t half size of the depth ) \n\tif exit then ( pass )\n\tfailed\n\t.\" Unequal depths:\" cr\n\t.\" depth: \" depth . cr\n\t.\" result: \" result @ . cr\n\tdie ;\n\n: equal? ( -- : determine if results equals expected )\n\tno-check? if exit then\n\tresult @ adjust equal\n\tif exit then\n\tfailed\n\t.\" Result is not equal to expected values. \" cr \n\t.\" Stack: \" cr .s cr\n\tdie ;\n\n: display ( c-addr u -- : print out testing message in estring )\n\tverbose if neutral type else 2drop then ;\n\n: pass ( -- : print out passing message )\n\tverbose if good .\" ok \" cr reset-color then ;\n\n: save ( -- : save current dictionary )\n\tpwd @ previous !\n\there dictionary ! ;\n\n: restore ( -- : restore dictionary )\n\tprevious @ pwd ! \n\tdictionary @ h ! ;\n\n\n: T{ ( -- : perform a unit test )\n\tdepth start ! ( save start of stack depth )\n\t0 result ! ( reset result variable )\n\t0 check ! ( reset check variable )\n\testring 0 fill ( zero input string )\n\tsave ( save dictionary state )\n\tkey drop ( drop next character, which is a space )\n\testring [char] } accepter #estring ! ( read in string to test )\n\ttest display ( print which string we are testing )\n\ttest evaluate ( perform test )\n\tevaluate? ( evaluate successfully? )\n\tdepth? ( correct depth )\n\tequal? ( results equal to expected values? )\n\tpass ( print pass message )\n\tresult @ adjust 2* ndrop ( remove items on stack generated by test )\n\trestore ; ( restore dictionary to previous state )\n\nT{ }T\nT{ -> }T\nT{ 1 -> 1 }T\nT{ 1 2 -> 1 2 }T\nT{ : c 1 2 ; c -> 1 2 }T\nT{ :noname 2 ; :noname 3 + ; compose execute -> 5 }T\n\nhide{ \n\tpass test display\n\tadjust start save restore dictionary previous \n\tevaluate? equal? depth? estring #estring result\n\tcheck no-check? die neutral bad good failed\n}hide\n\n( ==================== Unit test framework =================== )\n\n\n( ==================== Random Numbers ========================= )\n\n( \nSee:\nuses xorshift\nhttps:\/\/en.wikipedia.org\/wiki\/Xorshift\nhttp:\/\/excamera.com\/sphinx\/article-xorshift.html\nhttp:\/\/www.arklyffe.com\/main\/2010\/08\/29\/xorshift-pseudorandom-number-generator\/\nthese constants have be collected from the web \n)\n\nsize 2 = [if] 13 constant a 9 constant b 7 constant c [then]\nsize 4 = [if] 13 constant a 17 constant b 5 constant c [then]\nsize 8 = [if] 12 constant a 25 constant b 27 constant c [then]\n\n7 variable seed ( must not be zero )\n\n: seed! ( x -- : set the value of the PRNG seed )\n\tdup 0= if drop 7 ( zero not allowed ) then seed ! ;\n\n: random ( -- x : assumes word size is 32 bit )\n\tseed @\n\tdup a lshift xor\n\tdup b rshift xor\n\tdup c lshift xor\n\tdup seed! ;\n\nhide{ a b c seed }hide\n\n( ==================== Random Numbers ========================= )\n\n( ==================== Prime Numbers ========================== )\n( From original \"third\" code from the IOCCC at \nhttp:\/\/www.ioccc.org\/1992\/buzzard.2.design, the module works out\nand prints prime numbers. )\n\n: prime? ( u -- u | 0 : return number if it is prime, zero otherwise )\n\tdup 1 = if 1- exit then\n\tdup 2 = if exit then\n\tdup 2\/ 2 ( loop from 2 to n\/2 )\n\tdo\n\t\tdup ( value to check if prime )\n\t\ti mod ( mod by divisor )\n\t\tnot if\n\t\t\tdrop 0 leave\n\t\tthen\n\tloop ;\n\n0 variable counter\n\n: primes ( x1 x2 -- : print the primes from x2 to x1 )\n\t0 counter !\n\t\" The primes from \" dup . \" to \" over . \" are: \"\n\tcr\n\tcolumn.reset\n\tdo\n\t\ti prime?\n\t\tif\n\t\t\ti . counter @ column counter 1+!\n\t\tthen\n\tloop\n\tcr\n\t\" There are \" counter @ . \" primes.\"\n\tcr ;\n\nhide{ counter }hide\n( ==================== Prime Numbers ========================== )\n\n( ==================== Debugging info ========================= )\n\n( string handling should really be done with PARSE, and CMOVE )\n\n: sh ( cnl -- ior : execute a line as a system command )\n\tnl word count system ;\n\nhide{ .s }hide\n: .s ( -- : print out the stack for debugging )\n\t[char] < emit depth u. [char] > emit space\n\tdepth if\n\t\tdepth 0 do i column tab depth i 1+ - pick . loop\n\tthen\n\tcr ;\n\n1 variable hide-words ( do we want to hide hidden words or not )\n\n: name ( PWD -- c-addr : given a pointer to the PWD field of a word get a pointer to the name of the word )\n\tdup 1+ @ 256\/ word-mask and lsb - chars> ;\n\n( This function prints out all of the defined words, excluding hidden words.\nAn understanding of the layout of a Forth word helps here. The dictionary\ncontains a linked list of words, each forth word has a pointer to the previous\nword until the first word. The layout of a Forth word looks like this:\n\nNAME: Forth Word - A variable length ASCII NUL terminated string\nPWD: Previous Word Pointer, points to the previous word\nCODE: Flags, code word and offset from previous word pointer to start of Forth word string\nDATA: The body of the forth word definition, not interested in this.\n\nThere is a register which stores the latest defined word which can be\naccessed with the code \"pwd @\". In order to print out a word we need to\naccess a words CODE field, the offset to the NAME is stored here in bits\n8 to 14 and the offset is calculated from the PWD field.\n\n\"print\" expects a character address, so we need to multiply any calculated\naddress by the word size in bytes. )\n\n: words.immediate ( bool -- : emit or mark a word being printed as being immediate )\n\tnot if dark red foreground color then ;\n\n: words.defined ( bool -- : emit or mark a word being printed as being a built in word )\n\tnot if bright green background color then ;\n\n: words.hidden ( bool -- : emit or mark a word being printed as being a hidden word )\n\tif dark magenta foreground color then ;\n\n: words ( -- : print out all defined an visible words )\n\tlatest\n\tspace\n\tbegin\n\t\tdup\n\t\thidden? hide-words @ and\n\t\tnot if\n\t\t\thidden? words.hidden\n\t\t\tcompiling? words.immediate\n\t\t\tdup defined-word? words.defined\n\t\t\tname\n\t\t\tprint space\n\t\t\treset-color\n\t\telse\n\t\t\tdrop\n\t\tthen\n\t\t@ ( Get pointer to previous word )\n\t\tdup dictionary-start u< ( stop if pwd no longer points to a word )\n\tuntil\n\tdrop cr ;\n\n( Simpler version of words\n: words\n\tpwd @ \n\tbegin\n\t\tdup name print space @ dup dictionary-start u<\n\tuntil drop cr ; )\n\nhide{ words.immediate words.defined words.hidden hidden? hidden-bit }hide\n\n: TrueFalse ( -- : print true or false )\n\tif \" true\" else \" false\" then ;\n\n: registers ( -- : print out important registers and information about the virtual machine )\n\t\" return stack pointer: \" r@ . cr\n\t\" dictionary pointer \" here . cr\n\t\" previous word: \" pwd ? cr\n\t\" state: \" state ? cr\n\t\" base: \" base ? cr\n\t\" depth: \" depth . cr\n\t\" cell size (in bytes): \" size . cr\n\t\" last cell address: \" max-core . cr\n\t\" unused cells: \" unused . cr\n\t\" invalid: \" `invalid @ TrueFalse cr\n\t\" size of variable stack: \" `stack-size ? cr\n\t\" size of return stack: \" `stack-size ? cr\n\t\" start of variable stack: \" max-core `stack-size @ 2* - . cr\n\t\" start of return stack: \" max-core `stack-size @ - . cr\n\t\" current input source: \" source-id -1 = if \" string\" else \" file\" then cr\n\t\" tracing on: \" `debug @ TrueFalse cr\n\t\" starting word: \" `instruction ? cr\n\t\" real start address: \" `start-address ? cr\n\t\" error handling: \" `error-handler ? cr \n\t\" throw handler: \" `handler ? cr\n\t\" signal recieved: \" `signal ? cr ;\n\t\n( `sin `sidx `slen `fout\n `stdout `stderr `argc `argv )\n\n\n: y\/n? ( -- bool : ask a yes or no question )\n\tkey drop\n\t\" y\/n? \"\n\tbegin\n\t\tkey\n\t\tdup\n\t\t[char] y = if true exit then\n\t\t[char] n = if false exit then\n\t\t\" y\/n? \"\n\tagain ;\n\n: step\n\t( step through a word: this word could be augmented\n\twith commands such as \"dump\", \"halt\", and optional\n\t\".s\" and \"registers\" )\n\tregisters\n\t\" .s: \" .s cr\n\t\" -- press any key to continue -- \"\n\tkey drop ;\n\n: more ( -- : wait for more input )\n\t\" -- press any key to continue -- \" key drop cr page ;\n\n: debug-help ( -- : print out the help for the debug command )\n \" debug mode commands\n\th - print help\n\tq - exit interpreter word\n\tr - print registers\n\ts - print stack\n\tR - print return stack\n\tc - continue on with execution\n\" ;\n\ndoer debug-prompt\n: prompt-default\n\t.\" debug> \" ;\n\nmake debug-prompt prompt-default\n\n: debug ( -- : enter interactive debug prompt )\n\tcr\n\t\" Entered Debug Prompt. Type 'h' for help. \" cr \n\tbegin\n\t\tkey\n\t\tcase\n\t\t\tnl of debug-prompt endof\n\t\t\t[char] h of debug-help endof\n\t\t\t[char] q of bye endof\n\t\t\t[char] r of registers endof\n\t\t\t[char] s of >r .s r> endof\n\t\t\t[char] R of r> r.s >r endof\n\t\t\t[char] c of drop exit endof\n\t\t\t( @todo add throw here )\n\t\tendcase drop\n\tagain ;\nhider debug-prompt\n\n: code>pwd ( CODE -- PWD\/0 : calculate PWD from code address )\n\tdup dictionary-start here within not if drop 0 exit then\n\t1 cells - ;\n\n: word-printer ( CODE -- : print out a words name given its code field )\n\tdup 1 cells - @ -1 = if . \" noname\" exit then ( nonames are marked by a -1 before its code field )\n\tdup code>pwd ?dup-if .d name print else drop \" data\" then\n\t drop ;\n\nhide{ code>pwd }hide\n\n( these words push the execution tokens for various special cases for decompilation )\n: get-branch [ find branch ] literal ;\n: get-?branch [ find ?branch ] literal ;\n: get-original-exit [ find _exit ] literal ;\n: get-quote [ find ' ] literal ;\n\n( @todo replace 2- nos1+ nos1+ with appropriate word, like the string word \nthat increments a string by an amount, but that operates on CELLS )\n: branch-increment ( addr branch -- increment : calculate decompile increment for \"branch\" )\n\t1+ dup negative? \n\tif \n\t\tover cr . [char] : emit space . cr 2 \n\telse \n\t\t2dup 2- nos1+ nos1+ dump \n\tthen ;\n\n( these words take a code field to a primitive they implement, decompile it\nand any data belonging to that operation, and push a number to increment the\ndecompilers code stream pointer by )\n\n: decompile-literal ( code -- increment )\n\t1+ ? \" literal\" 2 ;\n\n: decompile-branch ( code -- increment )\n\tdark red foreground color\n\t1+ ? \" branch \" dup 1+ @ branch-increment ;\n\n: decompile-quote ( code -- increment )\n\tdark green foreground color\n\tdup\n\t[char] ' emit 1+ @ word-printer 2 reset-color ;\n\n: decompile-?branch ( code -- increment )\n\t1+ ? \" ?branch\" 2 ;\n\n: decompile-exit ( code -- 0 )\n\t\" _exit\" cr \" End of word: \" . 0 ;\n\n( The decompile word expects a pointer to the code field of a word, it\ndecompiles a words code field, it needs a lot of work however.\nThere are several complications to implementing this decompile\nfunction.\n\n\t' The next cell should be pushed\n\t:noname This has a marker before its code field of -1 which\n\t\t cannot occur normally, this is handled in word-printer\n\tbranch branches are used to skip over data, but also for\n\t\t some branch constructs, any data in between can only\n\t\t be printed out generally speaking\n\texit There are two definitions of exit, the one used in\n\t\t ';' and the one everything else uses, this is used\n\t\t to determine the actual end of the word\n\tliterals Literals can be distinguished by their low value,\n\t\t which cannot possibly be a word with a name, the\n\t\t next field is the actual literal\n\nOf special difficult is processing 'if' 'else' 'then' statements,\nthis will require keeping track of '?branch'.\n\nAlso of note, a number greater than \"here\" must be data )\n\n: decompile ( code-pointer -- code-pointer increment|0 : )\n\t.d [char] : emit space dup @\n\tcase\n\t\tdolit of drup decompile-literal cr endof\n\t\tget-branch of drup decompile-branch endof\n\t\tget-quote of drup decompile-quote cr endof\n\t\tget-?branch of drup decompile-?branch cr endof\n\t\tget-original-exit of drup decompile-exit endof\n\t\tword-printer 1 cr\n\tendcase reset-color ;\n\n: decompiler ( code-field-ptr -- : decompile a word in its entirety )\n\tbegin decompile over + tuck = until drop ;\n\nhide{\n\tword-printer get-branch get-?branch get-original-exit \n\tget-quote branch-increment decompile-literal \n\tdecompile-branch decompile-?branch decompile-quote\n\tdecompile-exit\n}hide\n\n( these words expect a pointer to the PWD field of a word )\n: see.name \" name: \" name print cr ;\n: see.start \" word start: \" name chars . cr ;\n: see.previous \" previous word: \" @ . cr ;\n: see.immediate \" immediate: \" compiling? swap drop not TrueFalse cr ;\n: see.instruction \" instruction: \" xt-instruction . cr ;\n: see.defined \" defined: \" defined-word? TrueFalse cr ;\n\n: see.header ( PWD -- is-immediate-word? )\n\tdup see.name\n\tdup see.start\n\tdup see.previous\n\tdup see.immediate\n\tdup see.instruction ( @todo look up instruction name )\n\tsee.defined ;\n\n( @todo This does not work for all words, so needs fixing. \n Specifically: \n\t2variable\n\t2constant\n\ttable\n\tconstant\n\tvariable\n\tarray \nWhich are all complex CREATE words\n\nA good way to test decompilation is with the following Unix pipe: \n\n\t.\/forth -f forth.fth -e words \n\t\t| sed 's\/ \/ see \/g' \n\t\t| .\/forth -t forth.fth &> decompiled.log\n)\n\n( @todo refactor into word that takes a PWD pointer and one that attempts to parse\/find name )\n: see ( c\" xxx\" -- : decompile the next word in the input stream )\n\tfind\n\tdup 0= if -32 throw then\n\t-1 cells + ( move to PWD field )\n\tdup see.header\n\tdup defined-word?\n\tif ( decompile if a compiled word )\n\t\t2 cells + ( move to code field )\n\t\t\" code field:\" cr\n\t\tdecompiler\n\telse ( the instruction describes the word if it is not a compiled word )\n\t\tdup 1 cells + @ instruction-mask and doconst = if ( special case for constants )\n\t\t\t\" constant: \" 2 cells + @ .\n\t\telse\n\t\t\tdrop\n\t\tthen\n\tthen cr ;\n\nhide{ \n\tsee.header see.name see.start see.previous see.immediate \n\tsee.instruction defined-word? see.defined\n}hide\n\n( These help messages could be moved to blocks, the blocks could then\nbe loaded from disk and printed instead of defining the help here,\nthis would allow much larger help )\n\n: help ( -- : print out a short help message )\n\tpage\n\tkey drop\n\" Welcome to Forth, an imperative stack based language. It is both a low\nlevel and a high level language, with a very small memory footprint. Most\nof Forth is defined as a combination of various primitives.\n\nA short description of the available function (or Forth words) follows,\nwords marked (1) are immediate and cannot be used in command mode, words\nmarked with (2) define new words. Words marked with (3) have both command\nand compile functionality.\n\n\"\nmore \" Some of the built in words that accessible are:\n\n(1,2)\t: define a new word, switching to compile mode\n\timmediate make latest defined word immediate\n\tread read in a word, execute in command mode else compile\n\t@ ! fetch, store\n\tc@ c! character based fetch and store\n\t- + * \/ standard arithmetic operations,\n\tand or xor invert standard bitwise operations\n\tlshift rshift left and right bit shift\n\tu< u> < > = comparison predicates\n\texit exit from a word\n\temit print character from top of stack\n\tkey get a character from input\n\tr> >r pop a value from or to the return stack\n\tfind find a word in the dictionary and push the location\n\t' store the address of the following word on the stack\n\t, write the top of the stack to the dictionary\n\tswap swap first two values on the stack\n\tdup duplicate the top of the stack\n\tdrop pop and drop a value\n\tover copy the second stack value over the first\n\t. pop the top of the stack and print it\n\" \nmore \" \n\tprint print a NUL terminated string at a character address\n\tdepth get the current stack depth\n\tclock get the time since execution start in milliseconds\n\tevaluate evaluate a string\n\tsystem execute a system command\n\tclose-file close a file handle\n\topen-file open a file handle\n\tdelete-file delete a file off disk given a string\n\tread-file read in characters from a file\n\twrite-file write characters to a file\n\tfile-position get the file offset\n\treposition-file reposition the file pointer\n\tflush-file flush a file to disk\n\trename-file rename a file on disk\n \"\n\nmore \" All of the other words in the interpreter are built from these\nprimitive words. A few examples:\n\n(1)\tif...else...then FORTH branching construct\n(1)\tbegin...until loop until top of stack is non zero\n(1)\tbegin...again infinite loop\n(1)\tdo...loop FORTH looping construct\n(2,3)\tcreate create a new word that pushes its location\n(1)\tdoes> declare a created words run time behaviour\n(1,2)\tvariable declare variable with initial value from top of stack\n(1,2)\tconstant declare a constant, taken from top of stack\n(1,2)\tarray declare an array with size taken from top of stack\n(1)\t; terminate a word definition and return to command mode\n\twords print out a list of all the defined words\n\thelp this help message\n\tdump print out memory contents starting at an address\n\tregisters print out the contents of the registers\n\tsee decompile a word, viewing what words compose it\n\t.s print out the contents of the stack\n\n\"\n\nmore \" Some more advanced words:\n\n\there push the dictionary pointer\n\th push the address of the dictionary pointer\n\tr push the return stack pointer\n\tallot allocate space in the dictionary\n(1)\t[ switch to command mode\n\t] switch to compile mode\n\t:: compile ':' into the dictionary\n\n\" more \"\nFor more information either consult the manual pages forth(1) and libforth(1)\nor consult the following sources:\n\n\thttps:\/\/github.com\/howerj\/libforth\n\thttp:\/\/work.anapnea.net\/html\/html\/projects.html\n\nAnd for a larger tutorial:\n\n\thttps:\/\/github.com\/howerj\/libforth\/blob\/master\/readme.md\n\nFor resources on Forth:\n\n\thttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\thttps:\/\/rwmj.wordpress.com\/2010\/08\/07\/jonesforth-git-repository\/\n\n -- end --\n\" cr\n;\n\n( ==================== Debugging info ========================= )\n\n( ==================== Files ================================== )\n\n( @todo implement the other file access methods in terms of the\n built in ones [see http:\/\/forth.sourceforge.net\/std\/dpans\/dpans11.htm]\n @todo read-line and write-line need their flag and ior setting correctly\n\n\tFILE-SIZE [ use file-positions ]\n\n Also of note:\t\n * Source ID needs extending. )\n\n: read-char ( c-addr fileid -- ior : read a char )\n\t1 swap read-file 0<> swap 1 <> or ;\n\n0 variable x\n\n: getchar ( fileid -- char ior )\n\tx chars> swap read-char x chars> c@ swap ;\n\n: write-char ( c-addr fileid -- ior : write a char )\n\t1 swap write-file 0<> swap 1 <> or ;\n\n: putchar ( char fileid -- ior )\n\tswap x chars> c! x chars> swap write-char ;\n\nhide{ x }hide\n\n: rewind-file ( file-id -- : rewind a file to the beginning )\n\t0 reposition-file throw ;\n\n: read-line ( c-addr u1 fileid -- u2 flag ior : read in a line of text )\n\t-rot bounds\n\tdo\n\t\tdup i swap read-char drop\n\t\ti c@ nl = if drop i 0 0 leave then\n\tloop drop ;\n\n: write-line ( c-addr u fileid -- u2 flag ior : write a line of text )\n\t-rot bounds\n\tdo\n\t\tdup i swap write-char drop\n\t\ti c@ nl = if drop i 0 0 leave then\n\tloop ;\n\n: resize-file ( ud fileid -- ior : attempt to resize a file )\n\t( There is no portable way to truncate a file :C )\n\t2drop -1 ( -1 to indicate failure ) ;\n\n: create-file ( c-addr u fam -- fileid ior )\n\t>r 2dup w\/o open-file throw close-file throw\n\tr> open-file ;\n\n: include-file ( file-id -- : evaluate a file ) \n\tdup >r 0 1 evaluator r> close-file throw throw ;\n\n: included ( c-addr u -- : attempt to open up a name file and evaluate it )\n\tr\/o open-file throw \n\tinclude-file ;\n\n: include ( c\" ccc\" -- : attempt to evaluate a named file )\n\t( @bug requires trailing space, should use parse-name )\n\tbl word count included ;\n\n: bin ( fam1 -- fam2 : modify a file access method to be binary not line oriented ) \n\t( Do nothing, all file access methods are binary )\n\t;\n\n( ==================== Files ================================== )\n\n( ==================== Matcher ================================ )\n( The following section implements a very simple regular expression\nengine, which expects an ASCIIZ Forth string. It is translated from C\ncode and performs an identical function.\n\nThe regular expression language is as follows:\n\n\tc\tmatch a literal character\n\t.\tmatch any character\n\t*\tmatch any characters\n\nThe \"*\" operator performs the same function as \".*\" does in most\nother regular expression engines. Most other regular expression engines\nalso do not anchor their selections to the beginning and the end of\nthe string to match, instead using the operators '^' and '$' to do\nso, to emulate this behavior '*' can be added as either a suffix,\nor a prefix, or both, to the matching expression.\n\nAs an example \"*, World!\" matches both \"Hello, World!\" and\n\"Good bye, cruel World!\". \"Hello, ....\" matches \"Hello, Bill\"\nand \"Hello, Fred\" but not \"Hello, Tim\" as there are two few\ncharacters in the last string.\n\n@todo make a matcher that expects a Forth string, which do not\nhave to be NUL terminated\n)\n\n\\ Translated from http:\/\/c-faq.com\/lib\/regex.html\n\\ int match(char *pat, char *str)\n\\ {\n\\ \tswitch(*pat) {\n\\ \tcase '\\0': return !*str;\n\\ \tcase '*': return match(pat+1, str) || *str && match(pat, str+1);\n\\ \tcase '.': return *str && match(pat+1, str+1);\n\\ \tdefault: return *pat == *str && match(pat+1, str+1);\n\\ \t}\n\\ }\n\n: *pat ( regex -- regex char : grab next character of pattern ) \n\tdup c@ ;\n\n: *str ( string regex -- string regex char : grab next character string to match )\n\tover c@ ;\n\n: pass ( c-addr1 c-addr2 -- bool : pass condition, characters matched ) \n\t2drop 1 ;\n\n: reject ( c-addr1 c-addr2 -- bool : fail condition, character not matched ) \n\t2drop 0 ;\n\n: *pat==*str ( c-addr1 c-addr2 -- c-addr1 c-addr2 bool )\n\t2dup c@ swap c@ = ;\n\n: ++ ( u1 u2 u3 u4 -- u1+u3 u2+u4 : not quite d+ [does no carry] )\n\tswap >r + swap r> + swap ;\n\ndefer matcher\n\n: advance ( string regex char -- bool : advance both regex and string )\n\tif 1 1 ++ matcher else reject then ;\n\n: advance-string ( string regex char -- bool : advance only the string )\n\tif 1 0 ++ matcher else reject then ;\n\n: advance-regex ( string regex -- bool : advance matching )\n\t2dup 0 1 ++ matcher if pass else *str advance-string then ;\n\n: match ( string regex -- bool : match a ASCIIZ pattern against an ASCIIZ string )\n\t( @todo Add limits and accept two Forth strings, making sure they are both\n\t ASCIIZ strings as well \n\t @warning This uses a non-standards compliant version of case! )\n\t*pat\n\tcase\n\t\t 0 of drop drop c@ not exit endof\n\t\t[char] * of drop advance-regex exit endof\n\t\t[char] . of drop *str advance exit endof\n\t\t drop *pat==*str advance exit\n\tendcase ;\n\nmatcher is match\n\nhide{ \n\t*str *pat *pat==*str pass reject advance \n\tadvance-string advance-regex matcher ++ \n}hide\n\n( ==================== Matcher ================================ )\n\n\n( ==================== Cons Cells ============================= )\n\n( From http:\/\/sametwice.com\/cons.fs, this could be improved if the optional\nmemory allocation words were added to the interpreter. This provides\na simple \"cons cell\" data structure. There is currently no way to\nfree allocated cells )\n\n: car! ( value cons-addr -- : store a value in the car cell of a cons cell ) \n\t! ;\n\n: cdr! ( value cons-addr -- : store a value in the cdr cell of a cons cell )\n\tcell+ ! ;\n\n: car@ ( cons-addr -- car-val : retrieve car value from cons cell )\n\t@ ;\n\n: cdr@ ( cons-addr -- cdr-val : retrieve cdr value from cons cell )\n\tcell+ @ ;\n\n: cons ( car-val cdr-val -- cons-addr : allocate a new cons cell )\n\tswap here >r , , r> ;\n\n: cons0 0 0 cons ;\n\nmarker cleanup\n77 987 cons constant x\nT{ x car@ -> 77 }T\nT{ x cdr@ -> 987 }T\nT{ 55 x cdr! x car@ x cdr@ -> 77 55 }T\nT{ 44 x car! x car@ x cdr@ -> 44 55 }T\ncleanup\n\n( ==================== Cons Cells ============================= )\n\n( ==================== Miscellaneous ========================== )\n\n: license ( -- : print out license information )\n\" \nThe MIT License (MIT)\n\nCopyright (c) 2016, 2017 Richard James Howe\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the 'Software'),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand\/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\nTHE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\nOTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\nARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE. \n\n\" \n;\n\n( ==================== Version information =================== )\n\n4 constant version\n\n( ==================== Version information =================== )\n\n( ==================== Core utilities ======================== )\n( Read the header of a core file and process it, printing the\nresults out )\n\n8 constant header-size ( size of Forth core file header )\n8 constant size-field-size ( the size in bytes of the size field in the core file )\n0 variable core-file ( core fileid we are reading in )\n0 variable core-cell-size ( cell size of Forth core )\n0 variable core-version ( version of core file )\n0 variable core-endianess ( endianess of core we are reading in )\n\n( save space to read in header )\ncreate header header-size chars allot\n: cheader ( -- c-addr : header char address )\n\theader chars> ;\ncreate size-field size-field-size chars allot\n: csize-field ( -- c-addr : address of place size field is stored in )\n\tsize-field chars> ;\n\n0\nenum header-magic0 ( magic number 0 : FF ) \nenum header-magic1 ( magic number 1 : '4' )\nenum header-magic2 ( magic number 2 : 'T' )\nenum header-magic3 ( magic number 3 : 'H' )\nenum header-cell-size ( size of a forth cell, either 2, 4 or 8 bytes )\nenum header-version ( version of the forth core )\nenum header-endianess ( endianess of the core )\nenum header-log2size ( binary logarithm of the core size )\n\n: cleanup ( -- : cleanup before abort )\n\tcore-file @ ?dup 0<> if close-file drop then ;\n\n: invalid-header ( bool -- : abort if header is invalid )\n\t<> if cleanup abort\" invalid header\" then ;\n\n: save-core-cell-size ( char -- : save the core file cell size, checking if it is valid )\n\tcore-cell-size !\n\t\" cell size:\" tab\n\tcore-cell-size @ 2 = if 2 . cr exit then\n\tcore-cell-size @ 4 = if 4 . cr exit then\n\tcore-cell-size @ 8 = if 8 . cr exit then\n\tcleanup core-cell-size @ . abort\" : invalid cell size\" ;\n\n: check-version-compatibility ( char -- : checks the version compatibility of the core file ) \n\tcore-version !\n\tcore-version @ version = if \" version: \" version . cr exit then\n\tcleanup core-version @ . abort\" : unknown version number\" ;\n\n: save-endianess ( char -- : save the endianess, checking if it is valid )\n\tcore-endianess !\n\t\" endianess:\" tab\n\tcore-endianess @ 0 = if \" big\" cr exit then\n\tcore-endianess @ 1 = if \" little\" cr exit then\n\tcleanup core-endianess @ . abort\" invalid endianess\" then ;\n\n: read-or-abort ( c-addr size fileid -- : )\n\tover >r read-file \n\t 0<> if cleanup abort\" file read failed\" then\n\tr> <> if cleanup abort\" header too small\" then ;\n\n: header? ( -- : print out header information )\n\tcheader header-size core-file @ read-or-abort\n\t( \" raw header:\" header 2 dump )\n\tcheader header-magic0 + c@ 255 invalid-header\n\tcheader header-magic1 + c@ [char] 4 invalid-header\n\tcheader header-magic2 + c@ [char] T invalid-header\n\tcheader header-magic3 + c@ [char] H invalid-header\n\tcheader header-cell-size + c@ save-core-cell-size\n\tcheader header-version + c@ check-version-compatibility\n\tcheader header-endianess + c@ save-endianess\n\t\" valid header\" cr ;\n\n: size? ( -- : print out core file size )\n\t\" size: \" cheader header-log2size + c@ 1 swap lshift . cr ;\n\n: core ( c-addr u -- : analyze a Forth core file from disk given its file name )\n\t2dup \" core file:\" tab type cr\n\tr\/o open-file throw core-file ! \n\theader?\n\tsize?\n\tcore-file @ close-file drop ;\n\n( s\" forth.core\" core )\n\nhide{ \nheader-size header? \nheader-magic0 header-magic1 header-magic2 header-magic3\nheader-version header-cell-size header-endianess header-log2size\nheader \ncore-file save-core-cell-size check-version-compatibility\ncore-cell-size cheader\ncore-endianess core-version save-endianess invalid-header\ncleanup size-field csize-field size-field-size\nread-or-abort size?\n}hide\n\n( ==================== Core utilities ======================== )\n\n( ==================== RLE =================================== )\n\n( These set of words implement Run Length Compression, which can be used for\nsaving space when compressing the core files generated by Forth programs, which\ncontain mostly runs of NUL characters. \n\nThe format of the encoded data is quite simple, there is a command byte\nfollowed by data. The command byte encodes only two commands; encode a run of\nliteral data and repeat the next character. \n\nIf the command byte is greater than X the command is a run of characters, \nX is then subtracted from the command byte and this is the number of \ncharacters that is to be copied verbatim when decompressing.\n\nIf the command byte is less than or equal to X then this number, plus one, is \nused to repeat the next data byte in the input stream.\n\nX is 128 for this application, but could be adjusted for better compression\ndepending on what the data looks like. \n\nExample:\n\t\n\t2 'a' 130 'b' 'c' 3 'd'\n\nBecomes:\n\n\taabcddd \n\nExample usage:\n\n\t: extract\n\t\tc\" forth.core\" w\/o open-file throw\n\t\tc\" forth.core.rle\" r\/o open-file throw\n\t\tdecompress ;\n\textract\n\n@note file redirection could be used for the input as well\n@todo compression, and reading\/writing to strings )\n\n: cpad pad chars> ;\n\n0 variable out\n128 constant run-length\n\n: next.char ( file-id -- char : read in a single character )\n\t>r cpad r> read-char throw cpad c@ ;\n\n: repeated ( count file-id -- : repeat a character count times )\n\tnext.char swap 0 do dup emit loop drop ;\n\n: literals ( count file-id -- : extract a literal run )\n\t>r cpad swap r> read-file throw cpad swap type ;\n\n: command ( file-id -- : process an RLE command )\n\tdup \n\t>r next.char\n\tdup run-length u> \n\tif \n\t\trun-length - r> literals \n\telse \n\t\t1+ r> repeated \n\tthen ;\n\n: redirect ( file-id-out -- : save current output pointer, redirect to output )\n\t`fout @ out ! `fout ! ;\n\n: restore ( -- : restore previous output pointer )\n\tout @ `fout ! ;\n\n: decompress ( file-id-out file-id-in -- : decompress an RLE encoded file )\n\tswap\n\tredirect\n\tbegin dup ' command catch until ( process commands until input exhausted )\n\t2drop ( drop twice because catch will restore stack before 'command' )\n\trestore ; ( restore input stream )\n\nhide{ literals repeated next.char out run-length command }hide\n\n( ==================== RLE =================================== )\n\n( ==================== Generate C Core file ================== )\n( The word core2c reads in a core file and turns it into a C file which \ncan then be compiled into the forth interpreter in a bootstrapping like\nprocess.\n\nUsage:\n c\" forth.core\" c\" core.gen.c\" core2c )\n\n0 variable count\n\n: wbyte ( u char -- : write a byte )\n\tpnum drop\n\t[char] , emit\n\t16 mod 0= if cr then ;\n\n: advance ( char -- : advance counter and print byte )\n\tcount 1+! count @ swap wbyte ;\n\n: hexify ( fileid -- fileid : turn core file into C numbers in array )\n\t0 count !\n\tbegin dup getchar 0= while advance repeat drop ;\n\n: quote ( -- : emit a quote character )\n\t[char] \" emit ;\n\n: core2c ( c-addr u c-addr u -- ior : generate a C file from a core file )\n\tw\/o open-file throw >r\n\tr\/o open-file ?dup-if r> close-file throw throw then\n\tr> redirect\n\t\" #include \" quote \" libforth.h\" quote cr\n\t\" unsigned char forth_core_data[] = {\" cr\n\thexify \n\t\" };\" cr\n\t\" forth_cell_t forth_core_size = \" count @ . \" ;\" cr cr\n\tclose-file\n\t`fout @ close-file \n\trestore or ;\n\nhide{ wbyte hexify count quote advance }hide\n \n( ==================== Generate C Core file ================== )\n\n: wc ( c-addr u -- u : count the bytes in a file )\n\tr\/o open-file throw\n\t0 swap\n\tbegin dup getchar nip 0= while nos1+ repeat close-file throw ;\n\n( ==================== Save Core file ======================== )\n\n( The following functionality allows the user to save the core file\nfrom within the running interpreter. The Forth core files have a very simple\nformat which means the words for doing this do not have to be too long, a header\nhas to emitted with a few calculated values and then the contents of the\nForths memory after this )\n\n( This write the header out to the current output device, this\nwill be redirected to a file )\n: header ( -- : write the header out )\n\t0xff emit ( magic 0 )\n\t[char] 4 emit ( magic 1 )\n\t[char] T emit ( magic 2 )\n\t[char] H emit ( magic 3 )\n\tsize emit ( cell size in bytes )\n\tversion emit ( core version )\n\tendian not emit ( endianess )\n\tmax-core log2 emit ; ( size field )\n\n: data ( -- : write the data out )\n\t0 max-core chars> `fout @ write-file throw drop ;\n\n: encore ( -- : write the core file out )\n\theader\n\tdata ;\n\n: save-core ( c-addr u -- : save core file or throw error ) \n\tw\/o open-file throw dup\n\tredirect \n\t\t' encore catch swap close-file throw \n\trestore ;\n\n( The following code illustrates an example of setting up a\nForth core file to execute a word when the core file is loaded.\nIn the example the word \"hello-world\" will be executed, which will\nalso quit the interpreter:\n\n\t\\ Only works for immediate words for now, we define\n\t\\ the word we wish to be executed when the forth core\n\t\\ is loaded\n\t: hello-world immediate\n\t\t\" Hello, World!\" cr bye ;\n\n\t\\ The following sets the starting word to our newly\n\t\\ defined word:\n\tfind hello-world cfa start!\n\n\t\\ Now we can save the core file out:\n\ts\" forth.core\" save-core \n\nThis can be used, in conjunction with aspects of the build system,\nto produce a standalone executable that will run only a single Forth\nword. )\n\nhide{ redirect restore data encore header }hide\n\n( ==================== Save Core file ======================== )\n\n( ==================== Hex dump ============================== )\n\n( @todo hexdump can read in too many characters and it does not\nprint out the correct address\n@todo utilities for easy redirecting of file input\/output )\n: input >r cpad 128 r> read-file ; ( file-id -- u 0 | error )\n: clean cpad 128 0 fill ; ( -- )\n: cdump cpad chars swap aligned chars dump ; ( u -- )\n: hexdump ( file-id -- : [hex]dump a file to the screen )\n\tdup \n\tclean\n\tinput if 2drop exit then\n\t?dup-if cdump else drop exit then\n\ttail ; \n\nhide{ cpad clean cdump input }hide\n\n( ==================== Hex dump ============================== )\n\n( ==================== Date ================================== )\n\n( Rather annoyingly months are start from 1 but weekdays from 0 )\n\n: >month ( month -- )\n\tcase\n\t\t 1 of \" Jan \" endof\n\t\t 2 of \" Feb \" endof\n\t\t 3 of \" Mar \" endof\n\t\t 4 of \" Apr \" endof\n\t\t 5 of \" May \" endof\n\t\t 6 of \" Jun \" endof\n\t\t 7 of \" Jul \" endof\n\t\t 8 of \" Aug \" endof\n\t\t 9 of \" Sep \" endof\n\t\t10 of \" Oct \" endof\n\t\t11 of \" Nov \" endof\n\t\t12 of \" Dec \" endof\n\tendcase drop ;\n\n: .day ( day -- : add ordinal to day )\n\t10 mod\n\tcase\n\t\t1 of \" st \" drop exit endof\n\t\t2 of \" nd \" drop exit endof\n\t\t3 of \" rd \" drop exit endof\n\t\t\" th \" \n\tendcase drop ;\n\n: >day ( day -- : add ordinal to day of month )\n\tdup u.\n\tdup 1 10 within if .day exit then\n\tdup 10 20 within if \" th\" drop exit then\n\t.day ;\n\n: >weekday ( weekday -- : print the weekday )\n\tcase\n\t\t0 of \" Sun \" endof\n\t\t1 of \" Mon \" endof\n\t\t2 of \" Tue \" endof\n\t\t3 of \" Wed \" endof\n\t\t4 of \" Thu \" endof\n\t\t5 of \" Fri \" endof\n\t\t6 of \" Sat \" endof\n\tendcase drop ;\n\n: padded ( u -- : print out a run of zero characters )\n\t0 do [char] 0 emit loop ;\n\n: 0u. ( u -- : print a zero padded number )\n\tdup 10 u< if 1 padded then u. space ;\n\n: .date ( date -- : print the date )\n\tif \" DST \" else \" GMT \" then \n\tdrop ( no need for days of year)\n\t>weekday\n\t. ( year ) \n\t>month \n\t>day \n\t0u. ( hour )\n\t0u. ( minute )\n\t0u. ( second ) cr ;\n\n: time&date ( -- second minute hour day month year )\n\tdate\n\t3drop ;\n\nhide{ 0u. >weekday .day >day >month padded }hide\n\n( ==================== Date ================================== )\n\n\n( ==================== CRC =================================== )\n\n( @todo implement all common CRC algorithms, but only if\nthe word size allows it [ie. 32 bit CRCs on a 32 or 64 bit\nmachine, 64 bit CRCs on a 64 bit machine] )\n\n( Make a word to limit arithmetic to a 16-bit value )\nsize 2 = [if] \n\t: limit immediate ; ( do nothing, no need to limit )\n[else] \n\t: limit 0xffff and ; ( limit to 16-bit value )\n[then]\n\n: ccitt ( crc char -- crc : calculate polynomial 0x1021 AKA \"x16 + x12 + x5 + 1\" )\n\t ( crc char )\n\tlimit over 256\/ xor ( crc x )\n\tdup 4 rshift xor ( crc x )\n\tdup 5 lshift limit xor ( crc x )\n\tdup 12 lshift limit xor ( crc x )\n\tswap 8 lshift limit xor ; ( crc )\n\n( see http:\/\/stackoverflow.com\/questions\/10564491\/function-to-calculate-a-crc16-checksum\n and https:\/\/www.lammertbies.nl\/comm\/info\/crc-calculation.html )\n: crc16-ccitt ( c-addr u -- u )\n\t0xFFFF -rot\n\t' ccitt\n\tforeach-char ;\nhide{ limit ccitt }hide\n\n( ==================== CRC =================================== )\n\n( ==================== Rational Data Type ==================== )\n( This word set allows the manipulation of a rational data type,\nwhich are basically fractions. This allows numbers like 1\/3 to\nbe represented without any loss of precision. Conversion to and\nfrom the data type to an integer type is trivial, although \ninformation can be lost during the conversion.\n\nTo convert to a rational, use 'dup', to convert from a rational,\nuse '\/'. \n\nThe denominator is the first number on the stack, the numerator the\nsecond number. Fractions are simplified after any rational operation,\nand all rational words can accept unsimplified arguments. For example\nthe fraction 1\/3 can be represented as 6\/18, they are equivalent, so\nthe rational equality operator \"=rat\" can accept both and returns\ntrue.\n\n\tT{ 1 3 6 18 =rat -> 1 }T\n\nSee: https:\/\/en.wikipedia.org\/wiki\/Rational_data_type \nFor more information.\n\nThis set of words use two cells to represent a fraction, however\na single cell could be used, with the numerator and the denominator\nstored in upper and lower half of a single cell. )\n\n: simplify ( a b -- a\/gcd{a,b} b\/gcd{a\/b} : simplify a rational )\n 2dup\n gcd\n tuck\n \/\n -rot\n \/\n swap ; \\ ? check this\n\n: crossmultiply ( a b c d -- a*d b*d c*b d*b )\n rot ( a c d b )\n 2dup ( a c d b d b )\n * ( a c d b d*b )\n >r ( a c d b , d*b )\n rot ( a d b c , d*b )\n * ( a d b*c , d*b )\n -rot ( b*c a d , d*b )\n * ( b*c a*d , d*b )\n r> ( b*c a*d d*b )\n tuck ( b*c d*b a*d d*b )\n 2swap ; ( done! )\n\n: *rat ( a\/b c\/d -- a\/b : multiply two rationals together )\n rot * -rot * swap simplify ;\n\n: \/rat ( a\/b c\/d -- a\/b : divide one rational by another )\n swap *rat ;\n\n: +rat ( a\/b c\/d -- a\/b : add two rationals together )\n crossmultiply\n rot\n drop ( or check if equal, if not there is an error )\n -rot\n +\n swap\n simplify ;\n\n: -rat ( a\/b c\/d -- a\/b : subtract one rational from another )\n crossmultiply \n rot\n drop ( or check if equal, if not there is an error )\n -rot\n -\n swap\n simplify ;\n\n: .rat ( a\/b -- : print out a rational number )\n simplify swap . [char] \/ emit space . ;\n\n: =rat ( a\/b c\/d -- bool : rational equal )\n crossmultiply rot = -rot = = ;\n\n: >rat ( a\/b c\/d -- bool : rational greater than )\n crossmultiply rot 2drop > ;\n\n: <=rat ( a\/b c\/d -- bool : rational less than or equal to )\n\t>rat not ;\n\n: =rat ( a\/b c\/d -- bool : rational greater or equal to )\n\t0 block number stored in buf)\n\n: invalid? ( n -- : throw if block number is invalid )\n\t0= if -35 throw then ;\n\n: update ( -- : mark currently loaded block buffer as dirty )\n\ttrue dirty ! ;\n\n: updated?\n\tdirty @ ;\n\n: block.name ( n -- c-addr u : make a block name )\n\tc\" .blk\" <# holds #s #> rot drop ;\n\n( @warning this will not work if we do not have permission,\nor in various other cases where we cannot open the file, for\nwhatever reason )\n: file-exists ( c-addr u : does a file exist? )\n\tr\/o open-file if drop 0 else close-file throw 1 then ;\n\n: buffer.exists ( n -- bool : does a block buffer exist on disk? )\n\tblock.name file-exists ;\n\n( @note block.write and block.read do not check if they have\nwrote or read in 1024 bytes, nor do they check that they can\nonly write or read 1024 and not a byte more )\n\n: block.read ( file-id -- file-id : read in buffer )\n\tdup >r buf r> read-file nip if close-file -33 throw then ;\n\n: block.write ( file-id -- file-id : write out buffer )\n\tdup >r buf r> write-file nip if close-file -34 throw then ;\n\n: block.open ( n fam -- file-id )\n\t>r block.name r> open-file throw ;\n\n: save-buffers \n\tblk @ 0= if exit then ( not a valid block number, exit )\n\tdirty @ not if exit then ( not dirty, no need to save )\n\tblk @ w\/o block.open ( open file backing block buffer )\n\tblock.write ( write it out )\n\tclose-file throw ( close it )\n\tfalse dirty ! ; ( but only mark it clean if everything succeeded )\n\n: empty-buffers ( -- : deallocate any saved buffers )\n\t0 blk ! ;\n\n: flush ( -- : perform save-buffers followed by empty-buffers )\n\tsave-buffers\n\tempty-buffers ;\n\n( Block is a complex word that does a lot, although it has a simple\ninterface. It does the following given a block number:\n\n1. Checks the provided block buffer number to make sure it is valid\n2. If the block is already loaded from the disk, then return the\naddress of the block buffer it is loaded into.\n3. If not, it checks to see if the currently loaded block buffer is\ndirty, if it is then it flushes the buffer to disk.\n4. If the block buffer does not exists on disk then it creates it.\n5. It then stores the block number in blk and returns an address to\nthe block buffer. )\n: block ( n -- c-addr : load a block )\n\tdup invalid? \n\tdup blk @ = if drop buf drop exit then\n\tflush\n\tdup buffer.exists if ( if the buffer exits on disk load it in )\n\t\tdup r\/o block.open \n\t\tblock.read \n\t\tclose-file throw \n\telse ( else it does not exist )\n\t\tbuf 0 fill ( clean the buffer )\n\tthen \n\tblk ! ( save the block number )\n\tbuf drop ;\n\n: buffer block ;\n\n( @warning uses hack, block buffer is NUL terminated, and evaluate requires\na NUL terminated string, evaluate checks that the last character is NUL, \nhence the 1+ )\n: load ( n -- : load and execute a block )\n\tblock b\/buf 1+ evaluate throw ;\n\nhide{ \n\tblock.name invalid? block.write \n\tblock.read buffer.exists block.open dirty\n}hide\n\n( ==================== Block Layer =========================== )\n\n( ==================== List ================================== )\n1 variable fancy-list\n0 variable scr\n64 constant c\/l ( characters per line )\n\n: line.number ( n -- : print line number )\n\tfancy-list @ if\n\t\tdup 10 < if space then ( leading space: works up to c\/l = 99)\n\t\t. [char] | emit ( print \" line-number : \")\n\telse\n\t\tdrop\n\tthen ;\n\n: line ( c-addr -- c-addr u : given a line number, display that line )\n\tdup \n\tline.number ( display line number )\n\tc\/l * + ( calculate offset )\n\tc\/l ; ( add line length )\n\n: list.end\n\tfancy-list @ not if exit then\n\t[char] | emit ;\n\n: list.type ( c-addr u -- : list a block )\n\tb\/buf c\/l \/ 0 do dup i line type list.end cr loop drop ;\n\n: list.border \" +---|---\" ;\n\n: list.box\n\tfancy-list @ not if exit then\n\t4 spaces\n\t8 0 do list.border loop cr ;\n\n: list ( n -- : display a block number and update scr )\n\tdup >r block r> scr ! list.box list.type list.box ;\n\n: thru\n\tkey drop\n\t1+ swap do i list more loop ;\n\n: make-blocks ( n1 n2 -- : make blocks on disk from n1 to n2 inclusive )\n\t1+ swap do i block b\/buf bl fill update loop save-buffers ;\n\nhide{ buf line line.number list.type fancy-list }hide\n\n( ==================== List ================================== )\n\n( ==================== Signal Handling ======================= )\n( Signal handling at the moment is quite primitive. When a signal\noccurs it has to be explicitly tested for by the programmer, this\ncould be improved on quite a bit. One way of doing this would be\nto check for signals in the virtual machine and cause a THROW\nfrom within it. )\n\n( signals are biased to fall outside the range of the error numbers\ndefined in the ANS Forth standard. )\n-512 constant signal-bias \n\n: signal ( -- signal\/0 : push the results of the signal register ) \n\t`signal @\n \t0 `signal ! ;\n\n( ==================== Signal Handling ======================= )\n\n( Looking at most Forths dictionary with \"words\" command they tend\nto have a lot of words that do not mean anything but to the implementers\nof that specific Forth, here we clean up as many non standard words as\npossible. )\nhide{ \n do-string ')' alignment-bits \n dictionary-start hidden-mask instruction-mask immediate-mask compiling?\n compile-bit\n max-core dolist doconst x x! x@ \n max-string-length \n _exit\n pnum evaluator \n TrueFalse >instruction \n xt-instruction\n `state\n `source-id `sin `sidx `slen `start-address `fin `fout `stdin\n `stdout `stderr `argc `argv `debug `invalid `top `instruction\n `stack-size `error-handler `x `handler _emit `signal \n}hide\n\n( \n## Forth To List\n\nThe following is a To-Do list for the Forth code itself, along with any\nother ideas.\n\n* FORTH, VOCABULARY\n* \"Value\", \"To\", \"Is\"\n* Double cell words \n* The interpreter should use character based addresses, instead of\nword based, and use values that are actual valid pointers, this\nwill allow easier interaction with the world outside the virtual machine\n* common words and actions should be factored out to simplify\ndefinitions of other words, their standards compliant version found\nif any\n* A soft floating point library would be useful which could be used\nto optionally implement floats [which is not something I really want\nto add to the virtual machine]. If floats were to be added, only the\nminimal set of functions should be added [f+,f-,f\/,f*,f<,f>,>float,...]\n* Allow the processing of argc and argv, the mechanism by which that\nthis can be achieved needs to be worked out. However all processing that\nis currently done in \"main.c\" should be done within the Forth interpreter\ninstead. Words for manipulating rationals and double width cells should\nbe made first.\n* A built in version of \"dump\" and \"words\" should be added to the Forth\nstarting vocabulary, simplified versions that can be hidden.\n* Here documents, string literals. Examples of these can be found online\n* Document the words in this file and built in words better, also turn this\ndocument into a literate Forth file.\n* Sort out \"'\", \"[']\", \"find\", \"compile,\" \n* Proper booleans should be used throughout, that is -1 is true, and 0 is\nfalse.\n* Attempt to add crypto primitives, not for serious use, like TEA, XTEA,\nXXTEA, RC4, MD5, ...\n* Add hash functions: CRC-32, CRC-16, ...\nhttp:\/\/stackoverflow.com\/questions\/10564491\/function-to-calculate-a-crc16-checksum\n* File operation primitives that close the file stream [and possibly restore\nI\/O to stdin\/stdout] if an error occurs, and then re-throws, should be made.\n* Implement as many things from http:\/\/lars.nocrew.org\/forth2012\/implement.html\nas is sensible. \n* CASE Statements http:\/\/dxforth.netbay.com.au\/miser.html\n* The current words that implement I\/O redirection need to be improved, and documented,\nI think this is quite a useful and powerful mechanism to use within Forth that simplifies\nprograms. This is a must and will make writing utilities in Forth a *lot* easier \n* Words for manipulating words should be added, for navigating to different\nfields within them, to the end of the word, etcetera.\n* The data structure used for parsing Forth words needs changing in libforth so a\ncounted string is produced. Counted strings should be used more often. The current\nlayout of a Forth word prevents a counted string being used and uses a byte more\nthan it has to.\n* Whether certain simple words [such as '1+', '1-', '>', '<', '<>', 'not', '<=',\n'>='] should be added as virtual machine instructions for speed [and size] reasons\nshould be investigated.\n* An analysis of the interpreter and the code it executes could be done to find\nthe most commonly executed words and instructions, as well as the most common two and\nthree sequences of words and instructions. This could be used to use to optimize the\ninterpreter, in terms of both speed and size.\n\n### libforth.c todo\n\n* A halt, a parse, and a print\/type instruction could be added to the Forth virtual\nmachine.\n* Throw\/Catch need to be added and used in the virtual machine\n* Various edge cases and exceptions should be removed [for example counted strings\nare not used internally, and '0x' can be used as a prefix only when base is zero].\n* A potential optimization is to order the words in the dictionary by frequency order,\nthis would mean chaning the X Macro that contains the list of words, after collecting\nstatistics. This should make find faster.\n* Investigate adding operating system specific code into the interpreter and\nisolating it to make it semi-portable.\n* Make equivalents for various Unix utilities in Forth, like a CRC check, cat,\ntr, etcetera.\n\n )\n\nverbose [if] \n\t.( FORTH: libforth successfully loaded.) cr\n\t.( Type 'help' and press return for a basic introduction.) cr\n\t.( Core: ) here . \" \/ \" here unused + . cr\n\t license\n[then]\n\n( The following will not work as we might actually be reading from a string [`sin]\nnot `fin. \n: key 32 chars> 1 `fin @ read-file drop 0 = if 0 else 32 chars> c@ then ; )\n\n\\ : ' immediate state @ if postpone ['] else find then ;\n\n( This really does not implement a correct FORTH\/VOCABULARY, for that\nwordlists will need to be introduced and used in libforth.c. The best\nthat this word set can do is to hide and reveal words to the user, this\nwas just an experiment. \n\n\t: forth \n\t\t[ find forth 1- @ ] literal\n\t\t[ find forth 1- ] literal ! ;\n\n\t: vocabulary\n\t\tcreate does> drop 0 [ find forth 1- ] literal ! ; )\n\n( Experimental block editor Mark II )\n( @todo '\\' needs extending to work with the block editor, for now, \nuse parenthesis for comments \n@todo make an 'm' word for forgetting all words defined since the\neditor was invoked.\n@todo add multi line insertion mode\n@todo Add to an editor vocabulary, which will need the vocabulary\nsystem to exist.\n@todo Using 'page' should be optional as not all terminals support\nANSI escape codes - thanks to CMD.EXE. Damned Windows.\n@todo How line numbers are printed out should be investigated,\nalso I should refactor 'dump' to use a similar line number system.\n@todo Format the output of list better, put a nice box around it.\n\nAdapted from http:\/\/retroforth.org\/pages\/?PortsOfRetroEditor )\n: h\npage cr\n\" Block Editor Help Menu\n\n n move to next block\n p move to previous block\n # d delete line in current block\n x erase current block\n e evaluate current block\n # i insert line\n # #2 ia insert at line #2 at column #\n q quit editor loop\n # b set block number\n s save block and write it out\n\n -- press any key to continue -- \" cr ( \" )\nchar drop ;\n\n: (block) blk @ block ; \n: (line) c\/l * (block) + ; ( n -- c-addr : push current line address )\n: n blk @ 1+ block ;\n: p blk @ 1- block ;\n: d (line) c\/l bl fill ; \n: x (block) b\/buf bl fill ;\n: s update save-buffers ;\n: q rdrop rdrop ;\n: e blk @ load ;\n: ia c\/l * + dup b\/buf swap - >r (block) + r> accept ; ( @bug accept NUL terminates the string! )\n: i 0 swap ia ;\n: editor\n\t1 block\n\tpostpone [ \n\tbegin\n\t\tpage cr\n\t\t\" BLOCK EDITOR: TYPE H FOR HELP \" cr\n\t\tblk @ list\n\t\t\" CURRENT BLOCK: \" blk @ . cr\n\t\tread\n\tagain ;\n\n( Extra niceties )\n: u update ;\n: b block ;\n: l blk @ list ;\n\nhide{ (block) (line) }hide\n\nhere fence !\n\n","old_contents":"#!.\/forth \n( Welcome to libforth, A dialect of Forth. Like all versions of Forth this\nversion is a little idiosyncratic, but how the interpreter works is\ndocumented here and in various other files.\n\nThis file contains most of the start up code, some basic start up code\nis executed in the C file as well which makes programming at least bearable.\nMost of Forth is programmed in itself, which may seem odd if your back\nground in programming comes from more traditional language [such as C],\nalthough less so if you know already know lisp.\n\nFor more information about this interpreter and Forth see:\n\thttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\treadme.md : for a manual for this interpreter\n\tlibforth.h : for information about the C API\n\tlibforth.c : for the interpreter itself\n\tunit.c : a series of unit tests against libforth.c\n\tunit.fth : a series of unit tests against this file\n\nThe interpreter and this code originally descend from a Forth interpreter\nwritten in 1992 for the International obfuscated C Coding Competition\n\nSee:\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\nThe manual for the interpreter should be read first before looking into this\ncode. It is important to understand the execution model of Forth, especially\nthe differences between command and compile mode, and how immediate and compiling\nwords work.\n\n@todo Restructure and describe structure of this file.\n\nEach of these sections is clearly labeled and they are generally in dependency order.\n\nUnfortunately the code in this file is not as portable as it could be, it makes\nassumptions about the size of cells provided by the virtual machine, which will\ntake time to rectify. Some of the constructs are subtly different from the\nDPANs Forth specification, which is usually noted. Eventually this should\nalso be fixed.)\n\n( ========================== Basic Word Set ================================== )\n\n( \nWe'll begin by defining very simple words we can use later, these a very\nbasic words, that perform simple tasks, they will not require much explanation.\n\nEven though the words are simple, their stack comment and a description for\nthem will still be included so external tools can process and automatically\nextract the document string for a given work.\n)\n\n: postpone ( -- : postpone execution of the following immediate word )\n\timmediate find , ;\n\n: :: ( -- : compiling version of ':' )\n\t[ find : , ] ;\n\n: constant \n\t:: ( compile word header )\n\there 1 - h ! ( decrement dictionary pointer )\n\there @ instruction-mask invert and doconst or here ! ( change instruction to CONST )\n\there 1 + h ! ( increment dictionary pointer )\n\t, ( write in value )\n\tpostpone [ ; ( back into command mode )\n\n( space saving measure )\n-1 constant -1\n 0 constant 0 \n 1 constant 1\n 2 constant 2\n 3 constant 3\n\n0 constant false\n1 constant true ( @warning not standards compliant )\n\n10 constant nl ( new line )\n\n1 hidden-bit lshift constant hidden-mask ( mask for the hide bit in a words CODE field )\n\n-1 -1 1 rshift invert and constant min-signed-integer\n\nmin-signed-integer invert constant max-signed-integer\n\n1 constant cell ( size of a cell in address units )\n\ncell size 8 * * constant address-unit-bits ( the number of bits in an address )\n\n-1 -1 1 rshift and invert constant sign-bit ( bit corresponding to the sign in a number )\n\n( @todo test by how much, if at all, making words like 1+, 1-, <>, and other\nsimple words, part of the interpreter would speed things up )\n\n: 1+ ( x -- x : increment a number ) \n\t1 + ;\n\n: 1- ( x -- x : decrement a number ) \n\t1 - ;\n\n: chars ( c-addr -- addr : convert a character address to an address )\n\tsize \/ ; \n\n: chars> ( addr -- c-addr: convert an address to a character address )\n\tsize * ; \n\n: tab ( -- : print a tab character to current output device )\n\t9 emit ;\n\n: 0= ( x -- bool : is 'x' equal to zero? )\n\t0 = ;\n\n: not ( x -- bool : is 'x' true? )\n\t0= ;\n\n: <> ( x x -- bool : not equal )\n\t= 0= ;\n\n: logical ( x -- bool : turn a value into a boolean ) \n\tnot not ;\n\n( @todo \": dolit ' ' ;\" works but does not interact well with \n'decompile', if this was fixed the special work could be removed,\nwith some extra effort in libforth.c as well )\n: dolit ( -- x : location of special \"push\" word )\n\t2 ; \n\n: 2, ( x x -- : write two values into the dictionary )\n\t, , ;\n\n: [literal] ( x -- : write a literal into the dictionary )\n\tdolit 2, ; \n\n: literal ( x -- : immediately write a literal into the dictionary )\n\timmediate [literal] ;\n\n: sliteral immediate ( I: c-addr u --, Run: -- c-addr u )\n\tswap [literal] [literal] ;\n\n( @todo throw if not found )\n: ['] ( I: c\" xxx\", Run: -- xt )\n\timmediate find [literal] ;\n\n: >instruction ( CODE -- Instruction : extract instruction from instruction field ) \n\tinstruction-mask and ;\n\n: immediate-mask ( -- x : pushes the mask for the compile bit in a words CODE field )\n\t[ 1 compile-bit lshift ] literal ;\n\n: hidden? ( PWD -- PWD bool : is a word hidden, given the words PWD field ) \n\tdup 1+ @ hidden-mask and logical ;\n\n: compiling? ( PWD -- PWD bool : is a word immediate, given the words PWD field )\n\tdup 1+ @ immediate-mask and logical ;\n\n\n: cr ( -- : emit a newline character )\n\tnl emit ;\n\n: < ( x1 x2 -- bool : signed less than comparison )\n\t- dup if max-signed-integer u> else logical then ;\n\n: > ( x1 x2 -- bool : signed greater than comparison )\n\t- dup if max-signed-integer u< else logical then ;\n\n: #pad ( -- u : offset into pad area )\n\t64 ;\n\n: pad\n\t( the pad is used for temporary storage, and moves\n\talong with dictionary pointer, always in front of it )\n\there #pad + ;\n\n( @todo this can be improved a lot, currently it uses more\nspace than it has to, 4 cells instead of three.\n\nIt does:\n\n\tpush value\n\tpush value\n\nInstead of:\n\n\tmagic-2literal-word\n\tvalue\n\tvalue\n\n)\n: 2literal immediate ( x x -- : immediate write two literals into the dictionary )\n\tswap [literal] [literal] ;\n\n: latest ( get latest defined word )\n\tpwd @ ; \n\n: stdin ( -- fileid : push the fileid for the standard input channel ) \n\t`stdin @ ;\n\n: stdout ( -- fileid : push the fileid for the standard output channel ) \n\t`stdout @ ;\n\n: stderr ( -- fileid : push the fileid for the standard error channel ) \n\t`stderr @ ;\n\n: stdin? ( -- bool : are we reading from standard input )\n\t`fin @ stdin = ;\n\n: *+ ( x1 x2 x3 -- x ) \n\t* + ;\n\t\n: 2- ( x -- x : decrement by two )\n\t2 - ( x -- x ) ;\n\n: 2+ ( x -- x : increment by two )\n\t2 + ( x -- x ) ;\n\n: 3+ ( x -- x : increment by three )\n\t3 + ( x -- x ) ;\n\n: 2* ( x -- x : multiply by two )\n\t1 lshift ( x -- x ) ;\n\n: 2\/ ( x -- x : divide by two )\n\t1 rshift ( x -- x ) ;\n\n: 4* ( x -- x : multiply by four )\n\t2 lshift ( x -- x ) ;\n\n: 4\/ ( x -- x : divide by four )\n\t2 rshift ( x -- x ) ;\n\n: 8* ( x -- x : multiply by eight )\n\t3 lshift ( x -- x ) ;\n\n: 8\/ ( x -- x : divide by eight )\n\t3 rshift ( x -- x ) ;\n\n: 256* ( x -- x : multiply by 256 )\n\t8 lshift ( x -- x ) ;\n\n: 256\/ ( x -- x : divide by 256 )\n\t8 rshift ( x -- x ) ;\n\n: 2dup ( x1 x2 -- x1 x2 x1 x2 : duplicate two values )\n\tover over ;\n\n: mod ( x u -- x : calculate the remainder of x divided by u ) \n\t2dup \/ * - ;\n\n( @todo implement um\/mod in the VM, then use this to implement \/ and mod )\n: um\/mod ( x1 x2 -- rem quot : calculate the remainder and quotient of x1 divided by x2 ) \n\t2dup \/ >r mod r> ;\n\n: *\/ ( x1 x2 x3 -- x4 : multiply then divide, @warning this does not use a double cell for the multiply )\n\t * \/ ; \n\n: char ( -- x : read in a character from the input steam )\n\tkey drop key ;\n\n: [char] ( -- x : immediately read in a character from the input stream )\n\timmediate char [literal] ;\n\n: compose ( xt1 xt2 -- xt3 : create a new function from two xt-tokens )\n\t>r >r ( save execution tokens )\n\tpostpone :noname ( create a new :noname word for our xt-tokens )\n\tr> , ( write first token )\n\tr> , ( write second token )\n\tpostpone ; ; ( terminate new :noname )\n\n: unless ( bool -- : like 'if' but execute clause if false )\n\timmediate ['] 0= , postpone if ;\n\n: endif ( synonym for 'then' ) \n\timmediate postpone then ;\n\n: cells ( n1 -- n2 : convert a number of cells into a number of cells in address units ) \n\timmediate ;\n\n: cell+ ( a-addr1 -- a-addr2 ) \n\tcell + ;\n\n: negative? ( x -- bool : is a number negative? )\n\tsign-bit and logical ;\n\n: mask-byte ( x -- x : generate mask byte ) \n\t8* 255 swap lshift ;\n\n: select-byte ( u i -- c ) \n\t8* rshift 0xff and ;\n\n: xt-instruction ( extract instruction from execution token )\n\tcell+ @ >instruction ;\n\n: defined-word? ( CODE -- bool : is a word a defined or a built in words )\n\txt-instruction dolist = ;\n\n: char+ ( c-addr -- c-addr : increment a character address by the size of one character ) \n\t1+ ;\n\n: 2chars ( c-addr1 c-addr2 -- addr addr : convert two character addresses to two cell addresses ) \n\tchars swap chars swap ;\n\n: 2chars> ( addr addr -- c-addr c-addr: convert two cell addresses to two character addresses )\n\tchars> swap chars> swap ;\n\n: hex ( -- : print out hex ) \n\t16 base ! ;\n\n: octal ( -- : print out octal ) \n\t8 base ! ;\n\n: binary ( -- : print out binary ) \n\t2 base ! ;\n\n: decimal ( -- : print out decimal ) \n\t0 base ! ;\n\n: negate ( x -- x ) \n\t-1 * ;\n\n: abs ( x -- u : return the absolute value of a number )\n\tdup negative? if negate then ;\n\n: square ( x -- x ) \n\tdup * ;\n\n: sum-of-squares ( a b -- c : compute a^2 + b^2 to get c )\n\tsquare swap square + ;\n\n: drup ( x y -- x x ) \n\tdrop dup ;\n\n: +! ( x addr -- : add x to a value stored at addr ) \n\ttuck @ + swap ! ;\n\n: 1+! ( addr -- : increment a value at an address ) \n\t1 swap +! ;\n\n: 1-! ( addr -- : decrement a value at an address ) \n\t-1 swap +! ;\n\n: c+! ( x c-addr -- : add x to a value stored at c-addr )\n\ttuck c@ + swap c! ;\n\n: toggle ( addr u -- : complement the value at address with the bit pattern u ) \n\tover @ xor swap ! ;\n\n: lsb ( x -- x : mask off the least significant byte of a cell ) \n\t255 and ;\n\n: \\ ( -- : immediate word, used for single line comments )\n\timmediate begin key nl = until ;\n\n: ?dup ( x -- ? ) \n\tdup if dup then ;\n\n: min ( x y -- min : return the minimum of two integers ) \n\t2dup < if drop else swap drop then ;\n\n: max ( x y -- max : return the maximum of two integers ) \n\t2dup > if drop else swap drop then ;\n\n: limit ( x min max -- x : limit x with a minimum and maximum )\n\trot min max ;\n\n: >= ( x y -- bool ) \n\t< not ;\n\n: <= ( x y -- bool ) \n\t> not ;\n\n: 2@ ( a-addr -- x1 x2 : load two consecutive memory cells )\n\tdup 1+ @ swap @ ;\n\n: 2! ( x1 x2 a-addr -- : store two values as two consecutive memory cells )\n\t2dup ! nip 1+ ! ;\n\n: r@ ( -- x, R: x -- )\n\tr> r @ swap >r ;\n\n: rp@ ( -- x, R: x -- )\n\tr> r @ swap >r ;\n\n( @todo r!, rp! )\n\n: 0> ( x -- bool )\n\t0 > ;\n\n: 0< ( x -- bool )\n\t0 < ;\n\n: 0<> ( x -- bool )\n\t0 <> ;\n\n: signum ( x -- -1 | 0 | 1 : )\n\tdup 0< if drop -1 exit then\n\t 0> if 1 exit then\n\t0 ;\n\n: nand ( x x -- x : bitwise NAND ) \n\tand invert ;\n\n: odd ( x -- bool : is 'x' odd? )\n\t1 and ;\n\n: even ( x -- bool : is 'x' even? )\n\todd not ;\n\n: nor ( x x -- x : bitwise NOR ) \n\tor invert ;\n\n: ms ( u -- : wait at least 'u' milliseconds ) \n\tclock + begin dup clock u< until drop ;\n\n: sleep ( u -- : sleep for 'u' seconds )\n\t1000 * ms ;\n\n: align ( addr -- addr : align an address, nop in this implemented )\n\timmediate ; \n\n: ) ( -- : do nothing, this allows easy commenting out of code )\n\timmediate ;\n\n: bell ( -- : emit an ASCII BEL character ) \n\t7 emit ;\n\n: b\/buf ( -- u : bytes per buffer ) \n\t1024 ;\n\n: .d ( x -- x : debug print ) \n\tdup . ;\n\n: compile, ( x -- : )\n\t, ;\n\n: >mark ( -- : write a hole into the dictionary and push a pointer to it ) \n\there 0 , ;\n\n: r - r> u< ;\n\n: invalidate ( -- : invalidate this Forth core )\n\t1 `invalid ! ;\n\n: signed ( x -- bool : return true if sign bit set ) \n\t[ 1 size 8 * 1- lshift ] literal and logical ;\n\n: u>= ( x y -- bool : unsigned greater than or equal to )\n\t2dup u> >r = r> or ;\n\n: u<= ( x y -- bool : unsigned less than or equal to )\n\tu>= not ;\n\n: rdrop ( R: x -- : drop a value from the return stack )\n\tr> ( get caller's return address )\n\tr> ( get value to drop )\n\tdrop ( drop it like it's hot )\n\t>r ; ( return return address )\n\n: rdup\n\tr> ( get caller's return address )\n\tr> ( get value to duplicate )\n\tdup ( ... )\n\t>r >r >r ; ( make it all work )\n\n: again immediate\n\t( loop unconditionally in a begin-loop:\n\t\tbegin ... again )\n\t' branch , ;\n\n: source ( -- c-addr u )\n\t#tib ( size of input buffer, in characters )\n\ttib ; ( start of input buffer, in characters )\n\n: stdin? ( -- bool : are we reading from standard in? )\n\t`fin @ `stdin @ = ;\n\n: source-id ( -- 0 | -1 | file-id )\n\t( \t\n\tValue Input Source\n\t-1 String\n\t0 Reading from user input \/ standard in\n\tfile-id )\n\t`source-id @ \n\t0= if\n\t\tstdin? if 0 else `fin @ then\n\telse\n\t\t-1\n\tthen ;\n\n: under ( x1 x2 -- x1 x1 x2 )\n\t>r dup r> ;\n\n: 2nip ( n1 n2 n3 n4 -- n3 n4 ) \n\t>r >r 2drop r> r> ;\n\n: 2over ( n1 n2 n3 n4 \u2013 n1 n2 n3 n4 n1 n2 )\n\t>r >r 2dup r> swap >r swap r> r> -rot ;\n\n: 2swap ( n1 n2 n3 n4 \u2013 n3 n4 n1 n2 )\n\t>r -rot r> -rot ;\n\n: 2tuck ( n1 n2 n3 n4 \u2013 n3 n4 n1 n2 n3 n4 )\n\t2swap 2over ;\n\n: 3drop ( x1 x2 x3 -- )\n\t2drop ;\n\n: nos1+ ( x1 x2 -- x1+1 x2 : increment the next variable on that stack )\n\tswap 1+ swap ;\n\n: ?dup-if immediate ( x -- x | - : ?dup and if rolled into one! )\n\t['] ?dup , postpone if ;\n\n: ?if ( -- : non destructive if ) \n\timmediate ['] dup , postpone if ;\n\n: hide ( token -- hide-token : this hides a word from being found by the interpreter )\n\t?dup-if\n\t\tdup @ hidden-mask or swap tuck ! exit\n\tthen 0 ;\n\n: hider ( WORD -- : hide with drop ) \n\tfind dup if hide then drop ;\n\n: reveal ( hide-token -- : reveal a hidden word ) \n\tdup @ hidden-mask invert and swap ! ;\n\n: ?exit ( x -- : exit current definition if not zero ) \n\tif rdrop exit then ;\n\n: number? ( c -- f : is character a number? )\n\t[char] 0 [ char 9 1+ ] literal within ;\n\n: lowercase? ( c -- f : is character lower case? )\n\t[char] a [ char z 1+ ] literal within ;\n\n: uppercase? ( C -- f : is character upper case? )\n\t[char] A [ char Z 1+ ] literal within ;\n\n: alpha? ( C -- f : is character part of the alphabet? )\n\tdup lowercase? swap uppercase? or ;\n\n: alphanumeric? ( C -- f : is character alphabetic or a number ? )\n\tdup alpha? swap number? or ;\n\n: printable? ( c -- bool : is printable, excluding new lines and tables )\n\t32 127 within ;\n\n: >upper ( c -- C : convert char to uppercase iff lower case )\n\tdup lowercase? if bl xor then ;\n\n: >lower ( C -- c : convert char to lowercase iff upper case )\n\tdup uppercase? if bl xor then ;\n\n: <=> ( x y -- z : spaceship operator! )\n\t2dup\n\t> if 2drop -1 exit then\n\t< ;\n\n: start-address ( -- c-addr : push the start address )\n\t`start-address @ ;\n\n: >real-address ( c-addr -- r-addr : convert an interpreter address to a real address )\n\tstart-address + ;\n\n: real-address> ( c-addr -- r-addr : convert a real address to an interpreter address )\n\tstart-address - ;\n\n: peek ( r-addr -- n : )\n\tpad chars> >real-address swap size memory-copy pad @ ;\n\n: poke ( n r-addr -- : )\n\tswap pad ! pad chars> >real-address size memory-copy ;\n\n: die! ( x -- : controls actions when encountering certain errors )\n\t`error-handler ! ;\n\n: start! ( cfa -- : set the word to execute at startup )\n\t`instruction ! ;\t\n\n: warm ( -- : restart the interpreter, warm restart )\n\t1 restart ;\n\n: trip ( x -- x x x : triplicate a number ) \n\tdup dup ;\n\n: roll ( xu xu-1 ... x0 u -- xu-1 ... x0 xu : move u+1 items on the top of the stack by u )\n\tdup 0 >\n\tif\n\t\tswap >r 1- roll r> swap\n\telse\n\t\tdrop\n\tthen ;\n\n: 2rot ( n1 n2 n3 n4 n5 n6 \u2013 n3 n4 n5 n6 n1 n2 )\n\t5 roll 5 roll ;\n\n: s>d ( x -- d : convert a signed value to a double width cell )\n\t( @note the if...else...then is only necessary as this Forths\n\tbooleans are 0 and 1, not 0 and -1 as it usually is )\n\tdup 0< if -1 else 0 then ;\n\n: trace ( level -- : set tracing level )\n\t`debug ! ;\n\n: verbose ( -- : get the log level )\n\t`debug @ ;\n\n: count ( c-addr1 -- c-addr2 u : get a string whose first char is its length )\n\tdup c@ nos1+ ;\n\n: bounds ( x y -- y+x x : make an upper and lower bound )\n\tover + swap ;\n\n: aligned ( unaligned -- aligned : align a pointer )\n\t[ size 1- ] literal + \n\t[ size 1- ] literal invert and ;\n\n: rdepth\n\tmax-core `stack-size @ - r @ swap - ;\n\n: r.s ( -- : print the contents of the return stack )\n\tr> \n\t[char] < emit rdepth . [char] > emit\n\tspace\n\trdepth dup 0> if dup\n\tbegin dup while r> -rot 1- repeat drop dup\n\tbegin dup while rot dup . >r 1- repeat drop\n\tthen drop cr \n\t>r ;\n\n: argv ( -- r-addr : push pointer to array of string pointers to program )\n\t`argv @ ;\n\n: argc ( -- u : push the number of arguments in the argv array )\n\t`argc @ ;\n\n: +- ( x1 x2 -- x3 : copy the sign of x1 to x2 giving x3 )\n\t[ sign-bit 1- ] literal and\n\tswap\n\tsign-bit and or\n\t;\n\nhider stdin?\n\n( ================================== DUMP ================================== )\n\\ : newline ( x -- x+1 : print a new line every fourth value )\n\\ \tdup 3 and 0= if cr then 1+ ;\n\\ \n\\ : address ( num count -- count : print current address we are dumping every fourth value )\n\\ \tdup >r\n\\ \t1- 3 and 0= if . [char] : emit space else drop then\n\\ \tr> ;\n\\ \n\\ : dump ( start count -- : print the contents of a section of memory )\n\\ \\\thex ( switch to hex mode )\n\\ \t1 >r ( save counter on return stack )\n\\ \tover + swap ( calculate limits: start start+count )\n\\ \tbegin \n\\ \t\t2dup u> ( stop if gone past limits )\n\\ \twhile \n\\ \t\tdup r> address >r\n\\ \t\tdup @ . 1+ \n\\ \t\tr> newline >r\n\\ \trepeat \n\\ \tr> drop\n\\ \t2drop ;\n\\ \n\\ hider newline\n\\ hider address \n( ================================== DUMP ================================== )\n\n: cfa immediate ( find-address -- cfa )\n\t( Given the address of the PWD field of a word this\n\tfunction will return an execution token for the word )\n\t( @todo if < dictionary start PWD is invalid )\n\t ;\n\n\\ : >body ( xt -- a-addr : a-addr is data field of a CREATEd word )\n\\\tcfa 5 + ;\n\n\n: execute ( xt -- : given an execution token, execute the word )\n\t( create a word that pushes the address of a hole to write to.\n\tA literal takes up two words, '!' takes up one, that's right,\n\tsome self modifying code! )\n\t[ here 3 cells + literal ] ( calculate place to write to )\n\t! ( write an execution token to a hole )\n\t[ 0 , ] ; ( this is the hole we write )\n\n( See: http:\/\/lars.nocrew.org\/dpans\/dpans9.htm\n@todo turn this into a lookup table of strings\n\n Code Reserved for\n ---- ------------\n -1 ABORT\n -2 ABORT\"\n -3 stack overflow\n -4 stack underflow\n -5 return stack overflow\n -6 return stack underflow\n -7 do-loops nested too deeply during execution\n -8 dictionary overflow\n -9 invalid memory address\n -10 division by zero\n -11 result out of range\n -12 argument type mismatch\n -13 undefined word\n -14 interpreting a compile-only word\n -15 invalid FORGET\n -16 attempt to use zero-length string as a name\n -17 pictured numeric output string overflow\n -18 parsed string overflow\n -19 definition name too long\n -20 write to a read-only location\n -21 unsupported operation [e.g., AT-XY on a\n too-dumb terminal]\n -22 control structure mismatch\n -23 address alignment exception\n -24 invalid numeric argument\n -25 return stack imbalance\n -26 loop parameters unavailable\n -27 invalid recursion\n -28 user interrupt\n -29 compiler nesting\n -30 obsolescent feature\n -31 >BODY used on non-CREATEd definition\n -32 invalid name argument [e.g., TO xxx]\n -33 block read exception\n -34 block write exception\n -35 invalid block number\n -36 invalid file position\n -37 file I\/O exception\n -38 non-existent file\n -39 unexpected end of file\n -40 invalid BASE for floating point conversion\n -41 loss of precision\n -42 floating-point divide by zero\n -43 floating-point result out of range\n -44 floating-point stack overflow\n -45 floating-point stack underflow\n -46 floating-point invalid argument\n -47 compilation word list deleted\n -48 invalid POSTPONE\n -49 search-order overflow\n -50 search-order underflow\n -51 compilation word list changed\n -52 control-flow stack overflow\n -53 exception stack overflow\n -54 floating-point underflow\n -55 floating-point unidentified fault\n -56 QUIT\n -57 exception in sending or receiving a character\n -58 [IF], [ELSE], or [THEN] exception )\n\n( @todo integrate catch\/throw into the interpreter as primitives )\n: catch ( xt -- exception# | 0 : return addr on stack )\n\tsp@ >r ( xt : save data stack pointer )\n\t`handler @ >r ( xt : and previous handler )\n\tr@ `handler ! ( xt : set current handler )\n\texecute ( execute returns if no throw )\n\tr> `handler ! ( restore previous handler )\n\tr> drop ( discard saved stack ptr )\n\t0 ; ( 0 : normal completion )\n\n( @todo use this everywhere )\n: throw ( ??? exception# -- ??? exception# )\n\t?dup-if ( exc# \\ 0 throw is no-op )\n\t\t`handler @ r ! ( exc# : restore prev return stack )\n\t\tr> `handler ! ( exc# : restore prev handler )\n\t\tr> swap >r ( saved-sp : exc# on return stack )\n\t\tsp! drop r> ( exc# : restore stack )\n\t\t( return to the caller of catch because return )\n\t\t( stack is restored to the state that existed )\n\t\t( when catch began execution )\n\tthen ; \n\n: interpret ( c1\" xxx\" ... cn\" xxx\" -- : This word implements the interpreter loop )\n\tbegin \n\t' read catch \n\t?dup-if [char] ! emit tab . cr then ( exception handler of last resort )\n\tagain ;\n\n: [interpret] ( c1\" xxx\" ... cn\" xxx\" -- : immediate version of interpret )\n\timmediate interpret ;\n\ninterpret ( use the new interpret word, which can catch exceptions )\n\nfind [interpret] cell+ start! ( the word executed on restart is now our new word )\n\n\n( ========================== Basic Word Set ================================== )\n\n( ========================== DOER\/MAKE ======================================= )\n( DOER\/MAKE is a word set that is quite powerful and is described in Leo Brodie's\nbook \"Thinking Forth\". It can be used to make words whose behavior can change\nafter they are defined. It essentially makes the structured use of self-modifying\ncode possible, along with the more common definitions of \"defer\/is\".\n\nAccording to \"Thinking Forth\", it has two purposes:\n\n1. To change the state of a function.\n2. To factor out common phrases of a words definition.\n\nAn example of the first instance:\n\n\tdoer say\n\t: sad \" Good bye, cruel World!\" cr ;\n\t: happy \" Hello, World!\" cr ;\n\n\t: person say ;\n\n\tmake person happy\n\tperson \\ prints \"Good bye, cruel World!\"\n\n\tmake person sad \n\tperson \\ prints \"Hello, World!\" \n\nAn example of the second:\n\n\tdoer op\n\n\t: sum \\ n0 ... nX X -- sum<0..X> \n\t\tmake op + 1 do op loop ;\n\n\t: mul \\ n0 ... nX X -- mul<0..X> \n\t\tmake op * 1 do op loop ;\n\nThe above example is a bit contrived, the definitions and functionality\nare too simple for this to be worth factoring out, but it shows how you\ncan use DOER\/MAKE. )\n\n: noop ; ( -- : default word to execute for doer )\n\n: doer ( c\" xxx\" -- : )\n\t:: ['] noop , postpone ; ;\n\n: found? ( xt -- xt : thrown an exception if the execution token is zero [not found] ) \n\tdup 0= if -13 throw then ;\n\n( It would be nice to provide a MAKE that worked with execution tokens\nas well, although \"defer\" and \"is\" can be used for that. MAKE expects\ntwo word names to be given as arguments. It will then change the behavior \nof the first word to use the second. MAKE is a state aware word. )\n\n: make immediate ( c1\" xxx\" c2\" xxx\" : change parsed word c1 to execute c2 )\n\tfind found? cell+\n\tfind found?\n\tstate @ if ( compiling )\n\t\tswap postpone 2literal ['] ! ,\n\telse ( command mode )\n\t\tswap !\n\tthen ;\n\nhider noop\n\n( ========================== DOER\/MAKE ======================================= )\n\n( ========================== Extended Word Set =============================== )\n\n: log2 ( x -- log2 )\n\t( Computes the binary integer logarithm of a number,\n\tzero however returns itself instead of reporting an error )\n\t0 swap\n\tbegin\n\t\tnos1+ 2\/ dup 0=\n\tuntil\n\tdrop 1- ;\n\n: time ( \" ccc\" -- n : time the number of milliseconds it takes to execute a word )\n\tclock >r\n\tfind execute\n\tclock r> - ;\n\n( defer...is is probably not standards compliant, it is still neat! )\n: (do-defer) ( -- self : pushes the location into which it is compiled )\n\tr> dup >r 1- ;\n\n: defer ( \" ccc\" -- , Run Time -- location : \n\tcreates a word that pushes a location to write an execution token into )\n\t:: ' (do-defer) , postpone ; ;\n\n: is ( location \" ccc\" -- : make a deferred word execute a word ) \n\tfind found? swap ! ;\n\nhider (do-defer)\nhider found?\n\n( The \"tail\" function implements tail calls, which is just a jump\nto the beginning of the words definition, for example this\nword will never overflow the stack and will print \"1\" followed\nby a new line forever,\n\n\t: forever 1 . cr tail ;\n\nWhereas\n\n\t: forever 1 . cr recurse ;\n\nor\n\n\t: forever 1 . cr forever ;\n\nWould overflow the return stack. )\n\nhider tail\n: tail ( -- : perform tail recursion in current word definition )\n\timmediate\n\tlatest cell+\n\t' branch ,\n\there - cell+ , ;\n\n: recurse immediate\n\t( This function implements recursion, although this interpreter\n\tallows calling a word directly. If used incorrectly this will\n\tblow up the return stack.\n\n\tWe can test \"recurse\" with this factorial function:\n\t : factorial dup 2 < if drop 1 exit then dup 1- recurse * ; )\n\tlatest cell+ , ;\n\n: factorial ( x -- x : compute the factorial of a number )\n\tdup 2 < if drop 1 exit then dup 1- recurse * ;\n\n: myself ( -- : myself is a synonym for recurse ) \n\timmediate postpone recurse ;\n\n: gcd ( x1 x2 -- x : greatest common divisor )\n\tdup if tuck mod tail then drop ;\n\n( ========================== Extended Word Set =============================== )\n\n( The words described here on out get more complex and will require more\nof an explanation as to how they work. )\n\n( ========================== CREATE DOES> ==================================== )\n\n( The following section defines a pair of words \"create\" and \"does>\" which\nare a powerful set of words that can be used to make words that can create\nother words. \"create\" has both run time and compile time behavior, whilst\n\"does>\" only works at compile time in conjunction with \"create\". These two\nwords can be used to add constants, variables and arrays to the language,\namongst other things.\n\nA simple version of create is as follows\n\n\t: create :: dolist , here 2 cells + , ' exit , 0 state ! ;\n\nBut this version is much more limited.\n\n\"create\"...\"does>\" is one of the constructs that makes Forth Forth, it\nallows the creation of words which can define new words in themselves,\nand thus allows us to extend the language easily.\n)\n\n: write-quote ( -- : A word that writes ' into the dictionary )\n\t['] ' , ; \n\n: write-exit ( -- : A word that write exit into the dictionary )\n\t['] _exit , ;\n\n: write-compile, ( -- : A word that writes , into the dictionary ) \n\t' , , ;\n\n: state! ( bool -- : set the compilation state variable ) \n\tstate ! ;\n\n: command-mode ( -- : put the interpreter into command mode )\n\tfalse state! ;\n\n: command-mode-create ( create a new work that pushes its data field )\n\t:: ( compile a word )\n\tdolit , ( write push into new word )\n\there 2 cells + , ( push a pointer to data field )\n\tpostpone ; ; ( write exit and switch to command mode )\n\n: mark write-compile, ( Write in a place holder 0 and push a pointer to to be used by does> )\n\twrite-quote write-exit write-compile, ( Write in an exit in the word we're compiling. )\n\t['] command-mode , ; ( Make sure to change the state back to command mode )\n\n: create immediate ( create word is quite a complex forth word )\n\tstate @ \n\tif \n\t\tpostpone ( hole-to-patch -- )\n\timmediate\n\twrite-exit ( we don't want the defining word to exit, but the *defined* word to )\n\there swap ! ( patch in the code fields to point to )\n\tdolist , ; ( write a run in )\n\nhider write-quote\nhider write-compile,\nhider write-exit\n\n( Now that we have create...does> we can use it to create arrays, variables\nand constants, as we mentioned before. )\n\n: array ( u c\" xxx\" -- : create a named array of length u ) \n\tcreate allot does> + ;\n\n: variable ( x c\" xxx\" -- : create a variable will initial value of x )\n\tcreate , does> ;\n\n\\ : constant ( x c\" xxx\" -- : create a constant with value of x ) \n\\\tcreate , does> @ ;\n\n: table ( u c\" xxx\" --, Run Time: -- addr u : create a named table )\n\tcreate dup , allot does> dup @ ;\n\n: string ( u c\" xxx\" --, Run Time: -- c-addr u : create a named string )\n\tcreate dup , chars allot does> dup @ swap 1+ chars> swap ;\n\n\\ : +field \\ n <\"name\"> -- ; exec: addr -- 'addr\n\\ create over , +\n\\ does> @ + ;\n\\ \n\\ : begin-structure \\ -- addr 0 ; -- size\n\\ \tcreate\n\\ \there 0 0 , \\ mark stack, lay dummy\n\\ \tdoes> @ ; \\ -- rec-len\n\\ \n\\ : end-structure \\ addr n --\n\\ swap ! ; \\ set len \n\\ \n\\ begin-structure point\n\\ \tpoint +field p.x\n\\ \tpoint +field p.y\n\\ end-structure\n\\ \n\\ This should work...\n\\ : buffer: ( u c\" xxx\" --, Run Time: -- addr )\n\\\tcreate allot ;\n\n: 2constant \n\tcreate , , does> dup 1+ @ swap @ ;\n\n: 2variable \n\tcreate , , does> ;\n\n: enum ( x \" ccc\" -- x+1 : define a series of enumerations )\n\tdup constant 1+ ; \n\n( ========================== CREATE DOES> ==================================== )\n\n( ========================== DO...LOOP ======================================= )\n\n( The following section implements Forth's do...loop constructs, the\nword definitions are quite complex as it involves a lot of juggling of\nthe return stack. Along with begin...until do loops are one of the\nmain looping constructs. \n\nUnlike begin...until do accepts two values a limit and a starting value,\nthey are also words only to be used within a word definition, some Forths\nextend the semantics so looping constructs operate in command mode, this\nForth does not do that as it complicates things unnecessarily.\n\nExample:\n\t\n\t: example-1 10 1 do i . i 5 > if cr leave then loop 100 . cr ; \n\texample-1\n\nPrints:\n\t1 2 3 4 5 6\n\nIn \"example-1\" we can see the following:\n\n1. A limit, 10, and a start value, 1, passed to \"do\".\n2. A word called 'i', which is the current count of the loop\n3. If the count is greater than 5, we call a word call 'leave', this\nword exits the current loop context as well as the current calling\nword.\n4. \"100 . cr\" is never called. This should be changed in future\nrevision, but this version of leave exits the calling word as well.\n\n'i', 'j', and 'leave' *must* be used within a do...loop construct. \n\nIn order to remedy point 4. loop should not use branch but instead \nshould use a value to return to which it pushes to the return stack )\n\n: (do)\n\tswap ( swap the limit and start )\n\tr> ( save our return stack to temporary variable )\n\t-rot ( limit start return -- return start limit )\n\t>r ( push limit onto return stack )\n\t>r ( push start onto return stack )\n\t>r ; ( restore our return address )\n\n: do immediate ( Run time: high low -- : begin do...loop construct )\n\t' (do) ,\n\tpostpone begin ; \n\n: (unloop) ( -- , R: i limit -- : remove limit and i from )\n\tr> ( save our return address )\n\trdrop ( pop off i )\n\trdrop ( pop off limit )\n\t>r ; ( restore our return stack )\n\n: (+loop) ( x -- bool : increment loop variable by x and test it )\n\tr@ 1- ( get the pointer to i )\n\t+! ( add value to it )\n\tr@ 1- @ ( find i again )\n\tr@ 2- @ ( find the limit value )\n\tu>= ;\n\n: (loop) ( -- bool : increment loop variable by 1 and test it )\n\tr@ 1- ( get the pointer to i )\n\t1+! ( add one to it )\n\tr@ 1- @ ( find the value again )\n\tr@ 2- @ ( find the limit value )\n\tu>= ;\n\n: loop ( -- : end do...loop construct )\n\timmediate ' (loop) , postpone until ' (unloop) , ;\n\n: +loop ( x -- : end do...+loop loop construct )\n\timmediate ' (+loop) , postpone until ' (unloop) , ;\n\n: leave ( -- , R: i limit return -- : break out of a do-loop construct )\n\t(unloop)\n\trdrop ; ( return to the caller's caller routine )\n\n: ?leave ( x -- , R: i limit return -- | i limit return : conditional leave )\n\tif\n\t\t(unloop)\n\t\trdrop ( return to the caller's caller routine )\n\tthen ;\n\n: i ( -- i : Get current, or innermost, loop index in do...loop construct )\n\tr> r> ( pop off return address and i )\n\ttuck ( tuck i away )\n\t>r >r ; ( restore return stack )\n\n: j ( -- j : Get outermost loop index in do...loop construct )\n\t4 rpick ;\n\n( This is a simple test function for the looping, for interactive\ntesting and debugging:\n : mm 5 1 do i . cr 4 1 do j . tab i . cr loop loop ; )\n\n: range ( nX nY -- nX nX+1 ... nY ) \n\tnos1+ do i loop ;\n\n: repeater ( n0 X -- n0 ... nX ) \n\t1 do dup loop ;\n\n: sum ( n0 ... nX X -- sum<0..X> ) \n\t1 do + loop ;\n\n: mul ( n0 ... nX X -- mul<0..X> ) \n\t1 do * loop ;\n\n: reverse ( x1 ... xn n -- xn ... x1 : reverse n items on the stack )\n\t0 do i roll loop ;\n\n( ========================== DO...LOOP ======================================= )\n\n0 variable column-counter\n4 variable column-width\n\n: column ( i -- )\t\n\tcolumn-width @ mod not if cr then ;\n\n: column.reset\t\t\n\t0 column-counter ! ;\n\n: auto-column\t\t\n\tcolumn-counter dup @ column 1+! ;\n\n: alignment-bits \n\t[ 1 size log2 lshift 1- literal ] and ;\n\n\n0 variable x\n: x! ( x -- ) \n\tx ! ;\n\n: x@ ( -- x ) \n\tx @ ;\n\n: 2>r ( x1 x2 -- R: x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tswap\n\t\t>r\n\t\t>r\n\tx@ >r ; ( restore return address )\n\n: 2r> ( R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tr>\n\t\tr>\n\t\tswap\n\tx@ >r ; ( restore return address )\n\n: 2r@ ( -- x1 x2 , R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\tr> r>\n\t2dup\n\t>r >r\n\tswap\n\tx@ >r ; ( restore return address )\n\n: unused ( -- u : push the amount of core left ) \n\tmax-core here - ;\n\n: accumulator ( initial \" ccc\" -- : make a word that increments by a value and pushes the result )\n\tcreate , does> tuck +! @ ;\n\n: counter ( \" ccc\" --, Run Time: -- x : make a word that increments itself by one, starting from zero )\n\tcreate -1 , does> dup 1+! @ ;\n\n0 variable delim\n: accepter ( c-addr max delimiter -- i )\n\t( store a \"max\" number of chars at c-addr until \"delimiter\" encountered,\n\tthe number of characters stored is returned )\n\tdelim ! ( store delimiter used to stop string storage when encountered)\n\t0\n\tdo\n\t\tkey dup delim @ <>\n\t\tif\n\t\t\tover c! 1+\n\t\telse ( terminate string )\n\t\t\tdrop 0 swap c! \n\t\t\ti \n\t\t\tleave\n\t\tthen\n\tloop\n\t-18 throw ; ( read in too many chars )\nhider delim\n\n: skip\n\tkey drop >r 0 begin drop key dup rdup r> <> until rdrop ;\n\n: word ( c -- c-addr : parse until 'c' is encountered, push transient counted string )\n\tdup skip chere 1+ c!\n\t>r\n\tchere 2+\n\tpad here - chars>\n\tr> accepter 1+\n\tchere c!\n\tchere ;\n\nhider skip\n\n: accept ( c-addr +n1 -- +n2 : see accepter definition ) \n\tnl accepter ;\n\n0xFFFF constant max-string-length\n\n: (.\") ( char -- c-addr u )\n\t( @todo This really needs simplifying, to do this\n\ta set of words that operate on a temporary buffer can\n\tbe used )\n\t( Write a string into word being currently defined, this\n\tcode has to jump over the string it has just put into the\n\tdictionary so normal execution of a word can continue. The\n\tlength and character address of the string are left on the\n\tstack )\n\t>r ( save delimiter )\n\t' branch , ( write in jump, this will jump past the string )\n\t>mark ( make hole )\n\tdup 1+ chars> ( calculate address to write to )\n\tmax-string-length \n\tr> ( restore delimiter )\n\taccepter dup >r ( write string into dictionary, save index )\n\taligned 2dup size \/ ( stack: length hole char-len hole )\n\t1+ dup allot ( update dictionary pointer with string length )\n\t1+ swap ! ( write place to jump to )\n\tdrop ( do not need string length anymore )\n\t1+ chars> ( calculate place to print )\n\tr> ; ( restore index and address of string )\n\n: length ( c-addr u -- u : push the length of an ASCIIZ string )\n tuck 0 do dup c@ 0= if 2drop i leave then 1+ loop ;\n\n: asciiz? ( c-addr u -- : is a Forth string also a ASCIIZ string )\n\ttuck length <> ;\n\n: asciiz ( c-addr u -- : trim a string until NUL terminator )\n\t2dup length nip ;\n\n( This foreach mechanism needs thinking about, what is the best information to\npresent to the word to be executed? At the moment only the contents of the\ncell that it should be processing is.\n\nAt the moment foreach uses a do...loop construct, which means that the\nfollowing cannot be used to exit from the foreach loop:\n\n\t: return [ : exit early from a foreach loop ]\n\t\tr> rdrop >r ;\n\nAlthough this can be remedied, we know that it puts a loop onto the return\nstack.\n\nIt also uses a variable 'xt', which means that foreach loops cannot be\nnested. This word really needs thinking about.\n\nIt might be more useful to present the word with only the address of the\ncell it will act on.\n\nThis seems to be a useful, general, mechanism that is missing from\nmost Forths. More words like this should be made, they are powerful\nlike the word 'compose', but they need to be created correctly. )\n\n0 variable xt\n: foreach ( addr u xt -- : execute xt for each cell in addr-u )\n\txt !\n\tbounds do i @ xt @ execute loop ;\n\n: foreach-char ( c-addr u xt -- : execute xt for each cell in c-addr u )\n\txt !\n\tbounds do i c@ xt @ execute loop ;\nhider xt\n\n: type ( c-addr u -- : print out 'u' characters at c-addr )\n\t\\ 0 do dup c@ emit 1+ loop drop ;\n\t['] emit foreach-char ;\n\n: do-string ( char -- : write a string into the dictionary reading it until char is encountered )\n\t(.\") \n\tstate @ if swap [literal] [literal] then ;\n\n: fill ( c-addr u char -- : fill in an area of memory with a character, only if u is greater than zero )\n\t-rot\n\t0 do 2dup i + c! loop\n\t2drop ;\n\n: \/string ( c-addr1 u1 n -- c-addr2 u2 : advance a string by n characters )\n\tover min rot over + -rot - ;\n\n: compare ( c-addr1 u1 c-addr2 u2 -- n : compare two strings, not quite compliant yet )\n\t>r swap r> min >r\n\tstart-address + swap start-address + r>\n\tmemory-compare ;\n\n128 string sbuf\n: s\" ( \"ccc\" --, Run Time -- c-addr u )\n\tkey drop sbuf 0 fill sbuf [char] \" accepter sbuf drop swap ;\nhider sbuf\n\n( @todo these strings really need rethinking, state awareness needs to be removed... )\n: type, \n\tstate @ if ' type , else type then ;\n\n: c\" \n\timmediate key drop [char] \" do-string ;\n\n: \" \n\timmediate key drop [char] \" do-string type, ;\n\n: sprint ( c -- : print out chars until 'c' is encountered )\n\tkey drop ( drop next space )\n\t>r ( save delimiter )\n\tbegin\n\t\tkey dup ( get next character )\n\t\trdup r> ( get delimiter )\n\t\t<> if emit 0 then\n\tuntil rdrop ;\n\n: .( \n\timmediate [char] ) sprint ;\nhider sprint\n\n: .\" \n\timmediate key drop [char] \" do-string type, ;\n\nhider type,\n\n( This word really should be removed along with any usages of this word, it\nis not a very \"Forth\" like word, it accepts a pointer to an ASCIIZ string and\nprints it out, it also does not checking of the returned values from write-file )\n: print ( c-addr -- : print out a string to the standard output )\n\t-1 over >r length r> swap stdout write-file 2drop ;\n\n: ok \n\t\" ok\" cr ;\n\n: empty-stack ( x-n ... x-0 -- : empty the variable stack )\n\tbegin depth while drop repeat ;\n\n: (quit) ( -- : do the work of quit, without the restart )\n\t0 `source-id ! ( set source to read from file )\n\t`stdin @ `fin ! ( read from stdin )\n\tpostpone [ ( back into command mode )\n\t' interpret start! ; ( set interpreter starting word )\n\n: quit ( -- : Empty return stack, go back to command mode, read from stdin, interpret input )\n\t(quit)\n\t-1 restart ; ( restart the interpreter )\n\n: abort\n\t-1 throw ;\n\n: (abort\") ( do the work of abort )\n\t(quit)\n\t-2 throw ;\n\n: abort\" immediate \n\tpostpone \"\n\t' cr , ' (abort\") , ;\n\n( ==================== CASE statements ======================== )\n\n( for a simpler case statement:\n\tsee Volume 2, issue 3, page 48 of Forth Dimensions at\n\thttp:\/\/www.forth.org\/fd\/contents.html )\n\n( These case statements need improving, it is not standards compliant )\n: case immediate\n\t' branch , 3 , ( branch over the next branch )\n\there ' branch , ( mark: place endof branches back to with again )\n\t>mark swap ; ( mark: place endcase writes jump to with then )\n\n: over= ( x y -- x bool : over ... then = )\n\tover = ;\n\n: of\n\timmediate ' over= , postpone if ;\n\n: endof\n\timmediate over postpone again postpone then ;\n\n: endcase\n\timmediate 1+ postpone then drop ;\n\n( ==================== CASE statements ======================== )\n\n( ==================== Hiding Words =========================== )\n\n: }hide ( should only be matched with 'hide{' )\n\timmediate -22 throw ;\n\n: hide{ ( -- : hide a list of words, the list is terminated with \"}hide\" )\n\tbegin\n\t\tfind ( find next word )\n\t\tdup [ find }hide ] literal = if\n\t\t\tdrop exit ( terminate hide{ )\n\t\tthen\n\t\tdup 0= if -15 throw then\n\t\thide drop\n\tagain ;\n\n( ==================== Hiding Words =========================== )\n\n: spaces ( n -- : print n spaces ) \n\t0 do space loop ;\n\n: erase ( addr u : erase a block of memory )\n\t2chars> 0 fill ;\n\n: blank ( c-addr u : fills a string with spaces )\n\tbl fill ;\n\n( move should check that u is not negative )\n: move ( addr1 addr2 u -- : copy u words of memory from 'addr2' to 'addr1' )\n\t0 do\n\t\t2dup i + @ swap i + !\n\tloop\n\t2drop ;\n\n( It would be nice if move and cmove could share more code, as they do exactly\n the same thing but with different load and store functions, cmove> )\n: cmove ( c-addr1 c-addr2 u -- : copy u characters of memory from 'c-addr2' to 'c-addr1' )\n\t0 do\n\t\t2dup i + c@ swap i + c!\n\tloop\n\t2drop ;\n\n( ==================== Conditional Compilation ================ )\n\n( The words \"[if]\", \"[else]\" and \"[then]\" implement conditional compilation,\nthey can be nested as well\n\nSee http:\/\/lars.nocrew.org\/dpans\/dpans15.htm for more information\n\nA much simpler conditional compilation method is the following\nsingle word definition:\n\n : compile-line? 0= if [ find \\\\ , ] then ;\n\nWhich will skip a line if a conditional is false, and compile it\nif true )\n\n( These words really, really need refactoring, I could use the newly defined \n \"defer\" to help out with this )\n0 variable nest ( level of [if] nesting )\n0 variable [if]-word ( populated later with \"find [if]\" )\n0 variable [else]-word ( populated later with \"find [else]\")\n: [then] immediate ;\n: reset-nest 1 nest ! ;\n: unnest? [ find [then] ] literal = if nest 1-! then ;\n: nest? [if]-word @ = if nest 1+! then ;\n: end-nest? nest @ 0= ;\n: match-[else]? [else]-word @ = nest @ 1 = and ;\n\n: [if] ( bool -- : conditional execution )\n\tunless\n\t\treset-nest\n\t\tbegin\n\t\t\tfind\n\t\t\tdup nest?\n\t\t\tdup match-[else]? if drop exit then\n\t\t\t unnest?\n\t\t\tend-nest?\n\t\tuntil\n\tthen ;\n\n: [else] ( discard input until [then] encounter, nesting for [if] )\n\treset-nest\n\tbegin\n\t\tfind\n\t\tdup nest? unnest?\n\t\tend-nest?\n\tuntil ;\n\nfind [if] [if]-word !\nfind [else] [else]-word !\n\n: ?( if postpone ( then ; \\ conditionally read until ')'\n: ?\\ if postpone \\ then ;\n: 16bit\\ size 2 <> if postpone \\ then ;\n: 32bit\\ size 4 <> if postpone \\ then ;\n: 64bit\\ size 8 <> if postpone \\ then ;\n\nhide{ \n\t[if]-word [else]-word nest \n\treset-nest unnest? match-[else]? \n\tend-nest? nest? \n}hide\n\n( ==================== Conditional Compilation ================ )\n\n( ==================== Endian Words =========================== )\n\nsize 2 = [if] 0x0123 `x ! [then]\nsize 4 = [if] 0x01234567 `x ! [then]\nsize 8 = [if] 0x01234567abcdef `x ! [then]\n\n: endian ( -- bool : returns the endianess of the processor, little = 0, big = 1 )\n\t[ `x chars> c@ 0x01 = ] literal ;\n\n: swap16 ( x -- x : swap the byte order a 16 bit number )\n\tdup 256* 0xff00 and >r 256\/ lsb r> or ;\n\nsize 4 >= [if] \n\t: swap32 \n\t\tdup 0xffff and swap16 16 lshift swap\n\t\t16 rshift 0xffff and swap16 or ;\n[then]\n\nsize 8 >= [if]\n\t: swap64 ( x -- x : swap the byte order of a 64 bit number )\n\t\t dup 0xffffffff and swap32 32 lshift swap\n\t\t 32 rshift 0xffffffff and swap32 or ;\n[then]\n\nsize 2 = [if]\n\tendian \n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\tswap16 ;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\t;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\tswap16 ;\n\t[then]\n[then]\n\nsize 4 = [if]\n\tendian \n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\tswap32 ;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\t;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\tswap32 ;\n\t[then]\n[then]\n\nsize 8 = [if]\n\tendian \n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\tswap64 ;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\t;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\tswap64 ;\n\t[then]\n[then]\n\n( ==================== Endian Words =========================== )\n\n( ==================== Misc words ============================= )\n\n0 variable counter\n\n: counted-column ( index -- : special column printing for dump )\n\tcounter @ column-width @ mod\n\tnot if cr . \" :\" space else drop then\n\tcounter 1+! ;\n\n: as-chars ( x n -- : print a cell out as characters, upto n chars )\n\t0 ( from zero to the size of a cell )\n\tdo\n\t\tdup ( copy variable to print out )\n\t\tsize i 1+ - select-byte ( select correct byte )\n\t\tdup printable? not ( is it not printable )\n\t\tif drop [char] . then ( print a '.' if it is not )\n\t\temit ( otherwise print it out )\n\tloop\n\tspace ( print out space after )\n\tdrop ; ( drop cell we have printed out )\n\n: lister ( addr u addr -- )\n\t0 counter ! 1- swap \n\tdo \n\t\tdup counted-column 1+ i ? i @ size as-chars \n\tloop ;\n\n( @todo this function should make use of 'defer' and 'is', then different\nversion of dump could be made that swapped out 'lister' )\n: dump ( addr u -- : dump out 'u' cells of memory starting from 'addr' )\n\t1+ over + under lister drop \n\tcr ;\n\nhide{ counted-column counter as-chars }hide\n\n( Fence can be used to prevent any word defined before it from being forgotten \nUsage:\n\there fence ! )\n0 variable fence\n\n: forgetter ( pwd-token -- : forget a found word and everything after it )\n\tdup 0= if -15 throw then ( word not found! )\n\tdup fence @ u< if -15 throw then ( forgetting a word before fence! )\n\tdup @ pwd ! h ! ;\n\n: forget ( WORD -- : forget word and every word defined after it )\n\tfind 1- forgetter ;\n\n: marker ( WORD -- : make word the forgets itself and words after it)\n\t:: latest [literal] ' forgetter , postpone ; ;\nhider forgetter\n\n: ** ( b e -- x : exponent, raise 'b' to the power of 'e')\n\t?dup-if\n\t\tover swap\n\t\t1 do over * loop \n\t\tnip\n\telse\n\t\tdrop 1\n\tendif ;\n\n0 variable a\n0 variable b\n0 variable m\n: equal ( a1...an b1...bn n -- a1...an b1...bn bool : determine if two lists are equal )\n\t( example: \n\t\t1 2 3 \n\t\t1 2 3 \n\t\t3 equal \n\treturns: 1 )\n\tdup m ! 1+ 1 ( store copy of length and use as loop index )\n\tdo \n\t\ti 1- pick b ! ( store ith element of list in b1...bn )\n\t\ti m @ + 1- pick a ! ( store ith element of list in a1...an )\n\t\ta @ b @ <> ( compare a and b for equality )\n\t\tif 0 leave then ( unequal, finish early )\n\tloop 1 ; ( lists must be equal )\n\nhide{ a b m }hide\n\n: ndrop ( drop n items )\n\t?dup-if 0 do drop loop then ;\n\n: caesar ( c key -- o : encode a alphabetic character with a key using a generalization of the Caesar cipher )\n\t>r\n\tdup uppercase? if [char] A - r> + 26 mod [char] A + exit then\n\tdup lowercase? if [char] a - r> + 26 mod [char] a + exit then\n\trdrop ; ( it goes without saying that this should not be used for anything serious! )\n\n: caesar-type ( c-addr u key : type out encoded text with a Caesar cipher )\n\t-rot bounds do i c@ over caesar emit loop drop ;\n\n: rot13 ( c -- c : encode a character with ROT-13 )\n\t13 caesar ;\n\n: rot13-type ( c-addr u : print string in ROT-13 encoded form )\n\t13 caesar-type ;\n\n\\ s\" abcdefghijklmnopqrstuvwxyz\" rot13-type -> nopqrstuvwxyzabcdefghijklm\n\\ s\" hello\" rot13-type -> uryyb\n\n( ==================== Misc words ============================= )\n\n( ==================== Pictured Numeric Output ================ )\n( Pictured numeric output is what Forths use to display numbers\nto the screen, this Forth has number output methods built into\nthe Forth kernel and mostly uses them instead, but the mechanism\nis still useful so it has been added.\n\n\n@todo characters are added in reverse order, is this the best\nway of doing things? It makes use of hold awkward \n@todo Pictured number output should act on a double cell number\nnot a single cell number )\n\n0 variable hld\n\n: overflow ( -- : check if we overflow the hold area )\n \there chars> pad chars> hld @ - u> if -17 throw then ;\n\n: hold ( char -- : add a character to the numeric output string )\n\toverflow pad chars> hld @ - c! hld 1+! ;\n\n: holds ( addr u -- )\n begin dup while 1- 2dup + c@ hold repeat 2drop ;\n\n: nbase ( -- base : in this forth 0 is a special base, push 10 is base is zero )\n\tbase @ dup 0= if drop 10 then ;\n\n: <# ( -- : setup pictured numeric output )\n\t0 hld ! ;\n\n: sign ( -- : add a sign to the pictured numeric output string )\n\t[char] - hold ;\n\n: # ( x -- x : divide x by base, turn into a character, put in pictured output string )\n\tnbase um\/mod swap \n \tdup 9 u>\n \tif 7 + then\n \t48 + hold ;\n\n: #s ( x -- 0 : repeatedly call # on x until x is zero )\n\tbegin # dup 0= until ; \n\n: #> ( -- c-addr u : end pictured output conversion, push output string to stack )\n\t0 hold ( NUL terminate string, just in case )\n\thld 1-! ( but do not include that in the count )\n\tpad chars> hld @ \n\ttuck - 1+ swap ;\n\n: u. ( u -- : display number in base 10 )\n\tbase @ >r decimal <# #s #> type drop r> base ! ;\n\nhide{ nbase overflow }hide\n\n( ==================== Pictured Numeric Output ================ )\n\n( ==================== ANSI Escape Codes ====================== )\n( Terminal colorization module, via ANSI Escape Codes\n \nsee: https:\/\/en.wikipedia.org\/wiki\/ANSI_escape_code\nThese codes will provide a relatively portable means of\nmanipulating a terminal )\n\n27 constant 'escape'\n: CSI 'escape' emit .\" [\" ;\n0 constant black\n1 constant red\n2 constant green\n3 constant yellow\n4 constant blue\n5 constant magenta\n6 constant cyan\n7 constant white\n: foreground 30 + ;\n: background 40 + ;\n0 constant dark\n1 constant bright\nfalse variable colorize \n\n: color ( brightness color-code -- : set the terminal color )\n\t( set color on an ANSI compliant terminal,\n\tfor example:\n\t\tbright red foreground color\n\tsets the foreground text to bright red )\n\tcolorize @ 0= if 2drop exit then \n\tCSI u. if .\" ;1\" then .\" m\" ;\n\n: at-xy ( x y -- : set ANSI terminal cursor position to x y )\n\tCSI u. [char] ; emit u. .\" H\" ;\n\n: page ( -- : clear ANSI terminal screen and move cursor to beginning ) \n\tCSI .\" 2J\" 1 1 at-xy ;\n\n: hide-cursor ( -- : hide the cursor from view ) \n\tCSI .\" ?25l\" ;\n\n: show-cursor ( -- : show the cursor ) \n\tCSI .\" ?25h\" ;\n\n: save-cursor ( -- : save cursor position ) \n\tCSI .\" s\" ;\n\n: restore-cursor ( -- : restore saved cursor position ) \n\tCSI .\" u\" ;\n\n: reset-color ( -- : reset terminal color to its default value)\n\tcolorize @ 0= if exit then\n\tCSI .\" 0m\" ;\n\nhide{ CSI }hide\n( ==================== ANSI Escape Codes ====================== )\n\n( ==================== Unit test framework =================== )\n\n256 string estring ( string to test )\n0 variable #estring ( actual string length )\n0 variable start ( starting depth )\n0 variable result ( result depth )\n0 variable check ( only check depth if -> is called )\n0 variable dictionary ( dictionary pointer on entering { )\n0 variable previous ( PWD register on entering { )\n\n: T ; ( hack until T{ can process words )\n\n: -> ( -- : save depth in variable ) \n\t1 check ! depth result ! ; \n\n: test estring drop #estring @ ; \n\n: fail ( -- : invalidate the forth interpreter and exit )\n\tinvalidate bye ;\n\n: neutral ( -- : neutral color )\n\t;\n\n: bad ( -- : bad color )\n\tdark red foreground color ;\n\n: good ( -- : good color )\n\tdark green foreground color ;\n\n: die bad test type reset-color cr fail ;\n\n: evaluate? ( bool -- : test if evaluation has failed )\n\tif .\" evaluation failed\" cr fail then ;\n\n: failed bad .\" failed\" reset-color cr ;\n\n: adjust ( x -- x : adjust a depth to take into account starting depth ) \n\tstart @ - ;\n\n: no-check? ( -- bool : if true we need to check the depth )\n\tcheck @ 0= ;\n\n: depth? ( -- : check if depth is correct )\n\tno-check? if exit then\n\tdepth adjust ( get depth and adjust for starting depth )\n\tresult @ adjust 2* = ( get results depth, same adjustment, should be\n\t half size of the depth ) \n\tif exit then ( pass )\n\tfailed\n\t.\" Unequal depths:\" cr\n\t.\" depth: \" depth . cr\n\t.\" result: \" result @ . cr\n\tdie ;\n\n: equal? ( -- : determine if results equals expected )\n\tno-check? if exit then\n\tresult @ adjust equal\n\tif exit then\n\tfailed\n\t.\" Result is not equal to expected values. \" cr \n\t.\" Stack: \" cr .s cr\n\tdie ;\n\n: display ( c-addr u -- : print out testing message in estring )\n\tverbose if neutral type else 2drop then ;\n\n: pass ( -- : print out passing message )\n\tverbose if good .\" ok \" cr reset-color then ;\n\n: save ( -- : save current dictionary )\n\tpwd @ previous !\n\there dictionary ! ;\n\n: restore ( -- : restore dictionary )\n\tprevious @ pwd ! \n\tdictionary @ h ! ;\n\n\n: T{ ( -- : perform a unit test )\n\tdepth start ! ( save start of stack depth )\n\t0 result ! ( reset result variable )\n\t0 check ! ( reset check variable )\n\testring 0 fill ( zero input string )\n\tsave ( save dictionary state )\n\tkey drop ( drop next character, which is a space )\n\testring [char] } accepter #estring ! ( read in string to test )\n\ttest display ( print which string we are testing )\n\ttest evaluate ( perform test )\n\tevaluate? ( evaluate successfully? )\n\tdepth? ( correct depth )\n\tequal? ( results equal to expected values? )\n\tpass ( print pass message )\n\tresult @ adjust 2* ndrop ( remove items on stack generated by test )\n\trestore ; ( restore dictionary to previous state )\n\nT{ }T\nT{ -> }T\nT{ 1 -> 1 }T\nT{ 1 2 -> 1 2 }T\nT{ : c 1 2 ; c -> 1 2 }T\nT{ :noname 2 ; :noname 3 + ; compose execute -> 5 }T\n\nhide{ \n\tpass test display\n\tadjust start save restore dictionary previous \n\tevaluate? equal? depth? estring #estring result\n\tcheck no-check? die neutral bad good failed\n}hide\n\n( ==================== Unit test framework =================== )\n\n\n( ==================== Random Numbers ========================= )\n\n( \nSee:\nuses xorshift\nhttps:\/\/en.wikipedia.org\/wiki\/Xorshift\nhttp:\/\/excamera.com\/sphinx\/article-xorshift.html\nhttp:\/\/www.arklyffe.com\/main\/2010\/08\/29\/xorshift-pseudorandom-number-generator\/\nthese constants have be collected from the web \n)\n\nsize 2 = [if] 13 constant a 9 constant b 7 constant c [then]\nsize 4 = [if] 13 constant a 17 constant b 5 constant c [then]\nsize 8 = [if] 12 constant a 25 constant b 27 constant c [then]\n\n7 variable seed ( must not be zero )\n\n: seed! ( x -- : set the value of the PRNG seed )\n\tdup 0= if drop 7 ( zero not allowed ) then seed ! ;\n\n: random ( -- x : assumes word size is 32 bit )\n\tseed @\n\tdup a lshift xor\n\tdup b rshift xor\n\tdup c lshift xor\n\tdup seed! ;\n\nhide{ a b c seed }hide\n\n( ==================== Random Numbers ========================= )\n\n( ==================== Prime Numbers ========================== )\n( From original \"third\" code from the IOCCC at \nhttp:\/\/www.ioccc.org\/1992\/buzzard.2.design, the module works out\nand prints prime numbers. )\n\n: prime? ( u -- u | 0 : return number if it is prime, zero otherwise )\n\tdup 1 = if 1- exit then\n\tdup 2 = if exit then\n\tdup 2\/ 2 ( loop from 2 to n\/2 )\n\tdo\n\t\tdup ( value to check if prime )\n\t\ti mod ( mod by divisor )\n\t\tnot if\n\t\t\tdrop 0 leave\n\t\tthen\n\tloop ;\n\n0 variable counter\n\n: primes ( x1 x2 -- : print the primes from x2 to x1 )\n\t0 counter !\n\t\" The primes from \" dup . \" to \" over . \" are: \"\n\tcr\n\tcolumn.reset\n\tdo\n\t\ti prime?\n\t\tif\n\t\t\ti . counter @ column counter 1+!\n\t\tthen\n\tloop\n\tcr\n\t\" There are \" counter @ . \" primes.\"\n\tcr ;\n\nhide{ counter }hide\n( ==================== Prime Numbers ========================== )\n\n( ==================== Debugging info ========================= )\n\n( string handling should really be done with PARSE, and CMOVE )\n\n: sh ( cnl -- ior : execute a line as a system command )\n\tnl word count system ;\n\nhide{ .s }hide\n: .s ( -- : print out the stack for debugging )\n\t[char] < emit depth u. [char] > emit space\n\tdepth if\n\t\tdepth 0 do i column tab depth i 1+ - pick . loop\n\tthen\n\tcr ;\n\n1 variable hide-words ( do we want to hide hidden words or not )\n\n: name ( PWD -- c-addr : given a pointer to the PWD field of a word get a pointer to the name of the word )\n\tdup 1+ @ 256\/ word-mask and lsb - chars> ;\n\n( This function prints out all of the defined words, excluding hidden words.\nAn understanding of the layout of a Forth word helps here. The dictionary\ncontains a linked list of words, each forth word has a pointer to the previous\nword until the first word. The layout of a Forth word looks like this:\n\nNAME: Forth Word - A variable length ASCII NUL terminated string\nPWD: Previous Word Pointer, points to the previous word\nCODE: Flags, code word and offset from previous word pointer to start of Forth word string\nDATA: The body of the forth word definition, not interested in this.\n\nThere is a register which stores the latest defined word which can be\naccessed with the code \"pwd @\". In order to print out a word we need to\naccess a words CODE field, the offset to the NAME is stored here in bits\n8 to 14 and the offset is calculated from the PWD field.\n\n\"print\" expects a character address, so we need to multiply any calculated\naddress by the word size in bytes. )\n\n: words.immediate ( bool -- : emit or mark a word being printed as being immediate )\n\tnot if dark red foreground color then ;\n\n: words.defined ( bool -- : emit or mark a word being printed as being a built in word )\n\tnot if bright green background color then ;\n\n: words.hidden ( bool -- : emit or mark a word being printed as being a hidden word )\n\tif dark magenta foreground color then ;\n\n: words ( -- : print out all defined an visible words )\n\tlatest\n\tspace\n\tbegin\n\t\tdup\n\t\thidden? hide-words @ and\n\t\tnot if\n\t\t\thidden? words.hidden\n\t\t\tcompiling? words.immediate\n\t\t\tdup defined-word? words.defined\n\t\t\tname\n\t\t\tprint space\n\t\t\treset-color\n\t\telse\n\t\t\tdrop\n\t\tthen\n\t\t@ ( Get pointer to previous word )\n\t\tdup dictionary-start u< ( stop if pwd no longer points to a word )\n\tuntil\n\tdrop cr ;\n\n( Simpler version of words\n: words\n\tpwd @ \n\tbegin\n\t\tdup name print space @ dup dictionary-start u<\n\tuntil drop cr ; )\n\nhide{ words.immediate words.defined words.hidden hidden? hidden-bit }hide\n\n: TrueFalse ( -- : print true or false )\n\tif \" true\" else \" false\" then ;\n\n: registers ( -- : print out important registers and information about the virtual machine )\n\t\" return stack pointer: \" r@ . cr\n\t\" dictionary pointer \" here . cr\n\t\" previous word: \" pwd ? cr\n\t\" state: \" state ? cr\n\t\" base: \" base ? cr\n\t\" depth: \" depth . cr\n\t\" cell size (in bytes): \" size . cr\n\t\" last cell address: \" max-core . cr\n\t\" unused cells: \" unused . cr\n\t\" invalid: \" `invalid @ TrueFalse cr\n\t\" size of variable stack: \" `stack-size ? cr\n\t\" size of return stack: \" `stack-size ? cr\n\t\" start of variable stack: \" max-core `stack-size @ 2* - . cr\n\t\" start of return stack: \" max-core `stack-size @ - . cr\n\t\" current input source: \" source-id -1 = if \" string\" else \" file\" then cr\n\t\" tracing on: \" `debug @ TrueFalse cr\n\t\" starting word: \" `instruction ? cr\n\t\" real start address: \" `start-address ? cr\n\t\" error handling: \" `error-handler ? cr \n\t\" throw handler: \" `handler ? cr\n\t\" signal recieved: \" `signal ? cr ;\n\t\n( `sin `sidx `slen `fout\n `stdout `stderr `argc `argv )\n\n\n: y\/n? ( -- bool : ask a yes or no question )\n\tkey drop\n\t\" y\/n? \"\n\tbegin\n\t\tkey\n\t\tdup\n\t\t[char] y = if true exit then\n\t\t[char] n = if false exit then\n\t\t\" y\/n? \"\n\tagain ;\n\n: step\n\t( step through a word: this word could be augmented\n\twith commands such as \"dump\", \"halt\", and optional\n\t\".s\" and \"registers\" )\n\tregisters\n\t\" .s: \" .s cr\n\t\" -- press any key to continue -- \"\n\tkey drop ;\n\n: more ( -- : wait for more input )\n\t\" -- press any key to continue -- \" key drop cr page ;\n\n: debug-help ( -- : print out the help for the debug command )\n \" debug mode commands\n\th - print help\n\tq - exit interpreter word\n\tr - print registers\n\ts - print stack\n\tR - print return stack\n\tc - continue on with execution\n\" ;\n\ndoer debug-prompt\n: prompt-default\n\t.\" debug> \" ;\n\nmake debug-prompt prompt-default\n\n: debug ( -- : enter interactive debug prompt )\n\tcr\n\t\" Entered Debug Prompt. Type 'h' for help. \" cr \n\tbegin\n\t\tkey\n\t\tcase\n\t\t\tnl of debug-prompt endof\n\t\t\t[char] h of debug-help endof\n\t\t\t[char] q of bye endof\n\t\t\t[char] r of registers endof\n\t\t\t[char] s of >r .s r> endof\n\t\t\t[char] R of r> r.s >r endof\n\t\t\t[char] c of drop exit endof\n\t\t\t( @todo add throw here )\n\t\tendcase drop\n\tagain ;\nhider debug-prompt\n\n: code>pwd ( CODE -- PWD\/0 : calculate PWD from code address )\n\tdup dictionary-start here within not if drop 0 exit then\n\t1 cells - ;\n\n: word-printer ( CODE -- : print out a words name given its code field )\n\tdup 1 cells - @ -1 = if . \" noname\" exit then ( nonames are marked by a -1 before its code field )\n\tdup code>pwd ?dup-if .d name print else drop \" data\" then\n\t drop ;\n\nhide{ code>pwd }hide\n\n( these words push the execution tokens for various special cases for decompilation )\n: get-branch [ find branch ] literal ;\n: get-?branch [ find ?branch ] literal ;\n: get-original-exit [ find _exit ] literal ;\n: get-quote [ find ' ] literal ;\n\n( @todo replace 2- nos1+ nos1+ with appropriate word, like the string word \nthat increments a string by an amount, but that operates on CELLS )\n: branch-increment ( addr branch -- increment : calculate decompile increment for \"branch\" )\n\t1+ dup negative? \n\tif \n\t\tover cr . [char] : emit space . cr 2 \n\telse \n\t\t2dup 2- nos1+ nos1+ dump \n\tthen ;\n\n( these words take a code field to a primitive they implement, decompile it\nand any data belonging to that operation, and push a number to increment the\ndecompilers code stream pointer by )\n\n: decompile-literal ( code -- increment )\n\t1+ ? \" literal\" 2 ;\n\n: decompile-branch ( code -- increment )\n\tdark red foreground color\n\t1+ ? \" branch \" dup 1+ @ branch-increment ;\n\n: decompile-quote ( code -- increment )\n\tdark green foreground color\n\tdup\n\t[char] ' emit 1+ @ word-printer 2 reset-color ;\n\n: decompile-?branch ( code -- increment )\n\t1+ ? \" ?branch\" 2 ;\n\n: decompile-exit ( code -- 0 )\n\t\" _exit\" cr \" End of word: \" . 0 ;\n\n( The decompile word expects a pointer to the code field of a word, it\ndecompiles a words code field, it needs a lot of work however.\nThere are several complications to implementing this decompile\nfunction.\n\n\t' The next cell should be pushed\n\t:noname This has a marker before its code field of -1 which\n\t\t cannot occur normally, this is handled in word-printer\n\tbranch branches are used to skip over data, but also for\n\t\t some branch constructs, any data in between can only\n\t\t be printed out generally speaking\n\texit There are two definitions of exit, the one used in\n\t\t ';' and the one everything else uses, this is used\n\t\t to determine the actual end of the word\n\tliterals Literals can be distinguished by their low value,\n\t\t which cannot possibly be a word with a name, the\n\t\t next field is the actual literal\n\nOf special difficult is processing 'if' 'else' 'then' statements,\nthis will require keeping track of '?branch'.\n\nAlso of note, a number greater than \"here\" must be data )\n\n: decompile ( code-pointer -- code-pointer increment|0 : )\n\t.d [char] : emit space dup @\n\tcase\n\t\tdolit of drup decompile-literal cr endof\n\t\tget-branch of drup decompile-branch endof\n\t\tget-quote of drup decompile-quote cr endof\n\t\tget-?branch of drup decompile-?branch cr endof\n\t\tget-original-exit of drup decompile-exit endof\n\t\tword-printer 1 cr\n\tendcase reset-color ;\n\n: decompiler ( code-field-ptr -- : decompile a word in its entirety )\n\tbegin decompile over + tuck = until drop ;\n\nhide{\n\tword-printer get-branch get-?branch get-original-exit \n\tget-quote branch-increment decompile-literal \n\tdecompile-branch decompile-?branch decompile-quote\n\tdecompile-exit\n}hide\n\n( these words expect a pointer to the PWD field of a word )\n: see.name \" name: \" name print cr ;\n: see.start \" word start: \" name chars . cr ;\n: see.previous \" previous word: \" @ . cr ;\n: see.immediate \" immediate: \" compiling? swap drop not TrueFalse cr ;\n: see.instruction \" instruction: \" xt-instruction . cr ;\n: see.defined \" defined: \" defined-word? TrueFalse cr ;\n\n: see.header ( PWD -- is-immediate-word? )\n\tdup see.name\n\tdup see.start\n\tdup see.previous\n\tdup see.immediate\n\tdup see.instruction ( @todo look up instruction name )\n\tsee.defined ;\n\n( @todo This does not work for all words, so needs fixing. \n Specifically: \n\t2variable\n\t2constant\n\ttable\n\tconstant\n\tvariable\n\tarray \nWhich are all complex CREATE words\n\nA good way to test decompilation is with the following Unix pipe: \n\n\t.\/forth -f forth.fth -e words \n\t\t| sed 's\/ \/ see \/g' \n\t\t| .\/forth -t forth.fth &> decompiled.log\n)\n\n( @todo refactor into word that takes a PWD pointer and one that attempts to parse\/find name )\n: see ( c\" xxx\" -- : decompile the next word in the input stream )\n\tfind\n\tdup 0= if -32 throw then\n\t-1 cells + ( move to PWD field )\n\tdup see.header\n\tdup defined-word?\n\tif ( decompile if a compiled word )\n\t\t2 cells + ( move to code field )\n\t\t\" code field:\" cr\n\t\tdecompiler\n\telse ( the instruction describes the word if it is not a compiled word )\n\t\tdup 1 cells + @ instruction-mask and doconst = if ( special case for constants )\n\t\t\t\" constant: \" 2 cells + @ .\n\t\telse\n\t\t\tdrop\n\t\tthen\n\tthen cr ;\n\nhide{ \n\tsee.header see.name see.start see.previous see.immediate \n\tsee.instruction defined-word? see.defined\n}hide\n\n( These help messages could be moved to blocks, the blocks could then\nbe loaded from disk and printed instead of defining the help here,\nthis would allow much larger help )\n\n: help ( -- : print out a short help message )\n\tpage\n\tkey drop\n\" Welcome to Forth, an imperative stack based language. It is both a low\nlevel and a high level language, with a very small memory footprint. Most\nof Forth is defined as a combination of various primitives.\n\nA short description of the available function (or Forth words) follows,\nwords marked (1) are immediate and cannot be used in command mode, words\nmarked with (2) define new words. Words marked with (3) have both command\nand compile functionality.\n\n\"\nmore \" Some of the built in words that accessible are:\n\n(1,2)\t: define a new word, switching to compile mode\n\timmediate make latest defined word immediate\n\tread read in a word, execute in command mode else compile\n\t@ ! fetch, store\n\tc@ c! character based fetch and store\n\t- + * \/ standard arithmetic operations,\n\tand or xor invert standard bitwise operations\n\tlshift rshift left and right bit shift\n\tu< u> < > = comparison predicates\n\texit exit from a word\n\temit print character from top of stack\n\tkey get a character from input\n\tr> >r pop a value from or to the return stack\n\tfind find a word in the dictionary and push the location\n\t' store the address of the following word on the stack\n\t, write the top of the stack to the dictionary\n\tswap swap first two values on the stack\n\tdup duplicate the top of the stack\n\tdrop pop and drop a value\n\tover copy the second stack value over the first\n\t. pop the top of the stack and print it\n\" \nmore \" \n\tprint print a NUL terminated string at a character address\n\tdepth get the current stack depth\n\tclock get the time since execution start in milliseconds\n\tevaluate evaluate a string\n\tsystem execute a system command\n\tclose-file close a file handle\n\topen-file open a file handle\n\tdelete-file delete a file off disk given a string\n\tread-file read in characters from a file\n\twrite-file write characters to a file\n\tfile-position get the file offset\n\treposition-file reposition the file pointer\n\tflush-file flush a file to disk\n\trename-file rename a file on disk\n \"\n\nmore \" All of the other words in the interpreter are built from these\nprimitive words. A few examples:\n\n(1)\tif...else...then FORTH branching construct\n(1)\tbegin...until loop until top of stack is non zero\n(1)\tbegin...again infinite loop\n(1)\tdo...loop FORTH looping construct\n(2,3)\tcreate create a new word that pushes its location\n(1)\tdoes> declare a created words run time behaviour\n(1,2)\tvariable declare variable with initial value from top of stack\n(1,2)\tconstant declare a constant, taken from top of stack\n(1,2)\tarray declare an array with size taken from top of stack\n(1)\t; terminate a word definition and return to command mode\n\twords print out a list of all the defined words\n\thelp this help message\n\tdump print out memory contents starting at an address\n\tregisters print out the contents of the registers\n\tsee decompile a word, viewing what words compose it\n\t.s print out the contents of the stack\n\n\"\n\nmore \" Some more advanced words:\n\n\there push the dictionary pointer\n\th push the address of the dictionary pointer\n\tr push the return stack pointer\n\tallot allocate space in the dictionary\n(1)\t[ switch to command mode\n\t] switch to compile mode\n\t:: compile ':' into the dictionary\n\n\" more \"\nFor more information either consult the manual pages forth(1) and libforth(1)\nor consult the following sources:\n\n\thttps:\/\/github.com\/howerj\/libforth\n\thttp:\/\/work.anapnea.net\/html\/html\/projects.html\n\nAnd for a larger tutorial:\n\n\thttps:\/\/github.com\/howerj\/libforth\/blob\/master\/readme.md\n\nFor resources on Forth:\n\n\thttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\thttps:\/\/rwmj.wordpress.com\/2010\/08\/07\/jonesforth-git-repository\/\n\n -- end --\n\" cr\n;\n\n( ==================== Debugging info ========================= )\n\n( ==================== Files ================================== )\n\n( @todo implement the other file access methods in terms of the\n built in ones [see http:\/\/forth.sourceforge.net\/std\/dpans\/dpans11.htm]\n @todo read-line and write-line need their flag and ior setting correctly\n\n\tFILE-SIZE [ use file-positions ]\n\n Also of note:\t\n * Source ID needs extending. )\n\n: read-char ( c-addr fileid -- ior : read a char )\n\t1 swap read-file 0<> swap 1 <> or ;\n\n0 variable x\n\n: getchar ( fileid -- char ior )\n\tx chars> swap read-char x chars> c@ swap ;\n\n: write-char ( c-addr fileid -- ior : write a char )\n\t1 swap write-file 0<> swap 1 <> or ;\n\n: putchar ( char fileid -- ior )\n\tswap x chars> c! x chars> swap write-char ;\n\nhide{ x }hide\n\n: rewind-file ( file-id -- : rewind a file to the beginning )\n\t0 reposition-file throw ;\n\n: read-line ( c-addr u1 fileid -- u2 flag ior : read in a line of text )\n\t-rot bounds\n\tdo\n\t\tdup i swap read-char drop\n\t\ti c@ nl = if drop i 0 0 leave then\n\tloop drop ;\n\n: write-line ( c-addr u fileid -- u2 flag ior : write a line of text )\n\t-rot bounds\n\tdo\n\t\tdup i swap write-char drop\n\t\ti c@ nl = if drop i 0 0 leave then\n\tloop ;\n\n: resize-file ( ud fileid -- ior : attempt to resize a file )\n\t( There is no portable way to truncate a file :C )\n\t2drop -1 ( -1 to indicate failure ) ;\n\n: create-file ( c-addr u fam -- fileid ior )\n\t>r 2dup w\/o open-file throw close-file throw\n\tr> open-file ;\n\n: include-file ( file-id -- : evaluate a file ) \n\tdup >r 0 1 evaluator r> close-file throw throw ;\n\n: included ( c-addr u -- : attempt to open up a name file and evaluate it )\n\tr\/o open-file throw \n\tinclude-file ;\n\n: include ( c\" ccc\" -- : attempt to evaluate a named file )\n\t( @bug requires trailing space, should use parse-name )\n\tbl word count included ;\n\n: bin ( fam1 -- fam2 : modify a file access method to be binary not line oriented ) \n\t( Do nothing, all file access methods are binary )\n\t;\n\n( ==================== Files ================================== )\n\n( ==================== Matcher ================================ )\n( The following section implements a very simple regular expression\nengine, which expects an ASCIIZ Forth string. It is translated from C\ncode and performs an identical function.\n\nThe regular expression language is as follows:\n\n\tc\tmatch a literal character\n\t.\tmatch any character\n\t*\tmatch any characters\n\nThe \"*\" operator performs the same function as \".*\" does in most\nother regular expression engines. Most other regular expression engines\nalso do not anchor their selections to the beginning and the end of\nthe string to match, instead using the operators '^' and '$' to do\nso, to emulate this behavior '*' can be added as either a suffix,\nor a prefix, or both, to the matching expression.\n\nAs an example \"*, World!\" matches both \"Hello, World!\" and\n\"Good bye, cruel World!\". \"Hello, ....\" matches \"Hello, Bill\"\nand \"Hello, Fred\" but not \"Hello, Tim\" as there are two few\ncharacters in the last string.\n\n@todo make a matcher that expects a Forth string, which do not\nhave to be NUL terminated\n)\n\n\\ Translated from http:\/\/c-faq.com\/lib\/regex.html\n\\ int match(char *pat, char *str)\n\\ {\n\\ \tswitch(*pat) {\n\\ \tcase '\\0': return !*str;\n\\ \tcase '*': return match(pat+1, str) || *str && match(pat, str+1);\n\\ \tcase '.': return *str && match(pat+1, str+1);\n\\ \tdefault: return *pat == *str && match(pat+1, str+1);\n\\ \t}\n\\ }\n\n: *pat ( regex -- regex char : grab next character of pattern ) \n\tdup c@ ;\n\n: *str ( string regex -- string regex char : grab next character string to match )\n\tover c@ ;\n\n: pass ( c-addr1 c-addr2 -- bool : pass condition, characters matched ) \n\t2drop 1 ;\n\n: reject ( c-addr1 c-addr2 -- bool : fail condition, character not matched ) \n\t2drop 0 ;\n\n: *pat==*str ( c-addr1 c-addr2 -- c-addr1 c-addr2 bool )\n\t2dup c@ swap c@ = ;\n\n: ++ ( u1 u2 u3 u4 -- u1+u3 u2+u4 : not quite d+ [does no carry] )\n\tswap >r + swap r> + swap ;\n\ndefer matcher\n\n: advance ( string regex char -- bool : advance both regex and string )\n\tif 1 1 ++ matcher else reject then ;\n\n: advance-string ( string regex char -- bool : advance only the string )\n\tif 1 0 ++ matcher else reject then ;\n\n: advance-regex ( string regex -- bool : advance matching )\n\t2dup 0 1 ++ matcher if pass else *str advance-string then ;\n\n: match ( string regex -- bool : match a ASCIIZ pattern against an ASCIIZ string )\n\t( @todo Add limits and accept two Forth strings, making sure they are both\n\t ASCIIZ strings as well \n\t @warning This uses a non-standards compliant version of case! )\n\t*pat\n\tcase\n\t\t 0 of drop drop c@ not exit endof\n\t\t[char] * of drop advance-regex exit endof\n\t\t[char] . of drop *str advance exit endof\n\t\t drop *pat==*str advance exit\n\tendcase ;\n\nmatcher is match\n\nhide{ \n\t*str *pat *pat==*str pass reject advance \n\tadvance-string advance-regex matcher ++ \n}hide\n\n( ==================== Matcher ================================ )\n\n\n( ==================== Cons Cells ============================= )\n\n( From http:\/\/sametwice.com\/cons.fs, this could be improved if the optional\nmemory allocation words were added to the interpreter. This provides\na simple \"cons cell\" data structure. There is currently no way to\nfree allocated cells )\n\n: car! ( value cons-addr -- : store a value in the car cell of a cons cell ) \n\t! ;\n\n: cdr! ( value cons-addr -- : store a value in the cdr cell of a cons cell )\n\tcell+ ! ;\n\n: car@ ( cons-addr -- car-val : retrieve car value from cons cell )\n\t@ ;\n\n: cdr@ ( cons-addr -- cdr-val : retrieve cdr value from cons cell )\n\tcell+ @ ;\n\n: cons ( car-val cdr-val -- cons-addr : allocate a new cons cell )\n\tswap here >r , , r> ;\n\n: cons0 0 0 cons ;\n\nmarker cleanup\n77 987 cons constant x\nT{ x car@ -> 77 }T\nT{ x cdr@ -> 987 }T\nT{ 55 x cdr! x car@ x cdr@ -> 77 55 }T\nT{ 44 x car! x car@ x cdr@ -> 44 55 }T\ncleanup\n\n( ==================== Cons Cells ============================= )\n\n( ==================== Miscellaneous ========================== )\n\n: license ( -- : print out license information )\n\" \nThe MIT License (MIT)\n\nCopyright (c) 2016, 2017 Richard James Howe\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the 'Software'),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand\/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\nTHE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\nOTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\nARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE. \n\n\" \n;\n\n( ==================== Version information =================== )\n\n4 constant version\n\n( ==================== Version information =================== )\n\n( ==================== Core utilities ======================== )\n( Read the header of a core file and process it, printing the\nresults out )\n\n8 constant header-size ( size of Forth core file header )\n8 constant size-field-size ( the size in bytes of the size field in the core file )\n0 variable core-file ( core fileid we are reading in )\n0 variable core-cell-size ( cell size of Forth core )\n0 variable core-version ( version of core file )\n0 variable core-endianess ( endianess of core we are reading in )\n\n( save space to read in header )\ncreate header header-size chars allot\n: cheader ( -- c-addr : header char address )\n\theader chars> ;\ncreate size-field size-field-size chars allot\n: csize-field ( -- c-addr : address of place size field is stored in )\n\tsize-field chars> ;\n\n0\nenum header-magic0 ( magic number 0 : FF ) \nenum header-magic1 ( magic number 1 : '4' )\nenum header-magic2 ( magic number 2 : 'T' )\nenum header-magic3 ( magic number 3 : 'H' )\nenum header-cell-size ( size of a forth cell, either 2, 4 or 8 bytes )\nenum header-version ( version of the forth core )\nenum header-endianess ( endianess of the core )\nenum header-log2size ( binary logarithm of the core size )\n\n: cleanup ( -- : cleanup before abort )\n\tcore-file @ ?dup 0<> if close-file drop then ;\n\n: invalid-header ( bool -- : abort if header is invalid )\n\t<> if cleanup abort\" invalid header\" then ;\n\n: save-core-cell-size ( char -- : save the core file cell size, checking if it is valid )\n\tcore-cell-size !\n\t\" cell size:\" tab\n\tcore-cell-size @ 2 = if 2 . cr exit then\n\tcore-cell-size @ 4 = if 4 . cr exit then\n\tcore-cell-size @ 8 = if 8 . cr exit then\n\tcleanup core-cell-size @ . abort\" : invalid cell size\" ;\n\n: check-version-compatibility ( char -- : checks the version compatibility of the core file ) \n\tcore-version !\n\tcore-version @ version = if \" version: \" version . cr exit then\n\tcleanup core-version @ . abort\" : unknown version number\" ;\n\n: save-endianess ( char -- : save the endianess, checking if it is valid )\n\tcore-endianess !\n\t\" endianess:\" tab\n\tcore-endianess @ 0 = if \" big\" cr exit then\n\tcore-endianess @ 1 = if \" little\" cr exit then\n\tcleanup core-endianess @ . abort\" invalid endianess\" then ;\n\n: read-or-abort ( c-addr size fileid -- : )\n\tover >r read-file \n\t 0<> if cleanup abort\" file read failed\" then\n\tr> <> if cleanup abort\" header too small\" then ;\n\n: header? ( -- : print out header information )\n\tcheader header-size core-file @ read-or-abort\n\t( \" raw header:\" header 2 dump )\n\tcheader header-magic0 + c@ 255 invalid-header\n\tcheader header-magic1 + c@ [char] 4 invalid-header\n\tcheader header-magic2 + c@ [char] T invalid-header\n\tcheader header-magic3 + c@ [char] H invalid-header\n\tcheader header-cell-size + c@ save-core-cell-size\n\tcheader header-version + c@ check-version-compatibility\n\tcheader header-endianess + c@ save-endianess\n\t\" valid header\" cr ;\n\n: size? ( -- : print out core file size )\n\t\" size: \" cheader header-log2size + c@ 1 swap lshift . cr ;\n\n: core ( c-addr u -- : analyze a Forth core file from disk given its file name )\n\t2dup \" core file:\" tab type cr\n\tr\/o open-file throw core-file ! \n\theader?\n\tsize?\n\tcore-file @ close-file drop ;\n\n( s\" forth.core\" core )\n\nhide{ \nheader-size header? \nheader-magic0 header-magic1 header-magic2 header-magic3\nheader-version header-cell-size header-endianess header-log2size\nheader \ncore-file save-core-cell-size check-version-compatibility\ncore-cell-size cheader\ncore-endianess core-version save-endianess invalid-header\ncleanup size-field csize-field size-field-size\nread-or-abort size?\n}hide\n\n( ==================== Core utilities ======================== )\n\n( ==================== RLE =================================== )\n\n( These set of words implement Run Length Compression, which can be used for\nsaving space when compressing the core files generated by Forth programs, which\ncontain mostly runs of NUL characters. \n\nThe format of the encoded data is quite simple, there is a command byte\nfollowed by data. The command byte encodes only two commands; encode a run of\nliteral data and repeat the next character. \n\nIf the command byte is greater than X the command is a run of characters, \nX is then subtracted from the command byte and this is the number of \ncharacters that is to be copied verbatim when decompressing.\n\nIf the command byte is less than or equal to X then this number, plus one, is \nused to repeat the next data byte in the input stream.\n\nX is 128 for this application, but could be adjusted for better compression\ndepending on what the data looks like. \n\nExample:\n\t\n\t2 'a' 130 'b' 'c' 3 'd'\n\nBecomes:\n\n\taabcddd \n\nExample usage:\n\n\t: extract\n\t\tc\" forth.core\" w\/o open-file throw\n\t\tc\" forth.core.rle\" r\/o open-file throw\n\t\tdecompress ;\n\textract\n\n@note file redirection could be used for the input as well\n@todo compression, and reading\/writing to strings )\n\n: cpad pad chars> ;\n\n0 variable out\n128 constant run-length\n\n: next.char ( file-id -- char : read in a single character )\n\t>r cpad r> read-char throw cpad c@ ;\n\n: repeated ( count file-id -- : repeat a character count times )\n\tnext.char swap 0 do dup emit loop drop ;\n\n: literals ( count file-id -- : extract a literal run )\n\t>r cpad swap r> read-file throw cpad swap type ;\n\n: command ( file-id -- : process an RLE command )\n\tdup \n\t>r next.char\n\tdup run-length u> \n\tif \n\t\trun-length - r> literals \n\telse \n\t\t1+ r> repeated \n\tthen ;\n\n: redirect ( file-id-out -- : save current output pointer, redirect to output )\n\t`fout @ out ! `fout ! ;\n\n: restore ( -- : restore previous output pointer )\n\tout @ `fout ! ;\n\n: decompress ( file-id-out file-id-in -- : decompress an RLE encoded file )\n\tswap\n\tredirect\n\tbegin dup ' command catch until ( process commands until input exhausted )\n\t2drop ( drop twice because catch will restore stack before 'command' )\n\trestore ; ( restore input stream )\n\nhide{ literals repeated next.char out run-length command }hide\n\n( ==================== RLE =================================== )\n\n( ==================== Generate C Core file ================== )\n( The word core2c reads in a core file and turns it into a C file which \ncan then be compiled into the forth interpreter in a bootstrapping like\nprocess.\n\nUsage:\n c\" forth.core\" c\" core.gen.c\" core2c )\n\n0 variable count\n\n: wbyte ( u char -- : write a byte )\n\tpnum drop\n\t[char] , emit\n\t16 mod 0= if cr then ;\n\n: advance ( char -- : advance counter and print byte )\n\tcount 1+! count @ swap wbyte ;\n\n: hexify ( fileid -- fileid : turn core file into C numbers in array )\n\t0 count !\n\tbegin dup getchar 0= while advance repeat drop ;\n\n: quote ( -- : emit a quote character )\n\t[char] \" emit ;\n\n: core2c ( c-addr u c-addr u -- ior : generate a C file from a core file )\n\tw\/o open-file throw >r\n\tr\/o open-file ?dup-if r> close-file throw throw then\n\tr> redirect\n\t\" #include \" quote \" libforth.h\" quote cr\n\t\" unsigned char forth_core_data[] = {\" cr\n\thexify \n\t\" };\" cr\n\t\" forth_cell_t forth_core_size = \" count @ . \" ;\" cr cr\n\tclose-file\n\t`fout @ close-file \n\trestore or ;\n\nhide{ wbyte hexify count quote advance }hide\n \n( ==================== Generate C Core file ================== )\n\n: wc ( c-addr u -- u : count the bytes in a file )\n\tr\/o open-file throw\n\t0 swap\n\tbegin dup getchar nip 0= while nos1+ repeat close-file throw ;\n\n( ==================== Save Core file ======================== )\n\n( The following functionality allows the user to save the core file\nfrom within the running interpreter. The Forth core files have a very simple\nformat which means the words for doing this do not have to be too long, a header\nhas to emitted with a few calculated values and then the contents of the\nForths memory after this )\n\n( This write the header out to the current output device, this\nwill be redirected to a file )\n: header ( -- : write the header out )\n\t0xff emit ( magic 0 )\n\t[char] 4 emit ( magic 1 )\n\t[char] T emit ( magic 2 )\n\t[char] H emit ( magic 3 )\n\tsize emit ( cell size in bytes )\n\tversion emit ( core version )\n\tendian not emit ( endianess )\n\tmax-core log2 emit ; ( size field )\n\n: data ( -- : write the data out )\n\t0 max-core chars> `fout @ write-file throw drop ;\n\n: encore ( -- : write the core file out )\n\theader\n\tdata ;\n\n: save-core ( c-addr u -- : save core file or throw error ) \n\tw\/o open-file throw dup\n\tredirect \n\t\t' encore catch swap close-file throw \n\trestore ;\n\n( The following code illustrates an example of setting up a\nForth core file to execute a word when the core file is loaded.\nIn the example the word \"hello-world\" will be executed, which will\nalso quit the interpreter:\n\n\t\\ Only works for immediate words for now, we define\n\t\\ the word we wish to be executed when the forth core\n\t\\ is loaded\n\t: hello-world immediate\n\t\t\" Hello, World!\" cr bye ;\n\n\t\\ The following sets the starting word to our newly\n\t\\ defined word:\n\tfind hello-world cfa start!\n\n\t\\ Now we can save the core file out:\n\ts\" forth.core\" save-core \n\nThis can be used, in conjunction with aspects of the build system,\nto produce a standalone executable that will run only a single Forth\nword. )\n\nhide{ redirect restore data encore header }hide\n\n( ==================== Save Core file ======================== )\n\n( ==================== Hex dump ============================== )\n\n( @todo hexdump can read in too many characters and it does not\nprint out the correct address\n@todo utilities for easy redirecting of file input\/output )\n: input >r cpad 128 r> read-file ; ( file-id -- u 0 | error )\n: clean cpad 128 0 fill ; ( -- )\n: cdump cpad chars swap aligned chars dump ; ( u -- )\n: hexdump ( file-id -- : [hex]dump a file to the screen )\n\tdup \n\tclean\n\tinput if 2drop exit then\n\t?dup-if cdump else drop exit then\n\ttail ; \n\nhide{ cpad clean cdump input }hide\n\n( ==================== Hex dump ============================== )\n\n( ==================== Date ================================== )\n\n( Rather annoyingly months are start from 1 but weekdays from 0 )\n\n: >month ( month -- )\n\tcase\n\t\t 1 of \" Jan \" endof\n\t\t 2 of \" Feb \" endof\n\t\t 3 of \" Mar \" endof\n\t\t 4 of \" Apr \" endof\n\t\t 5 of \" May \" endof\n\t\t 6 of \" Jun \" endof\n\t\t 7 of \" Jul \" endof\n\t\t 8 of \" Aug \" endof\n\t\t 9 of \" Sep \" endof\n\t\t10 of \" Oct \" endof\n\t\t11 of \" Nov \" endof\n\t\t12 of \" Dec \" endof\n\tendcase drop ;\n\n: .day ( day -- : add ordinal to day )\n\t10 mod\n\tcase\n\t\t1 of \" st \" drop exit endof\n\t\t2 of \" nd \" drop exit endof\n\t\t3 of \" rd \" drop exit endof\n\t\t\" th \" \n\tendcase drop ;\n\n: >day ( day -- : add ordinal to day of month )\n\tdup u.\n\tdup 1 10 within if .day exit then\n\tdup 10 20 within if \" th\" drop exit then\n\t.day ;\n\n: >weekday ( weekday -- : print the weekday )\n\tcase\n\t\t0 of \" Sun \" endof\n\t\t1 of \" Mon \" endof\n\t\t2 of \" Tue \" endof\n\t\t3 of \" Wed \" endof\n\t\t4 of \" Thu \" endof\n\t\t5 of \" Fri \" endof\n\t\t6 of \" Sat \" endof\n\tendcase drop ;\n\n: padded ( u -- : print out a run of zero characters )\n\t0 do [char] 0 emit loop ;\n\n: 0u. ( u -- : print a zero padded number )\n\tdup 10 u< if 1 padded then u. space ;\n\n: .date ( date -- : print the date )\n\tif \" DST \" else \" GMT \" then \n\tdrop ( no need for days of year)\n\t>weekday\n\t. ( year ) \n\t>month \n\t>day \n\t0u. ( hour )\n\t0u. ( minute )\n\t0u. ( second ) cr ;\n\n: time&date ( -- second minute hour day month year )\n\tdate\n\t3drop ;\n\nhide{ 0u. >weekday .day >day >month padded }hide\n\n( ==================== Date ================================== )\n\n\n( ==================== CRC =================================== )\n\n( @todo implement all common CRC algorithms, but only if\nthe word size allows it [ie. 32 bit CRCs on a 32 or 64 bit\nmachine, 64 bit CRCs on a 64 bit machine] )\n\n( Make a word to limit arithmetic to a 16-bit value )\nsize 2 = [if] \n\t: limit immediate ; ( do nothing, no need to limit )\n[else] \n\t: limit 0xffff and ; ( limit to 16-bit value )\n[then]\n\n: ccitt ( crc char -- crc : calculate polynomial 0x1021 AKA \"x16 + x12 + x5 + 1\" )\n\t ( crc char )\n\tlimit over 256\/ xor ( crc x )\n\tdup 4 rshift xor ( crc x )\n\tdup 5 lshift limit xor ( crc x )\n\tdup 12 lshift limit xor ( crc x )\n\tswap 8 lshift limit xor ; ( crc )\n\n( see http:\/\/stackoverflow.com\/questions\/10564491\/function-to-calculate-a-crc16-checksum\n and https:\/\/www.lammertbies.nl\/comm\/info\/crc-calculation.html )\n: crc16-ccitt ( c-addr u -- u )\n\t0xFFFF -rot\n\t' ccitt\n\tforeach-char ;\nhide{ limit ccitt }hide\n\n( ==================== CRC =================================== )\n\n( ==================== Rational Data Type ==================== )\n( This word set allows the manipulation of a rational data type,\nwhich are basically fractions. This allows numbers like 1\/3 to\nbe represented without any loss of precision. Conversion to and\nfrom the data type to an integer type is trivial, although \ninformation can be lost during the conversion.\n\nTo convert to a rational, use 'dup', to convert from a rational,\nuse '\/'. \n\nThe denominator is the first number on the stack, the numerator the\nsecond number. Fractions are simplified after any rational operation,\nand all rational words can accept unsimplified arguments. For example\nthe fraction 1\/3 can be represented as 6\/18, they are equivalent, so\nthe rational equality operator \"=rat\" can accept both and returns\ntrue.\n\n\tT{ 1 3 6 18 =rat -> 1 }T\n\nSee: https:\/\/en.wikipedia.org\/wiki\/Rational_data_type \nFor more information.\n\nThis set of words use two cells to represent a fraction, however\na single cell could be used, with the numerator and the denominator\nstored in upper and lower half of a single cell. )\n\n: simplify ( a b -- a\/gcd{a,b} b\/gcd{a\/b} : simplify a rational )\n 2dup\n gcd\n tuck\n \/\n -rot\n \/\n swap ; \\ ? check this\n\n: crossmultiply ( a b c d -- a*d b*d c*b d*b )\n rot ( a c d b )\n 2dup ( a c d b d b )\n * ( a c d b d*b )\n >r ( a c d b , d*b )\n rot ( a d b c , d*b )\n * ( a d b*c , d*b )\n -rot ( b*c a d , d*b )\n * ( b*c a*d , d*b )\n r> ( b*c a*d d*b )\n tuck ( b*c d*b a*d d*b )\n 2swap ; ( done! )\n\n: *rat ( a\/b c\/d -- a\/b : multiply two rationals together )\n rot * -rot * swap simplify ;\n\n: \/rat ( a\/b c\/d -- a\/b : divide one rational by another )\n swap *rat ;\n\n: +rat ( a\/b c\/d -- a\/b : add two rationals together )\n crossmultiply\n rot\n drop ( or check if equal, if not there is an error )\n -rot\n +\n swap\n simplify ;\n\n: -rat ( a\/b c\/d -- a\/b : subtract one rational from another )\n crossmultiply \n rot\n drop ( or check if equal, if not there is an error )\n -rot\n -\n swap\n simplify ;\n\n: .rat ( a\/b -- : print out a rational number )\n simplify swap . [char] \/ emit space . ;\n\n: =rat ( a\/b c\/d -- bool : rational equal )\n crossmultiply rot = -rot = = ;\n\n: >rat ( a\/b c\/d -- bool : rational greater than )\n crossmultiply rot 2drop > ;\n\n: <=rat ( a\/b c\/d -- bool : rational less than or equal to )\n\t>rat not ;\n\n: =rat ( a\/b c\/d -- bool : rational greater or equal to )\n\t0 block number stored in buf)\n\n: invalid? ( n -- : throw if block number is invalid )\n\t0= if -35 throw then ;\n\n: update ( -- : mark currently loaded block buffer as dirty )\n\t1 dirty ! ;\n\n: block.name ( n -- c-addr u : make a block name )\n\t<# \n\t\t[char] k hold\n\t\t[char] l hold\n\t\t[char] b hold\n\t\t[char] . hold\n\t\t#s \n\t#> rot drop ;\n\n( @warning this will not work if we do not have permission,\nor in various other cases where we cannot open the file, for\nwhatever reason )\n: file-exists ( c-addr u : does a file exist? )\n\tr\/o open-file if drop 0 else close-file throw 1 then ;\n\n: buffer.exists ( n -- bool : does a block buffer exist on disk? )\n\tblock.name file-exists ;\n\n( @note block.write and block.read do not check if they have\nwrote or read in 1024 bytes, nor do they check that they can\nonly write or read 1024 and not a byte more )\n\n: block.read ( file-id -- file-id : read in buffer )\n\tdup >r buf r> read-file nip if close-file -33 throw then ;\n\n: block.write ( file-id -- file-id : write out buffer )\n\tdup >r buf r> write-file nip if close-file -34 throw then ;\n\n: block.open ( n fam -- file-id )\n\t>r block.name r> open-file throw ;\n\n: save-buffers \n\tblk @ 0= if exit then ( not a valid block number, exit )\n\tdirty @ not if exit then ( not dirty, no need to save )\n\tblk @ w\/o block.open ( open file backing block buffer )\n\tblock.write ( write it out )\n\tclose-file throw ( close it )\n\t0 dirty ! ; ( but only mark it clean if everything succeeded )\n\n: empty-buffers ( -- : deallocate any saved buffers )\n\t0 blk ! ;\n\n: flush ( -- : perform save-buffers followed by empty-buffers )\n\tsave-buffers\n\tempty-buffers ;\n\n( Block is a complex word that does a lot, although it has a simple\ninterface. It does the following given a block number:\n\n1. Checks the provided block buffer number to make sure it is valid\n2. If the block is already loaded from the disk, then return the\naddress of the block buffer it is loaded into.\n3. If not, it checks to see if the currently loaded block buffer is\ndirty, if it is then it flushes the buffer to disk.\n4. If the block buffer does not exists on disk then it creates it.\n5. It then stores the block number in blk and returns an address to\nthe block buffer. )\n: block ( n -- c-addr : load a block )\n\tdup invalid? \n\tdup blk @ = if drop buf drop exit then\n\tflush\n\tdup buffer.exists if ( if the buffer exits on disk load it in )\n\t\tdup r\/o block.open \n\t\tblock.read \n\t\tclose-file throw \n\telse ( else it does not exist )\n\t\tbuf 0 fill ( clean the buffer )\n\tthen \n\tblk ! ( save the block number )\n\tbuf drop ;\n\n: buffer block ;\n\nhide{ \n\tblock.name invalid? block.write \n\tblock.read buffer.exists block.open dirty\n}hide\n\n( ==================== Block Layer =========================== )\n\n( ==================== List ================================== )\n1 variable list.lines\n0 variable scr\n64 constant #line ( line length )\n\n: line.number ( n -- : print line number )\n\tlist.lines @ if\n\t\tdup 10 < if space then ( leading space: works up to #line = 99)\n\t\t. [char] | emit ( print \" line-number : \")\n\telse\n\t\tdrop\n\tthen ;\n\n: line ( c-addr -- c-addr u : given a line number, display that line )\n\tdup \n\tline.number ( display line number )\n\t#line * + ( calculate offset )\n\t#line ; ( add line length )\n\n: list.type ( c-addr u -- : list a block )\n\tb\/buf #line \/ 0 do dup i line type cr loop drop ;\n\n: list ( n -- : display a block number and update scr )\n\tdup >r block r> scr ! list.type ;\n\n: thru\n\tkey drop\n\t1+ swap do i list more loop ;\n\n: make-blocks ( n1 n2 -- : make blocks on disk from n1 to n2 inclusive )\n\t1+ swap do i block b\/buf bl fill update loop save-buffers ;\n\nhide{ buf line line.number list.type list.lines }hide\n\n( ==================== List ================================== )\n\n( ==================== Signal Handling ======================= )\n( Signal handling at the moment is quite primitive. When a signal\noccurs it has to be explicitly tested for by the programmer, this\ncould be improved on quite a bit. One way of doing this would be\nto check for signals in the virtual machine and cause a THROW\nfrom within it. )\n\n( signals are biased to fall outside the range of the error numbers\ndefined in the ANS Forth standard. )\n-512 constant signal-bias \n\n: signal ( -- signal\/0 : push the results of the signal register ) \n\t`signal @\n \t0 `signal ! ;\n\n( ==================== Signal Handling ======================= )\n\n( Looking at most Forths dictionary with \"words\" command they tend\nto have a lot of words that do not mean anything but to the implementers\nof that specific Forth, here we clean up as many non standard words as\npossible. )\nhide{ \n do-string ')' alignment-bits \n dictionary-start hidden-mask instruction-mask immediate-mask compiling?\n compile-bit\n max-core dolist doconst x x! x@ \n max-string-length \n _exit\n pnum evaluator \n TrueFalse >instruction \n xt-instruction\n `state\n `source-id `sin `sidx `slen `start-address `fin `fout `stdin\n `stdout `stderr `argc `argv `debug `invalid `top `instruction\n `stack-size `error-handler `x `handler _emit `signal \n}hide\n\n( \n## Forth To List\n\nThe following is a To-Do list for the Forth code itself, along with any\nother ideas.\n\n* FORTH, VOCABULARY\n* \"Value\", \"To\", \"Is\"\n* Double cell words \n* The interpreter should use character based addresses, instead of\nword based, and use values that are actual valid pointers, this\nwill allow easier interaction with the world outside the virtual machine\n* common words and actions should be factored out to simplify\ndefinitions of other words, their standards compliant version found\nif any\n* A soft floating point library would be useful which could be used\nto optionally implement floats [which is not something I really want\nto add to the virtual machine]. If floats were to be added, only the\nminimal set of functions should be added [f+,f-,f\/,f*,f<,f>,>float,...]\n* Allow the processing of argc and argv, the mechanism by which that\nthis can be achieved needs to be worked out. However all processing that\nis currently done in \"main.c\" should be done within the Forth interpreter\ninstead. Words for manipulating rationals and double width cells should\nbe made first.\n* A built in version of \"dump\" and \"words\" should be added to the Forth\nstarting vocabulary, simplified versions that can be hidden.\n* Here documents, string literals. Examples of these can be found online\n* Document the words in this file and built in words better, also turn this\ndocument into a literate Forth file.\n* Sort out \"'\", \"[']\", \"find\", \"compile,\" \n* Proper booleans should be used throughout, that is -1 is true, and 0 is\nfalse.\n* Attempt to add crypto primitives, not for serious use, like TEA, XTEA,\nXXTEA, RC4, MD5, ...\n* Add hash functions: CRC-32, CRC-16, ...\nhttp:\/\/stackoverflow.com\/questions\/10564491\/function-to-calculate-a-crc16-checksum\n* File operation primitives that close the file stream [and possibly restore\nI\/O to stdin\/stdout] if an error occurs, and then re-throws, should be made.\n* Implement as many things from http:\/\/lars.nocrew.org\/forth2012\/implement.html\nas is sensible. \n* CASE Statements http:\/\/dxforth.netbay.com.au\/miser.html\n* The current words that implement I\/O redirection need to be improved, and documented,\nI think this is quite a useful and powerful mechanism to use within Forth that simplifies\nprograms. This is a must and will make writing utilities in Forth a *lot* easier \n* Words for manipulating words should be added, for navigating to different\nfields within them, to the end of the word, etcetera.\n* The data structure used for parsing Forth words needs changing in libforth so a\ncounted string is produced. Counted strings should be used more often. The current\nlayout of a Forth word prevents a counted string being used and uses a byte more\nthan it has to.\n* Whether certain simple words [such as '1+', '1-', '>', '<', '<>', 'not', '<=',\n'>='] should be added as virtual machine instructions for speed [and size] reasons\nshould be investigated.\n* An analysis of the interpreter and the code it executes could be done to find\nthe most commonly executed words and instructions, as well as the most common two and\nthree sequences of words and instructions. This could be used to use to optimize the\ninterpreter, in terms of both speed and size.\n\n### libforth.c todo\n\n* A halt, a parse, and a print\/type instruction could be added to the Forth virtual\nmachine.\n* Throw\/Catch need to be added and used in the virtual machine\n* Various edge cases and exceptions should be removed [for example counted strings\nare not used internally, and '0x' can be used as a prefix only when base is zero].\n* A potential optimization is to order the words in the dictionary by frequency order,\nthis would mean chaning the X Macro that contains the list of words, after collecting\nstatistics. This should make find faster.\n* Investigate adding operating system specific code into the interpreter and\nisolating it to make it semi-portable.\n* Make equivalents for various Unix utilities in Forth, like a CRC check, cat,\ntr, etcetera.\n\n )\n\nverbose [if] \n\t.( FORTH: libforth successfully loaded.) cr\n\t.( Type 'help' and press return for a basic introduction.) cr\n\t.( Core: ) here . \" \/ \" here unused + . cr\n\t license\n[then]\n\n( The following will not work as we might actually be reading from a string [`sin]\nnot `fin. \n: key 32 chars> 1 `fin @ read-file drop 0 = if 0 else 32 chars> c@ then ; )\n\n\\ : ' immediate state @ if postpone ['] else find then ;\n\n( This really does not implement a correct FORTH\/VOCABULARY, for that\nwordlists will need to be introduced and used in libforth.c. The best\nthat this word set can do is to hide and reveal words to the user, this\nwas just an experiment. \n\n\t: forth \n\t\t[ find forth 1- @ ] literal\n\t\t[ find forth 1- ] literal ! ;\n\n\t: vocabulary\n\t\tcreate does> drop 0 [ find forth 1- ] literal ! ; )\n\n( Experimental block editor Mark II )\n( @todo '\\' needs extending to work with the block editor, for now, \nuse parenthesis for comments \n@todo make an 'm' word for forgetting all words defined since the\neditor was invoked.\n@todo add multi line insertion mode\n@todo Add to an editor vocabulary, which will need the vocabulary\nsystem to exist.\n@todo Using 'page' should be optional as not all terminals support\nANSI escape codes - thanks to CMD.EXE. Damned Windows.\n@todo How line numbers are printed out should be investigated,\nalso I should refactor 'dump' to use a similar line number system.\n\nAdapted from http:\/\/retroforth.org\/pages\/?PortsOfRetroEditor )\n: h\npage\n\" Block Editor Help Menu\n\n n move to next block\n p move to previous block\n # d delete line in current block\n x erase current block\n e evaluate current block\n # i insert line\n # #2 ia insert at line #2 at column #\n q quit editor loop\n # b set block number\n s save block and write it out\n\n -- press any key to continue -- \" cr ( \" )\nchar drop ;\n\n: (block) blk @ block ; \n: (line) #line * (block) + ; ( n -- c-addr : push current line address )\n: n blk @ 1+ block ;\n: p blk @ 1- block ;\n: l blk @ list ;\n: d (line) #line bl fill ; \n: x (block) b\/buf bl fill ;\n: b block ;\n: s update save-buffers ;\n: q rdrop rdrop ;\n: e (block) b\/buf 1+ evaluate drop char drop ; ( @warning uses hack, block buffer is NUL terminated)\n: ia #line * + dup b\/buf swap - >r (block) + r> accept ; ( @bug accept NUL terminates the string! )\n: i 0 swap ia ;\n: editor\n\t1 block\n\tpostpone [ \n\tbegin\n\t\tpage\n\t\t\" BLOCK EDITOR: TYPE H FOR HELP \" cr\n\t\tblk @ list\n\t\t\" CURRENT BLOCK: \" blk @ . cr\n\t\tread\n\tagain ;\n\nhide{ (block) (line) }hide\n\nhere fence !\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"2018d664594de78ee945d53196fa4fe7e86983ac","subject":"Add descriptive comment","message":"Add descriptive comment\n","repos":"gitlarryf\/neon-lang,ghewgill\/neon-lang,ghewgill\/neon-lang,gitlarryf\/neon-lang,ghewgill\/neon-lang,ghewgill\/neon-lang,gitlarryf\/neon-lang,ghewgill\/neon-lang,ghewgill\/neon-lang,gitlarryf\/neon-lang,ghewgill\/neon-lang,ghewgill\/neon-lang,gitlarryf\/neon-lang,gitlarryf\/neon-lang,gitlarryf\/neon-lang,gitlarryf\/neon-lang,ghewgill\/neon-lang,gitlarryf\/neon-lang,ghewgill\/neon-lang,gitlarryf\/neon-lang","old_file":"samples\/forth\/tests.forth","new_file":"samples\/forth\/tests.forth","new_contents":"\\ Forth 2012 core test suite:\n\\ http:\/\/lars.nocrew.org\/forth2012\/testsuite.html\n\nHEX\n\nT{ -> }T ( Start with a clean slate )\n( Test if any bits are set; Answer in base 1 )\nT{ : BITSSET? IF 0 0 ELSE 0 THEN ; -> }T\nT{ 0 BITSSET? -> 0 }T ( Zero is all bits clear )\n\\ T{ 1 BITSSET? -> 0 0 }T ( Other numbers have at least one bit )\n\\ T{ -1 BITSSET? -> 0 0 }T\n\n\\ F.6.1.0720 AND\nT{ 0 0 AND -> 0 }T\nT{ 0 1 AND -> 0 }T\nT{ 1 0 AND -> 0 }T\nT{ 1 1 AND -> 1 }T\nT{ 0 INVERT 1 AND -> 1 }T\nT{ 1 INVERT 1 AND -> 0 }T\n\n\\ Define 0S and 1S\n0 CONSTANT 0S\n0S INVERT CONSTANT 1S\n\n\\ F.6.1.1720 INVERT\nT{ 0S INVERT -> 1S }T\nT{ 1S INVERT -> 0S }T\n\n\\ F.6.1.0950 CONSTANT\nT{ 123 CONSTANT X123 -> }T\nT{ X123 -> 123 }T\nT{ : EQU CONSTANT ; -> }T\nT{ X123 EQU Y123 -> }T\nT{ Y123 -> 123 }T\n\n\\ F.6.1.0720 AND (continued)\nT{ 0S 0S AND -> 0S }T\nT{ 0S 1S AND -> 0S }T\nT{ 1S 0S AND -> 0S }T\nT{ 1S 1S AND -> 1S }T\n\n\\ F.6.1.1980 OR\nT{ 0S 0S OR -> 0S }T\nT{ 0S 1S OR -> 1S }T\nT{ 1S 0S OR -> 1S }T\nT{ 1S 1S OR -> 1S }T\n\n\\ F.6.1.2490 XOR\nT{ 0S 0S XOR -> 0S }T\nT{ 0S 1S XOR -> 1S }T\nT{ 1S 0S XOR -> 1S }T\nT{ 1S 1S XOR -> 0S }T\n\n1S 1 RSHIFT INVERT CONSTANT MSB\nT{ MSB BITSSET? -> 0 0 }T\n\n\\ F.6.1.0320 2*\nT{ 0S 2* -> 0S }T\nT{ 1 2* -> 2 }T\nT{ 4000 2* -> 8000 }T\nT{ 1S 2* 1 XOR -> 1S }T\nT{ MSB 2* -> 0S }T\n\n\\ F.6.1.0330 2\/\nT{ 0S 2\/ -> 0S }T\nT{ 1 2\/ -> 0 }T\nT{ 4000 2\/ -> 2000 }T\nT{ 1S 2\/ -> 1S }T \\ MSB PROPOGATED\nT{ 1S 1 XOR 2\/ -> 1S }T\nT{ MSB 2\/ MSB AND -> MSB }T\n\n\\ F.6.1.1805 LSHIFT\nT{ 1 0 LSHIFT -> 1 }T\nT{ 1 1 LSHIFT -> 2 }T\nT{ 1 2 LSHIFT -> 4 }T\nT{ 1 F LSHIFT -> 8000 }T \\ BIGGEST GUARANTEED SHIFT\nT{ 1S 1 LSHIFT 1 XOR -> 1S }T\nT{ MSB 1 LSHIFT -> 0 }T\n\n\\ F.6.1.2162 RSHIFT\nT{ 1 0 RSHIFT -> 1 }T\nT{ 1 1 RSHIFT -> 0 }T\nT{ 2 1 RSHIFT -> 1 }T\nT{ 4 2 RSHIFT -> 1 }T\nT{ 8000 F RSHIFT -> 1 }T \\ Biggest\nT{ MSB 1 RSHIFT MSB AND -> 0 }T \\ RSHIFT zero fills MSBs\nT{ MSB 1 RSHIFT 2* -> MSB }T\n\nDECIMAL\nT{ #1289 -> 1289 }T\n\\ SKIP: T{ #12346789. -> 12346789. }T\nT{ #-1289 -> -1289 }T\n\\ SKIP: T{ #-12346789. -> -12346789. }T\nT{ $12eF -> 4847 }T\n\\ SKIP: T{ $12aBcDeF. -> 313249263. }T\nT{ $-12eF -> -4847 }T\n\\ SKIP: T{ $-12AbCdEf. -> -313249263. }T\nT{ %10010110 -> 150 }T\n\\ SKIP: T{ %10010110. -> 150. }T\nT{ %-10010110 -> -150 }T\n\\ SKIP: T{ %-10010110. -> -150. }T\n\\ TODO: T{ 'z' -> 122 }T\nHEX\n\n0 INVERT CONSTANT MAX-UINT\n0 INVERT 1 RSHIFT CONSTANT MAX-INT\n0 INVERT 1 RSHIFT INVERT CONSTANT MIN-INT\n0 INVERT 1 RSHIFT CONSTANT MID-UINT\n0 INVERT 1 RSHIFT INVERT CONSTANT MID-UINT+1\n\n0S CONSTANT \n1S CONSTANT \n\n\\ F.6.1.0270 0=\nT{ 0 0= -> }T\nT{ 1 0= -> }T\nT{ 2 0= -> }T\nT{ -1 0= -> }T\nT{ MAX-UINT 0= -> }T\nT{ MIN-INT 0= -> }T\nT{ MAX-INT 0= -> }T\n\n\\ F.6.1.0530 =\nT{ 0 0 = -> }T\nT{ 1 1 = -> }T\nT{ -1 -1 = -> }T\nT{ 1 0 = -> }T\nT{ -1 0 = -> }T\nT{ 0 1 = -> }T\nT{ 0 -1 = -> }T\n\n\\ F.6.1.0250 0<\nT{ 0 0< -> }T\nT{ -1 0< -> }T\nT{ MIN-INT 0< -> }T\nT{ 1 0< -> }T\nT{ MAX-INT 0< -> }T\n\n\\ F.6.1.0480 <\nT{ 0 1 < -> }T\nT{ 1 2 < -> }T\nT{ -1 0 < -> }T\nT{ -1 1 < -> }T\nT{ MIN-INT 0 < -> }T\nT{ MIN-INT MAX-INT < -> }T\nT{ 0 MAX-INT < -> }T\nT{ 0 0 < -> }T\nT{ 1 1 < -> }T\nT{ 1 0 < -> }T\nT{ 2 1 < -> }T\nT{ 0 -1 < -> }T\nT{ 1 -1 < -> }T\nT{ 0 MIN-INT < -> }T\nT{ MAX-INT MIN-INT < -> }T\nT{ MAX-INT 0 < -> }T\n\n\\ F.6.1.0540 >\nT{ 0 1 > -> }T\nT{ 1 2 > -> }T\nT{ -1 0 > -> }T\nT{ -1 1 > -> }T\nT{ MIN-INT 0 > -> }T\nT{ MIN-INT MAX-INT > -> }T\nT{ 0 MAX-INT > -> }T\nT{ 0 0 > -> }T\nT{ 1 1 > -> }T\nT{ 1 0 > -> }T\nT{ 2 1 > -> }T\nT{ 0 -1 > -> }T\nT{ 1 -1 > -> }T\nT{ 0 MIN-INT > -> }T\nT{ MAX-INT MIN-INT > -> }T\nT{ MAX-INT 0 > -> }T\n\n\\ F.6.1.2340 U<\nT{ 0 1 U< -> }T\nT{ 1 2 U< -> }T\nT{ 0 MID-UINT U< -> }T\nT{ 0 MAX-UINT U< -> }T\nT{ MID-UINT MAX-UINT U< -> }T\nT{ 0 0 U< -> }T\nT{ 1 1 U< -> }T\nT{ 1 0 U< -> }T\nT{ 2 1 U< -> }T\nT{ MID-UINT 0 U< -> }T\nT{ MAX-UINT 0 U< -> }T\nT{ MAX-UINT MID-UINT U< -> }T\n\n\\ F.6.1.1880 MIN\nT{ 0 1 MIN -> 0 }T\nT{ 1 2 MIN -> 1 }T\nT{ -1 0 MIN -> -1 }T\nT{ -1 1 MIN -> -1 }T\nT{ MIN-INT 0 MIN -> MIN-INT }T\nT{ MIN-INT MAX-INT MIN -> MIN-INT }T\nT{ 0 MAX-INT MIN -> 0 }T\nT{ 0 0 MIN -> 0 }T\nT{ 1 1 MIN -> 1 }T\nT{ 1 0 MIN -> 0 }T\nT{ 2 1 MIN -> 1 }T\nT{ 0 -1 MIN -> -1 }T\nT{ 1 -1 MIN -> -1 }T\nT{ 0 MIN-INT MIN -> MIN-INT }T\nT{ MAX-INT MIN-INT MIN -> MIN-INT }T\nT{ MAX-INT 0 MIN -> 0 }T\n\n\\ F.6.1.1870 MAX\nT{ 0 1 MAX -> 1 }T\nT{ 1 2 MAX -> 2 }T\nT{ -1 0 MAX -> 0 }T\nT{ -1 1 MAX -> 1 }T\nT{ MIN-INT 0 MAX -> 0 }T\nT{ MIN-INT MAX-INT MAX -> MAX-INT }T\nT{ 0 MAX-INT MAX -> MAX-INT }T\nT{ 0 0 MAX -> 0 }T\nT{ 1 1 MAX -> 1 }T\nT{ 1 0 MAX -> 1 }T\nT{ 2 1 MAX -> 2 }T\nT{ 0 -1 MAX -> 0 }T\nT{ 1 -1 MAX -> 1 }T\nT{ 0 MIN-INT MAX -> 0 }T\nT{ MAX-INT MIN-INT MAX -> MAX-INT }T\nT{ MAX-INT 0 MAX -> MAX-INT }T\n\n\\ F.6.1.1260 DROP\nT{ 1 2 DROP -> 1 }T\nT{ 0 DROP -> }T\n\n\\ F.6.1.1290 DUP\nT{ 1 DUP -> 1 1 }T\n\n\\ F.6.1.1990 OVER\nT{ 1 2 OVER -> 1 2 1 }T\n\n\\ F.6.1.2160 ROT\nT{ 1 2 3 ROT -> 2 3 1 }T\n\n\\ F.6.1.2260 SWAP\nT{ 1 2 SWAP -> 2 1 }T\n\n\\ F.6.1.0370 2DROP\nT{ 1 2 2DROP -> }T\n\n\\ F.6.1.0380 2DUP\nT{ 1 2 2DUP -> 1 2 1 2 }T\n\n\\ F.6.1.0400 2OVER\nT{ 1 2 3 4 2OVER -> 1 2 3 4 1 2 }T\n\n\\ F.6.1.0430 2SWAP\nT{ 1 2 3 4 2SWAP -> 3 4 1 2 }T\n\n\\ F.6.1.0630 ?DUP\nT{ -1 ?DUP -> -1 -1 }T\nT{ 0 ?DUP -> 0 }T\nT{ 1 ?DUP -> 1 1 }T\n\n\\ F.6.1.1200 DEPTH\nT{ 0 1 DEPTH -> 0 1 2 }T\nT{ 0 DEPTH -> 0 1 }T\nT{ DEPTH -> 0 }T\n\n\\ F.6.1.0580 >R\nT{ : GR1 >R R> ; -> }T\nT{ : GR2 >R R@ R> DROP ; -> }T\nT{ 123 GR1 -> 123 }T\nT{ 123 GR2 -> 123 }T\nT{ 1S GR1 -> 1S }T ( Return stack holds cells )\n\n\\ F.6.1.0120 +\nT{ 0 5 + -> 5 }T\nT{ 5 0 + -> 5 }T\nT{ 0 -5 + -> -5 }T\nT{ -5 0 + -> -5 }T\nT{ 1 2 + -> 3 }T\nT{ 1 -2 + -> -1 }T\nT{ -1 2 + -> 1 }T\nT{ -1 -2 + -> -3 }T\nT{ -1 1 + -> 0 }T\nT{ MID-UINT 1 + -> MID-UINT+1 }T\n\n\\ F.6.1.0160 -\nT{ 0 5 - -> -5 }T\nT{ 5 0 - -> 5 }T\nT{ 0 -5 - -> 5 }T\nT{ -5 0 - -> -5 }T\nT{ 1 2 - -> -1 }T\nT{ 1 -2 - -> 3 }T\nT{ -1 2 - -> -3 }T\nT{ -1 -2 - -> 1 }T\nT{ 0 1 - -> -1 }T\nT{ MID-UINT+1 1 - -> MID-UINT }T\n\n\\ F.6.1.0290 1+\nT{ 0 1+ -> 1 }T\nT{ -1 1+ -> 0 }T\nT{ 1 1+ -> 2 }T\nT{ MID-UINT 1+ -> MID-UINT+1 }T\n\n\\ F.6.1.0300 1-\nT{ 2 1- -> 1 }T\nT{ 1 1- -> 0 }T\nT{ 0 1- -> -1 }T\nT{ MID-UINT+1 1- -> MID-UINT }T\n\n\\ F.6.1.0690 ABS\nT{ 0 ABS -> 0 }T\nT{ 1 ABS -> 1 }T\nT{ -1 ABS -> 1 }T\nT{ MIN-INT ABS -> MID-UINT+1 }T\n\n\\ F.6.1.1910 NEGATE\nT{ 0 NEGATE -> 0 }T\nT{ 1 NEGATE -> -1 }T\nT{ -1 NEGATE -> 1 }T\nT{ 2 NEGATE -> -2 }T\nT{ -2 NEGATE -> 2 }T\n\n\\ F.6.1.2170 S>D\nT{ 0 S>D -> 0 0 }T\nT{ 1 S>D -> 1 0 }T\nT{ 2 S>D -> 2 0 }T\nT{ -1 S>D -> -1 -1 }T\nT{ -2 S>D -> -2 -1 }T\nT{ MIN-INT S>D -> MIN-INT -1 }T\nT{ MAX-INT S>D -> MAX-INT 0 }T\n\n\\ F.6.1.0090 *\nT{ 0 0 * -> 0 }T \\ TEST IDENTITIE\\S\nT{ 0 1 * -> 0 }T\nT{ 1 0 * -> 0 }T\nT{ 1 2 * -> 2 }T\nT{ 2 1 * -> 2 }T\nT{ 3 3 * -> 9 }T\nT{ -3 3 * -> -9 }T\nT{ 3 -3 * -> -9 }T\nT{ -3 -3 * -> 9 }T\nT{ MID-UINT+1 1 RSHIFT 2 * -> MID-UINT+1 }T\nT{ MID-UINT+1 2 RSHIFT 4 * -> MID-UINT+1 }T\nT{ MID-UINT+1 1 RSHIFT MID-UINT+1 OR 2 * -> MID-UINT+1 }T\n\n\\ F.6.1.1810 M*\nT{ 0 0 M* -> 0 S>D }T\nT{ 0 1 M* -> 0 S>D }T\nT{ 1 0 M* -> 0 S>D }T\nT{ 1 2 M* -> 2 S>D }T\nT{ 2 1 M* -> 2 S>D }T\nT{ 3 3 M* -> 9 S>D }T\nT{ -3 3 M* -> -9 S>D }T\nT{ 3 -3 M* -> -9 S>D }T\nT{ -3 -3 M* -> 9 S>D }T\nT{ 0 MIN-INT M* -> 0 S>D }T\nT{ 1 MIN-INT M* -> MIN-INT S>D }T\nT{ 2 MIN-INT M* -> 0 1S }T\nT{ 0 MAX-INT M* -> 0 S>D }T\nT{ 1 MAX-INT M* -> MAX-INT S>D }T\nT{ 2 MAX-INT M* -> MAX-INT 1 LSHIFT 0 }T\nT{ MIN-INT MIN-INT M* -> 0 MSB 1 RSHIFT }T\nT{ MAX-INT MIN-INT M* -> MSB MSB 2\/ }T\nT{ MAX-INT MAX-INT M* -> 1 MSB 2\/ INVERT }T\n\n\\ F.6.1.2360 UM*\nT{ 0 0 UM* -> 0 0 }T\nT{ 0 1 UM* -> 0 0 }T\nT{ 1 0 UM* -> 0 0 }T\nT{ 1 2 UM* -> 2 0 }T\nT{ 2 1 UM* -> 2 0 }T\nT{ 3 3 UM* -> 9 0 }T\nT{ MID-UINT+1 1 RSHIFT 2 UM* -> MID-UINT+1 0 }T\nT{ MID-UINT+1 2 UM* -> 0 1 }T\nT{ MID-UINT+1 4 UM* -> 0 2 }T\nT{ 1S 2 UM* -> 1S 1 LSHIFT 1 }T\nT{ MAX-UINT MAX-UINT UM* -> 1 1 INVERT }T\n\n\\ F.6.1.1561 FM\/MOD\nT{ 0 S>D 1 FM\/MOD -> 0 0 }T\nT{ 1 S>D 1 FM\/MOD -> 0 1 }T\nT{ 2 S>D 1 FM\/MOD -> 0 2 }T\nT{ -1 S>D 1 FM\/MOD -> 0 -1 }T\nT{ -2 S>D 1 FM\/MOD -> 0 -2 }T\nT{ 0 S>D -1 FM\/MOD -> 0 0 }T\nT{ 1 S>D -1 FM\/MOD -> 0 -1 }T\nT{ 2 S>D -1 FM\/MOD -> 0 -2 }T\nT{ -1 S>D -1 FM\/MOD -> 0 1 }T\nT{ -2 S>D -1 FM\/MOD -> 0 2 }T\nT{ 2 S>D 2 FM\/MOD -> 0 1 }T\nT{ -1 S>D -1 FM\/MOD -> 0 1 }T\nT{ -2 S>D -2 FM\/MOD -> 0 1 }T\nT{ 7 S>D 3 FM\/MOD -> 1 2 }T\nT{ 7 S>D -3 FM\/MOD -> -2 -3 }T\nT{ -7 S>D 3 FM\/MOD -> 2 -3 }T\nT{ -7 S>D -3 FM\/MOD -> -1 2 }T\nT{ MAX-INT S>D 1 FM\/MOD -> 0 MAX-INT }T\nT{ MIN-INT S>D 1 FM\/MOD -> 0 MIN-INT }T\nT{ MAX-INT S>D MAX-INT FM\/MOD -> 0 1 }T\nT{ MIN-INT S>D MIN-INT FM\/MOD -> 0 1 }T\nT{ 1S 1 4 FM\/MOD -> 3 MAX-INT }T\nT{ 1 MIN-INT M* 1 FM\/MOD -> 0 MIN-INT }T\nT{ 1 MIN-INT M* MIN-INT FM\/MOD -> 0 1 }T\nT{ 2 MIN-INT M* 2 FM\/MOD -> 0 MIN-INT }T\nT{ 2 MIN-INT M* MIN-INT FM\/MOD -> 0 2 }T\nT{ 1 MAX-INT M* 1 FM\/MOD -> 0 MAX-INT }T\nT{ 1 MAX-INT M* MAX-INT FM\/MOD -> 0 1 }T\nT{ 2 MAX-INT M* 2 FM\/MOD -> 0 MAX-INT }T\nT{ 2 MAX-INT M* MAX-INT FM\/MOD -> 0 2 }T\nT{ MIN-INT MIN-INT M* MIN-INT FM\/MOD -> 0 MIN-INT }T\nT{ MIN-INT MAX-INT M* MIN-INT FM\/MOD -> 0 MAX-INT }T\nT{ MIN-INT MAX-INT M* MAX-INT FM\/MOD -> 0 MIN-INT }T\nT{ MAX-INT MAX-INT M* MAX-INT FM\/MOD -> 0 MAX-INT }T\n\n\\ F.6.1.2214 SM\/REM\nT{ 0 S>D 1 SM\/REM -> 0 0 }T\nT{ 1 S>D 1 SM\/REM -> 0 1 }T\nT{ 2 S>D 1 SM\/REM -> 0 2 }T\nT{ -1 S>D 1 SM\/REM -> 0 -1 }T\nT{ -2 S>D 1 SM\/REM -> 0 -2 }T\nT{ 0 S>D -1 SM\/REM -> 0 0 }T\nT{ 1 S>D -1 SM\/REM -> 0 -1 }T\nT{ 2 S>D -1 SM\/REM -> 0 -2 }T\nT{ -1 S>D -1 SM\/REM -> 0 1 }T\nT{ -2 S>D -1 SM\/REM -> 0 2 }T\nT{ 2 S>D 2 SM\/REM -> 0 1 }T\nT{ -1 S>D -1 SM\/REM -> 0 1 }T\nT{ -2 S>D -2 SM\/REM -> 0 1 }T\nT{ 7 S>D 3 SM\/REM -> 1 2 }T\n\\ TODO: T{ 7 S>D -3 SM\/REM -> 1 -2 }T\n\\ TODO: T{ -7 S>D 3 SM\/REM -> 1 -2 }T\nT{ -7 S>D -3 SM\/REM -> -1 2 }T\nT{ MAX-INT S>D 1 SM\/REM -> 0 MAX-INT }T\nT{ MIN-INT S>D 1 SM\/REM -> 0 MIN-INT }T\nT{ MAX-INT S>D MAX-INT SM\/REM -> 0 1 }T\nT{ MIN-INT S>D MIN-INT SM\/REM -> 0 1 }T\nT{ 1S 1 4 SM\/REM -> 3 MAX-INT }T\nT{ 2 MIN-INT M* 2 SM\/REM -> 0 MIN-INT }T\nT{ 2 MIN-INT M* MIN-INT SM\/REM -> 0 2 }T\nT{ 2 MAX-INT M* 2 SM\/REM -> 0 MAX-INT }T\nT{ 2 MAX-INT M* MAX-INT SM\/REM -> 0 2 }T\nT{ MIN-INT MIN-INT M* MIN-INT SM\/REM -> 0 MIN-INT }T\nT{ MIN-INT MAX-INT M* MIN-INT SM\/REM -> 0 MAX-INT }T\nT{ MIN-INT MAX-INT M* MAX-INT SM\/REM -> 0 MIN-INT }T\nT{ MAX-INT MAX-INT M* MAX-INT SM\/REM -> 0 MAX-INT }T\n\n\\ F.6.1.2370 UM\/MOD\nT{ 0 0 1 UM\/MOD -> 0 0 }T\nT{ 1 0 1 UM\/MOD -> 0 1 }T\nT{ 1 0 2 UM\/MOD -> 1 0 }T\nT{ 3 0 2 UM\/MOD -> 1 1 }T\nT{ MAX-UINT 2 UM* 2 UM\/MOD -> 0 MAX-UINT }T\nT{ MAX-UINT 2 UM* MAX-UINT UM\/MOD -> 0 2 }T\nT{ MAX-UINT MAX-UINT UM* MAX-UINT UM\/MOD -> 0 MAX-UINT }T\n\n: IFFLOORED [ -3 2 \/ -2 = INVERT ] LITERAL IF POSTPONE \\ THEN ;\n: IFSYM [ -3 2 \/ -1 = INVERT ] LITERAL IF POSTPONE \\ THEN ;\n\n\\ F.6.1.0240 \/MOD\nIFFLOORED : T\/MOD >R S>D R> FM\/MOD ;\nIFSYM : T\/MOD >R S>D R> SM\/REM ;\nT{ 0 1 \/MOD -> 0 1 T\/MOD }T\nT{ 1 1 \/MOD -> 1 1 T\/MOD }T\nT{ 2 1 \/MOD -> 2 1 T\/MOD }T\nT{ -1 1 \/MOD -> -1 1 T\/MOD }T\nT{ -2 1 \/MOD -> -2 1 T\/MOD }T\nT{ 0 -1 \/MOD -> 0 -1 T\/MOD }T\nT{ 1 -1 \/MOD -> 1 -1 T\/MOD }T\nT{ 2 -1 \/MOD -> 2 -1 T\/MOD }T\nT{ -1 -1 \/MOD -> -1 -1 T\/MOD }T\nT{ -2 -1 \/MOD -> -2 -1 T\/MOD }T\nT{ 2 2 \/MOD -> 2 2 T\/MOD }T\nT{ -1 -1 \/MOD -> -1 -1 T\/MOD }T\nT{ -2 -2 \/MOD -> -2 -2 T\/MOD }T\nT{ 7 3 \/MOD -> 7 3 T\/MOD }T\nT{ 7 -3 \/MOD -> 7 -3 T\/MOD }T\nT{ -7 3 \/MOD -> -7 3 T\/MOD }T\nT{ -7 -3 \/MOD -> -7 -3 T\/MOD }T\nT{ MAX-INT 1 \/MOD -> MAX-INT 1 T\/MOD }T\nT{ MIN-INT 1 \/MOD -> MIN-INT 1 T\/MOD }T\nT{ MAX-INT MAX-INT \/MOD -> MAX-INT MAX-INT T\/MOD }T\nT{ MIN-INT MIN-INT \/MOD -> MIN-INT MIN-INT T\/MOD }T\n\n\\ F.6.1.0230 \/\nIFFLOORED : T\/ T\/MOD SWAP DROP ;\nIFSYM : T\/ T\/MOD SWAP DROP ;\nT{ 0 1 \/ -> 0 1 T\/ }T\nT{ 1 1 \/ -> 1 1 T\/ }T\nT{ 2 1 \/ -> 2 1 T\/ }T\nT{ -1 1 \/ -> -1 1 T\/ }T\nT{ -2 1 \/ -> -2 1 T\/ }T\nT{ 0 -1 \/ -> 0 -1 T\/ }T\nT{ 1 -1 \/ -> 1 -1 T\/ }T\nT{ 2 -1 \/ -> 2 -1 T\/ }T\nT{ -1 -1 \/ -> -1 -1 T\/ }T\nT{ -2 -1 \/ -> -2 -1 T\/ }T\nT{ 2 2 \/ -> 2 2 T\/ }T\nT{ -1 -1 \/ -> -1 -1 T\/ }T\nT{ -2 -2 \/ -> -2 -2 T\/ }T\nT{ 7 3 \/ -> 7 3 T\/ }T\nT{ 7 -3 \/ -> 7 -3 T\/ }T\nT{ -7 3 \/ -> -7 3 T\/ }T\nT{ -7 -3 \/ -> -7 -3 T\/ }T\nT{ MAX-INT 1 \/ -> MAX-INT 1 T\/ }T\nT{ MIN-INT 1 \/ -> MIN-INT 1 T\/ }T\nT{ MAX-INT MAX-INT \/ -> MAX-INT MAX-INT T\/ }T\nT{ MIN-INT MIN-INT \/ -> MIN-INT MIN-INT T\/ }T\n\n\\ F.6.1.1890 MOD\nIFFLOORED : TMOD T\/MOD DROP ;\nIFSYM : TMOD T\/MOD DROP ;\nT{ 0 1 MOD -> 0 1 TMOD }T\nT{ 1 1 MOD -> 1 1 TMOD }T\nT{ 2 1 MOD -> 2 1 TMOD }T\nT{ -1 1 MOD -> -1 1 TMOD }T\nT{ -2 1 MOD -> -2 1 TMOD }T\nT{ 0 -1 MOD -> 0 -1 TMOD }T\nT{ 1 -1 MOD -> 1 -1 TMOD }T\nT{ 2 -1 MOD -> 2 -1 TMOD }T\nT{ -1 -1 MOD -> -1 -1 TMOD }T\nT{ -2 -1 MOD -> -2 -1 TMOD }T\nT{ 2 2 MOD -> 2 2 TMOD }T\nT{ -1 -1 MOD -> -1 -1 TMOD }T\nT{ -2 -2 MOD -> -2 -2 TMOD }T\nT{ 7 3 MOD -> 7 3 TMOD }T\nT{ 7 -3 MOD -> 7 -3 TMOD }T\nT{ -7 3 MOD -> -7 3 TMOD }T\nT{ -7 -3 MOD -> -7 -3 TMOD }T\nT{ MAX-INT 1 MOD -> MAX-INT 1 TMOD }T\nT{ MIN-INT 1 MOD -> MIN-INT 1 TMOD }T\nT{ MAX-INT MAX-INT MOD -> MAX-INT MAX-INT TMOD }T\nT{ MIN-INT MIN-INT MOD -> MIN-INT MIN-INT TMOD }T\n\n\\ F.6.1.0110 *\/MOD\nIFFLOORED : T*\/MOD >R M* R> FM\/MOD ;\nIFSYM : T*\/MOD >R M* R> SM\/REM ;\nT{ 0 2 1 *\/MOD -> 0 2 1 T*\/MOD }T\nT{ 1 2 1 *\/MOD -> 1 2 1 T*\/MOD }T\nT{ 2 2 1 *\/MOD -> 2 2 1 T*\/MOD }T\nT{ -1 2 1 *\/MOD -> -1 2 1 T*\/MOD }T\nT{ -2 2 1 *\/MOD -> -2 2 1 T*\/MOD }T\nT{ 0 2 -1 *\/MOD -> 0 2 -1 T*\/MOD }T\nT{ 1 2 -1 *\/MOD -> 1 2 -1 T*\/MOD }T\nT{ 2 2 -1 *\/MOD -> 2 2 -1 T*\/MOD }T\nT{ -1 2 -1 *\/MOD -> -1 2 -1 T*\/MOD }T\nT{ -2 2 -1 *\/MOD -> -2 2 -1 T*\/MOD }T\nT{ 2 2 2 *\/MOD -> 2 2 2 T*\/MOD }T\nT{ -1 2 -1 *\/MOD -> -1 2 -1 T*\/MOD }T\nT{ -2 2 -2 *\/MOD -> -2 2 -2 T*\/MOD }T\nT{ 7 2 3 *\/MOD -> 7 2 3 T*\/MOD }T\nT{ 7 2 -3 *\/MOD -> 7 2 -3 T*\/MOD }T\nT{ -7 2 3 *\/MOD -> -7 2 3 T*\/MOD }T\nT{ -7 2 -3 *\/MOD -> -7 2 -3 T*\/MOD }T\nT{ MAX-INT 2 MAX-INT *\/MOD -> MAX-INT 2 MAX-INT T*\/MOD }T\nT{ MIN-INT 2 MIN-INT *\/MOD -> MIN-INT 2 MIN-INT T*\/MOD }T\n\n\\ F.6.1.0100 *\/\nIFFLOORED : T*\/ T*\/MOD SWAP DROP ;\nIFSYM : T*\/ T*\/MOD SWAP DROP ;\nT{ 0 2 1 *\/ -> 0 2 1 T*\/ }T\nT{ 1 2 1 *\/ -> 1 2 1 T*\/ }T\nT{ 2 2 1 *\/ -> 2 2 1 T*\/ }T\nT{ -1 2 1 *\/ -> -1 2 1 T*\/ }T\nT{ -2 2 1 *\/ -> -2 2 1 T*\/ }T\nT{ 0 2 -1 *\/ -> 0 2 -1 T*\/ }T\nT{ 1 2 -1 *\/ -> 1 2 -1 T*\/ }T\nT{ 2 2 -1 *\/ -> 2 2 -1 T*\/ }T\nT{ -1 2 -1 *\/ -> -1 2 -1 T*\/ }T\nT{ -2 2 -1 *\/ -> -2 2 -1 T*\/ }T\nT{ 2 2 2 *\/ -> 2 2 2 T*\/ }T\nT{ -1 2 -1 *\/ -> -1 2 -1 T*\/ }T\nT{ -2 2 -2 *\/ -> -2 2 -2 T*\/ }T\nT{ 7 2 3 *\/ -> 7 2 3 T*\/ }T\nT{ 7 2 -3 *\/ -> 7 2 -3 T*\/ }T\nT{ -7 2 3 *\/ -> -7 2 3 T*\/ }T\nT{ -7 2 -3 *\/ -> -7 2 -3 T*\/ }T\nT{ MAX-INT 2 MAX-INT *\/ -> MAX-INT 2 MAX-INT T*\/ }T\nT{ MIN-INT 2 MIN-INT *\/ -> MIN-INT 2 MIN-INT T*\/ }T\n\n\\ F.6.1.0150 ,\nHERE 1 ,\nHERE 2 ,\nCONSTANT 2ND\nCONSTANT 1ST\nT{ 1ST 2ND U< -> }T \\ HERE MUST GROW WITH ALLOT\nT{ 1ST CELL+ -> 2ND }T \\ ... BY ONE CELL\nT{ 1ST 1 CELLS + -> 2ND }T\nT{ 1ST @ 2ND @ -> 1 2 }T\nT{ 5 1ST ! -> }T\nT{ 1ST @ 2ND @ -> 5 2 }T\nT{ 6 2ND ! -> }T\nT{ 1ST @ 2ND @ -> 5 6 }T\nT{ 1ST 2@ -> 6 5 }T\nT{ 2 1 1ST 2! -> }T\nT{ 1ST 2@ -> 2 1 }T\nT{ 1S 1ST ! 1ST @ -> 1S }T \\ CAN STORE CELL-WIDE VALUE\n\n\\ F.6.1.0130 +!\nT{ 0 1ST ! -> }T\nT{ 1 1ST +! -> }T\nT{ 1ST @ -> 1 }T\nT{ -1 1ST +! 1ST @ -> 0 }T\n\n\\ F.6.1.0890 CELLS\n: BITS ( X -- U )\n 0 SWAP BEGIN DUP WHILE\n DUP MSB AND IF >R 1+ R> THEN 2*\n REPEAT DROP ;\n( CELLS >= 1 AU, INTEGRAL MULTIPLE OF CHAR SIZE, >= 16 BITS )\nT{ 1 CELLS 1 < -> }T\nT{ 1 CELLS 1 CHARS MOD -> 0 }T\nT{ 1S BITS 10 < -> }T\n\n\\ F.6.1.0860 C,\nHERE 1 C,\nHERE 2 C,\nCONSTANT 2NDC\nCONSTANT 1STC\nT{ 1STC 2NDC U< -> }T \\ HERE MUST GROW WITH ALLOT\nT{ 1STC CHAR+ -> 2NDC }T \\ ... BY ONE CHAR\nT{ 1STC 1 CHARS + -> 2NDC }T\nT{ 1STC C@ 2NDC C@ -> 1 2 }T\nT{ 3 1STC C! -> }T\nT{ 1STC C@ 2NDC C@ -> 3 2 }T\nT{ 4 2NDC C! -> }T\nT{ 1STC C@ 2NDC C@ -> 3 4 }T\n\n\\ F.6.1.0898 CHARS\n( CHARACTERS >= 1 AU, <= SIZE OF CELL, >= 8 BITS )\nT{ 1 CHARS 1 < -> }T\nT{ 1 CHARS 1 CELLS > -> }T\n( TBD: HOW TO FIND NUMBER OF BITS? )\n\n\\ F.6.1.0705 ALIGN\nALIGN 1 ALLOT HERE ALIGN HERE 3 CELLS ALLOT\nCONSTANT A-ADDR CONSTANT UA-ADDR\nT{ UA-ADDR ALIGNED -> A-ADDR }T\nT{ 1 A-ADDR C! A-ADDR C@ -> 1 }T\nT{ 1234 A-ADDR ! A-ADDR @ -> 1234 }T\nT{ 123 456 A-ADDR 2! A-ADDR 2@ -> 123 456 }T\nT{ 2 A-ADDR CHAR+ C! A-ADDR CHAR+ C@ -> 2 }T\nT{ 3 A-ADDR CELL+ C! A-ADDR CELL+ C@ -> 3 }T\nT{ 1234 A-ADDR CELL+ ! A-ADDR CELL+ @ -> 1234 }T\nT{ 123 456 A-ADDR CELL+ 2! A-ADDR CELL+ 2@ -> 123 456 }T\n\n\\ F.6.1.0710 ALLOT\nHERE 1 ALLOT\nHERE\nCONSTANT 2NDA\nCONSTANT 1STA\nT{ 1STA 2NDA U< -> }T \\ HERE MUST GROW WITH ALLOT\nT{ 1STA 1+ -> 2NDA }T \\ ... BY ONE ADDRESS UNIT\n( MISSING TEST: NEGATIVE ALLOT )\n\n\\ F.6.1.0770 BL\nT{ BL -> 20 }T\n\n\\ F.6.1.0895 CHAR\nT{ CHAR X -> 58 }T\nT{ CHAR HELLO -> 48 }T\n\n\\ F.6.1.2520 [CHAR]\nT{ : GC1 [CHAR] X ; -> }T\nT{ : GC2 [CHAR] HELLO ; -> }T\nT{ GC1 -> 58 }T\nT{ GC2 -> 48 }T\n\n\\ F.6.1.2500 [\nT{ : GC3 [ GC1 ] LITERAL ; -> }T\nT{ GC3 -> 58 }T\n\n\\ F.6.1.2165 S\"\nT{ : GC4 S\" XY\" ; -> }T\nT{ GC4 SWAP DROP -> 2 }T\nT{ GC4 DROP DUP C@ SWAP CHAR+ C@ -> 58 59 }T\n: GC5 S\" A String\"2DROP ; \\ There is no space between the \" and 2DROP\nT{ GC5 -> }T\n\n\\ F.6.1.0070 '\nT{ : GT1 123 ; -> }T\nT{ ' GT1 EXECUTE -> 123 }T\n\n\\ F.6.1.2510 [']\nT{ : GT2 ['] GT1 ; IMMEDIATE -> }T\nT{ GT2 EXECUTE -> 123 }T\n\n\\ F.6.1.1550 FIND\nHERE 3 C, CHAR G C, CHAR T C, CHAR 1 C, CONSTANT GT1STRING\nHERE 3 C, CHAR G C, CHAR T C, CHAR 2 C, CONSTANT GT2STRING\nT{ GT1STRING FIND -> ' GT1 -1 }T\nT{ GT2STRING FIND -> ' GT2 1 }T\n( HOW TO SEARCH FOR NON-EXISTENT WORD? )\n\n\\ F.6.1.1780 LITERAL\nT{ : GT3 GT2 LITERAL ; -> }T\nT{ GT3 -> ' GT1 }T\n\n\\ F.6.1.0980 COUNT\nT{ GT1STRING COUNT -> GT1STRING CHAR+ 3 }T\n\n\\ F.6.1.2033 POSTPONE\nT{ : GT4 POSTPONE GT1 ; IMMEDIATE -> }T\nT{ : GT5 GT4 ; -> }T\nT{ GT5 -> 123 }T\nT{ : GT6 345 ; IMMEDIATE -> }T\nT{ : GT7 POSTPONE GT6 ; -> }T\nT{ GT7 -> 345 }T\n\n\\ F.6.1.2250 STATE\nT{ : GT8 STATE @ ; IMMEDIATE -> }T\nT{ GT8 -> 0 }T\nT{ : GT9 GT8 LITERAL ; -> }T\nT{ GT9 0= -> }T\n\n\\ F.6.1.1700 IF\nT{ : GI1 IF 123 THEN ; -> }T\nT{ : GI2 IF 123 ELSE 234 THEN ; -> }T\nT{ 0 GI1 -> }T\nT{ 1 GI1 -> 123 }T\nT{ -1 GI1 -> 123 }T\nT{ 0 GI2 -> 234 }T\nT{ 1 GI2 -> 123 }T\nT{ -1 GI1 -> 123 }T\n\\ Multiple ELSEs in an IF statement\n: melse IF 1 ELSE 2 ELSE 3 ELSE 4 ELSE 5 THEN ;\nT{ melse -> 2 4 }T\nT{ melse -> 1 3 5 }T\n\n\\ F.6.1.2430 WHILE\nT{ : GI3 BEGIN DUP 5 < WHILE DUP 1+ REPEAT ; -> }T\nT{ 0 GI3 -> 0 1 2 3 4 5 }T\nT{ 4 GI3 -> 4 5 }T\nT{ 5 GI3 -> 5 }T\nT{ 6 GI3 -> 6 }T\nT{ : GI5 BEGIN DUP 2 > WHILE\n DUP 5 < WHILE DUP 1+ REPEAT\n 123 ELSE 345 THEN ; -> }T\nT{ 1 GI5 -> 1 345 }T\nT{ 2 GI5 -> 2 345 }T\nT{ 3 GI5 -> 3 4 5 123 }T\nT{ 4 GI5 -> 4 5 123 }T\nT{ 5 GI5 -> 5 123 }T\n\n\\ F.6.1.2390 UNTIL\nT{ : GI4 BEGIN DUP 1+ DUP 5 > UNTIL ; -> }T\nT{ 3 GI4 -> 3 4 5 6 }T\nT{ 5 GI4 -> 5 6 }T\nT{ 6 GI4 -> 6 7 }T\n\n\\ F.6.1.2120 RECURSE\nT{ : GI6 ( N -- 0,1,..N )\n DUP IF DUP >R 1- RECURSE R> THEN ; -> }T\nT{ 0 GI6 -> 0 }T\nT{ 1 GI6 -> 0 1 }T\nT{ 2 GI6 -> 0 1 2 }T\nT{ 3 GI6 -> 0 1 2 3 }T\nT{ 4 GI6 -> 0 1 2 3 4 }T\n\nDECIMAL\n\n\\ F.6.1.1800 LOOP\nT{ : GD1 DO I LOOP ; -> }T\nT{ 4 1 GD1 -> 1 2 3 }T\nT{ 2 -1 GD1 -> -1 0 1 }T\nT{ MID-UINT+1 MID-UINT GD1 -> MID-UINT }T\n\n\\ F.6.1.0140 +LOOP\nT{ : GD2 DO I -1 +LOOP ; -> }T\nT{ 1 4 GD2 -> 4 3 2 1 }T\nT{ -1 2 GD2 -> 2 1 0 -1 }T\nT{ MID-UINT MID-UINT+1 GD2 -> MID-UINT+1 MID-UINT }T\nVARIABLE gditerations\nVARIABLE gdincrement\n\n: gd7 ( limit start increment -- )\n gdincrement !\n 0 gditerations !\n DO\n 1 gditerations +!\n I\n gditerations @ 6 = IF LEAVE THEN\n gdincrement @\n +LOOP gditerations @\n;\n\nT{ 4 4 -1 gd7 -> 4 1 }T\nT{ 1 4 -1 gd7 -> 4 3 2 1 4 }T\nT{ 4 1 -1 gd7 -> 1 0 -1 -2 -3 -4 6 }T\nT{ 4 1 0 gd7 -> 1 1 1 1 1 1 6 }T\nT{ 0 0 0 gd7 -> 0 0 0 0 0 0 6 }T\nT{ 1 4 0 gd7 -> 4 4 4 4 4 4 6 }T\nT{ 1 4 1 gd7 -> 4 5 6 7 8 9 6 }T\nT{ 4 1 1 gd7 -> 1 2 3 3 }T\nT{ 4 4 1 gd7 -> 4 5 6 7 8 9 6 }T\nT{ 2 -1 -1 gd7 -> -1 -2 -3 -4 -5 -6 6 }T\nT{ -1 2 -1 gd7 -> 2 1 0 -1 4 }T\nT{ 2 -1 0 gd7 -> -1 -1 -1 -1 -1 -1 6 }T\nT{ -1 2 0 gd7 -> 2 2 2 2 2 2 6 }T\nT{ -1 2 1 gd7 -> 2 3 4 5 6 7 6 }T\nT{ 2 -1 1 gd7 -> -1 0 1 3 }T\nT{ -20 30 -10 gd7 -> 30 20 10 0 -10 -20 6 }T\nT{ -20 31 -10 gd7 -> 31 21 11 1 -9 -19 6 }T\nT{ -20 29 -10 gd7 -> 29 19 9 -1 -11 5 }T\n\n\\ With large and small increments\n\nMAX-UINT 8 RSHIFT 1+ CONSTANT ustep\nustep NEGATE CONSTANT -ustep\nMAX-INT 7 RSHIFT 1+ CONSTANT step\nstep NEGATE CONSTANT -step\n\nVARIABLE bump\n\nT{ : gd8 bump ! DO 1+ bump @ +LOOP ; -> }T\n\nT{ 0 MAX-UINT 0 ustep gd8 -> 256 }T\nT{ 0 0 MAX-UINT -ustep gd8 -> 256 }T\nT{ 0 MAX-INT MIN-INT step gd8 -> 256 }T\nT{ 0 MIN-INT MAX-INT -step gd8 -> 256 }T\n\n\\ F.6.1.1730 J\nT{ : GD3 DO 1 0 DO J LOOP LOOP ; -> }T\nT{ 4 1 GD3 -> 1 2 3 }T\nT{ 2 -1 GD3 -> -1 0 1 }T\nT{ MID-UINT+1 MID-UINT GD3 -> MID-UINT }T\nT{ : GD4 DO 1 0 DO J LOOP -1 +LOOP ; -> }T\nT{ 1 4 GD4 -> 4 3 2 1 }T\nT{ -1 2 GD4 -> 2 1 0 -1 }T\nT{ MID-UINT MID-UINT+1 GD4 -> MID-UINT+1 MID-UINT }T\n\n\\ F.6.1.1760 LEAVE\nT{ : GD5 123 SWAP 0 DO\n I 4 > IF DROP 234 LEAVE THEN\n LOOP ; -> }T\nT{ 1 GD5 -> 123 }T\nT{ 5 GD5 -> 123 }T\nT{ 6 GD5 -> 234 }T\n\n\\ F.6.1.2380 UNLOOP\nT{ : GD6 ( PAT: {0 0},{0 0}{1 0}{1 1},{0 0}{1 0}{1 1}{2 0}{2 1}{2 2} )\n 0 SWAP 0 DO\n I 1+ 0 DO\n I J + 3 = IF I UNLOOP I UNLOOP EXIT THEN 1+\n LOOP\n LOOP ; -> }T\nT{ 1 GD6 -> 1 }T\nT{ 2 GD6 -> 3 }T\nT{ 3 GD6 -> 4 1 2 }T\n\n\\ F.6.1.0450 :\nT{ : NOP : POSTPONE ; ; -> }T\nT{ NOP NOP1 NOP NOP2 -> }T\nT{ NOP1 -> }T\nT{ NOP2 -> }T\n\\ The following tests the dictionary search order:\nT{ : GDX 123 ; : GDX GDX 234 ; -> }T\nT{ GDX -> 123 234 }T\n\n\\ F.6.1.0950 CONSTANT\nT{ 123 CONSTANT X123 -> }T\nT{ X123 -> 123 }T\nT{ : EQU CONSTANT ; -> }T\nT{ X123 EQU Y123 -> }T\nT{ Y123 -> 123 }T\n\n\\ F.6.1.2410 VARIABLE\nT{ VARIABLE V1 -> }T\nT{ 123 V1 ! -> }T\nT{ V1 @ -> 123 }T\n\n\\ F.6.1.1250 DOES>\nT{ : DOES1 DOES> @ 1 + ; -> }T\nT{ : DOES2 DOES> @ 2 + ; -> }T\nT{ CREATE CR1 -> }T\nT{ CR1 -> HERE }T\nT{ 1 , -> }T\nT{ CR1 @ -> 1 }T\nT{ DOES1 -> }T\nT{ CR1 -> 2 }T\nT{ DOES2 -> }T\nT{ CR1 -> 3 }T\nT{ : WEIRD: CREATE DOES> 1 + DOES> 2 + ; -> }T\nT{ WEIRD: W1 -> }T\nT{ ' W1 >BODY -> HERE }T\nT{ W1 -> HERE 1 + }T\nT{ W1 -> HERE 2 + }T\n\n\\ F.6.1.0550 >BODY\nT{ CREATE CR0 -> }T\nT{ ' CR0 >BODY -> HERE }T\n\n\\ F.6.1.1360 EVALUATE\n: GE1 S\" 123\" ; IMMEDIATE\n: GE2 S\" 123 1+\" ; IMMEDIATE\n: GE3 S\" : GE4 345 ;\" ;\n: GE5 EVALUATE ; IMMEDIATE\nT{ GE1 EVALUATE -> 123 }T ( TEST EVALUATE IN INTERP. STATE )\nT{ GE2 EVALUATE -> 124 }T\nT{ GE3 EVALUATE -> }T\nT{ GE4 -> 345 }T\n\nT{ : GE6 GE1 GE5 ; -> }T ( TEST EVALUATE IN COMPILE STATE )\nT{ GE6 -> 123 }T\nT{ : GE7 GE2 GE5 ; -> }T\nT{ GE7 -> 124 }T\n\n\\ F.6.1.2216 SOURCE\n: GS1 S\" SOURCE\" 2DUP EVALUATE >R SWAP >R = R> R> = ;\nT{ GS1 -> }T\n: GS4 SOURCE >IN ! DROP ;\nT{ GS4 123 456\n -> }T\n\n\\ F.6.1.0560 >IN\nVARIABLE SCANS\n: RESCAN? -1 SCANS +! SCANS @ IF 0 >IN ! THEN ;\nT{ 2 SCANS !\n345 RESCAN?\n-> 345 345 }T\n\n: GS2 5 SCANS ! S\" 123 RESCAN?\" EVALUATE ;\nT{ GS2 -> 123 123 123 123 123 }T\n\n\\ These tests must start on a new line\nDECIMAL\nT{ 123456 DEPTH OVER 9 < 35 AND + 3 + >IN !\n-> 123456 23456 3456 456 56 6 }T\nT{ 14145 8115 ?DUP 0= 34 AND >IN +! TUCK MOD 14 >IN ! GCD calculation\n-> 15 }T\nHEX\n\n\\ F.6.1.2450 WORD\n: GS3 WORD COUNT SWAP C@ ;\nT{ BL GS3 HELLO -> 5 CHAR H }T\nT{ CHAR \" GS3 GOODBYE\" -> 7 CHAR G }T\nT{ BL GS3\n DROP -> 0 }T \\ Blank lines return zero-length strings\n\n: S= \\ ( ADDR1 C1 ADDR2 C2 -- T\/F ) Compare two strings.\n >R SWAP R@ = IF \\ Make sure strings have same length\n R> ?DUP IF \\ If non-empty strings\n 0 DO\n OVER C@ OVER C@ - IF 2DROP UNLOOP EXIT THEN\n SWAP CHAR+ SWAP CHAR+\n LOOP\n THEN\n 2DROP \\ If we get here, strings match\n ELSE\n R> DROP 2DROP \\ Lengths mismatch\n THEN ;\n\n\\ F.6.1.1670 HOLD\n: GP1 <# 41 HOLD 42 HOLD 0 0 #> S\" BA\" S= ;\nT{ GP1 -> }T\n\n\\ F.6.1.2210 SIGN\n: GP2 <# -1 SIGN 0 SIGN -1 SIGN 0 0 #> S\" --\" S= ;\nT{ GP2 -> }T\n\n\\ F.6.1.0030 #\n: GP3 <# 1 0 # # #> S\" 01\" S= ;\nT{ GP3 -> }T\n\n24 CONSTANT MAX-BASE \\ BASE 2 ... 36\n: COUNT-BITS\n 0 0 INVERT BEGIN DUP WHILE >R 1+ R> 2* REPEAT DROP ;\nCOUNT-BITS 2* CONSTANT #BITS-UD \\ NUMBER OF BITS IN UD\n\n\\ F.6.1.0050 #S\n: GP4 <# 1 0 #S #> S\" 1\" S= ;\nT{ GP4 -> }T\n: GP5\n BASE @ \n MAX-BASE 1+ 2 DO \\ FOR EACH POSSIBLE BASE\n I BASE ! \\ TBD: ASSUMES BASE WORKS\n I 0 <# #S #> S\" 10\" S= AND\n LOOP\n SWAP BASE ! ;\nT{ GP5 -> }T\n\n: GP6\n BASE @ >R 2 BASE !\n MAX-UINT MAX-UINT <# #S #> \\ MAXIMUM UD TO BINARY\n R> BASE ! \\ S: C-ADDR U\n DUP #BITS-UD = SWAP\n 0 DO \\ S: C-ADDR FLAG\n OVER C@ [CHAR] 1 = AND \\ ALL ONES\n >R CHAR+ R>\n LOOP SWAP DROP ;\nT{ GP6 -> }T\n\n: GP7\n BASE @ >R MAX-BASE BASE !\n \n A 0 DO\n I 0 <# #S #>\n 1 = SWAP C@ I 30 + = AND AND\n LOOP\n MAX-BASE A DO\n I 0 <# #S #>\n 1 = SWAP C@ 41 I A - + = AND AND\n LOOP\n R> BASE ! ;\nT{ GP7 -> }T\n\n\\ F.6.1.0570 >NUMBER\nCREATE GN-BUF 0 C,\n: GN-STRING GN-BUF 1 ;\n: GN-CONSUMED GN-BUF CHAR+ 0 ;\n: GN' [CHAR] ' WORD CHAR+ C@ GN-BUF C! GN-STRING ;\nT{ 0 0 GN' 0' >NUMBER -> 0 0 GN-CONSUMED }T\nT{ 0 0 GN' 1' >NUMBER -> 1 0 GN-CONSUMED }T\nT{ 1 0 GN' 1' >NUMBER -> BASE @ 1+ 0 GN-CONSUMED }T\n\\ FOLLOWING SHOULD FAIL TO CONVERT\nT{ 0 0 GN' -' >NUMBER -> 0 0 GN-STRING }T\nT{ 0 0 GN' +' >NUMBER -> 0 0 GN-STRING }T\nT{ 0 0 GN' .' >NUMBER -> 0 0 GN-STRING }T\n\n: >NUMBER-BASED\n BASE @ >R BASE ! >NUMBER R> BASE ! ;\n\nT{ 0 0 GN' 2' 10 >NUMBER-BASED -> 2 0 GN-CONSUMED }T\nT{ 0 0 GN' 2' 2 >NUMBER-BASED -> 0 0 GN-STRING }T\nT{ 0 0 GN' F' 10 >NUMBER-BASED -> F 0 GN-CONSUMED }T\nT{ 0 0 GN' G' 10 >NUMBER-BASED -> 0 0 GN-STRING }T\nT{ 0 0 GN' G' MAX-BASE >NUMBER-BASED -> 10 0 GN-CONSUMED }T\nT{ 0 0 GN' Z' MAX-BASE >NUMBER-BASED -> 23 0 GN-CONSUMED }T\n\n: GN1 ( UD BASE -- UD' LEN )\n \\ UD SHOULD EQUAL UD' AND LEN SHOULD BE ZERO.\n BASE @ >R BASE !\n <# #S #>\n 0 0 2SWAP >NUMBER SWAP DROP \\ RETURN LENGTH ONLY\n R> BASE ! ;\n\nT{ 0 0 2 GN1 -> 0 0 0 }T\nT{ MAX-UINT 0 2 GN1 -> MAX-UINT 0 0 }T\nT{ MAX-UINT DUP 2 GN1 -> MAX-UINT DUP 0 }T\nT{ 0 0 MAX-BASE GN1 -> 0 0 0 }T\nT{ MAX-UINT 0 MAX-BASE GN1 -> MAX-UINT 0 0 }T\nT{ MAX-UINT DUP MAX-BASE GN1 -> MAX-UINT DUP 0 }T\n\n\\ F.6.1.0750 BASE\n: GN2 \\ ( -- 16 10 )\n BASE @ >R HEX BASE @ DECIMAL BASE @ R> BASE ! ;\nT{ GN2 -> 10 A }T\n\nCREATE FBUF 00 C, 00 C, 00 C,\nCREATE SBUF 12 C, 34 C, 56 C,\n: SEEBUF FBUF C@ FBUF CHAR+ C@ FBUF CHAR+ CHAR+ C@ ;\n\n\\ F.6.1.1540 FILL\nT{ FBUF 0 20 FILL -> }T\nT{ SEEBUF -> 00 00 00 }T\nT{ FBUF 1 20 FILL -> }T\nT{ SEEBUF -> 20 00 00 }T\n\nT{ FBUF 3 20 FILL -> }T\nT{ SEEBUF -> 20 20 20 }T\n\n\\ F.6.1.1900 MOVE\nT{ FBUF FBUF 3 CHARS MOVE -> }T \\ BIZARRE SPECIAL CASE\nT{ SEEBUF -> 20 20 20 }T\nT{ SBUF FBUF 0 CHARS MOVE -> }T\nT{ SEEBUF -> 20 20 20 }T\n\nT{ SBUF FBUF 1 CHARS MOVE -> }T\nT{ SEEBUF -> 12 20 20 }T\n\nT{ SBUF FBUF 3 CHARS MOVE -> }T\nT{ SEEBUF -> 12 34 56 }T\n\nT{ FBUF FBUF CHAR+ 2 CHARS MOVE -> }T\nT{ SEEBUF -> 12 12 34 }T\n\nT{ FBUF CHAR+ FBUF 2 CHARS MOVE -> }T\nT{ SEEBUF -> 12 34 34 }T\n\n\\ F.6.1.1320 EMIT\n: OUTPUT-TEST\n .\" YOU SHOULD SEE THE STANDARD GRAPHIC CHARACTERS:\" CR\n 41 BL DO I EMIT LOOP CR\n 61 41 DO I EMIT LOOP CR\n 7F 61 DO I EMIT LOOP CR\n .\" YOU SHOULD SEE 0-9 SEPARATED BY A SPACE:\" CR\n 9 1+ 0 DO I . LOOP CR\n .\" YOU SHOULD SEE 0-9 (WITH NO SPACES):\" CR\n [CHAR] 9 1+ [CHAR] 0 DO I 0 SPACES EMIT LOOP CR\n .\" YOU SHOULD SEE A-G SEPARATED BY A SPACE:\" CR\n [CHAR] G 1+ [CHAR] A DO I EMIT SPACE LOOP CR\n .\" YOU SHOULD SEE 0-5 SEPARATED BY TWO SPACES:\" CR\n 5 1+ 0 DO I [CHAR] 0 + EMIT 2 SPACES LOOP CR\n .\" YOU SHOULD SEE TWO SEPARATE LINES:\" CR\n S\" LINE 1\" TYPE CR S\" LINE 2\" TYPE CR\n .\" YOU SHOULD SEE THE NUMBER RANGES OF SIGNED AND UNSIGNED NUMBERS:\" CR\n .\" SIGNED: \" MIN-INT . MAX-INT . CR\n .\" UNSIGNED: \" 0 U. MAX-UINT U. CR\n;\nT{ OUTPUT-TEST -> }T\n\n\\ F.6.1.0695 ACCEPT\nCREATE ABUF 80 CHARS ALLOT\n: ACCEPT-TEST\n CR .\" PLEASE TYPE UP TO 80 CHARACTERS:\" CR\n ABUF 80 ACCEPT\n CR .\" RECEIVED: \" [CHAR] \" EMIT\n ABUF SWAP TYPE [CHAR] \" EMIT CR\n;\n\\ SKIP: T{ ACCEPT-TEST -> }T\n\n\\ F.6.1.0450 :\nT{ : NOP : POSTPONE ; ; -> }T\nT{ NOP NOP1 NOP NOP2 -> }T\nT{ NOP1 -> }T\nT{ NOP2 -> }T\n\\ The following tests the dictionary search order:\nT{ : GDX 123 ; : GDX GDX 234 ; -> }T\nT{ GDX -> 123 234 }T\n\n.\" Done\" CR\nBYE\n","old_contents":"HEX\n\nT{ -> }T ( Start with a clean slate )\n( Test if any bits are set; Answer in base 1 )\nT{ : BITSSET? IF 0 0 ELSE 0 THEN ; -> }T\nT{ 0 BITSSET? -> 0 }T ( Zero is all bits clear )\n\\ T{ 1 BITSSET? -> 0 0 }T ( Other numbers have at least one bit )\n\\ T{ -1 BITSSET? -> 0 0 }T\n\n\\ F.6.1.0720 AND\nT{ 0 0 AND -> 0 }T\nT{ 0 1 AND -> 0 }T\nT{ 1 0 AND -> 0 }T\nT{ 1 1 AND -> 1 }T\nT{ 0 INVERT 1 AND -> 1 }T\nT{ 1 INVERT 1 AND -> 0 }T\n\n\\ Define 0S and 1S\n0 CONSTANT 0S\n0S INVERT CONSTANT 1S\n\n\\ F.6.1.1720 INVERT\nT{ 0S INVERT -> 1S }T\nT{ 1S INVERT -> 0S }T\n\n\\ F.6.1.0950 CONSTANT\nT{ 123 CONSTANT X123 -> }T\nT{ X123 -> 123 }T\nT{ : EQU CONSTANT ; -> }T\nT{ X123 EQU Y123 -> }T\nT{ Y123 -> 123 }T\n\n\\ F.6.1.0720 AND (continued)\nT{ 0S 0S AND -> 0S }T\nT{ 0S 1S AND -> 0S }T\nT{ 1S 0S AND -> 0S }T\nT{ 1S 1S AND -> 1S }T\n\n\\ F.6.1.1980 OR\nT{ 0S 0S OR -> 0S }T\nT{ 0S 1S OR -> 1S }T\nT{ 1S 0S OR -> 1S }T\nT{ 1S 1S OR -> 1S }T\n\n\\ F.6.1.2490 XOR\nT{ 0S 0S XOR -> 0S }T\nT{ 0S 1S XOR -> 1S }T\nT{ 1S 0S XOR -> 1S }T\nT{ 1S 1S XOR -> 0S }T\n\n1S 1 RSHIFT INVERT CONSTANT MSB\nT{ MSB BITSSET? -> 0 0 }T\n\n\\ F.6.1.0320 2*\nT{ 0S 2* -> 0S }T\nT{ 1 2* -> 2 }T\nT{ 4000 2* -> 8000 }T\nT{ 1S 2* 1 XOR -> 1S }T\nT{ MSB 2* -> 0S }T\n\n\\ F.6.1.0330 2\/\nT{ 0S 2\/ -> 0S }T\nT{ 1 2\/ -> 0 }T\nT{ 4000 2\/ -> 2000 }T\nT{ 1S 2\/ -> 1S }T \\ MSB PROPOGATED\nT{ 1S 1 XOR 2\/ -> 1S }T\nT{ MSB 2\/ MSB AND -> MSB }T\n\n\\ F.6.1.1805 LSHIFT\nT{ 1 0 LSHIFT -> 1 }T\nT{ 1 1 LSHIFT -> 2 }T\nT{ 1 2 LSHIFT -> 4 }T\nT{ 1 F LSHIFT -> 8000 }T \\ BIGGEST GUARANTEED SHIFT\nT{ 1S 1 LSHIFT 1 XOR -> 1S }T\nT{ MSB 1 LSHIFT -> 0 }T\n\n\\ F.6.1.2162 RSHIFT\nT{ 1 0 RSHIFT -> 1 }T\nT{ 1 1 RSHIFT -> 0 }T\nT{ 2 1 RSHIFT -> 1 }T\nT{ 4 2 RSHIFT -> 1 }T\nT{ 8000 F RSHIFT -> 1 }T \\ Biggest\nT{ MSB 1 RSHIFT MSB AND -> 0 }T \\ RSHIFT zero fills MSBs\nT{ MSB 1 RSHIFT 2* -> MSB }T\n\nDECIMAL\nT{ #1289 -> 1289 }T\n\\ SKIP: T{ #12346789. -> 12346789. }T\nT{ #-1289 -> -1289 }T\n\\ SKIP: T{ #-12346789. -> -12346789. }T\nT{ $12eF -> 4847 }T\n\\ SKIP: T{ $12aBcDeF. -> 313249263. }T\nT{ $-12eF -> -4847 }T\n\\ SKIP: T{ $-12AbCdEf. -> -313249263. }T\nT{ %10010110 -> 150 }T\n\\ SKIP: T{ %10010110. -> 150. }T\nT{ %-10010110 -> -150 }T\n\\ SKIP: T{ %-10010110. -> -150. }T\n\\ TODO: T{ 'z' -> 122 }T\nHEX\n\n0 INVERT CONSTANT MAX-UINT\n0 INVERT 1 RSHIFT CONSTANT MAX-INT\n0 INVERT 1 RSHIFT INVERT CONSTANT MIN-INT\n0 INVERT 1 RSHIFT CONSTANT MID-UINT\n0 INVERT 1 RSHIFT INVERT CONSTANT MID-UINT+1\n\n0S CONSTANT \n1S CONSTANT \n\n\\ F.6.1.0270 0=\nT{ 0 0= -> }T\nT{ 1 0= -> }T\nT{ 2 0= -> }T\nT{ -1 0= -> }T\nT{ MAX-UINT 0= -> }T\nT{ MIN-INT 0= -> }T\nT{ MAX-INT 0= -> }T\n\n\\ F.6.1.0530 =\nT{ 0 0 = -> }T\nT{ 1 1 = -> }T\nT{ -1 -1 = -> }T\nT{ 1 0 = -> }T\nT{ -1 0 = -> }T\nT{ 0 1 = -> }T\nT{ 0 -1 = -> }T\n\n\\ F.6.1.0250 0<\nT{ 0 0< -> }T\nT{ -1 0< -> }T\nT{ MIN-INT 0< -> }T\nT{ 1 0< -> }T\nT{ MAX-INT 0< -> }T\n\n\\ F.6.1.0480 <\nT{ 0 1 < -> }T\nT{ 1 2 < -> }T\nT{ -1 0 < -> }T\nT{ -1 1 < -> }T\nT{ MIN-INT 0 < -> }T\nT{ MIN-INT MAX-INT < -> }T\nT{ 0 MAX-INT < -> }T\nT{ 0 0 < -> }T\nT{ 1 1 < -> }T\nT{ 1 0 < -> }T\nT{ 2 1 < -> }T\nT{ 0 -1 < -> }T\nT{ 1 -1 < -> }T\nT{ 0 MIN-INT < -> }T\nT{ MAX-INT MIN-INT < -> }T\nT{ MAX-INT 0 < -> }T\n\n\\ F.6.1.0540 >\nT{ 0 1 > -> }T\nT{ 1 2 > -> }T\nT{ -1 0 > -> }T\nT{ -1 1 > -> }T\nT{ MIN-INT 0 > -> }T\nT{ MIN-INT MAX-INT > -> }T\nT{ 0 MAX-INT > -> }T\nT{ 0 0 > -> }T\nT{ 1 1 > -> }T\nT{ 1 0 > -> }T\nT{ 2 1 > -> }T\nT{ 0 -1 > -> }T\nT{ 1 -1 > -> }T\nT{ 0 MIN-INT > -> }T\nT{ MAX-INT MIN-INT > -> }T\nT{ MAX-INT 0 > -> }T\n\n\\ F.6.1.2340 U<\nT{ 0 1 U< -> }T\nT{ 1 2 U< -> }T\nT{ 0 MID-UINT U< -> }T\nT{ 0 MAX-UINT U< -> }T\nT{ MID-UINT MAX-UINT U< -> }T\nT{ 0 0 U< -> }T\nT{ 1 1 U< -> }T\nT{ 1 0 U< -> }T\nT{ 2 1 U< -> }T\nT{ MID-UINT 0 U< -> }T\nT{ MAX-UINT 0 U< -> }T\nT{ MAX-UINT MID-UINT U< -> }T\n\n\\ F.6.1.1880 MIN\nT{ 0 1 MIN -> 0 }T\nT{ 1 2 MIN -> 1 }T\nT{ -1 0 MIN -> -1 }T\nT{ -1 1 MIN -> -1 }T\nT{ MIN-INT 0 MIN -> MIN-INT }T\nT{ MIN-INT MAX-INT MIN -> MIN-INT }T\nT{ 0 MAX-INT MIN -> 0 }T\nT{ 0 0 MIN -> 0 }T\nT{ 1 1 MIN -> 1 }T\nT{ 1 0 MIN -> 0 }T\nT{ 2 1 MIN -> 1 }T\nT{ 0 -1 MIN -> -1 }T\nT{ 1 -1 MIN -> -1 }T\nT{ 0 MIN-INT MIN -> MIN-INT }T\nT{ MAX-INT MIN-INT MIN -> MIN-INT }T\nT{ MAX-INT 0 MIN -> 0 }T\n\n\\ F.6.1.1870 MAX\nT{ 0 1 MAX -> 1 }T\nT{ 1 2 MAX -> 2 }T\nT{ -1 0 MAX -> 0 }T\nT{ -1 1 MAX -> 1 }T\nT{ MIN-INT 0 MAX -> 0 }T\nT{ MIN-INT MAX-INT MAX -> MAX-INT }T\nT{ 0 MAX-INT MAX -> MAX-INT }T\nT{ 0 0 MAX -> 0 }T\nT{ 1 1 MAX -> 1 }T\nT{ 1 0 MAX -> 1 }T\nT{ 2 1 MAX -> 2 }T\nT{ 0 -1 MAX -> 0 }T\nT{ 1 -1 MAX -> 1 }T\nT{ 0 MIN-INT MAX -> 0 }T\nT{ MAX-INT MIN-INT MAX -> MAX-INT }T\nT{ MAX-INT 0 MAX -> MAX-INT }T\n\n\\ F.6.1.1260 DROP\nT{ 1 2 DROP -> 1 }T\nT{ 0 DROP -> }T\n\n\\ F.6.1.1290 DUP\nT{ 1 DUP -> 1 1 }T\n\n\\ F.6.1.1990 OVER\nT{ 1 2 OVER -> 1 2 1 }T\n\n\\ F.6.1.2160 ROT\nT{ 1 2 3 ROT -> 2 3 1 }T\n\n\\ F.6.1.2260 SWAP\nT{ 1 2 SWAP -> 2 1 }T\n\n\\ F.6.1.0370 2DROP\nT{ 1 2 2DROP -> }T\n\n\\ F.6.1.0380 2DUP\nT{ 1 2 2DUP -> 1 2 1 2 }T\n\n\\ F.6.1.0400 2OVER\nT{ 1 2 3 4 2OVER -> 1 2 3 4 1 2 }T\n\n\\ F.6.1.0430 2SWAP\nT{ 1 2 3 4 2SWAP -> 3 4 1 2 }T\n\n\\ F.6.1.0630 ?DUP\nT{ -1 ?DUP -> -1 -1 }T\nT{ 0 ?DUP -> 0 }T\nT{ 1 ?DUP -> 1 1 }T\n\n\\ F.6.1.1200 DEPTH\nT{ 0 1 DEPTH -> 0 1 2 }T\nT{ 0 DEPTH -> 0 1 }T\nT{ DEPTH -> 0 }T\n\n\\ F.6.1.0580 >R\nT{ : GR1 >R R> ; -> }T\nT{ : GR2 >R R@ R> DROP ; -> }T\nT{ 123 GR1 -> 123 }T\nT{ 123 GR2 -> 123 }T\nT{ 1S GR1 -> 1S }T ( Return stack holds cells )\n\n\\ F.6.1.0120 +\nT{ 0 5 + -> 5 }T\nT{ 5 0 + -> 5 }T\nT{ 0 -5 + -> -5 }T\nT{ -5 0 + -> -5 }T\nT{ 1 2 + -> 3 }T\nT{ 1 -2 + -> -1 }T\nT{ -1 2 + -> 1 }T\nT{ -1 -2 + -> -3 }T\nT{ -1 1 + -> 0 }T\nT{ MID-UINT 1 + -> MID-UINT+1 }T\n\n\\ F.6.1.0160 -\nT{ 0 5 - -> -5 }T\nT{ 5 0 - -> 5 }T\nT{ 0 -5 - -> 5 }T\nT{ -5 0 - -> -5 }T\nT{ 1 2 - -> -1 }T\nT{ 1 -2 - -> 3 }T\nT{ -1 2 - -> -3 }T\nT{ -1 -2 - -> 1 }T\nT{ 0 1 - -> -1 }T\nT{ MID-UINT+1 1 - -> MID-UINT }T\n\n\\ F.6.1.0290 1+\nT{ 0 1+ -> 1 }T\nT{ -1 1+ -> 0 }T\nT{ 1 1+ -> 2 }T\nT{ MID-UINT 1+ -> MID-UINT+1 }T\n\n\\ F.6.1.0300 1-\nT{ 2 1- -> 1 }T\nT{ 1 1- -> 0 }T\nT{ 0 1- -> -1 }T\nT{ MID-UINT+1 1- -> MID-UINT }T\n\n\\ F.6.1.0690 ABS\nT{ 0 ABS -> 0 }T\nT{ 1 ABS -> 1 }T\nT{ -1 ABS -> 1 }T\nT{ MIN-INT ABS -> MID-UINT+1 }T\n\n\\ F.6.1.1910 NEGATE\nT{ 0 NEGATE -> 0 }T\nT{ 1 NEGATE -> -1 }T\nT{ -1 NEGATE -> 1 }T\nT{ 2 NEGATE -> -2 }T\nT{ -2 NEGATE -> 2 }T\n\n\\ F.6.1.2170 S>D\nT{ 0 S>D -> 0 0 }T\nT{ 1 S>D -> 1 0 }T\nT{ 2 S>D -> 2 0 }T\nT{ -1 S>D -> -1 -1 }T\nT{ -2 S>D -> -2 -1 }T\nT{ MIN-INT S>D -> MIN-INT -1 }T\nT{ MAX-INT S>D -> MAX-INT 0 }T\n\n\\ F.6.1.0090 *\nT{ 0 0 * -> 0 }T \\ TEST IDENTITIE\\S\nT{ 0 1 * -> 0 }T\nT{ 1 0 * -> 0 }T\nT{ 1 2 * -> 2 }T\nT{ 2 1 * -> 2 }T\nT{ 3 3 * -> 9 }T\nT{ -3 3 * -> -9 }T\nT{ 3 -3 * -> -9 }T\nT{ -3 -3 * -> 9 }T\nT{ MID-UINT+1 1 RSHIFT 2 * -> MID-UINT+1 }T\nT{ MID-UINT+1 2 RSHIFT 4 * -> MID-UINT+1 }T\nT{ MID-UINT+1 1 RSHIFT MID-UINT+1 OR 2 * -> MID-UINT+1 }T\n\n\\ F.6.1.1810 M*\nT{ 0 0 M* -> 0 S>D }T\nT{ 0 1 M* -> 0 S>D }T\nT{ 1 0 M* -> 0 S>D }T\nT{ 1 2 M* -> 2 S>D }T\nT{ 2 1 M* -> 2 S>D }T\nT{ 3 3 M* -> 9 S>D }T\nT{ -3 3 M* -> -9 S>D }T\nT{ 3 -3 M* -> -9 S>D }T\nT{ -3 -3 M* -> 9 S>D }T\nT{ 0 MIN-INT M* -> 0 S>D }T\nT{ 1 MIN-INT M* -> MIN-INT S>D }T\nT{ 2 MIN-INT M* -> 0 1S }T\nT{ 0 MAX-INT M* -> 0 S>D }T\nT{ 1 MAX-INT M* -> MAX-INT S>D }T\nT{ 2 MAX-INT M* -> MAX-INT 1 LSHIFT 0 }T\nT{ MIN-INT MIN-INT M* -> 0 MSB 1 RSHIFT }T\nT{ MAX-INT MIN-INT M* -> MSB MSB 2\/ }T\nT{ MAX-INT MAX-INT M* -> 1 MSB 2\/ INVERT }T\n\n\\ F.6.1.2360 UM*\nT{ 0 0 UM* -> 0 0 }T\nT{ 0 1 UM* -> 0 0 }T\nT{ 1 0 UM* -> 0 0 }T\nT{ 1 2 UM* -> 2 0 }T\nT{ 2 1 UM* -> 2 0 }T\nT{ 3 3 UM* -> 9 0 }T\nT{ MID-UINT+1 1 RSHIFT 2 UM* -> MID-UINT+1 0 }T\nT{ MID-UINT+1 2 UM* -> 0 1 }T\nT{ MID-UINT+1 4 UM* -> 0 2 }T\nT{ 1S 2 UM* -> 1S 1 LSHIFT 1 }T\nT{ MAX-UINT MAX-UINT UM* -> 1 1 INVERT }T\n\n\\ F.6.1.1561 FM\/MOD\nT{ 0 S>D 1 FM\/MOD -> 0 0 }T\nT{ 1 S>D 1 FM\/MOD -> 0 1 }T\nT{ 2 S>D 1 FM\/MOD -> 0 2 }T\nT{ -1 S>D 1 FM\/MOD -> 0 -1 }T\nT{ -2 S>D 1 FM\/MOD -> 0 -2 }T\nT{ 0 S>D -1 FM\/MOD -> 0 0 }T\nT{ 1 S>D -1 FM\/MOD -> 0 -1 }T\nT{ 2 S>D -1 FM\/MOD -> 0 -2 }T\nT{ -1 S>D -1 FM\/MOD -> 0 1 }T\nT{ -2 S>D -1 FM\/MOD -> 0 2 }T\nT{ 2 S>D 2 FM\/MOD -> 0 1 }T\nT{ -1 S>D -1 FM\/MOD -> 0 1 }T\nT{ -2 S>D -2 FM\/MOD -> 0 1 }T\nT{ 7 S>D 3 FM\/MOD -> 1 2 }T\nT{ 7 S>D -3 FM\/MOD -> -2 -3 }T\nT{ -7 S>D 3 FM\/MOD -> 2 -3 }T\nT{ -7 S>D -3 FM\/MOD -> -1 2 }T\nT{ MAX-INT S>D 1 FM\/MOD -> 0 MAX-INT }T\nT{ MIN-INT S>D 1 FM\/MOD -> 0 MIN-INT }T\nT{ MAX-INT S>D MAX-INT FM\/MOD -> 0 1 }T\nT{ MIN-INT S>D MIN-INT FM\/MOD -> 0 1 }T\nT{ 1S 1 4 FM\/MOD -> 3 MAX-INT }T\nT{ 1 MIN-INT M* 1 FM\/MOD -> 0 MIN-INT }T\nT{ 1 MIN-INT M* MIN-INT FM\/MOD -> 0 1 }T\nT{ 2 MIN-INT M* 2 FM\/MOD -> 0 MIN-INT }T\nT{ 2 MIN-INT M* MIN-INT FM\/MOD -> 0 2 }T\nT{ 1 MAX-INT M* 1 FM\/MOD -> 0 MAX-INT }T\nT{ 1 MAX-INT M* MAX-INT FM\/MOD -> 0 1 }T\nT{ 2 MAX-INT M* 2 FM\/MOD -> 0 MAX-INT }T\nT{ 2 MAX-INT M* MAX-INT FM\/MOD -> 0 2 }T\nT{ MIN-INT MIN-INT M* MIN-INT FM\/MOD -> 0 MIN-INT }T\nT{ MIN-INT MAX-INT M* MIN-INT FM\/MOD -> 0 MAX-INT }T\nT{ MIN-INT MAX-INT M* MAX-INT FM\/MOD -> 0 MIN-INT }T\nT{ MAX-INT MAX-INT M* MAX-INT FM\/MOD -> 0 MAX-INT }T\n\n\\ F.6.1.2214 SM\/REM\nT{ 0 S>D 1 SM\/REM -> 0 0 }T\nT{ 1 S>D 1 SM\/REM -> 0 1 }T\nT{ 2 S>D 1 SM\/REM -> 0 2 }T\nT{ -1 S>D 1 SM\/REM -> 0 -1 }T\nT{ -2 S>D 1 SM\/REM -> 0 -2 }T\nT{ 0 S>D -1 SM\/REM -> 0 0 }T\nT{ 1 S>D -1 SM\/REM -> 0 -1 }T\nT{ 2 S>D -1 SM\/REM -> 0 -2 }T\nT{ -1 S>D -1 SM\/REM -> 0 1 }T\nT{ -2 S>D -1 SM\/REM -> 0 2 }T\nT{ 2 S>D 2 SM\/REM -> 0 1 }T\nT{ -1 S>D -1 SM\/REM -> 0 1 }T\nT{ -2 S>D -2 SM\/REM -> 0 1 }T\nT{ 7 S>D 3 SM\/REM -> 1 2 }T\n\\ TODO: T{ 7 S>D -3 SM\/REM -> 1 -2 }T\n\\ TODO: T{ -7 S>D 3 SM\/REM -> 1 -2 }T\nT{ -7 S>D -3 SM\/REM -> -1 2 }T\nT{ MAX-INT S>D 1 SM\/REM -> 0 MAX-INT }T\nT{ MIN-INT S>D 1 SM\/REM -> 0 MIN-INT }T\nT{ MAX-INT S>D MAX-INT SM\/REM -> 0 1 }T\nT{ MIN-INT S>D MIN-INT SM\/REM -> 0 1 }T\nT{ 1S 1 4 SM\/REM -> 3 MAX-INT }T\nT{ 2 MIN-INT M* 2 SM\/REM -> 0 MIN-INT }T\nT{ 2 MIN-INT M* MIN-INT SM\/REM -> 0 2 }T\nT{ 2 MAX-INT M* 2 SM\/REM -> 0 MAX-INT }T\nT{ 2 MAX-INT M* MAX-INT SM\/REM -> 0 2 }T\nT{ MIN-INT MIN-INT M* MIN-INT SM\/REM -> 0 MIN-INT }T\nT{ MIN-INT MAX-INT M* MIN-INT SM\/REM -> 0 MAX-INT }T\nT{ MIN-INT MAX-INT M* MAX-INT SM\/REM -> 0 MIN-INT }T\nT{ MAX-INT MAX-INT M* MAX-INT SM\/REM -> 0 MAX-INT }T\n\n\\ F.6.1.2370 UM\/MOD\nT{ 0 0 1 UM\/MOD -> 0 0 }T\nT{ 1 0 1 UM\/MOD -> 0 1 }T\nT{ 1 0 2 UM\/MOD -> 1 0 }T\nT{ 3 0 2 UM\/MOD -> 1 1 }T\nT{ MAX-UINT 2 UM* 2 UM\/MOD -> 0 MAX-UINT }T\nT{ MAX-UINT 2 UM* MAX-UINT UM\/MOD -> 0 2 }T\nT{ MAX-UINT MAX-UINT UM* MAX-UINT UM\/MOD -> 0 MAX-UINT }T\n\n: IFFLOORED [ -3 2 \/ -2 = INVERT ] LITERAL IF POSTPONE \\ THEN ;\n: IFSYM [ -3 2 \/ -1 = INVERT ] LITERAL IF POSTPONE \\ THEN ;\n\n\\ F.6.1.0240 \/MOD\nIFFLOORED : T\/MOD >R S>D R> FM\/MOD ;\nIFSYM : T\/MOD >R S>D R> SM\/REM ;\nT{ 0 1 \/MOD -> 0 1 T\/MOD }T\nT{ 1 1 \/MOD -> 1 1 T\/MOD }T\nT{ 2 1 \/MOD -> 2 1 T\/MOD }T\nT{ -1 1 \/MOD -> -1 1 T\/MOD }T\nT{ -2 1 \/MOD -> -2 1 T\/MOD }T\nT{ 0 -1 \/MOD -> 0 -1 T\/MOD }T\nT{ 1 -1 \/MOD -> 1 -1 T\/MOD }T\nT{ 2 -1 \/MOD -> 2 -1 T\/MOD }T\nT{ -1 -1 \/MOD -> -1 -1 T\/MOD }T\nT{ -2 -1 \/MOD -> -2 -1 T\/MOD }T\nT{ 2 2 \/MOD -> 2 2 T\/MOD }T\nT{ -1 -1 \/MOD -> -1 -1 T\/MOD }T\nT{ -2 -2 \/MOD -> -2 -2 T\/MOD }T\nT{ 7 3 \/MOD -> 7 3 T\/MOD }T\nT{ 7 -3 \/MOD -> 7 -3 T\/MOD }T\nT{ -7 3 \/MOD -> -7 3 T\/MOD }T\nT{ -7 -3 \/MOD -> -7 -3 T\/MOD }T\nT{ MAX-INT 1 \/MOD -> MAX-INT 1 T\/MOD }T\nT{ MIN-INT 1 \/MOD -> MIN-INT 1 T\/MOD }T\nT{ MAX-INT MAX-INT \/MOD -> MAX-INT MAX-INT T\/MOD }T\nT{ MIN-INT MIN-INT \/MOD -> MIN-INT MIN-INT T\/MOD }T\n\n\\ F.6.1.0230 \/\nIFFLOORED : T\/ T\/MOD SWAP DROP ;\nIFSYM : T\/ T\/MOD SWAP DROP ;\nT{ 0 1 \/ -> 0 1 T\/ }T\nT{ 1 1 \/ -> 1 1 T\/ }T\nT{ 2 1 \/ -> 2 1 T\/ }T\nT{ -1 1 \/ -> -1 1 T\/ }T\nT{ -2 1 \/ -> -2 1 T\/ }T\nT{ 0 -1 \/ -> 0 -1 T\/ }T\nT{ 1 -1 \/ -> 1 -1 T\/ }T\nT{ 2 -1 \/ -> 2 -1 T\/ }T\nT{ -1 -1 \/ -> -1 -1 T\/ }T\nT{ -2 -1 \/ -> -2 -1 T\/ }T\nT{ 2 2 \/ -> 2 2 T\/ }T\nT{ -1 -1 \/ -> -1 -1 T\/ }T\nT{ -2 -2 \/ -> -2 -2 T\/ }T\nT{ 7 3 \/ -> 7 3 T\/ }T\nT{ 7 -3 \/ -> 7 -3 T\/ }T\nT{ -7 3 \/ -> -7 3 T\/ }T\nT{ -7 -3 \/ -> -7 -3 T\/ }T\nT{ MAX-INT 1 \/ -> MAX-INT 1 T\/ }T\nT{ MIN-INT 1 \/ -> MIN-INT 1 T\/ }T\nT{ MAX-INT MAX-INT \/ -> MAX-INT MAX-INT T\/ }T\nT{ MIN-INT MIN-INT \/ -> MIN-INT MIN-INT T\/ }T\n\n\\ F.6.1.1890 MOD\nIFFLOORED : TMOD T\/MOD DROP ;\nIFSYM : TMOD T\/MOD DROP ;\nT{ 0 1 MOD -> 0 1 TMOD }T\nT{ 1 1 MOD -> 1 1 TMOD }T\nT{ 2 1 MOD -> 2 1 TMOD }T\nT{ -1 1 MOD -> -1 1 TMOD }T\nT{ -2 1 MOD -> -2 1 TMOD }T\nT{ 0 -1 MOD -> 0 -1 TMOD }T\nT{ 1 -1 MOD -> 1 -1 TMOD }T\nT{ 2 -1 MOD -> 2 -1 TMOD }T\nT{ -1 -1 MOD -> -1 -1 TMOD }T\nT{ -2 -1 MOD -> -2 -1 TMOD }T\nT{ 2 2 MOD -> 2 2 TMOD }T\nT{ -1 -1 MOD -> -1 -1 TMOD }T\nT{ -2 -2 MOD -> -2 -2 TMOD }T\nT{ 7 3 MOD -> 7 3 TMOD }T\nT{ 7 -3 MOD -> 7 -3 TMOD }T\nT{ -7 3 MOD -> -7 3 TMOD }T\nT{ -7 -3 MOD -> -7 -3 TMOD }T\nT{ MAX-INT 1 MOD -> MAX-INT 1 TMOD }T\nT{ MIN-INT 1 MOD -> MIN-INT 1 TMOD }T\nT{ MAX-INT MAX-INT MOD -> MAX-INT MAX-INT TMOD }T\nT{ MIN-INT MIN-INT MOD -> MIN-INT MIN-INT TMOD }T\n\n\\ F.6.1.0110 *\/MOD\nIFFLOORED : T*\/MOD >R M* R> FM\/MOD ;\nIFSYM : T*\/MOD >R M* R> SM\/REM ;\nT{ 0 2 1 *\/MOD -> 0 2 1 T*\/MOD }T\nT{ 1 2 1 *\/MOD -> 1 2 1 T*\/MOD }T\nT{ 2 2 1 *\/MOD -> 2 2 1 T*\/MOD }T\nT{ -1 2 1 *\/MOD -> -1 2 1 T*\/MOD }T\nT{ -2 2 1 *\/MOD -> -2 2 1 T*\/MOD }T\nT{ 0 2 -1 *\/MOD -> 0 2 -1 T*\/MOD }T\nT{ 1 2 -1 *\/MOD -> 1 2 -1 T*\/MOD }T\nT{ 2 2 -1 *\/MOD -> 2 2 -1 T*\/MOD }T\nT{ -1 2 -1 *\/MOD -> -1 2 -1 T*\/MOD }T\nT{ -2 2 -1 *\/MOD -> -2 2 -1 T*\/MOD }T\nT{ 2 2 2 *\/MOD -> 2 2 2 T*\/MOD }T\nT{ -1 2 -1 *\/MOD -> -1 2 -1 T*\/MOD }T\nT{ -2 2 -2 *\/MOD -> -2 2 -2 T*\/MOD }T\nT{ 7 2 3 *\/MOD -> 7 2 3 T*\/MOD }T\nT{ 7 2 -3 *\/MOD -> 7 2 -3 T*\/MOD }T\nT{ -7 2 3 *\/MOD -> -7 2 3 T*\/MOD }T\nT{ -7 2 -3 *\/MOD -> -7 2 -3 T*\/MOD }T\nT{ MAX-INT 2 MAX-INT *\/MOD -> MAX-INT 2 MAX-INT T*\/MOD }T\nT{ MIN-INT 2 MIN-INT *\/MOD -> MIN-INT 2 MIN-INT T*\/MOD }T\n\n\\ F.6.1.0100 *\/\nIFFLOORED : T*\/ T*\/MOD SWAP DROP ;\nIFSYM : T*\/ T*\/MOD SWAP DROP ;\nT{ 0 2 1 *\/ -> 0 2 1 T*\/ }T\nT{ 1 2 1 *\/ -> 1 2 1 T*\/ }T\nT{ 2 2 1 *\/ -> 2 2 1 T*\/ }T\nT{ -1 2 1 *\/ -> -1 2 1 T*\/ }T\nT{ -2 2 1 *\/ -> -2 2 1 T*\/ }T\nT{ 0 2 -1 *\/ -> 0 2 -1 T*\/ }T\nT{ 1 2 -1 *\/ -> 1 2 -1 T*\/ }T\nT{ 2 2 -1 *\/ -> 2 2 -1 T*\/ }T\nT{ -1 2 -1 *\/ -> -1 2 -1 T*\/ }T\nT{ -2 2 -1 *\/ -> -2 2 -1 T*\/ }T\nT{ 2 2 2 *\/ -> 2 2 2 T*\/ }T\nT{ -1 2 -1 *\/ -> -1 2 -1 T*\/ }T\nT{ -2 2 -2 *\/ -> -2 2 -2 T*\/ }T\nT{ 7 2 3 *\/ -> 7 2 3 T*\/ }T\nT{ 7 2 -3 *\/ -> 7 2 -3 T*\/ }T\nT{ -7 2 3 *\/ -> -7 2 3 T*\/ }T\nT{ -7 2 -3 *\/ -> -7 2 -3 T*\/ }T\nT{ MAX-INT 2 MAX-INT *\/ -> MAX-INT 2 MAX-INT T*\/ }T\nT{ MIN-INT 2 MIN-INT *\/ -> MIN-INT 2 MIN-INT T*\/ }T\n\n\\ F.6.1.0150 ,\nHERE 1 ,\nHERE 2 ,\nCONSTANT 2ND\nCONSTANT 1ST\nT{ 1ST 2ND U< -> }T \\ HERE MUST GROW WITH ALLOT\nT{ 1ST CELL+ -> 2ND }T \\ ... BY ONE CELL\nT{ 1ST 1 CELLS + -> 2ND }T\nT{ 1ST @ 2ND @ -> 1 2 }T\nT{ 5 1ST ! -> }T\nT{ 1ST @ 2ND @ -> 5 2 }T\nT{ 6 2ND ! -> }T\nT{ 1ST @ 2ND @ -> 5 6 }T\nT{ 1ST 2@ -> 6 5 }T\nT{ 2 1 1ST 2! -> }T\nT{ 1ST 2@ -> 2 1 }T\nT{ 1S 1ST ! 1ST @ -> 1S }T \\ CAN STORE CELL-WIDE VALUE\n\n\\ F.6.1.0130 +!\nT{ 0 1ST ! -> }T\nT{ 1 1ST +! -> }T\nT{ 1ST @ -> 1 }T\nT{ -1 1ST +! 1ST @ -> 0 }T\n\n\\ F.6.1.0890 CELLS\n: BITS ( X -- U )\n 0 SWAP BEGIN DUP WHILE\n DUP MSB AND IF >R 1+ R> THEN 2*\n REPEAT DROP ;\n( CELLS >= 1 AU, INTEGRAL MULTIPLE OF CHAR SIZE, >= 16 BITS )\nT{ 1 CELLS 1 < -> }T\nT{ 1 CELLS 1 CHARS MOD -> 0 }T\nT{ 1S BITS 10 < -> }T\n\n\\ F.6.1.0860 C,\nHERE 1 C,\nHERE 2 C,\nCONSTANT 2NDC\nCONSTANT 1STC\nT{ 1STC 2NDC U< -> }T \\ HERE MUST GROW WITH ALLOT\nT{ 1STC CHAR+ -> 2NDC }T \\ ... BY ONE CHAR\nT{ 1STC 1 CHARS + -> 2NDC }T\nT{ 1STC C@ 2NDC C@ -> 1 2 }T\nT{ 3 1STC C! -> }T\nT{ 1STC C@ 2NDC C@ -> 3 2 }T\nT{ 4 2NDC C! -> }T\nT{ 1STC C@ 2NDC C@ -> 3 4 }T\n\n\\ F.6.1.0898 CHARS\n( CHARACTERS >= 1 AU, <= SIZE OF CELL, >= 8 BITS )\nT{ 1 CHARS 1 < -> }T\nT{ 1 CHARS 1 CELLS > -> }T\n( TBD: HOW TO FIND NUMBER OF BITS? )\n\n\\ F.6.1.0705 ALIGN\nALIGN 1 ALLOT HERE ALIGN HERE 3 CELLS ALLOT\nCONSTANT A-ADDR CONSTANT UA-ADDR\nT{ UA-ADDR ALIGNED -> A-ADDR }T\nT{ 1 A-ADDR C! A-ADDR C@ -> 1 }T\nT{ 1234 A-ADDR ! A-ADDR @ -> 1234 }T\nT{ 123 456 A-ADDR 2! A-ADDR 2@ -> 123 456 }T\nT{ 2 A-ADDR CHAR+ C! A-ADDR CHAR+ C@ -> 2 }T\nT{ 3 A-ADDR CELL+ C! A-ADDR CELL+ C@ -> 3 }T\nT{ 1234 A-ADDR CELL+ ! A-ADDR CELL+ @ -> 1234 }T\nT{ 123 456 A-ADDR CELL+ 2! A-ADDR CELL+ 2@ -> 123 456 }T\n\n\\ F.6.1.0710 ALLOT\nHERE 1 ALLOT\nHERE\nCONSTANT 2NDA\nCONSTANT 1STA\nT{ 1STA 2NDA U< -> }T \\ HERE MUST GROW WITH ALLOT\nT{ 1STA 1+ -> 2NDA }T \\ ... BY ONE ADDRESS UNIT\n( MISSING TEST: NEGATIVE ALLOT )\n\n\\ F.6.1.0770 BL\nT{ BL -> 20 }T\n\n\\ F.6.1.0895 CHAR\nT{ CHAR X -> 58 }T\nT{ CHAR HELLO -> 48 }T\n\n\\ F.6.1.2520 [CHAR]\nT{ : GC1 [CHAR] X ; -> }T\nT{ : GC2 [CHAR] HELLO ; -> }T\nT{ GC1 -> 58 }T\nT{ GC2 -> 48 }T\n\n\\ F.6.1.2500 [\nT{ : GC3 [ GC1 ] LITERAL ; -> }T\nT{ GC3 -> 58 }T\n\n\\ F.6.1.2165 S\"\nT{ : GC4 S\" XY\" ; -> }T\nT{ GC4 SWAP DROP -> 2 }T\nT{ GC4 DROP DUP C@ SWAP CHAR+ C@ -> 58 59 }T\n: GC5 S\" A String\"2DROP ; \\ There is no space between the \" and 2DROP\nT{ GC5 -> }T\n\n\\ F.6.1.0070 '\nT{ : GT1 123 ; -> }T\nT{ ' GT1 EXECUTE -> 123 }T\n\n\\ F.6.1.2510 [']\nT{ : GT2 ['] GT1 ; IMMEDIATE -> }T\nT{ GT2 EXECUTE -> 123 }T\n\n\\ F.6.1.1550 FIND\nHERE 3 C, CHAR G C, CHAR T C, CHAR 1 C, CONSTANT GT1STRING\nHERE 3 C, CHAR G C, CHAR T C, CHAR 2 C, CONSTANT GT2STRING\nT{ GT1STRING FIND -> ' GT1 -1 }T\nT{ GT2STRING FIND -> ' GT2 1 }T\n( HOW TO SEARCH FOR NON-EXISTENT WORD? )\n\n\\ F.6.1.1780 LITERAL\nT{ : GT3 GT2 LITERAL ; -> }T\nT{ GT3 -> ' GT1 }T\n\n\\ F.6.1.0980 COUNT\nT{ GT1STRING COUNT -> GT1STRING CHAR+ 3 }T\n\n\\ F.6.1.2033 POSTPONE\nT{ : GT4 POSTPONE GT1 ; IMMEDIATE -> }T\nT{ : GT5 GT4 ; -> }T\nT{ GT5 -> 123 }T\nT{ : GT6 345 ; IMMEDIATE -> }T\nT{ : GT7 POSTPONE GT6 ; -> }T\nT{ GT7 -> 345 }T\n\n\\ F.6.1.2250 STATE\nT{ : GT8 STATE @ ; IMMEDIATE -> }T\nT{ GT8 -> 0 }T\nT{ : GT9 GT8 LITERAL ; -> }T\nT{ GT9 0= -> }T\n\n\\ F.6.1.1700 IF\nT{ : GI1 IF 123 THEN ; -> }T\nT{ : GI2 IF 123 ELSE 234 THEN ; -> }T\nT{ 0 GI1 -> }T\nT{ 1 GI1 -> 123 }T\nT{ -1 GI1 -> 123 }T\nT{ 0 GI2 -> 234 }T\nT{ 1 GI2 -> 123 }T\nT{ -1 GI1 -> 123 }T\n\\ Multiple ELSEs in an IF statement\n: melse IF 1 ELSE 2 ELSE 3 ELSE 4 ELSE 5 THEN ;\nT{ melse -> 2 4 }T\nT{ melse -> 1 3 5 }T\n\n\\ F.6.1.2430 WHILE\nT{ : GI3 BEGIN DUP 5 < WHILE DUP 1+ REPEAT ; -> }T\nT{ 0 GI3 -> 0 1 2 3 4 5 }T\nT{ 4 GI3 -> 4 5 }T\nT{ 5 GI3 -> 5 }T\nT{ 6 GI3 -> 6 }T\nT{ : GI5 BEGIN DUP 2 > WHILE\n DUP 5 < WHILE DUP 1+ REPEAT\n 123 ELSE 345 THEN ; -> }T\nT{ 1 GI5 -> 1 345 }T\nT{ 2 GI5 -> 2 345 }T\nT{ 3 GI5 -> 3 4 5 123 }T\nT{ 4 GI5 -> 4 5 123 }T\nT{ 5 GI5 -> 5 123 }T\n\n\\ F.6.1.2390 UNTIL\nT{ : GI4 BEGIN DUP 1+ DUP 5 > UNTIL ; -> }T\nT{ 3 GI4 -> 3 4 5 6 }T\nT{ 5 GI4 -> 5 6 }T\nT{ 6 GI4 -> 6 7 }T\n\n\\ F.6.1.2120 RECURSE\nT{ : GI6 ( N -- 0,1,..N )\n DUP IF DUP >R 1- RECURSE R> THEN ; -> }T\nT{ 0 GI6 -> 0 }T\nT{ 1 GI6 -> 0 1 }T\nT{ 2 GI6 -> 0 1 2 }T\nT{ 3 GI6 -> 0 1 2 3 }T\nT{ 4 GI6 -> 0 1 2 3 4 }T\n\nDECIMAL\n\n\\ F.6.1.1800 LOOP\nT{ : GD1 DO I LOOP ; -> }T\nT{ 4 1 GD1 -> 1 2 3 }T\nT{ 2 -1 GD1 -> -1 0 1 }T\nT{ MID-UINT+1 MID-UINT GD1 -> MID-UINT }T\n\n\\ F.6.1.0140 +LOOP\nT{ : GD2 DO I -1 +LOOP ; -> }T\nT{ 1 4 GD2 -> 4 3 2 1 }T\nT{ -1 2 GD2 -> 2 1 0 -1 }T\nT{ MID-UINT MID-UINT+1 GD2 -> MID-UINT+1 MID-UINT }T\nVARIABLE gditerations\nVARIABLE gdincrement\n\n: gd7 ( limit start increment -- )\n gdincrement !\n 0 gditerations !\n DO\n 1 gditerations +!\n I\n gditerations @ 6 = IF LEAVE THEN\n gdincrement @\n +LOOP gditerations @\n;\n\nT{ 4 4 -1 gd7 -> 4 1 }T\nT{ 1 4 -1 gd7 -> 4 3 2 1 4 }T\nT{ 4 1 -1 gd7 -> 1 0 -1 -2 -3 -4 6 }T\nT{ 4 1 0 gd7 -> 1 1 1 1 1 1 6 }T\nT{ 0 0 0 gd7 -> 0 0 0 0 0 0 6 }T\nT{ 1 4 0 gd7 -> 4 4 4 4 4 4 6 }T\nT{ 1 4 1 gd7 -> 4 5 6 7 8 9 6 }T\nT{ 4 1 1 gd7 -> 1 2 3 3 }T\nT{ 4 4 1 gd7 -> 4 5 6 7 8 9 6 }T\nT{ 2 -1 -1 gd7 -> -1 -2 -3 -4 -5 -6 6 }T\nT{ -1 2 -1 gd7 -> 2 1 0 -1 4 }T\nT{ 2 -1 0 gd7 -> -1 -1 -1 -1 -1 -1 6 }T\nT{ -1 2 0 gd7 -> 2 2 2 2 2 2 6 }T\nT{ -1 2 1 gd7 -> 2 3 4 5 6 7 6 }T\nT{ 2 -1 1 gd7 -> -1 0 1 3 }T\nT{ -20 30 -10 gd7 -> 30 20 10 0 -10 -20 6 }T\nT{ -20 31 -10 gd7 -> 31 21 11 1 -9 -19 6 }T\nT{ -20 29 -10 gd7 -> 29 19 9 -1 -11 5 }T\n\n\\ With large and small increments\n\nMAX-UINT 8 RSHIFT 1+ CONSTANT ustep\nustep NEGATE CONSTANT -ustep\nMAX-INT 7 RSHIFT 1+ CONSTANT step\nstep NEGATE CONSTANT -step\n\nVARIABLE bump\n\nT{ : gd8 bump ! DO 1+ bump @ +LOOP ; -> }T\n\nT{ 0 MAX-UINT 0 ustep gd8 -> 256 }T\nT{ 0 0 MAX-UINT -ustep gd8 -> 256 }T\nT{ 0 MAX-INT MIN-INT step gd8 -> 256 }T\nT{ 0 MIN-INT MAX-INT -step gd8 -> 256 }T\n\n\\ F.6.1.1730 J\nT{ : GD3 DO 1 0 DO J LOOP LOOP ; -> }T\nT{ 4 1 GD3 -> 1 2 3 }T\nT{ 2 -1 GD3 -> -1 0 1 }T\nT{ MID-UINT+1 MID-UINT GD3 -> MID-UINT }T\nT{ : GD4 DO 1 0 DO J LOOP -1 +LOOP ; -> }T\nT{ 1 4 GD4 -> 4 3 2 1 }T\nT{ -1 2 GD4 -> 2 1 0 -1 }T\nT{ MID-UINT MID-UINT+1 GD4 -> MID-UINT+1 MID-UINT }T\n\n\\ F.6.1.1760 LEAVE\nT{ : GD5 123 SWAP 0 DO\n I 4 > IF DROP 234 LEAVE THEN\n LOOP ; -> }T\nT{ 1 GD5 -> 123 }T\nT{ 5 GD5 -> 123 }T\nT{ 6 GD5 -> 234 }T\n\n\\ F.6.1.2380 UNLOOP\nT{ : GD6 ( PAT: {0 0},{0 0}{1 0}{1 1},{0 0}{1 0}{1 1}{2 0}{2 1}{2 2} )\n 0 SWAP 0 DO\n I 1+ 0 DO\n I J + 3 = IF I UNLOOP I UNLOOP EXIT THEN 1+\n LOOP\n LOOP ; -> }T\nT{ 1 GD6 -> 1 }T\nT{ 2 GD6 -> 3 }T\nT{ 3 GD6 -> 4 1 2 }T\n\n\\ F.6.1.0450 :\nT{ : NOP : POSTPONE ; ; -> }T\nT{ NOP NOP1 NOP NOP2 -> }T\nT{ NOP1 -> }T\nT{ NOP2 -> }T\n\\ The following tests the dictionary search order:\nT{ : GDX 123 ; : GDX GDX 234 ; -> }T\nT{ GDX -> 123 234 }T\n\n\\ F.6.1.0950 CONSTANT\nT{ 123 CONSTANT X123 -> }T\nT{ X123 -> 123 }T\nT{ : EQU CONSTANT ; -> }T\nT{ X123 EQU Y123 -> }T\nT{ Y123 -> 123 }T\n\n\\ F.6.1.2410 VARIABLE\nT{ VARIABLE V1 -> }T\nT{ 123 V1 ! -> }T\nT{ V1 @ -> 123 }T\n\n\\ F.6.1.1250 DOES>\nT{ : DOES1 DOES> @ 1 + ; -> }T\nT{ : DOES2 DOES> @ 2 + ; -> }T\nT{ CREATE CR1 -> }T\nT{ CR1 -> HERE }T\nT{ 1 , -> }T\nT{ CR1 @ -> 1 }T\nT{ DOES1 -> }T\nT{ CR1 -> 2 }T\nT{ DOES2 -> }T\nT{ CR1 -> 3 }T\nT{ : WEIRD: CREATE DOES> 1 + DOES> 2 + ; -> }T\nT{ WEIRD: W1 -> }T\nT{ ' W1 >BODY -> HERE }T\nT{ W1 -> HERE 1 + }T\nT{ W1 -> HERE 2 + }T\n\n\\ F.6.1.0550 >BODY\nT{ CREATE CR0 -> }T\nT{ ' CR0 >BODY -> HERE }T\n\n\\ F.6.1.1360 EVALUATE\n: GE1 S\" 123\" ; IMMEDIATE\n: GE2 S\" 123 1+\" ; IMMEDIATE\n: GE3 S\" : GE4 345 ;\" ;\n: GE5 EVALUATE ; IMMEDIATE\nT{ GE1 EVALUATE -> 123 }T ( TEST EVALUATE IN INTERP. STATE )\nT{ GE2 EVALUATE -> 124 }T\nT{ GE3 EVALUATE -> }T\nT{ GE4 -> 345 }T\n\nT{ : GE6 GE1 GE5 ; -> }T ( TEST EVALUATE IN COMPILE STATE )\nT{ GE6 -> 123 }T\nT{ : GE7 GE2 GE5 ; -> }T\nT{ GE7 -> 124 }T\n\n\\ F.6.1.2216 SOURCE\n: GS1 S\" SOURCE\" 2DUP EVALUATE >R SWAP >R = R> R> = ;\nT{ GS1 -> }T\n: GS4 SOURCE >IN ! DROP ;\nT{ GS4 123 456\n -> }T\n\n\\ F.6.1.0560 >IN\nVARIABLE SCANS\n: RESCAN? -1 SCANS +! SCANS @ IF 0 >IN ! THEN ;\nT{ 2 SCANS !\n345 RESCAN?\n-> 345 345 }T\n\n: GS2 5 SCANS ! S\" 123 RESCAN?\" EVALUATE ;\nT{ GS2 -> 123 123 123 123 123 }T\n\n\\ These tests must start on a new line\nDECIMAL\nT{ 123456 DEPTH OVER 9 < 35 AND + 3 + >IN !\n-> 123456 23456 3456 456 56 6 }T\nT{ 14145 8115 ?DUP 0= 34 AND >IN +! TUCK MOD 14 >IN ! GCD calculation\n-> 15 }T\nHEX\n\n\\ F.6.1.2450 WORD\n: GS3 WORD COUNT SWAP C@ ;\nT{ BL GS3 HELLO -> 5 CHAR H }T\nT{ CHAR \" GS3 GOODBYE\" -> 7 CHAR G }T\nT{ BL GS3\n DROP -> 0 }T \\ Blank lines return zero-length strings\n\n: S= \\ ( ADDR1 C1 ADDR2 C2 -- T\/F ) Compare two strings.\n >R SWAP R@ = IF \\ Make sure strings have same length\n R> ?DUP IF \\ If non-empty strings\n 0 DO\n OVER C@ OVER C@ - IF 2DROP UNLOOP EXIT THEN\n SWAP CHAR+ SWAP CHAR+\n LOOP\n THEN\n 2DROP \\ If we get here, strings match\n ELSE\n R> DROP 2DROP \\ Lengths mismatch\n THEN ;\n\n\\ F.6.1.1670 HOLD\n: GP1 <# 41 HOLD 42 HOLD 0 0 #> S\" BA\" S= ;\nT{ GP1 -> }T\n\n\\ F.6.1.2210 SIGN\n: GP2 <# -1 SIGN 0 SIGN -1 SIGN 0 0 #> S\" --\" S= ;\nT{ GP2 -> }T\n\n\\ F.6.1.0030 #\n: GP3 <# 1 0 # # #> S\" 01\" S= ;\nT{ GP3 -> }T\n\n24 CONSTANT MAX-BASE \\ BASE 2 ... 36\n: COUNT-BITS\n 0 0 INVERT BEGIN DUP WHILE >R 1+ R> 2* REPEAT DROP ;\nCOUNT-BITS 2* CONSTANT #BITS-UD \\ NUMBER OF BITS IN UD\n\n\\ F.6.1.0050 #S\n: GP4 <# 1 0 #S #> S\" 1\" S= ;\nT{ GP4 -> }T\n: GP5\n BASE @ \n MAX-BASE 1+ 2 DO \\ FOR EACH POSSIBLE BASE\n I BASE ! \\ TBD: ASSUMES BASE WORKS\n I 0 <# #S #> S\" 10\" S= AND\n LOOP\n SWAP BASE ! ;\nT{ GP5 -> }T\n\n: GP6\n BASE @ >R 2 BASE !\n MAX-UINT MAX-UINT <# #S #> \\ MAXIMUM UD TO BINARY\n R> BASE ! \\ S: C-ADDR U\n DUP #BITS-UD = SWAP\n 0 DO \\ S: C-ADDR FLAG\n OVER C@ [CHAR] 1 = AND \\ ALL ONES\n >R CHAR+ R>\n LOOP SWAP DROP ;\nT{ GP6 -> }T\n\n: GP7\n BASE @ >R MAX-BASE BASE !\n \n A 0 DO\n I 0 <# #S #>\n 1 = SWAP C@ I 30 + = AND AND\n LOOP\n MAX-BASE A DO\n I 0 <# #S #>\n 1 = SWAP C@ 41 I A - + = AND AND\n LOOP\n R> BASE ! ;\nT{ GP7 -> }T\n\n\\ F.6.1.0570 >NUMBER\nCREATE GN-BUF 0 C,\n: GN-STRING GN-BUF 1 ;\n: GN-CONSUMED GN-BUF CHAR+ 0 ;\n: GN' [CHAR] ' WORD CHAR+ C@ GN-BUF C! GN-STRING ;\nT{ 0 0 GN' 0' >NUMBER -> 0 0 GN-CONSUMED }T\nT{ 0 0 GN' 1' >NUMBER -> 1 0 GN-CONSUMED }T\nT{ 1 0 GN' 1' >NUMBER -> BASE @ 1+ 0 GN-CONSUMED }T\n\\ FOLLOWING SHOULD FAIL TO CONVERT\nT{ 0 0 GN' -' >NUMBER -> 0 0 GN-STRING }T\nT{ 0 0 GN' +' >NUMBER -> 0 0 GN-STRING }T\nT{ 0 0 GN' .' >NUMBER -> 0 0 GN-STRING }T\n\n: >NUMBER-BASED\n BASE @ >R BASE ! >NUMBER R> BASE ! ;\n\nT{ 0 0 GN' 2' 10 >NUMBER-BASED -> 2 0 GN-CONSUMED }T\nT{ 0 0 GN' 2' 2 >NUMBER-BASED -> 0 0 GN-STRING }T\nT{ 0 0 GN' F' 10 >NUMBER-BASED -> F 0 GN-CONSUMED }T\nT{ 0 0 GN' G' 10 >NUMBER-BASED -> 0 0 GN-STRING }T\nT{ 0 0 GN' G' MAX-BASE >NUMBER-BASED -> 10 0 GN-CONSUMED }T\nT{ 0 0 GN' Z' MAX-BASE >NUMBER-BASED -> 23 0 GN-CONSUMED }T\n\n: GN1 ( UD BASE -- UD' LEN )\n \\ UD SHOULD EQUAL UD' AND LEN SHOULD BE ZERO.\n BASE @ >R BASE !\n <# #S #>\n 0 0 2SWAP >NUMBER SWAP DROP \\ RETURN LENGTH ONLY\n R> BASE ! ;\n\nT{ 0 0 2 GN1 -> 0 0 0 }T\nT{ MAX-UINT 0 2 GN1 -> MAX-UINT 0 0 }T\nT{ MAX-UINT DUP 2 GN1 -> MAX-UINT DUP 0 }T\nT{ 0 0 MAX-BASE GN1 -> 0 0 0 }T\nT{ MAX-UINT 0 MAX-BASE GN1 -> MAX-UINT 0 0 }T\nT{ MAX-UINT DUP MAX-BASE GN1 -> MAX-UINT DUP 0 }T\n\n\\ F.6.1.0750 BASE\n: GN2 \\ ( -- 16 10 )\n BASE @ >R HEX BASE @ DECIMAL BASE @ R> BASE ! ;\nT{ GN2 -> 10 A }T\n\nCREATE FBUF 00 C, 00 C, 00 C,\nCREATE SBUF 12 C, 34 C, 56 C,\n: SEEBUF FBUF C@ FBUF CHAR+ C@ FBUF CHAR+ CHAR+ C@ ;\n\n\\ F.6.1.1540 FILL\nT{ FBUF 0 20 FILL -> }T\nT{ SEEBUF -> 00 00 00 }T\nT{ FBUF 1 20 FILL -> }T\nT{ SEEBUF -> 20 00 00 }T\n\nT{ FBUF 3 20 FILL -> }T\nT{ SEEBUF -> 20 20 20 }T\n\n\\ F.6.1.1900 MOVE\nT{ FBUF FBUF 3 CHARS MOVE -> }T \\ BIZARRE SPECIAL CASE\nT{ SEEBUF -> 20 20 20 }T\nT{ SBUF FBUF 0 CHARS MOVE -> }T\nT{ SEEBUF -> 20 20 20 }T\n\nT{ SBUF FBUF 1 CHARS MOVE -> }T\nT{ SEEBUF -> 12 20 20 }T\n\nT{ SBUF FBUF 3 CHARS MOVE -> }T\nT{ SEEBUF -> 12 34 56 }T\n\nT{ FBUF FBUF CHAR+ 2 CHARS MOVE -> }T\nT{ SEEBUF -> 12 12 34 }T\n\nT{ FBUF CHAR+ FBUF 2 CHARS MOVE -> }T\nT{ SEEBUF -> 12 34 34 }T\n\n\\ F.6.1.1320 EMIT\n: OUTPUT-TEST\n .\" YOU SHOULD SEE THE STANDARD GRAPHIC CHARACTERS:\" CR\n 41 BL DO I EMIT LOOP CR\n 61 41 DO I EMIT LOOP CR\n 7F 61 DO I EMIT LOOP CR\n .\" YOU SHOULD SEE 0-9 SEPARATED BY A SPACE:\" CR\n 9 1+ 0 DO I . LOOP CR\n .\" YOU SHOULD SEE 0-9 (WITH NO SPACES):\" CR\n [CHAR] 9 1+ [CHAR] 0 DO I 0 SPACES EMIT LOOP CR\n .\" YOU SHOULD SEE A-G SEPARATED BY A SPACE:\" CR\n [CHAR] G 1+ [CHAR] A DO I EMIT SPACE LOOP CR\n .\" YOU SHOULD SEE 0-5 SEPARATED BY TWO SPACES:\" CR\n 5 1+ 0 DO I [CHAR] 0 + EMIT 2 SPACES LOOP CR\n .\" YOU SHOULD SEE TWO SEPARATE LINES:\" CR\n S\" LINE 1\" TYPE CR S\" LINE 2\" TYPE CR\n .\" YOU SHOULD SEE THE NUMBER RANGES OF SIGNED AND UNSIGNED NUMBERS:\" CR\n .\" SIGNED: \" MIN-INT . MAX-INT . CR\n .\" UNSIGNED: \" 0 U. MAX-UINT U. CR\n;\nT{ OUTPUT-TEST -> }T\n\n\\ F.6.1.0695 ACCEPT\nCREATE ABUF 80 CHARS ALLOT\n: ACCEPT-TEST\n CR .\" PLEASE TYPE UP TO 80 CHARACTERS:\" CR\n ABUF 80 ACCEPT\n CR .\" RECEIVED: \" [CHAR] \" EMIT\n ABUF SWAP TYPE [CHAR] \" EMIT CR\n;\n\\ SKIP: T{ ACCEPT-TEST -> }T\n\n\\ F.6.1.0450 :\nT{ : NOP : POSTPONE ; ; -> }T\nT{ NOP NOP1 NOP NOP2 -> }T\nT{ NOP1 -> }T\nT{ NOP2 -> }T\n\\ The following tests the dictionary search order:\nT{ : GDX 123 ; : GDX GDX 234 ; -> }T\nT{ GDX -> 123 234 }T\n\n.\" Done\" CR\nBYE\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"ee7b6df7c62957ae4213109864a9066f88dd481e","subject":"Get rid of garbage left on the stack.","message":"Get rid of garbage left on the stack.\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/support.4th","new_file":"sys\/boot\/forth\/support.4th","new_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\ \n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\n\\ Loader.rc support functions:\n\\\n\\ initialize_support ( -- )\tinitialize global variables\n\\ initialize ( addr len -- )\tas above, plus load_conf_files\n\\ load_conf ( addr len -- )\tload conf file given\n\\ include_conf_files ( -- )\tload all conf files in load_conf_files\n\\ print_syntax_error ( -- )\tprint line and marker of where a syntax\n\\\t\t\t\terror was detected\n\\ print_line ( -- )\t\tprint last line processed\n\\ load_kernel ( -- )\t\tload kernel\n\\ load_modules ( -- )\t\tload modules flagged\n\\\n\\ Exported structures:\n\\\n\\ string\t\t\tcounted string structure\n\\\tcell .addr\t\t\tstring address\n\\\tcell .len\t\t\tstring length\n\\ module\t\t\tmodule loading information structure\n\\\tcell module.flag\t\tshould we load it?\n\\\tstring module.name\t\tmodule's name\n\\\tstring module.loadname\t\tname to be used in loading the module\n\\\tstring module.type\t\tmodule's type\n\\\tstring module.args\t\tflags to be passed during load\n\\\tstring module.beforeload\tcommand to be executed before load\n\\\tstring module.afterload\t\tcommand to be executed after load\n\\\tstring module.loaderror\t\tcommand to be executed if load fails\n\\\tcell module.next\t\tlist chain\n\\\n\\ Exported global variables;\n\\\n\\ string conf_files\t\tconfiguration files to be loaded\n\\ string password\t\tpassword\n\\ cell modules_options\t\tpointer to first module information\n\\ value verbose?\t\tindicates if user wants a verbose loading\n\\ value any_conf_read?\t\tindicates if a conf file was succesfully read\n\\\n\\ Other exported words:\n\\\n\\ strdup ( addr len -- addr' len)\t\t\tsimilar to strdup(3)\n\\ strcat ( addr len addr' len' -- addr len+len' )\tsimilar to strcat(3)\n\\ strlen ( addr -- len )\t\t\t\tsimilar to strlen(3)\n\\ s' ( | string' -- addr len | )\t\t\tsimilar to s\"\n\\ rudimentary structure support\n\n\\ Exception values\n\n1 constant syntax_error\n2 constant out_of_memory\n3 constant free_error\n4 constant set_error\n5 constant read_error\n6 constant open_error\n7 constant exec_error\n8 constant before_load_error\n9 constant after_load_error\n\n\\ Crude structure support\n\n: structure:\n create here 0 , ['] drop , 0\n does> create here swap dup @ allot cell+ @ execute\n;\n: member: create dup , over , + does> cell+ @ + ;\n: ;structure swap ! ;\n: constructor! >body cell+ ! ;\n: constructor: over :noname ;\n: ;constructor postpone ; swap cell+ ! ; immediate\n: sizeof ' >body @ state @ if postpone literal then ; immediate\n: offsetof ' >body cell+ @ state @ if postpone literal then ; immediate\n: ptr 1 cells member: ;\n: int 1 cells member: ;\n\n\\ String structure\n\nstructure: string\n\tptr .addr\n\tint .len\n\tconstructor:\n\t 0 over .addr !\n\t 0 swap .len !\n\t;constructor\n;structure\n\n\n\\ Module options linked list\n\nstructure: module\n\tint module.flag\n\tsizeof string member: module.name\n\tsizeof string member: module.loadname\n\tsizeof string member: module.type\n\tsizeof string member: module.args\n\tsizeof string member: module.beforeload\n\tsizeof string member: module.afterload\n\tsizeof string member: module.loaderror\n\tptr module.next\n;structure\n\n\\ Internal loader structures\nstructure: preloaded_file\n\tptr pf.name\n\tptr pf.type\n\tptr pf.args\n\tptr pf.metadata\t\\ file_metadata\n\tint pf.loader\n\tint pf.addr\n\tint pf.size\n\tptr pf.modules\t\\ kernel_module\n\tptr pf.next\t\\ preloaded_file\n;structure\n\nstructure: kernel_module\n\tptr km.name\n\t\\ ptr km.args\n\tptr km.fp\t\\ preloaded_file\n\tptr km.next\t\\ kernel_module\n;structure\n\nstructure: file_metadata\n\tint\t\tmd.size\n\t2 member:\tmd.type\t\\ this is not ANS Forth compatible (XXX)\n\tptr\t\tmd.next\t\\ file_metadata\n\t0 member:\tmd.data\t\\ variable size\n;structure\n\nstructure: config_resource\n\tptr cf.name\n\tint cf.type\n0 constant RES_INT\n1 constant RES_STRING\n2 constant RES_LONG\n\t2 cells member: u\n;structure\n\nstructure: config_device\n\tptr cd.name\n\tint cd.unit\n\tint cd.resource_count\n\tptr cd.resources\t\\ config_resource\n;structure\n\nstructure: STAILQ_HEAD\n\tptr stqh_first\t\\ type*\n\tptr stqh_last\t\\ type**\n;structure\n\nstructure: STAILQ_ENTRY\n\tptr stqe_next\t\\ type*\n;structure\n\nstructure: pnphandler\n\tptr pnph.name\n\tptr pnph.enumerate\n;structure\n\nstructure: pnpident\n\tptr pnpid.ident\t\t\t\t\t\\ char*\n\tsizeof STAILQ_ENTRY cells member: pnpid.link\t\\ pnpident\n;structure\n\nstructure: pnpinfo\n\tptr pnpi.desc\n\tint pnpi.revision\n\tptr pnpi.module\t\t\t\t\\ (char*) module args\n\tint pnpi.argc\n\tptr pnpi.argv\n\tptr pnpi.handler\t\t\t\\ pnphandler\n\tsizeof STAILQ_HEAD member: pnpi.ident\t\\ pnpident\n\tsizeof STAILQ_ENTRY member: pnpi.link\t\\ pnpinfo\n;structure\n\n\\ Global variables\n\nstring conf_files\nstring password\ncreate module_options sizeof module.next allot 0 module_options !\ncreate last_module_option sizeof module.next allot 0 last_module_option !\n0 value verbose?\n\n\\ Support string functions\n\n: strdup ( addr len -- addr' len )\n >r r@ allocate if out_of_memory throw then\n tuck r@ move\n r>\n;\n\n: strcat { addr len addr' len' -- addr len+len' }\n addr' addr len + len' move\n addr len len' +\n;\n\n: strlen ( addr -- len )\n 0 >r\n begin\n dup c@ while\n 1+ r> 1+ >r repeat\n drop r>\n;\n\n: s' \n [char] ' parse\n state @ if\n postpone sliteral\n then\n; immediate\n\n: 2>r postpone >r postpone >r ; immediate\n: 2r> postpone r> postpone r> ; immediate\n: 2r@ postpone 2r> postpone 2dup postpone 2>r ; immediate\n\n: getenv?\n getenv\n -1 = if false else drop true then\n;\n\n\\ Private definitions\n\nvocabulary support-functions\nonly forth also support-functions definitions\n\n\\ Some control characters constants\n\n7 constant bell\n8 constant backspace\n9 constant tab\n10 constant lf\n13 constant \n\n\\ Read buffer size\n\n80 constant read_buffer_size\n\n\\ Standard suffixes\n\n: load_module_suffix s\" _load\" ;\n: module_loadname_suffix s\" _name\" ;\n: module_type_suffix s\" _type\" ;\n: module_args_suffix s\" _flags\" ;\n: module_beforeload_suffix s\" _before\" ;\n: module_afterload_suffix s\" _after\" ;\n: module_loaderror_suffix s\" _error\" ;\n\n\\ Support operators\n\n: >= < 0= ;\n: <= > 0= ;\n\n\\ Assorted support funcitons\n\n: free-memory free if free_error throw then ;\n\n\\ Assignment data temporary storage\n\nstring name_buffer\nstring value_buffer\n\n\\ Line by line file reading functions\n\\\n\\ exported:\n\\\tline_buffer\n\\\tend_of_file?\n\\\tfd\n\\\tread_line\n\\\treset_line_reading\n\nvocabulary line-reading\nalso line-reading definitions also\n\n\\ File data temporary storage\n\nstring read_buffer\n0 value read_buffer_ptr\n\n\\ File's line reading function\n\nsupport-functions definitions\n\nstring line_buffer\n0 value end_of_file?\nvariable fd\n\nline-reading definitions\n\n: skip_newlines\n begin\n read_buffer .len @ read_buffer_ptr >\n while\n read_buffer .addr @ read_buffer_ptr + c@ lf = if\n read_buffer_ptr char+ to read_buffer_ptr\n else\n exit\n then\n repeat\n;\n\n: scan_buffer ( -- addr len )\n read_buffer_ptr >r\n begin\n read_buffer .len @ r@ >\n while\n read_buffer .addr @ r@ + c@ lf = if\n read_buffer .addr @ read_buffer_ptr + ( -- addr )\n r@ read_buffer_ptr - ( -- len )\n r> to read_buffer_ptr\n exit\n then\n r> char+ >r\n repeat\n read_buffer .addr @ read_buffer_ptr + ( -- addr )\n r@ read_buffer_ptr - ( -- len )\n r> to read_buffer_ptr\n;\n\n: line_buffer_resize ( len -- len )\n >r\n line_buffer .len @ if\n line_buffer .addr @\n line_buffer .len @ r@ +\n resize if out_of_memory throw then\n else\n r@ allocate if out_of_memory throw then\n then\n line_buffer .addr !\n r>\n;\n \n: append_to_line_buffer ( addr len -- )\n line_buffer .addr @ line_buffer .len @\n 2swap strcat\n line_buffer .len !\n drop\n;\n\n: read_from_buffer\n scan_buffer ( -- addr len )\n line_buffer_resize ( len -- len )\n append_to_line_buffer ( addr len -- )\n;\n\n: refill_required?\n read_buffer .len @ read_buffer_ptr =\n end_of_file? 0= and\n;\n\n: refill_buffer\n 0 to read_buffer_ptr\n read_buffer .addr @ 0= if\n read_buffer_size allocate if out_of_memory throw then\n read_buffer .addr !\n then\n fd @ read_buffer .addr @ read_buffer_size fread\n dup -1 = if read_error throw then\n dup 0= if true to end_of_file? then\n read_buffer .len !\n;\n\n: reset_line_buffer\n line_buffer .addr @ ?dup if\n free-memory\n then\n 0 line_buffer .addr !\n 0 line_buffer .len !\n;\n\nsupport-functions definitions\n\n: reset_line_reading\n 0 to read_buffer_ptr\n;\n\n: read_line\n reset_line_buffer\n skip_newlines\n begin\n read_from_buffer\n refill_required?\n while\n refill_buffer\n repeat\n;\n\nonly forth also support-functions definitions\n\n\\ Conf file line parser:\n\\ ::= '='[] |\n\\ []\n\\ ::= {||'_'}\n\\ ::= '\"'{|'\\'}'\"' | \n\\ ::= ASCII 32 to 126, except '\\' and '\"'\n\\ ::= '#'{}\n\\\n\\ exported:\n\\\tline_pointer\n\\\tprocess_conf\n\n0 value line_pointer\n\nvocabulary file-processing\nalso file-processing definitions\n\n\\ parser functions\n\\\n\\ exported:\n\\\tget_assignment\n\nvocabulary parser\nalso parser definitions also\n\n0 value parsing_function\n0 value end_of_line\n\n: end_of_line?\n line_pointer end_of_line =\n;\n\n: letter?\n line_pointer c@ >r\n r@ [char] A >=\n r@ [char] Z <= and\n r@ [char] a >=\n r> [char] z <= and\n or\n;\n\n: digit?\n line_pointer c@ >r\n r@ [char] 0 >=\n r> [char] 9 <= and\n;\n\n: quote?\n line_pointer c@ [char] \" =\n;\n\n: assignment_sign?\n line_pointer c@ [char] = =\n;\n\n: comment?\n line_pointer c@ [char] # =\n;\n\n: space?\n line_pointer c@ bl =\n line_pointer c@ tab = or\n;\n\n: backslash?\n line_pointer c@ [char] \\ =\n;\n\n: underscore?\n line_pointer c@ [char] _ =\n;\n\n: dot?\n line_pointer c@ [char] . =\n;\n\n: skip_character\n line_pointer char+ to line_pointer\n;\n\n: skip_to_end_of_line\n end_of_line to line_pointer\n;\n\n: eat_space\n begin\n space?\n while\n skip_character\n end_of_line? if exit then\n repeat\n;\n\n: parse_name ( -- addr len )\n line_pointer\n begin\n letter? digit? underscore? dot? or or or\n while\n skip_character\n end_of_line? if \n line_pointer over -\n strdup\n exit\n then\n repeat\n line_pointer over -\n strdup\n;\n\n: remove_backslashes { addr len | addr' len' -- addr' len' }\n len allocate if out_of_memory throw then\n to addr'\n addr >r\n begin\n addr c@ [char] \\ <> if\n addr c@ addr' len' + c!\n len' char+ to len'\n then\n addr char+ to addr\n r@ len + addr =\n until\n r> drop\n addr' len'\n;\n\n: parse_quote ( -- addr len )\n line_pointer\n skip_character\n end_of_line? if syntax_error throw then\n begin\n quote? 0=\n while\n backslash? if\n skip_character\n end_of_line? if syntax_error throw then\n then\n skip_character\n end_of_line? if syntax_error throw then \n repeat\n skip_character\n line_pointer over -\n remove_backslashes\n;\n\n: read_name\n parse_name\t\t( -- addr len )\n name_buffer .len !\n name_buffer .addr !\n;\n\n: read_value\n quote? if\n parse_quote\t\t( -- addr len )\n else\n parse_name\t\t( -- addr len )\n then\n value_buffer .len !\n value_buffer .addr !\n;\n\n: comment\n skip_to_end_of_line\n;\n\n: white_space_4\n eat_space\n comment? if ['] comment to parsing_function exit then\n end_of_line? 0= if syntax_error throw then\n;\n\n: variable_value\n read_value\n ['] white_space_4 to parsing_function\n;\n\n: white_space_3\n eat_space\n letter? digit? quote? or or if\n ['] variable_value to parsing_function exit\n then\n syntax_error throw\n;\n\n: assignment_sign\n skip_character\n ['] white_space_3 to parsing_function\n;\n\n: white_space_2\n eat_space\n assignment_sign? if ['] assignment_sign to parsing_function exit then\n syntax_error throw\n;\n\n: variable_name\n read_name\n ['] white_space_2 to parsing_function\n;\n\n: white_space_1\n eat_space\n letter? if ['] variable_name to parsing_function exit then\n comment? if ['] comment to parsing_function exit then\n end_of_line? 0= if syntax_error throw then\n;\n\nfile-processing definitions\n\n: get_assignment\n line_buffer .addr @ line_buffer .len @ + to end_of_line\n line_buffer .addr @ to line_pointer\n ['] white_space_1 to parsing_function\n begin\n end_of_line? 0=\n while\n parsing_function execute\n repeat\n parsing_function ['] comment =\n parsing_function ['] white_space_1 =\n parsing_function ['] white_space_4 =\n or or 0= if syntax_error throw then\n;\n\nonly forth also support-functions also file-processing definitions also\n\n\\ Process line\n\n: assignment_type? ( addr len -- flag )\n name_buffer .addr @ name_buffer .len @\n compare 0=\n;\n\n: suffix_type? ( addr len -- flag )\n name_buffer .len @ over <= if 2drop false exit then\n name_buffer .len @ over - name_buffer .addr @ +\n over compare 0=\n;\n\n: loader_conf_files?\n s\" loader_conf_files\" assignment_type?\n;\n\n: verbose_flag?\n s\" verbose_loading\" assignment_type?\n;\n\n: execute?\n s\" exec\" assignment_type?\n;\n\n: password?\n s\" password\" assignment_type?\n;\n\n: module_load?\n load_module_suffix suffix_type?\n;\n\n: module_loadname?\n module_loadname_suffix suffix_type?\n;\n\n: module_type?\n module_type_suffix suffix_type?\n;\n\n: module_args?\n module_args_suffix suffix_type?\n;\n\n: module_beforeload?\n module_beforeload_suffix suffix_type?\n;\n\n: module_afterload?\n module_afterload_suffix suffix_type?\n;\n\n: module_loaderror?\n module_loaderror_suffix suffix_type?\n;\n\n: set_conf_files\n conf_files .addr @ ?dup if\n free-memory\n then\n value_buffer .addr @ c@ [char] \" = if\n value_buffer .addr @ char+ value_buffer .len @ 2 chars -\n else\n value_buffer .addr @ value_buffer .len @\n then\n strdup\n conf_files .len ! conf_files .addr !\n;\n\n: append_to_module_options_list ( addr -- )\n module_options @ 0= if\n dup module_options !\n last_module_option !\n else\n dup last_module_option @ module.next !\n last_module_option !\n then\n;\n\n: set_module_name ( addr -- )\n name_buffer .addr @ name_buffer .len @\n strdup\n >r over module.name .addr !\n r> swap module.name .len !\n;\n\n: yes_value?\n value_buffer .addr @ value_buffer .len @\n 2dup s' \"YES\"' compare >r\n 2dup s' \"yes\"' compare >r\n 2dup s\" YES\" compare >r\n s\" yes\" compare r> r> r> and and and 0=\n;\n\n: find_module_option ( -- addr | 0 )\n module_options @\n begin\n dup\n while\n dup module.name dup .addr @ swap .len @\n name_buffer .addr @ name_buffer .len @\n compare 0= if exit then\n module.next @\n repeat\n;\n\n: new_module_option ( -- addr )\n sizeof module allocate if out_of_memory throw then\n dup sizeof module erase\n dup append_to_module_options_list\n dup set_module_name\n;\n\n: get_module_option ( -- addr )\n find_module_option\n ?dup 0= if new_module_option then\n;\n\n: set_module_flag\n name_buffer .len @ load_module_suffix nip - name_buffer .len !\n yes_value? get_module_option module.flag !\n;\n\n: set_module_args\n name_buffer .len @ module_args_suffix nip - name_buffer .len !\n get_module_option module.args\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_loadname\n name_buffer .len @ module_loadname_suffix nip - name_buffer .len !\n get_module_option module.loadname\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_type\n name_buffer .len @ module_type_suffix nip - name_buffer .len !\n get_module_option module.type\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_beforeload\n name_buffer .len @ module_beforeload_suffix nip - name_buffer .len !\n get_module_option module.beforeload\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_afterload\n name_buffer .len @ module_afterload_suffix nip - name_buffer .len !\n get_module_option module.afterload\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_loaderror\n name_buffer .len @ module_loaderror_suffix nip - name_buffer .len !\n get_module_option module.loaderror\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_environment_variable\n name_buffer .len @\n value_buffer .len @ +\n 5 chars +\n allocate if out_of_memory throw then\n dup 0 ( addr -- addr addr len )\n s\" set \" strcat\n name_buffer .addr @ name_buffer .len @ strcat\n s\" =\" strcat\n value_buffer .addr @ value_buffer .len @ strcat\n ['] evaluate catch if\n 2drop free drop\n set_error throw\n else\n free-memory\n then\n;\n\n: set_verbose\n yes_value? to verbose?\n;\n\n: execute_command\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 - swap char+ swap\n then\n ['] evaluate catch if exec_error throw then\n;\n\n: set_password\n password .addr @ ?dup if free if free_error throw then then\n value_buffer .addr @ c@ [char] \" = if\n value_buffer .addr @ char+ value_buffer .len @ 2 - strdup\n value_buffer .addr @ free if free_error throw then\n else\n value_buffer .addr @ value_buffer .len @\n then\n password .len ! password .addr !\n 0 value_buffer .addr !\n;\n\n: process_assignment\n name_buffer .len @ 0= if exit then\n loader_conf_files?\tif set_conf_files exit then\n verbose_flag?\t\tif set_verbose exit then\n execute?\t\tif execute_command exit then\n password?\t\tif set_password exit then\n module_load?\t\tif set_module_flag exit then\n module_loadname?\tif set_module_loadname exit then\n module_type?\t\tif set_module_type exit then\n module_args?\t\tif set_module_args exit then\n module_beforeload?\tif set_module_beforeload exit then\n module_afterload?\tif set_module_afterload exit then\n module_loaderror?\tif set_module_loaderror exit then\n set_environment_variable\n;\n\n\\ free_buffer ( -- )\n\\\n\\ Free some pointers if needed. The code then tests for errors\n\\ in freeing, and throws an exception if needed. If a pointer is\n\\ not allocated, it's value (0) is used as flag.\n\n: free_buffers\n name_buffer .addr @ dup if free then\n value_buffer .addr @ dup if free then\n or if free_error throw then\n;\n\n: reset_assignment_buffers\n 0 name_buffer .addr !\n 0 name_buffer .len !\n 0 value_buffer .addr !\n 0 value_buffer .len !\n;\n\n\\ Higher level file processing\n\nsupport-functions definitions\n\n: process_conf\n begin\n end_of_file? 0=\n while\n reset_assignment_buffers\n read_line\n get_assignment\n ['] process_assignment catch\n ['] free_buffers catch\n swap throw throw\n repeat\n;\n\nonly forth also support-functions definitions\n\n: create_null_terminated_string { addr len -- addr' len }\n len char+ allocate if out_of_memory throw then\n >r\n addr r@ len move\n 0 r@ len + c!\n r> len\n;\n\n\\ Interface to loading conf files\n\n: load_conf ( addr len -- )\n 0 to end_of_file?\n reset_line_reading\n create_null_terminated_string\n over >r\n fopen fd !\n r> free-memory\n fd @ -1 = if open_error throw then\n ['] process_conf catch\n fd @ fclose\n throw\n;\n\n: print_line\n line_buffer .addr @ line_buffer .len @ type cr\n;\n\n: print_syntax_error\n line_buffer .addr @ line_buffer .len @ type cr\n line_buffer .addr @\n begin\n line_pointer over <>\n while\n bl emit\n char+\n repeat\n drop\n .\" ^\" cr\n;\n\n\\ Depuration support functions\n\nonly forth definitions also support-functions\n\n: test-file \n ['] load_conf catch dup .\n syntax_error = if cr print_syntax_error then\n;\n\n: show-module-options\n module_options @\n begin\n ?dup\n while\n .\" Name: \" dup module.name dup .addr @ swap .len @ type cr\n .\" Path: \" dup module.loadname dup .addr @ swap .len @ type cr\n .\" Type: \" dup module.type dup .addr @ swap .len @ type cr\n .\" Flags: \" dup module.args dup .addr @ swap .len @ type cr\n .\" Before load: \" dup module.beforeload dup .addr @ swap .len @ type cr\n .\" After load: \" dup module.afterload dup .addr @ swap .len @ type cr\n .\" Error: \" dup module.loaderror dup .addr @ swap .len @ type cr\n .\" Status: \" dup module.flag @ if .\" Load\" else .\" Don't load\" then cr\n module.next @\n repeat\n;\n\nonly forth also support-functions definitions\n\n\\ Variables used for processing multiple conf files\n\nstring current_file_name\nvariable current_conf_files\n\n\\ Indicates if any conf file was succesfully read\n\n0 value any_conf_read?\n\n\\ loader_conf_files processing support functions\n\n: set_current_conf_files\n conf_files .addr @ current_conf_files !\n;\n\n: get_conf_files\n conf_files .addr @ conf_files .len @ strdup\n;\n\n: recurse_on_conf_files?\n current_conf_files @ conf_files .addr @ <>\n;\n\n: skip_leading_spaces { addr len pos -- addr len pos' }\n begin\n pos len = if addr len pos exit then\n addr pos + c@ bl =\n while\n pos char+ to pos\n repeat\n addr len pos\n;\n\n: get_file_name { addr len pos -- addr len pos' addr' len' || 0 }\n pos len = if \n addr free abort\" Fatal error freeing memory\"\n 0 exit\n then\n pos >r\n begin\n addr pos + c@ bl <>\n while\n pos char+ to pos\n pos len = if\n addr len pos addr r@ + pos r> - exit\n then\n repeat\n addr len pos addr r@ + pos r> -\n;\n\n: get_next_file ( addr len ptr -- addr len ptr' addr' len' | 0 )\n skip_leading_spaces\n get_file_name\n;\n\n: set_current_file_name\n over current_file_name .addr !\n dup current_file_name .len !\n;\n\n: print_current_file\n current_file_name .addr @ current_file_name .len @ type\n;\n\n: process_conf_errors\n dup 0= if true to any_conf_read? drop exit then\n >r 2drop r>\n dup syntax_error = if\n .\" Warning: syntax error on file \" print_current_file cr\n print_syntax_error drop exit\n then\n dup set_error = if\n .\" Warning: bad definition on file \" print_current_file cr\n print_line drop exit\n then\n dup read_error = if\n .\" Warning: error reading file \" print_current_file cr drop exit\n then\n dup open_error = if\n verbose? if .\" Warning: unable to open file \" print_current_file cr then\n drop exit\n then\n dup free_error = abort\" Fatal error freeing memory\"\n dup out_of_memory = abort\" Out of memory\"\n throw \\ Unknown error -- pass ahead\n;\n\n\\ Process loader_conf_files recursively\n\\ Interface to loader_conf_files processing\n\n: include_conf_files\n set_current_conf_files\n get_conf_files 0\n begin\n get_next_file ?dup\n while\n set_current_file_name\n ['] load_conf catch\n process_conf_errors\n recurse_on_conf_files? if recurse then\n repeat\n;\n\n\\ Module loading functions\n\n: load_module?\n module.flag @\n;\n\n: load_parameters ( addr -- addr addrN lenN ... addr1 len1 N )\n dup >r\n r@ module.args .addr @ r@ module.args .len @\n r@ module.loadname .len @ if\n r@ module.loadname .addr @ r@ module.loadname .len @\n else\n r@ module.name .addr @ r@ module.name .len @\n then\n r@ module.type .len @ if\n r@ module.type .addr @ r@ module.type .len @\n s\" -t \"\n 4 ( -t type name flags )\n else\n 2 ( name flags )\n then\n r> drop\n;\n\n: before_load ( addr -- addr )\n dup module.beforeload .len @ if\n dup module.beforeload .addr @ over module.beforeload .len @\n ['] evaluate catch if before_load_error throw then\n then\n;\n\n: after_load ( addr -- addr )\n dup module.afterload .len @ if\n dup module.afterload .addr @ over module.afterload .len @\n ['] evaluate catch if after_load_error throw then\n then\n;\n\n: load_error ( addr -- addr )\n dup module.loaderror .len @ if\n dup module.loaderror .addr @ over module.loaderror .len @\n evaluate \\ This we do not intercept so it can throw errors\n then\n;\n\n: pre_load_message ( addr -- addr )\n verbose? if\n dup module.name .addr @ over module.name .len @ type\n .\" ...\"\n then\n;\n\n: load_error_message verbose? if .\" failed!\" cr then ;\n\n: load_succesful_message verbose? if .\" ok\" cr then ;\n\n: load_module\n load_parameters load\n;\n\n: process_module ( addr -- addr )\n pre_load_message\n before_load\n begin\n ['] load_module catch if\n dup module.loaderror .len @ if\n load_error\t\t\t\\ Command should return a flag!\n else \n load_error_message true\t\t\\ Do not retry\n then\n else\n after_load\n load_succesful_message true\t\\ Succesful, do not retry\n then\n until\n;\n\n: process_module_errors ( addr ior -- )\n dup before_load_error = if\n drop\n .\" Module \"\n dup module.name .addr @ over module.name .len @ type\n dup module.loadname .len @ if\n .\" (\" dup module.loadname .addr @ over module.loadname .len @ type .\" )\"\n then\n cr\n .\" Error executing \"\n dup module.beforeload .addr @ over module.afterload .len @ type cr\n abort\n then\n\n dup after_load_error = if\n drop\n .\" Module \"\n dup module.name .addr @ over module.name .len @ type\n dup module.loadname .len @ if\n .\" (\" dup module.loadname .addr @ over module.loadname .len @ type .\" )\"\n then\n cr\n .\" Error executing \"\n dup module.afterload .addr @ over module.afterload .len @ type cr\n abort\n then\n\n throw \\ Don't know what it is all about -- pass ahead\n;\n\n\\ Module loading interface\n\n: load_modules ( -- ) ( throws: abort & user-defined )\n module_options @\n begin\n ?dup\n while\n dup load_module? if\n ['] process_module catch\n process_module_errors\n then\n module.next @\n repeat\n;\n\n\\ h00h00 magic used to try loading either a kernel with a given name,\n\\ or a kernel with the default name in a directory of a given name\n\\ (the pain!)\n\n: bootpath s\" \/boot\/\" ;\n: modulepath s\" module_path\" ;\n\n\\ Functions used to save and restore module_path's value.\n: saveenv ( addr len | -1 -- addr' len | 0 -1 )\n dup -1 = if 0 swap exit then\n strdup\n;\n: freeenv ( addr len | 0 -1 )\n -1 = if drop else free abort\" Freeing error\" then\n;\n: restoreenv ( addr len | 0 -1 -- )\n dup -1 = if ( it wasn't set )\n 2drop\n modulepath unsetenv\n else\n over >r\n modulepath setenv\n r> free abort\" Freeing error\"\n then\n;\n\n: clip_args \\ Drop second string if only one argument is passed\n 1 = if\n 2swap 2drop\n 1\n else\n 2\n then\n;\n\nalso builtins\n\n\\ Parse filename from a comma-separated list\n\n: parse-; ( addr len -- addr' len-x addr x )\n over 0 2swap\n begin\n dup 0 <>\n while\n over c@ [char] ; <>\n while\n 1- swap 1+ swap\n 2swap 1+ 2swap\n repeat then\n dup 0 <> if\n 1- swap 1+ swap\n then\n 2swap\n;\n\n\\ Try loading one of multiple kernels specified\n\n: try_multiple_kernels ( addr len addr' len' args -- flag )\n >r\n begin\n parse-; 2>r\n 2over 2r>\n r@ clip_args\n s\" DEBUG\" getenv? if\n s\" echo Module_path: ${module_path}\" evaluate\n .\" Kernel : \" >r 2dup type r> cr\n dup 2 = if .\" Flags : \" >r 2over type r> cr then\n then\n 1 load\n while\n dup 0=\n until\n 1 >r \\ Failure\n else\n 0 >r \\ Success\n then\n 2drop 2drop\n r>\n r> drop\n;\n\n\\ Try to load a kernel; the kernel name is taken from one of\n\\ the following lists, as ordered:\n\\\n\\ 1. The \"bootfile\" environment variable\n\\ 2. The \"kernel\" environment variable\n\\\n\\ Flags are passed, if available. If not, dummy values must be given.\n\\\n\\ The kernel gets loaded from the current module_path.\n\n: load_a_kernel ( flags len 1 | x x 0 -- flag )\n local args\n 2local flags\n 0 0 2local kernel\n end-locals\n\n \\ Check if a default kernel name exists at all, exits if not\n s\" bootfile\" getenv dup -1 <> if\n to kernel\n flags kernel args 1+ try_multiple_kernels\n dup 0= if exit then\n then\n drop\n\n s\" kernel\" getenv dup -1 <> if\n to kernel\n else\n drop\n 1 exit \\ Failure\n then\n\n \\ Try all default kernel names\n flags kernel args 1+ try_multiple_kernels\n;\n\n\\ Try to load a kernel; the kernel name is taken from one of\n\\ the following lists, as ordered:\n\\\n\\ 1. The \"bootfile\" environment variable\n\\ 2. The \"kernel\" environment variable\n\\\n\\ Flags are passed, if provided.\n\\\n\\ The kernel will be loaded from a directory computed from the\n\\ path given. Two directories will be tried in the following order:\n\\\n\\ 1. \/boot\/path\n\\ 2. path\n\\\n\\ The module_path variable is overridden if load is succesful, by\n\\ prepending the successful path.\n\n: load_from_directory ( path len 1 | flags len' path len 2 -- flag )\n local args\n 2local path\n args 1 = if 0 0 then\n 2local flags\n 0 0 2local oldmodulepath\n 0 0 2local newmodulepath\n end-locals\n\n \\ Set the environment variable module_path, and try loading\n \\ the kernel again.\n modulepath getenv saveenv to oldmodulepath\n\n \\ Try prepending \/boot\/ first\n bootpath nip path nip + \n oldmodulepath nip dup -1 = if\n drop\n else\n 1+ +\n then\n allocate\n if ( out of memory )\n 1 exit\n then\n\n 0\n bootpath strcat\n path strcat\n 2dup to newmodulepath\n modulepath setenv\n\n \\ Try all default kernel names\n flags args 1- load_a_kernel\n 0= if ( success )\n oldmodulepath nip -1 <> if\n newmodulepath s\" ;\" strcat\n oldmodulepath strcat\n modulepath setenv\n newmodulepath drop free-memory\n oldmodulepath drop free-memory\n then\n 0 exit\n then\n\n \\ Well, try without the prepended \/boot\/\n path newmodulepath drop swap move\n newmodulepath drop path nip\n 2dup to newmodulepath\n modulepath setenv\n\n \\ Try all default kernel names\n flags args 1- load_a_kernel\n if ( failed once more )\n oldmodulepath restoreenv\n newmodulepath drop free-memory\n 1\n else\n oldmodulepath nip -1 <> if\n newmodulepath s\" ;\" strcat\n oldmodulepath strcat\n modulepath setenv\n newmodulepath drop free-memory\n oldmodulepath drop free-memory\n then\n 0\n then\n;\n\n\\ Try to load a kernel; the kernel name is taken from one of\n\\ the following lists, as ordered:\n\\\n\\ 1. The \"bootfile\" environment variable\n\\ 2. The \"kernel\" environment variable\n\\ 3. The \"path\" argument\n\\\n\\ Flags are passed, if provided.\n\\\n\\ The kernel will be loaded from a directory computed from the\n\\ path given. Two directories will be tried in the following order:\n\\\n\\ 1. \/boot\/path\n\\ 2. path\n\\\n\\ Unless \"path\" is meant to be kernel name itself. In that case, it\n\\ will first be tried as a full path, and, next, search on the\n\\ directories pointed by module_path.\n\\\n\\ The module_path variable is overridden if load is succesful, by\n\\ prepending the successful path.\n\n: load_directory_or_file ( path len 1 | flags len' path len 2 -- flag )\n local args\n 2local path\n args 1 = if 0 0 then\n 2local flags\n end-locals\n\n \\ First, assume path is an absolute path to a directory\n flags path args clip_args load_from_directory\n dup 0= if exit else drop then\n\n \\ Next, assume path points to the kernel\n flags path args try_multiple_kernels\n;\n\n: initialize ( addr len -- )\n strdup conf_files .len ! conf_files .addr !\n;\n\n: kernel_options ( -- addr len 1 | 0 )\n s\" kernel_options\" getenv\n dup -1 = if drop 0 else 1 then\n;\n\n: standard_kernel_search ( flags 1 | 0 -- flag )\n local args\n args 0= if 0 0 then\n 2local flags\n s\" kernel\" getenv\n dup -1 = if 0 swap then\n 2local path\n end-locals\n\n path nip -1 = if ( there isn't a \"kernel\" environment variable )\n flags args load_a_kernel\n else\n flags path args 1+ clip_args load_directory_or_file\n then\n;\n\n: load_kernel ( -- ) ( throws: abort )\n kernel_options standard_kernel_search\n abort\" Unable to load a kernel!\"\n;\n\n: set_defaultoptions ( -- )\n s\" kernel_options\" getenv dup -1 = if\n drop\n else\n s\" temp_options\" setenv\n then\n;\n\n: argv[] ( aN uN ... a1 u1 N i -- aN uN ... a1 u1 N ai+1 ui+1 )\n 2dup = if 0 0 exit then\n dup >r\n 1+ 2* ( skip N and ui )\n pick\n r>\n 1+ 2* ( skip N and ai )\n pick\n;\n\n: drop_args ( aN uN ... a1 u1 N -- )\n 0 ?do 2drop loop\n;\n\n: argc\n dup\n;\n\n: queue_argv ( aN uN ... a1 u1 N a u -- a u aN uN ... a1 u1 N+1 )\n >r\n over 2* 1+ -roll\n r>\n over 2* 1+ -roll\n 1+\n;\n\n: unqueue_argv ( aN uN ... a1 u1 N -- aN uN ... a2 u2 N-1 a1 u1 )\n 1- -rot\n;\n\n: strlen(argv)\n dup 0= if 0 exit then\n 0 >r\t\\ Size\n 0 >r\t\\ Index\n begin\n argc r@ <>\n while\n r@ argv[]\n nip\n r> r> rot + 1+\n >r 1+ >r\n repeat\n r> drop\n r>\n;\n\n: concat_argv ( aN uN ... a1 u1 N -- a u )\n strlen(argv) allocate if out_of_memory throw then\n 0 2>r\n\n begin\n argc\n while\n unqueue_argv\n 2r> 2swap\n strcat\n s\" \" strcat\n 2>r\n repeat\n drop_args\n 2r>\n;\n\n: set_tempoptions ( addrN lenN ... addr1 len1 N -- addr len 1 | 0 )\n \\ Save the first argument, if it exists and is not a flag\n argc if\n 0 argv[] drop c@ [char] - <> if\n unqueue_argv 2>r \\ Filename\n 1 >r\t\t\\ Filename present\n else\n 0 >r\t\t\\ Filename not present\n then\n else\n 0 >r\t\t\\ Filename not present\n then\n\n \\ If there are other arguments, assume they are flags\n ?dup if\n concat_argv\n 2dup s\" temp_options\" setenv\n drop free if free_error throw then\n else\n set_defaultoptions\n then\n\n \\ Bring back the filename, if one was provided\n r> if 2r> 1 else 0 then\n;\n\n: get_arguments ( -- addrN lenN ... addr1 len1 N )\n 0\n begin\n \\ Get next word on the command line\n parse-word\n ?dup while\n queue_argv\n repeat\n drop ( empty string )\n;\n\n: load_kernel_and_modules ( args -- flag )\n set_tempoptions\n argc >r\n s\" temp_options\" getenv dup -1 <> if\n queue_argv\n else\n drop\n then\n r> if ( a path was passed )\n load_directory_or_file\n else\n standard_kernel_search\n then\n ?dup 0= if ['] load_modules catch then\n;\n\n: read-password { size | buf len -- }\n size allocate if out_of_memory throw then\n to buf\n 0 to len\n begin\n key\n dup backspace = if\n drop\n len if\n backspace emit bl emit backspace emit\n len 1 - to len\n else\n bell emit\n then\n else\n dup = if cr drop buf len exit then\n [char] * emit\n len size < if\n buf len chars + c!\n else\n drop\n then\n len 1+ to len\n then\n again\n;\n\n\\ Go back to straight forth vocabulary\n\nonly forth also definitions\n\n","old_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\ \n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\n\\ Loader.rc support functions:\n\\\n\\ initialize_support ( -- )\tinitialize global variables\n\\ initialize ( addr len -- )\tas above, plus load_conf_files\n\\ load_conf ( addr len -- )\tload conf file given\n\\ include_conf_files ( -- )\tload all conf files in load_conf_files\n\\ print_syntax_error ( -- )\tprint line and marker of where a syntax\n\\\t\t\t\terror was detected\n\\ print_line ( -- )\t\tprint last line processed\n\\ load_kernel ( -- )\t\tload kernel\n\\ load_modules ( -- )\t\tload modules flagged\n\\\n\\ Exported structures:\n\\\n\\ string\t\t\tcounted string structure\n\\\tcell .addr\t\t\tstring address\n\\\tcell .len\t\t\tstring length\n\\ module\t\t\tmodule loading information structure\n\\\tcell module.flag\t\tshould we load it?\n\\\tstring module.name\t\tmodule's name\n\\\tstring module.loadname\t\tname to be used in loading the module\n\\\tstring module.type\t\tmodule's type\n\\\tstring module.args\t\tflags to be passed during load\n\\\tstring module.beforeload\tcommand to be executed before load\n\\\tstring module.afterload\t\tcommand to be executed after load\n\\\tstring module.loaderror\t\tcommand to be executed if load fails\n\\\tcell module.next\t\tlist chain\n\\\n\\ Exported global variables;\n\\\n\\ string conf_files\t\tconfiguration files to be loaded\n\\ string password\t\tpassword\n\\ cell modules_options\t\tpointer to first module information\n\\ value verbose?\t\tindicates if user wants a verbose loading\n\\ value any_conf_read?\t\tindicates if a conf file was succesfully read\n\\\n\\ Other exported words:\n\\\n\\ strdup ( addr len -- addr' len)\t\t\tsimilar to strdup(3)\n\\ strcat ( addr len addr' len' -- addr len+len' )\tsimilar to strcat(3)\n\\ strlen ( addr -- len )\t\t\t\tsimilar to strlen(3)\n\\ s' ( | string' -- addr len | )\t\t\tsimilar to s\"\n\\ rudimentary structure support\n\n\\ Exception values\n\n1 constant syntax_error\n2 constant out_of_memory\n3 constant free_error\n4 constant set_error\n5 constant read_error\n6 constant open_error\n7 constant exec_error\n8 constant before_load_error\n9 constant after_load_error\n\n\\ Crude structure support\n\n: structure:\n create here 0 , ['] drop , 0\n does> create here swap dup @ allot cell+ @ execute\n;\n: member: create dup , over , + does> cell+ @ + ;\n: ;structure swap ! ;\n: constructor! >body cell+ ! ;\n: constructor: over :noname ;\n: ;constructor postpone ; swap cell+ ! ; immediate\n: sizeof ' >body @ state @ if postpone literal then ; immediate\n: offsetof ' >body cell+ @ state @ if postpone literal then ; immediate\n: ptr 1 cells member: ;\n: int 1 cells member: ;\n\n\\ String structure\n\nstructure: string\n\tptr .addr\n\tint .len\n\tconstructor:\n\t 0 over .addr !\n\t 0 swap .len !\n\t;constructor\n;structure\n\n\n\\ Module options linked list\n\nstructure: module\n\tint module.flag\n\tsizeof string member: module.name\n\tsizeof string member: module.loadname\n\tsizeof string member: module.type\n\tsizeof string member: module.args\n\tsizeof string member: module.beforeload\n\tsizeof string member: module.afterload\n\tsizeof string member: module.loaderror\n\tptr module.next\n;structure\n\n\\ Internal loader structures\nstructure: preloaded_file\n\tptr pf.name\n\tptr pf.type\n\tptr pf.args\n\tptr pf.metadata\t\\ file_metadata\n\tint pf.loader\n\tint pf.addr\n\tint pf.size\n\tptr pf.modules\t\\ kernel_module\n\tptr pf.next\t\\ preloaded_file\n;structure\n\nstructure: kernel_module\n\tptr km.name\n\t\\ ptr km.args\n\tptr km.fp\t\\ preloaded_file\n\tptr km.next\t\\ kernel_module\n;structure\n\nstructure: file_metadata\n\tint\t\tmd.size\n\t2 member:\tmd.type\t\\ this is not ANS Forth compatible (XXX)\n\tptr\t\tmd.next\t\\ file_metadata\n\t0 member:\tmd.data\t\\ variable size\n;structure\n\nstructure: config_resource\n\tptr cf.name\n\tint cf.type\n0 constant RES_INT\n1 constant RES_STRING\n2 constant RES_LONG\n\t2 cells member: u\n;structure\n\nstructure: config_device\n\tptr cd.name\n\tint cd.unit\n\tint cd.resource_count\n\tptr cd.resources\t\\ config_resource\n;structure\n\nstructure: STAILQ_HEAD\n\tptr stqh_first\t\\ type*\n\tptr stqh_last\t\\ type**\n;structure\n\nstructure: STAILQ_ENTRY\n\tptr stqe_next\t\\ type*\n;structure\n\nstructure: pnphandler\n\tptr pnph.name\n\tptr pnph.enumerate\n;structure\n\nstructure: pnpident\n\tptr pnpid.ident\t\t\t\t\t\\ char*\n\tsizeof STAILQ_ENTRY cells member: pnpid.link\t\\ pnpident\n;structure\n\nstructure: pnpinfo\n\tptr pnpi.desc\n\tint pnpi.revision\n\tptr pnpi.module\t\t\t\t\\ (char*) module args\n\tint pnpi.argc\n\tptr pnpi.argv\n\tptr pnpi.handler\t\t\t\\ pnphandler\n\tsizeof STAILQ_HEAD member: pnpi.ident\t\\ pnpident\n\tsizeof STAILQ_ENTRY member: pnpi.link\t\\ pnpinfo\n;structure\n\n\\ Global variables\n\nstring conf_files\nstring password\ncreate module_options sizeof module.next allot 0 module_options !\ncreate last_module_option sizeof module.next allot 0 last_module_option !\n0 value verbose?\n\n\\ Support string functions\n\n: strdup ( addr len -- addr' len )\n >r r@ allocate if out_of_memory throw then\n tuck r@ move\n r>\n;\n\n: strcat { addr len addr' len' -- addr len+len' }\n addr' addr len + len' move\n addr len len' +\n;\n\n: strlen ( addr -- len )\n 0 >r\n begin\n dup c@ while\n 1+ r> 1+ >r repeat\n drop r>\n;\n\n: s' \n [char] ' parse\n state @ if\n postpone sliteral\n then\n; immediate\n\n: 2>r postpone >r postpone >r ; immediate\n: 2r> postpone r> postpone r> ; immediate\n: 2r@ postpone 2r> postpone 2dup postpone 2>r ; immediate\n\n: getenv?\n getenv\n -1 = if false else drop true then\n;\n\n\\ Private definitions\n\nvocabulary support-functions\nonly forth also support-functions definitions\n\n\\ Some control characters constants\n\n7 constant bell\n8 constant backspace\n9 constant tab\n10 constant lf\n13 constant \n\n\\ Read buffer size\n\n80 constant read_buffer_size\n\n\\ Standard suffixes\n\n: load_module_suffix s\" _load\" ;\n: module_loadname_suffix s\" _name\" ;\n: module_type_suffix s\" _type\" ;\n: module_args_suffix s\" _flags\" ;\n: module_beforeload_suffix s\" _before\" ;\n: module_afterload_suffix s\" _after\" ;\n: module_loaderror_suffix s\" _error\" ;\n\n\\ Support operators\n\n: >= < 0= ;\n: <= > 0= ;\n\n\\ Assorted support funcitons\n\n: free-memory free if free_error throw then ;\n\n\\ Assignment data temporary storage\n\nstring name_buffer\nstring value_buffer\n\n\\ Line by line file reading functions\n\\\n\\ exported:\n\\\tline_buffer\n\\\tend_of_file?\n\\\tfd\n\\\tread_line\n\\\treset_line_reading\n\nvocabulary line-reading\nalso line-reading definitions also\n\n\\ File data temporary storage\n\nstring read_buffer\n0 value read_buffer_ptr\n\n\\ File's line reading function\n\nsupport-functions definitions\n\nstring line_buffer\n0 value end_of_file?\nvariable fd\n\nline-reading definitions\n\n: skip_newlines\n begin\n read_buffer .len @ read_buffer_ptr >\n while\n read_buffer .addr @ read_buffer_ptr + c@ lf = if\n read_buffer_ptr char+ to read_buffer_ptr\n else\n exit\n then\n repeat\n;\n\n: scan_buffer ( -- addr len )\n read_buffer_ptr >r\n begin\n read_buffer .len @ r@ >\n while\n read_buffer .addr @ r@ + c@ lf = if\n read_buffer .addr @ read_buffer_ptr + ( -- addr )\n r@ read_buffer_ptr - ( -- len )\n r> to read_buffer_ptr\n exit\n then\n r> char+ >r\n repeat\n read_buffer .addr @ read_buffer_ptr + ( -- addr )\n r@ read_buffer_ptr - ( -- len )\n r> to read_buffer_ptr\n;\n\n: line_buffer_resize ( len -- len )\n >r\n line_buffer .len @ if\n line_buffer .addr @\n line_buffer .len @ r@ +\n resize if out_of_memory throw then\n else\n r@ allocate if out_of_memory throw then\n then\n line_buffer .addr !\n r>\n;\n \n: append_to_line_buffer ( addr len -- )\n line_buffer .addr @ line_buffer .len @\n 2swap strcat\n line_buffer .len !\n drop\n;\n\n: read_from_buffer\n scan_buffer ( -- addr len )\n line_buffer_resize ( len -- len )\n append_to_line_buffer ( addr len -- )\n;\n\n: refill_required?\n read_buffer .len @ read_buffer_ptr =\n end_of_file? 0= and\n;\n\n: refill_buffer\n 0 to read_buffer_ptr\n read_buffer .addr @ 0= if\n read_buffer_size allocate if out_of_memory throw then\n read_buffer .addr !\n then\n fd @ read_buffer .addr @ read_buffer_size fread\n dup -1 = if read_error throw then\n dup 0= if true to end_of_file? then\n read_buffer .len !\n;\n\n: reset_line_buffer\n line_buffer .addr @ ?dup if\n free-memory\n then\n 0 line_buffer .addr !\n 0 line_buffer .len !\n;\n\nsupport-functions definitions\n\n: reset_line_reading\n 0 to read_buffer_ptr\n;\n\n: read_line\n reset_line_buffer\n skip_newlines\n begin\n read_from_buffer\n refill_required?\n while\n refill_buffer\n repeat\n;\n\nonly forth also support-functions definitions\n\n\\ Conf file line parser:\n\\ ::= '='[] |\n\\ []\n\\ ::= {||'_'}\n\\ ::= '\"'{|'\\'}'\"' | \n\\ ::= ASCII 32 to 126, except '\\' and '\"'\n\\ ::= '#'{}\n\\\n\\ exported:\n\\\tline_pointer\n\\\tprocess_conf\n\n0 value line_pointer\n\nvocabulary file-processing\nalso file-processing definitions\n\n\\ parser functions\n\\\n\\ exported:\n\\\tget_assignment\n\nvocabulary parser\nalso parser definitions also\n\n0 value parsing_function\n0 value end_of_line\n\n: end_of_line?\n line_pointer end_of_line =\n;\n\n: letter?\n line_pointer c@ >r\n r@ [char] A >=\n r@ [char] Z <= and\n r@ [char] a >=\n r> [char] z <= and\n or\n;\n\n: digit?\n line_pointer c@ >r\n r@ [char] 0 >=\n r> [char] 9 <= and\n;\n\n: quote?\n line_pointer c@ [char] \" =\n;\n\n: assignment_sign?\n line_pointer c@ [char] = =\n;\n\n: comment?\n line_pointer c@ [char] # =\n;\n\n: space?\n line_pointer c@ bl =\n line_pointer c@ tab = or\n;\n\n: backslash?\n line_pointer c@ [char] \\ =\n;\n\n: underscore?\n line_pointer c@ [char] _ =\n;\n\n: dot?\n line_pointer c@ [char] . =\n;\n\n: skip_character\n line_pointer char+ to line_pointer\n;\n\n: skip_to_end_of_line\n end_of_line to line_pointer\n;\n\n: eat_space\n begin\n space?\n while\n skip_character\n end_of_line? if exit then\n repeat\n;\n\n: parse_name ( -- addr len )\n line_pointer\n begin\n letter? digit? underscore? dot? or or or\n while\n skip_character\n end_of_line? if \n line_pointer over -\n strdup\n exit\n then\n repeat\n line_pointer over -\n strdup\n;\n\n: remove_backslashes { addr len | addr' len' -- addr' len' }\n len allocate if out_of_memory throw then\n to addr'\n addr >r\n begin\n addr c@ [char] \\ <> if\n addr c@ addr' len' + c!\n len' char+ to len'\n then\n addr char+ to addr\n r@ len + addr =\n until\n r> drop\n addr' len'\n;\n\n: parse_quote ( -- addr len )\n line_pointer\n skip_character\n end_of_line? if syntax_error throw then\n begin\n quote? 0=\n while\n backslash? if\n skip_character\n end_of_line? if syntax_error throw then\n then\n skip_character\n end_of_line? if syntax_error throw then \n repeat\n skip_character\n line_pointer over -\n remove_backslashes\n;\n\n: read_name\n parse_name\t\t( -- addr len )\n name_buffer .len !\n name_buffer .addr !\n;\n\n: read_value\n quote? if\n parse_quote\t\t( -- addr len )\n else\n parse_name\t\t( -- addr len )\n then\n value_buffer .len !\n value_buffer .addr !\n;\n\n: comment\n skip_to_end_of_line\n;\n\n: white_space_4\n eat_space\n comment? if ['] comment to parsing_function exit then\n end_of_line? 0= if syntax_error throw then\n;\n\n: variable_value\n read_value\n ['] white_space_4 to parsing_function\n;\n\n: white_space_3\n eat_space\n letter? digit? quote? or or if\n ['] variable_value to parsing_function exit\n then\n syntax_error throw\n;\n\n: assignment_sign\n skip_character\n ['] white_space_3 to parsing_function\n;\n\n: white_space_2\n eat_space\n assignment_sign? if ['] assignment_sign to parsing_function exit then\n syntax_error throw\n;\n\n: variable_name\n read_name\n ['] white_space_2 to parsing_function\n;\n\n: white_space_1\n eat_space\n letter? if ['] variable_name to parsing_function exit then\n comment? if ['] comment to parsing_function exit then\n end_of_line? 0= if syntax_error throw then\n;\n\nfile-processing definitions\n\n: get_assignment\n line_buffer .addr @ line_buffer .len @ + to end_of_line\n line_buffer .addr @ to line_pointer\n ['] white_space_1 to parsing_function\n begin\n end_of_line? 0=\n while\n parsing_function execute\n repeat\n parsing_function ['] comment =\n parsing_function ['] white_space_1 =\n parsing_function ['] white_space_4 =\n or or 0= if syntax_error throw then\n;\n\nonly forth also support-functions also file-processing definitions also\n\n\\ Process line\n\n: assignment_type? ( addr len -- flag )\n name_buffer .addr @ name_buffer .len @\n compare 0=\n;\n\n: suffix_type? ( addr len -- flag )\n name_buffer .len @ over <= if 2drop false exit then\n name_buffer .len @ over - name_buffer .addr @ +\n over compare 0=\n;\n\n: loader_conf_files?\n s\" loader_conf_files\" assignment_type?\n;\n\n: verbose_flag?\n s\" verbose_loading\" assignment_type?\n;\n\n: execute?\n s\" exec\" assignment_type?\n;\n\n: password?\n s\" password\" assignment_type?\n;\n\n: module_load?\n load_module_suffix suffix_type?\n;\n\n: module_loadname?\n module_loadname_suffix suffix_type?\n;\n\n: module_type?\n module_type_suffix suffix_type?\n;\n\n: module_args?\n module_args_suffix suffix_type?\n;\n\n: module_beforeload?\n module_beforeload_suffix suffix_type?\n;\n\n: module_afterload?\n module_afterload_suffix suffix_type?\n;\n\n: module_loaderror?\n module_loaderror_suffix suffix_type?\n;\n\n: set_conf_files\n conf_files .addr @ ?dup if\n free-memory\n then\n value_buffer .addr @ c@ [char] \" = if\n value_buffer .addr @ char+ value_buffer .len @ 2 chars -\n else\n value_buffer .addr @ value_buffer .len @\n then\n strdup\n conf_files .len ! conf_files .addr !\n;\n\n: append_to_module_options_list ( addr -- )\n module_options @ 0= if\n dup module_options !\n last_module_option !\n else\n dup last_module_option @ module.next !\n last_module_option !\n then\n;\n\n: set_module_name ( addr -- )\n name_buffer .addr @ name_buffer .len @\n strdup\n >r over module.name .addr !\n r> swap module.name .len !\n;\n\n: yes_value?\n value_buffer .addr @ value_buffer .len @\n 2dup s' \"YES\"' compare >r\n 2dup s' \"yes\"' compare >r\n 2dup s\" YES\" compare >r\n s\" yes\" compare r> r> r> and and and 0=\n;\n\n: find_module_option ( -- addr | 0 )\n module_options @\n begin\n dup\n while\n dup module.name dup .addr @ swap .len @\n name_buffer .addr @ name_buffer .len @\n compare 0= if exit then\n module.next @\n repeat\n;\n\n: new_module_option ( -- addr )\n sizeof module allocate if out_of_memory throw then\n dup sizeof module erase\n dup append_to_module_options_list\n dup set_module_name\n;\n\n: get_module_option ( -- addr )\n find_module_option\n ?dup 0= if new_module_option then\n;\n\n: set_module_flag\n name_buffer .len @ load_module_suffix nip - name_buffer .len !\n yes_value? get_module_option module.flag !\n;\n\n: set_module_args\n name_buffer .len @ module_args_suffix nip - name_buffer .len !\n get_module_option module.args\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_loadname\n name_buffer .len @ module_loadname_suffix nip - name_buffer .len !\n get_module_option module.loadname\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_type\n name_buffer .len @ module_type_suffix nip - name_buffer .len !\n get_module_option module.type\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_beforeload\n name_buffer .len @ module_beforeload_suffix nip - name_buffer .len !\n get_module_option module.beforeload\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_afterload\n name_buffer .len @ module_afterload_suffix nip - name_buffer .len !\n get_module_option module.afterload\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_loaderror\n name_buffer .len @ module_loaderror_suffix nip - name_buffer .len !\n get_module_option module.loaderror\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_environment_variable\n name_buffer .len @\n value_buffer .len @ +\n 5 chars +\n allocate if out_of_memory throw then\n dup 0 ( addr -- addr addr len )\n s\" set \" strcat\n name_buffer .addr @ name_buffer .len @ strcat\n s\" =\" strcat\n value_buffer .addr @ value_buffer .len @ strcat\n ['] evaluate catch if\n 2drop free drop\n set_error throw\n else\n free-memory\n then\n;\n\n: set_verbose\n yes_value? to verbose?\n;\n\n: execute_command\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 - swap char+ swap\n then\n ['] evaluate catch if exec_error throw then\n;\n\n: set_password\n password .addr @ ?dup if free if free_error throw then then\n value_buffer .addr @ c@ [char] \" = if\n value_buffer .addr @ char+ value_buffer .len @ 2 - strdup\n value_buffer .addr @ free if free_error throw then\n else\n value_buffer .addr @ value_buffer .len @\n then\n password .len ! password .addr !\n 0 value_buffer .addr !\n;\n\n: process_assignment\n name_buffer .len @ 0= if exit then\n loader_conf_files?\tif set_conf_files exit then\n verbose_flag?\t\tif set_verbose exit then\n execute?\t\tif execute_command exit then\n password?\t\tif set_password exit then\n module_load?\t\tif set_module_flag exit then\n module_loadname?\tif set_module_loadname exit then\n module_type?\t\tif set_module_type exit then\n module_args?\t\tif set_module_args exit then\n module_beforeload?\tif set_module_beforeload exit then\n module_afterload?\tif set_module_afterload exit then\n module_loaderror?\tif set_module_loaderror exit then\n set_environment_variable\n;\n\n\\ free_buffer ( -- )\n\\\n\\ Free some pointers if needed. The code then tests for errors\n\\ in freeing, and throws an exception if needed. If a pointer is\n\\ not allocated, it's value (0) is used as flag.\n\n: free_buffers\n name_buffer .addr @ dup if free then\n value_buffer .addr @ dup if free then\n or if free_error throw then\n;\n\n: reset_assignment_buffers\n 0 name_buffer .addr !\n 0 name_buffer .len !\n 0 value_buffer .addr !\n 0 value_buffer .len !\n;\n\n\\ Higher level file processing\n\nsupport-functions definitions\n\n: process_conf\n begin\n end_of_file? 0=\n while\n reset_assignment_buffers\n read_line\n get_assignment\n ['] process_assignment catch\n ['] free_buffers catch\n swap throw throw\n repeat\n;\n\nonly forth also support-functions definitions\n\n: create_null_terminated_string { addr len -- addr' len }\n len char+ allocate if out_of_memory throw then\n >r\n addr r@ len move\n 0 r@ len + c!\n r> len\n;\n\n\\ Interface to loading conf files\n\n: load_conf ( addr len -- )\n 0 to end_of_file?\n reset_line_reading\n create_null_terminated_string\n over >r\n fopen fd !\n r> free-memory\n fd @ -1 = if open_error throw then\n ['] process_conf catch\n fd @ fclose\n throw\n;\n\n: print_line\n line_buffer .addr @ line_buffer .len @ type cr\n;\n\n: print_syntax_error\n line_buffer .addr @ line_buffer .len @ type cr\n line_buffer .addr @\n begin\n line_pointer over <>\n while\n bl emit\n char+\n repeat\n drop\n .\" ^\" cr\n;\n\n\\ Depuration support functions\n\nonly forth definitions also support-functions\n\n: test-file \n ['] load_conf catch dup .\n syntax_error = if cr print_syntax_error then\n;\n\n: show-module-options\n module_options @\n begin\n ?dup\n while\n .\" Name: \" dup module.name dup .addr @ swap .len @ type cr\n .\" Path: \" dup module.loadname dup .addr @ swap .len @ type cr\n .\" Type: \" dup module.type dup .addr @ swap .len @ type cr\n .\" Flags: \" dup module.args dup .addr @ swap .len @ type cr\n .\" Before load: \" dup module.beforeload dup .addr @ swap .len @ type cr\n .\" After load: \" dup module.afterload dup .addr @ swap .len @ type cr\n .\" Error: \" dup module.loaderror dup .addr @ swap .len @ type cr\n .\" Status: \" dup module.flag @ if .\" Load\" else .\" Don't load\" then cr\n module.next @\n repeat\n;\n\nonly forth also support-functions definitions\n\n\\ Variables used for processing multiple conf files\n\nstring current_file_name\nvariable current_conf_files\n\n\\ Indicates if any conf file was succesfully read\n\n0 value any_conf_read?\n\n\\ loader_conf_files processing support functions\n\n: set_current_conf_files\n conf_files .addr @ current_conf_files !\n;\n\n: get_conf_files\n conf_files .addr @ conf_files .len @ strdup\n;\n\n: recurse_on_conf_files?\n current_conf_files @ conf_files .addr @ <>\n;\n\n: skip_leading_spaces { addr len pos -- addr len pos' }\n begin\n pos len = if addr len pos exit then\n addr pos + c@ bl =\n while\n pos char+ to pos\n repeat\n addr len pos\n;\n\n: get_file_name { addr len pos -- addr len pos' addr' len' || 0 }\n pos len = if \n addr free abort\" Fatal error freeing memory\"\n 0 exit\n then\n pos >r\n begin\n addr pos + c@ bl <>\n while\n pos char+ to pos\n pos len = if\n addr len pos addr r@ + pos r> - exit\n then\n repeat\n addr len pos addr r@ + pos r> -\n;\n\n: get_next_file ( addr len ptr -- addr len ptr' addr' len' | 0 )\n skip_leading_spaces\n get_file_name\n;\n\n: set_current_file_name\n over current_file_name .addr !\n dup current_file_name .len !\n;\n\n: print_current_file\n current_file_name .addr @ current_file_name .len @ type\n;\n\n: process_conf_errors\n dup 0= if true to any_conf_read? drop exit then\n >r 2drop r>\n dup syntax_error = if\n .\" Warning: syntax error on file \" print_current_file cr\n print_syntax_error drop exit\n then\n dup set_error = if\n .\" Warning: bad definition on file \" print_current_file cr\n print_line drop exit\n then\n dup read_error = if\n .\" Warning: error reading file \" print_current_file cr drop exit\n then\n dup open_error = if\n verbose? if .\" Warning: unable to open file \" print_current_file cr then\n drop exit\n then\n dup free_error = abort\" Fatal error freeing memory\"\n dup out_of_memory = abort\" Out of memory\"\n throw \\ Unknown error -- pass ahead\n;\n\n\\ Process loader_conf_files recursively\n\\ Interface to loader_conf_files processing\n\n: include_conf_files\n set_current_conf_files\n get_conf_files 0\n begin\n get_next_file ?dup\n while\n set_current_file_name\n ['] load_conf catch\n process_conf_errors\n recurse_on_conf_files? if recurse then\n repeat\n;\n\n\\ Module loading functions\n\n: load_module?\n module.flag @\n;\n\n: load_parameters ( addr -- addr addrN lenN ... addr1 len1 N )\n dup >r\n r@ module.args .addr @ r@ module.args .len @\n r@ module.loadname .len @ if\n r@ module.loadname .addr @ r@ module.loadname .len @\n else\n r@ module.name .addr @ r@ module.name .len @\n then\n r@ module.type .len @ if\n r@ module.type .addr @ r@ module.type .len @\n s\" -t \"\n 4 ( -t type name flags )\n else\n 2 ( name flags )\n then\n r> drop\n;\n\n: before_load ( addr -- addr )\n dup module.beforeload .len @ if\n dup module.beforeload .addr @ over module.beforeload .len @\n ['] evaluate catch if before_load_error throw then\n then\n;\n\n: after_load ( addr -- addr )\n dup module.afterload .len @ if\n dup module.afterload .addr @ over module.afterload .len @\n ['] evaluate catch if after_load_error throw then\n then\n;\n\n: load_error ( addr -- addr )\n dup module.loaderror .len @ if\n dup module.loaderror .addr @ over module.loaderror .len @\n evaluate \\ This we do not intercept so it can throw errors\n then\n;\n\n: pre_load_message ( addr -- addr )\n verbose? if\n dup module.name .addr @ over module.name .len @ type\n .\" ...\"\n then\n;\n\n: load_error_message verbose? if .\" failed!\" cr then ;\n\n: load_succesful_message verbose? if .\" ok\" cr then ;\n\n: load_module\n load_parameters load\n;\n\n: process_module ( addr -- addr )\n pre_load_message\n before_load\n begin\n ['] load_module catch if\n dup module.loaderror .len @ if\n load_error\t\t\t\\ Command should return a flag!\n else \n load_error_message true\t\t\\ Do not retry\n then\n else\n after_load\n load_succesful_message true\t\\ Succesful, do not retry\n then\n until\n;\n\n: process_module_errors ( addr ior -- )\n dup before_load_error = if\n drop\n .\" Module \"\n dup module.name .addr @ over module.name .len @ type\n dup module.loadname .len @ if\n .\" (\" dup module.loadname .addr @ over module.loadname .len @ type .\" )\"\n then\n cr\n .\" Error executing \"\n dup module.beforeload .addr @ over module.afterload .len @ type cr\n abort\n then\n\n dup after_load_error = if\n drop\n .\" Module \"\n dup module.name .addr @ over module.name .len @ type\n dup module.loadname .len @ if\n .\" (\" dup module.loadname .addr @ over module.loadname .len @ type .\" )\"\n then\n cr\n .\" Error executing \"\n dup module.afterload .addr @ over module.afterload .len @ type cr\n abort\n then\n\n throw \\ Don't know what it is all about -- pass ahead\n;\n\n\\ Module loading interface\n\n: load_modules ( -- ) ( throws: abort & user-defined )\n module_options @\n begin\n ?dup\n while\n dup load_module? if\n ['] process_module catch\n process_module_errors\n then\n module.next @\n repeat\n;\n\n\\ h00h00 magic used to try loading either a kernel with a given name,\n\\ or a kernel with the default name in a directory of a given name\n\\ (the pain!)\n\n: bootpath s\" \/boot\/\" ;\n: modulepath s\" module_path\" ;\n\n\\ Functions used to save and restore module_path's value.\n: saveenv ( addr len | -1 -- addr' len | 0 -1 )\n dup -1 = if 0 swap exit then\n strdup\n;\n: freeenv ( addr len | 0 -1 )\n -1 = if drop else free abort\" Freeing error\" then\n;\n: restoreenv ( addr len | 0 -1 -- )\n dup -1 = if ( it wasn't set )\n 2drop\n modulepath unsetenv\n else\n over >r\n modulepath setenv\n r> free abort\" Freeing error\"\n then\n;\n\n: clip_args \\ Drop second string if only one argument is passed\n 1 = if\n 2swap 2drop\n 1\n else\n 2\n then\n;\n\nalso builtins\n\n\\ Parse filename from a comma-separated list\n\n: parse-; ( addr len -- addr' len-x addr x )\n over 0 2swap\n begin\n dup 0 <>\n while\n over c@ [char] ; <>\n while\n 1- swap 1+ swap\n 2swap 1+ 2swap\n repeat then\n dup 0 <> if\n 1- swap 1+ swap\n then\n 2swap\n;\n\n\\ Try loading one of multiple kernels specified\n\n: try_multiple_kernels ( addr len addr' len' args -- flag )\n >r\n begin\n parse-; 2>r\n 2over 2r>\n r@ clip_args\n s\" DEBUG\" getenv? if\n s\" echo Module_path: ${module_path}\" evaluate\n .\" Kernel : \" >r 2dup type r> cr\n dup 2 = if .\" Flags : \" >r 2over type r> cr then\n then\n 1 load\n while\n dup 0=\n until\n 1 >r \\ Failure\n else\n 0 >r \\ Success\n then\n 2drop 2drop\n r>\n r> drop\n;\n\n\\ Try to load a kernel; the kernel name is taken from one of\n\\ the following lists, as ordered:\n\\\n\\ 1. The \"bootfile\" environment variable\n\\ 2. The \"kernel\" environment variable\n\\\n\\ Flags are passed, if available. If not, dummy values must be given.\n\\\n\\ The kernel gets loaded from the current module_path.\n\n: load_a_kernel ( flags len 1 | x x 0 -- flag )\n local args\n 2local flags\n 0 0 2local kernel\n end-locals\n\n \\ Check if a default kernel name exists at all, exits if not\n s\" bootfile\" getenv dup -1 <> if\n to kernel\n flags kernel args 1+ try_multiple_kernels\n dup 0= if exit then\n then\n drop\n\n s\" kernel\" getenv dup -1 <> if\n to kernel\n else\n drop\n 1 exit \\ Failure\n then\n\n \\ Try all default kernel names\n flags kernel args 1+ try_multiple_kernels\n;\n\n\\ Try to load a kernel; the kernel name is taken from one of\n\\ the following lists, as ordered:\n\\\n\\ 1. The \"bootfile\" environment variable\n\\ 2. The \"kernel\" environment variable\n\\\n\\ Flags are passed, if provided.\n\\\n\\ The kernel will be loaded from a directory computed from the\n\\ path given. Two directories will be tried in the following order:\n\\\n\\ 1. \/boot\/path\n\\ 2. path\n\\\n\\ The module_path variable is overridden if load is succesful, by\n\\ prepending the successful path.\n\n: load_from_directory ( path len 1 | flags len' path len 2 -- flag )\n local args\n 2local path\n args 1 = if 0 0 then\n 2local flags\n 0 0 2local oldmodulepath\n 0 0 2local newmodulepath\n end-locals\n\n \\ Set the environment variable module_path, and try loading\n \\ the kernel again.\n modulepath getenv saveenv to oldmodulepath\n\n \\ Try prepending \/boot\/ first\n bootpath nip path nip + \n oldmodulepath nip dup -1 = if\n drop\n else\n 1+ +\n then\n allocate\n if ( out of memory )\n 1 exit\n then\n\n 0\n bootpath strcat\n path strcat\n 2dup to newmodulepath\n modulepath setenv\n\n \\ Try all default kernel names\n flags args 1- load_a_kernel\n 0= if ( success )\n oldmodulepath nip -1 <> if\n newmodulepath s\" ;\" strcat\n oldmodulepath strcat\n modulepath setenv\n newmodulepath drop free-memory\n oldmodulepath drop free-memory\n then\n 0 exit\n then\n\n \\ Well, try without the prepended \/boot\/\n path newmodulepath drop swap move\n newmodulepath drop path nip\n 2dup to newmodulepath\n modulepath setenv\n\n \\ Try all default kernel names\n flags args 1- load_a_kernel\n if ( failed once more )\n oldmodulepath restoreenv\n newmodulepath drop free-memory\n 1\n else\n oldmodulepath nip -1 <> if\n newmodulepath s\" ;\" strcat\n oldmodulepath strcat\n modulepath setenv\n newmodulepath drop free-memory\n oldmodulepath drop free-memory\n then\n 0\n then\n;\n\n\\ Try to load a kernel; the kernel name is taken from one of\n\\ the following lists, as ordered:\n\\\n\\ 1. The \"bootfile\" environment variable\n\\ 2. The \"kernel\" environment variable\n\\ 3. The \"path\" argument\n\\\n\\ Flags are passed, if provided.\n\\\n\\ The kernel will be loaded from a directory computed from the\n\\ path given. Two directories will be tried in the following order:\n\\\n\\ 1. \/boot\/path\n\\ 2. path\n\\\n\\ Unless \"path\" is meant to be kernel name itself. In that case, it\n\\ will first be tried as a full path, and, next, search on the\n\\ directories pointed by module_path.\n\\\n\\ The module_path variable is overridden if load is succesful, by\n\\ prepending the successful path.\n\n: load_directory_or_file ( path len 1 | flags len' path len 2 -- flag )\n local args\n 2local path\n args 1 = if 0 0 then\n 2local flags\n end-locals\n\n \\ First, assume path is an absolute path to a directory\n flags path args clip_args load_from_directory\n dup 0= if exit else drop then\n\n \\ Next, assume path points to the kernel\n flags path args try_multiple_kernels\n;\n\n: initialize ( addr len -- )\n strdup conf_files .len ! conf_files .addr !\n;\n\n: kernel_options ( -- addr len 1 | 0 )\n s\" kernel_options\" getenv\n dup -1 = if drop 0 else 1 then\n;\n\n: standard_kernel_search ( flags 1 | 0 -- flag )\n local args\n args 0= if 0 0 then\n 2local flags\n s\" kernel\" getenv\n dup -1 = if 0 swap then\n 2local path\n end-locals\n\n path dup -1 = if ( there isn't a \"kernel\" environment variable )\n 2drop\n flags args load_a_kernel\n else\n flags path args 1+ clip_args load_directory_or_file\n then\n;\n\n: load_kernel ( -- ) ( throws: abort )\n kernel_options standard_kernel_search\n abort\" Unable to load a kernel!\"\n;\n\n: set_defaultoptions ( -- )\n s\" kernel_options\" getenv dup -1 = if\n drop\n else\n s\" temp_options\" setenv\n then\n;\n\n: argv[] ( aN uN ... a1 u1 N i -- aN uN ... a1 u1 N ai+1 ui+1 )\n 2dup = if 0 0 exit then\n dup >r\n 1+ 2* ( skip N and ui )\n pick\n r>\n 1+ 2* ( skip N and ai )\n pick\n;\n\n: drop_args ( aN uN ... a1 u1 N -- )\n 0 ?do 2drop loop\n;\n\n: argc\n dup\n;\n\n: queue_argv ( aN uN ... a1 u1 N a u -- a u aN uN ... a1 u1 N+1 )\n >r\n over 2* 1+ -roll\n r>\n over 2* 1+ -roll\n 1+\n;\n\n: unqueue_argv ( aN uN ... a1 u1 N -- aN uN ... a2 u2 N-1 a1 u1 )\n 1- -rot\n;\n\n: strlen(argv)\n dup 0= if 0 exit then\n 0 >r\t\\ Size\n 0 >r\t\\ Index\n begin\n argc r@ <>\n while\n r@ argv[]\n nip\n r> r> rot + 1+\n >r 1+ >r\n repeat\n r> drop\n r>\n;\n\n: concat_argv ( aN uN ... a1 u1 N -- a u )\n strlen(argv) allocate if out_of_memory throw then\n 0 2>r\n\n begin\n argc\n while\n unqueue_argv\n 2r> 2swap\n strcat\n s\" \" strcat\n 2>r\n repeat\n drop_args\n 2r>\n;\n\n: set_tempoptions ( addrN lenN ... addr1 len1 N -- addr len 1 | 0 )\n \\ Save the first argument, if it exists and is not a flag\n argc if\n 0 argv[] drop c@ [char] - <> if\n unqueue_argv 2>r \\ Filename\n 1 >r\t\t\\ Filename present\n else\n 0 >r\t\t\\ Filename not present\n then\n else\n 0 >r\t\t\\ Filename not present\n then\n\n \\ If there are other arguments, assume they are flags\n ?dup if\n concat_argv\n 2dup s\" temp_options\" setenv\n drop free if free_error throw then\n else\n set_defaultoptions\n then\n\n \\ Bring back the filename, if one was provided\n r> if 2r> 1 else 0 then\n;\n\n: get_arguments ( -- addrN lenN ... addr1 len1 N )\n 0\n begin\n \\ Get next word on the command line\n parse-word\n ?dup while\n queue_argv\n repeat\n drop ( empty string )\n;\n\n: load_kernel_and_modules ( args -- flag )\n set_tempoptions\n argc >r\n s\" temp_options\" getenv dup -1 <> if\n queue_argv\n else\n drop\n then\n r> if ( a path was passed )\n load_directory_or_file\n else\n standard_kernel_search\n then\n ?dup 0= if ['] load_modules catch then\n;\n\n: read-password { size | buf len -- }\n size allocate if out_of_memory throw then\n to buf\n 0 to len\n begin\n key\n dup backspace = if\n drop\n len if\n backspace emit bl emit backspace emit\n len 1 - to len\n else\n bell emit\n then\n else\n dup = if cr drop buf len exit then\n [char] * emit\n len size < if\n buf len chars + c!\n else\n drop\n then\n len 1+ to len\n then\n again\n;\n\n\\ Go back to straight forth vocabulary\n\nonly forth also definitions\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"86d1a370d6820bc655f80fdb9da014ea5c5568ba","subject":"Added PARSE-WORD","message":"Added PARSE-WORD\n","repos":"rm-hull\/byok3,rm-hull\/byok3","old_file":"src\/main\/resources\/forth\/system.fth","new_file":"src\/main\/resources\/forth\/system.fth","new_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\\n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n\n: COUNT dup 1+ swap c@ ;\n\n\\ Miscellaneous support words\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: <= ( a b -- f , true if A <= b ) > 0= ;\n: >= ( a b -- f , true if A >= b ) < 0= ;\n: NOT ( n -- !n , logical negation ) 0= ;\n: DNEGATE ( d -- -d , negate by doing 0-d )\n 0 swap -\n;\n: CELL+ ( n -- n+cell ) cell + ;\n: CELL- ( n -- n-cell ) cell - ;\n: CELL* ( n -- n*cell ) cells ;\n\n: CHAR+ ( n -- n+size_of_char ) 1+ ;\n\\ : CHARS ( n -- n*size_of_char, don't do anything ) ; immediate\n\n\\ useful stack manipulation words\n: -ROT ( a b c -- c a b ) rot rot ;\n: 3DUP ( a b c -- a b c a b c ) 2 pick 2 pick 2 pick ;\n\n\\ ------------------------------------------------------------------\n: ID. ( nfa -- ) count 31 and type ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: PAD ( -- addr ) here 128 + ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n\n: BETWEEN ( n lo hi -- flag , true if between lo & hi )\n >r over r> > >r\n < r> or 0=\n;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: ? ( -- ) @ . ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ ' (lit) , cell 1- , ] +\n [ ' (lit) , cell 1- invert , ] and ;\n\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n: ALLOT ( nbytes -- , allot space in dictionary ) dp +! align ;\n\n: C, ( c -- ) here c! 1 dp +! ;\n\\ : W, ( w -- ) dp @ even-up dup dp ! w! 2 dp +! ;\n\\ : , ( n -- , lay into dictionary ) align here ! cell allot ;\n\n: SEE ( -- )\n ' dup\n 16 + @ \\ offset in execution token for alloc size\n cells swap >body swap\n disassemble ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token )\n [compile] literal ( compile a call to literal )\n ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n: :NONAME ( -- xt , begin compilation of headerless secondary ) align here ] ;\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick )\n ?comp ' [compile] literal\n; immediate\n\n\n: (DOES>) ( xt -- , modify previous definition to execute code at xt )\n latest >body \\ get address of code for new word\n cell + \\ offset to second cell in create word\n ! \\ store execution token of DOES> code in new word\n;\n\n: DOES> ( -- , define execution code for CREATE word )\n 0 [compile] literal \\ dummy literal to hold xt\n here cell- \\ address of zero in literal\n compile (does>) \\ call (DOES>) from new creation word\n\t\t>r \\ move addrz to return stack so ; doesn't see stack garbage\n [compile] ; \\ terminate part of code before does>\n\t\tr>\n :noname ( addrz xt )\n swap ! \\ save execution token in literal\n; immediate\n\n0 1- constant -1\n0 2- constant -2\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 )\n swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 )\n dup cell+ @ swap @ ;\n\n: 2* ( n -- n*2 )\n 1 lshift\n;\n: 2\/ ( n -- n\/2 )\n 1 rshift\n;\n\n\n\\ define some useful constants ------------------------------\n1 0= constant FALSE\n0 0= constant TRUE\n32 constant BL\n\n\\ Stack data structure ----------------------------------------\n\\ This is a general purpose stack utility used to implement necessary\n\\ stacks for the compiler or the user. Not real fast.\n\\ These stacks grow up which is different then normal.\n\\ cell 0 - stack pointer, offset from pfa of word\n\\ cell 1 - limit for range checking\n\\ cell 2 - first data location\n\n: :STACK ( #cells -- )\n CREATE 2 cells , ( offset of first data location )\n dup , ( limit for range checking, not currently used )\n cells cell+ allot ( allot an extra cell for safety )\n;\n\n: >STACK ( n stack -- , push onto stack, postincrement )\n dup @ 2dup cell+ swap ! ( -- n stack offset )\n + !\n;\n\n: STACK> ( stack -- n , pop , predecrement )\n dup @ cell- 2dup swap !\n + @\n;\n\n: STACK@ ( stack -- n , copy )\n dup @ cell- + @\n;\n\n: STACK.PICK ( index stack -- n , grab Nth from top of stack )\n dup @ cell- +\n swap cells - \\ offset for index\n @\n;\n: STACKP ( stack -- ptr , to next empty location on stack )\n\tdup @ +\n;\n\n: 0STACKP ( stack -- , clear stack)\n 8 swap !\n;\n\n32 :stack ustack\nustack 0stackp\n\n\\ Define JForth like words.\n: >US ustack >stack ;\n: US> ustack stack> ;\n: US@ ustack stack@ ;\n: 0USP ustack 0stackp ;\n\n\n\n\\ DO LOOP ------------------------------------------------\n\n3 constant do_flag\n4 constant leave_flag\n5 constant ?do_flag\n\n: DO ( -- , loop-back do_flag jump-from ?do_flag )\n ?comp\n compile (do)\n here >us do_flag >us ( for backward branch )\n; immediate\n\n: ?DO ( -- , loop-back do_flag jump-from ?do_flag , on user stack )\n ?comp\n ( leave address to set for forward branch )\n compile (?do)\n here 0 ,\n here >us do_flag >us ( for backward branch )\n >us ( for forward branch ) ?do_flag >us\n; immediate\n\n: LEAVE ( -- addr leave_flag )\n compile (leave)\n here 0 , >us\n leave_flag >us\n; immediate\n\n: LOOP-FORWARD ( -us- jump-from ?do_flag -- )\n BEGIN\n us@ leave_flag =\n us@ ?do_flag =\n OR\n WHILE\n us> leave_flag =\n IF\n us> here over - cell+ swap !\n ELSE\n us> dup\n here swap -\n cell+ swap !\n THEN\n REPEAT\n;\n\n: LOOP-BACK ( loop-addr do_flag -us- )\n us> do_flag ?pairs\n us> here - here\n !\n cell allot\n;\n\n: LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (loop)\n loop-forward loop-back\n; immediate\n\n\\ : DOTEST 5 0 do 333 . loop 888 . ;\n\\ : ?DOTEST0 0 0 ?do 333 . loop 888 . ;\n\\ : ?DOTEST1 5 0 ?do 333 . loop 888 . ;\n\n: +LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (+loop)\n loop-forward loop-back\n; immediate\n\n: UNLOOP ( loop-sys -r- )\n r> \\ save return pointer\n rdrop rdrop\n >r\n;\n\n\n: RECURSE ( ? -- ? , call the word currently being defined )\n latest compile,\n; immediate\n\n: SPACE bl emit ;\n: SPACES 512 min 0 max 0 ?DO space LOOP ;\n: 0SP depth 0 ?do drop loop ;\n\n\\ : >NEWLINE ( -- , CR if needed )\n\\ out @ 0>\n\\ IF cr\n\\ THEN\n\\ ;\n\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 ) swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 ) dup cell+ @ swap @ ;\n\n: DABS ( d -- |d| )\n dup 0<\n IF dnegate\n THEN\n;\n\n: S>D ( s -- d , extend signed single precision to double )\n dup 0<\n IF -1\n ELSE 0\n THEN\n;\n\n: D>S ( d -- s ) drop ;\n\n: PARSE-WORD ( \"name\" -- c-addr u ) bl parse ;\n: \/STRING ( addr len n -- addr' len' ) over min rot over + -rot - ;\n: PLACE ( addr len to -- , move string ) 3dup 1+ swap cmove c! drop ;\n\n: ASCII ( -- char, state smart )\n bl parse drop c@\n state @ 1 =\n IF [compile] literal\n ELSE\n THEN\n; immediate\n\n: CHAR ( -- char , interpret mode ) bl parse drop c@ ;\n: [CHAR] ( -- char , for compile mode )\n char [compile] literal\n; immediate\n\n: $TYPE ( $string -- ) count type ;\n: 'word ( -- addr ) here ;\n\n: EVEN ( addr -- addr' ) dup 1 and + ;\n\n: (C\") ( -- $addr ) r> dup count + aligned >r ;\n: (S\") ( -- c-addr cnt ) r> count 2dup + aligned >r ;\n: (.\") ( -- , type following string ) r> count 2dup + aligned >r type ;\n: \", ( addr len -- , place string into dict ) tuck 'word place 1+ allot align ;\n: ,\" ( -- ) 34 parse \", ;\n\n: .( ( --, type string delimited by parens )\n 41 parse type\n; immediate\n\n: .\" ( -- , type string )\n state @ 1 =\n IF compile (.\") ,\"\n ELSE 34 parse type\n THEN\n; immediate\n\n: .' ( -- , type string delimited by single quote )\n state @\n IF compile (.\") [char] ' parse \",\n ELSE [char] ' parse type\n THEN\n; immediate\n\n: C\" ( -- addr , return string address, ANSI )\n state @\n IF compile (c\") ,\"\n ELSE [char] \" parse pad place pad\n THEN\n; immediate\n\n: S\" ( -- , -- addr , return string address, ANSI )\n state @\n IF compile (s\") ,\"\n ELSE [char] \" parse pad place pad count\n THEN\n; immediate\n\n: \" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n: P\" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n\n\\ : \"\" ( -- addr )\n\\ state @\n\\ IF\n\\ compile (C\")\n\\ bl parse-word \",\n\\ ELSE\n\\ bl parse-word pad place pad\n\\ THEN\n\\ ; immediate\n\n: SLITERAL ( addr cnt -- , compile string )\n\tcompile (S\")\n\t\",\n; IMMEDIATE\n\n: $APPEND ( addr count $1 -- , append text to $1 )\n over >r\n dup >r\n count + ( -- a2 c2 end1 )\n swap cmove\n r> dup c@ ( a1 c1 )\n r> + ( -- a1 totalcount )\n swap c!\n;\n\n\\ ANSI word to replace [COMPILE] and COMPILE ----------------\n\\ : POSTPONE ( -- )\n\\\tbl word find\n\\\tdup 0=\n\\\tIF\n\\\t\t.\" Postpone could not find \" count type cr abort\n\\\tELSE\n\\\t\t0>\n\\\t\tIF compile, \\ immediate\n\\\t\tELSE (compile) \\ normal\n\\\t\tTHEN\n\\\tTHEN\n\\ ; immediate\n\n\\ -----------------------------------------------------------------\n\\ Auto Initialization\n: AUTO.INIT ( -- )\n\\ Kernel finds AUTO.INIT and executes it after loading dictionary.\n\\\t.\" Begin AUTO.INIT ------\" cr\n;\n: AUTO.TERM ( -- )\n\\ Kernel finds AUTO.TERM and executes it on bye.\n\\\t.\" End AUTO.TERM ------\" cr\n;\n\n\n: CLEARSTACK ( i*x -- )\n BEGIN depth\n WHILE drop\n REPEAT ;\n\nvariable pictured_output \\ hidden?\nvariable pictured_output_len \\ hidden?\n\n: <# ( -- ) pad pictured_output ! 0 pictured_output_len ! ;\n: #> ( -- addr n ) drop pictured_output @ pictured_output_len @ ;\n\n: HOLD ( c -- )\n pictured_output @ dup dup 1+ pictured_output_len @ cmove c!\n 1 pictured_output_len +!\n;\n\n\\ ------------------------ INPUT -------------------------------\n\n: SIGN ( n -- ) < 0 IF 45 hold THEN\n;\n\n: DIGIT ( n -- ascii )\n dup 10 < IF 48 ELSE 87 THEN + ;\n\n: # ( n -- n )\n base @ \/mod swap digit hold ;\n\n: #S ( n -- )\n BEGIN base @ \/mod dup\n WHILE swap digit hold\n REPEAT\n digit hold ;","old_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\\n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n\n: COUNT dup 1+ swap c@ ;\n\n\\ Miscellaneous support words\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: <= ( a b -- f , true if A <= b ) > 0= ;\n: >= ( a b -- f , true if A >= b ) < 0= ;\n: NOT ( n -- !n , logical negation ) 0= ;\n: DNEGATE ( d -- -d , negate by doing 0-d )\n 0 swap -\n;\n: CELL+ ( n -- n+cell ) cell + ;\n: CELL- ( n -- n-cell ) cell - ;\n: CELL* ( n -- n*cell ) cells ;\n\n: CHAR+ ( n -- n+size_of_char ) 1+ ;\n\\ : CHARS ( n -- n*size_of_char, don't do anything ) ; immediate\n\n\\ useful stack manipulation words\n: -ROT ( a b c -- c a b ) rot rot ;\n: 3DUP ( a b c -- a b c a b c ) 2 pick 2 pick 2 pick ;\n\n\\ ------------------------------------------------------------------\n: ID. ( nfa -- ) count 31 and type ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: PAD ( -- addr ) here 128 + ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n\n: BETWEEN ( n lo hi -- flag , true if between lo & hi )\n >r over r> > >r\n < r> or 0=\n;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: ? ( -- ) @ . ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ ' (lit) , cell 1- , ] +\n [ ' (lit) , cell 1- invert , ] and ;\n\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n: ALLOT ( nbytes -- , allot space in dictionary ) dp +! align ;\n\n: C, ( c -- ) here c! 1 dp +! ;\n\\ : W, ( w -- ) dp @ even-up dup dp ! w! 2 dp +! ;\n\\ : , ( n -- , lay into dictionary ) align here ! cell allot ;\n\n: SEE ( -- )\n ' dup\n 16 + @ \\ offset in execution token for alloc size\n cells swap >body swap\n disassemble ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token )\n [compile] literal ( compile a call to literal )\n ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n: :NONAME ( -- xt , begin compilation of headerless secondary ) align here ] ;\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick )\n ?comp ' [compile] literal\n; immediate\n\n\n: (DOES>) ( xt -- , modify previous definition to execute code at xt )\n latest >body \\ get address of code for new word\n cell + \\ offset to second cell in create word\n ! \\ store execution token of DOES> code in new word\n;\n\n: DOES> ( -- , define execution code for CREATE word )\n 0 [compile] literal \\ dummy literal to hold xt\n here cell- \\ address of zero in literal\n compile (does>) \\ call (DOES>) from new creation word\n\t\t>r \\ move addrz to return stack so ; doesn't see stack garbage\n [compile] ; \\ terminate part of code before does>\n\t\tr>\n :noname ( addrz xt )\n swap ! \\ save execution token in literal\n; immediate\n\n0 1- constant -1\n0 2- constant -2\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 )\n swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 )\n dup cell+ @ swap @ ;\n\n: 2* ( n -- n*2 )\n 1 lshift\n;\n: 2\/ ( n -- n\/2 )\n 1 rshift\n;\n\n\n\\ define some useful constants ------------------------------\n1 0= constant FALSE\n0 0= constant TRUE\n32 constant BL\n\n\\ Stack data structure ----------------------------------------\n\\ This is a general purpose stack utility used to implement necessary\n\\ stacks for the compiler or the user. Not real fast.\n\\ These stacks grow up which is different then normal.\n\\ cell 0 - stack pointer, offset from pfa of word\n\\ cell 1 - limit for range checking\n\\ cell 2 - first data location\n\n: :STACK ( #cells -- )\n CREATE 2 cells , ( offset of first data location )\n dup , ( limit for range checking, not currently used )\n cells cell+ allot ( allot an extra cell for safety )\n;\n\n: >STACK ( n stack -- , push onto stack, postincrement )\n dup @ 2dup cell+ swap ! ( -- n stack offset )\n + !\n;\n\n: STACK> ( stack -- n , pop , predecrement )\n dup @ cell- 2dup swap !\n + @\n;\n\n: STACK@ ( stack -- n , copy )\n dup @ cell- + @\n;\n\n: STACK.PICK ( index stack -- n , grab Nth from top of stack )\n dup @ cell- +\n swap cells - \\ offset for index\n @\n;\n: STACKP ( stack -- ptr , to next empty location on stack )\n\tdup @ +\n;\n\n: 0STACKP ( stack -- , clear stack)\n 8 swap !\n;\n\n32 :stack ustack\nustack 0stackp\n\n\\ Define JForth like words.\n: >US ustack >stack ;\n: US> ustack stack> ;\n: US@ ustack stack@ ;\n: 0USP ustack 0stackp ;\n\n\n\n\\ DO LOOP ------------------------------------------------\n\n3 constant do_flag\n4 constant leave_flag\n5 constant ?do_flag\n\n: DO ( -- , loop-back do_flag jump-from ?do_flag )\n ?comp\n compile (do)\n here >us do_flag >us ( for backward branch )\n; immediate\n\n: ?DO ( -- , loop-back do_flag jump-from ?do_flag , on user stack )\n ?comp\n ( leave address to set for forward branch )\n compile (?do)\n here 0 ,\n here >us do_flag >us ( for backward branch )\n >us ( for forward branch ) ?do_flag >us\n; immediate\n\n: LEAVE ( -- addr leave_flag )\n compile (leave)\n here 0 , >us\n leave_flag >us\n; immediate\n\n: LOOP-FORWARD ( -us- jump-from ?do_flag -- )\n BEGIN\n us@ leave_flag =\n us@ ?do_flag =\n OR\n WHILE\n us> leave_flag =\n IF\n us> here over - cell+ swap !\n ELSE\n us> dup\n here swap -\n cell+ swap !\n THEN\n REPEAT\n;\n\n: LOOP-BACK ( loop-addr do_flag -us- )\n us> do_flag ?pairs\n us> here - here\n !\n cell allot\n;\n\n: LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (loop)\n loop-forward loop-back\n; immediate\n\n\\ : DOTEST 5 0 do 333 . loop 888 . ;\n\\ : ?DOTEST0 0 0 ?do 333 . loop 888 . ;\n\\ : ?DOTEST1 5 0 ?do 333 . loop 888 . ;\n\n: +LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (+loop)\n loop-forward loop-back\n; immediate\n\n: UNLOOP ( loop-sys -r- )\n r> \\ save return pointer\n rdrop rdrop\n >r\n;\n\n\n: RECURSE ( ? -- ? , call the word currently being defined )\n latest compile,\n; immediate\n\n: SPACE bl emit ;\n: SPACES 512 min 0 max 0 ?DO space LOOP ;\n: 0SP depth 0 ?do drop loop ;\n\n\\ : >NEWLINE ( -- , CR if needed )\n\\ out @ 0>\n\\ IF cr\n\\ THEN\n\\ ;\n\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 ) swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 ) dup cell+ @ swap @ ;\n\n: DABS ( d -- |d| )\n dup 0<\n IF dnegate\n THEN\n;\n\n: S>D ( s -- d , extend signed single precision to double )\n dup 0<\n IF -1\n ELSE 0\n THEN\n;\n\n: D>S ( d -- s ) drop ;\n\n: \/STRING ( addr len n -- addr' len' ) over min rot over + -rot - ;\n: PLACE ( addr len to -- , move string ) 3dup 1+ swap cmove c! drop ;\n\n: ASCII ( -- char, state smart )\n bl parse drop c@\n state @ 1 =\n IF [compile] literal\n ELSE\n THEN\n; immediate\n\n: CHAR ( -- char , interpret mode ) bl parse drop c@ ;\n: [CHAR] ( -- char , for compile mode )\n char [compile] literal\n; immediate\n\n: $TYPE ( $string -- ) count type ;\n: 'word ( -- addr ) here ;\n\n: EVEN ( addr -- addr' ) dup 1 and + ;\n\n: (C\") ( -- $addr ) r> dup count + aligned >r ;\n: (S\") ( -- c-addr cnt ) r> count 2dup + aligned >r ;\n: (.\") ( -- , type following string ) r> count 2dup + aligned >r type ;\n: \", ( addr len -- , place string into dict ) tuck 'word place 1+ allot align ;\n: ,\" ( -- ) 34 parse \", ;\n\n: .( ( --, type string delimited by parens )\n 41 parse type\n; immediate\n\n: .\" ( -- , type string )\n state @ 1 =\n IF compile (.\") ,\"\n ELSE 34 parse type\n THEN\n; immediate\n\n: .' ( -- , type string delimited by single quote )\n state @\n IF compile (.\") [char] ' parse \",\n ELSE [char] ' parse type\n THEN\n; immediate\n\n: C\" ( -- addr , return string address, ANSI )\n state @\n IF compile (c\") ,\"\n ELSE [char] \" parse pad place pad\n THEN\n; immediate\n\n: S\" ( -- , -- addr , return string address, ANSI )\n state @\n IF compile (s\") ,\"\n ELSE [char] \" parse pad place pad count\n THEN\n; immediate\n\n: \" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n: P\" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n\n\\ : \"\" ( -- addr )\n\\ state @\n\\ IF\n\\ compile (C\")\n\\ bl parse-word \",\n\\ ELSE\n\\ bl parse-word pad place pad\n\\ THEN\n\\ ; immediate\n\n: SLITERAL ( addr cnt -- , compile string )\n\tcompile (S\")\n\t\",\n; IMMEDIATE\n\n: $APPEND ( addr count $1 -- , append text to $1 )\n over >r\n dup >r\n count + ( -- a2 c2 end1 )\n swap cmove\n r> dup c@ ( a1 c1 )\n r> + ( -- a1 totalcount )\n swap c!\n;\n\n\\ ANSI word to replace [COMPILE] and COMPILE ----------------\n\\ : POSTPONE ( -- )\n\\\tbl word find\n\\\tdup 0=\n\\\tIF\n\\\t\t.\" Postpone could not find \" count type cr abort\n\\\tELSE\n\\\t\t0>\n\\\t\tIF compile, \\ immediate\n\\\t\tELSE (compile) \\ normal\n\\\t\tTHEN\n\\\tTHEN\n\\ ; immediate\n\n\\ -----------------------------------------------------------------\n\\ Auto Initialization\n: AUTO.INIT ( -- )\n\\ Kernel finds AUTO.INIT and executes it after loading dictionary.\n\\\t.\" Begin AUTO.INIT ------\" cr\n;\n: AUTO.TERM ( -- )\n\\ Kernel finds AUTO.TERM and executes it on bye.\n\\\t.\" End AUTO.TERM ------\" cr\n;\n\n\n: CLEARSTACK ( i*x -- )\n BEGIN depth\n WHILE drop\n REPEAT ;\n\nvariable pictured_output \\ hidden?\nvariable pictured_output_len \\ hidden?\n\n: <# ( -- ) pad pictured_output ! 0 pictured_output_len ! ;\n: #> ( -- addr n ) drop pictured_output @ pictured_output_len @ ;\n\n: HOLD ( c -- )\n pictured_output @ dup dup 1+ pictured_output_len @ cmove c!\n 1 pictured_output_len +!\n;\n\n\\ ------------------------ INPUT -------------------------------\n\n: SIGN ( n -- ) < 0 IF 45 hold THEN\n;\n\n: DIGIT ( n -- ascii )\n dup 10 < IF 48 ELSE 87 THEN + ;\n\n: # ( n -- n )\n base @ \/mod swap digit hold ;\n\n: #S ( n -- )\n BEGIN base @ \/mod dup\n WHILE swap digit hold\n REPEAT\n digit hold ;","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"00353796c25c23ed227493c1ac601deaa5899e87","subject":"Clarify test - address units must be ALIGNED","message":"Clarify test - address units must be ALIGNED\n","repos":"rm-hull\/byok3,rm-hull\/byok3","old_file":"core\/src\/test\/resources\/forth\/F3.11_memory.fth","new_file":"core\/src\/test\/resources\/forth\/F3.11_memory.fth","new_contents":"\\ ------------------------------------------------------------------------\nTESTING HERE , @ ! CELL+ CELLS C, C@ C! CHARS 2@ 2! ALIGN ALIGNED +! ALLOT\n\nHERE 1 ALLOT\nHERE\nCONSTANT 2NDA\nCONSTANT 1STA\n{ 1STA 2NDA U< -> } \\ HERE MUST GROW WITH ALLOT\n{ 1STA 1+ ALIGNED -> 2NDA } \\ ... BY ONE ADDRESS UNIT\n( MISSING TEST: NEGATIVE ALLOT )\n\nHERE 1 ,\nHERE 2 ,\nCONSTANT 2ND\nCONSTANT 1ST\n{ 1ST 2ND U< -> } \\ HERE MUST GROW WITH ALLOT\n{ 1ST CELL+ -> 2ND } \\ ... BY ONE CELL\n{ 1ST 1 CELLS + -> 2ND }\n{ 1ST @ 2ND @ -> 1 2 }\n{ 5 1ST ! -> }\n{ 1ST @ 2ND @ -> 5 2 }\n{ 6 2ND ! -> }\n{ 1ST @ 2ND @ -> 5 6 }\n{ 1ST 2@ -> 6 5 }\n{ 2 1 1ST 2! -> }\n{ 1ST 2@ -> 2 1 }\n{ 1S 1ST ! 1ST @ -> 1S } \\ CAN STORE CELL-WIDE VALUE\n\nHERE 1 C,\nHERE 2 C,\nCONSTANT 2NDC\nCONSTANT 1STC\n{ 1STC 2NDC U< -> } \\ HERE MUST GROW WITH ALLOT\n{ 1STC CHAR+ -> 2NDC } \\ ... BY ONE CHAR\n{ 1STC 1 CHARS + -> 2NDC }\n{ 1STC C@ 2NDC C@ -> 1 2 }\n{ 3 1STC C! -> }\n{ 1STC C@ 2NDC C@ -> 3 2 }\n{ 4 2NDC C! -> }\n{ 1STC C@ 2NDC C@ -> 3 4 }\n\nALIGN 1 ALLOT HERE ALIGN HERE 3 CELLS ALLOT\nCONSTANT A-ADDR CONSTANT UA-ADDR\n{ UA-ADDR ALIGNED -> A-ADDR }\n{ 1 A-ADDR C! A-ADDR C@ -> 1 }\n{ 1234 A-ADDR ! A-ADDR @ -> 1234 }\n{ 123 456 A-ADDR 2! A-ADDR 2@ -> 123 456 }\n{ 2 A-ADDR CHAR+ C! A-ADDR CHAR+ C@ -> 2 }\n{ 3 A-ADDR CELL+ C! A-ADDR CELL+ C@ -> 3 }\n{ 1234 A-ADDR CELL+ ! A-ADDR CELL+ @ -> 1234 }\n{ 123 456 A-ADDR CELL+ 2! A-ADDR CELL+ 2@ -> 123 456 }\n\n: BITS ( X -- U )\n 0 SWAP BEGIN DUP WHILE DUP MSB AND IF >R 1+ R> THEN 2* REPEAT DROP ;\n( CHARACTERS >= 1 AU, <= SIZE OF CELL, >= 8 BITS )\n{ 1 CHARS 1 < -> }\n{ 1 CHARS 1 CELLS > -> }\n( TBD: HOW TO FIND NUMBER OF BITS? )\n\n( CELLS >= 1 AU, INTEGRAL MULTIPLE OF CHAR SIZE, >= 16 BITS )\n{ 1 CELLS 1 < -> }\n{ 1 CELLS 1 CHARS MOD -> 0 }\n{ 1S BITS 10 < -> }\n\n{ 0 1ST ! -> }\n{ 1 1ST +! -> }\n{ 1ST @ -> 1 }\n{ -1 1ST +! 1ST @ -> 0 }","old_contents":"\\ ------------------------------------------------------------------------\nTESTING HERE , @ ! CELL+ CELLS C, C@ C! CHARS 2@ 2! ALIGN ALIGNED +! ALLOT\n\nHERE 1 ALLOT\nHERE\nCONSTANT 2NDA\nCONSTANT 1STA\n{ 1STA 2NDA U< -> }\t\t\\ HERE MUST GROW WITH ALLOT\n{ 1STA 1+ -> 2NDA }\t\t\t\\ ... BY ONE ADDRESS UNIT\n( MISSING TEST: NEGATIVE ALLOT )\n\nHERE 1 ,\nHERE 2 ,\nCONSTANT 2ND\nCONSTANT 1ST\n{ 1ST 2ND U< -> } \\ HERE MUST GROW WITH ALLOT\n{ 1ST CELL+ -> 2ND } \\ ... BY ONE CELL\n{ 1ST 1 CELLS + -> 2ND }\n{ 1ST @ 2ND @ -> 1 2 }\n{ 5 1ST ! -> }\n{ 1ST @ 2ND @ -> 5 2 }\n{ 6 2ND ! -> }\n{ 1ST @ 2ND @ -> 5 6 }\n{ 1ST 2@ -> 6 5 }\n{ 2 1 1ST 2! -> }\n{ 1ST 2@ -> 2 1 }\n{ 1S 1ST ! 1ST @ -> 1S } \\ CAN STORE CELL-WIDE VALUE\n\nHERE 1 C,\nHERE 2 C,\nCONSTANT 2NDC\nCONSTANT 1STC\n{ 1STC 2NDC U< -> } \\ HERE MUST GROW WITH ALLOT\n{ 1STC CHAR+ -> 2NDC } \\ ... BY ONE CHAR\n{ 1STC 1 CHARS + -> 2NDC }\n{ 1STC C@ 2NDC C@ -> 1 2 }\n{ 3 1STC C! -> }\n{ 1STC C@ 2NDC C@ -> 3 2 }\n{ 4 2NDC C! -> }\n{ 1STC C@ 2NDC C@ -> 3 4 }\n\nALIGN 1 ALLOT HERE ALIGN HERE 3 CELLS ALLOT\nCONSTANT A-ADDR CONSTANT UA-ADDR\n{ UA-ADDR ALIGNED -> A-ADDR }\n{ 1 A-ADDR C! A-ADDR C@ -> 1 }\n{ 1234 A-ADDR ! A-ADDR @ -> 1234 }\n{ 123 456 A-ADDR 2! A-ADDR 2@ -> 123 456 }\n{ 2 A-ADDR CHAR+ C! A-ADDR CHAR+ C@ -> 2 }\n{ 3 A-ADDR CELL+ C! A-ADDR CELL+ C@ -> 3 }\n{ 1234 A-ADDR CELL+ ! A-ADDR CELL+ @ -> 1234 }\n{ 123 456 A-ADDR CELL+ 2! A-ADDR CELL+ 2@ -> 123 456 }\n\n: BITS ( X -- U )\n 0 SWAP BEGIN DUP WHILE DUP MSB AND IF >R 1+ R> THEN 2* REPEAT DROP ;\n( CHARACTERS >= 1 AU, <= SIZE OF CELL, >= 8 BITS )\n{ 1 CHARS 1 < -> }\n{ 1 CHARS 1 CELLS > -> }\n( TBD: HOW TO FIND NUMBER OF BITS? )\n\n( CELLS >= 1 AU, INTEGRAL MULTIPLE OF CHAR SIZE, >= 16 BITS )\n{ 1 CELLS 1 < -> }\n{ 1 CELLS 1 CHARS MOD -> 0 }\n{ 1S BITS 10 < -> }\n\n{ 0 1ST ! -> }\n{ 1 1ST +! -> }\n{ 1ST @ -> 1 }\n{ -1 1ST +! 1ST @ -> 0 }","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"4d829020b381879f6372371cca29e589e5dc1719","subject":"Create take up 4 cells for initialization, so actually HERE + 4 == >BODY","message":"Create take up 4 cells for initialization, so actually HERE + 4 == >BODY\n","repos":"rm-hull\/byok3,rm-hull\/byok3","old_file":"core\/src\/test\/resources\/forth\/F3.16_defining_words.fth","new_file":"core\/src\/test\/resources\/forth\/F3.16_defining_words.fth","new_contents":"\\ ------------------------------------------------------------------------\nTESTING DEFINING WORDS: : ; CONSTANT VARIABLE CREATE DOES> >BODY\n\n{ 123 CONSTANT X123 -> }\n{ X123 -> 123 }\n{ : EQU CONSTANT ; -> }\n{ X123 EQU Y123 -> }\n{ Y123 -> 123 }\n\n{ VARIABLE V1 -> }\n{ 123 V1 ! -> }\n{ V1 @ -> 123 }\n\n{ : NOP : POSTPONE ; ; -> }\n{ NOP NOP1 NOP NOP2 -> }\n{ NOP1 -> }\n{ NOP2 -> }\n\n{ : DOES1 DOES> @ 1 + ; -> }\n{ : DOES2 DOES> @ 2 + ; -> }\n{ CREATE CR1 -> }\n{ CR1 -> HERE }\n{ ' CR1 >BODY 4 CELLS + -> HERE }\n{ 1 , -> }\n{ CR1 @ -> 1 }\n{ DOES1 -> }\n{ CR1 -> 2 }\n{ DOES2 -> }\n{ CR1 -> 3 }\n\n{ : WEIRD: CREATE DOES> 1 + DOES> 2 + ; -> }\n{ WEIRD: W1 -> }\n{ ' W1 >BODY 4 CELLS + -> HERE }\n{ W1 -> HERE 1 + }\n{ W1 -> HERE 2 + }\n","old_contents":"\\ ------------------------------------------------------------------------\nTESTING DEFINING WORDS: : ; CONSTANT VARIABLE CREATE DOES> >BODY\n\n{ 123 CONSTANT X123 -> }\n{ X123 -> 123 }\n{ : EQU CONSTANT ; -> }\n{ X123 EQU Y123 -> }\n{ Y123 -> 123 }\n\n{ VARIABLE V1 -> }\n{ 123 V1 ! -> }\n{ V1 @ -> 123 }\n\n{ : NOP : POSTPONE ; ; -> }\n{ NOP NOP1 NOP NOP2 -> }\n{ NOP1 -> }\n{ NOP2 -> }\n\n{ : DOES1 DOES> @ 1 + ; -> }\n{ : DOES2 DOES> @ 2 + ; -> }\n{ CREATE CR1 -> }\n{ CR1 -> HERE }\n{ ' CR1 >BODY -> HERE }\n{ 1 , -> }\n{ CR1 @ -> 1 }\n{ DOES1 -> }\n{ CR1 -> 2 }\n{ DOES2 -> }\n{ CR1 -> 3 }\n\n{ : WEIRD: CREATE DOES> 1 + DOES> 2 + ; -> }\n{ WEIRD: W1 -> }\n{ ' W1 >BODY -> HERE }\n{ W1 -> HERE 1 + }\n{ W1 -> HERE 2 + }\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"8fc320d242934e5ab6f7d0db27b16b5d570c53c4","subject":"A working dual-timescale clock demo.","message":"A working dual-timescale clock demo.","repos":"rbsexton\/gecko,rbsexton\/gecko,rbsexton\/gecko","old_file":"tiny\/basic\/forth\/startup.fth","new_file":"tiny\/basic\/forth\/startup.fth","new_contents":"(( App Startup ))\n\n0 value JT \\ The Jumptable\n\n\\ -------------------------------------------\n\\ The word that sets everything up.\n\\ This runs before the intro banner, after\n\\ Init-multi.\n\\ -------------------------------------------\n: StartApp\n\thex\n\tinit-dp @ dp ! \\ Set the dictionary pointer so that we can function.\n\t\\ I have no idea why I am doing this instead of the compilation system.\n\n\t1 getruntimelinks to jt\n\t.\" StartApp!\" \n\n\t4 [ SCSSCR _SCS + ] literal ! \\ Set deepsleep\n\t\t\t\n;\n\n\\ ------------------------------------------\n\\ Application code\n\\ ------------------------------------------\nstruct tod\n 1 field h\n 1 field m\n 1 field s\nend-struct\n \nudata\ncreate hms tod allot\ncreate dhms tod allot\ncdata\n\n: +CAP ( n max -- n ) >R 1 + dup r> = if drop 0 then ; \n\n: ADVANCE ( tod -- )\n dup s c@ #60 +cap 2dup swap s c! \\ Advance the seconds. base n -- \n if drop exit then\n \n dup m c@ #60 +cap 2dup swap m c! \\ advance minutes\n if drop exit then\n\n dup h c@ #24 +cap 2dup swap h c! \\ advance minutes\n\n 2drop \n;\n\n: DADVANCE ( tod -- )\n dup s c@ #100 +cap 2dup swap s c! \\ Advance the seconds. base n -- \n if drop exit then\n \n dup m c@ #100 +cap 2dup swap m c! \\ advance minutes\n if drop exit then\n\n dup h c@ #10 +cap 2dup swap h c! \\ advance minutes\n\n 2drop \n;\n\n\\ ----------------------------------------------\n\\ Tools for writing to the LCD\n\\ ----------------------------------------------\n: LCD#! ( n -- ) jt LCD_# @ swap call1-- ;\n: LCD$! ( addr -- ) jt LCD_Wr @ swap call1-- ; \n\nvariable thecount\n\n(( Sample code for demonstrating messages ))\n: wakestart 1 $10 wakereq drop ; \\ Request a wake \n: wakestop 1 0 wakereq drop ; \\ No more, please. \n\n: COUNT-WORD\n wakestart\n begin\n pause\n thecount dup @ 1+ dup lcd#! swap ! \n stop \n again\n;\n\n: COUNT-WORDd\n begin\n pause self msg? if get-message drop \\ We don't care who sent it.\n case \n 0 of wakestop endof\n 1 of wakestart endof\n endcase\n then\n\n thecount dup @ 1+ dup lcd#! swap ! \n stop \n again\n;\n\n\\ --------------------------------------------------------------------\n\\ Keeping time.\n\\ --------------------------------------------------------------------\ntask TOPTASK \n\n: TOPLCDOUT hms dup h c@ #100 * swap m c@ + lcd#! ; \n\n: TOPWORD\n 0 $10 wakereq drop \\ The first Second. \n begin\n pause\n toplcdout \n hms advance\n 2 $10 wakereq drop \\ Relative step\n again\n; \n\n\n\\ --------------------------------------------------------------------\n\\ Decimal Time\n\\ --------------------------------------------------------------------\n\ntask BOTTASK\n\n: BOTWORD\n 1 err interp-next wakereq drop \n begin\n pause\n dhms dadvance\n botlcd dms$ drop lcd$!\n 3 err interp-next wakereq drop \n again\n; \n\n: BOTLCD dhms\n dup h c@ #1000 *\n over m c@ #100 * +\n swap s c@ + ;\n\n\\ Include the terminating null.\n: dms$ base @ >R decimal s>d <# 0 hold # # $20 hold # # $20 hold # #> R> base ! ; \n\n: interp-next ( addr -- ) \\ A fixed version. Returns amount to step\n dup @ \\ err\n #103 - dup 1 > if swap ! #13 exit then\n \\ Otherwise, we need to adjust\n #125 + swap ! #14 \n;\n\n: CLOCKSTART\n ['] topword toptask initiate\n ['] botword bottask initiate \n;\n\nvariable err \n\n: COUNT-DT\n 0 err interp-next wakereq drop \\ Don't keep the return code.\n begin \n pause\n thecount dup @ 1 #9999 +cap dup lcd#! swap ! \n 2 err interp-next wakereq drop \\ Don't keep the return code. \n again\n;\n\n\n\n\n((\ntask foo \n' count-word foo initiate\n\n\n\n\n))\n\n \n\n\n","old_contents":"(( App Startup ))\n\n0 value JT \\ The Jumptable\n\n\\ -------------------------------------------\n\\ The word that sets everything up.\n\\ This runs before the intro banner, after\n\\ Init-multi.\n\\ -------------------------------------------\n: StartApp\n\thex\n\tinit-dp @ dp ! \\ Set the dictionary pointer so that we can function.\n\t\\ I have no idea why I am doing this instead of the compilation system.\n\n\t1 getruntimelinks to jt\n\t.\" StartApp!\" \n\n\t4 [ SCSSCR _SCS + ] literal ! \\ Set deepsleep\n\t\t\t\n;\n\n\\ ------------------------------------------\n\\ Application code\n\\ ------------------------------------------\nstruct tod\n 1 field h\n 1 field m\n 1 field s\nend-struct\n \nudata\ncreate hms tod allot\ncdata\n\n: +CAP ( n max -- n ) >R 1 + dup r> = if drop 0 then ; \n\n: ADVANCE ( tod -- )\n dup s c@ #60 +cap 2dup swap s c! \\ Advance the seconds. base n -- \n if drop exit then\n \n dup m c@ #60 +cap 2dup swap m c! \\ advance minutes\n if drop exit then\n\n dup h c@ #24 +cap 2dup swap h c! \\ advance minutes\n\n 2drop \n;\n\n\\ ----------------------------------------------\n\\ Tools for writing to the LCD\n\\ ----------------------------------------------\n: LCD#! ( n -- ) jt LCD_# @ swap call1-- ;\nvariable thecount\n\n: wakestart 1 $10 wakereq drop ; \\ Request a wake \n: wakestop 1 0 wakereq drop ; \\ No more, please. \n\n: COUNT-WORD\n wakestart\n begin\n pause\n thecount dup @ 1+ dup lcd#! swap ! \n stop \n again\n;\n\n: COUNT-WORDd\n begin\n pause self msg? if get-message drop \\ We don't care who sent it.\n case \n 0 of wakestop endof\n 1 of wakestart endof\n endcase\n then\n\n thecount dup @ 1+ dup lcd#! swap ! \n stop \n again\n;\n\n: interp-next ( addr -- ) \\ A fixed version. Returns amount to step\n dup @ \\ err\n #103 - dup 1 > if swap ! #13 exit then\n \\ Otherwise, we need to adjust\n #125 + swap ! #14 \n;\n\nvariable err \n\n: COUNT-DT\n begin \n 0 err interp-next wakereq drop \\ Don't keep the return code. \n pause\n thecount dup @ 1+ dup lcd#! swap ! \n again\n;\n\n((\ntask foo \n' count-word foo initiate\n\n\n\n\n))\n\n \n\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"8dce81f919abc01b348eed09bf78f768d1840aff","subject":"Don't be so strict about true = -1 ","message":"Don't be so strict about true = -1 ","repos":"rbsexton\/sockpuppet,rbsexton\/sockpuppet","old_file":"forth\/serCM3_sapi_p.fth","new_file":"forth\/serCM3_sapi_p.fth","new_contents":"\\ serCM3_sapi_p.fth - SAPI polled RX, polled TX, serial communication drivers\r\n\\ Written to run against the SockPuppet API.\r\n\r\n((\r\n\r\nAdapted from: the LPC polled driver.\r\n\r\n))\r\n\r\nonly forth definitions\r\n\r\n\r\n\\ ==============\r\n\\ *! serCM3_sapi_p\r\n\\ *T SAPI polled serial driver\r\n\\ ==============\r\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\r\n\\ ** using the internal UARTs via the SAPI. \r\n\r\n\r\n\\ ****************\r\n\\ *S Configuration\r\n\\ ****************\r\n\\ *P Configuration is managed by the SAPI\r\n\r\n\\ ********\r\n\\ *S Tools\r\n\\ ********\r\n\r\ntarget\r\n\r\n\\ ********************\r\n\\ *S Serial primitives\r\n\\ ********************\r\n\r\ninternal\r\n\r\n: +FaultConsole\t( -- ) ;\r\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\r\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\r\n\\ ** for more details.\r\n\r\ntarget\r\n\r\nCODE (seremitfc)\t\\ char base --\r\n\\ *G Service call for a single char - just fill in the registers\r\n\\ from the stack and make the call, and get back the flow control feedback\r\n\\ Put TOS into r0, pull r1 off the stack, and refresh the stack.\r\n\tmov r0, tos\r\n\tldr r1, [ psp ], # 4\t\r\n\tsvc # 2\r\n\tmov tos, r0\r\n next,\r\nEND-CODE\r\n\r\n: (seremit)\t\\ char base -- \r\n\\ *G Wrapped call that checks for throttling, and if so,\r\n\\ calls PAUSE to let another task run.\r\n\t(seremitfc)\r\n\t0<> IF PAUSE THEN\r\n\t;\r\n\r\n: (sertype)\t\\ caddr len base --\r\n\\ *G Transmit a string on the given UART.\r\n -rot bounds\r\n ?do i c@ over (seremit) loop\r\n drop\r\n;\r\n\r\n: (sercr)\t\\ base --\r\n\\ *G Transmit a CR\/LF pair on the given UART.\r\n $0D over (seremit) $0A swap (seremit)\r\n;\r\n\r\nCODE (sergetchar) \\ base -- c\r\n\\ *G Get a character from the port\r\n\tmov r0, tos\t\r\n\tsvc # 3\r\n\tmov tos, r0\r\n\tnext,\r\nEND-CODE\r\n\r\nCODE (serkey?) \\ base -- t\/f\r\n\\ *G Return true if the given UART has a character avilable to read.\r\n\\ The call returns 0 or 1. If 1, subtract 2.\r\n\tmov r0, tos\r\n\tsvc # 4\t\t\r\n\tmov tos, r0\r\n\tnext,\t\r\nEND-CODE\r\n\r\n: (serkey)\t\\ base -- char\r\n\\ *G Wait for a character to come available on the given UART and\r\n\\ ** return the character.\r\n begin\r\n[ tasking? ] [if] pause [else] wfi [then] \r\n dup (serkey?)\r\n until\r\n (sergetchar) \r\n;\r\n\r\nexternal \r\n\r\n: seremit0\t\\ char --\r\n\\ *G Transmit a character on UART0.\r\n 0 (seremit) ;\r\n: sertype0\t\\ c-addr len --\r\n\\ *G Transmit a string on UART0.\r\n 0 (sertype) ;\r\n: sercr0\t\\ --\r\n\\ *G Issue a CR\/LF pair to UART0.\r\n 0 (sercr) ;\r\n: serkey?0\t\\ -- flag\r\n\\ *G Return true if UART0 has a character available.\r\n 0 (serkey?) ;\r\n: serkey0\t\\ -- char\r\n\\ *G Wait for a character on UART0.\r\n 0 (serkey) ;\r\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\r\n\\ *G Generic I\/O device for UART0.\r\n ' serkey0 ,\t\t\\ -- char ; receive char\r\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\r\n ' seremit0 ,\t\t\\ -- char ; display char\r\n ' sertype0 ,\t\t\\ caddr len -- ; display string\r\n ' sercr0 ,\t\t\\ -- ; display new line\r\n\r\n\\ UART1\r\n: seremit1 #1 (seremit) ;\r\n: sertype1\t#1 (sertype) ;\r\n: sercr1\t#1 (sercr) ;\r\n: serkey?1\t#1 (serkey?) ;\r\n: serkey1\t#1 (serkey) ;\r\ncreate Console1 ' serkey1 , ' serkey?1 , ' seremit1 , ' sertype1 , ' sercr1 ,\t\r\n\r\n\\ UART2\r\n: seremit2 #2 (seremit) ;\r\n: sertype2\t#2 (sertype) ;\r\n: sercr2\t#2 (sercr) ;\r\n: serkey?2\t#2 (serkey?) ;\r\n: serkey2\t#2 (serkey) ;\r\ncreate Console2 ' serkey2 , ' serkey?2 , ' seremit2 , ' sertype2 , ' sercr2 ,\t\r\n\r\n\\ Versions for use with the TCP Port (10)\r\n: seremit10 #10 (seremit) ;\r\n: sertype10\t#10 (sertype) ;\r\n: sercr10\t#10 (sercr) ;\r\n: serkey?10\t#10 (serkey?) ;\r\n: serkey10\t#10 (serkey) ;\r\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\r\n\r\nconsole-port 0 = [if]\r\n console0 constant console\r\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\r\n\\ ** It may be changed by one of the phrases of the form:\r\n\\ *C dup opvec ! ipvec !\r\n\\ *C SetConsole\r\n[then]\r\n\r\nconsole-port #2 = [if]\r\n console2 constant console\r\n[then]\r\n\r\nconsole-port #10 = [if]\r\n console10 constant console\r\n[then]\r\n\r\n\\ ************************\r\n\\ *S System initialisation\r\n\\ ************************\r\n\r\n\\ This is a NOP in the SAPI environment\r\n: init-ser ;\t\\ --\r\n\\ *G Initialise all serial ports\r\n\r\n\r\n\\ ======\r\n\\ *> ###\r\n\\ ======\r\n\r\ndecimal\r\n","old_contents":"\\ serCM3_sapi_p.fth - SAPI polled RX, polled TX, serial communication drivers\r\n\\ Written to run against the SockPuppet API.\r\n\r\n((\r\n\r\nAdapted from: the LPC polled driver.\r\n\r\n))\r\n\r\nonly forth definitions\r\n\r\n\r\n\\ ==============\r\n\\ *! serCM3_sapi_p\r\n\\ *T SAPI polled serial driver\r\n\\ ==============\r\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\r\n\\ ** using the internal UARTs via the SAPI. \r\n\r\n\r\n\\ ****************\r\n\\ *S Configuration\r\n\\ ****************\r\n\\ *P Configuration is managed by the SAPI\r\n\r\n\\ ********\r\n\\ *S Tools\r\n\\ ********\r\n\r\ntarget\r\n\r\n\\ ********************\r\n\\ *S Serial primitives\r\n\\ ********************\r\n\r\ninternal\r\n\r\n: +FaultConsole\t( -- ) ;\r\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\r\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\r\n\\ ** for more details.\r\n\r\ntarget\r\n\r\nCODE (seremitfc)\t\\ char base --\r\n\\ *G Service call for a single char - just fill in the registers\r\n\\ from the stack and make the call, and get back the flow control feedback\r\n\\ Put TOS into r0, pull r1 off the stack, and refresh the stack.\r\n\tmov r0, tos\r\n\tldr r1, [ psp ], # 4\t\r\n\tsvc # 2\r\n\tmov tos, r0\r\n next,\r\nEND-CODE\r\n\r\n: (seremit)\t\\ char base -- \r\n\\ *G Wrapped call that checks for throttling, and if so,\r\n\\ calls PAUSE to let another task run.\r\n\t(seremitfc)\r\n\t0<> IF PAUSE THEN\r\n\t;\r\n\r\n: (sertype)\t\\ caddr len base --\r\n\\ *G Transmit a string on the given UART.\r\n -rot bounds\r\n ?do i c@ over (seremit) loop\r\n drop\r\n;\r\n\r\n: (sercr)\t\\ base --\r\n\\ *G Transmit a CR\/LF pair on the given UART.\r\n $0D over (seremit) $0A swap (seremit)\r\n;\r\n\r\nCODE (sergetchar) \\ base -- c\r\n\\ *G Get a character from the port\r\n\tmov r0, tos\t\r\n\tsvc # 3\r\n\tmov tos, r0\r\n\tnext,\r\nEND-CODE\r\n\r\nCODE (serkey?) \\ base -- t\/f\r\n\\ *G Return true if the given UART has a character avilable to read.\r\n\\ The call returns 0 or 1. If 1, subtract 2.\r\n\tmov r0, tos\r\n\tsvc # 4\t\t\r\n \tcmp r0, # 1\t\r\n\tit .eq\r\n \t sub r0, # 2\r\n\tmov tos, r0\r\n\tnext,\t\r\nEND-CODE\r\n\r\n: (serkey)\t\\ base -- char\r\n\\ *G Wait for a character to come available on the given UART and\r\n\\ ** return the character.\r\n begin\r\n[ tasking? ] [if] pause [else] wfi [then] \r\n dup (serkey?)\r\n until\r\n (sergetchar) \r\n;\r\n\r\nexternal \r\n\r\n: seremit0\t\\ char --\r\n\\ *G Transmit a character on UART0.\r\n 0 (seremit) ;\r\n: sertype0\t\\ c-addr len --\r\n\\ *G Transmit a string on UART0.\r\n 0 (sertype) ;\r\n: sercr0\t\\ --\r\n\\ *G Issue a CR\/LF pair to UART0.\r\n 0 (sercr) ;\r\n: serkey?0\t\\ -- flag\r\n\\ *G Return true if UART0 has a character available.\r\n 0 (serkey?) ;\r\n: serkey0\t\\ -- char\r\n\\ *G Wait for a character on UART0.\r\n 0 (serkey) ;\r\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\r\n\\ *G Generic I\/O device for UART0.\r\n ' serkey0 ,\t\t\\ -- char ; receive char\r\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\r\n ' seremit0 ,\t\t\\ -- char ; display char\r\n ' sertype0 ,\t\t\\ caddr len -- ; display string\r\n ' sercr0 ,\t\t\\ -- ; display new line\r\n\r\n\\ UART1\r\n: seremit1 #1 (seremit) ;\r\n: sertype1\t#1 (sertype) ;\r\n: sercr1\t#1 (sercr) ;\r\n: serkey?1\t#1 (serkey?) ;\r\n: serkey1\t#1 (serkey) ;\r\ncreate Console1 ' serkey1 , ' serkey?1 , ' seremit1 , ' sertype1 , ' sercr1 ,\t\r\n\r\n\\ UART2\r\n: seremit2 #2 (seremit) ;\r\n: sertype2\t#2 (sertype) ;\r\n: sercr2\t#2 (sercr) ;\r\n: serkey?2\t#2 (serkey?) ;\r\n: serkey2\t#2 (serkey) ;\r\ncreate Console2 ' serkey2 , ' serkey?2 , ' seremit2 , ' sertype2 , ' sercr2 ,\t\r\n\r\n\\ Versions for use with the TCP Port (10)\r\n: seremit10 #10 (seremit) ;\r\n: sertype10\t#10 (sertype) ;\r\n: sercr10\t#10 (sercr) ;\r\n: serkey?10\t#10 (serkey?) ;\r\n: serkey10\t#10 (serkey) ;\r\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\r\n\r\nconsole-port 0 = [if]\r\n console0 constant console\r\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\r\n\\ ** It may be changed by one of the phrases of the form:\r\n\\ *C dup opvec ! ipvec !\r\n\\ *C SetConsole\r\n[then]\r\n\r\nconsole-port #2 = [if]\r\n console2 constant console\r\n[then]\r\n\r\nconsole-port #10 = [if]\r\n console10 constant console\r\n[then]\r\n\r\n\\ ************************\r\n\\ *S System initialisation\r\n\\ ************************\r\n\r\n\\ This is a NOP in the SAPI environment\r\n: init-ser ;\t\\ --\r\n\\ *G Initialise all serial ports\r\n\r\n\r\n\\ ======\r\n\\ *> ###\r\n\\ ======\r\n\r\ndecimal\r\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"964d6c79dcf735286341680876bd0b715c55bff5","subject":"Fixes a silly bug that somehow escaped my notice all these months.","message":"Fixes a silly bug that somehow escaped my notice all these months.\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"share\/examples\/bootforth\/menuconf.4th","new_file":"share\/examples\/bootforth\/menuconf.4th","new_contents":"\\ Simple greeting screen, presenting basic options.\n\\ XXX This is far too trivial - I don't have time now to think\n\\ XXX about something more fancy... :-\/\n\\ $FreeBSD$\n\n: title\n\tf_single\n\t60 11 10 4 box\n\t29 4 at-xy 15 fg 7 bg\n\t.\" Welcome to BootFORTH!\"\n\tme\n;\n\n: menu\n\t2 fg\n\t20 7 at-xy \n\t.\" 1. Start FreeBSD with \/boot\/stable.conf.\"\n 20 8 at-xy\n .\" 2. Start FreeBSD with \/boot\/current.conf.\"\n\t20 9 at-xy\n\t.\" 3. Start FreeBSD with standard configuration. \"\n\t20 10 at-xy\n\t.\" 4. Reboot.\"\n\tme\n;\n\n: tkey\t( d -- flag | char )\n\tseconds +\n\tbegin 1 while\n\t dup seconds u< if\n\t\tdrop\n\t\t-1\n\t\texit\n\t then\n\t key? if\n\t\tdrop\n\t\tkey\n\t\texit\n\t then\n\trepeat\n;\n\n: prompt\n\t14 fg\n\t20 12 at-xy\n\t.\" Enter your option (1,2,3,4): \"\n\t10 tkey\n\tdup 32 = if\n\t drop key\n\tthen\n\tdup 0< if\n\t drop 51\n\tthen\n\tdup emit\n\tme\n;\n\n: help_text\n 10 18 at-xy .\" * Choose 1 or 2 to run special configuration file.\"\n\t10 19 at-xy .\" * Choose 3 to proceed with standard bootstrapping.\"\n\t12 20 at-xy .\" See '?' for available commands, and 'words' for\"\n\t12 21 at-xy .\" complete list of Forth words.\"\n\t10 22 at-xy .\" * Choose 4 in order to warm boot your machine.\"\n;\n\n: (reboot) 0 reboot ;\n\n: main_menu\n\tbegin 1 while\n\t\tclear\n\t\tf_double\n\t\t79 23 1 1 box\n\t\ttitle\n\t\tmenu\n\t\thelp_text\n\t\tprompt\n\t\tcr cr cr\n\t\tdup 49 = if\n\t\t\tdrop\n\t\t\t1 25 at-xy cr\n\t\t\t.\" Loading \/boot\/stable.conf. Please wait...\" cr\n\t\t\ts\" \/boot\/stable.conf\" read-conf\n\t\t\tboot-conf exit\n\t\tthen\n\t\tdup 50 = if\n\t\t\tdrop\n\t\t\t1 25 at-xy cr\n\t\t\t.\" Loading \/boot\/current.conf. Please wait...\" cr\n\t\t\ts\" \/boot\/current.conf\" read-conf\n\t\t\tboot-conf exit\n\t\tthen\n\t\tdup 51 = if\n\t\t\tdrop\n\t\t\t1 25 at-xy cr\n\t\t\t.\" Proceeding with standard boot. Please wait...\" cr\n\t\t\tboot-conf exit\n\t\tthen\n\t\tdup 52 = if\n\t\t\tdrop\n\t\t\t1 25 at-xy cr\n\t\t\t['] (reboot) catch abort\" Error rebooting\"\n\t\tthen\n\t\t20 12 at-xy\n\t\t.\" Key \" emit .\" is not a valid option!\"\n\t\t20 13 at-xy\n\t\t.\" Press any key to continue...\"\n\t\tkey drop\n\trepeat\n;\n\n","old_contents":"\\ Simple greeting screen, presenting basic options.\n\\ XXX This is far too trivial - I don't have time now to think\n\\ XXX about something more fancy... :-\/\n\\ $FreeBSD$\n\n: title\n\tf_single\n\t60 11 10 4 box\n\t29 4 at-xy 15 fg 7 bg\n\t.\" Welcome to BootFORTH!\"\n\tme\n;\n\n: menu\n\t2 fg\n\t20 7 at-xy \n\t.\" 1. Start FreeBSD with \/boot\/stable.conf.\"\n 20 8 at-xy\n .\" 2. Start FreeBSD with \/boot\/current.conf.\"\n\t20 9 at-xy\n\t.\" 3. Start FreeBSD with standard configuration. \"\n\t20 10 at-xy\n\t.\" 4. Reboot.\"\n\tme\n;\n\n: tkey\t( d -- flag | char )\n\tseconds +\n\tbegin 1 while\n\t dup seconds u< if\n\t\tdrop\n\t\t-1\n\t\texit\n\t then\n\t key? if\n\t\tdrop\n\t\tkey\n\t\texit\n\t then\n\trepeat\n;\n\n: prompt\n\t14 fg\n\t20 12 at-xy\n\t.\" Enter your option (1,2,3,4): \"\n\t10 tkey\n\tdup 32 = if\n\t drop key\n\tthen\n\tdup 0< if\n\t drop 51\n\tthen\n\tdup emit\n\tme\n;\n\n: help_text\n 10 18 at-xy .\" * Choose 1 or 2 to run special configuration file.\"\n\t10 19 at-xy .\" * Choose 3 to proceed with standard bootstrapping.\"\n\t12 20 at-xy .\" See '?' for available commands, and 'words' for\"\n\t12 21 at-xy .\" complete list of Forth words.\"\n\t10 22 at-xy .\" * Choose 4 in order to warm boot your machine.\"\n;\n\n: (reboot) 0 reboot ;\n\n: main_menu\n\tbegin 1 while\n\t\tclear\n\t\tf_double\n\t\t79 23 1 1 box\n\t\ttitle\n\t\tmenu\n\t\thelp_text\n\t\tprompt\n\t\tcr cr cr\n\t\tdup 49 = if\n\t\t\tdrop\n\t\t\t1 25 at-xy cr\n\t\t\t.\" Loading \/boot\/stable.conf. Please wait...\" cr\n\t\t\ts\" \/boot\/stable.conf\" read-conf\n\t\t\tboot-conf\n\t\tthen\n\t\tdup 50 = if\n\t\t\tdrop\n\t\t\t1 25 at-xy cr\n\t\t\t.\" Loading \/boot\/current.conf. Please wait...\" cr\n\t\t\ts\" \/boot\/current.conf\" read-conf\n\t\t\tboot-conf\n\t\tthen\n\t\tdup 51 = if\n\t\t\tdrop\n\t\t\t1 25 at-xy cr\n\t\t\t.\" Proceeding with standard boot. Please wait...\" cr\n\t\t\tboot-conf\n\t\tthen\n\t\tdup 52 = if\n\t\t\tdrop\n\t\t\t1 25 at-xy cr\n\t\t\t['] (reboot) catch abort\" Error rebooting\"\n\t\tthen\n\t\t20 12 at-xy\n\t\t.\" Key \" emit .\" is not a valid option!\"\n\t\t20 13 at-xy\n\t\t.\" Press any key to continue...\"\n\t\tkey drop\n\trepeat\n;\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"481029f60650fe9f829b07181d64865ca3841664","subject":"UI support for twiddling the hours.","message":"UI support for twiddling the hours.","repos":"rbsexton\/gecko,rbsexton\/gecko,rbsexton\/gecko","old_file":"zero\/clock-umb\/forth\/Clock.fth","new_file":"zero\/clock-umb\/forth\/Clock.fth","new_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( -- ) \n init-idata\n load-defaults \n icroot 0 over inter.rtcsem ! \\ Reset the free-running counters.\n 0 over inter.rtcdsem ! \\ Reset the free-running counters.\n\n begin \n \tdup inter.rtcsem @offex! ?dup if advancehms then\n \tdup inter.rtcdsem @offex! ?dup if advancedhms then\n [asm wfi asm]\n uiupdate if use-uivals else use-clockvals then \n key? until drop\n;\n \n\\ These two contain loops to ensure that we don't\n\\ drop any timer ticks on the floor.\n: ADVANCEHMS ( n -- ) 0 do hms advancetime loop ;\n: ADVANCEDHMS ( n -- ) 0 do dhms advancetime loop ;\n \n: LOAD-DEFAULTS ( -- )\n nvramvalid? if _nvramload then \n interp-init\n;\n\n\\ ----------------------------------------------------------\n\\ Define the structures before they get used.\n\\ ----------------------------------------------------------\nstruct ODN \\ On-Deck Needle \n\tint odn.s\n\tint odn.m\n\tint odn.h\nend-struct\n\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxsec \\ Max Value for secs+minutes\n\tint hms.maxhour \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_m \\ increment the minutes + hours\nend-struct\n\nstruct _interp_set\n\t4 cells field interp.a\n\t4 cells field interp.b\n\t4 cells field interp.c\nend-struct\n\n\\ ----------------------------------------------------------\n\\ Defaults get saved in the user data page.\n\\ ----------------------------------------------------------\n: NVRAMVALID? ( -- t\/f ) \n\\ *G See if there is valid data in the NVRAM.\n\\ ** It consists of 3 words. If any of them are \n\\ ** set to 0xffff:ffff, we go with the defaults.\n _USERDATA\n dup @ -1 <> \n over 4 + @ -1 <> and\n swap 8 + @ -1 <> and\n;\n\n: _NVRAMLOAD ( -- ) \n\\ *G Pull the needle maximums from flash.\n $C 0 do I ud@ needle_max I + ! 4 +loop \n; \n\n: NVRAM! ( addr -- )\n\\ *G Save the contents of the needle cal values.\n 0 UDPAGE_ERASE\n ( addr )\n $C 0 do dup I + @ I ud! 4 +loop\n drop \n;\n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nidata\ncreate ODN_HMS odn allot \\ On-Deck, HMS\ncreate ODN_DHMS odn allot \\ On-Deck, DHMS\ncreate ODN_UI odn allot \\ On-Deck, Generated by the UI.\ncdata\n\nidata \\ Has to match an odn.\ncreate NEEDLE_MAX #850 , #850 , #850 ,\ncdata\n\n(( \n: interp-next drop 1 ; \n: interp-reset drop .\" Reset\" ; \n\t\n))\n\n: RANGECHECK ( max n -- n or zero ) 2dup <= if 2drop 0 else swap drop then ; \n: QUADCLIP ( n -- n) \\ Force the contents to be legal ( 0-999 )\n dup 0 < if drop 0 exit then \n dup #999 > if drop #999 then \n;\n \n: INTER-BUMP ( max old interp -- new )\n\\ *G Get the next value from the interpolator, and \n\\ ** reset the interpolator if it wraps around to zero.\n >R R@ interp-next \\ Get the max \n + rangecheck \n dup 0= if R> interp-reset else R> drop then \n ; \n\n: NFETCH ( odn off -- max old )\n\\ *G Combine the current value with the maximum.\n >R R@ \\ stash the offset.\n + @ \\ Calculate the offset address, get the current val.\n needle_max R> + @\n swap \n;\n\n: ++NEEDLE_S \\ Called every time.\n odn_hms 0 odn.s nfetch ( max old )\n\tinterp_hms interp.a inter-bump ( new )\n\todn_hms odn.s ! \n\t;\n\n: ++NEEDLE_M ( -- )\n\\ *G Every time we roll the seconds, bump the minutes and the hour\n\todn_hms 0 odn.m nfetch ( max old )\n\tinterp_hms interp.b inter-bump \n\todn_hms odn.m ! \n\n\todn_hms 0 odn.h nfetch ( max old )\n\tinterp_hms interp.c inter-bump \n\todn_hms odn.h ! \n\t;\n\n: ++NEEDLE_DS ; \\ Called every time.\n: ++NEEDLE_DM ; \\ Every time we roll the seconds.\n\n: _USE ( odn-addr -- ) \n dup odn.s w@ pwm0!\n dup odn.m w@ pwm1!\n odn.h w@ pwm2!\n ;\n\n: USE-CLOCKVALS odn_hms _use ; \n: USE-UIVALS odn_ui _use ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Quadrature\n\\ ----------------------------------------------------------\n\n_timer1 $24 + equ QUAD-IN\n\n\\ The Quadrature encoder produces two per detent.\n: QUAD@ ( -- n ) \\ Fetch and zero\n quad-in @off \n [asm sxth tos, tos asm]\n [asm asr .s tos, tos, # 1 asm] \\ Divide by two,\n ;\n \n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_ds , ' ++needle_dm , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n: ADVANCETIME ( struct-addr -- )\n dup hms.w_s @ execute \\ Invoke the official update word.\n 1 over hms.subsec +! \\ Increment\n dup hms.subsec @\n over hms.maxsubsec @ < if drop exit then \\ If less then max, we're done\n 0 over hms.subsec ! \\ Reset the subsecs \n\n 1 over hms.s +!\n dup hms.s @ over hms.maxsec @ < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n dup hms.w_m @ execute\n 1 over hms.m +!\n dup hms.m @ over hms.maxsec @ < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ over hms.maxhour @ < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ----------------------------------------------------------\n\\ The interpolator. \n\\ Implement bresenhams algorithm. All of this code already\n\\ exists in C, but we'll own the data structures. They contain\n\\ A total of 4 words - fixed, err, num, & denom\n\\ ----------------------------------------------------------\nudata \ncreate interp_hms _interp_set allot\ncreate interp_dhms _interp_set allot \ncdata\n\n#16 #60 * equ raw_sec\n#10 #100 * equ raw_dsec\n\n: INTERP-INIT ( -- )\n (interp_init) interp_hms\n 2dup interp.a needle_max @ raw_sec call3-- \n 2dup interp.b needle_max 4 + @ #60 call3-- \n interp.c needle_max 8 + @ #24 #60 * call3--\n\n (interp_init) interp_dhms\n 2dup interp.a needle_max @ raw_dsec call3-- \n 2dup interp.b needle_max 4 + @ #100 call3-- \n interp.c needle_max 8 + @ #10 #100 * call3--\n;\n\n\\ Call the reset fn.\n: INTERP-RESET ( interp_addr -- )\n (interp_reset) swap call1-- \n;\n\n: INTERP-NEXT ( addr -- n )\n (interp_next) swap call1--n\n;\n\n\\ ----------------------------------------------------------\n\\ ----------------------------------------------------------\n\\ User Interface\n\\ ----------------------------------------------------------\n\\ ----------------------------------------------------------\nvariable uistate\nvariable uicount \n\n_GPIO $64 + equ _BUTTONIO\n: BUTTONUP? ( -- t\/f ) _buttonio @ 1 and ; \n: BUTTONDOWN? ( -- t\/f ) buttonup? 1 xor ; \n\n\\ The wrapper for all of the UI stuff.\n\\ Returns true if the UI is active - ie, use the values generated by the UI.\n: UIUPDATE ( -- t\/f )\n StateHandlers uistate @ + @ execute \n; \n\n: uitest \n uistate @ 4 \/ . .\" ->\" uiupdate uistate @ 4 \/ .\n uicount @ . if .\" True\" else .\" False\" then \n; \n\n\\ -----------------------------------------------\n\\ State numbers. These are defined x4 so that\n\\ we can just use the state number as an index \n\\ into a table of words.\n\\ -----------------------------------------------\n0 4 * equ _s_init\n1 4 * equ _s_b1\n2 4 * equ _s_1sec\n\n3 4 * equ _s_shSetH\n4 4 * equ _s_pendset_m\n5 4 * equ _s_setmin\n\n6 4 * equ _s_pendcal0\n7 4 * equ _s_cal0\n8 4 * equ _s_pendcalh\n9 4 * equ _s_calh\n10 4 * equ _s_pendcalm\n11 4 * equ _s_calm\n12 4 * equ _s_pendcals\n13 4 * equ _s_cals\n\n4 equ downcount_1s\n16 equ downcount_3s \n\n\\ All of the state handlers.\n\\ Everybody needs to know the state of the button, so that must\n\\ get passed in, thus they all look like this:\n\\ state ( t\/f -- t\/f )\n: shInit false \n buttondown? if \n _s_b1 uistate !\n uicount off \\ Reset this.\n then\n ;\n\n\\ Waiting for a full second to go by.\n: shB1 false\n buttonup? if _s_init uistate ! exit then\n \\ The Button is down. \n uicount @ downcount_1s >= if\n _s_1sec uistate !\n else \n 1 uicount +!\n\tthen\n ;\n\n\\ We're in the 1 second state\n: sh1sec true \n buttonup? if shseth_entry _s_shseth uistate ! exit then\n uicount @ downcount_3s >= if\n _s_pendcal0 uistate !\n else \n 1 uicount +!\n\tthen \n;\n\n\\ -------------------------------------------------\n\\ Setting the time\n\\ -------------------------------------------------\n: shSetH_entry \n adj_i off \\ Set the index to zero\n needle_max odn.h @ #24 make-set-list \n; \n\n: shSetH true buttondown? if _s_pendset_m uistate ! exit then\n adj_i @ quad@ - 24 mod \\ Now we have the next index.\n dup 0< if #24 + then \\ Negative wrap-around isn't cool\n dup adj_i ! \\ Save it.\n adj_points[]@ \\ Get the new value.\n odn_ui odn.h ! \n ;\n\n: shPendSetM true buttonup? if _s_setmin uistate ! then ;\n: shSetMin true buttondown? if _s_init uistate ! exit then ;\n\n\\ -------------------------------------------------\n\\ Calibration\n\\ -------------------------------------------------\n: shPendCal0 true buttonup? if _s_cal0 uistate ! helpODNClear then ;\n: shCal0 true buttondown? if _s_pendcalh uistate ! exit then ;\n\n: shPendCalH true buttonup? if _s_calh uistate ! helpODNMid then ; \n: shCalH true buttondown? if _s_pendcalm uistate ! exit then \n odn_ui odn.h helpQuad@ ; \n\n: shPendCalM true buttonup? if _s_calm uistate ! then ; \n: shCalM true buttondown? if _s_pendcals uistate ! exit then \n odn_ui odn.m helpQuad@ ; \n\n: shPendCalS true buttonup? if _s_cals uistate ! then ; \n: shCalS true buttondown? if \n _s_init uistate !\n odn_ui nvram! exit then \n \n odn_ui odn.s helpQuad@ ; \n\n\\ -------------------------------------------------\n\\ Helpers\n\\ -------------------------------------------------\n: helpODNClear ( -- ) \\ Set them all to zero\n odn_ui odn bounds do I off 4 +loop ; \n: helpODNMid ( -- ) \\ Set them all to 500\n odn_ui odn bounds do #750 I ! 4 +loop ; \n: helpQuad@ ( addr -- ) \\ update a location with the quadrature value\n dup @ quad@ + quadclip swap ! ;\n\n\ncreate StateHandlers \n' shInit , \n' shB1 ,\n' sh1sec ,\n\n' shSetH ,\n' shPendSetM , ' shSetMin ,\n\n' shPendCal0 , ' shCal0 ,\n' shPendCalH , ' shCalH , \n' shPendCalM , ' shCalM , \n' shPendCalS , ' shCalS , \n\n\\ -------------------------------------------------\n\\ Setting the time.\n\\ -------------------------------------------------\nvariable adj_i \\ THe working index into the points array.\n\nudata \ncreate adj_points #50 cells allot \\ 100 16-bit words. \ncreate interp_set _interp_set allot\ncdata \n\n\\ Generate a list of points.\n: MAKE-SET-LIST ( max steps ) \n 2dup \n >R (interp_init) swap interp_set swap R> call3--\n\n \\ Since zero is first, do the w! first.\n swap drop 0 swap \\ Keep a running counter.\n 0 do\n dup I adj_points[]! \\ Save the existing value\n interp_set interp-next + \n loop\n drop\n ;\n\n: ADJ_POINTS[]! ( data index -- ) 2* adj_points + w! ;\n: ADJ_POINTS[]@ ( index -- n ) 2* adj_points + w@ ;\n","old_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( -- ) \n init-idata\n load-defaults \n icroot 0 over inter.rtcsem ! \\ Reset the free-running counters.\n 0 over inter.rtcdsem ! \\ Reset the free-running counters.\n\n begin \n \tdup inter.rtcsem @offex! ?dup if advancehms then\n \tdup inter.rtcdsem @offex! ?dup if advancedhms then\n [asm wfi asm]\n uiupdate if use-uivals else use-clockvals then \n key? until drop\n;\n \n\\ These two contain loops to ensure that we don't\n\\ drop any timer ticks on the floor.\n: ADVANCEHMS ( n -- ) 0 do hms advancetime loop ;\n: ADVANCEDHMS ( n -- ) 0 do dhms advancetime loop ;\n \n: LOAD-DEFAULTS ( -- )\n nvramvalid? if _nvramload then \n interp-init\n;\n\n\\ ----------------------------------------------------------\n\\ Define the structures before they get used.\n\\ ----------------------------------------------------------\nstruct ODN \\ On-Deck Needle \n\tint odn.s\n\tint odn.m\n\tint odn.h\nend-struct\n\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxsec \\ Max Value for secs+minutes\n\tint hms.maxhour \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_m \\ increment the minutes + hours\nend-struct\n\nstruct _interp_set\n\t4 cells field interp.a\n\t4 cells field interp.b\n\t4 cells field interp.c\nend-struct\n\n\\ ----------------------------------------------------------\n\\ Defaults get saved in the user data page.\n\\ ----------------------------------------------------------\n: NVRAMVALID? ( -- t\/f ) \n\\ *G See if there is valid data in the NVRAM.\n\\ ** It consists of 3 words. If any of them are \n\\ ** set to 0xffff:ffff, we go with the defaults.\n _USERDATA\n dup @ -1 <> \n over 4 + @ -1 <> and\n swap 8 + @ -1 <> and\n;\n\n: _NVRAMLOAD ( -- ) \n\\ *G Pull the needle maximums from flash.\n $C 0 do I ud@ needle_max I + ! 4 +loop \n; \n\n: NVRAM! ( addr -- )\n\\ *G Save the contents of the needle cal values.\n 0 UDPAGE_ERASE\n ( addr )\n $C 0 do dup I + @ I ud! 4 +loop\n drop \n;\n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nidata\ncreate ODN_HMS odn allot \\ On-Deck, HMS\ncreate ODN_DHMS odn allot \\ On-Deck, DHMS\ncreate ODN_UI odn allot \\ On-Deck, Generated by the UI.\ncdata\n\nidata \\ Has to match an odn.\ncreate NEEDLE_MAX #850 , #850 , #850 ,\ncdata\n\n(( \n: interp-next drop 1 ; \n: interp-reset drop .\" Reset\" ; \n\t\n))\n\n: RANGECHECK ( max n -- n or zero ) 2dup <= if 2drop 0 else swap drop then ; \n: QUADCLIP ( n -- n) \\ Force the contents to be legal ( 0-999 )\n dup 0 < if drop 0 exit then \n dup #999 > if drop #999 then \n;\n \n: INTER-BUMP ( max old interp -- new )\n\\ *G Get the next value from the interpolator, and \n\\ ** reset the interpolator if it wraps around to zero.\n >R R@ interp-next \\ Get the max \n + rangecheck \n dup 0= if R> interp-reset else R> drop then \n ; \n\n: NFETCH ( odn off -- max old )\n\\ *G Combine the current value with the maximum.\n >R R@ \\ stash the offset.\n + @ \\ Calculate the offset address, get the current val.\n needle_max R> + @\n swap \n;\n\n: ++NEEDLE_S \\ Called every time.\n odn_hms 0 odn.s nfetch ( max old )\n\tinterp_hms interp.a inter-bump ( new )\n\todn_hms odn.s ! \n\t;\n\n: ++NEEDLE_M ( -- )\n\\ *G Every time we roll the seconds, bump the minutes and the hour\n\todn_hms 0 odn.m nfetch ( max old )\n\tinterp_hms interp.b inter-bump \n\todn_hms odn.m ! \n\n\todn_hms 0 odn.h nfetch ( max old )\n\tinterp_hms interp.c inter-bump \n\todn_hms odn.h ! \n\t;\n\n: ++NEEDLE_DS ; \\ Called every time.\n: ++NEEDLE_DM ; \\ Every time we roll the seconds.\n\n: _USE ( odn-addr -- ) \n dup odn.s w@ pwm0!\n dup odn.m w@ pwm1!\n odn.h w@ pwm2!\n ;\n\n: USE-CLOCKVALS odn_hms _use ; \n: USE-UIVALS odn_ui _use ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Quadrature\n\\ ----------------------------------------------------------\n\n_timer1 $24 + equ QUAD-IN\n\n\\ The Quadrature encoder produces two per detent.\n: QUAD@ ( -- n ) \\ Fetch and zero\n quad-in @off \n [asm sxth tos, tos asm]\n [asm asr .s tos, tos, # 1 asm] \\ Divide by two,\n ;\n \n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_ds , ' ++needle_dm , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n: ADVANCETIME ( struct-addr -- )\n dup hms.w_s @ execute \\ Invoke the official update word.\n 1 over hms.subsec +! \\ Increment\n dup hms.subsec @\n over hms.maxsubsec @ < if drop exit then \\ If less then max, we're done\n 0 over hms.subsec ! \\ Reset the subsecs \n\n 1 over hms.s +!\n dup hms.s @ over hms.maxsec @ < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n dup hms.w_m @ execute\n 1 over hms.m +!\n dup hms.m @ over hms.maxsec @ < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ over hms.maxhour @ < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ----------------------------------------------------------\n\\ The interpolator. \n\\ Implement bresenhams algorithm. All of this code already\n\\ exists in C, but we'll own the data structures. They contain\n\\ A total of 4 words - fixed, err, num, & denom\n\\ ----------------------------------------------------------\nudata \ncreate interp_hms _interp_set allot\ncreate interp_dhms _interp_set allot \ncdata\n\n#16 #60 * equ raw_sec\n#10 #100 * equ raw_dsec\n\n: INTERP-INIT ( -- )\n (interp_init) interp_hms\n 2dup interp.a needle_max @ raw_sec call3-- \n 2dup interp.b needle_max 4 + @ #60 call3-- \n interp.c needle_max 8 + @ #24 #60 * call3--\n\n (interp_init) interp_dhms\n 2dup interp.a needle_max @ raw_dsec call3-- \n 2dup interp.b needle_max 4 + @ #100 call3-- \n interp.c needle_max 8 + @ #10 #100 * call3--\n;\n\n\\ Call the reset fn.\n: INTERP-RESET ( interp_addr -- )\n (interp_reset) swap call1-- \n;\n\n: INTERP-NEXT ( addr -- n )\n (interp_next) swap call1--n\n;\n\n\\ ----------------------------------------------------------\n\\ ----------------------------------------------------------\n\\ User Interface\n\\ ----------------------------------------------------------\n\\ ----------------------------------------------------------\nvariable uistate\nvariable uicount \n\n_GPIO $64 + equ _BUTTONIO\n: BUTTONUP? ( -- t\/f ) _buttonio @ 1 and ; \n: BUTTONDOWN? ( -- t\/f ) buttonup? 1 xor ; \n\n\\ The wrapper for all of the UI stuff.\n\\ Returns true if the UI is active - ie, use the values generated by the UI.\n: UIUPDATE ( -- t\/f )\n StateHandlers uistate @ + @ execute \n; \n\n: uitest \n uistate @ 4 \/ . .\" ->\" uiupdate uistate @ 4 \/ .\n uicount @ . if .\" True\" else .\" False\" then \n; \n\n\\ -----------------------------------------------\n\\ State numbers. These are defined x4 so that\n\\ we can just use the state number as an index \n\\ into a table of words.\n\\ -----------------------------------------------\n0 4 * equ _s_init\n1 4 * equ _s_b1\n2 4 * equ _s_1sec\n\n3 4 * equ _s_set_h\n4 4 * equ _s_pendset_m\n5 4 * equ _s_setmin\n\n6 4 * equ _s_pendcal0\n7 4 * equ _s_cal0\n8 4 * equ _s_pendcalh\n9 4 * equ _s_calh\n10 4 * equ _s_pendcalm\n11 4 * equ _s_calm\n12 4 * equ _s_pendcals\n13 4 * equ _s_cals\n\n4 equ downcount_1s\n16 equ downcount_3s \n\n\\ All of the state handlers.\n\\ Everybody needs to know the state of the button, so that must\n\\ get passed in, thus they all look like this:\n\\ state ( t\/f -- t\/f )\n: shInit false \n buttondown? if \n _s_b1 uistate !\n uicount off \\ Reset this.\n then\n ;\n\n\\ Waiting for a full second to go by.\n: shB1 false\n buttonup? if _s_init uistate ! exit then\n \\ The Button is down. \n uicount @ downcount_1s >= if\n _s_1sec uistate !\n else \n 1 uicount +!\n\tthen\n ;\n\n\\ We're in the 1 second state\n: sh1sec true \n buttonup? if _s_set_h uistate ! exit then\n uicount @ downcount_3s >= if\n _s_pendcal0 uistate !\n else \n 1 uicount +!\n\tthen \n;\n\n\\ -------------------------------------------------\n\\ Setting the time\n\\ -------------------------------------------------\n: shSetH true buttondown? if _s_pendset_m uistate ! exit then ;\n\n: shPendSetM true buttonup? if _s_setmin uistate ! then ;\n: shSetMin true buttondown? if _s_init uistate ! exit then ;\n\n\\ -------------------------------------------------\n\\ Calibration\n\\ -------------------------------------------------\n: shPendCal0 true buttonup? if _s_cal0 uistate ! helpODNClear then ;\n: shCal0 true buttondown? if _s_pendcalh uistate ! exit then ;\n\n: shPendCalH true buttonup? if _s_calh uistate ! helpODNMid then ; \n: shCalH true buttondown? if _s_pendcalm uistate ! exit then \n odn_ui odn.h helpQuad@ ; \n\n: shPendCalM true buttonup? if _s_calm uistate ! then ; \n: shCalM true buttondown? if _s_pendcals uistate ! exit then \n odn_ui odn.m helpQuad@ ; \n\n: shPendCalS true buttonup? if _s_cals uistate ! then ; \n: shCalS true buttondown? if \n _s_init uistate !\n odn_ui nvram! exit then \n \n odn_ui odn.s helpQuad@ ; \n\n\\ -------------------------------------------------\n\\ Helpers\n\\ -------------------------------------------------\n: helpODNClear ( -- ) \\ Set them all to zero\n odn_ui odn bounds do I off 4 +loop ; \n: helpODNMid ( -- ) \\ Set them all to 500\n odn_ui odn bounds do #750 I ! 4 +loop ; \n: helpQuad@ ( addr -- ) \\ update a location with the quadrature value\n dup @ quad@ + quadclip swap ! ;\n\n\ncreate StateHandlers \n' shInit , \n' shB1 ,\n' sh1sec ,\n\n' shSetH ,\n' shPendSetM , ' shSetMin ,\n\n' shPendCal0 , ' shCal0 ,\n' shPendCalH , ' shCalH , \n' shPendCalM , ' shCalM , \n' shPendCalS , ' shCalS , \n\n\\ -------------------------------------------------\n\\ Setting the time.\n\\ -------------------------------------------------\nvariable adj_i \\ THe working index into the points array.\n\nudata \ncreate adj_points #50 cells allot \\ 100 16-bit words. \ncreate interp_set _interp_set allot\ncdata \n\n\\ Generate a list of points.\n: MAKE-SET-LIST ( max steps ) \n 2dup \n >R (interp_init) swap interp_set swap R> call3--\n\n \\ Since zero is first, do the w! first.\n swap drop 0 swap \\ Keep a running counter.\n 0 do\n dup I adj_points[]! \\ Save the existing value\n interp_set interp-next + \n loop\n drop\n ;\n\n: ADJ_POINTS[]! ( data index -- ) 2* adj_points + w! ;\n: ADJ_POINTS[]@ ( index -- n ) 2* adj_points + w@ ;\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"f9b4215ee0feca84aae338672b52b277eaa7bb29","subject":"Added more high level Forth code, mostly math code.","message":"Added more high level Forth code, mostly math code.\n","repos":"hth313\/hthforth","old_file":"src\/lib\/core.fth","new_file":"src\/lib\/core.fth","new_contents":"( block 1 -- Main load block )\n\nVARIABLE BLK\n: FH BLK @ + ; \\ relative block\n: LOAD BLK @ SWAP DUP BLK ! (LOAD) BLK ! ;\n\n100 LOAD\n( shadow 1 )\n( block 2 )\n( shadow 2 )\n( block 3 )\n( shadow 3 )\n\n( block 10 )\n( shadow 10 )\n( block 11 )\n( shadow 11 )\n( block 12 )\n( shadow 12 )\n\n( block 100 )\n\n1 FH 6 FH THRU\n\n( shadow 100 )\n( block 101 stack primitives )\n\n: ROT >R SWAP R> SWAP ;\n: -ROT SWAP >R SWAP R> ; \\ or ROT ROT\n: ?DUP DUP IF DUP THEN ;\n: NIP ( n1 n2 -- n2 ) SWAP DROP ;\n: TUCK ( n1 n2 -- n2 n1 n2 ) SWAP OVER ;\n\n: 2DROP DROP DROP ;\n: 2DUP OVER OVER ;\n: 2SWAP ROT >R ROT R> ;\n: 2OVER >R >R 2DUP R> R> 2SWAP ;\n( shadow 101 )\n( block 102 comparisons )\n\n-1 CONSTANT TRUE 0 CONSTANT FALSE\n\n: = ( n n -- f) XOR 0= ;\n: < ( n n -- f ) - 0< ;\n: > ( n n -- f ) SWAP < ;\n\n: MAX ( n n -- n ) 2DUP < IF SWAP THEN DROP ;\n: MIN ( n n -- n ) 2DUP > IF SWAP THEN DROP ;\n\n: WITHIN ( u ul uh -- f ) OVER - >R - R> U< ;\n( shadow 102 )\n( block 103 ALU )\n\n: 1+ 1 + ;\n: 1- 1 - ;\n: INVERT TRUE XOR ;\n: NEGATE INVERT 1+ ;\n: DNEGATE INVERT SWAP NEGATE TUCK 0= - ;\n: S>D ( n -- d ) DUP 0< ; \\ sign extend\n: ABS S>D IF NEGATE THEN ;\n: DABS DUP 0< IF DNEGATE THEN ;\n\n\n: +- 0< IF NEGATE THEN ;\n: D+- 0< IF DNEGATE THEN ;\n\n( shadow 103 )\n( block 104 variables )\n\nVARIABLE BASE\n: DECIMAL 10 BASE ! ; : HEX 16 BASE ! ;\n( shadow 104 )\n( block 105 math )\n\n: SM\/REM ( d n -- r q ) \\ symmetric\n OVER >R >R DABS R@ ABS UM\/MOD\n R> R@ XOR 0< IF NEGATE THEN\n R> 0< IF >R NEGATE R> THEN ;\n\n: FM\/MOD ( d n -- r q ) \\ floored\n DUP 0< DUP >R IF NEGATE >R DNEGATE R> THEN\n >R DUP 0< IF R@ + THEN\n R> UM\/MOD R> IF >R NEGATE R> THEN ;\n\n: \/MOD OVER 0< SWAP FM\/MOD ;\n: MOD \/MOD DROP ;\n: \/ \/MOD NIP ;\n\n( shadow 105 )\n( block 106 math continued )\n\n: * UM* DROP ;\n: M* 2DUP XOR R> ABS SWAP ABS UM* R> D+- ;\n: *\/MOD >R M* R> FM\/MOD ;\n: *\/ *\/MOD NIP ;\n\n: 2* DUP + ;\n\\ 2\/ which is right shift is native\n( shadow 106 )\n( block 107 )\n( shadow 107 )\n( block 108 )\n( shadow 108 )\n( block 109 )\n( shadow 109 )\n( block 110 compiler )\n\n: VARIABLE CREATE 1 CELLS ALLOT ;\n\nVARIABLE STATE ( compilation state variable )\n0 STATE ! ( interpreting by default )\n: [ FALSE STATE ! ;\n: ] TRUE STATE ! ;\n\n( Colon definitions )\n: : CREATE ] ;\n: ; POSTPONE EXIT SMUDGE [ ; IMMEDIATE\n\n( shadow 110 )\n( block 111 )\n( shadow 111 )\n( block 112 interpreter )\n\nCREATE _INPUT-BUFFER 80 CHARS ALLOT ( may do this internally? )\n\n: EVALUATE >IN @ >R 0 >IN ! SOURCE >R >R #IN 2! _INTERPRET\n R> R> #IN 2! R> >IN ! ;\n\n: QUIT _RESET-RSTACK\n BEGIN\n BEGIN\n\t _READ-LINE 0 >IN ! _INPUT-BUFFER 0 EVALUATE CR\n\t STATE @\n UNTIL .\" ok \" ( exhausted input in interpretation mode )\n AGAIN ;\n( shadow 112 )\n","old_contents":"( block 1 -- Main load block )\n\nVARIABLE BLK\n: FH BLK @ + ; \\ relative block\n: LOAD BLK @ SWAP DUP BLK ! (LOAD) BLK ! ;\n\n100 LOAD\n( shadow 1 )\n( block 2 )\n( shadow 2 )\n( block 3 )\n( shadow 3 )\n\n( block 10 )\n( shadow 10 )\n( block 11 )\n( shadow 11 )\n( block 12 )\n( shadow 12 )\n\n( block 100 )\n\n1 FH LOAD \\ stack primitives\n2 FH LOAD \\ ALU\n\n( shadow 100 )\n( block 101 stack primitives )\n\n: 2DROP DROP DROP ;\n: 2DUP OVER OVER ;\n: ?DUP DUP IF DUP THEN ;\n( shadow 101 )\n( block 102 ALU )\n\n: 1+ 1 + ;\n: 1- 1 - ;\n: INVERT -1 XOR ;\n: NEGATE INVERT 1+ ;\n: ABS DUP 0< IF NEGATE THEN ;\n\n( shadow 102 )\n( block 103 )\n( shadow 103 )\n( block 104 )\n( shadow 104 )\n( block 105 interpreter )\n\nCREATE _INPUT-BUFFER 80 CHARS ALLOT ( may do this internally? )\n\n: EVALUATE >IN @ >R 0 >IN ! SOURCE >R >R #IN 2! _INTERPRET\n R> R> #IN 2! R> >IN ! ;\n\n: QUIT _RESET-RSTACK\n BEGIN\n BEGIN\n\t _READ-LINE 0 >IN ! _INPUT-BUFFER 0 EVALUATE CR\n\t STATE @\n UNTIL .\" ok \" ( exhausted input in interpretation mode )\n AGAIN ;\n\n ( shadow 105 )\n( block 106 )\n( shadow 106 )\n( block 107 )\n( shadow 107 )\n( block 108 )\n( shadow 108 )\n( block 109 )\n( shadow 109 )\n( block 110 compiler )\n\n: VARIABLE CREATE 1 CELLS ALLOT ;\n\nVARIABLE STATE ( compilation state variable )\n0 STATE ! ( interpreting by default )\n: [ FALSE STATE ! ;\n: ] TRUE STATE ! ;\n\n( Colon definitions )\n: : CREATE ] ;\n: ; POSTPONE EXIT SMUDGE [ ; IMMEDIATE\n\n( shadow 110 )\n( block 111 )\n( shadow 111 )\n( block 112 )\n( shadow 112 )\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"89aa6b1d0d4188ba1d0f52a78adcd7ead3874cc3","subject":"?TWO-ADJACENT-1-BITS implemented","message":"?TWO-ADJACENT-1-BITS implemented\n","repos":"bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas","old_file":"KataDiversion.fth","new_file":"KataDiversion.fth","new_contents":"\\ KataDiversion in Forth\n\n\\ -- utils\n\n\\ empty the stack\n: EMPTY\n DEPTH 0 <> IF BEGIN\n DROP DEPTH 0 =\n UNTIL\n THEN ;\n\n\\ power\n: ** ( n1 n2 -- n1_pow_n2 ) 1 SWAP ?DUP IF 0 DO OVER * LOOP THEN NIP ;\n\n\\ test if the top is a negative number\n: ?NEG ( n -- bool ) DUP 0= IF -1 ELSE DUP ABS <> THEN ;\n\n\\ log2 (integer)\n: LOG2 ( n -- log2_n ) DUP 1 < IF 1 ABORT\" Log2 need a positive value.\"\n ELSE DUP 1 = IF 0\n ELSE\n 1 >R\n BEGIN ( n |R: i=1)\n DUP DUP 2 I ** - 2 *\n ( n n 2*[n-2**i])\n R> 1 + >R ( \u2026 |R: i+1)\n > ( n n>2*[n-2**i] )\n UNTIL\n R> 1 -\n THEN\n THEN NIP ;\n\n\\ decimal to binary\n\\ e.g. : ( 11 -- 1 0 1 1 )\n: DEC2BIN ( n -- n1 n2 n3 \u2026 ) DUP DUP 0 <> IF\n LOG2 2 SWAP ** >R ( n |R: X=2 ** n.log2 )\n BEGIN\n DUP I - 0 >= IF 1 SWAP I - ( 1 n-X )\n ELSE 0 SWAP ( 0 n )\n THEN\n I 1 =\n R> 2 \/ >R ( \u2026 | X\/2 )\n UNTIL\n R> 2DROP\n THEN\n ;\n\n\n\\ -- kata\n\n\\ test if the given N has two adjacent 1 bits\n\\ e.g. : 11 -> 1011 -> -1\n\\ 9 -> 1001 -> 0\n: ?TWO-ADJACENT-1-BITS ( n -- bool ) 0 SWAP DUP DUP 0 <> IF ( _ n n )\n LOG2 2 SWAP ** >R ( _ n |R: X=2 ** n.log2 )\n BEGIN\n DUP I - ( _ n n-X ) 0 >= IF \n SWAP DUP 1 = IF ( n _ ) 1+ SWAP ( 2 n )\n ELSE ( n _ ) 1+ SWAP ( _ n ) I -\n THEN\n ELSE NIP 0 SWAP ( 0 n ) \n THEN\n ( _ n )\n OVER ( _ n _ )\n 2 = \n I 1 = OR\n R> 2 \/ >R ( \u2026 | X\/2 )\n UNTIL\n R> 2DROP\n 2 =\n THEN ;\n\n\\ return the maximum number which can be made with N (given number) bits\n: ?MAX-NB ( n -- m ) DUP ?NEG IF DROP 0 ( 0 )\n ELSE \n DUP IF DUP 2 SWAP ** NIP ( 2**n )\n THEN\n THEN ;\n\n\n\\ return the number of numbers which can be made with N (given number) bits\n\\ or less, and which have not two adjacent 1 bits.\n\\ see http:\/\/www.codekata.com\/2007\/01\/code_kata_fifte.html\n: ?HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS ( n -- m ) ( TODO ) ;\n","old_contents":"\\ KataDiversion in Forth\n\n\\ -- utils\n\n\\ empty the stack\n: EMPTY\n DEPTH 0 <> IF BEGIN\n DROP DEPTH 0 =\n UNTIL\n THEN ;\n\n\\ power\n: ** ( n1 n2 -- n1_pow_n2 ) 1 SWAP ?DUP IF 0 DO OVER * LOOP THEN NIP ;\n\n\\ test if the top is a negative number\n: ?NEG ( n -- bool ) DUP 0= IF -1 ELSE DUP ABS <> THEN ;\n\n\\ log2 (integer)\n: LOG2 ( n -- log2_n ) DUP 1 < IF 1 ABORT\" Log2 need a positive value.\"\n ELSE DUP 1 = IF 0\n ELSE\n 1 >R\n BEGIN ( n |R: i=1)\n DUP DUP 2 I ** - 2 *\n ( n n 2*[n-2**i])\n R> 1 + >R ( \u2026 |R: i+1)\n > ( n n>2*[n-2**i] )\n UNTIL\n R> 1 -\n THEN\n THEN NIP ;\n\n\\ decimal to binary\n\\ e.g. : ( 11 -- 1 0 1 1 )\n: DEC2BIN ( n -- n1 n2 n3 \u2026 ) DUP DUP 0 <> IF\n LOG2 2 SWAP ** >R ( n |R: X=2 ** n.log2 )\n BEGIN\n DUP I - 0 >= IF 1 SWAP I - ( 1 n-X )\n ELSE 0 SWAP ( 0 n )\n THEN\n I 1 =\n R> 2 \/ >R ( \u2026 | X\/2 )\n UNTIL\n R> 2DROP\n THEN\n ;\n\n\n\\ -- kata\n\n\\ test if the given N has two adjacent 1 bits\n\\ e.g. : 11 -> 1011 -> -1\n\\ 9 -> 1001 -> 0\n: ?TWO-ADJACENT-1-BITS ( \u2026 n -- bool ) ( FIXME ) DUP DEC2BIN ( n n_bin )\n 0 >R\n BEGIN\n 1 = IF I 1 = IF R> EMPTY 0 -1 >R\n ELSE R> DROP 1 >R -1\n THEN\n ELSE 0 >R -1\n THEN\n UNTIL\n R> ;\n\n\\ return the maximum number which can be made with N (given number) bits\n: ?MAX-NB ( n -- m ) DUP ?NEG IF DROP 0 ( 0 )\n ELSE \n DUP IF DUP 2 SWAP ** NIP ( 2**n )\n THEN\n THEN ;\n\n\n\\ return the number of numbers which can be made with N (given number) bits\n\\ or less, and which have not two adjacent 1 bits.\n\\ see http:\/\/www.codekata.com\/2007\/01\/code_kata_fifte.html\n: ?HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS ( n -- m ) ( TODO ) ;\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"f1b6567bf85ef3f993760c8f87521fd62142ada4","subject":"More system words","message":"More system words\n","repos":"rm-hull\/byok3,rm-hull\/byok3","old_file":"src\/main\/resources\/forth\/system.fth","new_file":"src\/main\/resources\/forth\/system.fth","new_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\\n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n\n: COUNT dup 1+ swap c@ ;\n\n\\ Miscellaneous support words\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: CELL+ ( n -- n+cell ) cell + ;\n: CELL- ( n -- n-cell ) cell - ;\n: CELL* ( n -- n*cell ) cells ;\n\n: CHAR+ ( n -- n+size_of_char ) 1+ ;\n\\ : CHARS ( n -- n*size_of_char, don't do anything ) ; immediate\n\n\\ useful stack manipulation words\n: -ROT ( a b c -- c a b ) rot rot ;\n: 3DUP ( a b c -- a b c a b c ) 2 pick 2 pick 2 pick ;\n\n\\ ------------------------------------------------------------------\n: ID. ( nfa -- ) count 31 and type ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: PAD ( -- addr ) here 128 + ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: ? ( -- ) @ . ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ ' (lit) , cell 1- , ] +\n [ ' (lit) , cell 1- invert , ] and ;\n\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n: ALLOT ( nbytes -- , allot space in dictionary ) dp +! align ;\n\n: C, ( c -- ) here c! 1 dp +! ;\n\\ : W, ( w -- ) dp @ even-up dup dp ! w! 2 dp +! ;\n\\ : , ( n -- , lay into dictionary ) align here ! cell allot ;\n\n: SEE ( -- )\n ' dup\n 16 + @ \\ offset in execution token for alloc size\n cells swap >body swap\n disassemble ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token )\n [compile] literal ( compile a call to literal )\n ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n: :NONAME ( -- xt , begin compilation of headerless secondary ) align here ] ;\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick )\n ?comp ' [compile] literal\n; immediate\n\n: RECURSE ( ? -- ? , call the word currently being defined )\n latest compile,\n; immediate\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 ) swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 ) dup cell+ @ swap @ ;\n\n: \/STRING ( addr len n -- addr' len' ) over min rot over + -rot - ;\n: PLACE ( addr len to -- , move string ) 3dup 1+ swap cmove c! drop ;\n\n: ASCII ( -- char, state smart )\n bl parse drop c@\n state @ 1 =\n IF [compile] literal\n ELSE\n THEN\n; immediate\n\n: CHAR ( -- char , interpret mode ) bl parse drop c@ ;\n: [CHAR] ( -- char , for compile mode )\n char [compile] literal\n; immediate\n\n: 'word ( -- addr ) here ;\n\n: (C\") ( -- $addr ) r> dup count + aligned >r ;\n: (S\") ( -- c-addr cnt ) r> count 2dup + aligned >r ;\n: (.\") ( -- , type following string ) r> count 2dup + aligned >r type ;\n: \", ( addr len -- , place string into dict ) tuck 'word place 1+ allot align ;\n: ,\" ( -- ) 34 parse \", ;\n\n: .( ( --, type string delimited by parens )\n 41 parse type\n; immediate\n\n: .\" ( -- , type string )\n state @ 1 =\n IF compile (.\") ,\"\n ELSE 34 parse type\n THEN\n; immediate\n\n: CLEARSTACK ( i*x -- )\n BEGIN depth\n WHILE drop\n REPEAT ;\n\nvariable pictured_output \\ hidden?\nvariable pictured_output_len \\ hidden?\n\n: <# ( -- ) pad pictured_output ! 0 pictured_output_len ! ;\n: #> ( -- addr n ) drop pictured_output @ pictured_output_len @ ;\n\n: HOLD ( c -- )\n pictured_output @ dup dup 1+ pictured_output_len @ cmove c!\n 1 pictured_output_len +!\n;\n\n: DIGIT ( n -- ascii )\n dup 10 < IF 48 ELSE 87 THEN + ;\n\n: SIGN ( n -- ) < 0 IF 45 hold THEN\n;\n: # ( n -- n )\n base @ \/mod swap digit hold ;\n\n: #S ( n -- )\n BEGIN base @ \/mod dup\n WHILE swap digit hold\n REPEAT\n digit hold ;\n\n: (DOES>) ( xt -- , modify previous definition to execute code at xt )\n latest >body \\ get address of code for new word\n cell + \\ offset to second cell in create word\n ! \\ store execution token of DOES> code in new word\n;\n\n: DOES> ( -- , define execution code for CREATE word )\n 0 [compile] literal \\ dummy literal to hold xt\n here cell- \\ address of zero in literal\n compile (does>) \\ call (DOES>) from new creation word\n\t\t>r \\ move addrz to return stack so ; doesn't see stack garbage\n [compile] ; \\ terminate part of code before does>\n\t\tr>\n :noname ( addrz xt )\n swap ! \\ save execution token in literal\n; immediate\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 )\n swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 )\n dup cell+ @ swap @ ;\n\n\n\\ Stack data structure ----------------------------------------\n\\ This is a general purpose stack utility used to implement necessary\n\\ stacks for the compiler or the user. Not real fast.\n\\ These stacks grow up which is different then normal.\n\\ cell 0 - stack pointer, offset from pfa of word\n\\ cell 1 - limit for range checking\n\\ cell 2 - first data location\n\n: :STACK ( #cells -- )\n CREATE 2 cells , ( offset of first data location )\n dup , ( limit for range checking, not currently used )\n cells cell+ allot ( allot an extra cell for safety )\n;\n\n: >STACK ( n stack -- , push onto stack, postincrement )\n dup @ 2dup cell+ swap ! ( -- n stack offset )\n + !\n;\n\n: STACK> ( stack -- n , pop , predecrement )\n dup @ cell- 2dup swap !\n + @\n;\n\n: STACK@ ( stack -- n , copy )\n dup @ cell- + @\n;\n\n: STACK.PICK ( index stack -- n , grab Nth from top of stack )\n dup @ cell- +\n swap cells - \\ offset for index\n @\n;\n: STACKP ( stack -- ptr , to next empty location on stack )\n\tdup @ +\n;\n\n: 0STACKP ( stack -- , clear stack)\n 8 swap !\n;\n\n32 :stack ustack\nustack 0stackp\n\n\\ Define JForth like words.\n: >US ustack >stack ;\n: US> ustack stack> ;\n: US@ ustack stack@ ;\n: 0USP ustack 0stackp ;\n\n\n\n\\ DO LOOP ------------------------------------------------\n\n3 constant do_flag\n4 constant leave_flag\n5 constant ?do_flag\n\n: DO ( -- , loop-back do_flag jump-from ?do_flag )\n ?comp\n compile (do)\n here >us do_flag >us ( for backward branch )\n; immediate\n\n\\ : ?DO ( -- , loop-back do_flag jump-from ?do_flag , on user stack )\n\\ ?comp\n\\ ( leave address to set for forward branch )\n\\ compile (?do)\n\\ here 0 ,\n\\ here >us do_flag >us ( for backward branch )\n\\ >us ( for forward branch ) ?do_flag >us\n\\ ; immediate\n\n: LEAVE ( -- addr leave_flag )\n compile (leave)\n here 0 , >us\n leave_flag >us\n; immediate\n\n: LOOP-FORWARD ( -us- jump-from ?do_flag -- )\n BEGIN\n us@ leave_flag =\n us@ ?do_flag =\n OR\n WHILE\n us> leave_flag =\n IF\n us> here over - cell+ swap !\n ELSE\n us> dup\n here swap -\n cell+ swap !\n THEN\n REPEAT\n;\n\n: LOOP-BACK ( loop-addr do_flag -us- )\n us> do_flag ?pairs\n us> here - here\n !\n cell allot\n;\n\n: LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (loop)\n loop-forward loop-back\n; immediate\n\n\\ : DOTEST 5 0 do 333 . loop 888 . ;\n\\ : ?DOTEST0 0 0 ?do 333 . loop 888 . ;\n\\ : ?DOTEST1 5 0 ?do 333 . loop 888 . ;\n\n: +LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (+loop)\n loop-forward loop-back\n; immediate\n\n: UNLOOP ( loop-sys -r- )\n r> \\ save return pointer\n rdrop rdrop\n >r\n;","old_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\\n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n\n: COUNT dup 1+ swap c@ ;\n\n\\ Miscellaneous support words\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: CELL+ ( n -- n+cell ) cell + ;\n: CELL- ( n -- n-cell ) cell - ;\n: CELL* ( n -- n*cell ) cells ;\n\n: CHAR+ ( n -- n+size_of_char ) 1+ ;\n\\ : CHARS ( n -- n*size_of_char, don't do anything ) ; immediate\n\n\\ useful stack manipulation words\n: -ROT ( a b c -- c a b ) rot rot ;\n: 3DUP ( a b c -- a b c a b c ) 2 pick 2 pick 2 pick ;\n\n\\ ------------------------------------------------------------------\n: ID. ( nfa -- ) count 31 and type ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: PAD ( -- addr ) here 128 + ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: ? ( -- ) @ . ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ ' (lit) , cell 1- , ] +\n [ ' (lit) , cell 1- invert , ] and ;\n\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n: ALLOT ( nbytes -- , allot space in dictionary ) dp +! align ;\n\n: C, ( c -- ) here c! 1 dp +! ;\n\\ : W, ( w -- ) dp @ even-up dup dp ! w! 2 dp +! ;\n\\ : , ( n -- , lay into dictionary ) align here ! cell allot ;\n\n: SEE ( -- )\n ' dup\n 16 + @ \\ offset in execution token for alloc size\n cells swap >body swap\n disassemble ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token )\n [compile] literal ( compile a call to literal )\n ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n: :NONAME ( -- xt , begin compilation of headerless secondary ) align here ] ;\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick )\n ?comp ' [compile] literal\n; immediate\n\n: RECURSE ( ? -- ? , call the word currently being defined )\n latest compile,\n; immediate\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 ) swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 ) dup cell+ @ swap @ ;\n\n: \/STRING ( addr len n -- addr' len' ) over min rot over + -rot - ;\n: PLACE ( addr len to -- , move string ) 3dup 1+ swap cmove c! drop ;\n\n: ASCII ( -- char, state smart )\n bl parse drop c@\n state @ 1 =\n IF [compile] literal\n ELSE\n THEN\n; immediate\n\n: CHAR ( -- char , interpret mode ) bl parse drop c@ ;\n: [CHAR] ( -- char , for compile mode )\n char [compile] literal\n; immediate\n\n: 'word ( -- addr ) here ;\n\n: (C\") ( -- $addr ) r> dup count + aligned >r ;\n: (S\") ( -- c-addr cnt ) r> count 2dup + aligned >r ;\n: (.\") ( -- , type following string ) r> count 2dup + aligned >r type ;\n: \", ( addr len -- , place string into dict ) tuck 'word place 1+ allot align ;\n: ,\" ( -- ) 34 parse \", ;\n\n: .( ( --, type string delimited by parens )\n 41 parse type\n; immediate\n\n: .\" ( -- , type string )\n state @ 1 =\n IF compile (.\") ,\"\n ELSE 34 parse type\n THEN\n; immediate\n\n: CLEARSTACK ( i*x -- )\n BEGIN depth\n WHILE drop\n REPEAT ;\n\nvariable pictured_output \\ hidden?\nvariable pictured_output_len \\ hidden?\n\n: <# ( -- ) pad pictured_output ! 0 pictured_output_len ! ;\n: #> ( -- addr n ) drop pictured_output @ pictured_output_len @ ;\n\n: HOLD ( c -- )\n pictured_output @ dup dup 1+ pictured_output_len @ cmove c!\n 1 pictured_output_len +!\n;\n\n: DIGIT ( n -- ascii )\n dup 10 < IF 48 ELSE 87 THEN + ;\n\n: SIGN ( n -- ) < 0 IF 45 hold THEN\n;\n: # ( n -- n )\n base @ \/mod swap digit hold ;\n\n: #S ( n -- )\n BEGIN base @ \/mod dup\n WHILE swap digit hold\n REPEAT\n digit hold ;\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"c5867e87c458c78cd0c70af74db98fa50e2aed7a","subject":"Clean support for multiple streams.","message":"Clean support for multiple streams.","repos":"rbsexton\/sockpuppet,rbsexton\/sockpuppet","old_file":"forth\/serCM3_SAPI-level1.fth","new_file":"forth\/serCM3_SAPI-level1.fth","new_contents":"\\ serCM3_sapi_level1.fth - SAPI polled RX, polled TX, serial communication drivers\n\\ with support for blocking IO.\n\\ Written to run against the SockPuppet API.\n\n\\ Level 1 support. Requires TASKING. System calls request blocking.\n\\ KEY requires blocking, so that must be implemented here.\n\n\\ Copyright (c) 2017, Robert Sexton. All rights reserved.\n\\ Covered by the terms of the supplied Licence.txt file\n\nonly forth definitions\n\n\\ ==============\n\\ *T SAPI polled serial driver\n\\ ==============\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\n\\ ** using the internal UARTs via the SAPI call layer. This is \n\\ ** The simplest implementation level.\n\\ ** It doesn't use the CR or TYPE calls, but rather emulates them.\n\n\\ ****************\n\\ *S Configuration\n\\ ****************\n\\ *P Configuration is managed by the SAPI\n\ntarget\n\n\\ ********************\n\\ *S Serial primitives\n\\ ********************\ninternal\n\n: +FaultConsole\t( -- ) ;\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\n\\ ** for more details.\n\ntarget\n\n\\ CODE (seremitfc)\t\\ char base --\n\\ This is a system call.\n\n: (seremit)\t\\ char base -- \n\\ *G Wrapped call that checks for throttling, and if so,\n\\ calls PAUSE to let another task run, or just does a WFI if no multitasker.\n\\ The only interesting thing is failure, or -1. That means retry.\n (seremitfc) if [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then] then \n\t;\n\n: (sertype) \\ caddr len base --\n\\ *G Transmit a string on the given UART.\n -rot bounds\n ?do i c@ over (seremit) loop\n drop\n;\n\n: (sercr)\t\\ base --\n\\ *G Transmit a CR\/LF pair on the given UART.\n $0D over (seremit) $0A swap (seremit)\n;\n\n: (serkey) \\ base -- c\n\\ *G Get a character from the port. Retry until we get it.\n\\ The system call will stop the task and restart it when there is data.\n\\ See if its negative. If so, discard it and leave false to re-loop.\n\\ If not negative, leave true on the stack to exit.\n begin \\ base ret t\/f \n\tdup (serkeyfc) dup 0 < \\ base ret t\/f \n\t \\ If we have been blocked, drop the useless returned data and try again.\n\t IF [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then] drop false \n\t ELSE true \\ Leave the return code intact.\n\t THEN \\ base ret t\/f \n\tuntil \\ base ret \n\tswap drop \n;\n\n\\ THis is a system call.\n\\ CODE (serkey?) \\ base -- t\/f\n\\ *G Return true if the given UART has a character avilable to read.\n\nexternal \n\n: seremit0\t\\ char --\n\\ *G Transmit a character on UART0.\n 0 (seremit) ;\n: sertype0\t\\ c-addr len --\n\\ *G Transmit a string on UART0.\n 0 (sertype) ;\n: sercr0\t\\ --\n\\ *G Issue a CR\/LF pair to UART0.\n 0 (sercr) ;\n: serkey?0\t\\ -- flag\n\\ *G Return true if UART0 has a character available.\n 0 (serkey?) ;\n: serkey0\t\\ -- char\n\\ *G Wait for a character on UART0.\n 0 (serkey) ;\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\n\\ *G Generic I\/O device for UART0.\n ' serkey0 ,\t\t\\ -- char ; receive char\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\n ' seremit0 ,\t\t\\ -- char ; display char\n ' sertype0 ,\t\t\\ caddr len -- ; display string\n ' sercr0 ,\t\t\\ -- ; display new line\n\n\\ --------------------------------------------------------------------\n\\ Optional devices\n\\ --------------------------------------------------------------------\n[defined] useUART1? [if] useUART1? 1 = [if] \n: seremit1 #1 (seremit) ;\n: sertype1 #1 (sertype) ;\n: sercr1 #1 (sercr) ;\n: serkey?1 #1 (serkey?) ;\n: serkey1 #1 (serkey) ;\ncreate Console1 ' serkey1 , ' serkey?1 , ' seremit1 , ' sertype1 , ' sercr1 ,\t\n[then] [then]\n\n\\ --------------------------------------------------------------------\n\\ Non-UARTs.\n\\ --------------------------------------------------------------------\n[defined] useStream10? [if] useStream10? 1 = [if] \n: seremit10 #10 (seremit) ;\n: sertype10\t#10 (sertype) ;\n: sercr10\t#10 (sercr) ;\n: serkey?10\t#10 (serkey?) ;\n: serkey10\t#10 (serkey) ;\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\n[then] [then]\n\nconsole-port 0 = [if]\n console0 constant console\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\n\\ ** It may be changed by one of the phrases of the form:\n\\ *C dup opvec ! ipvec !\n\\ *C SetConsole\n[then]\n\nconsole-port #10 = [if]\n console10 constant console\n[then]\n\n\\ ************************\n\\ *S System initialisation\n\\ ************************\n\n\\ This is a NOP in the SAPI environment\n: init-ser ;\t\\ --\n\\ *G Initialise all serial ports\n\n\\ ======\n\\ *> ###\n\\ ======\n\ndecimal\n","old_contents":"\\ serCM3_sapi_level1.fth - SAPI polled RX, polled TX, serial communication drivers\n\\ with support for blocking IO.\n\\ Written to run against the SockPuppet API.\n\n\\ Level 1 support. Requires TASKING. System calls request blocking.\n\\ KEY requires blocking, so that must be implemented here.\n\n\\ Copyright (c) 2017, Robert Sexton. All rights reserved.\n\\ Covered by the terms of the supplied Licence.txt file\n\nonly forth definitions\n\n\\ ==============\n\\ *T SAPI polled serial driver\n\\ ==============\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\n\\ ** using the internal UARTs via the SAPI call layer. This is \n\\ ** The simplest implementation level.\n\\ ** It doesn't use the CR or TYPE calls, but rather emulates them.\n\n\\ ****************\n\\ *S Configuration\n\\ ****************\n\\ *P Configuration is managed by the SAPI\n\ntarget\n\n\\ ********************\n\\ *S Serial primitives\n\\ ********************\ninternal\n\n: +FaultConsole\t( -- ) ;\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\n\\ ** for more details.\n\ntarget\n\n\\ CODE (seremitfc)\t\\ char base --\n\\ This is a system call.\n\n: (seremit)\t\\ char base -- \n\\ *G Wrapped call that checks for throttling, and if so,\n\\ calls PAUSE to let another task run, or just does a WFI if no multitasker.\n\\ The only interesting thing is failure, or -1. That means retry.\n (seremitfc) if [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then] then \n\t;\n\n: (sertype) \\ caddr len base --\n\\ *G Transmit a string on the given UART.\n -rot bounds\n ?do i c@ over (seremit) loop\n drop\n;\n\n: (sercr)\t\\ base --\n\\ *G Transmit a CR\/LF pair on the given UART.\n $0D over (seremit) $0A swap (seremit)\n;\n\n: (serkey) \\ base -- c\n\\ *G Get a character from the port. Retry until we get it.\n\\ The system call will stop the task and restart it when there is data.\n\\ See if its negative. If so, discard it and leave false to re-loop.\n\\ If not negative, leave true on the stack to exit.\n begin \\ base ret t\/f \n\tdup (serkeyfc) dup 0 < \\ base ret t\/f \n\t IF [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then] drop false \n\t ELSE true \n\t THEN \\ base ret t\/f \n\tuntil \\ base ret \n\tswap drop \n;\n\n\\ THis is a system call.\n\\ CODE (serkey?) \\ base -- t\/f\n\\ *G Return true if the given UART has a character avilable to read.\n\nexternal \n\n: seremit0\t\\ char --\n\\ *G Transmit a character on UART0.\n 0 (seremit) ;\n: sertype0\t\\ c-addr len --\n\\ *G Transmit a string on UART0.\n 0 (sertype) ;\n: sercr0\t\\ --\n\\ *G Issue a CR\/LF pair to UART0.\n 0 (sercr) ;\n: serkey?0\t\\ -- flag\n\\ *G Return true if UART0 has a character available.\n 0 (serkey?) ;\n: serkey0\t\\ -- char\n\\ *G Wait for a character on UART0.\n 0 (serkey) ;\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\n\\ *G Generic I\/O device for UART0.\n ' serkey0 ,\t\t\\ -- char ; receive char\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\n ' seremit0 ,\t\t\\ -- char ; display char\n ' sertype0 ,\t\t\\ caddr len -- ; display string\n ' sercr0 ,\t\t\\ -- ; display new line\n\n\\ Non-UARTs.\n: seremit10 #10 (seremit) ;\n: sertype10\t#10 (sertype) ;\n: sercr10\t#10 (sercr) ;\n: serkey?10\t#10 (serkey?) ;\n: serkey10\t#10 (serkey) ;\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\n\nconsole-port 0 = [if]\n console0 constant console\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\n\\ ** It may be changed by one of the phrases of the form:\n\\ *C dup opvec ! ipvec !\n\\ *C SetConsole\n[then]\n\nconsole-port #10 = [if]\n console10 constant console\n[then]\n\n\\ ************************\n\\ *S System initialisation\n\\ ************************\n\n\\ This is a NOP in the SAPI environment\n: init-ser ;\t\\ --\n\\ *G Initialise all serial ports\n\n\\ ======\n\\ *> ###\n\\ ======\n\ndecimal\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"d846328ee044e40dbb09f9e3c5c71a1944bea949","subject":"SAPI-core has been obsoleted.","message":"SAPI-core has been obsoleted.","repos":"rbsexton\/sockpuppet,rbsexton\/sockpuppet","old_file":"forth\/SAPI-core.fth","new_file":"forth\/SAPI-core.fth","new_contents":"","old_contents":"\\ Wrappers for SAPI functions\n\\ SVC 0: Return the version of the API in use.\n\\ SVC 1: Return the address of the shared variables table\n\n\\ 2-4 are for use by the serial io routines, and are \n\\ defined elsewhere.\n\n\\ Note that the system call number is embedded into the instruction,\n\\ so this is not so easily parameterized.\n\n\\ Copyright (c) 2011-2016, Robert Sexton. All rights reserved.\n\\ Covered by the terms of the supplied Licence.txt file\n\n\n#0 equ SAPI_VEC_VERSION\n#1 equ SAPI_VEC_VARS\n#2 equ SAPI_VEC_PUTCHAR\n#3 equ SAPI_VEC_GETCHAR\n#4 equ SAPI_VEC_GETCHARAVAIL\n#5 equ SAPI_VEC_PUTCHARHASROOM\n#6 equ SAPI_VEC_SET_IO_CALLBACK\n#7 equ SAPI_VEC_GETMS\n\n#10 equ SAPI_VEC_STARTAPP\n#11 equ SAPI_VEC_MPULOAD\n#12 equ SAPI_VEC_PRIVMODE\n#13 equ SAPI_VEC_USAGE\n#14 equ SAPI_VEC_PETWATCHDOG\n\n\\ **********************************************************************\n\\ SVC 0: Return the version of the API in use.\n\\ **********************************************************************\nCODE SAPI-Version \\ -- n \n\t\\ Push TOS, and place the result there.\t\n\tsvc # SAPI_VEC_VERSION \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 1: Get the address of the shared variable list\n\\ **********************************************************************\nCODE GetSharedVars \\ -- n \n\tsvc # SAPI_VEC_VARS \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ Do a stack switch and startup the user App. Its a one-way\n\\ trip, so don't worry about stack cleanup.\n\\ **********************************************************************\nCODE RestartForth ( c-addr ) \\ -- \n\tmov r0, tos\n\tsvc # SAPI_VEC_STARTAPP\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ Request Privileged Mode. In some systems, this is a huge\n\\ Security hole.\n\\ **********************************************************************\nCODE privmode \\ -- \n\tsvc # SAPI_VEC_PRIVMODE\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ Ask for MPU entry updates.\n\\ **********************************************************************\nCODE MPULoad \\ -- \n\tmov r0, tos\n\tsvc # SAPI_VEC_MPULOAD\n\tldr tos, [ psp ], # $04\t\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ Refresh the watchdog\n\\ **********************************************************************\nCODE PetWatchDog \\ -- \n\tsvc # SAPI_VEC_PETWATCHDOG\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ Return Millisecond ticker value.\n\\ **********************************************************************\nCODE Ticks \\ -- n \n\tsvc # SAPI_VEC_GETMS\n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ The number of CPU cycles consumed in the last second.\n\\ **********************************************************************\nCODE GetUsage \\ -- n \n\tsvc # SAPI_VEC_USAGE\n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ Set the IO Callback address for a stream.\n\\ iovec, read\/write (r=1), address to set as zero.\n\\ Note the minor parameter swizzle here to keep the old value on TOS.\n\\ **********************************************************************\nCODE SetIOCallback \\ addr iovec read\/write -- n \n\tmov r1, tos\n\tldr r0, [ psp ], # 4 !\n\tldr r2, [ psp ], # 4 !\n \tsvc # SAPI_VEC_SET_IO_CALLBACK\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\n\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"ca2a1ac3055e8ef1e6ced68853090e970d4003bf","subject":"MFC r266938:","message":"MFC r266938:\n\nAllow customization of the brand displayed in the boot menu.\nIf the user specifies in \/boot\/loader.conf:\n\n loader_brand=\"mycustom-brand\"\n\nThen \"mycustom-brand\" will be executed instead of \"fbsd-logo\".\n\nSubmitted by: alfred\nObtained from: FreeNAS\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/brand.4th","new_file":"sys\/boot\/forth\/brand.4th","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"bsd-3-clause","lang":"Forth"} {"commit":"49af5b16df68ccf46ac93db5188e8b808b4dbaf4","subject":"Add DEFER, DEFER@ and DEFER! words","message":"Add DEFER, DEFER@ and DEFER! words\n","repos":"rm-hull\/byok3,rm-hull\/byok3","old_file":"core\/src\/main\/resources\/forth\/system.fth","new_file":"core\/src\/main\/resources\/forth\/system.fth","new_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\\n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n\n: COUNT dup 1+ swap c@ ;\n\n\\ Miscellaneous support words\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: <= ( a b -- f , true if A <= b ) > 0= ;\n: >= ( a b -- f , true if A >= b ) < 0= ;\n: NOT ( n -- !n , logical negation ) 0= ;\n: DNEGATE ( d -- -d , negate by doing 0-d )\n 0 swap -\n;\n: CELL+ ( n -- n+cell ) cell + ;\n: CELL- ( n -- n-cell ) cell - ;\n: CELL* ( n -- n*cell ) cells ;\n\n: CHAR+ ( n -- n+size_of_char ) 1+ ;\n\\ : CHARS ( n -- n*size_of_char, don't do anything ) ; immediate\n\n\\ useful stack manipulation words\n: -ROT ( a b c -- c a b ) rot rot ;\n: 3DUP ( a b c -- a b c a b c ) 2 pick 2 pick 2 pick ;\n\n\\ ------------------------------------------------------------------\n: ID. ( nfa -- ) count 31 and type ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: PAD ( -- addr ) here 128 + ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n\n: BETWEEN ( n lo hi -- flag , true if between lo & hi )\n >r over r> > >r\n < r> or 0=\n;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: ? ( -- ) @ . ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ ' (lit) , cell 1- , ] +\n [ ' (lit) , cell 1- invert , ] and ;\n\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n: ALLOT ( nbytes -- , allot space in dictionary ) dp +! align ;\n\n: C, ( c -- ) here c! 1 dp +! ;\n\\ : W, ( w -- ) dp @ even-up dup dp ! w! 2 dp +! ;\n\\ : , ( n -- , lay into dictionary ) align here ! cell allot ;\n\n: SEE ( -- )\n ' dup\n >body swap >size\n disassemble ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token )\n [compile] literal ( compile a call to literal )\n ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick )\n ?comp ' [compile] literal\n; immediate\n\n: (DOES>) ( xt -- , modify previous definition to execute code at xt )\n latest >body \\ get address of code for new word\n 3 cell* + \\ offset to EXIT cell in create word\n ! \\ store execution token of DOES> code in new word\n;\n\n: DOES> ( -- , define execution code for CREATE word )\n 0 [compile] literal \\ dummy literal to hold xt\n here cell- \\ address of zero in literal\n compile (does>) \\ call (DOES>) from new creation word\n\t\t>r \\ move addrz to return stack so ; doesn't see stack garbage\n [compile] ; \\ terminate part of code before does>\n\t\tr>\n :noname ( addrz xt )\n compile rdrop \\ drop a stack frame (call becomes goto)\n swap ! \\ save execution token in literal\n; immediate\n\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 )\n swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 )\n dup cell+ @ swap @ ;\n\n: 2* ( n -- n*2 )\n 2 *\n;\n: 2\/ ( n -- n\/2 )\n 2 \/\n;\n\n\n\\ define some useful constants ------------------------------\n1 0= constant FALSE\n0 0= constant TRUE\n32 constant BL\n\n\\ Stack data structure ----------------------------------------\n\\ This is a general purpose stack utility used to implement necessary\n\\ stacks for the compiler or the user. Not real fast.\n\\ These stacks grow up which is different then normal.\n\\ cell 0 - stack pointer, offset from pfa of word\n\\ cell 1 - limit for range checking\n\\ cell 2 - first data location\n\n: :STACK ( #cells -- )\n CREATE 2 cells , ( offset of first data location )\n dup , ( limit for range checking, not currently used )\n cells cell+ allot ( allot an extra cell for safety )\n;\n\n: >STACK ( n stack -- , push onto stack, postincrement )\n dup @ 2dup cell+ swap ! ( -- n stack offset )\n + !\n;\n\n: STACK> ( stack -- n , pop , predecrement )\n dup @ cell- 2dup swap !\n + @\n;\n\n: STACK@ ( stack -- n , copy )\n dup @ cell- + @\n;\n\n: STACK.PICK ( index stack -- n , grab Nth from top of stack )\n dup @ cell- +\n swap cells - \\ offset for index\n @\n;\n: STACKP ( stack -- ptr , to next empty location on stack )\n\tdup @ +\n;\n\n: 0STACKP ( stack -- , clear stack)\n 8 swap !\n;\n\n32 :stack ustack\nustack 0stackp\n\n\\ Define JForth like words.\n: >US ustack >stack ;\n: US> ustack stack> ;\n: US@ ustack stack@ ;\n: 0USP ustack 0stackp ;\n\n\n\n\\ DO LOOP ------------------------------------------------\n\n3 constant do_flag\n4 constant leave_flag\n5 constant ?do_flag\n\n: DO ( -- , loop-back do_flag jump-from ?do_flag )\n ?comp\n compile (do)\n here >us do_flag >us ( for backward branch )\n; immediate\n\n: ?DO ( -- , loop-back do_flag jump-from ?do_flag , on user stack )\n ?comp\n ( leave address to set for forward branch )\n compile (?do)\n here 0 ,\n here >us do_flag >us ( for backward branch )\n >us ( for forward branch ) ?do_flag >us\n; immediate\n\n: LEAVE ( -- addr leave_flag )\n compile (leave)\n here 0 , >us\n leave_flag >us\n; immediate\n\n: LOOP-FORWARD ( -us- jump-from ?do_flag -- )\n BEGIN\n us@ leave_flag =\n us@ ?do_flag =\n OR\n WHILE\n us> leave_flag =\n IF\n us> here over - cell+ swap !\n ELSE\n us> dup\n here swap -\n cell+ swap !\n THEN\n REPEAT\n;\n\n: LOOP-BACK ( loop-addr do_flag -us- )\n us> do_flag ?pairs\n us> here - here\n !\n cell allot\n;\n\n: LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (loop)\n loop-forward loop-back\n; immediate\n\n\\ : DOTEST 5 0 do 333 . loop 888 . ;\n\\ : ?DOTEST0 0 0 ?do 333 . loop 888 . ;\n\\ : ?DOTEST1 5 0 ?do 333 . loop 888 . ;\n\n: +LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (+loop)\n loop-forward loop-back\n; immediate\n\n: UNLOOP ( loop-sys -r- )\n r> \\ save return pointer\n rdrop rdrop\n >r\n;\n\n\n: RECURSE ( ? -- ? , call the word currently being defined )\n latest compile,\n; immediate\n\n: SPACE bl emit ;\n: SPACES 512 min 0 max 0 ?DO space LOOP ;\n: 0SP depth 0 ?do drop loop ;\n\n\\ : >NEWLINE ( -- , CR if needed )\n\\ out @ 0>\n\\ IF cr\n\\ THEN\n\\ ;\n\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 ) swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 ) dup cell+ @ swap @ ;\n\n: DABS ( d -- |d| )\n dup 0<\n IF dnegate\n THEN\n;\n\n: S>D ( s -- d , extend signed single precision to double )\n dup 0<\n IF -1\n ELSE 0\n THEN\n;\n\n: D>S ( d -- s ) drop ;\n\n: PARSE-WORD ( \"name\" -- c-addr u ) bl parse ;\n: \/STRING ( addr len n -- addr' len' ) over min rot over + -rot - ;\n: PLACE ( addr len to -- , move string ) 3dup 1+ swap cmove c! drop ;\n\n: ASCII ( -- char, state smart )\n bl parse drop c@\n state @ 1 =\n IF [compile] literal\n ELSE\n THEN\n; immediate\n\n: CHAR ( -- char , interpret mode ) bl parse drop c@ ;\n: [CHAR] ( -- char , for compile mode )\n char [compile] literal\n; immediate\n\n: $TYPE ( $string -- ) count type ;\n: 'word ( -- addr ) here ;\n\n: EVEN ( addr -- addr' ) dup 1 and + ;\n\n: (C\") ( -- $addr ) r> dup count + aligned >r ;\n: (S\") ( -- c-addr cnt ) r> count 2dup + aligned >r ;\n: (.\") ( -- , type following string ) r> count 2dup + aligned >r type ;\n: \", ( addr len -- , place string into dict ) tuck 'word place 1+ allot align ;\n: ,\" ( -- ) [char] \" parse \", ;\n\n: .( ( --, type string delimited by parens )\n [char] ) parse type\n; immediate\n\n: .\" ( -- , type string )\n state @ 1 =\n IF compile (.\") ,\"\n ELSE [char] \" parse type\n THEN\n; immediate\n\n: .' ( -- , type string delimited by single quote )\n state @\n IF compile (.\") [char] ' parse \",\n ELSE [char] ' parse type\n THEN\n; immediate\n\n: C\" ( -- addr , return string address, ANSI )\n state @\n IF compile (c\") ,\"\n ELSE [char] \" parse pad place pad\n THEN\n; immediate\n\n: S\" ( -- , -- addr , return string address, ANSI )\n state @\n IF compile (s\") ,\"\n ELSE [char] \" parse pad place pad count\n THEN\n; immediate\n\n: \" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n: P\" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n\n\\ : \"\" ( -- addr )\n\\ state @\n\\ IF\n\\ compile (C\")\n\\ bl parse-word \",\n\\ ELSE\n\\ bl parse-word pad place pad\n\\ THEN\n\\ ; immediate\n\n: SLITERAL ( addr cnt -- , compile string )\n\tcompile (S\")\n\t\",\n; IMMEDIATE\n\n: $APPEND ( addr count $1 -- , append text to $1 )\n over >r\n dup >r\n count + ( -- a2 c2 end1 )\n swap cmove\n r> dup c@ ( a1 c1 )\n r> + ( -- a1 totalcount )\n swap c!\n;\n\n\\ ANSI word to replace [COMPILE] and COMPILE ----------------\n\\ : POSTPONE ( -- )\n\\\tbl word find\n\\\tdup 0=\n\\\tIF\n\\\t\t.\" Postpone could not find \" count type cr abort\n\\\tELSE\n\\\t\t0>\n\\\t\tIF compile, \\ immediate\n\\\t\tELSE (compile) \\ normal\n\\\t\tTHEN\n\\\tTHEN\n\\ ; immediate\n\n\\ -----------------------------------------------------------------\n\\ Auto Initialization\n: AUTO.INIT ( -- )\n\\ Kernel finds AUTO.INIT and executes it after loading dictionary.\n\\\t.\" Begin AUTO.INIT ------\" cr\n;\n: AUTO.TERM ( -- )\n\\ Kernel finds AUTO.TERM and executes it on bye.\n\\\t.\" End AUTO.TERM ------\" cr\n;\n\n\n: CLEARSTACK ( i*x -- )\n BEGIN depth\n WHILE drop\n REPEAT ;\n\nvariable pictured_output \\ hidden?\nvariable pictured_output_len \\ hidden?\n\n: <# ( -- ) pad pictured_output ! 0 pictured_output_len ! ;\n: #> ( -- addr n ) drop pictured_output @ pictured_output_len @ ;\n\n: HOLD ( c -- )\n pictured_output @ dup dup 1+ pictured_output_len @ cmove c!\n 1 pictured_output_len +!\n;\n\n\\ ------------------------ INPUT -------------------------------\n\n: SIGN ( n -- ) < 0 IF 45 hold THEN\n;\n\n: DIGIT ( n -- ascii )\n dup 10 < IF 48 ELSE 87 THEN + ;\n\n: # ( n -- n )\n base @ \/mod swap digit hold ;\n\n: #S ( n -- )\n BEGIN base @ \/mod dup\n WHILE swap digit hold\n REPEAT\n digit hold ;\n\n\n: (WARNING\") ( flag $message -- )\n swap\n IF count type\n ELSE drop\n THEN\n;\n\n: WARNING\" ( flag -- , print warning if true. )\n\t[compile] \" ( compile message )\n\tstate @\n\tIF compile (warning\")\n\tELSE (warning\")\n\tTHEN\n; IMMEDIATE\n\n: ABORT\" ( flag -- , print warning if true. )\n\t[compile] \" ( compile message )\n\tstate @\n\tIF compile (abort\")\n\tELSE (abort\")\n\tTHEN\n; IMMEDIATE\n\n: DEFER ( \"name\" -- )\n CREATE ['] ABORT ,\n DOES> ( ... -- ... ) @ EXECUTE ;\n\n: DEFER! ( xt2 xt1 -- )\n >BODY 4 CELL* + ! ;\n\n: DEFER@ ( xt1 -- xt2 )\n >BODY 4 CELL* + @ ;\n\n","old_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\\n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n\n: COUNT dup 1+ swap c@ ;\n\n\\ Miscellaneous support words\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: <= ( a b -- f , true if A <= b ) > 0= ;\n: >= ( a b -- f , true if A >= b ) < 0= ;\n: NOT ( n -- !n , logical negation ) 0= ;\n: DNEGATE ( d -- -d , negate by doing 0-d )\n 0 swap -\n;\n: CELL+ ( n -- n+cell ) cell + ;\n: CELL- ( n -- n-cell ) cell - ;\n: CELL* ( n -- n*cell ) cells ;\n\n: CHAR+ ( n -- n+size_of_char ) 1+ ;\n\\ : CHARS ( n -- n*size_of_char, don't do anything ) ; immediate\n\n\\ useful stack manipulation words\n: -ROT ( a b c -- c a b ) rot rot ;\n: 3DUP ( a b c -- a b c a b c ) 2 pick 2 pick 2 pick ;\n\n\\ ------------------------------------------------------------------\n: ID. ( nfa -- ) count 31 and type ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: PAD ( -- addr ) here 128 + ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n\n: BETWEEN ( n lo hi -- flag , true if between lo & hi )\n >r over r> > >r\n < r> or 0=\n;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: ? ( -- ) @ . ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ ' (lit) , cell 1- , ] +\n [ ' (lit) , cell 1- invert , ] and ;\n\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n: ALLOT ( nbytes -- , allot space in dictionary ) dp +! align ;\n\n: C, ( c -- ) here c! 1 dp +! ;\n\\ : W, ( w -- ) dp @ even-up dup dp ! w! 2 dp +! ;\n\\ : , ( n -- , lay into dictionary ) align here ! cell allot ;\n\n: SEE ( -- )\n ' dup\n >body swap >size\n disassemble ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token )\n [compile] literal ( compile a call to literal )\n ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick )\n ?comp ' [compile] literal\n; immediate\n\n: (DOES>) ( xt -- , modify previous definition to execute code at xt )\n latest >body \\ get address of code for new word\n 3 cell* + \\ offset to EXIT cell in create word\n ! \\ store execution token of DOES> code in new word\n;\n\n: DOES> ( -- , define execution code for CREATE word )\n 0 [compile] literal \\ dummy literal to hold xt\n here cell- \\ address of zero in literal\n compile (does>) \\ call (DOES>) from new creation word\n\t\t>r \\ move addrz to return stack so ; doesn't see stack garbage\n [compile] ; \\ terminate part of code before does>\n\t\tr>\n :noname ( addrz xt )\n compile rdrop \\ drop a stack frame (call becomes goto)\n swap ! \\ save execution token in literal\n; immediate\n\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 )\n swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 )\n dup cell+ @ swap @ ;\n\n: 2* ( n -- n*2 )\n 2 *\n;\n: 2\/ ( n -- n\/2 )\n 2 \/\n;\n\n\n\\ define some useful constants ------------------------------\n1 0= constant FALSE\n0 0= constant TRUE\n32 constant BL\n\n\\ Stack data structure ----------------------------------------\n\\ This is a general purpose stack utility used to implement necessary\n\\ stacks for the compiler or the user. Not real fast.\n\\ These stacks grow up which is different then normal.\n\\ cell 0 - stack pointer, offset from pfa of word\n\\ cell 1 - limit for range checking\n\\ cell 2 - first data location\n\n: :STACK ( #cells -- )\n CREATE 2 cells , ( offset of first data location )\n dup , ( limit for range checking, not currently used )\n cells cell+ allot ( allot an extra cell for safety )\n;\n\n: >STACK ( n stack -- , push onto stack, postincrement )\n dup @ 2dup cell+ swap ! ( -- n stack offset )\n + !\n;\n\n: STACK> ( stack -- n , pop , predecrement )\n dup @ cell- 2dup swap !\n + @\n;\n\n: STACK@ ( stack -- n , copy )\n dup @ cell- + @\n;\n\n: STACK.PICK ( index stack -- n , grab Nth from top of stack )\n dup @ cell- +\n swap cells - \\ offset for index\n @\n;\n: STACKP ( stack -- ptr , to next empty location on stack )\n\tdup @ +\n;\n\n: 0STACKP ( stack -- , clear stack)\n 8 swap !\n;\n\n32 :stack ustack\nustack 0stackp\n\n\\ Define JForth like words.\n: >US ustack >stack ;\n: US> ustack stack> ;\n: US@ ustack stack@ ;\n: 0USP ustack 0stackp ;\n\n\n\n\\ DO LOOP ------------------------------------------------\n\n3 constant do_flag\n4 constant leave_flag\n5 constant ?do_flag\n\n: DO ( -- , loop-back do_flag jump-from ?do_flag )\n ?comp\n compile (do)\n here >us do_flag >us ( for backward branch )\n; immediate\n\n: ?DO ( -- , loop-back do_flag jump-from ?do_flag , on user stack )\n ?comp\n ( leave address to set for forward branch )\n compile (?do)\n here 0 ,\n here >us do_flag >us ( for backward branch )\n >us ( for forward branch ) ?do_flag >us\n; immediate\n\n: LEAVE ( -- addr leave_flag )\n compile (leave)\n here 0 , >us\n leave_flag >us\n; immediate\n\n: LOOP-FORWARD ( -us- jump-from ?do_flag -- )\n BEGIN\n us@ leave_flag =\n us@ ?do_flag =\n OR\n WHILE\n us> leave_flag =\n IF\n us> here over - cell+ swap !\n ELSE\n us> dup\n here swap -\n cell+ swap !\n THEN\n REPEAT\n;\n\n: LOOP-BACK ( loop-addr do_flag -us- )\n us> do_flag ?pairs\n us> here - here\n !\n cell allot\n;\n\n: LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (loop)\n loop-forward loop-back\n; immediate\n\n\\ : DOTEST 5 0 do 333 . loop 888 . ;\n\\ : ?DOTEST0 0 0 ?do 333 . loop 888 . ;\n\\ : ?DOTEST1 5 0 ?do 333 . loop 888 . ;\n\n: +LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (+loop)\n loop-forward loop-back\n; immediate\n\n: UNLOOP ( loop-sys -r- )\n r> \\ save return pointer\n rdrop rdrop\n >r\n;\n\n\n: RECURSE ( ? -- ? , call the word currently being defined )\n latest compile,\n; immediate\n\n: SPACE bl emit ;\n: SPACES 512 min 0 max 0 ?DO space LOOP ;\n: 0SP depth 0 ?do drop loop ;\n\n\\ : >NEWLINE ( -- , CR if needed )\n\\ out @ 0>\n\\ IF cr\n\\ THEN\n\\ ;\n\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 ) swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 ) dup cell+ @ swap @ ;\n\n: DABS ( d -- |d| )\n dup 0<\n IF dnegate\n THEN\n;\n\n: S>D ( s -- d , extend signed single precision to double )\n dup 0<\n IF -1\n ELSE 0\n THEN\n;\n\n: D>S ( d -- s ) drop ;\n\n: PARSE-WORD ( \"name\" -- c-addr u ) bl parse ;\n: \/STRING ( addr len n -- addr' len' ) over min rot over + -rot - ;\n: PLACE ( addr len to -- , move string ) 3dup 1+ swap cmove c! drop ;\n\n: ASCII ( -- char, state smart )\n bl parse drop c@\n state @ 1 =\n IF [compile] literal\n ELSE\n THEN\n; immediate\n\n: CHAR ( -- char , interpret mode ) bl parse drop c@ ;\n: [CHAR] ( -- char , for compile mode )\n char [compile] literal\n; immediate\n\n: $TYPE ( $string -- ) count type ;\n: 'word ( -- addr ) here ;\n\n: EVEN ( addr -- addr' ) dup 1 and + ;\n\n: (C\") ( -- $addr ) r> dup count + aligned >r ;\n: (S\") ( -- c-addr cnt ) r> count 2dup + aligned >r ;\n: (.\") ( -- , type following string ) r> count 2dup + aligned >r type ;\n: \", ( addr len -- , place string into dict ) tuck 'word place 1+ allot align ;\n: ,\" ( -- ) [char] \" parse \", ;\n\n: .( ( --, type string delimited by parens )\n [char] ) parse type\n; immediate\n\n: .\" ( -- , type string )\n state @ 1 =\n IF compile (.\") ,\"\n ELSE [char] \" parse type\n THEN\n; immediate\n\n: .' ( -- , type string delimited by single quote )\n state @\n IF compile (.\") [char] ' parse \",\n ELSE [char] ' parse type\n THEN\n; immediate\n\n: C\" ( -- addr , return string address, ANSI )\n state @\n IF compile (c\") ,\"\n ELSE [char] \" parse pad place pad\n THEN\n; immediate\n\n: S\" ( -- , -- addr , return string address, ANSI )\n state @\n IF compile (s\") ,\"\n ELSE [char] \" parse pad place pad count\n THEN\n; immediate\n\n: \" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n: P\" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n\n\\ : \"\" ( -- addr )\n\\ state @\n\\ IF\n\\ compile (C\")\n\\ bl parse-word \",\n\\ ELSE\n\\ bl parse-word pad place pad\n\\ THEN\n\\ ; immediate\n\n: SLITERAL ( addr cnt -- , compile string )\n\tcompile (S\")\n\t\",\n; IMMEDIATE\n\n: $APPEND ( addr count $1 -- , append text to $1 )\n over >r\n dup >r\n count + ( -- a2 c2 end1 )\n swap cmove\n r> dup c@ ( a1 c1 )\n r> + ( -- a1 totalcount )\n swap c!\n;\n\n\\ ANSI word to replace [COMPILE] and COMPILE ----------------\n\\ : POSTPONE ( -- )\n\\\tbl word find\n\\\tdup 0=\n\\\tIF\n\\\t\t.\" Postpone could not find \" count type cr abort\n\\\tELSE\n\\\t\t0>\n\\\t\tIF compile, \\ immediate\n\\\t\tELSE (compile) \\ normal\n\\\t\tTHEN\n\\\tTHEN\n\\ ; immediate\n\n\\ -----------------------------------------------------------------\n\\ Auto Initialization\n: AUTO.INIT ( -- )\n\\ Kernel finds AUTO.INIT and executes it after loading dictionary.\n\\\t.\" Begin AUTO.INIT ------\" cr\n;\n: AUTO.TERM ( -- )\n\\ Kernel finds AUTO.TERM and executes it on bye.\n\\\t.\" End AUTO.TERM ------\" cr\n;\n\n\n: CLEARSTACK ( i*x -- )\n BEGIN depth\n WHILE drop\n REPEAT ;\n\nvariable pictured_output \\ hidden?\nvariable pictured_output_len \\ hidden?\n\n: <# ( -- ) pad pictured_output ! 0 pictured_output_len ! ;\n: #> ( -- addr n ) drop pictured_output @ pictured_output_len @ ;\n\n: HOLD ( c -- )\n pictured_output @ dup dup 1+ pictured_output_len @ cmove c!\n 1 pictured_output_len +!\n;\n\n\\ ------------------------ INPUT -------------------------------\n\n: SIGN ( n -- ) < 0 IF 45 hold THEN\n;\n\n: DIGIT ( n -- ascii )\n dup 10 < IF 48 ELSE 87 THEN + ;\n\n: # ( n -- n )\n base @ \/mod swap digit hold ;\n\n: #S ( n -- )\n BEGIN base @ \/mod dup\n WHILE swap digit hold\n REPEAT\n digit hold ;\n\n\n: (WARNING\") ( flag $message -- )\n swap\n IF count type\n ELSE drop\n THEN\n;\n\n: WARNING\" ( flag -- , print warning if true. )\n\t[compile] \" ( compile message )\n\tstate @\n\tIF compile (warning\")\n\tELSE (warning\")\n\tTHEN\n; IMMEDIATE\n\n: ABORT\" ( flag -- , print warning if true. )\n\t[compile] \" ( compile message )\n\tstate @\n\tIF compile (abort\")\n\tELSE (abort\")\n\tTHEN\n; IMMEDIATE\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"7137e320c205d0717d5ce00cc4ff68f43cdf8826","subject":"tests added","message":"tests added\n","repos":"bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas","old_file":"KataDiversion_tests.fth","new_file":"KataDiversion_tests.fth","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"mit","lang":"Forth"} {"commit":"8bd7b86763b1659927fcf19c7712b9e44ef2f0be","subject":"LOG2 rewrapped, DEC2BIN improved for 0 value","message":"LOG2 rewrapped, DEC2BIN improved for 0 value\n","repos":"bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas","old_file":"KataDiversion.fth","new_file":"KataDiversion.fth","new_contents":"\\ KataDiversion in Forth\n\n\\ -- utils\n\n\\ empty the stack\n: EMPTY\n DEPTH 0 <> IF BEGIN\n DROP DEPTH 0 =\n UNTIL\n THEN ;\n\n\\ power\n: ** ( n1 n2 -- n1_pow_n2 ) 1 SWAP ?DUP IF 0 DO OVER * LOOP THEN NIP ;\n\n\\ test if the top is a negative number\n: ?NEG ( n -- bool ) DUP 0= IF -1 ELSE DUP ABS <> THEN ;\n\n\\ log2 (integer)\n: LOG2 ( n -- log2_n ) DUP 1 < IF 1 ABORT\" Log2 need a positive value.\"\n ELSE DUP 1 = IF 0\n ELSE\n 1 >R\n BEGIN ( n |R: i=1)\n DUP DUP 2 I ** - 2 *\n ( n n 2*[n-2**i])\n R> 1 + >R ( \u2026 |R: i+1)\n > ( n n>2*[n-2**i] )\n UNTIL\n R> 1 -\n THEN\n THEN NIP ;\n\n\\ decimal to binary\n\\ e.g. : ( 11 -- 1 0 1 1 )\n\\ FIXME n DEC2BIN seems to give the binary value of n-1\n: DEC2BIN ( n -- n1 n2 n3 \u2026 ) DUP 0 <> IF\n LOG2 2 SWAP ** >R ( n |R: X=2 ** n.log2 )\n BEGIN\n DUP I - 0 > IF 1 SWAP I - ( 1 n-X )\n ELSE 0 SWAP ( 0 n )\n THEN\n I 1 =\n R> 2 \/ >R ( \u2026 | X\/2 )\n UNTIL\n R> 2DROP\n THEN\n ;\n\n\\ -- kata\n\n\\ test if the given N has two adjacent 1 bits\n\\ e.g. : 1011 -> -1\n\\ 1001 -> 0\n: ?TWO-ADJACENT-1-BITS ( n -- bool ) ( TODO ) ;\n\n\\ return the maximum number which can be made with N (given number) bits\n: ?MAX-NB ( n -- m ) DUP ?NEG IF DROP 0 ( 0 )\n ELSE \n DUP IF DUP 2 SWAP ** NIP ( 2**n )\n THEN\n THEN ;\n\n\n\\ return the number of numbers which can be made with N (given number) bits\n\\ or less, and which have not two adjacent 1 bits.\n\\ see http:\/\/www.codekata.com\/2007\/01\/code_kata_fifte.html\n: ?HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS ( n -- m ) ( TODO ) ;\n","old_contents":"\\ KataDiversion in Forth\n\n\\ -- utils\n\n\\ empty the stack\n: EMPTY\n DEPTH 0 <> IF BEGIN\n DROP DEPTH 0 =\n UNTIL\n THEN ;\n\n\\ power\n: ** ( n1 n2 -- n1_pow_n2 ) 1 SWAP ?DUP IF 0 DO OVER * LOOP THEN NIP ;\n\n\\ test if the top is a negative number\n: ?NEG ( n -- bool ) DUP 0= IF -1 ELSE DUP ABS <> THEN ;\n\n\\ log2 (integer)\n: LOG2 ( n -- log2_n ) DUP 1 < IF 1 ABORT\" Log2 need a positive value.\"\n ELSE DUP 1 = IF 0\n ELSE\n 1 >R\n BEGIN ( n |R: i)\n DUP DUP 2 I ( n n n 2 i |R: i)\n ** ( n n n 2**i )\n - ( n n n-2**i )\n 2 * ( n n 2*[n-2**i])\n R> 1 + >R ( \u2026 |R: i+1)\n > ( n n>2*[n-2**i] )\n UNTIL\n R> 1 -\n THEN\n THEN NIP ;\n\n\\ decimal to binary\n\\ e.g. : ( 11 -- 1 0 1 1 )\n\\ FIXME n DEC2BIN seems to give the binary value of n-1\n: DEC2BIN ( n -- n1 n2 n3 \u2026 ) DUP LOG2 2 SWAP ** >R ( n |R: X = 2 ** n.log2 )\n BEGIN\n DUP I - 0 > IF 1 SWAP I - ( 1 n-X )\n ELSE 0 SWAP ( 0 n )\n THEN\n I 1 =\n R> 2 \/ >R ( \u2026 | X\/2 )\n UNTIL\n R> 2DROP\n ;\n\n\\ -- kata\n\n\\ test if the given N has two adjacent 1 bits\n\\ e.g. : 1011 -> -1\n\\ 1001 -> 0\n: ?TWO-ADJACENT-1-BITS ( n -- bool ) ( TODO ) ;\n\n\\ return the maximum number which can be made with N (given number) bits\n: ?MAX-NB ( n -- m ) DUP ?NEG IF DROP 0 ( 0 )\n ELSE \n DUP IF DUP 2 SWAP ** NIP ( 2**n )\n THEN\n THEN ;\n\n\n\\ return the number of numbers which can be made with N (given number) bits\n\\ or less, and which have not two adjacent 1 bits.\n\\ see http:\/\/www.codekata.com\/2007\/01\/code_kata_fifte.html\n: ?HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS ( n -- m ) ( TODO ) ;\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"0825c867b28af945a29d3b39c87094702f7ba7b2","subject":"Added many more forth word definitions - inc. working compiler & conditionals","message":"Added many more forth word definitions - inc. working compiler & conditionals","repos":"rm-hull\/byok,rm-hull\/byok,rm-hull\/byok,rm-hull\/byok","old_file":"forth\/src\/forth\/system.fth","new_file":"forth\/src\/forth\/system.fth","new_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\ \n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: CELL 1 ;\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n \n: COUNT dup 1 + swap c@ ;\n\n\\ Miscellaneous support words\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: CELL+ ( n -- n+cell ) cell + ;\n: CELL- ( n -- n-cell ) cell - ;\n: CELL* ( n -- n*cell ) cells ;\n\n: CHAR+ ( n -- n+size_of_char ) 1+\n\\ : CHARS ( n -- n*size_of_char, don't do anything ) ; immediate\n\n\\ useful stack manipulation words\n: -ROT ( a b c -- c a b ) rot rot ;\n: 3DUP ( a b c -- a b c a b c ) 2 pick 2 pick 2 pick ;\n\n\\ ------------------------------------------------------------------\n: ID. ( nfa -- ) count 31 and type ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: PAD ( -- addr ) here 128 + ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ cell 1- ] literal +\n [ cell 1- invert ] literal and ;\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n\\ : ALLOT ( nbytes -- , allot space in dictionary ) dp +! ( align ) ;\n\\ : C, ( c -- ) here c! 1 chars dp +! ;\n\\ : W, ( w -- ) dp @ even-up dup dp ! w! 2 chars dp +! ;\n\\ : , ( n -- , lay into dictionary ) align here ! cell allot ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token ) \n [compile] literal ( compile a call to literal )\n , ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n: :NONAME ( -- xt , begin compilation of headerless secondary ) align here ] ;\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick ) \n ?comp ' [compile] literal \n; immediate\n\n: RECURSE ( ? -- ? , call the word currently being defined ) \n latest compile, \n; immediate\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 ) swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 ) dup cell+ @ swap @ ;\n\n: \/STRING ( addr len n -- addr' len' ) over min rot over + -rot - ;\n: PLACE ( addr len to -- , move string ) 3dup 1+ swap cmove c! drop ;\n\n: ASCII ( -- char, state smart )\n bl parse drop c@\n state @\n IF [compile] literal\n THEN \n; immediate\n\n: CHAR ( -- char , interpret mode ) bl parse drop c@ ;\n: [CHAR] ( -- char , for compile mode )\n char [compile] literal \n; immediate\n\n: 'word ( -- addr ) here ;\n\n: (C\") ( -- $addr ) r> dup count + aligned >r ;\n: (S\") ( -- c-addr cnt ) r> count 2dup + aligned >r ;\n: (.\") ( -- , type following string ) r> count 2dup + aligned r> type ;\n: \", ( addr len -- , place string into dict ) tuck 'word place 1+ allot align ;\n: ,\" ( -- ) [char] \" parse \", ;\n\n: .( ( --, type string delimited by parens )\n [char] ) parse type\n; immediate\n\n: .\" ( -- , type string )\n state @\n IF compile (.\") ,\"\n ELSE [char] \" parse type\n THEN \n; immediate\n\n","old_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\ \n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: CELL 1 ;\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: CELL+ ( x -- x+cell ) cell + ;\n: CELL- ( x -- x-cell ) cell - ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: PAD ( -- addr ) here 128 + ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n \n: COUNT dup 1 + swap c@ ;\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ cell 1- ] literal +\n [ cell 1- invert ] literal and ;\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token ) \n [compile] literal ( compile a call to literal )\n ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n: :NONAME ( -- xt , begin compilation of headerless secondary ) align here ] ;\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick ) ?comp ' [compile] literal ; immediate\n\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"709cf475bad165f966f75630f5b40da3d32603d5","subject":"Get rid of a manifest constant.","message":"Get rid of a manifest constant.","repos":"rbsexton\/gecko,rbsexton\/gecko,rbsexton\/gecko","old_file":"tiny\/bringup\/forth\/Drivers\/serLE_p.fth","new_file":"tiny\/bringup\/forth\/Drivers\/serLE_p.fth","new_contents":"\\ serLE_p.fth - Polled Driver for the low-energy UART.\r\n\\ Assumes that the hardware is already setup by the launcher.\r\n\\\r\n\\ Note - The assumption here is that the LEUART is running at 9600 baud\r\n\\ The Zero Gecko can wake in 2us, and a character takes 10ms at this baud rate.\r\n\\ So we might as well WFI if the FIFO is full.\r\n\r\n\\ ********************\r\n\\ *S Serial primitives\r\n\\ ********************\r\n\r\n$8 equ LEUART_STATUS\r\nbit4 equ LEUART_STATUS_TXBL\r\nbit5 equ LEUART_STATUS_RXDATAV\r\n\r\n$1C equ LEUART_RXDATA\r\n$28 equ LEUART_TXDATA\r\n\r\ninternal\r\n\r\n: +FaultConsole\t( -- ) ;\r\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\r\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\r\n\\ ** for more details.\r\n\r\n: (seremit)\t\\ char base --\r\n\\ *G Transmit a character on the given UART.\r\n begin\r\n dup LEUART_STATUS + @ LEUART_STATUS_TXBL and \\ Tx FIFO full test\r\n until\r\n LEUART_TXDATA + !\r\n;\r\n\r\n: (sertype)\t\\ caddr len base --\r\n\\ *G Transmit a string on the given UART.\r\n -rot bounds\r\n ?do i c@ over (seremit) loop\r\n drop\r\n;\r\n\r\n: (sercr)\t\\ base --\r\n\\ *G Transmit a CR\/LF pair on the given UART.\r\n $0D over (seremit) $0A swap (seremit)\r\n;\r\n\r\n: (serkey?)\t\\ base -- t\/f\r\n\\ *G Return true if the given UART has a character avilable to read.\r\n LEUART_STATUS + @ LEUART_STATUS_RXDATAV and \\ Rx FIFO\r\n;\r\n\r\n: (serkey)\t\\ base -- char\r\n\\ *G Wait for a character to come available on the given UART and\r\n\\ ** return the character.\r\n begin\r\n dup (serkey?) \r\n \\ dup 0= if [ tasking? ] [if] pause [else] [asm wfi asm] [then] then \r\n until\r\n LEUART_RXDATA + @\r\n;\r\n\r\n: initUART\t\\ divisor22 base --\r\n drop drop\r\n;\r\n\r\nexternal\r\n\r\n\r\n\\ ********\r\n\\ *S UART0\r\n\\ ********\r\n\r\nuseUART0? [if]\r\n\r\n: init-ser0\t; \r\n\r\n: seremit0\t\\ char --\r\n\\ *G Transmit a character on UART0.\r\n _LEUART0 (seremit) ;\r\n: sertype0\t\\ c-addr len --\r\n\\ *G Transmit a string on UART0.\r\n _LEUART0 (sertype) ;\r\n: sercr0\t\\ --\r\n\\ *G Issue a CR\/LF pair to UART0.\r\n _LEUART0 (sercr) ;\r\n: serkey?0\t\\ -- flag\r\n\\ *G Return true if UART0 has a character available.\r\n _LEUART0 (serkey?) ;\r\n: serkey0\t\\ -- char\r\n\\ *G Wait for a character on UART0.\r\n _LEUART0 (serkey) ;\r\n\r\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\r\n\\ *G Generic I\/O device for UART0.\r\n ' serkey0 ,\t\t\\ -- char ; receive char\r\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\r\n ' seremit0 ,\t\t\\ -- char ; display char\r\n ' sertype0 ,\t\t\\ caddr len -- ; display string\r\n ' sercr0 ,\t\t\\ -- ; display new line\r\nconsole-port 0 = [if]\r\n console0 constant console\r\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\r\n\\ ** It may be changed by one of the phrases of the form:\r\n\\ *C dup opvec ! ipvec !\r\n\\ *C SetConsole\r\n[then]\r\n\r\n[then]\r\n\r\n\r\n\\ ************************\r\n\\ *S System initialisation\r\n\\ ************************\r\n\r\n: init-ser\t\\ --\r\n\\ *G Initialise all serial ports\r\n [ useUART0? ] [if] init-ser0 [then]\r\n;\r\n\r\n\r\n\\ ======\r\n\\ *> ###\r\n\\ ======\r\n\r\ndecimal\r\n","old_contents":"\\ serLE_p.fth - Polled Driver for the low-energy UART.\r\n\\ Assumes that the hardware is already setup by the launcher.\r\n\\\r\n\\ Note - The assumption here is that the LEUART is running at 9600 baud\r\n\\ The Zero Gecko can wake in 2us, and a character takes 10ms at this baud rate.\r\n\\ So we might as well WFI if the FIFO is full.\r\n\r\n\\ ********************\r\n\\ *S Serial primitives\r\n\\ ********************\r\n\r\n$8 equ LEUART_STATUS\r\nbit5 equ LEUART_STATUS_RXDATAV\r\n\r\n$1C equ LEUART_RXDATA\r\n$28 equ LEUART_TXDATA\r\n\r\ninternal\r\n\r\n: +FaultConsole\t( -- ) ;\r\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\r\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\r\n\\ ** for more details.\r\n\r\n: (seremit)\t\\ char base --\r\n\\ *G Transmit a character on the given UART.\r\n begin\r\n dup LEUART_STATUS + @ bit4 and \t\t\\ Tx FIFO full test\r\n until\r\n LEUART_TXDATA + !\r\n;\r\n\r\n: (sertype)\t\\ caddr len base --\r\n\\ *G Transmit a string on the given UART.\r\n -rot bounds\r\n ?do i c@ over (seremit) loop\r\n drop\r\n;\r\n\r\n: (sercr)\t\\ base --\r\n\\ *G Transmit a CR\/LF pair on the given UART.\r\n $0D over (seremit) $0A swap (seremit)\r\n;\r\n\r\n: (serkey?)\t\\ base -- t\/f\r\n\\ *G Return true if the given UART has a character avilable to read.\r\n LEUART_STATUS + @ LEUART_STATUS_RXDATAV and \\ Rx FIFO\r\n;\r\n\r\n: (serkey)\t\\ base -- char\r\n\\ *G Wait for a character to come available on the given UART and\r\n\\ ** return the character.\r\n begin\r\n dup (serkey?) \r\n \\ dup 0= if [ tasking? ] [if] pause [else] [asm wfi asm] [then] then \r\n until\r\n LEUART_RXDATA + @\r\n;\r\n\r\n: initUART\t\\ divisor22 base --\r\n drop drop\r\n;\r\n\r\nexternal\r\n\r\n\r\n\\ ********\r\n\\ *S UART0\r\n\\ ********\r\n\r\nuseUART0? [if]\r\n\r\n: init-ser0\t; \r\n\r\n: seremit0\t\\ char --\r\n\\ *G Transmit a character on UART0.\r\n _LEUART0 (seremit) ;\r\n: sertype0\t\\ c-addr len --\r\n\\ *G Transmit a string on UART0.\r\n _LEUART0 (sertype) ;\r\n: sercr0\t\\ --\r\n\\ *G Issue a CR\/LF pair to UART0.\r\n _LEUART0 (sercr) ;\r\n: serkey?0\t\\ -- flag\r\n\\ *G Return true if UART0 has a character available.\r\n _LEUART0 (serkey?) ;\r\n: serkey0\t\\ -- char\r\n\\ *G Wait for a character on UART0.\r\n _LEUART0 (serkey) ;\r\n\r\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\r\n\\ *G Generic I\/O device for UART0.\r\n ' serkey0 ,\t\t\\ -- char ; receive char\r\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\r\n ' seremit0 ,\t\t\\ -- char ; display char\r\n ' sertype0 ,\t\t\\ caddr len -- ; display string\r\n ' sercr0 ,\t\t\\ -- ; display new line\r\nconsole-port 0 = [if]\r\n console0 constant console\r\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\r\n\\ ** It may be changed by one of the phrases of the form:\r\n\\ *C dup opvec ! ipvec !\r\n\\ *C SetConsole\r\n[then]\r\n\r\n[then]\r\n\r\n\r\n\\ ************************\r\n\\ *S System initialisation\r\n\\ ************************\r\n\r\n: init-ser\t\\ --\r\n\\ *G Initialise all serial ports\r\n [ useUART0? ] [if] init-ser0 [then]\r\n;\r\n\r\n\r\n\\ ======\r\n\\ *> ###\r\n\\ ======\r\n\r\ndecimal\r\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"cc075aa5a835de5b7d5df5891a402e06acd3302f","subject":"Update test.4th","message":"Update test.4th","repos":"AshleyF\/Forthkit,AshleyF\/Forthkit,AshleyF\/Forthkit","old_file":"hardware\/register\/test.4th","new_file":"hardware\/register\/test.4th","new_contents":"( simple assembler\/VM test - capitalize [-32] console input )\n( requires assembler )\n\n0 const u ( to upper )\n1 const c ( char )\n\n 32 u ldc,\n label &start\n c in,\n c u c sub,\n c out,\n&start jump,\n\nassemble\n","old_contents":"( simple assembler\/VM test - capitalize [-32] console input )\n( requires assembler )\n\n0 const u\n1 const c\n\n 32 u ldc,\n label &start\n c in,\n c u c sub,\n c out,\n&start jump,\n\nassemble\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"05d248685dd224e5ab58a6327f5a10c2dcff538a","subject":"Fix things up so it's easier to use the blocking sys calls.","message":"Fix things up so it's easier to use the blocking sys calls.","repos":"rbsexton\/sockpuppet,rbsexton\/sockpuppet","old_file":"forth\/serCM3_sapi_p.fth","new_file":"forth\/serCM3_sapi_p.fth","new_contents":"\\ serCM3_sapi_p.fth - SAPI polled RX, polled TX, serial communication drivers\n\\ Written to run against the SockPuppet API.\n\n((\nAdapted from: the LPC polled driver.\n))\n\nonly forth definitions\nvariable cnt.pause \n\n\\ ==============\n\\ *! serCM3_sapi_p\n\\ *T SAPI polled serial driver\n\\ ==============\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\n\\ ** using the internal UARTs via the SAPI call layer.\n\n\n\\ ****************\n\\ *S Configuration\n\\ ****************\n\\ *P Configuration is managed by the SAPI\n\n\\ ********\n\\ *S Tools\n\\ ********\n\ntarget\n\n\\ ********************\n\\ *S Serial primitives\n\\ ********************\ninternal\n\n: +FaultConsole\t( -- ) ;\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\n\\ ** for more details.\n\ntarget\n\nCODE (seremitfc)\t\\ char base --\n\\ *G Service call for a single char - just fill in the registers\n\\ from the stack and make the call, and get back the flow control feedback\n\\ Put TOS into r0, pull r1 off the stack, and refresh the stack.\n\tmov r0, tos\n\tldr r1, [ psp ], # 4\t\n\tsvc # SAPI_VEC_PUTCHAR\t\n\tmov tos, r0\n next,\nEND-CODE\n\n: (seremit-blocking)\t\\ char base -- \n\\ *G Wrapped call that checks for throttling, and if so,\n\\ calls PAUSE to let another task run. Count these events for debugging purposes.\n\tDUP >R (seremitfc)\n\t0<> IF 1 cnt.pause +!\n\t\tself tcb.bbstatus @ R> 0 setiocallback drop stop \n\t\telse R> DROP then\n \t;\n\n: (seremit)\t\\ char base -- \n\\ *G Wrapped call that checks for throttling, and if so,\n\\ calls PAUSE to let another task run. Count these events for debugging purposes.\n\t(seremitfc)\n\t0<> IF 1 cnt.pause +! PAUSE THEN\n\t;\n\n: (sertype)\t\\ caddr len base --\n\\ *G Transmit a string on the given UART.\n -rot bounds\n ?do i c@ over (seremit) loop\n drop\n;\n\n: (sercr)\t\\ base --\n\\ *G Transmit a CR\/LF pair on the given UART.\n $0D over (seremit) $0A swap (seremit)\n;\n\nCODE (sergetchar) \\ base -- c\n\\ *G Get a character from the port\n\tmov r0, tos\t\n\tsvc # SAPI_VEC_GETCHAR\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE (serkey?) \\ base -- t\/f\n\\ *G Return true if the given UART has a character avilable to read.\n\\ The call returns 0 or 1. \n\tmov r0, tos\n\tsvc # SAPI_VEC_GETCHARAVAIL\t\t\n\tmov tos, r0\n\tnext,\t\nEND-CODE\n\n\\ Loop with pause until we get a non-zero result.\n: (serkey-pause) pause (serkey?) ;\n\n\\ A blocking version of (serkey-basic)\n: (serkey-block)\n\tself tcb.bbstatus @ over 1 setiocallback drop ( base )\n\tself halt \n\tdup (serkey?) IF self restart ELSE PAUSE THEN \\ We are now armed and ready to block\n (serkey?) \n;\n\n\\ *G Wait for a character to come available on the given UART and\n\\ ** return the character.\n\\ Advanced usage - Register a callback. \n\\ The tricky part is not screwing things up by missing a character\n\\ in the window between when you register, and when you pick up your\n\\ character. The way to do that is by registering, then self \n\\ halting, and then checking for a new character. That ensures that\n\\ if a character has slipped in, you will catch it.\n: (serkey)\t\\ base -- char\n\tbegin dup (serkey-pause) until (sergetchar)\n;\n\nexternal \n\n: seremit0\t\\ char --\n\\ *G Transmit a character on UART0.\n 0 (seremit) ;\n: sertype0\t\\ c-addr len --\n\\ *G Transmit a string on UART0.\n 0 (sertype) ;\n: sercr0\t\\ --\n\\ *G Issue a CR\/LF pair to UART0.\n 0 (sercr) ;\n: serkey?0\t\\ -- flag\n\\ *G Return true if UART0 has a character available.\n 0 (serkey?) ;\n: serkey0\t\\ -- char\n\\ *G Wait for a character on UART0.\n 0 (serkey) ;\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\n\\ *G Generic I\/O device for UART0.\n ' serkey0 ,\t\t\\ -- char ; receive char\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\n ' seremit0 ,\t\t\\ -- char ; display char\n ' sertype0 ,\t\t\\ caddr len -- ; display string\n ' sercr0 ,\t\t\\ -- ; display new line\n\n\\ UART2\n: seremit2 #2 (seremit) ;\n: sertype2\t#2 (sertype) ;\n: sercr2\t#2 (sercr) ;\n: serkey?2\t#2 (serkey?) ;\n: serkey2\t#2 (serkey) ;\ncreate Console2 ' serkey2 , ' serkey?2 , ' seremit2 , ' sertype2 , ' sercr2 ,\t\n\n\\ Versions for use with the TCP Port (10)\n: seremit10 #10 (seremit) ;\n: sertype10\t#10 (sertype) ;\n: sercr10\t#10 (sercr) ;\n: serkey?10\t#10 (serkey?) ;\n: serkey10\t#10 (serkey) ;\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\n\nconsole-port 0 = [if]\n console0 constant console\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\n\\ ** It may be changed by one of the phrases of the form:\n\\ *C dup opvec ! ipvec !\n\\ *C SetConsole\n[then]\n\nconsole-port #1 = [if]\n console1 constant console\n[then]\n\nconsole-port #10 = [if]\n console10 constant console\n[then]\n\n\\ ************************\n\\ *S System initialisation\n\\ ************************\n\n\\ This is a NOP in the SAPI environment\n: init-ser ;\t\\ --\n\\ *G Initialise all serial ports\n\n\n\\ ======\n\\ *> ###\n\\ ======\n\ndecimal\n","old_contents":"\\ serCM3_sapi_p.fth - SAPI polled RX, polled TX, serial communication drivers\n\\ Written to run against the SockPuppet API.\n\n((\nAdapted from: the LPC polled driver.\n))\n\nonly forth definitions\nvariable cnt.pause \n\n\\ ==============\n\\ *! serCM3_sapi_p\n\\ *T SAPI polled serial driver\n\\ ==============\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\n\\ ** using the internal UARTs via the SAPI call layer.\n\n\n\\ ****************\n\\ *S Configuration\n\\ ****************\n\\ *P Configuration is managed by the SAPI\n\n\\ ********\n\\ *S Tools\n\\ ********\n\ntarget\n\n\\ ********************\n\\ *S Serial primitives\n\\ ********************\ninternal\n\n: +FaultConsole\t( -- ) ;\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\n\\ ** for more details.\n\ntarget\n\nCODE (seremitfc)\t\\ char base --\n\\ *G Service call for a single char - just fill in the registers\n\\ from the stack and make the call, and get back the flow control feedback\n\\ Put TOS into r0, pull r1 off the stack, and refresh the stack.\n\tmov r0, tos\n\tldr r1, [ psp ], # 4\t\n\tsvc # SAPI_VEC_PUTCHAR\t\n\tmov tos, r0\n next,\nEND-CODE\n\n: (seremit)\t\\ char base -- \n\\ *G Wrapped call that checks for throttling, and if so,\n\\ calls PAUSE to let another task run. Count these events for debugging purposes.\n\tDUP >R (seremitfc)\n\t0<> IF 1 cnt.pause +!\n\t\tself tcb.bbstatus @ R> 0 setiocallback drop stop \n\t\telse R> DROP then\n\t;\n\n: (sertype)\t\\ caddr len base --\n\\ *G Transmit a string on the given UART.\n -rot bounds\n ?do i c@ over (seremit) loop\n drop\n;\n\n: (sercr)\t\\ base --\n\\ *G Transmit a CR\/LF pair on the given UART.\n $0D over (seremit) $0A swap (seremit)\n;\n\nCODE (sergetchar) \\ base -- c\n\\ *G Get a character from the port\n\tmov r0, tos\t\n\tsvc # SAPI_VEC_GETCHAR\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE (serkey?) \\ base -- t\/f\n\\ *G Return true if the given UART has a character avilable to read.\n\\ The call returns 0 or 1. \n\tmov r0, tos\n\tsvc # SAPI_VEC_GETCHARAVAIL\t\t\n\tmov tos, r0\n\tnext,\t\nEND-CODE\n\n: (serkey-basic)\n\tbegin pause \n\tdup (serkey?) until \n\t(sergetchar)\n;\n\n: (serkey-sleep?)\n\tself tcb.bbstatus @ over 1 setiocallback drop ( base )\n\tself halt \n\tdup (serkey?) IF self restart ELSE PAUSE THEN \\ We are now armed and ready to block\n (serkey?) \n;\n\n\\ *G Wait for a character to come available on the given UART and\n\\ ** return the character.\n\\ Advanced usage - Register a callback. \n\\ The tricky part is not screwing things up by missing a character\n\\ in the window between when you register, and when you pick up your\n\\ character. The way to do that is by registering, then self \n\\ halting, and then checking for a new character. That ensures that\n\\ if a character has slipped in, you will catch it.\n: (serkey)\t\\ base -- char\n\tbegin dup (serkey-sleep?) until (sergetchar)\n;\n\nexternal \n\n: seremit0\t\\ char --\n\\ *G Transmit a character on UART0.\n 0 (seremit) ;\n: sertype0\t\\ c-addr len --\n\\ *G Transmit a string on UART0.\n 0 (sertype) ;\n: sercr0\t\\ --\n\\ *G Issue a CR\/LF pair to UART0.\n 0 (sercr) ;\n: serkey?0\t\\ -- flag\n\\ *G Return true if UART0 has a character available.\n 0 (serkey?) ;\n: serkey0\t\\ -- char\n\\ *G Wait for a character on UART0.\n 0 (serkey) ;\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\n\\ *G Generic I\/O device for UART0.\n ' serkey0 ,\t\t\\ -- char ; receive char\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\n ' seremit0 ,\t\t\\ -- char ; display char\n ' sertype0 ,\t\t\\ caddr len -- ; display string\n ' sercr0 ,\t\t\\ -- ; display new line\n\n\\ UART2\n: seremit2 #2 (seremit) ;\n: sertype2\t#2 (sertype) ;\n: sercr2\t#2 (sercr) ;\n: serkey?2\t#2 (serkey?) ;\n: serkey2\t#2 (serkey) ;\ncreate Console2 ' serkey2 , ' serkey?2 , ' seremit2 , ' sertype2 , ' sercr2 ,\t\n\n\\ Versions for use with the TCP Port (10)\n: seremit10 #10 (seremit) ;\n: sertype10\t#10 (sertype) ;\n: sercr10\t#10 (sercr) ;\n: serkey?10\t#10 (serkey?) ;\n: serkey10\t#10 (serkey) ;\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\n\nconsole-port 0 = [if]\n console0 constant console\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\n\\ ** It may be changed by one of the phrases of the form:\n\\ *C dup opvec ! ipvec !\n\\ *C SetConsole\n[then]\n\nconsole-port #1 = [if]\n console1 constant console\n[then]\n\nconsole-port #10 = [if]\n console10 constant console\n[then]\n\n\\ ************************\n\\ *S System initialisation\n\\ ************************\n\n\\ This is a NOP in the SAPI environment\n: init-ser ;\t\\ --\n\\ *G Initialise all serial ports\n\n\n\\ ======\n\\ *> ###\n\\ ======\n\ndecimal\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"9599f3ed831b27a2e76d93d23c8901830471cca0","subject":"Do it the forth way\u2026","message":"Do it the forth way\u2026","repos":"rbsexton\/gecko,rbsexton\/gecko,rbsexton\/gecko","old_file":"tiny\/basic\/forth\/startup.fth","new_file":"tiny\/basic\/forth\/startup.fth","new_contents":"(( App Startup ))\n\n0 value JT \\ The Jumptable\n\n\\ -------------------------------------------\n\\ The word that sets everything up.\n\\ This runs before the intro banner, after\n\\ Init-multi.\n\\ -------------------------------------------\n: StartApp\n\thex\n\tinit-dp @ dp ! \\ Set the dictionary pointer so that we can function.\n\t\\ I have no idea why I am doing this instead of the compilation system.\n\n\t1 getruntimelinks to jt\n\t.\" StartApp!\" \n\n\t4 [ SCSSCR _SCS + ] literal ! \\ Set deepsleep\n\t\t\t\n;\n\n\\ ------------------------------------------\n\\ Application code\n\\ ------------------------------------------\nstruct tod\n 1 field h\n 1 field m\n 1 field s\nend-struct\n \nudata\ncreate hms tod allot\ncreate dhms tod allot\ncdata\n\n: +CAP ( n max -- n ) >R 1 + dup r> = if drop 0 then ; \n\n: ADVANCE ( tod -- )\n dup s c@ #60 +cap 2dup swap s c! \\ Advance the seconds. base n -- \n if drop exit then\n \n dup m c@ #60 +cap 2dup swap m c! \\ advance minutes\n if drop exit then\n\n dup h c@ #24 +cap 2dup swap h c! \\ advance minutes\n\n 2drop \n;\n\n: DADVANCE ( tod -- )\n dup s c@ #100 +cap 2dup swap s c! \\ Advance the seconds. base n -- \n if drop exit then\n \n dup m c@ #100 +cap 2dup swap m c! \\ advance minutes\n if drop exit then\n\n dup h c@ #10 +cap 2dup swap h c! \\ advance minutes\n\n 2drop \n;\n\n\\ ----------------------------------------------\n\\ Tools for writing to the LCD\n\\ ----------------------------------------------\n: LCD#! ( n -- ) jt LCD_# @ swap call1-- ;\n: LCD$! ( addr -- ) jt LCD_Wr @ swap call1-- ; \n\nvariable thecount\n\n(( Sample code for demonstrating messages ))\n: wakestart 1 $10 wakereq drop ; \\ Request a wake \n: wakestop 1 0 wakereq drop ; \\ No more, please. \n\n: COUNT-WORD\n wakestart\n begin\n pause\n thecount dup @ 1+ dup lcd#! swap ! \n stop \n again\n;\n\n: COUNT-WORDd\n begin\n pause self msg? if get-message drop \\ We don't care who sent it.\n case \n 0 of wakestop endof\n 1 of wakestart endof\n endcase\n then\n\n thecount dup @ 1+ dup lcd#! swap ! \n stop \n again\n;\n\n\\ --------------------------------------------------------------------\n\\ Keeping time.\n\\ --------------------------------------------------------------------\ntask TOPTASK \n\n: TOPLCDOUT hms dup h c@ #100 * swap m c@ + lcd#! ; \n\n: TOPWORD\n 0 $10 wakereq drop \\ The first Second. \n begin\n pause\n toplcdout \n hms advance\n 2 $10 wakereq drop \\ Relative step\n again\n; \n\n\n\\ --------------------------------------------------------------------\n\\ Decimal Time\n\\ --------------------------------------------------------------------\n\ntask BOTTASK\n\n: BOTWORD\n 1 err interp-next wakereq drop \n begin\n pause\n dhms dadvance\n botlcd dms$ drop lcd$!\n 3 err interp-next wakereq drop \n again\n; \n\n: BOTLCD dhms\n dup h c@ #10000 *\n over m c@ #100 * +\n swap s c@ + ;\n\n\\ Include the terminating null.\n: dms$ base @ >R decimal s>d <# 0 hold # # $20 hold # # $20 hold # #> R> base ! ; \n\n: interp-next ( addr -- ) \\ A fixed version. Returns amount to step\n dup @ \\ err\n #103 - dup 1 > if swap ! #13 exit then\n \\ Otherwise, we need to adjust\n #125 + swap ! #14 \n;\n\n: CLOCKSTART\n ['] topword toptask initiate\n ['] botword bottask initiate \n;\n\nvariable err \n\n: COUNT-DT\n 0 err interp-next wakereq drop \\ Don't keep the return code.\n begin \n pause\n thecount dup @ 1 #9999 +cap dup lcd#! swap ! \n 2 err interp-next wakereq drop \\ Don't keep the return code. \n again\n;\n\n\\ ---------------------------------------------------------------\n\\ Setting the time.\n\\ ---------------------------------------------------------------\n\n: *HMS->S ( addr -- n ) dup h c@ #3600 * over m c@ #60 * + swap s c@ + ; \n: *DHMS->S ( addr -- n ) dup h c@ #10000 * over m c@ #100 * + swap s c@ + ; \n\n\\ Stash things in the struct.\n: ->*HMS ( h m s addr -- ) dup >R s c! R@ m c! R> h c! ; \n\n: S->DS ( seconds -- seconds )\n dup #108 \/ #125 * \\ First pass \n swap #108 mod #125 * #108 \/ +\n;\n\n: DS->DHMS ( n -- h m s ) \n #10000 \/mod swap \n #100 \/mod swap \n ;\n\n: SETBOTH ( h m s -- ) \n hms ->*hms\n hms *hms->s\n s->ds ds->dhms\n dhms ->*hms \n;\n\n\n((\ntask foo \n' count-word foo initiate\n\n))\n\n \n\n\n","old_contents":"(( App Startup ))\n\n0 value JT \\ The Jumptable\n\n\\ -------------------------------------------\n\\ The word that sets everything up.\n\\ This runs before the intro banner, after\n\\ Init-multi.\n\\ -------------------------------------------\n: StartApp\n\thex\n\tinit-dp @ dp ! \\ Set the dictionary pointer so that we can function.\n\t\\ I have no idea why I am doing this instead of the compilation system.\n\n\t1 getruntimelinks to jt\n\t.\" StartApp!\" \n\n\t4 [ SCSSCR _SCS + ] literal ! \\ Set deepsleep\n\t\t\t\n;\n\n\\ ------------------------------------------\n\\ Application code\n\\ ------------------------------------------\nstruct tod\n 1 field h\n 1 field m\n 1 field s\nend-struct\n \nudata\ncreate hms tod allot\ncreate dhms tod allot\ncdata\n\n: +CAP ( n max -- n ) >R 1 + dup r> = if drop 0 then ; \n\n: ADVANCE ( tod -- )\n dup s c@ #60 +cap 2dup swap s c! \\ Advance the seconds. base n -- \n if drop exit then\n \n dup m c@ #60 +cap 2dup swap m c! \\ advance minutes\n if drop exit then\n\n dup h c@ #24 +cap 2dup swap h c! \\ advance minutes\n\n 2drop \n;\n\n: DADVANCE ( tod -- )\n dup s c@ #100 +cap 2dup swap s c! \\ Advance the seconds. base n -- \n if drop exit then\n \n dup m c@ #100 +cap 2dup swap m c! \\ advance minutes\n if drop exit then\n\n dup h c@ #10 +cap 2dup swap h c! \\ advance minutes\n\n 2drop \n;\n\n\\ ----------------------------------------------\n\\ Tools for writing to the LCD\n\\ ----------------------------------------------\n: LCD#! ( n -- ) jt LCD_# @ swap call1-- ;\n: LCD$! ( addr -- ) jt LCD_Wr @ swap call1-- ; \n\nvariable thecount\n\n(( Sample code for demonstrating messages ))\n: wakestart 1 $10 wakereq drop ; \\ Request a wake \n: wakestop 1 0 wakereq drop ; \\ No more, please. \n\n: COUNT-WORD\n wakestart\n begin\n pause\n thecount dup @ 1+ dup lcd#! swap ! \n stop \n again\n;\n\n: COUNT-WORDd\n begin\n pause self msg? if get-message drop \\ We don't care who sent it.\n case \n 0 of wakestop endof\n 1 of wakestart endof\n endcase\n then\n\n thecount dup @ 1+ dup lcd#! swap ! \n stop \n again\n;\n\n\\ --------------------------------------------------------------------\n\\ Keeping time.\n\\ --------------------------------------------------------------------\ntask TOPTASK \n\n: TOPLCDOUT hms dup h c@ #100 * swap m c@ + lcd#! ; \n\n: TOPWORD\n 0 $10 wakereq drop \\ The first Second. \n begin\n pause\n toplcdout \n hms advance\n 2 $10 wakereq drop \\ Relative step\n again\n; \n\n\n\\ --------------------------------------------------------------------\n\\ Decimal Time\n\\ --------------------------------------------------------------------\n\ntask BOTTASK\n\n: BOTWORD\n 1 err interp-next wakereq drop \n begin\n pause\n dhms dadvance\n botlcd dms$ drop lcd$!\n 3 err interp-next wakereq drop \n again\n; \n\n: BOTLCD dhms\n dup h c@ #10000 *\n over m c@ #100 * +\n swap s c@ + ;\n\n\\ Include the terminating null.\n: dms$ base @ >R decimal s>d <# 0 hold # # $20 hold # # $20 hold # #> R> base ! ; \n\n: interp-next ( addr -- ) \\ A fixed version. Returns amount to step\n dup @ \\ err\n #103 - dup 1 > if swap ! #13 exit then\n \\ Otherwise, we need to adjust\n #125 + swap ! #14 \n;\n\n: CLOCKSTART\n ['] topword toptask initiate\n ['] botword bottask initiate \n;\n\nvariable err \n\n: COUNT-DT\n 0 err interp-next wakereq drop \\ Don't keep the return code.\n begin \n pause\n thecount dup @ 1 #9999 +cap dup lcd#! swap ! \n 2 err interp-next wakereq drop \\ Don't keep the return code. \n again\n;\n\n\\ ---------------------------------------------------------------\n\\ Setting the time.\n\\ ---------------------------------------------------------------\n\n: *HMS->S ( addr -- n ) dup h c@ #3600 * over m c@ #60 * + swap s c@ + ; \n: *DHMS->S ( addr -- n ) dup h c@ #10000 * over m c@ #100 * + swap s c@ + ; \n\n\\ Stash things in the struct.\n: ->*HMS ( h m s addr -- ) dup >R s c! R@ m c! R> h c! ; \n\n: S->DS ( seconds -- seconds )\n dup #108 \/ #125 * \\ First pass \n swap #108 mod #125 * #108 \/ +\n;\n\n: DS->DHMS ( n -- h m s ) \n dup #10000 \/ swap #10000 mod \n dup #100 \/ swap #100 mod \n ;\n\n: SETBOTH ( h m s -- ) \n hms ->*hms\n hms *hms->s\n s->ds ds->dhms\n dhms ->*hms \n;\n\n\n((\ntask foo \n' count-word foo initiate\n\n))\n\n \n\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"9fdac657bca5bd01aea27b1b7f404dde1e4b91df","subject":"Fix c\/p error in comment.","message":"Fix c\/p error in comment.\n\nApproved by:\tadrian (co-mentor) (implicit)\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/menusets.4th","new_file":"sys\/boot\/forth\/menusets.4th","new_contents":"\\ Copyright (c) 2012 Devin Teske \n\\ All rights reserved.\n\\ \n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\ \n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\ \n\\ $FreeBSD$\n\nmarker task-menusets.4th\n\nvariable menuset_use_name\n\ncreate menuset_affixbuf\t255 allot\ncreate menuset_x 1 allot\ncreate menuset_y 1 allot\n\n: menuset-loadvar ( -- )\n\n\t\\ menuset_use_name is true or false\n\t\\ $type should be set to one of:\n\t\\ \tmenu toggled ansi\n\t\\ $var should be set to one of:\n\t\\ \tcaption command keycode text ...\n\t\\ $affix is either prefix (menuset_use_name is true)\n\t\\ or infix (menuset_use_name is false)\n\n\ts\" set cmdbuf='set ${type}_${var}=\\$'\" evaluate\n\ts\" cmdbuf\" getenv swap drop ( -- u1 ) \\ get string length\n\tmenuset_use_name @ true = if\n\t\ts\" set cmdbuf=${cmdbuf}${affix}${type}_${var}\"\n\t\t( u1 -- u1 c-addr2 u2 )\n\telse\n\t\ts\" set cmdbuf=${cmdbuf}${type}set${affix}_${var}\"\n\t\t( u1 -- u1 c-addr2 u2 )\n\tthen\n\tevaluate ( u1 c-addr2 u2 -- u1 )\n\ts\" cmdbuf\" getenv ( u1 -- u1 c-addr2 u2 )\n\trot 2 pick 2 pick over + -rot + tuck -\n\t\t( u1 c-addr2 u2 -- c-addr2 u2 c-addr1 u1 )\n\t\t\\ Generate a string representing rvalue inheritance var\n\tgetenv dup -1 = if\n\t\t( c-addr2 u2 c-addr1 u1 -- c-addr2 u2 -1 )\n\t\t\\ NOT set -- clean up the stack\n\t\tdrop ( c-addr2 u2 -1 -- c-addr2 u2 )\n\t\t2drop ( c-addr2 u2 -- )\n\telse\n\t\t( c-addr2 u2 c-addr1 u1 -- c-addr2 u2 c-addr1 u1 )\n\t\t\\ SET -- execute cmdbuf (c-addr2\/u2) to inherit value\n\t\t2drop ( c-addr2 u2 c-addr1 u1 -- c-addr2 u2 )\n\t\tevaluate ( c-addr2 u2 -- )\n\tthen\n\n\ts\" cmdbuf\" unsetenv\n;\n\n: menuset-unloadvar ( -- )\n\n\t\\ menuset_use_name is true or false\n\t\\ $type should be set to one of:\n\t\\ \tmenu toggled ansi\n\t\\ $var should be set to one of:\n\t\\ \tcaption command keycode text ...\n\t\\ $affix is either prefix (menuset_use_name is true)\n\t\\ or infix (menuset_use_name is false)\n\n\tmenuset_use_name @ true = if\n\t\ts\" set buf=${affix}${type}_${var}\"\n\telse\n\t\ts\" set buf=${type}set${affix}_${var}\"\n\tthen\n\tevaluate\n\ts\" buf\" getenv unsetenv\n\ts\" buf\" unsetenv\n;\n\n: menuset-loadmenuvar ( -- )\n\ts\" set type=menu\" evaluate\n\tmenuset-loadvar\n;\n\n: menuset-unloadmenuvar ( -- )\n\ts\" set type=menu\" evaluate\n\tmenuset-unloadvar\n;\n\n: menuset-loadxvar ( -- )\n\n\t\\ menuset_use_name is true or false\n\t\\ $type should be set to one of:\n\t\\ \tmenu toggled ansi\n\t\\ $var should be set to one of:\n\t\\ \tcaption command keycode text ...\n\t\\ $x is \"1\" through \"8\"\n\t\\ $affix is either prefix (menuset_use_name is true)\n\t\\ or infix (menuset_use_name is false)\n\n\ts\" set cmdbuf='set ${type}_${var}[${x}]=\\$'\" evaluate\n\ts\" cmdbuf\" getenv swap drop ( -- u1 ) \\ get string length\n\tmenuset_use_name @ true = if\n\t\ts\" set cmdbuf=${cmdbuf}${affix}${type}_${var}[${x}]\"\n\t\t( u1 -- u1 c-addr2 u2 )\n\telse\n\t\ts\" set cmdbuf=${cmdbuf}${type}set${affix}_${var}[${x}]\"\n\t\t( u1 -- u1 c-addr2 u2 )\n\tthen\n\tevaluate ( u1 c-addr2 u2 -- u1 )\n\ts\" cmdbuf\" getenv ( u1 -- u1 c-addr2 u2 )\n\trot 2 pick 2 pick over + -rot + tuck -\n\t\t( u1 c-addr2 u2 -- c-addr2 u2 c-addr1 u1 )\n\t\t\\ Generate a string representing rvalue inheritance var\n\tgetenv dup -1 = if\n\t\t( c-addr2 u2 c-addr1 u1 -- c-addr2 u2 -1 )\n\t\t\\ NOT set -- clean up the stack\n\t\tdrop ( c-addr2 u2 -1 -- c-addr2 u2 )\n\t\t2drop ( c-addr2 u2 -- )\n\telse\n\t\t( c-addr2 u2 c-addr1 u1 -- c-addr2 u2 c-addr1 u1 )\n\t\t\\ SET -- execute cmdbuf (c-addr2\/u2) to inherit value\n\t\t2drop ( c-addr2 u2 c-addr1 u1 -- c-addr2 u2 )\n\t\tevaluate ( c-addr2 u2 -- )\n\tthen\n\n\ts\" cmdbuf\" unsetenv\n;\n\n: menuset-unloadxvar ( -- )\n\n\t\\ menuset_use_name is true or false\n\t\\ $type should be set to one of:\n\t\\ \tmenu toggled ansi\n\t\\ $var should be set to one of:\n\t\\ \tcaption command keycode text ...\n\t\\ $x is \"1\" through \"8\"\n\t\\ $affix is either prefix (menuset_use_name is true)\n\t\\ or infix (menuset_use_name is false)\n\n\tmenuset_use_name @ true = if\n\t\ts\" set buf=${affix}${type}_${var}[${x}]\"\n\telse\n\t\ts\" set buf=${type}set${affix}_${var}[${x}]\"\n\tthen\n\tevaluate\n\ts\" buf\" getenv unsetenv\n\ts\" buf\" unsetenv\n;\n\n: menuset-loadansixvar ( -- )\n\ts\" set type=ansi\" evaluate\n\tmenuset-loadxvar\n;\n\n: menuset-unloadansixvar ( -- )\n\ts\" set type=ansi\" evaluate\n\tmenuset-unloadxvar\n;\n\n: menuset-loadmenuxvar ( -- )\n\ts\" set type=menu\" evaluate\n\tmenuset-loadxvar\n;\n\n: menuset-unloadmenuxvar ( -- )\n\ts\" set type=menu\" evaluate\n\tmenuset-unloadxvar\n;\n\n: menuset-loadtoggledxvar ( -- )\n\ts\" set type=toggled\" evaluate\n\tmenuset-loadxvar\n;\n\n: menuset-unloadtoggledxvar ( -- )\n\ts\" set type=toggled\" evaluate\n\tmenuset-unloadxvar\n;\n\n: menuset-loadxyvar ( -- )\n\n\t\\ menuset_use_name is true or false\n\t\\ $type should be set to one of:\n\t\\ \tmenu toggled ansi\n\t\\ $var should be set to one of:\n\t\\ \tcaption command keycode text ...\n\t\\ $x is \"1\" through \"8\"\n\t\\ $y is \"0\" through \"9\"\n\t\\ $affix is either prefix (menuset_use_name is true)\n\t\\ or infix (menuset_use_name is false)\n\n\ts\" set cmdbuf='set ${type}_${var}[${x}][${y}]=\\$'\" evaluate\n\ts\" cmdbuf\" getenv swap drop ( -- u1 ) \\ get string length\n\tmenuset_use_name @ true = if\n\t\ts\" set cmdbuf=${cmdbuf}${affix}${type}_${var}[${x}][${y}]\"\n\t\t( u1 -- u1 c-addr2 u2 )\n\telse\n\t\ts\" set cmdbuf=${cmdbuf}${type}set${affix}_${var}[${x}][${y}]\"\n\t\t( u1 -- u1 c-addr2 u2 )\n\tthen\n\tevaluate ( u1 c-addr2 u2 -- u1 )\n\ts\" cmdbuf\" getenv ( u1 -- u1 c-addr2 u2 )\n\trot 2 pick 2 pick over + -rot + tuck -\n\t\t( u1 c-addr2 u2 -- c-addr2 u2 c-addr1 u1 )\n\t\t\\ Generate a string representing rvalue inheritance var\n\tgetenv dup -1 = if\n\t\t( c-addr2 u2 c-addr1 u1 -- c-addr2 u2 -1 )\n\t\t\\ NOT set -- clean up the stack\n\t\tdrop ( c-addr2 u2 -1 -- c-addr2 u2 )\n\t\t2drop ( c-addr2 u2 -- )\n\telse\n\t\t( c-addr2 u2 c-addr1 u1 -- c-addr2 u2 c-addr1 u1 )\n\t\t\\ SET -- execute cmdbuf (c-addr2\/u2) to inherit value\n\t\t2drop ( c-addr2 u2 c-addr1 u1 -- c-addr2 u2 )\n\t\tevaluate ( c-addr2 u2 -- )\n\tthen\n\n\ts\" cmdbuf\" unsetenv\n;\n\n: menuset-unloadxyvar ( -- )\n\n\t\\ menuset_use_name is true or false\n\t\\ $type should be set to one of:\n\t\\ \tmenu toggled ansi\n\t\\ $var should be set to one of:\n\t\\ \tcaption command keycode text ...\n\t\\ $x is \"1\" through \"8\"\n\t\\ $y is \"0\" through \"9\"\n\t\\ $affix is either prefix (menuset_use_name is true)\n\t\\ or infix (menuset_use_name is false)\n\n\tmenuset_use_name @ true = if\n\t\ts\" set buf=${affix}${type}_${var}[${x}][${y}]\"\n\telse\n\t\ts\" set buf=${type}set${affix}_${var}[${x}][${y}]\"\n\tthen\n\tevaluate\n\ts\" buf\" getenv unsetenv\n\ts\" buf\" unsetenv\n;\n\n: menuset-loadansixyvar ( -- )\n\ts\" set type=ansi\" evaluate\n\tmenuset-loadxyvar\n;\n\n: menuset-unloadansixyvar ( -- )\n\ts\" set type=ansi\" evaluate\n\tmenuset-unloadxyvar\n;\n\n: menuset-loadmenuxyvar ( -- )\n\ts\" set type=menu\" evaluate\n\tmenuset-loadxyvar\n;\n\n: menuset-unloadmenuxyvar ( -- )\n\ts\" set type=menu\" evaluate\n\tmenuset-unloadxyvar\n;\n\n: menuset-setnum-namevar ( N -- C-Addr\/U )\n\n\ts\" menuset_nameNNNNN\" ( n -- n c-addr1 u1 )\t\\ variable basename\n\tdrop 12 ( n c-addr1 u1 -- n c-addr1 12 )\t\\ remove \"NNNNN\"\n\trot ( n c-addr1 12 -- c-addr1 12 n )\t\\ move number on top\n\n\t\\ convert to string\n\ts>d <# #s #> ( c-addr1 12 n -- c-addr1 12 c-addr2 u2 )\n\n\t\\ Combine strings\n\tbegin ( using u2 in c-addr2\/u2 pair as countdown to zero )\n\t\tover\t( c-addr1 u1 c-addr2 u2 -- continued below )\n\t\t\t( c-addr1 u1 c-addr2 u2 c-addr2 ) \\ copy src-addr\n\t\tc@\t( c-addr1 u1 c-addr2 u2 c-addr2 -- continued below )\n\t\t\t( c-addr1 u1 c-addr2 u2 c ) \\ get next src-addr byte\n\t\t4 pick 4 pick\n\t\t\t( c-addr1 u1 c-addr2 u2 c -- continued below )\n\t\t\t( c-addr1 u1 c-addr2 u2 c c-addr1 u1 )\n\t\t\t\\ get destination c-addr1\/u1 pair\n\t\t+\t( c-addr1 u1 c-addr2 u2 c c-addr1 u1 -- cont. below )\n\t\t\t( c-addr1 u1 c-addr2 u2 c c-addr3 )\n\t\t\t\\ combine dest-c-addr to get dest-addr for byte\n\t\tc!\t( c-addr1 u1 c-addr2 u2 c c-addr3 -- continued below )\n\t\t\t( c-addr1 u1 c-addr2 u2 )\n\t\t\t\\ store the current src-addr byte into dest-addr\n\n\t\t2swap 1+ 2swap\t\\ increment u1 in destination c-addr1\/u1 pair\n\t\tswap 1+ swap\t\\ increment c-addr2 in source c-addr2\/u2 pair\n\t\t1-\t\t\\ decrement u2 in the source c-addr2\/u2 pair\n\n\t\tdup 0= \\ time to break?\n\tuntil\n\n\t2drop\t( c-addr1 u1 c-addr2 u2 -- c-addr1 u1 )\n\t\t\\ drop temporary number-format conversion c-addr2\/u2\n;\n\n: menuset-checksetnum ( N -- )\n\n\t\\ \n\t\\ adjust input to be both positive and no-higher than 65535\n\t\\ \n\tabs dup 65535 > if drop 65535 then ( n -- n )\n\n\t\\\n\t\\ The next few blocks will determine if we should use the default\n\t\\ methodology (referencing the original numeric stack-input), or if-\n\t\\ instead $menuset_name{N} has been defined wherein we would then\n\t\\ use the value thereof as the prefix to every menu variable.\n\t\\ \n\n\tfalse menuset_use_name ! \\ assume name is not set\n\n\tmenuset-setnum-namevar \n\t\\ \n\t\\ We now have a string that is the assembled variable name to check\n\t\\ for... $menuset_name{N}. Let's check for it.\n\t\\ \n\t2dup ( c-addr1 u1 -- c-addr1 u1 c-addr1 u1 ) \\ save a copy\n\tgetenv dup -1 <> if ( c-addr1 u1 c-addr1 u1 -- c-addr1 u1 c-addr2 u2 )\n\t\t\\ The variable is set. Let's clean up the stack leaving only\n\t\t\\ its value for later use.\n\n\t\ttrue menuset_use_name !\n\t\t2swap 2drop\t( c-addr1 u1 c-addr2 u2 -- c-addr2 u2 )\n\t\t\t\t\\ drop assembled variable name, leave the value\n\telse ( c-addr1 u1 c-addr1 u1 -- c-addr1 u1 -1 ) \\ no such variable\n\t\t\\ The variable is not set. Let's clean up the stack leaving the\n\t\t\\ string [portion] representing the original numeric input.\n\n\t\tdrop ( c-addr1 u1 -1 -- c-addr1 u1 ) \\ drop -1 result\n\t\t12 - swap 12 + swap ( c-addr1 u1 -- c-addr2 u2 )\n\t\t\t\\ truncate to original numeric stack-input\n\tthen\n\n\t\\ \n\t\\ Now, depending on whether $menuset_name{N} has been set, we have\n\t\\ either the value thereof to be used as a prefix to all menu_*\n\t\\ variables or we have a string representing the numeric stack-input\n\t\\ to be used as a \"set{N}\" infix to the same menu_* variables.\n\t\\ \n\t\\ For example, if the stack-input is 1 and menuset_name1 is NOT set\n\t\\ the following variables will be referenced:\n\t\\ \tansiset1_caption[x]\t\t-> ansi_caption[x]\n\t\\ \tansiset1_caption[x][y]\t\t-> ansi_caption[x][y]\n\t\\ \tmenuset1_acpi\t\t\t-> menu_acpi\n\t\\ \tmenuset1_caption[x]\t\t-> menu_caption[x]\n\t\\ \tmenuset1_caption[x][y]\t\t-> menu_caption[x][y]\n\t\\ \tmenuset1_command[x]\t\t-> menu_command[x]\n\t\\ \tmenuset1_init\t\t\t-> ``evaluated''\n\t\\ \tmenuset1_init[x]\t\t-> menu_init[x]\n\t\\ \tmenuset1_keycode[x]\t\t-> menu_keycode[x]\n\t\\ \tmenuset1_options\t\t-> menu_options\n\t\\ \tmenuset1_optionstext\t\t-> menu_optionstext\n\t\\ \tmenuset1_reboot\t\t\t-> menu_reboot\n\t\\ \ttoggledset1_ansi[x]\t\t-> toggled_ansi[x]\n\t\\ \ttoggledset1_text[x]\t\t-> toggled_text[x]\n\t\\ otherwise, the following variables are referenced (where {name}\n\t\\ represents the value of $menuset_name1 (given 1 as stack-input):\n\t\\ \t{name}ansi_caption[x]\t\t-> ansi_caption[x]\n\t\\ \t{name}ansi_caption[x][y]\t-> ansi_caption[x][y]\n\t\\ \t{name}menu_acpi\t\t\t-> menu_acpi\n\t\\ \t{name}menu_caption[x]\t\t-> menu_caption[x]\n\t\\ \t{name}menu_caption[x][y]\t-> menu_caption[x][y]\n\t\\ \t{name}menu_command[x]\t\t-> menu_command[x]\n\t\\ \t{name}menu_init\t\t\t-> ``evaluated''\n\t\\ \t{name}menu_init[x]\t\t-> menu_init[x]\n\t\\ \t{name}menu_keycode[x]\t\t-> menu_keycode[x]\n\t\\ \t{name}menu_options\t\t-> menu_options\n\t\\ \t{name}menu_optionstext\t\t-> menu_optionstext\n\t\\ \t{name}menu_reboot\t\t-> menu_reboot\n\t\\ \t{name}toggled_ansi[x]\t\t-> toggled_ansi[x]\n\t\\ \t{name}toggled_text[x]\t\t-> toggled_text[x]\n\t\\ \n\t\\ Note that menuset{N}_init and {name}menu_init are the initializers\n\t\\ for the entire menu (for wholly dynamic menus) opposed to the per-\n\t\\ menuitem initializers (with [x] afterward). The whole-menu init\n\t\\ routine is evaluated and not passed down to $menu_init (which\n\t\\ would result in double evaluation). By doing this, the initializer\n\t\\ can initialize the menuset before we transfer it to active-duty.\n\t\\ \n\n\t\\ \n\t\\ Copy our affixation (prefix or infix depending on menuset_use_name)\n\t\\ to our buffer so that we can safely use the s-quote (s\") buf again.\n\t\\ \n\tmenuset_affixbuf 0 2swap ( c-addr2 u2 -- c-addr1 0 c-addr2 u2 )\n\tbegin ( using u2 in c-addr2\/u2 pair as countdown to zero )\n\t\tover ( c-addr1 u1 c-addr2 u2 -- c-addr1 u1 c-addr2 u2 c-addr2 )\n\t\tc@ ( c-addr1 u1 c-addr2 u2 -- c-addr1 u1 c-addr2 u2 c )\n\t\t4 pick 4 pick\n\t\t ( c-addr1 u1 c-addr2 u2 c -- continued below )\n\t\t ( c-addr1 u1 c-addr2 u2 c c-addr1 u1 )\n\t\t+ ( c-addr1 u1 c-addr2 u2 c c-addr1 u1 -- continued below )\n\t\t ( c-addr1 u1 c-addr2 u2 c c-addr3 )\n\t\tc! ( c-addr1 u1 c-addr2 u2 c c-addr3 -- continued below )\n\t\t ( c-addr1 u1 c-addr2 u2 )\n\t\t2swap 1+ 2swap\t\\ increment affixbuf byte position\/count\n\t\tswap 1+ swap\t\\ increment strbuf pointer (source c-addr2)\n\t\t1-\t\t\\ decrement strbuf byte count (source u2)\n\t\tdup 0= \\ time to break?\n\tuntil\n\t2drop ( c-addr1 u1 c-addr2 u2 -- c-addr1 u1 ) \\ drop strbuf c-addr2\/u2\n\n\t\\\n\t\\ Create a variable for referencing our affix data (prefix or infix\n\t\\ depending on menuset_use_name as described above). This variable will\n\t\\ be temporary and only used to simplify cmdbuf assembly.\n\t\\ \n\ts\" affix\" setenv ( c-addr1 u1 -- )\n;\n\n: menuset-cleanup ( -- )\n\ts\" type\" unsetenv\n\ts\" var\" unsetenv\n\ts\" x\" unsetenv\n\ts\" y\" unsetenv\n\ts\" affix\" unsetenv\n;\n\n: menuset-loadsetnum ( N -- )\n\n\tmenuset-checksetnum ( n -- )\n\n\t\\ \n\t\\ From here out, we use temporary environment variables to make\n\t\\ dealing with variable-length strings easier.\n\t\\ \n\t\\ menuset_use_name is true or false\n\t\\ $affix should be use appropriated w\/respect to menuset_use_name\n\t\\ \n\n\t\\ ... menu_init ...\n\ts\" set var=init\" evaluate\n\tmenuset-loadmenuvar\n\n\t\\ If menu_init was set by the above, evaluate it here-and-now\n\t\\ so that the remaining variables are influenced by its actions\n\ts\" menu_init\" 2dup getenv dup -1 <> if\n\t\t2swap unsetenv \\ don't want later menu-create to re-call this\n\t\tevaluate\n\telse\n\t\tdrop 2drop ( n c-addr u -1 -- n )\n\tthen\n\n\t[char] 1 ( -- x ) \\ Loop range ASCII '1' (49) to '8' (56)\n\tbegin\n\t\tdup menuset_x tuck c! 1 s\" x\" setenv \\ set loop iterator and $x\n\n\t\ts\" set var=caption\" evaluate\n\n\t\t\\ ... menu_caption[x] ...\n\t\tmenuset-loadmenuxvar\n\n\t\t\\ ... ansi_caption[x] ...\n\t\tmenuset-loadansixvar\n\n\t\t[char] 0 ( x -- x y ) \\ Inner Loop ASCII '1' (48) to '9' (57)\n\t\tbegin\n\t\t\tdup menuset_y tuck c! 1 s\" y\" setenv\n\t\t\t\t\\ set inner loop iterator and $y\n\n\t\t\t\\ ... menu_caption[x][y] ...\n\t\t\tmenuset-loadmenuxyvar\n\n\t\t\t\\ ... ansi_caption[x][y] ...\n\t\t\tmenuset-loadansixyvar\n\n\t\t\t1+ dup 57 > ( x y -- y' 0|-1 ) \\ increment and test\n\t\tuntil\n\t\tdrop ( x y -- x )\n\n\t\t\\ ... menu_command[x] ...\n\t\ts\" set var=command\" evaluate\n\t\tmenuset-loadmenuxvar\n\n\t\t\\ ... menu_init[x] ...\n\t\ts\" set var=init\" evaluate\n\t\tmenuset-loadmenuxvar\n\n\t\t\\ ... menu_keycode[x] ...\n\t\ts\" set var=keycode\" evaluate\n\t\tmenuset-loadmenuxvar\n\n\t\t\\ ... toggled_text[x] ...\n\t\ts\" set var=text\" evaluate\n\t\tmenuset-loadtoggledxvar\n\n\t\t\\ ... toggled_ansi[x] ...\n\t\ts\" set var=ansi\" evaluate\n\t\tmenuset-loadtoggledxvar\n\n\t\t1+ dup 56 > ( x -- x' 0|-1 ) \\ increment iterator\n\t\t \\ continue if less than 57\n\tuntil\n\tdrop ( x -- ) \\ loop iterator\n\n\t\\ ... menu_reboot ...\n\ts\" set var=reboot\" evaluate\n\tmenuset-loadmenuvar\n\n\t\\ ... menu_acpi ...\n\ts\" set var=acpi\" evaluate\n\tmenuset-loadmenuvar\n\n\t\\ ... menu_options ...\n\ts\" set var=options\" evaluate\n\tmenuset-loadmenuvar\n\n\t\\ ... menu_optionstext ...\n\ts\" set var=optionstext\" evaluate\n\tmenuset-loadmenuvar\n\n\tmenuset-cleanup\n;\n\n: menuset-loadinitial ( -- )\n\ts\" menuset_initial\" getenv dup -1 <> if\n\t\t?number 0<> if\n\t\t\tmenuset-loadsetnum\n\t\tthen\n\telse\n\t\tdrop \\ cruft\n\tthen\n;\n\n: menusets-unset ( -- )\n\n\ts\" menuset_initial\" unsetenv\n\n\t1 begin\n\t\tdup menuset-checksetnum ( n n -- n )\n\n\t\tdup menuset-setnum-namevar ( n n -- n )\n\t\tunsetenv\n\n\t\t\\ If the current menuset does not populate the first menuitem,\n\t\t\\ we stop completely.\n\n\t\tmenuset_use_name @ true = if\n\t\t\ts\" set buf=${affix}menu_caption[1]\"\n\t\telse\n\t\t\ts\" set buf=menuset${affix}_caption[1]\"\n\t\tthen\n\t\tevaluate s\" buf\" getenv getenv -1 = if\n\t\t\tdrop ( n -- )\n\t\t\ts\" buf\" unsetenv\n\t\t\tmenuset-cleanup\n\t\t\texit\n\t\telse\n\t\t\tdrop ( n c-addr2 -- n ) \\ unused\n\t\tthen\n\n\t\t[char] 1 ( n -- n x ) \\ Loop range ASCII '1' (49) to '8' (56)\n\t\tbegin\n\t\t\tdup menuset_x tuck c! 1 s\" x\" setenv \\ set $x to x\n\n\t\t\ts\" set var=caption\" evaluate\n\t\t\tmenuset-unloadmenuxvar\n\t\t\tmenuset-unloadmenuxvar\n\t\t\tmenuset-unloadansixvar\n\t\t\t[char] 0 ( n x -- n x y ) \\ Inner loop '0' to '9'\n\t\t\tbegin\n\t\t\t\tdup menuset_y tuck c! 1 s\" y\" setenv\n\t\t\t\t\t\\ sets $y to y\n\t\t\t\tmenuset-unloadmenuxyvar\n\t\t\t\tmenuset-unloadansixyvar\n\t\t\t\t1+ dup 57 > ( n x y -- n x y' 0|-1 )\n\t\t\tuntil\n\t\t\tdrop ( n x y -- n x )\n\t\t\ts\" set var=command\" evaluate menuset-unloadmenuxvar\n\t\t\ts\" set var=init\" evaluate menuset-unloadmenuxvar\n\t\t\ts\" set var=keycode\" evaluate menuset-unloadmenuxvar\n\t\t\ts\" set var=text\" evaluate menuset-unloadtoggledxvar\n\t\t\ts\" set var=ansi\" evaluate menuset-unloadtoggledxvar\n\n\t\t\t1+ dup 56 > ( x -- x' 0|-1 ) \\ increment and test\n\t\tuntil\n\t\tdrop ( n x -- n ) \\ loop iterator\n\n\t\ts\" set var=acpi\" evaluate menuset-unloadmenuvar\n\t\ts\" set var=init\" evaluate menuset-unloadmenuvar\n\t\ts\" set var=options\" evaluate menuset-unloadmenuvar\n\t\ts\" set var=optionstext\" evaluate menuset-unloadmenuvar\n\t\ts\" set var=reboot\" evaluate menuset-unloadmenuvar\n\n\t\t1+ dup 65535 > ( n -- n' 0|-1 ) \\ increment and test\n\tuntil\n\tdrop ( n' -- ) \\ loop iterator\n\n\ts\" buf\" unsetenv\n\tmenuset-cleanup\n;\n","old_contents":"\\ Copyright (c) 2012 Devin Teske \n\\ All rights reserved.\n\\ \n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\ \n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\ \n\\ $FreeBSD$\n\nmarker task-menusets.4th\n\nvariable menuset_use_name\n\ncreate menuset_affixbuf\t255 allot\ncreate menuset_x 1 allot\ncreate menuset_y 1 allot\n\n: menuset-loadvar ( -- )\n\n\t\\ menuset_use_name is true or false\n\t\\ $type should be set to one of:\n\t\\ \tmenu toggled ansi\n\t\\ $var should be set to one of:\n\t\\ \tcaption command keycode text ...\n\t\\ $affix is either prefix (menuset_use_name is true)\n\t\\ or infix (menuset_use_name is false)\n\n\ts\" set cmdbuf='set ${type}_${var}=\\$'\" evaluate\n\ts\" cmdbuf\" getenv swap drop ( -- u1 ) \\ get string length\n\tmenuset_use_name @ true = if\n\t\ts\" set cmdbuf=${cmdbuf}${affix}${type}_${var}\"\n\t\t( u1 -- u1 c-addr2 u2 )\n\telse\n\t\ts\" set cmdbuf=${cmdbuf}${type}set${affix}_${var}\"\n\t\t( u1 -- u1 c-addr2 u2 )\n\tthen\n\tevaluate ( u1 c-addr2 u2 -- u1 )\n\ts\" cmdbuf\" getenv ( u1 -- u1 c-addr2 u2 )\n\trot 2 pick 2 pick over + -rot + tuck -\n\t\t( u1 c-addr2 u2 -- c-addr2 u2 c-addr1 u1 )\n\t\t\\ Generate a string representing rvalue inheritance var\n\tgetenv dup -1 = if\n\t\t( c-addr2 u2 c-addr1 u1 -- c-addr2 u2 -1 )\n\t\t\\ NOT set -- clean up the stack\n\t\tdrop ( c-addr2 u2 -1 -- c-addr2 u2 )\n\t\t2drop ( c-addr2 u2 -- )\n\telse\n\t\t( c-addr2 u2 c-addr1 u1 -- c-addr2 u2 c-addr1 u1 )\n\t\t\\ SET -- execute cmdbuf (c-addr2\/u2) to inherit value\n\t\t2drop ( c-addr2 u2 c-addr1 u1 -- c-addr2 u2 )\n\t\tevaluate ( c-addr2 u2 -- )\n\tthen\n\n\ts\" cmdbuf\" unsetenv\n;\n\n: menuset-unloadvar ( -- )\n\n\t\\ menuset_use_name is true or false\n\t\\ $type should be set to one of:\n\t\\ \tmenu toggled ansi\n\t\\ $var should be set to one of:\n\t\\ \tcaption command keycode text ...\n\t\\ $affix is either prefix (menuset_use_name is true)\n\t\\ or infix (menuset_use_name is false)\n\n\tmenuset_use_name @ true = if\n\t\ts\" set buf=${affix}${type}_${var}\"\n\telse\n\t\ts\" set buf=${type}set${affix}_${var}\"\n\tthen\n\tevaluate\n\ts\" buf\" getenv unsetenv\n\ts\" buf\" unsetenv\n;\n\n: menuset-loadmenuvar ( -- )\n\ts\" set type=menu\" evaluate\n\tmenuset-loadvar\n;\n\n: menuset-unloadmenuvar ( -- )\n\ts\" set type=menu\" evaluate\n\tmenuset-unloadvar\n;\n\n: menuset-loadxvar ( -- )\n\n\t\\ menuset_use_name is true or false\n\t\\ $type should be set to one of:\n\t\\ \tmenu toggled ansi\n\t\\ $var should be set to one of:\n\t\\ \tcaption command keycode text ...\n\t\\ $x is \"1\" through \"8\"\n\t\\ $affix is either prefix (menuset_use_name is true)\n\t\\ or infix (menuset_use_name is false)\n\n\ts\" set cmdbuf='set ${type}_${var}[${x}]=\\$'\" evaluate\n\ts\" cmdbuf\" getenv swap drop ( -- u1 ) \\ get string length\n\tmenuset_use_name @ true = if\n\t\ts\" set cmdbuf=${cmdbuf}${affix}${type}_${var}[${x}]\"\n\t\t( u1 -- u1 c-addr2 u2 )\n\telse\n\t\ts\" set cmdbuf=${cmdbuf}${type}set${affix}_${var}[${x}]\"\n\t\t( u1 -- u1 c-addr2 u2 )\n\tthen\n\tevaluate ( u1 c-addr2 u2 -- u1 )\n\ts\" cmdbuf\" getenv ( u1 -- u1 c-addr2 u2 )\n\trot 2 pick 2 pick over + -rot + tuck -\n\t\t( u1 c-addr2 u2 -- c-addr2 u2 c-addr1 u1 )\n\t\t\\ Generate a string representing rvalue inheritance var\n\tgetenv dup -1 = if\n\t\t( c-addr2 u2 c-addr1 u1 -- c-addr2 u2 -1 )\n\t\t\\ NOT set -- clean up the stack\n\t\tdrop ( c-addr2 u2 -1 -- c-addr2 u2 )\n\t\t2drop ( c-addr2 u2 -- )\n\telse\n\t\t( c-addr2 u2 c-addr1 u1 -- c-addr2 u2 c-addr1 u1 )\n\t\t\\ SET -- execute cmdbuf (c-addr2\/u2) to inherit value\n\t\t2drop ( c-addr2 u2 c-addr1 u1 -- c-addr2 u2 )\n\t\tevaluate ( c-addr2 u2 -- )\n\tthen\n\n\ts\" cmdbuf\" unsetenv\n;\n\n: menuset-unloadxvar ( -- )\n\n\t\\ menuset_use_name is true or false\n\t\\ $type should be set to one of:\n\t\\ \tmenu toggled ansi\n\t\\ $var should be set to one of:\n\t\\ \tcaption command keycode text ...\n\t\\ $x is \"1\" through \"8\"\n\t\\ $affix is either prefix (menuset_use_name is true)\n\t\\ or infix (menuset_use_name is false)\n\n\tmenuset_use_name @ true = if\n\t\ts\" set buf=${affix}${type}_${var}[${x}]\"\n\telse\n\t\ts\" set buf=${type}set${affix}_${var}[${x}]\"\n\tthen\n\tevaluate\n\ts\" buf\" getenv unsetenv\n\ts\" buf\" unsetenv\n;\n\n: menuset-loadansixvar ( -- )\n\ts\" set type=ansi\" evaluate\n\tmenuset-loadxvar\n;\n\n: menuset-unloadansixvar ( -- )\n\ts\" set type=ansi\" evaluate\n\tmenuset-unloadxvar\n;\n\n: menuset-loadmenuxvar ( -- )\n\ts\" set type=menu\" evaluate\n\tmenuset-loadxvar\n;\n\n: menuset-unloadmenuxvar ( -- )\n\ts\" set type=menu\" evaluate\n\tmenuset-unloadxvar\n;\n\n: menuset-loadtoggledxvar ( -- )\n\ts\" set type=toggled\" evaluate\n\tmenuset-loadxvar\n;\n\n: menuset-unloadtoggledxvar ( -- )\n\ts\" set type=toggled\" evaluate\n\tmenuset-unloadxvar\n;\n\n: menuset-loadxyvar ( -- )\n\n\t\\ menuset_use_name is true or false\n\t\\ $type should be set to one of:\n\t\\ \tmenu toggled ansi\n\t\\ $var should be set to one of:\n\t\\ \tcaption command keycode text ...\n\t\\ $x is \"1\" through \"8\"\n\t\\ $y is \"0\" through \"9\"\n\t\\ $affix is either prefix (menuset_use_name is true)\n\t\\ or infix (menuset_use_name is false)\n\n\ts\" set cmdbuf='set ${type}_${var}[${x}][${y}]=\\$'\" evaluate\n\ts\" cmdbuf\" getenv swap drop ( -- u1 ) \\ get string length\n\tmenuset_use_name @ true = if\n\t\ts\" set cmdbuf=${cmdbuf}${affix}${type}_${var}[${x}][${y}]\"\n\t\t( u1 -- u1 c-addr2 u2 )\n\telse\n\t\ts\" set cmdbuf=${cmdbuf}${type}set${affix}_${var}[${x}][${y}]\"\n\t\t( u1 -- u1 c-addr2 u2 )\n\tthen\n\tevaluate ( u1 c-addr2 u2 -- u1 )\n\ts\" cmdbuf\" getenv ( u1 -- u1 c-addr2 u2 )\n\trot 2 pick 2 pick over + -rot + tuck -\n\t\t( u1 c-addr2 u2 -- c-addr2 u2 c-addr1 u1 )\n\t\t\\ Generate a string representing rvalue inheritance var\n\tgetenv dup -1 = if\n\t\t( c-addr2 u2 c-addr1 u1 -- c-addr2 u2 -1 )\n\t\t\\ NOT set -- clean up the stack\n\t\tdrop ( c-addr2 u2 -1 -- c-addr2 u2 )\n\t\t2drop ( c-addr2 u2 -- )\n\telse\n\t\t( c-addr2 u2 c-addr1 u1 -- c-addr2 u2 c-addr1 u1 )\n\t\t\\ SET -- execute cmdbuf (c-addr2\/u2) to inherit value\n\t\t2drop ( c-addr2 u2 c-addr1 u1 -- c-addr2 u2 )\n\t\tevaluate ( c-addr2 u2 -- )\n\tthen\n\n\ts\" cmdbuf\" unsetenv\n;\n\n: menuset-unloadxyvar ( -- )\n\n\t\\ menuset_use_name is true or false\n\t\\ $type should be set to one of:\n\t\\ \tmenu toggled ansi\n\t\\ $var should be set to one of:\n\t\\ \tcaption command keycode text ...\n\t\\ $x is \"1\" through \"8\"\n\t\\ $y is \"0\" through \"9\"\n\t\\ $affix is either prefix (menuset_use_name is true)\n\t\\ or infix (menuset_use_name is false)\n\n\tmenuset_use_name @ true = if\n\t\ts\" set buf=${affix}${type}_${var}[${x}][${y}]\"\n\telse\n\t\ts\" set buf=${type}set${affix}_${var}[${x}][${y}]\"\n\tthen\n\tevaluate\n\ts\" buf\" getenv unsetenv\n\ts\" buf\" unsetenv\n;\n\n: menuset-loadansixyvar ( -- )\n\ts\" set type=ansi\" evaluate\n\tmenuset-loadxyvar\n;\n\n: menuset-unloadansixyvar ( -- )\n\ts\" set type=ansi\" evaluate\n\tmenuset-unloadxyvar\n;\n\n: menuset-loadmenuxyvar ( -- )\n\ts\" set type=menu\" evaluate\n\tmenuset-loadxyvar\n;\n\n: menuset-unloadmenuxyvar ( -- )\n\ts\" set type=menu\" evaluate\n\tmenuset-unloadxyvar\n;\n\n: menuset-setnum-namevar ( N -- C-Addr\/U )\n\n\ts\" menuset_nameNNNNN\" ( n -- n c-addr1 u1 )\t\\ variable basename\n\tdrop 12 ( n c-addr1 u1 -- n c-addr1 12 )\t\\ remove \"NNNNN\"\n\trot ( n c-addr1 12 -- c-addr1 12 n )\t\\ move number on top\n\n\t\\ convert to string\n\ts>d <# #s #> ( c-addr1 12 n -- c-addr1 12 c-addr2 u2 )\n\n\t\\ Combine strings\n\tbegin ( using u2 in c-addr2\/u2 pair as countdown to zero )\n\t\tover\t( c-addr1 u1 c-addr2 u2 -- continued below )\n\t\t\t( c-addr1 u1 c-addr2 u2 c-addr2 ) \\ copy src-addr\n\t\tc@\t( c-addr1 u1 c-addr2 u2 c-addr2 -- continued below )\n\t\t\t( c-addr1 u1 c-addr2 u2 c ) \\ get next src-addr byte\n\t\t4 pick 4 pick\n\t\t\t( c-addr1 u1 c-addr2 u2 c -- continued below )\n\t\t\t( c-addr1 u1 c-addr2 u2 c c-addr1 u1 )\n\t\t\t\\ get destination c-addr1\/u1 pair\n\t\t+\t( c-addr1 u1 c-addr2 u2 c c-addr1 u1 -- cont. below )\n\t\t\t( c-addr1 u1 c-addr2 u2 c c-addr3 )\n\t\t\t\\ combine dest-c-addr to get dest-addr for byte\n\t\tc!\t( c-addr1 u1 c-addr2 u2 c c-addr3 -- continued below )\n\t\t\t( c-addr1 u1 c-addr2 u2 )\n\t\t\t\\ store the current src-addr byte into dest-addr\n\n\t\t2swap 1+ 2swap\t\\ increment u1 in destination c-addr1\/u1 pair\n\t\tswap 1+ swap\t\\ increment c-addr2 in source c-addr2\/u2 pair\n\t\t1-\t\t\\ decrement u2 in the source c-addr2\/u2 pair\n\n\t\tdup 0= \\ time to break?\n\tuntil\n\n\t2drop\t( c-addr1 u1 c-addr2 u2 -- c-addr1 u1 )\n\t\t\\ drop temporary number-format conversion c-addr2\/u2\n;\n\n: menuset-checksetnum ( N -- )\n\n\t\\ \n\t\\ adjust input to be both positive and no-higher than 65535\n\t\\ \n\tabs dup 65535 > if drop 65535 then ( n -- n )\n\n\t\\\n\t\\ The next few blocks will determine if we should use the default\n\t\\ methodology (referencing the original numeric stack-input), or if-\n\t\\ instead $menuset_name{N} has been defined wherein we would then\n\t\\ use the value thereof as the prefix to every menu variable.\n\t\\ \n\n\tfalse menuset_use_name ! \\ assume name is not set\n\n\tmenuset-setnum-namevar \n\t\\ \n\t\\ We now have a string that is the assembled variable name to check\n\t\\ for... $menuset_name{N}. Let's check for it.\n\t\\ \n\t2dup ( c-addr1 u1 -- c-addr1 u1 c-addr1 u1 ) \\ save a copy\n\tgetenv dup -1 <> if ( c-addr1 u1 c-addr1 u1 -- c-addr1 u1 c-addr2 u2 )\n\t\t\\ The variable is set. Let's clean up the stack leaving only\n\t\t\\ its value for later use.\n\n\t\ttrue menuset_use_name !\n\t\t2swap 2drop\t( c-addr1 u1 c-addr2 u2 -- c-addr2 u2 )\n\t\t\t\t\\ drop assembled variable name, leave the value\n\telse ( c-addr1 u1 c-addr1 u1 -- c-addr1 u1 -1 ) \\ no such variable\n\t\t\\ The variable is not set. Let's clean up the stack leaving the\n\t\t\\ string [portion] representing the original numeric input.\n\n\t\tdrop ( c-addr1 u1 -1 -- c-addr1 u1 ) \\ drop -1 result\n\t\t12 - swap 12 + swap ( c-addr1 u1 -- c-addr2 u2 )\n\t\t\t\\ truncate to original numeric stack-input\n\tthen\n\n\t\\ \n\t\\ Now, depending on whether $menuset_name{N} has been set, we have\n\t\\ either the value thereof to be used as a prefix to all menu_*\n\t\\ variables or we have a string representing the numeric stack-input\n\t\\ to be used as a \"set{N}\" infix to the same menu_* variables.\n\t\\ \n\t\\ For example, if the stack-input is 1 and menuset_name1 is NOT set\n\t\\ the following variables will be referenced:\n\t\\ \tansiset1_caption[x]\t\t-> ansi_caption[x]\n\t\\ \tansiset1_caption[x][y]\t\t-> ansi_caption[x][y]\n\t\\ \tmenuset1_acpi\t\t\t-> menu_acpi\n\t\\ \tmenuset1_caption[x]\t\t-> menu_caption[x]\n\t\\ \tmenuset1_caption[x][y]\t\t-> menu_caption[x][y]\n\t\\ \tmenuset1_command[x]\t\t-> menu_command[x]\n\t\\ \tmenuset1_init\t\t\t-> ``evaluated''\n\t\\ \tmenuset1_init[x]\t\t-> menu_init[x]\n\t\\ \tmenuset1_keycode[x]\t\t-> menu_keycode[x]\n\t\\ \tmenuset1_options\t\t-> menu_options\n\t\\ \tmenuset1_optionstext\t\t-> menu_optionstext\n\t\\ \tmenuset1_reboot\t\t\t-> menu_reboot\n\t\\ \ttoggledset1_ansi[x]\t\t-> toggled_ansi[x]\n\t\\ \ttoggledset1_text[x]\t\t-> toggled_text[x]\n\t\\ otherwise, the following variables are referenced (where {name}\n\t\\ represents the value of $menuset_name1 (given 1 as stack-input):\n\t\\ \t{name}ansi_caption[x]\t\t-> ansi_caption[x]\n\t\\ \t{name}ansi_caption[x][y]\t-> ansi_caption[x][y]\n\t\\ \t{name}menu_acpi\t\t\t-> menu_acpi\n\t\\ \t{name}menu_caption[x]\t\t-> menu_caption[x]\n\t\\ \t{name}menu_caption[x][y]\t-> menu_caption[x][y]\n\t\\ \t{name}menu_command[x]\t\t-> menu_command[x]\n\t\\ \t{name}menu_init\t\t\t-> ``evaluated''\n\t\\ \t{name}menu_init[x]\t\t-> menu_init[x]\n\t\\ \t{name}menu_keycode[x]\t\t-> menu_keycode[x]\n\t\\ \t{name}menu_options\t\t-> menu_options\n\t\\ \t{name}menu_optionstext\t\t-> menu_optionstext\n\t\\ \t{name}menu_reboot\t\t-> menu_reboot\n\t\\ \t{name}toggled_ansi[x]\t\t-> toggled_ansi[x]\n\t\\ \t{name}toggled_text[x]\t\t-> toggled_text[x]\n\t\\ \n\t\\ Note that menuset{N}_init and {name}menu_init are the initializers\n\t\\ for the entire menu (for wholly dynamic menus) opposed to the per-\n\t\\ menuitem initializers (with [x] afterward). The whole-menu init\n\t\\ routine is evaluated and not passed down to $menu_init (which\n\t\\ would result in double evaluation). By doing this, the initializer\n\t\\ can initialize the menuset before we transfer it to active-duty.\n\t\\ \n\n\t\\ \n\t\\ Copy our affixation (prefix or infix depending on menuset_use_name)\n\t\\ to our buffer so that we can safely use the s-quote (s\") buf again.\n\t\\ \n\tmenuset_affixbuf 0 2swap ( c-addr2 u2 -- c-addr1 0 c-addr2 u2 )\n\tbegin ( using u2 in c-addr2\/u2 pair as countdown to zero )\n\t\tover ( c-addr1 u1 c-addr2 u2 -- c-addr1 u1 c-addr2 u2 c-addr2 )\n\t\tc@ ( c-addr1 u1 c-addr2 u2 -- c-addr1 u1 c-addr2 u2 c )\n\t\t4 pick 4 pick\n\t\t ( c-addr1 u1 c-addr2 u2 c -- continued below )\n\t\t ( c-addr1 u1 c-addr2 u2 c c-addr1 u1 )\n\t\t+ ( c-addr1 u1 c-addr2 u2 c c-addr1 u1 -- continued below )\n\t\t ( c-addr1 u1 c-addr2 u2 c c-addr3 )\n\t\tc! ( c-addr1 u1 c-addr2 u2 c c-addr3 -- continued below )\n\t\t ( c-addr1 u1 c-addr2 u2 )\n\t\t2swap 1+ 2swap\t\\ increment affixbuf byte position\/count\n\t\tswap 1+ swap\t\\ increment strbuf pointer (source c-addr2)\n\t\t1-\t\t\\ decrement strbuf byte count (source u2)\n\t\tdup 0= \\ time to break?\n\tuntil\n\t2drop ( c-addr1 u1 c-addr2 u2 -- c-addr1 u1 ) \\ drop strbuf c-addr2\/u2\n\n\t\\\n\t\\ Create a variable for referencing our affix data (prefix or infix\n\t\\ depending on menuset_use_name as described above). This variable will\n\t\\ be temporary and only used to simplify cmdbuf assembly.\n\t\\ \n\ts\" affix\" setenv ( c-addr1 u1 -- )\n;\n\n: menuset-cleanup ( -- )\n\ts\" type\" unsetenv\n\ts\" var\" unsetenv\n\ts\" x\" unsetenv\n\ts\" y\" unsetenv\n\ts\" affix\" unsetenv\n;\n\n: menuset-loadsetnum ( N -- )\n\n\tmenuset-checksetnum ( n -- )\n\n\t\\ \n\t\\ From here out, we use temporary environment variables to make\n\t\\ dealing with variable-length strings easier.\n\t\\ \n\t\\ menuset_use_name is true or false\n\t\\ $affix should be use appropriated w\/respect to menuset_use_name\n\t\\ \n\n\t\\ ... menu_init ...\n\ts\" set var=init\" evaluate\n\tmenuset-loadmenuvar\n\n\t\\ If menu_init was set by the above, evaluate it here-and-now\n\t\\ so that the remaining variables are influenced by its actions\n\ts\" menu_init\" 2dup getenv dup -1 <> if\n\t\t2swap unsetenv \\ don't want later menu-create to re-call this\n\t\tevaluate\n\telse\n\t\tdrop 2drop ( n c-addr u -1 -- n )\n\tthen\n\n\t[char] 1 ( -- x ) \\ Loop range ASCII '1' (49) to '8' (56)\n\tbegin\n\t\tdup menuset_x tuck c! 1 s\" x\" setenv \\ set loop iterator and $x\n\n\t\ts\" set var=caption\" evaluate\n\n\t\t\\ ... menu_caption[x] ...\n\t\tmenuset-loadmenuxvar\n\n\t\t\\ ... ansi_caption[x] ...\n\t\tmenuset-loadansixvar\n\n\t\t[char] 0 ( x -- x y ) \\ Inner Loop ASCII '1' (48) to '9' (57)\n\t\tbegin\n\t\t\tdup menuset_y tuck c! 1 s\" y\" setenv\n\t\t\t\t\\ set inner loop iterator and $y\n\n\t\t\t\\ ... menu_caption[x][y] ...\n\t\t\tmenuset-loadmenuxyvar\n\n\t\t\t\\ ... ansi_caption[x][y] ...\n\t\t\tmenuset-loadansixyvar\n\n\t\t\t1+ dup 57 > ( x y -- y' 0|-1 ) \\ increment and test\n\t\tuntil\n\t\tdrop ( x y -- x )\n\n\t\t\\ ... menu_command[x] ...\n\t\ts\" set var=command\" evaluate\n\t\tmenuset-loadmenuxvar\n\n\t\t\\ ... menu_init[x] ...\n\t\ts\" set var=init\" evaluate\n\t\tmenuset-loadmenuxvar\n\n\t\t\\ ... menu_keycode[x] ...\n\t\ts\" set var=keycode\" evaluate\n\t\tmenuset-loadmenuxvar\n\n\t\t\\ ... toggled_text[x] ...\n\t\ts\" set var=text\" evaluate\n\t\tmenuset-loadtoggledxvar\n\n\t\t\\ ... toggled_ansi[x] ...\n\t\ts\" set var=ansi\" evaluate\n\t\tmenuset-loadtoggledxvar\n\n\t\t1+ dup 56 > ( x -- x' 0|-1 ) \\ increment iterator\n\t\t \\ continue if less than 57\n\tuntil\n\tdrop ( x -- ) \\ loop iterator\n\n\t\\ ... menu_reboot ...\n\ts\" set var=reboot\" evaluate\n\tmenuset-loadmenuvar\n\n\t\\ ... menu_acpi ...\n\ts\" set var=acpi\" evaluate\n\tmenuset-loadmenuvar\n\n\t\\ ... menu_options ...\n\ts\" set var=options\" evaluate\n\tmenuset-loadmenuvar\n\n\t\\ ... menu_options ...\n\ts\" set var=optionstext\" evaluate\n\tmenuset-loadmenuvar\n\n\tmenuset-cleanup\n;\n\n: menuset-loadinitial ( -- )\n\ts\" menuset_initial\" getenv dup -1 <> if\n\t\t?number 0<> if\n\t\t\tmenuset-loadsetnum\n\t\tthen\n\telse\n\t\tdrop \\ cruft\n\tthen\n;\n\n: menusets-unset ( -- )\n\n\ts\" menuset_initial\" unsetenv\n\n\t1 begin\n\t\tdup menuset-checksetnum ( n n -- n )\n\n\t\tdup menuset-setnum-namevar ( n n -- n )\n\t\tunsetenv\n\n\t\t\\ If the current menuset does not populate the first menuitem,\n\t\t\\ we stop completely.\n\n\t\tmenuset_use_name @ true = if\n\t\t\ts\" set buf=${affix}menu_caption[1]\"\n\t\telse\n\t\t\ts\" set buf=menuset${affix}_caption[1]\"\n\t\tthen\n\t\tevaluate s\" buf\" getenv getenv -1 = if\n\t\t\tdrop ( n -- )\n\t\t\ts\" buf\" unsetenv\n\t\t\tmenuset-cleanup\n\t\t\texit\n\t\telse\n\t\t\tdrop ( n c-addr2 -- n ) \\ unused\n\t\tthen\n\n\t\t[char] 1 ( n -- n x ) \\ Loop range ASCII '1' (49) to '8' (56)\n\t\tbegin\n\t\t\tdup menuset_x tuck c! 1 s\" x\" setenv \\ set $x to x\n\n\t\t\ts\" set var=caption\" evaluate\n\t\t\tmenuset-unloadmenuxvar\n\t\t\tmenuset-unloadmenuxvar\n\t\t\tmenuset-unloadansixvar\n\t\t\t[char] 0 ( n x -- n x y ) \\ Inner loop '0' to '9'\n\t\t\tbegin\n\t\t\t\tdup menuset_y tuck c! 1 s\" y\" setenv\n\t\t\t\t\t\\ sets $y to y\n\t\t\t\tmenuset-unloadmenuxyvar\n\t\t\t\tmenuset-unloadansixyvar\n\t\t\t\t1+ dup 57 > ( n x y -- n x y' 0|-1 )\n\t\t\tuntil\n\t\t\tdrop ( n x y -- n x )\n\t\t\ts\" set var=command\" evaluate menuset-unloadmenuxvar\n\t\t\ts\" set var=init\" evaluate menuset-unloadmenuxvar\n\t\t\ts\" set var=keycode\" evaluate menuset-unloadmenuxvar\n\t\t\ts\" set var=text\" evaluate menuset-unloadtoggledxvar\n\t\t\ts\" set var=ansi\" evaluate menuset-unloadtoggledxvar\n\n\t\t\t1+ dup 56 > ( x -- x' 0|-1 ) \\ increment and test\n\t\tuntil\n\t\tdrop ( n x -- n ) \\ loop iterator\n\n\t\ts\" set var=acpi\" evaluate menuset-unloadmenuvar\n\t\ts\" set var=init\" evaluate menuset-unloadmenuvar\n\t\ts\" set var=options\" evaluate menuset-unloadmenuvar\n\t\ts\" set var=optionstext\" evaluate menuset-unloadmenuvar\n\t\ts\" set var=reboot\" evaluate menuset-unloadmenuvar\n\n\t\t1+ dup 65535 > ( n -- n' 0|-1 ) \\ increment and test\n\tuntil\n\tdrop ( n' -- ) \\ loop iterator\n\n\ts\" buf\" unsetenv\n\tmenuset-cleanup\n;\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"0b6373844a5af006f252218a8d7ebebe1a32cffd","subject":"Fix funny comment.","message":"Fix funny comment.\n\nApproved by:\tadrian (co-mentor) (implicit)\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/menusets.4th","new_file":"sys\/boot\/forth\/menusets.4th","new_contents":"\\ Copyright (c) 2012 Devin Teske \n\\ All rights reserved.\n\\ \n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\ \n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\ \n\\ $FreeBSD$\n\nmarker task-menusets.4th\n\nvariable menuset_use_name\n\ncreate menuset_affixbuf\t255 allot\ncreate menuset_x 1 allot\ncreate menuset_y 1 allot\n\n: menuset-loadvar ( -- )\n\n\t\\ menuset_use_name is true or false\n\t\\ $type should be set to one of:\n\t\\ \tmenu toggled ansi\n\t\\ $var should be set to one of:\n\t\\ \tcaption command keycode text ...\n\t\\ $affix is either prefix (menuset_use_name is true)\n\t\\ or infix (menuset_use_name is false)\n\n\ts\" set cmdbuf='set ${type}_${var}=\\$'\" evaluate\n\ts\" cmdbuf\" getenv swap drop ( -- u1 ) \\ get string length\n\tmenuset_use_name @ true = if\n\t\ts\" set cmdbuf=${cmdbuf}${affix}${type}_${var}\"\n\t\t( u1 -- u1 c-addr2 u2 )\n\telse\n\t\ts\" set cmdbuf=${cmdbuf}${type}set${affix}_${var}\"\n\t\t( u1 -- u1 c-addr2 u2 )\n\tthen\n\tevaluate ( u1 c-addr2 u2 -- u1 )\n\ts\" cmdbuf\" getenv ( u1 -- u1 c-addr2 u2 )\n\trot 2 pick 2 pick over + -rot + tuck -\n\t\t( u1 c-addr2 u2 -- c-addr2 u2 c-addr1 u1 )\n\t\t\\ Generate a string representing rvalue inheritance var\n\tgetenv dup -1 = if\n\t\t( c-addr2 u2 c-addr1 u1 -- c-addr2 u2 -1 )\n\t\t\\ NOT set -- clean up the stack\n\t\tdrop ( c-addr2 u2 -1 -- c-addr2 u2 )\n\t\t2drop ( c-addr2 u2 -- )\n\telse\n\t\t( c-addr2 u2 c-addr1 u1 -- c-addr2 u2 c-addr1 u1 )\n\t\t\\ SET -- execute cmdbuf (c-addr2\/u2) to inherit value\n\t\t2drop ( c-addr2 u2 c-addr1 u1 -- c-addr2 u2 )\n\t\tevaluate ( c-addr2 u2 -- )\n\tthen\n\n\ts\" cmdbuf\" unsetenv\n;\n\n: menuset-unloadvar ( -- )\n\n\t\\ menuset_use_name is true or false\n\t\\ $type should be set to one of:\n\t\\ \tmenu toggled ansi\n\t\\ $var should be set to one of:\n\t\\ \tcaption command keycode text ...\n\t\\ $affix is either prefix (menuset_use_name is true)\n\t\\ or infix (menuset_use_name is false)\n\n\tmenuset_use_name @ true = if\n\t\ts\" set buf=${affix}${type}_${var}\"\n\telse\n\t\ts\" set buf=${type}set${affix}_${var}\"\n\tthen\n\tevaluate\n\ts\" buf\" getenv unsetenv\n\ts\" buf\" unsetenv\n;\n\n: menuset-loadmenuvar ( -- )\n\ts\" set type=menu\" evaluate\n\tmenuset-loadvar\n;\n\n: menuset-unloadmenuvar ( -- )\n\ts\" set type=menu\" evaluate\n\tmenuset-unloadvar\n;\n\n: menuset-loadxvar ( -- )\n\n\t\\ menuset_use_name is true or false\n\t\\ $type should be set to one of:\n\t\\ \tmenu toggled ansi\n\t\\ $var should be set to one of:\n\t\\ \tcaption command keycode text ...\n\t\\ $x is \"1\" through \"8\"\n\t\\ $affix is either prefix (menuset_use_name is true)\n\t\\ or infix (menuset_use_name is false)\n\n\ts\" set cmdbuf='set ${type}_${var}[${x}]=\\$'\" evaluate\n\ts\" cmdbuf\" getenv swap drop ( -- u1 ) \\ get string length\n\tmenuset_use_name @ true = if\n\t\ts\" set cmdbuf=${cmdbuf}${affix}${type}_${var}[${x}]\"\n\t\t( u1 -- u1 c-addr2 u2 )\n\telse\n\t\ts\" set cmdbuf=${cmdbuf}${type}set${affix}_${var}[${x}]\"\n\t\t( u1 -- u1 c-addr2 u2 )\n\tthen\n\tevaluate ( u1 c-addr2 u2 -- u1 )\n\ts\" cmdbuf\" getenv ( u1 -- u1 c-addr2 u2 )\n\trot 2 pick 2 pick over + -rot + tuck -\n\t\t( u1 c-addr2 u2 -- c-addr2 u2 c-addr1 u1 )\n\t\t\\ Generate a string representing rvalue inheritance var\n\tgetenv dup -1 = if\n\t\t( c-addr2 u2 c-addr1 u1 -- c-addr2 u2 -1 )\n\t\t\\ NOT set -- clean up the stack\n\t\tdrop ( c-addr2 u2 -1 -- c-addr2 u2 )\n\t\t2drop ( c-addr2 u2 -- )\n\telse\n\t\t( c-addr2 u2 c-addr1 u1 -- c-addr2 u2 c-addr1 u1 )\n\t\t\\ SET -- execute cmdbuf (c-addr2\/u2) to inherit value\n\t\t2drop ( c-addr2 u2 c-addr1 u1 -- c-addr2 u2 )\n\t\tevaluate ( c-addr2 u2 -- )\n\tthen\n\n\ts\" cmdbuf\" unsetenv\n;\n\n: menuset-unloadxvar ( -- )\n\n\t\\ menuset_use_name is true or false\n\t\\ $type should be set to one of:\n\t\\ \tmenu toggled ansi\n\t\\ $var should be set to one of:\n\t\\ \tcaption command keycode text ...\n\t\\ $x is \"1\" through \"8\"\n\t\\ $affix is either prefix (menuset_use_name is true)\n\t\\ or infix (menuset_use_name is false)\n\n\tmenuset_use_name @ true = if\n\t\ts\" set buf=${affix}${type}_${var}[${x}]\"\n\telse\n\t\ts\" set buf=${type}set${affix}_${var}[${x}]\"\n\tthen\n\tevaluate\n\ts\" buf\" getenv unsetenv\n\ts\" buf\" unsetenv\n;\n\n: menuset-loadansixvar ( -- )\n\ts\" set type=ansi\" evaluate\n\tmenuset-loadxvar\n;\n\n: menuset-unloadansixvar ( -- )\n\ts\" set type=ansi\" evaluate\n\tmenuset-unloadxvar\n;\n\n: menuset-loadmenuxvar ( -- )\n\ts\" set type=menu\" evaluate\n\tmenuset-loadxvar\n;\n\n: menuset-unloadmenuxvar ( -- )\n\ts\" set type=menu\" evaluate\n\tmenuset-unloadxvar\n;\n\n: menuset-loadtoggledxvar ( -- )\n\ts\" set type=toggled\" evaluate\n\tmenuset-loadxvar\n;\n\n: menuset-unloadtoggledxvar ( -- )\n\ts\" set type=toggled\" evaluate\n\tmenuset-unloadxvar\n;\n\n: menuset-loadxyvar ( -- )\n\n\t\\ menuset_use_name is true or false\n\t\\ $type should be set to one of:\n\t\\ \tmenu toggled ansi\n\t\\ $var should be set to one of:\n\t\\ \tcaption command keycode text ...\n\t\\ $x is \"1\" through \"8\"\n\t\\ $y is \"0\" through \"9\"\n\t\\ $affix is either prefix (menuset_use_name is true)\n\t\\ or infix (menuset_use_name is false)\n\n\ts\" set cmdbuf='set ${type}_${var}[${x}][${y}]=\\$'\" evaluate\n\ts\" cmdbuf\" getenv swap drop ( -- u1 ) \\ get string length\n\tmenuset_use_name @ true = if\n\t\ts\" set cmdbuf=${cmdbuf}${affix}${type}_${var}[${x}][${y}]\"\n\t\t( u1 -- u1 c-addr2 u2 )\n\telse\n\t\ts\" set cmdbuf=${cmdbuf}${type}set${affix}_${var}[${x}][${y}]\"\n\t\t( u1 -- u1 c-addr2 u2 )\n\tthen\n\tevaluate ( u1 c-addr2 u2 -- u1 )\n\ts\" cmdbuf\" getenv ( u1 -- u1 c-addr2 u2 )\n\trot 2 pick 2 pick over + -rot + tuck -\n\t\t( u1 c-addr2 u2 -- c-addr2 u2 c-addr1 u1 )\n\t\t\\ Generate a string representing rvalue inheritance var\n\tgetenv dup -1 = if\n\t\t( c-addr2 u2 c-addr1 u1 -- c-addr2 u2 -1 )\n\t\t\\ NOT set -- clean up the stack\n\t\tdrop ( c-addr2 u2 -1 -- c-addr2 u2 )\n\t\t2drop ( c-addr2 u2 -- )\n\telse\n\t\t( c-addr2 u2 c-addr1 u1 -- c-addr2 u2 c-addr1 u1 )\n\t\t\\ SET -- execute cmdbuf (c-addr2\/u2) to inherit value\n\t\t2drop ( c-addr2 u2 c-addr1 u1 -- c-addr2 u2 )\n\t\tevaluate ( c-addr2 u2 -- )\n\tthen\n\n\ts\" cmdbuf\" unsetenv\n;\n\n: menuset-unloadxyvar ( -- )\n\n\t\\ menuset_use_name is true or false\n\t\\ $type should be set to one of:\n\t\\ \tmenu toggled ansi\n\t\\ $var should be set to one of:\n\t\\ \tcaption command keycode text ...\n\t\\ $x is \"1\" through \"8\"\n\t\\ $y is \"0\" through \"9\"\n\t\\ $affix is either prefix (menuset_use_name is true)\n\t\\ or infix (menuset_use_name is false)\n\n\tmenuset_use_name @ true = if\n\t\ts\" set buf=${affix}${type}_${var}[${x}][${y}]\"\n\telse\n\t\ts\" set buf=${type}set${affix}_${var}[${x}][${y}]\"\n\tthen\n\tevaluate\n\ts\" buf\" getenv unsetenv\n\ts\" buf\" unsetenv\n;\n\n: menuset-loadansixyvar ( -- )\n\ts\" set type=ansi\" evaluate\n\tmenuset-loadxyvar\n;\n\n: menuset-unloadansixyvar ( -- )\n\ts\" set type=ansi\" evaluate\n\tmenuset-unloadxyvar\n;\n\n: menuset-loadmenuxyvar ( -- )\n\ts\" set type=menu\" evaluate\n\tmenuset-loadxyvar\n;\n\n: menuset-unloadmenuxyvar ( -- )\n\ts\" set type=menu\" evaluate\n\tmenuset-unloadxyvar\n;\n\n: menuset-setnum-namevar ( N -- C-Addr\/U )\n\n\ts\" menuset_nameNNNNN\" ( n -- n c-addr1 u1 )\t\\ variable basename\n\tdrop 12 ( n c-addr1 u1 -- n c-addr1 12 )\t\\ remove \"NNNNN\"\n\trot ( n c-addr1 12 -- c-addr1 12 n )\t\\ move number on top\n\n\t\\ convert to string\n\ts>d <# #s #> ( c-addr1 12 n -- c-addr1 12 c-addr2 u2 )\n\n\t\\ Combine strings\n\tbegin ( using u2 in c-addr2\/u2 pair as countdown to zero )\n\t\tover\t( c-addr1 u1 c-addr2 u2 -- continued below )\n\t\t\t( c-addr1 u1 c-addr2 u2 c-addr2 ) \\ copy src-addr\n\t\tc@\t( c-addr1 u1 c-addr2 u2 c-addr2 -- continued below )\n\t\t\t( c-addr1 u1 c-addr2 u2 c ) \\ get next src-addr byte\n\t\t4 pick 4 pick\n\t\t\t( c-addr1 u1 c-addr2 u2 c -- continued below )\n\t\t\t( c-addr1 u1 c-addr2 u2 c c-addr1 u1 )\n\t\t\t\\ get destination c-addr1\/u1 pair\n\t\t+\t( c-addr1 u1 c-addr2 u2 c c-addr1 u1 -- cont. below )\n\t\t\t( c-addr1 u1 c-addr2 u2 c c-addr3 )\n\t\t\t\\ combine dest-c-addr to get dest-addr for byte\n\t\tc!\t( c-addr1 u1 c-addr2 u2 c c-addr3 -- continued below )\n\t\t\t( c-addr1 u1 c-addr2 u2 )\n\t\t\t\\ store the current src-addr byte into dest-addr\n\n\t\t2swap 1+ 2swap\t\\ increment u1 in destination c-addr1\/u1 pair\n\t\tswap 1+ swap\t\\ increment c-addr2 in source c-addr2\/u2 pair\n\t\t1-\t\t\\ decrement u2 in the source c-addr2\/u2 pair\n\n\t\tdup 0= \\ time to break?\n\tuntil\n\n\t2drop\t( c-addr1 u1 c-addr2 u2 -- c-addr1 u1 )\n\t\t\\ drop temporary number-format conversion c-addr2\/u2\n;\n\n: menuset-checksetnum ( N -- )\n\n\t\\ \n\t\\ adjust input to be both positive and no-higher than 65535\n\t\\ \n\tabs dup 65535 > if drop 65535 then ( n -- n )\n\n\t\\\n\t\\ The next few blocks will determine if we should use the default\n\t\\ methodology (referencing the original numeric stack-input), or if-\n\t\\ instead $menuset_name{N} has been defined wherein we would then\n\t\\ use the value thereof as the prefix to every menu variable.\n\t\\ \n\n\tfalse menuset_use_name ! \\ assume name is not set\n\n\tmenuset-setnum-namevar \n\t\\ \n\t\\ We now have a string that is the assembled variable name to check\n\t\\ for... $menuset_name{N}. Let's check for it.\n\t\\ \n\t2dup ( c-addr1 u1 -- c-addr1 u1 c-addr1 u1 ) \\ save a copy\n\tgetenv dup -1 <> if ( c-addr1 u1 c-addr1 u1 -- c-addr1 u1 c-addr2 u2 )\n\t\t\\ The variable is set. Let's clean up the stack leaving only\n\t\t\\ its value for later use.\n\n\t\ttrue menuset_use_name !\n\t\t2swap 2drop\t( c-addr1 u1 c-addr2 u2 -- c-addr2 u2 )\n\t\t\t\t\\ drop assembled variable name, leave the value\n\telse ( c-addr1 u1 c-addr1 u1 -- c-addr1 u1 -1 ) \\ no such variable\n\t\t\\ The variable is not set. Let's clean up the stack leaving the\n\t\t\\ string [portion] representing the original numeric input.\n\n\t\tdrop ( c-addr1 u1 -1 -- c-addr1 u1 ) \\ drop -1 result\n\t\t12 - swap 12 + swap ( c-addr1 u1 -- c-addr2 u2 )\n\t\t\t\\ truncate to original numeric stack-input\n\tthen\n\n\t\\ \n\t\\ Now, depending on whether $menuset_name{N} has been set, we have\n\t\\ either the value thereof to be used as a prefix to all menu_*\n\t\\ variables or we have a string representing the numeric stack-input\n\t\\ to be used as a \"set{N}\" infix to the same menu_* variables.\n\t\\ \n\t\\ For example, if the stack-input is 1 and menuset_name1 is NOT set\n\t\\ the following variables will be referenced:\n\t\\ \tansiset1_caption[x]\t\t-> ansi_caption[x]\n\t\\ \tansiset1_caption[x][y]\t\t-> ansi_caption[x][y]\n\t\\ \tmenuset1_acpi\t\t\t-> menu_acpi\n\t\\ \tmenuset1_caption[x]\t\t-> menu_caption[x]\n\t\\ \tmenuset1_caption[x][y]\t\t-> menu_caption[x][y]\n\t\\ \tmenuset1_command[x]\t\t-> menu_command[x]\n\t\\ \tmenuset1_init\t\t\t-> ``evaluated''\n\t\\ \tmenuset1_init[x]\t\t-> menu_init[x]\n\t\\ \tmenuset1_keycode[x]\t\t-> menu_keycode[x]\n\t\\ \tmenuset1_options\t\t-> menu_options\n\t\\ \tmenuset1_optionstext\t\t-> menu_optionstext\n\t\\ \tmenuset1_reboot\t\t\t-> menu_reboot\n\t\\ \ttoggledset1_ansi[x]\t\t-> toggled_ansi[x]\n\t\\ \ttoggledset1_text[x]\t\t-> toggled_text[x]\n\t\\ otherwise, the following variables are referenced (where {name}\n\t\\ represents the value of $menuset_name1 (given 1 as stack-input):\n\t\\ \t{name}ansi_caption[x]\t\t-> ansi_caption[x]\n\t\\ \t{name}ansi_caption[x][y]\t-> ansi_caption[x][y]\n\t\\ \t{name}menu_acpi\t\t\t-> menu_acpi\n\t\\ \t{name}menu_caption[x]\t\t-> menu_caption[x]\n\t\\ \t{name}menu_caption[x][y]\t-> menu_caption[x][y]\n\t\\ \t{name}menu_command[x]\t\t-> menu_command[x]\n\t\\ \t{name}menu_init\t\t\t-> ``evaluated''\n\t\\ \t{name}menu_init[x]\t\t-> menu_init[x]\n\t\\ \t{name}menu_keycode[x]\t\t-> menu_keycode[x]\n\t\\ \t{name}menu_options\t\t-> menu_options\n\t\\ \t{name}menu_optionstext\t\t-> menu_optionstext\n\t\\ \t{name}menu_reboot\t\t-> menu_reboot\n\t\\ \t{name}toggled_ansi[x]\t\t-> toggled_ansi[x]\n\t\\ \t{name}toggled_text[x]\t\t-> toggled_text[x]\n\t\\ \n\t\\ Note that menuset{N}_init and {name}menu_init are the initializers\n\t\\ for the entire menu (for wholly dynamic menus) opposed to the per-\n\t\\ menuitem initializers (with [x] afterward). The whole-menu init\n\t\\ routine is evaluated and not passed down to $menu_init (which\n\t\\ would result in double evaluation). By doing this, the initializer\n\t\\ can initialize the menuset before we transfer it to active-duty.\n\t\\ \n\n\t\\ \n\t\\ Copy our affixation (prefix or infix depending on menuset_use_name)\n\t\\ to our buffer so that we can safely use the s-quote (s\") buf again.\n\t\\ \n\tmenuset_affixbuf 0 2swap ( c-addr2 u2 -- c-addr1 0 c-addr2 u2 )\n\tbegin ( using u2 in c-addr2\/u2 pair as countdown to zero )\n\t\tover ( c-addr1 u1 c-addr2 u2 -- c-addr1 u1 c-addr2 u2 c-addr2 )\n\t\tc@ ( c-addr1 u1 c-addr2 u2 -- c-addr1 u1 c-addr2 u2 c )\n\t\t4 pick 4 pick\n\t\t ( c-addr1 u1 c-addr2 u2 c -- continued below )\n\t\t ( c-addr1 u1 c-addr2 u2 c c-addr1 u1 )\n\t\t+ ( c-addr1 u1 c-addr2 u2 c c-addr1 u1 -- continued below )\n\t\t ( c-addr1 u1 c-addr2 u2 c c-addr3 )\n\t\tc! ( c-addr1 u1 c-addr2 u2 c c-addr3 -- continued below )\n\t\t ( c-addr1 u1 c-addr2 u2 )\n\t\t2swap 1+ 2swap\t\\ increment affixbuf byte position\/count\n\t\tswap 1+ swap\t\\ increment strbuf pointer (source c-addr2)\n\t\t1-\t\t\\ decrement strbuf byte count (source u2)\n\t\tdup 0= \\ time to break?\n\tuntil\n\t2drop ( c-addr1 u1 c-addr2 u2 -- c-addr1 u1 ) \\ drop strbuf c-addr2\/u2\n\n\t\\\n\t\\ Create a variable for referencing our affix data (prefix or infix\n\t\\ depending on menuset_use_name as described above). This variable will\n\t\\ be temporary and only used to simplify cmdbuf assembly.\n\t\\ \n\ts\" affix\" setenv ( c-addr1 u1 -- )\n;\n\n: menuset-cleanup ( -- )\n\ts\" type\" unsetenv\n\ts\" var\" unsetenv\n\ts\" x\" unsetenv\n\ts\" y\" unsetenv\n\ts\" affix\" unsetenv\n;\n\n: menuset-loadsetnum ( N -- )\n\n\tmenuset-checksetnum ( n -- )\n\n\t\\ \n\t\\ From here out, we use temporary environment variables to make\n\t\\ dealing with variable-length strings easier.\n\t\\ \n\t\\ menuset_use_name is true or false\n\t\\ $affix should be used appropriately w\/respect to menuset_use_name\n\t\\ \n\n\t\\ ... menu_init ...\n\ts\" set var=init\" evaluate\n\tmenuset-loadmenuvar\n\n\t\\ If menu_init was set by the above, evaluate it here-and-now\n\t\\ so that the remaining variables are influenced by its actions\n\ts\" menu_init\" 2dup getenv dup -1 <> if\n\t\t2swap unsetenv \\ don't want later menu-create to re-call this\n\t\tevaluate\n\telse\n\t\tdrop 2drop ( n c-addr u -1 -- n )\n\tthen\n\n\t[char] 1 ( -- x ) \\ Loop range ASCII '1' (49) to '8' (56)\n\tbegin\n\t\tdup menuset_x tuck c! 1 s\" x\" setenv \\ set loop iterator and $x\n\n\t\ts\" set var=caption\" evaluate\n\n\t\t\\ ... menu_caption[x] ...\n\t\tmenuset-loadmenuxvar\n\n\t\t\\ ... ansi_caption[x] ...\n\t\tmenuset-loadansixvar\n\n\t\t[char] 0 ( x -- x y ) \\ Inner Loop ASCII '1' (48) to '9' (57)\n\t\tbegin\n\t\t\tdup menuset_y tuck c! 1 s\" y\" setenv\n\t\t\t\t\\ set inner loop iterator and $y\n\n\t\t\t\\ ... menu_caption[x][y] ...\n\t\t\tmenuset-loadmenuxyvar\n\n\t\t\t\\ ... ansi_caption[x][y] ...\n\t\t\tmenuset-loadansixyvar\n\n\t\t\t1+ dup 57 > ( x y -- y' 0|-1 ) \\ increment and test\n\t\tuntil\n\t\tdrop ( x y -- x )\n\n\t\t\\ ... menu_command[x] ...\n\t\ts\" set var=command\" evaluate\n\t\tmenuset-loadmenuxvar\n\n\t\t\\ ... menu_init[x] ...\n\t\ts\" set var=init\" evaluate\n\t\tmenuset-loadmenuxvar\n\n\t\t\\ ... menu_keycode[x] ...\n\t\ts\" set var=keycode\" evaluate\n\t\tmenuset-loadmenuxvar\n\n\t\t\\ ... toggled_text[x] ...\n\t\ts\" set var=text\" evaluate\n\t\tmenuset-loadtoggledxvar\n\n\t\t\\ ... toggled_ansi[x] ...\n\t\ts\" set var=ansi\" evaluate\n\t\tmenuset-loadtoggledxvar\n\n\t\t1+ dup 56 > ( x -- x' 0|-1 ) \\ increment iterator\n\t\t \\ continue if less than 57\n\tuntil\n\tdrop ( x -- ) \\ loop iterator\n\n\t\\ ... menu_reboot ...\n\ts\" set var=reboot\" evaluate\n\tmenuset-loadmenuvar\n\n\t\\ ... menu_acpi ...\n\ts\" set var=acpi\" evaluate\n\tmenuset-loadmenuvar\n\n\t\\ ... menu_options ...\n\ts\" set var=options\" evaluate\n\tmenuset-loadmenuvar\n\n\t\\ ... menu_optionstext ...\n\ts\" set var=optionstext\" evaluate\n\tmenuset-loadmenuvar\n\n\tmenuset-cleanup\n;\n\n: menuset-loadinitial ( -- )\n\ts\" menuset_initial\" getenv dup -1 <> if\n\t\t?number 0<> if\n\t\t\tmenuset-loadsetnum\n\t\tthen\n\telse\n\t\tdrop \\ cruft\n\tthen\n;\n\n: menusets-unset ( -- )\n\n\ts\" menuset_initial\" unsetenv\n\n\t1 begin\n\t\tdup menuset-checksetnum ( n n -- n )\n\n\t\tdup menuset-setnum-namevar ( n n -- n )\n\t\tunsetenv\n\n\t\t\\ If the current menuset does not populate the first menuitem,\n\t\t\\ we stop completely.\n\n\t\tmenuset_use_name @ true = if\n\t\t\ts\" set buf=${affix}menu_caption[1]\"\n\t\telse\n\t\t\ts\" set buf=menuset${affix}_caption[1]\"\n\t\tthen\n\t\tevaluate s\" buf\" getenv getenv -1 = if\n\t\t\tdrop ( n -- )\n\t\t\ts\" buf\" unsetenv\n\t\t\tmenuset-cleanup\n\t\t\texit\n\t\telse\n\t\t\tdrop ( n c-addr2 -- n ) \\ unused\n\t\tthen\n\n\t\t[char] 1 ( n -- n x ) \\ Loop range ASCII '1' (49) to '8' (56)\n\t\tbegin\n\t\t\tdup menuset_x tuck c! 1 s\" x\" setenv \\ set $x to x\n\n\t\t\ts\" set var=caption\" evaluate\n\t\t\tmenuset-unloadmenuxvar\n\t\t\tmenuset-unloadmenuxvar\n\t\t\tmenuset-unloadansixvar\n\t\t\t[char] 0 ( n x -- n x y ) \\ Inner loop '0' to '9'\n\t\t\tbegin\n\t\t\t\tdup menuset_y tuck c! 1 s\" y\" setenv\n\t\t\t\t\t\\ sets $y to y\n\t\t\t\tmenuset-unloadmenuxyvar\n\t\t\t\tmenuset-unloadansixyvar\n\t\t\t\t1+ dup 57 > ( n x y -- n x y' 0|-1 )\n\t\t\tuntil\n\t\t\tdrop ( n x y -- n x )\n\t\t\ts\" set var=command\" evaluate menuset-unloadmenuxvar\n\t\t\ts\" set var=init\" evaluate menuset-unloadmenuxvar\n\t\t\ts\" set var=keycode\" evaluate menuset-unloadmenuxvar\n\t\t\ts\" set var=text\" evaluate menuset-unloadtoggledxvar\n\t\t\ts\" set var=ansi\" evaluate menuset-unloadtoggledxvar\n\n\t\t\t1+ dup 56 > ( x -- x' 0|-1 ) \\ increment and test\n\t\tuntil\n\t\tdrop ( n x -- n ) \\ loop iterator\n\n\t\ts\" set var=acpi\" evaluate menuset-unloadmenuvar\n\t\ts\" set var=init\" evaluate menuset-unloadmenuvar\n\t\ts\" set var=options\" evaluate menuset-unloadmenuvar\n\t\ts\" set var=optionstext\" evaluate menuset-unloadmenuvar\n\t\ts\" set var=reboot\" evaluate menuset-unloadmenuvar\n\n\t\t1+ dup 65535 > ( n -- n' 0|-1 ) \\ increment and test\n\tuntil\n\tdrop ( n' -- ) \\ loop iterator\n\n\ts\" buf\" unsetenv\n\tmenuset-cleanup\n;\n","old_contents":"\\ Copyright (c) 2012 Devin Teske \n\\ All rights reserved.\n\\ \n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\ \n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\ \n\\ $FreeBSD$\n\nmarker task-menusets.4th\n\nvariable menuset_use_name\n\ncreate menuset_affixbuf\t255 allot\ncreate menuset_x 1 allot\ncreate menuset_y 1 allot\n\n: menuset-loadvar ( -- )\n\n\t\\ menuset_use_name is true or false\n\t\\ $type should be set to one of:\n\t\\ \tmenu toggled ansi\n\t\\ $var should be set to one of:\n\t\\ \tcaption command keycode text ...\n\t\\ $affix is either prefix (menuset_use_name is true)\n\t\\ or infix (menuset_use_name is false)\n\n\ts\" set cmdbuf='set ${type}_${var}=\\$'\" evaluate\n\ts\" cmdbuf\" getenv swap drop ( -- u1 ) \\ get string length\n\tmenuset_use_name @ true = if\n\t\ts\" set cmdbuf=${cmdbuf}${affix}${type}_${var}\"\n\t\t( u1 -- u1 c-addr2 u2 )\n\telse\n\t\ts\" set cmdbuf=${cmdbuf}${type}set${affix}_${var}\"\n\t\t( u1 -- u1 c-addr2 u2 )\n\tthen\n\tevaluate ( u1 c-addr2 u2 -- u1 )\n\ts\" cmdbuf\" getenv ( u1 -- u1 c-addr2 u2 )\n\trot 2 pick 2 pick over + -rot + tuck -\n\t\t( u1 c-addr2 u2 -- c-addr2 u2 c-addr1 u1 )\n\t\t\\ Generate a string representing rvalue inheritance var\n\tgetenv dup -1 = if\n\t\t( c-addr2 u2 c-addr1 u1 -- c-addr2 u2 -1 )\n\t\t\\ NOT set -- clean up the stack\n\t\tdrop ( c-addr2 u2 -1 -- c-addr2 u2 )\n\t\t2drop ( c-addr2 u2 -- )\n\telse\n\t\t( c-addr2 u2 c-addr1 u1 -- c-addr2 u2 c-addr1 u1 )\n\t\t\\ SET -- execute cmdbuf (c-addr2\/u2) to inherit value\n\t\t2drop ( c-addr2 u2 c-addr1 u1 -- c-addr2 u2 )\n\t\tevaluate ( c-addr2 u2 -- )\n\tthen\n\n\ts\" cmdbuf\" unsetenv\n;\n\n: menuset-unloadvar ( -- )\n\n\t\\ menuset_use_name is true or false\n\t\\ $type should be set to one of:\n\t\\ \tmenu toggled ansi\n\t\\ $var should be set to one of:\n\t\\ \tcaption command keycode text ...\n\t\\ $affix is either prefix (menuset_use_name is true)\n\t\\ or infix (menuset_use_name is false)\n\n\tmenuset_use_name @ true = if\n\t\ts\" set buf=${affix}${type}_${var}\"\n\telse\n\t\ts\" set buf=${type}set${affix}_${var}\"\n\tthen\n\tevaluate\n\ts\" buf\" getenv unsetenv\n\ts\" buf\" unsetenv\n;\n\n: menuset-loadmenuvar ( -- )\n\ts\" set type=menu\" evaluate\n\tmenuset-loadvar\n;\n\n: menuset-unloadmenuvar ( -- )\n\ts\" set type=menu\" evaluate\n\tmenuset-unloadvar\n;\n\n: menuset-loadxvar ( -- )\n\n\t\\ menuset_use_name is true or false\n\t\\ $type should be set to one of:\n\t\\ \tmenu toggled ansi\n\t\\ $var should be set to one of:\n\t\\ \tcaption command keycode text ...\n\t\\ $x is \"1\" through \"8\"\n\t\\ $affix is either prefix (menuset_use_name is true)\n\t\\ or infix (menuset_use_name is false)\n\n\ts\" set cmdbuf='set ${type}_${var}[${x}]=\\$'\" evaluate\n\ts\" cmdbuf\" getenv swap drop ( -- u1 ) \\ get string length\n\tmenuset_use_name @ true = if\n\t\ts\" set cmdbuf=${cmdbuf}${affix}${type}_${var}[${x}]\"\n\t\t( u1 -- u1 c-addr2 u2 )\n\telse\n\t\ts\" set cmdbuf=${cmdbuf}${type}set${affix}_${var}[${x}]\"\n\t\t( u1 -- u1 c-addr2 u2 )\n\tthen\n\tevaluate ( u1 c-addr2 u2 -- u1 )\n\ts\" cmdbuf\" getenv ( u1 -- u1 c-addr2 u2 )\n\trot 2 pick 2 pick over + -rot + tuck -\n\t\t( u1 c-addr2 u2 -- c-addr2 u2 c-addr1 u1 )\n\t\t\\ Generate a string representing rvalue inheritance var\n\tgetenv dup -1 = if\n\t\t( c-addr2 u2 c-addr1 u1 -- c-addr2 u2 -1 )\n\t\t\\ NOT set -- clean up the stack\n\t\tdrop ( c-addr2 u2 -1 -- c-addr2 u2 )\n\t\t2drop ( c-addr2 u2 -- )\n\telse\n\t\t( c-addr2 u2 c-addr1 u1 -- c-addr2 u2 c-addr1 u1 )\n\t\t\\ SET -- execute cmdbuf (c-addr2\/u2) to inherit value\n\t\t2drop ( c-addr2 u2 c-addr1 u1 -- c-addr2 u2 )\n\t\tevaluate ( c-addr2 u2 -- )\n\tthen\n\n\ts\" cmdbuf\" unsetenv\n;\n\n: menuset-unloadxvar ( -- )\n\n\t\\ menuset_use_name is true or false\n\t\\ $type should be set to one of:\n\t\\ \tmenu toggled ansi\n\t\\ $var should be set to one of:\n\t\\ \tcaption command keycode text ...\n\t\\ $x is \"1\" through \"8\"\n\t\\ $affix is either prefix (menuset_use_name is true)\n\t\\ or infix (menuset_use_name is false)\n\n\tmenuset_use_name @ true = if\n\t\ts\" set buf=${affix}${type}_${var}[${x}]\"\n\telse\n\t\ts\" set buf=${type}set${affix}_${var}[${x}]\"\n\tthen\n\tevaluate\n\ts\" buf\" getenv unsetenv\n\ts\" buf\" unsetenv\n;\n\n: menuset-loadansixvar ( -- )\n\ts\" set type=ansi\" evaluate\n\tmenuset-loadxvar\n;\n\n: menuset-unloadansixvar ( -- )\n\ts\" set type=ansi\" evaluate\n\tmenuset-unloadxvar\n;\n\n: menuset-loadmenuxvar ( -- )\n\ts\" set type=menu\" evaluate\n\tmenuset-loadxvar\n;\n\n: menuset-unloadmenuxvar ( -- )\n\ts\" set type=menu\" evaluate\n\tmenuset-unloadxvar\n;\n\n: menuset-loadtoggledxvar ( -- )\n\ts\" set type=toggled\" evaluate\n\tmenuset-loadxvar\n;\n\n: menuset-unloadtoggledxvar ( -- )\n\ts\" set type=toggled\" evaluate\n\tmenuset-unloadxvar\n;\n\n: menuset-loadxyvar ( -- )\n\n\t\\ menuset_use_name is true or false\n\t\\ $type should be set to one of:\n\t\\ \tmenu toggled ansi\n\t\\ $var should be set to one of:\n\t\\ \tcaption command keycode text ...\n\t\\ $x is \"1\" through \"8\"\n\t\\ $y is \"0\" through \"9\"\n\t\\ $affix is either prefix (menuset_use_name is true)\n\t\\ or infix (menuset_use_name is false)\n\n\ts\" set cmdbuf='set ${type}_${var}[${x}][${y}]=\\$'\" evaluate\n\ts\" cmdbuf\" getenv swap drop ( -- u1 ) \\ get string length\n\tmenuset_use_name @ true = if\n\t\ts\" set cmdbuf=${cmdbuf}${affix}${type}_${var}[${x}][${y}]\"\n\t\t( u1 -- u1 c-addr2 u2 )\n\telse\n\t\ts\" set cmdbuf=${cmdbuf}${type}set${affix}_${var}[${x}][${y}]\"\n\t\t( u1 -- u1 c-addr2 u2 )\n\tthen\n\tevaluate ( u1 c-addr2 u2 -- u1 )\n\ts\" cmdbuf\" getenv ( u1 -- u1 c-addr2 u2 )\n\trot 2 pick 2 pick over + -rot + tuck -\n\t\t( u1 c-addr2 u2 -- c-addr2 u2 c-addr1 u1 )\n\t\t\\ Generate a string representing rvalue inheritance var\n\tgetenv dup -1 = if\n\t\t( c-addr2 u2 c-addr1 u1 -- c-addr2 u2 -1 )\n\t\t\\ NOT set -- clean up the stack\n\t\tdrop ( c-addr2 u2 -1 -- c-addr2 u2 )\n\t\t2drop ( c-addr2 u2 -- )\n\telse\n\t\t( c-addr2 u2 c-addr1 u1 -- c-addr2 u2 c-addr1 u1 )\n\t\t\\ SET -- execute cmdbuf (c-addr2\/u2) to inherit value\n\t\t2drop ( c-addr2 u2 c-addr1 u1 -- c-addr2 u2 )\n\t\tevaluate ( c-addr2 u2 -- )\n\tthen\n\n\ts\" cmdbuf\" unsetenv\n;\n\n: menuset-unloadxyvar ( -- )\n\n\t\\ menuset_use_name is true or false\n\t\\ $type should be set to one of:\n\t\\ \tmenu toggled ansi\n\t\\ $var should be set to one of:\n\t\\ \tcaption command keycode text ...\n\t\\ $x is \"1\" through \"8\"\n\t\\ $y is \"0\" through \"9\"\n\t\\ $affix is either prefix (menuset_use_name is true)\n\t\\ or infix (menuset_use_name is false)\n\n\tmenuset_use_name @ true = if\n\t\ts\" set buf=${affix}${type}_${var}[${x}][${y}]\"\n\telse\n\t\ts\" set buf=${type}set${affix}_${var}[${x}][${y}]\"\n\tthen\n\tevaluate\n\ts\" buf\" getenv unsetenv\n\ts\" buf\" unsetenv\n;\n\n: menuset-loadansixyvar ( -- )\n\ts\" set type=ansi\" evaluate\n\tmenuset-loadxyvar\n;\n\n: menuset-unloadansixyvar ( -- )\n\ts\" set type=ansi\" evaluate\n\tmenuset-unloadxyvar\n;\n\n: menuset-loadmenuxyvar ( -- )\n\ts\" set type=menu\" evaluate\n\tmenuset-loadxyvar\n;\n\n: menuset-unloadmenuxyvar ( -- )\n\ts\" set type=menu\" evaluate\n\tmenuset-unloadxyvar\n;\n\n: menuset-setnum-namevar ( N -- C-Addr\/U )\n\n\ts\" menuset_nameNNNNN\" ( n -- n c-addr1 u1 )\t\\ variable basename\n\tdrop 12 ( n c-addr1 u1 -- n c-addr1 12 )\t\\ remove \"NNNNN\"\n\trot ( n c-addr1 12 -- c-addr1 12 n )\t\\ move number on top\n\n\t\\ convert to string\n\ts>d <# #s #> ( c-addr1 12 n -- c-addr1 12 c-addr2 u2 )\n\n\t\\ Combine strings\n\tbegin ( using u2 in c-addr2\/u2 pair as countdown to zero )\n\t\tover\t( c-addr1 u1 c-addr2 u2 -- continued below )\n\t\t\t( c-addr1 u1 c-addr2 u2 c-addr2 ) \\ copy src-addr\n\t\tc@\t( c-addr1 u1 c-addr2 u2 c-addr2 -- continued below )\n\t\t\t( c-addr1 u1 c-addr2 u2 c ) \\ get next src-addr byte\n\t\t4 pick 4 pick\n\t\t\t( c-addr1 u1 c-addr2 u2 c -- continued below )\n\t\t\t( c-addr1 u1 c-addr2 u2 c c-addr1 u1 )\n\t\t\t\\ get destination c-addr1\/u1 pair\n\t\t+\t( c-addr1 u1 c-addr2 u2 c c-addr1 u1 -- cont. below )\n\t\t\t( c-addr1 u1 c-addr2 u2 c c-addr3 )\n\t\t\t\\ combine dest-c-addr to get dest-addr for byte\n\t\tc!\t( c-addr1 u1 c-addr2 u2 c c-addr3 -- continued below )\n\t\t\t( c-addr1 u1 c-addr2 u2 )\n\t\t\t\\ store the current src-addr byte into dest-addr\n\n\t\t2swap 1+ 2swap\t\\ increment u1 in destination c-addr1\/u1 pair\n\t\tswap 1+ swap\t\\ increment c-addr2 in source c-addr2\/u2 pair\n\t\t1-\t\t\\ decrement u2 in the source c-addr2\/u2 pair\n\n\t\tdup 0= \\ time to break?\n\tuntil\n\n\t2drop\t( c-addr1 u1 c-addr2 u2 -- c-addr1 u1 )\n\t\t\\ drop temporary number-format conversion c-addr2\/u2\n;\n\n: menuset-checksetnum ( N -- )\n\n\t\\ \n\t\\ adjust input to be both positive and no-higher than 65535\n\t\\ \n\tabs dup 65535 > if drop 65535 then ( n -- n )\n\n\t\\\n\t\\ The next few blocks will determine if we should use the default\n\t\\ methodology (referencing the original numeric stack-input), or if-\n\t\\ instead $menuset_name{N} has been defined wherein we would then\n\t\\ use the value thereof as the prefix to every menu variable.\n\t\\ \n\n\tfalse menuset_use_name ! \\ assume name is not set\n\n\tmenuset-setnum-namevar \n\t\\ \n\t\\ We now have a string that is the assembled variable name to check\n\t\\ for... $menuset_name{N}. Let's check for it.\n\t\\ \n\t2dup ( c-addr1 u1 -- c-addr1 u1 c-addr1 u1 ) \\ save a copy\n\tgetenv dup -1 <> if ( c-addr1 u1 c-addr1 u1 -- c-addr1 u1 c-addr2 u2 )\n\t\t\\ The variable is set. Let's clean up the stack leaving only\n\t\t\\ its value for later use.\n\n\t\ttrue menuset_use_name !\n\t\t2swap 2drop\t( c-addr1 u1 c-addr2 u2 -- c-addr2 u2 )\n\t\t\t\t\\ drop assembled variable name, leave the value\n\telse ( c-addr1 u1 c-addr1 u1 -- c-addr1 u1 -1 ) \\ no such variable\n\t\t\\ The variable is not set. Let's clean up the stack leaving the\n\t\t\\ string [portion] representing the original numeric input.\n\n\t\tdrop ( c-addr1 u1 -1 -- c-addr1 u1 ) \\ drop -1 result\n\t\t12 - swap 12 + swap ( c-addr1 u1 -- c-addr2 u2 )\n\t\t\t\\ truncate to original numeric stack-input\n\tthen\n\n\t\\ \n\t\\ Now, depending on whether $menuset_name{N} has been set, we have\n\t\\ either the value thereof to be used as a prefix to all menu_*\n\t\\ variables or we have a string representing the numeric stack-input\n\t\\ to be used as a \"set{N}\" infix to the same menu_* variables.\n\t\\ \n\t\\ For example, if the stack-input is 1 and menuset_name1 is NOT set\n\t\\ the following variables will be referenced:\n\t\\ \tansiset1_caption[x]\t\t-> ansi_caption[x]\n\t\\ \tansiset1_caption[x][y]\t\t-> ansi_caption[x][y]\n\t\\ \tmenuset1_acpi\t\t\t-> menu_acpi\n\t\\ \tmenuset1_caption[x]\t\t-> menu_caption[x]\n\t\\ \tmenuset1_caption[x][y]\t\t-> menu_caption[x][y]\n\t\\ \tmenuset1_command[x]\t\t-> menu_command[x]\n\t\\ \tmenuset1_init\t\t\t-> ``evaluated''\n\t\\ \tmenuset1_init[x]\t\t-> menu_init[x]\n\t\\ \tmenuset1_keycode[x]\t\t-> menu_keycode[x]\n\t\\ \tmenuset1_options\t\t-> menu_options\n\t\\ \tmenuset1_optionstext\t\t-> menu_optionstext\n\t\\ \tmenuset1_reboot\t\t\t-> menu_reboot\n\t\\ \ttoggledset1_ansi[x]\t\t-> toggled_ansi[x]\n\t\\ \ttoggledset1_text[x]\t\t-> toggled_text[x]\n\t\\ otherwise, the following variables are referenced (where {name}\n\t\\ represents the value of $menuset_name1 (given 1 as stack-input):\n\t\\ \t{name}ansi_caption[x]\t\t-> ansi_caption[x]\n\t\\ \t{name}ansi_caption[x][y]\t-> ansi_caption[x][y]\n\t\\ \t{name}menu_acpi\t\t\t-> menu_acpi\n\t\\ \t{name}menu_caption[x]\t\t-> menu_caption[x]\n\t\\ \t{name}menu_caption[x][y]\t-> menu_caption[x][y]\n\t\\ \t{name}menu_command[x]\t\t-> menu_command[x]\n\t\\ \t{name}menu_init\t\t\t-> ``evaluated''\n\t\\ \t{name}menu_init[x]\t\t-> menu_init[x]\n\t\\ \t{name}menu_keycode[x]\t\t-> menu_keycode[x]\n\t\\ \t{name}menu_options\t\t-> menu_options\n\t\\ \t{name}menu_optionstext\t\t-> menu_optionstext\n\t\\ \t{name}menu_reboot\t\t-> menu_reboot\n\t\\ \t{name}toggled_ansi[x]\t\t-> toggled_ansi[x]\n\t\\ \t{name}toggled_text[x]\t\t-> toggled_text[x]\n\t\\ \n\t\\ Note that menuset{N}_init and {name}menu_init are the initializers\n\t\\ for the entire menu (for wholly dynamic menus) opposed to the per-\n\t\\ menuitem initializers (with [x] afterward). The whole-menu init\n\t\\ routine is evaluated and not passed down to $menu_init (which\n\t\\ would result in double evaluation). By doing this, the initializer\n\t\\ can initialize the menuset before we transfer it to active-duty.\n\t\\ \n\n\t\\ \n\t\\ Copy our affixation (prefix or infix depending on menuset_use_name)\n\t\\ to our buffer so that we can safely use the s-quote (s\") buf again.\n\t\\ \n\tmenuset_affixbuf 0 2swap ( c-addr2 u2 -- c-addr1 0 c-addr2 u2 )\n\tbegin ( using u2 in c-addr2\/u2 pair as countdown to zero )\n\t\tover ( c-addr1 u1 c-addr2 u2 -- c-addr1 u1 c-addr2 u2 c-addr2 )\n\t\tc@ ( c-addr1 u1 c-addr2 u2 -- c-addr1 u1 c-addr2 u2 c )\n\t\t4 pick 4 pick\n\t\t ( c-addr1 u1 c-addr2 u2 c -- continued below )\n\t\t ( c-addr1 u1 c-addr2 u2 c c-addr1 u1 )\n\t\t+ ( c-addr1 u1 c-addr2 u2 c c-addr1 u1 -- continued below )\n\t\t ( c-addr1 u1 c-addr2 u2 c c-addr3 )\n\t\tc! ( c-addr1 u1 c-addr2 u2 c c-addr3 -- continued below )\n\t\t ( c-addr1 u1 c-addr2 u2 )\n\t\t2swap 1+ 2swap\t\\ increment affixbuf byte position\/count\n\t\tswap 1+ swap\t\\ increment strbuf pointer (source c-addr2)\n\t\t1-\t\t\\ decrement strbuf byte count (source u2)\n\t\tdup 0= \\ time to break?\n\tuntil\n\t2drop ( c-addr1 u1 c-addr2 u2 -- c-addr1 u1 ) \\ drop strbuf c-addr2\/u2\n\n\t\\\n\t\\ Create a variable for referencing our affix data (prefix or infix\n\t\\ depending on menuset_use_name as described above). This variable will\n\t\\ be temporary and only used to simplify cmdbuf assembly.\n\t\\ \n\ts\" affix\" setenv ( c-addr1 u1 -- )\n;\n\n: menuset-cleanup ( -- )\n\ts\" type\" unsetenv\n\ts\" var\" unsetenv\n\ts\" x\" unsetenv\n\ts\" y\" unsetenv\n\ts\" affix\" unsetenv\n;\n\n: menuset-loadsetnum ( N -- )\n\n\tmenuset-checksetnum ( n -- )\n\n\t\\ \n\t\\ From here out, we use temporary environment variables to make\n\t\\ dealing with variable-length strings easier.\n\t\\ \n\t\\ menuset_use_name is true or false\n\t\\ $affix should be use appropriated w\/respect to menuset_use_name\n\t\\ \n\n\t\\ ... menu_init ...\n\ts\" set var=init\" evaluate\n\tmenuset-loadmenuvar\n\n\t\\ If menu_init was set by the above, evaluate it here-and-now\n\t\\ so that the remaining variables are influenced by its actions\n\ts\" menu_init\" 2dup getenv dup -1 <> if\n\t\t2swap unsetenv \\ don't want later menu-create to re-call this\n\t\tevaluate\n\telse\n\t\tdrop 2drop ( n c-addr u -1 -- n )\n\tthen\n\n\t[char] 1 ( -- x ) \\ Loop range ASCII '1' (49) to '8' (56)\n\tbegin\n\t\tdup menuset_x tuck c! 1 s\" x\" setenv \\ set loop iterator and $x\n\n\t\ts\" set var=caption\" evaluate\n\n\t\t\\ ... menu_caption[x] ...\n\t\tmenuset-loadmenuxvar\n\n\t\t\\ ... ansi_caption[x] ...\n\t\tmenuset-loadansixvar\n\n\t\t[char] 0 ( x -- x y ) \\ Inner Loop ASCII '1' (48) to '9' (57)\n\t\tbegin\n\t\t\tdup menuset_y tuck c! 1 s\" y\" setenv\n\t\t\t\t\\ set inner loop iterator and $y\n\n\t\t\t\\ ... menu_caption[x][y] ...\n\t\t\tmenuset-loadmenuxyvar\n\n\t\t\t\\ ... ansi_caption[x][y] ...\n\t\t\tmenuset-loadansixyvar\n\n\t\t\t1+ dup 57 > ( x y -- y' 0|-1 ) \\ increment and test\n\t\tuntil\n\t\tdrop ( x y -- x )\n\n\t\t\\ ... menu_command[x] ...\n\t\ts\" set var=command\" evaluate\n\t\tmenuset-loadmenuxvar\n\n\t\t\\ ... menu_init[x] ...\n\t\ts\" set var=init\" evaluate\n\t\tmenuset-loadmenuxvar\n\n\t\t\\ ... menu_keycode[x] ...\n\t\ts\" set var=keycode\" evaluate\n\t\tmenuset-loadmenuxvar\n\n\t\t\\ ... toggled_text[x] ...\n\t\ts\" set var=text\" evaluate\n\t\tmenuset-loadtoggledxvar\n\n\t\t\\ ... toggled_ansi[x] ...\n\t\ts\" set var=ansi\" evaluate\n\t\tmenuset-loadtoggledxvar\n\n\t\t1+ dup 56 > ( x -- x' 0|-1 ) \\ increment iterator\n\t\t \\ continue if less than 57\n\tuntil\n\tdrop ( x -- ) \\ loop iterator\n\n\t\\ ... menu_reboot ...\n\ts\" set var=reboot\" evaluate\n\tmenuset-loadmenuvar\n\n\t\\ ... menu_acpi ...\n\ts\" set var=acpi\" evaluate\n\tmenuset-loadmenuvar\n\n\t\\ ... menu_options ...\n\ts\" set var=options\" evaluate\n\tmenuset-loadmenuvar\n\n\t\\ ... menu_optionstext ...\n\ts\" set var=optionstext\" evaluate\n\tmenuset-loadmenuvar\n\n\tmenuset-cleanup\n;\n\n: menuset-loadinitial ( -- )\n\ts\" menuset_initial\" getenv dup -1 <> if\n\t\t?number 0<> if\n\t\t\tmenuset-loadsetnum\n\t\tthen\n\telse\n\t\tdrop \\ cruft\n\tthen\n;\n\n: menusets-unset ( -- )\n\n\ts\" menuset_initial\" unsetenv\n\n\t1 begin\n\t\tdup menuset-checksetnum ( n n -- n )\n\n\t\tdup menuset-setnum-namevar ( n n -- n )\n\t\tunsetenv\n\n\t\t\\ If the current menuset does not populate the first menuitem,\n\t\t\\ we stop completely.\n\n\t\tmenuset_use_name @ true = if\n\t\t\ts\" set buf=${affix}menu_caption[1]\"\n\t\telse\n\t\t\ts\" set buf=menuset${affix}_caption[1]\"\n\t\tthen\n\t\tevaluate s\" buf\" getenv getenv -1 = if\n\t\t\tdrop ( n -- )\n\t\t\ts\" buf\" unsetenv\n\t\t\tmenuset-cleanup\n\t\t\texit\n\t\telse\n\t\t\tdrop ( n c-addr2 -- n ) \\ unused\n\t\tthen\n\n\t\t[char] 1 ( n -- n x ) \\ Loop range ASCII '1' (49) to '8' (56)\n\t\tbegin\n\t\t\tdup menuset_x tuck c! 1 s\" x\" setenv \\ set $x to x\n\n\t\t\ts\" set var=caption\" evaluate\n\t\t\tmenuset-unloadmenuxvar\n\t\t\tmenuset-unloadmenuxvar\n\t\t\tmenuset-unloadansixvar\n\t\t\t[char] 0 ( n x -- n x y ) \\ Inner loop '0' to '9'\n\t\t\tbegin\n\t\t\t\tdup menuset_y tuck c! 1 s\" y\" setenv\n\t\t\t\t\t\\ sets $y to y\n\t\t\t\tmenuset-unloadmenuxyvar\n\t\t\t\tmenuset-unloadansixyvar\n\t\t\t\t1+ dup 57 > ( n x y -- n x y' 0|-1 )\n\t\t\tuntil\n\t\t\tdrop ( n x y -- n x )\n\t\t\ts\" set var=command\" evaluate menuset-unloadmenuxvar\n\t\t\ts\" set var=init\" evaluate menuset-unloadmenuxvar\n\t\t\ts\" set var=keycode\" evaluate menuset-unloadmenuxvar\n\t\t\ts\" set var=text\" evaluate menuset-unloadtoggledxvar\n\t\t\ts\" set var=ansi\" evaluate menuset-unloadtoggledxvar\n\n\t\t\t1+ dup 56 > ( x -- x' 0|-1 ) \\ increment and test\n\t\tuntil\n\t\tdrop ( n x -- n ) \\ loop iterator\n\n\t\ts\" set var=acpi\" evaluate menuset-unloadmenuvar\n\t\ts\" set var=init\" evaluate menuset-unloadmenuvar\n\t\ts\" set var=options\" evaluate menuset-unloadmenuvar\n\t\ts\" set var=optionstext\" evaluate menuset-unloadmenuvar\n\t\ts\" set var=reboot\" evaluate menuset-unloadmenuvar\n\n\t\t1+ dup 65535 > ( n -- n' 0|-1 ) \\ increment and test\n\tuntil\n\tdrop ( n' -- ) \\ loop iterator\n\n\ts\" buf\" unsetenv\n\tmenuset-cleanup\n;\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"f8ccf8585defc1927b2639559a18452ff4b69aa5","subject":"Unnecessary COMMA in compile","message":"Unnecessary COMMA in compile","repos":"rm-hull\/byok,rm-hull\/byok,rm-hull\/byok,rm-hull\/byok","old_file":"forth\/src\/forth\/system.fth","new_file":"forth\/src\/forth\/system.fth","new_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\ \n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: CELL 1 ;\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n \n: COUNT dup 1 + swap c@ ;\n\n\\ Miscellaneous support words\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: CELL+ ( n -- n+cell ) cell + ;\n: CELL- ( n -- n-cell ) cell - ;\n: CELL* ( n -- n*cell ) cells ;\n\n: CHAR+ ( n -- n+size_of_char ) 1+\n\\ : CHARS ( n -- n*size_of_char, don't do anything ) ; immediate\n\n\\ useful stack manipulation words\n: -ROT ( a b c -- c a b ) rot rot ;\n: 3DUP ( a b c -- a b c a b c ) 2 pick 2 pick 2 pick ;\n\n\\ ------------------------------------------------------------------\n: ID. ( nfa -- ) count 31 and type ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: PAD ( -- addr ) here 128 + ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ cell 1- ] literal +\n [ cell 1- invert ] literal and ;\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n\\ : ALLOT ( nbytes -- , allot space in dictionary ) dp +! ( align ) ;\n\\ : C, ( c -- ) here c! 1 chars dp +! ;\n\\ : W, ( w -- ) dp @ even-up dup dp ! w! 2 chars dp +! ;\n\\ : , ( n -- , lay into dictionary ) align here ! cell allot ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token ) \n [compile] literal ( compile a call to literal )\n ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n: :NONAME ( -- xt , begin compilation of headerless secondary ) align here ] ;\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick ) \n ?comp ' [compile] literal \n; immediate\n\n: RECURSE ( ? -- ? , call the word currently being defined ) \n latest compile, \n; immediate\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 ) swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 ) dup cell+ @ swap @ ;\n\n: \/STRING ( addr len n -- addr' len' ) over min rot over + -rot - ;\n: PLACE ( addr len to -- , move string ) 3dup 1+ swap cmove c! drop ;\n\n: ASCII ( -- char, state smart )\n bl parse drop c@\n state @\n IF [compile] literal\n THEN \n; immediate\n\n: CHAR ( -- char , interpret mode ) bl parse drop c@ ;\n: [CHAR] ( -- char , for compile mode )\n char [compile] literal \n; immediate\n\n: 'word ( -- addr ) here ;\n\n: (C\") ( -- $addr ) r> dup count + aligned >r ;\n: (S\") ( -- c-addr cnt ) r> count 2dup + aligned >r ;\n: (.\") ( -- , type following string ) r> count 2dup + aligned r> type ;\n: \", ( addr len -- , place string into dict ) tuck 'word place 1+ allot align ;\n: ,\" ( -- ) [char] \" parse \", ;\n\n: .( ( --, type string delimited by parens )\n [char] ) parse type\n; immediate\n\n: .\" ( -- , type string )\n state @\n IF compile (.\") ,\"\n ELSE [char] \" parse type\n THEN \n; immediate\n\n","old_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\ \n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: CELL 1 ;\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n \n: COUNT dup 1 + swap c@ ;\n\n\\ Miscellaneous support words\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: CELL+ ( n -- n+cell ) cell + ;\n: CELL- ( n -- n-cell ) cell - ;\n: CELL* ( n -- n*cell ) cells ;\n\n: CHAR+ ( n -- n+size_of_char ) 1+\n\\ : CHARS ( n -- n*size_of_char, don't do anything ) ; immediate\n\n\\ useful stack manipulation words\n: -ROT ( a b c -- c a b ) rot rot ;\n: 3DUP ( a b c -- a b c a b c ) 2 pick 2 pick 2 pick ;\n\n\\ ------------------------------------------------------------------\n: ID. ( nfa -- ) count 31 and type ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: PAD ( -- addr ) here 128 + ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ cell 1- ] literal +\n [ cell 1- invert ] literal and ;\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n\\ : ALLOT ( nbytes -- , allot space in dictionary ) dp +! ( align ) ;\n\\ : C, ( c -- ) here c! 1 chars dp +! ;\n\\ : W, ( w -- ) dp @ even-up dup dp ! w! 2 chars dp +! ;\n\\ : , ( n -- , lay into dictionary ) align here ! cell allot ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token ) \n [compile] literal ( compile a call to literal )\n , ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n: :NONAME ( -- xt , begin compilation of headerless secondary ) align here ] ;\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick ) \n ?comp ' [compile] literal \n; immediate\n\n: RECURSE ( ? -- ? , call the word currently being defined ) \n latest compile, \n; immediate\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 ) swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 ) dup cell+ @ swap @ ;\n\n: \/STRING ( addr len n -- addr' len' ) over min rot over + -rot - ;\n: PLACE ( addr len to -- , move string ) 3dup 1+ swap cmove c! drop ;\n\n: ASCII ( -- char, state smart )\n bl parse drop c@\n state @\n IF [compile] literal\n THEN \n; immediate\n\n: CHAR ( -- char , interpret mode ) bl parse drop c@ ;\n: [CHAR] ( -- char , for compile mode )\n char [compile] literal \n; immediate\n\n: 'word ( -- addr ) here ;\n\n: (C\") ( -- $addr ) r> dup count + aligned >r ;\n: (S\") ( -- c-addr cnt ) r> count 2dup + aligned >r ;\n: (.\") ( -- , type following string ) r> count 2dup + aligned r> type ;\n: \", ( addr len -- , place string into dict ) tuck 'word place 1+ allot align ;\n: ,\" ( -- ) [char] \" parse \", ;\n\n: .( ( --, type string delimited by parens )\n [char] ) parse type\n; immediate\n\n: .\" ( -- , type string )\n state @\n IF compile (.\") ,\"\n ELSE [char] \" parse type\n THEN \n; immediate\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"d5bd8aa6af23c144de86496d3bd1904a6d4b9569","subject":"Fixed bug in (.\") which pushed erroneously on the data stack","message":"Fixed bug in (.\") which pushed erroneously on the data stack","repos":"rm-hull\/byok,rm-hull\/byok,rm-hull\/byok,rm-hull\/byok","old_file":"forth\/src\/forth\/system.fth","new_file":"forth\/src\/forth\/system.fth","new_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\ \n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n \n: COUNT dup 1+ swap c@ ;\n\n\\ Miscellaneous support words\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: CELL+ ( n -- n+cell ) cell + ;\n: CELL- ( n -- n-cell ) cell - ;\n: CELL* ( n -- n*cell ) cells ;\n\n: CHAR+ ( n -- n+size_of_char ) 1+\n\\ : CHARS ( n -- n*size_of_char, don't do anything ) ; immediate\n\n\\ useful stack manipulation words\n: -ROT ( a b c -- c a b ) rot rot ;\n: 3DUP ( a b c -- a b c a b c ) 2 pick 2 pick 2 pick ;\n\n\\ ------------------------------------------------------------------\n: ID. ( nfa -- ) count 31 and type ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: PAD ( -- addr ) here 128 + ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: ? ( -- ) @ . ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ ' (lit) , cell 1- , ] +\n [ ' (lit) , cell 1- invert , ] and ;\n\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n: ALLOT ( nbytes -- , allot space in dictionary ) dp +! align ;\n\n: C, ( c -- ) here c! 1 dp +! ;\n\\ : W, ( w -- ) dp @ even-up dup dp ! w! 2 dp +! ;\n\\ : , ( n -- , lay into dictionary ) align here ! cell allot ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token ) \n [compile] literal ( compile a call to literal )\n ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n: :NONAME ( -- xt , begin compilation of headerless secondary ) align here ] ;\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick ) \n ?comp ' [compile] literal \n; immediate\n\n: RECURSE ( ? -- ? , call the word currently being defined ) \n latest compile, \n; immediate\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 ) swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 ) dup cell+ @ swap @ ;\n\n: \/STRING ( addr len n -- addr' len' ) over min rot over + -rot - ;\n: PLACE ( addr len to -- , move string ) 3dup 1+ swap cmove c! drop ;\n\n: ASCII ( -- char, state smart )\n bl parse drop c@\n state @ 1 =\n IF [compile] literal\n ELSE \n THEN \n; immediate\n\n: CHAR ( -- char , interpret mode ) bl parse drop c@ ;\n: [CHAR] ( -- char , for compile mode )\n char [compile] literal \n; immediate\n\n: 'word ( -- addr ) here ;\n\n: (C\") ( -- $addr ) r> dup count + aligned >r ;\n: (S\") ( -- c-addr cnt ) r> count 2dup + aligned >r ;\n: (.\") ( -- , type following string ) r> count 2dup + aligned >r type ;\n: \", ( addr len -- , place string into dict ) tuck 'word place 1+ allot align ;\n: ,\" ( -- ) 34 parse \", ;\n\n: .( ( --, type string delimited by parens )\n 41 parse type\n; immediate\n\n: .\" ( -- , type string )\n state @ 1 =\n IF compile (.\") ,\"\n ELSE 34 parse type\n THEN \n; immediate\n\n: SEE ( -- )\n ' dup\n 16 + @ \\ offset in execution token for alloc size\n cells swap >body\n disassemble ;\n","old_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\ \n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n \n: COUNT dup 1+ swap c@ ;\n\n\\ Miscellaneous support words\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: CELL+ ( n -- n+cell ) cell + ;\n: CELL- ( n -- n-cell ) cell - ;\n: CELL* ( n -- n*cell ) cells ;\n\n: CHAR+ ( n -- n+size_of_char ) 1+\n\\ : CHARS ( n -- n*size_of_char, don't do anything ) ; immediate\n\n\\ useful stack manipulation words\n: -ROT ( a b c -- c a b ) rot rot ;\n: 3DUP ( a b c -- a b c a b c ) 2 pick 2 pick 2 pick ;\n\n\\ ------------------------------------------------------------------\n: ID. ( nfa -- ) count 31 and type ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: PAD ( -- addr ) here 128 + ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: ? ( -- ) @ . ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ ' (lit) , cell 1- , ] +\n [ ' (lit) , cell 1- invert , ] and ;\n\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n: ALLOT ( nbytes -- , allot space in dictionary ) dp +! align ;\n\n: C, ( c -- ) here c! 1 dp +! ;\n\\ : W, ( w -- ) dp @ even-up dup dp ! w! 2 dp +! ;\n\\ : , ( n -- , lay into dictionary ) align here ! cell allot ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token ) \n [compile] literal ( compile a call to literal )\n ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n: :NONAME ( -- xt , begin compilation of headerless secondary ) align here ] ;\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick ) \n ?comp ' [compile] literal \n; immediate\n\n: RECURSE ( ? -- ? , call the word currently being defined ) \n latest compile, \n; immediate\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 ) swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 ) dup cell+ @ swap @ ;\n\n: \/STRING ( addr len n -- addr' len' ) over min rot over + -rot - ;\n: PLACE ( addr len to -- , move string ) 3dup 1+ swap cmove c! drop ;\n\n: ASCII ( -- char, state smart )\n bl parse drop c@\n state @ 1 =\n IF [compile] literal\n ELSE \n THEN \n; immediate\n\n: CHAR ( -- char , interpret mode ) bl parse drop c@ ;\n: [CHAR] ( -- char , for compile mode )\n char [compile] literal \n; immediate\n\n: 'word ( -- addr ) here ;\n\n: (C\") ( -- $addr ) r> dup count + aligned >r ;\n: (S\") ( -- c-addr cnt ) r> count 2dup + aligned >r ;\n: (.\") ( -- , type following string ) r> count 2dup + aligned r> type ;\n: \", ( addr len -- , place string into dict ) tuck 'word place 1+ allot align ;\n: ,\" ( -- ) 34 parse \", ;\n\n: .( ( --, type string delimited by parens )\n 41 parse type\n; immediate\n\n: .\" ( -- , type string )\n state @ 1 =\n IF compile (.\") ,\"\n ELSE 34 parse type\n THEN \n; immediate\n\n: SEE ( -- )\n ' dup\n 16 + @ \\ offset in execution token for alloc size\n cells swap >body\n disassemble ;\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"a852933bd855be8992c91652b70ec441b284ca33","subject":"Converted eforth.forth to lowercase","message":"Converted eforth.forth to lowercase\n\nThe vm needs forth source in lowercase. The original uppercase eforth.forth was converted to lowercase with:\r\n tr '[:upper:]' '[:lower:]' < eforth.forth.original > eforth.forth","repos":"tehologist\/forthkit","old_file":"eforth.forth","new_file":"eforth.forth","new_contents":": + um+ drop ; \n: cells dup + ; \n: cell+ 2 + ; \n: cell- -2 + ; \n: cell 2 ; \n: boot 0 cells ; \n: forth 4 cells ; \n: dpl 5 cells ; \n: sp0 6 cells ; \n: rp0 7 cells ; \n: '?key 8 cells ; \n: 'emit 9 cells ; \n: 'expect 10 cells ; \n: 'tap 11 cells ; \n: 'echo 12 cells ; \n: 'prompt 13 cells ; \n: base 14 cells ; \n: tmp 15 cells ; \n: span 16 cells ; \n: >in 17 cells ; \n: #tibb 18 cells ; \n: tibb 19 cells ; \n: csp 20 cells ; \n: 'eval 21 cells ; \n: 'number 22 cells ; \n: hld 23 cells ; \n: handler 24 cells ; \n: context 25 cells ; \n: current 27 cells ; \n: cp 29 cells ; \n: np 30 cells ; \n: last 31 cells ; \n: state 32 cells ; \n: spp 33 cells ; \n: rpp 34 cells ; \n: true -1 ; \n: false 0 ; \n: bl 32 ; \n: bs 8 ; \n: =immed 3 ; \n: =wordlist 2 ; \n: immediate =immed last @ cell- ! ; \n: here cp @ ; \n: allot cp @ + cp ! ; \n: , here cell allot ! ; \n: c, here 1 allot c! ; \n: +! swap over @ + swap ! ; \n: compile r> dup @ , cell+ >r ; \n: state? state @ ; \n: literal compile lit , ; immediate \n: [ false state ! ; immediate \n: ] true state ! ; immediate \n: if compile 0branch here 0 , ; immediate \n: then here swap ! ; immediate \n: for compile >r here ; immediate \n: next compile next , ; immediate \n: begin here ; immediate \n: again compile branch , ; immediate \n: until compile 0branch , ; immediate \n: ahead compile branch here 0 , ; immediate \n: repeat compile branch , here swap ! ; immediate \n: aft drop compile branch here 0 , here swap ; immediate \n: else compile branch here 0 , swap here swap ! ; immediate \n: while compile 0branch here 0 , swap ; immediate \n: execute >r ; \n: @execute @ dup if execute then ; \n: r@ r> r> dup >r swap >r ; \n: #tib #tibb @ ; \n: tib tibb @ ; \n: \\ #tib @ >in ! ; immediate \n: rot >r swap r> swap ; \n: -rot swap >r swap r> ; \n: nip swap drop ; \n: tuck swap over ; \n: 2>r swap r> swap >r swap >r >r ; \n: 2r> r> r> swap r> swap >r swap ; \n: 2r@ r> r> r@ swap >r swap r@ swap >r ; \n: 2drop drop drop ; \n: 2dup over over ; \n: 2swap rot >r rot r> ; \n: 2over >r >r 2dup r> r> 2swap ; \n: 2rot 2>r 2swap 2r> 2swap ; \n: -2rot 2rot 2rot ; \n: 2nip 2swap 2drop ; \n: 2tuck 2swap 2over ; \n: not dup nand ; \n: and nand not ; \n: or not swap not nand ; \n: nor or not ; \n: xor 2dup and -rot nor nor ; \n: xnor xor not ; \n: negate not 1 + ; \n: - negate + ; \n: 1+ 1 + ; \n: 1- 1 - ; \n: 2+ 2 + ; \n: 2- 2 - ; \n: d+ >r swap >r um+ r> r> + + ; \n: dnegate not >r not 1 um+ r> + ; \n: d- dnegate d+ ; \n: 2! swap over ! cell+ ! ; \n: 2@ dup cell+ @ swap @ ; \n: ?dup dup if dup then ; \n: s>d dup 0< ; \n: abs dup 0< if negate then ; \n: dabs dup 0< if dnegate then ; \n: u< 2dup xor 0< if swap drop 0< exit then - 0< ; \n: u> swap u< ; \n: = xor if false exit then true ; \n: < 2dup xor 0< if drop 0< exit then - 0< ; \n: > swap < ; \n: 0> negate 0< ; \n: 0<> if true exit then false ; \n: 0= 0 = ; \n: <> = 0= ; \n: d0< swap drop 0< ; \n: d0> dnegate d0< ; \n: d0= or 0= ; \n: d= d- d0= ; \n: d< rot 2dup xor if swap 2swap 2drop < ; \n: du< rot 2dup xor if swap 2swap then then 2drop u< ; \n: dmin 2over 2over 2swap d< if 2swap then 2drop ; \n: dmax 2over 2over d< if 2swap then 2drop ; \n: m+ s>d d+ ; \n: m- s>d d- ; \n: min 2dup swap < if swap then drop ; \n: max 2dup < if swap then drop ; \n: umin 2dup swap u< if swap then drop ; \n: umax 2dup u< if swap then drop ; \n: within over - >r - r> u< ; \n: um\/mod \n 2dup u< \n if negate \n 15 for \n >r dup um+ \n >r >r dup um+ \n r> + dup r> r@ swap \n >r um+ \n r> or \n if >r drop 1+ r> \n else drop \n then r> \n next drop swap exit \n then drop 2drop -1 dup ; \n: m\/mod \n dup 0< dup >r \n if negate >r \n dnegate r> \n then >r dup 0< \n if r@ + \n then r> um\/mod \n r> \n if swap negate swap then ; \n: \/mod over 0< swap m\/mod ; \n: mod \/mod drop ; \n: \/ \/mod nip ; \n: um* \n 0 swap \n 15 for \n dup um+ >r >r \n dup um+ \n r> + \n r> \n if >r over um+ \n r> + \n then \n next \n rot drop ; \n: * um* drop ; \n: m* \n 2dup xor 0< >r \n abs swap abs um* \n r> if dnegate then ; \n: *\/mod >r m* r> m\/mod ; \n: *\/ *\/mod swap drop ; \n: 2* 2 * ; \n: 2\/ 2 \/ ; \n: mu\/mod >r 0 r@ um\/mod r> swap >r um\/mod r> ; \n: d2* 2dup d+ ; \n: du2\/ 2 mu\/mod rot drop ; \n: d2\/ dup >r 1 and du2\/ r> 2\/ or ; \n: aligned dup 0 2 um\/mod drop dup if 2 swap - then + ; \n: parse \n tmp ! over >r dup \n if \n 1- tmp @ bl = \n if \n for bl over c@ - 0< not \n while 1+ \n next r> drop 0 dup exit \n then r> \n then \n over swap \n for tmp @ over c@ - tmp @ bl = \n if 0< then \n while 1+ \n next dup >r \n else r> drop dup 1+ >r \n then over - r> r> - exit \n then over r> - ; \n: parse >r tib >in @ + #tib c@ >in @ - r> parse >in +! ; \n: char bl parse drop c@ ; \n: tx! 1 putc ; \n: emit 'emit @execute ; \n: type for aft dup c@ emit 1+ then next drop ; \n: ?rx 0 getc ; \n: ?key '?key @execute ; \n: key begin ?key until ; \n: count dup 1+ swap c@ ; \n: cmove \n for \n aft \n >r dup c@ r@ c! 1+ r> 1+ \n then \n next 2drop ; \n: fill \n swap \n for swap \n aft 2dup c! 1+ then \n next 2drop ; \n: -trailing \n for \n aft \n bl over r@ + c@ < \n if \n r> 1+ exit \n then \n then \n next 0 ; \n: pack$ \n dup >r \n 2dup c! 1+ 2dup + 0 swap ! swap cmove \n r> ; \n: word parse here pack$ ; \n: token bl parse 31 min np @ over - 1- pack$ ; \n: link> 3 cells - ; \n: code> 2 cells - ; \n: type> 1 cells - ; \n: data> cell+ ; \n: same? \n for aft \n over r@ cells + @ \n over r@ cells + @ \n - ?dup \n if r> drop exit then \n then \n next 0 ; \n: find \n @ begin dup while \n 2dup c@ swap c@ = if \n 2dup 1+ swap count aligned cell \/ >r swap r> \n same? 0= if \n 2drop swap drop dup code> @ swap -1 exit \n then 2drop then \n link> @ repeat ; \n: ' token context @ find if drop else swap drop 0 then ; \n: ! ! ; \n' tx! 'emit ! \n' ?rx '?key ! \n: ['] compile ' ; immediate \n: postpone ' , ; immediate \n: [char] char postpone literal ; immediate \n: ( [char] ) parse 2drop ; immediate \n: :noname here postpone ] ; \n: overt last @ current @ ! ; \n: $,n \n dup last ! cell- \n dup =wordlist \n swap ! \n cell- dup here \n swap ! \n cell- dup current @ @ \n swap ! \n cell- np ! ; \n: : token $,n postpone ] ; \n: ; compile exit postpone [ overt ; immediate \n: recurse last @ code> @ , ; immediate \n: dovar r> ; \n: create token $,n compile dovar overt ; \n: does last @ code> @ r> swap ! ; \n: does> compile does compile r> ; immediate \n: constant create , does> @ ; \n: variable create 0 , ; \n: 2literal swap postpone literal \n postpone literal ; immediate \n: 2constant create , , does> 2@ ; \n: 2variable create 2 cells allot ; \n: space bl emit ; \n: spaces 0 max for space next ; \n: pad here 80 + ; \n: decimal 10 base ! ; \n: hex 16 base ! ; \n: binary 2 base ! ; \n: octal 8 base ! ; \ndecimal \n: char- 1- ; \n: char+ 1+ ; \n: chars ; \n: >char 127 and dup 127 bl within if drop 95 then ; \n: digit 9 over < 7 and + [char] 0 + ; \n: <# pad hld ! ; \n: hold hld @ char- dup hld ! c! ; \n: # 0 base @ um\/mod >r base @ um\/mod swap digit hold r> ; \n: #s begin # 2dup or 0= until ; \n: sign 0< if [char] - hold then ; \n: #> 2drop hld @ pad over - ; \n: s.r over - spaces type ; \n: d.r >r dup >r dabs <# #s r> sign #> r> s.r ; \n: u.r 0 swap d.r ; \n: .r >r s>d r> d.r ; \n: d. 0 d.r space ; \n: u. 0 d. ; \n: . base @ 10 xor if u. exit then s>d d. ; \n: ? @ . ; \n: du.r >r <# #s #> r> s.r ; \n: du. du.r space ; \n: do$ r> r@ r> count + aligned >r swap >r ; \n: .\"| do$ count type ; \n: $,\" [char] \" word count + aligned cp ! ; \n: .\" compile .\"| $,\" ; immediate \n: .( [char] ) parse type ; immediate \n: $\"| do$ ; \n: $\" compile $\"| $,\" ; immediate \n: s\" [char] \" parse here pack$ ; \n: cr 10 emit ; \n: tap over c! 1+ ; \n: ktap \n 10 xor \n if \n bl tap exit \n then \n nip dup ; \n: accept \n over + over \n begin \n 2dup xor \n while \n key \n dup bl - 95 u< \n if tap else ktap then \n repeat drop over - ; \n: expect accept span ! drop ; \n: query tib 80 accept #tib c! drop 0 >in ! ; \n: digit? \n >r [char] 0 - \n 9 over < \n if 7 - dup 10 < or then \n dup r> u< ; \n: \/string dup >r - swap r> + swap ; \n: >number \n begin dup \n while >r dup >r c@ base @ digit? \n while swap base @ um* drop rot \n base @ um* d+ r> char+ r> 1 - \n repeat drop r> r> then ; \n: number? \n over c@ [char] - = dup >r if 1 \/string then \n >r >r 0 dup r> r> -1 dpl ! \n begin >number dup \n while over c@ [char] . xor \n if rot drop rot r> 2drop false exit \n then 1 - dpl ! char+ dpl @ \n repeat 2drop r> if dnegate then true ; \n' number? 'number ! \n: $interpret \n context @ find \n if drop execute exit then \n count 'number @execute if \n dpl @ 0< if drop then exit then .\" ?\" type ; \n: $compile \n context @ find \n if cell- @ =immed = \n if execute else , then exit \n then count 'number @execute \n if \n dpl @ 0< \n if drop postpone literal \n else postpone 2literal \n then exit \n then .\" ?\" type ; \n: eval state? if $compile else $interpret then ; \n' eval 'eval ! \n: eval \n begin token dup c@ while \n 'eval @execute \n repeat drop ; \n: ok cr .\" ok.\" space ; \n' ok 'prompt ! \n: quit \n begin 'prompt @execute query \n eval again ; \n: bye .\" good bye \" cr halt ; \n' quit boot ! \n: sp@ spp @ ; \n: depth sp@ sp0 @ - cell \/ ; \n: pick cells sp@ swap - 2 cells - @ ; \n: .s cr depth for aft r@ pick . then next space .\" \n @ space repeat drop cr ; \n\nvariable file \n: open f_open file ! ; \n: close file @ f_close ; \n: fput file @ putc ; \n: fget file @ getc ; \n: fputs count for aft dup c@ fput 1+ then next drop ; \n\n: savevm $\" eforth.img\" $\" wb\" open 0 \n 16384 for aft dup c@ fput 1+ then next close drop ; \n\nsavevm \n","old_contents":": + UM+ DROP ; \n: CELLS DUP + ; \n: CELL+ 2 + ; \n: CELL- -2 + ; \n: CELL 2 ; \n: BOOT 0 CELLS ; \n: FORTH 4 CELLS ; \n: DPL 5 CELLS ; \n: SP0 6 CELLS ; \n: RP0 7 CELLS ; \n: '?KEY 8 CELLS ; \n: 'EMIT 9 CELLS ; \n: 'EXPECT 10 CELLS ; \n: 'TAP 11 CELLS ; \n: 'ECHO 12 CELLS ; \n: 'PROMPT 13 CELLS ; \n: BASE 14 CELLS ; \n: tmp 15 CELLS ; \n: SPAN 16 CELLS ; \n: >IN 17 CELLS ; \n: #TIBB 18 CELLS ; \n: TIBB 19 CELLS ; \n: CSP 20 CELLS ; \n: 'EVAL 21 CELLS ; \n: 'NUMBER 22 CELLS ; \n: HLD 23 CELLS ; \n: HANDLER 24 CELLS ; \n: CONTEXT 25 CELLS ; \n: CURRENT 27 CELLS ; \n: CP 29 CELLS ; \n: NP 30 CELLS ; \n: LAST 31 CELLS ; \n: STATE 32 CELLS ; \n: SPP 33 CELLS ; \n: RPP 34 CELLS ; \n: TRUE -1 ; \n: FALSE 0 ; \n: BL 32 ; \n: BS 8 ; \n: =IMMED 3 ; \n: =WORDLIST 2 ; \n: IMMEDIATE =IMMED LAST @ CELL- ! ; \n: HERE CP @ ; \n: ALLOT CP @ + CP ! ; \n: , HERE CELL ALLOT ! ; \n: C, HERE 1 ALLOT C! ; \n: +! SWAP OVER @ + SWAP ! ; \n: COMPILE R> DUP @ , CELL+ >R ; \n: STATE? STATE @ ; \n: LITERAL COMPILE LIT , ; IMMEDIATE \n: [ FALSE STATE ! ; IMMEDIATE \n: ] TRUE STATE ! ; IMMEDIATE \n: IF COMPILE 0BRANCH HERE 0 , ; IMMEDIATE \n: THEN HERE SWAP ! ; IMMEDIATE \n: FOR COMPILE >R HERE ; IMMEDIATE \n: NEXT COMPILE next , ; IMMEDIATE \n: BEGIN HERE ; IMMEDIATE \n: AGAIN COMPILE BRANCH , ; IMMEDIATE \n: UNTIL COMPILE 0BRANCH , ; IMMEDIATE \n: AHEAD COMPILE BRANCH HERE 0 , ; IMMEDIATE \n: REPEAT COMPILE BRANCH , HERE SWAP ! ; IMMEDIATE \n: AFT DROP COMPILE BRANCH HERE 0 , HERE SWAP ; IMMEDIATE \n: ELSE COMPILE BRANCH HERE 0 , SWAP HERE SWAP ! ; IMMEDIATE \n: WHILE COMPILE 0BRANCH HERE 0 , SWAP ; IMMEDIATE \n: EXECUTE >R ; \n: @EXECUTE @ DUP IF EXECUTE THEN ; \n: R@ R> R> DUP >R SWAP >R ; \n: #TIB #TIBB @ ; \n: TIB TIBB @ ; \n: \\ #TIB @ >IN ! ; IMMEDIATE \n: ROT >R SWAP R> SWAP ; \n: -ROT SWAP >R SWAP R> ; \n: NIP SWAP DROP ; \n: TUCK SWAP OVER ; \n: 2>R SWAP R> SWAP >R SWAP >R >R ; \n: 2R> R> R> SWAP R> SWAP >R SWAP ; \n: 2R@ R> R> R@ SWAP >R SWAP R@ SWAP >R ; \n: 2DROP DROP DROP ; \n: 2DUP OVER OVER ; \n: 2SWAP ROT >R ROT R> ; \n: 2OVER >R >R 2DUP R> R> 2SWAP ; \n: 2ROT 2>R 2SWAP 2R> 2SWAP ; \n: -2ROT 2ROT 2ROT ; \n: 2NIP 2SWAP 2DROP ; \n: 2TUCK 2SWAP 2OVER ; \n: NOT DUP NAND ; \n: AND NAND NOT ; \n: OR NOT SWAP NOT NAND ; \n: NOR OR NOT ; \n: XOR 2DUP AND -ROT NOR NOR ; \n: XNOR XOR NOT ; \n: NEGATE NOT 1 + ; \n: - NEGATE + ; \n: 1+ 1 + ; \n: 1- 1 - ; \n: 2+ 2 + ; \n: 2- 2 - ; \n: D+ >R SWAP >R UM+ R> R> + + ; \n: DNEGATE NOT >R NOT 1 UM+ R> + ; \n: D- DNEGATE D+ ; \n: 2! SWAP OVER ! CELL+ ! ; \n: 2@ DUP CELL+ @ SWAP @ ; \n: ?DUP DUP IF DUP THEN ; \n: S>D DUP 0< ; \n: ABS DUP 0< IF NEGATE THEN ; \n: DABS DUP 0< IF DNEGATE THEN ; \n: U< 2DUP XOR 0< IF SWAP DROP 0< EXIT THEN - 0< ; \n: U> SWAP U< ; \n: = XOR IF FALSE EXIT THEN TRUE ; \n: < 2DUP XOR 0< IF DROP 0< EXIT THEN - 0< ; \n: > SWAP < ; \n: 0> NEGATE 0< ; \n: 0<> IF TRUE EXIT THEN FALSE ; \n: 0= 0 = ; \n: <> = 0= ; \n: D0< SWAP DROP 0< ; \n: D0> DNEGATE D0< ; \n: D0= OR 0= ; \n: D= D- D0= ; \n: D< ROT 2DUP XOR IF SWAP 2SWAP 2DROP < ; \n: DU< ROT 2DUP XOR IF SWAP 2SWAP THEN THEN 2DROP U< ; \n: DMIN 2OVER 2OVER 2SWAP D< IF 2SWAP THEN 2DROP ; \n: DMAX 2OVER 2OVER D< IF 2SWAP THEN 2DROP ; \n: M+ S>D D+ ; \n: M- S>D D- ; \n: MIN 2DUP SWAP < IF SWAP THEN DROP ; \n: MAX 2DUP < IF SWAP THEN DROP ; \n: UMIN 2DUP SWAP U< IF SWAP THEN DROP ; \n: UMAX 2DUP U< IF SWAP THEN DROP ; \n: WITHIN OVER - >R - R> U< ; \n: UM\/MOD \n 2DUP U< \n IF NEGATE \n 15 FOR \n >R DUP UM+ \n >R >R DUP UM+ \n R> + DUP R> R@ SWAP \n >R UM+ \n R> OR \n IF >R DROP 1+ R> \n ELSE DROP \n THEN R> \n NEXT DROP SWAP EXIT \n THEN DROP 2DROP -1 DUP ; \n: M\/MOD \n DUP 0< DUP >R \n IF NEGATE >R \n DNEGATE R> \n THEN >R DUP 0< \n IF R@ + \n THEN R> UM\/MOD \n R> \n IF SWAP NEGATE SWAP THEN ; \n: \/MOD OVER 0< SWAP M\/MOD ; \n: MOD \/MOD DROP ; \n: \/ \/MOD NIP ; \n: UM* \n 0 SWAP \n 15 FOR \n DUP UM+ >R >R \n DUP UM+ \n R> + \n R> \n IF >R OVER UM+ \n R> + \n THEN \n NEXT \n ROT DROP ; \n: * UM* DROP ; \n: M* \n 2DUP XOR 0< >R \n ABS SWAP ABS UM* \n R> IF DNEGATE THEN ; \n: *\/MOD >R M* R> M\/MOD ; \n: *\/ *\/MOD SWAP DROP ; \n: 2* 2 * ; \n: 2\/ 2 \/ ; \n: MU\/MOD >R 0 R@ UM\/MOD R> SWAP >R UM\/MOD R> ; \n: D2* 2DUP D+ ; \n: DU2\/ 2 MU\/MOD ROT DROP ; \n: D2\/ DUP >R 1 AND DU2\/ R> 2\/ OR ; \n: ALIGNED DUP 0 2 UM\/MOD DROP DUP IF 2 SWAP - THEN + ; \n: parse \n tmp ! OVER >R DUP \n IF \n 1- tmp @ BL = \n IF \n FOR BL OVER C@ - 0< NOT \n WHILE 1+ \n NEXT R> DROP 0 DUP EXIT \n THEN R> \n THEN \n OVER SWAP \n FOR tmp @ OVER C@ - tmp @ BL = \n IF 0< THEN \n WHILE 1+ \n NEXT DUP >R \n ELSE R> DROP DUP 1+ >R \n THEN OVER - R> R> - EXIT \n THEN OVER R> - ; \n: PARSE >R TIB >IN @ + #TIB C@ >IN @ - R> parse >IN +! ; \n: CHAR BL PARSE DROP C@ ; \n: TX! 1 PUTC ; \n: EMIT 'EMIT @EXECUTE ; \n: TYPE FOR AFT DUP C@ EMIT 1+ THEN NEXT DROP ; \n: ?RX 0 GETC ; \n: ?KEY '?KEY @EXECUTE ; \n: KEY BEGIN ?KEY UNTIL ; \n: COUNT DUP 1+ SWAP C@ ; \n: CMOVE \n FOR \n AFT \n >R DUP C@ R@ C! 1+ R> 1+ \n THEN \n NEXT 2DROP ; \n: FILL \n SWAP \n FOR SWAP \n AFT 2DUP C! 1+ THEN \n NEXT 2DROP ; \n: -TRAILING \n FOR \n AFT \n BL OVER R@ + C@ < \n IF \n R> 1+ EXIT \n THEN \n THEN \n NEXT 0 ; \n: PACK$ \n DUP >R \n 2DUP C! 1+ 2DUP + 0 SWAP ! SWAP CMOVE \n R> ; \n: WORD PARSE HERE PACK$ ; \n: TOKEN BL PARSE 31 MIN NP @ OVER - 1- PACK$ ; \n: LINK> 3 CELLS - ; \n: CODE> 2 CELLS - ; \n: TYPE> 1 CELLS - ; \n: DATA> CELL+ ; \n: SAME? \n FOR AFT \n OVER R@ CELLS + @ \n OVER R@ CELLS + @ \n - ?DUP \n IF R> DROP EXIT THEN \n THEN \n NEXT 0 ; \n: find \n @ BEGIN DUP WHILE \n 2DUP C@ SWAP C@ = IF \n 2DUP 1+ SWAP COUNT ALIGNED CELL \/ >R SWAP R> \n SAME? 0= IF \n 2DROP SWAP DROP DUP CODE> @ SWAP -1 EXIT \n THEN 2DROP THEN \n LINK> @ REPEAT ; \n: ' TOKEN CONTEXT @ find IF DROP ELSE SWAP DROP 0 THEN ; \n: ! ! ; \n' TX! 'EMIT ! \n' ?RX '?KEY ! \n: ['] COMPILE ' ; IMMEDIATE \n: POSTPONE ' , ; IMMEDIATE \n: [CHAR] CHAR POSTPONE LITERAL ; IMMEDIATE \n: ( [CHAR] ) PARSE 2DROP ; IMMEDIATE \n: :NONAME HERE POSTPONE ] ; \n: OVERT LAST @ CURRENT @ ! ; \n: $,n \n DUP LAST ! CELL- \n DUP =WORDLIST \n SWAP ! \n CELL- DUP HERE \n SWAP ! \n CELL- DUP CURRENT @ @ \n SWAP ! \n CELL- NP ! ; \n: : TOKEN $,n POSTPONE ] ; \n: ; COMPILE EXIT POSTPONE [ OVERT ; IMMEDIATE \n: RECURSE LAST @ code> @ , ; IMMEDIATE \n: doVAR R> ; \n: CREATE TOKEN $,n COMPILE doVAR OVERT ; \n: DOES LAST @ CODE> @ R> SWAP ! ; \n: DOES> COMPILE DOES COMPILE R> ; IMMEDIATE \n: CONSTANT CREATE , DOES> @ ; \n: VARIABLE CREATE 0 , ; \n: 2LITERAL SWAP POSTPONE LITERAL \n POSTPONE LITERAL ; IMMEDIATE \n: 2CONSTANT CREATE , , DOES> 2@ ; \n: 2VARIABLE CREATE 2 CELLS ALLOT ; \n: SPACE BL EMIT ; \n: SPACES 0 MAX FOR SPACE NEXT ; \n: PAD HERE 80 + ; \n: DECIMAL 10 BASE ! ; \n: HEX 16 BASE ! ; \n: BINARY 2 BASE ! ; \n: OCTAL 8 BASE ! ; \nDECIMAL \n: CHAR- 1- ; \n: CHAR+ 1+ ; \n: CHARS ; \n: >CHAR 127 AND DUP 127 BL WITHIN IF DROP 95 THEN ; \n: DIGIT 9 OVER < 7 AND + [CHAR] 0 + ; \n: <# PAD HLD ! ; \n: HOLD HLD @ CHAR- DUP HLD ! C! ; \n: # 0 BASE @ UM\/MOD >R BASE @ UM\/MOD SWAP DIGIT HOLD R> ; \n: #S BEGIN # 2DUP OR 0= UNTIL ; \n: SIGN 0< IF [CHAR] - HOLD THEN ; \n: #> 2DROP HLD @ PAD OVER - ; \n: S.R OVER - SPACES TYPE ; \n: D.R >R DUP >R DABS <# #S R> SIGN #> R> S.R ; \n: U.R 0 SWAP D.R ; \n: .R >R S>D R> D.R ; \n: D. 0 D.R SPACE ; \n: U. 0 D. ; \n: . BASE @ 10 XOR IF U. EXIT THEN S>D D. ; \n: ? @ . ; \n: DU.R >R <# #S #> R> S.R ; \n: DU. DU.R SPACE ; \n: do$ R> R@ R> COUNT + ALIGNED >R SWAP >R ; \n: .\"| do$ COUNT TYPE ; \n: $,\" [CHAR] \" WORD COUNT + ALIGNED CP ! ; \n: .\" COMPILE .\"| $,\" ; IMMEDIATE \n: .( [CHAR] ) PARSE TYPE ; IMMEDIATE \n: $\"| do$ ; \n: $\" COMPILE $\"| $,\" ; IMMEDIATE \n: s\" [CHAR] \" PARSE HERE PACK$ ; \n: CR 10 EMIT ; \n: TAP OVER C! 1+ ; \n: KTAP \n 10 XOR \n IF \n BL TAP EXIT \n THEN \n NIP DUP ; \n: ACCEPT \n OVER + OVER \n BEGIN \n 2DUP XOR \n WHILE \n KEY \n DUP BL - 95 U< \n IF TAP ELSE KTAP THEN \n REPEAT DROP OVER - ; \n: EXPECT ACCEPT SPAN ! DROP ; \n: QUERY TIB 80 ACCEPT #TIB C! DROP 0 >IN ! ; \n: DIGIT? \n >R [CHAR] 0 - \n 9 OVER < \n IF 7 - DUP 10 < OR THEN \n DUP R> U< ; \n: \/STRING DUP >R - SWAP R> + SWAP ; \n: >NUMBER \n BEGIN DUP \n WHILE >R DUP >R C@ BASE @ DIGIT? \n WHILE SWAP BASE @ UM* DROP ROT \n BASE @ UM* D+ R> CHAR+ R> 1 - \n REPEAT DROP R> R> THEN ; \n: NUMBER? \n OVER C@ [CHAR] - = DUP >R IF 1 \/STRING THEN \n >R >R 0 DUP R> R> -1 DPL ! \n BEGIN >NUMBER DUP \n WHILE OVER C@ [CHAR] . XOR \n IF ROT DROP ROT R> 2DROP FALSE EXIT \n THEN 1 - DPL ! CHAR+ DPL @ \n REPEAT 2DROP R> IF DNEGATE THEN TRUE ; \n' NUMBER? 'NUMBER ! \n: $INTERPRET \n CONTEXT @ find \n IF DROP EXECUTE EXIT THEN \n COUNT 'NUMBER @EXECUTE IF \n DPL @ 0< IF DROP THEN EXIT THEN .\" ?\" TYPE ; \n: $COMPILE \n CONTEXT @ find \n IF CELL- @ =IMMED = \n IF EXECUTE ELSE , THEN EXIT \n THEN COUNT 'NUMBER @EXECUTE \n IF \n DPL @ 0< \n IF DROP POSTPONE LITERAL \n ELSE POSTPONE 2LITERAL \n THEN EXIT \n THEN .\" ?\" TYPE ; \n: eval STATE? IF $COMPILE ELSE $INTERPRET THEN ; \n' eval 'EVAL ! \n: EVAL \n BEGIN TOKEN DUP C@ WHILE \n 'EVAL @EXECUTE \n REPEAT DROP ; \n: OK CR .\" OK.\" SPACE ; \n' OK 'PROMPT ! \n: QUIT \n BEGIN 'PROMPT @EXECUTE QUERY \n EVAL AGAIN ; \n: BYE .\" Good Bye \" CR HALT ; \n' QUIT BOOT ! \n: SP@ SPP @ ; \n: DEPTH SP@ SP0 @ - CELL \/ ; \n: PICK CELLS SP@ SWAP - 2 CELLS - @ ; \n: .S CR DEPTH FOR AFT R@ PICK . THEN NEXT SPACE .\" \n @ SPACE REPEAT DROP CR ; \n\nVARIABLE FILE \n: OPEN F_OPEN FILE ! ; \n: CLOSE FILE @ F_CLOSE ; \n: FPUT FILE @ PUTC ; \n: FGET FILE @ GETC ; \n: FPUTS COUNT FOR AFT DUP C@ FPUT 1+ THEN NEXT DROP ; \n\n: SAVEVM $\" eforth.img\" $\" wb\" OPEN 0 \n 16384 FOR AFT DUP C@ FPUT 1+ THEN NEXT CLOSE DROP ; \n\nSAVEVM \n\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"74ee4557d3dd09ef4f885588546aa8bc3c0aca30","subject":"Disable the APIC when selecting the 'Safe Mode' option of the loader. This will disable both APIC interrupt routing and SMP.","message":"Disable the APIC when selecting the 'Safe Mode' option of the loader. This\nwill disable both APIC interrupt routing and SMP.\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/beastie.4th","new_file":"sys\/boot\/forth\/beastie.4th","new_contents":"\\ Copyright (c) 2003 Scott Long \n\\ Copyright (c) 2003 Aleksander Fafula \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\nmarker task-beastie.4th\n\ninclude \/boot\/screen.4th\ninclude \/boot\/frames.4th\n\nhide\n\nvariable menuidx\nvariable menubllt\nvariable menuX\nvariable menuY\nvariable promptwidth\n\nvariable bootkey\nvariable bootacpikey\nvariable bootsafekey\nvariable bootverbosekey\nvariable bootsinglekey\nvariable escapekey\nvariable rebootkey\n\n46 constant dot\n\n\\ The BSD Daemon. He is 19 rows high and 34 columns wide\n: technicolor-beastie ( x y -- )\n2dup at-xy .\" \u001b[1;31m, ,\" 1+\n2dup at-xy .\" \/( )`\" 1+\n2dup at-xy .\" \\ \\___ \/ |\" 1+\n2dup at-xy .\" \/- \u001b[37m_\u001b[31m `-\/ '\" 1+\n2dup at-xy .\" (\u001b[37m\/\\\/ \\\u001b[31m \\ \/\\\" 1+\n2dup at-xy .\" \u001b[37m\/ \/ |\u001b[31m ` \\\" 1+\n2dup at-xy .\" \u001b[34mO O \u001b[37m) \u001b[31m\/ |\" 1+\n2dup at-xy .\" \u001b[37m`-^--'\u001b[31m`< '\" 1+\n2dup at-xy .\" (_.) _ ) \/\" 1+\n2dup at-xy .\" `.___\/` \/ \" 1+\n2dup at-xy .\" `-----' \/\" 1+\n2dup at-xy .\" \u001b[33m<----.\u001b[31m __ \/ __ \\\" 1+\n2dup at-xy .\" \u001b[33m<----|====\u001b[31mO)))\u001b[33m==\u001b[31m) \\) \/\u001b[33m====|\" 1+\n2dup at-xy .\" \u001b[33m<----'\u001b[31m `--' `.__,' \\\" 1+\n2dup at-xy .\" | |\" 1+\n2dup at-xy .\" \\ \/ \/\\\" 1+\n2dup at-xy .\" \u001b[36m______\u001b[31m( (_ \/ \\______\/\" 1+\n2dup at-xy .\" \u001b[36m,' ,-----' |\" 1+\nat-xy .\" `--{__________) \u001b[0m\" 1+\n;\n\n: boring-beastie ( x y -- )\n\t2dup at-xy .\" , ,\" 1+\n\t2dup at-xy .\" \/( )`\" 1+\n\t2dup at-xy .\" \\ \\___ \/ |\" 1+\n\t2dup at-xy .\" \/- _ `-\/ '\" 1+\n\t2dup at-xy .\" (\/\\\/ \\ \\ \/\\\" 1+\n\t2dup at-xy .\" \/ \/ | ` \\\" 1+\n\t2dup at-xy .\" O O ) \/ |\" 1+\n\t2dup at-xy .\" `-^--'`< '\" 1+\n\t2dup at-xy .\" (_.) _ ) \/\" 1+\n\t2dup at-xy .\" `.___\/` \/\" 1+\n\t2dup at-xy .\" `-----' \/\" 1+\n\t2dup at-xy .\" <----. __ \/ __ \\\" 1+\n\t2dup at-xy .\" <----|====O)))==) \\) \/====\" 1+\n\t2dup at-xy .\" <----' `--' `.__,' \\\" 1+\n\t2dup at-xy .\" | |\" 1+\n\t2dup at-xy .\" \\ \/ \/\\\" 1+\n\t2dup at-xy .\" ______( (_ \/ \\______\/\" 1+\n\t2dup at-xy .\" ,' ,-----' |\" 1+\n\t at-xy .\" `--{__________)\"\n;\n\n: print-beastie ( x y -- )\n\ts\" loader_color\" getenv\n\tdup -1 = if\n\t\tdrop\n\t\tboring-beastie\n\t\texit\n\tthen\n\ts\" YES\" compare-insensitive 0<> if\n\t\tboring-beastie\n\t\texit\n\tthen\n\ttechnicolor-beastie\n;\n\n: acpienabled? ( -- flag )\n\ts\" acpi_load\" getenv\n\tdup -1 = if\n\t\tdrop false exit\n\tthen\n\ts\" YES\" compare-insensitive 0<> if\n\t\tfalse exit\n\tthen\n\ts\" hint.acpi.0.disabled\" getenv\n\tdup -1 <> if\n\t\ts\" 0\" compare 0<> if\n\t\t\tfalse exit\n\t\tthen\n\tthen\n\ttrue\n;\n\n: printmenuitem ( -- n )\n\tmenuidx @\n\t1+ dup\n\tmenuidx !\n\tmenuY @ + dup menuX @ swap at-xy\n\tmenuidx @ .\n\tmenuX @ 1+ swap at-xy\n\tmenubllt @ emit\n\tmenuidx @ 48 +\n;\n\n: beastie-menu ( -- )\n\t0 menuidx !\n\tdot menubllt !\n\t8 menuY !\n\t5 menuX !\n\tclear\n\t46 4 print-beastie\n\t42 20 2 2 box\n\t13 6 at-xy .\" Welcome to FreeBSD!\"\n\tprintmenuitem .\" Boot FreeBSD [default]\" bootkey !\n\ts\" arch-i386\" environment? if\n\t\tprintmenuitem .\" Boot FreeBSD with ACPI \" bootacpikey !\n\t\tacpienabled? if\n\t\t\t.\" disabled\"\n\t\telse\n\t\t\t.\" enabled\"\n\t\tthen\n\telse\n\t\t-2 bootacpikey !\n\tthen\n\tprintmenuitem .\" Boot FreeBSD in Safe Mode\" bootsafekey !\n\tprintmenuitem .\" Boot FreeBSD in single user mode\" bootsinglekey !\n\tprintmenuitem .\" Boot FreeBSD with verbose logging\" bootverbosekey !\n\tprintmenuitem .\" Escape to loader prompt\" escapekey !\n\tprintmenuitem .\" Reboot\" rebootkey !\n\tmenuX @ 20 at-xy\n\t.\" Select option, [Enter] for default\"\n\tmenuX @ 21 at-xy\n\ts\" or [Space] to pause timer \" dup 2 - promptwidth !\n\ttype\n;\n\n: tkey\n\tdup\n\tseconds +\n\tbegin 1 while\n\t\tover 0<> if\n\t\t\tdup seconds u< if\n\t\t\t\tdrop\n\t\t\t\t-1\n\t\t\t\texit\n\t\t\tthen\n\t\t\tmenuX @ promptwidth @ + 21 at-xy dup seconds - .\n\t\tthen\n\t\tkey? if\n\t\t\tdrop\n\t\t\tkey\n\t\t\texit\n\t\tthen\n\t50 ms\n\trepeat\n;\n\nset-current\n\n: beastie-start\n\ts\" beastie_disable\" getenv\n\tdup -1 <> if\n\t\ts\" YES\" compare-insensitive 0= if\n\t\t\texit\n\t\tthen\n\tthen\n\tbeastie-menu\n\ts\" autoboot_delay\" getenv\n\tdup -1 = if\n\t\tdrop\n\t\t10\n\telse\n\t\t0 0 2swap >number drop drop drop\n\tthen\n\tbegin true while\n\t\tdup tkey\n\t\t0 25 at-xy\n\t\tdup 32 = if nip 0 swap then\n\t\tdup -1 = if 0 boot then\n\t\tdup 13 = if 0 boot then\n\t\tdup bootkey @ = if 0 boot then\n\t\tdup bootacpikey @ = if\n\t\t\tacpienabled? if\n\t\t\t\ts\" acpi_load\" unsetenv\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\telse\n\t\t\t\ts\" YES\" s\" acpi_load\" setenv\n\t\t\t\ts\" 0\" s\" hint.acpi.0.disabled\" setenv\n\t\t\tthen\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootsafekey @ = if\n\t\t\ts\" arch-i386\" environment? if\n\t\t\t\ts\" acpi_load\" unsetenv\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\t\ts\" 1\" s\" hint.apic.0.disabled\" setenv\n\t\t\tthen\n\t\t\ts\" 0\" s\" hw.ata.ata_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.atapi_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.wc\" setenv\n\t\t\ts\" 0\" s\" hw.eisa_slots\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootverbosekey @ = if\n\t\t\ts\" YES\" s\" boot_verbose\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootsinglekey @ = if\n\t\t\ts\" YES\" s\" boot_single\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup escapekey @ = if\n\t\t\t2drop\n\t\t\ts\" NO\" s\" autoboot_delay\" setenv\n\t\t\texit\n\t\tthen\n\t\trebootkey @ = if 0 reboot then\n\trepeat\n;\n\nprevious\n","old_contents":"\\ Copyright (c) 2003 Scott Long \n\\ Copyright (c) 2003 Aleksander Fafula \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\nmarker task-beastie.4th\n\ninclude \/boot\/screen.4th\ninclude \/boot\/frames.4th\n\nhide\n\nvariable menuidx\nvariable menubllt\nvariable menuX\nvariable menuY\nvariable promptwidth\n\nvariable bootkey\nvariable bootacpikey\nvariable bootsafekey\nvariable bootverbosekey\nvariable bootsinglekey\nvariable escapekey\nvariable rebootkey\n\n46 constant dot\n\n\\ The BSD Daemon. He is 19 rows high and 34 columns wide\n: technicolor-beastie ( x y -- )\n2dup at-xy .\" \u001b[1;31m, ,\" 1+\n2dup at-xy .\" \/( )`\" 1+\n2dup at-xy .\" \\ \\___ \/ |\" 1+\n2dup at-xy .\" \/- \u001b[37m_\u001b[31m `-\/ '\" 1+\n2dup at-xy .\" (\u001b[37m\/\\\/ \\\u001b[31m \\ \/\\\" 1+\n2dup at-xy .\" \u001b[37m\/ \/ |\u001b[31m ` \\\" 1+\n2dup at-xy .\" \u001b[34mO O \u001b[37m) \u001b[31m\/ |\" 1+\n2dup at-xy .\" \u001b[37m`-^--'\u001b[31m`< '\" 1+\n2dup at-xy .\" (_.) _ ) \/\" 1+\n2dup at-xy .\" `.___\/` \/ \" 1+\n2dup at-xy .\" `-----' \/\" 1+\n2dup at-xy .\" \u001b[33m<----.\u001b[31m __ \/ __ \\\" 1+\n2dup at-xy .\" \u001b[33m<----|====\u001b[31mO)))\u001b[33m==\u001b[31m) \\) \/\u001b[33m====|\" 1+\n2dup at-xy .\" \u001b[33m<----'\u001b[31m `--' `.__,' \\\" 1+\n2dup at-xy .\" | |\" 1+\n2dup at-xy .\" \\ \/ \/\\\" 1+\n2dup at-xy .\" \u001b[36m______\u001b[31m( (_ \/ \\______\/\" 1+\n2dup at-xy .\" \u001b[36m,' ,-----' |\" 1+\nat-xy .\" `--{__________) \u001b[0m\" 1+\n;\n\n: boring-beastie ( x y -- )\n\t2dup at-xy .\" , ,\" 1+\n\t2dup at-xy .\" \/( )`\" 1+\n\t2dup at-xy .\" \\ \\___ \/ |\" 1+\n\t2dup at-xy .\" \/- _ `-\/ '\" 1+\n\t2dup at-xy .\" (\/\\\/ \\ \\ \/\\\" 1+\n\t2dup at-xy .\" \/ \/ | ` \\\" 1+\n\t2dup at-xy .\" O O ) \/ |\" 1+\n\t2dup at-xy .\" `-^--'`< '\" 1+\n\t2dup at-xy .\" (_.) _ ) \/\" 1+\n\t2dup at-xy .\" `.___\/` \/\" 1+\n\t2dup at-xy .\" `-----' \/\" 1+\n\t2dup at-xy .\" <----. __ \/ __ \\\" 1+\n\t2dup at-xy .\" <----|====O)))==) \\) \/====\" 1+\n\t2dup at-xy .\" <----' `--' `.__,' \\\" 1+\n\t2dup at-xy .\" | |\" 1+\n\t2dup at-xy .\" \\ \/ \/\\\" 1+\n\t2dup at-xy .\" ______( (_ \/ \\______\/\" 1+\n\t2dup at-xy .\" ,' ,-----' |\" 1+\n\t at-xy .\" `--{__________)\"\n;\n\n: print-beastie ( x y -- )\n\ts\" loader_color\" getenv\n\tdup -1 = if\n\t\tdrop\n\t\tboring-beastie\n\t\texit\n\tthen\n\ts\" YES\" compare-insensitive 0<> if\n\t\tboring-beastie\n\t\texit\n\tthen\n\ttechnicolor-beastie\n;\n\n: acpienabled? ( -- flag )\n\ts\" acpi_load\" getenv\n\tdup -1 = if\n\t\tdrop false exit\n\tthen\n\ts\" YES\" compare-insensitive 0<> if\n\t\tfalse exit\n\tthen\n\ts\" hint.acpi.0.disabled\" getenv\n\tdup -1 <> if\n\t\ts\" 0\" compare 0<> if\n\t\t\tfalse exit\n\t\tthen\n\tthen\n\ttrue\n;\n\n: printmenuitem ( -- n )\n\tmenuidx @\n\t1+ dup\n\tmenuidx !\n\tmenuY @ + dup menuX @ swap at-xy\n\tmenuidx @ .\n\tmenuX @ 1+ swap at-xy\n\tmenubllt @ emit\n\tmenuidx @ 48 +\n;\n\n: beastie-menu ( -- )\n\t0 menuidx !\n\tdot menubllt !\n\t8 menuY !\n\t5 menuX !\n\tclear\n\t46 4 print-beastie\n\t42 20 2 2 box\n\t13 6 at-xy .\" Welcome to FreeBSD!\"\n\tprintmenuitem .\" Boot FreeBSD [default]\" bootkey !\n\ts\" arch-i386\" environment? if\n\t\tprintmenuitem .\" Boot FreeBSD with ACPI \" bootacpikey !\n\t\tacpienabled? if\n\t\t\t.\" disabled\"\n\t\telse\n\t\t\t.\" enabled\"\n\t\tthen\n\telse\n\t\t-2 bootacpikey !\n\tthen\n\tprintmenuitem .\" Boot FreeBSD in Safe Mode\" bootsafekey !\n\tprintmenuitem .\" Boot FreeBSD in single user mode\" bootsinglekey !\n\tprintmenuitem .\" Boot FreeBSD with verbose logging\" bootverbosekey !\n\tprintmenuitem .\" Escape to loader prompt\" escapekey !\n\tprintmenuitem .\" Reboot\" rebootkey !\n\tmenuX @ 20 at-xy\n\t.\" Select option, [Enter] for default\"\n\tmenuX @ 21 at-xy\n\ts\" or [Space] to pause timer \" dup 2 - promptwidth !\n\ttype\n;\n\n: tkey\n\tdup\n\tseconds +\n\tbegin 1 while\n\t\tover 0<> if\n\t\t\tdup seconds u< if\n\t\t\t\tdrop\n\t\t\t\t-1\n\t\t\t\texit\n\t\t\tthen\n\t\t\tmenuX @ promptwidth @ + 21 at-xy dup seconds - .\n\t\tthen\n\t\tkey? if\n\t\t\tdrop\n\t\t\tkey\n\t\t\texit\n\t\tthen\n\t50 ms\n\trepeat\n;\n\nset-current\n\n: beastie-start\n\ts\" beastie_disable\" getenv\n\tdup -1 <> if\n\t\ts\" YES\" compare-insensitive 0= if\n\t\t\texit\n\t\tthen\n\tthen\n\tbeastie-menu\n\ts\" autoboot_delay\" getenv\n\tdup -1 = if\n\t\tdrop\n\t\t10\n\telse\n\t\t0 0 2swap >number drop drop drop\n\tthen\n\tbegin true while\n\t\tdup tkey\n\t\t0 25 at-xy\n\t\tdup 32 = if nip 0 swap then\n\t\tdup -1 = if 0 boot then\n\t\tdup 13 = if 0 boot then\n\t\tdup bootkey @ = if 0 boot then\n\t\tdup bootacpikey @ = if\n\t\t\tacpienabled? if\n\t\t\t\ts\" acpi_load\" unsetenv\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\telse\n\t\t\t\ts\" YES\" s\" acpi_load\" setenv\n\t\t\t\ts\" 0\" s\" hint.acpi.0.disabled\" setenv\n\t\t\tthen\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootsafekey @ = if\n\t\t\ts\" arch-i386\" environment? if\n\t\t\t\ts\" acpi_load\" unsetenv\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\tthen\n\t\t\ts\" 0\" s\" hw.ata.ata_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.atapi_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.wc\" setenv\n\t\t\ts\" 0\" s\" hw.eisa_slots\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootverbosekey @ = if\n\t\t\ts\" YES\" s\" boot_verbose\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootsinglekey @ = if\n\t\t\ts\" YES\" s\" boot_single\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup escapekey @ = if\n\t\t\t2drop\n\t\t\ts\" NO\" s\" autoboot_delay\" setenv\n\t\t\texit\n\t\tthen\n\t\trebootkey @ = if 0 reboot then\n\trepeat\n;\n\nprevious\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"9a2404aa1f29493c17a310b6aff2e2cf01242433","subject":"Allocate more memory if necessary.","message":"Allocate more memory if necessary.\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/loader.4th","new_file":"sys\/boot\/forth\/loader.4th","new_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\ns\" arch-alpha\" environment? [if] [if]\n\ts\" loader_version\" environment? [if]\n\t\t11 < [if]\n\t\t\t.( Loader version 1.1+ required) cr\n\t\t\tabort\n\t\t[then]\n\t[else]\n\t\t.( Could not get loader version!) cr\n\t\tabort\n\t[then]\n[then] [then]\n\ns\" arch-i386\" environment? [if] [if]\n\ts\" loader_version\" environment? [if]\n\t\t10 < [if]\n\t\t\t.( Loader version 1.0+ required) cr\n\t\t\tabort\n\t\t[then]\n\t[else]\n\t\t.( Could not get loader version!) cr\n\t\tabort\n\t[then]\n[then] [then]\n\n256 dictthreshold ! \\ 256 cells minimum free space\n2048 dictincrease ! \\ 2048 additional cells each time\n\ninclude \/boot\/support.4th\n\n\\ ***** boot-conf\n\\\n\\\tPrepares to boot as specified by loaded configuration files.\n\nonly forth also support-functions also builtins definitions\n\n: boot\n 0= if ( interpreted ) get_arguments then\n\n \\ Unload only if a path was passed\n dup if\n >r over r> swap\n c@ [char] - <> if\n 0 1 unload drop\n else\n s\" kernelname\" getenv? if ( a kernel has been loaded )\n 1 boot exit\n then\n load_kernel_and_modules\n ?dup if exit then\n 0 1 boot exit\n then\n else\n s\" kernelname\" getenv? if ( a kernel has been loaded )\n 1 boot exit\n then\n load_kernel_and_modules\n ?dup if exit then\n 0 1 boot exit\n then\n load_kernel_and_modules\n ?dup 0= if 0 1 boot then\n;\n\n: boot-conf\n 0= if ( interpreted ) get_arguments then\n 0 1 unload drop\n load_kernel_and_modules\n ?dup 0= if 0 1 autoboot then\n;\n\nalso forth definitions also builtins\n\nbuiltin: boot\nbuiltin: boot-conf\n\nonly forth definitions also support-functions\n\n\\ ***** check-password\n\\\n\\\tIf a password was defined, execute autoboot and ask for\n\\\tpassword if autoboot returns.\n\n: check-password\n password .addr @ if\n 0 autoboot\n false >r\n begin\n bell emit bell emit\n .\" Password: \"\n password .len @ read-password\n dup password .len @ = if\n 2dup password .addr @ password .len @\n compare 0= if r> drop true >r then\n then\n drop free drop\n r@\n until\n r> drop\n then\n;\n\n\\ ***** start\n\\\n\\ Initializes support.4th global variables, sets loader_conf_files,\n\\ process conf files, and, if any one such file was succesfully\n\\ read to the end, load kernel and modules.\n\n: start ( -- ) ( throws: abort & user-defined )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n \\ Will *NOT* try to load kernel and modules if no configuration file\n \\ was succesfully loaded!\n any_conf_read? if\n load_kernel\n load_modules\n then\n;\n\n\\ ***** initialize\n\\\n\\\tOverrides support.4th initialization word with one that does\n\\\teverything start one does, short of loading the kernel and\n\\\tmodules. Returns a flag\n\n: initialize ( -- flag )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n any_conf_read?\n;\n\n\\ ***** read-conf\n\\\n\\\tRead a configuration file, whose name was specified on the command\n\\\tline, if interpreted, or given on the stack, if compiled in.\n\n: (read-conf) ( addr len -- )\n conf_files .addr @ ?dup if free abort\" Fatal error freeing memory\" then\n strdup conf_files .len ! conf_files .addr !\n include_conf_files \\ Will recurse on new loader_conf_files definitions\n;\n\n: read-conf ( | addr len -- ) ( throws: abort & user-defined )\n state @ if\n \\ Compiling\n postpone (read-conf)\n else\n \\ Interpreting\n bl parse (read-conf)\n then\n; immediate\n\n\\ ***** enable-module\n\\\n\\ Turn a module loading on.\n\n: enable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n true r> module.flag !\n .\" will be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** disable-module\n\\\n\\ Turn a module loading off.\n\n: disable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n false r> module.flag !\n .\" will not be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** toggle-module\n\\\n\\ Turn a module loading on\/off.\n\n: toggle-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n r@ module.flag @ 0= dup r> module.flag !\n if\n .\" will be loaded.\" cr\n else\n .\" will not be loaded.\" cr\n then\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** show-module\n\\\n\\\tShow loading information about a module.\n\n: show-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n .\" Name: \" r@ module.name dup .addr @ swap .len @ type cr\n .\" Path: \" r@ module.loadname dup .addr @ swap .len @ type cr\n .\" Type: \" r@ module.type dup .addr @ swap .len @ type cr\n .\" Flags: \" r@ module.args dup .addr @ swap .len @ type cr\n .\" Before load: \" r@ module.beforeload dup .addr @ swap .len @ type cr\n .\" After load: \" r@ module.afterload dup .addr @ swap .len @ type cr\n .\" Error: \" r@ module.loaderror dup .addr @ swap .len @ type cr\n .\" Status: \" r> module.flag @ if .\" Load\" else .\" Don't load\" then cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ Words to be used inside configuration files\n\n: retry false ; \\ For use in load error commands\n: ignore true ; \\ For use in load error commands\n\n\\ Return to strict forth vocabulary\n\n: #type\n over - >r\n type\n r> spaces\n;\n\n: .? 2 spaces 2swap 15 #type 2 spaces type cr ;\n\n: ?\n ['] ? execute\n s\" boot-conf\" s\" load kernel and modules, then autoboot\" .?\n s\" read-conf\" s\" read a configuration file\" .?\n s\" enable-module\" s\" enable loading of a module\" .?\n s\" disable-module\" s\" disable loading of a module\" .?\n s\" toggle-module\" s\" toggle loading of a module\" .?\n s\" show-module\" s\" show module load data\" .?\n;\n\nonly forth also\n\n","old_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\ns\" arch-alpha\" environment? [if] [if]\n\ts\" loader_version\" environment? [if]\n\t\t11 < [if]\n\t\t\t.( Loader version 1.1+ required) cr\n\t\t\tabort\n\t\t[then]\n\t[else]\n\t\t.( Could not get loader version!) cr\n\t\tabort\n\t[then]\n[then] [then]\n\ns\" arch-i386\" environment? [if] [if]\n\ts\" loader_version\" environment? [if]\n\t\t10 < [if]\n\t\t\t.( Loader version 1.0+ required) cr\n\t\t\tabort\n\t\t[then]\n\t[else]\n\t\t.( Could not get loader version!) cr\n\t\tabort\n\t[then]\n[then] [then]\n\ninclude \/boot\/support.4th\n\n\\ ***** boot-conf\n\\\n\\\tPrepares to boot as specified by loaded configuration files.\n\nonly forth also support-functions also builtins definitions\n\n: boot\n 0= if ( interpreted ) get_arguments then\n\n \\ Unload only if a path was passed\n dup if\n >r over r> swap\n c@ [char] - <> if\n 0 1 unload drop\n else\n s\" kernelname\" getenv? if ( a kernel has been loaded )\n 1 boot exit\n then\n load_kernel_and_modules\n ?dup if exit then\n 0 1 boot exit\n then\n else\n s\" kernelname\" getenv? if ( a kernel has been loaded )\n 1 boot exit\n then\n load_kernel_and_modules\n ?dup if exit then\n 0 1 boot exit\n then\n load_kernel_and_modules\n ?dup 0= if 0 1 boot then\n;\n\n: boot-conf\n 0= if ( interpreted ) get_arguments then\n 0 1 unload drop\n load_kernel_and_modules\n ?dup 0= if 0 1 autoboot then\n;\n\nalso forth definitions also builtins\n\nbuiltin: boot\nbuiltin: boot-conf\n\nonly forth definitions also support-functions\n\n\\ ***** check-password\n\\\n\\\tIf a password was defined, execute autoboot and ask for\n\\\tpassword if autoboot returns.\n\n: check-password\n password .addr @ if\n 0 autoboot\n false >r\n begin\n bell emit bell emit\n .\" Password: \"\n password .len @ read-password\n dup password .len @ = if\n 2dup password .addr @ password .len @\n compare 0= if r> drop true >r then\n then\n drop free drop\n r@\n until\n r> drop\n then\n;\n\n\\ ***** start\n\\\n\\ Initializes support.4th global variables, sets loader_conf_files,\n\\ process conf files, and, if any one such file was succesfully\n\\ read to the end, load kernel and modules.\n\n: start ( -- ) ( throws: abort & user-defined )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n \\ Will *NOT* try to load kernel and modules if no configuration file\n \\ was succesfully loaded!\n any_conf_read? if\n load_kernel\n load_modules\n then\n;\n\n\\ ***** initialize\n\\\n\\\tOverrides support.4th initialization word with one that does\n\\\teverything start one does, short of loading the kernel and\n\\\tmodules. Returns a flag\n\n: initialize ( -- flag )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n any_conf_read?\n;\n\n\\ ***** read-conf\n\\\n\\\tRead a configuration file, whose name was specified on the command\n\\\tline, if interpreted, or given on the stack, if compiled in.\n\n: (read-conf) ( addr len -- )\n conf_files .addr @ ?dup if free abort\" Fatal error freeing memory\" then\n strdup conf_files .len ! conf_files .addr !\n include_conf_files \\ Will recurse on new loader_conf_files definitions\n;\n\n: read-conf ( | addr len -- ) ( throws: abort & user-defined )\n state @ if\n \\ Compiling\n postpone (read-conf)\n else\n \\ Interpreting\n bl parse (read-conf)\n then\n; immediate\n\n\\ ***** enable-module\n\\\n\\ Turn a module loading on.\n\n: enable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n true r> module.flag !\n .\" will be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** disable-module\n\\\n\\ Turn a module loading off.\n\n: disable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n false r> module.flag !\n .\" will not be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** toggle-module\n\\\n\\ Turn a module loading on\/off.\n\n: toggle-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n r@ module.flag @ 0= dup r> module.flag !\n if\n .\" will be loaded.\" cr\n else\n .\" will not be loaded.\" cr\n then\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** show-module\n\\\n\\\tShow loading information about a module.\n\n: show-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n .\" Name: \" r@ module.name dup .addr @ swap .len @ type cr\n .\" Path: \" r@ module.loadname dup .addr @ swap .len @ type cr\n .\" Type: \" r@ module.type dup .addr @ swap .len @ type cr\n .\" Flags: \" r@ module.args dup .addr @ swap .len @ type cr\n .\" Before load: \" r@ module.beforeload dup .addr @ swap .len @ type cr\n .\" After load: \" r@ module.afterload dup .addr @ swap .len @ type cr\n .\" Error: \" r@ module.loaderror dup .addr @ swap .len @ type cr\n .\" Status: \" r> module.flag @ if .\" Load\" else .\" Don't load\" then cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ Words to be used inside configuration files\n\n: retry false ; \\ For use in load error commands\n: ignore true ; \\ For use in load error commands\n\n\\ Return to strict forth vocabulary\n\n: #type\n over - >r\n type\n r> spaces\n;\n\n: .? 2 spaces 2swap 15 #type 2 spaces type cr ;\n\n: ?\n ['] ? execute\n s\" boot-conf\" s\" load kernel and modules, then autoboot\" .?\n s\" read-conf\" s\" read a configuration file\" .?\n s\" enable-module\" s\" enable loading of a module\" .?\n s\" disable-module\" s\" disable loading of a module\" .?\n s\" toggle-module\" s\" toggle loading of a module\" .?\n s\" show-module\" s\" show module load data\" .?\n;\n\nonly forth also\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"32a78e55357f1a92ae7456ee3cbe5c3fb938c4bb","subject":"Update outer.4th","message":"Update outer.4th","repos":"AshleyF\/Forthkit,AshleyF\/Forthkit,AshleyF\/Forthkit","old_file":"hardware\/register\/outer.4th","new_file":"hardware\/register\/outer.4th","new_contents":"( outer interpreter - reads tokens, compiles headers, literals, ... )\n( requires assembler )\n\n( --- register allocation\/init ----------------------------------------------- )\n\n 0 const c ( char last read )\n 1 const sp ( space 32 ASCII )\n 2 const tib ( terminal input buffer )\n 3 const len ( token length )\n 4 const len' ( name length )\n 5 const zero ( constant 0 )\n 6 const d ( dictionary pointer )\n 7 const nm ( match flag for search )\n 8 const p ( pointer )\n 9 const c ( char being compared )\n 10 const p' ( pointer )\n 11 const c' ( char being compared )\n 12 const cur ( cursor )\n 13 const lnk ( link pointer )\n 14 const true ( truth value )\n 15 const false ( false value )\n 16 const n ( parsed number )\n 17 const zeroch ( '0' ASCII )\n 18 const base ( number base )\n 19 const s ( stack pointer )\n 20 const nreg ( register n number )\n 21 const ldc ( ldc instruction [0] )\n 22 const call ( call instruction [27] )\n 23 const ret ( return instruction [29] )\n 24 const two ( constant 2 )\n 25 const comp ( compiling flag )\n 26 const x ( temp )\n 27 const y ( temp )\n 28 const z ( temp - reserved bootstrap )\n\n 32 sp ldc, ( space ASCII )\n 48 zeroch ldc, ( '0' ASCII )\n -1 true ldc, ( all bits set [logical\/bitwise equivalent] )\n 10 base ldc, ( decimal by default )\n 32767 s ldc, ( top of data stack )\n n nreg ldc, ( register number of n )\n 27 call ldc, ( call instruction )\n 28 ret ldc, ( ret instruction )\n 2 two ldc, ( constant 2 )\n\nleap,\n\n( --- tokenization ----------------------------------------------------------- )\n\n label &skipws ( skip until non-whitespace )\n c in, ( read char )\n c sp &skipws ble, ( keep skipping whitespace )\n ret,\n \n label &name ( read input name into buffer )\n c tib st, ( append char )\n tib tib inc, ( advance tib )\n len len inc, ( increment length )\n c in, ( read char )\n c sp &name bgt, ( continue until whitespace )\n len tib st, ( append length )\n ret,\n \n label &token ( read token into buffer )\n d tib cp, ( end of dictionary as buffer )\n zero len cp, ( initial zero length )\n &skipws call, ( skip initial whitespace )\n &name jump, ( append name )\n\n( --- dictionary search ------------------------------------------------------ )\n \n label &nomatch\n true nm cp, ( set no-match flag )\n ret,\n \n label &compcs ( compare chars to input word )\n p c ld, ( get char of input word )\n p' c' ld, ( get char of dictionary word )\n c c' &nomatch bne, ( don't match? )\n p' p' inc, ( next char of dictionary word )\n p p inc, ( next char of input word )\n p tib &compcs blt, ( not end of word? continue... )\n ret, ( we have a match! )\n \n label &nextw ( advance to next word )\n cur cur ld, ( follow link address )\n ( fall through to &comp )\n \n label &comp\nzero cur &nomatch beq, ( no match if start of dict )\n tib len p sub, ( point p at start of token )\n cur p' dec, ( point p' at length field )\n p' len' ld, ( get length )\n len' len &nextw bne, ( lengths don't match? )\n p' len p' sub, ( move to beginning of word )\n false nm cp, ( reset no-match flag )\n &compcs call, ( compare characters )\n true nm &nextw beq, ( if no match, try next word )\n ret, ( we have a match! )\n \n label &find ( find word [tib within dictionary] )\n lnk cur cp, ( initialize cursor to last )\n &comp jump, ( compare with tib )\n \n( --- number processing ------------------------------------------------------ )\n\n label &digits\n p c ld, ( get char )\n c zeroch c sub, ( convert to digit )\n n base n mul, ( base shift left )\n n c n add, ( add in one's place )\n p p inc, ( next char )\n p tib &digits blt, ( not end? continue... )\n ret,\n \n label &parsenum ( parse token as number )\n tib len p sub, ( point p at start of word )\n zero n cp, ( init number )\n &digits jump,\n \n label &pushn ( push interactive number )\n n s st, ( store n at stack pointer )\n s s dec, ( adjust stack pointer )\n ret,\n \n label &popn ( pop number )\n s s inc, ( adjust stack pointer )\n s n ld, ( load value )\n ret,\n\n( --- literals --------------------------------------------------------------- )\n\n: append, d st, d d inc, ; ( macro: append and advance d )\n\n label &litn ( compile literal )\n ldc append, ( append ldc instruction )\n nreg append, ( append n register number )\n n append, ( append value )\n call append, ( append call instruction )\n &pushn x ldc, ( load address of &pushn )\n x append, ( append pushn address )\n ret,\n \n label &num ( process token as number )\n &parsenum call, ( parse number )\n true comp &litn beq, ( if compiling, compile literal )\n &pushn jump, ( else, push literal )\n \n( --- word processing -------------------------------------------------------- )\n\n label &exec ( execute word )\n two cur x add, ( point to code field )\n x exec, ( exec word )\n ret,\n \n label &compw ( compile word )\n cur x inc, ( point to immediate flag )\n x y ld, ( read immediate flag )\n true y &exec beq, ( execute if immediate )\n call append, ( append call instruction )\n x x inc, ( point to code field )\n x append, ( append code field address )\n ret,\n \n label &word ( process potential word token )\n true comp &compw beq, ( if compiling, compile word )\n &exec jump, ( else, execute word )\n \n label &eval ( process input tokens )\n &find call, ( try to find in dictionary )\n true nm &num beq, ( if not found, assume number )\n &word jump, ( else, process as a word )\n \n( --- REPL ------------------------------------------------------------------- )\n\n label &repl ( loop forever )\n &token call, ( read a token )\n &eval call, ( evaluate it )\n &repl jump, ( forever )\n \n( --- initial dictionary ----------------------------------------------------- )\n\nvar link\n: header, dup 0 do swap , loop , link @ here link ! , , ;\n\n 0 sym create header, ( word to create words )\n &token call, ( read a token )\n tib d cp, ( move dict ptr to end of name )\n d d inc, ( move past length field )\n lnk d st, ( append link address )\n d lnk cp, ( update link to here )\n d d inc, ( advance dictionary pointer )\n zero append, ( append 0 immediate flag ) \n ret,\n\n 0 sym immediate header, ( set immediate flag )\n lnk x inc, ( point to immediate flag )\n true x st, ( set immediate flag )\n ret,\n\n 0 sym compile header, ( switch to compiling mode )\n true comp cp, ( set comp flag )\n ret,\n\n 0 sym interact header, ( switch to interactive mode )\n label &interact\n false comp ldc, ( reset comp flag )\n ret,\n\n -1 sym ; header, ( return )\n ret append, ( append ret instruction )\n &interact jump, ( switch out of compiling mode )\n \n 0 sym pushn, header, ( push number [n] to stack from )\n &pushn jump, ( jump to push )\n \n 0 sym popn, header, ( pop number from stack to n )\n &popn jump, ( jump pop )\n \n 0 sym , header, ( append value from stack )\n &popn call, ( pop value from stack )\n n append, ( append n ) \n ret,\n \n 0 sym find header, ( find word )\n &token call, ( read a token )\n &find call, ( find token )\n cur n cp, ( prep to push cursor )\n two n n add, ( address of code field )\n &pushn jump, ( push cursor )\n \n 0 sym dump header, ( dump core to boot.bin )\n dump, ( TODO: build outside of outer interpreter )\n\nahead,\n\n( --- set `lnk` to within last header and `d` to just past this code --------- )\n\nlink @ lnk ldc, ( compile-time link ptr to runtime )\nhere 5 + d ldc, ( compile-time dict ptr to runtime [advance over init code below] )\n\n&repl jump, ( start the REPL )\n\nassemble\n\n","old_contents":"( inner interpreter - reads tokens, compiles headers, literals, ... )\n( requires assembler )\n\n( --- register allocation\/init ----------------------------------------------- )\n\n 0 const c ( char last read )\n 1 const sp ( space 32 ASCII )\n 2 const tib ( terminal input buffer )\n 3 const len ( token length )\n 4 const len' ( name length )\n 5 const zero ( constant 0 )\n 6 const d ( dictionary pointer )\n 7 const nm ( match flag for search )\n 8 const p ( pointer )\n 9 const c ( char being compared )\n 10 const p' ( pointer )\n 11 const c' ( char being compared )\n 12 const cur ( cursor )\n 13 const lnk ( link pointer )\n 14 const true ( truth value )\n 15 const false ( false value )\n 16 const n ( parsed number )\n 17 const zeroch ( '0' ASCII )\n 18 const base ( number base )\n 19 const s ( stack pointer )\n 20 const nreg ( register n number )\n 21 const ldc ( ldc instruction [0] )\n 22 const call ( call instruction [27] )\n 23 const ret ( return instruction [29] )\n 24 const two ( constant 2 )\n 25 const comp ( compiling flag )\n 26 const x ( temp )\n 27 const y ( temp )\n 28 const z ( temp - reserved bootstrap )\n\n 32 sp ldc, ( space ASCII )\n 48 zeroch ldc, ( '0' ASCII )\n -1 true ldc, ( all bits set [logical\/bitwise equivalent] )\n 10 base ldc, ( decimal by default )\n 32767 s ldc, ( top of data stack )\n n nreg ldc, ( register number of n )\n 27 call ldc, ( call instruction )\n 28 ret ldc, ( ret instruction )\n 2 two ldc, ( constant 2 )\n\nleap,\n\n( --- tokenization ----------------------------------------------------------- )\n\n label &skipws ( skip until non-whitespace )\n c in, ( read char )\n c sp &skipws ble, ( keep skipping whitespace )\n ret,\n \n label &name ( read input name into buffer )\n c tib st, ( append char )\n tib tib inc, ( advance tib )\n len len inc, ( increment length )\n c in, ( read char )\n c sp &name bgt, ( continue until whitespace )\n len tib st, ( append length )\n ret,\n \n label &token ( read token into buffer )\n d tib cp, ( end of dictionary as buffer )\n zero len cp, ( initial zero length )\n &skipws call, ( skip initial whitespace )\n &name jump, ( append name )\n\n( --- dictionary search ------------------------------------------------------ )\n \n label &nomatch\n true nm cp, ( set no-match flag )\n ret,\n \n label &compcs ( compare chars to input word )\n p c ld, ( get char of input word )\n p' c' ld, ( get char of dictionary word )\n c c' &nomatch bne, ( don't match? )\n p' p' inc, ( next char of dictionary word )\n p p inc, ( next char of input word )\n p tib &compcs blt, ( not end of word? continue... )\n ret, ( we have a match! )\n \n label &nextw ( advance to next word )\n cur cur ld, ( follow link address )\n ( fall through to &comp )\n \n label &comp\nzero cur &nomatch beq, ( no match if start of dict )\n tib len p sub, ( point p at start of token )\n cur p' dec, ( point p' at length field )\n p' len' ld, ( get length )\n len' len &nextw bne, ( lengths don't match? )\n p' len p' sub, ( move to beginning of word )\n false nm cp, ( reset no-match flag )\n &compcs call, ( compare characters )\n true nm &nextw beq, ( if no match, try next word )\n ret, ( we have a match! )\n \n label &find ( find word [tib within dictionary] )\n lnk cur cp, ( initialize cursor to last )\n &comp jump, ( compare with tib )\n \n( --- number processing ------------------------------------------------------ )\n\n label &digits\n p c ld, ( get char )\n c zeroch c sub, ( convert to digit )\n n base n mul, ( base shift left )\n n c n add, ( add in one's place )\n p p inc, ( next char )\n p tib &digits blt, ( not end? continue... )\n ret,\n \n label &parsenum ( parse token as number )\n tib len p sub, ( point p at start of word )\n zero n cp, ( init number )\n &digits jump,\n \n label &pushn ( push interactive number )\n n s st, ( store n at stack pointer )\n s s dec, ( adjust stack pointer )\n ret,\n \n label &popn ( pop number )\n s s inc, ( adjust stack pointer )\n s n ld, ( load value )\n ret,\n\n( --- literals --------------------------------------------------------------- )\n\n: append, d st, d d inc, ; ( macro: append and advance d )\n\n label &litn ( compile literal )\n ldc append, ( append ldc instruction )\n nreg append, ( append n register number )\n n append, ( append value )\n call append, ( append call instruction )\n &pushn x ldc, ( load address of &pushn )\n x append, ( append pushn address )\n ret,\n \n label &num ( process token as number )\n &parsenum call, ( parse number )\n true comp &litn beq, ( if compiling, compile literal )\n &pushn jump, ( else, push literal )\n \n( --- word processing -------------------------------------------------------- )\n\n label &exec ( execute word )\n two cur x add, ( point to code field )\n x exec, ( exec word )\n ret,\n \n label &compw ( compile word )\n cur x inc, ( point to immediate flag )\n x y ld, ( read immediate flag )\n true y &exec beq, ( execute if immediate )\n call append, ( append call instruction )\n x x inc, ( point to code field )\n x append, ( append code field address )\n ret,\n \n label &word ( process potential word token )\n true comp &compw beq, ( if compiling, compile word )\n &exec jump, ( else, execute word )\n \n label &eval ( process input tokens )\n &find call, ( try to find in dictionary )\n true nm &num beq, ( if not found, assume number )\n &word jump, ( else, process as a word )\n \n( --- REPL ------------------------------------------------------------------- )\n\n label &repl ( loop forever )\n &token call, ( read a token )\n &eval call, ( evaluate it )\n &repl jump, ( forever )\n \n( --- initial dictionary ----------------------------------------------------- )\n\nvar link\n: header, dup 0 do swap , loop , link @ here link ! , , ;\n\n 0 sym create header, ( word to create words )\n &token call, ( read a token )\n tib d cp, ( move dict ptr to end of name )\n d d inc, ( move past length field )\n lnk d st, ( append link address )\n d lnk cp, ( update link to here )\n d d inc, ( advance dictionary pointer )\n zero append, ( append 0 immediate flag ) \n ret,\n\n 0 sym immediate header, ( set immediate flag )\n lnk x inc, ( point to immediate flag )\n true x st, ( set immediate flag )\n ret,\n\n 0 sym compile header, ( switch to compiling mode )\n true comp cp, ( set comp flag )\n ret,\n\n 0 sym interact header, ( switch to interactive mode )\n label &interact\n false comp ldc, ( reset comp flag )\n ret,\n\n -1 sym ; header, ( return )\n ret append, ( append ret instruction )\n &interact jump, ( switch out of compiling mode )\n \n 0 sym pushn, header, ( push number [n] to stack from )\n &pushn jump, ( jump to push )\n \n 0 sym popn, header, ( pop number from stack to n )\n &popn jump, ( jump pop )\n \n 0 sym , header, ( append value from stack )\n &popn call, ( pop value from stack )\n n append, ( append n ) \n ret,\n \n 0 sym find header, ( find word )\n &token call, ( read a token )\n &find call, ( find token )\n cur n cp, ( prep to push cursor )\n two n n add, ( address of code field )\n &pushn jump, ( push cursor )\n \n 0 sym dump header, ( dump core to boot.bin )\n dump, ( TODO: build outside of outer interpreter )\n\nahead,\n\n( --- set `lnk` to within last header and `d` to just past this code --------- )\n\nlink @ lnk ldc, ( compile-time link ptr to runtime )\nhere 5 + d ldc, ( compile-time dict ptr to runtime [advance over init code below] )\n\n&repl jump, ( start the REPL )\n\nassemble\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"9aa7b8857efabe8d49489804630b50afd565c319","subject":"Update tmp\/bower_components\/ace-builds\/demo\/kitchen-sink\/docs\/forth.frt","message":"Update tmp\/bower_components\/ace-builds\/demo\/kitchen-sink\/docs\/forth.frt\n\nSigned-off-by: Bernard Ojengwa \n","repos":"apipanda\/openssl,apipanda\/openssl,apipanda\/openssl,apipanda\/openssl","old_file":"tmp\/bower_components\/ace-builds\/demo\/kitchen-sink\/docs\/forth.frt","new_file":"tmp\/bower_components\/ace-builds\/demo\/kitchen-sink\/docs\/forth.frt","new_contents":"","old_contents":": HELLO ( -- ) CR .\" Hello, world!\" ; \n\nHELLO \nHello, world!\n\n: [CHAR] CHAR POSTPONE LITERAL ; IMMEDIATE\n\n0 value ii 0 value jj\n0 value KeyAddr 0 value KeyLen\ncreate SArray 256 allot \\ state array of 256 bytes\n: KeyArray KeyLen mod KeyAddr ;\n\n: get_byte + c@ ;\n: set_byte + c! ;\n: as_byte 255 and ;\n: reset_ij 0 TO ii 0 TO jj ;\n: i_update 1 + as_byte TO ii ;\n: j_update ii SArray get_byte + as_byte TO jj ;\n: swap_s_ij\n jj SArray get_byte\n ii SArray get_byte jj SArray set_byte\n ii SArray set_byte\n;\n\n: rc4_init ( KeyAddr KeyLen -- )\n 256 min TO KeyLen TO KeyAddr\n 256 0 DO i i SArray set_byte LOOP\n reset_ij\n BEGIN\n ii KeyArray get_byte jj + j_update\n swap_s_ij\n ii 255 < WHILE\n ii i_update\n REPEAT\n reset_ij\n;\n: rc4_byte\n ii i_update jj j_update\n swap_s_ij\n ii SArray get_byte jj SArray get_byte + as_byte SArray get_byte xor\n;","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"2898924dfbd2181593233951187578b16ef0fcb7","subject":"Update public\/libs\/bower_components\/ace-builds\/demo\/kitchen-sink\/docs\/forth.frt","message":"Update public\/libs\/bower_components\/ace-builds\/demo\/kitchen-sink\/docs\/forth.frt\n\nSigned-off-by: Bernard Ojengwa \n","repos":"apipanda\/openssl,apipanda\/openssl,apipanda\/openssl,apipanda\/openssl","old_file":"public\/libs\/bower_components\/ace-builds\/demo\/kitchen-sink\/docs\/forth.frt","new_file":"public\/libs\/bower_components\/ace-builds\/demo\/kitchen-sink\/docs\/forth.frt","new_contents":"","old_contents":": HELLO ( -- ) CR .\" Hello, world!\" ; \n\nHELLO \nHello, world!\n\n: [CHAR] CHAR POSTPONE LITERAL ; IMMEDIATE\n\n0 value ii 0 value jj\n0 value KeyAddr 0 value KeyLen\ncreate SArray 256 allot \\ state array of 256 bytes\n: KeyArray KeyLen mod KeyAddr ;\n\n: get_byte + c@ ;\n: set_byte + c! ;\n: as_byte 255 and ;\n: reset_ij 0 TO ii 0 TO jj ;\n: i_update 1 + as_byte TO ii ;\n: j_update ii SArray get_byte + as_byte TO jj ;\n: swap_s_ij\n jj SArray get_byte\n ii SArray get_byte jj SArray set_byte\n ii SArray set_byte\n;\n\n: rc4_init ( KeyAddr KeyLen -- )\n 256 min TO KeyLen TO KeyAddr\n 256 0 DO i i SArray set_byte LOOP\n reset_ij\n BEGIN\n ii KeyArray get_byte jj + j_update\n swap_s_ij\n ii 255 < WHILE\n ii i_update\n REPEAT\n reset_ij\n;\n: rc4_byte\n ii i_update jj j_update\n swap_s_ij\n ii SArray get_byte jj SArray get_byte + as_byte SArray get_byte xor\n;","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"198a014d73bf0d2921de536ba1d4dfe903cc18db","subject":"assertion added for ?MAX-NB when param is negative","message":"assertion added for ?MAX-NB when param is negative\n","repos":"bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas","old_file":"KataDiversion_tests.fth","new_file":"KataDiversion_tests.fth","new_contents":"\\ KataDiversion tests, in Forth\n\\ running tests:\n\\ gforth KataDiversion_tests.fth -e bye\n\nREQUIRE KataDiversion.fth\n\nVARIABLE ASSERT-COUNT\n0 ASSERT-COUNT !\n\n: ASSERT-EQUAL ( n1 n2 -- n1 n2 )\n 2DUP <> IF 1 ABORT\" AssertEqual: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ - tests -\n\n\\ ?MAX-NB\n-1 ?MAX-NB 0 ASSERT-EQUAL\n0 ?MAX-NB 0 ASSERT-EQUAL\n1 ?MAX-NB 2 ASSERT-EQUAL\n2 ?MAX-NB 4 ASSERT-EQUAL\n3 ?MAX-NB 8 ASSERT-EQUAL\n\n\n\n\\ ---------\n\nASSERT-COUNT @ . .\" assertions successfully passed.\" CR\n\n","old_contents":"\\ KataDiversion tests, in Forth\n\\ running tests:\n\\ gforth KataDiversion_tests.fth -e bye\n\nREQUIRE KataDiversion.fth\n\nVARIABLE ASSERT-COUNT\n0 ASSERT-COUNT !\n\n: ASSERT-EQUAL ( n1 n2 -- n1 n2 )\n 2DUP <> IF 1 ABORT\" AssertEqual: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ - tests -\n\n\\ ?MAX-NB\n0 ?MAX-NB 0 ASSERT-EQUAL\n1 ?MAX-NB 2 ASSERT-EQUAL\n2 ?MAX-NB 4 ASSERT-EQUAL\n3 ?MAX-NB 8 ASSERT-EQUAL\n\n\n\n\\ ---------\n\nASSERT-COUNT @ . .\" assertions successfully passed.\" CR\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"22a8ccc7a566a4e6d3a47647be2039181618a7a3","subject":"Accessors for the working array.","message":"Accessors for the working array.","repos":"rbsexton\/gecko,rbsexton\/gecko,rbsexton\/gecko","old_file":"zero\/clock-umb\/forth\/Clock.fth","new_file":"zero\/clock-umb\/forth\/Clock.fth","new_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( -- )\n load-defaults \n icroot 0 over inter.rtcsem ! \\ Reset the free-running counters.\n 0 over inter.rtcdsem ! \\ Reset the free-running counters.\n\n begin \n \tdup inter.rtcsem @offex! ?dup if advancehms then\n \tdup inter.rtcdsem @offex! ?dup if advancedhms then\n [asm wfi asm]\n uiupdate if use-uivals else use-clockvals then \n key? until drop\n;\n \n\\ These two contain loops to ensure that we don't\n\\ drop any timer ticks on the floor.\n: ADVANCEHMS ( n -- ) 0 do hms advancetime loop ;\n: ADVANCEDHMS ( n -- ) 0 do dhms advancetime loop ;\n \n: LOAD-DEFAULTS ( -- )\n interp-init\n;\n\n\\ ----------------------------------------------------------\n\\ Define the structures before they get used.\n\\ ----------------------------------------------------------\nstruct ODN \\ On-Deck Needle \n\tint odn.s\n\tint odn.m\n\tint odn.h\nend-struct\n\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxsec \\ Max Value for secs+minutes\n\tint hms.maxhour \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_m \\ increment the minutes + hours\nend-struct\n\nstruct _interp_set\n\t4 cells field interp.a\n\t4 cells field interp.b\n\t4 cells field interp.c\nend-struct\n\n\\ ----------------------------------------------------------\n\\ Defaults get saved in the user data page.\n\\ ----------------------------------------------------------\n: NVRAMVALID? ( addr -- t\/f ) \n\\ *G See if there is valid data in the NVRAM.\n\\ ** It consists of 3 words. If any of them are \n\\ ** set to 0xffff:ffff, we go with the defaults.\n _USERDATA\n dup @ -1 <> \n over 4 + @ -1 <> and\n swap 8 + @ -1 <> and\n;\n\n: _NVRAMLOAD ( -- ) \n\\ *G Pull the needle maximums from flash.\n $C 0 do I ud@ needle_max I + ! 4 +loop \n; \n\n: NVRAM! ( -- )\n\\ *G Save the contents of the needle cal values.\n 0 UDPAGE_ERASE\n needle_max\n $C 0 do dup I + @ I ud! 4 +loop\n drop \n;\n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nidata\ncreate ODN_HMS odn allot \\ On-Deck, HMS\ncreate ODN_DHMS odn allot \\ On-Deck, DHMS\ncreate ODN_UI odn allot \\ On-Deck, Generated by the UI.\ncdata\n\nidata \\ Has to match an odn.\ncreate NEEDLE_MAX #850 , #850 , #850 ,\ncdata\n\n(( \n: interp-next drop 1 ; \n: interp-reset drop .\" Reset\" ; \n\t\n))\n\n: RANGECHECK ( max n -- n or zero ) 2dup <= if 2drop 0 else swap drop then ; \n\n: INTER-BUMP ( max old interp -- new )\n\\ *G Get the next value from the interpolator, and \n\\ ** reset the interpolator if it wraps around to zero.\n >R R@ interp-next \\ Get the max \n + rangecheck \n dup 0= if R> interp-reset else R> drop then \n ; \n\n: NFETCH ( odn off -- max old )\n\\ *G Combine the current value with the maximum.\n >R R@ \\ stash the offset.\n + @ \\ Calculate the offset address, get the current val.\n needle_max R> + @\n swap \n;\n\n: ++NEEDLE_S \\ Called every time.\n odn_hms 0 odn.s nfetch ( max old )\n\tinterp_hms interp.a inter-bump ( new )\n\todn_hms odn.s ! \n\t;\n\n: ++NEEDLE_M ( -- )\n\\ *G Every time we roll the seconds, bump the minutes and the hour\n\todn_hms 0 odn.m nfetch ( max old )\n\tinterp_hms interp.b inter-bump \n\todn_hms odn.m ! \n\n\todn_hms 0 odn.h nfetch ( max old )\n\tinterp_hms interp.c inter-bump \n\todn_hms odn.h ! \n\t;\n\n: ++NEEDLE_DS ; \\ Called every time.\n: ++NEEDLE_DM ; \\ Every time we roll the seconds.\n\n: _USE ( odn-addr -- ) \n dup odn.s w@ pwm0!\n dup odn.m w@ pwm1!\n odn.h w@ pwm2!\n ;\n\n: USE-CLOCKVALS odn_hms _use ; \n: USE-UIVALS odn_ui _use ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Quadrature\n\\ ----------------------------------------------------------\n\n_timer1 $24 + equ QUAD-IN\n\n\\ The Quadrature encoder produces two per detent.\n: QUAD@ ( -- n ) \\ Fetch and zero\n quad-in @off \n [asm sxth tos, tos asm]\n [asm asr .s tos, tos, # 1 asm] \\ Divide by two,\n ;\n \n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_ds , ' ++needle_dm , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n: ADVANCETIME ( struct-addr -- )\n dup hms.w_s @ execute \\ Invoke the official update word.\n 1 over hms.subsec +! \\ Increment\n dup hms.subsec @\n over hms.maxsubsec @ < if drop exit then \\ If less then max, we're done\n 0 over hms.subsec ! \\ Reset the subsecs \n\n 1 over hms.s +!\n dup hms.s @ over hms.maxsec @ < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n dup hms.w_m @ execute\n 1 over hms.m +!\n dup hms.m @ over hms.maxsec @ < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ over hms.maxhour @ < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ----------------------------------------------------------\n\\ The interpolator. \n\\ Implement bresenhams algorithm. All of this code already\n\\ exists in C, but we'll own the data structures. They contain\n\\ A total of 4 words - fixed, err, num, & denom\n\\ ----------------------------------------------------------\nudata \ncreate interp_hms _interp_set allot\ncreate interp_dhms _interp_set allot \ncreate adj_list #50 cells allot \\ 100 16-bit words. \ncdata\n\n#16 #60 * equ raw_sec\n#10 #100 * equ raw_dsec\n\n: INTERP-INIT ( -- )\n (interp_init) interp_hms\n 2dup interp.a needle_max @ raw_sec call3-- \n 2dup interp.b needle_max 4 + @ #60 call3-- \n interp.c needle_max 8 + @ #12 call3--\n\n (interp_init) interp_dhms\n 2dup interp.a needle_max @ raw_dsec call3-- \n 2dup interp.b needle_max 4 + @ #100 call3-- \n interp.c needle_max 8 + @ #10 call3--\n;\n\n\\ Call the reset fn.\n: INTERP-RESET ( interp_addr -- )\n (interp_reset) swap call1-- \n;\n\n: INTERP-NEXT ( addr -- n )\n (interp_next) swap call1--n\n;\n\n\n\\ ============================ UNTESTED =======================\n\\ VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n\n\\ ----------------------------------------------------------\n\\ User Interface\n\\ ----------------------------------------------------------\nvariable uistate\nvariable uicount \n\n_GPIO $64 + equ _BUTTONIO\n: BUTTONUP? ( -- t\/f ) _buttonio @ 1 and ; \n: BUTTONDOWN? ( -- t\/f ) buttonup? 1 xor ; \n\n\\ The wrapper for all of the UI stuff.\n\\ Returns true if the UI is active - ie, use the values generated by the UI.\n: UIUPDATE ( -- t\/f )\n StateHandlers uistate @ + @ execute \n; \n\n\\ -----------------------------------------------\n\\ State numbers. These are defined x4 so that\n\\ we can just use the state number as an index \n\\ into a table of words.\n\\ -----------------------------------------------\n0 4 * equ _s_init\n1 4 * equ _s_b1\n2 4 * equ _s_1sec\n\n3 4 * equ _s_set_h\n4 4 * equ _s_pendset_m\n5 4 * equ _s_setmin\n\n6 4 * equ _s_pendcal0\n7 4 * equ _s_cal0\n8 4 * equ _s_pendcalh\n9 4 * equ _s_calh\n10 4 * equ _s_pendcalm\n11 4 * equ _s_calm\n12 4 * equ _s_pendcals\n13 4 * equ _s_cals\n\n4 equ downcount_1s\n16 equ downcount_3s \n\n\\ All of the state handlers.\n\\ Everybody needs to know the state of the button, so that must\n\\ get passed in, thus they all look like this:\n\\ state ( t\/f -- t\/f )\n: shInit false \n buttondown? if \n _s_b1 uistate !\n uicount off \\ Reset this.\n then\n ;\n\n\\ Waiting for a full second to go by.\n: shB1 false\n buttonup? if _s_init uistate ! exit then\n \\ The Button is down. \n uicount @ downcount_1s >= if\n _s_1sec uistate !\n else \n 1 uicount +!\n\tthen\n ;\n\n\\ We're in the 1 second state\n: sh1sec true \n buttonup? if _s_set_h uistate ! exit then\n uicount @ downcount_3s >= if\n _s_pendcal0 uistate !\n else \n 1 uicount +!\n\tthen \n;\n\n\\ -------------------------------------------------\n\\ Setting the time\n\\ -------------------------------------------------\n: shSetH true buttondown? if _s_pendset_m uistate ! exit then ;\n\n: shPendSetM true buttonup? if _s_setmin uistate ! then ;\n: shSetMin true buttondown? if _s_init uistate ! exit then ;\n\n\\ -------------------------------------------------\n\\ Calibration\n\\ -------------------------------------------------\n: shPendCal0 true buttonup? if _s_cal0 uistate ! then ;\n: shCal0 true buttondown? if _s_pendcalh uistate ! exit then ;\n\n: shPendCalH true buttonup? if _s_calh uistate ! then ; \n: shCalH true buttondown? if _s_pendcalm uistate ! exit then ; \n\n: shPendCalM true buttonup? if _s_calm uistate ! then ; \n: shCalM true buttondown? if _s_pendcals uistate ! exit then ; \n\n: shPendCalS true buttonup? if _s_calm uistate ! then ; \n: shCalS true buttondown? if _s_init uistate ! exit then ; \n\ncreate StateHandlers \n' shInit , \n' shB1 ,\n' sh1sec ,\n\n' shSetH ,\n' shPendSetM , ' shSetMin ,\n\n' shPendCal0 , ' shCal0 ,\n' shPendCalH , ' shCalH , \n' shPendCalM , ' shCalM , \n' shPendCalS , ' shCalS , \n\n: ADJ_POINTS[]! ( data index -- ) 2* adj_points + w! ;\n: ADJ_POINTS[]@ ( index -- n ) 2* adj_points + w@ ;\n","old_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( -- )\n load-defaults \n icroot 0 over inter.rtcsem ! \\ Reset the free-running counters.\n 0 over inter.rtcdsem ! \\ Reset the free-running counters.\n\n begin \n \tdup inter.rtcsem @offex! ?dup if advancehms then\n \tdup inter.rtcdsem @offex! ?dup if advancedhms then\n [asm wfi asm]\n uiupdate if use-uivals else use-clockvals then \n key? until drop\n;\n \n\\ These two contain loops to ensure that we don't\n\\ drop any timer ticks on the floor.\n: ADVANCEHMS ( n -- ) 0 do hms advancetime loop ;\n: ADVANCEDHMS ( n -- ) 0 do dhms advancetime loop ;\n \n: LOAD-DEFAULTS ( -- )\n interp-init\n;\n\n\\ ----------------------------------------------------------\n\\ Define the structures before they get used.\n\\ ----------------------------------------------------------\nstruct ODN \\ On-Deck Needle \n\tint odn.s\n\tint odn.m\n\tint odn.h\nend-struct\n\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxsec \\ Max Value for secs+minutes\n\tint hms.maxhour \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_m \\ increment the minutes + hours\nend-struct\n\nstruct _interp_set\n\t4 cells field interp.a\n\t4 cells field interp.b\n\t4 cells field interp.c\nend-struct\n\n\\ ----------------------------------------------------------\n\\ Defaults get saved in the user data page.\n\\ ----------------------------------------------------------\n: NVRAMVALID? ( addr -- t\/f ) \n\\ *G See if there is valid data in the NVRAM.\n\\ ** It consists of 3 words. If any of them are \n\\ ** set to 0xffff:ffff, we go with the defaults.\n _USERDATA\n dup @ -1 <> \n over 4 + @ -1 <> and\n swap 8 + @ -1 <> and\n;\n\n: _NVRAMLOAD ( -- ) \n\\ *G Pull the needle maximums from flash.\n $C 0 do I ud@ needle_max I + ! 4 +loop \n; \n\n: NVRAM! ( -- )\n\\ *G Save the contents of the needle cal values.\n 0 UDPAGE_ERASE\n needle_max\n $C 0 do dup I + @ I ud! 4 +loop\n drop \n;\n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nidata\ncreate ODN_HMS odn allot \\ On-Deck, HMS\ncreate ODN_DHMS odn allot \\ On-Deck, DHMS\ncreate ODN_UI odn allot \\ On-Deck, Generated by the UI.\ncdata\n\nidata \\ Has to match an odn.\ncreate NEEDLE_MAX #850 , #850 , #850 ,\ncdata\n\n(( \n: interp-next drop 1 ; \n: interp-reset drop .\" Reset\" ; \n\t\n))\n\n: RANGECHECK ( max n -- n or zero ) 2dup <= if 2drop 0 else swap drop then ; \n\n: INTER-BUMP ( max old interp -- new )\n\\ *G Get the next value from the interpolator, and \n\\ ** reset the interpolator if it wraps around to zero.\n >R R@ interp-next \\ Get the max \n + rangecheck \n dup 0= if R> interp-reset else R> drop then \n ; \n\n: NFETCH ( odn off -- max old )\n\\ *G Combine the current value with the maximum.\n >R R@ \\ stash the offset.\n + @ \\ Calculate the offset address, get the current val.\n needle_max R> + @\n swap \n;\n\n: ++NEEDLE_S \\ Called every time.\n odn_hms 0 odn.s nfetch ( max old )\n\tinterp_hms interp.a inter-bump ( new )\n\todn_hms odn.s ! \n\t;\n\n: ++NEEDLE_M ( -- )\n\\ *G Every time we roll the seconds, bump the minutes and the hour\n\todn_hms 0 odn.m nfetch ( max old )\n\tinterp_hms interp.b inter-bump \n\todn_hms odn.m ! \n\n\todn_hms 0 odn.h nfetch ( max old )\n\tinterp_hms interp.c inter-bump \n\todn_hms odn.h ! \n\t;\n\n: ++NEEDLE_DS ; \\ Called every time.\n: ++NEEDLE_DM ; \\ Every time we roll the seconds.\n\n: _USE ( odn-addr -- ) \n dup odn.s w@ pwm0!\n dup odn.m w@ pwm1!\n odn.h w@ pwm2!\n ;\n\n: USE-CLOCKVALS odn_hms _use ; \n: USE-UIVALS odn_ui _use ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Quadrature\n\\ ----------------------------------------------------------\n\n_timer1 $24 + equ QUAD-IN\n\n\\ The Quadrature encoder produces two per detent.\n: QUAD@ ( -- n ) \\ Fetch and zero\n quad-in @off \n [asm sxth tos, tos asm]\n [asm asr .s tos, tos, # 1 asm] \\ Divide by two,\n ;\n \n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_ds , ' ++needle_dm , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n: ADVANCETIME ( struct-addr -- )\n dup hms.w_s @ execute \\ Invoke the official update word.\n 1 over hms.subsec +! \\ Increment\n dup hms.subsec @\n over hms.maxsubsec @ < if drop exit then \\ If less then max, we're done\n 0 over hms.subsec ! \\ Reset the subsecs \n\n 1 over hms.s +!\n dup hms.s @ over hms.maxsec @ < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n dup hms.w_m @ execute\n 1 over hms.m +!\n dup hms.m @ over hms.maxsec @ < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ over hms.maxhour @ < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ----------------------------------------------------------\n\\ The interpolator. \n\\ Implement bresenhams algorithm. All of this code already\n\\ exists in C, but we'll own the data structures. They contain\n\\ A total of 4 words - fixed, err, num, & denom\n\\ ----------------------------------------------------------\nudata \ncreate interp_hms _interp_set allot\ncreate interp_dhms _interp_set allot \ncreate adj_list #50 cells allot \\ 100 16-bit words. \ncdata\n\n#16 #60 * equ raw_sec\n#10 #100 * equ raw_dsec\n\n: INTERP-INIT ( -- )\n (interp_init) interp_hms\n 2dup interp.a needle_max @ raw_sec call3-- \n 2dup interp.b needle_max 4 + @ #60 call3-- \n interp.c needle_max 8 + @ #12 call3--\n\n (interp_init) interp_dhms\n 2dup interp.a needle_max @ raw_dsec call3-- \n 2dup interp.b needle_max 4 + @ #100 call3-- \n interp.c needle_max 8 + @ #10 call3--\n;\n\n\\ Call the reset fn.\n: INTERP-RESET ( interp_addr -- )\n (interp_reset) swap call1-- \n;\n\n: INTERP-NEXT ( addr -- n )\n (interp_next) swap call1--n\n;\n\n\n\\ ============================ UNTESTED =======================\n\\ VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n\n\\ ----------------------------------------------------------\n\\ User Interface\n\\ ----------------------------------------------------------\nvariable uistate\nvariable uicount \n\n_GPIO $64 + equ _BUTTONIO\n: BUTTONUP? ( -- t\/f ) _buttonio @ 1 and ; \n: BUTTONDOWN? ( -- t\/f ) buttonup? 1 xor ; \n\n\\ The wrapper for all of the UI stuff.\n\\ Returns true if the UI is active - ie, use the values generated by the UI.\n: UIUPDATE ( -- t\/f )\n StateHandlers uistate @ + @ execute \n; \n\n\\ -----------------------------------------------\n\\ State numbers. These are defined x4 so that\n\\ we can just use the state number as an index \n\\ into a table of words.\n\\ -----------------------------------------------\n0 4 * equ _s_init\n1 4 * equ _s_b1\n2 4 * equ _s_1sec\n\n3 4 * equ _s_set_h\n4 4 * equ _s_pendset_m\n5 4 * equ _s_setmin\n\n6 4 * equ _s_pendcal0\n7 4 * equ _s_cal0\n8 4 * equ _s_pendcalh\n9 4 * equ _s_calh\n10 4 * equ _s_pendcalm\n11 4 * equ _s_calm\n12 4 * equ _s_pendcals\n13 4 * equ _s_cals\n\n4 equ downcount_1s\n16 equ downcount_3s \n\n\\ All of the state handlers.\n\\ Everybody needs to know the state of the button, so that must\n\\ get passed in, thus they all look like this:\n\\ state ( t\/f -- t\/f )\n: shInit false \n buttondown? if \n _s_b1 uistate !\n uicount off \\ Reset this.\n then\n ;\n\n\\ Waiting for a full second to go by.\n: shB1 false\n buttonup? if _s_init uistate ! exit then\n \\ The Button is down. \n uicount @ downcount_1s >= if\n _s_1sec uistate !\n else \n 1 uicount +!\n\tthen\n ;\n\n\\ We're in the 1 second state\n: sh1sec true \n buttonup? if _s_set_h uistate ! exit then\n uicount @ downcount_3s >= if\n _s_pendcal0 uistate !\n else \n 1 uicount +!\n\tthen \n;\n\n\\ -------------------------------------------------\n\\ Setting the time\n\\ -------------------------------------------------\n: shSetH true buttondown? if _s_pendset_m uistate ! exit then ;\n\n: shPendSetM true buttonup? if _s_setmin uistate ! then ;\n: shSetMin true buttondown? if _s_init uistate ! exit then ;\n\n\\ -------------------------------------------------\n\\ Calibration\n\\ -------------------------------------------------\n: shPendCal0 true buttonup? if _s_cal0 uistate ! then ;\n: shCal0 true buttondown? if _s_pendcalh uistate ! exit then ;\n\n: shPendCalH true buttonup? if _s_calh uistate ! then ; \n: shCalH true buttondown? if _s_pendcalm uistate ! exit then ; \n\n: shPendCalM true buttonup? if _s_calm uistate ! then ; \n: shCalM true buttondown? if _s_pendcals uistate ! exit then ; \n\n: shPendCalS true buttonup? if _s_calm uistate ! then ; \n: shCalS true buttondown? if _s_init uistate ! exit then ; \n\ncreate StateHandlers \n' shInit , \n' shB1 ,\n' sh1sec ,\n\n' shSetH ,\n' shPendSetM , ' shSetMin ,\n\n' shPendCal0 , ' shCal0 ,\n' shPendCalH , ' shCalH , \n' shPendCalM , ' shCalM , \n' shPendCalS , ' shCalS , \n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"407e0f75b1c76961d38d4b629278a68649ebed1b","subject":"Back out the last commit. Bizzarely, that extra l@ makes boong from CD fail! Why this code, which must be executed, is not failing on disk is an utter mystery. More investigation needed.","message":"Back out the last commit. Bizzarely, that extra l@ makes boong from CD fail!\nWhy this code, which must be executed, is not failing on disk is an utter\nmystery. More investigation needed.\n","repos":"orumin\/openbsd-efivars,orumin\/openbsd-efivars,orumin\/openbsd-efivars,orumin\/openbsd-efivars","old_file":"arch\/sparc64\/stand\/bootblk\/bootblk.fth","new_file":"arch\/sparc64\/stand\/bootblk\/bootblk.fth","new_contents":"\\\t$OpenBSD: bootblk.fth,v 1.5 2010\/02\/26 19:59:11 deraadt Exp $\n\\\t$NetBSD: bootblk.fth,v 1.3 2001\/08\/15 20:10:24 eeh Exp $\n\\\n\\\tIEEE 1275 Open Firmware Boot Block\n\\\n\\\tParses disklabel and UFS and loads the file called `ofwboot'\n\\\n\\\n\\\tCopyright (c) 1998 Eduardo Horvath.\n\\\tAll rights reserved.\n\\\n\\\tRedistribution and use in source and binary forms, with or without\n\\\tmodification, are permitted provided that the following conditions\n\\\tare met:\n\\\t1. Redistributions of source code must retain the above copyright\n\\\t notice, this list of conditions and the following disclaimer.\n\\\t2. Redistributions in binary form must reproduce the above copyright\n\\\t notice, this list of conditions and the following disclaimer in the\n\\\t documentation and\/or other materials provided with the distribution.\n\\\t3. All advertising materials mentioning features or use of this software\n\\\t must display the following acknowledgement:\n\\\t This product includes software developed by Eduardo Horvath.\n\\\t4. The name of the author may not be used to endorse or promote products\n\\\t derived from this software without specific prior written permission\n\\\n\\\tTHIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n\\\tIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n\\\tOF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n\\\tIN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n\\\tINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n\\\tNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\\\tDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\\\tTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\\\t(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n\\\tTHIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\\\n\noffset16\nhex\nheaders\n\nfalse value boot-debug?\n\n\\\n\\ First some housekeeping: Open \/chosen and set up vectors into\n\\\tclient-services\n\n\" \/chosen\" find-package 0= if .\" Cannot find \/chosen\" 0 then\nconstant chosen-phandle\n\n\" \/openprom\/client-services\" find-package 0= if \n\t.\" Cannot find client-services\" cr abort\nthen constant cif-phandle\n\ndefer cif-claim ( align size virt -- base )\ndefer cif-release ( size virt -- )\ndefer cif-open ( cstr -- ihandle|0 )\ndefer cif-close ( ihandle -- )\ndefer cif-read ( len adr ihandle -- #read )\ndefer cif-seek ( low high ihandle -- -1|0|1 )\n\\ defer cif-peer ( phandle -- phandle )\n\\ defer cif-getprop ( len adr cstr phandle -- )\n\n: find-cif-method ( method,len -- xf )\n cif-phandle find-method drop \n;\n\n\" claim\" find-cif-method to cif-claim\n\" open\" find-cif-method to cif-open\n\" close\" find-cif-method to cif-close\n\" read\" find-cif-method to cif-read\n\" seek\" find-cif-method to cif-seek\n\n: twiddle ( -- ) .\" .\" ; \\ Need to do this right. Just spit out periods for now.\n\n\\\n\\ Support routines\n\\\n\n: strcmp ( s1 l1 s2 l2 -- true:false )\n rot tuck <> if 3drop false exit then\n comp 0=\n;\n\n\\ Move string into buffer\n\n: strmov ( s1 l1 d -- d l1 )\n dup 2over swap -rot\t\t( s1 l1 d s1 d l1 )\n move\t\t\t\t( s1 l1 d )\n rot drop swap\n;\n\n\\ Move s1 on the end of s2 and return the result\n\n: strcat ( s1 l1 s2 l2 -- d tot )\n 2over swap \t\t\t\t( s1 l1 s2 l2 l1 s1 )\n 2over + rot\t\t\t\t( s1 l1 s2 l2 s1 d l1 )\n move rot + \t\t\t\t( s1 s2 len )\n rot drop\t\t\t\t( s2 len )\n;\n\n: strchr ( s1 l1 c -- s2 l2 )\n begin\n dup 2over 0= if\t\t\t( s1 l1 c c s1 )\n 2drop drop exit then\n c@ = if\t\t\t\t( s1 l1 c )\n drop exit then\n -rot \/c - swap ca1+\t\t( c l2 s2 )\n swap rot\n again\n;\n\n \n: cstr ( ptr -- str len )\n dup \n begin dup c@ 0<> while + repeat\n over -\n;\n\n\\\n\\ BSD FFS parameters\n\\\n\nfload\tassym.fth.h\n\nsbsize buffer: sb-buf\n-1 value boot-ihandle\ndev_bsize value bsize\n0 value raid-offset\t\\ Offset if it's a raid-frame partition\n\n: strategy ( addr size start -- nread )\n raid-offset + bsize * 0 \" seek\" boot-ihandle $call-method\n -1 = if \n .\" strategy: Seek failed\" cr\n abort\n then\n \" read\" boot-ihandle $call-method\n;\n\n\\\n\\ Cylinder group macros\n\\\n\n: cgbase ( cg fs -- cgbase ) fs_fpg l@ * ;\n: cgstart ( cg fs -- cgstart ) \n 2dup fs_cgmask l@ not and\t\t( cg fs stuff -- )\n over fs_cgoffset l@ * -rot\t\t( stuffcg fs -- )\n cgbase +\n;\n: cgdmin ( cg fs -- 1st-data-block ) dup fs_dblkno l@ -rot cgstart + ;\n: cgimin ( cg fs -- inode-block ) dup fs_iblkno l@ -rot cgstart + ;\n: cgsblock ( cg fs -- super-block ) dup fs_sblkno l@ -rot cgstart + ;\n: cgstod ( cg fs -- cg-block ) dup fs_cblkno l@ -rot cgstart + ;\n\n\\\n\\ Block and frag position macros\n\\\n\n: blkoff ( pos fs -- off ) fs_qbmask x@ and ;\n: fragoff ( pos fs -- off ) fs_qfmask x@ and ;\n: lblktosize ( blk fs -- off ) fs_bshift l@ << ;\n: lblkno ( pos fs -- off ) fs_bshift l@ >> ;\n: numfrags ( pos fs -- off ) fs_fshift l@ >> ;\n: blkroundup ( pos fs -- off ) dup fs_bmask l@ -rot fs_qbmask x@ + and ;\n: fragroundup ( pos fs -- off ) dup fs_fmask l@ -rot fs_qfmask x@ + and ;\n\\ : fragroundup ( pos fs -- off ) tuck fs_qfmask x@ + swap fs_fmask l@ and ;\n: fragstoblks ( pos fs -- off ) fs_fragshift l@ >> ;\n: blkstofrags ( blk fs -- frag ) fs_fragshift l@ << ;\n: fragnum ( fsb fs -- off ) fs_frag l@ 1- and ;\n: blknum ( fsb fs -- off ) fs_frag l@ 1- not and ;\n: dblksize ( lbn dino fs -- size )\n -rot \t\t\t\t( fs lbn dino )\n di_size x@\t\t\t\t( fs lbn di_size )\n -rot dup 1+\t\t\t\t( di_size fs lbn lbn+1 )\n 2over fs_bshift l@\t\t\t( di_size fs lbn lbn+1 di_size b_shift )\n rot swap <<\t>=\t\t\t( di_size fs lbn res1 )\n swap ndaddr >= or if\t\t\t( di_size fs )\n swap drop fs_bsize l@ exit\t( size )\n then\ttuck blkoff swap fragroundup\t( size )\n;\n\n\n: ino-to-cg ( ino fs -- cg ) fs_ipg l@ \/ ;\n: ino-to-fsbo ( ino fs -- fsb0 ) fs_inopb l@ mod ;\n: ino-to-fsba ( ino fs -- ba )\t\\ Need to remove the stupid stack diags someday\n 2dup \t\t\t\t( ino fs ino fs )\n ino-to-cg\t\t\t\t( ino fs cg )\n over\t\t\t\t\t( ino fs cg fs )\n cgimin\t\t\t\t( ino fs inode-blk )\n -rot\t\t\t\t\t( inode-blk ino fs )\n tuck \t\t\t\t( inode-blk fs ino fs )\n fs_ipg l@ \t\t\t\t( inode-blk fs ino ipg )\n mod\t\t\t\t\t( inode-blk fs mod )\n swap\t\t\t\t\t( inode-blk mod fs )\n dup \t\t\t\t\t( inode-blk mod fs fs )\n fs_inopb l@ \t\t\t\t( inode-blk mod fs inopb )\n rot \t\t\t\t\t( inode-blk fs inopb mod )\n swap\t\t\t\t\t( inode-blk fs mod inopb )\n \/\t\t\t\t\t( inode-blk fs div )\n swap\t\t\t\t\t( inode-blk div fs )\n blkstofrags\t\t\t\t( inode-blk frag )\n +\n;\n: fsbtodb ( fsb fs -- db ) fs_fsbtodb l@ << ;\n\n\\\n\\ File stuff\n\\\n\nniaddr \/w* constant narraysize\n\nstruct \n 8\t\tfield\t>f_ihandle\t\\ device handle\n 8 \t\tfield \t>f_seekp\t\\ seek pointer\n 8 \t\tfield \t>f_fs\t\t\\ pointer to super block\n ufs1_dinode_SIZEOF \tfield \t>f_di\t\\ copy of on-disk inode\n 8\t\tfield\t>f_buf\t\t\\ buffer for data block\n 4\t\tfield \t>f_buf_size\t\\ size of data block\n 4\t\tfield\t>f_buf_blkno\t\\ block number of data block\nconstant file_SIZEOF\n\nfile_SIZEOF buffer: the-file\nsb-buf the-file >f_fs x!\n\nufs1_dinode_SIZEOF buffer: cur-inode\nh# 2000 buffer: indir-block\n-1 value indir-addr\n\n\\\n\\ Translate a fileblock to a disk block\n\\\n\\ We only allow single indirection\n\\\n\n: block-map ( fileblock -- diskblock )\n \\ Direct block?\n dup ndaddr < if \t\t\t( fileblock )\n cur-inode di_db\t\t\t( arr-indx arr-start )\n swap la+ l@ exit\t\t\t( diskblock )\n then \t\t\t\t( fileblock )\n ndaddr -\t\t\t\t( fileblock' )\n \\ Now we need to check the indirect block\n dup sb-buf fs_nindir l@ < if\t( fileblock' )\n cur-inode di_ib l@ dup\t\t( fileblock' indir-block indir-block )\n indir-addr <> if \t\t( fileblock' indir-block )\n to indir-addr\t\t\t( fileblock' )\n indir-block \t\t\t( fileblock' indir-block )\n sb-buf dup fs_bsize l@\t\t( fileblock' indir-block fs fs_bsize )\n swap indir-addr swap\t\t( fileblock' indir-block fs_bsize indiraddr fs )\n fsbtodb \t\t\t( fileblock' indir-block fs_bsize db )\n strategy\t\t\t( fileblock' nread )\n then\t\t\t\t( fileblock' nread|indir-block )\n drop \\ Really should check return value\n indir-block swap la+ l@ exit\n then\n dup sb-buf fs_nindir -\t\t( fileblock'' )\n \\ Now try 2nd level indirect block -- just read twice \n dup sb-buf fs_nindir l@ dup * < if\t( fileblock'' )\n cur-inode di_ib 1 la+ l@\t\t( fileblock'' indir2-block )\n to indir-addr\t\t\t( fileblock'' )\n \\ load 1st level indir block \n indir-block \t\t\t( fileblock'' indir-block )\n sb-buf dup fs_bsize l@\t\t( fileblock'' indir-block fs fs_bsize )\n swap indir-addr swap\t\t( fileblock'' indir-block fs_bsize indiraddr fs )\n fsbtodb \t\t\t\t( fileblock'' indir-block fs_bsize db )\n strategy\t\t\t\t( fileblock'' nread )\n drop\t\t\t\t( fileblock'' )\n dup sb-buf fs_nindir \/\t\t( fileblock'' indir-offset )\n indir-block swap la+ l@\t\t( fileblock'' indirblock )\n to indir-addr\t\t\t( fileblock'' )\n \\ load 2nd level indir block\n indir-block \t\t\t( fileblock'' indir-block )\n sb-buf dup fs_bsize l@\t\t( fileblock'' indir-block fs fs_bsize )\n swap indir-addr swap\t\t( fileblock'' indir-block fs_bsize indiraddr fs )\n fsbtodb \t\t\t\t( fileblock'' indir-block fs_bsize db )\n strategy\t\t\t\t( fileblock'' nread )\n drop\t\t\t\t( fileblock'' )\n sb-buf fs_nindir l@ mod indir-block swap la+ l@ exit\n then\n .\" block-map: exceeded max file size\" cr\n abort\n;\n\n\\\n\\ Read file into internal buffer and return pointer and len\n\\\n\n0 value cur-block\t\t\t\\ allocated dynamically in ufs-open\n0 value cur-blocksize\t\t\t\\ size of cur-block\n-1 value cur-blockno\n0 value cur-offset\n\n: buf-read-file ( fs -- len buf )\n cur-offset swap\t\t\t( seekp fs )\n 2dup blkoff\t\t\t\t( seekp fs off )\n -rot 2dup lblkno\t\t\t( off seekp fs block )\n swap 2dup cur-inode\t\t\t( off seekp block fs block fs inop )\n swap dblksize\t\t\t( off seekp block fs size )\n rot dup cur-blockno\t\t\t( off seekp fs size block block cur )\n <> if \t\t\t\t( off seekp fs size block )\n block-map\t\t\t\t( off seekp fs size diskblock )\n dup 0= if\t\t\t( off seekp fs size diskblock )\n over cur-block swap 0 fill\t( off seekp fs size diskblock )\n boot-debug? if .\" buf-read-file fell off end of file\" cr then\n else\n 2dup sb-buf fsbtodb cur-block -rot strategy\t( off seekp fs size diskblock nread )\n rot 2dup <> if \" buf-read-file: short read.\" cr abort then\n then\t\t\t\t( off seekp fs diskblock nread size )\n nip nip\t\t\t\t( off seekp fs size )\n else\t\t\t\t\t( off seekp fs size block block cur )\n 2drop\t\t\t\t( off seekp fs size )\n then\n\\ dup cur-offset + to cur-offset\t\\ Set up next xfer -- not done\n nip nip swap -\t\t\t( len )\n cur-block\n;\n\n\\\n\\ Read inode into cur-inode -- uses cur-block\n\\ \n\n: read-inode ( inode fs -- )\n twiddle\t\t\t\t( inode fs -- inode fs )\n\n cur-block\t\t\t\t( inode fs -- inode fs buffer )\n\n over\t\t\t\t\t( inode fs buffer -- inode fs buffer fs )\n fs_bsize l@\t\t\t\t( inode fs buffer -- inode fs buffer size )\n\n 2over\t\t\t\t( inode fs buffer size -- inode fs buffer size inode fs )\n 2over\t\t\t\t( inode fs buffer size inode fs -- inode fs buffer size inode fs buffer size )\n 2swap tuck\t\t\t\t( inode fs buffer size inode fs buffer size -- inode fs buffer size buffer size fs inode fs )\n\n ino-to-fsba \t\t\t\t( inode fs buffer size buffer size fs inode fs -- inode fs buffer size buffer size fs fsba )\n swap\t\t\t\t\t( inode fs buffer size buffer size fs fsba -- inode fs buffer size buffer size fsba fs )\n fsbtodb\t\t\t\t( inode fs buffer size buffer size fsba fs -- inode fs buffer size buffer size db )\n\n dup to cur-blockno\t\t\t( inode fs buffer size buffer size dstart -- inode fs buffer size buffer size dstart )\n strategy\t\t\t\t( inode fs buffer size buffer size dstart -- inode fs buffer size nread )\n <> if .\" read-inode - residual\" cr abort then\n dup 2over\t\t\t\t( inode fs buffer -- inode fs buffer buffer inode fs )\n ino-to-fsbo\t\t\t\t( inode fs buffer -- inode fs buffer buffer fsbo )\n ufs1_dinode_SIZEOF * +\t\t\t( inode fs buffer buffer fsbo -- inode fs buffer dinop )\n cur-inode ufs1_dinode_SIZEOF move \t( inode fs buffer dinop -- inode fs buffer )\n\t\\ clear out the old buffers\n drop\t\t\t\t\t( inode fs buffer -- inode fs )\n 2drop\n;\n\n\\ Identify inode type\n\n: is-dir? ( dinode -- true:false ) di_mode w@ ifmt and ifdir = ;\n: is-symlink? ( dinode -- true:false ) di_mode w@ ifmt and iflnk = ;\n\n\n\n\\\n\\ Hunt for directory entry:\n\\ \n\\ repeat\n\\ load a buffer\n\\ while entries do\n\\ if entry == name return\n\\ next entry\n\\ until no buffers\n\\\n\n: search-directory ( str len -- ino|0 )\n 0 to cur-offset\n begin cur-offset cur-inode di_size x@ < while\t( str len )\n sb-buf buf-read-file\t\t( str len len buf )\n over 0= if .\" search-directory: buf-read-file zero len\" cr abort then\n swap dup cur-offset + to cur-offset\t( str len buf len )\n 2dup + nip\t\t\t( str len buf bufend )\n swap 2swap rot\t\t\t( bufend str len buf )\n begin dup 4 pick < while\t\t( bufend str len buf )\n dup d_ino l@ 0<> if \t\t( bufend str len buf )\n boot-debug? if dup dup d_name swap d_namlen c@ type cr then\n 2dup d_namlen c@ = if\t( bufend str len buf )\n dup d_name 2over\t\t( bufend str len buf dname str len )\n comp 0= if\t\t( bufend str len buf )\n \\ Found it -- return inode\n d_ino l@ nip nip nip\t( dino )\n boot-debug? if .\" Found it\" cr then \n exit \t\t\t( dino )\n then\n then\t\t\t( bufend str len buf )\n then\t\t\t\t( bufend str len buf )\n dup d_reclen w@ +\t\t( bufend str len nextbuf )\n repeat\n drop rot drop\t\t\t( str len )\n repeat\n 2drop 2drop 0\t\t\t( 0 )\n;\n\n: ffs_oldcompat ( -- )\n\\ Make sure old ffs values in sb-buf are sane\n sb-buf fs_npsect dup l@ sb-buf fs_nsect l@ max swap l!\n sb-buf fs_interleave dup l@ 1 max swap l!\n sb-buf fs_postblformat l@ fs_42postblfmt = if\n 8 sb-buf fs_nrpos l!\n then\n sb-buf fs_inodefmt l@ fs_44inodefmt < if\n sb-buf fs_bsize l@ \n dup ndaddr * 1- sb-buf fs_maxfilesize x!\n niaddr 0 ?do\n\tsb-buf fs_nindir l@ * dup\t( sizebp sizebp -- )\n\tsb-buf fs_maxfilesize dup x@\t( sizebp sizebp *fs_maxfilesize fs_maxfilesize -- )\n\trot \t\t\t\t( sizebp *fs_maxfilesize fs_maxfilesize sizebp -- )\n\t+ \t\t\t\t( sizebp *fs_maxfilesize new_fs_maxfilesize -- ) \n swap x! \t\t\t( sizebp -- )\n loop drop \t\t\t( -- )\n sb-buf dup fs_bmask l@ not swap fs_qbmask x!\n sb-buf dup fs_fmask l@ not swap fs_qfmask x!\n then\n;\n\n: read-super ( sector -- )\n0 \" seek\" boot-ihandle $call-method\n -1 = if \n .\" Seek failed\" cr\n abort\n then\n sb-buf sbsize \" read\" boot-ihandle $call-method\n dup sbsize <> if\n .\" Read of superblock failed\" cr\n .\" requested\" space sbsize .\n .\" actual\" space . cr\n abort\n else \n drop\n then\n;\n\n: ufs-open ( bootpath,len -- )\n boot-ihandle -1 = if\n over cif-open dup 0= if \t\t( boot-path len ihandle? )\n .\" Could not open device\" space type cr \n abort\n then \t\t\t\t( boot-path len ihandle )\n to boot-ihandle\t\t\t\\ Save ihandle to boot device\n then 2drop\n sboff read-super\n sb-buf fs_magic l@ fs_magic_value <> if\n 64 dup to raid-offset \n dev_bsize * sboff + read-super\n sb-buf fs_magic l@ fs_magic_value <> if\n .\" Invalid superblock magic\" cr\n abort\n then\n then\n sb-buf fs_bsize l@ dup maxbsize > if\n .\" Superblock bsize\" space . .\" too large\" cr\n abort\n then \n dup fs_SIZEOF < if\n .\" Superblock bsize < size of superblock\" cr\n abort\n then\n ffs_oldcompat\t( fs_bsize -- fs_bsize )\n dup to cur-blocksize alloc-mem to cur-block \\ Allocate cur-block\n boot-debug? if .\" ufs-open complete\" cr then\n;\n\n: ufs-close ( -- ) \n boot-ihandle dup -1 <> if\n cif-close -1 to boot-ihandle \n then\n cur-block 0<> if\n cur-block cur-blocksize free-mem\n then\n;\n\n: boot-path ( -- boot-path )\n \" bootpath\" chosen-phandle get-package-property if\n .\" Could not find bootpath in \/chosen\" cr\n abort\n else\n decode-string 2swap 2drop\n then\n;\n\n: boot-args ( -- boot-args )\n \" bootargs\" chosen-phandle get-package-property if\n .\" Could not find bootargs in \/chosen\" cr\n abort\n else\n decode-string 2swap 2drop\n then\n;\n\n2000 buffer: boot-path-str\n2000 buffer: boot-path-tmp\n\n: split-path ( path len -- right len left len )\n\\ Split a string at the `\/'\n begin\n dup -rot\t\t\t\t( oldlen right len left )\n ascii \/ left-parse-string\t\t( oldlen right len left len )\n dup 0<> if 4 roll drop exit then\n 2drop\t\t\t\t( oldlen right len )\n rot over =\t\t\t( right len diff )\n until\n;\n\n: find-file ( load-file len -- )\n rootino dup sb-buf read-inode\t( load-file len -- load-file len ino )\n -rot\t\t\t\t\t( load-file len ino -- pino load-file len )\n \\\n \\ For each path component\n \\ \n begin split-path dup 0<> while\t( pino right len left len -- )\n cur-inode is-dir? not if .\" Inode not directory\" cr abort then\n boot-debug? if .\" Looking for\" space 2dup type space .\" in directory...\" cr then\n search-directory\t\t\t( pino right len left len -- pino right len ino|false )\n dup 0= if .\" Bad path\" cr abort then\t( pino right len cino )\n sb-buf read-inode\t\t\t( pino right len )\n cur-inode is-symlink? if\t\t\\ Symlink -- follow the damn thing\n \\ Save path in boot-path-tmp\n boot-path-tmp strmov\t\t( pino new-right len )\n\n \\ Now deal with symlink\n cur-inode di_size x@\t\t( pino right len linklen )\n dup sb-buf fs_maxsymlinklen l@\t( pino right len linklen linklen maxlinklen )\n < if\t\t\t\t\\ Now join the link to the path\n cur-inode di_shortlink l@\t( pino right len linklen linkp )\n swap boot-path-str strmov\t( pino right len new-linkp linklen )\n else\t\t\t\t\\ Read file for symlink -- Ugh\n \\ Read link into boot-path-str\n boot-path-str dup sb-buf fs_bsize l@\n 0 block-map\t\t\t( pino right len linklen boot-path-str bsize blockno )\n strategy drop swap\t\t( pino right len boot-path-str linklen )\n then \t\t\t\t( pino right len linkp linklen )\n \\ Concatenate the two paths\n strcat\t\t\t\t( pino new-right newlen )\n swap dup c@ ascii \/ = if\t\\ go to root inode?\n rot drop rootino -rot\t( rino len right )\n then\n rot dup sb-buf read-inode\t( len right pino )\n -rot swap\t\t\t( pino right len )\n then\t\t\t\t( pino right len )\n repeat\n 2drop drop\n;\n\n: read-file ( size addr -- )\n \\ Read x bytes from a file to buffer\n begin over 0> while\n cur-offset cur-inode di_size x@ > if .\" read-file EOF exceeded\" cr abort then\n sb-buf buf-read-file\t\t( size addr len buf )\n over 2over drop swap\t\t( size addr len buf addr len )\n move\t\t\t\t( size addr len )\n dup cur-offset + to cur-offset\t( size len newaddr )\n tuck +\t\t\t\t( size len newaddr )\n -rot - swap\t\t\t( newaddr newsize )\n repeat\n 2drop\n;\n\n\\\n\\ According to the 1275 addendum for SPARC processors:\n\\ Default load-base is 0x4000. At least 0x8.0000 or\n\\ 512KB must be available at that address. \n\\\n\\ The Fcode bootblock can take up up to 8KB (O.K., 7.5KB) \n\\ so load programs at 0x4000 + 0x2000=> 0x6000\n\\\n\nh# 6000 constant loader-base\n\n\\\n\\ Elf support -- find the load addr\n\\\n\n: is-elf? ( hdr -- res? ) h# 7f454c46 = ;\n\n\\\n\\ Finally we finish it all off\n\\\n\n: load-file-signon ( load-file len boot-path len -- load-file len boot-path len )\n .\" Loading file\" space 2over type cr .\" from device\" space 2dup type cr\n;\n\n: load-file-print-size ( size -- size )\n .\" Loading\" space dup . space .\" bytes of file...\" cr \n;\n\n: load-file ( load-file len boot-path len -- load-base )\n boot-debug? if load-file-signon then\n the-file file_SIZEOF 0 fill\t\t\\ Clear out file structure\n ufs-open \t\t\t\t( load-file len )\n find-file\t\t\t\t( )\n\n \\\n \\ Now we've found the file we should read it in in one big hunk\n \\\n\n cur-inode di_size x@\t\t\t( file-len )\n dup \" to file-size\" evaluate\t\t( file-len )\n boot-debug? if load-file-print-size then\n 0 to cur-offset\n loader-base\t\t\t\t( buf-len addr )\n 2dup read-file\t\t\t( buf-len addr )\n ufs-close\t\t\t\t( buf-len addr )\n dup is-elf? if .\" load-file: not an elf executable\" cr abort then\n\n \\ Luckily the prom should be able to handle ELF executables by itself\n\n nip\t\t\t\t\t( addr )\n;\n\n: do-boot ( bootfile -- )\n .\" OpenBSD IEEE 1275 Bootblock 1.1\" cr\n boot-path load-file ( -- load-base )\n dup 0<> if \" to load-base init-program\" evaluate then\n;\n\n\nboot-args ascii V strchr 0<> swap drop if\n true to boot-debug?\nthen\n\nboot-args ascii D strchr 0= swap drop if\n \" \/ofwboot\" do-boot\nthen exit\n\n\n","old_contents":"\\\t$OpenBSD: bootblk.fth,v 1.4 2009\/09\/03 16:39:37 jsing Exp $\n\\\t$NetBSD: bootblk.fth,v 1.3 2001\/08\/15 20:10:24 eeh Exp $\n\\\n\\\tIEEE 1275 Open Firmware Boot Block\n\\\n\\\tParses disklabel and UFS and loads the file called `ofwboot'\n\\\n\\\n\\\tCopyright (c) 1998 Eduardo Horvath.\n\\\tAll rights reserved.\n\\\n\\\tRedistribution and use in source and binary forms, with or without\n\\\tmodification, are permitted provided that the following conditions\n\\\tare met:\n\\\t1. Redistributions of source code must retain the above copyright\n\\\t notice, this list of conditions and the following disclaimer.\n\\\t2. Redistributions in binary form must reproduce the above copyright\n\\\t notice, this list of conditions and the following disclaimer in the\n\\\t documentation and\/or other materials provided with the distribution.\n\\\t3. All advertising materials mentioning features or use of this software\n\\\t must display the following acknowledgement:\n\\\t This product includes software developed by Eduardo Horvath.\n\\\t4. The name of the author may not be used to endorse or promote products\n\\\t derived from this software without specific prior written permission\n\\\n\\\tTHIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n\\\tIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n\\\tOF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n\\\tIN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n\\\tINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n\\\tNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\\\tDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\\\tTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\\\t(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n\\\tTHIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\\\n\noffset16\nhex\nheaders\n\nfalse value boot-debug?\n\n\\\n\\ First some housekeeping: Open \/chosen and set up vectors into\n\\\tclient-services\n\n\" \/chosen\" find-package 0= if .\" Cannot find \/chosen\" 0 then\nconstant chosen-phandle\n\n\" \/openprom\/client-services\" find-package 0= if \n\t.\" Cannot find client-services\" cr abort\nthen constant cif-phandle\n\ndefer cif-claim ( align size virt -- base )\ndefer cif-release ( size virt -- )\ndefer cif-open ( cstr -- ihandle|0 )\ndefer cif-close ( ihandle -- )\ndefer cif-read ( len adr ihandle -- #read )\ndefer cif-seek ( low high ihandle -- -1|0|1 )\n\\ defer cif-peer ( phandle -- phandle )\n\\ defer cif-getprop ( len adr cstr phandle -- )\n\n: find-cif-method ( method,len -- xf )\n cif-phandle find-method drop \n;\n\n\" claim\" find-cif-method to cif-claim\n\" open\" find-cif-method to cif-open\n\" close\" find-cif-method to cif-close\n\" read\" find-cif-method to cif-read\n\" seek\" find-cif-method to cif-seek\n\n: twiddle ( -- ) .\" .\" ; \\ Need to do this right. Just spit out periods for now.\n\n\\\n\\ Support routines\n\\\n\n: strcmp ( s1 l1 s2 l2 -- true:false )\n rot tuck <> if 3drop false exit then\n comp 0=\n;\n\n\\ Move string into buffer\n\n: strmov ( s1 l1 d -- d l1 )\n dup 2over swap -rot\t\t( s1 l1 d s1 d l1 )\n move\t\t\t\t( s1 l1 d )\n rot drop swap\n;\n\n\\ Move s1 on the end of s2 and return the result\n\n: strcat ( s1 l1 s2 l2 -- d tot )\n 2over swap \t\t\t\t( s1 l1 s2 l2 l1 s1 )\n 2over + rot\t\t\t\t( s1 l1 s2 l2 s1 d l1 )\n move rot + \t\t\t\t( s1 s2 len )\n rot drop\t\t\t\t( s2 len )\n;\n\n: strchr ( s1 l1 c -- s2 l2 )\n begin\n dup 2over 0= if\t\t\t( s1 l1 c c s1 )\n 2drop drop exit then\n c@ = if\t\t\t\t( s1 l1 c )\n drop exit then\n -rot \/c - swap ca1+\t\t( c l2 s2 )\n swap rot\n again\n;\n\n \n: cstr ( ptr -- str len )\n dup \n begin dup c@ 0<> while + repeat\n over -\n;\n\n\\\n\\ BSD FFS parameters\n\\\n\nfload\tassym.fth.h\n\nsbsize buffer: sb-buf\n-1 value boot-ihandle\ndev_bsize value bsize\n0 value raid-offset\t\\ Offset if it's a raid-frame partition\n\n: strategy ( addr size start -- nread )\n raid-offset + bsize * 0 \" seek\" boot-ihandle $call-method\n -1 = if \n .\" strategy: Seek failed\" cr\n abort\n then\n \" read\" boot-ihandle $call-method\n;\n\n\\\n\\ Cylinder group macros\n\\\n\n: cgbase ( cg fs -- cgbase ) fs_fpg l@ * ;\n: cgstart ( cg fs -- cgstart ) \n 2dup fs_cgmask l@ not and\t\t( cg fs stuff -- )\n over fs_cgoffset l@ * -rot\t\t( stuffcg fs -- )\n cgbase +\n;\n: cgdmin ( cg fs -- 1st-data-block ) dup fs_dblkno l@ -rot cgstart + ;\n: cgimin ( cg fs -- inode-block ) dup fs_iblkno l@ -rot cgstart + ;\n: cgsblock ( cg fs -- super-block ) dup fs_sblkno l@ -rot cgstart + ;\n: cgstod ( cg fs -- cg-block ) dup fs_cblkno l@ -rot cgstart + ;\n\n\\\n\\ Block and frag position macros\n\\\n\n: blkoff ( pos fs -- off ) fs_qbmask x@ and ;\n: fragoff ( pos fs -- off ) fs_qfmask x@ and ;\n: lblktosize ( blk fs -- off ) fs_bshift l@ << ;\n: lblkno ( pos fs -- off ) fs_bshift l@ >> ;\n: numfrags ( pos fs -- off ) fs_fshift l@ >> ;\n: blkroundup ( pos fs -- off ) dup fs_bmask l@ -rot fs_qbmask x@ + and ;\n: fragroundup ( pos fs -- off ) dup fs_fmask l@ -rot fs_qfmask x@ + and ;\n\\ : fragroundup ( pos fs -- off ) tuck fs_qfmask x@ + swap fs_fmask l@ and ;\n: fragstoblks ( pos fs -- off ) fs_fragshift l@ >> ;\n: blkstofrags ( blk fs -- frag ) fs_fragshift l@ << ;\n: fragnum ( fsb fs -- off ) fs_frag l@ 1- and ;\n: blknum ( fsb fs -- off ) fs_frag l@ 1- not and ;\n: dblksize ( lbn dino fs -- size )\n -rot \t\t\t\t( fs lbn dino )\n di_size x@\t\t\t\t( fs lbn di_size )\n -rot dup 1+\t\t\t\t( di_size fs lbn lbn+1 )\n 2over fs_bshift l@\t\t\t( di_size fs lbn lbn+1 di_size b_shift )\n rot swap <<\t>=\t\t\t( di_size fs lbn res1 )\n swap ndaddr >= or if\t\t\t( di_size fs )\n swap drop fs_bsize l@ exit\t( size )\n then\ttuck blkoff swap fragroundup\t( size )\n;\n\n\n: ino-to-cg ( ino fs -- cg ) fs_ipg l@ \/ ;\n: ino-to-fsbo ( ino fs -- fsb0 ) fs_inopb l@ mod ;\n: ino-to-fsba ( ino fs -- ba )\t\\ Need to remove the stupid stack diags someday\n 2dup \t\t\t\t( ino fs ino fs )\n ino-to-cg\t\t\t\t( ino fs cg )\n over\t\t\t\t\t( ino fs cg fs )\n cgimin\t\t\t\t( ino fs inode-blk )\n -rot\t\t\t\t\t( inode-blk ino fs )\n tuck \t\t\t\t( inode-blk fs ino fs )\n fs_ipg l@ \t\t\t\t( inode-blk fs ino ipg )\n mod\t\t\t\t\t( inode-blk fs mod )\n swap\t\t\t\t\t( inode-blk mod fs )\n dup \t\t\t\t\t( inode-blk mod fs fs )\n fs_inopb l@ \t\t\t\t( inode-blk mod fs inopb )\n rot \t\t\t\t\t( inode-blk fs inopb mod )\n swap\t\t\t\t\t( inode-blk fs mod inopb )\n \/\t\t\t\t\t( inode-blk fs div )\n swap\t\t\t\t\t( inode-blk div fs )\n blkstofrags\t\t\t\t( inode-blk frag )\n +\n;\n: fsbtodb ( fsb fs -- db ) fs_fsbtodb l@ << ;\n\n\\\n\\ File stuff\n\\\n\nniaddr \/w* constant narraysize\n\nstruct \n 8\t\tfield\t>f_ihandle\t\\ device handle\n 8 \t\tfield \t>f_seekp\t\\ seek pointer\n 8 \t\tfield \t>f_fs\t\t\\ pointer to super block\n ufs1_dinode_SIZEOF \tfield \t>f_di\t\\ copy of on-disk inode\n 8\t\tfield\t>f_buf\t\t\\ buffer for data block\n 4\t\tfield \t>f_buf_size\t\\ size of data block\n 4\t\tfield\t>f_buf_blkno\t\\ block number of data block\nconstant file_SIZEOF\n\nfile_SIZEOF buffer: the-file\nsb-buf the-file >f_fs x!\n\nufs1_dinode_SIZEOF buffer: cur-inode\nh# 2000 buffer: indir-block\n-1 value indir-addr\n\n\\\n\\ Translate a fileblock to a disk block\n\\\n\\ We only allow single indirection\n\\\n\n: block-map ( fileblock -- diskblock )\n \\ Direct block?\n dup ndaddr < if \t\t\t( fileblock )\n cur-inode di_db\t\t\t( arr-indx arr-start )\n swap la+ l@ exit\t\t\t( diskblock )\n then \t\t\t\t( fileblock )\n ndaddr -\t\t\t\t( fileblock' )\n \\ Now we need to check the indirect block\n dup sb-buf fs_nindir l@ < if\t( fileblock' )\n cur-inode di_ib l@ dup\t\t( fileblock' indir-block indir-block )\n indir-addr <> if \t\t( fileblock' indir-block )\n to indir-addr\t\t\t( fileblock' )\n indir-block \t\t\t( fileblock' indir-block )\n sb-buf dup fs_bsize l@\t\t( fileblock' indir-block fs fs_bsize )\n swap indir-addr swap\t\t( fileblock' indir-block fs_bsize indiraddr fs )\n fsbtodb \t\t\t( fileblock' indir-block fs_bsize db )\n strategy\t\t\t( fileblock' nread )\n then\t\t\t\t( fileblock' nread|indir-block )\n drop \\ Really should check return value\n indir-block swap la+ l@ exit\n then\n dup sb-buf fs_nindir -\t\t( fileblock'' )\n \\ Now try 2nd level indirect block -- just read twice \n dup sb-buf fs_nindir l@ dup * < if\t( fileblock'' )\n cur-inode di_ib 1 la+ l@\t\t( fileblock'' indir2-block )\n to indir-addr\t\t\t( fileblock'' )\n \\ load 1st level indir block \n indir-block \t\t\t( fileblock'' indir-block )\n sb-buf dup fs_bsize l@\t\t( fileblock'' indir-block fs fs_bsize )\n swap indir-addr swap\t\t( fileblock'' indir-block fs_bsize indiraddr fs )\n fsbtodb \t\t\t\t( fileblock'' indir-block fs_bsize db )\n strategy\t\t\t\t( fileblock'' nread )\n drop\t\t\t\t( fileblock'' )\n dup sb-buf fs_nindir \/\t\t( fileblock'' indir-offset )\n indir-block swap la+ l@\t\t( fileblock'' indirblock )\n to indir-addr\t\t\t( fileblock'' )\n \\ load 2nd level indir block\n indir-block \t\t\t( fileblock'' indir-block )\n sb-buf dup fs_bsize l@\t\t( fileblock'' indir-block fs fs_bsize )\n swap indir-addr swap\t\t( fileblock'' indir-block fs_bsize indiraddr fs )\n fsbtodb \t\t\t\t( fileblock'' indir-block fs_bsize db )\n strategy\t\t\t\t( fileblock'' nread )\n drop\t\t\t\t( fileblock'' )\n sb-buf fs_nindir l@ mod indir-block swap la+ l@ exit\n then\n .\" block-map: exceeded max file size\" cr\n abort\n;\n\n\\\n\\ Read file into internal buffer and return pointer and len\n\\\n\n0 value cur-block\t\t\t\\ allocated dynamically in ufs-open\n0 value cur-blocksize\t\t\t\\ size of cur-block\n-1 value cur-blockno\n0 value cur-offset\n\n: buf-read-file ( fs -- len buf )\n cur-offset swap\t\t\t( seekp fs )\n 2dup blkoff\t\t\t\t( seekp fs off )\n -rot 2dup lblkno\t\t\t( off seekp fs block )\n swap 2dup cur-inode\t\t\t( off seekp block fs block fs inop )\n swap dblksize\t\t\t( off seekp block fs size )\n rot dup cur-blockno\t\t\t( off seekp fs size block block cur )\n <> if \t\t\t\t( off seekp fs size block )\n block-map\t\t\t\t( off seekp fs size diskblock )\n dup 0= if\t\t\t( off seekp fs size diskblock )\n over cur-block swap 0 fill\t( off seekp fs size diskblock )\n boot-debug? if .\" buf-read-file fell off end of file\" cr then\n else\n 2dup sb-buf fsbtodb cur-block -rot strategy\t( off seekp fs size diskblock nread )\n rot 2dup <> if \" buf-read-file: short read.\" cr abort then\n then\t\t\t\t( off seekp fs diskblock nread size )\n nip nip\t\t\t\t( off seekp fs size )\n else\t\t\t\t\t( off seekp fs size block block cur )\n 2drop\t\t\t\t( off seekp fs size )\n then\n\\ dup cur-offset + to cur-offset\t\\ Set up next xfer -- not done\n nip nip swap -\t\t\t( len )\n cur-block\n;\n\n\\\n\\ Read inode into cur-inode -- uses cur-block\n\\ \n\n: read-inode ( inode fs -- )\n twiddle\t\t\t\t( inode fs -- inode fs )\n\n cur-block\t\t\t\t( inode fs -- inode fs buffer )\n\n over\t\t\t\t\t( inode fs buffer -- inode fs buffer fs )\n fs_bsize l@\t\t\t\t( inode fs buffer -- inode fs buffer size )\n\n 2over\t\t\t\t( inode fs buffer size -- inode fs buffer size inode fs )\n 2over\t\t\t\t( inode fs buffer size inode fs -- inode fs buffer size inode fs buffer size )\n 2swap tuck\t\t\t\t( inode fs buffer size inode fs buffer size -- inode fs buffer size buffer size fs inode fs )\n\n ino-to-fsba \t\t\t\t( inode fs buffer size buffer size fs inode fs -- inode fs buffer size buffer size fs fsba )\n swap\t\t\t\t\t( inode fs buffer size buffer size fs fsba -- inode fs buffer size buffer size fsba fs )\n fsbtodb\t\t\t\t( inode fs buffer size buffer size fsba fs -- inode fs buffer size buffer size db )\n\n dup to cur-blockno\t\t\t( inode fs buffer size buffer size dstart -- inode fs buffer size buffer size dstart )\n strategy\t\t\t\t( inode fs buffer size buffer size dstart -- inode fs buffer size nread )\n <> if .\" read-inode - residual\" cr abort then\n dup 2over\t\t\t\t( inode fs buffer -- inode fs buffer buffer inode fs )\n ino-to-fsbo\t\t\t\t( inode fs buffer -- inode fs buffer buffer fsbo )\n ufs1_dinode_SIZEOF * +\t\t\t( inode fs buffer buffer fsbo -- inode fs buffer dinop )\n cur-inode ufs1_dinode_SIZEOF move \t( inode fs buffer dinop -- inode fs buffer )\n\t\\ clear out the old buffers\n drop\t\t\t\t\t( inode fs buffer -- inode fs )\n 2drop\n;\n\n\\ Identify inode type\n\n: is-dir? ( dinode -- true:false ) di_mode w@ ifmt and ifdir = ;\n: is-symlink? ( dinode -- true:false ) di_mode w@ ifmt and iflnk = ;\n\n\n\n\\\n\\ Hunt for directory entry:\n\\ \n\\ repeat\n\\ load a buffer\n\\ while entries do\n\\ if entry == name return\n\\ next entry\n\\ until no buffers\n\\\n\n: search-directory ( str len -- ino|0 )\n 0 to cur-offset\n begin cur-offset cur-inode di_size x@ < while\t( str len )\n sb-buf buf-read-file\t\t( str len len buf )\n over 0= if .\" search-directory: buf-read-file zero len\" cr abort then\n swap dup cur-offset + to cur-offset\t( str len buf len )\n 2dup + nip\t\t\t( str len buf bufend )\n swap 2swap rot\t\t\t( bufend str len buf )\n begin dup 4 pick < while\t\t( bufend str len buf )\n dup d_ino l@ 0<> if \t\t( bufend str len buf )\n boot-debug? if dup dup d_name swap d_namlen c@ type cr then\n 2dup d_namlen c@ = if\t( bufend str len buf )\n dup d_name 2over\t\t( bufend str len buf dname str len )\n comp 0= if\t\t( bufend str len buf )\n \\ Found it -- return inode\n d_ino l@ nip nip nip\t( dino )\n boot-debug? if .\" Found it\" cr then \n exit \t\t\t( dino )\n then\n then\t\t\t( bufend str len buf )\n then\t\t\t\t( bufend str len buf )\n dup d_reclen w@ +\t\t( bufend str len nextbuf )\n repeat\n drop rot drop\t\t\t( str len )\n repeat\n 2drop 2drop 0\t\t\t( 0 )\n;\n\n: ffs_oldcompat ( -- )\n\\ Make sure old ffs values in sb-buf are sane\n sb-buf fs_npsect dup l@ sb-buf fs_nsect l@ max swap l!\n sb-buf fs_interleave dup l@ 1 max swap l!\n sb-buf fs_postblformat l@ fs_42postblfmt = if\n 8 sb-buf fs_nrpos l!\n then\n sb-buf fs_inodefmt l@ fs_44inodefmt < if\n sb-buf fs_bsize l@ \n dup ndaddr * 1- sb-buf fs_maxfilesize x!\n niaddr 0 ?do\n\tsb-buf fs_nindir l@ * dup\t( sizebp sizebp -- )\n\tsb-buf fs_maxfilesize dup x@\t( sizebp sizebp *fs_maxfilesize fs_maxfilesize -- )\n\trot \t\t\t\t( sizebp *fs_maxfilesize fs_maxfilesize sizebp -- )\n\t+ \t\t\t\t( sizebp *fs_maxfilesize new_fs_maxfilesize -- ) \n swap x! \t\t\t( sizebp -- )\n loop drop \t\t\t( -- )\n sb-buf dup fs_bmask l@ not swap fs_qbmask x!\n sb-buf dup fs_fmask l@ not swap fs_qfmask x!\n then\n;\n\n: read-super ( sector -- )\n0 \" seek\" boot-ihandle $call-method\n -1 = if \n .\" Seek failed\" cr\n abort\n then\n sb-buf sbsize \" read\" boot-ihandle $call-method\n dup sbsize <> if\n .\" Read of superblock failed\" cr\n .\" requested\" space sbsize .\n .\" actual\" space . cr\n abort\n else \n drop\n then\n;\n\n: ufs-open ( bootpath,len -- )\n boot-ihandle -1 = if\n over cif-open dup 0= if \t\t( boot-path len ihandle? )\n .\" Could not open device\" space type cr \n abort\n then \t\t\t\t( boot-path len ihandle )\n to boot-ihandle\t\t\t\\ Save ihandle to boot device\n then 2drop\n sboff read-super\n sb-buf fs_magic l@ fs_magic_value <> if\n 64 dup to raid-offset \n dev_bsize * sboff + read-super\n sb-buf fs_magic l@ fs_magic_value <> if\n .\" Invalid superblock magic\" cr\n abort\n then\n then\n sb-buf fs_bsize l@ dup maxbsize > if\n .\" Superblock bsize\" space . .\" too large\" cr\n abort\n then \n dup fs_SIZEOF < if\n .\" Superblock bsize < size of superblock\" cr\n abort\n then\n ffs_oldcompat\t( fs_bsize -- fs_bsize )\n dup to cur-blocksize alloc-mem to cur-block \\ Allocate cur-block\n boot-debug? if .\" ufs-open complete\" cr then\n;\n\n: ufs-close ( -- ) \n boot-ihandle dup -1 <> if\n cif-close -1 to boot-ihandle \n then\n cur-block 0<> if\n cur-block cur-blocksize free-mem\n then\n;\n\n: boot-path ( -- boot-path )\n \" bootpath\" chosen-phandle get-package-property if\n .\" Could not find bootpath in \/chosen\" cr\n abort\n else\n decode-string 2swap 2drop\n then\n;\n\n: boot-args ( -- boot-args )\n \" bootargs\" chosen-phandle get-package-property if\n .\" Could not find bootargs in \/chosen\" cr\n abort\n else\n decode-string 2swap 2drop\n then\n;\n\n2000 buffer: boot-path-str\n2000 buffer: boot-path-tmp\n\n: split-path ( path len -- right len left len )\n\\ Split a string at the `\/'\n begin\n dup -rot\t\t\t\t( oldlen right len left )\n ascii \/ left-parse-string\t\t( oldlen right len left len )\n dup 0<> if 4 roll drop exit then\n 2drop\t\t\t\t( oldlen right len )\n rot over =\t\t\t( right len diff )\n until\n;\n\n: find-file ( load-file len -- )\n rootino dup sb-buf read-inode\t( load-file len -- load-file len ino )\n -rot\t\t\t\t\t( load-file len ino -- pino load-file len )\n \\\n \\ For each path component\n \\ \n begin split-path dup 0<> while\t( pino right len left len -- )\n cur-inode is-dir? not if .\" Inode not directory\" cr abort then\n boot-debug? if .\" Looking for\" space 2dup type space .\" in directory...\" cr then\n search-directory\t\t\t( pino right len left len -- pino right len ino|false )\n dup 0= if .\" Bad path\" cr abort then\t( pino right len cino )\n sb-buf read-inode\t\t\t( pino right len )\n cur-inode is-symlink? if\t\t\\ Symlink -- follow the damn thing\n \\ Save path in boot-path-tmp\n boot-path-tmp strmov\t\t( pino new-right len )\n\n \\ Now deal with symlink\n cur-inode di_size x@\t\t( pino right len linklen )\n dup sb-buf fs_maxsymlinklen l@\t( pino right len linklen linklen maxlinklen )\n < if\t\t\t\t\\ Now join the link to the path\n cur-inode di_shortlink l@\t( pino right len linklen linkp )\n swap boot-path-str strmov\t( pino right len new-linkp linklen )\n else\t\t\t\t\\ Read file for symlink -- Ugh\n \\ Read link into boot-path-str\n boot-path-str dup sb-buf fs_bsize l@\n 0 block-map\t\t\t( pino right len linklen boot-path-str bsize blockno )\n strategy drop swap\t\t( pino right len boot-path-str linklen )\n then \t\t\t\t( pino right len linkp linklen )\n \\ Concatenate the two paths\n strcat\t\t\t\t( pino new-right newlen )\n swap dup c@ ascii \/ = if\t\\ go to root inode?\n rot drop rootino -rot\t( rino len right )\n then\n rot dup sb-buf read-inode\t( len right pino )\n -rot swap\t\t\t( pino right len )\n then\t\t\t\t( pino right len )\n repeat\n 2drop drop\n;\n\n: read-file ( size addr -- )\n \\ Read x bytes from a file to buffer\n begin over 0> while\n cur-offset cur-inode di_size x@ > if .\" read-file EOF exceeded\" cr abort then\n sb-buf buf-read-file\t\t( size addr len buf )\n over 2over drop swap\t\t( size addr len buf addr len )\n move\t\t\t\t( size addr len )\n dup cur-offset + to cur-offset\t( size len newaddr )\n tuck +\t\t\t\t( size len newaddr )\n -rot - swap\t\t\t( newaddr newsize )\n repeat\n 2drop\n;\n\n\\\n\\ According to the 1275 addendum for SPARC processors:\n\\ Default load-base is 0x4000. At least 0x8.0000 or\n\\ 512KB must be available at that address. \n\\\n\\ The Fcode bootblock can take up up to 8KB (O.K., 7.5KB) \n\\ so load programs at 0x4000 + 0x2000=> 0x6000\n\\\n\nh# 6000 constant loader-base\n\n\\\n\\ Elf support -- find the load addr\n\\\n\n: is-elf? ( hdr -- res? ) h# 7f454c46 = ;\n\n\\\n\\ Finally we finish it all off\n\\\n\n: load-file-signon ( load-file len boot-path len -- load-file len boot-path len )\n .\" Loading file\" space 2over type cr .\" from device\" space 2dup type cr\n;\n\n: load-file-print-size ( size -- size )\n .\" Loading\" space dup . space .\" bytes of file...\" cr \n;\n\n: load-file ( load-file len boot-path len -- load-base )\n boot-debug? if load-file-signon then\n the-file file_SIZEOF 0 fill\t\t\\ Clear out file structure\n ufs-open \t\t\t\t( load-file len )\n find-file\t\t\t\t( )\n\n \\\n \\ Now we've found the file we should read it in in one big hunk\n \\\n\n cur-inode di_size x@\t\t\t( file-len )\n dup \" to file-size\" evaluate\t\t( file-len )\n boot-debug? if load-file-print-size then\n 0 to cur-offset\n loader-base\t\t\t\t( buf-len addr )\n 2dup read-file\t\t\t( buf-len addr )\n ufs-close\t\t\t\t( buf-len addr )\n\n dup l@ is-elf? false = if\n .\" load-file: not an elf executable\" cr\n abort\n then\n\n \\ Luckily the prom should be able to handle ELF executables by itself\n\n nip\t\t\t\t\t( addr )\n;\n\n: do-boot ( bootfile -- )\n .\" OpenBSD IEEE 1275 Bootblock 1.1\" cr\n boot-path load-file ( -- load-base )\n dup 0<> if \" to load-base init-program\" evaluate then\n;\n\n\nboot-args ascii V strchr 0<> swap drop if\n true to boot-debug?\nthen\n\nboot-args ascii D strchr 0= swap drop if\n \" \/ofwboot\" do-boot\nthen exit\n\n\n","returncode":0,"stderr":"","license":"isc","lang":"Forth"} {"commit":"148263e158fc89f1572b4eedd787d777e50f6d3e","subject":"Don't display option 2 (to toggle ACPI on or off) on x86 machines if the BIOS does not support ACPI. The other options in the menu retain their existing numbers, option 2 is simply blanked out (and '2' is ignored).","message":"Don't display option 2 (to toggle ACPI on or off) on x86 machines if the\nBIOS does not support ACPI. The other options in the menu retain their\nexisting numbers, option 2 is simply blanked out (and '2' is ignored).\n\nMFC after:\t1 month\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/beastie.4th","new_file":"sys\/boot\/forth\/beastie.4th","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"bsd-3-clause","lang":"Forth"} {"commit":"05865bf8f7ff3f20ad698113cb4cccae9718009b","subject":"Re-factor the basic clock stuff.","message":"Re-factor the basic clock stuff.","repos":"rbsexton\/gecko,rbsexton\/gecko,rbsexton\/gecko","old_file":"zero\/clock-umb\/forth\/Clock.fth","new_file":"zero\/clock-umb\/forth\/Clock.fth","new_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( -- )\n load-defaults \n icroot 0 over inter.rtcsem ! \\ Reset the free-running counters.\n 0 over inter.rtcdsem ! \\ Reset the free-running counters.\n\n begin \n \tdup inter.rtcsem @offex! ?dup if advancehms then\n \tdup inter.rtcdsem @offex! ?dup if advancedhms then\n [asm wfi asm]\n uiupdate if use-uivals else use-clockvals then \n key? until drop\n;\n \n\\ These two contain loops to ensure that we don't\n\\ drop any timer ticks on the floor.\n: ADVANCEHMS ( n -- ) 0 do hms advancetime loop ;\n: ADVANCEDHMS ( n -- ) 0 do dhms advancetime loop ;\n \n: LOAD-DEFAULTS ( -- )\n interp-init\n;\n\n\\ ----------------------------------------------------------\n\\ Define the structures before they get used.\n\\ ----------------------------------------------------------\nstruct ODN \\ On-Deck Needle \n\tint odn.s\n\tint odn.m\n\tint odn.h\nend-struct\n\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxsec \\ Max Value for secs+minutes\n\tint hms.maxhour \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_m \\ increment the minutes + hours\nend-struct\n\nstruct _interp_set\n\t4 cells field interp.a\n\t4 cells field interp.b\n\t4 cells field interp.c\nend-struct\n\n\\ ----------------------------------------------------------\n\\ Defaults get saved in the user data page.\n\\ ----------------------------------------------------------\n: NVRAMVALID? ( addr -- t\/f ) \n\\ *G See if there is valid data in the NVRAM.\n\\ ** It consists of 3 words. If any of them are \n\\ ** set to 0xffff:ffff, we go with the defaults.\n _USERDATA\n dup @ -1 <> \n over 4 + @ -1 <> and\n swap 8 + @ -1 <> and\n;\n\n: _NVRAMLOAD ( -- ) \n\\ *G Pull the needle maximums from flash.\n $C 0 do I ud@ needle_max I + ! 4 +loop \n; \n\n: NVRAM! ( -- )\n\\ *G Save the contents of the needle cal values.\n 0 UDPAGE_ERASE\n needle_max\n $C 0 do dup I + @ I ud! 4 +loop\n drop \n;\n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nidata\ncreate ODN_HMS odn allot \\ On-Deck, HMS\ncreate ODN_DHMS odn allot \\ On-Deck, DHMS\ncreate ODN_UI odn allot \\ On-Deck, Generated by the UI.\ncdata\n\nidata \\ Has to match an odn.\ncreate NEEDLE_MAX #850 , #850 , #850 ,\ncdata\n\n(( \n: interp-next drop 1 ; \n: interp-reset drop .\" Reset\" ; \n\t\n))\n\n: RANGECHECK ( max n -- n or zero ) 2dup <= if 2drop 0 else swap drop then ; \n\n: INTER-BUMP ( max old interp -- new )\n\\ *G Get the next value from the interpolator, and \n\\ ** reset the interpolator if it wraps around to zero.\n >R R@ interp-next \\ Get the max \n + rangecheck \n dup 0= if R> interp-reset else R> drop then \n ; \n\n: NFETCH ( odn off -- max old )\n\\ *G Combine the current value with the maximum.\n >R R@ \\ stash the offset.\n + @ \\ Calculate the offset address, get the current val.\n needle_max R> + @\n swap \n;\n\n: ++NEEDLE_S \\ Called every time.\n odn_hms 0 odn.s nfetch ( max old )\n\tinterp_hms interp.a inter-bump ( new )\n\todn_hms odn.s ! \n\t;\n\n: ++NEEDLE_M ( -- )\n\\ *G Every time we roll the seconds, bump the minutes and the hour\n\todn_hms 0 odn.m nfetch ( max old )\n\tinterp_hms interp.b inter-bump \n\todn_hms odn.m ! \n\n\todn_hms 0 odn.h nfetch ( max old )\n\tinterp_hms interp.c inter-bump \n\todn_hms odn.h ! \n\t;\n\n: ++NEEDLE_DS ; \\ Called every time.\n: ++NEEDLE_DM ; \\ Every time we roll the seconds.\n\n: _USE ( odn-addr -- ) \n dup odn.s w@ pwm0!\n dup odn.m w@ pwm1!\n odn.h w@ pwm2!\n ;\n\n: USE-CLOCKVALS odn_hms _use ; \n: USE-UIVALS odn_ui _use ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Quadrature\n\\ ----------------------------------------------------------\n\n: QUAD@ ( addr -- n ) \\ Fetch and zero\n @off [asm sxth tos, tos asm] ;\n \n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_ds , ' ++needle_dm , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n: ADVANCETIME ( struct-addr -- )\n dup hms.w_s @ execute \\ Invoke the official update word.\n 1 over hms.subsec +! \\ Increment\n dup hms.subsec @\n over hms.maxsubsec @ < if drop exit then \\ If less then max, we're done\n 0 over hms.subsec ! \\ Reset the subsecs \n\n dup hms.w_m @ execute\n 1 over hms.s +!\n dup hms.s @ over hms.maxsec @ < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n 1 over hms.m +!\n dup hms.m @ over hms.maxsec @ < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ over hms.maxhour @ < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ----------------------------------------------------------\n\\ The interpolator. \n\\ Implement bresenhams algorithm. All of this code already\n\\ exists in C, but we'll own the data structures. They contain\n\\ A total of 4 words - fixed, err, num, & denom\n\\ ----------------------------------------------------------\nudata \ncreate interp_hms _interp_set allot\ncreate interp_dhms _interp_set allot \ncreate adj_list #50 cells allot \\ 100 16-bit words. \ncdata\n\n#16 #60 * equ raw_sec\n#10 #100 * equ raw_dsec\n\n: INTERP-INIT ( -- )\n (interp_init) interp_hms\n 2dup interp.a needle_max @ raw_sec call3-- \n 2dup interp.b needle_max 4 + @ #60 call3-- \n interp.c needle_max 8 + @ #12 call3--\n\n (interp_init) interp_dhms\n 2dup interp.a needle_max @ raw_dsec call3-- \n 2dup interp.b needle_max 4 + @ #100 call3-- \n interp.c needle_max 8 + @ #10 call3--\n;\n\n\\ Call the reset fn.\n: INTERP-RESET ( interp_addr -- )\n (interp_reset) swap call1-- \n;\n\n: INTERP-NEXT ( addr -- n )\n (interp_next) swap call1--n\n;\n\n\n\\ ============================ UNTESTED =======================\n\\ VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n\n\\ ----------------------------------------------------------\n\\ User Interface\n\\ ----------------------------------------------------------\nvariable uistate\nvariable uicount \n\n_GPIO $64 + equ _BUTTONIO\n: BUTTONUP? ( -- t\/f ) _buttonio @ 1 and ; \n: BUTTONDOWN? ( -- t\/f ) buttonup? 1 or ; \n\n\\ The wrapper for all of the UI stuff.\n\\ Returns true if the UI is active - ie, use the values generated by the UI.\n: UIUPDATE ( -- t\/f )\n StateHandlers uistate @ + @ execute \n; \n\n\\ -----------------------------------------------\n\\ State numbers. These are defined x4 so that\n\\ we can just use the state number as an index \n\\ into a table of words.\n\\ -----------------------------------------------\n0 4 * equ _s_init\n1 4 * equ _s_b1\n2 4 * equ _s_1sec\n3 4 * equ _s_seth\n4 4 * equ _s_pendset_m\n5 4 * equ _s_setmin\n6 4 * equ _s_pendcal0\n7 4 * equ _s_cal0\n8 4 * equ _s_pendcalh\n9 4 * equ _s_calh\n10 4 * equ _s_pendcalm\n11 4 * equ _s_calm\n12 4 * equ _s_pendcals\n13 4 * equ _s_cals\n\n\\ All of the state handlers.\n\\ Everybody needs to know the state of the button, so that must\n\\ get passed in, thus they all look like this:\n\\ state ( t\/f -- t\/f )\n: shInit false \n buttondown? if \n _s_b1 uistate !\n uicount off \\ Reset this.\n then\n ;\n\n\\ Waiting for a full second to go by.\n: shB1 false\n buttonup? if _s_init uistate ! exit then\n \\ The Button is down. \n uicount @ 16 > if\n _s_1sec uistate !\n else \n 1 uicount +!\n\tthen\n ;\n\n\\ We're in the 1 second state\n: sh1sec true \n buttonup? if _s_seth uistate ! true exit then\n uicount @ 48 > if\n _s_pendcal0 uistate !\n else \n 1 uicount +!\n\tthen \n;\n\n\\ -------------------------------------------------\n\\ Setting the time\n\\ -------------------------------------------------\n: shSetH true buttondown? if _s_pendset_m uistate ! exit then ;\n\n: shPendSetM true buttonup? if _s_setmin uistate ! then ;\n: shSetMin true buttondown? if _s_pendset_m uistate ! exit then ;\n\n\\ -------------------------------------------------\n\\ Calibration\n\\ -------------------------------------------------\n: shPendCal0 true buttonup? if _s_cal0 uistate ! then ;\n: shCal0 true buttondown? if _s_pendcalh uistate ! exit then ;\n\n: shPendCalH true buttonup? if _s_calh uistate ! then ; \n: shCalH true buttondown? if _s_pendcalm uistate ! exit then ; \n\n: shPendCalM true buttonup? if _s_calm uistate ! then ; \n: shCalM true buttondown? if _s_pendcals uistate ! exit then ; \n\n: shPendCalS true buttonup? if _s_calm uistate ! then ; \n: shCalS true buttondown? if _s_init uistate ! exit then ; \n\ncreate StateHandlers \n' shInit , \n' shB1 ,\n' sh1sec ,\n' shSetH ,\n' shPendSetM , ' shSetMin ,\n\n' shPendCal0 , ' shCal0 ,\n' shPendCalH , ' shCalH , \n' shPendCalM , ' shCalM , \n' shPendCalS , ' shCalS , \n\n","old_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( -- )\n load-defaults \n icroot 0 over inter.rtcsem ! \\ Reset the free-running counters.\n 0 over inter.rtcdsem ! \\ Reset the free-running counters.\n\n begin \n \tdup inter.rtcsem @offex! ?dup if advancehms then\n \tdup inter.rtcdsem @offex! ?dup if advancedhms then\n [asm wfi asm]\n uiupdate if use-uivals else use-clockvals then \n key? until drop\n;\n \n\\ These two contain loops to ensure that we don't\n\\ drop any timer ticks on the floor.\n: ADVANCEHMS ( n -- ) 0 do hms advancetime loop ;\n: ADVANCEDHMS ( n -- ) 0 do dhms advancetime loop ;\n \n: LOAD-DEFAULTS ( -- )\n interp-init\n;\n\n\\ ----------------------------------------------------------\n\\ Define the structures before they get used.\n\\ ----------------------------------------------------------\nstruct ODN \\ On-Deck Needle \n\tint odn.s\n\tint odn.m\n\tint odn.h\nend-struct\n\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxsec \\ Max Value for secs+minutes\n\tint hms.maxhour \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_m \\ increment the minutes + hours\nend-struct\n\nstruct _interp_set\n\t4 cells field interp.a\n\t4 cells field interp.b\n\t4 cells field interp.c\nend-struct\n\n\\ ----------------------------------------------------------\n\\ Defaults get saved in the user data page.\n\\ ----------------------------------------------------------\n: NVRAMVALID? ( addr -- t\/f ) \n\\ *G See if there is valid data in the NVRAM.\n\\ ** It consists of 3 words. If any of them are \n\\ ** set to 0xffff:ffff, we go with the defaults.\n _USERDATA\n dup @ -1 <> \n over 4 + @ -1 <> and\n swap 8 + @ -1 <> and\n;\n\n: _NVRAMLOAD ( -- ) \n\\ *G Pull the needle maximums from flash.\n $C 0 do I ud@ needle_max I + ! 4 +loop \n; \n\n: NVRAM! ( -- )\n\\ *G Save the contents of the needle cal values.\n 0 UDPAGE_ERASE\n needle_max\n $C 0 do dup I + @ I ud! 4 +loop\n drop \n;\n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nidata\ncreate ODN_HMS odn allot \\ On-Deck, HMS\ncreate ODN_DHMS odn allot \\ On-Deck, DHMS\ncreate ODN_UI odn allot \\ On-Deck, Generated by the UI.\ncdata\n\nidata\ncreate NEEDLE_MAX #850 , #850 , #850 ,\ncdata\n\n\n: rangecheck ( max n -- n or zero ) dup >R <= if R> drop 0 else R> then ; \n\n: ++NEEDLE_S \\ Called every time.\n odn_hms odn.s \\ Stash this address for the moment. \n\n\tneedle_max odn.s @ \\ Get the max \n\tover w@ \\ Current value \n\n\tinterp_hms interp.a interp-next + \\ Returns a value.\n\t\n\t\\ If we've wrapped to zero, reset the interpolator \n\t\\ so that we don't accumulate errors during setting\/\n\t\\ calibration operations.\n rangecheck dup 0= if interp_hms interp.a interp-reset then \t\t\n\tswap w! \n\t;\n\n: ++NEEDLE_DS ; \\ Called every time.\n\n: ++NEEDLE_M ; \\ Every time we roll the seconds.\n: ++NEEDLE_DM ; \\ Every time we roll the seconds.\n\n: _USE ( odn-addr -- ) \n dup w@ pwm0!\n dup 2 + w@ pwm1!\n 4 + w@ pwm2!\n ;\n\n: USE-CLOCKVALS odn_hms _use ; \n: USE-UIVALS odn_ui _use ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Quadrature\n\\ ----------------------------------------------------------\n\n: QUAD@ ( addr -- n ) \\ Fetch and zero\n @off [asm sxth tos, tos asm] ;\n \n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_ds , ' ++needle_dm , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n: ADVANCETIME ( struct-addr -- )\n dup hms.w_s @ execute \\ Invoke the official update word.\n 1 over hms.subsec +! \\ Increment\n dup hms.subsec @\n over hms.maxsubsec @ < if drop exit then \\ If less then max, we're done\n 0 over hms.subsec ! \\ Reset the subsecs \n\n dup hms.w_m @ execute\n 1 over hms.s +!\n dup hms.s @ over hms.maxsec @ < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n 1 over hms.m +!\n dup hms.m @ over hms.maxsec @ < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ over hms.maxhour @ < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ----------------------------------------------------------\n\\ The interpolator. \n\\ Implement bresenhams algorithm. All of this code already\n\\ exists in C, but we'll own the data structures. They contain\n\\ A total of 4 words - fixed, err, num, & denom\n\\ ----------------------------------------------------------\nudata \ncreate interp_hms _interp_set allot\ncreate interp_dhms _interp_set allot \ncreate adj_list #50 cells allot \\ 100 16-bit words. \ncdata\n\n#16 #60 * equ raw_sec\n#10 #100 * equ raw_dsec\n\n: INTERP-INIT ( -- )\n (interp_init) interp_hms\n 2dup interp.a needle_max @ raw_sec call3-- \n 2dup interp.b needle_max 4 + @ #60 call3-- \n interp.c needle_max 8 + @ #12 call3--\n\n (interp_init) interp_dhms\n 2dup interp.a needle_max @ raw_dsec call3-- \n 2dup interp.b needle_max 4 + @ #100 call3-- \n interp.c needle_max 8 + @ #10 call3--\n;\n\n\\ Call the reset fn.\n: INTERP-RESET ( interp_addr -- )\n (interp_reset) swap call1-- \n;\n\n: INTERP-NEXT ( addr -- n )\n (interp_next) swap call1--n\n;\n\n\n\\ ============================ UNTESTED =======================\n\\ VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n\n\\ ----------------------------------------------------------\n\\ User Interface\n\\ ----------------------------------------------------------\nvariable uistate\nvariable uicount \n\n_GPIO $64 + equ _BUTTONIO\n: BUTTONUP? ( -- t\/f ) _buttonio @ 1 and ; \n: BUTTONDOWN? ( -- t\/f ) buttonup? 1 or ; \n\n\\ The wrapper for all of the UI stuff.\n\\ Returns true if the UI is active - ie, use the values generated by the UI.\n: UIUPDATE ( -- t\/f )\n StateHandlers uistate @ + @ execute \n; \n\n\\ -----------------------------------------------\n\\ State numbers. These are defined x4 so that\n\\ we can just use the state number as an index \n\\ into a table of words.\n\\ -----------------------------------------------\n0 4 * equ _s_init\n1 4 * equ _s_b1\n2 4 * equ _s_1sec\n3 4 * equ _s_seth\n4 4 * equ _s_pendset_m\n5 4 * equ _s_setmin\n6 4 * equ _s_pendcal0\n7 4 * equ _s_cal0\n8 4 * equ _s_pendcalh\n9 4 * equ _s_calh\n10 4 * equ _s_pendcalm\n11 4 * equ _s_calm\n12 4 * equ _s_pendcals\n13 4 * equ _s_cals\n\n\\ All of the state handlers.\n\\ Everybody needs to know the state of the button, so that must\n\\ get passed in, thus they all look like this:\n\\ state ( t\/f -- t\/f )\n: shInit false \n buttondown? if \n _s_b1 uistate !\n uicount off \\ Reset this.\n then\n ;\n\n\\ Waiting for a full second to go by.\n: shB1 false\n buttonup? if _s_init uistate ! exit then\n \\ The Button is down. \n uicount @ 16 > if\n _s_1sec uistate !\n else \n 1 uicount +!\n\tthen\n ;\n\n\\ We're in the 1 second state\n: sh1sec true \n buttonup? if _s_seth uistate ! true exit then\n uicount @ 48 > if\n _s_pendcal0 uistate !\n else \n 1 uicount +!\n\tthen \n;\n\n\\ -------------------------------------------------\n\\ Setting the time\n\\ -------------------------------------------------\n: shSetH true buttondown? if _s_pendset_m uistate ! exit then ;\n\n: shPendSetM true buttonup? if _s_setmin uistate ! then ;\n: shSetMin true buttondown? if _s_pendset_m uistate ! exit then ;\n\n\\ -------------------------------------------------\n\\ Calibration\n\\ -------------------------------------------------\n: shPendCal0 true buttonup? if _s_cal0 uistate ! then ;\n: shCal0 true buttondown? if _s_pendcalh uistate ! exit then ;\n\n: shPendCalH true buttonup? if _s_calh uistate ! then ; \n: shCalH true buttondown? if _s_pendcalm uistate ! exit then ; \n\n: shPendCalM true buttonup? if _s_calm uistate ! then ; \n: shCalM true buttondown? if _s_pendcals uistate ! exit then ; \n\n: shPendCalS true buttonup? if _s_calm uistate ! then ; \n: shCalS true buttondown? if _s_init uistate ! exit then ; \n\ncreate StateHandlers \n' shInit , \n' shB1 ,\n' sh1sec ,\n' shSetH ,\n' shPendSetM , ' shSetMin ,\n\n' shPendCal0 , ' shCal0 ,\n' shPendCalH , ' shCalH , \n' shPendCalM , ' shCalM , \n' shPendCalS , ' shCalS , \n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"9f236f3f0ec56c76aca225d28ad5ff0ce6ccd77b","subject":"LOG2 ( n -- n log2_n ) -> ( n -- log2_n )","message":"LOG2 ( n -- n log2_n ) -> ( n -- log2_n )\n","repos":"bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas","old_file":"KataDiversion.fth","new_file":"KataDiversion.fth","new_contents":"\\ KataDiversion in Forth\n\n\\ -- utils\n\n\\ empty the stack\n: EMPTY\n DEPTH 0 <> IF BEGIN\n DROP DEPTH 0 =\n UNTIL\n THEN ;\n\n\\ power\n: ** ( n1 n2 -- n1_pow_n2 ) 1 SWAP ?DUP IF 0 DO OVER * LOOP THEN NIP ;\n\n\\ test if the top is a negative number\n: ?NEG ( n -- bool ) DUP 0= IF -1 ELSE DUP ABS <> THEN ;\n\n\\ log2 (integer)\n: LOG2 ( n -- log2_n ) DUP 1 < IF 1 ABORT\" Log2 need a positive value.\"\n ELSE DUP 1 = IF 0\n ELSE\n 1 >R\n BEGIN ( n |R: i)\n DUP DUP 2 I ( n n n 2 i |R: i)\n ** ( n n n 2**i )\n - ( n n n-2**i )\n 2 * ( n n 2*[n-2**i])\n R> 1 + >R ( \u2026 |R: i+1)\n > ( n n>2*[n-2**i] )\n UNTIL\n R> 1 -\n THEN\n THEN NIP ;\n\n\\ decimal to binary\n\\ e.g. : ( 11 -- 1 0 1 1 )\n\\ FIXME n DEC2BIN seems to give the binary value of n-1\n: DEC2BIN ( n -- n1 n2 n3 \u2026 ) DUP LOG2 2 SWAP ** >R ( n |R: X = 2 ** n.log2 )\n BEGIN\n DUP I - 0 > IF 1 SWAP I - ( 1 n-X )\n ELSE 0 SWAP ( 0 n )\n THEN\n I 1 =\n R> 2 \/ >R ( \u2026 | X\/2 )\n UNTIL\n R> 2DROP\n ;\n\n\\ -- kata\n\n\\ test if the given N has two adjacent 1 bits\n\\ e.g. : 1011 -> -1\n\\ 1001 -> 0\n: ?TWO-ADJACENT-1-BITS ( n -- bool ) ( TODO ) ;\n\n\\ return the maximum number which can be made with N (given number) bits\n: ?MAX-NB ( n -- m ) DUP ?NEG IF DROP 0 ( 0 )\n ELSE \n DUP IF DUP 2 SWAP ** NIP ( 2**n )\n THEN\n THEN ;\n\n\n\\ return the number of numbers which can be made with N (given number) bits\n\\ or less, and which have not two adjacent 1 bits.\n\\ see http:\/\/www.codekata.com\/2007\/01\/code_kata_fifte.html\n: ?HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS ( n -- m ) ( TODO ) ;\n","old_contents":"\\ KataDiversion in Forth\n\n\\ -- utils\n\n\\ empty the stack\n: EMPTY\n DEPTH 0 <> IF BEGIN\n DROP DEPTH 0 =\n UNTIL\n THEN ;\n\n\\ power\n: ** ( n1 n2 -- n1_pow_n2 ) 1 SWAP ?DUP IF 0 DO OVER * LOOP THEN NIP ;\n\n\\ test if the top is a negative number\n: ?NEG ( n -- bool ) DUP 0= IF -1 ELSE DUP ABS <> THEN ;\n\n\\ log2 (integer)\n: LOG2 ( n -- n log2_n ) DUP 1 < IF 1 ABORT\" Log2 need a positive value.\"\n ELSE DUP 1 = IF 0\n ELSE\n 1 >R\n BEGIN ( n |R: i)\n DUP DUP 2 I ( n n n 2 i |R: i)\n ** ( n n n 2**i )\n - ( n n n-2**i )\n 2 * ( n n 2*[n-2**i])\n R> 1 + >R ( \u2026 |R: i+1)\n > ( n n>2*[n-2**i] )\n UNTIL\n R> 1 -\n THEN\n THEN ;\n\n\\ decimal to binary\n\\ e.g. : ( 11 -- 1 0 1 1 )\n\\ FIXME n DEC2BIN seems to give the binary value of n-1\n: DEC2BIN ( n -- n1 n2 n3 \u2026 ) DUP LOG2 2 SWAP ** >R ( n |R: X = 2 ** n.log2 )\n BEGIN\n DUP I - 0 > IF 1 SWAP I - ( 1 n-X )\n ELSE 0 SWAP ( 0 n )\n THEN\n I 1 =\n R> 2 \/ >R ( \u2026 | X\/2 )\n UNTIL\n R> 2DROP\n ;\n\n\\ -- kata\n\n\\ test if the given N has two adjacent 1 bits\n\\ e.g. : 1011 -> -1\n\\ 1001 -> 0\n: ?TWO-ADJACENT-1-BITS ( n -- bool ) ( TODO ) ;\n\n\\ return the maximum number which can be made with N (given number) bits\n: ?MAX-NB ( n -- m ) DUP ?NEG IF DROP 0 ( 0 )\n ELSE \n DUP IF DUP 2 SWAP ** NIP ( 2**n )\n THEN\n THEN ;\n\n\n\\ return the number of numbers which can be made with N (given number) bits\n\\ or less, and which have not two adjacent 1 bits.\n\\ see http:\/\/www.codekata.com\/2007\/01\/code_kata_fifte.html\n: ?HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS ( n -- m ) ( TODO ) ;\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"b4ce2dc18ed374eb5f05c4c5789e0558446b5177","subject":"MAXPOW2 implemented, LOG2 removed","message":"MAXPOW2 implemented, LOG2 removed\n","repos":"bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas","old_file":"KataDiversion.fth","new_file":"KataDiversion.fth","new_contents":"\\ KataDiversion in Forth\n\n\\ -- utils\n\n\\ empty the stack\n: EMPTY\n DEPTH 0 <> IF BEGIN\n DROP DEPTH 0 =\n UNTIL\n THEN ;\n\n\\ power\n: ** ( n1 n2 -- n1_pow_n2 ) 1 SWAP ?DUP IF 0 DO OVER * LOOP THEN NIP ;\n\n\\ test if the top is a negative number\n: ?NEG ( n -- bool ) DUP 0= IF -1 ELSE DUP ABS <> THEN ;\n\n\\ compute the highest power of 2 below N.\n\\ e.g. : 31 -> 16, 4 -> 4\n: MAXPOW2 ( n -- log2_n ) DUP 1 < IF 1 ABORT\" Maxpow2 need a positive value.\"\n ELSE DUP 1 = IF 1\n ELSE\n 1 >R\n BEGIN ( n |R: i=1)\n DUP DUP I - 2 *\n ( n n 2*[n-i])\n R> 2 * >R ( \u2026 |R: i*2)\n > ( n n>2*[n-i] )\n UNTIL\n R> 2 \/\n THEN\n THEN NIP ;\n\n\\ -- kata\n\n\\ test if the given N has two adjacent 1 bits\n\\ e.g. : 11 -> 1011 -> -1\n\\ 9 -> 1001 -> 0\n: ?TWO-ADJACENT-1-BITS ( n -- bool )\n \\ the word uses the following algorithm :\n \\ (stack|return stack)\n \\ ( A N | X ) A: 0, X: N LOG2\n \\ loop: if N-X > 0 then A++ else A=0 ; X \/= 2\n \\ return -1 if A=2\n \\ if X=1 end loop and return 0\n 0 SWAP DUP DUP 0 <> IF\n MAXPOW2 >R\n BEGIN\n DUP I - 0 >= IF \n SWAP DUP 1 = IF 1+ SWAP\n ELSE 1+ SWAP I -\n THEN\n ELSE NIP 0 SWAP\n THEN\n OVER\n 2 =\n I 1 = OR\n R> 2 \/ >R\n UNTIL\n R> 2DROP\n 2 =\n THEN ;\n\n\\ return the maximum number which can be made with N (given number) bits\n: ?MAX-NB ( n -- m ) DUP ?NEG IF DROP 0 ( 0 )\n ELSE \n DUP IF DUP 2 SWAP ** NIP ( 2**n )\n THEN\n THEN ;\n\n\n\\ return the number of numbers which can be made with N (given number) bits\n\\ or less, and which have not two adjacent 1 bits.\n\\ see http:\/\/www.codekata.com\/2007\/01\/code_kata_fifte.html\n: ?HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS ( n -- m ) ( TODO ) ;\n","old_contents":"\\ KataDiversion in Forth\n\n\\ -- utils\n\n\\ empty the stack\n: EMPTY\n DEPTH 0 <> IF BEGIN\n DROP DEPTH 0 =\n UNTIL\n THEN ;\n\n\\ power\n: ** ( n1 n2 -- n1_pow_n2 ) 1 SWAP ?DUP IF 0 DO OVER * LOOP THEN NIP ;\n\n\\ test if the top is a negative number\n: ?NEG ( n -- bool ) DUP 0= IF -1 ELSE DUP ABS <> THEN ;\n\n\\ log2 (integer)\n\\ TODO remove this word, and add a new word\n\\ which compute the value of ( n LOG2 2 SWAP ** )\n: LOG2 ( n -- log2_n ) DUP 1 < IF 1 ABORT\" Log2 need a positive value.\"\n ELSE DUP 1 = IF 0\n ELSE\n 1 >R\n BEGIN ( n |R: i=1)\n DUP DUP 2 I ** - 2 *\n ( n n 2*[n-2**i])\n R> 1 + >R ( \u2026 |R: i+1)\n > ( n n>2*[n-2**i] )\n UNTIL\n R> 1 -\n THEN\n THEN NIP ;\n\n\\ -- kata\n\n\\ test if the given N has two adjacent 1 bits\n\\ e.g. : 11 -> 1011 -> -1\n\\ 9 -> 1001 -> 0\n: ?TWO-ADJACENT-1-BITS ( n -- bool )\n \\ the word uses the following algorithm :\n \\ (stack|return stack)\n \\ ( A N | X ) A: 0, X: N LOG2\n \\ loop: if N-X > 0 then A++ else A=0 ; X \/= 2\n \\ return -1 if A=2\n \\ if X=1 end loop and return 0\n 0 SWAP DUP DUP 0 <> IF\n LOG2 2 SWAP ** >R\n BEGIN\n DUP I - 0 >= IF \n SWAP DUP 1 = IF 1+ SWAP\n ELSE 1+ SWAP I -\n THEN\n ELSE NIP 0 SWAP\n THEN\n OVER\n 2 =\n I 1 = OR\n R> 2 \/ >R\n UNTIL\n R> 2DROP\n 2 =\n THEN ;\n\n\\ return the maximum number which can be made with N (given number) bits\n: ?MAX-NB ( n -- m ) DUP ?NEG IF DROP 0 ( 0 )\n ELSE \n DUP IF DUP 2 SWAP ** NIP ( 2**n )\n THEN\n THEN ;\n\n\n\\ return the number of numbers which can be made with N (given number) bits\n\\ or less, and which have not two adjacent 1 bits.\n\\ see http:\/\/www.codekata.com\/2007\/01\/code_kata_fifte.html\n: ?HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS ( n -- m ) ( TODO ) ;\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"4895a5f4601027a70f952b8ae5a278c6c74dd329","subject":"asm label prefix","message":"asm label prefix","repos":"cetic\/python-msp430-tools,cetic\/python-msp430-tools,cetic\/python-msp430-tools","old_file":"msp430\/asm\/forth\/_builtins.forth","new_file":"msp430\/asm\/forth\/_builtins.forth","new_contents":"( Implementations of builtins.\n These functions are provided for the host in the msp430.asm.forth module. The\n implementations here are for the target.\n\n vi:ft=forth\n)\n\n( ----- low level supporting functions ----- )\n\nCODE LIT\n .\" \\t decd TOS ; prepare push on stack \\n \"\n .\" \\t mov @IP+, 0(TOS) ; copy value from thread to stack \\n \"\n NEXT\nEND-CODE\n\nCODE BRANCH\n .\" \\t add @IP+, IP \\n \"\n .\" \\t decd IP \\n \"\n NEXT\nEND-CODE-INTERNAL\n\nCODE BRANCH0\n .\" \\t mov @IP+, W ; get offset \\n \"\n .\" \\t tst 0(TOS) ; check TOS \\n \"\n .\" \\t jnz .Lnjmp ; skip next if non zero \\n \"\n .\" \\t decd IP ; offset is relative to position of offset, correct \\n \"\n .\" \\t add W, IP ; adjust IP \\n \"\n.\" .Lnjmp: \"\n DROP-ASM\n NEXT\nEND-CODE-INTERNAL\n\n( ----- Stack ops ----- )\n\nCODE DROP\n .\" \\t incd TOS \" NL\n NEXT\nEND-CODE-INTERNAL\n\nCODE DUP\n .\" \\t decd TOS \" NL\n .\" \\t mov 2(TOS), 0(TOS) \" NL\n NEXT\nEND-CODE-INTERNAL\n\nCODE OVER\n .\" \\t decd TOS \" NL\n .\" \\t mov 4(TOS), 0(TOS) \" NL\n NEXT\nEND-CODE-INTERNAL\n\n( Push a copy of the N'th element )\nCODE PICK ( n - n )\n TOS->R15 ( get element number from stack )\n .\" \\t rla R15 \" NL ( multiply by 2 -> 2 byte \/ cells )\n .\" \\t add TOS, R15 \" NL ( calculate address on stack )\n .\" \\t decd TOS \" NL ( push copy )\n .\" \\t mov 0(R15), 0(TOS) \" NL\n NEXT\nEND-CODE-INTERNAL\n\nCODE SWAP ( y x - x y )\n .\" \\t mov 2(TOS), W \" NL\n .\" \\t mov 0(TOS), 2(TOS) \" NL\n .\" \\t mov W, 0(TOS) \" NL\n NEXT\nEND-CODE-INTERNAL\n\n( ----- MATH ----- )\n\nCODE +\n .\" \\t add 0(TOS), 2(TOS) \" NL\n DROP-ASM\n NEXT\nEND-CODE-INTERNAL\n\nCODE -\n .\" \\t sub 0(TOS), 2(TOS) \" NL\n DROP-ASM\n NEXT\nEND-CODE-INTERNAL\n\n( ----- bit - ops ----- )\nCODE &\n .\" \\t and 0(TOS), 2(TOS) \" NL\n DROP-ASM\n NEXT\nEND-CODE-INTERNAL\n\nCODE |\n .\" \\t bis 0(TOS), 2(TOS) \" NL\n DROP-ASM\n NEXT\nEND-CODE-INTERNAL\n\nCODE ^\n .\" \\t xor 0(TOS), 2(TOS) \" NL\n DROP-ASM\n NEXT\nEND-CODE-INTERNAL\n\nCODE ~\n .\" \\t inv 0(TOS), 2(TOS) \" NL\n DROP-ASM\n NEXT\nEND-CODE-INTERNAL\n\n( ----- Logic ops ----- )\n( include normalize to boolean )\n\nCODE NOT\n .\" \\t tst 0(TOS) \" NL\n .\" \\t jnz .not0 \" NL\n .\" \\t mov \\x23 -1, 0(TOS) \" NL ( replace TOS w\/ result )\n .\" \\t jmp .not2 \" NL\n .\" .not0: \" NL\n .\" \\t mov \\x23 0, 0(TOS) \" NL ( replace TOS w\/ result )\n .\" .not2: \" NL\n NEXT\nEND-CODE-INTERNAL\n\n( ---------------------------------------------------\n \"MIN\" \"\"\"Leave the smaller of two values on the stack\"\"\"\n \"MAX\" \"\"\"Leave the larger of two values on the stack\"\"\"\n \"*\"\n \"\/\"\n \"NEG\"\n \"<<\"\n \">>\"\n \"NOT\"\n \"AND\"\n \"OR\"\n)\n( ----- Compare ----- )\nCODE cmp_set_true ( n - n )\n .\" \\t mov \\x23 -1, 0(TOS) \" NL ( replace argument w\/ result )\n NEXT\nEND-CODE\n\nCODE cmp_set_false\n .\" \\t mov \\x23 0, 0(TOS) \" NL ( replace argument w\/ result )\n NEXT\nEND-CODE\n\n\nCODE cmp_true\n DROP-ASM ( remove 1nd argument )\n .\" \\t mov \\x23 -1, 0(TOS) \" NL ( replace 2nd argument w\/ result )\n NEXT\nEND-CODE\n\nCODE cmp_false\n DROP-ASM ( remove 1nd argument )\n .\" \\t mov \\x23 0, 0(TOS) \" NL ( replace 2nd argument w\/ result )\n NEXT\nEND-CODE\n\n\nCODE <\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(TOS), 2(TOS) \" NL\n .\" \\t jl _cmp_true \" NL\n .\" \\t jmp _cmp_false \" NL\nEND-CODE-INTERNAL\n\nCODE >\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(TOS), 2(TOS) \" NL\n .\" \\t jl _cmp_false \" NL\n .\" \\t jmp _cmp_true \" NL\nEND-CODE-INTERNAL\n\nCODE <=\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(TOS), 2(TOS) \" NL\n .\" \\t jge _cmp_false \" NL\n .\" \\t jmp _cmp_true \" NL\nEND-CODE-INTERNAL\n\nCODE >=\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(TOS), 2(TOS) \" NL\n .\" \\t jge _cmp_true \" NL\n .\" \\t jmp _cmp_false \" NL\nEND-CODE-INTERNAL\n\nCODE ==\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(TOS), 2(TOS) \" NL\n .\" \\t jeq _cmp_true \" NL\n .\" \\t jmp _cmp_false \" NL\nEND-CODE-INTERNAL\n\n( XXX alias for == )\nCODE ==\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(TOS), 2(TOS) \" NL\n .\" \\t jeq _cmp_true \" NL\n .\" \\t jmp _cmp_false \" NL\nEND-CODE-INTERNAL\n\nCODE !=\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(TOS), 2(TOS) \" NL\n .\" \\t jne _cmp_true \" NL\n .\" \\t jmp _cmp_false \" NL\nEND-CODE-INTERNAL\n\n\nCODE 0=\n DEPENDS-ON cmp_set_true\n DEPENDS-ON cmp_set_false\n .\" \\t tst 0(TOS) \" NL\n .\" \\t jz _cmp_set_true \" NL\n .\" \\t jmp _cmp_set_false \" NL\nEND-CODE-INTERNAL\n\nCODE 0>\n DEPENDS-ON cmp_set_true\n DEPENDS-ON cmp_set_false\n .\" \\t tst 0(TOS) \" NL\n .\" \\t jn _cmp_set_false \" NL\n .\" \\t jmp _cmp_set_true \" NL\nEND-CODE-INTERNAL\n","old_contents":"( Implementations of builtins.\n These functions are provided for the host in the msp430.asm.forth module. The\n implementations here are for the target.\n\n vi:ft=forth\n)\n\n( ----- low level supporting functions ----- )\n\nCODE LIT\n .\" \\t decd TOS ; prepare push on stack \\n \"\n .\" \\t mov @IP+, 0(TOS) ; copy value from thread to stack \\n \"\n NEXT\nEND-CODE\n\nCODE BRANCH\n .\" \\t add @IP+, IP \\n \"\n .\" \\t decd IP \\n \"\n NEXT\nEND-CODE-INTERNAL\n\nCODE BRANCH0\n .\" \\t mov @IP+, W ; get offset \\n \"\n .\" \\t tst 0(TOS) ; check TOS \\n \"\n .\" \\t jnz .Lnjmp ; skip next if non zero \\n \"\n .\" \\t decd IP ; offset is relative to position of offset, correct \\n \"\n .\" \\t add W, IP ; adjust IP \\n \"\n.\" .Lnjmp: \"\n DROP-ASM\n NEXT\nEND-CODE-INTERNAL\n\n( ----- Stack ops ----- )\n\nCODE DROP\n .\" \\t incd TOS \" NL\n NEXT\nEND-CODE-INTERNAL\n\nCODE DUP\n .\" \\t decd TOS \" NL\n .\" \\t mov 2(TOS), 0(TOS) \" NL\n NEXT\nEND-CODE-INTERNAL\n\nCODE OVER\n .\" \\t decd TOS \" NL\n .\" \\t mov 4(TOS), 0(TOS) \" NL\n NEXT\nEND-CODE-INTERNAL\n\n( Push a copy of the N'th element )\nCODE PICK ( n - n )\n TOS->R15 ( get element number from stack )\n .\" \\t rla R15 \" NL ( multiply by 2 -> 2 byte \/ cells )\n .\" \\t add TOS, R15 \" NL ( calculate address on stack )\n .\" \\t decd TOS \" NL ( push copy )\n .\" \\t mov 0(R15), 0(TOS) \" NL\n NEXT\nEND-CODE-INTERNAL\n\nCODE SWAP ( y x - x y )\n .\" \\t mov 2(TOS), W \" NL\n .\" \\t mov 0(TOS), 2(TOS) \" NL\n .\" \\t mov W, 0(TOS) \" NL\n NEXT\nEND-CODE-INTERNAL\n\n( ----- MATH ----- )\n\nCODE +\n .\" \\t add 0(TOS), 2(TOS) \" NL\n DROP-ASM\n NEXT\nEND-CODE-INTERNAL\n\nCODE -\n .\" \\t sub 0(TOS), 2(TOS) \" NL\n DROP-ASM\n NEXT\nEND-CODE-INTERNAL\n\n( ----- bit - ops ----- )\nCODE &\n .\" \\t and 0(TOS), 2(TOS) \" NL\n DROP-ASM\n NEXT\nEND-CODE-INTERNAL\n\nCODE |\n .\" \\t bis 0(TOS), 2(TOS) \" NL\n DROP-ASM\n NEXT\nEND-CODE-INTERNAL\n\nCODE ^\n .\" \\t xor 0(TOS), 2(TOS) \" NL\n DROP-ASM\n NEXT\nEND-CODE-INTERNAL\n\nCODE ~\n .\" \\t inv 0(TOS), 2(TOS) \" NL\n DROP-ASM\n NEXT\nEND-CODE-INTERNAL\n\n( ----- Logic ops ----- )\n( include normalize to boolean )\n\nCODE NOT\n .\" \\t tst 0(TOS) \" NL\n .\" \\t jnz .not0 \" NL\n .\" \\t mov \\x23 -1, 0(TOS) \" NL ( replace TOS w\/ result )\n .\" \\t jmp .not2 \" NL\n .\" .not0: \" NL\n .\" \\t mov \\x23 0, 0(TOS) \" NL ( replace TOS w\/ result )\n .\" .not2: \" NL\n NEXT\nEND-CODE-INTERNAL\n\n( ---------------------------------------------------\n \"MIN\" \"\"\"Leave the smaller of two values on the stack\"\"\"\n \"MAX\" \"\"\"Leave the larger of two values on the stack\"\"\"\n \"*\"\n \"\/\"\n \"NEG\"\n \"<<\"\n \">>\"\n \"NOT\"\n \"AND\"\n \"OR\"\n)\n( ----- Compare ----- )\nCODE cmp_set_true ( n - n )\n .\" \\t mov \\x23 -1, 0(TOS) \" NL ( replace argument w\/ result )\n NEXT\nEND-CODE\n\nCODE cmp_set_false\n .\" \\t mov \\x23 0, 0(TOS) \" NL ( replace argument w\/ result )\n NEXT\nEND-CODE\n\n\nCODE cmp_true\n DROP-ASM ( remove 1nd argument )\n .\" \\t mov \\x23 -1, 0(TOS) \" NL ( replace 2nd argument w\/ result )\n NEXT\nEND-CODE\n\nCODE cmp_false\n DROP-ASM ( remove 1nd argument )\n .\" \\t mov \\x23 0, 0(TOS) \" NL ( replace 2nd argument w\/ result )\n NEXT\nEND-CODE\n\n\nCODE <\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(TOS), 2(TOS) \" NL\n .\" \\t jl cmp_true \" NL\n .\" \\t jmp cmp_false \" NL\nEND-CODE-INTERNAL\n\nCODE >\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(TOS), 2(TOS) \" NL\n .\" \\t jl cmp_false \" NL\n .\" \\t jmp cmp_true \" NL\nEND-CODE-INTERNAL\n\nCODE <=\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(TOS), 2(TOS) \" NL\n .\" \\t jge cmp_false \" NL\n .\" \\t jmp cmp_true \" NL\nEND-CODE-INTERNAL\n\nCODE >=\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(TOS), 2(TOS) \" NL\n .\" \\t jge cmp_true \" NL\n .\" \\t jmp cmp_false \" NL\nEND-CODE-INTERNAL\n\nCODE ==\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(TOS), 2(TOS) \" NL\n .\" \\t jeq cmp_true \" NL\n .\" \\t jmp cmp_false \" NL\nEND-CODE-INTERNAL\n\n( XXX alias for == )\nCODE ==\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(TOS), 2(TOS) \" NL\n .\" \\t jeq cmp_true \" NL\n .\" \\t jmp cmp_false \" NL\nEND-CODE-INTERNAL\n\nCODE !=\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(TOS), 2(TOS) \" NL\n .\" \\t jne cmp_true \" NL\n .\" \\t jmp cmp_false \" NL\nEND-CODE-INTERNAL\n\n\nCODE 0=\n DEPENDS-ON cmp_set_true\n DEPENDS-ON cmp_set_false\n .\" \\t tst 0(TOS) \" NL\n .\" \\t jz cmp_set_true \" NL\n .\" \\t jmp cmp_set_false \" NL\nEND-CODE-INTERNAL\n\nCODE 0>\n DEPENDS-ON cmp_set_true\n DEPENDS-ON cmp_set_false\n .\" \\t tst 0(TOS) \" NL\n .\" \\t jn cmp_set_false \" NL\n .\" \\t jmp cmp_set_true \" NL\nEND-CODE-INTERNAL\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"747955699356e2007848e119f5bd4afb76204a6f","subject":"Make wake support a compile-time selection.","message":"Make wake support a compile-time selection.","repos":"rbsexton\/gecko,rbsexton\/gecko,rbsexton\/gecko","old_file":"leopard\/usbforth\/SysCalls.fth","new_file":"leopard\/usbforth\/SysCalls.fth","new_contents":"\\ Wrappers for SAPI functions, ABI 4.0\n\n\\ Note that the system call number is embedded into the instruction,\n\\ so this is not so easily parameterized.\n\n#0 equ SAPI_VEC_VERSION\n#1 equ SAPI_VEC_01_GetRuntimeLinks\n#2 equ SAPI_VEC_02_PutChar\n#3 equ SAPI_VEC_03_GetChar\n#4 equ SAPI_VEC_04_GetCharAvail\n#5 equ SAPI_VEC_05_PutString\n#6 equ SAPI_VEC_06_EOL\n#14 equ SAPI_VEC_14_PetWatchdog\n#15 equ SAPI_VEC_15_GetTimeMS\n\nCODE SAPI-Version \\ -- n\n\\ *G Get the version of the binary ABI in use. \n\tsvc # SAPI_VEC_VERSION \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE GETRUNTIMELINKS \\ type -- n\n\\ *G Get the runtime linking information. Type 0 - A Dynamic linking \n\\ ** table with name, address pairs. Type 1 - A Zero-Terminated Jump table.\n\tmov r0, tos\n\tsvc # SAPI_VEC_01_GetRuntimeLinks \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE (seremitfc) \\ char base --\n\\ *G Service call for a single char - This one has a special name because\n\\ ** It'll be wrapped by something that can respond to the flow control \n\\ ** return code and PAUSE + Retry \n\tmov r0, tos\n\tldr r1, [ psp ], # 4\n\t[defined] SAPIWakeSupport? [if] mov r2, up [else] mov r2, # 0 [then] \n\tsvc # SAPI_VEC_02_PutChar\t\n\tmov tos, r0\n next,\nEND-CODE\n\nCODE (serkeyfc) \\ base -- char \n\\ *G Get a character from the port, or -1 for fail\n\tmov r0, tos\t\n\t[defined] SAPIWakeSupport? [if] mov r1, up [else] mov r1, # 0 [then] \n\tsvc # SAPI_VEC_03_GetChar\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE (serkey?) \\ base -- t\/f\n\\ *G Return true if the given stream has a character avilable to read.\n\\ The call returns the number of chars available. \n\tmov r0, tos\n\tsvc # SAPI_VEC_04_GetCharAvail\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE (sercrfc) \\ base -- return \n\\ *G Send a line terminator to the port. Return 0 for success, -1 for fail.\n\tmov r0, tos\t\n\t[defined] SAPIWakeSupport? [if] mov r1, up [else] mov r1, # 0 [then] \n\tsvc # SAPI_VEC_06_EOL\n\tmov tos, r0\n\tnext,\nEND-CODE\n \n\\ These two can be created from simpler things, and are optional.\n\\ CODE (type) \n\\ END-CODE\n\n\\ CODE (cr) \n\\ END-CODE\n\nCODE PetWatchDog \\ n --\n\\ *G Refresh the watchdog. Pass in a platform-specific number\n\\ ** To specify a timerout (if supported), or zero for the default value. \n\tmov r0, tos\n\tldr r1, [ psp ], # 4\n\tsvc # SAPI_VEC_14_PetWatchdog\n\tldr tos, [ psp ], # 4\n\tnext,\nEND-CODE\n\nCODE TICKS \\ -- n \n\\ *G The current value of the millisecond ticker.\n mov r0, # 0 \\ We want the actual value.\n\tsvc # SAPI_VEC_15_GetTimeMS\n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\n\n\n","old_contents":"\\ Wrappers for SAPI functions, ABI 4.0\n\n\\ Note that the system call number is embedded into the instruction,\n\\ so this is not so easily parameterized.\n\n#0 equ SAPI_VEC_VERSION\n#1 equ SAPI_VEC_01_GetRuntimeLinks\n#2 equ SAPI_VEC_02_PutChar\n#3 equ SAPI_VEC_03_GetChar\n#4 equ SAPI_VEC_04_GetCharAvail\n#5 equ SAPI_VEC_05_PutString\n#6 equ SAPI_VEC_06_EOL\n#14 equ SAPI_VEC_14_PetWatchdog\n#15 equ SAPI_VEC_15_GetTimeMS\n\nCODE SAPI-Version \\ -- n\n\\ *G Get the version of the binary ABI in use. \n\tsvc # SAPI_VEC_VERSION \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE GETRUNTIMELINKS \\ type -- n\n\\ *G Get the runtime linking information. Type 0 - A Dynamic linking \n\\ ** table with name, address pairs. Type 1 - A Zero-Terminated Jump table.\n\tmov r0, tos\n\tsvc # SAPI_VEC_01_GetRuntimeLinks \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE (seremitfc) \\ char base --\n\\ *G Service call for a single char - This one has a special name because\n\\ ** It'll be wrapped by something that can respond to the flow control \n\\ ** return code and PAUSE + Retry \n\tmov r0, tos\n\tldr r1, [ psp ], # 4\n\tmov r2, # 0 \\ Don't request a wake.\n\tsvc # SAPI_VEC_02_PutChar\t\n\tmov tos, r0\n next,\nEND-CODE\n\nCODE (serkeyfc) \\ base -- char \n\\ *G Get a character from the port, or -1 for fail\n\tmov r0, tos\t\n\tmov r1, up \\ Block!\n\tsvc # SAPI_VEC_03_GetChar\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE (serkey?) \\ base -- t\/f\n\\ *G Return true if the given stream has a character avilable to read.\n\\ The call returns the number of chars available. \n\tmov r0, tos\n\tsvc # SAPI_VEC_04_GetCharAvail\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE (sercrfc) \\ base -- return \n\\ *G Send a line terminator to the port. Return 0 for success, -1 for fail.\n\tmov r0, tos\t\n\tmov r1, up \\ Block!\n\tsvc # SAPI_VEC_06_EOL\n\tmov tos, r0\n\tnext,\nEND-CODE\n \n\\ These two can be created from simpler things, and are optional.\n\\ CODE (type) \n\\ END-CODE\n\n\\ CODE (cr) \n\\ END-CODE\n\nCODE PetWatchDog \\ n --\n\\ *G Refresh the watchdog. Pass in a platform-specific number\n\\ ** To specify a timerout (if supported), or zero for the default value. \n\tmov r0, tos\n\tldr r1, [ psp ], # 4\n\tsvc # SAPI_VEC_14_PetWatchdog\n\tldr tos, [ psp ], # 4\n\tnext,\nEND-CODE\n\nCODE TICKS \\ -- n \n\\ *G The current value of the millisecond ticker.\n mov r0, # 0 \\ We want the actual value.\n\tsvc # SAPI_VEC_15_GetTimeMS\n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\n\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"b044bedbac0fbf5018a67f4ab9d7b4aeb1d7b3fd","subject":"LOG2 tests removed, MAXPOW2 tests added","message":"LOG2 tests removed, MAXPOW2 tests added\n","repos":"bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas","old_file":"KataDiversion_tests.fth","new_file":"KataDiversion_tests.fth","new_contents":"\\ KataDiversion tests, in Forth\n\\ running tests:\n\\ gforth KataDiversion_tests.fth -e bye\n\nREQUIRE KataDiversion.fth\n\nVARIABLE ASSERT-COUNT\n\n: ASSERTS-INIT ( -- )\n 0 ASSERT-COUNT ! ;\n\n: ASSERTS-RESULT ( -- )\n ASSERT-COUNT @ . .\" assertions successfully passed.\" CR ;\n\n\\ destructive assert-equal\n: ASSERT-EQUAL-D ( n1 n2 -- )\n <> IF 1 ABORT\" AssertEqual: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-equal\n: ASSERT-EQUAL ( n1 n2 -- n1 n2 )\n 2DUP ASSERT-EQUAL-D ;\n\n\\ destructive assert-true\n: ASSERT-TRUE-D ( n -- )\n 0 = IF 1 ABORT\" AssertTrue: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-true\n: ASSERT-TRUE ( n -- n )\n DUP ASSERT-TRUE-D ;\n\n\\ destructive assert-false\n: ASSERT-False-D ( n -- )\n 0 <> IF 1 ABORT\" AssertFalse: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-false\n: ASSERT-FALSE ( n -- n )\n DUP ASSERT-FALSE-D ;\n\n\\ ---- tests ----\n\nASSERTS-INIT\n\n\\ ?EMPTY\nEMPTY DEPTH 0 ASSERT-EQUAL-D\nEMPTY EMPTY DEPTH 0 ASSERT-EQUAL-D\n0 EMPTY DEPTH 0 ASSERT-EQUAL-D\n1 2 3 4 EMPTY DEPTH 0 ASSERT-EQUAL-D\n\n\\ ?NEGATIVE\n-1 ?NEG ASSERT-TRUE-D\n 0 ?NEG ASSERT-TRUE-D\n 1 ?NEG ASSERT-FALSE-D\n\n\\ ?MAX-NB\n-1 ?MAX-NB 0 ASSERT-EQUAL-D\n 0 ?MAX-NB 0 ASSERT-EQUAL-D\n 1 ?MAX-NB 2 ASSERT-EQUAL-D\n 2 ?MAX-NB 4 ASSERT-EQUAL-D\n 3 ?MAX-NB 8 ASSERT-EQUAL-D\n\n\\ MAXPOW2\n 1 MAXPOW2 1 ASSERT-EQUAL-D\n 2 MAXPOW2 2 ASSERT-EQUAL-D\n 3 MAXPOW2 2 ASSERT-EQUAL-D\n 4 MAXPOW2 4 ASSERT-EQUAL-D\n 5 MAXPOW2 4 ASSERT-EQUAL-D\n 8 MAXPOW2 8 ASSERT-EQUAL-D\n 42 MAXPOW2 32 ASSERT-EQUAL-D\n2000 MAXPOW2 1024 ASSERT-EQUAL-D\n\n\n\\ ?TWO-ADJACENT-1-BITS\n 1 ?TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n 2 ?TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n 3 ?TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n 6 ?TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n 7 ?TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n 8 ?TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n 11 ?TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n 65 ?TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n3072 ?TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n\nASSERTS-RESULT\n\\ ---------\n\n\n","old_contents":"\\ KataDiversion tests, in Forth\n\\ running tests:\n\\ gforth KataDiversion_tests.fth -e bye\n\nREQUIRE KataDiversion.fth\n\nVARIABLE ASSERT-COUNT\n\n: ASSERTS-INIT ( -- )\n 0 ASSERT-COUNT ! ;\n\n: ASSERTS-RESULT ( -- )\n ASSERT-COUNT @ . .\" assertions successfully passed.\" CR ;\n\n\\ destructive assert-equal\n: ASSERT-EQUAL-D ( n1 n2 -- )\n <> IF 1 ABORT\" AssertEqual: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-equal\n: ASSERT-EQUAL ( n1 n2 -- n1 n2 )\n 2DUP ASSERT-EQUAL-D ;\n\n\\ destructive assert-true\n: ASSERT-TRUE-D ( n -- )\n 0 = IF 1 ABORT\" AssertTrue: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-true\n: ASSERT-TRUE ( n -- n )\n DUP ASSERT-TRUE-D ;\n\n\\ destructive assert-false\n: ASSERT-False-D ( n -- )\n 0 <> IF 1 ABORT\" AssertFalse: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-false\n: ASSERT-FALSE ( n -- n )\n DUP ASSERT-FALSE-D ;\n\n\\ ---- tests ----\n\nASSERTS-INIT\n\n\\ ?EMPTY\nEMPTY DEPTH 0 ASSERT-EQUAL-D\nEMPTY EMPTY DEPTH 0 ASSERT-EQUAL-D\n0 EMPTY DEPTH 0 ASSERT-EQUAL-D\n1 2 3 4 EMPTY DEPTH 0 ASSERT-EQUAL-D\n\n\\ ?NEGATIVE\n-1 ?NEG ASSERT-TRUE-D\n 0 ?NEG ASSERT-TRUE-D\n 1 ?NEG ASSERT-FALSE-D\n\n\\ ?MAX-NB\n-1 ?MAX-NB 0 ASSERT-EQUAL-D\n 0 ?MAX-NB 0 ASSERT-EQUAL-D\n 1 ?MAX-NB 2 ASSERT-EQUAL-D\n 2 ?MAX-NB 4 ASSERT-EQUAL-D\n 3 ?MAX-NB 8 ASSERT-EQUAL-D\n\n\\ LOG2\n 1 LOG2 0 ASSERT-EQUAL-D\n 2 LOG2 1 ASSERT-EQUAL-D\n 3 LOG2 1 ASSERT-EQUAL-D\n 4 LOG2 2 ASSERT-EQUAL-D\n 5 LOG2 2 ASSERT-EQUAL-D\n 8 LOG2 3 ASSERT-EQUAL-D\n42 LOG2 5 ASSERT-EQUAL-D\n\n 1 ?TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n 2 ?TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n 3 ?TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n 6 ?TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n 7 ?TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n 8 ?TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n 11 ?TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n 65 ?TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n3072 ?TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n\nASSERTS-RESULT\n\\ ---------\n\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"bc5f5044cc7118b308b8ddb373694867f246076e","subject":"Fix duplicate code and bottom-right-valid constraint.","message":"Fix duplicate code and bottom-right-valid constraint.\n","repos":"Tim-Tom\/scratch,Tim-Tom\/scratch,Tim-Tom\/scratch,Tim-Tom\/scratch,Tim-Tom\/scratch,Tim-Tom\/scratch,Tim-Tom\/scratch,Tim-Tom\/scratch,Tim-Tom\/scratch,Tim-Tom\/scratch","old_file":"magic-puzzle\/magic-puzzle.fth","new_file":"magic-puzzle\/magic-puzzle.fth","new_contents":"3 constant width\n21 constant goal\nwidth 1- constant wm\nwidth 1+ constant wp\nwidth width * constant size\n\ncreate choices 3 , 4 , 5 ,\n 6 , 7 , 8 ,\n 9 , 10 , 11 ,\n\nvariable picked size allot\nvariable additional-constraints size cells allot\n\n: clear-picked\n size\n begin\n 1- dup 0>= while\n dup picked + 0 swap C!\n repeat\n drop ;\n\n: print-picked\n 9 0 do\n i picked + C@ .\n loop ;\n\n\nvariable a size cells allot\n\n: choice-search\n 0\n begin\n dup size < while\n choices over cells + @\n rot tuck = if\n drop -1 exit\n endif\n swap 1+\n repeat\n 2drop 0 ;\n\n: reverse-cross-valid\n 0\n wm wp * wm do\n a i cells + @ +\n wm +loop\n goal = ;\n\n: cross-valid\n 0\n size 0 do\n a i cells + @ +\n wp +loop\n goal = ;\n \n: bottom-row-valid\n 0\n size size width - do\n a i cells + @ +\n loop\n goal = ;\n\n: bottom-right-valid\n bottom-row-valid if\n cross-valid\n else\n 0\n endif ;\n\n0 VALUE pick-next-ref\n\n: execute-predicate?\n dup 0<> if\n execute\n else\n drop -1\n endif ;\n\n: pick-internal\n size 0 do\n dup cells a + choices i cells + @ swap !\n i picked + C@ 0= if\n dup cells additional-constraints + @ execute-predicate? if\n 1 i picked + C!\n dup pick-next-ref execute\n 0 i picked + C!\n endif\n endif\n loop\n drop ;\n\n: pick-right\n 0 over dup dup width mod - do\n a i cells + @ +\n loop\n goal swap - \n over over swap cells a + !\n choice-search if\n dup picked + C@ 0= if\n over cells additional-constraints + @ execute-predicate? if\n 1 over picked + C!\n over pick-next-ref execute\n 0 swap picked + C!\n else\n drop\n endif\n else\n drop\n endif\n endif\n drop ;\n\n: pick-bottom\n 0 over dup width mod do\n a i cells + @ +\n width +loop\n goal swap -\n over over swap cells a + !\n choice-search if\n dup picked + C@ 0= if\n over cells additional-constraints + @ execute-predicate? if\n 1 over picked + C!\n over pick-next-ref execute\n 0 swap picked + C!\n else\n drop\n endif\n else\n drop\n endif\n endif\n drop ;\n\ncreate solution-count 0 ,\n\n: solution\n solution-count @ 1+ dup solution-count !\n .\" --- Solution \" . .\" ---\" CR\n size 0 do\n a i cells + @ .\n i 3 mod 2 = if CR endif\n loop ;\n\n: print-right-internal\n dup width mod wm = if\n .\" pick-right \" .\n else\n .\" pick-internal \" .\n endif ;\n\n: print-next\n dup . .\" -> \"\n dup size 1- = if\n drop .\" solution\"\n else\n dup width wm * >= if\n wm -\n print-right-internal\n else\n dup width dup 2 - * >= if\n width +\n .\" pick-bottom \" .\n else\n 1+\n print-right-internal\n endif\n endif\n endif ;\n\n: pick-right-internal\n dup width mod wm = if\n pick-right\n else\n pick-internal\n endif ;\n\n: pick-next\n dup size 1- = if\n drop solution\n else\n dup width wm * >= if\n wm -\n pick-right-internal\n else\n dup width dup 2 - * >= if\n width +\n pick-bottom\n else\n 1+\n pick-right-internal\n endif\n endif\n endif ;\n\n' pick-next TO pick-next-ref\n\n: init-board\n size 0 do\n i 1+ a i cells + !\n loop ;\n\n: clear-constraints\n size 0 do\n 0 additional-constraints i cells + !\n loop ;\n\n\nclear-constraints\n' reverse-cross-valid additional-constraints size width - width - 1+ cells + !\n' bottom-right-valid additional-constraints size 1- cells + !\n\n: solve-puzzle\n clear-picked init-board 0 solution-count !\n 0 pick-internal ;\n","old_contents":"3 constant width\n21 constant goal\nwidth 1- constant wm\nwidth 1+ constant wp\nwidth width * constant size\n\ncreate choices 3 , 4 , 5 ,\n 6 , 7 , 8 ,\n 9 , 10 , 11 ,\n\nvariable picked size allot\nvariable additional-constraints size allot\n\n: clear-picked\n size\n begin\n 1- dup 0>= while\n dup picked + 0 swap C!\n repeat\n drop ;\n\n: print-picked\n 9 0 do\n i picked + C@ .\n loop ;\n\n\nvariable a size cells allot\n\n: choice-search\n 0\n begin\n dup size < while\n choices over cells + @\n rot tuck = if\n drop -1 exit\n endif\n swap 1+\n repeat\n 2drop 0 ;\n\n: reverse-cross-valid\n 0\n wm wp * wm do\n a i cells + @ +\n wm +loop\n goal = ;\n\n: cross-valid\n 0\n size 0 do\n a i cells + @ +\n wp +loop\n goal = ;\n \n: bottom-row-valid\n 0\n size size width - do\n a i cells + @ +\n loop\n goal = ;\n\n: bottom-right-valid\n bottom-row-valid if\n -1\n else\n cross-valid\n endif ;\n\n0 VALUE pick-next-ref\n\n: execute-predicate?\n dup 0<> if\n execute\n else\n drop -1\n endif ;\n\n: pick-internal\n size 0 do\n dup cells a + choices i cells + @ swap !\n i picked + C@ 0= if\n dup cells additional-constraints + @ execute-predicate? if\n 1 i picked + C!\n dup pick-next-ref execute\n 0 i picked + C!\n endif\n endif\n loop\n drop ;\n\n: pick-right\n 0 over dup dup width mod - do\n a i cells + @ +\n loop\n goal swap - \n over over swap cells a + !\n choice-search if\n dup picked + C@ 0= if\n over cells additional-constraints + @ execute-predicate? if\n 1 over picked + C!\n over pick-next-ref execute\n 0 swap picked + C!\n else\n drop\n endif\n 1 over picked + C!\n over pick-next-ref execute\n 0 swap picked + C!\n else\n drop\n endif\n endif\n drop ;\n\n: pick-bottom\n 0 over dup width mod do\n a i cells + @ +\n width +loop\n goal swap -\n over over swap cells a + !\n choice-search if\n dup picked + C@ 0= if\n over cells additional-constraints + @ execute-predicate? if\n 1 over picked + C!\n over pick-next-ref execute\n 0 swap picked + C!\n else\n drop\n endif\n else\n drop\n endif\n endif\n drop ;\n\ncreate solution-count 0 ,\n\n: solution\n solution-count @ 1+ dup solution-count !\n .\" --- Solution \" . .\" ---\" CR\n size 0 do\n a i cells + @ .\n i 3 mod 2 = if CR endif\n loop ;\n\n: print-right-internal\n dup width mod wm = if\n .\" pick-right \" .\n else\n .\" pick-internal \" .\n endif ;\n\n: print-next\n dup . .\" -> \"\n dup size 1- = if\n drop .\" solution\"\n else\n dup width wm * >= if\n wm -\n print-right-internal\n else\n dup width dup 2 - * >= if\n width +\n .\" pick-bottom \" .\n else\n 1+\n print-right-internal\n endif\n endif\n endif ;\n\n: pick-right-internal\n dup width mod wm = if\n pick-right\n else\n pick-internal\n endif ;\n\n: pick-next\n dup size 1- = if\n drop solution\n else\n dup width wm * >= if\n wm -\n pick-right-internal\n else\n dup width dup 2 - * >= if\n width +\n pick-bottom\n else\n 1+\n pick-right-internal\n endif\n endif\n endif ;\n\n' pick-next TO pick-next-ref\n\n: init-board\n size 0 do\n i 1+ a i cells + !\n loop ;\n\n: clear-constraints\n size 0 do\n 0 additional-constraints i cells + !\n loop ;\n\n\nclear-constraints\n' reverse-cross-valid additional-constraints size width - width - 1+ cells + !\n' bottom-right-valid additional-constraints size 1- cells + !\n\n: solve-puzzle\n clear-picked init-board 0 solution-count !\n 0 pick-internal ;\n","returncode":0,"stderr":"","license":"unlicense","lang":"Forth"} {"commit":"f7e06bde0896494c9aa7c1df686a1ff0c6e60645","subject":"A better name.","message":"A better name.","repos":"rbsexton\/gecko,rbsexton\/gecko,rbsexton\/gecko","old_file":"zero\/clock-umb\/forth\/Clock.fth","new_file":"zero\/clock-umb\/forth\/Clock.fth","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"mit","lang":"Forth"} {"commit":"5dcf88a08ed41a44cf6388ef5904841fc08725be","subject":"Postpone IS...","message":"Postpone IS...\n","repos":"rm-hull\/byok3,rm-hull\/byok3","old_file":"core\/src\/main\/resources\/forth\/system.fth","new_file":"core\/src\/main\/resources\/forth\/system.fth","new_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\\n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n\n: COUNT dup 1+ swap c@ ;\n\n\\ Miscellaneous support words\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: <= ( a b -- f , true if A <= b ) > 0= ;\n: >= ( a b -- f , true if A >= b ) < 0= ;\n: NOT ( n -- !n , logical negation ) 0= ;\n: DNEGATE ( d -- -d , negate by doing 0-d )\n 0 swap -\n;\n: CELL+ ( n -- n+cell ) cell + ;\n: CELL- ( n -- n-cell ) cell - ;\n: CELL* ( n -- n*cell ) cells ;\n\n: CHAR+ ( n -- n+size_of_char ) 1+ ;\n: CHARS ( n -- n*size_of_char, don't do anything ) ; immediate\n\n\\ useful stack manipulation words\n: -ROT ( a b c -- c a b ) rot rot ;\n: 3DUP ( a b c -- a b c a b c ) 2 pick 2 pick 2 pick ;\n\n\\ ------------------------------------------------------------------\n: ID. ( nfa -- ) count 31 and type ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: PAD ( -- addr ) here 128 + ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n\n: BETWEEN ( n lo hi -- flag , true if between lo & hi )\n >r over r> > >r\n < r> or 0=\n;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: ? ( -- ) @ . ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ ' (lit) , cell 1- , ] +\n [ ' (lit) , cell 1- invert , ] and ;\n\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n: ALLOT ( nbytes -- , allot space in dictionary ) dp +! align ;\n\n: C, ( c -- ) here c! 1 dp +! ;\n\\ : W, ( w -- ) dp @ even-up dup dp ! w! 2 dp +! ;\n\\ : , ( n -- , lay into dictionary ) align here ! cell allot ;\n\n: SEE ( -- )\n ' dup\n >body swap >size\n disassemble ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token )\n [compile] literal ( compile a call to literal )\n ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick )\n ?comp ' [compile] literal\n; immediate\n\n: (DOES>) ( xt -- , modify previous definition to execute code at xt )\n latest >body \\ get address of code for new word\n 3 cell* + \\ offset to EXIT cell in create word\n ! \\ store execution token of DOES> code in new word\n;\n\n: DOES> ( -- , define execution code for CREATE word )\n 0 [compile] literal \\ dummy literal to hold xt\n here cell- \\ address of zero in literal\n compile (does>) \\ call (DOES>) from new creation word\n\t\t>r \\ move addrz to return stack so ; doesn't see stack garbage\n [compile] ; \\ terminate part of code before does>\n\t\tr>\n :noname ( addrz xt )\n compile rdrop \\ drop a stack frame (call becomes goto)\n swap ! \\ save execution token in literal\n; immediate\n\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 )\n swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 )\n dup cell+ @ swap @ ;\n\n: 2* ( n -- n*2 )\n 2 *\n;\n: 2\/ ( n -- n\/2 )\n 2 \/\n;\n\n\n\\ define some useful constants ------------------------------\n1 0= constant FALSE\n0 0= constant TRUE\n32 constant BL\n\n\\ Stack data structure ----------------------------------------\n\\ This is a general purpose stack utility used to implement necessary\n\\ stacks for the compiler or the user. Not real fast.\n\\ These stacks grow up which is different then normal.\n\\ cell 0 - stack pointer, offset from pfa of word\n\\ cell 1 - limit for range checking\n\\ cell 2 - first data location\n\n: :STACK ( #cells -- )\n CREATE 2 cells , ( offset of first data location )\n dup , ( limit for range checking, not currently used )\n cells cell+ allot ( allot an extra cell for safety )\n;\n\n: >STACK ( n stack -- , push onto stack, postincrement )\n dup @ 2dup cell+ swap ! ( -- n stack offset )\n + !\n;\n\n: STACK> ( stack -- n , pop , predecrement )\n dup @ cell- 2dup swap !\n + @\n;\n\n: STACK@ ( stack -- n , copy )\n dup @ cell- + @\n;\n\n: STACK.PICK ( index stack -- n , grab Nth from top of stack )\n dup @ cell- +\n swap cells - \\ offset for index\n @\n;\n: STACKP ( stack -- ptr , to next empty location on stack )\n\tdup @ +\n;\n\n: 0STACKP ( stack -- , clear stack)\n 8 swap !\n;\n\n32 :stack ustack\nustack 0stackp\n\n\\ Define JForth like words.\n: >US ustack >stack ;\n: US> ustack stack> ;\n: US@ ustack stack@ ;\n: 0USP ustack 0stackp ;\n\n\n\n\\ DO LOOP ------------------------------------------------\n\n3 constant do_flag\n4 constant leave_flag\n5 constant ?do_flag\n\n: DO ( -- , loop-back do_flag jump-from ?do_flag )\n ?comp\n compile (do)\n here >us do_flag >us ( for backward branch )\n; immediate\n\n: ?DO ( -- , loop-back do_flag jump-from ?do_flag , on user stack )\n ?comp\n ( leave address to set for forward branch )\n compile (?do)\n here 0 ,\n here >us do_flag >us ( for backward branch )\n >us ( for forward branch ) ?do_flag >us\n; immediate\n\n: LEAVE ( -- addr leave_flag )\n compile (leave)\n here 0 , >us\n leave_flag >us\n; immediate\n\n: LOOP-FORWARD ( -us- jump-from ?do_flag -- )\n BEGIN\n us@ leave_flag =\n us@ ?do_flag =\n OR\n WHILE\n us> leave_flag =\n IF\n us> here over - cell+ swap !\n ELSE\n us> dup\n here swap -\n cell+ swap !\n THEN\n REPEAT\n;\n\n: LOOP-BACK ( loop-addr do_flag -us- )\n us> do_flag ?pairs\n us> here - here\n !\n cell allot\n;\n\n: LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (loop)\n loop-forward loop-back\n; immediate\n\n\\ : DOTEST 5 0 do 333 . loop 888 . ;\n\\ : ?DOTEST0 0 0 ?do 333 . loop 888 . ;\n\\ : ?DOTEST1 5 0 ?do 333 . loop 888 . ;\n\n: +LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (+loop)\n loop-forward loop-back\n; immediate\n\n: UNLOOP ( loop-sys -r- )\n r> \\ save return pointer\n rdrop rdrop\n >r\n;\n\n\n: RECURSE ( ? -- ? , call the word currently being defined )\n latest compile,\n; immediate\n\n: SPACE bl emit ;\n: 0SP depth 0 ?do drop loop ;\n\n\\ : >NEWLINE ( -- , CR if needed )\n\\ out @ 0>\n\\ IF cr\n\\ THEN\n\\ ;\n\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 ) swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 ) dup cell+ @ swap @ ;\n\n: DABS ( d -- |d| )\n dup 0<\n IF dnegate\n THEN\n;\n\n: S>D ( s -- d , extend signed single precision to double )\n dup 0<\n IF -1\n ELSE 0\n THEN\n;\n\n: D>S ( d -- s ) drop ;\n\n: PARSE-WORD ( \"name\" -- c-addr u ) bl parse ;\n: \/STRING ( addr len n -- addr' len' ) over min rot over + -rot - ;\n: PLACE ( addr len to -- , move string ) 3dup 1+ swap cmove c! drop ;\n\n: ASCII ( -- char, state smart )\n bl parse drop c@\n state @ 1 =\n IF [compile] literal\n ELSE\n THEN\n; immediate\n\n: CHAR ( -- char , interpret mode ) bl parse drop c@ ;\n: [CHAR] ( -- char , for compile mode )\n char [compile] literal\n; immediate\n\n: $TYPE ( $string -- ) count type ;\n: 'word ( -- addr ) here ;\n\n: EVEN ( addr -- addr' ) dup 1 and + ;\n\n: (C\") ( -- $addr ) r> dup count + aligned >r ;\n: (S\") ( -- c-addr cnt ) r> count 2dup + aligned >r ;\n: (.\") ( -- , type following string ) r> count 2dup + aligned >r type ;\n: \", ( addr len -- , place string into dict ) tuck 'word place 1+ allot align ;\n: ,\" ( -- ) [char] \" parse \", ;\n\n: .( ( --, type string delimited by parens )\n [char] ) parse type\n; immediate\n\n: .\" ( -- , type string )\n state @ 1 =\n IF compile (.\") ,\"\n ELSE [char] \" parse type\n THEN\n; immediate\n\n: .' ( -- , type string delimited by single quote )\n state @\n IF compile (.\") [char] ' parse \",\n ELSE [char] ' parse type\n THEN\n; immediate\n\n: C\" ( -- addr , return string address, ANSI )\n state @\n IF compile (c\") ,\"\n ELSE [char] \" parse pad place pad\n THEN\n; immediate\n\n: S\" ( -- , -- addr , return string address, ANSI )\n state @\n IF compile (s\") ,\"\n ELSE [char] \" parse pad place pad count\n THEN\n; immediate\n\n: \" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n: P\" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n\n: \"\" ( -- addr )\n state @\n IF\n compile (C\")\n bl parse-word \",\n ELSE\n bl parse-word pad place pad\n THEN\n; immediate\n\n: SLITERAL ( addr cnt -- , compile string )\n\tcompile (S\")\n\t\",\n; IMMEDIATE\n\n: $APPEND ( addr count $1 -- , append text to $1 )\n over >r\n dup >r\n count + ( -- a2 c2 end1 )\n swap cmove\n r> dup c@ ( a1 c1 )\n r> + ( -- a1 totalcount )\n swap c!\n;\n\n\\ ANSI word to replace [COMPILE] and COMPILE ----------------\n: POSTPONE ( -- )\n\tbl word find\n\tdup\n 0= -13 ?ERROR\n 0>\n IF compile, \\ immediate\n ELSE (compile) \\ normal\n THEN\n\n; immediate\n\n\\ -----------------------------------------------------------------\n\\ Auto Initialization\n: AUTO.INIT ( -- )\n\\ Kernel finds AUTO.INIT and executes it after loading dictionary.\n\\\t.\" Begin AUTO.INIT ------\" cr\n;\n: AUTO.TERM ( -- )\n\\ Kernel finds AUTO.TERM and executes it on bye.\n\\\t.\" End AUTO.TERM ------\" cr\n;\n\n: INCLUDE? ( -- , load file if word not defined )\n bl word find\n IF drop bl word drop ( eat word from source )\n ELSE drop include\n THEN\n; immediate\n\n: CLEARSTACK ( i*x -- )\n BEGIN depth\n WHILE drop\n REPEAT ;\n\nvariable pictured_output \\ hidden?\nvariable pictured_output_len \\ hidden?\n\n: <# ( -- ) pad pictured_output ! 0 pictured_output_len ! ;\n: #> ( -- addr n ) drop pictured_output @ pictured_output_len @ ;\n\n: HOLD ( c -- )\n pictured_output @ dup dup 1+ pictured_output_len @ cmove c!\n 1 pictured_output_len +!\n;\n\n\\ ------------------------ INPUT -------------------------------\n\n: SIGN ( n -- ) < 0 IF 45 hold THEN\n;\n\n: DIGIT ( n -- ascii )\n dup 10 < IF 48 ELSE 87 THEN + ;\n\n: # ( n -- n )\n base @ \/mod swap digit hold ;\n\n: #S ( n -- )\n BEGIN base @ \/mod dup\n WHILE swap digit hold\n REPEAT\n digit hold ;\n\n\n: (WARNING\") ( flag $message -- )\n swap\n IF count type\n ELSE drop\n THEN\n;\n\n: WARNING\" ( flag -- , print warning if true. )\n\t[compile] \" ( compile message )\n\tstate @\n\tIF compile (warning\")\n\tELSE (warning\")\n\tTHEN\n; IMMEDIATE\n\n: ABORT\" ( flag -- , print warning if true. )\n\t[compile] \" ( compile message )\n\tstate @\n\tIF compile (abort\")\n\tELSE (abort\")\n\tTHEN\n; IMMEDIATE\n\n: DEFER ( \"name\" -- )\n CREATE ['] ABORT ,\n DOES> ( ... -- ... ) @ EXECUTE ;\n\n: DEFER! ( xt2 xt1 -- )\n >BODY 4 CELL* + ! ;\n\n: DEFER@ ( xt1 -- xt2 )\n >BODY 4 CELL* + @ ;\n\n\\ : IS ( xt \"name\" -- , Skip leading spaces and parse name delimited by a space. Set name to execute xt. )\n\\ STATE @ IF\n\\ POSTPONE ['] POSTPONE DEFER!\n\\ ELSE\n\\ ' DEFER!\n\\ THEN ; IMMEDIATE\n\n","old_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\\n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n\n: COUNT dup 1+ swap c@ ;\n\n\\ Miscellaneous support words\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: <= ( a b -- f , true if A <= b ) > 0= ;\n: >= ( a b -- f , true if A >= b ) < 0= ;\n: NOT ( n -- !n , logical negation ) 0= ;\n: DNEGATE ( d -- -d , negate by doing 0-d )\n 0 swap -\n;\n: CELL+ ( n -- n+cell ) cell + ;\n: CELL- ( n -- n-cell ) cell - ;\n: CELL* ( n -- n*cell ) cells ;\n\n: CHAR+ ( n -- n+size_of_char ) 1+ ;\n: CHARS ( n -- n*size_of_char, don't do anything ) ; immediate\n\n\\ useful stack manipulation words\n: -ROT ( a b c -- c a b ) rot rot ;\n: 3DUP ( a b c -- a b c a b c ) 2 pick 2 pick 2 pick ;\n\n\\ ------------------------------------------------------------------\n: ID. ( nfa -- ) count 31 and type ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: PAD ( -- addr ) here 128 + ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n\n: BETWEEN ( n lo hi -- flag , true if between lo & hi )\n >r over r> > >r\n < r> or 0=\n;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: ? ( -- ) @ . ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ ' (lit) , cell 1- , ] +\n [ ' (lit) , cell 1- invert , ] and ;\n\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n: ALLOT ( nbytes -- , allot space in dictionary ) dp +! align ;\n\n: C, ( c -- ) here c! 1 dp +! ;\n\\ : W, ( w -- ) dp @ even-up dup dp ! w! 2 dp +! ;\n\\ : , ( n -- , lay into dictionary ) align here ! cell allot ;\n\n: SEE ( -- )\n ' dup\n >body swap >size\n disassemble ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token )\n [compile] literal ( compile a call to literal )\n ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick )\n ?comp ' [compile] literal\n; immediate\n\n: (DOES>) ( xt -- , modify previous definition to execute code at xt )\n latest >body \\ get address of code for new word\n 3 cell* + \\ offset to EXIT cell in create word\n ! \\ store execution token of DOES> code in new word\n;\n\n: DOES> ( -- , define execution code for CREATE word )\n 0 [compile] literal \\ dummy literal to hold xt\n here cell- \\ address of zero in literal\n compile (does>) \\ call (DOES>) from new creation word\n\t\t>r \\ move addrz to return stack so ; doesn't see stack garbage\n [compile] ; \\ terminate part of code before does>\n\t\tr>\n :noname ( addrz xt )\n compile rdrop \\ drop a stack frame (call becomes goto)\n swap ! \\ save execution token in literal\n; immediate\n\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 )\n swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 )\n dup cell+ @ swap @ ;\n\n: 2* ( n -- n*2 )\n 2 *\n;\n: 2\/ ( n -- n\/2 )\n 2 \/\n;\n\n\n\\ define some useful constants ------------------------------\n1 0= constant FALSE\n0 0= constant TRUE\n32 constant BL\n\n\\ Stack data structure ----------------------------------------\n\\ This is a general purpose stack utility used to implement necessary\n\\ stacks for the compiler or the user. Not real fast.\n\\ These stacks grow up which is different then normal.\n\\ cell 0 - stack pointer, offset from pfa of word\n\\ cell 1 - limit for range checking\n\\ cell 2 - first data location\n\n: :STACK ( #cells -- )\n CREATE 2 cells , ( offset of first data location )\n dup , ( limit for range checking, not currently used )\n cells cell+ allot ( allot an extra cell for safety )\n;\n\n: >STACK ( n stack -- , push onto stack, postincrement )\n dup @ 2dup cell+ swap ! ( -- n stack offset )\n + !\n;\n\n: STACK> ( stack -- n , pop , predecrement )\n dup @ cell- 2dup swap !\n + @\n;\n\n: STACK@ ( stack -- n , copy )\n dup @ cell- + @\n;\n\n: STACK.PICK ( index stack -- n , grab Nth from top of stack )\n dup @ cell- +\n swap cells - \\ offset for index\n @\n;\n: STACKP ( stack -- ptr , to next empty location on stack )\n\tdup @ +\n;\n\n: 0STACKP ( stack -- , clear stack)\n 8 swap !\n;\n\n32 :stack ustack\nustack 0stackp\n\n\\ Define JForth like words.\n: >US ustack >stack ;\n: US> ustack stack> ;\n: US@ ustack stack@ ;\n: 0USP ustack 0stackp ;\n\n\n\n\\ DO LOOP ------------------------------------------------\n\n3 constant do_flag\n4 constant leave_flag\n5 constant ?do_flag\n\n: DO ( -- , loop-back do_flag jump-from ?do_flag )\n ?comp\n compile (do)\n here >us do_flag >us ( for backward branch )\n; immediate\n\n: ?DO ( -- , loop-back do_flag jump-from ?do_flag , on user stack )\n ?comp\n ( leave address to set for forward branch )\n compile (?do)\n here 0 ,\n here >us do_flag >us ( for backward branch )\n >us ( for forward branch ) ?do_flag >us\n; immediate\n\n: LEAVE ( -- addr leave_flag )\n compile (leave)\n here 0 , >us\n leave_flag >us\n; immediate\n\n: LOOP-FORWARD ( -us- jump-from ?do_flag -- )\n BEGIN\n us@ leave_flag =\n us@ ?do_flag =\n OR\n WHILE\n us> leave_flag =\n IF\n us> here over - cell+ swap !\n ELSE\n us> dup\n here swap -\n cell+ swap !\n THEN\n REPEAT\n;\n\n: LOOP-BACK ( loop-addr do_flag -us- )\n us> do_flag ?pairs\n us> here - here\n !\n cell allot\n;\n\n: LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (loop)\n loop-forward loop-back\n; immediate\n\n\\ : DOTEST 5 0 do 333 . loop 888 . ;\n\\ : ?DOTEST0 0 0 ?do 333 . loop 888 . ;\n\\ : ?DOTEST1 5 0 ?do 333 . loop 888 . ;\n\n: +LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (+loop)\n loop-forward loop-back\n; immediate\n\n: UNLOOP ( loop-sys -r- )\n r> \\ save return pointer\n rdrop rdrop\n >r\n;\n\n\n: RECURSE ( ? -- ? , call the word currently being defined )\n latest compile,\n; immediate\n\n: SPACE bl emit ;\n: 0SP depth 0 ?do drop loop ;\n\n\\ : >NEWLINE ( -- , CR if needed )\n\\ out @ 0>\n\\ IF cr\n\\ THEN\n\\ ;\n\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 ) swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 ) dup cell+ @ swap @ ;\n\n: DABS ( d -- |d| )\n dup 0<\n IF dnegate\n THEN\n;\n\n: S>D ( s -- d , extend signed single precision to double )\n dup 0<\n IF -1\n ELSE 0\n THEN\n;\n\n: D>S ( d -- s ) drop ;\n\n: PARSE-WORD ( \"name\" -- c-addr u ) bl parse ;\n: \/STRING ( addr len n -- addr' len' ) over min rot over + -rot - ;\n: PLACE ( addr len to -- , move string ) 3dup 1+ swap cmove c! drop ;\n\n: ASCII ( -- char, state smart )\n bl parse drop c@\n state @ 1 =\n IF [compile] literal\n ELSE\n THEN\n; immediate\n\n: CHAR ( -- char , interpret mode ) bl parse drop c@ ;\n: [CHAR] ( -- char , for compile mode )\n char [compile] literal\n; immediate\n\n: $TYPE ( $string -- ) count type ;\n: 'word ( -- addr ) here ;\n\n: EVEN ( addr -- addr' ) dup 1 and + ;\n\n: (C\") ( -- $addr ) r> dup count + aligned >r ;\n: (S\") ( -- c-addr cnt ) r> count 2dup + aligned >r ;\n: (.\") ( -- , type following string ) r> count 2dup + aligned >r type ;\n: \", ( addr len -- , place string into dict ) tuck 'word place 1+ allot align ;\n: ,\" ( -- ) [char] \" parse \", ;\n\n: .( ( --, type string delimited by parens )\n [char] ) parse type\n; immediate\n\n: .\" ( -- , type string )\n state @ 1 =\n IF compile (.\") ,\"\n ELSE [char] \" parse type\n THEN\n; immediate\n\n: .' ( -- , type string delimited by single quote )\n state @\n IF compile (.\") [char] ' parse \",\n ELSE [char] ' parse type\n THEN\n; immediate\n\n: C\" ( -- addr , return string address, ANSI )\n state @\n IF compile (c\") ,\"\n ELSE [char] \" parse pad place pad\n THEN\n; immediate\n\n: S\" ( -- , -- addr , return string address, ANSI )\n state @\n IF compile (s\") ,\"\n ELSE [char] \" parse pad place pad count\n THEN\n; immediate\n\n: \" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n: P\" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n\n: \"\" ( -- addr )\n state @\n IF\n compile (C\")\n bl parse-word \",\n ELSE\n bl parse-word pad place pad\n THEN\n; immediate\n\n: SLITERAL ( addr cnt -- , compile string )\n\tcompile (S\")\n\t\",\n; IMMEDIATE\n\n: $APPEND ( addr count $1 -- , append text to $1 )\n over >r\n dup >r\n count + ( -- a2 c2 end1 )\n swap cmove\n r> dup c@ ( a1 c1 )\n r> + ( -- a1 totalcount )\n swap c!\n;\n\n\\ ANSI word to replace [COMPILE] and COMPILE ----------------\n: POSTPONE ( -- )\n\tbl word find\n\tdup\n 0= -13 ?ERROR\n 0>\n IF compile, \\ immediate\n ELSE (compile) \\ normal\n THEN\n\n; immediate\n\n\\ -----------------------------------------------------------------\n\\ Auto Initialization\n: AUTO.INIT ( -- )\n\\ Kernel finds AUTO.INIT and executes it after loading dictionary.\n\\\t.\" Begin AUTO.INIT ------\" cr\n;\n: AUTO.TERM ( -- )\n\\ Kernel finds AUTO.TERM and executes it on bye.\n\\\t.\" End AUTO.TERM ------\" cr\n;\n\n: INCLUDE? ( -- , load file if word not defined )\n bl word find\n IF drop bl word drop ( eat word from source )\n ELSE drop include\n THEN\n; immediate\n\n: CLEARSTACK ( i*x -- )\n BEGIN depth\n WHILE drop\n REPEAT ;\n\nvariable pictured_output \\ hidden?\nvariable pictured_output_len \\ hidden?\n\n: <# ( -- ) pad pictured_output ! 0 pictured_output_len ! ;\n: #> ( -- addr n ) drop pictured_output @ pictured_output_len @ ;\n\n: HOLD ( c -- )\n pictured_output @ dup dup 1+ pictured_output_len @ cmove c!\n 1 pictured_output_len +!\n;\n\n\\ ------------------------ INPUT -------------------------------\n\n: SIGN ( n -- ) < 0 IF 45 hold THEN\n;\n\n: DIGIT ( n -- ascii )\n dup 10 < IF 48 ELSE 87 THEN + ;\n\n: # ( n -- n )\n base @ \/mod swap digit hold ;\n\n: #S ( n -- )\n BEGIN base @ \/mod dup\n WHILE swap digit hold\n REPEAT\n digit hold ;\n\n\n: (WARNING\") ( flag $message -- )\n swap\n IF count type\n ELSE drop\n THEN\n;\n\n: WARNING\" ( flag -- , print warning if true. )\n\t[compile] \" ( compile message )\n\tstate @\n\tIF compile (warning\")\n\tELSE (warning\")\n\tTHEN\n; IMMEDIATE\n\n: ABORT\" ( flag -- , print warning if true. )\n\t[compile] \" ( compile message )\n\tstate @\n\tIF compile (abort\")\n\tELSE (abort\")\n\tTHEN\n; IMMEDIATE\n\n: DEFER ( \"name\" -- )\n CREATE ['] ABORT ,\n DOES> ( ... -- ... ) @ EXECUTE ;\n\n: DEFER! ( xt2 xt1 -- )\n >BODY 4 CELL* + ! ;\n\n: DEFER@ ( xt1 -- xt2 )\n >BODY 4 CELL* + @ ;\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"12f55ba3e1f1c8de85dbe1b8fcf1460bb47e4d0a","subject":"Don\u2019t configure the stack pointers in the forth startup. It doesn\u2019t know the big picture.","message":"Don\u2019t configure the stack pointers in the forth startup. It doesn\u2019t know the big picture.","repos":"rbsexton\/mpelite-stm32f0,rbsexton\/mpelite-stm32f0","old_file":"hello\/startSTM32F072.fth","new_file":"hello\/startSTM32F072.fth","new_contents":"\\ startSTM32F072.fth - Cortex startup code for SM32F072B-DISCO board\n\\ Customized for use with SockPuppet. No hardware init code.\n\n((\n\nTo do\n=====\n\nChange history\n==============\n))\n\nonly forth definitions decimal\n\n\\ ===========\n\\ *! startstm32f072\n\\ *T Cortex start up for STM32F072\n\\ ===========\n\nl: ExcVecs\t\\ -- addr ; start of vector table\n\\ *G The exception vector table is *\\fo{\/ExcVecs} bytes long. The\n\\ ** equate is defined in the control file. Note that this table\n\\ ** table must be correctly aligned as described in the Cortex-M3\n\\ ** Technical Reference Manual (ARM DDI0337, rev E page 8-21). If\n\\ ** placed at 0 or the start of Flash, you'll usually be fine.\n \/ExcVecs allot&erase\n\ninterpreter\n: SetExcVec\t\\ addr exc# --\n\\ *G Set the given exception vector number to the given address.\n\\ ** Note that for vectors other than 0, the Thumb bit is forced\n\\ ** to 1.\n dup if\t\t\t\t\\ If not the stack top\n swap 1 or swap\t\t\t\\ set the Thumb bit\n endif\n cells ExcVecs + ! ;\ntarget\n\nL: CLD1\t\t\\ holds xt of main word\n 0 ,\t\t\t\t\t\\ fixed by MAKE-TURNKEY\n\nproc DefExc2\tb $\tend-code\t\\ NMI\nproc DefExc3\tb $\tend-code\t\\ HardFault\nproc DefExc4\tb $\tend-code\t\\ MemManage\nproc DefExc5\tb $\tend-code\t\\ BusFault\nproc DefExc6\tb $\tend-code\t\\ UsageFault\nproc DefExc11\tb $\tend-code\t\\ SVC\nproc DefExc12\tb $\tend-code\t\\ DbgMon\nproc DefExc14\tb $\tend-code\t\\ PendSV\nproc DefExc15\tb $\tend-code\t\\ SysTick\n\n\n\\ Calculate the initial value for the data stack pointer.\n\\ We allow for TOS being in a register and guard space.\n\n[undefined] sp-guard [if]\t\t\\ if no guard value is set\n0 equ sp-guard\n[then]\n\ninit-s0 tos-cached? sp-guard + cells -\n equ real-init-s0\t\\ -- addr\n\\ The data stack pointer set at start up.\n\n: StartCortex\t\\ -- ; never exits\n\\ *G Set up the Forth registers and start Forth. Other primary\n\\ ** hardware initialisation can also be performed here.\n\\ ** All the GPIO blocks are enabled.\n begin\n \\ INT_STACK_TOP SP_main sys!\t\t\\ set SP_main for interrupts\n \\ INIT-R0 SP_process sys!\t\t\\ set SP_process for tasks\n \\ 2 control sys!\t\t\t\\ switch to SP_process\n \\ Don't mess with the stack pointers. The launcher will handle it.\n REAL-INIT-S0 set-sp\t\t\t\\ Allow for cached TOS and guard space\n INIT-U0 up!\t\t\t\t\\ USER area\n CLD1 @ execute\n again\n;\nexternal\n\nINT_STACK_TOP StackVec# SetExcVec\t\\ Define initial return stack\n' StartCortex ResetVec# SetExcVec\t\\ Define startup word\nDefExc2 2 SetExcVec\nDefExc3 3 SetExcVec\nDefExc4 4 SetExcVec\nDefExc5 5 SetExcVec\nDefExc11 11 SetExcVec\nDefExc12 12 SetExcVec\nDefExc14 14 SetExcVec\nDefExc15 15 SetExcVec\n\n\n\\ ------------------------------------------\n\\ reset values for user and system variables\n\\ ------------------------------------------\n\n[undefined] umbilical? [if]\nL: USER-RESET\n init-s0 tos-cached? sp-guard + cells - ,\t\\ s0\n init-r0 ,\t\t\t\t\\ r0\n 0 , 0 , \\ #tib, 'tib\n 0 , 0 , \\ >in, out\n $0A , 0 , \\ base, hld\n\n\\ initial values of system variables\nL: INIT-FENCE 0 , \\ fence\nL: INIT-DP 0 , \\ dp\nL: INIT-RP 0 ,\t\t\t\t\\ RP\nL: INIT-VOC-LINK 0 , \\ voc-link\n[then]\n\n\n\\ ======\n\\ *> ###\n\\ ======\n\ndecimal\n\n","old_contents":"\\ startSTM32F072.fth - Cortex startup code for SM32F072B-DISCO board\n\\ Customized for use with SockPuppet. No hardware init code.\n\n((\n\nTo do\n=====\n\nChange history\n==============\n))\n\nonly forth definitions decimal\n\n\\ ===========\n\\ *! startstm32f072\n\\ *T Cortex start up for STM32F072\n\\ ===========\n\nl: ExcVecs\t\\ -- addr ; start of vector table\n\\ *G The exception vector table is *\\fo{\/ExcVecs} bytes long. The\n\\ ** equate is defined in the control file. Note that this table\n\\ ** table must be correctly aligned as described in the Cortex-M3\n\\ ** Technical Reference Manual (ARM DDI0337, rev E page 8-21). If\n\\ ** placed at 0 or the start of Flash, you'll usually be fine.\n \/ExcVecs allot&erase\n\ninterpreter\n: SetExcVec\t\\ addr exc# --\n\\ *G Set the given exception vector number to the given address.\n\\ ** Note that for vectors other than 0, the Thumb bit is forced\n\\ ** to 1.\n dup if\t\t\t\t\\ If not the stack top\n swap 1 or swap\t\t\t\\ set the Thumb bit\n endif\n cells ExcVecs + ! ;\ntarget\n\nL: CLD1\t\t\\ holds xt of main word\n 0 ,\t\t\t\t\t\\ fixed by MAKE-TURNKEY\n\nproc DefExc2\tb $\tend-code\t\\ NMI\nproc DefExc3\tb $\tend-code\t\\ HardFault\nproc DefExc4\tb $\tend-code\t\\ MemManage\nproc DefExc5\tb $\tend-code\t\\ BusFault\nproc DefExc6\tb $\tend-code\t\\ UsageFault\nproc DefExc11\tb $\tend-code\t\\ SVC\nproc DefExc12\tb $\tend-code\t\\ DbgMon\nproc DefExc14\tb $\tend-code\t\\ PendSV\nproc DefExc15\tb $\tend-code\t\\ SysTick\n\n\n\\ Calculate the initial value for the data stack pointer.\n\\ We allow for TOS being in a register and guard space.\n\n[undefined] sp-guard [if]\t\t\\ if no guard value is set\n0 equ sp-guard\n[then]\n\ninit-s0 tos-cached? sp-guard + cells -\n equ real-init-s0\t\\ -- addr\n\\ The data stack pointer set at start up.\n\n: StartCortex\t\\ -- ; never exits\n\\ *G Set up the Forth registers and start Forth. Other primary\n\\ ** hardware initialisation can also be performed here.\n\\ ** All the GPIO blocks are enabled.\n begin\n \\ INT_STACK_TOP SP_main sys!\t\t\\ set SP_main for interrupts\n INIT-R0 SP_process sys!\t\t\\ set SP_process for tasks\n 2 control sys!\t\t\t\\ switch to SP_process\n REAL-INIT-S0 set-sp\t\t\t\\ Allow for cached TOS and guard space\n INIT-U0 up!\t\t\t\t\\ USER area\n CLD1 @ execute\n again\n;\nexternal\n\nINT_STACK_TOP StackVec# SetExcVec\t\\ Define initial return stack\n' StartCortex ResetVec# SetExcVec\t\\ Define startup word\nDefExc2 2 SetExcVec\nDefExc3 3 SetExcVec\nDefExc4 4 SetExcVec\nDefExc5 5 SetExcVec\nDefExc11 11 SetExcVec\nDefExc12 12 SetExcVec\nDefExc14 14 SetExcVec\nDefExc15 15 SetExcVec\n\n\n\\ ------------------------------------------\n\\ reset values for user and system variables\n\\ ------------------------------------------\n\n[undefined] umbilical? [if]\nL: USER-RESET\n init-s0 tos-cached? sp-guard + cells - ,\t\\ s0\n init-r0 ,\t\t\t\t\\ r0\n 0 , 0 , \\ #tib, 'tib\n 0 , 0 , \\ >in, out\n $0A , 0 , \\ base, hld\n\n\\ initial values of system variables\nL: INIT-FENCE 0 , \\ fence\nL: INIT-DP 0 , \\ dp\nL: INIT-RP 0 ,\t\t\t\t\\ RP\nL: INIT-VOC-LINK 0 , \\ voc-link\n[then]\n\n\n\\ ======\n\\ *> ###\n\\ ======\n\ndecimal\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"737b0e7825058e05e6e99797e8bf1d1a3e8199fe","subject":"Fix a stack bug in the system call handler.","message":"Fix a stack bug in the system call handler.","repos":"rbsexton\/sockpuppet,rbsexton\/sockpuppet","old_file":"forth\/SysCalls.fth","new_file":"forth\/SysCalls.fth","new_contents":"\\ Wrappers for SAPI functions, ABI 2.x\n\n\\ Note that the system call number is embedded into the instruction,\n\\ so this is not so easily parameterized.\n\n#0 equ SAPI_VEC_VERSION\n#1 equ SAPI_VEC_01_GetRuntimeLinks\n#2 equ SAPI_VEC_02_PutChar\n#3 equ SAPI_VEC_03_GetChar\n#4 equ SAPI_VEC_04_GetCharAvail\n#5 equ SAPI_VEC_05_PutString\n#6 equ SAPI_VEC_06_EOL\n#14 equ SAPI_VEC_14_PetWatchdog\n#15 equ SAPI_VEC_15_GetTimeMS\n\nCODE SAPI-Version \\ -- n\n\\ *G Get the version of the binary ABI in use. \n\tsvc # SAPI_VEC_VERSION \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE GETRUNTIMELINKS \\ type -- n\n\\ *G Get the runtime linking information. Type 0 - A Dynamic linking \n\\ ** table with name, address pairs. Type 1 - A Zero-Terminated Jump table.\n\tmov r0, tos\n\tsvc # SAPI_VEC_01_GetRuntimeLinks \n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ --------------------------------------------\n\\ System calls that will require wrappers\n\\ --------------------------------------------\n\nCODE (SEREMITFC) \\ char base --\n\\ *G Service call for a single char - This one has a special name because\n\\ ** It'll be wrapped by something that can respond to the flow control \n\\ ** return code and PAUSE + Retry \n\tmov r0, tos\n\tldr r1, [ psp ], # 4\n\t[defined] SAPIWakeSupport? [if] mov r2, up [else] mov r2, # 0 [then] \n\tsvc # SAPI_VEC_02_PutChar\t\n\tmov tos, r0\n next,\nEND-CODE\n\nCODE (SERKEYFC) \\ base -- char \n\\ *G Get a character from the port, or -1 for fail\n\tmov r0, tos\t\n\t[defined] SAPIWakeSupport? [if] mov r1, up [else] mov r1, # 0 [then] \n\tsvc # SAPI_VEC_03_GetChar\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE (SERTYPEFC) \\ caddr len base -- return \n\\ *G Output characters. \n\tmov r0, tos\t\n\tldr r1, [ psp ], # 4\n\tldr r2, [ psp ], # 4\n\t[defined] SAPIWakeSupport? [if] mov r3, up [else] mov r3, # 0 [then] \n\tsvc # SAPI_VEC_05_PutString\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE (SERCRFC) \\ base -- return \n\\ *G Send a line terminator to the port. Return 0 for success, -1 for fail.\n\tmov r0, tos\t\n\t[defined] SAPIWakeSupport? [if] mov r1, up [else] mov r1, # 0 [then] \n\tsvc # SAPI_VEC_06_EOL\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ --------------------------------------------\n\\ Direct substitures for existing stuff.\n\\ --------------------------------------------\n\nCODE (SERKEY?) \\ base -- t\/f\n\\ *G Return true if the given stream has a character avilable to read.\n\\ The call returns the number of chars available. \n\tmov r0, tos\n\tsvc # SAPI_VEC_04_GetCharAvail\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE PETWATCHDOG \\ n --\n\\ *G Refresh the watchdog. Pass in a platform-specific number\n\\ ** To specify a timerout (if supported), or zero for the default value. \n\tmov r0, tos\n\tldr r1, [ psp ], # 4\n\tsvc # SAPI_VEC_14_PetWatchdog\n\tldr tos, [ psp ], # 4\n\tnext,\nEND-CODE\n\nCODE TICKS \\ -- n \n\\ *G The current value of the millisecond ticker.\n mov r0, # 0 \\ We want the actual value.\n\tsvc # SAPI_VEC_15_GetTimeMS\n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\n\n\n","old_contents":"\\ Wrappers for SAPI functions, ABI 2.x\n\n\\ Note that the system call number is embedded into the instruction,\n\\ so this is not so easily parameterized.\n\n#0 equ SAPI_VEC_VERSION\n#1 equ SAPI_VEC_01_GetRuntimeLinks\n#2 equ SAPI_VEC_02_PutChar\n#3 equ SAPI_VEC_03_GetChar\n#4 equ SAPI_VEC_04_GetCharAvail\n#5 equ SAPI_VEC_05_PutString\n#6 equ SAPI_VEC_06_EOL\n#14 equ SAPI_VEC_14_PetWatchdog\n#15 equ SAPI_VEC_15_GetTimeMS\n\nCODE SAPI-Version \\ -- n\n\\ *G Get the version of the binary ABI in use. \n\tsvc # SAPI_VEC_VERSION \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE GETRUNTIMELINKS \\ type -- n\n\\ *G Get the runtime linking information. Type 0 - A Dynamic linking \n\\ ** table with name, address pairs. Type 1 - A Zero-Terminated Jump table.\n\tmov r0, tos\n\tsvc # SAPI_VEC_01_GetRuntimeLinks \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ --------------------------------------------\n\\ System calls that will require wrappers\n\\ --------------------------------------------\n\nCODE (SEREMITFC) \\ char base --\n\\ *G Service call for a single char - This one has a special name because\n\\ ** It'll be wrapped by something that can respond to the flow control \n\\ ** return code and PAUSE + Retry \n\tmov r0, tos\n\tldr r1, [ psp ], # 4\n\t[defined] SAPIWakeSupport? [if] mov r2, up [else] mov r2, # 0 [then] \n\tsvc # SAPI_VEC_02_PutChar\t\n\tmov tos, r0\n next,\nEND-CODE\n\nCODE (SERKEYFC) \\ base -- char \n\\ *G Get a character from the port, or -1 for fail\n\tmov r0, tos\t\n\t[defined] SAPIWakeSupport? [if] mov r1, up [else] mov r1, # 0 [then] \n\tsvc # SAPI_VEC_03_GetChar\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE (SERTYPEFC) \\ caddr len base -- return \n\\ *G Output characters. \n\tmov r0, tos\t\n\tldr r1, [ psp ], # 4\n\tldr r2, [ psp ], # 4\n\t[defined] SAPIWakeSupport? [if] mov r3, up [else] mov r3, # 0 [then] \n\tsvc # SAPI_VEC_05_PutString\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE (SERCRFC) \\ base -- return \n\\ *G Send a line terminator to the port. Return 0 for success, -1 for fail.\n\tmov r0, tos\t\n\t[defined] SAPIWakeSupport? [if] mov r1, up [else] mov r1, # 0 [then] \n\tsvc # SAPI_VEC_06_EOL\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ --------------------------------------------\n\\ Direct substitures for existing stuff.\n\\ --------------------------------------------\n\nCODE (SERKEY?) \\ base -- t\/f\n\\ *G Return true if the given stream has a character avilable to read.\n\\ The call returns the number of chars available. \n\tmov r0, tos\n\tsvc # SAPI_VEC_04_GetCharAvail\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE PETWATCHDOG \\ n --\n\\ *G Refresh the watchdog. Pass in a platform-specific number\n\\ ** To specify a timerout (if supported), or zero for the default value. \n\tmov r0, tos\n\tldr r1, [ psp ], # 4\n\tsvc # SAPI_VEC_14_PetWatchdog\n\tldr tos, [ psp ], # 4\n\tnext,\nEND-CODE\n\nCODE TICKS \\ -- n \n\\ *G The current value of the millisecond ticker.\n mov r0, # 0 \\ We want the actual value.\n\tsvc # SAPI_VEC_15_GetTimeMS\n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\n\n\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"4f6b3ea71b91e43e13d01ca51edb97f2be91afdf","subject":"cleanup example","message":"cleanup example","repos":"cetic\/python-msp430-tools,cetic\/python-msp430-tools,cetic\/python-msp430-tools","old_file":"examples\/asm\/forth_to_asm\/led.forth","new_file":"examples\/asm\/forth_to_asm\/led.forth","new_contents":"( LED flashing example\n Hardware: Launchpad\n\n vi:ft=forth\n)\n\nINCLUDE msp430.forth\nINCLUDE core.forth\n\nCODE BIT_CLEAR_BYTE\n TOS->R15\n TOS->R14\n .\" \\t bic.b R14, 0(R15) \" NL\n NEXT\nEND-CODE\n\nCODE BIT_SET_BYTE\n TOS->R15\n TOS->R14\n .\" \\t bis.b R14, 0(R15) \" NL\n NEXT\nEND-CODE\n\n( Control the LEDs on the Launchpad )\n: RED_ON BIT0 P1OUT BIT_SET_BYTE ;\n: RED_OFF BIT0 P1OUT BIT_CLEAR_BYTE ;\n: GREEN_ON BIT6 P1OUT BIT_SET_BYTE ;\n: GREEN_OFF BIT6 P1OUT BIT_CLEAR_BYTE ;\n\n( Read in the button on the Launchpad )\n: S2 P1IN C@ BIT3 & NOT ;\n\n\nCODE DELAY\n TOS->R15\n .\" .loop: \\t dec R15 \\n \"\n .\" \\t jnz .loop \\n \"\n NEXT\nEND-CODE\n\n: SHORT-DELAY 0x4fff DELAY ;\n: LONG-DELAY 0xffff DELAY ;\n: VERY-LONG-DELAY LONG-DELAY LONG-DELAY ;\n\n: INIT\n [ BIT0 BIT6 + ] LITERAL P1DIR C!\n 0 P1OUT C!\n GREEN_ON\n VERY-LONG-DELAY\n GREEN_OFF\n VERY-LONG-DELAY\n VERY-LONG-DELAY\n;\n\n: MAIN\n BEGIN\n ( Red flashing )\n RED_ON\n LONG-DELAY\n RED_OFF\n LONG-DELAY\n\n ( Green flashing if button is pressed )\n S2 IF\n GREEN_ON\n SHORT-DELAY\n GREEN_OFF\n SHORT-DELAY\n ENDIF\n AGAIN\n;\n\n( ========================================================================= )\n( Generate the assembler file now )\n\" LED example \" HEADER\n\n( output important runtime core parts )\n\" Core \" HEADER\nCROSS-COMPILE-CORE\n\n( cross compile application )\n\" Application \" HEADER\nCROSS-COMPILE-VARIABLES\nCROSS-COMPILE INIT\nCROSS-COMPILE MAIN\nCROSS-COMPILE-MISSING\n","old_contents":"( LED flashing example\n Hardware: Launchpad\n\n vi:ft=forth\n)\n\nINCLUDE msp430.forth\nINCLUDE core.forth\n\nCODE BIT_CLEAR_BYTE\n TOS->R15\n TOS->R14\n .\" \\t bic.b R14, 0(R15) \" NL\n NEXT\nEND-CODE\n\nCODE BIT_SET_BYTE\n TOS->R15\n TOS->R14\n .\" \\t bis.b R14, 0(R15) \" NL\n NEXT\nEND-CODE\n\n( Control the LEDs on the Launchpad )\n: RED_ON BIT0 P1OUT BIT_SET_BYTE ;\n: RED_OFF BIT0 P1OUT BIT_CLEAR_BYTE ;\n: GREEN_ON BIT6 P1OUT BIT_SET_BYTE ;\n: GREEN_OFF BIT6 P1OUT BIT_CLEAR_BYTE ;\n\n( Read in the button on the Launchpad )\n: S2 P1IN C@ BIT3 & NOT ;\n\n\nCODE DELAY\n TOS->R15\n .\" .loop: \\t dec R15 \\n \"\n .\" \\t jnz .loop \\n \"\n NEXT\nEND-CODE\n\n: INIT\n [ BIT0 BIT6 + ] LITERAL P1DIR C!\n 0 P1OUT C!\n GREEN_ON\n 0xffff DELAY 0xffff DELAY\n GREEN_OFF\n 0xffff DELAY 0xffff DELAY\n 0xffff DELAY 0xffff DELAY\n( 10 12 >\n IF 10 ELSE 20 ENDIF\n DROP\n)\n;\n\n: MAIN\n BEGIN\n ( Red flashing )\n RED_ON\n 0xffff DELAY\n RED_OFF\n 0xffff DELAY\n\n ( Green flashing if button is pressed )\n S2 IF\n GREEN_ON\n 0x4fff DELAY\n GREEN_OFF\n 0x4fff DELAY\n ENDIF\n AGAIN\n;\n\n( ========================================================================= )\n( Generate the assembler file now )\n\" LED example \" HEADER\n\n( output important runtime core parts )\n\" Core \" HEADER\nCROSS-COMPILE-CORE\n\n( cross compile application )\n\" Application \" HEADER\nCROSS-COMPILE-VARIABLES\nCROSS-COMPILE INIT\nCROSS-COMPILE MAIN\nCROSS-COMPILE-MISSING\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"a8c009aff5eac9bf2af4703b65e68ed5a84e9cd4","subject":"Replace loader_color with loader_logo","message":"Replace loader_color with loader_logo\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/beastie.4th","new_file":"sys\/boot\/forth\/beastie.4th","new_contents":"\\ Copyright (c) 2003 Scott Long \n\\ Copyright (c) 2003 Aleksander Fafula \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\nmarker task-beastie.4th\n\ninclude \/boot\/screen.4th\ninclude \/boot\/frames.4th\n\nhide\n\nvariable menuidx\nvariable menubllt\nvariable menuX\nvariable menuY\nvariable promptwidth\n\nvariable bootkey\nvariable bootacpikey\nvariable bootusbkey\nvariable bootsafekey\nvariable bootverbosekey\nvariable bootsinglekey\nvariable escapekey\nvariable rebootkey\n\n46 constant dot\n\n\\ The BSD Daemon. He is 19 rows high and 34 columns wide\n: beastie-logo ( x y -- )\n2dup at-xy .\" \u001b[1;31m, ,\" 1+\n2dup at-xy .\" \/( )`\" 1+\n2dup at-xy .\" \\ \\___ \/ |\" 1+\n2dup at-xy .\" \/- \u001b[37m_\u001b[31m `-\/ '\" 1+\n2dup at-xy .\" (\u001b[37m\/\\\/ \\\u001b[31m \\ \/\\\" 1+\n2dup at-xy .\" \u001b[37m\/ \/ |\u001b[31m ` \\\" 1+\n2dup at-xy .\" \u001b[34mO O \u001b[37m) \u001b[31m\/ |\" 1+\n2dup at-xy .\" \u001b[37m`-^--'\u001b[31m`< '\" 1+\n2dup at-xy .\" (_.) _ ) \/\" 1+\n2dup at-xy .\" `.___\/` \/ \" 1+\n2dup at-xy .\" `-----' \/\" 1+\n2dup at-xy .\" \u001b[33m<----.\u001b[31m __ \/ __ \\\" 1+\n2dup at-xy .\" \u001b[33m<----|====\u001b[31mO)))\u001b[33m==\u001b[31m) \\) \/\u001b[33m====|\" 1+\n2dup at-xy .\" \u001b[33m<----'\u001b[31m `--' `.__,' \\\" 1+\n2dup at-xy .\" | |\" 1+\n2dup at-xy .\" \\ \/ \/\\\" 1+\n2dup at-xy .\" \u001b[36m______\u001b[31m( (_ \/ \\______\/\" 1+\n2dup at-xy .\" \u001b[36m,' ,-----' |\" 1+\nat-xy .\" `--{__________) \u001b[0m\"\n;\n\n: beastiebw-logo ( x y -- )\n\t2dup at-xy .\" , ,\" 1+\n\t2dup at-xy .\" \/( )`\" 1+\n\t2dup at-xy .\" \\ \\___ \/ |\" 1+\n\t2dup at-xy .\" \/- _ `-\/ '\" 1+\n\t2dup at-xy .\" (\/\\\/ \\ \\ \/\\\" 1+\n\t2dup at-xy .\" \/ \/ | ` \\\" 1+\n\t2dup at-xy .\" O O ) \/ |\" 1+\n\t2dup at-xy .\" `-^--'`< '\" 1+\n\t2dup at-xy .\" (_.) _ ) \/\" 1+\n\t2dup at-xy .\" `.___\/` \/\" 1+\n\t2dup at-xy .\" `-----' \/\" 1+\n\t2dup at-xy .\" <----. __ \/ __ \\\" 1+\n\t2dup at-xy .\" <----|====O)))==) \\) \/====\" 1+\n\t2dup at-xy .\" <----' `--' `.__,' \\\" 1+\n\t2dup at-xy .\" | |\" 1+\n\t2dup at-xy .\" \\ \/ \/\\\" 1+\n\t2dup at-xy .\" ______( (_ \/ \\______\/\" 1+\n\t2dup at-xy .\" ,' ,-----' |\" 1+\n\t at-xy .\" `--{__________)\"\n;\n\n: fbsdbw-logo ( x y -- )\n\t2dup at-xy .\" ______\" 1+\n\t2dup at-xy .\" | ____| __ ___ ___ \" 1+\n\t2dup at-xy .\" | |__ | '__\/ _ \\\/ _ \\\" 1+\n\t2dup at-xy .\" | __|| | | __\/ __\/\" 1+\n\t2dup at-xy .\" | | | | | | |\" 1+\n\t2dup at-xy .\" |_| |_| \\___|\\___|\" 1+\n\t2dup at-xy .\" ____ _____ _____\" 1+\n\t2dup at-xy .\" | _ \\ \/ ____| __ \\\" 1+\n\t2dup at-xy .\" | |_) | (___ | | | |\" 1+\n\t2dup at-xy .\" | _ < \\___ \\| | | |\" 1+\n\t2dup at-xy .\" | |_) |____) | |__| |\" 1+\n\t2dup at-xy .\" | | | |\" 1+\n\t at-xy .\" |____\/|_____\/|_____\/\"\n;\n\n: print-logo ( x y -- )\n\ts\" loader_logo\" getenv\n\tdup -1 = if\n\t\tdrop\n\t\tfbsdbw-logo\n\t\texit\n\tthen\n\t2dup s\" fbsdbw\" compare-insensitive 0= if\n\t\t2drop\n\t\tfbsdbw-logo\n\t\texit\n\tthen\n\t2dup s\" beastiebw\" compare-insensitive 0= if\n\t\t2drop\n\t\tbeastiebw-logo\n\t\texit\n\tthen\n\t2dup s\" beastie\" compare-insensitive 0= if\n\t\t2drop\n\t\tbeastie-logo\n\t\texit\n\tthen\n\t2dup s\" none\" compare-insensitive 0= if\n\t\t2drop\n\t\t\\ no logo\n\t\texit\n\tthen\n\t2drop\n\tfbsdbw-logo\n;\n\n: acpienabled? ( -- flag )\n\ts\" acpi_load\" getenv\n\tdup -1 = if\n\t\tdrop false exit\n\tthen\n\ts\" YES\" compare-insensitive 0<> if\n\t\tfalse exit\n\tthen\n\ts\" hint.acpi.0.disabled\" getenv\n\tdup -1 <> if\n\t\ts\" 0\" compare 0<> if\n\t\t\tfalse exit\n\t\tthen\n\telse\n\t\tdrop\n\tthen\n\ttrue\n;\n\n: printmenuitem ( -- n )\n\tmenuidx @\n\t1+ dup\n\tmenuidx !\n\tmenuY @ + dup menuX @ swap at-xy\n\tmenuidx @ .\n\tmenuX @ 1+ swap at-xy\n\tmenubllt @ emit\n\tmenuidx @ 48 +\n;\n\n: beastie-menu ( -- )\n\t0 menuidx !\n\tdot menubllt !\n\t8 menuY !\n\t5 menuX !\n\tclear\n\t46 4 print-logo\n\t42 20 2 2 box\n\t13 6 at-xy .\" Welcome to FreeBSD!\"\n\tprintmenuitem .\" Boot FreeBSD [default]\" bootkey !\n\ts\" arch-i386\" environment? if\n\t\tdrop\n\t\tprintmenuitem .\" Boot FreeBSD with ACPI \" bootacpikey !\n\t\tacpienabled? if\n\t\t\t.\" disabled\"\n\t\telse\n\t\t\t.\" enabled\"\n\t\tthen\n\telse\n\t\t-2 bootacpikey !\n\tthen\n\tprintmenuitem .\" Boot FreeBSD in Safe Mode\" bootsafekey !\n\tprintmenuitem .\" Boot FreeBSD in single user mode\" bootsinglekey !\n\tprintmenuitem .\" Boot FreeBSD with verbose logging\" bootverbosekey !\n\tprintmenuitem .\" Escape to loader prompt\" escapekey !\n\ts\" arch-i386\" environment? if\n\t\tdrop\n\t\tprintmenuitem .\" Boot FreeBSD with USB keyboard\" bootusbkey !\n\telse\n\t\t-2 bootusbkey !\n\tthen\n\tprintmenuitem .\" Reboot\" rebootkey !\n\tmenuX @ 20 at-xy\n\t.\" Select option, [Enter] for default\"\n\tmenuX @ 21 at-xy\n\ts\" or [Space] to pause timer \" dup 2 - promptwidth !\n\ttype\n;\n\n: tkey\n\tseconds +\n\tbegin 1 while\n\t\tover 0<> if\n\t\t\tdup seconds u< if\n\t\t\t\tdrop\n\t\t\t\t-1\n\t\t\t\texit\n\t\t\tthen\n\t\t\tmenuX @ promptwidth @ + 21 at-xy dup seconds - .\n\t\tthen\n\t\tkey? if\n\t\t\tdrop\n\t\t\tkey\n\t\t\texit\n\t\tthen\n\t50 ms\n\trepeat\n;\n\nset-current\n\n: beastie-start\n\ts\" beastie_disable\" getenv\n\tdup -1 <> if\n\t\ts\" YES\" compare-insensitive 0= if\n\t\t\texit\n\t\tthen\n\telse\n\t\tdrop\n\tthen\n\tbeastie-menu\n\ts\" autoboot_delay\" getenv\n\tdup -1 = if\n\t\tdrop\n\t\t10\n\telse\n\t\t0 0 2swap >number drop drop drop\n\tthen\n\tbegin\n\t\tdup tkey\n\t\t0 25 at-xy\n\t\tdup 32 = if nip 0 swap then\n\t\tdup -1 = if 0 boot then\n\t\tdup 13 = if 0 boot then\n\t\tdup bootkey @ = if 0 boot then\n\t\tdup bootacpikey @ = if\n\t\t\tacpienabled? if\n\t\t\t\ts\" acpi_load\" unsetenv\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\telse\n\t\t\t\ts\" YES\" s\" acpi_load\" setenv\n\t\t\t\ts\" 0\" s\" hint.acpi.0.disabled\" setenv\n\t\t\tthen\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootusbkey @ = if\n\t\t\ts\" 0x1\" s\" hint.atkbd.0.flags\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootsafekey @ = if\n\t\t\ts\" arch-i386\" environment? if\n\t\t\t\tdrop\n\t\t\t\ts\" acpi_load\" unsetenv\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\t\ts\" 1\" s\" hint.apic.0.disabled\" setenv\n\t\t\tthen\n\t\t\ts\" 0\" s\" hw.ata.ata_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.atapi_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.wc\" setenv\n\t\t\ts\" 0\" s\" hw.eisa_slots\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootverbosekey @ = if\n\t\t\ts\" YES\" s\" boot_verbose\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootsinglekey @ = if\n\t\t\ts\" YES\" s\" boot_single\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup escapekey @ = if\n\t\t\t2drop\n\t\t\ts\" NO\" s\" autoboot_delay\" setenv\n\t\t\texit\n\t\tthen\n\t\trebootkey @ = if 0 reboot then\n\tagain\n;\n\nprevious\n","old_contents":"\\ Copyright (c) 2003 Scott Long \n\\ Copyright (c) 2003 Aleksander Fafula \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\nmarker task-beastie.4th\n\ninclude \/boot\/screen.4th\ninclude \/boot\/frames.4th\n\nhide\n\nvariable menuidx\nvariable menubllt\nvariable menuX\nvariable menuY\nvariable promptwidth\n\nvariable bootkey\nvariable bootacpikey\nvariable bootusbkey\nvariable bootsafekey\nvariable bootverbosekey\nvariable bootsinglekey\nvariable escapekey\nvariable rebootkey\n\n46 constant dot\n\n\\ The BSD Daemon. He is 19 rows high and 34 columns wide\n: technicolor-beastie ( x y -- )\n2dup at-xy .\" \u001b[1;31m, ,\" 1+\n2dup at-xy .\" \/( )`\" 1+\n2dup at-xy .\" \\ \\___ \/ |\" 1+\n2dup at-xy .\" \/- \u001b[37m_\u001b[31m `-\/ '\" 1+\n2dup at-xy .\" (\u001b[37m\/\\\/ \\\u001b[31m \\ \/\\\" 1+\n2dup at-xy .\" \u001b[37m\/ \/ |\u001b[31m ` \\\" 1+\n2dup at-xy .\" \u001b[34mO O \u001b[37m) \u001b[31m\/ |\" 1+\n2dup at-xy .\" \u001b[37m`-^--'\u001b[31m`< '\" 1+\n2dup at-xy .\" (_.) _ ) \/\" 1+\n2dup at-xy .\" `.___\/` \/ \" 1+\n2dup at-xy .\" `-----' \/\" 1+\n2dup at-xy .\" \u001b[33m<----.\u001b[31m __ \/ __ \\\" 1+\n2dup at-xy .\" \u001b[33m<----|====\u001b[31mO)))\u001b[33m==\u001b[31m) \\) \/\u001b[33m====|\" 1+\n2dup at-xy .\" \u001b[33m<----'\u001b[31m `--' `.__,' \\\" 1+\n2dup at-xy .\" | |\" 1+\n2dup at-xy .\" \\ \/ \/\\\" 1+\n2dup at-xy .\" \u001b[36m______\u001b[31m( (_ \/ \\______\/\" 1+\n2dup at-xy .\" \u001b[36m,' ,-----' |\" 1+\nat-xy .\" `--{__________) \u001b[0m\"\n;\n\n: boring-beastie ( x y -- )\n\t2dup at-xy .\" , ,\" 1+\n\t2dup at-xy .\" \/( )`\" 1+\n\t2dup at-xy .\" \\ \\___ \/ |\" 1+\n\t2dup at-xy .\" \/- _ `-\/ '\" 1+\n\t2dup at-xy .\" (\/\\\/ \\ \\ \/\\\" 1+\n\t2dup at-xy .\" \/ \/ | ` \\\" 1+\n\t2dup at-xy .\" O O ) \/ |\" 1+\n\t2dup at-xy .\" `-^--'`< '\" 1+\n\t2dup at-xy .\" (_.) _ ) \/\" 1+\n\t2dup at-xy .\" `.___\/` \/\" 1+\n\t2dup at-xy .\" `-----' \/\" 1+\n\t2dup at-xy .\" <----. __ \/ __ \\\" 1+\n\t2dup at-xy .\" <----|====O)))==) \\) \/====\" 1+\n\t2dup at-xy .\" <----' `--' `.__,' \\\" 1+\n\t2dup at-xy .\" | |\" 1+\n\t2dup at-xy .\" \\ \/ \/\\\" 1+\n\t2dup at-xy .\" ______( (_ \/ \\______\/\" 1+\n\t2dup at-xy .\" ,' ,-----' |\" 1+\n\t at-xy .\" `--{__________)\"\n;\n\n: print-beastie ( x y -- )\n\ts\" loader_color\" getenv\n\tdup -1 = if\n\t\tdrop\n\t\tboring-beastie\n\t\texit\n\tthen\n\ts\" YES\" compare-insensitive 0<> if\n\t\tboring-beastie\n\t\texit\n\tthen\n\ttechnicolor-beastie\n;\n\n: acpienabled? ( -- flag )\n\ts\" acpi_load\" getenv\n\tdup -1 = if\n\t\tdrop false exit\n\tthen\n\ts\" YES\" compare-insensitive 0<> if\n\t\tfalse exit\n\tthen\n\ts\" hint.acpi.0.disabled\" getenv\n\tdup -1 <> if\n\t\ts\" 0\" compare 0<> if\n\t\t\tfalse exit\n\t\tthen\n\telse\n\t\tdrop\n\tthen\n\ttrue\n;\n\n: printmenuitem ( -- n )\n\tmenuidx @\n\t1+ dup\n\tmenuidx !\n\tmenuY @ + dup menuX @ swap at-xy\n\tmenuidx @ .\n\tmenuX @ 1+ swap at-xy\n\tmenubllt @ emit\n\tmenuidx @ 48 +\n;\n\n: beastie-menu ( -- )\n\t0 menuidx !\n\tdot menubllt !\n\t8 menuY !\n\t5 menuX !\n\tclear\n\t46 4 print-beastie\n\t42 20 2 2 box\n\t13 6 at-xy .\" Welcome to FreeBSD!\"\n\tprintmenuitem .\" Boot FreeBSD [default]\" bootkey !\n\ts\" arch-i386\" environment? if\n\t\tdrop\n\t\tprintmenuitem .\" Boot FreeBSD with ACPI \" bootacpikey !\n\t\tacpienabled? if\n\t\t\t.\" disabled\"\n\t\telse\n\t\t\t.\" enabled\"\n\t\tthen\n\telse\n\t\t-2 bootacpikey !\n\tthen\n\tprintmenuitem .\" Boot FreeBSD in Safe Mode\" bootsafekey !\n\tprintmenuitem .\" Boot FreeBSD in single user mode\" bootsinglekey !\n\tprintmenuitem .\" Boot FreeBSD with verbose logging\" bootverbosekey !\n\tprintmenuitem .\" Escape to loader prompt\" escapekey !\n\ts\" arch-i386\" environment? if\n\t\tdrop\n\t\tprintmenuitem .\" Boot FreeBSD with USB keyboard\" bootusbkey !\n\telse\n\t\t-2 bootusbkey !\n\tthen\n\tprintmenuitem .\" Reboot\" rebootkey !\n\tmenuX @ 20 at-xy\n\t.\" Select option, [Enter] for default\"\n\tmenuX @ 21 at-xy\n\ts\" or [Space] to pause timer \" dup 2 - promptwidth !\n\ttype\n;\n\n: tkey\n\tseconds +\n\tbegin 1 while\n\t\tover 0<> if\n\t\t\tdup seconds u< if\n\t\t\t\tdrop\n\t\t\t\t-1\n\t\t\t\texit\n\t\t\tthen\n\t\t\tmenuX @ promptwidth @ + 21 at-xy dup seconds - .\n\t\tthen\n\t\tkey? if\n\t\t\tdrop\n\t\t\tkey\n\t\t\texit\n\t\tthen\n\t50 ms\n\trepeat\n;\n\nset-current\n\n: beastie-start\n\ts\" beastie_disable\" getenv\n\tdup -1 <> if\n\t\ts\" YES\" compare-insensitive 0= if\n\t\t\texit\n\t\tthen\n\telse\n\t\tdrop\n\tthen\n\tbeastie-menu\n\ts\" autoboot_delay\" getenv\n\tdup -1 = if\n\t\tdrop\n\t\t10\n\telse\n\t\t0 0 2swap >number drop drop drop\n\tthen\n\tbegin\n\t\tdup tkey\n\t\t0 25 at-xy\n\t\tdup 32 = if nip 0 swap then\n\t\tdup -1 = if 0 boot then\n\t\tdup 13 = if 0 boot then\n\t\tdup bootkey @ = if 0 boot then\n\t\tdup bootacpikey @ = if\n\t\t\tacpienabled? if\n\t\t\t\ts\" acpi_load\" unsetenv\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\telse\n\t\t\t\ts\" YES\" s\" acpi_load\" setenv\n\t\t\t\ts\" 0\" s\" hint.acpi.0.disabled\" setenv\n\t\t\tthen\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootusbkey @ = if\n\t\t\ts\" 0x1\" s\" hint.atkbd.0.flags\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootsafekey @ = if\n\t\t\ts\" arch-i386\" environment? if\n\t\t\t\tdrop\n\t\t\t\ts\" acpi_load\" unsetenv\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\t\ts\" 1\" s\" hint.apic.0.disabled\" setenv\n\t\t\tthen\n\t\t\ts\" 0\" s\" hw.ata.ata_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.atapi_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.wc\" setenv\n\t\t\ts\" 0\" s\" hw.eisa_slots\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootverbosekey @ = if\n\t\t\ts\" YES\" s\" boot_verbose\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootsinglekey @ = if\n\t\t\ts\" YES\" s\" boot_single\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup escapekey @ = if\n\t\t\t2drop\n\t\t\ts\" NO\" s\" autoboot_delay\" setenv\n\t\t\texit\n\t\tthen\n\t\trebootkey @ = if 0 reboot then\n\tagain\n;\n\nprevious\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"80b81c30a17cad45014984e9c719c3070ffd81fd","subject":"If autoboot_delay is set to -1, boot immediately without checking for a keypress to match the behavior of the loader.","message":"If autoboot_delay is set to -1, boot immediately without checking for\na keypress to match the behavior of the loader.\n\nPR:\t\tdocs\/108101\nSubmitted by:\tWayne Sierke ws of au.dyndns.ws\nTested by:\tbrd\nMFC after:\t1 week\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/beastie.4th","new_file":"sys\/boot\/forth\/beastie.4th","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"bsd-3-clause","lang":"Forth"} {"commit":"e13d1af2ff39e78b3bcb4e54247b1c17d385d331","subject":"Bug fixes in forth code, more words","message":"Bug fixes in forth code, more words\n\nThere is a long way to go with the forth code itself, but it is improving.\n\n'within' has been added, as has 's\"', 'type' has had bug fixed.\n'u.' has been added to fix a bug with at-xy and the other ansi color code words\n","repos":"howerj\/libforth","old_file":"forth.fth","new_file":"forth.fth","new_contents":"#!.\/forth -t\n( Welcome to libforth, A dialect of Forth. Like all versions of Forth this \nversion is a little idiosyncratic, but how the interpreter works is\ndocumented here and in various other files.\n\nThis file contains most of the start up code, some basic start up code\nis executed in the C file as well which makes programming at least bearable.\nMost of Forth is programmed in itself, which may seem odd if your back\nground in programming comes from more traditional language [such as C], \nalthough decidedly less so if you know already know lisp, for example.\n\nFor more information about this interpreter and Forth see: \n\thttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\treadme.md : for a manual for this interpreter\n\tlibforth.h : for information about the C API\n\tlibforth.3 : for limited information about the C API\n\tlibforth.c : for the interpreter itself\n\nThe interpreter and this code originally descend from a Forth interpreter\nwritten in 1992 for the International obfuscated C Coding Competition \n\nSee:\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n)\n\n( ========================== Basic Word Set ================================== )\n( We'll begin by defining very simple words we can use later )\n: < u< ; ( @todo fix this )\n: > u> ; ( @todo fix this )\n: logical ( x -- bool ) not not ;\n: hidden-mask 0x80 ( Mask for the hide bit in a words MISC field ) ;\n: instruction-mask 0x1f ( Mask for the first code word in a words MISC field ) ;\n: hidden? ( PWD -- PWD bool ) dup 1+ @ hidden-mask and logical ;\n: dolit 2 ; ( location of special \"push\" word )\n: compile-instruction 1 ; ( compile code word, threaded code interpreter instruction )\n: run-instruction 2 ; ( run code word, threaded code interpreter instruction )\n: [literal] dolit , , ; ( this word probably needs a better name )\n: literal immediate [literal] ;\n: latest pwd @ ; ( get latest defined word )\n: false 0 ;\n: true 1 ;\n: *+ * + ;\n: 2- 2 - ;\n: 2+ 2 + ;\n: 3+ 3 + ;\n: 2* 1 lshift ;\n: 2\/ 1 rshift ;\n: 4* 2 lshift ;\n: 4\/ 2 rshift ;\n: 8* 3 lshift ;\n: 8\/ 3 rshift ;\n: 256\/ 8 rshift ;\n: mod ( x u -- remainder ) 2dup \/ * - ;\n: *\/ ( n1 n2 n3 -- n4 ) * \/ ; ( warning: this does not use a double cell for the multiply )\n: char key drop key ;\n: [char] immediate char [literal] ;\n: postpone immediate find , ;\n: unless immediate ( bool -- : like 'if' but execute clause if false ) ' 0= , postpone if ;\n: endif immediate ( synonym for 'then' ) postpone then ;\n: bl ( space character ) [char] ; ( warning: white space is significant after [char] )\n: space bl emit ;\n: . pnum space ;\n: address-unit-bits size 8* ;\n: mask-byte ( x -- x ) 8* 0xff swap lshift ;\n: cell+ 1+ ( a-addr1 -- a-addr2 ) ;\n: cells ( n1 -- n2 ) ;\n: char+ ( c-addr1 -- c-addr2 ) 1+ ;\n: chars ( n1 -- n2: convert character address to cell address ) size \/ ;\n: chars> ( n1 -- n2: convert cell address to character address ) size * ;\n: hex ( -- ) ( print out hex ) 16 base ! ;\n: octal ( -- ) ( print out octal ) 8 base ! ;\n: decimal ( -- ) ( print out decimal ) 0 base ! ;\n: negate ( x -- x ) -1 * ;\n: square ( x -- x ) dup * ;\n: +! ( x addr -- ) ( add x to a value stored at addr ) tuck @ + swap ! ;\n: 1+! ( addr -- : increment a value at an address ) 1 swap +! ;\n: 1-! ( addr -- : decrement a value at an address ) -1 swap +! ;\n: lsb ( x -- x : mask off the least significant byte of a cell ) 255 and ;\n: \\ immediate begin key '\\n' = until ;\n: ?dup ( x -- ? ) dup if dup then ;\n: min ( x y -- min ) 2dup < if drop else swap drop then ; \n: max ( x y -- max ) 2dup > if drop else swap drop then ; \n: >= ( x y -- bool ) < not ;\n: <= ( x y -- bool ) > not ;\n: 2@ dup 1+ @ swap @ ;\n: r@ r> r @ swap >r ;\n: 0> 0 > ;\n: 0<> 0 <> ;\n: nand ( x x -- x : Logical NAND ) and not ;\n: nor ( x x -- x : Logical NOR ) or not ;\n: ms ( u -- : wait at least 'u' milliseconds ) clock + begin dup clock < until drop ;\n: sleep 1000 * ms ;\n: align immediate ( x -- x ) ; ( nop in this implementation )\n: ) immediate ;\n: ? ( a-addr -- : view value at address ) @ . cr ;\n: bell 7 ( ASCII BEL ) emit ;\n: b\/buf ( bytes per buffer ) 1024 ;\n: # dup ( x -- x : debug print ) pnum cr ;\n: compile, ' , , ; ( A word that writes , into the dictionary )\n: >mark ( -- ) here 0 , ; \n: r - r> u< ;\n: u. ( u -- : display number in base 10, although signed for now ) \n\tbase @ >r decimal pnum r> base ! ;\n\n: rdrop ( R: x -- )\n\tr> ( get caller's return address )\n\tr> ( get value to drop )\n\tdrop ( drop it like it's hot )\n\t>r ( return return address )\n;\n\n: again immediate \n\t( loop unconditionally in a begin-loop:\n\t\tbegin ... again )\n\t' branch , ] literal ( size of input buffer, in characters )\n\t[ 64 chars> ] literal ( start of input buffer, in characters )\n;\n\n: source-id ( -- 0 | 1 | 2 )\n\t( The returned values correspond to whether the interpreter is\n\treading from the user input device or is evaluating a string,\n\tcurrently the \"evaluate\" word is not accessible from within\n\tthe Forth environment and only via the C-API, however the\n\tvalue can still change, the values correspond to:\n\tValue Input Source\n\t-1 String\n\t0 File Input [this may be stdin] )\n\t`source-id @ ;\n\n: 2drop ( x y -- ) drop drop ;\n: hide ( token -- hide-token ) \n\t( This hides a word from being found by the interpreter )\n\tdup \n\tif \n\t\tdup @ hidden-mask or swap tuck ! \n\telse \n\t\tdrop 0 \n\tthen \n;\n\n: hider ( WORD -- ) ( hide with drop ) find dup if hide then drop ;\n: unhide ( hide-token -- ) dup @ hidden-mask invert and swap ! ;\n\n: original-exit [ find exit ] literal ;\n: exit \n\t( this will define a second version of exit, ';' will\n\tuse the original version, whilst everything else will\n\tuse this version, allowing us to distinguish between\n\tthe end of a word definition and an early exit by other\n\tmeans in \"see\" )\n\t[ find exit hide ] rdrop exit [ unhide ] ;\n\n: ?exit ( x -- ) ( exit current definition if not zero ) if rdrop exit then ;\n\n( ========================== Basic Word Set ================================== )\n\n( ========================== Extended Word Set =============================== )\n: gcd ( a b -- n ) ( greatest common divisor )\n\tbegin\n\t\tdup\n\t\tif\n\t\t\ttuck mod 0\n\t\telse\n\t\t\t1\n\t\tthen\n\tuntil\n\tdrop\n;\n\n: log2 ( x -- log2 ) \n\t( Computes the binary integer logarithm of a number,\n\tzero however returns itself instead of reporting an error )\n\t0 swap \n\tbegin \n\t\tswap 1+ swap 2\/ dup 0= \n\tuntil \n\tdrop 1- \n;\n\n: xt-token ( previous-word-address -- xt-token )\n\t( Given the address of the PWD field of a word this\n\tfunction will return an execution token for the word )\n\t1+ ( MISC field )\n\tdup \n\t@ ( Contents of MISC field )\n\tinstruction-mask and ( Mask off the instruction )\n\t( If the word is not an immediate word, execution token pointer ) \n\tcompile-instruction = +\n;\n\n: ['] immediate find xt-token [literal] ;\n\n: execute ( xt-token -- )\n\t( given an execution token, execute the word )\n\n\t( create a word that pushes the address of a hole to write to\n\ta literal takes up two words, '!' takes up one )\n\t1- ( execution token expects pointer to PWD field, it does not\n\t\tcare about that field however, and increments past it )\n\txt-token\n\t[ here 3+ literal ] \n\t! ( write an execution token to a hole )\n\t[ 0 , ] ( this is the hole we write )\n;\n\n( ========================== Extended Word Set =============================== )\n\n\n( ========================== CREATE DOES> ==================================== )\n\n( The following section defines a pair of words \"create\" and \"does>\" which \nare a powerful set of words that can be used to make words that can create\nother words. \"create\" has both run time and compile time behavior, whilst\n\"does>\" only works at compile time in conjunction with \"create\". These two\nwords can be used to add constants, variables and arrays to the language,\namongst other things.\n\nA simple version of create is as follows \n\t: create :: 2 , here 2 + , ' exit , 0 state ! ; \nBut this version is much more limited )\n\n: write-quote ['] ' , ; ( A word that writes ' into the dictionary )\n: write-exit ['] exit , ; ( A word that write exit into the dictionary ) \n\n: state! ( bool -- ) ( set the compilation state variable ) state ! ;\n\n: command-mode false state! ;\n\n: command-mode-create ( create a new work that pushes its data field )\n\t:: ( compile a word )\n\tdolit , ( write push into new word )\n\there 2+ , ( push a pointer to data field )\n\t['] exit , ( write in an exit to new word data field is after exit )\n\tcommand-mode ( return to command mode )\n;\n\n: mark compile, ( Write in a place holder 0 and push a pointer to to be used by does> )\n\twrite-quote write-exit compile, ( Write in an exit in the word we're compiling. )\n\t['] command-mode , ( Make sure to change the state back to command mode )\n;\n\n: create immediate ( create word is quite a complex forth word )\n state @ if postpone ( whole-to-patch -- ) \n\timmediate\n\twrite-exit ( we don't want the defining to exit, but the *defined* word to )\n\there swap ! ( patch in the code fields to point to )\n\trun-instruction , ( write a run in )\n;\n\n: >body ( xt -- a-addr : a-addr is data field of a CREATEd word )\n\txt-token 5 + ;\nhider write-quote \n\n( ========================== CREATE DOES> ==================================== )\n\n: array ( length -- : create a array ) create allot does> + ;\n: table ( length -- : create a table ) create allot does> ;\n: variable ( initial-value -- : create a variable ) create , does> ;\n: constant ( value -- : create a constant ) create , does> @ ;\n\n( do...loop could be improved by not using the return stack so much )\n\n: do immediate\n\t' swap , ( compile 'swap' to swap the limit and start )\n\t' >r , ( compile to push the limit onto the return stack )\n\t' >r , ( compile to push the start on the return stack )\n\there ( save this address so we can branch back to it )\n;\n\n: addi \n\t( @todo simplify )\n\tr@ 1- ( get the pointer to i )\n\t+! ( add value to it )\n\tr@ 1- @ ( find the value again )\n\tr@ 2- @ ( find the limit value )\n\t<\n\tif\n\t\tr@ @ @ r@ @ + r@ ! exit ( branch )\n\tthen\n\tr> 1+\n\trdrop\n\trdrop\n\t>r\n;\n\n: loop immediate 1 [literal] ' addi , r> ( pop off return address and i ) \n\ttuck ( tuck i away ) \n\t>r >r ( restore return stack ) \n;\n\n: range ( nX nY -- nX nX+1 ... nY ) swap 1+ swap do i loop ;\n: repeater ( n0 X -- n0 ... nX ) 1 do dup loop ;\n: sum ( n0 ... nX X -- sum<0..X> ) 1 do + loop ;\n: mul ( n0 ... nX X -- mul<0..X> ) 1 do * loop ;\n\n: factorial ( n -- n! )\n\t( This factorial is only here to test range, mul, do and loop )\n\tdup 1 <= \n\tif\n\t\tdrop\n\t\t1\n\telse ( This is obviously super space inefficient )\n \t\tdup >r 1 range r> mul\n\tthen\n;\n\n: tail \n\t( This function implements tail calls, which is just a jump\n\tto the beginning of the words definition, for example this\n\tword will never overflow the stack and will print \"1\" followed\n\tby a new line forever,\n \n\t\t: forever 1 . cr tail ; \n\n\tWhereas\n\n\t\t: forever 1 . cr recurse ;\n\n\tor\n\n\t\t: forever 1 . cr forever ;\n\n\tWould overflow the return stack. )\n\timmediate\n\tlatest xt-token \n\t' branch ,\n\there - 1+ ,\n;\n\n: recurse immediate\n\t( This function implements recursion, although this interpreter\n\tallows calling a word directly. If used incorrectly this will\n\tblow up the return stack.\n\n\tWe can test \"recurse\" with this factorial function:\n\t : factorial dup 2 < if drop 1 exit then dup 1- recurse * ;)\n\tlatest xt-token , ;\n: myself immediate postpone recurse ;\n\n0 variable column-counter\n4 variable column-width\n: column ( i -- )\tcolumn-width @ mod not if cr then ;\n: reset-column\t\t0 column-counter ! ;\n: auto-column\t\tcolumn-counter dup @ column 1+! ;\n\n: alignment-bits [ 1 size log2 lshift 1- literal ] and ;\n: name ( PWD -- c-addr ) \n\t( given a pointer to the PWD field of a word get a pointer to the name\n\tof the word )\n\tdup 1+ @ 256\/ lsb - chars> ;\n\n: c@ ( character-address -- char )\n\t( retrieve a character from an address )\n\tdup chars @\n\t>r \n\t\talignment-bits \n\t\tdup \n\t\tmask-byte \n\tr> \n\tand swap 8* rshift\n;\n\n: c! ( char character-address -- )\n\t( store a character at an address )\n\tdup \n\t>r ( new addr -- addr )\n\t\talignment-bits 8* lshift ( shift character into correct byte )\n\tr> ( new* addr )\n\tdup chars @ ( new* addr old )\n\tover ( new* addr old addr ) \n\talignment-bits mask-byte invert and ( new* addr old* )\n\trot or swap chars !\n;\n\n0 variable x\n: x! ( x -- ) x ! ;\n: x@ ( -- x ) x @ ;\n\n: 2>r ( x1 x2 -- R: x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tswap\n\t\t>r \n\t\t>r \n\tx@ >r ( restore return address )\n;\n\n: 2r> ( R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tr>\n\t\tr>\n\t\tswap\n\tx@ >r ( restore return address )\n;\n\n: 2r@ ( -- x1 x2 ) ( R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\tr> r>\n\t2dup\n\t>r >r\n\tswap\n\tx@ >r ( restore return address )\n;\n\n: unused ( -- u ) ( push the amount of core left ) max-core here - ;\n\n: roll \n\t( xu xu-1 ... x0 u -- xu-1 ... x0 xu )\n\t( remove u and rotate u+1 items on the top of the stack,\n\tthis could be replaced with a move on the stack and\n\tsome magic so the return stack is used less )\n\tdup 0 > \n\tif \n\t\tswap >r 1- roll r> swap \n\telse \n\t\tdrop \n\tthen ;\n\n: accumulator ( \" ccc\" -- : make a word that increments by a value and pushes the result )\n\tcreate , does> tuck +! @ ;\n\n0 variable delim\n: accepter\n\t( c-addr max delimiter -- i )\n\t( store a \"max\" number of chars at c-addr until \"delimiter\" encountered,\n\tthe number of characters stored is returned )\n\tkey drop ( drop first key after word )\n\tdelim ! ( store delimiter used to stop string storage when encountered)\n\t0\n\tdo\n\t\tkey dup delim @ <>\n\t\tif\n\t\t\tover c! 1+ \n\t\telse ( too many characters read in )\n\t\t\t0 swap c! drop\n\t\t\ti 1+\n\t\t\tleave\n\t\tthen\n\tloop\n\tbegin ( read until delimiter )\n\t\tkey delim @ =\n\tuntil\n;\nhider delim \n\n: '\"' ( -- char : push literal \" character ) [char] \" ;\n: accept ( c-addr +n1 -- +n2 : see accepter definition ) swap '\\n' accepter ;\n\n4096 constant max-string-length \n: accept-string max-string-length '\"' accepter ;\n\n0 variable delim\n: print-string \n\t( delimiter -- )\n\t( print out the next characters in the input stream until a \n\t\"delimiter\" character is reached )\n\tkey drop\n\tdelim !\n\tbegin \n\t\tkey dup delim @ = \n\t\tif \n\t\t\tdrop exit \n\t\tthen \n\t\temit 0 \n\tuntil \n;\nhider delim \n\nsize 1- constant aligner \n: aligned \n\taligner + aligner invert and\n;\nhider aligner \n\n0 variable delim\n: write-string ( char -- c-addr u )\n\t( @todo This really needs simplifying, to do this\n\ta set of words that operate on a temporary buffer can\n\tbe used )\n\t( Write a string into word being currently defined, this\n\tcode has to jump over the string it has just put into the\n\tdictionary so normal execution of a word can continue. The\n\tlength and character address of the string are left on the\n\tstack )\n\tdelim ! ( save delimiter )\n\t' branch , ( write in jump, this will jump past the string )\n\t>mark ( make hole )\n\tdup 1+ chars> ( calculate address to write to )\n\tmax-string-length delim @ accepter dup >r ( write string into dictionary, save index )\n\taligned 2dup size \/ ( stack: length hole char-len hole )\n\tdup here + h ! ( update dictionary pointer with string length )\n\t1+ swap ! ( write place to jump to )\n\tdrop ( do not need string length anymore )\n\t1+ chars> ( calculate place to print )\n\tr> ( restore index and address of string )\n;\nhider delim\n\n: type ( c-addr u -- : print out 'u' characters at c-addr )\n\t0 do dup c@ emit 1+ loop drop ;\n\n: do-string ( char -- )\n\tstate @ if write-string swap [literal] [literal] ' type , else print-string then ;\n\n: c\" immediate '\"' write-string ;\n\n: \" immediate '\"' do-string ;\n: .( immediate ')' do-string ;\n: .\" immediate '\"' do-string ;\n\n: ok \" ok\" cr ;\n\n( ==================== CASE statements ======================== )\n\n( for a simpler case statement: \n\tsee Volume 2, issue 3, page 48 of Forth Dimensions at \n\thttp:\/\/www.forth.org\/fd\/contents.html )\n\n: case immediate \n\t' branch , 3 , ( branch over the next branch )\n\there ' branch , ( mark: place endof branches back to with again )\n\t>mark swap ; ( mark: place endcase writes jump to with then )\n\n: over= over = ; \n: of immediate ' over= , postpone if ;\n: endof immediate over postpone again postpone then ;\n: endcase immediate postpone then drop ;\n\n( ==================== CASE statements ======================== )\n\n: error-no-word ( print error indicating last read in word as source )\n\t\" error: word '\" source drop print \" ' not found\" cr ;\n\n: ;hide ( should only be matched with ':hide' ) \n\timmediate \" error: ';hide' without ':hide'\" cr ;\n\n: :hide\n\t( hide a list of words, the list is terminated with \";hide\" )\n\tbegin\n\t\tfind ( find next word )\n\t\tdup [ find ;hide ] literal = if \n\t\t\tdrop exit ( terminate :hide )\n\t\tthen\n\t\tdup 0= if ( word not found )\n\t\t\tdrop \n\t\t\terror-no-word\n\t\t\texit \n\t\tthen\n\t\thide drop\n\tagain\n;\n\n: count ( c-addr1 -- c-addr2 u ) dup c@ swap 1+ swap ;\n\n: fill ( c-addr u char -- )\n\t( fill in an area of memory with a character, only if u is greater than zero )\n\t-rot\n\t0 do 2dup i + c! loop\n\t2drop \n;\n\n: spaces ( n -- : print n spaces ) 0 do space loop ;\n: erase ( addr u : erase a block of memory )\n\tchars> swap chars> swap 0 fill ;\n\n: blank ( c-addr u )\n\t( given a character address and length, this fills that range with spaces )\n\tbl fill ;\n\n: move ( addr1 addr2 u -- )\n\t( copy u words of memory from 'addr2' to 'addr1' )\n\t0 do\n\t\t2dup i + @ swap i + !\n\tloop\n\t2drop\n;\n\n( It would be nice if move and cmove could share more code, as they do exactly\n the same thing but with different load and store functions, cmove> )\n: cmove ( c-addr1 c-addr2 u -- )\n\t( copy u characters of memory from 'c-addr2' to 'c-addr1' )\n\t0 do\n\t\t2dup i + c@ swap i + c!\n\tloop\n\t2drop\n;\n\n( The words \"[if]\", \"[else]\" and \"[then]\" implement conditional compilation,\nthey can be nested as well\n\nSee http:\/\/lars.nocrew.org\/dpans\/dpans15.htm for more information\n\nA much simpler conditional compilation method is the following\nsingle word definition:\n\n : compile-line? 0= if [ find \\\\ , ] then ;\n\nWhich will skip a line if a conditional is false, and compile it\nif true )\n\n( These words really, really need refactoring )\n0 variable nest ( level of [if] nesting )\n0 variable [if]-word ( populated later with \"find [if]\" )\n0 variable [else]-word ( populated later with \"find [else]\")\n: [then] immediate ; \n: reset-nest 1 nest ! ;\n: unnest? [ find [then] ] literal = if nest 1-! then ;\n: nest? [if]-word @ = if nest 1+! then ;\n: end-nest? nest @ 0= ;\n: match-[else]? [else]-word @ = nest @ 1 = and ; \n\n: [if] ( bool -- : conditional execution )\n\tunless\n\t\treset-nest\n\t\tbegin\n\t\t\tfind \n\t\t\tdup nest?\n\t\t\tdup match-[else]? if drop exit then\n\t\t\t unnest?\n\t\t\tend-nest?\n\t\tuntil\n\tthen\n;\n\n: [else] ( discard input until [then] encounter, nesting for [if] )\n\treset-nest\n\tbegin\n\t\tfind\n\t\tdup nest? unnest?\n\t\tend-nest?\n\tuntil\n;\nfind [if] [if]-word !\nfind [else] [else]-word ! \n\n:hide [if]-word [else]-word nest reset-nest unnest? match-[else]? ;hide\n\nsize 2 = [if] 0x0123 variable endianess [then]\nsize 4 = [if] 0x01234567 variable endianess [then]\nsize 8 = [if] 0x01234567abcdef variable endianess [then]\n\n: endian ( -- bool )\n\t( returns the endianess of the processor )\n\t[ endianess chars> c@ 0x01 = ] literal \n;\nhider endianess\n\n: pad \n\t( the pad is used for temporary storage, and moves\n\talong with dictionary pointer, always in front of it )\n\there 64 + ;\n\n0 variable counter\n: counted-column ( index -- )\n\t( special column printing for dump )\n\tcounter @ column-width @ mod \n\tnot if cr . \" :\" space else drop then\n\tcounter 1+! ;\n\n: lister 0 counter ! swap do i counted-column i @ . loop ;\n\n( @todo dump should print out the data as characters as well, if printable )\n: dump ( addr u -- : dump out 'u' cells of memory starting from 'addr' )\n\tbase @ >r hex 1+ over + lister r> base ! cr ;\n:hide counted-column counter lister ;hide\n\n: forgetter ( pwd-token -- : forget a found word and everything after it )\n\tdup @ pwd ! h ! ;\n\n: forget ( WORD -- : forget word and every word defined after it )\n\tfind 1- forgetter ;\n\n: marker ( WORD -- : make word the forgets itself and words after it)\n\t:: latest [literal] ' forgetter , postpone ; ;\nhider forgetter\n\n: ?dup-if immediate ( x -- x | - ) \n\t' ?dup , postpone if ;\n\n: ** ( b e -- x : exponent, raise 'b' to the power of 'e')\n\tdup\n\tif \n\t\tdup\n\t\t1\n\t\tdo over * loop\n\telse\n\t\tdrop\n\t\t1\n\tendif\n;\n\n( ==================== Random Numbers ========================= )\n\n( See: \n\tuses xorshift\n\thttps:\/\/en.wikipedia.org\/wiki\/Xorshift\n\thttp:\/\/excamera.com\/sphinx\/article-xorshift.html\n\thttp:\/\/www.arklyffe.com\/main\/2010\/08\/29\/xorshift-pseudorandom-number-generator\/\n)\n( these constants have be collected from the web )\nsize 2 = [if] 13 constant a 9 constant b 7 constant c [then]\nsize 4 = [if] 13 constant a 17 constant b 5 constant c [then]\nsize 8 = [if] 12 constant a 25 constant b 27 constant c [then]\n\n7 variable seed ( must not be zero )\n\n: seed! ( u -- : set the value of the PRNG seed )\n\tdup 0= if drop 7 ( zero not allowed ) then seed ! ;\n\n: random\n\t( assumes word size is 32 bit )\n\tseed @ \n\tdup a lshift xor\n\tdup b rshift xor\n\tdup c lshift xor\n\tdup seed! ;\n:hide a b c seed ;hide\n\n( ==================== Random Numbers ========================= )\n\n( ==================== ANSI Escape Codes ====================== )\n(\n\tsee: https:\/\/en.wikipedia.org\/wiki\/ANSI_escape_code \n\tThese codes will provide a relatively portable means of \n\tmanipulating a terminal\n\n\t@bug won't work if hex is set\n)\n\n27 constant 'escape'\nchar ; constant ';'\n: CSI 'escape' emit .\" [\" ;\n0 constant black \n1 constant red \n2 constant green \n3 constant yellow \n4 constant blue \n5 constant magenta \n6 constant cyan \n7 constant white \n: foreground 30 + ;\n: background 40 + ;\n0 constant dark\n1 constant bright\n\n: color ( brightness color-code -- )\n\t( set color on an ANSI compliant terminal,\n\tfor example:\n\t\tbright red foreground color\n\tsets the foreground text to bright red )\n\tCSI u. if .\" ;1\" then .\" m\" ;\n\n: at-xy ( x y -- : set ANSI terminal cursor position to x y ) \n\tCSI u. ';' emit u. .\" H\" ;\n: page ( clear ANSI terminal screen and move cursor to beginning ) CSI .\" 2J\" 1 1 at-xy ;\n: hide-cursor ( hide the cursor from view ) CSI .\" ?25l\" ;\n: show-cursor ( show the cursor ) CSI .\" ?25h\" ;\n: save-cursor ( save cursor position ) CSI .\" s\" ;\n: restore-cursor ( restore saved cursor position ) CSI .\" u\" ;\n: reset-color CSI .\" 0m\" ;\nhider CSI\n( ==================== ANSI Escape Codes ====================== )\n\n\n( ==================== Prime Numbers ========================== )\n( from original \"third\" code from the ioccc http:\/\/www.ioccc.org\/1992\/buzzard.2.design )\n: prime? ( x -- x\/0 : return number if it is prime, zero otherwise )\n\tdup 1 = if 1- exit then\n\tdup 2 = if exit then\n\tdup 2 \/ 2 ( loop from 2 to n\/2 )\n\tdo\n\t\tdup ( value to check if prime )\n\t\ti mod ( mod by divisor )\n\t\tnot if\n\t\t\tdrop 0 leave\n\t\tthen\n\tloop\n;\n\n0 variable counter\n: primes\n\t0 counter !\n\t\" The primes from \" dup . \" to \" over . \" are: \"\n\tcr\n\treset-column\n\tdo\n\t\ti prime?\n\t\tif\n\t\t\ti . counter @ column counter 1+!\n\t\tthen\n\tloop\n\tcr\n\t\" There are \" counter @ . \" primes.\"\n\tcr ;\nhider counter\n( ==================== Prime Numbers ========================== )\n\n( ==================== Debugging info ========================= )\n\n( string handling should really be done with PARSE, and CMOVE )\n: .s ( -- : print out the stack for debugging )\n\tdepth if\n\t\tdepth 0 do i column tab i pick . loop\n\tthen\n\tcr ;\n\n1 variable hide-words ( do we want to hide hidden words or not )\n: words ( -- )\n\t( This function prints out all of the defined words, excluding hidden words.\n\tAn understanding of the layout of a Forth word helps here. The dictionary\n\tcontains a linked list of words, each forth word has a pointer to the previous\n\tword until the first word. The layout of a Forth word looks like this:\n\n\tNAME: Forth Word - A variable length ASCII NUL terminated string\n\tPWD: Previous Word Pointer, points to the previous word\n\tMISC: Flags, code word and offset from previous word pointer to start of Forth word string\n\tCODE\/DATA: The body of the forth word definition, not interested in this.\n\t\n\tThere is a register which stores the latest defined word which can be\n\taccessed with the code \"pwd @\". In order to print out a word we need to\n\taccess a words MISC field, the offset to the NAME is stored here in bits\n\t8 to 15 and the offset is calculated from the PWD field.\n\n\t\"print\" expects a character address, so we need to multiply any calculated\n\taddress by the word size in bytes. )\n\treset-column\n\tlatest \n\tbegin \n\t\tdup \n\t\thidden? hide-words @ and\n\t\tnot if \n\t\t\tname\n\t\t\tprint tab \n\t\t\tauto-column\n\t\telse \n\t\t\tdrop \n\t\tthen \n\t\t@ ( Get pointer to previous word )\n\t\tdup dictionary-start < ( stop if pwd no longer points to a word )\n\tuntil \n\tdrop cr \n; \nhider hide-words\n\n: registers ( -- )\n\t( print out important registers and information about the\n\tvirtual machine )\n\t\" return stack pointer: \" r@ . cr\n\t\" dictionary pointer \" here . cr\n\t\" previous word: \" pwd @ . cr\n\t\" state: \" state @ . cr\n\t\" base: \" base @ . cr\n\t\" depth: \" depth . cr\n\t\" cell size (in bytes): \" size . cr\n\t\" last cell address: \" max-core . cr\n\t\" unused cells: \" unused . cr\n\t( We could determine if we are reading from stdin by looking\n\tat the stdin register )\n\t\" current input source: \" source-id -1 = if \" string\" else \" file\" then cr\n\t( depth if \" Stack: \" .s then )\n\t( \" Raw Register Values: \" cr 0 31 dump )\n;\n\n: y\/n? ( -- bool : ask a yes or no question )\n\tkey drop\n\t\" y\/n? \"\n\tbegin\n\t\tkey\n\t\tdup \n\t\t[char] y = if true exit then\n\t\t[char] n = if false exit then\n\t\t\" y\/n? \"\n\tagain ;\n\n: TrueFalse if \" true\" else \" false\" then ;\n: >instruction ( extract instruction from instruction field ) 0x1f and ;\n\n: step\n\t( step through a word: this word could be augmented\n\twith commands such as \"dump\", \"halt\", and optional\n\t\".s\" and \"registers\" )\n\tregisters\n\t\" .s: \" .s cr\n\t\" -- press any key to continue -- \"\n\tkey drop ;\n\n: more ( wait for more input )\n\t\" -- press any key to continue -- \" key drop cr ;\n\n: debug-help \" debug mode commands \n\th - print help\n\tq - exit containing word\n\tr - print registers\n\ts - print stack\n\tc - continue on with execution \n\" ;\n: debug-prompt .\" debug> \" ;\n: debug ( a work in progress, debugging support, needs parse-word )\n\tcr\n\tbegin\n\t\tdebug-prompt\n\t\tkey dup '\\n' <> if source accept drop then\n\t\tcase\n\t\t\t[char] h of debug-help endof\n\t\t\t[char] q of drop rdrop exit ( call abort when this exists ) endof\n\t\t\t[char] r of registers endof\n\t\t\t\\ [char] d of dump endof \\ implement read in number\n\t\t\t[char] s of >r .s r> endof \n\t\t\t[char] c of drop exit endof\n\t\tendcase \n\tagain ;\nhider debug-prompt\n\n0 variable cf\n: code>pwd ( CODE -- PWD\/0 )\n\t( @todo simplify using \"within\"\n\t given a pointer to a executable code field\n\tthis words attempts to find the PWD field for\n\tthat word, or return zero )\n\tdup here >= if drop 0 exit then ( cannot be a word, too small )\n\tdup dictionary-start <= if drop 0 exit then ( cannot be a word, too large )\n\tcf !\n\tlatest dup @ ( p1 p2 )\n\tbegin\n\t\tover ( p1 p2 p1 )\n\t\tcf @ <= swap cf @ > and if exit then\n\t\tdup 0= if exit then \n\t\tdup @ swap \n\tagain\n;\nhider cf\n\n: end-print ( x -- ) \" => \" . \" )\" cr ;\n: word-printer\n\t( attempt to print out a word given a words code field\n\tWARNING: This is a dirty hack at the moment\n\tNOTE: given a pointer to somewhere in a word it is possible\n\tto work out the PWD by looping through the dictionary to\n\tfind the PWD below it )\n\t1- dup @ -1 = if \" ( noname )\" end-print exit then\n\t dup \" ( \" code>pwd dup if name print else drop \" data\" then \n\t end-print ;\nhider end-print\n\n: decompile ( code-field-ptr -- )\n\t( @todo Rewrite, simplify and get this working correctly\n \n\tThis word expects a pointer to the code field of a word, it\n\tdecompiles a words code field, it needs a lot of work however.\n\tThere are several complications to implementing this decompile\n\tfunction, \":noname\", \"branch\", multiple \"exit\" commands, and literals.\n\n\tThis word really needs CASE statements before it can be\n\tcompleted, as it stands the function is not complete\n\n\t:noname This has a marker before its code field of -1 which\n\t cannot occur normally\n\tbranch branches are used to skip over data, but also for\n\t some branch constructs, any data in between can only\n\t be printed out generally speaking \n\texit There are two definitions of exit, the one used in\n\t\t ';' and the one everything else uses, this is used\n\t\t to determine the actual end of the word\n\tliterals Literals can be distinguished by their low value,\n\t which cannot possibly be a word with a name, the\n\t next field is the actual literal \n\n\tOf special difficult is processing 'if' 'else' 'then' statements,\n\tthis will require keeping track of '?branch'.\n\n\tAlso of note, a number greater than \"here\" must be data )\n\t255 0\n\tdo\n\t\ttab \n\t\tdup @ dolit = if \" ( literal => \" 1+ dup @ . 1+ \" )\" cr tab then\n\t\tdup @ [ find branch xt-token ] literal = if \" ( branch => \" 1+ dup @ . \" )\" cr dup dup @ dump dup @ + cr tab then\n\t\tdup @ [ original-exit xt-token ] literal = if \" ( exit )\" i cr leave then\n\t\tdup @ word-printer\n\t\t1+\n\tloop\n\tcr\n\t255 = if \" decompile limit exceeded\" cr then\n\tdrop ;\n\nhider word-printer\n\n: xt-instruction ( extract instruction from execution token ) \n\txt-token @ >instruction ;\n( these words expect a pointer to the PWD field of a word )\n: defined-word? xt-instruction run-instruction = ;\n: print-name \" name: \" name print cr ;\n: print-start \" word start: \" name chars . cr ;\n: print-previous \" previous word: \" @ . cr ;\n: print-immediate \" immediate: \" 1+ @ >instruction compile-instruction <> TrueFalse cr ;\n: print-instruction \" instruction: \" xt-instruction . cr ;\n: print-defined \" defined: \" defined-word? TrueFalse cr ;\n\n: print-header ( PWD -- is-immediate-word? )\n\tdup print-name\n\tdup print-start\n\tdup print-previous\n\tdup print-immediate\n\tdup print-instruction ( TODO look up instruction name )\n\tprint-defined ;\n\n: see \n\t( decompile a word )\n\tfind \n\tdup 0= if drop error-no-word exit then\n\t1- ( move to PWD field )\n\tdup print-header\n\tdup defined-word?\n\tif ( decompile if a compiled word )\n\t\txt-token 1+ ( move to code field )\n\t\t\" code field:\" cr\n\t\tdecompile\n\telse ( the instruction describes the word if it is not a compiled word )\n\t\tdrop\n\tthen ;\n\n: empty-stack ( x-n ... x-0 -- : empty the variable stack )\n\tbegin depth while drop repeat ;\n\nr @ constant restart-address\n: quit\n\t0 `source-id ! ( set source to read from file )\n\t`stdin @ `fin ! ( read from stdin )\n\tpostpone [ ( back into command mode )\n\trestart-address r ! ( restart interpreter; this needs improving ) ;\n\n: abort empty-stack quit ;\n\n( These help messages could be moved to blocks, the blocks could then\n be loaded from disk and printed instead of defining the help here,\n this would allow much larger help )\n: help ( print out a short help message )\n\tpage\n\tkey drop\n\" Welcome to Forth, an imperative stack based language. It is both a low\nlevel and a high level language, with a very small memory footprint. Most\nof Forth is defined as a combination of various primitives.\n\nA short description of the available function (or Forth words) follows,\nwords marked (1) are immediate and cannot be used in command mode, words\nmarked with (2) define new words. Words marked with (3) have both command\nand compile functionality.\n\n\" \nmore \" The built in words that accessible are:\n\n(1,2)\t: define a new word, switching to compile mode\n\timmediate make latest defined word immediate\n\tread read in a word, execute in command mode else compile \n\t@ ! fetch, store\n\t- + * \/ standard arithmetic operations,\n\tand or xor invert standard bit operations\n\tlshift rshift left and right bit shift\n\t< > = comparison predicates\n\texit exit from a word\n\temit print character from top of stack\n\tkey get a character from input\n\tr> >r pop a value from or to the return stack\n\tfind find a word in the dictionary and push the location\n\t' store the address of the following word on the stack\n\t, write the top of the stack to the dictionary\n\tsave load save or load a block at address to indexed file\n\tswap swap first two values on the stack\n\tdup duplicate the top of the stack\n\tdrop pop and drop a value\n\tover copy the second stack value over the first\n\t. pop the top of the stack and print it\n\tprint print a NUL terminated string at a character address\n\tdepth get the current stack depth\n\tclock get the time since execution start in milliseconds\n\n \"\n\nmore \" All of the other words in the interpreter are built from these\nprimitive words. A few examples:\n\n(1)\tif...else...then FORTH branching construct \n(1)\tbegin...until loop until top of stack is non zero\n(1)\tbegin...again infinite loop\n(1)\tdo...loop FORTH looping construct\n(2,3)\tcreate create a new word that pushes its location\n(1)\tdoes> declare a created words run time behaviour\n(1,2)\tvariable declare variable with initial value from top of stack\n(1,2)\tconstant declare a constant, taken from top of stack\n(1,2)\tarray declare an array with size taken from top of stack\n(1)\t; terminate a word definition and return to command mode\n\twords print out a list of all the defined words\n\thelp this help message\n\tdump print out memory contents starting at an address\n\tregisters print out the contents of the registers\n\tsee decompile a word, viewing what words compose it\n\t.s print out the contents of the stack\n\n\"\n\nmore \" Some more advanced words:\n\n\there push the dictionary pointer\n\th push the address of the dictionary pointer\n\tr push the return stack pointer\n\tallot allocate space in the dictionary\n(1)\t[ switch to command mode\n\t] switch to compile mode\n\t:: compile ':' into the dictionary\n\n\"\n\nmore \"\nFor more information either consult the manual pages forth(1) and libforth(1)\nor consult the following sources:\n\n\thttps:\/\/github.com\/howerj\/libforth \n\thttp:\/\/work.anapnea.net\/html\/html\/projects.html\n\nAnd for a larger tutorial:\n\n\thttps:\/\/github.com\/howerj\/libforth\/blob\/master\/readme.md\n\nFor resources on Forth:\n\n\thttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\thttps:\/\/rwmj.wordpress.com\/2010\/08\/07\/jonesforth-git-repository\/\n\n -- end --\n\" cr\n;\n\n( ==================== Blocks ================================= )\n\n( @todo process invalid blocks [anything greater or equal to 0xFFFF] )\n( @todo only already created blocks can be loaded, this should be\n corrected so one is created if needed )\n( @todo better error handling )\n\n-1 variable scr-var \nfalse variable dirty ( has the buffer been modified? )\n: scr ( -- x : last screen used ) scr-var @ ;\nb\/buf chars table block-buffer ( block buffer - enough to store one block )\n\n: update ( mark block buffer as dirty, so it will be flushed if needed )\n\ttrue dirty ! ;\n: empty-buffers ( discard any buffers )\n\tfalse dirty ! block-buffer b\/buf chars erase ;\n: flush dirty @ if block-buffer chars> scr bsave drop false dirty ! then ;\n\n: list ( block-number -- : display a block )\n\tflush\n\tdup dup scr <> if\n\t\tblock-buffer chars> swap bload ( load buffer into block buffer )\n\t\tswap scr-var !\n\telse\n\t\t2drop 0\n\tthen\n\t-1 = if exit then ( failed to load )\n\tblock-buffer chars> b\/buf type ; ( print buffer )\n\n: block ( u -- addr : load block 'u' and push address to block )\n\tdup scr <> if flush block-buffer chars> swap bload then\n\t-1 = if -1 else block-buffer then ;\n\n: save-buffers flush ;\n\n: list-thru ( x y -- : list blocks x through to y )\n\t1+ swap \n\tkey drop\n\tdo \" screen no: \" i . cr i list cr more loop ;\n\n( ==================== Blocks ================================= )\n\n( clean up the environment )\n:hide\n scr-var block-buffer\n write-string do-string accept-string ')' alignment-bits print-string '\"'\n compile-instruction dictionary-start hidden? hidden-mask instruction-mask \n max-core run-instruction x x! x@ write-exit \n accepter max-string-length xt-token error-no-word\n original-exit\n restart-address pnum\n decompile TrueFalse >instruction print-header \n print-name print-start print-previous print-immediate \n print-instruction xt-instruction defined-word? print-defined\n `state \n `source-id `sin `sidx `slen `start-address `fin `fout `stdin\n `stdout `stderr `argc `argv `debug `invalid `top `instruction\n `stack-size `start-time\n;hide\n\n\n\n( \n: actual-base base @ dup 0= if drop 10 then ;\n: pnum\n\tdup\n\tactual-base mod [char] 0 +\n\tswap actual-base \/ dup\n\tif pnum 0 then\n\tdrop emit\n;\n\n: .\n\tdup 0 < \n\tif\n\t\t[char] - emit negate\n\tthen\n\tpnum\n\tspace\n; )\n\n( TODO\n\t* Evaluate \n\t* By adding \"c@\" and \"c!\" to the interpreter I could remove print\n\tand put string functionality earlier in the file\n\t* Add unit testing to the end of this file\n\t* Word, Parse, other forth words\n\t* Add a dump core and load core to the interpreter?\n\t* add \"j\" if possible to get outer loop context\n\t* FORTH, VOCABULARY \n\t* \"Value\", \"To\", \"Is\"\n\t* A small block editor\n\t* more help commands would be good, such as \"help-ANSI-escape\",\n\t\"tutorial\", etc.\n\t* Abort and Abort\", this could be used to implement words such\n\tas \"abort if in compile mode\", or \"abort if in command mode\".\n\t* Todo Various different assemblers [assemble VM instructions,\n\tnative instructions, and cross assemblers]\n\t* common words and actions should be factored out to simplify\n\tdefinitions of other words, their standards compliant version found\n\tif any\n\t* An assembler mode would execute primitives only, this would\n\trequire a change to the interpreter\n\t* throw and exception\n\t* here documents, string literals\n\t* A set of words for navigating around word definitions would be\n\thelp debugging words, for example:\n\t\tcompile-field code-field field-translate\n\twould take a pointer to a compile field for a word and translate\n\tthat into the code field\n\t* [ifdef] [ifundef]\n\t* if strings were stored in word order instead of byte order\n\tthen external tools could translate the dictionary by swapping\n\tthe byte order of it\n\t* store strings as length + string instead of ASCII strings\n\t* proper booleans should be used throughout\n\t* escaped strings\n\t* ideally all of the functionality of main_forth would be\n\tmoved into this file\n\t* fill move and the like are technically not compliant as\n\tthey do not test if the number is negative, however that would\n\tunnecessarily limit the range of operation\n\t* \"print\" should be removed from the interpreter\n\nSome interesting links:\n\t* http:\/\/www.figuk.plus.com\/build\/heart.htm\n\t* https:\/\/groups.google.com\/forum\/#!msg\/comp.lang.forth\/NS2icrCj1jQ\/1btBCkOWr9wJ\n\t* http:\/\/newsgroups.derkeiler.com\/Archive\/Comp\/comp.lang.forth\/2005-09\/msg00337.html\n\t* https:\/\/stackoverflow.com\/questions\/407987\/what-are-the-primitive-forth-operators\n)\n\n","old_contents":"#!.\/forth -t\n( Welcome to libforth, A dialect of Forth. Like all versions of Forth this \nversion is a little idiosyncratic, but how the interpreter works is\ndocumented here and in various other files.\n\nThis file contains most of the start up code, some basic start up code\nis executed in the C file as well which makes programming at least bearable.\nMost of Forth is programmed in itself, which may seem odd if your back\nground in programming comes from more traditional language [such as C], \nalthough decidedly less so if you know already know lisp, for example.\n\nFor more information about this interpreter and Forth see: \n\thttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\treadme.md : for a manual for this interpreter\n\tlibforth.h : for information about the C API\n\tlibforth.3 : for limited information about the C API\n\tlibforth.c : for the interpreter itself\n\nThe interpreter and this code originally descend from a Forth interpreter\nwritten in 1992 for the International obfuscated C Coding Competition \n\nSee:\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n)\n\n( ========================== Basic Word Set ================================== )\n( We'll begin by defining very simple words we can use later )\n: < u< ; ( @todo fix this )\n: > u> ; ( @todo fix this )\n: logical ( x -- bool ) not not ;\n: hidden-mask 0x80 ( Mask for the hide bit in a words MISC field ) ;\n: instruction-mask 0x1f ( Mask for the first code word in a words MISC field ) ;\n: hidden? ( PWD -- PWD bool ) dup 1+ @ hidden-mask and logical ;\n: dolit 2 ; ( location of special \"push\" word )\n: compile-instruction 1 ; ( compile code word, threaded code interpreter instruction )\n: run-instruction 2 ; ( run code word, threaded code interpreter instruction )\n: [literal] dolit , , ; ( this word probably needs a better name )\n: literal immediate [literal] ;\n: latest pwd @ ; ( get latest defined word )\n: false 0 ;\n: true 1 ;\n: *+ * + ;\n: 2- 2 - ;\n: 2+ 2 + ;\n: 3+ 3 + ;\n: 2* 1 lshift ;\n: 2\/ 1 rshift ;\n: 4* 2 lshift ;\n: 4\/ 2 rshift ;\n: 8* 3 lshift ;\n: 8\/ 3 rshift ;\n: 256\/ 8 rshift ;\n: mod ( x u -- remainder ) 2dup \/ * - ;\n: *\/ ( n1 n2 n3 -- n4 ) * \/ ; ( warning: this does not use a double cell for the multiply )\n: char key drop key ;\n: [char] immediate char [literal] ;\n: postpone immediate find , ;\n: unless immediate ( bool -- : like 'if' but execute clause if false ) ' 0= , postpone if ;\n: endif immediate ( synonym for 'then' ) postpone then ;\n: bl ( space character ) [char] ; ( warning: white space is significant after [char] )\n: space bl emit ;\n: . pnum space ;\n: address-unit-bits size 8* ;\n: mask-byte ( x -- x ) 8* 0xff swap lshift ;\n: cell+ 1+ ( a-addr1 -- a-addr2 ) ;\n: cells ( n1 -- n2 ) ;\n: char+ ( c-addr1 -- c-addr2 ) 1+ ;\n: chars ( n1 -- n2: convert character address to cell address ) size \/ ;\n: chars> ( n1 -- n2: convert cell address to character address ) size * ;\n: hex ( -- ) ( print out hex ) 16 base ! ;\n: octal ( -- ) ( print out octal ) 8 base ! ;\n: decimal ( -- ) ( print out decimal ) 0 base ! ;\n: negate ( x -- x ) -1 * ;\n: square ( x -- x ) dup * ;\n: +! ( x addr -- ) ( add x to a value stored at addr ) tuck @ + swap ! ;\n: 1+! ( addr -- : increment a value at an address ) 1 swap +! ;\n: 1-! ( addr -- : decrement a value at an address ) -1 swap +! ;\n: lsb ( x -- x : mask off the least significant byte of a cell ) 255 and ;\n: \\ immediate begin key '\\n' = until ;\n: ?dup ( x -- ? ) dup if dup then ;\n: min ( x y -- min ) 2dup < if drop else swap drop then ; \n: max ( x y -- max ) 2dup > if drop else swap drop then ; \n: >= ( x y -- bool ) < not ;\n: <= ( x y -- bool ) > not ;\n: 2@ dup 1+ @ swap @ ;\n: r@ r> r @ swap >r ;\n: 0> 0 > ;\n: 0<> 0 <> ;\n: nand ( x x -- x : Logical NAND ) and not ;\n: nor ( x x -- x : Logical NOR ) or not ;\n: ms ( u -- : wait at least 'u' milliseconds ) clock + begin dup clock < until drop ;\n: sleep 1000 * ms ;\n: align immediate ( x -- x ) ; ( nop in this implementation )\n: ) immediate ;\n: ? ( a-addr -- : view value at address ) @ . cr ;\n: bell 7 ( ASCII BEL ) emit ;\n: b\/buf ( bytes per buffer ) 1024 ;\n: # dup ( x -- x : debug print ) pnum cr ;\n: compile, ' , , ; ( A word that writes , into the dictionary )\n: >mark ( -- ) here 0 , ; \n: ( get caller's return address )\n\tr> ( get value to drop )\n\tdrop ( drop it like it's hot )\n\t>r ( return return address )\n;\n\n: again immediate \n\t( loop unconditionally in a begin-loop:\n\t\tbegin ... again )\n\t' branch , ] literal ( size of input buffer, in characters )\n\t[ 64 chars> ] literal ( start of input buffer, in characters )\n;\n\n: source-id ( -- 0 | 1 | 2 )\n\t( The returned values correspond to whether the interpreter is\n\treading from the user input device or is evaluating a string,\n\tcurrently the \"evaluate\" word is not accessible from within\n\tthe Forth environment and only via the C-API, however the\n\tvalue can still change, the values correspond to:\n\tValue Input Source\n\t-1 String\n\t0 File Input [this may be stdin] )\n\t`source-id @ ;\n\n: 2drop ( x y -- ) drop drop ;\n: hide ( token -- hide-token ) \n\t( This hides a word from being found by the interpreter )\n\tdup \n\tif \n\t\tdup @ hidden-mask or swap tuck ! \n\telse \n\t\tdrop 0 \n\tthen \n;\n\n: hider ( WORD -- ) ( hide with drop ) find dup if hide then drop ;\n: unhide ( hide-token -- ) dup @ hidden-mask invert and swap ! ;\n\n: original-exit [ find exit ] literal ;\n\n: exit \n\t( this will define a second version of exit, ';' will\n\tuse the original version, whilst everything else will\n\tuse this version, allowing us to distinguish between\n\tthe end of a word definition and an early exit by other\n\tmeans in \"see\" )\n\t[ find exit hide ] rdrop exit [ unhide ] ;\n\n: ?exit ( x -- ) ( exit current definition if not zero ) if rdrop exit then ;\n\n( ========================== Basic Word Set ================================== )\n\n( ========================== Extended Word Set =============================== )\n: gcd ( a b -- n ) ( greatest common divisor )\n\tbegin\n\t\tdup\n\t\tif\n\t\t\ttuck mod 0\n\t\telse\n\t\t\t1\n\t\tthen\n\tuntil\n\tdrop\n;\n\n: log2 ( x -- log2 ) \n\t( Computes the binary integer logarithm of a number,\n\tzero however returns itself instead of reporting an error )\n\t0 swap \n\tbegin \n\t\tswap 1+ swap 2\/ dup 0= \n\tuntil \n\tdrop 1- \n;\n\n: xt-token ( previous-word-address -- xt-token )\n\t( Given the address of the PWD field of a word this\n\tfunction will return an execution token for the word )\n\t1+ ( MISC field )\n\tdup \n\t@ ( Contents of MISC field )\n\tinstruction-mask and ( Mask off the instruction )\n\t( If the word is not an immediate word, execution token pointer ) \n\tcompile-instruction = +\n;\n\n: ['] immediate find xt-token [literal] ;\n\n: execute ( xt-token -- )\n\t( given an execution token, execute the word )\n\n\t( create a word that pushes the address of a hole to write to\n\ta literal takes up two words, '!' takes up one )\n\t1- ( execution token expects pointer to PWD field, it does not\n\t\tcare about that field however, and increments past it )\n\txt-token\n\t[ here 3+ literal ] \n\t! ( write an execution token to a hole )\n\t[ 0 , ] ( this is the hole we write )\n;\n\n( ========================== Extended Word Set =============================== )\n\n\n( ========================== CREATE DOES> ==================================== )\n\n( The following section defines a pair of words \"create\" and \"does>\" which \nare a powerful set of words that can be used to make words that can create\nother words. \"create\" has both run time and compile time behavior, whilst\n\"does>\" only works at compile time in conjunction with \"create\". These two\nwords can be used to add constants, variables and arrays to the language,\namongst other things.\n\nA simple version of create is as follows \n\t: create :: 2 , here 2 + , ' exit , 0 state ! ; \nBut this version is much more limited )\n\n: write-quote ['] ' , ; ( A word that writes ' into the dictionary )\n: write-exit ['] exit , ; ( A word that write exit into the dictionary ) \n\n: state! ( bool -- ) ( set the compilation state variable ) state ! ;\n\n: command-mode false state! ;\n\n: command-mode-create ( create a new work that pushes its data field )\n\t:: ( compile a word )\n\tdolit , ( write push into new word )\n\there 2+ , ( push a pointer to data field )\n\t['] exit , ( write in an exit to new word data field is after exit )\n\tcommand-mode ( return to command mode )\n;\n\n: mark compile, ( Write in a place holder 0 and push a pointer to to be used by does> )\n\twrite-quote write-exit compile, ( Write in an exit in the word we're compiling. )\n\t['] command-mode , ( Make sure to change the state back to command mode )\n;\n\n: create immediate ( create word is quite a complex forth word )\n state @ if postpone ( whole-to-patch -- ) \n\timmediate\n\twrite-exit ( we don't want the defining to exit, but the *defined* word to )\n\there swap ! ( patch in the code fields to point to )\n\trun-instruction , ( write a run in )\n;\nhider write-quote \n\n( ========================== CREATE DOES> ==================================== )\n\n: array ( length -- : create a array ) create allot does> + ;\n: table ( length -- : create a table ) create allot does> ;\n: variable ( initial-value -- : create a variable ) create , does> ;\n: constant ( value -- : create a constant ) create , does> @ ;\n\n( do...loop could be improved by not using the return stack so much )\n\n: do immediate\n\t' swap , ( compile 'swap' to swap the limit and start )\n\t' >r , ( compile to push the limit onto the return stack )\n\t' >r , ( compile to push the start on the return stack )\n\there ( save this address so we can branch back to it )\n;\n\n: addi \n\t( @todo simplify )\n\tr@ 1- ( get the pointer to i )\n\t+! ( add value to it )\n\tr@ 1- @ ( find the value again )\n\tr@ 2- @ ( find the limit value )\n\t<\n\tif\n\t\tr@ @ @ r@ @ + r@ ! exit ( branch )\n\tthen\n\tr> 1+\n\trdrop\n\trdrop\n\t>r\n;\n\n: loop immediate 1 [literal] ' addi , r> ( pop off return address and i ) \n\ttuck ( tuck i away ) \n\t>r >r ( restore return stack ) \n;\n\n: range ( nX nY -- nX nX+1 ... nY ) swap 1+ swap do i loop ;\n: repeater ( n0 X -- n0 ... nX ) 1 do dup loop ;\n: sum ( n0 ... nX X -- sum<0..X> ) 1 do + loop ;\n: mul ( n0 ... nX X -- mul<0..X> ) 1 do * loop ;\n\n: factorial ( n -- n! )\n\t( This factorial is only here to test range, mul, do and loop )\n\tdup 1 <= \n\tif\n\t\tdrop\n\t\t1\n\telse ( This is obviously super space inefficient )\n \t\tdup >r 1 range r> mul\n\tthen\n;\n\n: tail \n\t( This function implements tail calls, which is just a jump\n\tto the beginning of the words definition, for example this\n\tword will never overflow the stack and will print \"1\" followed\n\tby a new line forever,\n \n\t\t: forever 1 . cr tail ; \n\n\tWhereas\n\n\t\t: forever 1 . cr recurse ;\n\n\tor\n\n\t\t: forever 1 . cr forever ;\n\n\tWould overflow the return stack. )\n\timmediate\n\tlatest xt-token \n\t' branch ,\n\there - 1+ ,\n;\n\n: recurse immediate\n\t( This function implements recursion, although this interpreter\n\tallows calling a word directly. If used incorrectly this will\n\tblow up the return stack.\n\n\tWe can test \"recurse\" with this factorial function:\n\t : factorial dup 2 < if drop 1 exit then dup 1- recurse * ;)\n\tlatest xt-token , ;\n: myself immediate postpone recurse ;\n\n0 variable column-counter\n4 variable column-width\n: column ( i -- )\tcolumn-width @ mod not if cr then ;\n: reset-column\t\t0 column-counter ! ;\n: auto-column\t\tcolumn-counter dup @ column 1+! ;\n\n: alignment-bits [ 1 size log2 lshift 1- literal ] and ;\n: name ( PWD -- c-addr ) \n\t( given a pointer to the PWD field of a word get a pointer to the name\n\tof the word )\n\tdup 1+ @ 256\/ lsb - chars> ;\n\n: c@ ( character-address -- char )\n\t( retrieve a character from an address )\n\tdup chars @\n\t>r \n\t\talignment-bits \n\t\tdup \n\t\tmask-byte \n\tr> \n\tand swap 8* rshift\n;\n\n: c! ( char character-address -- )\n\t( store a character at an address )\n\tdup \n\t>r ( new addr -- addr )\n\t\talignment-bits 8* lshift ( shift character into correct byte )\n\tr> ( new* addr )\n\tdup chars @ ( new* addr old )\n\tover ( new* addr old addr ) \n\talignment-bits mask-byte invert and ( new* addr old* )\n\trot or swap chars !\n;\n\n0 variable x\n: x! ( x -- ) x ! ;\n: x@ ( -- x ) x @ ;\n\n: 2>r ( x1 x2 -- R: x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tswap\n\t\t>r \n\t\t>r \n\tx@ >r ( restore return address )\n;\n\n: 2r> ( R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tr>\n\t\tr>\n\t\tswap\n\tx@ >r ( restore return address )\n;\n\n: 2r@ ( -- x1 x2 ) ( R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\tr> r>\n\t2dup\n\t>r >r\n\tswap\n\tx@ >r ( restore return address )\n;\n\n: unused ( -- u ) ( push the amount of core left ) max-core here - ;\n\n: roll \n\t( xu xu-1 ... x0 u -- xu-1 ... x0 xu )\n\t( remove u and rotate u+1 items on the top of the stack,\n\tthis could be replaced with a move on the stack and\n\tsome magic so the return stack is used less )\n\tdup 0 > \n\tif \n\t\tswap >r 1- roll r> swap \n\telse \n\t\tdrop \n\tthen ;\n\n: accumulator ( \" ccc\" -- : make a word that increments by a value and pushes the result )\n\tcreate , does> tuck +! @ ;\n\n0 variable delim\n: accepter\n\t( c-addr max delimiter -- i )\n\t( store a \"max\" number of chars at c-addr until \"delimiter\" encountered,\n\tthe number of characters stored is returned )\n\tkey drop ( drop first key after word )\n\tdelim ! ( store delimiter used to stop string storage when encountered)\n\t0\n\tdo\n\t\tkey dup delim @ <>\n\t\tif\n\t\t\tover c! 1+ \n\t\telse ( too many characters read in )\n\t\t\t0 swap c! drop\n\t\t\ti 1+\n\t\t\tleave\n\t\tthen\n\tloop\n\tbegin ( read until delimiter )\n\t\tkey delim @ =\n\tuntil\n;\nhider delim \n\n: '\"' ( -- char : push literal \" character ) [char] \" ;\n: accept ( c-addr +n1 -- +n2 : see accepter definition ) swap '\\n' accepter ;\n\n4096 constant max-string-length \n: accept-string max-string-length '\"' accepter ;\n\n0 variable delim\n: print-string \n\t( delimiter -- )\n\t( print out the next characters in the input stream until a \n\t\"delimiter\" character is reached )\n\tkey drop\n\tdelim !\n\tbegin \n\t\tkey dup delim @ = \n\t\tif \n\t\t\tdrop exit \n\t\tthen \n\t\temit 0 \n\tuntil \n;\nhider delim \n\nsize 1- constant aligner \n: aligned \n\taligner + aligner invert and\n;\nhider aligner \n\n( string handling should really be done with PARSE, and CMOVE )\n\n0 variable delim\n: write-string ( char -- c-addr u )\n\t( @todo This really needs simplifying, to do this\n\ta set of words that operate on a temporary buffer can\n\tbe used )\n\t( Write a string into word being currently defined, this\n\tcode has to jump over the string it has just put into the\n\tdictionary so normal execution of a word can continue. The\n\tlength and character address of the string are left on the\n\tstack )\n\tdelim ! ( save delimiter )\n\t' branch , ( write in jump, this will jump past the string )\n\t>mark ( make hole )\n\tdup 1+ chars> ( calculate address to write to )\n\tmax-string-length delim @ accepter dup >r ( write string into dictionary, save index )\n\taligned 2dup size \/ ( stack: length hole char-len hole )\n\tdup here + h ! ( update dictionary pointer with string length )\n\t1+ swap ! ( write place to jump to )\n\tdrop ( do not need string length anymore )\n\tdolit , ( push next value ) \n\t1+ chars> dup >r ( calculate place to print, save it )\n\t, ( write value to push, the character address to print)\n\t' print , ( write out print, which will print our string )\n\tr> r> swap ( restore index and address of string )\n;\nhider delim\n\n: do-string ( char -- )\n\tstate @ if write-string 2drop else print-string then\n;\n\n: \" immediate '\"' do-string ;\n: .( immediate ')' do-string ;\n: .\" immediate '\"' do-string ;\n\n: ok \" ok\" cr ;\n\n( ==================== CASE statements ======================== )\n\n( for a simpler case statement: \n\tsee Volume 2, issue 3, page 48 of Forth Dimensions at \n\thttp:\/\/www.forth.org\/fd\/contents.html )\n\n: case immediate \n\t' branch , 3 , ( branch over the next branch )\n\there ' branch , ( mark: place endof branches back to with again )\n\t>mark swap ; ( mark: place endcase writes jump to with then )\n\n: over= over = ; \n: of immediate ' over= , postpone if ;\n: endof immediate over postpone again postpone then ;\n: endcase immediate postpone then drop ;\n\n( ==================== CASE statements ======================== )\n\n: error-no-word ( print error indicating last read in word as source )\n\t\" error: word '\" source drop print \" ' not found\" cr ;\n\n: ;hide ( should only be matched with ':hide' ) \n\timmediate \" error: ';hide' without ':hide'\" cr ;\n\n: :hide\n\t( hide a list of words, the list is terminated with \";hide\" )\n\tbegin\n\t\tfind ( find next word )\n\t\tdup [ find ;hide ] literal = if \n\t\t\tdrop exit ( terminate :hide )\n\t\tthen\n\t\tdup 0= if ( word not found )\n\t\t\tdrop \n\t\t\terror-no-word\n\t\t\texit \n\t\tthen\n\t\thide drop\n\tagain\n;\n\n: count ( c-addr1 -- c-addr2 u ) dup c@ swap 1+ swap ;\n\n: fill ( c-addr u char -- )\n\t( fill in an area of memory with a character, only if u is greater than zero )\n\t-rot\n\t0 do 2dup i + c! loop\n\t2drop \n;\n\n: spaces ( n -- : print n spaces ) 0 do space loop ;\n: erase ( addr u : erase a block of memory )\n\tchars> swap chars> swap 0 fill ;\n\n: blank ( c-addr u )\n\t( given a character address and length, this fills that range with spaces )\n\tbl fill ;\n\n: move ( addr1 addr2 u -- )\n\t( copy u words of memory from 'addr2' to 'addr1' )\n\t0 do\n\t\t2dup i + @ swap i + !\n\tloop\n\t2drop\n;\n\n( It would be nice if move and cmove could share more code, as they do exactly\n the same thing but with different load and store functions, cmove> )\n: cmove ( c-addr1 c-addr2 u -- )\n\t( copy u characters of memory from 'c-addr2' to 'c-addr1' )\n\t0 do\n\t\t2dup i + c@ swap i + c!\n\tloop\n\t2drop\n;\n\n( The words \"[if]\", \"[else]\" and \"[then]\" implement conditional compilation,\nthey can be nested as well\n\nSee http:\/\/lars.nocrew.org\/dpans\/dpans15.htm for more information\n\nA much simpler conditional compilation method is the following\nsingle word definition:\n\n : compile-line? 0= if [ find \\\\ , ] then ;\n\nWhich will skip a line if a conditional is false, and compile it\nif true )\n\n( These words really, really need refactoring )\n0 variable nest ( level of [if] nesting )\n0 variable [if]-word ( populated later with \"find [if]\" )\n0 variable [else]-word ( populated later with \"find [else]\")\n: [then] immediate ; \n: reset-nest 1 nest ! ;\n: unnest? [ find [then] ] literal = if nest 1-! then ;\n: nest? [if]-word @ = if nest 1+! then ;\n: end-nest? nest @ 0= ;\n: match-[else]? [else]-word @ = nest @ 1 = and ; \n\n: [if] ( bool -- : conditional execution )\n\tunless\n\t\treset-nest\n\t\tbegin\n\t\t\tfind \n\t\t\tdup nest?\n\t\t\tdup match-[else]? if drop exit then\n\t\t\t unnest?\n\t\t\tend-nest?\n\t\tuntil\n\tthen\n;\n\n: [else] ( discard input until [then] encounter, nesting for [if] )\n\treset-nest\n\tbegin\n\t\tfind\n\t\tdup nest? unnest?\n\t\tend-nest?\n\tuntil\n;\nfind [if] [if]-word !\nfind [else] [else]-word ! \n\n:hide [if]-word [else]-word nest reset-nest unnest? match-[else]? ;hide\n\nsize 2 = [if] 0x0123 variable endianess [then]\nsize 4 = [if] 0x01234567 variable endianess [then]\nsize 8 = [if] 0x01234567abcdef variable endianess [then]\n\n: endian ( -- bool )\n\t( returns the endianess of the processor )\n\t[ endianess chars> c@ 0x01 = ] literal \n;\nhider endianess\n\n: pad \n\t( the pad is used for temporary storage, and moves\n\talong with dictionary pointer, always in front of it )\n\there 64 + ;\n\n0 variable counter\n: counted-column ( index -- )\n\t( special column printing for dump )\n\tcounter @ column-width @ mod \n\tnot if cr . \" :\" space else drop then\n\tcounter 1+! ;\n\n: lister 0 counter ! swap do i counted-column i @ . loop ;\n\n( @todo dump should print out the data as characters as well, if printable )\n: dump ( addr u -- : dump out 'u' cells of memory starting from 'addr' )\n\tbase @ >r hex 1+ over + lister r> base ! cr ;\n:hide counted-column counter lister ;hide\n\n: forgetter ( pwd-token -- : forget a found word and everything after it )\n\tdup @ pwd ! h ! ;\n\n: forget ( WORD -- : forget word and every word defined after it )\n\tfind 1- forgetter ;\n\n: marker ( WORD -- : make word the forgets itself and words after it)\n\t:: latest [literal] ' forgetter , postpone ; ;\nhider forgetter\n\n: ?dup-if immediate ( x -- x | - ) \n\t' ?dup , postpone if ;\n\n: type ( c-addr u -- : print out 'u' characters at c-addr )\n\t0 do dup c@ emit 1+ loop ;\n\n: ** ( b e -- x : exponent, raise 'b' to the power of 'e')\n\tdup\n\tif \n\t\tdup\n\t\t1\n\t\tdo over * loop\n\telse\n\t\tdrop\n\t\t1\n\tendif\n;\n\n0 variable char-alignment\n: c, ( char c-addr -- : write a character into the dictionary )\n\tchar-alignment @ dup 1+ size mod char-alignment !\n\t+\n\tc!\n;\nhider char-alignment\n\n( ==================== Random Numbers ========================= )\n\n( See: \n\tuses xorshift\n\thttps:\/\/en.wikipedia.org\/wiki\/Xorshift\n\thttp:\/\/excamera.com\/sphinx\/article-xorshift.html\n\thttp:\/\/www.arklyffe.com\/main\/2010\/08\/29\/xorshift-pseudorandom-number-generator\/\n)\n( these constants have be collected from the web )\nsize 2 = [if] 13 constant a 9 constant b 7 constant c [then]\nsize 4 = [if] 13 constant a 17 constant b 5 constant c [then]\nsize 8 = [if] 12 constant a 25 constant b 27 constant c [then]\n\n7 variable seed ( must not be zero )\n\n: seed! ( u -- : set the value of the PRNG seed )\n\tdup 0= if drop 7 ( zero not allowed ) then seed ! ;\n\n: random\n\t( assumes word size is 32 bit )\n\tseed @ \n\tdup a lshift xor\n\tdup b rshift xor\n\tdup c lshift xor\n\tdup seed! ;\n:hide a b c seed ;hide\n\n( ==================== Random Numbers ========================= )\n\n( ==================== ANSI Escape Codes ====================== )\n(\n\tsee: https:\/\/en.wikipedia.org\/wiki\/ANSI_escape_code \n\tThese codes will provide a relatively portable means of \n\tmanipulating a terminal\n)\n\n27 constant 'escape'\nchar ; constant ';'\n: CSI 'escape' emit .\" [\" ;\n0 constant black \n1 constant red \n2 constant green \n3 constant yellow \n4 constant blue \n5 constant magenta \n6 constant cyan \n7 constant white \n: foreground 30 + ;\n: background 40 + ;\n0 constant dark\n1 constant bright\n\n: color ( brightness color-code -- )\n\t( set color on an ANSI compliant terminal,\n\tfor example:\n\t\tbright red foreground color\n\tsets the foreground text to bright red )\n\tCSI pnum if .\" ;1\" then .\" m\" ;\n\n: at-xy ( x y -- ) ( set ANSI terminal cursor position to x y ) CSI pnum ';' emit pnum .\" H\" ;\n: page ( clear ANSI terminal screen and move cursor to beginning ) CSI .\" 2J\" 1 1 at-xy ;\n: hide-cursor ( hide the cursor from view ) CSI .\" ?25l\" ;\n: show-cursor ( show the cursor ) CSI .\" ?25h\" ;\n: save-cursor ( save cursor position ) CSI .\" s\" ;\n: restore-cursor ( restore saved cursor position ) CSI .\" u\" ;\n: reset-color CSI .\" 0m\" ;\nhider CSI\n( ==================== ANSI Escape Codes ====================== )\n\n\n( ==================== Prime Numbers ========================== )\n( from original \"third\" code from the ioccc http:\/\/www.ioccc.org\/1992\/buzzard.2.design )\n: prime? ( x -- x\/0 : return number if it is prime, zero otherwise )\n\tdup 1 = if 1- exit then\n\tdup 2 = if exit then\n\tdup 2 \/ 2 ( loop from 2 to n\/2 )\n\tdo\n\t\tdup ( value to check if prime )\n\t\ti mod ( mod by divisor )\n\t\tnot if\n\t\t\tdrop 0 leave\n\t\tthen\n\tloop\n;\n\n0 variable counter\n: primes\n\t0 counter !\n\t\" The primes from \" dup . \" to \" over . \" are: \"\n\tcr\n\treset-column\n\tdo\n\t\ti prime?\n\t\tif\n\t\t\ti . counter @ column counter 1+!\n\t\tthen\n\tloop\n\tcr\n\t\" There are \" counter @ . \" primes.\"\n\tcr ;\nhider counter\n( ==================== Prime Numbers ========================== )\n\n( ==================== Debugging info ========================= )\n\n: .s ( -- : print out the stack for debugging )\n\tdepth if\n\t\tdepth 0 do i column tab i pick . loop\n\tthen\n\tcr ;\n\n1 variable hide-words ( do we want to hide hidden words or not )\n: words ( -- )\n\t( This function prints out all of the defined words, excluding hidden words.\n\tAn understanding of the layout of a Forth word helps here. The dictionary\n\tcontains a linked list of words, each forth word has a pointer to the previous\n\tword until the first word. The layout of a Forth word looks like this:\n\n\tNAME: Forth Word - A variable length ASCII NUL terminated string\n\tPWD: Previous Word Pointer, points to the previous word\n\tMISC: Flags, code word and offset from previous word pointer to start of Forth word string\n\tCODE\/DATA: The body of the forth word definition, not interested in this.\n\t\n\tThere is a register which stores the latest defined word which can be\n\taccessed with the code \"pwd @\". In order to print out a word we need to\n\taccess a words MISC field, the offset to the NAME is stored here in bits\n\t8 to 15 and the offset is calculated from the PWD field.\n\n\t\"print\" expects a character address, so we need to multiply any calculated\n\taddress by the word size in bytes. )\n\treset-column\n\tlatest \n\tbegin \n\t\tdup \n\t\thidden? hide-words @ and\n\t\tnot if \n\t\t\tname\n\t\t\tprint tab \n\t\t\tauto-column\n\t\telse \n\t\t\tdrop \n\t\tthen \n\t\t@ ( Get pointer to previous word )\n\t\tdup dictionary-start < ( stop if pwd no longer points to a word )\n\tuntil \n\tdrop cr \n; \nhider hide-words\n\n: registers ( -- )\n\t( print out important registers and information about the\n\tvirtual machine )\n\t\" return stack pointer: \" r@ . cr\n\t\" dictionary pointer \" here . cr\n\t\" previous word: \" pwd @ . cr\n\t\" state: \" state @ . cr\n\t\" base: \" base @ . cr\n\t\" depth: \" depth . cr\n\t\" cell size (in bytes): \" size . cr\n\t\" last cell address: \" max-core . cr\n\t\" unused cells: \" unused . cr\n\t( We could determine if we are reading from stdin by looking\n\tat the stdin register )\n\t\" current input source: \" source-id -1 = if \" string\" else \" file\" then cr\n\t( depth if \" Stack: \" .s then )\n\t( \" Raw Register Values: \" cr 0 31 dump )\n;\n\n: y\/n? ( -- bool : ask a yes or no question )\n\tkey drop\n\t\" y\/n? \"\n\tbegin\n\t\tkey\n\t\tdup \n\t\t[char] y = if true exit then\n\t\t[char] n = if false exit then\n\t\t\" y\/n? \"\n\tagain ;\n\n: TrueFalse if \" true\" else \" false\" then ;\n: >instruction ( extract instruction from instruction field ) 0x1f and ;\n\n: step\n\t( step through a word: this word could be augmented\n\twith commands such as \"dump\", \"halt\", and optional\n\t\".s\" and \"registers\" )\n\tregisters\n\t\" .s: \" .s cr\n\t\" -- press any key to continue -- \"\n\tkey drop ;\n\n: more ( wait for more input )\n\t\" -- press any key to continue -- \" key drop cr ;\n\n: debug-help \" debug mode commands \n\th - print help\n\tq - exit containing word\n\tr - print registers\n\ts - print stack\n\tc - continue on with execution \n\" ;\n: debug-prompt .\" debug> \" ;\n: debug ( a work in progress, debugging support )\n\tcr\n\tbegin\n\t\tdebug-prompt\n\t\tkey dup '\\n' <> if source accept drop then\n\t\tcase\n\t\t\t[char] h of debug-help endof\n\t\t\t[char] q of drop rdrop exit ( call abort when this exists ) endof\n\t\t\t[char] r of registers endof\n\t\t\t\\ [char] d of dump endof \\ implement read in number\n\t\t\t[char] s of >r .s r> endof \n\t\t\t[char] c of drop exit endof\n\t\tendcase \n\tagain ;\nhider debug-prompt\n\n0 variable cf\n: code>pwd ( CODE -- PWD\/0 )\n\t( given a pointer to a executable code field\n\tthis words attempts to find the PWD field for\n\tthat word, or return zero )\n\tdup here >= if drop 0 exit then ( cannot be a word, too small )\n\tdup dictionary-start <= if drop 0 exit then ( cannot be a word, too large )\n\tcf !\n\tlatest dup @ ( p1 p2 )\n\tbegin\n\t\tover ( p1 p2 p1 )\n\t\tcf @ <= swap cf @ > and if exit then\n\t\tdup 0= if exit then \n\t\tdup @ swap \n\tagain\n;\nhider cf\n\n: end-print ( x -- ) \" => \" . \" )\" cr ;\n: word-printer\n\t( attempt to print out a word given a words code field\n\tWARNING: This is a dirty hack at the moment\n\tNOTE: given a pointer to somewhere in a word it is possible\n\tto work out the PWD by looping through the dictionary to\n\tfind the PWD below it )\n\t1- dup @ -1 = if \" ( noname )\" end-print exit then\n\t dup \" ( \" code>pwd dup if name print else drop \" data\" then \n\t end-print ;\nhider end-print\n\n: decompile ( code-field-ptr -- )\n\t( @todo Rewrite, simplify and get this working correctly\n \n\tThis word expects a pointer to the code field of a word, it\n\tdecompiles a words code field, it needs a lot of work however.\n\tThere are several complications to implementing this decompile\n\tfunction, \":noname\", \"branch\", multiple \"exit\" commands, and literals.\n\n\tThis word really needs CASE statements before it can be\n\tcompleted, as it stands the function is not complete\n\n\t:noname This has a marker before its code field of -1 which\n\t cannot occur normally\n\tbranch branches are used to skip over data, but also for\n\t some branch constructs, any data in between can only\n\t be printed out generally speaking \n\texit There are two definitions of exit, the one used in\n\t\t ';' and the one everything else uses, this is used\n\t\t to determine the actual end of the word\n\tliterals Literals can be distinguished by their low value,\n\t which cannot possibly be a word with a name, the\n\t next field is the actual literal \n\n\tOf special difficult is processing 'if' 'else' 'then' statements,\n\tthis will require keeping track of '?branch'.\n\n\tAlso of note, a number greater than \"here\" must be data )\n\t255 0\n\tdo\n\t\ttab \n\t\tdup @ dolit = if \" ( literal => \" 1+ dup @ . 1+ \" )\" cr tab then\n\t\tdup @ [ find branch xt-token ] literal = if \" ( branch => \" 1+ dup @ . \" )\" cr dup dup @ dump dup @ + cr tab then\n\t\tdup @ [ original-exit xt-token ] literal = if \" ( exit )\" i cr leave then\n\t\tdup @ word-printer\n\t\t1+\n\tloop\n\tcr\n\t255 = if \" decompile limit exceeded\" cr then\n\tdrop ;\n\nhider word-printer\n\n: xt-instruction ( extract instruction from execution token ) \n\txt-token @ >instruction ;\n( these words expect a pointer to the PWD field of a word )\n: defined-word? xt-instruction run-instruction = ;\n: print-name \" name: \" name print cr ;\n: print-start \" word start: \" name chars . cr ;\n: print-previous \" previous word: \" @ . cr ;\n: print-immediate \" immediate: \" 1+ @ >instruction compile-instruction <> TrueFalse cr ;\n: print-instruction \" instruction: \" xt-instruction . cr ;\n: print-defined \" defined: \" defined-word? TrueFalse cr ;\n\n: print-header ( PWD -- is-immediate-word? )\n\tdup print-name\n\tdup print-start\n\tdup print-previous\n\tdup print-immediate\n\tdup print-instruction ( TODO look up instruction name )\n\tprint-defined ;\n\n: see \n\t( decompile a word )\n\tfind \n\tdup 0= if drop error-no-word exit then\n\t1- ( move to PWD field )\n\tdup print-header\n\tdup defined-word?\n\tif ( decompile if a compiled word )\n\t\txt-token 1+ ( move to code field )\n\t\t\" code field:\" cr\n\t\tdecompile\n\telse ( the instruction describes the word if it is not a compiled word )\n\t\tdrop\n\tthen ;\n\n: empty-stack ( x-n ... x-0 -- : empty the variable stack )\n\tbegin depth while drop repeat ;\n\nr @ constant restart-address\n: quit\n\t0 `source-id ! ( @todo store stdin in input file )\n\t]\n\trestart-address r ! ;\n\n: abort empty-stack quit ;\n\n( These help messages could be moved to blocks, the blocks could then\n be loaded from disk and printed instead of defining the help here,\n this would allow much larger help )\n: help ( print out a short help message )\n\tpage\n\tkey drop\n\" Welcome to Forth, an imperative stack based language. It is both a low\nlevel and a high level language, with a very small memory footprint. Most\nof Forth is defined as a combination of various primitives.\n\nA short description of the available function (or Forth words) follows,\nwords marked (1) are immediate and cannot be used in command mode, words\nmarked with (2) define new words. Words marked with (3) have both command\nand compile functionality.\n\n\" \nmore \" The built in words that accessible are:\n\n(1,2)\t: define a new word, switching to compile mode\n\timmediate make latest defined word immediate\n\tread read in a word, execute in command mode else compile \n\t@ ! fetch, store\n\t- + * \/ standard arithmetic operations,\n\tand or xor invert standard bit operations\n\tlshift rshift left and right bit shift\n\t< > = comparison predicates\n\texit exit from a word\n\temit print character from top of stack\n\tkey get a character from input\n\tr> >r pop a value from or to the return stack\n\tfind find a word in the dictionary and push the location\n\t' store the address of the following word on the stack\n\t, write the top of the stack to the dictionary\n\tsave load save or load a block at address to indexed file\n\tswap swap first two values on the stack\n\tdup duplicate the top of the stack\n\tdrop pop and drop a value\n\tover copy the second stack value over the first\n\t. pop the top of the stack and print it\n\tprint print a NUL terminated string at a character address\n\tdepth get the current stack depth\n\tclock get the time since execution start in milliseconds\n\n \"\n\nmore \" All of the other words in the interpreter are built from these\nprimitive words. A few examples:\n\n(1)\tif...else...then FORTH branching construct \n(1)\tbegin...until loop until top of stack is non zero\n(1)\tbegin...again infinite loop\n(1)\tdo...loop FORTH looping construct\n(2,3)\tcreate create a new word that pushes its location\n(1)\tdoes> declare a created words run time behaviour\n(1,2)\tvariable declare variable with initial value from top of stack\n(1,2)\tconstant declare a constant, taken from top of stack\n(1,2)\tarray declare an array with size taken from top of stack\n(1)\t; terminate a word definition and return to command mode\n\twords print out a list of all the defined words\n\thelp this help message\n\tdump print out memory contents starting at an address\n\tregisters print out the contents of the registers\n\tsee decompile a word, viewing what words compose it\n\t.s print out the contents of the stack\n\n\"\n\nmore \" Some more advanced words:\n\n\there push the dictionary pointer\n\th push the address of the dictionary pointer\n\tr push the return stack pointer\n\tallot allocate space in the dictionary\n(1)\t[ switch to command mode\n\t] switch to compile mode\n\t:: compile ':' into the dictionary\n\n\"\n\nmore \"\nFor more information either consult the manual pages forth(1) and libforth(1)\nor consult the following sources:\n\n\thttps:\/\/github.com\/howerj\/libforth \n\thttp:\/\/work.anapnea.net\/html\/html\/projects.html\n\nAnd for a larger tutorial:\n\n\thttps:\/\/github.com\/howerj\/libforth\/blob\/master\/readme.md\n\nFor resources on Forth:\n\n\thttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\thttps:\/\/rwmj.wordpress.com\/2010\/08\/07\/jonesforth-git-repository\/\n\n -- end --\n\" cr\n;\n\n( clean up the environment )\n:hide\n write-string do-string accept-string ')' alignment-bits print-string '\"'\n compile-instruction dictionary-start hidden? hidden-mask instruction-mask \n max-core run-instruction x x! x@ write-exit \n accepter max-string-length xt-token error-no-word\n original-exit\n restart-address pnum\n decompile TrueFalse >instruction print-header \n print-name print-start print-previous print-immediate \n print-instruction xt-instruction defined-word? print-defined\n `state \n `source-id `sin `sidx `slen `start-address `fin `fout `stdin\n `stdout `stderr `argc `argv `debug `invalid `top `instruction\n `stack-size `start-time\n;hide\n\n( ==================== Blocks ================================= )\n\n( @todo process invalid blocks [anything greater or equal to 0xFFFF] )\n( @todo only already created blocks can be loaded, this should be\n corrected so one is created if needed )\n( @todo better error handling )\n\n-1 variable scr-var \nfalse variable dirty ( has the buffer been modified? )\n: scr ( -- x : last screen used ) scr-var @ ;\nb\/buf chars table block-buffer ( block buffer - enough to store one block )\n\n: update true dirty ! ;\n: empty-buffers false dirty ! block-buffer b\/buf chars erase ;\n: flush dirty @ if block-buffer chars> scr bsave drop false dirty ! then ;\n\n: list\n\tflush\n\tdup dup scr <> if\n\t\tblock-buffer chars> swap bload ( load buffer into block buffer )\n\t\tswap scr-var !\n\telse\n\t\t2drop 0\n\tthen\n\t-1 = if exit then ( failed to load )\n\tblock-buffer chars> b\/buf type ; ( print buffer )\n\n: block ( u -- addr : load block 'u' and push address to block )\n\tdup scr <> if flush block-buffer chars> swap bload then\n\t-1 = if -1 else block-buffer then ;\n\n: save-buffers flush ;\n\n: list-thru\n\t1+ swap \n\tkey drop\n\tdo \" screen no: \" i . cr i list cr more loop ;\n\nhider scr-var\nhider block-buffer\n\n( ==================== Blocks ================================= )\n\n( \n: actual-base base @ dup 0= if drop 10 then ;\n: pnum\n\tdup\n\tactual-base mod [char] 0 +\n\tswap actual-base \/ dup\n\tif pnum 0 then\n\tdrop emit\n;\n\n: .\n\tdup 0 < \n\tif\n\t\t[char] - emit negate\n\tthen\n\tpnum\n\tspace\n; )\n\n( TODO\n\t* Evaluate \n\t* By adding \"c@\" and \"c!\" to the interpreter I could remove print\n\tand put string functionality earlier in the file\n\t* Add unit testing to the end of this file\n\t* Word, Parse, other forth words\n\t* Add a dump core and load core to the interpreter?\n\t* add \"j\" if possible to get outer loop context\n\t* FORTH, VOCABULARY \n\t* \"Value\", \"To\", \"Is\"\n\t* A small block editor\n\t* more help commands would be good, such as \"help-ANSI-escape\",\n\t\"tutorial\", etc.\n\t* Abort and Abort\", this could be used to implement words such\n\tas \"abort if in compile mode\", or \"abort if in command mode\".\n\t* Todo Various different assemblers [assemble VM instructions,\n\tnative instructions, and cross assemblers]\n\t* common words and actions should be factored out to simplify\n\tdefinitions of other words, their standards compliant version found\n\tif any\n\t* An assembler mode would execute primitives only, this would\n\trequire a change to the interpreter\n\t* throw and exception\n\t* here documents, string literals\n\t* A set of words for navigating around word definitions would be\n\thelp debugging words, for example:\n\t\tcompile-field code-field field-translate\n\twould take a pointer to a compile field for a word and translate\n\tthat into the code field\n\t* [ifdef] [ifundef]\n\t* if strings were stored in word order instead of byte order\n\tthen external tools could translate the dictionary by swapping\n\tthe byte order of it\n\t* store strings as length + string instead of ASCII strings\n\t* proper booleans should be used throughout\n\t* escaped strings\n\t* ideally all of the functionality of main_forth would be\n\tmoved into this file\n\t* fill move and the like are technically not compliant as\n\tthey do not test if the number is negative, however that would\n\tunnecessarily limit the range of operation\n\nSome interesting links:\n\t* http:\/\/www.figuk.plus.com\/build\/heart.htm\n\t* https:\/\/groups.google.com\/forum\/#!msg\/comp.lang.forth\/NS2icrCj1jQ\/1btBCkOWr9wJ\n\t* http:\/\/newsgroups.derkeiler.com\/Archive\/Comp\/comp.lang.forth\/2005-09\/msg00337.html\n\t* https:\/\/stackoverflow.com\/questions\/407987\/what-are-the-primitive-forth-operators\n)\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"a064a2b841b5daead3323cf9f62b0dc61fc4a990","subject":"use -1 for TRUE","message":"use -1 for TRUE","repos":"cetic\/python-msp430-tools,cetic\/python-msp430-tools,cetic\/python-msp430-tools","old_file":"msp430\/asm\/forth\/_builtins.forth","new_file":"msp430\/asm\/forth\/_builtins.forth","new_contents":"( Implementations of builtins.\n These functions are provided for the host in the msp430.asm.forth module. The\n implementations here are for the target.\n\n vi:ft=forth\n)\n\n( ----- low level supporting functions ----- )\n\nCODE LIT\n .\" \\t decd TOS ; prepare push on stack \\n \"\n .\" \\t mov @IP+, 0(TOS) ; copy value from thread to stack \\n \"\n NEXT\nEND-CODE\n\nCODE BRANCH\n .\" \\t add @IP+, IP \\n \"\n .\" \\t decd IP \\n \"\n NEXT\nEND-CODE-INTERNAL\n\nCODE BRANCH0\n .\" \\t mov @IP+, W ; get offset \\n \"\n .\" \\t tst 0(TOS) ; check TOS \\n \"\n .\" \\t jnz .Lnjmp ; skip next if non zero \\n \"\n .\" \\t decd IP ; offset is relative to position of offset, correct \\n \"\n .\" \\t add W, IP ; adjust IP \\n \"\n.\" .Lnjmp: \"\n DROP-ASM\n NEXT\nEND-CODE-INTERNAL\n\n( ----- Stack ops ----- )\n\nCODE DROP\n .\" \\t incd TOS \" NL\n NEXT\nEND-CODE-INTERNAL\n\nCODE DUP\n .\" \\t decd TOS \" NL\n .\" \\t mov 2(TOS), 0(TOS) \" NL\n NEXT\nEND-CODE-INTERNAL\n\nCODE OVER\n .\" \\t decd TOS \" NL\n .\" \\t mov 4(TOS), 0(TOS) \" NL\n NEXT\nEND-CODE-INTERNAL\n\n( Push a copy of the N'th element )\nCODE PICK ( n - n )\n TOS->R15 ( get element number from stack )\n .\" \\t rla R15 \" NL ( multiply by 2 -> 2 byte \/ cells )\n .\" \\t add TOS, R15 \" NL ( calculate address on stack )\n .\" \\t decd TOS \" NL ( push copy )\n .\" \\t mov 0(R15), 0(TOS) \" NL\n NEXT\nEND-CODE-INTERNAL\n\nCODE SWAP ( y x - x y )\n .\" \\t mov 2(TOS), W \" NL\n .\" \\t mov 0(TOS), 2(TOS) \" NL\n .\" \\t mov W, 0(TOS) \" NL\n NEXT\nEND-CODE-INTERNAL\n\n( ----- MATH ----- )\n\nCODE +\n .\" \\t add 0(TOS), 2(TOS) \" NL\n DROP-ASM\n NEXT\nEND-CODE-INTERNAL\n\nCODE -\n .\" \\t sub 0(TOS), 2(TOS) \" NL\n DROP-ASM\n NEXT\nEND-CODE-INTERNAL\n\n( ----- bit - ops ----- )\nCODE &\n .\" \\t and 0(TOS), 2(TOS) \" NL\n DROP-ASM\n NEXT\nEND-CODE-INTERNAL\n\nCODE |\n .\" \\t bis 0(TOS), 2(TOS) \" NL\n DROP-ASM\n NEXT\nEND-CODE-INTERNAL\n\nCODE ^\n .\" \\t xor 0(TOS), 2(TOS) \" NL\n DROP-ASM\n NEXT\nEND-CODE-INTERNAL\n\nCODE ~\n .\" \\t inv 0(TOS), 2(TOS) \" NL\n DROP-ASM\n NEXT\nEND-CODE-INTERNAL\n\n( ----- Logic ops ----- )\n( include normalize to boolean )\n\nCODE NOT\n .\" \\t tst 0(TOS) \" NL\n .\" \\t jnz .not0 \" NL\n .\" \\t mov \\x23 -1, 0(TOS) \" NL ( replace TOS w\/ result )\n .\" \\t jmp .not2 \" NL\n .\" .not0: \" NL\n .\" \\t mov \\x23 0, 0(TOS) \" NL ( replace TOS w\/ result )\n .\" .not2: \" NL\n NEXT\nEND-CODE-INTERNAL\n\n( ---------------------------------------------------\n \"MIN\" \"\"\"Leave the smaller of two values on the stack\"\"\"\n \"MAX\" \"\"\"Leave the larger of two values on the stack\"\"\"\n \"*\"\n \"\/\"\n \"NEG\"\n \"<<\"\n \">>\"\n \"NOT\"\n \"AND\"\n \"OR\"\n)\n( ----- Compare ----- )\nCODE cmp_set_true ( n - n )\n .\" \\t mov \\x23 -1, 0(TOS) \" NL ( replace argument w\/ result )\n NEXT\nEND-CODE\n\nCODE cmp_set_false\n .\" \\t mov \\x23 0, 0(TOS) \" NL ( replace argument w\/ result )\n NEXT\nEND-CODE\n\n\nCODE cmp_true\n DROP-ASM ( remove 1nd argument )\n .\" \\t mov \\x23 -1, 0(TOS) \" NL ( replace 2nd argument w\/ result )\n NEXT\nEND-CODE\n\nCODE cmp_false\n DROP-ASM ( remove 1nd argument )\n .\" \\t mov \\x23 0, 0(TOS) \" NL ( replace 2nd argument w\/ result )\n NEXT\nEND-CODE\n\n\nCODE <\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(TOS), 2(TOS) \" NL\n .\" \\t jl cmp_true \" NL\n .\" \\t jmp cmp_false \" NL\nEND-CODE-INTERNAL\n\nCODE >\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(TOS), 2(TOS) \" NL\n .\" \\t jl cmp_false \" NL\n .\" \\t jmp cmp_true \" NL\nEND-CODE-INTERNAL\n\nCODE <=\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(TOS), 2(TOS) \" NL\n .\" \\t jge cmp_false \" NL\n .\" \\t jmp cmp_true \" NL\nEND-CODE-INTERNAL\n\nCODE >=\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(TOS), 2(TOS) \" NL\n .\" \\t jge cmp_true \" NL\n .\" \\t jmp cmp_false \" NL\nEND-CODE-INTERNAL\n\nCODE ==\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(TOS), 2(TOS) \" NL\n .\" \\t jeq cmp_true \" NL\n .\" \\t jmp cmp_false \" NL\nEND-CODE-INTERNAL\n\n( XXX alias for == )\nCODE ==\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(TOS), 2(TOS) \" NL\n .\" \\t jeq cmp_true \" NL\n .\" \\t jmp cmp_false \" NL\nEND-CODE-INTERNAL\n\nCODE !=\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(TOS), 2(TOS) \" NL\n .\" \\t jne cmp_true \" NL\n .\" \\t jmp cmp_false \" NL\nEND-CODE-INTERNAL\n\n\nCODE 0=\n DEPENDS-ON cmp_set_true\n DEPENDS-ON cmp_set_false\n .\" \\t tst 0(TOS) \" NL\n .\" \\t jz cmp_set_true \" NL\n .\" \\t jmp cmp_set_false \" NL\nEND-CODE-INTERNAL\n\nCODE 0>\n DEPENDS-ON cmp_set_true\n DEPENDS-ON cmp_set_false\n .\" \\t tst 0(TOS) \" NL\n .\" \\t jn cmp_set_false \" NL\n .\" \\t jmp cmp_set_true \" NL\nEND-CODE-INTERNAL\n","old_contents":"( Implementations of builtins.\n These functions are provided for the host in the msp430.asm.forth module. The\n implementations here are for the target.\n\n vi:ft=forth\n)\n\n( ----- low level supporting functions ----- )\n\nCODE LIT\n .\" \\t decd TOS ; prepare push on stack \\n \"\n .\" \\t mov @IP+, 0(TOS) ; copy value from thread to stack \\n \"\n NEXT\nEND-CODE\n\nCODE BRANCH\n .\" \\t add @IP+, IP \\n \"\n .\" \\t decd IP \\n \"\n NEXT\nEND-CODE-INTERNAL\n\nCODE BRANCH0\n .\" \\t mov @IP+, W ; get offset \\n \"\n .\" \\t tst 0(TOS) ; check TOS \\n \"\n .\" \\t jnz .Lnjmp ; skip next if non zero \\n \"\n .\" \\t decd IP ; offset is relative to position of offset, correct \\n \"\n .\" \\t add W, IP ; adjust IP \\n \"\n.\" .Lnjmp: \"\n DROP-ASM\n NEXT\nEND-CODE-INTERNAL\n\n( ----- Stack ops ----- )\n\nCODE DROP\n .\" \\t incd TOS \" NL\n NEXT\nEND-CODE-INTERNAL\n\nCODE DUP\n .\" \\t decd TOS \" NL\n .\" \\t mov 2(TOS), 0(TOS) \" NL\n NEXT\nEND-CODE-INTERNAL\n\nCODE OVER\n .\" \\t decd TOS \" NL\n .\" \\t mov 4(TOS), 0(TOS) \" NL\n NEXT\nEND-CODE-INTERNAL\n\n( Push a copy of the N'th element )\nCODE PICK ( n - n )\n TOS->R15 ( get element number from stack )\n .\" \\t rla R15 \" NL ( multiply by 2 -> 2 byte \/ cells )\n .\" \\t add TOS, R15 \" NL ( calculate address on stack )\n .\" \\t decd TOS \" NL ( push copy )\n .\" \\t mov 0(R15), 0(TOS) \" NL\n NEXT\nEND-CODE-INTERNAL\n\nCODE SWAP ( y x - x y )\n .\" \\t mov 2(TOS), W \" NL\n .\" \\t mov 0(TOS), 2(TOS) \" NL\n .\" \\t mov W, 0(TOS) \" NL\n NEXT\nEND-CODE-INTERNAL\n\n( ----- MATH ----- )\n\nCODE +\n .\" \\t add 0(TOS), 2(TOS) \" NL\n DROP-ASM\n NEXT\nEND-CODE-INTERNAL\n\nCODE -\n .\" \\t sub 0(TOS), 2(TOS) \" NL\n DROP-ASM\n NEXT\nEND-CODE-INTERNAL\n\n( ----- bit - ops ----- )\nCODE &\n .\" \\t and 0(TOS), 2(TOS) \" NL\n DROP-ASM\n NEXT\nEND-CODE-INTERNAL\n\nCODE |\n .\" \\t bis 0(TOS), 2(TOS) \" NL\n DROP-ASM\n NEXT\nEND-CODE-INTERNAL\n\nCODE ^\n .\" \\t xor 0(TOS), 2(TOS) \" NL\n DROP-ASM\n NEXT\nEND-CODE-INTERNAL\n\nCODE ~\n .\" \\t inv 0(TOS), 2(TOS) \" NL\n DROP-ASM\n NEXT\nEND-CODE-INTERNAL\n\n( ----- Logic ops ----- )\n( include normalize to boolean )\n\nCODE NOT\n .\" \\t tst 0(TOS) \" NL\n .\" \\t jnz .not0 \" NL\n .\" \\t mov \\x23 1, 0(TOS) \" NL ( replace TOS w\/ result )\n .\" \\t jmp .not2 \" NL\n .\" .not0: \" NL\n .\" \\t mov \\x23 0, 0(TOS) \" NL ( replace TOS w\/ result )\n .\" .not2: \" NL\n NEXT\nEND-CODE-INTERNAL\n\n( ---------------------------------------------------\n \"MIN\" \"\"\"Leave the smaller of two values on the stack\"\"\"\n \"MAX\" \"\"\"Leave the larger of two values on the stack\"\"\"\n \"*\"\n \"\/\"\n \"NEG\"\n \"<<\"\n \">>\"\n \"NOT\"\n \"AND\"\n \"OR\"\n)\n( ----- Compare ----- )\nCODE cmp_set_true ( n - n )\n .\" \\t mov \\x23 1, 0(TOS) \" NL ( replace argument w\/ result )\n NEXT\nEND-CODE\n\nCODE cmp_set_false\n .\" \\t mov \\x23 0, 0(TOS) \" NL ( replace argument w\/ result )\n NEXT\nEND-CODE\n\n\nCODE cmp_true\n DROP-ASM ( remove 1nd argument )\n .\" \\t mov \\x23 1, 0(TOS) \" NL ( replace 2nd argument w\/ result )\n NEXT\nEND-CODE\n\nCODE cmp_false\n DROP-ASM ( remove 1nd argument )\n .\" \\t mov \\x23 0, 0(TOS) \" NL ( replace 2nd argument w\/ result )\n NEXT\nEND-CODE\n\n\nCODE <\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(TOS), 2(TOS) \" NL\n .\" \\t jl cmp_true \" NL\n .\" \\t jmp cmp_false \" NL\nEND-CODE-INTERNAL\n\nCODE >\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(TOS), 2(TOS) \" NL\n .\" \\t jl cmp_false \" NL\n .\" \\t jmp cmp_true \" NL\nEND-CODE-INTERNAL\n\nCODE <=\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(TOS), 2(TOS) \" NL\n .\" \\t jge cmp_false \" NL\n .\" \\t jmp cmp_true \" NL\nEND-CODE-INTERNAL\n\nCODE >=\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(TOS), 2(TOS) \" NL\n .\" \\t jge cmp_true \" NL\n .\" \\t jmp cmp_false \" NL\nEND-CODE-INTERNAL\n\nCODE ==\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(TOS), 2(TOS) \" NL\n .\" \\t jeq cmp_true \" NL\n .\" \\t jmp cmp_false \" NL\nEND-CODE-INTERNAL\n\n( XXX alias for == )\nCODE ==\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(TOS), 2(TOS) \" NL\n .\" \\t jeq cmp_true \" NL\n .\" \\t jmp cmp_false \" NL\nEND-CODE-INTERNAL\n\nCODE !=\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(TOS), 2(TOS) \" NL\n .\" \\t jne cmp_true \" NL\n .\" \\t jmp cmp_false \" NL\nEND-CODE-INTERNAL\n\n\nCODE 0=\n DEPENDS-ON cmp_set_true\n DEPENDS-ON cmp_set_false\n .\" \\t tst 0(TOS) \" NL\n .\" \\t jz cmp_set_true \" NL\n .\" \\t jmp cmp_set_false \" NL\nEND-CODE-INTERNAL\n\nCODE 0>\n DEPENDS-ON cmp_set_true\n DEPENDS-ON cmp_set_false\n .\" \\t tst 0(TOS) \" NL\n .\" \\t jn cmp_set_false \" NL\n .\" \\t jmp cmp_set_true \" NL\nEND-CODE-INTERNAL\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"3120ff152e9a68e4d1400233852981321eb20ef0","subject":"PC98 uses the different frame code.","message":"PC98 uses the different frame code.\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/frames.4th","new_file":"sys\/boot\/forth\/frames.4th","new_contents":"\\ Words implementing frame drawing\n\\ XXX Filled boxes are left as an exercise for the reader... ;-\/\n\\ $FreeBSD$\n\nmarker task-frames.4th\n\nvariable h_el\nvariable v_el\nvariable lt_el\nvariable lb_el\nvariable rt_el\nvariable rb_el\nvariable fill\n\ns\" arch-pc98\" environment? [if]\n\t\\ Single frames\n\t149 constant sh_el\n\t150 constant sv_el\n\t152 constant slt_el\n\t154 constant slb_el\n\t153 constant srt_el\n\t155 constant srb_el\n\t\\ Double frames\n\t149 constant dh_el\n\t150 constant dv_el\n\t152 constant dlt_el\n\t154 constant dlb_el\n\t153 constant drt_el\n\t155 constant drb_el\n\t\\ Fillings\n\t0 constant fill_none\n\t32 constant fill_blank\n\t135 constant fill_dark\n\t135 constant fill_med\n\t135 constant fill_bright\n[else]\n\t\\ Single frames\n\t196 constant sh_el\n\t179 constant sv_el\n\t218 constant slt_el\n\t192 constant slb_el\n\t191 constant srt_el\n\t217 constant srb_el\n\t\\ Double frames\n\t205 constant dh_el\n\t186 constant dv_el\n\t201 constant dlt_el\n\t200 constant dlb_el\n\t187 constant drt_el\n\t188 constant drb_el\n\t\\ Fillings\n\t0 constant fill_none\n\t32 constant fill_blank\n\t176 constant fill_dark\n\t177 constant fill_med\n\t178 constant fill_bright\n[then]\n\n: hline\t( len x y -- )\t\\ Draw horizontal single line\n\tat-xy\t\t\\ move cursor\n\t0 do\n\t\th_el @ emit\n\tloop\n;\n\n: f_single\t( -- )\t\\ set frames to single\n\tsh_el h_el !\n\tsv_el v_el !\n\tslt_el lt_el !\n\tslb_el lb_el !\n\tsrt_el rt_el !\n\tsrb_el rb_el !\n;\n\n: f_double\t( -- )\t\\ set frames to double\n\tdh_el h_el !\n\tdv_el v_el !\n\tdlt_el lt_el !\n\tdlb_el lb_el !\n\tdrt_el rt_el !\n\tdrb_el rb_el !\n;\n\n: vline\t( len x y -- )\t\\ Draw vertical single line\n\t2dup 4 pick\n\t0 do\n\t\tat-xy\n\t\tv_el @ emit\n\t\t1+\n\t\t2dup\n\tloop\n\t2drop 2drop drop\n;\n\n: box\t( w h x y -- )\t\\ Draw a box\n\t2dup 1+ 4 pick 1- -rot\n\tvline\t\t\\ Draw left vert line\n\t2dup 1+ swap 5 pick + swap 4 pick 1- -rot\n\tvline\t\t\\ Draw right vert line\n\t2dup swap 1+ swap 5 pick 1- -rot\n\thline\t\t\\ Draw top horiz line\n\t2dup swap 1+ swap 4 pick + 5 pick 1- -rot\n\thline\t\t\\ Draw bottom horiz line\n\t2dup at-xy lt_el @ emit\t\\ Draw left-top corner\n\t2dup 4 pick + at-xy lb_el @ emit\t\\ Draw left bottom corner\n\t2dup swap 5 pick + swap at-xy rt_el @ emit\t\\ Draw right top corner\n\t2 pick + swap 3 pick + swap at-xy rb_el @ emit\n\t2drop\n;\n\nf_single\nfill_none fill !\n","old_contents":"\\ Words implementing frame drawing\n\\ XXX Filled boxes are left as an exercise for the reader... ;-\/\n\\ $FreeBSD$\n\nmarker task-frames.4th\n\nvariable h_el\nvariable v_el\nvariable lt_el\nvariable lb_el\nvariable rt_el\nvariable rb_el\nvariable fill\n\n\\ Single frames\n196 constant sh_el\n179 constant sv_el\n218 constant slt_el\n192 constant slb_el\n191 constant srt_el\n217 constant srb_el\n\\ Double frames\n205 constant dh_el\n186 constant dv_el\n201 constant dlt_el\n200 constant dlb_el\n187 constant drt_el\n188 constant drb_el\n\\ Fillings\n0 constant fill_none\n32 constant fill_blank\n176 constant fill_dark\n177 constant fill_med\n178 constant fill_bright\n\n\n: hline\t( len x y -- )\t\\ Draw horizontal single line\n\tat-xy\t\t\\ move cursor\n\t0 do\n\t\th_el @ emit\n\tloop\n;\n\n: f_single\t( -- )\t\\ set frames to single\n\tsh_el h_el !\n\tsv_el v_el !\n\tslt_el lt_el !\n\tslb_el lb_el !\n\tsrt_el rt_el !\n\tsrb_el rb_el !\n;\n\n: f_double\t( -- )\t\\ set frames to double\n\tdh_el h_el !\n\tdv_el v_el !\n\tdlt_el lt_el !\n\tdlb_el lb_el !\n\tdrt_el rt_el !\n\tdrb_el rb_el !\n;\n\n: vline\t( len x y -- )\t\\ Draw vertical single line\n\t2dup 4 pick\n\t0 do\n\t\tat-xy\n\t\tv_el @ emit\n\t\t1+\n\t\t2dup\n\tloop\n\t2drop 2drop drop\n;\n\n: box\t( w h x y -- )\t\\ Draw a box\n\t2dup 1+ 4 pick 1- -rot\n\tvline\t\t\\ Draw left vert line\n\t2dup 1+ swap 5 pick + swap 4 pick 1- -rot\n\tvline\t\t\\ Draw right vert line\n\t2dup swap 1+ swap 5 pick 1- -rot\n\thline\t\t\\ Draw top horiz line\n\t2dup swap 1+ swap 4 pick + 5 pick 1- -rot\n\thline\t\t\\ Draw bottom horiz line\n\t2dup at-xy lt_el @ emit\t\\ Draw left-top corner\n\t2dup 4 pick + at-xy lb_el @ emit\t\\ Draw left bottom corner\n\t2dup swap 5 pick + swap at-xy rt_el @ emit\t\\ Draw right top corner\n\t2 pick + swap 3 pick + swap at-xy rb_el @ emit\n\t2drop\n;\n\nf_single\nfill_none fill !\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"52e5343bd3ec4db95f886666ce4c2e6e6f864ac2","subject":"The word environment? returns a flag indicating whether the variable was found or not. Fix it's usage. Alas, it caused no problem before, besides leaving garbage in the stack, because refill, used by [if] [else] [then], was broken.","message":"The word environment? returns a flag indicating whether the variable\nwas found or not. Fix it's usage. Alas, it caused no problem before,\nbesides leaving garbage in the stack, because refill, used by [if]\n[else] [then], was broken.\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/loader.4th","new_file":"sys\/boot\/forth\/loader.4th","new_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\ns\" arch-alpha\" environment? [if] [if]\n\ts\" loader_version\" environment? [if]\n\t\t3 < [if]\n\t\t\t.( Loader version 0.3+ required) cr\n\t\t\tabort\n\t\t[then]\n\t[else]\n\t\t.( Could not get loader version!) cr\n\t\tabort\n\t[then]\n[then] [then]\n\ns\" arch-i386\" environment? [if] [if]\n\ts\" loader_version\" environment? [if]\n\t\t8 < [if]\n\t\t\t.( Loader version 0.8+ required) cr\n\t\t\tabort\n\t\t[then]\n\t[else]\n\t\t.( Could not get loader version!) cr\n\t\tabort\n\t[then]\n[then] [then]\n\ninclude \/boot\/support.4th\n\nonly forth definitions also support-functions\n\n\\ ***** boot-conf\n\\\n\\\tPrepares to boot as specified by loaded configuration files.\n\nalso support-functions definitions\n\n: bootpath s\" \/boot\/\" ;\n: modulepath s\" module_path\" ;\n: saveenv ( addr len | 0 -1 -- addr' len | 0 -1 )\n dup -1 = if exit then\n dup allocate abort\" Out of memory\"\n swap 2dup 2>r\n move\n 2r>\n;\n: freeenv ( addr len | 0 -1 )\n -1 = if drop else free abort\" Freeing error\" then\n;\n: restoreenv ( addr len | 0 -1 -- )\n dup -1 = if ( it wasn't set )\n 2drop\n modulepath unsetenv\n else\n over >r\n modulepath setenv\n r> free abort\" Freeing error\"\n then\n;\n\nonly forth also support-functions also builtins definitions\n\n: boot-conf ( args 1 | 0 \"args\" -- flag )\n 0 1 unload drop\n\n 0= if ( interpreted )\n \\ Get next word on the command line\n bl word count\n ?dup 0= if ( there wasn't anything )\n drop 0\n else ( put in the number of strings )\n 1\n then\n then ( interpreted )\n\n if ( there are arguments )\n \\ Try to load the kernel\n s\" kernel_options\" getenv dup -1 = if drop 2dup 1 else 2over 2 then\n\n 1 load if ( load command failed )\n \\ Remove garbage from the stack\n\n \\ Set the environment variable module_path, and try loading\n \\ the kernel again.\n\n \\ First, save module_path value\n modulepath getenv saveenv dup -1 = if 0 swap then 2>r\n\n \\ Sets the new value\n 2dup modulepath setenv\n\n \\ Try to load the kernel\n s\" load ${kernel} ${kernel_options}\" ['] evaluate catch\n if ( load failed yet again )\n\t\\ Remove garbage from the stack\n\t2drop\n\n\t\\ Try prepending \/boot\/\n\tbootpath 2over nip over + allocate\n\tif ( out of memory )\n\t 2drop 2drop\n\t 2r> restoreenv\n\t 100 exit\n\tthen\n\n\t0 2swap strcat 2swap strcat\n\t2dup modulepath setenv\n\n\tdrop free if ( freeing memory error )\n\t 2drop\n\t 2r> restoreenv\n\t 100 exit\n\tthen\n \n\t\\ Now, once more, try to load the kernel\n\ts\" load ${kernel} ${kernel_options}\" ['] evaluate catch\n\tif ( failed once more )\n\t 2drop\n\t 2r> restoreenv\n\t 100 exit\n\tthen\n\n else ( we found the kernel on the path passed )\n\n\t2drop ( discard command line arguments )\n\n then ( could not load kernel from directory passed )\n\n \\ Load the remaining modules, if the kernel was loaded at all\n ['] load_modules catch if 2r> restoreenv 100 exit then\n\n \\ Call autoboot to perform the booting\n 0 1 autoboot\n\n \\ Keep new module_path\n 2r> freeenv\n\n exit\n then ( could not load kernel with name passed )\n\n 2drop ( discard command line arguments )\n\n else ( try just a straight-forward kernel load )\n s\" load ${kernel} ${kernel_options}\" ['] evaluate catch\n if ( kernel load failed ) 2drop 100 exit then\n\n then ( there are command line arguments )\n\n \\ Load the remaining modules, if the kernel was loaded at all\n ['] load_modules catch if 100 exit then\n\n \\ Call autoboot to perform the booting\n 0 1 autoboot\n;\n\nalso forth definitions\nbuiltin: boot-conf\nonly forth definitions also support-functions\n\n\\ ***** check-password\n\\\n\\\tIf a password was defined, execute autoboot and ask for\n\\\tpassword if autoboot returns.\n\n: check-password\n password .addr @ if\n 0 autoboot\n false >r\n begin\n bell emit bell emit\n .\" Password: \"\n password .len @ read-password\n dup password .len @ = if\n 2dup password .addr @ password .len @\n compare 0= if r> drop true >r then\n then\n drop free drop\n r@\n until\n r> drop\n then\n;\n\n\\ ***** start\n\\\n\\ Initializes support.4th global variables, sets loader_conf_files,\n\\ process conf files, and, if any one such file was succesfully\n\\ read to the end, load kernel and modules.\n\n: start ( -- ) ( throws: abort & user-defined )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n \\ Will *NOT* try to load kernel and modules if no configuration file\n \\ was succesfully loaded!\n any_conf_read? if\n load_kernel\n load_modules\n then\n;\n\n\\ ***** initialize\n\\\n\\\tOverrides support.4th initialization word with one that does\n\\\teverything start one does, short of loading the kernel and\n\\\tmodules. Returns a flag\n\n: initialize ( -- flag )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n any_conf_read?\n;\n\n\\ ***** read-conf\n\\\n\\\tRead a configuration file, whose name was specified on the command\n\\\tline, if interpreted, or given on the stack, if compiled in.\n\n: (read-conf) ( addr len -- )\n conf_files .addr @ ?dup if free abort\" Fatal error freeing memory\" then\n strdup conf_files .len ! conf_files .addr !\n include_conf_files \\ Will recurse on new loader_conf_files definitions\n;\n\n: read-conf ( | addr len -- ) ( throws: abort & user-defined )\n state @ if\n \\ Compiling\n postpone (read-conf)\n else\n \\ Interpreting\n bl parse (read-conf)\n then\n; immediate\n\n\\ ***** enable-module\n\\\n\\ Turn a module loading on.\n\n: enable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n true r> module.flag !\n .\" will be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** disable-module\n\\\n\\ Turn a module loading off.\n\n: disable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n false r> module.flag !\n .\" will not be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** toggle-module\n\\\n\\ Turn a module loading on\/off.\n\n: toggle-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n r@ module.flag @ 0= dup r> module.flag !\n if\n .\" will be loaded.\" cr\n else\n .\" will not be loaded.\" cr\n then\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** show-module\n\\\n\\\tShow loading information about a module.\n\n: show-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n .\" Name: \" r@ module.name dup .addr @ swap .len @ type cr\n .\" Path: \" r@ module.loadname dup .addr @ swap .len @ type cr\n .\" Type: \" r@ module.type dup .addr @ swap .len @ type cr\n .\" Flags: \" r@ module.args dup .addr @ swap .len @ type cr\n .\" Before load: \" r@ module.beforeload dup .addr @ swap .len @ type cr\n .\" After load: \" r@ module.afterload dup .addr @ swap .len @ type cr\n .\" Error: \" r@ module.loaderror dup .addr @ swap .len @ type cr\n .\" Status: \" r> module.flag @ if .\" Load\" else .\" Don't load\" then cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ Words to be used inside configuration files\n\n: retry false ; \\ For use in load error commands\n: ignore true ; \\ For use in load error commands\n\n\\ Return to strict forth vocabulary\n\nonly forth also\n\n","old_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\ns\" arch-alpha\" environment? [if]\ns\" loader_version\" environment? 3 < abort\" Loader version 0.3+ required\"\n[then]\n\ns\" arch-i386\" environment? [if]\ns\" loader_version\" environment? 8 < abort\" Loader version 0.8+ required\"\n[then]\n\ninclude \/boot\/support.4th\n\nonly forth definitions also support-functions\n\n\\ ***** boot-conf\n\\\n\\\tPrepares to boot as specified by loaded configuration files.\n\nalso support-functions definitions\n\n: bootpath s\" \/boot\/\" ;\n: modulepath s\" module_path\" ;\n: saveenv ( addr len | 0 -1 -- addr' len | 0 -1 )\n dup -1 = if exit then\n dup allocate abort\" Out of memory\"\n swap 2dup 2>r\n move\n 2r>\n;\n: freeenv ( addr len | 0 -1 )\n -1 = if drop else free abort\" Freeing error\" then\n;\n: restoreenv ( addr len | 0 -1 -- )\n dup -1 = if ( it wasn't set )\n 2drop\n modulepath unsetenv\n else\n over >r\n modulepath setenv\n r> free abort\" Freeing error\"\n then\n;\n\nonly forth also support-functions also builtins definitions\n\n: boot-conf ( args 1 | 0 \"args\" -- flag )\n 0 1 unload drop\n\n 0= if ( interpreted )\n \\ Get next word on the command line\n bl word count\n ?dup 0= if ( there wasn't anything )\n drop 0\n else ( put in the number of strings )\n 1\n then\n then ( interpreted )\n\n if ( there are arguments )\n \\ Try to load the kernel\n s\" kernel_options\" getenv dup -1 = if drop 2dup 1 else 2over 2 then\n\n 1 load if ( load command failed )\n \\ Remove garbage from the stack\n\n \\ Set the environment variable module_path, and try loading\n \\ the kernel again.\n\n \\ First, save module_path value\n modulepath getenv saveenv dup -1 = if 0 swap then 2>r\n\n \\ Sets the new value\n 2dup modulepath setenv\n\n \\ Try to load the kernel\n s\" load ${kernel} ${kernel_options}\" ['] evaluate catch\n if ( load failed yet again )\n\t\\ Remove garbage from the stack\n\t2drop\n\n\t\\ Try prepending \/boot\/\n\tbootpath 2over nip over + allocate\n\tif ( out of memory )\n\t 2drop 2drop\n\t 2r> restoreenv\n\t 100 exit\n\tthen\n\n\t0 2swap strcat 2swap strcat\n\t2dup modulepath setenv\n\n\tdrop free if ( freeing memory error )\n\t 2drop\n\t 2r> restoreenv\n\t 100 exit\n\tthen\n \n\t\\ Now, once more, try to load the kernel\n\ts\" load ${kernel} ${kernel_options}\" ['] evaluate catch\n\tif ( failed once more )\n\t 2drop\n\t 2r> restoreenv\n\t 100 exit\n\tthen\n\n else ( we found the kernel on the path passed )\n\n\t2drop ( discard command line arguments )\n\n then ( could not load kernel from directory passed )\n\n \\ Load the remaining modules, if the kernel was loaded at all\n ['] load_modules catch if 2r> restoreenv 100 exit then\n\n \\ Call autoboot to perform the booting\n 0 1 autoboot\n\n \\ Keep new module_path\n 2r> freeenv\n\n exit\n then ( could not load kernel with name passed )\n\n 2drop ( discard command line arguments )\n\n else ( try just a straight-forward kernel load )\n s\" load ${kernel} ${kernel_options}\" ['] evaluate catch\n if ( kernel load failed ) 2drop 100 exit then\n\n then ( there are command line arguments )\n\n \\ Load the remaining modules, if the kernel was loaded at all\n ['] load_modules catch if 100 exit then\n\n \\ Call autoboot to perform the booting\n 0 1 autoboot\n;\n\nalso forth definitions\nbuiltin: boot-conf\nonly forth definitions also support-functions\n\n\\ ***** check-password\n\\\n\\\tIf a password was defined, execute autoboot and ask for\n\\\tpassword if autoboot returns.\n\n: check-password\n password .addr @ if\n 0 autoboot\n false >r\n begin\n bell emit bell emit\n .\" Password: \"\n password .len @ read-password\n dup password .len @ = if\n 2dup password .addr @ password .len @\n compare 0= if r> drop true >r then\n then\n drop free drop\n r@\n until\n r> drop\n then\n;\n\n\\ ***** start\n\\\n\\ Initializes support.4th global variables, sets loader_conf_files,\n\\ process conf files, and, if any one such file was succesfully\n\\ read to the end, load kernel and modules.\n\n: start ( -- ) ( throws: abort & user-defined )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n \\ Will *NOT* try to load kernel and modules if no configuration file\n \\ was succesfully loaded!\n any_conf_read? if\n load_kernel\n load_modules\n then\n;\n\n\\ ***** initialize\n\\\n\\\tOverrides support.4th initialization word with one that does\n\\\teverything start one does, short of loading the kernel and\n\\\tmodules. Returns a flag\n\n: initialize ( -- flag )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n any_conf_read?\n;\n\n\\ ***** read-conf\n\\\n\\\tRead a configuration file, whose name was specified on the command\n\\\tline, if interpreted, or given on the stack, if compiled in.\n\n: (read-conf) ( addr len -- )\n conf_files .addr @ ?dup if free abort\" Fatal error freeing memory\" then\n strdup conf_files .len ! conf_files .addr !\n include_conf_files \\ Will recurse on new loader_conf_files definitions\n;\n\n: read-conf ( | addr len -- ) ( throws: abort & user-defined )\n state @ if\n \\ Compiling\n postpone (read-conf)\n else\n \\ Interpreting\n bl parse (read-conf)\n then\n; immediate\n\n\\ ***** enable-module\n\\\n\\ Turn a module loading on.\n\n: enable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n true r> module.flag !\n .\" will be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** disable-module\n\\\n\\ Turn a module loading off.\n\n: disable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n false r> module.flag !\n .\" will not be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** toggle-module\n\\\n\\ Turn a module loading on\/off.\n\n: toggle-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n r@ module.flag @ 0= dup r> module.flag !\n if\n .\" will be loaded.\" cr\n else\n .\" will not be loaded.\" cr\n then\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** show-module\n\\\n\\\tShow loading information about a module.\n\n: show-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n .\" Name: \" r@ module.name dup .addr @ swap .len @ type cr\n .\" Path: \" r@ module.loadname dup .addr @ swap .len @ type cr\n .\" Type: \" r@ module.type dup .addr @ swap .len @ type cr\n .\" Flags: \" r@ module.args dup .addr @ swap .len @ type cr\n .\" Before load: \" r@ module.beforeload dup .addr @ swap .len @ type cr\n .\" After load: \" r@ module.afterload dup .addr @ swap .len @ type cr\n .\" Error: \" r@ module.loaderror dup .addr @ swap .len @ type cr\n .\" Status: \" r> module.flag @ if .\" Load\" else .\" Don't load\" then cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ Words to be used inside configuration files\n\n: retry false ; \\ For use in load error commands\n: ignore true ; \\ For use in load error commands\n\n\\ Return to strict forth vocabulary\n\nonly forth also\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"dddc67f9130b7b6d79919c1341fdfa5a5c4fe5c4","subject":"What could possibly have possessed me to forget the \"0 (arguments)\" in two of the three boot words in the \"boot\" redefinition, I have no clue. Fix it.","message":"What could possibly have possessed me to forget the \"0 (arguments)\"\nin two of the three boot words in the \"boot\" redefinition, I have no\nclue. Fix it.\n\nNoticed by: bp\nNoticed by: adrian\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/loader.4th","new_file":"sys\/boot\/forth\/loader.4th","new_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\ns\" arch-alpha\" environment? [if] [if]\n\ts\" loader_version\" environment? [if]\n\t\t11 < [if]\n\t\t\t.( Loader version 1.1+ required) cr\n\t\t\tabort\n\t\t[then]\n\t[else]\n\t\t.( Could not get loader version!) cr\n\t\tabort\n\t[then]\n[then] [then]\n\ns\" arch-i386\" environment? [if] [if]\n\ts\" loader_version\" environment? [if]\n\t\t10 < [if]\n\t\t\t.( Loader version 1.0+ required) cr\n\t\t\tabort\n\t\t[then]\n\t[else]\n\t\t.( Could not get loader version!) cr\n\t\tabort\n\t[then]\n[then] [then]\n\ninclude \/boot\/support.4th\n\n\\ ***** boot-conf\n\\\n\\\tPrepares to boot as specified by loaded configuration files.\n\nonly forth also support-functions also builtins definitions\n\n: boot\n 0= if ( interpreted ) get_arguments then\n\n \\ Unload only if a path was passed\n dup if\n >r over r> swap\n c@ [char] - <> if\n 0 1 unload drop\n else\n s\" kernelname\" getenv? 0= if ( no kernel has been loaded )\n\tload_kernel_and_modules\n\t?dup if exit then\n then\n 0 1 boot exit\n then\n else\n s\" kernelname\" getenv? 0= if ( no kernel has been loaded )\n load_kernel_and_modules\n ?dup if exit then\n then\n 0 1 boot exit\n then\n load_kernel_and_modules\n ?dup 0= if 0 1 boot then\n;\n\n: boot-conf\n 0= if ( interpreted ) get_arguments then\n 0 1 unload drop\n load_kernel_and_modules\n ?dup 0= if 0 1 autoboot then\n;\n\nalso forth definitions also builtins\n\nbuiltin: boot\nbuiltin: boot-conf\n\nonly forth definitions also support-functions\n\n\\ ***** check-password\n\\\n\\\tIf a password was defined, execute autoboot and ask for\n\\\tpassword if autoboot returns.\n\n: check-password\n password .addr @ if\n 0 autoboot\n false >r\n begin\n bell emit bell emit\n .\" Password: \"\n password .len @ read-password\n dup password .len @ = if\n 2dup password .addr @ password .len @\n compare 0= if r> drop true >r then\n then\n drop free drop\n r@\n until\n r> drop\n then\n;\n\n\\ ***** start\n\\\n\\ Initializes support.4th global variables, sets loader_conf_files,\n\\ process conf files, and, if any one such file was succesfully\n\\ read to the end, load kernel and modules.\n\n: start ( -- ) ( throws: abort & user-defined )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n \\ Will *NOT* try to load kernel and modules if no configuration file\n \\ was succesfully loaded!\n any_conf_read? if\n load_kernel\n load_modules\n then\n;\n\n\\ ***** initialize\n\\\n\\\tOverrides support.4th initialization word with one that does\n\\\teverything start one does, short of loading the kernel and\n\\\tmodules. Returns a flag\n\n: initialize ( -- flag )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n any_conf_read?\n;\n\n\\ ***** read-conf\n\\\n\\\tRead a configuration file, whose name was specified on the command\n\\\tline, if interpreted, or given on the stack, if compiled in.\n\n: (read-conf) ( addr len -- )\n conf_files .addr @ ?dup if free abort\" Fatal error freeing memory\" then\n strdup conf_files .len ! conf_files .addr !\n include_conf_files \\ Will recurse on new loader_conf_files definitions\n;\n\n: read-conf ( | addr len -- ) ( throws: abort & user-defined )\n state @ if\n \\ Compiling\n postpone (read-conf)\n else\n \\ Interpreting\n bl parse (read-conf)\n then\n; immediate\n\n\\ ***** enable-module\n\\\n\\ Turn a module loading on.\n\n: enable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n true r> module.flag !\n .\" will be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** disable-module\n\\\n\\ Turn a module loading off.\n\n: disable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n false r> module.flag !\n .\" will not be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** toggle-module\n\\\n\\ Turn a module loading on\/off.\n\n: toggle-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n r@ module.flag @ 0= dup r> module.flag !\n if\n .\" will be loaded.\" cr\n else\n .\" will not be loaded.\" cr\n then\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** show-module\n\\\n\\\tShow loading information about a module.\n\n: show-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n .\" Name: \" r@ module.name dup .addr @ swap .len @ type cr\n .\" Path: \" r@ module.loadname dup .addr @ swap .len @ type cr\n .\" Type: \" r@ module.type dup .addr @ swap .len @ type cr\n .\" Flags: \" r@ module.args dup .addr @ swap .len @ type cr\n .\" Before load: \" r@ module.beforeload dup .addr @ swap .len @ type cr\n .\" After load: \" r@ module.afterload dup .addr @ swap .len @ type cr\n .\" Error: \" r@ module.loaderror dup .addr @ swap .len @ type cr\n .\" Status: \" r> module.flag @ if .\" Load\" else .\" Don't load\" then cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ Words to be used inside configuration files\n\n: retry false ; \\ For use in load error commands\n: ignore true ; \\ For use in load error commands\n\n\\ Return to strict forth vocabulary\n\n: #type\n over - >r\n type\n r> spaces\n;\n\n: .? 2 spaces 2swap 15 #type 2 spaces type cr ;\n\n: ?\n ['] ? execute\n s\" boot-conf\" s\" load kernel and modules, then autoboot\" .?\n s\" read-conf\" s\" read a configuration file\" .?\n s\" enable-module\" s\" enable loading of a module\" .?\n s\" disable-module\" s\" disable loading of a module\" .?\n s\" toggle-module\" s\" toggle loading of a module\" .?\n s\" show-module\" s\" show module load data\" .?\n;\n\nonly forth also\n\n","old_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\ns\" arch-alpha\" environment? [if] [if]\n\ts\" loader_version\" environment? [if]\n\t\t11 < [if]\n\t\t\t.( Loader version 1.1+ required) cr\n\t\t\tabort\n\t\t[then]\n\t[else]\n\t\t.( Could not get loader version!) cr\n\t\tabort\n\t[then]\n[then] [then]\n\ns\" arch-i386\" environment? [if] [if]\n\ts\" loader_version\" environment? [if]\n\t\t10 < [if]\n\t\t\t.( Loader version 1.0+ required) cr\n\t\t\tabort\n\t\t[then]\n\t[else]\n\t\t.( Could not get loader version!) cr\n\t\tabort\n\t[then]\n[then] [then]\n\ninclude \/boot\/support.4th\n\n\\ ***** boot-conf\n\\\n\\\tPrepares to boot as specified by loaded configuration files.\n\nonly forth also support-functions also builtins definitions\n\n: boot\n 0= if ( interpreted ) get_arguments then\n\n \\ Unload only if a path was passed\n dup if\n >r over r> swap\n c@ [char] - <> if\n 0 1 unload drop\n else\n s\" kernelname\" getenv? 0= if ( no kernel has been loaded )\n\tload_kernel_and_modules\n\t?dup if exit then\n then\n 1 boot exit\n then\n else\n s\" kernelname\" getenv? 0= if ( no kernel has been loaded )\n load_kernel_and_modules\n ?dup if exit then\n then\n 1 boot exit\n then\n load_kernel_and_modules\n ?dup 0= if 0 1 boot then\n;\n\n: boot-conf\n 0= if ( interpreted ) get_arguments then\n 0 1 unload drop\n load_kernel_and_modules\n ?dup 0= if 0 1 autoboot then\n;\n\nalso forth definitions also builtins\n\nbuiltin: boot\nbuiltin: boot-conf\n\nonly forth definitions also support-functions\n\n\\ ***** check-password\n\\\n\\\tIf a password was defined, execute autoboot and ask for\n\\\tpassword if autoboot returns.\n\n: check-password\n password .addr @ if\n 0 autoboot\n false >r\n begin\n bell emit bell emit\n .\" Password: \"\n password .len @ read-password\n dup password .len @ = if\n 2dup password .addr @ password .len @\n compare 0= if r> drop true >r then\n then\n drop free drop\n r@\n until\n r> drop\n then\n;\n\n\\ ***** start\n\\\n\\ Initializes support.4th global variables, sets loader_conf_files,\n\\ process conf files, and, if any one such file was succesfully\n\\ read to the end, load kernel and modules.\n\n: start ( -- ) ( throws: abort & user-defined )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n \\ Will *NOT* try to load kernel and modules if no configuration file\n \\ was succesfully loaded!\n any_conf_read? if\n load_kernel\n load_modules\n then\n;\n\n\\ ***** initialize\n\\\n\\\tOverrides support.4th initialization word with one that does\n\\\teverything start one does, short of loading the kernel and\n\\\tmodules. Returns a flag\n\n: initialize ( -- flag )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n any_conf_read?\n;\n\n\\ ***** read-conf\n\\\n\\\tRead a configuration file, whose name was specified on the command\n\\\tline, if interpreted, or given on the stack, if compiled in.\n\n: (read-conf) ( addr len -- )\n conf_files .addr @ ?dup if free abort\" Fatal error freeing memory\" then\n strdup conf_files .len ! conf_files .addr !\n include_conf_files \\ Will recurse on new loader_conf_files definitions\n;\n\n: read-conf ( | addr len -- ) ( throws: abort & user-defined )\n state @ if\n \\ Compiling\n postpone (read-conf)\n else\n \\ Interpreting\n bl parse (read-conf)\n then\n; immediate\n\n\\ ***** enable-module\n\\\n\\ Turn a module loading on.\n\n: enable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n true r> module.flag !\n .\" will be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** disable-module\n\\\n\\ Turn a module loading off.\n\n: disable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n false r> module.flag !\n .\" will not be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** toggle-module\n\\\n\\ Turn a module loading on\/off.\n\n: toggle-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n r@ module.flag @ 0= dup r> module.flag !\n if\n .\" will be loaded.\" cr\n else\n .\" will not be loaded.\" cr\n then\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** show-module\n\\\n\\\tShow loading information about a module.\n\n: show-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n .\" Name: \" r@ module.name dup .addr @ swap .len @ type cr\n .\" Path: \" r@ module.loadname dup .addr @ swap .len @ type cr\n .\" Type: \" r@ module.type dup .addr @ swap .len @ type cr\n .\" Flags: \" r@ module.args dup .addr @ swap .len @ type cr\n .\" Before load: \" r@ module.beforeload dup .addr @ swap .len @ type cr\n .\" After load: \" r@ module.afterload dup .addr @ swap .len @ type cr\n .\" Error: \" r@ module.loaderror dup .addr @ swap .len @ type cr\n .\" Status: \" r> module.flag @ if .\" Load\" else .\" Don't load\" then cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ Words to be used inside configuration files\n\n: retry false ; \\ For use in load error commands\n: ignore true ; \\ For use in load error commands\n\n\\ Return to strict forth vocabulary\n\n: #type\n over - >r\n type\n r> spaces\n;\n\n: .? 2 spaces 2swap 15 #type 2 spaces type cr ;\n\n: ?\n ['] ? execute\n s\" boot-conf\" s\" load kernel and modules, then autoboot\" .?\n s\" read-conf\" s\" read a configuration file\" .?\n s\" enable-module\" s\" enable loading of a module\" .?\n s\" disable-module\" s\" disable loading of a module\" .?\n s\" toggle-module\" s\" toggle loading of a module\" .?\n s\" show-module\" s\" show module load data\" .?\n;\n\nonly forth also\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"b714ea6bf98a62ea39dda7f963a30ed33c63ee74","subject":"Get rid of a spurious warning on the console when booting the kernel from the interactive loader(8) prompt and beastie_disable=\"YES\" is set in loader.conf(5). In this case menu.rc is not evaluated and consequently menu-unset does not have a body yet. This results in the ficl warning \"menu-unset not found\" when try-menu-unset invokes menu-unset.","message":"Get rid of a spurious warning on the console when booting the kernel\nfrom the interactive loader(8) prompt and beastie_disable=\"YES\" is set\nin loader.conf(5). In this case menu.rc is not evaluated and consequently\nmenu-unset does not have a body yet. This results in the ficl warning\n\"menu-unset not found\" when try-menu-unset invokes menu-unset.\n\nCheck for beastie_disable=\"YES\" explicitly, so that the try-menu-unset\nword will not attempt to invoke menu-unset because the menu will have\nnever been configured. [1]\nUse the sfind primitive as a last resort as an additional safer approach\nconjuring a foreign word safely. [2]\n\nPR:\t\tkern\/163938\nSubmitted by:\tDevin Teske [1]\nReviewed by:\tDevin Teske [2]\nReported and tested by:\tdim\nMFC after:\t1 week\nX-MFC with:\tr228985\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/loader.4th","new_file":"sys\/boot\/forth\/loader.4th","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"bsd-3-clause","lang":"Forth"} {"commit":"8cf870699c31657390efa045b16e101ad0a41399","subject":"MFC: Allow negative values to be specified in the loader.","message":"MFC: Allow negative values to be specified in the loader.\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/support.4th","new_file":"sys\/boot\/forth\/support.4th","new_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\ \n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\n\\ Loader.rc support functions:\n\\\n\\ initialize_support ( -- )\tinitialize global variables\n\\ initialize ( addr len -- )\tas above, plus load_conf_files\n\\ load_conf ( addr len -- )\tload conf file given\n\\ include_conf_files ( -- )\tload all conf files in load_conf_files\n\\ print_syntax_error ( -- )\tprint line and marker of where a syntax\n\\\t\t\t\terror was detected\n\\ print_line ( -- )\t\tprint last line processed\n\\ load_kernel ( -- )\t\tload kernel\n\\ load_modules ( -- )\t\tload modules flagged\n\\\n\\ Exported structures:\n\\\n\\ string\t\t\tcounted string structure\n\\\tcell .addr\t\t\tstring address\n\\\tcell .len\t\t\tstring length\n\\ module\t\t\tmodule loading information structure\n\\\tcell module.flag\t\tshould we load it?\n\\\tstring module.name\t\tmodule's name\n\\\tstring module.loadname\t\tname to be used in loading the module\n\\\tstring module.type\t\tmodule's type\n\\\tstring module.args\t\tflags to be passed during load\n\\\tstring module.beforeload\tcommand to be executed before load\n\\\tstring module.afterload\t\tcommand to be executed after load\n\\\tstring module.loaderror\t\tcommand to be executed if load fails\n\\\tcell module.next\t\tlist chain\n\\\n\\ Exported global variables;\n\\\n\\ string conf_files\t\tconfiguration files to be loaded\n\\ string password\t\tpassword\n\\ cell modules_options\t\tpointer to first module information\n\\ value verbose?\t\tindicates if user wants a verbose loading\n\\ value any_conf_read?\t\tindicates if a conf file was succesfully read\n\\\n\\ Other exported words:\n\\\n\\ strdup ( addr len -- addr' len)\t\t\tsimilar to strdup(3)\n\\ strcat ( addr len addr' len' -- addr len+len' )\tsimilar to strcat(3)\n\\ strlen ( addr -- len )\t\t\t\tsimilar to strlen(3)\n\\ s' ( | string' -- addr len | )\t\t\tsimilar to s\"\n\\ rudimentary structure support\n\n\\ Exception values\n\n1 constant syntax_error\n2 constant out_of_memory\n3 constant free_error\n4 constant set_error\n5 constant read_error\n6 constant open_error\n7 constant exec_error\n8 constant before_load_error\n9 constant after_load_error\n\n\\ I\/O constants\n\n0 constant SEEK_SET\n1 constant SEEK_CUR\n2 constant SEEK_END\n\n0 constant O_RDONLY\n1 constant O_WRONLY\n2 constant O_RDWR\n\n\\ Crude structure support\n\n: structure:\n create here 0 , ['] drop , 0\n does> create here swap dup @ allot cell+ @ execute\n;\n: member: create dup , over , + does> cell+ @ + ;\n: ;structure swap ! ;\n: constructor! >body cell+ ! ;\n: constructor: over :noname ;\n: ;constructor postpone ; swap cell+ ! ; immediate\n: sizeof ' >body @ state @ if postpone literal then ; immediate\n: offsetof ' >body cell+ @ state @ if postpone literal then ; immediate\n: ptr 1 cells member: ;\n: int 1 cells member: ;\n\n\\ String structure\n\nstructure: string\n\tptr .addr\n\tint .len\n\tconstructor:\n\t 0 over .addr !\n\t 0 swap .len !\n\t;constructor\n;structure\n\n\n\\ Module options linked list\n\nstructure: module\n\tint module.flag\n\tsizeof string member: module.name\n\tsizeof string member: module.loadname\n\tsizeof string member: module.type\n\tsizeof string member: module.args\n\tsizeof string member: module.beforeload\n\tsizeof string member: module.afterload\n\tsizeof string member: module.loaderror\n\tptr module.next\n;structure\n\n\\ Internal loader structures\nstructure: preloaded_file\n\tptr pf.name\n\tptr pf.type\n\tptr pf.args\n\tptr pf.metadata\t\\ file_metadata\n\tint pf.loader\n\tint pf.addr\n\tint pf.size\n\tptr pf.modules\t\\ kernel_module\n\tptr pf.next\t\\ preloaded_file\n;structure\n\nstructure: kernel_module\n\tptr km.name\n\t\\ ptr km.args\n\tptr km.fp\t\\ preloaded_file\n\tptr km.next\t\\ kernel_module\n;structure\n\nstructure: file_metadata\n\tint\t\tmd.size\n\t2 member:\tmd.type\t\\ this is not ANS Forth compatible (XXX)\n\tptr\t\tmd.next\t\\ file_metadata\n\t0 member:\tmd.data\t\\ variable size\n;structure\n\nstructure: config_resource\n\tptr cf.name\n\tint cf.type\n0 constant RES_INT\n1 constant RES_STRING\n2 constant RES_LONG\n\t2 cells member: u\n;structure\n\nstructure: config_device\n\tptr cd.name\n\tint cd.unit\n\tint cd.resource_count\n\tptr cd.resources\t\\ config_resource\n;structure\n\nstructure: STAILQ_HEAD\n\tptr stqh_first\t\\ type*\n\tptr stqh_last\t\\ type**\n;structure\n\nstructure: STAILQ_ENTRY\n\tptr stqe_next\t\\ type*\n;structure\n\nstructure: pnphandler\n\tptr pnph.name\n\tptr pnph.enumerate\n;structure\n\nstructure: pnpident\n\tptr pnpid.ident\t\t\t\t\t\\ char*\n\tsizeof STAILQ_ENTRY cells member: pnpid.link\t\\ pnpident\n;structure\n\nstructure: pnpinfo\n\tptr pnpi.desc\n\tint pnpi.revision\n\tptr pnpi.module\t\t\t\t\\ (char*) module args\n\tint pnpi.argc\n\tptr pnpi.argv\n\tptr pnpi.handler\t\t\t\\ pnphandler\n\tsizeof STAILQ_HEAD member: pnpi.ident\t\\ pnpident\n\tsizeof STAILQ_ENTRY member: pnpi.link\t\\ pnpinfo\n;structure\n\n\\ Global variables\n\nstring conf_files\nstring nextboot_conf_file\nstring password\ncreate module_options sizeof module.next allot 0 module_options !\ncreate last_module_option sizeof module.next allot 0 last_module_option !\n0 value verbose?\n0 value nextboot?\n\n\\ Support string functions\n\n: strdup ( addr len -- addr' len )\n >r r@ allocate if out_of_memory throw then\n tuck r@ move\n r>\n;\n\n: strcat { addr len addr' len' -- addr len+len' }\n addr' addr len + len' move\n addr len len' +\n;\n\n: strlen ( addr -- len )\n 0 >r\n begin\n dup c@ while\n 1+ r> 1+ >r repeat\n drop r>\n;\n\n: s' \n [char] ' parse\n state @ if\n postpone sliteral\n then\n; immediate\n\n: 2>r postpone >r postpone >r ; immediate\n: 2r> postpone r> postpone r> ; immediate\n: 2r@ postpone 2r> postpone 2dup postpone 2>r ; immediate\n\n: getenv?\n getenv\n -1 = if false else drop true then\n;\n\n\\ Private definitions\n\nvocabulary support-functions\nonly forth also support-functions definitions\n\n\\ Some control characters constants\n\n7 constant bell\n8 constant backspace\n9 constant tab\n10 constant lf\n13 constant \n\n\\ Read buffer size\n\n80 constant read_buffer_size\n\n\\ Standard suffixes\n\n: load_module_suffix s\" _load\" ;\n: module_loadname_suffix s\" _name\" ;\n: module_type_suffix s\" _type\" ;\n: module_args_suffix s\" _flags\" ;\n: module_beforeload_suffix s\" _before\" ;\n: module_afterload_suffix s\" _after\" ;\n: module_loaderror_suffix s\" _error\" ;\n\n\\ Support operators\n\n: >= < 0= ;\n: <= > 0= ;\n\n\\ Assorted support funcitons\n\n: free-memory free if free_error throw then ;\n\n\\ Assignment data temporary storage\n\nstring name_buffer\nstring value_buffer\n\n\\ Line by line file reading functions\n\\\n\\ exported:\n\\\tline_buffer\n\\\tend_of_file?\n\\\tfd\n\\\tread_line\n\\\treset_line_reading\n\nvocabulary line-reading\nalso line-reading definitions also\n\n\\ File data temporary storage\n\nstring read_buffer\n0 value read_buffer_ptr\n\n\\ File's line reading function\n\nsupport-functions definitions\n\nstring line_buffer\n0 value end_of_file?\nvariable fd\n\nline-reading definitions\n\n: skip_newlines\n begin\n read_buffer .len @ read_buffer_ptr >\n while\n read_buffer .addr @ read_buffer_ptr + c@ lf = if\n read_buffer_ptr char+ to read_buffer_ptr\n else\n exit\n then\n repeat\n;\n\n: scan_buffer ( -- addr len )\n read_buffer_ptr >r\n begin\n read_buffer .len @ r@ >\n while\n read_buffer .addr @ r@ + c@ lf = if\n read_buffer .addr @ read_buffer_ptr + ( -- addr )\n r@ read_buffer_ptr - ( -- len )\n r> to read_buffer_ptr\n exit\n then\n r> char+ >r\n repeat\n read_buffer .addr @ read_buffer_ptr + ( -- addr )\n r@ read_buffer_ptr - ( -- len )\n r> to read_buffer_ptr\n;\n\n: line_buffer_resize ( len -- len )\n >r\n line_buffer .len @ if\n line_buffer .addr @\n line_buffer .len @ r@ +\n resize if out_of_memory throw then\n else\n r@ allocate if out_of_memory throw then\n then\n line_buffer .addr !\n r>\n;\n \n: append_to_line_buffer ( addr len -- )\n line_buffer .addr @ line_buffer .len @\n 2swap strcat\n line_buffer .len !\n drop\n;\n\n: read_from_buffer\n scan_buffer ( -- addr len )\n line_buffer_resize ( len -- len )\n append_to_line_buffer ( addr len -- )\n;\n\n: refill_required?\n read_buffer .len @ read_buffer_ptr =\n end_of_file? 0= and\n;\n\n: refill_buffer\n 0 to read_buffer_ptr\n read_buffer .addr @ 0= if\n read_buffer_size allocate if out_of_memory throw then\n read_buffer .addr !\n then\n fd @ read_buffer .addr @ read_buffer_size fread\n dup -1 = if read_error throw then\n dup 0= if true to end_of_file? then\n read_buffer .len !\n;\n\n: reset_line_buffer\n line_buffer .addr @ ?dup if\n free-memory\n then\n 0 line_buffer .addr !\n 0 line_buffer .len !\n;\n\nsupport-functions definitions\n\n: reset_line_reading\n 0 to read_buffer_ptr\n;\n\n: read_line\n reset_line_buffer\n skip_newlines\n begin\n read_from_buffer\n refill_required?\n while\n refill_buffer\n repeat\n;\n\nonly forth also support-functions definitions\n\n\\ Conf file line parser:\n\\ ::= '='[] |\n\\ []\n\\ ::= {||'_'}\n\\ ::= '\"'{|'\\'}'\"' | \n\\ ::= ASCII 32 to 126, except '\\' and '\"'\n\\ ::= '#'{}\n\\\n\\ exported:\n\\\tline_pointer\n\\\tprocess_conf\n\n0 value line_pointer\n\nvocabulary file-processing\nalso file-processing definitions\n\n\\ parser functions\n\\\n\\ exported:\n\\\tget_assignment\n\nvocabulary parser\nalso parser definitions also\n\n0 value parsing_function\n0 value end_of_line\n\n: end_of_line?\n line_pointer end_of_line =\n;\n\n: letter?\n line_pointer c@ >r\n r@ [char] A >=\n r@ [char] Z <= and\n r@ [char] a >=\n r> [char] z <= and\n or\n;\n\n: digit?\n line_pointer c@ >r\n r@ [char] - =\n r@ [char] 0 >=\n r> [char] 9 <= and\n or\n;\n\n: quote?\n line_pointer c@ [char] \" =\n;\n\n: assignment_sign?\n line_pointer c@ [char] = =\n;\n\n: comment?\n line_pointer c@ [char] # =\n;\n\n: space?\n line_pointer c@ bl =\n line_pointer c@ tab = or\n;\n\n: backslash?\n line_pointer c@ [char] \\ =\n;\n\n: underscore?\n line_pointer c@ [char] _ =\n;\n\n: dot?\n line_pointer c@ [char] . =\n;\n\n: skip_character\n line_pointer char+ to line_pointer\n;\n\n: skip_to_end_of_line\n end_of_line to line_pointer\n;\n\n: eat_space\n begin\n space?\n while\n skip_character\n end_of_line? if exit then\n repeat\n;\n\n: parse_name ( -- addr len )\n line_pointer\n begin\n letter? digit? underscore? dot? or or or\n while\n skip_character\n end_of_line? if \n line_pointer over -\n strdup\n exit\n then\n repeat\n line_pointer over -\n strdup\n;\n\n: remove_backslashes { addr len | addr' len' -- addr' len' }\n len allocate if out_of_memory throw then\n to addr'\n addr >r\n begin\n addr c@ [char] \\ <> if\n addr c@ addr' len' + c!\n len' char+ to len'\n then\n addr char+ to addr\n r@ len + addr =\n until\n r> drop\n addr' len'\n;\n\n: parse_quote ( -- addr len )\n line_pointer\n skip_character\n end_of_line? if syntax_error throw then\n begin\n quote? 0=\n while\n backslash? if\n skip_character\n end_of_line? if syntax_error throw then\n then\n skip_character\n end_of_line? if syntax_error throw then \n repeat\n skip_character\n line_pointer over -\n remove_backslashes\n;\n\n: read_name\n parse_name\t\t( -- addr len )\n name_buffer .len !\n name_buffer .addr !\n;\n\n: read_value\n quote? if\n parse_quote\t\t( -- addr len )\n else\n parse_name\t\t( -- addr len )\n then\n value_buffer .len !\n value_buffer .addr !\n;\n\n: comment\n skip_to_end_of_line\n;\n\n: white_space_4\n eat_space\n comment? if ['] comment to parsing_function exit then\n end_of_line? 0= if syntax_error throw then\n;\n\n: variable_value\n read_value\n ['] white_space_4 to parsing_function\n;\n\n: white_space_3\n eat_space\n letter? digit? quote? or or if\n ['] variable_value to parsing_function exit\n then\n syntax_error throw\n;\n\n: assignment_sign\n skip_character\n ['] white_space_3 to parsing_function\n;\n\n: white_space_2\n eat_space\n assignment_sign? if ['] assignment_sign to parsing_function exit then\n syntax_error throw\n;\n\n: variable_name\n read_name\n ['] white_space_2 to parsing_function\n;\n\n: white_space_1\n eat_space\n letter? if ['] variable_name to parsing_function exit then\n comment? if ['] comment to parsing_function exit then\n end_of_line? 0= if syntax_error throw then\n;\n\nfile-processing definitions\n\n: get_assignment\n line_buffer .addr @ line_buffer .len @ + to end_of_line\n line_buffer .addr @ to line_pointer\n ['] white_space_1 to parsing_function\n begin\n end_of_line? 0=\n while\n parsing_function execute\n repeat\n parsing_function ['] comment =\n parsing_function ['] white_space_1 =\n parsing_function ['] white_space_4 =\n or or 0= if syntax_error throw then\n;\n\nonly forth also support-functions also file-processing definitions also\n\n\\ Process line\n\n: assignment_type? ( addr len -- flag )\n name_buffer .addr @ name_buffer .len @\n compare 0=\n;\n\n: suffix_type? ( addr len -- flag )\n name_buffer .len @ over <= if 2drop false exit then\n name_buffer .len @ over - name_buffer .addr @ +\n over compare 0=\n;\n\n: loader_conf_files?\n s\" loader_conf_files\" assignment_type?\n;\n\n: nextboot_flag?\n s\" nextboot_enable\" assignment_type?\n;\n\n: nextboot_conf?\n s\" nextboot_conf\" assignment_type?\n;\n\n: verbose_flag?\n s\" verbose_loading\" assignment_type?\n;\n\n: execute?\n s\" exec\" assignment_type?\n;\n\n: password?\n s\" password\" assignment_type?\n;\n\n: module_load?\n load_module_suffix suffix_type?\n;\n\n: module_loadname?\n module_loadname_suffix suffix_type?\n;\n\n: module_type?\n module_type_suffix suffix_type?\n;\n\n: module_args?\n module_args_suffix suffix_type?\n;\n\n: module_beforeload?\n module_beforeload_suffix suffix_type?\n;\n\n: module_afterload?\n module_afterload_suffix suffix_type?\n;\n\n: module_loaderror?\n module_loaderror_suffix suffix_type?\n;\n\n: set_conf_files\n conf_files .addr @ ?dup if\n free-memory\n then\n value_buffer .addr @ c@ [char] \" = if\n value_buffer .addr @ char+ value_buffer .len @ 2 chars -\n else\n value_buffer .addr @ value_buffer .len @\n then\n strdup\n conf_files .len ! conf_files .addr !\n;\n\n: set_nextboot_conf\n nextboot_conf_file .addr @ ?dup if\n free-memory\n then\n value_buffer .addr @ c@ [char] \" = if\n value_buffer .addr @ char+ value_buffer .len @ 2 chars -\n else\n value_buffer .addr @ value_buffer .len @\n then\n strdup\n nextboot_conf_file .len ! nextboot_conf_file .addr !\n;\n\n: append_to_module_options_list ( addr -- )\n module_options @ 0= if\n dup module_options !\n last_module_option !\n else\n dup last_module_option @ module.next !\n last_module_option !\n then\n;\n\n: set_module_name ( addr -- )\n name_buffer .addr @ name_buffer .len @\n strdup\n >r over module.name .addr !\n r> swap module.name .len !\n;\n\n: yes_value?\n value_buffer .addr @ value_buffer .len @\n 2dup s' \"YES\"' compare >r\n 2dup s' \"yes\"' compare >r\n 2dup s\" YES\" compare >r\n s\" yes\" compare r> r> r> and and and 0=\n;\n\n: find_module_option ( -- addr | 0 )\n module_options @\n begin\n dup\n while\n dup module.name dup .addr @ swap .len @\n name_buffer .addr @ name_buffer .len @\n compare 0= if exit then\n module.next @\n repeat\n;\n\n: new_module_option ( -- addr )\n sizeof module allocate if out_of_memory throw then\n dup sizeof module erase\n dup append_to_module_options_list\n dup set_module_name\n;\n\n: get_module_option ( -- addr )\n find_module_option\n ?dup 0= if new_module_option then\n;\n\n: set_module_flag\n name_buffer .len @ load_module_suffix nip - name_buffer .len !\n yes_value? get_module_option module.flag !\n;\n\n: set_module_args\n name_buffer .len @ module_args_suffix nip - name_buffer .len !\n get_module_option module.args\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_loadname\n name_buffer .len @ module_loadname_suffix nip - name_buffer .len !\n get_module_option module.loadname\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_type\n name_buffer .len @ module_type_suffix nip - name_buffer .len !\n get_module_option module.type\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_beforeload\n name_buffer .len @ module_beforeload_suffix nip - name_buffer .len !\n get_module_option module.beforeload\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_afterload\n name_buffer .len @ module_afterload_suffix nip - name_buffer .len !\n get_module_option module.afterload\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_loaderror\n name_buffer .len @ module_loaderror_suffix nip - name_buffer .len !\n get_module_option module.loaderror\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_environment_variable\n name_buffer .len @\n value_buffer .len @ +\n 5 chars +\n allocate if out_of_memory throw then\n dup 0 ( addr -- addr addr len )\n s\" set \" strcat\n name_buffer .addr @ name_buffer .len @ strcat\n s\" =\" strcat\n value_buffer .addr @ value_buffer .len @ strcat\n ['] evaluate catch if\n 2drop free drop\n set_error throw\n else\n free-memory\n then\n;\n\n: set_nextboot_flag\n yes_value? to nextboot?\n;\n\n: set_verbose\n yes_value? to verbose?\n;\n\n: execute_command\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 - swap char+ swap\n then\n ['] evaluate catch if exec_error throw then\n;\n\n: set_password\n password .addr @ ?dup if free if free_error throw then then\n value_buffer .addr @ c@ [char] \" = if\n value_buffer .addr @ char+ value_buffer .len @ 2 - strdup\n value_buffer .addr @ free if free_error throw then\n else\n value_buffer .addr @ value_buffer .len @\n then\n password .len ! password .addr !\n 0 value_buffer .addr !\n;\n\n: process_assignment\n name_buffer .len @ 0= if exit then\n loader_conf_files?\tif set_conf_files exit then\n nextboot_flag?\tif set_nextboot_flag exit then\n nextboot_conf?\tif set_nextboot_conf exit then\n verbose_flag?\t\tif set_verbose exit then\n execute?\t\tif execute_command exit then\n password?\t\tif set_password exit then\n module_load?\t\tif set_module_flag exit then\n module_loadname?\tif set_module_loadname exit then\n module_type?\t\tif set_module_type exit then\n module_args?\t\tif set_module_args exit then\n module_beforeload?\tif set_module_beforeload exit then\n module_afterload?\tif set_module_afterload exit then\n module_loaderror?\tif set_module_loaderror exit then\n set_environment_variable\n;\n\n\\ free_buffer ( -- )\n\\\n\\ Free some pointers if needed. The code then tests for errors\n\\ in freeing, and throws an exception if needed. If a pointer is\n\\ not allocated, it's value (0) is used as flag.\n\n: free_buffers\n name_buffer .addr @ dup if free then\n value_buffer .addr @ dup if free then\n or if free_error throw then\n;\n\n: reset_assignment_buffers\n 0 name_buffer .addr !\n 0 name_buffer .len !\n 0 value_buffer .addr !\n 0 value_buffer .len !\n;\n\n\\ Higher level file processing\n\nsupport-functions definitions\n\n: process_conf\n begin\n end_of_file? 0=\n while\n reset_assignment_buffers\n read_line\n get_assignment\n ['] process_assignment catch\n ['] free_buffers catch\n swap throw throw\n repeat\n;\n\n: peek_file\n 0 to end_of_file?\n reset_line_reading\n O_RDONLY fopen fd !\n fd @ -1 = if open_error throw then\n reset_assignment_buffers\n read_line\n get_assignment\n ['] process_assignment catch\n ['] free_buffers catch\n fd @ fclose\n;\n \nonly forth also support-functions definitions\n\n\\ Interface to loading conf files\n\n: load_conf ( addr len -- )\n 0 to end_of_file?\n reset_line_reading\n O_RDONLY fopen fd !\n fd @ -1 = if open_error throw then\n ['] process_conf catch\n fd @ fclose\n throw\n;\n\n: print_line\n line_buffer .addr @ line_buffer .len @ type cr\n;\n\n: print_syntax_error\n line_buffer .addr @ line_buffer .len @ type cr\n line_buffer .addr @\n begin\n line_pointer over <>\n while\n bl emit\n char+\n repeat\n drop\n .\" ^\" cr\n;\n\n\\ Debugging support functions\n\nonly forth definitions also support-functions\n\n: test-file \n ['] load_conf catch dup .\n syntax_error = if cr print_syntax_error then\n;\n\n: show-module-options\n module_options @\n begin\n ?dup\n while\n .\" Name: \" dup module.name dup .addr @ swap .len @ type cr\n .\" Path: \" dup module.loadname dup .addr @ swap .len @ type cr\n .\" Type: \" dup module.type dup .addr @ swap .len @ type cr\n .\" Flags: \" dup module.args dup .addr @ swap .len @ type cr\n .\" Before load: \" dup module.beforeload dup .addr @ swap .len @ type cr\n .\" After load: \" dup module.afterload dup .addr @ swap .len @ type cr\n .\" Error: \" dup module.loaderror dup .addr @ swap .len @ type cr\n .\" Status: \" dup module.flag @ if .\" Load\" else .\" Don't load\" then cr\n module.next @\n repeat\n;\n\nonly forth also support-functions definitions\n\n\\ Variables used for processing multiple conf files\n\nstring current_file_name\nvariable current_conf_files\n\n\\ Indicates if any conf file was succesfully read\n\n0 value any_conf_read?\n\n\\ loader_conf_files processing support functions\n\n: set_current_conf_files\n conf_files .addr @ current_conf_files !\n;\n\n: get_conf_files\n conf_files .addr @ conf_files .len @ strdup\n;\n\n: recurse_on_conf_files?\n current_conf_files @ conf_files .addr @ <>\n;\n\n: skip_leading_spaces { addr len pos -- addr len pos' }\n begin\n pos len = if addr len pos exit then\n addr pos + c@ bl =\n while\n pos char+ to pos\n repeat\n addr len pos\n;\n\n: get_file_name { addr len pos -- addr len pos' addr' len' || 0 }\n pos len = if \n addr free abort\" Fatal error freeing memory\"\n 0 exit\n then\n pos >r\n begin\n addr pos + c@ bl <>\n while\n pos char+ to pos\n pos len = if\n addr len pos addr r@ + pos r> - exit\n then\n repeat\n addr len pos addr r@ + pos r> -\n;\n\n: get_next_file ( addr len ptr -- addr len ptr' addr' len' | 0 )\n skip_leading_spaces\n get_file_name\n;\n\n: set_current_file_name\n over current_file_name .addr !\n dup current_file_name .len !\n;\n\n: print_current_file\n current_file_name .addr @ current_file_name .len @ type\n;\n\n: process_conf_errors\n dup 0= if true to any_conf_read? drop exit then\n >r 2drop r>\n dup syntax_error = if\n .\" Warning: syntax error on file \" print_current_file cr\n print_syntax_error drop exit\n then\n dup set_error = if\n .\" Warning: bad definition on file \" print_current_file cr\n print_line drop exit\n then\n dup read_error = if\n .\" Warning: error reading file \" print_current_file cr drop exit\n then\n dup open_error = if\n verbose? if .\" Warning: unable to open file \" print_current_file cr then\n drop exit\n then\n dup free_error = abort\" Fatal error freeing memory\"\n dup out_of_memory = abort\" Out of memory\"\n throw \\ Unknown error -- pass ahead\n;\n\n\\ Process loader_conf_files recursively\n\\ Interface to loader_conf_files processing\n\n: include_conf_files\n set_current_conf_files\n get_conf_files 0\n begin\n get_next_file ?dup\n while\n set_current_file_name\n ['] load_conf catch\n process_conf_errors\n recurse_on_conf_files? if recurse then\n repeat\n;\n\n: get_nextboot_conf_file ( -- addr len )\n nextboot_conf_file .addr @ nextboot_conf_file .len @ strdup\n;\n\n: rewrite_nextboot_file ( -- )\n get_nextboot_conf_file\n O_WRONLY fopen fd !\n fd @ -1 = if open_error throw then\n fd @ s' nextboot_enable=\"NO\" ' fwrite\n fd @ fclose\n;\n\n: include_nextboot_file\n get_nextboot_conf_file\n ['] peek_file catch\n nextboot? if\n get_nextboot_conf_file\n ['] load_conf catch\n process_conf_errors\n ['] rewrite_nextboot_file catch\n then\n;\n\n\\ Module loading functions\n\n: load_module?\n module.flag @\n;\n\n: load_parameters ( addr -- addr addrN lenN ... addr1 len1 N )\n dup >r\n r@ module.args .addr @ r@ module.args .len @\n r@ module.loadname .len @ if\n r@ module.loadname .addr @ r@ module.loadname .len @\n else\n r@ module.name .addr @ r@ module.name .len @\n then\n r@ module.type .len @ if\n r@ module.type .addr @ r@ module.type .len @\n s\" -t \"\n 4 ( -t type name flags )\n else\n 2 ( name flags )\n then\n r> drop\n;\n\n: before_load ( addr -- addr )\n dup module.beforeload .len @ if\n dup module.beforeload .addr @ over module.beforeload .len @\n ['] evaluate catch if before_load_error throw then\n then\n;\n\n: after_load ( addr -- addr )\n dup module.afterload .len @ if\n dup module.afterload .addr @ over module.afterload .len @\n ['] evaluate catch if after_load_error throw then\n then\n;\n\n: load_error ( addr -- addr )\n dup module.loaderror .len @ if\n dup module.loaderror .addr @ over module.loaderror .len @\n evaluate \\ This we do not intercept so it can throw errors\n then\n;\n\n: pre_load_message ( addr -- addr )\n verbose? if\n dup module.name .addr @ over module.name .len @ type\n .\" ...\"\n then\n;\n\n: load_error_message verbose? if .\" failed!\" cr then ;\n\n: load_succesful_message verbose? if .\" ok\" cr then ;\n\n: load_module\n load_parameters load\n;\n\n: process_module ( addr -- addr )\n pre_load_message\n before_load\n begin\n ['] load_module catch if\n dup module.loaderror .len @ if\n load_error\t\t\t\\ Command should return a flag!\n else \n load_error_message true\t\t\\ Do not retry\n then\n else\n after_load\n load_succesful_message true\t\\ Succesful, do not retry\n then\n until\n;\n\n: process_module_errors ( addr ior -- )\n dup before_load_error = if\n drop\n .\" Module \"\n dup module.name .addr @ over module.name .len @ type\n dup module.loadname .len @ if\n .\" (\" dup module.loadname .addr @ over module.loadname .len @ type .\" )\"\n then\n cr\n .\" Error executing \"\n dup module.beforeload .addr @ over module.afterload .len @ type cr\n abort\n then\n\n dup after_load_error = if\n drop\n .\" Module \"\n dup module.name .addr @ over module.name .len @ type\n dup module.loadname .len @ if\n .\" (\" dup module.loadname .addr @ over module.loadname .len @ type .\" )\"\n then\n cr\n .\" Error executing \"\n dup module.afterload .addr @ over module.afterload .len @ type cr\n abort\n then\n\n throw \\ Don't know what it is all about -- pass ahead\n;\n\n\\ Module loading interface\n\n: load_modules ( -- ) ( throws: abort & user-defined )\n module_options @\n begin\n ?dup\n while\n dup load_module? if\n ['] process_module catch\n process_module_errors\n then\n module.next @\n repeat\n;\n\n\\ h00h00 magic used to try loading either a kernel with a given name,\n\\ or a kernel with the default name in a directory of a given name\n\\ (the pain!)\n\n: bootpath s\" \/boot\/\" ;\n: modulepath s\" module_path\" ;\n\n\\ Functions used to save and restore module_path's value.\n: saveenv ( addr len | -1 -- addr' len | 0 -1 )\n dup -1 = if 0 swap exit then\n strdup\n;\n: freeenv ( addr len | 0 -1 )\n -1 = if drop else free abort\" Freeing error\" then\n;\n: restoreenv ( addr len | 0 -1 -- )\n dup -1 = if ( it wasn't set )\n 2drop\n modulepath unsetenv\n else\n over >r\n modulepath setenv\n r> free abort\" Freeing error\"\n then\n;\n\n: clip_args \\ Drop second string if only one argument is passed\n 1 = if\n 2swap 2drop\n 1\n else\n 2\n then\n;\n\nalso builtins\n\n\\ Parse filename from a comma-separated list\n\n: parse-; ( addr len -- addr' len-x addr x )\n over 0 2swap\n begin\n dup 0 <>\n while\n over c@ [char] ; <>\n while\n 1- swap 1+ swap\n 2swap 1+ 2swap\n repeat then\n dup 0 <> if\n 1- swap 1+ swap\n then\n 2swap\n;\n\n\\ Try loading one of multiple kernels specified\n\n: try_multiple_kernels ( addr len addr' len' args -- flag )\n >r\n begin\n parse-; 2>r\n 2over 2r>\n r@ clip_args\n s\" DEBUG\" getenv? if\n s\" echo Module_path: ${module_path}\" evaluate\n .\" Kernel : \" >r 2dup type r> cr\n dup 2 = if .\" Flags : \" >r 2over type r> cr then\n then\n 1 load\n while\n dup 0=\n until\n 1 >r \\ Failure\n else\n 0 >r \\ Success\n then\n 2drop 2drop\n r>\n r> drop\n;\n\n\\ Try to load a kernel; the kernel name is taken from one of\n\\ the following lists, as ordered:\n\\\n\\ 1. The \"bootfile\" environment variable\n\\ 2. The \"kernel\" environment variable\n\\\n\\ Flags are passed, if available. If not, dummy values must be given.\n\\\n\\ The kernel gets loaded from the current module_path.\n\n: load_a_kernel ( flags len 1 | x x 0 -- flag )\n local args\n 2local flags\n 0 0 2local kernel\n end-locals\n\n \\ Check if a default kernel name exists at all, exits if not\n s\" bootfile\" getenv dup -1 <> if\n to kernel\n flags kernel args 1+ try_multiple_kernels\n dup 0= if exit then\n then\n drop\n\n s\" kernel\" getenv dup -1 <> if\n to kernel\n else\n drop\n 1 exit \\ Failure\n then\n\n \\ Try all default kernel names\n flags kernel args 1+ try_multiple_kernels\n;\n\n\\ Try to load a kernel; the kernel name is taken from one of\n\\ the following lists, as ordered:\n\\\n\\ 1. The \"bootfile\" environment variable\n\\ 2. The \"kernel\" environment variable\n\\\n\\ Flags are passed, if provided.\n\\\n\\ The kernel will be loaded from a directory computed from the\n\\ path given. Two directories will be tried in the following order:\n\\\n\\ 1. \/boot\/path\n\\ 2. path\n\\\n\\ The module_path variable is overridden if load is succesful, by\n\\ prepending the successful path.\n\n: load_from_directory ( path len 1 | flags len' path len 2 -- flag )\n local args\n 2local path\n args 1 = if 0 0 then\n 2local flags\n 0 0 2local oldmodulepath\n 0 0 2local newmodulepath\n end-locals\n\n \\ Set the environment variable module_path, and try loading\n \\ the kernel again.\n modulepath getenv saveenv to oldmodulepath\n\n \\ Try prepending \/boot\/ first\n bootpath nip path nip + \n oldmodulepath nip dup -1 = if\n drop\n else\n 1+ +\n then\n allocate\n if ( out of memory )\n 1 exit\n then\n\n 0\n bootpath strcat\n path strcat\n 2dup to newmodulepath\n modulepath setenv\n\n \\ Try all default kernel names\n flags args 1- load_a_kernel\n 0= if ( success )\n oldmodulepath nip -1 <> if\n newmodulepath s\" ;\" strcat\n oldmodulepath strcat\n modulepath setenv\n newmodulepath drop free-memory\n oldmodulepath drop free-memory\n then\n 0 exit\n then\n\n \\ Well, try without the prepended \/boot\/\n path newmodulepath drop swap move\n newmodulepath drop path nip\n 2dup to newmodulepath\n modulepath setenv\n\n \\ Try all default kernel names\n flags args 1- load_a_kernel\n if ( failed once more )\n oldmodulepath restoreenv\n newmodulepath drop free-memory\n 1\n else\n oldmodulepath nip -1 <> if\n newmodulepath s\" ;\" strcat\n oldmodulepath strcat\n modulepath setenv\n newmodulepath drop free-memory\n oldmodulepath drop free-memory\n then\n 0\n then\n;\n\n\\ Try to load a kernel; the kernel name is taken from one of\n\\ the following lists, as ordered:\n\\\n\\ 1. The \"bootfile\" environment variable\n\\ 2. The \"kernel\" environment variable\n\\ 3. The \"path\" argument\n\\\n\\ Flags are passed, if provided.\n\\\n\\ The kernel will be loaded from a directory computed from the\n\\ path given. Two directories will be tried in the following order:\n\\\n\\ 1. \/boot\/path\n\\ 2. path\n\\\n\\ Unless \"path\" is meant to be kernel name itself. In that case, it\n\\ will first be tried as a full path, and, next, search on the\n\\ directories pointed by module_path.\n\\\n\\ The module_path variable is overridden if load is succesful, by\n\\ prepending the successful path.\n\n: load_directory_or_file ( path len 1 | flags len' path len 2 -- flag )\n local args\n 2local path\n args 1 = if 0 0 then\n 2local flags\n end-locals\n\n \\ First, assume path is an absolute path to a directory\n flags path args clip_args load_from_directory\n dup 0= if exit else drop then\n\n \\ Next, assume path points to the kernel\n flags path args try_multiple_kernels\n;\n\n: initialize ( addr len -- )\n strdup conf_files .len ! conf_files .addr !\n;\n\n: kernel_options ( -- addr len 1 | 0 )\n s\" kernel_options\" getenv\n dup -1 = if drop 0 else 1 then\n;\n\n: standard_kernel_search ( flags 1 | 0 -- flag )\n local args\n args 0= if 0 0 then\n 2local flags\n s\" kernel\" getenv\n dup -1 = if 0 swap then\n 2local path\n end-locals\n\n path nip -1 = if ( there isn't a \"kernel\" environment variable )\n flags args load_a_kernel\n else\n flags path args 1+ clip_args load_directory_or_file\n then\n;\n\n: load_kernel ( -- ) ( throws: abort )\n kernel_options standard_kernel_search\n abort\" Unable to load a kernel!\"\n;\n\n: set_defaultoptions ( -- )\n s\" kernel_options\" getenv dup -1 = if\n drop\n else\n s\" temp_options\" setenv\n then\n;\n\n: argv[] ( aN uN ... a1 u1 N i -- aN uN ... a1 u1 N ai+1 ui+1 )\n 2dup = if 0 0 exit then\n dup >r\n 1+ 2* ( skip N and ui )\n pick\n r>\n 1+ 2* ( skip N and ai )\n pick\n;\n\n: drop_args ( aN uN ... a1 u1 N -- )\n 0 ?do 2drop loop\n;\n\n: argc\n dup\n;\n\n: queue_argv ( aN uN ... a1 u1 N a u -- a u aN uN ... a1 u1 N+1 )\n >r\n over 2* 1+ -roll\n r>\n over 2* 1+ -roll\n 1+\n;\n\n: unqueue_argv ( aN uN ... a1 u1 N -- aN uN ... a2 u2 N-1 a1 u1 )\n 1- -rot\n;\n\n: strlen(argv)\n dup 0= if 0 exit then\n 0 >r\t\\ Size\n 0 >r\t\\ Index\n begin\n argc r@ <>\n while\n r@ argv[]\n nip\n r> r> rot + 1+\n >r 1+ >r\n repeat\n r> drop\n r>\n;\n\n: concat_argv ( aN uN ... a1 u1 N -- a u )\n strlen(argv) allocate if out_of_memory throw then\n 0 2>r\n\n begin\n argc\n while\n unqueue_argv\n 2r> 2swap\n strcat\n s\" \" strcat\n 2>r\n repeat\n drop_args\n 2r>\n;\n\n: set_tempoptions ( addrN lenN ... addr1 len1 N -- addr len 1 | 0 )\n \\ Save the first argument, if it exists and is not a flag\n argc if\n 0 argv[] drop c@ [char] - <> if\n unqueue_argv 2>r \\ Filename\n 1 >r\t\t\\ Filename present\n else\n 0 >r\t\t\\ Filename not present\n then\n else\n 0 >r\t\t\\ Filename not present\n then\n\n \\ If there are other arguments, assume they are flags\n ?dup if\n concat_argv\n 2dup s\" temp_options\" setenv\n drop free if free_error throw then\n else\n set_defaultoptions\n then\n\n \\ Bring back the filename, if one was provided\n r> if 2r> 1 else 0 then\n;\n\n: get_arguments ( -- addrN lenN ... addr1 len1 N )\n 0\n begin\n \\ Get next word on the command line\n parse-word\n ?dup while\n queue_argv\n repeat\n drop ( empty string )\n;\n\n: load_kernel_and_modules ( args -- flag )\n set_tempoptions\n argc >r\n s\" temp_options\" getenv dup -1 <> if\n queue_argv\n else\n drop\n then\n r> if ( a path was passed )\n load_directory_or_file\n else\n standard_kernel_search\n then\n ?dup 0= if ['] load_modules catch then\n;\n\n: read-password { size | buf len -- }\n size allocate if out_of_memory throw then\n to buf\n 0 to len\n begin\n key\n dup backspace = if\n drop\n len if\n backspace emit bl emit backspace emit\n len 1 - to len\n else\n bell emit\n then\n else\n dup = if cr drop buf len exit then\n [char] * emit\n len size < if\n buf len chars + c!\n else\n drop\n then\n len 1+ to len\n then\n again\n;\n\n\\ Go back to straight forth vocabulary\n\nonly forth also definitions\n\n","old_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\ \n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\n\\ Loader.rc support functions:\n\\\n\\ initialize_support ( -- )\tinitialize global variables\n\\ initialize ( addr len -- )\tas above, plus load_conf_files\n\\ load_conf ( addr len -- )\tload conf file given\n\\ include_conf_files ( -- )\tload all conf files in load_conf_files\n\\ print_syntax_error ( -- )\tprint line and marker of where a syntax\n\\\t\t\t\terror was detected\n\\ print_line ( -- )\t\tprint last line processed\n\\ load_kernel ( -- )\t\tload kernel\n\\ load_modules ( -- )\t\tload modules flagged\n\\\n\\ Exported structures:\n\\\n\\ string\t\t\tcounted string structure\n\\\tcell .addr\t\t\tstring address\n\\\tcell .len\t\t\tstring length\n\\ module\t\t\tmodule loading information structure\n\\\tcell module.flag\t\tshould we load it?\n\\\tstring module.name\t\tmodule's name\n\\\tstring module.loadname\t\tname to be used in loading the module\n\\\tstring module.type\t\tmodule's type\n\\\tstring module.args\t\tflags to be passed during load\n\\\tstring module.beforeload\tcommand to be executed before load\n\\\tstring module.afterload\t\tcommand to be executed after load\n\\\tstring module.loaderror\t\tcommand to be executed if load fails\n\\\tcell module.next\t\tlist chain\n\\\n\\ Exported global variables;\n\\\n\\ string conf_files\t\tconfiguration files to be loaded\n\\ string password\t\tpassword\n\\ cell modules_options\t\tpointer to first module information\n\\ value verbose?\t\tindicates if user wants a verbose loading\n\\ value any_conf_read?\t\tindicates if a conf file was succesfully read\n\\\n\\ Other exported words:\n\\\n\\ strdup ( addr len -- addr' len)\t\t\tsimilar to strdup(3)\n\\ strcat ( addr len addr' len' -- addr len+len' )\tsimilar to strcat(3)\n\\ strlen ( addr -- len )\t\t\t\tsimilar to strlen(3)\n\\ s' ( | string' -- addr len | )\t\t\tsimilar to s\"\n\\ rudimentary structure support\n\n\\ Exception values\n\n1 constant syntax_error\n2 constant out_of_memory\n3 constant free_error\n4 constant set_error\n5 constant read_error\n6 constant open_error\n7 constant exec_error\n8 constant before_load_error\n9 constant after_load_error\n\n\\ I\/O constants\n\n0 constant SEEK_SET\n1 constant SEEK_CUR\n2 constant SEEK_END\n\n0 constant O_RDONLY\n1 constant O_WRONLY\n2 constant O_RDWR\n\n\\ Crude structure support\n\n: structure:\n create here 0 , ['] drop , 0\n does> create here swap dup @ allot cell+ @ execute\n;\n: member: create dup , over , + does> cell+ @ + ;\n: ;structure swap ! ;\n: constructor! >body cell+ ! ;\n: constructor: over :noname ;\n: ;constructor postpone ; swap cell+ ! ; immediate\n: sizeof ' >body @ state @ if postpone literal then ; immediate\n: offsetof ' >body cell+ @ state @ if postpone literal then ; immediate\n: ptr 1 cells member: ;\n: int 1 cells member: ;\n\n\\ String structure\n\nstructure: string\n\tptr .addr\n\tint .len\n\tconstructor:\n\t 0 over .addr !\n\t 0 swap .len !\n\t;constructor\n;structure\n\n\n\\ Module options linked list\n\nstructure: module\n\tint module.flag\n\tsizeof string member: module.name\n\tsizeof string member: module.loadname\n\tsizeof string member: module.type\n\tsizeof string member: module.args\n\tsizeof string member: module.beforeload\n\tsizeof string member: module.afterload\n\tsizeof string member: module.loaderror\n\tptr module.next\n;structure\n\n\\ Internal loader structures\nstructure: preloaded_file\n\tptr pf.name\n\tptr pf.type\n\tptr pf.args\n\tptr pf.metadata\t\\ file_metadata\n\tint pf.loader\n\tint pf.addr\n\tint pf.size\n\tptr pf.modules\t\\ kernel_module\n\tptr pf.next\t\\ preloaded_file\n;structure\n\nstructure: kernel_module\n\tptr km.name\n\t\\ ptr km.args\n\tptr km.fp\t\\ preloaded_file\n\tptr km.next\t\\ kernel_module\n;structure\n\nstructure: file_metadata\n\tint\t\tmd.size\n\t2 member:\tmd.type\t\\ this is not ANS Forth compatible (XXX)\n\tptr\t\tmd.next\t\\ file_metadata\n\t0 member:\tmd.data\t\\ variable size\n;structure\n\nstructure: config_resource\n\tptr cf.name\n\tint cf.type\n0 constant RES_INT\n1 constant RES_STRING\n2 constant RES_LONG\n\t2 cells member: u\n;structure\n\nstructure: config_device\n\tptr cd.name\n\tint cd.unit\n\tint cd.resource_count\n\tptr cd.resources\t\\ config_resource\n;structure\n\nstructure: STAILQ_HEAD\n\tptr stqh_first\t\\ type*\n\tptr stqh_last\t\\ type**\n;structure\n\nstructure: STAILQ_ENTRY\n\tptr stqe_next\t\\ type*\n;structure\n\nstructure: pnphandler\n\tptr pnph.name\n\tptr pnph.enumerate\n;structure\n\nstructure: pnpident\n\tptr pnpid.ident\t\t\t\t\t\\ char*\n\tsizeof STAILQ_ENTRY cells member: pnpid.link\t\\ pnpident\n;structure\n\nstructure: pnpinfo\n\tptr pnpi.desc\n\tint pnpi.revision\n\tptr pnpi.module\t\t\t\t\\ (char*) module args\n\tint pnpi.argc\n\tptr pnpi.argv\n\tptr pnpi.handler\t\t\t\\ pnphandler\n\tsizeof STAILQ_HEAD member: pnpi.ident\t\\ pnpident\n\tsizeof STAILQ_ENTRY member: pnpi.link\t\\ pnpinfo\n;structure\n\n\\ Global variables\n\nstring conf_files\nstring nextboot_conf_file\nstring password\ncreate module_options sizeof module.next allot 0 module_options !\ncreate last_module_option sizeof module.next allot 0 last_module_option !\n0 value verbose?\n0 value nextboot?\n\n\\ Support string functions\n\n: strdup ( addr len -- addr' len )\n >r r@ allocate if out_of_memory throw then\n tuck r@ move\n r>\n;\n\n: strcat { addr len addr' len' -- addr len+len' }\n addr' addr len + len' move\n addr len len' +\n;\n\n: strlen ( addr -- len )\n 0 >r\n begin\n dup c@ while\n 1+ r> 1+ >r repeat\n drop r>\n;\n\n: s' \n [char] ' parse\n state @ if\n postpone sliteral\n then\n; immediate\n\n: 2>r postpone >r postpone >r ; immediate\n: 2r> postpone r> postpone r> ; immediate\n: 2r@ postpone 2r> postpone 2dup postpone 2>r ; immediate\n\n: getenv?\n getenv\n -1 = if false else drop true then\n;\n\n\\ Private definitions\n\nvocabulary support-functions\nonly forth also support-functions definitions\n\n\\ Some control characters constants\n\n7 constant bell\n8 constant backspace\n9 constant tab\n10 constant lf\n13 constant \n\n\\ Read buffer size\n\n80 constant read_buffer_size\n\n\\ Standard suffixes\n\n: load_module_suffix s\" _load\" ;\n: module_loadname_suffix s\" _name\" ;\n: module_type_suffix s\" _type\" ;\n: module_args_suffix s\" _flags\" ;\n: module_beforeload_suffix s\" _before\" ;\n: module_afterload_suffix s\" _after\" ;\n: module_loaderror_suffix s\" _error\" ;\n\n\\ Support operators\n\n: >= < 0= ;\n: <= > 0= ;\n\n\\ Assorted support funcitons\n\n: free-memory free if free_error throw then ;\n\n\\ Assignment data temporary storage\n\nstring name_buffer\nstring value_buffer\n\n\\ Line by line file reading functions\n\\\n\\ exported:\n\\\tline_buffer\n\\\tend_of_file?\n\\\tfd\n\\\tread_line\n\\\treset_line_reading\n\nvocabulary line-reading\nalso line-reading definitions also\n\n\\ File data temporary storage\n\nstring read_buffer\n0 value read_buffer_ptr\n\n\\ File's line reading function\n\nsupport-functions definitions\n\nstring line_buffer\n0 value end_of_file?\nvariable fd\n\nline-reading definitions\n\n: skip_newlines\n begin\n read_buffer .len @ read_buffer_ptr >\n while\n read_buffer .addr @ read_buffer_ptr + c@ lf = if\n read_buffer_ptr char+ to read_buffer_ptr\n else\n exit\n then\n repeat\n;\n\n: scan_buffer ( -- addr len )\n read_buffer_ptr >r\n begin\n read_buffer .len @ r@ >\n while\n read_buffer .addr @ r@ + c@ lf = if\n read_buffer .addr @ read_buffer_ptr + ( -- addr )\n r@ read_buffer_ptr - ( -- len )\n r> to read_buffer_ptr\n exit\n then\n r> char+ >r\n repeat\n read_buffer .addr @ read_buffer_ptr + ( -- addr )\n r@ read_buffer_ptr - ( -- len )\n r> to read_buffer_ptr\n;\n\n: line_buffer_resize ( len -- len )\n >r\n line_buffer .len @ if\n line_buffer .addr @\n line_buffer .len @ r@ +\n resize if out_of_memory throw then\n else\n r@ allocate if out_of_memory throw then\n then\n line_buffer .addr !\n r>\n;\n \n: append_to_line_buffer ( addr len -- )\n line_buffer .addr @ line_buffer .len @\n 2swap strcat\n line_buffer .len !\n drop\n;\n\n: read_from_buffer\n scan_buffer ( -- addr len )\n line_buffer_resize ( len -- len )\n append_to_line_buffer ( addr len -- )\n;\n\n: refill_required?\n read_buffer .len @ read_buffer_ptr =\n end_of_file? 0= and\n;\n\n: refill_buffer\n 0 to read_buffer_ptr\n read_buffer .addr @ 0= if\n read_buffer_size allocate if out_of_memory throw then\n read_buffer .addr !\n then\n fd @ read_buffer .addr @ read_buffer_size fread\n dup -1 = if read_error throw then\n dup 0= if true to end_of_file? then\n read_buffer .len !\n;\n\n: reset_line_buffer\n line_buffer .addr @ ?dup if\n free-memory\n then\n 0 line_buffer .addr !\n 0 line_buffer .len !\n;\n\nsupport-functions definitions\n\n: reset_line_reading\n 0 to read_buffer_ptr\n;\n\n: read_line\n reset_line_buffer\n skip_newlines\n begin\n read_from_buffer\n refill_required?\n while\n refill_buffer\n repeat\n;\n\nonly forth also support-functions definitions\n\n\\ Conf file line parser:\n\\ ::= '='[] |\n\\ []\n\\ ::= {||'_'}\n\\ ::= '\"'{|'\\'}'\"' | \n\\ ::= ASCII 32 to 126, except '\\' and '\"'\n\\ ::= '#'{}\n\\\n\\ exported:\n\\\tline_pointer\n\\\tprocess_conf\n\n0 value line_pointer\n\nvocabulary file-processing\nalso file-processing definitions\n\n\\ parser functions\n\\\n\\ exported:\n\\\tget_assignment\n\nvocabulary parser\nalso parser definitions also\n\n0 value parsing_function\n0 value end_of_line\n\n: end_of_line?\n line_pointer end_of_line =\n;\n\n: letter?\n line_pointer c@ >r\n r@ [char] A >=\n r@ [char] Z <= and\n r@ [char] a >=\n r> [char] z <= and\n or\n;\n\n: digit?\n line_pointer c@ >r\n r@ [char] 0 >=\n r> [char] 9 <= and\n;\n\n: quote?\n line_pointer c@ [char] \" =\n;\n\n: assignment_sign?\n line_pointer c@ [char] = =\n;\n\n: comment?\n line_pointer c@ [char] # =\n;\n\n: space?\n line_pointer c@ bl =\n line_pointer c@ tab = or\n;\n\n: backslash?\n line_pointer c@ [char] \\ =\n;\n\n: underscore?\n line_pointer c@ [char] _ =\n;\n\n: dot?\n line_pointer c@ [char] . =\n;\n\n: skip_character\n line_pointer char+ to line_pointer\n;\n\n: skip_to_end_of_line\n end_of_line to line_pointer\n;\n\n: eat_space\n begin\n space?\n while\n skip_character\n end_of_line? if exit then\n repeat\n;\n\n: parse_name ( -- addr len )\n line_pointer\n begin\n letter? digit? underscore? dot? or or or\n while\n skip_character\n end_of_line? if \n line_pointer over -\n strdup\n exit\n then\n repeat\n line_pointer over -\n strdup\n;\n\n: remove_backslashes { addr len | addr' len' -- addr' len' }\n len allocate if out_of_memory throw then\n to addr'\n addr >r\n begin\n addr c@ [char] \\ <> if\n addr c@ addr' len' + c!\n len' char+ to len'\n then\n addr char+ to addr\n r@ len + addr =\n until\n r> drop\n addr' len'\n;\n\n: parse_quote ( -- addr len )\n line_pointer\n skip_character\n end_of_line? if syntax_error throw then\n begin\n quote? 0=\n while\n backslash? if\n skip_character\n end_of_line? if syntax_error throw then\n then\n skip_character\n end_of_line? if syntax_error throw then \n repeat\n skip_character\n line_pointer over -\n remove_backslashes\n;\n\n: read_name\n parse_name\t\t( -- addr len )\n name_buffer .len !\n name_buffer .addr !\n;\n\n: read_value\n quote? if\n parse_quote\t\t( -- addr len )\n else\n parse_name\t\t( -- addr len )\n then\n value_buffer .len !\n value_buffer .addr !\n;\n\n: comment\n skip_to_end_of_line\n;\n\n: white_space_4\n eat_space\n comment? if ['] comment to parsing_function exit then\n end_of_line? 0= if syntax_error throw then\n;\n\n: variable_value\n read_value\n ['] white_space_4 to parsing_function\n;\n\n: white_space_3\n eat_space\n letter? digit? quote? or or if\n ['] variable_value to parsing_function exit\n then\n syntax_error throw\n;\n\n: assignment_sign\n skip_character\n ['] white_space_3 to parsing_function\n;\n\n: white_space_2\n eat_space\n assignment_sign? if ['] assignment_sign to parsing_function exit then\n syntax_error throw\n;\n\n: variable_name\n read_name\n ['] white_space_2 to parsing_function\n;\n\n: white_space_1\n eat_space\n letter? if ['] variable_name to parsing_function exit then\n comment? if ['] comment to parsing_function exit then\n end_of_line? 0= if syntax_error throw then\n;\n\nfile-processing definitions\n\n: get_assignment\n line_buffer .addr @ line_buffer .len @ + to end_of_line\n line_buffer .addr @ to line_pointer\n ['] white_space_1 to parsing_function\n begin\n end_of_line? 0=\n while\n parsing_function execute\n repeat\n parsing_function ['] comment =\n parsing_function ['] white_space_1 =\n parsing_function ['] white_space_4 =\n or or 0= if syntax_error throw then\n;\n\nonly forth also support-functions also file-processing definitions also\n\n\\ Process line\n\n: assignment_type? ( addr len -- flag )\n name_buffer .addr @ name_buffer .len @\n compare 0=\n;\n\n: suffix_type? ( addr len -- flag )\n name_buffer .len @ over <= if 2drop false exit then\n name_buffer .len @ over - name_buffer .addr @ +\n over compare 0=\n;\n\n: loader_conf_files?\n s\" loader_conf_files\" assignment_type?\n;\n\n: nextboot_flag?\n s\" nextboot_enable\" assignment_type?\n;\n\n: nextboot_conf?\n s\" nextboot_conf\" assignment_type?\n;\n\n: verbose_flag?\n s\" verbose_loading\" assignment_type?\n;\n\n: execute?\n s\" exec\" assignment_type?\n;\n\n: password?\n s\" password\" assignment_type?\n;\n\n: module_load?\n load_module_suffix suffix_type?\n;\n\n: module_loadname?\n module_loadname_suffix suffix_type?\n;\n\n: module_type?\n module_type_suffix suffix_type?\n;\n\n: module_args?\n module_args_suffix suffix_type?\n;\n\n: module_beforeload?\n module_beforeload_suffix suffix_type?\n;\n\n: module_afterload?\n module_afterload_suffix suffix_type?\n;\n\n: module_loaderror?\n module_loaderror_suffix suffix_type?\n;\n\n: set_conf_files\n conf_files .addr @ ?dup if\n free-memory\n then\n value_buffer .addr @ c@ [char] \" = if\n value_buffer .addr @ char+ value_buffer .len @ 2 chars -\n else\n value_buffer .addr @ value_buffer .len @\n then\n strdup\n conf_files .len ! conf_files .addr !\n;\n\n: set_nextboot_conf\n nextboot_conf_file .addr @ ?dup if\n free-memory\n then\n value_buffer .addr @ c@ [char] \" = if\n value_buffer .addr @ char+ value_buffer .len @ 2 chars -\n else\n value_buffer .addr @ value_buffer .len @\n then\n strdup\n nextboot_conf_file .len ! nextboot_conf_file .addr !\n;\n\n: append_to_module_options_list ( addr -- )\n module_options @ 0= if\n dup module_options !\n last_module_option !\n else\n dup last_module_option @ module.next !\n last_module_option !\n then\n;\n\n: set_module_name ( addr -- )\n name_buffer .addr @ name_buffer .len @\n strdup\n >r over module.name .addr !\n r> swap module.name .len !\n;\n\n: yes_value?\n value_buffer .addr @ value_buffer .len @\n 2dup s' \"YES\"' compare >r\n 2dup s' \"yes\"' compare >r\n 2dup s\" YES\" compare >r\n s\" yes\" compare r> r> r> and and and 0=\n;\n\n: find_module_option ( -- addr | 0 )\n module_options @\n begin\n dup\n while\n dup module.name dup .addr @ swap .len @\n name_buffer .addr @ name_buffer .len @\n compare 0= if exit then\n module.next @\n repeat\n;\n\n: new_module_option ( -- addr )\n sizeof module allocate if out_of_memory throw then\n dup sizeof module erase\n dup append_to_module_options_list\n dup set_module_name\n;\n\n: get_module_option ( -- addr )\n find_module_option\n ?dup 0= if new_module_option then\n;\n\n: set_module_flag\n name_buffer .len @ load_module_suffix nip - name_buffer .len !\n yes_value? get_module_option module.flag !\n;\n\n: set_module_args\n name_buffer .len @ module_args_suffix nip - name_buffer .len !\n get_module_option module.args\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_loadname\n name_buffer .len @ module_loadname_suffix nip - name_buffer .len !\n get_module_option module.loadname\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_type\n name_buffer .len @ module_type_suffix nip - name_buffer .len !\n get_module_option module.type\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_beforeload\n name_buffer .len @ module_beforeload_suffix nip - name_buffer .len !\n get_module_option module.beforeload\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_afterload\n name_buffer .len @ module_afterload_suffix nip - name_buffer .len !\n get_module_option module.afterload\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_loaderror\n name_buffer .len @ module_loaderror_suffix nip - name_buffer .len !\n get_module_option module.loaderror\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_environment_variable\n name_buffer .len @\n value_buffer .len @ +\n 5 chars +\n allocate if out_of_memory throw then\n dup 0 ( addr -- addr addr len )\n s\" set \" strcat\n name_buffer .addr @ name_buffer .len @ strcat\n s\" =\" strcat\n value_buffer .addr @ value_buffer .len @ strcat\n ['] evaluate catch if\n 2drop free drop\n set_error throw\n else\n free-memory\n then\n;\n\n: set_nextboot_flag\n yes_value? to nextboot?\n;\n\n: set_verbose\n yes_value? to verbose?\n;\n\n: execute_command\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 - swap char+ swap\n then\n ['] evaluate catch if exec_error throw then\n;\n\n: set_password\n password .addr @ ?dup if free if free_error throw then then\n value_buffer .addr @ c@ [char] \" = if\n value_buffer .addr @ char+ value_buffer .len @ 2 - strdup\n value_buffer .addr @ free if free_error throw then\n else\n value_buffer .addr @ value_buffer .len @\n then\n password .len ! password .addr !\n 0 value_buffer .addr !\n;\n\n: process_assignment\n name_buffer .len @ 0= if exit then\n loader_conf_files?\tif set_conf_files exit then\n nextboot_flag?\tif set_nextboot_flag exit then\n nextboot_conf?\tif set_nextboot_conf exit then\n verbose_flag?\t\tif set_verbose exit then\n execute?\t\tif execute_command exit then\n password?\t\tif set_password exit then\n module_load?\t\tif set_module_flag exit then\n module_loadname?\tif set_module_loadname exit then\n module_type?\t\tif set_module_type exit then\n module_args?\t\tif set_module_args exit then\n module_beforeload?\tif set_module_beforeload exit then\n module_afterload?\tif set_module_afterload exit then\n module_loaderror?\tif set_module_loaderror exit then\n set_environment_variable\n;\n\n\\ free_buffer ( -- )\n\\\n\\ Free some pointers if needed. The code then tests for errors\n\\ in freeing, and throws an exception if needed. If a pointer is\n\\ not allocated, it's value (0) is used as flag.\n\n: free_buffers\n name_buffer .addr @ dup if free then\n value_buffer .addr @ dup if free then\n or if free_error throw then\n;\n\n: reset_assignment_buffers\n 0 name_buffer .addr !\n 0 name_buffer .len !\n 0 value_buffer .addr !\n 0 value_buffer .len !\n;\n\n\\ Higher level file processing\n\nsupport-functions definitions\n\n: process_conf\n begin\n end_of_file? 0=\n while\n reset_assignment_buffers\n read_line\n get_assignment\n ['] process_assignment catch\n ['] free_buffers catch\n swap throw throw\n repeat\n;\n\n: peek_file\n 0 to end_of_file?\n reset_line_reading\n O_RDONLY fopen fd !\n fd @ -1 = if open_error throw then\n reset_assignment_buffers\n read_line\n get_assignment\n ['] process_assignment catch\n ['] free_buffers catch\n fd @ fclose\n;\n \nonly forth also support-functions definitions\n\n\\ Interface to loading conf files\n\n: load_conf ( addr len -- )\n 0 to end_of_file?\n reset_line_reading\n O_RDONLY fopen fd !\n fd @ -1 = if open_error throw then\n ['] process_conf catch\n fd @ fclose\n throw\n;\n\n: print_line\n line_buffer .addr @ line_buffer .len @ type cr\n;\n\n: print_syntax_error\n line_buffer .addr @ line_buffer .len @ type cr\n line_buffer .addr @\n begin\n line_pointer over <>\n while\n bl emit\n char+\n repeat\n drop\n .\" ^\" cr\n;\n\n\\ Debugging support functions\n\nonly forth definitions also support-functions\n\n: test-file \n ['] load_conf catch dup .\n syntax_error = if cr print_syntax_error then\n;\n\n: show-module-options\n module_options @\n begin\n ?dup\n while\n .\" Name: \" dup module.name dup .addr @ swap .len @ type cr\n .\" Path: \" dup module.loadname dup .addr @ swap .len @ type cr\n .\" Type: \" dup module.type dup .addr @ swap .len @ type cr\n .\" Flags: \" dup module.args dup .addr @ swap .len @ type cr\n .\" Before load: \" dup module.beforeload dup .addr @ swap .len @ type cr\n .\" After load: \" dup module.afterload dup .addr @ swap .len @ type cr\n .\" Error: \" dup module.loaderror dup .addr @ swap .len @ type cr\n .\" Status: \" dup module.flag @ if .\" Load\" else .\" Don't load\" then cr\n module.next @\n repeat\n;\n\nonly forth also support-functions definitions\n\n\\ Variables used for processing multiple conf files\n\nstring current_file_name\nvariable current_conf_files\n\n\\ Indicates if any conf file was succesfully read\n\n0 value any_conf_read?\n\n\\ loader_conf_files processing support functions\n\n: set_current_conf_files\n conf_files .addr @ current_conf_files !\n;\n\n: get_conf_files\n conf_files .addr @ conf_files .len @ strdup\n;\n\n: recurse_on_conf_files?\n current_conf_files @ conf_files .addr @ <>\n;\n\n: skip_leading_spaces { addr len pos -- addr len pos' }\n begin\n pos len = if addr len pos exit then\n addr pos + c@ bl =\n while\n pos char+ to pos\n repeat\n addr len pos\n;\n\n: get_file_name { addr len pos -- addr len pos' addr' len' || 0 }\n pos len = if \n addr free abort\" Fatal error freeing memory\"\n 0 exit\n then\n pos >r\n begin\n addr pos + c@ bl <>\n while\n pos char+ to pos\n pos len = if\n addr len pos addr r@ + pos r> - exit\n then\n repeat\n addr len pos addr r@ + pos r> -\n;\n\n: get_next_file ( addr len ptr -- addr len ptr' addr' len' | 0 )\n skip_leading_spaces\n get_file_name\n;\n\n: set_current_file_name\n over current_file_name .addr !\n dup current_file_name .len !\n;\n\n: print_current_file\n current_file_name .addr @ current_file_name .len @ type\n;\n\n: process_conf_errors\n dup 0= if true to any_conf_read? drop exit then\n >r 2drop r>\n dup syntax_error = if\n .\" Warning: syntax error on file \" print_current_file cr\n print_syntax_error drop exit\n then\n dup set_error = if\n .\" Warning: bad definition on file \" print_current_file cr\n print_line drop exit\n then\n dup read_error = if\n .\" Warning: error reading file \" print_current_file cr drop exit\n then\n dup open_error = if\n verbose? if .\" Warning: unable to open file \" print_current_file cr then\n drop exit\n then\n dup free_error = abort\" Fatal error freeing memory\"\n dup out_of_memory = abort\" Out of memory\"\n throw \\ Unknown error -- pass ahead\n;\n\n\\ Process loader_conf_files recursively\n\\ Interface to loader_conf_files processing\n\n: include_conf_files\n set_current_conf_files\n get_conf_files 0\n begin\n get_next_file ?dup\n while\n set_current_file_name\n ['] load_conf catch\n process_conf_errors\n recurse_on_conf_files? if recurse then\n repeat\n;\n\n: get_nextboot_conf_file ( -- addr len )\n nextboot_conf_file .addr @ nextboot_conf_file .len @ strdup\n;\n\n: rewrite_nextboot_file ( -- )\n get_nextboot_conf_file\n O_WRONLY fopen fd !\n fd @ -1 = if open_error throw then\n fd @ s' nextboot_enable=\"NO\" ' fwrite\n fd @ fclose\n;\n\n: include_nextboot_file\n get_nextboot_conf_file\n ['] peek_file catch\n nextboot? if\n get_nextboot_conf_file\n ['] load_conf catch\n process_conf_errors\n ['] rewrite_nextboot_file catch\n then\n;\n\n\\ Module loading functions\n\n: load_module?\n module.flag @\n;\n\n: load_parameters ( addr -- addr addrN lenN ... addr1 len1 N )\n dup >r\n r@ module.args .addr @ r@ module.args .len @\n r@ module.loadname .len @ if\n r@ module.loadname .addr @ r@ module.loadname .len @\n else\n r@ module.name .addr @ r@ module.name .len @\n then\n r@ module.type .len @ if\n r@ module.type .addr @ r@ module.type .len @\n s\" -t \"\n 4 ( -t type name flags )\n else\n 2 ( name flags )\n then\n r> drop\n;\n\n: before_load ( addr -- addr )\n dup module.beforeload .len @ if\n dup module.beforeload .addr @ over module.beforeload .len @\n ['] evaluate catch if before_load_error throw then\n then\n;\n\n: after_load ( addr -- addr )\n dup module.afterload .len @ if\n dup module.afterload .addr @ over module.afterload .len @\n ['] evaluate catch if after_load_error throw then\n then\n;\n\n: load_error ( addr -- addr )\n dup module.loaderror .len @ if\n dup module.loaderror .addr @ over module.loaderror .len @\n evaluate \\ This we do not intercept so it can throw errors\n then\n;\n\n: pre_load_message ( addr -- addr )\n verbose? if\n dup module.name .addr @ over module.name .len @ type\n .\" ...\"\n then\n;\n\n: load_error_message verbose? if .\" failed!\" cr then ;\n\n: load_succesful_message verbose? if .\" ok\" cr then ;\n\n: load_module\n load_parameters load\n;\n\n: process_module ( addr -- addr )\n pre_load_message\n before_load\n begin\n ['] load_module catch if\n dup module.loaderror .len @ if\n load_error\t\t\t\\ Command should return a flag!\n else \n load_error_message true\t\t\\ Do not retry\n then\n else\n after_load\n load_succesful_message true\t\\ Succesful, do not retry\n then\n until\n;\n\n: process_module_errors ( addr ior -- )\n dup before_load_error = if\n drop\n .\" Module \"\n dup module.name .addr @ over module.name .len @ type\n dup module.loadname .len @ if\n .\" (\" dup module.loadname .addr @ over module.loadname .len @ type .\" )\"\n then\n cr\n .\" Error executing \"\n dup module.beforeload .addr @ over module.afterload .len @ type cr\n abort\n then\n\n dup after_load_error = if\n drop\n .\" Module \"\n dup module.name .addr @ over module.name .len @ type\n dup module.loadname .len @ if\n .\" (\" dup module.loadname .addr @ over module.loadname .len @ type .\" )\"\n then\n cr\n .\" Error executing \"\n dup module.afterload .addr @ over module.afterload .len @ type cr\n abort\n then\n\n throw \\ Don't know what it is all about -- pass ahead\n;\n\n\\ Module loading interface\n\n: load_modules ( -- ) ( throws: abort & user-defined )\n module_options @\n begin\n ?dup\n while\n dup load_module? if\n ['] process_module catch\n process_module_errors\n then\n module.next @\n repeat\n;\n\n\\ h00h00 magic used to try loading either a kernel with a given name,\n\\ or a kernel with the default name in a directory of a given name\n\\ (the pain!)\n\n: bootpath s\" \/boot\/\" ;\n: modulepath s\" module_path\" ;\n\n\\ Functions used to save and restore module_path's value.\n: saveenv ( addr len | -1 -- addr' len | 0 -1 )\n dup -1 = if 0 swap exit then\n strdup\n;\n: freeenv ( addr len | 0 -1 )\n -1 = if drop else free abort\" Freeing error\" then\n;\n: restoreenv ( addr len | 0 -1 -- )\n dup -1 = if ( it wasn't set )\n 2drop\n modulepath unsetenv\n else\n over >r\n modulepath setenv\n r> free abort\" Freeing error\"\n then\n;\n\n: clip_args \\ Drop second string if only one argument is passed\n 1 = if\n 2swap 2drop\n 1\n else\n 2\n then\n;\n\nalso builtins\n\n\\ Parse filename from a comma-separated list\n\n: parse-; ( addr len -- addr' len-x addr x )\n over 0 2swap\n begin\n dup 0 <>\n while\n over c@ [char] ; <>\n while\n 1- swap 1+ swap\n 2swap 1+ 2swap\n repeat then\n dup 0 <> if\n 1- swap 1+ swap\n then\n 2swap\n;\n\n\\ Try loading one of multiple kernels specified\n\n: try_multiple_kernels ( addr len addr' len' args -- flag )\n >r\n begin\n parse-; 2>r\n 2over 2r>\n r@ clip_args\n s\" DEBUG\" getenv? if\n s\" echo Module_path: ${module_path}\" evaluate\n .\" Kernel : \" >r 2dup type r> cr\n dup 2 = if .\" Flags : \" >r 2over type r> cr then\n then\n 1 load\n while\n dup 0=\n until\n 1 >r \\ Failure\n else\n 0 >r \\ Success\n then\n 2drop 2drop\n r>\n r> drop\n;\n\n\\ Try to load a kernel; the kernel name is taken from one of\n\\ the following lists, as ordered:\n\\\n\\ 1. The \"bootfile\" environment variable\n\\ 2. The \"kernel\" environment variable\n\\\n\\ Flags are passed, if available. If not, dummy values must be given.\n\\\n\\ The kernel gets loaded from the current module_path.\n\n: load_a_kernel ( flags len 1 | x x 0 -- flag )\n local args\n 2local flags\n 0 0 2local kernel\n end-locals\n\n \\ Check if a default kernel name exists at all, exits if not\n s\" bootfile\" getenv dup -1 <> if\n to kernel\n flags kernel args 1+ try_multiple_kernels\n dup 0= if exit then\n then\n drop\n\n s\" kernel\" getenv dup -1 <> if\n to kernel\n else\n drop\n 1 exit \\ Failure\n then\n\n \\ Try all default kernel names\n flags kernel args 1+ try_multiple_kernels\n;\n\n\\ Try to load a kernel; the kernel name is taken from one of\n\\ the following lists, as ordered:\n\\\n\\ 1. The \"bootfile\" environment variable\n\\ 2. The \"kernel\" environment variable\n\\\n\\ Flags are passed, if provided.\n\\\n\\ The kernel will be loaded from a directory computed from the\n\\ path given. Two directories will be tried in the following order:\n\\\n\\ 1. \/boot\/path\n\\ 2. path\n\\\n\\ The module_path variable is overridden if load is succesful, by\n\\ prepending the successful path.\n\n: load_from_directory ( path len 1 | flags len' path len 2 -- flag )\n local args\n 2local path\n args 1 = if 0 0 then\n 2local flags\n 0 0 2local oldmodulepath\n 0 0 2local newmodulepath\n end-locals\n\n \\ Set the environment variable module_path, and try loading\n \\ the kernel again.\n modulepath getenv saveenv to oldmodulepath\n\n \\ Try prepending \/boot\/ first\n bootpath nip path nip + \n oldmodulepath nip dup -1 = if\n drop\n else\n 1+ +\n then\n allocate\n if ( out of memory )\n 1 exit\n then\n\n 0\n bootpath strcat\n path strcat\n 2dup to newmodulepath\n modulepath setenv\n\n \\ Try all default kernel names\n flags args 1- load_a_kernel\n 0= if ( success )\n oldmodulepath nip -1 <> if\n newmodulepath s\" ;\" strcat\n oldmodulepath strcat\n modulepath setenv\n newmodulepath drop free-memory\n oldmodulepath drop free-memory\n then\n 0 exit\n then\n\n \\ Well, try without the prepended \/boot\/\n path newmodulepath drop swap move\n newmodulepath drop path nip\n 2dup to newmodulepath\n modulepath setenv\n\n \\ Try all default kernel names\n flags args 1- load_a_kernel\n if ( failed once more )\n oldmodulepath restoreenv\n newmodulepath drop free-memory\n 1\n else\n oldmodulepath nip -1 <> if\n newmodulepath s\" ;\" strcat\n oldmodulepath strcat\n modulepath setenv\n newmodulepath drop free-memory\n oldmodulepath drop free-memory\n then\n 0\n then\n;\n\n\\ Try to load a kernel; the kernel name is taken from one of\n\\ the following lists, as ordered:\n\\\n\\ 1. The \"bootfile\" environment variable\n\\ 2. The \"kernel\" environment variable\n\\ 3. The \"path\" argument\n\\\n\\ Flags are passed, if provided.\n\\\n\\ The kernel will be loaded from a directory computed from the\n\\ path given. Two directories will be tried in the following order:\n\\\n\\ 1. \/boot\/path\n\\ 2. path\n\\\n\\ Unless \"path\" is meant to be kernel name itself. In that case, it\n\\ will first be tried as a full path, and, next, search on the\n\\ directories pointed by module_path.\n\\\n\\ The module_path variable is overridden if load is succesful, by\n\\ prepending the successful path.\n\n: load_directory_or_file ( path len 1 | flags len' path len 2 -- flag )\n local args\n 2local path\n args 1 = if 0 0 then\n 2local flags\n end-locals\n\n \\ First, assume path is an absolute path to a directory\n flags path args clip_args load_from_directory\n dup 0= if exit else drop then\n\n \\ Next, assume path points to the kernel\n flags path args try_multiple_kernels\n;\n\n: initialize ( addr len -- )\n strdup conf_files .len ! conf_files .addr !\n;\n\n: kernel_options ( -- addr len 1 | 0 )\n s\" kernel_options\" getenv\n dup -1 = if drop 0 else 1 then\n;\n\n: standard_kernel_search ( flags 1 | 0 -- flag )\n local args\n args 0= if 0 0 then\n 2local flags\n s\" kernel\" getenv\n dup -1 = if 0 swap then\n 2local path\n end-locals\n\n path nip -1 = if ( there isn't a \"kernel\" environment variable )\n flags args load_a_kernel\n else\n flags path args 1+ clip_args load_directory_or_file\n then\n;\n\n: load_kernel ( -- ) ( throws: abort )\n kernel_options standard_kernel_search\n abort\" Unable to load a kernel!\"\n;\n\n: set_defaultoptions ( -- )\n s\" kernel_options\" getenv dup -1 = if\n drop\n else\n s\" temp_options\" setenv\n then\n;\n\n: argv[] ( aN uN ... a1 u1 N i -- aN uN ... a1 u1 N ai+1 ui+1 )\n 2dup = if 0 0 exit then\n dup >r\n 1+ 2* ( skip N and ui )\n pick\n r>\n 1+ 2* ( skip N and ai )\n pick\n;\n\n: drop_args ( aN uN ... a1 u1 N -- )\n 0 ?do 2drop loop\n;\n\n: argc\n dup\n;\n\n: queue_argv ( aN uN ... a1 u1 N a u -- a u aN uN ... a1 u1 N+1 )\n >r\n over 2* 1+ -roll\n r>\n over 2* 1+ -roll\n 1+\n;\n\n: unqueue_argv ( aN uN ... a1 u1 N -- aN uN ... a2 u2 N-1 a1 u1 )\n 1- -rot\n;\n\n: strlen(argv)\n dup 0= if 0 exit then\n 0 >r\t\\ Size\n 0 >r\t\\ Index\n begin\n argc r@ <>\n while\n r@ argv[]\n nip\n r> r> rot + 1+\n >r 1+ >r\n repeat\n r> drop\n r>\n;\n\n: concat_argv ( aN uN ... a1 u1 N -- a u )\n strlen(argv) allocate if out_of_memory throw then\n 0 2>r\n\n begin\n argc\n while\n unqueue_argv\n 2r> 2swap\n strcat\n s\" \" strcat\n 2>r\n repeat\n drop_args\n 2r>\n;\n\n: set_tempoptions ( addrN lenN ... addr1 len1 N -- addr len 1 | 0 )\n \\ Save the first argument, if it exists and is not a flag\n argc if\n 0 argv[] drop c@ [char] - <> if\n unqueue_argv 2>r \\ Filename\n 1 >r\t\t\\ Filename present\n else\n 0 >r\t\t\\ Filename not present\n then\n else\n 0 >r\t\t\\ Filename not present\n then\n\n \\ If there are other arguments, assume they are flags\n ?dup if\n concat_argv\n 2dup s\" temp_options\" setenv\n drop free if free_error throw then\n else\n set_defaultoptions\n then\n\n \\ Bring back the filename, if one was provided\n r> if 2r> 1 else 0 then\n;\n\n: get_arguments ( -- addrN lenN ... addr1 len1 N )\n 0\n begin\n \\ Get next word on the command line\n parse-word\n ?dup while\n queue_argv\n repeat\n drop ( empty string )\n;\n\n: load_kernel_and_modules ( args -- flag )\n set_tempoptions\n argc >r\n s\" temp_options\" getenv dup -1 <> if\n queue_argv\n else\n drop\n then\n r> if ( a path was passed )\n load_directory_or_file\n else\n standard_kernel_search\n then\n ?dup 0= if ['] load_modules catch then\n;\n\n: read-password { size | buf len -- }\n size allocate if out_of_memory throw then\n to buf\n 0 to len\n begin\n key\n dup backspace = if\n drop\n len if\n backspace emit bl emit backspace emit\n len 1 - to len\n else\n bell emit\n then\n else\n dup = if cr drop buf len exit then\n [char] * emit\n len size < if\n buf len chars + c!\n else\n drop\n then\n len 1+ to len\n then\n again\n;\n\n\\ Go back to straight forth vocabulary\n\nonly forth also definitions\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"f2f3d42fded199ec1e64eb2c1eeaa57e0543aa37","subject":"With apologies to dcs, temporarily comment out the version check code. It is failing for everybody that I have spoken with that has tried it.","message":"With apologies to dcs, temporarily comment out the version check code. It\nis failing for everybody that I have spoken with that has tried it.\n\nFreeBSD\/i386 bootstrap loader, Revision 0.8\n(root@outback.netplex.com.au, Tue Jun 13 23:26:49 PDT 2000)\nLoader version 0.3+ required\nAborted!\nstart not found\n\nNote that the 0.3+ message is from inside the arch-alpha block, not the\ni386 block of code. And even then, 0.8 is higher than 0.3.\n\nThis prevents the rest of the loader.conf stuff working. :-\/\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/loader.4th","new_file":"sys\/boot\/forth\/loader.4th","new_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\n\\ s\" arch-alpha\" environment? [if] [if]\n\\\ts\" loader_version\" environment? [if]\n\\\t\t3 < [if]\n\\\t\t\t.( Loader version 0.3+ required) cr\n\\\t\t\tabort\n\\\t\t[then]\n\\\t[else]\n\\\t\t.( Could not get loader version!) cr\n\\\t\tabort\n\\\t[then]\n\\ [then] [then]\n\n\\ s\" arch-i386\" environment? [if] [if]\n\\\ts\" loader_version\" environment? [if]\n\\\t\t8 < [if]\n\\\t\t\t.( Loader version 0.8+ required) cr\n\\\t\t\tabort\n\\\t\t[then]\n\\\t[else]\n\\\t\t.( Could not get loader version!) cr\n\\\t\tabort\n\\\t[then]\n\\ [then] [then]\n\ninclude \/boot\/support.4th\n\nonly forth definitions also support-functions\n\n\\ ***** boot-conf\n\\\n\\\tPrepares to boot as specified by loaded configuration files.\n\nalso support-functions definitions\n\n: bootpath s\" \/boot\/\" ;\n: modulepath s\" module_path\" ;\n: saveenv ( addr len | 0 -1 -- addr' len | 0 -1 )\n dup -1 = if exit then\n dup allocate abort\" Out of memory\"\n swap 2dup 2>r\n move\n 2r>\n;\n: freeenv ( addr len | 0 -1 )\n -1 = if drop else free abort\" Freeing error\" then\n;\n: restoreenv ( addr len | 0 -1 -- )\n dup -1 = if ( it wasn't set )\n 2drop\n modulepath unsetenv\n else\n over >r\n modulepath setenv\n r> free abort\" Freeing error\"\n then\n;\n\nonly forth also support-functions also builtins definitions\n\n: boot-conf ( args 1 | 0 \"args\" -- flag )\n 0 1 unload drop\n\n 0= if ( interpreted )\n \\ Get next word on the command line\n bl word count\n ?dup 0= if ( there wasn't anything )\n drop 0\n else ( put in the number of strings )\n 1\n then\n then ( interpreted )\n\n if ( there are arguments )\n \\ Try to load the kernel\n s\" kernel_options\" getenv dup -1 = if drop 2dup 1 else 2over 2 then\n\n 1 load if ( load command failed )\n \\ Remove garbage from the stack\n\n \\ Set the environment variable module_path, and try loading\n \\ the kernel again.\n\n \\ First, save module_path value\n modulepath getenv saveenv dup -1 = if 0 swap then 2>r\n\n \\ Sets the new value\n 2dup modulepath setenv\n\n \\ Try to load the kernel\n s\" load ${kernel} ${kernel_options}\" ['] evaluate catch\n if ( load failed yet again )\n\t\\ Remove garbage from the stack\n\t2drop\n\n\t\\ Try prepending \/boot\/\n\tbootpath 2over nip over + allocate\n\tif ( out of memory )\n\t 2drop 2drop\n\t 2r> restoreenv\n\t 100 exit\n\tthen\n\n\t0 2swap strcat 2swap strcat\n\t2dup modulepath setenv\n\n\tdrop free if ( freeing memory error )\n\t 2drop\n\t 2r> restoreenv\n\t 100 exit\n\tthen\n \n\t\\ Now, once more, try to load the kernel\n\ts\" load ${kernel} ${kernel_options}\" ['] evaluate catch\n\tif ( failed once more )\n\t 2drop\n\t 2r> restoreenv\n\t 100 exit\n\tthen\n\n else ( we found the kernel on the path passed )\n\n\t2drop ( discard command line arguments )\n\n then ( could not load kernel from directory passed )\n\n \\ Load the remaining modules, if the kernel was loaded at all\n ['] load_modules catch if 2r> restoreenv 100 exit then\n\n \\ Call autoboot to perform the booting\n 0 1 autoboot\n\n \\ Keep new module_path\n 2r> freeenv\n\n exit\n then ( could not load kernel with name passed )\n\n 2drop ( discard command line arguments )\n\n else ( try just a straight-forward kernel load )\n s\" load ${kernel} ${kernel_options}\" ['] evaluate catch\n if ( kernel load failed ) 2drop 100 exit then\n\n then ( there are command line arguments )\n\n \\ Load the remaining modules, if the kernel was loaded at all\n ['] load_modules catch if 100 exit then\n\n \\ Call autoboot to perform the booting\n 0 1 autoboot\n;\n\nalso forth definitions\nbuiltin: boot-conf\nonly forth definitions also support-functions\n\n\\ ***** check-password\n\\\n\\\tIf a password was defined, execute autoboot and ask for\n\\\tpassword if autoboot returns.\n\n: check-password\n password .addr @ if\n 0 autoboot\n false >r\n begin\n bell emit bell emit\n .\" Password: \"\n password .len @ read-password\n dup password .len @ = if\n 2dup password .addr @ password .len @\n compare 0= if r> drop true >r then\n then\n drop free drop\n r@\n until\n r> drop\n then\n;\n\n\\ ***** start\n\\\n\\ Initializes support.4th global variables, sets loader_conf_files,\n\\ process conf files, and, if any one such file was succesfully\n\\ read to the end, load kernel and modules.\n\n: start ( -- ) ( throws: abort & user-defined )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n \\ Will *NOT* try to load kernel and modules if no configuration file\n \\ was succesfully loaded!\n any_conf_read? if\n load_kernel\n load_modules\n then\n;\n\n\\ ***** initialize\n\\\n\\\tOverrides support.4th initialization word with one that does\n\\\teverything start one does, short of loading the kernel and\n\\\tmodules. Returns a flag\n\n: initialize ( -- flag )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n any_conf_read?\n;\n\n\\ ***** read-conf\n\\\n\\\tRead a configuration file, whose name was specified on the command\n\\\tline, if interpreted, or given on the stack, if compiled in.\n\n: (read-conf) ( addr len -- )\n conf_files .addr @ ?dup if free abort\" Fatal error freeing memory\" then\n strdup conf_files .len ! conf_files .addr !\n include_conf_files \\ Will recurse on new loader_conf_files definitions\n;\n\n: read-conf ( | addr len -- ) ( throws: abort & user-defined )\n state @ if\n \\ Compiling\n postpone (read-conf)\n else\n \\ Interpreting\n bl parse (read-conf)\n then\n; immediate\n\n\\ ***** enable-module\n\\\n\\ Turn a module loading on.\n\n: enable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n true r> module.flag !\n .\" will be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** disable-module\n\\\n\\ Turn a module loading off.\n\n: disable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n false r> module.flag !\n .\" will not be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** toggle-module\n\\\n\\ Turn a module loading on\/off.\n\n: toggle-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n r@ module.flag @ 0= dup r> module.flag !\n if\n .\" will be loaded.\" cr\n else\n .\" will not be loaded.\" cr\n then\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** show-module\n\\\n\\\tShow loading information about a module.\n\n: show-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n .\" Name: \" r@ module.name dup .addr @ swap .len @ type cr\n .\" Path: \" r@ module.loadname dup .addr @ swap .len @ type cr\n .\" Type: \" r@ module.type dup .addr @ swap .len @ type cr\n .\" Flags: \" r@ module.args dup .addr @ swap .len @ type cr\n .\" Before load: \" r@ module.beforeload dup .addr @ swap .len @ type cr\n .\" After load: \" r@ module.afterload dup .addr @ swap .len @ type cr\n .\" Error: \" r@ module.loaderror dup .addr @ swap .len @ type cr\n .\" Status: \" r> module.flag @ if .\" Load\" else .\" Don't load\" then cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ Words to be used inside configuration files\n\n: retry false ; \\ For use in load error commands\n: ignore true ; \\ For use in load error commands\n\n\\ Return to strict forth vocabulary\n\nonly forth also\n\n","old_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\ns\" arch-alpha\" environment? [if] [if]\n\ts\" loader_version\" environment? [if]\n\t\t3 < [if]\n\t\t\t.( Loader version 0.3+ required) cr\n\t\t\tabort\n\t\t[then]\n\t[else]\n\t\t.( Could not get loader version!) cr\n\t\tabort\n\t[then]\n[then] [then]\n\ns\" arch-i386\" environment? [if] [if]\n\ts\" loader_version\" environment? [if]\n\t\t8 < [if]\n\t\t\t.( Loader version 0.8+ required) cr\n\t\t\tabort\n\t\t[then]\n\t[else]\n\t\t.( Could not get loader version!) cr\n\t\tabort\n\t[then]\n[then] [then]\n\ninclude \/boot\/support.4th\n\nonly forth definitions also support-functions\n\n\\ ***** boot-conf\n\\\n\\\tPrepares to boot as specified by loaded configuration files.\n\nalso support-functions definitions\n\n: bootpath s\" \/boot\/\" ;\n: modulepath s\" module_path\" ;\n: saveenv ( addr len | 0 -1 -- addr' len | 0 -1 )\n dup -1 = if exit then\n dup allocate abort\" Out of memory\"\n swap 2dup 2>r\n move\n 2r>\n;\n: freeenv ( addr len | 0 -1 )\n -1 = if drop else free abort\" Freeing error\" then\n;\n: restoreenv ( addr len | 0 -1 -- )\n dup -1 = if ( it wasn't set )\n 2drop\n modulepath unsetenv\n else\n over >r\n modulepath setenv\n r> free abort\" Freeing error\"\n then\n;\n\nonly forth also support-functions also builtins definitions\n\n: boot-conf ( args 1 | 0 \"args\" -- flag )\n 0 1 unload drop\n\n 0= if ( interpreted )\n \\ Get next word on the command line\n bl word count\n ?dup 0= if ( there wasn't anything )\n drop 0\n else ( put in the number of strings )\n 1\n then\n then ( interpreted )\n\n if ( there are arguments )\n \\ Try to load the kernel\n s\" kernel_options\" getenv dup -1 = if drop 2dup 1 else 2over 2 then\n\n 1 load if ( load command failed )\n \\ Remove garbage from the stack\n\n \\ Set the environment variable module_path, and try loading\n \\ the kernel again.\n\n \\ First, save module_path value\n modulepath getenv saveenv dup -1 = if 0 swap then 2>r\n\n \\ Sets the new value\n 2dup modulepath setenv\n\n \\ Try to load the kernel\n s\" load ${kernel} ${kernel_options}\" ['] evaluate catch\n if ( load failed yet again )\n\t\\ Remove garbage from the stack\n\t2drop\n\n\t\\ Try prepending \/boot\/\n\tbootpath 2over nip over + allocate\n\tif ( out of memory )\n\t 2drop 2drop\n\t 2r> restoreenv\n\t 100 exit\n\tthen\n\n\t0 2swap strcat 2swap strcat\n\t2dup modulepath setenv\n\n\tdrop free if ( freeing memory error )\n\t 2drop\n\t 2r> restoreenv\n\t 100 exit\n\tthen\n \n\t\\ Now, once more, try to load the kernel\n\ts\" load ${kernel} ${kernel_options}\" ['] evaluate catch\n\tif ( failed once more )\n\t 2drop\n\t 2r> restoreenv\n\t 100 exit\n\tthen\n\n else ( we found the kernel on the path passed )\n\n\t2drop ( discard command line arguments )\n\n then ( could not load kernel from directory passed )\n\n \\ Load the remaining modules, if the kernel was loaded at all\n ['] load_modules catch if 2r> restoreenv 100 exit then\n\n \\ Call autoboot to perform the booting\n 0 1 autoboot\n\n \\ Keep new module_path\n 2r> freeenv\n\n exit\n then ( could not load kernel with name passed )\n\n 2drop ( discard command line arguments )\n\n else ( try just a straight-forward kernel load )\n s\" load ${kernel} ${kernel_options}\" ['] evaluate catch\n if ( kernel load failed ) 2drop 100 exit then\n\n then ( there are command line arguments )\n\n \\ Load the remaining modules, if the kernel was loaded at all\n ['] load_modules catch if 100 exit then\n\n \\ Call autoboot to perform the booting\n 0 1 autoboot\n;\n\nalso forth definitions\nbuiltin: boot-conf\nonly forth definitions also support-functions\n\n\\ ***** check-password\n\\\n\\\tIf a password was defined, execute autoboot and ask for\n\\\tpassword if autoboot returns.\n\n: check-password\n password .addr @ if\n 0 autoboot\n false >r\n begin\n bell emit bell emit\n .\" Password: \"\n password .len @ read-password\n dup password .len @ = if\n 2dup password .addr @ password .len @\n compare 0= if r> drop true >r then\n then\n drop free drop\n r@\n until\n r> drop\n then\n;\n\n\\ ***** start\n\\\n\\ Initializes support.4th global variables, sets loader_conf_files,\n\\ process conf files, and, if any one such file was succesfully\n\\ read to the end, load kernel and modules.\n\n: start ( -- ) ( throws: abort & user-defined )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n \\ Will *NOT* try to load kernel and modules if no configuration file\n \\ was succesfully loaded!\n any_conf_read? if\n load_kernel\n load_modules\n then\n;\n\n\\ ***** initialize\n\\\n\\\tOverrides support.4th initialization word with one that does\n\\\teverything start one does, short of loading the kernel and\n\\\tmodules. Returns a flag\n\n: initialize ( -- flag )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n any_conf_read?\n;\n\n\\ ***** read-conf\n\\\n\\\tRead a configuration file, whose name was specified on the command\n\\\tline, if interpreted, or given on the stack, if compiled in.\n\n: (read-conf) ( addr len -- )\n conf_files .addr @ ?dup if free abort\" Fatal error freeing memory\" then\n strdup conf_files .len ! conf_files .addr !\n include_conf_files \\ Will recurse on new loader_conf_files definitions\n;\n\n: read-conf ( | addr len -- ) ( throws: abort & user-defined )\n state @ if\n \\ Compiling\n postpone (read-conf)\n else\n \\ Interpreting\n bl parse (read-conf)\n then\n; immediate\n\n\\ ***** enable-module\n\\\n\\ Turn a module loading on.\n\n: enable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n true r> module.flag !\n .\" will be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** disable-module\n\\\n\\ Turn a module loading off.\n\n: disable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n false r> module.flag !\n .\" will not be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** toggle-module\n\\\n\\ Turn a module loading on\/off.\n\n: toggle-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n r@ module.flag @ 0= dup r> module.flag !\n if\n .\" will be loaded.\" cr\n else\n .\" will not be loaded.\" cr\n then\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** show-module\n\\\n\\\tShow loading information about a module.\n\n: show-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n .\" Name: \" r@ module.name dup .addr @ swap .len @ type cr\n .\" Path: \" r@ module.loadname dup .addr @ swap .len @ type cr\n .\" Type: \" r@ module.type dup .addr @ swap .len @ type cr\n .\" Flags: \" r@ module.args dup .addr @ swap .len @ type cr\n .\" Before load: \" r@ module.beforeload dup .addr @ swap .len @ type cr\n .\" After load: \" r@ module.afterload dup .addr @ swap .len @ type cr\n .\" Error: \" r@ module.loaderror dup .addr @ swap .len @ type cr\n .\" Status: \" r> module.flag @ if .\" Load\" else .\" Don't load\" then cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ Words to be used inside configuration files\n\n: retry false ; \\ For use in load error commands\n: ignore true ; \\ For use in load error commands\n\n\\ Return to strict forth vocabulary\n\nonly forth also\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"f1c707af017f2af39f4af77653a4854ecbbcdcc5","subject":"?TWO-ADJACENT-1-BITS tests removed","message":"?TWO-ADJACENT-1-BITS tests removed\n","repos":"bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas","old_file":"KataDiversion_tests.fth","new_file":"KataDiversion_tests.fth","new_contents":"\\ KataDiversion tests, in Forth\n\\ running tests:\n\\ gforth KataDiversion_tests.fth -e bye\n\nREQUIRE KataDiversion.fth\n\nVARIABLE ASSERT-COUNT\n\n: ASSERTS-INIT ( -- )\n 0 ASSERT-COUNT ! ;\n\n: ASSERTS-RESULT ( -- )\n ASSERT-COUNT @ . .\" assertions successfully passed.\" CR ;\n\n\\ destructive assert-equal\n: ASSERT-EQUAL-D ( n1 n2 -- )\n <> IF 1 ABORT\" AssertEqual: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-equal\n: ASSERT-EQUAL ( n1 n2 -- n1 n2 )\n 2DUP ASSERT-EQUAL-D ;\n\n\\ destructive assert-true\n: ASSERT-TRUE-D ( n -- )\n 0 = IF 1 ABORT\" AssertTrue: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-true\n: ASSERT-TRUE ( n -- n )\n DUP ASSERT-TRUE-D ;\n\n\\ destructive assert-false\n: ASSERT-False-D ( n -- )\n 0 <> IF 1 ABORT\" AssertFalse: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-false\n: ASSERT-FALSE ( n -- n )\n DUP ASSERT-FALSE-D ;\n\n\\ ---- tests ----\n\nASSERTS-INIT\n\n\\ ?EMPTY\nEMPTY DEPTH 0 ASSERT-EQUAL-D\nEMPTY EMPTY DEPTH 0 ASSERT-EQUAL-D\n0 EMPTY DEPTH 0 ASSERT-EQUAL-D\n1 2 3 4 EMPTY DEPTH 0 ASSERT-EQUAL-D\n\n\\ ?MAX-NB\n-1 ?MAX-NB 0 ASSERT-EQUAL-D\n 0 ?MAX-NB 0 ASSERT-EQUAL-D\n 1 ?MAX-NB 2 ASSERT-EQUAL-D\n 2 ?MAX-NB 4 ASSERT-EQUAL-D\n 3 ?MAX-NB 8 ASSERT-EQUAL-D\n\n\\ MAXPOW2\n 1 MAXPOW2 1 ASSERT-EQUAL-D\n 2 MAXPOW2 2 ASSERT-EQUAL-D\n 3 MAXPOW2 2 ASSERT-EQUAL-D\n 4 MAXPOW2 4 ASSERT-EQUAL-D\n 5 MAXPOW2 4 ASSERT-EQUAL-D\n 8 MAXPOW2 8 ASSERT-EQUAL-D\n 42 MAXPOW2 32 ASSERT-EQUAL-D\n2000 MAXPOW2 1024 ASSERT-EQUAL-D\n\n\n\\ ?NOT-TWO-ADJACENT-1-BITS\n 1 ?NOT-TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n 2 ?NOT-TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n 3 ?NOT-TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n 6 ?NOT-TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n 7 ?NOT-TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n 8 ?NOT-TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n 11 ?NOT-TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n 65 ?NOT-TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n3072 ?NOT-TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n\nASSERTS-RESULT\n\\ ---------\n\n\n","old_contents":"\\ KataDiversion tests, in Forth\n\\ running tests:\n\\ gforth KataDiversion_tests.fth -e bye\n\nREQUIRE KataDiversion.fth\n\nVARIABLE ASSERT-COUNT\n\n: ASSERTS-INIT ( -- )\n 0 ASSERT-COUNT ! ;\n\n: ASSERTS-RESULT ( -- )\n ASSERT-COUNT @ . .\" assertions successfully passed.\" CR ;\n\n\\ destructive assert-equal\n: ASSERT-EQUAL-D ( n1 n2 -- )\n <> IF 1 ABORT\" AssertEqual: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-equal\n: ASSERT-EQUAL ( n1 n2 -- n1 n2 )\n 2DUP ASSERT-EQUAL-D ;\n\n\\ destructive assert-true\n: ASSERT-TRUE-D ( n -- )\n 0 = IF 1 ABORT\" AssertTrue: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-true\n: ASSERT-TRUE ( n -- n )\n DUP ASSERT-TRUE-D ;\n\n\\ destructive assert-false\n: ASSERT-False-D ( n -- )\n 0 <> IF 1 ABORT\" AssertFalse: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-false\n: ASSERT-FALSE ( n -- n )\n DUP ASSERT-FALSE-D ;\n\n\\ ---- tests ----\n\nASSERTS-INIT\n\n\\ ?EMPTY\nEMPTY DEPTH 0 ASSERT-EQUAL-D\nEMPTY EMPTY DEPTH 0 ASSERT-EQUAL-D\n0 EMPTY DEPTH 0 ASSERT-EQUAL-D\n1 2 3 4 EMPTY DEPTH 0 ASSERT-EQUAL-D\n\n\\ ?MAX-NB\n-1 ?MAX-NB 0 ASSERT-EQUAL-D\n 0 ?MAX-NB 0 ASSERT-EQUAL-D\n 1 ?MAX-NB 2 ASSERT-EQUAL-D\n 2 ?MAX-NB 4 ASSERT-EQUAL-D\n 3 ?MAX-NB 8 ASSERT-EQUAL-D\n\n\\ MAXPOW2\n 1 MAXPOW2 1 ASSERT-EQUAL-D\n 2 MAXPOW2 2 ASSERT-EQUAL-D\n 3 MAXPOW2 2 ASSERT-EQUAL-D\n 4 MAXPOW2 4 ASSERT-EQUAL-D\n 5 MAXPOW2 4 ASSERT-EQUAL-D\n 8 MAXPOW2 8 ASSERT-EQUAL-D\n 42 MAXPOW2 32 ASSERT-EQUAL-D\n2000 MAXPOW2 1024 ASSERT-EQUAL-D\n\n\n\\ ?TWO-ADJACENT-1-BITS\n 1 ?TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n 2 ?TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n 3 ?TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n 6 ?TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n 7 ?TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n 8 ?TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n 11 ?TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n 65 ?TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n3072 ?TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n\n\n\\ ?NOT-TWO-ADJACENT-1-BITS\n 1 ?NOT-TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n 2 ?NOT-TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n 3 ?NOT-TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n 6 ?NOT-TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n 7 ?NOT-TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n 8 ?NOT-TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n 11 ?NOT-TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n 65 ?NOT-TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n3072 ?NOT-TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n\nASSERTS-RESULT\n\\ ---------\n\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"9b1a80ce37c18c7ae9caed3735a03966def231f9","subject":"Remove the USB keyboard hack now that KBDMUX is enabled by default. Allow it to be disabled if Safe Mode is selected.","message":"Remove the USB keyboard hack now that KBDMUX is enabled by default. Allow\nit to be disabled if Safe Mode is selected.\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/beastie.4th","new_file":"sys\/boot\/forth\/beastie.4th","new_contents":"\\ Copyright (c) 2003 Scott Long \n\\ Copyright (c) 2003 Aleksander Fafula \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\nmarker task-beastie.4th\n\ninclude \/boot\/screen.4th\ninclude \/boot\/frames.4th\n\nhide\n\nvariable menuidx\nvariable menubllt\nvariable menuX\nvariable menuY\nvariable promptwidth\n\nvariable bootkey\nvariable bootacpikey\nvariable bootsafekey\nvariable bootverbosekey\nvariable bootsinglekey\nvariable escapekey\nvariable rebootkey\n\n46 constant dot\n\n\\ The BSD Daemon. He is 19 rows high and 34 columns wide\n: beastie-logo ( x y -- )\n2dup at-xy .\" \u001b[1;31m, ,\" 1+\n2dup at-xy .\" \/( )`\" 1+\n2dup at-xy .\" \\ \\___ \/ |\" 1+\n2dup at-xy .\" \/- \u001b[37m_\u001b[31m `-\/ '\" 1+\n2dup at-xy .\" (\u001b[37m\/\\\/ \\\u001b[31m \\ \/\\\" 1+\n2dup at-xy .\" \u001b[37m\/ \/ |\u001b[31m ` \\\" 1+\n2dup at-xy .\" \u001b[34mO O \u001b[37m) \u001b[31m\/ |\" 1+\n2dup at-xy .\" \u001b[37m`-^--'\u001b[31m`< '\" 1+\n2dup at-xy .\" (_.) _ ) \/\" 1+\n2dup at-xy .\" `.___\/` \/ \" 1+\n2dup at-xy .\" `-----' \/\" 1+\n2dup at-xy .\" \u001b[33m<----.\u001b[31m __ \/ __ \\\" 1+\n2dup at-xy .\" \u001b[33m<----|====\u001b[31mO)))\u001b[33m==\u001b[31m) \\) \/\u001b[33m====|\" 1+\n2dup at-xy .\" \u001b[33m<----'\u001b[31m `--' `.__,' \\\" 1+\n2dup at-xy .\" | |\" 1+\n2dup at-xy .\" \\ \/ \/\\\" 1+\n2dup at-xy .\" \u001b[36m______\u001b[31m( (_ \/ \\______\/\" 1+\n2dup at-xy .\" \u001b[36m,' ,-----' |\" 1+\nat-xy .\" `--{__________) \u001b[0m\"\n;\n\n: beastiebw-logo ( x y -- )\n\t2dup at-xy .\" , ,\" 1+\n\t2dup at-xy .\" \/( )`\" 1+\n\t2dup at-xy .\" \\ \\___ \/ |\" 1+\n\t2dup at-xy .\" \/- _ `-\/ '\" 1+\n\t2dup at-xy .\" (\/\\\/ \\ \\ \/\\\" 1+\n\t2dup at-xy .\" \/ \/ | ` \\\" 1+\n\t2dup at-xy .\" O O ) \/ |\" 1+\n\t2dup at-xy .\" `-^--'`< '\" 1+\n\t2dup at-xy .\" (_.) _ ) \/\" 1+\n\t2dup at-xy .\" `.___\/` \/\" 1+\n\t2dup at-xy .\" `-----' \/\" 1+\n\t2dup at-xy .\" <----. __ \/ __ \\\" 1+\n\t2dup at-xy .\" <----|====O)))==) \\) \/====\" 1+\n\t2dup at-xy .\" <----' `--' `.__,' \\\" 1+\n\t2dup at-xy .\" | |\" 1+\n\t2dup at-xy .\" \\ \/ \/\\\" 1+\n\t2dup at-xy .\" ______( (_ \/ \\______\/\" 1+\n\t2dup at-xy .\" ,' ,-----' |\" 1+\n\t at-xy .\" `--{__________)\"\n;\n\n: fbsdbw-logo ( x y -- )\n\t2dup at-xy .\" ______\" 1+\n\t2dup at-xy .\" | ____| __ ___ ___ \" 1+\n\t2dup at-xy .\" | |__ | '__\/ _ \\\/ _ \\\" 1+\n\t2dup at-xy .\" | __|| | | __\/ __\/\" 1+\n\t2dup at-xy .\" | | | | | | |\" 1+\n\t2dup at-xy .\" |_| |_| \\___|\\___|\" 1+\n\t2dup at-xy .\" ____ _____ _____\" 1+\n\t2dup at-xy .\" | _ \\ \/ ____| __ \\\" 1+\n\t2dup at-xy .\" | |_) | (___ | | | |\" 1+\n\t2dup at-xy .\" | _ < \\___ \\| | | |\" 1+\n\t2dup at-xy .\" | |_) |____) | |__| |\" 1+\n\t2dup at-xy .\" | | | |\" 1+\n\t at-xy .\" |____\/|_____\/|_____\/\"\n;\n\n: print-logo ( x y -- )\n\ts\" loader_logo\" getenv\n\tdup -1 = if\n\t\tdrop\n\t\tfbsdbw-logo\n\t\texit\n\tthen\n\t2dup s\" fbsdbw\" compare-insensitive 0= if\n\t\t2drop\n\t\tfbsdbw-logo\n\t\texit\n\tthen\n\t2dup s\" beastiebw\" compare-insensitive 0= if\n\t\t2drop\n\t\tbeastiebw-logo\n\t\texit\n\tthen\n\t2dup s\" beastie\" compare-insensitive 0= if\n\t\t2drop\n\t\tbeastie-logo\n\t\texit\n\tthen\n\t2dup s\" none\" compare-insensitive 0= if\n\t\t2drop\n\t\t\\ no logo\n\t\texit\n\tthen\n\t2drop\n\tfbsdbw-logo\n;\n\n: acpienabled? ( -- flag )\n\ts\" acpi_load\" getenv\n\tdup -1 = if\n\t\tdrop false exit\n\tthen\n\ts\" YES\" compare-insensitive 0<> if\n\t\tfalse exit\n\tthen\n\ts\" hint.acpi.0.disabled\" getenv\n\tdup -1 <> if\n\t\ts\" 0\" compare 0<> if\n\t\t\tfalse exit\n\t\tthen\n\telse\n\t\tdrop\n\tthen\n\ttrue\n;\n\n: printmenuitem ( -- n )\n\tmenuidx @\n\t1+ dup\n\tmenuidx !\n\tmenuY @ + dup menuX @ swap at-xy\n\tmenuidx @ .\n\tmenuX @ 1+ swap at-xy\n\tmenubllt @ emit\n\tmenuidx @ 48 +\n;\n\n: beastie-menu ( -- )\n\t0 menuidx !\n\tdot menubllt !\n\t8 menuY !\n\t5 menuX !\n\tclear\n\t46 4 print-logo\n\t42 20 2 2 box\n\t13 6 at-xy .\" Welcome to FreeBSD!\"\n\tprintmenuitem .\" Boot FreeBSD [default]\" bootkey !\n\ts\" arch-i386\" environment? if\n\t\tdrop\n\t\tprintmenuitem .\" Boot FreeBSD with ACPI \" bootacpikey !\n\t\tacpienabled? if\n\t\t\t.\" disabled\"\n\t\telse\n\t\t\t.\" enabled\"\n\t\tthen\n\telse\n\t\t-2 bootacpikey !\n\tthen\n\tprintmenuitem .\" Boot FreeBSD in Safe Mode\" bootsafekey !\n\tprintmenuitem .\" Boot FreeBSD in single user mode\" bootsinglekey !\n\tprintmenuitem .\" Boot FreeBSD with verbose logging\" bootverbosekey !\n\tprintmenuitem .\" Escape to loader prompt\" escapekey !\n\tprintmenuitem .\" Reboot\" rebootkey !\n\tmenuX @ 20 at-xy\n\t.\" Select option, [Enter] for default\"\n\tmenuX @ 21 at-xy\n\ts\" or [Space] to pause timer \" dup 2 - promptwidth !\n\ttype\n;\n\n: tkey\n\tseconds +\n\tbegin 1 while\n\t\tover 0<> if\n\t\t\tdup seconds u< if\n\t\t\t\tdrop\n\t\t\t\t-1\n\t\t\t\texit\n\t\t\tthen\n\t\t\tmenuX @ promptwidth @ + 21 at-xy dup seconds - .\n\t\tthen\n\t\tkey? if\n\t\t\tdrop\n\t\t\tkey\n\t\t\texit\n\t\tthen\n\t50 ms\n\trepeat\n;\n\nset-current\n\n: beastie-start\n\ts\" beastie_disable\" getenv\n\tdup -1 <> if\n\t\ts\" YES\" compare-insensitive 0= if\n\t\t\texit\n\t\tthen\n\telse\n\t\tdrop\n\tthen\n\tbeastie-menu\n\ts\" autoboot_delay\" getenv\n\tdup -1 = if\n\t\tdrop\n\t\t10\n\telse\n\t\t0 0 2swap >number drop drop drop\n\tthen\n\tbegin\n\t\tdup tkey\n\t\t0 25 at-xy\n\t\tdup 32 = if nip 0 swap then\n\t\tdup -1 = if 0 boot then\n\t\tdup 13 = if 0 boot then\n\t\tdup bootkey @ = if 0 boot then\n\t\tdup bootacpikey @ = if\n\t\t\tacpienabled? if\n\t\t\t\ts\" acpi_load\" unsetenv\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\telse\n\t\t\t\ts\" YES\" s\" acpi_load\" setenv\n\t\t\t\ts\" 0\" s\" hint.acpi.0.disabled\" setenv\n\t\t\tthen\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootsafekey @ = if\n\t\t\ts\" arch-i386\" environment? if\n\t\t\t\tdrop\n\t\t\t\ts\" acpi_load\" unsetenv\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\t\ts\" 1\" s\" hint.apic.0.disabled\" setenv\n\t\t\tthen\n\t\t\ts\" 0\" s\" hw.ata.ata_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.atapi_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.wc\" setenv\n\t\t\ts\" 0\" s\" hw.eisa_slots\" setenv\n\t\t\ts\" 1\" s\" hint.kbdmux.0.disabled\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootverbosekey @ = if\n\t\t\ts\" YES\" s\" boot_verbose\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootsinglekey @ = if\n\t\t\ts\" YES\" s\" boot_single\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup escapekey @ = if\n\t\t\t2drop\n\t\t\ts\" NO\" s\" autoboot_delay\" setenv\n\t\t\texit\n\t\tthen\n\t\trebootkey @ = if 0 reboot then\n\tagain\n;\n\nprevious\n","old_contents":"\\ Copyright (c) 2003 Scott Long \n\\ Copyright (c) 2003 Aleksander Fafula \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\nmarker task-beastie.4th\n\ninclude \/boot\/screen.4th\ninclude \/boot\/frames.4th\n\nhide\n\nvariable menuidx\nvariable menubllt\nvariable menuX\nvariable menuY\nvariable promptwidth\n\nvariable bootkey\nvariable bootacpikey\nvariable bootusbkey\nvariable bootsafekey\nvariable bootverbosekey\nvariable bootsinglekey\nvariable escapekey\nvariable rebootkey\n\n46 constant dot\n\n\\ The BSD Daemon. He is 19 rows high and 34 columns wide\n: beastie-logo ( x y -- )\n2dup at-xy .\" \u001b[1;31m, ,\" 1+\n2dup at-xy .\" \/( )`\" 1+\n2dup at-xy .\" \\ \\___ \/ |\" 1+\n2dup at-xy .\" \/- \u001b[37m_\u001b[31m `-\/ '\" 1+\n2dup at-xy .\" (\u001b[37m\/\\\/ \\\u001b[31m \\ \/\\\" 1+\n2dup at-xy .\" \u001b[37m\/ \/ |\u001b[31m ` \\\" 1+\n2dup at-xy .\" \u001b[34mO O \u001b[37m) \u001b[31m\/ |\" 1+\n2dup at-xy .\" \u001b[37m`-^--'\u001b[31m`< '\" 1+\n2dup at-xy .\" (_.) _ ) \/\" 1+\n2dup at-xy .\" `.___\/` \/ \" 1+\n2dup at-xy .\" `-----' \/\" 1+\n2dup at-xy .\" \u001b[33m<----.\u001b[31m __ \/ __ \\\" 1+\n2dup at-xy .\" \u001b[33m<----|====\u001b[31mO)))\u001b[33m==\u001b[31m) \\) \/\u001b[33m====|\" 1+\n2dup at-xy .\" \u001b[33m<----'\u001b[31m `--' `.__,' \\\" 1+\n2dup at-xy .\" | |\" 1+\n2dup at-xy .\" \\ \/ \/\\\" 1+\n2dup at-xy .\" \u001b[36m______\u001b[31m( (_ \/ \\______\/\" 1+\n2dup at-xy .\" \u001b[36m,' ,-----' |\" 1+\nat-xy .\" `--{__________) \u001b[0m\"\n;\n\n: beastiebw-logo ( x y -- )\n\t2dup at-xy .\" , ,\" 1+\n\t2dup at-xy .\" \/( )`\" 1+\n\t2dup at-xy .\" \\ \\___ \/ |\" 1+\n\t2dup at-xy .\" \/- _ `-\/ '\" 1+\n\t2dup at-xy .\" (\/\\\/ \\ \\ \/\\\" 1+\n\t2dup at-xy .\" \/ \/ | ` \\\" 1+\n\t2dup at-xy .\" O O ) \/ |\" 1+\n\t2dup at-xy .\" `-^--'`< '\" 1+\n\t2dup at-xy .\" (_.) _ ) \/\" 1+\n\t2dup at-xy .\" `.___\/` \/\" 1+\n\t2dup at-xy .\" `-----' \/\" 1+\n\t2dup at-xy .\" <----. __ \/ __ \\\" 1+\n\t2dup at-xy .\" <----|====O)))==) \\) \/====\" 1+\n\t2dup at-xy .\" <----' `--' `.__,' \\\" 1+\n\t2dup at-xy .\" | |\" 1+\n\t2dup at-xy .\" \\ \/ \/\\\" 1+\n\t2dup at-xy .\" ______( (_ \/ \\______\/\" 1+\n\t2dup at-xy .\" ,' ,-----' |\" 1+\n\t at-xy .\" `--{__________)\"\n;\n\n: fbsdbw-logo ( x y -- )\n\t2dup at-xy .\" ______\" 1+\n\t2dup at-xy .\" | ____| __ ___ ___ \" 1+\n\t2dup at-xy .\" | |__ | '__\/ _ \\\/ _ \\\" 1+\n\t2dup at-xy .\" | __|| | | __\/ __\/\" 1+\n\t2dup at-xy .\" | | | | | | |\" 1+\n\t2dup at-xy .\" |_| |_| \\___|\\___|\" 1+\n\t2dup at-xy .\" ____ _____ _____\" 1+\n\t2dup at-xy .\" | _ \\ \/ ____| __ \\\" 1+\n\t2dup at-xy .\" | |_) | (___ | | | |\" 1+\n\t2dup at-xy .\" | _ < \\___ \\| | | |\" 1+\n\t2dup at-xy .\" | |_) |____) | |__| |\" 1+\n\t2dup at-xy .\" | | | |\" 1+\n\t at-xy .\" |____\/|_____\/|_____\/\"\n;\n\n: print-logo ( x y -- )\n\ts\" loader_logo\" getenv\n\tdup -1 = if\n\t\tdrop\n\t\tfbsdbw-logo\n\t\texit\n\tthen\n\t2dup s\" fbsdbw\" compare-insensitive 0= if\n\t\t2drop\n\t\tfbsdbw-logo\n\t\texit\n\tthen\n\t2dup s\" beastiebw\" compare-insensitive 0= if\n\t\t2drop\n\t\tbeastiebw-logo\n\t\texit\n\tthen\n\t2dup s\" beastie\" compare-insensitive 0= if\n\t\t2drop\n\t\tbeastie-logo\n\t\texit\n\tthen\n\t2dup s\" none\" compare-insensitive 0= if\n\t\t2drop\n\t\t\\ no logo\n\t\texit\n\tthen\n\t2drop\n\tfbsdbw-logo\n;\n\n: acpienabled? ( -- flag )\n\ts\" acpi_load\" getenv\n\tdup -1 = if\n\t\tdrop false exit\n\tthen\n\ts\" YES\" compare-insensitive 0<> if\n\t\tfalse exit\n\tthen\n\ts\" hint.acpi.0.disabled\" getenv\n\tdup -1 <> if\n\t\ts\" 0\" compare 0<> if\n\t\t\tfalse exit\n\t\tthen\n\telse\n\t\tdrop\n\tthen\n\ttrue\n;\n\n: printmenuitem ( -- n )\n\tmenuidx @\n\t1+ dup\n\tmenuidx !\n\tmenuY @ + dup menuX @ swap at-xy\n\tmenuidx @ .\n\tmenuX @ 1+ swap at-xy\n\tmenubllt @ emit\n\tmenuidx @ 48 +\n;\n\n: beastie-menu ( -- )\n\t0 menuidx !\n\tdot menubllt !\n\t8 menuY !\n\t5 menuX !\n\tclear\n\t46 4 print-logo\n\t42 20 2 2 box\n\t13 6 at-xy .\" Welcome to FreeBSD!\"\n\tprintmenuitem .\" Boot FreeBSD [default]\" bootkey !\n\ts\" arch-i386\" environment? if\n\t\tdrop\n\t\tprintmenuitem .\" Boot FreeBSD with ACPI \" bootacpikey !\n\t\tacpienabled? if\n\t\t\t.\" disabled\"\n\t\telse\n\t\t\t.\" enabled\"\n\t\tthen\n\telse\n\t\t-2 bootacpikey !\n\tthen\n\tprintmenuitem .\" Boot FreeBSD in Safe Mode\" bootsafekey !\n\tprintmenuitem .\" Boot FreeBSD in single user mode\" bootsinglekey !\n\tprintmenuitem .\" Boot FreeBSD with verbose logging\" bootverbosekey !\n\tprintmenuitem .\" Escape to loader prompt\" escapekey !\n\ts\" arch-i386\" environment? if\n\t\tdrop\n\t\tprintmenuitem .\" Boot FreeBSD with USB keyboard\" bootusbkey !\n\telse\n\t\t-2 bootusbkey !\n\tthen\n\tprintmenuitem .\" Reboot\" rebootkey !\n\tmenuX @ 20 at-xy\n\t.\" Select option, [Enter] for default\"\n\tmenuX @ 21 at-xy\n\ts\" or [Space] to pause timer \" dup 2 - promptwidth !\n\ttype\n;\n\n: tkey\n\tseconds +\n\tbegin 1 while\n\t\tover 0<> if\n\t\t\tdup seconds u< if\n\t\t\t\tdrop\n\t\t\t\t-1\n\t\t\t\texit\n\t\t\tthen\n\t\t\tmenuX @ promptwidth @ + 21 at-xy dup seconds - .\n\t\tthen\n\t\tkey? if\n\t\t\tdrop\n\t\t\tkey\n\t\t\texit\n\t\tthen\n\t50 ms\n\trepeat\n;\n\nset-current\n\n: beastie-start\n\ts\" beastie_disable\" getenv\n\tdup -1 <> if\n\t\ts\" YES\" compare-insensitive 0= if\n\t\t\texit\n\t\tthen\n\telse\n\t\tdrop\n\tthen\n\tbeastie-menu\n\ts\" autoboot_delay\" getenv\n\tdup -1 = if\n\t\tdrop\n\t\t10\n\telse\n\t\t0 0 2swap >number drop drop drop\n\tthen\n\tbegin\n\t\tdup tkey\n\t\t0 25 at-xy\n\t\tdup 32 = if nip 0 swap then\n\t\tdup -1 = if 0 boot then\n\t\tdup 13 = if 0 boot then\n\t\tdup bootkey @ = if 0 boot then\n\t\tdup bootacpikey @ = if\n\t\t\tacpienabled? if\n\t\t\t\ts\" acpi_load\" unsetenv\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\telse\n\t\t\t\ts\" YES\" s\" acpi_load\" setenv\n\t\t\t\ts\" 0\" s\" hint.acpi.0.disabled\" setenv\n\t\t\tthen\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootusbkey @ = if\n\t\t\ts\" 0x1\" s\" hint.atkbd.0.flags\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootsafekey @ = if\n\t\t\ts\" arch-i386\" environment? if\n\t\t\t\tdrop\n\t\t\t\ts\" acpi_load\" unsetenv\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\t\ts\" 1\" s\" hint.apic.0.disabled\" setenv\n\t\t\tthen\n\t\t\ts\" 0\" s\" hw.ata.ata_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.atapi_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.wc\" setenv\n\t\t\ts\" 0\" s\" hw.eisa_slots\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootverbosekey @ = if\n\t\t\ts\" YES\" s\" boot_verbose\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootsinglekey @ = if\n\t\t\ts\" YES\" s\" boot_single\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup escapekey @ = if\n\t\t\t2drop\n\t\t\ts\" NO\" s\" autoboot_delay\" setenv\n\t\t\texit\n\t\tthen\n\t\trebootkey @ = if 0 reboot then\n\tagain\n;\n\nprevious\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"049e6a81c83ff5402bd64c65dc6f591e7bfb003e","subject":"Flag when ACPI has been disabled by the user so that sysinstall can do something with it.","message":"Flag when ACPI has been disabled by the user so that sysinstall can do\nsomething with it.\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/beastie.4th","new_file":"sys\/boot\/forth\/beastie.4th","new_contents":"\\ Copyright (c) 2003 Scott Long \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\nmarker task-beastie.4th\n\ninclude \/boot\/screen.4th\ninclude \/boot\/frames.4th\n\nhide\n\nvariable menuidx\nvariable menubllt\nvariable menuX\nvariable menuY\nvariable promptwidth\n\nvariable bootkey\nvariable bootacpikey\nvariable bootsafekey\nvariable bootverbosekey\nvariable bootsinglekey\nvariable escapekey\nvariable rebootkey\n\n46 constant dot\n\n\\ The BSD Daemon. He is 19 rows high and 34 columns wide\n: print-beastie ( x y -- )\n\t2dup at-xy .\" , ,\" 1+\n\t2dup at-xy .\" \/( )`\" 1+\n\t2dup at-xy .\" \\\\ \\\\___ \/ |\" 1+\n\t2dup at-xy .\" \/- _ `-\/ '\" 1+\n\t2dup at-xy .\" (\/\\\\\/ \\\\ \\\\ \/\\\\\" 1+\n\t2dup at-xy .\" \/ \/ | ` \\\\\" 1+\n\t2dup at-xy .\" O O ) \/ |\" 1+\n\t2dup at-xy .\" `-^--'`< '\" 1+\n\t2dup at-xy .\" (_.) _ ) \/\" 1+\n\t2dup at-xy .\" `.___\/` \/\" 1+\n\t2dup at-xy .\" `-----' \/\" 1+\n\t2dup at-xy .\" <----. __ \/ __ \\\\\" 1+\n\t2dup at-xy .\" <----|====O)))==) \\\\) \/====\" 1+\n\t2dup at-xy .\" <----' `--' `.__,' \\\\\" 1+\n\t2dup at-xy .\" | |\" 1+\n\t2dup at-xy .\" \\\\ \/ \/\\\\\" 1+\n\t2dup at-xy .\" ______( (_ \/ \\\\______\/\" 1+\n\t2dup at-xy .\" ,' ,-----' |\" 1+\n\t at-xy .\" `--{__________)\"\n;\n\n: acpienabled? ( -- flag )\n\ts\" acpi_load\" getenv\n\tdup -1 = if\n\t\tdrop false exit\n\tthen\n\ts\" YES\" compare-insensitive 0<> if\n\t\tfalse exit\n\tthen\n\ts\" hint.acpi.0.disabled\" getenv\n\tdup -1 <> if\n\t\ts\" 0\" compare 0<> if\n\t\t\tfalse exit\n\t\tthen\n\tthen\n\ttrue\n;\n\n: printmenuitem ( -- n )\n\tmenuidx @\n\t1+ dup\n\tmenuidx !\n\tmenuY @ + dup menuX @ swap at-xy\n\tmenuidx @ .\n\tmenuX @ 1+ swap at-xy\n\tmenubllt @ emit\n\tmenuidx @ 48 +\n;\n\n: beastie-menu ( -- )\n\t0 menuidx !\n\tdot menubllt !\n\t8 menuY !\n\t5 menuX !\n\tclear\n\t46 4 print-beastie\n\t42 20 2 2 box\n\t13 6 at-xy .\" Welcome to FreeBSD!\"\n\tprintmenuitem .\" Boot FreeBSD [default]\" bootkey !\n\ts\" arch-i386\" environment? if\n\t\tprintmenuitem .\" Boot FreeBSD with ACPI \" bootacpikey !\n\t\tacpienabled? if\n\t\t\t.\" disabled\"\n\t\telse\n\t\t\t.\" enabled\"\n\t\tthen\n\telse\n\t\t-2 bootacpikey !\n\tthen\n\tprintmenuitem .\" Boot FreeBSD in Safe Mode\" bootsafekey !\n\tprintmenuitem .\" Boot FreeBSD in single user mode\" bootsinglekey !\n\tprintmenuitem .\" Boot FreeBSD with verbose logging\" bootverbosekey !\n\tprintmenuitem .\" Escape to loader prompt\" escapekey !\n\tprintmenuitem .\" Reboot\" rebootkey !\n\tmenuX @ 20 at-xy\n\t.\" Select option, [Enter] for default\"\n\tmenuX @ 21 at-xy\n\ts\" or [Space] to pause timer \" dup 2 - promptwidth !\n\ttype\n;\n\n: tkey\n\tdup\n\tseconds +\n\tbegin 1 while\n\t\tover 0<> if\n\t\t\tdup seconds u< if\n\t\t\t\tdrop\n\t\t\t\t-1\n\t\t\t\texit\n\t\t\tthen\n\t\t\tmenuX @ promptwidth @ + 21 at-xy dup seconds - .\n\t\tthen\n\t\tkey? if\n\t\t\tdrop\n\t\t\tkey\n\t\t\texit\n\t\tthen\n\t50 ms\n\trepeat\n;\n\nset-current\n\n: beastie-start\n\tbeastie-menu\n\ts\" autoboot_delay\" getenv\n\tdup -1 = if\n\t\tdrop\n\t\t10\n\telse\n\t\t0 0 2swap >number drop drop drop\n\tthen\n\tbegin true while\n\t\tdup tkey\n\t\t0 25 at-xy\n\t\tdup 32 = if nip 0 swap then\n\t\tdup -1 = if s\" boot\" evaluate then\n\t\tdup 13 = if s\" boot\" evaluate then\n\t\tdup bootkey @ = if s\" boot\" evaluate then\n\t\tdup bootacpikey @ = if\n\t\t\tacpienabled? if\n\t\t\t\ts\" acpi_load\" unsetenv\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\telse\n\t\t\t\ts\" YES\" s\" acpi_load\" setenv\n\t\t\t\ts\" 0\" s\" hint.acpi.0.disabled\" setenv\n\t\t\tthen\n\t\t\ts\" boot\" evaluate\n\t\tthen\n\t\tdup bootsafekey @ = if\n\t\t\ts\" arch-i386\" environment? if\n\t\t\t\ts\" acpi_load\" unsetenv\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\tthen\n\t\t\ts\" 0\" s\" hw.ata.ata_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.atapi_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.wc\" setenv\n\t\t\ts\" 0\" s\" hw.eisa_slots\" setenv\n\t\t\ts\" boot\" evaluate\n\t\tthen\n\t\tdup bootverbosekey @ = if\n\t\t\ts\" YES\" s\" boot_verbose\" setenv\n\t\t\ts\" boot\" evaluate\n\t\tthen\n\t\tdup bootsinglekey @ = if\n\t\t\ts\" YES\" s\" boot_single\" setenv\n\t\t\ts\" boot\" evaluate\n\t\tthen\n\t\tdup escapekey @ = if 2drop exit then\n\t\trebootkey @ = if s\" reboot\" evaluate then\n\trepeat\n;\n\nprevious\n","old_contents":"\\ Copyright (c) 2003 Scott Long \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\nmarker task-beastie.4th\n\ninclude \/boot\/screen.4th\ninclude \/boot\/frames.4th\n\nhide\n\nvariable menuidx\nvariable menubllt\nvariable menuX\nvariable menuY\nvariable promptwidth\n\nvariable bootkey\nvariable bootacpikey\nvariable bootsafekey\nvariable bootverbosekey\nvariable bootsinglekey\nvariable escapekey\nvariable rebootkey\n\n46 constant dot\n\n\\ The BSD Daemon. He is 19 rows high and 34 columns wide\n: print-beastie ( x y -- )\n\t2dup at-xy .\" , ,\" 1+\n\t2dup at-xy .\" \/( )`\" 1+\n\t2dup at-xy .\" \\\\ \\\\___ \/ |\" 1+\n\t2dup at-xy .\" \/- _ `-\/ '\" 1+\n\t2dup at-xy .\" (\/\\\\\/ \\\\ \\\\ \/\\\\\" 1+\n\t2dup at-xy .\" \/ \/ | ` \\\\\" 1+\n\t2dup at-xy .\" O O ) \/ |\" 1+\n\t2dup at-xy .\" `-^--'`< '\" 1+\n\t2dup at-xy .\" (_.) _ ) \/\" 1+\n\t2dup at-xy .\" `.___\/` \/\" 1+\n\t2dup at-xy .\" `-----' \/\" 1+\n\t2dup at-xy .\" <----. __ \/ __ \\\\\" 1+\n\t2dup at-xy .\" <----|====O)))==) \\\\) \/====\" 1+\n\t2dup at-xy .\" <----' `--' `.__,' \\\\\" 1+\n\t2dup at-xy .\" | |\" 1+\n\t2dup at-xy .\" \\\\ \/ \/\\\\\" 1+\n\t2dup at-xy .\" ______( (_ \/ \\\\______\/\" 1+\n\t2dup at-xy .\" ,' ,-----' |\" 1+\n\t at-xy .\" `--{__________)\"\n;\n\n: acpienabled? ( -- flag )\n\ts\" acpi_load\" getenv\n\tdup -1 = if\n\t\tdrop false exit\n\tthen\n\ts\" YES\" compare-insensitive 0<> if\n\t\tfalse exit\n\tthen\n\ts\" hint.acpi.0.disabled\" getenv\n\tdup -1 <> if\n\t\ts\" 0\" compare 0<> if\n\t\t\tfalse exit\n\t\tthen\n\tthen\n\ttrue\n;\n\n: printmenuitem ( -- n )\n\tmenuidx @\n\t1+ dup\n\tmenuidx !\n\tmenuY @ + dup menuX @ swap at-xy\n\tmenuidx @ .\n\tmenuX @ 1+ swap at-xy\n\tmenubllt @ emit\n\tmenuidx @ 48 +\n;\n\n: beastie-menu ( -- )\n\t0 menuidx !\n\tdot menubllt !\n\t8 menuY !\n\t5 menuX !\n\tclear\n\t46 4 print-beastie\n\t42 20 2 2 box\n\t13 6 at-xy .\" Welcome to FreeBSD!\"\n\tprintmenuitem .\" Boot FreeBSD [default]\" bootkey !\n\ts\" arch-i386\" environment? if\n\t\tprintmenuitem .\" Boot FreeBSD with ACPI \" bootacpikey !\n\t\tacpienabled? if\n\t\t\t.\" disabled\"\n\t\telse\n\t\t\t.\" enabled\"\n\t\tthen\n\telse\n\t\t-2 bootacpikey !\n\tthen\n\tprintmenuitem .\" Boot FreeBSD in Safe Mode\" bootsafekey !\n\tprintmenuitem .\" Boot FreeBSD in single user mode\" bootsinglekey !\n\tprintmenuitem .\" Boot FreeBSD with verbose logging\" bootverbosekey !\n\tprintmenuitem .\" Escape to loader prompt\" escapekey !\n\tprintmenuitem .\" Reboot\" rebootkey !\n\tmenuX @ 20 at-xy\n\t.\" Select option, [Enter] for default\"\n\tmenuX @ 21 at-xy\n\ts\" or [Space] to pause timer \" dup 2 - promptwidth !\n\ttype\n;\n\n: tkey\n\tdup\n\tseconds +\n\tbegin 1 while\n\t\tover 0<> if\n\t\t\tdup seconds u< if\n\t\t\t\tdrop\n\t\t\t\t-1\n\t\t\t\texit\n\t\t\tthen\n\t\t\tmenuX @ promptwidth @ + 21 at-xy dup seconds - .\n\t\tthen\n\t\tkey? if\n\t\t\tdrop\n\t\t\tkey\n\t\t\texit\n\t\tthen\n\t50 ms\n\trepeat\n;\n\nset-current\n\n: beastie-start\n\tbeastie-menu\n\ts\" autoboot_delay\" getenv\n\tdup -1 = if\n\t\tdrop\n\t\t10\n\telse\n\t\t0 0 2swap >number drop drop drop\n\tthen\n\tbegin true while\n\t\tdup tkey\n\t\t0 25 at-xy\n\t\tdup 32 = if nip 0 swap then\n\t\tdup -1 = if s\" boot\" evaluate then\n\t\tdup 13 = if s\" boot\" evaluate then\n\t\tdup bootkey @ = if s\" boot\" evaluate then\n\t\tdup bootacpikey @ = if\n\t\t\tacpienabled? if\n\t\t\t\ts\" acpi_load\" unsetenv\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\telse\n\t\t\t\ts\" YES\" s\" acpi_load\" setenv\n\t\t\t\ts\" 0\" s\" hint.acpi.0.disabled\" setenv\n\t\t\tthen\n\t\t\ts\" boot\" evaluate\n\t\tthen\n\t\tdup bootsafekey @ = if\n\t\t\ts\" arch-i386\" environment? if\n\t\t\t\ts\" acpi_load\" unsetenv\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\tthen\n\t\t\ts\" 0\" s\" hw.ata.ata_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.atapi_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.wc\" setenv\n\t\t\ts\" 0\" s\" hw.eisa_slots\" setenv\n\t\t\ts\" boot\" evaluate\n\t\tthen\n\t\tdup bootverbosekey @ = if\n\t\t\ts\" YES\" s\" boot_verbose\" setenv\n\t\t\ts\" boot\" evaluate\n\t\tthen\n\t\tdup bootsinglekey @ = if\n\t\t\ts\" YES\" s\" boot_single\" setenv\n\t\t\ts\" boot\" evaluate\n\t\tthen\n\t\tdup escapekey @ = if 2drop exit then\n\t\trebootkey @ = if s\" reboot\" evaluate then\n\trepeat\n;\n\nprevious\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"c7db0c1f9014e4df9be137e5b42e314bf6d9afb0","subject":"?TWO-ADJACENT-1-BITS tests added","message":"?TWO-ADJACENT-1-BITS tests added\n","repos":"bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas","old_file":"KataDiversion_tests.fth","new_file":"KataDiversion_tests.fth","new_contents":"\\ KataDiversion tests, in Forth\n\\ running tests:\n\\ gforth KataDiversion_tests.fth -e bye\n\nREQUIRE KataDiversion.fth\n\nVARIABLE ASSERT-COUNT\n\n: ASSERTS-INIT ( -- )\n 0 ASSERT-COUNT ! ;\n\n: ASSERTS-RESULT ( -- )\n ASSERT-COUNT @ . .\" assertions successfully passed.\" CR ;\n\n\\ destructive assert-equal\n: ASSERT-EQUAL-D ( n1 n2 -- )\n <> IF 1 ABORT\" AssertEqual: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-equal\n: ASSERT-EQUAL ( n1 n2 -- n1 n2 )\n 2DUP ASSERT-EQUAL-D ;\n\n\\ destructive assert-true\n: ASSERT-TRUE-D ( n -- )\n 0 = IF 1 ABORT\" AssertTrue: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-true\n: ASSERT-TRUE ( n -- n )\n DUP ASSERT-TRUE-D ;\n\n\\ destructive assert-false\n: ASSERT-False-D ( n -- )\n 0 <> IF 1 ABORT\" AssertFalse: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-false\n: ASSERT-FALSE ( n -- n )\n DUP ASSERT-FALSE-D ;\n\n\\ ---- tests ----\n\nASSERTS-INIT\n\n\\ ?EMPTY\nEMPTY DEPTH 0 ASSERT-EQUAL-D\nEMPTY EMPTY DEPTH 0 ASSERT-EQUAL-D\n0 EMPTY DEPTH 0 ASSERT-EQUAL-D\n1 2 3 4 EMPTY DEPTH 0 ASSERT-EQUAL-D\n\n\\ ?NEGATIVE\n-1 ?NEG ASSERT-TRUE-D\n 0 ?NEG ASSERT-TRUE-D\n 1 ?NEG ASSERT-FALSE-D\n\n\\ ?MAX-NB\n-1 ?MAX-NB 0 ASSERT-EQUAL-D\n 0 ?MAX-NB 0 ASSERT-EQUAL-D\n 1 ?MAX-NB 2 ASSERT-EQUAL-D\n 2 ?MAX-NB 4 ASSERT-EQUAL-D\n 3 ?MAX-NB 8 ASSERT-EQUAL-D\n\n\\ LOG2\n 1 LOG2 0 ASSERT-EQUAL-D\n 2 LOG2 1 ASSERT-EQUAL-D\n 3 LOG2 1 ASSERT-EQUAL-D\n 4 LOG2 2 ASSERT-EQUAL-D\n 5 LOG2 2 ASSERT-EQUAL-D\n 8 LOG2 3 ASSERT-EQUAL-D\n42 LOG2 5 ASSERT-EQUAL-D\n\n 1 ?TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n 2 ?TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n 3 ?TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n 6 ?TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n 7 ?TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n 8 ?TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n 11 ?TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n 65 ?TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n3072 ?TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n\nASSERTS-RESULT\n\\ ---------\n\n\n","old_contents":"\\ KataDiversion tests, in Forth\n\\ running tests:\n\\ gforth KataDiversion_tests.fth -e bye\n\nREQUIRE KataDiversion.fth\n\nVARIABLE ASSERT-COUNT\n\n: ASSERTS-INIT ( -- )\n 0 ASSERT-COUNT ! ;\n\n: ASSERTS-RESULT ( -- )\n ASSERT-COUNT @ . .\" assertions successfully passed.\" CR ;\n\n\\ destructive assert-equal\n: ASSERT-EQUAL-D ( n1 n2 -- )\n <> IF 1 ABORT\" AssertEqual: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-equal\n: ASSERT-EQUAL ( n1 n2 -- n1 n2 )\n 2DUP ASSERT-EQUAL-D ;\n\n\\ destructive assert-true\n: ASSERT-TRUE-D ( n -- )\n 0 = IF 1 ABORT\" AssertTrue: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-true\n: ASSERT-TRUE ( n -- n )\n DUP ASSERT-TRUE-D ;\n\n\\ destructive assert-false\n: ASSERT-False-D ( n -- )\n 0 <> IF 1 ABORT\" AssertFalse: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-false\n: ASSERT-FALSE ( n -- n )\n DUP ASSERT-FALSE-D ;\n\n\\ ---- tests ----\n\nASSERTS-INIT\n\n\\ ?EMPTY\nEMPTY DEPTH 0 ASSERT-EQUAL-D\nEMPTY EMPTY DEPTH 0 ASSERT-EQUAL-D\n0 EMPTY DEPTH 0 ASSERT-EQUAL-D\n1 2 3 4 EMPTY DEPTH 0 ASSERT-EQUAL-D\n\n\\ ?NEGATIVE\n-1 ?NEG ASSERT-TRUE-D\n 0 ?NEG ASSERT-TRUE-D\n 1 ?NEG ASSERT-FALSE-D\n\n\\ ?MAX-NB\n-1 ?MAX-NB 0 ASSERT-EQUAL-D\n 0 ?MAX-NB 0 ASSERT-EQUAL-D\n 1 ?MAX-NB 2 ASSERT-EQUAL-D\n 2 ?MAX-NB 4 ASSERT-EQUAL-D\n 3 ?MAX-NB 8 ASSERT-EQUAL-D\n\n\\ LOG2\n 1 LOG2 0 ASSERT-EQUAL-D\n 2 LOG2 1 ASSERT-EQUAL-D\n 3 LOG2 1 ASSERT-EQUAL-D\n 4 LOG2 2 ASSERT-EQUAL-D\n 5 LOG2 2 ASSERT-EQUAL-D\n 8 LOG2 3 ASSERT-EQUAL-D\n42 LOG2 5 ASSERT-EQUAL-D\n\n\\ DEC2BIN\n\n 0 DEC2BIN 0 ASSERT-EQUAL-D\n 1 DEC2BIN 1 ASSERT-EQUAL-D\n 2 DEC2BIN 0 ASSERT-EQUAL-D ( 2 -> 10 )\n 1 ASSERT-EQUAL-D\n11 DEC2BIN 1 ASSERT-EQUAL-D ( 11 -> 1011 )\n 1 ASSERT-EQUAL-D\n 0 ASSERT-EQUAL-D\n 1 ASSERT-EQUAL-D\n\n\nASSERTS-RESULT\n\\ ---------\n\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"f4c0ee43cbf5ab55dee47e96f24114690287a186","subject":"add ZERO (aka ERASE) function","message":"add ZERO (aka ERASE) function","repos":"cetic\/python-msp430-tools,cetic\/python-msp430-tools,cetic\/python-msp430-tools","old_file":"msp430\/asm\/forth\/_builtins.forth","new_file":"msp430\/asm\/forth\/_builtins.forth","new_contents":"( Implementations of builtins.\n These functions are provided for the host in the msp430.asm.forth module. The\n implementations here are for the target.\n\n vi:ft=forth\n)\n\n( ----- low level supporting functions ----- )\n\nCODE LIT\n .\" \\t push @IP+ \\t; copy value from thread to stack \\n \"\n ASM-NEXT\nEND-CODE\n\nCODE BRANCH\n .\" \\t add @IP, IP \\n \"\n ASM-NEXT\nEND-CODE\n\nCODE BRANCH0\n .\" \\t mov @IP+, W \\t; get offset \\n \"\n .\" \\t tst 0(SP) \\t; check TOS \\n \"\n .\" \\t jnz .Lnjmp \\t; skip next if non zero \\n \"\n .\" \\t decd IP \\t; offset is relative to position of offset, correct \\n \"\n .\" \\t add W, IP \\t; adjust IP \\n \"\n.\" .Lnjmp: \"\n ASM-DROP\n ASM-NEXT\nEND-CODE\n\n( ----- Stack ops ----- )\n\nCODE DROP\n .\" \\t incd SP\\n \"\n ASM-NEXT\nEND-CODE\n\nCODE DUP\n( .\" \\t push @SP\\n \" )\n .\" \\t mov @SP, W\\n \"\n .\" \\t push W\\n \"\n ASM-NEXT\nEND-CODE\n\nCODE OVER\n( .\" \\t push 2(TOS\\n \" )\n .\" \\t mov 2(SP), W\\n \"\n .\" \\t push W\\n \"\n ASM-NEXT\nEND-CODE\n\n( Push a copy of the N'th element )\nCODE PICK ( n - n )\n TOS->W ( get element number from stack )\n .\" \\t rla W \" LF ( multiply by 2 -> 2 byte \/ cell )\n .\" \\t add SP, W \" LF ( calculate address on stack )\n .\" \\t push 0(W) \" LF\n ASM-NEXT\nEND-CODE\n\nCODE SWAP ( y x - x y )\n .\" \\t mov 2(SP), W \" LF\n .\" \\t mov 0(SP), 2(SP) \" LF\n .\" \\t mov W, 0(SP) \" LF\n ASM-NEXT\nEND-CODE\n\n( ----- Return Stack ops ----- )\n\n( Move x to the return stack. )\nCODE >R ( x -- ) ( R: -- x )\n .\" \\t decd RTOS \\t; make room on the return stack\\n \"\n .\" \\t pop 0(RTOS) \\t; pop value and put it on return stack\\n \"\n ASM-NEXT\nEND-CODE\n\n( Move x from the return stack to the data stack. )\nCODE R> ( -- x ) ( R: x -- )\n .\" \\t push @RTOS+ \\t; pop from return stack, push to data stack\\n \"\n ASM-NEXT\nEND-CODE\n\n( Copy x from the return stack to the data stack. )\nCODE R@ ( -- x ) ( R: x -- x )\n .\" \\t push @RTOS \\t; push copy of RTOS to data stack\\n \"\n ASM-NEXT\nEND-CODE\n\n\n( ----- MATH ----- )\n\nCODE +\n .\" \\t add 0(SP), 2(SP) \\t; y = x + y \" LF\n ASM-DROP\n ASM-NEXT\nEND-CODE\n\nCODE -\n .\" \\t sub 0(SP), 2(SP) \\t; y = y - x \" LF\n ASM-DROP\n ASM-NEXT\nEND-CODE\n\n( ----- bit - ops ----- )\nCODE AND\n .\" \\t and 0(SP), 2(SP) \\t; y = x & y \" LF\n ASM-DROP\n ASM-NEXT\nEND-CODE\n\nCODE OR\n .\" \\t bis 0(SP), 2(SP) \\t; y = x | y \" LF\n ASM-DROP\n ASM-NEXT\nEND-CODE\n\nCODE XOR\n .\" \\t xor 0(SP), 2(SP) \\t; y = x ^ y \" LF\n ASM-DROP\n ASM-NEXT\nEND-CODE\n\nCODE INVERT\n .\" \\t inv 0(SP) \\t; x = ~x \" LF\n ASM-NEXT\nEND-CODE\n\n\n( Multiply by two (arithmetic left shift) )\nCODE 2* ( n -- n*2 )\n .\" \\t rla 0(SP) \\t; x <<= 1 \" LF\n ASM-NEXT\nEND-CODE\n\n( Divide by two (arithmetic right shift) )\nCODE 2\/ ( n -- n\/2 )\n .\" \\t rra 0(SP) \\t; x >>= 1 \" LF\n ASM-NEXT\nEND-CODE\n\n\n( Logical left shift by u bits )\nCODE LSHIFT ( n u -- n*2^u )\n TOS->W\n .\" .lsh:\\t clrc \" LF\n .\" \\t rlc 0(SP) \\t; x <<= 1 \" LF\n .\" \\t dec W \" LF\n .\" \\t jnz .lsh W \" LF\n ASM-NEXT\nEND-CODE\n\n( Logical right shift by u bits )\nCODE RSHIFT ( n -- n\/2^-u )\n TOS->W\n .\" .rsh:\\t clrc \" LF\n .\" \\t rrc 0(SP) \\t; x >>= 1 \" LF\n .\" \\t dec W \" LF\n .\" \\t jnz .rsh W \" LF\n ASM-NEXT\nEND-CODE\n\n( ----- Logic ops ----- )\n( include normalize to boolean )\n\nCODE NOT\n .\" \\t tst 0(SP) \" LF\n .\" \\t jnz .not0 \" LF\n .\" \\t mov \\x23 -1, 0(SP) \" LF ( replace TOS w\/ result )\n .\" \\t jmp .not2 \" LF\n .\" .not0: \" LF\n .\" \\t mov \\x23 0, 0(SP) \" LF ( replace TOS w\/ result )\n .\" .not2: \" LF\n ASM-NEXT\nEND-CODE\n\n( ---------------------------------------------------\n \"*\"\n \"\/\"\n)\n( ----- Compare ----- )\nCODE cmp_set_true ( n - n )\n .\" \\t mov \\x23 -1, 0(SP) \" LF ( replace argument w\/ result )\n ASM-NEXT\nEND-CODE\n\nCODE cmp_set_false\n .\" \\t mov \\x23 0, 0(SP) \" LF ( replace argument w\/ result )\n ASM-NEXT\nEND-CODE\n\n\nCODE cmp_true\n ASM-DROP ( remove 1nd argument )\n .\" \\t mov \\x23 -1, 0(SP) \" LF ( replace 2nd argument w\/ result )\n ASM-NEXT\nEND-CODE\n\nCODE cmp_false\n ASM-DROP ( remove 1nd argument )\n .\" \\t mov \\x23 0, 0(SP) \" LF ( replace 2nd argument w\/ result )\n ASM-NEXT\nEND-CODE\n\n\nCODE <\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(SP), 2(SP) \" LF\n .\" \\t jl _cmp_true \" LF\n .\" \\t jmp _cmp_false \" LF\nEND-CODE\n\nCODE >\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 2(SP), 0(SP) \" LF\n .\" \\t jl _cmp_true \" LF\n .\" \\t jmp _cmp_false \" LF\nEND-CODE\n\nCODE <=\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(SP), 2(SP) \" LF\n .\" \\t jge _cmp_false \" LF\n .\" \\t jmp _cmp_true \" LF\nEND-CODE\n\nCODE >=\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(SP), 2(SP) \" LF\n .\" \\t jge _cmp_true \" LF\n .\" \\t jmp _cmp_false \" LF\nEND-CODE\n\nCODE ==\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(SP), 2(SP) \" LF\n .\" \\t jeq _cmp_true \" LF\n .\" \\t jmp _cmp_false \" LF\nEND-CODE\n\n( XXX alias for == )\nCODE =\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(SP), 2(SP) \" LF\n .\" \\t jeq _cmp_true \" LF\n .\" \\t jmp _cmp_false \" LF\nEND-CODE\n\nCODE !=\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(SP), 2(SP) \" LF\n .\" \\t jne _cmp_true \" LF\n .\" \\t jmp _cmp_false \" LF\nEND-CODE\n\n\nCODE 0=\n DEPENDS-ON cmp_set_true\n DEPENDS-ON cmp_set_false\n .\" \\t tst 0(SP) \" LF\n .\" \\t jz _cmp_set_true \" LF\n .\" \\t jmp _cmp_set_false \" LF\nEND-CODE\n\nCODE 0>\n DEPENDS-ON cmp_set_true\n DEPENDS-ON cmp_set_false\n .\" \\t tst 0(SP) \" LF\n .\" \\t jn _cmp_set_false \" LF\n .\" \\t jmp _cmp_set_true \" LF\nEND-CODE\n\n( --------------------------------------------------- )\n\n( XXX Forth name ERASE conflicts with FCTL bit name in MSP430 )\n( Erase memory area )\nCODE ZERO ( adr u - )\n TOS->W ( count )\n TOS->R15 ( address )\n .\" .erase_loop: clr.b 0(R15)\\n\"\n .\" \\t inc R15\\n\"\n .\" \\t dec W\\n\"\n .\" \\t jnz .erase_loop\\n\"\n ASM-NEXT\nEND-CODE\n\n( --------------------------------------------------- )\n( helper for .\" )\nCODE __write_text\n .\" \\t mov @IP+, R15\\n\"\n .\" \\t call \\x23 write\\n\"\n ASM-NEXT\nEND-CODE\n\n","old_contents":"( Implementations of builtins.\n These functions are provided for the host in the msp430.asm.forth module. The\n implementations here are for the target.\n\n vi:ft=forth\n)\n\n( ----- low level supporting functions ----- )\n\nCODE LIT\n .\" \\t push @IP+ \\t; copy value from thread to stack \\n \"\n ASM-NEXT\nEND-CODE\n\nCODE BRANCH\n .\" \\t add @IP, IP \\n \"\n ASM-NEXT\nEND-CODE\n\nCODE BRANCH0\n .\" \\t mov @IP+, W \\t; get offset \\n \"\n .\" \\t tst 0(SP) \\t; check TOS \\n \"\n .\" \\t jnz .Lnjmp \\t; skip next if non zero \\n \"\n .\" \\t decd IP \\t; offset is relative to position of offset, correct \\n \"\n .\" \\t add W, IP \\t; adjust IP \\n \"\n.\" .Lnjmp: \"\n ASM-DROP\n ASM-NEXT\nEND-CODE\n\n( ----- Stack ops ----- )\n\nCODE DROP\n .\" \\t incd SP\\n \"\n ASM-NEXT\nEND-CODE\n\nCODE DUP\n( .\" \\t push @SP\\n \" )\n .\" \\t mov @SP, W\\n \"\n .\" \\t push W\\n \"\n ASM-NEXT\nEND-CODE\n\nCODE OVER\n( .\" \\t push 2(TOS\\n \" )\n .\" \\t mov 2(SP), W\\n \"\n .\" \\t push W\\n \"\n ASM-NEXT\nEND-CODE\n\n( Push a copy of the N'th element )\nCODE PICK ( n - n )\n TOS->W ( get element number from stack )\n .\" \\t rla W \" LF ( multiply by 2 -> 2 byte \/ cell )\n .\" \\t add SP, W \" LF ( calculate address on stack )\n .\" \\t push 0(W) \" LF\n ASM-NEXT\nEND-CODE\n\nCODE SWAP ( y x - x y )\n .\" \\t mov 2(SP), W \" LF\n .\" \\t mov 0(SP), 2(SP) \" LF\n .\" \\t mov W, 0(SP) \" LF\n ASM-NEXT\nEND-CODE\n\n( ----- Return Stack ops ----- )\n\n( Move x to the return stack. )\nCODE >R ( x -- ) ( R: -- x )\n .\" \\t decd RTOS \\t; make room on the return stack\\n \"\n .\" \\t pop 0(RTOS) \\t; pop value and put it on return stack\\n \"\n ASM-NEXT\nEND-CODE\n\n( Move x from the return stack to the data stack. )\nCODE R> ( -- x ) ( R: x -- )\n .\" \\t push @RTOS+ \\t; pop from return stack, push to data stack\\n \"\n ASM-NEXT\nEND-CODE\n\n( Copy x from the return stack to the data stack. )\nCODE R@ ( -- x ) ( R: x -- x )\n .\" \\t push @RTOS \\t; push copy of RTOS to data stack\\n \"\n ASM-NEXT\nEND-CODE\n\n\n( ----- MATH ----- )\n\nCODE +\n .\" \\t add 0(SP), 2(SP) \\t; y = x + y \" LF\n ASM-DROP\n ASM-NEXT\nEND-CODE\n\nCODE -\n .\" \\t sub 0(SP), 2(SP) \\t; y = y - x \" LF\n ASM-DROP\n ASM-NEXT\nEND-CODE\n\n( ----- bit - ops ----- )\nCODE AND\n .\" \\t and 0(SP), 2(SP) \\t; y = x & y \" LF\n ASM-DROP\n ASM-NEXT\nEND-CODE\n\nCODE OR\n .\" \\t bis 0(SP), 2(SP) \\t; y = x | y \" LF\n ASM-DROP\n ASM-NEXT\nEND-CODE\n\nCODE XOR\n .\" \\t xor 0(SP), 2(SP) \\t; y = x ^ y \" LF\n ASM-DROP\n ASM-NEXT\nEND-CODE\n\nCODE INVERT\n .\" \\t inv 0(SP) \\t; x = ~x \" LF\n ASM-NEXT\nEND-CODE\n\n\n( Multiply by two (arithmetic left shift) )\nCODE 2* ( n -- n*2 )\n .\" \\t rla 0(SP) \\t; x <<= 1 \" LF\n ASM-NEXT\nEND-CODE\n\n( Divide by two (arithmetic right shift) )\nCODE 2\/ ( n -- n\/2 )\n .\" \\t rra 0(SP) \\t; x >>= 1 \" LF\n ASM-NEXT\nEND-CODE\n\n\n( Logical left shift by u bits )\nCODE LSHIFT ( n u -- n*2^u )\n TOS->W\n .\" .lsh:\\t clrc \" LF\n .\" \\t rlc 0(SP) \\t; x <<= 1 \" LF\n .\" \\t dec W \" LF\n .\" \\t jnz .lsh W \" LF\n ASM-NEXT\nEND-CODE\n\n( Logical right shift by u bits )\nCODE RSHIFT ( n -- n\/2^-u )\n TOS->W\n .\" .rsh:\\t clrc \" LF\n .\" \\t rrc 0(SP) \\t; x >>= 1 \" LF\n .\" \\t dec W \" LF\n .\" \\t jnz .rsh W \" LF\n ASM-NEXT\nEND-CODE\n\n( ----- Logic ops ----- )\n( include normalize to boolean )\n\nCODE NOT\n .\" \\t tst 0(SP) \" LF\n .\" \\t jnz .not0 \" LF\n .\" \\t mov \\x23 -1, 0(SP) \" LF ( replace TOS w\/ result )\n .\" \\t jmp .not2 \" LF\n .\" .not0: \" LF\n .\" \\t mov \\x23 0, 0(SP) \" LF ( replace TOS w\/ result )\n .\" .not2: \" LF\n ASM-NEXT\nEND-CODE\n\n( ---------------------------------------------------\n \"*\"\n \"\/\"\n)\n( ----- Compare ----- )\nCODE cmp_set_true ( n - n )\n .\" \\t mov \\x23 -1, 0(SP) \" LF ( replace argument w\/ result )\n ASM-NEXT\nEND-CODE\n\nCODE cmp_set_false\n .\" \\t mov \\x23 0, 0(SP) \" LF ( replace argument w\/ result )\n ASM-NEXT\nEND-CODE\n\n\nCODE cmp_true\n ASM-DROP ( remove 1nd argument )\n .\" \\t mov \\x23 -1, 0(SP) \" LF ( replace 2nd argument w\/ result )\n ASM-NEXT\nEND-CODE\n\nCODE cmp_false\n ASM-DROP ( remove 1nd argument )\n .\" \\t mov \\x23 0, 0(SP) \" LF ( replace 2nd argument w\/ result )\n ASM-NEXT\nEND-CODE\n\n\nCODE <\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(SP), 2(SP) \" LF\n .\" \\t jl _cmp_true \" LF\n .\" \\t jmp _cmp_false \" LF\nEND-CODE\n\nCODE >\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 2(SP), 0(SP) \" LF\n .\" \\t jl _cmp_true \" LF\n .\" \\t jmp _cmp_false \" LF\nEND-CODE\n\nCODE <=\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(SP), 2(SP) \" LF\n .\" \\t jge _cmp_false \" LF\n .\" \\t jmp _cmp_true \" LF\nEND-CODE\n\nCODE >=\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(SP), 2(SP) \" LF\n .\" \\t jge _cmp_true \" LF\n .\" \\t jmp _cmp_false \" LF\nEND-CODE\n\nCODE ==\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(SP), 2(SP) \" LF\n .\" \\t jeq _cmp_true \" LF\n .\" \\t jmp _cmp_false \" LF\nEND-CODE\n\n( XXX alias for == )\nCODE =\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(SP), 2(SP) \" LF\n .\" \\t jeq _cmp_true \" LF\n .\" \\t jmp _cmp_false \" LF\nEND-CODE\n\nCODE !=\n DEPENDS-ON cmp_true\n DEPENDS-ON cmp_false\n .\" \\t cmp 0(SP), 2(SP) \" LF\n .\" \\t jne _cmp_true \" LF\n .\" \\t jmp _cmp_false \" LF\nEND-CODE\n\n\nCODE 0=\n DEPENDS-ON cmp_set_true\n DEPENDS-ON cmp_set_false\n .\" \\t tst 0(SP) \" LF\n .\" \\t jz _cmp_set_true \" LF\n .\" \\t jmp _cmp_set_false \" LF\nEND-CODE\n\nCODE 0>\n DEPENDS-ON cmp_set_true\n DEPENDS-ON cmp_set_false\n .\" \\t tst 0(SP) \" LF\n .\" \\t jn _cmp_set_false \" LF\n .\" \\t jmp _cmp_set_true \" LF\nEND-CODE\n\n( --------------------------------------------------- )\n( helper for .\" )\nCODE __write_text\n .\" \\t mov @IP+, R15\\n\"\n .\" \\t call \\x23 write\\n\"\n ASM-NEXT\nEND-CODE\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"e0da37719f0865a9615a69889e493a2db24d92c3","subject":"report immediate for immediate : words","message":"report immediate for immediate : words\n","repos":"karlredgate\/forth,karlredgate\/forth","old_file":"see.fth","new_file":"see.fth","new_contents":"\\\n\\ Decompiler words.\n\\\n\\ TODO:\n\\\n\\ - Detect defer \/ vector: words and show target\n\\ - Detect create, does> words and dump better\n\\\n\nvocabulary decompiler\nalso decompiler definitions\n\n: tab ht emit ;\n: >target ( ip-of-branch -- adr ) ta1+ dup @ \/token * + ;\n: forward? ( ip-of-branch -- f ) ta1+ @ 0> ;\n: backward? ( ip-of-branch -- f ) ta1+ @ 0> ;\n\n: .type\n dup ['] (do) = if drop .\" do\" cr tab tab exit then\n dup ['] (loop) = if drop ta1+ cr tab .\" loop\" cr tab exit then\n dup ['] lit = if drop ta1+ .\" h# \" dup @ . exit then\n dup ['] branch = if .name ta1+ .\" h# \" dup @ . exit then\n dup ['] ?branch = if .name ta1+ .\" h# \" dup @ . exit then\n dup ['] (.\") = if\n [char] . emit [char] \" emit space\n drop ta1+ dup count type\n [char] \" emit space\n dup c@ 1+ talign + \/token -\n exit\n then\n dup ['] (abort\") = if\n .\" abort\" [char] \" emit space \n drop ta1+ dup count type [char] \" emit space\n dup c@ talign + \/token - exit\n then\n .name space\n;\n: .variable\n .\" variable \" dup .name\n .\" contents: \" >body >user @ . cr\n;\n: .constant\n dup >body @ . .\" constant \" .name cr\n;\n: .:\n .\" : \" dup .name cr\n dup\n tab >body\n begin\n dup @ ['] unnest <> while\n dup @ .type\n ta1+\n repeat\n drop cr .\" ; \"\n immediate? if .\" immediate\" then\n cr\n;\nprevious definitions\n\nalso decompiler\n: (see)\n dup @ do-variable = if .variable exit then\n dup @ do-constant = if .constant exit then\n dup @ do-primitive = if .\" primitive \" .name cr exit then\n dup @ do-colon = if .: exit then\n dup @ do-create = if .\" create \" .name cr exit then\n .\" create \" .name cr .\" does> \" cr\n;\n: see ( -- ) \\ name\n ' (see)\n;\nprevious\n","old_contents":"\\\n\\ Decompiler words.\n\\\n\\ TODO:\n\\\n\\ - Detect defer \/ vector: words and show target\n\\ - Detect create, does> words and dump better\n\\\n\nvocabulary decompiler\nalso decompiler definitions\n\n: tab ht emit ;\n: >target ( ip-of-branch -- adr ) ta1+ dup @ \/token * + ;\n: forward? ( ip-of-branch -- f ) ta1+ @ 0> ;\n: backward? ( ip-of-branch -- f ) ta1+ @ 0> ;\n\n: .type\n dup ['] (do) = if drop .\" do\" cr tab tab exit then\n dup ['] (loop) = if drop ta1+ cr tab .\" loop\" cr tab exit then\n dup ['] lit = if drop ta1+ .\" h# \" dup @ . exit then\n dup ['] branch = if .name ta1+ .\" h# \" dup @ . exit then\n dup ['] ?branch = if .name ta1+ .\" h# \" dup @ . exit then\n dup ['] (.\") = if\n [char] . emit [char] \" emit space\n drop ta1+ dup count type\n [char] \" emit space\n dup c@ 1+ talign + \/token -\n exit\n then\n dup ['] (abort\") = if\n .\" abort\" [char] \" emit space \n drop ta1+ dup count type [char] \" emit space\n dup c@ talign + \/token - exit\n then\n .name space\n;\n: .variable\n .\" variable \" dup .name\n .\" contents: \" >body >user @ . cr\n;\n: .constant\n dup >body @ . .\" constant \" .name cr\n;\n: .:\n .\" : \" dup .name cr\n tab >body\n begin\n dup @ ['] unnest <> while\n dup @ .type\n ta1+\n repeat\n drop cr .\" ;\" cr\n;\nprevious definitions\n\nalso decompiler\n: (see)\n dup @ do-variable = if .variable exit then\n dup @ do-constant = if .constant exit then\n dup @ do-primitive = if .\" primitive \" .name cr exit then\n dup @ do-colon = if .: exit then\n dup @ do-create = if .\" create \" .name cr exit then\n .\" create \" .name cr .\" does> \" cr\n;\n: see ( -- ) \\ name\n ' (see)\n;\nprevious\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"0d02d8dd55e6ac2eecc3d607ffaaf5dddc08ed9a","subject":"improve example","message":"improve example","repos":"cetic\/python-msp430-tools,cetic\/python-msp430-tools,cetic\/python-msp430-tools","old_file":"examples\/asm\/forth_to_asm_advanced\/demo.forth","new_file":"examples\/asm\/forth_to_asm_advanced\/demo.forth","new_contents":"\\ vi:ft=forth\n\\\n\\ Serial input output [X-Protocol] Example.\n\\ Hardware: Launchpad\n\\ Serial Port Settings: 2400,8,N,1\n\\\n\\ Notes\n\\ -----\n\\ The RED LED is blinking periodically. Its timing is made with the\n\\ Watchdog module configured as timer.\n\\\n\\ The RED LED is configured as ADC input when it is not active. This allows\n\\ to show the photo-sensitivity of the LED (compare ADC measurements of\n\\ channel 0 with bright and low ambient light).\n\\\n\\ Due to issues with the CDC-ACM driver under Linux are no messages sent\n\\ by the MSP430 on its own. All commands are initiated by the PC.\n\\\n\\ Copyright (C) 2011 Chris Liechti \n\\ All Rights Reserved.\n\\ Simplified BSD License (see LICENSE.txt for full text)\n\n\n( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - )\nINCLUDE core.forth\nINCLUDE msp430.forth\nINCLUDE io.forth\n\n( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - )\n\n( Write null terminated string using TimerA UART )\nCODE WRITE ( s -- )\n TOS->R15\n .\" \\t call \\x23 write\\n \"\n ASM-NEXT\nEND-CODE\n\n( Output character using the TimerA UART )\nCODE EMIT ( u -- )\n TOS->R15\n .\" \\t call \\x23 putchar\\n \"\n ASM-NEXT\nEND-CODE\n\n( Initialize TimerA UART for reception )\nCODE TIMER_A_UART_INIT ( -- )\n .\" \\t call \\x23 timer_uart_rx_setup\\n \"\n ASM-NEXT\nEND-CODE\n\n( Fetch received character from TimerA UART )\nCODE RX-CHAR ( -- u )\n .\" \\t mov.b timer_a_uart_rxd, W\\n \"\n .\" \\t push W\\n \"\n ASM-NEXT\nEND-CODE\n\n( Perform a single ADC10 measurement )\nCODE ADC10 ( u -- u )\n TOS->R15\n .\" \\t call \\x23 single_adc10\\n \"\n R15->TOS\n ASM-NEXT\nEND-CODE\n\n\n( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - )\n( Control the LEDs on the Launchpad )\n: RED_ON ( -- ) BIT0 P1DIR CSET BIT0 ADC10AE0 CRESET ;\n: RED_OFF ( -- ) BIT0 P1DIR CRESET BIT0 ADC10AE0 CSET ;\n: GREEN_ON ( -- ) BIT6 P1OUT CSET ;\n: GREEN_OFF ( -- ) BIT6 P1OUT CRESET ;\n\n( Read in the button on the Launchpad )\n: S2 BIT3 P1IN CTESTBIT NOT ;\n\n( Delay functions )\n: SHORT-DELAY ( -- ) 0x4fff DELAY ;\n: LONG-DELAY ( -- ) 0xffff DELAY ;\n: VERY-LONG-DELAY ( -- ) LONG-DELAY LONG-DELAY ;\n( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - )\n( Simple event handler. A bit field is used to keep track of events. )\nVARIABLE EVENTS\n( Bit masks for the individual events )\nBIT0 CONSTANT KEY-EVENT\nBIT1 CONSTANT TIMER-EVENT\nBIT2 CONSTANT RX-EVENT\n\n( ------ Helper functions ------ )\n( Start an event )\n: START ( u -- ) EVENTS CSET ;\n( Test if event was started. Reset its flag anyway and return true when it was set. )\n: PENDING? ( -- b )\n DUP ( copy bit mask )\n EVENTS CTESTBIT IF ( test if bit is set )\n EVENTS CRESET ( it is, reset )\n TRUE ( indicate true as return value )\n ELSE\n DROP ( drop bit mask )\n FALSE ( indicate false as return value )\n ENDIF\n;\n( Return true if no events are pending )\n: IDLE? ( -- b )\n EVENTS C@ 0=\n;\n( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - )\n\n( Interrupt handler for P1 )\nPORT1_VECTOR INTERRUPT P1-IRQ-HANDLER\n KEY-EVENT START ( Set event flag for key )\n WAKEUP ( terminate LPM modes )\n 0 P1IFG C! ( clear all interrupt flags )\nEND-INTERRUPT\n\n( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - )\n\n( Watchdog interrupts with SMCLK = 1MHz are too fast for us.\n Only wakeup every n-th interrupt. This is the counter\n used to achieve this. )\nVARIABLE SLOWDOWN\n\n( Interrupt handler for Watchdog module in timer mode )\nWDT_VECTOR INTERRUPT WATCHDOG-TIMER-HANDLER\n SLOWDOWN C@ 1+ ( get and increment counter )\n DUP 30 > IF ( check value )\n TIMER-EVENT START ( set event flag for timer )\n WAKEUP ( terminate LPM modes )\n DROP 0 ( reset counter )\n ENDIF\n SLOWDOWN C! ( store new value )\nEND-INTERRUPT\n\n( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - )\n\n( Received data is put into a small line buffer. When a newline\n is received processing in the foreground is started.\n)\n0 VALUE RX-POS\nRAM CREATE RX-BUFFER 8 ALLOT\n\n100 INTERRUPT TAUART_RX_INTERRUPT\n RX-CHAR DUP ( get the received character )\n RX-BUFFER RX-POS + C! ( store character )\n RX-POS 7 < IF ( increment write pos if there is space )\n RX-POS 1+ TO RX-POS\n ENDIF\n '\\n' = IF ( check for EOL )\n RX-EVENT START ( set event flag for reception )\n WAKEUP ( terminate LPM modes )\n 0 TO RX-POS ( reset read position )\n ENDIF\nEND-INTERRUPT\n\n( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - )\n( Initializations run after reset )\n: INIT ( -- )\n ( Initialize pins )\n OUT TACCTL0 ! ( Init Timer A CCTL before pin is activated DIR, SEL)\n [ BIT0 BIT1 + ] LITERAL P1OUT C! ( RED TXD )\n [ BIT1 BIT2 + ] LITERAL P1SEL C! ( TXD RXD )\n [ BIT1 BIT6 + ] LITERAL P1DIR C! ( GREEN TXD )\n BIT3 P1IES C! ( select neg edge )\n 0 P1IFG C! ( reset flags )\n BIT3 P1IE C! ( enable interrupts for S2 )\n\n ( Use Watchdog module as timer )\n [ WDTPW WDTTMSEL + ] LITERAL WDTCTL !\n WDTIE IE1 C!\n\n ( Initialize clock from calibration values )\n CALDCO_1MHZ DCOCTL C@!\n CALBC1_1MHZ BCSCTL1 C@!\n\n ( Set up Timer A - used for UART )\n [ TASSEL1 MC1 + ] LITERAL TACTL !\n TIMER_A_UART_INIT\n\n ( Enable ADC10 inputs )\n [ BIT0 BIT4 BIT5 BIT7 + + + ] LITERAL ADC10AE0 C!\n\n ( Indicate startup with LED )\n GREEN_ON\n VERY-LONG-DELAY\n GREEN_OFF\n\n ( Enable interrupts now )\n EINT\n;\n\n( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - )\n\n( Decode a hex digit, text -> number. supported input: 0123456789abcdefABCDEF\n This decoding does not check for invalid characters. It will simply return\n garbage, however in the range of 0 ... 15 )\n: HEXDIGIT ( char - u )\n DUP 'A' >= IF\n [ 'A' 10 - ] LITERAL -\n ENDIF\n 0xf AND\n;\n\n( Decode text, 2 hex digits, at given address and return value )\n: HEX-DECODE ( adr -- u )\n DUP\n C@ HEXDIGIT 4 LSHIFT SWAP\n 1+ C@ HEXDIGIT OR\n;\n\n( Decode text, 4 hex digits, big endian order, at given address and return value )\n: HEX-DECODE-WORD-BE ( adr -- u )\n DUP HEX-DECODE 8 LSHIFT\n SWAP 2 + HEX-DECODE OR\n;\n\n\n( Output one hex digit for the number on the stack )\n: .HEXDIGIT ( u -- )\n 0xf AND\n DUP 10 >= IF\n [ 'A' 10 - ] LITERAL\n ELSE\n '0'\n ENDIF\n + EMIT\n;\n\n( Output two hex digits for the byte on the stack )\n: .CHEX ( u -- )\n DUP\n 4 RSHIFT .HEXDIGIT\n .HEXDIGIT\n;\n\n( Output four hex digits for the word on the stack, big endian)\n: .HEX ( u -- )\n DUP\n 8 RSHIFT .CHEX\n .CHEX\n;\n\n( Output a line with 16 bytes as hex and ASCII dump. Includes newline. )\n: .HEXLINE ( adr -- )\n [CHAR] h EMIT SPACE ( write prefix )\n OVER .HEX SPACE SPACE ( write address )\n DUP 16 + SWAP ( calculate end_adr start_adr )\n ( output hex dump )\n BEGIN\n 2DUP > ( end address not yet reached )\n WHILE\n DUP C@ .CHEX ( hex dump of address )\n SPACE\n 1+ ( next address )\n REPEAT\n ( reset address )\n 16 -\n ( output ASCII dump )\n SPACE\n BEGIN\n 2DUP > ( end address not yet reached )\n WHILE\n DUP C@ ( get byte )\n DUP 32 < IF\n DROP [CHAR] .\n ENDIF\n EMIT\n 1+ ( next address )\n REPEAT\n 2DROP .\" \\n\" ( finish hex dump, drop address on stack )\n;\n\n( Print a hex dump of the given address range )\n: HEXDUMP ( adr_low adr_hi -- )\n SWAP\n BEGIN\n 2DUP >\n WHILE\n DUP .HEXLINE\n 16 +\n REPEAT\n 2DROP\n;\n\n\n( Output an integer )\n: .INT ( -- ) .\" i0x\" .HEX '\\n' EMIT ;\n\n( Output OK message )\n: .XOK ( -- ) .\" xOK\\n\" ;\n\n\n( Main application, run after INIT )\n: MAIN ( -- )\n BEGIN\n ( Test if events are pending )\n IDLE? IF\n ( XXX actually we could miss an event and go to sleep if it was set\n between test and LPM. The event flag is not lost, but it is\n executed later when some other event wakes up the CPU. )\n ( Wait in low power mode )\n ENTER-LPM0\n ENDIF\n ( After wakeup test for the different events )\n\n RX-EVENT PENDING? IF\n GREEN_ON ( Show activity )\n ( RX-CHAR EMIT ( send echo )\n RX-BUFFER C@ CASE\n\n ( read switch command )\n ( 's' Read switch )\n [CHAR] s OF\n S2 .INT ( return state of button )\n .XOK\n ENDOF\n\n ( make ADC10 measurement )\n ( 'aCC' ADC measurement if given channel in hex )\n [CHAR] a OF\n RX-BUFFER 1+ HEX-DECODE ( get channel from parameter )\n 12 LSHIFT ( prepare channel argument )\n ADC10DIV_3 OR\n ADC10 .INT ( measure and output)\n .XOK\n ENDOF\n\n ( output a message \/ echo )\n ( 'oM..' Echo message )\n [CHAR] o OF\n RX-BUFFER WRITE\n .XOK\n ENDOF\n\n ( memory dump of INFOMEM segment with calibration values )\n ( 'c' Dump calibration values )\n [CHAR] c OF\n 0x10c0 0x10ff HEXDUMP\n .XOK\n ENDOF\n\n ( memory dump of given address, 64B blocks )\n ( 'mHHHH' Hex dump of given address )\n [CHAR] m OF\n RX-BUFFER 1+ HEX-DECODE-WORD-BE\n DUP 64 + HEXDUMP\n .XOK\n ENDOF\n\n ( default )\n .\" xERR cmd?:\"\n RX-BUFFER WRITE\n ENDCASE\n RX-BUFFER 8 ZERO ( erase buffer for next round )\n GREEN_OFF ( Activity done )\n ENDIF\n\n KEY-EVENT PENDING? IF\n ( Green flashing )\n GREEN_ON\n SHORT-DELAY\n GREEN_OFF\n ENDIF\n\n TIMER-EVENT PENDING? IF\n ( Red flashing )\n RED_ON\n SHORT-DELAY\n RED_OFF\n ENDIF\n AGAIN\n;\n\n( ========================================================================= )\n( Generate the assembler file now )\n\" Advanced demo \" HEADER\n\n( output important runtime core parts )\nCROSS-COMPILE-CORE\n\n( cross compile application )\nCROSS-COMPILE-VARIABLES\nCROSS-COMPILE INIT\nCROSS-COMPILE MAIN\nCROSS-COMPILE P1-IRQ-HANDLER\nCROSS-COMPILE WATCHDOG-TIMER-HANDLER\nCROSS-COMPILE TAUART_RX_INTERRUPT\nCROSS-COMPILE-MISSING ( This compiles all words that were used indirectly )\n","old_contents":"\\ vi:ft=forth\n\\\n\\ Serial input output [X-Protocol] Example.\n\\ Hardware: Launchpad\n\\ Serial Port Settings: 2400,8,N,1\n\\\n\\ Notes\n\\ -----\n\\ The RED LED is blinking periodically. Its timing is made with the\n\\ Watchdog module configured as timer.\n\\\n\\ The RED LED is configured as ADC input when it is not active. This allows\n\\ to show the photo-sensitivity of the LED (compare ADC measurements of\n\\ channel 0 with bright and low ambient light).\n\\\n\\ Due to issues with the CDC-ACM driver under Linux are no messages sent\n\\ by the MSP430 on its own. All commands are initiated by the PC.\n\\\n\\ Copyright (C) 2011 Chris Liechti \n\\ All Rights Reserved.\n\\ Simplified BSD License (see LICENSE.txt for full text)\n\n\n( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - )\nINCLUDE core.forth\nINCLUDE msp430.forth\nINCLUDE io.forth\n\n( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - )\n\n( Write null terminated string using TimerA UART )\nCODE WRITE ( s -- )\n TOS->R15\n .\" \\t call \\x23 write\\n \"\n ASM-NEXT\nEND-CODE\n\n( Output character using the TimerA UART )\nCODE EMIT ( u -- )\n TOS->R15\n .\" \\t call \\x23 putchar\\n \"\n ASM-NEXT\nEND-CODE\n\n( Initialize TimerA UART for reception )\nCODE TIMER_A_UART_INIT ( -- )\n .\" \\t call \\x23 timer_uart_rx_setup\\n \"\n ASM-NEXT\nEND-CODE\n\n( Fetch received character from TimerA UART )\nCODE RX-CHAR ( -- u )\n .\" \\t mov.b timer_a_uart_rxd, W\\n \"\n .\" \\t push W\\n \"\n ASM-NEXT\nEND-CODE\n\n( Perform a single ADC10 measurement )\nCODE ADC10 ( u -- u )\n TOS->R15\n .\" \\t call \\x23 single_adc10\\n \"\n R15->TOS\n ASM-NEXT\nEND-CODE\n\n\n( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - )\n( Control the LEDs on the Launchpad )\n: RED_ON ( -- ) BIT0 P1DIR CSET BIT0 ADC10AE0 CRESET ;\n: RED_OFF ( -- ) BIT0 P1DIR CRESET BIT0 ADC10AE0 CSET ;\n: GREEN_ON ( -- ) BIT6 P1OUT CSET ;\n: GREEN_OFF ( -- ) BIT6 P1OUT CRESET ;\n\n( Read in the button on the Launchpad )\n: S2 P1IN C@ BIT3 AND NOT ;\n\n( Delay functions )\n: SHORT-DELAY ( -- ) 0x4fff DELAY ;\n: LONG-DELAY ( -- ) 0xffff DELAY ;\n: VERY-LONG-DELAY ( -- ) LONG-DELAY LONG-DELAY ;\n( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - )\n( Simple event handler. A bit field is used to keep track of events. )\nVARIABLE EVENTS\n( Bit masks for the individual events )\nBIT0 CONSTANT KEY-EVENT\nBIT1 CONSTANT TIMER-EVENT\nBIT2 CONSTANT RX-EVENT\n\n( ------ Helper functions ------ )\n( Start an event )\n: START ( u -- ) EVENTS CSET ;\n( Test if event was started. Reset its flag anyway and return true when it was set. )\n: PENDING? ( -- b )\n DUP ( copy bit mask )\n EVENTS CTESTBIT IF ( test if bit is set )\n EVENTS CRESET ( it is, reset )\n TRUE ( indicate true as return value )\n ELSE\n DROP ( drop bit mask )\n FALSE ( indicate false as return value )\n ENDIF\n;\n( Return true if no events are pending )\n: IDLE? ( -- b )\n EVENTS C@ 0=\n;\n( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - )\n\n( Interrupt handler for P1 )\nPORT1_VECTOR INTERRUPT P1-IRQ-HANDLER\n KEY-EVENT START ( Set event flag for key )\n WAKEUP ( terminate LPM modes )\n 0 P1IFG C! ( clear all interrupt flags )\nEND-INTERRUPT\n\n( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - )\n\n( Watchdog interrupts with SMCLK = 1MHz are too fast for us.\n Only wakeup every n-th interrupt. This is the counter\n used to achieve this. )\nVARIABLE SLOWDOWN\n\n( Interrupt handler for Watchdog module in timer mode )\nWDT_VECTOR INTERRUPT WATCHDOG-TIMER-HANDLER\n SLOWDOWN C@ 1+ ( get and increment counter )\n DUP 30 > IF ( check value )\n TIMER-EVENT START ( set event flag for timer )\n WAKEUP ( terminate LPM modes )\n DROP 0 ( reset counter )\n ENDIF\n SLOWDOWN C! ( store new value )\nEND-INTERRUPT\n\n( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - )\n\n( Received data is put into a small line buffer. When a newline\n is received processing in the foreground is started.\n)\n0 VALUE RX-POS\nRAM CREATE RX-BUFFER 8 ALLOT\n\n100 INTERRUPT TAUART_RX_INTERRUPT\n RX-CHAR DUP ( get the received character )\n RX-BUFFER RX-POS + C! ( store character )\n RX-POS 7 < IF ( increment write pos if there is space )\n RX-POS 1+ TO RX-POS\n ENDIF\n '\\n' = IF ( check for EOL )\n RX-EVENT START ( set event flag for reception )\n WAKEUP ( terminate LPM modes )\n 0 TO RX-POS ( reset read position )\n ENDIF\nEND-INTERRUPT\n\n( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - )\n( Initializations run after reset )\n: INIT ( -- )\n ( Initialize pins )\n OUT TACCTL0 ! ( Init Timer A CCTL before pin is activated DIR, SEL)\n [ BIT0 BIT1 + ] LITERAL P1OUT C! ( RED TXD )\n [ BIT1 BIT2 + ] LITERAL P1SEL C! ( TXD RXD )\n [ BIT1 BIT6 + ] LITERAL P1DIR C! ( GREEN TXD )\n BIT3 P1IES C! ( select neg edge )\n 0 P1IFG C! ( reset flags )\n BIT3 P1IE C! ( enable interrupts for S2 )\n\n ( Use Watchdog module as timer )\n [ WDTPW WDTTMSEL + ] LITERAL WDTCTL !\n WDTIE IE1 C!\n\n ( Initialize clock from calibration values )\n CALDCO_1MHZ DCOCTL C@!\n CALBC1_1MHZ BCSCTL1 C@!\n\n ( Set up Timer A - used for UART )\n [ TASSEL1 MC1 + ] LITERAL TACTL !\n TIMER_A_UART_INIT\n\n ( Enable ADC10 inputs )\n [ BIT0 BIT4 BIT5 BIT7 + + + ] LITERAL ADC10AE0 C!\n\n ( Indicate startup with LED )\n GREEN_ON\n VERY-LONG-DELAY\n GREEN_OFF\n\n ( Enable interrupts now )\n EINT\n;\n\n( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - )\n\n( Decode a hex digit, text -> number. supported input: 0123456789abcdefABCDEF\n This decoding does not check for invalid characters. It will simply return\n garbage, however in the range of 0 ... 15 )\n: HEXDIGIT ( char - u )\n DUP 'A' >= IF\n [ 'A' 10 - ] LITERAL -\n ENDIF\n 0xf AND\n;\n\n( Decode text, 2 hex digits, at given address and return value )\n: HEX-DECODE ( adr -- u )\n DUP\n C@ HEXDIGIT 4 LSHIFT SWAP\n 1+ C@ HEXDIGIT OR\n;\n\n( Decode text, 4 hex digits, big endian order, at given address and return value )\n: HEX-DECODE-WORD-BE ( adr -- u )\n DUP HEX-DECODE 8 LSHIFT\n SWAP 2 + HEX-DECODE OR\n;\n\n\n( Output one hex digit for the number on the stack )\n: .HEXDIGIT ( u -- )\n 0xf AND\n DUP 10 >= IF\n [ 'A' 10 - ] LITERAL\n ELSE\n '0'\n ENDIF\n + EMIT\n;\n\n( Output two hex digits for the byte on the stack )\n: .CHEX ( u -- )\n DUP\n 4 RSHIFT .HEXDIGIT\n .HEXDIGIT\n;\n\n( Output four hex digits for the word on the stack, big endian)\n: .HEX ( u -- )\n DUP\n 8 RSHIFT .CHEX\n .CHEX\n;\n\n( Output a line with 16 bytes as hex and ASCII dump. Includes newline. )\n: .HEXLINE ( adr -- )\n [CHAR] h EMIT SPACE ( write prefix )\n OVER .HEX SPACE SPACE ( write address )\n DUP 16 + SWAP ( calculate end_adr start_adr )\n ( output hex dump )\n BEGIN\n 2DUP > ( end address not yet reached )\n WHILE\n DUP C@ .CHEX ( hex dump of address )\n SPACE\n 1+ ( next address )\n REPEAT\n ( reset address )\n 16 -\n ( output ASCII dump )\n SPACE\n BEGIN\n 2DUP > ( end address not yet reached )\n WHILE\n DUP C@ ( get byte )\n DUP 32 < IF\n DROP [CHAR] .\n ENDIF\n EMIT\n 1+ ( next address )\n REPEAT\n 2DROP .\" \\n\" ( finish hex dump, drop address on stack )\n;\n\n( Print a hex dump of the given address range )\n: HEXDUMP ( adr_low adr_hi -- )\n SWAP\n BEGIN\n 2DUP >\n WHILE\n DUP .HEXLINE\n 16 +\n REPEAT\n 2DROP\n;\n\n\n( Output an integer )\n: .INT ( -- ) .\" i0x\" .HEX '\\n' EMIT ;\n\n( Output OK message )\n: .XOK ( -- ) .\" xOK\\n\" ;\n\n\n( Main application, run after INIT )\n: MAIN ( -- )\n BEGIN\n ( Test if events are pending )\n IDLE? IF\n ( XXX actually we could miss an event and go to sleep if it was set\n between test and LPM. The event flag is not lost, but it is\n executed later when some other event wakes up the CPU. )\n ( Wait in low power mode )\n ENTER-LPM0\n ENDIF\n ( After wakeup test for the different events )\n\n RX-EVENT PENDING? IF\n GREEN_ON ( Show activity )\n ( RX-CHAR EMIT ( send echo )\n RX-BUFFER C@ CASE\n\n ( read switch command )\n ( 's' Read switch )\n [CHAR] s OF\n S2 .INT ( return state of button )\n .XOK\n ENDOF\n\n ( make ADC10 measurement )\n ( 'aCC' ADC measurement if given channel in hex )\n [CHAR] a OF\n RX-BUFFER 1+ HEX-DECODE ( get channel from parameter )\n 12 LSHIFT ( prepare channel argument )\n ADC10DIV_3 OR\n ADC10 .INT ( measure and output)\n .XOK\n ENDOF\n\n ( output a message \/ echo )\n ( 'oM..' Echo message )\n [CHAR] o OF\n RX-BUFFER WRITE\n .XOK\n ENDOF\n\n ( memory dump of INFOMEM segment with calibration values )\n ( 'c' Dump calibration values )\n [CHAR] c OF\n 0x10c0 0x10ff HEXDUMP\n .XOK\n ENDOF\n\n ( memory dump of given address, 64B blocks )\n ( 'mHHHH' Hex dump of given address )\n [CHAR] m OF\n RX-BUFFER 1+ HEX-DECODE-WORD-BE\n DUP 64 + HEXDUMP\n .XOK\n ENDOF\n\n ( default )\n .\" xERR cmd?:\"\n RX-BUFFER WRITE\n ENDCASE\n RX-BUFFER 8 ZERO ( erase buffer for next round )\n GREEN_OFF ( Activity done )\n ENDIF\n\n KEY-EVENT PENDING? IF\n ( Green flashing )\n GREEN_ON\n SHORT-DELAY\n GREEN_OFF\n ENDIF\n\n TIMER-EVENT PENDING? IF\n ( Red flashing )\n RED_ON\n SHORT-DELAY\n RED_OFF\n ENDIF\n AGAIN\n;\n\n( ========================================================================= )\n( Generate the assembler file now )\n\" Advanced demo \" HEADER\n\n( output important runtime core parts )\nCROSS-COMPILE-CORE\n\n( cross compile application )\nCROSS-COMPILE-VARIABLES\nCROSS-COMPILE INIT\nCROSS-COMPILE MAIN\nCROSS-COMPILE P1-IRQ-HANDLER\nCROSS-COMPILE WATCHDOG-TIMER-HANDLER\nCROSS-COMPILE TAUART_RX_INTERRUPT\nCROSS-COMPILE-MISSING ( This compiles all words that were used indirectly )\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"bfeea7d7a935704282cedd58b470f4110e5ef12b","subject":"explicit floating point literals","message":"explicit floating point literals","repos":"AshleyF\/Forthkit,AshleyF\/Forthkit,AshleyF\/Forthkit","old_file":"library\/prelude.4th","new_file":"library\/prelude.4th","new_contents":"( shared library )\n\n: 2dup over over ;\n\n: 2drop drop drop ;\n: 3drop 2drop drop ;\n\n: min 2dup > if swap then drop ;\n: max 2dup < if swap then drop ;\n: between rot swap over >= -rot <= and ;\n\n: times 0 do ;\n\n: neg -1 * ;\n: abs dup 0 < if neg then ;\n\n: +! dup @ rot + swap ! ;\n\n3.14159265359 const pi\n: deg2rad pi 180.0 \/ * ;\n: rad2deg 180.0 pi \/ * ;\n","old_contents":"( shared library )\n\n: 2dup over over ;\n\n: 2drop drop drop ;\n: 3drop 2drop drop ;\n\n: min 2dup > if swap then drop ;\n: max 2dup < if swap then drop ;\n: between rot swap over >= -rot <= and ;\n\n: times 0 do ;\n\n: neg -1 * ;\n: abs dup 0 < if neg then ;\n\n: +! dup @ rot + swap ! ;\n\n3.14159265359 const pi\n: deg2rad pi 180 \/ * ;\n: rad2deg 180 pi \/ * ;\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"582a105e3514fc54946a0b6cf1df5d9af5224f9c","subject":"Add a loader menu option to set hint.atkbd.0.flags=0x1 which allows USB keyboards to work if no PS\/2 keyboard is attached. The position in the menu was chosen to avoid moving option 6 (loader prompt). This should be a no-op on non-i386\/amd64 machines.","message":"Add a loader menu option to set hint.atkbd.0.flags=0x1 which allows USB\nkeyboards to work if no PS\/2 keyboard is attached. The position in the\nmenu was chosen to avoid moving option 6 (loader prompt). This should\nbe a no-op on non-i386\/amd64 machines.\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/beastie.4th","new_file":"sys\/boot\/forth\/beastie.4th","new_contents":"\\ Copyright (c) 2003 Scott Long \n\\ Copyright (c) 2003 Aleksander Fafula \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\nmarker task-beastie.4th\n\ninclude \/boot\/screen.4th\ninclude \/boot\/frames.4th\n\nhide\n\nvariable menuidx\nvariable menubllt\nvariable menuX\nvariable menuY\nvariable promptwidth\n\nvariable bootkey\nvariable bootacpikey\nvariable bootusbkey\nvariable bootsafekey\nvariable bootverbosekey\nvariable bootsinglekey\nvariable escapekey\nvariable rebootkey\n\n46 constant dot\n\n\\ The BSD Daemon. He is 19 rows high and 34 columns wide\n: technicolor-beastie ( x y -- )\n2dup at-xy .\" \u001b[1;31m, ,\" 1+\n2dup at-xy .\" \/( )`\" 1+\n2dup at-xy .\" \\ \\___ \/ |\" 1+\n2dup at-xy .\" \/- \u001b[37m_\u001b[31m `-\/ '\" 1+\n2dup at-xy .\" (\u001b[37m\/\\\/ \\\u001b[31m \\ \/\\\" 1+\n2dup at-xy .\" \u001b[37m\/ \/ |\u001b[31m ` \\\" 1+\n2dup at-xy .\" \u001b[34mO O \u001b[37m) \u001b[31m\/ |\" 1+\n2dup at-xy .\" \u001b[37m`-^--'\u001b[31m`< '\" 1+\n2dup at-xy .\" (_.) _ ) \/\" 1+\n2dup at-xy .\" `.___\/` \/ \" 1+\n2dup at-xy .\" `-----' \/\" 1+\n2dup at-xy .\" \u001b[33m<----.\u001b[31m __ \/ __ \\\" 1+\n2dup at-xy .\" \u001b[33m<----|====\u001b[31mO)))\u001b[33m==\u001b[31m) \\) \/\u001b[33m====|\" 1+\n2dup at-xy .\" \u001b[33m<----'\u001b[31m `--' `.__,' \\\" 1+\n2dup at-xy .\" | |\" 1+\n2dup at-xy .\" \\ \/ \/\\\" 1+\n2dup at-xy .\" \u001b[36m______\u001b[31m( (_ \/ \\______\/\" 1+\n2dup at-xy .\" \u001b[36m,' ,-----' |\" 1+\nat-xy .\" `--{__________) \u001b[0m\" 1+\n;\n\n: boring-beastie ( x y -- )\n\t2dup at-xy .\" , ,\" 1+\n\t2dup at-xy .\" \/( )`\" 1+\n\t2dup at-xy .\" \\ \\___ \/ |\" 1+\n\t2dup at-xy .\" \/- _ `-\/ '\" 1+\n\t2dup at-xy .\" (\/\\\/ \\ \\ \/\\\" 1+\n\t2dup at-xy .\" \/ \/ | ` \\\" 1+\n\t2dup at-xy .\" O O ) \/ |\" 1+\n\t2dup at-xy .\" `-^--'`< '\" 1+\n\t2dup at-xy .\" (_.) _ ) \/\" 1+\n\t2dup at-xy .\" `.___\/` \/\" 1+\n\t2dup at-xy .\" `-----' \/\" 1+\n\t2dup at-xy .\" <----. __ \/ __ \\\" 1+\n\t2dup at-xy .\" <----|====O)))==) \\) \/====\" 1+\n\t2dup at-xy .\" <----' `--' `.__,' \\\" 1+\n\t2dup at-xy .\" | |\" 1+\n\t2dup at-xy .\" \\ \/ \/\\\" 1+\n\t2dup at-xy .\" ______( (_ \/ \\______\/\" 1+\n\t2dup at-xy .\" ,' ,-----' |\" 1+\n\t at-xy .\" `--{__________)\"\n;\n\n: print-beastie ( x y -- )\n\ts\" loader_color\" getenv\n\tdup -1 = if\n\t\tdrop\n\t\tboring-beastie\n\t\texit\n\tthen\n\ts\" YES\" compare-insensitive 0<> if\n\t\tboring-beastie\n\t\texit\n\tthen\n\ttechnicolor-beastie\n;\n\n: acpienabled? ( -- flag )\n\ts\" acpi_load\" getenv\n\tdup -1 = if\n\t\tdrop false exit\n\tthen\n\ts\" YES\" compare-insensitive 0<> if\n\t\tfalse exit\n\tthen\n\ts\" hint.acpi.0.disabled\" getenv\n\tdup -1 <> if\n\t\ts\" 0\" compare 0<> if\n\t\t\tfalse exit\n\t\tthen\n\tthen\n\ttrue\n;\n\n: printmenuitem ( -- n )\n\tmenuidx @\n\t1+ dup\n\tmenuidx !\n\tmenuY @ + dup menuX @ swap at-xy\n\tmenuidx @ .\n\tmenuX @ 1+ swap at-xy\n\tmenubllt @ emit\n\tmenuidx @ 48 +\n;\n\n: beastie-menu ( -- )\n\t0 menuidx !\n\tdot menubllt !\n\t8 menuY !\n\t5 menuX !\n\tclear\n\t46 4 print-beastie\n\t42 20 2 2 box\n\t13 6 at-xy .\" Welcome to FreeBSD!\"\n\tprintmenuitem .\" Boot FreeBSD [default]\" bootkey !\n\ts\" arch-i386\" environment? if\n\t\tprintmenuitem .\" Boot FreeBSD with ACPI \" bootacpikey !\n\t\tacpienabled? if\n\t\t\t.\" disabled\"\n\t\telse\n\t\t\t.\" enabled\"\n\t\tthen\n\telse\n\t\t-2 bootacpikey !\n\tthen\n\tprintmenuitem .\" Boot FreeBSD in Safe Mode\" bootsafekey !\n\tprintmenuitem .\" Boot FreeBSD in single user mode\" bootsinglekey !\n\tprintmenuitem .\" Boot FreeBSD with verbose logging\" bootverbosekey !\n\tprintmenuitem .\" Escape to loader prompt\" escapekey !\n\ts\" arch-i386\" environment? if\n\t\tprintmenuitem .\" Boot FreeBSD with USB keyboard\" bootusbkey !\n\telse\n\t\t-2 bootacpikey !\n\tthen\n\tprintmenuitem .\" Reboot\" rebootkey !\n\tmenuX @ 20 at-xy\n\t.\" Select option, [Enter] for default\"\n\tmenuX @ 21 at-xy\n\ts\" or [Space] to pause timer \" dup 2 - promptwidth !\n\ttype\n;\n\n: tkey\n\tdup\n\tseconds +\n\tbegin 1 while\n\t\tover 0<> if\n\t\t\tdup seconds u< if\n\t\t\t\tdrop\n\t\t\t\t-1\n\t\t\t\texit\n\t\t\tthen\n\t\t\tmenuX @ promptwidth @ + 21 at-xy dup seconds - .\n\t\tthen\n\t\tkey? if\n\t\t\tdrop\n\t\t\tkey\n\t\t\texit\n\t\tthen\n\t50 ms\n\trepeat\n;\n\nset-current\n\n: beastie-start\n\ts\" beastie_disable\" getenv\n\tdup -1 <> if\n\t\ts\" YES\" compare-insensitive 0= if\n\t\t\texit\n\t\tthen\n\tthen\n\tbeastie-menu\n\ts\" autoboot_delay\" getenv\n\tdup -1 = if\n\t\tdrop\n\t\t10\n\telse\n\t\t0 0 2swap >number drop drop drop\n\tthen\n\tbegin true while\n\t\tdup tkey\n\t\t0 25 at-xy\n\t\tdup 32 = if nip 0 swap then\n\t\tdup -1 = if 0 boot then\n\t\tdup 13 = if 0 boot then\n\t\tdup bootkey @ = if 0 boot then\n\t\tdup bootacpikey @ = if\n\t\t\tacpienabled? if\n\t\t\t\ts\" acpi_load\" unsetenv\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\telse\n\t\t\t\ts\" YES\" s\" acpi_load\" setenv\n\t\t\t\ts\" 0\" s\" hint.acpi.0.disabled\" setenv\n\t\t\tthen\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootusbkey @ = if\n\t\t\ts\" 0x1\" s\" hint.atkbd.0.flags\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootsafekey @ = if\n\t\t\ts\" arch-i386\" environment? if\n\t\t\t\ts\" acpi_load\" unsetenv\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\t\ts\" 1\" s\" hint.apic.0.disabled\" setenv\n\t\t\tthen\n\t\t\ts\" 0\" s\" hw.ata.ata_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.atapi_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.wc\" setenv\n\t\t\ts\" 0\" s\" hw.eisa_slots\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootverbosekey @ = if\n\t\t\ts\" YES\" s\" boot_verbose\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootsinglekey @ = if\n\t\t\ts\" YES\" s\" boot_single\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup escapekey @ = if\n\t\t\t2drop\n\t\t\ts\" NO\" s\" autoboot_delay\" setenv\n\t\t\texit\n\t\tthen\n\t\trebootkey @ = if 0 reboot then\n\trepeat\n;\n\nprevious\n","old_contents":"\\ Copyright (c) 2003 Scott Long \n\\ Copyright (c) 2003 Aleksander Fafula \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\nmarker task-beastie.4th\n\ninclude \/boot\/screen.4th\ninclude \/boot\/frames.4th\n\nhide\n\nvariable menuidx\nvariable menubllt\nvariable menuX\nvariable menuY\nvariable promptwidth\n\nvariable bootkey\nvariable bootacpikey\nvariable bootsafekey\nvariable bootverbosekey\nvariable bootsinglekey\nvariable escapekey\nvariable rebootkey\n\n46 constant dot\n\n\\ The BSD Daemon. He is 19 rows high and 34 columns wide\n: technicolor-beastie ( x y -- )\n2dup at-xy .\" \u001b[1;31m, ,\" 1+\n2dup at-xy .\" \/( )`\" 1+\n2dup at-xy .\" \\ \\___ \/ |\" 1+\n2dup at-xy .\" \/- \u001b[37m_\u001b[31m `-\/ '\" 1+\n2dup at-xy .\" (\u001b[37m\/\\\/ \\\u001b[31m \\ \/\\\" 1+\n2dup at-xy .\" \u001b[37m\/ \/ |\u001b[31m ` \\\" 1+\n2dup at-xy .\" \u001b[34mO O \u001b[37m) \u001b[31m\/ |\" 1+\n2dup at-xy .\" \u001b[37m`-^--'\u001b[31m`< '\" 1+\n2dup at-xy .\" (_.) _ ) \/\" 1+\n2dup at-xy .\" `.___\/` \/ \" 1+\n2dup at-xy .\" `-----' \/\" 1+\n2dup at-xy .\" \u001b[33m<----.\u001b[31m __ \/ __ \\\" 1+\n2dup at-xy .\" \u001b[33m<----|====\u001b[31mO)))\u001b[33m==\u001b[31m) \\) \/\u001b[33m====|\" 1+\n2dup at-xy .\" \u001b[33m<----'\u001b[31m `--' `.__,' \\\" 1+\n2dup at-xy .\" | |\" 1+\n2dup at-xy .\" \\ \/ \/\\\" 1+\n2dup at-xy .\" \u001b[36m______\u001b[31m( (_ \/ \\______\/\" 1+\n2dup at-xy .\" \u001b[36m,' ,-----' |\" 1+\nat-xy .\" `--{__________) \u001b[0m\" 1+\n;\n\n: boring-beastie ( x y -- )\n\t2dup at-xy .\" , ,\" 1+\n\t2dup at-xy .\" \/( )`\" 1+\n\t2dup at-xy .\" \\ \\___ \/ |\" 1+\n\t2dup at-xy .\" \/- _ `-\/ '\" 1+\n\t2dup at-xy .\" (\/\\\/ \\ \\ \/\\\" 1+\n\t2dup at-xy .\" \/ \/ | ` \\\" 1+\n\t2dup at-xy .\" O O ) \/ |\" 1+\n\t2dup at-xy .\" `-^--'`< '\" 1+\n\t2dup at-xy .\" (_.) _ ) \/\" 1+\n\t2dup at-xy .\" `.___\/` \/\" 1+\n\t2dup at-xy .\" `-----' \/\" 1+\n\t2dup at-xy .\" <----. __ \/ __ \\\" 1+\n\t2dup at-xy .\" <----|====O)))==) \\) \/====\" 1+\n\t2dup at-xy .\" <----' `--' `.__,' \\\" 1+\n\t2dup at-xy .\" | |\" 1+\n\t2dup at-xy .\" \\ \/ \/\\\" 1+\n\t2dup at-xy .\" ______( (_ \/ \\______\/\" 1+\n\t2dup at-xy .\" ,' ,-----' |\" 1+\n\t at-xy .\" `--{__________)\"\n;\n\n: print-beastie ( x y -- )\n\ts\" loader_color\" getenv\n\tdup -1 = if\n\t\tdrop\n\t\tboring-beastie\n\t\texit\n\tthen\n\ts\" YES\" compare-insensitive 0<> if\n\t\tboring-beastie\n\t\texit\n\tthen\n\ttechnicolor-beastie\n;\n\n: acpienabled? ( -- flag )\n\ts\" acpi_load\" getenv\n\tdup -1 = if\n\t\tdrop false exit\n\tthen\n\ts\" YES\" compare-insensitive 0<> if\n\t\tfalse exit\n\tthen\n\ts\" hint.acpi.0.disabled\" getenv\n\tdup -1 <> if\n\t\ts\" 0\" compare 0<> if\n\t\t\tfalse exit\n\t\tthen\n\tthen\n\ttrue\n;\n\n: printmenuitem ( -- n )\n\tmenuidx @\n\t1+ dup\n\tmenuidx !\n\tmenuY @ + dup menuX @ swap at-xy\n\tmenuidx @ .\n\tmenuX @ 1+ swap at-xy\n\tmenubllt @ emit\n\tmenuidx @ 48 +\n;\n\n: beastie-menu ( -- )\n\t0 menuidx !\n\tdot menubllt !\n\t8 menuY !\n\t5 menuX !\n\tclear\n\t46 4 print-beastie\n\t42 20 2 2 box\n\t13 6 at-xy .\" Welcome to FreeBSD!\"\n\tprintmenuitem .\" Boot FreeBSD [default]\" bootkey !\n\ts\" arch-i386\" environment? if\n\t\tprintmenuitem .\" Boot FreeBSD with ACPI \" bootacpikey !\n\t\tacpienabled? if\n\t\t\t.\" disabled\"\n\t\telse\n\t\t\t.\" enabled\"\n\t\tthen\n\telse\n\t\t-2 bootacpikey !\n\tthen\n\tprintmenuitem .\" Boot FreeBSD in Safe Mode\" bootsafekey !\n\tprintmenuitem .\" Boot FreeBSD in single user mode\" bootsinglekey !\n\tprintmenuitem .\" Boot FreeBSD with verbose logging\" bootverbosekey !\n\tprintmenuitem .\" Escape to loader prompt\" escapekey !\n\tprintmenuitem .\" Reboot\" rebootkey !\n\tmenuX @ 20 at-xy\n\t.\" Select option, [Enter] for default\"\n\tmenuX @ 21 at-xy\n\ts\" or [Space] to pause timer \" dup 2 - promptwidth !\n\ttype\n;\n\n: tkey\n\tdup\n\tseconds +\n\tbegin 1 while\n\t\tover 0<> if\n\t\t\tdup seconds u< if\n\t\t\t\tdrop\n\t\t\t\t-1\n\t\t\t\texit\n\t\t\tthen\n\t\t\tmenuX @ promptwidth @ + 21 at-xy dup seconds - .\n\t\tthen\n\t\tkey? if\n\t\t\tdrop\n\t\t\tkey\n\t\t\texit\n\t\tthen\n\t50 ms\n\trepeat\n;\n\nset-current\n\n: beastie-start\n\ts\" beastie_disable\" getenv\n\tdup -1 <> if\n\t\ts\" YES\" compare-insensitive 0= if\n\t\t\texit\n\t\tthen\n\tthen\n\tbeastie-menu\n\ts\" autoboot_delay\" getenv\n\tdup -1 = if\n\t\tdrop\n\t\t10\n\telse\n\t\t0 0 2swap >number drop drop drop\n\tthen\n\tbegin true while\n\t\tdup tkey\n\t\t0 25 at-xy\n\t\tdup 32 = if nip 0 swap then\n\t\tdup -1 = if 0 boot then\n\t\tdup 13 = if 0 boot then\n\t\tdup bootkey @ = if 0 boot then\n\t\tdup bootacpikey @ = if\n\t\t\tacpienabled? if\n\t\t\t\ts\" acpi_load\" unsetenv\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\telse\n\t\t\t\ts\" YES\" s\" acpi_load\" setenv\n\t\t\t\ts\" 0\" s\" hint.acpi.0.disabled\" setenv\n\t\t\tthen\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootsafekey @ = if\n\t\t\ts\" arch-i386\" environment? if\n\t\t\t\ts\" acpi_load\" unsetenv\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\t\ts\" 1\" s\" hint.apic.0.disabled\" setenv\n\t\t\tthen\n\t\t\ts\" 0\" s\" hw.ata.ata_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.atapi_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.wc\" setenv\n\t\t\ts\" 0\" s\" hw.eisa_slots\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootverbosekey @ = if\n\t\t\ts\" YES\" s\" boot_verbose\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootsinglekey @ = if\n\t\t\ts\" YES\" s\" boot_single\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup escapekey @ = if\n\t\t\t2drop\n\t\t\ts\" NO\" s\" autoboot_delay\" setenv\n\t\t\texit\n\t\tthen\n\t\trebootkey @ = if 0 reboot then\n\trepeat\n;\n\nprevious\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"6b52f3b63355e0fe1591ca7b2322387468f10f4b","subject":"Uncomment double-length word tests","message":"Uncomment double-length word tests\n","repos":"rm-hull\/byok3,rm-hull\/byok3","old_file":"core\/src\/test\/resources\/forth\/F3.04_numeric_notation.fth","new_file":"core\/src\/test\/resources\/forth\/F3.04_numeric_notation.fth","new_contents":"\\ @IGNORED\n\nDECIMAL\nT{ #1289 -> 1289 }T\nT{ #12346789. -> 12346789. }T\nT{ #-1289 -> -1289 }T\nT{ #-12346789. -> -12346789. }T\nT{ $12eF -> 4847 }T\nT{ $12aBcDeF. -> 313249263. }T\nT{ $-12eF -> -4847 }T\nT{ $-12AbCdEf. -> -313249263. }T\nT{ %10010110 -> 150 }T\nT{ %10010110. -> 150. }T\nT{ %-10010110 -> -150 }T\nT{ %-10010110. -> -150. }T\nT{ 'z' -> 122 }T","old_contents":"\\ @IGNORED\n\nDECIMAL\nT{ #1289 -> 1289 }T\n\\ T{ #12346789. -> 12346789. }T\nT{ #-1289 -> -1289 }T\n\\ T{ #-12346789. -> -12346789. }T\nT{ $12eF -> 4847 }T\n\\ T{ $12aBcDeF. -> 313249263. }T\nT{ $-12eF -> -4847 }T\n\\ T{ $-12AbCdEf. -> -313249263. }T\nT{ %10010110 -> 150 }T\n\\ T{ %10010110. -> 150. }T\nT{ %-10010110 -> -150 }T\n\\ T{ %-10010110. -> -150. }T\nT{ 'z' -> 122 }T","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"de87952f47dd3613153a2cfb4921882a40cb6b96","subject":"Move watchdog stuff out.","message":"Move watchdog stuff out.","repos":"rbsexton\/sockpuppet,rbsexton\/sockpuppet","old_file":"forth\/SAPI-core.fth","new_file":"forth\/SAPI-core.fth","new_contents":"\\ Wrappers for SAPI Core functions\n\\ SVC 0: Return the version of the API in use.\n\\ SVC 1: Return the address of the shared variables table\n\\ SVC 2: putchar\n\\ SVC 3: getchar\n\\ SVC 4: charsavail\n\n\\ SVC 5: Reserved\n\\ SVC 6: Reserved\n\\ SVC 7: Reserved\n\n\\ SVC 8: Watchdog Refresh\n\\ SVC 9: Return Millisecond ticker value.\n\\ SVC 10: The number of CPU cycles consumed in the last second.\n\n\\ 2-4 are for use by the serial io routines, and are \n\\ defined elsewhere.\n\n\\ Note that the system call number is embedded into the instruction,\n\\ so this is not so easily parameterized.\n\n\\ **********************************************************************\n\\ SVC 0: Return the version of the API in use.\n\\ **********************************************************************\nCODE SAPI-Version \\ -- n \n\t\\ Push TOS, and place the result there.\t\n\tsvc # 0 \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 1: Get the address of the shared variable list\n\\ **********************************************************************\nCODE GetSharedVars \\ -- n \n\tsvc # 1 \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 9: Return Millisecond ticker value.\n\\ **********************************************************************\nCODE Ticks \\ -- n \n\tsvc # 9\n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 10: The number of CPU cycles consumed in the last second.\n\\ **********************************************************************\nCODE GetUsage \\ -- n \n\tsvc # 10\n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n","old_contents":"\\ Wrappers for SAPI Core functions\n\\ SVC 0: Return the version of the API in use.\n\\ SVC 1: Return the address of the shared variables table\n\\ SVC 2: putchar\n\\ SVC 3: getchar\n\\ SVC 4: charsavail\n\n\\ SVC 5: Reserved\n\\ SVC 6: Reserved\n\\ SVC 7: Reserved\n\n\\ SVC 8: Watchdog Refresh\n\\ SVC 9: Return Millisecond ticker value.\n\\ SVC 10: The number of CPU cycles consumed in the last second.\n\n\\ 2-4 are for use by the serial io routines, and are \n\\ defined elsewhere.\n\n\\ Note that the system call number is embedded into the instruction,\n\\ so this is not so easily parameterized.\n\n\\ **********************************************************************\n\\ SVC 0: Return the version of the API in use.\n\\ **********************************************************************\nCODE SAPI-Version \\ -- n \n\t\\ Push TOS, and place the result there.\t\n\tsvc # 0 \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 1: Get the address of the shared variable list\n\\ **********************************************************************\nCODE GetSharedVars \\ -- n \n\tsvc # 1 \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 8: Update the Watchdog Countdown.\n\\ **********************************************************************\nCODE WDTKICK \\ n -- \n\tmov r0, tos\n\tsvc # 8\n\tldr tos, [ psp ], # 4\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 9: Return Millisecond ticker value.\n\\ **********************************************************************\nCODE Ticks \\ -- n \n\tsvc # 9\n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 10: The number of CPU cycles consumed in the last second.\n\\ **********************************************************************\nCODE GetUsage \\ -- n \n\tsvc # 10\n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"4bc70a5678d9d879104f33ba8b8a84fa0fa508ab","subject":"Use the system call to get the jumpable root.","message":"Use the system call to get the jumpable root.","repos":"rbsexton\/gecko,rbsexton\/gecko,rbsexton\/gecko","old_file":"tiny\/basic\/forth\/startup.fth","new_file":"tiny\/basic\/forth\/startup.fth","new_contents":"(( App Startup ))\n\n0 value JT \\ The Jumptable\n\n\\ -------------------------------------------\n\\ The word that sets everything up\n\\ -------------------------------------------\n: StartApp\n\thex\n\tinit-dp @ dp ! \\ Set the dictionary pointer so that we can function.\n\t1 getruntimelinks to jt\n\t\\ I have no idea why I am doing this instead of the compilation system.\n\t.\" StartApp! \" \n\t.\" ICRoot@\" icroot @ . cr\n\t\\ $100 0 do icroot @ u0rxdata @ . loop cr \n\t4 SCSSCR _SCS + ! \\ Set deepsleep\n\t\n\t\t\n;\n\n","old_contents":"(( App Startup ))\n\n\n\\ -------------------------------------------\n\\ The word that sets everything up\n\\ -------------------------------------------\n: StartApp\n\thex\n\tinit-dp @ dp ! \\ Set the dictionary pointer so that we can function.\n\t\\ I have no idea why I am doing this instead of the compilation system.\n\t.\" StartApp! \" \n\t.\" ICRoot@\" icroot @ . cr\n\t\\ $100 0 do icroot @ u0rxdata @ . loop cr \n\t4 SCSSCR _SCS + ! \\ Set deepsleep\n\t\n\t\t\n;\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"2ba31adf20f9b50760159a0e05771f092f742ad3","subject":"Clean up dynamic linking.","message":"Clean up dynamic linking.","repos":"rbsexton\/sockpuppet,rbsexton\/sockpuppet","old_file":"forth\/dylink.fth","new_file":"forth\/dylink.fth","new_contents":"\\ Code to support runtime\/dynamic into the C side via SAPI.\n\\\n\\ In the MPE environment, VALUEs work very well for this.\n\\ values are defined at compile time and can be updated at runtime.\n\n\\ So the basic logic is - walk the dynamic list, and if you find something\n\\ that is already defined, assume its a VALUE\n\\ otherwise, generate a constant.\n\n\\ Walk the table and make the constants.\n: dy-populate\n dy-first \n begin \n dup dy.val 0<> \n while\n dup dy-create\n dy-next\n repeat\n drop\n ; \n\n\\ The key bit. Look for an entry and if its a value, update it.\n\\ otherwise, add a constant to the dictionary.\n: dy-create ( c-addr -- )\n \\ Start by looking it up\n DUP dy.name count pad place \\ Make a counted string out of it.\n\n pad find \n 0= IF \\ If failure, cleanup and make-const \n 2DROP \\ Drop the length and pointer.\n dup dy.val \\ c-addr n \n over dy.name count \\ n c-addr b\n make-const\n ELSE \\ If Success, get the value and stuff it in there.\n SWAP dy.val \\ Fetch the value\n SWAP dy-stuff\n THEN\n ;\n\n\n\n\n: dy-first ( -- c-addr ) getsharedvars dy-recordlen + ; \n: dy-next ( c-addr -- c-addr ) dy-recordlen + ; \n\n\\ ************************************************************************\n\\ ************************************************************************\n\\ Secondary support functions \n\\ ************************************************************************\n\\ ************************************************************************\n\n\\ *********************************************\n\\ Accessors - Tightly tied the data structure\n\\ *********************************************\n: dy.val @ ; \n: dy.size #4 + w@ ; \n: dy.count #6 + w@ ; \n: dy.type #8 + c@ ;\n: dy.name #9 + ; \\ Counted string.\n\nUDATA \\ We need a scratch buffer.\ncreate dy.buf $20 allot\nCDATA\n\n\\ Return the recordlength. Its the first thing.\n: dy-recordlen getsharedvars @ ;\n\n: dy-string ( addr -- caddr n ) \n dy.name count\n; \n\n\\ Create a constant from scratch by laying down some assembly\n\\ A key trick is that we have to lay down a pointer to \n\\ the first character of the defintion after we finish\n\\ See the definition above for the template\n: make-const \\ n s-addr c --\n\there 4+ >r \\ This should point to the newly-created header.\n\tmakeheader \\\n\n\\ This is what a constant looks like after emerging from the compiler.\t\n\\ ( 0002:0270 4CF8047D Lx.} ) str r7, [ r12, # $-04 ]!\n\\ ( 0002:0274 004F .O ) ldr r7, [ PC, # $00 ] ( @$20278=$7D04F84C )\n\\ ( 0002:0276 7047 pG ) bx LR\n\n\t$7D04F84C , \\ str r7, [ r12, # $-04 ]!\n\t$4f00 w, \\ ldr r7, [ PC, # $00 ]\n\t$4770 w, \\ bx LR\n\t, \t \\ Lay down the payload\n\n\tr> , \\ lay down the link field for the next word - required\n\t;\n\n\\ Take an XT of a VALUE, and stuff something in there.\n: dy-stuff ( n xt -- ) $8 + @ ! ; \n\n\\ Dump out an entry as a set of constants\n: dy-print \\ c-addr --\n S\" $\" type\n DUP dy.val . \\ Fetch the value\n \n DUP dy.type [CHAR] V = \\ check the type \n \n IF\n \tS\" VALUE \"\n ELSE\n \tS\" CONSTANT \"\n THEN type \\ Display the result\n dup dy.size . .\" x \" DUP dy.count .\n dy-string TYPE\n CR\n ; \n\n\\ Given a record address and a string, figure out\n\\ if thats the one we're looking for\n: dy-compare ( caddr n addr -- n ) \n dy-string compare \n;\n\n\\ Walk the list and find a string.\n: dy-find ( c-addr n -- addr|0 ) \n dy-first\n >R \\ Put it onto the return stack\n BEGIN\n R@ dy.val 0<>\n WHILE \n 2DUP R@ dy-compare\n \\ If we find it, clean the stack and leave the address on R\n 0= IF 2DROP R> EXIT THEN\n R> dy-recordlen + >R\n REPEAT\n \\ If we fall out, there will be a string caddr\/n on the stack\n 2DROP R> DROP \n 0 \\ Leave behind a zero to indicate failure\n;\n\n","old_contents":"\\ Code to support runtime\/dynamic into the C side via SAPI.\n\\\n\\ In the MPE environment, VALUEs work very well for this.\n\\ values are defined at compile time and can be updated at runtime.\n\n\\ So the basic logic is - walk the dynamic list, and if you find something\n\\ that is already defined, assume its a VALUE\n\\ otherwise, generate a constant.\n\n\\ Walk the table and make the constants.\n: dy-populate\n dy-first@ \n begin \n dup dy.val 0<> \n while\n dup dy-create\n dy-recordlen +\n repeat\n drop\n ; \n\n\\ The key bit. Look for an entry and if its a value, update it.\n\\ otherwise, add a constant to the dictionary.\n: dy-create ( c-addr -- )\n \\ Start by looking it up\n DUP dy-cstring \\ Make a counted string out of it.\n\n dy.buf find \n 0= IF \\ If failure, cleanup and make-const \n DROP\n dup dy.val \\ c-addr n \n swap dup dy.name swap dy.namelen \\ n c-addr b\n make-const\n ELSE \\ If Success, get the value and stuff it in there.\n SWAP dy.val \\ Fetch the value\n SWAP dy-stuff\n THEN\n ;\n\n\n\n\n: dy-first@ ( -- c-addr ) getsharedvars dy-recordlen + ; \n: dy-cstring ( c-addr -- ) dy.name OVER dy.namelen dy.buf place ; \n\n\\ ************************************************************************\n\\ ************************************************************************\n\\ Secondary support functions \n\\ ************************************************************************\n\\ ************************************************************************\n\n\\ *********************************************\n\\ Accessors - Tightly tied the data structure\n\\ *********************************************\n: dy.val @ ; \n: dy.size #4 + w@ ; \n: dy.count #6 + w@ ; \n: dy.type #8 + c@ ;\n: dy.namelen #9 + c@ ;\n: dy.name #12 + @ ;\n\nUDATA \\ We need a scratch buffer.\ncreate dy.buf $20 allot\nCDATA\n\n\\ Return the recordlength. Its the first thing.\n: dy-recordlen getsharedvars @ ;\n\n\\ Retrieve the string.\n: dy-string ( addr -- caddr n ) \n dup dy.name swap dy.namelen \n; \n\n\\ Create a constant from scratch by laying down some assembly\n\\ A key trick is that we have to lay down a pointer to \n\\ the first character of the defintion after we finish\n\\ See the definition above for the template\n: make-const \\ n s-addr c --\n\there 4+ >r \\ This should point to the newly-created header.\n\tmakeheader \\\n\n\\ This is what a constant looks like after emerging from the compiler.\t\n\\ ( 0002:0270 4CF8047D Lx.} ) str r7, [ r12, # $-04 ]!\n\\ ( 0002:0274 004F .O ) ldr r7, [ PC, # $00 ] ( @$20278=$7D04F84C )\n\\ ( 0002:0276 7047 pG ) bx LR\n\n\t$7D04F84C , \\ str r7, [ r12, # $-04 ]!\n\t$4f00 w, \\ ldr r7, [ PC, # $00 ]\n\t$4770 w, \\ bx LR\n\t, \t \\ Lay down the payload\n\n\tr> , \\ lay down the link field for the next word - required\n\t;\n\n\\ Take an XT of a VALUE, and stuff something in there.\n: dy-stuff ( n xt -- ) 8 + @ ! ; \n\n\\ Dump out an entry as a set of constants\n: dy-print \\ c-addr --\n S\" $\" type\n DUP dy.val . \\ Fetch the value\n \n DUP dy.type [CHAR] V = \\ check the type \n \n IF\n \tS\" VALUE \"\n ELSE\n \tS\" CONSTANT \"\n THEN\n TYPE \\ Display the result\n DUP dy.size . S\" x\" DUP dy.count .\n dy-string TYPE\n CR\n ; \n\n\\ Take a pointer to a dynamic link record, and add a constant to the dictionary\n: dy-create \\ addr --\n\tDUP \\ addr addr \n\tdy.val \\ c-addr n \n\tSWAP dy-string \\ n c-addr b\n make-const\n ;\n\n\\ Given a record address and a string, figure out\n\\ if thats the one we're looking for\n: dy-compare ( caddr n addr -- n ) \n dy-string compare \n;\n\n\\ Find the record in the list to go with a string\n: dy-find ( c-addr n -- addr|0 ) \n getsharedvars dy-recordlen + \\ Skip over the empty first record\n >R \\ Put it onto the return stack\n BEGIN\n R@ dy.val 0<>\n WHILE \n 2DUP R@ dy-compare\n \\ If we find it, clean the stack and leave the address on R\n 0= IF 2DROP R> EXIT THEN\n R> dy-recordlen + >R\n REPEAT\n \\ If we fall out, there will be a string caddr\/n on the stack\n 2DROP R> DROP \n 0 \\ Leave behind a zero to indicate failure\n;\n\n\\ Walk the table and make the constants.\n: dy-populate\n getsharedvars dy-recordlen + \\ Skip over the empty first record\n BEGIN \n dup dy.val 0<> \n WHILE\n dup dy-create\n dy-recordlen +\n REPEAT\n 2DROP R> DROP 0\n ; \n \n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"8a3f3d24cd4bfc107e59b7c2e30624b68ffd6734","subject":"Commit the interim work. Needs testing.","message":"Commit the interim work. Needs testing.","repos":"rbsexton\/gecko,rbsexton\/gecko,rbsexton\/gecko","old_file":"zero\/clock-umb\/forth\/Clock.fth","new_file":"zero\/clock-umb\/forth\/Clock.fth","new_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( -- )\n load-defaults \n icroot 0 over inter.rtcsem ! \\ Reset the free-running counters.\n 0 over inter.rtcdsem ! \\ Reset the free-running counters.\n\n begin \n \tdup inter.rtcsem @offex! ?dup if hms advancetime then\n \tdup inter.rtcdsem @offex! ?dup if dhms advancetime then\n [asm wfi asm]\n uiupdate if use-uivals else use-clockvals then \n key? until drop\n;\n \n: LOAD-DEFAULTS ( -- )\n #1000 needlemax\n 2dup ! 4 + 2dup ! 4 + ! \n;\n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nstruct ODN \n\t2 field odn.s\n\t2 field odn.m\n\t2 field odn.h\nend-struct\n\nudata\ncreate NEEDLEMAX 3 cells allot\ncreate ODN_HMS odn allot \\ On-Deck, HMS\ncreate ODN_DHMS odn allot \\ On-Deck, DHMS\ncreate ODN_UI odn allot \\ On-Deck, Generated by the UI.\ncdata\n\n: rangecheck ( max n -- n or zero ) dup >R <= if R> drop 0 else R> then ; \n\n: ++NEEDLE_S \\ Called every time.\n odn_hms odn.s \\ Stash this address for the moment. \n\tinterp_max odn.s @ \\ Get the max \n\tover w@ \\ Current value \n\tinterp_hms interp.a interp-next + \\ Returns a value.\n\t\n\t\\ If we've wrapped to zero, reset the interpolator \n\t\\ the zero resets on every needle sweep.\n rangecheck ?dup if interp_hms interp.a interp-reset then \n swap w! \n;\n\n: ++NEEDLE_DS ; \\ Called every time.\n\n: ++NEEDLE_M ; \\ Every time we roll the seconds.\n: ++NEEDLE_DM ; \\ Every time we roll the seconds.\n\n\n\n: _USE ( odn-addr -- ) \n dup w@ pwm0!\n 2 + w@ pwm1!\n 4 + w@ pwm2!\n ;\n\n: USE-CLOCKVALS odn_hms _use ; \n: USE-UIVALS odn_ui _use ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Quadrature\n\\ ----------------------------------------------------------\n\n: QUAD@ ( addr -- n ) \\ Fetch and zero\n @off [asm sxth tos, tos asm] ;\n \n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxsec \\ Max Value for secs+minutes\n\tint hms.maxhour \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_m \\ increment the minutes + hours\nend-struct\n\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_ds , ' ++needle_dm , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n: ADVANCETIME ( struct-addr -- )\n dup hms.w_s @ execute \\ Invoke the official update word.\n 1 over hms.subsec +! \\ Increment\n dup hms.subsec @\n over hms.maxsubsec @ < if drop exit then \\ If less then max, we're done\n 0 over hms.subsec ! \\ Reset the subsecs \n\n dup hms.w_m @ execute\n 1 over hms.s +!\n dup hms.s @ over hms.maxsec @ < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n 1 over hms.m +!\n dup hms.m @ over hms.maxsec @ < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ over hms.maxhour @ < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ----------------------------------------------------------\n\\ The interpolator. \n\\ Implement bresenhams algorithm. All of this code already\n\\ exists in C, but we'll own the data structures. They contain\n\\ A total of 4 words - fixed, err, num, & denom\n\\ ----------------------------------------------------------\nstruct _interp_set\n\t4 cells field interp.a\n\t4 cells field interp.b\n\t4 cells field interp.c\nend-struct\n\nudata \ncreate interp_hms _interp_set allot\ncreate interp_dhms _interp_set allot \ncreate adj_list #50 cells allot \\ 100 16-bit words. \ncdata\n\n\\ Heres the default values. These are universal.\nidata\ncreate interp_max #850 , #850 , #850 ,\ncdata\n\n#16 #60 * equ raw_sec\n#10 #100 * equ raw_dsec\n\n: INTERP-INIT ( -- )\n (interp_init) interp_hms\n 2dup interp.a interp_max @ raw_sec call3-- \n 2dup interp.b interp_max 4 + @ #60 call3-- \n interp.c interp_max 8 + @ #12 call3--\n\n (interp_init) interp_dhms\n 2dup interp.a interp_max @ raw_dsec call3-- \n 2dup interp.b interp_max 4 + @ #100 call3-- \n interp.c interp_max 8 + @ #10 call3--\n;\n\n\\ Call the reset fn.\n: INTERP-RESET ( interp_addr -- )\n (interp_reset) swap call1-- \n;\n\n: INTERP-NEXT ( addr -- n )\n (interp_next) swap call1--n\n;\n\n\n\\ ============================ UNTESTED =======================\n\\ VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n\n\\ ----------------------------------------------------------\n\\ User Interface\n\\ ----------------------------------------------------------\nvariable uistate\nvariable uicount \n\n_GPIO $64 + equ _BUTTONIO\n: BUTTONUP? ( -- t\/f ) _buttonio @ 1 and ; \n: BUTTONDOWN? ( -- t\/f ) buttonup? 1 or ; \n\n\\ The wrapper for all of the UI stuff.\n\\ Returns true if the UI is active - ie, use the values generated by the UI.\n: UIUPDATE ( -- t\/f )\n StateHandlers uistate @ + @ execute \n; \n\n\\ -----------------------------------------------\n\\ State numbers. These are defined x4 so that\n\\ we can just use the state number as an index \n\\ into a table of words.\n\\ -----------------------------------------------\n0 4 * equ _s_init\n1 4 * equ _s_b1\n2 4 * equ _s_1sec\n3 4 * equ _s_seth\n4 4 * equ _s_pendset_m\n5 4 * equ _s_setmin\n6 4 * equ _s_pendcal0\n7 4 * equ _s_cal0\n8 4 * equ _s_pendcalh\n9 4 * equ _s_calh\n10 4 * equ _s_pendcalm\n11 4 * equ _s_calm\n12 4 * equ _s_pendcals\n13 4 * equ _s_cals\n\n\\ All of the state handlers.\n\\ Everybody needs to know the state of the button, so that must\n\\ get passed in, thus they all look like this:\n\\ state ( t\/f -- t\/f )\n: shInit false \n buttondown? if \n _s_b1 uistate !\n uicount off \\ Reset this.\n then\n ;\n\n\\ Waiting for a full second to go by.\n: shB1 false\n buttonup? if _s_init uistate ! exit then\n \\ The Button is down. \n uicount @ 16 > if\n _s_1sec uistate !\n else \n 1 uicount +!\n\tthen\n ;\n\n\\ We're in the 1 second state\n: sh1sec true \n buttonup? if _s_seth uistate ! true exit then\n uicount @ 48 > if\n _s_pendcal0 uistate !\n else \n 1 uicount +!\n\tthen \n;\n\n\\ -------------------------------------------------\n\\ Setting the time\n\\ -------------------------------------------------\n: shSetH true buttondown? if _s_pendset_m uistate ! exit then ;\n\n: shPendSetM true buttonup? if _s_setmin uistate ! then ;\n: shSetMin true buttondown? if _s_pendset_m uistate ! exit then ;\n\n\\ -------------------------------------------------\n\\ Calibration\n\\ -------------------------------------------------\n: shPendCal0 true buttonup? if _s_cal0 uistate ! then ;\n: shCal0 true buttondown? if _s_pendcalh uistate ! exit then ;\n\n: shPendCalH true buttonup? if _s_calh uistate ! then ; \n: shCalH true buttondown? if _s_pendcalm uistate ! exit then ; \n\n: shPendCalM true buttonup? if _s_calm uistate ! then ; \n: shCalM true buttondown? if _s_pendcals uistate ! exit then ; \n\n: shPendCalS true buttonup? if _s_calm uistate ! then ; \n: shCalS true buttondown? if _s_init uistate ! exit then ; \n\ncreate StateHandlers \n' shInit , \n' shB1 ,\n' sh1sec ,\n' shSetH ,\n' shPendSetM , ' shSetMin ,\n\n' shPendCal0 , ' shCal0 ,\n' shPendCalH , ' shCalH , \n' shPendCalM , ' shCalM , \n' shPendCalS , ' shCalS , \n\n","old_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( n -- ) \n icroot inter.rtcsem 0 over ! \\ Reset the free-running counter.\n swap \\ addr n -- \n 0 do \n dup @resetex! ?dup if advance else [asm wfi asm] then\n loop\n drop\n;\n\n: CLOCKINIT ( -- )\n #1000 needlemax\n 2dup ! 4 + 2dup ! 4 + ! \n;\n \n\\ Heres where we advance any needles.\n: ADVANCE ( n -- )\n pwm0@ + pwm0! \n;\n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nudata\ncreate NEEDLEMAX 3 cells allot\ncdata\n\n: ++NEEDLE_S ; \\ Called ever time.\n: ++NEEDLE_M ; \\ Every time we roll the seconds.\n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Quadrature\n\\ ----------------------------------------------------------\n\n: QUAD@ ( addr -- n ) \\ Fetch and zero\n @off [asm sxth tos, tos asm] ;\n \n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxsec \\ Max Value for secs+minutes\n\tint hms.maxhour \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_m \\ increment the minutes + hours\nend-struct\n\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_s , ' ++needle_m , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n\\ UNTESTED\n: ADVANCETIME ( struct-addr -- )\n dup hms.w_s @ execute \\ Invoke the official update word.\n 1 over hms.subsec +! \\ Increment\n dup hms.subsec @\n over hms.maxsubsec @ < if drop exit then \\ If less then max, we're done\n 0 over hms.subsec ! \\ Reset the subsecs \n\n dup hms.w_m @ execute\n 1 over hms.s +!\n dup hms.s @ over hms.maxsec @ < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n 1 over hms.m +!\n dup hms.m @ over hms.maxsec @ < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ over hms.maxhour @ < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ----------------------------------------------------------\n\\ The interpolator. \n\\ Implement bresenhams algorithm. All of this code already\n\\ exists in C, but we'll own the data structures. They contain\n\\ A total of 4 words - fixed, err, num, & denom\n\\ ----------------------------------------------------------\n\nudata \ncreate interp_a 4 cells allot\ncreate interp_b 4 cells allot\ncreate interp_c 4 cells allot\ncdata\n\n#16 #60 * equ raw_sec\n#10 #100 * equ raw_dsec\n\n: INTERP-INIT ( -- )\n (interp_init)\n dup interp_a #850 raw_sec call3-- \n dup interp_b #850 #60 call3-- \n interp_c #850 #12 call3--\n;\n\n: INTERP-NEXT ( addr -- n )\n (interp_next) swap call1--1\n\n\\ ============================ UNTESTED =======================\n\\ VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"eacaaa190c52e6ad74427b786f83123bda063d7a","subject":"fix 0= (bug from introduced 2 changesets ago)","message":"fix 0= (bug from introduced 2 changesets ago)","repos":"cetic\/python-msp430-tools,cetic\/python-msp430-tools,cetic\/python-msp430-tools","old_file":"msp430\/asm\/forth\/_builtins.forth","new_file":"msp430\/asm\/forth\/_builtins.forth","new_contents":"( vi:ft=forth\n\n Implementations of some builtins.\n\n These functions are provided for the host in the msp430.asm.forth module. The\n implementations here are for the target.\n\n Copyright [C] 2011 Chris Liechti \n All Rights Reserved.\n Simplified BSD License [see LICENSE.txt for full text]\n)\n\n( ----- low level supporting functions ----- )\n\n( > Put a literal [next element within thread] on the stack. )\nCODE LIT\n .\" \\t push @IP+ \\t; copy value from thread to stack \\n \"\n ASM-NEXT\nEND-CODE\n\n( > Relative jump within a thread. )\nCODE BRANCH\n .\" \\t add @IP, IP \\n \"\n ASM-NEXT\nEND-CODE\n\n( > Realtive jump within a thread. But only jump if value on stack is false. )\nCODE BRANCH0\n .\" \\t mov @IP+, W \\t; get offset \\n \"\n .\" \\t tst 0(SP) \\t; check TOS \\n \"\n .\" \\t jnz .Lnjmp \\t; do not adjust IP if non zero \\n \"\n .\" \\t decd IP \\t; offset is relative to position of offset, correct \\n \"\n .\" \\t add W, IP \\t; adjust IP \\n \"\n.\" .Lnjmp: \"\n ASM-DROP\n ASM-NEXT\nEND-CODE\n\n( ----- Stack ops ----- )\n\n( > Remove value from top of stack. )\nCODE DROP ( x -- )\n .\" \\t incd SP\\n \"\n ASM-NEXT\nEND-CODE\n\n( > Duplicate value on top of stack. )\nCODE DUP ( x -- x x )\n( .\" \\t push @SP\\n \" )\n .\" \\t mov @SP, W\\n \"\n .\" \\t push W\\n \"\n ASM-NEXT\nEND-CODE\n\n( > Push a copy of the second element on the stack. )\nCODE OVER ( y x -- y x y )\n( .\" \\t push 2(TOS\\n \" )\n .\" \\t mov 2(SP), W\\n \"\n .\" \\t push W\\n \"\n ASM-NEXT\nEND-CODE\n\n( > Push a copy of the N'th element. )\nCODE PICK ( n -- n )\n TOS->W ( get element number from stack )\n .\" \\t rla W \" LF ( multiply by 2 -> 2 byte \/ cell )\n .\" \\t add SP, W \" LF ( calculate address on stack )\n .\" \\t push 0(W) \" LF\n ASM-NEXT\nEND-CODE\n\n( > Exchange the two topmost values on the stack. )\nCODE SWAP ( y x -- x y )\n .\" \\t mov 2(SP), W \" LF\n .\" \\t mov 0(SP), 2(SP) \" LF\n .\" \\t mov W, 0(SP) \" LF\n ASM-NEXT\nEND-CODE\n\n( ----- Return Stack ops ----- )\n\n( > Move x to the return stack. )\nCODE >R ( x -- ) ( R: -- x )\n .\" \\t decd RTOS \\t; make room on the return stack\\n \"\n .\" \\t pop 0(RTOS) \\t; pop value and put it on return stack\\n \"\n ASM-NEXT\nEND-CODE\n\n( > Move x from the return stack to the data stack. )\nCODE R> ( -- x ) ( R: x -- )\n .\" \\t push @RTOS+ \\t; pop from return stack, push to data stack\\n \"\n ASM-NEXT\nEND-CODE\n\n( > Copy x from the return stack to the data stack. )\nCODE R@ ( -- x ) ( R: x -- x )\n .\" \\t push @RTOS \\t; push copy of RTOS to data stack\\n \"\n ASM-NEXT\nEND-CODE\n\n\n( ----- MATH ----- )\n\n( > Add two 16 bit values. )\nCODE + ( n n -- n )\n .\" \\t add 0(SP), 2(SP) \\t; y = x + y \" LF\n ASM-DROP\n ASM-NEXT\nEND-CODE\n\n( > Subtract two 16 bit values. )\nCODE - ( n n -- n )\n .\" \\t sub 0(SP), 2(SP) \\t; y = y - x \" LF\n ASM-DROP\n ASM-NEXT\nEND-CODE\n\n( ----- bit - ops ----- )\n( > Bitwise AND. )\nCODE AND ( n n -- n )\n .\" \\t and 0(SP), 2(SP) \\t; y = x & y \" LF\n ASM-DROP\n ASM-NEXT\nEND-CODE\n\n( > Bitwise OR. )\nCODE OR ( n n -- n )\n .\" \\t bis 0(SP), 2(SP) \\t; y = x | y \" LF\n ASM-DROP\n ASM-NEXT\nEND-CODE\n\n( > Bitwise XOR. )\nCODE XOR ( n n -- n )\n .\" \\t xor 0(SP), 2(SP) \\t; y = x ^ y \" LF\n ASM-DROP\n ASM-NEXT\nEND-CODE\n\n( > Bitwise invert. )\nCODE INVERT ( n -- n )\n .\" \\t inv 0(SP) \\t; x = ~x \" LF\n ASM-NEXT\nEND-CODE\n\n\n( > Multiply by two [arithmetic left shift]. )\nCODE 2* ( n -- n*2 )\n .\" \\t rla 0(SP) \\t; x <<= 1 \" LF\n ASM-NEXT\nEND-CODE\n\n( > Divide by two [arithmetic right shift]. )\nCODE 2\/ ( n -- n\/2 )\n .\" \\t rra 0(SP) \\t; x >>= 1 \" LF\n ASM-NEXT\nEND-CODE\n\n\n( > Logical left shift by u bits. )\nCODE LSHIFT ( n u -- n*2^u )\n TOS->W\n .\" .lsh:\\t clrc\\n\"\n .\" \\t rlc 0(SP) \\t; x <<= 1\\n\"\n .\" \\t dec W\\n\"\n .\" \\t jnz .lsh\\n\"\n ASM-NEXT\nEND-CODE\n\n( > Logical right shift by u bits. )\nCODE RSHIFT ( n u -- n\/2^u )\n TOS->W\n .\" .rsh:\\t clrc\\n\"\n .\" \\t rrc 0(SP) \\t; x >>= 1\\n\"\n .\" \\t dec W\\n\"\n .\" \\t jnz .rsh\\n\"\n ASM-NEXT\nEND-CODE\n\n( ----- Logic ops ----- )\n( 0 - false\n -1 - true\n)\n( > Boolean invert. )\nCODE NOT ( b -- b ) ( XXX alias 0= )\n DEPENDS-ON __COMPARE_HELPER\n .\" \\t tst 0(SP) \" LF\n .\" \\t jz __set_true \" LF\n .\" \\t jmp __set_false \" LF\nEND-CODE\n\n( ---------------------------------------------------\n \"*\"\n \"\/\"\n)\n( ----- Compare ----- )\n( > Internal helper. Providing several labels to be called from assembler:\n( >\n( > - ``__set_true`` stack: ``x -- true`` )\n( > - ``__set_false`` stack: ``x -- false`` )\n( > - ``__drop_and_set_true`` stack: ``x y -- true`` )\n( > - ``__drop_and_set_false`` stack: ``x y -- false`` )\nCODE __COMPARE_HELPER\n .\" __drop_and_set_true:\" LF\n ASM-DROP ( remove 1st argument )\n .\" __set_true:\" LF\n .\" \\t mov \\x23 -1, 0(SP) \" LF ( replace 2nd argument w\/ result )\n ASM-NEXT\n\n .\" __drop_and_set_false:\" LF\n ASM-DROP ( remove 1st argument )\n .\" __set_false:\" LF\n .\" \\t mov \\x23 0, 0(SP) \" LF ( replace 2nd argument w\/ result )\n ASM-NEXT\nEND-CODE\n\n\n( > Compare two numbers. )\nCODE < ( x y -- b )\n DEPENDS-ON __COMPARE_HELPER\n .\" \\t cmp 0(SP), 2(SP) \" LF\n .\" \\t jl __drop_and_set_true \" LF\n .\" \\t jmp __drop_and_set_false \" LF\nEND-CODE\n\n( > Compare two numbers. )\nCODE > ( x y -- b )\n DEPENDS-ON __COMPARE_HELPER\n .\" \\t cmp 2(SP), 0(SP) \" LF\n .\" \\t jl __drop_and_set_true \" LF\n .\" \\t jmp __drop_and_set_false \" LF\nEND-CODE\n\n( > Compare two numbers. )\nCODE <= ( x y -- b )\n DEPENDS-ON __COMPARE_HELPER\n .\" \\t cmp 0(SP), 2(SP) \" LF\n .\" \\t jge __drop_and_set_false \" LF\n .\" \\t jmp __drop_and_set_true \" LF\nEND-CODE\n\n( > Compare two numbers. )\nCODE >= ( x y -- b )\n DEPENDS-ON __COMPARE_HELPER\n .\" \\t cmp 0(SP), 2(SP) \" LF\n .\" \\t jge __drop_and_set_true \" LF\n .\" \\t jmp __drop_and_set_false \" LF\nEND-CODE\n\n( > Tests two numbers for equality. )\nCODE == ( x y -- b )\n DEPENDS-ON __COMPARE_HELPER\n .\" \\t cmp 0(SP), 2(SP) \" LF\n .\" \\t jeq __drop_and_set_true \" LF\n .\" \\t jmp __drop_and_set_false \" LF\nEND-CODE\n\n( XXX alias for == )\n( > Tests two numbers for equality. )\nCODE = ( x y -- b )\n DEPENDS-ON __COMPARE_HELPER\n .\" \\t cmp 0(SP), 2(SP) \" LF\n .\" \\t jeq __drop_and_set_true \" LF\n .\" \\t jmp __drop_and_set_false \" LF\nEND-CODE\n\n( > Tests two numbers for unequality. )\nCODE != ( x y -- b )\n DEPENDS-ON __COMPARE_HELPER\n .\" \\t cmp 0(SP), 2(SP) \" LF\n .\" \\t jne __drop_and_set_true \" LF\n .\" \\t jmp __drop_and_set_false \" LF\nEND-CODE\n\n\n( > Test if number equals zero. )\nCODE 0= ( x -- b )\n DEPENDS-ON __COMPARE_HELPER\n .\" \\t tst 0(SP) \" LF\n .\" \\t jz __set_true \" LF\n .\" \\t jmp __set_false \" LF\nEND-CODE\n\n( > Test if number is positive. )\nCODE 0> ( x -- b )\n DEPENDS-ON __COMPARE_HELPER\n .\" \\t tst 0(SP) \" LF\n .\" \\t jn __set_false \" LF\n .\" \\t jmp __set_true \" LF\nEND-CODE\n\n( --------------------------------------------------- )\n\n( XXX Forth name ERASE conflicts with FCTL bit name in MSP430 )\n( > Erase memory area. )\nCODE ZERO ( adr u -- )\n TOS->W ( count )\n TOS->R15 ( address )\n .\" .erase_loop: clr.b 0(R15)\\n\"\n .\" \\t inc R15\\n\"\n .\" \\t dec W\\n\"\n .\" \\t jnz .erase_loop\\n\"\n ASM-NEXT\nEND-CODE\n\n( --------------------------------------------------- )\n( > internal helper for ``.\"`` )\nCODE __write_text ( -- )\n .\" \\t mov @IP+, R15\\n\"\n .\" \\t call \\x23 write\\n\"\n ASM-NEXT\nEND-CODE\n\n","old_contents":"( vi:ft=forth\n\n Implementations of some builtins.\n\n These functions are provided for the host in the msp430.asm.forth module. The\n implementations here are for the target.\n\n Copyright [C] 2011 Chris Liechti \n All Rights Reserved.\n Simplified BSD License [see LICENSE.txt for full text]\n)\n\n( ----- low level supporting functions ----- )\n\n( > Put a literal [next element within thread] on the stack. )\nCODE LIT\n .\" \\t push @IP+ \\t; copy value from thread to stack \\n \"\n ASM-NEXT\nEND-CODE\n\n( > Relative jump within a thread. )\nCODE BRANCH\n .\" \\t add @IP, IP \\n \"\n ASM-NEXT\nEND-CODE\n\n( > Realtive jump within a thread. But only jump if value on stack is false. )\nCODE BRANCH0\n .\" \\t mov @IP+, W \\t; get offset \\n \"\n .\" \\t tst 0(SP) \\t; check TOS \\n \"\n .\" \\t jnz .Lnjmp \\t; do not adjust IP if non zero \\n \"\n .\" \\t decd IP \\t; offset is relative to position of offset, correct \\n \"\n .\" \\t add W, IP \\t; adjust IP \\n \"\n.\" .Lnjmp: \"\n ASM-DROP\n ASM-NEXT\nEND-CODE\n\n( ----- Stack ops ----- )\n\n( > Remove value from top of stack. )\nCODE DROP ( x -- )\n .\" \\t incd SP\\n \"\n ASM-NEXT\nEND-CODE\n\n( > Duplicate value on top of stack. )\nCODE DUP ( x -- x x )\n( .\" \\t push @SP\\n \" )\n .\" \\t mov @SP, W\\n \"\n .\" \\t push W\\n \"\n ASM-NEXT\nEND-CODE\n\n( > Push a copy of the second element on the stack. )\nCODE OVER ( y x -- y x y )\n( .\" \\t push 2(TOS\\n \" )\n .\" \\t mov 2(SP), W\\n \"\n .\" \\t push W\\n \"\n ASM-NEXT\nEND-CODE\n\n( > Push a copy of the N'th element. )\nCODE PICK ( n -- n )\n TOS->W ( get element number from stack )\n .\" \\t rla W \" LF ( multiply by 2 -> 2 byte \/ cell )\n .\" \\t add SP, W \" LF ( calculate address on stack )\n .\" \\t push 0(W) \" LF\n ASM-NEXT\nEND-CODE\n\n( > Exchange the two topmost values on the stack. )\nCODE SWAP ( y x -- x y )\n .\" \\t mov 2(SP), W \" LF\n .\" \\t mov 0(SP), 2(SP) \" LF\n .\" \\t mov W, 0(SP) \" LF\n ASM-NEXT\nEND-CODE\n\n( ----- Return Stack ops ----- )\n\n( > Move x to the return stack. )\nCODE >R ( x -- ) ( R: -- x )\n .\" \\t decd RTOS \\t; make room on the return stack\\n \"\n .\" \\t pop 0(RTOS) \\t; pop value and put it on return stack\\n \"\n ASM-NEXT\nEND-CODE\n\n( > Move x from the return stack to the data stack. )\nCODE R> ( -- x ) ( R: x -- )\n .\" \\t push @RTOS+ \\t; pop from return stack, push to data stack\\n \"\n ASM-NEXT\nEND-CODE\n\n( > Copy x from the return stack to the data stack. )\nCODE R@ ( -- x ) ( R: x -- x )\n .\" \\t push @RTOS \\t; push copy of RTOS to data stack\\n \"\n ASM-NEXT\nEND-CODE\n\n\n( ----- MATH ----- )\n\n( > Add two 16 bit values. )\nCODE + ( n n -- n )\n .\" \\t add 0(SP), 2(SP) \\t; y = x + y \" LF\n ASM-DROP\n ASM-NEXT\nEND-CODE\n\n( > Subtract two 16 bit values. )\nCODE - ( n n -- n )\n .\" \\t sub 0(SP), 2(SP) \\t; y = y - x \" LF\n ASM-DROP\n ASM-NEXT\nEND-CODE\n\n( ----- bit - ops ----- )\n( > Bitwise AND. )\nCODE AND ( n n -- n )\n .\" \\t and 0(SP), 2(SP) \\t; y = x & y \" LF\n ASM-DROP\n ASM-NEXT\nEND-CODE\n\n( > Bitwise OR. )\nCODE OR ( n n -- n )\n .\" \\t bis 0(SP), 2(SP) \\t; y = x | y \" LF\n ASM-DROP\n ASM-NEXT\nEND-CODE\n\n( > Bitwise XOR. )\nCODE XOR ( n n -- n )\n .\" \\t xor 0(SP), 2(SP) \\t; y = x ^ y \" LF\n ASM-DROP\n ASM-NEXT\nEND-CODE\n\n( > Bitwise invert. )\nCODE INVERT ( n -- n )\n .\" \\t inv 0(SP) \\t; x = ~x \" LF\n ASM-NEXT\nEND-CODE\n\n\n( > Multiply by two [arithmetic left shift]. )\nCODE 2* ( n -- n*2 )\n .\" \\t rla 0(SP) \\t; x <<= 1 \" LF\n ASM-NEXT\nEND-CODE\n\n( > Divide by two [arithmetic right shift]. )\nCODE 2\/ ( n -- n\/2 )\n .\" \\t rra 0(SP) \\t; x >>= 1 \" LF\n ASM-NEXT\nEND-CODE\n\n\n( > Logical left shift by u bits. )\nCODE LSHIFT ( n u -- n*2^u )\n TOS->W\n .\" .lsh:\\t clrc\\n\"\n .\" \\t rlc 0(SP) \\t; x <<= 1\\n\"\n .\" \\t dec W\\n\"\n .\" \\t jnz .lsh\\n\"\n ASM-NEXT\nEND-CODE\n\n( > Logical right shift by u bits. )\nCODE RSHIFT ( n u -- n\/2^u )\n TOS->W\n .\" .rsh:\\t clrc\\n\"\n .\" \\t rrc 0(SP) \\t; x >>= 1\\n\"\n .\" \\t dec W\\n\"\n .\" \\t jnz .rsh\\n\"\n ASM-NEXT\nEND-CODE\n\n( ----- Logic ops ----- )\n( 0 - false\n -1 - true\n)\n( > Boolean invert. )\nCODE NOT ( b -- b ) ( XXX alias 0= )\n DEPENDS-ON __COMPARE_HELPER\n .\" \\t tst 0(SP) \" LF\n .\" \\t jz __set_true \" LF\n .\" \\t jmp __set_false \" LF\nEND-CODE\n\n( ---------------------------------------------------\n \"*\"\n \"\/\"\n)\n( ----- Compare ----- )\n( > Internal helper. Providing several labels to be called from assembler:\n( >\n( > - ``__set_true`` stack: ``x -- true`` )\n( > - ``__set_false`` stack: ``x -- false`` )\n( > - ``__drop_and_set_true`` stack: ``x y -- true`` )\n( > - ``__drop_and_set_false`` stack: ``x y -- false`` )\nCODE __COMPARE_HELPER\n .\" __drop_and_set_true:\" LF\n ASM-DROP ( remove 1st argument )\n .\" __set_true:\" LF\n .\" \\t mov \\x23 -1, 0(SP) \" LF ( replace 2nd argument w\/ result )\n ASM-NEXT\n\n .\" __drop_and_set_false:\" LF\n ASM-DROP ( remove 1st argument )\n .\" __set_false:\" LF\n .\" \\t mov \\x23 0, 0(SP) \" LF ( replace 2nd argument w\/ result )\n ASM-NEXT\nEND-CODE\n\n\n( > Compare two numbers. )\nCODE < ( x y -- b )\n DEPENDS-ON __COMPARE_HELPER\n .\" \\t cmp 0(SP), 2(SP) \" LF\n .\" \\t jl __drop_and_set_true \" LF\n .\" \\t jmp __drop_and_set_false \" LF\nEND-CODE\n\n( > Compare two numbers. )\nCODE > ( x y -- b )\n DEPENDS-ON __COMPARE_HELPER\n .\" \\t cmp 2(SP), 0(SP) \" LF\n .\" \\t jl __drop_and_set_true \" LF\n .\" \\t jmp __drop_and_set_false \" LF\nEND-CODE\n\n( > Compare two numbers. )\nCODE <= ( x y -- b )\n DEPENDS-ON __COMPARE_HELPER\n .\" \\t cmp 0(SP), 2(SP) \" LF\n .\" \\t jge __drop_and_set_false \" LF\n .\" \\t jmp __drop_and_set_true \" LF\nEND-CODE\n\n( > Compare two numbers. )\nCODE >= ( x y -- b )\n DEPENDS-ON __COMPARE_HELPER\n .\" \\t cmp 0(SP), 2(SP) \" LF\n .\" \\t jge __drop_and_set_true \" LF\n .\" \\t jmp __drop_and_set_false \" LF\nEND-CODE\n\n( > Tests two numbers for equality. )\nCODE == ( x y -- b )\n DEPENDS-ON __COMPARE_HELPER\n .\" \\t cmp 0(SP), 2(SP) \" LF\n .\" \\t jeq __drop_and_set_true \" LF\n .\" \\t jmp __drop_and_set_false \" LF\nEND-CODE\n\n( XXX alias for == )\n( > Tests two numbers for equality. )\nCODE = ( x y -- b )\n DEPENDS-ON __COMPARE_HELPER\n .\" \\t cmp 0(SP), 2(SP) \" LF\n .\" \\t jeq __drop_and_set_true \" LF\n .\" \\t jmp __drop_and_set_false \" LF\nEND-CODE\n\n( > Tests two numbers for unequality. )\nCODE != ( x y -- b )\n DEPENDS-ON __COMPARE_HELPER\n .\" \\t cmp 0(SP), 2(SP) \" LF\n .\" \\t jne __drop_and_set_true \" LF\n .\" \\t jmp __drop_and_set_false \" LF\nEND-CODE\n\n\n( > Test if number equals zero. )\nCODE 0= ( x -- b )\n DEPENDS-ON __COMPARE_HELPER\n .\" \\t tst 0(SP) \" LF\n .\" \\t jz __set_false \" LF\n .\" \\t jmp __set_true \" LF\nEND-CODE\n\n( > Test if number is positive. )\nCODE 0> ( x -- b )\n DEPENDS-ON __COMPARE_HELPER\n .\" \\t tst 0(SP) \" LF\n .\" \\t jn __set_false \" LF\n .\" \\t jmp __set_true \" LF\nEND-CODE\n\n( --------------------------------------------------- )\n\n( XXX Forth name ERASE conflicts with FCTL bit name in MSP430 )\n( > Erase memory area. )\nCODE ZERO ( adr u -- )\n TOS->W ( count )\n TOS->R15 ( address )\n .\" .erase_loop: clr.b 0(R15)\\n\"\n .\" \\t inc R15\\n\"\n .\" \\t dec W\\n\"\n .\" \\t jnz .erase_loop\\n\"\n ASM-NEXT\nEND-CODE\n\n( --------------------------------------------------- )\n( > internal helper for ``.\"`` )\nCODE __write_text ( -- )\n .\" \\t mov @IP+, R15\\n\"\n .\" \\t call \\x23 write\\n\"\n ASM-NEXT\nEND-CODE\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"74481a9057c134a78d44afdbff2c4b8654ea8184","subject":"Add assigns for hp ht hsc (#156)","message":"Add assigns for hp ht hsc (#156)\n\nSo you can: include hp:xforms.fth","repos":"philburk\/hmsl,philburk\/hmsl,philburk\/hmsl","old_file":"hmsl\/fth\/load_hmsl.fth","new_file":"hmsl\/fth\/load_hmsl.fth","new_contents":"\\ $Id$\n\\ LOAD HMSL\n\\\n\\ Author: Phil Burk\n\\ Copyright 1986 - Phil Burk, Larry Polansky, David Rosenboom.\n\\\nANEW TASK-LOAD_HMSL\n\nfalse constant HOST=AMIGA\ntrue constant HOST=MAC\n\n: ' ( -- cfa , warn me if used the wrong way )\n state @\n IF\n .\" ' used! ====================\" cr\n source type cr\n .\" ============================\" cr\n postpone '\n ELSE\n '\n THEN\n; immediate\n\ninclude? task-stubs fth\/stubs.fth\n\n: [NEED] ( -- start compiling if not found )\n postpone exists? not postpone [IF]\n;\n\n\\ Decide whether to compile different parts of HMSL.\n[need] IF-LOAD-MIDI\nvariable IF-LOAD-MIDI\nvariable IF-LOAD-ACTIONS\nvariable IF-LOAD-MORPHS\nvariable IF-LOAD-GRAPHICS\nvariable IF-LOAD-SHAPE-ED\nvariable IF-LOAD-DEMO\nif-load-demo off\n[THEN]\n\n\\ SET THESE VARIABLES TO CONTROL WHAT GETS LOADED!!!!\nTRUE if-load-midi !\nTRUE if-load-morphs !\nTRUE if-load-actions ! ( perform screen )\nTRUE if-load-graphics !\nif-load-morphs @ if-load-shape-ed !\n\nif-load-midi @ 0= [IF] .\" Not loading MIDI support!\" cr [THEN]\nif-load-actions @ 0= [IF] .\" Not loading Actions or Perform Screen!\" cr [THEN]\nif-load-graphics @ 0= [IF] .\" Not loading Graphics Support\" cr [THEN]\nif-load-shape-ed @ 0= [IF] .\" Not loading Shape Editor\" cr [THEN]\n\n\\ Start of cascaded initialization and termination.\nexists? SYS.INIT not [if]\n : SYS.INIT ;\n : SYS.TERM ;\n : SYS.RESET ;\n[THEN]\n\nexists? SYS.CLEANUP not [if]\n : SYS.CLEANUP ; \\ less severe then SYS.RESET\n : SYS.START ;\n : SYS.STOP ;\n : SYS.TASK ;\n[THEN]\n\nexists? SYS.STATUS not [if]\n : SYS.STATUS >newline ;\n[THEN]\n\ninclude? within? fth\/p4thbase.fth\ninclude? toupper fth\/charmacr.fth\n\ninclude? task-misc_tools fth\/misc_tools.fth\ninclude? task-utils fth\/utils.fth\ninclude? stack.header fth\/stacks.fth\n\ninclude? task-errormsg fth\/errormsg.fth\ninclude? task-memalloc fth\/memalloc.fth\ninclude? task-cond_comp fth\/cond_comp.fth\n\ninclude? task-global_data fth\/global_data.fth\ninclude? task-service_tasks fth\/service_tasks.fth\ninclude? task-float_port fth\/float_port.fth\n\n\\ MIDI and Time support-------------------------------\nif-load-midi @ [IF]\n include? task-midi_globals fth\/midi_globals.fth\n include? task-time fth\/time.fth\n include? task-midi fth\/midi.fth\n include? task-midi_parser fth\/midi_parser.fth\n include? task-midi_text fth\/midi_text.fth\n[ELSE]\n include? task-midi_stubs fth\/midi_stubs.fth\n[THEN]\n\n\\\n\\ Object Oriented Code -------------------------\ninclude? task-ob_stack fth\/ob_stack.fth\ninclude? task-ob_main fth\/ob_main.fth\ninclude? task-ob_bind fth\/ob_bind.fth\ninclude? task-obmethod fth\/obmethod.fth\nmreset-warn off\ninclude? task-ob_ivars fth\/ob_ivars.fth\ninclude? task-dbl_list fth\/dbl_list.fth\ninclude? task-obobject fth\/obobject.fth\ninclude? task-ob_array fth\/ob_array.fth\ninclude? task-elmnts fth\/elmnts.fth\ninclude? task-ob_dlist fth\/ob_dlist.fth\n\n\\ Support for interactive screens\nif-load-graphics @ [IF]\n include? task-graphics fth\/graphics.fth\n include? task-graph_util fth\/graph_util.fth\n include? task-scg fth\/scg.fth\n include? task-bevel fth\/bevel.fth\n include? task-control fth\/control.fth\n include? task-ctrl_count fth\/ctrl_count.fth\n include? task-ctrl_numeric fth\/ctrl_numeric.fth\n include? task-ctrl_fader fth\/ctrl_fader.fth\n include? task-screen fth\/screen.fth\n include? task-ctrl_text fth\/ctrl_text.fth\n include? task-popup_text fth\/popup_text.fth\n[THEN]\n\n\\ HMSL Music Morphs\nif-load-morphs @ [IF]\ninclude? task-morph_lists fth\/morph_lists.fth\ninclude? task-morph fth\/morph.fth\ninclude? task-actobj fth\/actobj.fth\ninclude? task-collection fth\/collection.fth\ninclude? task-shape fth\/shape.fth\ninclude? task-structure fth\/structure.fth\ninclude? task-production fth\/production.fth\ninclude? task-event_list fth\/event_list.fth\ninclude? task-allocator fth\/allocator.fth\ninclude? task-translators fth\/translators.fth\ninclude? task-instrument fth\/instrument.fth\nif-load-midi @ [IF]\ninclude? task-midi_instrument fth\/midi_instrument.fth\n[THEN]\ninclude? task-job fth\/job.fth\ninclude? task-player fth\/player.fth\ninclude? task-interpreters fth\/interpreters.fth\n[THEN]\n\n\\ Some predefined morphs.\nif-load-morphs @ [IF]\ninclude? task-stock_morphs fth\/stock_morphs.fth\n[THEN]\n\nif-load-graphics @ [IF]\ninclude? task-build_menus fth\/build_menus.fth\n[THEN]\n\nif-load-demo @ 0= if-load-morphs @ and [IF]\ninclude? task-record fth\/record.fth\ninclude? task-packed_midi fth\/packed_midi.fth\n[THEN]\n\ninclude? task-top fth\/top.fth\n\n\\ include? task-set_vectors fth\/set_vectors.fth\ninclude? task-hmsl_version fth\/hmsl_version.fth\ninclude? task-hmsl_top fth\/hmsl_top.fth\ninclude? task-startup fth\/startup.fth\n\n\n\\ Editors in screen are loaded on top of the regular HMSL\nif-load-graphics @ if-load-shape-ed @ AND [IF]\n include? task-shape_editor fth\/shape_editor.fth\n[THEN]\n\n\\ Load actions by Larry Polansky , \"PERFORM\" module\nif-load-graphics @ if-load-actions @ AND [IF]\n include? task-action_utils fth\/action_utils.fth\n include? task-ob_actions fth\/ob_actions.fth\n include? task-test_actions fth\/test_actions.fth\n include? task-action_table fth\/action_table.fth\n include? task-action_screen fth\/action_screen.fth\n include? task-action_top fth\/action_top.fth\n[THEN]\n\n\\ load some tools\ninclude? assign tools\/assigns.fth\ninclude? file_port tools\/file_port.fth\ninclude? task-midifile tools\/midifile.fth\ninclude? task-markov_chain tools\/markov_chain.fth\ninclude? task-score_entry tools\/score_entry.fth\ninclude? task-bend_tuning tools\/bend_tuning.fth\ninclude? task-bend_score tools\/bend_score.fth\n\n\\ Set common HMSL named folder assignments.\nassign hmsl .\nassign hp hmsl:pieces\nassign ht hmsl:tools\nassign hsc hmsl:screens\n\nmreset-warn on\ncr .\" HMSL compilation finished.\" cr\nmap\n\nANEW SESSION\n\n","old_contents":"\\ $Id$\n\\ LOAD HMSL\n\\\n\\ Author: Phil Burk\n\\ Copyright 1986 - Phil Burk, Larry Polansky, David Rosenboom.\n\\\nANEW TASK-LOAD_HMSL\n\nfalse constant HOST=AMIGA\ntrue constant HOST=MAC\n\n: ' ( -- cfa , warn me if used the wrong way )\n state @\n IF\n .\" ' used! ====================\" cr\n source type cr\n .\" ============================\" cr\n postpone '\n ELSE\n '\n THEN\n; immediate\n\ninclude? task-stubs fth\/stubs.fth\n\n: [NEED] ( -- start compiling if not found )\n postpone exists? not postpone [IF]\n;\n\n\\ Decide whether to compile different parts of HMSL.\n[need] IF-LOAD-MIDI\nvariable IF-LOAD-MIDI\nvariable IF-LOAD-ACTIONS\nvariable IF-LOAD-MORPHS\nvariable IF-LOAD-GRAPHICS\nvariable IF-LOAD-SHAPE-ED\nvariable IF-LOAD-DEMO\nif-load-demo off\n[THEN]\n\n\\ SET THESE VARIABLES TO CONTROL WHAT GETS LOADED!!!!\nTRUE if-load-midi !\nTRUE if-load-morphs !\nTRUE if-load-actions ! ( perform screen )\nTRUE if-load-graphics !\nif-load-morphs @ if-load-shape-ed !\n\nif-load-midi @ 0= [IF] .\" Not loading MIDI support!\" cr [THEN]\nif-load-actions @ 0= [IF] .\" Not loading Actions or Perform Screen!\" cr [THEN]\nif-load-graphics @ 0= [IF] .\" Not loading Graphics Support\" cr [THEN]\nif-load-shape-ed @ 0= [IF] .\" Not loading Shape Editor\" cr [THEN]\n\n\\ Start of cascaded initialization and termination.\nexists? SYS.INIT not [if]\n : SYS.INIT ;\n : SYS.TERM ;\n : SYS.RESET ;\n[THEN]\n\nexists? SYS.CLEANUP not [if]\n : SYS.CLEANUP ; \\ less severe then SYS.RESET\n : SYS.START ;\n : SYS.STOP ;\n : SYS.TASK ;\n[THEN]\n\nexists? SYS.STATUS not [if]\n : SYS.STATUS >newline ;\n[THEN]\n\ninclude? within? fth\/p4thbase.fth\ninclude? toupper fth\/charmacr.fth\n\ninclude? task-misc_tools fth\/misc_tools.fth\ninclude? task-utils fth\/utils.fth\ninclude? stack.header fth\/stacks.fth\n\ninclude? task-errormsg fth\/errormsg.fth\ninclude? task-memalloc fth\/memalloc.fth\ninclude? task-cond_comp fth\/cond_comp.fth\n\ninclude? task-global_data fth\/global_data.fth\ninclude? task-service_tasks fth\/service_tasks.fth\ninclude? task-float_port fth\/float_port.fth\n\n\\ MIDI and Time support-------------------------------\nif-load-midi @ [IF]\n include? task-midi_globals fth\/midi_globals.fth\n include? task-time fth\/time.fth\n include? task-midi fth\/midi.fth\n include? task-midi_parser fth\/midi_parser.fth\n include? task-midi_text fth\/midi_text.fth\n[ELSE]\n include? task-midi_stubs fth\/midi_stubs.fth\n[THEN]\n\n\\\n\\ Object Oriented Code -------------------------\ninclude? task-ob_stack fth\/ob_stack.fth\ninclude? task-ob_main fth\/ob_main.fth\ninclude? task-ob_bind fth\/ob_bind.fth\ninclude? task-obmethod fth\/obmethod.fth\nmreset-warn off\ninclude? task-ob_ivars fth\/ob_ivars.fth\ninclude? task-dbl_list fth\/dbl_list.fth\ninclude? task-obobject fth\/obobject.fth\ninclude? task-ob_array fth\/ob_array.fth\ninclude? task-elmnts fth\/elmnts.fth\ninclude? task-ob_dlist fth\/ob_dlist.fth\n\n\\ Support for interactive screens\nif-load-graphics @ [IF]\n include? task-graphics fth\/graphics.fth\n include? task-graph_util fth\/graph_util.fth\n include? task-scg fth\/scg.fth\n include? task-bevel fth\/bevel.fth\n include? task-control fth\/control.fth\n include? task-ctrl_count fth\/ctrl_count.fth\n include? task-ctrl_numeric fth\/ctrl_numeric.fth\n include? task-ctrl_fader fth\/ctrl_fader.fth\n include? task-screen fth\/screen.fth\n include? task-ctrl_text fth\/ctrl_text.fth\n include? task-popup_text fth\/popup_text.fth\n[THEN]\n\n\\ HMSL Music Morphs\nif-load-morphs @ [IF]\ninclude? task-morph_lists fth\/morph_lists.fth\ninclude? task-morph fth\/morph.fth\ninclude? task-actobj fth\/actobj.fth\ninclude? task-collection fth\/collection.fth\ninclude? task-shape fth\/shape.fth\ninclude? task-structure fth\/structure.fth\ninclude? task-production fth\/production.fth\ninclude? task-event_list fth\/event_list.fth\ninclude? task-allocator fth\/allocator.fth\ninclude? task-translators fth\/translators.fth\ninclude? task-instrument fth\/instrument.fth\nif-load-midi @ [IF]\ninclude? task-midi_instrument fth\/midi_instrument.fth\n[THEN]\ninclude? task-job fth\/job.fth\ninclude? task-player fth\/player.fth\ninclude? task-interpreters fth\/interpreters.fth\n[THEN]\n\n\\ Some predefined morphs.\nif-load-morphs @ [IF]\ninclude? task-stock_morphs fth\/stock_morphs.fth\n[THEN]\n\nif-load-graphics @ [IF]\ninclude? task-build_menus fth\/build_menus.fth\n[THEN]\n\nif-load-demo @ 0= if-load-morphs @ and [IF]\ninclude? task-record fth\/record.fth\ninclude? task-packed_midi fth\/packed_midi.fth\n[THEN]\n\ninclude? task-top fth\/top.fth\n\n\\ include? task-set_vectors fth\/set_vectors.fth\ninclude? task-hmsl_version fth\/hmsl_version.fth\ninclude? task-hmsl_top fth\/hmsl_top.fth\ninclude? task-startup fth\/startup.fth\n\n\n\\ Editors in screen are loaded on top of the regular HMSL\nif-load-graphics @ if-load-shape-ed @ AND [IF]\n include? task-shape_editor fth\/shape_editor.fth\n[THEN]\n\n\\ Load actions by Larry Polansky , \"PERFORM\" module\nif-load-graphics @ if-load-actions @ AND [IF]\n include? task-action_utils fth\/action_utils.fth\n include? task-ob_actions fth\/ob_actions.fth\n include? task-test_actions fth\/test_actions.fth\n include? task-action_table fth\/action_table.fth\n include? task-action_screen fth\/action_screen.fth\n include? task-action_top fth\/action_top.fth\n[THEN]\n\n\\ load some tools\ninclude? assign tools\/assigns.fth\ninclude? file_port tools\/file_port.fth\ninclude? task-midifile tools\/midifile.fth\ninclude? task-markov_chain tools\/markov_chain.fth\ninclude? task-score_entry tools\/score_entry.fth\ninclude? task-bend_tuning tools\/bend_tuning.fth\ninclude? task-bend_score tools\/bend_score.fth\n\nmreset-warn on\ncr .\" HMSL compilation finished.\" cr\nmap\n\nANEW SESSION\n\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Forth"} {"commit":"bf1f504459b39b3f6246848a1fe738b25e808654","subject":"Directly call the 'boot' word instead of indirectly evaluating it.","message":"Directly call the 'boot' word instead of indirectly evaluating it.\n\nSubmitted by: dcs\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/beastie.4th","new_file":"sys\/boot\/forth\/beastie.4th","new_contents":"\\ Copyright (c) 2003 Scott Long \n\\ Copyright (c) 2003 Aleksander Fafula \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\nmarker task-beastie.4th\n\ninclude \/boot\/screen.4th\ninclude \/boot\/frames.4th\n\nhide\n\nvariable menuidx\nvariable menubllt\nvariable menuX\nvariable menuY\nvariable promptwidth\n\nvariable bootkey\nvariable bootacpikey\nvariable bootsafekey\nvariable bootverbosekey\nvariable bootsinglekey\nvariable escapekey\nvariable rebootkey\n\n46 constant dot\n\n\\ The BSD Daemon. He is 19 rows high and 34 columns wide\n: technicolor-beastie ( x y -- )\n2dup at-xy .\" \u001b[1;31m, ,\" 1+\n2dup at-xy .\" \/( )`\" 1+\n2dup at-xy .\" \\ \\___ \/ |\" 1+\n2dup at-xy .\" \/- \u001b[37m_\u001b[31m `-\/ '\" 1+\n2dup at-xy .\" (\u001b[37m\/\\\/ \\\u001b[31m \\ \/\\\" 1+\n2dup at-xy .\" \u001b[37m\/ \/ |\u001b[31m ` \\\" 1+\n2dup at-xy .\" \u001b[34mO O \u001b[37m) \u001b[31m\/ |\" 1+\n2dup at-xy .\" \u001b[37m`-^--'\u001b[31m`< '\" 1+\n2dup at-xy .\" (_.) _ ) \/\" 1+\n2dup at-xy .\" `.___\/` \/ \" 1+\n2dup at-xy .\" `-----' \/\" 1+\n2dup at-xy .\" \u001b[33m<----.\u001b[31m __ \/ __ \\\" 1+\n2dup at-xy .\" \u001b[33m<----|====\u001b[31mO)))\u001b[33m==\u001b[31m) \\) \/\u001b[33m====|\" 1+\n2dup at-xy .\" \u001b[33m<----'\u001b[31m `--' `.__,' \\\" 1+\n2dup at-xy .\" | |\" 1+\n2dup at-xy .\" \\ \/ \/\\\" 1+\n2dup at-xy .\" \u001b[36m______\u001b[31m( (_ \/ \\______\/\" 1+\n2dup at-xy .\" \u001b[36m,' ,-----' |\" 1+\nat-xy .\" `--{__________) \u001b[0m\" 1+\n;\n\n: boring-beastie ( x y -- )\n\t2dup at-xy .\" , ,\" 1+\n\t2dup at-xy .\" \/( )`\" 1+\n\t2dup at-xy .\" \\ \\___ \/ |\" 1+\n\t2dup at-xy .\" \/- _ `-\/ '\" 1+\n\t2dup at-xy .\" (\/\\\/ \\ \\ \/\\\" 1+\n\t2dup at-xy .\" \/ \/ | ` \\\" 1+\n\t2dup at-xy .\" O O ) \/ |\" 1+\n\t2dup at-xy .\" `-^--'`< '\" 1+\n\t2dup at-xy .\" (_.) _ ) \/\" 1+\n\t2dup at-xy .\" `.___\/` \/\" 1+\n\t2dup at-xy .\" `-----' \/\" 1+\n\t2dup at-xy .\" <----. __ \/ __ \\\" 1+\n\t2dup at-xy .\" <----|====O)))==) \\) \/====\" 1+\n\t2dup at-xy .\" <----' `--' `.__,' \\\" 1+\n\t2dup at-xy .\" | |\" 1+\n\t2dup at-xy .\" \\ \/ \/\\\" 1+\n\t2dup at-xy .\" ______( (_ \/ \\______\/\" 1+\n\t2dup at-xy .\" ,' ,-----' |\" 1+\n\t at-xy .\" `--{__________)\"\n;\n\n: print-beastie ( x y -- )\n\ts\" loader_color\" getenv\n\tdup -1 = if\n\t\tdrop\n\t\tboring-beastie\n\t\texit\n\tthen\n\ts\" YES\" compare-insensitive 0<> if\n\t\tboring-beastie\n\t\texit\n\tthen\n\ttechnicolor-beastie\n;\n\n: acpienabled? ( -- flag )\n\ts\" acpi_load\" getenv\n\tdup -1 = if\n\t\tdrop false exit\n\tthen\n\ts\" YES\" compare-insensitive 0<> if\n\t\tfalse exit\n\tthen\n\ts\" hint.acpi.0.disabled\" getenv\n\tdup -1 <> if\n\t\ts\" 0\" compare 0<> if\n\t\t\tfalse exit\n\t\tthen\n\tthen\n\ttrue\n;\n\n: printmenuitem ( -- n )\n\tmenuidx @\n\t1+ dup\n\tmenuidx !\n\tmenuY @ + dup menuX @ swap at-xy\n\tmenuidx @ .\n\tmenuX @ 1+ swap at-xy\n\tmenubllt @ emit\n\tmenuidx @ 48 +\n;\n\n: beastie-menu ( -- )\n\t0 menuidx !\n\tdot menubllt !\n\t8 menuY !\n\t5 menuX !\n\tclear\n\t46 4 print-beastie\n\t42 20 2 2 box\n\t13 6 at-xy .\" Welcome to FreeBSD!\"\n\tprintmenuitem .\" Boot FreeBSD [default]\" bootkey !\n\ts\" arch-i386\" environment? if\n\t\tprintmenuitem .\" Boot FreeBSD with ACPI \" bootacpikey !\n\t\tacpienabled? if\n\t\t\t.\" disabled\"\n\t\telse\n\t\t\t.\" enabled\"\n\t\tthen\n\telse\n\t\t-2 bootacpikey !\n\tthen\n\tprintmenuitem .\" Boot FreeBSD in Safe Mode\" bootsafekey !\n\tprintmenuitem .\" Boot FreeBSD in single user mode\" bootsinglekey !\n\tprintmenuitem .\" Boot FreeBSD with verbose logging\" bootverbosekey !\n\tprintmenuitem .\" Escape to loader prompt\" escapekey !\n\tprintmenuitem .\" Reboot\" rebootkey !\n\tmenuX @ 20 at-xy\n\t.\" Select option, [Enter] for default\"\n\tmenuX @ 21 at-xy\n\ts\" or [Space] to pause timer \" dup 2 - promptwidth !\n\ttype\n;\n\n: tkey\n\tdup\n\tseconds +\n\tbegin 1 while\n\t\tover 0<> if\n\t\t\tdup seconds u< if\n\t\t\t\tdrop\n\t\t\t\t-1\n\t\t\t\texit\n\t\t\tthen\n\t\t\tmenuX @ promptwidth @ + 21 at-xy dup seconds - .\n\t\tthen\n\t\tkey? if\n\t\t\tdrop\n\t\t\tkey\n\t\t\texit\n\t\tthen\n\t50 ms\n\trepeat\n;\n\nset-current\n\n: beastie-start\n\ts\" beastie_disable\" getenv\n\tdup -1 <> if\n\t\ts\" YES\" compare-insensitive 0= if\n\t\t\texit\n\t\tthen\n\tthen\n\tbeastie-menu\n\ts\" autoboot_delay\" getenv\n\tdup -1 = if\n\t\tdrop\n\t\t10\n\telse\n\t\t0 0 2swap >number drop drop drop\n\tthen\n\tbegin true while\n\t\tdup tkey\n\t\t0 25 at-xy\n\t\tdup 32 = if nip 0 swap then\n\t\tdup -1 = if 0 boot then\n\t\tdup 13 = if 0 boot then\n\t\tdup bootkey @ = if 0 boot then\n\t\tdup bootacpikey @ = if\n\t\t\tacpienabled? if\n\t\t\t\ts\" acpi_load\" unsetenv\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\telse\n\t\t\t\ts\" YES\" s\" acpi_load\" setenv\n\t\t\t\ts\" 0\" s\" hint.acpi.0.disabled\" setenv\n\t\t\tthen\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootsafekey @ = if\n\t\t\ts\" arch-i386\" environment? if\n\t\t\t\ts\" acpi_load\" unsetenv\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\tthen\n\t\t\ts\" 0\" s\" hw.ata.ata_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.atapi_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.wc\" setenv\n\t\t\ts\" 0\" s\" hw.eisa_slots\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootverbosekey @ = if\n\t\t\ts\" YES\" s\" boot_verbose\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootsinglekey @ = if\n\t\t\ts\" YES\" s\" boot_single\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup escapekey @ = if\n\t\t\t2drop\n\t\t\ts\" NO\" s\" autoboot_delay\" setenv\n\t\t\texit\n\t\tthen\n\t\trebootkey @ = if s\" reboot\" evaluate then\n\trepeat\n;\n\nprevious\n","old_contents":"\\ Copyright (c) 2003 Scott Long \n\\ Copyright (c) 2003 Aleksander Fafula \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\nmarker task-beastie.4th\n\ninclude \/boot\/screen.4th\ninclude \/boot\/frames.4th\n\nhide\n\nvariable menuidx\nvariable menubllt\nvariable menuX\nvariable menuY\nvariable promptwidth\n\nvariable bootkey\nvariable bootacpikey\nvariable bootsafekey\nvariable bootverbosekey\nvariable bootsinglekey\nvariable escapekey\nvariable rebootkey\n\n46 constant dot\n\n\\ The BSD Daemon. He is 19 rows high and 34 columns wide\n: technicolor-beastie ( x y -- )\n2dup at-xy .\" \u001b[1;31m, ,\" 1+\n2dup at-xy .\" \/( )`\" 1+\n2dup at-xy .\" \\ \\___ \/ |\" 1+\n2dup at-xy .\" \/- \u001b[37m_\u001b[31m `-\/ '\" 1+\n2dup at-xy .\" (\u001b[37m\/\\\/ \\\u001b[31m \\ \/\\\" 1+\n2dup at-xy .\" \u001b[37m\/ \/ |\u001b[31m ` \\\" 1+\n2dup at-xy .\" \u001b[34mO O \u001b[37m) \u001b[31m\/ |\" 1+\n2dup at-xy .\" \u001b[37m`-^--'\u001b[31m`< '\" 1+\n2dup at-xy .\" (_.) _ ) \/\" 1+\n2dup at-xy .\" `.___\/` \/ \" 1+\n2dup at-xy .\" `-----' \/\" 1+\n2dup at-xy .\" \u001b[33m<----.\u001b[31m __ \/ __ \\\" 1+\n2dup at-xy .\" \u001b[33m<----|====\u001b[31mO)))\u001b[33m==\u001b[31m) \\) \/\u001b[33m====|\" 1+\n2dup at-xy .\" \u001b[33m<----'\u001b[31m `--' `.__,' \\\" 1+\n2dup at-xy .\" | |\" 1+\n2dup at-xy .\" \\ \/ \/\\\" 1+\n2dup at-xy .\" \u001b[36m______\u001b[31m( (_ \/ \\______\/\" 1+\n2dup at-xy .\" \u001b[36m,' ,-----' |\" 1+\nat-xy .\" `--{__________) \u001b[0m\" 1+\n;\n\n: boring-beastie ( x y -- )\n\t2dup at-xy .\" , ,\" 1+\n\t2dup at-xy .\" \/( )`\" 1+\n\t2dup at-xy .\" \\ \\___ \/ |\" 1+\n\t2dup at-xy .\" \/- _ `-\/ '\" 1+\n\t2dup at-xy .\" (\/\\\/ \\ \\ \/\\\" 1+\n\t2dup at-xy .\" \/ \/ | ` \\\" 1+\n\t2dup at-xy .\" O O ) \/ |\" 1+\n\t2dup at-xy .\" `-^--'`< '\" 1+\n\t2dup at-xy .\" (_.) _ ) \/\" 1+\n\t2dup at-xy .\" `.___\/` \/\" 1+\n\t2dup at-xy .\" `-----' \/\" 1+\n\t2dup at-xy .\" <----. __ \/ __ \\\" 1+\n\t2dup at-xy .\" <----|====O)))==) \\) \/====\" 1+\n\t2dup at-xy .\" <----' `--' `.__,' \\\" 1+\n\t2dup at-xy .\" | |\" 1+\n\t2dup at-xy .\" \\ \/ \/\\\" 1+\n\t2dup at-xy .\" ______( (_ \/ \\______\/\" 1+\n\t2dup at-xy .\" ,' ,-----' |\" 1+\n\t at-xy .\" `--{__________)\"\n;\n\n: print-beastie ( x y -- )\n\ts\" loader_color\" getenv\n\tdup -1 = if\n\t\tdrop\n\t\tboring-beastie\n\t\texit\n\tthen\n\ts\" YES\" compare-insensitive 0<> if\n\t\tboring-beastie\n\t\texit\n\tthen\n\ttechnicolor-beastie\n;\n\n: acpienabled? ( -- flag )\n\ts\" acpi_load\" getenv\n\tdup -1 = if\n\t\tdrop false exit\n\tthen\n\ts\" YES\" compare-insensitive 0<> if\n\t\tfalse exit\n\tthen\n\ts\" hint.acpi.0.disabled\" getenv\n\tdup -1 <> if\n\t\ts\" 0\" compare 0<> if\n\t\t\tfalse exit\n\t\tthen\n\tthen\n\ttrue\n;\n\n: printmenuitem ( -- n )\n\tmenuidx @\n\t1+ dup\n\tmenuidx !\n\tmenuY @ + dup menuX @ swap at-xy\n\tmenuidx @ .\n\tmenuX @ 1+ swap at-xy\n\tmenubllt @ emit\n\tmenuidx @ 48 +\n;\n\n: beastie-menu ( -- )\n\t0 menuidx !\n\tdot menubllt !\n\t8 menuY !\n\t5 menuX !\n\tclear\n\t46 4 print-beastie\n\t42 20 2 2 box\n\t13 6 at-xy .\" Welcome to FreeBSD!\"\n\tprintmenuitem .\" Boot FreeBSD [default]\" bootkey !\n\ts\" arch-i386\" environment? if\n\t\tprintmenuitem .\" Boot FreeBSD with ACPI \" bootacpikey !\n\t\tacpienabled? if\n\t\t\t.\" disabled\"\n\t\telse\n\t\t\t.\" enabled\"\n\t\tthen\n\telse\n\t\t-2 bootacpikey !\n\tthen\n\tprintmenuitem .\" Boot FreeBSD in Safe Mode\" bootsafekey !\n\tprintmenuitem .\" Boot FreeBSD in single user mode\" bootsinglekey !\n\tprintmenuitem .\" Boot FreeBSD with verbose logging\" bootverbosekey !\n\tprintmenuitem .\" Escape to loader prompt\" escapekey !\n\tprintmenuitem .\" Reboot\" rebootkey !\n\tmenuX @ 20 at-xy\n\t.\" Select option, [Enter] for default\"\n\tmenuX @ 21 at-xy\n\ts\" or [Space] to pause timer \" dup 2 - promptwidth !\n\ttype\n;\n\n: tkey\n\tdup\n\tseconds +\n\tbegin 1 while\n\t\tover 0<> if\n\t\t\tdup seconds u< if\n\t\t\t\tdrop\n\t\t\t\t-1\n\t\t\t\texit\n\t\t\tthen\n\t\t\tmenuX @ promptwidth @ + 21 at-xy dup seconds - .\n\t\tthen\n\t\tkey? if\n\t\t\tdrop\n\t\t\tkey\n\t\t\texit\n\t\tthen\n\t50 ms\n\trepeat\n;\n\nset-current\n\n: beastie-start\n\ts\" beastie_disable\" getenv\n\tdup -1 <> if\n\t\ts\" YES\" compare-insensitive 0= if\n\t\t\texit\n\t\tthen\n\tthen\n\tbeastie-menu\n\ts\" autoboot_delay\" getenv\n\tdup -1 = if\n\t\tdrop\n\t\t10\n\telse\n\t\t0 0 2swap >number drop drop drop\n\tthen\n\tbegin true while\n\t\tdup tkey\n\t\t0 25 at-xy\n\t\tdup 32 = if nip 0 swap then\n\t\tdup -1 = if s\" boot\" evaluate then\n\t\tdup 13 = if s\" boot\" evaluate then\n\t\tdup bootkey @ = if s\" boot\" evaluate then\n\t\tdup bootacpikey @ = if\n\t\t\tacpienabled? if\n\t\t\t\ts\" acpi_load\" unsetenv\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\telse\n\t\t\t\ts\" YES\" s\" acpi_load\" setenv\n\t\t\t\ts\" 0\" s\" hint.acpi.0.disabled\" setenv\n\t\t\tthen\n\t\t\ts\" boot\" evaluate\n\t\tthen\n\t\tdup bootsafekey @ = if\n\t\t\ts\" arch-i386\" environment? if\n\t\t\t\ts\" acpi_load\" unsetenv\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\tthen\n\t\t\ts\" 0\" s\" hw.ata.ata_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.atapi_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.wc\" setenv\n\t\t\ts\" 0\" s\" hw.eisa_slots\" setenv\n\t\t\ts\" boot\" evaluate\n\t\tthen\n\t\tdup bootverbosekey @ = if\n\t\t\ts\" YES\" s\" boot_verbose\" setenv\n\t\t\ts\" boot\" evaluate\n\t\tthen\n\t\tdup bootsinglekey @ = if\n\t\t\ts\" YES\" s\" boot_single\" setenv\n\t\t\ts\" boot\" evaluate\n\t\tthen\n\t\tdup escapekey @ = if\n\t\t\t2drop\n\t\t\ts\" NO\" s\" autoboot_delay\" setenv\n\t\t\texit\n\t\tthen\n\t\trebootkey @ = if s\" reboot\" evaluate then\n\trepeat\n;\n\nprevious\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"a7f571cfc278d1d212faf0a50e88ce8c450182c8","subject":"Adjust the quadrature encoder for detent accuracy.","message":"Adjust the quadrature encoder for detent accuracy.","repos":"rbsexton\/gecko,rbsexton\/gecko,rbsexton\/gecko","old_file":"zero\/clock-umb\/forth\/Clock.fth","new_file":"zero\/clock-umb\/forth\/Clock.fth","new_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( -- )\n load-defaults \n icroot 0 over inter.rtcsem ! \\ Reset the free-running counters.\n 0 over inter.rtcdsem ! \\ Reset the free-running counters.\n\n begin \n \tdup inter.rtcsem @offex! ?dup if advancehms then\n \tdup inter.rtcdsem @offex! ?dup if advancedhms then\n [asm wfi asm]\n uiupdate if use-uivals else use-clockvals then \n key? until drop\n;\n \n\\ These two contain loops to ensure that we don't\n\\ drop any timer ticks on the floor.\n: ADVANCEHMS ( n -- ) 0 do hms advancetime loop ;\n: ADVANCEDHMS ( n -- ) 0 do dhms advancetime loop ;\n \n: LOAD-DEFAULTS ( -- )\n interp-init\n;\n\n\\ ----------------------------------------------------------\n\\ Define the structures before they get used.\n\\ ----------------------------------------------------------\nstruct ODN \\ On-Deck Needle \n\tint odn.s\n\tint odn.m\n\tint odn.h\nend-struct\n\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxsec \\ Max Value for secs+minutes\n\tint hms.maxhour \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_m \\ increment the minutes + hours\nend-struct\n\nstruct _interp_set\n\t4 cells field interp.a\n\t4 cells field interp.b\n\t4 cells field interp.c\nend-struct\n\n\\ ----------------------------------------------------------\n\\ Defaults get saved in the user data page.\n\\ ----------------------------------------------------------\n: NVRAMVALID? ( addr -- t\/f ) \n\\ *G See if there is valid data in the NVRAM.\n\\ ** It consists of 3 words. If any of them are \n\\ ** set to 0xffff:ffff, we go with the defaults.\n _USERDATA\n dup @ -1 <> \n over 4 + @ -1 <> and\n swap 8 + @ -1 <> and\n;\n\n: _NVRAMLOAD ( -- ) \n\\ *G Pull the needle maximums from flash.\n $C 0 do I ud@ needle_max I + ! 4 +loop \n; \n\n: NVRAM! ( -- )\n\\ *G Save the contents of the needle cal values.\n 0 UDPAGE_ERASE\n needle_max\n $C 0 do dup I + @ I ud! 4 +loop\n drop \n;\n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nidata\ncreate ODN_HMS odn allot \\ On-Deck, HMS\ncreate ODN_DHMS odn allot \\ On-Deck, DHMS\ncreate ODN_UI odn allot \\ On-Deck, Generated by the UI.\ncdata\n\nidata \\ Has to match an odn.\ncreate NEEDLE_MAX #850 , #850 , #850 ,\ncdata\n\n(( \n: interp-next drop 1 ; \n: interp-reset drop .\" Reset\" ; \n\t\n))\n\n: RANGECHECK ( max n -- n or zero ) 2dup <= if 2drop 0 else swap drop then ; \n\n: INTER-BUMP ( max old interp -- new )\n\\ *G Get the next value from the interpolator, and \n\\ ** reset the interpolator if it wraps around to zero.\n >R R@ interp-next \\ Get the max \n + rangecheck \n dup 0= if R> interp-reset else R> drop then \n ; \n\n: NFETCH ( odn off -- max old )\n\\ *G Combine the current value with the maximum.\n >R R@ \\ stash the offset.\n + @ \\ Calculate the offset address, get the current val.\n needle_max R> + @\n swap \n;\n\n: ++NEEDLE_S \\ Called every time.\n odn_hms 0 odn.s nfetch ( max old )\n\tinterp_hms interp.a inter-bump ( new )\n\todn_hms odn.s ! \n\t;\n\n: ++NEEDLE_M ( -- )\n\\ *G Every time we roll the seconds, bump the minutes and the hour\n\todn_hms 0 odn.m nfetch ( max old )\n\tinterp_hms interp.b inter-bump \n\todn_hms odn.m ! \n\n\todn_hms 0 odn.h nfetch ( max old )\n\tinterp_hms interp.c inter-bump \n\todn_hms odn.h ! \n\t;\n\n: ++NEEDLE_DS ; \\ Called every time.\n: ++NEEDLE_DM ; \\ Every time we roll the seconds.\n\n: _USE ( odn-addr -- ) \n dup odn.s w@ pwm0!\n dup odn.m w@ pwm1!\n odn.h w@ pwm2!\n ;\n\n: USE-CLOCKVALS odn_hms _use ; \n: USE-UIVALS odn_ui _use ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Quadrature\n\\ ----------------------------------------------------------\n\n_timer1 $24 + equ QUAD-IN\n\n\\ The Quadrature encoder produces two per detent.\n: QUAD@ ( -- n ) \\ Fetch and zero\n quad-in @off \n [asm sxth tos, tos asm]\n [asm asr .s tos, tos, # 1 asm] \\ Divide by two,\n ;\n \n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_ds , ' ++needle_dm , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n: ADVANCETIME ( struct-addr -- )\n dup hms.w_s @ execute \\ Invoke the official update word.\n 1 over hms.subsec +! \\ Increment\n dup hms.subsec @\n over hms.maxsubsec @ < if drop exit then \\ If less then max, we're done\n 0 over hms.subsec ! \\ Reset the subsecs \n\n 1 over hms.s +!\n dup hms.s @ over hms.maxsec @ < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n dup hms.w_m @ execute\n 1 over hms.m +!\n dup hms.m @ over hms.maxsec @ < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ over hms.maxhour @ < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ----------------------------------------------------------\n\\ The interpolator. \n\\ Implement bresenhams algorithm. All of this code already\n\\ exists in C, but we'll own the data structures. They contain\n\\ A total of 4 words - fixed, err, num, & denom\n\\ ----------------------------------------------------------\nudata \ncreate interp_hms _interp_set allot\ncreate interp_dhms _interp_set allot \ncreate adj_list #50 cells allot \\ 100 16-bit words. \ncdata\n\n#16 #60 * equ raw_sec\n#10 #100 * equ raw_dsec\n\n: INTERP-INIT ( -- )\n (interp_init) interp_hms\n 2dup interp.a needle_max @ raw_sec call3-- \n 2dup interp.b needle_max 4 + @ #60 call3-- \n interp.c needle_max 8 + @ #12 call3--\n\n (interp_init) interp_dhms\n 2dup interp.a needle_max @ raw_dsec call3-- \n 2dup interp.b needle_max 4 + @ #100 call3-- \n interp.c needle_max 8 + @ #10 call3--\n;\n\n\\ Call the reset fn.\n: INTERP-RESET ( interp_addr -- )\n (interp_reset) swap call1-- \n;\n\n: INTERP-NEXT ( addr -- n )\n (interp_next) swap call1--n\n;\n\n\n\\ ============================ UNTESTED =======================\n\\ VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n\n\\ ----------------------------------------------------------\n\\ User Interface\n\\ ----------------------------------------------------------\nvariable uistate\nvariable uicount \n\n_GPIO $64 + equ _BUTTONIO\n: BUTTONUP? ( -- t\/f ) _buttonio @ 1 and ; \n: BUTTONDOWN? ( -- t\/f ) buttonup? 1 xor ; \n\n\\ The wrapper for all of the UI stuff.\n\\ Returns true if the UI is active - ie, use the values generated by the UI.\n: UIUPDATE ( -- t\/f )\n StateHandlers uistate @ + @ execute \n; \n\n\\ -----------------------------------------------\n\\ State numbers. These are defined x4 so that\n\\ we can just use the state number as an index \n\\ into a table of words.\n\\ -----------------------------------------------\n0 4 * equ _s_init\n1 4 * equ _s_b1\n2 4 * equ _s_1sec\n\n3 4 * equ _s_set_h\n4 4 * equ _s_pendset_m\n5 4 * equ _s_setmin\n\n6 4 * equ _s_pendcal0\n7 4 * equ _s_cal0\n8 4 * equ _s_pendcalh\n9 4 * equ _s_calh\n10 4 * equ _s_pendcalm\n11 4 * equ _s_calm\n12 4 * equ _s_pendcals\n13 4 * equ _s_cals\n\n4 equ downcount_1s\n16 equ downcount_3s \n\n\\ All of the state handlers.\n\\ Everybody needs to know the state of the button, so that must\n\\ get passed in, thus they all look like this:\n\\ state ( t\/f -- t\/f )\n: shInit false \n buttondown? if \n _s_b1 uistate !\n uicount off \\ Reset this.\n then\n ;\n\n\\ Waiting for a full second to go by.\n: shB1 false\n buttonup? if _s_init uistate ! exit then\n \\ The Button is down. \n uicount @ downcount_1s >= if\n _s_1sec uistate !\n else \n 1 uicount +!\n\tthen\n ;\n\n\\ We're in the 1 second state\n: sh1sec true \n buttonup? if _s_set_h uistate ! exit then\n uicount @ downcount_3s >= if\n _s_pendcal0 uistate !\n else \n 1 uicount +!\n\tthen \n;\n\n\\ -------------------------------------------------\n\\ Setting the time\n\\ -------------------------------------------------\n: shSetH true buttondown? if _s_pendset_m uistate ! exit then ;\n\n: shPendSetM true buttonup? if _s_setmin uistate ! then ;\n: shSetMin true buttondown? if _s_init uistate ! exit then ;\n\n\\ -------------------------------------------------\n\\ Calibration\n\\ -------------------------------------------------\n: shPendCal0 true buttonup? if _s_cal0 uistate ! then ;\n: shCal0 true buttondown? if _s_pendcalh uistate ! exit then ;\n\n: shPendCalH true buttonup? if _s_calh uistate ! then ; \n: shCalH true buttondown? if _s_pendcalm uistate ! exit then ; \n\n: shPendCalM true buttonup? if _s_calm uistate ! then ; \n: shCalM true buttondown? if _s_pendcals uistate ! exit then ; \n\n: shPendCalS true buttonup? if _s_calm uistate ! then ; \n: shCalS true buttondown? if _s_init uistate ! exit then ; \n\ncreate StateHandlers \n' shInit , \n' shB1 ,\n' sh1sec ,\n\n' shSetH ,\n' shPendSetM , ' shSetMin ,\n\n' shPendCal0 , ' shCal0 ,\n' shPendCalH , ' shCalH , \n' shPendCalM , ' shCalM , \n' shPendCalS , ' shCalS , \n\n","old_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( -- )\n load-defaults \n icroot 0 over inter.rtcsem ! \\ Reset the free-running counters.\n 0 over inter.rtcdsem ! \\ Reset the free-running counters.\n\n begin \n \tdup inter.rtcsem @offex! ?dup if advancehms then\n \tdup inter.rtcdsem @offex! ?dup if advancedhms then\n [asm wfi asm]\n uiupdate if use-uivals else use-clockvals then \n key? until drop\n;\n \n\\ These two contain loops to ensure that we don't\n\\ drop any timer ticks on the floor.\n: ADVANCEHMS ( n -- ) 0 do hms advancetime loop ;\n: ADVANCEDHMS ( n -- ) 0 do dhms advancetime loop ;\n \n: LOAD-DEFAULTS ( -- )\n interp-init\n;\n\n\\ ----------------------------------------------------------\n\\ Define the structures before they get used.\n\\ ----------------------------------------------------------\nstruct ODN \\ On-Deck Needle \n\tint odn.s\n\tint odn.m\n\tint odn.h\nend-struct\n\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxsec \\ Max Value for secs+minutes\n\tint hms.maxhour \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_m \\ increment the minutes + hours\nend-struct\n\nstruct _interp_set\n\t4 cells field interp.a\n\t4 cells field interp.b\n\t4 cells field interp.c\nend-struct\n\n\\ ----------------------------------------------------------\n\\ Defaults get saved in the user data page.\n\\ ----------------------------------------------------------\n: NVRAMVALID? ( addr -- t\/f ) \n\\ *G See if there is valid data in the NVRAM.\n\\ ** It consists of 3 words. If any of them are \n\\ ** set to 0xffff:ffff, we go with the defaults.\n _USERDATA\n dup @ -1 <> \n over 4 + @ -1 <> and\n swap 8 + @ -1 <> and\n;\n\n: _NVRAMLOAD ( -- ) \n\\ *G Pull the needle maximums from flash.\n $C 0 do I ud@ needle_max I + ! 4 +loop \n; \n\n: NVRAM! ( -- )\n\\ *G Save the contents of the needle cal values.\n 0 UDPAGE_ERASE\n needle_max\n $C 0 do dup I + @ I ud! 4 +loop\n drop \n;\n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nidata\ncreate ODN_HMS odn allot \\ On-Deck, HMS\ncreate ODN_DHMS odn allot \\ On-Deck, DHMS\ncreate ODN_UI odn allot \\ On-Deck, Generated by the UI.\ncdata\n\nidata \\ Has to match an odn.\ncreate NEEDLE_MAX #850 , #850 , #850 ,\ncdata\n\n(( \n: interp-next drop 1 ; \n: interp-reset drop .\" Reset\" ; \n\t\n))\n\n: RANGECHECK ( max n -- n or zero ) 2dup <= if 2drop 0 else swap drop then ; \n\n: INTER-BUMP ( max old interp -- new )\n\\ *G Get the next value from the interpolator, and \n\\ ** reset the interpolator if it wraps around to zero.\n >R R@ interp-next \\ Get the max \n + rangecheck \n dup 0= if R> interp-reset else R> drop then \n ; \n\n: NFETCH ( odn off -- max old )\n\\ *G Combine the current value with the maximum.\n >R R@ \\ stash the offset.\n + @ \\ Calculate the offset address, get the current val.\n needle_max R> + @\n swap \n;\n\n: ++NEEDLE_S \\ Called every time.\n odn_hms 0 odn.s nfetch ( max old )\n\tinterp_hms interp.a inter-bump ( new )\n\todn_hms odn.s ! \n\t;\n\n: ++NEEDLE_M ( -- )\n\\ *G Every time we roll the seconds, bump the minutes and the hour\n\todn_hms 0 odn.m nfetch ( max old )\n\tinterp_hms interp.b inter-bump \n\todn_hms odn.m ! \n\n\todn_hms 0 odn.h nfetch ( max old )\n\tinterp_hms interp.c inter-bump \n\todn_hms odn.h ! \n\t;\n\n: ++NEEDLE_DS ; \\ Called every time.\n: ++NEEDLE_DM ; \\ Every time we roll the seconds.\n\n: _USE ( odn-addr -- ) \n dup odn.s w@ pwm0!\n dup odn.m w@ pwm1!\n odn.h w@ pwm2!\n ;\n\n: USE-CLOCKVALS odn_hms _use ; \n: USE-UIVALS odn_ui _use ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Quadrature\n\\ ----------------------------------------------------------\n\n: QUAD@ ( addr -- n ) \\ Fetch and zero\n @off [asm sxth tos, tos asm] ;\n \n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_ds , ' ++needle_dm , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n: ADVANCETIME ( struct-addr -- )\n dup hms.w_s @ execute \\ Invoke the official update word.\n 1 over hms.subsec +! \\ Increment\n dup hms.subsec @\n over hms.maxsubsec @ < if drop exit then \\ If less then max, we're done\n 0 over hms.subsec ! \\ Reset the subsecs \n\n 1 over hms.s +!\n dup hms.s @ over hms.maxsec @ < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n dup hms.w_m @ execute\n 1 over hms.m +!\n dup hms.m @ over hms.maxsec @ < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ over hms.maxhour @ < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ----------------------------------------------------------\n\\ The interpolator. \n\\ Implement bresenhams algorithm. All of this code already\n\\ exists in C, but we'll own the data structures. They contain\n\\ A total of 4 words - fixed, err, num, & denom\n\\ ----------------------------------------------------------\nudata \ncreate interp_hms _interp_set allot\ncreate interp_dhms _interp_set allot \ncreate adj_list #50 cells allot \\ 100 16-bit words. \ncdata\n\n#16 #60 * equ raw_sec\n#10 #100 * equ raw_dsec\n\n: INTERP-INIT ( -- )\n (interp_init) interp_hms\n 2dup interp.a needle_max @ raw_sec call3-- \n 2dup interp.b needle_max 4 + @ #60 call3-- \n interp.c needle_max 8 + @ #12 call3--\n\n (interp_init) interp_dhms\n 2dup interp.a needle_max @ raw_dsec call3-- \n 2dup interp.b needle_max 4 + @ #100 call3-- \n interp.c needle_max 8 + @ #10 call3--\n;\n\n\\ Call the reset fn.\n: INTERP-RESET ( interp_addr -- )\n (interp_reset) swap call1-- \n;\n\n: INTERP-NEXT ( addr -- n )\n (interp_next) swap call1--n\n;\n\n\n\\ ============================ UNTESTED =======================\n\\ VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n\n\\ ----------------------------------------------------------\n\\ User Interface\n\\ ----------------------------------------------------------\nvariable uistate\nvariable uicount \n\n_GPIO $64 + equ _BUTTONIO\n: BUTTONUP? ( -- t\/f ) _buttonio @ 1 and ; \n: BUTTONDOWN? ( -- t\/f ) buttonup? 1 xor ; \n\n\\ The wrapper for all of the UI stuff.\n\\ Returns true if the UI is active - ie, use the values generated by the UI.\n: UIUPDATE ( -- t\/f )\n StateHandlers uistate @ + @ execute \n; \n\n\\ -----------------------------------------------\n\\ State numbers. These are defined x4 so that\n\\ we can just use the state number as an index \n\\ into a table of words.\n\\ -----------------------------------------------\n0 4 * equ _s_init\n1 4 * equ _s_b1\n2 4 * equ _s_1sec\n\n3 4 * equ _s_set_h\n4 4 * equ _s_pendset_m\n5 4 * equ _s_setmin\n\n6 4 * equ _s_pendcal0\n7 4 * equ _s_cal0\n8 4 * equ _s_pendcalh\n9 4 * equ _s_calh\n10 4 * equ _s_pendcalm\n11 4 * equ _s_calm\n12 4 * equ _s_pendcals\n13 4 * equ _s_cals\n\n4 equ downcount_1s\n16 equ downcount_3s \n\n\\ All of the state handlers.\n\\ Everybody needs to know the state of the button, so that must\n\\ get passed in, thus they all look like this:\n\\ state ( t\/f -- t\/f )\n: shInit false \n buttondown? if \n _s_b1 uistate !\n uicount off \\ Reset this.\n then\n ;\n\n\\ Waiting for a full second to go by.\n: shB1 false\n buttonup? if _s_init uistate ! exit then\n \\ The Button is down. \n uicount @ downcount_1s >= if\n _s_1sec uistate !\n else \n 1 uicount +!\n\tthen\n ;\n\n\\ We're in the 1 second state\n: sh1sec true \n buttonup? if _s_set_h uistate ! exit then\n uicount @ downcount_3s >= if\n _s_pendcal0 uistate !\n else \n 1 uicount +!\n\tthen \n;\n\n\\ -------------------------------------------------\n\\ Setting the time\n\\ -------------------------------------------------\n: shSetH true buttondown? if _s_pendset_m uistate ! exit then ;\n\n: shPendSetM true buttonup? if _s_setmin uistate ! then ;\n: shSetMin true buttondown? if _s_init uistate ! exit then ;\n\n\\ -------------------------------------------------\n\\ Calibration\n\\ -------------------------------------------------\n: shPendCal0 true buttonup? if _s_cal0 uistate ! then ;\n: shCal0 true buttondown? if _s_pendcalh uistate ! exit then ;\n\n: shPendCalH true buttonup? if _s_calh uistate ! then ; \n: shCalH true buttondown? if _s_pendcalm uistate ! exit then ; \n\n: shPendCalM true buttonup? if _s_calm uistate ! then ; \n: shCalM true buttondown? if _s_pendcals uistate ! exit then ; \n\n: shPendCalS true buttonup? if _s_calm uistate ! then ; \n: shCalS true buttondown? if _s_init uistate ! exit then ; \n\ncreate StateHandlers \n' shInit , \n' shB1 ,\n' sh1sec ,\n\n' shSetH ,\n' shPendSetM , ' shSetMin ,\n\n' shPendCal0 , ' shCal0 ,\n' shPendCalH , ' shCalH , \n' shPendCalM , ' shCalM , \n' shPendCalS , ' shCalS , \n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"60fcd204bda22ec520256afb78adb1aa29a5307b","subject":"crank version of the ofwboot, so we can tell which is which","message":"crank version of the ofwboot, so we can tell which is which\n","repos":"orumin\/openbsd-efivars,orumin\/openbsd-efivars,orumin\/openbsd-efivars,orumin\/openbsd-efivars","old_file":"arch\/sparc64\/stand\/bootblk\/bootblk.fth","new_file":"arch\/sparc64\/stand\/bootblk\/bootblk.fth","new_contents":"\\\t$OpenBSD: bootblk.fth,v 1.6 2010\/02\/26 23:03:50 deraadt Exp $\n\\\t$NetBSD: bootblk.fth,v 1.3 2001\/08\/15 20:10:24 eeh Exp $\n\\\n\\\tIEEE 1275 Open Firmware Boot Block\n\\\n\\\tParses disklabel and UFS and loads the file called `ofwboot'\n\\\n\\\n\\\tCopyright (c) 1998 Eduardo Horvath.\n\\\tAll rights reserved.\n\\\n\\\tRedistribution and use in source and binary forms, with or without\n\\\tmodification, are permitted provided that the following conditions\n\\\tare met:\n\\\t1. Redistributions of source code must retain the above copyright\n\\\t notice, this list of conditions and the following disclaimer.\n\\\t2. Redistributions in binary form must reproduce the above copyright\n\\\t notice, this list of conditions and the following disclaimer in the\n\\\t documentation and\/or other materials provided with the distribution.\n\\\t3. All advertising materials mentioning features or use of this software\n\\\t must display the following acknowledgement:\n\\\t This product includes software developed by Eduardo Horvath.\n\\\t4. The name of the author may not be used to endorse or promote products\n\\\t derived from this software without specific prior written permission\n\\\n\\\tTHIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n\\\tIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n\\\tOF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n\\\tIN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n\\\tINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n\\\tNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\\\tDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\\\tTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\\\t(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n\\\tTHIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\\\n\noffset16\nhex\nheaders\n\nfalse value boot-debug?\n\n\\\n\\ First some housekeeping: Open \/chosen and set up vectors into\n\\\tclient-services\n\n\" \/chosen\" find-package 0= if .\" Cannot find \/chosen\" 0 then\nconstant chosen-phandle\n\n\" \/openprom\/client-services\" find-package 0= if \n\t.\" Cannot find client-services\" cr abort\nthen constant cif-phandle\n\ndefer cif-claim ( align size virt -- base )\ndefer cif-release ( size virt -- )\ndefer cif-open ( cstr -- ihandle|0 )\ndefer cif-close ( ihandle -- )\ndefer cif-read ( len adr ihandle -- #read )\ndefer cif-seek ( low high ihandle -- -1|0|1 )\n\\ defer cif-peer ( phandle -- phandle )\n\\ defer cif-getprop ( len adr cstr phandle -- )\n\n: find-cif-method ( method,len -- xf )\n cif-phandle find-method drop \n;\n\n\" claim\" find-cif-method to cif-claim\n\" open\" find-cif-method to cif-open\n\" close\" find-cif-method to cif-close\n\" read\" find-cif-method to cif-read\n\" seek\" find-cif-method to cif-seek\n\n: twiddle ( -- ) .\" .\" ; \\ Need to do this right. Just spit out periods for now.\n\n\\\n\\ Support routines\n\\\n\n: strcmp ( s1 l1 s2 l2 -- true:false )\n rot tuck <> if 3drop false exit then\n comp 0=\n;\n\n\\ Move string into buffer\n\n: strmov ( s1 l1 d -- d l1 )\n dup 2over swap -rot\t\t( s1 l1 d s1 d l1 )\n move\t\t\t\t( s1 l1 d )\n rot drop swap\n;\n\n\\ Move s1 on the end of s2 and return the result\n\n: strcat ( s1 l1 s2 l2 -- d tot )\n 2over swap \t\t\t\t( s1 l1 s2 l2 l1 s1 )\n 2over + rot\t\t\t\t( s1 l1 s2 l2 s1 d l1 )\n move rot + \t\t\t\t( s1 s2 len )\n rot drop\t\t\t\t( s2 len )\n;\n\n: strchr ( s1 l1 c -- s2 l2 )\n begin\n dup 2over 0= if\t\t\t( s1 l1 c c s1 )\n 2drop drop exit then\n c@ = if\t\t\t\t( s1 l1 c )\n drop exit then\n -rot \/c - swap ca1+\t\t( c l2 s2 )\n swap rot\n again\n;\n\n \n: cstr ( ptr -- str len )\n dup \n begin dup c@ 0<> while + repeat\n over -\n;\n\n\\\n\\ BSD FFS parameters\n\\\n\nfload\tassym.fth.h\n\nsbsize buffer: sb-buf\n-1 value boot-ihandle\ndev_bsize value bsize\n0 value raid-offset\t\\ Offset if it's a raid-frame partition\n\n: strategy ( addr size start -- nread )\n raid-offset + bsize * 0 \" seek\" boot-ihandle $call-method\n -1 = if \n .\" strategy: Seek failed\" cr\n abort\n then\n \" read\" boot-ihandle $call-method\n;\n\n\\\n\\ Cylinder group macros\n\\\n\n: cgbase ( cg fs -- cgbase ) fs_fpg l@ * ;\n: cgstart ( cg fs -- cgstart ) \n 2dup fs_cgmask l@ not and\t\t( cg fs stuff -- )\n over fs_cgoffset l@ * -rot\t\t( stuffcg fs -- )\n cgbase +\n;\n: cgdmin ( cg fs -- 1st-data-block ) dup fs_dblkno l@ -rot cgstart + ;\n: cgimin ( cg fs -- inode-block ) dup fs_iblkno l@ -rot cgstart + ;\n: cgsblock ( cg fs -- super-block ) dup fs_sblkno l@ -rot cgstart + ;\n: cgstod ( cg fs -- cg-block ) dup fs_cblkno l@ -rot cgstart + ;\n\n\\\n\\ Block and frag position macros\n\\\n\n: blkoff ( pos fs -- off ) fs_qbmask x@ and ;\n: fragoff ( pos fs -- off ) fs_qfmask x@ and ;\n: lblktosize ( blk fs -- off ) fs_bshift l@ << ;\n: lblkno ( pos fs -- off ) fs_bshift l@ >> ;\n: numfrags ( pos fs -- off ) fs_fshift l@ >> ;\n: blkroundup ( pos fs -- off ) dup fs_bmask l@ -rot fs_qbmask x@ + and ;\n: fragroundup ( pos fs -- off ) dup fs_fmask l@ -rot fs_qfmask x@ + and ;\n\\ : fragroundup ( pos fs -- off ) tuck fs_qfmask x@ + swap fs_fmask l@ and ;\n: fragstoblks ( pos fs -- off ) fs_fragshift l@ >> ;\n: blkstofrags ( blk fs -- frag ) fs_fragshift l@ << ;\n: fragnum ( fsb fs -- off ) fs_frag l@ 1- and ;\n: blknum ( fsb fs -- off ) fs_frag l@ 1- not and ;\n: dblksize ( lbn dino fs -- size )\n -rot \t\t\t\t( fs lbn dino )\n di_size x@\t\t\t\t( fs lbn di_size )\n -rot dup 1+\t\t\t\t( di_size fs lbn lbn+1 )\n 2over fs_bshift l@\t\t\t( di_size fs lbn lbn+1 di_size b_shift )\n rot swap <<\t>=\t\t\t( di_size fs lbn res1 )\n swap ndaddr >= or if\t\t\t( di_size fs )\n swap drop fs_bsize l@ exit\t( size )\n then\ttuck blkoff swap fragroundup\t( size )\n;\n\n\n: ino-to-cg ( ino fs -- cg ) fs_ipg l@ \/ ;\n: ino-to-fsbo ( ino fs -- fsb0 ) fs_inopb l@ mod ;\n: ino-to-fsba ( ino fs -- ba )\t\\ Need to remove the stupid stack diags someday\n 2dup \t\t\t\t( ino fs ino fs )\n ino-to-cg\t\t\t\t( ino fs cg )\n over\t\t\t\t\t( ino fs cg fs )\n cgimin\t\t\t\t( ino fs inode-blk )\n -rot\t\t\t\t\t( inode-blk ino fs )\n tuck \t\t\t\t( inode-blk fs ino fs )\n fs_ipg l@ \t\t\t\t( inode-blk fs ino ipg )\n mod\t\t\t\t\t( inode-blk fs mod )\n swap\t\t\t\t\t( inode-blk mod fs )\n dup \t\t\t\t\t( inode-blk mod fs fs )\n fs_inopb l@ \t\t\t\t( inode-blk mod fs inopb )\n rot \t\t\t\t\t( inode-blk fs inopb mod )\n swap\t\t\t\t\t( inode-blk fs mod inopb )\n \/\t\t\t\t\t( inode-blk fs div )\n swap\t\t\t\t\t( inode-blk div fs )\n blkstofrags\t\t\t\t( inode-blk frag )\n +\n;\n: fsbtodb ( fsb fs -- db ) fs_fsbtodb l@ << ;\n\n\\\n\\ File stuff\n\\\n\nniaddr \/w* constant narraysize\n\nstruct \n 8\t\tfield\t>f_ihandle\t\\ device handle\n 8 \t\tfield \t>f_seekp\t\\ seek pointer\n 8 \t\tfield \t>f_fs\t\t\\ pointer to super block\n ufs1_dinode_SIZEOF \tfield \t>f_di\t\\ copy of on-disk inode\n 8\t\tfield\t>f_buf\t\t\\ buffer for data block\n 4\t\tfield \t>f_buf_size\t\\ size of data block\n 4\t\tfield\t>f_buf_blkno\t\\ block number of data block\nconstant file_SIZEOF\n\nfile_SIZEOF buffer: the-file\nsb-buf the-file >f_fs x!\n\nufs1_dinode_SIZEOF buffer: cur-inode\nh# 2000 buffer: indir-block\n-1 value indir-addr\n\n\\\n\\ Translate a fileblock to a disk block\n\\\n\\ We only allow single indirection\n\\\n\n: block-map ( fileblock -- diskblock )\n \\ Direct block?\n dup ndaddr < if \t\t\t( fileblock )\n cur-inode di_db\t\t\t( arr-indx arr-start )\n swap la+ l@ exit\t\t\t( diskblock )\n then \t\t\t\t( fileblock )\n ndaddr -\t\t\t\t( fileblock' )\n \\ Now we need to check the indirect block\n dup sb-buf fs_nindir l@ < if\t( fileblock' )\n cur-inode di_ib l@ dup\t\t( fileblock' indir-block indir-block )\n indir-addr <> if \t\t( fileblock' indir-block )\n to indir-addr\t\t\t( fileblock' )\n indir-block \t\t\t( fileblock' indir-block )\n sb-buf dup fs_bsize l@\t\t( fileblock' indir-block fs fs_bsize )\n swap indir-addr swap\t\t( fileblock' indir-block fs_bsize indiraddr fs )\n fsbtodb \t\t\t( fileblock' indir-block fs_bsize db )\n strategy\t\t\t( fileblock' nread )\n then\t\t\t\t( fileblock' nread|indir-block )\n drop \\ Really should check return value\n indir-block swap la+ l@ exit\n then\n dup sb-buf fs_nindir -\t\t( fileblock'' )\n \\ Now try 2nd level indirect block -- just read twice \n dup sb-buf fs_nindir l@ dup * < if\t( fileblock'' )\n cur-inode di_ib 1 la+ l@\t\t( fileblock'' indir2-block )\n to indir-addr\t\t\t( fileblock'' )\n \\ load 1st level indir block \n indir-block \t\t\t( fileblock'' indir-block )\n sb-buf dup fs_bsize l@\t\t( fileblock'' indir-block fs fs_bsize )\n swap indir-addr swap\t\t( fileblock'' indir-block fs_bsize indiraddr fs )\n fsbtodb \t\t\t\t( fileblock'' indir-block fs_bsize db )\n strategy\t\t\t\t( fileblock'' nread )\n drop\t\t\t\t( fileblock'' )\n dup sb-buf fs_nindir \/\t\t( fileblock'' indir-offset )\n indir-block swap la+ l@\t\t( fileblock'' indirblock )\n to indir-addr\t\t\t( fileblock'' )\n \\ load 2nd level indir block\n indir-block \t\t\t( fileblock'' indir-block )\n sb-buf dup fs_bsize l@\t\t( fileblock'' indir-block fs fs_bsize )\n swap indir-addr swap\t\t( fileblock'' indir-block fs_bsize indiraddr fs )\n fsbtodb \t\t\t\t( fileblock'' indir-block fs_bsize db )\n strategy\t\t\t\t( fileblock'' nread )\n drop\t\t\t\t( fileblock'' )\n sb-buf fs_nindir l@ mod indir-block swap la+ l@ exit\n then\n .\" block-map: exceeded max file size\" cr\n abort\n;\n\n\\\n\\ Read file into internal buffer and return pointer and len\n\\\n\n0 value cur-block\t\t\t\\ allocated dynamically in ufs-open\n0 value cur-blocksize\t\t\t\\ size of cur-block\n-1 value cur-blockno\n0 value cur-offset\n\n: buf-read-file ( fs -- len buf )\n cur-offset swap\t\t\t( seekp fs )\n 2dup blkoff\t\t\t\t( seekp fs off )\n -rot 2dup lblkno\t\t\t( off seekp fs block )\n swap 2dup cur-inode\t\t\t( off seekp block fs block fs inop )\n swap dblksize\t\t\t( off seekp block fs size )\n rot dup cur-blockno\t\t\t( off seekp fs size block block cur )\n <> if \t\t\t\t( off seekp fs size block )\n block-map\t\t\t\t( off seekp fs size diskblock )\n dup 0= if\t\t\t( off seekp fs size diskblock )\n over cur-block swap 0 fill\t( off seekp fs size diskblock )\n boot-debug? if .\" buf-read-file fell off end of file\" cr then\n else\n 2dup sb-buf fsbtodb cur-block -rot strategy\t( off seekp fs size diskblock nread )\n rot 2dup <> if \" buf-read-file: short read.\" cr abort then\n then\t\t\t\t( off seekp fs diskblock nread size )\n nip nip\t\t\t\t( off seekp fs size )\n else\t\t\t\t\t( off seekp fs size block block cur )\n 2drop\t\t\t\t( off seekp fs size )\n then\n\\ dup cur-offset + to cur-offset\t\\ Set up next xfer -- not done\n nip nip swap -\t\t\t( len )\n cur-block\n;\n\n\\\n\\ Read inode into cur-inode -- uses cur-block\n\\ \n\n: read-inode ( inode fs -- )\n twiddle\t\t\t\t( inode fs -- inode fs )\n\n cur-block\t\t\t\t( inode fs -- inode fs buffer )\n\n over\t\t\t\t\t( inode fs buffer -- inode fs buffer fs )\n fs_bsize l@\t\t\t\t( inode fs buffer -- inode fs buffer size )\n\n 2over\t\t\t\t( inode fs buffer size -- inode fs buffer size inode fs )\n 2over\t\t\t\t( inode fs buffer size inode fs -- inode fs buffer size inode fs buffer size )\n 2swap tuck\t\t\t\t( inode fs buffer size inode fs buffer size -- inode fs buffer size buffer size fs inode fs )\n\n ino-to-fsba \t\t\t\t( inode fs buffer size buffer size fs inode fs -- inode fs buffer size buffer size fs fsba )\n swap\t\t\t\t\t( inode fs buffer size buffer size fs fsba -- inode fs buffer size buffer size fsba fs )\n fsbtodb\t\t\t\t( inode fs buffer size buffer size fsba fs -- inode fs buffer size buffer size db )\n\n dup to cur-blockno\t\t\t( inode fs buffer size buffer size dstart -- inode fs buffer size buffer size dstart )\n strategy\t\t\t\t( inode fs buffer size buffer size dstart -- inode fs buffer size nread )\n <> if .\" read-inode - residual\" cr abort then\n dup 2over\t\t\t\t( inode fs buffer -- inode fs buffer buffer inode fs )\n ino-to-fsbo\t\t\t\t( inode fs buffer -- inode fs buffer buffer fsbo )\n ufs1_dinode_SIZEOF * +\t\t\t( inode fs buffer buffer fsbo -- inode fs buffer dinop )\n cur-inode ufs1_dinode_SIZEOF move \t( inode fs buffer dinop -- inode fs buffer )\n\t\\ clear out the old buffers\n drop\t\t\t\t\t( inode fs buffer -- inode fs )\n 2drop\n;\n\n\\ Identify inode type\n\n: is-dir? ( dinode -- true:false ) di_mode w@ ifmt and ifdir = ;\n: is-symlink? ( dinode -- true:false ) di_mode w@ ifmt and iflnk = ;\n\n\n\n\\\n\\ Hunt for directory entry:\n\\ \n\\ repeat\n\\ load a buffer\n\\ while entries do\n\\ if entry == name return\n\\ next entry\n\\ until no buffers\n\\\n\n: search-directory ( str len -- ino|0 )\n 0 to cur-offset\n begin cur-offset cur-inode di_size x@ < while\t( str len )\n sb-buf buf-read-file\t\t( str len len buf )\n over 0= if .\" search-directory: buf-read-file zero len\" cr abort then\n swap dup cur-offset + to cur-offset\t( str len buf len )\n 2dup + nip\t\t\t( str len buf bufend )\n swap 2swap rot\t\t\t( bufend str len buf )\n begin dup 4 pick < while\t\t( bufend str len buf )\n dup d_ino l@ 0<> if \t\t( bufend str len buf )\n boot-debug? if dup dup d_name swap d_namlen c@ type cr then\n 2dup d_namlen c@ = if\t( bufend str len buf )\n dup d_name 2over\t\t( bufend str len buf dname str len )\n comp 0= if\t\t( bufend str len buf )\n \\ Found it -- return inode\n d_ino l@ nip nip nip\t( dino )\n boot-debug? if .\" Found it\" cr then \n exit \t\t\t( dino )\n then\n then\t\t\t( bufend str len buf )\n then\t\t\t\t( bufend str len buf )\n dup d_reclen w@ +\t\t( bufend str len nextbuf )\n repeat\n drop rot drop\t\t\t( str len )\n repeat\n 2drop 2drop 0\t\t\t( 0 )\n;\n\n: ffs_oldcompat ( -- )\n\\ Make sure old ffs values in sb-buf are sane\n sb-buf fs_npsect dup l@ sb-buf fs_nsect l@ max swap l!\n sb-buf fs_interleave dup l@ 1 max swap l!\n sb-buf fs_postblformat l@ fs_42postblfmt = if\n 8 sb-buf fs_nrpos l!\n then\n sb-buf fs_inodefmt l@ fs_44inodefmt < if\n sb-buf fs_bsize l@ \n dup ndaddr * 1- sb-buf fs_maxfilesize x!\n niaddr 0 ?do\n\tsb-buf fs_nindir l@ * dup\t( sizebp sizebp -- )\n\tsb-buf fs_maxfilesize dup x@\t( sizebp sizebp *fs_maxfilesize fs_maxfilesize -- )\n\trot \t\t\t\t( sizebp *fs_maxfilesize fs_maxfilesize sizebp -- )\n\t+ \t\t\t\t( sizebp *fs_maxfilesize new_fs_maxfilesize -- ) \n swap x! \t\t\t( sizebp -- )\n loop drop \t\t\t( -- )\n sb-buf dup fs_bmask l@ not swap fs_qbmask x!\n sb-buf dup fs_fmask l@ not swap fs_qfmask x!\n then\n;\n\n: read-super ( sector -- )\n0 \" seek\" boot-ihandle $call-method\n -1 = if \n .\" Seek failed\" cr\n abort\n then\n sb-buf sbsize \" read\" boot-ihandle $call-method\n dup sbsize <> if\n .\" Read of superblock failed\" cr\n .\" requested\" space sbsize .\n .\" actual\" space . cr\n abort\n else \n drop\n then\n;\n\n: ufs-open ( bootpath,len -- )\n boot-ihandle -1 = if\n over cif-open dup 0= if \t\t( boot-path len ihandle? )\n .\" Could not open device\" space type cr \n abort\n then \t\t\t\t( boot-path len ihandle )\n to boot-ihandle\t\t\t\\ Save ihandle to boot device\n then 2drop\n sboff read-super\n sb-buf fs_magic l@ fs_magic_value <> if\n 64 dup to raid-offset \n dev_bsize * sboff + read-super\n sb-buf fs_magic l@ fs_magic_value <> if\n .\" Invalid superblock magic\" cr\n abort\n then\n then\n sb-buf fs_bsize l@ dup maxbsize > if\n .\" Superblock bsize\" space . .\" too large\" cr\n abort\n then \n dup fs_SIZEOF < if\n .\" Superblock bsize < size of superblock\" cr\n abort\n then\n ffs_oldcompat\t( fs_bsize -- fs_bsize )\n dup to cur-blocksize alloc-mem to cur-block \\ Allocate cur-block\n boot-debug? if .\" ufs-open complete\" cr then\n;\n\n: ufs-close ( -- ) \n boot-ihandle dup -1 <> if\n cif-close -1 to boot-ihandle \n then\n cur-block 0<> if\n cur-block cur-blocksize free-mem\n then\n;\n\n: boot-path ( -- boot-path )\n \" bootpath\" chosen-phandle get-package-property if\n .\" Could not find bootpath in \/chosen\" cr\n abort\n else\n decode-string 2swap 2drop\n then\n;\n\n: boot-args ( -- boot-args )\n \" bootargs\" chosen-phandle get-package-property if\n .\" Could not find bootargs in \/chosen\" cr\n abort\n else\n decode-string 2swap 2drop\n then\n;\n\n2000 buffer: boot-path-str\n2000 buffer: boot-path-tmp\n\n: split-path ( path len -- right len left len )\n\\ Split a string at the `\/'\n begin\n dup -rot\t\t\t\t( oldlen right len left )\n ascii \/ left-parse-string\t\t( oldlen right len left len )\n dup 0<> if 4 roll drop exit then\n 2drop\t\t\t\t( oldlen right len )\n rot over =\t\t\t( right len diff )\n until\n;\n\n: find-file ( load-file len -- )\n rootino dup sb-buf read-inode\t( load-file len -- load-file len ino )\n -rot\t\t\t\t\t( load-file len ino -- pino load-file len )\n \\\n \\ For each path component\n \\ \n begin split-path dup 0<> while\t( pino right len left len -- )\n cur-inode is-dir? not if .\" Inode not directory\" cr abort then\n boot-debug? if .\" Looking for\" space 2dup type space .\" in directory...\" cr then\n search-directory\t\t\t( pino right len left len -- pino right len ino|false )\n dup 0= if .\" Bad path\" cr abort then\t( pino right len cino )\n sb-buf read-inode\t\t\t( pino right len )\n cur-inode is-symlink? if\t\t\\ Symlink -- follow the damn thing\n \\ Save path in boot-path-tmp\n boot-path-tmp strmov\t\t( pino new-right len )\n\n \\ Now deal with symlink\n cur-inode di_size x@\t\t( pino right len linklen )\n dup sb-buf fs_maxsymlinklen l@\t( pino right len linklen linklen maxlinklen )\n < if\t\t\t\t\\ Now join the link to the path\n cur-inode di_shortlink l@\t( pino right len linklen linkp )\n swap boot-path-str strmov\t( pino right len new-linkp linklen )\n else\t\t\t\t\\ Read file for symlink -- Ugh\n \\ Read link into boot-path-str\n boot-path-str dup sb-buf fs_bsize l@\n 0 block-map\t\t\t( pino right len linklen boot-path-str bsize blockno )\n strategy drop swap\t\t( pino right len boot-path-str linklen )\n then \t\t\t\t( pino right len linkp linklen )\n \\ Concatenate the two paths\n strcat\t\t\t\t( pino new-right newlen )\n swap dup c@ ascii \/ = if\t\\ go to root inode?\n rot drop rootino -rot\t( rino len right )\n then\n rot dup sb-buf read-inode\t( len right pino )\n -rot swap\t\t\t( pino right len )\n then\t\t\t\t( pino right len )\n repeat\n 2drop drop\n;\n\n: read-file ( size addr -- )\n \\ Read x bytes from a file to buffer\n begin over 0> while\n cur-offset cur-inode di_size x@ > if .\" read-file EOF exceeded\" cr abort then\n sb-buf buf-read-file\t\t( size addr len buf )\n over 2over drop swap\t\t( size addr len buf addr len )\n move\t\t\t\t( size addr len )\n dup cur-offset + to cur-offset\t( size len newaddr )\n tuck +\t\t\t\t( size len newaddr )\n -rot - swap\t\t\t( newaddr newsize )\n repeat\n 2drop\n;\n\n\\\n\\ According to the 1275 addendum for SPARC processors:\n\\ Default load-base is 0x4000. At least 0x8.0000 or\n\\ 512KB must be available at that address. \n\\\n\\ The Fcode bootblock can take up up to 8KB (O.K., 7.5KB) \n\\ so load programs at 0x4000 + 0x2000=> 0x6000\n\\\n\nh# 6000 constant loader-base\n\n\\\n\\ Elf support -- find the load addr\n\\\n\n: is-elf? ( hdr -- res? ) h# 7f454c46 = ;\n\n\\\n\\ Finally we finish it all off\n\\\n\n: load-file-signon ( load-file len boot-path len -- load-file len boot-path len )\n .\" Loading file\" space 2over type cr .\" from device\" space 2dup type cr\n;\n\n: load-file-print-size ( size -- size )\n .\" Loading\" space dup . space .\" bytes of file...\" cr \n;\n\n: load-file ( load-file len boot-path len -- load-base )\n boot-debug? if load-file-signon then\n the-file file_SIZEOF 0 fill\t\t\\ Clear out file structure\n ufs-open \t\t\t\t( load-file len )\n find-file\t\t\t\t( )\n\n \\\n \\ Now we've found the file we should read it in in one big hunk\n \\\n\n cur-inode di_size x@\t\t\t( file-len )\n dup \" to file-size\" evaluate\t\t( file-len )\n boot-debug? if load-file-print-size then\n 0 to cur-offset\n loader-base\t\t\t\t( buf-len addr )\n 2dup read-file\t\t\t( buf-len addr )\n ufs-close\t\t\t\t( buf-len addr )\n dup is-elf? if .\" load-file: not an elf executable\" cr abort then\n\n \\ Luckily the prom should be able to handle ELF executables by itself\n\n nip\t\t\t\t\t( addr )\n;\n\n: do-boot ( bootfile -- )\n .\" OpenBSD IEEE 1275 Bootblock 1.2\" cr\n boot-path load-file ( -- load-base )\n dup 0<> if \" to load-base init-program\" evaluate then\n;\n\n\nboot-args ascii V strchr 0<> swap drop if\n true to boot-debug?\nthen\n\nboot-args ascii D strchr 0= swap drop if\n \" \/ofwboot\" do-boot\nthen exit\n\n\n","old_contents":"\\\t$OpenBSD: bootblk.fth,v 1.5 2010\/02\/26 19:59:11 deraadt Exp $\n\\\t$NetBSD: bootblk.fth,v 1.3 2001\/08\/15 20:10:24 eeh Exp $\n\\\n\\\tIEEE 1275 Open Firmware Boot Block\n\\\n\\\tParses disklabel and UFS and loads the file called `ofwboot'\n\\\n\\\n\\\tCopyright (c) 1998 Eduardo Horvath.\n\\\tAll rights reserved.\n\\\n\\\tRedistribution and use in source and binary forms, with or without\n\\\tmodification, are permitted provided that the following conditions\n\\\tare met:\n\\\t1. Redistributions of source code must retain the above copyright\n\\\t notice, this list of conditions and the following disclaimer.\n\\\t2. Redistributions in binary form must reproduce the above copyright\n\\\t notice, this list of conditions and the following disclaimer in the\n\\\t documentation and\/or other materials provided with the distribution.\n\\\t3. All advertising materials mentioning features or use of this software\n\\\t must display the following acknowledgement:\n\\\t This product includes software developed by Eduardo Horvath.\n\\\t4. The name of the author may not be used to endorse or promote products\n\\\t derived from this software without specific prior written permission\n\\\n\\\tTHIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n\\\tIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n\\\tOF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n\\\tIN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n\\\tINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n\\\tNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\\\tDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\\\tTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\\\t(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n\\\tTHIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\\\n\noffset16\nhex\nheaders\n\nfalse value boot-debug?\n\n\\\n\\ First some housekeeping: Open \/chosen and set up vectors into\n\\\tclient-services\n\n\" \/chosen\" find-package 0= if .\" Cannot find \/chosen\" 0 then\nconstant chosen-phandle\n\n\" \/openprom\/client-services\" find-package 0= if \n\t.\" Cannot find client-services\" cr abort\nthen constant cif-phandle\n\ndefer cif-claim ( align size virt -- base )\ndefer cif-release ( size virt -- )\ndefer cif-open ( cstr -- ihandle|0 )\ndefer cif-close ( ihandle -- )\ndefer cif-read ( len adr ihandle -- #read )\ndefer cif-seek ( low high ihandle -- -1|0|1 )\n\\ defer cif-peer ( phandle -- phandle )\n\\ defer cif-getprop ( len adr cstr phandle -- )\n\n: find-cif-method ( method,len -- xf )\n cif-phandle find-method drop \n;\n\n\" claim\" find-cif-method to cif-claim\n\" open\" find-cif-method to cif-open\n\" close\" find-cif-method to cif-close\n\" read\" find-cif-method to cif-read\n\" seek\" find-cif-method to cif-seek\n\n: twiddle ( -- ) .\" .\" ; \\ Need to do this right. Just spit out periods for now.\n\n\\\n\\ Support routines\n\\\n\n: strcmp ( s1 l1 s2 l2 -- true:false )\n rot tuck <> if 3drop false exit then\n comp 0=\n;\n\n\\ Move string into buffer\n\n: strmov ( s1 l1 d -- d l1 )\n dup 2over swap -rot\t\t( s1 l1 d s1 d l1 )\n move\t\t\t\t( s1 l1 d )\n rot drop swap\n;\n\n\\ Move s1 on the end of s2 and return the result\n\n: strcat ( s1 l1 s2 l2 -- d tot )\n 2over swap \t\t\t\t( s1 l1 s2 l2 l1 s1 )\n 2over + rot\t\t\t\t( s1 l1 s2 l2 s1 d l1 )\n move rot + \t\t\t\t( s1 s2 len )\n rot drop\t\t\t\t( s2 len )\n;\n\n: strchr ( s1 l1 c -- s2 l2 )\n begin\n dup 2over 0= if\t\t\t( s1 l1 c c s1 )\n 2drop drop exit then\n c@ = if\t\t\t\t( s1 l1 c )\n drop exit then\n -rot \/c - swap ca1+\t\t( c l2 s2 )\n swap rot\n again\n;\n\n \n: cstr ( ptr -- str len )\n dup \n begin dup c@ 0<> while + repeat\n over -\n;\n\n\\\n\\ BSD FFS parameters\n\\\n\nfload\tassym.fth.h\n\nsbsize buffer: sb-buf\n-1 value boot-ihandle\ndev_bsize value bsize\n0 value raid-offset\t\\ Offset if it's a raid-frame partition\n\n: strategy ( addr size start -- nread )\n raid-offset + bsize * 0 \" seek\" boot-ihandle $call-method\n -1 = if \n .\" strategy: Seek failed\" cr\n abort\n then\n \" read\" boot-ihandle $call-method\n;\n\n\\\n\\ Cylinder group macros\n\\\n\n: cgbase ( cg fs -- cgbase ) fs_fpg l@ * ;\n: cgstart ( cg fs -- cgstart ) \n 2dup fs_cgmask l@ not and\t\t( cg fs stuff -- )\n over fs_cgoffset l@ * -rot\t\t( stuffcg fs -- )\n cgbase +\n;\n: cgdmin ( cg fs -- 1st-data-block ) dup fs_dblkno l@ -rot cgstart + ;\n: cgimin ( cg fs -- inode-block ) dup fs_iblkno l@ -rot cgstart + ;\n: cgsblock ( cg fs -- super-block ) dup fs_sblkno l@ -rot cgstart + ;\n: cgstod ( cg fs -- cg-block ) dup fs_cblkno l@ -rot cgstart + ;\n\n\\\n\\ Block and frag position macros\n\\\n\n: blkoff ( pos fs -- off ) fs_qbmask x@ and ;\n: fragoff ( pos fs -- off ) fs_qfmask x@ and ;\n: lblktosize ( blk fs -- off ) fs_bshift l@ << ;\n: lblkno ( pos fs -- off ) fs_bshift l@ >> ;\n: numfrags ( pos fs -- off ) fs_fshift l@ >> ;\n: blkroundup ( pos fs -- off ) dup fs_bmask l@ -rot fs_qbmask x@ + and ;\n: fragroundup ( pos fs -- off ) dup fs_fmask l@ -rot fs_qfmask x@ + and ;\n\\ : fragroundup ( pos fs -- off ) tuck fs_qfmask x@ + swap fs_fmask l@ and ;\n: fragstoblks ( pos fs -- off ) fs_fragshift l@ >> ;\n: blkstofrags ( blk fs -- frag ) fs_fragshift l@ << ;\n: fragnum ( fsb fs -- off ) fs_frag l@ 1- and ;\n: blknum ( fsb fs -- off ) fs_frag l@ 1- not and ;\n: dblksize ( lbn dino fs -- size )\n -rot \t\t\t\t( fs lbn dino )\n di_size x@\t\t\t\t( fs lbn di_size )\n -rot dup 1+\t\t\t\t( di_size fs lbn lbn+1 )\n 2over fs_bshift l@\t\t\t( di_size fs lbn lbn+1 di_size b_shift )\n rot swap <<\t>=\t\t\t( di_size fs lbn res1 )\n swap ndaddr >= or if\t\t\t( di_size fs )\n swap drop fs_bsize l@ exit\t( size )\n then\ttuck blkoff swap fragroundup\t( size )\n;\n\n\n: ino-to-cg ( ino fs -- cg ) fs_ipg l@ \/ ;\n: ino-to-fsbo ( ino fs -- fsb0 ) fs_inopb l@ mod ;\n: ino-to-fsba ( ino fs -- ba )\t\\ Need to remove the stupid stack diags someday\n 2dup \t\t\t\t( ino fs ino fs )\n ino-to-cg\t\t\t\t( ino fs cg )\n over\t\t\t\t\t( ino fs cg fs )\n cgimin\t\t\t\t( ino fs inode-blk )\n -rot\t\t\t\t\t( inode-blk ino fs )\n tuck \t\t\t\t( inode-blk fs ino fs )\n fs_ipg l@ \t\t\t\t( inode-blk fs ino ipg )\n mod\t\t\t\t\t( inode-blk fs mod )\n swap\t\t\t\t\t( inode-blk mod fs )\n dup \t\t\t\t\t( inode-blk mod fs fs )\n fs_inopb l@ \t\t\t\t( inode-blk mod fs inopb )\n rot \t\t\t\t\t( inode-blk fs inopb mod )\n swap\t\t\t\t\t( inode-blk fs mod inopb )\n \/\t\t\t\t\t( inode-blk fs div )\n swap\t\t\t\t\t( inode-blk div fs )\n blkstofrags\t\t\t\t( inode-blk frag )\n +\n;\n: fsbtodb ( fsb fs -- db ) fs_fsbtodb l@ << ;\n\n\\\n\\ File stuff\n\\\n\nniaddr \/w* constant narraysize\n\nstruct \n 8\t\tfield\t>f_ihandle\t\\ device handle\n 8 \t\tfield \t>f_seekp\t\\ seek pointer\n 8 \t\tfield \t>f_fs\t\t\\ pointer to super block\n ufs1_dinode_SIZEOF \tfield \t>f_di\t\\ copy of on-disk inode\n 8\t\tfield\t>f_buf\t\t\\ buffer for data block\n 4\t\tfield \t>f_buf_size\t\\ size of data block\n 4\t\tfield\t>f_buf_blkno\t\\ block number of data block\nconstant file_SIZEOF\n\nfile_SIZEOF buffer: the-file\nsb-buf the-file >f_fs x!\n\nufs1_dinode_SIZEOF buffer: cur-inode\nh# 2000 buffer: indir-block\n-1 value indir-addr\n\n\\\n\\ Translate a fileblock to a disk block\n\\\n\\ We only allow single indirection\n\\\n\n: block-map ( fileblock -- diskblock )\n \\ Direct block?\n dup ndaddr < if \t\t\t( fileblock )\n cur-inode di_db\t\t\t( arr-indx arr-start )\n swap la+ l@ exit\t\t\t( diskblock )\n then \t\t\t\t( fileblock )\n ndaddr -\t\t\t\t( fileblock' )\n \\ Now we need to check the indirect block\n dup sb-buf fs_nindir l@ < if\t( fileblock' )\n cur-inode di_ib l@ dup\t\t( fileblock' indir-block indir-block )\n indir-addr <> if \t\t( fileblock' indir-block )\n to indir-addr\t\t\t( fileblock' )\n indir-block \t\t\t( fileblock' indir-block )\n sb-buf dup fs_bsize l@\t\t( fileblock' indir-block fs fs_bsize )\n swap indir-addr swap\t\t( fileblock' indir-block fs_bsize indiraddr fs )\n fsbtodb \t\t\t( fileblock' indir-block fs_bsize db )\n strategy\t\t\t( fileblock' nread )\n then\t\t\t\t( fileblock' nread|indir-block )\n drop \\ Really should check return value\n indir-block swap la+ l@ exit\n then\n dup sb-buf fs_nindir -\t\t( fileblock'' )\n \\ Now try 2nd level indirect block -- just read twice \n dup sb-buf fs_nindir l@ dup * < if\t( fileblock'' )\n cur-inode di_ib 1 la+ l@\t\t( fileblock'' indir2-block )\n to indir-addr\t\t\t( fileblock'' )\n \\ load 1st level indir block \n indir-block \t\t\t( fileblock'' indir-block )\n sb-buf dup fs_bsize l@\t\t( fileblock'' indir-block fs fs_bsize )\n swap indir-addr swap\t\t( fileblock'' indir-block fs_bsize indiraddr fs )\n fsbtodb \t\t\t\t( fileblock'' indir-block fs_bsize db )\n strategy\t\t\t\t( fileblock'' nread )\n drop\t\t\t\t( fileblock'' )\n dup sb-buf fs_nindir \/\t\t( fileblock'' indir-offset )\n indir-block swap la+ l@\t\t( fileblock'' indirblock )\n to indir-addr\t\t\t( fileblock'' )\n \\ load 2nd level indir block\n indir-block \t\t\t( fileblock'' indir-block )\n sb-buf dup fs_bsize l@\t\t( fileblock'' indir-block fs fs_bsize )\n swap indir-addr swap\t\t( fileblock'' indir-block fs_bsize indiraddr fs )\n fsbtodb \t\t\t\t( fileblock'' indir-block fs_bsize db )\n strategy\t\t\t\t( fileblock'' nread )\n drop\t\t\t\t( fileblock'' )\n sb-buf fs_nindir l@ mod indir-block swap la+ l@ exit\n then\n .\" block-map: exceeded max file size\" cr\n abort\n;\n\n\\\n\\ Read file into internal buffer and return pointer and len\n\\\n\n0 value cur-block\t\t\t\\ allocated dynamically in ufs-open\n0 value cur-blocksize\t\t\t\\ size of cur-block\n-1 value cur-blockno\n0 value cur-offset\n\n: buf-read-file ( fs -- len buf )\n cur-offset swap\t\t\t( seekp fs )\n 2dup blkoff\t\t\t\t( seekp fs off )\n -rot 2dup lblkno\t\t\t( off seekp fs block )\n swap 2dup cur-inode\t\t\t( off seekp block fs block fs inop )\n swap dblksize\t\t\t( off seekp block fs size )\n rot dup cur-blockno\t\t\t( off seekp fs size block block cur )\n <> if \t\t\t\t( off seekp fs size block )\n block-map\t\t\t\t( off seekp fs size diskblock )\n dup 0= if\t\t\t( off seekp fs size diskblock )\n over cur-block swap 0 fill\t( off seekp fs size diskblock )\n boot-debug? if .\" buf-read-file fell off end of file\" cr then\n else\n 2dup sb-buf fsbtodb cur-block -rot strategy\t( off seekp fs size diskblock nread )\n rot 2dup <> if \" buf-read-file: short read.\" cr abort then\n then\t\t\t\t( off seekp fs diskblock nread size )\n nip nip\t\t\t\t( off seekp fs size )\n else\t\t\t\t\t( off seekp fs size block block cur )\n 2drop\t\t\t\t( off seekp fs size )\n then\n\\ dup cur-offset + to cur-offset\t\\ Set up next xfer -- not done\n nip nip swap -\t\t\t( len )\n cur-block\n;\n\n\\\n\\ Read inode into cur-inode -- uses cur-block\n\\ \n\n: read-inode ( inode fs -- )\n twiddle\t\t\t\t( inode fs -- inode fs )\n\n cur-block\t\t\t\t( inode fs -- inode fs buffer )\n\n over\t\t\t\t\t( inode fs buffer -- inode fs buffer fs )\n fs_bsize l@\t\t\t\t( inode fs buffer -- inode fs buffer size )\n\n 2over\t\t\t\t( inode fs buffer size -- inode fs buffer size inode fs )\n 2over\t\t\t\t( inode fs buffer size inode fs -- inode fs buffer size inode fs buffer size )\n 2swap tuck\t\t\t\t( inode fs buffer size inode fs buffer size -- inode fs buffer size buffer size fs inode fs )\n\n ino-to-fsba \t\t\t\t( inode fs buffer size buffer size fs inode fs -- inode fs buffer size buffer size fs fsba )\n swap\t\t\t\t\t( inode fs buffer size buffer size fs fsba -- inode fs buffer size buffer size fsba fs )\n fsbtodb\t\t\t\t( inode fs buffer size buffer size fsba fs -- inode fs buffer size buffer size db )\n\n dup to cur-blockno\t\t\t( inode fs buffer size buffer size dstart -- inode fs buffer size buffer size dstart )\n strategy\t\t\t\t( inode fs buffer size buffer size dstart -- inode fs buffer size nread )\n <> if .\" read-inode - residual\" cr abort then\n dup 2over\t\t\t\t( inode fs buffer -- inode fs buffer buffer inode fs )\n ino-to-fsbo\t\t\t\t( inode fs buffer -- inode fs buffer buffer fsbo )\n ufs1_dinode_SIZEOF * +\t\t\t( inode fs buffer buffer fsbo -- inode fs buffer dinop )\n cur-inode ufs1_dinode_SIZEOF move \t( inode fs buffer dinop -- inode fs buffer )\n\t\\ clear out the old buffers\n drop\t\t\t\t\t( inode fs buffer -- inode fs )\n 2drop\n;\n\n\\ Identify inode type\n\n: is-dir? ( dinode -- true:false ) di_mode w@ ifmt and ifdir = ;\n: is-symlink? ( dinode -- true:false ) di_mode w@ ifmt and iflnk = ;\n\n\n\n\\\n\\ Hunt for directory entry:\n\\ \n\\ repeat\n\\ load a buffer\n\\ while entries do\n\\ if entry == name return\n\\ next entry\n\\ until no buffers\n\\\n\n: search-directory ( str len -- ino|0 )\n 0 to cur-offset\n begin cur-offset cur-inode di_size x@ < while\t( str len )\n sb-buf buf-read-file\t\t( str len len buf )\n over 0= if .\" search-directory: buf-read-file zero len\" cr abort then\n swap dup cur-offset + to cur-offset\t( str len buf len )\n 2dup + nip\t\t\t( str len buf bufend )\n swap 2swap rot\t\t\t( bufend str len buf )\n begin dup 4 pick < while\t\t( bufend str len buf )\n dup d_ino l@ 0<> if \t\t( bufend str len buf )\n boot-debug? if dup dup d_name swap d_namlen c@ type cr then\n 2dup d_namlen c@ = if\t( bufend str len buf )\n dup d_name 2over\t\t( bufend str len buf dname str len )\n comp 0= if\t\t( bufend str len buf )\n \\ Found it -- return inode\n d_ino l@ nip nip nip\t( dino )\n boot-debug? if .\" Found it\" cr then \n exit \t\t\t( dino )\n then\n then\t\t\t( bufend str len buf )\n then\t\t\t\t( bufend str len buf )\n dup d_reclen w@ +\t\t( bufend str len nextbuf )\n repeat\n drop rot drop\t\t\t( str len )\n repeat\n 2drop 2drop 0\t\t\t( 0 )\n;\n\n: ffs_oldcompat ( -- )\n\\ Make sure old ffs values in sb-buf are sane\n sb-buf fs_npsect dup l@ sb-buf fs_nsect l@ max swap l!\n sb-buf fs_interleave dup l@ 1 max swap l!\n sb-buf fs_postblformat l@ fs_42postblfmt = if\n 8 sb-buf fs_nrpos l!\n then\n sb-buf fs_inodefmt l@ fs_44inodefmt < if\n sb-buf fs_bsize l@ \n dup ndaddr * 1- sb-buf fs_maxfilesize x!\n niaddr 0 ?do\n\tsb-buf fs_nindir l@ * dup\t( sizebp sizebp -- )\n\tsb-buf fs_maxfilesize dup x@\t( sizebp sizebp *fs_maxfilesize fs_maxfilesize -- )\n\trot \t\t\t\t( sizebp *fs_maxfilesize fs_maxfilesize sizebp -- )\n\t+ \t\t\t\t( sizebp *fs_maxfilesize new_fs_maxfilesize -- ) \n swap x! \t\t\t( sizebp -- )\n loop drop \t\t\t( -- )\n sb-buf dup fs_bmask l@ not swap fs_qbmask x!\n sb-buf dup fs_fmask l@ not swap fs_qfmask x!\n then\n;\n\n: read-super ( sector -- )\n0 \" seek\" boot-ihandle $call-method\n -1 = if \n .\" Seek failed\" cr\n abort\n then\n sb-buf sbsize \" read\" boot-ihandle $call-method\n dup sbsize <> if\n .\" Read of superblock failed\" cr\n .\" requested\" space sbsize .\n .\" actual\" space . cr\n abort\n else \n drop\n then\n;\n\n: ufs-open ( bootpath,len -- )\n boot-ihandle -1 = if\n over cif-open dup 0= if \t\t( boot-path len ihandle? )\n .\" Could not open device\" space type cr \n abort\n then \t\t\t\t( boot-path len ihandle )\n to boot-ihandle\t\t\t\\ Save ihandle to boot device\n then 2drop\n sboff read-super\n sb-buf fs_magic l@ fs_magic_value <> if\n 64 dup to raid-offset \n dev_bsize * sboff + read-super\n sb-buf fs_magic l@ fs_magic_value <> if\n .\" Invalid superblock magic\" cr\n abort\n then\n then\n sb-buf fs_bsize l@ dup maxbsize > if\n .\" Superblock bsize\" space . .\" too large\" cr\n abort\n then \n dup fs_SIZEOF < if\n .\" Superblock bsize < size of superblock\" cr\n abort\n then\n ffs_oldcompat\t( fs_bsize -- fs_bsize )\n dup to cur-blocksize alloc-mem to cur-block \\ Allocate cur-block\n boot-debug? if .\" ufs-open complete\" cr then\n;\n\n: ufs-close ( -- ) \n boot-ihandle dup -1 <> if\n cif-close -1 to boot-ihandle \n then\n cur-block 0<> if\n cur-block cur-blocksize free-mem\n then\n;\n\n: boot-path ( -- boot-path )\n \" bootpath\" chosen-phandle get-package-property if\n .\" Could not find bootpath in \/chosen\" cr\n abort\n else\n decode-string 2swap 2drop\n then\n;\n\n: boot-args ( -- boot-args )\n \" bootargs\" chosen-phandle get-package-property if\n .\" Could not find bootargs in \/chosen\" cr\n abort\n else\n decode-string 2swap 2drop\n then\n;\n\n2000 buffer: boot-path-str\n2000 buffer: boot-path-tmp\n\n: split-path ( path len -- right len left len )\n\\ Split a string at the `\/'\n begin\n dup -rot\t\t\t\t( oldlen right len left )\n ascii \/ left-parse-string\t\t( oldlen right len left len )\n dup 0<> if 4 roll drop exit then\n 2drop\t\t\t\t( oldlen right len )\n rot over =\t\t\t( right len diff )\n until\n;\n\n: find-file ( load-file len -- )\n rootino dup sb-buf read-inode\t( load-file len -- load-file len ino )\n -rot\t\t\t\t\t( load-file len ino -- pino load-file len )\n \\\n \\ For each path component\n \\ \n begin split-path dup 0<> while\t( pino right len left len -- )\n cur-inode is-dir? not if .\" Inode not directory\" cr abort then\n boot-debug? if .\" Looking for\" space 2dup type space .\" in directory...\" cr then\n search-directory\t\t\t( pino right len left len -- pino right len ino|false )\n dup 0= if .\" Bad path\" cr abort then\t( pino right len cino )\n sb-buf read-inode\t\t\t( pino right len )\n cur-inode is-symlink? if\t\t\\ Symlink -- follow the damn thing\n \\ Save path in boot-path-tmp\n boot-path-tmp strmov\t\t( pino new-right len )\n\n \\ Now deal with symlink\n cur-inode di_size x@\t\t( pino right len linklen )\n dup sb-buf fs_maxsymlinklen l@\t( pino right len linklen linklen maxlinklen )\n < if\t\t\t\t\\ Now join the link to the path\n cur-inode di_shortlink l@\t( pino right len linklen linkp )\n swap boot-path-str strmov\t( pino right len new-linkp linklen )\n else\t\t\t\t\\ Read file for symlink -- Ugh\n \\ Read link into boot-path-str\n boot-path-str dup sb-buf fs_bsize l@\n 0 block-map\t\t\t( pino right len linklen boot-path-str bsize blockno )\n strategy drop swap\t\t( pino right len boot-path-str linklen )\n then \t\t\t\t( pino right len linkp linklen )\n \\ Concatenate the two paths\n strcat\t\t\t\t( pino new-right newlen )\n swap dup c@ ascii \/ = if\t\\ go to root inode?\n rot drop rootino -rot\t( rino len right )\n then\n rot dup sb-buf read-inode\t( len right pino )\n -rot swap\t\t\t( pino right len )\n then\t\t\t\t( pino right len )\n repeat\n 2drop drop\n;\n\n: read-file ( size addr -- )\n \\ Read x bytes from a file to buffer\n begin over 0> while\n cur-offset cur-inode di_size x@ > if .\" read-file EOF exceeded\" cr abort then\n sb-buf buf-read-file\t\t( size addr len buf )\n over 2over drop swap\t\t( size addr len buf addr len )\n move\t\t\t\t( size addr len )\n dup cur-offset + to cur-offset\t( size len newaddr )\n tuck +\t\t\t\t( size len newaddr )\n -rot - swap\t\t\t( newaddr newsize )\n repeat\n 2drop\n;\n\n\\\n\\ According to the 1275 addendum for SPARC processors:\n\\ Default load-base is 0x4000. At least 0x8.0000 or\n\\ 512KB must be available at that address. \n\\\n\\ The Fcode bootblock can take up up to 8KB (O.K., 7.5KB) \n\\ so load programs at 0x4000 + 0x2000=> 0x6000\n\\\n\nh# 6000 constant loader-base\n\n\\\n\\ Elf support -- find the load addr\n\\\n\n: is-elf? ( hdr -- res? ) h# 7f454c46 = ;\n\n\\\n\\ Finally we finish it all off\n\\\n\n: load-file-signon ( load-file len boot-path len -- load-file len boot-path len )\n .\" Loading file\" space 2over type cr .\" from device\" space 2dup type cr\n;\n\n: load-file-print-size ( size -- size )\n .\" Loading\" space dup . space .\" bytes of file...\" cr \n;\n\n: load-file ( load-file len boot-path len -- load-base )\n boot-debug? if load-file-signon then\n the-file file_SIZEOF 0 fill\t\t\\ Clear out file structure\n ufs-open \t\t\t\t( load-file len )\n find-file\t\t\t\t( )\n\n \\\n \\ Now we've found the file we should read it in in one big hunk\n \\\n\n cur-inode di_size x@\t\t\t( file-len )\n dup \" to file-size\" evaluate\t\t( file-len )\n boot-debug? if load-file-print-size then\n 0 to cur-offset\n loader-base\t\t\t\t( buf-len addr )\n 2dup read-file\t\t\t( buf-len addr )\n ufs-close\t\t\t\t( buf-len addr )\n dup is-elf? if .\" load-file: not an elf executable\" cr abort then\n\n \\ Luckily the prom should be able to handle ELF executables by itself\n\n nip\t\t\t\t\t( addr )\n;\n\n: do-boot ( bootfile -- )\n .\" OpenBSD IEEE 1275 Bootblock 1.1\" cr\n boot-path load-file ( -- load-base )\n dup 0<> if \" to load-base init-program\" evaluate then\n;\n\n\nboot-args ascii V strchr 0<> swap drop if\n true to boot-debug?\nthen\n\nboot-args ascii D strchr 0= swap drop if\n \" \/ofwboot\" do-boot\nthen exit\n\n\n","returncode":0,"stderr":"","license":"isc","lang":"Forth"} {"commit":"c8e5506ce2c4a5d5c29258bd45d3600a71071133","subject":"Dash the stash","message":"Dash the stash\n","repos":"rm-hull\/byok3,rm-hull\/byok3","old_file":"core\/src\/main\/resources\/forth\/system.fth","new_file":"core\/src\/main\/resources\/forth\/system.fth","new_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\\n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n\n: COUNT dup 1+ swap c@ ;\n\n\\ Miscellaneous support words\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: <= ( a b -- f , true if A <= b ) > 0= ;\n: >= ( a b -- f , true if A >= b ) < 0= ;\n: NOT ( n -- !n , logical negation ) 0= ;\n: DNEGATE ( d -- -d , negate by doing 0-d )\n 0 swap -\n;\n: CELL+ ( n -- n+cell ) cell + ;\n: CELL- ( n -- n-cell ) cell - ;\n: CELL* ( n -- n*cell ) cells ;\n\n: CHAR+ ( n -- n+size_of_char ) 1+ ;\n: CHARS ( n -- n*size_of_char, don't do anything ) ; immediate\n\n\\ useful stack manipulation words\n: -ROT ( a b c -- c a b ) rot rot ;\n: 3DUP ( a b c -- a b c a b c ) 2 pick 2 pick 2 pick ;\n\n\\ ------------------------------------------------------------------\n: ID. ( nfa -- ) count 31 and type ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: PAD ( -- addr ) here 128 + ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n\n: BETWEEN ( n lo hi -- flag , true if between lo & hi )\n >r over r> > >r\n < r> or 0=\n;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: ? ( -- ) @ . ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ ' (lit) , cell 1- , ] +\n [ ' (lit) , cell 1- invert , ] and ;\n\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n: ALLOT ( nbytes -- , allot space in dictionary ) dp +! align ;\n\n: C, ( c -- ) here c! 1 dp +! ;\n\\ : W, ( w -- ) dp @ even-up dup dp ! w! 2 dp +! ;\n\\ : , ( n -- , lay into dictionary ) align here ! cell allot ;\n\n: SEE ( -- )\n ' dup\n >body swap >size\n disassemble ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token )\n [compile] literal ( compile a call to literal )\n ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick )\n ?comp ' [compile] literal\n; immediate\n\n: (DOES>) ( xt -- , modify previous definition to execute code at xt )\n latest >body \\ get address of code for new word\n 3 cell* + \\ offset to EXIT cell in create word\n ! \\ store execution token of DOES> code in new word\n;\n\n: DOES> ( -- , define execution code for CREATE word )\n 0 [compile] literal \\ dummy literal to hold xt\n here cell- \\ address of zero in literal\n compile (does>) \\ call (DOES>) from new creation word\n\t\t>r \\ move addrz to return stack so ; doesn't see stack garbage\n [compile] ; \\ terminate part of code before does>\n\t\tr>\n :noname ( addrz xt )\n compile rdrop \\ drop a stack frame (call becomes goto)\n swap ! \\ save execution token in literal\n; immediate\n\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 )\n swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 )\n dup cell+ @ swap @ ;\n\n: 2* ( n -- n*2 )\n 2 *\n;\n: 2\/ ( n -- n\/2 )\n 2 \/\n;\n\n\n\\ define some useful constants ------------------------------\n1 0= constant FALSE\n0 0= constant TRUE\n32 constant BL\n\n\\ Stack data structure ----------------------------------------\n\\ This is a general purpose stack utility used to implement necessary\n\\ stacks for the compiler or the user. Not real fast.\n\\ These stacks grow up which is different then normal.\n\\ cell 0 - stack pointer, offset from pfa of word\n\\ cell 1 - limit for range checking\n\\ cell 2 - first data location\n\n: :STACK ( #cells -- )\n CREATE 2 cells , ( offset of first data location )\n dup , ( limit for range checking, not currently used )\n cells cell+ allot ( allot an extra cell for safety )\n;\n\n: >STACK ( n stack -- , push onto stack, postincrement )\n dup @ 2dup cell+ swap ! ( -- n stack offset )\n + !\n;\n\n: STACK> ( stack -- n , pop , predecrement )\n dup @ cell- 2dup swap !\n + @\n;\n\n: STACK@ ( stack -- n , copy )\n dup @ cell- + @\n;\n\n: STACK.PICK ( index stack -- n , grab Nth from top of stack )\n dup @ cell- +\n swap cells - \\ offset for index\n @\n;\n: STACKP ( stack -- ptr , to next empty location on stack )\n\tdup @ +\n;\n\n: 0STACKP ( stack -- , clear stack)\n 8 swap !\n;\n\n32 :stack ustack\nustack 0stackp\n\n\\ Define JForth like words.\n: >US ustack >stack ;\n: US> ustack stack> ;\n: US@ ustack stack@ ;\n: 0USP ustack 0stackp ;\n\n\n\n\\ DO LOOP ------------------------------------------------\n\n3 constant do_flag\n4 constant leave_flag\n5 constant ?do_flag\n\n: DO ( -- , loop-back do_flag jump-from ?do_flag )\n ?comp\n compile (do)\n here >us do_flag >us ( for backward branch )\n; immediate\n\n: ?DO ( -- , loop-back do_flag jump-from ?do_flag , on user stack )\n ?comp\n ( leave address to set for forward branch )\n compile (?do)\n here 0 ,\n here >us do_flag >us ( for backward branch )\n >us ( for forward branch ) ?do_flag >us\n; immediate\n\n: LEAVE ( -- addr leave_flag )\n compile (leave)\n here 0 , >us\n leave_flag >us\n; immediate\n\n: LOOP-FORWARD ( -us- jump-from ?do_flag -- )\n BEGIN\n us@ leave_flag =\n us@ ?do_flag =\n OR\n WHILE\n us> leave_flag =\n IF\n us> here over - cell+ swap !\n ELSE\n us> dup\n here swap -\n cell+ swap !\n THEN\n REPEAT\n;\n\n: LOOP-BACK ( loop-addr do_flag -us- )\n us> do_flag ?pairs\n us> here - here\n !\n cell allot\n;\n\n: LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (loop)\n loop-forward loop-back\n; immediate\n\n\\ : DOTEST 5 0 do 333 . loop 888 . ;\n\\ : ?DOTEST0 0 0 ?do 333 . loop 888 . ;\n\\ : ?DOTEST1 5 0 ?do 333 . loop 888 . ;\n\n: +LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (+loop)\n loop-forward loop-back\n; immediate\n\n: UNLOOP ( loop-sys -r- )\n r> \\ save return pointer\n rdrop rdrop\n >r\n;\n\n\n: RECURSE ( ? -- ? , call the word currently being defined )\n latest compile,\n; immediate\n\n: SPACE bl emit ;\n: 0SP depth 0 ?do drop loop ;\n\n\\ : >NEWLINE ( -- , CR if needed )\n\\ out @ 0>\n\\ IF cr\n\\ THEN\n\\ ;\n\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 ) swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 ) dup cell+ @ swap @ ;\n\n: DABS ( d -- |d| )\n dup 0<\n IF dnegate\n THEN\n;\n\n: S>D ( s -- d , extend signed single precision to double )\n dup 0<\n IF -1\n ELSE 0\n THEN\n;\n\n: D>S ( d -- s ) drop ;\n\n: PARSE-WORD ( \"name\" -- c-addr u ) bl parse ;\n: \/STRING ( addr len n -- addr' len' ) over min rot over + -rot - ;\n: PLACE ( addr len to -- , move string ) 3dup 1+ swap cmove c! drop ;\n\n: ASCII ( -- char, state smart )\n bl parse drop c@\n state @ 1 =\n IF [compile] literal\n ELSE\n THEN\n; immediate\n\n: CHAR ( -- char , interpret mode ) bl parse drop c@ ;\n: [CHAR] ( -- char , for compile mode )\n char [compile] literal\n; immediate\n\n: $TYPE ( $string -- ) count type ;\n: 'word ( -- addr ) here ;\n\n: EVEN ( addr -- addr' ) dup 1 and + ;\n\n: (C\") ( -- $addr ) r> dup count + aligned >r ;\n: (S\") ( -- c-addr cnt ) r> count 2dup + aligned >r ;\n: (.\") ( -- , type following string ) r> count 2dup + aligned >r type ;\n: \", ( addr len -- , place string into dict ) tuck 'word place 1+ allot align ;\n: ,\" ( -- ) [char] \" parse \", ;\n\n: .( ( --, type string delimited by parens )\n [char] ) parse type\n; immediate\n\n: .\" ( -- , type string )\n state @ 1 =\n IF compile (.\") ,\"\n ELSE [char] \" parse type\n THEN\n; immediate\n\n: .' ( -- , type string delimited by single quote )\n state @\n IF compile (.\") [char] ' parse \",\n ELSE [char] ' parse type\n THEN\n; immediate\n\n: C\" ( -- addr , return string address, ANSI )\n state @\n IF compile (c\") ,\"\n ELSE [char] \" parse pad place pad\n THEN\n; immediate\n\n: S\" ( -- , -- addr , return string address, ANSI )\n state @\n IF compile (s\") ,\"\n ELSE [char] \" parse pad place pad count\n THEN\n; immediate\n\n: \" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n: P\" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n\n: \"\" ( -- addr )\n state @\n IF\n compile (C\")\n bl parse-word \",\n ELSE\n bl parse-word pad place pad\n THEN\n; immediate\n\n: SLITERAL ( addr cnt -- , compile string )\n\tcompile (S\")\n\t\",\n; IMMEDIATE\n\n: $APPEND ( addr count $1 -- , append text to $1 )\n over >r\n dup >r\n count + ( -- a2 c2 end1 )\n swap cmove\n r> dup c@ ( a1 c1 )\n r> + ( -- a1 totalcount )\n swap c!\n;\n\n\\ ANSI word to replace [COMPILE] and COMPILE ----------------\n: POSTPONE ( -- )\n\tbl word find\n\tdup\n 0= -13 ?ERROR\n 0>\n IF compile, \\ immediate\n ELSE (compile) \\ normal\n THEN\n\n; immediate\n\n\\ -----------------------------------------------------------------\n\\ Auto Initialization\n: AUTO.INIT ( -- )\n\\ Kernel finds AUTO.INIT and executes it after loading dictionary.\n\\\t.\" Begin AUTO.INIT ------\" cr\n;\n: AUTO.TERM ( -- )\n\\ Kernel finds AUTO.TERM and executes it on bye.\n\\\t.\" End AUTO.TERM ------\" cr\n;\n\n: INCLUDE? ( -- , load file if word not defined )\n bl word find\n IF drop bl word drop ( eat word from source )\n ELSE drop include\n THEN\n; immediate\n\n: CLEARSTACK ( i*x -- )\n BEGIN depth\n WHILE drop\n REPEAT ;\n\nvariable pictured_output \\ hidden?\nvariable pictured_output_len \\ hidden?\n\n: <# ( -- ) pad pictured_output ! 0 pictured_output_len ! ;\n: #> ( -- addr n ) drop pictured_output @ pictured_output_len @ ;\n\n: HOLD ( c -- )\n pictured_output @ dup dup 1+ pictured_output_len @ cmove c!\n 1 pictured_output_len +!\n;\n\n\\ ------------------------ INPUT -------------------------------\n\n: SIGN ( n -- ) < 0 IF 45 hold THEN\n;\n\n: DIGIT ( n -- ascii )\n dup 10 < IF 48 ELSE 87 THEN + ;\n\n: # ( n -- n )\n base @ \/mod swap digit hold ;\n\n: #S ( n -- )\n BEGIN base @ \/mod dup\n WHILE swap digit hold\n REPEAT\n digit hold ;\n\n\n: LWORD ( char -- addr )\n parse-word here place here \\ 00002 , use PARSE-WORD\n;\n\n: (WARNING\") ( flag $message -- )\n swap\n IF count type\n ELSE drop\n THEN\n;\n\n: WARNING\" ( flag -- , print warning if true. )\n\t[compile] \" ( compile message )\n\tstate @\n\tIF compile (warning\")\n\tELSE (warning\")\n\tTHEN\n; IMMEDIATE\n\n: ABORT\" ( flag -- , print warning if true. )\n\t[compile] \" ( compile message )\n\tstate @\n\tIF compile (abort\")\n\tELSE (abort\")\n\tTHEN\n; IMMEDIATE\n\n: DEFER ( \"name\" -- )\n CREATE ['] ABORT ,\n DOES> ( ... -- ... ) @ EXECUTE ;\n\n: DEFER! ( xt2 xt1 -- )\n >BODY 4 CELL* + ! ;\n\n: DEFER@ ( xt1 -- xt2 )\n >BODY 4 CELL* + @ ;\n\n\\ : IS ( xt \"name\" -- , Skip leading spaces and parse name delimited by a space. Set name to execute xt. )\n\\ STATE @ IF\n\\ POSTPONE ['] POSTPONE DEFER!\n\\ ELSE\n\\ ' DEFER!\n\\ THEN ; IMMEDIATE\n\n\n\\ : $ ( -- N , convert next number as hex )\n\\ base @ hex\n\\ 32 lword number? num_type_single = not\n\\ abort\" Not a single number!\"\n\\ swap base !\n\\ state @\n\\ IF [compile] literal\n\\ THEN\n\\ ; immediate","old_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\\n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n\n: COUNT dup 1+ swap c@ ;\n\n\\ Miscellaneous support words\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: <= ( a b -- f , true if A <= b ) > 0= ;\n: >= ( a b -- f , true if A >= b ) < 0= ;\n: NOT ( n -- !n , logical negation ) 0= ;\n: DNEGATE ( d -- -d , negate by doing 0-d )\n 0 swap -\n;\n: CELL+ ( n -- n+cell ) cell + ;\n: CELL- ( n -- n-cell ) cell - ;\n: CELL* ( n -- n*cell ) cells ;\n\n: CHAR+ ( n -- n+size_of_char ) 1+ ;\n: CHARS ( n -- n*size_of_char, don't do anything ) ; immediate\n\n\\ useful stack manipulation words\n: -ROT ( a b c -- c a b ) rot rot ;\n: 3DUP ( a b c -- a b c a b c ) 2 pick 2 pick 2 pick ;\n\n\\ ------------------------------------------------------------------\n: ID. ( nfa -- ) count 31 and type ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: PAD ( -- addr ) here 128 + ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n\n: BETWEEN ( n lo hi -- flag , true if between lo & hi )\n >r over r> > >r\n < r> or 0=\n;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: ? ( -- ) @ . ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ ' (lit) , cell 1- , ] +\n [ ' (lit) , cell 1- invert , ] and ;\n\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n: ALLOT ( nbytes -- , allot space in dictionary ) dp +! align ;\n\n: C, ( c -- ) here c! 1 dp +! ;\n\\ : W, ( w -- ) dp @ even-up dup dp ! w! 2 dp +! ;\n\\ : , ( n -- , lay into dictionary ) align here ! cell allot ;\n\n: SEE ( -- )\n ' dup\n >body swap >size\n disassemble ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token )\n [compile] literal ( compile a call to literal )\n ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick )\n ?comp ' [compile] literal\n; immediate\n\n: (DOES>) ( xt -- , modify previous definition to execute code at xt )\n latest >body \\ get address of code for new word\n 3 cell* + \\ offset to EXIT cell in create word\n ! \\ store execution token of DOES> code in new word\n;\n\n: DOES> ( -- , define execution code for CREATE word )\n 0 [compile] literal \\ dummy literal to hold xt\n here cell- \\ address of zero in literal\n compile (does>) \\ call (DOES>) from new creation word\n\t\t>r \\ move addrz to return stack so ; doesn't see stack garbage\n [compile] ; \\ terminate part of code before does>\n\t\tr>\n :noname ( addrz xt )\n compile rdrop \\ drop a stack frame (call becomes goto)\n swap ! \\ save execution token in literal\n; immediate\n\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 )\n swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 )\n dup cell+ @ swap @ ;\n\n: 2* ( n -- n*2 )\n 2 *\n;\n: 2\/ ( n -- n\/2 )\n 2 \/\n;\n\n\n\\ define some useful constants ------------------------------\n1 0= constant FALSE\n0 0= constant TRUE\n32 constant BL\n\n\\ Stack data structure ----------------------------------------\n\\ This is a general purpose stack utility used to implement necessary\n\\ stacks for the compiler or the user. Not real fast.\n\\ These stacks grow up which is different then normal.\n\\ cell 0 - stack pointer, offset from pfa of word\n\\ cell 1 - limit for range checking\n\\ cell 2 - first data location\n\n: :STACK ( #cells -- )\n CREATE 2 cells , ( offset of first data location )\n dup , ( limit for range checking, not currently used )\n cells cell+ allot ( allot an extra cell for safety )\n;\n\n: >STACK ( n stack -- , push onto stack, postincrement )\n dup @ 2dup cell+ swap ! ( -- n stack offset )\n + !\n;\n\n: STACK> ( stack -- n , pop , predecrement )\n dup @ cell- 2dup swap !\n + @\n;\n\n: STACK@ ( stack -- n , copy )\n dup @ cell- + @\n;\n\n: STACK.PICK ( index stack -- n , grab Nth from top of stack )\n dup @ cell- +\n swap cells - \\ offset for index\n @\n;\n: STACKP ( stack -- ptr , to next empty location on stack )\n\tdup @ +\n;\n\n: 0STACKP ( stack -- , clear stack)\n 8 swap !\n;\n\n32 :stack ustack\nustack 0stackp\n\n\\ Define JForth like words.\n: >US ustack >stack ;\n: US> ustack stack> ;\n: US@ ustack stack@ ;\n: 0USP ustack 0stackp ;\n\n\n\n\\ DO LOOP ------------------------------------------------\n\n3 constant do_flag\n4 constant leave_flag\n5 constant ?do_flag\n\n: DO ( -- , loop-back do_flag jump-from ?do_flag )\n ?comp\n compile (do)\n here >us do_flag >us ( for backward branch )\n; immediate\n\n: ?DO ( -- , loop-back do_flag jump-from ?do_flag , on user stack )\n ?comp\n ( leave address to set for forward branch )\n compile (?do)\n here 0 ,\n here >us do_flag >us ( for backward branch )\n >us ( for forward branch ) ?do_flag >us\n; immediate\n\n: LEAVE ( -- addr leave_flag )\n compile (leave)\n here 0 , >us\n leave_flag >us\n; immediate\n\n: LOOP-FORWARD ( -us- jump-from ?do_flag -- )\n BEGIN\n us@ leave_flag =\n us@ ?do_flag =\n OR\n WHILE\n us> leave_flag =\n IF\n us> here over - cell+ swap !\n ELSE\n us> dup\n here swap -\n cell+ swap !\n THEN\n REPEAT\n;\n\n: LOOP-BACK ( loop-addr do_flag -us- )\n us> do_flag ?pairs\n us> here - here\n !\n cell allot\n;\n\n: LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (loop)\n loop-forward loop-back\n; immediate\n\n\\ : DOTEST 5 0 do 333 . loop 888 . ;\n\\ : ?DOTEST0 0 0 ?do 333 . loop 888 . ;\n\\ : ?DOTEST1 5 0 ?do 333 . loop 888 . ;\n\n: +LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (+loop)\n loop-forward loop-back\n; immediate\n\n: UNLOOP ( loop-sys -r- )\n r> \\ save return pointer\n rdrop rdrop\n >r\n;\n\n\n: RECURSE ( ? -- ? , call the word currently being defined )\n latest compile,\n; immediate\n\n: SPACE bl emit ;\n: 0SP depth 0 ?do drop loop ;\n\n\\ : >NEWLINE ( -- , CR if needed )\n\\ out @ 0>\n\\ IF cr\n\\ THEN\n\\ ;\n\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 ) swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 ) dup cell+ @ swap @ ;\n\n: DABS ( d -- |d| )\n dup 0<\n IF dnegate\n THEN\n;\n\n: S>D ( s -- d , extend signed single precision to double )\n dup 0<\n IF -1\n ELSE 0\n THEN\n;\n\n: D>S ( d -- s ) drop ;\n\n: PARSE-WORD ( \"name\" -- c-addr u ) bl parse ;\n: \/STRING ( addr len n -- addr' len' ) over min rot over + -rot - ;\n: PLACE ( addr len to -- , move string ) 3dup 1+ swap cmove c! drop ;\n\n: ASCII ( -- char, state smart )\n bl parse drop c@\n state @ 1 =\n IF [compile] literal\n ELSE\n THEN\n; immediate\n\n: CHAR ( -- char , interpret mode ) bl parse drop c@ ;\n: [CHAR] ( -- char , for compile mode )\n char [compile] literal\n; immediate\n\n: $TYPE ( $string -- ) count type ;\n: 'word ( -- addr ) here ;\n\n: EVEN ( addr -- addr' ) dup 1 and + ;\n\n: (C\") ( -- $addr ) r> dup count + aligned >r ;\n: (S\") ( -- c-addr cnt ) r> count 2dup + aligned >r ;\n: (.\") ( -- , type following string ) r> count 2dup + aligned >r type ;\n: \", ( addr len -- , place string into dict ) tuck 'word place 1+ allot align ;\n: ,\" ( -- ) [char] \" parse \", ;\n\n: .( ( --, type string delimited by parens )\n [char] ) parse type\n; immediate\n\n: .\" ( -- , type string )\n state @ 1 =\n IF compile (.\") ,\"\n ELSE [char] \" parse type\n THEN\n; immediate\n\n: .' ( -- , type string delimited by single quote )\n state @\n IF compile (.\") [char] ' parse \",\n ELSE [char] ' parse type\n THEN\n; immediate\n\n: C\" ( -- addr , return string address, ANSI )\n state @\n IF compile (c\") ,\"\n ELSE [char] \" parse pad place pad\n THEN\n; immediate\n\n: S\" ( -- , -- addr , return string address, ANSI )\n state @\n IF compile (s\") ,\"\n ELSE [char] \" parse pad place pad count\n THEN\n; immediate\n\n: \" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n: P\" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n\n: \"\" ( -- addr )\n state @\n IF\n compile (C\")\n bl parse-word \",\n ELSE\n bl parse-word pad place pad\n THEN\n; immediate\n\n: SLITERAL ( addr cnt -- , compile string )\n\tcompile (S\")\n\t\",\n; IMMEDIATE\n\n: $APPEND ( addr count $1 -- , append text to $1 )\n over >r\n dup >r\n count + ( -- a2 c2 end1 )\n swap cmove\n r> dup c@ ( a1 c1 )\n r> + ( -- a1 totalcount )\n swap c!\n;\n\n\\ ANSI word to replace [COMPILE] and COMPILE ----------------\n: POSTPONE ( -- )\n\tbl word find\n\tdup\n 0= -13 ?ERROR\n 0>\n IF compile, \\ immediate\n ELSE (compile) \\ normal\n THEN\n\n; immediate\n\n\\ -----------------------------------------------------------------\n\\ Auto Initialization\n: AUTO.INIT ( -- )\n\\ Kernel finds AUTO.INIT and executes it after loading dictionary.\n\\\t.\" Begin AUTO.INIT ------\" cr\n;\n: AUTO.TERM ( -- )\n\\ Kernel finds AUTO.TERM and executes it on bye.\n\\\t.\" End AUTO.TERM ------\" cr\n;\n\n: INCLUDE? ( -- , load file if word not defined )\n bl word find\n IF drop bl word drop ( eat word from source )\n ELSE drop include\n THEN\n; immediate\n\n: CLEARSTACK ( i*x -- )\n BEGIN depth\n WHILE drop\n REPEAT ;\n\nvariable pictured_output \\ hidden?\nvariable pictured_output_len \\ hidden?\n\n: <# ( -- ) pad pictured_output ! 0 pictured_output_len ! ;\n: #> ( -- addr n ) drop pictured_output @ pictured_output_len @ ;\n\n: HOLD ( c -- )\n pictured_output @ dup dup 1+ pictured_output_len @ cmove c!\n 1 pictured_output_len +!\n;\n\n\\ ------------------------ INPUT -------------------------------\n\n: SIGN ( n -- ) < 0 IF 45 hold THEN\n;\n\n: DIGIT ( n -- ascii )\n dup 10 < IF 48 ELSE 87 THEN + ;\n\n: # ( n -- n )\n base @ \/mod swap digit hold ;\n\n: #S ( n -- )\n BEGIN base @ \/mod dup\n WHILE swap digit hold\n REPEAT\n digit hold ;\n\n\n: (WARNING\") ( flag $message -- )\n swap\n IF count type\n ELSE drop\n THEN\n;\n\n: WARNING\" ( flag -- , print warning if true. )\n\t[compile] \" ( compile message )\n\tstate @\n\tIF compile (warning\")\n\tELSE (warning\")\n\tTHEN\n; IMMEDIATE\n\n: ABORT\" ( flag -- , print warning if true. )\n\t[compile] \" ( compile message )\n\tstate @\n\tIF compile (abort\")\n\tELSE (abort\")\n\tTHEN\n; IMMEDIATE\n\n: DEFER ( \"name\" -- )\n CREATE ['] ABORT ,\n DOES> ( ... -- ... ) @ EXECUTE ;\n\n: DEFER! ( xt2 xt1 -- )\n >BODY 4 CELL* + ! ;\n\n: DEFER@ ( xt1 -- xt2 )\n >BODY 4 CELL* + @ ;\n\n\\ : IS ( xt \"name\" -- , Skip leading spaces and parse name delimited by a space. Set name to execute xt. )\n\\ STATE @ IF\n\\ POSTPONE ['] POSTPONE DEFER!\n\\ ELSE\n\\ ' DEFER!\n\\ THEN ; IMMEDIATE\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"b92a2844477fec8fc118723c369ce03400dcfa9e","subject":"Capitalize sample assembly","message":"Capitalize sample assembly\n","repos":"AshleyF\/Forthkit,AshleyF\/Forthkit,AshleyF\/Forthkit","old_file":"hardware\/register\/capitalize.4th","new_file":"hardware\/register\/capitalize.4th","new_contents":"( simple assembler\/VM test - capitalize [-32] console input )\n\n0 const u\n1 const c\n\nlabel &start\n\n 32 u ldc,\n c in,\n c u c sub,\n c out,\n&start jump,\n\nassemble\n\n","old_contents":"( simple assembler\/VM test - capitalize [-32] console input )\n\n0 const u\n1 const c\n\n 32 u ldc,\n c in,\nc u c sub,\n c out,\n 3 jump,\n\ndump\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"62832fe78e5d31f6b2d0eced9c99f99703e69fc3","subject":"Add do ... loop words","message":"Add do ... loop words\n\nAdd do ... loop words and i, j and k words to access loop variables.\r\nTodo: rewrite to not include _loop and _+loop","repos":"tehologist\/forthkit","old_file":"eforth.forth","new_file":"eforth.forth","new_contents":": + um+ drop ; \n: cells dup + ; \n: cell+ 2 + ; \n: cell- -2 + ; \n: cell 2 ; \n: boot 0 cells ; \n: forth 4 cells ; \n: dpl 5 cells ; \n: sp0 6 cells ; \n: rp0 7 cells ; \n: '?key 8 cells ; \n: 'emit 9 cells ; \n: 'expect 10 cells ; \n: 'tap 11 cells ; \n: 'echo 12 cells ; \n: 'prompt 13 cells ; \n: base 14 cells ; \n: tmp 15 cells ; \n: span 16 cells ; \n: >in 17 cells ; \n: #tibb 18 cells ; \n: tibb 19 cells ; \n: csp 20 cells ; \n: 'eval 21 cells ; \n: 'number 22 cells ; \n: hld 23 cells ; \n: handler 24 cells ; \n: context 25 cells ; \n: current 27 cells ; \n: cp 29 cells ; \n: np 30 cells ; \n: last 31 cells ; \n: state 32 cells ; \n: spp 33 cells ; \n: rpp 34 cells ; \n: true -1 ; \n: false 0 ; \n: bl 32 ; \n: bs 8 ; \n: =immed 3 ; \n: =wordlist 2 ; \n: immediate =immed last @ cell- ! ; \n: here cp @ ; \n: allot cp @ + cp ! ; \n: , here cell allot ! ; \n: c, here 1 allot c! ; \n: +! swap over @ + swap ! ; \n: compile r> dup @ , cell+ >r ; \n: state? state @ ; \n: literal compile lit , ; immediate \n: [ false state ! ; immediate \n: ] true state ! ; immediate \n: if compile 0branch here 0 , ; immediate \n: then here swap ! ; immediate \n: for compile >r here ; immediate \n: next compile next , ; immediate \n: begin here ; immediate \n: again compile branch , ; immediate \n: until compile 0branch , ; immediate \n: ahead compile branch here 0 , ; immediate \n: repeat compile branch , here swap ! ; immediate \n: aft drop compile branch here 0 , here swap ; immediate \n: else compile branch here 0 , swap here swap ! ; immediate \n: while compile 0branch here 0 , swap ; immediate \n: execute >r ; \n: @execute @ dup if execute then ; \n: r@ r> r> dup >r swap >r ; \n: #tib #tibb @ ; \n: tib tibb @ ; \n: \\ #tib @ >in ! ; immediate \n: rot >r swap r> swap ; \n: -rot swap >r swap r> ; \n: nip swap drop ; \n: tuck swap over ; \n: 2>r swap r> swap >r swap >r >r ; \n: 2r> r> r> swap r> swap >r swap ; \n: 2r@ r> r> r@ swap >r swap r@ swap >r ; \n: 2drop drop drop ; \n: 2dup over over ; \n: 2swap rot >r rot r> ; \n: 2over >r >r 2dup r> r> 2swap ; \n: 2rot 2>r 2swap 2r> 2swap ; \n: -2rot 2rot 2rot ; \n: 2nip 2swap 2drop ; \n: 2tuck 2swap 2over ; \n: not dup nand ; \n: and nand not ; \n: or not swap not nand ; \n: nor or not ; \n: xor 2dup and -rot nor nor ; \n: xnor xor not ; \n: negate not 1 + ; \n: - negate + ; \n: 1+ 1 + ; \n: 1- 1 - ; \n: 2+ 2 + ; \n: 2- 2 - ; \n: d+ >r swap >r um+ r> r> + + ; \n: dnegate not >r not 1 um+ r> + ; \n: d- dnegate d+ ; \n: 2! swap over ! cell+ ! ; \n: 2@ dup cell+ @ swap @ ; \n: ?dup dup if dup then ; \n: s>d dup 0< ; \n: abs dup 0< if negate then ; \n: dabs dup 0< if dnegate then ; \n: u< 2dup xor 0< if swap drop 0< exit then - 0< ; \n: u> swap u< ; \n: = xor if false exit then true ; \n: < 2dup xor 0< if drop 0< exit then - 0< ; \n: > swap < ; \n: 0> negate 0< ; \n: 0<> if true exit then false ; \n: 0= 0 = ; \n: <> = 0= ; \n: d0< swap drop 0< ; \n: d0> dnegate d0< ; \n: d0= or 0= ; \n: d= d- d0= ; \n: d< rot 2dup xor if swap 2swap 2drop < ; \n: du< rot 2dup xor if swap 2swap then then 2drop u< ; \n: dmin 2over 2over 2swap d< if 2swap then 2drop ; \n: dmax 2over 2over d< if 2swap then 2drop ; \n: m+ s>d d+ ; \n: m- s>d d- ; \n: min 2dup swap < if swap then drop ; \n: max 2dup < if swap then drop ; \n: umin 2dup swap u< if swap then drop ; \n: umax 2dup u< if swap then drop ; \n: within over - >r - r> u< ; \n: um\/mod \n 2dup u< \n if negate \n 15 for \n >r dup um+ \n >r >r dup um+ \n r> + dup r> r@ swap \n >r um+ \n r> or \n if >r drop 1+ r> \n else drop \n then r> \n next drop swap exit \n then drop 2drop -1 dup ; \n: m\/mod \n dup 0< dup >r \n if negate >r \n dnegate r> \n then >r dup 0< \n if r@ + \n then r> um\/mod \n r> \n if swap negate swap then ; \n: \/mod over 0< swap m\/mod ; \n: mod \/mod drop ; \n: \/ \/mod nip ; \n: um* \n 0 swap \n 15 for \n dup um+ >r >r \n dup um+ \n r> + \n r> \n if >r over um+ \n r> + \n then \n next \n rot drop ; \n: * um* drop ; \n: m* \n 2dup xor 0< >r \n abs swap abs um* \n r> if dnegate then ; \n: *\/mod >r m* r> m\/mod ; \n: *\/ *\/mod swap drop ; \n: 2* 2 * ; \n: 2\/ 2 \/ ; \n: mu\/mod >r 0 r@ um\/mod r> swap >r um\/mod r> ; \n: d2* 2dup d+ ; \n: du2\/ 2 mu\/mod rot drop ; \n: d2\/ dup >r 1 and du2\/ r> 2\/ or ; \n: aligned dup 0 2 um\/mod drop dup if 2 swap - then + ; \n: parse \n tmp ! over >r dup \n if \n 1- tmp @ bl = \n if \n for bl over c@ - 0< not \n while 1+ \n next r> drop 0 dup exit \n then r> \n then \n over swap \n for tmp @ over c@ - tmp @ bl = \n if 0< then \n while 1+ \n next dup >r \n else r> drop dup 1+ >r \n then over - r> r> - exit \n then over r> - ; \n: parse >r tib >in @ + #tib c@ >in @ - r> parse >in +! ; \n: char bl parse drop c@ ; \n: tx! 1 putc ; \n: emit 'emit @execute ; \n: type for aft dup c@ emit 1+ then next drop ; \n: ?rx 0 getc ; \n: ?key '?key @execute ; \n: key begin ?key until ; \n: count dup 1+ swap c@ ; \n: cmove \n for \n aft \n >r dup c@ r@ c! 1+ r> 1+ \n then \n next 2drop ; \n: fill \n swap \n for swap \n aft 2dup c! 1+ then \n next 2drop ; \n: -trailing \n for \n aft \n bl over r@ + c@ < \n if \n r> 1+ exit \n then \n then \n next 0 ; \n: pack$ \n dup >r \n 2dup c! 1+ 2dup + 0 swap ! swap cmove \n r> ; \n: word parse here pack$ ; \n: token bl parse 31 min np @ over - 1- pack$ ; \n: link> 3 cells - ; \n: code> 2 cells - ; \n: type> 1 cells - ; \n: data> cell+ ; \n: same? \n for aft \n over r@ cells + @ \n over r@ cells + @ \n - ?dup \n if r> drop exit then \n then \n next 0 ; \n: find \n @ begin dup while \n 2dup c@ swap c@ = if \n 2dup 1+ swap count aligned cell \/ >r swap r> \n same? 0= if \n 2drop swap drop dup code> @ swap -1 exit \n then 2drop then \n link> @ repeat ; \n: ' token context @ find if drop else swap drop 0 then ; \n: ! ! ; \n' tx! 'emit ! \n' ?rx '?key ! \n: ['] compile ' ; immediate \n: postpone ' , ; immediate \n: [char] char postpone literal ; immediate \n: ( [char] ) parse 2drop ; immediate \n: :noname here postpone ] ; \n: overt last @ current @ ! ; \n: $,n \n dup last ! cell- \n dup =wordlist \n swap ! \n cell- dup here \n swap ! \n cell- dup current @ @ \n swap ! \n cell- np ! ; \n: : token $,n postpone ] ; \n: ; compile exit postpone [ overt ; immediate \n: recurse last @ code> @ , ; immediate \n: dovar r> ; \n: create token $,n compile dovar overt ; \n: does last @ code> @ r> swap ! ; \n: does> compile does compile r> ; immediate \n: constant create , does> @ ; \n: variable create 0 , ; \n: 2literal swap postpone literal \n postpone literal ; immediate \n: 2constant create , , does> 2@ ; \n: 2variable create 2 cells allot ; \n: space bl emit ; \n: spaces 0 max for space next ; \n: pad here 80 + ; \n: decimal 10 base ! ; \n: hex 16 base ! ; \n: binary 2 base ! ; \n: octal 8 base ! ; \ndecimal \n: char- 1- ; \n: char+ 1+ ; \n: chars ; \n: >char 127 and dup 127 bl within if drop 95 then ; \n: digit 9 over < 7 and + [char] 0 + ; \n: <# pad hld ! ; \n: hold hld @ char- dup hld ! c! ; \n: # 0 base @ um\/mod >r base @ um\/mod swap digit hold r> ; \n: #s begin # 2dup or 0= until ; \n: sign 0< if [char] - hold then ; \n: #> 2drop hld @ pad over - ; \n: s.r over - spaces type ; \n: d.r >r dup >r dabs <# #s r> sign #> r> s.r ; \n: u.r 0 swap d.r ; \n: .r >r s>d r> d.r ; \n: d. 0 d.r space ; \n: u. 0 d. ; \n: . base @ 10 xor if u. exit then s>d d. ; \n: ? @ . ; \n: du.r >r <# #s #> r> s.r ; \n: du. du.r space ; \n: do$ r> r@ r> count + aligned >r swap >r ; \n: .\"| do$ count type ; \n: $,\" [char] \" word count + aligned cp ! ; \n: .\" compile .\"| $,\" ; immediate \n: .( [char] ) parse type ; immediate \n: $\"| do$ ; \n: $\" compile $\"| $,\" ; immediate \n: s\" [char] \" parse here pack$ ; \n: cr 10 emit ; \n: tap over c! 1+ ; \n: ktap \n 10 xor \n if \n bl tap exit \n then \n nip dup ; \n: accept \n over + over \n begin \n 2dup xor \n while \n key \n dup bl - 95 u< \n if tap else ktap then \n repeat drop over - ; \n: expect accept span ! drop ; \n: query tib 80 accept #tib c! drop 0 >in ! ; \n: digit? \n >r [char] 0 - \n 9 over < \n if 7 - dup 10 < or then \n dup r> u< ; \n: \/string dup >r - swap r> + swap ; \n: >number \n begin dup \n while >r dup >r c@ base @ digit? \n while swap base @ um* drop rot \n base @ um* d+ r> char+ r> 1 - \n repeat drop r> r> then ; \n: number? \n over c@ [char] - = dup >r if 1 \/string then \n >r >r 0 dup r> r> -1 dpl ! \n begin >number dup \n while over c@ [char] . xor \n if rot drop rot r> 2drop false exit \n then 1 - dpl ! char+ dpl @ \n repeat 2drop r> if dnegate then true ; \n' number? 'number ! \n: $interpret \n context @ find \n if drop execute exit then \n count 'number @execute if \n dpl @ 0< if drop then exit then .\" ?\" type ; \n: $compile \n context @ find \n if cell- @ =immed = \n if execute else , then exit \n then count 'number @execute \n if \n dpl @ 0< \n if drop postpone literal \n else postpone 2literal \n then exit \n then .\" ?\" type ; \n: eval state? if $compile else $interpret then ; \n' eval 'eval ! \n: eval \n begin token dup c@ while \n 'eval @execute \n repeat drop ; \n: ok cr .\" ok.\" space ; \n' ok 'prompt ! \n: quit \n begin 'prompt @execute query \n eval again ; \n: bye .\" good bye \" cr halt ; \n' quit boot ! \n: sp@ spp @ ; \n: depth sp@ sp0 @ - cell \/ ; \n: pick cells sp@ swap - 2 cells - @ ; \n: .s cr depth for aft r@ pick . then next space .\" \n @ space repeat drop cr ; \n \n: rpick r> rpp @ swap >r + 2- @ ; \n: do compile 2>r postpone begin ; immediate \n: _loop r> r> 1+ dup r@ 1- > swap >r swap >r ; \n: _+loop r> swap r> swap + dup r@ 1- > swap >r swap >r ; \n: leave r> 2r> 2drop >r ; \n: unloop r> r> drop r@ r> r> ; \n: loop compile _loop postpone until compile leave ; immediate \n: +loop compile _+loop postpone until compile leave ; immediate \n: i r> r> tuck >r >r ; \n: j 4 rpick ; \n: k 4 rpick ;\n\nvariable file \n: open f_open file ! ; \n: close file @ f_close ; \n: fput file @ putc ; \n: fget file @ getc ; \n: fputs count for aft dup c@ fput 1+ then next drop ; \n\n: savevm $\" eforth.img\" $\" wb\" open 0 \n 16384 for aft dup c@ fput 1+ then next close drop ; \n\nsavevm \n","old_contents":": + um+ drop ; \n: cells dup + ; \n: cell+ 2 + ; \n: cell- -2 + ; \n: cell 2 ; \n: boot 0 cells ; \n: forth 4 cells ; \n: dpl 5 cells ; \n: sp0 6 cells ; \n: rp0 7 cells ; \n: '?key 8 cells ; \n: 'emit 9 cells ; \n: 'expect 10 cells ; \n: 'tap 11 cells ; \n: 'echo 12 cells ; \n: 'prompt 13 cells ; \n: base 14 cells ; \n: tmp 15 cells ; \n: span 16 cells ; \n: >in 17 cells ; \n: #tibb 18 cells ; \n: tibb 19 cells ; \n: csp 20 cells ; \n: 'eval 21 cells ; \n: 'number 22 cells ; \n: hld 23 cells ; \n: handler 24 cells ; \n: context 25 cells ; \n: current 27 cells ; \n: cp 29 cells ; \n: np 30 cells ; \n: last 31 cells ; \n: state 32 cells ; \n: spp 33 cells ; \n: rpp 34 cells ; \n: true -1 ; \n: false 0 ; \n: bl 32 ; \n: bs 8 ; \n: =immed 3 ; \n: =wordlist 2 ; \n: immediate =immed last @ cell- ! ; \n: here cp @ ; \n: allot cp @ + cp ! ; \n: , here cell allot ! ; \n: c, here 1 allot c! ; \n: +! swap over @ + swap ! ; \n: compile r> dup @ , cell+ >r ; \n: state? state @ ; \n: literal compile lit , ; immediate \n: [ false state ! ; immediate \n: ] true state ! ; immediate \n: if compile 0branch here 0 , ; immediate \n: then here swap ! ; immediate \n: for compile >r here ; immediate \n: next compile next , ; immediate \n: begin here ; immediate \n: again compile branch , ; immediate \n: until compile 0branch , ; immediate \n: ahead compile branch here 0 , ; immediate \n: repeat compile branch , here swap ! ; immediate \n: aft drop compile branch here 0 , here swap ; immediate \n: else compile branch here 0 , swap here swap ! ; immediate \n: while compile 0branch here 0 , swap ; immediate \n: execute >r ; \n: @execute @ dup if execute then ; \n: r@ r> r> dup >r swap >r ; \n: #tib #tibb @ ; \n: tib tibb @ ; \n: \\ #tib @ >in ! ; immediate \n: rot >r swap r> swap ; \n: -rot swap >r swap r> ; \n: nip swap drop ; \n: tuck swap over ; \n: 2>r swap r> swap >r swap >r >r ; \n: 2r> r> r> swap r> swap >r swap ; \n: 2r@ r> r> r@ swap >r swap r@ swap >r ; \n: 2drop drop drop ; \n: 2dup over over ; \n: 2swap rot >r rot r> ; \n: 2over >r >r 2dup r> r> 2swap ; \n: 2rot 2>r 2swap 2r> 2swap ; \n: -2rot 2rot 2rot ; \n: 2nip 2swap 2drop ; \n: 2tuck 2swap 2over ; \n: not dup nand ; \n: and nand not ; \n: or not swap not nand ; \n: nor or not ; \n: xor 2dup and -rot nor nor ; \n: xnor xor not ; \n: negate not 1 + ; \n: - negate + ; \n: 1+ 1 + ; \n: 1- 1 - ; \n: 2+ 2 + ; \n: 2- 2 - ; \n: d+ >r swap >r um+ r> r> + + ; \n: dnegate not >r not 1 um+ r> + ; \n: d- dnegate d+ ; \n: 2! swap over ! cell+ ! ; \n: 2@ dup cell+ @ swap @ ; \n: ?dup dup if dup then ; \n: s>d dup 0< ; \n: abs dup 0< if negate then ; \n: dabs dup 0< if dnegate then ; \n: u< 2dup xor 0< if swap drop 0< exit then - 0< ; \n: u> swap u< ; \n: = xor if false exit then true ; \n: < 2dup xor 0< if drop 0< exit then - 0< ; \n: > swap < ; \n: 0> negate 0< ; \n: 0<> if true exit then false ; \n: 0= 0 = ; \n: <> = 0= ; \n: d0< swap drop 0< ; \n: d0> dnegate d0< ; \n: d0= or 0= ; \n: d= d- d0= ; \n: d< rot 2dup xor if swap 2swap 2drop < ; \n: du< rot 2dup xor if swap 2swap then then 2drop u< ; \n: dmin 2over 2over 2swap d< if 2swap then 2drop ; \n: dmax 2over 2over d< if 2swap then 2drop ; \n: m+ s>d d+ ; \n: m- s>d d- ; \n: min 2dup swap < if swap then drop ; \n: max 2dup < if swap then drop ; \n: umin 2dup swap u< if swap then drop ; \n: umax 2dup u< if swap then drop ; \n: within over - >r - r> u< ; \n: um\/mod \n 2dup u< \n if negate \n 15 for \n >r dup um+ \n >r >r dup um+ \n r> + dup r> r@ swap \n >r um+ \n r> or \n if >r drop 1+ r> \n else drop \n then r> \n next drop swap exit \n then drop 2drop -1 dup ; \n: m\/mod \n dup 0< dup >r \n if negate >r \n dnegate r> \n then >r dup 0< \n if r@ + \n then r> um\/mod \n r> \n if swap negate swap then ; \n: \/mod over 0< swap m\/mod ; \n: mod \/mod drop ; \n: \/ \/mod nip ; \n: um* \n 0 swap \n 15 for \n dup um+ >r >r \n dup um+ \n r> + \n r> \n if >r over um+ \n r> + \n then \n next \n rot drop ; \n: * um* drop ; \n: m* \n 2dup xor 0< >r \n abs swap abs um* \n r> if dnegate then ; \n: *\/mod >r m* r> m\/mod ; \n: *\/ *\/mod swap drop ; \n: 2* 2 * ; \n: 2\/ 2 \/ ; \n: mu\/mod >r 0 r@ um\/mod r> swap >r um\/mod r> ; \n: d2* 2dup d+ ; \n: du2\/ 2 mu\/mod rot drop ; \n: d2\/ dup >r 1 and du2\/ r> 2\/ or ; \n: aligned dup 0 2 um\/mod drop dup if 2 swap - then + ; \n: parse \n tmp ! over >r dup \n if \n 1- tmp @ bl = \n if \n for bl over c@ - 0< not \n while 1+ \n next r> drop 0 dup exit \n then r> \n then \n over swap \n for tmp @ over c@ - tmp @ bl = \n if 0< then \n while 1+ \n next dup >r \n else r> drop dup 1+ >r \n then over - r> r> - exit \n then over r> - ; \n: parse >r tib >in @ + #tib c@ >in @ - r> parse >in +! ; \n: char bl parse drop c@ ; \n: tx! 1 putc ; \n: emit 'emit @execute ; \n: type for aft dup c@ emit 1+ then next drop ; \n: ?rx 0 getc ; \n: ?key '?key @execute ; \n: key begin ?key until ; \n: count dup 1+ swap c@ ; \n: cmove \n for \n aft \n >r dup c@ r@ c! 1+ r> 1+ \n then \n next 2drop ; \n: fill \n swap \n for swap \n aft 2dup c! 1+ then \n next 2drop ; \n: -trailing \n for \n aft \n bl over r@ + c@ < \n if \n r> 1+ exit \n then \n then \n next 0 ; \n: pack$ \n dup >r \n 2dup c! 1+ 2dup + 0 swap ! swap cmove \n r> ; \n: word parse here pack$ ; \n: token bl parse 31 min np @ over - 1- pack$ ; \n: link> 3 cells - ; \n: code> 2 cells - ; \n: type> 1 cells - ; \n: data> cell+ ; \n: same? \n for aft \n over r@ cells + @ \n over r@ cells + @ \n - ?dup \n if r> drop exit then \n then \n next 0 ; \n: find \n @ begin dup while \n 2dup c@ swap c@ = if \n 2dup 1+ swap count aligned cell \/ >r swap r> \n same? 0= if \n 2drop swap drop dup code> @ swap -1 exit \n then 2drop then \n link> @ repeat ; \n: ' token context @ find if drop else swap drop 0 then ; \n: ! ! ; \n' tx! 'emit ! \n' ?rx '?key ! \n: ['] compile ' ; immediate \n: postpone ' , ; immediate \n: [char] char postpone literal ; immediate \n: ( [char] ) parse 2drop ; immediate \n: :noname here postpone ] ; \n: overt last @ current @ ! ; \n: $,n \n dup last ! cell- \n dup =wordlist \n swap ! \n cell- dup here \n swap ! \n cell- dup current @ @ \n swap ! \n cell- np ! ; \n: : token $,n postpone ] ; \n: ; compile exit postpone [ overt ; immediate \n: recurse last @ code> @ , ; immediate \n: dovar r> ; \n: create token $,n compile dovar overt ; \n: does last @ code> @ r> swap ! ; \n: does> compile does compile r> ; immediate \n: constant create , does> @ ; \n: variable create 0 , ; \n: 2literal swap postpone literal \n postpone literal ; immediate \n: 2constant create , , does> 2@ ; \n: 2variable create 2 cells allot ; \n: space bl emit ; \n: spaces 0 max for space next ; \n: pad here 80 + ; \n: decimal 10 base ! ; \n: hex 16 base ! ; \n: binary 2 base ! ; \n: octal 8 base ! ; \ndecimal \n: char- 1- ; \n: char+ 1+ ; \n: chars ; \n: >char 127 and dup 127 bl within if drop 95 then ; \n: digit 9 over < 7 and + [char] 0 + ; \n: <# pad hld ! ; \n: hold hld @ char- dup hld ! c! ; \n: # 0 base @ um\/mod >r base @ um\/mod swap digit hold r> ; \n: #s begin # 2dup or 0= until ; \n: sign 0< if [char] - hold then ; \n: #> 2drop hld @ pad over - ; \n: s.r over - spaces type ; \n: d.r >r dup >r dabs <# #s r> sign #> r> s.r ; \n: u.r 0 swap d.r ; \n: .r >r s>d r> d.r ; \n: d. 0 d.r space ; \n: u. 0 d. ; \n: . base @ 10 xor if u. exit then s>d d. ; \n: ? @ . ; \n: du.r >r <# #s #> r> s.r ; \n: du. du.r space ; \n: do$ r> r@ r> count + aligned >r swap >r ; \n: .\"| do$ count type ; \n: $,\" [char] \" word count + aligned cp ! ; \n: .\" compile .\"| $,\" ; immediate \n: .( [char] ) parse type ; immediate \n: $\"| do$ ; \n: $\" compile $\"| $,\" ; immediate \n: s\" [char] \" parse here pack$ ; \n: cr 10 emit ; \n: tap over c! 1+ ; \n: ktap \n 10 xor \n if \n bl tap exit \n then \n nip dup ; \n: accept \n over + over \n begin \n 2dup xor \n while \n key \n dup bl - 95 u< \n if tap else ktap then \n repeat drop over - ; \n: expect accept span ! drop ; \n: query tib 80 accept #tib c! drop 0 >in ! ; \n: digit? \n >r [char] 0 - \n 9 over < \n if 7 - dup 10 < or then \n dup r> u< ; \n: \/string dup >r - swap r> + swap ; \n: >number \n begin dup \n while >r dup >r c@ base @ digit? \n while swap base @ um* drop rot \n base @ um* d+ r> char+ r> 1 - \n repeat drop r> r> then ; \n: number? \n over c@ [char] - = dup >r if 1 \/string then \n >r >r 0 dup r> r> -1 dpl ! \n begin >number dup \n while over c@ [char] . xor \n if rot drop rot r> 2drop false exit \n then 1 - dpl ! char+ dpl @ \n repeat 2drop r> if dnegate then true ; \n' number? 'number ! \n: $interpret \n context @ find \n if drop execute exit then \n count 'number @execute if \n dpl @ 0< if drop then exit then .\" ?\" type ; \n: $compile \n context @ find \n if cell- @ =immed = \n if execute else , then exit \n then count 'number @execute \n if \n dpl @ 0< \n if drop postpone literal \n else postpone 2literal \n then exit \n then .\" ?\" type ; \n: eval state? if $compile else $interpret then ; \n' eval 'eval ! \n: eval \n begin token dup c@ while \n 'eval @execute \n repeat drop ; \n: ok cr .\" ok.\" space ; \n' ok 'prompt ! \n: quit \n begin 'prompt @execute query \n eval again ; \n: bye .\" good bye \" cr halt ; \n' quit boot ! \n: sp@ spp @ ; \n: depth sp@ sp0 @ - cell \/ ; \n: pick cells sp@ swap - 2 cells - @ ; \n: .s cr depth for aft r@ pick . then next space .\" \n @ space repeat drop cr ; \n\nvariable file \n: open f_open file ! ; \n: close file @ f_close ; \n: fput file @ putc ; \n: fget file @ getc ; \n: fputs count for aft dup c@ fput 1+ then next drop ; \n\n: savevm $\" eforth.img\" $\" wb\" open 0 \n 16384 for aft dup c@ fput 1+ then next close drop ; \n\nsavevm \n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"d6ac825b96f3cbcd57e180ad1063c83ff262ff9f","subject":"Define Wakerequest and TICKS","message":"Define Wakerequest and TICKS","repos":"rbsexton\/sockpuppet,rbsexton\/sockpuppet","old_file":"forth\/SysCalls-builtin.fth","new_file":"forth\/SysCalls-builtin.fth","new_contents":"\\ Wrappers for SAPI functions, ABI 3.x\n\n\\ *G Get the version of the binary ABI in use. \nSVC( #0 ) int SAPIVERSION( ); ( -- ver )\n\n\\ * Get a pointer to any shared data structures.\nSVC( #1 ) int SHARED_P( int x ); ( -- addr )\n\n\\ *G EMIT - Stream IO\n\\ Emit a character and return 0 when the output buffer is full.\n\\ Blocking\/Spinning. \n\\ -1 for output flush.\nSVC( #2 ) int __EMIT( int x, int stream); ( char channel -- room )\n\n\\ *G KEY? - Read a Key. \n\\ Blocking. Use with SERKEY? to detect blocking situations.\nSVC( #3 ) int __KEY(int stream); ( base -- key )\n\n\\ *G SERKEY? - Stream IO\n\\ Return the number of characters available in the input queue,\n\\ or empty\/full. Pass in a tcb to request a wakeup on new data. \nSVC( #4 ) int __KEY?(int stream, int tcb); ( base -- int )\n\n\\ *G EMIT_NB - Non-blocking emit \n\\ Returns -1 if the write failed. Pass in a TCB \nSVC( #7 ) int __EMIT_NB(int c, int stream, int tcb); ( base tcb -- key )\n\n\\ *G WAKEREQUEST \n\\ Request a task wake. The system call will stop the task. \nSVC( #8 ) void WAKEREQUEST(int tcb, int arg1, int arg2 ); ( base tcb -- key )\n\nSVC( #15 ) int TICKS( ); ( -- ms )\n","old_contents":"\\ Wrappers for SAPI functions, ABI 3.x\n\n\\ *G Get the version of the binary ABI in use. \nSVC( #0 ) int SAPIVERSION( ); ( -- ver )\n\n\\ * Get a pointer to any shared data structures.\nSVC( #1 ) int SHARED_P( ); ( -- addr )\n\n\\ *G EMIT - Stream IO\n\\ Emit a character and return 0 when the output buffer is full.\n\\ Blocking\/Spinning. \n\\ -1 for output flush.\nSVC( #2 ) int __EMIT( int x, int stream); ( char channel -- room )\n\n\\ *G KEY? - Read a Key. \n\\ Blocking. Use with SERKEY? to detect blocking situations.\nSVC( #3 ) int __KEY(int stream); ( base -- key )\n\n\\ *G SERKEY? - Stream IO\n\\ Return the number of characters available in the input queue,\n\\ or empty\/full. Pass in a tcb to request a wakeup on new data. \nSVC( #4 ) int __KEY?(int stream, int tcb); ( base -- int )\n\n\\ *G EMIT_NB - Non-blocking emit \n\\ Returns -1 if the write failed. Pass in a TCB \nSVC( #7 ) int __EMIT_NB(int c, int stream, int tcb); ( base tcb -- key )\n\nSVC( #15 ) int TICKS(); ( -- ms )\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"ccfaf68adbb4f44ab9d2d7a4a13b4e43752b1b37","subject":"MFC r258269: Refactor draw-beastie function.","message":"MFC r258269: Refactor draw-beastie function.\n\nDiscussed on:\t-hackers\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/beastie.4th","new_file":"sys\/boot\/forth\/beastie.4th","new_contents":"\\ Copyright (c) 2003 Scott Long \n\\ Copyright (c) 2003 Aleksander Fafula \n\\ Copyright (c) 2006-2013 Devin Teske \n\\ All rights reserved.\n\\ \n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\ \n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\ \n\\ $FreeBSD$\n\nmarker task-beastie.4th\n\nonly forth definitions also support-functions\n\nvariable logoX\nvariable logoY\n\n\\ Initialize logo placement to defaults\n46 logoX !\n4 logoY !\n\n: beastie-logo ( x y -- ) \\ color BSD mascot (19 rows x 34 columns)\n\n2dup at-xy .\" \u001b[31m, ,\" 1+\n2dup at-xy .\" \/( )`\" 1+\n2dup at-xy .\" \\ \\___ \/ |\" 1+\n2dup at-xy .\" \/- \u001b[37m_\u001b[31m `-\/ '\" 1+\n2dup at-xy .\" (\u001b[37m\/\\\/ \\\u001b[31m \\ \/\\\" 1+\n2dup at-xy .\" \u001b[37m\/ \/ |\u001b[31m ` \\\" 1+\n2dup at-xy .\" \u001b[34mO O \u001b[37m) \u001b[31m\/ |\" 1+\n2dup at-xy .\" \u001b[37m`-^--'\u001b[31m`< '\" 1+\n2dup at-xy .\" (_.) _ ) \/\" 1+\n2dup at-xy .\" `.___\/` \/\" 1+\n2dup at-xy .\" `-----' \/\" 1+\n2dup at-xy .\" \u001b[33m<----.\u001b[31m __ \/ __ \\\" 1+\n2dup at-xy .\" \u001b[33m<----|====\u001b[31mO)))\u001b[33m==\u001b[31m) \\) \/\u001b[33m====|\" 1+\n2dup at-xy .\" \u001b[33m<----'\u001b[31m `--' `.__,' \\\" 1+\n2dup at-xy .\" | |\" 1+\n2dup at-xy .\" \\ \/ \/\\\" 1+\n2dup at-xy .\" \u001b[36m______\u001b[31m( (_ \/ \\______\/\" 1+\n2dup at-xy .\" \u001b[36m,' ,-----' |\" 1+\n at-xy .\" `--{__________)\u001b[37m\"\n\n\t\\ Put the cursor back at the bottom\n\t0 25 at-xy\n;\n\n: beastiebw-logo ( x y -- ) \\ B\/W BSD mascot (19 rows x 34 columns)\n\n\t2dup at-xy .\" , ,\" 1+\n\t2dup at-xy .\" \/( )`\" 1+\n\t2dup at-xy .\" \\ \\___ \/ |\" 1+\n\t2dup at-xy .\" \/- _ `-\/ '\" 1+\n\t2dup at-xy .\" (\/\\\/ \\ \\ \/\\\" 1+\n\t2dup at-xy .\" \/ \/ | ` \\\" 1+\n\t2dup at-xy .\" O O ) \/ |\" 1+\n\t2dup at-xy .\" `-^--'`< '\" 1+\n\t2dup at-xy .\" (_.) _ ) \/\" 1+\n\t2dup at-xy .\" `.___\/` \/\" 1+\n\t2dup at-xy .\" `-----' \/\" 1+\n\t2dup at-xy .\" <----. __ \/ __ \\\" 1+\n\t2dup at-xy .\" <----|====O)))==) \\) \/====|\" 1+\n\t2dup at-xy .\" <----' `--' `.__,' \\\" 1+\n\t2dup at-xy .\" | |\" 1+\n\t2dup at-xy .\" \\ \/ \/\\\" 1+\n\t2dup at-xy .\" ______( (_ \/ \\______\/\" 1+\n\t2dup at-xy .\" ,' ,-----' |\" 1+\n\t at-xy .\" `--{__________)\"\n\n\t\\ Put the cursor back at the bottom\n\t0 25 at-xy\n;\n\n: fbsdbw-logo ( x y -- ) \\ \"FreeBSD\" logo in B\/W (13 rows x 21 columns)\n\n\t\\ We used to use the beastie himself as our default... until the\n\t\\ eventual complaint derided his reign of the advanced boot-menu.\n\t\\ \n\t\\ This is the replacement of beastie to satiate the haters of our\n\t\\ beloved helper-daemon (ready to track down and spear bugs with\n\t\\ his trident and sporty sneakers; see above).\n\t\\ \n\t\\ Since we merely just changed the default and not the default-\n\t\\ location, below is an adjustment to the passed-in coordinates,\n\t\\ forever influenced by the proper location of beastie himself\n\t\\ kept as the default loader_logo_x\/loader_logo_y values.\n\t\\ \n\t5 + swap 6 + swap\n\n\t2dup at-xy .\" ______\" 1+\n\t2dup at-xy .\" | ____| __ ___ ___ \" 1+\n\t2dup at-xy .\" | |__ | '__\/ _ \\\/ _ \\\" 1+\n\t2dup at-xy .\" | __|| | | __\/ __\/\" 1+\n\t2dup at-xy .\" | | | | | | |\" 1+\n\t2dup at-xy .\" |_| |_| \\___|\\___|\" 1+\n\t2dup at-xy .\" ____ _____ _____\" 1+\n\t2dup at-xy .\" | _ \\ \/ ____| __ \\\" 1+\n\t2dup at-xy .\" | |_) | (___ | | | |\" 1+\n\t2dup at-xy .\" | _ < \\___ \\| | | |\" 1+\n\t2dup at-xy .\" | |_) |____) | |__| |\" 1+\n\t2dup at-xy .\" | | | |\" 1+\n\t at-xy .\" |____\/|_____\/|_____\/\"\n\n\t\\ Put the cursor back at the bottom\n\t0 25 at-xy\n;\n\n: orb-logo ( x y -- ) \\ color Orb mascot (15 rows x 30 columns)\n\n\t3 + \\ beastie adjustment (see `fbsdbw-logo' comments above)\n\n\t2dup at-xy .\" \u001b[31m``` \u001b[31;1m`\u001b[31m\" 1+\n\t2dup at-xy .\" s` `.....---...\u001b[31;1m....--.``` -\/\u001b[31m\" 1+\n\t2dup at-xy .\" +o .--` \u001b[31;1m\/y:` +.\u001b[31m\" 1+\n\t2dup at-xy .\" yo`:. \u001b[31;1m:o `+-\u001b[31m\" 1+\n\t2dup at-xy .\" y\/ \u001b[31;1m-\/` -o\/\u001b[31m\" 1+\n\t2dup at-xy .\" .- \u001b[31;1m::\/sy+:.\u001b[31m\" 1+\n\t2dup at-xy .\" \/ \u001b[31;1m`-- \/\u001b[31m\" 1+\n\t2dup at-xy .\" `: \u001b[31;1m:`\u001b[31m\" 1+\n\t2dup at-xy .\" `: \u001b[31;1m:`\u001b[31m\" 1+\n\t2dup at-xy .\" \/ \u001b[31;1m\/\u001b[31m\" 1+\n\t2dup at-xy .\" .- \u001b[31;1m-.\u001b[31m\" 1+\n\t2dup at-xy .\" -- \u001b[31;1m-.\u001b[31m\" 1+\n\t2dup at-xy .\" `:` \u001b[31;1m`:`\" 1+\n\t2dup at-xy .\" \u001b[31;1m.-- `--.\" 1+\n\t at-xy .\" .---.....----.\u001b[37m\"\n\n \t\\ Put the cursor back at the bottom\n \t0 25 at-xy\n;\n\n: orbbw-logo ( x y -- ) \\ B\/W Orb mascot (15 rows x 32 columns)\n\n\t3 + \\ beastie adjustment (see `fbsdbw-logo' comments above)\n\n\t2dup at-xy .\" ``` `\" 1+\n\t2dup at-xy .\" s` `.....---.......--.``` -\/\" 1+\n\t2dup at-xy .\" +o .--` \/y:` +.\" 1+\n\t2dup at-xy .\" yo`:. :o `+-\" 1+\n\t2dup at-xy .\" y\/ -\/` -o\/\" 1+\n\t2dup at-xy .\" .- ::\/sy+:.\" 1+\n\t2dup at-xy .\" \/ `-- \/\" 1+\n\t2dup at-xy .\" `: :`\" 1+\n\t2dup at-xy .\" `: :`\" 1+\n\t2dup at-xy .\" \/ \/\" 1+\n\t2dup at-xy .\" .- -.\" 1+\n\t2dup at-xy .\" -- -.\" 1+\n\t2dup at-xy .\" `:` `:`\" 1+\n\t2dup at-xy .\" .-- `--.\" 1+\n\t at-xy .\" .---.....----.\"\n\n \t\\ Put the cursor back at the bottom\n \t0 25 at-xy\n;\n\n\\ This function draws any number of beastie logos at (loader_logo_x,\n\\ loader_logo_y) if defined, else (46,4) (to the right of the menu). To choose\n\\ your beastie, set the variable `loader_logo' to the respective logo name.\n\\ \n\\ Currently available:\n\\ \n\\ \tNAME DESCRIPTION\n\\ \tbeastie Color ``Helper Daemon'' mascot (19 rows x 34 columns)\n\\ \tbeastiebw B\/W ``Helper Daemon'' mascot (19 rows x 34 columns)\n\\ \tfbsdbw \"FreeBSD\" logo in B\/W (13 rows x 21 columns)\n\\ \torb Color ``Orb'' mascot (15 rows x 30 columns) (2nd default)\n\\ \torbbw B\/W ``Orb'' mascot (15 rows x 32 columns)\n\\ \ttribute Color ``Tribute'' (must fit 19 rows x 34 columns) (default)\n\\ \ttributebw B\/W ``Tribute'' (must fit 19 rows x 34 columns)\n\\ \n\\ NOTE: Setting `loader_logo' to an undefined value (such as \"none\") will\n\\ prevent beastie from being drawn.\n\\ \n: draw-beastie ( -- ) \\ at (loader_logo_x,loader_logo_y), else (46,4)\n\n\ts\" loader_logo_x\" getenv dup -1 <> if\n\t\t?number 1 = if logoX ! then\n\telse\n\t\tdrop\n\tthen\n\ts\" loader_logo_y\" getenv dup -1 <> if\n\t\t?number 1 = if logoY ! then\n\telse\n\t\tdrop\n\tthen\n\n\ts\" loader_logo\" getenv dup -1 <> if\n\t\tdup 5 + allocate if ENOMEM throw then\n\t\t0 2swap strcat s\" -logo\" strcat\n\t\tover -rot ( a-addr\/u -- a-addr a-addr\/u )\n\t\tsfind ( a-addr a-addr\/u -- a-addr xt bool )\n\t\trot ( a-addr xt bool -- xt bool a-addr )\n\t\tfree ( xt bool a-addr -- xt bool ior )\n\t\tif EFREE throw then\n\telse\n\t\t0 ( cruft -- cruft bool ) \\ load the default below\n\tthen\n\t0= if\n\t\tdrop ( cruft -- )\n\t\tloader_color? if\n\t\t\t['] orb-logo\n\t\telse\n\t\t\t['] orbbw-logo\n\t\tthen\n\tthen\n\tlogoX @ logoY @ rot execute\n;\n\n: clear-beastie ( -- ) \\ clears beastie from the screen\n\tlogoX @ logoY @\n\t2dup at-xy 34 spaces 1+\t\t2dup at-xy 34 spaces 1+\n\t2dup at-xy 34 spaces 1+\t\t2dup at-xy 34 spaces 1+\n\t2dup at-xy 34 spaces 1+\t\t2dup at-xy 34 spaces 1+\n\t2dup at-xy 34 spaces 1+\t\t2dup at-xy 34 spaces 1+\n\t2dup at-xy 34 spaces 1+\t\t2dup at-xy 34 spaces 1+\n\t2dup at-xy 34 spaces 1+\t\t2dup at-xy 34 spaces 1+\n\t2dup at-xy 34 spaces 1+\t\t2dup at-xy 34 spaces 1+\n\t2dup at-xy 34 spaces 1+\t\t2dup at-xy 34 spaces 1+\n\t2dup at-xy 34 spaces 1+\t\t2dup at-xy 34 spaces 1+\n\t2dup at-xy 34 spaces\t\t2drop\n\n\t\\ Put the cursor back at the bottom\n\t0 25 at-xy\n;\n\n: beastie-start ( -- ) \\ starts the menu\n\ts\" beastie_disable\" getenv\n\tdup -1 <> if\n\t\ts\" YES\" compare-insensitive 0= if\n\t\t\tany_conf_read? if\n\t\t\t\tload_kernel\n\t\t\t\tload_modules\n\t\t\tthen\n\t\t\texit \\ to autoboot (default)\n\t\tthen\n\telse\n\t\tdrop\n\tthen\n\n\ts\" loader_delay\" getenv\n\t-1 = if\n\t\ts\" include \/boot\/menu.rc\" evaluate\n\telse\n\t\tdrop\n\t\t.\" Loading Menu (Ctrl-C to Abort)\" cr\n\t\ts\" set delay_command='include \/boot\/menu.rc'\" evaluate\n\t\ts\" set delay_showdots\" evaluate\n\t\tdelay_execute\n\tthen\n;\n\nonly forth also\n","old_contents":"\\ Copyright (c) 2003 Scott Long \n\\ Copyright (c) 2003 Aleksander Fafula \n\\ Copyright (c) 2006-2013 Devin Teske \n\\ All rights reserved.\n\\ \n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\ \n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\ \n\\ $FreeBSD$\n\nmarker task-beastie.4th\n\nonly forth definitions also support-functions\n\nvariable logoX\nvariable logoY\n\n\\ Initialize logo placement to defaults\n46 logoX !\n4 logoY !\n\n: beastie-logo ( x y -- ) \\ color BSD mascot (19 rows x 34 columns)\n\n2dup at-xy .\" \u001b[31m, ,\" 1+\n2dup at-xy .\" \/( )`\" 1+\n2dup at-xy .\" \\ \\___ \/ |\" 1+\n2dup at-xy .\" \/- \u001b[37m_\u001b[31m `-\/ '\" 1+\n2dup at-xy .\" (\u001b[37m\/\\\/ \\\u001b[31m \\ \/\\\" 1+\n2dup at-xy .\" \u001b[37m\/ \/ |\u001b[31m ` \\\" 1+\n2dup at-xy .\" \u001b[34mO O \u001b[37m) \u001b[31m\/ |\" 1+\n2dup at-xy .\" \u001b[37m`-^--'\u001b[31m`< '\" 1+\n2dup at-xy .\" (_.) _ ) \/\" 1+\n2dup at-xy .\" `.___\/` \/\" 1+\n2dup at-xy .\" `-----' \/\" 1+\n2dup at-xy .\" \u001b[33m<----.\u001b[31m __ \/ __ \\\" 1+\n2dup at-xy .\" \u001b[33m<----|====\u001b[31mO)))\u001b[33m==\u001b[31m) \\) \/\u001b[33m====|\" 1+\n2dup at-xy .\" \u001b[33m<----'\u001b[31m `--' `.__,' \\\" 1+\n2dup at-xy .\" | |\" 1+\n2dup at-xy .\" \\ \/ \/\\\" 1+\n2dup at-xy .\" \u001b[36m______\u001b[31m( (_ \/ \\______\/\" 1+\n2dup at-xy .\" \u001b[36m,' ,-----' |\" 1+\n at-xy .\" `--{__________)\u001b[37m\"\n\n\t\\ Put the cursor back at the bottom\n\t0 25 at-xy\n;\n\n: beastiebw-logo ( x y -- ) \\ B\/W BSD mascot (19 rows x 34 columns)\n\n\t2dup at-xy .\" , ,\" 1+\n\t2dup at-xy .\" \/( )`\" 1+\n\t2dup at-xy .\" \\ \\___ \/ |\" 1+\n\t2dup at-xy .\" \/- _ `-\/ '\" 1+\n\t2dup at-xy .\" (\/\\\/ \\ \\ \/\\\" 1+\n\t2dup at-xy .\" \/ \/ | ` \\\" 1+\n\t2dup at-xy .\" O O ) \/ |\" 1+\n\t2dup at-xy .\" `-^--'`< '\" 1+\n\t2dup at-xy .\" (_.) _ ) \/\" 1+\n\t2dup at-xy .\" `.___\/` \/\" 1+\n\t2dup at-xy .\" `-----' \/\" 1+\n\t2dup at-xy .\" <----. __ \/ __ \\\" 1+\n\t2dup at-xy .\" <----|====O)))==) \\) \/====|\" 1+\n\t2dup at-xy .\" <----' `--' `.__,' \\\" 1+\n\t2dup at-xy .\" | |\" 1+\n\t2dup at-xy .\" \\ \/ \/\\\" 1+\n\t2dup at-xy .\" ______( (_ \/ \\______\/\" 1+\n\t2dup at-xy .\" ,' ,-----' |\" 1+\n\t at-xy .\" `--{__________)\"\n\n\t\\ Put the cursor back at the bottom\n\t0 25 at-xy\n;\n\n: fbsdbw-logo ( x y -- ) \\ \"FreeBSD\" logo in B\/W (13 rows x 21 columns)\n\n\t\\ We used to use the beastie himself as our default... until the\n\t\\ eventual complaint derided his reign of the advanced boot-menu.\n\t\\ \n\t\\ This is the replacement of beastie to satiate the haters of our\n\t\\ beloved helper-daemon (ready to track down and spear bugs with\n\t\\ his trident and sporty sneakers; see above).\n\t\\ \n\t\\ Since we merely just changed the default and not the default-\n\t\\ location, below is an adjustment to the passed-in coordinates,\n\t\\ forever influenced by the proper location of beastie himself\n\t\\ kept as the default loader_logo_x\/loader_logo_y values.\n\t\\ \n\t5 + swap 6 + swap\n\n\t2dup at-xy .\" ______\" 1+\n\t2dup at-xy .\" | ____| __ ___ ___ \" 1+\n\t2dup at-xy .\" | |__ | '__\/ _ \\\/ _ \\\" 1+\n\t2dup at-xy .\" | __|| | | __\/ __\/\" 1+\n\t2dup at-xy .\" | | | | | | |\" 1+\n\t2dup at-xy .\" |_| |_| \\___|\\___|\" 1+\n\t2dup at-xy .\" ____ _____ _____\" 1+\n\t2dup at-xy .\" | _ \\ \/ ____| __ \\\" 1+\n\t2dup at-xy .\" | |_) | (___ | | | |\" 1+\n\t2dup at-xy .\" | _ < \\___ \\| | | |\" 1+\n\t2dup at-xy .\" | |_) |____) | |__| |\" 1+\n\t2dup at-xy .\" | | | |\" 1+\n\t at-xy .\" |____\/|_____\/|_____\/\"\n\n\t\\ Put the cursor back at the bottom\n\t0 25 at-xy\n;\n\n: orb-logo ( x y -- ) \\ color Orb mascot (15 rows x 30 columns)\n\n\t3 + \\ beastie adjustment (see `fbsdbw-logo' comments above)\n\n\t2dup at-xy .\" \u001b[31m``` \u001b[31;1m`\u001b[31m\" 1+\n\t2dup at-xy .\" s` `.....---...\u001b[31;1m....--.``` -\/\u001b[31m\" 1+\n\t2dup at-xy .\" +o .--` \u001b[31;1m\/y:` +.\u001b[31m\" 1+\n\t2dup at-xy .\" yo`:. \u001b[31;1m:o `+-\u001b[31m\" 1+\n\t2dup at-xy .\" y\/ \u001b[31;1m-\/` -o\/\u001b[31m\" 1+\n\t2dup at-xy .\" .- \u001b[31;1m::\/sy+:.\u001b[31m\" 1+\n\t2dup at-xy .\" \/ \u001b[31;1m`-- \/\u001b[31m\" 1+\n\t2dup at-xy .\" `: \u001b[31;1m:`\u001b[31m\" 1+\n\t2dup at-xy .\" `: \u001b[31;1m:`\u001b[31m\" 1+\n\t2dup at-xy .\" \/ \u001b[31;1m\/\u001b[31m\" 1+\n\t2dup at-xy .\" .- \u001b[31;1m-.\u001b[31m\" 1+\n\t2dup at-xy .\" -- \u001b[31;1m-.\u001b[31m\" 1+\n\t2dup at-xy .\" `:` \u001b[31;1m`:`\" 1+\n\t2dup at-xy .\" \u001b[31;1m.-- `--.\" 1+\n\t at-xy .\" .---.....----.\u001b[37m\"\n\n \t\\ Put the cursor back at the bottom\n \t0 25 at-xy\n;\n\n: orbbw-logo ( x y -- ) \\ B\/W Orb mascot (15 rows x 32 columns)\n\n\t3 + \\ beastie adjustment (see `fbsdbw-logo' comments above)\n\n\t2dup at-xy .\" ``` `\" 1+\n\t2dup at-xy .\" s` `.....---.......--.``` -\/\" 1+\n\t2dup at-xy .\" +o .--` \/y:` +.\" 1+\n\t2dup at-xy .\" yo`:. :o `+-\" 1+\n\t2dup at-xy .\" y\/ -\/` -o\/\" 1+\n\t2dup at-xy .\" .- ::\/sy+:.\" 1+\n\t2dup at-xy .\" \/ `-- \/\" 1+\n\t2dup at-xy .\" `: :`\" 1+\n\t2dup at-xy .\" `: :`\" 1+\n\t2dup at-xy .\" \/ \/\" 1+\n\t2dup at-xy .\" .- -.\" 1+\n\t2dup at-xy .\" -- -.\" 1+\n\t2dup at-xy .\" `:` `:`\" 1+\n\t2dup at-xy .\" .-- `--.\" 1+\n\t at-xy .\" .---.....----.\"\n\n \t\\ Put the cursor back at the bottom\n \t0 25 at-xy\n;\n\n\\ This function draws any number of beastie logos at (loader_logo_x,\n\\ loader_logo_y) if defined, else (46,4) (to the right of the menu). To choose\n\\ your beastie, set the variable `loader_logo' to the respective logo name.\n\\ \n\\ Currently available:\n\\ \n\\ \tNAME DESCRIPTION\n\\ \tbeastie Color ``Helper Daemon'' mascot (19 rows x 34 columns)\n\\ \tbeastiebw B\/W ``Helper Daemon'' mascot (19 rows x 34 columns)\n\\ \tfbsdbw \"FreeBSD\" logo in B\/W (13 rows x 21 columns)\n\\ \torb Color ``Orb'' mascot (15 rows x 30 columns) (2nd default)\n\\ \torbbw B\/W ``Orb'' mascot (15 rows x 32 columns)\n\\ \ttribute Color ``Tribute'' (must fit 19 rows x 34 columns) (default)\n\\ \ttributebw B\/W ``Tribute'' (must fit 19 rows x 34 columns)\n\\ \n\\ NOTE: Setting `loader_logo' to an undefined value (such as \"none\") will\n\\ prevent beastie from being drawn.\n\\ \n: draw-beastie ( -- ) \\ at (loader_logo_x,loader_logo_y), else (46,4)\n\n\ts\" loader_logo_x\" getenv dup -1 <> if\n\t\t?number 1 = if logoX ! then\n\telse\n\t\tdrop\n\tthen\n\ts\" loader_logo_y\" getenv dup -1 <> if\n\t\t?number 1 = if logoY ! then\n\telse\n\t\tdrop\n\tthen\n\n\ts\" loader_logo\" getenv dup -1 = if\n\t\tlogoX @ logoY @\n\t\tloader_color? if\n\t\t\torb-logo\n\t\telse\n\t\t\torbbw-logo\n\t\tthen\n\t\tdrop exit\n\tthen\n\n\t2dup s\" beastie\" compare-insensitive 0= if\n\t\tlogoX @ logoY @ beastie-logo\n\t\t2drop exit\n\tthen\n\t2dup s\" beastiebw\" compare-insensitive 0= if\n\t\tlogoX @ logoY @ beastiebw-logo\n\t\t2drop exit\n\tthen\n\t2dup s\" fbsdbw\" compare-insensitive 0= if\n\t\tlogoX @ logoY @ fbsdbw-logo\n\t\t2drop exit\n\tthen\n\t2dup s\" orb\" compare-insensitive 0= if\n\t\tlogoX @ logoY @ orb-logo\n\t\t2drop exit\n\tthen\n\t2dup s\" orbbw\" compare-insensitive 0= if\n\t\tlogoX @ logoY @ orbbw-logo\n\t\t2drop exit\n\tthen\n\t2dup s\" tribute\" compare-insensitive 0= if\n\t\tlogoX @ logoY @\n\t\ts\" tribute-logo\" sfind if\n\t\t\texecute\n\t\telse\n\t\t\tdrop orb-logo\n\t\tthen\n\t\t2drop exit\n\tthen\n\t2dup s\" tributebw\" compare-insensitive 0= if\n\t\tlogoX @ logoY @\n\t\ts\" tributebw-logo\" sfind if\n\t\t\texecute\n\t\telse\n\t\t\tdrop orbbw-logo\n\t\tthen\n\t\t2drop exit\n\tthen\n\n\t2drop\n;\n\n: clear-beastie ( -- ) \\ clears beastie from the screen\n\tlogoX @ logoY @\n\t2dup at-xy 34 spaces 1+\t\t2dup at-xy 34 spaces 1+\n\t2dup at-xy 34 spaces 1+\t\t2dup at-xy 34 spaces 1+\n\t2dup at-xy 34 spaces 1+\t\t2dup at-xy 34 spaces 1+\n\t2dup at-xy 34 spaces 1+\t\t2dup at-xy 34 spaces 1+\n\t2dup at-xy 34 spaces 1+\t\t2dup at-xy 34 spaces 1+\n\t2dup at-xy 34 spaces 1+\t\t2dup at-xy 34 spaces 1+\n\t2dup at-xy 34 spaces 1+\t\t2dup at-xy 34 spaces 1+\n\t2dup at-xy 34 spaces 1+\t\t2dup at-xy 34 spaces 1+\n\t2dup at-xy 34 spaces 1+\t\t2dup at-xy 34 spaces 1+\n\t2dup at-xy 34 spaces\t\t2drop\n\n\t\\ Put the cursor back at the bottom\n\t0 25 at-xy\n;\n\n: beastie-start ( -- ) \\ starts the menu\n\ts\" beastie_disable\" getenv\n\tdup -1 <> if\n\t\ts\" YES\" compare-insensitive 0= if\n\t\t\tany_conf_read? if\n\t\t\t\tload_kernel\n\t\t\t\tload_modules\n\t\t\tthen\n\t\t\texit \\ to autoboot (default)\n\t\tthen\n\telse\n\t\tdrop\n\tthen\n\n\ts\" loader_delay\" getenv\n\t-1 = if\n\t\ts\" include \/boot\/menu.rc\" evaluate\n\telse\n\t\tdrop\n\t\t.\" Loading Menu (Ctrl-C to Abort)\" cr\n\t\ts\" set delay_command='include \/boot\/menu.rc'\" evaluate\n\t\ts\" set delay_showdots\" evaluate\n\t\tdelay_execute\n\tthen\n;\n\nonly forth also\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"b3785a72f19e7cdcc4ffb1703277f761511253bd","subject":"boot: this branch is 18.1-ALPHA now","message":"boot: this branch is 18.1-ALPHA now\n","repos":"opnsense\/core,opnsense\/core,opnsense\/core,opnsense\/core,opnsense\/core,opnsense\/core","old_file":"src\/boot\/logo-hourglass.4th","new_file":"src\/boot\/logo-hourglass.4th","new_contents":"\\ Copyright (c) 2006-2015 Devin Teske \n\\ Copyright (c) 2016-2017 Deciso B.V.\n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\n48 logoX ! 9 logoY ! \\ Initialize logo placement defaults\n\n: logo+ ( x y c-addr\/u -- x y' )\n\t2swap 2dup at-xy 2swap \\ position the cursor\n\t[char] # escc! \\ replace # with Esc\n\ttype \\ print to the screen\n\t1+ \\ increase y for next time we're called\n;\n\n: logo ( x y -- ) \\ color hourglass logo (15 rows x 32 columns)\n\n\ts\" #[37;1m @@@@@@@@@@@@@@@@@@@@@@@@@@@@\" logo+\n\ts\" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\" logo+\n\ts\" @@@@@ @@@@@\" logo+\n\ts\" @@@@@ @@@@@ \" logo+\n\ts\" @@@@@@@@@@@ @@@@@@@@@@@\" logo+\n\ts\" #[31;1m\\\\\\\\\\ \/\/\/\/\/ \" logo+\n\ts\" )))))))))))) (((((((((((\" logo+\n\ts\" \/\/\/\/\/ \\\\\\\\\\ #[m\" logo+\n\ts\" #[37;1m @@@@@@@@@@@ @@@@@@@@@@@\" logo+\n\ts\" @@@@@ @@@@@ \" logo+\n\ts\" @@@@@ @@@@@\" logo+\n\ts\" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\" logo+\n\ts\" @@@@@@@@@@@@@@@@@@@@@@@@@@@@ \" logo+\n\ts\" #[m \" logo+\n\ts\" 18.1 ``Insert Name Here'' #[m\" logo+\n\n\t2drop\n;\n","old_contents":"\\ Copyright (c) 2006-2015 Devin Teske \n\\ Copyright (c) 2016-2017 Deciso B.V.\n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\n48 logoX ! 9 logoY ! \\ Initialize logo placement defaults\n\n: logo+ ( x y c-addr\/u -- x y' )\n\t2swap 2dup at-xy 2swap \\ position the cursor\n\t[char] # escc! \\ replace # with Esc\n\ttype \\ print to the screen\n\t1+ \\ increase y for next time we're called\n;\n\n: logo ( x y -- ) \\ color hourglass logo (15 rows x 32 columns)\n\n\ts\" #[37;1m @@@@@@@@@@@@@@@@@@@@@@@@@@@@\" logo+\n\ts\" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\" logo+\n\ts\" @@@@@ @@@@@\" logo+\n\ts\" @@@@@ @@@@@ \" logo+\n\ts\" @@@@@@@@@@@ @@@@@@@@@@@\" logo+\n\ts\" #[31;1m\\\\\\\\\\ \/\/\/\/\/ \" logo+\n\ts\" )))))))))))) (((((((((((\" logo+\n\ts\" \/\/\/\/\/ \\\\\\\\\\ #[m\" logo+\n\ts\" #[37;1m @@@@@@@@@@@ @@@@@@@@@@@\" logo+\n\ts\" @@@@@ @@@@@ \" logo+\n\ts\" @@@@@ @@@@@\" logo+\n\ts\" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\" logo+\n\ts\" @@@@@@@@@@@@@@@@@@@@@@@@@@@@ \" logo+\n\ts\" #[m \" logo+\n\ts\" 17.7 ``Insert Name Here'' #[m\" logo+\n\n\t2drop\n;\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"cb3748625e112dc297467e4b22bfcc52556effc8","subject":"Core starts at block 30, added LSHIFT and RSHIFT","message":"Core starts at block 30, added LSHIFT and RSHIFT\n","repos":"hth313\/hthforth","old_file":"src\/lib\/core.fth","new_file":"src\/lib\/core.fth","new_contents":"( block 1 -- Main load block )\n\nVARIABLE BLK\n: FH BLK @ + ; \\ relative block\n: LOAD BLK @ SWAP DUP BLK ! (LOAD) BLK ! ;\n\n30 LOAD\n( shadow 1 )\n( block 2 )\n( shadow 2 )\n( block 3 )\n( shadow 3 )\n\n( block 10 )\n( shadow 10 )\n( block 11 )\n( shadow 11 )\n( block 12 )\n( shadow 12 )\n\n( block 30 CORE words )\n\n1 FH 6 FH THRU\n\n( shadow 30 )\n( block 31 stack primitives )\n\n: ROT >R SWAP R> SWAP ;\n: ?DUP DUP IF DUP THEN ;\n\n( Not part of CORE, disabled at the moment )\n\\ : -ROT SWAP >R SWAP R> ; \\ or ROT ROT\n\\ : NIP ( n1 n2 -- n2 ) SWAP DROP ;\n\\ : TUCK ( n1 n2 -- n2 n1 n2 ) SWAP OVER ;\n\n: 2DROP DROP DROP ;\n: 2DUP OVER OVER ;\n: 2SWAP ROT >R ROT R> ;\n: 2OVER >R >R 2DUP R> R> 2SWAP ;\n( shadow 31 )\n( block 32 comparisons )\n\n-1 CONSTANT TRUE 0 CONSTANT FALSE\n\n: = ( n n -- f) XOR 0= ;\n: < ( n n -- f ) - 0< ;\n: > ( n n -- f ) SWAP < ;\n\n: MAX ( n n -- n ) 2DUP < IF SWAP THEN DROP ;\n: MIN ( n n -- n ) 2DUP > IF SWAP THEN DROP ;\n\n: WITHIN ( u ul uh -- f ) OVER - >R - R> U< ;\n( shadow 32 )\n( block 33 ALU )\n\n: 1+ 1 + ;\n: 1- 1 - ;\n: INVERT TRUE XOR ;\n: NEGATE INVERT 1+ ;\n: DNEGATE INVERT SWAP NEGATE SWAP OVER 0= - ;\n: S>D ( n -- d ) DUP 0< ; \\ sign extend\n: ABS S>D IF NEGATE THEN ;\n: DABS DUP 0< IF DNEGATE THEN ;\n\n: +- 0< IF NEGATE THEN ;\n: D+- 0< IF DNEGATE THEN ;\n\n( shadow 33 )\n( block 34 variables )\n\nVARIABLE BASE\n: DECIMAL 10 BASE ! ; : HEX 16 BASE ! ;\n( shadow 34 )\n( block 35 math )\n\n: SM\/REM ( d n -- r q ) \\ symmetric\n OVER >R >R DABS R@ ABS UM\/MOD\n R> R@ XOR 0< IF NEGATE THEN\n R> 0< IF >R NEGATE R> THEN ;\n\n: FM\/MOD ( d n -- r q ) \\ floored\n DUP 0< DUP >R IF NEGATE >R DNEGATE R> THEN\n >R DUP 0< IF R@ + THEN\n R> UM\/MOD R> IF >R NEGATE R> THEN ;\n\n: \/MOD OVER 0< SWAP FM\/MOD ;\n: MOD \/MOD DROP ;\n: \/ \/MOD SWAP DROP ;\n\n( shadow 35 )\n( block 36 math continued )\n\n: * UM* DROP ;\n: M* 2DUP XOR R> ABS SWAP ABS UM* R> D+- ;\n: *\/MOD >R M* R> FM\/MOD ;\n: *\/ *\/MOD SWAP DROP ;\n\n: 2* DUP + ;\n\\ 2\/ which is right shift is native\n\n: LSHIFT ( x1 u -- x2 )\n BEGIN DUP WHILE SWAP 2* SWAP 1- REPEAT DROP ;\n\n: RSHIFT ( x1 u -- x2 )\n BEGIN DUP WHILE SWAP 2\/ SWAP 1- REPEAT DROP ;\n ( shadow 36 )\n( block 37 )\n( shadow 37 )\n( block 38 )\n( shadow 38 )\n( block 39 )\n( shadow 39 )\n( block 40 compiler )\n\n: VARIABLE CREATE 1 CELLS ALLOT ;\n\nVARIABLE STATE ( compilation state variable )\n0 STATE ! ( interpreting by default )\n: [ FALSE STATE ! ;\n: ] TRUE STATE ! ;\n\n( Colon definitions )\n: : CREATE ] ;\n: ; POSTPONE EXIT SMUDGE [ ; IMMEDIATE\n\n( shadow 40 )\n( block 41 )\n( shadow 41 )\n( block 42 interpreter )\n\nCREATE _INPUT-BUFFER 80 CHARS ALLOT ( may do this internally? )\n\n: EVALUATE >IN @ >R 0 >IN ! SOURCE >R >R #IN 2! _INTERPRET\n R> R> #IN 2! R> >IN ! ;\n\n: QUIT _RESET-RSTACK\n BEGIN\n BEGIN\n\t _READ-LINE 0 >IN ! _INPUT-BUFFER 0 EVALUATE CR\n\t STATE @\n UNTIL .\" ok \" ( exhausted input in interpretation mode )\n AGAIN ;\n( shadow 42 )\n","old_contents":"( block 1 -- Main load block )\n\nVARIABLE BLK\n: FH BLK @ + ; \\ relative block\n: LOAD BLK @ SWAP DUP BLK ! (LOAD) BLK ! ;\n\n100 LOAD\n( shadow 1 )\n( block 2 )\n( shadow 2 )\n( block 3 )\n( shadow 3 )\n\n( block 10 )\n( shadow 10 )\n( block 11 )\n( shadow 11 )\n( block 12 )\n( shadow 12 )\n\n( block 100 )\n\n1 FH 6 FH THRU\n\n( shadow 100 )\n( block 101 stack primitives )\n\n: ROT >R SWAP R> SWAP ;\n\\ : -ROT SWAP >R SWAP R> ; \\ or ROT ROT\n: ?DUP DUP IF DUP THEN ;\n\\ : NIP ( n1 n2 -- n2 ) SWAP DROP ;\n\\ : TUCK ( n1 n2 -- n2 n1 n2 ) SWAP OVER ;\n\n: 2DROP DROP DROP ;\n: 2DUP OVER OVER ;\n: 2SWAP ROT >R ROT R> ;\n: 2OVER >R >R 2DUP R> R> 2SWAP ;\n( shadow 101 )\n( block 102 comparisons )\n\n-1 CONSTANT TRUE 0 CONSTANT FALSE\n\n: = ( n n -- f) XOR 0= ;\n: < ( n n -- f ) - 0< ;\n: > ( n n -- f ) SWAP < ;\n\n: MAX ( n n -- n ) 2DUP < IF SWAP THEN DROP ;\n: MIN ( n n -- n ) 2DUP > IF SWAP THEN DROP ;\n\n: WITHIN ( u ul uh -- f ) OVER - >R - R> U< ;\n( shadow 102 )\n( block 103 ALU )\n\n: 1+ 1 + ;\n: 1- 1 - ;\n: INVERT TRUE XOR ;\n: NEGATE INVERT 1+ ;\n: DNEGATE INVERT SWAP NEGATE SWAP OVER 0= - ;\n: S>D ( n -- d ) DUP 0< ; \\ sign extend\n: ABS S>D IF NEGATE THEN ;\n: DABS DUP 0< IF DNEGATE THEN ;\n\n\n: +- 0< IF NEGATE THEN ;\n: D+- 0< IF DNEGATE THEN ;\n\n( shadow 103 )\n( block 104 variables )\n\nVARIABLE BASE\n: DECIMAL 10 BASE ! ; : HEX 16 BASE ! ;\n( shadow 104 )\n( block 105 math )\n\n: SM\/REM ( d n -- r q ) \\ symmetric\n OVER >R >R DABS R@ ABS UM\/MOD\n R> R@ XOR 0< IF NEGATE THEN\n R> 0< IF >R NEGATE R> THEN ;\n\n: FM\/MOD ( d n -- r q ) \\ floored\n DUP 0< DUP >R IF NEGATE >R DNEGATE R> THEN\n >R DUP 0< IF R@ + THEN\n R> UM\/MOD R> IF >R NEGATE R> THEN ;\n\n: \/MOD OVER 0< SWAP FM\/MOD ;\n: MOD \/MOD DROP ;\n: \/ \/MOD SWAP DROP ;\n\n( shadow 105 )\n( block 106 math continued )\n\n: * UM* DROP ;\n: M* 2DUP XOR R> ABS SWAP ABS UM* R> D+- ;\n: *\/MOD >R M* R> FM\/MOD ;\n: *\/ *\/MOD NIP ;\n\n: 2* DUP + ;\n\\ 2\/ which is right shift is native\n( shadow 106 )\n( block 107 )\n( shadow 107 )\n( block 108 )\n( shadow 108 )\n( block 109 )\n( shadow 109 )\n( block 110 compiler )\n\n: VARIABLE CREATE 1 CELLS ALLOT ;\n\nVARIABLE STATE ( compilation state variable )\n0 STATE ! ( interpreting by default )\n: [ FALSE STATE ! ;\n: ] TRUE STATE ! ;\n\n( Colon definitions )\n: : CREATE ] ;\n: ; POSTPONE EXIT SMUDGE [ ; IMMEDIATE\n\n( shadow 110 )\n( block 111 )\n( shadow 111 )\n( block 112 interpreter )\n\nCREATE _INPUT-BUFFER 80 CHARS ALLOT ( may do this internally? )\n\n: EVALUATE >IN @ >R 0 >IN ! SOURCE >R >R #IN 2! _INTERPRET\n R> R> #IN 2! R> >IN ! ;\n\n: QUIT _RESET-RSTACK\n BEGIN\n BEGIN\n\t _READ-LINE 0 >IN ! _INPUT-BUFFER 0 EVALUATE CR\n\t STATE @\n UNTIL .\" ok \" ( exhausted input in interpretation mode )\n AGAIN ;\n( shadow 112 )\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"2a24bbc3884cd6c5dd0f8fd28f93e74c72f09886","subject":"Add constructors to crude structure support. Rework some of the code into a more modular interface, with hidden vocabularies and such. Remove the need to a lot of ugly initialization.","message":"Add constructors to crude structure support. Rework some of the\ncode into a more modular interface, with hidden vocabularies and\nsuch. Remove the need to a lot of ugly initialization.\n\nAlso, add a few structure definitions, from stuff used on the C\npart of loader. Some of this will disappear, and the crude structure\nsupport will most likely be replaced by full-blown OOP support\nalready present on FICL, but not installed by default. But it was\ngetting increasingly inconvenient to keep this separate on my tree,\nand I already lost lots of work once because of the hurdles, so\ncommit this.\n\nAnyway, it makes support.4th more structured, and I'm not proceeding\nwith the work on it any time soon, unfortunately.\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/support.4th","new_file":"sys\/boot\/forth\/support.4th","new_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\ \n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\n\\ Loader.rc support functions:\n\\\n\\ initialize_support ( -- )\tinitialize global variables\n\\ initialize ( addr len -- )\tas above, plus load_conf_files\n\\ load_conf ( addr len -- )\tload conf file given\n\\ include_conf_files ( -- )\tload all conf files in load_conf_files\n\\ print_syntax_error ( -- )\tprint line and marker of where a syntax\n\\\t\t\t\terror was detected\n\\ print_line ( -- )\t\tprint last line processed\n\\ load_kernel ( -- )\t\tload kernel\n\\ load_modules ( -- )\t\tload modules flagged\n\\\n\\ Exported structures:\n\\\n\\ string\t\t\tcounted string structure\n\\\tcell .addr\t\t\tstring address\n\\\tcell .len\t\t\tstring length\n\\ module\t\t\tmodule loading information structure\n\\\tcell module.flag\t\tshould we load it?\n\\\tstring module.name\t\tmodule's name\n\\\tstring module.loadname\t\tname to be used in loading the module\n\\\tstring module.type\t\tmodule's type\n\\\tstring module.args\t\tflags to be passed during load\n\\\tstring module.beforeload\tcommand to be executed before load\n\\\tstring module.afterload\t\tcommand to be executed after load\n\\\tstring module.loaderror\t\tcommand to be executed if load fails\n\\\tcell module.next\t\tlist chain\n\\\n\\ Exported global variables;\n\\\n\\ string conf_files\t\tconfiguration files to be loaded\n\\ string password\t\tpassword\n\\ cell modules_options\t\tpointer to first module information\n\\ value verbose?\t\tindicates if user wants a verbose loading\n\\ value any_conf_read?\t\tindicates if a conf file was succesfully read\n\\\n\\ Other exported words:\n\\\n\\ strdup ( addr len -- addr' len)\t\t\tsimilar to strdup(3)\n\\ strcat ( addr len addr' len' -- addr len+len' )\tsimilar to strcat(3)\n\\ strlen ( addr -- len )\t\t\t\tsimilar to strlen(3)\n\\ s' ( | string' -- addr len | )\t\t\tsimilar to s\"\n\\ rudimentary structure support\n\n\\ Exception values\n\n1 constant syntax_error\n2 constant out_of_memory\n3 constant free_error\n4 constant set_error\n5 constant read_error\n6 constant open_error\n7 constant exec_error\n8 constant before_load_error\n9 constant after_load_error\n\n\\ Crude structure support\n\n: structure:\n create here 0 , ['] drop , 0\n does> create here swap dup @ allot cell+ @ execute\n;\n: member: create dup , over , + does> cell+ @ + ;\n: ;structure swap ! ;\n: constructor! >body cell+ ! ;\n: constructor: over :noname ;\n: ;constructor postpone ; swap cell+ ! ; immediate\n: sizeof ' >body @ state @ if postpone literal then ; immediate\n: offsetof ' >body cell+ @ state @ if postpone literal then ; immediate\n: ptr 1 cells member: ;\n: int 1 cells member: ;\n\n\\ String structure\n\nstructure: string\n\tptr .addr\n\tint .len\n\tconstructor:\n\t 0 over .addr !\n\t 0 swap .len !\n\t;constructor\n;structure\n\n\n\\ Module options linked list\n\nstructure: module\n\tint module.flag\n\tsizeof string member: module.name\n\tsizeof string member: module.loadname\n\tsizeof string member: module.type\n\tsizeof string member: module.args\n\tsizeof string member: module.beforeload\n\tsizeof string member: module.afterload\n\tsizeof string member: module.loaderror\n\tptr module.next\n;structure\n\n\\ Internal loader structures\nstructure: preloaded_file\n\tptr pf.name\n\tptr pf.type\n\tptr pf.args\n\tptr pf.metadata\t\\ file_metadata\n\tint pf.loader\n\tint pf.addr\n\tint pf.size\n\tptr pf.modules\t\\ kernel_module\n\tptr pf.next\t\\ preloaded_file\n;structure\n\nstructure: kernel_module\n\tptr km.name\n\t\\ ptr km.args\n\tptr km.fp\t\\ preloaded_file\n\tptr km.next\t\\ kernel_module\n;structure\n\nstructure: file_metadata\n\tint\t\tmd.size\n\t2 member:\tmd.type\t\\ this is not ANS Forth compatible (XXX)\n\tptr\t\tmd.next\t\\ file_metadata\n\t0 member:\tmd.data\t\\ variable size\n;structure\n\nstructure: config_resource\n\tptr cf.name\n\tint cf.type\n0 constant RES_INT\n1 constant RES_STRING\n2 constant RES_LONG\n\t2 cells member: u\n;structure\n\nstructure: config_device\n\tptr cd.name\n\tint cd.unit\n\tint cd.resource_count\n\tptr cd.resources\t\\ config_resource\n;structure\n\nstructure: STAILQ_HEAD\n\tptr stqh_first\t\\ type*\n\tptr stqh_last\t\\ type**\n;structure\n\nstructure: STAILQ_ENTRY\n\tptr stqe_next\t\\ type*\n;structure\n\nstructure: pnphandler\n\tptr pnph.name\n\tptr pnph.enumerate\n;structure\n\nstructure: pnpident\n\tptr pnpid.ident\t\t\t\t\t\\ char*\n\tsizeof STAILQ_ENTRY cells member: pnpid.link\t\\ pnpident\n;structure\n\nstructure: pnpinfo\n\tptr pnpi.desc\n\tint pnpi.revision\n\tptr pnpi.module\t\t\t\t\\ (char*) module args\n\tint pnpi.argc\n\tptr pnpi.argv\n\tptr pnpi.handler\t\t\t\\ pnphandler\n\tsizeof STAILQ_HEAD member: pnpi.ident\t\\ pnpident\n\tsizeof STAILQ_ENTRY member: pnpi.link\t\\ pnpinfo\n;structure\n\n\\ Global variables\n\nstring conf_files\nstring password\ncreate module_options sizeof module.next allot 0 module_options !\ncreate last_module_option sizeof module.next allot 0 last_module_option !\n0 value verbose?\n\n\\ Support string functions\n\n: strdup ( addr len -- addr' len )\n >r r@ allocate if out_of_memory throw then\n tuck r@ move\n r>\n;\n\n: strcat { addr len addr' len' -- addr len+len' }\n addr' addr len + len' move\n addr len len' +\n;\n\n: strlen ( addr -- len )\n 0 >r\n begin\n dup c@ while\n 1+ r> 1+ >r repeat\n drop r>\n;\n\n: s' \n [char] ' parse\n state @ if\n postpone sliteral\n then\n; immediate\n\n: 2>r postpone >r postpone >r ; immediate\n: 2r> postpone r> postpone r> ; immediate\n\n\\ Private definitions\n\nvocabulary support-functions\nonly forth also support-functions definitions\n\n\\ Some control characters constants\n\n7 constant bell\n8 constant backspace\n9 constant tab\n10 constant lf\n13 constant \n\n\\ Read buffer size\n\n80 constant read_buffer_size\n\n\\ Standard suffixes\n\n: load_module_suffix s\" _load\" ;\n: module_loadname_suffix s\" _name\" ;\n: module_type_suffix s\" _type\" ;\n: module_args_suffix s\" _flags\" ;\n: module_beforeload_suffix s\" _before\" ;\n: module_afterload_suffix s\" _after\" ;\n: module_loaderror_suffix s\" _error\" ;\n\n\\ Support operators\n\n: >= < 0= ;\n: <= > 0= ;\n\n\\ Assorted support funcitons\n\n: free-memory free if free_error throw then ;\n\n\\ Assignment data temporary storage\n\nstring name_buffer\nstring value_buffer\n\n\\ Line by line file reading functions\n\\\n\\ exported:\n\\\tline_buffer\n\\\tend_of_file?\n\\\tfd\n\\\tread_line\n\\\treset_line_reading\n\nvocabulary line-reading\nalso line-reading definitions also\n\n\\ File data temporary storage\n\nstring read_buffer\n0 value read_buffer_ptr\n\n\\ File's line reading function\n\nsupport-functions definitions\n\nstring line_buffer\n0 value end_of_file?\nvariable fd\n\nline-reading definitions\n\n: skip_newlines\n begin\n read_buffer .len @ read_buffer_ptr >\n while\n read_buffer .addr @ read_buffer_ptr + c@ lf = if\n read_buffer_ptr char+ to read_buffer_ptr\n else\n exit\n then\n repeat\n;\n\n: scan_buffer ( -- addr len )\n read_buffer_ptr >r\n begin\n read_buffer .len @ r@ >\n while\n read_buffer .addr @ r@ + c@ lf = if\n read_buffer .addr @ read_buffer_ptr + ( -- addr )\n r@ read_buffer_ptr - ( -- len )\n r> to read_buffer_ptr\n exit\n then\n r> char+ >r\n repeat\n read_buffer .addr @ read_buffer_ptr + ( -- addr )\n r@ read_buffer_ptr - ( -- len )\n r> to read_buffer_ptr\n;\n\n: line_buffer_resize ( len -- len )\n >r\n line_buffer .len @ if\n line_buffer .addr @\n line_buffer .len @ r@ +\n resize if out_of_memory throw then\n else\n r@ allocate if out_of_memory throw then\n then\n line_buffer .addr !\n r>\n;\n \n: append_to_line_buffer ( addr len -- )\n line_buffer .addr @ line_buffer .len @\n 2swap strcat\n line_buffer .len !\n drop\n;\n\n: read_from_buffer\n scan_buffer ( -- addr len )\n line_buffer_resize ( len -- len )\n append_to_line_buffer ( addr len -- )\n;\n\n: refill_required?\n read_buffer .len @ read_buffer_ptr =\n end_of_file? 0= and\n;\n\n: refill_buffer\n 0 to read_buffer_ptr\n read_buffer .addr @ 0= if\n read_buffer_size allocate if out_of_memory throw then\n read_buffer .addr !\n then\n fd @ read_buffer .addr @ read_buffer_size fread\n dup -1 = if read_error throw then\n dup 0= if true to end_of_file? then\n read_buffer .len !\n;\n\n: reset_line_buffer\n line_buffer .addr @ ?dup if\n free-memory\n then\n 0 line_buffer .addr !\n 0 line_buffer .len !\n;\n\nsupport-functions definitions\n\n: reset_line_reading\n 0 to read_buffer_ptr\n;\n\n: read_line\n reset_line_buffer\n skip_newlines\n begin\n read_from_buffer\n refill_required?\n while\n refill_buffer\n repeat\n;\n\nonly forth also support-functions definitions\n\n\\ Conf file line parser:\n\\ ::= '='[] |\n\\ []\n\\ ::= {||'_'}\n\\ ::= '\"'{|'\\'}'\"' | \n\\ ::= ASCII 32 to 126, except '\\' and '\"'\n\\ ::= '#'{}\n\\\n\\ exported:\n\\\tline_pointer\n\\\tprocess_conf\n\n0 value line_pointer\n\nvocabulary file-processing\nalso file-processing definitions\n\n\\ parser functions\n\\\n\\ exported:\n\\\tget_assignment\n\nvocabulary parser\nalso parser definitions also\n\n0 value parsing_function\n0 value end_of_line\n\n: end_of_line?\n line_pointer end_of_line =\n;\n\n: letter?\n line_pointer c@ >r\n r@ [char] A >=\n r@ [char] Z <= and\n r@ [char] a >=\n r> [char] z <= and\n or\n;\n\n: digit?\n line_pointer c@ >r\n r@ [char] 0 >=\n r> [char] 9 <= and\n;\n\n: quote?\n line_pointer c@ [char] \" =\n;\n\n: assignment_sign?\n line_pointer c@ [char] = =\n;\n\n: comment?\n line_pointer c@ [char] # =\n;\n\n: space?\n line_pointer c@ bl =\n line_pointer c@ tab = or\n;\n\n: backslash?\n line_pointer c@ [char] \\ =\n;\n\n: underscore?\n line_pointer c@ [char] _ =\n;\n\n: dot?\n line_pointer c@ [char] . =\n;\n\n: skip_character\n line_pointer char+ to line_pointer\n;\n\n: skip_to_end_of_line\n end_of_line to line_pointer\n;\n\n: eat_space\n begin\n space?\n while\n skip_character\n end_of_line? if exit then\n repeat\n;\n\n: parse_name ( -- addr len )\n line_pointer\n begin\n letter? digit? underscore? dot? or or or\n while\n skip_character\n end_of_line? if \n line_pointer over -\n strdup\n exit\n then\n repeat\n line_pointer over -\n strdup\n;\n\n: remove_backslashes { addr len | addr' len' -- addr' len' }\n len allocate if out_of_memory throw then\n to addr'\n addr >r\n begin\n addr c@ [char] \\ <> if\n addr c@ addr' len' + c!\n len' char+ to len'\n then\n addr char+ to addr\n r@ len + addr =\n until\n r> drop\n addr' len'\n;\n\n: parse_quote ( -- addr len )\n line_pointer\n skip_character\n end_of_line? if syntax_error throw then\n begin\n quote? 0=\n while\n backslash? if\n skip_character\n end_of_line? if syntax_error throw then\n then\n skip_character\n end_of_line? if syntax_error throw then \n repeat\n skip_character\n line_pointer over -\n remove_backslashes\n;\n\n: read_name\n parse_name\t\t( -- addr len )\n name_buffer .len !\n name_buffer .addr !\n;\n\n: read_value\n quote? if\n parse_quote\t\t( -- addr len )\n else\n parse_name\t\t( -- addr len )\n then\n value_buffer .len !\n value_buffer .addr !\n;\n\n: comment\n skip_to_end_of_line\n;\n\n: white_space_4\n eat_space\n comment? if ['] comment to parsing_function exit then\n end_of_line? 0= if syntax_error throw then\n;\n\n: variable_value\n read_value\n ['] white_space_4 to parsing_function\n;\n\n: white_space_3\n eat_space\n letter? digit? quote? or or if\n ['] variable_value to parsing_function exit\n then\n syntax_error throw\n;\n\n: assignment_sign\n skip_character\n ['] white_space_3 to parsing_function\n;\n\n: white_space_2\n eat_space\n assignment_sign? if ['] assignment_sign to parsing_function exit then\n syntax_error throw\n;\n\n: variable_name\n read_name\n ['] white_space_2 to parsing_function\n;\n\n: white_space_1\n eat_space\n letter? if ['] variable_name to parsing_function exit then\n comment? if ['] comment to parsing_function exit then\n end_of_line? 0= if syntax_error throw then\n;\n\nfile-processing definitions\n\n: get_assignment\n line_buffer .addr @ line_buffer .len @ + to end_of_line\n line_buffer .addr @ to line_pointer\n ['] white_space_1 to parsing_function\n begin\n end_of_line? 0=\n while\n parsing_function execute\n repeat\n parsing_function ['] comment =\n parsing_function ['] white_space_1 =\n parsing_function ['] white_space_4 =\n or or 0= if syntax_error throw then\n;\n\nonly forth also support-functions also file-processing definitions also\n\n\\ Process line\n\n: assignment_type? ( addr len -- flag )\n name_buffer .addr @ name_buffer .len @\n compare 0=\n;\n\n: suffix_type? ( addr len -- flag )\n name_buffer .len @ over <= if 2drop false exit then\n name_buffer .len @ over - name_buffer .addr @ +\n over compare 0=\n;\n\n: loader_conf_files?\n s\" loader_conf_files\" assignment_type?\n;\n\n: verbose_flag?\n s\" verbose_loading\" assignment_type?\n;\n\n: execute?\n s\" exec\" assignment_type?\n;\n\n: password?\n s\" password\" assignment_type?\n;\n\n: module_load?\n load_module_suffix suffix_type?\n;\n\n: module_loadname?\n module_loadname_suffix suffix_type?\n;\n\n: module_type?\n module_type_suffix suffix_type?\n;\n\n: module_args?\n module_args_suffix suffix_type?\n;\n\n: module_beforeload?\n module_beforeload_suffix suffix_type?\n;\n\n: module_afterload?\n module_afterload_suffix suffix_type?\n;\n\n: module_loaderror?\n module_loaderror_suffix suffix_type?\n;\n\n: set_conf_files\n conf_files .addr @ ?dup if\n free-memory\n then\n value_buffer .addr @ c@ [char] \" = if\n value_buffer .addr @ char+ value_buffer .len @ 2 chars -\n else\n value_buffer .addr @ value_buffer .len @\n then\n strdup\n conf_files .len ! conf_files .addr !\n;\n\n: append_to_module_options_list ( addr -- )\n module_options @ 0= if\n dup module_options !\n last_module_option !\n else\n dup last_module_option @ module.next !\n last_module_option !\n then\n;\n\n: set_module_name ( addr -- )\n name_buffer .addr @ name_buffer .len @\n strdup\n >r over module.name .addr !\n r> swap module.name .len !\n;\n\n: yes_value?\n value_buffer .addr @ value_buffer .len @\n 2dup s' \"YES\"' compare >r\n 2dup s' \"yes\"' compare >r\n 2dup s\" YES\" compare >r\n s\" yes\" compare r> r> r> and and and 0=\n;\n\n: find_module_option ( -- addr | 0 )\n module_options @\n begin\n dup\n while\n dup module.name dup .addr @ swap .len @\n name_buffer .addr @ name_buffer .len @\n compare 0= if exit then\n module.next @\n repeat\n;\n\n: new_module_option ( -- addr )\n sizeof module allocate if out_of_memory throw then\n dup sizeof module erase\n dup append_to_module_options_list\n dup set_module_name\n;\n\n: get_module_option ( -- addr )\n find_module_option\n ?dup 0= if new_module_option then\n;\n\n: set_module_flag\n name_buffer .len @ load_module_suffix nip - name_buffer .len !\n yes_value? get_module_option module.flag !\n;\n\n: set_module_args\n name_buffer .len @ module_args_suffix nip - name_buffer .len !\n get_module_option module.args\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_loadname\n name_buffer .len @ module_loadname_suffix nip - name_buffer .len !\n get_module_option module.loadname\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_type\n name_buffer .len @ module_type_suffix nip - name_buffer .len !\n get_module_option module.type\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_beforeload\n name_buffer .len @ module_beforeload_suffix nip - name_buffer .len !\n get_module_option module.beforeload\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_afterload\n name_buffer .len @ module_afterload_suffix nip - name_buffer .len !\n get_module_option module.afterload\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_loaderror\n name_buffer .len @ module_loaderror_suffix nip - name_buffer .len !\n get_module_option module.loaderror\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_environment_variable\n name_buffer .len @\n value_buffer .len @ +\n 5 chars +\n allocate if out_of_memory throw then\n dup 0 ( addr -- addr addr len )\n s\" set \" strcat\n name_buffer .addr @ name_buffer .len @ strcat\n s\" =\" strcat\n value_buffer .addr @ value_buffer .len @ strcat\n ['] evaluate catch if\n 2drop free drop\n set_error throw\n else\n free-memory\n then\n;\n\n: set_verbose\n yes_value? to verbose?\n;\n\n: execute_command\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 - swap char+ swap\n then\n ['] evaluate catch if exec_error throw then\n;\n\n: set_password\n password .addr @ ?dup if free if free_error throw then then\n value_buffer .addr @ c@ [char] \" = if\n value_buffer .addr @ char+ value_buffer .len @ 2 - strdup\n value_buffer .addr @ free if free_error throw then\n else\n value_buffer .addr @ value_buffer .len @\n then\n password .len ! password .addr !\n 0 value_buffer .addr !\n;\n\n: process_assignment\n name_buffer .len @ 0= if exit then\n loader_conf_files?\tif set_conf_files exit then\n verbose_flag?\t\tif set_verbose exit then\n execute?\t\tif execute_command exit then\n password?\t\tif set_password exit then\n module_load?\t\tif set_module_flag exit then\n module_loadname?\tif set_module_loadname exit then\n module_type?\t\tif set_module_type exit then\n module_args?\t\tif set_module_args exit then\n module_beforeload?\tif set_module_beforeload exit then\n module_afterload?\tif set_module_afterload exit then\n module_loaderror?\tif set_module_loaderror exit then\n set_environment_variable\n;\n\n\\ free_buffer ( -- )\n\\\n\\ Free some pointers if needed. The code then tests for errors\n\\ in freeing, and throws an exception if needed. If a pointer is\n\\ not allocated, it's value (0) is used as flag.\n\n: free_buffers\n name_buffer .addr @ dup if free then\n value_buffer .addr @ dup if free then\n or if free_error throw then\n;\n\n: reset_assignment_buffers\n 0 name_buffer .addr !\n 0 name_buffer .len !\n 0 value_buffer .addr !\n 0 value_buffer .len !\n;\n\n\\ Higher level file processing\n\nsupport-functions definitions\n\n: process_conf\n begin\n end_of_file? 0=\n while\n reset_assignment_buffers\n read_line\n get_assignment\n ['] process_assignment catch\n ['] free_buffers catch\n swap throw throw\n repeat\n;\n\nonly forth also support-functions definitions\n\n: create_null_terminated_string { addr len -- addr' len }\n len char+ allocate if out_of_memory throw then\n >r\n addr r@ len move\n 0 r@ len + c!\n r> len\n;\n\n\\ Interface to loading conf files\n\n: load_conf ( addr len -- )\n 0 to end_of_file?\n reset_line_reading\n create_null_terminated_string\n over >r\n fopen fd !\n r> free-memory\n fd @ -1 = if open_error throw then\n ['] process_conf catch\n fd @ fclose\n throw\n;\n\n: print_line\n line_buffer .addr @ line_buffer .len @ type cr\n;\n\n: print_syntax_error\n line_buffer .addr @ line_buffer .len @ type cr\n line_buffer .addr @\n begin\n line_pointer over <>\n while\n bl emit\n char+\n repeat\n drop\n .\" ^\" cr\n;\n\n\\ Depuration support functions\n\nonly forth definitions also support-functions\n\n: test-file \n ['] load_conf catch dup .\n syntax_error = if cr print_syntax_error then\n;\n\n: show-module-options\n module_options @\n begin\n ?dup\n while\n .\" Name: \" dup module.name dup .addr @ swap .len @ type cr\n .\" Path: \" dup module.loadname dup .addr @ swap .len @ type cr\n .\" Type: \" dup module.type dup .addr @ swap .len @ type cr\n .\" Flags: \" dup module.args dup .addr @ swap .len @ type cr\n .\" Before load: \" dup module.beforeload dup .addr @ swap .len @ type cr\n .\" After load: \" dup module.afterload dup .addr @ swap .len @ type cr\n .\" Error: \" dup module.loaderror dup .addr @ swap .len @ type cr\n .\" Status: \" dup module.flag @ if .\" Load\" else .\" Don't load\" then cr\n module.next @\n repeat\n;\n\nonly forth also support-functions definitions\n\n\\ Variables used for processing multiple conf files\n\nstring current_file_name\nvariable current_conf_files\n\n\\ Indicates if any conf file was succesfully read\n\n0 value any_conf_read?\n\n\\ loader_conf_files processing support functions\n\n: set_current_conf_files\n conf_files .addr @ current_conf_files !\n;\n\n: get_conf_files\n conf_files .addr @ conf_files .len @ strdup\n;\n\n: recurse_on_conf_files?\n current_conf_files @ conf_files .addr @ <>\n;\n\n: skip_leading_spaces { addr len pos -- addr len pos' }\n begin\n pos len = if addr len pos exit then\n addr pos + c@ bl =\n while\n pos char+ to pos\n repeat\n addr len pos\n;\n\n: get_file_name { addr len pos -- addr len pos' addr' len' || 0 }\n pos len = if \n addr free abort\" Fatal error freeing memory\"\n 0 exit\n then\n pos >r\n begin\n addr pos + c@ bl <>\n while\n pos char+ to pos\n pos len = if\n addr len pos addr r@ + pos r> - exit\n then\n repeat\n addr len pos addr r@ + pos r> -\n;\n\n: get_next_file ( addr len ptr -- addr len ptr' addr' len' | 0 )\n skip_leading_spaces\n get_file_name\n;\n\n: set_current_file_name\n over current_file_name .addr !\n dup current_file_name .len !\n;\n\n: print_current_file\n current_file_name .addr @ current_file_name .len @ type\n;\n\n: process_conf_errors\n dup 0= if true to any_conf_read? drop exit then\n >r 2drop r>\n dup syntax_error = if\n .\" Warning: syntax error on file \" print_current_file cr\n print_syntax_error drop exit\n then\n dup set_error = if\n .\" Warning: bad definition on file \" print_current_file cr\n print_line drop exit\n then\n dup read_error = if\n .\" Warning: error reading file \" print_current_file cr drop exit\n then\n dup open_error = if\n verbose? if .\" Warning: unable to open file \" print_current_file cr then\n drop exit\n then\n dup free_error = abort\" Fatal error freeing memory\"\n dup out_of_memory = abort\" Out of memory\"\n throw \\ Unknown error -- pass ahead\n;\n\n\\ Process loader_conf_files recursively\n\\ Interface to loader_conf_files processing\n\n: include_conf_files\n set_current_conf_files\n get_conf_files 0\n begin\n get_next_file ?dup\n while\n set_current_file_name\n ['] load_conf catch\n process_conf_errors\n recurse_on_conf_files? if recurse then\n repeat\n;\n\n\\ Module loading functions\n\n: load_module?\n module.flag @\n;\n\n: load_parameters ( addr -- addr addrN lenN ... addr1 len1 N )\n dup >r\n r@ module.args .addr @ r@ module.args .len @\n r@ module.loadname .len @ if\n r@ module.loadname .addr @ r@ module.loadname .len @\n else\n r@ module.name .addr @ r@ module.name .len @\n then\n r@ module.type .len @ if\n r@ module.type .addr @ r@ module.type .len @\n s\" -t \"\n 4 ( -t type name flags )\n else\n 2 ( name flags )\n then\n r> drop\n;\n\n: before_load ( addr -- addr )\n dup module.beforeload .len @ if\n dup module.beforeload .addr @ over module.beforeload .len @\n ['] evaluate catch if before_load_error throw then\n then\n;\n\n: after_load ( addr -- addr )\n dup module.afterload .len @ if\n dup module.afterload .addr @ over module.afterload .len @\n ['] evaluate catch if after_load_error throw then\n then\n;\n\n: load_error ( addr -- addr )\n dup module.loaderror .len @ if\n dup module.loaderror .addr @ over module.loaderror .len @\n evaluate \\ This we do not intercept so it can throw errors\n then\n;\n\n: pre_load_message ( addr -- addr )\n verbose? if\n dup module.name .addr @ over module.name .len @ type\n .\" ...\"\n then\n;\n\n: load_error_message verbose? if .\" failed!\" cr then ;\n\n: load_succesful_message verbose? if .\" ok\" cr then ;\n\n: load_module\n load_parameters load\n;\n\n: process_module ( addr -- addr )\n pre_load_message\n before_load\n begin\n ['] load_module catch if\n dup module.loaderror .len @ if\n load_error\t\t\t\\ Command should return a flag!\n else \n load_error_message true\t\t\\ Do not retry\n then\n else\n after_load\n load_succesful_message true\t\\ Succesful, do not retry\n then\n until\n;\n\n: process_module_errors ( addr ior -- )\n dup before_load_error = if\n drop\n .\" Module \"\n dup module.name .addr @ over module.name .len @ type\n dup module.loadname .len @ if\n .\" (\" dup module.loadname .addr @ over module.loadname .len @ type .\" )\"\n then\n cr\n .\" Error executing \"\n dup module.beforeload .addr @ over module.afterload .len @ type cr\n abort\n then\n\n dup after_load_error = if\n drop\n .\" Module \"\n dup module.name .addr @ over module.name .len @ type\n dup module.loadname .len @ if\n .\" (\" dup module.loadname .addr @ over module.loadname .len @ type .\" )\"\n then\n cr\n .\" Error executing \"\n dup module.afterload .addr @ over module.afterload .len @ type cr\n abort\n then\n\n throw \\ Don't know what it is all about -- pass ahead\n;\n\n\\ Module loading interface\n\n: load_modules ( -- ) ( throws: abort & user-defined )\n module_options @\n begin\n ?dup\n while\n dup load_module? if\n ['] process_module catch\n process_module_errors\n then\n module.next @\n repeat\n;\n\n\\ Additional functions used in \"start\"\n\n: initialize ( addr len -- )\n strdup conf_files .len ! conf_files .addr !\n;\n\n: load_kernel ( -- ) ( throws: abort )\n s\" load ${kernel} ${kernel_options}\" ['] evaluate catch\n if s\" echo Unable to load kernel: ${kernel_name}\" evaluate abort then\n;\n\n: read-password { size | buf len -- }\n size allocate if out_of_memory throw then\n to buf\n 0 to len\n begin\n key\n dup backspace = if\n drop\n len if\n backspace emit bl emit backspace emit\n len 1 - to len\n else\n bell emit\n then\n else\n dup = if cr drop buf len exit then\n [char] * emit\n len size < if\n buf len chars + c!\n else\n drop\n then\n len 1+ to len\n then\n again\n;\n\n\\ Go back to straight forth vocabulary\n\nonly forth also definitions\n\n","old_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\ \n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\n\\ Loader.rc support functions:\n\\\n\\ initialize_support ( -- )\tinitialize global variables\n\\ initialize ( addr len -- )\tas above, plus load_conf_files\n\\ load_conf ( addr len -- )\tload conf file given\n\\ include_conf_files ( -- )\tload all conf files in load_conf_files\n\\ print_syntax_error ( -- )\tprint line and marker of where a syntax\n\\\t\t\t\terror was detected\n\\ print_line ( -- )\t\tprint last line processed\n\\ load_kernel ( -- )\t\tload kernel\n\\ load_modules ( -- )\t\tload modules flagged\n\\\n\\ Exported structures:\n\\\n\\ string\t\t\tcounted string structure\n\\\tcell .addr\t\t\tstring address\n\\\tcell .len\t\t\tstring length\n\\ module\t\t\tmodule loading information structure\n\\\tcell module.flag\t\tshould we load it?\n\\\tstring module.name\t\tmodule's name\n\\\tstring module.loadname\t\tname to be used in loading the module\n\\\tstring module.type\t\tmodule's type\n\\\tstring module.args\t\tflags to be passed during load\n\\\tstring module.beforeload\tcommand to be executed before load\n\\\tstring module.afterload\t\tcommand to be executed after load\n\\\tstring module.loaderror\t\tcommand to be executed if load fails\n\\\tcell module.next\t\tlist chain\n\\\n\\ Exported global variables;\n\\\n\\ string conf_files\t\tconfiguration files to be loaded\n\\ string password\t\tpassword\n\\ cell modules_options\t\tpointer to first module information\n\\ value verbose?\t\tindicates if user wants a verbose loading\n\\ value any_conf_read?\t\tindicates if a conf file was succesfully read\n\\\n\\ Other exported words:\n\\\n\\ strdup ( addr len -- addr' len)\t\t\tsimilar to strdup(3)\n\\ strcat ( addr len addr' len' -- addr len+len' )\tsimilar to strcat(3)\n\\ strlen ( addr -- len )\t\t\t\tsimilar to strlen(3)\n\\ s' ( | string' -- addr len | )\t\t\tsimilar to s\"\n\\ rudimentary structure support\n\n\\ Exception values\n\n1 constant syntax_error\n2 constant out_of_memory\n3 constant free_error\n4 constant set_error\n5 constant read_error\n6 constant open_error\n7 constant exec_error\n8 constant before_load_error\n9 constant after_load_error\n\n\\ Crude structure support\n\n: structure: create here 0 , 0 does> create @ allot ;\n: member: create dup , over , + does> cell+ @ + ;\n: ;structure swap ! ;\n: sizeof ' >body @ state @ if postpone literal then ; immediate\n: offsetof ' >body cell+ @ state @ if postpone literal then ; immediate\n: ptr 1 cells member: ;\n: int 1 cells member: ;\n\n\\ String structure\n\nstructure: string\n\tptr .addr\n\tint .len\n;structure\n\n\\ Module options linked list\n\nstructure: module\n\tint module.flag\n\tsizeof string member: module.name\n\tsizeof string member: module.loadname\n\tsizeof string member: module.type\n\tsizeof string member: module.args\n\tsizeof string member: module.beforeload\n\tsizeof string member: module.afterload\n\tsizeof string member: module.loaderror\n\tptr module.next\n;structure\n\n\\ Global variables\n\nstring conf_files\nstring password\ncreate module_options sizeof module.next allot\ncreate last_module_option sizeof module.next allot\n0 value verbose?\n\n\\ Support string functions\n\n: strdup ( addr len -- addr' len )\n >r r@ allocate if out_of_memory throw then\n tuck r@ move\n r>\n;\n\n: strcat { addr len addr' len' -- addr len+len' }\n addr' addr len + len' move\n addr len len' +\n;\n\n: strlen ( addr -- len )\n 0 >r\n begin\n dup c@ while\n 1+ r> 1+ >r repeat\n drop r>\n;\n\n: s' \n [char] ' parse\n state @ if\n postpone sliteral\n then\n; immediate\n\n: 2>r postpone >r postpone >r ; immediate\n: 2r> postpone r> postpone r> ; immediate\n\n\\ Private definitions\n\nvocabulary support-functions\nonly forth also support-functions definitions\n\n\\ Some control characters constants\n\n7 constant bell\n8 constant backspace\n9 constant tab\n10 constant lf\n13 constant \n\n\\ Read buffer size\n\n80 constant read_buffer_size\n\n\\ Standard suffixes\n\n: load_module_suffix s\" _load\" ;\n: module_loadname_suffix s\" _name\" ;\n: module_type_suffix s\" _type\" ;\n: module_args_suffix s\" _flags\" ;\n: module_beforeload_suffix s\" _before\" ;\n: module_afterload_suffix s\" _after\" ;\n: module_loaderror_suffix s\" _error\" ;\n\n\\ Support operators\n\n: >= < 0= ;\n: <= > 0= ;\n\n\\ Assorted support funcitons\n\n: free-memory free if free_error throw then ;\n\n\\ Assignment data temporary storage\n\nstring name_buffer\nstring value_buffer\n\n\\ File data temporary storage\n\nstring line_buffer\nstring read_buffer\n0 value read_buffer_ptr\n\n\\ File's line reading function\n\n0 value end_of_file?\nvariable fd\n\n: skip_newlines\n begin\n read_buffer .len @ read_buffer_ptr >\n while\n read_buffer .addr @ read_buffer_ptr + c@ lf = if\n read_buffer_ptr char+ to read_buffer_ptr\n else\n exit\n then\n repeat\n;\n\n: scan_buffer ( -- addr len )\n read_buffer_ptr >r\n begin\n read_buffer .len @ r@ >\n while\n read_buffer .addr @ r@ + c@ lf = if\n read_buffer .addr @ read_buffer_ptr + ( -- addr )\n r@ read_buffer_ptr - ( -- len )\n r> to read_buffer_ptr\n exit\n then\n r> char+ >r\n repeat\n read_buffer .addr @ read_buffer_ptr + ( -- addr )\n r@ read_buffer_ptr - ( -- len )\n r> to read_buffer_ptr\n;\n\n: line_buffer_resize ( len -- len )\n >r\n line_buffer .len @ if\n line_buffer .addr @\n line_buffer .len @ r@ +\n resize if out_of_memory throw then\n else\n r@ allocate if out_of_memory throw then\n then\n line_buffer .addr !\n r>\n;\n \n: append_to_line_buffer ( addr len -- )\n line_buffer .addr @ line_buffer .len @\n 2swap strcat\n line_buffer .len !\n drop\n;\n\n: read_from_buffer\n scan_buffer ( -- addr len )\n line_buffer_resize ( len -- len )\n append_to_line_buffer ( addr len -- )\n;\n\n: refill_required?\n read_buffer .len @ read_buffer_ptr =\n end_of_file? 0= and\n;\n\n: refill_buffer\n 0 to read_buffer_ptr\n read_buffer .addr @ 0= if\n read_buffer_size allocate if out_of_memory throw then\n read_buffer .addr !\n then\n fd @ read_buffer .addr @ read_buffer_size fread\n dup -1 = if read_error throw then\n dup 0= if true to end_of_file? then\n read_buffer .len !\n;\n\n: reset_line_buffer\n 0 line_buffer .addr !\n 0 line_buffer .len !\n;\n\n: read_line\n reset_line_buffer\n skip_newlines\n begin\n read_from_buffer\n refill_required?\n while\n refill_buffer\n repeat\n;\n\n\\ Conf file line parser:\n\\ ::= '='[] |\n\\ []\n\\ ::= {||'_'}\n\\ ::= '\"'{|'\\'}'\"' | \n\\ ::= ASCII 32 to 126, except '\\' and '\"'\n\\ ::= '#'{}\n\n0 value parsing_function\n\n0 value end_of_line\n0 value line_pointer\n\n: end_of_line?\n line_pointer end_of_line =\n;\n\n: letter?\n line_pointer c@ >r\n r@ [char] A >=\n r@ [char] Z <= and\n r@ [char] a >=\n r> [char] z <= and\n or\n;\n\n: digit?\n line_pointer c@ >r\n r@ [char] 0 >=\n r> [char] 9 <= and\n;\n\n: quote?\n line_pointer c@ [char] \" =\n;\n\n: assignment_sign?\n line_pointer c@ [char] = =\n;\n\n: comment?\n line_pointer c@ [char] # =\n;\n\n: space?\n line_pointer c@ bl =\n line_pointer c@ tab = or\n;\n\n: backslash?\n line_pointer c@ [char] \\ =\n;\n\n: underscore?\n line_pointer c@ [char] _ =\n;\n\n: dot?\n line_pointer c@ [char] . =\n;\n\n: skip_character\n line_pointer char+ to line_pointer\n;\n\n: skip_to_end_of_line\n end_of_line to line_pointer\n;\n\n: eat_space\n begin\n space?\n while\n skip_character\n end_of_line? if exit then\n repeat\n;\n\n: parse_name ( -- addr len )\n line_pointer\n begin\n letter? digit? underscore? dot? or or or\n while\n skip_character\n end_of_line? if \n line_pointer over -\n strdup\n exit\n then\n repeat\n line_pointer over -\n strdup\n;\n\n: remove_backslashes { addr len | addr' len' -- addr' len' }\n len allocate if out_of_memory throw then\n to addr'\n addr >r\n begin\n addr c@ [char] \\ <> if\n addr c@ addr' len' + c!\n len' char+ to len'\n then\n addr char+ to addr\n r@ len + addr =\n until\n r> drop\n addr' len'\n;\n\n: parse_quote ( -- addr len )\n line_pointer\n skip_character\n end_of_line? if syntax_error throw then\n begin\n quote? 0=\n while\n backslash? if\n skip_character\n end_of_line? if syntax_error throw then\n then\n skip_character\n end_of_line? if syntax_error throw then \n repeat\n skip_character\n line_pointer over -\n remove_backslashes\n;\n\n: read_name\n parse_name\t\t( -- addr len )\n name_buffer .len !\n name_buffer .addr !\n;\n\n: read_value\n quote? if\n parse_quote\t\t( -- addr len )\n else\n parse_name\t\t( -- addr len )\n then\n value_buffer .len !\n value_buffer .addr !\n;\n\n: comment\n skip_to_end_of_line\n;\n\n: white_space_4\n eat_space\n comment? if ['] comment to parsing_function exit then\n end_of_line? 0= if syntax_error throw then\n;\n\n: variable_value\n read_value\n ['] white_space_4 to parsing_function\n;\n\n: white_space_3\n eat_space\n letter? digit? quote? or or if\n ['] variable_value to parsing_function exit\n then\n syntax_error throw\n;\n\n: assignment_sign\n skip_character\n ['] white_space_3 to parsing_function\n;\n\n: white_space_2\n eat_space\n assignment_sign? if ['] assignment_sign to parsing_function exit then\n syntax_error throw\n;\n\n: variable_name\n read_name\n ['] white_space_2 to parsing_function\n;\n\n: white_space_1\n eat_space\n letter? if ['] variable_name to parsing_function exit then\n comment? if ['] comment to parsing_function exit then\n end_of_line? 0= if syntax_error throw then\n;\n\n: get_assignment\n line_buffer .addr @ line_buffer .len @ + to end_of_line\n line_buffer .addr @ to line_pointer\n ['] white_space_1 to parsing_function\n begin\n end_of_line? 0=\n while\n parsing_function execute\n repeat\n parsing_function ['] comment =\n parsing_function ['] white_space_1 =\n parsing_function ['] white_space_4 =\n or or 0= if syntax_error throw then\n;\n\n\\ Process line\n\n: assignment_type? ( addr len -- flag )\n name_buffer .addr @ name_buffer .len @\n compare 0=\n;\n\n: suffix_type? ( addr len -- flag )\n name_buffer .len @ over <= if 2drop false exit then\n name_buffer .len @ over - name_buffer .addr @ +\n over compare 0=\n;\n\n: loader_conf_files?\n s\" loader_conf_files\" assignment_type?\n;\n\n: verbose_flag?\n s\" verbose_loading\" assignment_type?\n;\n\n: execute?\n s\" exec\" assignment_type?\n;\n\n: password?\n s\" password\" assignment_type?\n;\n\n: module_load?\n load_module_suffix suffix_type?\n;\n\n: module_loadname?\n module_loadname_suffix suffix_type?\n;\n\n: module_type?\n module_type_suffix suffix_type?\n;\n\n: module_args?\n module_args_suffix suffix_type?\n;\n\n: module_beforeload?\n module_beforeload_suffix suffix_type?\n;\n\n: module_afterload?\n module_afterload_suffix suffix_type?\n;\n\n: module_loaderror?\n module_loaderror_suffix suffix_type?\n;\n\n: set_conf_files\n conf_files .addr @ ?dup if\n free-memory\n then\n value_buffer .addr @ c@ [char] \" = if\n value_buffer .addr @ char+ value_buffer .len @ 2 chars -\n else\n value_buffer .addr @ value_buffer .len @\n then\n strdup\n conf_files .len ! conf_files .addr !\n;\n\n: append_to_module_options_list ( addr -- )\n module_options @ 0= if\n dup module_options !\n last_module_option !\n else\n dup last_module_option @ module.next !\n last_module_option !\n then\n;\n\n: set_module_name ( addr -- )\n name_buffer .addr @ name_buffer .len @\n strdup\n >r over module.name .addr !\n r> swap module.name .len !\n;\n\n: yes_value?\n value_buffer .addr @ value_buffer .len @\n 2dup s' \"YES\"' compare >r\n 2dup s' \"yes\"' compare >r\n 2dup s\" YES\" compare >r\n s\" yes\" compare r> r> r> and and and 0=\n;\n\n: find_module_option ( -- addr | 0 )\n module_options @\n begin\n dup\n while\n dup module.name dup .addr @ swap .len @\n name_buffer .addr @ name_buffer .len @\n compare 0= if exit then\n module.next @\n repeat\n;\n\n: new_module_option ( -- addr )\n sizeof module allocate if out_of_memory throw then\n dup sizeof module erase\n dup append_to_module_options_list\n dup set_module_name\n;\n\n: get_module_option ( -- addr )\n find_module_option\n ?dup 0= if new_module_option then\n;\n\n: set_module_flag\n name_buffer .len @ load_module_suffix nip - name_buffer .len !\n yes_value? get_module_option module.flag !\n;\n\n: set_module_args\n name_buffer .len @ module_args_suffix nip - name_buffer .len !\n get_module_option module.args\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_loadname\n name_buffer .len @ module_loadname_suffix nip - name_buffer .len !\n get_module_option module.loadname\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_type\n name_buffer .len @ module_type_suffix nip - name_buffer .len !\n get_module_option module.type\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_beforeload\n name_buffer .len @ module_beforeload_suffix nip - name_buffer .len !\n get_module_option module.beforeload\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_afterload\n name_buffer .len @ module_afterload_suffix nip - name_buffer .len !\n get_module_option module.afterload\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_loaderror\n name_buffer .len @ module_loaderror_suffix nip - name_buffer .len !\n get_module_option module.loaderror\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_environment_variable\n name_buffer .len @\n value_buffer .len @ +\n 5 chars +\n allocate if out_of_memory throw then\n dup 0 ( addr -- addr addr len )\n s\" set \" strcat\n name_buffer .addr @ name_buffer .len @ strcat\n s\" =\" strcat\n value_buffer .addr @ value_buffer .len @ strcat\n ['] evaluate catch if\n 2drop free drop\n set_error throw\n else\n free-memory\n then\n;\n\n: set_verbose\n yes_value? to verbose?\n;\n\n: execute_command\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 - swap char+ swap\n then\n ['] evaluate catch if exec_error throw then\n;\n\n: set_password\n password .addr @ ?dup if free if free_error throw then then\n value_buffer .addr @ c@ [char] \" = if\n value_buffer .addr @ char+ value_buffer .len @ 2 - strdup\n value_buffer .addr @ free if free_error throw then\n else\n value_buffer .addr @ value_buffer .len @\n then\n password .len ! password .addr !\n 0 value_buffer .addr !\n;\n\n: process_assignment\n name_buffer .len @ 0= if exit then\n loader_conf_files?\tif set_conf_files exit then\n verbose_flag?\t\tif set_verbose exit then\n execute?\t\tif execute_command exit then\n password?\t\tif set_password exit then\n module_load?\t\tif set_module_flag exit then\n module_loadname?\tif set_module_loadname exit then\n module_type?\t\tif set_module_type exit then\n module_args?\t\tif set_module_args exit then\n module_beforeload?\tif set_module_beforeload exit then\n module_afterload?\tif set_module_afterload exit then\n module_loaderror?\tif set_module_loaderror exit then\n set_environment_variable\n;\n\n\\ free_buffer ( -- )\n\\\n\\ Free some pointers if needed. The code then tests for errors\n\\ in freeing, and throws an exception if needed. If a pointer is\n\\ not allocated, it's value (0) is used as flag.\n\n: free_buffers\n line_buffer .addr @ dup if free then\n name_buffer .addr @ dup if free then\n value_buffer .addr @ dup if free then\n or or if free_error throw then\n;\n\n: reset_assignment_buffers\n 0 name_buffer .addr !\n 0 name_buffer .len !\n 0 value_buffer .addr !\n 0 value_buffer .len !\n;\n\n\\ Higher level file processing\n\n: process_conf\n begin\n end_of_file? 0=\n while\n reset_assignment_buffers\n read_line\n get_assignment\n ['] process_assignment catch\n ['] free_buffers catch\n swap throw throw\n repeat\n;\n\n: create_null_terminated_string { addr len -- addr' len }\n len char+ allocate if out_of_memory throw then\n >r\n addr r@ len move\n 0 r@ len + c!\n r> len\n;\n\n\\ Interface to loading conf files\n\n: load_conf ( addr len -- )\n 0 to end_of_file?\n 0 to read_buffer_ptr\n create_null_terminated_string\n over >r\n fopen fd !\n r> free-memory\n fd @ -1 = if open_error throw then\n ['] process_conf catch\n fd @ fclose\n throw\n;\n\n: initialize_support\n 0 read_buffer .addr !\n 0 conf_files .addr !\n 0 password .addr !\n 0 module_options !\n 0 last_module_option !\n 0 to verbose?\n;\n\n: print_line\n line_buffer .addr @ line_buffer .len @ type cr\n;\n\n: print_syntax_error\n line_buffer .addr @ line_buffer .len @ type cr\n line_buffer .addr @\n begin\n line_pointer over <>\n while\n bl emit\n char+\n repeat\n drop\n .\" ^\" cr\n;\n\n\\ Depuration support functions\n\nonly forth definitions also support-functions\n\n: test-file \n ['] load_conf catch dup .\n syntax_error = if cr print_syntax_error then\n;\n\n: show-module-options\n module_options @\n begin\n ?dup\n while\n .\" Name: \" dup module.name dup .addr @ swap .len @ type cr\n .\" Path: \" dup module.loadname dup .addr @ swap .len @ type cr\n .\" Type: \" dup module.type dup .addr @ swap .len @ type cr\n .\" Flags: \" dup module.args dup .addr @ swap .len @ type cr\n .\" Before load: \" dup module.beforeload dup .addr @ swap .len @ type cr\n .\" After load: \" dup module.afterload dup .addr @ swap .len @ type cr\n .\" Error: \" dup module.loaderror dup .addr @ swap .len @ type cr\n .\" Status: \" dup module.flag @ if .\" Load\" else .\" Don't load\" then cr\n module.next @\n repeat\n;\n\nonly forth also support-functions definitions\n\n\\ Variables used for processing multiple conf files\n\nstring current_file_name\nvariable current_conf_files\n\n\\ Indicates if any conf file was succesfully read\n\n0 value any_conf_read?\n\n\\ loader_conf_files processing support functions\n\n: set_current_conf_files\n conf_files .addr @ current_conf_files !\n;\n\n: get_conf_files\n conf_files .addr @ conf_files .len @ strdup\n;\n\n: recurse_on_conf_files?\n current_conf_files @ conf_files .addr @ <>\n;\n\n: skip_leading_spaces { addr len pos -- addr len pos' }\n begin\n pos len = if addr len pos exit then\n addr pos + c@ bl =\n while\n pos char+ to pos\n repeat\n addr len pos\n;\n\n: get_file_name { addr len pos -- addr len pos' addr' len' || 0 }\n pos len = if \n addr free abort\" Fatal error freeing memory\"\n 0 exit\n then\n pos >r\n begin\n addr pos + c@ bl <>\n while\n pos char+ to pos\n pos len = if\n addr len pos addr r@ + pos r> - exit\n then\n repeat\n addr len pos addr r@ + pos r> -\n;\n\n: get_next_file ( addr len ptr -- addr len ptr' addr' len' | 0 )\n skip_leading_spaces\n get_file_name\n;\n\n: set_current_file_name\n over current_file_name .addr !\n dup current_file_name .len !\n;\n\n: print_current_file\n current_file_name .addr @ current_file_name .len @ type\n;\n\n: process_conf_errors\n dup 0= if true to any_conf_read? drop exit then\n >r 2drop r>\n dup syntax_error = if\n .\" Warning: syntax error on file \" print_current_file cr\n print_syntax_error drop exit\n then\n dup set_error = if\n .\" Warning: bad definition on file \" print_current_file cr\n print_line drop exit\n then\n dup read_error = if\n .\" Warning: error reading file \" print_current_file cr drop exit\n then\n dup open_error = if\n verbose? if .\" Warning: unable to open file \" print_current_file cr then\n drop exit\n then\n dup free_error = abort\" Fatal error freeing memory\"\n dup out_of_memory = abort\" Out of memory\"\n throw \\ Unknown error -- pass ahead\n;\n\n\\ Process loader_conf_files recursively\n\\ Interface to loader_conf_files processing\n\n: include_conf_files\n set_current_conf_files\n get_conf_files 0\n begin\n get_next_file ?dup\n while\n set_current_file_name\n ['] load_conf catch\n process_conf_errors\n recurse_on_conf_files? if recurse then\n repeat\n;\n\n\\ Module loading functions\n\n: load_module?\n module.flag @\n;\n\n: load_parameters ( addr -- addr addrN lenN ... addr1 len1 N )\n dup >r\n r@ module.args .addr @ r@ module.args .len @\n r@ module.loadname .len @ if\n r@ module.loadname .addr @ r@ module.loadname .len @\n else\n r@ module.name .addr @ r@ module.name .len @\n then\n r@ module.type .len @ if\n r@ module.type .addr @ r@ module.type .len @\n s\" -t \"\n 4 ( -t type name flags )\n else\n 2 ( name flags )\n then\n r> drop\n;\n\n: before_load ( addr -- addr )\n dup module.beforeload .len @ if\n dup module.beforeload .addr @ over module.beforeload .len @\n ['] evaluate catch if before_load_error throw then\n then\n;\n\n: after_load ( addr -- addr )\n dup module.afterload .len @ if\n dup module.afterload .addr @ over module.afterload .len @\n ['] evaluate catch if after_load_error throw then\n then\n;\n\n: load_error ( addr -- addr )\n dup module.loaderror .len @ if\n dup module.loaderror .addr @ over module.loaderror .len @\n evaluate \\ This we do not intercept so it can throw errors\n then\n;\n\n: pre_load_message ( addr -- addr )\n verbose? if\n dup module.name .addr @ over module.name .len @ type\n .\" ...\"\n then\n;\n\n: load_error_message verbose? if .\" failed!\" cr then ;\n\n: load_succesful_message verbose? if .\" ok\" cr then ;\n\n: load_module\n load_parameters load\n;\n\n: process_module ( addr -- addr )\n pre_load_message\n before_load\n begin\n ['] load_module catch if\n dup module.loaderror .len @ if\n load_error\t\t\t\\ Command should return a flag!\n else \n load_error_message true\t\t\\ Do not retry\n then\n else\n after_load\n load_succesful_message true\t\\ Succesful, do not retry\n then\n until\n;\n\n: process_module_errors ( addr ior -- )\n dup before_load_error = if\n drop\n .\" Module \"\n dup module.name .addr @ over module.name .len @ type\n dup module.loadname .len @ if\n .\" (\" dup module.loadname .addr @ over module.loadname .len @ type .\" )\"\n then\n cr\n .\" Error executing \"\n dup module.beforeload .addr @ over module.afterload .len @ type cr\n abort\n then\n\n dup after_load_error = if\n drop\n .\" Module \"\n dup module.name .addr @ over module.name .len @ type\n dup module.loadname .len @ if\n .\" (\" dup module.loadname .addr @ over module.loadname .len @ type .\" )\"\n then\n cr\n .\" Error executing \"\n dup module.afterload .addr @ over module.afterload .len @ type cr\n abort\n then\n\n throw \\ Don't know what it is all about -- pass ahead\n;\n\n\\ Module loading interface\n\n: load_modules ( -- ) ( throws: abort & user-defined )\n module_options @\n begin\n ?dup\n while\n dup load_module? if\n ['] process_module catch\n process_module_errors\n then\n module.next @\n repeat\n;\n\n\\ Additional functions used in \"start\"\n\n: initialize ( addr len -- )\n initialize_support\n strdup conf_files .len ! conf_files .addr !\n;\n\n: load_kernel ( -- ) ( throws: abort )\n s\" load ${kernel} ${kernel_options}\" ['] evaluate catch\n if s\" echo Unable to load kernel: ${kernel_name}\" evaluate abort then\n;\n\n: read-password { size | buf len -- }\n size allocate if out_of_memory throw then\n to buf\n 0 to len\n begin\n key\n dup backspace = if\n drop\n len if\n backspace emit bl emit backspace emit\n len 1 - to len\n else\n bell emit\n then\n else\n dup = if cr drop buf len exit then\n [char] * emit\n len size < if\n buf len chars + c!\n else\n drop\n then\n len 1+ to len\n then\n again\n;\n\n\\ Go back to straight forth vocabulary\n\nonly forth also definitions\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"da727424691e747241a903799a4c8f7467748fb9","subject":"Fix a scope issue. Console10 is only defined if you use it.","message":"Fix a scope issue. Console10 is only defined if you use it.","repos":"rbsexton\/sockpuppet,rbsexton\/sockpuppet","old_file":"forth\/serCM3_SAPI-level1.fth","new_file":"forth\/serCM3_SAPI-level1.fth","new_contents":"\\ serCM3_sapi_level1.fth - SAPI polled RX, polled TX, serial communication drivers\n\\ with support for blocking IO.\n\\ Written to run against the SockPuppet API.\n\n\\ Level 1 support. Requires TASKING. System calls request blocking.\n\\ KEY requires blocking, so that must be implemented here.\n\n\\ Copyright (c) 2017, Robert Sexton. All rights reserved.\n\\ Covered by the terms of the supplied Licence.txt file\n\nonly forth definitions\n\n\\ ==============\n\\ *T SAPI polled serial driver\n\\ ==============\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\n\\ ** using the internal UARTs via the SAPI call layer. This is \n\\ ** The simplest implementation level.\n\\ ** It doesn't use the CR or TYPE calls, but rather emulates them.\n\n\\ ****************\n\\ *S Configuration\n\\ ****************\n\\ *P Configuration is managed by the SAPI\n\ntarget\n\n[defined] IOProfiling? [if]\nvariable c_emit\nvariable c_type\nvariable c_type_chars\nvariable c_cr\nvariable c_key\n[then]\n\n\\ ********************\n\\ *S Serial primitives\n\\ ********************\ninternal\n\n\\ : +FaultConsole\t( -- ) ;\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\n\\ ** for more details.\n\ntarget\n\n\\ CODE (seremitfc)\t\\ char base --\n\\ This is a system call.\n\n: (seremit)\t\\ char base -- \n\\ *G Wrapped call that checks for throttling, and if so,\n\\ calls PAUSE to let another task run, or just does a WFI if no multitasker.\n\\ The only interesting thing is failure, or -1. That means retry.\n\t\\ 1 c_emit +! \n (seremitfc) if [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then] then \n\t;\n\n: (sertype) \\ caddr len base --\n\\ *G Transmit a string on the given UART.\n \\ 1 c_type +!\n \\ over c_type_chars +!\n \n -rot bounds\n ?do i c@ over (seremit) loop\n drop\n;\n\n: (sercr)\t\\ base --\n\\ *G Transmit a CR\/LF pair on the given UART.\n \\ 2 c_cr +!\n $0D over (seremit) $0A swap (seremit)\n;\n\n: (serkey) \\ base -- c\n\\ *G Get a character from the port. Retry until we get it.\n\\ The system call will stop the task and restart it when there is data.\n\\ See if its negative. If so, discard it and leave false to re-loop.\n\\ If not negative, leave true on the stack to exit.\n begin \\ base ret t\/f \n\tdup (serkeyfc) dup 0 < \\ base ret t\/f \n\t \\ If we have been blocked, drop the useless returned data and try again.\n\t IF [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then] drop false \n\t ELSE true \\ Leave the return code intact.\n\t THEN \\ base ret t\/f \n\tuntil \\ base ret \n\tswap drop \n \\ 1 c_key +!\n;\n\n\\ THis is a system call.\n\\ CODE (serkey?) \\ base -- t\/f\n\\ *G Return true if the given UART has a character avilable to read.\n\nexternal \n\n: seremit0\t\\ char --\n\\ *G Transmit a character on UART0.\n 0 (seremit) ;\n: sertype0\t\\ c-addr len --\n\\ *G Transmit a string on UART0.\n 0 (sertype) ;\n: sercr0\t\\ --\n\\ *G Issue a CR\/LF pair to UART0.\n 0 (sercr) ;\n: serkey?0\t\\ -- flag\n\\ *G Return true if UART0 has a character available.\n 0 (serkey?) ;\n: serkey0\t\\ -- char\n\\ *G Wait for a character on UART0.\n 0 (serkey) ;\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\n\\ *G Generic I\/O device for UART0.\n ' serkey0 ,\t\t\\ -- char ; receive char\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\n ' seremit0 ,\t\t\\ -- char ; display char\n ' sertype0 ,\t\t\\ caddr len -- ; display string\n ' sercr0 ,\t\t\\ -- ; display new line\n\n\\ --------------------------------------------------------------------\n\\ Optional devices\n\\ --------------------------------------------------------------------\n[defined] useUART1? [if] useUART1? 1 = [if] \n: seremit1 #1 (seremit) ;\n: sertype1 #1 (sertype) ;\n: sercr1 #1 (sercr) ;\n: serkey?1 #1 (serkey?) ;\n: serkey1 #1 (serkey) ;\ncreate Console1 ' serkey1 , ' serkey?1 , ' seremit1 , ' sertype1 , ' sercr1 ,\t\n[then] [then]\n\n\\ --------------------------------------------------------------------\n\\ Non-UARTs.\n\\ --------------------------------------------------------------------\n[defined] useStream10? [if] useStream10? 1 = [if] \n: seremit10 #10 (seremit) ;\n: sertype10\t#10 (sertype) ;\n: sercr10\t#10 (sercr) ;\n: serkey?10\t#10 (serkey?) ;\n: serkey10\t#10 (serkey) ;\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\nconsole-port #10 = [if]\n console10 constant console\n[then]\n[then] [then]\n\n[defined] useStream11? [if] useStream11? 1 = [if] \n: seremit11 #11 (seremit) ;\n: sertype11\t#11 (sertype) ;\n: sercr11\t#11 (sercr) ;\n: serkey?11\t#11 (serkey?) ;\n: serkey11\t#11 (serkey) ;\ncreate Console11 ' serkey11 , ' serkey?11 , ' seremit11 , ' sertype11 , ' sercr11 ,\t\n[then] [then]\n\n\n\nconsole-port 0 = [if]\n console0 constant console\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\n\\ ** It may be changed by one of the phrases of the form:\n\\ *C dup opvec ! ipvec !\n\\ *C SetConsole\n[then]\n\n\n\\ ************************\n\\ *S System initialisation\n\\ ************************\n\n\\ This is a NOP in the SAPI environment\n: init-ser ;\t\\ --\n\\ *G Initialise all serial ports\n\n\\ ======\n\\ *> ###\n\\ ======\n\ndecimal\n","old_contents":"\\ serCM3_sapi_level1.fth - SAPI polled RX, polled TX, serial communication drivers\n\\ with support for blocking IO.\n\\ Written to run against the SockPuppet API.\n\n\\ Level 1 support. Requires TASKING. System calls request blocking.\n\\ KEY requires blocking, so that must be implemented here.\n\n\\ Copyright (c) 2017, Robert Sexton. All rights reserved.\n\\ Covered by the terms of the supplied Licence.txt file\n\nonly forth definitions\n\n\\ ==============\n\\ *T SAPI polled serial driver\n\\ ==============\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\n\\ ** using the internal UARTs via the SAPI call layer. This is \n\\ ** The simplest implementation level.\n\\ ** It doesn't use the CR or TYPE calls, but rather emulates them.\n\n\\ ****************\n\\ *S Configuration\n\\ ****************\n\\ *P Configuration is managed by the SAPI\n\ntarget\n\n[defined] IOProfiling? [if]\nvariable c_emit\nvariable c_type\nvariable c_type_chars\nvariable c_cr\nvariable c_key\n[then]\n\n\\ ********************\n\\ *S Serial primitives\n\\ ********************\ninternal\n\n\\ : +FaultConsole\t( -- ) ;\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\n\\ ** for more details.\n\ntarget\n\n\\ CODE (seremitfc)\t\\ char base --\n\\ This is a system call.\n\n: (seremit)\t\\ char base -- \n\\ *G Wrapped call that checks for throttling, and if so,\n\\ calls PAUSE to let another task run, or just does a WFI if no multitasker.\n\\ The only interesting thing is failure, or -1. That means retry.\n\t\\ 1 c_emit +! \n (seremitfc) if [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then] then \n\t;\n\n: (sertype) \\ caddr len base --\n\\ *G Transmit a string on the given UART.\n \\ 1 c_type +!\n \\ over c_type_chars +!\n \n -rot bounds\n ?do i c@ over (seremit) loop\n drop\n;\n\n: (sercr)\t\\ base --\n\\ *G Transmit a CR\/LF pair on the given UART.\n \\ 2 c_cr +!\n $0D over (seremit) $0A swap (seremit)\n;\n\n: (serkey) \\ base -- c\n\\ *G Get a character from the port. Retry until we get it.\n\\ The system call will stop the task and restart it when there is data.\n\\ See if its negative. If so, discard it and leave false to re-loop.\n\\ If not negative, leave true on the stack to exit.\n begin \\ base ret t\/f \n\tdup (serkeyfc) dup 0 < \\ base ret t\/f \n\t \\ If we have been blocked, drop the useless returned data and try again.\n\t IF [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then] drop false \n\t ELSE true \\ Leave the return code intact.\n\t THEN \\ base ret t\/f \n\tuntil \\ base ret \n\tswap drop \n \\ 1 c_key +!\n;\n\n\\ THis is a system call.\n\\ CODE (serkey?) \\ base -- t\/f\n\\ *G Return true if the given UART has a character avilable to read.\n\nexternal \n\n: seremit0\t\\ char --\n\\ *G Transmit a character on UART0.\n 0 (seremit) ;\n: sertype0\t\\ c-addr len --\n\\ *G Transmit a string on UART0.\n 0 (sertype) ;\n: sercr0\t\\ --\n\\ *G Issue a CR\/LF pair to UART0.\n 0 (sercr) ;\n: serkey?0\t\\ -- flag\n\\ *G Return true if UART0 has a character available.\n 0 (serkey?) ;\n: serkey0\t\\ -- char\n\\ *G Wait for a character on UART0.\n 0 (serkey) ;\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\n\\ *G Generic I\/O device for UART0.\n ' serkey0 ,\t\t\\ -- char ; receive char\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\n ' seremit0 ,\t\t\\ -- char ; display char\n ' sertype0 ,\t\t\\ caddr len -- ; display string\n ' sercr0 ,\t\t\\ -- ; display new line\n\n\\ --------------------------------------------------------------------\n\\ Optional devices\n\\ --------------------------------------------------------------------\n[defined] useUART1? [if] useUART1? 1 = [if] \n: seremit1 #1 (seremit) ;\n: sertype1 #1 (sertype) ;\n: sercr1 #1 (sercr) ;\n: serkey?1 #1 (serkey?) ;\n: serkey1 #1 (serkey) ;\ncreate Console1 ' serkey1 , ' serkey?1 , ' seremit1 , ' sertype1 , ' sercr1 ,\t\n[then] [then]\n\n\\ --------------------------------------------------------------------\n\\ Non-UARTs.\n\\ --------------------------------------------------------------------\n[defined] useStream10? [if] useStream10? 1 = [if] \n: seremit10 #10 (seremit) ;\n: sertype10\t#10 (sertype) ;\n: sercr10\t#10 (sercr) ;\n: serkey?10\t#10 (serkey?) ;\n: serkey10\t#10 (serkey) ;\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\n[then] [then]\n\n[defined] useStream11? [if] useStream11? 1 = [if] \n: seremit11 #11 (seremit) ;\n: sertype11\t#11 (sertype) ;\n: sercr11\t#11 (sercr) ;\n: serkey?11\t#11 (serkey?) ;\n: serkey11\t#11 (serkey) ;\ncreate Console11 ' serkey11 , ' serkey?11 , ' seremit11 , ' sertype11 , ' sercr11 ,\t\n[then] [then]\n\n\n\nconsole-port 0 = [if]\n console0 constant console\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\n\\ ** It may be changed by one of the phrases of the form:\n\\ *C dup opvec ! ipvec !\n\\ *C SetConsole\n[then]\n\nconsole-port #10 = [if]\n console10 constant console\n[then]\n\n\\ ************************\n\\ *S System initialisation\n\\ ************************\n\n\\ This is a NOP in the SAPI environment\n: init-ser ;\t\\ --\n\\ *G Initialise all serial ports\n\n\\ ======\n\\ *> ###\n\\ ======\n\ndecimal\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"6a9c4fa0c304b7dd8f73ffcdf49f9ad9b111b85c","subject":"comments added","message":"comments added\n","repos":"bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas","old_file":"KataDiversion.fth","new_file":"KataDiversion.fth","new_contents":"\\ KataDiversion in Forth\n\n\\ power\n: ** ( n1 n2 -- n1_pow_n2 ) 1 SWAP ?DUP IF 0 DO OVER * LOOP THEN NIP ;\n\n\\ test if the given N has two adjacent 1 bits\n\\ e.g. : 1011 -> -1\n\\ 1001 -> 0\n: ?TWO-ADJACENT-1-BITS ( n -- bool ) ( TODO ) ;\n\n\\ return the maximum number which can be made with N (given number) bits\n: ?MAX-NB ( n -- m ) DUP 2DUP ABS <> IF 0 NIP\n ELSE \n IF 2 SWAP ** NIP\n THEN\n THEN ;\n\n\\ return the number of numbers which can be made with N (given number) bits\n\\ or less, and which have not two adjacent 1 bits.\n\\ see http:\/\/www.codekata.com\/2007\/01\/code_kata_fifte.html\n: ?HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS ( n -- m ) ( TODO ) ;\n","old_contents":"\\ KataDiversion in Forth\n\n\\ power\n: ** ( n1 n2 -- n1_pow_n2 ) 1 SWAP ?DUP IF 0 DO OVER * LOOP THEN NIP ;\n\n\\ test if the given N has two adjacent 1 bits\n: ?TWO-ADJACENT-1-BITS ( n -- bool ) ;\n\n\\ return the maximum number which can be made with N (given) bits\n: ?MAX-NB ( n -- m ) DUP 2DUP ABS <> IF 0 NIP\n ELSE \n IF 2 SWAP ** NIP\n THEN\n THEN ;\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"31d0163dc56ccc5eee98d47944ddb1a1fb3c1add","subject":"NVRAM Code checks out.","message":"NVRAM Code checks out.","repos":"rbsexton\/gecko,rbsexton\/gecko,rbsexton\/gecko","old_file":"zero\/clock-umb\/forth\/Clock.fth","new_file":"zero\/clock-umb\/forth\/Clock.fth","new_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( -- )\n load-defaults \n icroot 0 over inter.rtcsem ! \\ Reset the free-running counters.\n 0 over inter.rtcdsem ! \\ Reset the free-running counters.\n\n begin \n \tdup inter.rtcsem @offex! ?dup if advancehms then\n \tdup inter.rtcdsem @offex! ?dup if advancedhms then\n [asm wfi asm]\n uiupdate if use-uivals else use-clockvals then \n key? until drop\n;\n \n\\ These two contain loops to ensure that we don't\n\\ drop any timer ticks on the floor.\n: ADVANCEHMS ( n -- ) 0 do hms advancetime loop ;\n: ADVANCEDHMS ( n -- ) 0 do dhms advancetime loop ;\n \n: LOAD-DEFAULTS ( -- )\n interp-init\n;\n\n\\ ----------------------------------------------------------\n\\ Define the structures before they get used.\n\\ ----------------------------------------------------------\nstruct ODN \\ On-Deck Needle \n\tint odn.s\n\tint odn.m\n\tint odn.h\nend-struct\n\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxsec \\ Max Value for secs+minutes\n\tint hms.maxhour \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_m \\ increment the minutes + hours\nend-struct\n\nstruct _interp_set\n\t4 cells field interp.a\n\t4 cells field interp.b\n\t4 cells field interp.c\nend-struct\n\n\\ ----------------------------------------------------------\n\\ Defaults get saved in the user data page.\n\\ ----------------------------------------------------------\n: NVRAMVALID? ( addr -- t\/f ) \n\\ *G See if there is valid data in the NVRAM.\n\\ ** It consists of 3 words. If any of them are \n\\ ** set to 0xffff:ffff, we go with the defaults.\n _USERDATA\n dup @ -1 <> \n over 4 + @ -1 <> and\n swap 8 + @ -1 <> and\n;\n\n: _NVRAMLOAD ( -- ) \n\\ *G Pull the needle maximums from flash.\n $C 0 do I ud@ needle_max I + ! 4 +loop \n; \n\n: NVRAM! ( -- )\n\\ *G Save the contents of the needle cal values.\n 0 UDPAGE_ERASE\n needle_max\n $C 0 do dup I + @ I ud! 4 +loop\n drop \n;\n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nidata\ncreate ODN_HMS odn allot \\ On-Deck, HMS\ncreate ODN_DHMS odn allot \\ On-Deck, DHMS\ncreate ODN_UI odn allot \\ On-Deck, Generated by the UI.\ncdata\n\nidata\ncreate NEEDLE_MAX #850 , #850 , #850 ,\ncdata\n\n\n: rangecheck ( max n -- n or zero ) dup >R <= if R> drop 0 else R> then ; \n\n: ++NEEDLE_S \\ Called every time.\n odn_hms odn.s \\ Stash this address for the moment. \n\n\tneedle_max odn.s @ \\ Get the max \n\tover w@ \\ Current value \n\n\tinterp_hms interp.a interp-next + \\ Returns a value.\n\t\n\t\\ If we've wrapped to zero, reset the interpolator \n\t\\ so that we don't accumulate errors during setting\/\n\t\\ calibration operations.\n rangecheck dup 0= if interp_hms interp.a interp-reset then \t\t\n\tswap w! \n\t;\n\n: ++NEEDLE_DS ; \\ Called every time.\n\n: ++NEEDLE_M ; \\ Every time we roll the seconds.\n: ++NEEDLE_DM ; \\ Every time we roll the seconds.\n\n: _USE ( odn-addr -- ) \n dup w@ pwm0!\n dup 2 + w@ pwm1!\n 4 + w@ pwm2!\n ;\n\n: USE-CLOCKVALS odn_hms _use ; \n: USE-UIVALS odn_ui _use ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Quadrature\n\\ ----------------------------------------------------------\n\n: QUAD@ ( addr -- n ) \\ Fetch and zero\n @off [asm sxth tos, tos asm] ;\n \n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_ds , ' ++needle_dm , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n: ADVANCETIME ( struct-addr -- )\n dup hms.w_s @ execute \\ Invoke the official update word.\n 1 over hms.subsec +! \\ Increment\n dup hms.subsec @\n over hms.maxsubsec @ < if drop exit then \\ If less then max, we're done\n 0 over hms.subsec ! \\ Reset the subsecs \n\n dup hms.w_m @ execute\n 1 over hms.s +!\n dup hms.s @ over hms.maxsec @ < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n 1 over hms.m +!\n dup hms.m @ over hms.maxsec @ < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ over hms.maxhour @ < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ----------------------------------------------------------\n\\ The interpolator. \n\\ Implement bresenhams algorithm. All of this code already\n\\ exists in C, but we'll own the data structures. They contain\n\\ A total of 4 words - fixed, err, num, & denom\n\\ ----------------------------------------------------------\nudata \ncreate interp_hms _interp_set allot\ncreate interp_dhms _interp_set allot \ncreate adj_list #50 cells allot \\ 100 16-bit words. \ncdata\n\n#16 #60 * equ raw_sec\n#10 #100 * equ raw_dsec\n\n: INTERP-INIT ( -- )\n (interp_init) interp_hms\n 2dup interp.a needle_max @ raw_sec call3-- \n 2dup interp.b needle_max 4 + @ #60 call3-- \n interp.c needle_max 8 + @ #12 call3--\n\n (interp_init) interp_dhms\n 2dup interp.a needle_max @ raw_dsec call3-- \n 2dup interp.b needle_max 4 + @ #100 call3-- \n interp.c needle_max 8 + @ #10 call3--\n;\n\n\\ Call the reset fn.\n: INTERP-RESET ( interp_addr -- )\n (interp_reset) swap call1-- \n;\n\n: INTERP-NEXT ( addr -- n )\n (interp_next) swap call1--n\n;\n\n\n\\ ============================ UNTESTED =======================\n\\ VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n\n\\ ----------------------------------------------------------\n\\ User Interface\n\\ ----------------------------------------------------------\nvariable uistate\nvariable uicount \n\n_GPIO $64 + equ _BUTTONIO\n: BUTTONUP? ( -- t\/f ) _buttonio @ 1 and ; \n: BUTTONDOWN? ( -- t\/f ) buttonup? 1 or ; \n\n\\ The wrapper for all of the UI stuff.\n\\ Returns true if the UI is active - ie, use the values generated by the UI.\n: UIUPDATE ( -- t\/f )\n StateHandlers uistate @ + @ execute \n; \n\n\\ -----------------------------------------------\n\\ State numbers. These are defined x4 so that\n\\ we can just use the state number as an index \n\\ into a table of words.\n\\ -----------------------------------------------\n0 4 * equ _s_init\n1 4 * equ _s_b1\n2 4 * equ _s_1sec\n3 4 * equ _s_seth\n4 4 * equ _s_pendset_m\n5 4 * equ _s_setmin\n6 4 * equ _s_pendcal0\n7 4 * equ _s_cal0\n8 4 * equ _s_pendcalh\n9 4 * equ _s_calh\n10 4 * equ _s_pendcalm\n11 4 * equ _s_calm\n12 4 * equ _s_pendcals\n13 4 * equ _s_cals\n\n\\ All of the state handlers.\n\\ Everybody needs to know the state of the button, so that must\n\\ get passed in, thus they all look like this:\n\\ state ( t\/f -- t\/f )\n: shInit false \n buttondown? if \n _s_b1 uistate !\n uicount off \\ Reset this.\n then\n ;\n\n\\ Waiting for a full second to go by.\n: shB1 false\n buttonup? if _s_init uistate ! exit then\n \\ The Button is down. \n uicount @ 16 > if\n _s_1sec uistate !\n else \n 1 uicount +!\n\tthen\n ;\n\n\\ We're in the 1 second state\n: sh1sec true \n buttonup? if _s_seth uistate ! true exit then\n uicount @ 48 > if\n _s_pendcal0 uistate !\n else \n 1 uicount +!\n\tthen \n;\n\n\\ -------------------------------------------------\n\\ Setting the time\n\\ -------------------------------------------------\n: shSetH true buttondown? if _s_pendset_m uistate ! exit then ;\n\n: shPendSetM true buttonup? if _s_setmin uistate ! then ;\n: shSetMin true buttondown? if _s_pendset_m uistate ! exit then ;\n\n\\ -------------------------------------------------\n\\ Calibration\n\\ -------------------------------------------------\n: shPendCal0 true buttonup? if _s_cal0 uistate ! then ;\n: shCal0 true buttondown? if _s_pendcalh uistate ! exit then ;\n\n: shPendCalH true buttonup? if _s_calh uistate ! then ; \n: shCalH true buttondown? if _s_pendcalm uistate ! exit then ; \n\n: shPendCalM true buttonup? if _s_calm uistate ! then ; \n: shCalM true buttondown? if _s_pendcals uistate ! exit then ; \n\n: shPendCalS true buttonup? if _s_calm uistate ! then ; \n: shCalS true buttondown? if _s_init uistate ! exit then ; \n\ncreate StateHandlers \n' shInit , \n' shB1 ,\n' sh1sec ,\n' shSetH ,\n' shPendSetM , ' shSetMin ,\n\n' shPendCal0 , ' shCal0 ,\n' shPendCalH , ' shCalH , \n' shPendCalM , ' shCalM , \n' shPendCalS , ' shCalS , \n\n","old_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( -- )\n load-defaults \n icroot 0 over inter.rtcsem ! \\ Reset the free-running counters.\n 0 over inter.rtcdsem ! \\ Reset the free-running counters.\n\n begin \n \tdup inter.rtcsem @offex! ?dup if advancehms then\n \tdup inter.rtcdsem @offex! ?dup if advancedhms then\n [asm wfi asm]\n uiupdate if use-uivals else use-clockvals then \n key? until drop\n;\n \n\\ These two contain loops to ensure that we don't\n\\ drop any timer ticks on the floor.\n: ADVANCEHMS ( n -- ) 0 do hms advancetime loop ;\n: ADVANCEDHMS ( n -- ) 0 do dhms advancetime loop ;\n \n: LOAD-DEFAULTS ( -- )\n interp-init\n;\n\n\\ ----------------------------------------------------------\n\\ Define the structures before they get used.\n\\ ----------------------------------------------------------\nstruct ODN \\ On-Deck Needle \n\tint odn.s\n\tint odn.m\n\tint odn.h\nend-struct\n\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxsec \\ Max Value for secs+minutes\n\tint hms.maxhour \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_m \\ increment the minutes + hours\nend-struct\n\nstruct _interp_set\n\t4 cells field interp.a\n\t4 cells field interp.b\n\t4 cells field interp.c\nend-struct\n\n\\ ----------------------------------------------------------\n\\ Defaults get saved in the user data page.\n\\ ----------------------------------------------------------\n\n: NVRAMVALID? ( addr -- t\/f ) \n\\ *G See if there is valid data in the NVRAM.\n\\ ** It consists of 3 words. If any of them are \n\\ ** set to 0xffff:ffff, we go with the defaults.\n dup @ -1 = \n over 4 + @ -1 = or\n swap 8 + @ -1 = or \n;\n\n: NVRAMLOAD ( addr -- ) $C 0 do dup I + @ needle_max I + ! 4 + loop ; \n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nidata\ncreate ODN_HMS odn allot \\ On-Deck, HMS\ncreate ODN_DHMS odn allot \\ On-Deck, DHMS\ncreate ODN_UI odn allot \\ On-Deck, Generated by the UI.\ncdata\n\nidata\ncreate NEEDLE_MAX #850 , #850 , #850 ,\ncdata\n\n\n: rangecheck ( max n -- n or zero ) dup >R <= if R> drop 0 else R> then ; \n\n: ++NEEDLE_S \\ Called every time.\n odn_hms odn.s \\ Stash this address for the moment. \n\n\tneedle_max odn.s @ \\ Get the max \n\tover w@ \\ Current value \n\n\tinterp_hms interp.a interp-next + \\ Returns a value.\n\t\n\t\\ If we've wrapped to zero, reset the interpolator \n\t\\ so that we don't accumulate errors during setting\/\n\t\\ calibration operations.\n rangecheck dup 0= if interp_hms interp.a interp-reset then \t\t\n\tswap w! \n\t;\n\n: ++NEEDLE_DS ; \\ Called every time.\n\n: ++NEEDLE_M ; \\ Every time we roll the seconds.\n: ++NEEDLE_DM ; \\ Every time we roll the seconds.\n\n: _USE ( odn-addr -- ) \n dup w@ pwm0!\n dup 2 + w@ pwm1!\n 4 + w@ pwm2!\n ;\n\n: USE-CLOCKVALS odn_hms _use ; \n: USE-UIVALS odn_ui _use ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Quadrature\n\\ ----------------------------------------------------------\n\n: QUAD@ ( addr -- n ) \\ Fetch and zero\n @off [asm sxth tos, tos asm] ;\n \n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_ds , ' ++needle_dm , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n: ADVANCETIME ( struct-addr -- )\n dup hms.w_s @ execute \\ Invoke the official update word.\n 1 over hms.subsec +! \\ Increment\n dup hms.subsec @\n over hms.maxsubsec @ < if drop exit then \\ If less then max, we're done\n 0 over hms.subsec ! \\ Reset the subsecs \n\n dup hms.w_m @ execute\n 1 over hms.s +!\n dup hms.s @ over hms.maxsec @ < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n 1 over hms.m +!\n dup hms.m @ over hms.maxsec @ < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ over hms.maxhour @ < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ----------------------------------------------------------\n\\ The interpolator. \n\\ Implement bresenhams algorithm. All of this code already\n\\ exists in C, but we'll own the data structures. They contain\n\\ A total of 4 words - fixed, err, num, & denom\n\\ ----------------------------------------------------------\nudata \ncreate interp_hms _interp_set allot\ncreate interp_dhms _interp_set allot \ncreate adj_list #50 cells allot \\ 100 16-bit words. \ncdata\n\n#16 #60 * equ raw_sec\n#10 #100 * equ raw_dsec\n\n: INTERP-INIT ( -- )\n (interp_init) interp_hms\n 2dup interp.a needle_max @ raw_sec call3-- \n 2dup interp.b needle_max 4 + @ #60 call3-- \n interp.c needle_max 8 + @ #12 call3--\n\n (interp_init) interp_dhms\n 2dup interp.a needle_max @ raw_dsec call3-- \n 2dup interp.b needle_max 4 + @ #100 call3-- \n interp.c needle_max 8 + @ #10 call3--\n;\n\n\\ Call the reset fn.\n: INTERP-RESET ( interp_addr -- )\n (interp_reset) swap call1-- \n;\n\n: INTERP-NEXT ( addr -- n )\n (interp_next) swap call1--n\n;\n\n\n\\ ============================ UNTESTED =======================\n\\ VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n\n\\ ----------------------------------------------------------\n\\ User Interface\n\\ ----------------------------------------------------------\nvariable uistate\nvariable uicount \n\n_GPIO $64 + equ _BUTTONIO\n: BUTTONUP? ( -- t\/f ) _buttonio @ 1 and ; \n: BUTTONDOWN? ( -- t\/f ) buttonup? 1 or ; \n\n\\ The wrapper for all of the UI stuff.\n\\ Returns true if the UI is active - ie, use the values generated by the UI.\n: UIUPDATE ( -- t\/f )\n StateHandlers uistate @ + @ execute \n; \n\n\\ -----------------------------------------------\n\\ State numbers. These are defined x4 so that\n\\ we can just use the state number as an index \n\\ into a table of words.\n\\ -----------------------------------------------\n0 4 * equ _s_init\n1 4 * equ _s_b1\n2 4 * equ _s_1sec\n3 4 * equ _s_seth\n4 4 * equ _s_pendset_m\n5 4 * equ _s_setmin\n6 4 * equ _s_pendcal0\n7 4 * equ _s_cal0\n8 4 * equ _s_pendcalh\n9 4 * equ _s_calh\n10 4 * equ _s_pendcalm\n11 4 * equ _s_calm\n12 4 * equ _s_pendcals\n13 4 * equ _s_cals\n\n\\ All of the state handlers.\n\\ Everybody needs to know the state of the button, so that must\n\\ get passed in, thus they all look like this:\n\\ state ( t\/f -- t\/f )\n: shInit false \n buttondown? if \n _s_b1 uistate !\n uicount off \\ Reset this.\n then\n ;\n\n\\ Waiting for a full second to go by.\n: shB1 false\n buttonup? if _s_init uistate ! exit then\n \\ The Button is down. \n uicount @ 16 > if\n _s_1sec uistate !\n else \n 1 uicount +!\n\tthen\n ;\n\n\\ We're in the 1 second state\n: sh1sec true \n buttonup? if _s_seth uistate ! true exit then\n uicount @ 48 > if\n _s_pendcal0 uistate !\n else \n 1 uicount +!\n\tthen \n;\n\n\\ -------------------------------------------------\n\\ Setting the time\n\\ -------------------------------------------------\n: shSetH true buttondown? if _s_pendset_m uistate ! exit then ;\n\n: shPendSetM true buttonup? if _s_setmin uistate ! then ;\n: shSetMin true buttondown? if _s_pendset_m uistate ! exit then ;\n\n\\ -------------------------------------------------\n\\ Calibration\n\\ -------------------------------------------------\n: shPendCal0 true buttonup? if _s_cal0 uistate ! then ;\n: shCal0 true buttondown? if _s_pendcalh uistate ! exit then ;\n\n: shPendCalH true buttonup? if _s_calh uistate ! then ; \n: shCalH true buttondown? if _s_pendcalm uistate ! exit then ; \n\n: shPendCalM true buttonup? if _s_calm uistate ! then ; \n: shCalM true buttondown? if _s_pendcals uistate ! exit then ; \n\n: shPendCalS true buttonup? if _s_calm uistate ! then ; \n: shCalS true buttondown? if _s_init uistate ! exit then ; \n\ncreate StateHandlers \n' shInit , \n' shB1 ,\n' sh1sec ,\n' shSetH ,\n' shPendSetM , ' shSetMin ,\n\n' shPendCal0 , ' shCal0 ,\n' shPendCalH , ' shCalH , \n' shPendCalM , ' shCalM , \n' shPendCalS , ' shCalS , \n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"2160ff58527c3253bc5fe11f85c2e3d0fa680688","subject":"Add support for comma-separated values (whitespace-separated still supported).","message":"Add support for comma-separated values (whitespace-separated still supported).\n\nPR:\t\tconf\/121064\nSubmitted by:\tkoitsu\nReviewed by:\tjh\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/support.4th","new_file":"sys\/boot\/forth\/support.4th","new_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\ \n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\n\\ Loader.rc support functions:\n\\\n\\ initialize ( addr len -- )\tas above, plus load_conf_files\n\\ load_conf ( addr len -- )\tload conf file given\n\\ include_conf_files ( -- )\tload all conf files in load_conf_files\n\\ print_syntax_error ( -- )\tprint line and marker of where a syntax\n\\\t\t\t\terror was detected\n\\ print_line ( -- )\t\tprint last line processed\n\\ load_kernel ( -- )\t\tload kernel\n\\ load_modules ( -- )\t\tload modules flagged\n\\\n\\ Exported structures:\n\\\n\\ string\t\t\tcounted string structure\n\\\tcell .addr\t\t\tstring address\n\\\tcell .len\t\t\tstring length\n\\ module\t\t\tmodule loading information structure\n\\\tcell module.flag\t\tshould we load it?\n\\\tstring module.name\t\tmodule's name\n\\\tstring module.loadname\t\tname to be used in loading the module\n\\\tstring module.type\t\tmodule's type\n\\\tstring module.args\t\tflags to be passed during load\n\\\tstring module.beforeload\tcommand to be executed before load\n\\\tstring module.afterload\t\tcommand to be executed after load\n\\\tstring module.loaderror\t\tcommand to be executed if load fails\n\\\tcell module.next\t\tlist chain\n\\\n\\ Exported global variables;\n\\\n\\ string conf_files\t\tconfiguration files to be loaded\n\\ cell modules_options\t\tpointer to first module information\n\\ value verbose?\t\tindicates if user wants a verbose loading\n\\ value any_conf_read?\t\tindicates if a conf file was succesfully read\n\\\n\\ Other exported words:\n\\ note, strlen is internal\n\\ strdup ( addr len -- addr' len)\t\t\tsimilar to strdup(3)\n\\ strcat ( addr len addr' len' -- addr len+len' )\tsimilar to strcat(3)\n\\ s' ( | string' -- addr len | )\t\t\tsimilar to s\"\n\\ rudimentary structure support\n\n\\ Exception values\n\n1 constant ESYNTAX\n2 constant ENOMEM\n3 constant EFREE\n4 constant ESETERROR\t\\ error setting environment variable\n5 constant EREAD\t\\ error reading\n6 constant EOPEN\n7 constant EEXEC\t\\ XXX never catched\n8 constant EBEFORELOAD\n9 constant EAFTERLOAD\n\n\\ I\/O constants\n\n0 constant SEEK_SET\n1 constant SEEK_CUR\n2 constant SEEK_END\n\n0 constant O_RDONLY\n1 constant O_WRONLY\n2 constant O_RDWR\n\n\\ Crude structure support\n\n: structure:\n create here 0 , ['] drop , 0\n does> create here swap dup @ allot cell+ @ execute\n;\n: member: create dup , over , + does> cell+ @ + ;\n: ;structure swap ! ;\n: constructor! >body cell+ ! ;\n: constructor: over :noname ;\n: ;constructor postpone ; swap cell+ ! ; immediate\n: sizeof ' >body @ state @ if postpone literal then ; immediate\n: offsetof ' >body cell+ @ state @ if postpone literal then ; immediate\n: ptr 1 cells member: ;\n: int 1 cells member: ;\n\n\\ String structure\n\nstructure: string\n\tptr .addr\n\tint .len\n\tconstructor:\n\t 0 over .addr !\n\t 0 swap .len !\n\t;constructor\n;structure\n\n\n\\ Module options linked list\n\nstructure: module\n\tint module.flag\n\tsizeof string member: module.name\n\tsizeof string member: module.loadname\n\tsizeof string member: module.type\n\tsizeof string member: module.args\n\tsizeof string member: module.beforeload\n\tsizeof string member: module.afterload\n\tsizeof string member: module.loaderror\n\tptr module.next\n;structure\n\n\\ Internal loader structures (preloaded_file, kernel_module, file_metadata)\n\\ must be in sync with the C struct in sys\/boot\/common\/bootstrap.h\nstructure: preloaded_file\n\tptr pf.name\n\tptr pf.type\n\tptr pf.args\n\tptr pf.metadata\t\\ file_metadata\n\tint pf.loader\n\tint pf.addr\n\tint pf.size\n\tptr pf.modules\t\\ kernel_module\n\tptr pf.next\t\\ preloaded_file\n;structure\n\nstructure: kernel_module\n\tptr km.name\n\t\\ ptr km.args\n\tptr km.fp\t\\ preloaded_file\n\tptr km.next\t\\ kernel_module\n;structure\n\nstructure: file_metadata\n\tint\t\tmd.size\n\t2 member:\tmd.type\t\\ this is not ANS Forth compatible (XXX)\n\tptr\t\tmd.next\t\\ file_metadata\n\t0 member:\tmd.data\t\\ variable size\n;structure\n\n\\ end of structures\n\n\\ Global variables\n\nstring conf_files\nstring nextboot_conf_file\ncreate module_options sizeof module.next allot 0 module_options !\ncreate last_module_option sizeof module.next allot 0 last_module_option !\n0 value verbose?\n0 value nextboot?\n\n\\ Support string functions\n: strdup { addr len -- addr' len' }\n len allocate if ENOMEM throw then\n addr over len move len\n;\n\n: strcat { addr len addr' len' -- addr len+len' }\n addr' addr len + len' move\n addr len len' +\n;\n\n: strchr { addr len c -- addr' len' }\n begin\n len\n while\n addr c@ c = if addr len exit then\n addr 1 + to addr\n len 1 - to len\n repeat\n 0 0\n;\n\n: s' \\ same as s\", allows \" in the string\n [char] ' parse\n state @ if postpone sliteral then\n; immediate\n\n: 2>r postpone >r postpone >r ; immediate\n: 2r> postpone r> postpone r> ; immediate\n: 2r@ postpone 2r> postpone 2dup postpone 2>r ; immediate\n\n: getenv? getenv -1 = if false else drop true then ;\n\n\\ determine if a word appears in a string, case-insensitive\n: contains? ( addr1 len1 addr2 len2 -- 0 | -1 )\n\t2 pick 0= if 2drop 2drop true exit then\n\tdup 0= if 2drop 2drop false exit then\n\tbegin\n\t\tbegin\n\t\t\tswap dup c@ dup 32 = over 9 = or over 10 = or\n\t\t\tover 13 = or over 44 = or swap drop\n\t\twhile 1+ swap 1- repeat\n\t\tswap 2 pick 1- over <\n\twhile\n\t\t2over 2over drop over compare-insensitive 0= if\n\t\t\t2 pick over = if 2drop 2drop true exit then\n\t\t\t2 pick tuck - -rot + swap over c@ dup 32 =\n\t\t\tover 9 = or over 10 = or over 13 = or over 44 = or\n\t\t\tswap drop if 2drop 2drop true exit then\n\t\tthen begin\n\t\t\tswap dup c@ dup 32 = over 9 = or over 10 = or\n\t\t\tover 13 = or over 44 = or swap drop\n\t\t\tif false else true then 2 pick 0> and\n\t\twhile 1+ swap 1- repeat\n\t\tswap\n\trepeat\n\t2drop 2drop false\n;\n\n: boot_serial? ( -- 0 | -1 )\n\ts\" console\" getenv dup -1 <> if\n\t\ts\" comconsole\" 2swap contains?\n\telse drop false then\n\ts\" boot_serial\" getenv dup -1 <> if\n\t\tswap drop 0>\n\telse drop false then\n\tor \\ console contains comconsole ( or ) boot_serial\n\ts\" boot_multicons\" getenv dup -1 <> if\n\t\tswap drop 0>\n\telse drop false then\n\tor \\ previous boolean ( or ) boot_multicons\n;\n\n\\ Private definitions\n\nvocabulary support-functions\nonly forth also support-functions definitions\n\n\\ Some control characters constants\n\n7 constant bell\n8 constant backspace\n9 constant tab\n10 constant lf\n13 constant \n\n\\ Read buffer size\n\n80 constant read_buffer_size\n\n\\ Standard suffixes\n\n: load_module_suffix\t\ts\" _load\" ;\n: module_loadname_suffix\ts\" _name\" ;\n: module_type_suffix\t\ts\" _type\" ;\n: module_args_suffix\t\ts\" _flags\" ;\n: module_beforeload_suffix\ts\" _before\" ;\n: module_afterload_suffix\ts\" _after\" ;\n: module_loaderror_suffix\ts\" _error\" ;\n\n\\ Support operators\n\n: >= < 0= ;\n: <= > 0= ;\n\n\\ Assorted support functions\n\n: free-memory free if EFREE throw then ;\n\n: strget { var -- addr len } var .addr @ var .len @ ;\n\n\\ assign addr len to variable.\n: strset { addr len var -- } addr var .addr ! len var .len ! ;\n\n\\ free memory and reset fields\n: strfree { var -- } var .addr @ ?dup if free-memory 0 0 var strset then ;\n\n\\ free old content, make a copy of the string and assign to variable\n: string= { addr len var -- } var strfree addr len strdup var strset ;\n\n: strtype ( str -- ) strget type ;\n\n\\ assign a reference to what is on the stack\n: strref { addr len var -- addr len }\n addr var .addr ! len var .len ! addr len\n;\n\n\\ unquote a string\n: unquote ( addr len -- addr len )\n over c@ [char] \" = if 2 chars - swap char+ swap then\n;\n\n\\ Assignment data temporary storage\n\nstring name_buffer\nstring value_buffer\n\n\\ Line by line file reading functions\n\\\n\\ exported:\n\\\tline_buffer\n\\\tend_of_file?\n\\\tfd\n\\\tread_line\n\\\treset_line_reading\n\nvocabulary line-reading\nalso line-reading definitions also\n\n\\ File data temporary storage\n\nstring read_buffer\n0 value read_buffer_ptr\n\n\\ File's line reading function\n\nsupport-functions definitions\n\nstring line_buffer\n0 value end_of_file?\nvariable fd\n\nline-reading definitions\n\n: skip_newlines\n begin\n read_buffer .len @ read_buffer_ptr >\n while\n read_buffer .addr @ read_buffer_ptr + c@ lf = if\n read_buffer_ptr char+ to read_buffer_ptr\n else\n exit\n then\n repeat\n;\n\n: scan_buffer ( -- addr len )\n read_buffer_ptr >r\n begin\n read_buffer .len @ r@ >\n while\n read_buffer .addr @ r@ + c@ lf = if\n read_buffer .addr @ read_buffer_ptr + ( -- addr )\n r@ read_buffer_ptr - ( -- len )\n r> to read_buffer_ptr\n exit\n then\n r> char+ >r\n repeat\n read_buffer .addr @ read_buffer_ptr + ( -- addr )\n r@ read_buffer_ptr - ( -- len )\n r> to read_buffer_ptr\n;\n\n: line_buffer_resize ( len -- len )\n >r\n line_buffer .len @ if\n line_buffer .addr @\n line_buffer .len @ r@ +\n resize if ENOMEM throw then\n else\n r@ allocate if ENOMEM throw then\n then\n line_buffer .addr !\n r>\n;\n \n: append_to_line_buffer ( addr len -- )\n line_buffer strget\n 2swap strcat\n line_buffer .len !\n drop\n;\n\n: read_from_buffer\n scan_buffer ( -- addr len )\n line_buffer_resize ( len -- len )\n append_to_line_buffer ( addr len -- )\n;\n\n: refill_required?\n read_buffer .len @ read_buffer_ptr =\n end_of_file? 0= and\n;\n\n: refill_buffer\n 0 to read_buffer_ptr\n read_buffer .addr @ 0= if\n read_buffer_size allocate if ENOMEM throw then\n read_buffer .addr !\n then\n fd @ read_buffer .addr @ read_buffer_size fread\n dup -1 = if EREAD throw then\n dup 0= if true to end_of_file? then\n read_buffer .len !\n;\n\nsupport-functions definitions\n\n: reset_line_reading\n 0 to read_buffer_ptr\n;\n\n: read_line\n line_buffer strfree\n skip_newlines\n begin\n read_from_buffer\n refill_required?\n while\n refill_buffer\n repeat\n;\n\nonly forth also support-functions definitions\n\n\\ Conf file line parser:\n\\ ::= '='[] |\n\\ []\n\\ ::= {||'_'}\n\\ ::= '\"'{|'\\'}'\"' | \n\\ ::= ASCII 32 to 126, except '\\' and '\"'\n\\ ::= '#'{}\n\\\n\\ exported:\n\\\tline_pointer\n\\\tprocess_conf\n\n0 value line_pointer\n\nvocabulary file-processing\nalso file-processing definitions\n\n\\ parser functions\n\\\n\\ exported:\n\\\tget_assignment\n\nvocabulary parser\nalso parser definitions also\n\n0 value parsing_function\n0 value end_of_line\n\n: end_of_line? line_pointer end_of_line = ;\n\n\\ classifiers for various character classes in the input line\n\n: letter?\n line_pointer c@ >r\n r@ [char] A >=\n r@ [char] Z <= and\n r@ [char] a >=\n r> [char] z <= and\n or\n;\n\n: digit?\n line_pointer c@ >r\n r@ [char] - =\n r@ [char] 0 >=\n r> [char] 9 <= and\n or\n;\n\n: quote? line_pointer c@ [char] \" = ;\n\n: assignment_sign? line_pointer c@ [char] = = ;\n\n: comment? line_pointer c@ [char] # = ;\n\n: space? line_pointer c@ bl = line_pointer c@ tab = or ;\n\n: backslash? line_pointer c@ [char] \\ = ;\n\n: underscore? line_pointer c@ [char] _ = ;\n\n: dot? line_pointer c@ [char] . = ;\n\n\\ manipulation of input line\n: skip_character line_pointer char+ to line_pointer ;\n\n: skip_to_end_of_line end_of_line to line_pointer ;\n\n: eat_space\n begin\n end_of_line? if 0 else space? then\n while\n skip_character\n repeat\n;\n\n: parse_name ( -- addr len )\n line_pointer\n begin\n end_of_line? if 0 else letter? digit? underscore? dot? or or or then\n while\n skip_character\n repeat\n line_pointer over -\n strdup\n;\n\n: remove_backslashes { addr len | addr' len' -- addr' len' }\n len allocate if ENOMEM throw then\n to addr'\n addr >r\n begin\n addr c@ [char] \\ <> if\n addr c@ addr' len' + c!\n len' char+ to len'\n then\n addr char+ to addr\n r@ len + addr =\n until\n r> drop\n addr' len'\n;\n\n: parse_quote ( -- addr len )\n line_pointer\n skip_character\n end_of_line? if ESYNTAX throw then\n begin\n quote? 0=\n while\n backslash? if\n skip_character\n end_of_line? if ESYNTAX throw then\n then\n skip_character\n end_of_line? if ESYNTAX throw then \n repeat\n skip_character\n line_pointer over -\n remove_backslashes\n;\n\n: read_name\n parse_name\t\t( -- addr len )\n name_buffer strset\n;\n\n: read_value\n quote? if\n parse_quote\t\t( -- addr len )\n else\n parse_name\t\t( -- addr len )\n then\n value_buffer strset\n;\n\n: comment\n skip_to_end_of_line\n;\n\n: white_space_4\n eat_space\n comment? if ['] comment to parsing_function exit then\n end_of_line? 0= if ESYNTAX throw then\n;\n\n: variable_value\n read_value\n ['] white_space_4 to parsing_function\n;\n\n: white_space_3\n eat_space\n letter? digit? quote? or or if\n ['] variable_value to parsing_function exit\n then\n ESYNTAX throw\n;\n\n: assignment_sign\n skip_character\n ['] white_space_3 to parsing_function\n;\n\n: white_space_2\n eat_space\n assignment_sign? if ['] assignment_sign to parsing_function exit then\n ESYNTAX throw\n;\n\n: variable_name\n read_name\n ['] white_space_2 to parsing_function\n;\n\n: white_space_1\n eat_space\n letter? if ['] variable_name to parsing_function exit then\n comment? if ['] comment to parsing_function exit then\n end_of_line? 0= if ESYNTAX throw then\n;\n\nfile-processing definitions\n\n: get_assignment\n line_buffer strget + to end_of_line\n line_buffer .addr @ to line_pointer\n ['] white_space_1 to parsing_function\n begin\n end_of_line? 0=\n while\n parsing_function execute\n repeat\n parsing_function ['] comment =\n parsing_function ['] white_space_1 =\n parsing_function ['] white_space_4 =\n or or 0= if ESYNTAX throw then\n;\n\nonly forth also support-functions also file-processing definitions also\n\n\\ Process line\n\n: assignment_type? ( addr len -- flag )\n name_buffer strget\n compare 0=\n;\n\n: suffix_type? ( addr len -- flag )\n name_buffer .len @ over <= if 2drop false exit then\n name_buffer .len @ over - name_buffer .addr @ +\n over compare 0=\n;\n\n: loader_conf_files? s\" loader_conf_files\" assignment_type? ;\n\n: nextboot_flag? s\" nextboot_enable\" assignment_type? ;\n\n: nextboot_conf? s\" nextboot_conf\" assignment_type? ;\n\n: verbose_flag? s\" verbose_loading\" assignment_type? ;\n\n: execute? s\" exec\" assignment_type? ;\n\n: module_load? load_module_suffix suffix_type? ;\n\n: module_loadname? module_loadname_suffix suffix_type? ;\n\n: module_type? module_type_suffix suffix_type? ;\n\n: module_args? module_args_suffix suffix_type? ;\n\n: module_beforeload? module_beforeload_suffix suffix_type? ;\n\n: module_afterload? module_afterload_suffix suffix_type? ;\n\n: module_loaderror? module_loaderror_suffix suffix_type? ;\n\n\\ build a 'set' statement and execute it\n: set_environment_variable\n name_buffer .len @ value_buffer .len @ + 5 chars + \\ size of result string\n allocate if ENOMEM throw then\n dup 0 \\ start with an empty string and append the pieces\n s\" set \" strcat\n name_buffer strget strcat\n s\" =\" strcat\n value_buffer strget strcat\n ['] evaluate catch if\n 2drop free drop\n ESETERROR throw\n else\n free-memory\n then\n;\n\n: set_conf_files\n set_environment_variable\n s\" loader_conf_files\" getenv conf_files string=\n;\n\n: set_nextboot_conf \\ XXX maybe do as set_conf_files ?\n value_buffer strget unquote nextboot_conf_file string=\n;\n\n: append_to_module_options_list ( addr -- )\n module_options @ 0= if\n dup module_options !\n last_module_option !\n else\n dup last_module_option @ module.next !\n last_module_option !\n then\n;\n\n: set_module_name { addr -- }\t\\ check leaks\n name_buffer strget addr module.name string=\n;\n\n: yes_value?\n value_buffer strget\t\\ XXX could use unquote\n 2dup s' \"YES\"' compare >r\n 2dup s' \"yes\"' compare >r\n 2dup s\" YES\" compare >r\n s\" yes\" compare r> r> r> and and and 0=\n;\n\n: find_module_option ( -- addr | 0 ) \\ return ptr to entry matching name_buffer\n module_options @\n begin\n dup\n while\n dup module.name strget\n name_buffer strget\n compare 0= if exit then\n module.next @\n repeat\n;\n\n: new_module_option ( -- addr )\n sizeof module allocate if ENOMEM throw then\n dup sizeof module erase\n dup append_to_module_options_list\n dup set_module_name\n;\n\n: get_module_option ( -- addr )\n find_module_option\n ?dup 0= if new_module_option then\n;\n\n: set_module_flag\n name_buffer .len @ load_module_suffix nip - name_buffer .len !\n yes_value? get_module_option module.flag !\n;\n\n: set_module_args\n name_buffer .len @ module_args_suffix nip - name_buffer .len !\n value_buffer strget unquote\n get_module_option module.args string=\n;\n\n: set_module_loadname\n name_buffer .len @ module_loadname_suffix nip - name_buffer .len !\n value_buffer strget unquote\n get_module_option module.loadname string=\n;\n\n: set_module_type\n name_buffer .len @ module_type_suffix nip - name_buffer .len !\n value_buffer strget unquote\n get_module_option module.type string=\n;\n\n: set_module_beforeload\n name_buffer .len @ module_beforeload_suffix nip - name_buffer .len !\n value_buffer strget unquote\n get_module_option module.beforeload string=\n;\n\n: set_module_afterload\n name_buffer .len @ module_afterload_suffix nip - name_buffer .len !\n value_buffer strget unquote\n get_module_option module.afterload string=\n;\n\n: set_module_loaderror\n name_buffer .len @ module_loaderror_suffix nip - name_buffer .len !\n value_buffer strget unquote\n get_module_option module.loaderror string=\n;\n\n: set_nextboot_flag\n yes_value? to nextboot?\n;\n\n: set_verbose\n yes_value? to verbose?\n;\n\n: execute_command\n value_buffer strget unquote\n ['] evaluate catch if EEXEC throw then\n;\n\n: process_assignment\n name_buffer .len @ 0= if exit then\n loader_conf_files?\tif set_conf_files exit then\n nextboot_flag?\tif set_nextboot_flag exit then\n nextboot_conf?\tif set_nextboot_conf exit then\n verbose_flag?\t\tif set_verbose exit then\n execute?\t\tif execute_command exit then\n module_load?\t\tif set_module_flag exit then\n module_loadname?\tif set_module_loadname exit then\n module_type?\t\tif set_module_type exit then\n module_args?\t\tif set_module_args exit then\n module_beforeload?\tif set_module_beforeload exit then\n module_afterload?\tif set_module_afterload exit then\n module_loaderror?\tif set_module_loaderror exit then\n set_environment_variable\n;\n\n\\ free_buffer ( -- )\n\\\n\\ Free some pointers if needed. The code then tests for errors\n\\ in freeing, and throws an exception if needed. If a pointer is\n\\ not allocated, it's value (0) is used as flag.\n\n: free_buffers\n name_buffer strfree\n value_buffer strfree\n;\n\n\\ Higher level file processing\n\nsupport-functions definitions\n\n: process_conf\n begin\n end_of_file? 0=\n while\n free_buffers\n read_line\n get_assignment\n ['] process_assignment catch\n ['] free_buffers catch\n swap throw throw\n repeat\n;\n\n: peek_file\n 0 to end_of_file?\n reset_line_reading\n O_RDONLY fopen fd !\n fd @ -1 = if EOPEN throw then\n free_buffers\n read_line\n get_assignment\n ['] process_assignment catch\n ['] free_buffers catch\n fd @ fclose\n;\n \nonly forth also support-functions definitions\n\n\\ Interface to loading conf files\n\n: load_conf ( addr len -- )\n \\ .\" ----- Trying conf \" 2dup type cr \\ debugging\n 0 to end_of_file?\n reset_line_reading\n O_RDONLY fopen fd !\n fd @ -1 = if EOPEN throw then\n ['] process_conf catch\n fd @ fclose\n throw\n;\n\n: print_line line_buffer strtype cr ;\n\n: print_syntax_error\n line_buffer strtype cr\n line_buffer .addr @\n begin\n line_pointer over <>\n while\n bl emit char+\n repeat\n drop\n .\" ^\" cr\n;\n\n\n\\ Debugging support functions\n\nonly forth definitions also support-functions\n\n: test-file \n ['] load_conf catch dup .\n ESYNTAX = if cr print_syntax_error then\n;\n\n\\ find a module name, leave addr on the stack (0 if not found)\n: find-module ( -- ptr | 0 )\n bl parse ( addr len )\n module_options @ >r ( store current pointer )\n begin\n r@\n while\n 2dup ( addr len addr len )\n r@ module.name strget\n compare 0= if drop drop r> exit then ( found it )\n r> module.next @ >r\n repeat\n type .\" was not found\" cr r>\n;\n\n: show-nonempty ( addr len mod -- )\n strget dup verbose? or if\n 2swap type type cr\n else\n drop drop drop drop\n then ;\n\n: show-one-module { addr -- addr }\n .\" Name: \" addr module.name strtype cr\n s\" Path: \" addr module.loadname show-nonempty\n s\" Type: \" addr module.type show-nonempty\n s\" Flags: \" addr module.args show-nonempty\n s\" Before load: \" addr module.beforeload show-nonempty\n s\" After load: \" addr module.afterload show-nonempty\n s\" Error: \" addr module.loaderror show-nonempty\n .\" Status: \" addr module.flag @ if .\" Load\" else .\" Don't load\" then cr\n cr\n addr\n;\n\n: show-module-options\n module_options @\n begin\n ?dup\n while\n show-one-module\n module.next @\n repeat\n;\n\nonly forth also support-functions definitions\n\n\\ Variables used for processing multiple conf files\n\nstring current_file_name_ref\t\\ used to print the file name\n\n\\ Indicates if any conf file was succesfully read\n\n0 value any_conf_read?\n\n\\ loader_conf_files processing support functions\n\n: get_conf_files ( -- addr len ) \\ put addr\/len on stack, reset var\n \\ .\" -- starting on <\" conf_files strtype .\" >\" cr \\ debugging\n conf_files strget 0 0 conf_files strset\n;\n\n: skip_leading_spaces { addr len pos -- addr len pos' }\n begin\n pos len = if 0 else addr pos + c@ bl = then\n while\n pos char+ to pos\n repeat\n addr len pos\n;\n\n\\ return the file name at pos, or free the string if nothing left\n: get_file_name { addr len pos -- addr len pos' addr' len' || 0 }\n pos len = if \n addr free abort\" Fatal error freeing memory\"\n 0 exit\n then\n pos >r\n begin\n \\ stay in the loop until have chars and they are not blank\n pos len = if 0 else addr pos + c@ bl <> then\n while\n pos char+ to pos\n repeat\n addr len pos addr r@ + pos r> -\n \\ 2dup .\" get_file_name has \" type cr \\ debugging\n;\n\n: get_next_file ( addr len ptr -- addr len ptr' addr' len' | 0 )\n skip_leading_spaces\n get_file_name\n;\n\n: print_current_file\n current_file_name_ref strtype\n;\n\n: process_conf_errors\n dup 0= if true to any_conf_read? drop exit then\n >r 2drop r>\n dup ESYNTAX = if\n .\" Warning: syntax error on file \" print_current_file cr\n print_syntax_error drop exit\n then\n dup ESETERROR = if\n .\" Warning: bad definition on file \" print_current_file cr\n print_line drop exit\n then\n dup EREAD = if\n .\" Warning: error reading file \" print_current_file cr drop exit\n then\n dup EOPEN = if\n verbose? if .\" Warning: unable to open file \" print_current_file cr then\n drop exit\n then\n dup EFREE = abort\" Fatal error freeing memory\"\n dup ENOMEM = abort\" Out of memory\"\n throw \\ Unknown error -- pass ahead\n;\n\n\\ Process loader_conf_files recursively\n\\ Interface to loader_conf_files processing\n\n: include_conf_files\n get_conf_files 0\t( addr len offset )\n begin\n get_next_file ?dup ( addr len 1 | 0 )\n while\n current_file_name_ref strref\n ['] load_conf catch\n process_conf_errors\n conf_files .addr @ if recurse then\n repeat\n;\n\n: get_nextboot_conf_file ( -- addr len )\n nextboot_conf_file strget strdup\t\\ XXX is the strdup a leak ?\n;\n\n: rewrite_nextboot_file ( -- )\n get_nextboot_conf_file\n O_WRONLY fopen fd !\n fd @ -1 = if EOPEN throw then\n fd @ s' nextboot_enable=\"NO\" ' fwrite\n fd @ fclose\n;\n\n: include_nextboot_file\n get_nextboot_conf_file\n ['] peek_file catch\n nextboot? if\n get_nextboot_conf_file\n ['] load_conf catch\n process_conf_errors\n ['] rewrite_nextboot_file catch\n then\n;\n\n\\ Module loading functions\n\n: load_parameters { addr -- addr addrN lenN ... addr1 len1 N }\n addr\n addr module.args strget\n addr module.loadname .len @ if\n addr module.loadname strget\n else\n addr module.name strget\n then\n addr module.type .len @ if\n addr module.type strget\n s\" -t \"\n 4 ( -t type name flags )\n else\n 2 ( name flags )\n then\n;\n\n: before_load ( addr -- addr )\n dup module.beforeload .len @ if\n dup module.beforeload strget\n ['] evaluate catch if EBEFORELOAD throw then\n then\n;\n\n: after_load ( addr -- addr )\n dup module.afterload .len @ if\n dup module.afterload strget\n ['] evaluate catch if EAFTERLOAD throw then\n then\n;\n\n: load_error ( addr -- addr )\n dup module.loaderror .len @ if\n dup module.loaderror strget\n evaluate \\ This we do not intercept so it can throw errors\n then\n;\n\n: pre_load_message ( addr -- addr )\n verbose? if\n dup module.name strtype\n .\" ...\"\n then\n;\n\n: load_error_message verbose? if .\" failed!\" cr then ;\n\n: load_succesful_message verbose? if .\" ok\" cr then ;\n\n: load_module\n load_parameters load\n;\n\n: process_module ( addr -- addr )\n pre_load_message\n before_load\n begin\n ['] load_module catch if\n dup module.loaderror .len @ if\n load_error\t\t\t\\ Command should return a flag!\n else \n load_error_message true\t\t\\ Do not retry\n then\n else\n after_load\n load_succesful_message true\t\\ Succesful, do not retry\n then\n until\n;\n\n: process_module_errors ( addr ior -- )\n dup EBEFORELOAD = if\n drop\n .\" Module \"\n dup module.name strtype\n dup module.loadname .len @ if\n .\" (\" dup module.loadname strtype .\" )\"\n then\n cr\n .\" Error executing \"\n dup module.beforeload strtype cr\t\\ XXX there was a typo here\n abort\n then\n\n dup EAFTERLOAD = if\n drop\n .\" Module \"\n dup module.name .addr @ over module.name .len @ type\n dup module.loadname .len @ if\n .\" (\" dup module.loadname strtype .\" )\"\n then\n cr\n .\" Error executing \"\n dup module.afterload strtype cr\n abort\n then\n\n throw \\ Don't know what it is all about -- pass ahead\n;\n\n\\ Module loading interface\n\n\\ scan the list of modules, load enabled ones.\n: load_modules ( -- ) ( throws: abort & user-defined )\n module_options @\t( list_head )\n begin\n ?dup\n while\n dup module.flag @ if\n ['] process_module catch\n process_module_errors\n then\n module.next @\n repeat\n;\n\n\\ h00h00 magic used to try loading either a kernel with a given name,\n\\ or a kernel with the default name in a directory of a given name\n\\ (the pain!)\n\n: bootpath s\" \/boot\/\" ;\n: modulepath s\" module_path\" ;\n\n\\ Functions used to save and restore module_path's value.\n: saveenv ( addr len | -1 -- addr' len | 0 -1 )\n dup -1 = if 0 swap exit then\n strdup\n;\n: freeenv ( addr len | 0 -1 )\n -1 = if drop else free abort\" Freeing error\" then\n;\n: restoreenv ( addr len | 0 -1 -- )\n dup -1 = if ( it wasn't set )\n 2drop\n modulepath unsetenv\n else\n over >r\n modulepath setenv\n r> free abort\" Freeing error\"\n then\n;\n\n: clip_args \\ Drop second string if only one argument is passed\n 1 = if\n 2swap 2drop\n 1\n else\n 2\n then\n;\n\nalso builtins\n\n\\ Parse filename from a semicolon-separated list\n\n\\ replacement, not working yet\n: newparse-; { addr len | a1 -- a' len-x addr x }\n addr len [char] ; strchr dup if\t( a1 len1 )\n swap to a1\t( store address )\n 1 - a1 @ 1 + swap ( remove match )\n addr a1 addr -\n else\n 0 0 addr len\n then\n;\n\n: parse-; ( addr len -- addr' len-x addr x )\n over 0 2swap\t\t\t( addr 0 addr len )\n begin\n dup 0 <>\t\t\t( addr 0 addr len )\n while\n over c@ [char] ; <>\t\t( addr 0 addr len flag )\n while\n 1- swap 1+ swap\n 2swap 1+ 2swap\n repeat then\n dup 0 <> if\n 1- swap 1+ swap\n then\n 2swap\n;\n\n\\ Try loading one of multiple kernels specified\n\n: try_multiple_kernels ( addr len addr' len' args -- flag )\n >r\n begin\n parse-; 2>r\n 2over 2r>\n r@ clip_args\n s\" DEBUG\" getenv? if\n s\" echo Module_path: ${module_path}\" evaluate\n .\" Kernel : \" >r 2dup type r> cr\n dup 2 = if .\" Flags : \" >r 2over type r> cr then\n then\n 1 load\n while\n dup 0=\n until\n 1 >r \\ Failure\n else\n 0 >r \\ Success\n then\n 2drop 2drop\n r>\n r> drop\n;\n\n\\ Try to load a kernel; the kernel name is taken from one of\n\\ the following lists, as ordered:\n\\\n\\ 1. The \"bootfile\" environment variable\n\\ 2. The \"kernel\" environment variable\n\\\n\\ Flags are passed, if available. If not, dummy values must be given.\n\\\n\\ The kernel gets loaded from the current module_path.\n\n: load_a_kernel ( flags len 1 | x x 0 -- flag )\n local args\n 2local flags\n 0 0 2local kernel\n end-locals\n\n \\ Check if a default kernel name exists at all, exits if not\n s\" bootfile\" getenv dup -1 <> if\n to kernel\n flags kernel args 1+ try_multiple_kernels\n dup 0= if exit then\n then\n drop\n\n s\" kernel\" getenv dup -1 <> if\n to kernel\n else\n drop\n 1 exit \\ Failure\n then\n\n \\ Try all default kernel names\n flags kernel args 1+ try_multiple_kernels\n;\n\n\\ Try to load a kernel; the kernel name is taken from one of\n\\ the following lists, as ordered:\n\\\n\\ 1. The \"bootfile\" environment variable\n\\ 2. The \"kernel\" environment variable\n\\\n\\ Flags are passed, if provided.\n\\\n\\ The kernel will be loaded from a directory computed from the\n\\ path given. Two directories will be tried in the following order:\n\\\n\\ 1. \/boot\/path\n\\ 2. path\n\\\n\\ The module_path variable is overridden if load is succesful, by\n\\ prepending the successful path.\n\n: load_from_directory ( path len 1 | flags len' path len 2 -- flag )\n local args\n 2local path\n args 1 = if 0 0 then\n 2local flags\n 0 0 2local oldmodulepath \\ like a string\n 0 0 2local newmodulepath \\ like a string\n end-locals\n\n \\ Set the environment variable module_path, and try loading\n \\ the kernel again.\n modulepath getenv saveenv to oldmodulepath\n\n \\ Try prepending \/boot\/ first\n bootpath nip path nip + \t\\ total length\n oldmodulepath nip dup -1 = if\n drop\n else\n 1+ +\t\t\t\\ add oldpath -- XXX why the 1+ ?\n then\n allocate if ( out of memory ) 1 exit then \\ XXX throw ?\n\n 0\n bootpath strcat\n path strcat\n 2dup to newmodulepath\n modulepath setenv\n\n \\ Try all default kernel names\n flags args 1- load_a_kernel\n 0= if ( success )\n oldmodulepath nip -1 <> if\n newmodulepath s\" ;\" strcat\n oldmodulepath strcat\n modulepath setenv\n newmodulepath drop free-memory\n oldmodulepath drop free-memory\n then\n 0 exit\n then\n\n \\ Well, try without the prepended \/boot\/\n path newmodulepath drop swap move\n newmodulepath drop path nip\n 2dup to newmodulepath\n modulepath setenv\n\n \\ Try all default kernel names\n flags args 1- load_a_kernel\n if ( failed once more )\n oldmodulepath restoreenv\n newmodulepath drop free-memory\n 1\n else\n oldmodulepath nip -1 <> if\n newmodulepath s\" ;\" strcat\n oldmodulepath strcat\n modulepath setenv\n newmodulepath drop free-memory\n oldmodulepath drop free-memory\n then\n 0\n then\n;\n\n\\ Try to load a kernel; the kernel name is taken from one of\n\\ the following lists, as ordered:\n\\\n\\ 1. The \"bootfile\" environment variable\n\\ 2. The \"kernel\" environment variable\n\\ 3. The \"path\" argument\n\\\n\\ Flags are passed, if provided.\n\\\n\\ The kernel will be loaded from a directory computed from the\n\\ path given. Two directories will be tried in the following order:\n\\\n\\ 1. \/boot\/path\n\\ 2. path\n\\\n\\ Unless \"path\" is meant to be kernel name itself. In that case, it\n\\ will first be tried as a full path, and, next, search on the\n\\ directories pointed by module_path.\n\\\n\\ The module_path variable is overridden if load is succesful, by\n\\ prepending the successful path.\n\n: load_directory_or_file ( path len 1 | flags len' path len 2 -- flag )\n local args\n 2local path\n args 1 = if 0 0 then\n 2local flags\n end-locals\n\n \\ First, assume path is an absolute path to a directory\n flags path args clip_args load_from_directory\n dup 0= if exit else drop then\n\n \\ Next, assume path points to the kernel\n flags path args try_multiple_kernels\n;\n\n: initialize ( addr len -- )\n strdup conf_files strset\n;\n\n: kernel_options ( -- addr len 1 | 0 )\n s\" kernel_options\" getenv\n dup -1 = if drop 0 else 1 then\n;\n\n: standard_kernel_search ( flags 1 | 0 -- flag )\n local args\n args 0= if 0 0 then\n 2local flags\n s\" kernel\" getenv\n dup -1 = if 0 swap then\n 2local path\n end-locals\n\n path nip -1 = if ( there isn't a \"kernel\" environment variable )\n flags args load_a_kernel\n else\n flags path args 1+ clip_args load_directory_or_file\n then\n;\n\n: load_kernel ( -- ) ( throws: abort )\n kernel_options standard_kernel_search\n abort\" Unable to load a kernel!\"\n;\n\n: set_defaultoptions ( -- )\n s\" kernel_options\" getenv dup -1 = if\n drop\n else\n s\" temp_options\" setenv\n then\n;\n\n\\ pick the i-th argument, i starts at 0\n: argv[] ( aN uN ... a1 u1 N i -- aN uN ... a1 u1 N ai+1 ui+1 )\n 2dup = if 0 0 exit then\t\\ out of range\n dup >r\n 1+ 2* ( skip N and ui )\n pick\n r>\n 1+ 2* ( skip N and ai )\n pick\n;\n\n: drop_args ( aN uN ... a1 u1 N -- )\n 0 ?do 2drop loop\n;\n\n: argc\n dup\n;\n\n: queue_argv ( aN uN ... a1 u1 N a u -- a u aN uN ... a1 u1 N+1 )\n >r\n over 2* 1+ -roll\n r>\n over 2* 1+ -roll\n 1+\n;\n\n: unqueue_argv ( aN uN ... a1 u1 N -- aN uN ... a2 u2 N-1 a1 u1 )\n 1- -rot\n;\n\n\\ compute the length of the buffer including the spaces between words\n: strlen(argv) ( aN uN .. a1 u1 N -- aN uN .. a1 u1 N len )\n dup 0= if 0 exit then\n 0 >r\t\\ Size\n 0 >r\t\\ Index\n begin\n argc r@ <>\n while\n r@ argv[]\n nip\n r> r> rot + 1+\n >r 1+ >r\n repeat\n r> drop\n r>\n;\n\n: concat_argv ( aN uN ... a1 u1 N -- a u )\n strlen(argv) allocate if ENOMEM throw then\n 0 2>r ( save addr 0 on return stack )\n\n begin\n dup\n while\n unqueue_argv ( ... N a1 u1 )\n 2r> 2swap\t ( old a1 u1 )\n strcat\n s\" \" strcat ( append one space ) \\ XXX this gives a trailing space\n 2>r\t\t( store string on the result stack )\n repeat\n drop_args\n 2r>\n;\n\n: set_tempoptions ( addrN lenN ... addr1 len1 N -- addr len 1 | 0 )\n \\ Save the first argument, if it exists and is not a flag\n argc if\n 0 argv[] drop c@ [char] - <> if\n unqueue_argv 2>r \\ Filename\n 1 >r\t\t\\ Filename present\n else\n 0 >r\t\t\\ Filename not present\n then\n else\n 0 >r\t\t\\ Filename not present\n then\n\n \\ If there are other arguments, assume they are flags\n ?dup if\n concat_argv\n 2dup s\" temp_options\" setenv\n drop free if EFREE throw then\n else\n set_defaultoptions\n then\n\n \\ Bring back the filename, if one was provided\n r> if 2r> 1 else 0 then\n;\n\n: get_arguments ( -- addrN lenN ... addr1 len1 N )\n 0\n begin\n \\ Get next word on the command line\n parse-word\n ?dup while\n queue_argv\n repeat\n drop ( empty string )\n;\n\n: load_kernel_and_modules ( args -- flag )\n set_tempoptions\n argc >r\n s\" temp_options\" getenv dup -1 <> if\n queue_argv\n else\n drop\n then\n r> if ( a path was passed )\n load_directory_or_file\n else\n standard_kernel_search\n then\n ?dup 0= if ['] load_modules catch then\n;\n\n\\ Go back to straight forth vocabulary\n\nonly forth also definitions\n\n","old_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\ \n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\n\\ Loader.rc support functions:\n\\\n\\ initialize ( addr len -- )\tas above, plus load_conf_files\n\\ load_conf ( addr len -- )\tload conf file given\n\\ include_conf_files ( -- )\tload all conf files in load_conf_files\n\\ print_syntax_error ( -- )\tprint line and marker of where a syntax\n\\\t\t\t\terror was detected\n\\ print_line ( -- )\t\tprint last line processed\n\\ load_kernel ( -- )\t\tload kernel\n\\ load_modules ( -- )\t\tload modules flagged\n\\\n\\ Exported structures:\n\\\n\\ string\t\t\tcounted string structure\n\\\tcell .addr\t\t\tstring address\n\\\tcell .len\t\t\tstring length\n\\ module\t\t\tmodule loading information structure\n\\\tcell module.flag\t\tshould we load it?\n\\\tstring module.name\t\tmodule's name\n\\\tstring module.loadname\t\tname to be used in loading the module\n\\\tstring module.type\t\tmodule's type\n\\\tstring module.args\t\tflags to be passed during load\n\\\tstring module.beforeload\tcommand to be executed before load\n\\\tstring module.afterload\t\tcommand to be executed after load\n\\\tstring module.loaderror\t\tcommand to be executed if load fails\n\\\tcell module.next\t\tlist chain\n\\\n\\ Exported global variables;\n\\\n\\ string conf_files\t\tconfiguration files to be loaded\n\\ cell modules_options\t\tpointer to first module information\n\\ value verbose?\t\tindicates if user wants a verbose loading\n\\ value any_conf_read?\t\tindicates if a conf file was succesfully read\n\\\n\\ Other exported words:\n\\ note, strlen is internal\n\\ strdup ( addr len -- addr' len)\t\t\tsimilar to strdup(3)\n\\ strcat ( addr len addr' len' -- addr len+len' )\tsimilar to strcat(3)\n\\ s' ( | string' -- addr len | )\t\t\tsimilar to s\"\n\\ rudimentary structure support\n\n\\ Exception values\n\n1 constant ESYNTAX\n2 constant ENOMEM\n3 constant EFREE\n4 constant ESETERROR\t\\ error setting environment variable\n5 constant EREAD\t\\ error reading\n6 constant EOPEN\n7 constant EEXEC\t\\ XXX never catched\n8 constant EBEFORELOAD\n9 constant EAFTERLOAD\n\n\\ I\/O constants\n\n0 constant SEEK_SET\n1 constant SEEK_CUR\n2 constant SEEK_END\n\n0 constant O_RDONLY\n1 constant O_WRONLY\n2 constant O_RDWR\n\n\\ Crude structure support\n\n: structure:\n create here 0 , ['] drop , 0\n does> create here swap dup @ allot cell+ @ execute\n;\n: member: create dup , over , + does> cell+ @ + ;\n: ;structure swap ! ;\n: constructor! >body cell+ ! ;\n: constructor: over :noname ;\n: ;constructor postpone ; swap cell+ ! ; immediate\n: sizeof ' >body @ state @ if postpone literal then ; immediate\n: offsetof ' >body cell+ @ state @ if postpone literal then ; immediate\n: ptr 1 cells member: ;\n: int 1 cells member: ;\n\n\\ String structure\n\nstructure: string\n\tptr .addr\n\tint .len\n\tconstructor:\n\t 0 over .addr !\n\t 0 swap .len !\n\t;constructor\n;structure\n\n\n\\ Module options linked list\n\nstructure: module\n\tint module.flag\n\tsizeof string member: module.name\n\tsizeof string member: module.loadname\n\tsizeof string member: module.type\n\tsizeof string member: module.args\n\tsizeof string member: module.beforeload\n\tsizeof string member: module.afterload\n\tsizeof string member: module.loaderror\n\tptr module.next\n;structure\n\n\\ Internal loader structures (preloaded_file, kernel_module, file_metadata)\n\\ must be in sync with the C struct in sys\/boot\/common\/bootstrap.h\nstructure: preloaded_file\n\tptr pf.name\n\tptr pf.type\n\tptr pf.args\n\tptr pf.metadata\t\\ file_metadata\n\tint pf.loader\n\tint pf.addr\n\tint pf.size\n\tptr pf.modules\t\\ kernel_module\n\tptr pf.next\t\\ preloaded_file\n;structure\n\nstructure: kernel_module\n\tptr km.name\n\t\\ ptr km.args\n\tptr km.fp\t\\ preloaded_file\n\tptr km.next\t\\ kernel_module\n;structure\n\nstructure: file_metadata\n\tint\t\tmd.size\n\t2 member:\tmd.type\t\\ this is not ANS Forth compatible (XXX)\n\tptr\t\tmd.next\t\\ file_metadata\n\t0 member:\tmd.data\t\\ variable size\n;structure\n\n\\ end of structures\n\n\\ Global variables\n\nstring conf_files\nstring nextboot_conf_file\ncreate module_options sizeof module.next allot 0 module_options !\ncreate last_module_option sizeof module.next allot 0 last_module_option !\n0 value verbose?\n0 value nextboot?\n\n\\ Support string functions\n: strdup { addr len -- addr' len' }\n len allocate if ENOMEM throw then\n addr over len move len\n;\n\n: strcat { addr len addr' len' -- addr len+len' }\n addr' addr len + len' move\n addr len len' +\n;\n\n: strchr { addr len c -- addr' len' }\n begin\n len\n while\n addr c@ c = if addr len exit then\n addr 1 + to addr\n len 1 - to len\n repeat\n 0 0\n;\n\n: s' \\ same as s\", allows \" in the string\n [char] ' parse\n state @ if postpone sliteral then\n; immediate\n\n: 2>r postpone >r postpone >r ; immediate\n: 2r> postpone r> postpone r> ; immediate\n: 2r@ postpone 2r> postpone 2dup postpone 2>r ; immediate\n\n: getenv? getenv -1 = if false else drop true then ;\n\n\\ determine if a word appears in a string, case-insensitive\n: contains? ( addr1 len1 addr2 len2 -- 0 | -1 )\n\t2 pick 0= if 2drop 2drop true exit then\n\tdup 0= if 2drop 2drop false exit then\n\tbegin\n\t\tbegin\n\t\t\tswap dup c@ dup 32 = over 9 = or\n\t\t\tover 10 = or over 13 = or swap drop\n\t\twhile 1+ swap 1- repeat\n\t\tswap 2 pick 1- over <\n\twhile\n\t\t2over 2over drop over compare-insensitive 0= if\n\t\t\t2 pick over = if 2drop 2drop true exit then\n\t\t\t2 pick tuck - -rot + swap over c@ dup 32 =\n\t\t\tover 9 = or over 10 = or over 13 = or\n\t\t\tswap drop if 2drop 2drop true exit then\n\t\tthen begin\n\t\t\tswap dup c@\n\t\t\tdup 32 = over 9 = or over 10 = or over 13 = or\n\t\t\tswap drop if false else true then 2 pick 0> and\n\t\twhile 1+ swap 1- repeat\n\t\tswap\n\trepeat\n\t2drop 2drop false\n;\n\n: boot_serial? ( -- 0 | -1 )\n\ts\" console\" getenv dup -1 <> if\n\t\ts\" comconsole\" 2swap contains?\n\telse drop false then\n\ts\" boot_serial\" getenv dup -1 <> if\n\t\tswap drop 0>\n\telse drop false then\n\tor \\ console contains comconsole ( or ) boot_serial\n\ts\" boot_multicons\" getenv dup -1 <> if\n\t\tswap drop 0>\n\telse drop false then\n\tor \\ previous boolean ( or ) boot_multicons\n;\n\n\\ Private definitions\n\nvocabulary support-functions\nonly forth also support-functions definitions\n\n\\ Some control characters constants\n\n7 constant bell\n8 constant backspace\n9 constant tab\n10 constant lf\n13 constant \n\n\\ Read buffer size\n\n80 constant read_buffer_size\n\n\\ Standard suffixes\n\n: load_module_suffix\t\ts\" _load\" ;\n: module_loadname_suffix\ts\" _name\" ;\n: module_type_suffix\t\ts\" _type\" ;\n: module_args_suffix\t\ts\" _flags\" ;\n: module_beforeload_suffix\ts\" _before\" ;\n: module_afterload_suffix\ts\" _after\" ;\n: module_loaderror_suffix\ts\" _error\" ;\n\n\\ Support operators\n\n: >= < 0= ;\n: <= > 0= ;\n\n\\ Assorted support functions\n\n: free-memory free if EFREE throw then ;\n\n: strget { var -- addr len } var .addr @ var .len @ ;\n\n\\ assign addr len to variable.\n: strset { addr len var -- } addr var .addr ! len var .len ! ;\n\n\\ free memory and reset fields\n: strfree { var -- } var .addr @ ?dup if free-memory 0 0 var strset then ;\n\n\\ free old content, make a copy of the string and assign to variable\n: string= { addr len var -- } var strfree addr len strdup var strset ;\n\n: strtype ( str -- ) strget type ;\n\n\\ assign a reference to what is on the stack\n: strref { addr len var -- addr len }\n addr var .addr ! len var .len ! addr len\n;\n\n\\ unquote a string\n: unquote ( addr len -- addr len )\n over c@ [char] \" = if 2 chars - swap char+ swap then\n;\n\n\\ Assignment data temporary storage\n\nstring name_buffer\nstring value_buffer\n\n\\ Line by line file reading functions\n\\\n\\ exported:\n\\\tline_buffer\n\\\tend_of_file?\n\\\tfd\n\\\tread_line\n\\\treset_line_reading\n\nvocabulary line-reading\nalso line-reading definitions also\n\n\\ File data temporary storage\n\nstring read_buffer\n0 value read_buffer_ptr\n\n\\ File's line reading function\n\nsupport-functions definitions\n\nstring line_buffer\n0 value end_of_file?\nvariable fd\n\nline-reading definitions\n\n: skip_newlines\n begin\n read_buffer .len @ read_buffer_ptr >\n while\n read_buffer .addr @ read_buffer_ptr + c@ lf = if\n read_buffer_ptr char+ to read_buffer_ptr\n else\n exit\n then\n repeat\n;\n\n: scan_buffer ( -- addr len )\n read_buffer_ptr >r\n begin\n read_buffer .len @ r@ >\n while\n read_buffer .addr @ r@ + c@ lf = if\n read_buffer .addr @ read_buffer_ptr + ( -- addr )\n r@ read_buffer_ptr - ( -- len )\n r> to read_buffer_ptr\n exit\n then\n r> char+ >r\n repeat\n read_buffer .addr @ read_buffer_ptr + ( -- addr )\n r@ read_buffer_ptr - ( -- len )\n r> to read_buffer_ptr\n;\n\n: line_buffer_resize ( len -- len )\n >r\n line_buffer .len @ if\n line_buffer .addr @\n line_buffer .len @ r@ +\n resize if ENOMEM throw then\n else\n r@ allocate if ENOMEM throw then\n then\n line_buffer .addr !\n r>\n;\n \n: append_to_line_buffer ( addr len -- )\n line_buffer strget\n 2swap strcat\n line_buffer .len !\n drop\n;\n\n: read_from_buffer\n scan_buffer ( -- addr len )\n line_buffer_resize ( len -- len )\n append_to_line_buffer ( addr len -- )\n;\n\n: refill_required?\n read_buffer .len @ read_buffer_ptr =\n end_of_file? 0= and\n;\n\n: refill_buffer\n 0 to read_buffer_ptr\n read_buffer .addr @ 0= if\n read_buffer_size allocate if ENOMEM throw then\n read_buffer .addr !\n then\n fd @ read_buffer .addr @ read_buffer_size fread\n dup -1 = if EREAD throw then\n dup 0= if true to end_of_file? then\n read_buffer .len !\n;\n\nsupport-functions definitions\n\n: reset_line_reading\n 0 to read_buffer_ptr\n;\n\n: read_line\n line_buffer strfree\n skip_newlines\n begin\n read_from_buffer\n refill_required?\n while\n refill_buffer\n repeat\n;\n\nonly forth also support-functions definitions\n\n\\ Conf file line parser:\n\\ ::= '='[] |\n\\ []\n\\ ::= {||'_'}\n\\ ::= '\"'{|'\\'}'\"' | \n\\ ::= ASCII 32 to 126, except '\\' and '\"'\n\\ ::= '#'{}\n\\\n\\ exported:\n\\\tline_pointer\n\\\tprocess_conf\n\n0 value line_pointer\n\nvocabulary file-processing\nalso file-processing definitions\n\n\\ parser functions\n\\\n\\ exported:\n\\\tget_assignment\n\nvocabulary parser\nalso parser definitions also\n\n0 value parsing_function\n0 value end_of_line\n\n: end_of_line? line_pointer end_of_line = ;\n\n\\ classifiers for various character classes in the input line\n\n: letter?\n line_pointer c@ >r\n r@ [char] A >=\n r@ [char] Z <= and\n r@ [char] a >=\n r> [char] z <= and\n or\n;\n\n: digit?\n line_pointer c@ >r\n r@ [char] - =\n r@ [char] 0 >=\n r> [char] 9 <= and\n or\n;\n\n: quote? line_pointer c@ [char] \" = ;\n\n: assignment_sign? line_pointer c@ [char] = = ;\n\n: comment? line_pointer c@ [char] # = ;\n\n: space? line_pointer c@ bl = line_pointer c@ tab = or ;\n\n: backslash? line_pointer c@ [char] \\ = ;\n\n: underscore? line_pointer c@ [char] _ = ;\n\n: dot? line_pointer c@ [char] . = ;\n\n\\ manipulation of input line\n: skip_character line_pointer char+ to line_pointer ;\n\n: skip_to_end_of_line end_of_line to line_pointer ;\n\n: eat_space\n begin\n end_of_line? if 0 else space? then\n while\n skip_character\n repeat\n;\n\n: parse_name ( -- addr len )\n line_pointer\n begin\n end_of_line? if 0 else letter? digit? underscore? dot? or or or then\n while\n skip_character\n repeat\n line_pointer over -\n strdup\n;\n\n: remove_backslashes { addr len | addr' len' -- addr' len' }\n len allocate if ENOMEM throw then\n to addr'\n addr >r\n begin\n addr c@ [char] \\ <> if\n addr c@ addr' len' + c!\n len' char+ to len'\n then\n addr char+ to addr\n r@ len + addr =\n until\n r> drop\n addr' len'\n;\n\n: parse_quote ( -- addr len )\n line_pointer\n skip_character\n end_of_line? if ESYNTAX throw then\n begin\n quote? 0=\n while\n backslash? if\n skip_character\n end_of_line? if ESYNTAX throw then\n then\n skip_character\n end_of_line? if ESYNTAX throw then \n repeat\n skip_character\n line_pointer over -\n remove_backslashes\n;\n\n: read_name\n parse_name\t\t( -- addr len )\n name_buffer strset\n;\n\n: read_value\n quote? if\n parse_quote\t\t( -- addr len )\n else\n parse_name\t\t( -- addr len )\n then\n value_buffer strset\n;\n\n: comment\n skip_to_end_of_line\n;\n\n: white_space_4\n eat_space\n comment? if ['] comment to parsing_function exit then\n end_of_line? 0= if ESYNTAX throw then\n;\n\n: variable_value\n read_value\n ['] white_space_4 to parsing_function\n;\n\n: white_space_3\n eat_space\n letter? digit? quote? or or if\n ['] variable_value to parsing_function exit\n then\n ESYNTAX throw\n;\n\n: assignment_sign\n skip_character\n ['] white_space_3 to parsing_function\n;\n\n: white_space_2\n eat_space\n assignment_sign? if ['] assignment_sign to parsing_function exit then\n ESYNTAX throw\n;\n\n: variable_name\n read_name\n ['] white_space_2 to parsing_function\n;\n\n: white_space_1\n eat_space\n letter? if ['] variable_name to parsing_function exit then\n comment? if ['] comment to parsing_function exit then\n end_of_line? 0= if ESYNTAX throw then\n;\n\nfile-processing definitions\n\n: get_assignment\n line_buffer strget + to end_of_line\n line_buffer .addr @ to line_pointer\n ['] white_space_1 to parsing_function\n begin\n end_of_line? 0=\n while\n parsing_function execute\n repeat\n parsing_function ['] comment =\n parsing_function ['] white_space_1 =\n parsing_function ['] white_space_4 =\n or or 0= if ESYNTAX throw then\n;\n\nonly forth also support-functions also file-processing definitions also\n\n\\ Process line\n\n: assignment_type? ( addr len -- flag )\n name_buffer strget\n compare 0=\n;\n\n: suffix_type? ( addr len -- flag )\n name_buffer .len @ over <= if 2drop false exit then\n name_buffer .len @ over - name_buffer .addr @ +\n over compare 0=\n;\n\n: loader_conf_files? s\" loader_conf_files\" assignment_type? ;\n\n: nextboot_flag? s\" nextboot_enable\" assignment_type? ;\n\n: nextboot_conf? s\" nextboot_conf\" assignment_type? ;\n\n: verbose_flag? s\" verbose_loading\" assignment_type? ;\n\n: execute? s\" exec\" assignment_type? ;\n\n: module_load? load_module_suffix suffix_type? ;\n\n: module_loadname? module_loadname_suffix suffix_type? ;\n\n: module_type? module_type_suffix suffix_type? ;\n\n: module_args? module_args_suffix suffix_type? ;\n\n: module_beforeload? module_beforeload_suffix suffix_type? ;\n\n: module_afterload? module_afterload_suffix suffix_type? ;\n\n: module_loaderror? module_loaderror_suffix suffix_type? ;\n\n\\ build a 'set' statement and execute it\n: set_environment_variable\n name_buffer .len @ value_buffer .len @ + 5 chars + \\ size of result string\n allocate if ENOMEM throw then\n dup 0 \\ start with an empty string and append the pieces\n s\" set \" strcat\n name_buffer strget strcat\n s\" =\" strcat\n value_buffer strget strcat\n ['] evaluate catch if\n 2drop free drop\n ESETERROR throw\n else\n free-memory\n then\n;\n\n: set_conf_files\n set_environment_variable\n s\" loader_conf_files\" getenv conf_files string=\n;\n\n: set_nextboot_conf \\ XXX maybe do as set_conf_files ?\n value_buffer strget unquote nextboot_conf_file string=\n;\n\n: append_to_module_options_list ( addr -- )\n module_options @ 0= if\n dup module_options !\n last_module_option !\n else\n dup last_module_option @ module.next !\n last_module_option !\n then\n;\n\n: set_module_name { addr -- }\t\\ check leaks\n name_buffer strget addr module.name string=\n;\n\n: yes_value?\n value_buffer strget\t\\ XXX could use unquote\n 2dup s' \"YES\"' compare >r\n 2dup s' \"yes\"' compare >r\n 2dup s\" YES\" compare >r\n s\" yes\" compare r> r> r> and and and 0=\n;\n\n: find_module_option ( -- addr | 0 ) \\ return ptr to entry matching name_buffer\n module_options @\n begin\n dup\n while\n dup module.name strget\n name_buffer strget\n compare 0= if exit then\n module.next @\n repeat\n;\n\n: new_module_option ( -- addr )\n sizeof module allocate if ENOMEM throw then\n dup sizeof module erase\n dup append_to_module_options_list\n dup set_module_name\n;\n\n: get_module_option ( -- addr )\n find_module_option\n ?dup 0= if new_module_option then\n;\n\n: set_module_flag\n name_buffer .len @ load_module_suffix nip - name_buffer .len !\n yes_value? get_module_option module.flag !\n;\n\n: set_module_args\n name_buffer .len @ module_args_suffix nip - name_buffer .len !\n value_buffer strget unquote\n get_module_option module.args string=\n;\n\n: set_module_loadname\n name_buffer .len @ module_loadname_suffix nip - name_buffer .len !\n value_buffer strget unquote\n get_module_option module.loadname string=\n;\n\n: set_module_type\n name_buffer .len @ module_type_suffix nip - name_buffer .len !\n value_buffer strget unquote\n get_module_option module.type string=\n;\n\n: set_module_beforeload\n name_buffer .len @ module_beforeload_suffix nip - name_buffer .len !\n value_buffer strget unquote\n get_module_option module.beforeload string=\n;\n\n: set_module_afterload\n name_buffer .len @ module_afterload_suffix nip - name_buffer .len !\n value_buffer strget unquote\n get_module_option module.afterload string=\n;\n\n: set_module_loaderror\n name_buffer .len @ module_loaderror_suffix nip - name_buffer .len !\n value_buffer strget unquote\n get_module_option module.loaderror string=\n;\n\n: set_nextboot_flag\n yes_value? to nextboot?\n;\n\n: set_verbose\n yes_value? to verbose?\n;\n\n: execute_command\n value_buffer strget unquote\n ['] evaluate catch if EEXEC throw then\n;\n\n: process_assignment\n name_buffer .len @ 0= if exit then\n loader_conf_files?\tif set_conf_files exit then\n nextboot_flag?\tif set_nextboot_flag exit then\n nextboot_conf?\tif set_nextboot_conf exit then\n verbose_flag?\t\tif set_verbose exit then\n execute?\t\tif execute_command exit then\n module_load?\t\tif set_module_flag exit then\n module_loadname?\tif set_module_loadname exit then\n module_type?\t\tif set_module_type exit then\n module_args?\t\tif set_module_args exit then\n module_beforeload?\tif set_module_beforeload exit then\n module_afterload?\tif set_module_afterload exit then\n module_loaderror?\tif set_module_loaderror exit then\n set_environment_variable\n;\n\n\\ free_buffer ( -- )\n\\\n\\ Free some pointers if needed. The code then tests for errors\n\\ in freeing, and throws an exception if needed. If a pointer is\n\\ not allocated, it's value (0) is used as flag.\n\n: free_buffers\n name_buffer strfree\n value_buffer strfree\n;\n\n\\ Higher level file processing\n\nsupport-functions definitions\n\n: process_conf\n begin\n end_of_file? 0=\n while\n free_buffers\n read_line\n get_assignment\n ['] process_assignment catch\n ['] free_buffers catch\n swap throw throw\n repeat\n;\n\n: peek_file\n 0 to end_of_file?\n reset_line_reading\n O_RDONLY fopen fd !\n fd @ -1 = if EOPEN throw then\n free_buffers\n read_line\n get_assignment\n ['] process_assignment catch\n ['] free_buffers catch\n fd @ fclose\n;\n \nonly forth also support-functions definitions\n\n\\ Interface to loading conf files\n\n: load_conf ( addr len -- )\n \\ .\" ----- Trying conf \" 2dup type cr \\ debugging\n 0 to end_of_file?\n reset_line_reading\n O_RDONLY fopen fd !\n fd @ -1 = if EOPEN throw then\n ['] process_conf catch\n fd @ fclose\n throw\n;\n\n: print_line line_buffer strtype cr ;\n\n: print_syntax_error\n line_buffer strtype cr\n line_buffer .addr @\n begin\n line_pointer over <>\n while\n bl emit char+\n repeat\n drop\n .\" ^\" cr\n;\n\n\n\\ Debugging support functions\n\nonly forth definitions also support-functions\n\n: test-file \n ['] load_conf catch dup .\n ESYNTAX = if cr print_syntax_error then\n;\n\n\\ find a module name, leave addr on the stack (0 if not found)\n: find-module ( -- ptr | 0 )\n bl parse ( addr len )\n module_options @ >r ( store current pointer )\n begin\n r@\n while\n 2dup ( addr len addr len )\n r@ module.name strget\n compare 0= if drop drop r> exit then ( found it )\n r> module.next @ >r\n repeat\n type .\" was not found\" cr r>\n;\n\n: show-nonempty ( addr len mod -- )\n strget dup verbose? or if\n 2swap type type cr\n else\n drop drop drop drop\n then ;\n\n: show-one-module { addr -- addr }\n .\" Name: \" addr module.name strtype cr\n s\" Path: \" addr module.loadname show-nonempty\n s\" Type: \" addr module.type show-nonempty\n s\" Flags: \" addr module.args show-nonempty\n s\" Before load: \" addr module.beforeload show-nonempty\n s\" After load: \" addr module.afterload show-nonempty\n s\" Error: \" addr module.loaderror show-nonempty\n .\" Status: \" addr module.flag @ if .\" Load\" else .\" Don't load\" then cr\n cr\n addr\n;\n\n: show-module-options\n module_options @\n begin\n ?dup\n while\n show-one-module\n module.next @\n repeat\n;\n\nonly forth also support-functions definitions\n\n\\ Variables used for processing multiple conf files\n\nstring current_file_name_ref\t\\ used to print the file name\n\n\\ Indicates if any conf file was succesfully read\n\n0 value any_conf_read?\n\n\\ loader_conf_files processing support functions\n\n: get_conf_files ( -- addr len ) \\ put addr\/len on stack, reset var\n \\ .\" -- starting on <\" conf_files strtype .\" >\" cr \\ debugging\n conf_files strget 0 0 conf_files strset\n;\n\n: skip_leading_spaces { addr len pos -- addr len pos' }\n begin\n pos len = if 0 else addr pos + c@ bl = then\n while\n pos char+ to pos\n repeat\n addr len pos\n;\n\n\\ return the file name at pos, or free the string if nothing left\n: get_file_name { addr len pos -- addr len pos' addr' len' || 0 }\n pos len = if \n addr free abort\" Fatal error freeing memory\"\n 0 exit\n then\n pos >r\n begin\n \\ stay in the loop until have chars and they are not blank\n pos len = if 0 else addr pos + c@ bl <> then\n while\n pos char+ to pos\n repeat\n addr len pos addr r@ + pos r> -\n \\ 2dup .\" get_file_name has \" type cr \\ debugging\n;\n\n: get_next_file ( addr len ptr -- addr len ptr' addr' len' | 0 )\n skip_leading_spaces\n get_file_name\n;\n\n: print_current_file\n current_file_name_ref strtype\n;\n\n: process_conf_errors\n dup 0= if true to any_conf_read? drop exit then\n >r 2drop r>\n dup ESYNTAX = if\n .\" Warning: syntax error on file \" print_current_file cr\n print_syntax_error drop exit\n then\n dup ESETERROR = if\n .\" Warning: bad definition on file \" print_current_file cr\n print_line drop exit\n then\n dup EREAD = if\n .\" Warning: error reading file \" print_current_file cr drop exit\n then\n dup EOPEN = if\n verbose? if .\" Warning: unable to open file \" print_current_file cr then\n drop exit\n then\n dup EFREE = abort\" Fatal error freeing memory\"\n dup ENOMEM = abort\" Out of memory\"\n throw \\ Unknown error -- pass ahead\n;\n\n\\ Process loader_conf_files recursively\n\\ Interface to loader_conf_files processing\n\n: include_conf_files\n get_conf_files 0\t( addr len offset )\n begin\n get_next_file ?dup ( addr len 1 | 0 )\n while\n current_file_name_ref strref\n ['] load_conf catch\n process_conf_errors\n conf_files .addr @ if recurse then\n repeat\n;\n\n: get_nextboot_conf_file ( -- addr len )\n nextboot_conf_file strget strdup\t\\ XXX is the strdup a leak ?\n;\n\n: rewrite_nextboot_file ( -- )\n get_nextboot_conf_file\n O_WRONLY fopen fd !\n fd @ -1 = if EOPEN throw then\n fd @ s' nextboot_enable=\"NO\" ' fwrite\n fd @ fclose\n;\n\n: include_nextboot_file\n get_nextboot_conf_file\n ['] peek_file catch\n nextboot? if\n get_nextboot_conf_file\n ['] load_conf catch\n process_conf_errors\n ['] rewrite_nextboot_file catch\n then\n;\n\n\\ Module loading functions\n\n: load_parameters { addr -- addr addrN lenN ... addr1 len1 N }\n addr\n addr module.args strget\n addr module.loadname .len @ if\n addr module.loadname strget\n else\n addr module.name strget\n then\n addr module.type .len @ if\n addr module.type strget\n s\" -t \"\n 4 ( -t type name flags )\n else\n 2 ( name flags )\n then\n;\n\n: before_load ( addr -- addr )\n dup module.beforeload .len @ if\n dup module.beforeload strget\n ['] evaluate catch if EBEFORELOAD throw then\n then\n;\n\n: after_load ( addr -- addr )\n dup module.afterload .len @ if\n dup module.afterload strget\n ['] evaluate catch if EAFTERLOAD throw then\n then\n;\n\n: load_error ( addr -- addr )\n dup module.loaderror .len @ if\n dup module.loaderror strget\n evaluate \\ This we do not intercept so it can throw errors\n then\n;\n\n: pre_load_message ( addr -- addr )\n verbose? if\n dup module.name strtype\n .\" ...\"\n then\n;\n\n: load_error_message verbose? if .\" failed!\" cr then ;\n\n: load_succesful_message verbose? if .\" ok\" cr then ;\n\n: load_module\n load_parameters load\n;\n\n: process_module ( addr -- addr )\n pre_load_message\n before_load\n begin\n ['] load_module catch if\n dup module.loaderror .len @ if\n load_error\t\t\t\\ Command should return a flag!\n else \n load_error_message true\t\t\\ Do not retry\n then\n else\n after_load\n load_succesful_message true\t\\ Succesful, do not retry\n then\n until\n;\n\n: process_module_errors ( addr ior -- )\n dup EBEFORELOAD = if\n drop\n .\" Module \"\n dup module.name strtype\n dup module.loadname .len @ if\n .\" (\" dup module.loadname strtype .\" )\"\n then\n cr\n .\" Error executing \"\n dup module.beforeload strtype cr\t\\ XXX there was a typo here\n abort\n then\n\n dup EAFTERLOAD = if\n drop\n .\" Module \"\n dup module.name .addr @ over module.name .len @ type\n dup module.loadname .len @ if\n .\" (\" dup module.loadname strtype .\" )\"\n then\n cr\n .\" Error executing \"\n dup module.afterload strtype cr\n abort\n then\n\n throw \\ Don't know what it is all about -- pass ahead\n;\n\n\\ Module loading interface\n\n\\ scan the list of modules, load enabled ones.\n: load_modules ( -- ) ( throws: abort & user-defined )\n module_options @\t( list_head )\n begin\n ?dup\n while\n dup module.flag @ if\n ['] process_module catch\n process_module_errors\n then\n module.next @\n repeat\n;\n\n\\ h00h00 magic used to try loading either a kernel with a given name,\n\\ or a kernel with the default name in a directory of a given name\n\\ (the pain!)\n\n: bootpath s\" \/boot\/\" ;\n: modulepath s\" module_path\" ;\n\n\\ Functions used to save and restore module_path's value.\n: saveenv ( addr len | -1 -- addr' len | 0 -1 )\n dup -1 = if 0 swap exit then\n strdup\n;\n: freeenv ( addr len | 0 -1 )\n -1 = if drop else free abort\" Freeing error\" then\n;\n: restoreenv ( addr len | 0 -1 -- )\n dup -1 = if ( it wasn't set )\n 2drop\n modulepath unsetenv\n else\n over >r\n modulepath setenv\n r> free abort\" Freeing error\"\n then\n;\n\n: clip_args \\ Drop second string if only one argument is passed\n 1 = if\n 2swap 2drop\n 1\n else\n 2\n then\n;\n\nalso builtins\n\n\\ Parse filename from a semicolon-separated list\n\n\\ replacement, not working yet\n: newparse-; { addr len | a1 -- a' len-x addr x }\n addr len [char] ; strchr dup if\t( a1 len1 )\n swap to a1\t( store address )\n 1 - a1 @ 1 + swap ( remove match )\n addr a1 addr -\n else\n 0 0 addr len\n then\n;\n\n: parse-; ( addr len -- addr' len-x addr x )\n over 0 2swap\t\t\t( addr 0 addr len )\n begin\n dup 0 <>\t\t\t( addr 0 addr len )\n while\n over c@ [char] ; <>\t\t( addr 0 addr len flag )\n while\n 1- swap 1+ swap\n 2swap 1+ 2swap\n repeat then\n dup 0 <> if\n 1- swap 1+ swap\n then\n 2swap\n;\n\n\\ Try loading one of multiple kernels specified\n\n: try_multiple_kernels ( addr len addr' len' args -- flag )\n >r\n begin\n parse-; 2>r\n 2over 2r>\n r@ clip_args\n s\" DEBUG\" getenv? if\n s\" echo Module_path: ${module_path}\" evaluate\n .\" Kernel : \" >r 2dup type r> cr\n dup 2 = if .\" Flags : \" >r 2over type r> cr then\n then\n 1 load\n while\n dup 0=\n until\n 1 >r \\ Failure\n else\n 0 >r \\ Success\n then\n 2drop 2drop\n r>\n r> drop\n;\n\n\\ Try to load a kernel; the kernel name is taken from one of\n\\ the following lists, as ordered:\n\\\n\\ 1. The \"bootfile\" environment variable\n\\ 2. The \"kernel\" environment variable\n\\\n\\ Flags are passed, if available. If not, dummy values must be given.\n\\\n\\ The kernel gets loaded from the current module_path.\n\n: load_a_kernel ( flags len 1 | x x 0 -- flag )\n local args\n 2local flags\n 0 0 2local kernel\n end-locals\n\n \\ Check if a default kernel name exists at all, exits if not\n s\" bootfile\" getenv dup -1 <> if\n to kernel\n flags kernel args 1+ try_multiple_kernels\n dup 0= if exit then\n then\n drop\n\n s\" kernel\" getenv dup -1 <> if\n to kernel\n else\n drop\n 1 exit \\ Failure\n then\n\n \\ Try all default kernel names\n flags kernel args 1+ try_multiple_kernels\n;\n\n\\ Try to load a kernel; the kernel name is taken from one of\n\\ the following lists, as ordered:\n\\\n\\ 1. The \"bootfile\" environment variable\n\\ 2. The \"kernel\" environment variable\n\\\n\\ Flags are passed, if provided.\n\\\n\\ The kernel will be loaded from a directory computed from the\n\\ path given. Two directories will be tried in the following order:\n\\\n\\ 1. \/boot\/path\n\\ 2. path\n\\\n\\ The module_path variable is overridden if load is succesful, by\n\\ prepending the successful path.\n\n: load_from_directory ( path len 1 | flags len' path len 2 -- flag )\n local args\n 2local path\n args 1 = if 0 0 then\n 2local flags\n 0 0 2local oldmodulepath \\ like a string\n 0 0 2local newmodulepath \\ like a string\n end-locals\n\n \\ Set the environment variable module_path, and try loading\n \\ the kernel again.\n modulepath getenv saveenv to oldmodulepath\n\n \\ Try prepending \/boot\/ first\n bootpath nip path nip + \t\\ total length\n oldmodulepath nip dup -1 = if\n drop\n else\n 1+ +\t\t\t\\ add oldpath -- XXX why the 1+ ?\n then\n allocate if ( out of memory ) 1 exit then \\ XXX throw ?\n\n 0\n bootpath strcat\n path strcat\n 2dup to newmodulepath\n modulepath setenv\n\n \\ Try all default kernel names\n flags args 1- load_a_kernel\n 0= if ( success )\n oldmodulepath nip -1 <> if\n newmodulepath s\" ;\" strcat\n oldmodulepath strcat\n modulepath setenv\n newmodulepath drop free-memory\n oldmodulepath drop free-memory\n then\n 0 exit\n then\n\n \\ Well, try without the prepended \/boot\/\n path newmodulepath drop swap move\n newmodulepath drop path nip\n 2dup to newmodulepath\n modulepath setenv\n\n \\ Try all default kernel names\n flags args 1- load_a_kernel\n if ( failed once more )\n oldmodulepath restoreenv\n newmodulepath drop free-memory\n 1\n else\n oldmodulepath nip -1 <> if\n newmodulepath s\" ;\" strcat\n oldmodulepath strcat\n modulepath setenv\n newmodulepath drop free-memory\n oldmodulepath drop free-memory\n then\n 0\n then\n;\n\n\\ Try to load a kernel; the kernel name is taken from one of\n\\ the following lists, as ordered:\n\\\n\\ 1. The \"bootfile\" environment variable\n\\ 2. The \"kernel\" environment variable\n\\ 3. The \"path\" argument\n\\\n\\ Flags are passed, if provided.\n\\\n\\ The kernel will be loaded from a directory computed from the\n\\ path given. Two directories will be tried in the following order:\n\\\n\\ 1. \/boot\/path\n\\ 2. path\n\\\n\\ Unless \"path\" is meant to be kernel name itself. In that case, it\n\\ will first be tried as a full path, and, next, search on the\n\\ directories pointed by module_path.\n\\\n\\ The module_path variable is overridden if load is succesful, by\n\\ prepending the successful path.\n\n: load_directory_or_file ( path len 1 | flags len' path len 2 -- flag )\n local args\n 2local path\n args 1 = if 0 0 then\n 2local flags\n end-locals\n\n \\ First, assume path is an absolute path to a directory\n flags path args clip_args load_from_directory\n dup 0= if exit else drop then\n\n \\ Next, assume path points to the kernel\n flags path args try_multiple_kernels\n;\n\n: initialize ( addr len -- )\n strdup conf_files strset\n;\n\n: kernel_options ( -- addr len 1 | 0 )\n s\" kernel_options\" getenv\n dup -1 = if drop 0 else 1 then\n;\n\n: standard_kernel_search ( flags 1 | 0 -- flag )\n local args\n args 0= if 0 0 then\n 2local flags\n s\" kernel\" getenv\n dup -1 = if 0 swap then\n 2local path\n end-locals\n\n path nip -1 = if ( there isn't a \"kernel\" environment variable )\n flags args load_a_kernel\n else\n flags path args 1+ clip_args load_directory_or_file\n then\n;\n\n: load_kernel ( -- ) ( throws: abort )\n kernel_options standard_kernel_search\n abort\" Unable to load a kernel!\"\n;\n\n: set_defaultoptions ( -- )\n s\" kernel_options\" getenv dup -1 = if\n drop\n else\n s\" temp_options\" setenv\n then\n;\n\n\\ pick the i-th argument, i starts at 0\n: argv[] ( aN uN ... a1 u1 N i -- aN uN ... a1 u1 N ai+1 ui+1 )\n 2dup = if 0 0 exit then\t\\ out of range\n dup >r\n 1+ 2* ( skip N and ui )\n pick\n r>\n 1+ 2* ( skip N and ai )\n pick\n;\n\n: drop_args ( aN uN ... a1 u1 N -- )\n 0 ?do 2drop loop\n;\n\n: argc\n dup\n;\n\n: queue_argv ( aN uN ... a1 u1 N a u -- a u aN uN ... a1 u1 N+1 )\n >r\n over 2* 1+ -roll\n r>\n over 2* 1+ -roll\n 1+\n;\n\n: unqueue_argv ( aN uN ... a1 u1 N -- aN uN ... a2 u2 N-1 a1 u1 )\n 1- -rot\n;\n\n\\ compute the length of the buffer including the spaces between words\n: strlen(argv) ( aN uN .. a1 u1 N -- aN uN .. a1 u1 N len )\n dup 0= if 0 exit then\n 0 >r\t\\ Size\n 0 >r\t\\ Index\n begin\n argc r@ <>\n while\n r@ argv[]\n nip\n r> r> rot + 1+\n >r 1+ >r\n repeat\n r> drop\n r>\n;\n\n: concat_argv ( aN uN ... a1 u1 N -- a u )\n strlen(argv) allocate if ENOMEM throw then\n 0 2>r ( save addr 0 on return stack )\n\n begin\n dup\n while\n unqueue_argv ( ... N a1 u1 )\n 2r> 2swap\t ( old a1 u1 )\n strcat\n s\" \" strcat ( append one space ) \\ XXX this gives a trailing space\n 2>r\t\t( store string on the result stack )\n repeat\n drop_args\n 2r>\n;\n\n: set_tempoptions ( addrN lenN ... addr1 len1 N -- addr len 1 | 0 )\n \\ Save the first argument, if it exists and is not a flag\n argc if\n 0 argv[] drop c@ [char] - <> if\n unqueue_argv 2>r \\ Filename\n 1 >r\t\t\\ Filename present\n else\n 0 >r\t\t\\ Filename not present\n then\n else\n 0 >r\t\t\\ Filename not present\n then\n\n \\ If there are other arguments, assume they are flags\n ?dup if\n concat_argv\n 2dup s\" temp_options\" setenv\n drop free if EFREE throw then\n else\n set_defaultoptions\n then\n\n \\ Bring back the filename, if one was provided\n r> if 2r> 1 else 0 then\n;\n\n: get_arguments ( -- addrN lenN ... addr1 len1 N )\n 0\n begin\n \\ Get next word on the command line\n parse-word\n ?dup while\n queue_argv\n repeat\n drop ( empty string )\n;\n\n: load_kernel_and_modules ( args -- flag )\n set_tempoptions\n argc >r\n s\" temp_options\" getenv dup -1 <> if\n queue_argv\n else\n drop\n then\n r> if ( a path was passed )\n load_directory_or_file\n else\n standard_kernel_search\n then\n ?dup 0= if ['] load_modules catch then\n;\n\n\\ Go back to straight forth vocabulary\n\nonly forth also definitions\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"2d5e16ee2d794fc416dae647dda6569c4bf0c684","subject":"Comment changes.","message":"Comment changes.","repos":"rbsexton\/gecko,rbsexton\/gecko,rbsexton\/gecko","old_file":"zero\/clock-umb\/forth\/Clock.fth","new_file":"zero\/clock-umb\/forth\/Clock.fth","new_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( -- ) \n init-idata\n load-defaults \n icroot 0 over inter.rtcsem ! \\ Reset the free-running counters.\n 0 over inter.rtcdsem ! \\ Reset the free-running counters.\n\n begin \n \tdup inter.rtcsem @offex! ?dup if advancehms then\n \tdup inter.rtcdsem @offex! ?dup if advancedhms then\n [asm wfi asm]\n uiupdate if use-uivals else use-clockvals then \n key? until drop\n;\n \n\\ These two contain loops to ensure that we don't\n\\ drop any timer ticks on the floor.\n: ADVANCEHMS ( n -- ) 0 do hms advancetime loop ;\n: ADVANCEDHMS ( n -- ) 0 do dhms advancetime loop ;\n \n: LOAD-DEFAULTS ( -- )\n nvramvalid? if _nvramload then \n interp-init\n;\n\n\\ ----------------------------------------------------------\n\\ Define the structures before they get used.\n\\ ----------------------------------------------------------\nstruct ODN \\ On-Deck Needle \n\tint odn.s\n\tint odn.m\n\tint odn.h\nend-struct\n\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxsec \\ Max Value for secs+minutes\n\tint hms.maxhour \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_m \\ increment the minutes + hours\nend-struct\n\nstruct _interp_set\n\t4 cells field interp.a\n\t4 cells field interp.b\n\t4 cells field interp.c\nend-struct\n\n\\ ----------------------------------------------------------\n\\ Defaults get saved in the user data page.\n\\ ----------------------------------------------------------\n: NVRAMVALID? ( -- t\/f ) \n\\ *G See if there is valid data in the NVRAM.\n\\ ** It consists of 3 words. If any of them are \n\\ ** set to 0xffff:ffff, we go with the defaults.\n _USERDATA\n dup @ -1 <> \n over 4 + @ -1 <> and\n swap 8 + @ -1 <> and\n;\n\n: _NVRAMLOAD ( -- ) \n\\ *G Pull the needle maximums from flash.\n $C 0 do I ud@ needle_max I + ! 4 +loop \n; \n\n: NVRAM! ( addr -- )\n\\ *G Save the contents of the needle cal values.\n 0 UDPAGE_ERASE\n ( addr )\n $C 0 do dup I + @ I ud! 4 +loop\n drop \n;\n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nidata\ncreate ODN_HMS odn allot \\ On-Deck, HMS\ncreate ODN_DHMS odn allot \\ On-Deck, DHMS\ncreate ODN_UI odn allot \\ On-Deck, Generated by the UI.\ncdata\n\nidata \\ Has to match an odn.\ncreate NEEDLE_MAX #850 , #850 , #850 ,\ncdata\n\n(( \n: interp-next drop 1 ; \n: interp-reset drop .\" Reset\" ; \n\t\n))\n\n: RANGECHECK ( max n -- n or zero ) 2dup <= if 2drop 0 else swap drop then ; \n: CLIP ( n -- n) \\ Force the contents to be legal ( 0-999 )\n dup 0 < if drop 0 exit then \n dup #999 > if drop #999 then \n;\n \n: INTER-BUMP ( max old interp -- new )\n\\ *G Get the next value from the interpolator, and \n\\ ** reset the interpolator if it wraps around to zero.\n >R R@ interp-next \\ Get the max \n + rangecheck \n dup 0= if R> interp-reset else R> drop then \n ; \n\n: NFETCH ( odn off -- max old )\n\\ *G Combine the current value with the maximum.\n >R R@ \\ stash the offset.\n + @ \\ Calculate the offset address, get the current val.\n needle_max R> + @\n swap \n;\n\n: ++NEEDLE_S \\ Called every time.\n odn_hms 0 odn.s nfetch ( max old )\n\tinterp_hms interp.a inter-bump ( new )\n\todn_hms odn.s ! \n\t;\n\n: ++NEEDLE_M ( -- )\n\\ *G Every time we roll the seconds, bump the minutes and the hour\n\todn_hms 0 odn.m nfetch ( max old )\n\tinterp_hms interp.b inter-bump \n\todn_hms odn.m ! \n\n\todn_hms 0 odn.h nfetch ( max old )\n\tinterp_hms interp.c inter-bump \n\todn_hms odn.h ! \n\t;\n\n: ++NEEDLE_DS ; \\ Called every time.\n: ++NEEDLE_DM ; \\ Every time we roll the seconds.\n\n: _USE ( odn-addr -- ) \n dup odn.s w@ pwm0!\n dup odn.m w@ pwm1!\n odn.h w@ pwm2!\n ;\n\n: USE-CLOCKVALS odn_hms _use ; \n: USE-UIVALS odn_ui _use ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Quadrature\n\\ ----------------------------------------------------------\n\n_timer1 $24 + equ QUAD-IN\n\n\\ The Quadrature encoder produces two per detent.\n: QUAD@ ( -- n ) \\ Fetch and zero\n quad-in @off \n [asm sxth tos, tos asm]\n [asm asr .s tos, tos, # 1 asm] \\ Divide by two,\n ;\n \n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_ds , ' ++needle_dm , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n: ADVANCETIME ( struct-addr -- )\n dup hms.w_s @ execute \\ Invoke the official update word.\n 1 over hms.subsec +! \\ Increment\n dup hms.subsec @\n over hms.maxsubsec @ < if drop exit then \\ If less then max, we're done\n 0 over hms.subsec ! \\ Reset the subsecs \n\n 1 over hms.s +!\n dup hms.s @ over hms.maxsec @ < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n dup hms.w_m @ execute\n 1 over hms.m +!\n dup hms.m @ over hms.maxsec @ < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ over hms.maxhour @ < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ----------------------------------------------------------\n\\ The interpolator. \n\\ Implement bresenhams algorithm. All of this code already\n\\ exists in C, but we'll own the data structures. They contain\n\\ A total of 4 words - fixed, err, num, & denom\n\\ ----------------------------------------------------------\nudata \ncreate interp_hms _interp_set allot\ncreate interp_dhms _interp_set allot \ncdata\n\n#16 #60 * equ raw_sec\n#10 #100 * equ raw_dsec\n\n: INTERP-INIT ( -- )\n (interp_init) interp_hms\n 2dup interp.a needle_max @ raw_sec call3-- \n 2dup interp.b needle_max 4 + @ #60 call3-- \n interp.c needle_max 8 + @ #24 #60 * call3--\n\n (interp_init) interp_dhms\n 2dup interp.a needle_max @ raw_dsec call3-- \n 2dup interp.b needle_max 4 + @ #100 call3-- \n interp.c needle_max 8 + @ #10 #100 * call3--\n;\n\n\\ Call the reset fn.\n: INTERP-RESET ( interp_addr -- )\n (interp_reset) swap call1-- \n;\n\n: INTERP-NEXT ( addr -- n )\n (interp_next) swap call1--n\n;\n\n\\ ----------------------------------------------------------\n\\ ----------------------------------------------------------\n\\ User Interface\n\\ ----------------------------------------------------------\n\\ ----------------------------------------------------------\nvariable uistate\nvariable uicount \n\n_GPIO $64 + equ _BUTTONIO\n: BUTTONUP? ( -- t\/f ) _buttonio @ 1 and ; \n: BUTTONDOWN? ( -- t\/f ) buttonup? 1 xor ; \n\n\\ The wrapper for all of the UI stuff.\n\\ Returns true if the UI is active - ie, use the values generated by the UI.\n: UIUPDATE ( -- t\/f )\n StateHandlers uistate @ + @ execute \n; \n\n: uitest \n uistate @ 4 \/ . .\" ->\" uiupdate uistate @ 4 \/ .\n uicount @ . if .\" True\" else .\" False\" then \n; \n\n\\ -----------------------------------------------\n\\ State numbers. These are defined x4 so that\n\\ we can just use the state number as an index \n\\ into a table of words.\n\\ -----------------------------------------------\n0 4 * equ _s_init\n1 4 * equ _s_b1\n2 4 * equ _s_1sec\n\n3 4 * equ _s_set_h\n4 4 * equ _s_pendset_m\n5 4 * equ _s_setmin\n\n6 4 * equ _s_pendcal0\n7 4 * equ _s_cal0\n8 4 * equ _s_pendcalh\n9 4 * equ _s_calh\n10 4 * equ _s_pendcalm\n11 4 * equ _s_calm\n12 4 * equ _s_pendcals\n13 4 * equ _s_cals\n\n4 equ downcount_1s\n16 equ downcount_3s \n\n\\ All of the state handlers.\n\\ Everybody needs to know the state of the button, so that must\n\\ get passed in, thus they all look like this:\n\\ state ( t\/f -- t\/f )\n: shInit false \n buttondown? if \n _s_b1 uistate !\n uicount off \\ Reset this.\n then\n ;\n\n\\ Waiting for a full second to go by.\n: shB1 false\n buttonup? if _s_init uistate ! exit then\n \\ The Button is down. \n uicount @ downcount_1s >= if\n _s_1sec uistate !\n else \n 1 uicount +!\n\tthen\n ;\n\n\\ We're in the 1 second state\n: sh1sec true \n buttonup? if _s_set_h uistate ! exit then\n uicount @ downcount_3s >= if\n _s_pendcal0 uistate !\n else \n 1 uicount +!\n\tthen \n;\n\n\\ -------------------------------------------------\n\\ Setting the time\n\\ -------------------------------------------------\n: shSetH true buttondown? if _s_pendset_m uistate ! exit then ;\n\n: shPendSetM true buttonup? if _s_setmin uistate ! then ;\n: shSetMin true buttondown? if _s_init uistate ! exit then ;\n\n\\ -------------------------------------------------\n\\ Calibration\n\\ -------------------------------------------------\n: shPendCal0 true buttonup? if _s_cal0 uistate ! helpODNClear then ;\n: shCal0 true buttondown? if _s_pendcalh uistate ! exit then ;\n\n: shPendCalH true buttonup? if _s_calh uistate ! helpODNMid then ; \n: shCalH true buttondown? if _s_pendcalm uistate ! exit then \n odn_ui odn.h helpQuad@ ; \n\n: shPendCalM true buttonup? if _s_calm uistate ! then ; \n: shCalM true buttondown? if _s_pendcals uistate ! exit then \n odn_ui odn.m helpQuad@ ; \n\n: shPendCalS true buttonup? if _s_cals uistate ! then ; \n: shCalS true buttondown? if \n _s_init uistate !\n odn_ui nvram! exit then \n \n odn_ui odn.s helpQuad@ ; \n\n\\ -------------------------------------------------\n\\ Helpers\n\\ -------------------------------------------------\n: helpODNClear ( -- ) \\ Set them all to zero\n odn_ui odn bounds do I off 4 +loop ; \n: helpODNMid ( -- ) \\ Set them all to 500\n odn_ui odn bounds do #750 I ! 4 +loop ; \n: helpQuad@ ( addr -- ) \\ update a location with the quadrature value\n dup @ quad@ + clip swap ! ;\n\n\ncreate StateHandlers \n' shInit , \n' shB1 ,\n' sh1sec ,\n\n' shSetH ,\n' shPendSetM , ' shSetMin ,\n\n' shPendCal0 , ' shCal0 ,\n' shPendCalH , ' shCalH , \n' shPendCalM , ' shCalM , \n' shPendCalS , ' shCalS , \n\n\\ -------------------------------------------------\n\\ Setting the time.\n\\ -------------------------------------------------\nvariable adj_i \\ THe working index into the points array.\n\nudata \ncreate adj_points #50 cells allot \\ 100 16-bit words. \ncreate interp_set _interp_set allot\ncdata \n\n\\ Generate a list of points.\n: MAKE-SET-LIST ( max steps ) \n 2dup \n >R (interp_init) swap interp_set swap R> call3--\n\n \\ Since zero is first, do the w! first.\n swap drop 0 swap \\ Keep a running counter.\n 0 do\n dup I adj_points[]! \\ Save the existing value\n interp_set interp-next + \n loop\n drop\n ;\n\n: ADJ_POINTS[]! ( data index -- ) 2* adj_points + w! ;\n: ADJ_POINTS[]@ ( index -- n ) 2* adj_points + w@ ;\n","old_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( -- ) \n init-idata\n load-defaults \n icroot 0 over inter.rtcsem ! \\ Reset the free-running counters.\n 0 over inter.rtcdsem ! \\ Reset the free-running counters.\n\n begin \n \tdup inter.rtcsem @offex! ?dup if advancehms then\n \tdup inter.rtcdsem @offex! ?dup if advancedhms then\n [asm wfi asm]\n uiupdate if use-uivals else use-clockvals then \n key? until drop\n;\n \n\\ These two contain loops to ensure that we don't\n\\ drop any timer ticks on the floor.\n: ADVANCEHMS ( n -- ) 0 do hms advancetime loop ;\n: ADVANCEDHMS ( n -- ) 0 do dhms advancetime loop ;\n \n: LOAD-DEFAULTS ( -- )\n nvramvalid? if _nvramload then \n interp-init\n;\n\n\\ ----------------------------------------------------------\n\\ Define the structures before they get used.\n\\ ----------------------------------------------------------\nstruct ODN \\ On-Deck Needle \n\tint odn.s\n\tint odn.m\n\tint odn.h\nend-struct\n\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxsec \\ Max Value for secs+minutes\n\tint hms.maxhour \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_m \\ increment the minutes + hours\nend-struct\n\nstruct _interp_set\n\t4 cells field interp.a\n\t4 cells field interp.b\n\t4 cells field interp.c\nend-struct\n\n\\ ----------------------------------------------------------\n\\ Defaults get saved in the user data page.\n\\ ----------------------------------------------------------\n: NVRAMVALID? ( -- t\/f ) \n\\ *G See if there is valid data in the NVRAM.\n\\ ** It consists of 3 words. If any of them are \n\\ ** set to 0xffff:ffff, we go with the defaults.\n _USERDATA\n dup @ -1 <> \n over 4 + @ -1 <> and\n swap 8 + @ -1 <> and\n;\n\n: _NVRAMLOAD ( -- ) \n\\ *G Pull the needle maximums from flash.\n $C 0 do I ud@ needle_max I + ! 4 +loop \n; \n\n: NVRAM! ( addr -- )\n\\ *G Save the contents of the needle cal values.\n 0 UDPAGE_ERASE\n ( addr )\n $C 0 do dup I + @ I ud! 4 +loop\n drop \n;\n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nidata\ncreate ODN_HMS odn allot \\ On-Deck, HMS\ncreate ODN_DHMS odn allot \\ On-Deck, DHMS\ncreate ODN_UI odn allot \\ On-Deck, Generated by the UI.\ncdata\n\nidata \\ Has to match an odn.\ncreate NEEDLE_MAX #850 , #850 , #850 ,\ncdata\n\n(( \n: interp-next drop 1 ; \n: interp-reset drop .\" Reset\" ; \n\t\n))\n\n: RANGECHECK ( max n -- n or zero ) 2dup <= if 2drop 0 else swap drop then ; \n: CLIP ( n -- n) \\ Force the contents to be legal ( 0-999 )\n dup 0 < if drop 0 exit then \n dup #999 > if drop #999 then \n;\n \n: INTER-BUMP ( max old interp -- new )\n\\ *G Get the next value from the interpolator, and \n\\ ** reset the interpolator if it wraps around to zero.\n >R R@ interp-next \\ Get the max \n + rangecheck \n dup 0= if R> interp-reset else R> drop then \n ; \n\n: NFETCH ( odn off -- max old )\n\\ *G Combine the current value with the maximum.\n >R R@ \\ stash the offset.\n + @ \\ Calculate the offset address, get the current val.\n needle_max R> + @\n swap \n;\n\n: ++NEEDLE_S \\ Called every time.\n odn_hms 0 odn.s nfetch ( max old )\n\tinterp_hms interp.a inter-bump ( new )\n\todn_hms odn.s ! \n\t;\n\n: ++NEEDLE_M ( -- )\n\\ *G Every time we roll the seconds, bump the minutes and the hour\n\todn_hms 0 odn.m nfetch ( max old )\n\tinterp_hms interp.b inter-bump \n\todn_hms odn.m ! \n\n\todn_hms 0 odn.h nfetch ( max old )\n\tinterp_hms interp.c inter-bump \n\todn_hms odn.h ! \n\t;\n\n: ++NEEDLE_DS ; \\ Called every time.\n: ++NEEDLE_DM ; \\ Every time we roll the seconds.\n\n: _USE ( odn-addr -- ) \n dup odn.s w@ pwm0!\n dup odn.m w@ pwm1!\n odn.h w@ pwm2!\n ;\n\n: USE-CLOCKVALS odn_hms _use ; \n: USE-UIVALS odn_ui _use ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Quadrature\n\\ ----------------------------------------------------------\n\n_timer1 $24 + equ QUAD-IN\n\n\\ The Quadrature encoder produces two per detent.\n: QUAD@ ( -- n ) \\ Fetch and zero\n quad-in @off \n [asm sxth tos, tos asm]\n [asm asr .s tos, tos, # 1 asm] \\ Divide by two,\n ;\n \n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_ds , ' ++needle_dm , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n: ADVANCETIME ( struct-addr -- )\n dup hms.w_s @ execute \\ Invoke the official update word.\n 1 over hms.subsec +! \\ Increment\n dup hms.subsec @\n over hms.maxsubsec @ < if drop exit then \\ If less then max, we're done\n 0 over hms.subsec ! \\ Reset the subsecs \n\n 1 over hms.s +!\n dup hms.s @ over hms.maxsec @ < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n dup hms.w_m @ execute\n 1 over hms.m +!\n dup hms.m @ over hms.maxsec @ < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ over hms.maxhour @ < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ----------------------------------------------------------\n\\ The interpolator. \n\\ Implement bresenhams algorithm. All of this code already\n\\ exists in C, but we'll own the data structures. They contain\n\\ A total of 4 words - fixed, err, num, & denom\n\\ ----------------------------------------------------------\nudata \ncreate interp_hms _interp_set allot\ncreate interp_dhms _interp_set allot \ncdata\n\n#16 #60 * equ raw_sec\n#10 #100 * equ raw_dsec\n\n: INTERP-INIT ( -- )\n (interp_init) interp_hms\n 2dup interp.a needle_max @ raw_sec call3-- \n 2dup interp.b needle_max 4 + @ #60 call3-- \n interp.c needle_max 8 + @ #24 #60 * call3--\n\n (interp_init) interp_dhms\n 2dup interp.a needle_max @ raw_dsec call3-- \n 2dup interp.b needle_max 4 + @ #100 call3-- \n interp.c needle_max 8 + @ #10 #100 * call3--\n;\n\n\\ Call the reset fn.\n: INTERP-RESET ( interp_addr -- )\n (interp_reset) swap call1-- \n;\n\n: INTERP-NEXT ( addr -- n )\n (interp_next) swap call1--n\n;\n\n\n\\ ============================ UNTESTED =======================\n\\ VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n\n\\ ----------------------------------------------------------\n\\ User Interface\n\\ ----------------------------------------------------------\nvariable uistate\nvariable uicount \n\n_GPIO $64 + equ _BUTTONIO\n: BUTTONUP? ( -- t\/f ) _buttonio @ 1 and ; \n: BUTTONDOWN? ( -- t\/f ) buttonup? 1 xor ; \n\n\\ The wrapper for all of the UI stuff.\n\\ Returns true if the UI is active - ie, use the values generated by the UI.\n: UIUPDATE ( -- t\/f )\n StateHandlers uistate @ + @ execute \n; \n\n: uitest \n uistate @ 4 \/ . .\" ->\" uiupdate uistate @ 4 \/ .\n uicount @ . if .\" True\" else .\" False\" then \n; \n\n\\ -----------------------------------------------\n\\ State numbers. These are defined x4 so that\n\\ we can just use the state number as an index \n\\ into a table of words.\n\\ -----------------------------------------------\n0 4 * equ _s_init\n1 4 * equ _s_b1\n2 4 * equ _s_1sec\n\n3 4 * equ _s_set_h\n4 4 * equ _s_pendset_m\n5 4 * equ _s_setmin\n\n6 4 * equ _s_pendcal0\n7 4 * equ _s_cal0\n8 4 * equ _s_pendcalh\n9 4 * equ _s_calh\n10 4 * equ _s_pendcalm\n11 4 * equ _s_calm\n12 4 * equ _s_pendcals\n13 4 * equ _s_cals\n\n4 equ downcount_1s\n16 equ downcount_3s \n\n\\ All of the state handlers.\n\\ Everybody needs to know the state of the button, so that must\n\\ get passed in, thus they all look like this:\n\\ state ( t\/f -- t\/f )\n: shInit false \n buttondown? if \n _s_b1 uistate !\n uicount off \\ Reset this.\n then\n ;\n\n\\ Waiting for a full second to go by.\n: shB1 false\n buttonup? if _s_init uistate ! exit then\n \\ The Button is down. \n uicount @ downcount_1s >= if\n _s_1sec uistate !\n else \n 1 uicount +!\n\tthen\n ;\n\n\\ We're in the 1 second state\n: sh1sec true \n buttonup? if _s_set_h uistate ! exit then\n uicount @ downcount_3s >= if\n _s_pendcal0 uistate !\n else \n 1 uicount +!\n\tthen \n;\n\n\\ -------------------------------------------------\n\\ Setting the time\n\\ -------------------------------------------------\n: shSetH true buttondown? if _s_pendset_m uistate ! exit then ;\n\n: shPendSetM true buttonup? if _s_setmin uistate ! then ;\n: shSetMin true buttondown? if _s_init uistate ! exit then ;\n\n\\ -------------------------------------------------\n\\ Calibration\n\\ -------------------------------------------------\n: shPendCal0 true buttonup? if _s_cal0 uistate ! helpODNClear then ;\n: shCal0 true buttondown? if _s_pendcalh uistate ! exit then ;\n\n: shPendCalH true buttonup? if _s_calh uistate ! helpODNMid then ; \n: shCalH true buttondown? if _s_pendcalm uistate ! exit then \n odn_ui odn.h helpQuad@ ; \n\n: shPendCalM true buttonup? if _s_calm uistate ! then ; \n: shCalM true buttondown? if _s_pendcals uistate ! exit then \n odn_ui odn.m helpQuad@ ; \n\n: shPendCalS true buttonup? if _s_cals uistate ! then ; \n: shCalS true buttondown? if \n _s_init uistate !\n odn_ui nvram! exit then \n \n odn_ui odn.s helpQuad@ ; \n\n\\ -------------------------------------------------\n\\ Helpers\n\\ -------------------------------------------------\n: helpODNClear ( -- ) \\ Set them all to zero\n odn_ui odn bounds do I off 4 +loop ; \n: helpODNMid ( -- ) \\ Set them all to 500\n odn_ui odn bounds do #750 I ! 4 +loop ; \n: helpQuad@ ( addr -- ) \\ update a location with the quadrature value\n dup @ quad@ + clip swap ! ;\n\n\ncreate StateHandlers \n' shInit , \n' shB1 ,\n' sh1sec ,\n\n' shSetH ,\n' shPendSetM , ' shSetMin ,\n\n' shPendCal0 , ' shCal0 ,\n' shPendCalH , ' shCalH , \n' shPendCalM , ' shCalM , \n' shPendCalS , ' shCalS , \n\n\\ -------------------------------------------------\n\\ Setting the time.\n\\ -------------------------------------------------\nvariable adj_i \\ THe working index into the points array.\n\nudata \ncreate adj_points #50 cells allot \\ 100 16-bit words. \ncreate interp_set _interp_set allot\ncdata \n\n\\ Generate a list of points.\n: MAKE-SET-LIST ( max steps ) \n 2dup \n >R (interp_init) swap interp_set swap R> call3--\n\n \\ Since zero is first, do the w! first.\n swap drop 0 swap \\ Keep a running counter.\n 0 do\n dup I adj_points[]! \\ Save the existing value\n interp_set interp-next + \n loop\n drop\n ;\n\n: ADJ_POINTS[]! ( data index -- ) 2* adj_points + w! ;\n: ADJ_POINTS[]@ ( index -- n ) 2* adj_points + w@ ;\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"4a272808c2860ae0e3f039d5b5f761c91e59c0f2","subject":"Fix a typo (s\/prefix\/suffix\/) and comment.","message":"Fix a typo (s\/prefix\/suffix\/) and comment.\n\nNOTE: This is in an unused portion of the menu framework.\n\nReviewed by:\teadler, adrian (co-mentor)\nApproved by:\tadrian (co-mentor)\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/menu-commands.4th","new_file":"sys\/boot\/forth\/menu-commands.4th","new_contents":"\\ Copyright (c) 2006-2012 Devin Teske \n\\ All rights reserved.\n\\ \n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\ \n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\ \n\\ $FreeBSD$\n\nmarker task-menu-commands.4th\n\n: acpi_enable ( -- )\n\ts\" set acpi_load=YES\" evaluate \\ XXX deprecated but harmless\n\ts\" set hint.acpi.0.disabled=0\" evaluate\n\ts\" loader.acpi_disabled_by_user\" unsetenv\n;\n\n: acpi_disable ( -- )\n\ts\" acpi_load\" unsetenv \\ XXX deprecated but harmless\n\ts\" set hint.acpi.0.disabled=1\" evaluate\n\ts\" set loader.acpi_disabled_by_user=1\" evaluate\n;\n\n: toggle_acpi ( N -- N TRUE )\n\n\t\\ Make changes effective _before_ calling menu-redraw\n\n\tacpienabled? if\n\t\tacpi_disable\n\telse\n\t\tacpi_enable\n\tthen\n\n\tmenu-redraw\n\n\tTRUE \\ loop menu again\n;\n\n: toggle_safemode ( N -- N TRUE )\n\ttoggle_menuitem\n\n\t\\ Now we're going to make the change effective\n\n\ts\" toggle_stateN @\" \\ base name of toggle state var\n\t-rot 2dup 12 + c! rot \\ replace 'N' with ASCII numeral\n\n\tevaluate 0= if\n\t\ts\" kern.smp.disabled\" unsetenv\n\t\ts\" hw.ata.ata_dma\" unsetenv\n\t\ts\" hw.ata.atapi_dma\" unsetenv\n\t\ts\" hw.ata.wc\" unsetenv\n\t\ts\" hw.eisa_slots\" unsetenv\n\t\ts\" kern.eventtimer.periodic\" unsetenv\n\t\ts\" kern.geom.part.check_integrity\" unsetenv\n\telse\n\t\ts\" set kern.smp.disabled=1\" evaluate\n\t\ts\" set hw.ata.ata_dma=0\" evaluate\n\t\ts\" set hw.ata.atapi_dma=0\" evaluate\n\t\ts\" set hw.ata.wc=0\" evaluate\n\t\ts\" set hw.eisa_slots=0\" evaluate\n\t\ts\" set kern.eventtimer.periodic=1\" evaluate\n\t\ts\" set kern.geom.part.check_integrity=0\" evaluate\n\tthen\n\n\tmenu-redraw\n\n\tTRUE \\ loop menu again\n;\n\n: toggle_singleuser ( N -- N TRUE )\n\ttoggle_menuitem\n\tmenu-redraw\n\n\t\\ Now we're going to make the change effective\n\n\ts\" toggle_stateN @\" \\ base name of toggle state var\n\t-rot 2dup 12 + c! rot \\ replace 'N' with ASCII numeral\n\n\tevaluate 0= if\n\t\ts\" boot_single\" unsetenv\n\telse\n\t\ts\" set boot_single=YES\" evaluate\n\tthen\n\n\tTRUE \\ loop menu again\n;\n\n: toggle_verbose ( N -- N TRUE )\n\ttoggle_menuitem\n\tmenu-redraw\n\n\t\\ Now we're going to make the change effective\n\n\ts\" toggle_stateN @\" \\ base name of toggle state var\n\t-rot 2dup 12 + c! rot \\ replace 'N' with ASCII numeral\n\n\tevaluate 0= if\n\t\ts\" boot_verbose\" unsetenv\n\telse\n\t\ts\" set boot_verbose=YES\" evaluate\n\tthen\n\n\tTRUE \\ loop menu again\n;\n\n: goto_prompt ( N -- N FALSE )\n\n\ts\" set autoboot_delay=NO\" evaluate\n\n\tcr\n\t.\" To get back to the menu, type `menu' and press ENTER\" cr\n\t.\" or type `boot' and press ENTER to start FreeBSD.\" cr\n\tcr\n\n\tFALSE \\ exit the menu\n;\n\n: cycle_kernel ( N -- N TRUE )\n\tcycle_menuitem\n\tmenu-redraw\n\n\t\\ Now we're going to make the change effective\n\n\ts\" cycle_stateN\" \\ base name of array state var\n\t-rot 2dup 11 + c! rot \\ replace 'N' with ASCII numeral\n\tevaluate \\ translate name into address\n\t@ \\ dereference address into value\n\t48 + \\ convert to ASCII numeral\n\n\ts\" set kernel=${kernel_prefix}${kernel[N]}${kernel_suffix}\"\n\t \\ command to assemble full kernel-path\n\t-rot tuck 36 + c! swap \\ replace 'N' with array index value\n\tevaluate \\ sets $kernel to full kernel-path\n\n\tTRUE \\ loop menu again\n;\n\n: cycle_root ( N -- N TRUE )\n\tcycle_menuitem\n\tmenu-redraw\n\n\t\\ Now we're going to make the change effective\n\n\ts\" cycle_stateN\" \\ base name of array state var\n\t-rot 2dup 11 + c! rot \\ replace 'N' with ASCII numeral\n\tevaluate \\ translate name into address\n\t@ \\ dereference address into value\n\t48 + \\ convert to ASCII numeral\n\n\ts\" set root=${root_prefix}${root[N]}${root_suffix}\"\n\t \\ command to assemble root image-path\n\t-rot tuck 30 + c! swap \\ replace 'N' with array index value\n\tevaluate \\ sets $kernel to full kernel-path\n\n\tTRUE \\ loop menu again\n;\n","old_contents":"\\ Copyright (c) 2006-2012 Devin Teske \n\\ All rights reserved.\n\\ \n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\ \n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\ \n\\ $FreeBSD$\n\nmarker task-menu-commands.4th\n\n: acpi_enable ( -- )\n\ts\" set acpi_load=YES\" evaluate \\ XXX deprecated but harmless\n\ts\" set hint.acpi.0.disabled=0\" evaluate\n\ts\" loader.acpi_disabled_by_user\" unsetenv\n;\n\n: acpi_disable ( -- )\n\ts\" acpi_load\" unsetenv \\ XXX deprecated but harmless\n\ts\" set hint.acpi.0.disabled=1\" evaluate\n\ts\" set loader.acpi_disabled_by_user=1\" evaluate\n;\n\n: toggle_acpi ( N -- N TRUE )\n\n\t\\ Make changes effective _before_ calling menu-redraw\n\n\tacpienabled? if\n\t\tacpi_disable\n\telse\n\t\tacpi_enable\n\tthen\n\n\tmenu-redraw\n\n\tTRUE \\ loop menu again\n;\n\n: toggle_safemode ( N -- N TRUE )\n\ttoggle_menuitem\n\n\t\\ Now we're going to make the change effective\n\n\ts\" toggle_stateN @\" \\ base name of toggle state var\n\t-rot 2dup 12 + c! rot \\ replace 'N' with ASCII numeral\n\n\tevaluate 0= if\n\t\ts\" kern.smp.disabled\" unsetenv\n\t\ts\" hw.ata.ata_dma\" unsetenv\n\t\ts\" hw.ata.atapi_dma\" unsetenv\n\t\ts\" hw.ata.wc\" unsetenv\n\t\ts\" hw.eisa_slots\" unsetenv\n\t\ts\" kern.eventtimer.periodic\" unsetenv\n\t\ts\" kern.geom.part.check_integrity\" unsetenv\n\telse\n\t\ts\" set kern.smp.disabled=1\" evaluate\n\t\ts\" set hw.ata.ata_dma=0\" evaluate\n\t\ts\" set hw.ata.atapi_dma=0\" evaluate\n\t\ts\" set hw.ata.wc=0\" evaluate\n\t\ts\" set hw.eisa_slots=0\" evaluate\n\t\ts\" set kern.eventtimer.periodic=1\" evaluate\n\t\ts\" set kern.geom.part.check_integrity=0\" evaluate\n\tthen\n\n\tmenu-redraw\n\n\tTRUE \\ loop menu again\n;\n\n: toggle_singleuser ( N -- N TRUE )\n\ttoggle_menuitem\n\tmenu-redraw\n\n\t\\ Now we're going to make the change effective\n\n\ts\" toggle_stateN @\" \\ base name of toggle state var\n\t-rot 2dup 12 + c! rot \\ replace 'N' with ASCII numeral\n\n\tevaluate 0= if\n\t\ts\" boot_single\" unsetenv\n\telse\n\t\ts\" set boot_single=YES\" evaluate\n\tthen\n\n\tTRUE \\ loop menu again\n;\n\n: toggle_verbose ( N -- N TRUE )\n\ttoggle_menuitem\n\tmenu-redraw\n\n\t\\ Now we're going to make the change effective\n\n\ts\" toggle_stateN @\" \\ base name of toggle state var\n\t-rot 2dup 12 + c! rot \\ replace 'N' with ASCII numeral\n\n\tevaluate 0= if\n\t\ts\" boot_verbose\" unsetenv\n\telse\n\t\ts\" set boot_verbose=YES\" evaluate\n\tthen\n\n\tTRUE \\ loop menu again\n;\n\n: goto_prompt ( N -- N FALSE )\n\n\ts\" set autoboot_delay=NO\" evaluate\n\n\tcr\n\t.\" To get back to the menu, type `menu' and press ENTER\" cr\n\t.\" or type `boot' and press ENTER to start FreeBSD.\" cr\n\tcr\n\n\tFALSE \\ exit the menu\n;\n\n: cycle_kernel ( N -- N TRUE )\n\tcycle_menuitem\n\tmenu-redraw\n\n\t\\ Now we're going to make the change effective\n\n\ts\" cycle_stateN\" \\ base name of array state var\n\t-rot 2dup 11 + c! rot \\ replace 'N' with ASCII numeral\n\tevaluate \\ translate name into address\n\t@ \\ dereference address into value\n\t48 + \\ convert to ASCII numeral\n\n\ts\" set kernel=${kernel_prefix}${kernel[N]}${kernel_suffix}\"\n\t \\ command to assemble full kernel-path\n\t-rot tuck 36 + c! swap \\ replace 'N' with array index value\n\tevaluate \\ sets $kernel to full kernel-path\n\n\tTRUE \\ loop menu again\n;\n\n: cycle_root ( N -- N TRUE )\n\tcycle_menuitem\n\tmenu-redraw\n\n\t\\ Now we're going to make the change effective\n\n\ts\" cycle_stateN\" \\ base name of array state var\n\t-rot 2dup 11 + c! rot \\ replace 'N' with ASCII numeral\n\tevaluate \\ translate name into address\n\t@ \\ dereference address into value\n\t48 + \\ convert to ASCII numeral\n\n\ts\" set root=${root_prefix}${root[N]}${root_prefix}\"\n\t \\ command to assemble full kernel-path\n\t-rot tuck 30 + c! swap \\ replace 'N' with array index value\n\tevaluate \\ sets $kernel to full kernel-path\n\n\tTRUE \\ loop menu again\n;\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"4f05f673018c27402fb6050c3ba2d1069402a2fe","subject":"Create an array of needle-specific values for setting the clock display.","message":"Create an array of needle-specific values for setting the clock display.","repos":"rbsexton\/gecko,rbsexton\/gecko,rbsexton\/gecko","old_file":"zero\/clock-umb\/forth\/Clock.fth","new_file":"zero\/clock-umb\/forth\/Clock.fth","new_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( -- )\n load-defaults \n icroot 0 over inter.rtcsem ! \\ Reset the free-running counters.\n 0 over inter.rtcdsem ! \\ Reset the free-running counters.\n\n begin \n \tdup inter.rtcsem @offex! ?dup if advancehms then\n \tdup inter.rtcdsem @offex! ?dup if advancedhms then\n [asm wfi asm]\n uiupdate if use-uivals else use-clockvals then \n key? until drop\n;\n \n\\ These two contain loops to ensure that we don't\n\\ drop any timer ticks on the floor.\n: ADVANCEHMS ( n -- ) 0 do hms advancetime loop ;\n: ADVANCEDHMS ( n -- ) 0 do dhms advancetime loop ;\n \n: LOAD-DEFAULTS ( -- )\n interp-init\n;\n\n\\ ----------------------------------------------------------\n\\ Define the structures before they get used.\n\\ ----------------------------------------------------------\nstruct ODN \\ On-Deck Needle \n\tint odn.s\n\tint odn.m\n\tint odn.h\nend-struct\n\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxsec \\ Max Value for secs+minutes\n\tint hms.maxhour \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_m \\ increment the minutes + hours\nend-struct\n\nstruct _interp_set\n\t4 cells field interp.a\n\t4 cells field interp.b\n\t4 cells field interp.c\nend-struct\n\n\\ ----------------------------------------------------------\n\\ Defaults get saved in the user data page.\n\\ ----------------------------------------------------------\n: NVRAMVALID? ( addr -- t\/f ) \n\\ *G See if there is valid data in the NVRAM.\n\\ ** It consists of 3 words. If any of them are \n\\ ** set to 0xffff:ffff, we go with the defaults.\n _USERDATA\n dup @ -1 <> \n over 4 + @ -1 <> and\n swap 8 + @ -1 <> and\n;\n\n: _NVRAMLOAD ( -- ) \n\\ *G Pull the needle maximums from flash.\n $C 0 do I ud@ needle_max I + ! 4 +loop \n; \n\n: NVRAM! ( -- )\n\\ *G Save the contents of the needle cal values.\n 0 UDPAGE_ERASE\n needle_max\n $C 0 do dup I + @ I ud! 4 +loop\n drop \n;\n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nidata\ncreate ODN_HMS odn allot \\ On-Deck, HMS\ncreate ODN_DHMS odn allot \\ On-Deck, DHMS\ncreate ODN_UI odn allot \\ On-Deck, Generated by the UI.\ncdata\n\nidata \\ Has to match an odn.\ncreate NEEDLE_MAX #850 , #850 , #850 ,\ncdata\n\n(( \n: interp-next drop 1 ; \n: interp-reset drop .\" Reset\" ; \n\t\n))\n\n: RANGECHECK ( max n -- n or zero ) 2dup <= if 2drop 0 else swap drop then ; \n\n: INTER-BUMP ( max old interp -- new )\n\\ *G Get the next value from the interpolator, and \n\\ ** reset the interpolator if it wraps around to zero.\n >R R@ interp-next \\ Get the max \n + rangecheck \n dup 0= if R> interp-reset else R> drop then \n ; \n\n: NFETCH ( odn off -- max old )\n\\ *G Combine the current value with the maximum.\n >R R@ \\ stash the offset.\n + @ \\ Calculate the offset address, get the current val.\n needle_max R> + @\n swap \n;\n\n: ++NEEDLE_S \\ Called every time.\n odn_hms 0 odn.s nfetch ( max old )\n\tinterp_hms interp.a inter-bump ( new )\n\todn_hms odn.s ! \n\t;\n\n: ++NEEDLE_M ( -- )\n\\ *G Every time we roll the seconds, bump the minutes and the hour\n\todn_hms 0 odn.m nfetch ( max old )\n\tinterp_hms interp.b inter-bump \n\todn_hms odn.m ! \n\n\todn_hms 0 odn.h nfetch ( max old )\n\tinterp_hms interp.c inter-bump \n\todn_hms odn.h ! \n\t;\n\n: ++NEEDLE_DS ; \\ Called every time.\n: ++NEEDLE_DM ; \\ Every time we roll the seconds.\n\n: _USE ( odn-addr -- ) \n dup odn.s w@ pwm0!\n dup odn.m w@ pwm1!\n odn.h w@ pwm2!\n ;\n\n: USE-CLOCKVALS odn_hms _use ; \n: USE-UIVALS odn_ui _use ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Quadrature\n\\ ----------------------------------------------------------\n\n_timer1 $24 + equ QUAD-IN\n\n\\ The Quadrature encoder produces two per detent.\n: QUAD@ ( -- n ) \\ Fetch and zero\n quad-in @off \n [asm sxth tos, tos asm]\n [asm asr .s tos, tos, # 1 asm] \\ Divide by two,\n ;\n \n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_ds , ' ++needle_dm , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n: ADVANCETIME ( struct-addr -- )\n dup hms.w_s @ execute \\ Invoke the official update word.\n 1 over hms.subsec +! \\ Increment\n dup hms.subsec @\n over hms.maxsubsec @ < if drop exit then \\ If less then max, we're done\n 0 over hms.subsec ! \\ Reset the subsecs \n\n 1 over hms.s +!\n dup hms.s @ over hms.maxsec @ < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n dup hms.w_m @ execute\n 1 over hms.m +!\n dup hms.m @ over hms.maxsec @ < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ over hms.maxhour @ < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ----------------------------------------------------------\n\\ The interpolator. \n\\ Implement bresenhams algorithm. All of this code already\n\\ exists in C, but we'll own the data structures. They contain\n\\ A total of 4 words - fixed, err, num, & denom\n\\ ----------------------------------------------------------\nudata \ncreate interp_hms _interp_set allot\ncreate interp_dhms _interp_set allot \ncdata\n\n#16 #60 * equ raw_sec\n#10 #100 * equ raw_dsec\n\n: INTERP-INIT ( -- )\n (interp_init) interp_hms\n 2dup interp.a needle_max @ raw_sec call3-- \n 2dup interp.b needle_max 4 + @ #60 call3-- \n interp.c needle_max 8 + @ #12 call3--\n\n (interp_init) interp_dhms\n 2dup interp.a needle_max @ raw_dsec call3-- \n 2dup interp.b needle_max 4 + @ #100 call3-- \n interp.c needle_max 8 + @ #10 call3--\n;\n\n\\ Call the reset fn.\n: INTERP-RESET ( interp_addr -- )\n (interp_reset) swap call1-- \n;\n\n: INTERP-NEXT ( addr -- n )\n (interp_next) swap call1--n\n;\n\n\n\\ ============================ UNTESTED =======================\n\\ VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n\n\\ ----------------------------------------------------------\n\\ User Interface\n\\ ----------------------------------------------------------\nvariable uistate\nvariable uicount \n\n_GPIO $64 + equ _BUTTONIO\n: BUTTONUP? ( -- t\/f ) _buttonio @ 1 and ; \n: BUTTONDOWN? ( -- t\/f ) buttonup? 1 xor ; \n\n\\ The wrapper for all of the UI stuff.\n\\ Returns true if the UI is active - ie, use the values generated by the UI.\n: UIUPDATE ( -- t\/f )\n StateHandlers uistate @ + @ execute \n; \n\n\\ -----------------------------------------------\n\\ State numbers. These are defined x4 so that\n\\ we can just use the state number as an index \n\\ into a table of words.\n\\ -----------------------------------------------\n0 4 * equ _s_init\n1 4 * equ _s_b1\n2 4 * equ _s_1sec\n\n3 4 * equ _s_set_h\n4 4 * equ _s_pendset_m\n5 4 * equ _s_setmin\n\n6 4 * equ _s_pendcal0\n7 4 * equ _s_cal0\n8 4 * equ _s_pendcalh\n9 4 * equ _s_calh\n10 4 * equ _s_pendcalm\n11 4 * equ _s_calm\n12 4 * equ _s_pendcals\n13 4 * equ _s_cals\n\n4 equ downcount_1s\n16 equ downcount_3s \n\n\\ All of the state handlers.\n\\ Everybody needs to know the state of the button, so that must\n\\ get passed in, thus they all look like this:\n\\ state ( t\/f -- t\/f )\n: shInit false \n buttondown? if \n _s_b1 uistate !\n uicount off \\ Reset this.\n then\n ;\n\n\\ Waiting for a full second to go by.\n: shB1 false\n buttonup? if _s_init uistate ! exit then\n \\ The Button is down. \n uicount @ downcount_1s >= if\n _s_1sec uistate !\n else \n 1 uicount +!\n\tthen\n ;\n\n\\ We're in the 1 second state\n: sh1sec true \n buttonup? if _s_set_h uistate ! exit then\n uicount @ downcount_3s >= if\n _s_pendcal0 uistate !\n else \n 1 uicount +!\n\tthen \n;\n\n\\ -------------------------------------------------\n\\ Setting the time\n\\ -------------------------------------------------\n: shSetH true buttondown? if _s_pendset_m uistate ! exit then ;\n\n: shPendSetM true buttonup? if _s_setmin uistate ! then ;\n: shSetMin true buttondown? if _s_init uistate ! exit then ;\n\n\\ -------------------------------------------------\n\\ Calibration\n\\ -------------------------------------------------\n: shPendCal0 true buttonup? if _s_cal0 uistate ! then ;\n: shCal0 true buttondown? if _s_pendcalh uistate ! exit then ;\n\n: shPendCalH true buttonup? if _s_calh uistate ! then ; \n: shCalH true buttondown? if _s_pendcalm uistate ! exit then ; \n\n: shPendCalM true buttonup? if _s_calm uistate ! then ; \n: shCalM true buttondown? if _s_pendcals uistate ! exit then ; \n\n: shPendCalS true buttonup? if _s_calm uistate ! then ; \n: shCalS true buttondown? if _s_init uistate ! exit then ; \n\ncreate StateHandlers \n' shInit , \n' shB1 ,\n' sh1sec ,\n\n' shSetH ,\n' shPendSetM , ' shSetMin ,\n\n' shPendCal0 , ' shCal0 ,\n' shPendCalH , ' shCalH , \n' shPendCalM , ' shCalM , \n' shPendCalS , ' shCalS , \n\n\\ -------------------------------------------------\n\\ Setting the time.\n\\ -------------------------------------------------\nvariable adj_i \\ THe working index into the points array.\n\nudata \ncreate adj_points #50 cells allot \\ 100 16-bit words. \ncreate interp_set _interp_set allot\ncdata \n\n\\ Generate a list of points.\n: MAKE-SET-LIST ( max steps ) \n 2dup \n >R (interp_init) swap interp_set swap R> call3--\n\n \\ Since zero is first, do the w! first.\n swap drop 0 swap \\ Keep a running counter.\n 0 do\n dup I adj_points[]! \\ Save the existing value\n interp_set interp-next + \n loop\n drop\n ;\n\n: ADJ_POINTS[]! ( data index -- ) 2* adj_points + w! ;\n: ADJ_POINTS[]@ ( index -- n ) 2* adj_points + w@ ;\n","old_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( -- )\n load-defaults \n icroot 0 over inter.rtcsem ! \\ Reset the free-running counters.\n 0 over inter.rtcdsem ! \\ Reset the free-running counters.\n\n begin \n \tdup inter.rtcsem @offex! ?dup if advancehms then\n \tdup inter.rtcdsem @offex! ?dup if advancedhms then\n [asm wfi asm]\n uiupdate if use-uivals else use-clockvals then \n key? until drop\n;\n \n\\ These two contain loops to ensure that we don't\n\\ drop any timer ticks on the floor.\n: ADVANCEHMS ( n -- ) 0 do hms advancetime loop ;\n: ADVANCEDHMS ( n -- ) 0 do dhms advancetime loop ;\n \n: LOAD-DEFAULTS ( -- )\n interp-init\n;\n\n\\ ----------------------------------------------------------\n\\ Define the structures before they get used.\n\\ ----------------------------------------------------------\nstruct ODN \\ On-Deck Needle \n\tint odn.s\n\tint odn.m\n\tint odn.h\nend-struct\n\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxsec \\ Max Value for secs+minutes\n\tint hms.maxhour \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_m \\ increment the minutes + hours\nend-struct\n\nstruct _interp_set\n\t4 cells field interp.a\n\t4 cells field interp.b\n\t4 cells field interp.c\nend-struct\n\n\\ ----------------------------------------------------------\n\\ Defaults get saved in the user data page.\n\\ ----------------------------------------------------------\n: NVRAMVALID? ( addr -- t\/f ) \n\\ *G See if there is valid data in the NVRAM.\n\\ ** It consists of 3 words. If any of them are \n\\ ** set to 0xffff:ffff, we go with the defaults.\n _USERDATA\n dup @ -1 <> \n over 4 + @ -1 <> and\n swap 8 + @ -1 <> and\n;\n\n: _NVRAMLOAD ( -- ) \n\\ *G Pull the needle maximums from flash.\n $C 0 do I ud@ needle_max I + ! 4 +loop \n; \n\n: NVRAM! ( -- )\n\\ *G Save the contents of the needle cal values.\n 0 UDPAGE_ERASE\n needle_max\n $C 0 do dup I + @ I ud! 4 +loop\n drop \n;\n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nidata\ncreate ODN_HMS odn allot \\ On-Deck, HMS\ncreate ODN_DHMS odn allot \\ On-Deck, DHMS\ncreate ODN_UI odn allot \\ On-Deck, Generated by the UI.\ncdata\n\nidata \\ Has to match an odn.\ncreate NEEDLE_MAX #850 , #850 , #850 ,\ncdata\n\n(( \n: interp-next drop 1 ; \n: interp-reset drop .\" Reset\" ; \n\t\n))\n\n: RANGECHECK ( max n -- n or zero ) 2dup <= if 2drop 0 else swap drop then ; \n\n: INTER-BUMP ( max old interp -- new )\n\\ *G Get the next value from the interpolator, and \n\\ ** reset the interpolator if it wraps around to zero.\n >R R@ interp-next \\ Get the max \n + rangecheck \n dup 0= if R> interp-reset else R> drop then \n ; \n\n: NFETCH ( odn off -- max old )\n\\ *G Combine the current value with the maximum.\n >R R@ \\ stash the offset.\n + @ \\ Calculate the offset address, get the current val.\n needle_max R> + @\n swap \n;\n\n: ++NEEDLE_S \\ Called every time.\n odn_hms 0 odn.s nfetch ( max old )\n\tinterp_hms interp.a inter-bump ( new )\n\todn_hms odn.s ! \n\t;\n\n: ++NEEDLE_M ( -- )\n\\ *G Every time we roll the seconds, bump the minutes and the hour\n\todn_hms 0 odn.m nfetch ( max old )\n\tinterp_hms interp.b inter-bump \n\todn_hms odn.m ! \n\n\todn_hms 0 odn.h nfetch ( max old )\n\tinterp_hms interp.c inter-bump \n\todn_hms odn.h ! \n\t;\n\n: ++NEEDLE_DS ; \\ Called every time.\n: ++NEEDLE_DM ; \\ Every time we roll the seconds.\n\n: _USE ( odn-addr -- ) \n dup odn.s w@ pwm0!\n dup odn.m w@ pwm1!\n odn.h w@ pwm2!\n ;\n\n: USE-CLOCKVALS odn_hms _use ; \n: USE-UIVALS odn_ui _use ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Quadrature\n\\ ----------------------------------------------------------\n\n_timer1 $24 + equ QUAD-IN\n\n\\ The Quadrature encoder produces two per detent.\n: QUAD@ ( -- n ) \\ Fetch and zero\n quad-in @off \n [asm sxth tos, tos asm]\n [asm asr .s tos, tos, # 1 asm] \\ Divide by two,\n ;\n \n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_ds , ' ++needle_dm , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n: ADVANCETIME ( struct-addr -- )\n dup hms.w_s @ execute \\ Invoke the official update word.\n 1 over hms.subsec +! \\ Increment\n dup hms.subsec @\n over hms.maxsubsec @ < if drop exit then \\ If less then max, we're done\n 0 over hms.subsec ! \\ Reset the subsecs \n\n 1 over hms.s +!\n dup hms.s @ over hms.maxsec @ < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n dup hms.w_m @ execute\n 1 over hms.m +!\n dup hms.m @ over hms.maxsec @ < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ over hms.maxhour @ < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ----------------------------------------------------------\n\\ The interpolator. \n\\ Implement bresenhams algorithm. All of this code already\n\\ exists in C, but we'll own the data structures. They contain\n\\ A total of 4 words - fixed, err, num, & denom\n\\ ----------------------------------------------------------\nudata \ncreate interp_hms _interp_set allot\ncreate interp_dhms _interp_set allot \ncreate adj_list #50 cells allot \\ 100 16-bit words. \ncdata\n\n#16 #60 * equ raw_sec\n#10 #100 * equ raw_dsec\n\n: INTERP-INIT ( -- )\n (interp_init) interp_hms\n 2dup interp.a needle_max @ raw_sec call3-- \n 2dup interp.b needle_max 4 + @ #60 call3-- \n interp.c needle_max 8 + @ #12 call3--\n\n (interp_init) interp_dhms\n 2dup interp.a needle_max @ raw_dsec call3-- \n 2dup interp.b needle_max 4 + @ #100 call3-- \n interp.c needle_max 8 + @ #10 call3--\n;\n\n\\ Call the reset fn.\n: INTERP-RESET ( interp_addr -- )\n (interp_reset) swap call1-- \n;\n\n: INTERP-NEXT ( addr -- n )\n (interp_next) swap call1--n\n;\n\n\n\\ ============================ UNTESTED =======================\n\\ VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n\n\\ ----------------------------------------------------------\n\\ User Interface\n\\ ----------------------------------------------------------\nvariable uistate\nvariable uicount \n\n_GPIO $64 + equ _BUTTONIO\n: BUTTONUP? ( -- t\/f ) _buttonio @ 1 and ; \n: BUTTONDOWN? ( -- t\/f ) buttonup? 1 xor ; \n\n\\ The wrapper for all of the UI stuff.\n\\ Returns true if the UI is active - ie, use the values generated by the UI.\n: UIUPDATE ( -- t\/f )\n StateHandlers uistate @ + @ execute \n; \n\n\\ -----------------------------------------------\n\\ State numbers. These are defined x4 so that\n\\ we can just use the state number as an index \n\\ into a table of words.\n\\ -----------------------------------------------\n0 4 * equ _s_init\n1 4 * equ _s_b1\n2 4 * equ _s_1sec\n\n3 4 * equ _s_set_h\n4 4 * equ _s_pendset_m\n5 4 * equ _s_setmin\n\n6 4 * equ _s_pendcal0\n7 4 * equ _s_cal0\n8 4 * equ _s_pendcalh\n9 4 * equ _s_calh\n10 4 * equ _s_pendcalm\n11 4 * equ _s_calm\n12 4 * equ _s_pendcals\n13 4 * equ _s_cals\n\n4 equ downcount_1s\n16 equ downcount_3s \n\n\\ All of the state handlers.\n\\ Everybody needs to know the state of the button, so that must\n\\ get passed in, thus they all look like this:\n\\ state ( t\/f -- t\/f )\n: shInit false \n buttondown? if \n _s_b1 uistate !\n uicount off \\ Reset this.\n then\n ;\n\n\\ Waiting for a full second to go by.\n: shB1 false\n buttonup? if _s_init uistate ! exit then\n \\ The Button is down. \n uicount @ downcount_1s >= if\n _s_1sec uistate !\n else \n 1 uicount +!\n\tthen\n ;\n\n\\ We're in the 1 second state\n: sh1sec true \n buttonup? if _s_set_h uistate ! exit then\n uicount @ downcount_3s >= if\n _s_pendcal0 uistate !\n else \n 1 uicount +!\n\tthen \n;\n\n\\ -------------------------------------------------\n\\ Setting the time\n\\ -------------------------------------------------\n: shSetH true buttondown? if _s_pendset_m uistate ! exit then ;\n\n: shPendSetM true buttonup? if _s_setmin uistate ! then ;\n: shSetMin true buttondown? if _s_init uistate ! exit then ;\n\n\\ -------------------------------------------------\n\\ Calibration\n\\ -------------------------------------------------\n: shPendCal0 true buttonup? if _s_cal0 uistate ! then ;\n: shCal0 true buttondown? if _s_pendcalh uistate ! exit then ;\n\n: shPendCalH true buttonup? if _s_calh uistate ! then ; \n: shCalH true buttondown? if _s_pendcalm uistate ! exit then ; \n\n: shPendCalM true buttonup? if _s_calm uistate ! then ; \n: shCalM true buttondown? if _s_pendcals uistate ! exit then ; \n\n: shPendCalS true buttonup? if _s_calm uistate ! then ; \n: shCalS true buttondown? if _s_init uistate ! exit then ; \n\ncreate StateHandlers \n' shInit , \n' shB1 ,\n' sh1sec ,\n\n' shSetH ,\n' shPendSetM , ' shSetMin ,\n\n' shPendCal0 , ' shCal0 ,\n' shPendCalH , ' shCalH , \n' shPendCalM , ' shCalM , \n' shPendCalS , ' shCalS , \n\n: ADJ_POINTS[]! ( data index -- ) 2* adj_points + w! ;\n: ADJ_POINTS[]@ ( index -- n ) 2* adj_points + w@ ;\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"e8e9cdc08eafba77bcc92b3a46c33a817220c7cc","subject":"Update assembler.4th","message":"Update assembler.4th","repos":"AshleyF\/Forthkit,AshleyF\/Forthkit,AshleyF\/Forthkit","old_file":"hardware\/register\/assembler.4th","new_file":"hardware\/register\/assembler.4th","new_contents":"( assembler for register VM )\n\nvar dp ( dictionary pointer )\n: here dp @ ;\n: , here m! here 1 + dp ! ; ( append )\n\n: ldc, 0 , , , ; ( v x ldc, \u2192 x = v )\n: ld, 1 , , , ; ( a x ld, \u2192 x = mem[a] )\n: st, 2 , , , ; ( x a st, \u2192 mem[a] = x )\n: cp, 3 , , , ; ( y x cp, \u2192 x = y )\n: in, 4 , , ; ( x in, \u2192 x = getc )\n: out, 5 , , ; ( x out, \u2192 putc x )\n: inc, 6 , , , ; ( y x inc, \u2192 x = y + 1 )\n: dec, 7 , , , ; ( y x dec, \u2192 x = y - 1 )\n: add, 8 , , , , ; ( z y x add, \u2192 x = z + y )\n: sub, 9 , , swap , , ; ( z y x sub, \u2192 x = z - y )\n: mul, 10 , , , , ; ( z y x mul, \u2192 x = z \u00d7 y )\n: div, 11 , , swap , , ; ( z y x div, \u2192 x = z \u00f7 y )\n: mod, 12 , , swap , , ; ( z y x mod, \u2192 x = z mod y )\n: and, 13 , , , , ; ( z y x and, \u2192 x = z and y )\n: or, 14 , , , , ; ( z y x or, \u2192 x = z or y )\n: xor, 15 , , , , ; ( z y x xor, \u2192 x = z xor y )\n: not, 16 , , , ; ( y x not, \u2192 x = not y )\n: shl, 17 , , swap , , ; ( z y x shl, \u2192 x = z << y )\n: shr, 18 , , swap , , ; ( z y x shr, \u2192 x = z >> y )\n: beq, 19 , , , , ; ( x y a beq, \u2192 pc = a if x = y )\n: bne, 20 , , , , ; ( x y a bne, \u2192 pc = a if x \u2260 y )\n: bgt, 21 , , swap , , ; ( x y a bgt, \u2192 pc = a if x > y )\n: bge, 22 , , swap , , ; ( x y a bge, \u2192 pc = a if x \u2265 y )\n: blt, 23 , , swap , , ; ( x y a blt, \u2192 pc = a if x < y )\n: ble, 24 , , swap , , ; ( x y a ble, \u2192 pc = a if x \u2264 y )\n: exec, 25 , , ; ( x exec, \u2192 pc = [x] )\n: jump, 26 , , ; ( a jump, \u2192 pc = a )\n: call, 27 , , ; ( a call, \u2192 push[pc], pc = a )\n: ret, 28 , ; ( ret, \u2192 pc = pop[] )\n: halt, 29 , ; ( halt, \u2192 halt machine )\n\n: label here const ;\n: leap, here 0 jump, ; ( dummy jump, push address )\n: ahead, here swap dp ! dup jump, dp ! ; ( pop address, patch jump )\n\n: assemble here . dump ;\n","old_contents":"( assembler for register VM )\n\nvar dp ( dictionary pointer )\n: here dp @ ;\n: , here m! here 1 + dp ! ; ( append )\n\n: ldc, 0 , , , ; ( v x ldc, \u2192 x = v )\n: ld, 1 , , , ; ( a x ld, \u2192 x = mem[a] )\n: st, 2 , , , ; ( x a st, \u2192 mem[a] = x )\n: cp, 3 , , , ; ( y x cp, \u2192 x = y )\n: in, 4 , , ; ( x in, \u2192 x = getc )\n: out, 5 , , ; ( x out, \u2192 putc x )\n: inc, 6 , , , ; ( x inc, \u2192 x++ )\n: dec, 7 , , , ; ( x dec, \u2192 x-- )\n: add, 8 , , , , ; ( z y x add, \u2192 x = y + z )\n: sub, 9 , , swap , , ; ( z y x sub, \u2192 x = y - z )\n: mul, 10 , , , , ; ( z y x mul, \u2192 x = y \u00d7 z )\n: div, 11 , , swap , , ; ( z y x div, \u2192 x = y \u00f7 z )\n: mod, 12 , , swap , , ; ( z y x mod, \u2192 x = y mod z )\n: and, 13 , , , , ; ( z y x and, \u2192 x = y and z )\n: or, 14 , , , , ; ( z y x or, \u2192 x = y or z )\n: xor, 15 , , , , ; ( z y x xor, \u2192 x = y xor z )\n: not, 16 , , , ; ( y x not, \u2192 x = not y )\n: shl, 17 , , swap , , ; ( z y x shl, \u2192 x = y << z )\n: shr, 18 , , swap , , ; ( z y x shr, \u2192 x = y >> z )\n: beq, 19 , , , , ; ( x y a beq, \u2192 pc = a if x = y )\n: bne, 20 , , , , ; ( x y a bne, \u2192 pc = a if x \u2260 y )\n: bgt, 21 , , swap , , ; ( x y a bgt, \u2192 pc = a if x > y )\n: bge, 22 , , swap , , ; ( x y a bge, \u2192 pc = a if x \u2265 y )\n: blt, 23 , , swap , , ; ( x y a blt, \u2192 pc = a if x < y )\n: ble, 24 , , swap , , ; ( x y a ble, \u2192 pc = a if x \u2264 y )\n: exec, 25 , , ; ( x exec, \u2192 pc = [x] )\n: jump, 26 , , ; ( a jump, \u2192 pc = a )\n: call, 27 , , ; ( a call, \u2192 push[pc], pc = a )\n: ret, 28 , ; ( ret, \u2192 pc = pop[] )\n: halt, 29 , ; ( halt, \u2192 halt machine )\n\n: label here const ;\n: leap, here 0 jump, ; ( dummy jump, push address )\n: ahead, here swap dp ! dup jump, dp ! ; ( pop address, patch jump )\n\n: assemble here . dump ;\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"bd453cd2ed9ec6bf9ff939bc49ac17480c2ce79b","subject":"Incorporate WFI into the serial driver.","message":"Incorporate WFI into the serial driver.","repos":"rbsexton\/gecko,rbsexton\/gecko,rbsexton\/gecko","old_file":"zero\/forth\/Drivers\/serLE_pi.fth","new_file":"zero\/forth\/Drivers\/serLE_pi.fth","new_contents":"\\ serLE_p.fth - Polled Driver for the low-energy UART.\r\n\\ Assumes that the hardware is already setup by the launcher.\r\n\\\r\n\\ Note - The assumption here is that the LEUART is running at 9600 baud\r\n\\ The Zero Gecko can wake in 2us, and a character takes 10ms at this baud rate.\r\n\\ So we might as well WFI if the FIFO is full.\r\n\r\n\\ ********************\r\n\\ *S Serial primitives\r\n\\ ********************\r\n\r\n$8 equ LEUART_STATUS\r\n$1C equ LEUART_RXDATA\r\n$28 equ LEUART_TXDATA\r\n\r\ninternal\r\n\r\n: +FaultConsole\t( -- ) ;\r\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\r\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\r\n\\ ** for more details.\r\n\r\n: (seremit)\t\\ char base --\r\n\\ *G Transmit a character on the given UART.\r\n begin\r\n dup LEUART_STATUS + @ bit4 and \t\t\\ Tx FIFO full test\r\n until\r\n LEUART_TXDATA + !\r\n;\r\n\r\n: (sertype)\t\\ caddr len base --\r\n\\ *G Transmit a string on the given UART.\r\n -rot bounds\r\n ?do i c@ over (seremit) loop\r\n drop\r\n;\r\n\r\n: (sercr)\t\\ base --\r\n\\ *G Transmit a CR\/LF pair on the given UART.\r\n $0D over (seremit) $0A swap (seremit)\r\n;\r\n\r\n: (serkey?)\t\\ base -- t\/f\r\n\\ *G Return true if the given UART has a character avilable to read.\r\n c@ \t\t\\ Rx FIFO empty test\r\n;\r\n\r\n: (serkey)\t\\ base -- char\r\n\\ *G Wait for a character to come available on the given UART and\r\n\\ ** return the character.\r\n begin\r\n[ tasking? ] [if] pause [then]\r\n dup c@\r\n dup 0= if [asm wfi asm] then \r\n until\r\n dup c@ swap 0 swap !\r\n;\r\n\r\n: initUART\t\\ divisor22 base --\r\n drop drop\r\n;\r\n\r\nexternal\r\n\r\n\r\n\\ ********\r\n\\ *S UART0\r\n\\ ********\r\n\r\nuseUART0? [if]\r\n\r\n: init-ser0\t; \r\n\r\n: seremit0\t\\ char --\r\n\\ *G Transmit a character on UART0.\r\n _LEUART0 (seremit) ;\r\n: sertype0\t\\ c-addr len --\r\n\\ *G Transmit a string on UART0.\r\n _LEUART0 (sertype) ;\r\n: sercr0\t\\ --\r\n\\ *G Issue a CR\/LF pair to UART0.\r\n _LEUART0 (sercr) ;\r\n: serkey?0\t\\ -- flag\r\n\\ *G Return true if UART0 has a character available.\r\n icroot u0rxdata (serkey?) ;\r\n: serkey0\t\\ -- char\r\n\\ *G Wait for a character on UART0.\r\n icroot u0rxdata (serkey) ;\r\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\r\n\\ *G Generic I\/O device for UART0.\r\n ' serkey0 ,\t\t\\ -- char ; receive char\r\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\r\n ' seremit0 ,\t\t\\ -- char ; display char\r\n ' sertype0 ,\t\t\\ caddr len -- ; display string\r\n ' sercr0 ,\t\t\\ -- ; display new line\r\nconsole-port 0 = [if]\r\n console0 constant console\r\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\r\n\\ ** It may be changed by one of the phrases of the form:\r\n\\ *C dup opvec ! ipvec !\r\n\\ *C SetConsole\r\n[then]\r\n\r\n[then]\r\n\r\n\r\n\\ ************************\r\n\\ *S System initialisation\r\n\\ ************************\r\n\r\n: init-ser\t\\ --\r\n\\ *G Initialise all serial ports\r\n [ useUART0? ] [if] init-ser0 [then]\r\n;\r\n\r\n\r\n\\ ======\r\n\\ *> ###\r\n\\ ======\r\n\r\ndecimal\r\n","old_contents":"\\ serLE_p.fth - Polled Driver for the low-energy UART.\r\n\\ Assumes that the hardware is already setup by the launcher.\r\n\\\r\n\\ Note - The assumption here is that the LEUART is running at 9600 baud\r\n\\ The Zero Gecko can wake in 2us, and a character takes 10ms at this baud rate.\r\n\\ So we might as well WFI if the FIFO is full.\r\n\r\n\\ ********************\r\n\\ *S Serial primitives\r\n\\ ********************\r\n\r\n$8 equ LEUART_STATUS\r\n$1C equ LEUART_RXDATA\r\n$28 equ LEUART_TXDATA\r\n\r\ninternal\r\n\r\n: +FaultConsole\t( -- ) ;\r\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\r\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\r\n\\ ** for more details.\r\n\r\n: (seremit)\t\\ char base --\r\n\\ *G Transmit a character on the given UART.\r\n begin\r\n dup LEUART_STATUS + @ bit4 and \t\t\\ Tx FIFO full test\r\n until\r\n LEUART_TXDATA + !\r\n;\r\n\r\n: (sertype)\t\\ caddr len base --\r\n\\ *G Transmit a string on the given UART.\r\n -rot bounds\r\n ?do i c@ over (seremit) loop\r\n drop\r\n;\r\n\r\n: (sercr)\t\\ base --\r\n\\ *G Transmit a CR\/LF pair on the given UART.\r\n $0D over (seremit) $0A swap (seremit)\r\n;\r\n\r\n: (serkey?)\t\\ base -- t\/f\r\n\\ *G Return true if the given UART has a character avilable to read.\r\n c@ \t\t\\ Rx FIFO empty test\r\n;\r\n\r\n: (serkey)\t\\ base -- char\r\n\\ *G Wait for a character to come available on the given UART and\r\n\\ ** return the character.\r\n begin\r\n[ tasking? ] [if] pause [then]\r\n dup c@ \r\n until\r\n dup c@ swap 0 swap !\r\n;\r\n\r\n: initUART\t\\ divisor22 base --\r\n drop drop\r\n;\r\n\r\nexternal\r\n\r\n\r\n\\ ********\r\n\\ *S UART0\r\n\\ ********\r\n\r\nuseUART0? [if]\r\n\r\n: init-ser0\t; \r\n\r\n: seremit0\t\\ char --\r\n\\ *G Transmit a character on UART0.\r\n _LEUART0 (seremit) ;\r\n: sertype0\t\\ c-addr len --\r\n\\ *G Transmit a string on UART0.\r\n _LEUART0 (sertype) ;\r\n: sercr0\t\\ --\r\n\\ *G Issue a CR\/LF pair to UART0.\r\n _LEUART0 (sercr) ;\r\n: serkey?0\t\\ -- flag\r\n\\ *G Return true if UART0 has a character available.\r\n icroot u0rxdata (serkey?) ;\r\n: serkey0\t\\ -- char\r\n\\ *G Wait for a character on UART0.\r\n icroot u0rxdata (serkey) ;\r\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\r\n\\ *G Generic I\/O device for UART0.\r\n ' serkey0 ,\t\t\\ -- char ; receive char\r\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\r\n ' seremit0 ,\t\t\\ -- char ; display char\r\n ' sertype0 ,\t\t\\ caddr len -- ; display string\r\n ' sercr0 ,\t\t\\ -- ; display new line\r\nconsole-port 0 = [if]\r\n console0 constant console\r\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\r\n\\ ** It may be changed by one of the phrases of the form:\r\n\\ *C dup opvec ! ipvec !\r\n\\ *C SetConsole\r\n[then]\r\n\r\n[then]\r\n\r\n\r\n\\ ************************\r\n\\ *S System initialisation\r\n\\ ************************\r\n\r\n: init-ser\t\\ --\r\n\\ *G Initialise all serial ports\r\n [ useUART0? ] [if] init-ser0 [then]\r\n;\r\n\r\n\r\n\\ ======\r\n\\ *> ###\r\n\\ ======\r\n\r\ndecimal\r\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"b61be3ee13fa5be779797ad05611705ec5913477","subject":"Revert 1.20, as it causes mysterious problems to the Alpha people.","message":"Revert 1.20, as it causes mysterious problems to the Alpha people.\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/loader.4th","new_file":"sys\/boot\/forth\/loader.4th","new_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\ns\" arch-alpha\" environment? [if] [if]\n\ts\" loader_version\" environment? [if]\n\t\t11 < [if]\n\t\t\t.( Loader version 1.1+ required) cr\n\t\t\tabort\n\t\t[then]\n\t[else]\n\t\t.( Could not get loader version!) cr\n\t\tabort\n\t[then]\n[then] [then]\n\ns\" arch-i386\" environment? [if] [if]\n\ts\" loader_version\" environment? [if]\n\t\t10 < [if]\n\t\t\t.( Loader version 1.0+ required) cr\n\t\t\tabort\n\t\t[then]\n\t[else]\n\t\t.( Could not get loader version!) cr\n\t\tabort\n\t[then]\n[then] [then]\n\ninclude \/boot\/support.4th\n\n\\ ***** boot-conf\n\\\n\\\tPrepares to boot as specified by loaded configuration files.\n\nonly forth also support-functions also builtins definitions\n\n: boot\n 0= if ( interpreted ) get_arguments then\n\n \\ Unload only if a path was passed\n dup if\n >r over r> swap\n c@ [char] - <> if\n 0 1 unload drop\n else\n s\" kernelname\" getenv? if ( a kernel has been loaded )\n 1 boot exit\n then\n load_kernel_and_modules\n ?dup if exit then\n 0 1 boot exit\n then\n else\n s\" kernelname\" getenv? if ( a kernel has been loaded )\n 1 boot exit\n then\n load_kernel_and_modules\n ?dup if exit then\n 0 1 boot exit\n then\n load_kernel_and_modules\n ?dup 0= if 0 1 boot then\n;\n\n: boot-conf\n 0= if ( interpreted ) get_arguments then\n 0 1 unload drop\n load_kernel_and_modules\n ?dup 0= if 0 1 autoboot then\n;\n\nalso forth definitions also builtins\n\nbuiltin: boot\nbuiltin: boot-conf\n\nonly forth definitions also support-functions\n\n\\ ***** check-password\n\\\n\\\tIf a password was defined, execute autoboot and ask for\n\\\tpassword if autoboot returns.\n\n: check-password\n password .addr @ if\n 0 autoboot\n false >r\n begin\n bell emit bell emit\n .\" Password: \"\n password .len @ read-password\n dup password .len @ = if\n 2dup password .addr @ password .len @\n compare 0= if r> drop true >r then\n then\n drop free drop\n r@\n until\n r> drop\n then\n;\n\n\\ ***** start\n\\\n\\ Initializes support.4th global variables, sets loader_conf_files,\n\\ process conf files, and, if any one such file was succesfully\n\\ read to the end, load kernel and modules.\n\n: start ( -- ) ( throws: abort & user-defined )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n \\ Will *NOT* try to load kernel and modules if no configuration file\n \\ was succesfully loaded!\n any_conf_read? if\n load_kernel\n load_modules\n then\n;\n\n\\ ***** initialize\n\\\n\\\tOverrides support.4th initialization word with one that does\n\\\teverything start one does, short of loading the kernel and\n\\\tmodules. Returns a flag\n\n: initialize ( -- flag )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n any_conf_read?\n;\n\n\\ ***** read-conf\n\\\n\\\tRead a configuration file, whose name was specified on the command\n\\\tline, if interpreted, or given on the stack, if compiled in.\n\n: (read-conf) ( addr len -- )\n conf_files .addr @ ?dup if free abort\" Fatal error freeing memory\" then\n strdup conf_files .len ! conf_files .addr !\n include_conf_files \\ Will recurse on new loader_conf_files definitions\n;\n\n: read-conf ( | addr len -- ) ( throws: abort & user-defined )\n state @ if\n \\ Compiling\n postpone (read-conf)\n else\n \\ Interpreting\n bl parse (read-conf)\n then\n; immediate\n\n\\ ***** enable-module\n\\\n\\ Turn a module loading on.\n\n: enable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n true r> module.flag !\n .\" will be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** disable-module\n\\\n\\ Turn a module loading off.\n\n: disable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n false r> module.flag !\n .\" will not be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** toggle-module\n\\\n\\ Turn a module loading on\/off.\n\n: toggle-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n r@ module.flag @ 0= dup r> module.flag !\n if\n .\" will be loaded.\" cr\n else\n .\" will not be loaded.\" cr\n then\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** show-module\n\\\n\\\tShow loading information about a module.\n\n: show-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n .\" Name: \" r@ module.name dup .addr @ swap .len @ type cr\n .\" Path: \" r@ module.loadname dup .addr @ swap .len @ type cr\n .\" Type: \" r@ module.type dup .addr @ swap .len @ type cr\n .\" Flags: \" r@ module.args dup .addr @ swap .len @ type cr\n .\" Before load: \" r@ module.beforeload dup .addr @ swap .len @ type cr\n .\" After load: \" r@ module.afterload dup .addr @ swap .len @ type cr\n .\" Error: \" r@ module.loaderror dup .addr @ swap .len @ type cr\n .\" Status: \" r> module.flag @ if .\" Load\" else .\" Don't load\" then cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ Words to be used inside configuration files\n\n: retry false ; \\ For use in load error commands\n: ignore true ; \\ For use in load error commands\n\n\\ Return to strict forth vocabulary\n\n: #type\n over - >r\n type\n r> spaces\n;\n\n: .? 2 spaces 2swap 15 #type 2 spaces type cr ;\n\n: ?\n ['] ? execute\n s\" boot-conf\" s\" load kernel and modules, then autoboot\" .?\n s\" read-conf\" s\" read a configuration file\" .?\n s\" enable-module\" s\" enable loading of a module\" .?\n s\" disable-module\" s\" disable loading of a module\" .?\n s\" toggle-module\" s\" toggle loading of a module\" .?\n s\" show-module\" s\" show module load data\" .?\n;\n\nonly forth also\n\n","old_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\ns\" arch-alpha\" environment? [if] [if]\n\ts\" loader_version\" environment? [if]\n\t\t11 < [if]\n\t\t\t.( Loader version 1.1+ required) cr\n\t\t\tabort\n\t\t[then]\n\t[else]\n\t\t.( Could not get loader version!) cr\n\t\tabort\n\t[then]\n[then] [then]\n\ns\" arch-i386\" environment? [if] [if]\n\ts\" loader_version\" environment? [if]\n\t\t10 < [if]\n\t\t\t.( Loader version 1.0+ required) cr\n\t\t\tabort\n\t\t[then]\n\t[else]\n\t\t.( Could not get loader version!) cr\n\t\tabort\n\t[then]\n[then] [then]\n\n256 dictthreshold ! \\ 256 cells minimum free space\n2048 dictincrease ! \\ 2048 additional cells each time\n\ninclude \/boot\/support.4th\n\n\\ ***** boot-conf\n\\\n\\\tPrepares to boot as specified by loaded configuration files.\n\nonly forth also support-functions also builtins definitions\n\n: boot\n 0= if ( interpreted ) get_arguments then\n\n \\ Unload only if a path was passed\n dup if\n >r over r> swap\n c@ [char] - <> if\n 0 1 unload drop\n else\n s\" kernelname\" getenv? if ( a kernel has been loaded )\n 1 boot exit\n then\n load_kernel_and_modules\n ?dup if exit then\n 0 1 boot exit\n then\n else\n s\" kernelname\" getenv? if ( a kernel has been loaded )\n 1 boot exit\n then\n load_kernel_and_modules\n ?dup if exit then\n 0 1 boot exit\n then\n load_kernel_and_modules\n ?dup 0= if 0 1 boot then\n;\n\n: boot-conf\n 0= if ( interpreted ) get_arguments then\n 0 1 unload drop\n load_kernel_and_modules\n ?dup 0= if 0 1 autoboot then\n;\n\nalso forth definitions also builtins\n\nbuiltin: boot\nbuiltin: boot-conf\n\nonly forth definitions also support-functions\n\n\\ ***** check-password\n\\\n\\\tIf a password was defined, execute autoboot and ask for\n\\\tpassword if autoboot returns.\n\n: check-password\n password .addr @ if\n 0 autoboot\n false >r\n begin\n bell emit bell emit\n .\" Password: \"\n password .len @ read-password\n dup password .len @ = if\n 2dup password .addr @ password .len @\n compare 0= if r> drop true >r then\n then\n drop free drop\n r@\n until\n r> drop\n then\n;\n\n\\ ***** start\n\\\n\\ Initializes support.4th global variables, sets loader_conf_files,\n\\ process conf files, and, if any one such file was succesfully\n\\ read to the end, load kernel and modules.\n\n: start ( -- ) ( throws: abort & user-defined )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n \\ Will *NOT* try to load kernel and modules if no configuration file\n \\ was succesfully loaded!\n any_conf_read? if\n load_kernel\n load_modules\n then\n;\n\n\\ ***** initialize\n\\\n\\\tOverrides support.4th initialization word with one that does\n\\\teverything start one does, short of loading the kernel and\n\\\tmodules. Returns a flag\n\n: initialize ( -- flag )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n any_conf_read?\n;\n\n\\ ***** read-conf\n\\\n\\\tRead a configuration file, whose name was specified on the command\n\\\tline, if interpreted, or given on the stack, if compiled in.\n\n: (read-conf) ( addr len -- )\n conf_files .addr @ ?dup if free abort\" Fatal error freeing memory\" then\n strdup conf_files .len ! conf_files .addr !\n include_conf_files \\ Will recurse on new loader_conf_files definitions\n;\n\n: read-conf ( | addr len -- ) ( throws: abort & user-defined )\n state @ if\n \\ Compiling\n postpone (read-conf)\n else\n \\ Interpreting\n bl parse (read-conf)\n then\n; immediate\n\n\\ ***** enable-module\n\\\n\\ Turn a module loading on.\n\n: enable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n true r> module.flag !\n .\" will be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** disable-module\n\\\n\\ Turn a module loading off.\n\n: disable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n false r> module.flag !\n .\" will not be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** toggle-module\n\\\n\\ Turn a module loading on\/off.\n\n: toggle-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n r@ module.flag @ 0= dup r> module.flag !\n if\n .\" will be loaded.\" cr\n else\n .\" will not be loaded.\" cr\n then\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** show-module\n\\\n\\\tShow loading information about a module.\n\n: show-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n .\" Name: \" r@ module.name dup .addr @ swap .len @ type cr\n .\" Path: \" r@ module.loadname dup .addr @ swap .len @ type cr\n .\" Type: \" r@ module.type dup .addr @ swap .len @ type cr\n .\" Flags: \" r@ module.args dup .addr @ swap .len @ type cr\n .\" Before load: \" r@ module.beforeload dup .addr @ swap .len @ type cr\n .\" After load: \" r@ module.afterload dup .addr @ swap .len @ type cr\n .\" Error: \" r@ module.loaderror dup .addr @ swap .len @ type cr\n .\" Status: \" r> module.flag @ if .\" Load\" else .\" Don't load\" then cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ Words to be used inside configuration files\n\n: retry false ; \\ For use in load error commands\n: ignore true ; \\ For use in load error commands\n\n\\ Return to strict forth vocabulary\n\n: #type\n over - >r\n type\n r> spaces\n;\n\n: .? 2 spaces 2swap 15 #type 2 spaces type cr ;\n\n: ?\n ['] ? execute\n s\" boot-conf\" s\" load kernel and modules, then autoboot\" .?\n s\" read-conf\" s\" read a configuration file\" .?\n s\" enable-module\" s\" enable loading of a module\" .?\n s\" disable-module\" s\" disable loading of a module\" .?\n s\" toggle-module\" s\" toggle loading of a module\" .?\n s\" show-module\" s\" show module load data\" .?\n;\n\nonly forth also\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"bd076d5da4a80a7701dd6ff16f842f574c3f04ef","subject":"'include' added","message":"'include' added\n","repos":"bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas","old_file":"KataDiversion_tests.fth","new_file":"KataDiversion_tests.fth","new_contents":"\\ KataDiversion tests, in Forth\n\nINCLUDE KataDiversion.ft\n\n","old_contents":"","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"00e85756662501467ff1a7c0b241f0882bf8f5b8","subject":" ?MAX-NB handles the negative case","message":" ?MAX-NB handles the negative case\n","repos":"bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas","old_file":"KataDiversion.fth","new_file":"KataDiversion.fth","new_contents":"\\ KataDiversion in Forth\n\n\\ power\n: ** ( n1 n2 -- n1_pow_n2 ) 1 SWAP ?DUP IF 0 DO OVER * LOOP THEN NIP ;\n\n\\ test if the given N has two adjacent 1 bits\n: ?TWO-ADJACENT-1-BITS ( n -- bool ) ;\n\n\\ return the maximum number which can be made with N (given) bits\n: ?MAX-NB ( n -- m ) DUP 2DUP ABS <> IF 0 NIP\n ELSE \n IF 2 SWAP ** NIP\n THEN\n THEN ;\n","old_contents":"\\ KataDiversion in Forth\n\n\\ power\n: ** ( n1 n2 -- n1_pow_n2 ) 1 SWAP ?DUP IF 0 DO OVER * LOOP THEN NIP ;\n\n\\ test if the given N has two adjacent 1 bits\n: ?TWO-ADJACENT-1-BITS ( n -- bool ) ;\n\n\\ return the maximum number which can be made with N (given) bits\n: ?MAX-NB ( n -- m ) DUP IF 2 SWAP ** NIP THEN ;\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"a7018c5db716504da404286c8b6372dde43fcd4e","subject":"More system words","message":"More system words\n","repos":"rm-hull\/byok3,rm-hull\/byok3","old_file":"src\/main\/resources\/forth\/system.fth","new_file":"src\/main\/resources\/forth\/system.fth","new_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\\n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n\n: COUNT dup 1+ swap c@ ;\n\n\\ Miscellaneous support words\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: <= ( a b -- f , true if A <= b ) > 0= ;\n: >= ( a b -- f , true if A >= b ) < 0= ;\n: NOT ( n -- !n , logical negation ) 0= ;\n: DNEGATE ( d -- -d , negate by doing 0-d )\n 0 swap -\n;\n: CELL+ ( n -- n+cell ) cell + ;\n: CELL- ( n -- n-cell ) cell - ;\n: CELL* ( n -- n*cell ) cells ;\n\n: CHAR+ ( n -- n+size_of_char ) 1+ ;\n\\ : CHARS ( n -- n*size_of_char, don't do anything ) ; immediate\n\n\\ useful stack manipulation words\n: -ROT ( a b c -- c a b ) rot rot ;\n: 3DUP ( a b c -- a b c a b c ) 2 pick 2 pick 2 pick ;\n\n\\ ------------------------------------------------------------------\n: ID. ( nfa -- ) count 31 and type ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: PAD ( -- addr ) here 128 + ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n\n: BETWEEN ( n lo hi -- flag , true if between lo & hi )\n >r over r> > >r\n < r> or 0=\n;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: ? ( -- ) @ . ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ ' (lit) , cell 1- , ] +\n [ ' (lit) , cell 1- invert , ] and ;\n\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n: ALLOT ( nbytes -- , allot space in dictionary ) dp +! align ;\n\n: C, ( c -- ) here c! 1 dp +! ;\n\\ : W, ( w -- ) dp @ even-up dup dp ! w! 2 dp +! ;\n\\ : , ( n -- , lay into dictionary ) align here ! cell allot ;\n\n: SEE ( -- )\n ' dup\n 16 + @ \\ offset in execution token for alloc size\n cells swap >body swap\n disassemble ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token )\n [compile] literal ( compile a call to literal )\n ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n: :NONAME ( -- xt , begin compilation of headerless secondary ) align here ] ;\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick )\n ?comp ' [compile] literal\n; immediate\n\n\n: (DOES>) ( xt -- , modify previous definition to execute code at xt )\n latest >body \\ get address of code for new word\n cell + \\ offset to second cell in create word\n ! \\ store execution token of DOES> code in new word\n;\n\n: DOES> ( -- , define execution code for CREATE word )\n 0 [compile] literal \\ dummy literal to hold xt\n here cell- \\ address of zero in literal\n compile (does>) \\ call (DOES>) from new creation word\n\t\t>r \\ move addrz to return stack so ; doesn't see stack garbage\n [compile] ; \\ terminate part of code before does>\n\t\tr>\n :noname ( addrz xt )\n swap ! \\ save execution token in literal\n; immediate\n\n0 1- constant -1\n0 2- constant -2\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 )\n swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 )\n dup cell+ @ swap @ ;\n\n: 2* ( n -- n*2 )\n 1 lshift\n;\n: 2\/ ( n -- n\/2 )\n 1 rshift\n;\n\n\n\\ define some useful constants ------------------------------\n1 0= constant FALSE\n0 0= constant TRUE\n32 constant BL\n\n\\ Stack data structure ----------------------------------------\n\\ This is a general purpose stack utility used to implement necessary\n\\ stacks for the compiler or the user. Not real fast.\n\\ These stacks grow up which is different then normal.\n\\ cell 0 - stack pointer, offset from pfa of word\n\\ cell 1 - limit for range checking\n\\ cell 2 - first data location\n\n: :STACK ( #cells -- )\n CREATE 2 cells , ( offset of first data location )\n dup , ( limit for range checking, not currently used )\n cells cell+ allot ( allot an extra cell for safety )\n;\n\n: >STACK ( n stack -- , push onto stack, postincrement )\n dup @ 2dup cell+ swap ! ( -- n stack offset )\n + !\n;\n\n: STACK> ( stack -- n , pop , predecrement )\n dup @ cell- 2dup swap !\n + @\n;\n\n: STACK@ ( stack -- n , copy )\n dup @ cell- + @\n;\n\n: STACK.PICK ( index stack -- n , grab Nth from top of stack )\n dup @ cell- +\n swap cells - \\ offset for index\n @\n;\n: STACKP ( stack -- ptr , to next empty location on stack )\n\tdup @ +\n;\n\n: 0STACKP ( stack -- , clear stack)\n 8 swap !\n;\n\n32 :stack ustack\nustack 0stackp\n\n\\ Define JForth like words.\n: >US ustack >stack ;\n: US> ustack stack> ;\n: US@ ustack stack@ ;\n: 0USP ustack 0stackp ;\n\n\n\n\\ DO LOOP ------------------------------------------------\n\n3 constant do_flag\n4 constant leave_flag\n5 constant ?do_flag\n\n: DO ( -- , loop-back do_flag jump-from ?do_flag )\n ?comp\n compile (do)\n here >us do_flag >us ( for backward branch )\n; immediate\n\n: ?DO ( -- , loop-back do_flag jump-from ?do_flag , on user stack )\n ?comp\n ( leave address to set for forward branch )\n compile (?do)\n here 0 ,\n here >us do_flag >us ( for backward branch )\n >us ( for forward branch ) ?do_flag >us\n; immediate\n\n: LEAVE ( -- addr leave_flag )\n compile (leave)\n here 0 , >us\n leave_flag >us\n; immediate\n\n: LOOP-FORWARD ( -us- jump-from ?do_flag -- )\n BEGIN\n us@ leave_flag =\n us@ ?do_flag =\n OR\n WHILE\n us> leave_flag =\n IF\n us> here over - cell+ swap !\n ELSE\n us> dup\n here swap -\n cell+ swap !\n THEN\n REPEAT\n;\n\n: LOOP-BACK ( loop-addr do_flag -us- )\n us> do_flag ?pairs\n us> here - here\n !\n cell allot\n;\n\n: LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (loop)\n loop-forward loop-back\n; immediate\n\n\\ : DOTEST 5 0 do 333 . loop 888 . ;\n\\ : ?DOTEST0 0 0 ?do 333 . loop 888 . ;\n\\ : ?DOTEST1 5 0 ?do 333 . loop 888 . ;\n\n: +LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (+loop)\n loop-forward loop-back\n; immediate\n\n: UNLOOP ( loop-sys -r- )\n r> \\ save return pointer\n rdrop rdrop\n >r\n;\n\n\n: RECURSE ( ? -- ? , call the word currently being defined )\n latest compile,\n; immediate\n\n: SPACE bl emit ;\n: SPACES 512 min 0 max 0 ?DO space LOOP ;\n: 0SP depth 0 ?do drop loop ;\n\n\\ : >NEWLINE ( -- , CR if needed )\n\\ out @ 0>\n\\ IF cr\n\\ THEN\n\\ ;\n\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 ) swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 ) dup cell+ @ swap @ ;\n\n: DABS ( d -- |d| )\n dup 0<\n IF dnegate\n THEN\n;\n\n: S>D ( s -- d , extend signed single precision to double )\n dup 0<\n IF -1\n ELSE 0\n THEN\n;\n\n: D>S ( d -- s ) drop ;\n\n: \/STRING ( addr len n -- addr' len' ) over min rot over + -rot - ;\n: PLACE ( addr len to -- , move string ) 3dup 1+ swap cmove c! drop ;\n\n: ASCII ( -- char, state smart )\n bl parse drop c@\n state @ 1 =\n IF [compile] literal\n ELSE\n THEN\n; immediate\n\n: CHAR ( -- char , interpret mode ) bl parse drop c@ ;\n: [CHAR] ( -- char , for compile mode )\n char [compile] literal\n; immediate\n\n: $TYPE ( $string -- ) count type ;\n: 'word ( -- addr ) here ;\n\n: EVEN ( addr -- addr' ) dup 1 and + ;\n\n: (C\") ( -- $addr ) r> dup count + aligned >r ;\n: (S\") ( -- c-addr cnt ) r> count 2dup + aligned >r ;\n: (.\") ( -- , type following string ) r> count 2dup + aligned >r type ;\n: \", ( addr len -- , place string into dict ) tuck 'word place 1+ allot align ;\n: ,\" ( -- ) 34 parse \", ;\n\n: .( ( --, type string delimited by parens )\n 41 parse type\n; immediate\n\n: .\" ( -- , type string )\n state @ 1 =\n IF compile (.\") ,\"\n ELSE 34 parse type\n THEN\n; immediate\n\n: .' ( -- , type string delimited by single quote )\n state @\n IF compile (.\") [char] ' parse \",\n ELSE [char] ' parse type\n THEN\n; immediate\n\n: C\" ( -- addr , return string address, ANSI )\n state @\n IF compile (c\") ,\"\n ELSE [char] \" parse pad place pad\n THEN\n; immediate\n\n: S\" ( -- , -- addr , return string address, ANSI )\n state @\n IF compile (s\") ,\"\n ELSE [char] \" parse pad place pad count\n THEN\n; immediate\n\n: \" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n: P\" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n\n\\ : \"\" ( -- addr )\n\\ state @\n\\ IF\n\\ compile (C\")\n\\ bl parse-word \",\n\\ ELSE\n\\ bl parse-word pad place pad\n\\ THEN\n\\ ; immediate\n\n: SLITERAL ( addr cnt -- , compile string )\n\tcompile (S\")\n\t\",\n; IMMEDIATE\n\n: $APPEND ( addr count $1 -- , append text to $1 )\n over >r\n dup >r\n count + ( -- a2 c2 end1 )\n swap cmove\n r> dup c@ ( a1 c1 )\n r> + ( -- a1 totalcount )\n swap c!\n;\n\n\\ ANSI word to replace [COMPILE] and COMPILE ----------------\n\\ : POSTPONE ( -- )\n\\\tbl word find\n\\\tdup 0=\n\\\tIF\n\\\t\t.\" Postpone could not find \" count type cr abort\n\\\tELSE\n\\\t\t0>\n\\\t\tIF compile, \\ immediate\n\\\t\tELSE (compile) \\ normal\n\\\t\tTHEN\n\\\tTHEN\n\\ ; immediate\n\n\\ -----------------------------------------------------------------\n\\ Auto Initialization\n: AUTO.INIT ( -- )\n\\ Kernel finds AUTO.INIT and executes it after loading dictionary.\n\\\t.\" Begin AUTO.INIT ------\" cr\n;\n: AUTO.TERM ( -- )\n\\ Kernel finds AUTO.TERM and executes it on bye.\n\\\t.\" End AUTO.TERM ------\" cr\n;\n\n\n: CLEARSTACK ( i*x -- )\n BEGIN depth\n WHILE drop\n REPEAT ;\n\nvariable pictured_output \\ hidden?\nvariable pictured_output_len \\ hidden?\n\n: <# ( -- ) pad pictured_output ! 0 pictured_output_len ! ;\n: #> ( -- addr n ) drop pictured_output @ pictured_output_len @ ;\n\n: HOLD ( c -- )\n pictured_output @ dup dup 1+ pictured_output_len @ cmove c!\n 1 pictured_output_len +!\n;\n\n\\ ------------------------ INPUT -------------------------------\n\n: SIGN ( n -- ) < 0 IF 45 hold THEN\n;\n\n: DIGIT ( n -- ascii )\n dup 10 < IF 48 ELSE 87 THEN + ;\n\n: # ( n -- n )\n base @ \/mod swap digit hold ;\n\n: #S ( n -- )\n BEGIN base @ \/mod dup\n WHILE swap digit hold\n REPEAT\n digit hold ;","old_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\\n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n\n: COUNT dup 1+ swap c@ ;\n\n\\ Miscellaneous support words\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: CELL+ ( n -- n+cell ) cell + ;\n: CELL- ( n -- n-cell ) cell - ;\n: CELL* ( n -- n*cell ) cells ;\n\n: CHAR+ ( n -- n+size_of_char ) 1+ ;\n\\ : CHARS ( n -- n*size_of_char, don't do anything ) ; immediate\n\n\\ useful stack manipulation words\n: -ROT ( a b c -- c a b ) rot rot ;\n: 3DUP ( a b c -- a b c a b c ) 2 pick 2 pick 2 pick ;\n\n\\ ------------------------------------------------------------------\n: ID. ( nfa -- ) count 31 and type ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: PAD ( -- addr ) here 128 + ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: ? ( -- ) @ . ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ ' (lit) , cell 1- , ] +\n [ ' (lit) , cell 1- invert , ] and ;\n\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n: ALLOT ( nbytes -- , allot space in dictionary ) dp +! align ;\n\n: C, ( c -- ) here c! 1 dp +! ;\n\\ : W, ( w -- ) dp @ even-up dup dp ! w! 2 dp +! ;\n\\ : , ( n -- , lay into dictionary ) align here ! cell allot ;\n\n: SEE ( -- )\n ' dup\n 16 + @ \\ offset in execution token for alloc size\n cells swap >body swap\n disassemble ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token )\n [compile] literal ( compile a call to literal )\n ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n: :NONAME ( -- xt , begin compilation of headerless secondary ) align here ] ;\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick )\n ?comp ' [compile] literal\n; immediate\n\n: RECURSE ( ? -- ? , call the word currently being defined )\n latest compile,\n; immediate\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 ) swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 ) dup cell+ @ swap @ ;\n\n: \/STRING ( addr len n -- addr' len' ) over min rot over + -rot - ;\n: PLACE ( addr len to -- , move string ) 3dup 1+ swap cmove c! drop ;\n\n: ASCII ( -- char, state smart )\n bl parse drop c@\n state @ 1 =\n IF [compile] literal\n ELSE\n THEN\n; immediate\n\n: CHAR ( -- char , interpret mode ) bl parse drop c@ ;\n: [CHAR] ( -- char , for compile mode )\n char [compile] literal\n; immediate\n\n: 'word ( -- addr ) here ;\n\n: (C\") ( -- $addr ) r> dup count + aligned >r ;\n: (S\") ( -- c-addr cnt ) r> count 2dup + aligned >r ;\n: (.\") ( -- , type following string ) r> count 2dup + aligned >r type ;\n: \", ( addr len -- , place string into dict ) tuck 'word place 1+ allot align ;\n: ,\" ( -- ) 34 parse \", ;\n\n: .( ( --, type string delimited by parens )\n 41 parse type\n; immediate\n\n: .\" ( -- , type string )\n state @ 1 =\n IF compile (.\") ,\"\n ELSE 34 parse type\n THEN\n; immediate\n\n: CLEARSTACK ( i*x -- )\n BEGIN depth\n WHILE drop\n REPEAT ;\n\nvariable pictured_output \\ hidden?\nvariable pictured_output_len \\ hidden?\n\n: <# ( -- ) pad pictured_output ! 0 pictured_output_len ! ;\n: #> ( -- addr n ) drop pictured_output @ pictured_output_len @ ;\n\n: HOLD ( c -- )\n pictured_output @ dup dup 1+ pictured_output_len @ cmove c!\n 1 pictured_output_len +!\n;\n\n: DIGIT ( n -- ascii )\n dup 10 < IF 48 ELSE 87 THEN + ;\n\n: SIGN ( n -- ) < 0 IF 45 hold THEN\n;\n: # ( n -- n )\n base @ \/mod swap digit hold ;\n\n: #S ( n -- )\n BEGIN base @ \/mod dup\n WHILE swap digit hold\n REPEAT\n digit hold ;\n\n: (DOES>) ( xt -- , modify previous definition to execute code at xt )\n latest >body \\ get address of code for new word\n cell + \\ offset to second cell in create word\n ! \\ store execution token of DOES> code in new word\n;\n\n: DOES> ( -- , define execution code for CREATE word )\n 0 [compile] literal \\ dummy literal to hold xt\n here cell- \\ address of zero in literal\n compile (does>) \\ call (DOES>) from new creation word\n\t\t>r \\ move addrz to return stack so ; doesn't see stack garbage\n [compile] ; \\ terminate part of code before does>\n\t\tr>\n :noname ( addrz xt )\n swap ! \\ save execution token in literal\n; immediate\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 )\n swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 )\n dup cell+ @ swap @ ;\n\n\n\\ Stack data structure ----------------------------------------\n\\ This is a general purpose stack utility used to implement necessary\n\\ stacks for the compiler or the user. Not real fast.\n\\ These stacks grow up which is different then normal.\n\\ cell 0 - stack pointer, offset from pfa of word\n\\ cell 1 - limit for range checking\n\\ cell 2 - first data location\n\n: :STACK ( #cells -- )\n CREATE 2 cells , ( offset of first data location )\n dup , ( limit for range checking, not currently used )\n cells cell+ allot ( allot an extra cell for safety )\n;\n\n: >STACK ( n stack -- , push onto stack, postincrement )\n dup @ 2dup cell+ swap ! ( -- n stack offset )\n + !\n;\n\n: STACK> ( stack -- n , pop , predecrement )\n dup @ cell- 2dup swap !\n + @\n;\n\n: STACK@ ( stack -- n , copy )\n dup @ cell- + @\n;\n\n: STACK.PICK ( index stack -- n , grab Nth from top of stack )\n dup @ cell- +\n swap cells - \\ offset for index\n @\n;\n: STACKP ( stack -- ptr , to next empty location on stack )\n\tdup @ +\n;\n\n: 0STACKP ( stack -- , clear stack)\n 8 swap !\n;\n\n32 :stack ustack\nustack 0stackp\n\n\\ Define JForth like words.\n: >US ustack >stack ;\n: US> ustack stack> ;\n: US@ ustack stack@ ;\n: 0USP ustack 0stackp ;\n\n\n\n\\ DO LOOP ------------------------------------------------\n\n3 constant do_flag\n4 constant leave_flag\n5 constant ?do_flag\n\n: DO ( -- , loop-back do_flag jump-from ?do_flag )\n ?comp\n compile (do)\n here >us do_flag >us ( for backward branch )\n; immediate\n\n: ?DO ( -- , loop-back do_flag jump-from ?do_flag , on user stack )\n ?comp\n ( leave address to set for forward branch )\n compile (?do)\n here 0 ,\n here >us do_flag >us ( for backward branch )\n >us ( for forward branch ) ?do_flag >us\n; immediate\n\n: LEAVE ( -- addr leave_flag )\n compile (leave)\n here 0 , >us\n leave_flag >us\n; immediate\n\n: LOOP-FORWARD ( -us- jump-from ?do_flag -- )\n BEGIN\n us@ leave_flag =\n us@ ?do_flag =\n OR\n WHILE\n us> leave_flag =\n IF\n us> here over - cell+ swap !\n ELSE\n us> dup\n here swap -\n cell+ swap !\n THEN\n REPEAT\n;\n\n: LOOP-BACK ( loop-addr do_flag -us- )\n us> do_flag ?pairs\n us> here - here\n !\n cell allot\n;\n\n: LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (loop)\n loop-forward loop-back\n; immediate\n\n\\ : DOTEST 5 0 do 333 . loop 888 . ;\n\\ : ?DOTEST0 0 0 ?do 333 . loop 888 . ;\n\\ : ?DOTEST1 5 0 ?do 333 . loop 888 . ;\n\n: +LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (+loop)\n loop-forward loop-back\n; immediate\n\n: UNLOOP ( loop-sys -r- )\n r> \\ save return pointer\n rdrop rdrop\n >r\n;","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"3c85e7ee70453744a3e1d5ea98967429495c3c69","subject":"Update test.4th","message":"Update test.4th","repos":"AshleyF\/Forthkit,AshleyF\/Forthkit,AshleyF\/Forthkit","old_file":"hardware\/register\/test.4th","new_file":"hardware\/register\/test.4th","new_contents":"( simple assembler\/VM test - capitalize [-32] console input )\n( requires assembler )\n\n0 const u\n1 const c\n\n 32 u ldc,\n label &start\n c in,\n c u c sub,\n c out,\n&start jump,\n\nassemble\n","old_contents":"( simple assembler\/VM test - capitalize [-32] console input )\n\n0 const u\n1 const c\n\n 32 u ldc,\n label &start\n c in,\n c u c sub,\n c out,\n&start jump,\n\nassemble\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"70b6b9d2d3898131891a12d5ee111938c1bb0e85","subject":"We need a word to fetch the latest from the quadrature encoder.","message":"We need a word to fetch the latest from the quadrature encoder.","repos":"rbsexton\/gecko,rbsexton\/gecko,rbsexton\/gecko","old_file":"zero\/clock-umb\/forth\/Clock.fth","new_file":"zero\/clock-umb\/forth\/Clock.fth","new_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( n -- ) \n icroot inter.rtcsem 0 over ! \\ Reset the free-running counter.\n swap \\ addr n -- \n 0 do \n dup @resetex! ?dup if advance else [asm wfi asm] then\n loop\n drop\n;\n\n: CLOCKINIT ( -- )\n #1000 needlemax\n 2dup ! 4 + 2dup ! 4 + ! \n;\n \n\\ Heres where we advance any needles.\n: ADVANCE ( n -- )\n pwm0@ + pwm0! \n;\n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nudata\ncreate NEEDLEMAX 3 cells allot\ncdata\n\n: ++NEEDLE_S ; \\ Called ever time.\n: ++NEEDLE_M ; \\ Every time we roll the seconds.\n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Quadrature\n\\ ----------------------------------------------------------\n\n: QUAD@ ( addr -- n ) \\ Fetch and zero\n @off [asm sxth tos, tos asm] ;\n \n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxsec \\ Max Value for secs+minutes\n\tint hms.maxhour \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_m \\ increment the minutes + hours\nend-struct\n\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_s , ' ++needle_m , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n\\ UNTESTED\n: ADVANCETIME ( struct-addr -- )\n dup hms.w_s @ execute \\ Invoke the official update word.\n 1 over hms.subsec +! \\ Increment\n dup hms.subsec @\n over hms.maxsubsec @ < if drop exit then \\ If less then max, we're done\n 0 over hms.subsec ! \\ Reset the subsecs \n\n dup hms.w_m @ execute\n 1 over hms.s +!\n dup hms.s @ over hms.maxsec @ < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n 1 over hms.m +!\n dup hms.m @ over hms.maxsec @ < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ over hms.maxhour @ < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ----------------------------------------------------------\n\\ The interpolator. \n\\ Implement bresenhams algorithm. All of this code already\n\\ exists in C, but we'll own the data structures. They contain\n\\ A total of 4 words - fixed, err, num, & denom\n\\ ----------------------------------------------------------\n\nudata \ncreate interp_a 4 cells allot\ncreate interp_b 4 cells allot\ncreate interp_c 4 cells allot\ncdata\n\n#16 #60 * equ raw_sec\n#10 #100 * equ raw_dsec\n\n: INTERP-INIT ( -- )\n (interp_init)\n dup interp_a #850 raw_sec call3-- \n dup interp_b #850 #60 call3-- \n interp_c #850 #12 call3--\n;\n\n: INTERP-NEXT ( addr -- n )\n (interp_next) swap call1--1\n\n\\ ============================ UNTESTED =======================\n\\ VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n\n","old_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( n -- ) \n icroot inter.rtcsem 0 over ! \\ Reset the free-running counter.\n swap \\ addr n -- \n 0 do \n dup @resetex! ?dup if advance else [asm wfi asm] then\n loop\n drop\n;\n\n: CLOCKINIT ( -- )\n #1000 needlemax\n 2dup ! 4 + 2dup ! 4 + ! \n;\n \n\\ Heres where we advance any needles.\n: ADVANCE ( n -- )\n pwm0@ + pwm0! \n;\n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nudata\ncreate NEEDLEMAX 3 cells allot\ncdata\n\n: ++NEEDLE_S ; \\ Called ever time.\n: ++NEEDLE_M ; \\ Every time we roll the seconds.\n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxsec \\ Max Value for secs+minutes\n\tint hms.maxhour \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_m \\ increment the minutes + hours\nend-struct\n\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_s , ' ++needle_m , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n\\ UNTESTED\n: ADVANCETIME ( struct-addr -- )\n dup hms.w_s @ execute \\ Invoke the official update word.\n 1 over hms.subsec +! \\ Increment\n dup hms.subsec @\n over hms.maxsubsec @ < if drop exit then \\ If less then max, we're done\n 0 over hms.subsec ! \\ Reset the subsecs \n\n dup hms.w_m @ execute\n 1 over hms.s +!\n dup hms.s @ over hms.maxsec @ < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n 1 over hms.m +!\n dup hms.m @ over hms.maxsec @ < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ over hms.maxhour @ < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ----------------------------------------------------------\n\\ The interpolator. \n\\ Implement bresenhams algorithm. All of this code already\n\\ exists in C, but we'll own the data structures. They contain\n\\ A total of 4 words - fixed, err, num, & denom\n\\ ----------------------------------------------------------\n\nudata \ncreate interp_a 4 cells allot\ncreate interp_b 4 cells allot\ncreate interp_c 4 cells allot\ncdata\n\n#16 #60 * equ raw_sec\n#10 #100 * equ raw_dsec\n\n: INTERP-INIT ( -- )\n (interp_init)\n dup interp_a #850 raw_sec call3-- \n dup interp_b #850 #60 call3-- \n interp_c #850 #12 call3--\n;\n\n: INTERP-NEXT ( addr -- n )\n (interp_next) swap call1--1\n\n\\ ============================ UNTESTED =======================\n\\ VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"e4f18b5bde6e819c49811af2c2d693bc6db85665","subject":"Basic, working state machine for needle calibration. Needs to save the results.","message":"Basic, working state machine for needle calibration. Needs to save the results.","repos":"rbsexton\/gecko,rbsexton\/gecko,rbsexton\/gecko","old_file":"zero\/clock-umb\/forth\/Clock.fth","new_file":"zero\/clock-umb\/forth\/Clock.fth","new_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( -- )\n load-defaults \n icroot 0 over inter.rtcsem ! \\ Reset the free-running counters.\n 0 over inter.rtcdsem ! \\ Reset the free-running counters.\n\n begin \n \tdup inter.rtcsem @offex! ?dup if advancehms then\n \tdup inter.rtcdsem @offex! ?dup if advancedhms then\n [asm wfi asm]\n uiupdate if use-uivals else use-clockvals then \n key? until drop\n;\n \n\\ These two contain loops to ensure that we don't\n\\ drop any timer ticks on the floor.\n: ADVANCEHMS ( n -- ) 0 do hms advancetime loop ;\n: ADVANCEDHMS ( n -- ) 0 do dhms advancetime loop ;\n \n: LOAD-DEFAULTS ( -- )\n interp-init\n;\n\n\\ ----------------------------------------------------------\n\\ Define the structures before they get used.\n\\ ----------------------------------------------------------\nstruct ODN \\ On-Deck Needle \n\tint odn.s\n\tint odn.m\n\tint odn.h\nend-struct\n\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxsec \\ Max Value for secs+minutes\n\tint hms.maxhour \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_m \\ increment the minutes + hours\nend-struct\n\nstruct _interp_set\n\t4 cells field interp.a\n\t4 cells field interp.b\n\t4 cells field interp.c\nend-struct\n\n\\ ----------------------------------------------------------\n\\ Defaults get saved in the user data page.\n\\ ----------------------------------------------------------\n: NVRAMVALID? ( addr -- t\/f ) \n\\ *G See if there is valid data in the NVRAM.\n\\ ** It consists of 3 words. If any of them are \n\\ ** set to 0xffff:ffff, we go with the defaults.\n _USERDATA\n dup @ -1 <> \n over 4 + @ -1 <> and\n swap 8 + @ -1 <> and\n;\n\n: _NVRAMLOAD ( -- ) \n\\ *G Pull the needle maximums from flash.\n $C 0 do I ud@ needle_max I + ! 4 +loop \n; \n\n: NVRAM! ( -- )\n\\ *G Save the contents of the needle cal values.\n 0 UDPAGE_ERASE\n needle_max\n $C 0 do dup I + @ I ud! 4 +loop\n drop \n;\n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nidata\ncreate ODN_HMS odn allot \\ On-Deck, HMS\ncreate ODN_DHMS odn allot \\ On-Deck, DHMS\ncreate ODN_UI odn allot \\ On-Deck, Generated by the UI.\ncdata\n\nidata \\ Has to match an odn.\ncreate NEEDLE_MAX #850 , #850 , #850 ,\ncdata\n\n(( \n: interp-next drop 1 ; \n: interp-reset drop .\" Reset\" ; \n\t\n))\n\n: RANGECHECK ( max n -- n or zero ) 2dup <= if 2drop 0 else swap drop then ; \n: CLIP ( n -- n) \\ Force the contents to be legal ( 0-999 )\n dup 0 < if drop 0 exit then \n dup #999 > if drop #999 then \n;\n \n: INTER-BUMP ( max old interp -- new )\n\\ *G Get the next value from the interpolator, and \n\\ ** reset the interpolator if it wraps around to zero.\n >R R@ interp-next \\ Get the max \n + rangecheck \n dup 0= if R> interp-reset else R> drop then \n ; \n\n: NFETCH ( odn off -- max old )\n\\ *G Combine the current value with the maximum.\n >R R@ \\ stash the offset.\n + @ \\ Calculate the offset address, get the current val.\n needle_max R> + @\n swap \n;\n\n: ++NEEDLE_S \\ Called every time.\n odn_hms 0 odn.s nfetch ( max old )\n\tinterp_hms interp.a inter-bump ( new )\n\todn_hms odn.s ! \n\t;\n\n: ++NEEDLE_M ( -- )\n\\ *G Every time we roll the seconds, bump the minutes and the hour\n\todn_hms 0 odn.m nfetch ( max old )\n\tinterp_hms interp.b inter-bump \n\todn_hms odn.m ! \n\n\todn_hms 0 odn.h nfetch ( max old )\n\tinterp_hms interp.c inter-bump \n\todn_hms odn.h ! \n\t;\n\n: ++NEEDLE_DS ; \\ Called every time.\n: ++NEEDLE_DM ; \\ Every time we roll the seconds.\n\n: _USE ( odn-addr -- ) \n dup odn.s w@ pwm0!\n dup odn.m w@ pwm1!\n odn.h w@ pwm2!\n ;\n\n: USE-CLOCKVALS odn_hms _use ; \n: USE-UIVALS odn_ui _use ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Quadrature\n\\ ----------------------------------------------------------\n\n_timer1 $24 + equ QUAD-IN\n\n\\ The Quadrature encoder produces two per detent.\n: QUAD@ ( -- n ) \\ Fetch and zero\n quad-in @off \n [asm sxth tos, tos asm]\n [asm asr .s tos, tos, # 1 asm] \\ Divide by two,\n ;\n \n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_ds , ' ++needle_dm , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n: ADVANCETIME ( struct-addr -- )\n dup hms.w_s @ execute \\ Invoke the official update word.\n 1 over hms.subsec +! \\ Increment\n dup hms.subsec @\n over hms.maxsubsec @ < if drop exit then \\ If less then max, we're done\n 0 over hms.subsec ! \\ Reset the subsecs \n\n 1 over hms.s +!\n dup hms.s @ over hms.maxsec @ < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n dup hms.w_m @ execute\n 1 over hms.m +!\n dup hms.m @ over hms.maxsec @ < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ over hms.maxhour @ < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ----------------------------------------------------------\n\\ The interpolator. \n\\ Implement bresenhams algorithm. All of this code already\n\\ exists in C, but we'll own the data structures. They contain\n\\ A total of 4 words - fixed, err, num, & denom\n\\ ----------------------------------------------------------\nudata \ncreate interp_hms _interp_set allot\ncreate interp_dhms _interp_set allot \ncdata\n\n#16 #60 * equ raw_sec\n#10 #100 * equ raw_dsec\n\n: INTERP-INIT ( -- )\n (interp_init) interp_hms\n 2dup interp.a needle_max @ raw_sec call3-- \n 2dup interp.b needle_max 4 + @ #60 call3-- \n interp.c needle_max 8 + @ #12 call3--\n\n (interp_init) interp_dhms\n 2dup interp.a needle_max @ raw_dsec call3-- \n 2dup interp.b needle_max 4 + @ #100 call3-- \n interp.c needle_max 8 + @ #10 call3--\n;\n\n\\ Call the reset fn.\n: INTERP-RESET ( interp_addr -- )\n (interp_reset) swap call1-- \n;\n\n: INTERP-NEXT ( addr -- n )\n (interp_next) swap call1--n\n;\n\n\n\\ ============================ UNTESTED =======================\n\\ VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n\n\\ ----------------------------------------------------------\n\\ User Interface\n\\ ----------------------------------------------------------\nvariable uistate\nvariable uicount \n\n_GPIO $64 + equ _BUTTONIO\n: BUTTONUP? ( -- t\/f ) _buttonio @ 1 and ; \n: BUTTONDOWN? ( -- t\/f ) buttonup? 1 xor ; \n\n\\ The wrapper for all of the UI stuff.\n\\ Returns true if the UI is active - ie, use the values generated by the UI.\n: UIUPDATE ( -- t\/f )\n StateHandlers uistate @ + @ execute \n; \n\n: uitest \n uistate @ 4 \/ . .\" ->\" uiupdate uistate @ 4 \/ .\n uicount @ . if .\" True\" else .\" False\" then \n; \n\n\\ -----------------------------------------------\n\\ State numbers. These are defined x4 so that\n\\ we can just use the state number as an index \n\\ into a table of words.\n\\ -----------------------------------------------\n0 4 * equ _s_init\n1 4 * equ _s_b1\n2 4 * equ _s_1sec\n\n3 4 * equ _s_set_h\n4 4 * equ _s_pendset_m\n5 4 * equ _s_setmin\n\n6 4 * equ _s_pendcal0\n7 4 * equ _s_cal0\n8 4 * equ _s_pendcalh\n9 4 * equ _s_calh\n10 4 * equ _s_pendcalm\n11 4 * equ _s_calm\n12 4 * equ _s_pendcals\n13 4 * equ _s_cals\n\n4 equ downcount_1s\n16 equ downcount_3s \n\n\\ All of the state handlers.\n\\ Everybody needs to know the state of the button, so that must\n\\ get passed in, thus they all look like this:\n\\ state ( t\/f -- t\/f )\n: shInit false \n buttondown? if \n _s_b1 uistate !\n uicount off \\ Reset this.\n then\n ;\n\n\\ Waiting for a full second to go by.\n: shB1 false\n buttonup? if _s_init uistate ! exit then\n \\ The Button is down. \n uicount @ downcount_1s >= if\n _s_1sec uistate !\n else \n 1 uicount +!\n\tthen\n ;\n\n\\ We're in the 1 second state\n: sh1sec true \n buttonup? if _s_set_h uistate ! exit then\n uicount @ downcount_3s >= if\n _s_pendcal0 uistate !\n else \n 1 uicount +!\n\tthen \n;\n\n\\ -------------------------------------------------\n\\ Setting the time\n\\ -------------------------------------------------\n: shSetH true buttondown? if _s_pendset_m uistate ! exit then ;\n\n: shPendSetM true buttonup? if _s_setmin uistate ! then ;\n: shSetMin true buttondown? if _s_init uistate ! exit then ;\n\n\\ -------------------------------------------------\n\\ Calibration\n\\ -------------------------------------------------\n: shPendCal0 true buttonup? if _s_cal0 uistate ! helpODNClear then ;\n: shCal0 true buttondown? if _s_pendcalh uistate ! exit then ;\n\n: shPendCalH true buttonup? if _s_calh uistate ! helpODNMid then ; \n: shCalH true buttondown? if _s_pendcalm uistate ! exit then \n odn_ui odn.h helpQuad@ ; \n\n: shPendCalM true buttonup? if _s_calm uistate ! then ; \n: shCalM true buttondown? if _s_pendcals uistate ! exit then \n odn_ui odn.m helpQuad@ ; \n\n: shPendCalS true buttonup? if _s_cals uistate ! then ; \n: shCalS true buttondown? if _s_init uistate ! exit then \n odn_ui odn.s helpQuad@ ; \n\n\\ -------------------------------------------------\n\\ Helpers\n\\ -------------------------------------------------\n: helpODNClear ( -- ) \\ Set them all to zero\n odn_ui odn bounds do I off 4 +loop ; \n: helpODNMid ( -- ) \\ Set them all to 500\n odn_ui odn bounds do #750 I ! 4 +loop ; \n: helpQuad@ ( addr -- ) \\ update a location with the quadrature value\n dup @ quad@ + clip swap ! ;\n\n\ncreate StateHandlers \n' shInit , \n' shB1 ,\n' sh1sec ,\n\n' shSetH ,\n' shPendSetM , ' shSetMin ,\n\n' shPendCal0 , ' shCal0 ,\n' shPendCalH , ' shCalH , \n' shPendCalM , ' shCalM , \n' shPendCalS , ' shCalS , \n\n\\ -------------------------------------------------\n\\ Setting the time.\n\\ -------------------------------------------------\nvariable adj_i \\ THe working index into the points array.\n\nudata \ncreate adj_points #50 cells allot \\ 100 16-bit words. \ncreate interp_set _interp_set allot\ncdata \n\n\\ Generate a list of points.\n: MAKE-SET-LIST ( max steps ) \n 2dup \n >R (interp_init) swap interp_set swap R> call3--\n\n \\ Since zero is first, do the w! first.\n swap drop 0 swap \\ Keep a running counter.\n 0 do\n dup I adj_points[]! \\ Save the existing value\n interp_set interp-next + \n loop\n drop\n ;\n\n: ADJ_POINTS[]! ( data index -- ) 2* adj_points + w! ;\n: ADJ_POINTS[]@ ( index -- n ) 2* adj_points + w@ ;\n","old_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( -- )\n load-defaults \n icroot 0 over inter.rtcsem ! \\ Reset the free-running counters.\n 0 over inter.rtcdsem ! \\ Reset the free-running counters.\n\n begin \n \tdup inter.rtcsem @offex! ?dup if advancehms then\n \tdup inter.rtcdsem @offex! ?dup if advancedhms then\n [asm wfi asm]\n uiupdate if use-uivals else use-clockvals then \n key? until drop\n;\n \n\\ These two contain loops to ensure that we don't\n\\ drop any timer ticks on the floor.\n: ADVANCEHMS ( n -- ) 0 do hms advancetime loop ;\n: ADVANCEDHMS ( n -- ) 0 do dhms advancetime loop ;\n \n: LOAD-DEFAULTS ( -- )\n interp-init\n;\n\n\\ ----------------------------------------------------------\n\\ Define the structures before they get used.\n\\ ----------------------------------------------------------\nstruct ODN \\ On-Deck Needle \n\tint odn.s\n\tint odn.m\n\tint odn.h\nend-struct\n\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxsec \\ Max Value for secs+minutes\n\tint hms.maxhour \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_m \\ increment the minutes + hours\nend-struct\n\nstruct _interp_set\n\t4 cells field interp.a\n\t4 cells field interp.b\n\t4 cells field interp.c\nend-struct\n\n\\ ----------------------------------------------------------\n\\ Defaults get saved in the user data page.\n\\ ----------------------------------------------------------\n: NVRAMVALID? ( addr -- t\/f ) \n\\ *G See if there is valid data in the NVRAM.\n\\ ** It consists of 3 words. If any of them are \n\\ ** set to 0xffff:ffff, we go with the defaults.\n _USERDATA\n dup @ -1 <> \n over 4 + @ -1 <> and\n swap 8 + @ -1 <> and\n;\n\n: _NVRAMLOAD ( -- ) \n\\ *G Pull the needle maximums from flash.\n $C 0 do I ud@ needle_max I + ! 4 +loop \n; \n\n: NVRAM! ( -- )\n\\ *G Save the contents of the needle cal values.\n 0 UDPAGE_ERASE\n needle_max\n $C 0 do dup I + @ I ud! 4 +loop\n drop \n;\n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nidata\ncreate ODN_HMS odn allot \\ On-Deck, HMS\ncreate ODN_DHMS odn allot \\ On-Deck, DHMS\ncreate ODN_UI odn allot \\ On-Deck, Generated by the UI.\ncdata\n\nidata \\ Has to match an odn.\ncreate NEEDLE_MAX #850 , #850 , #850 ,\ncdata\n\n(( \n: interp-next drop 1 ; \n: interp-reset drop .\" Reset\" ; \n\t\n))\n\n: RANGECHECK ( max n -- n or zero ) 2dup <= if 2drop 0 else swap drop then ; \n\n: INTER-BUMP ( max old interp -- new )\n\\ *G Get the next value from the interpolator, and \n\\ ** reset the interpolator if it wraps around to zero.\n >R R@ interp-next \\ Get the max \n + rangecheck \n dup 0= if R> interp-reset else R> drop then \n ; \n\n: NFETCH ( odn off -- max old )\n\\ *G Combine the current value with the maximum.\n >R R@ \\ stash the offset.\n + @ \\ Calculate the offset address, get the current val.\n needle_max R> + @\n swap \n;\n\n: ++NEEDLE_S \\ Called every time.\n odn_hms 0 odn.s nfetch ( max old )\n\tinterp_hms interp.a inter-bump ( new )\n\todn_hms odn.s ! \n\t;\n\n: ++NEEDLE_M ( -- )\n\\ *G Every time we roll the seconds, bump the minutes and the hour\n\todn_hms 0 odn.m nfetch ( max old )\n\tinterp_hms interp.b inter-bump \n\todn_hms odn.m ! \n\n\todn_hms 0 odn.h nfetch ( max old )\n\tinterp_hms interp.c inter-bump \n\todn_hms odn.h ! \n\t;\n\n: ++NEEDLE_DS ; \\ Called every time.\n: ++NEEDLE_DM ; \\ Every time we roll the seconds.\n\n: _USE ( odn-addr -- ) \n dup odn.s w@ pwm0!\n dup odn.m w@ pwm1!\n odn.h w@ pwm2!\n ;\n\n: USE-CLOCKVALS odn_hms _use ; \n: USE-UIVALS odn_ui _use ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Quadrature\n\\ ----------------------------------------------------------\n\n_timer1 $24 + equ QUAD-IN\n\n\\ The Quadrature encoder produces two per detent.\n: QUAD@ ( -- n ) \\ Fetch and zero\n quad-in @off \n [asm sxth tos, tos asm]\n [asm asr .s tos, tos, # 1 asm] \\ Divide by two,\n ;\n \n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_ds , ' ++needle_dm , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n: ADVANCETIME ( struct-addr -- )\n dup hms.w_s @ execute \\ Invoke the official update word.\n 1 over hms.subsec +! \\ Increment\n dup hms.subsec @\n over hms.maxsubsec @ < if drop exit then \\ If less then max, we're done\n 0 over hms.subsec ! \\ Reset the subsecs \n\n 1 over hms.s +!\n dup hms.s @ over hms.maxsec @ < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n dup hms.w_m @ execute\n 1 over hms.m +!\n dup hms.m @ over hms.maxsec @ < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ over hms.maxhour @ < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ----------------------------------------------------------\n\\ The interpolator. \n\\ Implement bresenhams algorithm. All of this code already\n\\ exists in C, but we'll own the data structures. They contain\n\\ A total of 4 words - fixed, err, num, & denom\n\\ ----------------------------------------------------------\nudata \ncreate interp_hms _interp_set allot\ncreate interp_dhms _interp_set allot \ncdata\n\n#16 #60 * equ raw_sec\n#10 #100 * equ raw_dsec\n\n: INTERP-INIT ( -- )\n (interp_init) interp_hms\n 2dup interp.a needle_max @ raw_sec call3-- \n 2dup interp.b needle_max 4 + @ #60 call3-- \n interp.c needle_max 8 + @ #12 call3--\n\n (interp_init) interp_dhms\n 2dup interp.a needle_max @ raw_dsec call3-- \n 2dup interp.b needle_max 4 + @ #100 call3-- \n interp.c needle_max 8 + @ #10 call3--\n;\n\n\\ Call the reset fn.\n: INTERP-RESET ( interp_addr -- )\n (interp_reset) swap call1-- \n;\n\n: INTERP-NEXT ( addr -- n )\n (interp_next) swap call1--n\n;\n\n\n\\ ============================ UNTESTED =======================\n\\ VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n\n\\ ----------------------------------------------------------\n\\ User Interface\n\\ ----------------------------------------------------------\nvariable uistate\nvariable uicount \n\n_GPIO $64 + equ _BUTTONIO\n: BUTTONUP? ( -- t\/f ) _buttonio @ 1 and ; \n: BUTTONDOWN? ( -- t\/f ) buttonup? 1 xor ; \n\n\\ The wrapper for all of the UI stuff.\n\\ Returns true if the UI is active - ie, use the values generated by the UI.\n: UIUPDATE ( -- t\/f )\n StateHandlers uistate @ + @ execute \n; \n\n\\ -----------------------------------------------\n\\ State numbers. These are defined x4 so that\n\\ we can just use the state number as an index \n\\ into a table of words.\n\\ -----------------------------------------------\n0 4 * equ _s_init\n1 4 * equ _s_b1\n2 4 * equ _s_1sec\n\n3 4 * equ _s_set_h\n4 4 * equ _s_pendset_m\n5 4 * equ _s_setmin\n\n6 4 * equ _s_pendcal0\n7 4 * equ _s_cal0\n8 4 * equ _s_pendcalh\n9 4 * equ _s_calh\n10 4 * equ _s_pendcalm\n11 4 * equ _s_calm\n12 4 * equ _s_pendcals\n13 4 * equ _s_cals\n\n4 equ downcount_1s\n16 equ downcount_3s \n\n\\ All of the state handlers.\n\\ Everybody needs to know the state of the button, so that must\n\\ get passed in, thus they all look like this:\n\\ state ( t\/f -- t\/f )\n: shInit false \n buttondown? if \n _s_b1 uistate !\n uicount off \\ Reset this.\n then\n ;\n\n\\ Waiting for a full second to go by.\n: shB1 false\n buttonup? if _s_init uistate ! exit then\n \\ The Button is down. \n uicount @ downcount_1s >= if\n _s_1sec uistate !\n else \n 1 uicount +!\n\tthen\n ;\n\n\\ We're in the 1 second state\n: sh1sec true \n buttonup? if _s_set_h uistate ! exit then\n uicount @ downcount_3s >= if\n _s_pendcal0 uistate !\n else \n 1 uicount +!\n\tthen \n;\n\n\\ -------------------------------------------------\n\\ Setting the time\n\\ -------------------------------------------------\n: shSetH true buttondown? if _s_pendset_m uistate ! exit then ;\n\n: shPendSetM true buttonup? if _s_setmin uistate ! then ;\n: shSetMin true buttondown? if _s_init uistate ! exit then ;\n\n\\ -------------------------------------------------\n\\ Calibration\n\\ -------------------------------------------------\n: shPendCal0 true buttonup? if _s_cal0 uistate ! then ;\n: shCal0 true buttondown? if _s_pendcalh uistate ! exit then ;\n\n: shPendCalH true buttonup? if _s_calh uistate ! then ; \n: shCalH true buttondown? if _s_pendcalm uistate ! exit then ; \n\n: shPendCalM true buttonup? if _s_calm uistate ! then ; \n: shCalM true buttondown? if _s_pendcals uistate ! exit then ; \n\n: shPendCalS true buttonup? if _s_calm uistate ! then ; \n: shCalS true buttondown? if _s_init uistate ! exit then ; \n\\ -------------------------------------------------\n\\ Helpers\n\\ -------------------------------------------------\n: helpODNClear ( -- ) \\ Set them all to zero\n odn_ui odn bounds do I off 4 +loop ; \n\ncreate StateHandlers \n' shInit , \n' shB1 ,\n' sh1sec ,\n\n' shSetH ,\n' shPendSetM , ' shSetMin ,\n\n' shPendCal0 , ' shCal0 ,\n' shPendCalH , ' shCalH , \n' shPendCalM , ' shCalM , \n' shPendCalS , ' shCalS , \n\n\\ -------------------------------------------------\n\\ Setting the time.\n\\ -------------------------------------------------\nvariable adj_i \\ THe working index into the points array.\n\nudata \ncreate adj_points #50 cells allot \\ 100 16-bit words. \ncreate interp_set _interp_set allot\ncdata \n\n\\ Generate a list of points.\n: MAKE-SET-LIST ( max steps ) \n 2dup \n >R (interp_init) swap interp_set swap R> call3--\n\n \\ Since zero is first, do the w! first.\n swap drop 0 swap \\ Keep a running counter.\n 0 do\n dup I adj_points[]! \\ Save the existing value\n interp_set interp-next + \n loop\n drop\n ;\n\n: ADJ_POINTS[]! ( data index -- ) 2* adj_points + w! ;\n: ADJ_POINTS[]@ ( index -- n ) 2* adj_points + w@ ;\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"4c854436f76409a02f1fc24fb800fe96fd8e8619","subject":"added compile and conditionals","message":"added compile and conditionals","repos":"rm-hull\/byok,rm-hull\/byok,rm-hull\/byok,rm-hull\/byok","old_file":"forth\/src\/forth\/system.fth","new_file":"forth\/src\/forth\/system.fth","new_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\ \n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: CELL 1 ;\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: CELL+ ( x -- x+cell ) cell + ;\n: CELL- ( x -- x-cell ) cell - ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: PAD ( -- addr ) here 128 + ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n \n: COUNT dup 1 + swap c@ ;\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ cell 1- ] literal +\n [ cell 1- invert ] literal and ;\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token ) \n [compile] literal ( compile a call to literal )\n ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n: :NONAME ( -- xt , begin compilation of headerless secondary ) align here ] ;\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick ) ?comp ' [compile] literal ; immediate\n\n\n","old_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Foth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\ \n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: COUNT dup 1 + swap c@ ;\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: CONDITIONAL_KEY 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: r\n\\ convert lower to upper\n\tdup ascii a < not\n\tIF\n\t\tascii a - ascii A +\n\tTHEN\n\\\n\tdup dup ascii A 1- >\n\tIF ascii A - ascii 9 + 1+\n\tELSE ( char char )\n\t\tdup ascii 9 >\n\t\tIF\n\t\t\t( between 9 and A is bad )\n\t\t\tdrop 0 ( trigger error below )\n\t\tTHEN\n\tTHEN\n\tascii 0 -\n\tdup r> <\n\tIF dup 1+ 0>\n\t\tIF nip true\n\t\tELSE drop FALSE\n\t\tTHEN\n\tELSE drop FALSE\n\tTHEN\n;\n\n: >NUMBER ( ud1 c-addr1 u1 -- ud2 c-addr2 u2 , convert till bad char , CORE )\n\t>r\n\tBEGIN\n\t\tr@ 0> \\ any characters left?\n\t\tIF\n\t\t\tdup c@ base @\n\t\t\tdigit ( ud1 c-addr , n true | char false )\n\t\t\tIF\n\t\t\t\tTRUE\n\t\t\tELSE\n\t\t\t\tdrop FALSE\n\t\t\tTHEN\n\t\tELSE\n\t\t\tfalse\n\t\tTHEN\n\tWHILE ( -- ud1 c-addr n )\n\t\tswap >r ( -- ud1lo ud1hi n )\n\t\tswap base @ ( -- ud1lo n ud1hi base )\n\t\tum* drop ( -- ud1lo n ud1hi*baselo )\n\t\trot base @ ( -- n ud1hi*baselo ud1lo base )\n\t\tum* ( -- n ud1hi*baselo ud1lo*basello ud1lo*baselhi )\n\t\td+ ( -- ud2 )\n\t\tr> 1+ \\ increment char*\n\t\tr> 1- >r \\ decrement count\n\tREPEAT\n\tr>\n;\n\n\\ obsolete\n: CONVERT ( ud1 c-addr1 -- ud2 c-addr2 , convert till bad char , CORE EXT )\n\t256 >NUMBER DROP\n;\n\n0 constant NUM_TYPE_BAD\n1 constant NUM_TYPE_SINGLE\n2 constant NUM_TYPE_DOUBLE\n\n\\ This is similar to the F83 NUMBER? except that it returns a number type\n\\ and then either a single or double precision number.\n: ((NUMBER?)) ( c-addr u -- 0 | n 1 | d 2 , convert string to number )\n\tdup 0= IF 2drop NUM_TYPE_BAD exit THEN \\ any chars?\n\n\\ prepare for >number\n\t0 0 2swap ( 0 0 c-addr cnt )\n\n\\ check for '-' at beginning, skip if present\n\tover c@ ascii - = \\ is it a '-'\n\tdup >r \\ save flag\n\tIF 1- >r 1+ r> ( -- 0 0 c-addr+1 cnt-1 , skip past minus sign )\n\tTHEN\n\\\n\t>number dup 0= \\ convert as much as we can\n\tIF\n\t\t2drop \\ drop addr cnt\n\t\tdrop \\ drop hi part of num\n\t\tr@ \\ check flag to see if '-' sign used\n\t\tIF negate\n\t\tTHEN\n\t\tNUM_TYPE_SINGLE\n\tELSE ( -- d addr cnt )\n\t\t1 = swap \\ if final character is '.' then double\n\t\tc@ ascii . = AND\n\t\tIF\n\t\t\tr@ \\ check flag to see if '-' sign used\n\t\t\tIF dnegate\n\t\t\tTHEN\n\t\t\tNUM_TYPE_DOUBLE\n\t\tELSE\n\t\t\t2drop\n\t\t\tNUM_TYPE_BAD\n\t\tTHEN\n\tTHEN\n\trdrop\n;\n\n: (NUMBER?) ( $addr -- 0 | n 1 | d 2 , convert string to number )\n\tcount ((number?))\n;\n\ndefer number?\n' (number?) is number?\n\n\\ hex\n\\ 0sp c\" xyz\" (number?) .s\n\\ 0sp c\" 234\" (number?) .s\n\\ 0sp c\" -234\" (number?) .s\n\\ 0sp c\" 234.\" (number?) .s\n\\ 0sp c\" -234.\" (number?) .s\n\\ 0sp c\" 1234567855554444.\" (number?) .s\n\n\n\\ ------------------------ OUTPUT ------------------------------\n\\ Number output based on F83\nvariable HLD \\ points to last character added\n\n: hold ( char -- , add character to text representation)\n\t-1 hld +!\n\thld @ c!\n;\n: <# ( -- , setup conversion )\n\tpad hld !\n;\n: #> ( d -- addr len , finish conversion )\n\t2drop hld @ pad over -\n;\n: sign ( n -- , add '-' if negative )\n\t0< if ascii - hold then\n;\n: # ( d -- d , convert one digit )\n base @ mu\/mod rot 9 over <\n IF 7 +\n THEN\n ascii 0 + hold\n;\n: #s ( d -- d , convert remaining digits )\n\tBEGIN # 2dup or 0=\n\tUNTIL\n;\n\n\n: (UD.) ( ud -- c-addr cnt )\n\t<# #s #>\n;\n: UD. ( ud -- , print unsigned double number )\n\t(ud.) type space\n;\n: UD.R ( ud n -- )\n\t>r (ud.) r> over - spaces type\n;\n: (D.) ( d -- c-addr cnt )\n\ttuck dabs <# #s rot sign #>\n;\n: D. ( d -- )\n\t(d.) type space\n;\n: D.R ( d n -- , right justified )\n\t>r (d.) r> over - spaces type\n;\n\n: (U.) ( u -- c-addr cnt )\n\t0 (ud.)\n;\n: U.R ( u n -- , print right justified )\n\t>r (u.) r> over - spaces type\n;\n: (.) ( n -- c-addr cnt )\n\tdup abs 0 <# #s rot sign #>\n;\n: .R ( n l -- , print right justified)\n\t>r (.) r> over - spaces type\n;","old_contents":"\\ @(#) numberio.fth 98\/01\/26 1.2\n\\ numberio.fth\n\\\n\\ numeric conversion\n\\\n\\ Author: Phil Burk\n\\ Copyright 1994 3DO, Phil Burk, Larry Polansky, Devid Rosenboom\n\\\n\\ The pForth software code is dedicated to the public domain,\n\\ and any third party may reproduce, distribute and modify\n\\ the pForth software code or any derivative works thereof\n\\ without any compensation or license. The pForth software\n\\ code is provided on an \"as is\" basis without any warranty\n\\ of any kind, including, without limitation, the implied\n\\ warranties of merchantability and fitness for a particular\n\\ purpose and their equivalents under the laws of any jurisdiction.\n\nanew task-numberio.fth\ndecimal\n\n\\ ------------------------ INPUT -------------------------------\n\\ Convert a single character to a number in the given base.\n: DIGIT ( char base -- n true | char false )\n\t>r\n\\ convert lower to upper\n\tdup ascii a < not\n\tIF\n\t\tascii a - ascii A +\n\tTHEN\n\\\n\tdup dup ascii A 1- >\n\tIF ascii A - ascii 9 + 1+\n\tELSE ( char char )\n\t\tdup ascii 9 >\n\t\tIF\n\t\t\t( between 9 and A is bad )\n\t\t\tdrop 0 ( trigger error below )\n\t\tTHEN\n\tTHEN\n\tascii 0 -\n\tdup r> <\n\tIF dup 1+ 0>\n\t\tIF nip true\n\t\tELSE drop FALSE\n\t\tTHEN\n\tELSE drop FALSE\n\tTHEN\n;\n\n: >NUMBER ( ud1 c-addr1 u1 -- ud2 c-addr2 u2 , convert till bad char , CORE )\n\t>r\n\tBEGIN\n\t\tr@ 0> \\ any characters left?\n\t\tIF\n\t\t\tdup c@ base @\n\t\t\tdigit ( ud1 c-addr , n true | char false )\n\t\t\tIF\n\t\t\t\tTRUE\n\t\t\tELSE\n\t\t\t\tdrop FALSE\n\t\t\tTHEN\n\t\tELSE\n\t\t\tfalse\n\t\tTHEN\n\tWHILE ( -- ud1 c-addr n )\n\t\tswap >r ( -- ud1lo ud1hi n )\n\t\tswap base @ ( -- ud1lo n ud1hi base )\n\t\tum* drop ( -- ud1lo n ud1hi*baselo )\n\t\trot base @ ( -- n ud1hi*baselo ud1lo base )\n\t\tum* ( -- n ud1hi*baselo ud1lo*basello ud1lo*baselhi )\n\t\td+ ( -- ud2 )\n\t\tr> 1+ \\ increment char*\n\t\tr> 1- >r \\ decrement count\n\tREPEAT\n\tr>\n;\n\n\\ obsolete\n: CONVERT ( ud1 c-addr1 -- ud2 c-addr2 , convert till bad char , CORE EXT )\n\t256 >NUMBER DROP\n;\n\n0 constant NUM_TYPE_BAD\n1 constant NUM_TYPE_SINGLE\n2 constant NUM_TYPE_DOUBLE\n\n\\ This is similar to the F83 NUMBER? except that it returns a number type\n\\ and then either a single or double precision number.\n: ((NUMBER?)) ( c-addr u -- 0 | n 1 | d 2 , convert string to number )\n\tdup 0= IF 2drop NUM_TYPE_BAD exit THEN \\ any chars?\n\n\\ prepare for >number\n\t0 0 2swap ( 0 0 c-addr cnt )\n\n\\ check for '-' at beginning, skip if present\n\tover c@ ascii - = \\ is it a '-'\n\tdup >r \\ save flag\n\tIF 1- >r 1+ r> ( -- 0 0 c-addr+1 cnt-1 , skip past minus sign )\n\tTHEN\n\\\n\t>number dup 0= \\ convert as much as we can\n\tIF\n\t\t2drop \\ drop addr cnt\n\t\tdrop \\ drop hi part of num\n\t\tr@ \\ check flag to see if '-' sign used\n\t\tIF negate\n\t\tTHEN\n\t\tNUM_TYPE_SINGLE\n\tELSE ( -- d addr cnt )\n\t\t1 = swap \\ if final character is '.' then double\n\t\tc@ ascii . = AND\n\t\tIF\n\t\t\tr@ \\ check flag to see if '-' sign used\n\t\t\tIF dnegate\n\t\t\tTHEN\n\t\t\tNUM_TYPE_DOUBLE\n\t\tELSE\n\t\t\t2drop\n\t\t\tNUM_TYPE_BAD\n\t\tTHEN\n\tTHEN\n\trdrop\n;\n\n: (NUMBER?) ( $addr -- 0 | n 1 | d 2 , convert string to number )\n\tcount ((number?))\n;\n\ndefer number?\n' (number?) is number?\n\n\\ hex\n\\ 0sp c\" xyz\" (number?) .s\n\\ 0sp c\" 234\" (number?) .s\n\\ 0sp c\" -234\" (number?) .s\n\\ 0sp c\" 234.\" (number?) .s\n\\ 0sp c\" -234.\" (number?) .s\n\\ 0sp c\" 1234567855554444.\" (number?) .s\n\n\n\\ ------------------------ OUTPUT ------------------------------\n\\ Number output based on F83\nvariable HLD \\ points to last character added\n\n: hold ( char -- , add character to text representation)\n\t-1 hld +!\n\thld @ c!\n;\n: <# ( -- , setup conversion )\n\tpad hld !\n;\n: #> ( d -- addr len , finish conversion )\n\t2drop hld @ pad over -\n;\n: sign ( n -- , add '-' if negative )\n\t0< if ascii - hold then\n;\n: # ( d -- d , convert one digit )\n base @ mu\/mod rot 9 over <\n IF 7 +\n THEN\n ascii 0 + hold\n;\n: #s ( d -- d , convert remaining digits )\n\tBEGIN # 2dup or 0=\n\tUNTIL\n;\n\n\n: (UD.) ( ud -- c-addr cnt )\n\t<# #s #>\n;\n: UD. ( ud -- , print unsigned double number )\n\t(ud.) type space\n;\n: UD.R ( ud n -- )\n\t>r (ud.) r> over - spaces type\n;\n: (D.) ( d -- c-addr cnt )\n\ttuck dabs <# #s rot sign #>\n;\n: D. ( d -- )\n\t(d.) type space\n;\n: D.R ( d n -- , right justified )\n\t>r (d.) r> over - spaces type\n;\n\n: (U.) ( u -- c-addr cnt )\n\t0 (ud.)\n;\n: U. ( u -- , print unsigned number )\n\t0 ud.\n;\n: U.R ( u n -- , print right justified )\n\t>r (u.) r> over - spaces type\n;\n: (.) ( n -- c-addr cnt )\n\tdup abs 0 <# #s rot sign #>\n;\n: .R ( n l -- , print right justified)\n\t>r (.) r> over - spaces type\n;","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"28125491d335f06162b64eed7abf429b50193adb","subject":"INIT-SER doesn't need to have a dictionary entry.","message":"INIT-SER doesn't need to have a dictionary entry.","repos":"rbsexton\/sockpuppet,rbsexton\/sockpuppet","old_file":"forth\/serCM3_SAPI-level0.fth","new_file":"forth\/serCM3_SAPI-level0.fth","new_contents":"\\ serCM3_sapi_level0.fth - SAPI polled RX, polled TX, serial communication drivers\n\\ Written to run against the SockPuppet API.\n\n\\ Level 0 support, with WFI instead of pause.\n\\ The SAPI is a system call interace, so there is no blocking.\n\\ KEY requires blocking, so that must be implemented here.\n\n\\ Copyright (c) 2016, Robert Sexton. All rights reserved.\n\\ Covered by the terms of the supplied Licence.txt file\n\nonly forth definitions\n\n\\ ==============\n\\ *T SAPI polled serial driver\n\\ ==============\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\n\\ ** using the internal UARTs via the SAPI call layer. This is \n\\ ** The simplest implementation level.\n\n\\ ****************\n\\ *S Configuration\n\\ ****************\n\\ *P Configuration is managed by the SAPI\n\ntarget\n\n\\ ********************\n\\ *S Serial primitives\n\\ ********************\ninternal\n\n: +FaultConsole\t( -- ) ;\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\n\\ ** for more details.\n\ntarget\n\n\\ CODE (seremitfc)\t\\ char base --\n\\ This is a system call.\n\n: (seremit)\t\\ char base -- \n\\ *G Wrapped call that checks for throttling, and if so,\n\\ calls PAUSE to let another task run, or just does a WFI if no multitasker.\n\\ The only interesting thing is failure, or -1. That means retry.\n\tbegin \n\t2dup (seremitfc) dup 0 < \\ char base ret t\/f\n\tIF [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then] THEN \\ char base ret \n 0 >= until\n 2drop\n\t;\n\n: (sertype) \\ caddr len base --\n\\ *G Transmit a string on the given UART.\n\\ * The system call wants base len caddr\n\\ * and it returns the number of characters sent.\n\t>R \\ We'll use this a few times.\n\tbegin \n\t2dup R@ (sertypefc) dup >R \\ caddr len ret\n\t- dup IF \\ If there are still characters left \n\t [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then]\n\t swap R> + swap \\ finish advancing the caddr len pair\n\tELSE R> drop \n\tTHEN \n\tdup 0= until \\ Do this until nothing is left.\n\t2drop \n\tR> drop \n;\n\n: (sercr)\t\\ base --\n\\ *G Transmit a CR\/LF pair on the given UART.\n\\ Wrapped version, just like (seremit)\n\tbegin \n\tdup (sercrfc) dup 0= \\ base ret t\/f\n IF [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then] THEN \\ base ret \n until\n drop\n\t;\n\n: (serkey) \\ base -- c\n\\ *G Get a character from the port. Retry until we get it.\n\\ See if its negative. If so, discard it and leave false to re-loop.\n\\ If not negative, leave true on the stack to exit.\n begin \\ base ret t\/f \n\tdup (serkeyfc) dup 0 < \\ base ret t\/f \n\t IF [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then] drop false \n\t ELSE true \n\t THEN \\ base ret t\/f \n\tuntil \\ base ret \n\tswap drop \n;\n\n\\ THis is a system call.\n\\ CODE (serkey?) \\ base -- t\/f\n\\ *G Return true if the given UART has a character avilable to read.\n\nexternal \n\n: seremit0\t\\ char --\n\\ *G Transmit a character on UART0.\n 0 (seremit) ;\n: sertype0\t\\ c-addr len --\n\\ *G Transmit a string on UART0.\n 0 (sertype) ;\n: sercr0\t\\ --\n\\ *G Issue a CR\/LF pair to UART0.\n 0 (sercr) ;\n: serkey?0\t\\ -- flag\n\\ *G Return true if UART0 has a character available.\n 0 (serkey?) ;\n: serkey0\t\\ -- char\n\\ *G Wait for a character on UART0.\n 0 (serkey) ;\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\n\\ *G Generic I\/O device for UART0.\n ' serkey0 ,\t\t\\ -- char ; receive char\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\n ' seremit0 ,\t\t\\ -- char ; display char\n ' sertype0 ,\t\t\\ caddr len -- ; display string\n ' sercr0 ,\t\t\\ -- ; display new line\n\n\\ Non-UARTs.\n: seremit10 #10 (seremit) ;\n: sertype10\t#10 (sertype) ;\n: sercr10\t#10 (sercr) ;\n: serkey?10\t#10 (serkey?) ;\n: serkey10\t#10 (serkey) ;\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\n\nconsole-port 0 = [if]\n console0 constant console\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\n\\ ** It may be changed by one of the phrases of the form:\n\\ *C dup opvec ! ipvec !\n\\ *C SetConsole\n[then]\n\nconsole-port #10 = [if]\n console10 constant console\n[then]\n\n\\ ************************\n\\ *S System initialisation\n\\ ************************\n\ninternal\n\\ This is a NOP in the SAPI environment\n: init-ser ;\t\\ --\n\\ *G Initialise all serial ports\nexternal\n\n\\ ======\n\\ *> ###\n\\ ======\n\ndecimal\n","old_contents":"\\ serCM3_sapi_level0.fth - SAPI polled RX, polled TX, serial communication drivers\n\\ Written to run against the SockPuppet API.\n\n\\ Level 0 support, with WFI instead of pause.\n\\ The SAPI is a system call interace, so there is no blocking.\n\\ KEY requires blocking, so that must be implemented here.\n\n\\ Copyright (c) 2016, Robert Sexton. All rights reserved.\n\\ Covered by the terms of the supplied Licence.txt file\n\nonly forth definitions\n\n\\ ==============\n\\ *T SAPI polled serial driver\n\\ ==============\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\n\\ ** using the internal UARTs via the SAPI call layer. This is \n\\ ** The simplest implementation level.\n\n\\ ****************\n\\ *S Configuration\n\\ ****************\n\\ *P Configuration is managed by the SAPI\n\ntarget\n\n\\ ********************\n\\ *S Serial primitives\n\\ ********************\ninternal\n\n: +FaultConsole\t( -- ) ;\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\n\\ ** for more details.\n\ntarget\n\n\\ CODE (seremitfc)\t\\ char base --\n\\ This is a system call.\n\n: (seremit)\t\\ char base -- \n\\ *G Wrapped call that checks for throttling, and if so,\n\\ calls PAUSE to let another task run, or just does a WFI if no multitasker.\n\\ The only interesting thing is failure, or -1. That means retry.\n\tbegin \n\t2dup (seremitfc) dup 0 < \\ char base ret t\/f\n\tIF [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then] THEN \\ char base ret \n 0 >= until\n 2drop\n\t;\n\n: (sertype) \\ caddr len base --\n\\ *G Transmit a string on the given UART.\n\\ * The system call wants base len caddr\n\\ * and it returns the number of characters sent.\n\t>R \\ We'll use this a few times.\n\tbegin \n\t2dup R@ (sertypefc) dup >R \\ caddr len ret\n\t- dup IF \\ If there are still characters left \n\t [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then]\n\t swap R> + swap \\ finish advancing the caddr len pair\n\tELSE R> drop \n\tTHEN \n\tdup 0= until \\ Do this until nothing is left.\n\t2drop \n\tR> drop \n;\n\n: (sercr)\t\\ base --\n\\ *G Transmit a CR\/LF pair on the given UART.\n\\ Wrapped version, just like (seremit)\n\tbegin \n\tdup (sercrfc) dup 0= \\ base ret t\/f\n IF [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then] THEN \\ base ret \n until\n drop\n\t;\n\n: (serkey) \\ base -- c\n\\ *G Get a character from the port. Retry until we get it.\n\\ See if its negative. If so, discard it and leave false to re-loop.\n\\ If not negative, leave true on the stack to exit.\n begin \\ base ret t\/f \n\tdup (serkeyfc) dup 0 < \\ base ret t\/f \n\t IF [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then] drop false \n\t ELSE true \n\t THEN \\ base ret t\/f \n\tuntil \\ base ret \n\tswap drop \n;\n\n\\ THis is a system call.\n\\ CODE (serkey?) \\ base -- t\/f\n\\ *G Return true if the given UART has a character avilable to read.\n\nexternal \n\n: seremit0\t\\ char --\n\\ *G Transmit a character on UART0.\n 0 (seremit) ;\n: sertype0\t\\ c-addr len --\n\\ *G Transmit a string on UART0.\n 0 (sertype) ;\n: sercr0\t\\ --\n\\ *G Issue a CR\/LF pair to UART0.\n 0 (sercr) ;\n: serkey?0\t\\ -- flag\n\\ *G Return true if UART0 has a character available.\n 0 (serkey?) ;\n: serkey0\t\\ -- char\n\\ *G Wait for a character on UART0.\n 0 (serkey) ;\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\n\\ *G Generic I\/O device for UART0.\n ' serkey0 ,\t\t\\ -- char ; receive char\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\n ' seremit0 ,\t\t\\ -- char ; display char\n ' sertype0 ,\t\t\\ caddr len -- ; display string\n ' sercr0 ,\t\t\\ -- ; display new line\n\n\\ Non-UARTs.\n: seremit10 #10 (seremit) ;\n: sertype10\t#10 (sertype) ;\n: sercr10\t#10 (sercr) ;\n: serkey?10\t#10 (serkey?) ;\n: serkey10\t#10 (serkey) ;\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\n\nconsole-port 0 = [if]\n console0 constant console\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\n\\ ** It may be changed by one of the phrases of the form:\n\\ *C dup opvec ! ipvec !\n\\ *C SetConsole\n[then]\n\nconsole-port #10 = [if]\n console10 constant console\n[then]\n\n\\ ************************\n\\ *S System initialisation\n\\ ************************\n\n\\ This is a NOP in the SAPI environment\n: init-ser ;\t\\ --\n\\ *G Initialise all serial ports\n\n\\ ======\n\\ *> ###\n\\ ======\n\ndecimal\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"5f4dd0275f9e483d7fcd1acb2fbbc64d29349ae6","subject":"Re-grind the code.","message":"Re-grind the code.","repos":"rbsexton\/sockpuppet,rbsexton\/sockpuppet","old_file":"forth\/serCM3_sapi_p.fth","new_file":"forth\/serCM3_sapi_p.fth","new_contents":"\\ serCM3_sapi_p.fth - SAPI polled RX, polled TX, serial communication drivers\n\\ Written to run against the SockPuppet API.\n\n((\nAdapted from: the LPC polled driver.\n))\n\nonly forth definitions\nvariable cnt.pause \n\n\\ ==============\n\\ *! serCM3_sapi_p\n\\ *T SAPI polled serial driver\n\\ ==============\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\n\\ ** using the internal UARTs via the SAPI call layer.\n\n\n\\ ****************\n\\ *S Configuration\n\\ ****************\n\\ *P Configuration is managed by the SAPI\n\n\\ ********\n\\ *S Tools\n\\ ********\n\ntarget\n\n\\ ********************\n\\ *S Serial primitives\n\\ ********************\n\ninternal\n\n: +FaultConsole\t( -- ) ;\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\n\\ ** for more details.\n\ntarget\n\nCODE (seremitfc)\t\\ char base --\n\\ *G Service call for a single char - just fill in the registers\n\\ from the stack and make the call, and get back the flow control feedback\n\\ Put TOS into r0, pull r1 off the stack, and refresh the stack.\n\tmov r0, tos\n\tldr r1, [ psp ], # 4\t\n\tsvc # SAPI_VEC_PUTCHAR\t\n\tmov tos, r0\n next,\nEND-CODE\n\n: (seremit)\t\\ char base -- \n\\ *G Wrapped call that checks for throttling, and if so,\n\\ calls PAUSE to let another task run. Count these events for debugging purposes.\n\t(seremitfc)\n\t0<> IF 1 cnt.pause +! #5 ms THEN\n\t;\n\n: (sertype)\t\\ caddr len base --\n\\ *G Transmit a string on the given UART.\n -rot bounds\n ?do i c@ over (seremit) loop\n drop\n;\n\n: (sercr)\t\\ base --\n\\ *G Transmit a CR\/LF pair on the given UART.\n $0D over (seremit) $0A swap (seremit)\n;\n\nCODE (sergetchar) \\ base -- c\n\\ *G Get a character from the port\n\tmov r0, tos\t\n\tsvc # SAPI_VEC_GETCHAR\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE (serkey?) \\ base -- t\/f\n\\ *G Return true if the given UART has a character avilable to read.\n\\ The call returns 0 or 1. \n\tmov r0, tos\n\tsvc # SAPI_VEC_CHARSAVAIL\t\t\n\tmov tos, r0\n\tnext,\t\nEND-CODE\n\n: (serkey)\t\\ base -- char\n\\ *G Wait for a character to come available on the given UART and\n\\ ** return the character.\n begin\n[ tasking? ] [if] pause [then] \n dup (serkey?)\n until\n (sergetchar) \n;\n\nexternal \n\n: seremit0\t\\ char --\n\\ *G Transmit a character on UART0.\n 0 (seremit) ;\n: sertype0\t\\ c-addr len --\n\\ *G Transmit a string on UART0.\n 0 (sertype) ;\n: sercr0\t\\ --\n\\ *G Issue a CR\/LF pair to UART0.\n 0 (sercr) ;\n: serkey?0\t\\ -- flag\n\\ *G Return true if UART0 has a character available.\n 0 (serkey?) ;\n: serkey0\t\\ -- char\n\\ *G Wait for a character on UART0.\n 0 (serkey) ;\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\n\\ *G Generic I\/O device for UART0.\n ' serkey0 ,\t\t\\ -- char ; receive char\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\n ' seremit0 ,\t\t\\ -- char ; display char\n ' sertype0 ,\t\t\\ caddr len -- ; display string\n ' sercr0 ,\t\t\\ -- ; display new line\n\n\\ UART2\n: seremit2 #2 (seremit) ;\n: sertype2\t#2 (sertype) ;\n: sercr2\t#2 (sercr) ;\n: serkey?2\t#2 (serkey?) ;\n: serkey2\t#2 (serkey) ;\ncreate Console2 ' serkey2 , ' serkey?2 , ' seremit2 , ' sertype2 , ' sercr2 ,\t\n\n\\ Versions for use with the TCP Port (10)\n: seremit10 #10 (seremit) ;\n: sertype10\t#10 (sertype) ;\n: sercr10\t#10 (sercr) ;\n: serkey?10\t#10 (serkey?) ;\n: serkey10\t#10 (serkey) ;\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\n\nconsole-port 0 = [if]\n console0 constant console\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\n\\ ** It may be changed by one of the phrases of the form:\n\\ *C dup opvec ! ipvec !\n\\ *C SetConsole\n[then]\n\nconsole-port #1 = [if]\n console1 constant console\n[then]\n\nconsole-port #10 = [if]\n console10 constant console\n[then]\n\n\\ ************************\n\\ *S System initialisation\n\\ ************************\n\n\\ This is a NOP in the SAPI environment\n: init-ser ;\t\\ --\n\\ *G Initialise all serial ports\n\n\n\\ ======\n\\ *> ###\n\\ ======\n\ndecimal\n","old_contents":"\\ serCM3_sapi_p.fth - SAPI polled RX, polled TX, serial communication drivers\r\n\\ Written to run against the SockPuppet API.\r\n\r\n((\r\nAdapted from: the LPC polled driver.\r\n))\r\n\r\nonly forth definitions\r\nvariable cnt.pause \r\n\r\n\\ ==============\r\n\\ *! serCM3_sapi_p\r\n\\ *T SAPI polled serial driver\r\n\\ ==============\r\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\r\n\\ ** using the internal UARTs via the SAPI call layer.\r\n\r\n\r\n\\ ****************\r\n\\ *S Configuration\r\n\\ ****************\r\n\\ *P Configuration is managed by the SAPI\r\n\r\n\\ ********\r\n\\ *S Tools\r\n\\ ********\r\n\r\ntarget\r\n\r\n\\ ********************\r\n\\ *S Serial primitives\r\n\\ ********************\r\n\r\ninternal\r\n\r\n: +FaultConsole\t( -- ) ;\r\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\r\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\r\n\\ ** for more details.\r\n\r\ntarget\r\n\r\nCODE (seremitfc)\t\\ char base --\r\n\\ *G Service call for a single char - just fill in the registers\r\n\\ from the stack and make the call, and get back the flow control feedback\r\n\\ Put TOS into r0, pull r1 off the stack, and refresh the stack.\r\n\tmov r0, tos\r\n\tldr r1, [ psp ], # 4\t\r\n\tsvc # SAPI_VEC_PUTCHAR\t\r\n\tmov tos, r0\r\n next,\r\nEND-CODE\r\n\r\n: (seremit)\t\\ char base -- \r\n\\ *G Wrapped call that checks for throttling, and if so,\r\n\\ calls PAUSE to let another task run. Count these events for debugging purposes.\r\n\t(seremitfc)\r\n\t0<> IF 1 cnt.pause +! PAUSE THEN\r\n\t;\r\n\r\n: (sertype)\t\\ caddr len base --\r\n\\ *G Transmit a string on the given UART.\r\n -rot bounds\r\n ?do i c@ over (seremit) loop\r\n drop\r\n;\r\n\r\n: (sercr)\t\\ base --\r\n\\ *G Transmit a CR\/LF pair on the given UART.\r\n $0D over (seremit) $0A swap (seremit)\r\n;\r\n\r\nCODE (sergetchar) \\ base -- c\r\n\\ *G Get a character from the port\r\n\tmov r0, tos\t\r\n\tsvc # SAPI_VEC_GETCHAR\r\n\tmov tos, r0\r\n\tnext,\r\nEND-CODE\r\n\r\nCODE (serkey?) \\ base -- t\/f\r\n\\ *G Return true if the given UART has a character avilable to read.\r\n\\ The call returns 0 or 1. \r\n\tmov r0, tos\r\n\tsvc # SAPI_VEC_CHARSAVAIL\t\t\r\n\tmov tos, r0\r\n\tnext,\t\r\nEND-CODE\r\n\r\n: (serkey)\t\\ base -- char\r\n\\ *G Wait for a character to come available on the given UART and\r\n\\ ** return the character.\r\n begin\r\n[ tasking? ] [if] pause [then] \r\n dup (serkey?)\r\n until\r\n (sergetchar) \r\n;\r\n\r\nexternal \r\n\r\n: seremit0\t\\ char --\r\n\\ *G Transmit a character on UART0.\r\n 0 (seremit) ;\r\n: sertype0\t\\ c-addr len --\r\n\\ *G Transmit a string on UART0.\r\n 0 (sertype) ;\r\n: sercr0\t\\ --\r\n\\ *G Issue a CR\/LF pair to UART0.\r\n 0 (sercr) ;\r\n: serkey?0\t\\ -- flag\r\n\\ *G Return true if UART0 has a character available.\r\n 0 (serkey?) ;\r\n: serkey0\t\\ -- char\r\n\\ *G Wait for a character on UART0.\r\n 0 (serkey) ;\r\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\r\n\\ *G Generic I\/O device for UART0.\r\n ' serkey0 ,\t\t\\ -- char ; receive char\r\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\r\n ' seremit0 ,\t\t\\ -- char ; display char\r\n ' sertype0 ,\t\t\\ caddr len -- ; display string\r\n ' sercr0 ,\t\t\\ -- ; display new line\r\n\r\n\\ UART2\r\n: seremit2 #2 (seremit) ;\r\n: sertype2\t#2 (sertype) ;\r\n: sercr2\t#2 (sercr) ;\r\n: serkey?2\t#2 (serkey?) ;\r\n: serkey2\t#2 (serkey) ;\r\ncreate Console2 ' serkey2 , ' serkey?2 , ' seremit2 , ' sertype2 , ' sercr2 ,\t\r\n\r\n\\ Versions for use with the TCP Port (10)\r\n: seremit10 #10 (seremit) ;\r\n: sertype10\t#10 (sertype) ;\r\n: sercr10\t#10 (sercr) ;\r\n: serkey?10\t#10 (serkey?) ;\r\n: serkey10\t#10 (serkey) ;\r\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\r\n\r\nconsole-port 0 = [if]\r\n console0 constant console\r\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\r\n\\ ** It may be changed by one of the phrases of the form:\r\n\\ *C dup opvec ! ipvec !\r\n\\ *C SetConsole\r\n[then]\r\n\r\nconsole-port #1 = [if]\r\n console1 constant console\r\n[then]\r\n\r\nconsole-port #10 = [if]\r\n console10 constant console\r\n[then]\r\n\r\n\\ ************************\r\n\\ *S System initialisation\r\n\\ ************************\r\n\r\n\\ This is a NOP in the SAPI environment\r\n: init-ser ;\t\\ --\r\n\\ *G Initialise all serial ports\r\n\r\n\r\n\\ ======\r\n\\ *> ###\r\n\\ ======\r\n\r\ndecimal\r\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"d235b248ad3bc1d1f47bf06aff61f3218a75e153","subject":"Float FIX uses FROUND","message":"Float FIX uses FROUND\n","repos":"philburk\/hmsl,philburk\/hmsl,philburk\/hmsl","old_file":"hmsl\/fth\/float_port.fth","new_file":"hmsl\/fth\/float_port.fth","new_contents":"\\ Floating point words from HMSL redefined using ANSI Forth\n\\\n\\ Author: Phil Burk\n\\ Copyright 2016 - Phil Burk, Larry Polansky, David Rosenboom.\n\\ All Rights Reserved\n\nANEW TASK-FLOAT_PORT\n\n: FPINIT ; \\ not needed, floats always available\n: FPTERM ;\n\n: FMOD ( r1 r2 -f- rem{f1\/f2} , calc remainder )\n fover fover f\/\n f>s s>f\n f* f-\n;\n\n: F= ( r1 r2 -f- , -- flag )\n f- f0=\n;\n\n: F> ( r1 r2 -f- , -- flag )\n fswap f<\n;\n\n: F>I ( r -f- , -- n )\n f>s\n;\n\n: FIX ( r -f- , -- n , rounds )\n fround\n;\n\n: FLOAT ( n -- , -f- r , convert to float )\n s>f\n;\n\n: I>F ( n -- , -f- r , convert to float )\n s>f\n;\n\n: INT ( r -f- , -- n )\n f>s\n;\n\n: F>TEXT ( r -f- addr count , converts fp to text )\n (f.)\n;\n\n: F.R ( r -f- , width -- , set width of field, print )\n >r \\ save width\n (f.)\n r> over - spaces\n type\n;\n\n: PLACES ( n -- , sets default number of fractional digits )\n set-precision \\ this is not quite right, this sets significant digits\n;\n\n: FNUMBER? ( $string -- true | false , -f- r )\n number? \\ handles both ints and floats\n;\n","old_contents":"\\ Miscellaneous H4th words needed by HMSL.\n\nANEW TASK-H4TH_PORT\n\n\\ Floating point words redefined using ANSI Forth -------------\n\n: FPINIT ; \\ not needed, floats always available\n: FPTERM ;\n\n: FMOD ( r1 r2 -f- rem{f1\/f2} , calc remainder )\n fover fover f\/\n f>s s>f\n f* f-\n;\n\n: F= ( r1 r2 -f- , -- flag )\n f- f0=\n;\n\n: F> ( r1 r2 -f- , -- flag )\n fswap f<\n;\n\n: F>I ( r -f- , -- n )\n f>s\n;\n\n: FIX ( r -f- , -- n , rounds ) \\ FROUND not implemented in pForth!\n 0.5 f+ f>s\n;\n\n: FLOAT ( n -- , -f- r , convert to float )\n s>f\n;\n\n: I>F ( n -- , -f- r , convert to float )\n s>f\n;\n\n: INT ( r -f- , -- n )\n f>s\n;\n\n: F>TEXT ( r -f- addr count , converts fp to text )\n (f.)\n;\n\n: F.R ( r -f- , width -- , set width of field, print )\n >r \\ save width\n (f.)\n r> over - spaces\n type\n;\n\n: PLACES ( n -- , sets default number of fractional digits )\n set-precision \\ this is not quite right, this sets significant digits\n;\n\n: FNUMBER? ( $string -- true | false , -f- r )\n number? \\ handles both ints and floats\n;\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Forth"} {"commit":"96ddf35ea73965d4e09e02d58097a5f0db44e0bb","subject":"update example: check switch too","message":"update example: check switch too","repos":"cetic\/python-msp430-tools,cetic\/python-msp430-tools,cetic\/python-msp430-tools","old_file":"examples\/asm\/forth_to_asm\/led.forth","new_file":"examples\/asm\/forth_to_asm\/led.forth","new_contents":"( LED flashing example\n Hardware: Lauchpad\n\n vi:ft=forth\n)\n\nINCLUDE msp430.forth\nINCLUDE core.forth\n\nCODE @B\n TOS->R15\n .\" \\t mov.b @R15, 0(TOS) \" NL\n NEXT\nEND-CODE\n\nCODE !B\n TOS->R14\n TOS->R15\n .\" \\t mov.b R14, 0(R15) \" NL\n NEXT\nEND-CODE\n\nCODE BIT_CLEAR_BYTE\n TOS->R14\n TOS->R15\n .\" \\t bic.b R14, 0(R15) \" NL\n NEXT\nEND-CODE\n\nCODE BIT_SET_BYTE\n TOS->R14\n TOS->R15\n .\" \\t bis.b R14, 0(R15) \" NL\n NEXT\nEND-CODE\n\n: INIT\n P1DIR [ BIT0 BIT6 + LITERAL ] !B\n P1OUT 0 !B\n( 10 12 >\n IF 10 ELSE 20 ENDIF\n DROP\n)\n;\n\nCODE DELAY\n TOS->R15\n .\" .loop: \\t dec R15 \\n \"\n .\" \\t jnz .loop \\n \"\n NEXT\nEND-CODE\n\n( Control the LEDs on the Launchpad )\n: RED_ON P1OUT BIT0 BIT_SET_BYTE ;\n: RED_OFF P1OUT BIT0 BIT_CLEAR_BYTE ;\n: GREEN_ON P1OUT BIT6 BIT_SET_BYTE ;\n: GREEN_OFF P1OUT BIT6 BIT_CLEAR_BYTE ;\n\n( Read in the button on the Launchpad )\n: S2 P1IN @B BIT3 & NOT ;\n\n: MAIN\n BEGIN\n ( Red flashing )\n RED_ON\n 0xffff DELAY\n RED_OFF\n 0xffff DELAY\n\n ( Green flashing if button is pressed )\n S2 IF\n GREEN_ON\n 0x4fff DELAY\n GREEN_OFF\n 0x4fff DELAY\n ENDIF\n LOOP\n;\n\n( ========================================================================= )\n( Generate the assembler file now )\n\" LED example \" HEADER\n\n( output important runtime core parts )\n\" Core \" HEADER\nCROSS-COMPILE-CORE\n\n( cross compile application )\n\" Application \" HEADER\nCROSS-COMPILE INIT\nCROSS-COMPILE MAIN\nCROSS-COMPILE-MISSING\n","old_contents":"( vi:ft=forth )\n\nINCLUDE msp430.forth\nINCLUDE core.forth\n\nCODE !B\n TOS->R14\n TOS->R15\n .\" \\t mov.b R14, 0(R15) \" NL\n NEXT\nEND-CODE\n\nCODE BIT_CLEAR_BYTE\n TOS->R14\n TOS->R15\n .\" \\t bic.b R14, 0(R15) \" NL\n NEXT\nEND-CODE\n\nCODE BIT_SET_BYTE\n TOS->R14\n TOS->R15\n .\" \\t bis.b R14, 0(R15) \" NL\n NEXT\nEND-CODE\n\n: INIT\n P1DIR [ BIT0 BIT6 + LITERAL ] !B\n P1OUT 0 !B\n 0 IF 10 ELSE 20 ENDIF\n;\n\nCODE DELAY\n TOS->R15\n .\" .loop: \\t dec R15 \\n \"\n .\" \\t jnz .loop \\n \"\n NEXT\nEND-CODE\n\n: RED_ON P1OUT BIT0 BIT_SET_BYTE ;\n: RED_OFF P1OUT BIT0 BIT_CLEAR_BYTE ;\n: GREEN_ON P1OUT BIT6 BIT_SET_BYTE ;\n: GREEN_OFF P1OUT BIT6 BIT_CLEAR_BYTE ;\n\n: MAIN\n BEGIN\n RED_ON\n 0xffff DELAY\n RED_OFF\n 0xffff DELAY\n GREEN_ON\n 0x4fff DELAY\n GREEN_OFF\n 0x4fff DELAY\n LOOP\n;\n\n( ========================================================================= )\n( Generate the assembler file now )\n\" LED example \" HEADER\n\n( output important runtime core parts )\n\" Core \" HEADER\nCROSS-COMPILE-CORE\n\n( cross compile application )\n\" Application \" HEADER\nCROSS-COMPILE INIT\nCROSS-COMPILE MAIN\nCROSS-COMPILE-MISSING\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"6d3ec05769bf7cfc14229a28e94e5dfba2355881","subject":"Revert \"Merge branch 'master' of https:\/\/github.com\/tehologist\/forthkit\"","message":"Revert \"Merge branch 'master' of https:\/\/github.com\/tehologist\/forthkit\"\n\nThis reverts commit acbc44b78e27995fbfcbced08e736113c335bc7d, reversing\nchanges made to 59ff3352d7cce3f7be728064c8fb9fcdc054f240.\n","repos":"tehologist\/forthkit","old_file":"eforth.forth","new_file":"eforth.forth","new_contents":": + UM+ DROP ; \n: CELLS DUP + ; \n: CELL+ 2 + ; \n: CELL- -2 + ; \n: CELL 2 ; \n: BOOT 0 CELLS ; \n: FORTH 4 CELLS ; \n: DPL 5 CELLS ; \n: SP0 6 CELLS ; \n: RP0 7 CELLS ; \n: '?KEY 8 CELLS ; \n: 'EMIT 9 CELLS ; \n: 'EXPECT 10 CELLS ; \n: 'TAP 11 CELLS ; \n: 'ECHO 12 CELLS ; \n: 'PROMPT 13 CELLS ; \n: BASE 14 CELLS ; \n: tmp 15 CELLS ; \n: SPAN 16 CELLS ; \n: >IN 17 CELLS ; \n: #TIBB 18 CELLS ; \n: TIBB 19 CELLS ; \n: CSP 20 CELLS ; \n: 'EVAL 21 CELLS ; \n: 'NUMBER 22 CELLS ; \n: HLD 23 CELLS ; \n: HANDLER 24 CELLS ; \n: CONTEXT 25 CELLS ; \n: CURRENT 27 CELLS ; \n: CP 29 CELLS ; \n: NP 30 CELLS ; \n: LAST 31 CELLS ; \n: STATE 32 CELLS ; \n: SPP 33 CELLS ; \n: RPP 34 CELLS ; \n: TRUE -1 ; \n: FALSE 0 ; \n: BL 32 ; \n: BS 8 ; \n: =IMMED 3 ; \n: =WORDLIST 2 ; \n: IMMEDIATE =IMMED LAST @ CELL- ! ; \n: HERE CP @ ; \n: ALLOT CP @ + CP ! ; \n: , HERE CELL ALLOT ! ; \n: C, HERE 1 ALLOT C! ; \n: +! SWAP OVER @ + SWAP ! ; \n: COMPILE R> DUP @ , CELL+ >R ; \n: STATE? STATE @ ; \n: LITERAL COMPILE LIT , ; IMMEDIATE \n: [ FALSE STATE ! ; IMMEDIATE \n: ] TRUE STATE ! ; IMMEDIATE \n: IF COMPILE 0BRANCH HERE 0 , ; IMMEDIATE \n: THEN HERE SWAP ! ; IMMEDIATE \n: FOR COMPILE >R HERE ; IMMEDIATE \n: NEXT COMPILE next , ; IMMEDIATE \n: BEGIN HERE ; IMMEDIATE \n: AGAIN COMPILE BRANCH , ; IMMEDIATE \n: UNTIL COMPILE 0BRANCH , ; IMMEDIATE \n: AHEAD COMPILE BRANCH HERE 0 , ; IMMEDIATE \n: REPEAT COMPILE BRANCH , HERE SWAP ! ; IMMEDIATE \n: AFT DROP COMPILE BRANCH HERE 0 , HERE SWAP ; IMMEDIATE \n: ELSE COMPILE BRANCH HERE 0 , SWAP HERE SWAP ! ; IMMEDIATE \n: WHILE COMPILE 0BRANCH HERE 0 , SWAP ; IMMEDIATE \n: EXECUTE >R ; \n: @EXECUTE @ DUP IF EXECUTE THEN ; \n: R@ R> R> DUP >R SWAP >R ; \n: #TIB #TIBB @ ; \n: TIB TIBB @ ; \n: \\ #TIB @ >IN ! ; IMMEDIATE \n: ROT >R SWAP R> SWAP ; \n: -ROT SWAP >R SWAP R> ; \n: NIP SWAP DROP ; \n: TUCK SWAP OVER ; \n: 2>R SWAP R> SWAP >R SWAP >R >R ; \n: 2R> R> R> SWAP R> SWAP >R SWAP ; \n: 2R@ R> R> R@ SWAP >R SWAP R@ SWAP >R ; \n: 2DROP DROP DROP ; \n: 2DUP OVER OVER ; \n: 2SWAP ROT >R ROT R> ; \n: 2OVER >R >R 2DUP R> R> 2SWAP ; \n: 2ROT 2>R 2SWAP 2R> 2SWAP ; \n: -2ROT 2ROT 2ROT ; \n: 2NIP 2SWAP 2DROP ; \n: 2TUCK 2SWAP 2OVER ; \n: NOT DUP NAND ; \n: AND NAND NOT ; \n: OR NOT SWAP NOT NAND ; \n: NOR OR NOT ; \n: XOR 2DUP AND -ROT NOR NOR ; \n: XNOR XOR NOT ; \n: NEGATE NOT 1 + ; \n: - NEGATE + ; \n: 1+ 1 + ; \n: 1- 1 - ; \n: 2+ 2 + ; \n: 2- 2 - ; \n: D+ >R SWAP >R UM+ R> R> + + ; \n: DNEGATE NOT >R NOT 1 UM+ R> + ; \n: D- DNEGATE D+ ; \n: 2! SWAP OVER ! CELL+ ! ; \n: 2@ DUP CELL+ @ SWAP @ ; \n: ?DUP DUP IF DUP THEN ; \n: S>D DUP 0< ; \n: ABS DUP 0< IF NEGATE THEN ; \n: DABS DUP 0< IF DNEGATE THEN ; \n: U< 2DUP XOR 0< IF SWAP DROP 0< EXIT THEN - 0< ; \n: U> SWAP U< ; \n: = XOR IF FALSE EXIT THEN TRUE ; \n: < 2DUP XOR 0< IF DROP 0< EXIT THEN - 0< ; \n: > SWAP < ; \n: 0> NEGATE 0< ; \n: 0<> IF TRUE EXIT THEN FALSE ; \n: 0= 0 = ; \n: <> = 0= ; \n: D0< SWAP DROP 0< ; \n: D0> DNEGATE D0< ; \n: D0= OR 0= ; \n: D= D- D0= ; \n: D< ROT 2DUP XOR IF SWAP 2SWAP 2DROP < ; \n: DU< ROT 2DUP XOR IF SWAP 2SWAP THEN THEN 2DROP U< ; \n: DMIN 2OVER 2OVER 2SWAP D< IF 2SWAP THEN 2DROP ; \n: DMAX 2OVER 2OVER D< IF 2SWAP THEN 2DROP ; \n: M+ S>D D+ ; \n: M- S>D D- ; \n: MIN 2DUP SWAP < IF SWAP THEN DROP ; \n: MAX 2DUP < IF SWAP THEN DROP ; \n: UMIN 2DUP SWAP U< IF SWAP THEN DROP ; \n: UMAX 2DUP U< IF SWAP THEN DROP ; \n: WITHIN OVER - >R - R> U< ; \n: UM\/MOD \n 2DUP U< \n IF NEGATE \n 15 FOR \n >R DUP UM+ \n >R >R DUP UM+ \n R> + DUP R> R@ SWAP \n >R UM+ \n R> OR \n IF >R DROP 1+ R> \n ELSE DROP \n THEN R> \n NEXT DROP SWAP EXIT \n THEN DROP 2DROP -1 DUP ; \n: M\/MOD \n DUP 0< DUP >R \n IF NEGATE >R \n DNEGATE R> \n THEN >R DUP 0< \n IF R@ + \n THEN R> UM\/MOD \n R> \n IF SWAP NEGATE SWAP THEN ; \n: \/MOD OVER 0< SWAP M\/MOD ; \n: MOD \/MOD DROP ; \n: \/ \/MOD NIP ; \n: UM* \n 0 SWAP \n 15 FOR \n DUP UM+ >R >R \n DUP UM+ \n R> + \n R> \n IF >R OVER UM+ \n R> + \n THEN \n NEXT \n ROT DROP ; \n: * UM* DROP ; \n: M* \n 2DUP XOR 0< >R \n ABS SWAP ABS UM* \n R> IF DNEGATE THEN ; \n: *\/MOD >R M* R> M\/MOD ; \n: *\/ *\/MOD SWAP DROP ; \n: 2* 2 * ; \n: 2\/ 2 \/ ; \n: MU\/MOD >R 0 R@ UM\/MOD R> SWAP >R UM\/MOD R> ; \n: D2* 2DUP D+ ; \n: DU2\/ 2 MU\/MOD ROT DROP ; \n: D2\/ DUP >R 1 AND DU2\/ R> 2\/ OR ; \n: ALIGNED DUP 0 2 UM\/MOD DROP DUP IF 2 SWAP - THEN + ; \n: parse \n tmp ! OVER >R DUP \n IF \n 1- tmp @ BL = \n IF \n FOR BL OVER C@ - 0< NOT \n WHILE 1+ \n NEXT R> DROP 0 DUP EXIT \n THEN R> \n THEN \n OVER SWAP \n FOR tmp @ OVER C@ - tmp @ BL = \n IF 0< THEN \n WHILE 1+ \n NEXT DUP >R \n ELSE R> DROP DUP 1+ >R \n THEN OVER - R> R> - EXIT \n THEN OVER R> - ; \n: PARSE >R TIB >IN @ + #TIB C@ >IN @ - R> parse >IN +! ; \n: CHAR BL PARSE DROP C@ ; \n: TX! 1 PUTC ; \n: EMIT 'EMIT @EXECUTE ; \n: TYPE FOR AFT DUP C@ EMIT 1+ THEN NEXT DROP ; \n: ?RX 0 GETC ; \n: ?KEY '?KEY @EXECUTE ; \n: KEY BEGIN ?KEY UNTIL ; \n: COUNT DUP 1+ SWAP C@ ; \n: CMOVE \n FOR \n AFT \n >R DUP C@ R@ C! 1+ R> 1+ \n THEN \n NEXT 2DROP ; \n: FILL \n SWAP \n FOR SWAP \n AFT 2DUP C! 1+ THEN \n NEXT 2DROP ; \n: -TRAILING \n FOR \n AFT \n BL OVER R@ + C@ < \n IF \n R> 1+ EXIT \n THEN \n THEN \n NEXT 0 ; \n: PACK$ \n DUP >R \n 2DUP C! 1+ 2DUP + 0 SWAP ! SWAP CMOVE \n R> ; \n: WORD PARSE HERE PACK$ ; \n: TOKEN BL PARSE 31 MIN NP @ OVER - 1- PACK$ ; \n: LINK> 3 CELLS - ; \n: CODE> 2 CELLS - ; \n: TYPE> 1 CELLS - ; \n: DATA> CELL+ ; \n: SAME? \n FOR AFT \n OVER R@ CELLS + @ \n OVER R@ CELLS + @ \n - ?DUP \n IF R> DROP EXIT THEN \n THEN \n NEXT 0 ; \n: find \n @ BEGIN DUP WHILE \n 2DUP C@ SWAP C@ = IF \n 2DUP 1+ SWAP COUNT ALIGNED CELL \/ >R SWAP R> \n SAME? 0= IF \n 2DROP SWAP DROP DUP CODE> @ SWAP -1 EXIT \n THEN 2DROP THEN \n LINK> @ REPEAT ; \n: ' TOKEN CONTEXT @ find IF DROP ELSE SWAP DROP 0 THEN ; \n: ! ! ; \n' TX! 'EMIT ! \n' ?RX '?KEY ! \n: ['] COMPILE ' ; IMMEDIATE \n: POSTPONE ' , ; IMMEDIATE \n: [CHAR] CHAR POSTPONE LITERAL ; IMMEDIATE \n: ( [CHAR] ) PARSE 2DROP ; IMMEDIATE \n: :NONAME HERE POSTPONE ] ; \n: OVERT LAST @ CURRENT @ ! ; \n: $,n \n DUP LAST ! CELL- \n DUP =WORDLIST \n SWAP ! \n CELL- DUP HERE \n SWAP ! \n CELL- DUP CURRENT @ @ \n SWAP ! \n CELL- NP ! ; \n: : TOKEN $,n POSTPONE ] ; \n: ; COMPILE EXIT POSTPONE [ OVERT ; IMMEDIATE \n: RECURSE LAST @ CURRENT @ ! ; IMMEDIATE \n: doVAR R> ; \n: CREATE TOKEN $,n COMPILE doVAR OVERT ; \n: DOES LAST @ CODE> @ R> SWAP ! ; \n: DOES> COMPILE DOES COMPILE R> ; IMMEDIATE \n: CONSTANT CREATE , DOES> @ ; \n: VARIABLE CREATE 0 , ; \n: 2LITERAL SWAP POSTPONE LITERAL \n POSTPONE LITERAL ; IMMEDIATE \n: 2CONSTANT CREATE , , DOES> 2@ ; \n: 2VARIABLE CREATE 2 CELLS ALLOT ; \n: SPACE BL EMIT ; \n: SPACES 0 MAX FOR SPACE NEXT ; \n: PAD HERE 80 + ; \n: DECIMAL 10 BASE ! ; \n: HEX 16 BASE ! ; \n: BINARY 2 BASE ! ; \n: OCTAL 8 BASE ! ; \nDECIMAL \n: CHAR- 1- ; \n: CHAR+ 1+ ; \n: CHARS ; \n: >CHAR 127 AND DUP 127 BL WITHIN IF DROP 95 THEN ; \n: DIGIT 9 OVER < 7 AND + [CHAR] 0 + ; \n: <# PAD HLD ! ; \n: HOLD HLD @ CHAR- DUP HLD ! C! ; \n: # 0 BASE @ UM\/MOD >R BASE @ UM\/MOD SWAP DIGIT HOLD R> ; \n: #S BEGIN # 2DUP OR 0= UNTIL ; \n: SIGN 0< IF [CHAR] - HOLD THEN ; \n: #> 2DROP HLD @ PAD OVER - ; \n: S.R OVER - SPACES TYPE ; \n: D.R >R DUP >R DABS <# #S R> SIGN #> R> S.R ; \n: U.R 0 SWAP D.R ; \n: .R >R S>D R> D.R ; \n: D. 0 D.R SPACE ; \n: U. 0 D. ; \n: . BASE @ 10 XOR IF U. EXIT THEN S>D D. ; \n: ? @ . ; \n: DU.R >R <# #S #> R> S.R ; \n: DU. DU.R SPACE ; \n: do$ R> R@ R> COUNT + ALIGNED >R SWAP >R ; \n: .\"| do$ COUNT TYPE ; \n: $,\" [CHAR] \" WORD COUNT + ALIGNED CP ! ; \n: .\" COMPILE .\"| $,\" ; IMMEDIATE \n: .( [CHAR] ) PARSE TYPE ; IMMEDIATE \n: $\"| do$ ; \n: $\" COMPILE $\"| $,\" ; IMMEDIATE \n: s\" [CHAR] \" PARSE HERE PACK$ ; \n: CR 10 EMIT ; \n: TAP OVER C! 1+ ; \n: KTAP \n 10 XOR \n IF \n BL TAP EXIT \n THEN \n NIP DUP ; \n: ACCEPT \n OVER + OVER \n BEGIN \n 2DUP XOR \n WHILE \n KEY \n DUP BL - 95 U< \n IF TAP ELSE KTAP THEN \n REPEAT DROP OVER - ; \n: EXPECT ACCEPT SPAN ! DROP ; \n: QUERY TIB 80 ACCEPT #TIB C! DROP 0 >IN ! ; \n: DIGIT? \n >R [CHAR] 0 - \n 9 OVER < \n IF 7 - DUP 10 < OR THEN \n DUP R> U< ; \n: \/STRING DUP >R - SWAP R> + SWAP ; \n: >NUMBER \n BEGIN DUP \n WHILE >R DUP >R C@ BASE @ DIGIT? \n WHILE SWAP BASE @ UM* DROP ROT \n BASE @ UM* D+ R> CHAR+ R> 1 - \n REPEAT DROP R> R> THEN ; \n: NUMBER? \n OVER C@ [CHAR] - = DUP >R IF 1 \/STRING THEN \n >R >R 0 DUP R> R> -1 DPL ! \n BEGIN >NUMBER DUP \n WHILE OVER C@ [CHAR] . XOR \n IF ROT DROP ROT R> 2DROP FALSE EXIT \n THEN 1 - DPL ! CHAR+ DPL @ \n REPEAT 2DROP R> IF DNEGATE THEN TRUE ; \n' NUMBER? 'NUMBER ! \n: $INTERPRET \n CONTEXT @ find \n IF DROP EXECUTE EXIT THEN \n COUNT 'NUMBER @EXECUTE IF \n DPL @ 0< IF DROP THEN EXIT THEN .\" ?\" TYPE ; \n: $COMPILE \n CONTEXT @ find \n IF CELL- @ =IMMED = \n IF EXECUTE ELSE , THEN EXIT \n THEN COUNT 'NUMBER @EXECUTE \n IF \n DPL @ 0< \n IF DROP POSTPONE LITERAL \n ELSE POSTPONE 2LITERAL \n THEN EXIT \n THEN .\" ?\" TYPE ; \n: eval STATE? IF $COMPILE ELSE $INTERPRET THEN ; \n' eval 'EVAL ! \n: EVAL \n BEGIN TOKEN DUP C@ WHILE \n 'EVAL @EXECUTE \n REPEAT DROP ; \n: OK CR .\" OK.\" SPACE ; \n' OK 'PROMPT ! \n: QUIT \n BEGIN 'PROMPT @EXECUTE QUERY \n EVAL AGAIN ; \n: BYE .\" Good Bye \" CR HALT ; \n' QUIT BOOT ! \n: SP@ SPP @ ; \n: DEPTH SP@ SP0 @ - CELL \/ ; \n: PICK CELLS SP@ SWAP - 2 CELLS - @ ; \n: .S CR DEPTH FOR AFT R@ PICK . THEN NEXT SPACE .\" \n @ SPACE REPEAT DROP CR ; \n\nVARIABLE FILE \n: OPEN F_OPEN FILE ! ; \n: CLOSE FILE @ F_CLOSE ; \n: FPUT FILE @ PUTC ; \n: FGET FILE @ GETC ; \n: FPUTS COUNT FOR AFT DUP C@ FPUT 1+ THEN NEXT DROP ; \n\n: SAVEVM $\" eforth.img\" $\" wb\" OPEN 0 \n 16384 FOR AFT DUP C@ FPUT 1+ THEN NEXT CLOSE DROP ; \n\nSAVEVM \n\n","old_contents":": + um+ drop ; \n: cells dup + ; \n: cell+ 2 + ; \n: cell- -2 + ; \n: cell 2 ; \n: boot 0 cells ; \n: forth 4 cells ; \n: dpl 5 cells ; \n: sp0 6 cells ; \n: rp0 7 cells ; \n: '?key 8 cells ; \n: 'emit 9 cells ; \n: 'expect 10 cells ; \n: 'tap 11 cells ; \n: 'echo 12 cells ; \n: 'prompt 13 cells ; \n: base 14 cells ; \n: tmp 15 cells ; \n: span 16 cells ; \n: >in 17 cells ; \n: #tibb 18 cells ; \n: tibb 19 cells ; \n: csp 20 cells ; \n: 'eval 21 cells ; \n: 'number 22 cells ; \n: hld 23 cells ; \n: handler 24 cells ; \n: context 25 cells ; \n: current 27 cells ; \n: cp 29 cells ; \n: np 30 cells ; \n: last 31 cells ; \n: state 32 cells ; \n: spp 33 cells ; \n: rpp 34 cells ; \n: true -1 ; \n: false 0 ; \n: bl 32 ; \n: bs 8 ; \n: =immed 3 ; \n: =wordlist 2 ; \n: immediate =immed last @ cell- ! ; \n: here cp @ ; \n: allot cp @ + cp ! ; \n: , here cell allot ! ; \n: c, here 1 allot c! ; \n: +! swap over @ + swap ! ; \n: compile r> dup @ , cell+ >r ; \n: state? state @ ; \n: literal compile lit , ; immediate \n: [ false state ! ; immediate \n: ] true state ! ; immediate \n: if compile 0branch here 0 , ; immediate \n: then here swap ! ; immediate \n: for compile >r here ; immediate \n: next compile next , ; immediate \n: begin here ; immediate \n: again compile branch , ; immediate \n: until compile 0branch , ; immediate \n: ahead compile branch here 0 , ; immediate \n: repeat compile branch , here swap ! ; immediate \n: aft drop compile branch here 0 , here swap ; immediate \n: else compile branch here 0 , swap here swap ! ; immediate \n: while compile 0branch here 0 , swap ; immediate \n: execute >r ; \n: @execute @ dup if execute then ; \n: r@ r> r> dup >r swap >r ; \n: #tib #tibb @ ; \n: tib tibb @ ; \n: \\ #tib @ >in ! ; immediate \n: rot >r swap r> swap ; \n: -rot swap >r swap r> ; \n: nip swap drop ; \n: tuck swap over ; \n: 2>r swap r> swap >r swap >r >r ; \n: 2r> r> r> swap r> swap >r swap ; \n: 2r@ r> r> r@ swap >r swap r@ swap >r ; \n: 2drop drop drop ; \n: 2dup over over ; \n: 2swap rot >r rot r> ; \n: 2over >r >r 2dup r> r> 2swap ; \n: 2rot 2>r 2swap 2r> 2swap ; \n: -2rot 2rot 2rot ; \n: 2nip 2swap 2drop ; \n: 2tuck 2swap 2over ; \n: not dup nand ; \n: and nand not ; \n: or not swap not nand ; \n: nor or not ; \n: xor 2dup and -rot nor nor ; \n: xnor xor not ; \n: negate not 1 + ; \n: - negate + ; \n: 1+ 1 + ; \n: 1- 1 - ; \n: 2+ 2 + ; \n: 2- 2 - ; \n: d+ >r swap >r um+ r> r> + + ; \n: dnegate not >r not 1 um+ r> + ; \n: d- dnegate d+ ; \n: 2! swap over ! cell+ ! ; \n: 2@ dup cell+ @ swap @ ; \n: ?dup dup if dup then ; \n: s>d dup 0< ; \n: abs dup 0< if negate then ; \n: dabs dup 0< if dnegate then ; \n: u< 2dup xor 0< if swap drop 0< exit then - 0< ; \n: u> swap u< ; \n: = xor if false exit then true ; \n: < 2dup xor 0< if drop 0< exit then - 0< ; \n: > swap < ; \n: 0> negate 0< ; \n: 0<> if true exit then false ; \n: 0= 0 = ; \n: <> = 0= ; \n: d0< swap drop 0< ; \n: d0> dnegate d0< ; \n: d0= or 0= ; \n: d= d- d0= ; \n: d< rot 2dup xor if swap 2swap 2drop < ; \n: du< rot 2dup xor if swap 2swap then then 2drop u< ; \n: dmin 2over 2over 2swap d< if 2swap then 2drop ; \n: dmax 2over 2over d< if 2swap then 2drop ; \n: m+ s>d d+ ; \n: m- s>d d- ; \n: min 2dup swap < if swap then drop ; \n: max 2dup < if swap then drop ; \n: umin 2dup swap u< if swap then drop ; \n: umax 2dup u< if swap then drop ; \n: within over - >r - r> u< ; \n: um\/mod \n 2dup u< \n if negate \n 15 for \n >r dup um+ \n >r >r dup um+ \n r> + dup r> r@ swap \n >r um+ \n r> or \n if >r drop 1+ r> \n else drop \n then r> \n next drop swap exit \n then drop 2drop -1 dup ; \n: m\/mod \n dup 0< dup >r \n if negate >r \n dnegate r> \n then >r dup 0< \n if r@ + \n then r> um\/mod \n r> \n if swap negate swap then ; \n: \/mod over 0< swap m\/mod ; \n: mod \/mod drop ; \n: \/ \/mod nip ; \n: um* \n 0 swap \n 15 for \n dup um+ >r >r \n dup um+ \n r> + \n r> \n if >r over um+ \n r> + \n then \n next \n rot drop ; \n: * um* drop ; \n: m* \n 2dup xor 0< >r \n abs swap abs um* \n r> if dnegate then ; \n: *\/mod >r m* r> m\/mod ; \n: *\/ *\/mod swap drop ; \n: 2* 2 * ; \n: 2\/ 2 \/ ; \n: mu\/mod >r 0 r@ um\/mod r> swap >r um\/mod r> ; \n: d2* 2dup d+ ; \n: du2\/ 2 mu\/mod rot drop ; \n: d2\/ dup >r 1 and du2\/ r> 2\/ or ; \n: aligned dup 0 2 um\/mod drop dup if 2 swap - then + ; \n: parse \n tmp ! over >r dup \n if \n 1- tmp @ bl = \n if \n for bl over c@ - 0< not \n while 1+ \n next r> drop 0 dup exit \n then r> \n then \n over swap \n for tmp @ over c@ - tmp @ bl = \n if 0< then \n while 1+ \n next dup >r \n else r> drop dup 1+ >r \n then over - r> r> - exit \n then over r> - ; \n: parse >r tib >in @ + #tib c@ >in @ - r> parse >in +! ; \n: char bl parse drop c@ ; \n: tx! 1 putc ; \n: emit 'emit @execute ; \n: type for aft dup c@ emit 1+ then next drop ; \n: ?rx 0 getc ; \n: ?key '?key @execute ; \n: key begin ?key until ; \n: count dup 1+ swap c@ ; \n: cmove \n for \n aft \n >r dup c@ r@ c! 1+ r> 1+ \n then \n next 2drop ; \n: fill \n swap \n for swap \n aft 2dup c! 1+ then \n next 2drop ; \n: -trailing \n for \n aft \n bl over r@ + c@ < \n if \n r> 1+ exit \n then \n then \n next 0 ; \n: pack$ \n dup >r \n 2dup c! 1+ 2dup + 0 swap ! swap cmove \n r> ; \n: word parse here pack$ ; \n: token bl parse 31 min np @ over - 1- pack$ ; \n: link> 3 cells - ; \n: code> 2 cells - ; \n: type> 1 cells - ; \n: data> cell+ ; \n: same? \n for aft \n over r@ cells + @ \n over r@ cells + @ \n - ?dup \n if r> drop exit then \n then \n next 0 ; \n: find \n @ begin dup while \n 2dup c@ swap c@ = if \n 2dup 1+ swap count aligned cell \/ >r swap r> \n same? 0= if \n 2drop swap drop dup code> @ swap -1 exit \n then 2drop then \n link> @ repeat ; \n: ' token context @ find if drop else swap drop 0 then ; \n: ! ! ; \n' tx! 'emit ! \n' ?rx '?key ! \n: ['] compile ' ; immediate \n: postpone ' , ; immediate \n: [char] char postpone literal ; immediate \n: ( [char] ) parse 2drop ; immediate \n: :noname here postpone ] ; \n: overt last @ current @ ! ; \n: $,n \n dup last ! cell- \n dup =wordlist \n swap ! \n cell- dup here \n swap ! \n cell- dup current @ @ \n swap ! \n cell- np ! ; \n: : token $,n postpone ] ; \n: ; compile exit postpone [ overt ; immediate \n: recurse last @ code> @ , ; immediate \n: dovar r> ; \n: create token $,n compile dovar overt ; \n: does last @ code> @ r> swap ! ; \n: does> compile does compile r> ; immediate \n: constant create , does> @ ; \n: variable create 0 , ; \n: 2literal swap postpone literal \n postpone literal ; immediate \n: 2constant create , , does> 2@ ; \n: 2variable create 2 cells allot ; \n: space bl emit ; \n: spaces 0 max for space next ; \n: pad here 80 + ; \n: decimal 10 base ! ; \n: hex 16 base ! ; \n: binary 2 base ! ; \n: octal 8 base ! ; \ndecimal \n: char- 1- ; \n: char+ 1+ ; \n: chars ; \n: >char 127 and dup 127 bl within if drop 95 then ; \n: digit 9 over < 7 and + [char] 0 + ; \n: <# pad hld ! ; \n: hold hld @ char- dup hld ! c! ; \n: # 0 base @ um\/mod >r base @ um\/mod swap digit hold r> ; \n: #s begin # 2dup or 0= until ; \n: sign 0< if [char] - hold then ; \n: #> 2drop hld @ pad over - ; \n: s.r over - spaces type ; \n: d.r >r dup >r dabs <# #s r> sign #> r> s.r ; \n: u.r 0 swap d.r ; \n: .r >r s>d r> d.r ; \n: d. 0 d.r space ; \n: u. 0 d. ; \n: . base @ 10 xor if u. exit then s>d d. ; \n: ? @ . ; \n: du.r >r <# #s #> r> s.r ; \n: du. du.r space ; \n: do$ r> r@ r> count + aligned >r swap >r ; \n: .\"| do$ count type ; \n: $,\" [char] \" word count + aligned cp ! ; \n: .\" compile .\"| $,\" ; immediate \n: .( [char] ) parse type ; immediate \n: $\"| do$ ; \n: $\" compile $\"| $,\" ; immediate \n: s\" [char] \" parse here pack$ ; \n: cr 10 emit ; \n: tap over c! 1+ ; \n: ktap \n 10 xor \n if \n bl tap exit \n then \n nip dup ; \n: accept \n over + over \n begin \n 2dup xor \n while \n key \n dup bl - 95 u< \n if tap else ktap then \n repeat drop over - ; \n: expect accept span ! drop ; \n: query tib 80 accept #tib c! drop 0 >in ! ; \n: digit? \n >r [char] 0 - \n 9 over < \n if 7 - dup 10 < or then \n dup r> u< ; \n: \/string dup >r - swap r> + swap ; \n: >number \n begin dup \n while >r dup >r c@ base @ digit? \n while swap base @ um* drop rot \n base @ um* d+ r> char+ r> 1 - \n repeat drop r> r> then ; \n: number? \n over c@ [char] - = dup >r if 1 \/string then \n >r >r 0 dup r> r> -1 dpl ! \n begin >number dup \n while over c@ [char] . xor \n if rot drop rot r> 2drop false exit \n then 1 - dpl ! char+ dpl @ \n repeat 2drop r> if dnegate then true ; \n' number? 'number ! \n: $interpret \n context @ find \n if drop execute exit then \n count 'number @execute if \n dpl @ 0< if drop then exit then .\" ?\" type ; \n: $compile \n context @ find \n if cell- @ =immed = \n if execute else , then exit \n then count 'number @execute \n if \n dpl @ 0< \n if drop postpone literal \n else postpone 2literal \n then exit \n then .\" ?\" type ; \n: eval state? if $compile else $interpret then ; \n' eval 'eval ! \n: eval \n begin token dup c@ while \n 'eval @execute \n repeat drop ; \n: ok cr .\" ok.\" space ; \n' ok 'prompt ! \n: quit \n begin 'prompt @execute query \n eval again ; \n: bye .\" good bye \" cr halt ; \n' quit boot ! \n: sp@ spp @ ; \n: depth sp@ sp0 @ - cell \/ ; \n: pick cells sp@ swap - 2 cells - @ ; \n: .s cr depth for aft r@ pick . then next space .\" \n @ space repeat drop cr ; \n \n: rpick r> rpp @ swap >r + 2- @ ; \n: do compile 2>r postpone begin ; immediate \n: _loop r> r> 1+ dup r@ 1- > swap >r swap >r ; \n: _+loop r> swap r> swap + dup r@ 1- > swap >r swap >r ; \n: leave r> 2r> 2drop >r ; \n: unloop r> r> drop r@ r> r> ; \n: loop compile _loop postpone until compile leave ; immediate \n: +loop compile _+loop postpone until compile leave ; immediate \n: i r> r> tuck >r >r ; \n: j 4 rpick ; \n: k 4 rpick ;\n\nvariable file \n: open f_open file ! ; \n: close file @ f_close ; \n: fput file @ putc ; \n: fget file @ getc ; \n: fputs count for aft dup c@ fput 1+ then next drop ; \n\n: savevm $\" eforth.img\" $\" wb\" open 0 \n 16384 for aft dup c@ fput 1+ then next close drop ; \n\nsavevm \n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"75a65e7ff8550a563c9ba1045b49d3cb42819690","subject":"4 assertions added","message":"4 assertions added\n","repos":"bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas","old_file":"KataDiversion_tests.fth","new_file":"KataDiversion_tests.fth","new_contents":"\\ KataDiversion tests, in Forth\n\\ running tests:\n\\ gforth KataDiversion_tests.fth -e bye\n\nREQUIRE KataDiversion.fth\n\nVARIABLE ASSERT-COUNT\n0 ASSERT-COUNT !\n\n: ASSERT-EQUAL ( n1 n2 -- n1 n2 )\n 2DUP <> IF 1 ABORT\" AssertEqual: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ - tests -\n\n\\ ?MAX-NB\n0 ?MAX-NB 0 ASSERT-EQUAL\n1 ?MAX-NB 2 ASSERT-EQUAL\n2 ?MAX-NB 4 ASSERT-EQUAL\n3 ?MAX-NB 8 ASSERT-EQUAL\n\n\n\n\\ ---------\n\nASSERT-COUNT @ . .\" assertions successfully passed.\" CR\n\n","old_contents":"\\ KataDiversion tests, in Forth\n\nINCLUDE KataDiversion.ft\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"eaa93f5a2f480f7198abc747e36a95b2e814d0e7","subject":"PROBLEM: putting in a loader config file a line of the form","message":"PROBLEM: putting in a loader config file a line of the form\n\n loader_conf_files=\"foo bar baz\"\n\nshould cause loading the files listed, and then resume with the\nremaining config files (from previous values of the variable).\nUnfortunately, sometimes the line was ignored -- actually even\nmodifying the line in \/boot\/default\/loader.conf sometimes doesn't work.\n\nANALYSIS: After much investigation, turned out to be a bug in the logic.\nThe existing code detected a new assignment by looking at the address\nof the the variable containing the string. This only worked by pure\nchance, i.e. if the new string is longer than the previous value\nthen the memory allocator may return a different address\nto store the string hence triggering the detection.\n\nSOLUTION: This commit contains a minimal change to fix the problem,\nwithout altering too much the existing structure of the code.\nHowever, as a step towards improving the quality and reliability of\nthis code, I have introduced a handful of one-line functions\n(strget, strset, strfree, string= ) that could be used in dozens\nof places in the existing code.\n\nHOWEVER:\nThere is a much bigger problem here. Even though I am no Forth\nexpert (as most fellow src committers) I can tell that much of the\nforth code (in support.4th at least) is in severe need of a\nreview\/refactoring:\n\n+ pieces of code are replicated multiple times instead of writing\n functions (see e.g. set_module_*);\n\n+ a lot of stale code (e.g. \"structure\" definitions for\n preloaded_files, kernel_module, pnp stuff) which is not used\n or at least belongs elsewhere.\n The code bload is extremely bad as the loader runs with very small\n memory constraints, and we already hit the limit once (see\n\n http:\/\/svn.freebsd.org\/viewvc\/base?view=revision&revision=185132\n Reducing the footprint of the forth files is critical.\n\n+ two different styles of coding, one using pure stack functions\n (maybe beautiful but surely highly unreadable), one using\n high level mechanisms to give names to arguments and local\n variables (which leads to readable code).\n\nNote that this code is used by default by all FreeBSD installations,\nso the fragility and the code bloat are extremely damaging.\nI will try to work fixing the three items above, but if others have\ntime, please have a look at these issues.\n\nMFC after:\t4 weeks\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/support.4th","new_file":"sys\/boot\/forth\/support.4th","new_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\ \n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\n\\ Loader.rc support functions:\n\\\n\\ initialize_support ( -- )\tinitialize global variables\n\\ initialize ( addr len -- )\tas above, plus load_conf_files\n\\ load_conf ( addr len -- )\tload conf file given\n\\ include_conf_files ( -- )\tload all conf files in load_conf_files\n\\ print_syntax_error ( -- )\tprint line and marker of where a syntax\n\\\t\t\t\terror was detected\n\\ print_line ( -- )\t\tprint last line processed\n\\ load_kernel ( -- )\t\tload kernel\n\\ load_modules ( -- )\t\tload modules flagged\n\\\n\\ Exported structures:\n\\\n\\ string\t\t\tcounted string structure\n\\\tcell .addr\t\t\tstring address\n\\\tcell .len\t\t\tstring length\n\\ module\t\t\tmodule loading information structure\n\\\tcell module.flag\t\tshould we load it?\n\\\tstring module.name\t\tmodule's name\n\\\tstring module.loadname\t\tname to be used in loading the module\n\\\tstring module.type\t\tmodule's type\n\\\tstring module.args\t\tflags to be passed during load\n\\\tstring module.beforeload\tcommand to be executed before load\n\\\tstring module.afterload\t\tcommand to be executed after load\n\\\tstring module.loaderror\t\tcommand to be executed if load fails\n\\\tcell module.next\t\tlist chain\n\\\n\\ Exported global variables;\n\\\n\\ string conf_files\t\tconfiguration files to be loaded\n\\ string password\t\tpassword\n\\ cell modules_options\t\tpointer to first module information\n\\ value verbose?\t\tindicates if user wants a verbose loading\n\\ value any_conf_read?\t\tindicates if a conf file was succesfully read\n\\\n\\ Other exported words:\n\\\n\\ strdup ( addr len -- addr' len)\t\t\tsimilar to strdup(3)\n\\ strcat ( addr len addr' len' -- addr len+len' )\tsimilar to strcat(3)\n\\ strlen ( addr -- len )\t\t\t\tsimilar to strlen(3)\n\\ s' ( | string' -- addr len | )\t\t\tsimilar to s\"\n\\ rudimentary structure support\n\n\\ Exception values\n\n1 constant syntax_error\n2 constant out_of_memory\n3 constant free_error\n4 constant set_error\n5 constant read_error\n6 constant open_error\n7 constant exec_error\n8 constant before_load_error\n9 constant after_load_error\n\n\\ I\/O constants\n\n0 constant SEEK_SET\n1 constant SEEK_CUR\n2 constant SEEK_END\n\n0 constant O_RDONLY\n1 constant O_WRONLY\n2 constant O_RDWR\n\n\\ Crude structure support\n\n: structure:\n create here 0 , ['] drop , 0\n does> create here swap dup @ allot cell+ @ execute\n;\n: member: create dup , over , + does> cell+ @ + ;\n: ;structure swap ! ;\n: constructor! >body cell+ ! ;\n: constructor: over :noname ;\n: ;constructor postpone ; swap cell+ ! ; immediate\n: sizeof ' >body @ state @ if postpone literal then ; immediate\n: offsetof ' >body cell+ @ state @ if postpone literal then ; immediate\n: ptr 1 cells member: ;\n: int 1 cells member: ;\n\n\\ String structure\n\nstructure: string\n\tptr .addr\n\tint .len\n\tconstructor:\n\t 0 over .addr !\n\t 0 swap .len !\n\t;constructor\n;structure\n\n\n\\ Module options linked list\n\nstructure: module\n\tint module.flag\n\tsizeof string member: module.name\n\tsizeof string member: module.loadname\n\tsizeof string member: module.type\n\tsizeof string member: module.args\n\tsizeof string member: module.beforeload\n\tsizeof string member: module.afterload\n\tsizeof string member: module.loaderror\n\tptr module.next\n;structure\n\n\\ Internal loader structures\nstructure: preloaded_file\n\tptr pf.name\n\tptr pf.type\n\tptr pf.args\n\tptr pf.metadata\t\\ file_metadata\n\tint pf.loader\n\tint pf.addr\n\tint pf.size\n\tptr pf.modules\t\\ kernel_module\n\tptr pf.next\t\\ preloaded_file\n;structure\n\nstructure: kernel_module\n\tptr km.name\n\t\\ ptr km.args\n\tptr km.fp\t\\ preloaded_file\n\tptr km.next\t\\ kernel_module\n;structure\n\nstructure: file_metadata\n\tint\t\tmd.size\n\t2 member:\tmd.type\t\\ this is not ANS Forth compatible (XXX)\n\tptr\t\tmd.next\t\\ file_metadata\n\t0 member:\tmd.data\t\\ variable size\n;structure\n\nstructure: config_resource\n\tptr cf.name\n\tint cf.type\n0 constant RES_INT\n1 constant RES_STRING\n2 constant RES_LONG\n\t2 cells member: u\n;structure\n\nstructure: config_device\n\tptr cd.name\n\tint cd.unit\n\tint cd.resource_count\n\tptr cd.resources\t\\ config_resource\n;structure\n\nstructure: STAILQ_HEAD\n\tptr stqh_first\t\\ type*\n\tptr stqh_last\t\\ type**\n;structure\n\nstructure: STAILQ_ENTRY\n\tptr stqe_next\t\\ type*\n;structure\n\nstructure: pnphandler\n\tptr pnph.name\n\tptr pnph.enumerate\n;structure\n\nstructure: pnpident\n\tptr pnpid.ident\t\t\t\t\t\\ char*\n\tsizeof STAILQ_ENTRY cells member: pnpid.link\t\\ pnpident\n;structure\n\nstructure: pnpinfo\n\tptr pnpi.desc\n\tint pnpi.revision\n\tptr pnpi.module\t\t\t\t\\ (char*) module args\n\tint pnpi.argc\n\tptr pnpi.argv\n\tptr pnpi.handler\t\t\t\\ pnphandler\n\tsizeof STAILQ_HEAD member: pnpi.ident\t\\ pnpident\n\tsizeof STAILQ_ENTRY member: pnpi.link\t\\ pnpinfo\n;structure\n\n\\ Global variables\n\nstring conf_files\nstring nextboot_conf_file\nstring password\ncreate module_options sizeof module.next allot 0 module_options !\ncreate last_module_option sizeof module.next allot 0 last_module_option !\n0 value verbose?\n0 value nextboot?\n\n\\ Support string functions\n\n: strdup ( addr len -- addr' len )\n >r r@ allocate if out_of_memory throw then\n tuck r@ move\n r>\n;\n\n: strcat { addr len addr' len' -- addr len+len' }\n addr' addr len + len' move\n addr len len' +\n;\n\n: strlen ( addr -- len )\n 0 >r\n begin\n dup c@ while\n 1+ r> 1+ >r repeat\n drop r>\n;\n\n: s' \n [char] ' parse\n state @ if\n postpone sliteral\n then\n; immediate\n\n: 2>r postpone >r postpone >r ; immediate\n: 2r> postpone r> postpone r> ; immediate\n: 2r@ postpone 2r> postpone 2dup postpone 2>r ; immediate\n\n: getenv?\n getenv\n -1 = if false else drop true then\n;\n\n\\ Private definitions\n\nvocabulary support-functions\nonly forth also support-functions definitions\n\n\\ Some control characters constants\n\n7 constant bell\n8 constant backspace\n9 constant tab\n10 constant lf\n13 constant \n\n\\ Read buffer size\n\n80 constant read_buffer_size\n\n\\ Standard suffixes\n\n: load_module_suffix s\" _load\" ;\n: module_loadname_suffix s\" _name\" ;\n: module_type_suffix s\" _type\" ;\n: module_args_suffix s\" _flags\" ;\n: module_beforeload_suffix s\" _before\" ;\n: module_afterload_suffix s\" _after\" ;\n: module_loaderror_suffix s\" _error\" ;\n\n\\ Support operators\n\n: >= < 0= ;\n: <= > 0= ;\n\n\\ Assorted support funcitons\n\n: free-memory free if free_error throw then ;\n\n: strget { var -- addr len } var .addr @ var .len @ ;\n\n\\ assign addr len to variable.\n: strset { addr len var -- } addr var .addr ! len var .len ! ;\n\n\\ free memory and reset fields\n: strfree { var -- } var .addr @ ?dup if free-memory 0 0 var strset then ;\n\n\\ free old content, make a copy of the string and assign to variable\n: string= { addr len var -- } var strfree addr len strdup var strset ;\n\n\\ Assignment data temporary storage\n\nstring name_buffer\nstring value_buffer\n\n\\ Line by line file reading functions\n\\\n\\ exported:\n\\\tline_buffer\n\\\tend_of_file?\n\\\tfd\n\\\tread_line\n\\\treset_line_reading\n\nvocabulary line-reading\nalso line-reading definitions also\n\n\\ File data temporary storage\n\nstring read_buffer\n0 value read_buffer_ptr\n\n\\ File's line reading function\n\nsupport-functions definitions\n\nstring line_buffer\n0 value end_of_file?\nvariable fd\n\nline-reading definitions\n\n: skip_newlines\n begin\n read_buffer .len @ read_buffer_ptr >\n while\n read_buffer .addr @ read_buffer_ptr + c@ lf = if\n read_buffer_ptr char+ to read_buffer_ptr\n else\n exit\n then\n repeat\n;\n\n: scan_buffer ( -- addr len )\n read_buffer_ptr >r\n begin\n read_buffer .len @ r@ >\n while\n read_buffer .addr @ r@ + c@ lf = if\n read_buffer .addr @ read_buffer_ptr + ( -- addr )\n r@ read_buffer_ptr - ( -- len )\n r> to read_buffer_ptr\n exit\n then\n r> char+ >r\n repeat\n read_buffer .addr @ read_buffer_ptr + ( -- addr )\n r@ read_buffer_ptr - ( -- len )\n r> to read_buffer_ptr\n;\n\n: line_buffer_resize ( len -- len )\n >r\n line_buffer .len @ if\n line_buffer .addr @\n line_buffer .len @ r@ +\n resize if out_of_memory throw then\n else\n r@ allocate if out_of_memory throw then\n then\n line_buffer .addr !\n r>\n;\n \n: append_to_line_buffer ( addr len -- )\n line_buffer .addr @ line_buffer .len @\n 2swap strcat\n line_buffer .len !\n drop\n;\n\n: read_from_buffer\n scan_buffer ( -- addr len )\n line_buffer_resize ( len -- len )\n append_to_line_buffer ( addr len -- )\n;\n\n: refill_required?\n read_buffer .len @ read_buffer_ptr =\n end_of_file? 0= and\n;\n\n: refill_buffer\n 0 to read_buffer_ptr\n read_buffer .addr @ 0= if\n read_buffer_size allocate if out_of_memory throw then\n read_buffer .addr !\n then\n fd @ read_buffer .addr @ read_buffer_size fread\n dup -1 = if read_error throw then\n dup 0= if true to end_of_file? then\n read_buffer .len !\n;\n\n: reset_line_buffer\n line_buffer .addr @ ?dup if\n free-memory\n then\n 0 line_buffer .addr !\n 0 line_buffer .len !\n;\n\nsupport-functions definitions\n\n: reset_line_reading\n 0 to read_buffer_ptr\n;\n\n: read_line\n reset_line_buffer\n skip_newlines\n begin\n read_from_buffer\n refill_required?\n while\n refill_buffer\n repeat\n;\n\nonly forth also support-functions definitions\n\n\\ Conf file line parser:\n\\ ::= '='[] |\n\\ []\n\\ ::= {||'_'}\n\\ ::= '\"'{|'\\'}'\"' | \n\\ ::= ASCII 32 to 126, except '\\' and '\"'\n\\ ::= '#'{}\n\\\n\\ exported:\n\\\tline_pointer\n\\\tprocess_conf\n\n0 value line_pointer\n\nvocabulary file-processing\nalso file-processing definitions\n\n\\ parser functions\n\\\n\\ exported:\n\\\tget_assignment\n\nvocabulary parser\nalso parser definitions also\n\n0 value parsing_function\n0 value end_of_line\n\n: end_of_line?\n line_pointer end_of_line =\n;\n\n: letter?\n line_pointer c@ >r\n r@ [char] A >=\n r@ [char] Z <= and\n r@ [char] a >=\n r> [char] z <= and\n or\n;\n\n: digit?\n line_pointer c@ >r\n r@ [char] - =\n r@ [char] 0 >=\n r> [char] 9 <= and\n or\n;\n\n: quote?\n line_pointer c@ [char] \" =\n;\n\n: assignment_sign?\n line_pointer c@ [char] = =\n;\n\n: comment?\n line_pointer c@ [char] # =\n;\n\n: space?\n line_pointer c@ bl =\n line_pointer c@ tab = or\n;\n\n: backslash?\n line_pointer c@ [char] \\ =\n;\n\n: underscore?\n line_pointer c@ [char] _ =\n;\n\n: dot?\n line_pointer c@ [char] . =\n;\n\n: skip_character\n line_pointer char+ to line_pointer\n;\n\n: skip_to_end_of_line\n end_of_line to line_pointer\n;\n\n: eat_space\n begin\n space?\n while\n skip_character\n end_of_line? if exit then\n repeat\n;\n\n: parse_name ( -- addr len )\n line_pointer\n begin\n letter? digit? underscore? dot? or or or\n while\n skip_character\n end_of_line? if \n line_pointer over -\n strdup\n exit\n then\n repeat\n line_pointer over -\n strdup\n;\n\n: remove_backslashes { addr len | addr' len' -- addr' len' }\n len allocate if out_of_memory throw then\n to addr'\n addr >r\n begin\n addr c@ [char] \\ <> if\n addr c@ addr' len' + c!\n len' char+ to len'\n then\n addr char+ to addr\n r@ len + addr =\n until\n r> drop\n addr' len'\n;\n\n: parse_quote ( -- addr len )\n line_pointer\n skip_character\n end_of_line? if syntax_error throw then\n begin\n quote? 0=\n while\n backslash? if\n skip_character\n end_of_line? if syntax_error throw then\n then\n skip_character\n end_of_line? if syntax_error throw then \n repeat\n skip_character\n line_pointer over -\n remove_backslashes\n;\n\n: read_name\n parse_name\t\t( -- addr len )\n name_buffer .len !\n name_buffer .addr !\n;\n\n: read_value\n quote? if\n parse_quote\t\t( -- addr len )\n else\n parse_name\t\t( -- addr len )\n then\n value_buffer .len !\n value_buffer .addr !\n;\n\n: comment\n skip_to_end_of_line\n;\n\n: white_space_4\n eat_space\n comment? if ['] comment to parsing_function exit then\n end_of_line? 0= if syntax_error throw then\n;\n\n: variable_value\n read_value\n ['] white_space_4 to parsing_function\n;\n\n: white_space_3\n eat_space\n letter? digit? quote? or or if\n ['] variable_value to parsing_function exit\n then\n syntax_error throw\n;\n\n: assignment_sign\n skip_character\n ['] white_space_3 to parsing_function\n;\n\n: white_space_2\n eat_space\n assignment_sign? if ['] assignment_sign to parsing_function exit then\n syntax_error throw\n;\n\n: variable_name\n read_name\n ['] white_space_2 to parsing_function\n;\n\n: white_space_1\n eat_space\n letter? if ['] variable_name to parsing_function exit then\n comment? if ['] comment to parsing_function exit then\n end_of_line? 0= if syntax_error throw then\n;\n\nfile-processing definitions\n\n: get_assignment\n line_buffer .addr @ line_buffer .len @ + to end_of_line\n line_buffer .addr @ to line_pointer\n ['] white_space_1 to parsing_function\n begin\n end_of_line? 0=\n while\n parsing_function execute\n repeat\n parsing_function ['] comment =\n parsing_function ['] white_space_1 =\n parsing_function ['] white_space_4 =\n or or 0= if syntax_error throw then\n;\n\nonly forth also support-functions also file-processing definitions also\n\n\\ Process line\n\n: assignment_type? ( addr len -- flag )\n name_buffer .addr @ name_buffer .len @\n compare 0=\n;\n\n: suffix_type? ( addr len -- flag )\n name_buffer .len @ over <= if 2drop false exit then\n name_buffer .len @ over - name_buffer .addr @ +\n over compare 0=\n;\n\n: loader_conf_files?\n s\" loader_conf_files\" assignment_type?\n;\n\n: nextboot_flag?\n s\" nextboot_enable\" assignment_type?\n;\n\n: nextboot_conf?\n s\" nextboot_conf\" assignment_type?\n;\n\n: verbose_flag?\n s\" verbose_loading\" assignment_type?\n;\n\n: execute?\n s\" exec\" assignment_type?\n;\n\n: password?\n s\" password\" assignment_type?\n;\n\n: module_load?\n load_module_suffix suffix_type?\n;\n\n: module_loadname?\n module_loadname_suffix suffix_type?\n;\n\n: module_type?\n module_type_suffix suffix_type?\n;\n\n: module_args?\n module_args_suffix suffix_type?\n;\n\n: module_beforeload?\n module_beforeload_suffix suffix_type?\n;\n\n: module_afterload?\n module_afterload_suffix suffix_type?\n;\n\n: module_loaderror?\n module_loaderror_suffix suffix_type?\n;\n\n: set_nextboot_conf\n nextboot_conf_file .addr @ ?dup if\n free-memory\n then\n value_buffer .addr @ c@ [char] \" = if\n value_buffer .addr @ char+ value_buffer .len @ 2 chars -\n else\n value_buffer .addr @ value_buffer .len @\n then\n strdup\n nextboot_conf_file .len ! nextboot_conf_file .addr !\n;\n\n: append_to_module_options_list ( addr -- )\n module_options @ 0= if\n dup module_options !\n last_module_option !\n else\n dup last_module_option @ module.next !\n last_module_option !\n then\n;\n\n: set_module_name ( addr -- )\n name_buffer .addr @ name_buffer .len @\n strdup\n >r over module.name .addr !\n r> swap module.name .len !\n;\n\n: yes_value?\n value_buffer .addr @ value_buffer .len @\n 2dup s' \"YES\"' compare >r\n 2dup s' \"yes\"' compare >r\n 2dup s\" YES\" compare >r\n s\" yes\" compare r> r> r> and and and 0=\n;\n\n: find_module_option ( -- addr | 0 )\n module_options @\n begin\n dup\n while\n dup module.name dup .addr @ swap .len @\n name_buffer .addr @ name_buffer .len @\n compare 0= if exit then\n module.next @\n repeat\n;\n\n: new_module_option ( -- addr )\n sizeof module allocate if out_of_memory throw then\n dup sizeof module erase\n dup append_to_module_options_list\n dup set_module_name\n;\n\n: get_module_option ( -- addr )\n find_module_option\n ?dup 0= if new_module_option then\n;\n\n: set_module_flag\n name_buffer .len @ load_module_suffix nip - name_buffer .len !\n yes_value? get_module_option module.flag !\n;\n\n: set_module_args\n name_buffer .len @ module_args_suffix nip - name_buffer .len !\n get_module_option module.args\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_loadname\n name_buffer .len @ module_loadname_suffix nip - name_buffer .len !\n get_module_option module.loadname\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_type\n name_buffer .len @ module_type_suffix nip - name_buffer .len !\n get_module_option module.type\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_beforeload\n name_buffer .len @ module_beforeload_suffix nip - name_buffer .len !\n get_module_option module.beforeload\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_afterload\n name_buffer .len @ module_afterload_suffix nip - name_buffer .len !\n get_module_option module.afterload\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_loaderror\n name_buffer .len @ module_loaderror_suffix nip - name_buffer .len !\n get_module_option module.loaderror\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_environment_variable\n name_buffer .len @\n value_buffer .len @ +\n 5 chars +\n allocate if out_of_memory throw then\n dup 0 ( addr -- addr addr len )\n s\" set \" strcat\n name_buffer .addr @ name_buffer .len @ strcat\n s\" =\" strcat\n value_buffer .addr @ value_buffer .len @ strcat\n ['] evaluate catch if\n 2drop free drop\n set_error throw\n else\n free-memory\n then\n;\n\n: set_conf_files\n set_environment_variable\n s\" loader_conf_files\" getenv conf_files string=\n;\n\n: set_nextboot_flag\n yes_value? to nextboot?\n;\n\n: set_verbose\n yes_value? to verbose?\n;\n\n: execute_command\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 - swap char+ swap\n then\n ['] evaluate catch if exec_error throw then\n;\n\n: set_password\n password .addr @ ?dup if free if free_error throw then then\n value_buffer .addr @ c@ [char] \" = if\n value_buffer .addr @ char+ value_buffer .len @ 2 - strdup\n value_buffer .addr @ free if free_error throw then\n else\n value_buffer .addr @ value_buffer .len @\n then\n password .len ! password .addr !\n 0 value_buffer .addr !\n;\n\n: process_assignment\n name_buffer .len @ 0= if exit then\n loader_conf_files?\tif set_conf_files exit then\n nextboot_flag?\tif set_nextboot_flag exit then\n nextboot_conf?\tif set_nextboot_conf exit then\n verbose_flag?\t\tif set_verbose exit then\n execute?\t\tif execute_command exit then\n password?\t\tif set_password exit then\n module_load?\t\tif set_module_flag exit then\n module_loadname?\tif set_module_loadname exit then\n module_type?\t\tif set_module_type exit then\n module_args?\t\tif set_module_args exit then\n module_beforeload?\tif set_module_beforeload exit then\n module_afterload?\tif set_module_afterload exit then\n module_loaderror?\tif set_module_loaderror exit then\n set_environment_variable\n;\n\n\\ free_buffer ( -- )\n\\\n\\ Free some pointers if needed. The code then tests for errors\n\\ in freeing, and throws an exception if needed. If a pointer is\n\\ not allocated, it's value (0) is used as flag.\n\n: free_buffers\n name_buffer .addr @ dup if free then\n value_buffer .addr @ dup if free then\n or if free_error throw then\n;\n\n: reset_assignment_buffers\n 0 name_buffer .addr !\n 0 name_buffer .len !\n 0 value_buffer .addr !\n 0 value_buffer .len !\n;\n\n\\ Higher level file processing\n\nsupport-functions definitions\n\n: process_conf\n begin\n end_of_file? 0=\n while\n reset_assignment_buffers\n read_line\n get_assignment\n ['] process_assignment catch\n ['] free_buffers catch\n swap throw throw\n repeat\n;\n\n: peek_file\n 0 to end_of_file?\n reset_line_reading\n O_RDONLY fopen fd !\n fd @ -1 = if open_error throw then\n reset_assignment_buffers\n read_line\n get_assignment\n ['] process_assignment catch\n ['] free_buffers catch\n fd @ fclose\n;\n \nonly forth also support-functions definitions\n\n\\ Interface to loading conf files\n\n: load_conf ( addr len -- )\n 0 to end_of_file?\n reset_line_reading\n O_RDONLY fopen fd !\n fd @ -1 = if open_error throw then\n ['] process_conf catch\n fd @ fclose\n throw\n;\n\n: print_line\n line_buffer .addr @ line_buffer .len @ type cr\n;\n\n: print_syntax_error\n line_buffer .addr @ line_buffer .len @ type cr\n line_buffer .addr @\n begin\n line_pointer over <>\n while\n bl emit\n char+\n repeat\n drop\n .\" ^\" cr\n;\n\n\\ Debugging support functions\n\nonly forth definitions also support-functions\n\n: test-file \n ['] load_conf catch dup .\n syntax_error = if cr print_syntax_error then\n;\n\n: show-module-options\n module_options @\n begin\n ?dup\n while\n .\" Name: \" dup module.name dup .addr @ swap .len @ type cr\n .\" Path: \" dup module.loadname dup .addr @ swap .len @ type cr\n .\" Type: \" dup module.type dup .addr @ swap .len @ type cr\n .\" Flags: \" dup module.args dup .addr @ swap .len @ type cr\n .\" Before load: \" dup module.beforeload dup .addr @ swap .len @ type cr\n .\" After load: \" dup module.afterload dup .addr @ swap .len @ type cr\n .\" Error: \" dup module.loaderror dup .addr @ swap .len @ type cr\n .\" Status: \" dup module.flag @ if .\" Load\" else .\" Don't load\" then cr\n module.next @\n repeat\n;\n\nonly forth also support-functions definitions\n\n\\ Variables used for processing multiple conf files\n\nstring current_file_name\n\n\\ Indicates if any conf file was succesfully read\n\n0 value any_conf_read?\n\n\\ loader_conf_files processing support functions\n\n: get_conf_files ( -- addr len ) \\ put addr\/len on stack, reset var\n conf_files strget 0 0 conf_files strset\n;\n\n: skip_leading_spaces { addr len pos -- addr len pos' }\n begin\n pos len = if addr len pos exit then\n addr pos + c@ bl =\n while\n pos char+ to pos\n repeat\n addr len pos\n;\n\n: get_file_name { addr len pos -- addr len pos' addr' len' || 0 }\n pos len = if \n addr free abort\" Fatal error freeing memory\"\n 0 exit\n then\n pos >r\n begin\n addr pos + c@ bl <>\n while\n pos char+ to pos\n pos len = if\n addr len pos addr r@ + pos r> - exit\n then\n repeat\n addr len pos addr r@ + pos r> -\n;\n\n: get_next_file ( addr len ptr -- addr len ptr' addr' len' | 0 )\n skip_leading_spaces\n get_file_name\n;\n\n: set_current_file_name\n over current_file_name .addr !\n dup current_file_name .len !\n;\n\n: print_current_file\n current_file_name .addr @ current_file_name .len @ type\n;\n\n: process_conf_errors\n dup 0= if true to any_conf_read? drop exit then\n >r 2drop r>\n dup syntax_error = if\n .\" Warning: syntax error on file \" print_current_file cr\n print_syntax_error drop exit\n then\n dup set_error = if\n .\" Warning: bad definition on file \" print_current_file cr\n print_line drop exit\n then\n dup read_error = if\n .\" Warning: error reading file \" print_current_file cr drop exit\n then\n dup open_error = if\n verbose? if .\" Warning: unable to open file \" print_current_file cr then\n drop exit\n then\n dup free_error = abort\" Fatal error freeing memory\"\n dup out_of_memory = abort\" Out of memory\"\n throw \\ Unknown error -- pass ahead\n;\n\n\\ Process loader_conf_files recursively\n\\ Interface to loader_conf_files processing\n\n: include_conf_files\n get_conf_files 0\n begin\n get_next_file ?dup\n while\n set_current_file_name\n ['] load_conf catch\n process_conf_errors\n conf_files .addr @ if recurse then\n repeat\n;\n\n: get_nextboot_conf_file ( -- addr len )\n nextboot_conf_file .addr @ nextboot_conf_file .len @ strdup\n;\n\n: rewrite_nextboot_file ( -- )\n get_nextboot_conf_file\n O_WRONLY fopen fd !\n fd @ -1 = if open_error throw then\n fd @ s' nextboot_enable=\"NO\" ' fwrite\n fd @ fclose\n;\n\n: include_nextboot_file\n get_nextboot_conf_file\n ['] peek_file catch\n nextboot? if\n get_nextboot_conf_file\n ['] load_conf catch\n process_conf_errors\n ['] rewrite_nextboot_file catch\n then\n;\n\n\\ Module loading functions\n\n: load_module?\n module.flag @\n;\n\n: load_parameters ( addr -- addr addrN lenN ... addr1 len1 N )\n dup >r\n r@ module.args .addr @ r@ module.args .len @\n r@ module.loadname .len @ if\n r@ module.loadname .addr @ r@ module.loadname .len @\n else\n r@ module.name .addr @ r@ module.name .len @\n then\n r@ module.type .len @ if\n r@ module.type .addr @ r@ module.type .len @\n s\" -t \"\n 4 ( -t type name flags )\n else\n 2 ( name flags )\n then\n r> drop\n;\n\n: before_load ( addr -- addr )\n dup module.beforeload .len @ if\n dup module.beforeload .addr @ over module.beforeload .len @\n ['] evaluate catch if before_load_error throw then\n then\n;\n\n: after_load ( addr -- addr )\n dup module.afterload .len @ if\n dup module.afterload .addr @ over module.afterload .len @\n ['] evaluate catch if after_load_error throw then\n then\n;\n\n: load_error ( addr -- addr )\n dup module.loaderror .len @ if\n dup module.loaderror .addr @ over module.loaderror .len @\n evaluate \\ This we do not intercept so it can throw errors\n then\n;\n\n: pre_load_message ( addr -- addr )\n verbose? if\n dup module.name .addr @ over module.name .len @ type\n .\" ...\"\n then\n;\n\n: load_error_message verbose? if .\" failed!\" cr then ;\n\n: load_succesful_message verbose? if .\" ok\" cr then ;\n\n: load_module\n load_parameters load\n;\n\n: process_module ( addr -- addr )\n pre_load_message\n before_load\n begin\n ['] load_module catch if\n dup module.loaderror .len @ if\n load_error\t\t\t\\ Command should return a flag!\n else \n load_error_message true\t\t\\ Do not retry\n then\n else\n after_load\n load_succesful_message true\t\\ Succesful, do not retry\n then\n until\n;\n\n: process_module_errors ( addr ior -- )\n dup before_load_error = if\n drop\n .\" Module \"\n dup module.name .addr @ over module.name .len @ type\n dup module.loadname .len @ if\n .\" (\" dup module.loadname .addr @ over module.loadname .len @ type .\" )\"\n then\n cr\n .\" Error executing \"\n dup module.beforeload .addr @ over module.afterload .len @ type cr\n abort\n then\n\n dup after_load_error = if\n drop\n .\" Module \"\n dup module.name .addr @ over module.name .len @ type\n dup module.loadname .len @ if\n .\" (\" dup module.loadname .addr @ over module.loadname .len @ type .\" )\"\n then\n cr\n .\" Error executing \"\n dup module.afterload .addr @ over module.afterload .len @ type cr\n abort\n then\n\n throw \\ Don't know what it is all about -- pass ahead\n;\n\n\\ Module loading interface\n\n: load_modules ( -- ) ( throws: abort & user-defined )\n module_options @\n begin\n ?dup\n while\n dup load_module? if\n ['] process_module catch\n process_module_errors\n then\n module.next @\n repeat\n;\n\n\\ h00h00 magic used to try loading either a kernel with a given name,\n\\ or a kernel with the default name in a directory of a given name\n\\ (the pain!)\n\n: bootpath s\" \/boot\/\" ;\n: modulepath s\" module_path\" ;\n\n\\ Functions used to save and restore module_path's value.\n: saveenv ( addr len | -1 -- addr' len | 0 -1 )\n dup -1 = if 0 swap exit then\n strdup\n;\n: freeenv ( addr len | 0 -1 )\n -1 = if drop else free abort\" Freeing error\" then\n;\n: restoreenv ( addr len | 0 -1 -- )\n dup -1 = if ( it wasn't set )\n 2drop\n modulepath unsetenv\n else\n over >r\n modulepath setenv\n r> free abort\" Freeing error\"\n then\n;\n\n: clip_args \\ Drop second string if only one argument is passed\n 1 = if\n 2swap 2drop\n 1\n else\n 2\n then\n;\n\nalso builtins\n\n\\ Parse filename from a comma-separated list\n\n: parse-; ( addr len -- addr' len-x addr x )\n over 0 2swap\n begin\n dup 0 <>\n while\n over c@ [char] ; <>\n while\n 1- swap 1+ swap\n 2swap 1+ 2swap\n repeat then\n dup 0 <> if\n 1- swap 1+ swap\n then\n 2swap\n;\n\n\\ Try loading one of multiple kernels specified\n\n: try_multiple_kernels ( addr len addr' len' args -- flag )\n >r\n begin\n parse-; 2>r\n 2over 2r>\n r@ clip_args\n s\" DEBUG\" getenv? if\n s\" echo Module_path: ${module_path}\" evaluate\n .\" Kernel : \" >r 2dup type r> cr\n dup 2 = if .\" Flags : \" >r 2over type r> cr then\n then\n 1 load\n while\n dup 0=\n until\n 1 >r \\ Failure\n else\n 0 >r \\ Success\n then\n 2drop 2drop\n r>\n r> drop\n;\n\n\\ Try to load a kernel; the kernel name is taken from one of\n\\ the following lists, as ordered:\n\\\n\\ 1. The \"bootfile\" environment variable\n\\ 2. The \"kernel\" environment variable\n\\\n\\ Flags are passed, if available. If not, dummy values must be given.\n\\\n\\ The kernel gets loaded from the current module_path.\n\n: load_a_kernel ( flags len 1 | x x 0 -- flag )\n local args\n 2local flags\n 0 0 2local kernel\n end-locals\n\n \\ Check if a default kernel name exists at all, exits if not\n s\" bootfile\" getenv dup -1 <> if\n to kernel\n flags kernel args 1+ try_multiple_kernels\n dup 0= if exit then\n then\n drop\n\n s\" kernel\" getenv dup -1 <> if\n to kernel\n else\n drop\n 1 exit \\ Failure\n then\n\n \\ Try all default kernel names\n flags kernel args 1+ try_multiple_kernels\n;\n\n\\ Try to load a kernel; the kernel name is taken from one of\n\\ the following lists, as ordered:\n\\\n\\ 1. The \"bootfile\" environment variable\n\\ 2. The \"kernel\" environment variable\n\\\n\\ Flags are passed, if provided.\n\\\n\\ The kernel will be loaded from a directory computed from the\n\\ path given. Two directories will be tried in the following order:\n\\\n\\ 1. \/boot\/path\n\\ 2. path\n\\\n\\ The module_path variable is overridden if load is succesful, by\n\\ prepending the successful path.\n\n: load_from_directory ( path len 1 | flags len' path len 2 -- flag )\n local args\n 2local path\n args 1 = if 0 0 then\n 2local flags\n 0 0 2local oldmodulepath\n 0 0 2local newmodulepath\n end-locals\n\n \\ Set the environment variable module_path, and try loading\n \\ the kernel again.\n modulepath getenv saveenv to oldmodulepath\n\n \\ Try prepending \/boot\/ first\n bootpath nip path nip + \n oldmodulepath nip dup -1 = if\n drop\n else\n 1+ +\n then\n allocate\n if ( out of memory )\n 1 exit\n then\n\n 0\n bootpath strcat\n path strcat\n 2dup to newmodulepath\n modulepath setenv\n\n \\ Try all default kernel names\n flags args 1- load_a_kernel\n 0= if ( success )\n oldmodulepath nip -1 <> if\n newmodulepath s\" ;\" strcat\n oldmodulepath strcat\n modulepath setenv\n newmodulepath drop free-memory\n oldmodulepath drop free-memory\n then\n 0 exit\n then\n\n \\ Well, try without the prepended \/boot\/\n path newmodulepath drop swap move\n newmodulepath drop path nip\n 2dup to newmodulepath\n modulepath setenv\n\n \\ Try all default kernel names\n flags args 1- load_a_kernel\n if ( failed once more )\n oldmodulepath restoreenv\n newmodulepath drop free-memory\n 1\n else\n oldmodulepath nip -1 <> if\n newmodulepath s\" ;\" strcat\n oldmodulepath strcat\n modulepath setenv\n newmodulepath drop free-memory\n oldmodulepath drop free-memory\n then\n 0\n then\n;\n\n\\ Try to load a kernel; the kernel name is taken from one of\n\\ the following lists, as ordered:\n\\\n\\ 1. The \"bootfile\" environment variable\n\\ 2. The \"kernel\" environment variable\n\\ 3. The \"path\" argument\n\\\n\\ Flags are passed, if provided.\n\\\n\\ The kernel will be loaded from a directory computed from the\n\\ path given. Two directories will be tried in the following order:\n\\\n\\ 1. \/boot\/path\n\\ 2. path\n\\\n\\ Unless \"path\" is meant to be kernel name itself. In that case, it\n\\ will first be tried as a full path, and, next, search on the\n\\ directories pointed by module_path.\n\\\n\\ The module_path variable is overridden if load is succesful, by\n\\ prepending the successful path.\n\n: load_directory_or_file ( path len 1 | flags len' path len 2 -- flag )\n local args\n 2local path\n args 1 = if 0 0 then\n 2local flags\n end-locals\n\n \\ First, assume path is an absolute path to a directory\n flags path args clip_args load_from_directory\n dup 0= if exit else drop then\n\n \\ Next, assume path points to the kernel\n flags path args try_multiple_kernels\n;\n\n: initialize ( addr len -- )\n strdup conf_files .len ! conf_files .addr !\n;\n\n: kernel_options ( -- addr len 1 | 0 )\n s\" kernel_options\" getenv\n dup -1 = if drop 0 else 1 then\n;\n\n: standard_kernel_search ( flags 1 | 0 -- flag )\n local args\n args 0= if 0 0 then\n 2local flags\n s\" kernel\" getenv\n dup -1 = if 0 swap then\n 2local path\n end-locals\n\n path nip -1 = if ( there isn't a \"kernel\" environment variable )\n flags args load_a_kernel\n else\n flags path args 1+ clip_args load_directory_or_file\n then\n;\n\n: load_kernel ( -- ) ( throws: abort )\n kernel_options standard_kernel_search\n abort\" Unable to load a kernel!\"\n;\n\n: set_defaultoptions ( -- )\n s\" kernel_options\" getenv dup -1 = if\n drop\n else\n s\" temp_options\" setenv\n then\n;\n\n: argv[] ( aN uN ... a1 u1 N i -- aN uN ... a1 u1 N ai+1 ui+1 )\n 2dup = if 0 0 exit then\n dup >r\n 1+ 2* ( skip N and ui )\n pick\n r>\n 1+ 2* ( skip N and ai )\n pick\n;\n\n: drop_args ( aN uN ... a1 u1 N -- )\n 0 ?do 2drop loop\n;\n\n: argc\n dup\n;\n\n: queue_argv ( aN uN ... a1 u1 N a u -- a u aN uN ... a1 u1 N+1 )\n >r\n over 2* 1+ -roll\n r>\n over 2* 1+ -roll\n 1+\n;\n\n: unqueue_argv ( aN uN ... a1 u1 N -- aN uN ... a2 u2 N-1 a1 u1 )\n 1- -rot\n;\n\n: strlen(argv)\n dup 0= if 0 exit then\n 0 >r\t\\ Size\n 0 >r\t\\ Index\n begin\n argc r@ <>\n while\n r@ argv[]\n nip\n r> r> rot + 1+\n >r 1+ >r\n repeat\n r> drop\n r>\n;\n\n: concat_argv ( aN uN ... a1 u1 N -- a u )\n strlen(argv) allocate if out_of_memory throw then\n 0 2>r\n\n begin\n argc\n while\n unqueue_argv\n 2r> 2swap\n strcat\n s\" \" strcat\n 2>r\n repeat\n drop_args\n 2r>\n;\n\n: set_tempoptions ( addrN lenN ... addr1 len1 N -- addr len 1 | 0 )\n \\ Save the first argument, if it exists and is not a flag\n argc if\n 0 argv[] drop c@ [char] - <> if\n unqueue_argv 2>r \\ Filename\n 1 >r\t\t\\ Filename present\n else\n 0 >r\t\t\\ Filename not present\n then\n else\n 0 >r\t\t\\ Filename not present\n then\n\n \\ If there are other arguments, assume they are flags\n ?dup if\n concat_argv\n 2dup s\" temp_options\" setenv\n drop free if free_error throw then\n else\n set_defaultoptions\n then\n\n \\ Bring back the filename, if one was provided\n r> if 2r> 1 else 0 then\n;\n\n: get_arguments ( -- addrN lenN ... addr1 len1 N )\n 0\n begin\n \\ Get next word on the command line\n parse-word\n ?dup while\n queue_argv\n repeat\n drop ( empty string )\n;\n\n: load_kernel_and_modules ( args -- flag )\n set_tempoptions\n argc >r\n s\" temp_options\" getenv dup -1 <> if\n queue_argv\n else\n drop\n then\n r> if ( a path was passed )\n load_directory_or_file\n else\n standard_kernel_search\n then\n ?dup 0= if ['] load_modules catch then\n;\n\n: read-password { size | buf len -- }\n size allocate if out_of_memory throw then\n to buf\n 0 to len\n begin\n key\n dup backspace = if\n drop\n len if\n backspace emit bl emit backspace emit\n len 1 - to len\n else\n bell emit\n then\n else\n dup = if cr drop buf len exit then\n [char] * emit\n len size < if\n buf len chars + c!\n else\n drop\n then\n len 1+ to len\n then\n again\n;\n\n\\ Go back to straight forth vocabulary\n\nonly forth also definitions\n\n","old_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\ \n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\n\\ Loader.rc support functions:\n\\\n\\ initialize_support ( -- )\tinitialize global variables\n\\ initialize ( addr len -- )\tas above, plus load_conf_files\n\\ load_conf ( addr len -- )\tload conf file given\n\\ include_conf_files ( -- )\tload all conf files in load_conf_files\n\\ print_syntax_error ( -- )\tprint line and marker of where a syntax\n\\\t\t\t\terror was detected\n\\ print_line ( -- )\t\tprint last line processed\n\\ load_kernel ( -- )\t\tload kernel\n\\ load_modules ( -- )\t\tload modules flagged\n\\\n\\ Exported structures:\n\\\n\\ string\t\t\tcounted string structure\n\\\tcell .addr\t\t\tstring address\n\\\tcell .len\t\t\tstring length\n\\ module\t\t\tmodule loading information structure\n\\\tcell module.flag\t\tshould we load it?\n\\\tstring module.name\t\tmodule's name\n\\\tstring module.loadname\t\tname to be used in loading the module\n\\\tstring module.type\t\tmodule's type\n\\\tstring module.args\t\tflags to be passed during load\n\\\tstring module.beforeload\tcommand to be executed before load\n\\\tstring module.afterload\t\tcommand to be executed after load\n\\\tstring module.loaderror\t\tcommand to be executed if load fails\n\\\tcell module.next\t\tlist chain\n\\\n\\ Exported global variables;\n\\\n\\ string conf_files\t\tconfiguration files to be loaded\n\\ string password\t\tpassword\n\\ cell modules_options\t\tpointer to first module information\n\\ value verbose?\t\tindicates if user wants a verbose loading\n\\ value any_conf_read?\t\tindicates if a conf file was succesfully read\n\\\n\\ Other exported words:\n\\\n\\ strdup ( addr len -- addr' len)\t\t\tsimilar to strdup(3)\n\\ strcat ( addr len addr' len' -- addr len+len' )\tsimilar to strcat(3)\n\\ strlen ( addr -- len )\t\t\t\tsimilar to strlen(3)\n\\ s' ( | string' -- addr len | )\t\t\tsimilar to s\"\n\\ rudimentary structure support\n\n\\ Exception values\n\n1 constant syntax_error\n2 constant out_of_memory\n3 constant free_error\n4 constant set_error\n5 constant read_error\n6 constant open_error\n7 constant exec_error\n8 constant before_load_error\n9 constant after_load_error\n\n\\ I\/O constants\n\n0 constant SEEK_SET\n1 constant SEEK_CUR\n2 constant SEEK_END\n\n0 constant O_RDONLY\n1 constant O_WRONLY\n2 constant O_RDWR\n\n\\ Crude structure support\n\n: structure:\n create here 0 , ['] drop , 0\n does> create here swap dup @ allot cell+ @ execute\n;\n: member: create dup , over , + does> cell+ @ + ;\n: ;structure swap ! ;\n: constructor! >body cell+ ! ;\n: constructor: over :noname ;\n: ;constructor postpone ; swap cell+ ! ; immediate\n: sizeof ' >body @ state @ if postpone literal then ; immediate\n: offsetof ' >body cell+ @ state @ if postpone literal then ; immediate\n: ptr 1 cells member: ;\n: int 1 cells member: ;\n\n\\ String structure\n\nstructure: string\n\tptr .addr\n\tint .len\n\tconstructor:\n\t 0 over .addr !\n\t 0 swap .len !\n\t;constructor\n;structure\n\n\n\\ Module options linked list\n\nstructure: module\n\tint module.flag\n\tsizeof string member: module.name\n\tsizeof string member: module.loadname\n\tsizeof string member: module.type\n\tsizeof string member: module.args\n\tsizeof string member: module.beforeload\n\tsizeof string member: module.afterload\n\tsizeof string member: module.loaderror\n\tptr module.next\n;structure\n\n\\ Internal loader structures\nstructure: preloaded_file\n\tptr pf.name\n\tptr pf.type\n\tptr pf.args\n\tptr pf.metadata\t\\ file_metadata\n\tint pf.loader\n\tint pf.addr\n\tint pf.size\n\tptr pf.modules\t\\ kernel_module\n\tptr pf.next\t\\ preloaded_file\n;structure\n\nstructure: kernel_module\n\tptr km.name\n\t\\ ptr km.args\n\tptr km.fp\t\\ preloaded_file\n\tptr km.next\t\\ kernel_module\n;structure\n\nstructure: file_metadata\n\tint\t\tmd.size\n\t2 member:\tmd.type\t\\ this is not ANS Forth compatible (XXX)\n\tptr\t\tmd.next\t\\ file_metadata\n\t0 member:\tmd.data\t\\ variable size\n;structure\n\nstructure: config_resource\n\tptr cf.name\n\tint cf.type\n0 constant RES_INT\n1 constant RES_STRING\n2 constant RES_LONG\n\t2 cells member: u\n;structure\n\nstructure: config_device\n\tptr cd.name\n\tint cd.unit\n\tint cd.resource_count\n\tptr cd.resources\t\\ config_resource\n;structure\n\nstructure: STAILQ_HEAD\n\tptr stqh_first\t\\ type*\n\tptr stqh_last\t\\ type**\n;structure\n\nstructure: STAILQ_ENTRY\n\tptr stqe_next\t\\ type*\n;structure\n\nstructure: pnphandler\n\tptr pnph.name\n\tptr pnph.enumerate\n;structure\n\nstructure: pnpident\n\tptr pnpid.ident\t\t\t\t\t\\ char*\n\tsizeof STAILQ_ENTRY cells member: pnpid.link\t\\ pnpident\n;structure\n\nstructure: pnpinfo\n\tptr pnpi.desc\n\tint pnpi.revision\n\tptr pnpi.module\t\t\t\t\\ (char*) module args\n\tint pnpi.argc\n\tptr pnpi.argv\n\tptr pnpi.handler\t\t\t\\ pnphandler\n\tsizeof STAILQ_HEAD member: pnpi.ident\t\\ pnpident\n\tsizeof STAILQ_ENTRY member: pnpi.link\t\\ pnpinfo\n;structure\n\n\\ Global variables\n\nstring conf_files\nstring nextboot_conf_file\nstring password\ncreate module_options sizeof module.next allot 0 module_options !\ncreate last_module_option sizeof module.next allot 0 last_module_option !\n0 value verbose?\n0 value nextboot?\n\n\\ Support string functions\n\n: strdup ( addr len -- addr' len )\n >r r@ allocate if out_of_memory throw then\n tuck r@ move\n r>\n;\n\n: strcat { addr len addr' len' -- addr len+len' }\n addr' addr len + len' move\n addr len len' +\n;\n\n: strlen ( addr -- len )\n 0 >r\n begin\n dup c@ while\n 1+ r> 1+ >r repeat\n drop r>\n;\n\n: s' \n [char] ' parse\n state @ if\n postpone sliteral\n then\n; immediate\n\n: 2>r postpone >r postpone >r ; immediate\n: 2r> postpone r> postpone r> ; immediate\n: 2r@ postpone 2r> postpone 2dup postpone 2>r ; immediate\n\n: getenv?\n getenv\n -1 = if false else drop true then\n;\n\n\\ Private definitions\n\nvocabulary support-functions\nonly forth also support-functions definitions\n\n\\ Some control characters constants\n\n7 constant bell\n8 constant backspace\n9 constant tab\n10 constant lf\n13 constant \n\n\\ Read buffer size\n\n80 constant read_buffer_size\n\n\\ Standard suffixes\n\n: load_module_suffix s\" _load\" ;\n: module_loadname_suffix s\" _name\" ;\n: module_type_suffix s\" _type\" ;\n: module_args_suffix s\" _flags\" ;\n: module_beforeload_suffix s\" _before\" ;\n: module_afterload_suffix s\" _after\" ;\n: module_loaderror_suffix s\" _error\" ;\n\n\\ Support operators\n\n: >= < 0= ;\n: <= > 0= ;\n\n\\ Assorted support funcitons\n\n: free-memory free if free_error throw then ;\n\n\\ Assignment data temporary storage\n\nstring name_buffer\nstring value_buffer\n\n\\ Line by line file reading functions\n\\\n\\ exported:\n\\\tline_buffer\n\\\tend_of_file?\n\\\tfd\n\\\tread_line\n\\\treset_line_reading\n\nvocabulary line-reading\nalso line-reading definitions also\n\n\\ File data temporary storage\n\nstring read_buffer\n0 value read_buffer_ptr\n\n\\ File's line reading function\n\nsupport-functions definitions\n\nstring line_buffer\n0 value end_of_file?\nvariable fd\n\nline-reading definitions\n\n: skip_newlines\n begin\n read_buffer .len @ read_buffer_ptr >\n while\n read_buffer .addr @ read_buffer_ptr + c@ lf = if\n read_buffer_ptr char+ to read_buffer_ptr\n else\n exit\n then\n repeat\n;\n\n: scan_buffer ( -- addr len )\n read_buffer_ptr >r\n begin\n read_buffer .len @ r@ >\n while\n read_buffer .addr @ r@ + c@ lf = if\n read_buffer .addr @ read_buffer_ptr + ( -- addr )\n r@ read_buffer_ptr - ( -- len )\n r> to read_buffer_ptr\n exit\n then\n r> char+ >r\n repeat\n read_buffer .addr @ read_buffer_ptr + ( -- addr )\n r@ read_buffer_ptr - ( -- len )\n r> to read_buffer_ptr\n;\n\n: line_buffer_resize ( len -- len )\n >r\n line_buffer .len @ if\n line_buffer .addr @\n line_buffer .len @ r@ +\n resize if out_of_memory throw then\n else\n r@ allocate if out_of_memory throw then\n then\n line_buffer .addr !\n r>\n;\n \n: append_to_line_buffer ( addr len -- )\n line_buffer .addr @ line_buffer .len @\n 2swap strcat\n line_buffer .len !\n drop\n;\n\n: read_from_buffer\n scan_buffer ( -- addr len )\n line_buffer_resize ( len -- len )\n append_to_line_buffer ( addr len -- )\n;\n\n: refill_required?\n read_buffer .len @ read_buffer_ptr =\n end_of_file? 0= and\n;\n\n: refill_buffer\n 0 to read_buffer_ptr\n read_buffer .addr @ 0= if\n read_buffer_size allocate if out_of_memory throw then\n read_buffer .addr !\n then\n fd @ read_buffer .addr @ read_buffer_size fread\n dup -1 = if read_error throw then\n dup 0= if true to end_of_file? then\n read_buffer .len !\n;\n\n: reset_line_buffer\n line_buffer .addr @ ?dup if\n free-memory\n then\n 0 line_buffer .addr !\n 0 line_buffer .len !\n;\n\nsupport-functions definitions\n\n: reset_line_reading\n 0 to read_buffer_ptr\n;\n\n: read_line\n reset_line_buffer\n skip_newlines\n begin\n read_from_buffer\n refill_required?\n while\n refill_buffer\n repeat\n;\n\nonly forth also support-functions definitions\n\n\\ Conf file line parser:\n\\ ::= '='[] |\n\\ []\n\\ ::= {||'_'}\n\\ ::= '\"'{|'\\'}'\"' | \n\\ ::= ASCII 32 to 126, except '\\' and '\"'\n\\ ::= '#'{}\n\\\n\\ exported:\n\\\tline_pointer\n\\\tprocess_conf\n\n0 value line_pointer\n\nvocabulary file-processing\nalso file-processing definitions\n\n\\ parser functions\n\\\n\\ exported:\n\\\tget_assignment\n\nvocabulary parser\nalso parser definitions also\n\n0 value parsing_function\n0 value end_of_line\n\n: end_of_line?\n line_pointer end_of_line =\n;\n\n: letter?\n line_pointer c@ >r\n r@ [char] A >=\n r@ [char] Z <= and\n r@ [char] a >=\n r> [char] z <= and\n or\n;\n\n: digit?\n line_pointer c@ >r\n r@ [char] - =\n r@ [char] 0 >=\n r> [char] 9 <= and\n or\n;\n\n: quote?\n line_pointer c@ [char] \" =\n;\n\n: assignment_sign?\n line_pointer c@ [char] = =\n;\n\n: comment?\n line_pointer c@ [char] # =\n;\n\n: space?\n line_pointer c@ bl =\n line_pointer c@ tab = or\n;\n\n: backslash?\n line_pointer c@ [char] \\ =\n;\n\n: underscore?\n line_pointer c@ [char] _ =\n;\n\n: dot?\n line_pointer c@ [char] . =\n;\n\n: skip_character\n line_pointer char+ to line_pointer\n;\n\n: skip_to_end_of_line\n end_of_line to line_pointer\n;\n\n: eat_space\n begin\n space?\n while\n skip_character\n end_of_line? if exit then\n repeat\n;\n\n: parse_name ( -- addr len )\n line_pointer\n begin\n letter? digit? underscore? dot? or or or\n while\n skip_character\n end_of_line? if \n line_pointer over -\n strdup\n exit\n then\n repeat\n line_pointer over -\n strdup\n;\n\n: remove_backslashes { addr len | addr' len' -- addr' len' }\n len allocate if out_of_memory throw then\n to addr'\n addr >r\n begin\n addr c@ [char] \\ <> if\n addr c@ addr' len' + c!\n len' char+ to len'\n then\n addr char+ to addr\n r@ len + addr =\n until\n r> drop\n addr' len'\n;\n\n: parse_quote ( -- addr len )\n line_pointer\n skip_character\n end_of_line? if syntax_error throw then\n begin\n quote? 0=\n while\n backslash? if\n skip_character\n end_of_line? if syntax_error throw then\n then\n skip_character\n end_of_line? if syntax_error throw then \n repeat\n skip_character\n line_pointer over -\n remove_backslashes\n;\n\n: read_name\n parse_name\t\t( -- addr len )\n name_buffer .len !\n name_buffer .addr !\n;\n\n: read_value\n quote? if\n parse_quote\t\t( -- addr len )\n else\n parse_name\t\t( -- addr len )\n then\n value_buffer .len !\n value_buffer .addr !\n;\n\n: comment\n skip_to_end_of_line\n;\n\n: white_space_4\n eat_space\n comment? if ['] comment to parsing_function exit then\n end_of_line? 0= if syntax_error throw then\n;\n\n: variable_value\n read_value\n ['] white_space_4 to parsing_function\n;\n\n: white_space_3\n eat_space\n letter? digit? quote? or or if\n ['] variable_value to parsing_function exit\n then\n syntax_error throw\n;\n\n: assignment_sign\n skip_character\n ['] white_space_3 to parsing_function\n;\n\n: white_space_2\n eat_space\n assignment_sign? if ['] assignment_sign to parsing_function exit then\n syntax_error throw\n;\n\n: variable_name\n read_name\n ['] white_space_2 to parsing_function\n;\n\n: white_space_1\n eat_space\n letter? if ['] variable_name to parsing_function exit then\n comment? if ['] comment to parsing_function exit then\n end_of_line? 0= if syntax_error throw then\n;\n\nfile-processing definitions\n\n: get_assignment\n line_buffer .addr @ line_buffer .len @ + to end_of_line\n line_buffer .addr @ to line_pointer\n ['] white_space_1 to parsing_function\n begin\n end_of_line? 0=\n while\n parsing_function execute\n repeat\n parsing_function ['] comment =\n parsing_function ['] white_space_1 =\n parsing_function ['] white_space_4 =\n or or 0= if syntax_error throw then\n;\n\nonly forth also support-functions also file-processing definitions also\n\n\\ Process line\n\n: assignment_type? ( addr len -- flag )\n name_buffer .addr @ name_buffer .len @\n compare 0=\n;\n\n: suffix_type? ( addr len -- flag )\n name_buffer .len @ over <= if 2drop false exit then\n name_buffer .len @ over - name_buffer .addr @ +\n over compare 0=\n;\n\n: loader_conf_files?\n s\" loader_conf_files\" assignment_type?\n;\n\n: nextboot_flag?\n s\" nextboot_enable\" assignment_type?\n;\n\n: nextboot_conf?\n s\" nextboot_conf\" assignment_type?\n;\n\n: verbose_flag?\n s\" verbose_loading\" assignment_type?\n;\n\n: execute?\n s\" exec\" assignment_type?\n;\n\n: password?\n s\" password\" assignment_type?\n;\n\n: module_load?\n load_module_suffix suffix_type?\n;\n\n: module_loadname?\n module_loadname_suffix suffix_type?\n;\n\n: module_type?\n module_type_suffix suffix_type?\n;\n\n: module_args?\n module_args_suffix suffix_type?\n;\n\n: module_beforeload?\n module_beforeload_suffix suffix_type?\n;\n\n: module_afterload?\n module_afterload_suffix suffix_type?\n;\n\n: module_loaderror?\n module_loaderror_suffix suffix_type?\n;\n\n: set_conf_files\n conf_files .addr @ ?dup if\n free-memory\n then\n value_buffer .addr @ c@ [char] \" = if\n value_buffer .addr @ char+ value_buffer .len @ 2 chars -\n else\n value_buffer .addr @ value_buffer .len @\n then\n strdup\n conf_files .len ! conf_files .addr !\n;\n\n: set_nextboot_conf\n nextboot_conf_file .addr @ ?dup if\n free-memory\n then\n value_buffer .addr @ c@ [char] \" = if\n value_buffer .addr @ char+ value_buffer .len @ 2 chars -\n else\n value_buffer .addr @ value_buffer .len @\n then\n strdup\n nextboot_conf_file .len ! nextboot_conf_file .addr !\n;\n\n: append_to_module_options_list ( addr -- )\n module_options @ 0= if\n dup module_options !\n last_module_option !\n else\n dup last_module_option @ module.next !\n last_module_option !\n then\n;\n\n: set_module_name ( addr -- )\n name_buffer .addr @ name_buffer .len @\n strdup\n >r over module.name .addr !\n r> swap module.name .len !\n;\n\n: yes_value?\n value_buffer .addr @ value_buffer .len @\n 2dup s' \"YES\"' compare >r\n 2dup s' \"yes\"' compare >r\n 2dup s\" YES\" compare >r\n s\" yes\" compare r> r> r> and and and 0=\n;\n\n: find_module_option ( -- addr | 0 )\n module_options @\n begin\n dup\n while\n dup module.name dup .addr @ swap .len @\n name_buffer .addr @ name_buffer .len @\n compare 0= if exit then\n module.next @\n repeat\n;\n\n: new_module_option ( -- addr )\n sizeof module allocate if out_of_memory throw then\n dup sizeof module erase\n dup append_to_module_options_list\n dup set_module_name\n;\n\n: get_module_option ( -- addr )\n find_module_option\n ?dup 0= if new_module_option then\n;\n\n: set_module_flag\n name_buffer .len @ load_module_suffix nip - name_buffer .len !\n yes_value? get_module_option module.flag !\n;\n\n: set_module_args\n name_buffer .len @ module_args_suffix nip - name_buffer .len !\n get_module_option module.args\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_loadname\n name_buffer .len @ module_loadname_suffix nip - name_buffer .len !\n get_module_option module.loadname\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_type\n name_buffer .len @ module_type_suffix nip - name_buffer .len !\n get_module_option module.type\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_beforeload\n name_buffer .len @ module_beforeload_suffix nip - name_buffer .len !\n get_module_option module.beforeload\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_afterload\n name_buffer .len @ module_afterload_suffix nip - name_buffer .len !\n get_module_option module.afterload\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_loaderror\n name_buffer .len @ module_loaderror_suffix nip - name_buffer .len !\n get_module_option module.loaderror\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_environment_variable\n name_buffer .len @\n value_buffer .len @ +\n 5 chars +\n allocate if out_of_memory throw then\n dup 0 ( addr -- addr addr len )\n s\" set \" strcat\n name_buffer .addr @ name_buffer .len @ strcat\n s\" =\" strcat\n value_buffer .addr @ value_buffer .len @ strcat\n ['] evaluate catch if\n 2drop free drop\n set_error throw\n else\n free-memory\n then\n;\n\n: set_nextboot_flag\n yes_value? to nextboot?\n;\n\n: set_verbose\n yes_value? to verbose?\n;\n\n: execute_command\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 - swap char+ swap\n then\n ['] evaluate catch if exec_error throw then\n;\n\n: set_password\n password .addr @ ?dup if free if free_error throw then then\n value_buffer .addr @ c@ [char] \" = if\n value_buffer .addr @ char+ value_buffer .len @ 2 - strdup\n value_buffer .addr @ free if free_error throw then\n else\n value_buffer .addr @ value_buffer .len @\n then\n password .len ! password .addr !\n 0 value_buffer .addr !\n;\n\n: process_assignment\n name_buffer .len @ 0= if exit then\n loader_conf_files?\tif set_conf_files exit then\n nextboot_flag?\tif set_nextboot_flag exit then\n nextboot_conf?\tif set_nextboot_conf exit then\n verbose_flag?\t\tif set_verbose exit then\n execute?\t\tif execute_command exit then\n password?\t\tif set_password exit then\n module_load?\t\tif set_module_flag exit then\n module_loadname?\tif set_module_loadname exit then\n module_type?\t\tif set_module_type exit then\n module_args?\t\tif set_module_args exit then\n module_beforeload?\tif set_module_beforeload exit then\n module_afterload?\tif set_module_afterload exit then\n module_loaderror?\tif set_module_loaderror exit then\n set_environment_variable\n;\n\n\\ free_buffer ( -- )\n\\\n\\ Free some pointers if needed. The code then tests for errors\n\\ in freeing, and throws an exception if needed. If a pointer is\n\\ not allocated, it's value (0) is used as flag.\n\n: free_buffers\n name_buffer .addr @ dup if free then\n value_buffer .addr @ dup if free then\n or if free_error throw then\n;\n\n: reset_assignment_buffers\n 0 name_buffer .addr !\n 0 name_buffer .len !\n 0 value_buffer .addr !\n 0 value_buffer .len !\n;\n\n\\ Higher level file processing\n\nsupport-functions definitions\n\n: process_conf\n begin\n end_of_file? 0=\n while\n reset_assignment_buffers\n read_line\n get_assignment\n ['] process_assignment catch\n ['] free_buffers catch\n swap throw throw\n repeat\n;\n\n: peek_file\n 0 to end_of_file?\n reset_line_reading\n O_RDONLY fopen fd !\n fd @ -1 = if open_error throw then\n reset_assignment_buffers\n read_line\n get_assignment\n ['] process_assignment catch\n ['] free_buffers catch\n fd @ fclose\n;\n \nonly forth also support-functions definitions\n\n\\ Interface to loading conf files\n\n: load_conf ( addr len -- )\n 0 to end_of_file?\n reset_line_reading\n O_RDONLY fopen fd !\n fd @ -1 = if open_error throw then\n ['] process_conf catch\n fd @ fclose\n throw\n;\n\n: print_line\n line_buffer .addr @ line_buffer .len @ type cr\n;\n\n: print_syntax_error\n line_buffer .addr @ line_buffer .len @ type cr\n line_buffer .addr @\n begin\n line_pointer over <>\n while\n bl emit\n char+\n repeat\n drop\n .\" ^\" cr\n;\n\n\\ Debugging support functions\n\nonly forth definitions also support-functions\n\n: test-file \n ['] load_conf catch dup .\n syntax_error = if cr print_syntax_error then\n;\n\n: show-module-options\n module_options @\n begin\n ?dup\n while\n .\" Name: \" dup module.name dup .addr @ swap .len @ type cr\n .\" Path: \" dup module.loadname dup .addr @ swap .len @ type cr\n .\" Type: \" dup module.type dup .addr @ swap .len @ type cr\n .\" Flags: \" dup module.args dup .addr @ swap .len @ type cr\n .\" Before load: \" dup module.beforeload dup .addr @ swap .len @ type cr\n .\" After load: \" dup module.afterload dup .addr @ swap .len @ type cr\n .\" Error: \" dup module.loaderror dup .addr @ swap .len @ type cr\n .\" Status: \" dup module.flag @ if .\" Load\" else .\" Don't load\" then cr\n module.next @\n repeat\n;\n\nonly forth also support-functions definitions\n\n\\ Variables used for processing multiple conf files\n\nstring current_file_name\nvariable current_conf_files\n\n\\ Indicates if any conf file was succesfully read\n\n0 value any_conf_read?\n\n\\ loader_conf_files processing support functions\n\n: set_current_conf_files\n conf_files .addr @ current_conf_files !\n;\n\n: get_conf_files\n conf_files .addr @ conf_files .len @ strdup\n;\n\n: recurse_on_conf_files?\n current_conf_files @ conf_files .addr @ <>\n;\n\n: skip_leading_spaces { addr len pos -- addr len pos' }\n begin\n pos len = if addr len pos exit then\n addr pos + c@ bl =\n while\n pos char+ to pos\n repeat\n addr len pos\n;\n\n: get_file_name { addr len pos -- addr len pos' addr' len' || 0 }\n pos len = if \n addr free abort\" Fatal error freeing memory\"\n 0 exit\n then\n pos >r\n begin\n addr pos + c@ bl <>\n while\n pos char+ to pos\n pos len = if\n addr len pos addr r@ + pos r> - exit\n then\n repeat\n addr len pos addr r@ + pos r> -\n;\n\n: get_next_file ( addr len ptr -- addr len ptr' addr' len' | 0 )\n skip_leading_spaces\n get_file_name\n;\n\n: set_current_file_name\n over current_file_name .addr !\n dup current_file_name .len !\n;\n\n: print_current_file\n current_file_name .addr @ current_file_name .len @ type\n;\n\n: process_conf_errors\n dup 0= if true to any_conf_read? drop exit then\n >r 2drop r>\n dup syntax_error = if\n .\" Warning: syntax error on file \" print_current_file cr\n print_syntax_error drop exit\n then\n dup set_error = if\n .\" Warning: bad definition on file \" print_current_file cr\n print_line drop exit\n then\n dup read_error = if\n .\" Warning: error reading file \" print_current_file cr drop exit\n then\n dup open_error = if\n verbose? if .\" Warning: unable to open file \" print_current_file cr then\n drop exit\n then\n dup free_error = abort\" Fatal error freeing memory\"\n dup out_of_memory = abort\" Out of memory\"\n throw \\ Unknown error -- pass ahead\n;\n\n\\ Process loader_conf_files recursively\n\\ Interface to loader_conf_files processing\n\n: include_conf_files\n set_current_conf_files\n get_conf_files 0\n begin\n get_next_file ?dup\n while\n set_current_file_name\n ['] load_conf catch\n process_conf_errors\n recurse_on_conf_files? if recurse then\n repeat\n;\n\n: get_nextboot_conf_file ( -- addr len )\n nextboot_conf_file .addr @ nextboot_conf_file .len @ strdup\n;\n\n: rewrite_nextboot_file ( -- )\n get_nextboot_conf_file\n O_WRONLY fopen fd !\n fd @ -1 = if open_error throw then\n fd @ s' nextboot_enable=\"NO\" ' fwrite\n fd @ fclose\n;\n\n: include_nextboot_file\n get_nextboot_conf_file\n ['] peek_file catch\n nextboot? if\n get_nextboot_conf_file\n ['] load_conf catch\n process_conf_errors\n ['] rewrite_nextboot_file catch\n then\n;\n\n\\ Module loading functions\n\n: load_module?\n module.flag @\n;\n\n: load_parameters ( addr -- addr addrN lenN ... addr1 len1 N )\n dup >r\n r@ module.args .addr @ r@ module.args .len @\n r@ module.loadname .len @ if\n r@ module.loadname .addr @ r@ module.loadname .len @\n else\n r@ module.name .addr @ r@ module.name .len @\n then\n r@ module.type .len @ if\n r@ module.type .addr @ r@ module.type .len @\n s\" -t \"\n 4 ( -t type name flags )\n else\n 2 ( name flags )\n then\n r> drop\n;\n\n: before_load ( addr -- addr )\n dup module.beforeload .len @ if\n dup module.beforeload .addr @ over module.beforeload .len @\n ['] evaluate catch if before_load_error throw then\n then\n;\n\n: after_load ( addr -- addr )\n dup module.afterload .len @ if\n dup module.afterload .addr @ over module.afterload .len @\n ['] evaluate catch if after_load_error throw then\n then\n;\n\n: load_error ( addr -- addr )\n dup module.loaderror .len @ if\n dup module.loaderror .addr @ over module.loaderror .len @\n evaluate \\ This we do not intercept so it can throw errors\n then\n;\n\n: pre_load_message ( addr -- addr )\n verbose? if\n dup module.name .addr @ over module.name .len @ type\n .\" ...\"\n then\n;\n\n: load_error_message verbose? if .\" failed!\" cr then ;\n\n: load_succesful_message verbose? if .\" ok\" cr then ;\n\n: load_module\n load_parameters load\n;\n\n: process_module ( addr -- addr )\n pre_load_message\n before_load\n begin\n ['] load_module catch if\n dup module.loaderror .len @ if\n load_error\t\t\t\\ Command should return a flag!\n else \n load_error_message true\t\t\\ Do not retry\n then\n else\n after_load\n load_succesful_message true\t\\ Succesful, do not retry\n then\n until\n;\n\n: process_module_errors ( addr ior -- )\n dup before_load_error = if\n drop\n .\" Module \"\n dup module.name .addr @ over module.name .len @ type\n dup module.loadname .len @ if\n .\" (\" dup module.loadname .addr @ over module.loadname .len @ type .\" )\"\n then\n cr\n .\" Error executing \"\n dup module.beforeload .addr @ over module.afterload .len @ type cr\n abort\n then\n\n dup after_load_error = if\n drop\n .\" Module \"\n dup module.name .addr @ over module.name .len @ type\n dup module.loadname .len @ if\n .\" (\" dup module.loadname .addr @ over module.loadname .len @ type .\" )\"\n then\n cr\n .\" Error executing \"\n dup module.afterload .addr @ over module.afterload .len @ type cr\n abort\n then\n\n throw \\ Don't know what it is all about -- pass ahead\n;\n\n\\ Module loading interface\n\n: load_modules ( -- ) ( throws: abort & user-defined )\n module_options @\n begin\n ?dup\n while\n dup load_module? if\n ['] process_module catch\n process_module_errors\n then\n module.next @\n repeat\n;\n\n\\ h00h00 magic used to try loading either a kernel with a given name,\n\\ or a kernel with the default name in a directory of a given name\n\\ (the pain!)\n\n: bootpath s\" \/boot\/\" ;\n: modulepath s\" module_path\" ;\n\n\\ Functions used to save and restore module_path's value.\n: saveenv ( addr len | -1 -- addr' len | 0 -1 )\n dup -1 = if 0 swap exit then\n strdup\n;\n: freeenv ( addr len | 0 -1 )\n -1 = if drop else free abort\" Freeing error\" then\n;\n: restoreenv ( addr len | 0 -1 -- )\n dup -1 = if ( it wasn't set )\n 2drop\n modulepath unsetenv\n else\n over >r\n modulepath setenv\n r> free abort\" Freeing error\"\n then\n;\n\n: clip_args \\ Drop second string if only one argument is passed\n 1 = if\n 2swap 2drop\n 1\n else\n 2\n then\n;\n\nalso builtins\n\n\\ Parse filename from a comma-separated list\n\n: parse-; ( addr len -- addr' len-x addr x )\n over 0 2swap\n begin\n dup 0 <>\n while\n over c@ [char] ; <>\n while\n 1- swap 1+ swap\n 2swap 1+ 2swap\n repeat then\n dup 0 <> if\n 1- swap 1+ swap\n then\n 2swap\n;\n\n\\ Try loading one of multiple kernels specified\n\n: try_multiple_kernels ( addr len addr' len' args -- flag )\n >r\n begin\n parse-; 2>r\n 2over 2r>\n r@ clip_args\n s\" DEBUG\" getenv? if\n s\" echo Module_path: ${module_path}\" evaluate\n .\" Kernel : \" >r 2dup type r> cr\n dup 2 = if .\" Flags : \" >r 2over type r> cr then\n then\n 1 load\n while\n dup 0=\n until\n 1 >r \\ Failure\n else\n 0 >r \\ Success\n then\n 2drop 2drop\n r>\n r> drop\n;\n\n\\ Try to load a kernel; the kernel name is taken from one of\n\\ the following lists, as ordered:\n\\\n\\ 1. The \"bootfile\" environment variable\n\\ 2. The \"kernel\" environment variable\n\\\n\\ Flags are passed, if available. If not, dummy values must be given.\n\\\n\\ The kernel gets loaded from the current module_path.\n\n: load_a_kernel ( flags len 1 | x x 0 -- flag )\n local args\n 2local flags\n 0 0 2local kernel\n end-locals\n\n \\ Check if a default kernel name exists at all, exits if not\n s\" bootfile\" getenv dup -1 <> if\n to kernel\n flags kernel args 1+ try_multiple_kernels\n dup 0= if exit then\n then\n drop\n\n s\" kernel\" getenv dup -1 <> if\n to kernel\n else\n drop\n 1 exit \\ Failure\n then\n\n \\ Try all default kernel names\n flags kernel args 1+ try_multiple_kernels\n;\n\n\\ Try to load a kernel; the kernel name is taken from one of\n\\ the following lists, as ordered:\n\\\n\\ 1. The \"bootfile\" environment variable\n\\ 2. The \"kernel\" environment variable\n\\\n\\ Flags are passed, if provided.\n\\\n\\ The kernel will be loaded from a directory computed from the\n\\ path given. Two directories will be tried in the following order:\n\\\n\\ 1. \/boot\/path\n\\ 2. path\n\\\n\\ The module_path variable is overridden if load is succesful, by\n\\ prepending the successful path.\n\n: load_from_directory ( path len 1 | flags len' path len 2 -- flag )\n local args\n 2local path\n args 1 = if 0 0 then\n 2local flags\n 0 0 2local oldmodulepath\n 0 0 2local newmodulepath\n end-locals\n\n \\ Set the environment variable module_path, and try loading\n \\ the kernel again.\n modulepath getenv saveenv to oldmodulepath\n\n \\ Try prepending \/boot\/ first\n bootpath nip path nip + \n oldmodulepath nip dup -1 = if\n drop\n else\n 1+ +\n then\n allocate\n if ( out of memory )\n 1 exit\n then\n\n 0\n bootpath strcat\n path strcat\n 2dup to newmodulepath\n modulepath setenv\n\n \\ Try all default kernel names\n flags args 1- load_a_kernel\n 0= if ( success )\n oldmodulepath nip -1 <> if\n newmodulepath s\" ;\" strcat\n oldmodulepath strcat\n modulepath setenv\n newmodulepath drop free-memory\n oldmodulepath drop free-memory\n then\n 0 exit\n then\n\n \\ Well, try without the prepended \/boot\/\n path newmodulepath drop swap move\n newmodulepath drop path nip\n 2dup to newmodulepath\n modulepath setenv\n\n \\ Try all default kernel names\n flags args 1- load_a_kernel\n if ( failed once more )\n oldmodulepath restoreenv\n newmodulepath drop free-memory\n 1\n else\n oldmodulepath nip -1 <> if\n newmodulepath s\" ;\" strcat\n oldmodulepath strcat\n modulepath setenv\n newmodulepath drop free-memory\n oldmodulepath drop free-memory\n then\n 0\n then\n;\n\n\\ Try to load a kernel; the kernel name is taken from one of\n\\ the following lists, as ordered:\n\\\n\\ 1. The \"bootfile\" environment variable\n\\ 2. The \"kernel\" environment variable\n\\ 3. The \"path\" argument\n\\\n\\ Flags are passed, if provided.\n\\\n\\ The kernel will be loaded from a directory computed from the\n\\ path given. Two directories will be tried in the following order:\n\\\n\\ 1. \/boot\/path\n\\ 2. path\n\\\n\\ Unless \"path\" is meant to be kernel name itself. In that case, it\n\\ will first be tried as a full path, and, next, search on the\n\\ directories pointed by module_path.\n\\\n\\ The module_path variable is overridden if load is succesful, by\n\\ prepending the successful path.\n\n: load_directory_or_file ( path len 1 | flags len' path len 2 -- flag )\n local args\n 2local path\n args 1 = if 0 0 then\n 2local flags\n end-locals\n\n \\ First, assume path is an absolute path to a directory\n flags path args clip_args load_from_directory\n dup 0= if exit else drop then\n\n \\ Next, assume path points to the kernel\n flags path args try_multiple_kernels\n;\n\n: initialize ( addr len -- )\n strdup conf_files .len ! conf_files .addr !\n;\n\n: kernel_options ( -- addr len 1 | 0 )\n s\" kernel_options\" getenv\n dup -1 = if drop 0 else 1 then\n;\n\n: standard_kernel_search ( flags 1 | 0 -- flag )\n local args\n args 0= if 0 0 then\n 2local flags\n s\" kernel\" getenv\n dup -1 = if 0 swap then\n 2local path\n end-locals\n\n path nip -1 = if ( there isn't a \"kernel\" environment variable )\n flags args load_a_kernel\n else\n flags path args 1+ clip_args load_directory_or_file\n then\n;\n\n: load_kernel ( -- ) ( throws: abort )\n kernel_options standard_kernel_search\n abort\" Unable to load a kernel!\"\n;\n\n: set_defaultoptions ( -- )\n s\" kernel_options\" getenv dup -1 = if\n drop\n else\n s\" temp_options\" setenv\n then\n;\n\n: argv[] ( aN uN ... a1 u1 N i -- aN uN ... a1 u1 N ai+1 ui+1 )\n 2dup = if 0 0 exit then\n dup >r\n 1+ 2* ( skip N and ui )\n pick\n r>\n 1+ 2* ( skip N and ai )\n pick\n;\n\n: drop_args ( aN uN ... a1 u1 N -- )\n 0 ?do 2drop loop\n;\n\n: argc\n dup\n;\n\n: queue_argv ( aN uN ... a1 u1 N a u -- a u aN uN ... a1 u1 N+1 )\n >r\n over 2* 1+ -roll\n r>\n over 2* 1+ -roll\n 1+\n;\n\n: unqueue_argv ( aN uN ... a1 u1 N -- aN uN ... a2 u2 N-1 a1 u1 )\n 1- -rot\n;\n\n: strlen(argv)\n dup 0= if 0 exit then\n 0 >r\t\\ Size\n 0 >r\t\\ Index\n begin\n argc r@ <>\n while\n r@ argv[]\n nip\n r> r> rot + 1+\n >r 1+ >r\n repeat\n r> drop\n r>\n;\n\n: concat_argv ( aN uN ... a1 u1 N -- a u )\n strlen(argv) allocate if out_of_memory throw then\n 0 2>r\n\n begin\n argc\n while\n unqueue_argv\n 2r> 2swap\n strcat\n s\" \" strcat\n 2>r\n repeat\n drop_args\n 2r>\n;\n\n: set_tempoptions ( addrN lenN ... addr1 len1 N -- addr len 1 | 0 )\n \\ Save the first argument, if it exists and is not a flag\n argc if\n 0 argv[] drop c@ [char] - <> if\n unqueue_argv 2>r \\ Filename\n 1 >r\t\t\\ Filename present\n else\n 0 >r\t\t\\ Filename not present\n then\n else\n 0 >r\t\t\\ Filename not present\n then\n\n \\ If there are other arguments, assume they are flags\n ?dup if\n concat_argv\n 2dup s\" temp_options\" setenv\n drop free if free_error throw then\n else\n set_defaultoptions\n then\n\n \\ Bring back the filename, if one was provided\n r> if 2r> 1 else 0 then\n;\n\n: get_arguments ( -- addrN lenN ... addr1 len1 N )\n 0\n begin\n \\ Get next word on the command line\n parse-word\n ?dup while\n queue_argv\n repeat\n drop ( empty string )\n;\n\n: load_kernel_and_modules ( args -- flag )\n set_tempoptions\n argc >r\n s\" temp_options\" getenv dup -1 <> if\n queue_argv\n else\n drop\n then\n r> if ( a path was passed )\n load_directory_or_file\n else\n standard_kernel_search\n then\n ?dup 0= if ['] load_modules catch then\n;\n\n: read-password { size | buf len -- }\n size allocate if out_of_memory throw then\n to buf\n 0 to len\n begin\n key\n dup backspace = if\n drop\n len if\n backspace emit bl emit backspace emit\n len 1 - to len\n else\n bell emit\n then\n else\n dup = if cr drop buf len exit then\n [char] * emit\n len size < if\n buf len chars + c!\n else\n drop\n then\n len 1+ to len\n then\n again\n;\n\n\\ Go back to straight forth vocabulary\n\nonly forth also definitions\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"b4f709345b9e9696e49037b69d66a1ecf99fe939","subject":"The sparc64 boot block currently compares a memory address to the ELF magic and complains if they do not match. Instead, load the start of the ELF header from memory and complain if this does not match the ELF magic.","message":"The sparc64 boot block currently compares a memory address to the ELF magic\nand complains if they do not match. Instead, load the start of the ELF\nheader from memory and complain if this does not match the ELF magic.\n\nTested by kettenis@\n\nok miod@\n","repos":"orumin\/openbsd-efivars,orumin\/openbsd-efivars,orumin\/openbsd-efivars,orumin\/openbsd-efivars","old_file":"arch\/sparc64\/stand\/bootblk\/bootblk.fth","new_file":"arch\/sparc64\/stand\/bootblk\/bootblk.fth","new_contents":"\\\t$OpenBSD: bootblk.fth,v 1.4 2009\/09\/03 16:39:37 jsing Exp $\n\\\t$NetBSD: bootblk.fth,v 1.3 2001\/08\/15 20:10:24 eeh Exp $\n\\\n\\\tIEEE 1275 Open Firmware Boot Block\n\\\n\\\tParses disklabel and UFS and loads the file called `ofwboot'\n\\\n\\\n\\\tCopyright (c) 1998 Eduardo Horvath.\n\\\tAll rights reserved.\n\\\n\\\tRedistribution and use in source and binary forms, with or without\n\\\tmodification, are permitted provided that the following conditions\n\\\tare met:\n\\\t1. Redistributions of source code must retain the above copyright\n\\\t notice, this list of conditions and the following disclaimer.\n\\\t2. Redistributions in binary form must reproduce the above copyright\n\\\t notice, this list of conditions and the following disclaimer in the\n\\\t documentation and\/or other materials provided with the distribution.\n\\\t3. All advertising materials mentioning features or use of this software\n\\\t must display the following acknowledgement:\n\\\t This product includes software developed by Eduardo Horvath.\n\\\t4. The name of the author may not be used to endorse or promote products\n\\\t derived from this software without specific prior written permission\n\\\n\\\tTHIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n\\\tIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n\\\tOF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n\\\tIN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n\\\tINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n\\\tNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\\\tDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\\\tTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\\\t(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n\\\tTHIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\\\n\noffset16\nhex\nheaders\n\nfalse value boot-debug?\n\n\\\n\\ First some housekeeping: Open \/chosen and set up vectors into\n\\\tclient-services\n\n\" \/chosen\" find-package 0= if .\" Cannot find \/chosen\" 0 then\nconstant chosen-phandle\n\n\" \/openprom\/client-services\" find-package 0= if \n\t.\" Cannot find client-services\" cr abort\nthen constant cif-phandle\n\ndefer cif-claim ( align size virt -- base )\ndefer cif-release ( size virt -- )\ndefer cif-open ( cstr -- ihandle|0 )\ndefer cif-close ( ihandle -- )\ndefer cif-read ( len adr ihandle -- #read )\ndefer cif-seek ( low high ihandle -- -1|0|1 )\n\\ defer cif-peer ( phandle -- phandle )\n\\ defer cif-getprop ( len adr cstr phandle -- )\n\n: find-cif-method ( method,len -- xf )\n cif-phandle find-method drop \n;\n\n\" claim\" find-cif-method to cif-claim\n\" open\" find-cif-method to cif-open\n\" close\" find-cif-method to cif-close\n\" read\" find-cif-method to cif-read\n\" seek\" find-cif-method to cif-seek\n\n: twiddle ( -- ) .\" .\" ; \\ Need to do this right. Just spit out periods for now.\n\n\\\n\\ Support routines\n\\\n\n: strcmp ( s1 l1 s2 l2 -- true:false )\n rot tuck <> if 3drop false exit then\n comp 0=\n;\n\n\\ Move string into buffer\n\n: strmov ( s1 l1 d -- d l1 )\n dup 2over swap -rot\t\t( s1 l1 d s1 d l1 )\n move\t\t\t\t( s1 l1 d )\n rot drop swap\n;\n\n\\ Move s1 on the end of s2 and return the result\n\n: strcat ( s1 l1 s2 l2 -- d tot )\n 2over swap \t\t\t\t( s1 l1 s2 l2 l1 s1 )\n 2over + rot\t\t\t\t( s1 l1 s2 l2 s1 d l1 )\n move rot + \t\t\t\t( s1 s2 len )\n rot drop\t\t\t\t( s2 len )\n;\n\n: strchr ( s1 l1 c -- s2 l2 )\n begin\n dup 2over 0= if\t\t\t( s1 l1 c c s1 )\n 2drop drop exit then\n c@ = if\t\t\t\t( s1 l1 c )\n drop exit then\n -rot \/c - swap ca1+\t\t( c l2 s2 )\n swap rot\n again\n;\n\n \n: cstr ( ptr -- str len )\n dup \n begin dup c@ 0<> while + repeat\n over -\n;\n\n\\\n\\ BSD FFS parameters\n\\\n\nfload\tassym.fth.h\n\nsbsize buffer: sb-buf\n-1 value boot-ihandle\ndev_bsize value bsize\n0 value raid-offset\t\\ Offset if it's a raid-frame partition\n\n: strategy ( addr size start -- nread )\n raid-offset + bsize * 0 \" seek\" boot-ihandle $call-method\n -1 = if \n .\" strategy: Seek failed\" cr\n abort\n then\n \" read\" boot-ihandle $call-method\n;\n\n\\\n\\ Cylinder group macros\n\\\n\n: cgbase ( cg fs -- cgbase ) fs_fpg l@ * ;\n: cgstart ( cg fs -- cgstart ) \n 2dup fs_cgmask l@ not and\t\t( cg fs stuff -- )\n over fs_cgoffset l@ * -rot\t\t( stuffcg fs -- )\n cgbase +\n;\n: cgdmin ( cg fs -- 1st-data-block ) dup fs_dblkno l@ -rot cgstart + ;\n: cgimin ( cg fs -- inode-block ) dup fs_iblkno l@ -rot cgstart + ;\n: cgsblock ( cg fs -- super-block ) dup fs_sblkno l@ -rot cgstart + ;\n: cgstod ( cg fs -- cg-block ) dup fs_cblkno l@ -rot cgstart + ;\n\n\\\n\\ Block and frag position macros\n\\\n\n: blkoff ( pos fs -- off ) fs_qbmask x@ and ;\n: fragoff ( pos fs -- off ) fs_qfmask x@ and ;\n: lblktosize ( blk fs -- off ) fs_bshift l@ << ;\n: lblkno ( pos fs -- off ) fs_bshift l@ >> ;\n: numfrags ( pos fs -- off ) fs_fshift l@ >> ;\n: blkroundup ( pos fs -- off ) dup fs_bmask l@ -rot fs_qbmask x@ + and ;\n: fragroundup ( pos fs -- off ) dup fs_fmask l@ -rot fs_qfmask x@ + and ;\n\\ : fragroundup ( pos fs -- off ) tuck fs_qfmask x@ + swap fs_fmask l@ and ;\n: fragstoblks ( pos fs -- off ) fs_fragshift l@ >> ;\n: blkstofrags ( blk fs -- frag ) fs_fragshift l@ << ;\n: fragnum ( fsb fs -- off ) fs_frag l@ 1- and ;\n: blknum ( fsb fs -- off ) fs_frag l@ 1- not and ;\n: dblksize ( lbn dino fs -- size )\n -rot \t\t\t\t( fs lbn dino )\n di_size x@\t\t\t\t( fs lbn di_size )\n -rot dup 1+\t\t\t\t( di_size fs lbn lbn+1 )\n 2over fs_bshift l@\t\t\t( di_size fs lbn lbn+1 di_size b_shift )\n rot swap <<\t>=\t\t\t( di_size fs lbn res1 )\n swap ndaddr >= or if\t\t\t( di_size fs )\n swap drop fs_bsize l@ exit\t( size )\n then\ttuck blkoff swap fragroundup\t( size )\n;\n\n\n: ino-to-cg ( ino fs -- cg ) fs_ipg l@ \/ ;\n: ino-to-fsbo ( ino fs -- fsb0 ) fs_inopb l@ mod ;\n: ino-to-fsba ( ino fs -- ba )\t\\ Need to remove the stupid stack diags someday\n 2dup \t\t\t\t( ino fs ino fs )\n ino-to-cg\t\t\t\t( ino fs cg )\n over\t\t\t\t\t( ino fs cg fs )\n cgimin\t\t\t\t( ino fs inode-blk )\n -rot\t\t\t\t\t( inode-blk ino fs )\n tuck \t\t\t\t( inode-blk fs ino fs )\n fs_ipg l@ \t\t\t\t( inode-blk fs ino ipg )\n mod\t\t\t\t\t( inode-blk fs mod )\n swap\t\t\t\t\t( inode-blk mod fs )\n dup \t\t\t\t\t( inode-blk mod fs fs )\n fs_inopb l@ \t\t\t\t( inode-blk mod fs inopb )\n rot \t\t\t\t\t( inode-blk fs inopb mod )\n swap\t\t\t\t\t( inode-blk fs mod inopb )\n \/\t\t\t\t\t( inode-blk fs div )\n swap\t\t\t\t\t( inode-blk div fs )\n blkstofrags\t\t\t\t( inode-blk frag )\n +\n;\n: fsbtodb ( fsb fs -- db ) fs_fsbtodb l@ << ;\n\n\\\n\\ File stuff\n\\\n\nniaddr \/w* constant narraysize\n\nstruct \n 8\t\tfield\t>f_ihandle\t\\ device handle\n 8 \t\tfield \t>f_seekp\t\\ seek pointer\n 8 \t\tfield \t>f_fs\t\t\\ pointer to super block\n ufs1_dinode_SIZEOF \tfield \t>f_di\t\\ copy of on-disk inode\n 8\t\tfield\t>f_buf\t\t\\ buffer for data block\n 4\t\tfield \t>f_buf_size\t\\ size of data block\n 4\t\tfield\t>f_buf_blkno\t\\ block number of data block\nconstant file_SIZEOF\n\nfile_SIZEOF buffer: the-file\nsb-buf the-file >f_fs x!\n\nufs1_dinode_SIZEOF buffer: cur-inode\nh# 2000 buffer: indir-block\n-1 value indir-addr\n\n\\\n\\ Translate a fileblock to a disk block\n\\\n\\ We only allow single indirection\n\\\n\n: block-map ( fileblock -- diskblock )\n \\ Direct block?\n dup ndaddr < if \t\t\t( fileblock )\n cur-inode di_db\t\t\t( arr-indx arr-start )\n swap la+ l@ exit\t\t\t( diskblock )\n then \t\t\t\t( fileblock )\n ndaddr -\t\t\t\t( fileblock' )\n \\ Now we need to check the indirect block\n dup sb-buf fs_nindir l@ < if\t( fileblock' )\n cur-inode di_ib l@ dup\t\t( fileblock' indir-block indir-block )\n indir-addr <> if \t\t( fileblock' indir-block )\n to indir-addr\t\t\t( fileblock' )\n indir-block \t\t\t( fileblock' indir-block )\n sb-buf dup fs_bsize l@\t\t( fileblock' indir-block fs fs_bsize )\n swap indir-addr swap\t\t( fileblock' indir-block fs_bsize indiraddr fs )\n fsbtodb \t\t\t( fileblock' indir-block fs_bsize db )\n strategy\t\t\t( fileblock' nread )\n then\t\t\t\t( fileblock' nread|indir-block )\n drop \\ Really should check return value\n indir-block swap la+ l@ exit\n then\n dup sb-buf fs_nindir -\t\t( fileblock'' )\n \\ Now try 2nd level indirect block -- just read twice \n dup sb-buf fs_nindir l@ dup * < if\t( fileblock'' )\n cur-inode di_ib 1 la+ l@\t\t( fileblock'' indir2-block )\n to indir-addr\t\t\t( fileblock'' )\n \\ load 1st level indir block \n indir-block \t\t\t( fileblock'' indir-block )\n sb-buf dup fs_bsize l@\t\t( fileblock'' indir-block fs fs_bsize )\n swap indir-addr swap\t\t( fileblock'' indir-block fs_bsize indiraddr fs )\n fsbtodb \t\t\t\t( fileblock'' indir-block fs_bsize db )\n strategy\t\t\t\t( fileblock'' nread )\n drop\t\t\t\t( fileblock'' )\n dup sb-buf fs_nindir \/\t\t( fileblock'' indir-offset )\n indir-block swap la+ l@\t\t( fileblock'' indirblock )\n to indir-addr\t\t\t( fileblock'' )\n \\ load 2nd level indir block\n indir-block \t\t\t( fileblock'' indir-block )\n sb-buf dup fs_bsize l@\t\t( fileblock'' indir-block fs fs_bsize )\n swap indir-addr swap\t\t( fileblock'' indir-block fs_bsize indiraddr fs )\n fsbtodb \t\t\t\t( fileblock'' indir-block fs_bsize db )\n strategy\t\t\t\t( fileblock'' nread )\n drop\t\t\t\t( fileblock'' )\n sb-buf fs_nindir l@ mod indir-block swap la+ l@ exit\n then\n .\" block-map: exceeded max file size\" cr\n abort\n;\n\n\\\n\\ Read file into internal buffer and return pointer and len\n\\\n\n0 value cur-block\t\t\t\\ allocated dynamically in ufs-open\n0 value cur-blocksize\t\t\t\\ size of cur-block\n-1 value cur-blockno\n0 value cur-offset\n\n: buf-read-file ( fs -- len buf )\n cur-offset swap\t\t\t( seekp fs )\n 2dup blkoff\t\t\t\t( seekp fs off )\n -rot 2dup lblkno\t\t\t( off seekp fs block )\n swap 2dup cur-inode\t\t\t( off seekp block fs block fs inop )\n swap dblksize\t\t\t( off seekp block fs size )\n rot dup cur-blockno\t\t\t( off seekp fs size block block cur )\n <> if \t\t\t\t( off seekp fs size block )\n block-map\t\t\t\t( off seekp fs size diskblock )\n dup 0= if\t\t\t( off seekp fs size diskblock )\n over cur-block swap 0 fill\t( off seekp fs size diskblock )\n boot-debug? if .\" buf-read-file fell off end of file\" cr then\n else\n 2dup sb-buf fsbtodb cur-block -rot strategy\t( off seekp fs size diskblock nread )\n rot 2dup <> if \" buf-read-file: short read.\" cr abort then\n then\t\t\t\t( off seekp fs diskblock nread size )\n nip nip\t\t\t\t( off seekp fs size )\n else\t\t\t\t\t( off seekp fs size block block cur )\n 2drop\t\t\t\t( off seekp fs size )\n then\n\\ dup cur-offset + to cur-offset\t\\ Set up next xfer -- not done\n nip nip swap -\t\t\t( len )\n cur-block\n;\n\n\\\n\\ Read inode into cur-inode -- uses cur-block\n\\ \n\n: read-inode ( inode fs -- )\n twiddle\t\t\t\t( inode fs -- inode fs )\n\n cur-block\t\t\t\t( inode fs -- inode fs buffer )\n\n over\t\t\t\t\t( inode fs buffer -- inode fs buffer fs )\n fs_bsize l@\t\t\t\t( inode fs buffer -- inode fs buffer size )\n\n 2over\t\t\t\t( inode fs buffer size -- inode fs buffer size inode fs )\n 2over\t\t\t\t( inode fs buffer size inode fs -- inode fs buffer size inode fs buffer size )\n 2swap tuck\t\t\t\t( inode fs buffer size inode fs buffer size -- inode fs buffer size buffer size fs inode fs )\n\n ino-to-fsba \t\t\t\t( inode fs buffer size buffer size fs inode fs -- inode fs buffer size buffer size fs fsba )\n swap\t\t\t\t\t( inode fs buffer size buffer size fs fsba -- inode fs buffer size buffer size fsba fs )\n fsbtodb\t\t\t\t( inode fs buffer size buffer size fsba fs -- inode fs buffer size buffer size db )\n\n dup to cur-blockno\t\t\t( inode fs buffer size buffer size dstart -- inode fs buffer size buffer size dstart )\n strategy\t\t\t\t( inode fs buffer size buffer size dstart -- inode fs buffer size nread )\n <> if .\" read-inode - residual\" cr abort then\n dup 2over\t\t\t\t( inode fs buffer -- inode fs buffer buffer inode fs )\n ino-to-fsbo\t\t\t\t( inode fs buffer -- inode fs buffer buffer fsbo )\n ufs1_dinode_SIZEOF * +\t\t\t( inode fs buffer buffer fsbo -- inode fs buffer dinop )\n cur-inode ufs1_dinode_SIZEOF move \t( inode fs buffer dinop -- inode fs buffer )\n\t\\ clear out the old buffers\n drop\t\t\t\t\t( inode fs buffer -- inode fs )\n 2drop\n;\n\n\\ Identify inode type\n\n: is-dir? ( dinode -- true:false ) di_mode w@ ifmt and ifdir = ;\n: is-symlink? ( dinode -- true:false ) di_mode w@ ifmt and iflnk = ;\n\n\n\n\\\n\\ Hunt for directory entry:\n\\ \n\\ repeat\n\\ load a buffer\n\\ while entries do\n\\ if entry == name return\n\\ next entry\n\\ until no buffers\n\\\n\n: search-directory ( str len -- ino|0 )\n 0 to cur-offset\n begin cur-offset cur-inode di_size x@ < while\t( str len )\n sb-buf buf-read-file\t\t( str len len buf )\n over 0= if .\" search-directory: buf-read-file zero len\" cr abort then\n swap dup cur-offset + to cur-offset\t( str len buf len )\n 2dup + nip\t\t\t( str len buf bufend )\n swap 2swap rot\t\t\t( bufend str len buf )\n begin dup 4 pick < while\t\t( bufend str len buf )\n dup d_ino l@ 0<> if \t\t( bufend str len buf )\n boot-debug? if dup dup d_name swap d_namlen c@ type cr then\n 2dup d_namlen c@ = if\t( bufend str len buf )\n dup d_name 2over\t\t( bufend str len buf dname str len )\n comp 0= if\t\t( bufend str len buf )\n \\ Found it -- return inode\n d_ino l@ nip nip nip\t( dino )\n boot-debug? if .\" Found it\" cr then \n exit \t\t\t( dino )\n then\n then\t\t\t( bufend str len buf )\n then\t\t\t\t( bufend str len buf )\n dup d_reclen w@ +\t\t( bufend str len nextbuf )\n repeat\n drop rot drop\t\t\t( str len )\n repeat\n 2drop 2drop 0\t\t\t( 0 )\n;\n\n: ffs_oldcompat ( -- )\n\\ Make sure old ffs values in sb-buf are sane\n sb-buf fs_npsect dup l@ sb-buf fs_nsect l@ max swap l!\n sb-buf fs_interleave dup l@ 1 max swap l!\n sb-buf fs_postblformat l@ fs_42postblfmt = if\n 8 sb-buf fs_nrpos l!\n then\n sb-buf fs_inodefmt l@ fs_44inodefmt < if\n sb-buf fs_bsize l@ \n dup ndaddr * 1- sb-buf fs_maxfilesize x!\n niaddr 0 ?do\n\tsb-buf fs_nindir l@ * dup\t( sizebp sizebp -- )\n\tsb-buf fs_maxfilesize dup x@\t( sizebp sizebp *fs_maxfilesize fs_maxfilesize -- )\n\trot \t\t\t\t( sizebp *fs_maxfilesize fs_maxfilesize sizebp -- )\n\t+ \t\t\t\t( sizebp *fs_maxfilesize new_fs_maxfilesize -- ) \n swap x! \t\t\t( sizebp -- )\n loop drop \t\t\t( -- )\n sb-buf dup fs_bmask l@ not swap fs_qbmask x!\n sb-buf dup fs_fmask l@ not swap fs_qfmask x!\n then\n;\n\n: read-super ( sector -- )\n0 \" seek\" boot-ihandle $call-method\n -1 = if \n .\" Seek failed\" cr\n abort\n then\n sb-buf sbsize \" read\" boot-ihandle $call-method\n dup sbsize <> if\n .\" Read of superblock failed\" cr\n .\" requested\" space sbsize .\n .\" actual\" space . cr\n abort\n else \n drop\n then\n;\n\n: ufs-open ( bootpath,len -- )\n boot-ihandle -1 = if\n over cif-open dup 0= if \t\t( boot-path len ihandle? )\n .\" Could not open device\" space type cr \n abort\n then \t\t\t\t( boot-path len ihandle )\n to boot-ihandle\t\t\t\\ Save ihandle to boot device\n then 2drop\n sboff read-super\n sb-buf fs_magic l@ fs_magic_value <> if\n 64 dup to raid-offset \n dev_bsize * sboff + read-super\n sb-buf fs_magic l@ fs_magic_value <> if\n .\" Invalid superblock magic\" cr\n abort\n then\n then\n sb-buf fs_bsize l@ dup maxbsize > if\n .\" Superblock bsize\" space . .\" too large\" cr\n abort\n then \n dup fs_SIZEOF < if\n .\" Superblock bsize < size of superblock\" cr\n abort\n then\n ffs_oldcompat\t( fs_bsize -- fs_bsize )\n dup to cur-blocksize alloc-mem to cur-block \\ Allocate cur-block\n boot-debug? if .\" ufs-open complete\" cr then\n;\n\n: ufs-close ( -- ) \n boot-ihandle dup -1 <> if\n cif-close -1 to boot-ihandle \n then\n cur-block 0<> if\n cur-block cur-blocksize free-mem\n then\n;\n\n: boot-path ( -- boot-path )\n \" bootpath\" chosen-phandle get-package-property if\n .\" Could not find bootpath in \/chosen\" cr\n abort\n else\n decode-string 2swap 2drop\n then\n;\n\n: boot-args ( -- boot-args )\n \" bootargs\" chosen-phandle get-package-property if\n .\" Could not find bootargs in \/chosen\" cr\n abort\n else\n decode-string 2swap 2drop\n then\n;\n\n2000 buffer: boot-path-str\n2000 buffer: boot-path-tmp\n\n: split-path ( path len -- right len left len )\n\\ Split a string at the `\/'\n begin\n dup -rot\t\t\t\t( oldlen right len left )\n ascii \/ left-parse-string\t\t( oldlen right len left len )\n dup 0<> if 4 roll drop exit then\n 2drop\t\t\t\t( oldlen right len )\n rot over =\t\t\t( right len diff )\n until\n;\n\n: find-file ( load-file len -- )\n rootino dup sb-buf read-inode\t( load-file len -- load-file len ino )\n -rot\t\t\t\t\t( load-file len ino -- pino load-file len )\n \\\n \\ For each path component\n \\ \n begin split-path dup 0<> while\t( pino right len left len -- )\n cur-inode is-dir? not if .\" Inode not directory\" cr abort then\n boot-debug? if .\" Looking for\" space 2dup type space .\" in directory...\" cr then\n search-directory\t\t\t( pino right len left len -- pino right len ino|false )\n dup 0= if .\" Bad path\" cr abort then\t( pino right len cino )\n sb-buf read-inode\t\t\t( pino right len )\n cur-inode is-symlink? if\t\t\\ Symlink -- follow the damn thing\n \\ Save path in boot-path-tmp\n boot-path-tmp strmov\t\t( pino new-right len )\n\n \\ Now deal with symlink\n cur-inode di_size x@\t\t( pino right len linklen )\n dup sb-buf fs_maxsymlinklen l@\t( pino right len linklen linklen maxlinklen )\n < if\t\t\t\t\\ Now join the link to the path\n cur-inode di_shortlink l@\t( pino right len linklen linkp )\n swap boot-path-str strmov\t( pino right len new-linkp linklen )\n else\t\t\t\t\\ Read file for symlink -- Ugh\n \\ Read link into boot-path-str\n boot-path-str dup sb-buf fs_bsize l@\n 0 block-map\t\t\t( pino right len linklen boot-path-str bsize blockno )\n strategy drop swap\t\t( pino right len boot-path-str linklen )\n then \t\t\t\t( pino right len linkp linklen )\n \\ Concatenate the two paths\n strcat\t\t\t\t( pino new-right newlen )\n swap dup c@ ascii \/ = if\t\\ go to root inode?\n rot drop rootino -rot\t( rino len right )\n then\n rot dup sb-buf read-inode\t( len right pino )\n -rot swap\t\t\t( pino right len )\n then\t\t\t\t( pino right len )\n repeat\n 2drop drop\n;\n\n: read-file ( size addr -- )\n \\ Read x bytes from a file to buffer\n begin over 0> while\n cur-offset cur-inode di_size x@ > if .\" read-file EOF exceeded\" cr abort then\n sb-buf buf-read-file\t\t( size addr len buf )\n over 2over drop swap\t\t( size addr len buf addr len )\n move\t\t\t\t( size addr len )\n dup cur-offset + to cur-offset\t( size len newaddr )\n tuck +\t\t\t\t( size len newaddr )\n -rot - swap\t\t\t( newaddr newsize )\n repeat\n 2drop\n;\n\n\\\n\\ According to the 1275 addendum for SPARC processors:\n\\ Default load-base is 0x4000. At least 0x8.0000 or\n\\ 512KB must be available at that address. \n\\\n\\ The Fcode bootblock can take up up to 8KB (O.K., 7.5KB) \n\\ so load programs at 0x4000 + 0x2000=> 0x6000\n\\\n\nh# 6000 constant loader-base\n\n\\\n\\ Elf support -- find the load addr\n\\\n\n: is-elf? ( hdr -- res? ) h# 7f454c46 = ;\n\n\\\n\\ Finally we finish it all off\n\\\n\n: load-file-signon ( load-file len boot-path len -- load-file len boot-path len )\n .\" Loading file\" space 2over type cr .\" from device\" space 2dup type cr\n;\n\n: load-file-print-size ( size -- size )\n .\" Loading\" space dup . space .\" bytes of file...\" cr \n;\n\n: load-file ( load-file len boot-path len -- load-base )\n boot-debug? if load-file-signon then\n the-file file_SIZEOF 0 fill\t\t\\ Clear out file structure\n ufs-open \t\t\t\t( load-file len )\n find-file\t\t\t\t( )\n\n \\\n \\ Now we've found the file we should read it in in one big hunk\n \\\n\n cur-inode di_size x@\t\t\t( file-len )\n dup \" to file-size\" evaluate\t\t( file-len )\n boot-debug? if load-file-print-size then\n 0 to cur-offset\n loader-base\t\t\t\t( buf-len addr )\n 2dup read-file\t\t\t( buf-len addr )\n ufs-close\t\t\t\t( buf-len addr )\n\n dup l@ is-elf? false = if\n .\" load-file: not an elf executable\" cr\n abort\n then\n\n \\ Luckily the prom should be able to handle ELF executables by itself\n\n nip\t\t\t\t\t( addr )\n;\n\n: do-boot ( bootfile -- )\n .\" OpenBSD IEEE 1275 Bootblock 1.1\" cr\n boot-path load-file ( -- load-base )\n dup 0<> if \" to load-base init-program\" evaluate then\n;\n\n\nboot-args ascii V strchr 0<> swap drop if\n true to boot-debug?\nthen\n\nboot-args ascii D strchr 0= swap drop if\n \" \/ofwboot\" do-boot\nthen exit\n\n\n","old_contents":"\\\t$OpenBSD: bootblk.fth,v 1.3 2003\/08\/28 23:47:31 jason Exp $\n\\\t$NetBSD: bootblk.fth,v 1.3 2001\/08\/15 20:10:24 eeh Exp $\n\\\n\\\tIEEE 1275 Open Firmware Boot Block\n\\\n\\\tParses disklabel and UFS and loads the file called `ofwboot'\n\\\n\\\n\\\tCopyright (c) 1998 Eduardo Horvath.\n\\\tAll rights reserved.\n\\\n\\\tRedistribution and use in source and binary forms, with or without\n\\\tmodification, are permitted provided that the following conditions\n\\\tare met:\n\\\t1. Redistributions of source code must retain the above copyright\n\\\t notice, this list of conditions and the following disclaimer.\n\\\t2. Redistributions in binary form must reproduce the above copyright\n\\\t notice, this list of conditions and the following disclaimer in the\n\\\t documentation and\/or other materials provided with the distribution.\n\\\t3. All advertising materials mentioning features or use of this software\n\\\t must display the following acknowledgement:\n\\\t This product includes software developed by Eduardo Horvath.\n\\\t4. The name of the author may not be used to endorse or promote products\n\\\t derived from this software without specific prior written permission\n\\\n\\\tTHIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n\\\tIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n\\\tOF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n\\\tIN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n\\\tINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n\\\tNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\\\tDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\\\tTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\\\t(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n\\\tTHIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\\\n\noffset16\nhex\nheaders\n\nfalse value boot-debug?\n\n\\\n\\ First some housekeeping: Open \/chosen and set up vectors into\n\\\tclient-services\n\n\" \/chosen\" find-package 0= if .\" Cannot find \/chosen\" 0 then\nconstant chosen-phandle\n\n\" \/openprom\/client-services\" find-package 0= if \n\t.\" Cannot find client-services\" cr abort\nthen constant cif-phandle\n\ndefer cif-claim ( align size virt -- base )\ndefer cif-release ( size virt -- )\ndefer cif-open ( cstr -- ihandle|0 )\ndefer cif-close ( ihandle -- )\ndefer cif-read ( len adr ihandle -- #read )\ndefer cif-seek ( low high ihandle -- -1|0|1 )\n\\ defer cif-peer ( phandle -- phandle )\n\\ defer cif-getprop ( len adr cstr phandle -- )\n\n: find-cif-method ( method,len -- xf )\n cif-phandle find-method drop \n;\n\n\" claim\" find-cif-method to cif-claim\n\" open\" find-cif-method to cif-open\n\" close\" find-cif-method to cif-close\n\" read\" find-cif-method to cif-read\n\" seek\" find-cif-method to cif-seek\n\n: twiddle ( -- ) .\" .\" ; \\ Need to do this right. Just spit out periods for now.\n\n\\\n\\ Support routines\n\\\n\n: strcmp ( s1 l1 s2 l2 -- true:false )\n rot tuck <> if 3drop false exit then\n comp 0=\n;\n\n\\ Move string into buffer\n\n: strmov ( s1 l1 d -- d l1 )\n dup 2over swap -rot\t\t( s1 l1 d s1 d l1 )\n move\t\t\t\t( s1 l1 d )\n rot drop swap\n;\n\n\\ Move s1 on the end of s2 and return the result\n\n: strcat ( s1 l1 s2 l2 -- d tot )\n 2over swap \t\t\t\t( s1 l1 s2 l2 l1 s1 )\n 2over + rot\t\t\t\t( s1 l1 s2 l2 s1 d l1 )\n move rot + \t\t\t\t( s1 s2 len )\n rot drop\t\t\t\t( s2 len )\n;\n\n: strchr ( s1 l1 c -- s2 l2 )\n begin\n dup 2over 0= if\t\t\t( s1 l1 c c s1 )\n 2drop drop exit then\n c@ = if\t\t\t\t( s1 l1 c )\n drop exit then\n -rot \/c - swap ca1+\t\t( c l2 s2 )\n swap rot\n again\n;\n\n \n: cstr ( ptr -- str len )\n dup \n begin dup c@ 0<> while + repeat\n over -\n;\n\n\\\n\\ BSD FFS parameters\n\\\n\nfload\tassym.fth.h\n\nsbsize buffer: sb-buf\n-1 value boot-ihandle\ndev_bsize value bsize\n0 value raid-offset\t\\ Offset if it's a raid-frame partition\n\n: strategy ( addr size start -- nread )\n raid-offset + bsize * 0 \" seek\" boot-ihandle $call-method\n -1 = if \n .\" strategy: Seek failed\" cr\n abort\n then\n \" read\" boot-ihandle $call-method\n;\n\n\\\n\\ Cylinder group macros\n\\\n\n: cgbase ( cg fs -- cgbase ) fs_fpg l@ * ;\n: cgstart ( cg fs -- cgstart ) \n 2dup fs_cgmask l@ not and\t\t( cg fs stuff -- )\n over fs_cgoffset l@ * -rot\t\t( stuffcg fs -- )\n cgbase +\n;\n: cgdmin ( cg fs -- 1st-data-block ) dup fs_dblkno l@ -rot cgstart + ;\n: cgimin ( cg fs -- inode-block ) dup fs_iblkno l@ -rot cgstart + ;\n: cgsblock ( cg fs -- super-block ) dup fs_sblkno l@ -rot cgstart + ;\n: cgstod ( cg fs -- cg-block ) dup fs_cblkno l@ -rot cgstart + ;\n\n\\\n\\ Block and frag position macros\n\\\n\n: blkoff ( pos fs -- off ) fs_qbmask x@ and ;\n: fragoff ( pos fs -- off ) fs_qfmask x@ and ;\n: lblktosize ( blk fs -- off ) fs_bshift l@ << ;\n: lblkno ( pos fs -- off ) fs_bshift l@ >> ;\n: numfrags ( pos fs -- off ) fs_fshift l@ >> ;\n: blkroundup ( pos fs -- off ) dup fs_bmask l@ -rot fs_qbmask x@ + and ;\n: fragroundup ( pos fs -- off ) dup fs_fmask l@ -rot fs_qfmask x@ + and ;\n\\ : fragroundup ( pos fs -- off ) tuck fs_qfmask x@ + swap fs_fmask l@ and ;\n: fragstoblks ( pos fs -- off ) fs_fragshift l@ >> ;\n: blkstofrags ( blk fs -- frag ) fs_fragshift l@ << ;\n: fragnum ( fsb fs -- off ) fs_frag l@ 1- and ;\n: blknum ( fsb fs -- off ) fs_frag l@ 1- not and ;\n: dblksize ( lbn dino fs -- size )\n -rot \t\t\t\t( fs lbn dino )\n di_size x@\t\t\t\t( fs lbn di_size )\n -rot dup 1+\t\t\t\t( di_size fs lbn lbn+1 )\n 2over fs_bshift l@\t\t\t( di_size fs lbn lbn+1 di_size b_shift )\n rot swap <<\t>=\t\t\t( di_size fs lbn res1 )\n swap ndaddr >= or if\t\t\t( di_size fs )\n swap drop fs_bsize l@ exit\t( size )\n then\ttuck blkoff swap fragroundup\t( size )\n;\n\n\n: ino-to-cg ( ino fs -- cg ) fs_ipg l@ \/ ;\n: ino-to-fsbo ( ino fs -- fsb0 ) fs_inopb l@ mod ;\n: ino-to-fsba ( ino fs -- ba )\t\\ Need to remove the stupid stack diags someday\n 2dup \t\t\t\t( ino fs ino fs )\n ino-to-cg\t\t\t\t( ino fs cg )\n over\t\t\t\t\t( ino fs cg fs )\n cgimin\t\t\t\t( ino fs inode-blk )\n -rot\t\t\t\t\t( inode-blk ino fs )\n tuck \t\t\t\t( inode-blk fs ino fs )\n fs_ipg l@ \t\t\t\t( inode-blk fs ino ipg )\n mod\t\t\t\t\t( inode-blk fs mod )\n swap\t\t\t\t\t( inode-blk mod fs )\n dup \t\t\t\t\t( inode-blk mod fs fs )\n fs_inopb l@ \t\t\t\t( inode-blk mod fs inopb )\n rot \t\t\t\t\t( inode-blk fs inopb mod )\n swap\t\t\t\t\t( inode-blk fs mod inopb )\n \/\t\t\t\t\t( inode-blk fs div )\n swap\t\t\t\t\t( inode-blk div fs )\n blkstofrags\t\t\t\t( inode-blk frag )\n +\n;\n: fsbtodb ( fsb fs -- db ) fs_fsbtodb l@ << ;\n\n\\\n\\ File stuff\n\\\n\nniaddr \/w* constant narraysize\n\nstruct \n 8\t\tfield\t>f_ihandle\t\\ device handle\n 8 \t\tfield \t>f_seekp\t\\ seek pointer\n 8 \t\tfield \t>f_fs\t\t\\ pointer to super block\n ufs1_dinode_SIZEOF \tfield \t>f_di\t\\ copy of on-disk inode\n 8\t\tfield\t>f_buf\t\t\\ buffer for data block\n 4\t\tfield \t>f_buf_size\t\\ size of data block\n 4\t\tfield\t>f_buf_blkno\t\\ block number of data block\nconstant file_SIZEOF\n\nfile_SIZEOF buffer: the-file\nsb-buf the-file >f_fs x!\n\nufs1_dinode_SIZEOF buffer: cur-inode\nh# 2000 buffer: indir-block\n-1 value indir-addr\n\n\\\n\\ Translate a fileblock to a disk block\n\\\n\\ We only allow single indirection\n\\\n\n: block-map ( fileblock -- diskblock )\n \\ Direct block?\n dup ndaddr < if \t\t\t( fileblock )\n cur-inode di_db\t\t\t( arr-indx arr-start )\n swap la+ l@ exit\t\t\t( diskblock )\n then \t\t\t\t( fileblock )\n ndaddr -\t\t\t\t( fileblock' )\n \\ Now we need to check the indirect block\n dup sb-buf fs_nindir l@ < if\t( fileblock' )\n cur-inode di_ib l@ dup\t\t( fileblock' indir-block indir-block )\n indir-addr <> if \t\t( fileblock' indir-block )\n to indir-addr\t\t\t( fileblock' )\n indir-block \t\t\t( fileblock' indir-block )\n sb-buf dup fs_bsize l@\t\t( fileblock' indir-block fs fs_bsize )\n swap indir-addr swap\t\t( fileblock' indir-block fs_bsize indiraddr fs )\n fsbtodb \t\t\t( fileblock' indir-block fs_bsize db )\n strategy\t\t\t( fileblock' nread )\n then\t\t\t\t( fileblock' nread|indir-block )\n drop \\ Really should check return value\n indir-block swap la+ l@ exit\n then\n dup sb-buf fs_nindir -\t\t( fileblock'' )\n \\ Now try 2nd level indirect block -- just read twice \n dup sb-buf fs_nindir l@ dup * < if\t( fileblock'' )\n cur-inode di_ib 1 la+ l@\t\t( fileblock'' indir2-block )\n to indir-addr\t\t\t( fileblock'' )\n \\ load 1st level indir block \n indir-block \t\t\t( fileblock'' indir-block )\n sb-buf dup fs_bsize l@\t\t( fileblock'' indir-block fs fs_bsize )\n swap indir-addr swap\t\t( fileblock'' indir-block fs_bsize indiraddr fs )\n fsbtodb \t\t\t\t( fileblock'' indir-block fs_bsize db )\n strategy\t\t\t\t( fileblock'' nread )\n drop\t\t\t\t( fileblock'' )\n dup sb-buf fs_nindir \/\t\t( fileblock'' indir-offset )\n indir-block swap la+ l@\t\t( fileblock'' indirblock )\n to indir-addr\t\t\t( fileblock'' )\n \\ load 2nd level indir block\n indir-block \t\t\t( fileblock'' indir-block )\n sb-buf dup fs_bsize l@\t\t( fileblock'' indir-block fs fs_bsize )\n swap indir-addr swap\t\t( fileblock'' indir-block fs_bsize indiraddr fs )\n fsbtodb \t\t\t\t( fileblock'' indir-block fs_bsize db )\n strategy\t\t\t\t( fileblock'' nread )\n drop\t\t\t\t( fileblock'' )\n sb-buf fs_nindir l@ mod indir-block swap la+ l@ exit\n then\n .\" block-map: exceeded max file size\" cr\n abort\n;\n\n\\\n\\ Read file into internal buffer and return pointer and len\n\\\n\n0 value cur-block\t\t\t\\ allocated dynamically in ufs-open\n0 value cur-blocksize\t\t\t\\ size of cur-block\n-1 value cur-blockno\n0 value cur-offset\n\n: buf-read-file ( fs -- len buf )\n cur-offset swap\t\t\t( seekp fs )\n 2dup blkoff\t\t\t\t( seekp fs off )\n -rot 2dup lblkno\t\t\t( off seekp fs block )\n swap 2dup cur-inode\t\t\t( off seekp block fs block fs inop )\n swap dblksize\t\t\t( off seekp block fs size )\n rot dup cur-blockno\t\t\t( off seekp fs size block block cur )\n <> if \t\t\t\t( off seekp fs size block )\n block-map\t\t\t\t( off seekp fs size diskblock )\n dup 0= if\t\t\t( off seekp fs size diskblock )\n over cur-block swap 0 fill\t( off seekp fs size diskblock )\n boot-debug? if .\" buf-read-file fell off end of file\" cr then\n else\n 2dup sb-buf fsbtodb cur-block -rot strategy\t( off seekp fs size diskblock nread )\n rot 2dup <> if \" buf-read-file: short read.\" cr abort then\n then\t\t\t\t( off seekp fs diskblock nread size )\n nip nip\t\t\t\t( off seekp fs size )\n else\t\t\t\t\t( off seekp fs size block block cur )\n 2drop\t\t\t\t( off seekp fs size )\n then\n\\ dup cur-offset + to cur-offset\t\\ Set up next xfer -- not done\n nip nip swap -\t\t\t( len )\n cur-block\n;\n\n\\\n\\ Read inode into cur-inode -- uses cur-block\n\\ \n\n: read-inode ( inode fs -- )\n twiddle\t\t\t\t( inode fs -- inode fs )\n\n cur-block\t\t\t\t( inode fs -- inode fs buffer )\n\n over\t\t\t\t\t( inode fs buffer -- inode fs buffer fs )\n fs_bsize l@\t\t\t\t( inode fs buffer -- inode fs buffer size )\n\n 2over\t\t\t\t( inode fs buffer size -- inode fs buffer size inode fs )\n 2over\t\t\t\t( inode fs buffer size inode fs -- inode fs buffer size inode fs buffer size )\n 2swap tuck\t\t\t\t( inode fs buffer size inode fs buffer size -- inode fs buffer size buffer size fs inode fs )\n\n ino-to-fsba \t\t\t\t( inode fs buffer size buffer size fs inode fs -- inode fs buffer size buffer size fs fsba )\n swap\t\t\t\t\t( inode fs buffer size buffer size fs fsba -- inode fs buffer size buffer size fsba fs )\n fsbtodb\t\t\t\t( inode fs buffer size buffer size fsba fs -- inode fs buffer size buffer size db )\n\n dup to cur-blockno\t\t\t( inode fs buffer size buffer size dstart -- inode fs buffer size buffer size dstart )\n strategy\t\t\t\t( inode fs buffer size buffer size dstart -- inode fs buffer size nread )\n <> if .\" read-inode - residual\" cr abort then\n dup 2over\t\t\t\t( inode fs buffer -- inode fs buffer buffer inode fs )\n ino-to-fsbo\t\t\t\t( inode fs buffer -- inode fs buffer buffer fsbo )\n ufs1_dinode_SIZEOF * +\t\t\t( inode fs buffer buffer fsbo -- inode fs buffer dinop )\n cur-inode ufs1_dinode_SIZEOF move \t( inode fs buffer dinop -- inode fs buffer )\n\t\\ clear out the old buffers\n drop\t\t\t\t\t( inode fs buffer -- inode fs )\n 2drop\n;\n\n\\ Identify inode type\n\n: is-dir? ( dinode -- true:false ) di_mode w@ ifmt and ifdir = ;\n: is-symlink? ( dinode -- true:false ) di_mode w@ ifmt and iflnk = ;\n\n\n\n\\\n\\ Hunt for directory entry:\n\\ \n\\ repeat\n\\ load a buffer\n\\ while entries do\n\\ if entry == name return\n\\ next entry\n\\ until no buffers\n\\\n\n: search-directory ( str len -- ino|0 )\n 0 to cur-offset\n begin cur-offset cur-inode di_size x@ < while\t( str len )\n sb-buf buf-read-file\t\t( str len len buf )\n over 0= if .\" search-directory: buf-read-file zero len\" cr abort then\n swap dup cur-offset + to cur-offset\t( str len buf len )\n 2dup + nip\t\t\t( str len buf bufend )\n swap 2swap rot\t\t\t( bufend str len buf )\n begin dup 4 pick < while\t\t( bufend str len buf )\n dup d_ino l@ 0<> if \t\t( bufend str len buf )\n boot-debug? if dup dup d_name swap d_namlen c@ type cr then\n 2dup d_namlen c@ = if\t( bufend str len buf )\n dup d_name 2over\t\t( bufend str len buf dname str len )\n comp 0= if\t\t( bufend str len buf )\n \\ Found it -- return inode\n d_ino l@ nip nip nip\t( dino )\n boot-debug? if .\" Found it\" cr then \n exit \t\t\t( dino )\n then\n then\t\t\t( bufend str len buf )\n then\t\t\t\t( bufend str len buf )\n dup d_reclen w@ +\t\t( bufend str len nextbuf )\n repeat\n drop rot drop\t\t\t( str len )\n repeat\n 2drop 2drop 0\t\t\t( 0 )\n;\n\n: ffs_oldcompat ( -- )\n\\ Make sure old ffs values in sb-buf are sane\n sb-buf fs_npsect dup l@ sb-buf fs_nsect l@ max swap l!\n sb-buf fs_interleave dup l@ 1 max swap l!\n sb-buf fs_postblformat l@ fs_42postblfmt = if\n 8 sb-buf fs_nrpos l!\n then\n sb-buf fs_inodefmt l@ fs_44inodefmt < if\n sb-buf fs_bsize l@ \n dup ndaddr * 1- sb-buf fs_maxfilesize x!\n niaddr 0 ?do\n\tsb-buf fs_nindir l@ * dup\t( sizebp sizebp -- )\n\tsb-buf fs_maxfilesize dup x@\t( sizebp sizebp *fs_maxfilesize fs_maxfilesize -- )\n\trot \t\t\t\t( sizebp *fs_maxfilesize fs_maxfilesize sizebp -- )\n\t+ \t\t\t\t( sizebp *fs_maxfilesize new_fs_maxfilesize -- ) \n swap x! \t\t\t( sizebp -- )\n loop drop \t\t\t( -- )\n sb-buf dup fs_bmask l@ not swap fs_qbmask x!\n sb-buf dup fs_fmask l@ not swap fs_qfmask x!\n then\n;\n\n: read-super ( sector -- )\n0 \" seek\" boot-ihandle $call-method\n -1 = if \n .\" Seek failed\" cr\n abort\n then\n sb-buf sbsize \" read\" boot-ihandle $call-method\n dup sbsize <> if\n .\" Read of superblock failed\" cr\n .\" requested\" space sbsize .\n .\" actual\" space . cr\n abort\n else \n drop\n then\n;\n\n: ufs-open ( bootpath,len -- )\n boot-ihandle -1 = if\n over cif-open dup 0= if \t\t( boot-path len ihandle? )\n .\" Could not open device\" space type cr \n abort\n then \t\t\t\t( boot-path len ihandle )\n to boot-ihandle\t\t\t\\ Save ihandle to boot device\n then 2drop\n sboff read-super\n sb-buf fs_magic l@ fs_magic_value <> if\n 64 dup to raid-offset \n dev_bsize * sboff + read-super\n sb-buf fs_magic l@ fs_magic_value <> if\n .\" Invalid superblock magic\" cr\n abort\n then\n then\n sb-buf fs_bsize l@ dup maxbsize > if\n .\" Superblock bsize\" space . .\" too large\" cr\n abort\n then \n dup fs_SIZEOF < if\n .\" Superblock bsize < size of superblock\" cr\n abort\n then\n ffs_oldcompat\t( fs_bsize -- fs_bsize )\n dup to cur-blocksize alloc-mem to cur-block \\ Allocate cur-block\n boot-debug? if .\" ufs-open complete\" cr then\n;\n\n: ufs-close ( -- ) \n boot-ihandle dup -1 <> if\n cif-close -1 to boot-ihandle \n then\n cur-block 0<> if\n cur-block cur-blocksize free-mem\n then\n;\n\n: boot-path ( -- boot-path )\n \" bootpath\" chosen-phandle get-package-property if\n .\" Could not find bootpath in \/chosen\" cr\n abort\n else\n decode-string 2swap 2drop\n then\n;\n\n: boot-args ( -- boot-args )\n \" bootargs\" chosen-phandle get-package-property if\n .\" Could not find bootargs in \/chosen\" cr\n abort\n else\n decode-string 2swap 2drop\n then\n;\n\n2000 buffer: boot-path-str\n2000 buffer: boot-path-tmp\n\n: split-path ( path len -- right len left len )\n\\ Split a string at the `\/'\n begin\n dup -rot\t\t\t\t( oldlen right len left )\n ascii \/ left-parse-string\t\t( oldlen right len left len )\n dup 0<> if 4 roll drop exit then\n 2drop\t\t\t\t( oldlen right len )\n rot over =\t\t\t( right len diff )\n until\n;\n\n: find-file ( load-file len -- )\n rootino dup sb-buf read-inode\t( load-file len -- load-file len ino )\n -rot\t\t\t\t\t( load-file len ino -- pino load-file len )\n \\\n \\ For each path component\n \\ \n begin split-path dup 0<> while\t( pino right len left len -- )\n cur-inode is-dir? not if .\" Inode not directory\" cr abort then\n boot-debug? if .\" Looking for\" space 2dup type space .\" in directory...\" cr then\n search-directory\t\t\t( pino right len left len -- pino right len ino|false )\n dup 0= if .\" Bad path\" cr abort then\t( pino right len cino )\n sb-buf read-inode\t\t\t( pino right len )\n cur-inode is-symlink? if\t\t\\ Symlink -- follow the damn thing\n \\ Save path in boot-path-tmp\n boot-path-tmp strmov\t\t( pino new-right len )\n\n \\ Now deal with symlink\n cur-inode di_size x@\t\t( pino right len linklen )\n dup sb-buf fs_maxsymlinklen l@\t( pino right len linklen linklen maxlinklen )\n < if\t\t\t\t\\ Now join the link to the path\n cur-inode di_shortlink l@\t( pino right len linklen linkp )\n swap boot-path-str strmov\t( pino right len new-linkp linklen )\n else\t\t\t\t\\ Read file for symlink -- Ugh\n \\ Read link into boot-path-str\n boot-path-str dup sb-buf fs_bsize l@\n 0 block-map\t\t\t( pino right len linklen boot-path-str bsize blockno )\n strategy drop swap\t\t( pino right len boot-path-str linklen )\n then \t\t\t\t( pino right len linkp linklen )\n \\ Concatenate the two paths\n strcat\t\t\t\t( pino new-right newlen )\n swap dup c@ ascii \/ = if\t\\ go to root inode?\n rot drop rootino -rot\t( rino len right )\n then\n rot dup sb-buf read-inode\t( len right pino )\n -rot swap\t\t\t( pino right len )\n then\t\t\t\t( pino right len )\n repeat\n 2drop drop\n;\n\n: read-file ( size addr -- )\n \\ Read x bytes from a file to buffer\n begin over 0> while\n cur-offset cur-inode di_size x@ > if .\" read-file EOF exceeded\" cr abort then\n sb-buf buf-read-file\t\t( size addr len buf )\n over 2over drop swap\t\t( size addr len buf addr len )\n move\t\t\t\t( size addr len )\n dup cur-offset + to cur-offset\t( size len newaddr )\n tuck +\t\t\t\t( size len newaddr )\n -rot - swap\t\t\t( newaddr newsize )\n repeat\n 2drop\n;\n\n\\\n\\ According to the 1275 addendum for SPARC processors:\n\\ Default load-base is 0x4000. At least 0x8.0000 or\n\\ 512KB must be available at that address. \n\\\n\\ The Fcode bootblock can take up up to 8KB (O.K., 7.5KB) \n\\ so load programs at 0x4000 + 0x2000=> 0x6000\n\\\n\nh# 6000 constant loader-base\n\n\\\n\\ Elf support -- find the load addr\n\\\n\n: is-elf? ( hdr -- res? ) h# 7f454c46 = ;\n\n\\\n\\ Finally we finish it all off\n\\\n\n: load-file-signon ( load-file len boot-path len -- load-file len boot-path len )\n .\" Loading file\" space 2over type cr .\" from device\" space 2dup type cr\n;\n\n: load-file-print-size ( size -- size )\n .\" Loading\" space dup . space .\" bytes of file...\" cr \n;\n\n: load-file ( load-file len boot-path len -- load-base )\n boot-debug? if load-file-signon then\n the-file file_SIZEOF 0 fill\t\t\\ Clear out file structure\n ufs-open \t\t\t\t( load-file len )\n find-file\t\t\t\t( )\n\n \\\n \\ Now we've found the file we should read it in in one big hunk\n \\\n\n cur-inode di_size x@\t\t\t( file-len )\n dup \" to file-size\" evaluate\t\t( file-len )\n boot-debug? if load-file-print-size then\n 0 to cur-offset\n loader-base\t\t\t\t( buf-len addr )\n 2dup read-file\t\t\t( buf-len addr )\n ufs-close\t\t\t\t( buf-len addr )\n dup is-elf? if .\" load-file: not an elf executable\" cr abort then\n\n \\ Luckily the prom should be able to handle ELF executables by itself\n\n nip\t\t\t\t\t( addr )\n;\n\n: do-boot ( bootfile -- )\n .\" OpenBSD IEEE 1275 Bootblock 1.1\" cr\n boot-path load-file ( -- load-base )\n dup 0<> if \" to load-base init-program\" evaluate then\n;\n\n\nboot-args ascii V strchr 0<> swap drop if\n true to boot-debug?\nthen\n\nboot-args ascii D strchr 0= swap drop if\n \" \/ofwboot\" do-boot\nthen exit\n\n\n","returncode":0,"stderr":"","license":"isc","lang":"Forth"} {"commit":"154f229b131cd562ab9ec8726fc5739017e7fac7","subject":"?NEG refactored","message":"?NEG refactored\n","repos":"bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas","old_file":"KataDiversion.fth","new_file":"KataDiversion.fth","new_contents":"\\ KataDiversion in Forth\n\n\\ -- utils\n\n\\ empty the stack\n: EMPTY\n DEPTH 0 <> IF BEGIN\n DROP DEPTH 0 =\n UNTIL\n THEN ;\n\n\\ power\n: ** ( n1 n2 -- n1_pow_n2 ) 1 SWAP ?DUP IF 0 DO OVER * LOOP THEN NIP ;\n\n\\ test if the top is a negative number\n: ?NEG ( n -- bool ) 1 < ;\n\n\\ compute the highest power of 2 below N.\n\\ e.g. : 31 -> 16, 4 -> 4\n: MAXPOW2 ( n -- log2_n ) DUP 1 < IF 1 ABORT\" Maxpow2 need a positive value.\"\n ELSE DUP 1 = IF 1\n ELSE\n 1 >R\n BEGIN ( n |R: i=1)\n DUP DUP I - 2 *\n ( n n 2*[n-i])\n R> 2 * >R ( \u2026 |R: i*2)\n > ( n n>2*[n-i] )\n UNTIL\n R> 2 \/\n THEN\n THEN NIP ;\n\n\\ -- kata\n\n\\ test if the given N has two adjacent 1 bits\n\\ e.g. : 11 -> 1011 -> -1\n\\ 9 -> 1001 -> 0\n: ?TWO-ADJACENT-1-BITS ( n -- bool )\n \\ the word uses the following algorithm :\n \\ (stack|return stack)\n \\ ( A N | X ) A: 0, X: N LOG2\n \\ loop: if N-X > 0 then A++ else A=0 ; X \/= 2\n \\ return -1 if A=2\n \\ if X=1 end loop and return 0\n 0 SWAP DUP DUP 0 <> IF\n MAXPOW2 >R\n BEGIN\n DUP I - 0 >= IF \n SWAP DUP 1 = IF 1+ SWAP\n ELSE 1+ SWAP I -\n THEN\n ELSE NIP 0 SWAP\n THEN\n OVER\n 2 =\n I 1 = OR\n R> 2 \/ >R\n UNTIL\n R> 2DROP\n 2 =\n THEN ;\n\n\\ return the maximum number which can be made with N (given number) bits\n: ?MAX-NB ( n -- m ) DUP ?NEG IF DROP 0 ( 0 )\n ELSE \n DUP IF DUP 2 SWAP ** NIP ( 2**n )\n THEN\n THEN ;\n\n\n\\ return the number of numbers which can be made with N (given number) bits\n\\ or less, and which have not two adjacent 1 bits.\n\\ see http:\/\/www.codekata.com\/2007\/01\/code_kata_fifte.html\n: ?HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS ( n -- m ) ( TODO ) ;\n","old_contents":"\\ KataDiversion in Forth\n\n\\ -- utils\n\n\\ empty the stack\n: EMPTY\n DEPTH 0 <> IF BEGIN\n DROP DEPTH 0 =\n UNTIL\n THEN ;\n\n\\ power\n: ** ( n1 n2 -- n1_pow_n2 ) 1 SWAP ?DUP IF 0 DO OVER * LOOP THEN NIP ;\n\n\\ test if the top is a negative number\n: ?NEG ( n -- bool ) DUP 0= IF -1 ELSE DUP ABS <> THEN ;\n\n\\ compute the highest power of 2 below N.\n\\ e.g. : 31 -> 16, 4 -> 4\n: MAXPOW2 ( n -- log2_n ) DUP 1 < IF 1 ABORT\" Maxpow2 need a positive value.\"\n ELSE DUP 1 = IF 1\n ELSE\n 1 >R\n BEGIN ( n |R: i=1)\n DUP DUP I - 2 *\n ( n n 2*[n-i])\n R> 2 * >R ( \u2026 |R: i*2)\n > ( n n>2*[n-i] )\n UNTIL\n R> 2 \/\n THEN\n THEN NIP ;\n\n\\ -- kata\n\n\\ test if the given N has two adjacent 1 bits\n\\ e.g. : 11 -> 1011 -> -1\n\\ 9 -> 1001 -> 0\n: ?TWO-ADJACENT-1-BITS ( n -- bool )\n \\ the word uses the following algorithm :\n \\ (stack|return stack)\n \\ ( A N | X ) A: 0, X: N LOG2\n \\ loop: if N-X > 0 then A++ else A=0 ; X \/= 2\n \\ return -1 if A=2\n \\ if X=1 end loop and return 0\n 0 SWAP DUP DUP 0 <> IF\n MAXPOW2 >R\n BEGIN\n DUP I - 0 >= IF \n SWAP DUP 1 = IF 1+ SWAP\n ELSE 1+ SWAP I -\n THEN\n ELSE NIP 0 SWAP\n THEN\n OVER\n 2 =\n I 1 = OR\n R> 2 \/ >R\n UNTIL\n R> 2DROP\n 2 =\n THEN ;\n\n\\ return the maximum number which can be made with N (given number) bits\n: ?MAX-NB ( n -- m ) DUP ?NEG IF DROP 0 ( 0 )\n ELSE \n DUP IF DUP 2 SWAP ** NIP ( 2**n )\n THEN\n THEN ;\n\n\n\\ return the number of numbers which can be made with N (given number) bits\n\\ or less, and which have not two adjacent 1 bits.\n\\ see http:\/\/www.codekata.com\/2007\/01\/code_kata_fifte.html\n: ?HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS ( n -- m ) ( TODO ) ;\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"ed1bf3879d725f53eddf7d00670b9139b3b60fd4","subject":"boot: 19.1 development now","message":"boot: 19.1 development now\n","repos":"opnsense\/core,opnsense\/core,opnsense\/core,opnsense\/core,opnsense\/core,opnsense\/core","old_file":"src\/boot\/logo-hourglass.4th","new_file":"src\/boot\/logo-hourglass.4th","new_contents":"\\ Copyright (c) 2006-2015 Devin Teske \n\\ Copyright (c) 2016-2017 Deciso B.V.\n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\n48 logoX ! 9 logoY ! \\ Initialize logo placement defaults\n\n: logo+ ( x y c-addr\/u -- x y' )\n\t2swap 2dup at-xy 2swap \\ position the cursor\n\t[char] # escc! \\ replace # with Esc\n\ttype \\ print to the screen\n\t1+ \\ increase y for next time we're called\n;\n\n: logo ( x y -- ) \\ color hourglass logo (15 rows x 32 columns)\n\n\ts\" #[37;1m @@@@@@@@@@@@@@@@@@@@@@@@@@@@\" logo+\n\ts\" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\" logo+\n\ts\" @@@@@ @@@@@\" logo+\n\ts\" @@@@@ @@@@@ \" logo+\n\ts\" @@@@@@@@@@@ @@@@@@@@@@@\" logo+\n\ts\" #[31;1m\\\\\\\\\\ \/\/\/\/\/ \" logo+\n\ts\" )))))))))))) (((((((((((\" logo+\n\ts\" \/\/\/\/\/ \\\\\\\\\\ #[m\" logo+\n\ts\" #[37;1m @@@@@@@@@@@ @@@@@@@@@@@\" logo+\n\ts\" @@@@@ @@@@@ \" logo+\n\ts\" @@@@@ @@@@@\" logo+\n\ts\" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\" logo+\n\ts\" @@@@@@@@@@@@@@@@@@@@@@@@@@@@ \" logo+\n\ts\" #[m \" logo+\n\ts\" 19.1 ``Insert Name Here'' #[m\" logo+\n\n\t2drop\n;\n","old_contents":"\\ Copyright (c) 2006-2015 Devin Teske \n\\ Copyright (c) 2016-2017 Deciso B.V.\n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\n48 logoX ! 9 logoY ! \\ Initialize logo placement defaults\n\n: logo+ ( x y c-addr\/u -- x y' )\n\t2swap 2dup at-xy 2swap \\ position the cursor\n\t[char] # escc! \\ replace # with Esc\n\ttype \\ print to the screen\n\t1+ \\ increase y for next time we're called\n;\n\n: logo ( x y -- ) \\ color hourglass logo (15 rows x 32 columns)\n\n\ts\" #[37;1m @@@@@@@@@@@@@@@@@@@@@@@@@@@@\" logo+\n\ts\" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\" logo+\n\ts\" @@@@@ @@@@@\" logo+\n\ts\" @@@@@ @@@@@ \" logo+\n\ts\" @@@@@@@@@@@ @@@@@@@@@@@\" logo+\n\ts\" #[31;1m\\\\\\\\\\ \/\/\/\/\/ \" logo+\n\ts\" )))))))))))) (((((((((((\" logo+\n\ts\" \/\/\/\/\/ \\\\\\\\\\ #[m\" logo+\n\ts\" #[37;1m @@@@@@@@@@@ @@@@@@@@@@@\" logo+\n\ts\" @@@@@ @@@@@ \" logo+\n\ts\" @@@@@ @@@@@\" logo+\n\ts\" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\" logo+\n\ts\" @@@@@@@@@@@@@@@@@@@@@@@@@@@@ \" logo+\n\ts\" #[m \" logo+\n\ts\" 18.7 ``Insert Name Here'' #[m\" logo+\n\n\t2drop\n;\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"365fe52f85a863e7e98d131e1b80671c53bc5259","subject":"added recurse keyword","message":"added recurse keyword\n","repos":"howerj\/libforth","old_file":"fth\/forth.4th","new_file":"fth\/forth.4th","new_contents":"\\ Howe Forth: Start up code.\n\\ @author Richard James Howe.\n\\ @copyright Copyright 2013 Richard James Howe.\n\\ @license LGPL \n\\ @email howe.r.j.89@gmail.com\n\n: true 1 exit\n: false 0 exit\n\n: cpf 13 exit \\ Compile Flag \n: state cpf !reg exit\n: ; immediate \n\t' exit , \n\tfalse state\nexit\n\n\\ Register constants\n: r 3 ;\t \\ Return stack pointer\n: v 4 ;\t \\ Variable stack pointer\n: h 5 ;\t \\ Dictionary pointer\n: str 6 ; \\ String storage pointer\n: pwd 7 ; \\ previous word\n: exf 14 ; \\ Pointer to execution token, executed on error.\n: iobl 21 ; \\ I\/O buf len address\n: here h @reg ;\n\n\\ Error handling!\n: on_err read on_err ; \\ This word is executed when an error occurs.\nfind on_err exf !reg \\ Write the executable token for on_err into the dictionary.\n\n\\ change to command mode\n: [ immediate false state ;\n\\ change to compile mode\n: ] true state ;\n\n\\ These words represent words with no name in the dictionary, \n\\ the 'invisible' words.\n: _push 0 ;\n: _compile 1 ;\n: _run 2 ;\n\n\\ System calls\n: reset 0 ;\n: fopen 1 ;\n: fclose 2 ;\n: fflush 3 ;\n: remove 4 ;\n: rename 5 ;\n: rewind 6 ;\n: system 7 ;\n\n\\ Constants for system call arguments\n: input 0 ;\n: output 1 ;\n\n: literal immediate _push , , ;\n\n\\ ASCII chars\n\n: 'esc' 27 ;\n: '\"' 34 ;\n: ')' 41 ;\n\n: 0= 0 = ;\n: 0< 0 < ;\n: 0> 0 > ;\n\n: space 32 emit ;\n: cr 10 emit ;\n: tab 9 emit ;\n\n: prnn 10 swap printnum ;\n: . prnn cr ;\n\n: tuck swap over ;\n: nip swap drop ;\n: rot >r swap r> swap ;\n: <> = 0= ;\n: negate -1 * ;\n: -rot rot rot ;\n\n: 2drop drop drop ;\n: 2dup over over ;\n: 2swap rot >r rot r> ;\n\n: 2+ 1+ 1+ ;\n: 2* 2 * ;\n: 2\/ 2 \/ ; \n: 2- 1- 1- ;\n\n: if immediate \n\t' ?br , \n\there 0 , \n;\n\n: else immediate\n\t' br ,\n\there\n\t0 ,\n\tswap dup here swap -\n\tswap !\n;\n\n: then immediate \n\tdup here \n\tswap - swap \n\t! \n;\n\n: begin immediate\n\there\n;\n\n: until immediate\n\t' ?br ,\n\there - ,\n;\n\n: ?dup dup if dup then ;\n: abs dup 0 < if negate then ;\n\n: min 2dup < if drop else swap drop then ; \n: max 2dup > if drop else swap drop then ; \n\n: allot here + h !reg ;\n: :noname immediate here _run , ] ;\n: ? 0= if \\ ( bool -- ) ( Conditional evaluation )\n [ find \\ literal ] execute \n then \n;\n\n: _( \\ ( letter bool -- ) \\ \n >r \\ Store bool on return stack for simplicity\n begin \n key 2dup = \\ key in a letter, test if it is equal to out terminator\n if\n 2drop 1 \\ Drop items, quit loop\n else \n r> dup >r \\ test for bool\n if \\ bool == 1, emit letter, bool == 0 drop it.\n emit \n else \n drop \n then \n 0 \\ Continue\n then \n until \n r> drop \\ Return stack back to normal now.\n;\n\n: ( immediate ')' 0 _( ; ( Now we have proper comments )\n: .( immediate ')' 1 _( ; ( Print out word )\n\n ( Print out a string stored in string storage )\n: prn ( str_ptr -- )\n begin\n dup @str dup 0= ( if null )\n if\n 2drop 1 \n else\n emit 1+ 0\n then\n until\n;\n\n ( Store a '\"' terminated string in string storage )\n: _.\" ( -- )\n str @reg 1-\n begin\n key dup >r '\"' =\n if\n r> drop 1\n else\n 1+ dup r> swap !str 0\n then\n until\n 2+\n str !reg\n;\n\n: .\" immediate\n cpf @reg 0= if\n '\"' 1 _(\n else\n _push , str @reg ,\n _.\"\n ' prn ,\n then\n;\n \n: :: \t( compiles a ':' )\n [ find : , ]\n;\n\n( Helper words for create )\n: '', ' ' , ; \\ A word that writes ' into the dictionary\n: ',, ' , , ; \\ A word that writes , into the dictionary\n: 'exit, ' exit , ; \\ A word that write exit into the dictionary\n: 3+ 2+ 1+ ;\n\n( The word create involves multiple levels of indirection.\n It makes a word which has to write in values into\n another word )\n: create immediate \\ This is a complicated word! It makes a\n \\ word that makes a word.\n cpf @reg if \\ Compile time behavour\n ' :: , \\ Make the defining word compile a header\n '', _push , ',, \\ Write in push to the creating word\n ' here , ' 3+ , ',, \\ Write in the number we want the created word to push\n '', here 0 , ',, \\ Write in a place holder (0) and push a \n \\ pointer to to be used by does>\n '', 'exit, ',, \\ Write in an exit in the word we're compiling.\n ' false , ' state , \\ Make sure to change the state back to command mode\n else \\ Run time behavour\n :: \\ Compile a word\n _push , \\ Write push into new word\n here 2+ , \\ Push a pointer to data field\n 'exit, \\ Write in an exit to new word (data field is after exit)\n false state \\ Return to command mode.\n then\n;\n\n: does> immediate\n 'exit, \\ Write in an exit, we don't want the\n \\ defining to run it, but the *defined* word to.\n here swap ! \\ Patch in the code fields to point to.\n _run , \\ Write a run in.\n;\n\n: constant create , does> @ ; \n: variable create , does> ;\n: array create allot does> + ;\n\n( Store temporary filenames here. )\nstr @reg dup iobl @reg + str !reg constant filename\n\n0 variable strvar\n: getstr\"\n 0 strvar !\n begin\n key dup '\"' \n = \n if\n 0 strvar @ filename + !str\n drop 1\n else\n strvar @ filename + !str \n strvar @ 1+ strvar !\n 0 \n then\n until\n filename\n;\n\n( file i\/o )\n: foutput\n filename getword\n filename output fopen kernel \n;\n\n: finput\n filename getword\n filename input fopen kernel \n drop\n;\n\n: fremove\n filename getword\n filename remove kernel\n;\n\n: frewind\n output rewind kernel\n;\n\n: system\"\n getstr\"\n system kernel\n;\n\n0 variable i\n0 variable j\n\n: i! i ! ;\n: j! j ! ;\n: i@ i @ ;\n: j@ j @ ;\n\n: do immediate ( this needs redoing so it can be nested )\n ' j! ,\n ' i! ,\n here\n;\n\n: not ( a -- ~a )\n if 0 else 1 then\n;\n\n: >= ( a b -- bool )\n < not\n;\n\n: (++i)>=j\n i@ 1+ i! i@ j@ >= \n;\n\n: loop immediate\n ' (++i)>=j ,\n ' ?br ,\n here - ,\n;\n\n: break ( break out of a do ... loop )\n j@ i!\n;\n\n: gcd ( a b -- n ) ( greatest common divisor )\n begin\n dup\n if\n tuck mod 0\n else\n 1\n then\n until\n drop\n;\n\n: fpwdf \\ Find the previous words data field\n pwd @reg 2 + \n dup @ 1 = if\n 2+\n else\n 1+\n then \n;\n\n: recurse immediate\n ' br ,\n fpwdf \n here - ,\n;\n\n( =========================================================================== )\n\n\\ : vocabulary create pwd @reg , does> @ pwd !reg ;\n\\ vocabulary forth\n\nfinput ..\/fth\/debug.4th ( Debugging operations )\nfinput ..\/fth\/rational.4th ( Real type )\nfinput ..\/fth\/math.4th ( Math functions )\nfinput ..\/fth\/auto.4th ( Auto generated constants )\nfinput ..\/fth\/memory.4th ( Memory allocation and manipulation )\nfinput ..\/fth\/welcome.4th ( Welcome and cursor control )\n\n.( : hello ; ) cr\n: hello .\" hello, world \" cr ; find hello dup 20 + show \nfpwdf .\n.( : ihello ; ) cr\n: ihello immediate .\" hello, world \" cr ; find ihello dup 20 + show \nfpwdf .\n","old_contents":"\\ Howe Forth: Start up code.\n\\ @author Richard James Howe.\n\\ @copyright Copyright 2013 Richard James Howe.\n\\ @license LGPL \n\\ @email howe.r.j.89@gmail.com\n\n: true 1 exit\n: false 0 exit\n\n: cpf 13 exit \\ Compile Flag \n: state cpf !reg exit\n: ; immediate \n\t' exit , \n\tfalse state\nexit\n\n\\ Register constants\n: r 3 ;\t \\ Return stack pointer\n: v 4 ;\t \\ Variable stack pointer\n: h 5 ;\t \\ Dictionary pointer\n: str 6 ; \\ String storage pointer\n: pwd 7 ; \\ previous word\n: exf 14 ; \\ Pointer to execution token, executed on error.\n: iobl 21 ; \\ I\/O buf len address\n: here h @reg ;\n\n\\ Error handling!\n: on_err read on_err ; \\ This word is executed when an error occurs.\nfind on_err exf !reg \\ Write the executable token for on_err into the dictionary.\n\n\\ change to command mode\n: [ immediate false state ;\n\\ change to compile mode\n: ] true state ;\n\n\\ These words represent words with no name in the dictionary, \n\\ the 'invisible' words.\n: _push 0 ;\n: _compile 1 ;\n: _run 2 ;\n\n\\ System calls\n: reset 0 ;\n: fopen 1 ;\n: fclose 2 ;\n: fflush 3 ;\n: remove 4 ;\n: rename 5 ;\n: rewind 6 ;\n: system 7 ;\n\n\\ Constants for system call arguments\n: input 0 ;\n: output 1 ;\n\n: literal immediate _push , , ;\n\n\\ ASCII chars\n\n: 'esc' 27 ;\n: '\"' 34 ;\n: ')' 41 ;\n\n: 0= 0 = ;\n: 0< 0 < ;\n: 0> 0 > ;\n\n: space 32 emit ;\n: cr 10 emit ;\n: tab 9 emit ;\n\n: prnn 10 swap printnum ;\n: . prnn cr ;\n\n: tuck swap over ;\n: nip swap drop ;\n: rot >r swap r> swap ;\n: <> = 0= ;\n: negate -1 * ;\n: -rot rot rot ;\n\n: 2drop drop drop ;\n: 2dup over over ;\n: 2swap rot >r rot r> ;\n\n: 2+ 1+ 1+ ;\n: 2* 2 * ;\n: 2\/ 2 \/ ; \n: 2- 1- 1- ;\n\n: if immediate \n\t' ?br , \n\there 0 , \n;\n\n: else immediate\n\t' br ,\n\there\n\t0 ,\n\tswap dup here swap -\n\tswap !\n;\n\n: then immediate \n\tdup here \n\tswap - swap \n\t! \n;\n\n: begin immediate\n\there\n;\n\n: until immediate\n\t' ?br ,\n\there - ,\n;\n\n: ?dup dup if dup then ;\n: abs dup 0 < if negate then ;\n\n: min 2dup < if drop else swap drop then ; \n: max 2dup > if drop else swap drop then ; \n\n: allot here + h !reg ;\n: :noname immediate here _run , ] ;\n: ? 0= if \\ ( bool -- ) ( Conditional evaluation )\n [ find \\ literal ] execute \n then \n;\n\n: _( \\ ( letter bool -- ) \\ \n >r \\ Store bool on return stack for simplicity\n begin \n key 2dup = \\ key in a letter, test if it is equal to out terminator\n if\n 2drop 1 \\ Drop items, quit loop\n else \n r> dup >r \\ test for bool\n if \\ bool == 1, emit letter, bool == 0 drop it.\n emit \n else \n drop \n then \n 0 \\ Continue\n then \n until \n r> drop \\ Return stack back to normal now.\n;\n\n: ( immediate ')' 0 _( ; ( Now we have proper comments )\n: .( immediate ')' 1 _( ; ( Print out word )\n\n ( Print out a string stored in string storage )\n: prn ( str_ptr -- )\n begin\n dup @str dup 0= ( if null )\n if\n 2drop 1 \n else\n emit 1+ 0\n then\n until\n;\n\n ( Store a '\"' terminated string in string storage )\n: _.\" ( -- )\n str @reg 1-\n begin\n key dup >r '\"' =\n if\n r> drop 1\n else\n 1+ dup r> swap !str 0\n then\n until\n 2+\n str !reg\n;\n\n: .\" immediate\n cpf @reg 0= if\n '\"' 1 _(\n else\n _push , str @reg ,\n _.\"\n ' prn ,\n then\n;\n \n: :: \t( compiles a ':' )\n [ find : , ]\n;\n\n( Helper words for create )\n: '', ' ' , ; \\ A word that writes ' into the dictionary\n: ',, ' , , ; \\ A word that writes , into the dictionary\n: 'exit, ' exit , ; \\ A word that write exit into the dictionary\n: 3+ 2+ 1+ ;\n\n( The word create involves multiple levels of indirection.\n It makes a word which has to write in values into\n another word )\n: create immediate \\ This is a complicated word! It makes a\n \\ word that makes a word.\n cpf @reg if \\ Compile time behavour\n ' :: , \\ Make the defining word compile a header\n '', _push , ',, \\ Write in push to the creating word\n ' here , ' 3+ , ',, \\ Write in the number we want the created word to push\n '', here 0 , ',, \\ Write in a place holder (0) and push a \n \\ pointer to to be used by does>\n '', 'exit, ',, \\ Write in an exit in the word we're compiling.\n ' false , ' state , \\ Make sure to change the state back to command mode\n else \\ Run time behavour\n :: \\ Compile a word\n _push , \\ Write push into new word\n here 2+ , \\ Push a pointer to data field\n 'exit, \\ Write in an exit to new word (data field is after exit)\n false state \\ Return to command mode.\n then\n;\n\n: does> immediate\n 'exit, \\ Write in an exit, we don't want the\n \\ defining to run it, but the *defined* word to.\n here swap ! \\ Patch in the code fields to point to.\n _run , \\ Write a run in.\n;\n\n: constant create , does> @ ; \n: variable create , does> ;\n: array create allot does> + ;\n\n( Store temporary filenames here. )\nstr @reg dup iobl @reg + str !reg constant filename\n\n0 variable strvar\n: getstr\"\n 0 strvar !\n begin\n key dup '\"' \n = \n if\n 0 strvar @ filename + !str\n drop 1\n else\n strvar @ filename + !str \n strvar @ 1+ strvar !\n 0 \n then\n until\n filename\n;\n\n( file i\/o )\n: foutput\n filename getword\n filename output fopen kernel \n;\n\n: finput\n filename getword\n filename input fopen kernel \n drop\n;\n\n: fremove\n filename getword\n filename remove kernel\n;\n\n: frewind\n output rewind kernel\n;\n\n: system\"\n getstr\"\n system kernel\n;\n\n0 variable i\n0 variable j\n\n: i! i ! ;\n: j! j ! ;\n: i@ i @ ;\n: j@ j @ ;\n\n: do immediate ( this needs redoing so it can be nested )\n ' j! ,\n ' i! ,\n here\n;\n\n: not ( a -- ~a )\n if 0 else 1 then\n;\n\n: >= ( a b -- bool )\n < not\n;\n\n: (++i)>=j\n i@ 1+ i! i@ j@ >= \n;\n\n: loop immediate\n ' (++i)>=j ,\n ' ?br ,\n here - ,\n;\n\n: break ( break out of a do ... loop )\n j@ i!\n;\n\n: gcd ( a b -- n ) ( greatest common divisor )\n begin\n dup\n if\n tuck mod 0\n else\n 1\n then\n until\n drop\n;\n\n( =========================================================================== )\n\n\\ : vocabulary create pwd @reg , does> @ pwd !reg ;\n\\ vocabulary forth\n\nfinput ..\/fth\/debug.4th ( Debugging operations )\nfinput ..\/fth\/rational.4th ( Real type )\nfinput ..\/fth\/math.4th ( Math functions )\nfinput ..\/fth\/auto.4th ( Auto generated constants )\nfinput ..\/fth\/memory.4th ( Memory allocation and manipulation )\nfinput ..\/fth\/welcome.4th ( Welcome and cursor control )\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"5240d87bfd2a23b564fc5e9e21a3334aa4774db7","subject":"couple time operations","message":"couple time operations\n","repos":"cooper\/ferret","old_file":"std\/Time.frt","new_file":"std\/Time.frt","new_contents":"class Time 1.0\n\nalias _PO = NATIVE::PerlObject\nload Time::Duration # FIXME\n\n############################\n### DATE COMPONENT TYPES ###\n############################\n\n#> generic type for time components measured from zero\ntype _timeUnitMeasuredFromZero {\n isa Num\n satisfies $_ >= 0\n}\n\n#> generic type for time components measured from one\ntype _timeUnitMeasuredFromOne {\n isa Num\n satisfies $_ >= 1\n}\n\n#> generic type for minutes and seconds\ntype _timeUnit0to59 {\n isa Num\n satisfies $_ >= 0 && $_ <= 59\n}\n\n#> years, starting at year 0\nalias Year = _timeUnitMeasuredFromZero\n\n$months = [\n undefined,\n :January,\n :February,\n :March,\n :April,\n :May,\n :June,\n :July,\n :August,\n :September,\n :October,\n :November,\n :December\n];\n\n#> Month type accepting a month symbol or integer 1-12.\n#| Yields a MonthSym.\ntype Month {\n transform func {\n need $num: Int | MonthSym\n if $num.*isa(Num)\n $num = $months[$num]\n return $num : MonthSym\n }\n}\n\ntype MonthSym {\n isa Sym\n satisfies $months.contains($_)\n}\n\n#> day of the month, 1-31\nalias Day = _timeUnitMeasuredFromOne\n\n$weekdays = [\n undefined,\n :Monday,\n :Tuesday,\n :Wednesday,\n :Thursday,\n :Friday,\n :Saturday,\n :Sunday\n]\n\n#> Weekday type accepting a weekday symbol or integer 1-7, starting with Monday.\n#| Yields a WeekdaySym.\ntype Weekday {\n transform func {\n need $num: Int | WeekdaySym\n if $num.*isa(Num)\n $num = $weekdays[$num]\n return $num : WeekdaySym\n }\n}\n\ntype WeekdaySym {\n isa Sym\n satisfies $weekdays.contains($_)\n}\n\n#> hour 0-23\ntype Hour {\n isa Num\n satisfies $_ >= 0 && $_ <= 23\n}\n\n#> minute 0-59\nalias Minute = _timeUnit0to59\n\n#> second 0-59\nalias Second = _timeUnit0to59\n\n#> nanosecond >= 0\ntype Nanosecond {\n isa Int\n satisfies $_ >= 0\n}\n\n#> creates a new time given date components\ninit {\n want $year: Year\n want $month: Month\n want $day: Day\n want $hour: Hour\n want $minute: Minute\n want $second: Second\n want $nanosecond: Nanosecond\n want $timeZone: Str\n\n _PO.require(\"DateTime\")\n\n # determine args to DateTime constructor\n $args = []\n $possible = [\n year: $year,\n month: $months.indexOf($month),\n day: $day,\n hour: $hour,\n minute: $minute,\n second: $second,\n nanosecond: $nanosecond\n ]\n for ($arg, $val) in $possible {\n if !$val || $val == 0\n next\n $args.push($arg, $val)\n }\n\n # use current time if no options provided\n $init = \"new\"\n if $args.empty\n $init = \"now\"\n\n if $timeZone\n $args.push(\"time_zone\", $timeZone)\n\n # create the underlying DateTime object\n @dt = _PO(\"DateTime\", INIT: $init, args: $args) catch $e\n throw Error(:Bad, \"sorry\")\n\n}\n\n#######################\n### DATE COMPONENTS ###\n#######################\n\n#> year\nprop year {\n return Year(@dt.year!) : Year\n}\n\n#> month\nprop month {\n return Month(@dt.month!) : MonthSym\n}\n\nprop monthName {\n return @month.name\n}\n\n#> day of the month, 1-31\nprop day {\n return Day(@dt.day!) : Day\n}\n\n#> day of the week\nprop weekday {\n return Weekday(@dt.day_of_week!) : WeekdaySym\n}\n\n#> string name of the day of the week\nprop weekdayName {\n return @weekday.name\n}\n\n#################\n### OPERATORS ###\n#################\n\noperator + {\n need $ehs: Duration\n $t = @copy!\n $t.dt.add_duration($ehs.dtd)\n return $t\n}\n\noperator - {\n need $rhs: Duration\n $t = @copy!\n $t.dt.subtract_duration($rhs.dtd)\n return $t\n}\n\n#####################\n### MISCELLANEOUS ###\n#####################\n\nmethod copy {\n $t = Time.now!\n $t.dt = @dt.clone!\n return $t\n}\n\nmethod description {\n return @dt.ymd(\"-\") + \" \" + @dt.hms(\":\")\n}\n\n#> returns the current time\nfunc now {\n return Time()\n}\n\n#> returns a time at the moment the current day started\nfunc today {\n $t = Time()\n $t.dt.truncate(to: \"day\")\n return $t\n}\n\n#> returns a time at the start of tomorrow\nfunc tomorrow {\n return @today! + Duration(days: 1)\n}\n","old_contents":"class Time 1.0\n\nalias _PO = NATIVE::PerlObject\n\n############################\n### DATE COMPONENT TYPES ###\n############################\n\n#> generic type for time components measured from zero\ntype _timeUnitMeasuredFromZero {\n isa Num\n satisfies $_ >= 0\n}\n\n#> generic type for time components measured from one\ntype _timeUnitMeasuredFromOne {\n isa Num\n satisfies $_ >= 1\n}\n\n#> generic type for minutes and seconds\ntype _timeUnit0to59 {\n isa Num\n satisfies $_ >= 0 && $_ <= 59\n}\n\n#> years, starting at year 0\nalias Year = _timeUnitMeasuredFromZero\n\n$months = [\n undefined,\n :January,\n :February,\n :March,\n :April,\n :May,\n :June,\n :July,\n :August,\n :September,\n :October,\n :November,\n :December\n];\n\n#> Month type accepting a month symbol or integer 1-12.\n#| Yields a MonthSym.\ntype Month {\n transform func {\n need $num: Int | MonthSym\n if $num.*isa(Num)\n $num = $months[$num]\n return $num : MonthSym\n }\n}\n\ntype MonthSym {\n isa Sym\n satisfies $months.contains($_)\n}\n\n#> day of the month, 1-31\nalias Day = _timeUnitMeasuredFromOne\n\n$weekdays = [\n undefined,\n :Monday,\n :Tuesday,\n :Wednesday,\n :Thursday,\n :Friday,\n :Saturday,\n :Sunday\n]\n\n#> Weekday type accepting a weekday symbol or integer 1-7, starting with Monday.\n#| Yields a WeekdaySym.\ntype Weekday {\n transform func {\n need $num: Int | WeekdaySym\n if $num.*isa(Num)\n $num = $weekdays[$num]\n return $num : WeekdaySym\n }\n}\n\ntype WeekdaySym {\n isa Sym\n satisfies $weekdays.contains($_)\n}\n\n#> hour 0-23\ntype Hour {\n isa Num\n satisfies $_ >= 0 && $_ <= 23\n}\n\n#> minute 0-59\nalias Minute = _timeUnit0to59\n\n#> second 0-59\nalias Second = _timeUnit0to59\n\n#> nanosecond >= 0\ntype Nanosecond {\n isa Int\n satisfies $_ >= 0\n}\n\n\n\n#> creates a new time given date components\ninit {\n want $year: Year\n want $month: Month\n want $day: Day\n want $hour: Hour\n want $minute: Minute\n want $second: Second\n want $nanosecond: Nanosecond\n\n _PO.require(\"DateTime\")\n\n # determine args to DateTime constructor\n $args = []\n $possible = [\n year: $year,\n month: $months.indexOf($month),\n day: $day,\n hour: $hour,\n minute: $minute,\n second: $second,\n nanosecond: $nanosecond\n ]\n for ($arg, $val) in $possible {\n if !$val || $val == 0\n next\n $args.push($arg, $val)\n }\n\n # use current time if no options provided\n $init = \"new\"\n if $args.empty\n $init = \"now\"\n\n # create the underlying DateTime object\n @dt = _PO(\"DateTime\", INIT: $init, args: $args) catch $e\n throw Error(:Bad, \"sorry\")\n\n # want @locale\n # want @timeZone\n}\n\n#######################\n### DATE COMPONENTS ###\n#######################\n\n#> year\nprop year {\n return Year(@dt.year!) : Year\n}\n\n#> month\nprop month {\n return Month(@dt.month!) : MonthSym\n}\n\nprop monthName {\n return @month.name\n}\n\n#> day of the month, 1-31\nprop day {\n return Day(@dt.day!) : Day\n}\n\n#> day of the week\nprop weekday {\n return Weekday(@dt.day_of_week!) : WeekdaySym\n}\n\n#> string name of the day of the week\nprop weekdayName {\n return @weekday.name\n}\n\n#################\n### OPERATORS ###\n#################\n\n#####################\n### MISCELLANEOUS ###\n#####################\n\nmethod description {\n return @dt.ymd(\"-\") + \" \" + @dt.hms(\":\")\n}\n\n#> returns the current time\nfunc now {\n return Time()\n}\n\n#> returns a time at the moment the current day started\nfunc today {\n $t = Time()\n $t.dt.truncate(to: \"day\")\n return $t\n}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"0e14b6e7368c885e72af3e7c303c07764181e3c7","subject":"Rename to use dashes as language intented.","message":"Rename to use dashes as language intented.\n\nFound the error in my code, I was not properly dropping the choice index on pick-right and\npick-bottom. Now that I've put in the additional-constraints it looks extra hacky and I\nmay go to more consistent looking code instead of needing all these else branches.\n\nFirst pass at additional constraints. Even with them cleared, at some point something\ncorrupts my stack, so I have to look into it.\n","repos":"Tim-Tom\/scratch,Tim-Tom\/scratch,Tim-Tom\/scratch,Tim-Tom\/scratch,Tim-Tom\/scratch,Tim-Tom\/scratch,Tim-Tom\/scratch,Tim-Tom\/scratch,Tim-Tom\/scratch,Tim-Tom\/scratch","old_file":"magic-puzzle\/magic-puzzle.fth","new_file":"magic-puzzle\/magic-puzzle.fth","new_contents":"3 constant width\n21 constant goal\nwidth 1- constant wm\nwidth 1+ constant wp\nwidth width * constant size\n\ncreate choices 3 , 4 , 5 ,\n 6 , 7 , 8 ,\n 9 , 10 , 11 ,\n\nvariable picked size allot\nvariable additional-constraints size allot\n\n: clear-picked\n size\n begin\n 1- dup 0>= while\n dup picked + 0 swap C!\n repeat\n drop ;\n\n: print-picked\n 9 0 do\n i picked + C@ .\n loop ;\n\n\nvariable a size cells allot\n\n: choice-search\n 0\n begin\n dup size < while\n choices over cells + @\n rot tuck = if\n drop -1 exit\n endif\n swap 1+\n repeat\n 2drop 0 ;\n\n: reverse-cross-valid\n 0\n wm wp * wm do\n a i cells + @ +\n wm +loop\n goal = ;\n\n: cross-valid\n 0\n size 0 do\n a i cells + @ +\n wp +loop\n goal = ;\n \n: bottom-row-valid\n 0\n size size width - do\n a i cells + @ +\n loop\n goal = ;\n\n: bottom-right-valid\n bottom-row-valid if\n -1\n else\n cross-valid\n endif ;\n\n0 VALUE pick-next-ref\n\n: execute-predicate?\n dup 0<> if\n execute\n else\n drop -1\n endif ;\n\n: pick-internal\n size 0 do\n dup cells a + choices i cells + @ swap !\n i picked + C@ 0= if\n dup cells additional-constraints + @ execute-predicate? if\n 1 i picked + C!\n dup pick-next-ref execute\n 0 i picked + C!\n endif\n endif\n loop\n drop ;\n\n: pick-right\n 0 over dup dup width mod - do\n a i cells + @ +\n loop\n goal swap - \n over over swap cells a + !\n choice-search if\n dup picked + C@ 0= if\n over cells additional-constraints + @ execute-predicate? if\n 1 over picked + C!\n over pick-next-ref execute\n 0 swap picked + C!\n else\n drop\n endif\n 1 over picked + C!\n over pick-next-ref execute\n 0 swap picked + C!\n else\n drop\n endif\n endif\n drop ;\n\n: pick-bottom\n 0 over dup width mod do\n a i cells + @ +\n width +loop\n goal swap -\n over over swap cells a + !\n choice-search if\n dup picked + C@ 0= if\n over cells additional-constraints + @ execute-predicate? if\n 1 over picked + C!\n over pick-next-ref execute\n 0 swap picked + C!\n else\n drop\n endif\n else\n drop\n endif\n endif\n drop ;\n\ncreate solution-count 0 ,\n\n: solution\n solution-count @ 1+ dup solution-count !\n .\" --- Solution \" . .\" ---\" CR\n size 0 do\n a i cells + @ .\n i 3 mod 2 = if CR endif\n loop ;\n\n: print-right-internal\n dup width mod wm = if\n .\" pick-right \" .\n else\n .\" pick-internal \" .\n endif ;\n\n: print-next\n dup . .\" -> \"\n dup size 1- = if\n drop .\" solution\"\n else\n dup width wm * >= if\n wm -\n print-right-internal\n else\n dup width dup 2 - * >= if\n width +\n .\" pick-bottom \" .\n else\n 1+\n print-right-internal\n endif\n endif\n endif ;\n\n: pick-right-internal\n dup width mod wm = if\n pick-right\n else\n pick-internal\n endif ;\n\n: pick-next\n dup size 1- = if\n drop solution\n else\n dup width wm * >= if\n wm -\n pick-right-internal\n else\n dup width dup 2 - * >= if\n width +\n pick-bottom\n else\n 1+\n pick-right-internal\n endif\n endif\n endif ;\n\n' pick-next TO pick-next-ref\n\n: init-board\n size 0 do\n i 1+ a i cells + !\n loop ;\n\n: clear-constraints\n size 0 do\n 0 additional-constraints i cells + !\n loop ;\n\n\nclear-constraints\n' reverse-cross-valid additional-constraints size width - width - 1+ cells + !\n' bottom-right-valid additional-constraints size 1- cells + !\n\n: solve-puzzle\n clear-picked init-board 0 solution-count !\n 0 pick-internal ;\n","old_contents":"3 constant width\n21 constant goal\nwidth 1- constant wm\nwidth 1+ constant wp\nwidth width * constant size\n\ncreate choices 3 , 4 , 5 ,\n 6 , 7 , 8 ,\n 9 , 10 , 11 ,\n\nvariable picked size allot\n\n: clearPicked\n size\n begin\n 1- dup 0>= while\n dup picked + 0 swap C!\n repeat\n drop ;\n\nvariable a size cells allot\n\n: choiceSearch\n 0\n begin\n dup size < while\n choices over cells + @\n rot tuck = if\n drop -1 exit\n endif\n swap 1+\n repeat\n 2drop 0 ;\n\n: reverseCrossInvalid\n 0\n wm wp * wm do\n a i cells + @ +\n wm +loop\n goal = ;\n\n: crossInvalid\n 0\n size 0 do\n a i cells + @ +\n wp +loop\n goal = ;\n \n: bottomRowInvalid\n 0\n size size width - do\n a i cells + @ +\n loop\n goal = ;\n\n: bottomRightInvalid\n bottomRowInvalid if\n -1\n else\n crossInvalid\n endif ;\n\n0 VALUE pickNextRef\n\n: pickInternal\n size 0 do\n dup cells a + choices i cells + @ swap !\n i picked + C@ 0= if\n 1 i picked + C!\n dup pickNextRef execute\n 0 i picked + C!\n endif\n loop\n drop ;\n\n: pickRight\n 0 over dup dup width mod - do\n a i cells + @ +\n loop\n goal swap - \n over over swap cells a + !\n choiceSearch if\n dup picked + C@ 0= if\n 1 over picked + C!\n over pickNextRef execute\n 0 swap picked + C!\n endif\n endif\n drop ;\n\n: pickBottom\n 0 over dup width mod do\n a i cells + @ +\n width +loop\n goal swap -\n over over swap cells a + !\n choiceSearch if\n dup picked + C@ 0= if\n 1 over picked + C!\n over pickNextRef execute\n 0 swap picked + C!\n endif\n endif\n drop ;\n\ncreate solution_count 0 ,\n\n: solution\n solution_count @ 1+ dup solution_count !\n .\" --- Solution \" . .\" ---\" CR\n size 0 do\n a i cells + @ .\n i 3 mod 2 = if CR endif\n loop ;\n\n: pickNext\n dup .\" pickNext \" .\n dup size 1- = if\n drop .\" -> solution\" CR solution exit\n endif\n dup width wm * >= if\n wm -\n else\n dup width dup 2 - * >= if\n width + .\" -> pickBottom \" dup . CR pickBottom exit\n else\n 1+\n endif\n endif\n dup width mod wm = if\n .\" -> pickRight \" dup . CR pickRight\n else\n .\" -> pickInternal \" dup . CR pickInternal\n endif ;\n\n' pickNext TO pickNextRef\n\n: initBoard\n 9 0 do\n i 1+ a i cells + !\n loop ;\n\n: solve-puzzle\n clearPicked initBoard 0 solution_count !\n 0 pickInternal ;\n","returncode":0,"stderr":"","license":"unlicense","lang":"Forth"} {"commit":"26c5ab7ac97983284974e36c6eaf66d72bae1a93","subject":"time: reduce time-advance","message":"time: reduce time-advance\n\nMakes editing more responsive.\nWe don't need such high latency these days.\n","repos":"philburk\/hmsl,philburk\/hmsl,philburk\/hmsl","old_file":"hmsl\/fth\/time.fth","new_file":"hmsl\/fth\/time.fth","new_contents":"\\ Device independant TIME handling.\n\\ These words are vectored to allow a composer to change the notion\n\\ of time in HMSL.\n\\\n\\ Author: Phil Burk\n\\ Copyright 1986 - Phil Burk, Larry Polansky, David Rosenboom.\n\\ All Rights Reserved\n\\\n\\ MOD: PLB 10\/14\/87 Added calls to HARD.TIME.INIT and TERM\n\\ MOD: PLB 11\/16\/89 Add RATE->MICS\/BEAT\n\\ MOD: PLB 11\/17\/89 Big changes.\n\\ Removed TIME-BASE HARD.TIME@ SOFT.TIME@ .\n\\ TIME@ TIME! and TIME+! are now deferred!!\n\\ Default is ahead.time , time-advance set to zero.\n\\ MOD: PLB 2\/9\/90 Added VTIME.SAVE stuff from SES\n\\ MOD: PLB 3\/18\/90 Add DELAY\n\\ MOD: PLB 4\/13\/90 Change AO.REPEAT to SELF.CLOCK\n\\ MOD: PLB 6\/7\/90 Fixed Stack for delay.\n\\ MOD: PLB 1\/2\/91 Changed DELAY , no abort, BUMPS vtime with MAX\n\\ MOD: PLB 2\/7\/91 Set defaults for TIME@ TIME! and TIME+!\n\\ MOD: PLB 4\/9\/91 Set default for TIME@ to FALSE\n\\ MOD: PLB 7\/1\/91 Comment out SYS.INIT so that MIDI can INIT when ready.\n\\ MOD: PLB 2\/18\/92 Add SYS.TASK\n\nANEW TASK-TIME\n\ndefer TIME@\n' false is time@\ndefer TIME!\n' drop is time!\ndefer TIME+!\n' drop is time+!\n\n: TIME+1 ( -- , used by software clocks )\n 1 time+!\n;\n\n\\ This word is used to decide if it's time for an event.\n\\ It compares the time on the stack to the current time.\nmax-inline @ 12 max-inline !\n: TIME> ( time1 time2 -- flag , use circular number system )\n - 0> both\n;\n: TIME< ( time1 time2 -- flag )\n - 0< both\n;\nmax-inline !\n\n: DOITNOW? ( atime -- flag , true if time is now or past)\n dup time-virtual !\n time@ time> not ( careful with changing this word, subtle )\n;\n\n: VTIME@ ( -- virtual_time )\n time-virtual @\n;\n\n: VTIME! ( virtual_time -- )\n time-virtual !\n;\n\n: VTIME+! ( N -- )\n time-virtual +!\n;\n\n: AHEAD.TIME@ ( -- time , give time ahead of RTC )\n rtc.time@ time-advance @ +\n;\n\n: AHEAD.TIME! ( time -- , set ahead time )\n time-advance @ - 0 max rtc.time!\n;\n\n: ANOW ( -- , set virtual time to be advance time )\n time@ vtime!\n;\n\n: RNOW ( -- , set virtual time to be real time )\n rtc.time@ vtime!\n;\n\n\\ Reserve for self incrementing clock.\ndefer SELF.CLOCK ( function to call each cycle of HMSL scheduler)\n\n: USE.SELF.TIMER ( -- , advance time as HMSL scans )\n rtc.stop\n 'c time+1 is self.clock\n;\n\n: USE.HARDWARE.TIMER ( -- , Use HARDWARE timer )\n rtc.start\n 'c noop is self.clock\n;\n\n: USE.SOFTWARE.TIMER ( -- , Use SOFTWARE timer )\n rtc.stop\n 'c noop is self.clock\n;\n\n: 0TIME ( -- zero out timer variables )\n 0 rtc.time!\n 0 time-virtual !\n;\n\n32 constant VTIME_SMAX\nCREATE VTIME-DATA vtime_smax cell* allot\n\nstack.header vtime-stack\n\n: VTIME.PUSH ( vtime -- , push onto time stack )\n vtime-stack stack.push\n;\n: VTIME.POP ( -- vtime )\n vtime-stack stack.pop\n;\n\n: VTIME.SAVE ( -- , save current virtual time , PUSH)\n vtime@ vtime.push\n;\n: VTIME.RESTORE ( -- , restore from stack , POP)\n vtime.pop vtime!\n;\n\n: VTIME.COPY ( -- , copy from vtime stack , COPY)\n vtime-stack stack.copy vtime!\n;\n: VTIME.DROP ( -- , drop from vtime stack )\n vtime-stack stack.drop\n;\n\n: TIME.INIT ( -- , initialize vectors )\n \" TIME.INIT\" debug.type\n 0 time-current !\n rtc.init\n 'c ahead.time! is time!\n 'c ahead.time@ is time@\n 'c rtc.time+! is time+!\n 'c noop is self.clock\n rtc.rate@ 6 \/ time-advance !\n rtc.rate@ 2* 3 \/ ticks\/beat !\n anow\n vtime-data vtime_smax vtime-stack stack.setup\n;\n\n: TIME.TERM ( -- )\n \" TIME.TERM\" debug.type\n rtc.term\n;\n\n: SYS.INIT sys.init time.init ;\n: SYS.TERM time.term sys.term ;\n\n: WATCH ( -- )\n BEGIN\n time@ . cr\n ?terminal\n UNTIL\n;\n\n: RATE->MICS\/BEAT ( ticks\/second -- microseconds\/beat )\n >r ticks\/beat @ 1000000 r> *\/\n;\n\n: DELAY ( ticks -- , delay N ticks and advance VTIME )\n\\ force VTIME to be N past now\n dup vtime@ rtc.time@ max + vtime!\n time@ +\n BEGIN dup time@ time<\n UNTIL drop\n;\n\n\n: ?DELAY { ticks | flag -- flag , delay N ticks and advance VTIME }\n\\ force VTIME to be N past now\n ticks vtime@ rtc.time@ max + vtime!\n ticks time@ +\n BEGIN dup time@ time<\n ?terminal dup -> flag\n OR\n UNTIL\n drop\n flag\n;\n\n: SYS.TASK sys.task self.clock ;\n\n","old_contents":"\\ Device independant TIME handling.\n\\ These words are vectored to allow a composer to change the notion\n\\ of time in HMSL.\n\\\n\\ Author: Phil Burk\n\\ Copyright 1986 - Phil Burk, Larry Polansky, David Rosenboom.\n\\ All Rights Reserved\n\\\n\\ MOD: PLB 10\/14\/87 Added calls to HARD.TIME.INIT and TERM\n\\ MOD: PLB 11\/16\/89 Add RATE->MICS\/BEAT\n\\ MOD: PLB 11\/17\/89 Big changes.\n\\ Removed TIME-BASE HARD.TIME@ SOFT.TIME@ .\n\\ TIME@ TIME! and TIME+! are now deferred!!\n\\ Default is ahead.time , time-advance set to zero.\n\\ MOD: PLB 2\/9\/90 Added VTIME.SAVE stuff from SES\n\\ MOD: PLB 3\/18\/90 Add DELAY\n\\ MOD: PLB 4\/13\/90 Change AO.REPEAT to SELF.CLOCK\n\\ MOD: PLB 6\/7\/90 Fixed Stack for delay.\n\\ MOD: PLB 1\/2\/91 Changed DELAY , no abort, BUMPS vtime with MAX\n\\ MOD: PLB 2\/7\/91 Set defaults for TIME@ TIME! and TIME+!\n\\ MOD: PLB 4\/9\/91 Set default for TIME@ to FALSE\n\\ MOD: PLB 7\/1\/91 Comment out SYS.INIT so that MIDI can INIT when ready.\n\\ MOD: PLB 2\/18\/92 Add SYS.TASK\n\nANEW TASK-TIME\n\ndefer TIME@\n' false is time@\ndefer TIME!\n' drop is time!\ndefer TIME+!\n' drop is time+!\n\n: TIME+1 ( -- , used by software clocks )\n 1 time+!\n;\n\n\\ This word is used to decide if it's time for an event.\n\\ It compares the time on the stack to the current time.\nmax-inline @ 12 max-inline !\n: TIME> ( time1 time2 -- flag , use circular number system )\n - 0> both\n;\n: TIME< ( time1 time2 -- flag )\n - 0< both\n;\nmax-inline !\n\n: DOITNOW? ( atime -- flag , true if time is now or past)\n dup time-virtual !\n time@ time> not ( careful with changing this word, subtle )\n;\n\n: VTIME@ ( -- virtual_time )\n time-virtual @\n;\n\n: VTIME! ( virtual_time -- )\n time-virtual !\n;\n\n: VTIME+! ( N -- )\n time-virtual +!\n;\n\n: AHEAD.TIME@ ( -- time , give time ahead of RTC )\n rtc.time@ time-advance @ +\n;\n\n: AHEAD.TIME! ( time -- , set ahead time )\n time-advance @ - 0 max rtc.time!\n;\n\n: ANOW ( -- , set virtual time to be advance time )\n time@ vtime!\n;\n\n: RNOW ( -- , set virtual time to be real time )\n rtc.time@ vtime!\n;\n\n\\ Reserve for self incrementing clock.\ndefer SELF.CLOCK ( function to call each cycle of HMSL scheduler)\n\n: USE.SELF.TIMER ( -- , advance time as HMSL scans )\n rtc.stop\n 'c time+1 is self.clock\n;\n\n: USE.HARDWARE.TIMER ( -- , Use HARDWARE timer )\n rtc.start\n 'c noop is self.clock\n;\n\n: USE.SOFTWARE.TIMER ( -- , Use SOFTWARE timer )\n rtc.stop\n 'c noop is self.clock\n;\n\n: 0TIME ( -- zero out timer variables )\n 0 rtc.time!\n 0 time-virtual !\n;\n\n32 constant VTIME_SMAX\nCREATE VTIME-DATA vtime_smax cell* allot\n\nstack.header vtime-stack\n\n: VTIME.PUSH ( vtime -- , push onto time stack )\n vtime-stack stack.push\n;\n: VTIME.POP ( -- vtime )\n vtime-stack stack.pop\n;\n\n: VTIME.SAVE ( -- , save current virtual time , PUSH)\n vtime@ vtime.push\n;\n: VTIME.RESTORE ( -- , restore from stack , POP)\n vtime.pop vtime!\n;\n\n: VTIME.COPY ( -- , copy from vtime stack , COPY)\n vtime-stack stack.copy vtime!\n;\n: VTIME.DROP ( -- , drop from vtime stack )\n vtime-stack stack.drop\n;\n\n: TIME.INIT ( -- , initialize vectors )\n \" TIME.INIT\" debug.type\n 0 time-current !\n rtc.init\n 'c ahead.time! is time!\n 'c ahead.time@ is time@\n 'c rtc.time+! is time+!\n 'c noop is self.clock\n rtc.rate@ time-advance !\n rtc.rate@ 2* 3 \/ ticks\/beat !\n anow\n vtime-data vtime_smax vtime-stack stack.setup\n;\n\n: TIME.TERM ( -- )\n \" TIME.TERM\" debug.type\n rtc.term\n;\n\n: SYS.INIT sys.init time.init ;\n: SYS.TERM time.term sys.term ;\n\n: WATCH ( -- )\n BEGIN\n time@ . cr\n ?terminal\n UNTIL\n;\n\n: RATE->MICS\/BEAT ( ticks\/second -- microseconds\/beat )\n >r ticks\/beat @ 1000000 r> *\/\n;\n\n: DELAY ( ticks -- , delay N ticks and advance VTIME )\n\\ force VTIME to be N past now\n dup vtime@ rtc.time@ max + vtime!\n time@ +\n BEGIN dup time@ time<\n UNTIL drop\n;\n\n\n: ?DELAY { ticks | flag -- flag , delay N ticks and advance VTIME }\n\\ force VTIME to be N past now\n ticks vtime@ rtc.time@ max + vtime!\n ticks time@ +\n BEGIN dup time@ time<\n ?terminal dup -> flag\n OR\n UNTIL\n drop\n flag\n;\n\n: SYS.TASK sys.task self.clock ;\n\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Forth"} {"commit":"bf419dd16a38c5ffcdefe48ba344212b71e4088f","subject":"Words for user page data retrieval.","message":"Words for user page data retrieval.","repos":"rbsexton\/gecko,rbsexton\/gecko,rbsexton\/gecko","old_file":"zero\/clock-umb\/forth\/Clock.fth","new_file":"zero\/clock-umb\/forth\/Clock.fth","new_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( -- )\n load-defaults \n icroot 0 over inter.rtcsem ! \\ Reset the free-running counters.\n 0 over inter.rtcdsem ! \\ Reset the free-running counters.\n\n begin \n \tdup inter.rtcsem @offex! ?dup if advancehms then\n \tdup inter.rtcdsem @offex! ?dup if advancedhms then\n [asm wfi asm]\n uiupdate if use-uivals else use-clockvals then \n key? until drop\n;\n \n\\ These two contain loops to ensure that we don't\n\\ drop any timer ticks on the floor.\n: ADVANCEHMS ( n -- ) 0 do hms advancetime loop ;\n: ADVANCEDHMS ( n -- ) 0 do dhms advancetime loop ;\n \n: LOAD-DEFAULTS ( -- )\n #1000 needlemax\n 2dup ! 4 + 2dup ! 4 + ! \n interp-init\n;\n\n\\ ----------------------------------------------------------\n\\ Define the structures before they get used.\n\\ ----------------------------------------------------------\nstruct ODN \\ On-Deck Needle \n\t2 field odn.s\n\t2 field odn.m\n\t2 field odn.h\nend-struct\n\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxsec \\ Max Value for secs+minutes\n\tint hms.maxhour \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_m \\ increment the minutes + hours\nend-struct\n\nstruct _interp_set\n\t4 cells field interp.a\n\t4 cells field interp.b\n\t4 cells field interp.c\nend-struct\n\n\\ ----------------------------------------------------------\n\\ Defaults get saved in the user data page.\n\\ ----------------------------------------------------------\n\n: NVRAMVALID? ( addr -- t\/f ) \n\\ *G See if there is valid data in the NVRAM.\n\\ ** It consists of 3 words. If any of them are \n\\ ** set to 0xffff:ffff, we go with the defaults.\n dup @ -1 = \n over 4 + @ -1 = or\n swap 8 + @ -1 = or \n;\n\n: NVRAMLOAD ( addr -- ) $C 0 do dup I + @ needle_max I + ! 4 + loop ; \n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nidata\ncreate ODN_HMS odn allot \\ On-Deck, HMS\ncreate ODN_DHMS odn allot \\ On-Deck, DHMS\ncreate ODN_UI odn allot \\ On-Deck, Generated by the UI.\ncdata\n\nidata\ncreate NEEDLE_MAX #850 , #850 , #850 ,\ncdata\n\n\n: rangecheck ( max n -- n or zero ) dup >R <= if R> drop 0 else R> then ; \n\n: ++NEEDLE_S \\ Called every time.\n odn_hms odn.s \\ Stash this address for the moment. \n\n\tneedle_max odn.s @ \\ Get the max \n\tover w@ \\ Current value \n\n\tinterp_hms interp.a interp-next + \\ Returns a value.\n\t\n\t\\ If we've wrapped to zero, reset the interpolator \n\t\\ so that we don't accumulate errors during setting\/\n\t\\ calibration operations.\n rangecheck dup 0= if interp_hms interp.a interp-reset then \t\t\n\tswap w! \n\t;\n\n: ++NEEDLE_DS ; \\ Called every time.\n\n: ++NEEDLE_M ; \\ Every time we roll the seconds.\n: ++NEEDLE_DM ; \\ Every time we roll the seconds.\n\n: _USE ( odn-addr -- ) \n dup w@ pwm0!\n dup 2 + w@ pwm1!\n 4 + w@ pwm2!\n ;\n\n: USE-CLOCKVALS odn_hms _use ; \n: USE-UIVALS odn_ui _use ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Quadrature\n\\ ----------------------------------------------------------\n\n: QUAD@ ( addr -- n ) \\ Fetch and zero\n @off [asm sxth tos, tos asm] ;\n \n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_ds , ' ++needle_dm , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n: ADVANCETIME ( struct-addr -- )\n dup hms.w_s @ execute \\ Invoke the official update word.\n 1 over hms.subsec +! \\ Increment\n dup hms.subsec @\n over hms.maxsubsec @ < if drop exit then \\ If less then max, we're done\n 0 over hms.subsec ! \\ Reset the subsecs \n\n dup hms.w_m @ execute\n 1 over hms.s +!\n dup hms.s @ over hms.maxsec @ < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n 1 over hms.m +!\n dup hms.m @ over hms.maxsec @ < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ over hms.maxhour @ < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ----------------------------------------------------------\n\\ The interpolator. \n\\ Implement bresenhams algorithm. All of this code already\n\\ exists in C, but we'll own the data structures. They contain\n\\ A total of 4 words - fixed, err, num, & denom\n\\ ----------------------------------------------------------\nudata \ncreate interp_hms _interp_set allot\ncreate interp_dhms _interp_set allot \ncreate adj_list #50 cells allot \\ 100 16-bit words. \ncdata\n\n\\ Heres the default values. These are universal.\nidata\ncreate interp_max #850 , #850 , #850 ,\ncdata\n\n#16 #60 * equ raw_sec\n#10 #100 * equ raw_dsec\n\n: INTERP-INIT ( -- )\n (interp_init) interp_hms\n 2dup interp.a interp_max @ raw_sec call3-- \n 2dup interp.b interp_max 4 + @ #60 call3-- \n interp.c interp_max 8 + @ #12 call3--\n\n (interp_init) interp_dhms\n 2dup interp.a interp_max @ raw_dsec call3-- \n 2dup interp.b interp_max 4 + @ #100 call3-- \n interp.c interp_max 8 + @ #10 call3--\n;\n\n\\ Call the reset fn.\n: INTERP-RESET ( interp_addr -- )\n (interp_reset) swap call1-- \n;\n\n: INTERP-NEXT ( addr -- n )\n (interp_next) swap call1--n\n;\n\n\n\\ ============================ UNTESTED =======================\n\\ VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n\n\\ ----------------------------------------------------------\n\\ User Interface\n\\ ----------------------------------------------------------\nvariable uistate\nvariable uicount \n\n_GPIO $64 + equ _BUTTONIO\n: BUTTONUP? ( -- t\/f ) _buttonio @ 1 and ; \n: BUTTONDOWN? ( -- t\/f ) buttonup? 1 or ; \n\n\\ The wrapper for all of the UI stuff.\n\\ Returns true if the UI is active - ie, use the values generated by the UI.\n: UIUPDATE ( -- t\/f )\n StateHandlers uistate @ + @ execute \n; \n\n\\ -----------------------------------------------\n\\ State numbers. These are defined x4 so that\n\\ we can just use the state number as an index \n\\ into a table of words.\n\\ -----------------------------------------------\n0 4 * equ _s_init\n1 4 * equ _s_b1\n2 4 * equ _s_1sec\n3 4 * equ _s_seth\n4 4 * equ _s_pendset_m\n5 4 * equ _s_setmin\n6 4 * equ _s_pendcal0\n7 4 * equ _s_cal0\n8 4 * equ _s_pendcalh\n9 4 * equ _s_calh\n10 4 * equ _s_pendcalm\n11 4 * equ _s_calm\n12 4 * equ _s_pendcals\n13 4 * equ _s_cals\n\n\\ All of the state handlers.\n\\ Everybody needs to know the state of the button, so that must\n\\ get passed in, thus they all look like this:\n\\ state ( t\/f -- t\/f )\n: shInit false \n buttondown? if \n _s_b1 uistate !\n uicount off \\ Reset this.\n then\n ;\n\n\\ Waiting for a full second to go by.\n: shB1 false\n buttonup? if _s_init uistate ! exit then\n \\ The Button is down. \n uicount @ 16 > if\n _s_1sec uistate !\n else \n 1 uicount +!\n\tthen\n ;\n\n\\ We're in the 1 second state\n: sh1sec true \n buttonup? if _s_seth uistate ! true exit then\n uicount @ 48 > if\n _s_pendcal0 uistate !\n else \n 1 uicount +!\n\tthen \n;\n\n\\ -------------------------------------------------\n\\ Setting the time\n\\ -------------------------------------------------\n: shSetH true buttondown? if _s_pendset_m uistate ! exit then ;\n\n: shPendSetM true buttonup? if _s_setmin uistate ! then ;\n: shSetMin true buttondown? if _s_pendset_m uistate ! exit then ;\n\n\\ -------------------------------------------------\n\\ Calibration\n\\ -------------------------------------------------\n: shPendCal0 true buttonup? if _s_cal0 uistate ! then ;\n: shCal0 true buttondown? if _s_pendcalh uistate ! exit then ;\n\n: shPendCalH true buttonup? if _s_calh uistate ! then ; \n: shCalH true buttondown? if _s_pendcalm uistate ! exit then ; \n\n: shPendCalM true buttonup? if _s_calm uistate ! then ; \n: shCalM true buttondown? if _s_pendcals uistate ! exit then ; \n\n: shPendCalS true buttonup? if _s_calm uistate ! then ; \n: shCalS true buttondown? if _s_init uistate ! exit then ; \n\ncreate StateHandlers \n' shInit , \n' shB1 ,\n' sh1sec ,\n' shSetH ,\n' shPendSetM , ' shSetMin ,\n\n' shPendCal0 , ' shCal0 ,\n' shPendCalH , ' shCalH , \n' shPendCalM , ' shCalM , \n' shPendCalS , ' shCalS , \n\n","old_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( -- )\n load-defaults \n icroot 0 over inter.rtcsem ! \\ Reset the free-running counters.\n 0 over inter.rtcdsem ! \\ Reset the free-running counters.\n\n begin \n \tdup inter.rtcsem @offex! ?dup if advancehms then\n \tdup inter.rtcdsem @offex! ?dup if advancedhms then\n [asm wfi asm]\n uiupdate if use-uivals else use-clockvals then \n key? until drop\n;\n \n\\ These two contain loops to ensure that we don't\n\\ drop any timer ticks on the floor.\n: ADVANCEHMS ( n -- ) 0 do hms advancetime loop ;\n: ADVANCEDHMS ( n -- ) 0 do dhms advancetime loop ;\n \n: LOAD-DEFAULTS ( -- )\n #1000 needlemax\n 2dup ! 4 + 2dup ! 4 + ! \n interp-init\n;\n\n\\ ----------------------------------------------------------\n\\ Define the structures before they get used.\n\\ ----------------------------------------------------------\nstruct ODN \\ On-Deck Needle \n\t2 field odn.s\n\t2 field odn.m\n\t2 field odn.h\nend-struct\n\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxsec \\ Max Value for secs+minutes\n\tint hms.maxhour \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_m \\ increment the minutes + hours\nend-struct\n\nstruct _interp_set\n\t4 cells field interp.a\n\t4 cells field interp.b\n\t4 cells field interp.c\nend-struct\n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nidata\ncreate NEEDLEMAX 3 cells allot\ncreate ODN_HMS odn allot \\ On-Deck, HMS\ncreate ODN_DHMS odn allot \\ On-Deck, DHMS\ncreate ODN_UI odn allot \\ On-Deck, Generated by the UI.\ncdata\n\n: rangecheck ( max n -- n or zero ) dup >R <= if R> drop 0 else R> then ; \n\n: ++NEEDLE_S \\ Called every time.\n odn_hms odn.s \\ Stash this address for the moment. \n\n\tinterp_max odn.s @ \\ Get the max \n\tover w@ \\ Current value \n\n\tinterp_hms interp.a interp-next + \\ Returns a value.\n\t\n\t\\ If we've wrapped to zero, reset the interpolator \n\t\\ so that we don't accumulate errors during setting\/\n\t\\ calibration operations.\n rangecheck dup 0= if interp_hms interp.a interp-reset then \t\t\n\tswap w! \n\t;\n\n: ++NEEDLE_DS ; \\ Called every time.\n\n: ++NEEDLE_M ; \\ Every time we roll the seconds.\n: ++NEEDLE_DM ; \\ Every time we roll the seconds.\n\n: _USE ( odn-addr -- ) \n dup w@ pwm0!\n dup 2 + w@ pwm1!\n 4 + w@ pwm2!\n ;\n\n: USE-CLOCKVALS odn_hms _use ; \n: USE-UIVALS odn_ui _use ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Quadrature\n\\ ----------------------------------------------------------\n\n: QUAD@ ( addr -- n ) \\ Fetch and zero\n @off [asm sxth tos, tos asm] ;\n \n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_ds , ' ++needle_dm , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n: ADVANCETIME ( struct-addr -- )\n dup hms.w_s @ execute \\ Invoke the official update word.\n 1 over hms.subsec +! \\ Increment\n dup hms.subsec @\n over hms.maxsubsec @ < if drop exit then \\ If less then max, we're done\n 0 over hms.subsec ! \\ Reset the subsecs \n\n dup hms.w_m @ execute\n 1 over hms.s +!\n dup hms.s @ over hms.maxsec @ < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n 1 over hms.m +!\n dup hms.m @ over hms.maxsec @ < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ over hms.maxhour @ < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ----------------------------------------------------------\n\\ The interpolator. \n\\ Implement bresenhams algorithm. All of this code already\n\\ exists in C, but we'll own the data structures. They contain\n\\ A total of 4 words - fixed, err, num, & denom\n\\ ----------------------------------------------------------\nudata \ncreate interp_hms _interp_set allot\ncreate interp_dhms _interp_set allot \ncreate adj_list #50 cells allot \\ 100 16-bit words. \ncdata\n\n\\ Heres the default values. These are universal.\nidata\ncreate interp_max #850 , #850 , #850 ,\ncdata\n\n#16 #60 * equ raw_sec\n#10 #100 * equ raw_dsec\n\n: INTERP-INIT ( -- )\n (interp_init) interp_hms\n 2dup interp.a interp_max @ raw_sec call3-- \n 2dup interp.b interp_max 4 + @ #60 call3-- \n interp.c interp_max 8 + @ #12 call3--\n\n (interp_init) interp_dhms\n 2dup interp.a interp_max @ raw_dsec call3-- \n 2dup interp.b interp_max 4 + @ #100 call3-- \n interp.c interp_max 8 + @ #10 call3--\n;\n\n\\ Call the reset fn.\n: INTERP-RESET ( interp_addr -- )\n (interp_reset) swap call1-- \n;\n\n: INTERP-NEXT ( addr -- n )\n (interp_next) swap call1--n\n;\n\n\n\\ ============================ UNTESTED =======================\n\\ VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n\n\\ ----------------------------------------------------------\n\\ User Interface\n\\ ----------------------------------------------------------\nvariable uistate\nvariable uicount \n\n_GPIO $64 + equ _BUTTONIO\n: BUTTONUP? ( -- t\/f ) _buttonio @ 1 and ; \n: BUTTONDOWN? ( -- t\/f ) buttonup? 1 or ; \n\n\\ The wrapper for all of the UI stuff.\n\\ Returns true if the UI is active - ie, use the values generated by the UI.\n: UIUPDATE ( -- t\/f )\n StateHandlers uistate @ + @ execute \n; \n\n\\ -----------------------------------------------\n\\ State numbers. These are defined x4 so that\n\\ we can just use the state number as an index \n\\ into a table of words.\n\\ -----------------------------------------------\n0 4 * equ _s_init\n1 4 * equ _s_b1\n2 4 * equ _s_1sec\n3 4 * equ _s_seth\n4 4 * equ _s_pendset_m\n5 4 * equ _s_setmin\n6 4 * equ _s_pendcal0\n7 4 * equ _s_cal0\n8 4 * equ _s_pendcalh\n9 4 * equ _s_calh\n10 4 * equ _s_pendcalm\n11 4 * equ _s_calm\n12 4 * equ _s_pendcals\n13 4 * equ _s_cals\n\n\\ All of the state handlers.\n\\ Everybody needs to know the state of the button, so that must\n\\ get passed in, thus they all look like this:\n\\ state ( t\/f -- t\/f )\n: shInit false \n buttondown? if \n _s_b1 uistate !\n uicount off \\ Reset this.\n then\n ;\n\n\\ Waiting for a full second to go by.\n: shB1 false\n buttonup? if _s_init uistate ! exit then\n \\ The Button is down. \n uicount @ 16 > if\n _s_1sec uistate !\n else \n 1 uicount +!\n\tthen\n ;\n\n\\ We're in the 1 second state\n: sh1sec true \n buttonup? if _s_seth uistate ! true exit then\n uicount @ 48 > if\n _s_pendcal0 uistate !\n else \n 1 uicount +!\n\tthen \n;\n\n\\ -------------------------------------------------\n\\ Setting the time\n\\ -------------------------------------------------\n: shSetH true buttondown? if _s_pendset_m uistate ! exit then ;\n\n: shPendSetM true buttonup? if _s_setmin uistate ! then ;\n: shSetMin true buttondown? if _s_pendset_m uistate ! exit then ;\n\n\\ -------------------------------------------------\n\\ Calibration\n\\ -------------------------------------------------\n: shPendCal0 true buttonup? if _s_cal0 uistate ! then ;\n: shCal0 true buttondown? if _s_pendcalh uistate ! exit then ;\n\n: shPendCalH true buttonup? if _s_calh uistate ! then ; \n: shCalH true buttondown? if _s_pendcalm uistate ! exit then ; \n\n: shPendCalM true buttonup? if _s_calm uistate ! then ; \n: shCalM true buttondown? if _s_pendcals uistate ! exit then ; \n\n: shPendCalS true buttonup? if _s_calm uistate ! then ; \n: shCalS true buttondown? if _s_init uistate ! exit then ; \n\ncreate StateHandlers \n' shInit , \n' shB1 ,\n' sh1sec ,\n' shSetH ,\n' shPendSetM , ' shSetMin ,\n\n' shPendCal0 , ' shCal0 ,\n' shPendCalH , ' shCalH , \n' shPendCalM , ' shCalM , \n' shPendCalS , ' shCalS , \n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"f98d003a8427ba845e03a2a7173fd6087af2d6a7","subject":"DEC2BIN fixed (working! )","message":"DEC2BIN fixed (working! )\n","repos":"bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas","old_file":"KataDiversion.fth","new_file":"KataDiversion.fth","new_contents":"\\ KataDiversion in Forth\n\n\\ -- utils\n\n\\ empty the stack\n: EMPTY\n DEPTH 0 <> IF BEGIN\n DROP DEPTH 0 =\n UNTIL\n THEN ;\n\n\\ power\n: ** ( n1 n2 -- n1_pow_n2 ) 1 SWAP ?DUP IF 0 DO OVER * LOOP THEN NIP ;\n\n\\ test if the top is a negative number\n: ?NEG ( n -- bool ) DUP 0= IF -1 ELSE DUP ABS <> THEN ;\n\n\\ log2 (integer)\n: LOG2 ( n -- log2_n ) DUP 1 < IF 1 ABORT\" Log2 need a positive value.\"\n ELSE DUP 1 = IF 0\n ELSE\n 1 >R\n BEGIN ( n |R: i=1)\n DUP DUP 2 I ** - 2 *\n ( n n 2*[n-2**i])\n R> 1 + >R ( \u2026 |R: i+1)\n > ( n n>2*[n-2**i] )\n UNTIL\n R> 1 -\n THEN\n THEN NIP ;\n\n\\ decimal to binary\n\\ e.g. : ( 11 -- 1 0 1 1 )\n: DEC2BIN ( n -- n1 n2 n3 \u2026 ) DUP DUP 0 <> IF\n LOG2 2 SWAP ** >R ( n |R: X=2 ** n.log2 )\n BEGIN\n DUP I - 0 >= IF 1 SWAP I - ( 1 n-X )\n ELSE 0 SWAP ( 0 n )\n THEN\n I 1 =\n R> 2 \/ >R ( \u2026 | X\/2 )\n UNTIL\n R> 2DROP\n THEN\n ;\n\n\\ -- kata\n\n\\ test if the given N has two adjacent 1 bits\n\\ e.g. : 1011 -> -1\n\\ 1001 -> 0\n: ?TWO-ADJACENT-1-BITS ( n -- bool ) ( TODO ) ;\n\n\\ return the maximum number which can be made with N (given number) bits\n: ?MAX-NB ( n -- m ) DUP ?NEG IF DROP 0 ( 0 )\n ELSE \n DUP IF DUP 2 SWAP ** NIP ( 2**n )\n THEN\n THEN ;\n\n\n\\ return the number of numbers which can be made with N (given number) bits\n\\ or less, and which have not two adjacent 1 bits.\n\\ see http:\/\/www.codekata.com\/2007\/01\/code_kata_fifte.html\n: ?HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS ( n -- m ) ( TODO ) ;\n","old_contents":"\\ KataDiversion in Forth\n\n\\ -- utils\n\n\\ empty the stack\n: EMPTY\n DEPTH 0 <> IF BEGIN\n DROP DEPTH 0 =\n UNTIL\n THEN ;\n\n\\ power\n: ** ( n1 n2 -- n1_pow_n2 ) 1 SWAP ?DUP IF 0 DO OVER * LOOP THEN NIP ;\n\n\\ test if the top is a negative number\n: ?NEG ( n -- bool ) DUP 0= IF -1 ELSE DUP ABS <> THEN ;\n\n\\ log2 (integer)\n: LOG2 ( n -- log2_n ) DUP 1 < IF 1 ABORT\" Log2 need a positive value.\"\n ELSE DUP 1 = IF 0\n ELSE\n 1 >R\n BEGIN ( n |R: i=1)\n DUP DUP 2 I ** - 2 *\n ( n n 2*[n-2**i])\n R> 1 + >R ( \u2026 |R: i+1)\n > ( n n>2*[n-2**i] )\n UNTIL\n R> 1 -\n THEN\n THEN NIP ;\n\n\\ decimal to binary\n\\ e.g. : ( 11 -- 1 0 1 1 )\n\\ FIXME n DEC2BIN seems to give the binary value of n-1\n: DEC2BIN ( n -- n1 n2 n3 \u2026 ) DUP 0 <> IF\n LOG2 2 SWAP ** >R ( n |R: X=2 ** n.log2 )\n BEGIN\n DUP I - 0 > IF 1 SWAP I - ( 1 n-X )\n ELSE 0 SWAP ( 0 n )\n THEN\n I 1 =\n R> 2 \/ >R ( \u2026 | X\/2 )\n UNTIL\n R> 2DROP\n THEN\n ;\n\n\\ -- kata\n\n\\ test if the given N has two adjacent 1 bits\n\\ e.g. : 1011 -> -1\n\\ 1001 -> 0\n: ?TWO-ADJACENT-1-BITS ( n -- bool ) ( TODO ) ;\n\n\\ return the maximum number which can be made with N (given number) bits\n: ?MAX-NB ( n -- m ) DUP ?NEG IF DROP 0 ( 0 )\n ELSE \n DUP IF DUP 2 SWAP ** NIP ( 2**n )\n THEN\n THEN ;\n\n\n\\ return the number of numbers which can be made with N (given number) bits\n\\ or less, and which have not two adjacent 1 bits.\n\\ see http:\/\/www.codekata.com\/2007\/01\/code_kata_fifte.html\n: ?HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS ( n -- m ) ( TODO ) ;\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"1fcb4ba3c28c264d2c6eb50ce48a9466d423a73d","subject":"HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS tests added","message":"HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS tests added\n","repos":"bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas","old_file":"KataDiversion_tests.fth","new_file":"KataDiversion_tests.fth","new_contents":"\\ KataDiversion tests, in Forth\n\\ running tests:\n\\ gforth KataDiversion_tests.fth -e bye\n\nREQUIRE KataDiversion.fth\n\nVARIABLE ASSERT-COUNT\n\n: ASSERTS-INIT ( -- )\n 0 ASSERT-COUNT ! ;\n\n: ASSERTS-RESULT ( -- )\n ASSERT-COUNT @ . .\" assertions successfully passed.\" CR ;\n\n\\ destructive assert-equal\n: ASSERT-EQUAL-D ( n1 n2 -- )\n <> IF 1 ABORT\" AssertEqual: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-equal\n: ASSERT-EQUAL ( n1 n2 -- n1 n2 )\n 2DUP ASSERT-EQUAL-D ;\n\n\\ destructive assert-true\n: ASSERT-TRUE-D ( n -- )\n 0 = IF 1 ABORT\" AssertTrue: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-true\n: ASSERT-TRUE ( n -- n )\n DUP ASSERT-TRUE-D ;\n\n\\ destructive assert-false\n: ASSERT-False-D ( n -- )\n 0 <> IF 1 ABORT\" AssertFalse: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-false\n: ASSERT-FALSE ( n -- n )\n DUP ASSERT-FALSE-D ;\n\n\\ ---- tests ----\n\nASSERTS-INIT\n\n\\ EMPTY\nEMPTY DEPTH 0 ASSERT-EQUAL-D\nEMPTY EMPTY DEPTH 0 ASSERT-EQUAL-D\n0 EMPTY DEPTH 0 ASSERT-EQUAL-D\n1 2 3 4 EMPTY DEPTH 0 ASSERT-EQUAL-D\n\n\\ MAX-NB\n-1 MAX-NB 0 ASSERT-EQUAL-D\n 0 MAX-NB 0 ASSERT-EQUAL-D\n 1 MAX-NB 1 ASSERT-EQUAL-D\n 2 MAX-NB 3 ASSERT-EQUAL-D\n 3 MAX-NB 7 ASSERT-EQUAL-D\n\n\\ MAXPOW2\n 1 MAXPOW2 1 ASSERT-EQUAL-D\n 2 MAXPOW2 2 ASSERT-EQUAL-D\n 3 MAXPOW2 2 ASSERT-EQUAL-D\n 4 MAXPOW2 4 ASSERT-EQUAL-D\n 5 MAXPOW2 4 ASSERT-EQUAL-D\n 8 MAXPOW2 8 ASSERT-EQUAL-D\n 42 MAXPOW2 32 ASSERT-EQUAL-D\n2000 MAXPOW2 1024 ASSERT-EQUAL-D\n\n\\ ?NOT-TWO-ADJACENT-1-BITS\n 0 ?NOT-TWO-ADJACENT-1-BITS ASSERT-TRUE-D\n 1 ?NOT-TWO-ADJACENT-1-BITS ASSERT-TRUE-D\n 2 ?NOT-TWO-ADJACENT-1-BITS ASSERT-TRUE-D\n 3 ?NOT-TWO-ADJACENT-1-BITS ASSERT-FALSE-D\n 6 ?NOT-TWO-ADJACENT-1-BITS ASSERT-FALSE-D\n 7 ?NOT-TWO-ADJACENT-1-BITS ASSERT-FALSE-D\n 8 ?NOT-TWO-ADJACENT-1-BITS ASSERT-TRUE-D\n 11 ?NOT-TWO-ADJACENT-1-BITS ASSERT-FALSE-D\n 65 ?NOT-TWO-ADJACENT-1-BITS ASSERT-TRUE-D\n3072 ?NOT-TWO-ADJACENT-1-BITS ASSERT-FALSE-D\n\n\\ HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS\n \\ 0, 1\n1 HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS 2 ASSERT-EQUAL-D\n \\ 00, 01, 10\n2 HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS 3 ASSERT-EQUAL-D\n \\ 000, 001, 010, 100, 101\n3 HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS 5 ASSERT-EQUAL-D\n \\ 0000, 0001, 0010, 0100, 0101, 1000, 1001, 1010\n4 HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS 8 ASSERT-EQUAL-D\n\n\nASSERTS-RESULT\n\\ ---------\n\n\n","old_contents":"\\ KataDiversion tests, in Forth\n\\ running tests:\n\\ gforth KataDiversion_tests.fth -e bye\n\nREQUIRE KataDiversion.fth\n\nVARIABLE ASSERT-COUNT\n\n: ASSERTS-INIT ( -- )\n 0 ASSERT-COUNT ! ;\n\n: ASSERTS-RESULT ( -- )\n ASSERT-COUNT @ . .\" assertions successfully passed.\" CR ;\n\n\\ destructive assert-equal\n: ASSERT-EQUAL-D ( n1 n2 -- )\n <> IF 1 ABORT\" AssertEqual: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-equal\n: ASSERT-EQUAL ( n1 n2 -- n1 n2 )\n 2DUP ASSERT-EQUAL-D ;\n\n\\ destructive assert-true\n: ASSERT-TRUE-D ( n -- )\n 0 = IF 1 ABORT\" AssertTrue: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-true\n: ASSERT-TRUE ( n -- n )\n DUP ASSERT-TRUE-D ;\n\n\\ destructive assert-false\n: ASSERT-False-D ( n -- )\n 0 <> IF 1 ABORT\" AssertFalse: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-false\n: ASSERT-FALSE ( n -- n )\n DUP ASSERT-FALSE-D ;\n\n\\ ---- tests ----\n\nASSERTS-INIT\n\n\\ ?EMPTY\nEMPTY DEPTH 0 ASSERT-EQUAL-D\nEMPTY EMPTY DEPTH 0 ASSERT-EQUAL-D\n0 EMPTY DEPTH 0 ASSERT-EQUAL-D\n1 2 3 4 EMPTY DEPTH 0 ASSERT-EQUAL-D\n\n\\ ?MAX-NB\n-1 ?MAX-NB 0 ASSERT-EQUAL-D\n 0 ?MAX-NB 0 ASSERT-EQUAL-D\n 1 ?MAX-NB 2 ASSERT-EQUAL-D\n 2 ?MAX-NB 4 ASSERT-EQUAL-D\n 3 ?MAX-NB 8 ASSERT-EQUAL-D\n\n\\ MAXPOW2\n 1 MAXPOW2 1 ASSERT-EQUAL-D\n 2 MAXPOW2 2 ASSERT-EQUAL-D\n 3 MAXPOW2 2 ASSERT-EQUAL-D\n 4 MAXPOW2 4 ASSERT-EQUAL-D\n 5 MAXPOW2 4 ASSERT-EQUAL-D\n 8 MAXPOW2 8 ASSERT-EQUAL-D\n 42 MAXPOW2 32 ASSERT-EQUAL-D\n2000 MAXPOW2 1024 ASSERT-EQUAL-D\n\n\n\\ ?NOT-TWO-ADJACENT-1-BITS\n 1 ?NOT-TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n 2 ?NOT-TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n 3 ?NOT-TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n 6 ?NOT-TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n 7 ?NOT-TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n 8 ?NOT-TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n 11 ?NOT-TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n 65 ?NOT-TWO-ADJACENT-1-BITS -1 ASSERT-EQUAL-D\n3072 ?NOT-TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n\nASSERTS-RESULT\n\\ ---------\n\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"68a74e2924ce0827626e0216151398f6e6af85d9","subject":"Added words for dealing with permutations.","message":"Added words for dealing with permutations.\n\nThis is all.\n","repos":"howerj\/libforth","old_file":"forth.fth","new_file":"forth.fth","new_contents":"#!.\/forth\n( Welcome to libforth, A dialect of Forth. Like all versions\nof Forth this version is a little idiosyncratic, but how\nthe interpreter works is documented here and in various\nother files.\n\nThis file contains most of the start up code, some basic\nstart up code is executed in the C file as well which makes\nprogramming at least bearable. Most of Forth is programmed in\nitself, which may seem odd if your back ground in programming\ncomes from more traditional language [such as C], although\nless so if you know already know lisp.\n\nFor more information about this interpreter and Forth see:\n\nhttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\nAnd within this code base:\n\n\treadme.md : for a manual for this interpreter\n\tlibforth.h : for information about the C API\n\tlibforth.c : for the interpreter itself\n\tunit.c : unit tests for libforth.c\n\tunit.fth : unit tests against this file\n\tmain.c : an example interpreter\n\nThe interpreter and this code originally descend from a Forth\ninterpreter written in 1992 for the International obfuscated\nC Coding Competition.\n\nSee:\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\nThe manual for the interpreter should be read first before\nlooking into this code. It is important to understand the\nexecution model of Forth, especially the differences between\ncommand and compile mode, and how immediate and compiling\nwords work.\n\nEach of these sections is clearly labeled and they are\ngenerally in dependency order.\n\nUnfortunately the code in this file is not as portable as it\ncould be, it makes assumptions about the size of cells provided\nby the virtual machine, which will take time to rectify. Some\nof the constructs are subtly different from the DPANs Forth\nspecification, which is usually noted. Eventually this should\nalso be fixed.\n\nA little note on how code is formatted, a line of Forth code\nshould not exceed 64 characters. All words stack effect, how\nmany variables on the stack it accepts and returns, should\nbe commented with the following types:\n\n\tchar \/ c A character\n\tc-addr An address of a character\n\taddr An address of a cell\n\tr-addr A real address*\n\tu A unsigned number\n\tn A signed number\n\tc\" xxx\" The word parses a word\n\tc\" x\" The word parses a single character\n\txt An execution token\n\tbool A boolean value\n\tior A file error return status [0 on no error]\n\tfileid A file identifier.\n\tCODE A number from a words code field\n\tPWD A number from a words previous word field\n\t* A real address is one outside the range of the\n\tForth address space.\n\nIn the comments Forth words should be written in uppercase. As\nthis is supposed to be a tutorial about Forth and describe the\ninternals of a Forth interpreter, be as verbose as possible.\n\nThe code in this file will need to be modified to abide by\nthese standards, but new code should follow it from the start.\n\nDoxygen style tags for documenting bugs, todos and warnings\nshould be used within comments. This makes finding code that\nneeds working on much easier.)\n\n( ==================== Basic Word Set ======================== )\n\n( We'll begin by defining very simple words we can use later,\nthese a very basic words, that perform simple tasks, they\nwill not require much explanation.\n\nEven though the words are simple, their stack comment and\na description for them will still be included so external\ntools can process and automatically extract the document\nstring for a given work. )\n\n: postpone ( c\" xxx\" -- : postpone execution of a word )\n\timmediate find , ;\n\n: constant\n\t:: ( compile word header )\n\there 1 - h ! ( decrement dictionary pointer )\n\t( change instruction to CONST )\n\there @ instruction-mask invert and doconst or here !\n\there 1 + h ! ( increment dictionary pointer )\n\t, ( write in value )\n\tpostpone [ ; ( back into command mode )\n\n( These constants are defined as a space saving measure,\nnumbers in a definition usually take up two cells, one\nfor the instruction to push the next cell and the cell\nitself, for the most frequently used numbers it is worth\ndefining them as constants, it is just as fast but saves\na lot of space )\n-1 constant -1\n 0 constant 0\n 1 constant 1\n 2 constant 2\n 3 constant 3\n\n0 constant false\n1 constant true ( @warning not standards compliant )\n\n( Confusingly the word CR prints a line feed )\n10 constant lf ( line feed )\nlf constant nl ( new line - line feed on Unixen )\n13 constant cret ( carriage return )\n\n-1 -1 1 rshift invert and constant min-signed-integer\nmin-signed-integer invert constant max-signed-integer\n\n( The following version number is used to mark whether core\nfiles will be compatible with each other, The version number\ngets stored in the core file and is used by the loader to\ndetermine compatibility )\n4 constant version ( version number for the interpreter )\n\n( This constant defines the number of bits in an address )\ncell size 8 * * constant address-unit-bits \n\n( Bit corresponding to the sign in a number )\n-1 -1 1 rshift and invert constant sign-bit \n\n( @todo test by how much, if at all, making words like 1+,\n1-, <>, and other simple words, part of the interpreter would\nspeed things up )\n\n: 1+ ( x -- x : increment a number )\n\t1 + ;\n\n: 1- ( x -- x : decrement a number )\n\t1 - ;\n\n: chars ( c-addr -- addr : convert a c-addr to an addr )\n\tsize \/ ;\n\n: chars> ( addr -- c-addr: convert an addr to a c-addr )\n\tsize * ;\n\n: tab ( -- : print a tab character )\n\t9 emit ;\n\n: 0= ( n -- bool : is 'n' equal to zero? )\n\t0 = ;\n\n: not ( n -- bool : is 'n' true? )\n\t0= ;\n\n: <> ( n n -- bool : not equal )\n\t= 0= ;\n\n: logical ( n -- bool : turn a value into a boolean )\n\tnot not ;\n\n: 2, ( n n -- : write two values into the dictionary )\n\t, , ;\n\n: [literal] ( n -- : write a literal into the dictionary )\n\tdolit 2, ;\n\n: literal ( n -- : immediately compile a literal )\n\timmediate [literal] ;\n\n: sliteral immediate ( I: c-addr u --, Run: -- c-addr u )\n\tswap [literal] [literal] ;\n\n( @todo throw if not found )\n: ['] ( I: c\" xxx\", Run: -- xt )\n\timmediate find [literal] ;\n\n: >instruction ( CODE -- u : extract instruction CODE field )\n\tinstruction-mask and ;\n\n( IMMEDIATE-MASK pushes the mask for the compile bit,\nwhich can be used on a CODE field of a word )\n1 compile-bit lshift constant immediate-mask\n\n: hidden? ( PWD -- PWD bool : is a word hidden? )\n\tdup 1+ @ hidden-mask and logical ;\n\n: compiling? ( PWD -- PWD bool : is a word immediate? )\n\tdup 1+ @ immediate-mask and logical ;\n\n: cr ( -- : emit a newline character )\n\tnl emit ;\n\n: < ( x1 x2 -- bool : signed less than comparison )\n\t- dup if max-signed-integer u> else logical then ;\n\n: > ( x1 x2 -- bool : signed greater than comparison )\n\t- dup if max-signed-integer u< else logical then ;\n\n( The pad area is an area used for temporary storage, some\nwords use it, although which ones do should be kept to a\nminimum. It is an area of space #pad amount of characters\nafter the latest dictionary definition. The area between\nthe end of the dictionary and start of PAD space is used for\npictured numeric output [<#, #, #S, #>]. It is best not to\nuse the pad area that much. )\n128 constant #pad\n\n: pad ( -- addr : push pointer to the pad area )\n\there #pad + ;\n\n( @todo this can be improved a lot, currently it uses more\nspace than it has to, 4 cells instead of three.\n\nIt does:\n\n\tpush value\n\tpush value\n\nInstead of:\n\n\tmagic-2literal-word\n\tvalue\n\tvalue\n\n)\n: 2literal immediate ( n n -- : compile two literals )\n\tswap [literal] [literal] ;\n\n: latest ( get latest defined word )\n\tpwd @ ;\n\n: stdin ( -- fileid : push fileid for standard input )\n\t`stdin @ ;\n\n: stdout ( -- fileid : push fileid for standard output )\n\t`stdout @ ;\n\n: stderr ( -- fileid : push fileid for the standard error )\n\t`stderr @ ;\n\n: stdin? ( -- bool : are we reading from standard input )\n\t`fin @ stdin = ;\n\n: *+ ( n1 n2 n3 -- n )\n\t* + ;\n\t\n: 2- ( n -- n : decrement by two )\n\t2 - ;\n\n: 2+ ( n -- n : increment by two )\n\t2 + ;\n\n: 3+ ( n -- n : increment by three )\n\t3 + ;\n\n: 2* ( n -- n : multiply by two )\n\t1 lshift ;\n\n: 2\/ ( n -- n : divide by two )\n\t1 rshift ;\n\n: 4* ( n -- n : multiply by four )\n\t2 lshift ;\n\n: 4\/ ( n -- n : divide by four )\n\t2 rshift ;\n\n: 8* ( n -- n : multiply by eight )\n\t3 lshift ;\n\n: 8\/ ( n -- n : divide by eight )\n\t3 rshift ;\n\n: 256* ( n -- n : multiply by 256 )\n\t8 lshift ;\n\n: 256\/ ( n -- n : divide by 256 )\n\t8 rshift ;\n\n: 2dup ( n1 n2 -- n1 n2 n1 n2 : duplicate two values )\n\tover over ;\n\n: mod ( u1 u2 -- u : calculate the remainder of u1\/u2 )\n\t2dup \/ * - ;\n\n( @todo implement UM\/MOD in the VM, then use this to implement\n'\/' and MOD )\n: um\/mod ( u1 u2 -- rem quot : remainder and quotient of u1\/u2 )\n\t2dup \/ >r mod r> ;\n\n( @warning this does not use a double cell for the multiply )\n: *\/ ( n1 n2 n3 -- n4 : [n2*n3]\/n1 )\n\t * \/ ;\n\n: char ( -- n : read in a character from the input steam )\n\tkey drop key ;\n\n: [char] ( c\" x\" -- R: -- char : immediately compile next char )\n\timmediate char [literal] ;\n\n( COMPOSE is a high level function that can take two executions\ntokens and produce a unnamed function that can do what they\nboth do.\n\nIt can be used like so:\n\n\t:noname 2 ;\n\t:noname 3 + ;\n\tcompose\n\texecute \n\t.\n\t5 <-- 5 is printed!\n\nI have not found a use for it yet, but it sure is neat.)\n\n: compose ( xt1 xt2 -- xt3 : create a function from xt-tokens )\n\t>r >r ( save execution tokens )\n\tpostpone :noname ( create a new :noname word )\n\tr> , ( write first token )\n\tr> , ( write second token )\n\t(;) ; ( terminate new :noname )\n\n( CELLS is a word that is not needed in this interpreter but\nit required to write portable code [I have probably missed\nquite a few places where it should be used]. The reason it\nis not needed in this interpreter is a cell address can only\nbe in multiples of cells, not in characters. This should be\naddressed in the libforth interpreter as it adds complications\nwhen having to convert to and from character and cell address.)\n\n: cells ( n1 -- n2 : convert cell count to address count)\n\timmediate ;\n\n: cell+ ( a-addr1 -- a-addr2 )\n\tcell + ;\n\n: cell- ( a-addr1 -- addr2 )\n\tcell - ;\n\n: negative? ( x -- bool : is a number negative? )\n\tsign-bit and logical ;\n\n: mask-byte ( x -- x : generate mask byte )\n\t8* 255 swap lshift ;\n\n: select-byte ( u i -- c )\n\t8* rshift 0xff and ;\n\n: xt-instruction ( PWD -- CODE : extract instruction from PWD )\n\tcell+ @ >instruction ;\n\n: defined-word? ( PWD -- bool : is defined or a built-in word)\n\txt-instruction dolist = ;\n\n: char+ ( c-addr -- c-addr : increment a c-addr one c-addr )\n\t1+ ;\n\n: 2chars ( c-addr1 c-addr2 -- addr addr : chars on two c-addr) \n\tchars swap chars swap ;\n\n: 2chars> ( addr addr -- c-addr c-addr: chars> on two addr )\n\tchars> swap chars> swap ;\n\n: hex ( -- : print out hex )\n\t16 base ! ;\n\n: octal ( -- : print out octal )\n\t8 base ! ;\n\n: binary ( -- : print out binary )\n\t2 base ! ;\n\n: decimal ( -- : print out decimal )\n\t0 base ! ;\n\n: negate ( x -- x )\n\t-1 * ;\n\n: abs ( x -- u : return the absolute value of a number )\n\tdup negative? if negate then ;\n\n: square ( x -- x )\n\tdup * ;\n\n: sum-of-squares ( a b -- c : compute a^2 + b^2 to get c )\n\tsquare swap square + ;\n\n: drup ( x y -- x x )\n\tdrop dup ;\n\n: +! ( x addr -- : add x to a value stored at addr )\n\ttuck @ + swap ! ;\n\n: 1+! ( addr -- : increment a value at an address )\n\t1 swap +! ;\n\n: 1-! ( addr -- : decrement a value at an address )\n\t-1 swap +! ;\n\n: c+! ( x c-addr -- : add x to a value stored at c-addr )\n\ttuck c@ + swap c! ;\n\n: toggle ( addr u -- : xor value at addr with u )\n\tover @ xor swap ! ;\n\n: lsb ( x -- x : mask off the least significant byte of a cell )\n\t255 and ;\n\n: \\ ( -- : immediate word, used for single line comments )\n\timmediate begin key nl = until ;\n\n: ?dup ( x -- ? )\n\tdup if dup then ;\n\n: min ( n n -- n : return the minimum of two integers )\n\t2dup < if drop else nip then ;\n\n: max ( n n -- n : return the maximum of two integers )\n\t2dup > if drop else nip then ;\n\n: umin ( u u -- u : return the minimum of two unsigned numbers )\n\t2dup u< if drop else nip then ;\n\n: umax ( u u -- u : return the maximum of two unsigned numbers )\n\t2dup > if drop else nip then ;\n\n: limit ( x min max -- x : limit x with a minimum and maximum )\n\trot min max ;\n\n: >= ( n n -- bool )\n\t< not ;\n\n: <= ( n n -- bool )\n\t> not ;\n\n: 2@ ( a-addr -- u1 u2 : load two consecutive memory cells )\n\tdup 1+ @ swap @ ;\n\n: 2! ( u1 u2 a-addr -- : store two values at two consecutive memory cells )\n\t2dup ! nip 1+ ! ;\n\n( @bug I don't think this is correct. )\n: r@ ( -- u, R: u -- )\n\tr> r @ swap >r ;\n\n: rp@ ( -- u, R: u -- )\n\tr> r @ swap >r ;\n\n( @todo r!, rp! )\n\n: 0> ( n -- bool )\n\t0 > ;\n\n: 0<= ( n -- bool )\n\t0> not ;\n\n: 0< ( n -- bool )\n\t0 < ;\n\n: 0>= ( n -- bool )\n\t0< not ;\n\n: 0<> ( n -- bool )\n\t0 <> ;\n\n: signum ( n -- -1 | 0 | 1 : Signum function )\n\tdup 0> if drop 1 exit then\n\t 0< if -1 exit then\n\t0 ;\n\n: nand ( u u -- u : bitwise NAND )\n\tand invert ;\n\n: odd ( u -- bool : is 'n' odd? )\n\t1 and ;\n\n: even ( u -- bool : is 'n' even? )\n\todd not ;\n\n: nor ( u u -- u : bitwise NOR )\n\tor invert ;\n\n: ms ( u -- : wait at least 'u' milliseconds )\n\tclock + begin dup clock u< until drop ;\n\n: sleep ( u -- : sleep for 'u' seconds )\n\t1000 * ms ;\n\n: align ( addr -- addr : align an address, nop in this implemented )\n\timmediate ;\n\n: ) ( -- : do nothing, this allows easy commenting out of code )\n\timmediate ;\n\n: bell ( -- : emit an ASCII BEL character )\n\t7 emit ;\n\n: b\/buf ( -- u : bytes per buffer )\n\t1024 ;\n\n: .d ( x -- x : debug print )\n\tdup . ;\n\n: compile, ( x -- : )\n\t, ;\n\n: >mark ( -- : write a hole into the dictionary and push a pointer to it )\n\there 0 , ;\n\n: r - r> u< ;\n\n: invalidate ( -- : invalidate this Forth core )\n\t1 `invalid ! ;\n\n: signed ( x -- bool : return true if sign bit set )\n\t[ 1 size 8 * 1- lshift ] literal and logical ;\n\n: u>= ( x y -- bool : unsigned greater than or equal to )\n\t2dup u> >r = r> or ;\n\n: u<= ( x y -- bool : unsigned less than or equal to )\n\tu>= not ;\n\n: rdrop ( R: x -- : drop a value from the return stack )\n\tr> ( get caller's return address )\n\tr> ( get value to drop )\n\tdrop ( drop it like it's hot )\n\t>r ; ( return return address )\n\n: rdup\n\tr> ( get caller's return address )\n\tr> ( get value to duplicate )\n\tdup ( ... )\n\t>r >r >r ; ( make it all work )\n\n: chere ( -- c-addr : here as in character address units )\n\there chars> ;\n\n: source ( -- c-addr u )\n\t#tib ( size of input buffer, in characters )\n\ttib ; ( start of input buffer, in characters )\n\n: stdin? ( -- bool : are we reading from standard in? )\n\t`fin @ `stdin @ = ;\n\n: source-id ( -- 0 | -1 | file-id )\n\t( \t\n\tValue Input Source\n\t-1 String\n\t0 Reading from user input \/ standard in\n\tfile-id )\n\t`source-id @\n\t0= if\n\t\tstdin? if 0 else `fin @ then\n\telse\n\t\t-1\n\tthen ;\n\n: under ( x1 x2 -- x1 x1 x2 )\n\t>r dup r> ;\n\n: 2nip ( n1 n2 n3 n4 -- n3 n4 )\n\t>r >r 2drop r> r> ;\n\n: 2over ( n1 n2 n3 n4 \u2013 n1 n2 n3 n4 n1 n2 )\n\t>r >r 2dup r> swap >r swap r> r> -rot ;\n\n: 2swap ( n1 n2 n3 n4 \u2013 n3 n4 n1 n2 )\n\t>r -rot r> -rot ;\n\n: 2tuck ( n1 n2 n3 n4 \u2013 n3 n4 n1 n2 n3 n4 )\n\t2swap 2over ;\n\n: 3drop ( n1 n2 n3 -- )\n\tdrop 2drop ;\n\n: 4drop ( n1 n2 n3 n4 -- )\n\t2drop 2drop ;\n\n: nos1+ ( x1 x2 -- x1+1 x2 : increment the next variable on that stack )\n\tswap 1+ swap ;\n\n: ?dup-if immediate ( x -- x | - : ?dup and if rolled into one! )\n\t['] ?dup , postpone if ;\n\n: ?if ( -- : non destructive if )\n\timmediate ['] dup , postpone if ;\n\n: (hide) ( token -- hide-token : this hides a word from being found by the interpreter )\n\t?dup-if\n\t\tdup @ hidden-mask or swap tuck ! exit\n\tthen 0 ;\n\n: hide ( WORD -- : hide with drop )\n\tfind dup if (hide) then drop ;\n\n: reveal ( hide-token -- : reveal a hidden word )\n\tdup @ hidden-mask invert and swap ! ;\n\n: ?exit ( x -- : exit current definition if not zero )\n\tif rdrop exit then ;\n\n: decimal? ( c -- f : is character a number? )\n\t[char] 0 [ char 9 1+ ] literal within ;\n\n: lowercase? ( c -- f : is character lower case? )\n\t[char] a [ char z 1+ ] literal within ;\n\n: uppercase? ( C -- f : is character upper case? )\n\t[char] A [ char Z 1+ ] literal within ;\n\n: alpha? ( C -- f : is character part of the alphabet? )\n\tdup lowercase? swap uppercase? or ;\n\n: alphanumeric? ( C -- f : is character alphabetic or a number ? )\n\tdup alpha? swap decimal? or ;\n\n: printable? ( c -- bool : is printable, excluding new lines and tables )\n\t32 127 within ;\n\n: >upper ( c -- C : convert char to uppercase iff lower case )\n\tdup lowercase? if bl xor then ;\n\n: >lower ( C -- c : convert char to lowercase iff upper case )\n\tdup uppercase? if bl xor then ;\n\n: <=> ( x y -- z : spaceship operator! )\n\t2dup\n\t> if 2drop -1 exit then\n\t< ;\n\n: start-address ( -- c-addr : push the start address )\n\t`start-address @ ;\n\n: >real-address ( c-addr -- r-addr : convert an interpreter address to a real address )\n\tstart-address + ;\n\n: real-address> ( c-addr -- r-addr : convert a real address to an interpreter address )\n\tstart-address - ;\n\n: peek ( r-addr -- n : )\n\tpad chars> >real-address swap size memory-copy pad @ ;\n\n: poke ( n r-addr -- : )\n\tswap pad ! pad chars> >real-address size memory-copy ;\n\n: die! ( x -- : controls actions when encountering certain errors )\n\t`error-handler ! ;\n\n: start! ( cfa -- : set the word to execute at startup )\n\t`instruction ! ;\t\n\n: warm ( -- : restart the interpreter, warm restart )\n\t1 restart ;\n\n: trip ( x -- x x x : triplicate a number )\n\tdup dup ;\n\n: roll ( xu xu-1 ... x0 u -- xu-1 ... x0 xu : move u+1 items on the top of the stack by u )\n\t[ smudge ] ( un-hide this word so we can call it recursively )\n\tdup 0 >\n\tif\n\t\tswap >r 1- roll r> swap\n\telse\n\t\tdrop\n\tthen ;\nsmudge\n\n: 2rot ( n1 n2 n3 n4 n5 n6 \u2013 n3 n4 n5 n6 n1 n2 )\n\t5 roll 5 roll ;\n\n: s>d ( x -- d : convert a signed value to a double width cell )\n\t( @note the if...else...then is only necessary as this Forths\n\tbooleans are 0 and 1, not 0 and -1 as it usually is )\n\tdup 0< if -1 else 0 then ;\n\n: trace ( level -- : set tracing level )\n\t`debug ! ;\n\n: verbose ( -- : get the log level )\n\t`debug @ ;\n\n: count ( c-addr1 -- c-addr2 u : get a string whose first char is its length )\n\tdup c@ nos1+ ;\n\n: bounds ( x y -- y+x x : make an upper and lower bound )\n\tover + swap ;\n\n: aligned ( unaligned -- aligned : align a pointer )\n\t[ size 1- ] literal +\n\t[ size 1- ] literal invert and ;\n\n: rdepth\n\tmax-core `stack-size @ - r @ swap - ;\n\n: argv ( -- r-addr : push pointer to array of string pointers to program )\n\t`argv @ ;\n\n: argc ( -- u : push the number of arguments in the argv array )\n\t`argc @ ;\n\n: +- ( x1 x2 -- x3 : copy the sign of x1 to x2 giving x3 )\n\t[ sign-bit 1- ] literal and\n\tswap\n\tsign-bit and or ;\n\n: \/string ( c-addr1 u1 u2 -- c-addr2 u2 : advance a string by n characters )\n\tover min rot over + -rot - ;\n\nhide stdin?\n\n: cfa immediate ( find-address -- cfa )\n\t( Given the address of the PWD field of a word this\n\tfunction will return an execution token for the word )\n\t( @todo if < dictionary start PWD is invalid )\n\t ;\n\n: again immediate\n\t( loop unconditionally in a begin-loop:\n\t\tbegin ... again )\n\t['] branch , body ( xt -- a-addr : a-addr is data field of a CREATEd word )\n\\\tcfa 5 + ;\n\n\n: execute ( xt -- : given an execution token, execute the word )\n\t( create a word that pushes the address of a hole to write to.\n\tA literal takes up two words, '!' takes up one, that's right,\n\tsome self modifying code! )\n\t[ here 3 cells + literal ] ( calculate place to write to )\n\t! ( write an execution token to a hole )\n\t[ 0 , ] ; ( this is the hole we write )\n\n( @todo integrate catch\/throw into the interpreter as primitives )\n: catch ( xt -- exception# | 0 : return addr on stack )\n\tsp@ >r ( xt : save data stack pointer )\n\t`handler @ >r ( xt : and previous handler )\n\tr@ `handler ! ( xt : set current handler )\n\texecute ( execute returns if no throw )\n\tr> `handler ! ( restore previous handler )\n\tr> drop ( discard saved stack ptr )\n\t0 ; ( 0 : normal completion )\n\n( @todo use this everywhere )\n: throw ( ??? exception# -- ??? exception# )\n\t?dup-if ( exc# \\ 0 throw is no-op )\n\t\t`handler @ r ! ( exc# : restore prev return stack )\n\t\tr> `handler ! ( exc# : restore prev handler )\n\t\tr> swap >r ( saved-sp : exc# on return stack )\n\t\tsp! drop r> ( exc# : restore stack )\n\t\t( return to the caller of catch because return )\n\t\t( stack is restored to the state that existed )\n\t\t( when catch began execution )\n\tthen ;\n\n: interpret ( c1\" xxx\" ... cn\" xxx\" -- : This word implements the interpreter loop )\n\tbegin\n\t['] read catch\n\t?dup-if [char] ! emit tab . cr then ( exception handler of last resort )\n\tagain ;\n\n: [interpret] ( c1\" xxx\" ... cn\" xxx\" -- : immediate version of interpret )\n\timmediate interpret ;\n\ninterpret ( use the new interpret word, which can catch exceptions )\n\nfind [interpret] cell+ start! ( the word executed on restart is now our new word )\n\n( The following words are using in various control structure related\nwords to make sure they only execute in the correct state )\n\n: ?comp ( -- : error if not compiling )\n\tstate @ 0= if -14 throw then ;\n\n: ?exec ( -- : error if not executing )\n\tstate @ if -22 throw then ;\n\n( begin...while...repeat These are defined in a very \"Forth\" way )\n: while\n\t?comp\n\timmediate postpone if ( branch to repeats THEN ) ;\n\n: whilst postpone while ;\n\n: repeat immediate\n\t?comp\n\tswap ( swap BEGIN here and WHILE here )\n\tpostpone again ( again jumps to begin )\n\tpostpone then ; ( then writes to the hole made in if )\n\n: never ( never...then : reserve space in word )\n\timmediate 0 [literal] postpone if ;\n\n: unless ( bool -- : like IF but execute clause if false )\n\timmediate ?comp ['] 0= , postpone if ;\n\n: endif ( synonym for THEN )\n\timmediate ?comp postpone then ;\n\n( Experimental FOR ... NEXT )\n: for immediate \n\t?comp\n\t['] 1- ,\n\t['] >r ,\n\there ;\n\n: (next) ( -- bool, R: val -- | val+1 )\n\tr> r> 1- dup 0< if drop >r 1 else >r >r 0 then ;\n\n: next immediate\n\t?comp\n\t['] (next) , \n\t['] ?branch , \n\there - , ;\n\n( ==================== Basic Word Set ======================== )\n\n( ==================== DOER\/MAKE ============================= )\n( DOER\/MAKE is a word set that is quite powerful and is\ndescribed in Leo Brodie's book \"Thinking Forth\". It can be\nused to make words whose behavior can change after they\nare defined. It essentially makes the structured use of\nself-modifying code possible, along with the more common\ndefinitions of \"defer\/is\".\n\nAccording to \"Thinking Forth\", it has two purposes:\n\n1. To change the state of a function.\n2. To factor out common phrases of a words definition.\n\nAn example of the first instance:\n\n\tdoer say\n\t: sad \" Good bye, cruel World!\" cr ;\n\t: happy \" Hello, World!\" cr ;\n\n\t: person say ;\n\n\tmake person happy\n\tperson \\ prints \"Good bye, cruel World!\"\n\n\tmake person sad\n\tperson \\ prints \"Hello, World!\"\n\nAn example of the second:\n\n\tdoer op\n\n\t: sum \\ n0 ... nX X -- sum<0..X>\n\t\tmake op + 1 do op loop ;\n\n\t: mul \\ n0 ... nX X -- mul<0..X>\n\t\tmake op * 1 do op loop ;\n\nThe above example is a bit contrived, the definitions and\nfunctionality are too simple for this to be worth factoring\nout, but it shows how you can use DOER\/MAKE. )\n\n: noop ; ( -- : default word to execute for doer, does nothing )\n\n: doer ( c\" xxx\" -- : make a work whose behavior can be changed by make )\n\timmediate ?exec :: ['] noop , (;) ;\n\n: found? ( xt -- xt : thrown an exception if the xt is zero )\n\tdup 0= if -13 throw then ;\n\n( It would be nice to provide a MAKE that worked with\nexecution tokens as well, although \"defer\" and \"is\" can be\nused for that. MAKE expects two word names to be given as\narguments. It will then change the behavior of the first word\nto use the second. MAKE is a state aware word. )\n\n: make immediate ( c1\" xxx\" c2\" xxx\" : change parsed word c1 to execute c2 )\n\tfind found? cell+\n\tfind found?\n\tstate @ if ( compiling )\n\t\tswap postpone 2literal ['] ! ,\n\telse ( command mode )\n\t\tswap !\n\tthen ;\n\n( ==================== DOER\/MAKE ============================= )\n\n( ==================== Extended Word Set ===================== )\n\n: r.s ( -- : print the contents of the return stack )\n\tr>\n\t[char] < emit rdepth (.) drop [char] > emit\n\tspace\n\trdepth dup 0> if dup\n\tbegin dup while r> -rot 1- repeat drop dup\n\tbegin dup while rot dup . >r 1- repeat drop\n\tthen drop cr\n\t>r ;\n\n: log ( u base -- u : command the _integer_ logarithm of u in base )\n\t>r\n\tdup 0= if -11 throw then ( logarithm of zero is an error )\n\t0 swap\n\tbegin\n\t\tnos1+ rdup r> \/ dup 0= ( keep dividing until 'u' is zero )\n\tuntil\n\tdrop 1- rdrop ;\n\n: log2 ( u -- u : compute the _integer_ logarithm of u )\n\t2 log ;\n\n: alignment-bits ( c-addr -- u : get the bits used for aligning a cell )\n\t[ 1 size log2 lshift 1- literal ] and ;\n\n: time ( \" ccc\" -- n : time the number of milliseconds it takes to execute a word )\n\tclock >r\n\tfind found? execute\n\tclock r> - ;\n\n( defer...is is probably not standards compliant, it is still neat! )\n: (do-defer) ( -- self : pushes the location into which it is compiled )\n\tr> dup >r 1- ;\n\n: defer immediate ( \" ccc\" -- , Run Time -- location :\n\tcreates a word that pushes a location to write an execution token into )\n\t?exec\n\t:: ['] (do-defer) , (;) ;\n\n: is ( location \" ccc\" -- : make a deferred word execute a word )\n\tfind found? swap ! ;\n\nhide (do-defer)\n\n( This RECURSE word is the standard Forth word for allowing\nfunctions to be called recursively. A word is hidden from the\ncompiler until the matching ';' is hit. This allows for previous\ndefinitions of words to be used when redefining new words, it\nalso means that words cannot be called recursively unless the\nrecurse word is used.\n\nRECURSE calls the word being defined, which means that it\ntakes up space on the return stack. Words using recursion\nshould be careful not to take up too much space on the return\nstack, and of course they should terminate after a finite\nnumber of steps.\n\nWe can test \"recurse\" with this factorial function:\n\n : factorial dup 2 < if drop 1 exit then dup 1- recurse * ;\n\n)\n: recurse immediate\n\t?comp\n\tlatest cell+ , ;\n\n: myself ( -- : myself is a synonym for recurse )\n\timmediate postpone recurse ;\n\n( The \"tail\" function implements tail calls, which is just a\njump to the beginning of the words definition, for example\nthis word will never overflow the stack and will print \"1\"\nfollowed by a new line forever,\n\n\t: forever 1 . cr tail ;\n\nWhereas\n\n\t: forever 1 . cr recurse ;\n\nor\n\n\t: forever 1 . cr forever ;\n\nWould overflow the return stack. )\n\nhide tail\n: tail ( -- : perform tail recursion in current word definition )\n\timmediate\n\t?comp\n\tlatest cell+\n\t['] branch ,\n\there - cell+ , ;\n\n( @todo better version of this )\n: factorial ( u -- u : factorial of u )\n\tdup 2 u< if drop 1 exit then dup 1- recurse * ;\n\n: permutations ( u1 u2 -- u : number of ordered combinations )\n\tover swap - factorial swap factorial swap \/ ;\n\n: combinations ( u1 u2 -- u : number of unordered combinations )\n\tdup dup permutations >r permutations r> \/\n\t;\n\n: average ( u1 u2 -- u : average of u1 and u2 ) \n\t+ 2\/ ;\n\n: gcd ( u1 u2 -- u : greatest common divisor )\n\tdup if tuck mod tail then drop ;\n\n: lcm ( u1 u2 -- u : lowest common multiple of u1 and u2 )\n\t2dup gcd \/ * ;\n\n( From: https:\/\/en.wikipedia.org\/wiki\/Integer_square_root\n\nThis function computes the integer square root of a number.\n\n@note this should be changed to the iterative algorithm so\nit takes up less space on the stack - not that is takes up\na hideous amount as it is. )\n\n: sqrt ( n -- u : integer square root )\n\tdup 0< if -11 throw then ( does not work for signed values )\n\tdup 2 < if exit then ( return 0 or 1 )\n\tdup ( u u )\n\t2 rshift recurse 2* ( u sc : 'sc' == unsigned small candidate )\n\tdup ( u sc sc )\n\t1+ dup square ( u sc lc lc^2 : 'lc' == unsigned large candidate )\n\t>r rot r> < ( sc lc bool )\n\tif drop else nip then ; ( return small or large candidate respectively )\n\n\n( ==================== Extended Word Set ===================== )\n\n( ==================== For Each Loop ========================= )\n( The foreach word set allows the user to take action over an\nentire array without setting up loops and checking bounds. It\nbehaves like the foreach loops that are popular in other\nlanguages.\n\nThe foreach word accepts a string and an execution token,\nfor each character in the string it passes the current address\nof the character that it should operate on.\n\nThe complexity of the foreach loop is due to the requirements\nplaced on it. It cannot pollute the variable stack with\nvalues it needs to operate on, and it cannot store values in\nlocal variables as a foreach loop could be called from within\nthe execution token it was passed. It therefore has to store\nall of it uses on the return stack for the duration of EXECUTE.\n\nAt the moment it only acts on strings as \"\/string\" only\nincrements the address passed to the word foreach executes\nto the next character address. )\n\n\\ (FOREACH) leaves the point at which the foreach loop\n\\ terminated on the stack, this allows programmer to determine\n\\ if the loop terminated early or not, and at which point.\n\n: (foreach) ( c-addr u xt -- c-addr u : execute xt for each cell in c-addr u\n\treturning number of items not processed )\n\tbegin\n\t\t3dup >r >r >r ( c-addr u xt R: c-addr u xt )\n\t\tnip ( c-addr xt R: c-addr u xt )\n\t\texecute ( R: c-addr u xt )\n\t\tr> r> r> ( c-addr u xt )\n\t\t-rot ( xt c-addr u )\n\t\t1 \/string ( xt c-addr u )\n\t\tdup 0= if rot drop exit then ( End of string - drop and exit! )\n\t\trot ( c-addr u xt )\n\tagain ;\n\n\\ If we do not care about returning early from the foreach\n\\ loop we can instead call FOREACH instead of (FOREACH),\n\\ it simply drops the results (FOREACH) placed on the stack.\n: foreach ( c-addr u xt -- : execute xt for each cell in c-addr u )\n\t(foreach) 2drop ;\n\n\\ RETURN is used for an early exit from within the execution\n\\ token, it leaves the point at which it exited\n: return ( -- n : return early from within a foreach loop function, returning number of items left )\n\trdrop ( pop off this words return value )\n\trdrop ( pop off the calling words return value )\n\trdrop ( pop off the xt token )\n\tr> ( save u )\n\tr> ( save c-addr )\n\trdrop ; ( pop off the foreach return value )\n\n\\ SKIP is an example of a word that uses the foreach loop\n\\ mechanism. It takes a string and a character and returns a\n\\ string that starts at the first occurrence of that character\n\\ in that string - or until it reaches the end of the string.\n\n\\ SKIP is defined in two steps, first there is a word,\n\\ (SKIP), that exits the foreach loop if there is a match,\n\\ if there is no match it does nothing. In either case it\n\\ leaves the character to skip until on the stack.\n\n: (skip) ( char c-addr -- char : exit out of foreach loop if there is a match )\n\tover swap c@ = if return then ;\n\n\\ SKIP then setups up the foreach loop, the char argument\n\\ will present on the stack when (SKIP) is executed, it must\n\\ leave a copy on the stack whatever happens, this is then\n\\ dropped at the end. (FOREACH) leaves the point at which\n\\ the loop terminated on the stack, which is what we want.\n\n: skip ( c-addr u char -- c-addr u : skip until char is found or until end of string )\n\t-rot ['] (skip) (foreach) rot drop ;\nhide (skip)\n\n( ==================== For Each Loop ========================= )\n\n( ==================== Hiding Words ========================== )\n( The two functions hide{ and }hide allow lists of words to\nbe hidden, instead of just hiding individual words. It stops\nthe dictionary from being polluted with meaningless words in\nan easy way. )\n\n: }hide ( should only be matched with 'hide{' )\n\timmediate -22 throw ;\n\n: hide{ ( -- : hide a list of words, the list is terminated with \"}hide\" )\n\t?exec\n\tbegin\n\t\tfind ( find next word )\n\t\tdup [ find }hide ] literal = if\n\t\t\tdrop exit ( terminate hide{ )\n\t\tthen\n\t\tdup 0= if -15 throw then\n\t\t(hide) drop\n\tagain ;\n\nhide (hide)\n\n( ==================== Hiding Words ========================== )\n\n( The words described here on out get more complex and will\nrequire more of an explanation as to how they work. )\n\n( ==================== Create Does> ========================== )\n\n( The following section defines a pair of words \"create\"\nand \"does>\" which are a powerful set of words that can be\nused to make words that can create other words. \"create\"\nhas both run time and compile time behavior, whilst \"does>\"\nonly works at compile time in conjunction with \"create\". These\ntwo words can be used to add constants, variables and arrays\nto the language, amongst other things.\n\nA simple version of create is as follows\n\n\t: create :: dolist , here 2 cells + , ' exit , 0 state ! ;\n\nBut this version is much more limited.\n\n\"create\"...\"does>\" is one of the constructs that makes Forth\nForth, it allows the creation of words which can define new\nwords in themselves, and thus allows us to extend the language\neasily. )\n\n: write-exit ( -- : A word that write exit into the dictionary )\n\t['] _exit , ;\n\n: write-compile, ( -- : A word that writes , into the dictionary )\n\t['] , , ;\n\n: create ( create a new work that pushes its data field )\n\t:: ( compile a word )\n\tdolit , ( write push into new word )\n\there 2 cells + , ( push a pointer to data field )\n\t(;) ; ( write exit, switch to command mode )\n\n: mark write-compile, ( Write in a place holder 0 and push a pointer to to be used by does> )\n\tdolit , write-exit write-compile, ( Write in an exit in the word we're compiling. )\n\t['] [ , ; ( Make sure to change the state back to command mode )\n\n\\ : ( hole-to-patch -- )\n\timmediate\n\t?comp\n\twrite-exit ( we don't want the defining word to exit, but the *defined* word to )\n\there swap ! ( patch in the code fields to point to )\n\tdolist , ; ( write a run in )\n\nhide{ write-compile, write-exit }hide\n\n( Now that we have create...does> we can use it to create\narrays, variables and constants, as we mentioned before. )\n\n: array ( u c\" xxx\" -- : create a named array of length u )\n\tcreate allot does> + ;\n\n: variable ( x c\" xxx\" -- : create a variable will initial value of x )\n\tcreate , does> ;\n\n\\ : constant ( x c\" xxx\" -- : create a constant with value of x )\n\\\tcreate , does> @ ;\n\n: table ( u c\" xxx\" --, Run Time: -- addr u : create a named table )\n\tcreate dup , allot does> dup @ ;\n\n: string ( u c\" xxx\" --, Run Time: -- c-addr u : create a named string )\n\tcreate dup , chars allot does> dup @ swap 1+ chars> swap ;\n\n\\ : +field \\ n <\"name\"> -- ; exec: addr -- 'addr\n\\ create over , +\n\\ does> @ + ;\n\\\n\\ : begin-structure \\ -- addr 0 ; -- size\n\\ \tcreate\n\\ \there 0 0 , \\ mark stack, lay dummy\n\\ \tdoes> @ ; \\ -- rec-len\n\\\n\\ : end-structure \\ addr n --\n\\ swap ! ; \\ set len\n\\\n\\ begin-structure point\n\\ \tpoint +field p.x\n\\ \tpoint +field p.y\n\\ end-structure\n\\\n\\ This should work...\n\\ : buffer: ( u c\" xxx\" --, Run Time: -- addr )\n\\\tcreate allot ;\n\n: 2constant\n\tcreate , , does> dup 1+ @ swap @ ;\n\n: 2variable\n\tcreate , , does> ;\n\n: enum ( x \" ccc\" -- x+1 : define a series of enumerations )\n\tdup constant 1+ ;\n\n( ==================== Create Does> ========================== )\n\n( ==================== Do ... Loop =========================== )\n\n( The following section implements Forth's do...loop\nconstructs, the word definitions are quite complex as it\ninvolves a lot of juggling of the return stack. Along with\nbegin...until do loops are one of the main looping constructs.\n\nUnlike begin...until do accepts two values a limit and a\nstarting value, they are also words only to be used within a\nword definition, some Forths extend the semantics so looping\nconstructs operate in command mode, this Forth does not do\nthat as it complicates things unnecessarily.\n\nExample:\n\n\t: example-1\n\t\t10 1 do\n\t\t\ti . i 5 > if cr leave then loop\n\t\t100 . cr ;\n\n\texample-1\n\nPrints:\n\t1 2 3 4 5 6\n\nIn \"example-1\" we can see the following:\n\n1. A limit, 10, and a start value, 1, passed to \"do\".\n2. A word called 'i', which is the current count of the loop.\n3. If the count is greater than 5, we call a word call\nLEAVE, this word exits the current loop context as well as\nthe current calling word.\n4. \"100 . cr\" is never called. This should be changed in\nfuture revision, but this version of leave exits the calling\nword as well.\n\n'i', 'j', and LEAVE *must* be used within a do...loop\nconstruct.\n\nIn order to remedy point 4. loop should not use branch but\ninstead should use a value to return to which it pushes to\nthe return stack )\n\n: (do)\n\tswap ( swap the limit and start )\n\tr> ( save our return stack to temporary variable )\n\t-rot ( limit start return -- return start limit )\n\t>r ( push limit onto return stack )\n\t>r ( push start onto return stack )\n\t>r ; ( restore our return address )\n\n: do immediate ( Run time: high low -- : begin do...loop construct )\n\t?comp\n\t['] (do) ,\n\tpostpone begin ;\n\n: (unloop) ( -- , R: i limit -- : remove limit and i from )\n\tr> ( save our return address )\n\trdrop ( pop off i )\n\trdrop ( pop off limit )\n\t>r ; ( restore our return stack )\n\n: (+loop) ( x -- bool : increment loop variable by x and test it )\n\tr@ 1- ( get the pointer to i )\n\t+! ( add value to it )\n\tr@ 1- @ ( find i again )\n\tr@ 2- @ ( find the limit value )\n\tu>= ;\n\n: (loop) ( -- bool : increment loop variable by 1 and test it )\n\tr@ 1- ( get the pointer to i )\n\t1+! ( add one to it )\n\tr@ 1- @ ( find the value again )\n\tr@ 2- @ ( find the limit value )\n\tu>= ;\n\n: loop ( -- : end do...loop construct )\n\timmediate ?comp ['] (loop) , postpone until ['] (unloop) , ;\n\n: +loop ( x -- : end do...+loop loop construct )\n\timmediate ?comp ['] (+loop) , postpone until ['] (unloop) , ;\n\n: leave ( -- , R: i limit return -- : break out of a do-loop construct )\n\t(unloop)\n\trdrop ; ( return to the caller's caller routine )\n\n: ?leave ( x -- , R: i limit return -- | i limit return : conditional leave )\n\tif\n\t\t(unloop)\n\t\trdrop ( return to the caller's caller routine )\n\tthen ;\n\n\\ @todo define '(i)', '(j)' and '(k)', then make their\n\\ wrappers, 'i', 'j' and 'k' call ?comp then compile a pointer\n\\ to the thing that implements them, likewise for leave,\n\\ loop and +loop.\n: i ( -- i : Get current, or innermost, loop index in do...loop construct )\n\tr> r> ( pop off return address and i )\n\ttuck ( tuck i away )\n\t>r >r ; ( restore return stack )\n\n: j ( -- j : Get outermost loop index in do...loop construct )\n\t4 rpick ;\n\n( This is a simple test function for the looping, for interactive\ntesting and debugging:\n : mm 5 1 do i . cr 4 1 do j . tab i . cr loop loop ; )\n\n: range ( nX nY -- nX nX+1 ... nY )\n\tnos1+ do i loop ;\n\n: repeater ( n0 X -- n0 ... nX )\n\t1 do dup loop ;\n\n: sum ( n0 ... nX X -- sum<0..X> )\n\t1 do + loop ;\n\n: mul ( n0 ... nX X -- mul<0..X> )\n\t1 do * loop ;\n\n: reverse ( x1 ... xn n -- xn ... x1 : reverse n items on the stack )\n\t0 do i roll loop ;\n\ndoer (banner)\nmake (banner) space\n\n: banner ( n -- : )\n\tdup 0<= if drop exit then\n\t0 do (banner) loop ;\n\n: zero ( -- : emit a single 0 character )\n\t[char] 0 emit ;\n\n: spaces ( n -- : print n spaces if n is greater than zero )\n\tmake (banner) space\n\tbanner ;\n\n: zeros ( n -- : print n spaces if n is greater than zero )\n\tmake (banner) zero\n\tbanner ;\n\nhide{ (banner) banner }hide\n\n( @todo check u for negative )\n: fill ( c-addr u char -- : fill in an area of memory with a character, only if u is greater than zero )\n\t-rot\n\t0 do 2dup i + c! loop\n\t2drop ;\n\n: default ( addr u n -- : fill in an area of memory with a cell )\n\t-rot\n\t0 do 2dup i cells + ! loop\n\t2drop ;\n\n: compare ( c-addr1 u1 c-addr2 u2 -- n : compare two strings, not quite compliant yet )\n\t>r swap r> min >r\n\tstart-address + swap start-address + r>\n\tmemory-compare ;\n\n: erase ( addr u : erase a block of memory )\n\t2chars> 0 fill ;\n\n: blank ( c-addr u : fills a string with spaces )\n\tbl fill ;\n\n( move should check that u is not negative )\n: move ( addr1 addr2 u -- : copy u words of memory from 'addr2' to 'addr1' )\n\t0 do\n\t\t2dup i + @ swap i + !\n\tloop\n\t2drop ;\n\n( It would be nice if move and cmove could share more code, as they do exactly\n the same thing but with different load and store functions, cmove> )\n: cmove ( c-addr1 c-addr2 u -- : copy u characters of memory from 'c-addr2' to 'c-addr1' )\n\t0 do\n\t\t2dup i + c@ swap i + c!\n\tloop\n\t2drop ;\n\n\n\n( ==================== Do ... Loop =========================== )\n\n( ==================== String Substitution =================== )\n\n: (subst) ( char1 char2 c-addr )\n\t3dup ( char1 char2 c-addr char1 char2 c-addr )\n\tc@ = if ( char1 char2 c-addr char1 )\n\t\tswap c! ( match, substitute character )\n\telse ( char1 char2 c-addr char1 )\n\t\t2drop ( no match )\n\tthen ;\n\n: subst ( c-addr u char1 char2 -- replace all char1 with char2 in string )\n\tswap\n\t2swap\n\t['] (subst) foreach 2drop ;\nhide (subst)\n\n0 variable c\n0 variable sub\n0 variable #sub\n\n: (subst-all) ( c-addr : search in sub\/#sub for a character to replace at c-addr )\n\tsub @ #sub @ bounds ( get limits )\n\tdo\n\t\tdup ( duplicate supplied c-addr )\n\t\tc@ i c@ = if ( check if match )\n\t\t\tdup\n\t\t\tc chars c@ swap c! ( write out replacement char )\n\t\tthen\n\tloop drop ;\n\n: subst-all ( c-addr1 u c-addr2 u char -- replace chars in str1 if in str2 with char )\n\tc chars c! #sub ! sub ! ( store strings away )\n\t['] (subst-all) foreach ;\n\nhide{ c sub #sub (subst-all) }hide\n\n( ==================== String Substitution =================== )\n\n0 variable column-counter\n4 variable column-width\n\n: column ( i -- )\t\n\tcolumn-width @ mod not if cr then ;\n\n: column.reset\t\t\n\t0 column-counter ! ;\n\n: auto-column\t\t\n\tcolumn-counter dup @ column 1+! ;\n\n0 variable x\n: x! ( x -- )\n\tx ! ;\n\n: x@ ( -- x )\n\tx @ ;\n\n: 2>r ( x1 x2 -- R: x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tswap\n\t\t>r\n\t\t>r\n\tx@ >r ; ( restore return address )\n\n: 2r> ( R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tr>\n\t\tr>\n\t\tswap\n\tx@ >r ; ( restore return address )\n\n: 2r@ ( -- x1 x2 , R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\tr> r>\n\t2dup\n\t>r >r\n\tswap\n\tx@ >r ; ( restore return address )\n\n: unused ( -- u : push the amount of core left )\n\tmax-core here - ;\n\n: accumulator ( initial \" ccc\" -- : make a word that increments by a value and pushes the result )\n\tcreate , does> tuck +! @ ;\n\n: counter ( n \" ccc\" --, Run Time: -- x : make a word that increments itself by one, starting from 'n' )\n\tcreate 1- , does> dup 1+! @ ;\n\n0 variable delim\n: accepter ( c-addr max delimiter -- i )\n\t( store a \"max\" number of chars at c-addr until \"delimiter\" encountered,\n\tthe number of characters stored is returned )\n\tdelim ! ( store delimiter used to stop string storage when encountered)\n\t0\n\tdo\n\t\tkey dup delim @ <>\n\t\tif\n\t\t\tover c! 1+\n\t\telse ( terminate string )\n\t\t\tdrop 0 swap c!\n\t\t\ti\n\t\t\tleave\n\t\tthen\n\tloop\n\t-18 throw ; ( read in too many chars )\nhide delim\n\n: skip ( char -- : read input until string is reached )\n\tkey drop >r 0 begin drop key dup rdup r> <> until rdrop ;\n\n: word ( c -- c-addr : parse until 'c' is encountered, push transient counted string )\n\ttib #tib 0 fill ( zero terminal input buffer so we NUL terminate string )\n\tdup skip tib 1+ c!\n\t>r\n\ttib 2+\n\t#tib 1-\n\tr> accepter 1+\n\ttib c!\n\ttib ;\nhide skip\n\n: accept ( c-addr +n1 -- +n2 : see accepter definition )\n\tnl accepter ;\n\n0xFFFF constant max-string-length\n\n: (.\") ( char -- c-addr u )\n\t( @todo This really needs simplifying, to do this\n\ta set of words that operate on a temporary buffer can\n\tbe used )\n\t( Write a string into word being currently defined, this\n\tcode has to jump over the string it has just put into the\n\tdictionary so normal execution of a word can continue. The\n\tlength and character address of the string are left on the\n\tstack )\n\t>r ( save delimiter )\n\t['] branch , ( write in jump, this will jump past the string )\n\t>mark ( make hole )\n\tdup 1+ chars> ( calculate address to write to )\n\tmax-string-length\n\tr> ( restore delimiter )\n\taccepter dup >r ( write string into dictionary, save index )\n\taligned 2dup size \/ ( stack: length hole char-len hole )\n\t1+ dup allot ( update dictionary pointer with string length )\n\t1+ swap ! ( write place to jump to )\n\tdrop ( do not need string length anymore )\n\t1+ chars> ( calculate place to print )\n\tr> ; ( restore index and address of string )\n\n: length ( c-addr u -- u : push the length of an ASCIIZ string )\n tuck 0 do dup c@ 0= if 2drop i leave then 1+ loop ;\n\n: asciiz? ( c-addr u -- : is a Forth string also a ASCIIZ string )\n\ttuck length <> ;\n\n: asciiz ( c-addr u -- : trim a string until NUL terminator )\n\t2dup length nip ;\n\n: (type) ( c-addr -- : emit a single character )\n\tc@ emit ;\n\n: type ( c-addr u -- : print out 'u' characters at c-addr )\n\t['] (type) foreach ;\nhide (type)\n\n: do-string ( char -- : write a string into the dictionary reading it until char is encountered )\n\t(.\")\n\tstate @ if swap [literal] [literal] then ;\n\n128 string sbuf\n: s\" ( \"ccc\" --, Run Time -- c-addr u )\n\tkey drop sbuf 0 fill sbuf [char] \" accepter sbuf drop swap ;\nhide sbuf\n\n( @todo these strings really need rethinking, state awareness needs to be removed... )\n: type,\n\tstate @ if ['] type , else type then ;\n\n: c\"\n\timmediate key drop [char] \" do-string ;\n\n: \"\n\timmediate key drop [char] \" do-string type, ;\n\n: sprint ( c -- : print out chars until 'c' is encountered )\n\tkey drop ( drop next space )\n\t>r ( save delimiter )\n\tbegin\n\t\tkey dup ( get next character )\n\t\trdup r> ( get delimiter )\n\t\t<> if emit 0 then\n\tuntil rdrop ;\n\n: .(\n\timmediate [char] ) sprint ;\nhide sprint\n\n: .\"\n\timmediate key drop [char] \" do-string type, ;\n\nhide type,\n\n( This word really should be removed along with any usages\nof this word, it is not a very \"Forth\" like word, it accepts\na pointer to an ASCIIZ string and prints it out, it also does\nnot checking of the returned values from write-file )\n: print ( c-addr -- : print out a string to the standard output )\n\t-1 over >r length r> swap stdout write-file 2drop ;\n\n: ok\n\t\" ok\" cr ;\n\n: empty-stack ( x-n ... x-0 -- : empty the variable stack )\n\tbegin depth while drop repeat ;\n\n: (quit) ( -- : do the work of quit, without the restart )\n\t0 `source-id ! ( set source to read from file )\n\t`stdin @ `fin ! ( read from stdin )\n\tpostpone [ ( back into command mode )\n\t['] interpret start! ; ( set interpreter starting word )\n\n: quit ( -- : Empty return stack, go back to command mode, read from stdin, interpret input )\n\t(quit)\n\t-1 restart ; ( restart the interpreter )\n\n: abort\n\t-1 throw ;\n\n: (abort\") ( do the work of abort )\n\t(quit)\n\t-2 throw ;\n\n: abort\" immediate\n\tpostpone \"\n\t['] cr , ['] (abort\") , ;\n\n\n( ==================== Error Messages ======================== )\n( This section implements a look up table for error messages,\nthe word MESSAGE was inspired by FIG-FORTH, words like ERROR\nwill be implemented later.\n\nThe DPANS standard defines a range of numbers which correspond\nto specific errors, the word MESSAGE can decode these numbers\nby looking up known words in a table.\n\nSee: http:\/\/lars.nocrew.org\/dpans\/dpans9.htm\n\n Code Reserved for\n ---- ------------\n -1 ABORT\n -2 ABORT\"\n -3 stack overflow\n -4 stack underflow\n -5 return stack overflow\n -6 return stack underflow\n -7 do-loops nested too deeply during execution\n -8 dictionary overflow\n -9 invalid memory address\n -10 division by zero\n -11 result out of range\n -12 argument type mismatch\n -13 undefined word\n -14 interpreting a compile-only word\n -15 invalid FORGET\n -16 attempt to use zero-length string as a name\n -17 pictured numeric output string overflow\n -18 parsed string overflow\n -19 definition name too long\n -20 write to a read-only location\n -21 unsupported operation [e.g., AT-XY on a\n too-dumb terminal]\n -22 control structure mismatch\n -23 address alignment exception\n -24 invalid numeric argument\n -25 return stack imbalance\n -26 loop parameters unavailable\n -27 invalid recursion\n -28 user interrupt\n -29 compiler nesting\n -30 obsolescent feature\n -31 >BODY used on non-CREATEd definition\n -32 invalid name argument [e.g., TO xxx]\n -33 block read exception\n -34 block write exception\n -35 invalid block number\n -36 invalid file position\n -37 file I\/O exception\n -38 non-existent file\n -39 unexpected end of file\n -40 invalid BASE for floating point conversion\n -41 loss of precision\n -42 floating-point divide by zero\n -43 floating-point result out of range\n -44 floating-point stack overflow\n -45 floating-point stack underflow\n -46 floating-point invalid argument\n -47 compilation word list deleted\n -48 invalid POSTPONE\n -49 search-order overflow\n -50 search-order underflow\n -51 compilation word list changed\n -52 control-flow stack overflow\n -53 exception stack overflow\n -54 floating-point underflow\n -55 floating-point unidentified fault\n -56 QUIT\n -57 exception in sending or receiving a character\n -58 [IF], [ELSE], or [THEN] exception )\n\n( The word X\" compiles a counted string into a word definition, it\nis useful as a space saving measure and simplifies our lookup table\ndefinition. Instead of having to store a C-ADDR and it's length, we\nonly have to store a C-ADDR in the lookup table, which occupies only\none element instead of two. The strings used for error messages are\nshort, so the limit of 256 characters that counted strings present\nis not a problem. )\n\n: x\" immediate ( c\" xxx\" -- c-addr : compile a counted string )\n\t[char] \" word ( read in a counted string )\n\tcount -1 \/string dup ( go back to start of string )\n\tpostpone never >r ( make a hole in the dictionary )\n\tchere >r ( character marker )\n\taligned chars allot ( allocate space in hole )\n\tr> dup >r -rot cmove ( copy string from word buffer )\n\tr> ( restore pointer to counted string )\n\tr> postpone then ; ( finish hole )\n\ncreate lookup 64 cells allot ( our lookup table )\n\n: nomsg ( -- c-addr : push counted string to undefined error message )\n\tx\" Undefined Error\" literal ;\n\nlookup 64 cells find nomsg default\n\n1 variable warning\n\n: message ( n -- : print an error message )\n\twarning @ 0= if . exit then\n\tdup -63 1 within if abs lookup + @ count type exit then\n\tdrop nomsg count type ;\n\n1 counter #msg\n\n: nmsg ( n -- : populate next slot in available in LOOKUP )\n\tlookup #msg cells + ! ;\n\nx\" ABORT\" nmsg\nx\" ABORT Double Quote\" nmsg\nx\" stack overflow\" nmsg\nx\" stack underflow\" nmsg\nx\" return stack overflow\" nmsg\nx\" return stack underflow\" nmsg\nx\" do-loops nested too deeply during execution\" nmsg\nx\" dictionary overflow\" nmsg\nx\" invalid memory address\" nmsg\nx\" division by zero\" nmsg\nx\" result out of range\" nmsg\nx\" argument type mismatch\" nmsg\nx\" undefined word\" nmsg\nx\" interpreting a compile-only word\" nmsg\nx\" invalid FORGET\" nmsg\nx\" attempt to use zero-length string as a name\" nmsg\nx\" pictured numeric output string overflow\" nmsg\nx\" parsed string overflow\" nmsg\nx\" definition name too long\" nmsg\nx\" write to a read-only location\" nmsg\nx\" unsupported operation \" nmsg\nx\" control structure mismatch\" nmsg\nx\" address alignment exception\" nmsg\nx\" invalid numeric argument\" nmsg\nx\" return stack imbalance\" nmsg\nx\" loop parameters unavailable\" nmsg\nx\" invalid recursion\" nmsg\nx\" user interrupt\" nmsg\nx\" compiler nesting\" nmsg\nx\" obsolescent feature\" nmsg\nx\" >BODY used on non-CREATEd definition\" nmsg\nx\" invalid name argument \" nmsg\nx\" block read exception\" nmsg\nx\" block write exception\" nmsg\nx\" invalid block number\" nmsg\nx\" invalid file position\" nmsg\nx\" file I\/O exception\" nmsg\nx\" non-existent file\" nmsg\nx\" unexpected end of file\" nmsg\nx\" invalid BASE for floating point conversion\" nmsg\nx\" loss of precision\" nmsg\nx\" floating-point divide by zero\" nmsg\nx\" floating-point result out of range\" nmsg\nx\" floating-point stack overflow\" nmsg\nx\" floating-point stack underflow\" nmsg\nx\" floating-point invalid argument\" nmsg\nx\" compilation word list deleted\" nmsg\nx\" invalid POSTPONE\" nmsg\nx\" search-order overflow\" nmsg\nx\" search-order underflow\" nmsg\nx\" compilation word list changed\" nmsg\nx\" control-flow stack overflow\" nmsg\nx\" exception stack overflow\" nmsg\nx\" floating-point underflow\" nmsg\nx\" floating-point unidentified fault\" nmsg\nx\" QUIT\" nmsg\nx\" exception in sending or receiving a character\" nmsg\nx\" [IF], [ELSE], or [THEN] exception\" nmsg\n\nhide{ nmsg #msg nomsg }hide\n \n\n( ==================== Error Messages ======================== )\n\n\n( ==================== CASE statements ======================= )\n( This simple set of words adds case statements to the\ninterpreter, the implementation is not particularly efficient,\nbut it works and is simple.\n\nBelow is an example of how to use the CASE statement,\nthe following word, \"example\" will read in a character and\nswitch to different statements depending on the character\ninput. There are two cases, when 'a' and 'b' are input, and\na default case which occurs when none of the statements match:\n\n\t: example\n\t\tchar\n\t\tcase\n\t\t\t[char] a of \" a was selected \" cr endof\n\t\t\t[char] b of \" b was selected \" cr endof\n\n\t\t\tdup \\ encase will drop the selector\n\t\t\t\" unknown char: \" emit cr\n\t\tendcase ;\n\n\texample a \\ prints \"a was selected\"\n\texample b \\ prints \"b was selected\"\n\texample c \\ prints \"unknown char: c\"\n\nOther examples of how to use case statements can be found\nthroughout the code.\n\nFor a simpler case statement see, Volume 2, issue 3, page 48\nof Forth Dimensions at http:\/\/www.forth.org\/fd\/contents.html )\n\n: case immediate\n\t?comp\n\t['] branch , 3 cells , ( branch over the next branch )\n\there ['] branch , ( mark: place endof branches back to with again )\n\t>mark swap ; ( mark: place endcase writes jump to with then )\n\n: over= ( x y -- [x 0] | 1 : )\n\tover = if drop 1 else 0 then ;\n\n: of\n\timmediate ?comp ['] over= , postpone if ;\n\n: endof\n\timmediate ?comp over postpone again postpone then ;\n\n: endcase\n\timmediate ?comp ['] drop , 1+ postpone then drop ;\n\n( ==================== CASE statements ======================= )\n\n( ==================== Conditional Compilation =============== )\n( The words \"[if]\", \"[else]\" and \"[then]\" implement conditional\ncompilation, they can be nested as well\n\nSee http:\/\/lars.nocrew.org\/dpans\/dpans15.htm for more\ninformation\n\nA much simpler conditional compilation method is the following\nsingle word definition:\n\n : compile-line? 0= if [ find \\\\ , ] then ;\n\nWhich will skip a line if a conditional is false, and compile\nit if true )\n\n( These words really, really need refactoring, I could use the newly defined\n \"defer\" to help out with this )\n0 variable nest ( level of [if] nesting )\n0 variable [if]-word ( populated later with \"find [if]\" )\n0 variable [else]-word ( populated later with \"find [else]\")\n: [then] immediate ;\n: reset-nest 1 nest ! ;\n: unnest? [ find [then] ] literal = if nest 1-! then ;\n: nest? [if]-word @ = if nest 1+! then ;\n: end-nest? nest @ 0= ;\n: match-[else]? [else]-word @ = nest @ 1 = and ;\n\n: [if] ( bool -- : conditional execution )\n\t?exec\n\tunless\n\t\treset-nest\n\t\tbegin\n\t\t\tfind\n\t\t\tdup nest?\n\t\t\tdup match-[else]? if drop exit then\n\t\t\t unnest?\n\t\t\tend-nest?\n\t\tuntil\n\tthen ;\n\n: [else] ( discard input until [then] encounter, nesting for [if] )\n\t?exec\n\treset-nest\n\tbegin\n\t\tfind\n\t\tdup nest? unnest?\n\t\tend-nest?\n\tuntil ;\n\nfind [if] [if]-word !\nfind [else] [else]-word !\n\n: ?( if postpone ( then ; \\ conditionally read until ')'\n: ?\\ if postpone \\ then ;\n: 16bit\\ size 2 <> if postpone \\ then ;\n: 32bit\\ size 4 <> if postpone \\ then ;\n: 64bit\\ size 8 <> if postpone \\ then ;\n\nhide{\n\t[if]-word [else]-word nest\n\treset-nest unnest? match-[else]?\n\tend-nest? nest?\n}hide\n\n( ==================== Conditional Compilation =============== )\n\n( ==================== Endian Words ========================== )\n( This words are allow the user to determinate the endianess\nof the machine that is currently being used to execute libforth,\nthey make heavy use of conditional compilation )\n\n0 variable x\n\nsize 2 = [if] 0x0123 x ! [then]\nsize 4 = [if] 0x01234567 x ! [then]\nsize 8 = [if] 0x01234567abcdef x ! [then]\n\nx chars> c@ 0x01 = constant endian\n\nhide{ x }hide\n\n: swap16 ( x -- x : swap the byte order of a 16 bit number )\n\tdup 256* 0xff00 and >r 256\/ lsb r> or ;\n\nsize 4 >= [if]\n\t: swap32\n\t\tdup 0xffff and swap16 16 lshift swap\n\t\t16 rshift 0xffff and swap16 or ;\n[then]\n\nsize 8 >= [if]\n\t: swap64 ( x -- x : swap the byte order of a 64 bit number )\n\t\t dup 0xffffffff and swap32 32 lshift swap\n\t\t 32 rshift 0xffffffff and swap32 or ;\n[then]\n\nsize 2 = [if]\n\tendian\n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order )\n\t\tswap16 ;\n\t: >big ( x -- x : host byte order to big endian order )\n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order )\n\t\t;\n\t: >big ( x -- x : host byte order to big endian order )\n\t\tswap16 ;\n\t[then]\n[then]\n\nsize 4 = [if]\n\tendian\n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order )\n\t\tswap32 ;\n\t: >big ( x -- x : host byte order to big endian order )\n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order )\n\t\t;\n\t: >big ( x -- x : host byte order to big endian order )\n\t\tswap32 ;\n\t[then]\n[then]\n\nsize 8 = [if]\n\tendian\n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order )\n\t\tswap64 ;\n\t: >big ( x -- x : host byte order to big endian order )\n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order )\n\t\t;\n\t: >big ( x -- x : host byte order to big endian order )\n\t\tswap64 ;\n\t[then]\n[then]\n\n( ==================== Endian Words ========================== )\n\n( ==================== Misc words ============================ )\n\n: (base) ( -- base : unmess up libforth's base variable )\n\tbase @ dup 0= if drop 10 then ;\n\n: #digits ( u -- u : number of characters needed to represent 'u' in current base )\n\tdup 0= if 1+ exit then\n\t(base) log 1+ ;\n\n: digits ( -- u : number of characters needed to represent largest unsigned number in current base )\n\t-1 #digits ;\n\n: cdigits ( -- u : number of characters needed to represent largest characters in current base )\n\t0xff #digits ;\n\n: .r ( u -- print a number taking up a fixed amount of space on the screen )\n\tdup #digits digits swap - spaces . ;\n\n: ?.r ( u -- : print out address, right aligned )\n\t@ .r ;\n\n0 variable counter\n\n: counted-column ( index -- : special column printing for dump )\n\tcounter @ column-width @ mod\n\tnot if cr .r \" :\" space else drop then\n\tcounter 1+! ;\n\n: .chars ( x n -- : print a cell out as characters, upto n chars )\n\t0 ( from zero to the size of a cell )\n\tdo\n\t\tdup ( copy variable to print out )\n\t\tsize i 1+ - select-byte ( select correct byte )\n\t\tdup printable? not ( is it not printable )\n\t\tif drop [char] . then ( print a '.' if it is not )\n\t\temit ( otherwise print it out )\n\tloop\n\tdrop ; ( drop cell we have printed out )\n\n: lister ( addr u addr -- )\n\t0 counter ! 1- swap\n\tdo\n\t\tdup counted-column 1+ i ?.r i @ size .chars space\n\tloop ;\n\n( @todo this function should make use of DEFER and IS, then different\nversion of dump could be made that swapped out LISTER )\n: dump ( addr u -- : dump out 'u' cells of memory starting from 'addr' )\n\t1+ over + under lister drop\n\tcr ;\n\nhide{ counted-column counter }hide\n\n( Fence can be used to prevent any word defined before it from being forgotten\nUsage:\n\there fence ! )\n0 variable fence\n\n: ?fence ( addr -- : throw an exception of address is before fence )\n\tfence @ u< if -15 throw then ;\n\n: (forget) ( pwd-token -- : forget a found word and everything after it )\n\tdup 0= if -15 throw then ( word not found! )\n\tdup ?fence\n\tdup @ pwd ! h ! ;\n\n: forget ( c\" xxx\" -- : forget word and every word defined after it )\n\tfind 1- (forget) ;\n\n0 variable fp ( FIND Pointer )\n\n: rendezvous ( -- : set up a rendezvous point )\n\there ?fence\n\there fence !\n\tlatest fp ! ;\n\n: retreat ( -- : retreat to the rendezvous point, forgetting any words )\n\tfence @ h !\n\tfp @ pwd ! ;\n\nhide{ fp }hide\n\n: marker ( c\" xxx\" -- : make word the forgets itself and words after it)\n\t:: latest [literal] ['] (forget) , (;) ;\nhere fence ! ( This should also be done at the end of the file )\nhide (forget)\n\n: ** ( b e -- x : exponent, raise 'b' to the power of 'e')\n\t?dup-if\n\t\tover swap\n\t\t1 do over * loop\n\t\tnip\n\telse\n\t\tdrop 1\n\tthen ;\n\n0 variable a\n0 variable b\n0 variable m\n: equal ( a1...an b1...bn n -- a1...an b1...bn bool : determine if two lists are equal )\n\t( example:\n\t\t1 2 3\n\t\t1 2 3\n\t\t3 equal\n\treturns: 1 )\n\tdup m ! 1+ 1 ( store copy of length and use as loop index )\n\tdo\n\t\ti 1- pick b ! ( store ith element of list in b1...bn )\n\t\ti m @ + 1- pick a ! ( store ith element of list in a1...an )\n\t\ta @ b @ <> ( compare a and b for equality )\n\t\tif 0 leave then ( unequal, finish early )\n\tloop 1 ; ( lists must be equal )\n\nhide{ a b m }hide\n\n: ndrop ( u1...un n -- : drop n items )\n\t?dup-if 0 do drop loop then ;\n\n: caesar ( c key -- o : encode a alphabetic character with a key using a generalization of the Caesar cipher )\n\t>r\n\tdup uppercase? if [char] A - r> + 26 mod [char] A + exit then\n\tdup lowercase? if [char] a - r> + 26 mod [char] a + exit then\n\trdrop ; ( it goes without saying that this should not be used for anything serious! )\n\n: caesar-type ( c-addr u key : type out encoded text with a Caesar cipher )\n\t-rot bounds do i c@ over caesar emit loop drop ;\n\n: rot13 ( c -- c : encode a character with ROT-13 )\n\t13 caesar ;\n\n: rot13-type ( c-addr u : print string in ROT-13 encoded form )\n\t13 caesar-type ;\n\n\\ s\" abcdefghijklmnopqrstuvwxyz\" rot13-type -> nopqrstuvwxyzabcdefghijklm\n\\ s\" hello\" rot13-type -> uryyb\n\n( ==================== Misc words ============================ )\n\n( ==================== Pictured Numeric Output =============== )\n( Pictured numeric output is what Forths use to display\nnumbers to the screen, this Forth has number output methods\nbuilt into the Forth kernel and mostly uses them instead,\nbut the mechanism is still useful so it has been added.\n\n@todo Pictured number output should act on a double cell\nnumber not a single cell number )\n\n0 variable hld\n\n: overflow ( -- : check if we overflow the hold area )\n \there chars> pad chars> hld @ - u> if -17 throw then ;\n\n: hold ( char -- : add a character to the numeric output string )\n\toverflow pad chars> hld @ - c! hld 1+! ;\n\n: holds ( c-addr u -- : hold an entire string )\n begin dup while 1- 2dup + c@ hold repeat 2drop ;\n\n: <# ( -- : setup pictured numeric output )\n\t0 hld ! ;\n\n: sign ( -- : add a sign to the pictured numeric output string )\n\t[char] - hold ;\n\n: # ( x -- x : divide x by base, turn into a character, put in pictured output string )\n\t(base) um\/mod swap\n \tdup 9 u>\n \tif 7 + then\n \t48 + hold ;\n\n: #s ( x -- 0 : repeatedly call # on x until x is zero )\n\tbegin # dup 0= until ;\n\n: #> ( -- c-addr u : end pictured output conversion, push output string to stack )\n\t0 hold ( NUL terminate string, just in case )\n\thld 1-! ( but do not include that in the count )\n\tpad chars> hld @\n\ttuck - 1+ swap ;\n\ndoer characters\nmake characters spaces\n\n: u.rc\n\t>r <# #s #> rot drop r> over - characters type ;\n\n: u.r ( u n -- print a number taking up a fixed amount of space on the screen )\n\tmake characters spaces u.rc ;\n\n: u.rz ( u n -- print a number taking up a fixed amount of space on the screen, using leading zeros )\n\tmake characters zeros u.rc ;\n\n: u. ( u -- : display an unsigned number in current base )\n\t0 u.r ;\n\nhide{ overflow u.rc characters }hide\n\n( ==================== Pictured Numeric Output =============== )\n\n( ==================== Numeric Input ========================= )\n( The Forth executable can handle numeric input and does not\nneed the routines defined here, however the user might want\nto write routines that use >NUMBER. >NUMBER is a generic word,\nbut it is a bit difficult to use on its own. )\n\n: map ( char -- n|-1 : convert character in 0-9 a-z range to number )\n\tdup lowercase? if [char] a - 10 + exit then\n\tdup decimal? if [char] 0 - exit then\n\tdrop -1 ;\n\n: number? ( char -- bool : is a character a number in the current base )\n\t>lower map (base) u< ;\n\n: >number ( n c-addr u -- n c-addr u : convert string )\n\tbegin\n\t\t( get next character )\n\t\t2dup >r >r drop c@ dup number? ( n char bool, R: c-addr u )\n\t\tif ( n char )\n\t\t\tswap (base) * swap map + ( accumulate number )\n\t\telse ( n char )\n\t\t\tdrop\n\t\t\tr> r> ( restore string )\n\t\t\texit\n\t\tthen\n\t\tr> r> ( restore string )\n\t\t1 \/string dup 0= ( advance string and test for end )\n\tuntil ;\n\nhide{ map }hide\n\n( ==================== Numeric Input ========================= )\n\n( ==================== ANSI Escape Codes ===================== )\n( Terminal colorization module, via ANSI Escape Codes\n\nsee: https:\/\/en.wikipedia.org\/wiki\/ANSI_escape_code\nThese codes will provide a relatively portable means of\nmanipulating a terminal )\n\n27 constant 'escape'\n: CSI 'escape' emit .\" [\" ;\n0 constant black\n1 constant red\n2 constant green\n3 constant yellow\n4 constant blue\n5 constant magenta\n6 constant cyan\n7 constant white\n: foreground 30 + ;\n: background 40 + ;\n0 constant dark\n1 constant bright\nfalse variable colorize\n\n: 10u. ( n -- : print a number in decimal )\n\tbase @ >r decimal u. r> base ! ;\n\n: color ( brightness color-code -- : set the terminal color )\n\t( set color on an ANSI compliant terminal,\n\tfor example:\n\t\tbright red foreground color\n\tsets the foreground text to bright red )\n\tcolorize @ 0= if 2drop exit then\n\tCSI 10u. if .\" ;1\" then .\" m\" ;\n\n: at-xy ( x y -- : set ANSI terminal cursor position to x y )\n\tCSI 10u. [char] ; emit 10u. .\" H\" ;\n\n: page ( -- : clear ANSI terminal screen and move cursor to beginning )\n\tCSI .\" 2J\" 1 1 at-xy ;\n\n: hide-cursor ( -- : hide the cursor from view )\n\tCSI .\" ?25l\" ;\n\n: show-cursor ( -- : show the cursor )\n\tCSI .\" ?25h\" ;\n\n: save-cursor ( -- : save cursor position )\n\tCSI .\" s\" ;\n\n: restore-cursor ( -- : restore saved cursor position )\n\tCSI .\" u\" ;\n\n: reset-color ( -- : reset terminal color to its default value)\n\tcolorize @ 0= if exit then\n\tCSI .\" 0m\" ;\n\nhide{ CSI 10u. }hide\n( ==================== ANSI Escape Codes ===================== )\n\n( ==================== Unit test framework =================== )\n\n256 string estring ( string to test )\n0 variable #estring ( actual string length )\n0 variable start ( starting depth )\n0 variable result ( result depth )\n0 variable check ( only check depth if -> is called )\n0 variable dictionary ( dictionary pointer on entering { )\n0 variable previous ( PWD register on entering { )\n\n: T ; ( hack until T{ can process words )\n\n: -> ( -- : save depth in variable )\n\t1 check ! depth result ! ;\n\n: test estring drop #estring @ ;\n\n: fail ( -- : invalidate the forth interpreter and exit )\n\tinvalidate bye ;\n\n: neutral ( -- : neutral color )\n\t;\n\n: bad ( -- : bad color )\n\tdark red foreground color ;\n\n: good ( -- : good color )\n\tdark green foreground color ;\n\n: die bad test type reset-color cr fail ;\n\n: evaluate? ( bool -- : test if evaluation has failed )\n\tif .\" evaluation failed\" cr fail then ;\n\n: failed bad .\" failed\" reset-color cr ;\n\n: adjust ( x -- x : adjust a depth to take into account starting depth )\n\tstart @ - ;\n\n: no-check? ( -- bool : if true we need to check the depth )\n\tcheck @ 0= ;\n\n: depth? ( -- : check if depth is correct )\n\tno-check? if exit then\n\tdepth adjust ( get depth and adjust for starting depth )\n\tresult @ adjust 2* = ( get results depth, same adjustment, should be\n\t half size of the depth )\n\tif exit then ( pass )\n\tfailed\n\t.\" Unequal depths:\" cr\n\t.\" depth: \" depth . cr\n\t.\" result: \" result @ . cr\n\tdie ;\n\n: equal? ( -- : determine if results equals expected )\n\tno-check? if exit then\n\tresult @ adjust equal\n\tif exit then\n\tfailed\n\t.\" Result is not equal to expected values. \" cr\n\t.\" Stack: \" cr .s cr\n\tdie ;\n\n: display ( c-addr u -- : print out testing message in estring )\n\tverbose if neutral type else 2drop then ;\n\n: pass ( -- : print out passing message )\n\tverbose if good .\" ok \" cr reset-color then ;\n\n: save ( -- : save current dictionary )\n\tpwd @ previous !\n\there dictionary ! ;\n\n: restore ( -- : restore dictionary )\n\tprevious @ pwd !\n\tdictionary @ h ! ;\n\n: T{ ( -- : perform a unit test )\n\tdepth start ! ( save start of stack depth )\n\t0 result ! ( reset result variable )\n\t0 check ! ( reset check variable )\n\testring 0 fill ( zero input string )\n\tsave ( save dictionary state )\n\tkey drop ( drop next character, which is a space )\n\testring [char] } accepter #estring ! ( read in string to test )\n\ttest display ( print which string we are testing )\n\ttest evaluate ( perform test )\n\tevaluate? ( evaluate successfully? )\n\tdepth? ( correct depth )\n\tequal? ( results equal to expected values? )\n\tpass ( print pass message )\n\trestore ( restore dictionary to previous state )\n\tno-check? if exit then\n\tresult @ adjust 2* ndrop ( remove items on stack generated by test )\n\t; \n\nT{ }T \nT{ -> }T\nT{ 1 -> 1 }T\nT{ 1 2 -> 1 2 }T\nT{ : c 1 2 ; c -> 1 2 }T\n\n( @bug ';' smudges the previous word, but :noname does\nnot. )\nT{ :noname 2 ; :noname 3 + ; compose execute -> 5 }T\n\nhide{\n\tpass test display\n\tadjust start save restore dictionary previous\n\tevaluate? equal? depth? estring #estring result\n\tcheck no-check? die neutral bad good failed\n}hide\n\n( ==================== Unit test framework =================== )\n\n\n( ==================== Pseudo Random Numbers ================= )\n( This section implements a Pseudo Random Number generator, it\nuses the xor-shift algorithm to do so.\nSee:\nhttps:\/\/en.wikipedia.org\/wiki\/Xorshift\nhttp:\/\/excamera.com\/sphinx\/article-xorshift.html\nhttp:\/\/xoroshiro.di.unimi.it\/\nhttp:\/\/www.arklyffe.com\/main\/2010\/08\/29\/xorshift-pseudorandom-number-generator\/\n\nThe constants used have been collected from various places\non the web and are specific to the size of a cell. )\n\nsize 2 = [if] 13 constant a 9 constant b 7 constant c [then]\nsize 4 = [if] 13 constant a 17 constant b 5 constant c [then]\nsize 8 = [if] 12 constant a 25 constant b 27 constant c [then]\n\n7 variable seed ( must not be zero )\n\n: seed! ( x -- : set the value of the PRNG seed )\n\tdup 0= if drop 7 ( zero not allowed ) then seed ! ;\n\n: random ( -- x : assumes word size is 32 bit )\n\tseed @\n\tdup a lshift xor\n\tdup b rshift xor\n\tdup c lshift xor\n\tdup seed! ;\n\nhide{ a b c seed }hide\n\n( ==================== Random Numbers ======================== )\n\n( ==================== Prime Numbers ========================= )\n( From original \"third\" code from the IOCCC at\nhttp:\/\/www.ioccc.org\/1992\/buzzard.2.design, the module works\nout and prints prime numbers. )\n\n: prime? ( u -- u | 0 : return number if it is prime, zero otherwise )\n\tdup 1 = if 1- exit then\n\tdup 2 = if exit then\n\tdup 2\/ 2 ( loop from 2 to n\/2 )\n\tdo\n\t\tdup ( value to check if prime )\n\t\ti mod ( mod by divisor )\n\t\tnot if\n\t\t\tdrop 0 leave\n\t\tthen\n\tloop ;\n\n0 variable counter\n\n: primes ( x1 x2 -- : print the primes from x2 to x1 )\n\t0 counter !\n\t\" The primes from \" dup . \" to \" over . \" are: \"\n\tcr\n\tcolumn.reset\n\tdo\n\t\ti prime?\n\t\tif\n\t\t\ti . counter @ column counter 1+!\n\t\tthen\n\tloop\n\tcr\n\t\" There are \" counter @ . \" primes.\"\n\tcr ;\n\nhide{ counter }hide\n( ==================== Prime Numbers ========================= )\n\n( ==================== Debugging info ======================== )\n( This section implements various debugging utilities that the\nprogrammer can use to inspect the environment and debug Forth\nwords. )\n\n( String handling should really be done with PARSE, and CMOVE )\n: sh ( cnl -- ior : execute a line as a system command )\n\tnl word count system ;\n\nhide{ .s }hide\n: .s ( -- : print out the stack for debugging )\n\t[char] < emit depth (.) drop [char] > emit space\n\tdepth if\n\t\tdepth 0 do i column tab depth i 1+ - pick . loop\n\tthen\n\tcr ;\n\n1 variable hide-words ( do we want to hide hidden words or not )\n\n: name ( PWD -- c-addr : given a pointer to the PWD field of a word get a pointer to the name of the word )\n\tdup 1+ @ 256\/ word-mask and lsb - chars> ;\n\n( This function prints out all of the defined words, excluding\nhidden words. An understanding of the layout of a Forth word\nhelps here. The dictionary contains a linked list of words,\neach forth word has a pointer to the previous word until the\nfirst word. The layout of a Forth word looks like this:\n\nNAME: Forth Word - A variable length ASCII NUL terminated\n string.\nPWD: Previous Word Pointer, points to the previous\n word.\nCODE: Flags, code word and offset from previous word\n pointer to start of Forth word string.\nDATA: The body of the forth word definition, not interested\n in this.\n\nThere is a register which stores the latest defined word which\ncan be accessed with the code \"pwd @\". In order to print out\na word we need to access a words CODE field, the offset to\nthe NAME is stored here in bits 8 to 14 and the offset is\ncalculated from the PWD field.\n\n\"print\" expects a character address, so we need to multiply\nany calculated address by the word size in bytes. )\n\n: words.immediate ( bool -- : emit or mark a word being printed as being immediate )\n\tnot if dark red foreground color then ;\n\n: words.defined ( bool -- : emit or mark a word being printed as being a built in word )\n\tnot if bright green background color then ;\n\n: words.hidden ( bool -- : emit or mark a word being printed as being a hidden word )\n\tif dark magenta foreground color then ;\n\n: words ( -- : print out all defined an visible words )\n\tlatest\n\tspace\n\tbegin\n\t\tdup\n\t\thidden? hide-words @ and\n\t\tnot if\n\t\t\thidden? words.hidden\n\t\t\tcompiling? words.immediate\n\t\t\tdup defined-word? words.defined\n\t\t\tname\n\t\t\tprint space\n\t\t\treset-color\n\t\telse\n\t\t\tdrop\n\t\tthen\n\t\t@ ( Get pointer to previous word )\n\t\tdup dictionary-start u< ( stop if pwd no longer points to a word )\n\tuntil\n\tdrop cr ;\n\n( Simpler version of words\n: words\n\tpwd @\n\tbegin\n\t\tdup name print space @ dup dictionary-start u<\n\tuntil drop cr ; )\n\nhide{ words.immediate words.defined words.hidden hidden? hidden-bit }hide\n\n: TrueFalse ( bool -- : print true or false )\n\tif \" true\" else \" false\" then ;\n\n: registers ( -- : print out important registers and information about the virtual machine )\n\t\" return stack pointer: \" r@ . cr\n\t\" dictionary pointer \" here . cr\n\t\" previous word: \" pwd ? cr\n\t\" state: \" state ? cr\n\t\" base: \" base ? cr\n\t\" depth: \" depth . cr\n\t\" cell size (in bytes): \" size . cr\n\t\" last cell address: \" max-core . cr\n\t\" unused cells: \" unused . cr\n\t\" invalid: \" `invalid @ TrueFalse cr\n\t\" size of variable stack: \" `stack-size ? cr\n\t\" size of return stack: \" `stack-size ? cr\n\t\" start of variable stack: \" max-core `stack-size @ 2* - . cr\n\t\" start of return stack: \" max-core `stack-size @ - . cr\n\t\" current input source: \" source-id -1 = if \" string\" else \" file\" then cr\n\t\" tracing on: \" `debug @ TrueFalse cr\n\t\" starting word: \" `instruction ? cr\n\t\" real start address: \" `start-address ? cr\n\t\" error handling: \" `error-handler ? cr\n\t\" throw handler: \" `handler ? cr\n\t\" signal recieved: \" `signal ? cr ;\n\t\n( `sin `sidx `slen `fout\n `stdout `stderr `argc `argv )\n\n\n: y\/n? ( -- bool : ask a yes or no question )\n\tkey drop\n\t\" y\/n? \"\n\tbegin\n\t\tkey\n\t\tdup\n\t\t[char] y = if true exit then\n\t\t[char] n = if false exit then\n\t\t\" y\/n? \"\n\tagain ;\n\n: step\n\t( step through a word: this word could be augmented\n\twith commands such as \"dump\", \"halt\", and optional\n\t\".s\" and \"registers\" )\n\tregisters\n\t\" .s: \" .s cr\n\t\" -- press any key to continue -- \"\n\tkey drop ;\n\n: more ( -- : wait for more input )\n\t\" -- press any key to continue -- \" key drop cr page ;\n\n: debug-help ( -- : print out the help for the debug command )\n \" debug mode commands\n\th - print help\n\tq - exit interpreter word\n\tr - print registers\n\ts - print stack\n\tR - print return stack\n\tc - continue on with execution\n\" ;\n\ndoer debug-prompt\n: prompt-default\n\t.\" debug> \" ;\n\nmake debug-prompt prompt-default\n\n: debug ( -- : enter interactive debug prompt )\n\tcr\n\t\" Entered Debug Prompt. Type 'h' for help. \" cr\n\tbegin\n\t\tkey\n\t\tcase\n\t\t\tnl of debug-prompt endof\n\t\t\t[char] h of debug-help endof\n\t\t\t[char] q of bye endof\n\t\t\t[char] r of registers endof\n\t\t\t[char] s of .s endof\n\t\t\t[char] R of r.s endof\n\t\t\t[char] c of exit endof\n\t\t\t( @todo add throw here )\n\t\tendcase\n\tagain ;\nhide debug-prompt\n\n: code>pwd ( CODE -- PWD\/0 : calculate PWD from code address )\n\tdup dictionary-start here within not if drop 0 exit then\n\t1 cells - ;\n\n: word-printer ( CODE -- : print out a words name given its code field )\n\tdup 1 cells - @ -1 = if . \" noname\" exit then ( nonames are marked by a -1 before its code field )\n\tdup code>pwd ?dup-if .d name print else drop \" data\" then\n\t drop ;\n\nhide{ code>pwd }hide\n\n( these words push the execution tokens for various special\ncases for decompilation )\n: get-branch [ find branch ] literal ;\n: get-?branch [ find ?branch ] literal ;\n: get-original-exit [ find _exit ] literal ;\n: get-quote [ find ' ] literal ;\n\n( @todo replace 2- nos1+ nos1+ with appropriate word, like\nthe string word that increments a string by an amount, but\nthat operates on CELLS )\n: branch-increment ( addr branch -- increment : calculate decompile increment for \"branch\" )\n\t1+ dup negative?\n\tif\n\t\tover cr . [char] : emit space . cr 2\n\telse\n\t\t2dup 2- nos1+ nos1+ dump\n\tthen ;\n\n( these words take a code field to a primitive they implement,\ndecompile it and any data belonging to that operation, and push\na number to increment the decompilers code stream pointer by )\n\n: decompile-literal ( code -- increment )\n\t1+ ? \" literal\" 2 ;\n\n: decompile-branch ( code -- increment )\n\tdark red foreground color\n\t1+ ? \" branch \" dup 1+ @ branch-increment ;\n\n: decompile-quote ( code -- increment )\n\tdark green foreground color\n\tdup\n\t[char] ' emit 1+ @ word-printer 2 reset-color ;\n\n: decompile-?branch ( code -- increment )\n\t1+ ? \" ?branch\" 2 ;\n\n: decompile-exit ( code -- 0 )\n\t\" _exit\" cr \" End of word: \" . 0 ;\n\n( The decompile word expects a pointer to the code field of\na word, it decompiles a words code field, it needs a lot of\nwork however. There are several complications to implementing\nthis decompile function.\n\n\t'\t The next cell should be pushed\n\n\t:noname This has a marker before its code field of\n\t -1 which cannot occur normally, this is\n\t handled in word-printer\n\n\tbranch\t branches are used to skip over data, but\n\t also for some branch constructs, any data\n\t in between can only be printed out\n\t generally speaking\n\n\texit\t There are two definitions of exit, the one\n\t used in ';' and the one everything else uses,\n\t this is used to determine the actual end\n\t of the word\n\n\tliterals Literals can be distinguished by their\n\t low value, which cannot possibly be a word\n\t with a name, the next field is the\n\t actual literal\n\nOf special difficult is processing IF, THEN and ELSE\nstatements, this will require keeping track of '?branch'.\n\nAlso of note, a number greater than \"here\" must be data )\n\n: decompile ( code-pointer -- code-pointer increment|0 : )\n\t.d [char] : emit space dup @\n\tcase\n\t\tdolit of dup decompile-literal cr endof\n\t\tget-branch of dup decompile-branch endof\n\t\tget-quote of dup decompile-quote cr endof\n\t\tget-?branch of dup decompile-?branch cr endof\n\t\tget-original-exit of dup decompile-exit endof\n\t\tdup word-printer 1 swap cr\n\tendcase reset-color ;\n\n: decompiler ( code-field-ptr -- : decompile a word in its entirety )\n\tbegin decompile over + tuck = until drop ;\n\nhide{\n\tword-printer get-branch get-?branch get-original-exit\n\tget-quote branch-increment decompile-literal\n\tdecompile-branch decompile-?branch decompile-quote\n\tdecompile-exit\n}hide\n\n( these words expect a pointer to the PWD field of a word )\n: see.name \" name: \" name print cr ;\n: see.start \" word start: \" name chars . cr ;\n: see.previous \" previous word: \" @ . cr ;\n: see.immediate \" immediate: \" compiling? nip not TrueFalse cr ;\n: see.instruction \" instruction: \" xt-instruction . cr ;\n: see.defined \" defined: \" defined-word? TrueFalse cr ;\n\n: see.header ( PWD -- is-immediate-word? )\n\tdup see.name\n\tdup see.start\n\tdup see.previous\n\tdup see.immediate\n\tdup see.instruction ( @todo look up instruction name )\n\tsee.defined ;\n\n( @todo This does not work for all words, so needs fixing.\n Specifically:\n\n\t2variable\n\t2constant\n\ttable\n\tconstant\n\tvariable\n\tarray\nWhich are all complex CREATE words\n\nA good way to test decompilation is with the following\nUnix pipe:\n\n\t.\/forth -f forth.fth -e words\n\t\t| sed 's\/ \/ see \/g'\n\t\t| .\/forth -t forth.fth &> decompiled.log\n)\n\n( @todo refactor into word that takes a PWD pointer and one that attempts to parse\/find name )\n: see ( c\" xxx\" -- : decompile a word )\n\tfind\n\tdup 0= if -32 throw then\n\tcell- ( move to PWD field )\n\tdup see.header\n\tdup defined-word?\n\tif ( decompile if a compiled word )\n\t\t2 cells + ( move to code field )\n\t\t\" code field:\" cr\n\t\tdecompiler\n\telse ( the instruction describes the word if it is not a compiled word )\n\t\tdup 1 cells + @ instruction-mask and doconst = if ( special case for constants )\n\t\t\t\" constant: \" 2 cells + @ .\n\t\telse\n\t\t\tdrop\n\t\tthen\n\tthen cr ;\n\n( @todo This has a bug, if any data within a word happens\nto match the address of _exit word.end calculates the wrong\naddress, this needs to mirror the DECOMPILE word )\n: word.end ( addr -- addr : find the end of a word )\n\tbegin\n\t\tdup\n\t\t@ [ find _exit ] literal = if exit then\n\t\tcell+\n\tagain ;\n\n: (inline) ( xt -- : inline an word from its execution token )\n\tdup cell- defined-word? if\n\t\tcell+\n\t\tdup word.end over - here -rot dup allot move\n\telse\n\t\t,\n\tthen ;\n\n: ;inline ( -- : terminate :inline )\n\timmediate -22 throw ;\n\n: :inline immediate\n\t?comp\n\tbegin\n\t\tfind found?\n\t\tdup [ find ;inline ] literal = if\n\t\t\tdrop exit ( terminate :inline )\n\t\tthen\n\t\t(inline)\n\tagain ;\n\nhide{\n\tsee.header see.name see.start see.previous see.immediate\n\tsee.instruction defined-word? see.defined _exit found?\n\t(inline) word.end\n}hide\n\n( These help messages could be moved to blocks, the blocks\ncould then be loaded from disk and printed instead of defining\nthe help here, this would allow much larger help )\n\n: help ( -- : print out a short help message )\n\tpage\n\tkey drop\n\" Welcome to Forth, an imperative stack based language. It is\nboth a low level and a high level language, with a very small\nmemory footprint. Most of Forth is defined as a combination\nof various primitives.\n\nA short description of the available function (or Forth words)\nfollows, words marked (1) are immediate and cannot be used in\ncommand mode, words marked with (2) define new words. Words\nmarked with (3) have both command and compile functionality.\n\n\"\nmore \" Some of the built in words that accessible are:\n\n(1,2)\t: define a new word, switching to compile mode\n\timmediate make latest defined word immediate\n\tread read in a word, execute in command mode else compile\n\t@ ! fetch, store\n\tc@ c! character based fetch and store\n\t- + * \/ standard arithmetic operations,\n\tand or xor invert standard bitwise operations\n\tlshift rshift left and right bit shift\n\tu< u> < > = comparison predicates\n\texit exit from a word\n\temit print character from top of stack\n\tkey get a character from input\n\tr> >r pop a value from or to the return stack\n\tfind find a word in the dictionary and push the location\n\t' store the address of the following word on the stack\n\t, write the top of the stack to the dictionary\n\tswap swap first two values on the stack\n\tdup duplicate the top of the stack\n\tdrop pop and drop a value\n\tover copy the second stack value over the first\n\t. pop the top of the stack and print it\n\"\nmore \"\n\tprint print a NUL terminated string at a character address\n\tdepth get the current stack depth\n\tclock get the time since execution start in milliseconds\n\tevaluate evaluate a string\n\tsystem execute a system command\n\tclose-file close a file handle\n\topen-file open a file handle\n\tdelete-file delete a file off disk given a string\n\tread-file read in characters from a file\n\twrite-file write characters to a file\n\tfile-position get the file offset\n\treposition-file reposition the file pointer\n\tflush-file flush a file to disk\n\trename-file rename a file on disk\n \"\n\nmore \" All of the other words in the interpreter are built\nfrom these primitive words. A few examples:\n\n(1)\tif...else...then FORTH branching construct\n(1)\tbegin...until loop until top of stack is non zero\n(1)\tbegin...again infinite loop\n(1)\tdo...loop FORTH looping construct\n(2,3)\tcreate create a new word that pushes its location\n(1)\tdoes> declare a created words run time behaviour\n(1,2)\tvariable declare variable with initial value from top of stack\n(1,2)\tconstant declare a constant, taken from top of stack\n(1,2)\tarray declare an array with size taken from top of stack\n(1)\t; terminate a word definition and return to command mode\n\twords print out a list of all the defined words\n\thelp this help message\n\tdump print out memory contents starting at an address\n\tregisters print out the contents of the registers\n\tsee decompile a word, viewing what words compose it\n\t.s print out the contents of the stack\n\n\"\n\nmore \" Some more advanced words:\n\n\there push the dictionary pointer\n\th push the address of the dictionary pointer\n\tr push the return stack pointer\n\tallot allocate space in the dictionary\n(1)\t[ switch to command mode\n\t] switch to compile mode\n\t:: compile ':' into the dictionary\n\n\" more \"\nFor more information either consult the manual pages forth(1)\nand libforth(1) or consult the following sources:\n\n\thttps:\/\/github.com\/howerj\/libforth\n\thttp:\/\/work.anapnea.net\/html\/html\/projects.html\n\nAnd for a larger tutorial:\n\n\thttps:\/\/github.com\/howerj\/libforth\/blob\/master\/readme.md\n\nFor resources on Forth:\n\n\thttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\thttps:\/\/rwmj.wordpress.com\/2010\/08\/07\/jonesforth-git-repository\/\n\n -- end --\n\" cr\n;\n\n( ==================== Debugging info ======================== )\n\n( ==================== Files ================================= )\n( These words implement more of the standard file access words\nin terms of the ones provided by the virtual machine. These\nwords are not the most easy to use words, although the ones\ndefined here and the ones that are part of the interpreter are\nthe standard ones.\n\nSome thoughts:\n\nI believe extensions to this word set, once I have figured\nout the semantics, should be made to make them easier to use,\nones which automatically clean up after failure and call throw\nwould be more useful [and safer] when dealing with a single\ninput or output stream. The most common action after calling\none of the file access words is to call throw any way.\n\nFor example, a word like:\n\n\t: #write-file \\ c-addr u fileid -- fileid u\n\t\tdup >r\n\t\twrite-file dup if r> close-file throw throw then\n\t\tr> swap ;\n\nWould be easier to deal with, it preserves the file identifier\nand throws if there is any problem. It would be a bit more\ndifficult to use when there are two files open at a time.\n\n@todo implement the other file access methods in terms of the\nbuilt in ones.\n@todo read-line and write-line need their flag and ior setting\ncorrectly\n\n\tFILE-SIZE [ use file-positions ]\n\nAlso of note, Source ID needs extending.\n\nSee: [http:\/\/forth.sourceforge.net\/std\/dpans\/dpans11.htm] )\n\n: read-char ( c-addr fileid -- ior : read a char )\n\t1 swap read-file 0<> swap 1 <> or ;\n\n0 variable x\n\n: getchar ( fileid -- char ior )\n\tx chars> swap read-char x chars> c@ swap ;\n\n: write-char ( c-addr fileid -- ior : write a char )\n\t1 swap write-file 0<> swap 1 <> or ;\n\n: putchar ( char fileid -- ior )\n\tswap x chars> c! x chars> swap write-char ;\n\n\\ @todo This shouldn't affect the file position indicator.\n\\ @todo This doesn't return a sensible error indicator.\n\\ : file-size ( fileid -- ud ior )\n\\\t0 swap\n\\\tbegin dup getchar nip 0= while nos1+ repeat drop ;\n\n\nhide{ x }hide\n\n: rewind-file ( file-id -- : rewind a file to the beginning )\n\t0 reposition-file throw ;\n\n: read-line ( c-addr u1 fileid -- u2 flag ior : read in a line of text )\n\t-rot bounds\n\tdo\n\t\tdup i swap read-char drop\n\t\ti c@ nl = if drop i 0 0 leave then\n\tloop drop ;\n\n: write-line ( c-addr u fileid -- u2 flag ior : write a line of text )\n\t-rot bounds\n\tdo\n\t\tdup i swap write-char drop\n\t\ti c@ nl = if drop i 0 0 leave then\n\tloop ;\n\n: resize-file ( ud fileid -- ior : attempt to resize a file )\n\t( There is no portable way to truncate a file :C )\n\t2drop -1 ( -1 to indicate failure ) ;\n\n: create-file ( c-addr u fam -- fileid ior )\n\t>r 2dup w\/o open-file throw close-file throw\n\tr> open-file ;\n\n: include-file ( file-id -- : evaluate a file )\n\tdup >r 0 1 evaluator r> close-file throw throw ;\n\n: included ( c-addr u -- : attempt to open up a name file and evaluate it )\n\tr\/o open-file throw\n\tinclude-file ;\n\n: include ( c\" ccc\" -- : attempt to evaluate a named file )\n\t( @bug requires trailing space, should use parse-name )\n\tbl word count included ;\n\n: bin ( fam1 -- fam2 : modify a file access method to be binary not line oriented )\n\t( Do nothing, all file access methods are binary )\n\t;\n\n( ==================== Files ================================= )\n\n( ==================== Matcher =============================== )\n( The following section implements a very simple regular\nexpression engine, which expects an ASCIIZ Forth string. It\nis translated from C code and performs an identical function.\n\nThe regular expression language is as follows:\n\n\tc\tmatch a literal character\n\t.\tmatch any character\n\t*\tmatch any characters\n\nThe \"*\" operator performs the same function as \".*\" does in\nmost other regular expression engines. Most other regular\nexpression engines also do not anchor their selections to the\nbeginning and the end of the string to match, instead using\nthe operators '^' and '$' to do so, to emulate this behavior\n'*' can be added as either a suffix, or a prefix, or both,\nto the matching expression.\n\nAs an example \"*, World!\" matches both \"Hello, World!\" and\n\"Good bye, cruel World!\". \"Hello, ....\" matches \"Hello, Bill\"\nand \"Hello, Fred\" but not \"Hello, Tim\" as there are two few\ncharacters in the last string.\n\n@todo make a matcher that expects a Forth string, which do\nnot have to be NUL terminated )\n\n\\ Translated from http:\/\/c-faq.com\/lib\/regex.html\n\\ int match(char *pat, char *str)\n\\ {\n\\ \tswitch(*pat) {\n\\ \tcase '\\0': return !*str;\n\\ \tcase '*': return match(pat+1, str) || *str && match(pat, str+1);\n\\ \tcase '.': return *str && match(pat+1, str+1);\n\\ \tdefault: return *pat == *str && match(pat+1, str+1);\n\\ \t}\n\\ }\n\n: *pat ( regex -- regex char : grab next character of pattern )\n\tdup c@ ;\n\n: *str ( string regex -- string regex char : grab next character string to match )\n\tover c@ ;\n\n: pass ( c-addr1 c-addr2 -- bool : pass condition, characters matched )\n\t2drop 1 ;\n\n: reject ( c-addr1 c-addr2 -- bool : fail condition, character not matched )\n\t2drop 0 ;\n\n: *pat==*str ( c-addr1 c-addr2 -- c-addr1 c-addr2 bool )\n\t2dup c@ swap c@ = ;\n\n: ++ ( u1 u2 u3 u4 -- u1+u3 u2+u4 : not quite d+ [does no carry] )\n\tswap >r + swap r> + swap ;\n\ndefer matcher\n\n: advance ( string regex char -- bool : advance both regex and string )\n\tif 1 1 ++ matcher else reject then ;\n\n: advance-string ( string regex char -- bool : advance only the string )\n\tif 1 0 ++ matcher else reject then ;\n\n: advance-regex ( string regex -- bool : advance matching )\n\t2dup 0 1 ++ matcher if pass else *str advance-string then ;\n\n: match ( string regex -- bool : match a ASCIIZ pattern against an ASCIIZ string )\n\t( @todo Add limits and accept two Forth strings, making sure they are both\n\t ASCIIZ strings as well\n\t @warning This uses a non-standards compliant version of case! )\n\t*pat\n\tcase\n\t\t 0 of drop c@ not endof\n\t\t[char] * of advance-regex endof\n\t\t[char] . of *str advance endof\n\t\t\n\t\tdrop *pat==*str advance exit\n\n\tendcase ;\n\nmatcher is match\n\nhide{\n\t*str *pat *pat==*str pass reject advance\n\tadvance-string advance-regex matcher ++\n}hide\n\n( ==================== Matcher =============================== )\n\n\n( ==================== Cons Cells ============================ )\n( From http:\/\/sametwice.com\/cons.fs, this could be improved\nif the optional memory allocation words were added to\nthe interpreter. This provides a simple \"cons cell\" data\nstructure. There is currently no way to free allocated\ncells. I do not think this is particularly useful, but it is\ninteresting. )\n\n: car! ( value cons-addr -- : store a value in the car cell of a cons cell )\n\t! ;\n\n: cdr! ( value cons-addr -- : store a value in the cdr cell of a cons cell )\n\tcell+ ! ;\n\n: car@ ( cons-addr -- car-val : retrieve car value from cons cell )\n\t@ ;\n\n: cdr@ ( cons-addr -- cdr-val : retrieve cdr value from cons cell )\n\tcell+ @ ;\n\n: cons ( car-val cdr-val -- cons-addr : allocate a new cons cell )\n\tswap here >r , , r> ;\n\n: cons0 0 0 cons ;\n\n( ==================== Cons Cells ============================ )\n\n( ==================== License =============================== )\n( The license has been chosen specifically to make this library\nand any associated programs easy to integrate into arbitrary\nproducts without any hassle. For the main libforth program\nthe LGPL license would have been also suitable [although it\nis MIT licensed as well], but to keep confusion down the same\nlicense, the MIT license, is used in both the Forth code and\nC code. This has not been done for any ideological reasons,\nand I am not that bothered about licenses. )\n\n: license ( -- : print out license information )\n\"\nThe MIT License (MIT)\n\nCopyright (c) 2016, 2017 Richard James Howe\n\nPermission is hereby granted, free of charge, to any person\nobtaining a copy of this software and associated documentation\nfiles (the 'Software'), to deal in the Software without\nrestriction, including without limitation the rights to use,\ncopy, modify, merge, publish, distribute, sublicense, and\/or\nsell copies of the Software, and to permit persons to whom\nthe Software is furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY\nKIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\nWARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE\nAND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\nHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE\nOR OTHER DEALINGS IN THE SOFTWARE.\n\n\"\n;\n\n( ==================== License =============================== )\n\n( ==================== Core utilities ======================== )\n( Read the header of a core file and process it, printing the\nresults out )\n\n8 constant header-size ( size of Forth core file header )\n8 constant size-field-size ( the size in bytes of the size field in the core file )\n0 variable core-file ( core fileid we are reading in )\n0 variable core-cell-size ( cell size of Forth core )\n0 variable core-version ( version of core file )\n0 variable core-endianess ( endianess of core we are reading in )\n\n( save space to read in header )\ncreate header header-size chars allot\n: cheader ( -- c-addr : header char address )\n\theader chars> ;\ncreate size-field size-field-size chars allot\n: csize-field ( -- c-addr : address of place size field is stored in )\n\tsize-field chars> ;\n\n0\nenum header-magic0 ( magic number 0 : FF )\nenum header-magic1 ( magic number 1 : '4' )\nenum header-magic2 ( magic number 2 : 'T' )\nenum header-magic3 ( magic number 3 : 'H' )\nenum header-cell-size ( size of a forth cell, either 2, 4 or 8 bytes )\nenum header-version ( version of the forth core )\nenum header-endianess ( endianess of the core )\nenum header-log2size ( binary logarithm of the core size )\n\n: cleanup ( -- : cleanup before abort )\n\tcore-file @ ?dup 0<> if close-file drop then ;\n\n: invalid-header ( bool -- : abort if header is invalid )\n\t<> if cleanup abort\" invalid header\" then ;\n\n: save-core-cell-size ( char -- : save the core file cell size, checking if it is valid )\n\tcore-cell-size !\n\t\" cell size:\" tab\n\tcore-cell-size @ 2 = if 2 . cr exit then\n\tcore-cell-size @ 4 = if 4 . cr exit then\n\tcore-cell-size @ 8 = if 8 . cr exit then\n\tcleanup core-cell-size @ . abort\" : invalid cell size\" ;\n\n: check-version-compatibility ( char -- : checks the version compatibility of the core file )\n\tcore-version !\n\tcore-version @ version = if \" version: \" version . cr exit then\n\tcleanup core-version @ . abort\" : unknown version number\" ;\n\n: save-endianess ( char -- : save the endianess, checking if it is valid )\n\tcore-endianess !\n\t\" endianess:\" tab\n\tcore-endianess @ 0 = if \" big\" cr exit then\n\tcore-endianess @ 1 = if \" little\" cr exit then\n\tcleanup core-endianess @ . abort\" invalid endianess\" then ;\n\n: read-or-abort ( c-addr size fileid -- : )\n\tover >r read-file\n\t 0<> if cleanup abort\" file read failed\" then\n\tr> <> if cleanup abort\" header too small\" then ;\n\n: header? ( -- : print out header information )\n\tcheader header-size core-file @ read-or-abort\n\t( \" raw header:\" header 2 dump )\n\tcheader header-magic0 + c@ 255 invalid-header\n\tcheader header-magic1 + c@ [char] 4 invalid-header\n\tcheader header-magic2 + c@ [char] T invalid-header\n\tcheader header-magic3 + c@ [char] H invalid-header\n\tcheader header-cell-size + c@ save-core-cell-size\n\tcheader header-version + c@ check-version-compatibility\n\tcheader header-endianess + c@ save-endianess\n\t\" valid header\" cr ;\n\n: size? ( -- : print out core file size )\n\t\" size: \" cheader header-log2size + c@ 1 swap lshift . cr ;\n\n: core ( c-addr u -- : analyze a Forth core file from disk given its file name )\n\t2dup \" core file:\" tab type cr\n\tr\/o open-file throw core-file !\n\theader?\n\tsize?\n\tcore-file @ close-file drop ;\n\n( s\" forth.core\" core )\n\nhide{\nheader-size header?\nheader-magic0 header-magic1 header-magic2 header-magic3\nheader-version header-cell-size header-endianess header-log2size\nheader\ncore-file save-core-cell-size check-version-compatibility\ncore-cell-size cheader\ncore-endianess core-version save-endianess invalid-header\ncleanup size-field csize-field size-field-size\nread-or-abort size?\n}hide\n\n( ==================== Core utilities ======================== )\n\n( ==================== RLE =================================== )\n\n( These set of words implement Run Length Compression, which\ncan be used for saving space when compressing the core files\ngenerated by Forth programs, which contain mostly runs of\nNUL characters.\n\nThe format of the encoded data is quite simple, there is a\ncommand byte followed by data. The command byte encodes only\ntwo commands; encode a run of literal data and repeat the\nnext character.\n\nIf the command byte is greater than X the command is a run\nof characters, X is then subtracted from the command byte\nand this is the number of characters that is to be copied\nverbatim when decompressing.\n\nIf the command byte is less than or equal to X then this\nnumber, plus one, is used to repeat the next data byte in\nthe input stream.\n\nX is 128 for this application, but could be adjusted for\nbetter compression depending on what the data looks like.\n\nExample:\n\n\t2 'a' 130 'b' 'c' 3 'd'\n\nBecomes:\n\n\taabcddd\n\nExample usage:\n\n\t: extract\n\t\tc\" forth.core\" w\/o open-file throw c\"\n\t\tforth.core.rle\" r\/o open-file throw\n\t\tdecompress ;\n\textract\n\n@note file redirection could be used for the input as well\n@todo compression, and reading\/writing to strings )\n\n: cpad pad chars> ;\n\n0 variable out\n128 constant run-length\n\n: next.char ( file-id -- char : read in a single character )\n\t>r cpad r> read-char throw cpad c@ ;\n\n: repeated ( count file-id -- : repeat a character count times )\n\tnext.char swap 0 do dup emit loop drop ;\n\n: literals ( count file-id -- : extract a literal run )\n\t>r cpad swap r> read-file throw cpad swap type ;\n\n: command ( file-id -- : process an RLE command )\n\tdup\n\t>r next.char\n\tdup run-length u>\n\tif\n\t\trun-length - r> literals\n\telse\n\t\t1+ r> repeated\n\tthen ;\n\n: redirect ( file-id-out -- : save current output pointer, redirect to output )\n\t`fout @ out ! `fout ! ;\n\n: restore ( -- : restore previous output pointer )\n\tout @ `fout ! ;\n\n: decompress ( file-id-out file-id-in -- : decompress an RLE encoded file )\n\tswap\n\tredirect\n\tbegin dup ['] command catch until ( process commands until input exhausted )\n\t2drop ( drop twice because catch will restore stack before COMMAND )\n\trestore ; ( restore input stream )\n\nhide{ literals repeated next.char out run-length command }hide\n\n( ==================== RLE =================================== )\n\n( ==================== Generate C Core file ================== )\n( The word core2c reads in a core file and turns it into a\nC file which can then be compiled into the forth interpreter\nin a bootstrapping like process. The process is described\nelsewhere as well, but it goes like this.\n\n1. We want to generate an executable program that contains the\ncore Forth interpreter, written in C, and the contents of this\nfile in compiled form. However, in order to compile this code\nwe need a Forth interpreter to do so. This is the problem.\n2. To solve the problem we first make a program which is capable\nof compiling \"forth.fth\".\n3. We then generate a core file from this.\n4. We then convert the generated core file to C code.\n5. We recompile the original program to includes this core\nfile, and which runs the core file at start up.\n6. We run the new executable.\n\nUsage:\n c\" forth.core\" c\" core.gen.c\" core2c )\n\n0 variable count\n\n: wbyte ( u char -- : write a byte )\n\t(.) drop\n\t[char] , emit\n\t16 mod 0= if cr then ;\n\n: advance ( char -- : advance counter and print byte )\n\tcount 1+! count @ swap wbyte ;\n\n: hexify ( fileid -- fileid : turn core file into C numbers in array )\n\t0 count !\n\tbegin dup getchar 0= while advance repeat drop ;\n\n: quote ( -- : emit a quote character )\n\t[char] \" emit ;\n\n: core2c ( c-addr u c-addr u -- ior : generate a C file from a core file )\n\tw\/o open-file throw >r\n\tr\/o open-file ?dup-if r> close-file throw throw then\n\tr> redirect\n\t\" #include \" quote \" libforth.h\" quote cr\n\t\" unsigned char forth_core_data[] = {\" cr\n\thexify\n\t\" };\" cr\n\t\" forth_cell_t forth_core_size = \" count @ . \" ;\" cr cr\n\tclose-file\n\t`fout @ close-file\n\trestore or ;\n\nhide{ wbyte hexify count quote advance }hide\n\n( ==================== Generate C Core file ================== )\n\n( ==================== Word Count Program ==================== )\n\n( @todo implement FILE-SIZE in terms of this program )\n( @todo extend wc to include line count and word count )\n: wc ( c-addr u -- u : count the bytes in a file )\n\tr\/o open-file throw\n\t0 swap\n\tbegin\n\t\tdup getchar nip 0=\n\twhile\n\t\tnos1+\n\trepeat\n\tclose-file throw ;\n\n( ==================== Word Count Program ==================== )\n\n( ==================== Save Core file ======================== )\n( The following functionality allows the user to save the\ncore file from within the running interpreter. The Forth\ncore files have a very simple format which means the words\nfor doing this do not have to be too long, a header has to\nemitted with a few calculated values and then the contents\nof the Forths memory after this )\n\n( This write the header out to the current output device, this\nwill be redirected to a file )\n: header ( -- : write the header out )\n\t0xff emit ( magic 0 )\n\t[char] 4 emit ( magic 1 )\n\t[char] T emit ( magic 2 )\n\t[char] H emit ( magic 3 )\n\tsize emit ( cell size in bytes )\n\tversion emit ( core version )\n\tendian not emit ( endianess )\n\tmax-core log2 emit ; ( size field )\n\n: data ( -- : write the data out )\n\t0 max-core chars> `fout @ write-file throw drop ;\n\n: encore ( -- : write the core file out )\n\theader\n\tdata ;\n\n: save-core ( c-addr u -- : save core file or throw error )\n\tw\/o open-file throw dup\n\tredirect\n\t\t['] encore catch swap close-file throw\n\trestore ;\n\n( The following code illustrates an example of setting up a\nForth core file to execute a word when the core file is loaded.\nIn the example the word \"hello-world\" will be executed,\nwhich will also quit the interpreter:\n\nThis only works for immediate words for now, we define\nthe word we wish to be executed when the forth core\nis loaded:\n\n\t: hello-world immediate\n\t\t\" Hello, World!\" cr bye ;\n\nThe following sets the starting word to our newly\ndefined word:\n\n\tfind hello-world cfa start!\n\n\t\\ Now we can save the core file out:\n\ts\" forth.core\" save-core\n\nThis can be used, in conjunction with aspects of the build\nsystem, to produce a standalone executable that will run only\na single Forth word. This is known as creating a 'turn-key'\napplication. )\n\nhide{ redirect restore data encore header }hide\n\n( ==================== Save Core file ======================== )\n\n( ==================== Hex dump ============================== )\n\n( @todo hexdump can read in too many characters and it does not\nprint out the correct address\n@todo utilities for easy redirecting of file input\/output )\n\\ : input >r cpad 128 r> read-file ; ( file-id -- u 0 | error )\n\\ : clean cpad 128 0 fill ; ( -- )\n\\ : cdump cpad chars swap aligned chars dump ; ( u -- )\n\\ : hexdump ( file-id -- : [hex]dump a file to the screen )\n\\ \tdup\n\\ \tclean\n\\ \tinput if 2drop exit then\n\\ \t?dup-if cdump else drop exit then\n\\ \ttail ;\n\\\n\\ 0 variable u\n\\ 0 variable u1\n\\ 0 variable cdigs\n\\ 0 variable digs\n\\\n\\ : address ( -- bool : is it time to print out a new line and an address )\n\\ \tu @ u1 @ - 4 size * mod 0= ;\n\\\n\\ : (dump) ( u c-addr u : u -- )\n\\ \trot dup u ! u1 !\n\\ \tcdigits cdigs !\n\\ \tdigits digs !\n\\ \tbounds\n\\ \tdo\n\\ \t\taddress if cr u @ digs @ u.rz [char] : emit space then\n\\ \t\ti c@ cdigs @ u.rz\n\\ \t\t\n\\ \t\ti 1+ size mod 0= if space then\n\\ \t\tu 1+!\n\\ \tloop\n\\ \tu @\n\\ \t;\n\\\n\\ : hexdump-file ( c-addr u )\n\\ \tr\/o open-file throw\n\\ \t\n\\ \t;\n\\\n\\ hide{ u u1 cdigs digs address }hide\n\\ hex\n\\ 999 0 197 (dump)\n\\ decimal\n\\\n\\ hide{ cpad clean cdump input }hide\n\\\n( ==================== Hex dump ============================== )\n\n( ==================== Date ================================== )\n( This word set implements a words for date processing, so\nyou can print out nicely formatted date strings. It implements\nthe standard Forth word time&date and two words which interact\nwith the libforth DATE instruction, which pushes the current\ntime information onto the stack.\n\nRather annoyingly months are start from 1 but weekdays from\n0. )\n\n: >month ( month -- c-addr u : convert month to month string )\n\tcase\n\t\t 1 of c\" Jan \" endof\n\t\t 2 of c\" Feb \" endof\n\t\t 3 of c\" Mar \" endof\n\t\t 4 of c\" Apr \" endof\n\t\t 5 of c\" May \" endof\n\t\t 6 of c\" Jun \" endof\n\t\t 7 of c\" Jul \" endof\n\t\t 8 of c\" Aug \" endof\n\t\t 9 of c\" Sep \" endof\n\t\t10 of c\" Oct \" endof\n\t\t11 of c\" Nov \" endof\n\t\t12 of c\" Dec \" endof\n\t\t-11 throw\n\tendcase ;\n\n: .day ( day -- c-addr u : add ordinal to day )\n\t10 mod\n\tcase\n\t\t1 of c\" st \" endof\n\t\t2 of c\" nd \" endof\n\t\t3 of c\" rd \" endof\n\t\tdrop c\" th \" exit\n\tendcase ;\n\n: >day ( day -- c-addr u: add ordinal to day of month )\n\tdup 1 10 within if .day exit then\n\tdup 10 20 within if drop c\" th\" exit then\n\t.day ;\n\n: >weekday ( weekday -- c-addr u : print the weekday )\n\tcase\n\t\t0 of c\" Sun \" endof\n\t\t1 of c\" Mon \" endof\n\t\t2 of c\" Tue \" endof\n\t\t3 of c\" Wed \" endof\n\t\t4 of c\" Thu \" endof\n\t\t5 of c\" Fri \" endof\n\t\t6 of c\" Sat \" endof\n\t\t-11 throw\n\tendcase ;\n\n: >gmt ( bool -- GMT or DST? )\n\tif c\" DST \" else c\" GMT \" then ;\n\n: colon ( -- char : push a colon character )\n\t[char] : ;\n\n: 0? ( n -- : hold a space if number is less than base )\n\t(base) u< if [char] 0 hold then ;\n\n( .NB You can format the date in hex if you want! )\n: date-string ( date -- c-addr u : format a date string in transient memory )\n\t9 reverse ( reverse the date string )\n\t<#\n\t\tdup #s drop 0? ( seconds )\n\t\tcolon hold\n\t\tdup #s drop 0? ( minute )\n\t\tcolon hold\n\t\tdup #s drop 0? ( hour )\n\t\tdup >day holds\n\t\t#s drop ( day )\n\t\t>month holds\n\t\tbl hold\n\t\t#s drop ( year )\n\t\t>weekday holds\n\t\tdrop ( no need for days of year )\n\t\t>gmt holds\n\t\t0\n\t#> ;\n\n: .date ( date -- : print the date )\n\tdate-string type ;\n\n: time&date ( -- second minute hour day month year )\n\tdate\n\t3drop ;\n\nhide{ >weekday .day >day >month colon >gmt 0? }hide\n\n( ==================== Date ================================== )\n\n\n( ==================== CRC =================================== )\n\n( @todo implement all common CRC algorithms, but only if the\nword size allows it [ie. 32 bit CRCs on a 32 or 64 bit machine,\n64 bit CRCs on a 64 bit machine] )\n\n( Make a word to limit arithmetic to a 16-bit value )\nsize 2 = [if]\n\t: limit immediate ; ( do nothing, no need to limit )\n[else]\n\t: limit 0xffff and ; ( limit to 16-bit value )\n[then]\n\n: ccitt ( crc c-addr -- crc : calculate polynomial 0x1021 AKA \"x16 + x12 + x5 + 1\" )\n\tc@ ( get char )\n\tlimit over 256\/ xor ( crc x )\n\tdup 4 rshift xor ( crc x )\n\tdup 5 lshift limit xor ( crc x )\n\tdup 12 lshift limit xor ( crc x )\n\tswap 8 lshift limit xor ; ( crc )\n\n( See http:\/\/stackoverflow.com\/questions\/10564491\n and https:\/\/www.lammertbies.nl\/comm\/info\/crc-calculation.html )\n: crc16-ccitt ( c-addr u -- u )\n\t0xffff -rot\n\t['] ccitt foreach ;\nhide{ limit ccitt }hide\n\n( ==================== CRC =================================== )\n\n( ==================== Rational Data Type ==================== )\n( This word set allows the manipulation of a rational data\ntype, which are basically fractions. This allows numbers like\n1\/3 to be represented without any loss of precision. Conversion\nto and from the data type to an integer type is trivial,\nalthough information can be lost during the conversion.\n\nTo convert to a rational, use DUP, to convert from a\nrational, use '\/'.\n\nThe denominator is the first number on the stack, the numerator\nthe second number. Fractions are simplified after any rational\noperation, and all rational words can accept unsimplified\narguments. For example the fraction 1\/3 can be represented as\n6\/18, they are equivalent, so the rational equality operator\n\"=rat\" can accept both and returns true.\n\n\tT{ 1 3 6 18 =rat -> 1 }T\n\nSee: https:\/\/en.wikipedia.org\/wiki\/Rational_data_type For\nmore information.\n\nThis set of words use two cells to represent a fraction,\nhowever a single cell could be used, with the numerator and the\ndenominator stored in upper and lower half of a single cell.\n\n@todo add saturating Q numbers to the interpreter, as well as\narithmetic word for acting on double cells [d+, d-, etcetera]\nhttps:\/\/en.wikipedia.org\/wiki\/Q_%28number_format%29, this\ncan be used in lieu of floating point numbers. )\n\n: simplify ( a b -- a\/gcd{a,b} b\/gcd{a\/b} : simplify a rational )\n 2dup\n gcd\n tuck\n \/\n -rot\n \/\n swap ; \\ ? check this\n\n: crossmultiply ( a b c d -- a*d b*d c*b d*b )\n rot ( a c d b )\n 2dup ( a c d b d b )\n * ( a c d b d*b )\n >r ( a c d b , d*b )\n rot ( a d b c , d*b )\n * ( a d b*c , d*b )\n -rot ( b*c a d , d*b )\n * ( b*c a*d , d*b )\n r> ( b*c a*d d*b )\n tuck ( b*c d*b a*d d*b )\n 2swap ; ( done! )\n\n: *rat ( a\/b c\/d -- a\/b : multiply two rationals together )\n rot * -rot * swap simplify ;\n\n: \/rat ( a\/b c\/d -- a\/b : divide one rational by another )\n swap *rat ;\n\n: +rat ( a\/b c\/d -- a\/b : add two rationals together )\n crossmultiply\n rot\n drop ( or check if equal, if not there is an error )\n -rot\n +\n swap\n simplify ;\n\n: -rat ( a\/b c\/d -- a\/b : subtract one rational from another )\n crossmultiply\n rot\n drop ( or check if equal, if not there is an error )\n -rot\n -\n swap\n simplify ;\n\n: .rat ( a\/b -- : print out a rational number )\n simplify swap (.) drop [char] \/ emit . ;\n\n: =rat ( a\/b c\/d -- bool : rational equal )\n crossmultiply rot = -rot = = ;\n\n: >rat ( a\/b c\/d -- bool : rational greater than )\n crossmultiply rot 2drop > ;\n\n: <=rat ( a\/b c\/d -- bool : rational less than or equal to )\n\t>rat not ;\n\n: =rat ( a\/b c\/d -- bool : rational greater or equal to )\n\trational is a work in progress, make it better )\n: 0>number 0 -rot >number ;\n0 0 2variable saved\n: failed 0 0 saved 2@ ;\n: >rational ( c-addr u -- a\/b c-addr u )\n\t2dup saved 2!\n\t0>number 2dup 0= if 4drop failed exit then ( @note could convert to rational n\/1 )\n\tc@ [char] \/ <> if 3drop failed exit then\n\t1 \/string\n\t0>number ;\n\nhide{ 0>number saved failed }hide\n\n( ==================== Rational Data Type ==================== )\n\n( ==================== Block Layer =========================== )\n( This is the block layer, it assumes that the file access\nwords exists and use them, it would have to be rewritten\nfor an embedded device that used EEPROM or something\nsimilar. Currently it does not interact well with the current\ninput methods used by the interpreter which will need changing.\n\nThe block layer is the traditional way Forths implement a\nsystem to interact with mass storage, one which imposes little\non the underlying system only requiring that blocks 1024 bytes\ncan be loaded and saved to it [which make it suitable for\nmicrocomputers that lack a file system or an embedded device].\n\nThe block layer is used less than it once as a lot more Forths\nare hosted under a guest operating system so have access to\nmethods for reading and writing to files through it.\n\nEach block number accepted by BLOCK is backed by a file\n[or created if it does not exist]. The name of the file is\nthe block number with \".blk\" appended to it.\n\nSome Notes:\n\nBLOCK only uses one block buffer, most other Forths have\nmultiple block buffers, this could be improved on, but\nwould take up more space.\n\nAnother way of storing the blocks could be made, which is to\nstore the blocks in a single file and seek to the correct\nplace within it. This might be implemented in the future,\nor offered as an alternative. \n\nYet another way is to not have on disk blocks, but instead\nhave in memory blocks, this simplifies things significantly,\nand would mean saving the blocks to disk would use the same\nmechanism as saving the core file to disk. Computers certainly\nhave enough memory to do this. The block word set could\nbe factored so it could use either the on disk method or\nthe memory option. \n\nTo simplify the current code, and make the code portable\nto devices with EEPROM an instruction in the virtual machine\ncould be made which does the task of transfering a block to\ndisk. \n\n@todo refactor BLOCK to use MAKE\/DOER so its behavior can\nbe changed. )\n\n0 variable dirty\nb\/buf string buf ( block buffer, only one exists )\n0 , ( make sure buffer is NUL terminated, just in case )\n0 variable blk ( 0 = invalid block number, >0 block number stored in buf)\n\n: invalid? ( n -- : throw if block number is invalid )\n\t0= if -35 throw then ;\n\n: update ( -- : mark currently loaded block buffer as dirty )\n\ttrue dirty ! ;\n\n: updated? ( n -- bool : is a block updated? )\n \tblk @ <> if 0 else dirty @ then ;\n\n: block.name ( n -- c-addr u : make a block name )\n\tc\" .blk\" <# holds #s #> rot drop ;\n\n( @warning this will not work if we do not have permission,\nor in various other cases where we cannot open the file,\nfor whatever reason )\n: file-exists ( c-addr u : does a file exist? )\n\tr\/o open-file if drop 0 else close-file throw 1 then ;\n\n: block.exists ( n -- bool : does a block buffer exist on disk? )\n\tblock.name file-exists ;\n\n( @note block.write and block.read do not check if they have\nwrote or read in 1024 bytes, nor do they check that they can\nonly write or read 1024 and not a byte more )\n\n: block.read ( file-id -- file-id : read in buffer )\n\tdup >r buf r> read-file nip if close-file -33 throw then ;\n\n: block.write ( file-id -- file-id : write out buffer )\n\tdup >r buf r> write-file nip if close-file -34 throw then ;\n\n: block.open ( n fam -- file-id )\n\t>r block.name r> open-file throw ;\n\n: save-buffers\n\tblk @ 0= if exit then ( not a valid block number, exit )\n\tdirty @ not if exit then ( not dirty, no need to save )\n\tblk @ w\/o block.open ( open file backing block buffer )\n\tblock.write ( write it out )\n\tclose-file throw ( close it )\n\tfalse dirty ! ; ( but only mark it clean if everything succeeded )\n\n: empty-buffers ( -- : deallocate any saved buffers )\n\t0 blk ! ;\n\n: flush ( -- : perform save-buffers followed by empty-buffers )\n\tsave-buffers\n\tempty-buffers ;\n\n( Block is a complex word that does a lot, although it has\na simple interface. It does the following given a block number:\n\n1. Checks the provided block buffer number to make sure it\nis valid.\n2. If the block is already loaded from the disk, then return\nthe address of the block buffer it is loaded into.\n3. If not, it checks to see if the currently loaded block\nbuffer is dirty, if it is then it flushes the buffer to disk.\n4. If the block buffer does not exists on disk then it\ncreates it.\n5. It then stores the block number in blk and returns an\naddress to the block buffer. )\n: block ( n -- c-addr : load a block )\n\tdup invalid?\n\tdup blk @ = if drop buf drop exit then\n\tflush\n\tdup block.exists if ( if the buffer exits on disk load it in )\n\t\tdup r\/o block.open\n\t\tblock.read\n\t\tclose-file throw\n\telse ( else it does not exist )\n\t\tbuf 0 fill ( clean the buffer )\n\tthen\n\tblk ! ( save the block number )\n\tbuf drop ;\n\n: buffer block ;\n\n: load ( n -- : load and execute a block )\n\tblock b\/buf evaluate throw ;\n\n: +block ( n -- u : calculate new block number relative to current block )\n\tblk @ + ;\n\n: --> ( -- : load next block )\n\t1 +block load ;\n\n( @todo refactor into BLOCK.MAKE, which BLOCKS.MAKE would use )\n: blocks.make ( n1 n2 -- : make blocks on disk from n1 to n2 inclusive )\n\t1+ swap do i block b\/buf bl fill update loop save-buffers ;\n\n: block.copy ( n1 n2 -- bool : copy block n2 to n1 if n2 exists )\n\tswap dup block.exists 0= if 2drop false exit then ( n2 n1 )\n\tblock drop ( load in block n1 )\n\tw\/o block.open block.write close-file throw\n\ttrue ;\n\n: block.delete ( n -- : delete block )\n\tdup block.exists 0= if drop exit then\n\tblock.name delete-file drop ;\n\n\\ @todo implement a word that splits a file into blocks\n\\ : split ( c-addr u : split a file into blocks )\n\\\t;\n\nhide{\n\tblock.name invalid? block.write\n\tblock.read block.exists block.open dirty\n}hide\n\n( ==================== Block Layer =========================== )\n\n( ==================== List ================================== )\n( The list word set allows the viewing of Forth blocks,\nthis version of list can create two Formats, a simple mode\nwhere it just spits out the block with a carriage return\nafter each line and a more fancy version which also prints\nout line numbers and draws a box around the data. LIST is\nnot aware of any formatting and characters that might be\npresent in the data, or none printable characters.\n\nA very primitive version of list can be defined as follows:\n\n\t: list block b\/buf type ;\n\n)\n\n1 variable fancy-list\n0 variable scr\n64 constant c\/l ( characters per line )\n\n: pipe ( -- : emit a pipe character )\n\t[char] | emit ;\n\n: line.number ( n -- : print line number )\n\tfancy-list @ not if drop exit then\n\t2 u.r space pipe ;\n\n: list.end ( -- : print the right hand side of the box )\n\tfancy-list @ not if exit then\n\tpipe ;\n\n: line ( c-addr -- c-addr u : given a line number, display that line number and calculate offset )\n\tdup\n\tline.number ( display line number )\n\tc\/l * + ( calculate offset )\n\tc\/l ; ( add line length )\n\n: list.type ( c-addr u -- : list a block )\n\tb\/buf c\/l \/ 0 do dup i line type list.end cr loop drop ;\n\n: list.border ( -- : print a section of the border )\n\t\" +---|---\" ;\n\n: list.box ( )\n\tfancy-list @ not if exit then\n\t4 spaces\n\t8 0 do list.border loop cr ;\n\n: list ( n -- : display a block number and update scr )\n\tdup >r block r> scr ! list.box list.type list.box ;\n\n: thru\n\tkey drop\n\t1+ swap do i list more loop ;\n\nhide{\n\tbuf line line.number list.type\n\t(base) list.box list.border list.end pipe\n}hide\n\n( ==================== List ================================== )\n\n( ==================== Signal Handling ======================= )\n( Signal handling at the moment is quite primitive. When\na signal occurs it has to be explicitly tested for by the\nprogrammer, this could be improved on quite a bit. One way\nof doing this would be to check for signals in the virtual\nmachine and cause a THROW from within it. )\n\n( signals are biased to fall outside the range of the error\nnumbers defined in the ANS Forth standard. )\n-512 constant signal-bias\n\n: signal ( -- signal\/0 : push the results of the signal register )\n\t`signal @\n \t0 `signal ! ;\n\n( ==================== Signal Handling ======================= )\n\n( Looking at most Forths dictionary with \"words\" command they\ntend to have a lot of words that do not mean anything but to\nthe implementers of that specific Forth, here we clean up as\nmany non standard words as possible. )\nhide{\n do-string ')' alignment-bits\n dictionary-start hidden-mask instruction-mask immediate-mask compiling?\n compile-bit\n max-core dolist doconst x x! x@\n max-string-length\n evaluator\n TrueFalse >instruction\n xt-instruction\n `source-id `sin `sidx `slen `start-address `fin `fout `stdin\n `stdout `stderr `argc `argv `debug `invalid `top `instruction\n `stack-size `error-handler `handler _emit `signal `x\n}hide\n\n(\n## Forth To List\n\nThe following is a To-Do list for the Forth code itself,\nalong with any other ideas.\n\n* FORTH, VOCABULARY\n\n* \"Value\", \"To\", \"Is\"\n\n* Double cell words\n\n* The interpreter should use character based addresses,\ninstead of word based, and use values that are actual valid\npointers, this will allow easier interaction with the world\noutside the virtual machine\n\n* common words and actions should be factored out to simplify\ndefinitions of other words, their standards compliant version\nfound if any.\n\n* A soft floating point library would be useful which could be\nused to optionally implement floats [which is not something I\nreally want to add to the virtual machine]. If floats were to\nbe added, only the minimal set of functions should be added\n[f+,f-,f\/,f*,f<,f>,>float,...]\n\n* Allow the processing of argc and argv, the mechanism by which\nthat this can be achieved needs to be worked out. However all\nprocessing that is currently done in \"main.c\" should be done\nwithin the Forth interpreter instead. Words for manipulating\nrationals and double width cells should be made first.\n\n* A built in version of \"dump\" and \"words\" should be added\nto the Forth starting vocabulary, simplified versions that\ncan be hidden.\n\n* Here documents, string literals. Examples of these can be\nfound online\n\n* Document the words in this file and built in words better,\nalso turn this document into a literate Forth file.\n\n* Sort out \"'\", \"[']\", \"find\", \"compile,\"\n\n* Proper booleans should be used throughout, that is -1 is\ntrue, and 0 is false.\n\n* Attempt to add crypto primitives, not for serious use,\nlike TEA, XTEA, XXTEA, RC4, MD5, ...\n\n* Add hash functions: CRC-32, CRC-16, ...\nhttp:\/\/stackoverflow.com\/questions\/10564491\/\n\n* Implement as many things from\nhttp:\/\/lars.nocrew.org\/forth2012\/implement.html as is sensible.\n\n* Works like EMIT and KEY should be DOER\/MAKE words\n\n* The current words that implement I\/O redirection need to\nbe improved, and documented, I think this is quite a useful\nand powerful mechanism to use within Forth that simplifies\nprograms. This is a must and will make writing utilities in\nForth a *lot* easier\n\n* Words for manipulating words should be added, for navigating\nto different fields within them, to the end of the word,\netcetera.\n\n* The data structure used for parsing Forth words needs\nchanging in libforth so a counted string is produced. Counted\nstrings should be used more often. The current layout of a\nForth word prevents a counted string being used and uses a\nbyte more than it has to.\n\n* Whether certain simple words [such as '1+', '1-', '>',\n'<', '<>', NOT, <=', '>='] should be added as virtual\nmachine instructions for speed [and size] reasons should\nbe investigated.\n\n* An analysis of the interpreter and the code it executes\ncould be done to find the most commonly executed words\nand instructions, as well as the most common two and three\nsequences of words and instructions. This could be used to use\nto optimize the interpreter, in terms of both speed and size.\n\n* The source code for this file should go through a code\nreview, which should focus on formatting, stack comments and\nreorganizing the code. Currently it is not clear that variables\nlike COLORIZE and FANCY-LIST exist and can be changed by\nthe user. Lines should be 64 characters in length - maximum,\nincluding the new line at the end of the file.\n\n### libforth.c todo\n\n* A halt, a parse, and a print\/type instruction could be\nadded to the Forth virtual machine.\n\n* Make case sensitivity optional\n\n* u.r, or a more generic version should be added to the\ninterpreter instead of the current simpler primitive. As\nshould >number - for fast numeric input and output.\n\n* Throw\/Catch need to be added and used in the virtual machine\n\n* Integrate Travis Continous Integration into the Github\nproject.\n\n* A potential optimization is to order the words in the\ndictionary by frequency order, this would mean chaning the\nX Macro that contains the list of words, after collecting\nstatistics. This should make find faster.\n\n* Investigate adding operating system specific code into the\ninterpreter and isolating it to make it semi-portable.\n\n* Make equivalents for various Unix utilities in Forth,\nlike a CRC check, cat, tr, etcetera.\n\n* It would be interesting to make a primitive file system based\nupon Forth blocks, this could then be ported to systems that\ndo not have file systems, such as microcontrollers [which\nusually have EEPROM].\n\n* In a _very_ unportable way it would be possible to have an\ninstruction that takes the top of the stack, treats it as a\nfunction pointer and then attempts to call said function. This\nwould allow us to assemble machine dependant code within the\ncore file, generate a new function, then call it. It is just\na thought.\n )\n\nverbose [if]\n\t.( FORTH: libforth successfully loaded.) cr\n\tdate .date cr\n\t.( Type 'help' and press return for a basic introduction.) cr\n\t.( Core: ) here . \" \/ \" here unused + . cr\n\t license\n[then]\n\n( ==================== Test Code ============================= )\n\n( The following will not work as we might actually be reading\nfrom a string [`sin] not `fin.\n\n: key 32 chars> 1 `fin @\n\tread-file drop 0 = if 0 else 32 chars> c@ then ; )\n\n\\ : ' immediate state @ if postpone ['] else find then ;\n\n( This really does not implement a correct FORTH\/VOCABULARY,\nfor that wordlists will need to be introduced and used in\nlibforth.c. The best that this word set can do is to hide\nand reveal words to the user, this was just an experiment.\n\n\t: forth\n\t\t[ find forth 1- @ ] literal\n\t\t[ find forth 1- ] literal ! ;\n\n\t: vocabulary\n\t\tcreate does> drop 0 [ find forth 1- ] literal ! ; )\n\n\\ @todo The built in primitives should be redefined so to make sure\n\\ they are called and nested correctly, using the following words\n\\ 0 variable csp\n\\ : !csp sp@ csp ! ;\n\\ : ?csp sp@ csp @ <> if -22 throw then ;\n\n\\ @todo Make this work\n\\ : >body ??? ;\n\\ : noop ( -- ) ;\n\\ : defer create ( \"name\" -- ) ['] noop , does> ( -- ) @ execute ;\n\\ : is ( xt \"name\" -- ) find >body ! ;\n\\ defer lessthan\n\\ find < is lessthan\n\n( ==================== Test Code ============================= )\n\n( ==================== Block Editor ========================== )\n( Experimental block editor Mark II\n\nThis is a simple block editor, it really shows off the power\nand simplicity of Forth systems - both the concept of a block\neditor and the implementation.\n\nForth source code used to organized into things called 'blocks',\nnowadays most people use normal resizeable stream based files.\nA block simply consists of 1024 bytes of data that can be\ntransfered to and from mass storage. This works on systems that\ndo not have a file system. A block can be used for storing\narbitrary data as well, so the user had to know what was stored\nin what block.\n\n1024 bytes is quite a limiting Form factor for storing source\ncode, which is probably one reason Forth earned a reputation\nfor being terse. A few conventions arose around dealing with\nForth source code stored in blocks - both in how the code should\nbe formatted within them, and in how programs that required\nmore than one block of storage should be dealt with.\n\nOne of the conventions is how many columns and rows each block\nconsists of, the traditional way is to organize the code into\n16 lines of text, with a column width of 64 characters. The only\nspace character used is the space [or ASCII character 32], tabs\nand new lines are not used, as they are not needed - the editor\nknows how long a line is so it can wrap the text.\n\nVarious standards and common practice evolved as to what goes\ninto a block - for example the first line is usually a comment\ndescribing what the block does, with the date is was last edited\nand who edited it.\n\nThe way the editor works is by defining a simple set of words\nthat act on the currently loaded block, LIST is used to display\nthe loaded block. An editor loop which executes forth words\nand automatically displays the currently block can be entered\nby calling EDITOR. This loop is essential an extension of\nthe INTERPRET word, it does no special processing such as\nlooking for keys - all commands are Forth words. The editor\nloop could have been implemented in the following fashion\n[or something similar]:\n\n\t: editor-command\n\t\tkey\n\t\tcase\n\t\t\t[char] h of print-editor-help endof\n\t\t\t[char] i of insert-text endof\n\t\t\t[char] d of delete-line endof\n\t\t\t... more editor commands\n\t\t\t[char] q of quit-editor-loop endof\n\t\t\tpush-number-by-default\n\t\tendof ;\n\nHowever this is rather limiting, it only works for single\ncharacter commands and numeric input is handled as a special\ncase. It is far simpler to just call the READ word with the\neditor commands in search order, and it can be extended not\nby adding more parsing code in CASE statements but just by\ndefining new words in the ordinary manner.\n\nThe editor loop does not have to be used while editing code,\nbut it does make things easier. The commands defined can be\nused on there own.\n\t\nThe code was adapted from: \t\n\nhttp:\/\/retroforth.org\/pages\/?PortsOfRetroEditor\n\nWhich contains ports of an editor written for Retro Forth.\n\n@todo Improve the block editor\n\n- '\\' needs extending to work with the block editor, for now,\nuse parenthesis for comments\n- add multi line insertion mode\n- Add to an editor vocabulary, which will need the vocabulary\nsystem to exist.\n- Using PAGE should be optional as not all terminals support\nANSI escape codes - thanks to CMD.EXE. Damned Windows.\n\nAdapted from http:\/\/retroforth.org\/pages\/?PortsOfRetroEditor )\n\n\n: help ( @todo rename to H once vocabularies are implemented )\npage cr\n\" Block Editor Help Menu\n\n n move to next block\n p move to previous block\n # d delete line in current block\n x erase current block\n e evaluate current block\n # i insert line\n # #2 ia insert at line #2 at column #\n q quit editor loop\n # b set block number\n s save block and write it out\n u update block\n\n -- press any key to continue -- \" cr ( \" )\nchar drop ;\n\n: (block) blk @ block ;\n: (check) dup b\/buf c\/l \/ u>= if -24 throw then ;\n: (line) (check) c\/l * (block) + ; ( n -- c-addr : push current line address )\n: (clean)\n\t(block) b\/buf\n\t2dup nl bl subst\n\t2dup cret bl subst\n\t 0 bl subst ;\n: n 1 +block block ;\n: p -1 +block block ;\n: d (line) c\/l bl fill ;\n: x (block) b\/buf bl fill ;\n: s update save-buffers ;\n: q rdrop rdrop ;\n: e blk @ load char drop ;\n: ia c\/l * + dup b\/buf swap - >r (block) + r> accept drop (clean) ;\n: i 0 swap ia ;\n: editor\n\t1 block ( load first block by default )\n\trendezvous ( set up a rendezvous so we can forget words up to this point )\n\tbegin\n\t\tpage cr\n\t\t\" BLOCK EDITOR: TYPE 'HELP' FOR A LIST OF COMMANDS\" cr\n\t\tblk @ list\n\t\t\" [BLOCK: \" blk @ u. \" ] \" \n\t\t\" [HERE: \" here u. \" ] \" \n\t\t\" [SAVED: \" blk @ updated? not u. \" ] \"\n\t\tcr\n\t\tpostpone [ ( need to be in command mode )\n\t\tread\n\tagain ;\n\n( Extra niceties )\nc\/l string yank \nyank bl fill\n: u update ;\n: b block ;\n: l blk @ list ;\n: y (line) yank >r swap r> cmove ; ( n -- yank line number to buffer )\n: c (line) yank cmove ; ( n -- copy yank buffer to line )\n: ct swap y c ; ( n1 n2 -- copy line n1 to n2 )\n: ea (line) c\/l evaluate throw ;\n: m retreat ; ( -- : forget everything since editor session began )\n\n: sw 2dup y (line) swap (line) swap c\/l cmove c ;\n\nhide{ (block) (line) (clean) yank }hide\n\n( ==================== Block Editor ========================== )\n\n( ==================== Error checking ======================== )\n( This is a series of redefinitions that make the use of control\nstructures a bit safer. )\n\n: if immediate ?comp postpone if [ hide if ] ;\n: else immediate ?comp postpone else [ hide else ] ;\n: then immediate ?comp postpone then [ hide then ] ;\n: begin immediate ?comp postpone begin [ hide begin ] ;\n: until immediate ?comp postpone until [ hide until ] ;\n: never immediate ?comp postpone never [ hide never ] ;\n\\ : ; immediate ?comp postpone ; [ hide ; ] ; ( @todo do nesting checking for control statements )\n\n( ==================== Error checking ======================== )\n\n( ==================== DUMP ================================== )\n\\ : newline ( x -- x+1 : print a new line every fourth value )\n\\ \tdup 3 and 0= if cr then 1+ ;\n\\\n\\ : address ( num count -- count : print current address we are dumping every fourth value )\n\\ \tdup >r\n\\ \t1- 3 and 0= if . [char] : emit space else drop then\n\\ \tr> ;\n\\\n\\ : dump ( start count -- : print the contents of a section of memory )\n\\ \\\thex ( switch to hex mode )\n\\ \t1 >r ( save counter on return stack )\n\\ \tover + swap ( calculate limits: start start+count )\n\\ \tbegin\n\\ \t\t2dup u> ( stop if gone past limits )\n\\ \twhile\n\\ \t\tdup r> address >r\n\\ \t\tdup @ . 1+\n\\ \t\tr> newline >r\n\\ \trepeat\n\\ \tr> drop\n\\ \t2drop ;\n\\\n\\ hide newline\n\\ hide address\n( ==================== DUMP ================================== )\n\n( ==================== End of File Functions ================= )\n\n( set up a rendezvous point, we can call the word RETREAT to\nrestore the dictionary to this point. This word also updates\nfence to this location in the dictionary )\nrendezvous\n\n: task ; ( Task is a word that can safely be forgotten )\n\n( ==================== End of File Functions ================= )\n\n\n","old_contents":"#!.\/forth\n( Welcome to libforth, A dialect of Forth. Like all versions\nof Forth this version is a little idiosyncratic, but how\nthe interpreter works is documented here and in various\nother files.\n\nThis file contains most of the start up code, some basic\nstart up code is executed in the C file as well which makes\nprogramming at least bearable. Most of Forth is programmed in\nitself, which may seem odd if your back ground in programming\ncomes from more traditional language [such as C], although\nless so if you know already know lisp.\n\nFor more information about this interpreter and Forth see:\n\nhttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\nAnd within this code base:\n\n\treadme.md : for a manual for this interpreter\n\tlibforth.h : for information about the C API\n\tlibforth.c : for the interpreter itself\n\tunit.c : unit tests for libforth.c\n\tunit.fth : unit tests against this file\n\tmain.c : an example interpreter\n\nThe interpreter and this code originally descend from a Forth\ninterpreter written in 1992 for the International obfuscated\nC Coding Competition.\n\nSee:\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\nThe manual for the interpreter should be read first before\nlooking into this code. It is important to understand the\nexecution model of Forth, especially the differences between\ncommand and compile mode, and how immediate and compiling\nwords work.\n\nEach of these sections is clearly labeled and they are\ngenerally in dependency order.\n\nUnfortunately the code in this file is not as portable as it\ncould be, it makes assumptions about the size of cells provided\nby the virtual machine, which will take time to rectify. Some\nof the constructs are subtly different from the DPANs Forth\nspecification, which is usually noted. Eventually this should\nalso be fixed.\n\nA little note on how code is formatted, a line of Forth code\nshould not exceed 64 characters. All words stack effect, how\nmany variables on the stack it accepts and returns, should\nbe commented with the following types:\n\n\tchar \/ c A character\n\tc-addr An address of a character\n\taddr An address of a cell\n\tr-addr A real address*\n\tu A unsigned number\n\tn A signed number\n\tc\" xxx\" The word parses a word\n\tc\" x\" The word parses a single character\n\txt An execution token\n\tbool A boolean value\n\tior A file error return status [0 on no error]\n\tfileid A file identifier.\n\tCODE A number from a words code field\n\tPWD A number from a words previous word field\n\t* A real address is one outside the range of the\n\tForth address space.\n\nIn the comments Forth words should be written in uppercase. As\nthis is supposed to be a tutorial about Forth and describe the\ninternals of a Forth interpreter, be as verbose as possible.\n\nThe code in this file will need to be modified to abide by\nthese standards, but new code should follow it from the start.\n\nDoxygen style tags for documenting bugs, todos and warnings\nshould be used within comments. This makes finding code that\nneeds working on much easier.)\n\n( ==================== Basic Word Set ======================== )\n\n( We'll begin by defining very simple words we can use later,\nthese a very basic words, that perform simple tasks, they\nwill not require much explanation.\n\nEven though the words are simple, their stack comment and\na description for them will still be included so external\ntools can process and automatically extract the document\nstring for a given work. )\n\n: postpone ( c\" xxx\" -- : postpone execution of a word )\n\timmediate find , ;\n\n: constant\n\t:: ( compile word header )\n\there 1 - h ! ( decrement dictionary pointer )\n\t( change instruction to CONST )\n\there @ instruction-mask invert and doconst or here !\n\there 1 + h ! ( increment dictionary pointer )\n\t, ( write in value )\n\tpostpone [ ; ( back into command mode )\n\n( These constants are defined as a space saving measure,\nnumbers in a definition usually take up two cells, one\nfor the instruction to push the next cell and the cell\nitself, for the most frequently used numbers it is worth\ndefining them as constants, it is just as fast but saves\na lot of space )\n-1 constant -1\n 0 constant 0\n 1 constant 1\n 2 constant 2\n 3 constant 3\n\n0 constant false\n1 constant true ( @warning not standards compliant )\n\n( Confusingly the word CR prints a line feed )\n10 constant lf ( line feed )\nlf constant nl ( new line - line feed on Unixen )\n13 constant cret ( carriage return )\n\n-1 -1 1 rshift invert and constant min-signed-integer\nmin-signed-integer invert constant max-signed-integer\n\n( The following version number is used to mark whether core\nfiles will be compatible with each other, The version number\ngets stored in the core file and is used by the loader to\ndetermine compatibility )\n4 constant version ( version number for the interpreter )\n\n( This constant defines the number of bits in an address )\ncell size 8 * * constant address-unit-bits \n\n( Bit corresponding to the sign in a number )\n-1 -1 1 rshift and invert constant sign-bit \n\n( @todo test by how much, if at all, making words like 1+,\n1-, <>, and other simple words, part of the interpreter would\nspeed things up )\n\n: 1+ ( x -- x : increment a number )\n\t1 + ;\n\n: 1- ( x -- x : decrement a number )\n\t1 - ;\n\n: chars ( c-addr -- addr : convert a c-addr to an addr )\n\tsize \/ ;\n\n: chars> ( addr -- c-addr: convert an addr to a c-addr )\n\tsize * ;\n\n: tab ( -- : print a tab character )\n\t9 emit ;\n\n: 0= ( n -- bool : is 'n' equal to zero? )\n\t0 = ;\n\n: not ( n -- bool : is 'n' true? )\n\t0= ;\n\n: <> ( n n -- bool : not equal )\n\t= 0= ;\n\n: logical ( n -- bool : turn a value into a boolean )\n\tnot not ;\n\n: 2, ( n n -- : write two values into the dictionary )\n\t, , ;\n\n: [literal] ( n -- : write a literal into the dictionary )\n\tdolit 2, ;\n\n: literal ( n -- : immediately compile a literal )\n\timmediate [literal] ;\n\n: sliteral immediate ( I: c-addr u --, Run: -- c-addr u )\n\tswap [literal] [literal] ;\n\n( @todo throw if not found )\n: ['] ( I: c\" xxx\", Run: -- xt )\n\timmediate find [literal] ;\n\n: >instruction ( CODE -- u : extract instruction CODE field )\n\tinstruction-mask and ;\n\n( IMMEDIATE-MASK pushes the mask for the compile bit,\nwhich can be used on a CODE field of a word )\n1 compile-bit lshift constant immediate-mask\n\n: hidden? ( PWD -- PWD bool : is a word hidden? )\n\tdup 1+ @ hidden-mask and logical ;\n\n: compiling? ( PWD -- PWD bool : is a word immediate? )\n\tdup 1+ @ immediate-mask and logical ;\n\n: cr ( -- : emit a newline character )\n\tnl emit ;\n\n: < ( x1 x2 -- bool : signed less than comparison )\n\t- dup if max-signed-integer u> else logical then ;\n\n: > ( x1 x2 -- bool : signed greater than comparison )\n\t- dup if max-signed-integer u< else logical then ;\n\n( The pad area is an area used for temporary storage, some\nwords use it, although which ones do should be kept to a\nminimum. It is an area of space #pad amount of characters\nafter the latest dictionary definition. The area between\nthe end of the dictionary and start of PAD space is used for\npictured numeric output [<#, #, #S, #>]. It is best not to\nuse the pad area that much. )\n128 constant #pad\n\n: pad ( -- addr : push pointer to the pad area )\n\there #pad + ;\n\n( @todo this can be improved a lot, currently it uses more\nspace than it has to, 4 cells instead of three.\n\nIt does:\n\n\tpush value\n\tpush value\n\nInstead of:\n\n\tmagic-2literal-word\n\tvalue\n\tvalue\n\n)\n: 2literal immediate ( n n -- : compile two literals )\n\tswap [literal] [literal] ;\n\n: latest ( get latest defined word )\n\tpwd @ ;\n\n: stdin ( -- fileid : push fileid for standard input )\n\t`stdin @ ;\n\n: stdout ( -- fileid : push fileid for standard output )\n\t`stdout @ ;\n\n: stderr ( -- fileid : push fileid for the standard error )\n\t`stderr @ ;\n\n: stdin? ( -- bool : are we reading from standard input )\n\t`fin @ stdin = ;\n\n: *+ ( n1 n2 n3 -- n )\n\t* + ;\n\t\n: 2- ( n -- n : decrement by two )\n\t2 - ;\n\n: 2+ ( n -- n : increment by two )\n\t2 + ;\n\n: 3+ ( n -- n : increment by three )\n\t3 + ;\n\n: 2* ( n -- n : multiply by two )\n\t1 lshift ;\n\n: 2\/ ( n -- n : divide by two )\n\t1 rshift ;\n\n: 4* ( n -- n : multiply by four )\n\t2 lshift ;\n\n: 4\/ ( n -- n : divide by four )\n\t2 rshift ;\n\n: 8* ( n -- n : multiply by eight )\n\t3 lshift ;\n\n: 8\/ ( n -- n : divide by eight )\n\t3 rshift ;\n\n: 256* ( n -- n : multiply by 256 )\n\t8 lshift ;\n\n: 256\/ ( n -- n : divide by 256 )\n\t8 rshift ;\n\n: 2dup ( n1 n2 -- n1 n2 n1 n2 : duplicate two values )\n\tover over ;\n\n: mod ( u1 u2 -- u : calculate the remainder of u1\/u2 )\n\t2dup \/ * - ;\n\n( @todo implement UM\/MOD in the VM, then use this to implement\n'\/' and MOD )\n: um\/mod ( u1 u2 -- rem quot : remainder and quotient of u1\/u2 )\n\t2dup \/ >r mod r> ;\n\n( @warning this does not use a double cell for the multiply )\n: *\/ ( n1 n2 n3 -- n4 : [n2*n3]\/n1 )\n\t * \/ ;\n\n: char ( -- n : read in a character from the input steam )\n\tkey drop key ;\n\n: [char] ( c\" x\" -- R: -- char : immediately compile next char )\n\timmediate char [literal] ;\n\n( COMPOSE is a high level function that can take two executions\ntokens and produce a unnamed function that can do what they\nboth do.\n\nIt can be used like so:\n\n\t:noname 2 ;\n\t:noname 3 + ;\n\tcompose\n\texecute \n\t.\n\t5 <-- 5 is printed!\n\nI have not found a use for it yet, but it sure is neat.)\n\n: compose ( xt1 xt2 -- xt3 : create a function from xt-tokens )\n\t>r >r ( save execution tokens )\n\tpostpone :noname ( create a new :noname word )\n\tr> , ( write first token )\n\tr> , ( write second token )\n\t(;) ; ( terminate new :noname )\n\n( CELLS is a word that is not needed in this interpreter but\nit required to write portable code [I have probably missed\nquite a few places where it should be used]. The reason it\nis not needed in this interpreter is a cell address can only\nbe in multiples of cells, not in characters. This should be\naddressed in the libforth interpreter as it adds complications\nwhen having to convert to and from character and cell address.)\n\n: cells ( n1 -- n2 : convert cell count to address count)\n\timmediate ;\n\n: cell+ ( a-addr1 -- a-addr2 )\n\tcell + ;\n\n: cell- ( a-addr1 -- addr2 )\n\tcell - ;\n\n: negative? ( x -- bool : is a number negative? )\n\tsign-bit and logical ;\n\n: mask-byte ( x -- x : generate mask byte )\n\t8* 255 swap lshift ;\n\n: select-byte ( u i -- c )\n\t8* rshift 0xff and ;\n\n: xt-instruction ( PWD -- CODE : extract instruction from PWD )\n\tcell+ @ >instruction ;\n\n: defined-word? ( PWD -- bool : is defined or a built-in word)\n\txt-instruction dolist = ;\n\n: char+ ( c-addr -- c-addr : increment a c-addr one c-addr )\n\t1+ ;\n\n: 2chars ( c-addr1 c-addr2 -- addr addr : chars on two c-addr) \n\tchars swap chars swap ;\n\n: 2chars> ( addr addr -- c-addr c-addr: chars> on two addr )\n\tchars> swap chars> swap ;\n\n: hex ( -- : print out hex )\n\t16 base ! ;\n\n: octal ( -- : print out octal )\n\t8 base ! ;\n\n: binary ( -- : print out binary )\n\t2 base ! ;\n\n: decimal ( -- : print out decimal )\n\t0 base ! ;\n\n: negate ( x -- x )\n\t-1 * ;\n\n: abs ( x -- u : return the absolute value of a number )\n\tdup negative? if negate then ;\n\n: square ( x -- x )\n\tdup * ;\n\n: sum-of-squares ( a b -- c : compute a^2 + b^2 to get c )\n\tsquare swap square + ;\n\n: drup ( x y -- x x )\n\tdrop dup ;\n\n: +! ( x addr -- : add x to a value stored at addr )\n\ttuck @ + swap ! ;\n\n: 1+! ( addr -- : increment a value at an address )\n\t1 swap +! ;\n\n: 1-! ( addr -- : decrement a value at an address )\n\t-1 swap +! ;\n\n: c+! ( x c-addr -- : add x to a value stored at c-addr )\n\ttuck c@ + swap c! ;\n\n: toggle ( addr u -- : xor value at addr with u )\n\tover @ xor swap ! ;\n\n: lsb ( x -- x : mask off the least significant byte of a cell )\n\t255 and ;\n\n: \\ ( -- : immediate word, used for single line comments )\n\timmediate begin key nl = until ;\n\n: ?dup ( x -- ? )\n\tdup if dup then ;\n\n: min ( n n -- n : return the minimum of two integers )\n\t2dup < if drop else nip then ;\n\n: max ( n n -- n : return the maximum of two integers )\n\t2dup > if drop else nip then ;\n\n: umin ( u u -- u : return the minimum of two unsigned numbers )\n\t2dup u< if drop else nip then ;\n\n: umax ( u u -- u : return the maximum of two unsigned numbers )\n\t2dup > if drop else nip then ;\n\n: limit ( x min max -- x : limit x with a minimum and maximum )\n\trot min max ;\n\n: >= ( n n -- bool )\n\t< not ;\n\n: <= ( n n -- bool )\n\t> not ;\n\n: 2@ ( a-addr -- u1 u2 : load two consecutive memory cells )\n\tdup 1+ @ swap @ ;\n\n: 2! ( u1 u2 a-addr -- : store two values at two consecutive memory cells )\n\t2dup ! nip 1+ ! ;\n\n( @bug I don't think this is correct. )\n: r@ ( -- u, R: u -- )\n\tr> r @ swap >r ;\n\n: rp@ ( -- u, R: u -- )\n\tr> r @ swap >r ;\n\n( @todo r!, rp! )\n\n: 0> ( n -- bool )\n\t0 > ;\n\n: 0<= ( n -- bool )\n\t0> not ;\n\n: 0< ( n -- bool )\n\t0 < ;\n\n: 0>= ( n -- bool )\n\t0< not ;\n\n: 0<> ( n -- bool )\n\t0 <> ;\n\n: signum ( n -- -1 | 0 | 1 : Signum function )\n\tdup 0> if drop 1 exit then\n\t 0< if -1 exit then\n\t0 ;\n\n: nand ( u u -- u : bitwise NAND )\n\tand invert ;\n\n: odd ( u -- bool : is 'n' odd? )\n\t1 and ;\n\n: even ( u -- bool : is 'n' even? )\n\todd not ;\n\n: nor ( u u -- u : bitwise NOR )\n\tor invert ;\n\n: ms ( u -- : wait at least 'u' milliseconds )\n\tclock + begin dup clock u< until drop ;\n\n: sleep ( u -- : sleep for 'u' seconds )\n\t1000 * ms ;\n\n: align ( addr -- addr : align an address, nop in this implemented )\n\timmediate ;\n\n: ) ( -- : do nothing, this allows easy commenting out of code )\n\timmediate ;\n\n: bell ( -- : emit an ASCII BEL character )\n\t7 emit ;\n\n: b\/buf ( -- u : bytes per buffer )\n\t1024 ;\n\n: .d ( x -- x : debug print )\n\tdup . ;\n\n: compile, ( x -- : )\n\t, ;\n\n: >mark ( -- : write a hole into the dictionary and push a pointer to it )\n\there 0 , ;\n\n: r - r> u< ;\n\n: invalidate ( -- : invalidate this Forth core )\n\t1 `invalid ! ;\n\n: signed ( x -- bool : return true if sign bit set )\n\t[ 1 size 8 * 1- lshift ] literal and logical ;\n\n: u>= ( x y -- bool : unsigned greater than or equal to )\n\t2dup u> >r = r> or ;\n\n: u<= ( x y -- bool : unsigned less than or equal to )\n\tu>= not ;\n\n: rdrop ( R: x -- : drop a value from the return stack )\n\tr> ( get caller's return address )\n\tr> ( get value to drop )\n\tdrop ( drop it like it's hot )\n\t>r ; ( return return address )\n\n: rdup\n\tr> ( get caller's return address )\n\tr> ( get value to duplicate )\n\tdup ( ... )\n\t>r >r >r ; ( make it all work )\n\n: chere ( -- c-addr : here as in character address units )\n\there chars> ;\n\n: source ( -- c-addr u )\n\t#tib ( size of input buffer, in characters )\n\ttib ; ( start of input buffer, in characters )\n\n: stdin? ( -- bool : are we reading from standard in? )\n\t`fin @ `stdin @ = ;\n\n: source-id ( -- 0 | -1 | file-id )\n\t( \t\n\tValue Input Source\n\t-1 String\n\t0 Reading from user input \/ standard in\n\tfile-id )\n\t`source-id @\n\t0= if\n\t\tstdin? if 0 else `fin @ then\n\telse\n\t\t-1\n\tthen ;\n\n: under ( x1 x2 -- x1 x1 x2 )\n\t>r dup r> ;\n\n: 2nip ( n1 n2 n3 n4 -- n3 n4 )\n\t>r >r 2drop r> r> ;\n\n: 2over ( n1 n2 n3 n4 \u2013 n1 n2 n3 n4 n1 n2 )\n\t>r >r 2dup r> swap >r swap r> r> -rot ;\n\n: 2swap ( n1 n2 n3 n4 \u2013 n3 n4 n1 n2 )\n\t>r -rot r> -rot ;\n\n: 2tuck ( n1 n2 n3 n4 \u2013 n3 n4 n1 n2 n3 n4 )\n\t2swap 2over ;\n\n: 3drop ( n1 n2 n3 -- )\n\tdrop 2drop ;\n\n: 4drop ( n1 n2 n3 n4 -- )\n\t2drop 2drop ;\n\n: nos1+ ( x1 x2 -- x1+1 x2 : increment the next variable on that stack )\n\tswap 1+ swap ;\n\n: ?dup-if immediate ( x -- x | - : ?dup and if rolled into one! )\n\t['] ?dup , postpone if ;\n\n: ?if ( -- : non destructive if )\n\timmediate ['] dup , postpone if ;\n\n: (hide) ( token -- hide-token : this hides a word from being found by the interpreter )\n\t?dup-if\n\t\tdup @ hidden-mask or swap tuck ! exit\n\tthen 0 ;\n\n: hide ( WORD -- : hide with drop )\n\tfind dup if (hide) then drop ;\n\n: reveal ( hide-token -- : reveal a hidden word )\n\tdup @ hidden-mask invert and swap ! ;\n\n: ?exit ( x -- : exit current definition if not zero )\n\tif rdrop exit then ;\n\n: decimal? ( c -- f : is character a number? )\n\t[char] 0 [ char 9 1+ ] literal within ;\n\n: lowercase? ( c -- f : is character lower case? )\n\t[char] a [ char z 1+ ] literal within ;\n\n: uppercase? ( C -- f : is character upper case? )\n\t[char] A [ char Z 1+ ] literal within ;\n\n: alpha? ( C -- f : is character part of the alphabet? )\n\tdup lowercase? swap uppercase? or ;\n\n: alphanumeric? ( C -- f : is character alphabetic or a number ? )\n\tdup alpha? swap decimal? or ;\n\n: printable? ( c -- bool : is printable, excluding new lines and tables )\n\t32 127 within ;\n\n: >upper ( c -- C : convert char to uppercase iff lower case )\n\tdup lowercase? if bl xor then ;\n\n: >lower ( C -- c : convert char to lowercase iff upper case )\n\tdup uppercase? if bl xor then ;\n\n: <=> ( x y -- z : spaceship operator! )\n\t2dup\n\t> if 2drop -1 exit then\n\t< ;\n\n: start-address ( -- c-addr : push the start address )\n\t`start-address @ ;\n\n: >real-address ( c-addr -- r-addr : convert an interpreter address to a real address )\n\tstart-address + ;\n\n: real-address> ( c-addr -- r-addr : convert a real address to an interpreter address )\n\tstart-address - ;\n\n: peek ( r-addr -- n : )\n\tpad chars> >real-address swap size memory-copy pad @ ;\n\n: poke ( n r-addr -- : )\n\tswap pad ! pad chars> >real-address size memory-copy ;\n\n: die! ( x -- : controls actions when encountering certain errors )\n\t`error-handler ! ;\n\n: start! ( cfa -- : set the word to execute at startup )\n\t`instruction ! ;\t\n\n: warm ( -- : restart the interpreter, warm restart )\n\t1 restart ;\n\n: trip ( x -- x x x : triplicate a number )\n\tdup dup ;\n\n: roll ( xu xu-1 ... x0 u -- xu-1 ... x0 xu : move u+1 items on the top of the stack by u )\n\t[ smudge ] ( un-hide this word so we can call it recursively )\n\tdup 0 >\n\tif\n\t\tswap >r 1- roll r> swap\n\telse\n\t\tdrop\n\tthen ;\nsmudge\n\n: 2rot ( n1 n2 n3 n4 n5 n6 \u2013 n3 n4 n5 n6 n1 n2 )\n\t5 roll 5 roll ;\n\n: s>d ( x -- d : convert a signed value to a double width cell )\n\t( @note the if...else...then is only necessary as this Forths\n\tbooleans are 0 and 1, not 0 and -1 as it usually is )\n\tdup 0< if -1 else 0 then ;\n\n: trace ( level -- : set tracing level )\n\t`debug ! ;\n\n: verbose ( -- : get the log level )\n\t`debug @ ;\n\n: count ( c-addr1 -- c-addr2 u : get a string whose first char is its length )\n\tdup c@ nos1+ ;\n\n: bounds ( x y -- y+x x : make an upper and lower bound )\n\tover + swap ;\n\n: aligned ( unaligned -- aligned : align a pointer )\n\t[ size 1- ] literal +\n\t[ size 1- ] literal invert and ;\n\n: rdepth\n\tmax-core `stack-size @ - r @ swap - ;\n\n: argv ( -- r-addr : push pointer to array of string pointers to program )\n\t`argv @ ;\n\n: argc ( -- u : push the number of arguments in the argv array )\n\t`argc @ ;\n\n: +- ( x1 x2 -- x3 : copy the sign of x1 to x2 giving x3 )\n\t[ sign-bit 1- ] literal and\n\tswap\n\tsign-bit and or ;\n\n: \/string ( c-addr1 u1 u2 -- c-addr2 u2 : advance a string by n characters )\n\tover min rot over + -rot - ;\n\nhide stdin?\n\n: cfa immediate ( find-address -- cfa )\n\t( Given the address of the PWD field of a word this\n\tfunction will return an execution token for the word )\n\t( @todo if < dictionary start PWD is invalid )\n\t ;\n\n: again immediate\n\t( loop unconditionally in a begin-loop:\n\t\tbegin ... again )\n\t['] branch , body ( xt -- a-addr : a-addr is data field of a CREATEd word )\n\\\tcfa 5 + ;\n\n\n: execute ( xt -- : given an execution token, execute the word )\n\t( create a word that pushes the address of a hole to write to.\n\tA literal takes up two words, '!' takes up one, that's right,\n\tsome self modifying code! )\n\t[ here 3 cells + literal ] ( calculate place to write to )\n\t! ( write an execution token to a hole )\n\t[ 0 , ] ; ( this is the hole we write )\n\n( @todo integrate catch\/throw into the interpreter as primitives )\n: catch ( xt -- exception# | 0 : return addr on stack )\n\tsp@ >r ( xt : save data stack pointer )\n\t`handler @ >r ( xt : and previous handler )\n\tr@ `handler ! ( xt : set current handler )\n\texecute ( execute returns if no throw )\n\tr> `handler ! ( restore previous handler )\n\tr> drop ( discard saved stack ptr )\n\t0 ; ( 0 : normal completion )\n\n( @todo use this everywhere )\n: throw ( ??? exception# -- ??? exception# )\n\t?dup-if ( exc# \\ 0 throw is no-op )\n\t\t`handler @ r ! ( exc# : restore prev return stack )\n\t\tr> `handler ! ( exc# : restore prev handler )\n\t\tr> swap >r ( saved-sp : exc# on return stack )\n\t\tsp! drop r> ( exc# : restore stack )\n\t\t( return to the caller of catch because return )\n\t\t( stack is restored to the state that existed )\n\t\t( when catch began execution )\n\tthen ;\n\n: interpret ( c1\" xxx\" ... cn\" xxx\" -- : This word implements the interpreter loop )\n\tbegin\n\t['] read catch\n\t?dup-if [char] ! emit tab . cr then ( exception handler of last resort )\n\tagain ;\n\n: [interpret] ( c1\" xxx\" ... cn\" xxx\" -- : immediate version of interpret )\n\timmediate interpret ;\n\ninterpret ( use the new interpret word, which can catch exceptions )\n\nfind [interpret] cell+ start! ( the word executed on restart is now our new word )\n\n( The following words are using in various control structure related\nwords to make sure they only execute in the correct state )\n\n: ?comp ( -- : error if not compiling )\n\tstate @ 0= if -14 throw then ;\n\n: ?exec ( -- : error if not executing )\n\tstate @ if -22 throw then ;\n\n( begin...while...repeat These are defined in a very \"Forth\" way )\n: while\n\t?comp\n\timmediate postpone if ( branch to repeats THEN ) ;\n\n: whilst postpone while ;\n\n: repeat immediate\n\t?comp\n\tswap ( swap BEGIN here and WHILE here )\n\tpostpone again ( again jumps to begin )\n\tpostpone then ; ( then writes to the hole made in if )\n\n: never ( never...then : reserve space in word )\n\timmediate 0 [literal] postpone if ;\n\n: unless ( bool -- : like IF but execute clause if false )\n\timmediate ?comp ['] 0= , postpone if ;\n\n: endif ( synonym for THEN )\n\timmediate ?comp postpone then ;\n\n( ==================== Basic Word Set ======================== )\n\n( ==================== DOER\/MAKE ============================= )\n( DOER\/MAKE is a word set that is quite powerful and is\ndescribed in Leo Brodie's book \"Thinking Forth\". It can be\nused to make words whose behavior can change after they\nare defined. It essentially makes the structured use of\nself-modifying code possible, along with the more common\ndefinitions of \"defer\/is\".\n\nAccording to \"Thinking Forth\", it has two purposes:\n\n1. To change the state of a function.\n2. To factor out common phrases of a words definition.\n\nAn example of the first instance:\n\n\tdoer say\n\t: sad \" Good bye, cruel World!\" cr ;\n\t: happy \" Hello, World!\" cr ;\n\n\t: person say ;\n\n\tmake person happy\n\tperson \\ prints \"Good bye, cruel World!\"\n\n\tmake person sad\n\tperson \\ prints \"Hello, World!\"\n\nAn example of the second:\n\n\tdoer op\n\n\t: sum \\ n0 ... nX X -- sum<0..X>\n\t\tmake op + 1 do op loop ;\n\n\t: mul \\ n0 ... nX X -- mul<0..X>\n\t\tmake op * 1 do op loop ;\n\nThe above example is a bit contrived, the definitions and\nfunctionality are too simple for this to be worth factoring\nout, but it shows how you can use DOER\/MAKE. )\n\n: noop ; ( -- : default word to execute for doer, does nothing )\n\n: doer ( c\" xxx\" -- : make a work whose behavior can be changed by make )\n\timmediate ?exec :: ['] noop , (;) ;\n\n: found? ( xt -- xt : thrown an exception if the xt is zero )\n\tdup 0= if -13 throw then ;\n\n( It would be nice to provide a MAKE that worked with\nexecution tokens as well, although \"defer\" and \"is\" can be\nused for that. MAKE expects two word names to be given as\narguments. It will then change the behavior of the first word\nto use the second. MAKE is a state aware word. )\n\n: make immediate ( c1\" xxx\" c2\" xxx\" : change parsed word c1 to execute c2 )\n\tfind found? cell+\n\tfind found?\n\tstate @ if ( compiling )\n\t\tswap postpone 2literal ['] ! ,\n\telse ( command mode )\n\t\tswap !\n\tthen ;\n\n( ==================== DOER\/MAKE ============================= )\n\n( ==================== Extended Word Set ===================== )\n\n: r.s ( -- : print the contents of the return stack )\n\tr>\n\t[char] < emit rdepth (.) drop [char] > emit\n\tspace\n\trdepth dup 0> if dup\n\tbegin dup while r> -rot 1- repeat drop dup\n\tbegin dup while rot dup . >r 1- repeat drop\n\tthen drop cr\n\t>r ;\n\n: log ( u base -- u : command the _integer_ logarithm of u in base )\n\t>r\n\tdup 0= if -11 throw then ( logarithm of zero is an error )\n\t0 swap\n\tbegin\n\t\tnos1+ rdup r> \/ dup 0= ( keep dividing until 'u' is zero )\n\tuntil\n\tdrop 1- rdrop ;\n\n: log2 ( u -- u : compute the _integer_ logarithm of u )\n\t2 log ;\n\n: alignment-bits ( c-addr -- u : get the bits used for aligning a cell )\n\t[ 1 size log2 lshift 1- literal ] and ;\n\n: time ( \" ccc\" -- n : time the number of milliseconds it takes to execute a word )\n\tclock >r\n\tfind found? execute\n\tclock r> - ;\n\n( defer...is is probably not standards compliant, it is still neat! )\n: (do-defer) ( -- self : pushes the location into which it is compiled )\n\tr> dup >r 1- ;\n\n: defer immediate ( \" ccc\" -- , Run Time -- location :\n\tcreates a word that pushes a location to write an execution token into )\n\t?exec\n\t:: ['] (do-defer) , (;) ;\n\n: is ( location \" ccc\" -- : make a deferred word execute a word )\n\tfind found? swap ! ;\n\nhide (do-defer)\n\n( This RECURSE word is the standard Forth word for allowing\nfunctions to be called recursively. A word is hidden from the\ncompiler until the matching ';' is hit. This allows for previous\ndefinitions of words to be used when redefining new words, it\nalso means that words cannot be called recursively unless the\nrecurse word is used.\n\nRECURSE calls the word being defined, which means that it\ntakes up space on the return stack. Words using recursion\nshould be careful not to take up too much space on the return\nstack, and of course they should terminate after a finite\nnumber of steps.\n\nWe can test \"recurse\" with this factorial function:\n\n : factorial dup 2 < if drop 1 exit then dup 1- recurse * ;\n\n)\n: recurse immediate\n\t?comp\n\tlatest cell+ , ;\n\n: myself ( -- : myself is a synonym for recurse )\n\timmediate postpone recurse ;\n\n( The \"tail\" function implements tail calls, which is just a\njump to the beginning of the words definition, for example\nthis word will never overflow the stack and will print \"1\"\nfollowed by a new line forever,\n\n\t: forever 1 . cr tail ;\n\nWhereas\n\n\t: forever 1 . cr recurse ;\n\nor\n\n\t: forever 1 . cr forever ;\n\nWould overflow the return stack. )\n\nhide tail\n: tail ( -- : perform tail recursion in current word definition )\n\timmediate\n\t?comp\n\tlatest cell+\n\t['] branch ,\n\there - cell+ , ;\n\n: factorial ( u -- u : factorial of u )\n\tdup 2 u< if drop 1 exit then dup 1- recurse * ;\n\n: gcd ( u1 u2 -- u : greatest common divisor )\n\tdup if tuck mod tail then drop ;\n\n: lcm ( u1 u2 -- u : lowest common multiple of u1 and u2 )\n\t2dup gcd \/ * ;\n\n( From: https:\/\/en.wikipedia.org\/wiki\/Integer_square_root\n\nThis function computes the integer square root of a number.\n\n@note this should be changed to the iterative algorithm so\nit takes up less space on the stack - not that is takes up\na hideous amount as it is. )\n\n: sqrt ( n -- u : integer square root )\n\tdup 0< if -11 throw then ( does not work for signed values )\n\tdup 2 < if exit then ( return 0 or 1 )\n\tdup ( u u )\n\t2 rshift recurse 2* ( u sc : 'sc' == unsigned small candidate )\n\tdup ( u sc sc )\n\t1+ dup square ( u sc lc lc^2 : 'lc' == unsigned large candidate )\n\t>r rot r> < ( sc lc bool )\n\tif drop else nip then ; ( return small or large candidate respectively )\n\n\n( ==================== Extended Word Set ===================== )\n\n( ==================== For Each Loop ========================= )\n( The foreach word set allows the user to take action over an\nentire array without setting up loops and checking bounds. It\nbehaves like the foreach loops that are popular in other\nlanguages.\n\nThe foreach word accepts a string and an execution token,\nfor each character in the string it passes the current address\nof the character that it should operate on.\n\nThe complexity of the foreach loop is due to the requirements\nplaced on it. It cannot pollute the variable stack with\nvalues it needs to operate on, and it cannot store values in\nlocal variables as a foreach loop could be called from within\nthe execution token it was passed. It therefore has to store\nall of it uses on the return stack for the duration of EXECUTE.\n\nAt the moment it only acts on strings as \"\/string\" only\nincrements the address passed to the word foreach executes\nto the next character address. )\n\n\\ (FOREACH) leaves the point at which the foreach loop\n\\ terminated on the stack, this allows programmer to determine\n\\ if the loop terminated early or not, and at which point.\n\n: (foreach) ( c-addr u xt -- c-addr u : execute xt for each cell in c-addr u\n\treturning number of items not processed )\n\tbegin\n\t\t3dup >r >r >r ( c-addr u xt R: c-addr u xt )\n\t\tnip ( c-addr xt R: c-addr u xt )\n\t\texecute ( R: c-addr u xt )\n\t\tr> r> r> ( c-addr u xt )\n\t\t-rot ( xt c-addr u )\n\t\t1 \/string ( xt c-addr u )\n\t\tdup 0= if rot drop exit then ( End of string - drop and exit! )\n\t\trot ( c-addr u xt )\n\tagain ;\n\n\\ If we do not care about returning early from the foreach\n\\ loop we can instead call FOREACH instead of (FOREACH),\n\\ it simply drops the results (FOREACH) placed on the stack.\n: foreach ( c-addr u xt -- : execute xt for each cell in c-addr u )\n\t(foreach) 2drop ;\n\n\\ RETURN is used for an early exit from within the execution\n\\ token, it leaves the point at which it exited\n: return ( -- n : return early from within a foreach loop function, returning number of items left )\n\trdrop ( pop off this words return value )\n\trdrop ( pop off the calling words return value )\n\trdrop ( pop off the xt token )\n\tr> ( save u )\n\tr> ( save c-addr )\n\trdrop ; ( pop off the foreach return value )\n\n\\ SKIP is an example of a word that uses the foreach loop\n\\ mechanism. It takes a string and a character and returns a\n\\ string that starts at the first occurrence of that character\n\\ in that string - or until it reaches the end of the string.\n\n\\ SKIP is defined in two steps, first there is a word,\n\\ (SKIP), that exits the foreach loop if there is a match,\n\\ if there is no match it does nothing. In either case it\n\\ leaves the character to skip until on the stack.\n\n: (skip) ( char c-addr -- char : exit out of foreach loop if there is a match )\n\tover swap c@ = if return then ;\n\n\\ SKIP then setups up the foreach loop, the char argument\n\\ will present on the stack when (SKIP) is executed, it must\n\\ leave a copy on the stack whatever happens, this is then\n\\ dropped at the end. (FOREACH) leaves the point at which\n\\ the loop terminated on the stack, which is what we want.\n\n: skip ( c-addr u char -- c-addr u : skip until char is found or until end of string )\n\t-rot ['] (skip) (foreach) rot drop ;\nhide (skip)\n\n( ==================== For Each Loop ========================= )\n\n( ==================== Hiding Words ========================== )\n( The two functions hide{ and }hide allow lists of words to\nbe hidden, instead of just hiding individual words. It stops\nthe dictionary from being polluted with meaningless words in\nan easy way. )\n\n: }hide ( should only be matched with 'hide{' )\n\timmediate -22 throw ;\n\n: hide{ ( -- : hide a list of words, the list is terminated with \"}hide\" )\n\t?exec\n\tbegin\n\t\tfind ( find next word )\n\t\tdup [ find }hide ] literal = if\n\t\t\tdrop exit ( terminate hide{ )\n\t\tthen\n\t\tdup 0= if -15 throw then\n\t\t(hide) drop\n\tagain ;\n\nhide (hide)\n\n( ==================== Hiding Words ========================== )\n\n( The words described here on out get more complex and will\nrequire more of an explanation as to how they work. )\n\n( ==================== Create Does> ========================== )\n\n( The following section defines a pair of words \"create\"\nand \"does>\" which are a powerful set of words that can be\nused to make words that can create other words. \"create\"\nhas both run time and compile time behavior, whilst \"does>\"\nonly works at compile time in conjunction with \"create\". These\ntwo words can be used to add constants, variables and arrays\nto the language, amongst other things.\n\nA simple version of create is as follows\n\n\t: create :: dolist , here 2 cells + , ' exit , 0 state ! ;\n\nBut this version is much more limited.\n\n\"create\"...\"does>\" is one of the constructs that makes Forth\nForth, it allows the creation of words which can define new\nwords in themselves, and thus allows us to extend the language\neasily. )\n\n: write-exit ( -- : A word that write exit into the dictionary )\n\t['] _exit , ;\n\n: write-compile, ( -- : A word that writes , into the dictionary )\n\t['] , , ;\n\n: create ( create a new work that pushes its data field )\n\t:: ( compile a word )\n\tdolit , ( write push into new word )\n\there 2 cells + , ( push a pointer to data field )\n\t(;) ; ( write exit, switch to command mode )\n\n: mark write-compile, ( Write in a place holder 0 and push a pointer to to be used by does> )\n\tdolit , write-exit write-compile, ( Write in an exit in the word we're compiling. )\n\t['] [ , ; ( Make sure to change the state back to command mode )\n\n\\ : ( hole-to-patch -- )\n\timmediate\n\t?comp\n\twrite-exit ( we don't want the defining word to exit, but the *defined* word to )\n\there swap ! ( patch in the code fields to point to )\n\tdolist , ; ( write a run in )\n\nhide{ write-compile, write-exit }hide\n\n( Now that we have create...does> we can use it to create\narrays, variables and constants, as we mentioned before. )\n\n: array ( u c\" xxx\" -- : create a named array of length u )\n\tcreate allot does> + ;\n\n: variable ( x c\" xxx\" -- : create a variable will initial value of x )\n\tcreate , does> ;\n\n\\ : constant ( x c\" xxx\" -- : create a constant with value of x )\n\\\tcreate , does> @ ;\n\n: table ( u c\" xxx\" --, Run Time: -- addr u : create a named table )\n\tcreate dup , allot does> dup @ ;\n\n: string ( u c\" xxx\" --, Run Time: -- c-addr u : create a named string )\n\tcreate dup , chars allot does> dup @ swap 1+ chars> swap ;\n\n\\ : +field \\ n <\"name\"> -- ; exec: addr -- 'addr\n\\ create over , +\n\\ does> @ + ;\n\\\n\\ : begin-structure \\ -- addr 0 ; -- size\n\\ \tcreate\n\\ \there 0 0 , \\ mark stack, lay dummy\n\\ \tdoes> @ ; \\ -- rec-len\n\\\n\\ : end-structure \\ addr n --\n\\ swap ! ; \\ set len\n\\\n\\ begin-structure point\n\\ \tpoint +field p.x\n\\ \tpoint +field p.y\n\\ end-structure\n\\\n\\ This should work...\n\\ : buffer: ( u c\" xxx\" --, Run Time: -- addr )\n\\\tcreate allot ;\n\n: 2constant\n\tcreate , , does> dup 1+ @ swap @ ;\n\n: 2variable\n\tcreate , , does> ;\n\n: enum ( x \" ccc\" -- x+1 : define a series of enumerations )\n\tdup constant 1+ ;\n\n( ==================== Create Does> ========================== )\n\n( ==================== Do ... Loop =========================== )\n\n( The following section implements Forth's do...loop\nconstructs, the word definitions are quite complex as it\ninvolves a lot of juggling of the return stack. Along with\nbegin...until do loops are one of the main looping constructs.\n\nUnlike begin...until do accepts two values a limit and a\nstarting value, they are also words only to be used within a\nword definition, some Forths extend the semantics so looping\nconstructs operate in command mode, this Forth does not do\nthat as it complicates things unnecessarily.\n\nExample:\n\n\t: example-1\n\t\t10 1 do\n\t\t\ti . i 5 > if cr leave then loop\n\t\t100 . cr ;\n\n\texample-1\n\nPrints:\n\t1 2 3 4 5 6\n\nIn \"example-1\" we can see the following:\n\n1. A limit, 10, and a start value, 1, passed to \"do\".\n2. A word called 'i', which is the current count of the loop.\n3. If the count is greater than 5, we call a word call\nLEAVE, this word exits the current loop context as well as\nthe current calling word.\n4. \"100 . cr\" is never called. This should be changed in\nfuture revision, but this version of leave exits the calling\nword as well.\n\n'i', 'j', and LEAVE *must* be used within a do...loop\nconstruct.\n\nIn order to remedy point 4. loop should not use branch but\ninstead should use a value to return to which it pushes to\nthe return stack )\n\n: (do)\n\tswap ( swap the limit and start )\n\tr> ( save our return stack to temporary variable )\n\t-rot ( limit start return -- return start limit )\n\t>r ( push limit onto return stack )\n\t>r ( push start onto return stack )\n\t>r ; ( restore our return address )\n\n: do immediate ( Run time: high low -- : begin do...loop construct )\n\t?comp\n\t['] (do) ,\n\tpostpone begin ;\n\n: (unloop) ( -- , R: i limit -- : remove limit and i from )\n\tr> ( save our return address )\n\trdrop ( pop off i )\n\trdrop ( pop off limit )\n\t>r ; ( restore our return stack )\n\n: (+loop) ( x -- bool : increment loop variable by x and test it )\n\tr@ 1- ( get the pointer to i )\n\t+! ( add value to it )\n\tr@ 1- @ ( find i again )\n\tr@ 2- @ ( find the limit value )\n\tu>= ;\n\n: (loop) ( -- bool : increment loop variable by 1 and test it )\n\tr@ 1- ( get the pointer to i )\n\t1+! ( add one to it )\n\tr@ 1- @ ( find the value again )\n\tr@ 2- @ ( find the limit value )\n\tu>= ;\n\n: loop ( -- : end do...loop construct )\n\timmediate ?comp ['] (loop) , postpone until ['] (unloop) , ;\n\n: +loop ( x -- : end do...+loop loop construct )\n\timmediate ?comp ['] (+loop) , postpone until ['] (unloop) , ;\n\n: leave ( -- , R: i limit return -- : break out of a do-loop construct )\n\t(unloop)\n\trdrop ; ( return to the caller's caller routine )\n\n: ?leave ( x -- , R: i limit return -- | i limit return : conditional leave )\n\tif\n\t\t(unloop)\n\t\trdrop ( return to the caller's caller routine )\n\tthen ;\n\n\\ @todo define '(i)', '(j)' and '(k)', then make their\n\\ wrappers, 'i', 'j' and 'k' call ?comp then compile a pointer\n\\ to the thing that implements them, likewise for leave,\n\\ loop and +loop.\n: i ( -- i : Get current, or innermost, loop index in do...loop construct )\n\tr> r> ( pop off return address and i )\n\ttuck ( tuck i away )\n\t>r >r ; ( restore return stack )\n\n: j ( -- j : Get outermost loop index in do...loop construct )\n\t4 rpick ;\n\n( This is a simple test function for the looping, for interactive\ntesting and debugging:\n : mm 5 1 do i . cr 4 1 do j . tab i . cr loop loop ; )\n\n: range ( nX nY -- nX nX+1 ... nY )\n\tnos1+ do i loop ;\n\n: repeater ( n0 X -- n0 ... nX )\n\t1 do dup loop ;\n\n: sum ( n0 ... nX X -- sum<0..X> )\n\t1 do + loop ;\n\n: mul ( n0 ... nX X -- mul<0..X> )\n\t1 do * loop ;\n\n: reverse ( x1 ... xn n -- xn ... x1 : reverse n items on the stack )\n\t0 do i roll loop ;\n\ndoer (banner)\nmake (banner) space\n\n: banner ( n -- : )\n\tdup 0<= if drop exit then\n\t0 do (banner) loop ;\n\n: zero ( -- : emit a single 0 character )\n\t[char] 0 emit ;\n\n: spaces ( n -- : print n spaces if n is greater than zero )\n\tmake (banner) space\n\tbanner ;\n\n: zeros ( n -- : print n spaces if n is greater than zero )\n\tmake (banner) zero\n\tbanner ;\n\nhide{ (banner) banner }hide\n\n( @todo check u for negative )\n: fill ( c-addr u char -- : fill in an area of memory with a character, only if u is greater than zero )\n\t-rot\n\t0 do 2dup i + c! loop\n\t2drop ;\n\n: default ( addr u n -- : fill in an area of memory with a cell )\n\t-rot\n\t0 do 2dup i cells + ! loop\n\t2drop ;\n\n: compare ( c-addr1 u1 c-addr2 u2 -- n : compare two strings, not quite compliant yet )\n\t>r swap r> min >r\n\tstart-address + swap start-address + r>\n\tmemory-compare ;\n\n: erase ( addr u : erase a block of memory )\n\t2chars> 0 fill ;\n\n: blank ( c-addr u : fills a string with spaces )\n\tbl fill ;\n\n( move should check that u is not negative )\n: move ( addr1 addr2 u -- : copy u words of memory from 'addr2' to 'addr1' )\n\t0 do\n\t\t2dup i + @ swap i + !\n\tloop\n\t2drop ;\n\n( It would be nice if move and cmove could share more code, as they do exactly\n the same thing but with different load and store functions, cmove> )\n: cmove ( c-addr1 c-addr2 u -- : copy u characters of memory from 'c-addr2' to 'c-addr1' )\n\t0 do\n\t\t2dup i + c@ swap i + c!\n\tloop\n\t2drop ;\n\n\n\n( ==================== Do ... Loop =========================== )\n\n( ==================== String Substitution =================== )\n\n: (subst) ( char1 char2 c-addr )\n\t3dup ( char1 char2 c-addr char1 char2 c-addr )\n\tc@ = if ( char1 char2 c-addr char1 )\n\t\tswap c! ( match, substitute character )\n\telse ( char1 char2 c-addr char1 )\n\t\t2drop ( no match )\n\tthen ;\n\n: subst ( c-addr u char1 char2 -- replace all char1 with char2 in string )\n\tswap\n\t2swap\n\t['] (subst) foreach 2drop ;\nhide (subst)\n\n0 variable c\n0 variable sub\n0 variable #sub\n\n: (subst-all) ( c-addr : search in sub\/#sub for a character to replace at c-addr )\n\tsub @ #sub @ bounds ( get limits )\n\tdo\n\t\tdup ( duplicate supplied c-addr )\n\t\tc@ i c@ = if ( check if match )\n\t\t\tdup\n\t\t\tc chars c@ swap c! ( write out replacement char )\n\t\tthen\n\tloop drop ;\n\n: subst-all ( c-addr1 u c-addr2 u char -- replace chars in str1 if in str2 with char )\n\tc chars c! #sub ! sub ! ( store strings away )\n\t['] (subst-all) foreach ;\n\nhide{ c sub #sub (subst-all) }hide\n\n( ==================== String Substitution =================== )\n\n0 variable column-counter\n4 variable column-width\n\n: column ( i -- )\t\n\tcolumn-width @ mod not if cr then ;\n\n: column.reset\t\t\n\t0 column-counter ! ;\n\n: auto-column\t\t\n\tcolumn-counter dup @ column 1+! ;\n\n0 variable x\n: x! ( x -- )\n\tx ! ;\n\n: x@ ( -- x )\n\tx @ ;\n\n: 2>r ( x1 x2 -- R: x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tswap\n\t\t>r\n\t\t>r\n\tx@ >r ; ( restore return address )\n\n: 2r> ( R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tr>\n\t\tr>\n\t\tswap\n\tx@ >r ; ( restore return address )\n\n: 2r@ ( -- x1 x2 , R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\tr> r>\n\t2dup\n\t>r >r\n\tswap\n\tx@ >r ; ( restore return address )\n\n: unused ( -- u : push the amount of core left )\n\tmax-core here - ;\n\n: accumulator ( initial \" ccc\" -- : make a word that increments by a value and pushes the result )\n\tcreate , does> tuck +! @ ;\n\n: counter ( n \" ccc\" --, Run Time: -- x : make a word that increments itself by one, starting from 'n' )\n\tcreate 1- , does> dup 1+! @ ;\n\n0 variable delim\n: accepter ( c-addr max delimiter -- i )\n\t( store a \"max\" number of chars at c-addr until \"delimiter\" encountered,\n\tthe number of characters stored is returned )\n\tdelim ! ( store delimiter used to stop string storage when encountered)\n\t0\n\tdo\n\t\tkey dup delim @ <>\n\t\tif\n\t\t\tover c! 1+\n\t\telse ( terminate string )\n\t\t\tdrop 0 swap c!\n\t\t\ti\n\t\t\tleave\n\t\tthen\n\tloop\n\t-18 throw ; ( read in too many chars )\nhide delim\n\n: skip ( char -- : read input until string is reached )\n\tkey drop >r 0 begin drop key dup rdup r> <> until rdrop ;\n\n: word ( c -- c-addr : parse until 'c' is encountered, push transient counted string )\n\ttib #tib 0 fill ( zero terminal input buffer so we NUL terminate string )\n\tdup skip tib 1+ c!\n\t>r\n\ttib 2+\n\t#tib 1-\n\tr> accepter 1+\n\ttib c!\n\ttib ;\nhide skip\n\n: accept ( c-addr +n1 -- +n2 : see accepter definition )\n\tnl accepter ;\n\n0xFFFF constant max-string-length\n\n: (.\") ( char -- c-addr u )\n\t( @todo This really needs simplifying, to do this\n\ta set of words that operate on a temporary buffer can\n\tbe used )\n\t( Write a string into word being currently defined, this\n\tcode has to jump over the string it has just put into the\n\tdictionary so normal execution of a word can continue. The\n\tlength and character address of the string are left on the\n\tstack )\n\t>r ( save delimiter )\n\t['] branch , ( write in jump, this will jump past the string )\n\t>mark ( make hole )\n\tdup 1+ chars> ( calculate address to write to )\n\tmax-string-length\n\tr> ( restore delimiter )\n\taccepter dup >r ( write string into dictionary, save index )\n\taligned 2dup size \/ ( stack: length hole char-len hole )\n\t1+ dup allot ( update dictionary pointer with string length )\n\t1+ swap ! ( write place to jump to )\n\tdrop ( do not need string length anymore )\n\t1+ chars> ( calculate place to print )\n\tr> ; ( restore index and address of string )\n\n: length ( c-addr u -- u : push the length of an ASCIIZ string )\n tuck 0 do dup c@ 0= if 2drop i leave then 1+ loop ;\n\n: asciiz? ( c-addr u -- : is a Forth string also a ASCIIZ string )\n\ttuck length <> ;\n\n: asciiz ( c-addr u -- : trim a string until NUL terminator )\n\t2dup length nip ;\n\n: (type) ( c-addr -- : emit a single character )\n\tc@ emit ;\n\n: type ( c-addr u -- : print out 'u' characters at c-addr )\n\t['] (type) foreach ;\nhide (type)\n\n: do-string ( char -- : write a string into the dictionary reading it until char is encountered )\n\t(.\")\n\tstate @ if swap [literal] [literal] then ;\n\n128 string sbuf\n: s\" ( \"ccc\" --, Run Time -- c-addr u )\n\tkey drop sbuf 0 fill sbuf [char] \" accepter sbuf drop swap ;\nhide sbuf\n\n( @todo these strings really need rethinking, state awareness needs to be removed... )\n: type,\n\tstate @ if ['] type , else type then ;\n\n: c\"\n\timmediate key drop [char] \" do-string ;\n\n: \"\n\timmediate key drop [char] \" do-string type, ;\n\n: sprint ( c -- : print out chars until 'c' is encountered )\n\tkey drop ( drop next space )\n\t>r ( save delimiter )\n\tbegin\n\t\tkey dup ( get next character )\n\t\trdup r> ( get delimiter )\n\t\t<> if emit 0 then\n\tuntil rdrop ;\n\n: .(\n\timmediate [char] ) sprint ;\nhide sprint\n\n: .\"\n\timmediate key drop [char] \" do-string type, ;\n\nhide type,\n\n( This word really should be removed along with any usages\nof this word, it is not a very \"Forth\" like word, it accepts\na pointer to an ASCIIZ string and prints it out, it also does\nnot checking of the returned values from write-file )\n: print ( c-addr -- : print out a string to the standard output )\n\t-1 over >r length r> swap stdout write-file 2drop ;\n\n: ok\n\t\" ok\" cr ;\n\n: empty-stack ( x-n ... x-0 -- : empty the variable stack )\n\tbegin depth while drop repeat ;\n\n: (quit) ( -- : do the work of quit, without the restart )\n\t0 `source-id ! ( set source to read from file )\n\t`stdin @ `fin ! ( read from stdin )\n\tpostpone [ ( back into command mode )\n\t['] interpret start! ; ( set interpreter starting word )\n\n: quit ( -- : Empty return stack, go back to command mode, read from stdin, interpret input )\n\t(quit)\n\t-1 restart ; ( restart the interpreter )\n\n: abort\n\t-1 throw ;\n\n: (abort\") ( do the work of abort )\n\t(quit)\n\t-2 throw ;\n\n: abort\" immediate\n\tpostpone \"\n\t['] cr , ['] (abort\") , ;\n\n\n( ==================== Error Messages ======================== )\n( This section implements a look up table for error messages,\nthe word MESSAGE was inspired by FIG-FORTH, words like ERROR\nwill be implemented later.\n\nThe DPANS standard defines a range of numbers which correspond\nto specific errors, the word MESSAGE can decode these numbers\nby looking up known words in a table.\n\nSee: http:\/\/lars.nocrew.org\/dpans\/dpans9.htm\n\n Code Reserved for\n ---- ------------\n -1 ABORT\n -2 ABORT\"\n -3 stack overflow\n -4 stack underflow\n -5 return stack overflow\n -6 return stack underflow\n -7 do-loops nested too deeply during execution\n -8 dictionary overflow\n -9 invalid memory address\n -10 division by zero\n -11 result out of range\n -12 argument type mismatch\n -13 undefined word\n -14 interpreting a compile-only word\n -15 invalid FORGET\n -16 attempt to use zero-length string as a name\n -17 pictured numeric output string overflow\n -18 parsed string overflow\n -19 definition name too long\n -20 write to a read-only location\n -21 unsupported operation [e.g., AT-XY on a\n too-dumb terminal]\n -22 control structure mismatch\n -23 address alignment exception\n -24 invalid numeric argument\n -25 return stack imbalance\n -26 loop parameters unavailable\n -27 invalid recursion\n -28 user interrupt\n -29 compiler nesting\n -30 obsolescent feature\n -31 >BODY used on non-CREATEd definition\n -32 invalid name argument [e.g., TO xxx]\n -33 block read exception\n -34 block write exception\n -35 invalid block number\n -36 invalid file position\n -37 file I\/O exception\n -38 non-existent file\n -39 unexpected end of file\n -40 invalid BASE for floating point conversion\n -41 loss of precision\n -42 floating-point divide by zero\n -43 floating-point result out of range\n -44 floating-point stack overflow\n -45 floating-point stack underflow\n -46 floating-point invalid argument\n -47 compilation word list deleted\n -48 invalid POSTPONE\n -49 search-order overflow\n -50 search-order underflow\n -51 compilation word list changed\n -52 control-flow stack overflow\n -53 exception stack overflow\n -54 floating-point underflow\n -55 floating-point unidentified fault\n -56 QUIT\n -57 exception in sending or receiving a character\n -58 [IF], [ELSE], or [THEN] exception )\n\n( The word X\" compiles a counted string into a word definition, it\nis useful as a space saving measure and simplifies our lookup table\ndefinition. Instead of having to store a C-ADDR and it's length, we\nonly have to store a C-ADDR in the lookup table, which occupies only\none element instead of two. The strings used for error messages are\nshort, so the limit of 256 characters that counted strings present\nis not a problem. )\n\n: x\" immediate ( c\" xxx\" -- c-addr : compile a counted string )\n\t[char] \" word ( read in a counted string )\n\tcount -1 \/string dup ( go back to start of string )\n\tpostpone never >r ( make a hole in the dictionary )\n\tchere >r ( character marker )\n\taligned chars allot ( allocate space in hole )\n\tr> dup >r -rot cmove ( copy string from word buffer )\n\tr> ( restore pointer to counted string )\n\tr> postpone then ; ( finish hole )\n\ncreate lookup 64 cells allot ( our lookup table )\n\n: nomsg ( -- c-addr : push counted string to undefined error message )\n\tx\" Undefined Error\" literal ;\n\nlookup 64 cells find nomsg default\n\n1 variable warning\n\n: message ( n -- : print an error message )\n\twarning @ 0= if . exit then\n\tdup -63 1 within if abs lookup + @ count type exit then\n\tdrop nomsg count type ;\n\n1 counter #msg\n\n: nmsg ( n -- : populate next slot in available in LOOKUP )\n\tlookup #msg cells + ! ;\n\nx\" ABORT\" nmsg\nx\" ABORT Double Quote\" nmsg\nx\" stack overflow\" nmsg\nx\" stack underflow\" nmsg\nx\" return stack overflow\" nmsg\nx\" return stack underflow\" nmsg\nx\" do-loops nested too deeply during execution\" nmsg\nx\" dictionary overflow\" nmsg\nx\" invalid memory address\" nmsg\nx\" division by zero\" nmsg\nx\" result out of range\" nmsg\nx\" argument type mismatch\" nmsg\nx\" undefined word\" nmsg\nx\" interpreting a compile-only word\" nmsg\nx\" invalid FORGET\" nmsg\nx\" attempt to use zero-length string as a name\" nmsg\nx\" pictured numeric output string overflow\" nmsg\nx\" parsed string overflow\" nmsg\nx\" definition name too long\" nmsg\nx\" write to a read-only location\" nmsg\nx\" unsupported operation \" nmsg\nx\" control structure mismatch\" nmsg\nx\" address alignment exception\" nmsg\nx\" invalid numeric argument\" nmsg\nx\" return stack imbalance\" nmsg\nx\" loop parameters unavailable\" nmsg\nx\" invalid recursion\" nmsg\nx\" user interrupt\" nmsg\nx\" compiler nesting\" nmsg\nx\" obsolescent feature\" nmsg\nx\" >BODY used on non-CREATEd definition\" nmsg\nx\" invalid name argument \" nmsg\nx\" block read exception\" nmsg\nx\" block write exception\" nmsg\nx\" invalid block number\" nmsg\nx\" invalid file position\" nmsg\nx\" file I\/O exception\" nmsg\nx\" non-existent file\" nmsg\nx\" unexpected end of file\" nmsg\nx\" invalid BASE for floating point conversion\" nmsg\nx\" loss of precision\" nmsg\nx\" floating-point divide by zero\" nmsg\nx\" floating-point result out of range\" nmsg\nx\" floating-point stack overflow\" nmsg\nx\" floating-point stack underflow\" nmsg\nx\" floating-point invalid argument\" nmsg\nx\" compilation word list deleted\" nmsg\nx\" invalid POSTPONE\" nmsg\nx\" search-order overflow\" nmsg\nx\" search-order underflow\" nmsg\nx\" compilation word list changed\" nmsg\nx\" control-flow stack overflow\" nmsg\nx\" exception stack overflow\" nmsg\nx\" floating-point underflow\" nmsg\nx\" floating-point unidentified fault\" nmsg\nx\" QUIT\" nmsg\nx\" exception in sending or receiving a character\" nmsg\nx\" [IF], [ELSE], or [THEN] exception\" nmsg\n\nhide{ nmsg #msg nomsg }hide\n \n\n( ==================== Error Messages ======================== )\n\n\n( ==================== CASE statements ======================= )\n( This simple set of words adds case statements to the\ninterpreter, the implementation is not particularly efficient,\nbut it works and is simple.\n\nBelow is an example of how to use the CASE statement,\nthe following word, \"example\" will read in a character and\nswitch to different statements depending on the character\ninput. There are two cases, when 'a' and 'b' are input, and\na default case which occurs when none of the statements match:\n\n\t: example\n\t\tchar\n\t\tcase\n\t\t\t[char] a of \" a was selected \" cr endof\n\t\t\t[char] b of \" b was selected \" cr endof\n\n\t\t\tdup \\ encase will drop the selector\n\t\t\t\" unknown char: \" emit cr\n\t\tendcase ;\n\n\texample a \\ prints \"a was selected\"\n\texample b \\ prints \"b was selected\"\n\texample c \\ prints \"unknown char: c\"\n\nOther examples of how to use case statements can be found\nthroughout the code.\n\nFor a simpler case statement see, Volume 2, issue 3, page 48\nof Forth Dimensions at http:\/\/www.forth.org\/fd\/contents.html )\n\n: case immediate\n\t?comp\n\t['] branch , 3 cells , ( branch over the next branch )\n\there ['] branch , ( mark: place endof branches back to with again )\n\t>mark swap ; ( mark: place endcase writes jump to with then )\n\n: over= ( x y -- [x 0] | 1 : )\n\tover = if drop 1 else 0 then ;\n\n: of\n\timmediate ?comp ['] over= , postpone if ;\n\n: endof\n\timmediate ?comp over postpone again postpone then ;\n\n: endcase\n\timmediate ?comp ['] drop , 1+ postpone then drop ;\n\n( ==================== CASE statements ======================= )\n\n( ==================== Conditional Compilation =============== )\n( The words \"[if]\", \"[else]\" and \"[then]\" implement conditional\ncompilation, they can be nested as well\n\nSee http:\/\/lars.nocrew.org\/dpans\/dpans15.htm for more\ninformation\n\nA much simpler conditional compilation method is the following\nsingle word definition:\n\n : compile-line? 0= if [ find \\\\ , ] then ;\n\nWhich will skip a line if a conditional is false, and compile\nit if true )\n\n( These words really, really need refactoring, I could use the newly defined\n \"defer\" to help out with this )\n0 variable nest ( level of [if] nesting )\n0 variable [if]-word ( populated later with \"find [if]\" )\n0 variable [else]-word ( populated later with \"find [else]\")\n: [then] immediate ;\n: reset-nest 1 nest ! ;\n: unnest? [ find [then] ] literal = if nest 1-! then ;\n: nest? [if]-word @ = if nest 1+! then ;\n: end-nest? nest @ 0= ;\n: match-[else]? [else]-word @ = nest @ 1 = and ;\n\n: [if] ( bool -- : conditional execution )\n\t?exec\n\tunless\n\t\treset-nest\n\t\tbegin\n\t\t\tfind\n\t\t\tdup nest?\n\t\t\tdup match-[else]? if drop exit then\n\t\t\t unnest?\n\t\t\tend-nest?\n\t\tuntil\n\tthen ;\n\n: [else] ( discard input until [then] encounter, nesting for [if] )\n\t?exec\n\treset-nest\n\tbegin\n\t\tfind\n\t\tdup nest? unnest?\n\t\tend-nest?\n\tuntil ;\n\nfind [if] [if]-word !\nfind [else] [else]-word !\n\n: ?( if postpone ( then ; \\ conditionally read until ')'\n: ?\\ if postpone \\ then ;\n: 16bit\\ size 2 <> if postpone \\ then ;\n: 32bit\\ size 4 <> if postpone \\ then ;\n: 64bit\\ size 8 <> if postpone \\ then ;\n\nhide{\n\t[if]-word [else]-word nest\n\treset-nest unnest? match-[else]?\n\tend-nest? nest?\n}hide\n\n( ==================== Conditional Compilation =============== )\n\n( ==================== Endian Words ========================== )\n( This words are allow the user to determinate the endianess\nof the machine that is currently being used to execute libforth,\nthey make heavy use of conditional compilation )\n\n0 variable x\n\nsize 2 = [if] 0x0123 x ! [then]\nsize 4 = [if] 0x01234567 x ! [then]\nsize 8 = [if] 0x01234567abcdef x ! [then]\n\nx chars> c@ 0x01 = constant endian\n\nhide{ x }hide\n\n: swap16 ( x -- x : swap the byte order of a 16 bit number )\n\tdup 256* 0xff00 and >r 256\/ lsb r> or ;\n\nsize 4 >= [if]\n\t: swap32\n\t\tdup 0xffff and swap16 16 lshift swap\n\t\t16 rshift 0xffff and swap16 or ;\n[then]\n\nsize 8 >= [if]\n\t: swap64 ( x -- x : swap the byte order of a 64 bit number )\n\t\t dup 0xffffffff and swap32 32 lshift swap\n\t\t 32 rshift 0xffffffff and swap32 or ;\n[then]\n\nsize 2 = [if]\n\tendian\n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order )\n\t\tswap16 ;\n\t: >big ( x -- x : host byte order to big endian order )\n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order )\n\t\t;\n\t: >big ( x -- x : host byte order to big endian order )\n\t\tswap16 ;\n\t[then]\n[then]\n\nsize 4 = [if]\n\tendian\n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order )\n\t\tswap32 ;\n\t: >big ( x -- x : host byte order to big endian order )\n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order )\n\t\t;\n\t: >big ( x -- x : host byte order to big endian order )\n\t\tswap32 ;\n\t[then]\n[then]\n\nsize 8 = [if]\n\tendian\n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order )\n\t\tswap64 ;\n\t: >big ( x -- x : host byte order to big endian order )\n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order )\n\t\t;\n\t: >big ( x -- x : host byte order to big endian order )\n\t\tswap64 ;\n\t[then]\n[then]\n\n( ==================== Endian Words ========================== )\n\n( ==================== Misc words ============================ )\n\n: (base) ( -- base : unmess up libforth's base variable )\n\tbase @ dup 0= if drop 10 then ;\n\n: #digits ( u -- u : number of characters needed to represent 'u' in current base )\n\tdup 0= if 1+ exit then\n\t(base) log 1+ ;\n\n: digits ( -- u : number of characters needed to represent largest unsigned number in current base )\n\t-1 #digits ;\n\n: cdigits ( -- u : number of characters needed to represent largest characters in current base )\n\t0xff #digits ;\n\n: .r ( u -- print a number taking up a fixed amount of space on the screen )\n\tdup #digits digits swap - spaces . ;\n\n: ?.r ( u -- : print out address, right aligned )\n\t@ .r ;\n\n0 variable counter\n\n: counted-column ( index -- : special column printing for dump )\n\tcounter @ column-width @ mod\n\tnot if cr .r \" :\" space else drop then\n\tcounter 1+! ;\n\n: .chars ( x n -- : print a cell out as characters, upto n chars )\n\t0 ( from zero to the size of a cell )\n\tdo\n\t\tdup ( copy variable to print out )\n\t\tsize i 1+ - select-byte ( select correct byte )\n\t\tdup printable? not ( is it not printable )\n\t\tif drop [char] . then ( print a '.' if it is not )\n\t\temit ( otherwise print it out )\n\tloop\n\tdrop ; ( drop cell we have printed out )\n\n: lister ( addr u addr -- )\n\t0 counter ! 1- swap\n\tdo\n\t\tdup counted-column 1+ i ?.r i @ size .chars space\n\tloop ;\n\n( @todo this function should make use of DEFER and IS, then different\nversion of dump could be made that swapped out LISTER )\n: dump ( addr u -- : dump out 'u' cells of memory starting from 'addr' )\n\t1+ over + under lister drop\n\tcr ;\n\nhide{ counted-column counter }hide\n\n( Fence can be used to prevent any word defined before it from being forgotten\nUsage:\n\there fence ! )\n0 variable fence\n\n: ?fence ( addr -- : throw an exception of address is before fence )\n\tfence @ u< if -15 throw then ;\n\n: (forget) ( pwd-token -- : forget a found word and everything after it )\n\tdup 0= if -15 throw then ( word not found! )\n\tdup ?fence\n\tdup @ pwd ! h ! ;\n\n: forget ( c\" xxx\" -- : forget word and every word defined after it )\n\tfind 1- (forget) ;\n\n0 variable fp ( FIND Pointer )\n\n: rendezvous ( -- : set up a rendezvous point )\n\there ?fence\n\there fence !\n\tlatest fp ! ;\n\n: retreat ( -- : retreat to the rendezvous point, forgetting any words )\n\tfence @ h !\n\tfp @ pwd ! ;\n\nhide{ fp }hide\n\n: marker ( c\" xxx\" -- : make word the forgets itself and words after it)\n\t:: latest [literal] ['] (forget) , (;) ;\nhere fence ! ( This should also be done at the end of the file )\nhide (forget)\n\n: ** ( b e -- x : exponent, raise 'b' to the power of 'e')\n\t?dup-if\n\t\tover swap\n\t\t1 do over * loop\n\t\tnip\n\telse\n\t\tdrop 1\n\tthen ;\n\n0 variable a\n0 variable b\n0 variable m\n: equal ( a1...an b1...bn n -- a1...an b1...bn bool : determine if two lists are equal )\n\t( example:\n\t\t1 2 3\n\t\t1 2 3\n\t\t3 equal\n\treturns: 1 )\n\tdup m ! 1+ 1 ( store copy of length and use as loop index )\n\tdo\n\t\ti 1- pick b ! ( store ith element of list in b1...bn )\n\t\ti m @ + 1- pick a ! ( store ith element of list in a1...an )\n\t\ta @ b @ <> ( compare a and b for equality )\n\t\tif 0 leave then ( unequal, finish early )\n\tloop 1 ; ( lists must be equal )\n\nhide{ a b m }hide\n\n: ndrop ( u1...un n -- : drop n items )\n\t?dup-if 0 do drop loop then ;\n\n: caesar ( c key -- o : encode a alphabetic character with a key using a generalization of the Caesar cipher )\n\t>r\n\tdup uppercase? if [char] A - r> + 26 mod [char] A + exit then\n\tdup lowercase? if [char] a - r> + 26 mod [char] a + exit then\n\trdrop ; ( it goes without saying that this should not be used for anything serious! )\n\n: caesar-type ( c-addr u key : type out encoded text with a Caesar cipher )\n\t-rot bounds do i c@ over caesar emit loop drop ;\n\n: rot13 ( c -- c : encode a character with ROT-13 )\n\t13 caesar ;\n\n: rot13-type ( c-addr u : print string in ROT-13 encoded form )\n\t13 caesar-type ;\n\n\\ s\" abcdefghijklmnopqrstuvwxyz\" rot13-type -> nopqrstuvwxyzabcdefghijklm\n\\ s\" hello\" rot13-type -> uryyb\n\n( ==================== Misc words ============================ )\n\n( ==================== Pictured Numeric Output =============== )\n( Pictured numeric output is what Forths use to display\nnumbers to the screen, this Forth has number output methods\nbuilt into the Forth kernel and mostly uses them instead,\nbut the mechanism is still useful so it has been added.\n\n@todo Pictured number output should act on a double cell\nnumber not a single cell number )\n\n0 variable hld\n\n: overflow ( -- : check if we overflow the hold area )\n \there chars> pad chars> hld @ - u> if -17 throw then ;\n\n: hold ( char -- : add a character to the numeric output string )\n\toverflow pad chars> hld @ - c! hld 1+! ;\n\n: holds ( c-addr u -- : hold an entire string )\n begin dup while 1- 2dup + c@ hold repeat 2drop ;\n\n: <# ( -- : setup pictured numeric output )\n\t0 hld ! ;\n\n: sign ( -- : add a sign to the pictured numeric output string )\n\t[char] - hold ;\n\n: # ( x -- x : divide x by base, turn into a character, put in pictured output string )\n\t(base) um\/mod swap\n \tdup 9 u>\n \tif 7 + then\n \t48 + hold ;\n\n: #s ( x -- 0 : repeatedly call # on x until x is zero )\n\tbegin # dup 0= until ;\n\n: #> ( -- c-addr u : end pictured output conversion, push output string to stack )\n\t0 hold ( NUL terminate string, just in case )\n\thld 1-! ( but do not include that in the count )\n\tpad chars> hld @\n\ttuck - 1+ swap ;\n\ndoer characters\nmake characters spaces\n\n: u.rc\n\t>r <# #s #> rot drop r> over - characters type ;\n\n: u.r ( u n -- print a number taking up a fixed amount of space on the screen )\n\tmake characters spaces u.rc ;\n\n: u.rz ( u n -- print a number taking up a fixed amount of space on the screen, using leading zeros )\n\tmake characters zeros u.rc ;\n\n: u. ( u -- : display an unsigned number in current base )\n\t0 u.r ;\n\nhide{ overflow u.rc characters }hide\n\n( ==================== Pictured Numeric Output =============== )\n\n( ==================== Numeric Input ========================= )\n( The Forth executable can handle numeric input and does not\nneed the routines defined here, however the user might want\nto write routines that use >NUMBER. >NUMBER is a generic word,\nbut it is a bit difficult to use on its own. )\n\n: map ( char -- n|-1 : convert character in 0-9 a-z range to number )\n\tdup lowercase? if [char] a - 10 + exit then\n\tdup decimal? if [char] 0 - exit then\n\tdrop -1 ;\n\n: number? ( char -- bool : is a character a number in the current base )\n\t>lower map (base) u< ;\n\n: >number ( n c-addr u -- n c-addr u : convert string )\n\tbegin\n\t\t( get next character )\n\t\t2dup >r >r drop c@ dup number? ( n char bool, R: c-addr u )\n\t\tif ( n char )\n\t\t\tswap (base) * swap map + ( accumulate number )\n\t\telse ( n char )\n\t\t\tdrop\n\t\t\tr> r> ( restore string )\n\t\t\texit\n\t\tthen\n\t\tr> r> ( restore string )\n\t\t1 \/string dup 0= ( advance string and test for end )\n\tuntil ;\n\nhide{ map }hide\n\n( ==================== Numeric Input ========================= )\n\n( ==================== ANSI Escape Codes ===================== )\n( Terminal colorization module, via ANSI Escape Codes\n\nsee: https:\/\/en.wikipedia.org\/wiki\/ANSI_escape_code\nThese codes will provide a relatively portable means of\nmanipulating a terminal )\n\n27 constant 'escape'\n: CSI 'escape' emit .\" [\" ;\n0 constant black\n1 constant red\n2 constant green\n3 constant yellow\n4 constant blue\n5 constant magenta\n6 constant cyan\n7 constant white\n: foreground 30 + ;\n: background 40 + ;\n0 constant dark\n1 constant bright\nfalse variable colorize\n\n: 10u. ( n -- : print a number in decimal )\n\tbase @ >r decimal u. r> base ! ;\n\n: color ( brightness color-code -- : set the terminal color )\n\t( set color on an ANSI compliant terminal,\n\tfor example:\n\t\tbright red foreground color\n\tsets the foreground text to bright red )\n\tcolorize @ 0= if 2drop exit then\n\tCSI 10u. if .\" ;1\" then .\" m\" ;\n\n: at-xy ( x y -- : set ANSI terminal cursor position to x y )\n\tCSI 10u. [char] ; emit 10u. .\" H\" ;\n\n: page ( -- : clear ANSI terminal screen and move cursor to beginning )\n\tCSI .\" 2J\" 1 1 at-xy ;\n\n: hide-cursor ( -- : hide the cursor from view )\n\tCSI .\" ?25l\" ;\n\n: show-cursor ( -- : show the cursor )\n\tCSI .\" ?25h\" ;\n\n: save-cursor ( -- : save cursor position )\n\tCSI .\" s\" ;\n\n: restore-cursor ( -- : restore saved cursor position )\n\tCSI .\" u\" ;\n\n: reset-color ( -- : reset terminal color to its default value)\n\tcolorize @ 0= if exit then\n\tCSI .\" 0m\" ;\n\nhide{ CSI 10u. }hide\n( ==================== ANSI Escape Codes ===================== )\n\n( ==================== Unit test framework =================== )\n\n256 string estring ( string to test )\n0 variable #estring ( actual string length )\n0 variable start ( starting depth )\n0 variable result ( result depth )\n0 variable check ( only check depth if -> is called )\n0 variable dictionary ( dictionary pointer on entering { )\n0 variable previous ( PWD register on entering { )\n\n: T ; ( hack until T{ can process words )\n\n: -> ( -- : save depth in variable )\n\t1 check ! depth result ! ;\n\n: test estring drop #estring @ ;\n\n: fail ( -- : invalidate the forth interpreter and exit )\n\tinvalidate bye ;\n\n: neutral ( -- : neutral color )\n\t;\n\n: bad ( -- : bad color )\n\tdark red foreground color ;\n\n: good ( -- : good color )\n\tdark green foreground color ;\n\n: die bad test type reset-color cr fail ;\n\n: evaluate? ( bool -- : test if evaluation has failed )\n\tif .\" evaluation failed\" cr fail then ;\n\n: failed bad .\" failed\" reset-color cr ;\n\n: adjust ( x -- x : adjust a depth to take into account starting depth )\n\tstart @ - ;\n\n: no-check? ( -- bool : if true we need to check the depth )\n\tcheck @ 0= ;\n\n: depth? ( -- : check if depth is correct )\n\tno-check? if exit then\n\tdepth adjust ( get depth and adjust for starting depth )\n\tresult @ adjust 2* = ( get results depth, same adjustment, should be\n\t half size of the depth )\n\tif exit then ( pass )\n\tfailed\n\t.\" Unequal depths:\" cr\n\t.\" depth: \" depth . cr\n\t.\" result: \" result @ . cr\n\tdie ;\n\n: equal? ( -- : determine if results equals expected )\n\tno-check? if exit then\n\tresult @ adjust equal\n\tif exit then\n\tfailed\n\t.\" Result is not equal to expected values. \" cr\n\t.\" Stack: \" cr .s cr\n\tdie ;\n\n: display ( c-addr u -- : print out testing message in estring )\n\tverbose if neutral type else 2drop then ;\n\n: pass ( -- : print out passing message )\n\tverbose if good .\" ok \" cr reset-color then ;\n\n: save ( -- : save current dictionary )\n\tpwd @ previous !\n\there dictionary ! ;\n\n: restore ( -- : restore dictionary )\n\tprevious @ pwd !\n\tdictionary @ h ! ;\n\n: T{ ( -- : perform a unit test )\n\tdepth start ! ( save start of stack depth )\n\t0 result ! ( reset result variable )\n\t0 check ! ( reset check variable )\n\testring 0 fill ( zero input string )\n\tsave ( save dictionary state )\n\tkey drop ( drop next character, which is a space )\n\testring [char] } accepter #estring ! ( read in string to test )\n\ttest display ( print which string we are testing )\n\ttest evaluate ( perform test )\n\tevaluate? ( evaluate successfully? )\n\tdepth? ( correct depth )\n\tequal? ( results equal to expected values? )\n\tpass ( print pass message )\n\trestore ( restore dictionary to previous state )\n\tno-check? if exit then\n\tresult @ adjust 2* ndrop ( remove items on stack generated by test )\n\t; \n\nT{ }T \nT{ -> }T\nT{ 1 -> 1 }T\nT{ 1 2 -> 1 2 }T\nT{ : c 1 2 ; c -> 1 2 }T\n\n( @bug ';' smudges the previous word, but :noname does\nnot. )\nT{ :noname 2 ; :noname 3 + ; compose execute -> 5 }T\n\nhide{\n\tpass test display\n\tadjust start save restore dictionary previous\n\tevaluate? equal? depth? estring #estring result\n\tcheck no-check? die neutral bad good failed\n}hide\n\n( ==================== Unit test framework =================== )\n\n\n( ==================== Pseudo Random Numbers ================= )\n( This section implements a Pseudo Random Number generator, it\nuses the xor-shift algorithm to do so.\nSee:\nhttps:\/\/en.wikipedia.org\/wiki\/Xorshift\nhttp:\/\/excamera.com\/sphinx\/article-xorshift.html\nhttp:\/\/xoroshiro.di.unimi.it\/\nhttp:\/\/www.arklyffe.com\/main\/2010\/08\/29\/xorshift-pseudorandom-number-generator\/\n\nThe constants used have been collected from various places\non the web and are specific to the size of a cell. )\n\nsize 2 = [if] 13 constant a 9 constant b 7 constant c [then]\nsize 4 = [if] 13 constant a 17 constant b 5 constant c [then]\nsize 8 = [if] 12 constant a 25 constant b 27 constant c [then]\n\n7 variable seed ( must not be zero )\n\n: seed! ( x -- : set the value of the PRNG seed )\n\tdup 0= if drop 7 ( zero not allowed ) then seed ! ;\n\n: random ( -- x : assumes word size is 32 bit )\n\tseed @\n\tdup a lshift xor\n\tdup b rshift xor\n\tdup c lshift xor\n\tdup seed! ;\n\nhide{ a b c seed }hide\n\n( ==================== Random Numbers ======================== )\n\n( ==================== Prime Numbers ========================= )\n( From original \"third\" code from the IOCCC at\nhttp:\/\/www.ioccc.org\/1992\/buzzard.2.design, the module works\nout and prints prime numbers. )\n\n: prime? ( u -- u | 0 : return number if it is prime, zero otherwise )\n\tdup 1 = if 1- exit then\n\tdup 2 = if exit then\n\tdup 2\/ 2 ( loop from 2 to n\/2 )\n\tdo\n\t\tdup ( value to check if prime )\n\t\ti mod ( mod by divisor )\n\t\tnot if\n\t\t\tdrop 0 leave\n\t\tthen\n\tloop ;\n\n0 variable counter\n\n: primes ( x1 x2 -- : print the primes from x2 to x1 )\n\t0 counter !\n\t\" The primes from \" dup . \" to \" over . \" are: \"\n\tcr\n\tcolumn.reset\n\tdo\n\t\ti prime?\n\t\tif\n\t\t\ti . counter @ column counter 1+!\n\t\tthen\n\tloop\n\tcr\n\t\" There are \" counter @ . \" primes.\"\n\tcr ;\n\nhide{ counter }hide\n( ==================== Prime Numbers ========================= )\n\n( ==================== Debugging info ======================== )\n( This section implements various debugging utilities that the\nprogrammer can use to inspect the environment and debug Forth\nwords. )\n\n( String handling should really be done with PARSE, and CMOVE )\n: sh ( cnl -- ior : execute a line as a system command )\n\tnl word count system ;\n\nhide{ .s }hide\n: .s ( -- : print out the stack for debugging )\n\t[char] < emit depth (.) drop [char] > emit space\n\tdepth if\n\t\tdepth 0 do i column tab depth i 1+ - pick . loop\n\tthen\n\tcr ;\n\n1 variable hide-words ( do we want to hide hidden words or not )\n\n: name ( PWD -- c-addr : given a pointer to the PWD field of a word get a pointer to the name of the word )\n\tdup 1+ @ 256\/ word-mask and lsb - chars> ;\n\n( This function prints out all of the defined words, excluding\nhidden words. An understanding of the layout of a Forth word\nhelps here. The dictionary contains a linked list of words,\neach forth word has a pointer to the previous word until the\nfirst word. The layout of a Forth word looks like this:\n\nNAME: Forth Word - A variable length ASCII NUL terminated\n string.\nPWD: Previous Word Pointer, points to the previous\n word.\nCODE: Flags, code word and offset from previous word\n pointer to start of Forth word string.\nDATA: The body of the forth word definition, not interested\n in this.\n\nThere is a register which stores the latest defined word which\ncan be accessed with the code \"pwd @\". In order to print out\na word we need to access a words CODE field, the offset to\nthe NAME is stored here in bits 8 to 14 and the offset is\ncalculated from the PWD field.\n\n\"print\" expects a character address, so we need to multiply\nany calculated address by the word size in bytes. )\n\n: words.immediate ( bool -- : emit or mark a word being printed as being immediate )\n\tnot if dark red foreground color then ;\n\n: words.defined ( bool -- : emit or mark a word being printed as being a built in word )\n\tnot if bright green background color then ;\n\n: words.hidden ( bool -- : emit or mark a word being printed as being a hidden word )\n\tif dark magenta foreground color then ;\n\n: words ( -- : print out all defined an visible words )\n\tlatest\n\tspace\n\tbegin\n\t\tdup\n\t\thidden? hide-words @ and\n\t\tnot if\n\t\t\thidden? words.hidden\n\t\t\tcompiling? words.immediate\n\t\t\tdup defined-word? words.defined\n\t\t\tname\n\t\t\tprint space\n\t\t\treset-color\n\t\telse\n\t\t\tdrop\n\t\tthen\n\t\t@ ( Get pointer to previous word )\n\t\tdup dictionary-start u< ( stop if pwd no longer points to a word )\n\tuntil\n\tdrop cr ;\n\n( Simpler version of words\n: words\n\tpwd @\n\tbegin\n\t\tdup name print space @ dup dictionary-start u<\n\tuntil drop cr ; )\n\nhide{ words.immediate words.defined words.hidden hidden? hidden-bit }hide\n\n: TrueFalse ( bool -- : print true or false )\n\tif \" true\" else \" false\" then ;\n\n: registers ( -- : print out important registers and information about the virtual machine )\n\t\" return stack pointer: \" r@ . cr\n\t\" dictionary pointer \" here . cr\n\t\" previous word: \" pwd ? cr\n\t\" state: \" state ? cr\n\t\" base: \" base ? cr\n\t\" depth: \" depth . cr\n\t\" cell size (in bytes): \" size . cr\n\t\" last cell address: \" max-core . cr\n\t\" unused cells: \" unused . cr\n\t\" invalid: \" `invalid @ TrueFalse cr\n\t\" size of variable stack: \" `stack-size ? cr\n\t\" size of return stack: \" `stack-size ? cr\n\t\" start of variable stack: \" max-core `stack-size @ 2* - . cr\n\t\" start of return stack: \" max-core `stack-size @ - . cr\n\t\" current input source: \" source-id -1 = if \" string\" else \" file\" then cr\n\t\" tracing on: \" `debug @ TrueFalse cr\n\t\" starting word: \" `instruction ? cr\n\t\" real start address: \" `start-address ? cr\n\t\" error handling: \" `error-handler ? cr\n\t\" throw handler: \" `handler ? cr\n\t\" signal recieved: \" `signal ? cr ;\n\t\n( `sin `sidx `slen `fout\n `stdout `stderr `argc `argv )\n\n\n: y\/n? ( -- bool : ask a yes or no question )\n\tkey drop\n\t\" y\/n? \"\n\tbegin\n\t\tkey\n\t\tdup\n\t\t[char] y = if true exit then\n\t\t[char] n = if false exit then\n\t\t\" y\/n? \"\n\tagain ;\n\n: step\n\t( step through a word: this word could be augmented\n\twith commands such as \"dump\", \"halt\", and optional\n\t\".s\" and \"registers\" )\n\tregisters\n\t\" .s: \" .s cr\n\t\" -- press any key to continue -- \"\n\tkey drop ;\n\n: more ( -- : wait for more input )\n\t\" -- press any key to continue -- \" key drop cr page ;\n\n: debug-help ( -- : print out the help for the debug command )\n \" debug mode commands\n\th - print help\n\tq - exit interpreter word\n\tr - print registers\n\ts - print stack\n\tR - print return stack\n\tc - continue on with execution\n\" ;\n\ndoer debug-prompt\n: prompt-default\n\t.\" debug> \" ;\n\nmake debug-prompt prompt-default\n\n: debug ( -- : enter interactive debug prompt )\n\tcr\n\t\" Entered Debug Prompt. Type 'h' for help. \" cr\n\tbegin\n\t\tkey\n\t\tcase\n\t\t\tnl of debug-prompt endof\n\t\t\t[char] h of debug-help endof\n\t\t\t[char] q of bye endof\n\t\t\t[char] r of registers endof\n\t\t\t[char] s of .s endof\n\t\t\t[char] R of r.s endof\n\t\t\t[char] c of exit endof\n\t\t\t( @todo add throw here )\n\t\tendcase\n\tagain ;\nhide debug-prompt\n\n: code>pwd ( CODE -- PWD\/0 : calculate PWD from code address )\n\tdup dictionary-start here within not if drop 0 exit then\n\t1 cells - ;\n\n: word-printer ( CODE -- : print out a words name given its code field )\n\tdup 1 cells - @ -1 = if . \" noname\" exit then ( nonames are marked by a -1 before its code field )\n\tdup code>pwd ?dup-if .d name print else drop \" data\" then\n\t drop ;\n\nhide{ code>pwd }hide\n\n( these words push the execution tokens for various special\ncases for decompilation )\n: get-branch [ find branch ] literal ;\n: get-?branch [ find ?branch ] literal ;\n: get-original-exit [ find _exit ] literal ;\n: get-quote [ find ' ] literal ;\n\n( @todo replace 2- nos1+ nos1+ with appropriate word, like\nthe string word that increments a string by an amount, but\nthat operates on CELLS )\n: branch-increment ( addr branch -- increment : calculate decompile increment for \"branch\" )\n\t1+ dup negative?\n\tif\n\t\tover cr . [char] : emit space . cr 2\n\telse\n\t\t2dup 2- nos1+ nos1+ dump\n\tthen ;\n\n( these words take a code field to a primitive they implement,\ndecompile it and any data belonging to that operation, and push\na number to increment the decompilers code stream pointer by )\n\n: decompile-literal ( code -- increment )\n\t1+ ? \" literal\" 2 ;\n\n: decompile-branch ( code -- increment )\n\tdark red foreground color\n\t1+ ? \" branch \" dup 1+ @ branch-increment ;\n\n: decompile-quote ( code -- increment )\n\tdark green foreground color\n\tdup\n\t[char] ' emit 1+ @ word-printer 2 reset-color ;\n\n: decompile-?branch ( code -- increment )\n\t1+ ? \" ?branch\" 2 ;\n\n: decompile-exit ( code -- 0 )\n\t\" _exit\" cr \" End of word: \" . 0 ;\n\n( The decompile word expects a pointer to the code field of\na word, it decompiles a words code field, it needs a lot of\nwork however. There are several complications to implementing\nthis decompile function.\n\n\t'\t The next cell should be pushed\n\n\t:noname This has a marker before its code field of\n\t -1 which cannot occur normally, this is\n\t handled in word-printer\n\n\tbranch\t branches are used to skip over data, but\n\t also for some branch constructs, any data\n\t in between can only be printed out\n\t generally speaking\n\n\texit\t There are two definitions of exit, the one\n\t used in ';' and the one everything else uses,\n\t this is used to determine the actual end\n\t of the word\n\n\tliterals Literals can be distinguished by their\n\t low value, which cannot possibly be a word\n\t with a name, the next field is the\n\t actual literal\n\nOf special difficult is processing IF, THEN and ELSE\nstatements, this will require keeping track of '?branch'.\n\nAlso of note, a number greater than \"here\" must be data )\n\n: decompile ( code-pointer -- code-pointer increment|0 : )\n\t.d [char] : emit space dup @\n\tcase\n\t\tdolit of dup decompile-literal cr endof\n\t\tget-branch of dup decompile-branch endof\n\t\tget-quote of dup decompile-quote cr endof\n\t\tget-?branch of dup decompile-?branch cr endof\n\t\tget-original-exit of dup decompile-exit endof\n\t\tdup word-printer 1 swap cr\n\tendcase reset-color ;\n\n: decompiler ( code-field-ptr -- : decompile a word in its entirety )\n\tbegin decompile over + tuck = until drop ;\n\nhide{\n\tword-printer get-branch get-?branch get-original-exit\n\tget-quote branch-increment decompile-literal\n\tdecompile-branch decompile-?branch decompile-quote\n\tdecompile-exit\n}hide\n\n( these words expect a pointer to the PWD field of a word )\n: see.name \" name: \" name print cr ;\n: see.start \" word start: \" name chars . cr ;\n: see.previous \" previous word: \" @ . cr ;\n: see.immediate \" immediate: \" compiling? nip not TrueFalse cr ;\n: see.instruction \" instruction: \" xt-instruction . cr ;\n: see.defined \" defined: \" defined-word? TrueFalse cr ;\n\n: see.header ( PWD -- is-immediate-word? )\n\tdup see.name\n\tdup see.start\n\tdup see.previous\n\tdup see.immediate\n\tdup see.instruction ( @todo look up instruction name )\n\tsee.defined ;\n\n( @todo This does not work for all words, so needs fixing.\n Specifically:\n\n\t2variable\n\t2constant\n\ttable\n\tconstant\n\tvariable\n\tarray\nWhich are all complex CREATE words\n\nA good way to test decompilation is with the following\nUnix pipe:\n\n\t.\/forth -f forth.fth -e words\n\t\t| sed 's\/ \/ see \/g'\n\t\t| .\/forth -t forth.fth &> decompiled.log\n)\n\n( @todo refactor into word that takes a PWD pointer and one that attempts to parse\/find name )\n: see ( c\" xxx\" -- : decompile a word )\n\tfind\n\tdup 0= if -32 throw then\n\tcell- ( move to PWD field )\n\tdup see.header\n\tdup defined-word?\n\tif ( decompile if a compiled word )\n\t\t2 cells + ( move to code field )\n\t\t\" code field:\" cr\n\t\tdecompiler\n\telse ( the instruction describes the word if it is not a compiled word )\n\t\tdup 1 cells + @ instruction-mask and doconst = if ( special case for constants )\n\t\t\t\" constant: \" 2 cells + @ .\n\t\telse\n\t\t\tdrop\n\t\tthen\n\tthen cr ;\n\n( @todo This has a bug, if any data within a word happens\nto match the address of _exit word.end calculates the wrong\naddress, this needs to mirror the DECOMPILE word )\n: word.end ( addr -- addr : find the end of a word )\n\tbegin\n\t\tdup\n\t\t@ [ find _exit ] literal = if exit then\n\t\tcell+\n\tagain ;\n\n: (inline) ( xt -- : inline an word from its execution token )\n\tdup cell- defined-word? if\n\t\tcell+\n\t\tdup word.end over - here -rot dup allot move\n\telse\n\t\t,\n\tthen ;\n\n: ;inline ( -- : terminate :inline )\n\timmediate -22 throw ;\n\n: :inline immediate\n\t?comp\n\tbegin\n\t\tfind found?\n\t\tdup [ find ;inline ] literal = if\n\t\t\tdrop exit ( terminate :inline )\n\t\tthen\n\t\t(inline)\n\tagain ;\n\nhide{\n\tsee.header see.name see.start see.previous see.immediate\n\tsee.instruction defined-word? see.defined _exit found?\n\t(inline) word.end\n}hide\n\n( These help messages could be moved to blocks, the blocks\ncould then be loaded from disk and printed instead of defining\nthe help here, this would allow much larger help )\n\n: help ( -- : print out a short help message )\n\tpage\n\tkey drop\n\" Welcome to Forth, an imperative stack based language. It is\nboth a low level and a high level language, with a very small\nmemory footprint. Most of Forth is defined as a combination\nof various primitives.\n\nA short description of the available function (or Forth words)\nfollows, words marked (1) are immediate and cannot be used in\ncommand mode, words marked with (2) define new words. Words\nmarked with (3) have both command and compile functionality.\n\n\"\nmore \" Some of the built in words that accessible are:\n\n(1,2)\t: define a new word, switching to compile mode\n\timmediate make latest defined word immediate\n\tread read in a word, execute in command mode else compile\n\t@ ! fetch, store\n\tc@ c! character based fetch and store\n\t- + * \/ standard arithmetic operations,\n\tand or xor invert standard bitwise operations\n\tlshift rshift left and right bit shift\n\tu< u> < > = comparison predicates\n\texit exit from a word\n\temit print character from top of stack\n\tkey get a character from input\n\tr> >r pop a value from or to the return stack\n\tfind find a word in the dictionary and push the location\n\t' store the address of the following word on the stack\n\t, write the top of the stack to the dictionary\n\tswap swap first two values on the stack\n\tdup duplicate the top of the stack\n\tdrop pop and drop a value\n\tover copy the second stack value over the first\n\t. pop the top of the stack and print it\n\"\nmore \"\n\tprint print a NUL terminated string at a character address\n\tdepth get the current stack depth\n\tclock get the time since execution start in milliseconds\n\tevaluate evaluate a string\n\tsystem execute a system command\n\tclose-file close a file handle\n\topen-file open a file handle\n\tdelete-file delete a file off disk given a string\n\tread-file read in characters from a file\n\twrite-file write characters to a file\n\tfile-position get the file offset\n\treposition-file reposition the file pointer\n\tflush-file flush a file to disk\n\trename-file rename a file on disk\n \"\n\nmore \" All of the other words in the interpreter are built\nfrom these primitive words. A few examples:\n\n(1)\tif...else...then FORTH branching construct\n(1)\tbegin...until loop until top of stack is non zero\n(1)\tbegin...again infinite loop\n(1)\tdo...loop FORTH looping construct\n(2,3)\tcreate create a new word that pushes its location\n(1)\tdoes> declare a created words run time behaviour\n(1,2)\tvariable declare variable with initial value from top of stack\n(1,2)\tconstant declare a constant, taken from top of stack\n(1,2)\tarray declare an array with size taken from top of stack\n(1)\t; terminate a word definition and return to command mode\n\twords print out a list of all the defined words\n\thelp this help message\n\tdump print out memory contents starting at an address\n\tregisters print out the contents of the registers\n\tsee decompile a word, viewing what words compose it\n\t.s print out the contents of the stack\n\n\"\n\nmore \" Some more advanced words:\n\n\there push the dictionary pointer\n\th push the address of the dictionary pointer\n\tr push the return stack pointer\n\tallot allocate space in the dictionary\n(1)\t[ switch to command mode\n\t] switch to compile mode\n\t:: compile ':' into the dictionary\n\n\" more \"\nFor more information either consult the manual pages forth(1)\nand libforth(1) or consult the following sources:\n\n\thttps:\/\/github.com\/howerj\/libforth\n\thttp:\/\/work.anapnea.net\/html\/html\/projects.html\n\nAnd for a larger tutorial:\n\n\thttps:\/\/github.com\/howerj\/libforth\/blob\/master\/readme.md\n\nFor resources on Forth:\n\n\thttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\thttps:\/\/rwmj.wordpress.com\/2010\/08\/07\/jonesforth-git-repository\/\n\n -- end --\n\" cr\n;\n\n( ==================== Debugging info ======================== )\n\n( ==================== Files ================================= )\n( These words implement more of the standard file access words\nin terms of the ones provided by the virtual machine. These\nwords are not the most easy to use words, although the ones\ndefined here and the ones that are part of the interpreter are\nthe standard ones.\n\nSome thoughts:\n\nI believe extensions to this word set, once I have figured\nout the semantics, should be made to make them easier to use,\nones which automatically clean up after failure and call throw\nwould be more useful [and safer] when dealing with a single\ninput or output stream. The most common action after calling\none of the file access words is to call throw any way.\n\nFor example, a word like:\n\n\t: #write-file \\ c-addr u fileid -- fileid u\n\t\tdup >r\n\t\twrite-file dup if r> close-file throw throw then\n\t\tr> swap ;\n\nWould be easier to deal with, it preserves the file identifier\nand throws if there is any problem. It would be a bit more\ndifficult to use when there are two files open at a time.\n\n@todo implement the other file access methods in terms of the\nbuilt in ones.\n@todo read-line and write-line need their flag and ior setting\ncorrectly\n\n\tFILE-SIZE [ use file-positions ]\n\nAlso of note, Source ID needs extending.\n\nSee: [http:\/\/forth.sourceforge.net\/std\/dpans\/dpans11.htm] )\n\n: read-char ( c-addr fileid -- ior : read a char )\n\t1 swap read-file 0<> swap 1 <> or ;\n\n0 variable x\n\n: getchar ( fileid -- char ior )\n\tx chars> swap read-char x chars> c@ swap ;\n\n: write-char ( c-addr fileid -- ior : write a char )\n\t1 swap write-file 0<> swap 1 <> or ;\n\n: putchar ( char fileid -- ior )\n\tswap x chars> c! x chars> swap write-char ;\n\n\\ @todo This shouldn't affect the file position indicator.\n\\ @todo This doesn't return a sensible error indicator.\n\\ : file-size ( fileid -- ud ior )\n\\\t0 swap\n\\\tbegin dup getchar nip 0= while nos1+ repeat drop ;\n\n\nhide{ x }hide\n\n: rewind-file ( file-id -- : rewind a file to the beginning )\n\t0 reposition-file throw ;\n\n: read-line ( c-addr u1 fileid -- u2 flag ior : read in a line of text )\n\t-rot bounds\n\tdo\n\t\tdup i swap read-char drop\n\t\ti c@ nl = if drop i 0 0 leave then\n\tloop drop ;\n\n: write-line ( c-addr u fileid -- u2 flag ior : write a line of text )\n\t-rot bounds\n\tdo\n\t\tdup i swap write-char drop\n\t\ti c@ nl = if drop i 0 0 leave then\n\tloop ;\n\n: resize-file ( ud fileid -- ior : attempt to resize a file )\n\t( There is no portable way to truncate a file :C )\n\t2drop -1 ( -1 to indicate failure ) ;\n\n: create-file ( c-addr u fam -- fileid ior )\n\t>r 2dup w\/o open-file throw close-file throw\n\tr> open-file ;\n\n: include-file ( file-id -- : evaluate a file )\n\tdup >r 0 1 evaluator r> close-file throw throw ;\n\n: included ( c-addr u -- : attempt to open up a name file and evaluate it )\n\tr\/o open-file throw\n\tinclude-file ;\n\n: include ( c\" ccc\" -- : attempt to evaluate a named file )\n\t( @bug requires trailing space, should use parse-name )\n\tbl word count included ;\n\n: bin ( fam1 -- fam2 : modify a file access method to be binary not line oriented )\n\t( Do nothing, all file access methods are binary )\n\t;\n\n( ==================== Files ================================= )\n\n( ==================== Matcher =============================== )\n( The following section implements a very simple regular\nexpression engine, which expects an ASCIIZ Forth string. It\nis translated from C code and performs an identical function.\n\nThe regular expression language is as follows:\n\n\tc\tmatch a literal character\n\t.\tmatch any character\n\t*\tmatch any characters\n\nThe \"*\" operator performs the same function as \".*\" does in\nmost other regular expression engines. Most other regular\nexpression engines also do not anchor their selections to the\nbeginning and the end of the string to match, instead using\nthe operators '^' and '$' to do so, to emulate this behavior\n'*' can be added as either a suffix, or a prefix, or both,\nto the matching expression.\n\nAs an example \"*, World!\" matches both \"Hello, World!\" and\n\"Good bye, cruel World!\". \"Hello, ....\" matches \"Hello, Bill\"\nand \"Hello, Fred\" but not \"Hello, Tim\" as there are two few\ncharacters in the last string.\n\n@todo make a matcher that expects a Forth string, which do\nnot have to be NUL terminated )\n\n\\ Translated from http:\/\/c-faq.com\/lib\/regex.html\n\\ int match(char *pat, char *str)\n\\ {\n\\ \tswitch(*pat) {\n\\ \tcase '\\0': return !*str;\n\\ \tcase '*': return match(pat+1, str) || *str && match(pat, str+1);\n\\ \tcase '.': return *str && match(pat+1, str+1);\n\\ \tdefault: return *pat == *str && match(pat+1, str+1);\n\\ \t}\n\\ }\n\n: *pat ( regex -- regex char : grab next character of pattern )\n\tdup c@ ;\n\n: *str ( string regex -- string regex char : grab next character string to match )\n\tover c@ ;\n\n: pass ( c-addr1 c-addr2 -- bool : pass condition, characters matched )\n\t2drop 1 ;\n\n: reject ( c-addr1 c-addr2 -- bool : fail condition, character not matched )\n\t2drop 0 ;\n\n: *pat==*str ( c-addr1 c-addr2 -- c-addr1 c-addr2 bool )\n\t2dup c@ swap c@ = ;\n\n: ++ ( u1 u2 u3 u4 -- u1+u3 u2+u4 : not quite d+ [does no carry] )\n\tswap >r + swap r> + swap ;\n\ndefer matcher\n\n: advance ( string regex char -- bool : advance both regex and string )\n\tif 1 1 ++ matcher else reject then ;\n\n: advance-string ( string regex char -- bool : advance only the string )\n\tif 1 0 ++ matcher else reject then ;\n\n: advance-regex ( string regex -- bool : advance matching )\n\t2dup 0 1 ++ matcher if pass else *str advance-string then ;\n\n: match ( string regex -- bool : match a ASCIIZ pattern against an ASCIIZ string )\n\t( @todo Add limits and accept two Forth strings, making sure they are both\n\t ASCIIZ strings as well\n\t @warning This uses a non-standards compliant version of case! )\n\t*pat\n\tcase\n\t\t 0 of drop c@ not endof\n\t\t[char] * of advance-regex endof\n\t\t[char] . of *str advance endof\n\t\t\n\t\tdrop *pat==*str advance exit\n\n\tendcase ;\n\nmatcher is match\n\nhide{\n\t*str *pat *pat==*str pass reject advance\n\tadvance-string advance-regex matcher ++\n}hide\n\n( ==================== Matcher =============================== )\n\n\n( ==================== Cons Cells ============================ )\n( From http:\/\/sametwice.com\/cons.fs, this could be improved\nif the optional memory allocation words were added to\nthe interpreter. This provides a simple \"cons cell\" data\nstructure. There is currently no way to free allocated\ncells. I do not think this is particularly useful, but it is\ninteresting. )\n\n: car! ( value cons-addr -- : store a value in the car cell of a cons cell )\n\t! ;\n\n: cdr! ( value cons-addr -- : store a value in the cdr cell of a cons cell )\n\tcell+ ! ;\n\n: car@ ( cons-addr -- car-val : retrieve car value from cons cell )\n\t@ ;\n\n: cdr@ ( cons-addr -- cdr-val : retrieve cdr value from cons cell )\n\tcell+ @ ;\n\n: cons ( car-val cdr-val -- cons-addr : allocate a new cons cell )\n\tswap here >r , , r> ;\n\n: cons0 0 0 cons ;\n\n( ==================== Cons Cells ============================ )\n\n( ==================== License =============================== )\n( The license has been chosen specifically to make this library\nand any associated programs easy to integrate into arbitrary\nproducts without any hassle. For the main libforth program\nthe LGPL license would have been also suitable [although it\nis MIT licensed as well], but to keep confusion down the same\nlicense, the MIT license, is used in both the Forth code and\nC code. This has not been done for any ideological reasons,\nand I am not that bothered about licenses. )\n\n: license ( -- : print out license information )\n\"\nThe MIT License (MIT)\n\nCopyright (c) 2016, 2017 Richard James Howe\n\nPermission is hereby granted, free of charge, to any person\nobtaining a copy of this software and associated documentation\nfiles (the 'Software'), to deal in the Software without\nrestriction, including without limitation the rights to use,\ncopy, modify, merge, publish, distribute, sublicense, and\/or\nsell copies of the Software, and to permit persons to whom\nthe Software is furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY\nKIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\nWARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE\nAND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\nHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE\nOR OTHER DEALINGS IN THE SOFTWARE.\n\n\"\n;\n\n( ==================== License =============================== )\n\n( ==================== Core utilities ======================== )\n( Read the header of a core file and process it, printing the\nresults out )\n\n8 constant header-size ( size of Forth core file header )\n8 constant size-field-size ( the size in bytes of the size field in the core file )\n0 variable core-file ( core fileid we are reading in )\n0 variable core-cell-size ( cell size of Forth core )\n0 variable core-version ( version of core file )\n0 variable core-endianess ( endianess of core we are reading in )\n\n( save space to read in header )\ncreate header header-size chars allot\n: cheader ( -- c-addr : header char address )\n\theader chars> ;\ncreate size-field size-field-size chars allot\n: csize-field ( -- c-addr : address of place size field is stored in )\n\tsize-field chars> ;\n\n0\nenum header-magic0 ( magic number 0 : FF )\nenum header-magic1 ( magic number 1 : '4' )\nenum header-magic2 ( magic number 2 : 'T' )\nenum header-magic3 ( magic number 3 : 'H' )\nenum header-cell-size ( size of a forth cell, either 2, 4 or 8 bytes )\nenum header-version ( version of the forth core )\nenum header-endianess ( endianess of the core )\nenum header-log2size ( binary logarithm of the core size )\n\n: cleanup ( -- : cleanup before abort )\n\tcore-file @ ?dup 0<> if close-file drop then ;\n\n: invalid-header ( bool -- : abort if header is invalid )\n\t<> if cleanup abort\" invalid header\" then ;\n\n: save-core-cell-size ( char -- : save the core file cell size, checking if it is valid )\n\tcore-cell-size !\n\t\" cell size:\" tab\n\tcore-cell-size @ 2 = if 2 . cr exit then\n\tcore-cell-size @ 4 = if 4 . cr exit then\n\tcore-cell-size @ 8 = if 8 . cr exit then\n\tcleanup core-cell-size @ . abort\" : invalid cell size\" ;\n\n: check-version-compatibility ( char -- : checks the version compatibility of the core file )\n\tcore-version !\n\tcore-version @ version = if \" version: \" version . cr exit then\n\tcleanup core-version @ . abort\" : unknown version number\" ;\n\n: save-endianess ( char -- : save the endianess, checking if it is valid )\n\tcore-endianess !\n\t\" endianess:\" tab\n\tcore-endianess @ 0 = if \" big\" cr exit then\n\tcore-endianess @ 1 = if \" little\" cr exit then\n\tcleanup core-endianess @ . abort\" invalid endianess\" then ;\n\n: read-or-abort ( c-addr size fileid -- : )\n\tover >r read-file\n\t 0<> if cleanup abort\" file read failed\" then\n\tr> <> if cleanup abort\" header too small\" then ;\n\n: header? ( -- : print out header information )\n\tcheader header-size core-file @ read-or-abort\n\t( \" raw header:\" header 2 dump )\n\tcheader header-magic0 + c@ 255 invalid-header\n\tcheader header-magic1 + c@ [char] 4 invalid-header\n\tcheader header-magic2 + c@ [char] T invalid-header\n\tcheader header-magic3 + c@ [char] H invalid-header\n\tcheader header-cell-size + c@ save-core-cell-size\n\tcheader header-version + c@ check-version-compatibility\n\tcheader header-endianess + c@ save-endianess\n\t\" valid header\" cr ;\n\n: size? ( -- : print out core file size )\n\t\" size: \" cheader header-log2size + c@ 1 swap lshift . cr ;\n\n: core ( c-addr u -- : analyze a Forth core file from disk given its file name )\n\t2dup \" core file:\" tab type cr\n\tr\/o open-file throw core-file !\n\theader?\n\tsize?\n\tcore-file @ close-file drop ;\n\n( s\" forth.core\" core )\n\nhide{\nheader-size header?\nheader-magic0 header-magic1 header-magic2 header-magic3\nheader-version header-cell-size header-endianess header-log2size\nheader\ncore-file save-core-cell-size check-version-compatibility\ncore-cell-size cheader\ncore-endianess core-version save-endianess invalid-header\ncleanup size-field csize-field size-field-size\nread-or-abort size?\n}hide\n\n( ==================== Core utilities ======================== )\n\n( ==================== RLE =================================== )\n\n( These set of words implement Run Length Compression, which\ncan be used for saving space when compressing the core files\ngenerated by Forth programs, which contain mostly runs of\nNUL characters.\n\nThe format of the encoded data is quite simple, there is a\ncommand byte followed by data. The command byte encodes only\ntwo commands; encode a run of literal data and repeat the\nnext character.\n\nIf the command byte is greater than X the command is a run\nof characters, X is then subtracted from the command byte\nand this is the number of characters that is to be copied\nverbatim when decompressing.\n\nIf the command byte is less than or equal to X then this\nnumber, plus one, is used to repeat the next data byte in\nthe input stream.\n\nX is 128 for this application, but could be adjusted for\nbetter compression depending on what the data looks like.\n\nExample:\n\n\t2 'a' 130 'b' 'c' 3 'd'\n\nBecomes:\n\n\taabcddd\n\nExample usage:\n\n\t: extract\n\t\tc\" forth.core\" w\/o open-file throw c\"\n\t\tforth.core.rle\" r\/o open-file throw\n\t\tdecompress ;\n\textract\n\n@note file redirection could be used for the input as well\n@todo compression, and reading\/writing to strings )\n\n: cpad pad chars> ;\n\n0 variable out\n128 constant run-length\n\n: next.char ( file-id -- char : read in a single character )\n\t>r cpad r> read-char throw cpad c@ ;\n\n: repeated ( count file-id -- : repeat a character count times )\n\tnext.char swap 0 do dup emit loop drop ;\n\n: literals ( count file-id -- : extract a literal run )\n\t>r cpad swap r> read-file throw cpad swap type ;\n\n: command ( file-id -- : process an RLE command )\n\tdup\n\t>r next.char\n\tdup run-length u>\n\tif\n\t\trun-length - r> literals\n\telse\n\t\t1+ r> repeated\n\tthen ;\n\n: redirect ( file-id-out -- : save current output pointer, redirect to output )\n\t`fout @ out ! `fout ! ;\n\n: restore ( -- : restore previous output pointer )\n\tout @ `fout ! ;\n\n: decompress ( file-id-out file-id-in -- : decompress an RLE encoded file )\n\tswap\n\tredirect\n\tbegin dup ['] command catch until ( process commands until input exhausted )\n\t2drop ( drop twice because catch will restore stack before COMMAND )\n\trestore ; ( restore input stream )\n\nhide{ literals repeated next.char out run-length command }hide\n\n( ==================== RLE =================================== )\n\n( ==================== Generate C Core file ================== )\n( The word core2c reads in a core file and turns it into a\nC file which can then be compiled into the forth interpreter\nin a bootstrapping like process. The process is described\nelsewhere as well, but it goes like this.\n\n1. We want to generate an executable program that contains the\ncore Forth interpreter, written in C, and the contents of this\nfile in compiled form. However, in order to compile this code\nwe need a Forth interpreter to do so. This is the problem.\n2. To solve the problem we first make a program which is capable\nof compiling \"forth.fth\".\n3. We then generate a core file from this.\n4. We then convert the generated core file to C code.\n5. We recompile the original program to includes this core\nfile, and which runs the core file at start up.\n6. We run the new executable.\n\nUsage:\n c\" forth.core\" c\" core.gen.c\" core2c )\n\n0 variable count\n\n: wbyte ( u char -- : write a byte )\n\t(.) drop\n\t[char] , emit\n\t16 mod 0= if cr then ;\n\n: advance ( char -- : advance counter and print byte )\n\tcount 1+! count @ swap wbyte ;\n\n: hexify ( fileid -- fileid : turn core file into C numbers in array )\n\t0 count !\n\tbegin dup getchar 0= while advance repeat drop ;\n\n: quote ( -- : emit a quote character )\n\t[char] \" emit ;\n\n: core2c ( c-addr u c-addr u -- ior : generate a C file from a core file )\n\tw\/o open-file throw >r\n\tr\/o open-file ?dup-if r> close-file throw throw then\n\tr> redirect\n\t\" #include \" quote \" libforth.h\" quote cr\n\t\" unsigned char forth_core_data[] = {\" cr\n\thexify\n\t\" };\" cr\n\t\" forth_cell_t forth_core_size = \" count @ . \" ;\" cr cr\n\tclose-file\n\t`fout @ close-file\n\trestore or ;\n\nhide{ wbyte hexify count quote advance }hide\n\n( ==================== Generate C Core file ================== )\n\n( ==================== Word Count Program ==================== )\n\n( @todo implement FILE-SIZE in terms of this program )\n( @todo extend wc to include line count and word count )\n: wc ( c-addr u -- u : count the bytes in a file )\n\tr\/o open-file throw\n\t0 swap\n\tbegin\n\t\tdup getchar nip 0=\n\twhile\n\t\tnos1+\n\trepeat\n\tclose-file throw ;\n\n( ==================== Word Count Program ==================== )\n\n( ==================== Save Core file ======================== )\n( The following functionality allows the user to save the\ncore file from within the running interpreter. The Forth\ncore files have a very simple format which means the words\nfor doing this do not have to be too long, a header has to\nemitted with a few calculated values and then the contents\nof the Forths memory after this )\n\n( This write the header out to the current output device, this\nwill be redirected to a file )\n: header ( -- : write the header out )\n\t0xff emit ( magic 0 )\n\t[char] 4 emit ( magic 1 )\n\t[char] T emit ( magic 2 )\n\t[char] H emit ( magic 3 )\n\tsize emit ( cell size in bytes )\n\tversion emit ( core version )\n\tendian not emit ( endianess )\n\tmax-core log2 emit ; ( size field )\n\n: data ( -- : write the data out )\n\t0 max-core chars> `fout @ write-file throw drop ;\n\n: encore ( -- : write the core file out )\n\theader\n\tdata ;\n\n: save-core ( c-addr u -- : save core file or throw error )\n\tw\/o open-file throw dup\n\tredirect\n\t\t['] encore catch swap close-file throw\n\trestore ;\n\n( The following code illustrates an example of setting up a\nForth core file to execute a word when the core file is loaded.\nIn the example the word \"hello-world\" will be executed,\nwhich will also quit the interpreter:\n\nThis only works for immediate words for now, we define\nthe word we wish to be executed when the forth core\nis loaded:\n\n\t: hello-world immediate\n\t\t\" Hello, World!\" cr bye ;\n\nThe following sets the starting word to our newly\ndefined word:\n\n\tfind hello-world cfa start!\n\n\t\\ Now we can save the core file out:\n\ts\" forth.core\" save-core\n\nThis can be used, in conjunction with aspects of the build\nsystem, to produce a standalone executable that will run only\na single Forth word. This is known as creating a 'turn-key'\napplication. )\n\nhide{ redirect restore data encore header }hide\n\n( ==================== Save Core file ======================== )\n\n( ==================== Hex dump ============================== )\n\n( @todo hexdump can read in too many characters and it does not\nprint out the correct address\n@todo utilities for easy redirecting of file input\/output )\n\\ : input >r cpad 128 r> read-file ; ( file-id -- u 0 | error )\n\\ : clean cpad 128 0 fill ; ( -- )\n\\ : cdump cpad chars swap aligned chars dump ; ( u -- )\n\\ : hexdump ( file-id -- : [hex]dump a file to the screen )\n\\ \tdup\n\\ \tclean\n\\ \tinput if 2drop exit then\n\\ \t?dup-if cdump else drop exit then\n\\ \ttail ;\n\\\n\\ 0 variable u\n\\ 0 variable u1\n\\ 0 variable cdigs\n\\ 0 variable digs\n\\\n\\ : address ( -- bool : is it time to print out a new line and an address )\n\\ \tu @ u1 @ - 4 size * mod 0= ;\n\\\n\\ : (dump) ( u c-addr u : u -- )\n\\ \trot dup u ! u1 !\n\\ \tcdigits cdigs !\n\\ \tdigits digs !\n\\ \tbounds\n\\ \tdo\n\\ \t\taddress if cr u @ digs @ u.rz [char] : emit space then\n\\ \t\ti c@ cdigs @ u.rz\n\\ \t\t\n\\ \t\ti 1+ size mod 0= if space then\n\\ \t\tu 1+!\n\\ \tloop\n\\ \tu @\n\\ \t;\n\\\n\\ : hexdump-file ( c-addr u )\n\\ \tr\/o open-file throw\n\\ \t\n\\ \t;\n\\\n\\ hide{ u u1 cdigs digs address }hide\n\\ hex\n\\ 999 0 197 (dump)\n\\ decimal\n\\\n\\ hide{ cpad clean cdump input }hide\n\\\n( ==================== Hex dump ============================== )\n\n( ==================== Date ================================== )\n( This word set implements a words for date processing, so\nyou can print out nicely formatted date strings. It implements\nthe standard Forth word time&date and two words which interact\nwith the libforth DATE instruction, which pushes the current\ntime information onto the stack.\n\nRather annoyingly months are start from 1 but weekdays from\n0. )\n\n: >month ( month -- c-addr u : convert month to month string )\n\tcase\n\t\t 1 of c\" Jan \" endof\n\t\t 2 of c\" Feb \" endof\n\t\t 3 of c\" Mar \" endof\n\t\t 4 of c\" Apr \" endof\n\t\t 5 of c\" May \" endof\n\t\t 6 of c\" Jun \" endof\n\t\t 7 of c\" Jul \" endof\n\t\t 8 of c\" Aug \" endof\n\t\t 9 of c\" Sep \" endof\n\t\t10 of c\" Oct \" endof\n\t\t11 of c\" Nov \" endof\n\t\t12 of c\" Dec \" endof\n\t\t-11 throw\n\tendcase ;\n\n: .day ( day -- c-addr u : add ordinal to day )\n\t10 mod\n\tcase\n\t\t1 of c\" st \" endof\n\t\t2 of c\" nd \" endof\n\t\t3 of c\" rd \" endof\n\t\tdrop c\" th \" exit\n\tendcase ;\n\n: >day ( day -- c-addr u: add ordinal to day of month )\n\tdup 1 10 within if .day exit then\n\tdup 10 20 within if drop c\" th\" exit then\n\t.day ;\n\n: >weekday ( weekday -- c-addr u : print the weekday )\n\tcase\n\t\t0 of c\" Sun \" endof\n\t\t1 of c\" Mon \" endof\n\t\t2 of c\" Tue \" endof\n\t\t3 of c\" Wed \" endof\n\t\t4 of c\" Thu \" endof\n\t\t5 of c\" Fri \" endof\n\t\t6 of c\" Sat \" endof\n\t\t-11 throw\n\tendcase ;\n\n: >gmt ( bool -- GMT or DST? )\n\tif c\" DST \" else c\" GMT \" then ;\n\n: colon ( -- char : push a colon character )\n\t[char] : ;\n\n: 0? ( n -- : hold a space if number is less than base )\n\t(base) u< if [char] 0 hold then ;\n\n( .NB You can format the date in hex if you want! )\n: date-string ( date -- c-addr u : format a date string in transient memory )\n\t9 reverse ( reverse the date string )\n\t<#\n\t\tdup #s drop 0? ( seconds )\n\t\tcolon hold\n\t\tdup #s drop 0? ( minute )\n\t\tcolon hold\n\t\tdup #s drop 0? ( hour )\n\t\tdup >day holds\n\t\t#s drop ( day )\n\t\t>month holds\n\t\tbl hold\n\t\t#s drop ( year )\n\t\t>weekday holds\n\t\tdrop ( no need for days of year )\n\t\t>gmt holds\n\t\t0\n\t#> ;\n\n: .date ( date -- : print the date )\n\tdate-string type ;\n\n: time&date ( -- second minute hour day month year )\n\tdate\n\t3drop ;\n\nhide{ >weekday .day >day >month colon >gmt 0? }hide\n\n( ==================== Date ================================== )\n\n\n( ==================== CRC =================================== )\n\n( @todo implement all common CRC algorithms, but only if the\nword size allows it [ie. 32 bit CRCs on a 32 or 64 bit machine,\n64 bit CRCs on a 64 bit machine] )\n\n( Make a word to limit arithmetic to a 16-bit value )\nsize 2 = [if]\n\t: limit immediate ; ( do nothing, no need to limit )\n[else]\n\t: limit 0xffff and ; ( limit to 16-bit value )\n[then]\n\n: ccitt ( crc c-addr -- crc : calculate polynomial 0x1021 AKA \"x16 + x12 + x5 + 1\" )\n\tc@ ( get char )\n\tlimit over 256\/ xor ( crc x )\n\tdup 4 rshift xor ( crc x )\n\tdup 5 lshift limit xor ( crc x )\n\tdup 12 lshift limit xor ( crc x )\n\tswap 8 lshift limit xor ; ( crc )\n\n( See http:\/\/stackoverflow.com\/questions\/10564491\n and https:\/\/www.lammertbies.nl\/comm\/info\/crc-calculation.html )\n: crc16-ccitt ( c-addr u -- u )\n\t0xffff -rot\n\t['] ccitt foreach ;\nhide{ limit ccitt }hide\n\n( ==================== CRC =================================== )\n\n( ==================== Rational Data Type ==================== )\n( This word set allows the manipulation of a rational data\ntype, which are basically fractions. This allows numbers like\n1\/3 to be represented without any loss of precision. Conversion\nto and from the data type to an integer type is trivial,\nalthough information can be lost during the conversion.\n\nTo convert to a rational, use DUP, to convert from a\nrational, use '\/'.\n\nThe denominator is the first number on the stack, the numerator\nthe second number. Fractions are simplified after any rational\noperation, and all rational words can accept unsimplified\narguments. For example the fraction 1\/3 can be represented as\n6\/18, they are equivalent, so the rational equality operator\n\"=rat\" can accept both and returns true.\n\n\tT{ 1 3 6 18 =rat -> 1 }T\n\nSee: https:\/\/en.wikipedia.org\/wiki\/Rational_data_type For\nmore information.\n\nThis set of words use two cells to represent a fraction,\nhowever a single cell could be used, with the numerator and the\ndenominator stored in upper and lower half of a single cell.\n\n@todo add saturating Q numbers to the interpreter, as well as\narithmetic word for acting on double cells [d+, d-, etcetera]\nhttps:\/\/en.wikipedia.org\/wiki\/Q_%28number_format%29, this\ncan be used in lieu of floating point numbers. )\n\n: simplify ( a b -- a\/gcd{a,b} b\/gcd{a\/b} : simplify a rational )\n 2dup\n gcd\n tuck\n \/\n -rot\n \/\n swap ; \\ ? check this\n\n: crossmultiply ( a b c d -- a*d b*d c*b d*b )\n rot ( a c d b )\n 2dup ( a c d b d b )\n * ( a c d b d*b )\n >r ( a c d b , d*b )\n rot ( a d b c , d*b )\n * ( a d b*c , d*b )\n -rot ( b*c a d , d*b )\n * ( b*c a*d , d*b )\n r> ( b*c a*d d*b )\n tuck ( b*c d*b a*d d*b )\n 2swap ; ( done! )\n\n: *rat ( a\/b c\/d -- a\/b : multiply two rationals together )\n rot * -rot * swap simplify ;\n\n: \/rat ( a\/b c\/d -- a\/b : divide one rational by another )\n swap *rat ;\n\n: +rat ( a\/b c\/d -- a\/b : add two rationals together )\n crossmultiply\n rot\n drop ( or check if equal, if not there is an error )\n -rot\n +\n swap\n simplify ;\n\n: -rat ( a\/b c\/d -- a\/b : subtract one rational from another )\n crossmultiply\n rot\n drop ( or check if equal, if not there is an error )\n -rot\n -\n swap\n simplify ;\n\n: .rat ( a\/b -- : print out a rational number )\n simplify swap (.) drop [char] \/ emit . ;\n\n: =rat ( a\/b c\/d -- bool : rational equal )\n crossmultiply rot = -rot = = ;\n\n: >rat ( a\/b c\/d -- bool : rational greater than )\n crossmultiply rot 2drop > ;\n\n: <=rat ( a\/b c\/d -- bool : rational less than or equal to )\n\t>rat not ;\n\n: =rat ( a\/b c\/d -- bool : rational greater or equal to )\n\trational is a work in progress, make it better )\n: 0>number 0 -rot >number ;\n0 0 2variable saved\n: failed 0 0 saved 2@ ;\n: >rational ( c-addr u -- a\/b c-addr u )\n\t2dup saved 2!\n\t0>number 2dup 0= if 4drop failed exit then ( @note could convert to rational n\/1 )\n\tc@ [char] \/ <> if 3drop failed exit then\n\t1 \/string\n\t0>number ;\n\nhide{ 0>number saved failed }hide\n\n( ==================== Rational Data Type ==================== )\n\n( ==================== Block Layer =========================== )\n( This is the block layer, it assumes that the file access\nwords exists and use them, it would have to be rewritten\nfor an embedded device that used EEPROM or something\nsimilar. Currently it does not interact well with the current\ninput methods used by the interpreter which will need changing.\n\nThe block layer is the traditional way Forths implement a\nsystem to interact with mass storage, one which imposes little\non the underlying system only requiring that blocks 1024 bytes\ncan be loaded and saved to it [which make it suitable for\nmicrocomputers that lack a file system or an embedded device].\n\nThe block layer is used less than it once as a lot more Forths\nare hosted under a guest operating system so have access to\nmethods for reading and writing to files through it.\n\nEach block number accepted by BLOCK is backed by a file\n[or created if it does not exist]. The name of the file is\nthe block number with \".blk\" appended to it.\n\nSome Notes:\n\nBLOCK only uses one block buffer, most other Forths have\nmultiple block buffers, this could be improved on, but\nwould take up more space.\n\nAnother way of storing the blocks could be made, which is to\nstore the blocks in a single file and seek to the correct\nplace within it. This might be implemented in the future,\nor offered as an alternative. \n\nYet another way is to not have on disk blocks, but instead\nhave in memory blocks, this simplifies things significantly,\nand would mean saving the blocks to disk would use the same\nmechanism as saving the core file to disk. Computers certainly\nhave enough memory to do this. The block word set could\nbe factored so it could use either the on disk method or\nthe memory option. \n\nTo simplify the current code, and make the code portable\nto devices with EEPROM an instruction in the virtual machine\ncould be made which does the task of transfering a block to\ndisk. \n\n@todo refactor BLOCK to use MAKE\/DOER so its behavior can\nbe changed. )\n\n0 variable dirty\nb\/buf string buf ( block buffer, only one exists )\n0 , ( make sure buffer is NUL terminated, just in case )\n0 variable blk ( 0 = invalid block number, >0 block number stored in buf)\n\n: invalid? ( n -- : throw if block number is invalid )\n\t0= if -35 throw then ;\n\n: update ( -- : mark currently loaded block buffer as dirty )\n\ttrue dirty ! ;\n\n: updated? ( n -- bool : is a block updated? )\n \tblk @ <> if 0 else dirty @ then ;\n\n: block.name ( n -- c-addr u : make a block name )\n\tc\" .blk\" <# holds #s #> rot drop ;\n\n( @warning this will not work if we do not have permission,\nor in various other cases where we cannot open the file,\nfor whatever reason )\n: file-exists ( c-addr u : does a file exist? )\n\tr\/o open-file if drop 0 else close-file throw 1 then ;\n\n: block.exists ( n -- bool : does a block buffer exist on disk? )\n\tblock.name file-exists ;\n\n( @note block.write and block.read do not check if they have\nwrote or read in 1024 bytes, nor do they check that they can\nonly write or read 1024 and not a byte more )\n\n: block.read ( file-id -- file-id : read in buffer )\n\tdup >r buf r> read-file nip if close-file -33 throw then ;\n\n: block.write ( file-id -- file-id : write out buffer )\n\tdup >r buf r> write-file nip if close-file -34 throw then ;\n\n: block.open ( n fam -- file-id )\n\t>r block.name r> open-file throw ;\n\n: save-buffers\n\tblk @ 0= if exit then ( not a valid block number, exit )\n\tdirty @ not if exit then ( not dirty, no need to save )\n\tblk @ w\/o block.open ( open file backing block buffer )\n\tblock.write ( write it out )\n\tclose-file throw ( close it )\n\tfalse dirty ! ; ( but only mark it clean if everything succeeded )\n\n: empty-buffers ( -- : deallocate any saved buffers )\n\t0 blk ! ;\n\n: flush ( -- : perform save-buffers followed by empty-buffers )\n\tsave-buffers\n\tempty-buffers ;\n\n( Block is a complex word that does a lot, although it has\na simple interface. It does the following given a block number:\n\n1. Checks the provided block buffer number to make sure it\nis valid.\n2. If the block is already loaded from the disk, then return\nthe address of the block buffer it is loaded into.\n3. If not, it checks to see if the currently loaded block\nbuffer is dirty, if it is then it flushes the buffer to disk.\n4. If the block buffer does not exists on disk then it\ncreates it.\n5. It then stores the block number in blk and returns an\naddress to the block buffer. )\n: block ( n -- c-addr : load a block )\n\tdup invalid?\n\tdup blk @ = if drop buf drop exit then\n\tflush\n\tdup block.exists if ( if the buffer exits on disk load it in )\n\t\tdup r\/o block.open\n\t\tblock.read\n\t\tclose-file throw\n\telse ( else it does not exist )\n\t\tbuf 0 fill ( clean the buffer )\n\tthen\n\tblk ! ( save the block number )\n\tbuf drop ;\n\n: buffer block ;\n\n: load ( n -- : load and execute a block )\n\tblock b\/buf evaluate throw ;\n\n: +block ( n -- u : calculate new block number relative to current block )\n\tblk @ + ;\n\n: --> ( -- : load next block )\n\t1 +block load ;\n\n( @todo refactor into BLOCK.MAKE, which BLOCKS.MAKE would use )\n: blocks.make ( n1 n2 -- : make blocks on disk from n1 to n2 inclusive )\n\t1+ swap do i block b\/buf bl fill update loop save-buffers ;\n\n: block.copy ( n1 n2 -- bool : copy block n2 to n1 if n2 exists )\n\tswap dup block.exists 0= if 2drop false exit then ( n2 n1 )\n\tblock drop ( load in block n1 )\n\tw\/o block.open block.write close-file throw\n\ttrue ;\n\n: block.delete ( n -- : delete block )\n\tdup block.exists 0= if drop exit then\n\tblock.name delete-file drop ;\n\n\\ @todo implement a word that splits a file into blocks\n\\ : split ( c-addr u : split a file into blocks )\n\\\t;\n\nhide{\n\tblock.name invalid? block.write\n\tblock.read block.exists block.open dirty\n}hide\n\n( ==================== Block Layer =========================== )\n\n( ==================== List ================================== )\n( The list word set allows the viewing of Forth blocks,\nthis version of list can create two Formats, a simple mode\nwhere it just spits out the block with a carriage return\nafter each line and a more fancy version which also prints\nout line numbers and draws a box around the data. LIST is\nnot aware of any formatting and characters that might be\npresent in the data, or none printable characters.\n\nA very primitive version of list can be defined as follows:\n\n\t: list block b\/buf type ;\n\n)\n\n1 variable fancy-list\n0 variable scr\n64 constant c\/l ( characters per line )\n\n: pipe ( -- : emit a pipe character )\n\t[char] | emit ;\n\n: line.number ( n -- : print line number )\n\tfancy-list @ not if drop exit then\n\t2 u.r space pipe ;\n\n: list.end ( -- : print the right hand side of the box )\n\tfancy-list @ not if exit then\n\tpipe ;\n\n: line ( c-addr -- c-addr u : given a line number, display that line number and calculate offset )\n\tdup\n\tline.number ( display line number )\n\tc\/l * + ( calculate offset )\n\tc\/l ; ( add line length )\n\n: list.type ( c-addr u -- : list a block )\n\tb\/buf c\/l \/ 0 do dup i line type list.end cr loop drop ;\n\n: list.border ( -- : print a section of the border )\n\t\" +---|---\" ;\n\n: list.box ( )\n\tfancy-list @ not if exit then\n\t4 spaces\n\t8 0 do list.border loop cr ;\n\n: list ( n -- : display a block number and update scr )\n\tdup >r block r> scr ! list.box list.type list.box ;\n\n: thru\n\tkey drop\n\t1+ swap do i list more loop ;\n\nhide{\n\tbuf line line.number list.type\n\t(base) list.box list.border list.end pipe\n}hide\n\n( ==================== List ================================== )\n\n( ==================== Signal Handling ======================= )\n( Signal handling at the moment is quite primitive. When\na signal occurs it has to be explicitly tested for by the\nprogrammer, this could be improved on quite a bit. One way\nof doing this would be to check for signals in the virtual\nmachine and cause a THROW from within it. )\n\n( signals are biased to fall outside the range of the error\nnumbers defined in the ANS Forth standard. )\n-512 constant signal-bias\n\n: signal ( -- signal\/0 : push the results of the signal register )\n\t`signal @\n \t0 `signal ! ;\n\n( ==================== Signal Handling ======================= )\n\n( Looking at most Forths dictionary with \"words\" command they\ntend to have a lot of words that do not mean anything but to\nthe implementers of that specific Forth, here we clean up as\nmany non standard words as possible. )\nhide{\n do-string ')' alignment-bits\n dictionary-start hidden-mask instruction-mask immediate-mask compiling?\n compile-bit\n max-core dolist doconst x x! x@\n max-string-length\n evaluator\n TrueFalse >instruction\n xt-instruction\n `source-id `sin `sidx `slen `start-address `fin `fout `stdin\n `stdout `stderr `argc `argv `debug `invalid `top `instruction\n `stack-size `error-handler `handler _emit `signal `x\n}hide\n\n(\n## Forth To List\n\nThe following is a To-Do list for the Forth code itself,\nalong with any other ideas.\n\n* FORTH, VOCABULARY\n\n* \"Value\", \"To\", \"Is\"\n\n* Double cell words\n\n* The interpreter should use character based addresses,\ninstead of word based, and use values that are actual valid\npointers, this will allow easier interaction with the world\noutside the virtual machine\n\n* common words and actions should be factored out to simplify\ndefinitions of other words, their standards compliant version\nfound if any.\n\n* A soft floating point library would be useful which could be\nused to optionally implement floats [which is not something I\nreally want to add to the virtual machine]. If floats were to\nbe added, only the minimal set of functions should be added\n[f+,f-,f\/,f*,f<,f>,>float,...]\n\n* Allow the processing of argc and argv, the mechanism by which\nthat this can be achieved needs to be worked out. However all\nprocessing that is currently done in \"main.c\" should be done\nwithin the Forth interpreter instead. Words for manipulating\nrationals and double width cells should be made first.\n\n* A built in version of \"dump\" and \"words\" should be added\nto the Forth starting vocabulary, simplified versions that\ncan be hidden.\n\n* Here documents, string literals. Examples of these can be\nfound online\n\n* Document the words in this file and built in words better,\nalso turn this document into a literate Forth file.\n\n* Sort out \"'\", \"[']\", \"find\", \"compile,\"\n\n* Proper booleans should be used throughout, that is -1 is\ntrue, and 0 is false.\n\n* Attempt to add crypto primitives, not for serious use,\nlike TEA, XTEA, XXTEA, RC4, MD5, ...\n\n* Add hash functions: CRC-32, CRC-16, ...\nhttp:\/\/stackoverflow.com\/questions\/10564491\/\n\n* Implement as many things from\nhttp:\/\/lars.nocrew.org\/forth2012\/implement.html as is sensible.\n\n* Works like EMIT and KEY should be DOER\/MAKE words\n\n* The current words that implement I\/O redirection need to\nbe improved, and documented, I think this is quite a useful\nand powerful mechanism to use within Forth that simplifies\nprograms. This is a must and will make writing utilities in\nForth a *lot* easier\n\n* Words for manipulating words should be added, for navigating\nto different fields within them, to the end of the word,\netcetera.\n\n* The data structure used for parsing Forth words needs\nchanging in libforth so a counted string is produced. Counted\nstrings should be used more often. The current layout of a\nForth word prevents a counted string being used and uses a\nbyte more than it has to.\n\n* Whether certain simple words [such as '1+', '1-', '>',\n'<', '<>', NOT, <=', '>='] should be added as virtual\nmachine instructions for speed [and size] reasons should\nbe investigated.\n\n* An analysis of the interpreter and the code it executes\ncould be done to find the most commonly executed words\nand instructions, as well as the most common two and three\nsequences of words and instructions. This could be used to use\nto optimize the interpreter, in terms of both speed and size.\n\n* The source code for this file should go through a code\nreview, which should focus on formatting, stack comments and\nreorganizing the code. Currently it is not clear that variables\nlike COLORIZE and FANCY-LIST exist and can be changed by\nthe user. Lines should be 64 characters in length - maximum,\nincluding the new line at the end of the file.\n\n### libforth.c todo\n\n* A halt, a parse, and a print\/type instruction could be\nadded to the Forth virtual machine.\n\n* Make case sensitivity optional\n\n* u.r, or a more generic version should be added to the\ninterpreter instead of the current simpler primitive. As\nshould >number - for fast numeric input and output.\n\n* Throw\/Catch need to be added and used in the virtual machine\n\n* Integrate Travis Continous Integration into the Github\nproject.\n\n* A potential optimization is to order the words in the\ndictionary by frequency order, this would mean chaning the\nX Macro that contains the list of words, after collecting\nstatistics. This should make find faster.\n\n* Investigate adding operating system specific code into the\ninterpreter and isolating it to make it semi-portable.\n\n* Make equivalents for various Unix utilities in Forth,\nlike a CRC check, cat, tr, etcetera.\n\n* It would be interesting to make a primitive file system based\nupon Forth blocks, this could then be ported to systems that\ndo not have file systems, such as microcontrollers [which\nusually have EEPROM].\n\n* In a _very_ unportable way it would be possible to have an\ninstruction that takes the top of the stack, treats it as a\nfunction pointer and then attempts to call said function. This\nwould allow us to assemble machine dependant code within the\ncore file, generate a new function, then call it. It is just\na thought.\n )\n\nverbose [if]\n\t.( FORTH: libforth successfully loaded.) cr\n\tdate .date cr\n\t.( Type 'help' and press return for a basic introduction.) cr\n\t.( Core: ) here . \" \/ \" here unused + . cr\n\t license\n[then]\n\n( ==================== Test Code ============================= )\n\n( The following will not work as we might actually be reading\nfrom a string [`sin] not `fin.\n\n: key 32 chars> 1 `fin @\n\tread-file drop 0 = if 0 else 32 chars> c@ then ; )\n\n\\ : ' immediate state @ if postpone ['] else find then ;\n\n( This really does not implement a correct FORTH\/VOCABULARY,\nfor that wordlists will need to be introduced and used in\nlibforth.c. The best that this word set can do is to hide\nand reveal words to the user, this was just an experiment.\n\n\t: forth\n\t\t[ find forth 1- @ ] literal\n\t\t[ find forth 1- ] literal ! ;\n\n\t: vocabulary\n\t\tcreate does> drop 0 [ find forth 1- ] literal ! ; )\n\n\\ @todo The built in primitives should be redefined so to make sure\n\\ they are called and nested correctly, using the following words\n\\ 0 variable csp\n\\ : !csp sp@ csp ! ;\n\\ : ?csp sp@ csp @ <> if -22 throw then ;\n\n\\ @todo Make this work\n\\ : >body ??? ;\n\\ : noop ( -- ) ;\n\\ : defer create ( \"name\" -- ) ['] noop , does> ( -- ) @ execute ;\n\\ : is ( xt \"name\" -- ) find >body ! ;\n\\ defer lessthan\n\\ find < is lessthan\n\n( ==================== Test Code ============================= )\n\n( ==================== Block Editor ========================== )\n( Experimental block editor Mark II\n\nThis is a simple block editor, it really shows off the power\nand simplicity of Forth systems - both the concept of a block\neditor and the implementation.\n\nForth source code used to organized into things called 'blocks',\nnowadays most people use normal resizeable stream based files.\nA block simply consists of 1024 bytes of data that can be\ntransfered to and from mass storage. This works on systems that\ndo not have a file system. A block can be used for storing\narbitrary data as well, so the user had to know what was stored\nin what block.\n\n1024 bytes is quite a limiting Form factor for storing source\ncode, which is probably one reason Forth earned a reputation\nfor being terse. A few conventions arose around dealing with\nForth source code stored in blocks - both in how the code should\nbe formatted within them, and in how programs that required\nmore than one block of storage should be dealt with.\n\nOne of the conventions is how many columns and rows each block\nconsists of, the traditional way is to organize the code into\n16 lines of text, with a column width of 64 characters. The only\nspace character used is the space [or ASCII character 32], tabs\nand new lines are not used, as they are not needed - the editor\nknows how long a line is so it can wrap the text.\n\nVarious standards and common practice evolved as to what goes\ninto a block - for example the first line is usually a comment\ndescribing what the block does, with the date is was last edited\nand who edited it.\n\nThe way the editor works is by defining a simple set of words\nthat act on the currently loaded block, LIST is used to display\nthe loaded block. An editor loop which executes forth words\nand automatically displays the currently block can be entered\nby calling EDITOR. This loop is essential an extension of\nthe INTERPRET word, it does no special processing such as\nlooking for keys - all commands are Forth words. The editor\nloop could have been implemented in the following fashion\n[or something similar]:\n\n\t: editor-command\n\t\tkey\n\t\tcase\n\t\t\t[char] h of print-editor-help endof\n\t\t\t[char] i of insert-text endof\n\t\t\t[char] d of delete-line endof\n\t\t\t... more editor commands\n\t\t\t[char] q of quit-editor-loop endof\n\t\t\tpush-number-by-default\n\t\tendof ;\n\nHowever this is rather limiting, it only works for single\ncharacter commands and numeric input is handled as a special\ncase. It is far simpler to just call the READ word with the\neditor commands in search order, and it can be extended not\nby adding more parsing code in CASE statements but just by\ndefining new words in the ordinary manner.\n\nThe editor loop does not have to be used while editing code,\nbut it does make things easier. The commands defined can be\nused on there own.\n\t\nThe code was adapted from: \t\n\nhttp:\/\/retroforth.org\/pages\/?PortsOfRetroEditor\n\nWhich contains ports of an editor written for Retro Forth.\n\n@todo Improve the block editor\n\n- '\\' needs extending to work with the block editor, for now,\nuse parenthesis for comments\n- add multi line insertion mode\n- Add to an editor vocabulary, which will need the vocabulary\nsystem to exist.\n- Using PAGE should be optional as not all terminals support\nANSI escape codes - thanks to CMD.EXE. Damned Windows.\n\nAdapted from http:\/\/retroforth.org\/pages\/?PortsOfRetroEditor )\n\n\n: help ( @todo rename to H once vocabularies are implemented )\npage cr\n\" Block Editor Help Menu\n\n n move to next block\n p move to previous block\n # d delete line in current block\n x erase current block\n e evaluate current block\n # i insert line\n # #2 ia insert at line #2 at column #\n q quit editor loop\n # b set block number\n s save block and write it out\n u update block\n\n -- press any key to continue -- \" cr ( \" )\nchar drop ;\n\n: (block) blk @ block ;\n: (check) dup b\/buf c\/l \/ u>= if -24 throw then ;\n: (line) (check) c\/l * (block) + ; ( n -- c-addr : push current line address )\n: (clean)\n\t(block) b\/buf\n\t2dup nl bl subst\n\t2dup cret bl subst\n\t 0 bl subst ;\n: n 1 +block block ;\n: p -1 +block block ;\n: d (line) c\/l bl fill ;\n: x (block) b\/buf bl fill ;\n: s update save-buffers ;\n: q rdrop rdrop ;\n: e blk @ load char drop ;\n: ia c\/l * + dup b\/buf swap - >r (block) + r> accept drop (clean) ;\n: i 0 swap ia ;\n: editor\n\t1 block ( load first block by default )\n\trendezvous ( set up a rendezvous so we can forget words up to this point )\n\tbegin\n\t\tpage cr\n\t\t\" BLOCK EDITOR: TYPE 'HELP' FOR A LIST OF COMMANDS\" cr\n\t\tblk @ list\n\t\t\" [BLOCK: \" blk @ u. \" ] \" \n\t\t\" [HERE: \" here u. \" ] \" \n\t\t\" [SAVED: \" blk @ updated? not u. \" ] \"\n\t\tcr\n\t\tpostpone [ ( need to be in command mode )\n\t\tread\n\tagain ;\n\n( Extra niceties )\nc\/l string yank \nyank bl fill\n: u update ;\n: b block ;\n: l blk @ list ;\n: y (line) yank >r swap r> cmove ; ( n -- yank line number to buffer )\n: c (line) yank cmove ; ( n -- copy yank buffer to line )\n: ct swap y c ; ( n1 n2 -- copy line n1 to n2 )\n: ea (line) c\/l evaluate throw ;\n: m retreat ; ( -- : forget everything since editor session began )\n\n: sw 2dup y (line) swap (line) swap c\/l cmove c ;\n\nhide{ (block) (line) (clean) yank }hide\n\n( ==================== Block Editor ========================== )\n\n( ==================== Error checking ======================== )\n( This is a series of redefinitions that make the use of control\nstructures a bit safer. )\n\n: if immediate ?comp postpone if [ hide if ] ;\n: else immediate ?comp postpone else [ hide else ] ;\n: then immediate ?comp postpone then [ hide then ] ;\n: begin immediate ?comp postpone begin [ hide begin ] ;\n: until immediate ?comp postpone until [ hide until ] ;\n: never immediate ?comp postpone never [ hide never ] ;\n\\ : ; immediate ?comp postpone ; [ hide ; ] ; ( @todo do nesting checking for control statements )\n\n( ==================== Error checking ======================== )\n\n( ==================== DUMP ================================== )\n\\ : newline ( x -- x+1 : print a new line every fourth value )\n\\ \tdup 3 and 0= if cr then 1+ ;\n\\\n\\ : address ( num count -- count : print current address we are dumping every fourth value )\n\\ \tdup >r\n\\ \t1- 3 and 0= if . [char] : emit space else drop then\n\\ \tr> ;\n\\\n\\ : dump ( start count -- : print the contents of a section of memory )\n\\ \\\thex ( switch to hex mode )\n\\ \t1 >r ( save counter on return stack )\n\\ \tover + swap ( calculate limits: start start+count )\n\\ \tbegin\n\\ \t\t2dup u> ( stop if gone past limits )\n\\ \twhile\n\\ \t\tdup r> address >r\n\\ \t\tdup @ . 1+\n\\ \t\tr> newline >r\n\\ \trepeat\n\\ \tr> drop\n\\ \t2drop ;\n\\\n\\ hide newline\n\\ hide address\n( ==================== DUMP ================================== )\n\n( ==================== End of File Functions ================= )\n\n( set up a rendezvous point, we can call the word RETREAT to\nrestore the dictionary to this point. This word also updates\nfence to this location in the dictionary )\nrendezvous\n\n: task ; ( Task is a word that can safely be forgotten )\n\n( ==================== End of File Functions ================= )\n\n( Experimental FOR ... NEXT )\n: for immediate\n\t?comp\n\t['] >r ,\n\there\n\t;\n\n: (next) ( -- bool, R: val -- | val+1 )\n\tr> r> 1- dup 0= if drop >r 1 else >r >r 0 then ;\n\n: next immediate\n\t?comp\n\t['] (next) , ['] ?branch , here - , ;\n \n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"d23e64a924a1279a83dbfc2c1292c8a2ce041962","subject":"Porposed new test for D< bug","message":"Porposed new test for D< bug\n","repos":"zuloloxi\/swapforth,uho\/swapforth,RGD2\/swapforth,RGD2\/swapforth,jamesbowman\/swapforth,jamesbowman\/swapforth,zuloloxi\/swapforth,zuloloxi\/swapforth,zuloloxi\/swapforth,jamesbowman\/swapforth,GuzTech\/swapforth,uho\/swapforth,jamesbowman\/swapforth,uho\/swapforth,uho\/swapforth,GuzTech\/swapforth,RGD2\/swapforth,GuzTech\/swapforth,RGD2\/swapforth,GuzTech\/swapforth","old_file":"anstests\/doubletest.fth","new_file":"anstests\/doubletest.fth","new_contents":"\\ To test the ANS Forth Double-Number word set and double number extensions\r\n\r\n\\ This program was written by Gerry Jackson in 2006, with contributions from\r\n\\ others where indicated, and is in the public domain - it can be distributed\r\n\\ and\/or modified in any way but please retain this notice.\r\n\r\n\\ This program is distributed in the hope that it will be useful,\r\n\\ but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n\\ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\r\n\r\n\\ The tests are not claimed to be comprehensive or correct \r\n\\ ------------------------------------------------------------------------------\r\n\\ Version 0.11 7 April 2015 2VALUE tested\r\n\\ 0.6 1 April 2012 Tests placed in the public domain.\r\n\\ Immediate 2CONSTANTs and 2VARIABLEs tested\r\n\\ 0.5 20 November 2009 Various constants renamed to avoid\r\n\\ redefinition warnings. and replaced\r\n\\ with TRUE and FALSE\r\n\\ 0.4 6 March 2009 { and } replaced with T{ and }T\r\n\\ Tests rewritten to be independent of word size and\r\n\\ tests re-ordered\r\n\\ 0.3 20 April 2007 ANS Forth words changed to upper case\r\n\\ 0.2 30 Oct 2006 Updated following GForth test to include\r\n\\ various constants from core.fr\r\n\\ 0.1 Oct 2006 First version released\r\n\\ ------------------------------------------------------------------------------\r\n\\ The tests are based on John Hayes test program for the core word set\r\n\r\n\\ Words tested in this file are:\r\n\\ 2CONSTANT 2LITERAL 2VARIABLE D+ D- D. D.R D0< D0= D2* D2\/\r\n\\ D< D= D>S DABS DMAX DMIN DNEGATE M*\/ M+ 2ROT DU<\r\n\\ Also tests the interpreter and compiler reading a double number\r\n\\ ------------------------------------------------------------------------------\r\n\\ Assumptions and dependencies:\r\n\\ - tester.fr or ttester.fs has been included prior to this file\r\n\\ - core words and core extension words have been tested\r\n\\ ------------------------------------------------------------------------------\r\n\\ Constant definitions\r\n\r\nDECIMAL\r\n0 INVERT CONSTANT 1SD\r\n1SD 1 RSHIFT CONSTANT MAX-INTD \\ 01...1\r\nMAX-INTD INVERT CONSTANT MIN-INTD \\ 10...0\r\nMAX-INTD 2\/ CONSTANT HI-INT \\ 001...1\r\nMIN-INTD 2\/ CONSTANT LO-INT \\ 110...1\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING interpreter and compiler reading a double number\r\n\r\nT{ 1. -> 1 0 }T\r\nT{ -2. -> -2 -1 }T\r\nT{ : RDL1 3. ; RDL1 -> 3 0 }T\r\nT{ : RDL2 -4. ; RDL2 -> -4 -1 }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING 2CONSTANT\r\n\r\nT{ 1 2 2CONSTANT 2C1 -> }T\r\nT{ 2C1 -> 1 2 }T\r\nT{ : CD1 2C1 ; -> }T\r\nT{ CD1 -> 1 2 }T\r\nT{ : CD2 2CONSTANT ; -> }T\r\nT{ -1 -2 CD2 2C2 -> }T\r\nT{ 2C2 -> -1 -2 }T\r\nT{ 4 5 2CONSTANT 2C3 IMMEDIATE 2C3 -> 4 5 }T\r\nT{ : CD6 2C3 2LITERAL ; CD6 -> 4 5 }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\n\\ Some 2CONSTANTs for the following tests\r\n\r\n1SD MAX-INTD 2CONSTANT MAX-2INT \\ 01...1\r\n0 MIN-INTD 2CONSTANT MIN-2INT \\ 10...0\r\nMAX-2INT 2\/ 2CONSTANT HI-2INT \\ 001...1\r\nMIN-2INT 2\/ 2CONSTANT LO-2INT \\ 110...0\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING DNEGATE\r\n\r\nT{ 0. DNEGATE -> 0. }T\r\nT{ 1. DNEGATE -> -1. }T\r\nT{ -1. DNEGATE -> 1. }T\r\nT{ MAX-2INT DNEGATE -> MIN-2INT SWAP 1+ SWAP }T\r\nT{ MIN-2INT SWAP 1+ SWAP DNEGATE -> MAX-2INT }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING D+ with small integers\r\n\r\nT{ 0. 5. D+ -> 5. }T\r\nT{ -5. 0. D+ -> -5. }T\r\nT{ 1. 2. D+ -> 3. }T\r\nT{ 1. -2. D+ -> -1. }T\r\nT{ -1. 2. D+ -> 1. }T\r\nT{ -1. -2. D+ -> -3. }T\r\nT{ -1. 1. D+ -> 0. }T\r\n\r\nTESTING D+ with mid range integers\r\n\r\nT{ 0 0 0 5 D+ -> 0 5 }T\r\nT{ -1 5 0 0 D+ -> -1 5 }T\r\nT{ 0 0 0 -5 D+ -> 0 -5 }T\r\nT{ 0 -5 -1 0 D+ -> -1 -5 }T\r\nT{ 0 1 0 2 D+ -> 0 3 }T\r\nT{ -1 1 0 -2 D+ -> -1 -1 }T\r\nT{ 0 -1 0 2 D+ -> 0 1 }T\r\nT{ 0 -1 -1 -2 D+ -> -1 -3 }T\r\nT{ -1 -1 0 1 D+ -> -1 0 }T\r\nT{ MIN-INTD 0 2DUP D+ -> 0 1 }T\r\nT{ MIN-INTD S>D MIN-INTD 0 D+ -> 0 0 }T\r\n\r\nTESTING D+ with large double integers\r\n\r\nT{ HI-2INT 1. D+ -> 0 HI-INT 1+ }T\r\nT{ HI-2INT 2DUP D+ -> 1SD 1- MAX-INTD }T\r\nT{ MAX-2INT MIN-2INT D+ -> -1. }T\r\nT{ MAX-2INT LO-2INT D+ -> HI-2INT }T\r\nT{ HI-2INT MIN-2INT D+ 1. D+ -> LO-2INT }T\r\nT{ LO-2INT 2DUP D+ -> MIN-2INT }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING D- with small integers\r\n\r\nT{ 0. 5. D- -> -5. }T\r\nT{ 5. 0. D- -> 5. }T\r\nT{ 0. -5. D- -> 5. }T\r\nT{ 1. 2. D- -> -1. }T\r\nT{ 1. -2. D- -> 3. }T\r\nT{ -1. 2. D- -> -3. }T\r\nT{ -1. -2. D- -> 1. }T\r\nT{ -1. -1. D- -> 0. }T\r\n\r\nTESTING D- with mid-range integers\r\n\r\nT{ 0 0 0 5 D- -> 0 -5 }T\r\nT{ -1 5 0 0 D- -> -1 5 }T\r\nT{ 0 0 -1 -5 D- -> 1 4 }T\r\nT{ 0 -5 0 0 D- -> 0 -5 }T\r\nT{ -1 1 0 2 D- -> -1 -1 }T\r\nT{ 0 1 -1 -2 D- -> 1 2 }T\r\nT{ 0 -1 0 2 D- -> 0 -3 }T\r\nT{ 0 -1 0 -2 D- -> 0 1 }T\r\nT{ 0 0 0 1 D- -> 0 -1 }T\r\nT{ MIN-INTD 0 2DUP D- -> 0. }T\r\nT{ MIN-INTD S>D MAX-INTD 0 D- -> 1 1SD }T\r\n\r\nTESTING D- with large integers\r\n\r\nT{ MAX-2INT MAX-2INT D- -> 0. }T\r\nT{ MIN-2INT MIN-2INT D- -> 0. }T\r\nT{ MAX-2INT HI-2INT D- -> LO-2INT DNEGATE }T\r\nT{ HI-2INT LO-2INT D- -> MAX-2INT }T\r\nT{ LO-2INT HI-2INT D- -> MIN-2INT 1. D+ }T\r\nT{ MIN-2INT MIN-2INT D- -> 0. }T\r\nT{ MIN-2INT LO-2INT D- -> LO-2INT }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING D0< D0=\r\n\r\nT{ 0. D0< -> FALSE }T\r\nT{ 1. D0< -> FALSE }T\r\nT{ MIN-INTD 0 D0< -> FALSE }T\r\nT{ 0 MAX-INTD D0< -> FALSE }T\r\nT{ MAX-2INT D0< -> FALSE }T\r\nT{ -1. D0< -> TRUE }T\r\nT{ MIN-2INT D0< -> TRUE }T\r\n\r\nT{ 1. D0= -> FALSE }T\r\nT{ MIN-INTD 0 D0= -> FALSE }T\r\nT{ MAX-2INT D0= -> FALSE }T\r\nT{ -1 MAX-INTD D0= -> FALSE }T\r\nT{ 0. D0= -> TRUE }T\r\nT{ -1. D0= -> FALSE }T\r\nT{ 0 MIN-INTD D0= -> FALSE }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING D2* D2\/\r\n\r\nT{ 0. D2* -> 0. D2* }T\r\nT{ MIN-INTD 0 D2* -> 0 1 }T\r\nT{ HI-2INT D2* -> MAX-2INT 1. D- }T\r\nT{ LO-2INT D2* -> MIN-2INT }T\r\n\r\nT{ 0. D2\/ -> 0. }T\r\nT{ 1. D2\/ -> 0. }T\r\nT{ 0 1 D2\/ -> MIN-INTD 0 }T\r\nT{ MAX-2INT D2\/ -> HI-2INT }T\r\nT{ -1. D2\/ -> -1. }T\r\nT{ MIN-2INT D2\/ -> LO-2INT }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING D< D=\r\n\r\nT{ 0. 1. D< -> TRUE }T\r\nT{ 0. 0. D< -> FALSE }T\r\nT{ 1. 0. D< -> FALSE }T\r\nT{ -1. 1. D< -> TRUE }T\r\nT{ -1. 0. D< -> TRUE }T\r\nT{ -2. -1. D< -> TRUE }T\r\nT{ -1. -2. D< -> FALSE }T\r\nT{ -1. MAX-2INT D< -> TRUE }T\r\nT{ MIN-2INT MAX-2INT D< -> TRUE }T\r\nT{ MAX-2INT -1. D< -> FALSE }T\r\nT{ MAX-2INT MIN-2INT D< -> FALSE }T\r\nT{ MAX-2INT 2DUP -1. D+ D< -> FALSE }T\r\nT{ MIN-2INT 2DUP 1. D+ D< -> TRUE }T\r\nT{ MAX-INTD S>D 2DUP 1. D+ D< -> TRUE }T\r\n\r\nT{ -1. -1. D= -> TRUE }T\r\nT{ -1. 0. D= -> FALSE }T\r\nT{ -1. 1. D= -> FALSE }T\r\nT{ 0. -1. D= -> FALSE }T\r\nT{ 0. 0. D= -> TRUE }T\r\nT{ 0. 1. D= -> FALSE }T\r\nT{ 1. -1. D= -> FALSE }T\r\nT{ 1. 0. D= -> FALSE }T\r\nT{ 1. 1. D= -> TRUE }T\r\n\r\nT{ 0 -1 0 -1 D= -> TRUE }T\r\nT{ 0 -1 0 0 D= -> FALSE }T\r\nT{ 0 -1 0 1 D= -> FALSE }T\r\nT{ 0 0 0 -1 D= -> FALSE }T\r\nT{ 0 0 0 0 D= -> TRUE }T\r\nT{ 0 0 0 1 D= -> FALSE }T\r\nT{ 0 1 0 -1 D= -> FALSE }T\r\nT{ 0 1 0 0 D= -> FALSE }T\r\nT{ 0 1 0 1 D= -> TRUE }T\r\n\r\nT{ MAX-2INT MIN-2INT D= -> FALSE }T\r\nT{ MAX-2INT 0. D= -> FALSE }T\r\nT{ MAX-2INT MAX-2INT D= -> TRUE }T\r\nT{ MAX-2INT HI-2INT D= -> FALSE }T\r\nT{ MAX-2INT MIN-2INT D= -> FALSE }T\r\nT{ MIN-2INT MIN-2INT D= -> TRUE }T\r\nT{ MIN-2INT LO-2INT D= -> FALSE }T\r\nT{ MIN-2INT MAX-2INT D= -> FALSE }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING 2LITERAL 2VARIABLE\r\n\r\nT{ : CD3 [ MAX-2INT ] 2LITERAL ; -> }T\r\nT{ CD3 -> MAX-2INT }T\r\nT{ 2VARIABLE 2V1 -> }T\r\nT{ 0. 2V1 2! -> }T\r\nT{ 2V1 2@ -> 0. }T\r\nT{ -1 -2 2V1 2! -> }T\r\nT{ 2V1 2@ -> -1 -2 }T\r\nT{ : CD4 2VARIABLE ; -> }T\r\nT{ CD4 2V2 -> }T\r\nT{ : CD5 2V2 2! ; -> }T\r\nT{ -2 -1 CD5 -> }T\r\nT{ 2V2 2@ -> -2 -1 }T\r\nT{ 2VARIABLE 2V3 IMMEDIATE 5 6 2V3 2! -> }T\r\nT{ 2V3 2@ -> 5 6 }T\r\nT{ : CD7 2V3 [ 2@ ] 2LITERAL ; CD7 -> 5 6 }T\r\nT{ : CD8 [ 6 7 ] 2V3 [ 2! ] ; 2V3 2@ -> 6 7 }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING DMAX DMIN\r\n\r\nT{ 1. 2. DMAX -> 2. }T\r\nT{ 1. 0. DMAX -> 1. }T\r\nT{ 1. -1. DMAX -> 1. }T\r\nT{ 1. 1. DMAX -> 1. }T\r\nT{ 0. 1. DMAX -> 1. }T\r\nT{ 0. -1. DMAX -> 0. }T\r\nT{ -1. 1. DMAX -> 1. }T\r\nT{ -1. -2. DMAX -> -1. }T\r\n\r\nT{ MAX-2INT HI-2INT DMAX -> MAX-2INT }T\r\nT{ MAX-2INT MIN-2INT DMAX -> MAX-2INT }T\r\nT{ MIN-2INT MAX-2INT DMAX -> MAX-2INT }T\r\nT{ MIN-2INT LO-2INT DMAX -> LO-2INT }T\r\n\r\nT{ MAX-2INT 1. DMAX -> MAX-2INT }T\r\nT{ MAX-2INT -1. DMAX -> MAX-2INT }T\r\nT{ MIN-2INT 1. DMAX -> 1. }T\r\nT{ MIN-2INT -1. DMAX -> -1. }T\r\n\r\n\r\nT{ 1. 2. DMIN -> 1. }T\r\nT{ 1. 0. DMIN -> 0. }T\r\nT{ 1. -1. DMIN -> -1. }T\r\nT{ 1. 1. DMIN -> 1. }T\r\nT{ 0. 1. DMIN -> 0. }T\r\nT{ 0. -1. DMIN -> -1. }T\r\nT{ -1. 1. DMIN -> -1. }T\r\nT{ -1. -2. DMIN -> -2. }T\r\n\r\nT{ MAX-2INT HI-2INT DMIN -> HI-2INT }T\r\nT{ MAX-2INT MIN-2INT DMIN -> MIN-2INT }T\r\nT{ MIN-2INT MAX-2INT DMIN -> MIN-2INT }T\r\nT{ MIN-2INT LO-2INT DMIN -> MIN-2INT }T\r\n\r\nT{ MAX-2INT 1. DMIN -> 1. }T\r\nT{ MAX-2INT -1. DMIN -> -1. }T\r\nT{ MIN-2INT 1. DMIN -> MIN-2INT }T\r\nT{ MIN-2INT -1. DMIN -> MIN-2INT }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING D>S DABS\r\n\r\nT{ 1234 0 D>S -> 1234 }T\r\nT{ -1234 -1 D>S -> -1234 }T\r\nT{ MAX-INTD 0 D>S -> MAX-INTD }T\r\nT{ MIN-INTD -1 D>S -> MIN-INTD }T\r\n\r\nT{ 1. DABS -> 1. }T\r\nT{ -1. DABS -> 1. }T\r\nT{ MAX-2INT DABS -> MAX-2INT }T\r\nT{ MIN-2INT 1. D+ DABS -> MAX-2INT }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING M+ M*\/\r\n\r\nT{ HI-2INT 1 M+ -> HI-2INT 1. D+ }T\r\nT{ MAX-2INT -1 M+ -> MAX-2INT -1. D+ }T\r\nT{ MIN-2INT 1 M+ -> MIN-2INT 1. D+ }T\r\nT{ LO-2INT -1 M+ -> LO-2INT -1. D+ }T\r\n\r\n\\ To correct the result if the division is floored, only used when\r\n\\ necessary i.e. negative quotient and remainder <> 0\r\n\r\n: ?FLOORED [ -3 2 \/ -2 = ] LITERAL IF 1. D- THEN ;\r\n\r\nT{ 5. 7 11 M*\/ -> 3. }T\r\nT{ 5. -7 11 M*\/ -> -3. ?FLOORED }T \\ FLOORED -4.\r\nT{ -5. 7 11 M*\/ -> -3. ?FLOORED }T \\ FLOORED -4.\r\nT{ -5. -7 11 M*\/ -> 3. }T\r\nT{ MAX-2INT 8 16 M*\/ -> HI-2INT }T\r\nT{ MAX-2INT -8 16 M*\/ -> HI-2INT DNEGATE ?FLOORED }T \\ FLOORED SUBTRACT 1\r\nT{ MIN-2INT 8 16 M*\/ -> LO-2INT }T\r\nT{ MIN-2INT -8 16 M*\/ -> LO-2INT DNEGATE }T\r\nT{ MAX-2INT MAX-INTD MAX-INTD M*\/ -> MAX-2INT }T\r\nT{ MAX-2INT MAX-INTD 2\/ MAX-INTD M*\/ -> MAX-INTD 1- HI-2INT NIP }T\r\nT{ MIN-2INT LO-2INT NIP DUP NEGATE M*\/ -> MIN-2INT }T\r\nT{ MIN-2INT LO-2INT NIP 1- MAX-INTD M*\/ -> MIN-INTD 3 + HI-2INT NIP 2 + }T\r\nT{ MAX-2INT LO-2INT NIP DUP NEGATE M*\/ -> MAX-2INT DNEGATE }T\r\nT{ MIN-2INT MAX-INTD DUP M*\/ -> MIN-2INT }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING D. D.R\r\n\r\n\\ Create some large double numbers\r\nMAX-2INT 71 73 M*\/ 2CONSTANT DBL1\r\nMIN-2INT 73 79 M*\/ 2CONSTANT DBL2\r\n\r\n: D>ASCII ( D -- CADDR U )\r\n DUP >R <# DABS #S R> SIGN #> ( -- CADDR1 U )\r\n HERE SWAP 2DUP 2>R CHARS DUP ALLOT MOVE 2R>\r\n;\r\n\r\nDBL1 D>ASCII 2CONSTANT \"DBL1\"\r\nDBL2 D>ASCII 2CONSTANT \"DBL2\"\r\n\r\n: DOUBLEOUTPUT\r\n CR .\" You should see lines duplicated:\" CR\r\n 5 SPACES \"DBL1\" TYPE CR\r\n 5 SPACES DBL1 D. CR\r\n 8 SPACES \"DBL1\" DUP >R TYPE CR\r\n 5 SPACES DBL1 R> 3 + D.R CR\r\n 5 SPACES \"DBL2\" TYPE CR\r\n 5 SPACES DBL2 D. CR\r\n 10 SPACES \"DBL2\" DUP >R TYPE CR\r\n 5 SPACES DBL2 R> 5 + D.R CR\r\n;\r\n\r\nT{ DOUBLEOUTPUT -> }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING 2ROT DU< (Double Number extension words)\r\n\r\nT{ 1. 2. 3. 2ROT -> 2. 3. 1. }T\r\nT{ MAX-2INT MIN-2INT 1. 2ROT -> MIN-2INT 1. MAX-2INT }T\r\n\r\nT{ 1. 1. DU< -> FALSE }T\r\nT{ 1. -1. DU< -> TRUE }T\r\nT{ -1. 1. DU< -> FALSE }T\r\nT{ -1. -2. DU< -> FALSE }T\r\n\r\nT{ MAX-2INT HI-2INT DU< -> FALSE }T\r\nT{ HI-2INT MAX-2INT DU< -> TRUE }T\r\nT{ MAX-2INT MIN-2INT DU< -> TRUE }T\r\nT{ MIN-2INT MAX-2INT DU< -> FALSE }T\r\nT{ MIN-2INT LO-2INT DU< -> TRUE }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING 2VALUE\r\n\r\nT{ 1111 2222 2VALUE 2VAL -> }T\r\nT{ 2VAL -> 1111 2222 }T\r\nT{ 3333 4444 TO 2VAL -> }T\r\nT{ 2VAL -> 3333 4444 }T\r\nT{ : TO-2VAL TO 2VAL ; 5555 6666 TO-2VAL -> }T\r\nT{ 2VAL -> 5555 6666 }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\n\r\nDOUBLE-ERRORS SET-ERROR-COUNT\r\n\r\nCR .( End of Double-Number word tests) CR\r\n\r\n","old_contents":"\\ To test the ANS Forth Double-Number word set and double number extensions\r\n\r\n\\ This program was written by Gerry Jackson in 2006, with contributions from\r\n\\ others where indicated, and is in the public domain - it can be distributed\r\n\\ and\/or modified in any way but please retain this notice.\r\n\r\n\\ This program is distributed in the hope that it will be useful,\r\n\\ but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n\\ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\r\n\r\n\\ The tests are not claimed to be comprehensive or correct \r\n\\ ------------------------------------------------------------------------------\r\n\\ Version 0.11 7 April 2015 2VALUE tested\r\n\\ 0.6 1 April 2012 Tests placed in the public domain.\r\n\\ Immediate 2CONSTANTs and 2VARIABLEs tested\r\n\\ 0.5 20 November 2009 Various constants renamed to avoid\r\n\\ redefinition warnings. and replaced\r\n\\ with TRUE and FALSE\r\n\\ 0.4 6 March 2009 { and } replaced with T{ and }T\r\n\\ Tests rewritten to be independent of word size and\r\n\\ tests re-ordered\r\n\\ 0.3 20 April 2007 ANS Forth words changed to upper case\r\n\\ 0.2 30 Oct 2006 Updated following GForth test to include\r\n\\ various constants from core.fr\r\n\\ 0.1 Oct 2006 First version released\r\n\\ ------------------------------------------------------------------------------\r\n\\ The tests are based on John Hayes test program for the core word set\r\n\r\n\\ Words tested in this file are:\r\n\\ 2CONSTANT 2LITERAL 2VARIABLE D+ D- D. D.R D0< D0= D2* D2\/\r\n\\ D< D= D>S DABS DMAX DMIN DNEGATE M*\/ M+ 2ROT DU<\r\n\\ Also tests the interpreter and compiler reading a double number\r\n\\ ------------------------------------------------------------------------------\r\n\\ Assumptions and dependencies:\r\n\\ - tester.fr or ttester.fs has been included prior to this file\r\n\\ - core words and core extension words have been tested\r\n\\ ------------------------------------------------------------------------------\r\n\\ Constant definitions\r\n\r\nDECIMAL\r\n0 INVERT CONSTANT 1SD\r\n1SD 1 RSHIFT CONSTANT MAX-INTD \\ 01...1\r\nMAX-INTD INVERT CONSTANT MIN-INTD \\ 10...0\r\nMAX-INTD 2\/ CONSTANT HI-INT \\ 001...1\r\nMIN-INTD 2\/ CONSTANT LO-INT \\ 110...1\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING interpreter and compiler reading a double number\r\n\r\nT{ 1. -> 1 0 }T\r\nT{ -2. -> -2 -1 }T\r\nT{ : RDL1 3. ; RDL1 -> 3 0 }T\r\nT{ : RDL2 -4. ; RDL2 -> -4 -1 }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING 2CONSTANT\r\n\r\nT{ 1 2 2CONSTANT 2C1 -> }T\r\nT{ 2C1 -> 1 2 }T\r\nT{ : CD1 2C1 ; -> }T\r\nT{ CD1 -> 1 2 }T\r\nT{ : CD2 2CONSTANT ; -> }T\r\nT{ -1 -2 CD2 2C2 -> }T\r\nT{ 2C2 -> -1 -2 }T\r\nT{ 4 5 2CONSTANT 2C3 IMMEDIATE 2C3 -> 4 5 }T\r\nT{ : CD6 2C3 2LITERAL ; CD6 -> 4 5 }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\n\\ Some 2CONSTANTs for the following tests\r\n\r\n1SD MAX-INTD 2CONSTANT MAX-2INT \\ 01...1\r\n0 MIN-INTD 2CONSTANT MIN-2INT \\ 10...0\r\nMAX-2INT 2\/ 2CONSTANT HI-2INT \\ 001...1\r\nMIN-2INT 2\/ 2CONSTANT LO-2INT \\ 110...0\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING DNEGATE\r\n\r\nT{ 0. DNEGATE -> 0. }T\r\nT{ 1. DNEGATE -> -1. }T\r\nT{ -1. DNEGATE -> 1. }T\r\nT{ MAX-2INT DNEGATE -> MIN-2INT SWAP 1+ SWAP }T\r\nT{ MIN-2INT SWAP 1+ SWAP DNEGATE -> MAX-2INT }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING D+ with small integers\r\n\r\nT{ 0. 5. D+ -> 5. }T\r\nT{ -5. 0. D+ -> -5. }T\r\nT{ 1. 2. D+ -> 3. }T\r\nT{ 1. -2. D+ -> -1. }T\r\nT{ -1. 2. D+ -> 1. }T\r\nT{ -1. -2. D+ -> -3. }T\r\nT{ -1. 1. D+ -> 0. }T\r\n\r\nTESTING D+ with mid range integers\r\n\r\nT{ 0 0 0 5 D+ -> 0 5 }T\r\nT{ -1 5 0 0 D+ -> -1 5 }T\r\nT{ 0 0 0 -5 D+ -> 0 -5 }T\r\nT{ 0 -5 -1 0 D+ -> -1 -5 }T\r\nT{ 0 1 0 2 D+ -> 0 3 }T\r\nT{ -1 1 0 -2 D+ -> -1 -1 }T\r\nT{ 0 -1 0 2 D+ -> 0 1 }T\r\nT{ 0 -1 -1 -2 D+ -> -1 -3 }T\r\nT{ -1 -1 0 1 D+ -> -1 0 }T\r\nT{ MIN-INTD 0 2DUP D+ -> 0 1 }T\r\nT{ MIN-INTD S>D MIN-INTD 0 D+ -> 0 0 }T\r\n\r\nTESTING D+ with large double integers\r\n\r\nT{ HI-2INT 1. D+ -> 0 HI-INT 1+ }T\r\nT{ HI-2INT 2DUP D+ -> 1SD 1- MAX-INTD }T\r\nT{ MAX-2INT MIN-2INT D+ -> -1. }T\r\nT{ MAX-2INT LO-2INT D+ -> HI-2INT }T\r\nT{ HI-2INT MIN-2INT D+ 1. D+ -> LO-2INT }T\r\nT{ LO-2INT 2DUP D+ -> MIN-2INT }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING D- with small integers\r\n\r\nT{ 0. 5. D- -> -5. }T\r\nT{ 5. 0. D- -> 5. }T\r\nT{ 0. -5. D- -> 5. }T\r\nT{ 1. 2. D- -> -1. }T\r\nT{ 1. -2. D- -> 3. }T\r\nT{ -1. 2. D- -> -3. }T\r\nT{ -1. -2. D- -> 1. }T\r\nT{ -1. -1. D- -> 0. }T\r\n\r\nTESTING D- with mid-range integers\r\n\r\nT{ 0 0 0 5 D- -> 0 -5 }T\r\nT{ -1 5 0 0 D- -> -1 5 }T\r\nT{ 0 0 -1 -5 D- -> 1 4 }T\r\nT{ 0 -5 0 0 D- -> 0 -5 }T\r\nT{ -1 1 0 2 D- -> -1 -1 }T\r\nT{ 0 1 -1 -2 D- -> 1 2 }T\r\nT{ 0 -1 0 2 D- -> 0 -3 }T\r\nT{ 0 -1 0 -2 D- -> 0 1 }T\r\nT{ 0 0 0 1 D- -> 0 -1 }T\r\nT{ MIN-INTD 0 2DUP D- -> 0. }T\r\nT{ MIN-INTD S>D MAX-INTD 0 D- -> 1 1SD }T\r\n\r\nTESTING D- with large integers\r\n\r\nT{ MAX-2INT MAX-2INT D- -> 0. }T\r\nT{ MIN-2INT MIN-2INT D- -> 0. }T\r\nT{ MAX-2INT HI-2INT D- -> LO-2INT DNEGATE }T\r\nT{ HI-2INT LO-2INT D- -> MAX-2INT }T\r\nT{ LO-2INT HI-2INT D- -> MIN-2INT 1. D+ }T\r\nT{ MIN-2INT MIN-2INT D- -> 0. }T\r\nT{ MIN-2INT LO-2INT D- -> LO-2INT }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING D0< D0=\r\n\r\nT{ 0. D0< -> FALSE }T\r\nT{ 1. D0< -> FALSE }T\r\nT{ MIN-INTD 0 D0< -> FALSE }T\r\nT{ 0 MAX-INTD D0< -> FALSE }T\r\nT{ MAX-2INT D0< -> FALSE }T\r\nT{ -1. D0< -> TRUE }T\r\nT{ MIN-2INT D0< -> TRUE }T\r\n\r\nT{ 1. D0= -> FALSE }T\r\nT{ MIN-INTD 0 D0= -> FALSE }T\r\nT{ MAX-2INT D0= -> FALSE }T\r\nT{ -1 MAX-INTD D0= -> FALSE }T\r\nT{ 0. D0= -> TRUE }T\r\nT{ -1. D0= -> FALSE }T\r\nT{ 0 MIN-INTD D0= -> FALSE }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING D2* D2\/\r\n\r\nT{ 0. D2* -> 0. D2* }T\r\nT{ MIN-INTD 0 D2* -> 0 1 }T\r\nT{ HI-2INT D2* -> MAX-2INT 1. D- }T\r\nT{ LO-2INT D2* -> MIN-2INT }T\r\n\r\nT{ 0. D2\/ -> 0. }T\r\nT{ 1. D2\/ -> 0. }T\r\nT{ 0 1 D2\/ -> MIN-INTD 0 }T\r\nT{ MAX-2INT D2\/ -> HI-2INT }T\r\nT{ -1. D2\/ -> -1. }T\r\nT{ MIN-2INT D2\/ -> LO-2INT }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING D< D=\r\n\r\nT{ 0. 1. D< -> TRUE }T\r\nT{ 0. 0. D< -> FALSE }T\r\nT{ 1. 0. D< -> FALSE }T\r\nT{ -1. 1. D< -> TRUE }T\r\nT{ -1. 0. D< -> TRUE }T\r\nT{ -2. -1. D< -> TRUE }T\r\nT{ -1. -2. D< -> FALSE }T\r\nT{ -1. MAX-2INT D< -> TRUE }T\r\nT{ MIN-2INT MAX-2INT D< -> TRUE }T\r\nT{ MAX-2INT -1. D< -> FALSE }T\r\nT{ MAX-2INT MIN-2INT D< -> FALSE }T\r\nT{ MAX-2INT 2DUP -1. D+ D< -> FALSE }T\r\nT{ MIN-2INT 2DUP 1. D+ D< -> TRUE }T\r\n\r\nT{ -1. -1. D= -> TRUE }T\r\nT{ -1. 0. D= -> FALSE }T\r\nT{ -1. 1. D= -> FALSE }T\r\nT{ 0. -1. D= -> FALSE }T\r\nT{ 0. 0. D= -> TRUE }T\r\nT{ 0. 1. D= -> FALSE }T\r\nT{ 1. -1. D= -> FALSE }T\r\nT{ 1. 0. D= -> FALSE }T\r\nT{ 1. 1. D= -> TRUE }T\r\n\r\nT{ 0 -1 0 -1 D= -> TRUE }T\r\nT{ 0 -1 0 0 D= -> FALSE }T\r\nT{ 0 -1 0 1 D= -> FALSE }T\r\nT{ 0 0 0 -1 D= -> FALSE }T\r\nT{ 0 0 0 0 D= -> TRUE }T\r\nT{ 0 0 0 1 D= -> FALSE }T\r\nT{ 0 1 0 -1 D= -> FALSE }T\r\nT{ 0 1 0 0 D= -> FALSE }T\r\nT{ 0 1 0 1 D= -> TRUE }T\r\n\r\nT{ MAX-2INT MIN-2INT D= -> FALSE }T\r\nT{ MAX-2INT 0. D= -> FALSE }T\r\nT{ MAX-2INT MAX-2INT D= -> TRUE }T\r\nT{ MAX-2INT HI-2INT D= -> FALSE }T\r\nT{ MAX-2INT MIN-2INT D= -> FALSE }T\r\nT{ MIN-2INT MIN-2INT D= -> TRUE }T\r\nT{ MIN-2INT LO-2INT D= -> FALSE }T\r\nT{ MIN-2INT MAX-2INT D= -> FALSE }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING 2LITERAL 2VARIABLE\r\n\r\nT{ : CD3 [ MAX-2INT ] 2LITERAL ; -> }T\r\nT{ CD3 -> MAX-2INT }T\r\nT{ 2VARIABLE 2V1 -> }T\r\nT{ 0. 2V1 2! -> }T\r\nT{ 2V1 2@ -> 0. }T\r\nT{ -1 -2 2V1 2! -> }T\r\nT{ 2V1 2@ -> -1 -2 }T\r\nT{ : CD4 2VARIABLE ; -> }T\r\nT{ CD4 2V2 -> }T\r\nT{ : CD5 2V2 2! ; -> }T\r\nT{ -2 -1 CD5 -> }T\r\nT{ 2V2 2@ -> -2 -1 }T\r\nT{ 2VARIABLE 2V3 IMMEDIATE 5 6 2V3 2! -> }T\r\nT{ 2V3 2@ -> 5 6 }T\r\nT{ : CD7 2V3 [ 2@ ] 2LITERAL ; CD7 -> 5 6 }T\r\nT{ : CD8 [ 6 7 ] 2V3 [ 2! ] ; 2V3 2@ -> 6 7 }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING DMAX DMIN\r\n\r\nT{ 1. 2. DMAX -> 2. }T\r\nT{ 1. 0. DMAX -> 1. }T\r\nT{ 1. -1. DMAX -> 1. }T\r\nT{ 1. 1. DMAX -> 1. }T\r\nT{ 0. 1. DMAX -> 1. }T\r\nT{ 0. -1. DMAX -> 0. }T\r\nT{ -1. 1. DMAX -> 1. }T\r\nT{ -1. -2. DMAX -> -1. }T\r\n\r\nT{ MAX-2INT HI-2INT DMAX -> MAX-2INT }T\r\nT{ MAX-2INT MIN-2INT DMAX -> MAX-2INT }T\r\nT{ MIN-2INT MAX-2INT DMAX -> MAX-2INT }T\r\nT{ MIN-2INT LO-2INT DMAX -> LO-2INT }T\r\n\r\nT{ MAX-2INT 1. DMAX -> MAX-2INT }T\r\nT{ MAX-2INT -1. DMAX -> MAX-2INT }T\r\nT{ MIN-2INT 1. DMAX -> 1. }T\r\nT{ MIN-2INT -1. DMAX -> -1. }T\r\n\r\n\r\nT{ 1. 2. DMIN -> 1. }T\r\nT{ 1. 0. DMIN -> 0. }T\r\nT{ 1. -1. DMIN -> -1. }T\r\nT{ 1. 1. DMIN -> 1. }T\r\nT{ 0. 1. DMIN -> 0. }T\r\nT{ 0. -1. DMIN -> -1. }T\r\nT{ -1. 1. DMIN -> -1. }T\r\nT{ -1. -2. DMIN -> -2. }T\r\n\r\nT{ MAX-2INT HI-2INT DMIN -> HI-2INT }T\r\nT{ MAX-2INT MIN-2INT DMIN -> MIN-2INT }T\r\nT{ MIN-2INT MAX-2INT DMIN -> MIN-2INT }T\r\nT{ MIN-2INT LO-2INT DMIN -> MIN-2INT }T\r\n\r\nT{ MAX-2INT 1. DMIN -> 1. }T\r\nT{ MAX-2INT -1. DMIN -> -1. }T\r\nT{ MIN-2INT 1. DMIN -> MIN-2INT }T\r\nT{ MIN-2INT -1. DMIN -> MIN-2INT }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING D>S DABS\r\n\r\nT{ 1234 0 D>S -> 1234 }T\r\nT{ -1234 -1 D>S -> -1234 }T\r\nT{ MAX-INTD 0 D>S -> MAX-INTD }T\r\nT{ MIN-INTD -1 D>S -> MIN-INTD }T\r\n\r\nT{ 1. DABS -> 1. }T\r\nT{ -1. DABS -> 1. }T\r\nT{ MAX-2INT DABS -> MAX-2INT }T\r\nT{ MIN-2INT 1. D+ DABS -> MAX-2INT }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING M+ M*\/\r\n\r\nT{ HI-2INT 1 M+ -> HI-2INT 1. D+ }T\r\nT{ MAX-2INT -1 M+ -> MAX-2INT -1. D+ }T\r\nT{ MIN-2INT 1 M+ -> MIN-2INT 1. D+ }T\r\nT{ LO-2INT -1 M+ -> LO-2INT -1. D+ }T\r\n\r\n\\ To correct the result if the division is floored, only used when\r\n\\ necessary i.e. negative quotient and remainder <> 0\r\n\r\n: ?FLOORED [ -3 2 \/ -2 = ] LITERAL IF 1. D- THEN ;\r\n\r\nT{ 5. 7 11 M*\/ -> 3. }T\r\nT{ 5. -7 11 M*\/ -> -3. ?FLOORED }T \\ FLOORED -4.\r\nT{ -5. 7 11 M*\/ -> -3. ?FLOORED }T \\ FLOORED -4.\r\nT{ -5. -7 11 M*\/ -> 3. }T\r\nT{ MAX-2INT 8 16 M*\/ -> HI-2INT }T\r\nT{ MAX-2INT -8 16 M*\/ -> HI-2INT DNEGATE ?FLOORED }T \\ FLOORED SUBTRACT 1\r\nT{ MIN-2INT 8 16 M*\/ -> LO-2INT }T\r\nT{ MIN-2INT -8 16 M*\/ -> LO-2INT DNEGATE }T\r\nT{ MAX-2INT MAX-INTD MAX-INTD M*\/ -> MAX-2INT }T\r\nT{ MAX-2INT MAX-INTD 2\/ MAX-INTD M*\/ -> MAX-INTD 1- HI-2INT NIP }T\r\nT{ MIN-2INT LO-2INT NIP DUP NEGATE M*\/ -> MIN-2INT }T\r\nT{ MIN-2INT LO-2INT NIP 1- MAX-INTD M*\/ -> MIN-INTD 3 + HI-2INT NIP 2 + }T\r\nT{ MAX-2INT LO-2INT NIP DUP NEGATE M*\/ -> MAX-2INT DNEGATE }T\r\nT{ MIN-2INT MAX-INTD DUP M*\/ -> MIN-2INT }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING D. D.R\r\n\r\n\\ Create some large double numbers\r\nMAX-2INT 71 73 M*\/ 2CONSTANT DBL1\r\nMIN-2INT 73 79 M*\/ 2CONSTANT DBL2\r\n\r\n: D>ASCII ( D -- CADDR U )\r\n DUP >R <# DABS #S R> SIGN #> ( -- CADDR1 U )\r\n HERE SWAP 2DUP 2>R CHARS DUP ALLOT MOVE 2R>\r\n;\r\n\r\nDBL1 D>ASCII 2CONSTANT \"DBL1\"\r\nDBL2 D>ASCII 2CONSTANT \"DBL2\"\r\n\r\n: DOUBLEOUTPUT\r\n CR .\" You should see lines duplicated:\" CR\r\n 5 SPACES \"DBL1\" TYPE CR\r\n 5 SPACES DBL1 D. CR\r\n 8 SPACES \"DBL1\" DUP >R TYPE CR\r\n 5 SPACES DBL1 R> 3 + D.R CR\r\n 5 SPACES \"DBL2\" TYPE CR\r\n 5 SPACES DBL2 D. CR\r\n 10 SPACES \"DBL2\" DUP >R TYPE CR\r\n 5 SPACES DBL2 R> 5 + D.R CR\r\n;\r\n\r\nT{ DOUBLEOUTPUT -> }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING 2ROT DU< (Double Number extension words)\r\n\r\nT{ 1. 2. 3. 2ROT -> 2. 3. 1. }T\r\nT{ MAX-2INT MIN-2INT 1. 2ROT -> MIN-2INT 1. MAX-2INT }T\r\n\r\nT{ 1. 1. DU< -> FALSE }T\r\nT{ 1. -1. DU< -> TRUE }T\r\nT{ -1. 1. DU< -> FALSE }T\r\nT{ -1. -2. DU< -> FALSE }T\r\n\r\nT{ MAX-2INT HI-2INT DU< -> FALSE }T\r\nT{ HI-2INT MAX-2INT DU< -> TRUE }T\r\nT{ MAX-2INT MIN-2INT DU< -> TRUE }T\r\nT{ MIN-2INT MAX-2INT DU< -> FALSE }T\r\nT{ MIN-2INT LO-2INT DU< -> TRUE }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\nTESTING 2VALUE\r\n\r\nT{ 1111 2222 2VALUE 2VAL -> }T\r\nT{ 2VAL -> 1111 2222 }T\r\nT{ 3333 4444 TO 2VAL -> }T\r\nT{ 2VAL -> 3333 4444 }T\r\nT{ : TO-2VAL TO 2VAL ; 5555 6666 TO-2VAL -> }T\r\nT{ 2VAL -> 5555 6666 }T\r\n\r\n\\ ------------------------------------------------------------------------------\r\n\r\nDOUBLE-ERRORS SET-ERROR-COUNT\r\n\r\nCR .( End of Double-Number word tests) CR\r\n\r\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"5790a5b093d8bbd36e9dac4c0d6e54587e3422e6","subject":"Update copyright.","message":"Update copyright.\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/version.4th","new_file":"sys\/boot\/forth\/version.4th","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"bsd-3-clause","lang":"Forth"} {"commit":"169b92afacb6e591278924496668692ead8fd227","subject":"Remove ELF check. It is broken and since the PROM checks the loaded executable anyway, it's not worth fixing. Bump version number.","message":"Remove ELF check. It is broken and since the PROM checks the loaded executable\nanyway, it's not worth fixing. Bump version number.\n\nok deraadt@\n","repos":"orumin\/openbsd-efivars,orumin\/openbsd-efivars,orumin\/openbsd-efivars,orumin\/openbsd-efivars","old_file":"arch\/sparc64\/stand\/bootblk\/bootblk.fth","new_file":"arch\/sparc64\/stand\/bootblk\/bootblk.fth","new_contents":"\\\t$OpenBSD: bootblk.fth,v 1.7 2010\/02\/27 22:23:16 kettenis Exp $\n\\\t$NetBSD: bootblk.fth,v 1.3 2001\/08\/15 20:10:24 eeh Exp $\n\\\n\\\tIEEE 1275 Open Firmware Boot Block\n\\\n\\\tParses disklabel and UFS and loads the file called `ofwboot'\n\\\n\\\n\\\tCopyright (c) 1998 Eduardo Horvath.\n\\\tAll rights reserved.\n\\\n\\\tRedistribution and use in source and binary forms, with or without\n\\\tmodification, are permitted provided that the following conditions\n\\\tare met:\n\\\t1. Redistributions of source code must retain the above copyright\n\\\t notice, this list of conditions and the following disclaimer.\n\\\t2. Redistributions in binary form must reproduce the above copyright\n\\\t notice, this list of conditions and the following disclaimer in the\n\\\t documentation and\/or other materials provided with the distribution.\n\\\t3. All advertising materials mentioning features or use of this software\n\\\t must display the following acknowledgement:\n\\\t This product includes software developed by Eduardo Horvath.\n\\\t4. The name of the author may not be used to endorse or promote products\n\\\t derived from this software without specific prior written permission\n\\\n\\\tTHIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n\\\tIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n\\\tOF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n\\\tIN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n\\\tINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n\\\tNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\\\tDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\\\tTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\\\t(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n\\\tTHIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\\\n\noffset16\nhex\nheaders\n\nfalse value boot-debug?\n\n\\\n\\ First some housekeeping: Open \/chosen and set up vectors into\n\\\tclient-services\n\n\" \/chosen\" find-package 0= if .\" Cannot find \/chosen\" 0 then\nconstant chosen-phandle\n\n\" \/openprom\/client-services\" find-package 0= if \n\t.\" Cannot find client-services\" cr abort\nthen constant cif-phandle\n\ndefer cif-claim ( align size virt -- base )\ndefer cif-release ( size virt -- )\ndefer cif-open ( cstr -- ihandle|0 )\ndefer cif-close ( ihandle -- )\ndefer cif-read ( len adr ihandle -- #read )\ndefer cif-seek ( low high ihandle -- -1|0|1 )\n\\ defer cif-peer ( phandle -- phandle )\n\\ defer cif-getprop ( len adr cstr phandle -- )\n\n: find-cif-method ( method,len -- xf )\n cif-phandle find-method drop \n;\n\n\" claim\" find-cif-method to cif-claim\n\" open\" find-cif-method to cif-open\n\" close\" find-cif-method to cif-close\n\" read\" find-cif-method to cif-read\n\" seek\" find-cif-method to cif-seek\n\n: twiddle ( -- ) .\" .\" ; \\ Need to do this right. Just spit out periods for now.\n\n\\\n\\ Support routines\n\\\n\n: strcmp ( s1 l1 s2 l2 -- true:false )\n rot tuck <> if 3drop false exit then\n comp 0=\n;\n\n\\ Move string into buffer\n\n: strmov ( s1 l1 d -- d l1 )\n dup 2over swap -rot\t\t( s1 l1 d s1 d l1 )\n move\t\t\t\t( s1 l1 d )\n rot drop swap\n;\n\n\\ Move s1 on the end of s2 and return the result\n\n: strcat ( s1 l1 s2 l2 -- d tot )\n 2over swap \t\t\t\t( s1 l1 s2 l2 l1 s1 )\n 2over + rot\t\t\t\t( s1 l1 s2 l2 s1 d l1 )\n move rot + \t\t\t\t( s1 s2 len )\n rot drop\t\t\t\t( s2 len )\n;\n\n: strchr ( s1 l1 c -- s2 l2 )\n begin\n dup 2over 0= if\t\t\t( s1 l1 c c s1 )\n 2drop drop exit then\n c@ = if\t\t\t\t( s1 l1 c )\n drop exit then\n -rot \/c - swap ca1+\t\t( c l2 s2 )\n swap rot\n again\n;\n\n \n: cstr ( ptr -- str len )\n dup \n begin dup c@ 0<> while + repeat\n over -\n;\n\n\\\n\\ BSD FFS parameters\n\\\n\nfload\tassym.fth.h\n\nsbsize buffer: sb-buf\n-1 value boot-ihandle\ndev_bsize value bsize\n0 value raid-offset\t\\ Offset if it's a raid-frame partition\n\n: strategy ( addr size start -- nread )\n raid-offset + bsize * 0 \" seek\" boot-ihandle $call-method\n -1 = if \n .\" strategy: Seek failed\" cr\n abort\n then\n \" read\" boot-ihandle $call-method\n;\n\n\\\n\\ Cylinder group macros\n\\\n\n: cgbase ( cg fs -- cgbase ) fs_fpg l@ * ;\n: cgstart ( cg fs -- cgstart ) \n 2dup fs_cgmask l@ not and\t\t( cg fs stuff -- )\n over fs_cgoffset l@ * -rot\t\t( stuffcg fs -- )\n cgbase +\n;\n: cgdmin ( cg fs -- 1st-data-block ) dup fs_dblkno l@ -rot cgstart + ;\n: cgimin ( cg fs -- inode-block ) dup fs_iblkno l@ -rot cgstart + ;\n: cgsblock ( cg fs -- super-block ) dup fs_sblkno l@ -rot cgstart + ;\n: cgstod ( cg fs -- cg-block ) dup fs_cblkno l@ -rot cgstart + ;\n\n\\\n\\ Block and frag position macros\n\\\n\n: blkoff ( pos fs -- off ) fs_qbmask x@ and ;\n: fragoff ( pos fs -- off ) fs_qfmask x@ and ;\n: lblktosize ( blk fs -- off ) fs_bshift l@ << ;\n: lblkno ( pos fs -- off ) fs_bshift l@ >> ;\n: numfrags ( pos fs -- off ) fs_fshift l@ >> ;\n: blkroundup ( pos fs -- off ) dup fs_bmask l@ -rot fs_qbmask x@ + and ;\n: fragroundup ( pos fs -- off ) dup fs_fmask l@ -rot fs_qfmask x@ + and ;\n\\ : fragroundup ( pos fs -- off ) tuck fs_qfmask x@ + swap fs_fmask l@ and ;\n: fragstoblks ( pos fs -- off ) fs_fragshift l@ >> ;\n: blkstofrags ( blk fs -- frag ) fs_fragshift l@ << ;\n: fragnum ( fsb fs -- off ) fs_frag l@ 1- and ;\n: blknum ( fsb fs -- off ) fs_frag l@ 1- not and ;\n: dblksize ( lbn dino fs -- size )\n -rot \t\t\t\t( fs lbn dino )\n di_size x@\t\t\t\t( fs lbn di_size )\n -rot dup 1+\t\t\t\t( di_size fs lbn lbn+1 )\n 2over fs_bshift l@\t\t\t( di_size fs lbn lbn+1 di_size b_shift )\n rot swap <<\t>=\t\t\t( di_size fs lbn res1 )\n swap ndaddr >= or if\t\t\t( di_size fs )\n swap drop fs_bsize l@ exit\t( size )\n then\ttuck blkoff swap fragroundup\t( size )\n;\n\n\n: ino-to-cg ( ino fs -- cg ) fs_ipg l@ \/ ;\n: ino-to-fsbo ( ino fs -- fsb0 ) fs_inopb l@ mod ;\n: ino-to-fsba ( ino fs -- ba )\t\\ Need to remove the stupid stack diags someday\n 2dup \t\t\t\t( ino fs ino fs )\n ino-to-cg\t\t\t\t( ino fs cg )\n over\t\t\t\t\t( ino fs cg fs )\n cgimin\t\t\t\t( ino fs inode-blk )\n -rot\t\t\t\t\t( inode-blk ino fs )\n tuck \t\t\t\t( inode-blk fs ino fs )\n fs_ipg l@ \t\t\t\t( inode-blk fs ino ipg )\n mod\t\t\t\t\t( inode-blk fs mod )\n swap\t\t\t\t\t( inode-blk mod fs )\n dup \t\t\t\t\t( inode-blk mod fs fs )\n fs_inopb l@ \t\t\t\t( inode-blk mod fs inopb )\n rot \t\t\t\t\t( inode-blk fs inopb mod )\n swap\t\t\t\t\t( inode-blk fs mod inopb )\n \/\t\t\t\t\t( inode-blk fs div )\n swap\t\t\t\t\t( inode-blk div fs )\n blkstofrags\t\t\t\t( inode-blk frag )\n +\n;\n: fsbtodb ( fsb fs -- db ) fs_fsbtodb l@ << ;\n\n\\\n\\ File stuff\n\\\n\nniaddr \/w* constant narraysize\n\nstruct \n 8\t\tfield\t>f_ihandle\t\\ device handle\n 8 \t\tfield \t>f_seekp\t\\ seek pointer\n 8 \t\tfield \t>f_fs\t\t\\ pointer to super block\n ufs1_dinode_SIZEOF \tfield \t>f_di\t\\ copy of on-disk inode\n 8\t\tfield\t>f_buf\t\t\\ buffer for data block\n 4\t\tfield \t>f_buf_size\t\\ size of data block\n 4\t\tfield\t>f_buf_blkno\t\\ block number of data block\nconstant file_SIZEOF\n\nfile_SIZEOF buffer: the-file\nsb-buf the-file >f_fs x!\n\nufs1_dinode_SIZEOF buffer: cur-inode\nh# 2000 buffer: indir-block\n-1 value indir-addr\n\n\\\n\\ Translate a fileblock to a disk block\n\\\n\\ We only allow single indirection\n\\\n\n: block-map ( fileblock -- diskblock )\n \\ Direct block?\n dup ndaddr < if \t\t\t( fileblock )\n cur-inode di_db\t\t\t( arr-indx arr-start )\n swap la+ l@ exit\t\t\t( diskblock )\n then \t\t\t\t( fileblock )\n ndaddr -\t\t\t\t( fileblock' )\n \\ Now we need to check the indirect block\n dup sb-buf fs_nindir l@ < if\t( fileblock' )\n cur-inode di_ib l@ dup\t\t( fileblock' indir-block indir-block )\n indir-addr <> if \t\t( fileblock' indir-block )\n to indir-addr\t\t\t( fileblock' )\n indir-block \t\t\t( fileblock' indir-block )\n sb-buf dup fs_bsize l@\t\t( fileblock' indir-block fs fs_bsize )\n swap indir-addr swap\t\t( fileblock' indir-block fs_bsize indiraddr fs )\n fsbtodb \t\t\t( fileblock' indir-block fs_bsize db )\n strategy\t\t\t( fileblock' nread )\n then\t\t\t\t( fileblock' nread|indir-block )\n drop \\ Really should check return value\n indir-block swap la+ l@ exit\n then\n dup sb-buf fs_nindir -\t\t( fileblock'' )\n \\ Now try 2nd level indirect block -- just read twice \n dup sb-buf fs_nindir l@ dup * < if\t( fileblock'' )\n cur-inode di_ib 1 la+ l@\t\t( fileblock'' indir2-block )\n to indir-addr\t\t\t( fileblock'' )\n \\ load 1st level indir block \n indir-block \t\t\t( fileblock'' indir-block )\n sb-buf dup fs_bsize l@\t\t( fileblock'' indir-block fs fs_bsize )\n swap indir-addr swap\t\t( fileblock'' indir-block fs_bsize indiraddr fs )\n fsbtodb \t\t\t\t( fileblock'' indir-block fs_bsize db )\n strategy\t\t\t\t( fileblock'' nread )\n drop\t\t\t\t( fileblock'' )\n dup sb-buf fs_nindir \/\t\t( fileblock'' indir-offset )\n indir-block swap la+ l@\t\t( fileblock'' indirblock )\n to indir-addr\t\t\t( fileblock'' )\n \\ load 2nd level indir block\n indir-block \t\t\t( fileblock'' indir-block )\n sb-buf dup fs_bsize l@\t\t( fileblock'' indir-block fs fs_bsize )\n swap indir-addr swap\t\t( fileblock'' indir-block fs_bsize indiraddr fs )\n fsbtodb \t\t\t\t( fileblock'' indir-block fs_bsize db )\n strategy\t\t\t\t( fileblock'' nread )\n drop\t\t\t\t( fileblock'' )\n sb-buf fs_nindir l@ mod indir-block swap la+ l@ exit\n then\n .\" block-map: exceeded max file size\" cr\n abort\n;\n\n\\\n\\ Read file into internal buffer and return pointer and len\n\\\n\n0 value cur-block\t\t\t\\ allocated dynamically in ufs-open\n0 value cur-blocksize\t\t\t\\ size of cur-block\n-1 value cur-blockno\n0 value cur-offset\n\n: buf-read-file ( fs -- len buf )\n cur-offset swap\t\t\t( seekp fs )\n 2dup blkoff\t\t\t\t( seekp fs off )\n -rot 2dup lblkno\t\t\t( off seekp fs block )\n swap 2dup cur-inode\t\t\t( off seekp block fs block fs inop )\n swap dblksize\t\t\t( off seekp block fs size )\n rot dup cur-blockno\t\t\t( off seekp fs size block block cur )\n <> if \t\t\t\t( off seekp fs size block )\n block-map\t\t\t\t( off seekp fs size diskblock )\n dup 0= if\t\t\t( off seekp fs size diskblock )\n over cur-block swap 0 fill\t( off seekp fs size diskblock )\n boot-debug? if .\" buf-read-file fell off end of file\" cr then\n else\n 2dup sb-buf fsbtodb cur-block -rot strategy\t( off seekp fs size diskblock nread )\n rot 2dup <> if \" buf-read-file: short read.\" cr abort then\n then\t\t\t\t( off seekp fs diskblock nread size )\n nip nip\t\t\t\t( off seekp fs size )\n else\t\t\t\t\t( off seekp fs size block block cur )\n 2drop\t\t\t\t( off seekp fs size )\n then\n\\ dup cur-offset + to cur-offset\t\\ Set up next xfer -- not done\n nip nip swap -\t\t\t( len )\n cur-block\n;\n\n\\\n\\ Read inode into cur-inode -- uses cur-block\n\\ \n\n: read-inode ( inode fs -- )\n twiddle\t\t\t\t( inode fs -- inode fs )\n\n cur-block\t\t\t\t( inode fs -- inode fs buffer )\n\n over\t\t\t\t\t( inode fs buffer -- inode fs buffer fs )\n fs_bsize l@\t\t\t\t( inode fs buffer -- inode fs buffer size )\n\n 2over\t\t\t\t( inode fs buffer size -- inode fs buffer size inode fs )\n 2over\t\t\t\t( inode fs buffer size inode fs -- inode fs buffer size inode fs buffer size )\n 2swap tuck\t\t\t\t( inode fs buffer size inode fs buffer size -- inode fs buffer size buffer size fs inode fs )\n\n ino-to-fsba \t\t\t\t( inode fs buffer size buffer size fs inode fs -- inode fs buffer size buffer size fs fsba )\n swap\t\t\t\t\t( inode fs buffer size buffer size fs fsba -- inode fs buffer size buffer size fsba fs )\n fsbtodb\t\t\t\t( inode fs buffer size buffer size fsba fs -- inode fs buffer size buffer size db )\n\n dup to cur-blockno\t\t\t( inode fs buffer size buffer size dstart -- inode fs buffer size buffer size dstart )\n strategy\t\t\t\t( inode fs buffer size buffer size dstart -- inode fs buffer size nread )\n <> if .\" read-inode - residual\" cr abort then\n dup 2over\t\t\t\t( inode fs buffer -- inode fs buffer buffer inode fs )\n ino-to-fsbo\t\t\t\t( inode fs buffer -- inode fs buffer buffer fsbo )\n ufs1_dinode_SIZEOF * +\t\t\t( inode fs buffer buffer fsbo -- inode fs buffer dinop )\n cur-inode ufs1_dinode_SIZEOF move \t( inode fs buffer dinop -- inode fs buffer )\n\t\\ clear out the old buffers\n drop\t\t\t\t\t( inode fs buffer -- inode fs )\n 2drop\n;\n\n\\ Identify inode type\n\n: is-dir? ( dinode -- true:false ) di_mode w@ ifmt and ifdir = ;\n: is-symlink? ( dinode -- true:false ) di_mode w@ ifmt and iflnk = ;\n\n\n\n\\\n\\ Hunt for directory entry:\n\\ \n\\ repeat\n\\ load a buffer\n\\ while entries do\n\\ if entry == name return\n\\ next entry\n\\ until no buffers\n\\\n\n: search-directory ( str len -- ino|0 )\n 0 to cur-offset\n begin cur-offset cur-inode di_size x@ < while\t( str len )\n sb-buf buf-read-file\t\t( str len len buf )\n over 0= if .\" search-directory: buf-read-file zero len\" cr abort then\n swap dup cur-offset + to cur-offset\t( str len buf len )\n 2dup + nip\t\t\t( str len buf bufend )\n swap 2swap rot\t\t\t( bufend str len buf )\n begin dup 4 pick < while\t\t( bufend str len buf )\n dup d_ino l@ 0<> if \t\t( bufend str len buf )\n boot-debug? if dup dup d_name swap d_namlen c@ type cr then\n 2dup d_namlen c@ = if\t( bufend str len buf )\n dup d_name 2over\t\t( bufend str len buf dname str len )\n comp 0= if\t\t( bufend str len buf )\n \\ Found it -- return inode\n d_ino l@ nip nip nip\t( dino )\n boot-debug? if .\" Found it\" cr then \n exit \t\t\t( dino )\n then\n then\t\t\t( bufend str len buf )\n then\t\t\t\t( bufend str len buf )\n dup d_reclen w@ +\t\t( bufend str len nextbuf )\n repeat\n drop rot drop\t\t\t( str len )\n repeat\n 2drop 2drop 0\t\t\t( 0 )\n;\n\n: ffs_oldcompat ( -- )\n\\ Make sure old ffs values in sb-buf are sane\n sb-buf fs_npsect dup l@ sb-buf fs_nsect l@ max swap l!\n sb-buf fs_interleave dup l@ 1 max swap l!\n sb-buf fs_postblformat l@ fs_42postblfmt = if\n 8 sb-buf fs_nrpos l!\n then\n sb-buf fs_inodefmt l@ fs_44inodefmt < if\n sb-buf fs_bsize l@ \n dup ndaddr * 1- sb-buf fs_maxfilesize x!\n niaddr 0 ?do\n\tsb-buf fs_nindir l@ * dup\t( sizebp sizebp -- )\n\tsb-buf fs_maxfilesize dup x@\t( sizebp sizebp *fs_maxfilesize fs_maxfilesize -- )\n\trot \t\t\t\t( sizebp *fs_maxfilesize fs_maxfilesize sizebp -- )\n\t+ \t\t\t\t( sizebp *fs_maxfilesize new_fs_maxfilesize -- ) \n swap x! \t\t\t( sizebp -- )\n loop drop \t\t\t( -- )\n sb-buf dup fs_bmask l@ not swap fs_qbmask x!\n sb-buf dup fs_fmask l@ not swap fs_qfmask x!\n then\n;\n\n: read-super ( sector -- )\n0 \" seek\" boot-ihandle $call-method\n -1 = if \n .\" Seek failed\" cr\n abort\n then\n sb-buf sbsize \" read\" boot-ihandle $call-method\n dup sbsize <> if\n .\" Read of superblock failed\" cr\n .\" requested\" space sbsize .\n .\" actual\" space . cr\n abort\n else \n drop\n then\n;\n\n: ufs-open ( bootpath,len -- )\n boot-ihandle -1 = if\n over cif-open dup 0= if \t\t( boot-path len ihandle? )\n .\" Could not open device\" space type cr \n abort\n then \t\t\t\t( boot-path len ihandle )\n to boot-ihandle\t\t\t\\ Save ihandle to boot device\n then 2drop\n sboff read-super\n sb-buf fs_magic l@ fs_magic_value <> if\n 64 dup to raid-offset \n dev_bsize * sboff + read-super\n sb-buf fs_magic l@ fs_magic_value <> if\n .\" Invalid superblock magic\" cr\n abort\n then\n then\n sb-buf fs_bsize l@ dup maxbsize > if\n .\" Superblock bsize\" space . .\" too large\" cr\n abort\n then \n dup fs_SIZEOF < if\n .\" Superblock bsize < size of superblock\" cr\n abort\n then\n ffs_oldcompat\t( fs_bsize -- fs_bsize )\n dup to cur-blocksize alloc-mem to cur-block \\ Allocate cur-block\n boot-debug? if .\" ufs-open complete\" cr then\n;\n\n: ufs-close ( -- ) \n boot-ihandle dup -1 <> if\n cif-close -1 to boot-ihandle \n then\n cur-block 0<> if\n cur-block cur-blocksize free-mem\n then\n;\n\n: boot-path ( -- boot-path )\n \" bootpath\" chosen-phandle get-package-property if\n .\" Could not find bootpath in \/chosen\" cr\n abort\n else\n decode-string 2swap 2drop\n then\n;\n\n: boot-args ( -- boot-args )\n \" bootargs\" chosen-phandle get-package-property if\n .\" Could not find bootargs in \/chosen\" cr\n abort\n else\n decode-string 2swap 2drop\n then\n;\n\n2000 buffer: boot-path-str\n2000 buffer: boot-path-tmp\n\n: split-path ( path len -- right len left len )\n\\ Split a string at the `\/'\n begin\n dup -rot\t\t\t\t( oldlen right len left )\n ascii \/ left-parse-string\t\t( oldlen right len left len )\n dup 0<> if 4 roll drop exit then\n 2drop\t\t\t\t( oldlen right len )\n rot over =\t\t\t( right len diff )\n until\n;\n\n: find-file ( load-file len -- )\n rootino dup sb-buf read-inode\t( load-file len -- load-file len ino )\n -rot\t\t\t\t\t( load-file len ino -- pino load-file len )\n \\\n \\ For each path component\n \\ \n begin split-path dup 0<> while\t( pino right len left len -- )\n cur-inode is-dir? not if .\" Inode not directory\" cr abort then\n boot-debug? if .\" Looking for\" space 2dup type space .\" in directory...\" cr then\n search-directory\t\t\t( pino right len left len -- pino right len ino|false )\n dup 0= if .\" Bad path\" cr abort then\t( pino right len cino )\n sb-buf read-inode\t\t\t( pino right len )\n cur-inode is-symlink? if\t\t\\ Symlink -- follow the damn thing\n \\ Save path in boot-path-tmp\n boot-path-tmp strmov\t\t( pino new-right len )\n\n \\ Now deal with symlink\n cur-inode di_size x@\t\t( pino right len linklen )\n dup sb-buf fs_maxsymlinklen l@\t( pino right len linklen linklen maxlinklen )\n < if\t\t\t\t\\ Now join the link to the path\n cur-inode di_shortlink l@\t( pino right len linklen linkp )\n swap boot-path-str strmov\t( pino right len new-linkp linklen )\n else\t\t\t\t\\ Read file for symlink -- Ugh\n \\ Read link into boot-path-str\n boot-path-str dup sb-buf fs_bsize l@\n 0 block-map\t\t\t( pino right len linklen boot-path-str bsize blockno )\n strategy drop swap\t\t( pino right len boot-path-str linklen )\n then \t\t\t\t( pino right len linkp linklen )\n \\ Concatenate the two paths\n strcat\t\t\t\t( pino new-right newlen )\n swap dup c@ ascii \/ = if\t\\ go to root inode?\n rot drop rootino -rot\t( rino len right )\n then\n rot dup sb-buf read-inode\t( len right pino )\n -rot swap\t\t\t( pino right len )\n then\t\t\t\t( pino right len )\n repeat\n 2drop drop\n;\n\n: read-file ( size addr -- )\n \\ Read x bytes from a file to buffer\n begin over 0> while\n cur-offset cur-inode di_size x@ > if .\" read-file EOF exceeded\" cr abort then\n sb-buf buf-read-file\t\t( size addr len buf )\n over 2over drop swap\t\t( size addr len buf addr len )\n move\t\t\t\t( size addr len )\n dup cur-offset + to cur-offset\t( size len newaddr )\n tuck +\t\t\t\t( size len newaddr )\n -rot - swap\t\t\t( newaddr newsize )\n repeat\n 2drop\n;\n\n\\\n\\ According to the 1275 addendum for SPARC processors:\n\\ Default load-base is 0x4000. At least 0x8.0000 or\n\\ 512KB must be available at that address. \n\\\n\\ The Fcode bootblock can take up up to 8KB (O.K., 7.5KB) \n\\ so load programs at 0x4000 + 0x2000=> 0x6000\n\\\n\nh# 6000 constant loader-base\n\n\\\n\\ Finally we finish it all off\n\\\n\n: load-file-signon ( load-file len boot-path len -- load-file len boot-path len )\n .\" Loading file\" space 2over type cr .\" from device\" space 2dup type cr\n;\n\n: load-file-print-size ( size -- size )\n .\" Loading\" space dup . space .\" bytes of file...\" cr \n;\n\n: load-file ( load-file len boot-path len -- load-base )\n boot-debug? if load-file-signon then\n the-file file_SIZEOF 0 fill\t\t\\ Clear out file structure\n ufs-open \t\t\t\t( load-file len )\n find-file\t\t\t\t( )\n\n \\\n \\ Now we've found the file we should read it in in one big hunk\n \\\n\n cur-inode di_size x@\t\t\t( file-len )\n dup \" to file-size\" evaluate\t\t( file-len )\n boot-debug? if load-file-print-size then\n 0 to cur-offset\n loader-base\t\t\t\t( buf-len addr )\n 2dup read-file\t\t\t( buf-len addr )\n ufs-close\t\t\t\t( buf-len addr )\n\n \\ Luckily the prom should be able to handle ELF executables by itself\n\n nip\t\t\t\t\t( addr )\n;\n\n: do-boot ( bootfile -- )\n .\" OpenBSD IEEE 1275 Bootblock 1.3\" cr\n boot-path load-file ( -- load-base )\n dup 0<> if \" to load-base init-program\" evaluate then\n;\n\n\nboot-args ascii V strchr 0<> swap drop if\n true to boot-debug?\nthen\n\nboot-args ascii D strchr 0= swap drop if\n \" \/ofwboot\" do-boot\nthen exit\n\n\n","old_contents":"\\\t$OpenBSD: bootblk.fth,v 1.6 2010\/02\/26 23:03:50 deraadt Exp $\n\\\t$NetBSD: bootblk.fth,v 1.3 2001\/08\/15 20:10:24 eeh Exp $\n\\\n\\\tIEEE 1275 Open Firmware Boot Block\n\\\n\\\tParses disklabel and UFS and loads the file called `ofwboot'\n\\\n\\\n\\\tCopyright (c) 1998 Eduardo Horvath.\n\\\tAll rights reserved.\n\\\n\\\tRedistribution and use in source and binary forms, with or without\n\\\tmodification, are permitted provided that the following conditions\n\\\tare met:\n\\\t1. Redistributions of source code must retain the above copyright\n\\\t notice, this list of conditions and the following disclaimer.\n\\\t2. Redistributions in binary form must reproduce the above copyright\n\\\t notice, this list of conditions and the following disclaimer in the\n\\\t documentation and\/or other materials provided with the distribution.\n\\\t3. All advertising materials mentioning features or use of this software\n\\\t must display the following acknowledgement:\n\\\t This product includes software developed by Eduardo Horvath.\n\\\t4. The name of the author may not be used to endorse or promote products\n\\\t derived from this software without specific prior written permission\n\\\n\\\tTHIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n\\\tIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n\\\tOF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n\\\tIN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n\\\tINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n\\\tNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\\\tDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\\\tTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\\\t(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n\\\tTHIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\\\n\noffset16\nhex\nheaders\n\nfalse value boot-debug?\n\n\\\n\\ First some housekeeping: Open \/chosen and set up vectors into\n\\\tclient-services\n\n\" \/chosen\" find-package 0= if .\" Cannot find \/chosen\" 0 then\nconstant chosen-phandle\n\n\" \/openprom\/client-services\" find-package 0= if \n\t.\" Cannot find client-services\" cr abort\nthen constant cif-phandle\n\ndefer cif-claim ( align size virt -- base )\ndefer cif-release ( size virt -- )\ndefer cif-open ( cstr -- ihandle|0 )\ndefer cif-close ( ihandle -- )\ndefer cif-read ( len adr ihandle -- #read )\ndefer cif-seek ( low high ihandle -- -1|0|1 )\n\\ defer cif-peer ( phandle -- phandle )\n\\ defer cif-getprop ( len adr cstr phandle -- )\n\n: find-cif-method ( method,len -- xf )\n cif-phandle find-method drop \n;\n\n\" claim\" find-cif-method to cif-claim\n\" open\" find-cif-method to cif-open\n\" close\" find-cif-method to cif-close\n\" read\" find-cif-method to cif-read\n\" seek\" find-cif-method to cif-seek\n\n: twiddle ( -- ) .\" .\" ; \\ Need to do this right. Just spit out periods for now.\n\n\\\n\\ Support routines\n\\\n\n: strcmp ( s1 l1 s2 l2 -- true:false )\n rot tuck <> if 3drop false exit then\n comp 0=\n;\n\n\\ Move string into buffer\n\n: strmov ( s1 l1 d -- d l1 )\n dup 2over swap -rot\t\t( s1 l1 d s1 d l1 )\n move\t\t\t\t( s1 l1 d )\n rot drop swap\n;\n\n\\ Move s1 on the end of s2 and return the result\n\n: strcat ( s1 l1 s2 l2 -- d tot )\n 2over swap \t\t\t\t( s1 l1 s2 l2 l1 s1 )\n 2over + rot\t\t\t\t( s1 l1 s2 l2 s1 d l1 )\n move rot + \t\t\t\t( s1 s2 len )\n rot drop\t\t\t\t( s2 len )\n;\n\n: strchr ( s1 l1 c -- s2 l2 )\n begin\n dup 2over 0= if\t\t\t( s1 l1 c c s1 )\n 2drop drop exit then\n c@ = if\t\t\t\t( s1 l1 c )\n drop exit then\n -rot \/c - swap ca1+\t\t( c l2 s2 )\n swap rot\n again\n;\n\n \n: cstr ( ptr -- str len )\n dup \n begin dup c@ 0<> while + repeat\n over -\n;\n\n\\\n\\ BSD FFS parameters\n\\\n\nfload\tassym.fth.h\n\nsbsize buffer: sb-buf\n-1 value boot-ihandle\ndev_bsize value bsize\n0 value raid-offset\t\\ Offset if it's a raid-frame partition\n\n: strategy ( addr size start -- nread )\n raid-offset + bsize * 0 \" seek\" boot-ihandle $call-method\n -1 = if \n .\" strategy: Seek failed\" cr\n abort\n then\n \" read\" boot-ihandle $call-method\n;\n\n\\\n\\ Cylinder group macros\n\\\n\n: cgbase ( cg fs -- cgbase ) fs_fpg l@ * ;\n: cgstart ( cg fs -- cgstart ) \n 2dup fs_cgmask l@ not and\t\t( cg fs stuff -- )\n over fs_cgoffset l@ * -rot\t\t( stuffcg fs -- )\n cgbase +\n;\n: cgdmin ( cg fs -- 1st-data-block ) dup fs_dblkno l@ -rot cgstart + ;\n: cgimin ( cg fs -- inode-block ) dup fs_iblkno l@ -rot cgstart + ;\n: cgsblock ( cg fs -- super-block ) dup fs_sblkno l@ -rot cgstart + ;\n: cgstod ( cg fs -- cg-block ) dup fs_cblkno l@ -rot cgstart + ;\n\n\\\n\\ Block and frag position macros\n\\\n\n: blkoff ( pos fs -- off ) fs_qbmask x@ and ;\n: fragoff ( pos fs -- off ) fs_qfmask x@ and ;\n: lblktosize ( blk fs -- off ) fs_bshift l@ << ;\n: lblkno ( pos fs -- off ) fs_bshift l@ >> ;\n: numfrags ( pos fs -- off ) fs_fshift l@ >> ;\n: blkroundup ( pos fs -- off ) dup fs_bmask l@ -rot fs_qbmask x@ + and ;\n: fragroundup ( pos fs -- off ) dup fs_fmask l@ -rot fs_qfmask x@ + and ;\n\\ : fragroundup ( pos fs -- off ) tuck fs_qfmask x@ + swap fs_fmask l@ and ;\n: fragstoblks ( pos fs -- off ) fs_fragshift l@ >> ;\n: blkstofrags ( blk fs -- frag ) fs_fragshift l@ << ;\n: fragnum ( fsb fs -- off ) fs_frag l@ 1- and ;\n: blknum ( fsb fs -- off ) fs_frag l@ 1- not and ;\n: dblksize ( lbn dino fs -- size )\n -rot \t\t\t\t( fs lbn dino )\n di_size x@\t\t\t\t( fs lbn di_size )\n -rot dup 1+\t\t\t\t( di_size fs lbn lbn+1 )\n 2over fs_bshift l@\t\t\t( di_size fs lbn lbn+1 di_size b_shift )\n rot swap <<\t>=\t\t\t( di_size fs lbn res1 )\n swap ndaddr >= or if\t\t\t( di_size fs )\n swap drop fs_bsize l@ exit\t( size )\n then\ttuck blkoff swap fragroundup\t( size )\n;\n\n\n: ino-to-cg ( ino fs -- cg ) fs_ipg l@ \/ ;\n: ino-to-fsbo ( ino fs -- fsb0 ) fs_inopb l@ mod ;\n: ino-to-fsba ( ino fs -- ba )\t\\ Need to remove the stupid stack diags someday\n 2dup \t\t\t\t( ino fs ino fs )\n ino-to-cg\t\t\t\t( ino fs cg )\n over\t\t\t\t\t( ino fs cg fs )\n cgimin\t\t\t\t( ino fs inode-blk )\n -rot\t\t\t\t\t( inode-blk ino fs )\n tuck \t\t\t\t( inode-blk fs ino fs )\n fs_ipg l@ \t\t\t\t( inode-blk fs ino ipg )\n mod\t\t\t\t\t( inode-blk fs mod )\n swap\t\t\t\t\t( inode-blk mod fs )\n dup \t\t\t\t\t( inode-blk mod fs fs )\n fs_inopb l@ \t\t\t\t( inode-blk mod fs inopb )\n rot \t\t\t\t\t( inode-blk fs inopb mod )\n swap\t\t\t\t\t( inode-blk fs mod inopb )\n \/\t\t\t\t\t( inode-blk fs div )\n swap\t\t\t\t\t( inode-blk div fs )\n blkstofrags\t\t\t\t( inode-blk frag )\n +\n;\n: fsbtodb ( fsb fs -- db ) fs_fsbtodb l@ << ;\n\n\\\n\\ File stuff\n\\\n\nniaddr \/w* constant narraysize\n\nstruct \n 8\t\tfield\t>f_ihandle\t\\ device handle\n 8 \t\tfield \t>f_seekp\t\\ seek pointer\n 8 \t\tfield \t>f_fs\t\t\\ pointer to super block\n ufs1_dinode_SIZEOF \tfield \t>f_di\t\\ copy of on-disk inode\n 8\t\tfield\t>f_buf\t\t\\ buffer for data block\n 4\t\tfield \t>f_buf_size\t\\ size of data block\n 4\t\tfield\t>f_buf_blkno\t\\ block number of data block\nconstant file_SIZEOF\n\nfile_SIZEOF buffer: the-file\nsb-buf the-file >f_fs x!\n\nufs1_dinode_SIZEOF buffer: cur-inode\nh# 2000 buffer: indir-block\n-1 value indir-addr\n\n\\\n\\ Translate a fileblock to a disk block\n\\\n\\ We only allow single indirection\n\\\n\n: block-map ( fileblock -- diskblock )\n \\ Direct block?\n dup ndaddr < if \t\t\t( fileblock )\n cur-inode di_db\t\t\t( arr-indx arr-start )\n swap la+ l@ exit\t\t\t( diskblock )\n then \t\t\t\t( fileblock )\n ndaddr -\t\t\t\t( fileblock' )\n \\ Now we need to check the indirect block\n dup sb-buf fs_nindir l@ < if\t( fileblock' )\n cur-inode di_ib l@ dup\t\t( fileblock' indir-block indir-block )\n indir-addr <> if \t\t( fileblock' indir-block )\n to indir-addr\t\t\t( fileblock' )\n indir-block \t\t\t( fileblock' indir-block )\n sb-buf dup fs_bsize l@\t\t( fileblock' indir-block fs fs_bsize )\n swap indir-addr swap\t\t( fileblock' indir-block fs_bsize indiraddr fs )\n fsbtodb \t\t\t( fileblock' indir-block fs_bsize db )\n strategy\t\t\t( fileblock' nread )\n then\t\t\t\t( fileblock' nread|indir-block )\n drop \\ Really should check return value\n indir-block swap la+ l@ exit\n then\n dup sb-buf fs_nindir -\t\t( fileblock'' )\n \\ Now try 2nd level indirect block -- just read twice \n dup sb-buf fs_nindir l@ dup * < if\t( fileblock'' )\n cur-inode di_ib 1 la+ l@\t\t( fileblock'' indir2-block )\n to indir-addr\t\t\t( fileblock'' )\n \\ load 1st level indir block \n indir-block \t\t\t( fileblock'' indir-block )\n sb-buf dup fs_bsize l@\t\t( fileblock'' indir-block fs fs_bsize )\n swap indir-addr swap\t\t( fileblock'' indir-block fs_bsize indiraddr fs )\n fsbtodb \t\t\t\t( fileblock'' indir-block fs_bsize db )\n strategy\t\t\t\t( fileblock'' nread )\n drop\t\t\t\t( fileblock'' )\n dup sb-buf fs_nindir \/\t\t( fileblock'' indir-offset )\n indir-block swap la+ l@\t\t( fileblock'' indirblock )\n to indir-addr\t\t\t( fileblock'' )\n \\ load 2nd level indir block\n indir-block \t\t\t( fileblock'' indir-block )\n sb-buf dup fs_bsize l@\t\t( fileblock'' indir-block fs fs_bsize )\n swap indir-addr swap\t\t( fileblock'' indir-block fs_bsize indiraddr fs )\n fsbtodb \t\t\t\t( fileblock'' indir-block fs_bsize db )\n strategy\t\t\t\t( fileblock'' nread )\n drop\t\t\t\t( fileblock'' )\n sb-buf fs_nindir l@ mod indir-block swap la+ l@ exit\n then\n .\" block-map: exceeded max file size\" cr\n abort\n;\n\n\\\n\\ Read file into internal buffer and return pointer and len\n\\\n\n0 value cur-block\t\t\t\\ allocated dynamically in ufs-open\n0 value cur-blocksize\t\t\t\\ size of cur-block\n-1 value cur-blockno\n0 value cur-offset\n\n: buf-read-file ( fs -- len buf )\n cur-offset swap\t\t\t( seekp fs )\n 2dup blkoff\t\t\t\t( seekp fs off )\n -rot 2dup lblkno\t\t\t( off seekp fs block )\n swap 2dup cur-inode\t\t\t( off seekp block fs block fs inop )\n swap dblksize\t\t\t( off seekp block fs size )\n rot dup cur-blockno\t\t\t( off seekp fs size block block cur )\n <> if \t\t\t\t( off seekp fs size block )\n block-map\t\t\t\t( off seekp fs size diskblock )\n dup 0= if\t\t\t( off seekp fs size diskblock )\n over cur-block swap 0 fill\t( off seekp fs size diskblock )\n boot-debug? if .\" buf-read-file fell off end of file\" cr then\n else\n 2dup sb-buf fsbtodb cur-block -rot strategy\t( off seekp fs size diskblock nread )\n rot 2dup <> if \" buf-read-file: short read.\" cr abort then\n then\t\t\t\t( off seekp fs diskblock nread size )\n nip nip\t\t\t\t( off seekp fs size )\n else\t\t\t\t\t( off seekp fs size block block cur )\n 2drop\t\t\t\t( off seekp fs size )\n then\n\\ dup cur-offset + to cur-offset\t\\ Set up next xfer -- not done\n nip nip swap -\t\t\t( len )\n cur-block\n;\n\n\\\n\\ Read inode into cur-inode -- uses cur-block\n\\ \n\n: read-inode ( inode fs -- )\n twiddle\t\t\t\t( inode fs -- inode fs )\n\n cur-block\t\t\t\t( inode fs -- inode fs buffer )\n\n over\t\t\t\t\t( inode fs buffer -- inode fs buffer fs )\n fs_bsize l@\t\t\t\t( inode fs buffer -- inode fs buffer size )\n\n 2over\t\t\t\t( inode fs buffer size -- inode fs buffer size inode fs )\n 2over\t\t\t\t( inode fs buffer size inode fs -- inode fs buffer size inode fs buffer size )\n 2swap tuck\t\t\t\t( inode fs buffer size inode fs buffer size -- inode fs buffer size buffer size fs inode fs )\n\n ino-to-fsba \t\t\t\t( inode fs buffer size buffer size fs inode fs -- inode fs buffer size buffer size fs fsba )\n swap\t\t\t\t\t( inode fs buffer size buffer size fs fsba -- inode fs buffer size buffer size fsba fs )\n fsbtodb\t\t\t\t( inode fs buffer size buffer size fsba fs -- inode fs buffer size buffer size db )\n\n dup to cur-blockno\t\t\t( inode fs buffer size buffer size dstart -- inode fs buffer size buffer size dstart )\n strategy\t\t\t\t( inode fs buffer size buffer size dstart -- inode fs buffer size nread )\n <> if .\" read-inode - residual\" cr abort then\n dup 2over\t\t\t\t( inode fs buffer -- inode fs buffer buffer inode fs )\n ino-to-fsbo\t\t\t\t( inode fs buffer -- inode fs buffer buffer fsbo )\n ufs1_dinode_SIZEOF * +\t\t\t( inode fs buffer buffer fsbo -- inode fs buffer dinop )\n cur-inode ufs1_dinode_SIZEOF move \t( inode fs buffer dinop -- inode fs buffer )\n\t\\ clear out the old buffers\n drop\t\t\t\t\t( inode fs buffer -- inode fs )\n 2drop\n;\n\n\\ Identify inode type\n\n: is-dir? ( dinode -- true:false ) di_mode w@ ifmt and ifdir = ;\n: is-symlink? ( dinode -- true:false ) di_mode w@ ifmt and iflnk = ;\n\n\n\n\\\n\\ Hunt for directory entry:\n\\ \n\\ repeat\n\\ load a buffer\n\\ while entries do\n\\ if entry == name return\n\\ next entry\n\\ until no buffers\n\\\n\n: search-directory ( str len -- ino|0 )\n 0 to cur-offset\n begin cur-offset cur-inode di_size x@ < while\t( str len )\n sb-buf buf-read-file\t\t( str len len buf )\n over 0= if .\" search-directory: buf-read-file zero len\" cr abort then\n swap dup cur-offset + to cur-offset\t( str len buf len )\n 2dup + nip\t\t\t( str len buf bufend )\n swap 2swap rot\t\t\t( bufend str len buf )\n begin dup 4 pick < while\t\t( bufend str len buf )\n dup d_ino l@ 0<> if \t\t( bufend str len buf )\n boot-debug? if dup dup d_name swap d_namlen c@ type cr then\n 2dup d_namlen c@ = if\t( bufend str len buf )\n dup d_name 2over\t\t( bufend str len buf dname str len )\n comp 0= if\t\t( bufend str len buf )\n \\ Found it -- return inode\n d_ino l@ nip nip nip\t( dino )\n boot-debug? if .\" Found it\" cr then \n exit \t\t\t( dino )\n then\n then\t\t\t( bufend str len buf )\n then\t\t\t\t( bufend str len buf )\n dup d_reclen w@ +\t\t( bufend str len nextbuf )\n repeat\n drop rot drop\t\t\t( str len )\n repeat\n 2drop 2drop 0\t\t\t( 0 )\n;\n\n: ffs_oldcompat ( -- )\n\\ Make sure old ffs values in sb-buf are sane\n sb-buf fs_npsect dup l@ sb-buf fs_nsect l@ max swap l!\n sb-buf fs_interleave dup l@ 1 max swap l!\n sb-buf fs_postblformat l@ fs_42postblfmt = if\n 8 sb-buf fs_nrpos l!\n then\n sb-buf fs_inodefmt l@ fs_44inodefmt < if\n sb-buf fs_bsize l@ \n dup ndaddr * 1- sb-buf fs_maxfilesize x!\n niaddr 0 ?do\n\tsb-buf fs_nindir l@ * dup\t( sizebp sizebp -- )\n\tsb-buf fs_maxfilesize dup x@\t( sizebp sizebp *fs_maxfilesize fs_maxfilesize -- )\n\trot \t\t\t\t( sizebp *fs_maxfilesize fs_maxfilesize sizebp -- )\n\t+ \t\t\t\t( sizebp *fs_maxfilesize new_fs_maxfilesize -- ) \n swap x! \t\t\t( sizebp -- )\n loop drop \t\t\t( -- )\n sb-buf dup fs_bmask l@ not swap fs_qbmask x!\n sb-buf dup fs_fmask l@ not swap fs_qfmask x!\n then\n;\n\n: read-super ( sector -- )\n0 \" seek\" boot-ihandle $call-method\n -1 = if \n .\" Seek failed\" cr\n abort\n then\n sb-buf sbsize \" read\" boot-ihandle $call-method\n dup sbsize <> if\n .\" Read of superblock failed\" cr\n .\" requested\" space sbsize .\n .\" actual\" space . cr\n abort\n else \n drop\n then\n;\n\n: ufs-open ( bootpath,len -- )\n boot-ihandle -1 = if\n over cif-open dup 0= if \t\t( boot-path len ihandle? )\n .\" Could not open device\" space type cr \n abort\n then \t\t\t\t( boot-path len ihandle )\n to boot-ihandle\t\t\t\\ Save ihandle to boot device\n then 2drop\n sboff read-super\n sb-buf fs_magic l@ fs_magic_value <> if\n 64 dup to raid-offset \n dev_bsize * sboff + read-super\n sb-buf fs_magic l@ fs_magic_value <> if\n .\" Invalid superblock magic\" cr\n abort\n then\n then\n sb-buf fs_bsize l@ dup maxbsize > if\n .\" Superblock bsize\" space . .\" too large\" cr\n abort\n then \n dup fs_SIZEOF < if\n .\" Superblock bsize < size of superblock\" cr\n abort\n then\n ffs_oldcompat\t( fs_bsize -- fs_bsize )\n dup to cur-blocksize alloc-mem to cur-block \\ Allocate cur-block\n boot-debug? if .\" ufs-open complete\" cr then\n;\n\n: ufs-close ( -- ) \n boot-ihandle dup -1 <> if\n cif-close -1 to boot-ihandle \n then\n cur-block 0<> if\n cur-block cur-blocksize free-mem\n then\n;\n\n: boot-path ( -- boot-path )\n \" bootpath\" chosen-phandle get-package-property if\n .\" Could not find bootpath in \/chosen\" cr\n abort\n else\n decode-string 2swap 2drop\n then\n;\n\n: boot-args ( -- boot-args )\n \" bootargs\" chosen-phandle get-package-property if\n .\" Could not find bootargs in \/chosen\" cr\n abort\n else\n decode-string 2swap 2drop\n then\n;\n\n2000 buffer: boot-path-str\n2000 buffer: boot-path-tmp\n\n: split-path ( path len -- right len left len )\n\\ Split a string at the `\/'\n begin\n dup -rot\t\t\t\t( oldlen right len left )\n ascii \/ left-parse-string\t\t( oldlen right len left len )\n dup 0<> if 4 roll drop exit then\n 2drop\t\t\t\t( oldlen right len )\n rot over =\t\t\t( right len diff )\n until\n;\n\n: find-file ( load-file len -- )\n rootino dup sb-buf read-inode\t( load-file len -- load-file len ino )\n -rot\t\t\t\t\t( load-file len ino -- pino load-file len )\n \\\n \\ For each path component\n \\ \n begin split-path dup 0<> while\t( pino right len left len -- )\n cur-inode is-dir? not if .\" Inode not directory\" cr abort then\n boot-debug? if .\" Looking for\" space 2dup type space .\" in directory...\" cr then\n search-directory\t\t\t( pino right len left len -- pino right len ino|false )\n dup 0= if .\" Bad path\" cr abort then\t( pino right len cino )\n sb-buf read-inode\t\t\t( pino right len )\n cur-inode is-symlink? if\t\t\\ Symlink -- follow the damn thing\n \\ Save path in boot-path-tmp\n boot-path-tmp strmov\t\t( pino new-right len )\n\n \\ Now deal with symlink\n cur-inode di_size x@\t\t( pino right len linklen )\n dup sb-buf fs_maxsymlinklen l@\t( pino right len linklen linklen maxlinklen )\n < if\t\t\t\t\\ Now join the link to the path\n cur-inode di_shortlink l@\t( pino right len linklen linkp )\n swap boot-path-str strmov\t( pino right len new-linkp linklen )\n else\t\t\t\t\\ Read file for symlink -- Ugh\n \\ Read link into boot-path-str\n boot-path-str dup sb-buf fs_bsize l@\n 0 block-map\t\t\t( pino right len linklen boot-path-str bsize blockno )\n strategy drop swap\t\t( pino right len boot-path-str linklen )\n then \t\t\t\t( pino right len linkp linklen )\n \\ Concatenate the two paths\n strcat\t\t\t\t( pino new-right newlen )\n swap dup c@ ascii \/ = if\t\\ go to root inode?\n rot drop rootino -rot\t( rino len right )\n then\n rot dup sb-buf read-inode\t( len right pino )\n -rot swap\t\t\t( pino right len )\n then\t\t\t\t( pino right len )\n repeat\n 2drop drop\n;\n\n: read-file ( size addr -- )\n \\ Read x bytes from a file to buffer\n begin over 0> while\n cur-offset cur-inode di_size x@ > if .\" read-file EOF exceeded\" cr abort then\n sb-buf buf-read-file\t\t( size addr len buf )\n over 2over drop swap\t\t( size addr len buf addr len )\n move\t\t\t\t( size addr len )\n dup cur-offset + to cur-offset\t( size len newaddr )\n tuck +\t\t\t\t( size len newaddr )\n -rot - swap\t\t\t( newaddr newsize )\n repeat\n 2drop\n;\n\n\\\n\\ According to the 1275 addendum for SPARC processors:\n\\ Default load-base is 0x4000. At least 0x8.0000 or\n\\ 512KB must be available at that address. \n\\\n\\ The Fcode bootblock can take up up to 8KB (O.K., 7.5KB) \n\\ so load programs at 0x4000 + 0x2000=> 0x6000\n\\\n\nh# 6000 constant loader-base\n\n\\\n\\ Elf support -- find the load addr\n\\\n\n: is-elf? ( hdr -- res? ) h# 7f454c46 = ;\n\n\\\n\\ Finally we finish it all off\n\\\n\n: load-file-signon ( load-file len boot-path len -- load-file len boot-path len )\n .\" Loading file\" space 2over type cr .\" from device\" space 2dup type cr\n;\n\n: load-file-print-size ( size -- size )\n .\" Loading\" space dup . space .\" bytes of file...\" cr \n;\n\n: load-file ( load-file len boot-path len -- load-base )\n boot-debug? if load-file-signon then\n the-file file_SIZEOF 0 fill\t\t\\ Clear out file structure\n ufs-open \t\t\t\t( load-file len )\n find-file\t\t\t\t( )\n\n \\\n \\ Now we've found the file we should read it in in one big hunk\n \\\n\n cur-inode di_size x@\t\t\t( file-len )\n dup \" to file-size\" evaluate\t\t( file-len )\n boot-debug? if load-file-print-size then\n 0 to cur-offset\n loader-base\t\t\t\t( buf-len addr )\n 2dup read-file\t\t\t( buf-len addr )\n ufs-close\t\t\t\t( buf-len addr )\n dup is-elf? if .\" load-file: not an elf executable\" cr abort then\n\n \\ Luckily the prom should be able to handle ELF executables by itself\n\n nip\t\t\t\t\t( addr )\n;\n\n: do-boot ( bootfile -- )\n .\" OpenBSD IEEE 1275 Bootblock 1.2\" cr\n boot-path load-file ( -- load-base )\n dup 0<> if \" to load-base init-program\" evaluate then\n;\n\n\nboot-args ascii V strchr 0<> swap drop if\n true to boot-debug?\nthen\n\nboot-args ascii D strchr 0= swap drop if\n \" \/ofwboot\" do-boot\nthen exit\n\n\n","returncode":0,"stderr":"","license":"isc","lang":"Forth"} {"commit":"78adabebb68a75b862755580a73ac5106e73766e","subject":"A helper word for clearing the cal values.","message":"A helper word for clearing the cal values.","repos":"rbsexton\/gecko,rbsexton\/gecko,rbsexton\/gecko","old_file":"zero\/clock-umb\/forth\/Clock.fth","new_file":"zero\/clock-umb\/forth\/Clock.fth","new_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( -- )\n load-defaults \n icroot 0 over inter.rtcsem ! \\ Reset the free-running counters.\n 0 over inter.rtcdsem ! \\ Reset the free-running counters.\n\n begin \n \tdup inter.rtcsem @offex! ?dup if advancehms then\n \tdup inter.rtcdsem @offex! ?dup if advancedhms then\n [asm wfi asm]\n uiupdate if use-uivals else use-clockvals then \n key? until drop\n;\n \n\\ These two contain loops to ensure that we don't\n\\ drop any timer ticks on the floor.\n: ADVANCEHMS ( n -- ) 0 do hms advancetime loop ;\n: ADVANCEDHMS ( n -- ) 0 do dhms advancetime loop ;\n \n: LOAD-DEFAULTS ( -- )\n interp-init\n;\n\n\\ ----------------------------------------------------------\n\\ Define the structures before they get used.\n\\ ----------------------------------------------------------\nstruct ODN \\ On-Deck Needle \n\tint odn.s\n\tint odn.m\n\tint odn.h\nend-struct\n\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxsec \\ Max Value for secs+minutes\n\tint hms.maxhour \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_m \\ increment the minutes + hours\nend-struct\n\nstruct _interp_set\n\t4 cells field interp.a\n\t4 cells field interp.b\n\t4 cells field interp.c\nend-struct\n\n\\ ----------------------------------------------------------\n\\ Defaults get saved in the user data page.\n\\ ----------------------------------------------------------\n: NVRAMVALID? ( addr -- t\/f ) \n\\ *G See if there is valid data in the NVRAM.\n\\ ** It consists of 3 words. If any of them are \n\\ ** set to 0xffff:ffff, we go with the defaults.\n _USERDATA\n dup @ -1 <> \n over 4 + @ -1 <> and\n swap 8 + @ -1 <> and\n;\n\n: _NVRAMLOAD ( -- ) \n\\ *G Pull the needle maximums from flash.\n $C 0 do I ud@ needle_max I + ! 4 +loop \n; \n\n: NVRAM! ( -- )\n\\ *G Save the contents of the needle cal values.\n 0 UDPAGE_ERASE\n needle_max\n $C 0 do dup I + @ I ud! 4 +loop\n drop \n;\n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nidata\ncreate ODN_HMS odn allot \\ On-Deck, HMS\ncreate ODN_DHMS odn allot \\ On-Deck, DHMS\ncreate ODN_UI odn allot \\ On-Deck, Generated by the UI.\ncdata\n\nidata \\ Has to match an odn.\ncreate NEEDLE_MAX #850 , #850 , #850 ,\ncdata\n\n(( \n: interp-next drop 1 ; \n: interp-reset drop .\" Reset\" ; \n\t\n))\n\n: RANGECHECK ( max n -- n or zero ) 2dup <= if 2drop 0 else swap drop then ; \n\n: INTER-BUMP ( max old interp -- new )\n\\ *G Get the next value from the interpolator, and \n\\ ** reset the interpolator if it wraps around to zero.\n >R R@ interp-next \\ Get the max \n + rangecheck \n dup 0= if R> interp-reset else R> drop then \n ; \n\n: NFETCH ( odn off -- max old )\n\\ *G Combine the current value with the maximum.\n >R R@ \\ stash the offset.\n + @ \\ Calculate the offset address, get the current val.\n needle_max R> + @\n swap \n;\n\n: ++NEEDLE_S \\ Called every time.\n odn_hms 0 odn.s nfetch ( max old )\n\tinterp_hms interp.a inter-bump ( new )\n\todn_hms odn.s ! \n\t;\n\n: ++NEEDLE_M ( -- )\n\\ *G Every time we roll the seconds, bump the minutes and the hour\n\todn_hms 0 odn.m nfetch ( max old )\n\tinterp_hms interp.b inter-bump \n\todn_hms odn.m ! \n\n\todn_hms 0 odn.h nfetch ( max old )\n\tinterp_hms interp.c inter-bump \n\todn_hms odn.h ! \n\t;\n\n: ++NEEDLE_DS ; \\ Called every time.\n: ++NEEDLE_DM ; \\ Every time we roll the seconds.\n\n: _USE ( odn-addr -- ) \n dup odn.s w@ pwm0!\n dup odn.m w@ pwm1!\n odn.h w@ pwm2!\n ;\n\n: USE-CLOCKVALS odn_hms _use ; \n: USE-UIVALS odn_ui _use ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Quadrature\n\\ ----------------------------------------------------------\n\n_timer1 $24 + equ QUAD-IN\n\n\\ The Quadrature encoder produces two per detent.\n: QUAD@ ( -- n ) \\ Fetch and zero\n quad-in @off \n [asm sxth tos, tos asm]\n [asm asr .s tos, tos, # 1 asm] \\ Divide by two,\n ;\n \n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_ds , ' ++needle_dm , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n: ADVANCETIME ( struct-addr -- )\n dup hms.w_s @ execute \\ Invoke the official update word.\n 1 over hms.subsec +! \\ Increment\n dup hms.subsec @\n over hms.maxsubsec @ < if drop exit then \\ If less then max, we're done\n 0 over hms.subsec ! \\ Reset the subsecs \n\n 1 over hms.s +!\n dup hms.s @ over hms.maxsec @ < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n dup hms.w_m @ execute\n 1 over hms.m +!\n dup hms.m @ over hms.maxsec @ < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ over hms.maxhour @ < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ----------------------------------------------------------\n\\ The interpolator. \n\\ Implement bresenhams algorithm. All of this code already\n\\ exists in C, but we'll own the data structures. They contain\n\\ A total of 4 words - fixed, err, num, & denom\n\\ ----------------------------------------------------------\nudata \ncreate interp_hms _interp_set allot\ncreate interp_dhms _interp_set allot \ncdata\n\n#16 #60 * equ raw_sec\n#10 #100 * equ raw_dsec\n\n: INTERP-INIT ( -- )\n (interp_init) interp_hms\n 2dup interp.a needle_max @ raw_sec call3-- \n 2dup interp.b needle_max 4 + @ #60 call3-- \n interp.c needle_max 8 + @ #12 call3--\n\n (interp_init) interp_dhms\n 2dup interp.a needle_max @ raw_dsec call3-- \n 2dup interp.b needle_max 4 + @ #100 call3-- \n interp.c needle_max 8 + @ #10 call3--\n;\n\n\\ Call the reset fn.\n: INTERP-RESET ( interp_addr -- )\n (interp_reset) swap call1-- \n;\n\n: INTERP-NEXT ( addr -- n )\n (interp_next) swap call1--n\n;\n\n\n\\ ============================ UNTESTED =======================\n\\ VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n\n\\ ----------------------------------------------------------\n\\ User Interface\n\\ ----------------------------------------------------------\nvariable uistate\nvariable uicount \n\n_GPIO $64 + equ _BUTTONIO\n: BUTTONUP? ( -- t\/f ) _buttonio @ 1 and ; \n: BUTTONDOWN? ( -- t\/f ) buttonup? 1 xor ; \n\n\\ The wrapper for all of the UI stuff.\n\\ Returns true if the UI is active - ie, use the values generated by the UI.\n: UIUPDATE ( -- t\/f )\n StateHandlers uistate @ + @ execute \n; \n\n\\ -----------------------------------------------\n\\ State numbers. These are defined x4 so that\n\\ we can just use the state number as an index \n\\ into a table of words.\n\\ -----------------------------------------------\n0 4 * equ _s_init\n1 4 * equ _s_b1\n2 4 * equ _s_1sec\n\n3 4 * equ _s_set_h\n4 4 * equ _s_pendset_m\n5 4 * equ _s_setmin\n\n6 4 * equ _s_pendcal0\n7 4 * equ _s_cal0\n8 4 * equ _s_pendcalh\n9 4 * equ _s_calh\n10 4 * equ _s_pendcalm\n11 4 * equ _s_calm\n12 4 * equ _s_pendcals\n13 4 * equ _s_cals\n\n4 equ downcount_1s\n16 equ downcount_3s \n\n\\ All of the state handlers.\n\\ Everybody needs to know the state of the button, so that must\n\\ get passed in, thus they all look like this:\n\\ state ( t\/f -- t\/f )\n: shInit false \n buttondown? if \n _s_b1 uistate !\n uicount off \\ Reset this.\n then\n ;\n\n\\ Waiting for a full second to go by.\n: shB1 false\n buttonup? if _s_init uistate ! exit then\n \\ The Button is down. \n uicount @ downcount_1s >= if\n _s_1sec uistate !\n else \n 1 uicount +!\n\tthen\n ;\n\n\\ We're in the 1 second state\n: sh1sec true \n buttonup? if _s_set_h uistate ! exit then\n uicount @ downcount_3s >= if\n _s_pendcal0 uistate !\n else \n 1 uicount +!\n\tthen \n;\n\n\\ -------------------------------------------------\n\\ Setting the time\n\\ -------------------------------------------------\n: shSetH true buttondown? if _s_pendset_m uistate ! exit then ;\n\n: shPendSetM true buttonup? if _s_setmin uistate ! then ;\n: shSetMin true buttondown? if _s_init uistate ! exit then ;\n\n\\ -------------------------------------------------\n\\ Calibration\n\\ -------------------------------------------------\n: shPendCal0 true buttonup? if _s_cal0 uistate ! then ;\n: shCal0 true buttondown? if _s_pendcalh uistate ! exit then ;\n\n: shPendCalH true buttonup? if _s_calh uistate ! then ; \n: shCalH true buttondown? if _s_pendcalm uistate ! exit then ; \n\n: shPendCalM true buttonup? if _s_calm uistate ! then ; \n: shCalM true buttondown? if _s_pendcals uistate ! exit then ; \n\n: shPendCalS true buttonup? if _s_calm uistate ! then ; \n: shCalS true buttondown? if _s_init uistate ! exit then ; \n\\ -------------------------------------------------\n\\ Helpers\n\\ -------------------------------------------------\n: helpODNClear ( -- ) \\ Set them all to zero\n odn_ui odn bounds do I off 4 +loop ; \n\ncreate StateHandlers \n' shInit , \n' shB1 ,\n' sh1sec ,\n\n' shSetH ,\n' shPendSetM , ' shSetMin ,\n\n' shPendCal0 , ' shCal0 ,\n' shPendCalH , ' shCalH , \n' shPendCalM , ' shCalM , \n' shPendCalS , ' shCalS , \n\n\\ -------------------------------------------------\n\\ Setting the time.\n\\ -------------------------------------------------\nvariable adj_i \\ THe working index into the points array.\n\nudata \ncreate adj_points #50 cells allot \\ 100 16-bit words. \ncreate interp_set _interp_set allot\ncdata \n\n\\ Generate a list of points.\n: MAKE-SET-LIST ( max steps ) \n 2dup \n >R (interp_init) swap interp_set swap R> call3--\n\n \\ Since zero is first, do the w! first.\n swap drop 0 swap \\ Keep a running counter.\n 0 do\n dup I adj_points[]! \\ Save the existing value\n interp_set interp-next + \n loop\n drop\n ;\n\n: ADJ_POINTS[]! ( data index -- ) 2* adj_points + w! ;\n: ADJ_POINTS[]@ ( index -- n ) 2* adj_points + w@ ;\n","old_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( -- )\n load-defaults \n icroot 0 over inter.rtcsem ! \\ Reset the free-running counters.\n 0 over inter.rtcdsem ! \\ Reset the free-running counters.\n\n begin \n \tdup inter.rtcsem @offex! ?dup if advancehms then\n \tdup inter.rtcdsem @offex! ?dup if advancedhms then\n [asm wfi asm]\n uiupdate if use-uivals else use-clockvals then \n key? until drop\n;\n \n\\ These two contain loops to ensure that we don't\n\\ drop any timer ticks on the floor.\n: ADVANCEHMS ( n -- ) 0 do hms advancetime loop ;\n: ADVANCEDHMS ( n -- ) 0 do dhms advancetime loop ;\n \n: LOAD-DEFAULTS ( -- )\n interp-init\n;\n\n\\ ----------------------------------------------------------\n\\ Define the structures before they get used.\n\\ ----------------------------------------------------------\nstruct ODN \\ On-Deck Needle \n\tint odn.s\n\tint odn.m\n\tint odn.h\nend-struct\n\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxsec \\ Max Value for secs+minutes\n\tint hms.maxhour \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_m \\ increment the minutes + hours\nend-struct\n\nstruct _interp_set\n\t4 cells field interp.a\n\t4 cells field interp.b\n\t4 cells field interp.c\nend-struct\n\n\\ ----------------------------------------------------------\n\\ Defaults get saved in the user data page.\n\\ ----------------------------------------------------------\n: NVRAMVALID? ( addr -- t\/f ) \n\\ *G See if there is valid data in the NVRAM.\n\\ ** It consists of 3 words. If any of them are \n\\ ** set to 0xffff:ffff, we go with the defaults.\n _USERDATA\n dup @ -1 <> \n over 4 + @ -1 <> and\n swap 8 + @ -1 <> and\n;\n\n: _NVRAMLOAD ( -- ) \n\\ *G Pull the needle maximums from flash.\n $C 0 do I ud@ needle_max I + ! 4 +loop \n; \n\n: NVRAM! ( -- )\n\\ *G Save the contents of the needle cal values.\n 0 UDPAGE_ERASE\n needle_max\n $C 0 do dup I + @ I ud! 4 +loop\n drop \n;\n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nidata\ncreate ODN_HMS odn allot \\ On-Deck, HMS\ncreate ODN_DHMS odn allot \\ On-Deck, DHMS\ncreate ODN_UI odn allot \\ On-Deck, Generated by the UI.\ncdata\n\nidata \\ Has to match an odn.\ncreate NEEDLE_MAX #850 , #850 , #850 ,\ncdata\n\n(( \n: interp-next drop 1 ; \n: interp-reset drop .\" Reset\" ; \n\t\n))\n\n: RANGECHECK ( max n -- n or zero ) 2dup <= if 2drop 0 else swap drop then ; \n\n: INTER-BUMP ( max old interp -- new )\n\\ *G Get the next value from the interpolator, and \n\\ ** reset the interpolator if it wraps around to zero.\n >R R@ interp-next \\ Get the max \n + rangecheck \n dup 0= if R> interp-reset else R> drop then \n ; \n\n: NFETCH ( odn off -- max old )\n\\ *G Combine the current value with the maximum.\n >R R@ \\ stash the offset.\n + @ \\ Calculate the offset address, get the current val.\n needle_max R> + @\n swap \n;\n\n: ++NEEDLE_S \\ Called every time.\n odn_hms 0 odn.s nfetch ( max old )\n\tinterp_hms interp.a inter-bump ( new )\n\todn_hms odn.s ! \n\t;\n\n: ++NEEDLE_M ( -- )\n\\ *G Every time we roll the seconds, bump the minutes and the hour\n\todn_hms 0 odn.m nfetch ( max old )\n\tinterp_hms interp.b inter-bump \n\todn_hms odn.m ! \n\n\todn_hms 0 odn.h nfetch ( max old )\n\tinterp_hms interp.c inter-bump \n\todn_hms odn.h ! \n\t;\n\n: ++NEEDLE_DS ; \\ Called every time.\n: ++NEEDLE_DM ; \\ Every time we roll the seconds.\n\n: _USE ( odn-addr -- ) \n dup odn.s w@ pwm0!\n dup odn.m w@ pwm1!\n odn.h w@ pwm2!\n ;\n\n: USE-CLOCKVALS odn_hms _use ; \n: USE-UIVALS odn_ui _use ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Quadrature\n\\ ----------------------------------------------------------\n\n_timer1 $24 + equ QUAD-IN\n\n\\ The Quadrature encoder produces two per detent.\n: QUAD@ ( -- n ) \\ Fetch and zero\n quad-in @off \n [asm sxth tos, tos asm]\n [asm asr .s tos, tos, # 1 asm] \\ Divide by two,\n ;\n \n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_ds , ' ++needle_dm , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n: ADVANCETIME ( struct-addr -- )\n dup hms.w_s @ execute \\ Invoke the official update word.\n 1 over hms.subsec +! \\ Increment\n dup hms.subsec @\n over hms.maxsubsec @ < if drop exit then \\ If less then max, we're done\n 0 over hms.subsec ! \\ Reset the subsecs \n\n 1 over hms.s +!\n dup hms.s @ over hms.maxsec @ < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n dup hms.w_m @ execute\n 1 over hms.m +!\n dup hms.m @ over hms.maxsec @ < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ over hms.maxhour @ < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ----------------------------------------------------------\n\\ The interpolator. \n\\ Implement bresenhams algorithm. All of this code already\n\\ exists in C, but we'll own the data structures. They contain\n\\ A total of 4 words - fixed, err, num, & denom\n\\ ----------------------------------------------------------\nudata \ncreate interp_hms _interp_set allot\ncreate interp_dhms _interp_set allot \ncdata\n\n#16 #60 * equ raw_sec\n#10 #100 * equ raw_dsec\n\n: INTERP-INIT ( -- )\n (interp_init) interp_hms\n 2dup interp.a needle_max @ raw_sec call3-- \n 2dup interp.b needle_max 4 + @ #60 call3-- \n interp.c needle_max 8 + @ #12 call3--\n\n (interp_init) interp_dhms\n 2dup interp.a needle_max @ raw_dsec call3-- \n 2dup interp.b needle_max 4 + @ #100 call3-- \n interp.c needle_max 8 + @ #10 call3--\n;\n\n\\ Call the reset fn.\n: INTERP-RESET ( interp_addr -- )\n (interp_reset) swap call1-- \n;\n\n: INTERP-NEXT ( addr -- n )\n (interp_next) swap call1--n\n;\n\n\n\\ ============================ UNTESTED =======================\n\\ VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n\n\\ ----------------------------------------------------------\n\\ User Interface\n\\ ----------------------------------------------------------\nvariable uistate\nvariable uicount \n\n_GPIO $64 + equ _BUTTONIO\n: BUTTONUP? ( -- t\/f ) _buttonio @ 1 and ; \n: BUTTONDOWN? ( -- t\/f ) buttonup? 1 xor ; \n\n\\ The wrapper for all of the UI stuff.\n\\ Returns true if the UI is active - ie, use the values generated by the UI.\n: UIUPDATE ( -- t\/f )\n StateHandlers uistate @ + @ execute \n; \n\n\\ -----------------------------------------------\n\\ State numbers. These are defined x4 so that\n\\ we can just use the state number as an index \n\\ into a table of words.\n\\ -----------------------------------------------\n0 4 * equ _s_init\n1 4 * equ _s_b1\n2 4 * equ _s_1sec\n\n3 4 * equ _s_set_h\n4 4 * equ _s_pendset_m\n5 4 * equ _s_setmin\n\n6 4 * equ _s_pendcal0\n7 4 * equ _s_cal0\n8 4 * equ _s_pendcalh\n9 4 * equ _s_calh\n10 4 * equ _s_pendcalm\n11 4 * equ _s_calm\n12 4 * equ _s_pendcals\n13 4 * equ _s_cals\n\n4 equ downcount_1s\n16 equ downcount_3s \n\n\\ All of the state handlers.\n\\ Everybody needs to know the state of the button, so that must\n\\ get passed in, thus they all look like this:\n\\ state ( t\/f -- t\/f )\n: shInit false \n buttondown? if \n _s_b1 uistate !\n uicount off \\ Reset this.\n then\n ;\n\n\\ Waiting for a full second to go by.\n: shB1 false\n buttonup? if _s_init uistate ! exit then\n \\ The Button is down. \n uicount @ downcount_1s >= if\n _s_1sec uistate !\n else \n 1 uicount +!\n\tthen\n ;\n\n\\ We're in the 1 second state\n: sh1sec true \n buttonup? if _s_set_h uistate ! exit then\n uicount @ downcount_3s >= if\n _s_pendcal0 uistate !\n else \n 1 uicount +!\n\tthen \n;\n\n\\ -------------------------------------------------\n\\ Setting the time\n\\ -------------------------------------------------\n: shSetH true buttondown? if _s_pendset_m uistate ! exit then ;\n\n: shPendSetM true buttonup? if _s_setmin uistate ! then ;\n: shSetMin true buttondown? if _s_init uistate ! exit then ;\n\n\\ -------------------------------------------------\n\\ Calibration\n\\ -------------------------------------------------\n: shPendCal0 true buttonup? if _s_cal0 uistate ! then ;\n: shCal0 true buttondown? if _s_pendcalh uistate ! exit then ;\n\n: shPendCalH true buttonup? if _s_calh uistate ! then ; \n: shCalH true buttondown? if _s_pendcalm uistate ! exit then ; \n\n: shPendCalM true buttonup? if _s_calm uistate ! then ; \n: shCalM true buttondown? if _s_pendcals uistate ! exit then ; \n\n: shPendCalS true buttonup? if _s_calm uistate ! then ; \n: shCalS true buttondown? if _s_init uistate ! exit then ; \n\ncreate StateHandlers \n' shInit , \n' shB1 ,\n' sh1sec ,\n\n' shSetH ,\n' shPendSetM , ' shSetMin ,\n\n' shPendCal0 , ' shCal0 ,\n' shPendCalH , ' shCalH , \n' shPendCalM , ' shCalM , \n' shPendCalS , ' shCalS , \n\n\\ -------------------------------------------------\n\\ Setting the time.\n\\ -------------------------------------------------\nvariable adj_i \\ THe working index into the points array.\n\nudata \ncreate adj_points #50 cells allot \\ 100 16-bit words. \ncreate interp_set _interp_set allot\ncdata \n\n\\ Generate a list of points.\n: MAKE-SET-LIST ( max steps ) \n 2dup \n >R (interp_init) swap interp_set swap R> call3--\n\n \\ Since zero is first, do the w! first.\n swap drop 0 swap \\ Keep a running counter.\n 0 do\n dup I adj_points[]! \\ Save the existing value\n interp_set interp-next + \n loop\n drop\n ;\n\n: ADJ_POINTS[]! ( data index -- ) 2* adj_points + w! ;\n: ADJ_POINTS[]@ ( index -- n ) 2* adj_points + w@ ;\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"5bed569c96a982477ce5ee5ea42058a61dc8afe1","subject":"Code to set the time.","message":"Code to set the time.","repos":"rbsexton\/gecko,rbsexton\/gecko,rbsexton\/gecko","old_file":"tiny\/basic\/forth\/startup.fth","new_file":"tiny\/basic\/forth\/startup.fth","new_contents":"(( App Startup ))\n\n0 value JT \\ The Jumptable\n\n\\ -------------------------------------------\n\\ The word that sets everything up.\n\\ This runs before the intro banner, after\n\\ Init-multi.\n\\ -------------------------------------------\n: StartApp\n\thex\n\tinit-dp @ dp ! \\ Set the dictionary pointer so that we can function.\n\t\\ I have no idea why I am doing this instead of the compilation system.\n\n\t1 getruntimelinks to jt\n\t.\" StartApp!\" \n\n\t4 [ SCSSCR _SCS + ] literal ! \\ Set deepsleep\n\t\t\t\n;\n\n\\ ------------------------------------------\n\\ Application code\n\\ ------------------------------------------\nstruct tod\n 1 field h\n 1 field m\n 1 field s\nend-struct\n \nudata\ncreate hms tod allot\ncreate dhms tod allot\ncdata\n\n: +CAP ( n max -- n ) >R 1 + dup r> = if drop 0 then ; \n\n: ADVANCE ( tod -- )\n dup s c@ #60 +cap 2dup swap s c! \\ Advance the seconds. base n -- \n if drop exit then\n \n dup m c@ #60 +cap 2dup swap m c! \\ advance minutes\n if drop exit then\n\n dup h c@ #24 +cap 2dup swap h c! \\ advance minutes\n\n 2drop \n;\n\n: DADVANCE ( tod -- )\n dup s c@ #100 +cap 2dup swap s c! \\ Advance the seconds. base n -- \n if drop exit then\n \n dup m c@ #100 +cap 2dup swap m c! \\ advance minutes\n if drop exit then\n\n dup h c@ #10 +cap 2dup swap h c! \\ advance minutes\n\n 2drop \n;\n\n\\ ----------------------------------------------\n\\ Tools for writing to the LCD\n\\ ----------------------------------------------\n: LCD#! ( n -- ) jt LCD_# @ swap call1-- ;\n: LCD$! ( addr -- ) jt LCD_Wr @ swap call1-- ; \n\nvariable thecount\n\n(( Sample code for demonstrating messages ))\n: wakestart 1 $10 wakereq drop ; \\ Request a wake \n: wakestop 1 0 wakereq drop ; \\ No more, please. \n\n: COUNT-WORD\n wakestart\n begin\n pause\n thecount dup @ 1+ dup lcd#! swap ! \n stop \n again\n;\n\n: COUNT-WORDd\n begin\n pause self msg? if get-message drop \\ We don't care who sent it.\n case \n 0 of wakestop endof\n 1 of wakestart endof\n endcase\n then\n\n thecount dup @ 1+ dup lcd#! swap ! \n stop \n again\n;\n\n\\ --------------------------------------------------------------------\n\\ Keeping time.\n\\ --------------------------------------------------------------------\ntask TOPTASK \n\n: TOPLCDOUT hms dup h c@ #100 * swap m c@ + lcd#! ; \n\n: TOPWORD\n 0 $10 wakereq drop \\ The first Second. \n begin\n pause\n toplcdout \n hms advance\n 2 $10 wakereq drop \\ Relative step\n again\n; \n\n\n\\ --------------------------------------------------------------------\n\\ Decimal Time\n\\ --------------------------------------------------------------------\n\ntask BOTTASK\n\n: BOTWORD\n 1 err interp-next wakereq drop \n begin\n pause\n dhms dadvance\n botlcd dms$ drop lcd$!\n 3 err interp-next wakereq drop \n again\n; \n\n: BOTLCD dhms\n dup h c@ #10000 *\n over m c@ #100 * +\n swap s c@ + ;\n\n\\ Include the terminating null.\n: dms$ base @ >R decimal s>d <# 0 hold # # $20 hold # # $20 hold # #> R> base ! ; \n\n: interp-next ( addr -- ) \\ A fixed version. Returns amount to step\n dup @ \\ err\n #103 - dup 1 > if swap ! #13 exit then\n \\ Otherwise, we need to adjust\n #125 + swap ! #14 \n;\n\n: CLOCKSTART\n ['] topword toptask initiate\n ['] botword bottask initiate \n;\n\nvariable err \n\n: COUNT-DT\n 0 err interp-next wakereq drop \\ Don't keep the return code.\n begin \n pause\n thecount dup @ 1 #9999 +cap dup lcd#! swap ! \n 2 err interp-next wakereq drop \\ Don't keep the return code. \n again\n;\n\n\\ ---------------------------------------------------------------\n\\ Setting the time.\n\\ ---------------------------------------------------------------\n\n: *HMS->S ( addr -- n ) dup h c@ #3600 * over m c@ #60 * + swap s c@ + ; \n: *DHMS->S ( addr -- n ) dup h c@ #10000 * over m c@ #100 * + swap s c@ + ; \n\n\\ Stash things in the struct.\n: ->*HMS ( h m s addr -- ) dup >R s c! R@ m c! R> h c! ; \n\n: S->DS ( seconds -- seconds )\n dup #108 \/ #125 * \\ First pass \n swap #108 mod #125 * #108 \/ +\n;\n\n: DS->DHMS ( n -- h m s ) \n dup #10000 \/ swap #10000 mod \n dup #100 \/ swap #100 mod \n ;\n\n: SETBOTH ( h m s -- ) \n hms ->*hms\n hms *hms->s\n s->ds ds->dhms\n dhms ->*hms \n;\n\n\n((\ntask foo \n' count-word foo initiate\n\n))\n\n \n\n\n","old_contents":"(( App Startup ))\n\n0 value JT \\ The Jumptable\n\n\\ -------------------------------------------\n\\ The word that sets everything up.\n\\ This runs before the intro banner, after\n\\ Init-multi.\n\\ -------------------------------------------\n: StartApp\n\thex\n\tinit-dp @ dp ! \\ Set the dictionary pointer so that we can function.\n\t\\ I have no idea why I am doing this instead of the compilation system.\n\n\t1 getruntimelinks to jt\n\t.\" StartApp!\" \n\n\t4 [ SCSSCR _SCS + ] literal ! \\ Set deepsleep\n\t\t\t\n;\n\n\\ ------------------------------------------\n\\ Application code\n\\ ------------------------------------------\nstruct tod\n 1 field h\n 1 field m\n 1 field s\nend-struct\n \nudata\ncreate hms tod allot\ncreate dhms tod allot\ncdata\n\n: +CAP ( n max -- n ) >R 1 + dup r> = if drop 0 then ; \n\n: ADVANCE ( tod -- )\n dup s c@ #60 +cap 2dup swap s c! \\ Advance the seconds. base n -- \n if drop exit then\n \n dup m c@ #60 +cap 2dup swap m c! \\ advance minutes\n if drop exit then\n\n dup h c@ #24 +cap 2dup swap h c! \\ advance minutes\n\n 2drop \n;\n\n: DADVANCE ( tod -- )\n dup s c@ #100 +cap 2dup swap s c! \\ Advance the seconds. base n -- \n if drop exit then\n \n dup m c@ #100 +cap 2dup swap m c! \\ advance minutes\n if drop exit then\n\n dup h c@ #10 +cap 2dup swap h c! \\ advance minutes\n\n 2drop \n;\n\n\\ ----------------------------------------------\n\\ Tools for writing to the LCD\n\\ ----------------------------------------------\n: LCD#! ( n -- ) jt LCD_# @ swap call1-- ;\n: LCD$! ( addr -- ) jt LCD_Wr @ swap call1-- ; \n\nvariable thecount\n\n(( Sample code for demonstrating messages ))\n: wakestart 1 $10 wakereq drop ; \\ Request a wake \n: wakestop 1 0 wakereq drop ; \\ No more, please. \n\n: COUNT-WORD\n wakestart\n begin\n pause\n thecount dup @ 1+ dup lcd#! swap ! \n stop \n again\n;\n\n: COUNT-WORDd\n begin\n pause self msg? if get-message drop \\ We don't care who sent it.\n case \n 0 of wakestop endof\n 1 of wakestart endof\n endcase\n then\n\n thecount dup @ 1+ dup lcd#! swap ! \n stop \n again\n;\n\n\\ --------------------------------------------------------------------\n\\ Keeping time.\n\\ --------------------------------------------------------------------\ntask TOPTASK \n\n: TOPLCDOUT hms dup h c@ #100 * swap m c@ + lcd#! ; \n\n: TOPWORD\n 0 $10 wakereq drop \\ The first Second. \n begin\n pause\n toplcdout \n hms advance\n 2 $10 wakereq drop \\ Relative step\n again\n; \n\n\n\\ --------------------------------------------------------------------\n\\ Decimal Time\n\\ --------------------------------------------------------------------\n\ntask BOTTASK\n\n: BOTWORD\n 1 err interp-next wakereq drop \n begin\n pause\n dhms dadvance\n botlcd dms$ drop lcd$!\n 3 err interp-next wakereq drop \n again\n; \n\n: BOTLCD dhms\n dup h c@ #10000 *\n over m c@ #100 * +\n swap s c@ + ;\n\n\\ Include the terminating null.\n: dms$ base @ >R decimal s>d <# 0 hold # # $20 hold # # $20 hold # #> R> base ! ; \n\n: interp-next ( addr -- ) \\ A fixed version. Returns amount to step\n dup @ \\ err\n #103 - dup 1 > if swap ! #13 exit then\n \\ Otherwise, we need to adjust\n #125 + swap ! #14 \n;\n\n: CLOCKSTART\n ['] topword toptask initiate\n ['] botword bottask initiate \n;\n\nvariable err \n\n: COUNT-DT\n 0 err interp-next wakereq drop \\ Don't keep the return code.\n begin \n pause\n thecount dup @ 1 #9999 +cap dup lcd#! swap ! \n 2 err interp-next wakereq drop \\ Don't keep the return code. \n again\n;\n\n\n\n\n((\ntask foo \n' count-word foo initiate\n\n\n\n\n))\n\n \n\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"b0bb7cf1eb3e027a57e0d7ef6e02a298642d9b8b","subject":"More Cleanup.","message":"More Cleanup.","repos":"rbsexton\/sockpuppet,rbsexton\/sockpuppet","old_file":"forth\/SAPI-core.fth","new_file":"forth\/SAPI-core.fth","new_contents":"\\ Wrappers for SAPI functions\n\\ SVC 0: Return the version of the API in use.\n\\ SVC 1: Return the address of the shared variables table\n\n\\ 2-4 are for use by the serial io routines, and are \n\\ defined elsewhere.\n\n\\ Note that the system call number is embedded into the instruction,\n\\ so this is not so easily parameterized.\n\n#0 equ SAPI_VEC_VERSION\n#1 equ SAPI_VEC_VARS\n#2 equ SAPI_VEC_PUTCHAR\n#3 equ SAPI_VEC_GETCHAR\n#4 equ SAPI_VEC_GETCHARAVAIL\n#5 equ SAPI_VEC_PUTCHARHASROOM\n#6 equ SAPI_VEC_SET_IO_CALLBACK\n#7 equ SAPI_VEC_GETMS\n\n#10 equ SAPI_VEC_STARTAPP\n#11 equ SAPI_VEC_MPULOAD\n#12 equ SAPI_VEC_PRIVMODE\n#13 equ SAPI_VEC_USAGE\n#14 equ SAPI_VEC_PETWATCHDOG\n\n\\ **********************************************************************\n\\ SVC 0: Return the version of the API in use.\n\\ **********************************************************************\nCODE SAPI-Version \\ -- n \n\t\\ Push TOS, and place the result there.\t\n\tsvc # SAPI_VEC_VERSION \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 1: Get the address of the shared variable list\n\\ **********************************************************************\nCODE GetSharedVars \\ -- n \n\tsvc # SAPI_VEC_VARS \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ Do a stack switch and startup the user App. Its a one-way\n\\ trip, so don't worry about stack cleanup.\n\\ **********************************************************************\nCODE RestartForth ( c-addr ) \\ -- \n\tmov r0, tos\n\tsvc # SAPI_VEC_STARTAPP\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ Request Privileged Mode. In some systems, this is a huge\n\\ Security hole.\n\\ **********************************************************************\nCODE privmode \\ -- \n\tsvc # SAPI_VEC_PRIVMODE\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ Ask for MPU entry updates.\n\\ **********************************************************************\nCODE MPULoad \\ -- \n\tmov r0, tos\n\tsvc # SAPI_VEC_MPULOAD\n\tldr tos, [ psp ], # $04\t\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ Refresh the watchdog\n\\ **********************************************************************\nCODE PetWatchDog \\ -- \n\tsvc # SAPI_VEC_PETWATCHDOG\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ Return Millisecond ticker value.\n\\ **********************************************************************\nCODE Ticks \\ -- n \n\tsvc # SAPI_VEC_GETMS\n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ The number of CPU cycles consumed in the last second.\n\\ **********************************************************************\nCODE GetUsage \\ -- n \n\tsvc # SAPI_VEC_USAGE\n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ Set the IO Callback address for a stream.\n\\ iovec, read\/write (r=1), address to set as zero.\n\\ Note the minor parameter swizzle here to keep the old value on TOS.\n\\ **********************************************************************\nCODE SetIOCallback \\ addr iovec read\/write -- n \n\tmov r1, tos\n\tldr r0, [ psp ], # 4 !\n\tldr r2, [ psp ], # 4 !\n \tsvc # SAPI_VEC_SET_IO_CALLBACK\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\n\n","old_contents":"\\ Wrappers for SAPI Core functions\n\\ SVC 0: Return the version of the API in use.\n\\ SVC 1: Return the address of the shared variables table\n\\ SVC 2: putchar\n\\ SVC 3: getchar\n\\ SVC 4: charsavail\n\n\\ SVC 5: LaunchUserApp\n\\ SVC 6: Reserved\n\\ SVC 7: Reserved\n\n\\ SVC 8: Watchdog Refresh\n\\ SVC 9: Return Millisecond ticker value.\n\\ SVC 10: The number of CPU cycles consumed in the last second.\n\n\\ 2-4 are for use by the serial io routines, and are \n\\ defined elsewhere.\n\n\\ Note that the system call number is embedded into the instruction,\n\\ so this is not so easily parameterized.\n\n#0 equ SAPI_VEC_VERSION\n#1 equ SAPI_VEC_VARS\n#2 equ SAPI_VEC_PUTCHAR\n#3 equ SAPI_VEC_GETCHAR\n#4 equ SAPI_VEC_GETCHARAVAIL\n#5 equ SAPI_VEC_PUTCHARHASROOM\n#6 equ SAPI_VEC_SET_IO_CALLBACK\n#7 equ SAPI_VEC_GETMS\n\n#10 equ SAPI_VEC_STARTAPP\n#11 equ SAPI_VEC_MPULOAD\n#12 equ SAPI_VEC_PRIVMODE\n#13 equ SAPI_VEC_USAGE\n#14 equ SAPI_VEC_PETWATCHDOG\n\n\\ **********************************************************************\n\\ SVC 0: Return the version of the API in use.\n\\ **********************************************************************\nCODE SAPI-Version \\ -- n \n\t\\ Push TOS, and place the result there.\t\n\tsvc # SAPI_VEC_VERSION \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 1: Get the address of the shared variable list\n\\ **********************************************************************\nCODE GetSharedVars \\ -- n \n\tsvc # SAPI_VEC_VARS \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ Do a stack switch and startup the user App. Its a one-way\n\\ trip, so don't worry about stack cleanup.\n\\ **********************************************************************\nCODE RestartForth ( c-addr ) \\ -- \n\tmov r0, tos\n\tsvc # SAPI_VEC_STARTAPP\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ Request Privileged Mode. In some systems, this is a huge\n\\ Security hole.\n\\ **********************************************************************\nCODE privmode \\ -- \n\tsvc # SAPI_VEC_PRIVMODE\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ Ask for MPU entry updates.\n\\ **********************************************************************\nCODE MPULoad \\ -- \n\tmov r0, tos\n\tsvc # SAPI_VEC_MPULOAD\n\tldr tos, [ psp ], # $04\t\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ Refresh the watchdog\n\\ **********************************************************************\nCODE PetWatchDog \\ -- \n\tsvc # SAPI_VEC_PETWATCHDOG\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ Return Millisecond ticker value.\n\\ **********************************************************************\nCODE Ticks \\ -- n \n\tsvc # SAPI_VEC_GETMS\n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ The number of CPU cycles consumed in the last second.\n\\ **********************************************************************\nCODE GetUsage \\ -- n \n\tsvc # SAPI_VEC_USAGE\n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ Set the IO Callback address for a stream.\n\\ iovec, read\/write (r=1), address to set as zero.\n\\ Note the minor parameter swizzle here to keep the old value on TOS.\n\\ **********************************************************************\nCODE SetIOCallback \\ addr iovec read\/write -- n \n\tmov r1, tos\n\tldr r0, [ psp ], # 4 !\n\tldr r2, [ psp ], # 4 !\n \tsvc # SAPI_VEC_SET_IO_CALLBACK\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\n\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"c26dd9475587567b584fa8511d8a8de24ba27e44","subject":"Don't start the beastie menu if the 'beastie_disable' variable is set to 'YES'.","message":"Don't start the beastie menu if the 'beastie_disable' variable is set to\n'YES'.\n\nIf the user selects to escape to the loader prompt, set 'autoboot_delay'\nto 'NO' so that the prompt timer doesn't run.\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/beastie.4th","new_file":"sys\/boot\/forth\/beastie.4th","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"bsd-3-clause","lang":"Forth"} {"commit":"f3d90ca8da2916bdf6d5a1b2b9520509a4e81658","subject":"Use the right function.","message":"Use the right function.\n","repos":"rbsexton\/gecko,rbsexton\/gecko,rbsexton\/gecko","old_file":"zero\/forth\/interconnect.fth","new_file":"zero\/forth\/interconnect.fth","new_contents":"\\ Access to the interconnect things.\n\\ Its got to match interconnect.h\n\n$20000000 equ ICROOT\n\nstruct \/INTER\t\\ -- size\n\tptr jumptable\n\tptr u0rxdata \nend-struct\n\n: jt icroot @ ; \n\nstruct \/jt\n\tptr EnterEM2\nend-struct\n\n","old_contents":"\\ Access to the interconnect things.\n\\ Its got to match interconnect.h\n\n$20000000 equ ICROOT\n\nstruct \/INTER\t\\ -- size\n\tptr jumptable\n\tptr u0rxdata \nend-struct\n\n: jt root @ ; \n\nstruct \/jt\n\tptr EnterEM2\nend-struct\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"6fb12dd3d562bb6c79e21fe9fc2bfba0da8922f9","subject":"Fix a stack leak in r215345 when skipping over the ACPI menu item for machines that do not support ACPI.","message":"Fix a stack leak in r215345 when skipping over the ACPI menu item for\nmachines that do not support ACPI.\n\nSubmitted by:\tolli\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/beastie.4th","new_file":"sys\/boot\/forth\/beastie.4th","new_contents":"\\ Copyright (c) 2003 Scott Long \n\\ Copyright (c) 2003 Aleksander Fafula \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\nmarker task-beastie.4th\n\ninclude \/boot\/screen.4th\ninclude \/boot\/frames.4th\n\nhide\n\nvariable menuidx\nvariable menubllt\nvariable menuX\nvariable menuY\nvariable promptwidth\n\nvariable bootkey\nvariable bootacpikey\nvariable bootsafekey\nvariable bootverbosekey\nvariable bootsinglekey\nvariable escapekey\nvariable rebootkey\n\n46 constant dot\n\n\\ The BSD Daemon. He is 19 rows high and 34 columns wide\n: beastie-logo ( x y -- )\n2dup at-xy .\" \u001b[1;31m, ,\" 1+\n2dup at-xy .\" \/( )`\" 1+\n2dup at-xy .\" \\ \\___ \/ |\" 1+\n2dup at-xy .\" \/- \u001b[37m_\u001b[31m `-\/ '\" 1+\n2dup at-xy .\" (\u001b[37m\/\\\/ \\\u001b[31m \\ \/\\\" 1+\n2dup at-xy .\" \u001b[37m\/ \/ |\u001b[31m ` \\\" 1+\n2dup at-xy .\" \u001b[34mO O \u001b[37m) \u001b[31m\/ |\" 1+\n2dup at-xy .\" \u001b[37m`-^--'\u001b[31m`< '\" 1+\n2dup at-xy .\" (_.) _ ) \/\" 1+\n2dup at-xy .\" `.___\/` \/ \" 1+\n2dup at-xy .\" `-----' \/\" 1+\n2dup at-xy .\" \u001b[33m<----.\u001b[31m __ \/ __ \\\" 1+\n2dup at-xy .\" \u001b[33m<----|====\u001b[31mO)))\u001b[33m==\u001b[31m) \\) \/\u001b[33m====|\" 1+\n2dup at-xy .\" \u001b[33m<----'\u001b[31m `--' `.__,' \\\" 1+\n2dup at-xy .\" | |\" 1+\n2dup at-xy .\" \\ \/ \/\\\" 1+\n2dup at-xy .\" \u001b[36m______\u001b[31m( (_ \/ \\______\/\" 1+\n2dup at-xy .\" \u001b[36m,' ,-----' |\" 1+\nat-xy .\" `--{__________) \u001b[0m\"\n;\n\n: beastiebw-logo ( x y -- )\n\t2dup at-xy .\" , ,\" 1+\n\t2dup at-xy .\" \/( )`\" 1+\n\t2dup at-xy .\" \\ \\___ \/ |\" 1+\n\t2dup at-xy .\" \/- _ `-\/ '\" 1+\n\t2dup at-xy .\" (\/\\\/ \\ \\ \/\\\" 1+\n\t2dup at-xy .\" \/ \/ | ` \\\" 1+\n\t2dup at-xy .\" O O ) \/ |\" 1+\n\t2dup at-xy .\" `-^--'`< '\" 1+\n\t2dup at-xy .\" (_.) _ ) \/\" 1+\n\t2dup at-xy .\" `.___\/` \/\" 1+\n\t2dup at-xy .\" `-----' \/\" 1+\n\t2dup at-xy .\" <----. __ \/ __ \\\" 1+\n\t2dup at-xy .\" <----|====O)))==) \\) \/====\" 1+\n\t2dup at-xy .\" <----' `--' `.__,' \\\" 1+\n\t2dup at-xy .\" | |\" 1+\n\t2dup at-xy .\" \\ \/ \/\\\" 1+\n\t2dup at-xy .\" ______( (_ \/ \\______\/\" 1+\n\t2dup at-xy .\" ,' ,-----' |\" 1+\n\t at-xy .\" `--{__________)\"\n;\n\n: fbsdbw-logo ( x y -- )\n\t2dup at-xy .\" ______\" 1+\n\t2dup at-xy .\" | ____| __ ___ ___ \" 1+\n\t2dup at-xy .\" | |__ | '__\/ _ \\\/ _ \\\" 1+\n\t2dup at-xy .\" | __|| | | __\/ __\/\" 1+\n\t2dup at-xy .\" | | | | | | |\" 1+\n\t2dup at-xy .\" |_| |_| \\___|\\___|\" 1+\n\t2dup at-xy .\" ____ _____ _____\" 1+\n\t2dup at-xy .\" | _ \\ \/ ____| __ \\\" 1+\n\t2dup at-xy .\" | |_) | (___ | | | |\" 1+\n\t2dup at-xy .\" | _ < \\___ \\| | | |\" 1+\n\t2dup at-xy .\" | |_) |____) | |__| |\" 1+\n\t2dup at-xy .\" | | | |\" 1+\n\t at-xy .\" |____\/|_____\/|_____\/\"\n;\n\n: print-logo ( x y -- )\n\ts\" loader_logo\" getenv\n\tdup -1 = if\n\t\tdrop\n\t\tfbsdbw-logo\n\t\texit\n\tthen\n\t2dup s\" fbsdbw\" compare-insensitive 0= if\n\t\t2drop\n\t\tfbsdbw-logo\n\t\texit\n\tthen\n\t2dup s\" beastiebw\" compare-insensitive 0= if\n\t\t2drop\n\t\tbeastiebw-logo\n\t\texit\n\tthen\n\t2dup s\" beastie\" compare-insensitive 0= if\n\t\t2drop\n\t\tbeastie-logo\n\t\texit\n\tthen\n\t2dup s\" none\" compare-insensitive 0= if\n\t\t2drop\n\t\t\\ no logo\n\t\texit\n\tthen\n\t2drop\n\tfbsdbw-logo\n;\n\n: acpipresent? ( -- flag )\n\ts\" hint.acpi.0.rsdp\" getenv\n\tdup -1 = if\n\t\tdrop false exit\n\tthen\n\t2drop\n\ttrue\n;\n\n: acpienabled? ( -- flag )\n\ts\" hint.acpi.0.disabled\" getenv\n\tdup -1 <> if\n\t\ts\" 0\" compare 0<> if\n\t\t\tfalse exit\n\t\tthen\n\telse\n\t\tdrop\n\tthen\n\ttrue\n;\n\n: printmenuitem ( -- n )\n\tmenuidx @\n\t1+ dup\n\tmenuidx !\n\tmenuY @ + dup menuX @ swap at-xy\n\tmenuidx @ .\n\tmenuX @ 1+ swap at-xy\n\tmenubllt @ emit\n\tmenuidx @ 48 +\n;\n\n: beastie-menu ( -- )\n\t0 menuidx !\n\tdot menubllt !\n\t8 menuY !\n\t5 menuX !\n\tclear\n\t46 4 print-logo\n\t42 20 2 2 box\n\t13 6 at-xy .\" Welcome to FreeBSD!\"\n\tprintmenuitem .\" Boot FreeBSD [default]\" bootkey !\n\ts\" arch-i386\" environment? if\n\t\tdrop\n\t\tacpipresent? if\n\t\t\tprintmenuitem .\" Boot FreeBSD with ACPI \" bootacpikey !\n\t\t\tacpienabled? if\n\t\t\t\t.\" disabled\"\n\t\t\telse\n\t\t\t\t.\" enabled\"\n\t\t\tthen\n\t\telse\n\t\t\tmenuidx @\n\t\t\t1+\n\t\t\tmenuidx !\n\t\t\t-2 bootacpikey !\n\t\tthen\n\telse\n\t\t-2 bootacpikey !\n\tthen\n\tprintmenuitem .\" Boot FreeBSD in Safe Mode\" bootsafekey !\n\tprintmenuitem .\" Boot FreeBSD in single user mode\" bootsinglekey !\n\tprintmenuitem .\" Boot FreeBSD with verbose logging\" bootverbosekey !\n\tprintmenuitem .\" Escape to loader prompt\" escapekey !\n\tprintmenuitem .\" Reboot\" rebootkey !\n\tmenuX @ 20 at-xy\n\t.\" Select option, [Enter] for default\"\n\tmenuX @ 21 at-xy\n\ts\" or [Space] to pause timer \" dup 2 - promptwidth !\n\ttype\n;\n\n: tkey\n\tseconds +\n\tbegin 1 while\n\t\tover 0<> if\n\t\t\tdup seconds u< if\n\t\t\t\tdrop\n\t\t\t\t-1\n\t\t\t\texit\n\t\t\tthen\n\t\t\tmenuX @ promptwidth @ + 21 at-xy dup seconds - .\n\t\tthen\n\t\tkey? if\n\t\t\tdrop\n\t\t\tkey\n\t\t\texit\n\t\tthen\n\t50 ms\n\trepeat\n;\n\nset-current\n\n: beastie-start\n\ts\" beastie_disable\" getenv\n\tdup -1 <> if\n\t\ts\" YES\" compare-insensitive 0= if\n\t\t\texit\n\t\tthen\n\telse\n\t\tdrop\n\tthen\n\tbeastie-menu\n\ts\" autoboot_delay\" getenv\n\tdup -1 = if\n\t\tdrop\n\t\t10\n\telse\n\t\t2dup s\" -1\" compare 0= if\n\t\t\t0 boot\n\t\tthen\n\t\t0 s>d 2swap >number 2drop drop\n\tthen\n\tbegin\n\t\tdup tkey\n\t\t0 25 at-xy\n\t\tdup 32 = if nip 0 swap then\n\t\tdup -1 = if 0 boot then\n\t\tdup 13 = if 0 boot then\n\t\tdup bootkey @ = if 0 boot then\n\t\tdup bootacpikey @ = if\n\t\t\tacpienabled? if\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\telse\n\t\t\t\ts\" 0\" s\" hint.acpi.0.disabled\" setenv\n\t\t\tthen\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootsafekey @ = if\n\t\t\ts\" arch-i386\" environment? if\n\t\t\t\tdrop\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\t\ts\" 1\" s\" hint.apic.0.disabled\" setenv\n\t\t\tthen\n\t\t\ts\" 0\" s\" hw.ata.ata_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.atapi_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.wc\" setenv\n\t\t\ts\" 0\" s\" hw.eisa_slots\" setenv\n\t\t\ts\" 1\" s\" hint.kbdmux.0.disabled\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootverbosekey @ = if\n\t\t\ts\" YES\" s\" boot_verbose\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootsinglekey @ = if\n\t\t\ts\" YES\" s\" boot_single\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup escapekey @ = if\n\t\t\t2drop\n\t\t\ts\" NO\" s\" autoboot_delay\" setenv\n\t\t\texit\n\t\tthen\n\t\trebootkey @ = if 0 reboot then\n\tagain\n;\n\nprevious\n","old_contents":"\\ Copyright (c) 2003 Scott Long \n\\ Copyright (c) 2003 Aleksander Fafula \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\nmarker task-beastie.4th\n\ninclude \/boot\/screen.4th\ninclude \/boot\/frames.4th\n\nhide\n\nvariable menuidx\nvariable menubllt\nvariable menuX\nvariable menuY\nvariable promptwidth\n\nvariable bootkey\nvariable bootacpikey\nvariable bootsafekey\nvariable bootverbosekey\nvariable bootsinglekey\nvariable escapekey\nvariable rebootkey\n\n46 constant dot\n\n\\ The BSD Daemon. He is 19 rows high and 34 columns wide\n: beastie-logo ( x y -- )\n2dup at-xy .\" \u001b[1;31m, ,\" 1+\n2dup at-xy .\" \/( )`\" 1+\n2dup at-xy .\" \\ \\___ \/ |\" 1+\n2dup at-xy .\" \/- \u001b[37m_\u001b[31m `-\/ '\" 1+\n2dup at-xy .\" (\u001b[37m\/\\\/ \\\u001b[31m \\ \/\\\" 1+\n2dup at-xy .\" \u001b[37m\/ \/ |\u001b[31m ` \\\" 1+\n2dup at-xy .\" \u001b[34mO O \u001b[37m) \u001b[31m\/ |\" 1+\n2dup at-xy .\" \u001b[37m`-^--'\u001b[31m`< '\" 1+\n2dup at-xy .\" (_.) _ ) \/\" 1+\n2dup at-xy .\" `.___\/` \/ \" 1+\n2dup at-xy .\" `-----' \/\" 1+\n2dup at-xy .\" \u001b[33m<----.\u001b[31m __ \/ __ \\\" 1+\n2dup at-xy .\" \u001b[33m<----|====\u001b[31mO)))\u001b[33m==\u001b[31m) \\) \/\u001b[33m====|\" 1+\n2dup at-xy .\" \u001b[33m<----'\u001b[31m `--' `.__,' \\\" 1+\n2dup at-xy .\" | |\" 1+\n2dup at-xy .\" \\ \/ \/\\\" 1+\n2dup at-xy .\" \u001b[36m______\u001b[31m( (_ \/ \\______\/\" 1+\n2dup at-xy .\" \u001b[36m,' ,-----' |\" 1+\nat-xy .\" `--{__________) \u001b[0m\"\n;\n\n: beastiebw-logo ( x y -- )\n\t2dup at-xy .\" , ,\" 1+\n\t2dup at-xy .\" \/( )`\" 1+\n\t2dup at-xy .\" \\ \\___ \/ |\" 1+\n\t2dup at-xy .\" \/- _ `-\/ '\" 1+\n\t2dup at-xy .\" (\/\\\/ \\ \\ \/\\\" 1+\n\t2dup at-xy .\" \/ \/ | ` \\\" 1+\n\t2dup at-xy .\" O O ) \/ |\" 1+\n\t2dup at-xy .\" `-^--'`< '\" 1+\n\t2dup at-xy .\" (_.) _ ) \/\" 1+\n\t2dup at-xy .\" `.___\/` \/\" 1+\n\t2dup at-xy .\" `-----' \/\" 1+\n\t2dup at-xy .\" <----. __ \/ __ \\\" 1+\n\t2dup at-xy .\" <----|====O)))==) \\) \/====\" 1+\n\t2dup at-xy .\" <----' `--' `.__,' \\\" 1+\n\t2dup at-xy .\" | |\" 1+\n\t2dup at-xy .\" \\ \/ \/\\\" 1+\n\t2dup at-xy .\" ______( (_ \/ \\______\/\" 1+\n\t2dup at-xy .\" ,' ,-----' |\" 1+\n\t at-xy .\" `--{__________)\"\n;\n\n: fbsdbw-logo ( x y -- )\n\t2dup at-xy .\" ______\" 1+\n\t2dup at-xy .\" | ____| __ ___ ___ \" 1+\n\t2dup at-xy .\" | |__ | '__\/ _ \\\/ _ \\\" 1+\n\t2dup at-xy .\" | __|| | | __\/ __\/\" 1+\n\t2dup at-xy .\" | | | | | | |\" 1+\n\t2dup at-xy .\" |_| |_| \\___|\\___|\" 1+\n\t2dup at-xy .\" ____ _____ _____\" 1+\n\t2dup at-xy .\" | _ \\ \/ ____| __ \\\" 1+\n\t2dup at-xy .\" | |_) | (___ | | | |\" 1+\n\t2dup at-xy .\" | _ < \\___ \\| | | |\" 1+\n\t2dup at-xy .\" | |_) |____) | |__| |\" 1+\n\t2dup at-xy .\" | | | |\" 1+\n\t at-xy .\" |____\/|_____\/|_____\/\"\n;\n\n: print-logo ( x y -- )\n\ts\" loader_logo\" getenv\n\tdup -1 = if\n\t\tdrop\n\t\tfbsdbw-logo\n\t\texit\n\tthen\n\t2dup s\" fbsdbw\" compare-insensitive 0= if\n\t\t2drop\n\t\tfbsdbw-logo\n\t\texit\n\tthen\n\t2dup s\" beastiebw\" compare-insensitive 0= if\n\t\t2drop\n\t\tbeastiebw-logo\n\t\texit\n\tthen\n\t2dup s\" beastie\" compare-insensitive 0= if\n\t\t2drop\n\t\tbeastie-logo\n\t\texit\n\tthen\n\t2dup s\" none\" compare-insensitive 0= if\n\t\t2drop\n\t\t\\ no logo\n\t\texit\n\tthen\n\t2drop\n\tfbsdbw-logo\n;\n\n: acpipresent? ( -- flag )\n\ts\" hint.acpi.0.rsdp\" getenv\n\tdup -1 = if\n\t\tdrop false exit\n\tthen\n\t2drop\n\ttrue\n;\n\n: acpienabled? ( -- flag )\n\ts\" hint.acpi.0.disabled\" getenv\n\tdup -1 <> if\n\t\ts\" 0\" compare 0<> if\n\t\t\tfalse exit\n\t\tthen\n\telse\n\t\tdrop\n\tthen\n\ttrue\n;\n\n: printmenuitem ( -- n )\n\tmenuidx @\n\t1+ dup\n\tmenuidx !\n\tmenuY @ + dup menuX @ swap at-xy\n\tmenuidx @ .\n\tmenuX @ 1+ swap at-xy\n\tmenubllt @ emit\n\tmenuidx @ 48 +\n;\n\n: beastie-menu ( -- )\n\t0 menuidx !\n\tdot menubllt !\n\t8 menuY !\n\t5 menuX !\n\tclear\n\t46 4 print-logo\n\t42 20 2 2 box\n\t13 6 at-xy .\" Welcome to FreeBSD!\"\n\tprintmenuitem .\" Boot FreeBSD [default]\" bootkey !\n\ts\" arch-i386\" environment? if\n\t\tdrop\n\t\tacpipresent? if\n\t\t\tprintmenuitem .\" Boot FreeBSD with ACPI \" bootacpikey !\n\t\t\tacpienabled? if\n\t\t\t\t.\" disabled\"\n\t\t\telse\n\t\t\t\t.\" enabled\"\n\t\t\tthen\n\t\telse\n\t\t\tmenuidx @\n\t\t\t1+ dup\n\t\t\tmenuidx !\n\t\t\t-2 bootacpikey !\n\t\tthen\n\telse\n\t\t-2 bootacpikey !\n\tthen\n\tprintmenuitem .\" Boot FreeBSD in Safe Mode\" bootsafekey !\n\tprintmenuitem .\" Boot FreeBSD in single user mode\" bootsinglekey !\n\tprintmenuitem .\" Boot FreeBSD with verbose logging\" bootverbosekey !\n\tprintmenuitem .\" Escape to loader prompt\" escapekey !\n\tprintmenuitem .\" Reboot\" rebootkey !\n\tmenuX @ 20 at-xy\n\t.\" Select option, [Enter] for default\"\n\tmenuX @ 21 at-xy\n\ts\" or [Space] to pause timer \" dup 2 - promptwidth !\n\ttype\n;\n\n: tkey\n\tseconds +\n\tbegin 1 while\n\t\tover 0<> if\n\t\t\tdup seconds u< if\n\t\t\t\tdrop\n\t\t\t\t-1\n\t\t\t\texit\n\t\t\tthen\n\t\t\tmenuX @ promptwidth @ + 21 at-xy dup seconds - .\n\t\tthen\n\t\tkey? if\n\t\t\tdrop\n\t\t\tkey\n\t\t\texit\n\t\tthen\n\t50 ms\n\trepeat\n;\n\nset-current\n\n: beastie-start\n\ts\" beastie_disable\" getenv\n\tdup -1 <> if\n\t\ts\" YES\" compare-insensitive 0= if\n\t\t\texit\n\t\tthen\n\telse\n\t\tdrop\n\tthen\n\tbeastie-menu\n\ts\" autoboot_delay\" getenv\n\tdup -1 = if\n\t\tdrop\n\t\t10\n\telse\n\t\t2dup s\" -1\" compare 0= if\n\t\t\t0 boot\n\t\tthen\n\t\t0 s>d 2swap >number 2drop drop\n\tthen\n\tbegin\n\t\tdup tkey\n\t\t0 25 at-xy\n\t\tdup 32 = if nip 0 swap then\n\t\tdup -1 = if 0 boot then\n\t\tdup 13 = if 0 boot then\n\t\tdup bootkey @ = if 0 boot then\n\t\tdup bootacpikey @ = if\n\t\t\tacpienabled? if\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\telse\n\t\t\t\ts\" 0\" s\" hint.acpi.0.disabled\" setenv\n\t\t\tthen\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootsafekey @ = if\n\t\t\ts\" arch-i386\" environment? if\n\t\t\t\tdrop\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\t\ts\" 1\" s\" hint.apic.0.disabled\" setenv\n\t\t\tthen\n\t\t\ts\" 0\" s\" hw.ata.ata_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.atapi_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.wc\" setenv\n\t\t\ts\" 0\" s\" hw.eisa_slots\" setenv\n\t\t\ts\" 1\" s\" hint.kbdmux.0.disabled\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootverbosekey @ = if\n\t\t\ts\" YES\" s\" boot_verbose\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootsinglekey @ = if\n\t\t\ts\" YES\" s\" boot_single\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup escapekey @ = if\n\t\t\t2drop\n\t\t\ts\" NO\" s\" autoboot_delay\" setenv\n\t\t\texit\n\t\tthen\n\t\trebootkey @ = if 0 reboot then\n\tagain\n;\n\nprevious\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"edee84f0a7e48061ee9d37608c2fbdeb8b70fe3c","subject":"Allow negative values to be specified in the loader.","message":"Allow negative values to be specified in the loader.\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/support.4th","new_file":"sys\/boot\/forth\/support.4th","new_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\ \n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\n\\ Loader.rc support functions:\n\\\n\\ initialize_support ( -- )\tinitialize global variables\n\\ initialize ( addr len -- )\tas above, plus load_conf_files\n\\ load_conf ( addr len -- )\tload conf file given\n\\ include_conf_files ( -- )\tload all conf files in load_conf_files\n\\ print_syntax_error ( -- )\tprint line and marker of where a syntax\n\\\t\t\t\terror was detected\n\\ print_line ( -- )\t\tprint last line processed\n\\ load_kernel ( -- )\t\tload kernel\n\\ load_modules ( -- )\t\tload modules flagged\n\\\n\\ Exported structures:\n\\\n\\ string\t\t\tcounted string structure\n\\\tcell .addr\t\t\tstring address\n\\\tcell .len\t\t\tstring length\n\\ module\t\t\tmodule loading information structure\n\\\tcell module.flag\t\tshould we load it?\n\\\tstring module.name\t\tmodule's name\n\\\tstring module.loadname\t\tname to be used in loading the module\n\\\tstring module.type\t\tmodule's type\n\\\tstring module.args\t\tflags to be passed during load\n\\\tstring module.beforeload\tcommand to be executed before load\n\\\tstring module.afterload\t\tcommand to be executed after load\n\\\tstring module.loaderror\t\tcommand to be executed if load fails\n\\\tcell module.next\t\tlist chain\n\\\n\\ Exported global variables;\n\\\n\\ string conf_files\t\tconfiguration files to be loaded\n\\ string password\t\tpassword\n\\ cell modules_options\t\tpointer to first module information\n\\ value verbose?\t\tindicates if user wants a verbose loading\n\\ value any_conf_read?\t\tindicates if a conf file was succesfully read\n\\\n\\ Other exported words:\n\\\n\\ strdup ( addr len -- addr' len)\t\t\tsimilar to strdup(3)\n\\ strcat ( addr len addr' len' -- addr len+len' )\tsimilar to strcat(3)\n\\ strlen ( addr -- len )\t\t\t\tsimilar to strlen(3)\n\\ s' ( | string' -- addr len | )\t\t\tsimilar to s\"\n\\ rudimentary structure support\n\n\\ Exception values\n\n1 constant syntax_error\n2 constant out_of_memory\n3 constant free_error\n4 constant set_error\n5 constant read_error\n6 constant open_error\n7 constant exec_error\n8 constant before_load_error\n9 constant after_load_error\n\n\\ I\/O constants\n\n0 constant SEEK_SET\n1 constant SEEK_CUR\n2 constant SEEK_END\n\n0 constant O_RDONLY\n1 constant O_WRONLY\n2 constant O_RDWR\n\n\\ Crude structure support\n\n: structure:\n create here 0 , ['] drop , 0\n does> create here swap dup @ allot cell+ @ execute\n;\n: member: create dup , over , + does> cell+ @ + ;\n: ;structure swap ! ;\n: constructor! >body cell+ ! ;\n: constructor: over :noname ;\n: ;constructor postpone ; swap cell+ ! ; immediate\n: sizeof ' >body @ state @ if postpone literal then ; immediate\n: offsetof ' >body cell+ @ state @ if postpone literal then ; immediate\n: ptr 1 cells member: ;\n: int 1 cells member: ;\n\n\\ String structure\n\nstructure: string\n\tptr .addr\n\tint .len\n\tconstructor:\n\t 0 over .addr !\n\t 0 swap .len !\n\t;constructor\n;structure\n\n\n\\ Module options linked list\n\nstructure: module\n\tint module.flag\n\tsizeof string member: module.name\n\tsizeof string member: module.loadname\n\tsizeof string member: module.type\n\tsizeof string member: module.args\n\tsizeof string member: module.beforeload\n\tsizeof string member: module.afterload\n\tsizeof string member: module.loaderror\n\tptr module.next\n;structure\n\n\\ Internal loader structures\nstructure: preloaded_file\n\tptr pf.name\n\tptr pf.type\n\tptr pf.args\n\tptr pf.metadata\t\\ file_metadata\n\tint pf.loader\n\tint pf.addr\n\tint pf.size\n\tptr pf.modules\t\\ kernel_module\n\tptr pf.next\t\\ preloaded_file\n;structure\n\nstructure: kernel_module\n\tptr km.name\n\t\\ ptr km.args\n\tptr km.fp\t\\ preloaded_file\n\tptr km.next\t\\ kernel_module\n;structure\n\nstructure: file_metadata\n\tint\t\tmd.size\n\t2 member:\tmd.type\t\\ this is not ANS Forth compatible (XXX)\n\tptr\t\tmd.next\t\\ file_metadata\n\t0 member:\tmd.data\t\\ variable size\n;structure\n\nstructure: config_resource\n\tptr cf.name\n\tint cf.type\n0 constant RES_INT\n1 constant RES_STRING\n2 constant RES_LONG\n\t2 cells member: u\n;structure\n\nstructure: config_device\n\tptr cd.name\n\tint cd.unit\n\tint cd.resource_count\n\tptr cd.resources\t\\ config_resource\n;structure\n\nstructure: STAILQ_HEAD\n\tptr stqh_first\t\\ type*\n\tptr stqh_last\t\\ type**\n;structure\n\nstructure: STAILQ_ENTRY\n\tptr stqe_next\t\\ type*\n;structure\n\nstructure: pnphandler\n\tptr pnph.name\n\tptr pnph.enumerate\n;structure\n\nstructure: pnpident\n\tptr pnpid.ident\t\t\t\t\t\\ char*\n\tsizeof STAILQ_ENTRY cells member: pnpid.link\t\\ pnpident\n;structure\n\nstructure: pnpinfo\n\tptr pnpi.desc\n\tint pnpi.revision\n\tptr pnpi.module\t\t\t\t\\ (char*) module args\n\tint pnpi.argc\n\tptr pnpi.argv\n\tptr pnpi.handler\t\t\t\\ pnphandler\n\tsizeof STAILQ_HEAD member: pnpi.ident\t\\ pnpident\n\tsizeof STAILQ_ENTRY member: pnpi.link\t\\ pnpinfo\n;structure\n\n\\ Global variables\n\nstring conf_files\nstring nextboot_conf_file\nstring password\ncreate module_options sizeof module.next allot 0 module_options !\ncreate last_module_option sizeof module.next allot 0 last_module_option !\n0 value verbose?\n0 value nextboot?\n\n\\ Support string functions\n\n: strdup ( addr len -- addr' len )\n >r r@ allocate if out_of_memory throw then\n tuck r@ move\n r>\n;\n\n: strcat { addr len addr' len' -- addr len+len' }\n addr' addr len + len' move\n addr len len' +\n;\n\n: strlen ( addr -- len )\n 0 >r\n begin\n dup c@ while\n 1+ r> 1+ >r repeat\n drop r>\n;\n\n: s' \n [char] ' parse\n state @ if\n postpone sliteral\n then\n; immediate\n\n: 2>r postpone >r postpone >r ; immediate\n: 2r> postpone r> postpone r> ; immediate\n: 2r@ postpone 2r> postpone 2dup postpone 2>r ; immediate\n\n: getenv?\n getenv\n -1 = if false else drop true then\n;\n\n\\ Private definitions\n\nvocabulary support-functions\nonly forth also support-functions definitions\n\n\\ Some control characters constants\n\n7 constant bell\n8 constant backspace\n9 constant tab\n10 constant lf\n13 constant \n\n\\ Read buffer size\n\n80 constant read_buffer_size\n\n\\ Standard suffixes\n\n: load_module_suffix s\" _load\" ;\n: module_loadname_suffix s\" _name\" ;\n: module_type_suffix s\" _type\" ;\n: module_args_suffix s\" _flags\" ;\n: module_beforeload_suffix s\" _before\" ;\n: module_afterload_suffix s\" _after\" ;\n: module_loaderror_suffix s\" _error\" ;\n\n\\ Support operators\n\n: >= < 0= ;\n: <= > 0= ;\n\n\\ Assorted support funcitons\n\n: free-memory free if free_error throw then ;\n\n\\ Assignment data temporary storage\n\nstring name_buffer\nstring value_buffer\n\n\\ Line by line file reading functions\n\\\n\\ exported:\n\\\tline_buffer\n\\\tend_of_file?\n\\\tfd\n\\\tread_line\n\\\treset_line_reading\n\nvocabulary line-reading\nalso line-reading definitions also\n\n\\ File data temporary storage\n\nstring read_buffer\n0 value read_buffer_ptr\n\n\\ File's line reading function\n\nsupport-functions definitions\n\nstring line_buffer\n0 value end_of_file?\nvariable fd\n\nline-reading definitions\n\n: skip_newlines\n begin\n read_buffer .len @ read_buffer_ptr >\n while\n read_buffer .addr @ read_buffer_ptr + c@ lf = if\n read_buffer_ptr char+ to read_buffer_ptr\n else\n exit\n then\n repeat\n;\n\n: scan_buffer ( -- addr len )\n read_buffer_ptr >r\n begin\n read_buffer .len @ r@ >\n while\n read_buffer .addr @ r@ + c@ lf = if\n read_buffer .addr @ read_buffer_ptr + ( -- addr )\n r@ read_buffer_ptr - ( -- len )\n r> to read_buffer_ptr\n exit\n then\n r> char+ >r\n repeat\n read_buffer .addr @ read_buffer_ptr + ( -- addr )\n r@ read_buffer_ptr - ( -- len )\n r> to read_buffer_ptr\n;\n\n: line_buffer_resize ( len -- len )\n >r\n line_buffer .len @ if\n line_buffer .addr @\n line_buffer .len @ r@ +\n resize if out_of_memory throw then\n else\n r@ allocate if out_of_memory throw then\n then\n line_buffer .addr !\n r>\n;\n \n: append_to_line_buffer ( addr len -- )\n line_buffer .addr @ line_buffer .len @\n 2swap strcat\n line_buffer .len !\n drop\n;\n\n: read_from_buffer\n scan_buffer ( -- addr len )\n line_buffer_resize ( len -- len )\n append_to_line_buffer ( addr len -- )\n;\n\n: refill_required?\n read_buffer .len @ read_buffer_ptr =\n end_of_file? 0= and\n;\n\n: refill_buffer\n 0 to read_buffer_ptr\n read_buffer .addr @ 0= if\n read_buffer_size allocate if out_of_memory throw then\n read_buffer .addr !\n then\n fd @ read_buffer .addr @ read_buffer_size fread\n dup -1 = if read_error throw then\n dup 0= if true to end_of_file? then\n read_buffer .len !\n;\n\n: reset_line_buffer\n line_buffer .addr @ ?dup if\n free-memory\n then\n 0 line_buffer .addr !\n 0 line_buffer .len !\n;\n\nsupport-functions definitions\n\n: reset_line_reading\n 0 to read_buffer_ptr\n;\n\n: read_line\n reset_line_buffer\n skip_newlines\n begin\n read_from_buffer\n refill_required?\n while\n refill_buffer\n repeat\n;\n\nonly forth also support-functions definitions\n\n\\ Conf file line parser:\n\\ ::= '='[] |\n\\ []\n\\ ::= {||'_'}\n\\ ::= '\"'{|'\\'}'\"' | \n\\ ::= ASCII 32 to 126, except '\\' and '\"'\n\\ ::= '#'{}\n\\\n\\ exported:\n\\\tline_pointer\n\\\tprocess_conf\n\n0 value line_pointer\n\nvocabulary file-processing\nalso file-processing definitions\n\n\\ parser functions\n\\\n\\ exported:\n\\\tget_assignment\n\nvocabulary parser\nalso parser definitions also\n\n0 value parsing_function\n0 value end_of_line\n\n: end_of_line?\n line_pointer end_of_line =\n;\n\n: letter?\n line_pointer c@ >r\n r@ [char] A >=\n r@ [char] Z <= and\n r@ [char] a >=\n r> [char] z <= and\n or\n;\n\n: digit?\n line_pointer c@ >r\n r@ [char] - =\n r@ [char] 0 >=\n r> [char] 9 <= and\n or\n;\n\n: quote?\n line_pointer c@ [char] \" =\n;\n\n: assignment_sign?\n line_pointer c@ [char] = =\n;\n\n: comment?\n line_pointer c@ [char] # =\n;\n\n: space?\n line_pointer c@ bl =\n line_pointer c@ tab = or\n;\n\n: backslash?\n line_pointer c@ [char] \\ =\n;\n\n: underscore?\n line_pointer c@ [char] _ =\n;\n\n: dot?\n line_pointer c@ [char] . =\n;\n\n: skip_character\n line_pointer char+ to line_pointer\n;\n\n: skip_to_end_of_line\n end_of_line to line_pointer\n;\n\n: eat_space\n begin\n space?\n while\n skip_character\n end_of_line? if exit then\n repeat\n;\n\n: parse_name ( -- addr len )\n line_pointer\n begin\n letter? digit? underscore? dot? or or or\n while\n skip_character\n end_of_line? if \n line_pointer over -\n strdup\n exit\n then\n repeat\n line_pointer over -\n strdup\n;\n\n: remove_backslashes { addr len | addr' len' -- addr' len' }\n len allocate if out_of_memory throw then\n to addr'\n addr >r\n begin\n addr c@ [char] \\ <> if\n addr c@ addr' len' + c!\n len' char+ to len'\n then\n addr char+ to addr\n r@ len + addr =\n until\n r> drop\n addr' len'\n;\n\n: parse_quote ( -- addr len )\n line_pointer\n skip_character\n end_of_line? if syntax_error throw then\n begin\n quote? 0=\n while\n backslash? if\n skip_character\n end_of_line? if syntax_error throw then\n then\n skip_character\n end_of_line? if syntax_error throw then \n repeat\n skip_character\n line_pointer over -\n remove_backslashes\n;\n\n: read_name\n parse_name\t\t( -- addr len )\n name_buffer .len !\n name_buffer .addr !\n;\n\n: read_value\n quote? if\n parse_quote\t\t( -- addr len )\n else\n parse_name\t\t( -- addr len )\n then\n value_buffer .len !\n value_buffer .addr !\n;\n\n: comment\n skip_to_end_of_line\n;\n\n: white_space_4\n eat_space\n comment? if ['] comment to parsing_function exit then\n end_of_line? 0= if syntax_error throw then\n;\n\n: variable_value\n read_value\n ['] white_space_4 to parsing_function\n;\n\n: white_space_3\n eat_space\n letter? digit? quote? or or if\n ['] variable_value to parsing_function exit\n then\n syntax_error throw\n;\n\n: assignment_sign\n skip_character\n ['] white_space_3 to parsing_function\n;\n\n: white_space_2\n eat_space\n assignment_sign? if ['] assignment_sign to parsing_function exit then\n syntax_error throw\n;\n\n: variable_name\n read_name\n ['] white_space_2 to parsing_function\n;\n\n: white_space_1\n eat_space\n letter? if ['] variable_name to parsing_function exit then\n comment? if ['] comment to parsing_function exit then\n end_of_line? 0= if syntax_error throw then\n;\n\nfile-processing definitions\n\n: get_assignment\n line_buffer .addr @ line_buffer .len @ + to end_of_line\n line_buffer .addr @ to line_pointer\n ['] white_space_1 to parsing_function\n begin\n end_of_line? 0=\n while\n parsing_function execute\n repeat\n parsing_function ['] comment =\n parsing_function ['] white_space_1 =\n parsing_function ['] white_space_4 =\n or or 0= if syntax_error throw then\n;\n\nonly forth also support-functions also file-processing definitions also\n\n\\ Process line\n\n: assignment_type? ( addr len -- flag )\n name_buffer .addr @ name_buffer .len @\n compare 0=\n;\n\n: suffix_type? ( addr len -- flag )\n name_buffer .len @ over <= if 2drop false exit then\n name_buffer .len @ over - name_buffer .addr @ +\n over compare 0=\n;\n\n: loader_conf_files?\n s\" loader_conf_files\" assignment_type?\n;\n\n: nextboot_flag?\n s\" nextboot_enable\" assignment_type?\n;\n\n: nextboot_conf?\n s\" nextboot_conf\" assignment_type?\n;\n\n: verbose_flag?\n s\" verbose_loading\" assignment_type?\n;\n\n: execute?\n s\" exec\" assignment_type?\n;\n\n: password?\n s\" password\" assignment_type?\n;\n\n: module_load?\n load_module_suffix suffix_type?\n;\n\n: module_loadname?\n module_loadname_suffix suffix_type?\n;\n\n: module_type?\n module_type_suffix suffix_type?\n;\n\n: module_args?\n module_args_suffix suffix_type?\n;\n\n: module_beforeload?\n module_beforeload_suffix suffix_type?\n;\n\n: module_afterload?\n module_afterload_suffix suffix_type?\n;\n\n: module_loaderror?\n module_loaderror_suffix suffix_type?\n;\n\n: set_conf_files\n conf_files .addr @ ?dup if\n free-memory\n then\n value_buffer .addr @ c@ [char] \" = if\n value_buffer .addr @ char+ value_buffer .len @ 2 chars -\n else\n value_buffer .addr @ value_buffer .len @\n then\n strdup\n conf_files .len ! conf_files .addr !\n;\n\n: set_nextboot_conf\n nextboot_conf_file .addr @ ?dup if\n free-memory\n then\n value_buffer .addr @ c@ [char] \" = if\n value_buffer .addr @ char+ value_buffer .len @ 2 chars -\n else\n value_buffer .addr @ value_buffer .len @\n then\n strdup\n nextboot_conf_file .len ! nextboot_conf_file .addr !\n;\n\n: append_to_module_options_list ( addr -- )\n module_options @ 0= if\n dup module_options !\n last_module_option !\n else\n dup last_module_option @ module.next !\n last_module_option !\n then\n;\n\n: set_module_name ( addr -- )\n name_buffer .addr @ name_buffer .len @\n strdup\n >r over module.name .addr !\n r> swap module.name .len !\n;\n\n: yes_value?\n value_buffer .addr @ value_buffer .len @\n 2dup s' \"YES\"' compare >r\n 2dup s' \"yes\"' compare >r\n 2dup s\" YES\" compare >r\n s\" yes\" compare r> r> r> and and and 0=\n;\n\n: find_module_option ( -- addr | 0 )\n module_options @\n begin\n dup\n while\n dup module.name dup .addr @ swap .len @\n name_buffer .addr @ name_buffer .len @\n compare 0= if exit then\n module.next @\n repeat\n;\n\n: new_module_option ( -- addr )\n sizeof module allocate if out_of_memory throw then\n dup sizeof module erase\n dup append_to_module_options_list\n dup set_module_name\n;\n\n: get_module_option ( -- addr )\n find_module_option\n ?dup 0= if new_module_option then\n;\n\n: set_module_flag\n name_buffer .len @ load_module_suffix nip - name_buffer .len !\n yes_value? get_module_option module.flag !\n;\n\n: set_module_args\n name_buffer .len @ module_args_suffix nip - name_buffer .len !\n get_module_option module.args\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_loadname\n name_buffer .len @ module_loadname_suffix nip - name_buffer .len !\n get_module_option module.loadname\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_type\n name_buffer .len @ module_type_suffix nip - name_buffer .len !\n get_module_option module.type\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_beforeload\n name_buffer .len @ module_beforeload_suffix nip - name_buffer .len !\n get_module_option module.beforeload\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_afterload\n name_buffer .len @ module_afterload_suffix nip - name_buffer .len !\n get_module_option module.afterload\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_loaderror\n name_buffer .len @ module_loaderror_suffix nip - name_buffer .len !\n get_module_option module.loaderror\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_environment_variable\n name_buffer .len @\n value_buffer .len @ +\n 5 chars +\n allocate if out_of_memory throw then\n dup 0 ( addr -- addr addr len )\n s\" set \" strcat\n name_buffer .addr @ name_buffer .len @ strcat\n s\" =\" strcat\n value_buffer .addr @ value_buffer .len @ strcat\n ['] evaluate catch if\n 2drop free drop\n set_error throw\n else\n free-memory\n then\n;\n\n: set_nextboot_flag\n yes_value? to nextboot?\n;\n\n: set_verbose\n yes_value? to verbose?\n;\n\n: execute_command\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 - swap char+ swap\n then\n ['] evaluate catch if exec_error throw then\n;\n\n: set_password\n password .addr @ ?dup if free if free_error throw then then\n value_buffer .addr @ c@ [char] \" = if\n value_buffer .addr @ char+ value_buffer .len @ 2 - strdup\n value_buffer .addr @ free if free_error throw then\n else\n value_buffer .addr @ value_buffer .len @\n then\n password .len ! password .addr !\n 0 value_buffer .addr !\n;\n\n: process_assignment\n name_buffer .len @ 0= if exit then\n loader_conf_files?\tif set_conf_files exit then\n nextboot_flag?\tif set_nextboot_flag exit then\n nextboot_conf?\tif set_nextboot_conf exit then\n verbose_flag?\t\tif set_verbose exit then\n execute?\t\tif execute_command exit then\n password?\t\tif set_password exit then\n module_load?\t\tif set_module_flag exit then\n module_loadname?\tif set_module_loadname exit then\n module_type?\t\tif set_module_type exit then\n module_args?\t\tif set_module_args exit then\n module_beforeload?\tif set_module_beforeload exit then\n module_afterload?\tif set_module_afterload exit then\n module_loaderror?\tif set_module_loaderror exit then\n set_environment_variable\n;\n\n\\ free_buffer ( -- )\n\\\n\\ Free some pointers if needed. The code then tests for errors\n\\ in freeing, and throws an exception if needed. If a pointer is\n\\ not allocated, it's value (0) is used as flag.\n\n: free_buffers\n name_buffer .addr @ dup if free then\n value_buffer .addr @ dup if free then\n or if free_error throw then\n;\n\n: reset_assignment_buffers\n 0 name_buffer .addr !\n 0 name_buffer .len !\n 0 value_buffer .addr !\n 0 value_buffer .len !\n;\n\n\\ Higher level file processing\n\nsupport-functions definitions\n\n: process_conf\n begin\n end_of_file? 0=\n while\n reset_assignment_buffers\n read_line\n get_assignment\n ['] process_assignment catch\n ['] free_buffers catch\n swap throw throw\n repeat\n;\n\n: peek_file\n 0 to end_of_file?\n reset_line_reading\n O_RDONLY fopen fd !\n fd @ -1 = if open_error throw then\n reset_assignment_buffers\n read_line\n get_assignment\n ['] process_assignment catch\n ['] free_buffers catch\n fd @ fclose\n;\n \nonly forth also support-functions definitions\n\n\\ Interface to loading conf files\n\n: load_conf ( addr len -- )\n 0 to end_of_file?\n reset_line_reading\n O_RDONLY fopen fd !\n fd @ -1 = if open_error throw then\n ['] process_conf catch\n fd @ fclose\n throw\n;\n\n: print_line\n line_buffer .addr @ line_buffer .len @ type cr\n;\n\n: print_syntax_error\n line_buffer .addr @ line_buffer .len @ type cr\n line_buffer .addr @\n begin\n line_pointer over <>\n while\n bl emit\n char+\n repeat\n drop\n .\" ^\" cr\n;\n\n\\ Debugging support functions\n\nonly forth definitions also support-functions\n\n: test-file \n ['] load_conf catch dup .\n syntax_error = if cr print_syntax_error then\n;\n\n: show-module-options\n module_options @\n begin\n ?dup\n while\n .\" Name: \" dup module.name dup .addr @ swap .len @ type cr\n .\" Path: \" dup module.loadname dup .addr @ swap .len @ type cr\n .\" Type: \" dup module.type dup .addr @ swap .len @ type cr\n .\" Flags: \" dup module.args dup .addr @ swap .len @ type cr\n .\" Before load: \" dup module.beforeload dup .addr @ swap .len @ type cr\n .\" After load: \" dup module.afterload dup .addr @ swap .len @ type cr\n .\" Error: \" dup module.loaderror dup .addr @ swap .len @ type cr\n .\" Status: \" dup module.flag @ if .\" Load\" else .\" Don't load\" then cr\n module.next @\n repeat\n;\n\nonly forth also support-functions definitions\n\n\\ Variables used for processing multiple conf files\n\nstring current_file_name\nvariable current_conf_files\n\n\\ Indicates if any conf file was succesfully read\n\n0 value any_conf_read?\n\n\\ loader_conf_files processing support functions\n\n: set_current_conf_files\n conf_files .addr @ current_conf_files !\n;\n\n: get_conf_files\n conf_files .addr @ conf_files .len @ strdup\n;\n\n: recurse_on_conf_files?\n current_conf_files @ conf_files .addr @ <>\n;\n\n: skip_leading_spaces { addr len pos -- addr len pos' }\n begin\n pos len = if addr len pos exit then\n addr pos + c@ bl =\n while\n pos char+ to pos\n repeat\n addr len pos\n;\n\n: get_file_name { addr len pos -- addr len pos' addr' len' || 0 }\n pos len = if \n addr free abort\" Fatal error freeing memory\"\n 0 exit\n then\n pos >r\n begin\n addr pos + c@ bl <>\n while\n pos char+ to pos\n pos len = if\n addr len pos addr r@ + pos r> - exit\n then\n repeat\n addr len pos addr r@ + pos r> -\n;\n\n: get_next_file ( addr len ptr -- addr len ptr' addr' len' | 0 )\n skip_leading_spaces\n get_file_name\n;\n\n: set_current_file_name\n over current_file_name .addr !\n dup current_file_name .len !\n;\n\n: print_current_file\n current_file_name .addr @ current_file_name .len @ type\n;\n\n: process_conf_errors\n dup 0= if true to any_conf_read? drop exit then\n >r 2drop r>\n dup syntax_error = if\n .\" Warning: syntax error on file \" print_current_file cr\n print_syntax_error drop exit\n then\n dup set_error = if\n .\" Warning: bad definition on file \" print_current_file cr\n print_line drop exit\n then\n dup read_error = if\n .\" Warning: error reading file \" print_current_file cr drop exit\n then\n dup open_error = if\n verbose? if .\" Warning: unable to open file \" print_current_file cr then\n drop exit\n then\n dup free_error = abort\" Fatal error freeing memory\"\n dup out_of_memory = abort\" Out of memory\"\n throw \\ Unknown error -- pass ahead\n;\n\n\\ Process loader_conf_files recursively\n\\ Interface to loader_conf_files processing\n\n: include_conf_files\n set_current_conf_files\n get_conf_files 0\n begin\n get_next_file ?dup\n while\n set_current_file_name\n ['] load_conf catch\n process_conf_errors\n recurse_on_conf_files? if recurse then\n repeat\n;\n\n: get_nextboot_conf_file ( -- addr len )\n nextboot_conf_file .addr @ nextboot_conf_file .len @ strdup\n;\n\n: rewrite_nextboot_file ( -- )\n get_nextboot_conf_file\n O_WRONLY fopen fd !\n fd @ -1 = if open_error throw then\n fd @ s' nextboot_enable=\"NO\" ' fwrite\n fd @ fclose\n;\n\n: include_nextboot_file\n get_nextboot_conf_file\n ['] peek_file catch\n nextboot? if\n get_nextboot_conf_file\n ['] load_conf catch\n process_conf_errors\n ['] rewrite_nextboot_file catch\n then\n;\n\n\\ Module loading functions\n\n: load_module?\n module.flag @\n;\n\n: load_parameters ( addr -- addr addrN lenN ... addr1 len1 N )\n dup >r\n r@ module.args .addr @ r@ module.args .len @\n r@ module.loadname .len @ if\n r@ module.loadname .addr @ r@ module.loadname .len @\n else\n r@ module.name .addr @ r@ module.name .len @\n then\n r@ module.type .len @ if\n r@ module.type .addr @ r@ module.type .len @\n s\" -t \"\n 4 ( -t type name flags )\n else\n 2 ( name flags )\n then\n r> drop\n;\n\n: before_load ( addr -- addr )\n dup module.beforeload .len @ if\n dup module.beforeload .addr @ over module.beforeload .len @\n ['] evaluate catch if before_load_error throw then\n then\n;\n\n: after_load ( addr -- addr )\n dup module.afterload .len @ if\n dup module.afterload .addr @ over module.afterload .len @\n ['] evaluate catch if after_load_error throw then\n then\n;\n\n: load_error ( addr -- addr )\n dup module.loaderror .len @ if\n dup module.loaderror .addr @ over module.loaderror .len @\n evaluate \\ This we do not intercept so it can throw errors\n then\n;\n\n: pre_load_message ( addr -- addr )\n verbose? if\n dup module.name .addr @ over module.name .len @ type\n .\" ...\"\n then\n;\n\n: load_error_message verbose? if .\" failed!\" cr then ;\n\n: load_succesful_message verbose? if .\" ok\" cr then ;\n\n: load_module\n load_parameters load\n;\n\n: process_module ( addr -- addr )\n pre_load_message\n before_load\n begin\n ['] load_module catch if\n dup module.loaderror .len @ if\n load_error\t\t\t\\ Command should return a flag!\n else \n load_error_message true\t\t\\ Do not retry\n then\n else\n after_load\n load_succesful_message true\t\\ Succesful, do not retry\n then\n until\n;\n\n: process_module_errors ( addr ior -- )\n dup before_load_error = if\n drop\n .\" Module \"\n dup module.name .addr @ over module.name .len @ type\n dup module.loadname .len @ if\n .\" (\" dup module.loadname .addr @ over module.loadname .len @ type .\" )\"\n then\n cr\n .\" Error executing \"\n dup module.beforeload .addr @ over module.afterload .len @ type cr\n abort\n then\n\n dup after_load_error = if\n drop\n .\" Module \"\n dup module.name .addr @ over module.name .len @ type\n dup module.loadname .len @ if\n .\" (\" dup module.loadname .addr @ over module.loadname .len @ type .\" )\"\n then\n cr\n .\" Error executing \"\n dup module.afterload .addr @ over module.afterload .len @ type cr\n abort\n then\n\n throw \\ Don't know what it is all about -- pass ahead\n;\n\n\\ Module loading interface\n\n: load_modules ( -- ) ( throws: abort & user-defined )\n module_options @\n begin\n ?dup\n while\n dup load_module? if\n ['] process_module catch\n process_module_errors\n then\n module.next @\n repeat\n;\n\n\\ h00h00 magic used to try loading either a kernel with a given name,\n\\ or a kernel with the default name in a directory of a given name\n\\ (the pain!)\n\n: bootpath s\" \/boot\/\" ;\n: modulepath s\" module_path\" ;\n\n\\ Functions used to save and restore module_path's value.\n: saveenv ( addr len | -1 -- addr' len | 0 -1 )\n dup -1 = if 0 swap exit then\n strdup\n;\n: freeenv ( addr len | 0 -1 )\n -1 = if drop else free abort\" Freeing error\" then\n;\n: restoreenv ( addr len | 0 -1 -- )\n dup -1 = if ( it wasn't set )\n 2drop\n modulepath unsetenv\n else\n over >r\n modulepath setenv\n r> free abort\" Freeing error\"\n then\n;\n\n: clip_args \\ Drop second string if only one argument is passed\n 1 = if\n 2swap 2drop\n 1\n else\n 2\n then\n;\n\nalso builtins\n\n\\ Parse filename from a comma-separated list\n\n: parse-; ( addr len -- addr' len-x addr x )\n over 0 2swap\n begin\n dup 0 <>\n while\n over c@ [char] ; <>\n while\n 1- swap 1+ swap\n 2swap 1+ 2swap\n repeat then\n dup 0 <> if\n 1- swap 1+ swap\n then\n 2swap\n;\n\n\\ Try loading one of multiple kernels specified\n\n: try_multiple_kernels ( addr len addr' len' args -- flag )\n >r\n begin\n parse-; 2>r\n 2over 2r>\n r@ clip_args\n s\" DEBUG\" getenv? if\n s\" echo Module_path: ${module_path}\" evaluate\n .\" Kernel : \" >r 2dup type r> cr\n dup 2 = if .\" Flags : \" >r 2over type r> cr then\n then\n 1 load\n while\n dup 0=\n until\n 1 >r \\ Failure\n else\n 0 >r \\ Success\n then\n 2drop 2drop\n r>\n r> drop\n;\n\n\\ Try to load a kernel; the kernel name is taken from one of\n\\ the following lists, as ordered:\n\\\n\\ 1. The \"bootfile\" environment variable\n\\ 2. The \"kernel\" environment variable\n\\\n\\ Flags are passed, if available. If not, dummy values must be given.\n\\\n\\ The kernel gets loaded from the current module_path.\n\n: load_a_kernel ( flags len 1 | x x 0 -- flag )\n local args\n 2local flags\n 0 0 2local kernel\n end-locals\n\n \\ Check if a default kernel name exists at all, exits if not\n s\" bootfile\" getenv dup -1 <> if\n to kernel\n flags kernel args 1+ try_multiple_kernels\n dup 0= if exit then\n then\n drop\n\n s\" kernel\" getenv dup -1 <> if\n to kernel\n else\n drop\n 1 exit \\ Failure\n then\n\n \\ Try all default kernel names\n flags kernel args 1+ try_multiple_kernels\n;\n\n\\ Try to load a kernel; the kernel name is taken from one of\n\\ the following lists, as ordered:\n\\\n\\ 1. The \"bootfile\" environment variable\n\\ 2. The \"kernel\" environment variable\n\\\n\\ Flags are passed, if provided.\n\\\n\\ The kernel will be loaded from a directory computed from the\n\\ path given. Two directories will be tried in the following order:\n\\\n\\ 1. \/boot\/path\n\\ 2. path\n\\\n\\ The module_path variable is overridden if load is succesful, by\n\\ prepending the successful path.\n\n: load_from_directory ( path len 1 | flags len' path len 2 -- flag )\n local args\n 2local path\n args 1 = if 0 0 then\n 2local flags\n 0 0 2local oldmodulepath\n 0 0 2local newmodulepath\n end-locals\n\n \\ Set the environment variable module_path, and try loading\n \\ the kernel again.\n modulepath getenv saveenv to oldmodulepath\n\n \\ Try prepending \/boot\/ first\n bootpath nip path nip + \n oldmodulepath nip dup -1 = if\n drop\n else\n 1+ +\n then\n allocate\n if ( out of memory )\n 1 exit\n then\n\n 0\n bootpath strcat\n path strcat\n 2dup to newmodulepath\n modulepath setenv\n\n \\ Try all default kernel names\n flags args 1- load_a_kernel\n 0= if ( success )\n oldmodulepath nip -1 <> if\n newmodulepath s\" ;\" strcat\n oldmodulepath strcat\n modulepath setenv\n newmodulepath drop free-memory\n oldmodulepath drop free-memory\n then\n 0 exit\n then\n\n \\ Well, try without the prepended \/boot\/\n path newmodulepath drop swap move\n newmodulepath drop path nip\n 2dup to newmodulepath\n modulepath setenv\n\n \\ Try all default kernel names\n flags args 1- load_a_kernel\n if ( failed once more )\n oldmodulepath restoreenv\n newmodulepath drop free-memory\n 1\n else\n oldmodulepath nip -1 <> if\n newmodulepath s\" ;\" strcat\n oldmodulepath strcat\n modulepath setenv\n newmodulepath drop free-memory\n oldmodulepath drop free-memory\n then\n 0\n then\n;\n\n\\ Try to load a kernel; the kernel name is taken from one of\n\\ the following lists, as ordered:\n\\\n\\ 1. The \"bootfile\" environment variable\n\\ 2. The \"kernel\" environment variable\n\\ 3. The \"path\" argument\n\\\n\\ Flags are passed, if provided.\n\\\n\\ The kernel will be loaded from a directory computed from the\n\\ path given. Two directories will be tried in the following order:\n\\\n\\ 1. \/boot\/path\n\\ 2. path\n\\\n\\ Unless \"path\" is meant to be kernel name itself. In that case, it\n\\ will first be tried as a full path, and, next, search on the\n\\ directories pointed by module_path.\n\\\n\\ The module_path variable is overridden if load is succesful, by\n\\ prepending the successful path.\n\n: load_directory_or_file ( path len 1 | flags len' path len 2 -- flag )\n local args\n 2local path\n args 1 = if 0 0 then\n 2local flags\n end-locals\n\n \\ First, assume path is an absolute path to a directory\n flags path args clip_args load_from_directory\n dup 0= if exit else drop then\n\n \\ Next, assume path points to the kernel\n flags path args try_multiple_kernels\n;\n\n: initialize ( addr len -- )\n strdup conf_files .len ! conf_files .addr !\n;\n\n: kernel_options ( -- addr len 1 | 0 )\n s\" kernel_options\" getenv\n dup -1 = if drop 0 else 1 then\n;\n\n: standard_kernel_search ( flags 1 | 0 -- flag )\n local args\n args 0= if 0 0 then\n 2local flags\n s\" kernel\" getenv\n dup -1 = if 0 swap then\n 2local path\n end-locals\n\n path nip -1 = if ( there isn't a \"kernel\" environment variable )\n flags args load_a_kernel\n else\n flags path args 1+ clip_args load_directory_or_file\n then\n;\n\n: load_kernel ( -- ) ( throws: abort )\n kernel_options standard_kernel_search\n abort\" Unable to load a kernel!\"\n;\n\n: set_defaultoptions ( -- )\n s\" kernel_options\" getenv dup -1 = if\n drop\n else\n s\" temp_options\" setenv\n then\n;\n\n: argv[] ( aN uN ... a1 u1 N i -- aN uN ... a1 u1 N ai+1 ui+1 )\n 2dup = if 0 0 exit then\n dup >r\n 1+ 2* ( skip N and ui )\n pick\n r>\n 1+ 2* ( skip N and ai )\n pick\n;\n\n: drop_args ( aN uN ... a1 u1 N -- )\n 0 ?do 2drop loop\n;\n\n: argc\n dup\n;\n\n: queue_argv ( aN uN ... a1 u1 N a u -- a u aN uN ... a1 u1 N+1 )\n >r\n over 2* 1+ -roll\n r>\n over 2* 1+ -roll\n 1+\n;\n\n: unqueue_argv ( aN uN ... a1 u1 N -- aN uN ... a2 u2 N-1 a1 u1 )\n 1- -rot\n;\n\n: strlen(argv)\n dup 0= if 0 exit then\n 0 >r\t\\ Size\n 0 >r\t\\ Index\n begin\n argc r@ <>\n while\n r@ argv[]\n nip\n r> r> rot + 1+\n >r 1+ >r\n repeat\n r> drop\n r>\n;\n\n: concat_argv ( aN uN ... a1 u1 N -- a u )\n strlen(argv) allocate if out_of_memory throw then\n 0 2>r\n\n begin\n argc\n while\n unqueue_argv\n 2r> 2swap\n strcat\n s\" \" strcat\n 2>r\n repeat\n drop_args\n 2r>\n;\n\n: set_tempoptions ( addrN lenN ... addr1 len1 N -- addr len 1 | 0 )\n \\ Save the first argument, if it exists and is not a flag\n argc if\n 0 argv[] drop c@ [char] - <> if\n unqueue_argv 2>r \\ Filename\n 1 >r\t\t\\ Filename present\n else\n 0 >r\t\t\\ Filename not present\n then\n else\n 0 >r\t\t\\ Filename not present\n then\n\n \\ If there are other arguments, assume they are flags\n ?dup if\n concat_argv\n 2dup s\" temp_options\" setenv\n drop free if free_error throw then\n else\n set_defaultoptions\n then\n\n \\ Bring back the filename, if one was provided\n r> if 2r> 1 else 0 then\n;\n\n: get_arguments ( -- addrN lenN ... addr1 len1 N )\n 0\n begin\n \\ Get next word on the command line\n parse-word\n ?dup while\n queue_argv\n repeat\n drop ( empty string )\n;\n\n: load_kernel_and_modules ( args -- flag )\n set_tempoptions\n argc >r\n s\" temp_options\" getenv dup -1 <> if\n queue_argv\n else\n drop\n then\n r> if ( a path was passed )\n load_directory_or_file\n else\n standard_kernel_search\n then\n ?dup 0= if ['] load_modules catch then\n;\n\n: read-password { size | buf len -- }\n size allocate if out_of_memory throw then\n to buf\n 0 to len\n begin\n key\n dup backspace = if\n drop\n len if\n backspace emit bl emit backspace emit\n len 1 - to len\n else\n bell emit\n then\n else\n dup = if cr drop buf len exit then\n [char] * emit\n len size < if\n buf len chars + c!\n else\n drop\n then\n len 1+ to len\n then\n again\n;\n\n\\ Go back to straight forth vocabulary\n\nonly forth also definitions\n\n","old_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\ \n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\n\\ Loader.rc support functions:\n\\\n\\ initialize_support ( -- )\tinitialize global variables\n\\ initialize ( addr len -- )\tas above, plus load_conf_files\n\\ load_conf ( addr len -- )\tload conf file given\n\\ include_conf_files ( -- )\tload all conf files in load_conf_files\n\\ print_syntax_error ( -- )\tprint line and marker of where a syntax\n\\\t\t\t\terror was detected\n\\ print_line ( -- )\t\tprint last line processed\n\\ load_kernel ( -- )\t\tload kernel\n\\ load_modules ( -- )\t\tload modules flagged\n\\\n\\ Exported structures:\n\\\n\\ string\t\t\tcounted string structure\n\\\tcell .addr\t\t\tstring address\n\\\tcell .len\t\t\tstring length\n\\ module\t\t\tmodule loading information structure\n\\\tcell module.flag\t\tshould we load it?\n\\\tstring module.name\t\tmodule's name\n\\\tstring module.loadname\t\tname to be used in loading the module\n\\\tstring module.type\t\tmodule's type\n\\\tstring module.args\t\tflags to be passed during load\n\\\tstring module.beforeload\tcommand to be executed before load\n\\\tstring module.afterload\t\tcommand to be executed after load\n\\\tstring module.loaderror\t\tcommand to be executed if load fails\n\\\tcell module.next\t\tlist chain\n\\\n\\ Exported global variables;\n\\\n\\ string conf_files\t\tconfiguration files to be loaded\n\\ string password\t\tpassword\n\\ cell modules_options\t\tpointer to first module information\n\\ value verbose?\t\tindicates if user wants a verbose loading\n\\ value any_conf_read?\t\tindicates if a conf file was succesfully read\n\\\n\\ Other exported words:\n\\\n\\ strdup ( addr len -- addr' len)\t\t\tsimilar to strdup(3)\n\\ strcat ( addr len addr' len' -- addr len+len' )\tsimilar to strcat(3)\n\\ strlen ( addr -- len )\t\t\t\tsimilar to strlen(3)\n\\ s' ( | string' -- addr len | )\t\t\tsimilar to s\"\n\\ rudimentary structure support\n\n\\ Exception values\n\n1 constant syntax_error\n2 constant out_of_memory\n3 constant free_error\n4 constant set_error\n5 constant read_error\n6 constant open_error\n7 constant exec_error\n8 constant before_load_error\n9 constant after_load_error\n\n\\ I\/O constants\n\n0 constant SEEK_SET\n1 constant SEEK_CUR\n2 constant SEEK_END\n\n0 constant O_RDONLY\n1 constant O_WRONLY\n2 constant O_RDWR\n\n\\ Crude structure support\n\n: structure:\n create here 0 , ['] drop , 0\n does> create here swap dup @ allot cell+ @ execute\n;\n: member: create dup , over , + does> cell+ @ + ;\n: ;structure swap ! ;\n: constructor! >body cell+ ! ;\n: constructor: over :noname ;\n: ;constructor postpone ; swap cell+ ! ; immediate\n: sizeof ' >body @ state @ if postpone literal then ; immediate\n: offsetof ' >body cell+ @ state @ if postpone literal then ; immediate\n: ptr 1 cells member: ;\n: int 1 cells member: ;\n\n\\ String structure\n\nstructure: string\n\tptr .addr\n\tint .len\n\tconstructor:\n\t 0 over .addr !\n\t 0 swap .len !\n\t;constructor\n;structure\n\n\n\\ Module options linked list\n\nstructure: module\n\tint module.flag\n\tsizeof string member: module.name\n\tsizeof string member: module.loadname\n\tsizeof string member: module.type\n\tsizeof string member: module.args\n\tsizeof string member: module.beforeload\n\tsizeof string member: module.afterload\n\tsizeof string member: module.loaderror\n\tptr module.next\n;structure\n\n\\ Internal loader structures\nstructure: preloaded_file\n\tptr pf.name\n\tptr pf.type\n\tptr pf.args\n\tptr pf.metadata\t\\ file_metadata\n\tint pf.loader\n\tint pf.addr\n\tint pf.size\n\tptr pf.modules\t\\ kernel_module\n\tptr pf.next\t\\ preloaded_file\n;structure\n\nstructure: kernel_module\n\tptr km.name\n\t\\ ptr km.args\n\tptr km.fp\t\\ preloaded_file\n\tptr km.next\t\\ kernel_module\n;structure\n\nstructure: file_metadata\n\tint\t\tmd.size\n\t2 member:\tmd.type\t\\ this is not ANS Forth compatible (XXX)\n\tptr\t\tmd.next\t\\ file_metadata\n\t0 member:\tmd.data\t\\ variable size\n;structure\n\nstructure: config_resource\n\tptr cf.name\n\tint cf.type\n0 constant RES_INT\n1 constant RES_STRING\n2 constant RES_LONG\n\t2 cells member: u\n;structure\n\nstructure: config_device\n\tptr cd.name\n\tint cd.unit\n\tint cd.resource_count\n\tptr cd.resources\t\\ config_resource\n;structure\n\nstructure: STAILQ_HEAD\n\tptr stqh_first\t\\ type*\n\tptr stqh_last\t\\ type**\n;structure\n\nstructure: STAILQ_ENTRY\n\tptr stqe_next\t\\ type*\n;structure\n\nstructure: pnphandler\n\tptr pnph.name\n\tptr pnph.enumerate\n;structure\n\nstructure: pnpident\n\tptr pnpid.ident\t\t\t\t\t\\ char*\n\tsizeof STAILQ_ENTRY cells member: pnpid.link\t\\ pnpident\n;structure\n\nstructure: pnpinfo\n\tptr pnpi.desc\n\tint pnpi.revision\n\tptr pnpi.module\t\t\t\t\\ (char*) module args\n\tint pnpi.argc\n\tptr pnpi.argv\n\tptr pnpi.handler\t\t\t\\ pnphandler\n\tsizeof STAILQ_HEAD member: pnpi.ident\t\\ pnpident\n\tsizeof STAILQ_ENTRY member: pnpi.link\t\\ pnpinfo\n;structure\n\n\\ Global variables\n\nstring conf_files\nstring nextboot_conf_file\nstring password\ncreate module_options sizeof module.next allot 0 module_options !\ncreate last_module_option sizeof module.next allot 0 last_module_option !\n0 value verbose?\n0 value nextboot?\n\n\\ Support string functions\n\n: strdup ( addr len -- addr' len )\n >r r@ allocate if out_of_memory throw then\n tuck r@ move\n r>\n;\n\n: strcat { addr len addr' len' -- addr len+len' }\n addr' addr len + len' move\n addr len len' +\n;\n\n: strlen ( addr -- len )\n 0 >r\n begin\n dup c@ while\n 1+ r> 1+ >r repeat\n drop r>\n;\n\n: s' \n [char] ' parse\n state @ if\n postpone sliteral\n then\n; immediate\n\n: 2>r postpone >r postpone >r ; immediate\n: 2r> postpone r> postpone r> ; immediate\n: 2r@ postpone 2r> postpone 2dup postpone 2>r ; immediate\n\n: getenv?\n getenv\n -1 = if false else drop true then\n;\n\n\\ Private definitions\n\nvocabulary support-functions\nonly forth also support-functions definitions\n\n\\ Some control characters constants\n\n7 constant bell\n8 constant backspace\n9 constant tab\n10 constant lf\n13 constant \n\n\\ Read buffer size\n\n80 constant read_buffer_size\n\n\\ Standard suffixes\n\n: load_module_suffix s\" _load\" ;\n: module_loadname_suffix s\" _name\" ;\n: module_type_suffix s\" _type\" ;\n: module_args_suffix s\" _flags\" ;\n: module_beforeload_suffix s\" _before\" ;\n: module_afterload_suffix s\" _after\" ;\n: module_loaderror_suffix s\" _error\" ;\n\n\\ Support operators\n\n: >= < 0= ;\n: <= > 0= ;\n\n\\ Assorted support funcitons\n\n: free-memory free if free_error throw then ;\n\n\\ Assignment data temporary storage\n\nstring name_buffer\nstring value_buffer\n\n\\ Line by line file reading functions\n\\\n\\ exported:\n\\\tline_buffer\n\\\tend_of_file?\n\\\tfd\n\\\tread_line\n\\\treset_line_reading\n\nvocabulary line-reading\nalso line-reading definitions also\n\n\\ File data temporary storage\n\nstring read_buffer\n0 value read_buffer_ptr\n\n\\ File's line reading function\n\nsupport-functions definitions\n\nstring line_buffer\n0 value end_of_file?\nvariable fd\n\nline-reading definitions\n\n: skip_newlines\n begin\n read_buffer .len @ read_buffer_ptr >\n while\n read_buffer .addr @ read_buffer_ptr + c@ lf = if\n read_buffer_ptr char+ to read_buffer_ptr\n else\n exit\n then\n repeat\n;\n\n: scan_buffer ( -- addr len )\n read_buffer_ptr >r\n begin\n read_buffer .len @ r@ >\n while\n read_buffer .addr @ r@ + c@ lf = if\n read_buffer .addr @ read_buffer_ptr + ( -- addr )\n r@ read_buffer_ptr - ( -- len )\n r> to read_buffer_ptr\n exit\n then\n r> char+ >r\n repeat\n read_buffer .addr @ read_buffer_ptr + ( -- addr )\n r@ read_buffer_ptr - ( -- len )\n r> to read_buffer_ptr\n;\n\n: line_buffer_resize ( len -- len )\n >r\n line_buffer .len @ if\n line_buffer .addr @\n line_buffer .len @ r@ +\n resize if out_of_memory throw then\n else\n r@ allocate if out_of_memory throw then\n then\n line_buffer .addr !\n r>\n;\n \n: append_to_line_buffer ( addr len -- )\n line_buffer .addr @ line_buffer .len @\n 2swap strcat\n line_buffer .len !\n drop\n;\n\n: read_from_buffer\n scan_buffer ( -- addr len )\n line_buffer_resize ( len -- len )\n append_to_line_buffer ( addr len -- )\n;\n\n: refill_required?\n read_buffer .len @ read_buffer_ptr =\n end_of_file? 0= and\n;\n\n: refill_buffer\n 0 to read_buffer_ptr\n read_buffer .addr @ 0= if\n read_buffer_size allocate if out_of_memory throw then\n read_buffer .addr !\n then\n fd @ read_buffer .addr @ read_buffer_size fread\n dup -1 = if read_error throw then\n dup 0= if true to end_of_file? then\n read_buffer .len !\n;\n\n: reset_line_buffer\n line_buffer .addr @ ?dup if\n free-memory\n then\n 0 line_buffer .addr !\n 0 line_buffer .len !\n;\n\nsupport-functions definitions\n\n: reset_line_reading\n 0 to read_buffer_ptr\n;\n\n: read_line\n reset_line_buffer\n skip_newlines\n begin\n read_from_buffer\n refill_required?\n while\n refill_buffer\n repeat\n;\n\nonly forth also support-functions definitions\n\n\\ Conf file line parser:\n\\ ::= '='[] |\n\\ []\n\\ ::= {||'_'}\n\\ ::= '\"'{|'\\'}'\"' | \n\\ ::= ASCII 32 to 126, except '\\' and '\"'\n\\ ::= '#'{}\n\\\n\\ exported:\n\\\tline_pointer\n\\\tprocess_conf\n\n0 value line_pointer\n\nvocabulary file-processing\nalso file-processing definitions\n\n\\ parser functions\n\\\n\\ exported:\n\\\tget_assignment\n\nvocabulary parser\nalso parser definitions also\n\n0 value parsing_function\n0 value end_of_line\n\n: end_of_line?\n line_pointer end_of_line =\n;\n\n: letter?\n line_pointer c@ >r\n r@ [char] A >=\n r@ [char] Z <= and\n r@ [char] a >=\n r> [char] z <= and\n or\n;\n\n: digit?\n line_pointer c@ >r\n r@ [char] 0 >=\n r> [char] 9 <= and\n;\n\n: quote?\n line_pointer c@ [char] \" =\n;\n\n: assignment_sign?\n line_pointer c@ [char] = =\n;\n\n: comment?\n line_pointer c@ [char] # =\n;\n\n: space?\n line_pointer c@ bl =\n line_pointer c@ tab = or\n;\n\n: backslash?\n line_pointer c@ [char] \\ =\n;\n\n: underscore?\n line_pointer c@ [char] _ =\n;\n\n: dot?\n line_pointer c@ [char] . =\n;\n\n: skip_character\n line_pointer char+ to line_pointer\n;\n\n: skip_to_end_of_line\n end_of_line to line_pointer\n;\n\n: eat_space\n begin\n space?\n while\n skip_character\n end_of_line? if exit then\n repeat\n;\n\n: parse_name ( -- addr len )\n line_pointer\n begin\n letter? digit? underscore? dot? or or or\n while\n skip_character\n end_of_line? if \n line_pointer over -\n strdup\n exit\n then\n repeat\n line_pointer over -\n strdup\n;\n\n: remove_backslashes { addr len | addr' len' -- addr' len' }\n len allocate if out_of_memory throw then\n to addr'\n addr >r\n begin\n addr c@ [char] \\ <> if\n addr c@ addr' len' + c!\n len' char+ to len'\n then\n addr char+ to addr\n r@ len + addr =\n until\n r> drop\n addr' len'\n;\n\n: parse_quote ( -- addr len )\n line_pointer\n skip_character\n end_of_line? if syntax_error throw then\n begin\n quote? 0=\n while\n backslash? if\n skip_character\n end_of_line? if syntax_error throw then\n then\n skip_character\n end_of_line? if syntax_error throw then \n repeat\n skip_character\n line_pointer over -\n remove_backslashes\n;\n\n: read_name\n parse_name\t\t( -- addr len )\n name_buffer .len !\n name_buffer .addr !\n;\n\n: read_value\n quote? if\n parse_quote\t\t( -- addr len )\n else\n parse_name\t\t( -- addr len )\n then\n value_buffer .len !\n value_buffer .addr !\n;\n\n: comment\n skip_to_end_of_line\n;\n\n: white_space_4\n eat_space\n comment? if ['] comment to parsing_function exit then\n end_of_line? 0= if syntax_error throw then\n;\n\n: variable_value\n read_value\n ['] white_space_4 to parsing_function\n;\n\n: white_space_3\n eat_space\n letter? digit? quote? or or if\n ['] variable_value to parsing_function exit\n then\n syntax_error throw\n;\n\n: assignment_sign\n skip_character\n ['] white_space_3 to parsing_function\n;\n\n: white_space_2\n eat_space\n assignment_sign? if ['] assignment_sign to parsing_function exit then\n syntax_error throw\n;\n\n: variable_name\n read_name\n ['] white_space_2 to parsing_function\n;\n\n: white_space_1\n eat_space\n letter? if ['] variable_name to parsing_function exit then\n comment? if ['] comment to parsing_function exit then\n end_of_line? 0= if syntax_error throw then\n;\n\nfile-processing definitions\n\n: get_assignment\n line_buffer .addr @ line_buffer .len @ + to end_of_line\n line_buffer .addr @ to line_pointer\n ['] white_space_1 to parsing_function\n begin\n end_of_line? 0=\n while\n parsing_function execute\n repeat\n parsing_function ['] comment =\n parsing_function ['] white_space_1 =\n parsing_function ['] white_space_4 =\n or or 0= if syntax_error throw then\n;\n\nonly forth also support-functions also file-processing definitions also\n\n\\ Process line\n\n: assignment_type? ( addr len -- flag )\n name_buffer .addr @ name_buffer .len @\n compare 0=\n;\n\n: suffix_type? ( addr len -- flag )\n name_buffer .len @ over <= if 2drop false exit then\n name_buffer .len @ over - name_buffer .addr @ +\n over compare 0=\n;\n\n: loader_conf_files?\n s\" loader_conf_files\" assignment_type?\n;\n\n: nextboot_flag?\n s\" nextboot_enable\" assignment_type?\n;\n\n: nextboot_conf?\n s\" nextboot_conf\" assignment_type?\n;\n\n: verbose_flag?\n s\" verbose_loading\" assignment_type?\n;\n\n: execute?\n s\" exec\" assignment_type?\n;\n\n: password?\n s\" password\" assignment_type?\n;\n\n: module_load?\n load_module_suffix suffix_type?\n;\n\n: module_loadname?\n module_loadname_suffix suffix_type?\n;\n\n: module_type?\n module_type_suffix suffix_type?\n;\n\n: module_args?\n module_args_suffix suffix_type?\n;\n\n: module_beforeload?\n module_beforeload_suffix suffix_type?\n;\n\n: module_afterload?\n module_afterload_suffix suffix_type?\n;\n\n: module_loaderror?\n module_loaderror_suffix suffix_type?\n;\n\n: set_conf_files\n conf_files .addr @ ?dup if\n free-memory\n then\n value_buffer .addr @ c@ [char] \" = if\n value_buffer .addr @ char+ value_buffer .len @ 2 chars -\n else\n value_buffer .addr @ value_buffer .len @\n then\n strdup\n conf_files .len ! conf_files .addr !\n;\n\n: set_nextboot_conf\n nextboot_conf_file .addr @ ?dup if\n free-memory\n then\n value_buffer .addr @ c@ [char] \" = if\n value_buffer .addr @ char+ value_buffer .len @ 2 chars -\n else\n value_buffer .addr @ value_buffer .len @\n then\n strdup\n nextboot_conf_file .len ! nextboot_conf_file .addr !\n;\n\n: append_to_module_options_list ( addr -- )\n module_options @ 0= if\n dup module_options !\n last_module_option !\n else\n dup last_module_option @ module.next !\n last_module_option !\n then\n;\n\n: set_module_name ( addr -- )\n name_buffer .addr @ name_buffer .len @\n strdup\n >r over module.name .addr !\n r> swap module.name .len !\n;\n\n: yes_value?\n value_buffer .addr @ value_buffer .len @\n 2dup s' \"YES\"' compare >r\n 2dup s' \"yes\"' compare >r\n 2dup s\" YES\" compare >r\n s\" yes\" compare r> r> r> and and and 0=\n;\n\n: find_module_option ( -- addr | 0 )\n module_options @\n begin\n dup\n while\n dup module.name dup .addr @ swap .len @\n name_buffer .addr @ name_buffer .len @\n compare 0= if exit then\n module.next @\n repeat\n;\n\n: new_module_option ( -- addr )\n sizeof module allocate if out_of_memory throw then\n dup sizeof module erase\n dup append_to_module_options_list\n dup set_module_name\n;\n\n: get_module_option ( -- addr )\n find_module_option\n ?dup 0= if new_module_option then\n;\n\n: set_module_flag\n name_buffer .len @ load_module_suffix nip - name_buffer .len !\n yes_value? get_module_option module.flag !\n;\n\n: set_module_args\n name_buffer .len @ module_args_suffix nip - name_buffer .len !\n get_module_option module.args\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_loadname\n name_buffer .len @ module_loadname_suffix nip - name_buffer .len !\n get_module_option module.loadname\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_type\n name_buffer .len @ module_type_suffix nip - name_buffer .len !\n get_module_option module.type\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_beforeload\n name_buffer .len @ module_beforeload_suffix nip - name_buffer .len !\n get_module_option module.beforeload\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_afterload\n name_buffer .len @ module_afterload_suffix nip - name_buffer .len !\n get_module_option module.afterload\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_loaderror\n name_buffer .len @ module_loaderror_suffix nip - name_buffer .len !\n get_module_option module.loaderror\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_environment_variable\n name_buffer .len @\n value_buffer .len @ +\n 5 chars +\n allocate if out_of_memory throw then\n dup 0 ( addr -- addr addr len )\n s\" set \" strcat\n name_buffer .addr @ name_buffer .len @ strcat\n s\" =\" strcat\n value_buffer .addr @ value_buffer .len @ strcat\n ['] evaluate catch if\n 2drop free drop\n set_error throw\n else\n free-memory\n then\n;\n\n: set_nextboot_flag\n yes_value? to nextboot?\n;\n\n: set_verbose\n yes_value? to verbose?\n;\n\n: execute_command\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 - swap char+ swap\n then\n ['] evaluate catch if exec_error throw then\n;\n\n: set_password\n password .addr @ ?dup if free if free_error throw then then\n value_buffer .addr @ c@ [char] \" = if\n value_buffer .addr @ char+ value_buffer .len @ 2 - strdup\n value_buffer .addr @ free if free_error throw then\n else\n value_buffer .addr @ value_buffer .len @\n then\n password .len ! password .addr !\n 0 value_buffer .addr !\n;\n\n: process_assignment\n name_buffer .len @ 0= if exit then\n loader_conf_files?\tif set_conf_files exit then\n nextboot_flag?\tif set_nextboot_flag exit then\n nextboot_conf?\tif set_nextboot_conf exit then\n verbose_flag?\t\tif set_verbose exit then\n execute?\t\tif execute_command exit then\n password?\t\tif set_password exit then\n module_load?\t\tif set_module_flag exit then\n module_loadname?\tif set_module_loadname exit then\n module_type?\t\tif set_module_type exit then\n module_args?\t\tif set_module_args exit then\n module_beforeload?\tif set_module_beforeload exit then\n module_afterload?\tif set_module_afterload exit then\n module_loaderror?\tif set_module_loaderror exit then\n set_environment_variable\n;\n\n\\ free_buffer ( -- )\n\\\n\\ Free some pointers if needed. The code then tests for errors\n\\ in freeing, and throws an exception if needed. If a pointer is\n\\ not allocated, it's value (0) is used as flag.\n\n: free_buffers\n name_buffer .addr @ dup if free then\n value_buffer .addr @ dup if free then\n or if free_error throw then\n;\n\n: reset_assignment_buffers\n 0 name_buffer .addr !\n 0 name_buffer .len !\n 0 value_buffer .addr !\n 0 value_buffer .len !\n;\n\n\\ Higher level file processing\n\nsupport-functions definitions\n\n: process_conf\n begin\n end_of_file? 0=\n while\n reset_assignment_buffers\n read_line\n get_assignment\n ['] process_assignment catch\n ['] free_buffers catch\n swap throw throw\n repeat\n;\n\n: peek_file\n 0 to end_of_file?\n reset_line_reading\n O_RDONLY fopen fd !\n fd @ -1 = if open_error throw then\n reset_assignment_buffers\n read_line\n get_assignment\n ['] process_assignment catch\n ['] free_buffers catch\n fd @ fclose\n;\n \nonly forth also support-functions definitions\n\n\\ Interface to loading conf files\n\n: load_conf ( addr len -- )\n 0 to end_of_file?\n reset_line_reading\n O_RDONLY fopen fd !\n fd @ -1 = if open_error throw then\n ['] process_conf catch\n fd @ fclose\n throw\n;\n\n: print_line\n line_buffer .addr @ line_buffer .len @ type cr\n;\n\n: print_syntax_error\n line_buffer .addr @ line_buffer .len @ type cr\n line_buffer .addr @\n begin\n line_pointer over <>\n while\n bl emit\n char+\n repeat\n drop\n .\" ^\" cr\n;\n\n\\ Debugging support functions\n\nonly forth definitions also support-functions\n\n: test-file \n ['] load_conf catch dup .\n syntax_error = if cr print_syntax_error then\n;\n\n: show-module-options\n module_options @\n begin\n ?dup\n while\n .\" Name: \" dup module.name dup .addr @ swap .len @ type cr\n .\" Path: \" dup module.loadname dup .addr @ swap .len @ type cr\n .\" Type: \" dup module.type dup .addr @ swap .len @ type cr\n .\" Flags: \" dup module.args dup .addr @ swap .len @ type cr\n .\" Before load: \" dup module.beforeload dup .addr @ swap .len @ type cr\n .\" After load: \" dup module.afterload dup .addr @ swap .len @ type cr\n .\" Error: \" dup module.loaderror dup .addr @ swap .len @ type cr\n .\" Status: \" dup module.flag @ if .\" Load\" else .\" Don't load\" then cr\n module.next @\n repeat\n;\n\nonly forth also support-functions definitions\n\n\\ Variables used for processing multiple conf files\n\nstring current_file_name\nvariable current_conf_files\n\n\\ Indicates if any conf file was succesfully read\n\n0 value any_conf_read?\n\n\\ loader_conf_files processing support functions\n\n: set_current_conf_files\n conf_files .addr @ current_conf_files !\n;\n\n: get_conf_files\n conf_files .addr @ conf_files .len @ strdup\n;\n\n: recurse_on_conf_files?\n current_conf_files @ conf_files .addr @ <>\n;\n\n: skip_leading_spaces { addr len pos -- addr len pos' }\n begin\n pos len = if addr len pos exit then\n addr pos + c@ bl =\n while\n pos char+ to pos\n repeat\n addr len pos\n;\n\n: get_file_name { addr len pos -- addr len pos' addr' len' || 0 }\n pos len = if \n addr free abort\" Fatal error freeing memory\"\n 0 exit\n then\n pos >r\n begin\n addr pos + c@ bl <>\n while\n pos char+ to pos\n pos len = if\n addr len pos addr r@ + pos r> - exit\n then\n repeat\n addr len pos addr r@ + pos r> -\n;\n\n: get_next_file ( addr len ptr -- addr len ptr' addr' len' | 0 )\n skip_leading_spaces\n get_file_name\n;\n\n: set_current_file_name\n over current_file_name .addr !\n dup current_file_name .len !\n;\n\n: print_current_file\n current_file_name .addr @ current_file_name .len @ type\n;\n\n: process_conf_errors\n dup 0= if true to any_conf_read? drop exit then\n >r 2drop r>\n dup syntax_error = if\n .\" Warning: syntax error on file \" print_current_file cr\n print_syntax_error drop exit\n then\n dup set_error = if\n .\" Warning: bad definition on file \" print_current_file cr\n print_line drop exit\n then\n dup read_error = if\n .\" Warning: error reading file \" print_current_file cr drop exit\n then\n dup open_error = if\n verbose? if .\" Warning: unable to open file \" print_current_file cr then\n drop exit\n then\n dup free_error = abort\" Fatal error freeing memory\"\n dup out_of_memory = abort\" Out of memory\"\n throw \\ Unknown error -- pass ahead\n;\n\n\\ Process loader_conf_files recursively\n\\ Interface to loader_conf_files processing\n\n: include_conf_files\n set_current_conf_files\n get_conf_files 0\n begin\n get_next_file ?dup\n while\n set_current_file_name\n ['] load_conf catch\n process_conf_errors\n recurse_on_conf_files? if recurse then\n repeat\n;\n\n: get_nextboot_conf_file ( -- addr len )\n nextboot_conf_file .addr @ nextboot_conf_file .len @ strdup\n;\n\n: rewrite_nextboot_file ( -- )\n get_nextboot_conf_file\n O_WRONLY fopen fd !\n fd @ -1 = if open_error throw then\n fd @ s' nextboot_enable=\"NO\" ' fwrite\n fd @ fclose\n;\n\n: include_nextboot_file\n get_nextboot_conf_file\n ['] peek_file catch\n nextboot? if\n get_nextboot_conf_file\n ['] load_conf catch\n process_conf_errors\n ['] rewrite_nextboot_file catch\n then\n;\n\n\\ Module loading functions\n\n: load_module?\n module.flag @\n;\n\n: load_parameters ( addr -- addr addrN lenN ... addr1 len1 N )\n dup >r\n r@ module.args .addr @ r@ module.args .len @\n r@ module.loadname .len @ if\n r@ module.loadname .addr @ r@ module.loadname .len @\n else\n r@ module.name .addr @ r@ module.name .len @\n then\n r@ module.type .len @ if\n r@ module.type .addr @ r@ module.type .len @\n s\" -t \"\n 4 ( -t type name flags )\n else\n 2 ( name flags )\n then\n r> drop\n;\n\n: before_load ( addr -- addr )\n dup module.beforeload .len @ if\n dup module.beforeload .addr @ over module.beforeload .len @\n ['] evaluate catch if before_load_error throw then\n then\n;\n\n: after_load ( addr -- addr )\n dup module.afterload .len @ if\n dup module.afterload .addr @ over module.afterload .len @\n ['] evaluate catch if after_load_error throw then\n then\n;\n\n: load_error ( addr -- addr )\n dup module.loaderror .len @ if\n dup module.loaderror .addr @ over module.loaderror .len @\n evaluate \\ This we do not intercept so it can throw errors\n then\n;\n\n: pre_load_message ( addr -- addr )\n verbose? if\n dup module.name .addr @ over module.name .len @ type\n .\" ...\"\n then\n;\n\n: load_error_message verbose? if .\" failed!\" cr then ;\n\n: load_succesful_message verbose? if .\" ok\" cr then ;\n\n: load_module\n load_parameters load\n;\n\n: process_module ( addr -- addr )\n pre_load_message\n before_load\n begin\n ['] load_module catch if\n dup module.loaderror .len @ if\n load_error\t\t\t\\ Command should return a flag!\n else \n load_error_message true\t\t\\ Do not retry\n then\n else\n after_load\n load_succesful_message true\t\\ Succesful, do not retry\n then\n until\n;\n\n: process_module_errors ( addr ior -- )\n dup before_load_error = if\n drop\n .\" Module \"\n dup module.name .addr @ over module.name .len @ type\n dup module.loadname .len @ if\n .\" (\" dup module.loadname .addr @ over module.loadname .len @ type .\" )\"\n then\n cr\n .\" Error executing \"\n dup module.beforeload .addr @ over module.afterload .len @ type cr\n abort\n then\n\n dup after_load_error = if\n drop\n .\" Module \"\n dup module.name .addr @ over module.name .len @ type\n dup module.loadname .len @ if\n .\" (\" dup module.loadname .addr @ over module.loadname .len @ type .\" )\"\n then\n cr\n .\" Error executing \"\n dup module.afterload .addr @ over module.afterload .len @ type cr\n abort\n then\n\n throw \\ Don't know what it is all about -- pass ahead\n;\n\n\\ Module loading interface\n\n: load_modules ( -- ) ( throws: abort & user-defined )\n module_options @\n begin\n ?dup\n while\n dup load_module? if\n ['] process_module catch\n process_module_errors\n then\n module.next @\n repeat\n;\n\n\\ h00h00 magic used to try loading either a kernel with a given name,\n\\ or a kernel with the default name in a directory of a given name\n\\ (the pain!)\n\n: bootpath s\" \/boot\/\" ;\n: modulepath s\" module_path\" ;\n\n\\ Functions used to save and restore module_path's value.\n: saveenv ( addr len | -1 -- addr' len | 0 -1 )\n dup -1 = if 0 swap exit then\n strdup\n;\n: freeenv ( addr len | 0 -1 )\n -1 = if drop else free abort\" Freeing error\" then\n;\n: restoreenv ( addr len | 0 -1 -- )\n dup -1 = if ( it wasn't set )\n 2drop\n modulepath unsetenv\n else\n over >r\n modulepath setenv\n r> free abort\" Freeing error\"\n then\n;\n\n: clip_args \\ Drop second string if only one argument is passed\n 1 = if\n 2swap 2drop\n 1\n else\n 2\n then\n;\n\nalso builtins\n\n\\ Parse filename from a comma-separated list\n\n: parse-; ( addr len -- addr' len-x addr x )\n over 0 2swap\n begin\n dup 0 <>\n while\n over c@ [char] ; <>\n while\n 1- swap 1+ swap\n 2swap 1+ 2swap\n repeat then\n dup 0 <> if\n 1- swap 1+ swap\n then\n 2swap\n;\n\n\\ Try loading one of multiple kernels specified\n\n: try_multiple_kernels ( addr len addr' len' args -- flag )\n >r\n begin\n parse-; 2>r\n 2over 2r>\n r@ clip_args\n s\" DEBUG\" getenv? if\n s\" echo Module_path: ${module_path}\" evaluate\n .\" Kernel : \" >r 2dup type r> cr\n dup 2 = if .\" Flags : \" >r 2over type r> cr then\n then\n 1 load\n while\n dup 0=\n until\n 1 >r \\ Failure\n else\n 0 >r \\ Success\n then\n 2drop 2drop\n r>\n r> drop\n;\n\n\\ Try to load a kernel; the kernel name is taken from one of\n\\ the following lists, as ordered:\n\\\n\\ 1. The \"bootfile\" environment variable\n\\ 2. The \"kernel\" environment variable\n\\\n\\ Flags are passed, if available. If not, dummy values must be given.\n\\\n\\ The kernel gets loaded from the current module_path.\n\n: load_a_kernel ( flags len 1 | x x 0 -- flag )\n local args\n 2local flags\n 0 0 2local kernel\n end-locals\n\n \\ Check if a default kernel name exists at all, exits if not\n s\" bootfile\" getenv dup -1 <> if\n to kernel\n flags kernel args 1+ try_multiple_kernels\n dup 0= if exit then\n then\n drop\n\n s\" kernel\" getenv dup -1 <> if\n to kernel\n else\n drop\n 1 exit \\ Failure\n then\n\n \\ Try all default kernel names\n flags kernel args 1+ try_multiple_kernels\n;\n\n\\ Try to load a kernel; the kernel name is taken from one of\n\\ the following lists, as ordered:\n\\\n\\ 1. The \"bootfile\" environment variable\n\\ 2. The \"kernel\" environment variable\n\\\n\\ Flags are passed, if provided.\n\\\n\\ The kernel will be loaded from a directory computed from the\n\\ path given. Two directories will be tried in the following order:\n\\\n\\ 1. \/boot\/path\n\\ 2. path\n\\\n\\ The module_path variable is overridden if load is succesful, by\n\\ prepending the successful path.\n\n: load_from_directory ( path len 1 | flags len' path len 2 -- flag )\n local args\n 2local path\n args 1 = if 0 0 then\n 2local flags\n 0 0 2local oldmodulepath\n 0 0 2local newmodulepath\n end-locals\n\n \\ Set the environment variable module_path, and try loading\n \\ the kernel again.\n modulepath getenv saveenv to oldmodulepath\n\n \\ Try prepending \/boot\/ first\n bootpath nip path nip + \n oldmodulepath nip dup -1 = if\n drop\n else\n 1+ +\n then\n allocate\n if ( out of memory )\n 1 exit\n then\n\n 0\n bootpath strcat\n path strcat\n 2dup to newmodulepath\n modulepath setenv\n\n \\ Try all default kernel names\n flags args 1- load_a_kernel\n 0= if ( success )\n oldmodulepath nip -1 <> if\n newmodulepath s\" ;\" strcat\n oldmodulepath strcat\n modulepath setenv\n newmodulepath drop free-memory\n oldmodulepath drop free-memory\n then\n 0 exit\n then\n\n \\ Well, try without the prepended \/boot\/\n path newmodulepath drop swap move\n newmodulepath drop path nip\n 2dup to newmodulepath\n modulepath setenv\n\n \\ Try all default kernel names\n flags args 1- load_a_kernel\n if ( failed once more )\n oldmodulepath restoreenv\n newmodulepath drop free-memory\n 1\n else\n oldmodulepath nip -1 <> if\n newmodulepath s\" ;\" strcat\n oldmodulepath strcat\n modulepath setenv\n newmodulepath drop free-memory\n oldmodulepath drop free-memory\n then\n 0\n then\n;\n\n\\ Try to load a kernel; the kernel name is taken from one of\n\\ the following lists, as ordered:\n\\\n\\ 1. The \"bootfile\" environment variable\n\\ 2. The \"kernel\" environment variable\n\\ 3. The \"path\" argument\n\\\n\\ Flags are passed, if provided.\n\\\n\\ The kernel will be loaded from a directory computed from the\n\\ path given. Two directories will be tried in the following order:\n\\\n\\ 1. \/boot\/path\n\\ 2. path\n\\\n\\ Unless \"path\" is meant to be kernel name itself. In that case, it\n\\ will first be tried as a full path, and, next, search on the\n\\ directories pointed by module_path.\n\\\n\\ The module_path variable is overridden if load is succesful, by\n\\ prepending the successful path.\n\n: load_directory_or_file ( path len 1 | flags len' path len 2 -- flag )\n local args\n 2local path\n args 1 = if 0 0 then\n 2local flags\n end-locals\n\n \\ First, assume path is an absolute path to a directory\n flags path args clip_args load_from_directory\n dup 0= if exit else drop then\n\n \\ Next, assume path points to the kernel\n flags path args try_multiple_kernels\n;\n\n: initialize ( addr len -- )\n strdup conf_files .len ! conf_files .addr !\n;\n\n: kernel_options ( -- addr len 1 | 0 )\n s\" kernel_options\" getenv\n dup -1 = if drop 0 else 1 then\n;\n\n: standard_kernel_search ( flags 1 | 0 -- flag )\n local args\n args 0= if 0 0 then\n 2local flags\n s\" kernel\" getenv\n dup -1 = if 0 swap then\n 2local path\n end-locals\n\n path nip -1 = if ( there isn't a \"kernel\" environment variable )\n flags args load_a_kernel\n else\n flags path args 1+ clip_args load_directory_or_file\n then\n;\n\n: load_kernel ( -- ) ( throws: abort )\n kernel_options standard_kernel_search\n abort\" Unable to load a kernel!\"\n;\n\n: set_defaultoptions ( -- )\n s\" kernel_options\" getenv dup -1 = if\n drop\n else\n s\" temp_options\" setenv\n then\n;\n\n: argv[] ( aN uN ... a1 u1 N i -- aN uN ... a1 u1 N ai+1 ui+1 )\n 2dup = if 0 0 exit then\n dup >r\n 1+ 2* ( skip N and ui )\n pick\n r>\n 1+ 2* ( skip N and ai )\n pick\n;\n\n: drop_args ( aN uN ... a1 u1 N -- )\n 0 ?do 2drop loop\n;\n\n: argc\n dup\n;\n\n: queue_argv ( aN uN ... a1 u1 N a u -- a u aN uN ... a1 u1 N+1 )\n >r\n over 2* 1+ -roll\n r>\n over 2* 1+ -roll\n 1+\n;\n\n: unqueue_argv ( aN uN ... a1 u1 N -- aN uN ... a2 u2 N-1 a1 u1 )\n 1- -rot\n;\n\n: strlen(argv)\n dup 0= if 0 exit then\n 0 >r\t\\ Size\n 0 >r\t\\ Index\n begin\n argc r@ <>\n while\n r@ argv[]\n nip\n r> r> rot + 1+\n >r 1+ >r\n repeat\n r> drop\n r>\n;\n\n: concat_argv ( aN uN ... a1 u1 N -- a u )\n strlen(argv) allocate if out_of_memory throw then\n 0 2>r\n\n begin\n argc\n while\n unqueue_argv\n 2r> 2swap\n strcat\n s\" \" strcat\n 2>r\n repeat\n drop_args\n 2r>\n;\n\n: set_tempoptions ( addrN lenN ... addr1 len1 N -- addr len 1 | 0 )\n \\ Save the first argument, if it exists and is not a flag\n argc if\n 0 argv[] drop c@ [char] - <> if\n unqueue_argv 2>r \\ Filename\n 1 >r\t\t\\ Filename present\n else\n 0 >r\t\t\\ Filename not present\n then\n else\n 0 >r\t\t\\ Filename not present\n then\n\n \\ If there are other arguments, assume they are flags\n ?dup if\n concat_argv\n 2dup s\" temp_options\" setenv\n drop free if free_error throw then\n else\n set_defaultoptions\n then\n\n \\ Bring back the filename, if one was provided\n r> if 2r> 1 else 0 then\n;\n\n: get_arguments ( -- addrN lenN ... addr1 len1 N )\n 0\n begin\n \\ Get next word on the command line\n parse-word\n ?dup while\n queue_argv\n repeat\n drop ( empty string )\n;\n\n: load_kernel_and_modules ( args -- flag )\n set_tempoptions\n argc >r\n s\" temp_options\" getenv dup -1 <> if\n queue_argv\n else\n drop\n then\n r> if ( a path was passed )\n load_directory_or_file\n else\n standard_kernel_search\n then\n ?dup 0= if ['] load_modules catch then\n;\n\n: read-password { size | buf len -- }\n size allocate if out_of_memory throw then\n to buf\n 0 to len\n begin\n key\n dup backspace = if\n drop\n len if\n backspace emit bl emit backspace emit\n len 1 - to len\n else\n bell emit\n then\n else\n dup = if cr drop buf len exit then\n [char] * emit\n len size < if\n buf len chars + c!\n else\n drop\n then\n len 1+ to len\n then\n again\n;\n\n\\ Go back to straight forth vocabulary\n\nonly forth also definitions\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"45fcbd8f6de7adc48fcef017f0e1e1d13ad59a71","subject":"Fixed interpret.","message":"Fixed interpret.\n\n'interpret' has now been fixed, which installs the exception handler and\nreimplements the Read-Evaluate-Loop function.\n","repos":"howerj\/libforth","old_file":"forth.fth","new_file":"forth.fth","new_contents":"#!.\/forth \n( ==================================================================== )\n( ==================================================================== )\n( ==================================================================== )\n( \n\tTHIS CODE IS CURRENTLY NON FUNCTIONAL\n\tTHIS CODE IS CURRENTLY NON FUNCTIONAL\n\tTHIS CODE IS CURRENTLY NON FUNCTIONAL\n\tTHIS CODE IS CURRENTLY NON FUNCTIONAL\n\tTHIS CODE IS CURRENTLY NON FUNCTIONAL\n\n\tThis is due to a large change in the interpreter, it will\n\ttake time to fix this, however it will be an improvement.\n)\n( ==================================================================== )\n( ==================================================================== )\n( ==================================================================== )\n( ==================================================================== )\n( \nWelcome to libforth, A dialect of Forth. Like all versions of Forth this\nversion is a little idiosyncratic, but how the interpreter works is\ndocumented here and in various other files.\n\nThis file contains most of the start up code, some basic start up code\nis executed in the C file as well which makes programming at least bearable.\nMost of Forth is programmed in itself, which may seem odd if your back\nground in programming comes from more traditional language [such as C],\nalthough less so if you know already know lisp.\n\nFor more information about this interpreter and Forth see:\n\thttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\treadme.md : for a manual for this interpreter\n\tlibforth.h : for information about the C API\n\tlibforth.c : for the interpreter itself\n\tunit.c : a series of unit tests against libforth.c\n\tunit.fth : a series of unit tests against this file\n\nThe interpreter and this code originally descend from a Forth interpreter\nwritten in 1992 for the International obfuscated C Coding Competition\n\nSee:\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\nThe manual for the interpreter should be read first before looking into this\ncode. It is important to understand the execution model of Forth, especially\nthe differences between command and compile mode, and how immediate and compiling\nwords work.\n\nThe structure of this file is as follows:\n\n * Basic Word Set\n * Extended Word Set\n * CREATE DOES>\n * DO...LOOP\n * CASE statements\n * Conditional Compilation\n * Endian Words\n * Misc words\n * Random Numbers\n * ANSI Escape Codes\n * Prime Numbers\n * Debugging info\n * Files\n * Blocks\n * Matcher\n * Cons Cells\n * Miscellaneous\n * Core utilities\n\nEach of these sections is clearly labeled and they are generally in dependency order.\n\nUnfortunately the code in this file is not as portable as it could be, it makes\nassumptions about the size of cells provided by the virtual machine, which will\ntake time to rectify. Some of the constructs are subtly different from the\nDPANs Forth specification, which is usually noted. Eventually this should\nalso be fixed.)\n\n( ========================== Basic Word Set ================================== )\n\n( \nWe'll begin by defining very simple words we can use later, these a very\nbasic words, that perform simple tasks, they will not require much explanation.\n\nEven though the words are simple, their stack comment and a description for\nthem will still be included so external tools can process and automatically\nextract the document string for a given work.\n)\n\n: 1+ ( x -- x : increment a number ) \n\t1 + ;\n\n: 1- ( x -- x : decrement a number ) \n\t1 - ;\n\n: chars ( c-addr -- addr : convert a character address to an address )\n\tsize \/ ; \n\n: chars> ( addr -- c-addr: convert an address to a character address )\n\tsize * ; \n\n: tab ( -- : print a tab character to current output device )\n\t9 emit ;\n\n: 0= ( x -- bool : is 'x' equal to zero? )\n\t0 = ;\n\n: not ( x -- bool : is 'x' true? )\n\t0= ;\n\n: <> ( x x -- bool : not equal )\n\t= 0= ;\n\n: logical ( x -- bool : turn a value into a boolean ) \n\tnot not ;\n\n: :: ( -- : compiling version of ':' )\n\t[ find : , ] ;\n\n: '\\n' ( -- n : push the newline character )\n\t10 ;\n\n: cr ( -- : emit a newline character )\n\t'\\n' emit ;\n\n: hidden-mask ( -- x : pushes mask for the hide bit in a words MISC field )\n\t0x80 ;\n\n: instruction-mask ( -- x : pushes mask for the first code word in a words MISC field )\n\t0x7f ;\n\n: hidden? ( PWD -- PWD bool : is a word hidden, given the words PWD field ) \n\tdup 1+ @ hidden-mask and logical ;\n\n: dolist ( -- x : run code word, threaded code interpreter instruction )\n\t1 ; \n\n: dolit ( -- x : location of special \"push\" word )\n\t2 ;\n\n: 2, ( x x -- : write two values into the dictionary )\n\t, , ;\n\n: [literal] ( x -- : write a literal into the dictionary )\n\tdolit 2, ; \n\n: literal ( x -- : immediately write a literal into the dictionary )\n\timmediate [literal] ;\n\n: sliteral immediate ( I: c-addr u --, Run: -- c-addr u )\n\tswap [literal] [literal] ;\n\n( space saving measure )\n-1 : -1 literal ;\n 0 : 0 literal ;\n 1 : 1 literal ;\n 2 : 2 literal ;\n 3 : 3 literal ;\n\n: min-signed-integer ( -- x : push the minimum signed integer value )\n\t[ -1 -1 1 rshift invert and ] literal ;\n\n: max-signed-integer ( -- x : push the maximum signed integer value )\n\t[ min-signed-integer invert ] literal ;\n\n: < ( x1 x2 -- bool : signed less than comparison )\n\t- dup if max-signed-integer u> else logical then ;\n\n: > ( x1 x2 -- bool : signed greater than comparison )\n\t- dup if max-signed-integer u< else logical then ;\n\n: 2literal immediate ( x x -- : immediate write two literals into the dictionary )\n\tswap [literal] [literal] ;\n\n: latest ( get latest defined word )\n\tpwd @ ; \n\n: stdin ( -- fileid : push the fileid for the standard input channel ) \n\t`stdin @ ;\n\n: stdout ( -- fileid : push the fileid for the standard output channel ) \n\t`stdout @ ;\n\n: stderr ( -- fileid : push the fileid for the standard error channel ) \n\t`stderr @ ;\n\n: stdin? ( -- bool : are we reading from standard input )\n\t`fin @ stdin = ;\n\n: false ( -- x : push the value representing false )\n\t0 ;\n\n: true ( -- x : push the value representing true )\n\t-1 ;\n\n: *+ ( x1 x2 x3 -- x ) \n\t* + ;\n\t\n: 2- ( x -- x : decrement by two )\n\t2 - ( x -- x ) ;\n\n: 2+ ( x -- x : increment by two )\n\t2 + ( x -- x ) ;\n\n: 3+ ( x -- x : increment by three )\n\t3 + ( x -- x ) ;\n\n: 2* ( x -- x : multiply by two )\n\t1 lshift ( x -- x ) ;\n\n: 2\/ ( x -- x : divide by two )\n\t1 rshift ( x -- x ) ;\n\n: 4* ( x -- x : multiply by four )\n\t2 lshift ( x -- x ) ;\n\n: 4\/ ( x -- x : divide by four )\n\t2 rshift ( x -- x ) ;\n\n: 8* ( x -- x : multiply by eight )\n\t3 lshift ( x -- x ) ;\n\n: 8\/ ( x -- x : divide by eight )\n\t3 rshift ( x -- x ) ;\n\n: 256* ( x -- x : multiply by 256 )\n\t8 lshift ( x -- x ) ;\n\n: 256\/ ( x -- x : divide by 256 )\n\t8 rshift ( x -- x ) ;\n\n: 2dup ( x1 x2 -- x1 x2 x1 x2 : duplicate two values )\n\tover over ;\n\n: mod ( x u -- x : calculate the remainder of x divided by u ) \n\t2dup \/ * - ;\n\n( @todo implement um\/mod in the VM, then use this to implement \/ and mod )\n: um\/mod ( x1 x2 -- rem quot : calculate the remainder and quotient of x1 divided by x2 ) \n\t2dup \/ >r mod r> ;\n\n: *\/ ( x1 x2 x3 -- x4 : multiply then divide, @warning this does not use a double cell for the multiply )\n\t * \/ ; \n\n: char ( -- x : read in a character from the input steam )\n\tkey drop key ;\n\n: [char] ( -- x : immediately read in a character from the input stream )\n\timmediate char [literal] ;\n\n: postpone ( -- : postpone execution of the following immediate word )\n\timmediate find , ;\n\n: compose ( xt1 xt2 -- xt3 : create a new function from two xt-tokens )\n\t>r >r ( save execution tokens )\n\tpostpone :noname ( )\n\tr> , ( write first token )\n\tr> , ( write second token )\n\tpostpone ; ; ( terminate new :noname )\n\n: unless ( bool -- : like 'if' but execute clause if false )\n\timmediate ' 0= , postpone if ;\n\n: endif ( synonym for 'then' ) \n\timmediate postpone then ;\n\n: cell+ ( a-addr1 -- a-addr2 ) \n\t1+ ;\n\n: cells ( n1 -- n2 ) \n\timmediate ;\n\n: cell ( -- u : defined as 1 cells )\n\t1 cells ;\n\n: address-unit-bits ( -- x : push the number of bits in an address )\n\t[ cell size 8* * ] literal ;\n\n: negative? ( x -- bool : is a number negative? )\n\t[ 1 address-unit-bits 1- lshift ] literal and logical ;\n\n: mask-byte ( x -- x : generate mask byte ) \n\t8* 255 swap lshift ;\n\n: select-byte ( u i -- c ) \n\t8* rshift 0xff and ;\n\n: char+ ( c-addr -- c-addr : increment a character address by the size of one character ) \n\t1+ ;\n\n: 2chars ( c-addr1 c-addr2 -- addr addr : convert two character addresses to two cell addresses ) \n\tchars swap chars swap ;\n\n: 2chars> ( addr addr -- c-addr c-addr: convert two cell addresses to two character addresses )\n\tchars> swap chars> swap ;\n\n: hex ( -- : print out hex ) \n\t16 base ! ;\n\n: octal ( -- : print out octal ) \n\t8 base ! ;\n\n: binary ( -- : print out binary ) \n\t2 base ! ;\n\n: decimal ( -- : print out decimal ) \n\t0 base ! ;\n\n: negate ( x -- x ) \n\t-1 * ;\n\n: abs ( x -- u : return the absolute value of a number )\n\tdup negative? if negate then ;\n\n: square ( x -- x ) \n\tdup * ;\n\n: sum-of-squares ( a b -- c : compute a^2 + b^2 to get c )\n\tsquare swap square + ;\n\n: drup ( x y -- x x ) \n\tdrop dup ;\n\n: +! ( x addr -- : add x to a value stored at addr ) \n\ttuck @ + swap ! ;\n\n: 1+! ( addr -- : increment a value at an address ) \n\t1 swap +! ;\n\n: 1-! ( addr -- : decrement a value at an address ) \n\t-1 swap +! ;\n\n: toggle ( addr u -- : complement the value at address with the bit pattern u ) \n\tover @ xor swap ! ;\n\n: lsb ( x -- x : mask off the least significant byte of a cell ) \n\t255 and ;\n\n: \\ ( -- : immediate word, used for single line comments )\n\timmediate begin key '\\n' = until ;\n\n: ?dup ( x -- ? ) \n\tdup if dup then ;\n\n: min ( x y -- min : return the minimum of two integers ) \n\t2dup < if drop else swap drop then ;\n\n: max ( x y -- max : return the maximum of two integers ) \n\t2dup > if drop else swap drop then ;\n\n: limit ( x min max -- x : limit x with a minimum and maximum )\n\trot min max ;\n\n: >= ( x y -- bool ) \n\t< not ;\n\n: <= ( x y -- bool ) \n\t> not ;\n\n: 2@ ( a-addr -- x1 x2 : load two consecutive memory cells )\n\tdup 1+ @ swap @ ;\n\n: 2! ( x1 x2 a-addr -- : store two values as two consecutive memory cells )\n\t2dup ! nip 1+ ! ;\n\n: r@ ( -- x, R: x -- )\n\tr> r @ swap >r ;\n\n: rp@ ( -- x, R: x -- )\n\tr> r @ swap >r ;\n\n( @todo r!, rp! )\n\n: 0> ( x -- bool )\n\t0 > ;\n\n: 0< ( x -- bool )\n\t0 < ;\n\n: 0<> ( x -- bool )\n\t0 <> ;\n\n: signum ( x -- -1 | 0 | 1 : )\n\tdup 0< if drop -1 exit then\n\t 0> if 1 exit then\n\t0 ;\n\n: nand ( x x -- x : bitwise NAND ) \n\tand invert ;\n\n: odd ( x -- bool : is 'x' odd? )\n\t1 and ;\n\n: even ( x -- bool : is 'x' even? )\n\todd not ;\n\n: nor ( x x -- x : bitwise NOR ) \n\tor invert ;\n\n: ms ( u -- : wait at least 'u' milliseconds ) \n\tclock + begin dup clock u< until drop ;\n\n: sleep ( u -- : sleep for 'u' seconds )\n\t1000 * ms ;\n\n: align ( addr -- addr : align an address, nop in this implemented )\n\timmediate ; \n\n: ) ( -- : do nothing, this allows easy commenting out of code )\n\timmediate ;\n\n: bell ( -- : emit an ASCII BEL character ) \n\t7 emit ;\n\n: b\/buf ( -- u : bytes per buffer ) \n\t1024 ;\n\n: .d ( x -- x : debug print ) \n\tdup . ;\n\n: compile, ( x -- : )\n\t, ;\n\n: >mark ( -- : write a hole into the dictionary and push a pointer to it ) \n\there 0 , ;\n\n: r - r> u< ;\n\n: invalidate ( -- : invalidate this Forth core )\n\t1 `invalid ! ;\n\n: signed ( x -- bool : return true if sign bit set ) \n\t[ 1 size 8 * 1- lshift ] literal and logical ;\n\n: u>= ( x y -- bool : unsigned greater than or equal to )\n\t2dup u> >r = r> or ;\n\n: u<= ( x y -- bool : unsigned less than or equal to )\n\tu>= not ;\n\n: rdrop ( R: x -- : drop a value from the return stack )\n\tr> ( get caller's return address )\n\tr> ( get value to drop )\n\tdrop ( drop it like it's hot )\n\t>r ; ( return return address )\n\n: rdup\n\tr> ( get caller's return address )\n\tr> ( get value to duplicate )\n\tdup ( ... )\n\t>r >r >r ; ( make it all work )\n\n: again immediate\n\t( loop unconditionally in a begin-loop:\n\t\tbegin ... again )\n\t' branch , ;\n\n: source ( -- c-addr u )\n\t#tib ( size of input buffer, in characters )\n\ttib ; ( start of input buffer, in characters )\n\n: stdin?\n\t`fin @ `stdin @ = ;\n\n: source-id ( -- 0 | -1 | file-id )\n\t( \t\n\tValue Input Source\n\t-1 String\n\t0 Reading from user input \/ standard in\n\tfile-id )\n\t`source-id @ \n\t0= if\n\t\tstdin? if 0 else `fin @ then\n\telse\n\t\t-1\n\tthen ;\n\n: under ( x1 x2 -- x1 x1 x2 )\n\t>r dup r> ;\n\n: 2nip ( n1 n2 n3 n4 -- n3 n4 ) \n\t>r >r 2drop r> r> ;\n\n: 2over ( n1 n2 n3 n4 \u2013 n1 n2 n3 n4 n1 n2 )\n\t>r >r 2dup r> swap >r swap r> r> -rot ;\n\n: 2swap ( n1 n2 n3 n4 \u2013 n3 n4 n1 n2 )\n\t>r -rot r> -rot ;\n\n: 2tuck ( n1 n2 n3 n4 \u2013 n3 n4 n1 n2 n3 n4 )\n\t2swap 2over ;\n\n: 3drop ( x1 x2 x3 -- )\n\t2drop ;\n\n: nos1+ ( x1 x2 -- x1+1 x2 : increment the next variable on that stack )\n\tswap 1+ swap ;\n\n: ?dup-if immediate ( x -- x | - : ?dup and if rolled into one! )\n\t' ?dup , postpone if ;\n\n: ?if ( -- : non destructive if ) \n\timmediate ' dup , postpone if ;\n\n: hide ( token -- hide-token : this hides a word from being found by the interpreter )\n\t?dup-if\n\t\tdup @ hidden-mask or swap tuck ! exit\n\tthen 0 ;\n\n: hider ( WORD -- : hide with drop ) \n\tfind dup if hide then drop ;\n\n: reveal ( hide-token -- : reveal a hidden word ) \n\tdup @ hidden-mask invert and swap ! ;\n\n: original-exit \n\t[ find exit ] literal ;\n\n: exit ( -- : this will define a second version of exit, ';' will\n\tuse the original version, whilst everything else will\n\tuse this version, allowing us to distinguish between\n\tthe end of a word definition and an early exit by other\n\tmeans in \"see\" \n\t@todo Get rid of this, this is going to slow the interpreter\n\tdown *a lot*, for very little gain! )\n\t[ find exit hide ] rdrop exit [ reveal ] ;\n\n: ?exit ( x -- : exit current definition if not zero ) \n\tif rdrop exit then ;\n\n: number? ( c -- f : is character a number? )\n\t[char] 0 [ char 9 1+ ] literal within ;\n\n: lowercase? ( c -- f : is character lower case? )\n\t[char] a [ char z 1+ ] literal within ;\n\n: uppercase? ( C -- f : is character upper case? )\n\t[char] A [ char Z 1+ ] literal within ;\n\n: alpha? ( C -- f : is character part of the alphabet? )\n\tdup lowercase? swap uppercase? or ;\n\n: alphanumeric? ( C -- f : is character alphabetic or a number ? )\n\tdup alpha? swap number? or ;\n\n: printable? ( c -- bool : is printable, excluding new lines and tables )\n\t32 127 within ;\n\n: >upper ( c -- C : convert char to uppercase iff lower case )\n\tdup lowercase? if bl xor then ;\n\n: >lower ( C -- c : convert char to lowercase iff upper case )\n\tdup uppercase? if bl xor then ;\n\n: <=> ( x y -- z : spaceship operator! )\n\t2dup\n\t> if 2drop -1 exit then\n\t< ;\n\n: start-address ( -- c-addr : push the start address )\n\t`start-address @ ;\n\n: >real-address ( c-addr -- c-addr : convert an interpreter address to a real address )\n\tstart-address - ;\n\n: real-address> ( c-addr -- c-addr : convert a real address to an interpreter address )\n\tstart-address + ;\n\n: peek ( c-addr -- char : peek at real memory )\n\t>real-address c@ ;\n\n: poke ( char c-addr -- : poke a real memory address )\n\t>real-address c! ;\n\n: die! ( x -- : controls actions when encountering certain errors )\n\t`error-handler ! ;\n\n: start! ( cfa -- : set the word to execute at startup )\n\t`instruction ! ;\t\n\n: warm ( -- : restart the interpreter, warm restart )\n\t1 restart ;\n\n: trip ( x -- x x x : triplicate a number ) \n\tdup dup ;\n\n: roll ( xu xu-1 ... x0 u -- xu-1 ... x0 xu : move u+1 items on the top of the stack by u )\n\tdup 0 >\n\tif\n\t\tswap >r 1- roll r> swap\n\telse\n\t\tdrop\n\tthen ;\n\n: 2rot ( n1 n2 n3 n4 n5 n6 \u2013 n3 n4 n5 n6 n1 n2 )\n\t5 roll 5 roll ;\n\n: s>d ( x -- d : convert a signed value to a double width cell )\n\t( @note the if...else...then is only necessary as this Forths\n\tbooleans are 0 and 1, not 0 and -1 as it usually is )\n\tdup 0< if -1 else 0 then ;\n\n: trace ( level -- : set tracing level )\n\t`debug ! ;\n\n: verbose ( -- : get the log level )\n\t`debug @ ;\n\n: #pad ( -- u : offset into pad area )\n\t64 ;\n\n: pad\n\t( the pad is used for temporary storage, and moves\n\talong with dictionary pointer, always in front of it )\n\there #pad + ;\n\n: count ( c-addr1 -- c-addr2 u : get a string whose first char is its length )\n\tdup c@ nos1+ ;\n\n: bounds ( x y -- y+x x : make an upper and lower bound )\n\tover + swap ;\n\n: aligned ( unaligned -- aligned : align a pointer )\n\t[ size 1- ] literal + \n\t[ size 1- ] literal invert and ;\n\n\n( ================================== DUMP ================================== )\n: newline ( x -- x+1 : print a new line every fourth value )\n\tdup 3 and 0= if cr then 1+ ;\n\n: address ( num count -- count : print current address we are dumping every fourth value )\n\tdup >r\n\t1- 3 and 0= if . [char] : emit space else drop then\n\tr> ;\n\n: dump ( start count -- : print the contents of a section of memory )\n\tbase @ >r ( save current base )\n\thex ( switch to hex mode )\n\t1 >r ( save counter on return stack )\n\tover + swap ( calculate limits: start start+count )\n\tbegin \n\t\t2dup u> ( stop if gone past limits )\n\twhile \n\t\tdup r> address >r\n\t\tdup @ . 1+ \n\t\tr> newline >r\n\trepeat \n\tr> drop\n\tr> base !\n\t2drop ;\n\nhider newline\nhider address \n( ================================== DUMP ================================== )\n\n: cfa immediate ( find-address -- cfa )\n\t( Given the address of the PWD field of a word this\n\tfunction will return an execution token for the word )\n\t( @todo if < dictionary start PWD is invalid )\n\t ;\n\n: >body ( xt -- a-addr : a-addr is data field of a CREATEd word )\n\tcfa 5 + ;\n\n( @todo non-compliant, fix )\n: ['] immediate find [literal] ;\n\n: execute ( xt -- : given an execution token, execute the word )\n\t( create a word that pushes the address of a hole to write to\n\ta literal takes up two words, '!' takes up one, that's right,\n\tsome self modifying code! )\n\t\\ 1- ( execution token expects pointer to PWD field, it does not\n\t\\ \tcare about that field however, and increments past it )\n\t[ here 3+ literal ] ( calculate place to write to )\n\t! ( write an execution token to a hole )\n\t[ 0 , ] ; ( this is the hole we write )\n\n( See: http:\/\/lars.nocrew.org\/dpans\/dpans9.htm\n Code Reserved for\n ---- ------------\n -1 ABORT\n -2 ABORT\"\n -3 stack overflow\n -4 stack underflow\n -5 return stack overflow\n -6 return stack underflow\n -7 do-loops nested too deeply during execution\n -8 dictionary overflow\n -9 invalid memory address\n -10 division by zero\n -11 result out of range\n -12 argument type mismatch\n -13 undefined word\n -14 interpreting a compile-only word\n -15 invalid FORGET\n -16 attempt to use zero-length string as a name\n -17 pictured numeric output string overflow\n -18 parsed string overflow\n -19 definition name too long\n -20 write to a read-only location\n -21 unsupported operation [e.g., AT-XY on a\n too-dumb terminal]\n -22 control structure mismatch\n -23 address alignment exception\n -24 invalid numeric argument\n -25 return stack imbalance\n -26 loop parameters unavailable\n -27 invalid recursion\n -28 user interrupt\n -29 compiler nesting\n -30 obsolescent feature\n -31 >BODY used on non-CREATEd definition\n -32 invalid name argument [e.g., TO xxx]\n -33 block read exception\n -34 block write exception\n -35 invalid block number\n -36 invalid file position\n -37 file I\/O exception\n -38 non-existent file\n -39 unexpected end of file\n -40 invalid BASE for floating point conversion\n -41 loss of precision\n -42 floating-point divide by zero\n -43 floating-point result out of range\n -44 floating-point stack overflow\n -45 floating-point stack underflow\n -46 floating-point invalid argument\n -47 compilation word list deleted\n -48 invalid POSTPONE\n -49 search-order overflow\n -50 search-order underflow\n -51 compilation word list changed\n -52 control-flow stack overflow\n -53 exception stack overflow\n -54 floating-point underflow\n -55 floating-point unidentified fault\n -56 QUIT\n -57 exception in sending or receiving a character\n -58 [IF], [ELSE], or [THEN] exception )\n\n( @todo integrate catch\/throw into the interpreter as primitives )\n: catch ( xt -- exception# | 0 : return addr on stack )\n\tsp@ >r ( xt : save data stack pointer )\n\t`handler @ >r ( xt : and previous handler )\n\tr@ `handler ! ( xt : set current handler )\n\texecute ( execute returns if no throw )\n\tr> `handler ! ( restore previous handler )\n\tr> drop ( discard saved stack ptr )\n\t0 ; ( 0 : normal completion )\n\n( @todo use this everywhere )\n: throw ( ??? exception# -- ??? exception# )\n\t?dup-if ( exc# \\ 0 throw is no-op )\n\t\t`handler @ r ! ( exc# : restore prev return stack )\n\t\tr> `handler ! ( exc# : restore prev handler )\n\t\tr> swap >r ( saved-sp : exc# on return stack )\n\t\tsp! drop r> ( exc# : restore stack )\n\t\t( return to the caller of catch because return )\n\t\t( stack is restored to the state that existed )\n\t\t( when catch began execution )\n\tthen ; \n\n: interpret \n\tbegin \n\t' read catch \n\t?dup-if [char] ! emit tab . cr then ( exception handler of last resort )\n\tagain ;\n\n: [interpret] \n\timmediate interpret ;\n\n\ninterpret ( use the new interpret word, which can catch exceptions )\n\nfind [interpret] cell+ start! ( the word executed on restart is now our new word )\n\n\n( ========================== Basic Word Set ================================== )\n\n( ========================== Extended Word Set =============================== )\n\n: log2 ( x -- log2 )\n\t( Computes the binary integer logarithm of a number,\n\tzero however returns itself instead of reporting an error )\n\t0 swap\n\tbegin\n\t\tnos1+ 2\/ dup 0=\n\tuntil\n\tdrop 1- ;\n\n: time ( \" ccc\" -- n : time the number of milliseconds it takes to execute a word )\n\tclock >r\n\tfind execute\n\tclock r> - ;\n\n: rdepth\n\tmax-core `stack-size @ - r @ swap - ;\n\n( defer...is is probably not standards compliant, it is still neat! Also, there\n is no error handling if \"find\" fails... )\n: (do-defer) ( -- self : pushes the location into which it is compiled )\n\tr> dup >r 1- ;\n\n: defer ( \" ccc\" -- , Run Time -- location : \n\tcreates a word that pushes a location to write an execution token into )\n\t:: ' (do-defer) , postpone ; ;\n\n: is ( location \" ccc\" -- : make a deferred word execute a word ) \n\tfind cfa swap ! ;\n\n\nhider (do-defer)\n\n( The \"tail\" function implements tail calls, which is just a jump\nto the beginning of the words definition, for example this\nword will never overflow the stack and will print \"1\" followed\nby a new line forever,\n\n\t: forever 1 . cr tail ;\n\nWhereas\n\n\t: forever 1 . cr recurse ;\n\nor\n\n\t: forever 1 . cr forever ;\n\nWould overflow the return stack. )\n\nhider tail\n: tail ( -- : perform tail recursion in current word definition )\n\timmediate\n\tlatest cell+\n\t' branch ,\n\there - cell+ , ;\n\n: recurse immediate\n\t( This function implements recursion, although this interpreter\n\tallows calling a word directly. If used incorrectly this will\n\tblow up the return stack.\n\n\tWe can test \"recurse\" with this factorial function:\n\t : factorial dup 2 < if drop 1 exit then dup 1- recurse * ; )\n\tlatest cell+ , ;\n\n: factorial ( x -- x : compute the factorial of a number )\n\tdup 2 < if drop 1 exit then dup 1- recurse * ;\n\n: myself ( -- : myself is a synonym for recurse ) \n\timmediate postpone recurse ;\n\n: gcd ( x1 x2 -- x : greatest common divisor )\n\tdup if tuck mod tail then drop ;\n\n( ========================== Extended Word Set =============================== )\n\n( The words described here on out get more complex and will require more\nof an explanation as to how they work. )\n\n( ========================== CREATE DOES> ==================================== )\n\n( The following section defines a pair of words \"create\" and \"does>\" which\nare a powerful set of words that can be used to make words that can create\nother words. \"create\" has both run time and compile time behavior, whilst\n\"does>\" only works at compile time in conjunction with \"create\". These two\nwords can be used to add constants, variables and arrays to the language,\namongst other things.\n\nA simple version of create is as follows\n\n\t: create :: 2 , here 2 + , ' exit , 0 state ! ;\n\nBut this version is much more limited.\n\n\"create\"...\"does>\" is one of the constructs that makes Forth Forth, it\nallows the creation of words which can define new words in themselves,\nand thus allows us to extend the language easily.\n)\n\n: write-quote ( -- : A word that writes ' into the dictionary )\n\t['] ' , ; \n\n: write-exit ( -- : A word that write exit into the dictionary )\n\toriginal-exit , ;\n\n: write-compile, ( -- : A word that writes , into the dictionary ) \n\t' , , ;\n\n: state! ( bool -- : set the compilation state variable ) \n\tstate ! ;\n\n: command-mode ( -- : put the interpreter into command mode )\n\tfalse state! ;\n\n: command-mode-create ( create a new work that pushes its data field )\n\t:: ( compile a word )\n\tdolit , ( write push into new word )\n\there 2+ , ( push a pointer to data field )\n\tpostpone ; ; ( write exit and switch to command mode )\n\n: mark write-compile, ( Write in a place holder 0 and push a pointer to to be used by does> )\n\twrite-quote write-exit write-compile, ( Write in an exit in the word we're compiling. )\n\t['] command-mode , ; ( Make sure to change the state back to command mode )\n\n: create immediate ( create word is quite a complex forth word )\n\tstate @ \n\tif \n\t\tpostpone ( hole-to-patch -- )\n\timmediate\n\twrite-exit ( we don't want the defining word to exit, but the *defined* word to )\n\there swap ! ( patch in the code fields to point to )\n\tdolist , ; ( write a run in )\n\nhider write-quote\nhider write-compile,\n\n( Now that we have create...does> we can use it to create arrays, variables\nand constants, as we mentioned before. )\n\n: array ( u c\" xxx\" -- : create a named array of length u ) \n\tcreate allot does> + ;\n\n: variable ( x c\" xxx\" -- : create a variable will initial value of x )\n\tcreate , does> ;\n\n: constant ( x c\" xxx\" -- : create a constant with value of x ) \n\tcreate , does> @ ;\n\n: table ( u c\" xxx\" --, Run Time: -- addr u : create a named table )\n\tcreate dup , allot does> dup @ ;\n\n: string ( u c\" xxx\" --, Run Time: -- addr u : create a named table )\n\tcreate dup , chars allot does> dup @ swap 1+ chars> swap ;\n\n\\ : +field \\ n <\"name\"> -- ; exec: addr -- 'addr\n\\ create over , +\n\\ does> @ + ;\n\\ \n\\ : begin-structure \\ -- addr 0 ; -- size\n\\ \tcreate\n\\ \there 0 0 , \\ mark stack, lay dummy\n\\ \tdoes> @ ; \\ -- rec-len\n\\ \n\\ : end-structure \\ addr n --\n\\ swap ! ; \\ set len \n\\ \n\\ begin-structure point\n\\ \tpoint +field p.x\n\\ \tpoint +field p.y\n\\ end-structure\n\\ \n\\ This should work...\n\\ : buffer: ( u c\" xxx\" --, Run Time: -- addr )\n\\\tcreate allot ;\n\n: 2constant \n\tcreate , , does> dup 1+ @ swap @ ;\n\n: 2variable \n\tcreate , , does> ;\n\n: enum ( x \" ccc\" -- x+1 : define a series of enumerations )\n\tdup constant 1+ ; \n\n( ========================== CREATE DOES> ==================================== )\n\n( ========================== DO...LOOP ======================================= )\n\n( The following section implements Forth's do...loop constructs, the\nword definitions are quite complex as it involves a lot of juggling of\nthe return stack. Along with begin...until do loops are one of the\nmain looping constructs. \n\nUnlike begin...until do accepts two values a limit and a starting value,\nthey are also words only to be used within a word definition, some Forths\nextend the semantics so looping constructs operate in command mode, this\nForth does not do that as it complicates things unnecessarily.\n\nExample:\n\t\n\t: example-1 10 1 do i . i 5 > if cr leave then loop 100 . cr ; \n\texample-1\n\nPrints:\n\t1 2 3 4 5 6\n\nIn \"example-1\" we can see the following:\n\n1. A limit, 10, and a start value, 1, passed to \"do\".\n2. A word called 'i', which is the current count of the loop\n3. If the count is greater than 5, we call a word call 'leave', this\nword exits the current loop context as well as the current calling\nword.\n4. \"100 . cr\" is never called. This should be changed in future\nrevision, but this version of leave exits the calling word as well.\n\n'i', 'j', and 'leave' *must* be used within a do...loop construct. \n\nIn order to remedy point 4. loop should not use branch but instead \nshould use a value to return to which it pushes to the return stack )\n\n: (do)\n\tswap ( swap the limit and start )\n\tr> ( save our return stack to temporary variable )\n\t-rot ( limit start return -- return start limit )\n\t>r ( push limit onto return stack )\n\t>r ( push start onto return stack )\n\t>r ; ( restore our return address )\n\n: do immediate ( Run time: high low -- : begin do...loop construct )\n\t' (do) ,\n\tpostpone begin ; \n\n: (unloop) ( -- , R: i limit -- : remove limit and i from )\n\tr> ( save our return address )\n\trdrop ( pop off i )\n\trdrop ( pop off limit )\n\t>r ; ( restore our return stack )\n\n: (+loop) ( x -- bool : increment loop variable by x and test it )\n\tr@ 1- ( get the pointer to i )\n\t+! ( add value to it )\n\tr@ 1- @ ( find i again )\n\tr@ 2- @ ( find the limit value )\n\tu>= ;\n\n: (loop) ( -- bool : increment loop variable by 1 and test it )\n\tr@ 1- ( get the pointer to i )\n\t1+! ( add one to it )\n\tr@ 1- @ ( find the value again )\n\tr@ 2- @ ( find the limit value )\n\tu>= ;\n\n: loop ( -- : end do...loop construct )\n\timmediate ' (loop) , postpone until ' (unloop) , ;\n\n: +loop ( x -- : end do...+loop loop construct )\n\timmediate ' (+loop) , postpone until ' (unloop) , ;\n\n: leave ( -- , R: i limit return -- : break out of a do-loop construct )\n\t(unloop)\n\trdrop ; ( return to the caller's caller routine )\n\n: ?leave ( x -- , R: i limit return -- | i limit return : conditional leave )\n\tif\n\t\t(unloop)\n\t\trdrop ( return to the caller's caller routine )\n\tthen ;\n\n: i ( -- i : Get current, or innermost, loop index in do...loop construct )\n\tr> r> ( pop off return address and i )\n\ttuck ( tuck i away )\n\t>r >r ; ( restore return stack )\n\n: j ( -- j : Get outermost loop index in do...loop construct )\n\t4 rpick ;\n\n( This is a simple test function for the looping, for interactive\ntesting and debugging:\n : mm 5 1 do i . cr 4 1 do j . tab i . cr loop loop ; )\n\n: range ( nX nY -- nX nX+1 ... nY ) \n\tnos1+ do i loop ;\n\n: repeater ( n0 X -- n0 ... nX ) \n\t1 do dup loop ;\n\n: sum ( n0 ... nX X -- sum<0..X> ) \n\t1 do + loop ;\n\n: mul ( n0 ... nX X -- mul<0..X> ) \n\t1 do * loop ;\n\n: reverse ( x1 ... xn n -- xn ... x1 : reverse n items on the stack )\n\t0 do i roll loop ;\n\n\n( ========================== DO...LOOP ======================================= )\n0 variable column-counter\n4 variable column-width\n\n: column ( i -- )\t\n\tcolumn-width @ mod not if cr then ;\n\n: reset-column\t\t\n\t0 column-counter ! ;\n\n: auto-column\t\t\n\tcolumn-counter dup @ column 1+! ;\n\n: alignment-bits \n\t[ 1 size log2 lshift 1- literal ] and ;\n\n: name ( PWD -- c-addr : given a pointer to the PWD field of a word get a pointer to the name of the word )\n\tdup 1+ @ 256\/ 127 and lsb - chars> ;\n\n0 variable x\n: x! ( x -- ) \n\tx ! ;\n\n: x@ ( -- x ) \n\tx @ ;\n\n: 2>r ( x1 x2 -- R: x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tswap\n\t\t>r\n\t\t>r\n\tx@ >r ; ( restore return address )\n\n: 2r> ( R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tr>\n\t\tr>\n\t\tswap\n\tx@ >r ; ( restore return address )\n\n: 2r@ ( -- x1 x2 , R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\tr> r>\n\t2dup\n\t>r >r\n\tswap\n\tx@ >r ; ( restore return address )\n\n: unused ( -- u : push the amount of core left ) \n\tmax-core here - ;\n\n: accumulator ( initial \" ccc\" -- : make a word that increments by a value and pushes the result )\n\tcreate , does> tuck +! @ ;\n\n: counter ( \" ccc\" --, Run Time: -- x : make a word that increments itself by one, starting from zero )\n\tcreate -1 , does> dup 1+! @ ;\n\n0 variable delim\n: accepter ( c-addr max delimiter -- i )\n\t( store a \"max\" number of chars at c-addr until \"delimiter\" encountered,\n\tthe number of characters stored is returned )\n\tdelim ! ( store delimiter used to stop string storage when encountered)\n\t0\n\tdo\n\t\tkey dup delim @ <>\n\t\tif\n\t\t\tover c! 1+\n\t\telse ( terminate string )\n\t\t\tdrop 0 swap c! \n\t\t\ti \n\t\t\tleave\n\t\tthen\n\tloop\n\t-11 throw ; ( read in too many chars )\nhider delim\n\n: skip\n\tkey drop >r 0 begin drop key dup rdup r> <> until rdrop ;\n\n: word ( c -- c-addr : parse until 'c' is encountered, push transient counted string )\n\tdup skip chere 1+ c!\n\t>r\n\tchere 2+\n\tpad here - chars>\n\tr> accepter 1+\n\tchere c!\n\tchere ;\n\nhider skip\n\n: accept ( c-addr +n1 -- +n2 : see accepter definition ) \n\t'\\n' accepter ;\n\n0xFFFF constant max-string-length\n\n: (.\") ( char -- c-addr u )\n\t( @todo This really needs simplifying, to do this\n\ta set of words that operate on a temporary buffer can\n\tbe used )\n\t( Write a string into word being currently defined, this\n\tcode has to jump over the string it has just put into the\n\tdictionary so normal execution of a word can continue. The\n\tlength and character address of the string are left on the\n\tstack )\n\t>r ( save delimiter )\n\t' branch , ( write in jump, this will jump past the string )\n\t>mark ( make hole )\n\tdup 1+ chars> ( calculate address to write to )\n\tmax-string-length \n\tr> ( restore delimiter )\n\taccepter dup >r ( write string into dictionary, save index )\n\taligned 2dup size \/ ( stack: length hole char-len hole )\n\t1+ dup allot ( update dictionary pointer with string length )\n\t1+ swap ! ( write place to jump to )\n\tdrop ( do not need string length anymore )\n\t1+ chars> ( calculate place to print )\n\tr> ; ( restore index and address of string )\n\n: length ( c-addr u -- u : push the length of an ASCIIZ string )\n tuck 0 do dup c@ 0= if 2drop i leave then 1+ loop ;\n\n: asciiz? ( c-addr u -- : is a Forth string also a ASCIIZ string )\n\ttuck length <> ;\n\n: asciiz ( c-addr u -- : trim a string until NUL terminator )\n\t2dup length nip ;\n\n: type ( c-addr u -- : print out 'u' characters at c-addr )\n\t0 do dup c@ emit 1+ loop drop ;\n\n: do-string ( char -- : write a string into the dictionary reading it until char is encountered )\n\t(.\") \n\tstate @ if swap [literal] [literal] then ;\n\n: fill ( c-addr u char -- : fill in an area of memory with a character, only if u is greater than zero )\n\t-rot\n\t0 do 2dup i + c! loop\n\t2drop ;\n\n: \/string ( c-addr1 u1 n -- c-addr2 u2 : advance a string by n characters )\n\tover min rot over + -rot - ;\n\n: compare ( c-addr1 u1 c-addr2 u2 -- n : compare two strings, not quite compliant yet )\n\t>r swap r> min >r\n\tstart-address + swap start-address + r>\n\tmemory-compare ;\n\n128 string sbuf\n: s\" ( \"ccc\" --, Run Time -- c-addr u )\n\tkey drop sbuf 0 fill sbuf [char] \" accepter sbuf drop swap ;\nhider sbuf\n\n( @todo these strings really need rethinking, state awareness needs to be removed... )\n: type, \n\tstate @ if ' type , else type then ;\n\n: c\" \n\timmediate key drop [char] \" do-string ;\n\n: \" \n\timmediate key drop [char] \" do-string type, ;\n\n: sprint ( c -- : print out chars until 'c' is encountered )\n\tkey drop ( drop next space )\n\t>r ( save delimiter )\n\tbegin\n\t\tkey dup ( get next character )\n\t\trdup r> ( get delimiter )\n\t\t<> if emit 0 then\n\tuntil rdrop ;\n\n: .( \n\timmediate [char] ) sprint ;\nhider sprint\n\n: .\" \n\timmediate key drop [char] \" do-string type, ;\n\nhider type,\n\n( This word really should be removed along with any usages of this word, it\nis not a very \"Forth\" like word, it accepts a pointer to an ASCIIZ string and\nprints it out, it also does not checking of the returned values from write-file )\n: print ( c-addr -- : print out a string to the standard output )\n\t-1 over >r length r> swap stdout write-file 2drop ;\n\n: ok \n\t\" ok\" cr ;\n\n: empty-stack ( x-n ... x-0 -- : empty the variable stack )\n\tbegin depth while drop repeat ;\n\n: (quit) ( -- : do the work of quit, without the restart )\n\t0 `source-id ! ( set source to read from file )\n\t`stdin @ `fin ! ( read from stdin )\n\tpostpone [ ( back into command mode )\n\t' interpret start! ; ( set interpreter starting word )\n\n: quit ( -- : Empty return stack, go back to command mode, read from stdin, interpret input )\n\t(quit)\n\t-1 restart ; ( restart the interpreter )\n\n: abort\n\t-1 throw ;\n\n: (abort\") ( do the work of abort )\n\t(quit)\n\t-2 throw ;\n\n: abort\" immediate \n\tpostpone \"\n\t' cr , ' (abort\") , ;\n\n( ==================== CASE statements ======================== )\n\n( for a simpler case statement:\n\tsee Volume 2, issue 3, page 48 of Forth Dimensions at\n\thttp:\/\/www.forth.org\/fd\/contents.html )\n\n( These case statements need improving, it is not standards compliant )\n: case immediate\n\t' branch , 3 , ( branch over the next branch )\n\there ' branch , ( mark: place endof branches back to with again )\n\t>mark swap ; ( mark: place endcase writes jump to with then )\n\n: over= ( x y -- x bool : over ... then = )\n\tover = ;\n\n: of\n\timmediate ' over= , postpone if ;\n\n: endof\n\timmediate over postpone again postpone then ;\n\n: endcase\n\timmediate 1+ postpone then drop ;\n\n( ==================== CASE statements ======================== )\n\n( ==================== Hiding Words =========================== )\n\n: }hide ( should only be matched with 'hide{' )\n\timmediate -22 throw ;\n\n: hide{ ( -- : hide a list of words, the list is terminated with \"}hide\" )\n\tbegin\n\t\tfind ( find next word )\n\t\tdup [ find }hide ] literal = if\n\t\t\tdrop exit ( terminate hide{ )\n\t\tthen\n\t\tdup 0= if -15 throw then\n\t\thide drop\n\tagain ;\n\n( ==================== Hiding Words =========================== )\n\n: spaces ( n -- : print n spaces ) \n\t0 do space loop ;\n\n: erase ( addr u : erase a block of memory )\n\t2chars> 0 fill ;\n\n: blank ( c-addr u : fills a string with spaces )\n\tbl fill ;\n\n( move should check that u is not negative )\n: move ( addr1 addr2 u -- : copy u words of memory from 'addr2' to 'addr1' )\n\t0 do\n\t\t2dup i + @ swap i + !\n\tloop\n\t2drop ;\n\n( It would be nice if move and cmove could share more code, as they do exactly\n the same thing but with different load and store functions, cmove> )\n: cmove ( c-addr1 c-addr2 u -- : copy u characters of memory from 'c-addr2' to 'c-addr1' )\n\t0 do\n\t\t2dup i + c@ swap i + c!\n\tloop\n\t2drop ;\n\n( ==================== Conditional Compilation ================ )\n\n( The words \"[if]\", \"[else]\" and \"[then]\" implement conditional compilation,\nthey can be nested as well\n\nSee http:\/\/lars.nocrew.org\/dpans\/dpans15.htm for more information\n\nA much simpler conditional compilation method is the following\nsingle word definition:\n\n : compile-line? 0= if [ find \\\\ , ] then ;\n\nWhich will skip a line if a conditional is false, and compile it\nif true )\n\n( These words really, really need refactoring, I could use the newly defined \n \"defer\" to help out with this )\n0 variable nest ( level of [if] nesting )\n0 variable [if]-word ( populated later with \"find [if]\" )\n0 variable [else]-word ( populated later with \"find [else]\")\n: [then] immediate ;\n: reset-nest 1 nest ! ;\n: unnest? [ find [then] ] literal = if nest 1-! then ;\n: nest? [if]-word @ = if nest 1+! then ;\n: end-nest? nest @ 0= ;\n: match-[else]? [else]-word @ = nest @ 1 = and ;\n\n: [if] ( bool -- : conditional execution )\n\tunless\n\t\treset-nest\n\t\tbegin\n\t\t\tfind\n\t\t\tdup nest?\n\t\t\tdup match-[else]? if drop exit then\n\t\t\t unnest?\n\t\t\tend-nest?\n\t\tuntil\n\tthen ;\n\n: [else] ( discard input until [then] encounter, nesting for [if] )\n\treset-nest\n\tbegin\n\t\tfind\n\t\tdup nest? unnest?\n\t\tend-nest?\n\tuntil ;\n\nfind [if] [if]-word !\nfind [else] [else]-word !\n\nhide{ \n[if]-word [else]-word nest reset-nest unnest? match-[else]? end-nest? nest? }hide\n\n( ==================== Conditional Compilation ================ )\n\n( ==================== Endian Words =========================== )\n\nsize 2 = [if] 0x0123 variable endianess [then]\nsize 4 = [if] 0x01234567 variable endianess [then]\nsize 8 = [if] 0x01234567abcdef variable endianess [then]\n\n: endian ( -- bool : returns the endianess of the processor, little = 0, big = 1 )\n\t[ endianess chars> c@ 0x01 = ] literal ;\nhider endianess\n\n: swap16 ( x -- x : swap the byte order a 16 bit number )\n\tdup 256* 0xff00 and >r 256\/ lsb r> or ;\n\nsize 4 >= [if] \n\t: swap32 \n\t\tdup 0xffff and swap16 16 lshift swap\n\t\t16 rshift 0xffff and swap16 or ;\n[then]\n\nsize 8 >= [if]\n\t: swap64 ( x -- x : swap the byte order of a 64 bit number )\n\t\t dup 0xffffffff and swap32 32 lshift swap\n\t\t 32 rshift 0xffffffff and swap32 or ;\n[then]\n\nsize 2 = [if]\n\tendian \n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\tswap16 ;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\t;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\tswap16 ;\n\t[then]\n[then]\n\nsize 4 = [if]\n\tendian \n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\tswap32 ;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\t;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\tswap32 ;\n\t[then]\n[then]\n\nsize 8 = [if]\n\tendian \n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\tswap64 ;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\t;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\tswap64 ;\n\t[then]\n[then]\n\n( ==================== Endian Words =========================== )\n\n( ==================== Misc words ============================= )\n\n0 variable counter\n\n: counted-column ( index -- : special column printing for dump )\n\tcounter @ column-width @ mod\n\tnot if cr . \" :\" space else drop then\n\tcounter 1+! ;\n\n: as-chars ( x n -- : print a cell out as characters, upto n chars )\n\t0 ( from zero to the size of a cell )\n\tdo\n\t\tdup ( copy variable to print out )\n\t\tsize i 1+ - select-byte ( select correct byte )\n\t\tdup printable? not ( is it not printable )\n\t\tif drop [char] . then ( print a '.' if it is not )\n\t\temit ( otherwise print it out )\n\tloop\n\tspace ( print out space after )\n\tdrop ; ( drop cell we have printed out )\n\n: lister ( addr u addr -- )\n\t0 counter ! 1- swap \n\tdo \n\t\tdup counted-column 1+ i ? i @ size as-chars \n\tloop ;\n\n( @todo this function should make use of 'defer' and 'is', then different\nversion of dump could be made that swapped out 'lister' )\n: dump ( addr u -- : dump out 'u' cells of memory starting from 'addr' )\n\tbase @ >r hex 1+ over + under lister drop r> base ! cr ;\n\nhide{ counted-column counter as-chars }hide\n\n: forgetter ( pwd-token -- : forget a found word and everything after it )\n\tdup @ pwd ! h ! ;\n\n( @bug will not work for immediate defined words \n@note Fig Forth had a word FENCE, if anything before this word was\nattempted to be forgotten then an exception is throw )\n: forget ( WORD -- : forget word and every word defined after it )\n\tfind dup 0= if -15 throw then 1- forgetter ;\n\n: marker ( WORD -- : make word the forgets itself and words after it)\n\t:: latest [literal] ' forgetter , postpone ; ;\nhider forgetter\n\n: ** ( b e -- x : exponent, raise 'b' to the power of 'e')\n\t?dup-if\n\t\tover swap\n\t\t1 do over * loop \n\t\tnip\n\telse\n\t\tdrop 1\n\tendif ;\n\n0 variable a\n0 variable b\n0 variable m\n: equal ( a1...an b1...bn n -- a1...an b1...bn bool : determine if two lists are equal )\n\t( example: \n\t\t1 2 3 \n\t\t1 2 3 \n\t\t3 equal \n\treturns: 1 )\n\tdup m ! 1+ 1 ( store copy of length and use as loop index )\n\tdo \n\t\ti 1- pick b ! ( store ith element of list in b1...bn )\n\t\ti m @ + 1- pick a ! ( store ith element of list in a1...an )\n\t\ta @ b @ <> ( compare a and b for equality )\n\t\tif 0 leave then ( unequal, finish early )\n\tloop 1 ; ( lists must be equal )\n\nhide{ a b m }hide\n\n: ndrop ( drop n items )\n\t?dup-if 0 do drop loop then ;\n\n( ==================== Misc words ============================= )\n\n( ==================== Pictured Numeric Output ================ )\n\n0 variable hld\n\n: overflow ( -- : )\n \there chars> pad chars> hld @ - u> if -17 throw then ;\n\n: hold ( char -- : add a character to the numeric output string )\n\toverflow pad chars> hld @ - c! hld 1+! ;\n\n: holds ( addr u -- )\n begin dup while 1- 2dup + c@ hold repeat 2drop ;\n\n: nbase ( -- base : in this forth 0 is a special base, push 10 is base is zero )\n\tbase @ dup 0= if drop 10 then ;\n\n: <# ( -- : setup pictured numeric output )\n\t0 hld ! ;\n\n: sign ( -- : add a sign to the pictured numeric output string )\n\t[char] - hold ;\n\n: # ( x -- x : divide x by base, turn into a character, put in pictured output string )\n\tnbase um\/mod swap \n \tdup 9 u>\n \tif 7 + then\n \t48 + hold ;\n\n: #s ( x -- 0 : repeatedly call # on x until x is zero )\n\tbegin # dup 0= until ; \n\n: #> ( -- c-addr u : end pictured output conversion, push output string to stack )\n\t0 hold ( NUL terminate string, just in case )\n\thld 1-! ( but do not include that in the count )\n\tpad chars> hld @ \n\ttuck - 1+ swap ;\n\n: u. ( u -- : display number in base 10 )\n\tbase @ >r decimal <# #s #> type drop r> base ! ;\n\nhide{ nbase overflow }hide\n\n( ==================== Pictured Numeric Output ================ )\n\n( ==================== ANSI Escape Codes ====================== )\n( Terminal colorization module, via ANSI Escape Codes\n \nsee: https:\/\/en.wikipedia.org\/wiki\/ANSI_escape_code\nThese codes will provide a relatively portable means of\nmanipulating a terminal )\n\n27 constant 'escape'\n: CSI 'escape' emit .\" [\" ;\n0 constant black\n1 constant red\n2 constant green\n3 constant yellow\n4 constant blue\n5 constant magenta\n6 constant cyan\n7 constant white\n: foreground 30 + ;\n: background 40 + ;\n0 constant dark\n1 constant bright\nfalse variable colorize \n\n: color ( brightness color-code -- : set the terminal color )\n\t( set color on an ANSI compliant terminal,\n\tfor example:\n\t\tbright red foreground color\n\tsets the foreground text to bright red )\n\tcolorize @ 0= if 2drop exit then \n\tCSI u. if .\" ;1\" then .\" m\" ;\n\n: at-xy ( x y -- : set ANSI terminal cursor position to x y )\n\tCSI u. [char] ; emit u. .\" H\" ;\n\n: page ( -- : clear ANSI terminal screen and move cursor to beginning ) \n\tCSI .\" 2J\" 1 1 at-xy ;\n\n: hide-cursor ( -- : hide the cursor from view ) \n\tCSI .\" ?25l\" ;\n\n: show-cursor ( -- : show the cursor ) \n\tCSI .\" ?25h\" ;\n\n: save-cursor ( -- : save cursor position ) \n\tCSI .\" s\" ;\n\n: restore-cursor ( -- : restore saved cursor position ) \n\tCSI .\" u\" ;\n\n: reset-color ( -- : reset terminal color to its default value)\n\tcolorize @ 0= if exit then\n\tCSI .\" 0m\" ;\n\nhide{ CSI }hide\n( ==================== ANSI Escape Codes ====================== )\n\n( ==================== Unit test framework =================== )\n\n256 string estring ( string to test )\n0 variable #estring ( actual string length )\n0 variable start ( starting depth )\n0 variable result ( result depth )\n0 variable check ( only check depth if -> is called )\n0 variable dictionary ( dictionary pointer on entering { )\n0 variable previous ( PWD register on entering { )\n\n: T ; ( hack until T{ can process words )\n\n: -> ( -- : save depth in variable ) \n\t1 check ! depth result ! ; \n\n: test estring drop #estring @ ; \n\n: fail ( -- : invalidate the forth interpreter and exit )\n\tinvalidate bye ;\n\n: neutral ( -- : neutral color )\n\t;\n\n: bad ( -- : bad color )\n\tdark red foreground color ;\n\n: good ( -- : good color )\n\tdark green foreground color ;\n\n: die bad test type reset-color cr fail ;\n\n: evaluate? ( bool -- : test if evaluation has failed )\n\tif .\" evaluation failed\" cr fail then ;\n\n: failed bad .\" failed\" reset-color cr ;\n\n: adjust ( x -- x : adjust a depth to take into account starting depth ) \n\tstart @ - ;\n\n: no-check? ( -- bool : if true we need to check the depth )\n\tcheck @ 0= ;\n\n: depth? ( -- : check if depth is correct )\n\tno-check? if exit then\n\tdepth adjust ( get depth and adjust for starting depth )\n\tresult @ adjust 2* = ( get results depth, same adjustment, should be\n\t half size of the depth ) \n\tif exit then ( pass )\n\tfailed\n\t.\" Unequal depths:\" cr\n\t.\" depth: \" depth . cr\n\t.\" result: \" result @ . cr\n\tdie ;\n\n: equal? ( -- : determine if results equals expected )\n\tno-check? if exit then\n\tresult @ adjust equal\n\tif exit then\n\tfailed\n\t.\" Result is not equal to expected values. \" cr \n\t.\" Stack: \" cr .s cr\n\tdie ;\n\n: display ( c-addr u -- : print out testing message in estring )\n\tverbose if neutral type else 2drop then ;\n\n: pass ( -- : print out passing message )\n\tverbose if good .\" ok \" cr reset-color then ;\n\n: save ( -- : save current dictionary )\n\tpwd @ previous !\n\there dictionary ! ;\n\n: restore ( -- : restore dictionary )\n\tprevious @ pwd ! \n\tdictionary @ h ! ;\n\n\n: T{ ( -- : perform a unit test )\n\tdepth start ! ( save start of stack depth )\n\t0 result ! ( reset result variable )\n\t0 check ! ( reset check variable )\n\testring 0 fill ( zero input string )\n\tsave ( save dictionary state )\n\tkey drop ( drop next character, which is a space )\n\testring [char] } accepter #estring ! ( read in string to test )\n\ttest display ( print which string we are testing )\n\ttest evaluate ( perform test )\n\tevaluate? ( evaluate successfully? )\n\tdepth? ( correct depth )\n\tequal? ( results equal to expected values? )\n\tpass ( print pass message )\n\tresult @ adjust 2* ndrop ( remove items on stack generated by test )\n\trestore ; ( restore dictionary to previous state )\n\nT{ }T\nT{ -> }T\nT{ 1 -> 1 }T\nT{ 1 2 -> 1 2 }T\nT{ : c 1 2 ; c -> 1 2 }T\nT{ :noname 2 ; :noname 3 + ; compose execute -> 5 }T\n\nhide{ \n\tpass test display\n\tadjust start save restore dictionary previous \n\tevaluate? equal? depth? estring #estring result\n\tcheck no-check? die neutral bad good failed\n}hide\n\n( ==================== Unit test framework =================== )\n\n\n( ==================== Random Numbers ========================= )\n\n( \nSee:\nuses xorshift\nhttps:\/\/en.wikipedia.org\/wiki\/Xorshift\nhttp:\/\/excamera.com\/sphinx\/article-xorshift.html\nhttp:\/\/www.arklyffe.com\/main\/2010\/08\/29\/xorshift-pseudorandom-number-generator\/\nthese constants have be collected from the web \n)\n\nsize 2 = [if] 13 constant a 9 constant b 7 constant c [then]\nsize 4 = [if] 13 constant a 17 constant b 5 constant c [then]\nsize 8 = [if] 12 constant a 25 constant b 27 constant c [then]\n\n7 variable seed ( must not be zero )\n\n: seed! ( x -- : set the value of the PRNG seed )\n\tdup 0= if drop 7 ( zero not allowed ) then seed ! ;\n\n: random ( -- x : assumes word size is 32 bit )\n\tseed @\n\tdup a lshift xor\n\tdup b rshift xor\n\tdup c lshift xor\n\tdup seed! ;\n\nhide{ a b c seed }hide\n\n( ==================== Random Numbers ========================= )\n\n( ==================== Prime Numbers ========================== )\n( From original \"third\" code from the IOCCC at \nhttp:\/\/www.ioccc.org\/1992\/buzzard.2.design, the module works out\nand prints prime numbers. )\n\n: prime? ( u -- u | 0 : return number if it is prime, zero otherwise )\n\tdup 1 = if 1- exit then\n\tdup 2 = if exit then\n\tdup 2 \/ 2 ( loop from 2 to n\/2 )\n\tdo\n\t\tdup ( value to check if prime )\n\t\ti mod ( mod by divisor )\n\t\tnot if\n\t\t\tdrop 0 leave\n\t\tthen\n\tloop ;\n\n0 variable counter\n\n: primes ( x1 x2 -- : print the primes from x2 to x1 )\n\t0 counter !\n\t\" The primes from \" dup . \" to \" over . \" are: \"\n\tcr\n\treset-column\n\tdo\n\t\ti prime?\n\t\tif\n\t\t\ti . counter @ column counter 1+!\n\t\tthen\n\tloop\n\tcr\n\t\" There are \" counter @ . \" primes.\"\n\tcr ;\n\nhide{ counter }hide\n( ==================== Prime Numbers ========================== )\n\n( ==================== Debugging info ========================= )\n\n( string handling should really be done with PARSE, and CMOVE )\n\nhide{ .s }hide\n: .s ( -- : print out the stack for debugging )\n\t\" <\" depth u. \" >\" space\n\tdepth if\n\t\tdepth 0 do i column tab depth i 1+ - pick u. loop\n\tthen\n\tcr ;\n\n1 variable hide-words ( do we want to hide hidden words or not )\n( This function prints out all of the defined words, excluding hidden words.\nAn understanding of the layout of a Forth word helps here. The dictionary\ncontains a linked list of words, each forth word has a pointer to the previous\nword until the first word. The layout of a Forth word looks like this:\n\nNAME: Forth Word - A variable length ASCII NUL terminated string\nPWD: Previous Word Pointer, points to the previous word\nMISC: Flags, code word and offset from previous word pointer to start of Forth word string\nCODE\/DATA: The body of the forth word definition, not interested in this.\n\nThere is a register which stores the latest defined word which can be\naccessed with the code \"pwd @\". In order to print out a word we need to\naccess a words MISC field, the offset to the NAME is stored here in bits\n8 to 15 and the offset is calculated from the PWD field.\n\n\"print\" expects a character address, so we need to multiply any calculated\naddress by the word size in bytes. )\n\n: words ( -- : print out all defined an visible words )\n\tlatest\n\tbegin\n\t\tdup\n\t\thidden? hide-words @ and\n\t\tnot if\n\t\t\tname\n\t\t\tprint space\n\t\telse\n\t\t\tdrop\n\t\tthen\n\t\t@ ( Get pointer to previous word )\n\t\tdup dictionary-start u< ( stop if pwd no longer points to a word )\n\tuntil\n\tdrop cr ;\nhider hide-words\n\n: TrueFalse ( -- : print true or false )\n\tif \" true\" else \" false\" then ;\n\n: registers ( -- : print out important registers and information about the virtual machine )\n\t\" return stack pointer: \" r@ . cr\n\t\" dictionary pointer \" here . cr\n\t\" previous word: \" pwd ? cr\n\t\" state: \" state ? cr\n\t\" base: \" base ? cr\n\t\" depth: \" depth . cr\n\t\" cell size (in bytes): \" size . cr\n\t\" last cell address: \" max-core . cr\n\t\" unused cells: \" unused . cr\n\t\" invalid: \" `invalid @ TrueFalse cr\n\t\" size of variable stack: \" `stack-size ? cr\n\t\" size of return stack: \" `stack-size ? cr\n\t\" start of variable stack: \" max-core `stack-size @ 2* - . cr\n\t\" start of return stack: \" max-core `stack-size @ - . cr\n\t\" current input source: \" source-id -1 = if \" string\" else \" file\" then cr\n\t\" reading from stdin: \" source-id 0 = stdin? and TrueFalse cr\n\t\" tracing on: \" `debug @ TrueFalse cr\n\t\" starting word: \" `instruction ? cr\n\t\" real start address: \" `start-address ? cr\n\t\" error handling: \" `error-handler ? cr ;\n( `sin `sidx `slen `fout\n `stdout `stderr `argc `argv )\n\n\n: y\/n? ( -- bool : ask a yes or no question )\n\tkey drop\n\t\" y\/n? \"\n\tbegin\n\t\tkey\n\t\tdup\n\t\t[char] y = if true exit then\n\t\t[char] n = if false exit then\n\t\t\" y\/n? \"\n\tagain ;\n\n: >instruction ( MISC -- Instruction : extract instruction from instruction field ) \n\tinstruction-mask and ;\n\n: step\n\t( step through a word: this word could be augmented\n\twith commands such as \"dump\", \"halt\", and optional\n\t\".s\" and \"registers\" )\n\tregisters\n\t\" .s: \" .s cr\n\t\" -- press any key to continue -- \"\n\tkey drop ;\n\n: more ( -- : wait for more input )\n\t\" -- press any key to continue -- \" key drop cr page ;\n\n: debug-help ( -- : this is not quite ready for prime time )\n \" debug mode commands\n\th - print help\n\tq - exit containing word\n\tr - print registers\n\ts - print stack\n\tc - continue on with execution\n\" ;\n\n: debug-prompt \n\t.\" debug> \" ;\n\n: debug ( a work in progress, debugging support, needs parse-word )\n\t\\ \" Entered Debug Prompt. Type 'h' for help. \" cr \n\tkey drop\n\tcr\n\tbegin\n\t\tdebug-prompt\n\t\t'\\n' word count drop c@\n\t\tcase\n\t\t\t[char] h of debug-help endof\n\t\t\t[char] q of bye endof\n\t\t\t[char] r of registers endof\n\t\t\t[char] s of >r .s r> endof\n\t\t\t[char] c of drop exit endof\n\t\t\t( @todo add throw here )\n\t\tendcase drop\n\tagain ;\nhider debug-prompt\n\n: code>pwd ( CODE -- PWD\/0 : calculate PWD from code address )\n\tdup dictionary-start here within not if drop 0 exit then\n\t>r\n\tlatest dup @ ( p1 p2 )\n\tbegin\n\t\tover ( p1 p2 p1 )\n\t\trdup r> u<= swap rdup r> > and if rdrop exit then\n\t\tdup 0= if rdrop exit then\n\t\tdup @ swap\n\tagain ;\n\n: end-print ( x -- )\n\t\"\t\t=> \" . \" ]\" ;\n\n: word-printer\n\t( attempt to print out a word given a words code field\n\tWARNING: This is a dirty hack at the moment\n\tNOTE: given a pointer to somewhere in a word it is possible\n\tto work out the PWD by looping through the dictionary to\n\tfind the PWD below it )\n\tdup 1- @ -1 = if \" [ noname\" end-print exit then\n\tdup \" [ \" code>pwd ?dup-if name print else drop \" data\" then\n\t end-print ;\n\nhide{ end-print code>pwd }hide\n\n( these words push the execution tokens for various special cases for decompilation )\n: get-branch [ find branch ] literal ;\n: get-?branch [ find ?branch ] literal ;\n: get-original-exit [ original-exit ] literal ;\n: get-quote [ find ' ] literal ;\n\n: branch-increment ( addr branch -- increment : calculate decompile increment for \"branch\" )\n\t1+ dup negative? if drop 2 else 2dup dump then ;\n\n( these words take a code field to a primitive they implement, decompile it\nand any data belonging to that operation, and push a number to increment the\ndecompilers code stream pointer by )\n\n: decompile-literal ( code -- increment )\n\t\" [ literal\t=> \" 1+ ? \" ]\" 2 ;\n: decompile-branch ( code -- increment )\n\t\" [ branch\t=> \" 1+ ? \" ]\" dup 1+ @ branch-increment ;\n: decompile-quote ( code -- increment )\n\t\" [ '\t=> \" 1+ @ word-printer \" ]\" 2 ;\n: decompile-?branch ( code -- increment )\n\t\" [ ?branch\t=> \" 1+ ? \" ]\" 2 ;\n\n( The decompile word expects a pointer to the code field of a word, it\ndecompiles a words code field, it needs a lot of work however.\nThere are several complications to implementing this decompile\nfunction.\n\n\t' The next cell should be pushed\n\t:noname This has a marker before its code field of -1 which\n\t\t cannot occur normally, this is handles in word-printer\n\tbranch branches are used to skip over data, but also for\n\t\t some branch constructs, any data in between can only\n\t\t be printed out generally speaking\n\texit There are two definitions of exit, the one used in\n\t\t ';' and the one everything else uses, this is used\n\t\t to determine the actual end of the word\n\tliterals Literals can be distinguished by their low value,\n\t\t which cannot possibly be a word with a name, the\n\t\t next field is the actual literal\n\nOf special difficult is processing 'if' 'else' 'then' statements,\nthis will require keeping track of '?branch'.\n\nAlso of note, a number greater than \"here\" must be data )\n\n: decompile ( code-field-ptr -- : decompile a word )\n\tbegin\n\t\ttab\n\t\tdup @\n\t\tcase\n\t\t\tdolit of drup decompile-literal endof\n\t\t\tget-branch of drup decompile-branch endof\n\t\t\tget-quote of drup decompile-quote endof\n\t\t\tget-?branch of drup decompile-?branch endof\n\t\t\tget-original-exit of 2drop \" [ exit ]\" cr exit endof\n\t\t\tword-printer 1\n\t\tendcase\n\t\t+\n\t\tcr\n\tagain ;\n\nhide{\n\tword-printer get-branch get-?branch get-original-exit \n\tget-quote branch-increment decompile-literal \n\tdecompile-branch decompile-?branch decompile-quote\n}hide\n\n: xt-instruction ( extract instruction from execution token )\n\tcell+ @ >instruction ;\n\n( these words expect a pointer to the PWD field of a word )\n: defined-word? xt-instruction dolist = ;\n: print-name \" name: \" name print cr ;\n: print-start \" word start: \" name chars . cr ;\n: print-previous \" previous word: \" @ . cr ;\n: print-immediate \" immediate: \" cell+ @ 0x8000 and 0= TrueFalse cr ;\n: print-instruction \" instruction: \" xt-instruction . cr ;\n: print-defined \" defined: \" defined-word? TrueFalse cr ;\n\n: print-header ( PWD -- is-immediate-word? )\n\tdup print-name\n\tdup print-start\n\tdup print-previous\n\tdup print-immediate\n\tdup print-instruction ( @todo look up instruction name )\n\tprint-defined ;\n\n( @todo This does not work for all words, so needs fixing. \n Specifically: \n\t2variable\n\t2constant\n\ttable\n\tconstant\n\tvariable\n\tarray \nWhich are all complex CREATE words\n\nA good way to test decompilation is with the following Unix pipe: \n\n\t.\/forth -f forth.fth -e words \n\t\t| sed 's\/ \/ see \/g' \n\t\t| .\/forth -t forth.fth &> decompiled.log\n)\n\n\n: see ( c\" xxx\" -- : decompile the next word in the input stream )\n\tfind\n\tdup 0= if -32 throw then\n\t1- ( move to PWD field )\n\tdup print-header\n\tdup defined-word?\n\tif ( decompile if a compiled word )\n\t\t2 cells + ( move to code field )\n\t\t\" code field:\" cr\n\t\tdecompile\n\telse ( the instruction describes the word if it is not a compiled word )\n\t\tdrop\n\tthen cr ;\n\n( These help messages could be moved to blocks, the blocks could then\nbe loaded from disk and printed instead of defining the help here,\nthis would allow much larger help )\n\n: help ( -- : print out a short help message )\n\tpage\n\tkey drop\n\" Welcome to Forth, an imperative stack based language. It is both a low\nlevel and a high level language, with a very small memory footprint. Most\nof Forth is defined as a combination of various primitives.\n\nA short description of the available function (or Forth words) follows,\nwords marked (1) are immediate and cannot be used in command mode, words\nmarked with (2) define new words. Words marked with (3) have both command\nand compile functionality.\n\n\"\nmore \" The built in words that accessible are:\n\n(1,2)\t: define a new word, switching to compile mode\n\timmediate make latest defined word immediate\n\tread read in a word, execute in command mode else compile\n\t@ ! fetch, store\n\tc@ c! character based fetch and store\n\t- + * \/ standard arithmetic operations,\n\tand or xor invert standard bitwise operations\n\tlshift rshift left and right bit shift\n\tu< u> < > = comparison predicates\n\texit exit from a word\n\temit print character from top of stack\n\tkey get a character from input\n\tr> >r pop a value from or to the return stack\n\tfind find a word in the dictionary and push the location\n\t' store the address of the following word on the stack\n\t, write the top of the stack to the dictionary\n\tswap swap first two values on the stack\n\tdup duplicate the top of the stack\n\tdrop pop and drop a value\n\tover copy the second stack value over the first\n\t. pop the top of the stack and print it\n\" \nmore \" \n\tprint print a NUL terminated string at a character address\n\tdepth get the current stack depth\n\tclock get the time since execution start in milliseconds\n\tevaluate evaluate a string\n\tsystem execute a system command\n\tclose-file close a file handle\n\topen-file open a file handle\n\tdelete-file delete a file off disk given a string\n\tread-file read in characters from a file\n\twrite-file write characters to a file\n\tfile-position get the file offset\n\treposition-file reposition the file pointer\n\tflush-file flush a file to disk\n\trename-file rename a file on disk\n \"\n\nmore \" All of the other words in the interpreter are built from these\nprimitive words. A few examples:\n\n(1)\tif...else...then FORTH branching construct\n(1)\tbegin...until loop until top of stack is non zero\n(1)\tbegin...again infinite loop\n(1)\tdo...loop FORTH looping construct\n(2,3)\tcreate create a new word that pushes its location\n(1)\tdoes> declare a created words run time behaviour\n(1,2)\tvariable declare variable with initial value from top of stack\n(1,2)\tconstant declare a constant, taken from top of stack\n(1,2)\tarray declare an array with size taken from top of stack\n(1)\t; terminate a word definition and return to command mode\n\twords print out a list of all the defined words\n\thelp this help message\n\tdump print out memory contents starting at an address\n\tregisters print out the contents of the registers\n\tsee decompile a word, viewing what words compose it\n\t.s print out the contents of the stack\n\n\"\n\nmore \" Some more advanced words:\n\n\there push the dictionary pointer\n\th push the address of the dictionary pointer\n\tr push the return stack pointer\n\tallot allocate space in the dictionary\n(1)\t[ switch to command mode\n\t] switch to compile mode\n\t:: compile ':' into the dictionary\n\n\" more \"\nFor more information either consult the manual pages forth(1) and libforth(1)\nor consult the following sources:\n\n\thttps:\/\/github.com\/howerj\/libforth\n\thttp:\/\/work.anapnea.net\/html\/html\/projects.html\n\nAnd for a larger tutorial:\n\n\thttps:\/\/github.com\/howerj\/libforth\/blob\/master\/readme.md\n\nFor resources on Forth:\n\n\thttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\thttps:\/\/rwmj.wordpress.com\/2010\/08\/07\/jonesforth-git-repository\/\n\n -- end --\n\" cr\n;\n\n( ==================== Files ================================== )\n\n( @todo implement the other file access methods in terms of the\n built in ones [see http:\/\/forth.sourceforge.net\/std\/dpans\/dpans11.htm]\n @todo read-line and write-line need their flag and ior setting correctly\n\n\tFILE-SIZE [ use file-positions ]\n\n Also of note:\t\n * Source ID needs extending. )\n\n: read-char ( c-addr fileid -- ior : read a char )\n\t1 swap read-file 0<> swap 1 <> or ;\n\n0 variable x\n\n: getchar ( fileid -- char ior )\n\tx chars> swap read-char x chars> c@ swap ;\n\n: write-char ( c-addr fileid -- ior : write a char )\n\t1 swap write-file 0<> swap 1 <> or ;\n\n: putchar ( char fileid -- ior )\n\tswap x chars> c! x chars> swap write-char ;\n\nhide{ x }hide\n\n: rewind-file ( file-id -- : rewind a file to the beginning )\n\t0 reposition-file throw ;\n\n: read-line ( c-addr u1 fileid -- u2 flag ior : read in a line of text )\n\t-rot bounds\n\tdo\n\t\tdup i swap read-char drop\n\t\ti c@ '\\n' = if drop i 0 0 leave then\n\tloop drop ;\n\n: write-line ( c-addr u fileid -- u2 flag ior : write a line of text )\n\t-rot bounds\n\tdo\n\t\tdup i swap write-char drop\n\t\ti c@ '\\n' = if drop i 0 0 leave then\n\tloop ;\n\n: resize-file ( ud fileid -- ior : attempt to resize a file )\n\t( There is no portable way to truncate a file :C )\n\t2drop -1 ( -1 to indicate failure ) ;\n\n: create-file ( c-addr u fam -- fileid ior )\n\t>r 2dup w\/o open-file throw close-file throw\n\tr> open-file ;\n\n: include-file ( file-id -- : evaluate a file ) \n\tdup >r 0 1 evaluator r> close-file throw throw ;\n\n: included ( c-addr u -- : attempt to open up a name file and evaluate it )\n\tr\/o open-file throw \n\tinclude-file ;\n\n: include ( c\" ccc\" -- : attempt to evaluate a named file )\n\t( @bug requires trailing space, should use parse-name )\n\tbl word count included ;\n\n: bin ( fam1 -- fam2 : modify a file access method to be binary not line oriented ) \n\t( Do nothing, all file access methods are binary )\n\t;\n\n( ==================== Files ================================== )\n\n( ==================== Blocks ================================= )\n( \n0 variable dirty\nb\/buf string buf\n0 variable loaded\n0 variable blk\n0 variable scr\n\n: update 1 dirty ! ;\n: empty-buffers 0 loaded ! ;\n: ?update dup loaded @ <> dirty @ or ;\n: ?invalid dup 0= if empty-buffers -35 throw then ;\n: write dup >r write-file r> close-file throw ;\n: read dup >r read-file r> close-file throw ;\n: name >r <# #s #> rot drop r> create-file throw ; \\ @todo add .blk with holds, also create file deletes file first...\n: update! >r buf r> w\/o name write throw drop empty-buffers ;\n: get >r buf r> r\/o name read throw drop ;\n: block ?invalid ?update if dup update! then dup get loaded ! buf drop ;\n\nhide{ dirty ?update update! loaded name get ?invalid write read }hide\n\n: c \n\t1 block update drop\n\t2 block update drop\n\t3 block update drop\n\t4 block update drop ;\nc )\n\n( ==================== Blocks ================================= )\n\n( ==================== Matcher ================================ )\n( The following section implements a very simple regular expression\nengine, which expects an ASCIIZ Forth string. It is translated from C\ncode and performs an identical function.\n\nThe regular expression language is as follows:\n\n\tc\tmatch a literal character\n\t.\tmatch any character\n\t*\tmatch any characters\n\nThe \"*\" operator performs the same function as \".*\" does in most\nother regular expression engines. Most other regular expression engines\nalso do not anchor their selections to the beginning and the end of\nthe string to match, instead using the operators '^' and '$' to do\nso, to emulate this behavior '*' can be added as either a suffix,\nor a prefix, or both, to the matching expression.\n\nAs an example \"*, World!\" matches both \"Hello, World!\" and\n\"Good bye, cruel World!\". \"Hello, ....\" matches \"Hello, Bill\"\nand \"Hello, Fred\" but not \"Hello, Tim\" as there are two few\ncharacters in the last string.\n\n@todo make a matcher that expects a Forth string, which do not\nhave to be NUL terminated\n)\n\n\\ Translated from http:\/\/c-faq.com\/lib\/regex.html\n\\ int match(char *pat, char *str)\n\\ {\n\\ \tswitch(*pat) {\n\\ \tcase '\\0': return !*str;\n\\ \tcase '*': return match(pat+1, str) || *str && match(pat, str+1);\n\\ \tcase '.': return *str && match(pat+1, str+1);\n\\ \tdefault: return *pat == *str && match(pat+1, str+1);\n\\ \t}\n\\ }\n\n: *pat ( regex -- regex char : grab next character of pattern ) \n\tdup c@ ;\n\n: *str ( string regex -- string regex char : grab next character string to match )\n\tover c@ ;\n\n: pass ( c-addr1 c-addr2 -- bool : pass condition, characters matched ) \n\t2drop 1 ;\n\n: reject ( c-addr1 c-addr2 -- bool : fail condition, character not matched ) \n\t2drop 0 ;\n\n: *pat==*str ( c-addr1 c-addr2 -- c-addr1 c-addr2 bool )\n\t2dup c@ swap c@ = ;\n\n: ++ ( u1 u2 u3 u4 -- u1+u3 u2+u4 : not quite d+ [does no carry] )\n\tswap >r + swap r> + swap ;\n\ndefer matcher\n\n: advance ( string regex char -- bool : advance both regex and string )\n\tif 1 1 ++ matcher else reject then ;\n\n: advance-string ( string regex char -- bool : advance only the string )\n\tif 1 0 ++ matcher else reject then ;\n\n: advance-regex ( string regex -- bool : advance matching )\n\t2dup 0 1 ++ matcher if pass else *str advance-string then ;\n\n: match ( string regex -- bool : match a ASCIIZ pattern against an ASCIIZ string )\n\t( @todo Add limits and accept two Forth strings, making sure they are both\n\t ASCIIZ strings as well \n\t @warning This uses a non-standards compliant version of case! )\n\t*pat\n\tcase\n\t\t 0 of drop drop c@ not exit endof\n\t\t[char] * of drop advance-regex exit endof\n\t\t[char] . of drop *str advance exit endof\n\t\t drop *pat==*str advance exit\n\tendcase ;\n\nmatcher is match\n\nhide{ \n\t*str *pat *pat==*str pass reject advance \n\tadvance-string advance-regex matcher ++ \n}hide\n\n( ==================== Matcher ================================ )\n\n\n( ==================== Cons Cells ============================= )\n\n( From http:\/\/sametwice.com\/cons.fs, this could be improved if the optional\nmemory allocation words were added to the interpreter. This provides\na simple \"cons cell\" data structure. There is currently no way to\nfree allocated cells )\n\n: car! ( value cons-addr -- : store a value in the car cell of a cons cell ) \n\t! ;\n\n: cdr! ( value cons-addr -- : store a value in the cdr cell of a cons cell )\n\tcell+ ! ;\n\n: car@ ( cons-addr -- car-val : retrieve car value from cons cell )\n\t@ ;\n\n: cdr@ ( cons-addr -- cdr-val : retrieve cdr value from cons cell )\n\tcell+ @ ;\n\n: cons ( car-val cdr-val -- cons-addr : allocate a new cons cell )\n\tswap here >r , , r> ;\n\n: cons0 0 0 cons ;\n\nmarker cleanup\n77 987 cons constant x\nT{ x car@ -> 77 }T\nT{ x cdr@ -> 987 }T\nT{ 55 x cdr! x car@ x cdr@ -> 77 55 }T\nT{ 44 x car! x car@ x cdr@ -> 44 55 }T\ncleanup\n\n( ==================== Cons Cells ============================= )\n\n( ==================== Miscellaneous ========================== )\n\n: license ( -- : print out license information )\n\" \nThe MIT License (MIT)\n\nCopyright (c) 2016 Richard James Howe\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the 'Software'),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand\/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\nTHE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\nOTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\nARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE. \n\n\" \n;\n\n( ==================== Version information =================== )\n\n4 constant version\n\n( ==================== Version information =================== )\n\n( ==================== Core utilities ======================== )\n( Read the header of a core file and process it, printing the\nresults out )\n\n8 constant header-size ( size of Forth core file header )\n8 constant size-field-size ( the size in bytes of the size field in the core file )\n0 variable core-file ( core fileid we are reading in )\n0 variable core-cell-size ( cell size of Forth core )\n0 variable core-version ( version of core file )\n0 variable core-endianess ( endianess of core we are reading in )\n\n( save space to read in header )\ncreate header header-size chars allot\n: cheader ( -- c-addr : header char address )\n\theader chars> ;\ncreate size-field size-field-size chars allot\n: csize-field ( -- c-addr : address of place size field is stored in )\n\tsize-field chars> ;\n\n0\nenum header-magic0 ( magic number 0 : FF ) \nenum header-magic1 ( magic number 1 : '4' )\nenum header-magic2 ( magic number 2 : 'T' )\nenum header-magic3 ( magic number 3 : 'H' )\nenum header-cell-size ( size of a forth cell, either 2, 4 or 8 bytes )\nenum header-version ( version of the forth core )\nenum header-endianess ( endianess of the core )\nenum header-log2size ( binary logarithm of the core size )\n\n: cleanup ( -- : cleanup before abort )\n\tcore-file @ ?dup 0<> if close-file drop then ;\n\n: invalid-header ( bool -- : abort if header is invalid )\n\t<> if cleanup abort\" invalid header\" then ;\n\n: save-core-cell-size ( char -- : save the core file cell size, checking if it is valid )\n\tcore-cell-size !\n\t\" cell size:\" tab\n\tcore-cell-size @ 2 = if 2 . cr exit then\n\tcore-cell-size @ 4 = if 4 . cr exit then\n\tcore-cell-size @ 8 = if 8 . cr exit then\n\tcleanup core-cell-size @ . abort\" : invalid cell size\" ;\n\n: check-version-compatibility ( char -- : checks the version compatibility of the core file ) \n\tcore-version !\n\tcore-version @ version = if \" version: \" version . cr exit then\n\tcleanup core-version @ . abort\" : unknown version number\" ;\n\n: save-endianess ( char -- : save the endianess, checking if it is valid )\n\tcore-endianess !\n\t\" endianess:\" tab\n\tcore-endianess @ 0 = if \" big\" cr exit then\n\tcore-endianess @ 1 = if \" little\" cr exit then\n\tcleanup core-endianess @ . abort\" invalid endianess\" then ;\n\n: read-or-abort ( c-addr size fileid -- : )\n\tover >r read-file \n\t 0<> if cleanup abort\" file read failed\" then\n\tr> <> if cleanup abort\" header too small\" then ;\n\n: header? ( -- : print out header information )\n\tcheader header-size core-file @ read-or-abort\n\t( \" raw header:\" header 2 dump )\n\tcheader header-magic0 + c@ 255 invalid-header\n\tcheader header-magic1 + c@ [char] 4 invalid-header\n\tcheader header-magic2 + c@ [char] T invalid-header\n\tcheader header-magic3 + c@ [char] H invalid-header\n\tcheader header-cell-size + c@ save-core-cell-size\n\tcheader header-version + c@ check-version-compatibility\n\tcheader header-endianess + c@ save-endianess\n\t\" valid header\" cr ;\n\n: size? ( -- : print out core file size )\n\t\" size: \" cheader header-log2size + c@ 1 swap lshift . cr ;\n\n: core ( c-addr u -- : analyze a Forth core file from disk given its file name )\n\t2dup \" core file:\" tab type cr\n\tr\/o open-file throw core-file ! \n\theader?\n\tsize?\n\tcore-file @ close-file drop ;\n\n( s\" forth.core\" core )\n\nhide{ \nheader-size header? \nheader-magic0 header-magic1 header-magic2 header-magic3\nheader-version header-cell-size header-endianess header-log2size\nheader \ncore-file save-core-cell-size check-version-compatibility\ncore-cell-size cheader\ncore-endianess core-version save-endianess invalid-header\ncleanup size-field csize-field size-field-size\nread-or-abort size?\n}hide\n\n( ==================== Core utilities ======================== )\n\n( ==================== RLE =================================== )\n\n( These set of words implement Run Length Compression, which can be used for\nsaving space when compressing the core files generated by Forth programs, which\ncontain mostly runs of NUL characters. \n\nThe format of the encoded data is quite simple, there is a command byte\nfollowed by data. The command byte encodes only two commands; encode a run of\nliteral data and repeat the next character. \n\nIf the command byte is greater than X the command is a run of characters, \nX is then subtracted from the command byte and this is the number of \ncharacters that is to be copied verbatim when decompressing.\n\nIf the command byte is less than or equal to X then this number, plus one, is \nused to repeat the next data byte in the input stream.\n\nX is 128 for this application, but could be adjusted for better compression\ndepending on what the data looks like. \n\nExample:\n\t\n\t2 'a' 130 'b' 'c' 3 'd'\n\nBecomes:\n\n\taabcddd \n\nExample usage:\n\n\t: extract\n\t\tc\" forth.core\" w\/o open-file throw\n\t\tc\" forth.core.rle\" r\/o open-file throw\n\t\tdecompress ;\n\textract\n\n@note file redirection could be used for the input as well\n@todo compression, and reading\/writing to strings )\n\n: cpad pad chars> ;\n\n0 variable out\n128 constant run-length\n\n: more ( file-id -- char : read in a single character )\n\t>r cpad r> read-char throw cpad c@ ;\n\n: repeated ( count file-id -- : repeat a character count times )\n\tmore swap 0 do dup emit loop drop ;\n\n: literals ( count file-id -- : extract a literal run )\n\t>r cpad swap r> read-file throw cpad swap type ;\n\n: command ( file-id -- : process an RLE command )\n\tdup \n\t>r more \n\tdup run-length u> \n\tif \n\t\trun-length - r> literals \n\telse \n\t\t1+ r> repeated \n\tthen ;\n\n: redirect ( file-id-out -- : save current output pointer, redirect to output )\n\t`fout @ out ! `fout ! ;\n\n: restore ( -- : restore previous output pointer )\n\tout @ `fout ! ;\n\n: decompress ( file-id-out file-id-in -- : decompress an RLE encoded file )\n\tswap\n\tredirect\n\tbegin dup ' command catch until ( process commands until input exhausted )\n\t2drop ( drop twice because catch will restore stack before 'command' )\n\trestore ; ( restore input stream )\n\nhide{ literals repeated more out run-length command }hide\n\n( ==================== RLE =================================== )\n\n( ==================== Generate C Core file ================== )\n( The word core2c reads in a core file and turns it into a C file which \ncan then be compiled into the forth interpreter in a bootstrapping like\nprocess.\n\nUsage:\n c\" forth.core\" c\" core.gen.c\" core2c )\n\n0 variable count\n\n: wbyte ( u char -- : write a byte )\n\tpnum drop\n\t[char] , emit\n\t16 mod 0= if cr then ;\n\n: advance ( char -- : advance counter and print byte )\n\tcount 1+! count @ swap wbyte ;\n\n: hexify ( fileid -- fileid : turn core file into C numbers in array )\n\t0 count !\n\tbegin dup getchar 0= while advance repeat drop ;\n\n: quote ( -- : emit a quote character )\n\t[char] \" emit ;\n\n: core2c ( c-addr u c-addr u -- ior : generate a C file from a core file )\n\tw\/o open-file throw >r\n\tr\/o open-file ?dup-if r> close-file throw throw then\n\tr> redirect\n\t\" #include \" quote \" libforth.h\" quote cr\n\t\" unsigned char forth_core_data[] = {\" cr\n\thexify \n\t\" };\" cr\n\t\" forth_cell_t forth_core_size = \" count @ . \" ;\" cr cr\n\tclose-file\n\t`fout @ close-file \n\trestore or ;\n\nhide{ wbyte hexify count quote advance }hide\n \n( ==================== Generate C Core file ================== )\n\n: wc ( c-addr u -- u : count the bytes in a file )\n\tr\/o open-file throw\n\t0 swap\n\tbegin dup getchar nip 0= while nos1+ repeat close-file throw ;\n\n( ==================== Save Core file ======================== )\n\n( The following functionality allows the user to save the core file\nfrom within the running interpreter. The Forth core files have a very simple\nformat which means the words for doing this do not have to be too long, a header\nhas to emitted with a few calculated values and then the contents of the\nForths memory after this )\n\n( This write the header out to the current output device, this\nwill be redirected to a file )\n: header ( -- : write the header out )\n\t0xff emit ( magic 0 )\n\t[char] 4 emit ( magic 1 )\n\t[char] T emit ( magic 2 )\n\t[char] H emit ( magic 3 )\n\tsize emit ( cell size in bytes )\n\tversion emit ( core version )\n\tendian not emit ( endianess )\n\tmax-core log2 emit ; ( size field )\n\n: data ( -- : write the data out )\n\t0 max-core chars> `fout @ write-file throw drop ;\n\n: encore ( -- : write the core file out )\n\theader\n\tdata ;\n\n: save-core ( c-addr u -- : save core file or throw error ) \n\tw\/o open-file throw dup\n\tredirect \n\t\t' encore catch swap close-file throw \n\trestore ;\n\n( The following code illustrates an example of setting up a\nForth core file to execute a word when the core file is loaded.\nIn the example the word \"hello-world\" will be executed, which will\nalso quit the interpreter:\n\n\t\\ Only works for immediate words for now, we define\n\t\\ the word we wish to be executed when the forth core\n\t\\ is loaded\n\t: hello-world immediate\n\t\t\" Hello, World!\" cr bye ;\n\n\t\\ The following sets the starting word to our newly\n\t\\ defined word:\n\tfind hello-world cfa start!\n\n\t\\ Now we can save the core file out:\n\ts\" forth.core\" save-core \n\nThis can be used, in conjunction with aspects of the build system,\nto produce a standalone executable that will run only a single Forth\nword. )\n\nhide{ redirect restore data encore header }hide\n\n( ==================== Save Core file ======================== )\n\n( ==================== Hex dump ============================== )\n\n( @todo hexdump can read in too many characters and it does not\nprint out the correct address\n@todo utilities for easy redirecting of file input\/output )\n: input >r cpad 128 r> read-file ; ( file-id -- u 0 | error )\n: clean cpad 128 0 fill ; ( -- )\n: cdump cpad chars swap aligned chars dump ; ( u -- )\n: hexdump ( file-id -- : [hex]dump a file to the screen )\n\tdup \n\tclean\n\tinput if 2drop exit then\n\t?dup-if cdump else drop exit then\n\ttail ; \n\nhide{ more cpad clean cdump input }hide\n\n( ==================== Hex dump ============================== )\n\n( ==================== Date ================================== )\n\n( Rather annoyingly months are start from 1 but weekdays from 0 )\n\n: >month ( month -- )\n\tcase\n\t\t 1 of \" Jan \" endof\n\t\t 2 of \" Feb \" endof\n\t\t 3 of \" Mar \" endof\n\t\t 4 of \" Apr \" endof\n\t\t 5 of \" May \" endof\n\t\t 6 of \" Jun \" endof\n\t\t 7 of \" Jul \" endof\n\t\t 8 of \" Aug \" endof\n\t\t 9 of \" Sep \" endof\n\t\t10 of \" Oct \" endof\n\t\t11 of \" Nov \" endof\n\t\t12 of \" Dec \" endof\n\tendcase drop ;\n\n: .day ( day -- : add ordinal to day )\n\t10 mod\n\tcase\n\t\t1 of \" st \" drop exit endof\n\t\t2 of \" nd \" drop exit endof\n\t\t3 of \" rd \" drop exit endof\n\t\t\" th \" \n\tendcase drop ;\n\n: >day ( day -- : add ordinal to day of month )\n\tdup u.\n\tdup 1 10 within if .day exit then\n\tdup 10 20 within if \" th\" drop exit then\n\t.day ;\n\n: >weekday ( weekday -- : print the weekday )\n\tcase\n\t\t0 of \" Sun \" endof\n\t\t1 of \" Mon \" endof\n\t\t2 of \" Tue \" endof\n\t\t3 of \" Wed \" endof\n\t\t4 of \" Thu \" endof\n\t\t5 of \" Fri \" endof\n\t\t6 of \" Sat \" endof\n\tendcase drop ;\n\n: padded ( u -- : print out a run of zero characters )\n\t0 do [char] 0 emit loop ;\n\n: 0u. ( u -- : print a zero padded number )\n\tdup 10 u< if 1 padded then u. space ;\n\n: .date ( date -- : print the date )\n\tif \" DST \" else \" GMT \" then \n\tdrop ( no need for days of year)\n\t>weekday\n\t. ( year ) \n\t>month \n\t>day \n\t0u. ( hour )\n\t0u. ( minute )\n\t0u. ( second ) cr ;\n\n: time&date ( -- second minute hour day month year )\n\tdate\n\t3drop ;\n\nhide{ 0u. >weekday .day >day >month padded }hide\n\n( ==================== Date ================================== )\n\n( Looking at most Forths dictionary with \"words\" command they tend\nto have a lot of words that do not mean anything but to the implementers\nof that specific Forth, here we clean up as many non standard words as\npossible. )\nhide{ \n do-string ')' alignment-bits \n dictionary-start hidden? hidden-mask instruction-mask\n max-core dolist x x! x@ write-exit\n max-string-length \n original-exit\n pnum evaluator \n TrueFalse >instruction print-header\n print-name print-start print-previous print-immediate\n print-instruction xt-instruction defined-word? print-defined\n `state\n `source-id `sin `sidx `slen `start-address `fin `fout `stdin\n `stdout `stderr `argc `argv `debug `invalid `top `instruction\n `stack-size `error-handler `x `y `handler _emit\n}hide\n\n( \n## Forth To List\n\nThe following is a To-Do list for the Forth code itself, along with any\nother ideas.\n\n* FORTH, VOCABULARY\n* \"Value\", \"To\", \"Is\"\n* Double cell words and floating point library\n* The interpreter should use character based addresses, instead of\nword based, and use values that are actual valid pointers, this\nwill allow easier interaction with the world outside the virtual machine\n* common words and actions should be factored out to simplify\ndefinitions of other words, their standards compliant version found\nif any\n* Allow the processing of argc and argv, the mechanism by which that\nthis can be achieved needs to be worked out. However all processing that\nis currently done in \"main.c\" should be done within the Forth interpreter\ninstead.\n* A built in version of \"dump\" and \"words\" should be added to the Forth\nstarting vocabulary, simplified versions that can be hidden.\n* Here documents, string literals. Examples of these can be found online\nat Rosetta Code, although the Forth versions online will need adapting.\n* Document the words in this file and built in words better, also turn this\ndocument into a literate Forth file.\n* Sort out \"'\", \"[']\", \"find\", \"compile,\" \n* Proper booleans should be used throughout, that is -1 is true, and 0 is\nfalse.\n* File operation primitives that close the file stream [and possibly restore\nI\/O to stdin\/stdout] if an error occurs, and then re-throws, should be made.\n* Implement as many things from http:\/\/lars.nocrew.org\/forth2012\/implement.html\nas is sensible. \n* CASE Statements http:\/\/dxforth.netbay.com.au\/miser.html\n* The current words that implement I\/O redirection need to be improved, and documented,\nI think this is quite a useful and powerful mechanism to use within Forth that simplifies\nprograms. This is a must and will make writing utilities in Forth a *lot* easier \n\nImplement:\n\nhttp:\/\/rosettacode.org\/wiki\/CRC-32#Forth\nhttp:\/\/rosettacode.org\/wiki\/Monte_Carlo_methods#Forth \n\nAnd various other things from Rosetta Code.\n\n\n)\n\n( \nThe following will not work as we might actually be reading from a string [`sin]\nnot `fin. \n: key 32 chars> 1 `fin @ read-file drop 0 = if 0 else 32 chars> c@ then ; )\n\nverbose [if] \n\t.( FORTH: libforth successfully loaded.) cr\n\t.( Type 'help' and press return for a basic introduction.) cr\n\t.( Core: ) here . \" \/ \" here unused + . cr\n\t \n\t.( The MIT License ) cr\n\t.( ) cr\n\t.( Copyright 2016 Richard James Howe) cr\n\t.( ) cr\n\t.( Permission is hereby granted, free of charge, to any person obtaining a) cr\n\t.( copy of this software and associated documentation files [the \"Software\"],) cr\n\t.( to deal in the Software without restriction, including without limitation) cr\n\t.( the rights to use, copy, modify, merge, publish, distribute, sublicense,) cr\n\t.( and\/or sell copies of the Software, and to permit persons to whom the) cr\n\t.( Software is furnished to do so, subject to the following conditions:) cr\n\t.( ) cr\n\t.( The above copyright notice and this permission notice shall be included) cr\n\t.( in all copies or substantial portions of the Software.) cr\n\t.( ) cr\n\t.( THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR) cr\n\t.( IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,) cr\n\t.( FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL) cr\n\t.( THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR) cr\n\t.( OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,) cr\n\t.( ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR) cr\n\t.( OTHER DEALINGS IN THE SOFTWARE. ) cr\n[then]\n\n( \\ integrate simple 'dump' and 'words' into initial forth program \n: nl dup 3 and not ;\n: ?? \\ addr1 \n nl if dup cr . [char] : emit space then ? ;\n: dump \\ addr n --\n\tbase @ >r hex over + swap 1- begin 1+ 2dup dup ?? 2+ u< until r> base ! ; )\n\n\n","old_contents":"#!.\/forth \n( ==================================================================== )\n( ==================================================================== )\n( ==================================================================== )\n( \n\tTHIS CODE IS CURRENTLY NON FUNCTIONAL\n\tTHIS CODE IS CURRENTLY NON FUNCTIONAL\n\tTHIS CODE IS CURRENTLY NON FUNCTIONAL\n\tTHIS CODE IS CURRENTLY NON FUNCTIONAL\n\tTHIS CODE IS CURRENTLY NON FUNCTIONAL\n\n\tThis is due to a large change in the interpreter, it will\n\ttake time to fix this, however it will be an improvement.\n)\n( ==================================================================== )\n( ==================================================================== )\n( ==================================================================== )\n( ==================================================================== )\n( \nWelcome to libforth, A dialect of Forth. Like all versions of Forth this\nversion is a little idiosyncratic, but how the interpreter works is\ndocumented here and in various other files.\n\nThis file contains most of the start up code, some basic start up code\nis executed in the C file as well which makes programming at least bearable.\nMost of Forth is programmed in itself, which may seem odd if your back\nground in programming comes from more traditional language [such as C],\nalthough less so if you know already know lisp.\n\nFor more information about this interpreter and Forth see:\n\thttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\treadme.md : for a manual for this interpreter\n\tlibforth.h : for information about the C API\n\tlibforth.c : for the interpreter itself\n\tunit.c : a series of unit tests against libforth.c\n\tunit.fth : a series of unit tests against this file\n\nThe interpreter and this code originally descend from a Forth interpreter\nwritten in 1992 for the International obfuscated C Coding Competition\n\nSee:\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\nThe manual for the interpreter should be read first before looking into this\ncode. It is important to understand the execution model of Forth, especially\nthe differences between command and compile mode, and how immediate and compiling\nwords work.\n\nThe structure of this file is as follows:\n\n * Basic Word Set\n * Extended Word Set\n * CREATE DOES>\n * DO...LOOP\n * CASE statements\n * Conditional Compilation\n * Endian Words\n * Misc words\n * Random Numbers\n * ANSI Escape Codes\n * Prime Numbers\n * Debugging info\n * Files\n * Blocks\n * Matcher\n * Cons Cells\n * Miscellaneous\n * Core utilities\n\nEach of these sections is clearly labeled and they are generally in dependency order.\n\nUnfortunately the code in this file is not as portable as it could be, it makes\nassumptions about the size of cells provided by the virtual machine, which will\ntake time to rectify. Some of the constructs are subtly different from the\nDPANs Forth specification, which is usually noted. Eventually this should\nalso be fixed.)\n\n( ========================== Basic Word Set ================================== )\n\n( \nWe'll begin by defining very simple words we can use later, these a very\nbasic words, that perform simple tasks, they will not require much explanation.\n\nEven though the words are simple, their stack comment and a description for\nthem will still be included so external tools can process and automatically\nextract the document string for a given work.\n)\n\n: 1+ ( x -- x : increment a number ) \n\t1 + ;\n\n: 1- ( x -- x : decrement a number ) \n\t1 - ;\n\n: chars ( c-addr -- addr : convert a character address to an address )\n\tsize \/ ; \n\n: chars> ( addr -- c-addr: convert an address to a character address )\n\tsize * ; \n\n: tab ( -- : print a tab character to current output device )\n\t9 emit ;\n\n: 0= ( x -- bool : is 'x' equal to zero? )\n\t0 = ;\n\n: not ( x -- bool : is 'x' true? )\n\t0= ;\n\n: <> ( x x -- bool : not equal )\n\t= 0= ;\n\n: logical ( x -- bool : turn a value into a boolean ) \n\tnot not ;\n\n: :: ( -- : compiling version of ':' )\n\t[ find : , ] ;\n\n: '\\n' ( -- n : push the newline character )\n\t10 ;\n\n: cr ( -- : emit a newline character )\n\t'\\n' emit ;\n\n: hidden-mask ( -- x : pushes mask for the hide bit in a words MISC field )\n\t0x80 ;\n\n: instruction-mask ( -- x : pushes mask for the first code word in a words MISC field )\n\t0x7f ;\n\n: hidden? ( PWD -- PWD bool : is a word hidden, given the words PWD field ) \n\tdup 1+ @ hidden-mask and logical ;\n\n: dolist ( -- x : run code word, threaded code interpreter instruction )\n\t1 ; \n\n: dolit ( -- x : location of special \"push\" word )\n\t2 ;\n\n: 2, ( x x -- : write two values into the dictionary )\n\t, , ;\n\n: [literal] ( x -- : write a literal into the dictionary )\n\tdolit 2, ; \n\n: literal ( x -- : immediately write a literal into the dictionary )\n\timmediate [literal] ;\n\n: sliteral immediate ( I: c-addr u --, Run: -- c-addr u )\n\tswap [literal] [literal] ;\n\n( space saving measure )\n-1 : -1 literal ;\n 0 : 0 literal ;\n 1 : 1 literal ;\n 2 : 2 literal ;\n 3 : 3 literal ;\n\n: min-signed-integer ( -- x : push the minimum signed integer value )\n\t[ -1 -1 1 rshift invert and ] literal ;\n\n: max-signed-integer ( -- x : push the maximum signed integer value )\n\t[ min-signed-integer invert ] literal ;\n\n: < ( x1 x2 -- bool : signed less than comparison )\n\t- dup if max-signed-integer u> else logical then ;\n\n: > ( x1 x2 -- bool : signed greater than comparison )\n\t- dup if max-signed-integer u< else logical then ;\n\n: 2literal immediate ( x x -- : immediate write two literals into the dictionary )\n\tswap [literal] [literal] ;\n\n: latest ( get latest defined word )\n\tpwd @ ; \n\n: stdin ( -- fileid : push the fileid for the standard input channel ) \n\t`stdin @ ;\n\n: stdout ( -- fileid : push the fileid for the standard output channel ) \n\t`stdout @ ;\n\n: stderr ( -- fileid : push the fileid for the standard error channel ) \n\t`stderr @ ;\n\n: stdin? ( -- bool : are we reading from standard input )\n\t`fin @ stdin = ;\n\n: false ( -- x : push the value representing false )\n\t0 ;\n\n: true ( -- x : push the value representing true )\n\t-1 ;\n\n: *+ ( x1 x2 x3 -- x ) \n\t* + ;\n\t\n: 2- ( x -- x : decrement by two )\n\t2 - ( x -- x ) ;\n\n: 2+ ( x -- x : increment by two )\n\t2 + ( x -- x ) ;\n\n: 3+ ( x -- x : increment by three )\n\t3 + ( x -- x ) ;\n\n: 2* ( x -- x : multiply by two )\n\t1 lshift ( x -- x ) ;\n\n: 2\/ ( x -- x : divide by two )\n\t1 rshift ( x -- x ) ;\n\n: 4* ( x -- x : multiply by four )\n\t2 lshift ( x -- x ) ;\n\n: 4\/ ( x -- x : divide by four )\n\t2 rshift ( x -- x ) ;\n\n: 8* ( x -- x : multiply by eight )\n\t3 lshift ( x -- x ) ;\n\n: 8\/ ( x -- x : divide by eight )\n\t3 rshift ( x -- x ) ;\n\n: 256* ( x -- x : multiply by 256 )\n\t8 lshift ( x -- x ) ;\n\n: 256\/ ( x -- x : divide by 256 )\n\t8 rshift ( x -- x ) ;\n\n: 2dup ( x1 x2 -- x1 x2 x1 x2 : duplicate two values )\n\tover over ;\n\n: mod ( x u -- x : calculate the remainder of x divided by u ) \n\t2dup \/ * - ;\n\n( @todo implement um\/mod in the VM, then use this to implement \/ and mod )\n: um\/mod ( x1 x2 -- rem quot : calculate the remainder and quotient of x1 divided by x2 ) \n\t2dup \/ >r mod r> ;\n\n: *\/ ( x1 x2 x3 -- x4 : multiply then divide, @warning this does not use a double cell for the multiply )\n\t * \/ ; \n\n: char ( -- x : read in a character from the input steam )\n\tkey drop key ;\n\n: [char] ( -- x : immediately read in a character from the input stream )\n\timmediate char [literal] ;\n\n: postpone ( -- : postpone execution of the following immediate word )\n\timmediate find , ;\n\n: compose ( xt1 xt2 -- xt3 : create a new function from two xt-tokens )\n\t>r >r ( save execution tokens )\n\tpostpone :noname ( )\n\tr> , ( write first token )\n\tr> , ( write second token )\n\tpostpone ; ; ( terminate new :noname )\n\n: unless ( bool -- : like 'if' but execute clause if false )\n\timmediate ' 0= , postpone if ;\n\n: endif ( synonym for 'then' ) \n\timmediate postpone then ;\n\n: cell+ ( a-addr1 -- a-addr2 ) \n\t1+ ;\n\n: cells ( n1 -- n2 ) \n\timmediate ;\n\n: cell ( -- u : defined as 1 cells )\n\t1 cells ;\n\n: address-unit-bits ( -- x : push the number of bits in an address )\n\t[ cell size 8* * ] literal ;\n\n: negative? ( x -- bool : is a number negative? )\n\t[ 1 address-unit-bits 1- lshift ] literal and logical ;\n\n: mask-byte ( x -- x : generate mask byte ) \n\t8* 255 swap lshift ;\n\n: select-byte ( u i -- c ) \n\t8* rshift 0xff and ;\n\n: char+ ( c-addr -- c-addr : increment a character address by the size of one character ) \n\t1+ ;\n\n: 2chars ( c-addr1 c-addr2 -- addr addr : convert two character addresses to two cell addresses ) \n\tchars swap chars swap ;\n\n: 2chars> ( addr addr -- c-addr c-addr: convert two cell addresses to two character addresses )\n\tchars> swap chars> swap ;\n\n: hex ( -- : print out hex ) \n\t16 base ! ;\n\n: octal ( -- : print out octal ) \n\t8 base ! ;\n\n: binary ( -- : print out binary ) \n\t2 base ! ;\n\n: decimal ( -- : print out decimal ) \n\t0 base ! ;\n\n: negate ( x -- x ) \n\t-1 * ;\n\n: abs ( x -- u : return the absolute value of a number )\n\tdup negative? if negate then ;\n\n: square ( x -- x ) \n\tdup * ;\n\n: sum-of-squares ( a b -- c : compute a^2 + b^2 to get c )\n\tsquare swap square + ;\n\n: drup ( x y -- x x ) \n\tdrop dup ;\n\n: +! ( x addr -- : add x to a value stored at addr ) \n\ttuck @ + swap ! ;\n\n: 1+! ( addr -- : increment a value at an address ) \n\t1 swap +! ;\n\n: 1-! ( addr -- : decrement a value at an address ) \n\t-1 swap +! ;\n\n: toggle ( addr u -- : complement the value at address with the bit pattern u ) \n\tover @ xor swap ! ;\n\n: lsb ( x -- x : mask off the least significant byte of a cell ) \n\t255 and ;\n\n: \\ ( -- : immediate word, used for single line comments )\n\timmediate begin key '\\n' = until ;\n\n: ?dup ( x -- ? ) \n\tdup if dup then ;\n\n: min ( x y -- min : return the minimum of two integers ) \n\t2dup < if drop else swap drop then ;\n\n: max ( x y -- max : return the maximum of two integers ) \n\t2dup > if drop else swap drop then ;\n\n: limit ( x min max -- x : limit x with a minimum and maximum )\n\trot min max ;\n\n: >= ( x y -- bool ) \n\t< not ;\n\n: <= ( x y -- bool ) \n\t> not ;\n\n: 2@ ( a-addr -- x1 x2 : load two consecutive memory cells )\n\tdup 1+ @ swap @ ;\n\n: 2! ( x1 x2 a-addr -- : store two values as two consecutive memory cells )\n\t2dup ! nip 1+ ! ;\n\n: r@ ( -- x, R: x -- )\n\tr> r @ swap >r ;\n\n: rp@ ( -- x, R: x -- )\n\tr> r @ swap >r ;\n\n( @todo r!, rp! )\n\n: 0> ( x -- bool )\n\t0 > ;\n\n: 0< ( x -- bool )\n\t0 < ;\n\n: 0<> ( x -- bool )\n\t0 <> ;\n\n: signum ( x -- -1 | 0 | 1 : )\n\tdup 0< if drop -1 exit then\n\t 0> if 1 exit then\n\t0 ;\n\n: nand ( x x -- x : bitwise NAND ) \n\tand invert ;\n\n: odd ( x -- bool : is 'x' odd? )\n\t1 and ;\n\n: even ( x -- bool : is 'x' even? )\n\todd not ;\n\n: nor ( x x -- x : bitwise NOR ) \n\tor invert ;\n\n: ms ( u -- : wait at least 'u' milliseconds ) \n\tclock + begin dup clock u< until drop ;\n\n: sleep ( u -- : sleep for 'u' seconds )\n\t1000 * ms ;\n\n: align ( addr -- addr : align an address, nop in this implemented )\n\timmediate ; \n\n: ) ( -- : do nothing, this allows easy commenting out of code )\n\timmediate ;\n\n: bell ( -- : emit an ASCII BEL character ) \n\t7 emit ;\n\n: b\/buf ( -- u : bytes per buffer ) \n\t1024 ;\n\n: .d ( x -- x : debug print ) \n\tdup . ;\n\n: compile, ( x -- : )\n\t, ;\n\n: >mark ( -- : write a hole into the dictionary and push a pointer to it ) \n\there 0 , ;\n\n: r - r> u< ;\n\n: invalidate ( -- : invalidate this Forth core )\n\t1 `invalid ! ;\n\n: signed ( x -- bool : return true if sign bit set ) \n\t[ 1 size 8 * 1- lshift ] literal and logical ;\n\n: u>= ( x y -- bool : unsigned greater than or equal to )\n\t2dup u> >r = r> or ;\n\n: u<= ( x y -- bool : unsigned less than or equal to )\n\tu>= not ;\n\n: rdrop ( R: x -- : drop a value from the return stack )\n\tr> ( get caller's return address )\n\tr> ( get value to drop )\n\tdrop ( drop it like it's hot )\n\t>r ; ( return return address )\n\n: rdup\n\tr> ( get caller's return address )\n\tr> ( get value to duplicate )\n\tdup ( ... )\n\t>r >r >r ; ( make it all work )\n\n: again immediate\n\t( loop unconditionally in a begin-loop:\n\t\tbegin ... again )\n\t' branch , ;\n\n: source ( -- c-addr u )\n\t#tib ( size of input buffer, in characters )\n\ttib ; ( start of input buffer, in characters )\n\n: stdin?\n\t`fin @ `stdin @ = ;\n\n: source-id ( -- 0 | -1 | file-id )\n\t( \t\n\tValue Input Source\n\t-1 String\n\t0 Reading from user input \/ standard in\n\tfile-id )\n\t`source-id @ \n\t0= if\n\t\tstdin? if 0 else `fin @ then\n\telse\n\t\t-1\n\tthen ;\n\n: under ( x1 x2 -- x1 x1 x2 )\n\t>r dup r> ;\n\n: 2nip ( n1 n2 n3 n4 -- n3 n4 ) \n\t>r >r 2drop r> r> ;\n\n: 2over ( n1 n2 n3 n4 \u2013 n1 n2 n3 n4 n1 n2 )\n\t>r >r 2dup r> swap >r swap r> r> -rot ;\n\n: 2swap ( n1 n2 n3 n4 \u2013 n3 n4 n1 n2 )\n\t>r -rot r> -rot ;\n\n: 2tuck ( n1 n2 n3 n4 \u2013 n3 n4 n1 n2 n3 n4 )\n\t2swap 2over ;\n\n: nos1+ ( x1 x2 -- x1+1 x2 : increment the next variable on that stack )\n\tswap 1+ swap ;\n\n: ?dup-if immediate ( x -- x | - : ?dup and if rolled into one! )\n\t' ?dup , postpone if ;\n\n: ?if ( -- : non destructive if ) \n\timmediate ' dup , postpone if ;\n\n: hide ( token -- hide-token : this hides a word from being found by the interpreter )\n\t?dup-if\n\t\tdup @ hidden-mask or swap tuck ! exit\n\tthen 0 ;\n\n: hider ( WORD -- : hide with drop ) \n\tfind dup if hide then drop ;\n\n: reveal ( hide-token -- : reveal a hidden word ) \n\tdup @ hidden-mask invert and swap ! ;\n\n: original-exit \n\t[ find exit ] literal ;\n\n: exit ( -- : this will define a second version of exit, ';' will\n\tuse the original version, whilst everything else will\n\tuse this version, allowing us to distinguish between\n\tthe end of a word definition and an early exit by other\n\tmeans in \"see\" \n\t@todo Get rid of this, this is going to slow the interpreter\n\tdown *a lot*, for very little gain! )\n\t[ find exit hide ] rdrop exit [ reveal ] ;\n\n: ?exit ( x -- : exit current definition if not zero ) \n\tif rdrop exit then ;\n\n: number? ( c -- f : is character a number? )\n\t[char] 0 [ char 9 1+ ] literal within ;\n\n: lowercase? ( c -- f : is character lower case? )\n\t[char] a [ char z 1+ ] literal within ;\n\n: uppercase? ( C -- f : is character upper case? )\n\t[char] A [ char Z 1+ ] literal within ;\n\n: alpha? ( C -- f : is character part of the alphabet? )\n\tdup lowercase? swap uppercase? or ;\n\n: alphanumeric? ( C -- f : is character alphabetic or a number ? )\n\tdup alpha? swap number? or ;\n\n: printable? ( c -- bool : is printable, excluding new lines and tables )\n\t32 127 within ;\n\n: >upper ( c -- C : convert char to uppercase iff lower case )\n\tdup lowercase? if bl xor then ;\n\n: >lower ( C -- c : convert char to lowercase iff upper case )\n\tdup uppercase? if bl xor then ;\n\n: <=> ( x y -- z : spaceship operator! )\n\t2dup\n\t> if 2drop -1 exit then\n\t< ;\n\n: start-address ( -- c-addr : push the start address )\n\t`start-address @ ;\n\n: >real-address ( c-addr -- c-addr : convert an interpreter address to a real address )\n\tstart-address - ;\n\n: real-address> ( c-addr -- c-addr : convert a real address to an interpreter address )\n\tstart-address + ;\n\n: peek ( c-addr -- char : peek at real memory )\n\t>real-address c@ ;\n\n: poke ( char c-addr -- : poke a real memory address )\n\t>real-address c! ;\n\n: die! ( x -- : controls actions when encountering certain errors )\n\t`error-handler ! ;\n\n: start! ( cfa -- : set the word to execute at startup )\n\t`instruction ! ;\t\n\n: warm ( -- : restart the interpreter, warm restart )\n\t1 restart ;\n\n: trip ( x -- x x x : triplicate a number ) \n\tdup dup ;\n\n: roll ( xu xu-1 ... x0 u -- xu-1 ... x0 xu : move u+1 items on the top of the stack by u )\n\tdup 0 >\n\tif\n\t\tswap >r 1- roll r> swap\n\telse\n\t\tdrop\n\tthen ;\n\n: 2rot ( n1 n2 n3 n4 n5 n6 \u2013 n3 n4 n5 n6 n1 n2 )\n\t5 roll 5 roll ;\n\n: s>d ( x -- d : convert a signed value to a double width cell )\n\t( @note the if...else...then is only necessary as this Forths\n\tbooleans are 0 and 1, not 0 and -1 as it usually is )\n\tdup 0< if -1 else 0 then ;\n\n: trace ( level -- : set tracing level )\n\t`debug ! ;\n\n: verbose ( -- : get the log level )\n\t`debug @ ;\n\n: #pad ( -- u : offset into pad area )\n\t64 ;\n\n: pad\n\t( the pad is used for temporary storage, and moves\n\talong with dictionary pointer, always in front of it )\n\there #pad + ;\n\n: count ( c-addr1 -- c-addr2 u : get a string whose first char is its length )\n\tdup c@ nos1+ ;\n\n: bounds ( x y -- y+x x : make an upper and lower bound )\n\tover + swap ;\n\n: aligned ( unaligned -- aligned : align a pointer )\n\t[ size 1- ] literal + \n\t[ size 1- ] literal invert and ;\n\n\n( ================================== DUMP ================================== )\n: newline ( x -- x+1 : print a new line every fourth value )\n\tdup 3 and 0= if cr then 1+ ;\n\n: address ( num count -- count : print current address we are dumping every fourth value )\n\tdup >r\n\t1- 3 and 0= if . [char] : emit space else drop then\n\tr> ;\n\n: dump ( start count -- : print the contents of a section of memory )\n\tbase @ >r ( save current base )\n\thex ( switch to hex mode )\n\t1 >r ( save counter on return stack )\n\tover + swap ( calculate limits: start start+count )\n\tbegin \n\t\t2dup u> ( stop if gone past limits )\n\twhile \n\t\tdup r> address >r\n\t\tdup @ . 1+ \n\t\tr> newline >r\n\trepeat \n\tr> drop\n\tr> base !\n\t2drop ;\n\nhider newline\nhider address \n( ================================== DUMP ================================== )\n\n: cfa immediate ( find-address -- cfa )\n\t( Given the address of the PWD field of a word this\n\tfunction will return an execution token for the word )\n\t( @todo if < dictionary start PWD is invalid )\n\t ;\n\n: >body ( xt -- a-addr : a-addr is data field of a CREATEd word )\n\tcfa 5 + ;\n\n( @todo non-compliant, fix )\n: ['] immediate find [literal] ;\n\n: execute ( xt -- : given an execution token, execute the word )\n\t( create a word that pushes the address of a hole to write to\n\ta literal takes up two words, '!' takes up one, that's right,\n\tsome self modifying code! )\n\t\\ 1- ( execution token expects pointer to PWD field, it does not\n\t\\ \tcare about that field however, and increments past it )\n\t[ here 3+ literal ] ( calculate place to write to )\n\t! ( write an execution token to a hole )\n\t[ 0 , ] ; ( this is the hole we write )\n\n( See: http:\/\/lars.nocrew.org\/dpans\/dpans9.htm\n Code Reserved for\n ---- ------------\n -1 ABORT\n -2 ABORT\"\n -3 stack overflow\n -4 stack underflow\n -5 return stack overflow\n -6 return stack underflow\n -7 do-loops nested too deeply during execution\n -8 dictionary overflow\n -9 invalid memory address\n -10 division by zero\n -11 result out of range\n -12 argument type mismatch\n -13 undefined word\n -14 interpreting a compile-only word\n -15 invalid FORGET\n -16 attempt to use zero-length string as a name\n -17 pictured numeric output string overflow\n -18 parsed string overflow\n -19 definition name too long\n -20 write to a read-only location\n -21 unsupported operation [e.g., AT-XY on a\n too-dumb terminal]\n -22 control structure mismatch\n -23 address alignment exception\n -24 invalid numeric argument\n -25 return stack imbalance\n -26 loop parameters unavailable\n -27 invalid recursion\n -28 user interrupt\n -29 compiler nesting\n -30 obsolescent feature\n -31 >BODY used on non-CREATEd definition\n -32 invalid name argument [e.g., TO xxx]\n -33 block read exception\n -34 block write exception\n -35 invalid block number\n -36 invalid file position\n -37 file I\/O exception\n -38 non-existent file\n -39 unexpected end of file\n -40 invalid BASE for floating point conversion\n -41 loss of precision\n -42 floating-point divide by zero\n -43 floating-point result out of range\n -44 floating-point stack overflow\n -45 floating-point stack underflow\n -46 floating-point invalid argument\n -47 compilation word list deleted\n -48 invalid POSTPONE\n -49 search-order overflow\n -50 search-order underflow\n -51 compilation word list changed\n -52 control-flow stack overflow\n -53 exception stack overflow\n -54 floating-point underflow\n -55 floating-point unidentified fault\n -56 QUIT\n -57 exception in sending or receiving a character\n -58 [IF], [ELSE], or [THEN] exception )\n\n( @todo integrate catch\/throw into the interpreter as primitives )\n: catch ( xt -- exception# | 0 : return addr on stack )\n\tsp@ >r ( xt : save data stack pointer )\n\t`handler @ >r ( xt : and previous handler )\n\tr@ `handler ! ( xt : set current handler )\n\texecute ( execute returns if no throw )\n\tr> `handler ! ( restore previous handler )\n\tr> drop ( discard saved stack ptr )\n\t0 ; ( 0 : normal completion )\n\n( @todo use this everywhere )\n: throw ( ??? exception# -- ??? exception# )\n\t?dup-if ( exc# \\ 0 throw is no-op )\n\t\t`handler @ r ! ( exc# : restore prev return stack )\n\t\tr> `handler ! ( exc# : restore prev handler )\n\t\tr> swap >r ( saved-sp : exc# on return stack )\n\t\tsp! drop r> ( exc# : restore stack )\n\t\t( return to the caller of catch because return )\n\t\t( stack is restored to the state that existed )\n\t\t( when catch began execution )\n\tthen ; \n\n( @bug replacing \"drop drop\" with \"2drop\" causes a stack underflow in\n\"T{\" on a 32-bit platform, \"2drop\" can be used, but only if 3drop is defined\nafter \"interpret\" - something is ever so subtly going wrong. The code fails\nin \"T{\" when \"evaluate\" is called - which does lots of magic in the virtual\nmachine. This is the kind of bug that is difficult to find and reproduce, I\nhave not given up on it yet, however I am going to apply the \"fix\" for now,\nwhich is to change the definitions of 3drop to \"drop drop drop\"... for future\nreference the bug is present in git commit ccd802f9b6151da4c213465a72dacb1f7c22b0ac )\n\n: 3drop ( x1 x2 x3 -- )\n\tdrop drop drop ;\n\n: interpret \n\tbegin \n\t' read catch \n\t?dup-if [char] ! emit tab . cr then ( exception handler of last resort )\n\tagain ;\n\n: [interpret] \n\timmediate interpret ;\n\n( ============================================================================= )\n( WORKS UP TO HERE )\n( WORKS UP TO HERE )\n( WORKS UP TO HERE )\n( WORKS UP TO HERE )\n( WORKS UP TO HERE )\n( NB. It does not crash that is, previously defined words might be incorrect )\n( ============================================================================= )\n\n\n\\ interpret ( use the new interpret word, which can catch exceptions )\n\n\n\n\\ find [interpret] cfa start! ( the word executed on restart is now our new word )\n\n\n( ========================== Basic Word Set ================================== )\n\n( ========================== Extended Word Set =============================== )\n\n: log2 ( x -- log2 )\n\t( Computes the binary integer logarithm of a number,\n\tzero however returns itself instead of reporting an error )\n\t0 swap\n\tbegin\n\t\tnos1+ 2\/ dup 0=\n\tuntil\n\tdrop 1- ;\n\n: time ( \" ccc\" -- n : time the number of milliseconds it takes to execute a word )\n\tclock >r\n\tfind execute\n\tclock r> - ;\n\n: rdepth\n\tmax-core `stack-size @ - r @ swap - ;\n\n( defer...is is probably not standards compliant, it is still neat! Also, there\n is no error handling if \"find\" fails... )\n: (do-defer) ( -- self : pushes the location into which it is compiled )\n\tr> dup >r 1- ;\n\n: defer ( \" ccc\" -- , Run Time -- location : \n\tcreates a word that pushes a location to write an execution token into )\n\t:: ' (do-defer) , postpone ; ;\n\n: is ( location \" ccc\" -- : make a deferred word execute a word ) \n\tfind cfa swap ! ;\n\n\nhider (do-defer)\n\n( The \"tail\" function implements tail calls, which is just a jump\nto the beginning of the words definition, for example this\nword will never overflow the stack and will print \"1\" followed\nby a new line forever,\n\n\t: forever 1 . cr tail ;\n\nWhereas\n\n\t: forever 1 . cr recurse ;\n\nor\n\n\t: forever 1 . cr forever ;\n\nWould overflow the return stack. )\n\nhider tail\n: tail ( -- : perform tail recursion in current word definition )\n\timmediate\n\tlatest cell+\n\t' branch ,\n\there - cell+ , ;\n\n: recurse immediate\n\t( This function implements recursion, although this interpreter\n\tallows calling a word directly. If used incorrectly this will\n\tblow up the return stack.\n\n\tWe can test \"recurse\" with this factorial function:\n\t : factorial dup 2 < if drop 1 exit then dup 1- recurse * ; )\n\tlatest cell+ , ;\n\n: factorial ( x -- x : compute the factorial of a number )\n\tdup 2 < if drop 1 exit then dup 1- recurse * ;\n\n: myself ( -- : myself is a synonym for recurse ) \n\timmediate postpone recurse ;\n\n: gcd ( x1 x2 -- x : greatest common divisor )\n\tdup if tuck mod tail then drop ;\n\n( ========================== Extended Word Set =============================== )\n\n( The words described here on out get more complex and will require more\nof an explanation as to how they work. )\n\n( ========================== CREATE DOES> ==================================== )\n\n( The following section defines a pair of words \"create\" and \"does>\" which\nare a powerful set of words that can be used to make words that can create\nother words. \"create\" has both run time and compile time behavior, whilst\n\"does>\" only works at compile time in conjunction with \"create\". These two\nwords can be used to add constants, variables and arrays to the language,\namongst other things.\n\nA simple version of create is as follows\n\n\t: create :: 2 , here 2 + , ' exit , 0 state ! ;\n\nBut this version is much more limited.\n\n\"create\"...\"does>\" is one of the constructs that makes Forth Forth, it\nallows the creation of words which can define new words in themselves,\nand thus allows us to extend the language easily.\n)\n\n: write-quote ( -- : A word that writes ' into the dictionary )\n\t['] ' , ; \n\n: write-exit ( -- : A word that write exit into the dictionary )\n\toriginal-exit , ;\n\n: write-compile, ( -- : A word that writes , into the dictionary ) \n\t' , , ;\n\n: state! ( bool -- : set the compilation state variable ) \n\tstate ! ;\n\n: command-mode ( -- : put the interpreter into command mode )\n\tfalse state! ;\n\n: command-mode-create ( create a new work that pushes its data field )\n\t:: ( compile a word )\n\tdolit , ( write push into new word )\n\there 2+ , ( push a pointer to data field )\n\tpostpone ; ; ( write exit and switch to command mode )\n\n: mark write-compile, ( Write in a place holder 0 and push a pointer to to be used by does> )\n\twrite-quote write-exit write-compile, ( Write in an exit in the word we're compiling. )\n\t['] command-mode , ; ( Make sure to change the state back to command mode )\n\n: create immediate ( create word is quite a complex forth word )\n\tstate @ \n\tif \n\t\tpostpone ( hole-to-patch -- )\n\timmediate\n\twrite-exit ( we don't want the defining word to exit, but the *defined* word to )\n\there swap ! ( patch in the code fields to point to )\n\tdolist , ; ( write a run in )\n\nhider write-quote\nhider write-compile,\n\n( Now that we have create...does> we can use it to create arrays, variables\nand constants, as we mentioned before. )\n\n: array ( u c\" xxx\" -- : create a named array of length u ) \n\tcreate allot does> + ;\n\n: variable ( x c\" xxx\" -- : create a variable will initial value of x )\n\tcreate , does> ;\n\n: constant ( x c\" xxx\" -- : create a constant with value of x ) \n\tcreate , does> @ ;\n\n: table ( u c\" xxx\" --, Run Time: -- addr u : create a named table )\n\tcreate dup , allot does> dup @ ;\n\n: string ( u c\" xxx\" --, Run Time: -- addr u : create a named table )\n\tcreate dup , chars allot does> dup @ swap 1+ chars> swap ;\n\n\\ : +field \\ n <\"name\"> -- ; exec: addr -- 'addr\n\\ create over , +\n\\ does> @ + ;\n\\ \n\\ : begin-structure \\ -- addr 0 ; -- size\n\\ \tcreate\n\\ \there 0 0 , \\ mark stack, lay dummy\n\\ \tdoes> @ ; \\ -- rec-len\n\\ \n\\ : end-structure \\ addr n --\n\\ swap ! ; \\ set len \n\\ \n\\ begin-structure point\n\\ \tpoint +field p.x\n\\ \tpoint +field p.y\n\\ end-structure\n\\ \n\\ This should work...\n\\ : buffer: ( u c\" xxx\" --, Run Time: -- addr )\n\\\tcreate allot ;\n\n: 2constant \n\tcreate , , does> dup 1+ @ swap @ ;\n\n: 2variable \n\tcreate , , does> ;\n\n: enum ( x \" ccc\" -- x+1 : define a series of enumerations )\n\tdup constant 1+ ; \n\n( ========================== CREATE DOES> ==================================== )\n\n( ========================== DO...LOOP ======================================= )\n\n( The following section implements Forth's do...loop constructs, the\nword definitions are quite complex as it involves a lot of juggling of\nthe return stack. Along with begin...until do loops are one of the\nmain looping constructs. \n\nUnlike begin...until do accepts two values a limit and a starting value,\nthey are also words only to be used within a word definition, some Forths\nextend the semantics so looping constructs operate in command mode, this\nForth does not do that as it complicates things unnecessarily.\n\nExample:\n\t\n\t: example-1 10 1 do i . i 5 > if cr leave then loop 100 . cr ; \n\texample-1\n\nPrints:\n\t1 2 3 4 5 6\n\nIn \"example-1\" we can see the following:\n\n1. A limit, 10, and a start value, 1, passed to \"do\".\n2. A word called 'i', which is the current count of the loop\n3. If the count is greater than 5, we call a word call 'leave', this\nword exits the current loop context as well as the current calling\nword.\n4. \"100 . cr\" is never called. This should be changed in future\nrevision, but this version of leave exits the calling word as well.\n\n'i', 'j', and 'leave' *must* be used within a do...loop construct. \n\nIn order to remedy point 4. loop should not use branch but instead \nshould use a value to return to which it pushes to the return stack )\n\n: (do)\n\tswap ( swap the limit and start )\n\tr> ( save our return stack to temporary variable )\n\t-rot ( limit start return -- return start limit )\n\t>r ( push limit onto return stack )\n\t>r ( push start onto return stack )\n\t>r ; ( restore our return address )\n\n: do immediate ( Run time: high low -- : begin do...loop construct )\n\t' (do) ,\n\tpostpone begin ; \n\n: (unloop) ( -- , R: i limit -- : remove limit and i from )\n\tr> ( save our return address )\n\trdrop ( pop off i )\n\trdrop ( pop off limit )\n\t>r ; ( restore our return stack )\n\n: (+loop) ( x -- bool : increment loop variable by x and test it )\n\tr@ 1- ( get the pointer to i )\n\t+! ( add value to it )\n\tr@ 1- @ ( find i again )\n\tr@ 2- @ ( find the limit value )\n\tu>= ;\n\n: (loop) ( -- bool : increment loop variable by 1 and test it )\n\tr@ 1- ( get the pointer to i )\n\t1+! ( add one to it )\n\tr@ 1- @ ( find the value again )\n\tr@ 2- @ ( find the limit value )\n\tu>= ;\n\n: loop ( -- : end do...loop construct )\n\timmediate ' (loop) , postpone until ' (unloop) , ;\n\n: +loop ( x -- : end do...+loop loop construct )\n\timmediate ' (+loop) , postpone until ' (unloop) , ;\n\n: leave ( -- , R: i limit return -- : break out of a do-loop construct )\n\t(unloop)\n\trdrop ; ( return to the caller's caller routine )\n\n: ?leave ( x -- , R: i limit return -- | i limit return : conditional leave )\n\tif\n\t\t(unloop)\n\t\trdrop ( return to the caller's caller routine )\n\tthen ;\n\n: i ( -- i : Get current, or innermost, loop index in do...loop construct )\n\tr> r> ( pop off return address and i )\n\ttuck ( tuck i away )\n\t>r >r ; ( restore return stack )\n\n: j ( -- j : Get outermost loop index in do...loop construct )\n\t4 rpick ;\n\n( This is a simple test function for the looping, for interactive\ntesting and debugging:\n : mm 5 1 do i . cr 4 1 do j . tab i . cr loop loop ; )\n\n: range ( nX nY -- nX nX+1 ... nY ) \n\tnos1+ do i loop ;\n\n: repeater ( n0 X -- n0 ... nX ) \n\t1 do dup loop ;\n\n: sum ( n0 ... nX X -- sum<0..X> ) \n\t1 do + loop ;\n\n: mul ( n0 ... nX X -- mul<0..X> ) \n\t1 do * loop ;\n\n: reverse ( x1 ... xn n -- xn ... x1 : reverse n items on the stack )\n\t0 do i roll loop ;\n\n\n( ========================== DO...LOOP ======================================= )\n0 variable column-counter\n4 variable column-width\n\n: column ( i -- )\t\n\tcolumn-width @ mod not if cr then ;\n\n: reset-column\t\t\n\t0 column-counter ! ;\n\n: auto-column\t\t\n\tcolumn-counter dup @ column 1+! ;\n\n: alignment-bits \n\t[ 1 size log2 lshift 1- literal ] and ;\n\n: name ( PWD -- c-addr : given a pointer to the PWD field of a word get a pointer to the name of the word )\n\tdup 1+ @ 256\/ 127 and lsb - chars> ;\n\n0 variable x\n: x! ( x -- ) \n\tx ! ;\n\n: x@ ( -- x ) \n\tx @ ;\n\n: 2>r ( x1 x2 -- R: x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tswap\n\t\t>r\n\t\t>r\n\tx@ >r ; ( restore return address )\n\n: 2r> ( R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tr>\n\t\tr>\n\t\tswap\n\tx@ >r ; ( restore return address )\n\n: 2r@ ( -- x1 x2 , R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\tr> r>\n\t2dup\n\t>r >r\n\tswap\n\tx@ >r ; ( restore return address )\n\n: unused ( -- u : push the amount of core left ) \n\tmax-core here - ;\n\n: accumulator ( initial \" ccc\" -- : make a word that increments by a value and pushes the result )\n\tcreate , does> tuck +! @ ;\n\n: counter ( \" ccc\" --, Run Time: -- x : make a word that increments itself by one, starting from zero )\n\tcreate -1 , does> dup 1+! @ ;\n\n0 variable delim\n: accepter ( c-addr max delimiter -- i )\n\t( store a \"max\" number of chars at c-addr until \"delimiter\" encountered,\n\tthe number of characters stored is returned )\n\tdelim ! ( store delimiter used to stop string storage when encountered)\n\t0\n\tdo\n\t\tkey dup delim @ <>\n\t\tif\n\t\t\tover c! 1+\n\t\telse ( terminate string )\n\t\t\tdrop 0 swap c! \n\t\t\ti \n\t\t\tleave\n\t\tthen\n\tloop\n\t-11 throw ; ( read in too many chars )\nhider delim\n\n: skip\n\tkey drop >r 0 begin drop key dup rdup r> <> until rdrop ;\n\n: word ( c -- c-addr : parse until 'c' is encountered, push transient counted string )\n\tdup skip chere 1+ c!\n\t>r\n\tchere 2+\n\tpad here - chars>\n\tr> accepter 1+\n\tchere c!\n\tchere ;\n\nhider skip\n\n: accept ( c-addr +n1 -- +n2 : see accepter definition ) \n\t'\\n' accepter ;\n\n0xFFFF constant max-string-length\n\n: (.\") ( char -- c-addr u )\n\t( @todo This really needs simplifying, to do this\n\ta set of words that operate on a temporary buffer can\n\tbe used )\n\t( Write a string into word being currently defined, this\n\tcode has to jump over the string it has just put into the\n\tdictionary so normal execution of a word can continue. The\n\tlength and character address of the string are left on the\n\tstack )\n\t>r ( save delimiter )\n\t' branch , ( write in jump, this will jump past the string )\n\t>mark ( make hole )\n\tdup 1+ chars> ( calculate address to write to )\n\tmax-string-length \n\tr> ( restore delimiter )\n\taccepter dup >r ( write string into dictionary, save index )\n\taligned 2dup size \/ ( stack: length hole char-len hole )\n\t1+ dup allot ( update dictionary pointer with string length )\n\t1+ swap ! ( write place to jump to )\n\tdrop ( do not need string length anymore )\n\t1+ chars> ( calculate place to print )\n\tr> ; ( restore index and address of string )\n\n: length ( c-addr u -- u : push the length of an ASCIIZ string )\n tuck 0 do dup c@ 0= if 2drop i leave then 1+ loop ;\n\n: asciiz? ( c-addr u -- : is a Forth string also a ASCIIZ string )\n\ttuck length <> ;\n\n: asciiz ( c-addr u -- : trim a string until NUL terminator )\n\t2dup length nip ;\n\n: type ( c-addr u -- : print out 'u' characters at c-addr )\n\t0 do dup c@ emit 1+ loop drop ;\n\n: do-string ( char -- : write a string into the dictionary reading it until char is encountered )\n\t(.\") \n\tstate @ if swap [literal] [literal] then ;\n\n: fill ( c-addr u char -- : fill in an area of memory with a character, only if u is greater than zero )\n\t-rot\n\t0 do 2dup i + c! loop\n\t2drop ;\n\n: \/string ( c-addr1 u1 n -- c-addr2 u2 : advance a string by n characters )\n\tover min rot over + -rot - ;\n\n: compare ( c-addr1 u1 c-addr2 u2 -- n : compare two strings, not quite compliant yet )\n\t>r swap r> min >r\n\tstart-address + swap start-address + r>\n\tmemory-compare ;\n\n128 string sbuf\n: s\" ( \"ccc\" --, Run Time -- c-addr u )\n\tkey drop sbuf 0 fill sbuf [char] \" accepter sbuf drop swap ;\nhider sbuf\n\n( @todo these strings really need rethinking, state awareness needs to be removed... )\n: type, \n\tstate @ if ' type , else type then ;\n\n: c\" \n\timmediate key drop [char] \" do-string ;\n\n: \" \n\timmediate key drop [char] \" do-string type, ;\n\n: sprint ( c -- : print out chars until 'c' is encountered )\n\tkey drop ( drop next space )\n\t>r ( save delimiter )\n\tbegin\n\t\tkey dup ( get next character )\n\t\trdup r> ( get delimiter )\n\t\t<> if emit 0 then\n\tuntil rdrop ;\n\n: .( \n\timmediate [char] ) sprint ;\nhider sprint\n\n: .\" \n\timmediate key drop [char] \" do-string type, ;\n\nhider type,\n\n( This word really should be removed along with any usages of this word, it\nis not a very \"Forth\" like word, it accepts a pointer to an ASCIIZ string and\nprints it out, it also does not checking of the returned values from write-file )\n: print ( c-addr -- : print out a string to the standard output )\n\t-1 over >r length r> swap stdout write-file 2drop ;\n\n: ok \n\t\" ok\" cr ;\n\n: empty-stack ( x-n ... x-0 -- : empty the variable stack )\n\tbegin depth while drop repeat ;\n\n: (quit) ( -- : do the work of quit, without the restart )\n\t0 `source-id ! ( set source to read from file )\n\t`stdin @ `fin ! ( read from stdin )\n\tpostpone [ ( back into command mode )\n\t' interpret start! ; ( set interpreter starting word )\n\n: quit ( -- : Empty return stack, go back to command mode, read from stdin, interpret input )\n\t(quit)\n\t-1 restart ; ( restart the interpreter )\n\n: abort\n\t-1 throw ;\n\n: (abort\") ( do the work of abort )\n\t(quit)\n\t-2 throw ;\n\n: abort\" immediate \n\tpostpone \"\n\t' cr , ' (abort\") , ;\n\n( ==================== CASE statements ======================== )\n\n( for a simpler case statement:\n\tsee Volume 2, issue 3, page 48 of Forth Dimensions at\n\thttp:\/\/www.forth.org\/fd\/contents.html )\n\n( These case statements need improving, it is not standards compliant )\n: case immediate\n\t' branch , 3 , ( branch over the next branch )\n\there ' branch , ( mark: place endof branches back to with again )\n\t>mark swap ; ( mark: place endcase writes jump to with then )\n\n: over= ( x y -- x bool : over ... then = )\n\tover = ;\n\n: of\n\timmediate ' over= , postpone if ;\n\n: endof\n\timmediate over postpone again postpone then ;\n\n: endcase\n\timmediate 1+ postpone then drop ;\n\n( ==================== CASE statements ======================== )\n\n( ==================== Hiding Words =========================== )\n\n: }hide ( should only be matched with 'hide{' )\n\timmediate -22 throw ;\n\n: hide{ ( -- : hide a list of words, the list is terminated with \"}hide\" )\n\tbegin\n\t\tfind ( find next word )\n\t\tdup [ find }hide ] literal = if\n\t\t\tdrop exit ( terminate hide{ )\n\t\tthen\n\t\tdup 0= if -15 throw then\n\t\thide drop\n\tagain ;\n\n( ==================== Hiding Words =========================== )\n\n: spaces ( n -- : print n spaces ) \n\t0 do space loop ;\n\n: erase ( addr u : erase a block of memory )\n\t2chars> 0 fill ;\n\n: blank ( c-addr u : fills a string with spaces )\n\tbl fill ;\n\n( move should check that u is not negative )\n: move ( addr1 addr2 u -- : copy u words of memory from 'addr2' to 'addr1' )\n\t0 do\n\t\t2dup i + @ swap i + !\n\tloop\n\t2drop ;\n\n( It would be nice if move and cmove could share more code, as they do exactly\n the same thing but with different load and store functions, cmove> )\n: cmove ( c-addr1 c-addr2 u -- : copy u characters of memory from 'c-addr2' to 'c-addr1' )\n\t0 do\n\t\t2dup i + c@ swap i + c!\n\tloop\n\t2drop ;\n\n( ==================== Conditional Compilation ================ )\n\n( The words \"[if]\", \"[else]\" and \"[then]\" implement conditional compilation,\nthey can be nested as well\n\nSee http:\/\/lars.nocrew.org\/dpans\/dpans15.htm for more information\n\nA much simpler conditional compilation method is the following\nsingle word definition:\n\n : compile-line? 0= if [ find \\\\ , ] then ;\n\nWhich will skip a line if a conditional is false, and compile it\nif true )\n\n( These words really, really need refactoring, I could use the newly defined \n \"defer\" to help out with this )\n0 variable nest ( level of [if] nesting )\n0 variable [if]-word ( populated later with \"find [if]\" )\n0 variable [else]-word ( populated later with \"find [else]\")\n: [then] immediate ;\n: reset-nest 1 nest ! ;\n: unnest? [ find [then] ] literal = if nest 1-! then ;\n: nest? [if]-word @ = if nest 1+! then ;\n: end-nest? nest @ 0= ;\n: match-[else]? [else]-word @ = nest @ 1 = and ;\n\n: [if] ( bool -- : conditional execution )\n\tunless\n\t\treset-nest\n\t\tbegin\n\t\t\tfind\n\t\t\tdup nest?\n\t\t\tdup match-[else]? if drop exit then\n\t\t\t unnest?\n\t\t\tend-nest?\n\t\tuntil\n\tthen ;\n\n: [else] ( discard input until [then] encounter, nesting for [if] )\n\treset-nest\n\tbegin\n\t\tfind\n\t\tdup nest? unnest?\n\t\tend-nest?\n\tuntil ;\n\nfind [if] [if]-word !\nfind [else] [else]-word !\n\nhide{ \n[if]-word [else]-word nest reset-nest unnest? match-[else]? end-nest? nest? }hide\n\n( ==================== Conditional Compilation ================ )\n\n( ==================== Endian Words =========================== )\n\nsize 2 = [if] 0x0123 variable endianess [then]\nsize 4 = [if] 0x01234567 variable endianess [then]\nsize 8 = [if] 0x01234567abcdef variable endianess [then]\n\n: endian ( -- bool : returns the endianess of the processor, little = 0, big = 1 )\n\t[ endianess chars> c@ 0x01 = ] literal ;\nhider endianess\n\n: swap16 ( x -- x : swap the byte order a 16 bit number )\n\tdup 256* 0xff00 and >r 256\/ lsb r> or ;\n\nsize 4 >= [if] \n\t: swap32 \n\t\tdup 0xffff and swap16 16 lshift swap\n\t\t16 rshift 0xffff and swap16 or ;\n[then]\n\nsize 8 >= [if]\n\t: swap64 ( x -- x : swap the byte order of a 64 bit number )\n\t\t dup 0xffffffff and swap32 32 lshift swap\n\t\t 32 rshift 0xffffffff and swap32 or ;\n[then]\n\nsize 2 = [if]\n\tendian \n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\tswap16 ;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\t;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\tswap16 ;\n\t[then]\n[then]\n\nsize 4 = [if]\n\tendian \n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\tswap32 ;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\t;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\tswap32 ;\n\t[then]\n[then]\n\nsize 8 = [if]\n\tendian \n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\tswap64 ;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\t;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\tswap64 ;\n\t[then]\n[then]\n\n( ==================== Endian Words =========================== )\n\n( ==================== Misc words ============================= )\n\n0 variable counter\n\n: counted-column ( index -- : special column printing for dump )\n\tcounter @ column-width @ mod\n\tnot if cr . \" :\" space else drop then\n\tcounter 1+! ;\n\n: as-chars ( x n -- : print a cell out as characters, upto n chars )\n\t0 ( from zero to the size of a cell )\n\tdo\n\t\tdup ( copy variable to print out )\n\t\tsize i 1+ - select-byte ( select correct byte )\n\t\tdup printable? not ( is it not printable )\n\t\tif drop [char] . then ( print a '.' if it is not )\n\t\temit ( otherwise print it out )\n\tloop\n\tspace ( print out space after )\n\tdrop ; ( drop cell we have printed out )\n\n: lister ( addr u addr -- )\n\t0 counter ! 1- swap \n\tdo \n\t\tdup counted-column 1+ i ? i @ size as-chars \n\tloop ;\n\n( @todo this function should make use of 'defer' and 'is', then different\nversion of dump could be made that swapped out 'lister' )\n: dump ( addr u -- : dump out 'u' cells of memory starting from 'addr' )\n\tbase @ >r hex 1+ over + under lister drop r> base ! cr ;\n\nhide{ counted-column counter as-chars }hide\n\n: forgetter ( pwd-token -- : forget a found word and everything after it )\n\tdup @ pwd ! h ! ;\n\n( @bug will not work for immediate defined words \n@note Fig Forth had a word FENCE, if anything before this word was\nattempted to be forgotten then an exception is throw )\n: forget ( WORD -- : forget word and every word defined after it )\n\tfind dup 0= if -15 throw then 1- forgetter ;\n\n: marker ( WORD -- : make word the forgets itself and words after it)\n\t:: latest [literal] ' forgetter , postpone ; ;\nhider forgetter\n\n: ** ( b e -- x : exponent, raise 'b' to the power of 'e')\n\t?dup-if\n\t\tover swap\n\t\t1 do over * loop \n\t\tnip\n\telse\n\t\tdrop 1\n\tendif ;\n\n0 variable a\n0 variable b\n0 variable m\n: equal ( a1...an b1...bn n -- a1...an b1...bn bool : determine if two lists are equal )\n\t( example: \n\t\t1 2 3 \n\t\t1 2 3 \n\t\t3 equal \n\treturns: 1 )\n\tdup m ! 1+ 1 ( store copy of length and use as loop index )\n\tdo \n\t\ti 1- pick b ! ( store ith element of list in b1...bn )\n\t\ti m @ + 1- pick a ! ( store ith element of list in a1...an )\n\t\ta @ b @ <> ( compare a and b for equality )\n\t\tif 0 leave then ( unequal, finish early )\n\tloop 1 ; ( lists must be equal )\n\nhide{ a b m }hide\n\n: ndrop ( drop n items )\n\t?dup-if 0 do drop loop then ;\n\n( ==================== Misc words ============================= )\n\n( ==================== Pictured Numeric Output ================ )\n\n0 variable hld\n\n: overflow ( -- : )\n \there chars> pad chars> hld @ - u> if -17 throw then ;\n\n: hold ( char -- : add a character to the numeric output string )\n\toverflow pad chars> hld @ - c! hld 1+! ;\n\n: holds ( addr u -- )\n begin dup while 1- 2dup + c@ hold repeat 2drop ;\n\n: nbase ( -- base : in this forth 0 is a special base, push 10 is base is zero )\n\tbase @ dup 0= if drop 10 then ;\n\n: <# ( -- : setup pictured numeric output )\n\t0 hld ! ;\n\n: sign ( -- : add a sign to the pictured numeric output string )\n\t[char] - hold ;\n\n: # ( x -- x : divide x by base, turn into a character, put in pictured output string )\n\tnbase um\/mod swap \n \tdup 9 u>\n \tif 7 + then\n \t48 + hold ;\n\n: #s ( x -- 0 : repeatedly call # on x until x is zero )\n\tbegin # dup 0= until ; \n\n: #> ( -- c-addr u : end pictured output conversion, push output string to stack )\n\t0 hold ( NUL terminate string, just in case )\n\thld 1-! ( but do not include that in the count )\n\tpad chars> hld @ \n\ttuck - 1+ swap ;\n\n: u. ( u -- : display number in base 10 )\n\tbase @ >r decimal <# #s #> type drop r> base ! ;\n\nhide{ nbase overflow }hide\n\n( ==================== Pictured Numeric Output ================ )\n\n( ==================== ANSI Escape Codes ====================== )\n( Terminal colorization module, via ANSI Escape Codes\n \nsee: https:\/\/en.wikipedia.org\/wiki\/ANSI_escape_code\nThese codes will provide a relatively portable means of\nmanipulating a terminal )\n\n27 constant 'escape'\n: CSI 'escape' emit .\" [\" ;\n0 constant black\n1 constant red\n2 constant green\n3 constant yellow\n4 constant blue\n5 constant magenta\n6 constant cyan\n7 constant white\n: foreground 30 + ;\n: background 40 + ;\n0 constant dark\n1 constant bright\nfalse variable colorize \n\n: color ( brightness color-code -- : set the terminal color )\n\t( set color on an ANSI compliant terminal,\n\tfor example:\n\t\tbright red foreground color\n\tsets the foreground text to bright red )\n\tcolorize @ 0= if 2drop exit then \n\tCSI u. if .\" ;1\" then .\" m\" ;\n\n: at-xy ( x y -- : set ANSI terminal cursor position to x y )\n\tCSI u. [char] ; emit u. .\" H\" ;\n\n: page ( -- : clear ANSI terminal screen and move cursor to beginning ) \n\tCSI .\" 2J\" 1 1 at-xy ;\n\n: hide-cursor ( -- : hide the cursor from view ) \n\tCSI .\" ?25l\" ;\n\n: show-cursor ( -- : show the cursor ) \n\tCSI .\" ?25h\" ;\n\n: save-cursor ( -- : save cursor position ) \n\tCSI .\" s\" ;\n\n: restore-cursor ( -- : restore saved cursor position ) \n\tCSI .\" u\" ;\n\n: reset-color ( -- : reset terminal color to its default value)\n\tcolorize @ 0= if exit then\n\tCSI .\" 0m\" ;\n\nhide{ CSI }hide\n( ==================== ANSI Escape Codes ====================== )\n\n( ==================== Unit test framework =================== )\n\n256 string estring ( string to test )\n0 variable #estring ( actual string length )\n0 variable start ( starting depth )\n0 variable result ( result depth )\n0 variable check ( only check depth if -> is called )\n0 variable dictionary ( dictionary pointer on entering { )\n0 variable previous ( PWD register on entering { )\n\n: T ; ( hack until T{ can process words )\n\n: -> ( -- : save depth in variable ) \n\t1 check ! depth result ! ; \n\n: test estring drop #estring @ ; \n\n: fail ( -- : invalidate the forth interpreter and exit )\n\tinvalidate bye ;\n\n: neutral ( -- : neutral color )\n\t;\n\n: bad ( -- : bad color )\n\tdark red foreground color ;\n\n: good ( -- : good color )\n\tdark green foreground color ;\n\n: die bad test type reset-color cr fail ;\n\n: evaluate? ( bool -- : test if evaluation has failed )\n\tif .\" evaluation failed\" cr fail then ;\n\n: failed bad .\" failed\" reset-color cr ;\n\n: adjust ( x -- x : adjust a depth to take into account starting depth ) \n\tstart @ - ;\n\n: no-check? ( -- bool : if true we need to check the depth )\n\tcheck @ 0= ;\n\n: depth? ( -- : check if depth is correct )\n\tno-check? if exit then\n\tdepth adjust ( get depth and adjust for starting depth )\n\tresult @ adjust 2* = ( get results depth, same adjustment, should be\n\t half size of the depth ) \n\tif exit then ( pass )\n\tfailed\n\t.\" Unequal depths:\" cr\n\t.\" depth: \" depth . cr\n\t.\" result: \" result @ . cr\n\tdie ;\n\n: equal? ( -- : determine if results equals expected )\n\tno-check? if exit then\n\tresult @ adjust equal\n\tif exit then\n\tfailed\n\t.\" Result is not equal to expected values. \" cr \n\t.\" Stack: \" cr .s cr\n\tdie ;\n\n: display ( c-addr u -- : print out testing message in estring )\n\tverbose if neutral type else 2drop then ;\n\n: pass ( -- : print out passing message )\n\tverbose if good .\" ok \" cr reset-color then ;\n\n: save ( -- : save current dictionary )\n\tpwd @ previous !\n\there dictionary ! ;\n\n: restore ( -- : restore dictionary )\n\tprevious @ pwd ! \n\tdictionary @ h ! ;\n\n\n: T{ ( -- : perform a unit test )\n\tdepth start ! ( save start of stack depth )\n\t0 result ! ( reset result variable )\n\t0 check ! ( reset check variable )\n\testring 0 fill ( zero input string )\n\tsave ( save dictionary state )\n\tkey drop ( drop next character, which is a space )\n\testring [char] } accepter #estring ! ( read in string to test )\n\ttest display ( print which string we are testing )\n\ttest evaluate ( perform test )\n\tevaluate? ( evaluate successfully? )\n\tdepth? ( correct depth )\n\tequal? ( results equal to expected values? )\n\tpass ( print pass message )\n\tresult @ adjust 2* ndrop ( remove items on stack generated by test )\n\trestore ; ( restore dictionary to previous state )\n\nT{ }T\nT{ -> }T\nT{ 1 -> 1 }T\nT{ 1 2 -> 1 2 }T\nT{ : c 1 2 ; c -> 1 2 }T\nT{ :noname 2 ; :noname 3 + ; compose execute -> 5 }T\n\nhide{ \n\tpass test display\n\tadjust start save restore dictionary previous \n\tevaluate? equal? depth? estring #estring result\n\tcheck no-check? die neutral bad good failed\n}hide\n\n( ==================== Unit test framework =================== )\n\n\n( ==================== Random Numbers ========================= )\n\n( \nSee:\nuses xorshift\nhttps:\/\/en.wikipedia.org\/wiki\/Xorshift\nhttp:\/\/excamera.com\/sphinx\/article-xorshift.html\nhttp:\/\/www.arklyffe.com\/main\/2010\/08\/29\/xorshift-pseudorandom-number-generator\/\nthese constants have be collected from the web \n)\n\nsize 2 = [if] 13 constant a 9 constant b 7 constant c [then]\nsize 4 = [if] 13 constant a 17 constant b 5 constant c [then]\nsize 8 = [if] 12 constant a 25 constant b 27 constant c [then]\n\n7 variable seed ( must not be zero )\n\n: seed! ( x -- : set the value of the PRNG seed )\n\tdup 0= if drop 7 ( zero not allowed ) then seed ! ;\n\n: random ( -- x : assumes word size is 32 bit )\n\tseed @\n\tdup a lshift xor\n\tdup b rshift xor\n\tdup c lshift xor\n\tdup seed! ;\n\nhide{ a b c seed }hide\n\n( ==================== Random Numbers ========================= )\n\n( ==================== Prime Numbers ========================== )\n( From original \"third\" code from the IOCCC at \nhttp:\/\/www.ioccc.org\/1992\/buzzard.2.design, the module works out\nand prints prime numbers. )\n\n: prime? ( u -- u | 0 : return number if it is prime, zero otherwise )\n\tdup 1 = if 1- exit then\n\tdup 2 = if exit then\n\tdup 2 \/ 2 ( loop from 2 to n\/2 )\n\tdo\n\t\tdup ( value to check if prime )\n\t\ti mod ( mod by divisor )\n\t\tnot if\n\t\t\tdrop 0 leave\n\t\tthen\n\tloop ;\n\n0 variable counter\n\n: primes ( x1 x2 -- : print the primes from x2 to x1 )\n\t0 counter !\n\t\" The primes from \" dup . \" to \" over . \" are: \"\n\tcr\n\treset-column\n\tdo\n\t\ti prime?\n\t\tif\n\t\t\ti . counter @ column counter 1+!\n\t\tthen\n\tloop\n\tcr\n\t\" There are \" counter @ . \" primes.\"\n\tcr ;\n\nhide{ counter }hide\n( ==================== Prime Numbers ========================== )\n\n( ==================== Debugging info ========================= )\n\n( string handling should really be done with PARSE, and CMOVE )\n\nhide{ .s }hide\n: .s ( -- : print out the stack for debugging )\n\t\" <\" depth u. \" >\" space\n\tdepth if\n\t\tdepth 0 do i column tab depth i 1+ - pick u. loop\n\tthen\n\tcr ;\n\n1 variable hide-words ( do we want to hide hidden words or not )\n( This function prints out all of the defined words, excluding hidden words.\nAn understanding of the layout of a Forth word helps here. The dictionary\ncontains a linked list of words, each forth word has a pointer to the previous\nword until the first word. The layout of a Forth word looks like this:\n\nNAME: Forth Word - A variable length ASCII NUL terminated string\nPWD: Previous Word Pointer, points to the previous word\nMISC: Flags, code word and offset from previous word pointer to start of Forth word string\nCODE\/DATA: The body of the forth word definition, not interested in this.\n\nThere is a register which stores the latest defined word which can be\naccessed with the code \"pwd @\". In order to print out a word we need to\naccess a words MISC field, the offset to the NAME is stored here in bits\n8 to 15 and the offset is calculated from the PWD field.\n\n\"print\" expects a character address, so we need to multiply any calculated\naddress by the word size in bytes. )\n\n: words ( -- : print out all defined an visible words )\n\tlatest\n\tbegin\n\t\tdup\n\t\thidden? hide-words @ and\n\t\tnot if\n\t\t\tname\n\t\t\tprint space\n\t\telse\n\t\t\tdrop\n\t\tthen\n\t\t@ ( Get pointer to previous word )\n\t\tdup dictionary-start u< ( stop if pwd no longer points to a word )\n\tuntil\n\tdrop cr ;\nhider hide-words\n\n: TrueFalse ( -- : print true or false )\n\tif \" true\" else \" false\" then ;\n\n: registers ( -- : print out important registers and information about the virtual machine )\n\t\" return stack pointer: \" r@ . cr\n\t\" dictionary pointer \" here . cr\n\t\" previous word: \" pwd ? cr\n\t\" state: \" state ? cr\n\t\" base: \" base ? cr\n\t\" depth: \" depth . cr\n\t\" cell size (in bytes): \" size . cr\n\t\" last cell address: \" max-core . cr\n\t\" unused cells: \" unused . cr\n\t\" invalid: \" `invalid @ TrueFalse cr\n\t\" size of variable stack: \" `stack-size ? cr\n\t\" size of return stack: \" `stack-size ? cr\n\t\" start of variable stack: \" max-core `stack-size @ 2* - . cr\n\t\" start of return stack: \" max-core `stack-size @ - . cr\n\t\" current input source: \" source-id -1 = if \" string\" else \" file\" then cr\n\t\" reading from stdin: \" source-id 0 = stdin? and TrueFalse cr\n\t\" tracing on: \" `debug @ TrueFalse cr\n\t\" starting word: \" `instruction ? cr\n\t\" real start address: \" `start-address ? cr\n\t\" error handling: \" `error-handler ? cr ;\n( `sin `sidx `slen `fout\n `stdout `stderr `argc `argv )\n\n\n: y\/n? ( -- bool : ask a yes or no question )\n\tkey drop\n\t\" y\/n? \"\n\tbegin\n\t\tkey\n\t\tdup\n\t\t[char] y = if true exit then\n\t\t[char] n = if false exit then\n\t\t\" y\/n? \"\n\tagain ;\n\n: >instruction ( MISC -- Instruction : extract instruction from instruction field ) \n\tinstruction-mask and ;\n\n: step\n\t( step through a word: this word could be augmented\n\twith commands such as \"dump\", \"halt\", and optional\n\t\".s\" and \"registers\" )\n\tregisters\n\t\" .s: \" .s cr\n\t\" -- press any key to continue -- \"\n\tkey drop ;\n\n: more ( -- : wait for more input )\n\t\" -- press any key to continue -- \" key drop cr page ;\n\n: debug-help ( -- : this is not quite ready for prime time )\n \" debug mode commands\n\th - print help\n\tq - exit containing word\n\tr - print registers\n\ts - print stack\n\tc - continue on with execution\n\" ;\n\n: debug-prompt \n\t.\" debug> \" ;\n\n: debug ( a work in progress, debugging support, needs parse-word )\n\t\\ \" Entered Debug Prompt. Type 'h' for help. \" cr \n\tkey drop\n\tcr\n\tbegin\n\t\tdebug-prompt\n\t\t'\\n' word count drop c@\n\t\tcase\n\t\t\t[char] h of debug-help endof\n\t\t\t[char] q of bye endof\n\t\t\t[char] r of registers endof\n\t\t\t[char] s of >r .s r> endof\n\t\t\t[char] c of drop exit endof\n\t\t\t( @todo add throw here )\n\t\tendcase drop\n\tagain ;\nhider debug-prompt\n\n: code>pwd ( CODE -- PWD\/0 : calculate PWD from code address )\n\tdup dictionary-start here within not if drop 0 exit then\n\t>r\n\tlatest dup @ ( p1 p2 )\n\tbegin\n\t\tover ( p1 p2 p1 )\n\t\trdup r> u<= swap rdup r> > and if rdrop exit then\n\t\tdup 0= if rdrop exit then\n\t\tdup @ swap\n\tagain ;\n\n: end-print ( x -- )\n\t\"\t\t=> \" . \" ]\" ;\n\n: word-printer\n\t( attempt to print out a word given a words code field\n\tWARNING: This is a dirty hack at the moment\n\tNOTE: given a pointer to somewhere in a word it is possible\n\tto work out the PWD by looping through the dictionary to\n\tfind the PWD below it )\n\tdup 1- @ -1 = if \" [ noname\" end-print exit then\n\tdup \" [ \" code>pwd ?dup-if name print else drop \" data\" then\n\t end-print ;\n\nhide{ end-print code>pwd }hide\n\n( these words push the execution tokens for various special cases for decompilation )\n: get-branch [ find branch ] literal ;\n: get-?branch [ find ?branch ] literal ;\n: get-original-exit [ original-exit ] literal ;\n: get-quote [ find ' ] literal ;\n\n: branch-increment ( addr branch -- increment : calculate decompile increment for \"branch\" )\n\t1+ dup negative? if drop 2 else 2dup dump then ;\n\n( these words take a code field to a primitive they implement, decompile it\nand any data belonging to that operation, and push a number to increment the\ndecompilers code stream pointer by )\n\n: decompile-literal ( code -- increment )\n\t\" [ literal\t=> \" 1+ ? \" ]\" 2 ;\n: decompile-branch ( code -- increment )\n\t\" [ branch\t=> \" 1+ ? \" ]\" dup 1+ @ branch-increment ;\n: decompile-quote ( code -- increment )\n\t\" [ '\t=> \" 1+ @ word-printer \" ]\" 2 ;\n: decompile-?branch ( code -- increment )\n\t\" [ ?branch\t=> \" 1+ ? \" ]\" 2 ;\n\n( The decompile word expects a pointer to the code field of a word, it\ndecompiles a words code field, it needs a lot of work however.\nThere are several complications to implementing this decompile\nfunction.\n\n\t' The next cell should be pushed\n\t:noname This has a marker before its code field of -1 which\n\t\t cannot occur normally, this is handles in word-printer\n\tbranch branches are used to skip over data, but also for\n\t\t some branch constructs, any data in between can only\n\t\t be printed out generally speaking\n\texit There are two definitions of exit, the one used in\n\t\t ';' and the one everything else uses, this is used\n\t\t to determine the actual end of the word\n\tliterals Literals can be distinguished by their low value,\n\t\t which cannot possibly be a word with a name, the\n\t\t next field is the actual literal\n\nOf special difficult is processing 'if' 'else' 'then' statements,\nthis will require keeping track of '?branch'.\n\nAlso of note, a number greater than \"here\" must be data )\n\n: decompile ( code-field-ptr -- : decompile a word )\n\tbegin\n\t\ttab\n\t\tdup @\n\t\tcase\n\t\t\tdolit of drup decompile-literal endof\n\t\t\tget-branch of drup decompile-branch endof\n\t\t\tget-quote of drup decompile-quote endof\n\t\t\tget-?branch of drup decompile-?branch endof\n\t\t\tget-original-exit of 2drop \" [ exit ]\" cr exit endof\n\t\t\tword-printer 1\n\t\tendcase\n\t\t+\n\t\tcr\n\tagain ;\n\nhide{\n\tword-printer get-branch get-?branch get-original-exit \n\tget-quote branch-increment decompile-literal \n\tdecompile-branch decompile-?branch decompile-quote\n}hide\n\n: xt-instruction ( extract instruction from execution token )\n\tcell+ @ >instruction ;\n\n( these words expect a pointer to the PWD field of a word )\n: defined-word? xt-instruction dolist = ;\n: print-name \" name: \" name print cr ;\n: print-start \" word start: \" name chars . cr ;\n: print-previous \" previous word: \" @ . cr ;\n: print-immediate \" immediate: \" cell+ @ 0x8000 and 0= TrueFalse cr ;\n: print-instruction \" instruction: \" xt-instruction . cr ;\n: print-defined \" defined: \" defined-word? TrueFalse cr ;\n\n: print-header ( PWD -- is-immediate-word? )\n\tdup print-name\n\tdup print-start\n\tdup print-previous\n\tdup print-immediate\n\tdup print-instruction ( @todo look up instruction name )\n\tprint-defined ;\n\n( @todo This does not work for all words, so needs fixing. \n Specifically: \n\t2variable\n\t2constant\n\ttable\n\tconstant\n\tvariable\n\tarray \nWhich are all complex CREATE words\n\nA good way to test decompilation is with the following Unix pipe: \n\n\t.\/forth -f forth.fth -e words \n\t\t| sed 's\/ \/ see \/g' \n\t\t| .\/forth -t forth.fth &> decompiled.log\n)\n\n\n: see ( c\" xxx\" -- : decompile the next word in the input stream )\n\tfind\n\tdup 0= if -32 throw then\n\t1- ( move to PWD field )\n\tdup print-header\n\tdup defined-word?\n\tif ( decompile if a compiled word )\n\t\t2 cells + ( move to code field )\n\t\t\" code field:\" cr\n\t\tdecompile\n\telse ( the instruction describes the word if it is not a compiled word )\n\t\tdrop\n\tthen cr ;\n\n( These help messages could be moved to blocks, the blocks could then\nbe loaded from disk and printed instead of defining the help here,\nthis would allow much larger help )\n\n: help ( -- : print out a short help message )\n\tpage\n\tkey drop\n\" Welcome to Forth, an imperative stack based language. It is both a low\nlevel and a high level language, with a very small memory footprint. Most\nof Forth is defined as a combination of various primitives.\n\nA short description of the available function (or Forth words) follows,\nwords marked (1) are immediate and cannot be used in command mode, words\nmarked with (2) define new words. Words marked with (3) have both command\nand compile functionality.\n\n\"\nmore \" The built in words that accessible are:\n\n(1,2)\t: define a new word, switching to compile mode\n\timmediate make latest defined word immediate\n\tread read in a word, execute in command mode else compile\n\t@ ! fetch, store\n\tc@ c! character based fetch and store\n\t- + * \/ standard arithmetic operations,\n\tand or xor invert standard bitwise operations\n\tlshift rshift left and right bit shift\n\tu< u> < > = comparison predicates\n\texit exit from a word\n\temit print character from top of stack\n\tkey get a character from input\n\tr> >r pop a value from or to the return stack\n\tfind find a word in the dictionary and push the location\n\t' store the address of the following word on the stack\n\t, write the top of the stack to the dictionary\n\tswap swap first two values on the stack\n\tdup duplicate the top of the stack\n\tdrop pop and drop a value\n\tover copy the second stack value over the first\n\t. pop the top of the stack and print it\n\" \nmore \" \n\tprint print a NUL terminated string at a character address\n\tdepth get the current stack depth\n\tclock get the time since execution start in milliseconds\n\tevaluate evaluate a string\n\tsystem execute a system command\n\tclose-file close a file handle\n\topen-file open a file handle\n\tdelete-file delete a file off disk given a string\n\tread-file read in characters from a file\n\twrite-file write characters to a file\n\tfile-position get the file offset\n\treposition-file reposition the file pointer\n\tflush-file flush a file to disk\n\trename-file rename a file on disk\n \"\n\nmore \" All of the other words in the interpreter are built from these\nprimitive words. A few examples:\n\n(1)\tif...else...then FORTH branching construct\n(1)\tbegin...until loop until top of stack is non zero\n(1)\tbegin...again infinite loop\n(1)\tdo...loop FORTH looping construct\n(2,3)\tcreate create a new word that pushes its location\n(1)\tdoes> declare a created words run time behaviour\n(1,2)\tvariable declare variable with initial value from top of stack\n(1,2)\tconstant declare a constant, taken from top of stack\n(1,2)\tarray declare an array with size taken from top of stack\n(1)\t; terminate a word definition and return to command mode\n\twords print out a list of all the defined words\n\thelp this help message\n\tdump print out memory contents starting at an address\n\tregisters print out the contents of the registers\n\tsee decompile a word, viewing what words compose it\n\t.s print out the contents of the stack\n\n\"\n\nmore \" Some more advanced words:\n\n\there push the dictionary pointer\n\th push the address of the dictionary pointer\n\tr push the return stack pointer\n\tallot allocate space in the dictionary\n(1)\t[ switch to command mode\n\t] switch to compile mode\n\t:: compile ':' into the dictionary\n\n\" more \"\nFor more information either consult the manual pages forth(1) and libforth(1)\nor consult the following sources:\n\n\thttps:\/\/github.com\/howerj\/libforth\n\thttp:\/\/work.anapnea.net\/html\/html\/projects.html\n\nAnd for a larger tutorial:\n\n\thttps:\/\/github.com\/howerj\/libforth\/blob\/master\/readme.md\n\nFor resources on Forth:\n\n\thttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\thttps:\/\/rwmj.wordpress.com\/2010\/08\/07\/jonesforth-git-repository\/\n\n -- end --\n\" cr\n;\n\n( ==================== Files ================================== )\n\n( @todo implement the other file access methods in terms of the\n built in ones [see http:\/\/forth.sourceforge.net\/std\/dpans\/dpans11.htm]\n @todo read-line and write-line need their flag and ior setting correctly\n\n\tFILE-SIZE [ use file-positions ]\n\n Also of note:\t\n * Source ID needs extending. )\n\n: read-char ( c-addr fileid -- ior : read a char )\n\t1 swap read-file 0<> swap 1 <> or ;\n\n0 variable x\n\n: getchar ( fileid -- char ior )\n\tx chars> swap read-char x chars> c@ swap ;\n\n: write-char ( c-addr fileid -- ior : write a char )\n\t1 swap write-file 0<> swap 1 <> or ;\n\n: putchar ( char fileid -- ior )\n\tswap x chars> c! x chars> swap write-char ;\n\nhide{ x }hide\n\n: rewind-file ( file-id -- : rewind a file to the beginning )\n\t0 reposition-file throw ;\n\n: read-line ( c-addr u1 fileid -- u2 flag ior : read in a line of text )\n\t-rot bounds\n\tdo\n\t\tdup i swap read-char drop\n\t\ti c@ '\\n' = if drop i 0 0 leave then\n\tloop drop ;\n\n: write-line ( c-addr u fileid -- u2 flag ior : write a line of text )\n\t-rot bounds\n\tdo\n\t\tdup i swap write-char drop\n\t\ti c@ '\\n' = if drop i 0 0 leave then\n\tloop ;\n\n: resize-file ( ud fileid -- ior : attempt to resize a file )\n\t( There is no portable way to truncate a file :C )\n\t2drop -1 ( -1 to indicate failure ) ;\n\n: create-file ( c-addr u fam -- fileid ior )\n\t>r 2dup w\/o open-file throw close-file throw\n\tr> open-file ;\n\n: include-file ( file-id -- : evaluate a file ) \n\tdup >r 0 1 evaluator r> close-file throw throw ;\n\n: included ( c-addr u -- : attempt to open up a name file and evaluate it )\n\tr\/o open-file throw \n\tinclude-file ;\n\n: include ( c\" ccc\" -- : attempt to evaluate a named file )\n\t( @bug requires trailing space, should use parse-name )\n\tbl word count included ;\n\n: bin ( fam1 -- fam2 : modify a file access method to be binary not line oriented ) \n\t( Do nothing, all file access methods are binary )\n\t;\n\n( ==================== Files ================================== )\n\n( ==================== Blocks ================================= )\n( \n0 variable dirty\nb\/buf string buf\n0 variable loaded\n0 variable blk\n0 variable scr\n\n: update 1 dirty ! ;\n: empty-buffers 0 loaded ! ;\n: ?update dup loaded @ <> dirty @ or ;\n: ?invalid dup 0= if empty-buffers -35 throw then ;\n: write dup >r write-file r> close-file throw ;\n: read dup >r read-file r> close-file throw ;\n: name >r <# #s #> rot drop r> create-file throw ; \\ @todo add .blk with holds, also create file deletes file first...\n: update! >r buf r> w\/o name write throw drop empty-buffers ;\n: get >r buf r> r\/o name read throw drop ;\n: block ?invalid ?update if dup update! then dup get loaded ! buf drop ;\n\nhide{ dirty ?update update! loaded name get ?invalid write read }hide\n\n: c \n\t1 block update drop\n\t2 block update drop\n\t3 block update drop\n\t4 block update drop ;\nc )\n\n( ==================== Blocks ================================= )\n\n( ==================== Matcher ================================ )\n( The following section implements a very simple regular expression\nengine, which expects an ASCIIZ Forth string. It is translated from C\ncode and performs an identical function.\n\nThe regular expression language is as follows:\n\n\tc\tmatch a literal character\n\t.\tmatch any character\n\t*\tmatch any characters\n\nThe \"*\" operator performs the same function as \".*\" does in most\nother regular expression engines. Most other regular expression engines\nalso do not anchor their selections to the beginning and the end of\nthe string to match, instead using the operators '^' and '$' to do\nso, to emulate this behavior '*' can be added as either a suffix,\nor a prefix, or both, to the matching expression.\n\nAs an example \"*, World!\" matches both \"Hello, World!\" and\n\"Good bye, cruel World!\". \"Hello, ....\" matches \"Hello, Bill\"\nand \"Hello, Fred\" but not \"Hello, Tim\" as there are two few\ncharacters in the last string.\n\n@todo make a matcher that expects a Forth string, which do not\nhave to be NUL terminated\n)\n\n\\ Translated from http:\/\/c-faq.com\/lib\/regex.html\n\\ int match(char *pat, char *str)\n\\ {\n\\ \tswitch(*pat) {\n\\ \tcase '\\0': return !*str;\n\\ \tcase '*': return match(pat+1, str) || *str && match(pat, str+1);\n\\ \tcase '.': return *str && match(pat+1, str+1);\n\\ \tdefault: return *pat == *str && match(pat+1, str+1);\n\\ \t}\n\\ }\n\n: *pat ( regex -- regex char : grab next character of pattern ) \n\tdup c@ ;\n\n: *str ( string regex -- string regex char : grab next character string to match )\n\tover c@ ;\n\n: pass ( c-addr1 c-addr2 -- bool : pass condition, characters matched ) \n\t2drop 1 ;\n\n: reject ( c-addr1 c-addr2 -- bool : fail condition, character not matched ) \n\t2drop 0 ;\n\n: *pat==*str ( c-addr1 c-addr2 -- c-addr1 c-addr2 bool )\n\t2dup c@ swap c@ = ;\n\n: ++ ( u1 u2 u3 u4 -- u1+u3 u2+u4 : not quite d+ [does no carry] )\n\tswap >r + swap r> + swap ;\n\ndefer matcher\n\n: advance ( string regex char -- bool : advance both regex and string )\n\tif 1 1 ++ matcher else reject then ;\n\n: advance-string ( string regex char -- bool : advance only the string )\n\tif 1 0 ++ matcher else reject then ;\n\n: advance-regex ( string regex -- bool : advance matching )\n\t2dup 0 1 ++ matcher if pass else *str advance-string then ;\n\n: match ( string regex -- bool : match a ASCIIZ pattern against an ASCIIZ string )\n\t( @todo Add limits and accept two Forth strings, making sure they are both\n\t ASCIIZ strings as well \n\t @warning This uses a non-standards compliant version of case! )\n\t*pat\n\tcase\n\t\t 0 of drop drop c@ not exit endof\n\t\t[char] * of drop advance-regex exit endof\n\t\t[char] . of drop *str advance exit endof\n\t\t drop *pat==*str advance exit\n\tendcase ;\n\nmatcher is match\n\nhide{ \n\t*str *pat *pat==*str pass reject advance \n\tadvance-string advance-regex matcher ++ \n}hide\n\n( ==================== Matcher ================================ )\n\n\n( ==================== Cons Cells ============================= )\n\n( From http:\/\/sametwice.com\/cons.fs, this could be improved if the optional\nmemory allocation words were added to the interpreter. This provides\na simple \"cons cell\" data structure. There is currently no way to\nfree allocated cells )\n\n: car! ( value cons-addr -- : store a value in the car cell of a cons cell ) \n\t! ;\n\n: cdr! ( value cons-addr -- : store a value in the cdr cell of a cons cell )\n\tcell+ ! ;\n\n: car@ ( cons-addr -- car-val : retrieve car value from cons cell )\n\t@ ;\n\n: cdr@ ( cons-addr -- cdr-val : retrieve cdr value from cons cell )\n\tcell+ @ ;\n\n: cons ( car-val cdr-val -- cons-addr : allocate a new cons cell )\n\tswap here >r , , r> ;\n\n: cons0 0 0 cons ;\n\nmarker cleanup\n77 987 cons constant x\nT{ x car@ -> 77 }T\nT{ x cdr@ -> 987 }T\nT{ 55 x cdr! x car@ x cdr@ -> 77 55 }T\nT{ 44 x car! x car@ x cdr@ -> 44 55 }T\ncleanup\n\n( ==================== Cons Cells ============================= )\n\n( ==================== Miscellaneous ========================== )\n\n: license ( -- : print out license information )\n\" \nThe MIT License (MIT)\n\nCopyright (c) 2016 Richard James Howe\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the 'Software'),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand\/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\nTHE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\nOTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\nARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE. \n\n\" \n;\n\n( ==================== Version information =================== )\n\n4 constant version\n\n( ==================== Version information =================== )\n\n( ==================== Core utilities ======================== )\n( Read the header of a core file and process it, printing the\nresults out )\n\n8 constant header-size ( size of Forth core file header )\n8 constant size-field-size ( the size in bytes of the size field in the core file )\n0 variable core-file ( core fileid we are reading in )\n0 variable core-cell-size ( cell size of Forth core )\n0 variable core-version ( version of core file )\n0 variable core-endianess ( endianess of core we are reading in )\n\n( save space to read in header )\ncreate header header-size chars allot\n: cheader ( -- c-addr : header char address )\n\theader chars> ;\ncreate size-field size-field-size chars allot\n: csize-field ( -- c-addr : address of place size field is stored in )\n\tsize-field chars> ;\n\n0\nenum header-magic0 ( magic number 0 : FF ) \nenum header-magic1 ( magic number 1 : '4' )\nenum header-magic2 ( magic number 2 : 'T' )\nenum header-magic3 ( magic number 3 : 'H' )\nenum header-cell-size ( size of a forth cell, either 2, 4 or 8 bytes )\nenum header-version ( version of the forth core )\nenum header-endianess ( endianess of the core )\nenum header-log2size ( binary logarithm of the core size )\n\n: cleanup ( -- : cleanup before abort )\n\tcore-file @ ?dup 0<> if close-file drop then ;\n\n: invalid-header ( bool -- : abort if header is invalid )\n\t<> if cleanup abort\" invalid header\" then ;\n\n: save-core-cell-size ( char -- : save the core file cell size, checking if it is valid )\n\tcore-cell-size !\n\t\" cell size:\" tab\n\tcore-cell-size @ 2 = if 2 . cr exit then\n\tcore-cell-size @ 4 = if 4 . cr exit then\n\tcore-cell-size @ 8 = if 8 . cr exit then\n\tcleanup core-cell-size @ . abort\" : invalid cell size\" ;\n\n: check-version-compatibility ( char -- : checks the version compatibility of the core file ) \n\tcore-version !\n\tcore-version @ version = if \" version: \" version . cr exit then\n\tcleanup core-version @ . abort\" : unknown version number\" ;\n\n: save-endianess ( char -- : save the endianess, checking if it is valid )\n\tcore-endianess !\n\t\" endianess:\" tab\n\tcore-endianess @ 0 = if \" big\" cr exit then\n\tcore-endianess @ 1 = if \" little\" cr exit then\n\tcleanup core-endianess @ . abort\" invalid endianess\" then ;\n\n: read-or-abort ( c-addr size fileid -- : )\n\tover >r read-file \n\t 0<> if cleanup abort\" file read failed\" then\n\tr> <> if cleanup abort\" header too small\" then ;\n\n: header? ( -- : print out header information )\n\tcheader header-size core-file @ read-or-abort\n\t( \" raw header:\" header 2 dump )\n\tcheader header-magic0 + c@ 255 invalid-header\n\tcheader header-magic1 + c@ [char] 4 invalid-header\n\tcheader header-magic2 + c@ [char] T invalid-header\n\tcheader header-magic3 + c@ [char] H invalid-header\n\tcheader header-cell-size + c@ save-core-cell-size\n\tcheader header-version + c@ check-version-compatibility\n\tcheader header-endianess + c@ save-endianess\n\t\" valid header\" cr ;\n\n: size? ( -- : print out core file size )\n\t\" size: \" cheader header-log2size + c@ 1 swap lshift . cr ;\n\n: core ( c-addr u -- : analyze a Forth core file from disk given its file name )\n\t2dup \" core file:\" tab type cr\n\tr\/o open-file throw core-file ! \n\theader?\n\tsize?\n\tcore-file @ close-file drop ;\n\n( s\" forth.core\" core )\n\nhide{ \nheader-size header? \nheader-magic0 header-magic1 header-magic2 header-magic3\nheader-version header-cell-size header-endianess header-log2size\nheader \ncore-file save-core-cell-size check-version-compatibility\ncore-cell-size cheader\ncore-endianess core-version save-endianess invalid-header\ncleanup size-field csize-field size-field-size\nread-or-abort size?\n}hide\n\n( ==================== Core utilities ======================== )\n\n( ==================== RLE =================================== )\n\n( These set of words implement Run Length Compression, which can be used for\nsaving space when compressing the core files generated by Forth programs, which\ncontain mostly runs of NUL characters. \n\nThe format of the encoded data is quite simple, there is a command byte\nfollowed by data. The command byte encodes only two commands; encode a run of\nliteral data and repeat the next character. \n\nIf the command byte is greater than X the command is a run of characters, \nX is then subtracted from the command byte and this is the number of \ncharacters that is to be copied verbatim when decompressing.\n\nIf the command byte is less than or equal to X then this number, plus one, is \nused to repeat the next data byte in the input stream.\n\nX is 128 for this application, but could be adjusted for better compression\ndepending on what the data looks like. \n\nExample:\n\t\n\t2 'a' 130 'b' 'c' 3 'd'\n\nBecomes:\n\n\taabcddd \n\nExample usage:\n\n\t: extract\n\t\tc\" forth.core\" w\/o open-file throw\n\t\tc\" forth.core.rle\" r\/o open-file throw\n\t\tdecompress ;\n\textract\n\n@note file redirection could be used for the input as well\n@todo compression, and reading\/writing to strings )\n\n: cpad pad chars> ;\n\n0 variable out\n128 constant run-length\n\n: more ( file-id -- char : read in a single character )\n\t>r cpad r> read-char throw cpad c@ ;\n\n: repeated ( count file-id -- : repeat a character count times )\n\tmore swap 0 do dup emit loop drop ;\n\n: literals ( count file-id -- : extract a literal run )\n\t>r cpad swap r> read-file throw cpad swap type ;\n\n: command ( file-id -- : process an RLE command )\n\tdup \n\t>r more \n\tdup run-length u> \n\tif \n\t\trun-length - r> literals \n\telse \n\t\t1+ r> repeated \n\tthen ;\n\n: redirect ( file-id-out -- : save current output pointer, redirect to output )\n\t`fout @ out ! `fout ! ;\n\n: restore ( -- : restore previous output pointer )\n\tout @ `fout ! ;\n\n: decompress ( file-id-out file-id-in -- : decompress an RLE encoded file )\n\tswap\n\tredirect\n\tbegin dup ' command catch until ( process commands until input exhausted )\n\t2drop ( drop twice because catch will restore stack before 'command' )\n\trestore ; ( restore input stream )\n\nhide{ literals repeated more out run-length command }hide\n\n( ==================== RLE =================================== )\n\n( ==================== Generate C Core file ================== )\n( The word core2c reads in a core file and turns it into a C file which \ncan then be compiled into the forth interpreter in a bootstrapping like\nprocess.\n\nUsage:\n c\" forth.core\" c\" core.gen.c\" core2c )\n\n0 variable count\n\n: wbyte ( u char -- : write a byte )\n\tpnum drop\n\t[char] , emit\n\t16 mod 0= if cr then ;\n\n: advance ( char -- : advance counter and print byte )\n\tcount 1+! count @ swap wbyte ;\n\n: hexify ( fileid -- fileid : turn core file into C numbers in array )\n\t0 count !\n\tbegin dup getchar 0= while advance repeat drop ;\n\n: quote ( -- : emit a quote character )\n\t[char] \" emit ;\n\n: core2c ( c-addr u c-addr u -- ior : generate a C file from a core file )\n\tw\/o open-file throw >r\n\tr\/o open-file ?dup-if r> close-file throw throw then\n\tr> redirect\n\t\" #include \" quote \" libforth.h\" quote cr\n\t\" unsigned char forth_core_data[] = {\" cr\n\thexify \n\t\" };\" cr\n\t\" forth_cell_t forth_core_size = \" count @ . \" ;\" cr cr\n\tclose-file\n\t`fout @ close-file \n\trestore or ;\n\nhide{ wbyte hexify count quote advance }hide\n \n( ==================== Generate C Core file ================== )\n\n: wc ( c-addr u -- u : count the bytes in a file )\n\tr\/o open-file throw\n\t0 swap\n\tbegin dup getchar nip 0= while nos1+ repeat close-file throw ;\n\n( ==================== Save Core file ======================== )\n\n( The following functionality allows the user to save the core file\nfrom within the running interpreter. The Forth core files have a very simple\nformat which means the words for doing this do not have to be too long, a header\nhas to emitted with a few calculated values and then the contents of the\nForths memory after this )\n\n( This write the header out to the current output device, this\nwill be redirected to a file )\n: header ( -- : write the header out )\n\t0xff emit ( magic 0 )\n\t[char] 4 emit ( magic 1 )\n\t[char] T emit ( magic 2 )\n\t[char] H emit ( magic 3 )\n\tsize emit ( cell size in bytes )\n\tversion emit ( core version )\n\tendian not emit ( endianess )\n\tmax-core log2 emit ; ( size field )\n\n: data ( -- : write the data out )\n\t0 max-core chars> `fout @ write-file throw drop ;\n\n: encore ( -- : write the core file out )\n\theader\n\tdata ;\n\n: save-core ( c-addr u -- : save core file or throw error ) \n\tw\/o open-file throw dup\n\tredirect \n\t\t' encore catch swap close-file throw \n\trestore ;\n\n( The following code illustrates an example of setting up a\nForth core file to execute a word when the core file is loaded.\nIn the example the word \"hello-world\" will be executed, which will\nalso quit the interpreter:\n\n\t\\ Only works for immediate words for now, we define\n\t\\ the word we wish to be executed when the forth core\n\t\\ is loaded\n\t: hello-world immediate\n\t\t\" Hello, World!\" cr bye ;\n\n\t\\ The following sets the starting word to our newly\n\t\\ defined word:\n\tfind hello-world cfa start!\n\n\t\\ Now we can save the core file out:\n\ts\" forth.core\" save-core \n\nThis can be used, in conjunction with aspects of the build system,\nto produce a standalone executable that will run only a single Forth\nword. )\n\nhide{ redirect restore data encore header }hide\n\n( ==================== Save Core file ======================== )\n\n( ==================== Hex dump ============================== )\n\n( @todo hexdump can read in too many characters and it does not\nprint out the correct address\n@todo utilities for easy redirecting of file input\/output )\n: input >r cpad 128 r> read-file ; ( file-id -- u 0 | error )\n: clean cpad 128 0 fill ; ( -- )\n: cdump cpad chars swap aligned chars dump ; ( u -- )\n: hexdump ( file-id -- : [hex]dump a file to the screen )\n\tdup \n\tclean\n\tinput if 2drop exit then\n\t?dup-if cdump else drop exit then\n\ttail ; \n\nhide{ more cpad clean cdump input }hide\n\n( ==================== Hex dump ============================== )\n\n( ==================== Date ================================== )\n\n( Rather annoyingly months are start from 1 but weekdays from 0 )\n\n: >month ( month -- )\n\tcase\n\t\t 1 of \" Jan \" endof\n\t\t 2 of \" Feb \" endof\n\t\t 3 of \" Mar \" endof\n\t\t 4 of \" Apr \" endof\n\t\t 5 of \" May \" endof\n\t\t 6 of \" Jun \" endof\n\t\t 7 of \" Jul \" endof\n\t\t 8 of \" Aug \" endof\n\t\t 9 of \" Sep \" endof\n\t\t10 of \" Oct \" endof\n\t\t11 of \" Nov \" endof\n\t\t12 of \" Dec \" endof\n\tendcase drop ;\n\n: .day ( day -- : add ordinal to day )\n\t10 mod\n\tcase\n\t\t1 of \" st \" drop exit endof\n\t\t2 of \" nd \" drop exit endof\n\t\t3 of \" rd \" drop exit endof\n\t\t\" th \" \n\tendcase drop ;\n\n: >day ( day -- : add ordinal to day of month )\n\tdup u.\n\tdup 1 10 within if .day exit then\n\tdup 10 20 within if \" th\" drop exit then\n\t.day ;\n\n: >weekday ( weekday -- : print the weekday )\n\tcase\n\t\t0 of \" Sun \" endof\n\t\t1 of \" Mon \" endof\n\t\t2 of \" Tue \" endof\n\t\t3 of \" Wed \" endof\n\t\t4 of \" Thu \" endof\n\t\t5 of \" Fri \" endof\n\t\t6 of \" Sat \" endof\n\tendcase drop ;\n\n: padded ( u -- : print out a run of zero characters )\n\t0 do [char] 0 emit loop ;\n\n: 0u. ( u -- : print a zero padded number )\n\tdup 10 u< if 1 padded then u. space ;\n\n: .date ( date -- : print the date )\n\tif \" DST \" else \" GMT \" then \n\tdrop ( no need for days of year)\n\t>weekday\n\t. ( year ) \n\t>month \n\t>day \n\t0u. ( hour )\n\t0u. ( minute )\n\t0u. ( second ) cr ;\n\n: time&date ( -- second minute hour day month year )\n\tdate\n\t3drop ;\n\nhide{ 0u. >weekday .day >day >month padded }hide\n\n( ==================== Date ================================== )\n\n( Looking at most Forths dictionary with \"words\" command they tend\nto have a lot of words that do not mean anything but to the implementers\nof that specific Forth, here we clean up as many non standard words as\npossible. )\nhide{ \n do-string ')' alignment-bits \n dictionary-start hidden? hidden-mask instruction-mask\n max-core dolist x x! x@ write-exit\n max-string-length \n original-exit\n pnum evaluator \n TrueFalse >instruction print-header\n print-name print-start print-previous print-immediate\n print-instruction xt-instruction defined-word? print-defined\n `state\n `source-id `sin `sidx `slen `start-address `fin `fout `stdin\n `stdout `stderr `argc `argv `debug `invalid `top `instruction\n `stack-size `error-handler `x `y `handler _emit\n}hide\n\n( \n## Forth To List\n\nThe following is a To-Do list for the Forth code itself, along with any\nother ideas.\n\n* FORTH, VOCABULARY\n* \"Value\", \"To\", \"Is\"\n* Double cell words and floating point library\n* The interpreter should use character based addresses, instead of\nword based, and use values that are actual valid pointers, this\nwill allow easier interaction with the world outside the virtual machine\n* common words and actions should be factored out to simplify\ndefinitions of other words, their standards compliant version found\nif any\n* Allow the processing of argc and argv, the mechanism by which that\nthis can be achieved needs to be worked out. However all processing that\nis currently done in \"main.c\" should be done within the Forth interpreter\ninstead.\n* A built in version of \"dump\" and \"words\" should be added to the Forth\nstarting vocabulary, simplified versions that can be hidden.\n* Here documents, string literals. Examples of these can be found online\nat Rosetta Code, although the Forth versions online will need adapting.\n* Document the words in this file and built in words better, also turn this\ndocument into a literate Forth file.\n* Sort out \"'\", \"[']\", \"find\", \"compile,\" \n* Proper booleans should be used throughout, that is -1 is true, and 0 is\nfalse.\n* File operation primitives that close the file stream [and possibly restore\nI\/O to stdin\/stdout] if an error occurs, and then re-throws, should be made.\n* Implement as many things from http:\/\/lars.nocrew.org\/forth2012\/implement.html\nas is sensible. \n* CASE Statements http:\/\/dxforth.netbay.com.au\/miser.html\n* The current words that implement I\/O redirection need to be improved, and documented,\nI think this is quite a useful and powerful mechanism to use within Forth that simplifies\nprograms. This is a must and will make writing utilities in Forth a *lot* easier \n\nImplement:\n\nhttp:\/\/rosettacode.org\/wiki\/CRC-32#Forth\nhttp:\/\/rosettacode.org\/wiki\/Monte_Carlo_methods#Forth \n\nAnd various other things from Rosetta Code.\n\n\n)\n\n( \nThe following will not work as we might actually be reading from a string [`sin]\nnot `fin. \n: key 32 chars> 1 `fin @ read-file drop 0 = if 0 else 32 chars> c@ then ; )\n\nverbose [if] \n\t.( FORTH: libforth successfully loaded.) cr\n\t.( Type 'help' and press return for a basic introduction.) cr\n\t.( Core: ) here . \" \/ \" here unused + . cr\n\t \n\t.( The MIT License ) cr\n\t.( ) cr\n\t.( Copyright 2016 Richard James Howe) cr\n\t.( ) cr\n\t.( Permission is hereby granted, free of charge, to any person obtaining a) cr\n\t.( copy of this software and associated documentation files [the \"Software\"],) cr\n\t.( to deal in the Software without restriction, including without limitation) cr\n\t.( the rights to use, copy, modify, merge, publish, distribute, sublicense,) cr\n\t.( and\/or sell copies of the Software, and to permit persons to whom the) cr\n\t.( Software is furnished to do so, subject to the following conditions:) cr\n\t.( ) cr\n\t.( The above copyright notice and this permission notice shall be included) cr\n\t.( in all copies or substantial portions of the Software.) cr\n\t.( ) cr\n\t.( THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR) cr\n\t.( IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,) cr\n\t.( FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL) cr\n\t.( THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR) cr\n\t.( OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,) cr\n\t.( ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR) cr\n\t.( OTHER DEALINGS IN THE SOFTWARE. ) cr\n[then]\n\n( \\ integrate simple 'dump' and 'words' into initial forth program \n: nl dup 3 and not ;\n: ?? \\ addr1 \n nl if dup cr . [char] : emit space then ? ;\n: dump \\ addr n --\n\tbase @ >r hex over + swap 1- begin 1+ 2dup dup ?? 2+ u< until r> base ! ; )\n\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"9d73c75d539465beff3913e7b09fa466d89ade0e","subject":"Hooks for collecting IO stats.","message":"Hooks for collecting IO stats.","repos":"rbsexton\/sockpuppet,rbsexton\/sockpuppet","old_file":"forth\/serCM3_SAPI-level1.fth","new_file":"forth\/serCM3_SAPI-level1.fth","new_contents":"\\ serCM3_sapi_level1.fth - SAPI polled RX, polled TX, serial communication drivers\n\\ with support for blocking IO.\n\\ Written to run against the SockPuppet API.\n\n\\ Level 1 support. Requires TASKING. System calls request blocking.\n\\ KEY requires blocking, so that must be implemented here.\n\n\\ Copyright (c) 2017, Robert Sexton. All rights reserved.\n\\ Covered by the terms of the supplied Licence.txt file\n\nonly forth definitions\n\n\\ ==============\n\\ *T SAPI polled serial driver\n\\ ==============\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\n\\ ** using the internal UARTs via the SAPI call layer. This is \n\\ ** The simplest implementation level.\n\\ ** It doesn't use the CR or TYPE calls, but rather emulates them.\n\n\\ ****************\n\\ *S Configuration\n\\ ****************\n\\ *P Configuration is managed by the SAPI\n\ntarget\n\n[defined] IOProfiling? [if]\nvariable c_emit\nvariable c_type\nvariable c_type_chars\nvariable c_cr\nvariable c_key\n[then]\n\n\\ ********************\n\\ *S Serial primitives\n\\ ********************\ninternal\n\n\\ : +FaultConsole\t( -- ) ;\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\n\\ ** for more details.\n\ntarget\n\n\\ CODE (seremitfc)\t\\ char base --\n\\ This is a system call.\n\n: (seremit)\t\\ char base -- \n\\ *G Wrapped call that checks for throttling, and if so,\n\\ calls PAUSE to let another task run, or just does a WFI if no multitasker.\n\\ The only interesting thing is failure, or -1. That means retry.\n\t\\ 1 c_emit +! \n (seremitfc) if [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then] then \n\t;\n\n: (sertype) \\ caddr len base --\n\\ *G Transmit a string on the given UART.\n \\ 1 c_type +!\n \\ over c_type_chars +!\n \n -rot bounds\n ?do i c@ over (seremit) loop\n drop\n;\n\n: (sercr)\t\\ base --\n\\ *G Transmit a CR\/LF pair on the given UART.\n \\ 2 c_cr +!\n $0D over (seremit) $0A swap (seremit)\n;\n\n: (serkey) \\ base -- c\n\\ *G Get a character from the port. Retry until we get it.\n\\ The system call will stop the task and restart it when there is data.\n\\ See if its negative. If so, discard it and leave false to re-loop.\n\\ If not negative, leave true on the stack to exit.\n begin \\ base ret t\/f \n\tdup (serkeyfc) dup 0 < \\ base ret t\/f \n\t \\ If we have been blocked, drop the useless returned data and try again.\n\t IF [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then] drop false \n\t ELSE true \\ Leave the return code intact.\n\t THEN \\ base ret t\/f \n\tuntil \\ base ret \n\tswap drop \n \\ 1 c_key +!\n;\n\n\\ THis is a system call.\n\\ CODE (serkey?) \\ base -- t\/f\n\\ *G Return true if the given UART has a character avilable to read.\n\nexternal \n\n: seremit0\t\\ char --\n\\ *G Transmit a character on UART0.\n 0 (seremit) ;\n: sertype0\t\\ c-addr len --\n\\ *G Transmit a string on UART0.\n 0 (sertype) ;\n: sercr0\t\\ --\n\\ *G Issue a CR\/LF pair to UART0.\n 0 (sercr) ;\n: serkey?0\t\\ -- flag\n\\ *G Return true if UART0 has a character available.\n 0 (serkey?) ;\n: serkey0\t\\ -- char\n\\ *G Wait for a character on UART0.\n 0 (serkey) ;\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\n\\ *G Generic I\/O device for UART0.\n ' serkey0 ,\t\t\\ -- char ; receive char\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\n ' seremit0 ,\t\t\\ -- char ; display char\n ' sertype0 ,\t\t\\ caddr len -- ; display string\n ' sercr0 ,\t\t\\ -- ; display new line\n\n\\ --------------------------------------------------------------------\n\\ Optional devices\n\\ --------------------------------------------------------------------\n[defined] useUART1? [if] useUART1? 1 = [if] \n: seremit1 #1 (seremit) ;\n: sertype1 #1 (sertype) ;\n: sercr1 #1 (sercr) ;\n: serkey?1 #1 (serkey?) ;\n: serkey1 #1 (serkey) ;\ncreate Console1 ' serkey1 , ' serkey?1 , ' seremit1 , ' sertype1 , ' sercr1 ,\t\n[then] [then]\n\n\\ --------------------------------------------------------------------\n\\ Non-UARTs.\n\\ --------------------------------------------------------------------\n[defined] useStream10? [if] useStream10? 1 = [if] \n: seremit10 #10 (seremit) ;\n: sertype10\t#10 (sertype) ;\n: sercr10\t#10 (sercr) ;\n: serkey?10\t#10 (serkey?) ;\n: serkey10\t#10 (serkey) ;\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\n[then] [then]\n\nconsole-port 0 = [if]\n console0 constant console\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\n\\ ** It may be changed by one of the phrases of the form:\n\\ *C dup opvec ! ipvec !\n\\ *C SetConsole\n[then]\n\nconsole-port #10 = [if]\n console10 constant console\n[then]\n\n\\ ************************\n\\ *S System initialisation\n\\ ************************\n\n\\ This is a NOP in the SAPI environment\n: init-ser ;\t\\ --\n\\ *G Initialise all serial ports\n\n\\ ======\n\\ *> ###\n\\ ======\n\ndecimal\n","old_contents":"\\ serCM3_sapi_level1.fth - SAPI polled RX, polled TX, serial communication drivers\n\\ with support for blocking IO.\n\\ Written to run against the SockPuppet API.\n\n\\ Level 1 support. Requires TASKING. System calls request blocking.\n\\ KEY requires blocking, so that must be implemented here.\n\n\\ Copyright (c) 2017, Robert Sexton. All rights reserved.\n\\ Covered by the terms of the supplied Licence.txt file\n\nonly forth definitions\n\n\\ ==============\n\\ *T SAPI polled serial driver\n\\ ==============\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\n\\ ** using the internal UARTs via the SAPI call layer. This is \n\\ ** The simplest implementation level.\n\\ ** It doesn't use the CR or TYPE calls, but rather emulates them.\n\n\\ ****************\n\\ *S Configuration\n\\ ****************\n\\ *P Configuration is managed by the SAPI\n\ntarget\n\n\\ ********************\n\\ *S Serial primitives\n\\ ********************\ninternal\n\n: +FaultConsole\t( -- ) ;\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\n\\ ** for more details.\n\ntarget\n\n\\ CODE (seremitfc)\t\\ char base --\n\\ This is a system call.\n\n: (seremit)\t\\ char base -- \n\\ *G Wrapped call that checks for throttling, and if so,\n\\ calls PAUSE to let another task run, or just does a WFI if no multitasker.\n\\ The only interesting thing is failure, or -1. That means retry.\n (seremitfc) if [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then] then \n\t;\n\n: (sertype) \\ caddr len base --\n\\ *G Transmit a string on the given UART.\n -rot bounds\n ?do i c@ over (seremit) loop\n drop\n;\n\n: (sercr)\t\\ base --\n\\ *G Transmit a CR\/LF pair on the given UART.\n $0D over (seremit) $0A swap (seremit)\n;\n\n: (serkey) \\ base -- c\n\\ *G Get a character from the port. Retry until we get it.\n\\ The system call will stop the task and restart it when there is data.\n\\ See if its negative. If so, discard it and leave false to re-loop.\n\\ If not negative, leave true on the stack to exit.\n begin \\ base ret t\/f \n\tdup (serkeyfc) dup 0 < \\ base ret t\/f \n\t \\ If we have been blocked, drop the useless returned data and try again.\n\t IF [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then] drop false \n\t ELSE true \\ Leave the return code intact.\n\t THEN \\ base ret t\/f \n\tuntil \\ base ret \n\tswap drop \n;\n\n\\ THis is a system call.\n\\ CODE (serkey?) \\ base -- t\/f\n\\ *G Return true if the given UART has a character avilable to read.\n\nexternal \n\n: seremit0\t\\ char --\n\\ *G Transmit a character on UART0.\n 0 (seremit) ;\n: sertype0\t\\ c-addr len --\n\\ *G Transmit a string on UART0.\n 0 (sertype) ;\n: sercr0\t\\ --\n\\ *G Issue a CR\/LF pair to UART0.\n 0 (sercr) ;\n: serkey?0\t\\ -- flag\n\\ *G Return true if UART0 has a character available.\n 0 (serkey?) ;\n: serkey0\t\\ -- char\n\\ *G Wait for a character on UART0.\n 0 (serkey) ;\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\n\\ *G Generic I\/O device for UART0.\n ' serkey0 ,\t\t\\ -- char ; receive char\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\n ' seremit0 ,\t\t\\ -- char ; display char\n ' sertype0 ,\t\t\\ caddr len -- ; display string\n ' sercr0 ,\t\t\\ -- ; display new line\n\n\\ --------------------------------------------------------------------\n\\ Optional devices\n\\ --------------------------------------------------------------------\n[defined] useUART1? [if] useUART1? 1 = [if] \n: seremit1 #1 (seremit) ;\n: sertype1 #1 (sertype) ;\n: sercr1 #1 (sercr) ;\n: serkey?1 #1 (serkey?) ;\n: serkey1 #1 (serkey) ;\ncreate Console1 ' serkey1 , ' serkey?1 , ' seremit1 , ' sertype1 , ' sercr1 ,\t\n[then] [then]\n\n\\ --------------------------------------------------------------------\n\\ Non-UARTs.\n\\ --------------------------------------------------------------------\n[defined] useStream10? [if] useStream10? 1 = [if] \n: seremit10 #10 (seremit) ;\n: sertype10\t#10 (sertype) ;\n: sercr10\t#10 (sercr) ;\n: serkey?10\t#10 (serkey?) ;\n: serkey10\t#10 (serkey) ;\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\n[then] [then]\n\nconsole-port 0 = [if]\n console0 constant console\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\n\\ ** It may be changed by one of the phrases of the form:\n\\ *C dup opvec ! ipvec !\n\\ *C SetConsole\n[then]\n\nconsole-port #10 = [if]\n console10 constant console\n[then]\n\n\\ ************************\n\\ *S System initialisation\n\\ ************************\n\n\\ This is a NOP in the SAPI environment\n: init-ser ;\t\\ --\n\\ *G Initialise all serial ports\n\n\\ ======\n\\ *> ###\n\\ ======\n\ndecimal\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"7faff021734db2928ee8a10b3eacfbac9c80c138","subject":"Removed NIP, TUCK and -ROT","message":"Removed NIP, TUCK and -ROT\n","repos":"hth313\/hthforth","old_file":"src\/lib\/core.fth","new_file":"src\/lib\/core.fth","new_contents":"( block 1 -- Main load block )\n\nVARIABLE BLK\n: FH BLK @ + ; \\ relative block\n: LOAD BLK @ SWAP DUP BLK ! (LOAD) BLK ! ;\n\n100 LOAD\n( shadow 1 )\n( block 2 )\n( shadow 2 )\n( block 3 )\n( shadow 3 )\n\n( block 10 )\n( shadow 10 )\n( block 11 )\n( shadow 11 )\n( block 12 )\n( shadow 12 )\n\n( block 100 )\n\n1 FH 6 FH THRU\n\n( shadow 100 )\n( block 101 stack primitives )\n\n: ROT >R SWAP R> SWAP ;\n\\ : -ROT SWAP >R SWAP R> ; \\ or ROT ROT\n: ?DUP DUP IF DUP THEN ;\n\\ : NIP ( n1 n2 -- n2 ) SWAP DROP ;\n\\ : TUCK ( n1 n2 -- n2 n1 n2 ) SWAP OVER ;\n\n: 2DROP DROP DROP ;\n: 2DUP OVER OVER ;\n: 2SWAP ROT >R ROT R> ;\n: 2OVER >R >R 2DUP R> R> 2SWAP ;\n( shadow 101 )\n( block 102 comparisons )\n\n-1 CONSTANT TRUE 0 CONSTANT FALSE\n\n: = ( n n -- f) XOR 0= ;\n: < ( n n -- f ) - 0< ;\n: > ( n n -- f ) SWAP < ;\n\n: MAX ( n n -- n ) 2DUP < IF SWAP THEN DROP ;\n: MIN ( n n -- n ) 2DUP > IF SWAP THEN DROP ;\n\n: WITHIN ( u ul uh -- f ) OVER - >R - R> U< ;\n( shadow 102 )\n( block 103 ALU )\n\n: 1+ 1 + ;\n: 1- 1 - ;\n: INVERT TRUE XOR ;\n: NEGATE INVERT 1+ ;\n: DNEGATE INVERT SWAP NEGATE SWAP OVER 0= - ;\n: S>D ( n -- d ) DUP 0< ; \\ sign extend\n: ABS S>D IF NEGATE THEN ;\n: DABS DUP 0< IF DNEGATE THEN ;\n\n\n: +- 0< IF NEGATE THEN ;\n: D+- 0< IF DNEGATE THEN ;\n\n( shadow 103 )\n( block 104 variables )\n\nVARIABLE BASE\n: DECIMAL 10 BASE ! ; : HEX 16 BASE ! ;\n( shadow 104 )\n( block 105 math )\n\n: SM\/REM ( d n -- r q ) \\ symmetric\n OVER >R >R DABS R@ ABS UM\/MOD\n R> R@ XOR 0< IF NEGATE THEN\n R> 0< IF >R NEGATE R> THEN ;\n\n: FM\/MOD ( d n -- r q ) \\ floored\n DUP 0< DUP >R IF NEGATE >R DNEGATE R> THEN\n >R DUP 0< IF R@ + THEN\n R> UM\/MOD R> IF >R NEGATE R> THEN ;\n\n: \/MOD OVER 0< SWAP FM\/MOD ;\n: MOD \/MOD DROP ;\n: \/ \/MOD SWAP DROP ;\n\n( shadow 105 )\n( block 106 math continued )\n\n: * UM* DROP ;\n: M* 2DUP XOR R> ABS SWAP ABS UM* R> D+- ;\n: *\/MOD >R M* R> FM\/MOD ;\n: *\/ *\/MOD NIP ;\n\n: 2* DUP + ;\n\\ 2\/ which is right shift is native\n( shadow 106 )\n( block 107 )\n( shadow 107 )\n( block 108 )\n( shadow 108 )\n( block 109 )\n( shadow 109 )\n( block 110 compiler )\n\n: VARIABLE CREATE 1 CELLS ALLOT ;\n\nVARIABLE STATE ( compilation state variable )\n0 STATE ! ( interpreting by default )\n: [ FALSE STATE ! ;\n: ] TRUE STATE ! ;\n\n( Colon definitions )\n: : CREATE ] ;\n: ; POSTPONE EXIT SMUDGE [ ; IMMEDIATE\n\n( shadow 110 )\n( block 111 )\n( shadow 111 )\n( block 112 interpreter )\n\nCREATE _INPUT-BUFFER 80 CHARS ALLOT ( may do this internally? )\n\n: EVALUATE >IN @ >R 0 >IN ! SOURCE >R >R #IN 2! _INTERPRET\n R> R> #IN 2! R> >IN ! ;\n\n: QUIT _RESET-RSTACK\n BEGIN\n BEGIN\n\t _READ-LINE 0 >IN ! _INPUT-BUFFER 0 EVALUATE CR\n\t STATE @\n UNTIL .\" ok \" ( exhausted input in interpretation mode )\n AGAIN ;\n( shadow 112 )\n","old_contents":"( block 1 -- Main load block )\n\nVARIABLE BLK\n: FH BLK @ + ; \\ relative block\n: LOAD BLK @ SWAP DUP BLK ! (LOAD) BLK ! ;\n\n100 LOAD\n( shadow 1 )\n( block 2 )\n( shadow 2 )\n( block 3 )\n( shadow 3 )\n\n( block 10 )\n( shadow 10 )\n( block 11 )\n( shadow 11 )\n( block 12 )\n( shadow 12 )\n\n( block 100 )\n\n1 FH 6 FH THRU\n\n( shadow 100 )\n( block 101 stack primitives )\n\n: ROT >R SWAP R> SWAP ;\n: -ROT SWAP >R SWAP R> ; \\ or ROT ROT\n: ?DUP DUP IF DUP THEN ;\n: NIP ( n1 n2 -- n2 ) SWAP DROP ;\n: TUCK ( n1 n2 -- n2 n1 n2 ) SWAP OVER ;\n\n: 2DROP DROP DROP ;\n: 2DUP OVER OVER ;\n: 2SWAP ROT >R ROT R> ;\n: 2OVER >R >R 2DUP R> R> 2SWAP ;\n( shadow 101 )\n( block 102 comparisons )\n\n-1 CONSTANT TRUE 0 CONSTANT FALSE\n\n: = ( n n -- f) XOR 0= ;\n: < ( n n -- f ) - 0< ;\n: > ( n n -- f ) SWAP < ;\n\n: MAX ( n n -- n ) 2DUP < IF SWAP THEN DROP ;\n: MIN ( n n -- n ) 2DUP > IF SWAP THEN DROP ;\n\n: WITHIN ( u ul uh -- f ) OVER - >R - R> U< ;\n( shadow 102 )\n( block 103 ALU )\n\n: 1+ 1 + ;\n: 1- 1 - ;\n: INVERT TRUE XOR ;\n: NEGATE INVERT 1+ ;\n: DNEGATE INVERT SWAP NEGATE TUCK 0= - ;\n: S>D ( n -- d ) DUP 0< ; \\ sign extend\n: ABS S>D IF NEGATE THEN ;\n: DABS DUP 0< IF DNEGATE THEN ;\n\n\n: +- 0< IF NEGATE THEN ;\n: D+- 0< IF DNEGATE THEN ;\n\n( shadow 103 )\n( block 104 variables )\n\nVARIABLE BASE\n: DECIMAL 10 BASE ! ; : HEX 16 BASE ! ;\n( shadow 104 )\n( block 105 math )\n\n: SM\/REM ( d n -- r q ) \\ symmetric\n OVER >R >R DABS R@ ABS UM\/MOD\n R> R@ XOR 0< IF NEGATE THEN\n R> 0< IF >R NEGATE R> THEN ;\n\n: FM\/MOD ( d n -- r q ) \\ floored\n DUP 0< DUP >R IF NEGATE >R DNEGATE R> THEN\n >R DUP 0< IF R@ + THEN\n R> UM\/MOD R> IF >R NEGATE R> THEN ;\n\n: \/MOD OVER 0< SWAP FM\/MOD ;\n: MOD \/MOD DROP ;\n: \/ \/MOD NIP ;\n\n( shadow 105 )\n( block 106 math continued )\n\n: * UM* DROP ;\n: M* 2DUP XOR R> ABS SWAP ABS UM* R> D+- ;\n: *\/MOD >R M* R> FM\/MOD ;\n: *\/ *\/MOD NIP ;\n\n: 2* DUP + ;\n\\ 2\/ which is right shift is native\n( shadow 106 )\n( block 107 )\n( shadow 107 )\n( block 108 )\n( shadow 108 )\n( block 109 )\n( shadow 109 )\n( block 110 compiler )\n\n: VARIABLE CREATE 1 CELLS ALLOT ;\n\nVARIABLE STATE ( compilation state variable )\n0 STATE ! ( interpreting by default )\n: [ FALSE STATE ! ;\n: ] TRUE STATE ! ;\n\n( Colon definitions )\n: : CREATE ] ;\n: ; POSTPONE EXIT SMUDGE [ ; IMMEDIATE\n\n( shadow 110 )\n( block 111 )\n( shadow 111 )\n( block 112 interpreter )\n\nCREATE _INPUT-BUFFER 80 CHARS ALLOT ( may do this internally? )\n\n: EVALUATE >IN @ >R 0 >IN ! SOURCE >R >R #IN 2! _INTERPRET\n R> R> #IN 2! R> >IN ! ;\n\n: QUIT _RESET-RSTACK\n BEGIN\n BEGIN\n\t _READ-LINE 0 >IN ! _INPUT-BUFFER 0 EVALUATE CR\n\t STATE @\n UNTIL .\" ok \" ( exhausted input in interpretation mode )\n AGAIN ;\n( shadow 112 )\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"89d084b0c2b769c8a2ba0795100ced5d806774fb","subject":"Prevent SAVE-FORTH from asking user Y\/N","message":"Prevent SAVE-FORTH from asking user Y\/N\n","repos":"philburk\/hmsl,philburk\/hmsl,philburk\/hmsl","old_file":"hmsl\/fth\/make_hmsl.fth","new_file":"hmsl\/fth\/make_hmsl.fth","new_contents":"\\ %Z% %M% %E% %I%\n\\ make_hmsl.fth\n\\ Create HMSL dictionary\n\ninclude fth\/load_hmsl.fth\n\n\\ Do not execute auto.init chain if stack is large.\n\\ This is a hack so that SAVE-FORTH won't trigger HMSL.INIT,\n\\ which asks the user Y\/N, which messes up the XCode build script.\n\\ We have to block this using the stack because if\n\\ we used a variable, the variable value would get saved in the dictionary\n\\ preventing HMSL.INIT when HMSL was run.\n: AUTO.INIT ( -- )\n depth 4 > IF\n .\" AUTO.INIT disabled because DEPTH > 4.\" cr\n .S\n\tELSE\n auto.init\n THEN\n;\n\n.\" Block AUTO.INIT that is called by SAVE-FORTH\" cr\n1 2 3 4 5 6\nc\" pforth.dic\" save-forth\n6 0 DO drop LOOP\n","old_contents":"\\ %Z% %M% %E% %I%\n\\ make_hmsl.fth\n\\ Create HMSL dictionary\n\ninclude fth\/load_hmsl.fth\nc\" pforth.dic\" save-forth\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Forth"} {"commit":"503fe7875d8026f8a088d926e8be81c5c72c9a89","subject":"Update SysCalls.ft for M0 Compatibility. Remove the support for passing in a zero'd TCB pointer.","message":"Update SysCalls.ft for M0 Compatibility.\nRemove the support for passing in a zero'd TCB pointer.\n","repos":"rbsexton\/sockpuppet,rbsexton\/sockpuppet","old_file":"forth\/SysCalls.fth","new_file":"forth\/SysCalls.fth","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"bsd-2-clause","lang":"Forth"} {"commit":"208696733a419f6f2b87aa24339e64bfd62d276e","subject":"Directly call the 'reboot' word instead of indirectly evaluating it.","message":"Directly call the 'reboot' word instead of indirectly evaluating it.\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/beastie.4th","new_file":"sys\/boot\/forth\/beastie.4th","new_contents":"\\ Copyright (c) 2003 Scott Long \n\\ Copyright (c) 2003 Aleksander Fafula \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\nmarker task-beastie.4th\n\ninclude \/boot\/screen.4th\ninclude \/boot\/frames.4th\n\nhide\n\nvariable menuidx\nvariable menubllt\nvariable menuX\nvariable menuY\nvariable promptwidth\n\nvariable bootkey\nvariable bootacpikey\nvariable bootsafekey\nvariable bootverbosekey\nvariable bootsinglekey\nvariable escapekey\nvariable rebootkey\n\n46 constant dot\n\n\\ The BSD Daemon. He is 19 rows high and 34 columns wide\n: technicolor-beastie ( x y -- )\n2dup at-xy .\" \u001b[1;31m, ,\" 1+\n2dup at-xy .\" \/( )`\" 1+\n2dup at-xy .\" \\ \\___ \/ |\" 1+\n2dup at-xy .\" \/- \u001b[37m_\u001b[31m `-\/ '\" 1+\n2dup at-xy .\" (\u001b[37m\/\\\/ \\\u001b[31m \\ \/\\\" 1+\n2dup at-xy .\" \u001b[37m\/ \/ |\u001b[31m ` \\\" 1+\n2dup at-xy .\" \u001b[34mO O \u001b[37m) \u001b[31m\/ |\" 1+\n2dup at-xy .\" \u001b[37m`-^--'\u001b[31m`< '\" 1+\n2dup at-xy .\" (_.) _ ) \/\" 1+\n2dup at-xy .\" `.___\/` \/ \" 1+\n2dup at-xy .\" `-----' \/\" 1+\n2dup at-xy .\" \u001b[33m<----.\u001b[31m __ \/ __ \\\" 1+\n2dup at-xy .\" \u001b[33m<----|====\u001b[31mO)))\u001b[33m==\u001b[31m) \\) \/\u001b[33m====|\" 1+\n2dup at-xy .\" \u001b[33m<----'\u001b[31m `--' `.__,' \\\" 1+\n2dup at-xy .\" | |\" 1+\n2dup at-xy .\" \\ \/ \/\\\" 1+\n2dup at-xy .\" \u001b[36m______\u001b[31m( (_ \/ \\______\/\" 1+\n2dup at-xy .\" \u001b[36m,' ,-----' |\" 1+\nat-xy .\" `--{__________) \u001b[0m\" 1+\n;\n\n: boring-beastie ( x y -- )\n\t2dup at-xy .\" , ,\" 1+\n\t2dup at-xy .\" \/( )`\" 1+\n\t2dup at-xy .\" \\ \\___ \/ |\" 1+\n\t2dup at-xy .\" \/- _ `-\/ '\" 1+\n\t2dup at-xy .\" (\/\\\/ \\ \\ \/\\\" 1+\n\t2dup at-xy .\" \/ \/ | ` \\\" 1+\n\t2dup at-xy .\" O O ) \/ |\" 1+\n\t2dup at-xy .\" `-^--'`< '\" 1+\n\t2dup at-xy .\" (_.) _ ) \/\" 1+\n\t2dup at-xy .\" `.___\/` \/\" 1+\n\t2dup at-xy .\" `-----' \/\" 1+\n\t2dup at-xy .\" <----. __ \/ __ \\\" 1+\n\t2dup at-xy .\" <----|====O)))==) \\) \/====\" 1+\n\t2dup at-xy .\" <----' `--' `.__,' \\\" 1+\n\t2dup at-xy .\" | |\" 1+\n\t2dup at-xy .\" \\ \/ \/\\\" 1+\n\t2dup at-xy .\" ______( (_ \/ \\______\/\" 1+\n\t2dup at-xy .\" ,' ,-----' |\" 1+\n\t at-xy .\" `--{__________)\"\n;\n\n: print-beastie ( x y -- )\n\ts\" loader_color\" getenv\n\tdup -1 = if\n\t\tdrop\n\t\tboring-beastie\n\t\texit\n\tthen\n\ts\" YES\" compare-insensitive 0<> if\n\t\tboring-beastie\n\t\texit\n\tthen\n\ttechnicolor-beastie\n;\n\n: acpienabled? ( -- flag )\n\ts\" acpi_load\" getenv\n\tdup -1 = if\n\t\tdrop false exit\n\tthen\n\ts\" YES\" compare-insensitive 0<> if\n\t\tfalse exit\n\tthen\n\ts\" hint.acpi.0.disabled\" getenv\n\tdup -1 <> if\n\t\ts\" 0\" compare 0<> if\n\t\t\tfalse exit\n\t\tthen\n\tthen\n\ttrue\n;\n\n: printmenuitem ( -- n )\n\tmenuidx @\n\t1+ dup\n\tmenuidx !\n\tmenuY @ + dup menuX @ swap at-xy\n\tmenuidx @ .\n\tmenuX @ 1+ swap at-xy\n\tmenubllt @ emit\n\tmenuidx @ 48 +\n;\n\n: beastie-menu ( -- )\n\t0 menuidx !\n\tdot menubllt !\n\t8 menuY !\n\t5 menuX !\n\tclear\n\t46 4 print-beastie\n\t42 20 2 2 box\n\t13 6 at-xy .\" Welcome to FreeBSD!\"\n\tprintmenuitem .\" Boot FreeBSD [default]\" bootkey !\n\ts\" arch-i386\" environment? if\n\t\tprintmenuitem .\" Boot FreeBSD with ACPI \" bootacpikey !\n\t\tacpienabled? if\n\t\t\t.\" disabled\"\n\t\telse\n\t\t\t.\" enabled\"\n\t\tthen\n\telse\n\t\t-2 bootacpikey !\n\tthen\n\tprintmenuitem .\" Boot FreeBSD in Safe Mode\" bootsafekey !\n\tprintmenuitem .\" Boot FreeBSD in single user mode\" bootsinglekey !\n\tprintmenuitem .\" Boot FreeBSD with verbose logging\" bootverbosekey !\n\tprintmenuitem .\" Escape to loader prompt\" escapekey !\n\tprintmenuitem .\" Reboot\" rebootkey !\n\tmenuX @ 20 at-xy\n\t.\" Select option, [Enter] for default\"\n\tmenuX @ 21 at-xy\n\ts\" or [Space] to pause timer \" dup 2 - promptwidth !\n\ttype\n;\n\n: tkey\n\tdup\n\tseconds +\n\tbegin 1 while\n\t\tover 0<> if\n\t\t\tdup seconds u< if\n\t\t\t\tdrop\n\t\t\t\t-1\n\t\t\t\texit\n\t\t\tthen\n\t\t\tmenuX @ promptwidth @ + 21 at-xy dup seconds - .\n\t\tthen\n\t\tkey? if\n\t\t\tdrop\n\t\t\tkey\n\t\t\texit\n\t\tthen\n\t50 ms\n\trepeat\n;\n\nset-current\n\n: beastie-start\n\ts\" beastie_disable\" getenv\n\tdup -1 <> if\n\t\ts\" YES\" compare-insensitive 0= if\n\t\t\texit\n\t\tthen\n\tthen\n\tbeastie-menu\n\ts\" autoboot_delay\" getenv\n\tdup -1 = if\n\t\tdrop\n\t\t10\n\telse\n\t\t0 0 2swap >number drop drop drop\n\tthen\n\tbegin true while\n\t\tdup tkey\n\t\t0 25 at-xy\n\t\tdup 32 = if nip 0 swap then\n\t\tdup -1 = if 0 boot then\n\t\tdup 13 = if 0 boot then\n\t\tdup bootkey @ = if 0 boot then\n\t\tdup bootacpikey @ = if\n\t\t\tacpienabled? if\n\t\t\t\ts\" acpi_load\" unsetenv\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\telse\n\t\t\t\ts\" YES\" s\" acpi_load\" setenv\n\t\t\t\ts\" 0\" s\" hint.acpi.0.disabled\" setenv\n\t\t\tthen\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootsafekey @ = if\n\t\t\ts\" arch-i386\" environment? if\n\t\t\t\ts\" acpi_load\" unsetenv\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\tthen\n\t\t\ts\" 0\" s\" hw.ata.ata_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.atapi_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.wc\" setenv\n\t\t\ts\" 0\" s\" hw.eisa_slots\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootverbosekey @ = if\n\t\t\ts\" YES\" s\" boot_verbose\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootsinglekey @ = if\n\t\t\ts\" YES\" s\" boot_single\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup escapekey @ = if\n\t\t\t2drop\n\t\t\ts\" NO\" s\" autoboot_delay\" setenv\n\t\t\texit\n\t\tthen\n\t\trebootkey @ = if 0 reboot then\n\trepeat\n;\n\nprevious\n","old_contents":"\\ Copyright (c) 2003 Scott Long \n\\ Copyright (c) 2003 Aleksander Fafula \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\nmarker task-beastie.4th\n\ninclude \/boot\/screen.4th\ninclude \/boot\/frames.4th\n\nhide\n\nvariable menuidx\nvariable menubllt\nvariable menuX\nvariable menuY\nvariable promptwidth\n\nvariable bootkey\nvariable bootacpikey\nvariable bootsafekey\nvariable bootverbosekey\nvariable bootsinglekey\nvariable escapekey\nvariable rebootkey\n\n46 constant dot\n\n\\ The BSD Daemon. He is 19 rows high and 34 columns wide\n: technicolor-beastie ( x y -- )\n2dup at-xy .\" \u001b[1;31m, ,\" 1+\n2dup at-xy .\" \/( )`\" 1+\n2dup at-xy .\" \\ \\___ \/ |\" 1+\n2dup at-xy .\" \/- \u001b[37m_\u001b[31m `-\/ '\" 1+\n2dup at-xy .\" (\u001b[37m\/\\\/ \\\u001b[31m \\ \/\\\" 1+\n2dup at-xy .\" \u001b[37m\/ \/ |\u001b[31m ` \\\" 1+\n2dup at-xy .\" \u001b[34mO O \u001b[37m) \u001b[31m\/ |\" 1+\n2dup at-xy .\" \u001b[37m`-^--'\u001b[31m`< '\" 1+\n2dup at-xy .\" (_.) _ ) \/\" 1+\n2dup at-xy .\" `.___\/` \/ \" 1+\n2dup at-xy .\" `-----' \/\" 1+\n2dup at-xy .\" \u001b[33m<----.\u001b[31m __ \/ __ \\\" 1+\n2dup at-xy .\" \u001b[33m<----|====\u001b[31mO)))\u001b[33m==\u001b[31m) \\) \/\u001b[33m====|\" 1+\n2dup at-xy .\" \u001b[33m<----'\u001b[31m `--' `.__,' \\\" 1+\n2dup at-xy .\" | |\" 1+\n2dup at-xy .\" \\ \/ \/\\\" 1+\n2dup at-xy .\" \u001b[36m______\u001b[31m( (_ \/ \\______\/\" 1+\n2dup at-xy .\" \u001b[36m,' ,-----' |\" 1+\nat-xy .\" `--{__________) \u001b[0m\" 1+\n;\n\n: boring-beastie ( x y -- )\n\t2dup at-xy .\" , ,\" 1+\n\t2dup at-xy .\" \/( )`\" 1+\n\t2dup at-xy .\" \\ \\___ \/ |\" 1+\n\t2dup at-xy .\" \/- _ `-\/ '\" 1+\n\t2dup at-xy .\" (\/\\\/ \\ \\ \/\\\" 1+\n\t2dup at-xy .\" \/ \/ | ` \\\" 1+\n\t2dup at-xy .\" O O ) \/ |\" 1+\n\t2dup at-xy .\" `-^--'`< '\" 1+\n\t2dup at-xy .\" (_.) _ ) \/\" 1+\n\t2dup at-xy .\" `.___\/` \/\" 1+\n\t2dup at-xy .\" `-----' \/\" 1+\n\t2dup at-xy .\" <----. __ \/ __ \\\" 1+\n\t2dup at-xy .\" <----|====O)))==) \\) \/====\" 1+\n\t2dup at-xy .\" <----' `--' `.__,' \\\" 1+\n\t2dup at-xy .\" | |\" 1+\n\t2dup at-xy .\" \\ \/ \/\\\" 1+\n\t2dup at-xy .\" ______( (_ \/ \\______\/\" 1+\n\t2dup at-xy .\" ,' ,-----' |\" 1+\n\t at-xy .\" `--{__________)\"\n;\n\n: print-beastie ( x y -- )\n\ts\" loader_color\" getenv\n\tdup -1 = if\n\t\tdrop\n\t\tboring-beastie\n\t\texit\n\tthen\n\ts\" YES\" compare-insensitive 0<> if\n\t\tboring-beastie\n\t\texit\n\tthen\n\ttechnicolor-beastie\n;\n\n: acpienabled? ( -- flag )\n\ts\" acpi_load\" getenv\n\tdup -1 = if\n\t\tdrop false exit\n\tthen\n\ts\" YES\" compare-insensitive 0<> if\n\t\tfalse exit\n\tthen\n\ts\" hint.acpi.0.disabled\" getenv\n\tdup -1 <> if\n\t\ts\" 0\" compare 0<> if\n\t\t\tfalse exit\n\t\tthen\n\tthen\n\ttrue\n;\n\n: printmenuitem ( -- n )\n\tmenuidx @\n\t1+ dup\n\tmenuidx !\n\tmenuY @ + dup menuX @ swap at-xy\n\tmenuidx @ .\n\tmenuX @ 1+ swap at-xy\n\tmenubllt @ emit\n\tmenuidx @ 48 +\n;\n\n: beastie-menu ( -- )\n\t0 menuidx !\n\tdot menubllt !\n\t8 menuY !\n\t5 menuX !\n\tclear\n\t46 4 print-beastie\n\t42 20 2 2 box\n\t13 6 at-xy .\" Welcome to FreeBSD!\"\n\tprintmenuitem .\" Boot FreeBSD [default]\" bootkey !\n\ts\" arch-i386\" environment? if\n\t\tprintmenuitem .\" Boot FreeBSD with ACPI \" bootacpikey !\n\t\tacpienabled? if\n\t\t\t.\" disabled\"\n\t\telse\n\t\t\t.\" enabled\"\n\t\tthen\n\telse\n\t\t-2 bootacpikey !\n\tthen\n\tprintmenuitem .\" Boot FreeBSD in Safe Mode\" bootsafekey !\n\tprintmenuitem .\" Boot FreeBSD in single user mode\" bootsinglekey !\n\tprintmenuitem .\" Boot FreeBSD with verbose logging\" bootverbosekey !\n\tprintmenuitem .\" Escape to loader prompt\" escapekey !\n\tprintmenuitem .\" Reboot\" rebootkey !\n\tmenuX @ 20 at-xy\n\t.\" Select option, [Enter] for default\"\n\tmenuX @ 21 at-xy\n\ts\" or [Space] to pause timer \" dup 2 - promptwidth !\n\ttype\n;\n\n: tkey\n\tdup\n\tseconds +\n\tbegin 1 while\n\t\tover 0<> if\n\t\t\tdup seconds u< if\n\t\t\t\tdrop\n\t\t\t\t-1\n\t\t\t\texit\n\t\t\tthen\n\t\t\tmenuX @ promptwidth @ + 21 at-xy dup seconds - .\n\t\tthen\n\t\tkey? if\n\t\t\tdrop\n\t\t\tkey\n\t\t\texit\n\t\tthen\n\t50 ms\n\trepeat\n;\n\nset-current\n\n: beastie-start\n\ts\" beastie_disable\" getenv\n\tdup -1 <> if\n\t\ts\" YES\" compare-insensitive 0= if\n\t\t\texit\n\t\tthen\n\tthen\n\tbeastie-menu\n\ts\" autoboot_delay\" getenv\n\tdup -1 = if\n\t\tdrop\n\t\t10\n\telse\n\t\t0 0 2swap >number drop drop drop\n\tthen\n\tbegin true while\n\t\tdup tkey\n\t\t0 25 at-xy\n\t\tdup 32 = if nip 0 swap then\n\t\tdup -1 = if 0 boot then\n\t\tdup 13 = if 0 boot then\n\t\tdup bootkey @ = if 0 boot then\n\t\tdup bootacpikey @ = if\n\t\t\tacpienabled? if\n\t\t\t\ts\" acpi_load\" unsetenv\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\telse\n\t\t\t\ts\" YES\" s\" acpi_load\" setenv\n\t\t\t\ts\" 0\" s\" hint.acpi.0.disabled\" setenv\n\t\t\tthen\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootsafekey @ = if\n\t\t\ts\" arch-i386\" environment? if\n\t\t\t\ts\" acpi_load\" unsetenv\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\tthen\n\t\t\ts\" 0\" s\" hw.ata.ata_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.atapi_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.wc\" setenv\n\t\t\ts\" 0\" s\" hw.eisa_slots\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootverbosekey @ = if\n\t\t\ts\" YES\" s\" boot_verbose\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootsinglekey @ = if\n\t\t\ts\" YES\" s\" boot_single\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup escapekey @ = if\n\t\t\t2drop\n\t\t\ts\" NO\" s\" autoboot_delay\" setenv\n\t\t\texit\n\t\tthen\n\t\trebootkey @ = if s\" reboot\" evaluate then\n\trepeat\n;\n\nprevious\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"b83f4b7b9f56b36b6de55964b5b57767cd427d5e","subject":"DEC2BIN added (not working)","message":"DEC2BIN added (not working)\n","repos":"bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas","old_file":"KataDiversion.fth","new_file":"KataDiversion.fth","new_contents":"\\ KataDiversion in Forth\n\n\\ -- utils\n\n\\ empty the stack\n: EMPTY\n DEPTH 0 <> IF BEGIN\n DROP DEPTH 0 =\n UNTIL\n THEN ;\n\n\\ power\n: ** ( n1 n2 -- n1_pow_n2 ) 1 SWAP ?DUP IF 0 DO OVER * LOOP THEN NIP ;\n\n\\ test if the top is a negative number\n: ?NEG ( n -- bool ) DUP 0= IF -1 ELSE DUP ABS <> THEN ;\n\n\\ log2 (integer)\n: LOG2 ( n -- n log2_n ) DUP 1 < IF 1 ABORT\" Log2 need a positive value.\"\n ELSE DUP 1 = IF 0\n ELSE\n 1 >R\n BEGIN ( n |R: i)\n DUP DUP 2 I ( n n n 2 i |R: i)\n ** ( n n n 2**i )\n - ( n n n-2**i )\n 2 * ( n n 2*[n-2**i])\n R> 1 + >R ( \u2026 |R: i+1)\n > ( n n>2*[n-2**i] )\n UNTIL\n R> 1 -\n THEN\n THEN ;\n\n\\ decimal to binary\n\\ e.g. : ( 11 -- 1 0 1 1 )\n\\ FIXME n DEC2BIN seems to give the binary value of n-1\n: DEC2BIN ( n -- n1 n2 n3 \u2026 ) DUP LOG2 2 SWAP ** >R ( n |R: X = 2 ** n.log2 )\n BEGIN\n DUP I - 0 > IF 1 SWAP I - ( 1 n-X )\n ELSE 0 SWAP ( 0 n )\n THEN\n I 1 =\n R> 2 \/ >R ( \u2026 | X\/2 )\n UNTIL\n R> 2DROP\n ;\n\n\\ -- kata\n\n\\ test if the given N has two adjacent 1 bits\n\\ e.g. : 1011 -> -1\n\\ 1001 -> 0\n: ?TWO-ADJACENT-1-BITS ( n -- bool ) ( TODO ) ;\n\n\\ return the maximum number which can be made with N (given number) bits\n: ?MAX-NB ( n -- m ) DUP ?NEG IF DROP 0 ( 0 )\n ELSE \n DUP IF DUP 2 SWAP ** NIP ( 2**n )\n THEN\n THEN ;\n\n\n\\ return the number of numbers which can be made with N (given number) bits\n\\ or less, and which have not two adjacent 1 bits.\n\\ see http:\/\/www.codekata.com\/2007\/01\/code_kata_fifte.html\n: ?HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS ( n -- m ) ( TODO ) ;\n","old_contents":"\\ KataDiversion in Forth\n\n\\ -- utils\n\n\\ empty the stack\n: EMPTY\n DEPTH 0 <> IF BEGIN\n DROP DEPTH 0 =\n UNTIL\n THEN ;\n\n\\ power\n: ** ( n1 n2 -- n1_pow_n2 ) 1 SWAP ?DUP IF 0 DO OVER * LOOP THEN NIP ;\n\n\\ test if the top is a negative number\n: ?NEG ( n -- bool ) DUP 0= IF -1 ELSE DUP ABS <> THEN ;\n\n\\ log2 (integer)\n: LOG2 ( n -- n log2_n ) DUP 1 < IF 1 ABORT\" Log2 need a positive value.\"\n ELSE DUP 1 = IF 0\n ELSE\n 1 >R\n BEGIN ( n |R: i)\n DUP DUP 2 I ( n n n 2 i |R: i)\n ** ( n n n 2**i )\n - ( n n n-2**i )\n 2 * ( n n 2*[n-2**i])\n R> 1 + >R ( \u2026 |R: i+1)\n > ( n n>2*[n-2**i] )\n UNTIL\n R> 1 -\n THEN\n THEN ;\n \n\n\\ -- kata\n\n\\ test if the given N has two adjacent 1 bits\n\\ e.g. : 1011 -> -1\n\\ 1001 -> 0\n: ?TWO-ADJACENT-1-BITS ( n -- bool ) ( TODO ) ;\n\n\\ return the maximum number which can be made with N (given number) bits\n: ?MAX-NB ( n -- m ) DUP ?NEG IF DROP 0 ( 0 )\n ELSE \n DUP IF DUP 2 SWAP ** NIP ( 2**n )\n THEN\n THEN ;\n\n\n\\ return the number of numbers which can be made with N (given number) bits\n\\ or less, and which have not two adjacent 1 bits.\n\\ see http:\/\/www.codekata.com\/2007\/01\/code_kata_fifte.html\n: ?HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS ( n -- m ) ( TODO ) ;\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"a75d50ddee5f3fd2a77ecb0988391484208f8deb","subject":"9 seconds for 4 x 4 puzzle, not bad for a language that's not going to get any optimization in the gnu toolset. I could probably shave a second or two off that by being more efficient with when I store things in memory instead of just always doing it, but I think this is an adequate effort for now. Plus I have that same behavior in the c version.","message":"9 seconds for 4 x 4 puzzle, not bad for a language that's not going to get any\noptimization in the gnu toolset. I could probably shave a second or two off that by being\nmore efficient with when I store things in memory instead of just always doing it, but I\nthink this is an adequate effort for now. Plus I have that same behavior in the c version.\n","repos":"Tim-Tom\/scratch,Tim-Tom\/scratch,Tim-Tom\/scratch,Tim-Tom\/scratch,Tim-Tom\/scratch,Tim-Tom\/scratch,Tim-Tom\/scratch,Tim-Tom\/scratch,Tim-Tom\/scratch,Tim-Tom\/scratch","old_file":"magic-puzzle\/magic-puzzle.fth","new_file":"magic-puzzle\/magic-puzzle.fth","new_contents":"3 constant width\n21 constant goal\nwidth 1- constant wm\nwidth 1+ constant wp\nwidth width * constant size\n\n(\ncreate choices 3 , 4 , 5 ,\n 6 , 7 , 8 ,\n 9 , 10 , 11 ,\n)\n\ncreate choices 1 , 2 , 3 , 4 ,\n 5 , 6 , 7 , 8 ,\n 9 , 10 , 11 , 12 ,\n 13 , 14 , 15 , 16 ,\n\nvariable picked size allot\nvariable additional-constraints size cells allot\n\n: clear-picked\n size 0 do\n 0 i picked + C!\n loop ;\n\n: print-picked\n size 0 do\n i picked + C@ .\n loop ;\n\nvariable a size cells allot\n\n: choice-search\n 0\n begin\n dup size < while\n choices over cells + @\n rot tuck = if\n drop -1 exit\n endif\n swap 1+\n repeat\n 2drop 0 ;\n\n: reverse-cross-valid\n 0\n wm wp * wm do\n a i cells + @ +\n wm +loop\n goal = ;\n\n: cross-valid\n 0\n size 0 do\n a i cells + @ +\n wp +loop\n goal = ;\n \n: bottom-row-valid\n 0\n size size width - do\n a i cells + @ +\n loop\n goal = ;\n\n: bottom-right-valid\n bottom-row-valid if\n cross-valid\n else\n 0\n endif ;\n\n0 VALUE pick-next-ref\n\n: execute-predicate?\n dup 0<> if\n execute\n else\n drop -1\n endif ;\n\n: pick-internal\n size 0 do\n dup cells a + choices i cells + @ swap !\n i picked + C@ 0= if\n dup cells additional-constraints + @ execute-predicate? if\n 1 i picked + C!\n dup pick-next-ref execute\n 0 i picked + C!\n endif\n endif\n loop\n drop ;\n\n: pick-right\n 0 over dup dup width mod - do\n a i cells + @ +\n loop\n goal swap - \n over over swap cells a + !\n choice-search if\n dup picked + C@ 0= if\n over cells additional-constraints + @ execute-predicate? if\n 1 over picked + C!\n over pick-next-ref execute\n 0 swap picked + C!\n else\n drop\n endif\n else\n drop\n endif\n endif\n drop ;\n\n: pick-bottom\n 0 over dup width mod do\n a i cells + @ +\n width +loop\n goal swap -\n over over swap cells a + !\n choice-search if\n dup picked + C@ 0= if\n over cells additional-constraints + @ execute-predicate? if\n 1 over picked + C!\n over pick-next-ref execute\n 0 swap picked + C!\n else\n drop\n endif\n else\n drop\n endif\n endif\n drop ;\n\ncreate solution-count 0 ,\n\n: solution\n solution-count @ 1+ dup solution-count !\n .\" --- Solution \" . .\" ---\" CR\n size 0 do\n a i cells + @ .\n i width mod wm = if CR endif\n loop ;\n\n: print-right-internal\n dup width mod wm = if\n .\" pick-right \" .\n else\n .\" pick-internal \" .\n endif ;\n\n: print-next\n dup . .\" -> \"\n dup size 1- = if\n drop .\" solution\"\n else\n dup width wm * >= if\n wm -\n print-right-internal\n else\n dup width dup 2 - * >= if\n width +\n .\" pick-bottom \" .\n else\n 1+\n print-right-internal\n endif\n endif\n endif ;\n\n: pick-right-internal\n dup width mod wm = if\n pick-right\n else\n pick-internal\n endif ;\n\n: pick-next\n dup size 1- = if\n drop solution\n else\n dup width wm * >= if\n wm -\n pick-right-internal\n else\n dup width dup 2 - * >= if\n width +\n pick-bottom\n else\n 1+\n pick-right-internal\n endif\n endif\n endif ;\n\n' pick-next TO pick-next-ref\n\n: init-board\n size 0 do\n i 1+ a i cells + !\n loop ;\n\n: clear-constraints\n size 0 do\n 0 additional-constraints i cells + !\n loop ;\n\n\nclear-constraints\n' reverse-cross-valid additional-constraints size width - width - 1+ cells + !\n' bottom-right-valid additional-constraints size 1- cells + !\n\n: solve-puzzle\n clear-picked init-board 0 solution-count !\n 0 pick-internal ;\n","old_contents":"3 constant width\n21 constant goal\nwidth 1- constant wm\nwidth 1+ constant wp\nwidth width * constant size\n\ncreate choices 3 , 4 , 5 ,\n 6 , 7 , 8 ,\n 9 , 10 , 11 ,\n\nvariable picked size allot\nvariable additional-constraints size cells allot\n\n: clear-picked\n size\n begin\n 1- dup 0>= while\n dup picked + 0 swap C!\n repeat\n drop ;\n\n: print-picked\n 9 0 do\n i picked + C@ .\n loop ;\n\n\nvariable a size cells allot\n\n: choice-search\n 0\n begin\n dup size < while\n choices over cells + @\n rot tuck = if\n drop -1 exit\n endif\n swap 1+\n repeat\n 2drop 0 ;\n\n: reverse-cross-valid\n 0\n wm wp * wm do\n a i cells + @ +\n wm +loop\n goal = ;\n\n: cross-valid\n 0\n size 0 do\n a i cells + @ +\n wp +loop\n goal = ;\n \n: bottom-row-valid\n 0\n size size width - do\n a i cells + @ +\n loop\n goal = ;\n\n: bottom-right-valid\n bottom-row-valid if\n cross-valid\n else\n 0\n endif ;\n\n0 VALUE pick-next-ref\n\n: execute-predicate?\n dup 0<> if\n execute\n else\n drop -1\n endif ;\n\n: pick-internal\n size 0 do\n dup cells a + choices i cells + @ swap !\n i picked + C@ 0= if\n dup cells additional-constraints + @ execute-predicate? if\n 1 i picked + C!\n dup pick-next-ref execute\n 0 i picked + C!\n endif\n endif\n loop\n drop ;\n\n: pick-right\n 0 over dup dup width mod - do\n a i cells + @ +\n loop\n goal swap - \n over over swap cells a + !\n choice-search if\n dup picked + C@ 0= if\n over cells additional-constraints + @ execute-predicate? if\n 1 over picked + C!\n over pick-next-ref execute\n 0 swap picked + C!\n else\n drop\n endif\n else\n drop\n endif\n endif\n drop ;\n\n: pick-bottom\n 0 over dup width mod do\n a i cells + @ +\n width +loop\n goal swap -\n over over swap cells a + !\n choice-search if\n dup picked + C@ 0= if\n over cells additional-constraints + @ execute-predicate? if\n 1 over picked + C!\n over pick-next-ref execute\n 0 swap picked + C!\n else\n drop\n endif\n else\n drop\n endif\n endif\n drop ;\n\ncreate solution-count 0 ,\n\n: solution\n solution-count @ 1+ dup solution-count !\n .\" --- Solution \" . .\" ---\" CR\n size 0 do\n a i cells + @ .\n i 3 mod 2 = if CR endif\n loop ;\n\n: print-right-internal\n dup width mod wm = if\n .\" pick-right \" .\n else\n .\" pick-internal \" .\n endif ;\n\n: print-next\n dup . .\" -> \"\n dup size 1- = if\n drop .\" solution\"\n else\n dup width wm * >= if\n wm -\n print-right-internal\n else\n dup width dup 2 - * >= if\n width +\n .\" pick-bottom \" .\n else\n 1+\n print-right-internal\n endif\n endif\n endif ;\n\n: pick-right-internal\n dup width mod wm = if\n pick-right\n else\n pick-internal\n endif ;\n\n: pick-next\n dup size 1- = if\n drop solution\n else\n dup width wm * >= if\n wm -\n pick-right-internal\n else\n dup width dup 2 - * >= if\n width +\n pick-bottom\n else\n 1+\n pick-right-internal\n endif\n endif\n endif ;\n\n' pick-next TO pick-next-ref\n\n: init-board\n size 0 do\n i 1+ a i cells + !\n loop ;\n\n: clear-constraints\n size 0 do\n 0 additional-constraints i cells + !\n loop ;\n\n\nclear-constraints\n' reverse-cross-valid additional-constraints size width - width - 1+ cells + !\n' bottom-right-valid additional-constraints size 1- cells + !\n\n: solve-puzzle\n clear-picked init-board 0 solution-count !\n 0 pick-internal ;\n","returncode":0,"stderr":"","license":"unlicense","lang":"Forth"} {"commit":"6497edb9341abf467977ca5d18b5a5adb3bb1dc5","subject":"Apparently you have to define structures before they get used.","message":"Apparently you have to define structures before they get used.","repos":"rbsexton\/gecko,rbsexton\/gecko,rbsexton\/gecko","old_file":"zero\/clock-umb\/forth\/Clock.fth","new_file":"zero\/clock-umb\/forth\/Clock.fth","new_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( -- )\n load-defaults \n icroot 0 over inter.rtcsem ! \\ Reset the free-running counters.\n 0 over inter.rtcdsem ! \\ Reset the free-running counters.\n\n begin \n \tdup inter.rtcsem @offex! ?dup if advancehms then\n \tdup inter.rtcdsem @offex! ?dup if advancedhms then\n [asm wfi asm]\n uiupdate if use-uivals else use-clockvals then \n key? until drop\n;\n \n\\ These two contain loops to ensure that we don't\n\\ drop any timer ticks on the floor.\n: ADVANCEHMS ( n -- ) 0 do hms advancetime loop ;\n: ADVANCEDHMS ( n -- ) 0 do dhms advancetime loop ;\n \n: LOAD-DEFAULTS ( -- )\n #1000 needlemax\n 2dup ! 4 + 2dup ! 4 + ! \n interp-init\n;\n\n\\ ----------------------------------------------------------\n\\ Define the structures before they get used.\n\\ ----------------------------------------------------------\nstruct ODN \\ On-Deck Needle \n\t2 field odn.s\n\t2 field odn.m\n\t2 field odn.h\nend-struct\n\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxsec \\ Max Value for secs+minutes\n\tint hms.maxhour \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_m \\ increment the minutes + hours\nend-struct\n\nstruct _interp_set\n\t4 cells field interp.a\n\t4 cells field interp.b\n\t4 cells field interp.c\nend-struct\n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nidata\ncreate NEEDLEMAX 3 cells allot\ncreate ODN_HMS odn allot \\ On-Deck, HMS\ncreate ODN_DHMS odn allot \\ On-Deck, DHMS\ncreate ODN_UI odn allot \\ On-Deck, Generated by the UI.\ncdata\n\n: rangecheck ( max n -- n or zero ) dup >R <= if R> drop 0 else R> then ; \n\n: ++NEEDLE_S \\ Called every time.\n odn_hms odn.s \\ Stash this address for the moment. \n\n\tinterp_max odn.s @ \\ Get the max \n\tover w@ \\ Current value \n\n\tinterp_hms interp.a interp-next + \\ Returns a value.\n\t\n\t\\ If we've wrapped to zero, reset the interpolator \n\t\\ so that we don't accumulate errors during setting\/\n\t\\ calibration operations.\n rangecheck dup 0= if interp_hms interp.a interp-reset then \t\t\n\tswap w! \n\t;\n\n: ++NEEDLE_DS ; \\ Called every time.\n\n: ++NEEDLE_M ; \\ Every time we roll the seconds.\n: ++NEEDLE_DM ; \\ Every time we roll the seconds.\n\n\n\n: _USE ( odn-addr -- ) \n dup w@ pwm0!\n 2 + w@ pwm1!\n 4 + w@ pwm2!\n ;\n\n: USE-CLOCKVALS odn_hms _use ; \n: USE-UIVALS odn_ui _use ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Quadrature\n\\ ----------------------------------------------------------\n\n: QUAD@ ( addr -- n ) \\ Fetch and zero\n @off [asm sxth tos, tos asm] ;\n \n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_ds , ' ++needle_dm , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n: ADVANCETIME ( struct-addr -- )\n dup hms.w_s @ execute \\ Invoke the official update word.\n 1 over hms.subsec +! \\ Increment\n dup hms.subsec @\n over hms.maxsubsec @ < if drop exit then \\ If less then max, we're done\n 0 over hms.subsec ! \\ Reset the subsecs \n\n dup hms.w_m @ execute\n 1 over hms.s +!\n dup hms.s @ over hms.maxsec @ < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n 1 over hms.m +!\n dup hms.m @ over hms.maxsec @ < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ over hms.maxhour @ < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ----------------------------------------------------------\n\\ The interpolator. \n\\ Implement bresenhams algorithm. All of this code already\n\\ exists in C, but we'll own the data structures. They contain\n\\ A total of 4 words - fixed, err, num, & denom\n\\ ----------------------------------------------------------\nudata \ncreate interp_hms _interp_set allot\ncreate interp_dhms _interp_set allot \ncreate adj_list #50 cells allot \\ 100 16-bit words. \ncdata\n\n\\ Heres the default values. These are universal.\nidata\ncreate interp_max #850 , #850 , #850 ,\ncdata\n\n#16 #60 * equ raw_sec\n#10 #100 * equ raw_dsec\n\n: INTERP-INIT ( -- )\n (interp_init) interp_hms\n 2dup interp.a interp_max @ raw_sec call3-- \n 2dup interp.b interp_max 4 + @ #60 call3-- \n interp.c interp_max 8 + @ #12 call3--\n\n (interp_init) interp_dhms\n 2dup interp.a interp_max @ raw_dsec call3-- \n 2dup interp.b interp_max 4 + @ #100 call3-- \n interp.c interp_max 8 + @ #10 call3--\n;\n\n\\ Call the reset fn.\n: INTERP-RESET ( interp_addr -- )\n (interp_reset) swap call1-- \n;\n\n: INTERP-NEXT ( addr -- n )\n (interp_next) swap call1--n\n;\n\n\n\\ ============================ UNTESTED =======================\n\\ VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n\n\\ ----------------------------------------------------------\n\\ User Interface\n\\ ----------------------------------------------------------\nvariable uistate\nvariable uicount \n\n_GPIO $64 + equ _BUTTONIO\n: BUTTONUP? ( -- t\/f ) _buttonio @ 1 and ; \n: BUTTONDOWN? ( -- t\/f ) buttonup? 1 or ; \n\n\\ The wrapper for all of the UI stuff.\n\\ Returns true if the UI is active - ie, use the values generated by the UI.\n: UIUPDATE ( -- t\/f )\n StateHandlers uistate @ + @ execute \n; \n\n\\ -----------------------------------------------\n\\ State numbers. These are defined x4 so that\n\\ we can just use the state number as an index \n\\ into a table of words.\n\\ -----------------------------------------------\n0 4 * equ _s_init\n1 4 * equ _s_b1\n2 4 * equ _s_1sec\n3 4 * equ _s_seth\n4 4 * equ _s_pendset_m\n5 4 * equ _s_setmin\n6 4 * equ _s_pendcal0\n7 4 * equ _s_cal0\n8 4 * equ _s_pendcalh\n9 4 * equ _s_calh\n10 4 * equ _s_pendcalm\n11 4 * equ _s_calm\n12 4 * equ _s_pendcals\n13 4 * equ _s_cals\n\n\\ All of the state handlers.\n\\ Everybody needs to know the state of the button, so that must\n\\ get passed in, thus they all look like this:\n\\ state ( t\/f -- t\/f )\n: shInit false \n buttondown? if \n _s_b1 uistate !\n uicount off \\ Reset this.\n then\n ;\n\n\\ Waiting for a full second to go by.\n: shB1 false\n buttonup? if _s_init uistate ! exit then\n \\ The Button is down. \n uicount @ 16 > if\n _s_1sec uistate !\n else \n 1 uicount +!\n\tthen\n ;\n\n\\ We're in the 1 second state\n: sh1sec true \n buttonup? if _s_seth uistate ! true exit then\n uicount @ 48 > if\n _s_pendcal0 uistate !\n else \n 1 uicount +!\n\tthen \n;\n\n\\ -------------------------------------------------\n\\ Setting the time\n\\ -------------------------------------------------\n: shSetH true buttondown? if _s_pendset_m uistate ! exit then ;\n\n: shPendSetM true buttonup? if _s_setmin uistate ! then ;\n: shSetMin true buttondown? if _s_pendset_m uistate ! exit then ;\n\n\\ -------------------------------------------------\n\\ Calibration\n\\ -------------------------------------------------\n: shPendCal0 true buttonup? if _s_cal0 uistate ! then ;\n: shCal0 true buttondown? if _s_pendcalh uistate ! exit then ;\n\n: shPendCalH true buttonup? if _s_calh uistate ! then ; \n: shCalH true buttondown? if _s_pendcalm uistate ! exit then ; \n\n: shPendCalM true buttonup? if _s_calm uistate ! then ; \n: shCalM true buttondown? if _s_pendcals uistate ! exit then ; \n\n: shPendCalS true buttonup? if _s_calm uistate ! then ; \n: shCalS true buttondown? if _s_init uistate ! exit then ; \n\ncreate StateHandlers \n' shInit , \n' shB1 ,\n' sh1sec ,\n' shSetH ,\n' shPendSetM , ' shSetMin ,\n\n' shPendCal0 , ' shCal0 ,\n' shPendCalH , ' shCalH , \n' shPendCalM , ' shCalM , \n' shPendCalS , ' shCalS , \n\n","old_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( -- )\n load-defaults \n icroot 0 over inter.rtcsem ! \\ Reset the free-running counters.\n 0 over inter.rtcdsem ! \\ Reset the free-running counters.\n\n begin \n \tdup inter.rtcsem @offex! ?dup if hms advancetime then\n \tdup inter.rtcdsem @offex! ?dup if dhms advancetime then\n [asm wfi asm]\n uiupdate if use-uivals else use-clockvals then \n key? until drop\n;\n \n: LOAD-DEFAULTS ( -- )\n #1000 needlemax\n 2dup ! 4 + 2dup ! 4 + ! \n;\n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nstruct ODN \n\t2 field odn.s\n\t2 field odn.m\n\t2 field odn.h\nend-struct\n\nudata\ncreate NEEDLEMAX 3 cells allot\ncreate ODN_HMS odn allot \\ On-Deck, HMS\ncreate ODN_DHMS odn allot \\ On-Deck, DHMS\ncreate ODN_UI odn allot \\ On-Deck, Generated by the UI.\ncdata\n\n: rangecheck ( max n -- n or zero ) dup >R <= if R> drop 0 else R> then ; \n\n: ++NEEDLE_S \\ Called every time.\n odn_hms odn.s \\ Stash this address for the moment. \n\tinterp_max odn.s @ \\ Get the max \n\tover w@ \\ Current value \n\tinterp_hms interp.a interp-next + \\ Returns a value.\n\t\n\t\\ If we've wrapped to zero, reset the interpolator \n\t\\ the zero resets on every needle sweep.\n rangecheck ?dup if interp_hms interp.a interp-reset then \n swap w! \n;\n\n: ++NEEDLE_DS ; \\ Called every time.\n\n: ++NEEDLE_M ; \\ Every time we roll the seconds.\n: ++NEEDLE_DM ; \\ Every time we roll the seconds.\n\n\n\n: _USE ( odn-addr -- ) \n dup w@ pwm0!\n 2 + w@ pwm1!\n 4 + w@ pwm2!\n ;\n\n: USE-CLOCKVALS odn_hms _use ; \n: USE-UIVALS odn_ui _use ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Quadrature\n\\ ----------------------------------------------------------\n\n: QUAD@ ( addr -- n ) \\ Fetch and zero\n @off [asm sxth tos, tos asm] ;\n \n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxsec \\ Max Value for secs+minutes\n\tint hms.maxhour \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_m \\ increment the minutes + hours\nend-struct\n\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_ds , ' ++needle_dm , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n: ADVANCETIME ( struct-addr -- )\n dup hms.w_s @ execute \\ Invoke the official update word.\n 1 over hms.subsec +! \\ Increment\n dup hms.subsec @\n over hms.maxsubsec @ < if drop exit then \\ If less then max, we're done\n 0 over hms.subsec ! \\ Reset the subsecs \n\n dup hms.w_m @ execute\n 1 over hms.s +!\n dup hms.s @ over hms.maxsec @ < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n 1 over hms.m +!\n dup hms.m @ over hms.maxsec @ < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ over hms.maxhour @ < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ----------------------------------------------------------\n\\ The interpolator. \n\\ Implement bresenhams algorithm. All of this code already\n\\ exists in C, but we'll own the data structures. They contain\n\\ A total of 4 words - fixed, err, num, & denom\n\\ ----------------------------------------------------------\nstruct _interp_set\n\t4 cells field interp.a\n\t4 cells field interp.b\n\t4 cells field interp.c\nend-struct\n\nudata \ncreate interp_hms _interp_set allot\ncreate interp_dhms _interp_set allot \ncreate adj_list #50 cells allot \\ 100 16-bit words. \ncdata\n\n\\ Heres the default values. These are universal.\nidata\ncreate interp_max #850 , #850 , #850 ,\ncdata\n\n#16 #60 * equ raw_sec\n#10 #100 * equ raw_dsec\n\n: INTERP-INIT ( -- )\n (interp_init) interp_hms\n 2dup interp.a interp_max @ raw_sec call3-- \n 2dup interp.b interp_max 4 + @ #60 call3-- \n interp.c interp_max 8 + @ #12 call3--\n\n (interp_init) interp_dhms\n 2dup interp.a interp_max @ raw_dsec call3-- \n 2dup interp.b interp_max 4 + @ #100 call3-- \n interp.c interp_max 8 + @ #10 call3--\n;\n\n\\ Call the reset fn.\n: INTERP-RESET ( interp_addr -- )\n (interp_reset) swap call1-- \n;\n\n: INTERP-NEXT ( addr -- n )\n (interp_next) swap call1--n\n;\n\n\n\\ ============================ UNTESTED =======================\n\\ VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n\n\\ ----------------------------------------------------------\n\\ User Interface\n\\ ----------------------------------------------------------\nvariable uistate\nvariable uicount \n\n_GPIO $64 + equ _BUTTONIO\n: BUTTONUP? ( -- t\/f ) _buttonio @ 1 and ; \n: BUTTONDOWN? ( -- t\/f ) buttonup? 1 or ; \n\n\\ The wrapper for all of the UI stuff.\n\\ Returns true if the UI is active - ie, use the values generated by the UI.\n: UIUPDATE ( -- t\/f )\n StateHandlers uistate @ + @ execute \n; \n\n\\ -----------------------------------------------\n\\ State numbers. These are defined x4 so that\n\\ we can just use the state number as an index \n\\ into a table of words.\n\\ -----------------------------------------------\n0 4 * equ _s_init\n1 4 * equ _s_b1\n2 4 * equ _s_1sec\n3 4 * equ _s_seth\n4 4 * equ _s_pendset_m\n5 4 * equ _s_setmin\n6 4 * equ _s_pendcal0\n7 4 * equ _s_cal0\n8 4 * equ _s_pendcalh\n9 4 * equ _s_calh\n10 4 * equ _s_pendcalm\n11 4 * equ _s_calm\n12 4 * equ _s_pendcals\n13 4 * equ _s_cals\n\n\\ All of the state handlers.\n\\ Everybody needs to know the state of the button, so that must\n\\ get passed in, thus they all look like this:\n\\ state ( t\/f -- t\/f )\n: shInit false \n buttondown? if \n _s_b1 uistate !\n uicount off \\ Reset this.\n then\n ;\n\n\\ Waiting for a full second to go by.\n: shB1 false\n buttonup? if _s_init uistate ! exit then\n \\ The Button is down. \n uicount @ 16 > if\n _s_1sec uistate !\n else \n 1 uicount +!\n\tthen\n ;\n\n\\ We're in the 1 second state\n: sh1sec true \n buttonup? if _s_seth uistate ! true exit then\n uicount @ 48 > if\n _s_pendcal0 uistate !\n else \n 1 uicount +!\n\tthen \n;\n\n\\ -------------------------------------------------\n\\ Setting the time\n\\ -------------------------------------------------\n: shSetH true buttondown? if _s_pendset_m uistate ! exit then ;\n\n: shPendSetM true buttonup? if _s_setmin uistate ! then ;\n: shSetMin true buttondown? if _s_pendset_m uistate ! exit then ;\n\n\\ -------------------------------------------------\n\\ Calibration\n\\ -------------------------------------------------\n: shPendCal0 true buttonup? if _s_cal0 uistate ! then ;\n: shCal0 true buttondown? if _s_pendcalh uistate ! exit then ;\n\n: shPendCalH true buttonup? if _s_calh uistate ! then ; \n: shCalH true buttondown? if _s_pendcalm uistate ! exit then ; \n\n: shPendCalM true buttonup? if _s_calm uistate ! then ; \n: shCalM true buttondown? if _s_pendcals uistate ! exit then ; \n\n: shPendCalS true buttonup? if _s_calm uistate ! then ; \n: shCalS true buttondown? if _s_init uistate ! exit then ; \n\ncreate StateHandlers \n' shInit , \n' shB1 ,\n' sh1sec ,\n' shSetH ,\n' shPendSetM , ' shSetMin ,\n\n' shPendCal0 , ' shCal0 ,\n' shPendCalH , ' shCalH , \n' shPendCalM , ' shCalM , \n' shPendCalS , ' shCalS , \n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"6c13d9384a9dfe2f5975657cee35731ee76d6927","subject":"Make things a bit more concise.","message":"Make things a bit more concise.","repos":"rbsexton\/sockpuppet,rbsexton\/sockpuppet","old_file":"forth\/serCM3_SAPI-level0.fth","new_file":"forth\/serCM3_SAPI-level0.fth","new_contents":"\\ serCM3_sapi_level0.fth - SAPI polled RX, polled TX, serial communication drivers\n\\ Written to run against the SockPuppet API.\n\n\\ Level 0 support, with WFI instead of pause.\n\\ The SAPI is a system call interace, so there is no blocking.\n\\ KEY requires blocking, so that must be implemented here.\n\nonly forth definitions\n\n\\ ==============\n\\ *T SAPI polled serial driver\n\\ ==============\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\n\\ ** using the internal UARTs via the SAPI call layer. This is \n\\ ** The simplest implementation level.\n\n\\ ****************\n\\ *S Configuration\n\\ ****************\n\\ *P Configuration is managed by the SAPI\n\ntarget\n\n\\ ********************\n\\ *S Serial primitives\n\\ ********************\ninternal\n\n: +FaultConsole\t( -- ) ;\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\n\\ ** for more details.\n\ntarget\n\n\\ CODE (seremitfc)\t\\ char base --\n\\ This is a system call.\n\n: (seremit)\t\\ char base -- \n\\ *G Wrapped call that checks for throttling, and if so,\n\\ calls PAUSE to let another task run, or just does a WFI if no multitasker.\n\\ The only interesting thing is failure, or -1. That means retry.\n\tbegin \n\t2dup (seremitfc) dup 0 < \\ char base ret t\/f\n\tIF [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then] THEN \\ char base ret \n 0 >= until\n 2drop\n\t;\n\n: (sertype) \\ caddr len base --\n\\ *G Transmit a string on the given UART.\n\\ * The system call wants base len caddr\n\t>R \\ We'll use this a few times.\n\tbegin \n\t2dup R@ (sertypefc) dup \\ caddr len ret ret\n\tIF \n\t [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then]\n\t dup >R - swap R> + swap \\ Advance the caddr len pair\n\tTHEN \n\t0= until\n\t2drop \n\tR> drop \n;\n\n: (sercr)\t\\ base --\n\\ *G Transmit a CR\/LF pair on the given UART.\n\\ Wrapped version, just like (seremit)\n\tbegin \n\tdup (sercrfc) dup 0= \\ base ret t\/f\n IF [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then] THEN \\ base ret \n until\n drop\n\t;\n\n: (serkey) \\ base -- c\n\\ *G Get a character from the port. Retry until we get it.\n\\ See if its negative. If so, discard it and leave false to re-loop.\n\\ If not negative, leave true on the stack to exit.\n begin \\ base ret t\/f \n\tdup (serkeyfc) dup 0 < \\ base ret t\/f \n\t IF [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then] drop false \n\t ELSE true \n\t THEN \\ base ret t\/f \n\tuntil \\ base ret \n\tswap drop \n;\n\n\\ THis is a system call.\n\\ CODE (serkey?) \\ base -- t\/f\n\\ *G Return true if the given UART has a character avilable to read.\n\nexternal \n\n: seremit0\t\\ char --\n\\ *G Transmit a character on UART0.\n 0 (seremit) ;\n: sertype0\t\\ c-addr len --\n\\ *G Transmit a string on UART0.\n 0 (sertype) ;\n: sercr0\t\\ --\n\\ *G Issue a CR\/LF pair to UART0.\n 0 (sercr) ;\n: serkey?0\t\\ -- flag\n\\ *G Return true if UART0 has a character available.\n 0 (serkey?) ;\n: serkey0\t\\ -- char\n\\ *G Wait for a character on UART0.\n 0 (serkey) ;\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\n\\ *G Generic I\/O device for UART0.\n ' serkey0 ,\t\t\\ -- char ; receive char\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\n ' seremit0 ,\t\t\\ -- char ; display char\n ' sertype0 ,\t\t\\ caddr len -- ; display string\n ' sercr0 ,\t\t\\ -- ; display new line\n\n\\ Non-UARTs.\n: seremit10 #10 (seremit) ;\n: sertype10\t#10 (sertype) ;\n: sercr10\t#10 (sercr) ;\n: serkey?10\t#10 (serkey?) ;\n: serkey10\t#10 (serkey) ;\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\n\nconsole-port 0 = [if]\n console0 constant console\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\n\\ ** It may be changed by one of the phrases of the form:\n\\ *C dup opvec ! ipvec !\n\\ *C SetConsole\n[then]\n\nconsole-port #10 = [if]\n console10 constant console\n[then]\n\n\\ ************************\n\\ *S System initialisation\n\\ ************************\n\n\\ This is a NOP in the SAPI environment\n: init-ser ;\t\\ --\n\\ *G Initialise all serial ports\n\n\\ ======\n\\ *> ###\n\\ ======\n\ndecimal\n","old_contents":"\\ serCM3_sapi_level0.fth - SAPI polled RX, polled TX, serial communication drivers\n\\ Written to run against the SockPuppet API.\n\n\\ Level 0 support, with WFI instead of pause.\n\\ The SAPI is a system call interace, so there is no blocking.\n\\ KEY requires blocking, so that must be implemented here.\n\nonly forth definitions\n\n\\ ==============\n\\ *T SAPI polled serial driver\n\\ ==============\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\n\\ ** using the internal UARTs via the SAPI call layer. This is \n\\ ** The simplest implementation level.\n\n\\ ****************\n\\ *S Configuration\n\\ ****************\n\\ *P Configuration is managed by the SAPI\n\ntarget\n\n\\ ********************\n\\ *S Serial primitives\n\\ ********************\ninternal\n\n: +FaultConsole\t( -- ) ;\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\n\\ ** for more details.\n\ntarget\n\n\\ CODE (seremitfc)\t\\ char base --\n\\ This is a system call.\n\n: (seremit)\t\\ char base -- \n\\ *G Wrapped call that checks for throttling, and if so,\n\\ calls PAUSE to let another task run, or just does a WFI if no multitasker.\n\\ The only interesting thing is failure, or -1. That means retry.\n\tbegin \n\t2dup (seremitfc) dup 0 < \\ char base ret t\/f\n[ tasking? ] [if]\n\tIF PAUSE THEN\n[else]\n\tIF [asm wfi asm] THEN\n[then] \\ char base ret \n 0 >= until\n 2drop\n\t;\n\n: (sertype) \\ caddr len base --\n\\ *G Transmit a string on the given UART.\n\\ * The system call wants base len caddr\n\t>R \\ We'll use this a few times.\n\tbegin \n\t2dup R@ (sertypefc) dup \\ caddr len ret ret\n\tIF \n\t [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then]\n\t dup >R - swap R> + swap \\ Advance the caddr len pair\n\tTHEN \n\t0= until\n\t2drop \n\tR> drop \n;\n\n: (sercr)\t\\ base --\n\\ *G Transmit a CR\/LF pair on the given UART.\n\\ Wrapped version, just like (seremit)\n\tbegin \n\tdup (sercrfc) dup 0= \\ base ret t\/f\n[ tasking? ] [if]\n\tIF PAUSE THEN\n[else]\n\tIF [asm wfi asm] THEN\n[then] \\ base ret \n until\n drop\n\t;\n\n: (serkey) \\ base -- c\n\\ *G Get a character from the port. Retry until we get it.\n\\ See if its negative. If so, discard it and leave false to re-loop.\n\\ If not negative, leave true on the stack to exit.\n begin \\ base ret t\/f \n\tdup (serkeyfc) dup 0 < \\ base ret t\/f \n\t[ tasking? ] [if]\n\t\tIF PAUSE drop false ELSE true THEN\n\t[else]\n\t\tIF [asm wfi asm] drop false ELSE true THEN\n\t[then] \\ base ret \n\tuntil \\ base ret \n\tswap drop \n;\n\n\\ THis is a system call.\n\\ CODE (serkey?) \\ base -- t\/f\n\\ *G Return true if the given UART has a character avilable to read.\n\nexternal \n\n: seremit0\t\\ char --\n\\ *G Transmit a character on UART0.\n 0 (seremit) ;\n: sertype0\t\\ c-addr len --\n\\ *G Transmit a string on UART0.\n 0 (sertype) ;\n: sercr0\t\\ --\n\\ *G Issue a CR\/LF pair to UART0.\n 0 (sercr) ;\n: serkey?0\t\\ -- flag\n\\ *G Return true if UART0 has a character available.\n 0 (serkey?) ;\n: serkey0\t\\ -- char\n\\ *G Wait for a character on UART0.\n 0 (serkey) ;\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\n\\ *G Generic I\/O device for UART0.\n ' serkey0 ,\t\t\\ -- char ; receive char\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\n ' seremit0 ,\t\t\\ -- char ; display char\n ' sertype0 ,\t\t\\ caddr len -- ; display string\n ' sercr0 ,\t\t\\ -- ; display new line\n\n\\ Non-UARTs.\n: seremit10 #10 (seremit) ;\n: sertype10\t#10 (sertype) ;\n: sercr10\t#10 (sercr) ;\n: serkey?10\t#10 (serkey?) ;\n: serkey10\t#10 (serkey) ;\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\n\nconsole-port 0 = [if]\n console0 constant console\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\n\\ ** It may be changed by one of the phrases of the form:\n\\ *C dup opvec ! ipvec !\n\\ *C SetConsole\n[then]\n\nconsole-port #10 = [if]\n console10 constant console\n[then]\n\n\\ ************************\n\\ *S System initialisation\n\\ ************************\n\n\\ This is a NOP in the SAPI environment\n: init-ser ;\t\\ --\n\\ *G Initialise all serial ports\n\n\\ ======\n\\ *> ###\n\\ ======\n\ndecimal\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"dc55584392601996465c14e1e97814ccf4fc9832","subject":"Fixed bug in umax","message":"Fixed bug in umax\n","repos":"howerj\/libforth","old_file":"forth.fth","new_file":"forth.fth","new_contents":"#!.\/forth\n( Welcome to libforth, A dialect of Forth. Like all versions\nof Forth this version is a little idiosyncratic, but how\nthe interpreter works is documented here and in various\nother files.\n\nThis file contains most of the start up code, some basic\nstart up code is executed in the C file as well which makes\nprogramming at least bearable. Most of Forth is programmed in\nitself, which may seem odd if your back ground in programming\ncomes from more traditional language [such as C], although\nless so if you know already know lisp.\n\nFor more information about this interpreter and Forth see:\n\nhttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\nAnd within this code base:\n\n\treadme.md : for a manual for this interpreter\n\tlibforth.h : for information about the C API\n\tlibforth.c : for the interpreter itself\n\tunit.c : unit tests for libforth.c\n\tunit.fth : unit tests against this file\n\tmain.c : an example interpreter\n\nThe interpreter and this code originally descend from a Forth\ninterpreter written in 1992 for the International obfuscated\nC Coding Competition.\n\nSee:\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\nThe manual for the interpreter should be read first before\nlooking into this code. It is important to understand the\nexecution model of Forth, especially the differences between\ncommand and compile mode, and how immediate and compiling\nwords work.\n\nEach of these sections is clearly labeled and they are\ngenerally in dependency order.\n\nUnfortunately the code in this file is not as portable as it\ncould be, it makes assumptions about the size of cells provided\nby the virtual machine, which will take time to rectify. Some\nof the constructs are subtly different from the DPANs Forth\nspecification, which is usually noted. Eventually this should\nalso be fixed.\n\nA little note on how code is formatted, a line of Forth code\nshould not exceed 64 characters. All words stack effect, how\nmany variables on the stack it accepts and returns, should\nbe commented with the following types:\n\n\tchar \/ c A character\n\tc-addr An address of a character\n\taddr An address of a cell\n\tr-addr A real address*\n\tu A unsigned number\n\tn A signed number\n\tc\" xxx\" The word parses a word\n\tc\" x\" The word parses a single character\n\txt An execution token\n\tbool A boolean value\n\tior A file error return status [0 on no error]\n\tfileid A file identifier.\n\tCODE A number from a words code field\n\tPWD A number from a words previous word field\n\t* A real address is one outside the range of the\n\tForth address space.\n\nIn the comments Forth words should be written in uppercase. As\nthis is supposed to be a tutorial about Forth and describe the\ninternals of a Forth interpreter, be as verbose as possible.\n\nThe code in this file will need to be modified to abide by\nthese standards, but new code should follow it from the start.\n\nDoxygen style tags for documenting bugs, todos and warnings\nshould be used within comments. This makes finding code that\nneeds working on much easier.)\n\n( ==================== Basic Word Set ======================== )\n\n( We'll begin by defining very simple words we can use later,\nthese a very basic words, that perform simple tasks, they\nwill not require much explanation.\n\nEven though the words are simple, their stack comment and\na description for them will still be included so external\ntools can process and automatically extract the document\nstring for a given work. )\n\n: postpone ( c\" xxx\" -- : postpone execution of a word )\n\timmediate find , ;\n\n: constant\n\t:: ( compile word header )\n\there 1 - h ! ( decrement dictionary pointer )\n\t( change instruction to CONST )\n\there @ instruction-mask invert and doconst or here !\n\there 1 + h ! ( increment dictionary pointer )\n\t, ( write in value )\n\tpostpone [ ; ( back into command mode )\n\n( These constants are defined as a space saving measure,\nnumbers in a definition usually take up two cells, one\nfor the instruction to push the next cell and the cell\nitself, for the most frequently used numbers it is worth\ndefining them as constants, it is just as fast but saves\na lot of space )\n-1 constant -1\n 0 constant 0\n 1 constant 1\n 2 constant 2\n 3 constant 3\n\n0 constant false\n1 constant true ( @warning not standards compliant )\n\n( Confusingly the word CR prints a line feed )\n10 constant lf ( line feed )\nlf constant nl ( new line - line feed on Unixen )\n13 constant cret ( carriage return )\n\n-1 -1 1 rshift invert and constant min-signed-integer\nmin-signed-integer invert constant max-signed-integer\n\n( The following version number is used to mark whether core\nfiles will be compatible with each other, The version number\ngets stored in the core file and is used by the loader to\ndetermine compatibility )\n4 constant version ( version number for the interpreter )\n\n( This constant defines the number of bits in an address )\ncell size 8 * * constant address-unit-bits \n\n( Bit corresponding to the sign in a number )\n-1 -1 1 rshift and invert constant sign-bit \n\n( @todo test by how much, if at all, making words like 1+,\n1-, <>, and other simple words, part of the interpreter would\nspeed things up )\n\n: 1+ ( x -- x : increment a number )\n\t1 + ;\n\n: 1- ( x -- x : decrement a number )\n\t1 - ;\n\n: chars ( c-addr -- addr : convert a c-addr to an addr )\n\tsize \/ ;\n\n: chars> ( addr -- c-addr: convert an addr to a c-addr )\n\tsize * ;\n\n: tab ( -- : print a tab character )\n\t9 emit ;\n\n: 0= ( n -- bool : is 'n' equal to zero? )\n\t0 = ;\n\n: not ( n -- bool : is 'n' true? )\n\t0= ;\n\n: <> ( n n -- bool : not equal )\n\t= 0= ;\n\n: logical ( n -- bool : turn a value into a boolean )\n\tnot not ;\n\n: 2, ( n n -- : write two values into the dictionary )\n\t, , ;\n\n: [literal] ( n -- : write a literal into the dictionary )\n\tdolit 2, ;\n\n: literal ( n -- : immediately compile a literal )\n\timmediate [literal] ;\n\n: sliteral immediate ( I: c-addr u --, Run: -- c-addr u )\n\tswap [literal] [literal] ;\n\n( @todo throw if not found )\n: ['] ( I: c\" xxx\", Run: -- xt )\n\timmediate find [literal] ;\n\n: >instruction ( CODE -- u : extract instruction CODE field )\n\tinstruction-mask and ;\n\n( IMMEDIATE-MASK pushes the mask for the compile bit,\nwhich can be used on a CODE field of a word )\n1 compile-bit lshift constant immediate-mask\n\n: hidden? ( PWD -- PWD bool : is a word hidden? )\n\tdup 1+ @ hidden-mask and logical ;\n\n: compiling? ( PWD -- PWD bool : is a word immediate? )\n\tdup 1+ @ immediate-mask and logical ;\n\n: cr ( -- : emit a newline character )\n\tnl emit ;\n\n: < ( x1 x2 -- bool : signed less than comparison )\n\t- dup if max-signed-integer u> else logical then ;\n\n: > ( x1 x2 -- bool : signed greater than comparison )\n\t- dup if max-signed-integer u< else logical then ;\n\n( The pad area is an area used for temporary storage, some\nwords use it, although which ones do should be kept to a\nminimum. It is an area of space #pad amount of characters\nafter the latest dictionary definition. The area between\nthe end of the dictionary and start of PAD space is used for\npictured numeric output [<#, #, #S, #>]. It is best not to\nuse the pad area that much. )\n128 constant #pad\n\n: pad ( -- addr : push pointer to the pad area )\n\there #pad + ;\n\n( @todo this can be improved a lot, currently it uses more\nspace than it has to, 4 cells instead of three.\n\nIt does:\n\n\tpush value\n\tpush value\n\nInstead of:\n\n\tmagic-2literal-word\n\tvalue\n\tvalue\n\n)\n: 2literal immediate ( n n -- : compile two literals )\n\tswap [literal] [literal] ;\n\n: latest ( get latest defined word )\n\tpwd @ ;\n\n: stdin ( -- fileid : push fileid for standard input )\n\t`stdin @ ;\n\n: stdout ( -- fileid : push fileid for standard output )\n\t`stdout @ ;\n\n: stderr ( -- fileid : push fileid for the standard error )\n\t`stderr @ ;\n\n: stdin? ( -- bool : are we reading from standard input )\n\t`fin @ stdin = ;\n\n: *+ ( n1 n2 n3 -- n )\n\t* + ;\n\t\n: 2- ( n -- n : decrement by two )\n\t2 - ;\n\n: 2+ ( n -- n : increment by two )\n\t2 + ;\n\n: 3+ ( n -- n : increment by three )\n\t3 + ;\n\n: 2* ( n -- n : multiply by two )\n\t1 lshift ;\n\n: 2\/ ( n -- n : divide by two )\n\t1 rshift ;\n\n: 4* ( n -- n : multiply by four )\n\t2 lshift ;\n\n: 4\/ ( n -- n : divide by four )\n\t2 rshift ;\n\n: 8* ( n -- n : multiply by eight )\n\t3 lshift ;\n\n: 8\/ ( n -- n : divide by eight )\n\t3 rshift ;\n\n: 256* ( n -- n : multiply by 256 )\n\t8 lshift ;\n\n: 256\/ ( n -- n : divide by 256 )\n\t8 rshift ;\n\n: 2dup ( n1 n2 -- n1 n2 n1 n2 : duplicate two values )\n\tover over ;\n\n: mod ( u1 u2 -- u : calculate the remainder of u1\/u2 )\n\t2dup \/ * - ;\n\n( @todo implement UM\/MOD in the VM, then use this to implement\n'\/' and MOD )\n: um\/mod ( u1 u2 -- rem quot : remainder and quotient of u1\/u2 )\n\t2dup \/ >r mod r> ;\n\n( @warning this does not use a double cell for the multiply )\n: *\/ ( n1 n2 n3 -- n4 : [n2*n3]\/n1 )\n\t * \/ ;\n\n: char ( -- n : read in a character from the input steam )\n\tkey drop key ;\n\n: [char] ( c\" x\" -- R: -- char : immediately compile next char )\n\timmediate char [literal] ;\n\n( COMPOSE is a high level function that can take two executions\ntokens and produce a unnamed function that can do what they\nboth do.\n\nIt can be used like so:\n\n\t:noname 2 ;\n\t:noname 3 + ;\n\tcompose\n\texecute \n\t.\n\t5 <-- 5 is printed!\n\nI have not found a use for it yet, but it sure is neat.)\n\n: compose ( xt1 xt2 -- xt3 : create a function from xt-tokens )\n\t>r >r ( save execution tokens )\n\tpostpone :noname ( create a new :noname word )\n\tr> , ( write first token )\n\tr> , ( write second token )\n\t(;) ; ( terminate new :noname )\n\n( CELLS is a word that is not needed in this interpreter but\nit required to write portable code [I have probably missed\nquite a few places where it should be used]. The reason it\nis not needed in this interpreter is a cell address can only\nbe in multiples of cells, not in characters. This should be\naddressed in the libforth interpreter as it adds complications\nwhen having to convert to and from character and cell address.)\n\n: cells ( n1 -- n2 : convert cell count to address count)\n\timmediate ;\n\n: cell+ ( a-addr1 -- a-addr2 )\n\tcell + ;\n\n: cell- ( a-addr1 -- addr2 )\n\tcell - ;\n\n: negative? ( x -- bool : is a number negative? )\n\tsign-bit and logical ;\n\n: mask-byte ( x -- x : generate mask byte )\n\t8* 255 swap lshift ;\n\n: select-byte ( u i -- c )\n\t8* rshift 0xff and ;\n\n: xt-instruction ( PWD -- CODE : extract instruction from PWD )\n\tcell+ @ >instruction ;\n\n: defined-word? ( PWD -- bool : is defined or a built-in word)\n\txt-instruction dolist = ;\n\n: char+ ( c-addr -- c-addr : increment a c-addr one c-addr )\n\t1+ ;\n\n: 2chars ( c-addr1 c-addr2 -- addr addr : chars on two c-addr) \n\tchars swap chars swap ;\n\n: 2chars> ( addr addr -- c-addr c-addr: chars> on two addr )\n\tchars> swap chars> swap ;\n\n: hex ( -- : print out hex )\n\t16 base ! ;\n\n: octal ( -- : print out octal )\n\t8 base ! ;\n\n: binary ( -- : print out binary )\n\t2 base ! ;\n\n: decimal ( -- : print out decimal )\n\t0 base ! ;\n\n: negate ( x -- x )\n\t-1 * ;\n\n: abs ( x -- u : return the absolute value of a number )\n\tdup negative? if negate then ;\n\n: square ( x -- x )\n\tdup * ;\n\n: sum-of-squares ( a b -- c : compute a^2 + b^2 to get c )\n\tsquare swap square + ;\n\n: drup ( x y -- x x )\n\tdrop dup ;\n\n: +! ( x addr -- : add x to a value stored at addr )\n\ttuck @ + swap ! ;\n\n: 1+! ( addr -- : increment a value at an address )\n\t1 swap +! ;\n\n: 1-! ( addr -- : decrement a value at an address )\n\t-1 swap +! ;\n\n: c+! ( x c-addr -- : add x to a value stored at c-addr )\n\ttuck c@ + swap c! ;\n\n: toggle ( addr u -- : xor value at addr with u )\n\tover @ xor swap ! ;\n\n: lsb ( x -- x : mask off the least significant byte of a cell )\n\t255 and ;\n\n: \\ ( -- : immediate word, used for single line comments )\n\timmediate begin key nl = until ;\n\n: ?dup ( x -- ? )\n\tdup if dup then ;\n\n: min ( n n -- n : return the minimum of two integers )\n\t2dup < if drop else nip then ;\n\n: max ( n n -- n : return the maximum of two integers )\n\t2dup > if drop else nip then ;\n\n: umin ( u u -- u : return the minimum of two unsigned numbers )\n\t2dup u< if drop else nip then ;\n\n: umax ( u u -- u : return the maximum of two unsigned numbers )\n\t2dup u> if drop else nip then ;\n\n: limit ( x min max -- x : limit x with a minimum and maximum )\n\trot min max ;\n\n: >= ( n n -- bool )\n\t< not ;\n\n: <= ( n n -- bool )\n\t> not ;\n\n: 2@ ( a-addr -- u1 u2 : load two consecutive memory cells )\n\tdup 1+ @ swap @ ;\n\n: 2! ( u1 u2 a-addr -- : store two values at two consecutive memory cells )\n\t2dup ! nip 1+ ! ;\n\n( @bug I don't think this is correct. )\n: r@ ( -- u, R: u -- )\n\tr> r @ swap >r ;\n\n: rp@ ( -- u, R: u -- )\n\tr> r @ swap >r ;\n\n( @todo r!, rp! )\n\n: 0> ( n -- bool )\n\t0 > ;\n\n: 0<= ( n -- bool )\n\t0> not ;\n\n: 0< ( n -- bool )\n\t0 < ;\n\n: 0>= ( n -- bool )\n\t0< not ;\n\n: 0<> ( n -- bool )\n\t0 <> ;\n\n: signum ( n -- -1 | 0 | 1 : Signum function )\n\tdup 0> if drop 1 exit then\n\t 0< if -1 exit then\n\t0 ;\n\n: nand ( u u -- u : bitwise NAND )\n\tand invert ;\n\n: odd ( u -- bool : is 'n' odd? )\n\t1 and ;\n\n: even ( u -- bool : is 'n' even? )\n\todd not ;\n\n: nor ( u u -- u : bitwise NOR )\n\tor invert ;\n\n: ms ( u -- : wait at least 'u' milliseconds )\n\tclock + begin dup clock u< until drop ;\n\n: sleep ( u -- : sleep for 'u' seconds )\n\t1000 * ms ;\n\n: align ( addr -- addr : align an address, nop in this implemented )\n\timmediate ;\n\n: ) ( -- : do nothing, this allows easy commenting out of code )\n\timmediate ;\n\n: bell ( -- : emit an ASCII BEL character )\n\t7 emit ;\n\n: b\/buf ( -- u : bytes per buffer )\n\t1024 ;\n\n: .d ( x -- x : debug print )\n\tdup . ;\n\n: compile, ( x -- : )\n\t, ;\n\n: >mark ( -- : write a hole into the dictionary and push a pointer to it )\n\there 0 , ;\n\n: r - r> u< ;\n\n: invalidate ( -- : invalidate this Forth core )\n\t1 `invalid ! ;\n\n: signed ( x -- bool : return true if sign bit set )\n\t[ 1 size 8 * 1- lshift ] literal and logical ;\n\n: u>= ( x y -- bool : unsigned greater than or equal to )\n\t2dup u> >r = r> or ;\n\n: u<= ( x y -- bool : unsigned less than or equal to )\n\tu>= not ;\n\n: rdrop ( R: x -- : drop a value from the return stack )\n\tr> ( get caller's return address )\n\tr> ( get value to drop )\n\tdrop ( drop it like it's hot )\n\t>r ; ( return return address )\n\n: rdup\n\tr> ( get caller's return address )\n\tr> ( get value to duplicate )\n\tdup ( ... )\n\t>r >r >r ; ( make it all work )\n\n: chere ( -- c-addr : here as in character address units )\n\there chars> ;\n\n: source ( -- c-addr u )\n\t#tib ( size of input buffer, in characters )\n\ttib ; ( start of input buffer, in characters )\n\n: stdin? ( -- bool : are we reading from standard in? )\n\t`fin @ `stdin @ = ;\n\n: source-id ( -- 0 | -1 | file-id )\n\t( \t\n\tValue Input Source\n\t-1 String\n\t0 Reading from user input \/ standard in\n\tfile-id )\n\t`source-id @\n\t0= if\n\t\tstdin? if 0 else `fin @ then\n\telse\n\t\t-1\n\tthen ;\n\n: under ( x1 x2 -- x1 x1 x2 )\n\t>r dup r> ;\n\n: 2nip ( n1 n2 n3 n4 -- n3 n4 )\n\t>r >r 2drop r> r> ;\n\n: 2over ( n1 n2 n3 n4 \u2013 n1 n2 n3 n4 n1 n2 )\n\t>r >r 2dup r> swap >r swap r> r> -rot ;\n\n: 2swap ( n1 n2 n3 n4 \u2013 n3 n4 n1 n2 )\n\t>r -rot r> -rot ;\n\n: 2tuck ( n1 n2 n3 n4 \u2013 n3 n4 n1 n2 n3 n4 )\n\t2swap 2over ;\n\n: 3drop ( n1 n2 n3 -- )\n\tdrop 2drop ;\n\n: 4drop ( n1 n2 n3 n4 -- )\n\t2drop 2drop ;\n\n: nos1+ ( x1 x2 -- x1+1 x2 : increment the next variable on that stack )\n\tswap 1+ swap ;\n\n: ?dup-if immediate ( x -- x | - : ?dup and if rolled into one! )\n\t['] ?dup , postpone if ;\n\n: ?if ( -- : non destructive if )\n\timmediate ['] dup , postpone if ;\n\n: (hide) ( token -- hide-token : this hides a word from being found by the interpreter )\n\t?dup-if\n\t\tdup @ hidden-mask or swap tuck ! exit\n\tthen 0 ;\n\n: hide ( WORD -- : hide with drop )\n\tfind dup if (hide) then drop ;\n\n: reveal ( hide-token -- : reveal a hidden word )\n\tdup @ hidden-mask invert and swap ! ;\n\n: ?exit ( x -- : exit current definition if not zero )\n\tif rdrop exit then ;\n\n: decimal? ( c -- f : is character a number? )\n\t[char] 0 [ char 9 1+ ] literal within ;\n\n: lowercase? ( c -- f : is character lower case? )\n\t[char] a [ char z 1+ ] literal within ;\n\n: uppercase? ( C -- f : is character upper case? )\n\t[char] A [ char Z 1+ ] literal within ;\n\n: alpha? ( C -- f : is character part of the alphabet? )\n\tdup lowercase? swap uppercase? or ;\n\n: alphanumeric? ( C -- f : is character alphabetic or a number ? )\n\tdup alpha? swap decimal? or ;\n\n: printable? ( c -- bool : is printable, excluding new lines and tables )\n\t32 127 within ;\n\n: >upper ( c -- C : convert char to uppercase iff lower case )\n\tdup lowercase? if bl xor then ;\n\n: >lower ( C -- c : convert char to lowercase iff upper case )\n\tdup uppercase? if bl xor then ;\n\n: <=> ( x y -- z : spaceship operator! )\n\t2dup\n\t> if 2drop -1 exit then\n\t< ;\n\n: start-address ( -- c-addr : push the start address )\n\t`start-address @ ;\n\n: >real-address ( c-addr -- r-addr : convert an interpreter address to a real address )\n\tstart-address + ;\n\n: real-address> ( c-addr -- r-addr : convert a real address to an interpreter address )\n\tstart-address - ;\n\n: peek ( r-addr -- n : )\n\tpad chars> >real-address swap size memory-copy pad @ ;\n\n: poke ( n r-addr -- : )\n\tswap pad ! pad chars> >real-address size memory-copy ;\n\n: die! ( x -- : controls actions when encountering certain errors )\n\t`error-handler ! ;\n\n: start! ( cfa -- : set the word to execute at startup )\n\t`instruction ! ;\t\n\n: warm ( -- : restart the interpreter, warm restart )\n\t1 restart ;\n\n: trip ( x -- x x x : triplicate a number )\n\tdup dup ;\n\n: roll ( xu xu-1 ... x0 u -- xu-1 ... x0 xu : move u+1 items on the top of the stack by u )\n\t[ smudge ] ( un-hide this word so we can call it recursively )\n\tdup 0 >\n\tif\n\t\tswap >r 1- roll r> swap\n\telse\n\t\tdrop\n\tthen ;\nsmudge\n\n: 2rot ( n1 n2 n3 n4 n5 n6 \u2013 n3 n4 n5 n6 n1 n2 )\n\t5 roll 5 roll ;\n\n: s>d ( x -- d : convert a signed value to a double width cell )\n\t( @note the if...else...then is only necessary as this Forths\n\tbooleans are 0 and 1, not 0 and -1 as it usually is )\n\tdup 0< if -1 else 0 then ;\n\n: trace ( level -- : set tracing level )\n\t`debug ! ;\n\n: verbose ( -- : get the log level )\n\t`debug @ ;\n\n: count ( c-addr1 -- c-addr2 u : get a string whose first char is its length )\n\tdup c@ nos1+ ;\n\n: bounds ( x y -- y+x x : make an upper and lower bound )\n\tover + swap ;\n\n: aligned ( unaligned -- aligned : align a pointer )\n\t[ size 1- ] literal +\n\t[ size 1- ] literal invert and ;\n\n: rdepth\n\tmax-core `stack-size @ - r @ swap - ;\n\n: argv ( -- r-addr : push pointer to array of string pointers to program )\n\t`argv @ ;\n\n: argc ( -- u : push the number of arguments in the argv array )\n\t`argc @ ;\n\n: +- ( x1 x2 -- x3 : copy the sign of x1 to x2 giving x3 )\n\t[ sign-bit 1- ] literal and\n\tswap\n\tsign-bit and or ;\n\n: \/string ( c-addr1 u1 u2 -- c-addr2 u2 : advance a string by n characters )\n\tover min rot over + -rot - ;\n\nhide stdin?\n\n: cfa immediate ( find-address -- cfa )\n\t( Given the address of the PWD field of a word this\n\tfunction will return an execution token for the word )\n\t( @todo if < dictionary start PWD is invalid )\n\t ;\n\n: again immediate\n\t( loop unconditionally in a begin-loop:\n\t\tbegin ... again )\n\t['] branch , body ( xt -- a-addr : a-addr is data field of a CREATEd word )\n\\\tcfa 5 + ;\n\n\n: execute ( xt -- : given an execution token, execute the word )\n\t( create a word that pushes the address of a hole to write to.\n\tA literal takes up two words, '!' takes up one, that's right,\n\tsome self modifying code! )\n\t[ here 3 cells + literal ] ( calculate place to write to )\n\t! ( write an execution token to a hole )\n\t[ 0 , ] ; ( this is the hole we write )\n\n( @todo integrate catch\/throw into the interpreter as primitives )\n: catch ( xt -- exception# | 0 : return addr on stack )\n\tsp@ >r ( xt : save data stack pointer )\n\t`handler @ >r ( xt : and previous handler )\n\tr@ `handler ! ( xt : set current handler )\n\texecute ( execute returns if no throw )\n\tr> `handler ! ( restore previous handler )\n\tr> drop ( discard saved stack ptr )\n\t0 ; ( 0 : normal completion )\n\n( @todo use this everywhere )\n: throw ( ??? exception# -- ??? exception# )\n\t?dup-if ( exc# \\ 0 throw is no-op )\n\t\t`handler @ r ! ( exc# : restore prev return stack )\n\t\tr> `handler ! ( exc# : restore prev handler )\n\t\tr> swap >r ( saved-sp : exc# on return stack )\n\t\tsp! drop r> ( exc# : restore stack )\n\t\t( return to the caller of catch because return )\n\t\t( stack is restored to the state that existed )\n\t\t( when catch began execution )\n\tthen ;\n\n: interpret ( c1\" xxx\" ... cn\" xxx\" -- : This word implements the interpreter loop )\n\tbegin\n\t['] read catch\n\t?dup-if [char] ! emit tab . cr then ( exception handler of last resort )\n\tagain ;\n\n: [interpret] ( c1\" xxx\" ... cn\" xxx\" -- : immediate version of interpret )\n\timmediate interpret ;\n\ninterpret ( use the new interpret word, which can catch exceptions )\n\nfind [interpret] cell+ start! ( the word executed on restart is now our new word )\n\n( The following words are using in various control structure related\nwords to make sure they only execute in the correct state )\n\n: ?comp ( -- : error if not compiling )\n\tstate @ 0= if -14 throw then ;\n\n: ?exec ( -- : error if not executing )\n\tstate @ if -22 throw then ;\n\n( begin...while...repeat These are defined in a very \"Forth\" way )\n: while\n\t?comp\n\timmediate postpone if ( branch to repeats THEN ) ;\n\n: whilst postpone while ;\n\n: repeat immediate\n\t?comp\n\tswap ( swap BEGIN here and WHILE here )\n\tpostpone again ( again jumps to begin )\n\tpostpone then ; ( then writes to the hole made in if )\n\n: never ( never...then : reserve space in word )\n\timmediate 0 [literal] postpone if ;\n\n: unless ( bool -- : like IF but execute clause if false )\n\timmediate ?comp ['] 0= , postpone if ;\n\n: endif ( synonym for THEN )\n\timmediate ?comp postpone then ;\n\n( Experimental FOR ... NEXT )\n: for immediate \n\t?comp\n\t['] 1- ,\n\t['] >r ,\n\there ;\n\n: (next) ( -- bool, R: val -- | val+1 )\n\tr> r> 1- dup 0< if drop >r 1 else >r >r 0 then ;\n\n: next immediate\n\t?comp\n\t['] (next) , \n\t['] ?branch , \n\there - , ;\n\n( ==================== Basic Word Set ======================== )\n\n( ==================== DOER\/MAKE ============================= )\n( DOER\/MAKE is a word set that is quite powerful and is\ndescribed in Leo Brodie's book \"Thinking Forth\". It can be\nused to make words whose behavior can change after they\nare defined. It essentially makes the structured use of\nself-modifying code possible, along with the more common\ndefinitions of \"defer\/is\".\n\nAccording to \"Thinking Forth\", it has two purposes:\n\n1. To change the state of a function.\n2. To factor out common phrases of a words definition.\n\nAn example of the first instance:\n\n\tdoer say\n\t: sad \" Good bye, cruel World!\" cr ;\n\t: happy \" Hello, World!\" cr ;\n\n\t: person say ;\n\n\tmake person happy\n\tperson \\ prints \"Good bye, cruel World!\"\n\n\tmake person sad\n\tperson \\ prints \"Hello, World!\"\n\nAn example of the second:\n\n\tdoer op\n\n\t: sum \\ n0 ... nX X -- sum<0..X>\n\t\tmake op + 1 do op loop ;\n\n\t: mul \\ n0 ... nX X -- mul<0..X>\n\t\tmake op * 1 do op loop ;\n\nThe above example is a bit contrived, the definitions and\nfunctionality are too simple for this to be worth factoring\nout, but it shows how you can use DOER\/MAKE. )\n\n: noop ; ( -- : default word to execute for doer, does nothing )\n\n: doer ( c\" xxx\" -- : make a work whose behavior can be changed by make )\n\timmediate ?exec :: ['] noop , (;) ;\n\n: found? ( xt -- xt : thrown an exception if the xt is zero )\n\tdup 0= if -13 throw then ;\n\n( It would be nice to provide a MAKE that worked with\nexecution tokens as well, although \"defer\" and \"is\" can be\nused for that. MAKE expects two word names to be given as\narguments. It will then change the behavior of the first word\nto use the second. MAKE is a state aware word. )\n\n: make immediate ( c1\" xxx\" c2\" xxx\" : change parsed word c1 to execute c2 )\n\tfind found? cell+\n\tfind found?\n\tstate @ if ( compiling )\n\t\tswap postpone 2literal ['] ! ,\n\telse ( command mode )\n\t\tswap !\n\tthen ;\n\n( ==================== DOER\/MAKE ============================= )\n\n( ==================== Extended Word Set ===================== )\n\n: r.s ( -- : print the contents of the return stack )\n\tr>\n\t[char] < emit rdepth (.) drop [char] > emit\n\tspace\n\trdepth dup 0> if dup\n\tbegin dup while r> -rot 1- repeat drop dup\n\tbegin dup while rot dup . >r 1- repeat drop\n\tthen drop cr\n\t>r ;\n\n: log ( u base -- u : command the _integer_ logarithm of u in base )\n\t>r\n\tdup 0= if -11 throw then ( logarithm of zero is an error )\n\t0 swap\n\tbegin\n\t\tnos1+ rdup r> \/ dup 0= ( keep dividing until 'u' is zero )\n\tuntil\n\tdrop 1- rdrop ;\n\n: log2 ( u -- u : compute the _integer_ logarithm of u )\n\t2 log ;\n\n: alignment-bits ( c-addr -- u : get the bits used for aligning a cell )\n\t[ 1 size log2 lshift 1- literal ] and ;\n\n: time ( \" ccc\" -- n : time the number of milliseconds it takes to execute a word )\n\tclock >r\n\tfind found? execute\n\tclock r> - ;\n\n( defer...is is probably not standards compliant, it is still neat! )\n: (do-defer) ( -- self : pushes the location into which it is compiled )\n\tr> dup >r 1- ;\n\n: defer immediate ( \" ccc\" -- , Run Time -- location :\n\tcreates a word that pushes a location to write an execution token into )\n\t?exec\n\t:: ['] (do-defer) , (;) ;\n\n: is ( location \" ccc\" -- : make a deferred word execute a word )\n\tfind found? swap ! ;\n\nhide (do-defer)\n\n( This RECURSE word is the standard Forth word for allowing\nfunctions to be called recursively. A word is hidden from the\ncompiler until the matching ';' is hit. This allows for previous\ndefinitions of words to be used when redefining new words, it\nalso means that words cannot be called recursively unless the\nrecurse word is used.\n\nRECURSE calls the word being defined, which means that it\ntakes up space on the return stack. Words using recursion\nshould be careful not to take up too much space on the return\nstack, and of course they should terminate after a finite\nnumber of steps.\n\nWe can test \"recurse\" with this factorial function:\n\n : factorial dup 2 < if drop 1 exit then dup 1- recurse * ;\n\n)\n: recurse immediate\n\t?comp\n\tlatest cell+ , ;\n\n: myself ( -- : myself is a synonym for recurse )\n\timmediate postpone recurse ;\n\n( The \"tail\" function implements tail calls, which is just a\njump to the beginning of the words definition, for example\nthis word will never overflow the stack and will print \"1\"\nfollowed by a new line forever,\n\n\t: forever 1 . cr tail ;\n\nWhereas\n\n\t: forever 1 . cr recurse ;\n\nor\n\n\t: forever 1 . cr forever ;\n\nWould overflow the return stack. )\n\nhide tail\n: tail ( -- : perform tail recursion in current word definition )\n\timmediate\n\t?comp\n\tlatest cell+\n\t['] branch ,\n\there - cell+ , ;\n\n( @todo better version of this )\n: factorial ( u -- u : factorial of u )\n\tdup 2 u< if drop 1 exit then dup 1- recurse * ;\n\n: permutations ( u1 u2 -- u : number of ordered combinations )\n\tover swap - factorial swap factorial swap \/ ;\n\n: combinations ( u1 u2 -- u : number of unordered combinations )\n\tdup dup permutations >r permutations r> \/\n\t;\n\n: average ( u1 u2 -- u : average of u1 and u2 ) \n\t+ 2\/ ;\n\n: gcd ( u1 u2 -- u : greatest common divisor )\n\tdup if tuck mod tail then drop ;\n\n: lcm ( u1 u2 -- u : lowest common multiple of u1 and u2 )\n\t2dup gcd \/ * ;\n\n( From: https:\/\/en.wikipedia.org\/wiki\/Integer_square_root\n\nThis function computes the integer square root of a number.\n\n@note this should be changed to the iterative algorithm so\nit takes up less space on the stack - not that is takes up\na hideous amount as it is. )\n\n: sqrt ( n -- u : integer square root )\n\tdup 0< if -11 throw then ( does not work for signed values )\n\tdup 2 < if exit then ( return 0 or 1 )\n\tdup ( u u )\n\t2 rshift recurse 2* ( u sc : 'sc' == unsigned small candidate )\n\tdup ( u sc sc )\n\t1+ dup square ( u sc lc lc^2 : 'lc' == unsigned large candidate )\n\t>r rot r> < ( sc lc bool )\n\tif drop else nip then ; ( return small or large candidate respectively )\n\n\n( ==================== Extended Word Set ===================== )\n\n( ==================== For Each Loop ========================= )\n( The foreach word set allows the user to take action over an\nentire array without setting up loops and checking bounds. It\nbehaves like the foreach loops that are popular in other\nlanguages.\n\nThe foreach word accepts a string and an execution token,\nfor each character in the string it passes the current address\nof the character that it should operate on.\n\nThe complexity of the foreach loop is due to the requirements\nplaced on it. It cannot pollute the variable stack with\nvalues it needs to operate on, and it cannot store values in\nlocal variables as a foreach loop could be called from within\nthe execution token it was passed. It therefore has to store\nall of it uses on the return stack for the duration of EXECUTE.\n\nAt the moment it only acts on strings as \"\/string\" only\nincrements the address passed to the word foreach executes\nto the next character address. )\n\n\\ (FOREACH) leaves the point at which the foreach loop\n\\ terminated on the stack, this allows programmer to determine\n\\ if the loop terminated early or not, and at which point.\n\n: (foreach) ( c-addr u xt -- c-addr u : execute xt for each cell in c-addr u\n\treturning number of items not processed )\n\tbegin\n\t\t3dup >r >r >r ( c-addr u xt R: c-addr u xt )\n\t\tnip ( c-addr xt R: c-addr u xt )\n\t\texecute ( R: c-addr u xt )\n\t\tr> r> r> ( c-addr u xt )\n\t\t-rot ( xt c-addr u )\n\t\t1 \/string ( xt c-addr u )\n\t\tdup 0= if rot drop exit then ( End of string - drop and exit! )\n\t\trot ( c-addr u xt )\n\tagain ;\n\n\\ If we do not care about returning early from the foreach\n\\ loop we can instead call FOREACH instead of (FOREACH),\n\\ it simply drops the results (FOREACH) placed on the stack.\n: foreach ( c-addr u xt -- : execute xt for each cell in c-addr u )\n\t(foreach) 2drop ;\n\n\\ RETURN is used for an early exit from within the execution\n\\ token, it leaves the point at which it exited\n: return ( -- n : return early from within a foreach loop function, returning number of items left )\n\trdrop ( pop off this words return value )\n\trdrop ( pop off the calling words return value )\n\trdrop ( pop off the xt token )\n\tr> ( save u )\n\tr> ( save c-addr )\n\trdrop ; ( pop off the foreach return value )\n\n\\ SKIP is an example of a word that uses the foreach loop\n\\ mechanism. It takes a string and a character and returns a\n\\ string that starts at the first occurrence of that character\n\\ in that string - or until it reaches the end of the string.\n\n\\ SKIP is defined in two steps, first there is a word,\n\\ (SKIP), that exits the foreach loop if there is a match,\n\\ if there is no match it does nothing. In either case it\n\\ leaves the character to skip until on the stack.\n\n: (skip) ( char c-addr -- char : exit out of foreach loop if there is a match )\n\tover swap c@ = if return then ;\n\n\\ SKIP then setups up the foreach loop, the char argument\n\\ will present on the stack when (SKIP) is executed, it must\n\\ leave a copy on the stack whatever happens, this is then\n\\ dropped at the end. (FOREACH) leaves the point at which\n\\ the loop terminated on the stack, which is what we want.\n\n: skip ( c-addr u char -- c-addr u : skip until char is found or until end of string )\n\t-rot ['] (skip) (foreach) rot drop ;\nhide (skip)\n\n( ==================== For Each Loop ========================= )\n\n( ==================== Hiding Words ========================== )\n( The two functions hide{ and }hide allow lists of words to\nbe hidden, instead of just hiding individual words. It stops\nthe dictionary from being polluted with meaningless words in\nan easy way. )\n\n: }hide ( should only be matched with 'hide{' )\n\timmediate -22 throw ;\n\n: hide{ ( -- : hide a list of words, the list is terminated with \"}hide\" )\n\t?exec\n\tbegin\n\t\tfind ( find next word )\n\t\tdup [ find }hide ] literal = if\n\t\t\tdrop exit ( terminate hide{ )\n\t\tthen\n\t\tdup 0= if -15 throw then\n\t\t(hide) drop\n\tagain ;\n\nhide (hide)\n\n( ==================== Hiding Words ========================== )\n\n( The words described here on out get more complex and will\nrequire more of an explanation as to how they work. )\n\n( ==================== Create Does> ========================== )\n\n( The following section defines a pair of words \"create\"\nand \"does>\" which are a powerful set of words that can be\nused to make words that can create other words. \"create\"\nhas both run time and compile time behavior, whilst \"does>\"\nonly works at compile time in conjunction with \"create\". These\ntwo words can be used to add constants, variables and arrays\nto the language, amongst other things.\n\nA simple version of create is as follows\n\n\t: create :: dolist , here 2 cells + , ' exit , 0 state ! ;\n\nBut this version is much more limited.\n\n\"create\"...\"does>\" is one of the constructs that makes Forth\nForth, it allows the creation of words which can define new\nwords in themselves, and thus allows us to extend the language\neasily. )\n\n: write-exit ( -- : A word that write exit into the dictionary )\n\t['] _exit , ;\n\n: write-compile, ( -- : A word that writes , into the dictionary )\n\t['] , , ;\n\n: create ( create a new work that pushes its data field )\n\t:: ( compile a word )\n\tdolit , ( write push into new word )\n\there 2 cells + , ( push a pointer to data field )\n\t(;) ; ( write exit, switch to command mode )\n\n: mark write-compile, ( Write in a place holder 0 and push a pointer to to be used by does> )\n\tdolit , write-exit write-compile, ( Write in an exit in the word we're compiling. )\n\t['] [ , ; ( Make sure to change the state back to command mode )\n\n\\ : ( hole-to-patch -- )\n\timmediate\n\t?comp\n\twrite-exit ( we don't want the defining word to exit, but the *defined* word to )\n\there swap ! ( patch in the code fields to point to )\n\tdolist , ; ( write a run in )\n\nhide{ write-compile, write-exit }hide\n\n( Now that we have create...does> we can use it to create\narrays, variables and constants, as we mentioned before. )\n\n: array ( u c\" xxx\" -- : create a named array of length u )\n\tcreate allot does> + ;\n\n: variable ( x c\" xxx\" -- : create a variable will initial value of x )\n\tcreate , does> ;\n\n\\ : constant ( x c\" xxx\" -- : create a constant with value of x )\n\\\tcreate , does> @ ;\n\n: table ( u c\" xxx\" --, Run Time: -- addr u : create a named table )\n\tcreate dup , allot does> dup @ ;\n\n: string ( u c\" xxx\" --, Run Time: -- c-addr u : create a named string )\n\tcreate dup , chars allot does> dup @ swap 1+ chars> swap ;\n\n\\ : +field \\ n <\"name\"> -- ; exec: addr -- 'addr\n\\ create over , +\n\\ does> @ + ;\n\\\n\\ : begin-structure \\ -- addr 0 ; -- size\n\\ \tcreate\n\\ \there 0 0 , \\ mark stack, lay dummy\n\\ \tdoes> @ ; \\ -- rec-len\n\\\n\\ : end-structure \\ addr n --\n\\ swap ! ; \\ set len\n\\\n\\ begin-structure point\n\\ \tpoint +field p.x\n\\ \tpoint +field p.y\n\\ end-structure\n\\\n\\ This should work...\n\\ : buffer: ( u c\" xxx\" --, Run Time: -- addr )\n\\\tcreate allot ;\n\n: 2constant\n\tcreate , , does> dup 1+ @ swap @ ;\n\n: 2variable\n\tcreate , , does> ;\n\n: enum ( x \" ccc\" -- x+1 : define a series of enumerations )\n\tdup constant 1+ ;\n\n( ==================== Create Does> ========================== )\n\n( ==================== Do ... Loop =========================== )\n\n( The following section implements Forth's do...loop\nconstructs, the word definitions are quite complex as it\ninvolves a lot of juggling of the return stack. Along with\nbegin...until do loops are one of the main looping constructs.\n\nUnlike begin...until do accepts two values a limit and a\nstarting value, they are also words only to be used within a\nword definition, some Forths extend the semantics so looping\nconstructs operate in command mode, this Forth does not do\nthat as it complicates things unnecessarily.\n\nExample:\n\n\t: example-1\n\t\t10 1 do\n\t\t\ti . i 5 > if cr leave then loop\n\t\t100 . cr ;\n\n\texample-1\n\nPrints:\n\t1 2 3 4 5 6\n\nIn \"example-1\" we can see the following:\n\n1. A limit, 10, and a start value, 1, passed to \"do\".\n2. A word called 'i', which is the current count of the loop.\n3. If the count is greater than 5, we call a word call\nLEAVE, this word exits the current loop context as well as\nthe current calling word.\n4. \"100 . cr\" is never called. This should be changed in\nfuture revision, but this version of leave exits the calling\nword as well.\n\n'i', 'j', and LEAVE *must* be used within a do...loop\nconstruct.\n\nIn order to remedy point 4. loop should not use branch but\ninstead should use a value to return to which it pushes to\nthe return stack )\n\n: (do)\n\tswap ( swap the limit and start )\n\tr> ( save our return stack to temporary variable )\n\t-rot ( limit start return -- return start limit )\n\t>r ( push limit onto return stack )\n\t>r ( push start onto return stack )\n\t>r ; ( restore our return address )\n\n: do immediate ( Run time: high low -- : begin do...loop construct )\n\t?comp\n\t['] (do) ,\n\tpostpone begin ;\n\n: (unloop) ( -- , R: i limit -- : remove limit and i from )\n\tr> ( save our return address )\n\trdrop ( pop off i )\n\trdrop ( pop off limit )\n\t>r ; ( restore our return stack )\n\n: (+loop) ( x -- bool : increment loop variable by x and test it )\n\tr@ 1- ( get the pointer to i )\n\t+! ( add value to it )\n\tr@ 1- @ ( find i again )\n\tr@ 2- @ ( find the limit value )\n\tu>= ;\n\n: (loop) ( -- bool : increment loop variable by 1 and test it )\n\tr@ 1- ( get the pointer to i )\n\t1+! ( add one to it )\n\tr@ 1- @ ( find the value again )\n\tr@ 2- @ ( find the limit value )\n\tu>= ;\n\n: loop ( -- : end do...loop construct )\n\timmediate ?comp ['] (loop) , postpone until ['] (unloop) , ;\n\n: +loop ( x -- : end do...+loop loop construct )\n\timmediate ?comp ['] (+loop) , postpone until ['] (unloop) , ;\n\n: leave ( -- , R: i limit return -- : break out of a do-loop construct )\n\t(unloop)\n\trdrop ; ( return to the caller's caller routine )\n\n: ?leave ( x -- , R: i limit return -- | i limit return : conditional leave )\n\tif\n\t\t(unloop)\n\t\trdrop ( return to the caller's caller routine )\n\tthen ;\n\n\\ @todo define '(i)', '(j)' and '(k)', then make their\n\\ wrappers, 'i', 'j' and 'k' call ?comp then compile a pointer\n\\ to the thing that implements them, likewise for leave,\n\\ loop and +loop.\n: i ( -- i : Get current, or innermost, loop index in do...loop construct )\n\tr> r> ( pop off return address and i )\n\ttuck ( tuck i away )\n\t>r >r ; ( restore return stack )\n\n: j ( -- j : Get outermost loop index in do...loop construct )\n\t4 rpick ;\n\n( This is a simple test function for the looping, for interactive\ntesting and debugging:\n : mm 5 1 do i . cr 4 1 do j . tab i . cr loop loop ; )\n\n: range ( nX nY -- nX nX+1 ... nY )\n\tnos1+ do i loop ;\n\n: repeater ( n0 X -- n0 ... nX )\n\t1 do dup loop ;\n\n: sum ( n0 ... nX X -- sum<0..X> )\n\t1 do + loop ;\n\n: mul ( n0 ... nX X -- mul<0..X> )\n\t1 do * loop ;\n\n: reverse ( x1 ... xn n -- xn ... x1 : reverse n items on the stack )\n\t0 do i roll loop ;\n\ndoer (banner)\nmake (banner) space\n\n: banner ( n -- : )\n\tdup 0<= if drop exit then\n\t0 do (banner) loop ;\n\n: zero ( -- : emit a single 0 character )\n\t[char] 0 emit ;\n\n: spaces ( n -- : print n spaces if n is greater than zero )\n\tmake (banner) space\n\tbanner ;\n\n: zeros ( n -- : print n spaces if n is greater than zero )\n\tmake (banner) zero\n\tbanner ;\n\nhide{ (banner) banner }hide\n\n( @todo check u for negative )\n: fill ( c-addr u char -- : fill in an area of memory with a character, only if u is greater than zero )\n\t-rot\n\t0 do 2dup i + c! loop\n\t2drop ;\n\n: default ( addr u n -- : fill in an area of memory with a cell )\n\t-rot\n\t0 do 2dup i cells + ! loop\n\t2drop ;\n\n: compare ( c-addr1 u1 c-addr2 u2 -- n : compare two strings, not quite compliant yet )\n\t>r swap r> min >r\n\tstart-address + swap start-address + r>\n\tmemory-compare ;\n\n: erase ( addr u : erase a block of memory )\n\t2chars> 0 fill ;\n\n: blank ( c-addr u : fills a string with spaces )\n\tbl fill ;\n\n( move should check that u is not negative )\n: move ( addr1 addr2 u -- : copy u words of memory from 'addr2' to 'addr1' )\n\t0 do\n\t\t2dup i + @ swap i + !\n\tloop\n\t2drop ;\n\n( It would be nice if move and cmove could share more code, as they do exactly\n the same thing but with different load and store functions, cmove> )\n: cmove ( c-addr1 c-addr2 u -- : copy u characters of memory from 'c-addr2' to 'c-addr1' )\n\t0 do\n\t\t2dup i + c@ swap i + c!\n\tloop\n\t2drop ;\n\n\n\n( ==================== Do ... Loop =========================== )\n\n( ==================== String Substitution =================== )\n\n: (subst) ( char1 char2 c-addr )\n\t3dup ( char1 char2 c-addr char1 char2 c-addr )\n\tc@ = if ( char1 char2 c-addr char1 )\n\t\tswap c! ( match, substitute character )\n\telse ( char1 char2 c-addr char1 )\n\t\t2drop ( no match )\n\tthen ;\n\n: subst ( c-addr u char1 char2 -- replace all char1 with char2 in string )\n\tswap\n\t2swap\n\t['] (subst) foreach 2drop ;\nhide (subst)\n\n0 variable c\n0 variable sub\n0 variable #sub\n\n: (subst-all) ( c-addr : search in sub\/#sub for a character to replace at c-addr )\n\tsub @ #sub @ bounds ( get limits )\n\tdo\n\t\tdup ( duplicate supplied c-addr )\n\t\tc@ i c@ = if ( check if match )\n\t\t\tdup\n\t\t\tc chars c@ swap c! ( write out replacement char )\n\t\tthen\n\tloop drop ;\n\n: subst-all ( c-addr1 u c-addr2 u char -- replace chars in str1 if in str2 with char )\n\tc chars c! #sub ! sub ! ( store strings away )\n\t['] (subst-all) foreach ;\n\nhide{ c sub #sub (subst-all) }hide\n\n( ==================== String Substitution =================== )\n\n0 variable column-counter\n4 variable column-width\n\n: column ( i -- )\t\n\tcolumn-width @ mod not if cr then ;\n\n: column.reset\t\t\n\t0 column-counter ! ;\n\n: auto-column\t\t\n\tcolumn-counter dup @ column 1+! ;\n\n0 variable x\n: x! ( x -- )\n\tx ! ;\n\n: x@ ( -- x )\n\tx @ ;\n\n: 2>r ( x1 x2 -- R: x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tswap\n\t\t>r\n\t\t>r\n\tx@ >r ; ( restore return address )\n\n: 2r> ( R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tr>\n\t\tr>\n\t\tswap\n\tx@ >r ; ( restore return address )\n\n: 2r@ ( -- x1 x2 , R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\tr> r>\n\t2dup\n\t>r >r\n\tswap\n\tx@ >r ; ( restore return address )\n\n: unused ( -- u : push the amount of core left )\n\tmax-core here - ;\n\n: accumulator ( initial \" ccc\" -- : make a word that increments by a value and pushes the result )\n\tcreate , does> tuck +! @ ;\n\n: counter ( n \" ccc\" --, Run Time: -- x : make a word that increments itself by one, starting from 'n' )\n\tcreate 1- , does> dup 1+! @ ;\n\n0 variable delim\n: accepter ( c-addr max delimiter -- i )\n\t( store a \"max\" number of chars at c-addr until \"delimiter\" encountered,\n\tthe number of characters stored is returned )\n\tdelim ! ( store delimiter used to stop string storage when encountered)\n\t0\n\tdo\n\t\tkey dup delim @ <>\n\t\tif\n\t\t\tover c! 1+\n\t\telse ( terminate string )\n\t\t\tdrop 0 swap c!\n\t\t\ti\n\t\t\tleave\n\t\tthen\n\tloop\n\t-18 throw ; ( read in too many chars )\nhide delim\n\n: skip ( char -- : read input until string is reached )\n\tkey drop >r 0 begin drop key dup rdup r> <> until rdrop ;\n\n: word ( c -- c-addr : parse until 'c' is encountered, push transient counted string )\n\ttib #tib 0 fill ( zero terminal input buffer so we NUL terminate string )\n\tdup skip tib 1+ c!\n\t>r\n\ttib 2+\n\t#tib 1-\n\tr> accepter 1+\n\ttib c!\n\ttib ;\nhide skip\n\n: accept ( c-addr +n1 -- +n2 : see accepter definition )\n\tnl accepter ;\n\n0xFFFF constant max-string-length\n\n: (.\") ( char -- c-addr u )\n\t( @todo This really needs simplifying, to do this\n\ta set of words that operate on a temporary buffer can\n\tbe used )\n\t( Write a string into word being currently defined, this\n\tcode has to jump over the string it has just put into the\n\tdictionary so normal execution of a word can continue. The\n\tlength and character address of the string are left on the\n\tstack )\n\t>r ( save delimiter )\n\t['] branch , ( write in jump, this will jump past the string )\n\t>mark ( make hole )\n\tdup 1+ chars> ( calculate address to write to )\n\tmax-string-length\n\tr> ( restore delimiter )\n\taccepter dup >r ( write string into dictionary, save index )\n\taligned 2dup size \/ ( stack: length hole char-len hole )\n\t1+ dup allot ( update dictionary pointer with string length )\n\t1+ swap ! ( write place to jump to )\n\tdrop ( do not need string length anymore )\n\t1+ chars> ( calculate place to print )\n\tr> ; ( restore index and address of string )\n\n: length ( c-addr u -- u : push the length of an ASCIIZ string )\n tuck 0 do dup c@ 0= if 2drop i leave then 1+ loop ;\n\n: asciiz? ( c-addr u -- : is a Forth string also a ASCIIZ string )\n\ttuck length <> ;\n\n: asciiz ( c-addr u -- : trim a string until NUL terminator )\n\t2dup length nip ;\n\n: (type) ( c-addr -- : emit a single character )\n\tc@ emit ;\n\n: type ( c-addr u -- : print out 'u' characters at c-addr )\n\t['] (type) foreach ;\nhide (type)\n\n: do-string ( char -- : write a string into the dictionary reading it until char is encountered )\n\t(.\")\n\tstate @ if swap [literal] [literal] then ;\n\n128 string sbuf\n: s\" ( \"ccc\" --, Run Time -- c-addr u )\n\tkey drop sbuf 0 fill sbuf [char] \" accepter sbuf drop swap ;\nhide sbuf\n\n( @todo these strings really need rethinking, state awareness needs to be removed... )\n: type,\n\tstate @ if ['] type , else type then ;\n\n: c\"\n\timmediate key drop [char] \" do-string ;\n\n: \"\n\timmediate key drop [char] \" do-string type, ;\n\n: sprint ( c -- : print out chars until 'c' is encountered )\n\tkey drop ( drop next space )\n\t>r ( save delimiter )\n\tbegin\n\t\tkey dup ( get next character )\n\t\trdup r> ( get delimiter )\n\t\t<> if emit 0 then\n\tuntil rdrop ;\n\n: .(\n\timmediate [char] ) sprint ;\nhide sprint\n\n: .\"\n\timmediate key drop [char] \" do-string type, ;\n\nhide type,\n\n( This word really should be removed along with any usages\nof this word, it is not a very \"Forth\" like word, it accepts\na pointer to an ASCIIZ string and prints it out, it also does\nnot checking of the returned values from write-file )\n: print ( c-addr -- : print out a string to the standard output )\n\t-1 over >r length r> swap stdout write-file 2drop ;\n\n: ok\n\t\" ok\" cr ;\n\n: empty-stack ( x-n ... x-0 -- : empty the variable stack )\n\tbegin depth while drop repeat ;\n\n: (quit) ( -- : do the work of quit, without the restart )\n\t0 `source-id ! ( set source to read from file )\n\t`stdin @ `fin ! ( read from stdin )\n\tpostpone [ ( back into command mode )\n\t['] interpret start! ; ( set interpreter starting word )\n\n: quit ( -- : Empty return stack, go back to command mode, read from stdin, interpret input )\n\t(quit)\n\t-1 restart ; ( restart the interpreter )\n\n: abort\n\t-1 throw ;\n\n: (abort\") ( do the work of abort )\n\t(quit)\n\t-2 throw ;\n\n: abort\" immediate\n\tpostpone \"\n\t['] cr , ['] (abort\") , ;\n\n\n( ==================== Error Messages ======================== )\n( This section implements a look up table for error messages,\nthe word MESSAGE was inspired by FIG-FORTH, words like ERROR\nwill be implemented later.\n\nThe DPANS standard defines a range of numbers which correspond\nto specific errors, the word MESSAGE can decode these numbers\nby looking up known words in a table.\n\nSee: http:\/\/lars.nocrew.org\/dpans\/dpans9.htm\n\n Code Reserved for\n ---- ------------\n -1 ABORT\n -2 ABORT\"\n -3 stack overflow\n -4 stack underflow\n -5 return stack overflow\n -6 return stack underflow\n -7 do-loops nested too deeply during execution\n -8 dictionary overflow\n -9 invalid memory address\n -10 division by zero\n -11 result out of range\n -12 argument type mismatch\n -13 undefined word\n -14 interpreting a compile-only word\n -15 invalid FORGET\n -16 attempt to use zero-length string as a name\n -17 pictured numeric output string overflow\n -18 parsed string overflow\n -19 definition name too long\n -20 write to a read-only location\n -21 unsupported operation [e.g., AT-XY on a\n too-dumb terminal]\n -22 control structure mismatch\n -23 address alignment exception\n -24 invalid numeric argument\n -25 return stack imbalance\n -26 loop parameters unavailable\n -27 invalid recursion\n -28 user interrupt\n -29 compiler nesting\n -30 obsolescent feature\n -31 >BODY used on non-CREATEd definition\n -32 invalid name argument [e.g., TO xxx]\n -33 block read exception\n -34 block write exception\n -35 invalid block number\n -36 invalid file position\n -37 file I\/O exception\n -38 non-existent file\n -39 unexpected end of file\n -40 invalid BASE for floating point conversion\n -41 loss of precision\n -42 floating-point divide by zero\n -43 floating-point result out of range\n -44 floating-point stack overflow\n -45 floating-point stack underflow\n -46 floating-point invalid argument\n -47 compilation word list deleted\n -48 invalid POSTPONE\n -49 search-order overflow\n -50 search-order underflow\n -51 compilation word list changed\n -52 control-flow stack overflow\n -53 exception stack overflow\n -54 floating-point underflow\n -55 floating-point unidentified fault\n -56 QUIT\n -57 exception in sending or receiving a character\n -58 [IF], [ELSE], or [THEN] exception )\n\n( The word X\" compiles a counted string into a word definition, it\nis useful as a space saving measure and simplifies our lookup table\ndefinition. Instead of having to store a C-ADDR and it's length, we\nonly have to store a C-ADDR in the lookup table, which occupies only\none element instead of two. The strings used for error messages are\nshort, so the limit of 256 characters that counted strings present\nis not a problem. )\n\n: x\" immediate ( c\" xxx\" -- c-addr : compile a counted string )\n\t[char] \" word ( read in a counted string )\n\tcount -1 \/string dup ( go back to start of string )\n\tpostpone never >r ( make a hole in the dictionary )\n\tchere >r ( character marker )\n\taligned chars allot ( allocate space in hole )\n\tr> dup >r -rot cmove ( copy string from word buffer )\n\tr> ( restore pointer to counted string )\n\tr> postpone then ; ( finish hole )\n\ncreate lookup 64 cells allot ( our lookup table )\n\n: nomsg ( -- c-addr : push counted string to undefined error message )\n\tx\" Undefined Error\" literal ;\n\nlookup 64 cells find nomsg default\n\n1 variable warning\n\n: message ( n -- : print an error message )\n\twarning @ 0= if . exit then\n\tdup -63 1 within if abs lookup + @ count type exit then\n\tdrop nomsg count type ;\n\n1 counter #msg\n\n: nmsg ( n -- : populate next slot in available in LOOKUP )\n\tlookup #msg cells + ! ;\n\nx\" ABORT\" nmsg\nx\" ABORT Double Quote\" nmsg\nx\" stack overflow\" nmsg\nx\" stack underflow\" nmsg\nx\" return stack overflow\" nmsg\nx\" return stack underflow\" nmsg\nx\" do-loops nested too deeply during execution\" nmsg\nx\" dictionary overflow\" nmsg\nx\" invalid memory address\" nmsg\nx\" division by zero\" nmsg\nx\" result out of range\" nmsg\nx\" argument type mismatch\" nmsg\nx\" undefined word\" nmsg\nx\" interpreting a compile-only word\" nmsg\nx\" invalid FORGET\" nmsg\nx\" attempt to use zero-length string as a name\" nmsg\nx\" pictured numeric output string overflow\" nmsg\nx\" parsed string overflow\" nmsg\nx\" definition name too long\" nmsg\nx\" write to a read-only location\" nmsg\nx\" unsupported operation \" nmsg\nx\" control structure mismatch\" nmsg\nx\" address alignment exception\" nmsg\nx\" invalid numeric argument\" nmsg\nx\" return stack imbalance\" nmsg\nx\" loop parameters unavailable\" nmsg\nx\" invalid recursion\" nmsg\nx\" user interrupt\" nmsg\nx\" compiler nesting\" nmsg\nx\" obsolescent feature\" nmsg\nx\" >BODY used on non-CREATEd definition\" nmsg\nx\" invalid name argument \" nmsg\nx\" block read exception\" nmsg\nx\" block write exception\" nmsg\nx\" invalid block number\" nmsg\nx\" invalid file position\" nmsg\nx\" file I\/O exception\" nmsg\nx\" non-existent file\" nmsg\nx\" unexpected end of file\" nmsg\nx\" invalid BASE for floating point conversion\" nmsg\nx\" loss of precision\" nmsg\nx\" floating-point divide by zero\" nmsg\nx\" floating-point result out of range\" nmsg\nx\" floating-point stack overflow\" nmsg\nx\" floating-point stack underflow\" nmsg\nx\" floating-point invalid argument\" nmsg\nx\" compilation word list deleted\" nmsg\nx\" invalid POSTPONE\" nmsg\nx\" search-order overflow\" nmsg\nx\" search-order underflow\" nmsg\nx\" compilation word list changed\" nmsg\nx\" control-flow stack overflow\" nmsg\nx\" exception stack overflow\" nmsg\nx\" floating-point underflow\" nmsg\nx\" floating-point unidentified fault\" nmsg\nx\" QUIT\" nmsg\nx\" exception in sending or receiving a character\" nmsg\nx\" [IF], [ELSE], or [THEN] exception\" nmsg\n\nhide{ nmsg #msg nomsg }hide\n \n\n( ==================== Error Messages ======================== )\n\n\n( ==================== CASE statements ======================= )\n( This simple set of words adds case statements to the\ninterpreter, the implementation is not particularly efficient,\nbut it works and is simple.\n\nBelow is an example of how to use the CASE statement,\nthe following word, \"example\" will read in a character and\nswitch to different statements depending on the character\ninput. There are two cases, when 'a' and 'b' are input, and\na default case which occurs when none of the statements match:\n\n\t: example\n\t\tchar\n\t\tcase\n\t\t\t[char] a of \" a was selected \" cr endof\n\t\t\t[char] b of \" b was selected \" cr endof\n\n\t\t\tdup \\ encase will drop the selector\n\t\t\t\" unknown char: \" emit cr\n\t\tendcase ;\n\n\texample a \\ prints \"a was selected\"\n\texample b \\ prints \"b was selected\"\n\texample c \\ prints \"unknown char: c\"\n\nOther examples of how to use case statements can be found\nthroughout the code.\n\nFor a simpler case statement see, Volume 2, issue 3, page 48\nof Forth Dimensions at http:\/\/www.forth.org\/fd\/contents.html )\n\n: case immediate\n\t?comp\n\t['] branch , 3 cells , ( branch over the next branch )\n\there ['] branch , ( mark: place endof branches back to with again )\n\t>mark swap ; ( mark: place endcase writes jump to with then )\n\n: over= ( x y -- [x 0] | 1 : )\n\tover = if drop 1 else 0 then ;\n\n: of\n\timmediate ?comp ['] over= , postpone if ;\n\n: endof\n\timmediate ?comp over postpone again postpone then ;\n\n: endcase\n\timmediate ?comp ['] drop , 1+ postpone then drop ;\n\n( ==================== CASE statements ======================= )\n\n( ==================== Conditional Compilation =============== )\n( The words \"[if]\", \"[else]\" and \"[then]\" implement conditional\ncompilation, they can be nested as well\n\nSee http:\/\/lars.nocrew.org\/dpans\/dpans15.htm for more\ninformation\n\nA much simpler conditional compilation method is the following\nsingle word definition:\n\n : compile-line? 0= if [ find \\\\ , ] then ;\n\nWhich will skip a line if a conditional is false, and compile\nit if true )\n\n( These words really, really need refactoring, I could use the newly defined\n \"defer\" to help out with this )\n0 variable nest ( level of [if] nesting )\n0 variable [if]-word ( populated later with \"find [if]\" )\n0 variable [else]-word ( populated later with \"find [else]\")\n: [then] immediate ;\n: reset-nest 1 nest ! ;\n: unnest? [ find [then] ] literal = if nest 1-! then ;\n: nest? [if]-word @ = if nest 1+! then ;\n: end-nest? nest @ 0= ;\n: match-[else]? [else]-word @ = nest @ 1 = and ;\n\n: [if] ( bool -- : conditional execution )\n\t?exec\n\tunless\n\t\treset-nest\n\t\tbegin\n\t\t\tfind\n\t\t\tdup nest?\n\t\t\tdup match-[else]? if drop exit then\n\t\t\t unnest?\n\t\t\tend-nest?\n\t\tuntil\n\tthen ;\n\n: [else] ( discard input until [then] encounter, nesting for [if] )\n\t?exec\n\treset-nest\n\tbegin\n\t\tfind\n\t\tdup nest? unnest?\n\t\tend-nest?\n\tuntil ;\n\nfind [if] [if]-word !\nfind [else] [else]-word !\n\n: ?( if postpone ( then ; \\ conditionally read until ')'\n: ?\\ if postpone \\ then ;\n: 16bit\\ size 2 <> if postpone \\ then ;\n: 32bit\\ size 4 <> if postpone \\ then ;\n: 64bit\\ size 8 <> if postpone \\ then ;\n\nhide{\n\t[if]-word [else]-word nest\n\treset-nest unnest? match-[else]?\n\tend-nest? nest?\n}hide\n\n( ==================== Conditional Compilation =============== )\n\n( ==================== Endian Words ========================== )\n( This words are allow the user to determinate the endianess\nof the machine that is currently being used to execute libforth,\nthey make heavy use of conditional compilation )\n\n0 variable x\n\nsize 2 = [if] 0x0123 x ! [then]\nsize 4 = [if] 0x01234567 x ! [then]\nsize 8 = [if] 0x01234567abcdef x ! [then]\n\nx chars> c@ 0x01 = constant endian\n\nhide{ x }hide\n\n: swap16 ( x -- x : swap the byte order of a 16 bit number )\n\tdup 256* 0xff00 and >r 256\/ lsb r> or ;\n\nsize 4 >= [if]\n\t: swap32\n\t\tdup 0xffff and swap16 16 lshift swap\n\t\t16 rshift 0xffff and swap16 or ;\n[then]\n\nsize 8 >= [if]\n\t: swap64 ( x -- x : swap the byte order of a 64 bit number )\n\t\t dup 0xffffffff and swap32 32 lshift swap\n\t\t 32 rshift 0xffffffff and swap32 or ;\n[then]\n\nsize 2 = [if]\n\tendian\n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order )\n\t\tswap16 ;\n\t: >big ( x -- x : host byte order to big endian order )\n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order )\n\t\t;\n\t: >big ( x -- x : host byte order to big endian order )\n\t\tswap16 ;\n\t[then]\n[then]\n\nsize 4 = [if]\n\tendian\n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order )\n\t\tswap32 ;\n\t: >big ( x -- x : host byte order to big endian order )\n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order )\n\t\t;\n\t: >big ( x -- x : host byte order to big endian order )\n\t\tswap32 ;\n\t[then]\n[then]\n\nsize 8 = [if]\n\tendian\n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order )\n\t\tswap64 ;\n\t: >big ( x -- x : host byte order to big endian order )\n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order )\n\t\t;\n\t: >big ( x -- x : host byte order to big endian order )\n\t\tswap64 ;\n\t[then]\n[then]\n\n( ==================== Endian Words ========================== )\n\n( ==================== Misc words ============================ )\n\n: (base) ( -- base : unmess up libforth's base variable )\n\tbase @ dup 0= if drop 10 then ;\n\n: #digits ( u -- u : number of characters needed to represent 'u' in current base )\n\tdup 0= if 1+ exit then\n\t(base) log 1+ ;\n\n: digits ( -- u : number of characters needed to represent largest unsigned number in current base )\n\t-1 #digits ;\n\n: cdigits ( -- u : number of characters needed to represent largest characters in current base )\n\t0xff #digits ;\n\n: .r ( u -- print a number taking up a fixed amount of space on the screen )\n\tdup #digits digits swap - spaces . ;\n\n: ?.r ( u -- : print out address, right aligned )\n\t@ .r ;\n\n0 variable counter\n\n: counted-column ( index -- : special column printing for dump )\n\tcounter @ column-width @ mod\n\tnot if cr .r \" :\" space else drop then\n\tcounter 1+! ;\n\n: .chars ( x n -- : print a cell out as characters, upto n chars )\n\t0 ( from zero to the size of a cell )\n\tdo\n\t\tdup ( copy variable to print out )\n\t\tsize i 1+ - select-byte ( select correct byte )\n\t\tdup printable? not ( is it not printable )\n\t\tif drop [char] . then ( print a '.' if it is not )\n\t\temit ( otherwise print it out )\n\tloop\n\tdrop ; ( drop cell we have printed out )\n\n: lister ( addr u addr -- )\n\t0 counter ! 1- swap\n\tdo\n\t\tdup counted-column 1+ i ?.r i @ size .chars space\n\tloop ;\n\n( @todo this function should make use of DEFER and IS, then different\nversion of dump could be made that swapped out LISTER )\n: dump ( addr u -- : dump out 'u' cells of memory starting from 'addr' )\n\t1+ over + under lister drop\n\tcr ;\n\nhide{ counted-column counter }hide\n\n( Fence can be used to prevent any word defined before it from being forgotten\nUsage:\n\there fence ! )\n0 variable fence\n\n: ?fence ( addr -- : throw an exception of address is before fence )\n\tfence @ u< if -15 throw then ;\n\n: (forget) ( pwd-token -- : forget a found word and everything after it )\n\tdup 0= if -15 throw then ( word not found! )\n\tdup ?fence\n\tdup @ pwd ! h ! ;\n\n: forget ( c\" xxx\" -- : forget word and every word defined after it )\n\tfind 1- (forget) ;\n\n0 variable fp ( FIND Pointer )\n\n: rendezvous ( -- : set up a rendezvous point )\n\there ?fence\n\there fence !\n\tlatest fp ! ;\n\n: retreat ( -- : retreat to the rendezvous point, forgetting any words )\n\tfence @ h !\n\tfp @ pwd ! ;\n\nhide{ fp }hide\n\n: marker ( c\" xxx\" -- : make word the forgets itself and words after it)\n\t:: latest [literal] ['] (forget) , (;) ;\nhere fence ! ( This should also be done at the end of the file )\nhide (forget)\n\n: ** ( b e -- x : exponent, raise 'b' to the power of 'e')\n\t?dup-if\n\t\tover swap\n\t\t1 do over * loop\n\t\tnip\n\telse\n\t\tdrop 1\n\tthen ;\n\n0 variable a\n0 variable b\n0 variable m\n: equal ( a1...an b1...bn n -- a1...an b1...bn bool : determine if two lists are equal )\n\t( example:\n\t\t1 2 3\n\t\t1 2 3\n\t\t3 equal\n\treturns: 1 )\n\tdup m ! 1+ 1 ( store copy of length and use as loop index )\n\tdo\n\t\ti 1- pick b ! ( store ith element of list in b1...bn )\n\t\ti m @ + 1- pick a ! ( store ith element of list in a1...an )\n\t\ta @ b @ <> ( compare a and b for equality )\n\t\tif 0 leave then ( unequal, finish early )\n\tloop 1 ; ( lists must be equal )\n\nhide{ a b m }hide\n\n: ndrop ( u1...un n -- : drop n items )\n\t?dup-if 0 do drop loop then ;\n\n: caesar ( c key -- o : encode a alphabetic character with a key using a generalization of the Caesar cipher )\n\t>r\n\tdup uppercase? if [char] A - r> + 26 mod [char] A + exit then\n\tdup lowercase? if [char] a - r> + 26 mod [char] a + exit then\n\trdrop ; ( it goes without saying that this should not be used for anything serious! )\n\n: caesar-type ( c-addr u key : type out encoded text with a Caesar cipher )\n\t-rot bounds do i c@ over caesar emit loop drop ;\n\n: rot13 ( c -- c : encode a character with ROT-13 )\n\t13 caesar ;\n\n: rot13-type ( c-addr u : print string in ROT-13 encoded form )\n\t13 caesar-type ;\n\n\\ s\" abcdefghijklmnopqrstuvwxyz\" rot13-type -> nopqrstuvwxyzabcdefghijklm\n\\ s\" hello\" rot13-type -> uryyb\n\n( ==================== Misc words ============================ )\n\n( ==================== Pictured Numeric Output =============== )\n( Pictured numeric output is what Forths use to display\nnumbers to the screen, this Forth has number output methods\nbuilt into the Forth kernel and mostly uses them instead,\nbut the mechanism is still useful so it has been added.\n\n@todo Pictured number output should act on a double cell\nnumber not a single cell number )\n\n0 variable hld\n\n: overflow ( -- : check if we overflow the hold area )\n \there chars> pad chars> hld @ - u> if -17 throw then ;\n\n: hold ( char -- : add a character to the numeric output string )\n\toverflow pad chars> hld @ - c! hld 1+! ;\n\n: holds ( c-addr u -- : hold an entire string )\n begin dup while 1- 2dup + c@ hold repeat 2drop ;\n\n: <# ( -- : setup pictured numeric output )\n\t0 hld ! ;\n\n: sign ( -- : add a sign to the pictured numeric output string )\n\t[char] - hold ;\n\n: # ( x -- x : divide x by base, turn into a character, put in pictured output string )\n\t(base) um\/mod swap\n \tdup 9 u>\n \tif 7 + then\n \t48 + hold ;\n\n: #s ( x -- 0 : repeatedly call # on x until x is zero )\n\tbegin # dup 0= until ;\n\n: #> ( -- c-addr u : end pictured output conversion, push output string to stack )\n\t0 hold ( NUL terminate string, just in case )\n\thld 1-! ( but do not include that in the count )\n\tpad chars> hld @\n\ttuck - 1+ swap ;\n\ndoer characters\nmake characters spaces\n\n: u.rc\n\t>r <# #s #> rot drop r> over - characters type ;\n\n: u.r ( u n -- print a number taking up a fixed amount of space on the screen )\n\tmake characters spaces u.rc ;\n\n: u.rz ( u n -- print a number taking up a fixed amount of space on the screen, using leading zeros )\n\tmake characters zeros u.rc ;\n\n: u. ( u -- : display an unsigned number in current base )\n\t0 u.r ;\n\nhide{ overflow u.rc characters }hide\n\n( ==================== Pictured Numeric Output =============== )\n\n( ==================== Numeric Input ========================= )\n( The Forth executable can handle numeric input and does not\nneed the routines defined here, however the user might want\nto write routines that use >NUMBER. >NUMBER is a generic word,\nbut it is a bit difficult to use on its own. )\n\n: map ( char -- n|-1 : convert character in 0-9 a-z range to number )\n\tdup lowercase? if [char] a - 10 + exit then\n\tdup decimal? if [char] 0 - exit then\n\tdrop -1 ;\n\n: number? ( char -- bool : is a character a number in the current base )\n\t>lower map (base) u< ;\n\n: >number ( n c-addr u -- n c-addr u : convert string )\n\tbegin\n\t\t( get next character )\n\t\t2dup >r >r drop c@ dup number? ( n char bool, R: c-addr u )\n\t\tif ( n char )\n\t\t\tswap (base) * swap map + ( accumulate number )\n\t\telse ( n char )\n\t\t\tdrop\n\t\t\tr> r> ( restore string )\n\t\t\texit\n\t\tthen\n\t\tr> r> ( restore string )\n\t\t1 \/string dup 0= ( advance string and test for end )\n\tuntil ;\n\nhide{ map }hide\n\n( ==================== Numeric Input ========================= )\n\n( ==================== ANSI Escape Codes ===================== )\n( Terminal colorization module, via ANSI Escape Codes\n\nsee: https:\/\/en.wikipedia.org\/wiki\/ANSI_escape_code\nThese codes will provide a relatively portable means of\nmanipulating a terminal )\n\n27 constant 'escape'\n: CSI 'escape' emit .\" [\" ;\n0 constant black\n1 constant red\n2 constant green\n3 constant yellow\n4 constant blue\n5 constant magenta\n6 constant cyan\n7 constant white\n: foreground 30 + ;\n: background 40 + ;\n0 constant dark\n1 constant bright\nfalse variable colorize\n\n: 10u. ( n -- : print a number in decimal )\n\tbase @ >r decimal u. r> base ! ;\n\n: color ( brightness color-code -- : set the terminal color )\n\t( set color on an ANSI compliant terminal,\n\tfor example:\n\t\tbright red foreground color\n\tsets the foreground text to bright red )\n\tcolorize @ 0= if 2drop exit then\n\tCSI 10u. if .\" ;1\" then .\" m\" ;\n\n: at-xy ( x y -- : set ANSI terminal cursor position to x y )\n\tCSI 10u. [char] ; emit 10u. .\" H\" ;\n\n: page ( -- : clear ANSI terminal screen and move cursor to beginning )\n\tCSI .\" 2J\" 1 1 at-xy ;\n\n: hide-cursor ( -- : hide the cursor from view )\n\tCSI .\" ?25l\" ;\n\n: show-cursor ( -- : show the cursor )\n\tCSI .\" ?25h\" ;\n\n: save-cursor ( -- : save cursor position )\n\tCSI .\" s\" ;\n\n: restore-cursor ( -- : restore saved cursor position )\n\tCSI .\" u\" ;\n\n: reset-color ( -- : reset terminal color to its default value)\n\tcolorize @ 0= if exit then\n\tCSI .\" 0m\" ;\n\nhide{ CSI 10u. }hide\n( ==================== ANSI Escape Codes ===================== )\n\n( ==================== Unit test framework =================== )\n\n256 string estring ( string to test )\n0 variable #estring ( actual string length )\n0 variable start ( starting depth )\n0 variable result ( result depth )\n0 variable check ( only check depth if -> is called )\n0 variable dictionary ( dictionary pointer on entering { )\n0 variable previous ( PWD register on entering { )\n\n: T ; ( hack until T{ can process words )\n\n: -> ( -- : save depth in variable )\n\t1 check ! depth result ! ;\n\n: test estring drop #estring @ ;\n\n: fail ( -- : invalidate the forth interpreter and exit )\n\tinvalidate bye ;\n\n: neutral ( -- : neutral color )\n\t;\n\n: bad ( -- : bad color )\n\tdark red foreground color ;\n\n: good ( -- : good color )\n\tdark green foreground color ;\n\n: die bad test type reset-color cr fail ;\n\n: evaluate? ( bool -- : test if evaluation has failed )\n\tif .\" evaluation failed\" cr fail then ;\n\n: failed bad .\" failed\" reset-color cr ;\n\n: adjust ( x -- x : adjust a depth to take into account starting depth )\n\tstart @ - ;\n\n: no-check? ( -- bool : if true we need to check the depth )\n\tcheck @ 0= ;\n\n: depth? ( -- : check if depth is correct )\n\tno-check? if exit then\n\tdepth adjust ( get depth and adjust for starting depth )\n\tresult @ adjust 2* = ( get results depth, same adjustment, should be\n\t half size of the depth )\n\tif exit then ( pass )\n\tfailed\n\t.\" Unequal depths:\" cr\n\t.\" depth: \" depth . cr\n\t.\" result: \" result @ . cr\n\tdie ;\n\n: equal? ( -- : determine if results equals expected )\n\tno-check? if exit then\n\tresult @ adjust equal\n\tif exit then\n\tfailed\n\t.\" Result is not equal to expected values. \" cr\n\t.\" Stack: \" cr .s cr\n\tdie ;\n\n: display ( c-addr u -- : print out testing message in estring )\n\tverbose if neutral type else 2drop then ;\n\n: pass ( -- : print out passing message )\n\tverbose if good .\" ok \" cr reset-color then ;\n\n: save ( -- : save current dictionary )\n\tpwd @ previous !\n\there dictionary ! ;\n\n: restore ( -- : restore dictionary )\n\tprevious @ pwd !\n\tdictionary @ h ! ;\n\n: T{ ( -- : perform a unit test )\n\tdepth start ! ( save start of stack depth )\n\t0 result ! ( reset result variable )\n\t0 check ! ( reset check variable )\n\testring 0 fill ( zero input string )\n\tsave ( save dictionary state )\n\tkey drop ( drop next character, which is a space )\n\testring [char] } accepter #estring ! ( read in string to test )\n\ttest display ( print which string we are testing )\n\ttest evaluate ( perform test )\n\tevaluate? ( evaluate successfully? )\n\tdepth? ( correct depth )\n\tequal? ( results equal to expected values? )\n\tpass ( print pass message )\n\trestore ( restore dictionary to previous state )\n\tno-check? if exit then\n\tresult @ adjust 2* ndrop ( remove items on stack generated by test )\n\t; \n\nT{ }T \nT{ -> }T\nT{ 1 -> 1 }T\nT{ 1 2 -> 1 2 }T\nT{ : c 1 2 ; c -> 1 2 }T\n\n( @bug ';' smudges the previous word, but :noname does\nnot. )\nT{ :noname 2 ; :noname 3 + ; compose execute -> 5 }T\n\nhide{\n\tpass test display\n\tadjust start save restore dictionary previous\n\tevaluate? equal? depth? estring #estring result\n\tcheck no-check? die neutral bad good failed\n}hide\n\n( ==================== Unit test framework =================== )\n\n\n( ==================== Pseudo Random Numbers ================= )\n( This section implements a Pseudo Random Number generator, it\nuses the xor-shift algorithm to do so.\nSee:\nhttps:\/\/en.wikipedia.org\/wiki\/Xorshift\nhttp:\/\/excamera.com\/sphinx\/article-xorshift.html\nhttp:\/\/xoroshiro.di.unimi.it\/\nhttp:\/\/www.arklyffe.com\/main\/2010\/08\/29\/xorshift-pseudorandom-number-generator\/\n\nThe constants used have been collected from various places\non the web and are specific to the size of a cell. )\n\nsize 2 = [if] 13 constant a 9 constant b 7 constant c [then]\nsize 4 = [if] 13 constant a 17 constant b 5 constant c [then]\nsize 8 = [if] 12 constant a 25 constant b 27 constant c [then]\n\n7 variable seed ( must not be zero )\n\n: seed! ( x -- : set the value of the PRNG seed )\n\tdup 0= if drop 7 ( zero not allowed ) then seed ! ;\n\n: random ( -- x : assumes word size is 32 bit )\n\tseed @\n\tdup a lshift xor\n\tdup b rshift xor\n\tdup c lshift xor\n\tdup seed! ;\n\nhide{ a b c seed }hide\n\n( ==================== Random Numbers ======================== )\n\n( ==================== Prime Numbers ========================= )\n( From original \"third\" code from the IOCCC at\nhttp:\/\/www.ioccc.org\/1992\/buzzard.2.design, the module works\nout and prints prime numbers. )\n\n: prime? ( u -- u | 0 : return number if it is prime, zero otherwise )\n\tdup 1 = if 1- exit then\n\tdup 2 = if exit then\n\tdup 2\/ 2 ( loop from 2 to n\/2 )\n\tdo\n\t\tdup ( value to check if prime )\n\t\ti mod ( mod by divisor )\n\t\tnot if\n\t\t\tdrop 0 leave\n\t\tthen\n\tloop ;\n\n0 variable counter\n\n: primes ( x1 x2 -- : print the primes from x2 to x1 )\n\t0 counter !\n\t\" The primes from \" dup . \" to \" over . \" are: \"\n\tcr\n\tcolumn.reset\n\tdo\n\t\ti prime?\n\t\tif\n\t\t\ti . counter @ column counter 1+!\n\t\tthen\n\tloop\n\tcr\n\t\" There are \" counter @ . \" primes.\"\n\tcr ;\n\nhide{ counter }hide\n( ==================== Prime Numbers ========================= )\n\n( ==================== Debugging info ======================== )\n( This section implements various debugging utilities that the\nprogrammer can use to inspect the environment and debug Forth\nwords. )\n\n( String handling should really be done with PARSE, and CMOVE )\n: sh ( cnl -- ior : execute a line as a system command )\n\tnl word count system ;\n\nhide{ .s }hide\n: .s ( -- : print out the stack for debugging )\n\t[char] < emit depth (.) drop [char] > emit space\n\tdepth if\n\t\tdepth 0 do i column tab depth i 1+ - pick . loop\n\tthen\n\tcr ;\n\n1 variable hide-words ( do we want to hide hidden words or not )\n\n: name ( PWD -- c-addr : given a pointer to the PWD field of a word get a pointer to the name of the word )\n\tdup 1+ @ 256\/ word-mask and lsb - chars> ;\n\n( This function prints out all of the defined words, excluding\nhidden words. An understanding of the layout of a Forth word\nhelps here. The dictionary contains a linked list of words,\neach forth word has a pointer to the previous word until the\nfirst word. The layout of a Forth word looks like this:\n\nNAME: Forth Word - A variable length ASCII NUL terminated\n string.\nPWD: Previous Word Pointer, points to the previous\n word.\nCODE: Flags, code word and offset from previous word\n pointer to start of Forth word string.\nDATA: The body of the forth word definition, not interested\n in this.\n\nThere is a register which stores the latest defined word which\ncan be accessed with the code \"pwd @\". In order to print out\na word we need to access a words CODE field, the offset to\nthe NAME is stored here in bits 8 to 14 and the offset is\ncalculated from the PWD field.\n\n\"print\" expects a character address, so we need to multiply\nany calculated address by the word size in bytes. )\n\n: words.immediate ( bool -- : emit or mark a word being printed as being immediate )\n\tnot if dark red foreground color then ;\n\n: words.defined ( bool -- : emit or mark a word being printed as being a built in word )\n\tnot if bright green background color then ;\n\n: words.hidden ( bool -- : emit or mark a word being printed as being a hidden word )\n\tif dark magenta foreground color then ;\n\n: words ( -- : print out all defined an visible words )\n\tlatest\n\tspace\n\tbegin\n\t\tdup\n\t\thidden? hide-words @ and\n\t\tnot if\n\t\t\thidden? words.hidden\n\t\t\tcompiling? words.immediate\n\t\t\tdup defined-word? words.defined\n\t\t\tname\n\t\t\tprint space\n\t\t\treset-color\n\t\telse\n\t\t\tdrop\n\t\tthen\n\t\t@ ( Get pointer to previous word )\n\t\tdup dictionary-start u< ( stop if pwd no longer points to a word )\n\tuntil\n\tdrop cr ;\n\n( Simpler version of words\n: words\n\tpwd @\n\tbegin\n\t\tdup name print space @ dup dictionary-start u<\n\tuntil drop cr ; )\n\nhide{ words.immediate words.defined words.hidden hidden? hidden-bit }hide\n\n: TrueFalse ( bool -- : print true or false )\n\tif \" true\" else \" false\" then ;\n\n: registers ( -- : print out important registers and information about the virtual machine )\n\t\" return stack pointer: \" r@ . cr\n\t\" dictionary pointer \" here . cr\n\t\" previous word: \" pwd ? cr\n\t\" state: \" state ? cr\n\t\" base: \" base ? cr\n\t\" depth: \" depth . cr\n\t\" cell size (in bytes): \" size . cr\n\t\" last cell address: \" max-core . cr\n\t\" unused cells: \" unused . cr\n\t\" invalid: \" `invalid @ TrueFalse cr\n\t\" size of variable stack: \" `stack-size ? cr\n\t\" size of return stack: \" `stack-size ? cr\n\t\" start of variable stack: \" max-core `stack-size @ 2* - . cr\n\t\" start of return stack: \" max-core `stack-size @ - . cr\n\t\" current input source: \" source-id -1 = if \" string\" else \" file\" then cr\n\t\" tracing on: \" `debug @ TrueFalse cr\n\t\" starting word: \" `instruction ? cr\n\t\" real start address: \" `start-address ? cr\n\t\" error handling: \" `error-handler ? cr\n\t\" throw handler: \" `handler ? cr\n\t\" signal recieved: \" `signal ? cr ;\n\t\n( `sin `sidx `slen `fout\n `stdout `stderr `argc `argv )\n\n\n: y\/n? ( -- bool : ask a yes or no question )\n\tkey drop\n\t\" y\/n? \"\n\tbegin\n\t\tkey\n\t\tdup\n\t\t[char] y = if true exit then\n\t\t[char] n = if false exit then\n\t\t\" y\/n? \"\n\tagain ;\n\n: step\n\t( step through a word: this word could be augmented\n\twith commands such as \"dump\", \"halt\", and optional\n\t\".s\" and \"registers\" )\n\tregisters\n\t\" .s: \" .s cr\n\t\" -- press any key to continue -- \"\n\tkey drop ;\n\n: more ( -- : wait for more input )\n\t\" -- press any key to continue -- \" key drop cr page ;\n\n: debug-help ( -- : print out the help for the debug command )\n \" debug mode commands\n\th - print help\n\tq - exit interpreter word\n\tr - print registers\n\ts - print stack\n\tR - print return stack\n\tc - continue on with execution\n\" ;\n\ndoer debug-prompt\n: prompt-default\n\t.\" debug> \" ;\n\nmake debug-prompt prompt-default\n\n: debug ( -- : enter interactive debug prompt )\n\tcr\n\t\" Entered Debug Prompt. Type 'h' for help. \" cr\n\tbegin\n\t\tkey\n\t\tcase\n\t\t\tnl of debug-prompt endof\n\t\t\t[char] h of debug-help endof\n\t\t\t[char] q of bye endof\n\t\t\t[char] r of registers endof\n\t\t\t[char] s of .s endof\n\t\t\t[char] R of r.s endof\n\t\t\t[char] c of exit endof\n\t\t\t( @todo add throw here )\n\t\tendcase\n\tagain ;\nhide debug-prompt\n\n: code>pwd ( CODE -- PWD\/0 : calculate PWD from code address )\n\tdup dictionary-start here within not if drop 0 exit then\n\t1 cells - ;\n\n: word-printer ( CODE -- : print out a words name given its code field )\n\tdup 1 cells - @ -1 = if . \" noname\" exit then ( nonames are marked by a -1 before its code field )\n\tdup code>pwd ?dup-if .d name print else drop \" data\" then\n\t drop ;\n\nhide{ code>pwd }hide\n\n( these words push the execution tokens for various special\ncases for decompilation )\n: get-branch [ find branch ] literal ;\n: get-?branch [ find ?branch ] literal ;\n: get-original-exit [ find _exit ] literal ;\n: get-quote [ find ' ] literal ;\n\n( @todo replace 2- nos1+ nos1+ with appropriate word, like\nthe string word that increments a string by an amount, but\nthat operates on CELLS )\n: branch-increment ( addr branch -- increment : calculate decompile increment for \"branch\" )\n\t1+ dup negative?\n\tif\n\t\tover cr . [char] : emit space . cr 2\n\telse\n\t\t2dup 2- nos1+ nos1+ dump\n\tthen ;\n\n( these words take a code field to a primitive they implement,\ndecompile it and any data belonging to that operation, and push\na number to increment the decompilers code stream pointer by )\n\n: decompile-literal ( code -- increment )\n\t1+ ? \" literal\" 2 ;\n\n: decompile-branch ( code -- increment )\n\tdark red foreground color\n\t1+ ? \" branch \" dup 1+ @ branch-increment ;\n\n: decompile-quote ( code -- increment )\n\tdark green foreground color\n\tdup\n\t[char] ' emit 1+ @ word-printer 2 reset-color ;\n\n: decompile-?branch ( code -- increment )\n\t1+ ? \" ?branch\" 2 ;\n\n: decompile-exit ( code -- 0 )\n\t\" _exit\" cr \" End of word: \" . 0 ;\n\n( The decompile word expects a pointer to the code field of\na word, it decompiles a words code field, it needs a lot of\nwork however. There are several complications to implementing\nthis decompile function.\n\n\t'\t The next cell should be pushed\n\n\t:noname This has a marker before its code field of\n\t -1 which cannot occur normally, this is\n\t handled in word-printer\n\n\tbranch\t branches are used to skip over data, but\n\t also for some branch constructs, any data\n\t in between can only be printed out\n\t generally speaking\n\n\texit\t There are two definitions of exit, the one\n\t used in ';' and the one everything else uses,\n\t this is used to determine the actual end\n\t of the word\n\n\tliterals Literals can be distinguished by their\n\t low value, which cannot possibly be a word\n\t with a name, the next field is the\n\t actual literal\n\nOf special difficult is processing IF, THEN and ELSE\nstatements, this will require keeping track of '?branch'.\n\nAlso of note, a number greater than \"here\" must be data )\n\n: decompile ( code-pointer -- code-pointer increment|0 : )\n\t.d [char] : emit space dup @\n\tcase\n\t\tdolit of dup decompile-literal cr endof\n\t\tget-branch of dup decompile-branch endof\n\t\tget-quote of dup decompile-quote cr endof\n\t\tget-?branch of dup decompile-?branch cr endof\n\t\tget-original-exit of dup decompile-exit endof\n\t\tdup word-printer 1 swap cr\n\tendcase reset-color ;\n\n: decompiler ( code-field-ptr -- : decompile a word in its entirety )\n\tbegin decompile over + tuck = until drop ;\n\nhide{\n\tword-printer get-branch get-?branch get-original-exit\n\tget-quote branch-increment decompile-literal\n\tdecompile-branch decompile-?branch decompile-quote\n\tdecompile-exit\n}hide\n\n( these words expect a pointer to the PWD field of a word )\n: see.name \" name: \" name print cr ;\n: see.start \" word start: \" name chars . cr ;\n: see.previous \" previous word: \" @ . cr ;\n: see.immediate \" immediate: \" compiling? nip not TrueFalse cr ;\n: see.instruction \" instruction: \" xt-instruction . cr ;\n: see.defined \" defined: \" defined-word? TrueFalse cr ;\n\n: see.header ( PWD -- is-immediate-word? )\n\tdup see.name\n\tdup see.start\n\tdup see.previous\n\tdup see.immediate\n\tdup see.instruction ( @todo look up instruction name )\n\tsee.defined ;\n\n( @todo This does not work for all words, so needs fixing.\n Specifically:\n\n\t2variable\n\t2constant\n\ttable\n\tconstant\n\tvariable\n\tarray\nWhich are all complex CREATE words\n\nA good way to test decompilation is with the following\nUnix pipe:\n\n\t.\/forth -f forth.fth -e words\n\t\t| sed 's\/ \/ see \/g'\n\t\t| .\/forth -t forth.fth &> decompiled.log\n)\n\n( @todo refactor into word that takes a PWD pointer and one that attempts to parse\/find name )\n: see ( c\" xxx\" -- : decompile a word )\n\tfind\n\tdup 0= if -32 throw then\n\tcell- ( move to PWD field )\n\tdup see.header\n\tdup defined-word?\n\tif ( decompile if a compiled word )\n\t\t2 cells + ( move to code field )\n\t\t\" code field:\" cr\n\t\tdecompiler\n\telse ( the instruction describes the word if it is not a compiled word )\n\t\tdup 1 cells + @ instruction-mask and doconst = if ( special case for constants )\n\t\t\t\" constant: \" 2 cells + @ .\n\t\telse\n\t\t\tdrop\n\t\tthen\n\tthen cr ;\n\n( @todo This has a bug, if any data within a word happens\nto match the address of _exit word.end calculates the wrong\naddress, this needs to mirror the DECOMPILE word )\n: word.end ( addr -- addr : find the end of a word )\n\tbegin\n\t\tdup\n\t\t@ [ find _exit ] literal = if exit then\n\t\tcell+\n\tagain ;\n\n: (inline) ( xt -- : inline an word from its execution token )\n\tdup cell- defined-word? if\n\t\tcell+\n\t\tdup word.end over - here -rot dup allot move\n\telse\n\t\t,\n\tthen ;\n\n: ;inline ( -- : terminate :inline )\n\timmediate -22 throw ;\n\n: :inline immediate\n\t?comp\n\tbegin\n\t\tfind found?\n\t\tdup [ find ;inline ] literal = if\n\t\t\tdrop exit ( terminate :inline )\n\t\tthen\n\t\t(inline)\n\tagain ;\n\nhide{\n\tsee.header see.name see.start see.previous see.immediate\n\tsee.instruction defined-word? see.defined _exit found?\n\t(inline) word.end\n}hide\n\n( These help messages could be moved to blocks, the blocks\ncould then be loaded from disk and printed instead of defining\nthe help here, this would allow much larger help )\n\n: help ( -- : print out a short help message )\n\tpage\n\tkey drop\n\" Welcome to Forth, an imperative stack based language. It is\nboth a low level and a high level language, with a very small\nmemory footprint. Most of Forth is defined as a combination\nof various primitives.\n\nA short description of the available function (or Forth words)\nfollows, words marked (1) are immediate and cannot be used in\ncommand mode, words marked with (2) define new words. Words\nmarked with (3) have both command and compile functionality.\n\n\"\nmore \" Some of the built in words that accessible are:\n\n(1,2)\t: define a new word, switching to compile mode\n\timmediate make latest defined word immediate\n\tread read in a word, execute in command mode else compile\n\t@ ! fetch, store\n\tc@ c! character based fetch and store\n\t- + * \/ standard arithmetic operations,\n\tand or xor invert standard bitwise operations\n\tlshift rshift left and right bit shift\n\tu< u> < > = comparison predicates\n\texit exit from a word\n\temit print character from top of stack\n\tkey get a character from input\n\tr> >r pop a value from or to the return stack\n\tfind find a word in the dictionary and push the location\n\t' store the address of the following word on the stack\n\t, write the top of the stack to the dictionary\n\tswap swap first two values on the stack\n\tdup duplicate the top of the stack\n\tdrop pop and drop a value\n\tover copy the second stack value over the first\n\t. pop the top of the stack and print it\n\"\nmore \"\n\tprint print a NUL terminated string at a character address\n\tdepth get the current stack depth\n\tclock get the time since execution start in milliseconds\n\tevaluate evaluate a string\n\tsystem execute a system command\n\tclose-file close a file handle\n\topen-file open a file handle\n\tdelete-file delete a file off disk given a string\n\tread-file read in characters from a file\n\twrite-file write characters to a file\n\tfile-position get the file offset\n\treposition-file reposition the file pointer\n\tflush-file flush a file to disk\n\trename-file rename a file on disk\n \"\n\nmore \" All of the other words in the interpreter are built\nfrom these primitive words. A few examples:\n\n(1)\tif...else...then FORTH branching construct\n(1)\tbegin...until loop until top of stack is non zero\n(1)\tbegin...again infinite loop\n(1)\tdo...loop FORTH looping construct\n(2,3)\tcreate create a new word that pushes its location\n(1)\tdoes> declare a created words run time behaviour\n(1,2)\tvariable declare variable with initial value from top of stack\n(1,2)\tconstant declare a constant, taken from top of stack\n(1,2)\tarray declare an array with size taken from top of stack\n(1)\t; terminate a word definition and return to command mode\n\twords print out a list of all the defined words\n\thelp this help message\n\tdump print out memory contents starting at an address\n\tregisters print out the contents of the registers\n\tsee decompile a word, viewing what words compose it\n\t.s print out the contents of the stack\n\n\"\n\nmore \" Some more advanced words:\n\n\there push the dictionary pointer\n\th push the address of the dictionary pointer\n\tr push the return stack pointer\n\tallot allocate space in the dictionary\n(1)\t[ switch to command mode\n\t] switch to compile mode\n\t:: compile ':' into the dictionary\n\n\" more \"\nFor more information either consult the manual pages forth(1)\nand libforth(1) or consult the following sources:\n\n\thttps:\/\/github.com\/howerj\/libforth\n\thttp:\/\/work.anapnea.net\/html\/html\/projects.html\n\nAnd for a larger tutorial:\n\n\thttps:\/\/github.com\/howerj\/libforth\/blob\/master\/readme.md\n\nFor resources on Forth:\n\n\thttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\thttps:\/\/rwmj.wordpress.com\/2010\/08\/07\/jonesforth-git-repository\/\n\n -- end --\n\" cr\n;\n\n( ==================== Debugging info ======================== )\n\n( ==================== Files ================================= )\n( These words implement more of the standard file access words\nin terms of the ones provided by the virtual machine. These\nwords are not the most easy to use words, although the ones\ndefined here and the ones that are part of the interpreter are\nthe standard ones.\n\nSome thoughts:\n\nI believe extensions to this word set, once I have figured\nout the semantics, should be made to make them easier to use,\nones which automatically clean up after failure and call throw\nwould be more useful [and safer] when dealing with a single\ninput or output stream. The most common action after calling\none of the file access words is to call throw any way.\n\nFor example, a word like:\n\n\t: #write-file \\ c-addr u fileid -- fileid u\n\t\tdup >r\n\t\twrite-file dup if r> close-file throw throw then\n\t\tr> swap ;\n\nWould be easier to deal with, it preserves the file identifier\nand throws if there is any problem. It would be a bit more\ndifficult to use when there are two files open at a time.\n\n@todo implement the other file access methods in terms of the\nbuilt in ones.\n@todo read-line and write-line need their flag and ior setting\ncorrectly\n\n\tFILE-SIZE [ use file-positions ]\n\nAlso of note, Source ID needs extending.\n\nSee: [http:\/\/forth.sourceforge.net\/std\/dpans\/dpans11.htm] )\n\n: read-char ( c-addr fileid -- ior : read a char )\n\t1 swap read-file 0<> swap 1 <> or ;\n\n0 variable x\n\n: getchar ( fileid -- char ior )\n\tx chars> swap read-char x chars> c@ swap ;\n\n: write-char ( c-addr fileid -- ior : write a char )\n\t1 swap write-file 0<> swap 1 <> or ;\n\n: putchar ( char fileid -- ior )\n\tswap x chars> c! x chars> swap write-char ;\n\n\\ @todo This shouldn't affect the file position indicator.\n\\ @todo This doesn't return a sensible error indicator.\n\\ : file-size ( fileid -- ud ior )\n\\\t0 swap\n\\\tbegin dup getchar nip 0= while nos1+ repeat drop ;\n\n\nhide{ x }hide\n\n: rewind-file ( file-id -- : rewind a file to the beginning )\n\t0 reposition-file throw ;\n\n: read-line ( c-addr u1 fileid -- u2 flag ior : read in a line of text )\n\t-rot bounds\n\tdo\n\t\tdup i swap read-char drop\n\t\ti c@ nl = if drop i 0 0 leave then\n\tloop drop ;\n\n: write-line ( c-addr u fileid -- u2 flag ior : write a line of text )\n\t-rot bounds\n\tdo\n\t\tdup i swap write-char drop\n\t\ti c@ nl = if drop i 0 0 leave then\n\tloop ;\n\n: resize-file ( ud fileid -- ior : attempt to resize a file )\n\t( There is no portable way to truncate a file :C )\n\t2drop -1 ( -1 to indicate failure ) ;\n\n: create-file ( c-addr u fam -- fileid ior )\n\t>r 2dup w\/o open-file throw close-file throw\n\tr> open-file ;\n\n: include-file ( file-id -- : evaluate a file )\n\tdup >r 0 1 evaluator r> close-file throw throw ;\n\n: included ( c-addr u -- : attempt to open up a name file and evaluate it )\n\tr\/o open-file throw\n\tinclude-file ;\n\n: include ( c\" ccc\" -- : attempt to evaluate a named file )\n\t( @bug requires trailing space, should use parse-name )\n\tbl word count included ;\n\n: bin ( fam1 -- fam2 : modify a file access method to be binary not line oriented )\n\t( Do nothing, all file access methods are binary )\n\t;\n\n( ==================== Files ================================= )\n\n( ==================== Matcher =============================== )\n( The following section implements a very simple regular\nexpression engine, which expects an ASCIIZ Forth string. It\nis translated from C code and performs an identical function.\n\nThe regular expression language is as follows:\n\n\tc\tmatch a literal character\n\t.\tmatch any character\n\t*\tmatch any characters\n\nThe \"*\" operator performs the same function as \".*\" does in\nmost other regular expression engines. Most other regular\nexpression engines also do not anchor their selections to the\nbeginning and the end of the string to match, instead using\nthe operators '^' and '$' to do so, to emulate this behavior\n'*' can be added as either a suffix, or a prefix, or both,\nto the matching expression.\n\nAs an example \"*, World!\" matches both \"Hello, World!\" and\n\"Good bye, cruel World!\". \"Hello, ....\" matches \"Hello, Bill\"\nand \"Hello, Fred\" but not \"Hello, Tim\" as there are two few\ncharacters in the last string.\n\n@todo make a matcher that expects a Forth string, which do\nnot have to be NUL terminated )\n\n\\ Translated from http:\/\/c-faq.com\/lib\/regex.html\n\\ int match(char *pat, char *str)\n\\ {\n\\ \tswitch(*pat) {\n\\ \tcase '\\0': return !*str;\n\\ \tcase '*': return match(pat+1, str) || *str && match(pat, str+1);\n\\ \tcase '.': return *str && match(pat+1, str+1);\n\\ \tdefault: return *pat == *str && match(pat+1, str+1);\n\\ \t}\n\\ }\n\n: *pat ( regex -- regex char : grab next character of pattern )\n\tdup c@ ;\n\n: *str ( string regex -- string regex char : grab next character string to match )\n\tover c@ ;\n\n: pass ( c-addr1 c-addr2 -- bool : pass condition, characters matched )\n\t2drop 1 ;\n\n: reject ( c-addr1 c-addr2 -- bool : fail condition, character not matched )\n\t2drop 0 ;\n\n: *pat==*str ( c-addr1 c-addr2 -- c-addr1 c-addr2 bool )\n\t2dup c@ swap c@ = ;\n\n: ++ ( u1 u2 u3 u4 -- u1+u3 u2+u4 : not quite d+ [does no carry] )\n\tswap >r + swap r> + swap ;\n\ndefer matcher\n\n: advance ( string regex char -- bool : advance both regex and string )\n\tif 1 1 ++ matcher else reject then ;\n\n: advance-string ( string regex char -- bool : advance only the string )\n\tif 1 0 ++ matcher else reject then ;\n\n: advance-regex ( string regex -- bool : advance matching )\n\t2dup 0 1 ++ matcher if pass else *str advance-string then ;\n\n: match ( string regex -- bool : match a ASCIIZ pattern against an ASCIIZ string )\n\t( @todo Add limits and accept two Forth strings, making sure they are both\n\t ASCIIZ strings as well\n\t @warning This uses a non-standards compliant version of case! )\n\t*pat\n\tcase\n\t\t 0 of drop c@ not endof\n\t\t[char] * of advance-regex endof\n\t\t[char] . of *str advance endof\n\t\t\n\t\tdrop *pat==*str advance exit\n\n\tendcase ;\n\nmatcher is match\n\nhide{\n\t*str *pat *pat==*str pass reject advance\n\tadvance-string advance-regex matcher ++\n}hide\n\n( ==================== Matcher =============================== )\n\n\n( ==================== Cons Cells ============================ )\n( From http:\/\/sametwice.com\/cons.fs, this could be improved\nif the optional memory allocation words were added to\nthe interpreter. This provides a simple \"cons cell\" data\nstructure. There is currently no way to free allocated\ncells. I do not think this is particularly useful, but it is\ninteresting. )\n\n: car! ( value cons-addr -- : store a value in the car cell of a cons cell )\n\t! ;\n\n: cdr! ( value cons-addr -- : store a value in the cdr cell of a cons cell )\n\tcell+ ! ;\n\n: car@ ( cons-addr -- car-val : retrieve car value from cons cell )\n\t@ ;\n\n: cdr@ ( cons-addr -- cdr-val : retrieve cdr value from cons cell )\n\tcell+ @ ;\n\n: cons ( car-val cdr-val -- cons-addr : allocate a new cons cell )\n\tswap here >r , , r> ;\n\n: cons0 0 0 cons ;\n\n( ==================== Cons Cells ============================ )\n\n( ==================== License =============================== )\n( The license has been chosen specifically to make this library\nand any associated programs easy to integrate into arbitrary\nproducts without any hassle. For the main libforth program\nthe LGPL license would have been also suitable [although it\nis MIT licensed as well], but to keep confusion down the same\nlicense, the MIT license, is used in both the Forth code and\nC code. This has not been done for any ideological reasons,\nand I am not that bothered about licenses. )\n\n: license ( -- : print out license information )\n\"\nThe MIT License (MIT)\n\nCopyright (c) 2016, 2017 Richard James Howe\n\nPermission is hereby granted, free of charge, to any person\nobtaining a copy of this software and associated documentation\nfiles (the 'Software'), to deal in the Software without\nrestriction, including without limitation the rights to use,\ncopy, modify, merge, publish, distribute, sublicense, and\/or\nsell copies of the Software, and to permit persons to whom\nthe Software is furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY\nKIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\nWARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE\nAND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\nHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE\nOR OTHER DEALINGS IN THE SOFTWARE.\n\n\"\n;\n\n( ==================== License =============================== )\n\n( ==================== Core utilities ======================== )\n( Read the header of a core file and process it, printing the\nresults out )\n\n8 constant header-size ( size of Forth core file header )\n8 constant size-field-size ( the size in bytes of the size field in the core file )\n0 variable core-file ( core fileid we are reading in )\n0 variable core-cell-size ( cell size of Forth core )\n0 variable core-version ( version of core file )\n0 variable core-endianess ( endianess of core we are reading in )\n\n( save space to read in header )\ncreate header header-size chars allot\n: cheader ( -- c-addr : header char address )\n\theader chars> ;\ncreate size-field size-field-size chars allot\n: csize-field ( -- c-addr : address of place size field is stored in )\n\tsize-field chars> ;\n\n0\nenum header-magic0 ( magic number 0 : FF )\nenum header-magic1 ( magic number 1 : '4' )\nenum header-magic2 ( magic number 2 : 'T' )\nenum header-magic3 ( magic number 3 : 'H' )\nenum header-cell-size ( size of a forth cell, either 2, 4 or 8 bytes )\nenum header-version ( version of the forth core )\nenum header-endianess ( endianess of the core )\nenum header-log2size ( binary logarithm of the core size )\n\n: cleanup ( -- : cleanup before abort )\n\tcore-file @ ?dup 0<> if close-file drop then ;\n\n: invalid-header ( bool -- : abort if header is invalid )\n\t<> if cleanup abort\" invalid header\" then ;\n\n: save-core-cell-size ( char -- : save the core file cell size, checking if it is valid )\n\tcore-cell-size !\n\t\" cell size:\" tab\n\tcore-cell-size @ 2 = if 2 . cr exit then\n\tcore-cell-size @ 4 = if 4 . cr exit then\n\tcore-cell-size @ 8 = if 8 . cr exit then\n\tcleanup core-cell-size @ . abort\" : invalid cell size\" ;\n\n: check-version-compatibility ( char -- : checks the version compatibility of the core file )\n\tcore-version !\n\tcore-version @ version = if \" version: \" version . cr exit then\n\tcleanup core-version @ . abort\" : unknown version number\" ;\n\n: save-endianess ( char -- : save the endianess, checking if it is valid )\n\tcore-endianess !\n\t\" endianess:\" tab\n\tcore-endianess @ 0 = if \" big\" cr exit then\n\tcore-endianess @ 1 = if \" little\" cr exit then\n\tcleanup core-endianess @ . abort\" invalid endianess\" then ;\n\n: read-or-abort ( c-addr size fileid -- : )\n\tover >r read-file\n\t 0<> if cleanup abort\" file read failed\" then\n\tr> <> if cleanup abort\" header too small\" then ;\n\n: header? ( -- : print out header information )\n\tcheader header-size core-file @ read-or-abort\n\t( \" raw header:\" header 2 dump )\n\tcheader header-magic0 + c@ 255 invalid-header\n\tcheader header-magic1 + c@ [char] 4 invalid-header\n\tcheader header-magic2 + c@ [char] T invalid-header\n\tcheader header-magic3 + c@ [char] H invalid-header\n\tcheader header-cell-size + c@ save-core-cell-size\n\tcheader header-version + c@ check-version-compatibility\n\tcheader header-endianess + c@ save-endianess\n\t\" valid header\" cr ;\n\n: size? ( -- : print out core file size )\n\t\" size: \" cheader header-log2size + c@ 1 swap lshift . cr ;\n\n: core ( c-addr u -- : analyze a Forth core file from disk given its file name )\n\t2dup \" core file:\" tab type cr\n\tr\/o open-file throw core-file !\n\theader?\n\tsize?\n\tcore-file @ close-file drop ;\n\n( s\" forth.core\" core )\n\nhide{\nheader-size header?\nheader-magic0 header-magic1 header-magic2 header-magic3\nheader-version header-cell-size header-endianess header-log2size\nheader\ncore-file save-core-cell-size check-version-compatibility\ncore-cell-size cheader\ncore-endianess core-version save-endianess invalid-header\ncleanup size-field csize-field size-field-size\nread-or-abort size?\n}hide\n\n( ==================== Core utilities ======================== )\n\n( ==================== RLE =================================== )\n\n( These set of words implement Run Length Compression, which\ncan be used for saving space when compressing the core files\ngenerated by Forth programs, which contain mostly runs of\nNUL characters.\n\nThe format of the encoded data is quite simple, there is a\ncommand byte followed by data. The command byte encodes only\ntwo commands; encode a run of literal data and repeat the\nnext character.\n\nIf the command byte is greater than X the command is a run\nof characters, X is then subtracted from the command byte\nand this is the number of characters that is to be copied\nverbatim when decompressing.\n\nIf the command byte is less than or equal to X then this\nnumber, plus one, is used to repeat the next data byte in\nthe input stream.\n\nX is 128 for this application, but could be adjusted for\nbetter compression depending on what the data looks like.\n\nExample:\n\n\t2 'a' 130 'b' 'c' 3 'd'\n\nBecomes:\n\n\taabcddd\n\nExample usage:\n\n\t: extract\n\t\tc\" forth.core\" w\/o open-file throw c\"\n\t\tforth.core.rle\" r\/o open-file throw\n\t\tdecompress ;\n\textract\n\n@note file redirection could be used for the input as well\n@todo compression, and reading\/writing to strings )\n\n: cpad pad chars> ;\n\n0 variable out\n128 constant run-length\n\n: next.char ( file-id -- char : read in a single character )\n\t>r cpad r> read-char throw cpad c@ ;\n\n: repeated ( count file-id -- : repeat a character count times )\n\tnext.char swap 0 do dup emit loop drop ;\n\n: literals ( count file-id -- : extract a literal run )\n\t>r cpad swap r> read-file throw cpad swap type ;\n\n: command ( file-id -- : process an RLE command )\n\tdup\n\t>r next.char\n\tdup run-length u>\n\tif\n\t\trun-length - r> literals\n\telse\n\t\t1+ r> repeated\n\tthen ;\n\n: redirect ( file-id-out -- : save current output pointer, redirect to output )\n\t`fout @ out ! `fout ! ;\n\n: restore ( -- : restore previous output pointer )\n\tout @ `fout ! ;\n\n: decompress ( file-id-out file-id-in -- : decompress an RLE encoded file )\n\tswap\n\tredirect\n\tbegin dup ['] command catch until ( process commands until input exhausted )\n\t2drop ( drop twice because catch will restore stack before COMMAND )\n\trestore ; ( restore input stream )\n\nhide{ literals repeated next.char out run-length command }hide\n\n( ==================== RLE =================================== )\n\n( ==================== Generate C Core file ================== )\n( The word core2c reads in a core file and turns it into a\nC file which can then be compiled into the forth interpreter\nin a bootstrapping like process. The process is described\nelsewhere as well, but it goes like this.\n\n1. We want to generate an executable program that contains the\ncore Forth interpreter, written in C, and the contents of this\nfile in compiled form. However, in order to compile this code\nwe need a Forth interpreter to do so. This is the problem.\n2. To solve the problem we first make a program which is capable\nof compiling \"forth.fth\".\n3. We then generate a core file from this.\n4. We then convert the generated core file to C code.\n5. We recompile the original program to includes this core\nfile, and which runs the core file at start up.\n6. We run the new executable.\n\nUsage:\n c\" forth.core\" c\" core.gen.c\" core2c )\n\n0 variable count\n\n: wbyte ( u char -- : write a byte )\n\t(.) drop\n\t[char] , emit\n\t16 mod 0= if cr then ;\n\n: advance ( char -- : advance counter and print byte )\n\tcount 1+! count @ swap wbyte ;\n\n: hexify ( fileid -- fileid : turn core file into C numbers in array )\n\t0 count !\n\tbegin dup getchar 0= while advance repeat drop ;\n\n: quote ( -- : emit a quote character )\n\t[char] \" emit ;\n\n: core2c ( c-addr u c-addr u -- ior : generate a C file from a core file )\n\tw\/o open-file throw >r\n\tr\/o open-file ?dup-if r> close-file throw throw then\n\tr> redirect\n\t\" #include \" quote \" libforth.h\" quote cr\n\t\" unsigned char forth_core_data[] = {\" cr\n\thexify\n\t\" };\" cr\n\t\" forth_cell_t forth_core_size = \" count @ . \" ;\" cr cr\n\tclose-file\n\t`fout @ close-file\n\trestore or ;\n\nhide{ wbyte hexify count quote advance }hide\n\n( ==================== Generate C Core file ================== )\n\n( ==================== Word Count Program ==================== )\n\n( @todo implement FILE-SIZE in terms of this program )\n( @todo extend wc to include line count and word count )\n: wc ( c-addr u -- u : count the bytes in a file )\n\tr\/o open-file throw\n\t0 swap\n\tbegin\n\t\tdup getchar nip 0=\n\twhile\n\t\tnos1+\n\trepeat\n\tclose-file throw ;\n\n( ==================== Word Count Program ==================== )\n\n( ==================== Save Core file ======================== )\n( The following functionality allows the user to save the\ncore file from within the running interpreter. The Forth\ncore files have a very simple format which means the words\nfor doing this do not have to be too long, a header has to\nemitted with a few calculated values and then the contents\nof the Forths memory after this )\n\n( This write the header out to the current output device, this\nwill be redirected to a file )\n: header ( -- : write the header out )\n\t0xff emit ( magic 0 )\n\t[char] 4 emit ( magic 1 )\n\t[char] T emit ( magic 2 )\n\t[char] H emit ( magic 3 )\n\tsize emit ( cell size in bytes )\n\tversion emit ( core version )\n\tendian not emit ( endianess )\n\tmax-core log2 emit ; ( size field )\n\n: data ( -- : write the data out )\n\t0 max-core chars> `fout @ write-file throw drop ;\n\n: encore ( -- : write the core file out )\n\theader\n\tdata ;\n\n: save-core ( c-addr u -- : save core file or throw error )\n\tw\/o open-file throw dup\n\tredirect\n\t\t['] encore catch swap close-file throw\n\trestore ;\n\n( The following code illustrates an example of setting up a\nForth core file to execute a word when the core file is loaded.\nIn the example the word \"hello-world\" will be executed,\nwhich will also quit the interpreter:\n\nThis only works for immediate words for now, we define\nthe word we wish to be executed when the forth core\nis loaded:\n\n\t: hello-world immediate\n\t\t\" Hello, World!\" cr bye ;\n\nThe following sets the starting word to our newly\ndefined word:\n\n\tfind hello-world cfa start!\n\n\t\\ Now we can save the core file out:\n\ts\" forth.core\" save-core\n\nThis can be used, in conjunction with aspects of the build\nsystem, to produce a standalone executable that will run only\na single Forth word. This is known as creating a 'turn-key'\napplication. )\n\nhide{ redirect restore data encore header }hide\n\n( ==================== Save Core file ======================== )\n\n( ==================== Hex dump ============================== )\n\n( @todo hexdump can read in too many characters and it does not\nprint out the correct address\n@todo utilities for easy redirecting of file input\/output )\n\\ : input >r cpad 128 r> read-file ; ( file-id -- u 0 | error )\n\\ : clean cpad 128 0 fill ; ( -- )\n\\ : cdump cpad chars swap aligned chars dump ; ( u -- )\n\\ : hexdump ( file-id -- : [hex]dump a file to the screen )\n\\ \tdup\n\\ \tclean\n\\ \tinput if 2drop exit then\n\\ \t?dup-if cdump else drop exit then\n\\ \ttail ;\n\\\n\\ 0 variable u\n\\ 0 variable u1\n\\ 0 variable cdigs\n\\ 0 variable digs\n\\\n\\ : address ( -- bool : is it time to print out a new line and an address )\n\\ \tu @ u1 @ - 4 size * mod 0= ;\n\\\n\\ : (dump) ( u c-addr u : u -- )\n\\ \trot dup u ! u1 !\n\\ \tcdigits cdigs !\n\\ \tdigits digs !\n\\ \tbounds\n\\ \tdo\n\\ \t\taddress if cr u @ digs @ u.rz [char] : emit space then\n\\ \t\ti c@ cdigs @ u.rz\n\\ \t\t\n\\ \t\ti 1+ size mod 0= if space then\n\\ \t\tu 1+!\n\\ \tloop\n\\ \tu @\n\\ \t;\n\\\n\\ : hexdump-file ( c-addr u )\n\\ \tr\/o open-file throw\n\\ \t\n\\ \t;\n\\\n\\ hide{ u u1 cdigs digs address }hide\n\\ hex\n\\ 999 0 197 (dump)\n\\ decimal\n\\\n\\ hide{ cpad clean cdump input }hide\n\\\n( ==================== Hex dump ============================== )\n\n( ==================== Date ================================== )\n( This word set implements a words for date processing, so\nyou can print out nicely formatted date strings. It implements\nthe standard Forth word time&date and two words which interact\nwith the libforth DATE instruction, which pushes the current\ntime information onto the stack.\n\nRather annoyingly months are start from 1 but weekdays from\n0. )\n\n: >month ( month -- c-addr u : convert month to month string )\n\tcase\n\t\t 1 of c\" Jan \" endof\n\t\t 2 of c\" Feb \" endof\n\t\t 3 of c\" Mar \" endof\n\t\t 4 of c\" Apr \" endof\n\t\t 5 of c\" May \" endof\n\t\t 6 of c\" Jun \" endof\n\t\t 7 of c\" Jul \" endof\n\t\t 8 of c\" Aug \" endof\n\t\t 9 of c\" Sep \" endof\n\t\t10 of c\" Oct \" endof\n\t\t11 of c\" Nov \" endof\n\t\t12 of c\" Dec \" endof\n\t\t-11 throw\n\tendcase ;\n\n: .day ( day -- c-addr u : add ordinal to day )\n\t10 mod\n\tcase\n\t\t1 of c\" st \" endof\n\t\t2 of c\" nd \" endof\n\t\t3 of c\" rd \" endof\n\t\tdrop c\" th \" exit\n\tendcase ;\n\n: >day ( day -- c-addr u: add ordinal to day of month )\n\tdup 1 10 within if .day exit then\n\tdup 10 20 within if drop c\" th\" exit then\n\t.day ;\n\n: >weekday ( weekday -- c-addr u : print the weekday )\n\tcase\n\t\t0 of c\" Sun \" endof\n\t\t1 of c\" Mon \" endof\n\t\t2 of c\" Tue \" endof\n\t\t3 of c\" Wed \" endof\n\t\t4 of c\" Thu \" endof\n\t\t5 of c\" Fri \" endof\n\t\t6 of c\" Sat \" endof\n\t\t-11 throw\n\tendcase ;\n\n: >gmt ( bool -- GMT or DST? )\n\tif c\" DST \" else c\" GMT \" then ;\n\n: colon ( -- char : push a colon character )\n\t[char] : ;\n\n: 0? ( n -- : hold a space if number is less than base )\n\t(base) u< if [char] 0 hold then ;\n\n( .NB You can format the date in hex if you want! )\n: date-string ( date -- c-addr u : format a date string in transient memory )\n\t9 reverse ( reverse the date string )\n\t<#\n\t\tdup #s drop 0? ( seconds )\n\t\tcolon hold\n\t\tdup #s drop 0? ( minute )\n\t\tcolon hold\n\t\tdup #s drop 0? ( hour )\n\t\tdup >day holds\n\t\t#s drop ( day )\n\t\t>month holds\n\t\tbl hold\n\t\t#s drop ( year )\n\t\t>weekday holds\n\t\tdrop ( no need for days of year )\n\t\t>gmt holds\n\t\t0\n\t#> ;\n\n: .date ( date -- : print the date )\n\tdate-string type ;\n\n: time&date ( -- second minute hour day month year )\n\tdate\n\t3drop ;\n\nhide{ >weekday .day >day >month colon >gmt 0? }hide\n\n( ==================== Date ================================== )\n\n\n( ==================== CRC =================================== )\n\n( @todo implement all common CRC algorithms, but only if the\nword size allows it [ie. 32 bit CRCs on a 32 or 64 bit machine,\n64 bit CRCs on a 64 bit machine] )\n\n( Make a word to limit arithmetic to a 16-bit value )\nsize 2 = [if]\n\t: limit immediate ; ( do nothing, no need to limit )\n[else]\n\t: limit 0xffff and ; ( limit to 16-bit value )\n[then]\n\n: ccitt ( crc c-addr -- crc : calculate polynomial 0x1021 AKA \"x16 + x12 + x5 + 1\" )\n\tc@ ( get char )\n\tlimit over 256\/ xor ( crc x )\n\tdup 4 rshift xor ( crc x )\n\tdup 5 lshift limit xor ( crc x )\n\tdup 12 lshift limit xor ( crc x )\n\tswap 8 lshift limit xor ; ( crc )\n\n( See http:\/\/stackoverflow.com\/questions\/10564491\n and https:\/\/www.lammertbies.nl\/comm\/info\/crc-calculation.html )\n: crc16-ccitt ( c-addr u -- u )\n\t0xffff -rot\n\t['] ccitt foreach ;\nhide{ limit ccitt }hide\n\n( ==================== CRC =================================== )\n\n( ==================== Rational Data Type ==================== )\n( This word set allows the manipulation of a rational data\ntype, which are basically fractions. This allows numbers like\n1\/3 to be represented without any loss of precision. Conversion\nto and from the data type to an integer type is trivial,\nalthough information can be lost during the conversion.\n\nTo convert to a rational, use DUP, to convert from a\nrational, use '\/'.\n\nThe denominator is the first number on the stack, the numerator\nthe second number. Fractions are simplified after any rational\noperation, and all rational words can accept unsimplified\narguments. For example the fraction 1\/3 can be represented as\n6\/18, they are equivalent, so the rational equality operator\n\"=rat\" can accept both and returns true.\n\n\tT{ 1 3 6 18 =rat -> 1 }T\n\nSee: https:\/\/en.wikipedia.org\/wiki\/Rational_data_type For\nmore information.\n\nThis set of words use two cells to represent a fraction,\nhowever a single cell could be used, with the numerator and the\ndenominator stored in upper and lower half of a single cell.\n\n@todo add saturating Q numbers to the interpreter, as well as\narithmetic word for acting on double cells [d+, d-, etcetera]\nhttps:\/\/en.wikipedia.org\/wiki\/Q_%28number_format%29, this\ncan be used in lieu of floating point numbers. )\n\n: simplify ( a b -- a\/gcd{a,b} b\/gcd{a\/b} : simplify a rational )\n 2dup\n gcd\n tuck\n \/\n -rot\n \/\n swap ; \\ ? check this\n\n: crossmultiply ( a b c d -- a*d b*d c*b d*b )\n rot ( a c d b )\n 2dup ( a c d b d b )\n * ( a c d b d*b )\n >r ( a c d b , d*b )\n rot ( a d b c , d*b )\n * ( a d b*c , d*b )\n -rot ( b*c a d , d*b )\n * ( b*c a*d , d*b )\n r> ( b*c a*d d*b )\n tuck ( b*c d*b a*d d*b )\n 2swap ; ( done! )\n\n: *rat ( a\/b c\/d -- a\/b : multiply two rationals together )\n rot * -rot * swap simplify ;\n\n: \/rat ( a\/b c\/d -- a\/b : divide one rational by another )\n swap *rat ;\n\n: +rat ( a\/b c\/d -- a\/b : add two rationals together )\n crossmultiply\n rot\n drop ( or check if equal, if not there is an error )\n -rot\n +\n swap\n simplify ;\n\n: -rat ( a\/b c\/d -- a\/b : subtract one rational from another )\n crossmultiply\n rot\n drop ( or check if equal, if not there is an error )\n -rot\n -\n swap\n simplify ;\n\n: .rat ( a\/b -- : print out a rational number )\n simplify swap (.) drop [char] \/ emit . ;\n\n: =rat ( a\/b c\/d -- bool : rational equal )\n crossmultiply rot = -rot = = ;\n\n: >rat ( a\/b c\/d -- bool : rational greater than )\n crossmultiply rot 2drop > ;\n\n: <=rat ( a\/b c\/d -- bool : rational less than or equal to )\n\t>rat not ;\n\n: =rat ( a\/b c\/d -- bool : rational greater or equal to )\n\trational is a work in progress, make it better )\n: 0>number 0 -rot >number ;\n0 0 2variable saved\n: failed 0 0 saved 2@ ;\n: >rational ( c-addr u -- a\/b c-addr u )\n\t2dup saved 2!\n\t0>number 2dup 0= if 4drop failed exit then ( @note could convert to rational n\/1 )\n\tc@ [char] \/ <> if 3drop failed exit then\n\t1 \/string\n\t0>number ;\n\nhide{ 0>number saved failed }hide\n\n( ==================== Rational Data Type ==================== )\n\n( ==================== Block Layer =========================== )\n( This is the block layer, it assumes that the file access\nwords exists and use them, it would have to be rewritten\nfor an embedded device that used EEPROM or something\nsimilar. Currently it does not interact well with the current\ninput methods used by the interpreter which will need changing.\n\nThe block layer is the traditional way Forths implement a\nsystem to interact with mass storage, one which imposes little\non the underlying system only requiring that blocks 1024 bytes\ncan be loaded and saved to it [which make it suitable for\nmicrocomputers that lack a file system or an embedded device].\n\nThe block layer is used less than it once as a lot more Forths\nare hosted under a guest operating system so have access to\nmethods for reading and writing to files through it.\n\nEach block number accepted by BLOCK is backed by a file\n[or created if it does not exist]. The name of the file is\nthe block number with \".blk\" appended to it.\n\nSome Notes:\n\nBLOCK only uses one block buffer, most other Forths have\nmultiple block buffers, this could be improved on, but\nwould take up more space.\n\nAnother way of storing the blocks could be made, which is to\nstore the blocks in a single file and seek to the correct\nplace within it. This might be implemented in the future,\nor offered as an alternative. \n\nYet another way is to not have on disk blocks, but instead\nhave in memory blocks, this simplifies things significantly,\nand would mean saving the blocks to disk would use the same\nmechanism as saving the core file to disk. Computers certainly\nhave enough memory to do this. The block word set could\nbe factored so it could use either the on disk method or\nthe memory option. \n\nTo simplify the current code, and make the code portable\nto devices with EEPROM an instruction in the virtual machine\ncould be made which does the task of transfering a block to\ndisk. \n\n@todo refactor BLOCK to use MAKE\/DOER so its behavior can\nbe changed. )\n\n0 variable dirty\nb\/buf string buf ( block buffer, only one exists )\n0 , ( make sure buffer is NUL terminated, just in case )\n0 variable blk ( 0 = invalid block number, >0 block number stored in buf)\n\n: invalid? ( n -- : throw if block number is invalid )\n\t0= if -35 throw then ;\n\n: update ( -- : mark currently loaded block buffer as dirty )\n\ttrue dirty ! ;\n\n: updated? ( n -- bool : is a block updated? )\n \tblk @ <> if 0 else dirty @ then ;\n\n: block.name ( n -- c-addr u : make a block name )\n\tc\" .blk\" <# holds #s #> rot drop ;\n\n( @warning this will not work if we do not have permission,\nor in various other cases where we cannot open the file,\nfor whatever reason )\n: file-exists ( c-addr u : does a file exist? )\n\tr\/o open-file if drop 0 else close-file throw 1 then ;\n\n: block.exists ( n -- bool : does a block buffer exist on disk? )\n\tblock.name file-exists ;\n\n( @note block.write and block.read do not check if they have\nwrote or read in 1024 bytes, nor do they check that they can\nonly write or read 1024 and not a byte more )\n\n: block.read ( file-id -- file-id : read in buffer )\n\tdup >r buf r> read-file nip if close-file -33 throw then ;\n\n: block.write ( file-id -- file-id : write out buffer )\n\tdup >r buf r> write-file nip if close-file -34 throw then ;\n\n: block.open ( n fam -- file-id )\n\t>r block.name r> open-file throw ;\n\n: save-buffers\n\tblk @ 0= if exit then ( not a valid block number, exit )\n\tdirty @ not if exit then ( not dirty, no need to save )\n\tblk @ w\/o block.open ( open file backing block buffer )\n\tblock.write ( write it out )\n\tclose-file throw ( close it )\n\tfalse dirty ! ; ( but only mark it clean if everything succeeded )\n\n: empty-buffers ( -- : deallocate any saved buffers )\n\t0 blk ! ;\n\n: flush ( -- : perform save-buffers followed by empty-buffers )\n\tsave-buffers\n\tempty-buffers ;\n\n( Block is a complex word that does a lot, although it has\na simple interface. It does the following given a block number:\n\n1. Checks the provided block buffer number to make sure it\nis valid.\n2. If the block is already loaded from the disk, then return\nthe address of the block buffer it is loaded into.\n3. If not, it checks to see if the currently loaded block\nbuffer is dirty, if it is then it flushes the buffer to disk.\n4. If the block buffer does not exists on disk then it\ncreates it.\n5. It then stores the block number in blk and returns an\naddress to the block buffer. )\n: block ( n -- c-addr : load a block )\n\tdup invalid?\n\tdup blk @ = if drop buf drop exit then\n\tflush\n\tdup block.exists if ( if the buffer exits on disk load it in )\n\t\tdup r\/o block.open\n\t\tblock.read\n\t\tclose-file throw\n\telse ( else it does not exist )\n\t\tbuf 0 fill ( clean the buffer )\n\tthen\n\tblk ! ( save the block number )\n\tbuf drop ;\n\n: buffer block ;\n\n: load ( n -- : load and execute a block )\n\tblock b\/buf evaluate throw ;\n\n: +block ( n -- u : calculate new block number relative to current block )\n\tblk @ + ;\n\n: --> ( -- : load next block )\n\t1 +block load ;\n\n( @todo refactor into BLOCK.MAKE, which BLOCKS.MAKE would use )\n: blocks.make ( n1 n2 -- : make blocks on disk from n1 to n2 inclusive )\n\t1+ swap do i block b\/buf bl fill update loop save-buffers ;\n\n: block.copy ( n1 n2 -- bool : copy block n2 to n1 if n2 exists )\n\tswap dup block.exists 0= if 2drop false exit then ( n2 n1 )\n\tblock drop ( load in block n1 )\n\tw\/o block.open block.write close-file throw\n\ttrue ;\n\n: block.delete ( n -- : delete block )\n\tdup block.exists 0= if drop exit then\n\tblock.name delete-file drop ;\n\n\\ @todo implement a word that splits a file into blocks\n\\ : split ( c-addr u : split a file into blocks )\n\\\t;\n\nhide{\n\tblock.name invalid? block.write\n\tblock.read block.exists block.open dirty\n}hide\n\n( ==================== Block Layer =========================== )\n\n( ==================== List ================================== )\n( The list word set allows the viewing of Forth blocks,\nthis version of list can create two Formats, a simple mode\nwhere it just spits out the block with a carriage return\nafter each line and a more fancy version which also prints\nout line numbers and draws a box around the data. LIST is\nnot aware of any formatting and characters that might be\npresent in the data, or none printable characters.\n\nA very primitive version of list can be defined as follows:\n\n\t: list block b\/buf type ;\n\n)\n\n1 variable fancy-list\n0 variable scr\n64 constant c\/l ( characters per line )\n\n: pipe ( -- : emit a pipe character )\n\t[char] | emit ;\n\n: line.number ( n -- : print line number )\n\tfancy-list @ not if drop exit then\n\t2 u.r space pipe ;\n\n: list.end ( -- : print the right hand side of the box )\n\tfancy-list @ not if exit then\n\tpipe ;\n\n: line ( c-addr -- c-addr u : given a line number, display that line number and calculate offset )\n\tdup\n\tline.number ( display line number )\n\tc\/l * + ( calculate offset )\n\tc\/l ; ( add line length )\n\n: list.type ( c-addr u -- : list a block )\n\tb\/buf c\/l \/ 0 do dup i line type list.end cr loop drop ;\n\n: list.border ( -- : print a section of the border )\n\t\" +---|---\" ;\n\n: list.box ( )\n\tfancy-list @ not if exit then\n\t4 spaces\n\t8 0 do list.border loop cr ;\n\n: list ( n -- : display a block number and update scr )\n\tdup >r block r> scr ! list.box list.type list.box ;\n\n: thru\n\tkey drop\n\t1+ swap do i list more loop ;\n\nhide{\n\tbuf line line.number list.type\n\t(base) list.box list.border list.end pipe\n}hide\n\n( ==================== List ================================== )\n\n( ==================== Signal Handling ======================= )\n( Signal handling at the moment is quite primitive. When\na signal occurs it has to be explicitly tested for by the\nprogrammer, this could be improved on quite a bit. One way\nof doing this would be to check for signals in the virtual\nmachine and cause a THROW from within it. )\n\n( signals are biased to fall outside the range of the error\nnumbers defined in the ANS Forth standard. )\n-512 constant signal-bias\n\n: signal ( -- signal\/0 : push the results of the signal register )\n\t`signal @\n \t0 `signal ! ;\n\n( ==================== Signal Handling ======================= )\n\n( Looking at most Forths dictionary with \"words\" command they\ntend to have a lot of words that do not mean anything but to\nthe implementers of that specific Forth, here we clean up as\nmany non standard words as possible. )\nhide{\n do-string ')' alignment-bits\n dictionary-start hidden-mask instruction-mask immediate-mask compiling?\n compile-bit\n max-core dolist doconst x x! x@\n max-string-length\n evaluator\n TrueFalse >instruction\n xt-instruction\n `source-id `sin `sidx `slen `start-address `fin `fout `stdin\n `stdout `stderr `argc `argv `debug `invalid `top `instruction\n `stack-size `error-handler `handler _emit `signal `x\n}hide\n\n(\n## Forth To List\n\nThe following is a To-Do list for the Forth code itself,\nalong with any other ideas.\n\n* FORTH, VOCABULARY\n\n* \"Value\", \"To\", \"Is\"\n\n* Double cell words\n\n* The interpreter should use character based addresses,\ninstead of word based, and use values that are actual valid\npointers, this will allow easier interaction with the world\noutside the virtual machine\n\n* common words and actions should be factored out to simplify\ndefinitions of other words, their standards compliant version\nfound if any.\n\n* A soft floating point library would be useful which could be\nused to optionally implement floats [which is not something I\nreally want to add to the virtual machine]. If floats were to\nbe added, only the minimal set of functions should be added\n[f+,f-,f\/,f*,f<,f>,>float,...]\n\n* Allow the processing of argc and argv, the mechanism by which\nthat this can be achieved needs to be worked out. However all\nprocessing that is currently done in \"main.c\" should be done\nwithin the Forth interpreter instead. Words for manipulating\nrationals and double width cells should be made first.\n\n* A built in version of \"dump\" and \"words\" should be added\nto the Forth starting vocabulary, simplified versions that\ncan be hidden.\n\n* Here documents, string literals. Examples of these can be\nfound online\n\n* Document the words in this file and built in words better,\nalso turn this document into a literate Forth file.\n\n* Sort out \"'\", \"[']\", \"find\", \"compile,\"\n\n* Proper booleans should be used throughout, that is -1 is\ntrue, and 0 is false.\n\n* Attempt to add crypto primitives, not for serious use,\nlike TEA, XTEA, XXTEA, RC4, MD5, ...\n\n* Add hash functions: CRC-32, CRC-16, ...\nhttp:\/\/stackoverflow.com\/questions\/10564491\/\n\n* Implement as many things from\nhttp:\/\/lars.nocrew.org\/forth2012\/implement.html as is sensible.\n\n* Works like EMIT and KEY should be DOER\/MAKE words\n\n* The current words that implement I\/O redirection need to\nbe improved, and documented, I think this is quite a useful\nand powerful mechanism to use within Forth that simplifies\nprograms. This is a must and will make writing utilities in\nForth a *lot* easier\n\n* Words for manipulating words should be added, for navigating\nto different fields within them, to the end of the word,\netcetera.\n\n* The data structure used for parsing Forth words needs\nchanging in libforth so a counted string is produced. Counted\nstrings should be used more often. The current layout of a\nForth word prevents a counted string being used and uses a\nbyte more than it has to.\n\n* Whether certain simple words [such as '1+', '1-', '>',\n'<', '<>', NOT, <=', '>='] should be added as virtual\nmachine instructions for speed [and size] reasons should\nbe investigated.\n\n* An analysis of the interpreter and the code it executes\ncould be done to find the most commonly executed words\nand instructions, as well as the most common two and three\nsequences of words and instructions. This could be used to use\nto optimize the interpreter, in terms of both speed and size.\n\n* The source code for this file should go through a code\nreview, which should focus on formatting, stack comments and\nreorganizing the code. Currently it is not clear that variables\nlike COLORIZE and FANCY-LIST exist and can be changed by\nthe user. Lines should be 64 characters in length - maximum,\nincluding the new line at the end of the file.\n\n### libforth.c todo\n\n* A halt, a parse, and a print\/type instruction could be\nadded to the Forth virtual machine.\n\n* Make case sensitivity optional\n\n* u.r, or a more generic version should be added to the\ninterpreter instead of the current simpler primitive. As\nshould >number - for fast numeric input and output.\n\n* Throw\/Catch need to be added and used in the virtual machine\n\n* Integrate Travis Continous Integration into the Github\nproject.\n\n* A potential optimization is to order the words in the\ndictionary by frequency order, this would mean chaning the\nX Macro that contains the list of words, after collecting\nstatistics. This should make find faster.\n\n* Investigate adding operating system specific code into the\ninterpreter and isolating it to make it semi-portable.\n\n* Make equivalents for various Unix utilities in Forth,\nlike a CRC check, cat, tr, etcetera.\n\n* It would be interesting to make a primitive file system based\nupon Forth blocks, this could then be ported to systems that\ndo not have file systems, such as microcontrollers [which\nusually have EEPROM].\n\n* In a _very_ unportable way it would be possible to have an\ninstruction that takes the top of the stack, treats it as a\nfunction pointer and then attempts to call said function. This\nwould allow us to assemble machine dependant code within the\ncore file, generate a new function, then call it. It is just\na thought.\n )\n\nverbose [if]\n\t.( FORTH: libforth successfully loaded.) cr\n\tdate .date cr\n\t.( Type 'help' and press return for a basic introduction.) cr\n\t.( Core: ) here . \" \/ \" here unused + . cr\n\t license\n[then]\n\n( ==================== Test Code ============================= )\n\n( The following will not work as we might actually be reading\nfrom a string [`sin] not `fin.\n\n: key 32 chars> 1 `fin @\n\tread-file drop 0 = if 0 else 32 chars> c@ then ; )\n\n\\ : ' immediate state @ if postpone ['] else find then ;\n\n( This really does not implement a correct FORTH\/VOCABULARY,\nfor that wordlists will need to be introduced and used in\nlibforth.c. The best that this word set can do is to hide\nand reveal words to the user, this was just an experiment.\n\n\t: forth\n\t\t[ find forth 1- @ ] literal\n\t\t[ find forth 1- ] literal ! ;\n\n\t: vocabulary\n\t\tcreate does> drop 0 [ find forth 1- ] literal ! ; )\n\n\\ @todo The built in primitives should be redefined so to make sure\n\\ they are called and nested correctly, using the following words\n\\ 0 variable csp\n\\ : !csp sp@ csp ! ;\n\\ : ?csp sp@ csp @ <> if -22 throw then ;\n\n\\ @todo Make this work\n\\ : >body ??? ;\n\\ : noop ( -- ) ;\n\\ : defer create ( \"name\" -- ) ['] noop , does> ( -- ) @ execute ;\n\\ : is ( xt \"name\" -- ) find >body ! ;\n\\ defer lessthan\n\\ find < is lessthan\n\n( ==================== Test Code ============================= )\n\n( ==================== Block Editor ========================== )\n( Experimental block editor Mark II\n\nThis is a simple block editor, it really shows off the power\nand simplicity of Forth systems - both the concept of a block\neditor and the implementation.\n\nForth source code used to organized into things called 'blocks',\nnowadays most people use normal resizeable stream based files.\nA block simply consists of 1024 bytes of data that can be\ntransfered to and from mass storage. This works on systems that\ndo not have a file system. A block can be used for storing\narbitrary data as well, so the user had to know what was stored\nin what block.\n\n1024 bytes is quite a limiting Form factor for storing source\ncode, which is probably one reason Forth earned a reputation\nfor being terse. A few conventions arose around dealing with\nForth source code stored in blocks - both in how the code should\nbe formatted within them, and in how programs that required\nmore than one block of storage should be dealt with.\n\nOne of the conventions is how many columns and rows each block\nconsists of, the traditional way is to organize the code into\n16 lines of text, with a column width of 64 characters. The only\nspace character used is the space [or ASCII character 32], tabs\nand new lines are not used, as they are not needed - the editor\nknows how long a line is so it can wrap the text.\n\nVarious standards and common practice evolved as to what goes\ninto a block - for example the first line is usually a comment\ndescribing what the block does, with the date is was last edited\nand who edited it.\n\nThe way the editor works is by defining a simple set of words\nthat act on the currently loaded block, LIST is used to display\nthe loaded block. An editor loop which executes forth words\nand automatically displays the currently block can be entered\nby calling EDITOR. This loop is essential an extension of\nthe INTERPRET word, it does no special processing such as\nlooking for keys - all commands are Forth words. The editor\nloop could have been implemented in the following fashion\n[or something similar]:\n\n\t: editor-command\n\t\tkey\n\t\tcase\n\t\t\t[char] h of print-editor-help endof\n\t\t\t[char] i of insert-text endof\n\t\t\t[char] d of delete-line endof\n\t\t\t... more editor commands\n\t\t\t[char] q of quit-editor-loop endof\n\t\t\tpush-number-by-default\n\t\tendof ;\n\nHowever this is rather limiting, it only works for single\ncharacter commands and numeric input is handled as a special\ncase. It is far simpler to just call the READ word with the\neditor commands in search order, and it can be extended not\nby adding more parsing code in CASE statements but just by\ndefining new words in the ordinary manner.\n\nThe editor loop does not have to be used while editing code,\nbut it does make things easier. The commands defined can be\nused on there own.\n\t\nThe code was adapted from: \t\n\nhttp:\/\/retroforth.org\/pages\/?PortsOfRetroEditor\n\nWhich contains ports of an editor written for Retro Forth.\n\n@todo Improve the block editor\n\n- '\\' needs extending to work with the block editor, for now,\nuse parenthesis for comments\n- add multi line insertion mode\n- Add to an editor vocabulary, which will need the vocabulary\nsystem to exist.\n- Using PAGE should be optional as not all terminals support\nANSI escape codes - thanks to CMD.EXE. Damned Windows.\n\nAdapted from http:\/\/retroforth.org\/pages\/?PortsOfRetroEditor )\n\n\n: help ( @todo rename to H once vocabularies are implemented )\npage cr\n\" Block Editor Help Menu\n\n n move to next block\n p move to previous block\n # d delete line in current block\n x erase current block\n e evaluate current block\n # i insert line\n # #2 ia insert at line #2 at column #\n q quit editor loop\n # b set block number\n s save block and write it out\n u update block\n\n -- press any key to continue -- \" cr ( \" )\nchar drop ;\n\n: (block) blk @ block ;\n: (check) dup b\/buf c\/l \/ u>= if -24 throw then ;\n: (line) (check) c\/l * (block) + ; ( n -- c-addr : push current line address )\n: (clean)\n\t(block) b\/buf\n\t2dup nl bl subst\n\t2dup cret bl subst\n\t 0 bl subst ;\n: n 1 +block block ;\n: p -1 +block block ;\n: d (line) c\/l bl fill ;\n: x (block) b\/buf bl fill ;\n: s update save-buffers ;\n: q rdrop rdrop ;\n: e blk @ load char drop ;\n: ia c\/l * + dup b\/buf swap - >r (block) + r> accept drop (clean) ;\n: i 0 swap ia ;\n: editor\n\t1 block ( load first block by default )\n\trendezvous ( set up a rendezvous so we can forget words up to this point )\n\tbegin\n\t\tpage cr\n\t\t\" BLOCK EDITOR: TYPE 'HELP' FOR A LIST OF COMMANDS\" cr\n\t\tblk @ list\n\t\t\" [BLOCK: \" blk @ u. \" ] \" \n\t\t\" [HERE: \" here u. \" ] \" \n\t\t\" [SAVED: \" blk @ updated? not u. \" ] \"\n\t\tcr\n\t\tpostpone [ ( need to be in command mode )\n\t\tread\n\tagain ;\n\n( Extra niceties )\nc\/l string yank \nyank bl fill\n: u update ;\n: b block ;\n: l blk @ list ;\n: y (line) yank >r swap r> cmove ; ( n -- yank line number to buffer )\n: c (line) yank cmove ; ( n -- copy yank buffer to line )\n: ct swap y c ; ( n1 n2 -- copy line n1 to n2 )\n: ea (line) c\/l evaluate throw ;\n: m retreat ; ( -- : forget everything since editor session began )\n\n: sw 2dup y (line) swap (line) swap c\/l cmove c ;\n\nhide{ (block) (line) (clean) yank }hide\n\n( ==================== Block Editor ========================== )\n\n( ==================== Error checking ======================== )\n( This is a series of redefinitions that make the use of control\nstructures a bit safer. )\n\n: if immediate ?comp postpone if [ hide if ] ;\n: else immediate ?comp postpone else [ hide else ] ;\n: then immediate ?comp postpone then [ hide then ] ;\n: begin immediate ?comp postpone begin [ hide begin ] ;\n: until immediate ?comp postpone until [ hide until ] ;\n: never immediate ?comp postpone never [ hide never ] ;\n\\ : ; immediate ?comp postpone ; [ hide ; ] ; ( @todo do nesting checking for control statements )\n\n( ==================== Error checking ======================== )\n\n( ==================== DUMP ================================== )\n\\ : newline ( x -- x+1 : print a new line every fourth value )\n\\ \tdup 3 and 0= if cr then 1+ ;\n\\\n\\ : address ( num count -- count : print current address we are dumping every fourth value )\n\\ \tdup >r\n\\ \t1- 3 and 0= if . [char] : emit space else drop then\n\\ \tr> ;\n\\\n\\ : dump ( start count -- : print the contents of a section of memory )\n\\ \\\thex ( switch to hex mode )\n\\ \t1 >r ( save counter on return stack )\n\\ \tover + swap ( calculate limits: start start+count )\n\\ \tbegin\n\\ \t\t2dup u> ( stop if gone past limits )\n\\ \twhile\n\\ \t\tdup r> address >r\n\\ \t\tdup @ . 1+\n\\ \t\tr> newline >r\n\\ \trepeat\n\\ \tr> drop\n\\ \t2drop ;\n\\\n\\ hide newline\n\\ hide address\n( ==================== DUMP ================================== )\n\n( ==================== End of File Functions ================= )\n\n( set up a rendezvous point, we can call the word RETREAT to\nrestore the dictionary to this point. This word also updates\nfence to this location in the dictionary )\nrendezvous\n\n: task ; ( Task is a word that can safely be forgotten )\n\n( ==================== End of File Functions ================= )\n\n\n","old_contents":"#!.\/forth\n( Welcome to libforth, A dialect of Forth. Like all versions\nof Forth this version is a little idiosyncratic, but how\nthe interpreter works is documented here and in various\nother files.\n\nThis file contains most of the start up code, some basic\nstart up code is executed in the C file as well which makes\nprogramming at least bearable. Most of Forth is programmed in\nitself, which may seem odd if your back ground in programming\ncomes from more traditional language [such as C], although\nless so if you know already know lisp.\n\nFor more information about this interpreter and Forth see:\n\nhttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\nAnd within this code base:\n\n\treadme.md : for a manual for this interpreter\n\tlibforth.h : for information about the C API\n\tlibforth.c : for the interpreter itself\n\tunit.c : unit tests for libforth.c\n\tunit.fth : unit tests against this file\n\tmain.c : an example interpreter\n\nThe interpreter and this code originally descend from a Forth\ninterpreter written in 1992 for the International obfuscated\nC Coding Competition.\n\nSee:\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\nThe manual for the interpreter should be read first before\nlooking into this code. It is important to understand the\nexecution model of Forth, especially the differences between\ncommand and compile mode, and how immediate and compiling\nwords work.\n\nEach of these sections is clearly labeled and they are\ngenerally in dependency order.\n\nUnfortunately the code in this file is not as portable as it\ncould be, it makes assumptions about the size of cells provided\nby the virtual machine, which will take time to rectify. Some\nof the constructs are subtly different from the DPANs Forth\nspecification, which is usually noted. Eventually this should\nalso be fixed.\n\nA little note on how code is formatted, a line of Forth code\nshould not exceed 64 characters. All words stack effect, how\nmany variables on the stack it accepts and returns, should\nbe commented with the following types:\n\n\tchar \/ c A character\n\tc-addr An address of a character\n\taddr An address of a cell\n\tr-addr A real address*\n\tu A unsigned number\n\tn A signed number\n\tc\" xxx\" The word parses a word\n\tc\" x\" The word parses a single character\n\txt An execution token\n\tbool A boolean value\n\tior A file error return status [0 on no error]\n\tfileid A file identifier.\n\tCODE A number from a words code field\n\tPWD A number from a words previous word field\n\t* A real address is one outside the range of the\n\tForth address space.\n\nIn the comments Forth words should be written in uppercase. As\nthis is supposed to be a tutorial about Forth and describe the\ninternals of a Forth interpreter, be as verbose as possible.\n\nThe code in this file will need to be modified to abide by\nthese standards, but new code should follow it from the start.\n\nDoxygen style tags for documenting bugs, todos and warnings\nshould be used within comments. This makes finding code that\nneeds working on much easier.)\n\n( ==================== Basic Word Set ======================== )\n\n( We'll begin by defining very simple words we can use later,\nthese a very basic words, that perform simple tasks, they\nwill not require much explanation.\n\nEven though the words are simple, their stack comment and\na description for them will still be included so external\ntools can process and automatically extract the document\nstring for a given work. )\n\n: postpone ( c\" xxx\" -- : postpone execution of a word )\n\timmediate find , ;\n\n: constant\n\t:: ( compile word header )\n\there 1 - h ! ( decrement dictionary pointer )\n\t( change instruction to CONST )\n\there @ instruction-mask invert and doconst or here !\n\there 1 + h ! ( increment dictionary pointer )\n\t, ( write in value )\n\tpostpone [ ; ( back into command mode )\n\n( These constants are defined as a space saving measure,\nnumbers in a definition usually take up two cells, one\nfor the instruction to push the next cell and the cell\nitself, for the most frequently used numbers it is worth\ndefining them as constants, it is just as fast but saves\na lot of space )\n-1 constant -1\n 0 constant 0\n 1 constant 1\n 2 constant 2\n 3 constant 3\n\n0 constant false\n1 constant true ( @warning not standards compliant )\n\n( Confusingly the word CR prints a line feed )\n10 constant lf ( line feed )\nlf constant nl ( new line - line feed on Unixen )\n13 constant cret ( carriage return )\n\n-1 -1 1 rshift invert and constant min-signed-integer\nmin-signed-integer invert constant max-signed-integer\n\n( The following version number is used to mark whether core\nfiles will be compatible with each other, The version number\ngets stored in the core file and is used by the loader to\ndetermine compatibility )\n4 constant version ( version number for the interpreter )\n\n( This constant defines the number of bits in an address )\ncell size 8 * * constant address-unit-bits \n\n( Bit corresponding to the sign in a number )\n-1 -1 1 rshift and invert constant sign-bit \n\n( @todo test by how much, if at all, making words like 1+,\n1-, <>, and other simple words, part of the interpreter would\nspeed things up )\n\n: 1+ ( x -- x : increment a number )\n\t1 + ;\n\n: 1- ( x -- x : decrement a number )\n\t1 - ;\n\n: chars ( c-addr -- addr : convert a c-addr to an addr )\n\tsize \/ ;\n\n: chars> ( addr -- c-addr: convert an addr to a c-addr )\n\tsize * ;\n\n: tab ( -- : print a tab character )\n\t9 emit ;\n\n: 0= ( n -- bool : is 'n' equal to zero? )\n\t0 = ;\n\n: not ( n -- bool : is 'n' true? )\n\t0= ;\n\n: <> ( n n -- bool : not equal )\n\t= 0= ;\n\n: logical ( n -- bool : turn a value into a boolean )\n\tnot not ;\n\n: 2, ( n n -- : write two values into the dictionary )\n\t, , ;\n\n: [literal] ( n -- : write a literal into the dictionary )\n\tdolit 2, ;\n\n: literal ( n -- : immediately compile a literal )\n\timmediate [literal] ;\n\n: sliteral immediate ( I: c-addr u --, Run: -- c-addr u )\n\tswap [literal] [literal] ;\n\n( @todo throw if not found )\n: ['] ( I: c\" xxx\", Run: -- xt )\n\timmediate find [literal] ;\n\n: >instruction ( CODE -- u : extract instruction CODE field )\n\tinstruction-mask and ;\n\n( IMMEDIATE-MASK pushes the mask for the compile bit,\nwhich can be used on a CODE field of a word )\n1 compile-bit lshift constant immediate-mask\n\n: hidden? ( PWD -- PWD bool : is a word hidden? )\n\tdup 1+ @ hidden-mask and logical ;\n\n: compiling? ( PWD -- PWD bool : is a word immediate? )\n\tdup 1+ @ immediate-mask and logical ;\n\n: cr ( -- : emit a newline character )\n\tnl emit ;\n\n: < ( x1 x2 -- bool : signed less than comparison )\n\t- dup if max-signed-integer u> else logical then ;\n\n: > ( x1 x2 -- bool : signed greater than comparison )\n\t- dup if max-signed-integer u< else logical then ;\n\n( The pad area is an area used for temporary storage, some\nwords use it, although which ones do should be kept to a\nminimum. It is an area of space #pad amount of characters\nafter the latest dictionary definition. The area between\nthe end of the dictionary and start of PAD space is used for\npictured numeric output [<#, #, #S, #>]. It is best not to\nuse the pad area that much. )\n128 constant #pad\n\n: pad ( -- addr : push pointer to the pad area )\n\there #pad + ;\n\n( @todo this can be improved a lot, currently it uses more\nspace than it has to, 4 cells instead of three.\n\nIt does:\n\n\tpush value\n\tpush value\n\nInstead of:\n\n\tmagic-2literal-word\n\tvalue\n\tvalue\n\n)\n: 2literal immediate ( n n -- : compile two literals )\n\tswap [literal] [literal] ;\n\n: latest ( get latest defined word )\n\tpwd @ ;\n\n: stdin ( -- fileid : push fileid for standard input )\n\t`stdin @ ;\n\n: stdout ( -- fileid : push fileid for standard output )\n\t`stdout @ ;\n\n: stderr ( -- fileid : push fileid for the standard error )\n\t`stderr @ ;\n\n: stdin? ( -- bool : are we reading from standard input )\n\t`fin @ stdin = ;\n\n: *+ ( n1 n2 n3 -- n )\n\t* + ;\n\t\n: 2- ( n -- n : decrement by two )\n\t2 - ;\n\n: 2+ ( n -- n : increment by two )\n\t2 + ;\n\n: 3+ ( n -- n : increment by three )\n\t3 + ;\n\n: 2* ( n -- n : multiply by two )\n\t1 lshift ;\n\n: 2\/ ( n -- n : divide by two )\n\t1 rshift ;\n\n: 4* ( n -- n : multiply by four )\n\t2 lshift ;\n\n: 4\/ ( n -- n : divide by four )\n\t2 rshift ;\n\n: 8* ( n -- n : multiply by eight )\n\t3 lshift ;\n\n: 8\/ ( n -- n : divide by eight )\n\t3 rshift ;\n\n: 256* ( n -- n : multiply by 256 )\n\t8 lshift ;\n\n: 256\/ ( n -- n : divide by 256 )\n\t8 rshift ;\n\n: 2dup ( n1 n2 -- n1 n2 n1 n2 : duplicate two values )\n\tover over ;\n\n: mod ( u1 u2 -- u : calculate the remainder of u1\/u2 )\n\t2dup \/ * - ;\n\n( @todo implement UM\/MOD in the VM, then use this to implement\n'\/' and MOD )\n: um\/mod ( u1 u2 -- rem quot : remainder and quotient of u1\/u2 )\n\t2dup \/ >r mod r> ;\n\n( @warning this does not use a double cell for the multiply )\n: *\/ ( n1 n2 n3 -- n4 : [n2*n3]\/n1 )\n\t * \/ ;\n\n: char ( -- n : read in a character from the input steam )\n\tkey drop key ;\n\n: [char] ( c\" x\" -- R: -- char : immediately compile next char )\n\timmediate char [literal] ;\n\n( COMPOSE is a high level function that can take two executions\ntokens and produce a unnamed function that can do what they\nboth do.\n\nIt can be used like so:\n\n\t:noname 2 ;\n\t:noname 3 + ;\n\tcompose\n\texecute \n\t.\n\t5 <-- 5 is printed!\n\nI have not found a use for it yet, but it sure is neat.)\n\n: compose ( xt1 xt2 -- xt3 : create a function from xt-tokens )\n\t>r >r ( save execution tokens )\n\tpostpone :noname ( create a new :noname word )\n\tr> , ( write first token )\n\tr> , ( write second token )\n\t(;) ; ( terminate new :noname )\n\n( CELLS is a word that is not needed in this interpreter but\nit required to write portable code [I have probably missed\nquite a few places where it should be used]. The reason it\nis not needed in this interpreter is a cell address can only\nbe in multiples of cells, not in characters. This should be\naddressed in the libforth interpreter as it adds complications\nwhen having to convert to and from character and cell address.)\n\n: cells ( n1 -- n2 : convert cell count to address count)\n\timmediate ;\n\n: cell+ ( a-addr1 -- a-addr2 )\n\tcell + ;\n\n: cell- ( a-addr1 -- addr2 )\n\tcell - ;\n\n: negative? ( x -- bool : is a number negative? )\n\tsign-bit and logical ;\n\n: mask-byte ( x -- x : generate mask byte )\n\t8* 255 swap lshift ;\n\n: select-byte ( u i -- c )\n\t8* rshift 0xff and ;\n\n: xt-instruction ( PWD -- CODE : extract instruction from PWD )\n\tcell+ @ >instruction ;\n\n: defined-word? ( PWD -- bool : is defined or a built-in word)\n\txt-instruction dolist = ;\n\n: char+ ( c-addr -- c-addr : increment a c-addr one c-addr )\n\t1+ ;\n\n: 2chars ( c-addr1 c-addr2 -- addr addr : chars on two c-addr) \n\tchars swap chars swap ;\n\n: 2chars> ( addr addr -- c-addr c-addr: chars> on two addr )\n\tchars> swap chars> swap ;\n\n: hex ( -- : print out hex )\n\t16 base ! ;\n\n: octal ( -- : print out octal )\n\t8 base ! ;\n\n: binary ( -- : print out binary )\n\t2 base ! ;\n\n: decimal ( -- : print out decimal )\n\t0 base ! ;\n\n: negate ( x -- x )\n\t-1 * ;\n\n: abs ( x -- u : return the absolute value of a number )\n\tdup negative? if negate then ;\n\n: square ( x -- x )\n\tdup * ;\n\n: sum-of-squares ( a b -- c : compute a^2 + b^2 to get c )\n\tsquare swap square + ;\n\n: drup ( x y -- x x )\n\tdrop dup ;\n\n: +! ( x addr -- : add x to a value stored at addr )\n\ttuck @ + swap ! ;\n\n: 1+! ( addr -- : increment a value at an address )\n\t1 swap +! ;\n\n: 1-! ( addr -- : decrement a value at an address )\n\t-1 swap +! ;\n\n: c+! ( x c-addr -- : add x to a value stored at c-addr )\n\ttuck c@ + swap c! ;\n\n: toggle ( addr u -- : xor value at addr with u )\n\tover @ xor swap ! ;\n\n: lsb ( x -- x : mask off the least significant byte of a cell )\n\t255 and ;\n\n: \\ ( -- : immediate word, used for single line comments )\n\timmediate begin key nl = until ;\n\n: ?dup ( x -- ? )\n\tdup if dup then ;\n\n: min ( n n -- n : return the minimum of two integers )\n\t2dup < if drop else nip then ;\n\n: max ( n n -- n : return the maximum of two integers )\n\t2dup > if drop else nip then ;\n\n: umin ( u u -- u : return the minimum of two unsigned numbers )\n\t2dup u< if drop else nip then ;\n\n: umax ( u u -- u : return the maximum of two unsigned numbers )\n\t2dup > if drop else nip then ;\n\n: limit ( x min max -- x : limit x with a minimum and maximum )\n\trot min max ;\n\n: >= ( n n -- bool )\n\t< not ;\n\n: <= ( n n -- bool )\n\t> not ;\n\n: 2@ ( a-addr -- u1 u2 : load two consecutive memory cells )\n\tdup 1+ @ swap @ ;\n\n: 2! ( u1 u2 a-addr -- : store two values at two consecutive memory cells )\n\t2dup ! nip 1+ ! ;\n\n( @bug I don't think this is correct. )\n: r@ ( -- u, R: u -- )\n\tr> r @ swap >r ;\n\n: rp@ ( -- u, R: u -- )\n\tr> r @ swap >r ;\n\n( @todo r!, rp! )\n\n: 0> ( n -- bool )\n\t0 > ;\n\n: 0<= ( n -- bool )\n\t0> not ;\n\n: 0< ( n -- bool )\n\t0 < ;\n\n: 0>= ( n -- bool )\n\t0< not ;\n\n: 0<> ( n -- bool )\n\t0 <> ;\n\n: signum ( n -- -1 | 0 | 1 : Signum function )\n\tdup 0> if drop 1 exit then\n\t 0< if -1 exit then\n\t0 ;\n\n: nand ( u u -- u : bitwise NAND )\n\tand invert ;\n\n: odd ( u -- bool : is 'n' odd? )\n\t1 and ;\n\n: even ( u -- bool : is 'n' even? )\n\todd not ;\n\n: nor ( u u -- u : bitwise NOR )\n\tor invert ;\n\n: ms ( u -- : wait at least 'u' milliseconds )\n\tclock + begin dup clock u< until drop ;\n\n: sleep ( u -- : sleep for 'u' seconds )\n\t1000 * ms ;\n\n: align ( addr -- addr : align an address, nop in this implemented )\n\timmediate ;\n\n: ) ( -- : do nothing, this allows easy commenting out of code )\n\timmediate ;\n\n: bell ( -- : emit an ASCII BEL character )\n\t7 emit ;\n\n: b\/buf ( -- u : bytes per buffer )\n\t1024 ;\n\n: .d ( x -- x : debug print )\n\tdup . ;\n\n: compile, ( x -- : )\n\t, ;\n\n: >mark ( -- : write a hole into the dictionary and push a pointer to it )\n\there 0 , ;\n\n: r - r> u< ;\n\n: invalidate ( -- : invalidate this Forth core )\n\t1 `invalid ! ;\n\n: signed ( x -- bool : return true if sign bit set )\n\t[ 1 size 8 * 1- lshift ] literal and logical ;\n\n: u>= ( x y -- bool : unsigned greater than or equal to )\n\t2dup u> >r = r> or ;\n\n: u<= ( x y -- bool : unsigned less than or equal to )\n\tu>= not ;\n\n: rdrop ( R: x -- : drop a value from the return stack )\n\tr> ( get caller's return address )\n\tr> ( get value to drop )\n\tdrop ( drop it like it's hot )\n\t>r ; ( return return address )\n\n: rdup\n\tr> ( get caller's return address )\n\tr> ( get value to duplicate )\n\tdup ( ... )\n\t>r >r >r ; ( make it all work )\n\n: chere ( -- c-addr : here as in character address units )\n\there chars> ;\n\n: source ( -- c-addr u )\n\t#tib ( size of input buffer, in characters )\n\ttib ; ( start of input buffer, in characters )\n\n: stdin? ( -- bool : are we reading from standard in? )\n\t`fin @ `stdin @ = ;\n\n: source-id ( -- 0 | -1 | file-id )\n\t( \t\n\tValue Input Source\n\t-1 String\n\t0 Reading from user input \/ standard in\n\tfile-id )\n\t`source-id @\n\t0= if\n\t\tstdin? if 0 else `fin @ then\n\telse\n\t\t-1\n\tthen ;\n\n: under ( x1 x2 -- x1 x1 x2 )\n\t>r dup r> ;\n\n: 2nip ( n1 n2 n3 n4 -- n3 n4 )\n\t>r >r 2drop r> r> ;\n\n: 2over ( n1 n2 n3 n4 \u2013 n1 n2 n3 n4 n1 n2 )\n\t>r >r 2dup r> swap >r swap r> r> -rot ;\n\n: 2swap ( n1 n2 n3 n4 \u2013 n3 n4 n1 n2 )\n\t>r -rot r> -rot ;\n\n: 2tuck ( n1 n2 n3 n4 \u2013 n3 n4 n1 n2 n3 n4 )\n\t2swap 2over ;\n\n: 3drop ( n1 n2 n3 -- )\n\tdrop 2drop ;\n\n: 4drop ( n1 n2 n3 n4 -- )\n\t2drop 2drop ;\n\n: nos1+ ( x1 x2 -- x1+1 x2 : increment the next variable on that stack )\n\tswap 1+ swap ;\n\n: ?dup-if immediate ( x -- x | - : ?dup and if rolled into one! )\n\t['] ?dup , postpone if ;\n\n: ?if ( -- : non destructive if )\n\timmediate ['] dup , postpone if ;\n\n: (hide) ( token -- hide-token : this hides a word from being found by the interpreter )\n\t?dup-if\n\t\tdup @ hidden-mask or swap tuck ! exit\n\tthen 0 ;\n\n: hide ( WORD -- : hide with drop )\n\tfind dup if (hide) then drop ;\n\n: reveal ( hide-token -- : reveal a hidden word )\n\tdup @ hidden-mask invert and swap ! ;\n\n: ?exit ( x -- : exit current definition if not zero )\n\tif rdrop exit then ;\n\n: decimal? ( c -- f : is character a number? )\n\t[char] 0 [ char 9 1+ ] literal within ;\n\n: lowercase? ( c -- f : is character lower case? )\n\t[char] a [ char z 1+ ] literal within ;\n\n: uppercase? ( C -- f : is character upper case? )\n\t[char] A [ char Z 1+ ] literal within ;\n\n: alpha? ( C -- f : is character part of the alphabet? )\n\tdup lowercase? swap uppercase? or ;\n\n: alphanumeric? ( C -- f : is character alphabetic or a number ? )\n\tdup alpha? swap decimal? or ;\n\n: printable? ( c -- bool : is printable, excluding new lines and tables )\n\t32 127 within ;\n\n: >upper ( c -- C : convert char to uppercase iff lower case )\n\tdup lowercase? if bl xor then ;\n\n: >lower ( C -- c : convert char to lowercase iff upper case )\n\tdup uppercase? if bl xor then ;\n\n: <=> ( x y -- z : spaceship operator! )\n\t2dup\n\t> if 2drop -1 exit then\n\t< ;\n\n: start-address ( -- c-addr : push the start address )\n\t`start-address @ ;\n\n: >real-address ( c-addr -- r-addr : convert an interpreter address to a real address )\n\tstart-address + ;\n\n: real-address> ( c-addr -- r-addr : convert a real address to an interpreter address )\n\tstart-address - ;\n\n: peek ( r-addr -- n : )\n\tpad chars> >real-address swap size memory-copy pad @ ;\n\n: poke ( n r-addr -- : )\n\tswap pad ! pad chars> >real-address size memory-copy ;\n\n: die! ( x -- : controls actions when encountering certain errors )\n\t`error-handler ! ;\n\n: start! ( cfa -- : set the word to execute at startup )\n\t`instruction ! ;\t\n\n: warm ( -- : restart the interpreter, warm restart )\n\t1 restart ;\n\n: trip ( x -- x x x : triplicate a number )\n\tdup dup ;\n\n: roll ( xu xu-1 ... x0 u -- xu-1 ... x0 xu : move u+1 items on the top of the stack by u )\n\t[ smudge ] ( un-hide this word so we can call it recursively )\n\tdup 0 >\n\tif\n\t\tswap >r 1- roll r> swap\n\telse\n\t\tdrop\n\tthen ;\nsmudge\n\n: 2rot ( n1 n2 n3 n4 n5 n6 \u2013 n3 n4 n5 n6 n1 n2 )\n\t5 roll 5 roll ;\n\n: s>d ( x -- d : convert a signed value to a double width cell )\n\t( @note the if...else...then is only necessary as this Forths\n\tbooleans are 0 and 1, not 0 and -1 as it usually is )\n\tdup 0< if -1 else 0 then ;\n\n: trace ( level -- : set tracing level )\n\t`debug ! ;\n\n: verbose ( -- : get the log level )\n\t`debug @ ;\n\n: count ( c-addr1 -- c-addr2 u : get a string whose first char is its length )\n\tdup c@ nos1+ ;\n\n: bounds ( x y -- y+x x : make an upper and lower bound )\n\tover + swap ;\n\n: aligned ( unaligned -- aligned : align a pointer )\n\t[ size 1- ] literal +\n\t[ size 1- ] literal invert and ;\n\n: rdepth\n\tmax-core `stack-size @ - r @ swap - ;\n\n: argv ( -- r-addr : push pointer to array of string pointers to program )\n\t`argv @ ;\n\n: argc ( -- u : push the number of arguments in the argv array )\n\t`argc @ ;\n\n: +- ( x1 x2 -- x3 : copy the sign of x1 to x2 giving x3 )\n\t[ sign-bit 1- ] literal and\n\tswap\n\tsign-bit and or ;\n\n: \/string ( c-addr1 u1 u2 -- c-addr2 u2 : advance a string by n characters )\n\tover min rot over + -rot - ;\n\nhide stdin?\n\n: cfa immediate ( find-address -- cfa )\n\t( Given the address of the PWD field of a word this\n\tfunction will return an execution token for the word )\n\t( @todo if < dictionary start PWD is invalid )\n\t ;\n\n: again immediate\n\t( loop unconditionally in a begin-loop:\n\t\tbegin ... again )\n\t['] branch , body ( xt -- a-addr : a-addr is data field of a CREATEd word )\n\\\tcfa 5 + ;\n\n\n: execute ( xt -- : given an execution token, execute the word )\n\t( create a word that pushes the address of a hole to write to.\n\tA literal takes up two words, '!' takes up one, that's right,\n\tsome self modifying code! )\n\t[ here 3 cells + literal ] ( calculate place to write to )\n\t! ( write an execution token to a hole )\n\t[ 0 , ] ; ( this is the hole we write )\n\n( @todo integrate catch\/throw into the interpreter as primitives )\n: catch ( xt -- exception# | 0 : return addr on stack )\n\tsp@ >r ( xt : save data stack pointer )\n\t`handler @ >r ( xt : and previous handler )\n\tr@ `handler ! ( xt : set current handler )\n\texecute ( execute returns if no throw )\n\tr> `handler ! ( restore previous handler )\n\tr> drop ( discard saved stack ptr )\n\t0 ; ( 0 : normal completion )\n\n( @todo use this everywhere )\n: throw ( ??? exception# -- ??? exception# )\n\t?dup-if ( exc# \\ 0 throw is no-op )\n\t\t`handler @ r ! ( exc# : restore prev return stack )\n\t\tr> `handler ! ( exc# : restore prev handler )\n\t\tr> swap >r ( saved-sp : exc# on return stack )\n\t\tsp! drop r> ( exc# : restore stack )\n\t\t( return to the caller of catch because return )\n\t\t( stack is restored to the state that existed )\n\t\t( when catch began execution )\n\tthen ;\n\n: interpret ( c1\" xxx\" ... cn\" xxx\" -- : This word implements the interpreter loop )\n\tbegin\n\t['] read catch\n\t?dup-if [char] ! emit tab . cr then ( exception handler of last resort )\n\tagain ;\n\n: [interpret] ( c1\" xxx\" ... cn\" xxx\" -- : immediate version of interpret )\n\timmediate interpret ;\n\ninterpret ( use the new interpret word, which can catch exceptions )\n\nfind [interpret] cell+ start! ( the word executed on restart is now our new word )\n\n( The following words are using in various control structure related\nwords to make sure they only execute in the correct state )\n\n: ?comp ( -- : error if not compiling )\n\tstate @ 0= if -14 throw then ;\n\n: ?exec ( -- : error if not executing )\n\tstate @ if -22 throw then ;\n\n( begin...while...repeat These are defined in a very \"Forth\" way )\n: while\n\t?comp\n\timmediate postpone if ( branch to repeats THEN ) ;\n\n: whilst postpone while ;\n\n: repeat immediate\n\t?comp\n\tswap ( swap BEGIN here and WHILE here )\n\tpostpone again ( again jumps to begin )\n\tpostpone then ; ( then writes to the hole made in if )\n\n: never ( never...then : reserve space in word )\n\timmediate 0 [literal] postpone if ;\n\n: unless ( bool -- : like IF but execute clause if false )\n\timmediate ?comp ['] 0= , postpone if ;\n\n: endif ( synonym for THEN )\n\timmediate ?comp postpone then ;\n\n( Experimental FOR ... NEXT )\n: for immediate \n\t?comp\n\t['] 1- ,\n\t['] >r ,\n\there ;\n\n: (next) ( -- bool, R: val -- | val+1 )\n\tr> r> 1- dup 0< if drop >r 1 else >r >r 0 then ;\n\n: next immediate\n\t?comp\n\t['] (next) , \n\t['] ?branch , \n\there - , ;\n\n( ==================== Basic Word Set ======================== )\n\n( ==================== DOER\/MAKE ============================= )\n( DOER\/MAKE is a word set that is quite powerful and is\ndescribed in Leo Brodie's book \"Thinking Forth\". It can be\nused to make words whose behavior can change after they\nare defined. It essentially makes the structured use of\nself-modifying code possible, along with the more common\ndefinitions of \"defer\/is\".\n\nAccording to \"Thinking Forth\", it has two purposes:\n\n1. To change the state of a function.\n2. To factor out common phrases of a words definition.\n\nAn example of the first instance:\n\n\tdoer say\n\t: sad \" Good bye, cruel World!\" cr ;\n\t: happy \" Hello, World!\" cr ;\n\n\t: person say ;\n\n\tmake person happy\n\tperson \\ prints \"Good bye, cruel World!\"\n\n\tmake person sad\n\tperson \\ prints \"Hello, World!\"\n\nAn example of the second:\n\n\tdoer op\n\n\t: sum \\ n0 ... nX X -- sum<0..X>\n\t\tmake op + 1 do op loop ;\n\n\t: mul \\ n0 ... nX X -- mul<0..X>\n\t\tmake op * 1 do op loop ;\n\nThe above example is a bit contrived, the definitions and\nfunctionality are too simple for this to be worth factoring\nout, but it shows how you can use DOER\/MAKE. )\n\n: noop ; ( -- : default word to execute for doer, does nothing )\n\n: doer ( c\" xxx\" -- : make a work whose behavior can be changed by make )\n\timmediate ?exec :: ['] noop , (;) ;\n\n: found? ( xt -- xt : thrown an exception if the xt is zero )\n\tdup 0= if -13 throw then ;\n\n( It would be nice to provide a MAKE that worked with\nexecution tokens as well, although \"defer\" and \"is\" can be\nused for that. MAKE expects two word names to be given as\narguments. It will then change the behavior of the first word\nto use the second. MAKE is a state aware word. )\n\n: make immediate ( c1\" xxx\" c2\" xxx\" : change parsed word c1 to execute c2 )\n\tfind found? cell+\n\tfind found?\n\tstate @ if ( compiling )\n\t\tswap postpone 2literal ['] ! ,\n\telse ( command mode )\n\t\tswap !\n\tthen ;\n\n( ==================== DOER\/MAKE ============================= )\n\n( ==================== Extended Word Set ===================== )\n\n: r.s ( -- : print the contents of the return stack )\n\tr>\n\t[char] < emit rdepth (.) drop [char] > emit\n\tspace\n\trdepth dup 0> if dup\n\tbegin dup while r> -rot 1- repeat drop dup\n\tbegin dup while rot dup . >r 1- repeat drop\n\tthen drop cr\n\t>r ;\n\n: log ( u base -- u : command the _integer_ logarithm of u in base )\n\t>r\n\tdup 0= if -11 throw then ( logarithm of zero is an error )\n\t0 swap\n\tbegin\n\t\tnos1+ rdup r> \/ dup 0= ( keep dividing until 'u' is zero )\n\tuntil\n\tdrop 1- rdrop ;\n\n: log2 ( u -- u : compute the _integer_ logarithm of u )\n\t2 log ;\n\n: alignment-bits ( c-addr -- u : get the bits used for aligning a cell )\n\t[ 1 size log2 lshift 1- literal ] and ;\n\n: time ( \" ccc\" -- n : time the number of milliseconds it takes to execute a word )\n\tclock >r\n\tfind found? execute\n\tclock r> - ;\n\n( defer...is is probably not standards compliant, it is still neat! )\n: (do-defer) ( -- self : pushes the location into which it is compiled )\n\tr> dup >r 1- ;\n\n: defer immediate ( \" ccc\" -- , Run Time -- location :\n\tcreates a word that pushes a location to write an execution token into )\n\t?exec\n\t:: ['] (do-defer) , (;) ;\n\n: is ( location \" ccc\" -- : make a deferred word execute a word )\n\tfind found? swap ! ;\n\nhide (do-defer)\n\n( This RECURSE word is the standard Forth word for allowing\nfunctions to be called recursively. A word is hidden from the\ncompiler until the matching ';' is hit. This allows for previous\ndefinitions of words to be used when redefining new words, it\nalso means that words cannot be called recursively unless the\nrecurse word is used.\n\nRECURSE calls the word being defined, which means that it\ntakes up space on the return stack. Words using recursion\nshould be careful not to take up too much space on the return\nstack, and of course they should terminate after a finite\nnumber of steps.\n\nWe can test \"recurse\" with this factorial function:\n\n : factorial dup 2 < if drop 1 exit then dup 1- recurse * ;\n\n)\n: recurse immediate\n\t?comp\n\tlatest cell+ , ;\n\n: myself ( -- : myself is a synonym for recurse )\n\timmediate postpone recurse ;\n\n( The \"tail\" function implements tail calls, which is just a\njump to the beginning of the words definition, for example\nthis word will never overflow the stack and will print \"1\"\nfollowed by a new line forever,\n\n\t: forever 1 . cr tail ;\n\nWhereas\n\n\t: forever 1 . cr recurse ;\n\nor\n\n\t: forever 1 . cr forever ;\n\nWould overflow the return stack. )\n\nhide tail\n: tail ( -- : perform tail recursion in current word definition )\n\timmediate\n\t?comp\n\tlatest cell+\n\t['] branch ,\n\there - cell+ , ;\n\n( @todo better version of this )\n: factorial ( u -- u : factorial of u )\n\tdup 2 u< if drop 1 exit then dup 1- recurse * ;\n\n: permutations ( u1 u2 -- u : number of ordered combinations )\n\tover swap - factorial swap factorial swap \/ ;\n\n: combinations ( u1 u2 -- u : number of unordered combinations )\n\tdup dup permutations >r permutations r> \/\n\t;\n\n: average ( u1 u2 -- u : average of u1 and u2 ) \n\t+ 2\/ ;\n\n: gcd ( u1 u2 -- u : greatest common divisor )\n\tdup if tuck mod tail then drop ;\n\n: lcm ( u1 u2 -- u : lowest common multiple of u1 and u2 )\n\t2dup gcd \/ * ;\n\n( From: https:\/\/en.wikipedia.org\/wiki\/Integer_square_root\n\nThis function computes the integer square root of a number.\n\n@note this should be changed to the iterative algorithm so\nit takes up less space on the stack - not that is takes up\na hideous amount as it is. )\n\n: sqrt ( n -- u : integer square root )\n\tdup 0< if -11 throw then ( does not work for signed values )\n\tdup 2 < if exit then ( return 0 or 1 )\n\tdup ( u u )\n\t2 rshift recurse 2* ( u sc : 'sc' == unsigned small candidate )\n\tdup ( u sc sc )\n\t1+ dup square ( u sc lc lc^2 : 'lc' == unsigned large candidate )\n\t>r rot r> < ( sc lc bool )\n\tif drop else nip then ; ( return small or large candidate respectively )\n\n\n( ==================== Extended Word Set ===================== )\n\n( ==================== For Each Loop ========================= )\n( The foreach word set allows the user to take action over an\nentire array without setting up loops and checking bounds. It\nbehaves like the foreach loops that are popular in other\nlanguages.\n\nThe foreach word accepts a string and an execution token,\nfor each character in the string it passes the current address\nof the character that it should operate on.\n\nThe complexity of the foreach loop is due to the requirements\nplaced on it. It cannot pollute the variable stack with\nvalues it needs to operate on, and it cannot store values in\nlocal variables as a foreach loop could be called from within\nthe execution token it was passed. It therefore has to store\nall of it uses on the return stack for the duration of EXECUTE.\n\nAt the moment it only acts on strings as \"\/string\" only\nincrements the address passed to the word foreach executes\nto the next character address. )\n\n\\ (FOREACH) leaves the point at which the foreach loop\n\\ terminated on the stack, this allows programmer to determine\n\\ if the loop terminated early or not, and at which point.\n\n: (foreach) ( c-addr u xt -- c-addr u : execute xt for each cell in c-addr u\n\treturning number of items not processed )\n\tbegin\n\t\t3dup >r >r >r ( c-addr u xt R: c-addr u xt )\n\t\tnip ( c-addr xt R: c-addr u xt )\n\t\texecute ( R: c-addr u xt )\n\t\tr> r> r> ( c-addr u xt )\n\t\t-rot ( xt c-addr u )\n\t\t1 \/string ( xt c-addr u )\n\t\tdup 0= if rot drop exit then ( End of string - drop and exit! )\n\t\trot ( c-addr u xt )\n\tagain ;\n\n\\ If we do not care about returning early from the foreach\n\\ loop we can instead call FOREACH instead of (FOREACH),\n\\ it simply drops the results (FOREACH) placed on the stack.\n: foreach ( c-addr u xt -- : execute xt for each cell in c-addr u )\n\t(foreach) 2drop ;\n\n\\ RETURN is used for an early exit from within the execution\n\\ token, it leaves the point at which it exited\n: return ( -- n : return early from within a foreach loop function, returning number of items left )\n\trdrop ( pop off this words return value )\n\trdrop ( pop off the calling words return value )\n\trdrop ( pop off the xt token )\n\tr> ( save u )\n\tr> ( save c-addr )\n\trdrop ; ( pop off the foreach return value )\n\n\\ SKIP is an example of a word that uses the foreach loop\n\\ mechanism. It takes a string and a character and returns a\n\\ string that starts at the first occurrence of that character\n\\ in that string - or until it reaches the end of the string.\n\n\\ SKIP is defined in two steps, first there is a word,\n\\ (SKIP), that exits the foreach loop if there is a match,\n\\ if there is no match it does nothing. In either case it\n\\ leaves the character to skip until on the stack.\n\n: (skip) ( char c-addr -- char : exit out of foreach loop if there is a match )\n\tover swap c@ = if return then ;\n\n\\ SKIP then setups up the foreach loop, the char argument\n\\ will present on the stack when (SKIP) is executed, it must\n\\ leave a copy on the stack whatever happens, this is then\n\\ dropped at the end. (FOREACH) leaves the point at which\n\\ the loop terminated on the stack, which is what we want.\n\n: skip ( c-addr u char -- c-addr u : skip until char is found or until end of string )\n\t-rot ['] (skip) (foreach) rot drop ;\nhide (skip)\n\n( ==================== For Each Loop ========================= )\n\n( ==================== Hiding Words ========================== )\n( The two functions hide{ and }hide allow lists of words to\nbe hidden, instead of just hiding individual words. It stops\nthe dictionary from being polluted with meaningless words in\nan easy way. )\n\n: }hide ( should only be matched with 'hide{' )\n\timmediate -22 throw ;\n\n: hide{ ( -- : hide a list of words, the list is terminated with \"}hide\" )\n\t?exec\n\tbegin\n\t\tfind ( find next word )\n\t\tdup [ find }hide ] literal = if\n\t\t\tdrop exit ( terminate hide{ )\n\t\tthen\n\t\tdup 0= if -15 throw then\n\t\t(hide) drop\n\tagain ;\n\nhide (hide)\n\n( ==================== Hiding Words ========================== )\n\n( The words described here on out get more complex and will\nrequire more of an explanation as to how they work. )\n\n( ==================== Create Does> ========================== )\n\n( The following section defines a pair of words \"create\"\nand \"does>\" which are a powerful set of words that can be\nused to make words that can create other words. \"create\"\nhas both run time and compile time behavior, whilst \"does>\"\nonly works at compile time in conjunction with \"create\". These\ntwo words can be used to add constants, variables and arrays\nto the language, amongst other things.\n\nA simple version of create is as follows\n\n\t: create :: dolist , here 2 cells + , ' exit , 0 state ! ;\n\nBut this version is much more limited.\n\n\"create\"...\"does>\" is one of the constructs that makes Forth\nForth, it allows the creation of words which can define new\nwords in themselves, and thus allows us to extend the language\neasily. )\n\n: write-exit ( -- : A word that write exit into the dictionary )\n\t['] _exit , ;\n\n: write-compile, ( -- : A word that writes , into the dictionary )\n\t['] , , ;\n\n: create ( create a new work that pushes its data field )\n\t:: ( compile a word )\n\tdolit , ( write push into new word )\n\there 2 cells + , ( push a pointer to data field )\n\t(;) ; ( write exit, switch to command mode )\n\n: mark write-compile, ( Write in a place holder 0 and push a pointer to to be used by does> )\n\tdolit , write-exit write-compile, ( Write in an exit in the word we're compiling. )\n\t['] [ , ; ( Make sure to change the state back to command mode )\n\n\\ : ( hole-to-patch -- )\n\timmediate\n\t?comp\n\twrite-exit ( we don't want the defining word to exit, but the *defined* word to )\n\there swap ! ( patch in the code fields to point to )\n\tdolist , ; ( write a run in )\n\nhide{ write-compile, write-exit }hide\n\n( Now that we have create...does> we can use it to create\narrays, variables and constants, as we mentioned before. )\n\n: array ( u c\" xxx\" -- : create a named array of length u )\n\tcreate allot does> + ;\n\n: variable ( x c\" xxx\" -- : create a variable will initial value of x )\n\tcreate , does> ;\n\n\\ : constant ( x c\" xxx\" -- : create a constant with value of x )\n\\\tcreate , does> @ ;\n\n: table ( u c\" xxx\" --, Run Time: -- addr u : create a named table )\n\tcreate dup , allot does> dup @ ;\n\n: string ( u c\" xxx\" --, Run Time: -- c-addr u : create a named string )\n\tcreate dup , chars allot does> dup @ swap 1+ chars> swap ;\n\n\\ : +field \\ n <\"name\"> -- ; exec: addr -- 'addr\n\\ create over , +\n\\ does> @ + ;\n\\\n\\ : begin-structure \\ -- addr 0 ; -- size\n\\ \tcreate\n\\ \there 0 0 , \\ mark stack, lay dummy\n\\ \tdoes> @ ; \\ -- rec-len\n\\\n\\ : end-structure \\ addr n --\n\\ swap ! ; \\ set len\n\\\n\\ begin-structure point\n\\ \tpoint +field p.x\n\\ \tpoint +field p.y\n\\ end-structure\n\\\n\\ This should work...\n\\ : buffer: ( u c\" xxx\" --, Run Time: -- addr )\n\\\tcreate allot ;\n\n: 2constant\n\tcreate , , does> dup 1+ @ swap @ ;\n\n: 2variable\n\tcreate , , does> ;\n\n: enum ( x \" ccc\" -- x+1 : define a series of enumerations )\n\tdup constant 1+ ;\n\n( ==================== Create Does> ========================== )\n\n( ==================== Do ... Loop =========================== )\n\n( The following section implements Forth's do...loop\nconstructs, the word definitions are quite complex as it\ninvolves a lot of juggling of the return stack. Along with\nbegin...until do loops are one of the main looping constructs.\n\nUnlike begin...until do accepts two values a limit and a\nstarting value, they are also words only to be used within a\nword definition, some Forths extend the semantics so looping\nconstructs operate in command mode, this Forth does not do\nthat as it complicates things unnecessarily.\n\nExample:\n\n\t: example-1\n\t\t10 1 do\n\t\t\ti . i 5 > if cr leave then loop\n\t\t100 . cr ;\n\n\texample-1\n\nPrints:\n\t1 2 3 4 5 6\n\nIn \"example-1\" we can see the following:\n\n1. A limit, 10, and a start value, 1, passed to \"do\".\n2. A word called 'i', which is the current count of the loop.\n3. If the count is greater than 5, we call a word call\nLEAVE, this word exits the current loop context as well as\nthe current calling word.\n4. \"100 . cr\" is never called. This should be changed in\nfuture revision, but this version of leave exits the calling\nword as well.\n\n'i', 'j', and LEAVE *must* be used within a do...loop\nconstruct.\n\nIn order to remedy point 4. loop should not use branch but\ninstead should use a value to return to which it pushes to\nthe return stack )\n\n: (do)\n\tswap ( swap the limit and start )\n\tr> ( save our return stack to temporary variable )\n\t-rot ( limit start return -- return start limit )\n\t>r ( push limit onto return stack )\n\t>r ( push start onto return stack )\n\t>r ; ( restore our return address )\n\n: do immediate ( Run time: high low -- : begin do...loop construct )\n\t?comp\n\t['] (do) ,\n\tpostpone begin ;\n\n: (unloop) ( -- , R: i limit -- : remove limit and i from )\n\tr> ( save our return address )\n\trdrop ( pop off i )\n\trdrop ( pop off limit )\n\t>r ; ( restore our return stack )\n\n: (+loop) ( x -- bool : increment loop variable by x and test it )\n\tr@ 1- ( get the pointer to i )\n\t+! ( add value to it )\n\tr@ 1- @ ( find i again )\n\tr@ 2- @ ( find the limit value )\n\tu>= ;\n\n: (loop) ( -- bool : increment loop variable by 1 and test it )\n\tr@ 1- ( get the pointer to i )\n\t1+! ( add one to it )\n\tr@ 1- @ ( find the value again )\n\tr@ 2- @ ( find the limit value )\n\tu>= ;\n\n: loop ( -- : end do...loop construct )\n\timmediate ?comp ['] (loop) , postpone until ['] (unloop) , ;\n\n: +loop ( x -- : end do...+loop loop construct )\n\timmediate ?comp ['] (+loop) , postpone until ['] (unloop) , ;\n\n: leave ( -- , R: i limit return -- : break out of a do-loop construct )\n\t(unloop)\n\trdrop ; ( return to the caller's caller routine )\n\n: ?leave ( x -- , R: i limit return -- | i limit return : conditional leave )\n\tif\n\t\t(unloop)\n\t\trdrop ( return to the caller's caller routine )\n\tthen ;\n\n\\ @todo define '(i)', '(j)' and '(k)', then make their\n\\ wrappers, 'i', 'j' and 'k' call ?comp then compile a pointer\n\\ to the thing that implements them, likewise for leave,\n\\ loop and +loop.\n: i ( -- i : Get current, or innermost, loop index in do...loop construct )\n\tr> r> ( pop off return address and i )\n\ttuck ( tuck i away )\n\t>r >r ; ( restore return stack )\n\n: j ( -- j : Get outermost loop index in do...loop construct )\n\t4 rpick ;\n\n( This is a simple test function for the looping, for interactive\ntesting and debugging:\n : mm 5 1 do i . cr 4 1 do j . tab i . cr loop loop ; )\n\n: range ( nX nY -- nX nX+1 ... nY )\n\tnos1+ do i loop ;\n\n: repeater ( n0 X -- n0 ... nX )\n\t1 do dup loop ;\n\n: sum ( n0 ... nX X -- sum<0..X> )\n\t1 do + loop ;\n\n: mul ( n0 ... nX X -- mul<0..X> )\n\t1 do * loop ;\n\n: reverse ( x1 ... xn n -- xn ... x1 : reverse n items on the stack )\n\t0 do i roll loop ;\n\ndoer (banner)\nmake (banner) space\n\n: banner ( n -- : )\n\tdup 0<= if drop exit then\n\t0 do (banner) loop ;\n\n: zero ( -- : emit a single 0 character )\n\t[char] 0 emit ;\n\n: spaces ( n -- : print n spaces if n is greater than zero )\n\tmake (banner) space\n\tbanner ;\n\n: zeros ( n -- : print n spaces if n is greater than zero )\n\tmake (banner) zero\n\tbanner ;\n\nhide{ (banner) banner }hide\n\n( @todo check u for negative )\n: fill ( c-addr u char -- : fill in an area of memory with a character, only if u is greater than zero )\n\t-rot\n\t0 do 2dup i + c! loop\n\t2drop ;\n\n: default ( addr u n -- : fill in an area of memory with a cell )\n\t-rot\n\t0 do 2dup i cells + ! loop\n\t2drop ;\n\n: compare ( c-addr1 u1 c-addr2 u2 -- n : compare two strings, not quite compliant yet )\n\t>r swap r> min >r\n\tstart-address + swap start-address + r>\n\tmemory-compare ;\n\n: erase ( addr u : erase a block of memory )\n\t2chars> 0 fill ;\n\n: blank ( c-addr u : fills a string with spaces )\n\tbl fill ;\n\n( move should check that u is not negative )\n: move ( addr1 addr2 u -- : copy u words of memory from 'addr2' to 'addr1' )\n\t0 do\n\t\t2dup i + @ swap i + !\n\tloop\n\t2drop ;\n\n( It would be nice if move and cmove could share more code, as they do exactly\n the same thing but with different load and store functions, cmove> )\n: cmove ( c-addr1 c-addr2 u -- : copy u characters of memory from 'c-addr2' to 'c-addr1' )\n\t0 do\n\t\t2dup i + c@ swap i + c!\n\tloop\n\t2drop ;\n\n\n\n( ==================== Do ... Loop =========================== )\n\n( ==================== String Substitution =================== )\n\n: (subst) ( char1 char2 c-addr )\n\t3dup ( char1 char2 c-addr char1 char2 c-addr )\n\tc@ = if ( char1 char2 c-addr char1 )\n\t\tswap c! ( match, substitute character )\n\telse ( char1 char2 c-addr char1 )\n\t\t2drop ( no match )\n\tthen ;\n\n: subst ( c-addr u char1 char2 -- replace all char1 with char2 in string )\n\tswap\n\t2swap\n\t['] (subst) foreach 2drop ;\nhide (subst)\n\n0 variable c\n0 variable sub\n0 variable #sub\n\n: (subst-all) ( c-addr : search in sub\/#sub for a character to replace at c-addr )\n\tsub @ #sub @ bounds ( get limits )\n\tdo\n\t\tdup ( duplicate supplied c-addr )\n\t\tc@ i c@ = if ( check if match )\n\t\t\tdup\n\t\t\tc chars c@ swap c! ( write out replacement char )\n\t\tthen\n\tloop drop ;\n\n: subst-all ( c-addr1 u c-addr2 u char -- replace chars in str1 if in str2 with char )\n\tc chars c! #sub ! sub ! ( store strings away )\n\t['] (subst-all) foreach ;\n\nhide{ c sub #sub (subst-all) }hide\n\n( ==================== String Substitution =================== )\n\n0 variable column-counter\n4 variable column-width\n\n: column ( i -- )\t\n\tcolumn-width @ mod not if cr then ;\n\n: column.reset\t\t\n\t0 column-counter ! ;\n\n: auto-column\t\t\n\tcolumn-counter dup @ column 1+! ;\n\n0 variable x\n: x! ( x -- )\n\tx ! ;\n\n: x@ ( -- x )\n\tx @ ;\n\n: 2>r ( x1 x2 -- R: x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tswap\n\t\t>r\n\t\t>r\n\tx@ >r ; ( restore return address )\n\n: 2r> ( R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tr>\n\t\tr>\n\t\tswap\n\tx@ >r ; ( restore return address )\n\n: 2r@ ( -- x1 x2 , R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\tr> r>\n\t2dup\n\t>r >r\n\tswap\n\tx@ >r ; ( restore return address )\n\n: unused ( -- u : push the amount of core left )\n\tmax-core here - ;\n\n: accumulator ( initial \" ccc\" -- : make a word that increments by a value and pushes the result )\n\tcreate , does> tuck +! @ ;\n\n: counter ( n \" ccc\" --, Run Time: -- x : make a word that increments itself by one, starting from 'n' )\n\tcreate 1- , does> dup 1+! @ ;\n\n0 variable delim\n: accepter ( c-addr max delimiter -- i )\n\t( store a \"max\" number of chars at c-addr until \"delimiter\" encountered,\n\tthe number of characters stored is returned )\n\tdelim ! ( store delimiter used to stop string storage when encountered)\n\t0\n\tdo\n\t\tkey dup delim @ <>\n\t\tif\n\t\t\tover c! 1+\n\t\telse ( terminate string )\n\t\t\tdrop 0 swap c!\n\t\t\ti\n\t\t\tleave\n\t\tthen\n\tloop\n\t-18 throw ; ( read in too many chars )\nhide delim\n\n: skip ( char -- : read input until string is reached )\n\tkey drop >r 0 begin drop key dup rdup r> <> until rdrop ;\n\n: word ( c -- c-addr : parse until 'c' is encountered, push transient counted string )\n\ttib #tib 0 fill ( zero terminal input buffer so we NUL terminate string )\n\tdup skip tib 1+ c!\n\t>r\n\ttib 2+\n\t#tib 1-\n\tr> accepter 1+\n\ttib c!\n\ttib ;\nhide skip\n\n: accept ( c-addr +n1 -- +n2 : see accepter definition )\n\tnl accepter ;\n\n0xFFFF constant max-string-length\n\n: (.\") ( char -- c-addr u )\n\t( @todo This really needs simplifying, to do this\n\ta set of words that operate on a temporary buffer can\n\tbe used )\n\t( Write a string into word being currently defined, this\n\tcode has to jump over the string it has just put into the\n\tdictionary so normal execution of a word can continue. The\n\tlength and character address of the string are left on the\n\tstack )\n\t>r ( save delimiter )\n\t['] branch , ( write in jump, this will jump past the string )\n\t>mark ( make hole )\n\tdup 1+ chars> ( calculate address to write to )\n\tmax-string-length\n\tr> ( restore delimiter )\n\taccepter dup >r ( write string into dictionary, save index )\n\taligned 2dup size \/ ( stack: length hole char-len hole )\n\t1+ dup allot ( update dictionary pointer with string length )\n\t1+ swap ! ( write place to jump to )\n\tdrop ( do not need string length anymore )\n\t1+ chars> ( calculate place to print )\n\tr> ; ( restore index and address of string )\n\n: length ( c-addr u -- u : push the length of an ASCIIZ string )\n tuck 0 do dup c@ 0= if 2drop i leave then 1+ loop ;\n\n: asciiz? ( c-addr u -- : is a Forth string also a ASCIIZ string )\n\ttuck length <> ;\n\n: asciiz ( c-addr u -- : trim a string until NUL terminator )\n\t2dup length nip ;\n\n: (type) ( c-addr -- : emit a single character )\n\tc@ emit ;\n\n: type ( c-addr u -- : print out 'u' characters at c-addr )\n\t['] (type) foreach ;\nhide (type)\n\n: do-string ( char -- : write a string into the dictionary reading it until char is encountered )\n\t(.\")\n\tstate @ if swap [literal] [literal] then ;\n\n128 string sbuf\n: s\" ( \"ccc\" --, Run Time -- c-addr u )\n\tkey drop sbuf 0 fill sbuf [char] \" accepter sbuf drop swap ;\nhide sbuf\n\n( @todo these strings really need rethinking, state awareness needs to be removed... )\n: type,\n\tstate @ if ['] type , else type then ;\n\n: c\"\n\timmediate key drop [char] \" do-string ;\n\n: \"\n\timmediate key drop [char] \" do-string type, ;\n\n: sprint ( c -- : print out chars until 'c' is encountered )\n\tkey drop ( drop next space )\n\t>r ( save delimiter )\n\tbegin\n\t\tkey dup ( get next character )\n\t\trdup r> ( get delimiter )\n\t\t<> if emit 0 then\n\tuntil rdrop ;\n\n: .(\n\timmediate [char] ) sprint ;\nhide sprint\n\n: .\"\n\timmediate key drop [char] \" do-string type, ;\n\nhide type,\n\n( This word really should be removed along with any usages\nof this word, it is not a very \"Forth\" like word, it accepts\na pointer to an ASCIIZ string and prints it out, it also does\nnot checking of the returned values from write-file )\n: print ( c-addr -- : print out a string to the standard output )\n\t-1 over >r length r> swap stdout write-file 2drop ;\n\n: ok\n\t\" ok\" cr ;\n\n: empty-stack ( x-n ... x-0 -- : empty the variable stack )\n\tbegin depth while drop repeat ;\n\n: (quit) ( -- : do the work of quit, without the restart )\n\t0 `source-id ! ( set source to read from file )\n\t`stdin @ `fin ! ( read from stdin )\n\tpostpone [ ( back into command mode )\n\t['] interpret start! ; ( set interpreter starting word )\n\n: quit ( -- : Empty return stack, go back to command mode, read from stdin, interpret input )\n\t(quit)\n\t-1 restart ; ( restart the interpreter )\n\n: abort\n\t-1 throw ;\n\n: (abort\") ( do the work of abort )\n\t(quit)\n\t-2 throw ;\n\n: abort\" immediate\n\tpostpone \"\n\t['] cr , ['] (abort\") , ;\n\n\n( ==================== Error Messages ======================== )\n( This section implements a look up table for error messages,\nthe word MESSAGE was inspired by FIG-FORTH, words like ERROR\nwill be implemented later.\n\nThe DPANS standard defines a range of numbers which correspond\nto specific errors, the word MESSAGE can decode these numbers\nby looking up known words in a table.\n\nSee: http:\/\/lars.nocrew.org\/dpans\/dpans9.htm\n\n Code Reserved for\n ---- ------------\n -1 ABORT\n -2 ABORT\"\n -3 stack overflow\n -4 stack underflow\n -5 return stack overflow\n -6 return stack underflow\n -7 do-loops nested too deeply during execution\n -8 dictionary overflow\n -9 invalid memory address\n -10 division by zero\n -11 result out of range\n -12 argument type mismatch\n -13 undefined word\n -14 interpreting a compile-only word\n -15 invalid FORGET\n -16 attempt to use zero-length string as a name\n -17 pictured numeric output string overflow\n -18 parsed string overflow\n -19 definition name too long\n -20 write to a read-only location\n -21 unsupported operation [e.g., AT-XY on a\n too-dumb terminal]\n -22 control structure mismatch\n -23 address alignment exception\n -24 invalid numeric argument\n -25 return stack imbalance\n -26 loop parameters unavailable\n -27 invalid recursion\n -28 user interrupt\n -29 compiler nesting\n -30 obsolescent feature\n -31 >BODY used on non-CREATEd definition\n -32 invalid name argument [e.g., TO xxx]\n -33 block read exception\n -34 block write exception\n -35 invalid block number\n -36 invalid file position\n -37 file I\/O exception\n -38 non-existent file\n -39 unexpected end of file\n -40 invalid BASE for floating point conversion\n -41 loss of precision\n -42 floating-point divide by zero\n -43 floating-point result out of range\n -44 floating-point stack overflow\n -45 floating-point stack underflow\n -46 floating-point invalid argument\n -47 compilation word list deleted\n -48 invalid POSTPONE\n -49 search-order overflow\n -50 search-order underflow\n -51 compilation word list changed\n -52 control-flow stack overflow\n -53 exception stack overflow\n -54 floating-point underflow\n -55 floating-point unidentified fault\n -56 QUIT\n -57 exception in sending or receiving a character\n -58 [IF], [ELSE], or [THEN] exception )\n\n( The word X\" compiles a counted string into a word definition, it\nis useful as a space saving measure and simplifies our lookup table\ndefinition. Instead of having to store a C-ADDR and it's length, we\nonly have to store a C-ADDR in the lookup table, which occupies only\none element instead of two. The strings used for error messages are\nshort, so the limit of 256 characters that counted strings present\nis not a problem. )\n\n: x\" immediate ( c\" xxx\" -- c-addr : compile a counted string )\n\t[char] \" word ( read in a counted string )\n\tcount -1 \/string dup ( go back to start of string )\n\tpostpone never >r ( make a hole in the dictionary )\n\tchere >r ( character marker )\n\taligned chars allot ( allocate space in hole )\n\tr> dup >r -rot cmove ( copy string from word buffer )\n\tr> ( restore pointer to counted string )\n\tr> postpone then ; ( finish hole )\n\ncreate lookup 64 cells allot ( our lookup table )\n\n: nomsg ( -- c-addr : push counted string to undefined error message )\n\tx\" Undefined Error\" literal ;\n\nlookup 64 cells find nomsg default\n\n1 variable warning\n\n: message ( n -- : print an error message )\n\twarning @ 0= if . exit then\n\tdup -63 1 within if abs lookup + @ count type exit then\n\tdrop nomsg count type ;\n\n1 counter #msg\n\n: nmsg ( n -- : populate next slot in available in LOOKUP )\n\tlookup #msg cells + ! ;\n\nx\" ABORT\" nmsg\nx\" ABORT Double Quote\" nmsg\nx\" stack overflow\" nmsg\nx\" stack underflow\" nmsg\nx\" return stack overflow\" nmsg\nx\" return stack underflow\" nmsg\nx\" do-loops nested too deeply during execution\" nmsg\nx\" dictionary overflow\" nmsg\nx\" invalid memory address\" nmsg\nx\" division by zero\" nmsg\nx\" result out of range\" nmsg\nx\" argument type mismatch\" nmsg\nx\" undefined word\" nmsg\nx\" interpreting a compile-only word\" nmsg\nx\" invalid FORGET\" nmsg\nx\" attempt to use zero-length string as a name\" nmsg\nx\" pictured numeric output string overflow\" nmsg\nx\" parsed string overflow\" nmsg\nx\" definition name too long\" nmsg\nx\" write to a read-only location\" nmsg\nx\" unsupported operation \" nmsg\nx\" control structure mismatch\" nmsg\nx\" address alignment exception\" nmsg\nx\" invalid numeric argument\" nmsg\nx\" return stack imbalance\" nmsg\nx\" loop parameters unavailable\" nmsg\nx\" invalid recursion\" nmsg\nx\" user interrupt\" nmsg\nx\" compiler nesting\" nmsg\nx\" obsolescent feature\" nmsg\nx\" >BODY used on non-CREATEd definition\" nmsg\nx\" invalid name argument \" nmsg\nx\" block read exception\" nmsg\nx\" block write exception\" nmsg\nx\" invalid block number\" nmsg\nx\" invalid file position\" nmsg\nx\" file I\/O exception\" nmsg\nx\" non-existent file\" nmsg\nx\" unexpected end of file\" nmsg\nx\" invalid BASE for floating point conversion\" nmsg\nx\" loss of precision\" nmsg\nx\" floating-point divide by zero\" nmsg\nx\" floating-point result out of range\" nmsg\nx\" floating-point stack overflow\" nmsg\nx\" floating-point stack underflow\" nmsg\nx\" floating-point invalid argument\" nmsg\nx\" compilation word list deleted\" nmsg\nx\" invalid POSTPONE\" nmsg\nx\" search-order overflow\" nmsg\nx\" search-order underflow\" nmsg\nx\" compilation word list changed\" nmsg\nx\" control-flow stack overflow\" nmsg\nx\" exception stack overflow\" nmsg\nx\" floating-point underflow\" nmsg\nx\" floating-point unidentified fault\" nmsg\nx\" QUIT\" nmsg\nx\" exception in sending or receiving a character\" nmsg\nx\" [IF], [ELSE], or [THEN] exception\" nmsg\n\nhide{ nmsg #msg nomsg }hide\n \n\n( ==================== Error Messages ======================== )\n\n\n( ==================== CASE statements ======================= )\n( This simple set of words adds case statements to the\ninterpreter, the implementation is not particularly efficient,\nbut it works and is simple.\n\nBelow is an example of how to use the CASE statement,\nthe following word, \"example\" will read in a character and\nswitch to different statements depending on the character\ninput. There are two cases, when 'a' and 'b' are input, and\na default case which occurs when none of the statements match:\n\n\t: example\n\t\tchar\n\t\tcase\n\t\t\t[char] a of \" a was selected \" cr endof\n\t\t\t[char] b of \" b was selected \" cr endof\n\n\t\t\tdup \\ encase will drop the selector\n\t\t\t\" unknown char: \" emit cr\n\t\tendcase ;\n\n\texample a \\ prints \"a was selected\"\n\texample b \\ prints \"b was selected\"\n\texample c \\ prints \"unknown char: c\"\n\nOther examples of how to use case statements can be found\nthroughout the code.\n\nFor a simpler case statement see, Volume 2, issue 3, page 48\nof Forth Dimensions at http:\/\/www.forth.org\/fd\/contents.html )\n\n: case immediate\n\t?comp\n\t['] branch , 3 cells , ( branch over the next branch )\n\there ['] branch , ( mark: place endof branches back to with again )\n\t>mark swap ; ( mark: place endcase writes jump to with then )\n\n: over= ( x y -- [x 0] | 1 : )\n\tover = if drop 1 else 0 then ;\n\n: of\n\timmediate ?comp ['] over= , postpone if ;\n\n: endof\n\timmediate ?comp over postpone again postpone then ;\n\n: endcase\n\timmediate ?comp ['] drop , 1+ postpone then drop ;\n\n( ==================== CASE statements ======================= )\n\n( ==================== Conditional Compilation =============== )\n( The words \"[if]\", \"[else]\" and \"[then]\" implement conditional\ncompilation, they can be nested as well\n\nSee http:\/\/lars.nocrew.org\/dpans\/dpans15.htm for more\ninformation\n\nA much simpler conditional compilation method is the following\nsingle word definition:\n\n : compile-line? 0= if [ find \\\\ , ] then ;\n\nWhich will skip a line if a conditional is false, and compile\nit if true )\n\n( These words really, really need refactoring, I could use the newly defined\n \"defer\" to help out with this )\n0 variable nest ( level of [if] nesting )\n0 variable [if]-word ( populated later with \"find [if]\" )\n0 variable [else]-word ( populated later with \"find [else]\")\n: [then] immediate ;\n: reset-nest 1 nest ! ;\n: unnest? [ find [then] ] literal = if nest 1-! then ;\n: nest? [if]-word @ = if nest 1+! then ;\n: end-nest? nest @ 0= ;\n: match-[else]? [else]-word @ = nest @ 1 = and ;\n\n: [if] ( bool -- : conditional execution )\n\t?exec\n\tunless\n\t\treset-nest\n\t\tbegin\n\t\t\tfind\n\t\t\tdup nest?\n\t\t\tdup match-[else]? if drop exit then\n\t\t\t unnest?\n\t\t\tend-nest?\n\t\tuntil\n\tthen ;\n\n: [else] ( discard input until [then] encounter, nesting for [if] )\n\t?exec\n\treset-nest\n\tbegin\n\t\tfind\n\t\tdup nest? unnest?\n\t\tend-nest?\n\tuntil ;\n\nfind [if] [if]-word !\nfind [else] [else]-word !\n\n: ?( if postpone ( then ; \\ conditionally read until ')'\n: ?\\ if postpone \\ then ;\n: 16bit\\ size 2 <> if postpone \\ then ;\n: 32bit\\ size 4 <> if postpone \\ then ;\n: 64bit\\ size 8 <> if postpone \\ then ;\n\nhide{\n\t[if]-word [else]-word nest\n\treset-nest unnest? match-[else]?\n\tend-nest? nest?\n}hide\n\n( ==================== Conditional Compilation =============== )\n\n( ==================== Endian Words ========================== )\n( This words are allow the user to determinate the endianess\nof the machine that is currently being used to execute libforth,\nthey make heavy use of conditional compilation )\n\n0 variable x\n\nsize 2 = [if] 0x0123 x ! [then]\nsize 4 = [if] 0x01234567 x ! [then]\nsize 8 = [if] 0x01234567abcdef x ! [then]\n\nx chars> c@ 0x01 = constant endian\n\nhide{ x }hide\n\n: swap16 ( x -- x : swap the byte order of a 16 bit number )\n\tdup 256* 0xff00 and >r 256\/ lsb r> or ;\n\nsize 4 >= [if]\n\t: swap32\n\t\tdup 0xffff and swap16 16 lshift swap\n\t\t16 rshift 0xffff and swap16 or ;\n[then]\n\nsize 8 >= [if]\n\t: swap64 ( x -- x : swap the byte order of a 64 bit number )\n\t\t dup 0xffffffff and swap32 32 lshift swap\n\t\t 32 rshift 0xffffffff and swap32 or ;\n[then]\n\nsize 2 = [if]\n\tendian\n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order )\n\t\tswap16 ;\n\t: >big ( x -- x : host byte order to big endian order )\n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order )\n\t\t;\n\t: >big ( x -- x : host byte order to big endian order )\n\t\tswap16 ;\n\t[then]\n[then]\n\nsize 4 = [if]\n\tendian\n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order )\n\t\tswap32 ;\n\t: >big ( x -- x : host byte order to big endian order )\n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order )\n\t\t;\n\t: >big ( x -- x : host byte order to big endian order )\n\t\tswap32 ;\n\t[then]\n[then]\n\nsize 8 = [if]\n\tendian\n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order )\n\t\tswap64 ;\n\t: >big ( x -- x : host byte order to big endian order )\n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order )\n\t\t;\n\t: >big ( x -- x : host byte order to big endian order )\n\t\tswap64 ;\n\t[then]\n[then]\n\n( ==================== Endian Words ========================== )\n\n( ==================== Misc words ============================ )\n\n: (base) ( -- base : unmess up libforth's base variable )\n\tbase @ dup 0= if drop 10 then ;\n\n: #digits ( u -- u : number of characters needed to represent 'u' in current base )\n\tdup 0= if 1+ exit then\n\t(base) log 1+ ;\n\n: digits ( -- u : number of characters needed to represent largest unsigned number in current base )\n\t-1 #digits ;\n\n: cdigits ( -- u : number of characters needed to represent largest characters in current base )\n\t0xff #digits ;\n\n: .r ( u -- print a number taking up a fixed amount of space on the screen )\n\tdup #digits digits swap - spaces . ;\n\n: ?.r ( u -- : print out address, right aligned )\n\t@ .r ;\n\n0 variable counter\n\n: counted-column ( index -- : special column printing for dump )\n\tcounter @ column-width @ mod\n\tnot if cr .r \" :\" space else drop then\n\tcounter 1+! ;\n\n: .chars ( x n -- : print a cell out as characters, upto n chars )\n\t0 ( from zero to the size of a cell )\n\tdo\n\t\tdup ( copy variable to print out )\n\t\tsize i 1+ - select-byte ( select correct byte )\n\t\tdup printable? not ( is it not printable )\n\t\tif drop [char] . then ( print a '.' if it is not )\n\t\temit ( otherwise print it out )\n\tloop\n\tdrop ; ( drop cell we have printed out )\n\n: lister ( addr u addr -- )\n\t0 counter ! 1- swap\n\tdo\n\t\tdup counted-column 1+ i ?.r i @ size .chars space\n\tloop ;\n\n( @todo this function should make use of DEFER and IS, then different\nversion of dump could be made that swapped out LISTER )\n: dump ( addr u -- : dump out 'u' cells of memory starting from 'addr' )\n\t1+ over + under lister drop\n\tcr ;\n\nhide{ counted-column counter }hide\n\n( Fence can be used to prevent any word defined before it from being forgotten\nUsage:\n\there fence ! )\n0 variable fence\n\n: ?fence ( addr -- : throw an exception of address is before fence )\n\tfence @ u< if -15 throw then ;\n\n: (forget) ( pwd-token -- : forget a found word and everything after it )\n\tdup 0= if -15 throw then ( word not found! )\n\tdup ?fence\n\tdup @ pwd ! h ! ;\n\n: forget ( c\" xxx\" -- : forget word and every word defined after it )\n\tfind 1- (forget) ;\n\n0 variable fp ( FIND Pointer )\n\n: rendezvous ( -- : set up a rendezvous point )\n\there ?fence\n\there fence !\n\tlatest fp ! ;\n\n: retreat ( -- : retreat to the rendezvous point, forgetting any words )\n\tfence @ h !\n\tfp @ pwd ! ;\n\nhide{ fp }hide\n\n: marker ( c\" xxx\" -- : make word the forgets itself and words after it)\n\t:: latest [literal] ['] (forget) , (;) ;\nhere fence ! ( This should also be done at the end of the file )\nhide (forget)\n\n: ** ( b e -- x : exponent, raise 'b' to the power of 'e')\n\t?dup-if\n\t\tover swap\n\t\t1 do over * loop\n\t\tnip\n\telse\n\t\tdrop 1\n\tthen ;\n\n0 variable a\n0 variable b\n0 variable m\n: equal ( a1...an b1...bn n -- a1...an b1...bn bool : determine if two lists are equal )\n\t( example:\n\t\t1 2 3\n\t\t1 2 3\n\t\t3 equal\n\treturns: 1 )\n\tdup m ! 1+ 1 ( store copy of length and use as loop index )\n\tdo\n\t\ti 1- pick b ! ( store ith element of list in b1...bn )\n\t\ti m @ + 1- pick a ! ( store ith element of list in a1...an )\n\t\ta @ b @ <> ( compare a and b for equality )\n\t\tif 0 leave then ( unequal, finish early )\n\tloop 1 ; ( lists must be equal )\n\nhide{ a b m }hide\n\n: ndrop ( u1...un n -- : drop n items )\n\t?dup-if 0 do drop loop then ;\n\n: caesar ( c key -- o : encode a alphabetic character with a key using a generalization of the Caesar cipher )\n\t>r\n\tdup uppercase? if [char] A - r> + 26 mod [char] A + exit then\n\tdup lowercase? if [char] a - r> + 26 mod [char] a + exit then\n\trdrop ; ( it goes without saying that this should not be used for anything serious! )\n\n: caesar-type ( c-addr u key : type out encoded text with a Caesar cipher )\n\t-rot bounds do i c@ over caesar emit loop drop ;\n\n: rot13 ( c -- c : encode a character with ROT-13 )\n\t13 caesar ;\n\n: rot13-type ( c-addr u : print string in ROT-13 encoded form )\n\t13 caesar-type ;\n\n\\ s\" abcdefghijklmnopqrstuvwxyz\" rot13-type -> nopqrstuvwxyzabcdefghijklm\n\\ s\" hello\" rot13-type -> uryyb\n\n( ==================== Misc words ============================ )\n\n( ==================== Pictured Numeric Output =============== )\n( Pictured numeric output is what Forths use to display\nnumbers to the screen, this Forth has number output methods\nbuilt into the Forth kernel and mostly uses them instead,\nbut the mechanism is still useful so it has been added.\n\n@todo Pictured number output should act on a double cell\nnumber not a single cell number )\n\n0 variable hld\n\n: overflow ( -- : check if we overflow the hold area )\n \there chars> pad chars> hld @ - u> if -17 throw then ;\n\n: hold ( char -- : add a character to the numeric output string )\n\toverflow pad chars> hld @ - c! hld 1+! ;\n\n: holds ( c-addr u -- : hold an entire string )\n begin dup while 1- 2dup + c@ hold repeat 2drop ;\n\n: <# ( -- : setup pictured numeric output )\n\t0 hld ! ;\n\n: sign ( -- : add a sign to the pictured numeric output string )\n\t[char] - hold ;\n\n: # ( x -- x : divide x by base, turn into a character, put in pictured output string )\n\t(base) um\/mod swap\n \tdup 9 u>\n \tif 7 + then\n \t48 + hold ;\n\n: #s ( x -- 0 : repeatedly call # on x until x is zero )\n\tbegin # dup 0= until ;\n\n: #> ( -- c-addr u : end pictured output conversion, push output string to stack )\n\t0 hold ( NUL terminate string, just in case )\n\thld 1-! ( but do not include that in the count )\n\tpad chars> hld @\n\ttuck - 1+ swap ;\n\ndoer characters\nmake characters spaces\n\n: u.rc\n\t>r <# #s #> rot drop r> over - characters type ;\n\n: u.r ( u n -- print a number taking up a fixed amount of space on the screen )\n\tmake characters spaces u.rc ;\n\n: u.rz ( u n -- print a number taking up a fixed amount of space on the screen, using leading zeros )\n\tmake characters zeros u.rc ;\n\n: u. ( u -- : display an unsigned number in current base )\n\t0 u.r ;\n\nhide{ overflow u.rc characters }hide\n\n( ==================== Pictured Numeric Output =============== )\n\n( ==================== Numeric Input ========================= )\n( The Forth executable can handle numeric input and does not\nneed the routines defined here, however the user might want\nto write routines that use >NUMBER. >NUMBER is a generic word,\nbut it is a bit difficult to use on its own. )\n\n: map ( char -- n|-1 : convert character in 0-9 a-z range to number )\n\tdup lowercase? if [char] a - 10 + exit then\n\tdup decimal? if [char] 0 - exit then\n\tdrop -1 ;\n\n: number? ( char -- bool : is a character a number in the current base )\n\t>lower map (base) u< ;\n\n: >number ( n c-addr u -- n c-addr u : convert string )\n\tbegin\n\t\t( get next character )\n\t\t2dup >r >r drop c@ dup number? ( n char bool, R: c-addr u )\n\t\tif ( n char )\n\t\t\tswap (base) * swap map + ( accumulate number )\n\t\telse ( n char )\n\t\t\tdrop\n\t\t\tr> r> ( restore string )\n\t\t\texit\n\t\tthen\n\t\tr> r> ( restore string )\n\t\t1 \/string dup 0= ( advance string and test for end )\n\tuntil ;\n\nhide{ map }hide\n\n( ==================== Numeric Input ========================= )\n\n( ==================== ANSI Escape Codes ===================== )\n( Terminal colorization module, via ANSI Escape Codes\n\nsee: https:\/\/en.wikipedia.org\/wiki\/ANSI_escape_code\nThese codes will provide a relatively portable means of\nmanipulating a terminal )\n\n27 constant 'escape'\n: CSI 'escape' emit .\" [\" ;\n0 constant black\n1 constant red\n2 constant green\n3 constant yellow\n4 constant blue\n5 constant magenta\n6 constant cyan\n7 constant white\n: foreground 30 + ;\n: background 40 + ;\n0 constant dark\n1 constant bright\nfalse variable colorize\n\n: 10u. ( n -- : print a number in decimal )\n\tbase @ >r decimal u. r> base ! ;\n\n: color ( brightness color-code -- : set the terminal color )\n\t( set color on an ANSI compliant terminal,\n\tfor example:\n\t\tbright red foreground color\n\tsets the foreground text to bright red )\n\tcolorize @ 0= if 2drop exit then\n\tCSI 10u. if .\" ;1\" then .\" m\" ;\n\n: at-xy ( x y -- : set ANSI terminal cursor position to x y )\n\tCSI 10u. [char] ; emit 10u. .\" H\" ;\n\n: page ( -- : clear ANSI terminal screen and move cursor to beginning )\n\tCSI .\" 2J\" 1 1 at-xy ;\n\n: hide-cursor ( -- : hide the cursor from view )\n\tCSI .\" ?25l\" ;\n\n: show-cursor ( -- : show the cursor )\n\tCSI .\" ?25h\" ;\n\n: save-cursor ( -- : save cursor position )\n\tCSI .\" s\" ;\n\n: restore-cursor ( -- : restore saved cursor position )\n\tCSI .\" u\" ;\n\n: reset-color ( -- : reset terminal color to its default value)\n\tcolorize @ 0= if exit then\n\tCSI .\" 0m\" ;\n\nhide{ CSI 10u. }hide\n( ==================== ANSI Escape Codes ===================== )\n\n( ==================== Unit test framework =================== )\n\n256 string estring ( string to test )\n0 variable #estring ( actual string length )\n0 variable start ( starting depth )\n0 variable result ( result depth )\n0 variable check ( only check depth if -> is called )\n0 variable dictionary ( dictionary pointer on entering { )\n0 variable previous ( PWD register on entering { )\n\n: T ; ( hack until T{ can process words )\n\n: -> ( -- : save depth in variable )\n\t1 check ! depth result ! ;\n\n: test estring drop #estring @ ;\n\n: fail ( -- : invalidate the forth interpreter and exit )\n\tinvalidate bye ;\n\n: neutral ( -- : neutral color )\n\t;\n\n: bad ( -- : bad color )\n\tdark red foreground color ;\n\n: good ( -- : good color )\n\tdark green foreground color ;\n\n: die bad test type reset-color cr fail ;\n\n: evaluate? ( bool -- : test if evaluation has failed )\n\tif .\" evaluation failed\" cr fail then ;\n\n: failed bad .\" failed\" reset-color cr ;\n\n: adjust ( x -- x : adjust a depth to take into account starting depth )\n\tstart @ - ;\n\n: no-check? ( -- bool : if true we need to check the depth )\n\tcheck @ 0= ;\n\n: depth? ( -- : check if depth is correct )\n\tno-check? if exit then\n\tdepth adjust ( get depth and adjust for starting depth )\n\tresult @ adjust 2* = ( get results depth, same adjustment, should be\n\t half size of the depth )\n\tif exit then ( pass )\n\tfailed\n\t.\" Unequal depths:\" cr\n\t.\" depth: \" depth . cr\n\t.\" result: \" result @ . cr\n\tdie ;\n\n: equal? ( -- : determine if results equals expected )\n\tno-check? if exit then\n\tresult @ adjust equal\n\tif exit then\n\tfailed\n\t.\" Result is not equal to expected values. \" cr\n\t.\" Stack: \" cr .s cr\n\tdie ;\n\n: display ( c-addr u -- : print out testing message in estring )\n\tverbose if neutral type else 2drop then ;\n\n: pass ( -- : print out passing message )\n\tverbose if good .\" ok \" cr reset-color then ;\n\n: save ( -- : save current dictionary )\n\tpwd @ previous !\n\there dictionary ! ;\n\n: restore ( -- : restore dictionary )\n\tprevious @ pwd !\n\tdictionary @ h ! ;\n\n: T{ ( -- : perform a unit test )\n\tdepth start ! ( save start of stack depth )\n\t0 result ! ( reset result variable )\n\t0 check ! ( reset check variable )\n\testring 0 fill ( zero input string )\n\tsave ( save dictionary state )\n\tkey drop ( drop next character, which is a space )\n\testring [char] } accepter #estring ! ( read in string to test )\n\ttest display ( print which string we are testing )\n\ttest evaluate ( perform test )\n\tevaluate? ( evaluate successfully? )\n\tdepth? ( correct depth )\n\tequal? ( results equal to expected values? )\n\tpass ( print pass message )\n\trestore ( restore dictionary to previous state )\n\tno-check? if exit then\n\tresult @ adjust 2* ndrop ( remove items on stack generated by test )\n\t; \n\nT{ }T \nT{ -> }T\nT{ 1 -> 1 }T\nT{ 1 2 -> 1 2 }T\nT{ : c 1 2 ; c -> 1 2 }T\n\n( @bug ';' smudges the previous word, but :noname does\nnot. )\nT{ :noname 2 ; :noname 3 + ; compose execute -> 5 }T\n\nhide{\n\tpass test display\n\tadjust start save restore dictionary previous\n\tevaluate? equal? depth? estring #estring result\n\tcheck no-check? die neutral bad good failed\n}hide\n\n( ==================== Unit test framework =================== )\n\n\n( ==================== Pseudo Random Numbers ================= )\n( This section implements a Pseudo Random Number generator, it\nuses the xor-shift algorithm to do so.\nSee:\nhttps:\/\/en.wikipedia.org\/wiki\/Xorshift\nhttp:\/\/excamera.com\/sphinx\/article-xorshift.html\nhttp:\/\/xoroshiro.di.unimi.it\/\nhttp:\/\/www.arklyffe.com\/main\/2010\/08\/29\/xorshift-pseudorandom-number-generator\/\n\nThe constants used have been collected from various places\non the web and are specific to the size of a cell. )\n\nsize 2 = [if] 13 constant a 9 constant b 7 constant c [then]\nsize 4 = [if] 13 constant a 17 constant b 5 constant c [then]\nsize 8 = [if] 12 constant a 25 constant b 27 constant c [then]\n\n7 variable seed ( must not be zero )\n\n: seed! ( x -- : set the value of the PRNG seed )\n\tdup 0= if drop 7 ( zero not allowed ) then seed ! ;\n\n: random ( -- x : assumes word size is 32 bit )\n\tseed @\n\tdup a lshift xor\n\tdup b rshift xor\n\tdup c lshift xor\n\tdup seed! ;\n\nhide{ a b c seed }hide\n\n( ==================== Random Numbers ======================== )\n\n( ==================== Prime Numbers ========================= )\n( From original \"third\" code from the IOCCC at\nhttp:\/\/www.ioccc.org\/1992\/buzzard.2.design, the module works\nout and prints prime numbers. )\n\n: prime? ( u -- u | 0 : return number if it is prime, zero otherwise )\n\tdup 1 = if 1- exit then\n\tdup 2 = if exit then\n\tdup 2\/ 2 ( loop from 2 to n\/2 )\n\tdo\n\t\tdup ( value to check if prime )\n\t\ti mod ( mod by divisor )\n\t\tnot if\n\t\t\tdrop 0 leave\n\t\tthen\n\tloop ;\n\n0 variable counter\n\n: primes ( x1 x2 -- : print the primes from x2 to x1 )\n\t0 counter !\n\t\" The primes from \" dup . \" to \" over . \" are: \"\n\tcr\n\tcolumn.reset\n\tdo\n\t\ti prime?\n\t\tif\n\t\t\ti . counter @ column counter 1+!\n\t\tthen\n\tloop\n\tcr\n\t\" There are \" counter @ . \" primes.\"\n\tcr ;\n\nhide{ counter }hide\n( ==================== Prime Numbers ========================= )\n\n( ==================== Debugging info ======================== )\n( This section implements various debugging utilities that the\nprogrammer can use to inspect the environment and debug Forth\nwords. )\n\n( String handling should really be done with PARSE, and CMOVE )\n: sh ( cnl -- ior : execute a line as a system command )\n\tnl word count system ;\n\nhide{ .s }hide\n: .s ( -- : print out the stack for debugging )\n\t[char] < emit depth (.) drop [char] > emit space\n\tdepth if\n\t\tdepth 0 do i column tab depth i 1+ - pick . loop\n\tthen\n\tcr ;\n\n1 variable hide-words ( do we want to hide hidden words or not )\n\n: name ( PWD -- c-addr : given a pointer to the PWD field of a word get a pointer to the name of the word )\n\tdup 1+ @ 256\/ word-mask and lsb - chars> ;\n\n( This function prints out all of the defined words, excluding\nhidden words. An understanding of the layout of a Forth word\nhelps here. The dictionary contains a linked list of words,\neach forth word has a pointer to the previous word until the\nfirst word. The layout of a Forth word looks like this:\n\nNAME: Forth Word - A variable length ASCII NUL terminated\n string.\nPWD: Previous Word Pointer, points to the previous\n word.\nCODE: Flags, code word and offset from previous word\n pointer to start of Forth word string.\nDATA: The body of the forth word definition, not interested\n in this.\n\nThere is a register which stores the latest defined word which\ncan be accessed with the code \"pwd @\". In order to print out\na word we need to access a words CODE field, the offset to\nthe NAME is stored here in bits 8 to 14 and the offset is\ncalculated from the PWD field.\n\n\"print\" expects a character address, so we need to multiply\nany calculated address by the word size in bytes. )\n\n: words.immediate ( bool -- : emit or mark a word being printed as being immediate )\n\tnot if dark red foreground color then ;\n\n: words.defined ( bool -- : emit or mark a word being printed as being a built in word )\n\tnot if bright green background color then ;\n\n: words.hidden ( bool -- : emit or mark a word being printed as being a hidden word )\n\tif dark magenta foreground color then ;\n\n: words ( -- : print out all defined an visible words )\n\tlatest\n\tspace\n\tbegin\n\t\tdup\n\t\thidden? hide-words @ and\n\t\tnot if\n\t\t\thidden? words.hidden\n\t\t\tcompiling? words.immediate\n\t\t\tdup defined-word? words.defined\n\t\t\tname\n\t\t\tprint space\n\t\t\treset-color\n\t\telse\n\t\t\tdrop\n\t\tthen\n\t\t@ ( Get pointer to previous word )\n\t\tdup dictionary-start u< ( stop if pwd no longer points to a word )\n\tuntil\n\tdrop cr ;\n\n( Simpler version of words\n: words\n\tpwd @\n\tbegin\n\t\tdup name print space @ dup dictionary-start u<\n\tuntil drop cr ; )\n\nhide{ words.immediate words.defined words.hidden hidden? hidden-bit }hide\n\n: TrueFalse ( bool -- : print true or false )\n\tif \" true\" else \" false\" then ;\n\n: registers ( -- : print out important registers and information about the virtual machine )\n\t\" return stack pointer: \" r@ . cr\n\t\" dictionary pointer \" here . cr\n\t\" previous word: \" pwd ? cr\n\t\" state: \" state ? cr\n\t\" base: \" base ? cr\n\t\" depth: \" depth . cr\n\t\" cell size (in bytes): \" size . cr\n\t\" last cell address: \" max-core . cr\n\t\" unused cells: \" unused . cr\n\t\" invalid: \" `invalid @ TrueFalse cr\n\t\" size of variable stack: \" `stack-size ? cr\n\t\" size of return stack: \" `stack-size ? cr\n\t\" start of variable stack: \" max-core `stack-size @ 2* - . cr\n\t\" start of return stack: \" max-core `stack-size @ - . cr\n\t\" current input source: \" source-id -1 = if \" string\" else \" file\" then cr\n\t\" tracing on: \" `debug @ TrueFalse cr\n\t\" starting word: \" `instruction ? cr\n\t\" real start address: \" `start-address ? cr\n\t\" error handling: \" `error-handler ? cr\n\t\" throw handler: \" `handler ? cr\n\t\" signal recieved: \" `signal ? cr ;\n\t\n( `sin `sidx `slen `fout\n `stdout `stderr `argc `argv )\n\n\n: y\/n? ( -- bool : ask a yes or no question )\n\tkey drop\n\t\" y\/n? \"\n\tbegin\n\t\tkey\n\t\tdup\n\t\t[char] y = if true exit then\n\t\t[char] n = if false exit then\n\t\t\" y\/n? \"\n\tagain ;\n\n: step\n\t( step through a word: this word could be augmented\n\twith commands such as \"dump\", \"halt\", and optional\n\t\".s\" and \"registers\" )\n\tregisters\n\t\" .s: \" .s cr\n\t\" -- press any key to continue -- \"\n\tkey drop ;\n\n: more ( -- : wait for more input )\n\t\" -- press any key to continue -- \" key drop cr page ;\n\n: debug-help ( -- : print out the help for the debug command )\n \" debug mode commands\n\th - print help\n\tq - exit interpreter word\n\tr - print registers\n\ts - print stack\n\tR - print return stack\n\tc - continue on with execution\n\" ;\n\ndoer debug-prompt\n: prompt-default\n\t.\" debug> \" ;\n\nmake debug-prompt prompt-default\n\n: debug ( -- : enter interactive debug prompt )\n\tcr\n\t\" Entered Debug Prompt. Type 'h' for help. \" cr\n\tbegin\n\t\tkey\n\t\tcase\n\t\t\tnl of debug-prompt endof\n\t\t\t[char] h of debug-help endof\n\t\t\t[char] q of bye endof\n\t\t\t[char] r of registers endof\n\t\t\t[char] s of .s endof\n\t\t\t[char] R of r.s endof\n\t\t\t[char] c of exit endof\n\t\t\t( @todo add throw here )\n\t\tendcase\n\tagain ;\nhide debug-prompt\n\n: code>pwd ( CODE -- PWD\/0 : calculate PWD from code address )\n\tdup dictionary-start here within not if drop 0 exit then\n\t1 cells - ;\n\n: word-printer ( CODE -- : print out a words name given its code field )\n\tdup 1 cells - @ -1 = if . \" noname\" exit then ( nonames are marked by a -1 before its code field )\n\tdup code>pwd ?dup-if .d name print else drop \" data\" then\n\t drop ;\n\nhide{ code>pwd }hide\n\n( these words push the execution tokens for various special\ncases for decompilation )\n: get-branch [ find branch ] literal ;\n: get-?branch [ find ?branch ] literal ;\n: get-original-exit [ find _exit ] literal ;\n: get-quote [ find ' ] literal ;\n\n( @todo replace 2- nos1+ nos1+ with appropriate word, like\nthe string word that increments a string by an amount, but\nthat operates on CELLS )\n: branch-increment ( addr branch -- increment : calculate decompile increment for \"branch\" )\n\t1+ dup negative?\n\tif\n\t\tover cr . [char] : emit space . cr 2\n\telse\n\t\t2dup 2- nos1+ nos1+ dump\n\tthen ;\n\n( these words take a code field to a primitive they implement,\ndecompile it and any data belonging to that operation, and push\na number to increment the decompilers code stream pointer by )\n\n: decompile-literal ( code -- increment )\n\t1+ ? \" literal\" 2 ;\n\n: decompile-branch ( code -- increment )\n\tdark red foreground color\n\t1+ ? \" branch \" dup 1+ @ branch-increment ;\n\n: decompile-quote ( code -- increment )\n\tdark green foreground color\n\tdup\n\t[char] ' emit 1+ @ word-printer 2 reset-color ;\n\n: decompile-?branch ( code -- increment )\n\t1+ ? \" ?branch\" 2 ;\n\n: decompile-exit ( code -- 0 )\n\t\" _exit\" cr \" End of word: \" . 0 ;\n\n( The decompile word expects a pointer to the code field of\na word, it decompiles a words code field, it needs a lot of\nwork however. There are several complications to implementing\nthis decompile function.\n\n\t'\t The next cell should be pushed\n\n\t:noname This has a marker before its code field of\n\t -1 which cannot occur normally, this is\n\t handled in word-printer\n\n\tbranch\t branches are used to skip over data, but\n\t also for some branch constructs, any data\n\t in between can only be printed out\n\t generally speaking\n\n\texit\t There are two definitions of exit, the one\n\t used in ';' and the one everything else uses,\n\t this is used to determine the actual end\n\t of the word\n\n\tliterals Literals can be distinguished by their\n\t low value, which cannot possibly be a word\n\t with a name, the next field is the\n\t actual literal\n\nOf special difficult is processing IF, THEN and ELSE\nstatements, this will require keeping track of '?branch'.\n\nAlso of note, a number greater than \"here\" must be data )\n\n: decompile ( code-pointer -- code-pointer increment|0 : )\n\t.d [char] : emit space dup @\n\tcase\n\t\tdolit of dup decompile-literal cr endof\n\t\tget-branch of dup decompile-branch endof\n\t\tget-quote of dup decompile-quote cr endof\n\t\tget-?branch of dup decompile-?branch cr endof\n\t\tget-original-exit of dup decompile-exit endof\n\t\tdup word-printer 1 swap cr\n\tendcase reset-color ;\n\n: decompiler ( code-field-ptr -- : decompile a word in its entirety )\n\tbegin decompile over + tuck = until drop ;\n\nhide{\n\tword-printer get-branch get-?branch get-original-exit\n\tget-quote branch-increment decompile-literal\n\tdecompile-branch decompile-?branch decompile-quote\n\tdecompile-exit\n}hide\n\n( these words expect a pointer to the PWD field of a word )\n: see.name \" name: \" name print cr ;\n: see.start \" word start: \" name chars . cr ;\n: see.previous \" previous word: \" @ . cr ;\n: see.immediate \" immediate: \" compiling? nip not TrueFalse cr ;\n: see.instruction \" instruction: \" xt-instruction . cr ;\n: see.defined \" defined: \" defined-word? TrueFalse cr ;\n\n: see.header ( PWD -- is-immediate-word? )\n\tdup see.name\n\tdup see.start\n\tdup see.previous\n\tdup see.immediate\n\tdup see.instruction ( @todo look up instruction name )\n\tsee.defined ;\n\n( @todo This does not work for all words, so needs fixing.\n Specifically:\n\n\t2variable\n\t2constant\n\ttable\n\tconstant\n\tvariable\n\tarray\nWhich are all complex CREATE words\n\nA good way to test decompilation is with the following\nUnix pipe:\n\n\t.\/forth -f forth.fth -e words\n\t\t| sed 's\/ \/ see \/g'\n\t\t| .\/forth -t forth.fth &> decompiled.log\n)\n\n( @todo refactor into word that takes a PWD pointer and one that attempts to parse\/find name )\n: see ( c\" xxx\" -- : decompile a word )\n\tfind\n\tdup 0= if -32 throw then\n\tcell- ( move to PWD field )\n\tdup see.header\n\tdup defined-word?\n\tif ( decompile if a compiled word )\n\t\t2 cells + ( move to code field )\n\t\t\" code field:\" cr\n\t\tdecompiler\n\telse ( the instruction describes the word if it is not a compiled word )\n\t\tdup 1 cells + @ instruction-mask and doconst = if ( special case for constants )\n\t\t\t\" constant: \" 2 cells + @ .\n\t\telse\n\t\t\tdrop\n\t\tthen\n\tthen cr ;\n\n( @todo This has a bug, if any data within a word happens\nto match the address of _exit word.end calculates the wrong\naddress, this needs to mirror the DECOMPILE word )\n: word.end ( addr -- addr : find the end of a word )\n\tbegin\n\t\tdup\n\t\t@ [ find _exit ] literal = if exit then\n\t\tcell+\n\tagain ;\n\n: (inline) ( xt -- : inline an word from its execution token )\n\tdup cell- defined-word? if\n\t\tcell+\n\t\tdup word.end over - here -rot dup allot move\n\telse\n\t\t,\n\tthen ;\n\n: ;inline ( -- : terminate :inline )\n\timmediate -22 throw ;\n\n: :inline immediate\n\t?comp\n\tbegin\n\t\tfind found?\n\t\tdup [ find ;inline ] literal = if\n\t\t\tdrop exit ( terminate :inline )\n\t\tthen\n\t\t(inline)\n\tagain ;\n\nhide{\n\tsee.header see.name see.start see.previous see.immediate\n\tsee.instruction defined-word? see.defined _exit found?\n\t(inline) word.end\n}hide\n\n( These help messages could be moved to blocks, the blocks\ncould then be loaded from disk and printed instead of defining\nthe help here, this would allow much larger help )\n\n: help ( -- : print out a short help message )\n\tpage\n\tkey drop\n\" Welcome to Forth, an imperative stack based language. It is\nboth a low level and a high level language, with a very small\nmemory footprint. Most of Forth is defined as a combination\nof various primitives.\n\nA short description of the available function (or Forth words)\nfollows, words marked (1) are immediate and cannot be used in\ncommand mode, words marked with (2) define new words. Words\nmarked with (3) have both command and compile functionality.\n\n\"\nmore \" Some of the built in words that accessible are:\n\n(1,2)\t: define a new word, switching to compile mode\n\timmediate make latest defined word immediate\n\tread read in a word, execute in command mode else compile\n\t@ ! fetch, store\n\tc@ c! character based fetch and store\n\t- + * \/ standard arithmetic operations,\n\tand or xor invert standard bitwise operations\n\tlshift rshift left and right bit shift\n\tu< u> < > = comparison predicates\n\texit exit from a word\n\temit print character from top of stack\n\tkey get a character from input\n\tr> >r pop a value from or to the return stack\n\tfind find a word in the dictionary and push the location\n\t' store the address of the following word on the stack\n\t, write the top of the stack to the dictionary\n\tswap swap first two values on the stack\n\tdup duplicate the top of the stack\n\tdrop pop and drop a value\n\tover copy the second stack value over the first\n\t. pop the top of the stack and print it\n\"\nmore \"\n\tprint print a NUL terminated string at a character address\n\tdepth get the current stack depth\n\tclock get the time since execution start in milliseconds\n\tevaluate evaluate a string\n\tsystem execute a system command\n\tclose-file close a file handle\n\topen-file open a file handle\n\tdelete-file delete a file off disk given a string\n\tread-file read in characters from a file\n\twrite-file write characters to a file\n\tfile-position get the file offset\n\treposition-file reposition the file pointer\n\tflush-file flush a file to disk\n\trename-file rename a file on disk\n \"\n\nmore \" All of the other words in the interpreter are built\nfrom these primitive words. A few examples:\n\n(1)\tif...else...then FORTH branching construct\n(1)\tbegin...until loop until top of stack is non zero\n(1)\tbegin...again infinite loop\n(1)\tdo...loop FORTH looping construct\n(2,3)\tcreate create a new word that pushes its location\n(1)\tdoes> declare a created words run time behaviour\n(1,2)\tvariable declare variable with initial value from top of stack\n(1,2)\tconstant declare a constant, taken from top of stack\n(1,2)\tarray declare an array with size taken from top of stack\n(1)\t; terminate a word definition and return to command mode\n\twords print out a list of all the defined words\n\thelp this help message\n\tdump print out memory contents starting at an address\n\tregisters print out the contents of the registers\n\tsee decompile a word, viewing what words compose it\n\t.s print out the contents of the stack\n\n\"\n\nmore \" Some more advanced words:\n\n\there push the dictionary pointer\n\th push the address of the dictionary pointer\n\tr push the return stack pointer\n\tallot allocate space in the dictionary\n(1)\t[ switch to command mode\n\t] switch to compile mode\n\t:: compile ':' into the dictionary\n\n\" more \"\nFor more information either consult the manual pages forth(1)\nand libforth(1) or consult the following sources:\n\n\thttps:\/\/github.com\/howerj\/libforth\n\thttp:\/\/work.anapnea.net\/html\/html\/projects.html\n\nAnd for a larger tutorial:\n\n\thttps:\/\/github.com\/howerj\/libforth\/blob\/master\/readme.md\n\nFor resources on Forth:\n\n\thttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\thttps:\/\/rwmj.wordpress.com\/2010\/08\/07\/jonesforth-git-repository\/\n\n -- end --\n\" cr\n;\n\n( ==================== Debugging info ======================== )\n\n( ==================== Files ================================= )\n( These words implement more of the standard file access words\nin terms of the ones provided by the virtual machine. These\nwords are not the most easy to use words, although the ones\ndefined here and the ones that are part of the interpreter are\nthe standard ones.\n\nSome thoughts:\n\nI believe extensions to this word set, once I have figured\nout the semantics, should be made to make them easier to use,\nones which automatically clean up after failure and call throw\nwould be more useful [and safer] when dealing with a single\ninput or output stream. The most common action after calling\none of the file access words is to call throw any way.\n\nFor example, a word like:\n\n\t: #write-file \\ c-addr u fileid -- fileid u\n\t\tdup >r\n\t\twrite-file dup if r> close-file throw throw then\n\t\tr> swap ;\n\nWould be easier to deal with, it preserves the file identifier\nand throws if there is any problem. It would be a bit more\ndifficult to use when there are two files open at a time.\n\n@todo implement the other file access methods in terms of the\nbuilt in ones.\n@todo read-line and write-line need their flag and ior setting\ncorrectly\n\n\tFILE-SIZE [ use file-positions ]\n\nAlso of note, Source ID needs extending.\n\nSee: [http:\/\/forth.sourceforge.net\/std\/dpans\/dpans11.htm] )\n\n: read-char ( c-addr fileid -- ior : read a char )\n\t1 swap read-file 0<> swap 1 <> or ;\n\n0 variable x\n\n: getchar ( fileid -- char ior )\n\tx chars> swap read-char x chars> c@ swap ;\n\n: write-char ( c-addr fileid -- ior : write a char )\n\t1 swap write-file 0<> swap 1 <> or ;\n\n: putchar ( char fileid -- ior )\n\tswap x chars> c! x chars> swap write-char ;\n\n\\ @todo This shouldn't affect the file position indicator.\n\\ @todo This doesn't return a sensible error indicator.\n\\ : file-size ( fileid -- ud ior )\n\\\t0 swap\n\\\tbegin dup getchar nip 0= while nos1+ repeat drop ;\n\n\nhide{ x }hide\n\n: rewind-file ( file-id -- : rewind a file to the beginning )\n\t0 reposition-file throw ;\n\n: read-line ( c-addr u1 fileid -- u2 flag ior : read in a line of text )\n\t-rot bounds\n\tdo\n\t\tdup i swap read-char drop\n\t\ti c@ nl = if drop i 0 0 leave then\n\tloop drop ;\n\n: write-line ( c-addr u fileid -- u2 flag ior : write a line of text )\n\t-rot bounds\n\tdo\n\t\tdup i swap write-char drop\n\t\ti c@ nl = if drop i 0 0 leave then\n\tloop ;\n\n: resize-file ( ud fileid -- ior : attempt to resize a file )\n\t( There is no portable way to truncate a file :C )\n\t2drop -1 ( -1 to indicate failure ) ;\n\n: create-file ( c-addr u fam -- fileid ior )\n\t>r 2dup w\/o open-file throw close-file throw\n\tr> open-file ;\n\n: include-file ( file-id -- : evaluate a file )\n\tdup >r 0 1 evaluator r> close-file throw throw ;\n\n: included ( c-addr u -- : attempt to open up a name file and evaluate it )\n\tr\/o open-file throw\n\tinclude-file ;\n\n: include ( c\" ccc\" -- : attempt to evaluate a named file )\n\t( @bug requires trailing space, should use parse-name )\n\tbl word count included ;\n\n: bin ( fam1 -- fam2 : modify a file access method to be binary not line oriented )\n\t( Do nothing, all file access methods are binary )\n\t;\n\n( ==================== Files ================================= )\n\n( ==================== Matcher =============================== )\n( The following section implements a very simple regular\nexpression engine, which expects an ASCIIZ Forth string. It\nis translated from C code and performs an identical function.\n\nThe regular expression language is as follows:\n\n\tc\tmatch a literal character\n\t.\tmatch any character\n\t*\tmatch any characters\n\nThe \"*\" operator performs the same function as \".*\" does in\nmost other regular expression engines. Most other regular\nexpression engines also do not anchor their selections to the\nbeginning and the end of the string to match, instead using\nthe operators '^' and '$' to do so, to emulate this behavior\n'*' can be added as either a suffix, or a prefix, or both,\nto the matching expression.\n\nAs an example \"*, World!\" matches both \"Hello, World!\" and\n\"Good bye, cruel World!\". \"Hello, ....\" matches \"Hello, Bill\"\nand \"Hello, Fred\" but not \"Hello, Tim\" as there are two few\ncharacters in the last string.\n\n@todo make a matcher that expects a Forth string, which do\nnot have to be NUL terminated )\n\n\\ Translated from http:\/\/c-faq.com\/lib\/regex.html\n\\ int match(char *pat, char *str)\n\\ {\n\\ \tswitch(*pat) {\n\\ \tcase '\\0': return !*str;\n\\ \tcase '*': return match(pat+1, str) || *str && match(pat, str+1);\n\\ \tcase '.': return *str && match(pat+1, str+1);\n\\ \tdefault: return *pat == *str && match(pat+1, str+1);\n\\ \t}\n\\ }\n\n: *pat ( regex -- regex char : grab next character of pattern )\n\tdup c@ ;\n\n: *str ( string regex -- string regex char : grab next character string to match )\n\tover c@ ;\n\n: pass ( c-addr1 c-addr2 -- bool : pass condition, characters matched )\n\t2drop 1 ;\n\n: reject ( c-addr1 c-addr2 -- bool : fail condition, character not matched )\n\t2drop 0 ;\n\n: *pat==*str ( c-addr1 c-addr2 -- c-addr1 c-addr2 bool )\n\t2dup c@ swap c@ = ;\n\n: ++ ( u1 u2 u3 u4 -- u1+u3 u2+u4 : not quite d+ [does no carry] )\n\tswap >r + swap r> + swap ;\n\ndefer matcher\n\n: advance ( string regex char -- bool : advance both regex and string )\n\tif 1 1 ++ matcher else reject then ;\n\n: advance-string ( string regex char -- bool : advance only the string )\n\tif 1 0 ++ matcher else reject then ;\n\n: advance-regex ( string regex -- bool : advance matching )\n\t2dup 0 1 ++ matcher if pass else *str advance-string then ;\n\n: match ( string regex -- bool : match a ASCIIZ pattern against an ASCIIZ string )\n\t( @todo Add limits and accept two Forth strings, making sure they are both\n\t ASCIIZ strings as well\n\t @warning This uses a non-standards compliant version of case! )\n\t*pat\n\tcase\n\t\t 0 of drop c@ not endof\n\t\t[char] * of advance-regex endof\n\t\t[char] . of *str advance endof\n\t\t\n\t\tdrop *pat==*str advance exit\n\n\tendcase ;\n\nmatcher is match\n\nhide{\n\t*str *pat *pat==*str pass reject advance\n\tadvance-string advance-regex matcher ++\n}hide\n\n( ==================== Matcher =============================== )\n\n\n( ==================== Cons Cells ============================ )\n( From http:\/\/sametwice.com\/cons.fs, this could be improved\nif the optional memory allocation words were added to\nthe interpreter. This provides a simple \"cons cell\" data\nstructure. There is currently no way to free allocated\ncells. I do not think this is particularly useful, but it is\ninteresting. )\n\n: car! ( value cons-addr -- : store a value in the car cell of a cons cell )\n\t! ;\n\n: cdr! ( value cons-addr -- : store a value in the cdr cell of a cons cell )\n\tcell+ ! ;\n\n: car@ ( cons-addr -- car-val : retrieve car value from cons cell )\n\t@ ;\n\n: cdr@ ( cons-addr -- cdr-val : retrieve cdr value from cons cell )\n\tcell+ @ ;\n\n: cons ( car-val cdr-val -- cons-addr : allocate a new cons cell )\n\tswap here >r , , r> ;\n\n: cons0 0 0 cons ;\n\n( ==================== Cons Cells ============================ )\n\n( ==================== License =============================== )\n( The license has been chosen specifically to make this library\nand any associated programs easy to integrate into arbitrary\nproducts without any hassle. For the main libforth program\nthe LGPL license would have been also suitable [although it\nis MIT licensed as well], but to keep confusion down the same\nlicense, the MIT license, is used in both the Forth code and\nC code. This has not been done for any ideological reasons,\nand I am not that bothered about licenses. )\n\n: license ( -- : print out license information )\n\"\nThe MIT License (MIT)\n\nCopyright (c) 2016, 2017 Richard James Howe\n\nPermission is hereby granted, free of charge, to any person\nobtaining a copy of this software and associated documentation\nfiles (the 'Software'), to deal in the Software without\nrestriction, including without limitation the rights to use,\ncopy, modify, merge, publish, distribute, sublicense, and\/or\nsell copies of the Software, and to permit persons to whom\nthe Software is furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY\nKIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\nWARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE\nAND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\nHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE\nOR OTHER DEALINGS IN THE SOFTWARE.\n\n\"\n;\n\n( ==================== License =============================== )\n\n( ==================== Core utilities ======================== )\n( Read the header of a core file and process it, printing the\nresults out )\n\n8 constant header-size ( size of Forth core file header )\n8 constant size-field-size ( the size in bytes of the size field in the core file )\n0 variable core-file ( core fileid we are reading in )\n0 variable core-cell-size ( cell size of Forth core )\n0 variable core-version ( version of core file )\n0 variable core-endianess ( endianess of core we are reading in )\n\n( save space to read in header )\ncreate header header-size chars allot\n: cheader ( -- c-addr : header char address )\n\theader chars> ;\ncreate size-field size-field-size chars allot\n: csize-field ( -- c-addr : address of place size field is stored in )\n\tsize-field chars> ;\n\n0\nenum header-magic0 ( magic number 0 : FF )\nenum header-magic1 ( magic number 1 : '4' )\nenum header-magic2 ( magic number 2 : 'T' )\nenum header-magic3 ( magic number 3 : 'H' )\nenum header-cell-size ( size of a forth cell, either 2, 4 or 8 bytes )\nenum header-version ( version of the forth core )\nenum header-endianess ( endianess of the core )\nenum header-log2size ( binary logarithm of the core size )\n\n: cleanup ( -- : cleanup before abort )\n\tcore-file @ ?dup 0<> if close-file drop then ;\n\n: invalid-header ( bool -- : abort if header is invalid )\n\t<> if cleanup abort\" invalid header\" then ;\n\n: save-core-cell-size ( char -- : save the core file cell size, checking if it is valid )\n\tcore-cell-size !\n\t\" cell size:\" tab\n\tcore-cell-size @ 2 = if 2 . cr exit then\n\tcore-cell-size @ 4 = if 4 . cr exit then\n\tcore-cell-size @ 8 = if 8 . cr exit then\n\tcleanup core-cell-size @ . abort\" : invalid cell size\" ;\n\n: check-version-compatibility ( char -- : checks the version compatibility of the core file )\n\tcore-version !\n\tcore-version @ version = if \" version: \" version . cr exit then\n\tcleanup core-version @ . abort\" : unknown version number\" ;\n\n: save-endianess ( char -- : save the endianess, checking if it is valid )\n\tcore-endianess !\n\t\" endianess:\" tab\n\tcore-endianess @ 0 = if \" big\" cr exit then\n\tcore-endianess @ 1 = if \" little\" cr exit then\n\tcleanup core-endianess @ . abort\" invalid endianess\" then ;\n\n: read-or-abort ( c-addr size fileid -- : )\n\tover >r read-file\n\t 0<> if cleanup abort\" file read failed\" then\n\tr> <> if cleanup abort\" header too small\" then ;\n\n: header? ( -- : print out header information )\n\tcheader header-size core-file @ read-or-abort\n\t( \" raw header:\" header 2 dump )\n\tcheader header-magic0 + c@ 255 invalid-header\n\tcheader header-magic1 + c@ [char] 4 invalid-header\n\tcheader header-magic2 + c@ [char] T invalid-header\n\tcheader header-magic3 + c@ [char] H invalid-header\n\tcheader header-cell-size + c@ save-core-cell-size\n\tcheader header-version + c@ check-version-compatibility\n\tcheader header-endianess + c@ save-endianess\n\t\" valid header\" cr ;\n\n: size? ( -- : print out core file size )\n\t\" size: \" cheader header-log2size + c@ 1 swap lshift . cr ;\n\n: core ( c-addr u -- : analyze a Forth core file from disk given its file name )\n\t2dup \" core file:\" tab type cr\n\tr\/o open-file throw core-file !\n\theader?\n\tsize?\n\tcore-file @ close-file drop ;\n\n( s\" forth.core\" core )\n\nhide{\nheader-size header?\nheader-magic0 header-magic1 header-magic2 header-magic3\nheader-version header-cell-size header-endianess header-log2size\nheader\ncore-file save-core-cell-size check-version-compatibility\ncore-cell-size cheader\ncore-endianess core-version save-endianess invalid-header\ncleanup size-field csize-field size-field-size\nread-or-abort size?\n}hide\n\n( ==================== Core utilities ======================== )\n\n( ==================== RLE =================================== )\n\n( These set of words implement Run Length Compression, which\ncan be used for saving space when compressing the core files\ngenerated by Forth programs, which contain mostly runs of\nNUL characters.\n\nThe format of the encoded data is quite simple, there is a\ncommand byte followed by data. The command byte encodes only\ntwo commands; encode a run of literal data and repeat the\nnext character.\n\nIf the command byte is greater than X the command is a run\nof characters, X is then subtracted from the command byte\nand this is the number of characters that is to be copied\nverbatim when decompressing.\n\nIf the command byte is less than or equal to X then this\nnumber, plus one, is used to repeat the next data byte in\nthe input stream.\n\nX is 128 for this application, but could be adjusted for\nbetter compression depending on what the data looks like.\n\nExample:\n\n\t2 'a' 130 'b' 'c' 3 'd'\n\nBecomes:\n\n\taabcddd\n\nExample usage:\n\n\t: extract\n\t\tc\" forth.core\" w\/o open-file throw c\"\n\t\tforth.core.rle\" r\/o open-file throw\n\t\tdecompress ;\n\textract\n\n@note file redirection could be used for the input as well\n@todo compression, and reading\/writing to strings )\n\n: cpad pad chars> ;\n\n0 variable out\n128 constant run-length\n\n: next.char ( file-id -- char : read in a single character )\n\t>r cpad r> read-char throw cpad c@ ;\n\n: repeated ( count file-id -- : repeat a character count times )\n\tnext.char swap 0 do dup emit loop drop ;\n\n: literals ( count file-id -- : extract a literal run )\n\t>r cpad swap r> read-file throw cpad swap type ;\n\n: command ( file-id -- : process an RLE command )\n\tdup\n\t>r next.char\n\tdup run-length u>\n\tif\n\t\trun-length - r> literals\n\telse\n\t\t1+ r> repeated\n\tthen ;\n\n: redirect ( file-id-out -- : save current output pointer, redirect to output )\n\t`fout @ out ! `fout ! ;\n\n: restore ( -- : restore previous output pointer )\n\tout @ `fout ! ;\n\n: decompress ( file-id-out file-id-in -- : decompress an RLE encoded file )\n\tswap\n\tredirect\n\tbegin dup ['] command catch until ( process commands until input exhausted )\n\t2drop ( drop twice because catch will restore stack before COMMAND )\n\trestore ; ( restore input stream )\n\nhide{ literals repeated next.char out run-length command }hide\n\n( ==================== RLE =================================== )\n\n( ==================== Generate C Core file ================== )\n( The word core2c reads in a core file and turns it into a\nC file which can then be compiled into the forth interpreter\nin a bootstrapping like process. The process is described\nelsewhere as well, but it goes like this.\n\n1. We want to generate an executable program that contains the\ncore Forth interpreter, written in C, and the contents of this\nfile in compiled form. However, in order to compile this code\nwe need a Forth interpreter to do so. This is the problem.\n2. To solve the problem we first make a program which is capable\nof compiling \"forth.fth\".\n3. We then generate a core file from this.\n4. We then convert the generated core file to C code.\n5. We recompile the original program to includes this core\nfile, and which runs the core file at start up.\n6. We run the new executable.\n\nUsage:\n c\" forth.core\" c\" core.gen.c\" core2c )\n\n0 variable count\n\n: wbyte ( u char -- : write a byte )\n\t(.) drop\n\t[char] , emit\n\t16 mod 0= if cr then ;\n\n: advance ( char -- : advance counter and print byte )\n\tcount 1+! count @ swap wbyte ;\n\n: hexify ( fileid -- fileid : turn core file into C numbers in array )\n\t0 count !\n\tbegin dup getchar 0= while advance repeat drop ;\n\n: quote ( -- : emit a quote character )\n\t[char] \" emit ;\n\n: core2c ( c-addr u c-addr u -- ior : generate a C file from a core file )\n\tw\/o open-file throw >r\n\tr\/o open-file ?dup-if r> close-file throw throw then\n\tr> redirect\n\t\" #include \" quote \" libforth.h\" quote cr\n\t\" unsigned char forth_core_data[] = {\" cr\n\thexify\n\t\" };\" cr\n\t\" forth_cell_t forth_core_size = \" count @ . \" ;\" cr cr\n\tclose-file\n\t`fout @ close-file\n\trestore or ;\n\nhide{ wbyte hexify count quote advance }hide\n\n( ==================== Generate C Core file ================== )\n\n( ==================== Word Count Program ==================== )\n\n( @todo implement FILE-SIZE in terms of this program )\n( @todo extend wc to include line count and word count )\n: wc ( c-addr u -- u : count the bytes in a file )\n\tr\/o open-file throw\n\t0 swap\n\tbegin\n\t\tdup getchar nip 0=\n\twhile\n\t\tnos1+\n\trepeat\n\tclose-file throw ;\n\n( ==================== Word Count Program ==================== )\n\n( ==================== Save Core file ======================== )\n( The following functionality allows the user to save the\ncore file from within the running interpreter. The Forth\ncore files have a very simple format which means the words\nfor doing this do not have to be too long, a header has to\nemitted with a few calculated values and then the contents\nof the Forths memory after this )\n\n( This write the header out to the current output device, this\nwill be redirected to a file )\n: header ( -- : write the header out )\n\t0xff emit ( magic 0 )\n\t[char] 4 emit ( magic 1 )\n\t[char] T emit ( magic 2 )\n\t[char] H emit ( magic 3 )\n\tsize emit ( cell size in bytes )\n\tversion emit ( core version )\n\tendian not emit ( endianess )\n\tmax-core log2 emit ; ( size field )\n\n: data ( -- : write the data out )\n\t0 max-core chars> `fout @ write-file throw drop ;\n\n: encore ( -- : write the core file out )\n\theader\n\tdata ;\n\n: save-core ( c-addr u -- : save core file or throw error )\n\tw\/o open-file throw dup\n\tredirect\n\t\t['] encore catch swap close-file throw\n\trestore ;\n\n( The following code illustrates an example of setting up a\nForth core file to execute a word when the core file is loaded.\nIn the example the word \"hello-world\" will be executed,\nwhich will also quit the interpreter:\n\nThis only works for immediate words for now, we define\nthe word we wish to be executed when the forth core\nis loaded:\n\n\t: hello-world immediate\n\t\t\" Hello, World!\" cr bye ;\n\nThe following sets the starting word to our newly\ndefined word:\n\n\tfind hello-world cfa start!\n\n\t\\ Now we can save the core file out:\n\ts\" forth.core\" save-core\n\nThis can be used, in conjunction with aspects of the build\nsystem, to produce a standalone executable that will run only\na single Forth word. This is known as creating a 'turn-key'\napplication. )\n\nhide{ redirect restore data encore header }hide\n\n( ==================== Save Core file ======================== )\n\n( ==================== Hex dump ============================== )\n\n( @todo hexdump can read in too many characters and it does not\nprint out the correct address\n@todo utilities for easy redirecting of file input\/output )\n\\ : input >r cpad 128 r> read-file ; ( file-id -- u 0 | error )\n\\ : clean cpad 128 0 fill ; ( -- )\n\\ : cdump cpad chars swap aligned chars dump ; ( u -- )\n\\ : hexdump ( file-id -- : [hex]dump a file to the screen )\n\\ \tdup\n\\ \tclean\n\\ \tinput if 2drop exit then\n\\ \t?dup-if cdump else drop exit then\n\\ \ttail ;\n\\\n\\ 0 variable u\n\\ 0 variable u1\n\\ 0 variable cdigs\n\\ 0 variable digs\n\\\n\\ : address ( -- bool : is it time to print out a new line and an address )\n\\ \tu @ u1 @ - 4 size * mod 0= ;\n\\\n\\ : (dump) ( u c-addr u : u -- )\n\\ \trot dup u ! u1 !\n\\ \tcdigits cdigs !\n\\ \tdigits digs !\n\\ \tbounds\n\\ \tdo\n\\ \t\taddress if cr u @ digs @ u.rz [char] : emit space then\n\\ \t\ti c@ cdigs @ u.rz\n\\ \t\t\n\\ \t\ti 1+ size mod 0= if space then\n\\ \t\tu 1+!\n\\ \tloop\n\\ \tu @\n\\ \t;\n\\\n\\ : hexdump-file ( c-addr u )\n\\ \tr\/o open-file throw\n\\ \t\n\\ \t;\n\\\n\\ hide{ u u1 cdigs digs address }hide\n\\ hex\n\\ 999 0 197 (dump)\n\\ decimal\n\\\n\\ hide{ cpad clean cdump input }hide\n\\\n( ==================== Hex dump ============================== )\n\n( ==================== Date ================================== )\n( This word set implements a words for date processing, so\nyou can print out nicely formatted date strings. It implements\nthe standard Forth word time&date and two words which interact\nwith the libforth DATE instruction, which pushes the current\ntime information onto the stack.\n\nRather annoyingly months are start from 1 but weekdays from\n0. )\n\n: >month ( month -- c-addr u : convert month to month string )\n\tcase\n\t\t 1 of c\" Jan \" endof\n\t\t 2 of c\" Feb \" endof\n\t\t 3 of c\" Mar \" endof\n\t\t 4 of c\" Apr \" endof\n\t\t 5 of c\" May \" endof\n\t\t 6 of c\" Jun \" endof\n\t\t 7 of c\" Jul \" endof\n\t\t 8 of c\" Aug \" endof\n\t\t 9 of c\" Sep \" endof\n\t\t10 of c\" Oct \" endof\n\t\t11 of c\" Nov \" endof\n\t\t12 of c\" Dec \" endof\n\t\t-11 throw\n\tendcase ;\n\n: .day ( day -- c-addr u : add ordinal to day )\n\t10 mod\n\tcase\n\t\t1 of c\" st \" endof\n\t\t2 of c\" nd \" endof\n\t\t3 of c\" rd \" endof\n\t\tdrop c\" th \" exit\n\tendcase ;\n\n: >day ( day -- c-addr u: add ordinal to day of month )\n\tdup 1 10 within if .day exit then\n\tdup 10 20 within if drop c\" th\" exit then\n\t.day ;\n\n: >weekday ( weekday -- c-addr u : print the weekday )\n\tcase\n\t\t0 of c\" Sun \" endof\n\t\t1 of c\" Mon \" endof\n\t\t2 of c\" Tue \" endof\n\t\t3 of c\" Wed \" endof\n\t\t4 of c\" Thu \" endof\n\t\t5 of c\" Fri \" endof\n\t\t6 of c\" Sat \" endof\n\t\t-11 throw\n\tendcase ;\n\n: >gmt ( bool -- GMT or DST? )\n\tif c\" DST \" else c\" GMT \" then ;\n\n: colon ( -- char : push a colon character )\n\t[char] : ;\n\n: 0? ( n -- : hold a space if number is less than base )\n\t(base) u< if [char] 0 hold then ;\n\n( .NB You can format the date in hex if you want! )\n: date-string ( date -- c-addr u : format a date string in transient memory )\n\t9 reverse ( reverse the date string )\n\t<#\n\t\tdup #s drop 0? ( seconds )\n\t\tcolon hold\n\t\tdup #s drop 0? ( minute )\n\t\tcolon hold\n\t\tdup #s drop 0? ( hour )\n\t\tdup >day holds\n\t\t#s drop ( day )\n\t\t>month holds\n\t\tbl hold\n\t\t#s drop ( year )\n\t\t>weekday holds\n\t\tdrop ( no need for days of year )\n\t\t>gmt holds\n\t\t0\n\t#> ;\n\n: .date ( date -- : print the date )\n\tdate-string type ;\n\n: time&date ( -- second minute hour day month year )\n\tdate\n\t3drop ;\n\nhide{ >weekday .day >day >month colon >gmt 0? }hide\n\n( ==================== Date ================================== )\n\n\n( ==================== CRC =================================== )\n\n( @todo implement all common CRC algorithms, but only if the\nword size allows it [ie. 32 bit CRCs on a 32 or 64 bit machine,\n64 bit CRCs on a 64 bit machine] )\n\n( Make a word to limit arithmetic to a 16-bit value )\nsize 2 = [if]\n\t: limit immediate ; ( do nothing, no need to limit )\n[else]\n\t: limit 0xffff and ; ( limit to 16-bit value )\n[then]\n\n: ccitt ( crc c-addr -- crc : calculate polynomial 0x1021 AKA \"x16 + x12 + x5 + 1\" )\n\tc@ ( get char )\n\tlimit over 256\/ xor ( crc x )\n\tdup 4 rshift xor ( crc x )\n\tdup 5 lshift limit xor ( crc x )\n\tdup 12 lshift limit xor ( crc x )\n\tswap 8 lshift limit xor ; ( crc )\n\n( See http:\/\/stackoverflow.com\/questions\/10564491\n and https:\/\/www.lammertbies.nl\/comm\/info\/crc-calculation.html )\n: crc16-ccitt ( c-addr u -- u )\n\t0xffff -rot\n\t['] ccitt foreach ;\nhide{ limit ccitt }hide\n\n( ==================== CRC =================================== )\n\n( ==================== Rational Data Type ==================== )\n( This word set allows the manipulation of a rational data\ntype, which are basically fractions. This allows numbers like\n1\/3 to be represented without any loss of precision. Conversion\nto and from the data type to an integer type is trivial,\nalthough information can be lost during the conversion.\n\nTo convert to a rational, use DUP, to convert from a\nrational, use '\/'.\n\nThe denominator is the first number on the stack, the numerator\nthe second number. Fractions are simplified after any rational\noperation, and all rational words can accept unsimplified\narguments. For example the fraction 1\/3 can be represented as\n6\/18, they are equivalent, so the rational equality operator\n\"=rat\" can accept both and returns true.\n\n\tT{ 1 3 6 18 =rat -> 1 }T\n\nSee: https:\/\/en.wikipedia.org\/wiki\/Rational_data_type For\nmore information.\n\nThis set of words use two cells to represent a fraction,\nhowever a single cell could be used, with the numerator and the\ndenominator stored in upper and lower half of a single cell.\n\n@todo add saturating Q numbers to the interpreter, as well as\narithmetic word for acting on double cells [d+, d-, etcetera]\nhttps:\/\/en.wikipedia.org\/wiki\/Q_%28number_format%29, this\ncan be used in lieu of floating point numbers. )\n\n: simplify ( a b -- a\/gcd{a,b} b\/gcd{a\/b} : simplify a rational )\n 2dup\n gcd\n tuck\n \/\n -rot\n \/\n swap ; \\ ? check this\n\n: crossmultiply ( a b c d -- a*d b*d c*b d*b )\n rot ( a c d b )\n 2dup ( a c d b d b )\n * ( a c d b d*b )\n >r ( a c d b , d*b )\n rot ( a d b c , d*b )\n * ( a d b*c , d*b )\n -rot ( b*c a d , d*b )\n * ( b*c a*d , d*b )\n r> ( b*c a*d d*b )\n tuck ( b*c d*b a*d d*b )\n 2swap ; ( done! )\n\n: *rat ( a\/b c\/d -- a\/b : multiply two rationals together )\n rot * -rot * swap simplify ;\n\n: \/rat ( a\/b c\/d -- a\/b : divide one rational by another )\n swap *rat ;\n\n: +rat ( a\/b c\/d -- a\/b : add two rationals together )\n crossmultiply\n rot\n drop ( or check if equal, if not there is an error )\n -rot\n +\n swap\n simplify ;\n\n: -rat ( a\/b c\/d -- a\/b : subtract one rational from another )\n crossmultiply\n rot\n drop ( or check if equal, if not there is an error )\n -rot\n -\n swap\n simplify ;\n\n: .rat ( a\/b -- : print out a rational number )\n simplify swap (.) drop [char] \/ emit . ;\n\n: =rat ( a\/b c\/d -- bool : rational equal )\n crossmultiply rot = -rot = = ;\n\n: >rat ( a\/b c\/d -- bool : rational greater than )\n crossmultiply rot 2drop > ;\n\n: <=rat ( a\/b c\/d -- bool : rational less than or equal to )\n\t>rat not ;\n\n: =rat ( a\/b c\/d -- bool : rational greater or equal to )\n\trational is a work in progress, make it better )\n: 0>number 0 -rot >number ;\n0 0 2variable saved\n: failed 0 0 saved 2@ ;\n: >rational ( c-addr u -- a\/b c-addr u )\n\t2dup saved 2!\n\t0>number 2dup 0= if 4drop failed exit then ( @note could convert to rational n\/1 )\n\tc@ [char] \/ <> if 3drop failed exit then\n\t1 \/string\n\t0>number ;\n\nhide{ 0>number saved failed }hide\n\n( ==================== Rational Data Type ==================== )\n\n( ==================== Block Layer =========================== )\n( This is the block layer, it assumes that the file access\nwords exists and use them, it would have to be rewritten\nfor an embedded device that used EEPROM or something\nsimilar. Currently it does not interact well with the current\ninput methods used by the interpreter which will need changing.\n\nThe block layer is the traditional way Forths implement a\nsystem to interact with mass storage, one which imposes little\non the underlying system only requiring that blocks 1024 bytes\ncan be loaded and saved to it [which make it suitable for\nmicrocomputers that lack a file system or an embedded device].\n\nThe block layer is used less than it once as a lot more Forths\nare hosted under a guest operating system so have access to\nmethods for reading and writing to files through it.\n\nEach block number accepted by BLOCK is backed by a file\n[or created if it does not exist]. The name of the file is\nthe block number with \".blk\" appended to it.\n\nSome Notes:\n\nBLOCK only uses one block buffer, most other Forths have\nmultiple block buffers, this could be improved on, but\nwould take up more space.\n\nAnother way of storing the blocks could be made, which is to\nstore the blocks in a single file and seek to the correct\nplace within it. This might be implemented in the future,\nor offered as an alternative. \n\nYet another way is to not have on disk blocks, but instead\nhave in memory blocks, this simplifies things significantly,\nand would mean saving the blocks to disk would use the same\nmechanism as saving the core file to disk. Computers certainly\nhave enough memory to do this. The block word set could\nbe factored so it could use either the on disk method or\nthe memory option. \n\nTo simplify the current code, and make the code portable\nto devices with EEPROM an instruction in the virtual machine\ncould be made which does the task of transfering a block to\ndisk. \n\n@todo refactor BLOCK to use MAKE\/DOER so its behavior can\nbe changed. )\n\n0 variable dirty\nb\/buf string buf ( block buffer, only one exists )\n0 , ( make sure buffer is NUL terminated, just in case )\n0 variable blk ( 0 = invalid block number, >0 block number stored in buf)\n\n: invalid? ( n -- : throw if block number is invalid )\n\t0= if -35 throw then ;\n\n: update ( -- : mark currently loaded block buffer as dirty )\n\ttrue dirty ! ;\n\n: updated? ( n -- bool : is a block updated? )\n \tblk @ <> if 0 else dirty @ then ;\n\n: block.name ( n -- c-addr u : make a block name )\n\tc\" .blk\" <# holds #s #> rot drop ;\n\n( @warning this will not work if we do not have permission,\nor in various other cases where we cannot open the file,\nfor whatever reason )\n: file-exists ( c-addr u : does a file exist? )\n\tr\/o open-file if drop 0 else close-file throw 1 then ;\n\n: block.exists ( n -- bool : does a block buffer exist on disk? )\n\tblock.name file-exists ;\n\n( @note block.write and block.read do not check if they have\nwrote or read in 1024 bytes, nor do they check that they can\nonly write or read 1024 and not a byte more )\n\n: block.read ( file-id -- file-id : read in buffer )\n\tdup >r buf r> read-file nip if close-file -33 throw then ;\n\n: block.write ( file-id -- file-id : write out buffer )\n\tdup >r buf r> write-file nip if close-file -34 throw then ;\n\n: block.open ( n fam -- file-id )\n\t>r block.name r> open-file throw ;\n\n: save-buffers\n\tblk @ 0= if exit then ( not a valid block number, exit )\n\tdirty @ not if exit then ( not dirty, no need to save )\n\tblk @ w\/o block.open ( open file backing block buffer )\n\tblock.write ( write it out )\n\tclose-file throw ( close it )\n\tfalse dirty ! ; ( but only mark it clean if everything succeeded )\n\n: empty-buffers ( -- : deallocate any saved buffers )\n\t0 blk ! ;\n\n: flush ( -- : perform save-buffers followed by empty-buffers )\n\tsave-buffers\n\tempty-buffers ;\n\n( Block is a complex word that does a lot, although it has\na simple interface. It does the following given a block number:\n\n1. Checks the provided block buffer number to make sure it\nis valid.\n2. If the block is already loaded from the disk, then return\nthe address of the block buffer it is loaded into.\n3. If not, it checks to see if the currently loaded block\nbuffer is dirty, if it is then it flushes the buffer to disk.\n4. If the block buffer does not exists on disk then it\ncreates it.\n5. It then stores the block number in blk and returns an\naddress to the block buffer. )\n: block ( n -- c-addr : load a block )\n\tdup invalid?\n\tdup blk @ = if drop buf drop exit then\n\tflush\n\tdup block.exists if ( if the buffer exits on disk load it in )\n\t\tdup r\/o block.open\n\t\tblock.read\n\t\tclose-file throw\n\telse ( else it does not exist )\n\t\tbuf 0 fill ( clean the buffer )\n\tthen\n\tblk ! ( save the block number )\n\tbuf drop ;\n\n: buffer block ;\n\n: load ( n -- : load and execute a block )\n\tblock b\/buf evaluate throw ;\n\n: +block ( n -- u : calculate new block number relative to current block )\n\tblk @ + ;\n\n: --> ( -- : load next block )\n\t1 +block load ;\n\n( @todo refactor into BLOCK.MAKE, which BLOCKS.MAKE would use )\n: blocks.make ( n1 n2 -- : make blocks on disk from n1 to n2 inclusive )\n\t1+ swap do i block b\/buf bl fill update loop save-buffers ;\n\n: block.copy ( n1 n2 -- bool : copy block n2 to n1 if n2 exists )\n\tswap dup block.exists 0= if 2drop false exit then ( n2 n1 )\n\tblock drop ( load in block n1 )\n\tw\/o block.open block.write close-file throw\n\ttrue ;\n\n: block.delete ( n -- : delete block )\n\tdup block.exists 0= if drop exit then\n\tblock.name delete-file drop ;\n\n\\ @todo implement a word that splits a file into blocks\n\\ : split ( c-addr u : split a file into blocks )\n\\\t;\n\nhide{\n\tblock.name invalid? block.write\n\tblock.read block.exists block.open dirty\n}hide\n\n( ==================== Block Layer =========================== )\n\n( ==================== List ================================== )\n( The list word set allows the viewing of Forth blocks,\nthis version of list can create two Formats, a simple mode\nwhere it just spits out the block with a carriage return\nafter each line and a more fancy version which also prints\nout line numbers and draws a box around the data. LIST is\nnot aware of any formatting and characters that might be\npresent in the data, or none printable characters.\n\nA very primitive version of list can be defined as follows:\n\n\t: list block b\/buf type ;\n\n)\n\n1 variable fancy-list\n0 variable scr\n64 constant c\/l ( characters per line )\n\n: pipe ( -- : emit a pipe character )\n\t[char] | emit ;\n\n: line.number ( n -- : print line number )\n\tfancy-list @ not if drop exit then\n\t2 u.r space pipe ;\n\n: list.end ( -- : print the right hand side of the box )\n\tfancy-list @ not if exit then\n\tpipe ;\n\n: line ( c-addr -- c-addr u : given a line number, display that line number and calculate offset )\n\tdup\n\tline.number ( display line number )\n\tc\/l * + ( calculate offset )\n\tc\/l ; ( add line length )\n\n: list.type ( c-addr u -- : list a block )\n\tb\/buf c\/l \/ 0 do dup i line type list.end cr loop drop ;\n\n: list.border ( -- : print a section of the border )\n\t\" +---|---\" ;\n\n: list.box ( )\n\tfancy-list @ not if exit then\n\t4 spaces\n\t8 0 do list.border loop cr ;\n\n: list ( n -- : display a block number and update scr )\n\tdup >r block r> scr ! list.box list.type list.box ;\n\n: thru\n\tkey drop\n\t1+ swap do i list more loop ;\n\nhide{\n\tbuf line line.number list.type\n\t(base) list.box list.border list.end pipe\n}hide\n\n( ==================== List ================================== )\n\n( ==================== Signal Handling ======================= )\n( Signal handling at the moment is quite primitive. When\na signal occurs it has to be explicitly tested for by the\nprogrammer, this could be improved on quite a bit. One way\nof doing this would be to check for signals in the virtual\nmachine and cause a THROW from within it. )\n\n( signals are biased to fall outside the range of the error\nnumbers defined in the ANS Forth standard. )\n-512 constant signal-bias\n\n: signal ( -- signal\/0 : push the results of the signal register )\n\t`signal @\n \t0 `signal ! ;\n\n( ==================== Signal Handling ======================= )\n\n( Looking at most Forths dictionary with \"words\" command they\ntend to have a lot of words that do not mean anything but to\nthe implementers of that specific Forth, here we clean up as\nmany non standard words as possible. )\nhide{\n do-string ')' alignment-bits\n dictionary-start hidden-mask instruction-mask immediate-mask compiling?\n compile-bit\n max-core dolist doconst x x! x@\n max-string-length\n evaluator\n TrueFalse >instruction\n xt-instruction\n `source-id `sin `sidx `slen `start-address `fin `fout `stdin\n `stdout `stderr `argc `argv `debug `invalid `top `instruction\n `stack-size `error-handler `handler _emit `signal `x\n}hide\n\n(\n## Forth To List\n\nThe following is a To-Do list for the Forth code itself,\nalong with any other ideas.\n\n* FORTH, VOCABULARY\n\n* \"Value\", \"To\", \"Is\"\n\n* Double cell words\n\n* The interpreter should use character based addresses,\ninstead of word based, and use values that are actual valid\npointers, this will allow easier interaction with the world\noutside the virtual machine\n\n* common words and actions should be factored out to simplify\ndefinitions of other words, their standards compliant version\nfound if any.\n\n* A soft floating point library would be useful which could be\nused to optionally implement floats [which is not something I\nreally want to add to the virtual machine]. If floats were to\nbe added, only the minimal set of functions should be added\n[f+,f-,f\/,f*,f<,f>,>float,...]\n\n* Allow the processing of argc and argv, the mechanism by which\nthat this can be achieved needs to be worked out. However all\nprocessing that is currently done in \"main.c\" should be done\nwithin the Forth interpreter instead. Words for manipulating\nrationals and double width cells should be made first.\n\n* A built in version of \"dump\" and \"words\" should be added\nto the Forth starting vocabulary, simplified versions that\ncan be hidden.\n\n* Here documents, string literals. Examples of these can be\nfound online\n\n* Document the words in this file and built in words better,\nalso turn this document into a literate Forth file.\n\n* Sort out \"'\", \"[']\", \"find\", \"compile,\"\n\n* Proper booleans should be used throughout, that is -1 is\ntrue, and 0 is false.\n\n* Attempt to add crypto primitives, not for serious use,\nlike TEA, XTEA, XXTEA, RC4, MD5, ...\n\n* Add hash functions: CRC-32, CRC-16, ...\nhttp:\/\/stackoverflow.com\/questions\/10564491\/\n\n* Implement as many things from\nhttp:\/\/lars.nocrew.org\/forth2012\/implement.html as is sensible.\n\n* Works like EMIT and KEY should be DOER\/MAKE words\n\n* The current words that implement I\/O redirection need to\nbe improved, and documented, I think this is quite a useful\nand powerful mechanism to use within Forth that simplifies\nprograms. This is a must and will make writing utilities in\nForth a *lot* easier\n\n* Words for manipulating words should be added, for navigating\nto different fields within them, to the end of the word,\netcetera.\n\n* The data structure used for parsing Forth words needs\nchanging in libforth so a counted string is produced. Counted\nstrings should be used more often. The current layout of a\nForth word prevents a counted string being used and uses a\nbyte more than it has to.\n\n* Whether certain simple words [such as '1+', '1-', '>',\n'<', '<>', NOT, <=', '>='] should be added as virtual\nmachine instructions for speed [and size] reasons should\nbe investigated.\n\n* An analysis of the interpreter and the code it executes\ncould be done to find the most commonly executed words\nand instructions, as well as the most common two and three\nsequences of words and instructions. This could be used to use\nto optimize the interpreter, in terms of both speed and size.\n\n* The source code for this file should go through a code\nreview, which should focus on formatting, stack comments and\nreorganizing the code. Currently it is not clear that variables\nlike COLORIZE and FANCY-LIST exist and can be changed by\nthe user. Lines should be 64 characters in length - maximum,\nincluding the new line at the end of the file.\n\n### libforth.c todo\n\n* A halt, a parse, and a print\/type instruction could be\nadded to the Forth virtual machine.\n\n* Make case sensitivity optional\n\n* u.r, or a more generic version should be added to the\ninterpreter instead of the current simpler primitive. As\nshould >number - for fast numeric input and output.\n\n* Throw\/Catch need to be added and used in the virtual machine\n\n* Integrate Travis Continous Integration into the Github\nproject.\n\n* A potential optimization is to order the words in the\ndictionary by frequency order, this would mean chaning the\nX Macro that contains the list of words, after collecting\nstatistics. This should make find faster.\n\n* Investigate adding operating system specific code into the\ninterpreter and isolating it to make it semi-portable.\n\n* Make equivalents for various Unix utilities in Forth,\nlike a CRC check, cat, tr, etcetera.\n\n* It would be interesting to make a primitive file system based\nupon Forth blocks, this could then be ported to systems that\ndo not have file systems, such as microcontrollers [which\nusually have EEPROM].\n\n* In a _very_ unportable way it would be possible to have an\ninstruction that takes the top of the stack, treats it as a\nfunction pointer and then attempts to call said function. This\nwould allow us to assemble machine dependant code within the\ncore file, generate a new function, then call it. It is just\na thought.\n )\n\nverbose [if]\n\t.( FORTH: libforth successfully loaded.) cr\n\tdate .date cr\n\t.( Type 'help' and press return for a basic introduction.) cr\n\t.( Core: ) here . \" \/ \" here unused + . cr\n\t license\n[then]\n\n( ==================== Test Code ============================= )\n\n( The following will not work as we might actually be reading\nfrom a string [`sin] not `fin.\n\n: key 32 chars> 1 `fin @\n\tread-file drop 0 = if 0 else 32 chars> c@ then ; )\n\n\\ : ' immediate state @ if postpone ['] else find then ;\n\n( This really does not implement a correct FORTH\/VOCABULARY,\nfor that wordlists will need to be introduced and used in\nlibforth.c. The best that this word set can do is to hide\nand reveal words to the user, this was just an experiment.\n\n\t: forth\n\t\t[ find forth 1- @ ] literal\n\t\t[ find forth 1- ] literal ! ;\n\n\t: vocabulary\n\t\tcreate does> drop 0 [ find forth 1- ] literal ! ; )\n\n\\ @todo The built in primitives should be redefined so to make sure\n\\ they are called and nested correctly, using the following words\n\\ 0 variable csp\n\\ : !csp sp@ csp ! ;\n\\ : ?csp sp@ csp @ <> if -22 throw then ;\n\n\\ @todo Make this work\n\\ : >body ??? ;\n\\ : noop ( -- ) ;\n\\ : defer create ( \"name\" -- ) ['] noop , does> ( -- ) @ execute ;\n\\ : is ( xt \"name\" -- ) find >body ! ;\n\\ defer lessthan\n\\ find < is lessthan\n\n( ==================== Test Code ============================= )\n\n( ==================== Block Editor ========================== )\n( Experimental block editor Mark II\n\nThis is a simple block editor, it really shows off the power\nand simplicity of Forth systems - both the concept of a block\neditor and the implementation.\n\nForth source code used to organized into things called 'blocks',\nnowadays most people use normal resizeable stream based files.\nA block simply consists of 1024 bytes of data that can be\ntransfered to and from mass storage. This works on systems that\ndo not have a file system. A block can be used for storing\narbitrary data as well, so the user had to know what was stored\nin what block.\n\n1024 bytes is quite a limiting Form factor for storing source\ncode, which is probably one reason Forth earned a reputation\nfor being terse. A few conventions arose around dealing with\nForth source code stored in blocks - both in how the code should\nbe formatted within them, and in how programs that required\nmore than one block of storage should be dealt with.\n\nOne of the conventions is how many columns and rows each block\nconsists of, the traditional way is to organize the code into\n16 lines of text, with a column width of 64 characters. The only\nspace character used is the space [or ASCII character 32], tabs\nand new lines are not used, as they are not needed - the editor\nknows how long a line is so it can wrap the text.\n\nVarious standards and common practice evolved as to what goes\ninto a block - for example the first line is usually a comment\ndescribing what the block does, with the date is was last edited\nand who edited it.\n\nThe way the editor works is by defining a simple set of words\nthat act on the currently loaded block, LIST is used to display\nthe loaded block. An editor loop which executes forth words\nand automatically displays the currently block can be entered\nby calling EDITOR. This loop is essential an extension of\nthe INTERPRET word, it does no special processing such as\nlooking for keys - all commands are Forth words. The editor\nloop could have been implemented in the following fashion\n[or something similar]:\n\n\t: editor-command\n\t\tkey\n\t\tcase\n\t\t\t[char] h of print-editor-help endof\n\t\t\t[char] i of insert-text endof\n\t\t\t[char] d of delete-line endof\n\t\t\t... more editor commands\n\t\t\t[char] q of quit-editor-loop endof\n\t\t\tpush-number-by-default\n\t\tendof ;\n\nHowever this is rather limiting, it only works for single\ncharacter commands and numeric input is handled as a special\ncase. It is far simpler to just call the READ word with the\neditor commands in search order, and it can be extended not\nby adding more parsing code in CASE statements but just by\ndefining new words in the ordinary manner.\n\nThe editor loop does not have to be used while editing code,\nbut it does make things easier. The commands defined can be\nused on there own.\n\t\nThe code was adapted from: \t\n\nhttp:\/\/retroforth.org\/pages\/?PortsOfRetroEditor\n\nWhich contains ports of an editor written for Retro Forth.\n\n@todo Improve the block editor\n\n- '\\' needs extending to work with the block editor, for now,\nuse parenthesis for comments\n- add multi line insertion mode\n- Add to an editor vocabulary, which will need the vocabulary\nsystem to exist.\n- Using PAGE should be optional as not all terminals support\nANSI escape codes - thanks to CMD.EXE. Damned Windows.\n\nAdapted from http:\/\/retroforth.org\/pages\/?PortsOfRetroEditor )\n\n\n: help ( @todo rename to H once vocabularies are implemented )\npage cr\n\" Block Editor Help Menu\n\n n move to next block\n p move to previous block\n # d delete line in current block\n x erase current block\n e evaluate current block\n # i insert line\n # #2 ia insert at line #2 at column #\n q quit editor loop\n # b set block number\n s save block and write it out\n u update block\n\n -- press any key to continue -- \" cr ( \" )\nchar drop ;\n\n: (block) blk @ block ;\n: (check) dup b\/buf c\/l \/ u>= if -24 throw then ;\n: (line) (check) c\/l * (block) + ; ( n -- c-addr : push current line address )\n: (clean)\n\t(block) b\/buf\n\t2dup nl bl subst\n\t2dup cret bl subst\n\t 0 bl subst ;\n: n 1 +block block ;\n: p -1 +block block ;\n: d (line) c\/l bl fill ;\n: x (block) b\/buf bl fill ;\n: s update save-buffers ;\n: q rdrop rdrop ;\n: e blk @ load char drop ;\n: ia c\/l * + dup b\/buf swap - >r (block) + r> accept drop (clean) ;\n: i 0 swap ia ;\n: editor\n\t1 block ( load first block by default )\n\trendezvous ( set up a rendezvous so we can forget words up to this point )\n\tbegin\n\t\tpage cr\n\t\t\" BLOCK EDITOR: TYPE 'HELP' FOR A LIST OF COMMANDS\" cr\n\t\tblk @ list\n\t\t\" [BLOCK: \" blk @ u. \" ] \" \n\t\t\" [HERE: \" here u. \" ] \" \n\t\t\" [SAVED: \" blk @ updated? not u. \" ] \"\n\t\tcr\n\t\tpostpone [ ( need to be in command mode )\n\t\tread\n\tagain ;\n\n( Extra niceties )\nc\/l string yank \nyank bl fill\n: u update ;\n: b block ;\n: l blk @ list ;\n: y (line) yank >r swap r> cmove ; ( n -- yank line number to buffer )\n: c (line) yank cmove ; ( n -- copy yank buffer to line )\n: ct swap y c ; ( n1 n2 -- copy line n1 to n2 )\n: ea (line) c\/l evaluate throw ;\n: m retreat ; ( -- : forget everything since editor session began )\n\n: sw 2dup y (line) swap (line) swap c\/l cmove c ;\n\nhide{ (block) (line) (clean) yank }hide\n\n( ==================== Block Editor ========================== )\n\n( ==================== Error checking ======================== )\n( This is a series of redefinitions that make the use of control\nstructures a bit safer. )\n\n: if immediate ?comp postpone if [ hide if ] ;\n: else immediate ?comp postpone else [ hide else ] ;\n: then immediate ?comp postpone then [ hide then ] ;\n: begin immediate ?comp postpone begin [ hide begin ] ;\n: until immediate ?comp postpone until [ hide until ] ;\n: never immediate ?comp postpone never [ hide never ] ;\n\\ : ; immediate ?comp postpone ; [ hide ; ] ; ( @todo do nesting checking for control statements )\n\n( ==================== Error checking ======================== )\n\n( ==================== DUMP ================================== )\n\\ : newline ( x -- x+1 : print a new line every fourth value )\n\\ \tdup 3 and 0= if cr then 1+ ;\n\\\n\\ : address ( num count -- count : print current address we are dumping every fourth value )\n\\ \tdup >r\n\\ \t1- 3 and 0= if . [char] : emit space else drop then\n\\ \tr> ;\n\\\n\\ : dump ( start count -- : print the contents of a section of memory )\n\\ \\\thex ( switch to hex mode )\n\\ \t1 >r ( save counter on return stack )\n\\ \tover + swap ( calculate limits: start start+count )\n\\ \tbegin\n\\ \t\t2dup u> ( stop if gone past limits )\n\\ \twhile\n\\ \t\tdup r> address >r\n\\ \t\tdup @ . 1+\n\\ \t\tr> newline >r\n\\ \trepeat\n\\ \tr> drop\n\\ \t2drop ;\n\\\n\\ hide newline\n\\ hide address\n( ==================== DUMP ================================== )\n\n( ==================== End of File Functions ================= )\n\n( set up a rendezvous point, we can call the word RETREAT to\nrestore the dictionary to this point. This word also updates\nfence to this location in the dictionary )\nrendezvous\n\n: task ; ( Task is a word that can safely be forgotten )\n\n( ==================== End of File Functions ================= )\n\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"051bed851db4db27dcb1de6bffb2483a92791550","subject":"Comments, added smudge.","message":"Comments, added smudge.\n\nMore comments and the \"smudge\" word has been added.\n","repos":"howerj\/libforth","old_file":"forth.fth","new_file":"forth.fth","new_contents":"#!.\/forth \n( Welcome to libforth, A dialect of Forth. Like all versions of Forth this\nversion is a little idiosyncratic, but how the interpreter works is\ndocumented here and in various other files.\n\nThis file contains most of the start up code, some basic start up code\nis executed in the C file as well which makes programming at least bearable.\nMost of Forth is programmed in itself, which may seem odd if your back\nground in programming comes from more traditional language [such as C],\nalthough less so if you know already know lisp.\n\nFor more information about this interpreter and Forth see:\n\thttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\treadme.md : for a manual for this interpreter\n\tlibforth.h : for information about the C API\n\tlibforth.c : for the interpreter itself\n\tunit.c : a series of unit tests against libforth.c\n\tunit.fth : a series of unit tests against this file\n\nThe interpreter and this code originally descend from a Forth interpreter\nwritten in 1992 for the International obfuscated C Coding Competition\n\nSee:\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\nThe manual for the interpreter should be read first before looking into this\ncode. It is important to understand the execution model of Forth, especially\nthe differences between command and compile mode, and how immediate and compiling\nwords work.\n\n@todo Restructure and describe structure of this file.\n\nEach of these sections is clearly labeled and they are generally in dependency order.\n\nUnfortunately the code in this file is not as portable as it could be, it makes\nassumptions about the size of cells provided by the virtual machine, which will\ntake time to rectify. Some of the constructs are subtly different from the\nDPANs Forth specification, which is usually noted. Eventually this should\nalso be fixed.)\n\n( ========================== Basic Word Set ================================== )\n\n( \nWe'll begin by defining very simple words we can use later, these a very\nbasic words, that perform simple tasks, they will not require much explanation.\n\nEven though the words are simple, their stack comment and a description for\nthem will still be included so external tools can process and automatically\nextract the document string for a given work.\n)\n\n: postpone ( -- : postpone execution of the following immediate word )\n\timmediate find , ;\n\n: :: ( -- : compiling version of ':' )\n\t[ find : , ] ;\n\n: constant \n\t:: ( compile word header )\n\there 1 - h ! ( decrement dictionary pointer )\n\there @ instruction-mask invert and doconst or here ! ( change instruction to CONST )\n\there 1 + h ! ( increment dictionary pointer )\n\t, ( write in value )\n\tpostpone [ ; ( back into command mode )\n\n( space saving measure )\n-1 constant -1\n 0 constant 0 \n 1 constant 1\n 2 constant 2\n 3 constant 3\n\n0 constant false\n1 constant true ( @warning not standards compliant )\n\n( Confusingly the word 'cr' prints a line feed )\n10 constant lf ( line feed )\nlf constant nl ( new line - line feed on Unixen )\n13 constant cret ( carriage return )\n\n1 hidden-bit lshift constant hidden-mask ( mask for the hide bit in a words CODE field )\n\n-1 -1 1 rshift invert and constant min-signed-integer\n\nmin-signed-integer invert constant max-signed-integer\n\n1 constant cell ( size of a cell in address units )\n\n4 constant version ( version number for the interpreter )\n\ncell size 8 * * constant address-unit-bits ( the number of bits in an address )\n\n-1 -1 1 rshift and invert constant sign-bit ( bit corresponding to the sign in a number )\n\n( @todo test by how much, if at all, making words like 1+, 1-, <>, and other\nsimple words, part of the interpreter would speed things up )\n\n: 1+ ( x -- x : increment a number ) \n\t1 + ;\n\n: 1- ( x -- x : decrement a number ) \n\t1 - ;\n\n: chars ( c-addr -- addr : convert a character address to an address )\n\tsize \/ ; \n\n: chars> ( addr -- c-addr: convert an address to a character address )\n\tsize * ; \n\n: tab ( -- : print a tab character to current output device )\n\t9 emit ;\n\n: 0= ( x -- bool : is 'x' equal to zero? )\n\t0 = ;\n\n: not ( x -- bool : is 'x' true? )\n\t0= ;\n\n: <> ( x x -- bool : not equal )\n\t= 0= ;\n\n: logical ( x -- bool : turn a value into a boolean ) \n\tnot not ;\n\n( @todo \": dolit ' ' ;\" works but does not interact well with \n'decompile', if this was fixed the special work could be removed,\nwith some extra effort in libforth.c as well )\n: dolit ( -- x : location of special \"push\" word )\n\t2 ; \n\n: 2, ( x x -- : write two values into the dictionary )\n\t, , ;\n\n: [literal] ( x -- : write a literal into the dictionary )\n\tdolit 2, ; \n\n: literal ( x -- : immediately write a literal into the dictionary )\n\timmediate [literal] ;\n\n: sliteral immediate ( I: c-addr u --, Run: -- c-addr u )\n\tswap [literal] [literal] ;\n\n( @todo throw if not found )\n: ['] ( I: c\" xxx\", Run: -- xt )\n\timmediate find [literal] ;\n\n: >instruction ( CODE -- Instruction : extract instruction from instruction field ) \n\tinstruction-mask and ;\n\n: immediate-mask ( -- x : pushes the mask for the compile bit in a words CODE field )\n\t[ 1 compile-bit lshift ] literal ;\n\n: hidden? ( PWD -- PWD bool : is a word hidden, given the words PWD field ) \n\tdup 1+ @ hidden-mask and logical ;\n\n: compiling? ( PWD -- PWD bool : is a word immediate, given the words PWD field )\n\tdup 1+ @ immediate-mask and logical ;\n\n: cr ( -- : emit a newline character )\n\tnl emit ;\n\n: < ( x1 x2 -- bool : signed less than comparison )\n\t- dup if max-signed-integer u> else logical then ;\n\n: > ( x1 x2 -- bool : signed greater than comparison )\n\t- dup if max-signed-integer u< else logical then ;\n\n: #pad ( -- u : offset into pad area )\n\t64 ;\n\n: pad\n\t( the pad is used for temporary storage, and moves\n\talong with dictionary pointer, always in front of it )\n\there #pad + ;\n\n( @todo this can be improved a lot, currently it uses more\nspace than it has to, 4 cells instead of three.\n\nIt does:\n\n\tpush value\n\tpush value\n\nInstead of:\n\n\tmagic-2literal-word\n\tvalue\n\tvalue\n\n)\n: 2literal immediate ( x x -- : immediate write two literals into the dictionary )\n\tswap [literal] [literal] ;\n\n: latest ( get latest defined word )\n\tpwd @ ; \n\n: stdin ( -- fileid : push the fileid for the standard input channel ) \n\t`stdin @ ;\n\n: stdout ( -- fileid : push the fileid for the standard output channel ) \n\t`stdout @ ;\n\n: stderr ( -- fileid : push the fileid for the standard error channel ) \n\t`stderr @ ;\n\n: stdin? ( -- bool : are we reading from standard input )\n\t`fin @ stdin = ;\n\n: *+ ( x1 x2 x3 -- x ) \n\t* + ;\n\t\n: 2- ( x -- x : decrement by two )\n\t2 - ( x -- x ) ;\n\n: 2+ ( x -- x : increment by two )\n\t2 + ( x -- x ) ;\n\n: 3+ ( x -- x : increment by three )\n\t3 + ( x -- x ) ;\n\n: 2* ( x -- x : multiply by two )\n\t1 lshift ( x -- x ) ;\n\n: 2\/ ( x -- x : divide by two )\n\t1 rshift ( x -- x ) ;\n\n: 4* ( x -- x : multiply by four )\n\t2 lshift ( x -- x ) ;\n\n: 4\/ ( x -- x : divide by four )\n\t2 rshift ( x -- x ) ;\n\n: 8* ( x -- x : multiply by eight )\n\t3 lshift ( x -- x ) ;\n\n: 8\/ ( x -- x : divide by eight )\n\t3 rshift ( x -- x ) ;\n\n: 256* ( x -- x : multiply by 256 )\n\t8 lshift ( x -- x ) ;\n\n: 256\/ ( x -- x : divide by 256 )\n\t8 rshift ( x -- x ) ;\n\n: 2dup ( x1 x2 -- x1 x2 x1 x2 : duplicate two values )\n\tover over ;\n\n: mod ( x u -- x : calculate the remainder of x divided by u ) \n\t2dup \/ * - ;\n\n( @todo implement um\/mod in the VM, then use this to implement \/ and mod )\n: um\/mod ( x1 x2 -- rem quot : calculate the remainder and quotient of x1 divided by x2 ) \n\t2dup \/ >r mod r> ;\n\n: *\/ ( x1 x2 x3 -- x4 : multiply then divide, @warning this does not use a double cell for the multiply )\n\t * \/ ; \n\n: char ( -- x : read in a character from the input steam )\n\tkey drop key ;\n\n: [char] ( -- x : immediately read in a character from the input stream )\n\timmediate char [literal] ;\n\n: compose ( xt1 xt2 -- xt3 : create a new function from two xt-tokens )\n\t>r >r ( save execution tokens )\n\tpostpone :noname ( create a new :noname word for our xt-tokens )\n\tr> , ( write first token )\n\tr> , ( write second token )\n\tpostpone ; ; ( terminate new :noname )\n\n: unless ( bool -- : like 'if' but execute clause if false )\n\timmediate ['] 0= , postpone if ;\n\n: endif ( synonym for 'then' ) \n\timmediate postpone then ;\n\n: cells ( n1 -- n2 : convert a number of cells into a number of cells in address units ) \n\timmediate ;\n\n: cell+ ( a-addr1 -- a-addr2 ) \n\tcell + ;\n\n: negative? ( x -- bool : is a number negative? )\n\tsign-bit and logical ;\n\n: mask-byte ( x -- x : generate mask byte ) \n\t8* 255 swap lshift ;\n\n: select-byte ( u i -- c ) \n\t8* rshift 0xff and ;\n\n: xt-instruction ( extract instruction from execution token )\n\tcell+ @ >instruction ;\n\n: defined-word? ( CODE -- bool : is a word a defined or a built in words )\n\txt-instruction dolist = ;\n\n: char+ ( c-addr -- c-addr : increment a character address by the size of one character ) \n\t1+ ;\n\n: 2chars ( c-addr1 c-addr2 -- addr addr : convert two character addresses to two cell addresses ) \n\tchars swap chars swap ;\n\n: 2chars> ( addr addr -- c-addr c-addr: convert two cell addresses to two character addresses )\n\tchars> swap chars> swap ;\n\n: hex ( -- : print out hex ) \n\t16 base ! ;\n\n: octal ( -- : print out octal ) \n\t8 base ! ;\n\n: binary ( -- : print out binary ) \n\t2 base ! ;\n\n: decimal ( -- : print out decimal ) \n\t0 base ! ;\n\n: negate ( x -- x ) \n\t-1 * ;\n\n: abs ( x -- u : return the absolute value of a number )\n\tdup negative? if negate then ;\n\n: square ( x -- x ) \n\tdup * ;\n\n: sum-of-squares ( a b -- c : compute a^2 + b^2 to get c )\n\tsquare swap square + ;\n\n: drup ( x y -- x x ) \n\tdrop dup ;\n\n: +! ( x addr -- : add x to a value stored at addr ) \n\ttuck @ + swap ! ;\n\n: 1+! ( addr -- : increment a value at an address ) \n\t1 swap +! ;\n\n: 1-! ( addr -- : decrement a value at an address ) \n\t-1 swap +! ;\n\n: c+! ( x c-addr -- : add x to a value stored at c-addr )\n\ttuck c@ + swap c! ;\n\n: toggle ( addr u -- : complement the value at address with the bit pattern u ) \n\tover @ xor swap ! ;\n\n: lsb ( x -- x : mask off the least significant byte of a cell ) \n\t255 and ;\n\n: \\ ( -- : immediate word, used for single line comments )\n\timmediate begin key nl = until ;\n\n: ?dup ( x -- ? ) \n\tdup if dup then ;\n\n: min ( x y -- min : return the minimum of two integers ) \n\t2dup < if drop else swap drop then ;\n\n: max ( x y -- max : return the maximum of two integers ) \n\t2dup > if drop else swap drop then ;\n\n: limit ( x min max -- x : limit x with a minimum and maximum )\n\trot min max ;\n\n: >= ( x y -- bool ) \n\t< not ;\n\n: <= ( x y -- bool ) \n\t> not ;\n\n: 2@ ( a-addr -- x1 x2 : load two consecutive memory cells )\n\tdup 1+ @ swap @ ;\n\n: 2! ( x1 x2 a-addr -- : store two values as two consecutive memory cells )\n\t2dup ! nip 1+ ! ;\n\n: r@ ( -- x, R: x -- )\n\tr> r @ swap >r ;\n\n: rp@ ( -- x, R: x -- )\n\tr> r @ swap >r ;\n\n( @todo r!, rp! )\n\n: 0> ( x -- bool )\n\t0 > ;\n\n: 0< ( x -- bool )\n\t0 < ;\n\n: 0<> ( x -- bool )\n\t0 <> ;\n\n: signum ( x -- -1 | 0 | 1 : )\n\tdup 0< if drop -1 exit then\n\t 0> if 1 exit then\n\t0 ;\n\n: nand ( x x -- x : bitwise NAND ) \n\tand invert ;\n\n: odd ( x -- bool : is 'x' odd? )\n\t1 and ;\n\n: even ( x -- bool : is 'x' even? )\n\todd not ;\n\n: nor ( x x -- x : bitwise NOR ) \n\tor invert ;\n\n: ms ( u -- : wait at least 'u' milliseconds ) \n\tclock + begin dup clock u< until drop ;\n\n: sleep ( u -- : sleep for 'u' seconds )\n\t1000 * ms ;\n\n: align ( addr -- addr : align an address, nop in this implemented )\n\timmediate ; \n\n: ) ( -- : do nothing, this allows easy commenting out of code )\n\timmediate ;\n\n: bell ( -- : emit an ASCII BEL character ) \n\t7 emit ;\n\n: b\/buf ( -- u : bytes per buffer ) \n\t1024 ;\n\n: .d ( x -- x : debug print ) \n\tdup . ;\n\n: compile, ( x -- : )\n\t, ;\n\n: >mark ( -- : write a hole into the dictionary and push a pointer to it ) \n\there 0 , ;\n\n: r - r> u< ;\n\n: invalidate ( -- : invalidate this Forth core )\n\t1 `invalid ! ;\n\n: signed ( x -- bool : return true if sign bit set ) \n\t[ 1 size 8 * 1- lshift ] literal and logical ;\n\n: u>= ( x y -- bool : unsigned greater than or equal to )\n\t2dup u> >r = r> or ;\n\n: u<= ( x y -- bool : unsigned less than or equal to )\n\tu>= not ;\n\n: rdrop ( R: x -- : drop a value from the return stack )\n\tr> ( get caller's return address )\n\tr> ( get value to drop )\n\tdrop ( drop it like it's hot )\n\t>r ; ( return return address )\n\n: rdup\n\tr> ( get caller's return address )\n\tr> ( get value to duplicate )\n\tdup ( ... )\n\t>r >r >r ; ( make it all work )\n\n: again immediate\n\t( loop unconditionally in a begin-loop:\n\t\tbegin ... again )\n\t' branch , ;\n\n: source ( -- c-addr u )\n\t#tib ( size of input buffer, in characters )\n\ttib ; ( start of input buffer, in characters )\n\n: stdin? ( -- bool : are we reading from standard in? )\n\t`fin @ `stdin @ = ;\n\n: source-id ( -- 0 | -1 | file-id )\n\t( \t\n\tValue Input Source\n\t-1 String\n\t0 Reading from user input \/ standard in\n\tfile-id )\n\t`source-id @ \n\t0= if\n\t\tstdin? if 0 else `fin @ then\n\telse\n\t\t-1\n\tthen ;\n\n: under ( x1 x2 -- x1 x1 x2 )\n\t>r dup r> ;\n\n: 2nip ( n1 n2 n3 n4 -- n3 n4 ) \n\t>r >r 2drop r> r> ;\n\n: 2over ( n1 n2 n3 n4 \u2013 n1 n2 n3 n4 n1 n2 )\n\t>r >r 2dup r> swap >r swap r> r> -rot ;\n\n: 2swap ( n1 n2 n3 n4 \u2013 n3 n4 n1 n2 )\n\t>r -rot r> -rot ;\n\n: 2tuck ( n1 n2 n3 n4 \u2013 n3 n4 n1 n2 n3 n4 )\n\t2swap 2over ;\n\n: 3drop ( x1 x2 x3 -- )\n\tdrop 2drop ;\n\n: nos1+ ( x1 x2 -- x1+1 x2 : increment the next variable on that stack )\n\tswap 1+ swap ;\n\n: ?dup-if immediate ( x -- x | - : ?dup and if rolled into one! )\n\t['] ?dup , postpone if ;\n\n: ?if ( -- : non destructive if ) \n\timmediate ['] dup , postpone if ;\n\n: (hide) ( token -- hide-token : this hides a word from being found by the interpreter )\n\t?dup-if\n\t\tdup @ hidden-mask or swap tuck ! exit\n\tthen 0 ;\n\n( @todo refine ':' and ';' to use smudge, this could be done in libforth.c )\n: smudge ( -- : hide the latest defined word )\n\tlatest 1+ dup @ hidden-mask xor swap ! ;\n\n: hide ( WORD -- : hide with drop ) \n\tfind dup if (hide) then drop ;\n\n: reveal ( hide-token -- : reveal a hidden word ) \n\tdup @ hidden-mask invert and swap ! ;\n\n: ?exit ( x -- : exit current definition if not zero ) \n\tif rdrop exit then ;\n\n: decimal? ( c -- f : is character a number? )\n\t[char] 0 [ char 9 1+ ] literal within ;\n\n: lowercase? ( c -- f : is character lower case? )\n\t[char] a [ char z 1+ ] literal within ;\n\n: uppercase? ( C -- f : is character upper case? )\n\t[char] A [ char Z 1+ ] literal within ;\n\n: alpha? ( C -- f : is character part of the alphabet? )\n\tdup lowercase? swap uppercase? or ;\n\n: alphanumeric? ( C -- f : is character alphabetic or a number ? )\n\tdup alpha? swap decimal? or ;\n\n: printable? ( c -- bool : is printable, excluding new lines and tables )\n\t32 127 within ;\n\n: >upper ( c -- C : convert char to uppercase iff lower case )\n\tdup lowercase? if bl xor then ;\n\n: >lower ( C -- c : convert char to lowercase iff upper case )\n\tdup uppercase? if bl xor then ;\n\n: <=> ( x y -- z : spaceship operator! )\n\t2dup\n\t> if 2drop -1 exit then\n\t< ;\n\n: start-address ( -- c-addr : push the start address )\n\t`start-address @ ;\n\n: >real-address ( c-addr -- r-addr : convert an interpreter address to a real address )\n\tstart-address + ;\n\n: real-address> ( c-addr -- r-addr : convert a real address to an interpreter address )\n\tstart-address - ;\n\n: peek ( r-addr -- n : )\n\tpad chars> >real-address swap size memory-copy pad @ ;\n\n: poke ( n r-addr -- : )\n\tswap pad ! pad chars> >real-address size memory-copy ;\n\n: die! ( x -- : controls actions when encountering certain errors )\n\t`error-handler ! ;\n\n: start! ( cfa -- : set the word to execute at startup )\n\t`instruction ! ;\t\n\n: warm ( -- : restart the interpreter, warm restart )\n\t1 restart ;\n\n: trip ( x -- x x x : triplicate a number ) \n\tdup dup ;\n\n: roll ( xu xu-1 ... x0 u -- xu-1 ... x0 xu : move u+1 items on the top of the stack by u )\n\tdup 0 >\n\tif\n\t\tswap >r 1- roll r> swap\n\telse\n\t\tdrop\n\tthen ;\n\n: 2rot ( n1 n2 n3 n4 n5 n6 \u2013 n3 n4 n5 n6 n1 n2 )\n\t5 roll 5 roll ;\n\n: s>d ( x -- d : convert a signed value to a double width cell )\n\t( @note the if...else...then is only necessary as this Forths\n\tbooleans are 0 and 1, not 0 and -1 as it usually is )\n\tdup 0< if -1 else 0 then ;\n\n: trace ( level -- : set tracing level )\n\t`debug ! ;\n\n: verbose ( -- : get the log level )\n\t`debug @ ;\n\n: count ( c-addr1 -- c-addr2 u : get a string whose first char is its length )\n\tdup c@ nos1+ ;\n\n: bounds ( x y -- y+x x : make an upper and lower bound )\n\tover + swap ;\n\n: aligned ( unaligned -- aligned : align a pointer )\n\t[ size 1- ] literal + \n\t[ size 1- ] literal invert and ;\n\n: rdepth\n\tmax-core `stack-size @ - r @ swap - ;\n\n: r.s ( -- : print the contents of the return stack )\n\tr> \n\t[char] < emit rdepth . [char] > emit\n\tspace\n\trdepth dup 0> if dup\n\tbegin dup while r> -rot 1- repeat drop dup\n\tbegin dup while rot dup . >r 1- repeat drop\n\tthen drop cr \n\t>r ;\n\n: argv ( -- r-addr : push pointer to array of string pointers to program )\n\t`argv @ ;\n\n: argc ( -- u : push the number of arguments in the argv array )\n\t`argc @ ;\n\n: +- ( x1 x2 -- x3 : copy the sign of x1 to x2 giving x3 )\n\t[ sign-bit 1- ] literal and\n\tswap\n\tsign-bit and or ;\n\n: \/string ( c-addr1 u1 u2 -- c-addr2 u2 : advance a string by n characters )\n\tover min rot over + -rot - ;\n\nhide stdin?\n\n( ================================== DUMP ================================== )\n\\ : newline ( x -- x+1 : print a new line every fourth value )\n\\ \tdup 3 and 0= if cr then 1+ ;\n\\ \n\\ : address ( num count -- count : print current address we are dumping every fourth value )\n\\ \tdup >r\n\\ \t1- 3 and 0= if . [char] : emit space else drop then\n\\ \tr> ;\n\\ \n\\ : dump ( start count -- : print the contents of a section of memory )\n\\ \\\thex ( switch to hex mode )\n\\ \t1 >r ( save counter on return stack )\n\\ \tover + swap ( calculate limits: start start+count )\n\\ \tbegin \n\\ \t\t2dup u> ( stop if gone past limits )\n\\ \twhile \n\\ \t\tdup r> address >r\n\\ \t\tdup @ . 1+ \n\\ \t\tr> newline >r\n\\ \trepeat \n\\ \tr> drop\n\\ \t2drop ;\n\\ \n\\ hide newline\n\\ hide address \n( ================================== DUMP ================================== )\n\n: cfa immediate ( find-address -- cfa )\n\t( Given the address of the PWD field of a word this\n\tfunction will return an execution token for the word )\n\t( @todo if < dictionary start PWD is invalid )\n\t ;\n\n\\ : >body ( xt -- a-addr : a-addr is data field of a CREATEd word )\n\\\tcfa 5 + ;\n\n\n: execute ( xt -- : given an execution token, execute the word )\n\t( create a word that pushes the address of a hole to write to.\n\tA literal takes up two words, '!' takes up one, that's right,\n\tsome self modifying code! )\n\t[ here 3 cells + literal ] ( calculate place to write to )\n\t! ( write an execution token to a hole )\n\t[ 0 , ] ; ( this is the hole we write )\n\n( See: http:\/\/lars.nocrew.org\/dpans\/dpans9.htm\n@todo turn this into a lookup table of strings\n\n Code Reserved for\n ---- ------------\n -1 ABORT\n -2 ABORT\"\n -3 stack overflow\n -4 stack underflow\n -5 return stack overflow\n -6 return stack underflow\n -7 do-loops nested too deeply during execution\n -8 dictionary overflow\n -9 invalid memory address\n -10 division by zero\n -11 result out of range\n -12 argument type mismatch\n -13 undefined word\n -14 interpreting a compile-only word\n -15 invalid FORGET\n -16 attempt to use zero-length string as a name\n -17 pictured numeric output string overflow\n -18 parsed string overflow\n -19 definition name too long\n -20 write to a read-only location\n -21 unsupported operation [e.g., AT-XY on a\n too-dumb terminal]\n -22 control structure mismatch\n -23 address alignment exception\n -24 invalid numeric argument\n -25 return stack imbalance\n -26 loop parameters unavailable\n -27 invalid recursion\n -28 user interrupt\n -29 compiler nesting\n -30 obsolescent feature\n -31 >BODY used on non-CREATEd definition\n -32 invalid name argument [e.g., TO xxx]\n -33 block read exception\n -34 block write exception\n -35 invalid block number\n -36 invalid file position\n -37 file I\/O exception\n -38 non-existent file\n -39 unexpected end of file\n -40 invalid BASE for floating point conversion\n -41 loss of precision\n -42 floating-point divide by zero\n -43 floating-point result out of range\n -44 floating-point stack overflow\n -45 floating-point stack underflow\n -46 floating-point invalid argument\n -47 compilation word list deleted\n -48 invalid POSTPONE\n -49 search-order overflow\n -50 search-order underflow\n -51 compilation word list changed\n -52 control-flow stack overflow\n -53 exception stack overflow\n -54 floating-point underflow\n -55 floating-point unidentified fault\n -56 QUIT\n -57 exception in sending or receiving a character\n -58 [IF], [ELSE], or [THEN] exception )\n\n( @todo integrate catch\/throw into the interpreter as primitives )\n: catch ( xt -- exception# | 0 : return addr on stack )\n\tsp@ >r ( xt : save data stack pointer )\n\t`handler @ >r ( xt : and previous handler )\n\tr@ `handler ! ( xt : set current handler )\n\texecute ( execute returns if no throw )\n\tr> `handler ! ( restore previous handler )\n\tr> drop ( discard saved stack ptr )\n\t0 ; ( 0 : normal completion )\n\n( @todo use this everywhere )\n: throw ( ??? exception# -- ??? exception# )\n\t?dup-if ( exc# \\ 0 throw is no-op )\n\t\t`handler @ r ! ( exc# : restore prev return stack )\n\t\tr> `handler ! ( exc# : restore prev handler )\n\t\tr> swap >r ( saved-sp : exc# on return stack )\n\t\tsp! drop r> ( exc# : restore stack )\n\t\t( return to the caller of catch because return )\n\t\t( stack is restored to the state that existed )\n\t\t( when catch began execution )\n\tthen ; \n\n: interpret ( c1\" xxx\" ... cn\" xxx\" -- : This word implements the interpreter loop )\n\tbegin \n\t' read catch \n\t?dup-if [char] ! emit tab . cr then ( exception handler of last resort )\n\tagain ;\n\n\n: [interpret] ( c1\" xxx\" ... cn\" xxx\" -- : immediate version of interpret )\n\timmediate interpret ;\n\ninterpret ( use the new interpret word, which can catch exceptions )\n\nfind [interpret] cell+ start! ( the word executed on restart is now our new word )\n\n( The following words are using in various control structure related\nwords to make sure they only execute in the correct state )\n\n: ?comp ( -- : error if not compiling )\n\tstate @ 0= if -22 throw then ; \n\n: ?exec ( -- : error if not executing )\n\tstate @ if -22 throw then ; \n\n\n( ========================== Basic Word Set ================================== )\n\n( ========================== DOER\/MAKE ======================================= )\n( DOER\/MAKE is a word set that is quite powerful and is described in Leo Brodie's\nbook \"Thinking Forth\". It can be used to make words whose behavior can change\nafter they are defined. It essentially makes the structured use of self-modifying\ncode possible, along with the more common definitions of \"defer\/is\".\n\nAccording to \"Thinking Forth\", it has two purposes:\n\n1. To change the state of a function.\n2. To factor out common phrases of a words definition.\n\nAn example of the first instance:\n\n\tdoer say\n\t: sad \" Good bye, cruel World!\" cr ;\n\t: happy \" Hello, World!\" cr ;\n\n\t: person say ;\n\n\tmake person happy\n\tperson \\ prints \"Good bye, cruel World!\"\n\n\tmake person sad \n\tperson \\ prints \"Hello, World!\" \n\nAn example of the second:\n\n\tdoer op\n\n\t: sum \\ n0 ... nX X -- sum<0..X> \n\t\tmake op + 1 do op loop ;\n\n\t: mul \\ n0 ... nX X -- mul<0..X> \n\t\tmake op * 1 do op loop ;\n\nThe above example is a bit contrived, the definitions and functionality\nare too simple for this to be worth factoring out, but it shows how you\ncan use DOER\/MAKE. )\n\n: noop ; ( -- : default word to execute for doer, does nothing )\n\n: doer ( c\" xxx\" -- : make a work whose behavior can be changed by make )\n\timmediate ?exec :: ['] noop , postpone ; ;\n\n: found? ( xt -- xt : thrown an exception if the execution token is zero [not found] ) \n\tdup 0= if -13 throw then ;\n\n( It would be nice to provide a MAKE that worked with execution tokens\nas well, although \"defer\" and \"is\" can be used for that. MAKE expects\ntwo word names to be given as arguments. It will then change the behavior \nof the first word to use the second. MAKE is a state aware word. )\n\n: make immediate ( c1\" xxx\" c2\" xxx\" : change parsed word c1 to execute c2 )\n\tfind found? cell+\n\tfind found?\n\tstate @ if ( compiling )\n\t\tswap postpone 2literal ['] ! ,\n\telse ( command mode )\n\t\tswap !\n\tthen ;\n\nhide noop ( noop! noop! )\n\n( ========================== DOER\/MAKE ======================================= )\n\n( ========================== Extended Word Set =============================== )\n\n: log ( u base -- u : command the _integer_ logarithm of u in base )\n\t>r \n\tdup 0= if -11 throw then ( logarithm of zero is an error )\n\t0 swap\n\tbegin\n\t\tnos1+ rdup r> \/ dup 0= ( keep dividing until 'u' is zero )\n\tuntil\n\tdrop 1- rdrop ;\n\n: log2 ( u -- u : compute the _integer_ logarithm of u )\n\t2 log ;\n\n: time ( \" ccc\" -- n : time the number of milliseconds it takes to execute a word )\n\tclock >r\n\tfind execute\n\tclock r> - ;\n\n( defer...is is probably not standards compliant, it is still neat! )\n: (do-defer) ( -- self : pushes the location into which it is compiled )\n\tr> dup >r 1- ;\n\n: defer immediate ( \" ccc\" -- , Run Time -- location : \n\tcreates a word that pushes a location to write an execution token into )\n\t?exec\n\t:: ' (do-defer) , postpone ; ;\n\n: is ( location \" ccc\" -- : make a deferred word execute a word ) \n\tfind found? swap ! ;\n\nhide (do-defer)\nhide found?\n\n( The \"tail\" function implements tail calls, which is just a jump\nto the beginning of the words definition, for example this\nword will never overflow the stack and will print \"1\" followed\nby a new line forever,\n\n\t: forever 1 . cr tail ;\n\nWhereas\n\n\t: forever 1 . cr recurse ;\n\nor\n\n\t: forever 1 . cr forever ;\n\nWould overflow the return stack. )\n\nhide tail\n: tail ( -- : perform tail recursion in current word definition )\n\timmediate\n\t?comp\n\tlatest cell+\n\t' branch ,\n\there - cell+ , ;\n\n: recurse immediate\n\t( This function implements recursion, although this interpreter\n\tallows calling a word directly. If used incorrectly this will\n\tblow up the return stack.\n\n\tWe can test \"recurse\" with this factorial function:\n\t : factorial dup 2 < if drop 1 exit then dup 1- recurse * ; )\n\t?comp\n\tlatest cell+ , ;\n\n: factorial ( x -- x : compute the factorial of a number )\n\tdup 2 < if drop 1 exit then dup 1- recurse * ;\n\n: myself ( -- : myself is a synonym for recurse ) \n\timmediate postpone recurse ;\n\n: gcd ( x1 x2 -- x : greatest common divisor )\n\tdup if tuck mod tail then drop ;\n\n( ========================== Extended Word Set =============================== )\n\n( ========================== For Each Loop =================================== )\n\n( The foreach word set allows the user to take action over an entire array\nwithout setting up loops and checking bounds. It behaves like the foreach loops\nthat are popular in other languages. \n\nThe foreach word accepts a string and an execution token, for each character\nin the string it passes the current address of the character that it should\noperate on. \n\nThe complexity of the foreach loop is due to the requirements placed on it.\nIt cannot pollute the variable stack with values it needs to operate on, and\nit cannot store values in local variables as a foreach loop could be called\nfrom within the execution token it was passed. It therefore has to store all\nof it uses on the return stack for the duration of EXECUTE.\n\nAt the moment it only acts on strings as \"\/string\" only increments the address \npassed to the word foreach executes to the next character address. )\n\n\\ (FOREACH) leaves the point at which the foreach loop terminated on the stack,\n\\ this allows programmer to determine if the loop terminated early or not, and\n\\ at which point.\n: (foreach) ( c-addr u xt -- c-addr u : execute xt for each cell in c-addr u \n\treturning number of items not processed )\n\tbegin \n\t\t3dup >r >r >r ( c-addr u xt R: c-addr u xt )\n\t\tnip ( c-addr xt R: c-addr u xt )\n\t\texecute ( R: c-addr u xt )\n\t\tr> r> r> ( c-addr u xt )\n\t\t-rot ( xt c-addr u )\n\t\t1 \/string ( xt c-addr u )\n\t\tdup 0= if rot drop exit then ( End of string - drop and exit! )\n\t\trot ( c-addr u xt )\n\tagain ;\n\n\\ If we do not care about returning early from the foreach loop we\n\\ can instead call FOREACH instead of (FOREACH), it simply drops the\n\\ results (FOREACH) placed on the stack.\n: foreach ( c-addr u xt -- : execute xt for each cell in c-addr u )\n\t(foreach) 2drop ;\n\n\\ RETURN is used for an early exit from within the execution token, it\n\\ leaves the point at which it exited \n: return ( -- n : return early from within a foreach loop function, returning number of items left )\n\trdrop ( pop off this words return value )\n\trdrop ( pop off the calling words return value )\n\trdrop ( pop off the xt token )\n\tr> ( save u )\n\tr> ( save c-addr )\n\trdrop ; ( pop off the foreach return value )\n\n\\ SKIP is an example of a word that uses the foreach loop mechanism. It\n\\ takes a string and a character and returns a string that starts at\n\\ the first occurrence of that character in that string - or until it\n\\ reaches the end of the string.\n\n\\ SKIP is defined in two steps, first there is a word, (SKIP), that\n\\ exits the foreach loop if there is a match, if there is no match it\n\\ does nothing. In either case it leaves the character to skip until\n\\ on the stack.\n\n: (skip) ( char c-addr -- char : exit out of foreach loop if there is a match )\n\tover swap c@ = if return then ;\n\n\\ SKIP then setups up the foreach loop, the char argument will present on the\n\\ stack when (SKIP) is executed, it must leave a copy on the stack whatever\n\\ happens, this is then dropped at the end. (FOREACH) leaves the point at\n\\ which the loop terminated on the stack, which is what we want.\n: skip ( c-addr u char -- c-addr u : skip until char is found or until end of string )\n\t-rot ['] (skip) (foreach) rot drop ;\nhide (skip)\n\n( ========================== For Each Loop =================================== )\n\n( The words described here on out get more complex and will require more\nof an explanation as to how they work. )\n\n( ========================== CREATE DOES> ==================================== )\n\n( The following section defines a pair of words \"create\" and \"does>\" which\nare a powerful set of words that can be used to make words that can create\nother words. \"create\" has both run time and compile time behavior, whilst\n\"does>\" only works at compile time in conjunction with \"create\". These two\nwords can be used to add constants, variables and arrays to the language,\namongst other things.\n\nA simple version of create is as follows\n\n\t: create :: dolist , here 2 cells + , ' exit , 0 state ! ;\n\nBut this version is much more limited.\n\n\"create\"...\"does>\" is one of the constructs that makes Forth Forth, it\nallows the creation of words which can define new words in themselves,\nand thus allows us to extend the language easily.\n)\n\n: write-quote ( -- : A word that writes ' into the dictionary )\n\t['] ' , ; \n\n: write-exit ( -- : A word that write exit into the dictionary )\n\t['] _exit , ;\n\n: write-compile, ( -- : A word that writes , into the dictionary ) \n\t' , , ;\n\n: command-mode ( -- : put the interpreter into command mode )\n\tfalse state ! ;\n\n: command-mode-create ( create a new work that pushes its data field )\n\t:: ( compile a word )\n\tdolit , ( write push into new word )\n\there 2 cells + , ( push a pointer to data field )\n\tpostpone ; ; ( write exit and switch to command mode )\n\n: mark write-compile, ( Write in a place holder 0 and push a pointer to to be used by does> )\n\twrite-quote write-exit write-compile, ( Write in an exit in the word we're compiling. )\n\t['] command-mode , ; ( Make sure to change the state back to command mode )\n\n: create immediate ( create word is quite a complex forth word )\n\tstate @ \n\tif \n\t\tpostpone ( hole-to-patch -- )\n\timmediate\n\t?comp\n\twrite-exit ( we don't want the defining word to exit, but the *defined* word to )\n\there swap ! ( patch in the code fields to point to )\n\tdolist , ; ( write a run in )\n\nhide write-quote\nhide write-compile,\nhide write-exit\n\n( Now that we have create...does> we can use it to create arrays, variables\nand constants, as we mentioned before. )\n\n: array ( u c\" xxx\" -- : create a named array of length u )\n\tcreate allot does> + ;\n\n: variable ( x c\" xxx\" -- : create a variable will initial value of x )\n\tcreate , does> ;\n\n\\ : constant ( x c\" xxx\" -- : create a constant with value of x ) \n\\\tcreate , does> @ ;\n\n: table ( u c\" xxx\" --, Run Time: -- addr u : create a named table )\n\tcreate dup , allot does> dup @ ;\n\n: string ( u c\" xxx\" --, Run Time: -- c-addr u : create a named string )\n\tcreate dup , chars allot does> dup @ swap 1+ chars> swap ;\n\n\\ : +field \\ n <\"name\"> -- ; exec: addr -- 'addr\n\\ create over , +\n\\ does> @ + ;\n\\ \n\\ : begin-structure \\ -- addr 0 ; -- size\n\\ \tcreate\n\\ \there 0 0 , \\ mark stack, lay dummy\n\\ \tdoes> @ ; \\ -- rec-len\n\\ \n\\ : end-structure \\ addr n --\n\\ swap ! ; \\ set len \n\\ \n\\ begin-structure point\n\\ \tpoint +field p.x\n\\ \tpoint +field p.y\n\\ end-structure\n\\ \n\\ This should work...\n\\ : buffer: ( u c\" xxx\" --, Run Time: -- addr )\n\\\tcreate allot ;\n\n: 2constant \n\tcreate , , does> dup 1+ @ swap @ ;\n\n: 2variable \n\tcreate , , does> ;\n\n: enum ( x \" ccc\" -- x+1 : define a series of enumerations )\n\tdup constant 1+ ; \n\n( ========================== CREATE DOES> ==================================== )\n\n( ========================== DO...LOOP ======================================= )\n\n( The following section implements Forth's do...loop constructs, the\nword definitions are quite complex as it involves a lot of juggling of\nthe return stack. Along with begin...until do loops are one of the\nmain looping constructs. \n\nUnlike begin...until do accepts two values a limit and a starting value,\nthey are also words only to be used within a word definition, some Forths\nextend the semantics so looping constructs operate in command mode, this\nForth does not do that as it complicates things unnecessarily.\n\nExample:\n\t\n\t: example-1 10 1 do i . i 5 > if cr leave then loop 100 . cr ; \n\texample-1\n\nPrints:\n\t1 2 3 4 5 6\n\nIn \"example-1\" we can see the following:\n\n1. A limit, 10, and a start value, 1, passed to \"do\".\n2. A word called 'i', which is the current count of the loop\n3. If the count is greater than 5, we call a word call 'leave', this\nword exits the current loop context as well as the current calling\nword.\n4. \"100 . cr\" is never called. This should be changed in future\nrevision, but this version of leave exits the calling word as well.\n\n'i', 'j', and 'leave' *must* be used within a do...loop construct. \n\nIn order to remedy point 4. loop should not use branch but instead \nshould use a value to return to which it pushes to the return stack )\n\n: (do)\n\tswap ( swap the limit and start )\n\tr> ( save our return stack to temporary variable )\n\t-rot ( limit start return -- return start limit )\n\t>r ( push limit onto return stack )\n\t>r ( push start onto return stack )\n\t>r ; ( restore our return address )\n\n: do immediate ( Run time: high low -- : begin do...loop construct )\n\t?comp\n\t' (do) ,\n\tpostpone begin ; \n\n: (unloop) ( -- , R: i limit -- : remove limit and i from )\n\tr> ( save our return address )\n\trdrop ( pop off i )\n\trdrop ( pop off limit )\n\t>r ; ( restore our return stack )\n\n: (+loop) ( x -- bool : increment loop variable by x and test it )\n\tr@ 1- ( get the pointer to i )\n\t+! ( add value to it )\n\tr@ 1- @ ( find i again )\n\tr@ 2- @ ( find the limit value )\n\tu>= ;\n\n: (loop) ( -- bool : increment loop variable by 1 and test it )\n\tr@ 1- ( get the pointer to i )\n\t1+! ( add one to it )\n\tr@ 1- @ ( find the value again )\n\tr@ 2- @ ( find the limit value )\n\tu>= ;\n\n: loop ( -- : end do...loop construct )\n\timmediate ?comp ' (loop) , postpone until ' (unloop) , ;\n\n: +loop ( x -- : end do...+loop loop construct )\n\timmediate ?comp ' (+loop) , postpone until ' (unloop) , ;\n\n: leave ( -- , R: i limit return -- : break out of a do-loop construct )\n\t(unloop)\n\trdrop ; ( return to the caller's caller routine )\n\n: ?leave ( x -- , R: i limit return -- | i limit return : conditional leave )\n\tif\n\t\t(unloop)\n\t\trdrop ( return to the caller's caller routine )\n\tthen ;\n\n\\ @todo define '(i)', '(j)' and '(k)', then make their wrappers, 'i', 'j'\n\\ and 'k' call ?comp then compile a pointer to the thing that implements them,\n\\ likewise for leave, loop and +loop.\n: i ( -- i : Get current, or innermost, loop index in do...loop construct )\n\tr> r> ( pop off return address and i )\n\ttuck ( tuck i away )\n\t>r >r ; ( restore return stack )\n\n: j ( -- j : Get outermost loop index in do...loop construct )\n\t4 rpick ;\n\n( This is a simple test function for the looping, for interactive\ntesting and debugging:\n : mm 5 1 do i . cr 4 1 do j . tab i . cr loop loop ; )\n\n: range ( nX nY -- nX nX+1 ... nY ) \n\tnos1+ do i loop ;\n\n: repeater ( n0 X -- n0 ... nX ) \n\t1 do dup loop ;\n\n: sum ( n0 ... nX X -- sum<0..X> ) \n\t1 do + loop ;\n\n: mul ( n0 ... nX X -- mul<0..X> ) \n\t1 do * loop ;\n\n: reverse ( x1 ... xn n -- xn ... x1 : reverse n items on the stack )\n\t0 do i roll loop ;\n\n( ========================== DO...LOOP ======================================= )\n\n0 variable column-counter\n4 variable column-width\n\n: column ( i -- )\t\n\tcolumn-width @ mod not if cr then ;\n\n: column.reset\t\t\n\t0 column-counter ! ;\n\n: auto-column\t\t\n\tcolumn-counter dup @ column 1+! ;\n\n: alignment-bits \n\t[ 1 size log2 lshift 1- literal ] and ;\n\n0 variable x\n: x! ( x -- ) \n\tx ! ;\n\n: x@ ( -- x ) \n\tx @ ;\n\n: 2>r ( x1 x2 -- R: x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tswap\n\t\t>r\n\t\t>r\n\tx@ >r ; ( restore return address )\n\n: 2r> ( R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tr>\n\t\tr>\n\t\tswap\n\tx@ >r ; ( restore return address )\n\n: 2r@ ( -- x1 x2 , R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\tr> r>\n\t2dup\n\t>r >r\n\tswap\n\tx@ >r ; ( restore return address )\n\n: unused ( -- u : push the amount of core left ) \n\tmax-core here - ;\n\n: accumulator ( initial \" ccc\" -- : make a word that increments by a value and pushes the result )\n\tcreate , does> tuck +! @ ;\n\n: counter ( \" ccc\" --, Run Time: -- x : make a word that increments itself by one, starting from zero )\n\tcreate -1 , does> dup 1+! @ ;\n\n0 variable delim\n: accepter ( c-addr max delimiter -- i )\n\t( store a \"max\" number of chars at c-addr until \"delimiter\" encountered,\n\tthe number of characters stored is returned )\n\tdelim ! ( store delimiter used to stop string storage when encountered)\n\t0\n\tdo\n\t\tkey dup delim @ <>\n\t\tif\n\t\t\tover c! 1+\n\t\telse ( terminate string )\n\t\t\tdrop 0 swap c! \n\t\t\ti \n\t\t\tleave\n\t\tthen\n\tloop\n\t-18 throw ; ( read in too many chars )\nhide delim\n\n: skip ( char -- : read input until string is reached )\n\tkey drop >r 0 begin drop key dup rdup r> <> until rdrop ;\n\n: word ( c -- c-addr : parse until 'c' is encountered, push transient counted string )\n\tdup skip chere 1+ c!\n\t>r\n\tchere 2+\n\tpad here - chars>\n\tr> accepter 1+\n\tchere c!\n\tchere ;\nhide skip\n\n: accept ( c-addr +n1 -- +n2 : see accepter definition ) \n\tnl accepter ;\n\n: (subst) ( char1 char2 c-addr )\n\t3dup ( char1 char2 c-addr char1 char2 c-addr )\n\tc@ = if ( char1 char2 c-addr char1 )\n\t\tswap c! ( match, substitute character )\n\telse ( char1 char2 c-addr char1 )\n\t\t2drop ( no match )\n\tthen ;\n\n: subst ( c-addr u char1 char2 -- replace all char1 with char2 in string )\n\tswap\n\t2swap\n\t['] (subst) foreach 2drop ;\nhide (subst)\n\n0xFFFF constant max-string-length\n\n: (.\") ( char -- c-addr u )\n\t( @todo This really needs simplifying, to do this\n\ta set of words that operate on a temporary buffer can\n\tbe used )\n\t( Write a string into word being currently defined, this\n\tcode has to jump over the string it has just put into the\n\tdictionary so normal execution of a word can continue. The\n\tlength and character address of the string are left on the\n\tstack )\n\t>r ( save delimiter )\n\t' branch , ( write in jump, this will jump past the string )\n\t>mark ( make hole )\n\tdup 1+ chars> ( calculate address to write to )\n\tmax-string-length \n\tr> ( restore delimiter )\n\taccepter dup >r ( write string into dictionary, save index )\n\taligned 2dup size \/ ( stack: length hole char-len hole )\n\t1+ dup allot ( update dictionary pointer with string length )\n\t1+ swap ! ( write place to jump to )\n\tdrop ( do not need string length anymore )\n\t1+ chars> ( calculate place to print )\n\tr> ; ( restore index and address of string )\n\n: length ( c-addr u -- u : push the length of an ASCIIZ string )\n tuck 0 do dup c@ 0= if 2drop i leave then 1+ loop ;\n\n: asciiz? ( c-addr u -- : is a Forth string also a ASCIIZ string )\n\ttuck length <> ;\n\n: asciiz ( c-addr u -- : trim a string until NUL terminator )\n\t2dup length nip ;\n\n\n: (type) ( c-addr -- ) \n\tc@ emit ;\n\n: type ( c-addr u -- : print out 'u' characters at c-addr )\n\t['] (type) foreach ;\nhide (type)\n\n: do-string ( char -- : write a string into the dictionary reading it until char is encountered )\n\t(.\") \n\tstate @ if swap [literal] [literal] then ;\n\n: fill ( c-addr u char -- : fill in an area of memory with a character, only if u is greater than zero )\n\t-rot\n\t0 do 2dup i + c! loop\n\t2drop ;\n\n: compare ( c-addr1 u1 c-addr2 u2 -- n : compare two strings, not quite compliant yet )\n\t>r swap r> min >r\n\tstart-address + swap start-address + r>\n\tmemory-compare ;\n\n128 string sbuf\n: s\" ( \"ccc\" --, Run Time -- c-addr u )\n\tkey drop sbuf 0 fill sbuf [char] \" accepter sbuf drop swap ;\nhide sbuf\n\n( @todo these strings really need rethinking, state awareness needs to be removed... )\n: type, \n\tstate @ if ' type , else type then ;\n\n: c\" \n\timmediate key drop [char] \" do-string ;\n\n: \" \n\timmediate key drop [char] \" do-string type, ;\n\n: sprint ( c -- : print out chars until 'c' is encountered )\n\tkey drop ( drop next space )\n\t>r ( save delimiter )\n\tbegin\n\t\tkey dup ( get next character )\n\t\trdup r> ( get delimiter )\n\t\t<> if emit 0 then\n\tuntil rdrop ;\n\n: .( \n\timmediate [char] ) sprint ;\nhide sprint\n\n: .\" \n\timmediate key drop [char] \" do-string type, ;\n\nhide type,\n\n( This word really should be removed along with any usages of this word, it\nis not a very \"Forth\" like word, it accepts a pointer to an ASCIIZ string and\nprints it out, it also does not checking of the returned values from write-file )\n: print ( c-addr -- : print out a string to the standard output )\n\t-1 over >r length r> swap stdout write-file 2drop ;\n\n: ok \n\t\" ok\" cr ;\n\n: empty-stack ( x-n ... x-0 -- : empty the variable stack )\n\tbegin depth while drop repeat ;\n\n: (quit) ( -- : do the work of quit, without the restart )\n\t0 `source-id ! ( set source to read from file )\n\t`stdin @ `fin ! ( read from stdin )\n\tpostpone [ ( back into command mode )\n\t' interpret start! ; ( set interpreter starting word )\n\n: quit ( -- : Empty return stack, go back to command mode, read from stdin, interpret input )\n\t(quit)\n\t-1 restart ; ( restart the interpreter )\n\n: abort\n\t-1 throw ;\n\n: (abort\") ( do the work of abort )\n\t(quit)\n\t-2 throw ;\n\n: abort\" immediate \n\tpostpone \"\n\t' cr , ' (abort\") , ;\n\n( ==================== CASE statements ======================== )\n( This simple set of words adds case statements to the interpreter,\nthe implementation is not particularly efficient, but it works and\nis simple.\n\nBelow is an example of how to use the CASE statement, the following\nword, \"example\" will read in a character and switch to different\nstatements depending on the character input. There are two cases,\nwhen 'a' and 'b' are input, and a default case which occurs when\nnone of the statements match:\n\n\t: example\n\t\tchar \n\t\tcase\n\t\t\t[char] a of \" a was selected \" cr endof\n\t\t\t[char] b of \" b was selected \" cr endof\n\n\t\t\tdup \\ encase will drop the selector\n\t\t\t\" unknown char: \" emit cr\n\t\tendcase ;\n\n\texample a \\ prints \"a was selected\"\n\texample b \\ prints \"b was selected\"\n\texample c \\ prints \"unknown char: c\"\n\nOther examples of how to use case statements can be found throughout \nthe code. \n\nFor a simpler case statement see, Volume 2, issue 3, page 48 \nof Forth Dimensions at http:\/\/www.forth.org\/fd\/contents.html )\n\n: case immediate\n\t?comp\n\t' branch , 3 , ( branch over the next branch )\n\there ' branch , ( mark: place endof branches back to with again )\n\t>mark swap ; ( mark: place endcase writes jump to with then )\n\n: over= ( x y -- [x 0] | 1 : )\n\tover = if drop 1 else 0 then ;\n\n: of\n\timmediate ?comp ' over= , postpone if ;\n\n: endof\n\timmediate ?comp over postpone again postpone then ;\n\n: endcase\n\timmediate ?comp ' drop , 1+ postpone then drop ;\n\n( ==================== CASE statements ======================== )\n\n( ==================== Hiding Words =========================== )\n\n: }hide ( should only be matched with 'hide{' )\n\timmediate -22 throw ;\n\n: hide{ ( -- : hide a list of words, the list is terminated with \"}hide\" )\n\t?exec\n\tbegin\n\t\tfind ( find next word )\n\t\tdup [ find }hide ] literal = if\n\t\t\tdrop exit ( terminate hide{ )\n\t\tthen\n\t\tdup 0= if -15 throw then\n\t\t(hide) drop\n\tagain ;\n\nhide (hide)\n\n( ==================== Hiding Words =========================== )\n\n: spaces ( n -- : print n spaces ) \n\t0 do space loop ;\n\n: erase ( addr u : erase a block of memory )\n\t2chars> 0 fill ;\n\n: blank ( c-addr u : fills a string with spaces )\n\tbl fill ;\n\n( move should check that u is not negative )\n: move ( addr1 addr2 u -- : copy u words of memory from 'addr2' to 'addr1' )\n\t0 do\n\t\t2dup i + @ swap i + !\n\tloop\n\t2drop ;\n\n( It would be nice if move and cmove could share more code, as they do exactly\n the same thing but with different load and store functions, cmove> )\n: cmove ( c-addr1 c-addr2 u -- : copy u characters of memory from 'c-addr2' to 'c-addr1' )\n\t0 do\n\t\t2dup i + c@ swap i + c!\n\tloop\n\t2drop ;\n\n( ==================== Conditional Compilation ================ )\n\n( The words \"[if]\", \"[else]\" and \"[then]\" implement conditional compilation,\nthey can be nested as well\n\nSee http:\/\/lars.nocrew.org\/dpans\/dpans15.htm for more information\n\nA much simpler conditional compilation method is the following\nsingle word definition:\n\n : compile-line? 0= if [ find \\\\ , ] then ;\n\nWhich will skip a line if a conditional is false, and compile it\nif true )\n\n( These words really, really need refactoring, I could use the newly defined \n \"defer\" to help out with this )\n0 variable nest ( level of [if] nesting )\n0 variable [if]-word ( populated later with \"find [if]\" )\n0 variable [else]-word ( populated later with \"find [else]\")\n: [then] immediate ;\n: reset-nest 1 nest ! ;\n: unnest? [ find [then] ] literal = if nest 1-! then ;\n: nest? [if]-word @ = if nest 1+! then ;\n: end-nest? nest @ 0= ;\n: match-[else]? [else]-word @ = nest @ 1 = and ;\n\n: [if] ( bool -- : conditional execution )\n\tunless\n\t\treset-nest\n\t\tbegin\n\t\t\tfind\n\t\t\tdup nest?\n\t\t\tdup match-[else]? if drop exit then\n\t\t\t unnest?\n\t\t\tend-nest?\n\t\tuntil\n\tthen ;\n\n: [else] ( discard input until [then] encounter, nesting for [if] )\n\treset-nest\n\tbegin\n\t\tfind\n\t\tdup nest? unnest?\n\t\tend-nest?\n\tuntil ;\n\nfind [if] [if]-word !\nfind [else] [else]-word !\n\n: ?( if postpone ( then ; \\ conditionally read until ')'\n: ?\\ if postpone \\ then ;\n: 16bit\\ size 2 <> if postpone \\ then ;\n: 32bit\\ size 4 <> if postpone \\ then ;\n: 64bit\\ size 8 <> if postpone \\ then ;\n\nhide{ \n\t[if]-word [else]-word nest \n\treset-nest unnest? match-[else]? \n\tend-nest? nest? \n}hide\n\n( ==================== Conditional Compilation ================ )\n\n( ==================== Endian Words =========================== )\n\nsize 2 = [if] 0x0123 `x ! [then]\nsize 4 = [if] 0x01234567 `x ! [then]\nsize 8 = [if] 0x01234567abcdef `x ! [then]\n\n: endian ( -- bool : returns the endianess of the processor, little = 0, big = 1 )\n\t[ `x chars> c@ 0x01 = ] literal ;\n\n: swap16 ( x -- x : swap the byte order a 16 bit number )\n\tdup 256* 0xff00 and >r 256\/ lsb r> or ;\n\nsize 4 >= [if] \n\t: swap32 \n\t\tdup 0xffff and swap16 16 lshift swap\n\t\t16 rshift 0xffff and swap16 or ;\n[then]\n\nsize 8 >= [if]\n\t: swap64 ( x -- x : swap the byte order of a 64 bit number )\n\t\t dup 0xffffffff and swap32 32 lshift swap\n\t\t 32 rshift 0xffffffff and swap32 or ;\n[then]\n\nsize 2 = [if]\n\tendian \n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\tswap16 ;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\t;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\tswap16 ;\n\t[then]\n[then]\n\nsize 4 = [if]\n\tendian \n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\tswap32 ;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\t;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\tswap32 ;\n\t[then]\n[then]\n\nsize 8 = [if]\n\tendian \n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\tswap64 ;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\t;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\tswap64 ;\n\t[then]\n[then]\n\n( ==================== Endian Words =========================== )\n\n( ==================== Misc words ============================= )\n\n: (base) ( -- base : unmess up libforth's base variable )\n\tbase @ 0= if 10 else base @ then ;\n\n: #digits ( u -- u : number of characters needed to represent 'u' in current base )\n\tdup 0= if 1+ exit then\n\t(base) log 1+ ;\n\n: digits ( -- u : number of characters needed to represent largest unsigned number in current base )\n\t-1 #digits ;\n\n: print-number ( u -- print a number taking up a fixed amount of space on the screen )\n\tbase @ 16 = if . exit then ( @todo this is a hack related to libforth printing out hex specially)\n\tdup #digits digits swap - dup 0<> if spaces else drop then . ;\n\n: address ( u -- : print out and address )\n\t@ print-number ;\n\n0 variable counter\n\n: counted-column ( index -- : special column printing for dump )\n\tcounter @ column-width @ mod\n\tnot if cr print-number \" :\" space else drop then\n\tcounter 1+! ;\n\n: as-chars ( x n -- : print a cell out as characters, upto n chars )\n\t0 ( from zero to the size of a cell )\n\tdo\n\t\tdup ( copy variable to print out )\n\t\tsize i 1+ - select-byte ( select correct byte )\n\t\tdup printable? not ( is it not printable )\n\t\tif drop [char] . then ( print a '.' if it is not )\n\t\temit ( otherwise print it out )\n\tloop\n\tspace ( print out space after )\n\tdrop ; ( drop cell we have printed out )\n\n: lister ( addr u addr -- )\n\t0 counter ! 1- swap \n\tdo \n\t\tdup counted-column 1+ i address i @ size as-chars \n\tloop ;\n\n( @todo this function should make use of 'defer' and 'is', then different\nversion of dump could be made that swapped out 'lister' )\n: dump ( addr u -- : dump out 'u' cells of memory starting from 'addr' )\n\t1+ over + under lister drop \n\tcr ;\n\nhide{ counted-column counter as-chars address print-number }hide\n\n( Fence can be used to prevent any word defined before it from being forgotten \nUsage:\n\there fence ! )\n0 variable fence\n\n: (forget) ( pwd-token -- : forget a found word and everything after it )\n\tdup 0= if -15 throw then ( word not found! )\n\tdup fence @ u< if -15 throw then ( forgetting a word before fence! )\n\tdup @ pwd ! h ! ;\n\n: forget ( c\" xxx\" -- : forget word and every word defined after it )\n\tfind 1- (forget) ;\n\n: marker ( c\" xxx\" -- : make word the forgets itself and words after it)\n\t:: latest [literal] ' (forget) , postpone ; ;\nhere fence ! ( This should also be done at the end of the file )\nhide (forget)\n\n: ** ( b e -- x : exponent, raise 'b' to the power of 'e')\n\t?dup-if\n\t\tover swap\n\t\t1 do over * loop \n\t\tnip\n\telse\n\t\tdrop 1\n\tendif ;\n\n0 variable a\n0 variable b\n0 variable m\n: equal ( a1...an b1...bn n -- a1...an b1...bn bool : determine if two lists are equal )\n\t( example: \n\t\t1 2 3 \n\t\t1 2 3 \n\t\t3 equal \n\treturns: 1 )\n\tdup m ! 1+ 1 ( store copy of length and use as loop index )\n\tdo \n\t\ti 1- pick b ! ( store ith element of list in b1...bn )\n\t\ti m @ + 1- pick a ! ( store ith element of list in a1...an )\n\t\ta @ b @ <> ( compare a and b for equality )\n\t\tif 0 leave then ( unequal, finish early )\n\tloop 1 ; ( lists must be equal )\n\nhide{ a b m }hide\n\n: ndrop ( drop n items )\n\t?dup-if 0 do drop loop then ;\n\n: caesar ( c key -- o : encode a alphabetic character with a key using a generalization of the Caesar cipher )\n\t>r\n\tdup uppercase? if [char] A - r> + 26 mod [char] A + exit then\n\tdup lowercase? if [char] a - r> + 26 mod [char] a + exit then\n\trdrop ; ( it goes without saying that this should not be used for anything serious! )\n\n: caesar-type ( c-addr u key : type out encoded text with a Caesar cipher )\n\t-rot bounds do i c@ over caesar emit loop drop ;\n\n: rot13 ( c -- c : encode a character with ROT-13 )\n\t13 caesar ;\n\n: rot13-type ( c-addr u : print string in ROT-13 encoded form )\n\t13 caesar-type ;\n\n\\ s\" abcdefghijklmnopqrstuvwxyz\" rot13-type -> nopqrstuvwxyzabcdefghijklm\n\\ s\" hello\" rot13-type -> uryyb\n\n( ==================== Misc words ============================= )\n\n( ==================== Pictured Numeric Output ================ )\n( Pictured numeric output is what Forths use to display numbers\nto the screen, this Forth has number output methods built into\nthe Forth kernel and mostly uses them instead, but the mechanism\nis still useful so it has been added.\n\n@todo Pictured number output should act on a double cell number\nnot a single cell number )\n\n0 variable hld\n\n: overflow ( -- : check if we overflow the hold area )\n \there chars> pad chars> hld @ - u> if -17 throw then ;\n\n: hold ( char -- : add a character to the numeric output string )\n\toverflow pad chars> hld @ - c! hld 1+! ;\n\n: holds ( addr u -- )\n begin dup while 1- 2dup + c@ hold repeat 2drop ;\n\n: nbase ( -- base : in this forth 0 is a special base, push 10 is base is zero )\n\tbase @ dup 0= if drop 10 then ;\n\n: <# ( -- : setup pictured numeric output )\n\t0 hld ! ;\n\n: sign ( -- : add a sign to the pictured numeric output string )\n\t[char] - hold ;\n\n: # ( x -- x : divide x by base, turn into a character, put in pictured output string )\n\tnbase um\/mod swap \n \tdup 9 u>\n \tif 7 + then\n \t48 + hold ;\n\n: #s ( x -- 0 : repeatedly call # on x until x is zero )\n\tbegin # dup 0= until ; \n\n: #> ( -- c-addr u : end pictured output conversion, push output string to stack )\n\t0 hold ( NUL terminate string, just in case )\n\thld 1-! ( but do not include that in the count )\n\tpad chars> hld @ \n\ttuck - 1+ swap ;\n\n: u. ( u -- : display number in base 10 )\n\tbase @ >r decimal <# #s #> type drop r> base ! ;\n\nhide{ nbase overflow }hide\n\n( ==================== Pictured Numeric Output ================ )\n\n( ==================== Numeric Input ========================= )\n( The Forth executable can handle numeric input and does not need\nthe routines defined here, however the user might want to write\nroutines that use >NUMBER. >NUMBER is a generic word, but it\nis a bit difficult to use on its own. )\n\n: map ( char -- n|-1 : convert character in 0-9 a-z range to number )\n\tdup lowercase? if [char] a - 10 + exit then\n\tdup decimal? if [char] 0 - exit then\n\tdrop -1 ;\n\n: number? ( char -- bool : is a character a number in the current base )\n\t>lower map (base) u< ;\n\n: >number ( n c-addr u -- n c-addr u : convert string )\n\tbegin\n\t\t( get next character )\n\t\t2dup >r >r drop c@ dup number? ( n char bool, R: c-addr u )\n\t\tif ( n char )\n\t\t\tswap (base) * swap map + ( accumulate number )\n\t\telse ( n char )\n\t\t\tdrop\n\t\t\tr> r> ( restore string )\n\t\t\texit\n\t\tthen\n\t\tr> r> ( restore string )\n\t\t1 \/string dup 0= ( advance string and test for end )\n\tuntil ;\n\nhide{ map }hide\n\n( ==================== Numeric Input ========================= )\n\n( ==================== ANSI Escape Codes ====================== )\n( Terminal colorization module, via ANSI Escape Codes\n \nsee: https:\/\/en.wikipedia.org\/wiki\/ANSI_escape_code\nThese codes will provide a relatively portable means of\nmanipulating a terminal )\n\n27 constant 'escape'\n: CSI 'escape' emit .\" [\" ;\n0 constant black\n1 constant red\n2 constant green\n3 constant yellow\n4 constant blue\n5 constant magenta\n6 constant cyan\n7 constant white\n: foreground 30 + ;\n: background 40 + ;\n0 constant dark\n1 constant bright\nfalse variable colorize \n\n: color ( brightness color-code -- : set the terminal color )\n\t( set color on an ANSI compliant terminal,\n\tfor example:\n\t\tbright red foreground color\n\tsets the foreground text to bright red )\n\tcolorize @ 0= if 2drop exit then \n\tCSI u. if .\" ;1\" then .\" m\" ;\n\n: at-xy ( x y -- : set ANSI terminal cursor position to x y )\n\tCSI u. [char] ; emit u. .\" H\" ;\n\n: page ( -- : clear ANSI terminal screen and move cursor to beginning ) \n\tCSI .\" 2J\" 1 1 at-xy ;\n\n: hide-cursor ( -- : hide the cursor from view ) \n\tCSI .\" ?25l\" ;\n\n: show-cursor ( -- : show the cursor ) \n\tCSI .\" ?25h\" ;\n\n: save-cursor ( -- : save cursor position ) \n\tCSI .\" s\" ;\n\n: restore-cursor ( -- : restore saved cursor position ) \n\tCSI .\" u\" ;\n\n: reset-color ( -- : reset terminal color to its default value)\n\tcolorize @ 0= if exit then\n\tCSI .\" 0m\" ;\n\nhide{ CSI }hide\n( ==================== ANSI Escape Codes ====================== )\n\n( ==================== Unit test framework =================== )\n\n256 string estring ( string to test )\n0 variable #estring ( actual string length )\n0 variable start ( starting depth )\n0 variable result ( result depth )\n0 variable check ( only check depth if -> is called )\n0 variable dictionary ( dictionary pointer on entering { )\n0 variable previous ( PWD register on entering { )\n\n: T ; ( hack until T{ can process words )\n\n: -> ( -- : save depth in variable ) \n\t1 check ! depth result ! ; \n\n: test estring drop #estring @ ; \n\n: fail ( -- : invalidate the forth interpreter and exit )\n\tinvalidate bye ;\n\n: neutral ( -- : neutral color )\n\t;\n\n: bad ( -- : bad color )\n\tdark red foreground color ;\n\n: good ( -- : good color )\n\tdark green foreground color ;\n\n: die bad test type reset-color cr fail ;\n\n: evaluate? ( bool -- : test if evaluation has failed )\n\tif .\" evaluation failed\" cr fail then ;\n\n: failed bad .\" failed\" reset-color cr ;\n\n: adjust ( x -- x : adjust a depth to take into account starting depth ) \n\tstart @ - ;\n\n: no-check? ( -- bool : if true we need to check the depth )\n\tcheck @ 0= ;\n\n: depth? ( -- : check if depth is correct )\n\tno-check? if exit then\n\tdepth adjust ( get depth and adjust for starting depth )\n\tresult @ adjust 2* = ( get results depth, same adjustment, should be\n\t half size of the depth ) \n\tif exit then ( pass )\n\tfailed\n\t.\" Unequal depths:\" cr\n\t.\" depth: \" depth . cr\n\t.\" result: \" result @ . cr\n\tdie ;\n\n: equal? ( -- : determine if results equals expected )\n\tno-check? if exit then\n\tresult @ adjust equal\n\tif exit then\n\tfailed\n\t.\" Result is not equal to expected values. \" cr \n\t.\" Stack: \" cr .s cr\n\tdie ;\n\n: display ( c-addr u -- : print out testing message in estring )\n\tverbose if neutral type else 2drop then ;\n\n: pass ( -- : print out passing message )\n\tverbose if good .\" ok \" cr reset-color then ;\n\n: save ( -- : save current dictionary )\n\tpwd @ previous !\n\there dictionary ! ;\n\n: restore ( -- : restore dictionary )\n\tprevious @ pwd ! \n\tdictionary @ h ! ;\n\n\n: T{ ( -- : perform a unit test )\n\tdepth start ! ( save start of stack depth )\n\t0 result ! ( reset result variable )\n\t0 check ! ( reset check variable )\n\testring 0 fill ( zero input string )\n\tsave ( save dictionary state )\n\tkey drop ( drop next character, which is a space )\n\testring [char] } accepter #estring ! ( read in string to test )\n\ttest display ( print which string we are testing )\n\ttest evaluate ( perform test )\n\tevaluate? ( evaluate successfully? )\n\tdepth? ( correct depth )\n\tequal? ( results equal to expected values? )\n\tpass ( print pass message )\n\tresult @ adjust 2* ndrop ( remove items on stack generated by test )\n\trestore ; ( restore dictionary to previous state )\n\nT{ }T\nT{ -> }T\nT{ 1 -> 1 }T\nT{ 1 2 -> 1 2 }T\nT{ : c 1 2 ; c -> 1 2 }T\nT{ :noname 2 ; :noname 3 + ; compose execute -> 5 }T\n\nhide{ \n\tpass test display\n\tadjust start save restore dictionary previous \n\tevaluate? equal? depth? estring #estring result\n\tcheck no-check? die neutral bad good failed\n}hide\n\n( ==================== Unit test framework =================== )\n\n\n( ==================== Random Numbers ========================= )\n\n( \nSee:\nuses xorshift\nhttps:\/\/en.wikipedia.org\/wiki\/Xorshift\nhttp:\/\/excamera.com\/sphinx\/article-xorshift.html\nhttp:\/\/www.arklyffe.com\/main\/2010\/08\/29\/xorshift-pseudorandom-number-generator\/\nthese constants have be collected from the web \n)\n\nsize 2 = [if] 13 constant a 9 constant b 7 constant c [then]\nsize 4 = [if] 13 constant a 17 constant b 5 constant c [then]\nsize 8 = [if] 12 constant a 25 constant b 27 constant c [then]\n\n7 variable seed ( must not be zero )\n\n: seed! ( x -- : set the value of the PRNG seed )\n\tdup 0= if drop 7 ( zero not allowed ) then seed ! ;\n\n: random ( -- x : assumes word size is 32 bit )\n\tseed @\n\tdup a lshift xor\n\tdup b rshift xor\n\tdup c lshift xor\n\tdup seed! ;\n\nhide{ a b c seed }hide\n\n( ==================== Random Numbers ========================= )\n\n( ==================== Prime Numbers ========================== )\n( From original \"third\" code from the IOCCC at \nhttp:\/\/www.ioccc.org\/1992\/buzzard.2.design, the module works out\nand prints prime numbers. )\n\n: prime? ( u -- u | 0 : return number if it is prime, zero otherwise )\n\tdup 1 = if 1- exit then\n\tdup 2 = if exit then\n\tdup 2\/ 2 ( loop from 2 to n\/2 )\n\tdo\n\t\tdup ( value to check if prime )\n\t\ti mod ( mod by divisor )\n\t\tnot if\n\t\t\tdrop 0 leave\n\t\tthen\n\tloop ;\n\n0 variable counter\n\n: primes ( x1 x2 -- : print the primes from x2 to x1 )\n\t0 counter !\n\t\" The primes from \" dup . \" to \" over . \" are: \"\n\tcr\n\tcolumn.reset\n\tdo\n\t\ti prime?\n\t\tif\n\t\t\ti . counter @ column counter 1+!\n\t\tthen\n\tloop\n\tcr\n\t\" There are \" counter @ . \" primes.\"\n\tcr ;\n\nhide{ counter }hide\n( ==================== Prime Numbers ========================== )\n\n( ==================== Debugging info ========================= )\n\n( string handling should really be done with PARSE, and CMOVE )\n\n: sh ( cnl -- ior : execute a line as a system command )\n\tnl word count system ;\n\nhide{ .s }hide\n: .s ( -- : print out the stack for debugging )\n\t[char] < emit depth u. [char] > emit space\n\tdepth if\n\t\tdepth 0 do i column tab depth i 1+ - pick . loop\n\tthen\n\tcr ;\n\n1 variable hide-words ( do we want to hide hidden words or not )\n\n: name ( PWD -- c-addr : given a pointer to the PWD field of a word get a pointer to the name of the word )\n\tdup 1+ @ 256\/ word-mask and lsb - chars> ;\n\n( This function prints out all of the defined words, excluding hidden words.\nAn understanding of the layout of a Forth word helps here. The dictionary\ncontains a linked list of words, each forth word has a pointer to the previous\nword until the first word. The layout of a Forth word looks like this:\n\nNAME: Forth Word - A variable length ASCII NUL terminated string\nPWD: Previous Word Pointer, points to the previous word\nCODE: Flags, code word and offset from previous word pointer to start of Forth word string\nDATA: The body of the forth word definition, not interested in this.\n\nThere is a register which stores the latest defined word which can be\naccessed with the code \"pwd @\". In order to print out a word we need to\naccess a words CODE field, the offset to the NAME is stored here in bits\n8 to 14 and the offset is calculated from the PWD field.\n\n\"print\" expects a character address, so we need to multiply any calculated\naddress by the word size in bytes. )\n\n: words.immediate ( bool -- : emit or mark a word being printed as being immediate )\n\tnot if dark red foreground color then ;\n\n: words.defined ( bool -- : emit or mark a word being printed as being a built in word )\n\tnot if bright green background color then ;\n\n: words.hidden ( bool -- : emit or mark a word being printed as being a hidden word )\n\tif dark magenta foreground color then ;\n\n: words ( -- : print out all defined an visible words )\n\tlatest\n\tspace\n\tbegin\n\t\tdup\n\t\thidden? hide-words @ and\n\t\tnot if\n\t\t\thidden? words.hidden\n\t\t\tcompiling? words.immediate\n\t\t\tdup defined-word? words.defined\n\t\t\tname\n\t\t\tprint space\n\t\t\treset-color\n\t\telse\n\t\t\tdrop\n\t\tthen\n\t\t@ ( Get pointer to previous word )\n\t\tdup dictionary-start u< ( stop if pwd no longer points to a word )\n\tuntil\n\tdrop cr ;\n\n( Simpler version of words\n: words\n\tpwd @ \n\tbegin\n\t\tdup name print space @ dup dictionary-start u<\n\tuntil drop cr ; )\n\nhide{ words.immediate words.defined words.hidden hidden? hidden-bit }hide\n\n: TrueFalse ( -- : print true or false )\n\tif \" true\" else \" false\" then ;\n\n: registers ( -- : print out important registers and information about the virtual machine )\n\t\" return stack pointer: \" r@ . cr\n\t\" dictionary pointer \" here . cr\n\t\" previous word: \" pwd ? cr\n\t\" state: \" state ? cr\n\t\" base: \" base ? cr\n\t\" depth: \" depth . cr\n\t\" cell size (in bytes): \" size . cr\n\t\" last cell address: \" max-core . cr\n\t\" unused cells: \" unused . cr\n\t\" invalid: \" `invalid @ TrueFalse cr\n\t\" size of variable stack: \" `stack-size ? cr\n\t\" size of return stack: \" `stack-size ? cr\n\t\" start of variable stack: \" max-core `stack-size @ 2* - . cr\n\t\" start of return stack: \" max-core `stack-size @ - . cr\n\t\" current input source: \" source-id -1 = if \" string\" else \" file\" then cr\n\t\" tracing on: \" `debug @ TrueFalse cr\n\t\" starting word: \" `instruction ? cr\n\t\" real start address: \" `start-address ? cr\n\t\" error handling: \" `error-handler ? cr \n\t\" throw handler: \" `handler ? cr\n\t\" signal recieved: \" `signal ? cr ;\n\t\n( `sin `sidx `slen `fout\n `stdout `stderr `argc `argv )\n\n\n: y\/n? ( -- bool : ask a yes or no question )\n\tkey drop\n\t\" y\/n? \"\n\tbegin\n\t\tkey\n\t\tdup\n\t\t[char] y = if true exit then\n\t\t[char] n = if false exit then\n\t\t\" y\/n? \"\n\tagain ;\n\n: step\n\t( step through a word: this word could be augmented\n\twith commands such as \"dump\", \"halt\", and optional\n\t\".s\" and \"registers\" )\n\tregisters\n\t\" .s: \" .s cr\n\t\" -- press any key to continue -- \"\n\tkey drop ;\n\n: more ( -- : wait for more input )\n\t\" -- press any key to continue -- \" key drop cr page ;\n\n: debug-help ( -- : print out the help for the debug command )\n \" debug mode commands\n\th - print help\n\tq - exit interpreter word\n\tr - print registers\n\ts - print stack\n\tR - print return stack\n\tc - continue on with execution\n\" ;\n\ndoer debug-prompt\n: prompt-default\n\t.\" debug> \" ;\n\nmake debug-prompt prompt-default\n\n: debug ( -- : enter interactive debug prompt )\n\tcr\n\t\" Entered Debug Prompt. Type 'h' for help. \" cr \n\tbegin\n\t\tkey\n\t\tcase\n\t\t\tnl of debug-prompt endof\n\t\t\t[char] h of debug-help endof\n\t\t\t[char] q of bye endof\n\t\t\t[char] r of registers endof\n\t\t\t[char] s of .s endof\n\t\t\t[char] R of r.s endof\n\t\t\t[char] c of exit endof\n\t\t\t( @todo add throw here )\n\t\tendcase \n\tagain ;\nhide debug-prompt\n\n: code>pwd ( CODE -- PWD\/0 : calculate PWD from code address )\n\tdup dictionary-start here within not if drop 0 exit then\n\t1 cells - ;\n\n: word-printer ( CODE -- : print out a words name given its code field )\n\tdup 1 cells - @ -1 = if . \" noname\" exit then ( nonames are marked by a -1 before its code field )\n\tdup code>pwd ?dup-if .d name print else drop \" data\" then\n\t drop ;\n\nhide{ code>pwd }hide\n\n( these words push the execution tokens for various special cases for decompilation )\n: get-branch [ find branch ] literal ;\n: get-?branch [ find ?branch ] literal ;\n: get-original-exit [ find _exit ] literal ;\n: get-quote [ find ' ] literal ;\n\n( @todo replace 2- nos1+ nos1+ with appropriate word, like the string word \nthat increments a string by an amount, but that operates on CELLS )\n: branch-increment ( addr branch -- increment : calculate decompile increment for \"branch\" )\n\t1+ dup negative? \n\tif \n\t\tover cr . [char] : emit space . cr 2 \n\telse \n\t\t2dup 2- nos1+ nos1+ dump \n\tthen ;\n\n( these words take a code field to a primitive they implement, decompile it\nand any data belonging to that operation, and push a number to increment the\ndecompilers code stream pointer by )\n\n: decompile-literal ( code -- increment )\n\t1+ ? \" literal\" 2 ;\n\n: decompile-branch ( code -- increment )\n\tdark red foreground color\n\t1+ ? \" branch \" dup 1+ @ branch-increment ;\n\n: decompile-quote ( code -- increment )\n\tdark green foreground color\n\tdup\n\t[char] ' emit 1+ @ word-printer 2 reset-color ;\n\n: decompile-?branch ( code -- increment )\n\t1+ ? \" ?branch\" 2 ;\n\n: decompile-exit ( code -- 0 )\n\t\" _exit\" cr \" End of word: \" . 0 ;\n\n( The decompile word expects a pointer to the code field of a word, it\ndecompiles a words code field, it needs a lot of work however.\nThere are several complications to implementing this decompile\nfunction.\n\n\t' The next cell should be pushed\n\t:noname This has a marker before its code field of -1 which\n\t\t cannot occur normally, this is handled in word-printer\n\tbranch branches are used to skip over data, but also for\n\t\t some branch constructs, any data in between can only\n\t\t be printed out generally speaking\n\texit There are two definitions of exit, the one used in\n\t\t ';' and the one everything else uses, this is used\n\t\t to determine the actual end of the word\n\tliterals Literals can be distinguished by their low value,\n\t\t which cannot possibly be a word with a name, the\n\t\t next field is the actual literal\n\nOf special difficult is processing 'if' 'else' 'then' statements,\nthis will require keeping track of '?branch'.\n\nAlso of note, a number greater than \"here\" must be data )\n\n: decompile ( code-pointer -- code-pointer increment|0 : )\n\t.d [char] : emit space dup @\n\tcase\n\t\tdolit of dup decompile-literal cr endof\n\t\tget-branch of dup decompile-branch endof\n\t\tget-quote of dup decompile-quote cr endof\n\t\tget-?branch of dup decompile-?branch cr endof\n\t\tget-original-exit of dup decompile-exit endof\n\t\tdup word-printer 1 swap cr\n\tendcase reset-color ;\n\n: decompiler ( code-field-ptr -- : decompile a word in its entirety )\n\tbegin decompile over + tuck = until drop ;\n\nhide{\n\tword-printer get-branch get-?branch get-original-exit \n\tget-quote branch-increment decompile-literal \n\tdecompile-branch decompile-?branch decompile-quote\n\tdecompile-exit\n}hide\n\n( these words expect a pointer to the PWD field of a word )\n: see.name \" name: \" name print cr ;\n: see.start \" word start: \" name chars . cr ;\n: see.previous \" previous word: \" @ . cr ;\n: see.immediate \" immediate: \" compiling? swap drop not TrueFalse cr ;\n: see.instruction \" instruction: \" xt-instruction . cr ;\n: see.defined \" defined: \" defined-word? TrueFalse cr ;\n\n: see.header ( PWD -- is-immediate-word? )\n\tdup see.name\n\tdup see.start\n\tdup see.previous\n\tdup see.immediate\n\tdup see.instruction ( @todo look up instruction name )\n\tsee.defined ;\n\n( @todo This does not work for all words, so needs fixing. \n Specifically: \n\t2variable\n\t2constant\n\ttable\n\tconstant\n\tvariable\n\tarray \nWhich are all complex CREATE words\n\nA good way to test decompilation is with the following Unix pipe: \n\n\t.\/forth -f forth.fth -e words \n\t\t| sed 's\/ \/ see \/g' \n\t\t| .\/forth -t forth.fth &> decompiled.log\n)\n\n( @todo refactor into word that takes a PWD pointer and one that attempts to parse\/find name )\n: see ( c\" xxx\" -- : decompile the next word in the input stream )\n\tfind\n\tdup 0= if -32 throw then\n\t-1 cells + ( move to PWD field )\n\tdup see.header\n\tdup defined-word?\n\tif ( decompile if a compiled word )\n\t\t2 cells + ( move to code field )\n\t\t\" code field:\" cr\n\t\tdecompiler\n\telse ( the instruction describes the word if it is not a compiled word )\n\t\tdup 1 cells + @ instruction-mask and doconst = if ( special case for constants )\n\t\t\t\" constant: \" 2 cells + @ .\n\t\telse\n\t\t\tdrop\n\t\tthen\n\tthen cr ;\n\nhide{ \n\tsee.header see.name see.start see.previous see.immediate \n\tsee.instruction defined-word? see.defined\n}hide\n\n( These help messages could be moved to blocks, the blocks could then\nbe loaded from disk and printed instead of defining the help here,\nthis would allow much larger help )\n\n: help ( -- : print out a short help message )\n\tpage\n\tkey drop\n\" Welcome to Forth, an imperative stack based language. It is both a low\nlevel and a high level language, with a very small memory footprint. Most\nof Forth is defined as a combination of various primitives.\n\nA short description of the available function (or Forth words) follows,\nwords marked (1) are immediate and cannot be used in command mode, words\nmarked with (2) define new words. Words marked with (3) have both command\nand compile functionality.\n\n\"\nmore \" Some of the built in words that accessible are:\n\n(1,2)\t: define a new word, switching to compile mode\n\timmediate make latest defined word immediate\n\tread read in a word, execute in command mode else compile\n\t@ ! fetch, store\n\tc@ c! character based fetch and store\n\t- + * \/ standard arithmetic operations,\n\tand or xor invert standard bitwise operations\n\tlshift rshift left and right bit shift\n\tu< u> < > = comparison predicates\n\texit exit from a word\n\temit print character from top of stack\n\tkey get a character from input\n\tr> >r pop a value from or to the return stack\n\tfind find a word in the dictionary and push the location\n\t' store the address of the following word on the stack\n\t, write the top of the stack to the dictionary\n\tswap swap first two values on the stack\n\tdup duplicate the top of the stack\n\tdrop pop and drop a value\n\tover copy the second stack value over the first\n\t. pop the top of the stack and print it\n\" \nmore \" \n\tprint print a NUL terminated string at a character address\n\tdepth get the current stack depth\n\tclock get the time since execution start in milliseconds\n\tevaluate evaluate a string\n\tsystem execute a system command\n\tclose-file close a file handle\n\topen-file open a file handle\n\tdelete-file delete a file off disk given a string\n\tread-file read in characters from a file\n\twrite-file write characters to a file\n\tfile-position get the file offset\n\treposition-file reposition the file pointer\n\tflush-file flush a file to disk\n\trename-file rename a file on disk\n \"\n\nmore \" All of the other words in the interpreter are built from these\nprimitive words. A few examples:\n\n(1)\tif...else...then FORTH branching construct\n(1)\tbegin...until loop until top of stack is non zero\n(1)\tbegin...again infinite loop\n(1)\tdo...loop FORTH looping construct\n(2,3)\tcreate create a new word that pushes its location\n(1)\tdoes> declare a created words run time behaviour\n(1,2)\tvariable declare variable with initial value from top of stack\n(1,2)\tconstant declare a constant, taken from top of stack\n(1,2)\tarray declare an array with size taken from top of stack\n(1)\t; terminate a word definition and return to command mode\n\twords print out a list of all the defined words\n\thelp this help message\n\tdump print out memory contents starting at an address\n\tregisters print out the contents of the registers\n\tsee decompile a word, viewing what words compose it\n\t.s print out the contents of the stack\n\n\"\n\nmore \" Some more advanced words:\n\n\there push the dictionary pointer\n\th push the address of the dictionary pointer\n\tr push the return stack pointer\n\tallot allocate space in the dictionary\n(1)\t[ switch to command mode\n\t] switch to compile mode\n\t:: compile ':' into the dictionary\n\n\" more \"\nFor more information either consult the manual pages forth(1) and libforth(1)\nor consult the following sources:\n\n\thttps:\/\/github.com\/howerj\/libforth\n\thttp:\/\/work.anapnea.net\/html\/html\/projects.html\n\nAnd for a larger tutorial:\n\n\thttps:\/\/github.com\/howerj\/libforth\/blob\/master\/readme.md\n\nFor resources on Forth:\n\n\thttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\thttps:\/\/rwmj.wordpress.com\/2010\/08\/07\/jonesforth-git-repository\/\n\n -- end --\n\" cr\n;\n\n( ==================== Debugging info ========================= )\n\n( ==================== Files ================================== )\n\n( @todo implement the other file access methods in terms of the\n built in ones [see http:\/\/forth.sourceforge.net\/std\/dpans\/dpans11.htm]\n @todo read-line and write-line need their flag and ior setting correctly\n\n\tFILE-SIZE [ use file-positions ]\n\n Also of note:\t\n * Source ID needs extending. )\n\n: read-char ( c-addr fileid -- ior : read a char )\n\t1 swap read-file 0<> swap 1 <> or ;\n\n0 variable x\n\n: getchar ( fileid -- char ior )\n\tx chars> swap read-char x chars> c@ swap ;\n\n: write-char ( c-addr fileid -- ior : write a char )\n\t1 swap write-file 0<> swap 1 <> or ;\n\n: putchar ( char fileid -- ior )\n\tswap x chars> c! x chars> swap write-char ;\n\nhide{ x }hide\n\n: rewind-file ( file-id -- : rewind a file to the beginning )\n\t0 reposition-file throw ;\n\n: read-line ( c-addr u1 fileid -- u2 flag ior : read in a line of text )\n\t-rot bounds\n\tdo\n\t\tdup i swap read-char drop\n\t\ti c@ nl = if drop i 0 0 leave then\n\tloop drop ;\n\n: write-line ( c-addr u fileid -- u2 flag ior : write a line of text )\n\t-rot bounds\n\tdo\n\t\tdup i swap write-char drop\n\t\ti c@ nl = if drop i 0 0 leave then\n\tloop ;\n\n: resize-file ( ud fileid -- ior : attempt to resize a file )\n\t( There is no portable way to truncate a file :C )\n\t2drop -1 ( -1 to indicate failure ) ;\n\n: create-file ( c-addr u fam -- fileid ior )\n\t>r 2dup w\/o open-file throw close-file throw\n\tr> open-file ;\n\n: include-file ( file-id -- : evaluate a file ) \n\tdup >r 0 1 evaluator r> close-file throw throw ;\n\n: included ( c-addr u -- : attempt to open up a name file and evaluate it )\n\tr\/o open-file throw \n\tinclude-file ;\n\n: include ( c\" ccc\" -- : attempt to evaluate a named file )\n\t( @bug requires trailing space, should use parse-name )\n\tbl word count included ;\n\n: bin ( fam1 -- fam2 : modify a file access method to be binary not line oriented ) \n\t( Do nothing, all file access methods are binary )\n\t;\n\n( ==================== Files ================================== )\n\n( ==================== Matcher ================================ )\n( The following section implements a very simple regular expression\nengine, which expects an ASCIIZ Forth string. It is translated from C\ncode and performs an identical function.\n\nThe regular expression language is as follows:\n\n\tc\tmatch a literal character\n\t.\tmatch any character\n\t*\tmatch any characters\n\nThe \"*\" operator performs the same function as \".*\" does in most\nother regular expression engines. Most other regular expression engines\nalso do not anchor their selections to the beginning and the end of\nthe string to match, instead using the operators '^' and '$' to do\nso, to emulate this behavior '*' can be added as either a suffix,\nor a prefix, or both, to the matching expression.\n\nAs an example \"*, World!\" matches both \"Hello, World!\" and\n\"Good bye, cruel World!\". \"Hello, ....\" matches \"Hello, Bill\"\nand \"Hello, Fred\" but not \"Hello, Tim\" as there are two few\ncharacters in the last string.\n\n@todo make a matcher that expects a Forth string, which do not\nhave to be NUL terminated\n)\n\n\\ Translated from http:\/\/c-faq.com\/lib\/regex.html\n\\ int match(char *pat, char *str)\n\\ {\n\\ \tswitch(*pat) {\n\\ \tcase '\\0': return !*str;\n\\ \tcase '*': return match(pat+1, str) || *str && match(pat, str+1);\n\\ \tcase '.': return *str && match(pat+1, str+1);\n\\ \tdefault: return *pat == *str && match(pat+1, str+1);\n\\ \t}\n\\ }\n\n: *pat ( regex -- regex char : grab next character of pattern ) \n\tdup c@ ;\n\n: *str ( string regex -- string regex char : grab next character string to match )\n\tover c@ ;\n\n: pass ( c-addr1 c-addr2 -- bool : pass condition, characters matched ) \n\t2drop 1 ;\n\n: reject ( c-addr1 c-addr2 -- bool : fail condition, character not matched ) \n\t2drop 0 ;\n\n: *pat==*str ( c-addr1 c-addr2 -- c-addr1 c-addr2 bool )\n\t2dup c@ swap c@ = ;\n\n: ++ ( u1 u2 u3 u4 -- u1+u3 u2+u4 : not quite d+ [does no carry] )\n\tswap >r + swap r> + swap ;\n\ndefer matcher\n\n: advance ( string regex char -- bool : advance both regex and string )\n\tif 1 1 ++ matcher else reject then ;\n\n: advance-string ( string regex char -- bool : advance only the string )\n\tif 1 0 ++ matcher else reject then ;\n\n: advance-regex ( string regex -- bool : advance matching )\n\t2dup 0 1 ++ matcher if pass else *str advance-string then ;\n\n: match ( string regex -- bool : match a ASCIIZ pattern against an ASCIIZ string )\n\t( @todo Add limits and accept two Forth strings, making sure they are both\n\t ASCIIZ strings as well \n\t @warning This uses a non-standards compliant version of case! )\n\t*pat\n\tcase\n\t\t 0 of drop c@ not endof\n\t\t[char] * of advance-regex endof\n\t\t[char] . of *str advance endof\n\t\t drop *pat==*str advance exit\n\tendcase ;\n\nmatcher is match\n\nhide{ \n\t*str *pat *pat==*str pass reject advance \n\tadvance-string advance-regex matcher ++ \n}hide\n\n( ==================== Matcher ================================ )\n\n\n( ==================== Cons Cells ============================= )\n\n( From http:\/\/sametwice.com\/cons.fs, this could be improved if the optional\nmemory allocation words were added to the interpreter. This provides\na simple \"cons cell\" data structure. There is currently no way to\nfree allocated cells )\n\n: car! ( value cons-addr -- : store a value in the car cell of a cons cell ) \n\t! ;\n\n: cdr! ( value cons-addr -- : store a value in the cdr cell of a cons cell )\n\tcell+ ! ;\n\n: car@ ( cons-addr -- car-val : retrieve car value from cons cell )\n\t@ ;\n\n: cdr@ ( cons-addr -- cdr-val : retrieve cdr value from cons cell )\n\tcell+ @ ;\n\n: cons ( car-val cdr-val -- cons-addr : allocate a new cons cell )\n\tswap here >r , , r> ;\n\n: cons0 0 0 cons ;\n\n( ==================== Cons Cells ============================= )\n\n( ==================== Miscellaneous ========================== )\n\n: license ( -- : print out license information )\n\" \nThe MIT License (MIT)\n\nCopyright (c) 2016, 2017 Richard James Howe\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the 'Software'),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand\/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\nTHE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\nOTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\nARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE. \n\n\" \n;\n\n\n\n\n( ==================== Core utilities ======================== )\n( Read the header of a core file and process it, printing the\nresults out )\n\n8 constant header-size ( size of Forth core file header )\n8 constant size-field-size ( the size in bytes of the size field in the core file )\n0 variable core-file ( core fileid we are reading in )\n0 variable core-cell-size ( cell size of Forth core )\n0 variable core-version ( version of core file )\n0 variable core-endianess ( endianess of core we are reading in )\n\n( save space to read in header )\ncreate header header-size chars allot\n: cheader ( -- c-addr : header char address )\n\theader chars> ;\ncreate size-field size-field-size chars allot\n: csize-field ( -- c-addr : address of place size field is stored in )\n\tsize-field chars> ;\n\n0\nenum header-magic0 ( magic number 0 : FF ) \nenum header-magic1 ( magic number 1 : '4' )\nenum header-magic2 ( magic number 2 : 'T' )\nenum header-magic3 ( magic number 3 : 'H' )\nenum header-cell-size ( size of a forth cell, either 2, 4 or 8 bytes )\nenum header-version ( version of the forth core )\nenum header-endianess ( endianess of the core )\nenum header-log2size ( binary logarithm of the core size )\n\n: cleanup ( -- : cleanup before abort )\n\tcore-file @ ?dup 0<> if close-file drop then ;\n\n: invalid-header ( bool -- : abort if header is invalid )\n\t<> if cleanup abort\" invalid header\" then ;\n\n: save-core-cell-size ( char -- : save the core file cell size, checking if it is valid )\n\tcore-cell-size !\n\t\" cell size:\" tab\n\tcore-cell-size @ 2 = if 2 . cr exit then\n\tcore-cell-size @ 4 = if 4 . cr exit then\n\tcore-cell-size @ 8 = if 8 . cr exit then\n\tcleanup core-cell-size @ . abort\" : invalid cell size\" ;\n\n: check-version-compatibility ( char -- : checks the version compatibility of the core file ) \n\tcore-version !\n\tcore-version @ version = if \" version: \" version . cr exit then\n\tcleanup core-version @ . abort\" : unknown version number\" ;\n\n: save-endianess ( char -- : save the endianess, checking if it is valid )\n\tcore-endianess !\n\t\" endianess:\" tab\n\tcore-endianess @ 0 = if \" big\" cr exit then\n\tcore-endianess @ 1 = if \" little\" cr exit then\n\tcleanup core-endianess @ . abort\" invalid endianess\" then ;\n\n: read-or-abort ( c-addr size fileid -- : )\n\tover >r read-file \n\t 0<> if cleanup abort\" file read failed\" then\n\tr> <> if cleanup abort\" header too small\" then ;\n\n: header? ( -- : print out header information )\n\tcheader header-size core-file @ read-or-abort\n\t( \" raw header:\" header 2 dump )\n\tcheader header-magic0 + c@ 255 invalid-header\n\tcheader header-magic1 + c@ [char] 4 invalid-header\n\tcheader header-magic2 + c@ [char] T invalid-header\n\tcheader header-magic3 + c@ [char] H invalid-header\n\tcheader header-cell-size + c@ save-core-cell-size\n\tcheader header-version + c@ check-version-compatibility\n\tcheader header-endianess + c@ save-endianess\n\t\" valid header\" cr ;\n\n: size? ( -- : print out core file size )\n\t\" size: \" cheader header-log2size + c@ 1 swap lshift . cr ;\n\n: core ( c-addr u -- : analyze a Forth core file from disk given its file name )\n\t2dup \" core file:\" tab type cr\n\tr\/o open-file throw core-file ! \n\theader?\n\tsize?\n\tcore-file @ close-file drop ;\n\n( s\" forth.core\" core )\n\nhide{ \nheader-size header? \nheader-magic0 header-magic1 header-magic2 header-magic3\nheader-version header-cell-size header-endianess header-log2size\nheader \ncore-file save-core-cell-size check-version-compatibility\ncore-cell-size cheader\ncore-endianess core-version save-endianess invalid-header\ncleanup size-field csize-field size-field-size\nread-or-abort size?\n}hide\n\n( ==================== Core utilities ======================== )\n\n( ==================== RLE =================================== )\n\n( These set of words implement Run Length Compression, which can be used for\nsaving space when compressing the core files generated by Forth programs, which\ncontain mostly runs of NUL characters. \n\nThe format of the encoded data is quite simple, there is a command byte\nfollowed by data. The command byte encodes only two commands; encode a run of\nliteral data and repeat the next character. \n\nIf the command byte is greater than X the command is a run of characters, \nX is then subtracted from the command byte and this is the number of \ncharacters that is to be copied verbatim when decompressing.\n\nIf the command byte is less than or equal to X then this number, plus one, is \nused to repeat the next data byte in the input stream.\n\nX is 128 for this application, but could be adjusted for better compression\ndepending on what the data looks like. \n\nExample:\n\t\n\t2 'a' 130 'b' 'c' 3 'd'\n\nBecomes:\n\n\taabcddd \n\nExample usage:\n\n\t: extract\n\t\tc\" forth.core\" w\/o open-file throw\n\t\tc\" forth.core.rle\" r\/o open-file throw\n\t\tdecompress ;\n\textract\n\n@note file redirection could be used for the input as well\n@todo compression, and reading\/writing to strings )\n\n: cpad pad chars> ;\n\n0 variable out\n128 constant run-length\n\n: next.char ( file-id -- char : read in a single character )\n\t>r cpad r> read-char throw cpad c@ ;\n\n: repeated ( count file-id -- : repeat a character count times )\n\tnext.char swap 0 do dup emit loop drop ;\n\n: literals ( count file-id -- : extract a literal run )\n\t>r cpad swap r> read-file throw cpad swap type ;\n\n: command ( file-id -- : process an RLE command )\n\tdup \n\t>r next.char\n\tdup run-length u> \n\tif \n\t\trun-length - r> literals \n\telse \n\t\t1+ r> repeated \n\tthen ;\n\n: redirect ( file-id-out -- : save current output pointer, redirect to output )\n\t`fout @ out ! `fout ! ;\n\n: restore ( -- : restore previous output pointer )\n\tout @ `fout ! ;\n\n: decompress ( file-id-out file-id-in -- : decompress an RLE encoded file )\n\tswap\n\tredirect\n\tbegin dup ' command catch until ( process commands until input exhausted )\n\t2drop ( drop twice because catch will restore stack before 'command' )\n\trestore ; ( restore input stream )\n\nhide{ literals repeated next.char out run-length command }hide\n\n( ==================== RLE =================================== )\n\n( ==================== Generate C Core file ================== )\n( The word core2c reads in a core file and turns it into a C file which \ncan then be compiled into the forth interpreter in a bootstrapping like\nprocess.\n\nUsage:\n c\" forth.core\" c\" core.gen.c\" core2c )\n\n0 variable count\n\n: wbyte ( u char -- : write a byte )\n\tpnum drop\n\t[char] , emit\n\t16 mod 0= if cr then ;\n\n: advance ( char -- : advance counter and print byte )\n\tcount 1+! count @ swap wbyte ;\n\n: hexify ( fileid -- fileid : turn core file into C numbers in array )\n\t0 count !\n\tbegin dup getchar 0= while advance repeat drop ;\n\n: quote ( -- : emit a quote character )\n\t[char] \" emit ;\n\n: core2c ( c-addr u c-addr u -- ior : generate a C file from a core file )\n\tw\/o open-file throw >r\n\tr\/o open-file ?dup-if r> close-file throw throw then\n\tr> redirect\n\t\" #include \" quote \" libforth.h\" quote cr\n\t\" unsigned char forth_core_data[] = {\" cr\n\thexify \n\t\" };\" cr\n\t\" forth_cell_t forth_core_size = \" count @ . \" ;\" cr cr\n\tclose-file\n\t`fout @ close-file \n\trestore or ;\n\nhide{ wbyte hexify count quote advance }hide\n \n( ==================== Generate C Core file ================== )\n\n: wc ( c-addr u -- u : count the bytes in a file )\n\tr\/o open-file throw\n\t0 swap\n\tbegin dup getchar nip 0= while nos1+ repeat close-file throw ;\n\n( ==================== Save Core file ======================== )\n\n( The following functionality allows the user to save the core file\nfrom within the running interpreter. The Forth core files have a very simple\nformat which means the words for doing this do not have to be too long, a header\nhas to emitted with a few calculated values and then the contents of the\nForths memory after this )\n\n( This write the header out to the current output device, this\nwill be redirected to a file )\n: header ( -- : write the header out )\n\t0xff emit ( magic 0 )\n\t[char] 4 emit ( magic 1 )\n\t[char] T emit ( magic 2 )\n\t[char] H emit ( magic 3 )\n\tsize emit ( cell size in bytes )\n\tversion emit ( core version )\n\tendian not emit ( endianess )\n\tmax-core log2 emit ; ( size field )\n\n: data ( -- : write the data out )\n\t0 max-core chars> `fout @ write-file throw drop ;\n\n: encore ( -- : write the core file out )\n\theader\n\tdata ;\n\n: save-core ( c-addr u -- : save core file or throw error ) \n\tw\/o open-file throw dup\n\tredirect \n\t\t' encore catch swap close-file throw \n\trestore ;\n\n( The following code illustrates an example of setting up a\nForth core file to execute a word when the core file is loaded.\nIn the example the word \"hello-world\" will be executed, which will\nalso quit the interpreter:\n\n\t\\ Only works for immediate words for now, we define\n\t\\ the word we wish to be executed when the forth core\n\t\\ is loaded\n\t: hello-world immediate\n\t\t\" Hello, World!\" cr bye ;\n\n\t\\ The following sets the starting word to our newly\n\t\\ defined word:\n\tfind hello-world cfa start!\n\n\t\\ Now we can save the core file out:\n\ts\" forth.core\" save-core \n\nThis can be used, in conjunction with aspects of the build system,\nto produce a standalone executable that will run only a single Forth\nword. )\n\nhide{ redirect restore data encore header }hide\n\n( ==================== Save Core file ======================== )\n\n( ==================== Hex dump ============================== )\n\n( @todo hexdump can read in too many characters and it does not\nprint out the correct address\n@todo utilities for easy redirecting of file input\/output )\n: input >r cpad 128 r> read-file ; ( file-id -- u 0 | error )\n: clean cpad 128 0 fill ; ( -- )\n: cdump cpad chars swap aligned chars dump ; ( u -- )\n: hexdump ( file-id -- : [hex]dump a file to the screen )\n\tdup \n\tclean\n\tinput if 2drop exit then\n\t?dup-if cdump else drop exit then\n\ttail ; \n\nhide{ cpad clean cdump input }hide\n\n( ==================== Hex dump ============================== )\n\n( ==================== Date ================================== )\n\n( Rather annoyingly months are start from 1 but weekdays from 0 )\n\n: >month ( month -- )\n\tcase\n\t\t 1 of \" Jan \" endof\n\t\t 2 of \" Feb \" endof\n\t\t 3 of \" Mar \" endof\n\t\t 4 of \" Apr \" endof\n\t\t 5 of \" May \" endof\n\t\t 6 of \" Jun \" endof\n\t\t 7 of \" Jul \" endof\n\t\t 8 of \" Aug \" endof\n\t\t 9 of \" Sep \" endof\n\t\t10 of \" Oct \" endof\n\t\t11 of \" Nov \" endof\n\t\t12 of \" Dec \" endof\n\t\t-11 throw\n\tendcase ;\n\n: .day ( day -- : add ordinal to day )\n\t10 mod\n\tcase\n\t\t1 of \" st \" exit endof\n\t\t2 of \" nd \" exit endof\n\t\t3 of \" rd \" exit endof\n\t\t\" th \" \n\tendcase ;\n\n: >day ( day -- : add ordinal to day of month )\n\tdup u.\n\tdup 1 10 within if .day exit then\n\tdup 10 20 within if \" th\" drop exit then\n\t.day ;\n\n: >weekday ( weekday -- : print the weekday )\n\tcase\n\t\t0 of \" Sun \" endof\n\t\t1 of \" Mon \" endof\n\t\t2 of \" Tue \" endof\n\t\t3 of \" Wed \" endof\n\t\t4 of \" Thu \" endof\n\t\t5 of \" Fri \" endof\n\t\t6 of \" Sat \" endof\n\tendcase ;\n\n: padded ( u -- : print out a run of zero characters )\n\t0 do [char] 0 emit loop ;\n\n: 0u. ( u -- : print a zero padded number @todo replace with u.r )\n\tdup 10 u< if 1 padded then u. space ;\n\n: .date ( date -- : print the date )\n\tif \" DST \" else \" GMT \" then \n\tdrop ( no need for days of year)\n\t>weekday\n\t. ( year ) \n\t>month \n\t>day \n\t0u. ( hour )\n\t0u. ( minute )\n\t0u. ( second ) cr ;\n\n: time&date ( -- second minute hour day month year )\n\tdate\n\t3drop ;\n\nhide{ 0u. >weekday .day >day >month padded }hide\n\n( ==================== Date ================================== )\n\n\n( ==================== CRC =================================== )\n\n( @todo implement all common CRC algorithms, but only if\nthe word size allows it [ie. 32 bit CRCs on a 32 or 64 bit\nmachine, 64 bit CRCs on a 64 bit machine] )\n\n( Make a word to limit arithmetic to a 16-bit value )\nsize 2 = [if] \n\t: limit immediate ; ( do nothing, no need to limit )\n[else] \n\t: limit 0xffff and ; ( limit to 16-bit value )\n[then]\n\n: ccitt ( crc c-addr -- crc : calculate polynomial 0x1021 AKA \"x16 + x12 + x5 + 1\" )\n\tc@ ( get char )\n\tlimit over 256\/ xor ( crc x )\n\tdup 4 rshift xor ( crc x )\n\tdup 5 lshift limit xor ( crc x )\n\tdup 12 lshift limit xor ( crc x )\n\tswap 8 lshift limit xor ; ( crc )\n\n( see http:\/\/stackoverflow.com\/questions\/10564491\/function-to-calculate-a-crc16-checksum\n and https:\/\/www.lammertbies.nl\/comm\/info\/crc-calculation.html )\n: crc16-ccitt ( c-addr u -- u )\n\t0xFFFF -rot\n\t['] ccitt\n\tforeach ;\nhide{ limit ccitt }hide\n\n( ==================== CRC =================================== )\n\n( ==================== Rational Data Type ==================== )\n( This word set allows the manipulation of a rational data type,\nwhich are basically fractions. This allows numbers like 1\/3 to\nbe represented without any loss of precision. Conversion to and\nfrom the data type to an integer type is trivial, although \ninformation can be lost during the conversion.\n\nTo convert to a rational, use 'dup', to convert from a rational,\nuse '\/'. \n\nThe denominator is the first number on the stack, the numerator the\nsecond number. Fractions are simplified after any rational operation,\nand all rational words can accept unsimplified arguments. For example\nthe fraction 1\/3 can be represented as 6\/18, they are equivalent, so\nthe rational equality operator \"=rat\" can accept both and returns\ntrue.\n\n\tT{ 1 3 6 18 =rat -> 1 }T\n\nSee: https:\/\/en.wikipedia.org\/wiki\/Rational_data_type \nFor more information.\n\nThis set of words use two cells to represent a fraction, however\na single cell could be used, with the numerator and the denominator\nstored in upper and lower half of a single cell. )\n\n: simplify ( a b -- a\/gcd{a,b} b\/gcd{a\/b} : simplify a rational )\n 2dup\n gcd\n tuck\n \/\n -rot\n \/\n swap ; \\ ? check this\n\n: crossmultiply ( a b c d -- a*d b*d c*b d*b )\n rot ( a c d b )\n 2dup ( a c d b d b )\n * ( a c d b d*b )\n >r ( a c d b , d*b )\n rot ( a d b c , d*b )\n * ( a d b*c , d*b )\n -rot ( b*c a d , d*b )\n * ( b*c a*d , d*b )\n r> ( b*c a*d d*b )\n tuck ( b*c d*b a*d d*b )\n 2swap ; ( done! )\n\n: *rat ( a\/b c\/d -- a\/b : multiply two rationals together )\n rot * -rot * swap simplify ;\n\n: \/rat ( a\/b c\/d -- a\/b : divide one rational by another )\n swap *rat ;\n\n: +rat ( a\/b c\/d -- a\/b : add two rationals together )\n crossmultiply\n rot\n drop ( or check if equal, if not there is an error )\n -rot\n +\n swap\n simplify ;\n\n: -rat ( a\/b c\/d -- a\/b : subtract one rational from another )\n crossmultiply \n rot\n drop ( or check if equal, if not there is an error )\n -rot\n -\n swap\n simplify ;\n\n: .rat ( a\/b -- : print out a rational number )\n simplify swap . [char] \/ emit space . ;\n\n: =rat ( a\/b c\/d -- bool : rational equal )\n crossmultiply rot = -rot = = ;\n\n: >rat ( a\/b c\/d -- bool : rational greater than )\n crossmultiply rot 2drop > ;\n\n: <=rat ( a\/b c\/d -- bool : rational less than or equal to )\n\t>rat not ;\n\n: =rat ( a\/b c\/d -- bool : rational greater or equal to )\n\t0 block number stored in buf)\n\n: invalid? ( n -- : throw if block number is invalid )\n\t0= if -35 throw then ;\n\n: update ( -- : mark currently loaded block buffer as dirty )\n\ttrue dirty ! ;\n\n: updated? ( n -- bool : )\n\t\n\tdirty @ ;\n\n: block.name ( n -- c-addr u : make a block name )\n\tc\" .blk\" <# holds #s #> rot drop ;\n\n( @warning this will not work if we do not have permission,\nor in various other cases where we cannot open the file, for\nwhatever reason )\n: file-exists ( c-addr u : does a file exist? )\n\tr\/o open-file if drop 0 else close-file throw 1 then ;\n\n: buffer.exists ( n -- bool : does a block buffer exist on disk? )\n\tblock.name file-exists ;\n\n( @note block.write and block.read do not check if they have\nwrote or read in 1024 bytes, nor do they check that they can\nonly write or read 1024 and not a byte more )\n\n: block.read ( file-id -- file-id : read in buffer )\n\tdup >r buf r> read-file nip if close-file -33 throw then ;\n\n: block.write ( file-id -- file-id : write out buffer )\n\tdup >r buf r> write-file nip if close-file -34 throw then ;\n\n: block.open ( n fam -- file-id )\n\t>r block.name r> open-file throw ;\n\n: save-buffers \n\tblk @ 0= if exit then ( not a valid block number, exit )\n\tdirty @ not if exit then ( not dirty, no need to save )\n\tblk @ w\/o block.open ( open file backing block buffer )\n\tblock.write ( write it out )\n\tclose-file throw ( close it )\n\tfalse dirty ! ; ( but only mark it clean if everything succeeded )\n\n: empty-buffers ( -- : deallocate any saved buffers )\n\t0 blk ! ;\n\n: flush ( -- : perform save-buffers followed by empty-buffers )\n\tsave-buffers\n\tempty-buffers ;\n\n( Block is a complex word that does a lot, although it has a simple\ninterface. It does the following given a block number:\n\n1. Checks the provided block buffer number to make sure it is valid\n2. If the block is already loaded from the disk, then return the\naddress of the block buffer it is loaded into.\n3. If not, it checks to see if the currently loaded block buffer is\ndirty, if it is then it flushes the buffer to disk.\n4. If the block buffer does not exists on disk then it creates it.\n5. It then stores the block number in blk and returns an address to\nthe block buffer. )\n: block ( n -- c-addr : load a block )\n\tdup invalid? \n\tdup blk @ = if drop buf drop exit then\n\tflush\n\tdup buffer.exists if ( if the buffer exits on disk load it in )\n\t\tdup r\/o block.open \n\t\tblock.read \n\t\tclose-file throw \n\telse ( else it does not exist )\n\t\tbuf 0 fill ( clean the buffer )\n\tthen \n\tblk ! ( save the block number )\n\tbuf drop ;\n\n: buffer block ;\n\n( @warning uses hack, block buffer is NUL terminated, and evaluate requires\na NUL terminated string, evaluate checks that the last character is NUL, \nhence the 1+ )\n: load ( n -- : load and execute a block )\n\tblock b\/buf 1+ evaluate throw ;\n\nhide{ \n\tblock.name invalid? block.write \n\tblock.read buffer.exists block.open dirty\n}hide\n\n( ==================== Block Layer =========================== )\n\n( ==================== List ================================== )\n1 variable fancy-list\n0 variable scr\n64 constant c\/l ( characters per line )\n\n: line.number ( n -- : print line number )\n\tfancy-list @ if\n\t\tdup 10 < (base) 10 = and if space then ( leading space: works up to c\/l = 99)\n\t\t. [char] | emit ( print \" line-number : \")\n\telse\n\t\tdrop\n\tthen ;\n\n: line ( c-addr -- c-addr u : given a line number, display that line )\n\tdup \n\tline.number ( display line number )\n\tc\/l * + ( calculate offset )\n\tc\/l ; ( add line length )\n\n: list.end\n\tfancy-list @ not if exit then\n\t[char] | emit ;\n\n: list.type ( c-addr u -- : list a block )\n\tb\/buf c\/l \/ 0 do dup i line type list.end cr loop drop ;\n\n: list.border \" +---|---\" ;\n\n: list.box\n\tfancy-list @ not if exit then\n\t4 spaces\n\t8 0 do list.border loop cr ;\n\n: list ( n -- : display a block number and update scr )\n\tdup >r block r> scr ! list.box list.type list.box ;\n\n: thru\n\tkey drop\n\t1+ swap do i list more loop ;\n\n: make-blocks ( n1 n2 -- : make blocks on disk from n1 to n2 inclusive )\n\t1+ swap do i block b\/buf bl fill update loop save-buffers ;\n\nhide{ buf line line.number list.type fancy-list (base) list.box list.border list.end }hide\n\n( ==================== List ================================== )\n\n( ==================== Signal Handling ======================= )\n( Signal handling at the moment is quite primitive. When a signal\noccurs it has to be explicitly tested for by the programmer, this\ncould be improved on quite a bit. One way of doing this would be\nto check for signals in the virtual machine and cause a THROW\nfrom within it. )\n\n( signals are biased to fall outside the range of the error numbers\ndefined in the ANS Forth standard. )\n-512 constant signal-bias \n\n: signal ( -- signal\/0 : push the results of the signal register ) \n\t`signal @\n \t0 `signal ! ;\n\n( ==================== Signal Handling ======================= )\n\n( Looking at most Forths dictionary with \"words\" command they tend\nto have a lot of words that do not mean anything but to the implementers\nof that specific Forth, here we clean up as many non standard words as\npossible. )\nhide{ \n do-string ')' alignment-bits \n dictionary-start hidden-mask instruction-mask immediate-mask compiling?\n compile-bit\n max-core dolist doconst x x! x@ \n max-string-length \n _exit\n pnum evaluator \n TrueFalse >instruction \n xt-instruction\n `state\n `source-id `sin `sidx `slen `start-address `fin `fout `stdin\n `stdout `stderr `argc `argv `debug `invalid `top `instruction\n `stack-size `error-handler `x `handler _emit `signal \n}hide\n\n( \n## Forth To List\n\nThe following is a To-Do list for the Forth code itself, along with any\nother ideas.\n\n* FORTH, VOCABULARY\n* \"Value\", \"To\", \"Is\"\n* Double cell words \n* The interpreter should use character based addresses, instead of\nword based, and use values that are actual valid pointers, this\nwill allow easier interaction with the world outside the virtual machine\n* common words and actions should be factored out to simplify\ndefinitions of other words, their standards compliant version found\nif any\n* A soft floating point library would be useful which could be used\nto optionally implement floats [which is not something I really want\nto add to the virtual machine]. If floats were to be added, only the\nminimal set of functions should be added [f+,f-,f\/,f*,f<,f>,>float,...]\n* Allow the processing of argc and argv, the mechanism by which that\nthis can be achieved needs to be worked out. However all processing that\nis currently done in \"main.c\" should be done within the Forth interpreter\ninstead. Words for manipulating rationals and double width cells should\nbe made first.\n* A built in version of \"dump\" and \"words\" should be added to the Forth\nstarting vocabulary, simplified versions that can be hidden.\n* Here documents, string literals. Examples of these can be found online\n* Document the words in this file and built in words better, also turn this\ndocument into a literate Forth file.\n* Sort out \"'\", \"[']\", \"find\", \"compile,\" \n* Proper booleans should be used throughout, that is -1 is true, and 0 is\nfalse.\n* Attempt to add crypto primitives, not for serious use, like TEA, XTEA,\nXXTEA, RC4, MD5, ...\n* Add hash functions: CRC-32, CRC-16, ...\nhttp:\/\/stackoverflow.com\/questions\/10564491\/function-to-calculate-a-crc16-checksum\n* File operation primitives that close the file stream [and possibly restore\nI\/O to stdin\/stdout] if an error occurs, and then re-throws, should be made.\n* Implement as many things from http:\/\/lars.nocrew.org\/forth2012\/implement.html\nas is sensible. \n* The current words that implement I\/O redirection need to be improved, and documented,\nI think this is quite a useful and powerful mechanism to use within Forth that simplifies\nprograms. This is a must and will make writing utilities in Forth a *lot* easier \n* Words for manipulating words should be added, for navigating to different\nfields within them, to the end of the word, etcetera.\n* The data structure used for parsing Forth words needs changing in libforth so a\ncounted string is produced. Counted strings should be used more often. The current\nlayout of a Forth word prevents a counted string being used and uses a byte more\nthan it has to.\n* Whether certain simple words [such as '1+', '1-', '>', '<', '<>', 'not', '<=',\n'>='] should be added as virtual machine instructions for speed [and size] reasons\nshould be investigated.\n* An analysis of the interpreter and the code it executes could be done to find\nthe most commonly executed words and instructions, as well as the most common two and\nthree sequences of words and instructions. This could be used to use to optimize the\ninterpreter, in terms of both speed and size.\n* As a thought, a word for inlining other words could be made by copying everything\ninto the current definition until it reaches a _exit, it would need to be aware of\nliterals written into a word, like 'see' is.\n\n### libforth.c todo\n\n* A halt, a parse, and a print\/type instruction could be added to the Forth virtual\nmachine.\n* Throw\/Catch need to be added and used in the virtual machine\n* Various edge cases and exceptions should be removed [for example counted strings\nare not used internally, and '0x' can be used as a prefix only when base is zero].\n* A potential optimization is to order the words in the dictionary by frequency order,\nthis would mean chaning the X Macro that contains the list of words, after collecting\nstatistics. This should make find faster.\n* Investigate adding operating system specific code into the interpreter and\nisolating it to make it semi-portable.\n* Make equivalents for various Unix utilities in Forth, like a CRC check, cat,\ntr, etcetera.\n\n )\n\nverbose [if] \n\t.( FORTH: libforth successfully loaded.) cr\n\t.( Type 'help' and press return for a basic introduction.) cr\n\t.( Core: ) here . \" \/ \" here unused + . cr\n\t license\n[then]\n\n\n( ==================== Test Code ============================= )\n\n( The following will not work as we might actually be reading from a string [`sin]\nnot `fin. \n: key 32 chars> 1 `fin @ read-file drop 0 = if 0 else 32 chars> c@ then ; )\n\n\\ : ' immediate state @ if postpone ['] else find then ;\n\n( This really does not implement a correct FORTH\/VOCABULARY, for that\nwordlists will need to be introduced and used in libforth.c. The best\nthat this word set can do is to hide and reveal words to the user, this\nwas just an experiment. \n\n\t: forth \n\t\t[ find forth 1- @ ] literal\n\t\t[ find forth 1- ] literal ! ;\n\n\t: vocabulary\n\t\tcreate does> drop 0 [ find forth 1- ] literal ! ; )\n\n\\ @todo The built in primitives should be redefined so to make sure\n\\ they are called and nested correctly, using the following words\n\\ 0 variable csp\n\\ : !csp sp@ csp ! ;\n\\ : ?csp sp@ csp @ <> if -22 throw then ;\n\n\\ @todo Make this work\n\\ : >body ??? ;\n\\ : noop ( -- ) ;\n\\ : defer create ( \"name\" -- ) ['] noop , does> ( -- ) @ execute ;\n\\ : is ( xt \"name\" -- ) find >body ! ;\n\\ defer lessthan\n\\ find < is lessthan\n\n( ==================== Test Code ============================= )\n\n( ==================== Block Editor ========================== )\n( Experimental block editor Mark II \n\n@todo Improve the block editor \n\n- '\\' needs extending to work with the block editor, for now, \nuse parenthesis for comments \n- make an 'm' word for forgetting all words defined since the\neditor was invoked.\n- add multi line insertion mode\n- Add to an editor vocabulary, which will need the vocabulary\nsystem to exist.\n- Using 'page' should be optional as not all terminals support\nANSI escape codes - thanks to CMD.EXE. Damned Windows.\n- How line numbers are printed out should be investigated,\nalso I should refactor 'dump' to use a similar line number system.\n- Format the output of list better, put a nice box around it.\n\nAdapted from http:\/\/retroforth.org\/pages\/?PortsOfRetroEditor )\n\n \n: help ( @todo renamed to 'h' once vocabularies are implemented )\npage cr\n\" Block Editor Help Menu\n\n n move to next block\n p move to previous block\n # d delete line in current block\n x erase current block\n e evaluate current block\n # i insert line\n # #2 ia insert at line #2 at column #\n q quit editor loop\n # b set block number\n s save block and write it out\n\n -- press any key to continue -- \" cr ( \" )\nchar drop ;\n\n: (block) blk @ block ; \n: (line) c\/l * (block) + ; ( n -- c-addr : push current line address )\n: (clean) \n\t(block) b\/buf\n\t2dup nl bl subst\n\t2dup cret bl subst\n\t 0 bl subst ;\n: n blk @ 1+ block ;\n: p blk @ 1- block ;\n: d (line) c\/l bl fill ; \n: x (block) b\/buf bl fill ;\n: s update save-buffers ;\n: q rdrop rdrop ;\n: e blk @ load char drop ;\n: ia c\/l * + dup b\/buf swap - >r (block) + r> accept (clean) ; \n: i 0 swap ia ;\n: editor\n\t1 block\n\tbegin\n\t\tpostpone [ ( need to be in command mode )\n\t\tpage cr\n\t\t\" BLOCK EDITOR: TYPE 'HELP' FOR A LIST OF COMMANDS\" cr\n\t\tblk @ list\n\t\t\" CURRENT BLOCK: \" blk @ . cr\n\t\tread\n\tagain ;\n\n( Extra niceties )\nc\/l string yank\nyank bl fill\n: u update ;\n: b block ;\n: l blk @ list ;\n: y (line) yank >r swap r> cmove ;\n: c (line) yank cmove ;\n: ct swap y c ;\n\nhide{ (block) (line) (clean) yank }hide\n\n( ==================== Block Editor ========================== )\n\nhere fence ! ( final fence - works before this cannot be forgotten )\n\n\n\n","old_contents":"#!.\/forth \n( Welcome to libforth, A dialect of Forth. Like all versions of Forth this\nversion is a little idiosyncratic, but how the interpreter works is\ndocumented here and in various other files.\n\nThis file contains most of the start up code, some basic start up code\nis executed in the C file as well which makes programming at least bearable.\nMost of Forth is programmed in itself, which may seem odd if your back\nground in programming comes from more traditional language [such as C],\nalthough less so if you know already know lisp.\n\nFor more information about this interpreter and Forth see:\n\thttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\treadme.md : for a manual for this interpreter\n\tlibforth.h : for information about the C API\n\tlibforth.c : for the interpreter itself\n\tunit.c : a series of unit tests against libforth.c\n\tunit.fth : a series of unit tests against this file\n\nThe interpreter and this code originally descend from a Forth interpreter\nwritten in 1992 for the International obfuscated C Coding Competition\n\nSee:\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\nThe manual for the interpreter should be read first before looking into this\ncode. It is important to understand the execution model of Forth, especially\nthe differences between command and compile mode, and how immediate and compiling\nwords work.\n\n@todo Restructure and describe structure of this file.\n\nEach of these sections is clearly labeled and they are generally in dependency order.\n\nUnfortunately the code in this file is not as portable as it could be, it makes\nassumptions about the size of cells provided by the virtual machine, which will\ntake time to rectify. Some of the constructs are subtly different from the\nDPANs Forth specification, which is usually noted. Eventually this should\nalso be fixed.)\n\n( ========================== Basic Word Set ================================== )\n\n( \nWe'll begin by defining very simple words we can use later, these a very\nbasic words, that perform simple tasks, they will not require much explanation.\n\nEven though the words are simple, their stack comment and a description for\nthem will still be included so external tools can process and automatically\nextract the document string for a given work.\n)\n\n: postpone ( -- : postpone execution of the following immediate word )\n\timmediate find , ;\n\n: :: ( -- : compiling version of ':' )\n\t[ find : , ] ;\n\n: constant \n\t:: ( compile word header )\n\there 1 - h ! ( decrement dictionary pointer )\n\there @ instruction-mask invert and doconst or here ! ( change instruction to CONST )\n\there 1 + h ! ( increment dictionary pointer )\n\t, ( write in value )\n\tpostpone [ ; ( back into command mode )\n\n( space saving measure )\n-1 constant -1\n 0 constant 0 \n 1 constant 1\n 2 constant 2\n 3 constant 3\n\n0 constant false\n1 constant true ( @warning not standards compliant )\n\n( Confusingly the word 'cr' prints a line feed )\n10 constant lf ( line feed )\nlf constant nl ( new line - line feed on Unixen )\n13 constant cret ( carriage return )\n\n1 hidden-bit lshift constant hidden-mask ( mask for the hide bit in a words CODE field )\n\n-1 -1 1 rshift invert and constant min-signed-integer\n\nmin-signed-integer invert constant max-signed-integer\n\n1 constant cell ( size of a cell in address units )\n\n4 constant version ( version number for the interpreter )\n\ncell size 8 * * constant address-unit-bits ( the number of bits in an address )\n\n-1 -1 1 rshift and invert constant sign-bit ( bit corresponding to the sign in a number )\n\n( @todo test by how much, if at all, making words like 1+, 1-, <>, and other\nsimple words, part of the interpreter would speed things up )\n\n: 1+ ( x -- x : increment a number ) \n\t1 + ;\n\n: 1- ( x -- x : decrement a number ) \n\t1 - ;\n\n: chars ( c-addr -- addr : convert a character address to an address )\n\tsize \/ ; \n\n: chars> ( addr -- c-addr: convert an address to a character address )\n\tsize * ; \n\n: tab ( -- : print a tab character to current output device )\n\t9 emit ;\n\n: 0= ( x -- bool : is 'x' equal to zero? )\n\t0 = ;\n\n: not ( x -- bool : is 'x' true? )\n\t0= ;\n\n: <> ( x x -- bool : not equal )\n\t= 0= ;\n\n: logical ( x -- bool : turn a value into a boolean ) \n\tnot not ;\n\n( @todo \": dolit ' ' ;\" works but does not interact well with \n'decompile', if this was fixed the special work could be removed,\nwith some extra effort in libforth.c as well )\n: dolit ( -- x : location of special \"push\" word )\n\t2 ; \n\n: 2, ( x x -- : write two values into the dictionary )\n\t, , ;\n\n: [literal] ( x -- : write a literal into the dictionary )\n\tdolit 2, ; \n\n: literal ( x -- : immediately write a literal into the dictionary )\n\timmediate [literal] ;\n\n: sliteral immediate ( I: c-addr u --, Run: -- c-addr u )\n\tswap [literal] [literal] ;\n\n( @todo throw if not found )\n: ['] ( I: c\" xxx\", Run: -- xt )\n\timmediate find [literal] ;\n\n: >instruction ( CODE -- Instruction : extract instruction from instruction field ) \n\tinstruction-mask and ;\n\n: immediate-mask ( -- x : pushes the mask for the compile bit in a words CODE field )\n\t[ 1 compile-bit lshift ] literal ;\n\n: hidden? ( PWD -- PWD bool : is a word hidden, given the words PWD field ) \n\tdup 1+ @ hidden-mask and logical ;\n\n: compiling? ( PWD -- PWD bool : is a word immediate, given the words PWD field )\n\tdup 1+ @ immediate-mask and logical ;\n\n: cr ( -- : emit a newline character )\n\tnl emit ;\n\n: < ( x1 x2 -- bool : signed less than comparison )\n\t- dup if max-signed-integer u> else logical then ;\n\n: > ( x1 x2 -- bool : signed greater than comparison )\n\t- dup if max-signed-integer u< else logical then ;\n\n: #pad ( -- u : offset into pad area )\n\t64 ;\n\n: pad\n\t( the pad is used for temporary storage, and moves\n\talong with dictionary pointer, always in front of it )\n\there #pad + ;\n\n( @todo this can be improved a lot, currently it uses more\nspace than it has to, 4 cells instead of three.\n\nIt does:\n\n\tpush value\n\tpush value\n\nInstead of:\n\n\tmagic-2literal-word\n\tvalue\n\tvalue\n\n)\n: 2literal immediate ( x x -- : immediate write two literals into the dictionary )\n\tswap [literal] [literal] ;\n\n: latest ( get latest defined word )\n\tpwd @ ; \n\n: stdin ( -- fileid : push the fileid for the standard input channel ) \n\t`stdin @ ;\n\n: stdout ( -- fileid : push the fileid for the standard output channel ) \n\t`stdout @ ;\n\n: stderr ( -- fileid : push the fileid for the standard error channel ) \n\t`stderr @ ;\n\n: stdin? ( -- bool : are we reading from standard input )\n\t`fin @ stdin = ;\n\n: *+ ( x1 x2 x3 -- x ) \n\t* + ;\n\t\n: 2- ( x -- x : decrement by two )\n\t2 - ( x -- x ) ;\n\n: 2+ ( x -- x : increment by two )\n\t2 + ( x -- x ) ;\n\n: 3+ ( x -- x : increment by three )\n\t3 + ( x -- x ) ;\n\n: 2* ( x -- x : multiply by two )\n\t1 lshift ( x -- x ) ;\n\n: 2\/ ( x -- x : divide by two )\n\t1 rshift ( x -- x ) ;\n\n: 4* ( x -- x : multiply by four )\n\t2 lshift ( x -- x ) ;\n\n: 4\/ ( x -- x : divide by four )\n\t2 rshift ( x -- x ) ;\n\n: 8* ( x -- x : multiply by eight )\n\t3 lshift ( x -- x ) ;\n\n: 8\/ ( x -- x : divide by eight )\n\t3 rshift ( x -- x ) ;\n\n: 256* ( x -- x : multiply by 256 )\n\t8 lshift ( x -- x ) ;\n\n: 256\/ ( x -- x : divide by 256 )\n\t8 rshift ( x -- x ) ;\n\n: 2dup ( x1 x2 -- x1 x2 x1 x2 : duplicate two values )\n\tover over ;\n\n: mod ( x u -- x : calculate the remainder of x divided by u ) \n\t2dup \/ * - ;\n\n( @todo implement um\/mod in the VM, then use this to implement \/ and mod )\n: um\/mod ( x1 x2 -- rem quot : calculate the remainder and quotient of x1 divided by x2 ) \n\t2dup \/ >r mod r> ;\n\n: *\/ ( x1 x2 x3 -- x4 : multiply then divide, @warning this does not use a double cell for the multiply )\n\t * \/ ; \n\n: char ( -- x : read in a character from the input steam )\n\tkey drop key ;\n\n: [char] ( -- x : immediately read in a character from the input stream )\n\timmediate char [literal] ;\n\n: compose ( xt1 xt2 -- xt3 : create a new function from two xt-tokens )\n\t>r >r ( save execution tokens )\n\tpostpone :noname ( create a new :noname word for our xt-tokens )\n\tr> , ( write first token )\n\tr> , ( write second token )\n\tpostpone ; ; ( terminate new :noname )\n\n: unless ( bool -- : like 'if' but execute clause if false )\n\timmediate ['] 0= , postpone if ;\n\n: endif ( synonym for 'then' ) \n\timmediate postpone then ;\n\n: cells ( n1 -- n2 : convert a number of cells into a number of cells in address units ) \n\timmediate ;\n\n: cell+ ( a-addr1 -- a-addr2 ) \n\tcell + ;\n\n: negative? ( x -- bool : is a number negative? )\n\tsign-bit and logical ;\n\n: mask-byte ( x -- x : generate mask byte ) \n\t8* 255 swap lshift ;\n\n: select-byte ( u i -- c ) \n\t8* rshift 0xff and ;\n\n: xt-instruction ( extract instruction from execution token )\n\tcell+ @ >instruction ;\n\n: defined-word? ( CODE -- bool : is a word a defined or a built in words )\n\txt-instruction dolist = ;\n\n: char+ ( c-addr -- c-addr : increment a character address by the size of one character ) \n\t1+ ;\n\n: 2chars ( c-addr1 c-addr2 -- addr addr : convert two character addresses to two cell addresses ) \n\tchars swap chars swap ;\n\n: 2chars> ( addr addr -- c-addr c-addr: convert two cell addresses to two character addresses )\n\tchars> swap chars> swap ;\n\n: hex ( -- : print out hex ) \n\t16 base ! ;\n\n: octal ( -- : print out octal ) \n\t8 base ! ;\n\n: binary ( -- : print out binary ) \n\t2 base ! ;\n\n: decimal ( -- : print out decimal ) \n\t0 base ! ;\n\n: negate ( x -- x ) \n\t-1 * ;\n\n: abs ( x -- u : return the absolute value of a number )\n\tdup negative? if negate then ;\n\n: square ( x -- x ) \n\tdup * ;\n\n: sum-of-squares ( a b -- c : compute a^2 + b^2 to get c )\n\tsquare swap square + ;\n\n: drup ( x y -- x x ) \n\tdrop dup ;\n\n: +! ( x addr -- : add x to a value stored at addr ) \n\ttuck @ + swap ! ;\n\n: 1+! ( addr -- : increment a value at an address ) \n\t1 swap +! ;\n\n: 1-! ( addr -- : decrement a value at an address ) \n\t-1 swap +! ;\n\n: c+! ( x c-addr -- : add x to a value stored at c-addr )\n\ttuck c@ + swap c! ;\n\n: toggle ( addr u -- : complement the value at address with the bit pattern u ) \n\tover @ xor swap ! ;\n\n: lsb ( x -- x : mask off the least significant byte of a cell ) \n\t255 and ;\n\n: \\ ( -- : immediate word, used for single line comments )\n\timmediate begin key nl = until ;\n\n: ?dup ( x -- ? ) \n\tdup if dup then ;\n\n: min ( x y -- min : return the minimum of two integers ) \n\t2dup < if drop else swap drop then ;\n\n: max ( x y -- max : return the maximum of two integers ) \n\t2dup > if drop else swap drop then ;\n\n: limit ( x min max -- x : limit x with a minimum and maximum )\n\trot min max ;\n\n: >= ( x y -- bool ) \n\t< not ;\n\n: <= ( x y -- bool ) \n\t> not ;\n\n: 2@ ( a-addr -- x1 x2 : load two consecutive memory cells )\n\tdup 1+ @ swap @ ;\n\n: 2! ( x1 x2 a-addr -- : store two values as two consecutive memory cells )\n\t2dup ! nip 1+ ! ;\n\n: r@ ( -- x, R: x -- )\n\tr> r @ swap >r ;\n\n: rp@ ( -- x, R: x -- )\n\tr> r @ swap >r ;\n\n( @todo r!, rp! )\n\n: 0> ( x -- bool )\n\t0 > ;\n\n: 0< ( x -- bool )\n\t0 < ;\n\n: 0<> ( x -- bool )\n\t0 <> ;\n\n: signum ( x -- -1 | 0 | 1 : )\n\tdup 0< if drop -1 exit then\n\t 0> if 1 exit then\n\t0 ;\n\n: nand ( x x -- x : bitwise NAND ) \n\tand invert ;\n\n: odd ( x -- bool : is 'x' odd? )\n\t1 and ;\n\n: even ( x -- bool : is 'x' even? )\n\todd not ;\n\n: nor ( x x -- x : bitwise NOR ) \n\tor invert ;\n\n: ms ( u -- : wait at least 'u' milliseconds ) \n\tclock + begin dup clock u< until drop ;\n\n: sleep ( u -- : sleep for 'u' seconds )\n\t1000 * ms ;\n\n: align ( addr -- addr : align an address, nop in this implemented )\n\timmediate ; \n\n: ) ( -- : do nothing, this allows easy commenting out of code )\n\timmediate ;\n\n: bell ( -- : emit an ASCII BEL character ) \n\t7 emit ;\n\n: b\/buf ( -- u : bytes per buffer ) \n\t1024 ;\n\n: .d ( x -- x : debug print ) \n\tdup . ;\n\n: compile, ( x -- : )\n\t, ;\n\n: >mark ( -- : write a hole into the dictionary and push a pointer to it ) \n\there 0 , ;\n\n: r - r> u< ;\n\n: invalidate ( -- : invalidate this Forth core )\n\t1 `invalid ! ;\n\n: signed ( x -- bool : return true if sign bit set ) \n\t[ 1 size 8 * 1- lshift ] literal and logical ;\n\n: u>= ( x y -- bool : unsigned greater than or equal to )\n\t2dup u> >r = r> or ;\n\n: u<= ( x y -- bool : unsigned less than or equal to )\n\tu>= not ;\n\n: rdrop ( R: x -- : drop a value from the return stack )\n\tr> ( get caller's return address )\n\tr> ( get value to drop )\n\tdrop ( drop it like it's hot )\n\t>r ; ( return return address )\n\n: rdup\n\tr> ( get caller's return address )\n\tr> ( get value to duplicate )\n\tdup ( ... )\n\t>r >r >r ; ( make it all work )\n\n: again immediate\n\t( loop unconditionally in a begin-loop:\n\t\tbegin ... again )\n\t' branch , ;\n\n: source ( -- c-addr u )\n\t#tib ( size of input buffer, in characters )\n\ttib ; ( start of input buffer, in characters )\n\n: stdin? ( -- bool : are we reading from standard in? )\n\t`fin @ `stdin @ = ;\n\n: source-id ( -- 0 | -1 | file-id )\n\t( \t\n\tValue Input Source\n\t-1 String\n\t0 Reading from user input \/ standard in\n\tfile-id )\n\t`source-id @ \n\t0= if\n\t\tstdin? if 0 else `fin @ then\n\telse\n\t\t-1\n\tthen ;\n\n: under ( x1 x2 -- x1 x1 x2 )\n\t>r dup r> ;\n\n: 2nip ( n1 n2 n3 n4 -- n3 n4 ) \n\t>r >r 2drop r> r> ;\n\n: 2over ( n1 n2 n3 n4 \u2013 n1 n2 n3 n4 n1 n2 )\n\t>r >r 2dup r> swap >r swap r> r> -rot ;\n\n: 2swap ( n1 n2 n3 n4 \u2013 n3 n4 n1 n2 )\n\t>r -rot r> -rot ;\n\n: 2tuck ( n1 n2 n3 n4 \u2013 n3 n4 n1 n2 n3 n4 )\n\t2swap 2over ;\n\n: 3drop ( x1 x2 x3 -- )\n\tdrop 2drop ;\n\n: nos1+ ( x1 x2 -- x1+1 x2 : increment the next variable on that stack )\n\tswap 1+ swap ;\n\n: ?dup-if immediate ( x -- x | - : ?dup and if rolled into one! )\n\t['] ?dup , postpone if ;\n\n: ?if ( -- : non destructive if ) \n\timmediate ['] dup , postpone if ;\n\n: (hide) ( token -- hide-token : this hides a word from being found by the interpreter )\n\t?dup-if\n\t\tdup @ hidden-mask or swap tuck ! exit\n\tthen 0 ;\n\n: hide ( WORD -- : hide with drop ) \n\tfind dup if (hide) then drop ;\n\n: reveal ( hide-token -- : reveal a hidden word ) \n\tdup @ hidden-mask invert and swap ! ;\n\n: ?exit ( x -- : exit current definition if not zero ) \n\tif rdrop exit then ;\n\n: decimal? ( c -- f : is character a number? )\n\t[char] 0 [ char 9 1+ ] literal within ;\n\n: lowercase? ( c -- f : is character lower case? )\n\t[char] a [ char z 1+ ] literal within ;\n\n: uppercase? ( C -- f : is character upper case? )\n\t[char] A [ char Z 1+ ] literal within ;\n\n: alpha? ( C -- f : is character part of the alphabet? )\n\tdup lowercase? swap uppercase? or ;\n\n: alphanumeric? ( C -- f : is character alphabetic or a number ? )\n\tdup alpha? swap decimal? or ;\n\n: printable? ( c -- bool : is printable, excluding new lines and tables )\n\t32 127 within ;\n\n: >upper ( c -- C : convert char to uppercase iff lower case )\n\tdup lowercase? if bl xor then ;\n\n: >lower ( C -- c : convert char to lowercase iff upper case )\n\tdup uppercase? if bl xor then ;\n\n: <=> ( x y -- z : spaceship operator! )\n\t2dup\n\t> if 2drop -1 exit then\n\t< ;\n\n: start-address ( -- c-addr : push the start address )\n\t`start-address @ ;\n\n: >real-address ( c-addr -- r-addr : convert an interpreter address to a real address )\n\tstart-address + ;\n\n: real-address> ( c-addr -- r-addr : convert a real address to an interpreter address )\n\tstart-address - ;\n\n: peek ( r-addr -- n : )\n\tpad chars> >real-address swap size memory-copy pad @ ;\n\n: poke ( n r-addr -- : )\n\tswap pad ! pad chars> >real-address size memory-copy ;\n\n: die! ( x -- : controls actions when encountering certain errors )\n\t`error-handler ! ;\n\n: start! ( cfa -- : set the word to execute at startup )\n\t`instruction ! ;\t\n\n: warm ( -- : restart the interpreter, warm restart )\n\t1 restart ;\n\n: trip ( x -- x x x : triplicate a number ) \n\tdup dup ;\n\n: roll ( xu xu-1 ... x0 u -- xu-1 ... x0 xu : move u+1 items on the top of the stack by u )\n\tdup 0 >\n\tif\n\t\tswap >r 1- roll r> swap\n\telse\n\t\tdrop\n\tthen ;\n\n: 2rot ( n1 n2 n3 n4 n5 n6 \u2013 n3 n4 n5 n6 n1 n2 )\n\t5 roll 5 roll ;\n\n: s>d ( x -- d : convert a signed value to a double width cell )\n\t( @note the if...else...then is only necessary as this Forths\n\tbooleans are 0 and 1, not 0 and -1 as it usually is )\n\tdup 0< if -1 else 0 then ;\n\n: trace ( level -- : set tracing level )\n\t`debug ! ;\n\n: verbose ( -- : get the log level )\n\t`debug @ ;\n\n: count ( c-addr1 -- c-addr2 u : get a string whose first char is its length )\n\tdup c@ nos1+ ;\n\n: bounds ( x y -- y+x x : make an upper and lower bound )\n\tover + swap ;\n\n: aligned ( unaligned -- aligned : align a pointer )\n\t[ size 1- ] literal + \n\t[ size 1- ] literal invert and ;\n\n: rdepth\n\tmax-core `stack-size @ - r @ swap - ;\n\n: r.s ( -- : print the contents of the return stack )\n\tr> \n\t[char] < emit rdepth . [char] > emit\n\tspace\n\trdepth dup 0> if dup\n\tbegin dup while r> -rot 1- repeat drop dup\n\tbegin dup while rot dup . >r 1- repeat drop\n\tthen drop cr \n\t>r ;\n\n: argv ( -- r-addr : push pointer to array of string pointers to program )\n\t`argv @ ;\n\n: argc ( -- u : push the number of arguments in the argv array )\n\t`argc @ ;\n\n: +- ( x1 x2 -- x3 : copy the sign of x1 to x2 giving x3 )\n\t[ sign-bit 1- ] literal and\n\tswap\n\tsign-bit and or ;\n\n: \/string ( c-addr1 u1 u2 -- c-addr2 u2 : advance a string by n characters )\n\tover min rot over + -rot - ;\n\nhide stdin?\n\n( ================================== DUMP ================================== )\n\\ : newline ( x -- x+1 : print a new line every fourth value )\n\\ \tdup 3 and 0= if cr then 1+ ;\n\\ \n\\ : address ( num count -- count : print current address we are dumping every fourth value )\n\\ \tdup >r\n\\ \t1- 3 and 0= if . [char] : emit space else drop then\n\\ \tr> ;\n\\ \n\\ : dump ( start count -- : print the contents of a section of memory )\n\\ \\\thex ( switch to hex mode )\n\\ \t1 >r ( save counter on return stack )\n\\ \tover + swap ( calculate limits: start start+count )\n\\ \tbegin \n\\ \t\t2dup u> ( stop if gone past limits )\n\\ \twhile \n\\ \t\tdup r> address >r\n\\ \t\tdup @ . 1+ \n\\ \t\tr> newline >r\n\\ \trepeat \n\\ \tr> drop\n\\ \t2drop ;\n\\ \n\\ hide newline\n\\ hide address \n( ================================== DUMP ================================== )\n\n: cfa immediate ( find-address -- cfa )\n\t( Given the address of the PWD field of a word this\n\tfunction will return an execution token for the word )\n\t( @todo if < dictionary start PWD is invalid )\n\t ;\n\n\\ : >body ( xt -- a-addr : a-addr is data field of a CREATEd word )\n\\\tcfa 5 + ;\n\n\n: execute ( xt -- : given an execution token, execute the word )\n\t( create a word that pushes the address of a hole to write to.\n\tA literal takes up two words, '!' takes up one, that's right,\n\tsome self modifying code! )\n\t[ here 3 cells + literal ] ( calculate place to write to )\n\t! ( write an execution token to a hole )\n\t[ 0 , ] ; ( this is the hole we write )\n\n( See: http:\/\/lars.nocrew.org\/dpans\/dpans9.htm\n@todo turn this into a lookup table of strings\n\n Code Reserved for\n ---- ------------\n -1 ABORT\n -2 ABORT\"\n -3 stack overflow\n -4 stack underflow\n -5 return stack overflow\n -6 return stack underflow\n -7 do-loops nested too deeply during execution\n -8 dictionary overflow\n -9 invalid memory address\n -10 division by zero\n -11 result out of range\n -12 argument type mismatch\n -13 undefined word\n -14 interpreting a compile-only word\n -15 invalid FORGET\n -16 attempt to use zero-length string as a name\n -17 pictured numeric output string overflow\n -18 parsed string overflow\n -19 definition name too long\n -20 write to a read-only location\n -21 unsupported operation [e.g., AT-XY on a\n too-dumb terminal]\n -22 control structure mismatch\n -23 address alignment exception\n -24 invalid numeric argument\n -25 return stack imbalance\n -26 loop parameters unavailable\n -27 invalid recursion\n -28 user interrupt\n -29 compiler nesting\n -30 obsolescent feature\n -31 >BODY used on non-CREATEd definition\n -32 invalid name argument [e.g., TO xxx]\n -33 block read exception\n -34 block write exception\n -35 invalid block number\n -36 invalid file position\n -37 file I\/O exception\n -38 non-existent file\n -39 unexpected end of file\n -40 invalid BASE for floating point conversion\n -41 loss of precision\n -42 floating-point divide by zero\n -43 floating-point result out of range\n -44 floating-point stack overflow\n -45 floating-point stack underflow\n -46 floating-point invalid argument\n -47 compilation word list deleted\n -48 invalid POSTPONE\n -49 search-order overflow\n -50 search-order underflow\n -51 compilation word list changed\n -52 control-flow stack overflow\n -53 exception stack overflow\n -54 floating-point underflow\n -55 floating-point unidentified fault\n -56 QUIT\n -57 exception in sending or receiving a character\n -58 [IF], [ELSE], or [THEN] exception )\n\n( @todo integrate catch\/throw into the interpreter as primitives )\n: catch ( xt -- exception# | 0 : return addr on stack )\n\tsp@ >r ( xt : save data stack pointer )\n\t`handler @ >r ( xt : and previous handler )\n\tr@ `handler ! ( xt : set current handler )\n\texecute ( execute returns if no throw )\n\tr> `handler ! ( restore previous handler )\n\tr> drop ( discard saved stack ptr )\n\t0 ; ( 0 : normal completion )\n\n( @todo use this everywhere )\n: throw ( ??? exception# -- ??? exception# )\n\t?dup-if ( exc# \\ 0 throw is no-op )\n\t\t`handler @ r ! ( exc# : restore prev return stack )\n\t\tr> `handler ! ( exc# : restore prev handler )\n\t\tr> swap >r ( saved-sp : exc# on return stack )\n\t\tsp! drop r> ( exc# : restore stack )\n\t\t( return to the caller of catch because return )\n\t\t( stack is restored to the state that existed )\n\t\t( when catch began execution )\n\tthen ; \n\n: interpret ( c1\" xxx\" ... cn\" xxx\" -- : This word implements the interpreter loop )\n\tbegin \n\t' read catch \n\t?dup-if [char] ! emit tab . cr then ( exception handler of last resort )\n\tagain ;\n\n\n: [interpret] ( c1\" xxx\" ... cn\" xxx\" -- : immediate version of interpret )\n\timmediate interpret ;\n\ninterpret ( use the new interpret word, which can catch exceptions )\n\nfind [interpret] cell+ start! ( the word executed on restart is now our new word )\n\n( The following words are using in various control structure related\nwords to make sure they only execute in the correct state )\n\n: ?comp ( -- : error if not compiling )\n\tstate @ 0= if -22 throw then ; \n\n: ?exec ( -- : error if not executing )\n\tstate @ if -22 throw then ; \n\n\n( ========================== Basic Word Set ================================== )\n\n( ========================== DOER\/MAKE ======================================= )\n( DOER\/MAKE is a word set that is quite powerful and is described in Leo Brodie's\nbook \"Thinking Forth\". It can be used to make words whose behavior can change\nafter they are defined. It essentially makes the structured use of self-modifying\ncode possible, along with the more common definitions of \"defer\/is\".\n\nAccording to \"Thinking Forth\", it has two purposes:\n\n1. To change the state of a function.\n2. To factor out common phrases of a words definition.\n\nAn example of the first instance:\n\n\tdoer say\n\t: sad \" Good bye, cruel World!\" cr ;\n\t: happy \" Hello, World!\" cr ;\n\n\t: person say ;\n\n\tmake person happy\n\tperson \\ prints \"Good bye, cruel World!\"\n\n\tmake person sad \n\tperson \\ prints \"Hello, World!\" \n\nAn example of the second:\n\n\tdoer op\n\n\t: sum \\ n0 ... nX X -- sum<0..X> \n\t\tmake op + 1 do op loop ;\n\n\t: mul \\ n0 ... nX X -- mul<0..X> \n\t\tmake op * 1 do op loop ;\n\nThe above example is a bit contrived, the definitions and functionality\nare too simple for this to be worth factoring out, but it shows how you\ncan use DOER\/MAKE. )\n\n: noop ; ( -- : default word to execute for doer, does nothing )\n\n: doer ( c\" xxx\" -- : make a work whose behavior can be changed by make )\n\timmediate ?exec :: ['] noop , postpone ; ;\n\n: found? ( xt -- xt : thrown an exception if the execution token is zero [not found] ) \n\tdup 0= if -13 throw then ;\n\n( It would be nice to provide a MAKE that worked with execution tokens\nas well, although \"defer\" and \"is\" can be used for that. MAKE expects\ntwo word names to be given as arguments. It will then change the behavior \nof the first word to use the second. MAKE is a state aware word. )\n\n: make immediate ( c1\" xxx\" c2\" xxx\" : change parsed word c1 to execute c2 )\n\tfind found? cell+\n\tfind found?\n\tstate @ if ( compiling )\n\t\tswap postpone 2literal ['] ! ,\n\telse ( command mode )\n\t\tswap !\n\tthen ;\n\nhide noop ( noop! noop! )\n\n( ========================== DOER\/MAKE ======================================= )\n\n( ========================== Extended Word Set =============================== )\n\n: log ( u base -- u : command the _integer_ logarithm of u in base )\n\t>r \n\tdup 0= if -11 throw then ( logarithm of zero is an error )\n\t0 swap\n\tbegin\n\t\tnos1+ rdup r> \/ dup 0= ( keep dividing until 'u' is zero )\n\tuntil\n\tdrop 1- rdrop ;\n\n: log2 ( u -- u : compute the _integer_ logarithm of u )\n\t2 log ;\n\n: time ( \" ccc\" -- n : time the number of milliseconds it takes to execute a word )\n\tclock >r\n\tfind execute\n\tclock r> - ;\n\n( defer...is is probably not standards compliant, it is still neat! )\n: (do-defer) ( -- self : pushes the location into which it is compiled )\n\tr> dup >r 1- ;\n\n: defer immediate ( \" ccc\" -- , Run Time -- location : \n\tcreates a word that pushes a location to write an execution token into )\n\t?exec\n\t:: ' (do-defer) , postpone ; ;\n\n: is ( location \" ccc\" -- : make a deferred word execute a word ) \n\tfind found? swap ! ;\n\nhide (do-defer)\nhide found?\n\n( The \"tail\" function implements tail calls, which is just a jump\nto the beginning of the words definition, for example this\nword will never overflow the stack and will print \"1\" followed\nby a new line forever,\n\n\t: forever 1 . cr tail ;\n\nWhereas\n\n\t: forever 1 . cr recurse ;\n\nor\n\n\t: forever 1 . cr forever ;\n\nWould overflow the return stack. )\n\nhide tail\n: tail ( -- : perform tail recursion in current word definition )\n\timmediate\n\t?comp\n\tlatest cell+\n\t' branch ,\n\there - cell+ , ;\n\n: recurse immediate\n\t( This function implements recursion, although this interpreter\n\tallows calling a word directly. If used incorrectly this will\n\tblow up the return stack.\n\n\tWe can test \"recurse\" with this factorial function:\n\t : factorial dup 2 < if drop 1 exit then dup 1- recurse * ; )\n\t?comp\n\tlatest cell+ , ;\n\n: factorial ( x -- x : compute the factorial of a number )\n\tdup 2 < if drop 1 exit then dup 1- recurse * ;\n\n: myself ( -- : myself is a synonym for recurse ) \n\timmediate postpone recurse ;\n\n: gcd ( x1 x2 -- x : greatest common divisor )\n\tdup if tuck mod tail then drop ;\n\n( ========================== Extended Word Set =============================== )\n\n( ========================== For Each Loop =================================== )\n\n( The foreach word set allows the user to take action over an entire array\nwithout setting up loops and checking bounds. It behaves like the foreach loops\nthat are popular in other languages. \n\nThe foreach word accepts a string and an execution token, for each character\nin the string it passes the current address of the character that it should\noperate on. \n\nThe complexity of the foreach loop is due to the requirements placed on it.\nIt cannot pollute the variable stack with values it needs to operate on, and\nit cannot store values in local variables as a foreach loop could be called\nfrom within the execution token it was passed. It therefore has to store all\nof it uses on the return stack for the duration of EXECUTE.\n\nAt the moment it only acts on strings as \"\/string\" only increments the address \npassed to the word foreach executes to the next character address. )\n\n\\ (FOREACH) leaves the point at which the foreach loop terminated on the stack,\n\\ this allows programmer to determine if the loop terminated early or not, and\n\\ at which point.\n: (foreach) ( c-addr u xt -- c-addr u : execute xt for each cell in c-addr u \n\treturning number of items not processed )\n\tbegin \n\t\t3dup >r >r >r ( c-addr u xt R: c-addr u xt )\n\t\tnip ( c-addr xt R: c-addr u xt )\n\t\texecute ( R: c-addr u xt )\n\t\tr> r> r> ( c-addr u xt )\n\t\t-rot ( xt c-addr u )\n\t\t1 \/string ( xt c-addr u )\n\t\tdup 0= if rot drop exit then ( End of string - drop and exit! )\n\t\trot ( c-addr u xt )\n\tagain ;\n\n\\ If we do not care about returning early from the foreach loop we\n\\ can instead call FOREACH instead of (FOREACH), it simply drops the\n\\ results (FOREACH) placed on the stack.\n: foreach ( c-addr u xt -- : execute xt for each cell in c-addr u )\n\t(foreach) 2drop ;\n\n\\ RETURN is used for an early exit from within the execution token, it\n\\ leaves the point at which it exited \n: return ( -- n : return early from within a foreach loop function, returning number of items left )\n\trdrop ( pop off this words return value )\n\trdrop ( pop off the calling words return value )\n\trdrop ( pop off the xt token )\n\tr> ( save u )\n\tr> ( save c-addr )\n\trdrop ; ( pop off the foreach return value )\n\n\\ SKIP is an example of a word that uses the foreach loop mechanism. It\n\\ takes a string and a character and returns a string that starts at\n\\ the first occurrence of that character in that string - or until it\n\\ reaches the end of the string.\n\n\\ SKIP is defined in two steps, first there is a word, (SKIP), that\n\\ exits the foreach loop if there is a match, if there is no match it\n\\ does nothing. In either case it leaves the character to skip until\n\\ on the stack.\n\n: (skip) ( char c-addr -- char : exit out of foreach loop if there is a match )\n\tover swap c@ = if return then ;\n\n\\ SKIP then setups up the foreach loop, the char argument will present on the\n\\ stack when (SKIP) is executed, it must leave a copy on the stack whatever\n\\ happens, this is then dropped at the end. (FOREACH) leaves the point at\n\\ which the loop terminated on the stack, which is what we want.\n: skip ( c-addr u char -- c-addr u : skip until char is found or until end of string )\n\t-rot ['] (skip) (foreach) rot drop ;\nhide (skip)\n\n( ========================== For Each Loop =================================== )\n\n( The words described here on out get more complex and will require more\nof an explanation as to how they work. )\n\n( ========================== CREATE DOES> ==================================== )\n\n( The following section defines a pair of words \"create\" and \"does>\" which\nare a powerful set of words that can be used to make words that can create\nother words. \"create\" has both run time and compile time behavior, whilst\n\"does>\" only works at compile time in conjunction with \"create\". These two\nwords can be used to add constants, variables and arrays to the language,\namongst other things.\n\nA simple version of create is as follows\n\n\t: create :: dolist , here 2 cells + , ' exit , 0 state ! ;\n\nBut this version is much more limited.\n\n\"create\"...\"does>\" is one of the constructs that makes Forth Forth, it\nallows the creation of words which can define new words in themselves,\nand thus allows us to extend the language easily.\n)\n\n: write-quote ( -- : A word that writes ' into the dictionary )\n\t['] ' , ; \n\n: write-exit ( -- : A word that write exit into the dictionary )\n\t['] _exit , ;\n\n: write-compile, ( -- : A word that writes , into the dictionary ) \n\t' , , ;\n\n: command-mode ( -- : put the interpreter into command mode )\n\tfalse state ! ;\n\n: command-mode-create ( create a new work that pushes its data field )\n\t:: ( compile a word )\n\tdolit , ( write push into new word )\n\there 2 cells + , ( push a pointer to data field )\n\tpostpone ; ; ( write exit and switch to command mode )\n\n: mark write-compile, ( Write in a place holder 0 and push a pointer to to be used by does> )\n\twrite-quote write-exit write-compile, ( Write in an exit in the word we're compiling. )\n\t['] command-mode , ; ( Make sure to change the state back to command mode )\n\n: create immediate ( create word is quite a complex forth word )\n\tstate @ \n\tif \n\t\tpostpone ( hole-to-patch -- )\n\timmediate\n\t?comp\n\twrite-exit ( we don't want the defining word to exit, but the *defined* word to )\n\there swap ! ( patch in the code fields to point to )\n\tdolist , ; ( write a run in )\n\nhide write-quote\nhide write-compile,\nhide write-exit\n\n( Now that we have create...does> we can use it to create arrays, variables\nand constants, as we mentioned before. )\n\n: array ( u c\" xxx\" -- : create a named array of length u )\n\tcreate allot does> + ;\n\n: variable ( x c\" xxx\" -- : create a variable will initial value of x )\n\tcreate , does> ;\n\n\\ : constant ( x c\" xxx\" -- : create a constant with value of x ) \n\\\tcreate , does> @ ;\n\n: table ( u c\" xxx\" --, Run Time: -- addr u : create a named table )\n\tcreate dup , allot does> dup @ ;\n\n: string ( u c\" xxx\" --, Run Time: -- c-addr u : create a named string )\n\tcreate dup , chars allot does> dup @ swap 1+ chars> swap ;\n\n\\ : +field \\ n <\"name\"> -- ; exec: addr -- 'addr\n\\ create over , +\n\\ does> @ + ;\n\\ \n\\ : begin-structure \\ -- addr 0 ; -- size\n\\ \tcreate\n\\ \there 0 0 , \\ mark stack, lay dummy\n\\ \tdoes> @ ; \\ -- rec-len\n\\ \n\\ : end-structure \\ addr n --\n\\ swap ! ; \\ set len \n\\ \n\\ begin-structure point\n\\ \tpoint +field p.x\n\\ \tpoint +field p.y\n\\ end-structure\n\\ \n\\ This should work...\n\\ : buffer: ( u c\" xxx\" --, Run Time: -- addr )\n\\\tcreate allot ;\n\n: 2constant \n\tcreate , , does> dup 1+ @ swap @ ;\n\n: 2variable \n\tcreate , , does> ;\n\n: enum ( x \" ccc\" -- x+1 : define a series of enumerations )\n\tdup constant 1+ ; \n\n( ========================== CREATE DOES> ==================================== )\n\n( ========================== DO...LOOP ======================================= )\n\n( The following section implements Forth's do...loop constructs, the\nword definitions are quite complex as it involves a lot of juggling of\nthe return stack. Along with begin...until do loops are one of the\nmain looping constructs. \n\nUnlike begin...until do accepts two values a limit and a starting value,\nthey are also words only to be used within a word definition, some Forths\nextend the semantics so looping constructs operate in command mode, this\nForth does not do that as it complicates things unnecessarily.\n\nExample:\n\t\n\t: example-1 10 1 do i . i 5 > if cr leave then loop 100 . cr ; \n\texample-1\n\nPrints:\n\t1 2 3 4 5 6\n\nIn \"example-1\" we can see the following:\n\n1. A limit, 10, and a start value, 1, passed to \"do\".\n2. A word called 'i', which is the current count of the loop\n3. If the count is greater than 5, we call a word call 'leave', this\nword exits the current loop context as well as the current calling\nword.\n4. \"100 . cr\" is never called. This should be changed in future\nrevision, but this version of leave exits the calling word as well.\n\n'i', 'j', and 'leave' *must* be used within a do...loop construct. \n\nIn order to remedy point 4. loop should not use branch but instead \nshould use a value to return to which it pushes to the return stack )\n\n: (do)\n\tswap ( swap the limit and start )\n\tr> ( save our return stack to temporary variable )\n\t-rot ( limit start return -- return start limit )\n\t>r ( push limit onto return stack )\n\t>r ( push start onto return stack )\n\t>r ; ( restore our return address )\n\n: do immediate ( Run time: high low -- : begin do...loop construct )\n\t?comp\n\t' (do) ,\n\tpostpone begin ; \n\n: (unloop) ( -- , R: i limit -- : remove limit and i from )\n\tr> ( save our return address )\n\trdrop ( pop off i )\n\trdrop ( pop off limit )\n\t>r ; ( restore our return stack )\n\n: (+loop) ( x -- bool : increment loop variable by x and test it )\n\tr@ 1- ( get the pointer to i )\n\t+! ( add value to it )\n\tr@ 1- @ ( find i again )\n\tr@ 2- @ ( find the limit value )\n\tu>= ;\n\n: (loop) ( -- bool : increment loop variable by 1 and test it )\n\tr@ 1- ( get the pointer to i )\n\t1+! ( add one to it )\n\tr@ 1- @ ( find the value again )\n\tr@ 2- @ ( find the limit value )\n\tu>= ;\n\n: loop ( -- : end do...loop construct )\n\timmediate ?comp ' (loop) , postpone until ' (unloop) , ;\n\n: +loop ( x -- : end do...+loop loop construct )\n\timmediate ?comp ' (+loop) , postpone until ' (unloop) , ;\n\n: leave ( -- , R: i limit return -- : break out of a do-loop construct )\n\t(unloop)\n\trdrop ; ( return to the caller's caller routine )\n\n: ?leave ( x -- , R: i limit return -- | i limit return : conditional leave )\n\tif\n\t\t(unloop)\n\t\trdrop ( return to the caller's caller routine )\n\tthen ;\n\n: i ( -- i : Get current, or innermost, loop index in do...loop construct )\n\tr> r> ( pop off return address and i )\n\ttuck ( tuck i away )\n\t>r >r ; ( restore return stack )\n\n: j ( -- j : Get outermost loop index in do...loop construct )\n\t4 rpick ;\n\n( This is a simple test function for the looping, for interactive\ntesting and debugging:\n : mm 5 1 do i . cr 4 1 do j . tab i . cr loop loop ; )\n\n: range ( nX nY -- nX nX+1 ... nY ) \n\tnos1+ do i loop ;\n\n: repeater ( n0 X -- n0 ... nX ) \n\t1 do dup loop ;\n\n: sum ( n0 ... nX X -- sum<0..X> ) \n\t1 do + loop ;\n\n: mul ( n0 ... nX X -- mul<0..X> ) \n\t1 do * loop ;\n\n: reverse ( x1 ... xn n -- xn ... x1 : reverse n items on the stack )\n\t0 do i roll loop ;\n\n( ========================== DO...LOOP ======================================= )\n\n0 variable column-counter\n4 variable column-width\n\n: column ( i -- )\t\n\tcolumn-width @ mod not if cr then ;\n\n: column.reset\t\t\n\t0 column-counter ! ;\n\n: auto-column\t\t\n\tcolumn-counter dup @ column 1+! ;\n\n: alignment-bits \n\t[ 1 size log2 lshift 1- literal ] and ;\n\n0 variable x\n: x! ( x -- ) \n\tx ! ;\n\n: x@ ( -- x ) \n\tx @ ;\n\n: 2>r ( x1 x2 -- R: x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tswap\n\t\t>r\n\t\t>r\n\tx@ >r ; ( restore return address )\n\n: 2r> ( R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tr>\n\t\tr>\n\t\tswap\n\tx@ >r ; ( restore return address )\n\n: 2r@ ( -- x1 x2 , R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\tr> r>\n\t2dup\n\t>r >r\n\tswap\n\tx@ >r ; ( restore return address )\n\n: unused ( -- u : push the amount of core left ) \n\tmax-core here - ;\n\n: accumulator ( initial \" ccc\" -- : make a word that increments by a value and pushes the result )\n\tcreate , does> tuck +! @ ;\n\n: counter ( \" ccc\" --, Run Time: -- x : make a word that increments itself by one, starting from zero )\n\tcreate -1 , does> dup 1+! @ ;\n\n0 variable delim\n: accepter ( c-addr max delimiter -- i )\n\t( store a \"max\" number of chars at c-addr until \"delimiter\" encountered,\n\tthe number of characters stored is returned )\n\tdelim ! ( store delimiter used to stop string storage when encountered)\n\t0\n\tdo\n\t\tkey dup delim @ <>\n\t\tif\n\t\t\tover c! 1+\n\t\telse ( terminate string )\n\t\t\tdrop 0 swap c! \n\t\t\ti \n\t\t\tleave\n\t\tthen\n\tloop\n\t-18 throw ; ( read in too many chars )\nhide delim\n\n: skip ( char -- : read input until string is reached )\n\tkey drop >r 0 begin drop key dup rdup r> <> until rdrop ;\n\n: word ( c -- c-addr : parse until 'c' is encountered, push transient counted string )\n\tdup skip chere 1+ c!\n\t>r\n\tchere 2+\n\tpad here - chars>\n\tr> accepter 1+\n\tchere c!\n\tchere ;\nhide skip\n\n: accept ( c-addr +n1 -- +n2 : see accepter definition ) \n\tnl accepter ;\n\n: (subst) ( char1 char2 c-addr )\n\t3dup ( char1 char2 c-addr char1 char2 c-addr )\n\tc@ = if ( char1 char2 c-addr char1 )\n\t\tswap c! ( match, substitute character )\n\telse ( char1 char2 c-addr char1 )\n\t\t2drop ( no match )\n\tthen ;\n\n: subst ( c-addr u char1 char2 -- replace all char1 with char2 in string )\n\tswap\n\t2swap\n\t['] (subst) foreach 2drop ;\nhide (subst)\n\n0xFFFF constant max-string-length\n\n: (.\") ( char -- c-addr u )\n\t( @todo This really needs simplifying, to do this\n\ta set of words that operate on a temporary buffer can\n\tbe used )\n\t( Write a string into word being currently defined, this\n\tcode has to jump over the string it has just put into the\n\tdictionary so normal execution of a word can continue. The\n\tlength and character address of the string are left on the\n\tstack )\n\t>r ( save delimiter )\n\t' branch , ( write in jump, this will jump past the string )\n\t>mark ( make hole )\n\tdup 1+ chars> ( calculate address to write to )\n\tmax-string-length \n\tr> ( restore delimiter )\n\taccepter dup >r ( write string into dictionary, save index )\n\taligned 2dup size \/ ( stack: length hole char-len hole )\n\t1+ dup allot ( update dictionary pointer with string length )\n\t1+ swap ! ( write place to jump to )\n\tdrop ( do not need string length anymore )\n\t1+ chars> ( calculate place to print )\n\tr> ; ( restore index and address of string )\n\n: length ( c-addr u -- u : push the length of an ASCIIZ string )\n tuck 0 do dup c@ 0= if 2drop i leave then 1+ loop ;\n\n: asciiz? ( c-addr u -- : is a Forth string also a ASCIIZ string )\n\ttuck length <> ;\n\n: asciiz ( c-addr u -- : trim a string until NUL terminator )\n\t2dup length nip ;\n\n\n: (type) ( c-addr -- ) \n\tc@ emit ;\n\n: type ( c-addr u -- : print out 'u' characters at c-addr )\n\t['] (type) foreach ;\nhide (type)\n\n: do-string ( char -- : write a string into the dictionary reading it until char is encountered )\n\t(.\") \n\tstate @ if swap [literal] [literal] then ;\n\n: fill ( c-addr u char -- : fill in an area of memory with a character, only if u is greater than zero )\n\t-rot\n\t0 do 2dup i + c! loop\n\t2drop ;\n\n: compare ( c-addr1 u1 c-addr2 u2 -- n : compare two strings, not quite compliant yet )\n\t>r swap r> min >r\n\tstart-address + swap start-address + r>\n\tmemory-compare ;\n\n128 string sbuf\n: s\" ( \"ccc\" --, Run Time -- c-addr u )\n\tkey drop sbuf 0 fill sbuf [char] \" accepter sbuf drop swap ;\nhide sbuf\n\n( @todo these strings really need rethinking, state awareness needs to be removed... )\n: type, \n\tstate @ if ' type , else type then ;\n\n: c\" \n\timmediate key drop [char] \" do-string ;\n\n: \" \n\timmediate key drop [char] \" do-string type, ;\n\n: sprint ( c -- : print out chars until 'c' is encountered )\n\tkey drop ( drop next space )\n\t>r ( save delimiter )\n\tbegin\n\t\tkey dup ( get next character )\n\t\trdup r> ( get delimiter )\n\t\t<> if emit 0 then\n\tuntil rdrop ;\n\n: .( \n\timmediate [char] ) sprint ;\nhide sprint\n\n: .\" \n\timmediate key drop [char] \" do-string type, ;\n\nhide type,\n\n( This word really should be removed along with any usages of this word, it\nis not a very \"Forth\" like word, it accepts a pointer to an ASCIIZ string and\nprints it out, it also does not checking of the returned values from write-file )\n: print ( c-addr -- : print out a string to the standard output )\n\t-1 over >r length r> swap stdout write-file 2drop ;\n\n: ok \n\t\" ok\" cr ;\n\n: empty-stack ( x-n ... x-0 -- : empty the variable stack )\n\tbegin depth while drop repeat ;\n\n: (quit) ( -- : do the work of quit, without the restart )\n\t0 `source-id ! ( set source to read from file )\n\t`stdin @ `fin ! ( read from stdin )\n\tpostpone [ ( back into command mode )\n\t' interpret start! ; ( set interpreter starting word )\n\n: quit ( -- : Empty return stack, go back to command mode, read from stdin, interpret input )\n\t(quit)\n\t-1 restart ; ( restart the interpreter )\n\n: abort\n\t-1 throw ;\n\n: (abort\") ( do the work of abort )\n\t(quit)\n\t-2 throw ;\n\n: abort\" immediate \n\tpostpone \"\n\t' cr , ' (abort\") , ;\n\n( ==================== CASE statements ======================== )\n( This simple set of words adds case statements to the interpreter,\nthe implementation is not particularly efficient, but it works and\nis simple.\n\nBelow is an example of how to use the CASE statement, the following\nword, \"example\" will read in a character and switch to different\nstatements depending on the character input. There are two cases,\nwhen 'a' and 'b' are input, and a default case which occurs when\nnone of the statements match:\n\n\t: example\n\t\tchar \n\t\tcase\n\t\t\t[char] a of \" a was selected \" cr endof\n\t\t\t[char] b of \" b was selected \" cr endof\n\n\t\t\tdup \\ encase will drop the selector\n\t\t\t\" unknown char: \" emit cr\n\t\tendcase ;\n\n\texample a \\ prints \"a was selected\"\n\texample b \\ prints \"b was selected\"\n\texample c \\ prints \"unknown char: c\"\n\nOther examples of how to use case statements can be found throughout \nthe code. \n\nFor a simpler case statement see, Volume 2, issue 3, page 48 \nof Forth Dimensions at http:\/\/www.forth.org\/fd\/contents.html )\n\n: case immediate\n\t?comp\n\t' branch , 3 , ( branch over the next branch )\n\there ' branch , ( mark: place endof branches back to with again )\n\t>mark swap ; ( mark: place endcase writes jump to with then )\n\n: over= ( x y -- [x 0] | 1 : )\n\tover = if drop 1 else 0 then ;\n\n: of\n\timmediate ?comp ' over= , postpone if ;\n\n: endof\n\timmediate ?comp over postpone again postpone then ;\n\n: endcase\n\timmediate ?comp ' drop , 1+ postpone then drop ;\n\n( ==================== CASE statements ======================== )\n\n( ==================== Hiding Words =========================== )\n\n: }hide ( should only be matched with 'hide{' )\n\timmediate -22 throw ;\n\n: hide{ ( -- : hide a list of words, the list is terminated with \"}hide\" )\n\t?exec\n\tbegin\n\t\tfind ( find next word )\n\t\tdup [ find }hide ] literal = if\n\t\t\tdrop exit ( terminate hide{ )\n\t\tthen\n\t\tdup 0= if -15 throw then\n\t\t(hide) drop\n\tagain ;\n\nhide (hide)\n\n( ==================== Hiding Words =========================== )\n\n: spaces ( n -- : print n spaces ) \n\t0 do space loop ;\n\n: erase ( addr u : erase a block of memory )\n\t2chars> 0 fill ;\n\n: blank ( c-addr u : fills a string with spaces )\n\tbl fill ;\n\n( move should check that u is not negative )\n: move ( addr1 addr2 u -- : copy u words of memory from 'addr2' to 'addr1' )\n\t0 do\n\t\t2dup i + @ swap i + !\n\tloop\n\t2drop ;\n\n( It would be nice if move and cmove could share more code, as they do exactly\n the same thing but with different load and store functions, cmove> )\n: cmove ( c-addr1 c-addr2 u -- : copy u characters of memory from 'c-addr2' to 'c-addr1' )\n\t0 do\n\t\t2dup i + c@ swap i + c!\n\tloop\n\t2drop ;\n\n( ==================== Conditional Compilation ================ )\n\n( The words \"[if]\", \"[else]\" and \"[then]\" implement conditional compilation,\nthey can be nested as well\n\nSee http:\/\/lars.nocrew.org\/dpans\/dpans15.htm for more information\n\nA much simpler conditional compilation method is the following\nsingle word definition:\n\n : compile-line? 0= if [ find \\\\ , ] then ;\n\nWhich will skip a line if a conditional is false, and compile it\nif true )\n\n( These words really, really need refactoring, I could use the newly defined \n \"defer\" to help out with this )\n0 variable nest ( level of [if] nesting )\n0 variable [if]-word ( populated later with \"find [if]\" )\n0 variable [else]-word ( populated later with \"find [else]\")\n: [then] immediate ;\n: reset-nest 1 nest ! ;\n: unnest? [ find [then] ] literal = if nest 1-! then ;\n: nest? [if]-word @ = if nest 1+! then ;\n: end-nest? nest @ 0= ;\n: match-[else]? [else]-word @ = nest @ 1 = and ;\n\n: [if] ( bool -- : conditional execution )\n\tunless\n\t\treset-nest\n\t\tbegin\n\t\t\tfind\n\t\t\tdup nest?\n\t\t\tdup match-[else]? if drop exit then\n\t\t\t unnest?\n\t\t\tend-nest?\n\t\tuntil\n\tthen ;\n\n: [else] ( discard input until [then] encounter, nesting for [if] )\n\treset-nest\n\tbegin\n\t\tfind\n\t\tdup nest? unnest?\n\t\tend-nest?\n\tuntil ;\n\nfind [if] [if]-word !\nfind [else] [else]-word !\n\n: ?( if postpone ( then ; \\ conditionally read until ')'\n: ?\\ if postpone \\ then ;\n: 16bit\\ size 2 <> if postpone \\ then ;\n: 32bit\\ size 4 <> if postpone \\ then ;\n: 64bit\\ size 8 <> if postpone \\ then ;\n\nhide{ \n\t[if]-word [else]-word nest \n\treset-nest unnest? match-[else]? \n\tend-nest? nest? \n}hide\n\n( ==================== Conditional Compilation ================ )\n\n( ==================== Endian Words =========================== )\n\nsize 2 = [if] 0x0123 `x ! [then]\nsize 4 = [if] 0x01234567 `x ! [then]\nsize 8 = [if] 0x01234567abcdef `x ! [then]\n\n: endian ( -- bool : returns the endianess of the processor, little = 0, big = 1 )\n\t[ `x chars> c@ 0x01 = ] literal ;\n\n: swap16 ( x -- x : swap the byte order a 16 bit number )\n\tdup 256* 0xff00 and >r 256\/ lsb r> or ;\n\nsize 4 >= [if] \n\t: swap32 \n\t\tdup 0xffff and swap16 16 lshift swap\n\t\t16 rshift 0xffff and swap16 or ;\n[then]\n\nsize 8 >= [if]\n\t: swap64 ( x -- x : swap the byte order of a 64 bit number )\n\t\t dup 0xffffffff and swap32 32 lshift swap\n\t\t 32 rshift 0xffffffff and swap32 or ;\n[then]\n\nsize 2 = [if]\n\tendian \n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\tswap16 ;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\t;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\tswap16 ;\n\t[then]\n[then]\n\nsize 4 = [if]\n\tendian \n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\tswap32 ;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\t;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\tswap32 ;\n\t[then]\n[then]\n\nsize 8 = [if]\n\tendian \n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\tswap64 ;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order ) \n\t\t;\n\t: >big ( x -- x : host byte order to big endian order ) \n\t\tswap64 ;\n\t[then]\n[then]\n\n( ==================== Endian Words =========================== )\n\n( ==================== Misc words ============================= )\n\n: (base) ( -- base : unmess up libforth's base variable )\n\tbase @ 0= if 10 else base @ then ;\n\n: #digits ( u -- u : number of characters needed to represent 'u' in current base )\n\tdup 0= if 1+ exit then\n\t(base) log 1+ ;\n\n: digits ( -- u : number of characters needed to represent largest unsigned number in current base )\n\t-1 #digits ;\n\n: print-number ( u -- print a number taking up a fixed amount of space on the screen )\n\tbase @ 16 = if . exit then ( @todo this is a hack related to libforth printing out hex specially)\n\tdup #digits digits swap - dup 0<> if spaces else drop then . ;\n\n: address ( u -- : print out and address )\n\t@ print-number ;\n\n0 variable counter\n\n: counted-column ( index -- : special column printing for dump )\n\tcounter @ column-width @ mod\n\tnot if cr print-number \" :\" space else drop then\n\tcounter 1+! ;\n\n: as-chars ( x n -- : print a cell out as characters, upto n chars )\n\t0 ( from zero to the size of a cell )\n\tdo\n\t\tdup ( copy variable to print out )\n\t\tsize i 1+ - select-byte ( select correct byte )\n\t\tdup printable? not ( is it not printable )\n\t\tif drop [char] . then ( print a '.' if it is not )\n\t\temit ( otherwise print it out )\n\tloop\n\tspace ( print out space after )\n\tdrop ; ( drop cell we have printed out )\n\n: lister ( addr u addr -- )\n\t0 counter ! 1- swap \n\tdo \n\t\tdup counted-column 1+ i address i @ size as-chars \n\tloop ;\n\n( @todo this function should make use of 'defer' and 'is', then different\nversion of dump could be made that swapped out 'lister' )\n: dump ( addr u -- : dump out 'u' cells of memory starting from 'addr' )\n\t1+ over + under lister drop \n\tcr ;\n\nhide{ counted-column counter as-chars address print-number }hide\n\n( Fence can be used to prevent any word defined before it from being forgotten \nUsage:\n\there fence ! )\n0 variable fence\n\n: (forget) ( pwd-token -- : forget a found word and everything after it )\n\tdup 0= if -15 throw then ( word not found! )\n\tdup fence @ u< if -15 throw then ( forgetting a word before fence! )\n\tdup @ pwd ! h ! ;\n\n: forget ( c\" xxx\" -- : forget word and every word defined after it )\n\tfind 1- (forget) ;\n\n: marker ( c\" xxx\" -- : make word the forgets itself and words after it)\n\t:: latest [literal] ' (forget) , postpone ; ;\nhere fence ! ( This should also be done at the end of the file )\nhide (forget)\n\n: ** ( b e -- x : exponent, raise 'b' to the power of 'e')\n\t?dup-if\n\t\tover swap\n\t\t1 do over * loop \n\t\tnip\n\telse\n\t\tdrop 1\n\tendif ;\n\n0 variable a\n0 variable b\n0 variable m\n: equal ( a1...an b1...bn n -- a1...an b1...bn bool : determine if two lists are equal )\n\t( example: \n\t\t1 2 3 \n\t\t1 2 3 \n\t\t3 equal \n\treturns: 1 )\n\tdup m ! 1+ 1 ( store copy of length and use as loop index )\n\tdo \n\t\ti 1- pick b ! ( store ith element of list in b1...bn )\n\t\ti m @ + 1- pick a ! ( store ith element of list in a1...an )\n\t\ta @ b @ <> ( compare a and b for equality )\n\t\tif 0 leave then ( unequal, finish early )\n\tloop 1 ; ( lists must be equal )\n\nhide{ a b m }hide\n\n: ndrop ( drop n items )\n\t?dup-if 0 do drop loop then ;\n\n: caesar ( c key -- o : encode a alphabetic character with a key using a generalization of the Caesar cipher )\n\t>r\n\tdup uppercase? if [char] A - r> + 26 mod [char] A + exit then\n\tdup lowercase? if [char] a - r> + 26 mod [char] a + exit then\n\trdrop ; ( it goes without saying that this should not be used for anything serious! )\n\n: caesar-type ( c-addr u key : type out encoded text with a Caesar cipher )\n\t-rot bounds do i c@ over caesar emit loop drop ;\n\n: rot13 ( c -- c : encode a character with ROT-13 )\n\t13 caesar ;\n\n: rot13-type ( c-addr u : print string in ROT-13 encoded form )\n\t13 caesar-type ;\n\n\\ s\" abcdefghijklmnopqrstuvwxyz\" rot13-type -> nopqrstuvwxyzabcdefghijklm\n\\ s\" hello\" rot13-type -> uryyb\n\n( ==================== Misc words ============================= )\n\n( ==================== Pictured Numeric Output ================ )\n( Pictured numeric output is what Forths use to display numbers\nto the screen, this Forth has number output methods built into\nthe Forth kernel and mostly uses them instead, but the mechanism\nis still useful so it has been added.\n\n@todo Pictured number output should act on a double cell number\nnot a single cell number )\n\n0 variable hld\n\n: overflow ( -- : check if we overflow the hold area )\n \there chars> pad chars> hld @ - u> if -17 throw then ;\n\n: hold ( char -- : add a character to the numeric output string )\n\toverflow pad chars> hld @ - c! hld 1+! ;\n\n: holds ( addr u -- )\n begin dup while 1- 2dup + c@ hold repeat 2drop ;\n\n: nbase ( -- base : in this forth 0 is a special base, push 10 is base is zero )\n\tbase @ dup 0= if drop 10 then ;\n\n: <# ( -- : setup pictured numeric output )\n\t0 hld ! ;\n\n: sign ( -- : add a sign to the pictured numeric output string )\n\t[char] - hold ;\n\n: # ( x -- x : divide x by base, turn into a character, put in pictured output string )\n\tnbase um\/mod swap \n \tdup 9 u>\n \tif 7 + then\n \t48 + hold ;\n\n: #s ( x -- 0 : repeatedly call # on x until x is zero )\n\tbegin # dup 0= until ; \n\n: #> ( -- c-addr u : end pictured output conversion, push output string to stack )\n\t0 hold ( NUL terminate string, just in case )\n\thld 1-! ( but do not include that in the count )\n\tpad chars> hld @ \n\ttuck - 1+ swap ;\n\n: u. ( u -- : display number in base 10 )\n\tbase @ >r decimal <# #s #> type drop r> base ! ;\n\nhide{ nbase overflow }hide\n\n( ==================== Pictured Numeric Output ================ )\n\n( ==================== Numeric Input ========================= )\n( The Forth executable can handle numeric input and does not need\nthe routines defined here, however the user might want to write\nroutines that use >NUMBER. >NUMBER is a generic word, but it\nis a bit difficult to use on its own. )\n\n: map ( char -- n|-1 : convert character in 0-9 a-z range to number )\n\tdup lowercase? if [char] a - 10 + exit then\n\tdup decimal? if [char] 0 - exit then\n\tdrop -1 ;\n\n: number? ( char -- bool : is a character a number in the current base )\n\t>lower map (base) u< ;\n\n: >number ( n c-addr u -- n c-addr u : convert string )\n\tbegin\n\t\t( get next character )\n\t\t2dup >r >r drop c@ dup number? ( n char bool, R: c-addr u )\n\t\tif ( n char )\n\t\t\tswap (base) * swap map + ( accumulate number )\n\t\telse ( n char )\n\t\t\tdrop\n\t\t\tr> r> ( restore string )\n\t\t\texit\n\t\tthen\n\t\tr> r> ( restore string )\n\t\t1 \/string dup 0= ( advance string and test for end )\n\tuntil ;\n\nhide{ map }hide\n\n( ==================== Numeric Input ========================= )\n\n( ==================== ANSI Escape Codes ====================== )\n( Terminal colorization module, via ANSI Escape Codes\n \nsee: https:\/\/en.wikipedia.org\/wiki\/ANSI_escape_code\nThese codes will provide a relatively portable means of\nmanipulating a terminal )\n\n27 constant 'escape'\n: CSI 'escape' emit .\" [\" ;\n0 constant black\n1 constant red\n2 constant green\n3 constant yellow\n4 constant blue\n5 constant magenta\n6 constant cyan\n7 constant white\n: foreground 30 + ;\n: background 40 + ;\n0 constant dark\n1 constant bright\nfalse variable colorize \n\n: color ( brightness color-code -- : set the terminal color )\n\t( set color on an ANSI compliant terminal,\n\tfor example:\n\t\tbright red foreground color\n\tsets the foreground text to bright red )\n\tcolorize @ 0= if 2drop exit then \n\tCSI u. if .\" ;1\" then .\" m\" ;\n\n: at-xy ( x y -- : set ANSI terminal cursor position to x y )\n\tCSI u. [char] ; emit u. .\" H\" ;\n\n: page ( -- : clear ANSI terminal screen and move cursor to beginning ) \n\tCSI .\" 2J\" 1 1 at-xy ;\n\n: hide-cursor ( -- : hide the cursor from view ) \n\tCSI .\" ?25l\" ;\n\n: show-cursor ( -- : show the cursor ) \n\tCSI .\" ?25h\" ;\n\n: save-cursor ( -- : save cursor position ) \n\tCSI .\" s\" ;\n\n: restore-cursor ( -- : restore saved cursor position ) \n\tCSI .\" u\" ;\n\n: reset-color ( -- : reset terminal color to its default value)\n\tcolorize @ 0= if exit then\n\tCSI .\" 0m\" ;\n\nhide{ CSI }hide\n( ==================== ANSI Escape Codes ====================== )\n\n( ==================== Unit test framework =================== )\n\n256 string estring ( string to test )\n0 variable #estring ( actual string length )\n0 variable start ( starting depth )\n0 variable result ( result depth )\n0 variable check ( only check depth if -> is called )\n0 variable dictionary ( dictionary pointer on entering { )\n0 variable previous ( PWD register on entering { )\n\n: T ; ( hack until T{ can process words )\n\n: -> ( -- : save depth in variable ) \n\t1 check ! depth result ! ; \n\n: test estring drop #estring @ ; \n\n: fail ( -- : invalidate the forth interpreter and exit )\n\tinvalidate bye ;\n\n: neutral ( -- : neutral color )\n\t;\n\n: bad ( -- : bad color )\n\tdark red foreground color ;\n\n: good ( -- : good color )\n\tdark green foreground color ;\n\n: die bad test type reset-color cr fail ;\n\n: evaluate? ( bool -- : test if evaluation has failed )\n\tif .\" evaluation failed\" cr fail then ;\n\n: failed bad .\" failed\" reset-color cr ;\n\n: adjust ( x -- x : adjust a depth to take into account starting depth ) \n\tstart @ - ;\n\n: no-check? ( -- bool : if true we need to check the depth )\n\tcheck @ 0= ;\n\n: depth? ( -- : check if depth is correct )\n\tno-check? if exit then\n\tdepth adjust ( get depth and adjust for starting depth )\n\tresult @ adjust 2* = ( get results depth, same adjustment, should be\n\t half size of the depth ) \n\tif exit then ( pass )\n\tfailed\n\t.\" Unequal depths:\" cr\n\t.\" depth: \" depth . cr\n\t.\" result: \" result @ . cr\n\tdie ;\n\n: equal? ( -- : determine if results equals expected )\n\tno-check? if exit then\n\tresult @ adjust equal\n\tif exit then\n\tfailed\n\t.\" Result is not equal to expected values. \" cr \n\t.\" Stack: \" cr .s cr\n\tdie ;\n\n: display ( c-addr u -- : print out testing message in estring )\n\tverbose if neutral type else 2drop then ;\n\n: pass ( -- : print out passing message )\n\tverbose if good .\" ok \" cr reset-color then ;\n\n: save ( -- : save current dictionary )\n\tpwd @ previous !\n\there dictionary ! ;\n\n: restore ( -- : restore dictionary )\n\tprevious @ pwd ! \n\tdictionary @ h ! ;\n\n\n: T{ ( -- : perform a unit test )\n\tdepth start ! ( save start of stack depth )\n\t0 result ! ( reset result variable )\n\t0 check ! ( reset check variable )\n\testring 0 fill ( zero input string )\n\tsave ( save dictionary state )\n\tkey drop ( drop next character, which is a space )\n\testring [char] } accepter #estring ! ( read in string to test )\n\ttest display ( print which string we are testing )\n\ttest evaluate ( perform test )\n\tevaluate? ( evaluate successfully? )\n\tdepth? ( correct depth )\n\tequal? ( results equal to expected values? )\n\tpass ( print pass message )\n\tresult @ adjust 2* ndrop ( remove items on stack generated by test )\n\trestore ; ( restore dictionary to previous state )\n\nT{ }T\nT{ -> }T\nT{ 1 -> 1 }T\nT{ 1 2 -> 1 2 }T\nT{ : c 1 2 ; c -> 1 2 }T\nT{ :noname 2 ; :noname 3 + ; compose execute -> 5 }T\n\nhide{ \n\tpass test display\n\tadjust start save restore dictionary previous \n\tevaluate? equal? depth? estring #estring result\n\tcheck no-check? die neutral bad good failed\n}hide\n\n( ==================== Unit test framework =================== )\n\n\n( ==================== Random Numbers ========================= )\n\n( \nSee:\nuses xorshift\nhttps:\/\/en.wikipedia.org\/wiki\/Xorshift\nhttp:\/\/excamera.com\/sphinx\/article-xorshift.html\nhttp:\/\/www.arklyffe.com\/main\/2010\/08\/29\/xorshift-pseudorandom-number-generator\/\nthese constants have be collected from the web \n)\n\nsize 2 = [if] 13 constant a 9 constant b 7 constant c [then]\nsize 4 = [if] 13 constant a 17 constant b 5 constant c [then]\nsize 8 = [if] 12 constant a 25 constant b 27 constant c [then]\n\n7 variable seed ( must not be zero )\n\n: seed! ( x -- : set the value of the PRNG seed )\n\tdup 0= if drop 7 ( zero not allowed ) then seed ! ;\n\n: random ( -- x : assumes word size is 32 bit )\n\tseed @\n\tdup a lshift xor\n\tdup b rshift xor\n\tdup c lshift xor\n\tdup seed! ;\n\nhide{ a b c seed }hide\n\n( ==================== Random Numbers ========================= )\n\n( ==================== Prime Numbers ========================== )\n( From original \"third\" code from the IOCCC at \nhttp:\/\/www.ioccc.org\/1992\/buzzard.2.design, the module works out\nand prints prime numbers. )\n\n: prime? ( u -- u | 0 : return number if it is prime, zero otherwise )\n\tdup 1 = if 1- exit then\n\tdup 2 = if exit then\n\tdup 2\/ 2 ( loop from 2 to n\/2 )\n\tdo\n\t\tdup ( value to check if prime )\n\t\ti mod ( mod by divisor )\n\t\tnot if\n\t\t\tdrop 0 leave\n\t\tthen\n\tloop ;\n\n0 variable counter\n\n: primes ( x1 x2 -- : print the primes from x2 to x1 )\n\t0 counter !\n\t\" The primes from \" dup . \" to \" over . \" are: \"\n\tcr\n\tcolumn.reset\n\tdo\n\t\ti prime?\n\t\tif\n\t\t\ti . counter @ column counter 1+!\n\t\tthen\n\tloop\n\tcr\n\t\" There are \" counter @ . \" primes.\"\n\tcr ;\n\nhide{ counter }hide\n( ==================== Prime Numbers ========================== )\n\n( ==================== Debugging info ========================= )\n\n( string handling should really be done with PARSE, and CMOVE )\n\n: sh ( cnl -- ior : execute a line as a system command )\n\tnl word count system ;\n\nhide{ .s }hide\n: .s ( -- : print out the stack for debugging )\n\t[char] < emit depth u. [char] > emit space\n\tdepth if\n\t\tdepth 0 do i column tab depth i 1+ - pick . loop\n\tthen\n\tcr ;\n\n1 variable hide-words ( do we want to hide hidden words or not )\n\n: name ( PWD -- c-addr : given a pointer to the PWD field of a word get a pointer to the name of the word )\n\tdup 1+ @ 256\/ word-mask and lsb - chars> ;\n\n( This function prints out all of the defined words, excluding hidden words.\nAn understanding of the layout of a Forth word helps here. The dictionary\ncontains a linked list of words, each forth word has a pointer to the previous\nword until the first word. The layout of a Forth word looks like this:\n\nNAME: Forth Word - A variable length ASCII NUL terminated string\nPWD: Previous Word Pointer, points to the previous word\nCODE: Flags, code word and offset from previous word pointer to start of Forth word string\nDATA: The body of the forth word definition, not interested in this.\n\nThere is a register which stores the latest defined word which can be\naccessed with the code \"pwd @\". In order to print out a word we need to\naccess a words CODE field, the offset to the NAME is stored here in bits\n8 to 14 and the offset is calculated from the PWD field.\n\n\"print\" expects a character address, so we need to multiply any calculated\naddress by the word size in bytes. )\n\n: words.immediate ( bool -- : emit or mark a word being printed as being immediate )\n\tnot if dark red foreground color then ;\n\n: words.defined ( bool -- : emit or mark a word being printed as being a built in word )\n\tnot if bright green background color then ;\n\n: words.hidden ( bool -- : emit or mark a word being printed as being a hidden word )\n\tif dark magenta foreground color then ;\n\n: words ( -- : print out all defined an visible words )\n\tlatest\n\tspace\n\tbegin\n\t\tdup\n\t\thidden? hide-words @ and\n\t\tnot if\n\t\t\thidden? words.hidden\n\t\t\tcompiling? words.immediate\n\t\t\tdup defined-word? words.defined\n\t\t\tname\n\t\t\tprint space\n\t\t\treset-color\n\t\telse\n\t\t\tdrop\n\t\tthen\n\t\t@ ( Get pointer to previous word )\n\t\tdup dictionary-start u< ( stop if pwd no longer points to a word )\n\tuntil\n\tdrop cr ;\n\n( Simpler version of words\n: words\n\tpwd @ \n\tbegin\n\t\tdup name print space @ dup dictionary-start u<\n\tuntil drop cr ; )\n\nhide{ words.immediate words.defined words.hidden hidden? hidden-bit }hide\n\n: TrueFalse ( -- : print true or false )\n\tif \" true\" else \" false\" then ;\n\n: registers ( -- : print out important registers and information about the virtual machine )\n\t\" return stack pointer: \" r@ . cr\n\t\" dictionary pointer \" here . cr\n\t\" previous word: \" pwd ? cr\n\t\" state: \" state ? cr\n\t\" base: \" base ? cr\n\t\" depth: \" depth . cr\n\t\" cell size (in bytes): \" size . cr\n\t\" last cell address: \" max-core . cr\n\t\" unused cells: \" unused . cr\n\t\" invalid: \" `invalid @ TrueFalse cr\n\t\" size of variable stack: \" `stack-size ? cr\n\t\" size of return stack: \" `stack-size ? cr\n\t\" start of variable stack: \" max-core `stack-size @ 2* - . cr\n\t\" start of return stack: \" max-core `stack-size @ - . cr\n\t\" current input source: \" source-id -1 = if \" string\" else \" file\" then cr\n\t\" tracing on: \" `debug @ TrueFalse cr\n\t\" starting word: \" `instruction ? cr\n\t\" real start address: \" `start-address ? cr\n\t\" error handling: \" `error-handler ? cr \n\t\" throw handler: \" `handler ? cr\n\t\" signal recieved: \" `signal ? cr ;\n\t\n( `sin `sidx `slen `fout\n `stdout `stderr `argc `argv )\n\n\n: y\/n? ( -- bool : ask a yes or no question )\n\tkey drop\n\t\" y\/n? \"\n\tbegin\n\t\tkey\n\t\tdup\n\t\t[char] y = if true exit then\n\t\t[char] n = if false exit then\n\t\t\" y\/n? \"\n\tagain ;\n\n: step\n\t( step through a word: this word could be augmented\n\twith commands such as \"dump\", \"halt\", and optional\n\t\".s\" and \"registers\" )\n\tregisters\n\t\" .s: \" .s cr\n\t\" -- press any key to continue -- \"\n\tkey drop ;\n\n: more ( -- : wait for more input )\n\t\" -- press any key to continue -- \" key drop cr page ;\n\n: debug-help ( -- : print out the help for the debug command )\n \" debug mode commands\n\th - print help\n\tq - exit interpreter word\n\tr - print registers\n\ts - print stack\n\tR - print return stack\n\tc - continue on with execution\n\" ;\n\ndoer debug-prompt\n: prompt-default\n\t.\" debug> \" ;\n\nmake debug-prompt prompt-default\n\n: debug ( -- : enter interactive debug prompt )\n\tcr\n\t\" Entered Debug Prompt. Type 'h' for help. \" cr \n\tbegin\n\t\tkey\n\t\tcase\n\t\t\tnl of debug-prompt endof\n\t\t\t[char] h of debug-help endof\n\t\t\t[char] q of bye endof\n\t\t\t[char] r of registers endof\n\t\t\t[char] s of .s endof\n\t\t\t[char] R of r.s endof\n\t\t\t[char] c of exit endof\n\t\t\t( @todo add throw here )\n\t\tendcase \n\tagain ;\nhide debug-prompt\n\n: code>pwd ( CODE -- PWD\/0 : calculate PWD from code address )\n\tdup dictionary-start here within not if drop 0 exit then\n\t1 cells - ;\n\n: word-printer ( CODE -- : print out a words name given its code field )\n\tdup 1 cells - @ -1 = if . \" noname\" exit then ( nonames are marked by a -1 before its code field )\n\tdup code>pwd ?dup-if .d name print else drop \" data\" then\n\t drop ;\n\nhide{ code>pwd }hide\n\n( these words push the execution tokens for various special cases for decompilation )\n: get-branch [ find branch ] literal ;\n: get-?branch [ find ?branch ] literal ;\n: get-original-exit [ find _exit ] literal ;\n: get-quote [ find ' ] literal ;\n\n( @todo replace 2- nos1+ nos1+ with appropriate word, like the string word \nthat increments a string by an amount, but that operates on CELLS )\n: branch-increment ( addr branch -- increment : calculate decompile increment for \"branch\" )\n\t1+ dup negative? \n\tif \n\t\tover cr . [char] : emit space . cr 2 \n\telse \n\t\t2dup 2- nos1+ nos1+ dump \n\tthen ;\n\n( these words take a code field to a primitive they implement, decompile it\nand any data belonging to that operation, and push a number to increment the\ndecompilers code stream pointer by )\n\n: decompile-literal ( code -- increment )\n\t1+ ? \" literal\" 2 ;\n\n: decompile-branch ( code -- increment )\n\tdark red foreground color\n\t1+ ? \" branch \" dup 1+ @ branch-increment ;\n\n: decompile-quote ( code -- increment )\n\tdark green foreground color\n\tdup\n\t[char] ' emit 1+ @ word-printer 2 reset-color ;\n\n: decompile-?branch ( code -- increment )\n\t1+ ? \" ?branch\" 2 ;\n\n: decompile-exit ( code -- 0 )\n\t\" _exit\" cr \" End of word: \" . 0 ;\n\n( The decompile word expects a pointer to the code field of a word, it\ndecompiles a words code field, it needs a lot of work however.\nThere are several complications to implementing this decompile\nfunction.\n\n\t' The next cell should be pushed\n\t:noname This has a marker before its code field of -1 which\n\t\t cannot occur normally, this is handled in word-printer\n\tbranch branches are used to skip over data, but also for\n\t\t some branch constructs, any data in between can only\n\t\t be printed out generally speaking\n\texit There are two definitions of exit, the one used in\n\t\t ';' and the one everything else uses, this is used\n\t\t to determine the actual end of the word\n\tliterals Literals can be distinguished by their low value,\n\t\t which cannot possibly be a word with a name, the\n\t\t next field is the actual literal\n\nOf special difficult is processing 'if' 'else' 'then' statements,\nthis will require keeping track of '?branch'.\n\nAlso of note, a number greater than \"here\" must be data )\n\n: decompile ( code-pointer -- code-pointer increment|0 : )\n\t.d [char] : emit space dup @\n\tcase\n\t\tdolit of dup decompile-literal cr endof\n\t\tget-branch of dup decompile-branch endof\n\t\tget-quote of dup decompile-quote cr endof\n\t\tget-?branch of dup decompile-?branch cr endof\n\t\tget-original-exit of dup decompile-exit endof\n\t\tdup word-printer 1 swap cr\n\tendcase reset-color ;\n\n: decompiler ( code-field-ptr -- : decompile a word in its entirety )\n\tbegin decompile over + tuck = until drop ;\n\nhide{\n\tword-printer get-branch get-?branch get-original-exit \n\tget-quote branch-increment decompile-literal \n\tdecompile-branch decompile-?branch decompile-quote\n\tdecompile-exit\n}hide\n\n( these words expect a pointer to the PWD field of a word )\n: see.name \" name: \" name print cr ;\n: see.start \" word start: \" name chars . cr ;\n: see.previous \" previous word: \" @ . cr ;\n: see.immediate \" immediate: \" compiling? swap drop not TrueFalse cr ;\n: see.instruction \" instruction: \" xt-instruction . cr ;\n: see.defined \" defined: \" defined-word? TrueFalse cr ;\n\n: see.header ( PWD -- is-immediate-word? )\n\tdup see.name\n\tdup see.start\n\tdup see.previous\n\tdup see.immediate\n\tdup see.instruction ( @todo look up instruction name )\n\tsee.defined ;\n\n( @todo This does not work for all words, so needs fixing. \n Specifically: \n\t2variable\n\t2constant\n\ttable\n\tconstant\n\tvariable\n\tarray \nWhich are all complex CREATE words\n\nA good way to test decompilation is with the following Unix pipe: \n\n\t.\/forth -f forth.fth -e words \n\t\t| sed 's\/ \/ see \/g' \n\t\t| .\/forth -t forth.fth &> decompiled.log\n)\n\n( @todo refactor into word that takes a PWD pointer and one that attempts to parse\/find name )\n: see ( c\" xxx\" -- : decompile the next word in the input stream )\n\tfind\n\tdup 0= if -32 throw then\n\t-1 cells + ( move to PWD field )\n\tdup see.header\n\tdup defined-word?\n\tif ( decompile if a compiled word )\n\t\t2 cells + ( move to code field )\n\t\t\" code field:\" cr\n\t\tdecompiler\n\telse ( the instruction describes the word if it is not a compiled word )\n\t\tdup 1 cells + @ instruction-mask and doconst = if ( special case for constants )\n\t\t\t\" constant: \" 2 cells + @ .\n\t\telse\n\t\t\tdrop\n\t\tthen\n\tthen cr ;\n\nhide{ \n\tsee.header see.name see.start see.previous see.immediate \n\tsee.instruction defined-word? see.defined\n}hide\n\n( These help messages could be moved to blocks, the blocks could then\nbe loaded from disk and printed instead of defining the help here,\nthis would allow much larger help )\n\n: help ( -- : print out a short help message )\n\tpage\n\tkey drop\n\" Welcome to Forth, an imperative stack based language. It is both a low\nlevel and a high level language, with a very small memory footprint. Most\nof Forth is defined as a combination of various primitives.\n\nA short description of the available function (or Forth words) follows,\nwords marked (1) are immediate and cannot be used in command mode, words\nmarked with (2) define new words. Words marked with (3) have both command\nand compile functionality.\n\n\"\nmore \" Some of the built in words that accessible are:\n\n(1,2)\t: define a new word, switching to compile mode\n\timmediate make latest defined word immediate\n\tread read in a word, execute in command mode else compile\n\t@ ! fetch, store\n\tc@ c! character based fetch and store\n\t- + * \/ standard arithmetic operations,\n\tand or xor invert standard bitwise operations\n\tlshift rshift left and right bit shift\n\tu< u> < > = comparison predicates\n\texit exit from a word\n\temit print character from top of stack\n\tkey get a character from input\n\tr> >r pop a value from or to the return stack\n\tfind find a word in the dictionary and push the location\n\t' store the address of the following word on the stack\n\t, write the top of the stack to the dictionary\n\tswap swap first two values on the stack\n\tdup duplicate the top of the stack\n\tdrop pop and drop a value\n\tover copy the second stack value over the first\n\t. pop the top of the stack and print it\n\" \nmore \" \n\tprint print a NUL terminated string at a character address\n\tdepth get the current stack depth\n\tclock get the time since execution start in milliseconds\n\tevaluate evaluate a string\n\tsystem execute a system command\n\tclose-file close a file handle\n\topen-file open a file handle\n\tdelete-file delete a file off disk given a string\n\tread-file read in characters from a file\n\twrite-file write characters to a file\n\tfile-position get the file offset\n\treposition-file reposition the file pointer\n\tflush-file flush a file to disk\n\trename-file rename a file on disk\n \"\n\nmore \" All of the other words in the interpreter are built from these\nprimitive words. A few examples:\n\n(1)\tif...else...then FORTH branching construct\n(1)\tbegin...until loop until top of stack is non zero\n(1)\tbegin...again infinite loop\n(1)\tdo...loop FORTH looping construct\n(2,3)\tcreate create a new word that pushes its location\n(1)\tdoes> declare a created words run time behaviour\n(1,2)\tvariable declare variable with initial value from top of stack\n(1,2)\tconstant declare a constant, taken from top of stack\n(1,2)\tarray declare an array with size taken from top of stack\n(1)\t; terminate a word definition and return to command mode\n\twords print out a list of all the defined words\n\thelp this help message\n\tdump print out memory contents starting at an address\n\tregisters print out the contents of the registers\n\tsee decompile a word, viewing what words compose it\n\t.s print out the contents of the stack\n\n\"\n\nmore \" Some more advanced words:\n\n\there push the dictionary pointer\n\th push the address of the dictionary pointer\n\tr push the return stack pointer\n\tallot allocate space in the dictionary\n(1)\t[ switch to command mode\n\t] switch to compile mode\n\t:: compile ':' into the dictionary\n\n\" more \"\nFor more information either consult the manual pages forth(1) and libforth(1)\nor consult the following sources:\n\n\thttps:\/\/github.com\/howerj\/libforth\n\thttp:\/\/work.anapnea.net\/html\/html\/projects.html\n\nAnd for a larger tutorial:\n\n\thttps:\/\/github.com\/howerj\/libforth\/blob\/master\/readme.md\n\nFor resources on Forth:\n\n\thttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\thttps:\/\/rwmj.wordpress.com\/2010\/08\/07\/jonesforth-git-repository\/\n\n -- end --\n\" cr\n;\n\n( ==================== Debugging info ========================= )\n\n( ==================== Files ================================== )\n\n( @todo implement the other file access methods in terms of the\n built in ones [see http:\/\/forth.sourceforge.net\/std\/dpans\/dpans11.htm]\n @todo read-line and write-line need their flag and ior setting correctly\n\n\tFILE-SIZE [ use file-positions ]\n\n Also of note:\t\n * Source ID needs extending. )\n\n: read-char ( c-addr fileid -- ior : read a char )\n\t1 swap read-file 0<> swap 1 <> or ;\n\n0 variable x\n\n: getchar ( fileid -- char ior )\n\tx chars> swap read-char x chars> c@ swap ;\n\n: write-char ( c-addr fileid -- ior : write a char )\n\t1 swap write-file 0<> swap 1 <> or ;\n\n: putchar ( char fileid -- ior )\n\tswap x chars> c! x chars> swap write-char ;\n\nhide{ x }hide\n\n: rewind-file ( file-id -- : rewind a file to the beginning )\n\t0 reposition-file throw ;\n\n: read-line ( c-addr u1 fileid -- u2 flag ior : read in a line of text )\n\t-rot bounds\n\tdo\n\t\tdup i swap read-char drop\n\t\ti c@ nl = if drop i 0 0 leave then\n\tloop drop ;\n\n: write-line ( c-addr u fileid -- u2 flag ior : write a line of text )\n\t-rot bounds\n\tdo\n\t\tdup i swap write-char drop\n\t\ti c@ nl = if drop i 0 0 leave then\n\tloop ;\n\n: resize-file ( ud fileid -- ior : attempt to resize a file )\n\t( There is no portable way to truncate a file :C )\n\t2drop -1 ( -1 to indicate failure ) ;\n\n: create-file ( c-addr u fam -- fileid ior )\n\t>r 2dup w\/o open-file throw close-file throw\n\tr> open-file ;\n\n: include-file ( file-id -- : evaluate a file ) \n\tdup >r 0 1 evaluator r> close-file throw throw ;\n\n: included ( c-addr u -- : attempt to open up a name file and evaluate it )\n\tr\/o open-file throw \n\tinclude-file ;\n\n: include ( c\" ccc\" -- : attempt to evaluate a named file )\n\t( @bug requires trailing space, should use parse-name )\n\tbl word count included ;\n\n: bin ( fam1 -- fam2 : modify a file access method to be binary not line oriented ) \n\t( Do nothing, all file access methods are binary )\n\t;\n\n( ==================== Files ================================== )\n\n( ==================== Matcher ================================ )\n( The following section implements a very simple regular expression\nengine, which expects an ASCIIZ Forth string. It is translated from C\ncode and performs an identical function.\n\nThe regular expression language is as follows:\n\n\tc\tmatch a literal character\n\t.\tmatch any character\n\t*\tmatch any characters\n\nThe \"*\" operator performs the same function as \".*\" does in most\nother regular expression engines. Most other regular expression engines\nalso do not anchor their selections to the beginning and the end of\nthe string to match, instead using the operators '^' and '$' to do\nso, to emulate this behavior '*' can be added as either a suffix,\nor a prefix, or both, to the matching expression.\n\nAs an example \"*, World!\" matches both \"Hello, World!\" and\n\"Good bye, cruel World!\". \"Hello, ....\" matches \"Hello, Bill\"\nand \"Hello, Fred\" but not \"Hello, Tim\" as there are two few\ncharacters in the last string.\n\n@todo make a matcher that expects a Forth string, which do not\nhave to be NUL terminated\n)\n\n\\ Translated from http:\/\/c-faq.com\/lib\/regex.html\n\\ int match(char *pat, char *str)\n\\ {\n\\ \tswitch(*pat) {\n\\ \tcase '\\0': return !*str;\n\\ \tcase '*': return match(pat+1, str) || *str && match(pat, str+1);\n\\ \tcase '.': return *str && match(pat+1, str+1);\n\\ \tdefault: return *pat == *str && match(pat+1, str+1);\n\\ \t}\n\\ }\n\n: *pat ( regex -- regex char : grab next character of pattern ) \n\tdup c@ ;\n\n: *str ( string regex -- string regex char : grab next character string to match )\n\tover c@ ;\n\n: pass ( c-addr1 c-addr2 -- bool : pass condition, characters matched ) \n\t2drop 1 ;\n\n: reject ( c-addr1 c-addr2 -- bool : fail condition, character not matched ) \n\t2drop 0 ;\n\n: *pat==*str ( c-addr1 c-addr2 -- c-addr1 c-addr2 bool )\n\t2dup c@ swap c@ = ;\n\n: ++ ( u1 u2 u3 u4 -- u1+u3 u2+u4 : not quite d+ [does no carry] )\n\tswap >r + swap r> + swap ;\n\ndefer matcher\n\n: advance ( string regex char -- bool : advance both regex and string )\n\tif 1 1 ++ matcher else reject then ;\n\n: advance-string ( string regex char -- bool : advance only the string )\n\tif 1 0 ++ matcher else reject then ;\n\n: advance-regex ( string regex -- bool : advance matching )\n\t2dup 0 1 ++ matcher if pass else *str advance-string then ;\n\n: match ( string regex -- bool : match a ASCIIZ pattern against an ASCIIZ string )\n\t( @todo Add limits and accept two Forth strings, making sure they are both\n\t ASCIIZ strings as well \n\t @warning This uses a non-standards compliant version of case! )\n\t*pat\n\tcase\n\t\t 0 of drop c@ not endof\n\t\t[char] * of advance-regex endof\n\t\t[char] . of *str advance endof\n\t\t drop *pat==*str advance exit\n\tendcase ;\n\nmatcher is match\n\nhide{ \n\t*str *pat *pat==*str pass reject advance \n\tadvance-string advance-regex matcher ++ \n}hide\n\n( ==================== Matcher ================================ )\n\n\n( ==================== Cons Cells ============================= )\n\n( From http:\/\/sametwice.com\/cons.fs, this could be improved if the optional\nmemory allocation words were added to the interpreter. This provides\na simple \"cons cell\" data structure. There is currently no way to\nfree allocated cells )\n\n: car! ( value cons-addr -- : store a value in the car cell of a cons cell ) \n\t! ;\n\n: cdr! ( value cons-addr -- : store a value in the cdr cell of a cons cell )\n\tcell+ ! ;\n\n: car@ ( cons-addr -- car-val : retrieve car value from cons cell )\n\t@ ;\n\n: cdr@ ( cons-addr -- cdr-val : retrieve cdr value from cons cell )\n\tcell+ @ ;\n\n: cons ( car-val cdr-val -- cons-addr : allocate a new cons cell )\n\tswap here >r , , r> ;\n\n: cons0 0 0 cons ;\n\n( ==================== Cons Cells ============================= )\n\n( ==================== Miscellaneous ========================== )\n\n: license ( -- : print out license information )\n\" \nThe MIT License (MIT)\n\nCopyright (c) 2016, 2017 Richard James Howe\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the 'Software'),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand\/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\nTHE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\nOTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\nARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE. \n\n\" \n;\n\n\n\n\n( ==================== Core utilities ======================== )\n( Read the header of a core file and process it, printing the\nresults out )\n\n8 constant header-size ( size of Forth core file header )\n8 constant size-field-size ( the size in bytes of the size field in the core file )\n0 variable core-file ( core fileid we are reading in )\n0 variable core-cell-size ( cell size of Forth core )\n0 variable core-version ( version of core file )\n0 variable core-endianess ( endianess of core we are reading in )\n\n( save space to read in header )\ncreate header header-size chars allot\n: cheader ( -- c-addr : header char address )\n\theader chars> ;\ncreate size-field size-field-size chars allot\n: csize-field ( -- c-addr : address of place size field is stored in )\n\tsize-field chars> ;\n\n0\nenum header-magic0 ( magic number 0 : FF ) \nenum header-magic1 ( magic number 1 : '4' )\nenum header-magic2 ( magic number 2 : 'T' )\nenum header-magic3 ( magic number 3 : 'H' )\nenum header-cell-size ( size of a forth cell, either 2, 4 or 8 bytes )\nenum header-version ( version of the forth core )\nenum header-endianess ( endianess of the core )\nenum header-log2size ( binary logarithm of the core size )\n\n: cleanup ( -- : cleanup before abort )\n\tcore-file @ ?dup 0<> if close-file drop then ;\n\n: invalid-header ( bool -- : abort if header is invalid )\n\t<> if cleanup abort\" invalid header\" then ;\n\n: save-core-cell-size ( char -- : save the core file cell size, checking if it is valid )\n\tcore-cell-size !\n\t\" cell size:\" tab\n\tcore-cell-size @ 2 = if 2 . cr exit then\n\tcore-cell-size @ 4 = if 4 . cr exit then\n\tcore-cell-size @ 8 = if 8 . cr exit then\n\tcleanup core-cell-size @ . abort\" : invalid cell size\" ;\n\n: check-version-compatibility ( char -- : checks the version compatibility of the core file ) \n\tcore-version !\n\tcore-version @ version = if \" version: \" version . cr exit then\n\tcleanup core-version @ . abort\" : unknown version number\" ;\n\n: save-endianess ( char -- : save the endianess, checking if it is valid )\n\tcore-endianess !\n\t\" endianess:\" tab\n\tcore-endianess @ 0 = if \" big\" cr exit then\n\tcore-endianess @ 1 = if \" little\" cr exit then\n\tcleanup core-endianess @ . abort\" invalid endianess\" then ;\n\n: read-or-abort ( c-addr size fileid -- : )\n\tover >r read-file \n\t 0<> if cleanup abort\" file read failed\" then\n\tr> <> if cleanup abort\" header too small\" then ;\n\n: header? ( -- : print out header information )\n\tcheader header-size core-file @ read-or-abort\n\t( \" raw header:\" header 2 dump )\n\tcheader header-magic0 + c@ 255 invalid-header\n\tcheader header-magic1 + c@ [char] 4 invalid-header\n\tcheader header-magic2 + c@ [char] T invalid-header\n\tcheader header-magic3 + c@ [char] H invalid-header\n\tcheader header-cell-size + c@ save-core-cell-size\n\tcheader header-version + c@ check-version-compatibility\n\tcheader header-endianess + c@ save-endianess\n\t\" valid header\" cr ;\n\n: size? ( -- : print out core file size )\n\t\" size: \" cheader header-log2size + c@ 1 swap lshift . cr ;\n\n: core ( c-addr u -- : analyze a Forth core file from disk given its file name )\n\t2dup \" core file:\" tab type cr\n\tr\/o open-file throw core-file ! \n\theader?\n\tsize?\n\tcore-file @ close-file drop ;\n\n( s\" forth.core\" core )\n\nhide{ \nheader-size header? \nheader-magic0 header-magic1 header-magic2 header-magic3\nheader-version header-cell-size header-endianess header-log2size\nheader \ncore-file save-core-cell-size check-version-compatibility\ncore-cell-size cheader\ncore-endianess core-version save-endianess invalid-header\ncleanup size-field csize-field size-field-size\nread-or-abort size?\n}hide\n\n( ==================== Core utilities ======================== )\n\n( ==================== RLE =================================== )\n\n( These set of words implement Run Length Compression, which can be used for\nsaving space when compressing the core files generated by Forth programs, which\ncontain mostly runs of NUL characters. \n\nThe format of the encoded data is quite simple, there is a command byte\nfollowed by data. The command byte encodes only two commands; encode a run of\nliteral data and repeat the next character. \n\nIf the command byte is greater than X the command is a run of characters, \nX is then subtracted from the command byte and this is the number of \ncharacters that is to be copied verbatim when decompressing.\n\nIf the command byte is less than or equal to X then this number, plus one, is \nused to repeat the next data byte in the input stream.\n\nX is 128 for this application, but could be adjusted for better compression\ndepending on what the data looks like. \n\nExample:\n\t\n\t2 'a' 130 'b' 'c' 3 'd'\n\nBecomes:\n\n\taabcddd \n\nExample usage:\n\n\t: extract\n\t\tc\" forth.core\" w\/o open-file throw\n\t\tc\" forth.core.rle\" r\/o open-file throw\n\t\tdecompress ;\n\textract\n\n@note file redirection could be used for the input as well\n@todo compression, and reading\/writing to strings )\n\n: cpad pad chars> ;\n\n0 variable out\n128 constant run-length\n\n: next.char ( file-id -- char : read in a single character )\n\t>r cpad r> read-char throw cpad c@ ;\n\n: repeated ( count file-id -- : repeat a character count times )\n\tnext.char swap 0 do dup emit loop drop ;\n\n: literals ( count file-id -- : extract a literal run )\n\t>r cpad swap r> read-file throw cpad swap type ;\n\n: command ( file-id -- : process an RLE command )\n\tdup \n\t>r next.char\n\tdup run-length u> \n\tif \n\t\trun-length - r> literals \n\telse \n\t\t1+ r> repeated \n\tthen ;\n\n: redirect ( file-id-out -- : save current output pointer, redirect to output )\n\t`fout @ out ! `fout ! ;\n\n: restore ( -- : restore previous output pointer )\n\tout @ `fout ! ;\n\n: decompress ( file-id-out file-id-in -- : decompress an RLE encoded file )\n\tswap\n\tredirect\n\tbegin dup ' command catch until ( process commands until input exhausted )\n\t2drop ( drop twice because catch will restore stack before 'command' )\n\trestore ; ( restore input stream )\n\nhide{ literals repeated next.char out run-length command }hide\n\n( ==================== RLE =================================== )\n\n( ==================== Generate C Core file ================== )\n( The word core2c reads in a core file and turns it into a C file which \ncan then be compiled into the forth interpreter in a bootstrapping like\nprocess.\n\nUsage:\n c\" forth.core\" c\" core.gen.c\" core2c )\n\n0 variable count\n\n: wbyte ( u char -- : write a byte )\n\tpnum drop\n\t[char] , emit\n\t16 mod 0= if cr then ;\n\n: advance ( char -- : advance counter and print byte )\n\tcount 1+! count @ swap wbyte ;\n\n: hexify ( fileid -- fileid : turn core file into C numbers in array )\n\t0 count !\n\tbegin dup getchar 0= while advance repeat drop ;\n\n: quote ( -- : emit a quote character )\n\t[char] \" emit ;\n\n: core2c ( c-addr u c-addr u -- ior : generate a C file from a core file )\n\tw\/o open-file throw >r\n\tr\/o open-file ?dup-if r> close-file throw throw then\n\tr> redirect\n\t\" #include \" quote \" libforth.h\" quote cr\n\t\" unsigned char forth_core_data[] = {\" cr\n\thexify \n\t\" };\" cr\n\t\" forth_cell_t forth_core_size = \" count @ . \" ;\" cr cr\n\tclose-file\n\t`fout @ close-file \n\trestore or ;\n\nhide{ wbyte hexify count quote advance }hide\n \n( ==================== Generate C Core file ================== )\n\n: wc ( c-addr u -- u : count the bytes in a file )\n\tr\/o open-file throw\n\t0 swap\n\tbegin dup getchar nip 0= while nos1+ repeat close-file throw ;\n\n( ==================== Save Core file ======================== )\n\n( The following functionality allows the user to save the core file\nfrom within the running interpreter. The Forth core files have a very simple\nformat which means the words for doing this do not have to be too long, a header\nhas to emitted with a few calculated values and then the contents of the\nForths memory after this )\n\n( This write the header out to the current output device, this\nwill be redirected to a file )\n: header ( -- : write the header out )\n\t0xff emit ( magic 0 )\n\t[char] 4 emit ( magic 1 )\n\t[char] T emit ( magic 2 )\n\t[char] H emit ( magic 3 )\n\tsize emit ( cell size in bytes )\n\tversion emit ( core version )\n\tendian not emit ( endianess )\n\tmax-core log2 emit ; ( size field )\n\n: data ( -- : write the data out )\n\t0 max-core chars> `fout @ write-file throw drop ;\n\n: encore ( -- : write the core file out )\n\theader\n\tdata ;\n\n: save-core ( c-addr u -- : save core file or throw error ) \n\tw\/o open-file throw dup\n\tredirect \n\t\t' encore catch swap close-file throw \n\trestore ;\n\n( The following code illustrates an example of setting up a\nForth core file to execute a word when the core file is loaded.\nIn the example the word \"hello-world\" will be executed, which will\nalso quit the interpreter:\n\n\t\\ Only works for immediate words for now, we define\n\t\\ the word we wish to be executed when the forth core\n\t\\ is loaded\n\t: hello-world immediate\n\t\t\" Hello, World!\" cr bye ;\n\n\t\\ The following sets the starting word to our newly\n\t\\ defined word:\n\tfind hello-world cfa start!\n\n\t\\ Now we can save the core file out:\n\ts\" forth.core\" save-core \n\nThis can be used, in conjunction with aspects of the build system,\nto produce a standalone executable that will run only a single Forth\nword. )\n\nhide{ redirect restore data encore header }hide\n\n( ==================== Save Core file ======================== )\n\n( ==================== Hex dump ============================== )\n\n( @todo hexdump can read in too many characters and it does not\nprint out the correct address\n@todo utilities for easy redirecting of file input\/output )\n: input >r cpad 128 r> read-file ; ( file-id -- u 0 | error )\n: clean cpad 128 0 fill ; ( -- )\n: cdump cpad chars swap aligned chars dump ; ( u -- )\n: hexdump ( file-id -- : [hex]dump a file to the screen )\n\tdup \n\tclean\n\tinput if 2drop exit then\n\t?dup-if cdump else drop exit then\n\ttail ; \n\nhide{ cpad clean cdump input }hide\n\n( ==================== Hex dump ============================== )\n\n( ==================== Date ================================== )\n\n( Rather annoyingly months are start from 1 but weekdays from 0 )\n\n: >month ( month -- )\n\tcase\n\t\t 1 of \" Jan \" endof\n\t\t 2 of \" Feb \" endof\n\t\t 3 of \" Mar \" endof\n\t\t 4 of \" Apr \" endof\n\t\t 5 of \" May \" endof\n\t\t 6 of \" Jun \" endof\n\t\t 7 of \" Jul \" endof\n\t\t 8 of \" Aug \" endof\n\t\t 9 of \" Sep \" endof\n\t\t10 of \" Oct \" endof\n\t\t11 of \" Nov \" endof\n\t\t12 of \" Dec \" endof\n\t\t-11 throw\n\tendcase ;\n\n: .day ( day -- : add ordinal to day )\n\t10 mod\n\tcase\n\t\t1 of \" st \" exit endof\n\t\t2 of \" nd \" exit endof\n\t\t3 of \" rd \" exit endof\n\t\t\" th \" \n\tendcase ;\n\n: >day ( day -- : add ordinal to day of month )\n\tdup u.\n\tdup 1 10 within if .day exit then\n\tdup 10 20 within if \" th\" drop exit then\n\t.day ;\n\n: >weekday ( weekday -- : print the weekday )\n\tcase\n\t\t0 of \" Sun \" endof\n\t\t1 of \" Mon \" endof\n\t\t2 of \" Tue \" endof\n\t\t3 of \" Wed \" endof\n\t\t4 of \" Thu \" endof\n\t\t5 of \" Fri \" endof\n\t\t6 of \" Sat \" endof\n\tendcase ;\n\n: padded ( u -- : print out a run of zero characters )\n\t0 do [char] 0 emit loop ;\n\n: 0u. ( u -- : print a zero padded number @todo replace with u.r )\n\tdup 10 u< if 1 padded then u. space ;\n\n: .date ( date -- : print the date )\n\tif \" DST \" else \" GMT \" then \n\tdrop ( no need for days of year)\n\t>weekday\n\t. ( year ) \n\t>month \n\t>day \n\t0u. ( hour )\n\t0u. ( minute )\n\t0u. ( second ) cr ;\n\n: time&date ( -- second minute hour day month year )\n\tdate\n\t3drop ;\n\nhide{ 0u. >weekday .day >day >month padded }hide\n\n( ==================== Date ================================== )\n\n\n( ==================== CRC =================================== )\n\n( @todo implement all common CRC algorithms, but only if\nthe word size allows it [ie. 32 bit CRCs on a 32 or 64 bit\nmachine, 64 bit CRCs on a 64 bit machine] )\n\n( Make a word to limit arithmetic to a 16-bit value )\nsize 2 = [if] \n\t: limit immediate ; ( do nothing, no need to limit )\n[else] \n\t: limit 0xffff and ; ( limit to 16-bit value )\n[then]\n\n: ccitt ( crc c-addr -- crc : calculate polynomial 0x1021 AKA \"x16 + x12 + x5 + 1\" )\n\tc@ ( get char )\n\tlimit over 256\/ xor ( crc x )\n\tdup 4 rshift xor ( crc x )\n\tdup 5 lshift limit xor ( crc x )\n\tdup 12 lshift limit xor ( crc x )\n\tswap 8 lshift limit xor ; ( crc )\n\n( see http:\/\/stackoverflow.com\/questions\/10564491\/function-to-calculate-a-crc16-checksum\n and https:\/\/www.lammertbies.nl\/comm\/info\/crc-calculation.html )\n: crc16-ccitt ( c-addr u -- u )\n\t0xFFFF -rot\n\t['] ccitt\n\tforeach ;\nhide{ limit ccitt }hide\n\n( ==================== CRC =================================== )\n\n( ==================== Rational Data Type ==================== )\n( This word set allows the manipulation of a rational data type,\nwhich are basically fractions. This allows numbers like 1\/3 to\nbe represented without any loss of precision. Conversion to and\nfrom the data type to an integer type is trivial, although \ninformation can be lost during the conversion.\n\nTo convert to a rational, use 'dup', to convert from a rational,\nuse '\/'. \n\nThe denominator is the first number on the stack, the numerator the\nsecond number. Fractions are simplified after any rational operation,\nand all rational words can accept unsimplified arguments. For example\nthe fraction 1\/3 can be represented as 6\/18, they are equivalent, so\nthe rational equality operator \"=rat\" can accept both and returns\ntrue.\n\n\tT{ 1 3 6 18 =rat -> 1 }T\n\nSee: https:\/\/en.wikipedia.org\/wiki\/Rational_data_type \nFor more information.\n\nThis set of words use two cells to represent a fraction, however\na single cell could be used, with the numerator and the denominator\nstored in upper and lower half of a single cell. )\n\n: simplify ( a b -- a\/gcd{a,b} b\/gcd{a\/b} : simplify a rational )\n 2dup\n gcd\n tuck\n \/\n -rot\n \/\n swap ; \\ ? check this\n\n: crossmultiply ( a b c d -- a*d b*d c*b d*b )\n rot ( a c d b )\n 2dup ( a c d b d b )\n * ( a c d b d*b )\n >r ( a c d b , d*b )\n rot ( a d b c , d*b )\n * ( a d b*c , d*b )\n -rot ( b*c a d , d*b )\n * ( b*c a*d , d*b )\n r> ( b*c a*d d*b )\n tuck ( b*c d*b a*d d*b )\n 2swap ; ( done! )\n\n: *rat ( a\/b c\/d -- a\/b : multiply two rationals together )\n rot * -rot * swap simplify ;\n\n: \/rat ( a\/b c\/d -- a\/b : divide one rational by another )\n swap *rat ;\n\n: +rat ( a\/b c\/d -- a\/b : add two rationals together )\n crossmultiply\n rot\n drop ( or check if equal, if not there is an error )\n -rot\n +\n swap\n simplify ;\n\n: -rat ( a\/b c\/d -- a\/b : subtract one rational from another )\n crossmultiply \n rot\n drop ( or check if equal, if not there is an error )\n -rot\n -\n swap\n simplify ;\n\n: .rat ( a\/b -- : print out a rational number )\n simplify swap . [char] \/ emit space . ;\n\n: =rat ( a\/b c\/d -- bool : rational equal )\n crossmultiply rot = -rot = = ;\n\n: >rat ( a\/b c\/d -- bool : rational greater than )\n crossmultiply rot 2drop > ;\n\n: <=rat ( a\/b c\/d -- bool : rational less than or equal to )\n\t>rat not ;\n\n: =rat ( a\/b c\/d -- bool : rational greater or equal to )\n\t0 block number stored in buf)\n\n: invalid? ( n -- : throw if block number is invalid )\n\t0= if -35 throw then ;\n\n: update ( -- : mark currently loaded block buffer as dirty )\n\ttrue dirty ! ;\n\n: updated? ( n -- bool : )\n\t\n\tdirty @ ;\n\n: block.name ( n -- c-addr u : make a block name )\n\tc\" .blk\" <# holds #s #> rot drop ;\n\n( @warning this will not work if we do not have permission,\nor in various other cases where we cannot open the file, for\nwhatever reason )\n: file-exists ( c-addr u : does a file exist? )\n\tr\/o open-file if drop 0 else close-file throw 1 then ;\n\n: buffer.exists ( n -- bool : does a block buffer exist on disk? )\n\tblock.name file-exists ;\n\n( @note block.write and block.read do not check if they have\nwrote or read in 1024 bytes, nor do they check that they can\nonly write or read 1024 and not a byte more )\n\n: block.read ( file-id -- file-id : read in buffer )\n\tdup >r buf r> read-file nip if close-file -33 throw then ;\n\n: block.write ( file-id -- file-id : write out buffer )\n\tdup >r buf r> write-file nip if close-file -34 throw then ;\n\n: block.open ( n fam -- file-id )\n\t>r block.name r> open-file throw ;\n\n: save-buffers \n\tblk @ 0= if exit then ( not a valid block number, exit )\n\tdirty @ not if exit then ( not dirty, no need to save )\n\tblk @ w\/o block.open ( open file backing block buffer )\n\tblock.write ( write it out )\n\tclose-file throw ( close it )\n\tfalse dirty ! ; ( but only mark it clean if everything succeeded )\n\n: empty-buffers ( -- : deallocate any saved buffers )\n\t0 blk ! ;\n\n: flush ( -- : perform save-buffers followed by empty-buffers )\n\tsave-buffers\n\tempty-buffers ;\n\n( Block is a complex word that does a lot, although it has a simple\ninterface. It does the following given a block number:\n\n1. Checks the provided block buffer number to make sure it is valid\n2. If the block is already loaded from the disk, then return the\naddress of the block buffer it is loaded into.\n3. If not, it checks to see if the currently loaded block buffer is\ndirty, if it is then it flushes the buffer to disk.\n4. If the block buffer does not exists on disk then it creates it.\n5. It then stores the block number in blk and returns an address to\nthe block buffer. )\n: block ( n -- c-addr : load a block )\n\tdup invalid? \n\tdup blk @ = if drop buf drop exit then\n\tflush\n\tdup buffer.exists if ( if the buffer exits on disk load it in )\n\t\tdup r\/o block.open \n\t\tblock.read \n\t\tclose-file throw \n\telse ( else it does not exist )\n\t\tbuf 0 fill ( clean the buffer )\n\tthen \n\tblk ! ( save the block number )\n\tbuf drop ;\n\n: buffer block ;\n\n( @warning uses hack, block buffer is NUL terminated, and evaluate requires\na NUL terminated string, evaluate checks that the last character is NUL, \nhence the 1+ )\n: load ( n -- : load and execute a block )\n\tblock b\/buf 1+ evaluate throw ;\n\nhide{ \n\tblock.name invalid? block.write \n\tblock.read buffer.exists block.open dirty\n}hide\n\n( ==================== Block Layer =========================== )\n\n( ==================== List ================================== )\n1 variable fancy-list\n0 variable scr\n64 constant c\/l ( characters per line )\n\n: line.number ( n -- : print line number )\n\tfancy-list @ if\n\t\tdup 10 < (base) 10 = and if space then ( leading space: works up to c\/l = 99)\n\t\t. [char] | emit ( print \" line-number : \")\n\telse\n\t\tdrop\n\tthen ;\n\n: line ( c-addr -- c-addr u : given a line number, display that line )\n\tdup \n\tline.number ( display line number )\n\tc\/l * + ( calculate offset )\n\tc\/l ; ( add line length )\n\n: list.end\n\tfancy-list @ not if exit then\n\t[char] | emit ;\n\n: list.type ( c-addr u -- : list a block )\n\tb\/buf c\/l \/ 0 do dup i line type list.end cr loop drop ;\n\n: list.border \" +---|---\" ;\n\n: list.box\n\tfancy-list @ not if exit then\n\t4 spaces\n\t8 0 do list.border loop cr ;\n\n: list ( n -- : display a block number and update scr )\n\tdup >r block r> scr ! list.box list.type list.box ;\n\n: thru\n\tkey drop\n\t1+ swap do i list more loop ;\n\n: make-blocks ( n1 n2 -- : make blocks on disk from n1 to n2 inclusive )\n\t1+ swap do i block b\/buf bl fill update loop save-buffers ;\n\nhide{ buf line line.number list.type fancy-list (base) list.box list.border list.end }hide\n\n( ==================== List ================================== )\n\n( ==================== Signal Handling ======================= )\n( Signal handling at the moment is quite primitive. When a signal\noccurs it has to be explicitly tested for by the programmer, this\ncould be improved on quite a bit. One way of doing this would be\nto check for signals in the virtual machine and cause a THROW\nfrom within it. )\n\n( signals are biased to fall outside the range of the error numbers\ndefined in the ANS Forth standard. )\n-512 constant signal-bias \n\n: signal ( -- signal\/0 : push the results of the signal register ) \n\t`signal @\n \t0 `signal ! ;\n\n( ==================== Signal Handling ======================= )\n\n( Looking at most Forths dictionary with \"words\" command they tend\nto have a lot of words that do not mean anything but to the implementers\nof that specific Forth, here we clean up as many non standard words as\npossible. )\nhide{ \n do-string ')' alignment-bits \n dictionary-start hidden-mask instruction-mask immediate-mask compiling?\n compile-bit\n max-core dolist doconst x x! x@ \n max-string-length \n _exit\n pnum evaluator \n TrueFalse >instruction \n xt-instruction\n `state\n `source-id `sin `sidx `slen `start-address `fin `fout `stdin\n `stdout `stderr `argc `argv `debug `invalid `top `instruction\n `stack-size `error-handler `x `handler _emit `signal \n}hide\n\n( \n## Forth To List\n\nThe following is a To-Do list for the Forth code itself, along with any\nother ideas.\n\n* FORTH, VOCABULARY\n* \"Value\", \"To\", \"Is\"\n* Double cell words \n* The interpreter should use character based addresses, instead of\nword based, and use values that are actual valid pointers, this\nwill allow easier interaction with the world outside the virtual machine\n* common words and actions should be factored out to simplify\ndefinitions of other words, their standards compliant version found\nif any\n* A soft floating point library would be useful which could be used\nto optionally implement floats [which is not something I really want\nto add to the virtual machine]. If floats were to be added, only the\nminimal set of functions should be added [f+,f-,f\/,f*,f<,f>,>float,...]\n* Allow the processing of argc and argv, the mechanism by which that\nthis can be achieved needs to be worked out. However all processing that\nis currently done in \"main.c\" should be done within the Forth interpreter\ninstead. Words for manipulating rationals and double width cells should\nbe made first.\n* A built in version of \"dump\" and \"words\" should be added to the Forth\nstarting vocabulary, simplified versions that can be hidden.\n* Here documents, string literals. Examples of these can be found online\n* Document the words in this file and built in words better, also turn this\ndocument into a literate Forth file.\n* Sort out \"'\", \"[']\", \"find\", \"compile,\" \n* Proper booleans should be used throughout, that is -1 is true, and 0 is\nfalse.\n* Attempt to add crypto primitives, not for serious use, like TEA, XTEA,\nXXTEA, RC4, MD5, ...\n* Add hash functions: CRC-32, CRC-16, ...\nhttp:\/\/stackoverflow.com\/questions\/10564491\/function-to-calculate-a-crc16-checksum\n* File operation primitives that close the file stream [and possibly restore\nI\/O to stdin\/stdout] if an error occurs, and then re-throws, should be made.\n* Implement as many things from http:\/\/lars.nocrew.org\/forth2012\/implement.html\nas is sensible. \n* The current words that implement I\/O redirection need to be improved, and documented,\nI think this is quite a useful and powerful mechanism to use within Forth that simplifies\nprograms. This is a must and will make writing utilities in Forth a *lot* easier \n* Words for manipulating words should be added, for navigating to different\nfields within them, to the end of the word, etcetera.\n* The data structure used for parsing Forth words needs changing in libforth so a\ncounted string is produced. Counted strings should be used more often. The current\nlayout of a Forth word prevents a counted string being used and uses a byte more\nthan it has to.\n* Whether certain simple words [such as '1+', '1-', '>', '<', '<>', 'not', '<=',\n'>='] should be added as virtual machine instructions for speed [and size] reasons\nshould be investigated.\n* An analysis of the interpreter and the code it executes could be done to find\nthe most commonly executed words and instructions, as well as the most common two and\nthree sequences of words and instructions. This could be used to use to optimize the\ninterpreter, in terms of both speed and size.\n* As a thought, a word for inlining other words could be made by copying everything\ninto the current definition until it reaches a _exit, it would need to be aware of\nliterals written into a word, like 'see' is.\n\n### libforth.c todo\n\n* A halt, a parse, and a print\/type instruction could be added to the Forth virtual\nmachine.\n* Throw\/Catch need to be added and used in the virtual machine\n* Various edge cases and exceptions should be removed [for example counted strings\nare not used internally, and '0x' can be used as a prefix only when base is zero].\n* A potential optimization is to order the words in the dictionary by frequency order,\nthis would mean chaning the X Macro that contains the list of words, after collecting\nstatistics. This should make find faster.\n* Investigate adding operating system specific code into the interpreter and\nisolating it to make it semi-portable.\n* Make equivalents for various Unix utilities in Forth, like a CRC check, cat,\ntr, etcetera.\n\n )\n\nverbose [if] \n\t.( FORTH: libforth successfully loaded.) cr\n\t.( Type 'help' and press return for a basic introduction.) cr\n\t.( Core: ) here . \" \/ \" here unused + . cr\n\t license\n[then]\n\n\n( ==================== Test Code ============================= )\n\n( The following will not work as we might actually be reading from a string [`sin]\nnot `fin. \n: key 32 chars> 1 `fin @ read-file drop 0 = if 0 else 32 chars> c@ then ; )\n\n\\ : ' immediate state @ if postpone ['] else find then ;\n\n( This really does not implement a correct FORTH\/VOCABULARY, for that\nwordlists will need to be introduced and used in libforth.c. The best\nthat this word set can do is to hide and reveal words to the user, this\nwas just an experiment. \n\n\t: forth \n\t\t[ find forth 1- @ ] literal\n\t\t[ find forth 1- ] literal ! ;\n\n\t: vocabulary\n\t\tcreate does> drop 0 [ find forth 1- ] literal ! ; )\n\n\\ @todo The built in primitives should be redefined so to make sure\n\\ they are called and nested correctly, using the following words\n\\ 0 variable csp\n\\ : !csp sp@ csp ! ;\n\\ : ?csp sp@ csp @ <> if -22 throw then ;\n\n\\ @todo Make this work\n\\ : >body ??? ;\n\\ : noop ( -- ) ;\n\\ : defer create ( \"name\" -- ) ['] noop , does> ( -- ) @ execute ;\n\\ : is ( xt \"name\" -- ) find >body ! ;\n\\ defer lessthan\n\\ find < is lessthan\n\n( ==================== Test Code ============================= )\n\n( ==================== Block Editor ========================== )\n( Experimental block editor Mark II \n\n@todo Improve the block editor \n\n- '\\' needs extending to work with the block editor, for now, \nuse parenthesis for comments \n- make an 'm' word for forgetting all words defined since the\neditor was invoked.\n- add multi line insertion mode\n- Add to an editor vocabulary, which will need the vocabulary\nsystem to exist.\n- Using 'page' should be optional as not all terminals support\nANSI escape codes - thanks to CMD.EXE. Damned Windows.\n- How line numbers are printed out should be investigated,\nalso I should refactor 'dump' to use a similar line number system.\n- Format the output of list better, put a nice box around it.\n\nAdapted from http:\/\/retroforth.org\/pages\/?PortsOfRetroEditor )\n\n \n: help ( @todo renamed to 'h' once vocabularies are implemented )\npage cr\n\" Block Editor Help Menu\n\n n move to next block\n p move to previous block\n # d delete line in current block\n x erase current block\n e evaluate current block\n # i insert line\n # #2 ia insert at line #2 at column #\n q quit editor loop\n # b set block number\n s save block and write it out\n\n -- press any key to continue -- \" cr ( \" )\nchar drop ;\n\n: (block) blk @ block ; \n: (line) c\/l * (block) + ; ( n -- c-addr : push current line address )\n: (clean) \n\t(block) b\/buf\n\t2dup nl bl subst\n\t2dup cret bl subst\n\t 0 bl subst ;\n: n blk @ 1+ block ;\n: p blk @ 1- block ;\n: d (line) c\/l bl fill ; \n: x (block) b\/buf bl fill ;\n: s update save-buffers ;\n: q rdrop rdrop ;\n: e blk @ load char drop ;\n: ia c\/l * + dup b\/buf swap - >r (block) + r> accept (clean) ; \n: i 0 swap ia ;\n: editor\n\t1 block\n\tbegin\n\t\tpostpone [ ( need to be in command mode )\n\t\tpage cr\n\t\t\" BLOCK EDITOR: TYPE 'HELP' FOR A LIST OF COMMANDS\" cr\n\t\tblk @ list\n\t\t\" CURRENT BLOCK: \" blk @ . cr\n\t\tread\n\tagain ;\n\n( Extra niceties )\nc\/l string yank\nyank bl fill\n: u update ;\n: b block ;\n: l blk @ list ;\n: y (line) yank >r swap r> cmove ;\n: c (line) yank cmove ;\n: ct swap y c ;\n\nhide{ (block) (line) (clean) yank }hide\n\n( ==================== Block Editor ========================== )\n\nhere fence ! ( final fence - works before this cannot be forgotten )\n\n\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"24f834492fa25ab4f2cd12b8b5ad54903eae5241","subject":"Formatting bug.","message":"Formatting bug.","repos":"rbsexton\/gecko,rbsexton\/gecko,rbsexton\/gecko","old_file":"tiny\/basic\/forth\/startup.fth","new_file":"tiny\/basic\/forth\/startup.fth","new_contents":"(( App Startup ))\n\n0 value JT \\ The Jumptable\n\n\\ -------------------------------------------\n\\ The word that sets everything up.\n\\ This runs before the intro banner, after\n\\ Init-multi.\n\\ -------------------------------------------\n: StartApp\n\thex\n\tinit-dp @ dp ! \\ Set the dictionary pointer so that we can function.\n\t\\ I have no idea why I am doing this instead of the compilation system.\n\n\t1 getruntimelinks to jt\n\t.\" StartApp!\" \n\n\t4 [ SCSSCR _SCS + ] literal ! \\ Set deepsleep\n\t\t\t\n;\n\n\\ ------------------------------------------\n\\ Application code\n\\ ------------------------------------------\nstruct tod\n 1 field h\n 1 field m\n 1 field s\nend-struct\n \nudata\ncreate hms tod allot\ncreate dhms tod allot\ncdata\n\n: +CAP ( n max -- n ) >R 1 + dup r> = if drop 0 then ; \n\n: ADVANCE ( tod -- )\n dup s c@ #60 +cap 2dup swap s c! \\ Advance the seconds. base n -- \n if drop exit then\n \n dup m c@ #60 +cap 2dup swap m c! \\ advance minutes\n if drop exit then\n\n dup h c@ #24 +cap 2dup swap h c! \\ advance minutes\n\n 2drop \n;\n\n: DADVANCE ( tod -- )\n dup s c@ #100 +cap 2dup swap s c! \\ Advance the seconds. base n -- \n if drop exit then\n \n dup m c@ #100 +cap 2dup swap m c! \\ advance minutes\n if drop exit then\n\n dup h c@ #10 +cap 2dup swap h c! \\ advance minutes\n\n 2drop \n;\n\n\\ ----------------------------------------------\n\\ Tools for writing to the LCD\n\\ ----------------------------------------------\n: LCD#! ( n -- ) jt LCD_# @ swap call1-- ;\n: LCD$! ( addr -- ) jt LCD_Wr @ swap call1-- ; \n\nvariable thecount\n\n(( Sample code for demonstrating messages ))\n: wakestart 1 $10 wakereq drop ; \\ Request a wake \n: wakestop 1 0 wakereq drop ; \\ No more, please. \n\n: COUNT-WORD\n wakestart\n begin\n pause\n thecount dup @ 1+ dup lcd#! swap ! \n stop \n again\n;\n\n: COUNT-WORDd\n begin\n pause self msg? if get-message drop \\ We don't care who sent it.\n case \n 0 of wakestop endof\n 1 of wakestart endof\n endcase\n then\n\n thecount dup @ 1+ dup lcd#! swap ! \n stop \n again\n;\n\n\\ --------------------------------------------------------------------\n\\ Keeping time.\n\\ --------------------------------------------------------------------\ntask TOPTASK \n\n: TOPLCDOUT hms dup h c@ #100 * swap m c@ + lcd#! ; \n\n: TOPWORD\n 0 $10 wakereq drop \\ The first Second. \n begin\n pause\n toplcdout \n hms advance\n 2 $10 wakereq drop \\ Relative step\n again\n; \n\n\n\\ --------------------------------------------------------------------\n\\ Decimal Time\n\\ --------------------------------------------------------------------\n\ntask BOTTASK\n\n: BOTWORD\n 1 err interp-next wakereq drop \n begin\n pause\n dhms dadvance\n botlcd dms$ drop lcd$!\n 3 err interp-next wakereq drop \n again\n; \n\n: BOTLCD dhms\n dup h c@ #10000 *\n over m c@ #100 * +\n swap s c@ + ;\n\n\\ Include the terminating null.\n: dms$ base @ >R decimal s>d <# 0 hold # # $20 hold # # $20 hold # #> R> base ! ; \n\n: interp-next ( addr -- ) \\ A fixed version. Returns amount to step\n dup @ \\ err\n #103 - dup 1 > if swap ! #13 exit then\n \\ Otherwise, we need to adjust\n #125 + swap ! #14 \n;\n\n: CLOCKSTART\n ['] topword toptask initiate\n ['] botword bottask initiate \n;\n\nvariable err \n\n: COUNT-DT\n 0 err interp-next wakereq drop \\ Don't keep the return code.\n begin \n pause\n thecount dup @ 1 #9999 +cap dup lcd#! swap ! \n 2 err interp-next wakereq drop \\ Don't keep the return code. \n again\n;\n\n\n\n\n((\ntask foo \n' count-word foo initiate\n\n\n\n\n))\n\n \n\n\n","old_contents":"(( App Startup ))\n\n0 value JT \\ The Jumptable\n\n\\ -------------------------------------------\n\\ The word that sets everything up.\n\\ This runs before the intro banner, after\n\\ Init-multi.\n\\ -------------------------------------------\n: StartApp\n\thex\n\tinit-dp @ dp ! \\ Set the dictionary pointer so that we can function.\n\t\\ I have no idea why I am doing this instead of the compilation system.\n\n\t1 getruntimelinks to jt\n\t.\" StartApp!\" \n\n\t4 [ SCSSCR _SCS + ] literal ! \\ Set deepsleep\n\t\t\t\n;\n\n\\ ------------------------------------------\n\\ Application code\n\\ ------------------------------------------\nstruct tod\n 1 field h\n 1 field m\n 1 field s\nend-struct\n \nudata\ncreate hms tod allot\ncreate dhms tod allot\ncdata\n\n: +CAP ( n max -- n ) >R 1 + dup r> = if drop 0 then ; \n\n: ADVANCE ( tod -- )\n dup s c@ #60 +cap 2dup swap s c! \\ Advance the seconds. base n -- \n if drop exit then\n \n dup m c@ #60 +cap 2dup swap m c! \\ advance minutes\n if drop exit then\n\n dup h c@ #24 +cap 2dup swap h c! \\ advance minutes\n\n 2drop \n;\n\n: DADVANCE ( tod -- )\n dup s c@ #100 +cap 2dup swap s c! \\ Advance the seconds. base n -- \n if drop exit then\n \n dup m c@ #100 +cap 2dup swap m c! \\ advance minutes\n if drop exit then\n\n dup h c@ #10 +cap 2dup swap h c! \\ advance minutes\n\n 2drop \n;\n\n\\ ----------------------------------------------\n\\ Tools for writing to the LCD\n\\ ----------------------------------------------\n: LCD#! ( n -- ) jt LCD_# @ swap call1-- ;\n: LCD$! ( addr -- ) jt LCD_Wr @ swap call1-- ; \n\nvariable thecount\n\n(( Sample code for demonstrating messages ))\n: wakestart 1 $10 wakereq drop ; \\ Request a wake \n: wakestop 1 0 wakereq drop ; \\ No more, please. \n\n: COUNT-WORD\n wakestart\n begin\n pause\n thecount dup @ 1+ dup lcd#! swap ! \n stop \n again\n;\n\n: COUNT-WORDd\n begin\n pause self msg? if get-message drop \\ We don't care who sent it.\n case \n 0 of wakestop endof\n 1 of wakestart endof\n endcase\n then\n\n thecount dup @ 1+ dup lcd#! swap ! \n stop \n again\n;\n\n\\ --------------------------------------------------------------------\n\\ Keeping time.\n\\ --------------------------------------------------------------------\ntask TOPTASK \n\n: TOPLCDOUT hms dup h c@ #100 * swap m c@ + lcd#! ; \n\n: TOPWORD\n 0 $10 wakereq drop \\ The first Second. \n begin\n pause\n toplcdout \n hms advance\n 2 $10 wakereq drop \\ Relative step\n again\n; \n\n\n\\ --------------------------------------------------------------------\n\\ Decimal Time\n\\ --------------------------------------------------------------------\n\ntask BOTTASK\n\n: BOTWORD\n 1 err interp-next wakereq drop \n begin\n pause\n dhms dadvance\n botlcd dms$ drop lcd$!\n 3 err interp-next wakereq drop \n again\n; \n\n: BOTLCD dhms\n dup h c@ #1000 *\n over m c@ #100 * +\n swap s c@ + ;\n\n\\ Include the terminating null.\n: dms$ base @ >R decimal s>d <# 0 hold # # $20 hold # # $20 hold # #> R> base ! ; \n\n: interp-next ( addr -- ) \\ A fixed version. Returns amount to step\n dup @ \\ err\n #103 - dup 1 > if swap ! #13 exit then\n \\ Otherwise, we need to adjust\n #125 + swap ! #14 \n;\n\n: CLOCKSTART\n ['] topword toptask initiate\n ['] botword bottask initiate \n;\n\nvariable err \n\n: COUNT-DT\n 0 err interp-next wakereq drop \\ Don't keep the return code.\n begin \n pause\n thecount dup @ 1 #9999 +cap dup lcd#! swap ! \n 2 err interp-next wakereq drop \\ Don't keep the return code. \n again\n;\n\n\n\n\n((\ntask foo \n' count-word foo initiate\n\n\n\n\n))\n\n \n\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"2b4c5fde13d1f626084b39e71f1ec5e6deca7cf9","subject":"New calls for returning to priv mode, and MPU stuffing.","message":"New calls for returning to priv mode, and MPU stuffing.","repos":"rbsexton\/sockpuppet,rbsexton\/sockpuppet","old_file":"forth\/SAPI-core.fth","new_file":"forth\/SAPI-core.fth","new_contents":"\\ Wrappers for SAPI Core functions\n\\ SVC 0: Return the version of the API in use.\n\\ SVC 1: Return the address of the shared variables table\n\\ SVC 2: putchar\n\\ SVC 3: getchar\n\\ SVC 4: charsavail\n\n\\ SVC 5: LaunchUserApp\n\\ SVC 6: Reserved\n\\ SVC 7: Reserved\n\n\\ SVC 8: Watchdog Refresh\n\\ SVC 9: Return Millisecond ticker value.\n\\ SVC 10: The number of CPU cycles consumed in the last second.\n\n\\ 2-4 are for use by the serial io routines, and are \n\\ defined elsewhere.\n\n\\ Note that the system call number is embedded into the instruction,\n\\ so this is not so easily parameterized.\n\n#0 equ SAPI_VEC_VERSION\n#1 equ SAPI_VEC_VARS\n#2 equ SAPI_VEC_PUTCHAR\n#3 equ SAPI_VEC_GETCHAR\n#4 equ SAPI_VEC_CHARSAVAIL\n#5 equ SAPI_VEC_STARTAPP\n#6 equ SAPI_VEC_PRIVMODE\n#7 equ SAPI_VEC_MPULOAD\n#8 equ SAPI_VEC_PETWATCHDOG\n#9 equ SAPI_VEC_USAGE\n#10 equ SAPI_VEC_GETMS\n\n\\ **********************************************************************\n\\ SVC 0: Return the version of the API in use.\n\\ **********************************************************************\nCODE SAPI-Version \\ -- n \n\t\\ Push TOS, and place the result there.\t\n\tsvc # SAPI_VEC_VERSION \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 1: Get the address of the shared variable list\n\\ **********************************************************************\nCODE GetSharedVars \\ -- n \n\tsvc # SAPI_VEC_VARS \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 5: Do a stack switch and startup the user App. Its a one-way\n\\ trip, so don't worry about stack cleanup.\n\\ **********************************************************************\nCODE RestartForth ( c-addr ) \\ -- \n\tmov r0, tos\n\tsvc # SAPI_VEC_STARTAPP\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 6: Request Privileged Mode. In some systems, this is a huge\n\\ Security hole.\n\\ **********************************************************************\nCODE privmode \\ -- \n\tsvc # SAPI_VEC_PRIVMODE\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 7: Ask for MPU entry updates.\n\\ **********************************************************************\nCODE MPULoad \\ -- \n\tmov r0, tos\n\tsvc # SAPI_VEC_MPULOAD\n\tldr tos, [ psp ], # $04\t\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 8: Refresh the watchdog\n\\ **********************************************************************\nCODE PetWatchDog \\ -- \n\tsvc # SAPI_VEC_PETWATCHDOG\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 9: Return Millisecond ticker value.\n\\ **********************************************************************\nCODE Ticks \\ -- n \n\tsvc # SAPI_VEC_GETMS\n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 10: The number of CPU cycles consumed in the last second.\n\\ **********************************************************************\nCODE GetUsage \\ -- n \n\tsvc # SAPI_VEC_USAGE\n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n","old_contents":"\\ Wrappers for SAPI Core functions\n\\ SVC 0: Return the version of the API in use.\n\\ SVC 1: Return the address of the shared variables table\n\\ SVC 2: putchar\n\\ SVC 3: getchar\n\\ SVC 4: charsavail\n\n\\ SVC 5: LaunchUserApp\n\\ SVC 6: Reserved\n\\ SVC 7: Reserved\n\n\\ SVC 8: Watchdog Refresh\n\\ SVC 9: Return Millisecond ticker value.\n\\ SVC 10: The number of CPU cycles consumed in the last second.\n\n\\ 2-4 are for use by the serial io routines, and are \n\\ defined elsewhere.\n\n\\ Note that the system call number is embedded into the instruction,\n\\ so this is not so easily parameterized.\n\n#0 equ SAPI_VEC_VERSION\n#1 equ SAPI_VEC_VARS\n#2 equ SAPI_VEC_PUTCHAR\n#3 equ SAPI_VEC_GETCHAR\n#4 equ SAPI_VEC_CHARSAVAIL\n#5 equ SAPI_VEC_STARTAPP\n\n#8 equ SAPI_VEC_PETWATCHDOG\n#9 equ SAPI_VEC_USAGE\n#10 equ SAPI_VEC_GETMS\n\n\\ **********************************************************************\n\\ SVC 0: Return the version of the API in use.\n\\ **********************************************************************\nCODE SAPI-Version \\ -- n \n\t\\ Push TOS, and place the result there.\t\n\tsvc # SAPI_VEC_VERSION \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 1: Get the address of the shared variable list\n\\ **********************************************************************\nCODE GetSharedVars \\ -- n \n\tsvc # SAPI_VEC_VARS \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 5: Do a stack switch and startup the user App.\n\\ **********************************************************************\nCODE StartForth \\ -- \n\tsvc # SAPI_VEC_STARTAPP\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 8: Refresh the watchdog\n\\ **********************************************************************\nCODE PetWatchDog \\ -- \n\tsvc # SAPI_VEC_PETWATCHDOG\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 9: Return Millisecond ticker value.\n\\ **********************************************************************\nCODE Ticks \\ -- n \n\tsvc # SAPI_VEC_GETMS\n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 10: The number of CPU cycles consumed in the last second.\n\\ **********************************************************************\nCODE GetUsage \\ -- n \n\tsvc # SAPI_VEC_USAGE\n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"2ba0d9ee9f3b8c9acd2069e87752492393e4cd75","subject":"2 tests added for HOW-MANY-NB-\u2026","message":"2 tests added for HOW-MANY-NB-\u2026\n","repos":"bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas","old_file":"KataDiversion_tests.fth","new_file":"KataDiversion_tests.fth","new_contents":"\\ KataDiversion tests, in Forth\n\\ running tests:\n\\ gforth KataDiversion_tests.fth -e bye\n\nREQUIRE KataDiversion.fth\n\nVARIABLE ASSERT-COUNT\n\n: ASSERTS-INIT ( -- )\n 0 ASSERT-COUNT ! ;\n\n: ASSERTS-RESULT ( -- )\n ASSERT-COUNT @ . .\" assertions successfully passed.\" CR ;\n\n\\ destructive assert-equal\n: ASSERT-EQUAL-D ( n1 n2 -- )\n <> IF 1 ABORT\" AssertEqual: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-equal\n: ASSERT-EQUAL ( n1 n2 -- n1 n2 )\n 2DUP ASSERT-EQUAL-D ;\n\n\\ destructive assert-true\n: ASSERT-TRUE-D ( n -- )\n 0 = IF 1 ABORT\" AssertTrue: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-true\n: ASSERT-TRUE ( n -- n )\n DUP ASSERT-TRUE-D ;\n\n\\ destructive assert-false\n: ASSERT-False-D ( n -- )\n 0 <> IF 1 ABORT\" AssertFalse: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-false\n: ASSERT-FALSE ( n -- n )\n DUP ASSERT-FALSE-D ;\n\n\\ ---- tests ----\n\nASSERTS-INIT\n\n\\ EMPTY\nEMPTY DEPTH 0 ASSERT-EQUAL-D\nEMPTY EMPTY DEPTH 0 ASSERT-EQUAL-D\n0 EMPTY DEPTH 0 ASSERT-EQUAL-D\n1 2 3 4 EMPTY DEPTH 0 ASSERT-EQUAL-D\n\n\\ MAX-NB\n-1 MAX-NB 0 ASSERT-EQUAL-D\n 0 MAX-NB 0 ASSERT-EQUAL-D\n 1 MAX-NB 1 ASSERT-EQUAL-D\n 2 MAX-NB 3 ASSERT-EQUAL-D\n 3 MAX-NB 7 ASSERT-EQUAL-D\n\n\\ MAXPOW2\n 1 MAXPOW2 1 ASSERT-EQUAL-D\n 2 MAXPOW2 2 ASSERT-EQUAL-D\n 3 MAXPOW2 2 ASSERT-EQUAL-D\n 4 MAXPOW2 4 ASSERT-EQUAL-D\n 5 MAXPOW2 4 ASSERT-EQUAL-D\n 8 MAXPOW2 8 ASSERT-EQUAL-D\n 42 MAXPOW2 32 ASSERT-EQUAL-D\n2000 MAXPOW2 1024 ASSERT-EQUAL-D\n\n\\ ?NOT-TWO-ADJACENT-1-BITS\n 0 ?NOT-TWO-ADJACENT-1-BITS ASSERT-TRUE-D\n 1 ?NOT-TWO-ADJACENT-1-BITS ASSERT-TRUE-D\n 2 ?NOT-TWO-ADJACENT-1-BITS ASSERT-TRUE-D\n 3 ?NOT-TWO-ADJACENT-1-BITS ASSERT-FALSE-D\n 6 ?NOT-TWO-ADJACENT-1-BITS ASSERT-FALSE-D\n 7 ?NOT-TWO-ADJACENT-1-BITS ASSERT-FALSE-D\n 8 ?NOT-TWO-ADJACENT-1-BITS ASSERT-TRUE-D\n 11 ?NOT-TWO-ADJACENT-1-BITS ASSERT-FALSE-D\n 65 ?NOT-TWO-ADJACENT-1-BITS ASSERT-TRUE-D\n3072 ?NOT-TWO-ADJACENT-1-BITS ASSERT-FALSE-D\n\n\\ HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS\n0 HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS 0 ASSERT-EQUAL-D\n \\ 0, 1\n1 HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS 2 ASSERT-EQUAL-D\n \\ 00, 01, 10\n2 HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS 3 ASSERT-EQUAL-D\n \\ 000, 001, 010, 100, 101\n3 HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS 5 ASSERT-EQUAL-D\n \\ 0000, 0001, 0010, 0100, 0101, 1000, 1001, 1010\n4 HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS 8 ASSERT-EQUAL-D\n \\ 00000, 00001, 00010, 00100, 00101, 01000, 01001,\n \\ 01010, 10000, 10001, 10010, 10100, 10101\n5 HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS 13 ASSERT-EQUAL-D\n\n\nASSERTS-RESULT\n\\ ---------\n\n\n","old_contents":"\\ KataDiversion tests, in Forth\n\\ running tests:\n\\ gforth KataDiversion_tests.fth -e bye\n\nREQUIRE KataDiversion.fth\n\nVARIABLE ASSERT-COUNT\n\n: ASSERTS-INIT ( -- )\n 0 ASSERT-COUNT ! ;\n\n: ASSERTS-RESULT ( -- )\n ASSERT-COUNT @ . .\" assertions successfully passed.\" CR ;\n\n\\ destructive assert-equal\n: ASSERT-EQUAL-D ( n1 n2 -- )\n <> IF 1 ABORT\" AssertEqual: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-equal\n: ASSERT-EQUAL ( n1 n2 -- n1 n2 )\n 2DUP ASSERT-EQUAL-D ;\n\n\\ destructive assert-true\n: ASSERT-TRUE-D ( n -- )\n 0 = IF 1 ABORT\" AssertTrue: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-true\n: ASSERT-TRUE ( n -- n )\n DUP ASSERT-TRUE-D ;\n\n\\ destructive assert-false\n: ASSERT-False-D ( n -- )\n 0 <> IF 1 ABORT\" AssertFalse: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-false\n: ASSERT-FALSE ( n -- n )\n DUP ASSERT-FALSE-D ;\n\n\\ ---- tests ----\n\nASSERTS-INIT\n\n\\ EMPTY\nEMPTY DEPTH 0 ASSERT-EQUAL-D\nEMPTY EMPTY DEPTH 0 ASSERT-EQUAL-D\n0 EMPTY DEPTH 0 ASSERT-EQUAL-D\n1 2 3 4 EMPTY DEPTH 0 ASSERT-EQUAL-D\n\n\\ MAX-NB\n-1 MAX-NB 0 ASSERT-EQUAL-D\n 0 MAX-NB 0 ASSERT-EQUAL-D\n 1 MAX-NB 1 ASSERT-EQUAL-D\n 2 MAX-NB 3 ASSERT-EQUAL-D\n 3 MAX-NB 7 ASSERT-EQUAL-D\n\n\\ MAXPOW2\n 1 MAXPOW2 1 ASSERT-EQUAL-D\n 2 MAXPOW2 2 ASSERT-EQUAL-D\n 3 MAXPOW2 2 ASSERT-EQUAL-D\n 4 MAXPOW2 4 ASSERT-EQUAL-D\n 5 MAXPOW2 4 ASSERT-EQUAL-D\n 8 MAXPOW2 8 ASSERT-EQUAL-D\n 42 MAXPOW2 32 ASSERT-EQUAL-D\n2000 MAXPOW2 1024 ASSERT-EQUAL-D\n\n\\ ?NOT-TWO-ADJACENT-1-BITS\n 0 ?NOT-TWO-ADJACENT-1-BITS ASSERT-TRUE-D\n 1 ?NOT-TWO-ADJACENT-1-BITS ASSERT-TRUE-D\n 2 ?NOT-TWO-ADJACENT-1-BITS ASSERT-TRUE-D\n 3 ?NOT-TWO-ADJACENT-1-BITS ASSERT-FALSE-D\n 6 ?NOT-TWO-ADJACENT-1-BITS ASSERT-FALSE-D\n 7 ?NOT-TWO-ADJACENT-1-BITS ASSERT-FALSE-D\n 8 ?NOT-TWO-ADJACENT-1-BITS ASSERT-TRUE-D\n 11 ?NOT-TWO-ADJACENT-1-BITS ASSERT-FALSE-D\n 65 ?NOT-TWO-ADJACENT-1-BITS ASSERT-TRUE-D\n3072 ?NOT-TWO-ADJACENT-1-BITS ASSERT-FALSE-D\n\n\\ HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS\n \\ 0, 1\n1 HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS 2 ASSERT-EQUAL-D\n \\ 00, 01, 10\n2 HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS 3 ASSERT-EQUAL-D\n \\ 000, 001, 010, 100, 101\n3 HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS 5 ASSERT-EQUAL-D\n \\ 0000, 0001, 0010, 0100, 0101, 1000, 1001, 1010\n4 HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS 8 ASSERT-EQUAL-D\n\n\nASSERTS-RESULT\n\\ ---------\n\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"42c0616fdd333d05f0ba08566b790d1b57cd4f5a","subject":"Good thing about these examples is that no one uses them, so they can stay broken for months without anyone noticing.","message":"Good thing about these examples is that no one uses them, so they can\nstay broken for months without anyone noticing.\n\nThe boot-conf command was changed as to reproduce the behavior of builtin\nloader words precisely. As a result, it now always need an argument, possibly\n0 indicating that no other arguments are being passed. This broke in a\nnon-deterministic way (ie, it could go on working as if everything was fine).\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"share\/examples\/bootforth\/menuconf.4th","new_file":"share\/examples\/bootforth\/menuconf.4th","new_contents":"\\ Simple greeting screen, presenting basic options.\n\\ XXX This is far too trivial - I don't have time now to think\n\\ XXX about something more fancy... :-\/\n\\ $FreeBSD$\n\n: title\n\tf_single\n\t60 11 10 4 box\n\t29 4 at-xy 15 fg 7 bg\n\t.\" Welcome to BootFORTH!\"\n\tme\n;\n\n: menu\n\t2 fg\n\t20 7 at-xy \n\t.\" 1. Start FreeBSD with \/boot\/stable.conf.\"\n 20 8 at-xy\n .\" 2. Start FreeBSD with \/boot\/current.conf.\"\n\t20 9 at-xy\n\t.\" 3. Start FreeBSD with standard configuration. \"\n\t20 10 at-xy\n\t.\" 4. Reboot.\"\n\tme\n;\n\n: tkey\t( d -- flag | char )\n\tseconds +\n\tbegin 1 while\n\t dup seconds u< if\n\t\tdrop\n\t\t-1\n\t\texit\n\t then\n\t key? if\n\t\tdrop\n\t\tkey\n\t\texit\n\t then\n\trepeat\n;\n\n: prompt\n\t14 fg\n\t20 12 at-xy\n\t.\" Enter your option (1,2,3,4): \"\n\t10 tkey\n\tdup 32 = if\n\t drop key\n\tthen\n\tdup 0< if\n\t drop 51\n\tthen\n\tdup emit\n\tme\n;\n\n: help_text\n 10 18 at-xy .\" * Choose 1 or 2 to run special configuration file.\"\n\t10 19 at-xy .\" * Choose 3 to proceed with standard bootstrapping.\"\n\t12 20 at-xy .\" See '?' for available commands, and 'words' for\"\n\t12 21 at-xy .\" complete list of Forth words.\"\n\t10 22 at-xy .\" * Choose 4 in order to warm boot your machine.\"\n;\n\n: (reboot) 0 reboot ;\n\n: main_menu\n\tbegin 1 while\n\t\tclear\n\t\tf_double\n\t\t79 23 1 1 box\n\t\ttitle\n\t\tmenu\n\t\thelp_text\n\t\tprompt\n\t\tcr cr cr\n\t\tdup 49 = if\n\t\t\tdrop\n\t\t\t1 25 at-xy cr\n\t\t\t.\" Loading \/boot\/stable.conf. Please wait...\" cr\n\t\t\ts\" \/boot\/stable.conf\" read-conf\n\t\t\t0 boot-conf exit\n\t\tthen\n\t\tdup 50 = if\n\t\t\tdrop\n\t\t\t1 25 at-xy cr\n\t\t\t.\" Loading \/boot\/current.conf. Please wait...\" cr\n\t\t\ts\" \/boot\/current.conf\" read-conf\n\t\t\t0 boot-conf exit\n\t\tthen\n\t\tdup 51 = if\n\t\t\tdrop\n\t\t\t1 25 at-xy cr\n\t\t\t.\" Proceeding with standard boot. Please wait...\" cr\n\t\t\t0 boot-conf exit\n\t\tthen\n\t\tdup 52 = if\n\t\t\tdrop\n\t\t\t1 25 at-xy cr\n\t\t\t['] (reboot) catch abort\" Error rebooting\"\n\t\tthen\n\t\t20 12 at-xy\n\t\t.\" Key \" emit .\" is not a valid option!\"\n\t\t20 13 at-xy\n\t\t.\" Press any key to continue...\"\n\t\tkey drop\n\trepeat\n;\n\n","old_contents":"\\ Simple greeting screen, presenting basic options.\n\\ XXX This is far too trivial - I don't have time now to think\n\\ XXX about something more fancy... :-\/\n\\ $FreeBSD$\n\n: title\n\tf_single\n\t60 11 10 4 box\n\t29 4 at-xy 15 fg 7 bg\n\t.\" Welcome to BootFORTH!\"\n\tme\n;\n\n: menu\n\t2 fg\n\t20 7 at-xy \n\t.\" 1. Start FreeBSD with \/boot\/stable.conf.\"\n 20 8 at-xy\n .\" 2. Start FreeBSD with \/boot\/current.conf.\"\n\t20 9 at-xy\n\t.\" 3. Start FreeBSD with standard configuration. \"\n\t20 10 at-xy\n\t.\" 4. Reboot.\"\n\tme\n;\n\n: tkey\t( d -- flag | char )\n\tseconds +\n\tbegin 1 while\n\t dup seconds u< if\n\t\tdrop\n\t\t-1\n\t\texit\n\t then\n\t key? if\n\t\tdrop\n\t\tkey\n\t\texit\n\t then\n\trepeat\n;\n\n: prompt\n\t14 fg\n\t20 12 at-xy\n\t.\" Enter your option (1,2,3,4): \"\n\t10 tkey\n\tdup 32 = if\n\t drop key\n\tthen\n\tdup 0< if\n\t drop 51\n\tthen\n\tdup emit\n\tme\n;\n\n: help_text\n 10 18 at-xy .\" * Choose 1 or 2 to run special configuration file.\"\n\t10 19 at-xy .\" * Choose 3 to proceed with standard bootstrapping.\"\n\t12 20 at-xy .\" See '?' for available commands, and 'words' for\"\n\t12 21 at-xy .\" complete list of Forth words.\"\n\t10 22 at-xy .\" * Choose 4 in order to warm boot your machine.\"\n;\n\n: (reboot) 0 reboot ;\n\n: main_menu\n\tbegin 1 while\n\t\tclear\n\t\tf_double\n\t\t79 23 1 1 box\n\t\ttitle\n\t\tmenu\n\t\thelp_text\n\t\tprompt\n\t\tcr cr cr\n\t\tdup 49 = if\n\t\t\tdrop\n\t\t\t1 25 at-xy cr\n\t\t\t.\" Loading \/boot\/stable.conf. Please wait...\" cr\n\t\t\ts\" \/boot\/stable.conf\" read-conf\n\t\t\tboot-conf exit\n\t\tthen\n\t\tdup 50 = if\n\t\t\tdrop\n\t\t\t1 25 at-xy cr\n\t\t\t.\" Loading \/boot\/current.conf. Please wait...\" cr\n\t\t\ts\" \/boot\/current.conf\" read-conf\n\t\t\tboot-conf exit\n\t\tthen\n\t\tdup 51 = if\n\t\t\tdrop\n\t\t\t1 25 at-xy cr\n\t\t\t.\" Proceeding with standard boot. Please wait...\" cr\n\t\t\tboot-conf exit\n\t\tthen\n\t\tdup 52 = if\n\t\t\tdrop\n\t\t\t1 25 at-xy cr\n\t\t\t['] (reboot) catch abort\" Error rebooting\"\n\t\tthen\n\t\t20 12 at-xy\n\t\t.\" Key \" emit .\" is not a valid option!\"\n\t\t20 13 at-xy\n\t\t.\" Press any key to continue...\"\n\t\tkey drop\n\trepeat\n;\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"90b705ad03503dd10a7e9bfaeee8f64c616049f1","subject":"Re-instate DEFER benchmark","message":"Re-instate DEFER benchmark\n","repos":"rm-hull\/byok3,rm-hull\/byok3","old_file":"core\/src\/main\/resources\/forth\/bench.fth","new_file":"core\/src\/main\/resources\/forth\/bench.fth","new_contents":"\\ @(#) bench.fth 97\/12\/10 1.1\n\\ Benchmark Forth\n\\ by Phil Burk\n\\ 11\/17\/95\n\\\n\\ pForthV9 on Indy, compiled with gcc\n\\ bench1 took 15 seconds\n\\ bench2 took 16 seconds\n\\ bench3 took 17 seconds\n\\ bench4 took 17 seconds\n\\ bench5 took 19 seconds\n\\ sieve took 4 seconds\n\\\n\\ Darren Gibbs reports that on an SGI Octane loaded with multiple users:\n\\ bench1 took 2.8sec\n\\ bench2 took 2.7\n\\ bench3 took 2.9\n\\ bench4 took 2.1\n\\ bench 5 took 2.5\n\\ seive took .6\n\\\n\\ HForth on Mac Quadra 800, 68040\n\\ bench1 took 1.73 seconds\n\\ bench2 took 6.48 seconds\n\\ bench3 took 2.65 seconds\n\\ bench4 took 2.50 seconds\n\\ bench5 took 1.91 seconds\n\\ sieve took 0.45 seconds\n\\\n\\ pForthV9 on Mac Quadra 800\n\\ bench1 took 40 seconds\n\\ bench2 took 43 seconds\n\\ bench3 took 43 seconds\n\\ bench4 took 44 seconds\n\\ bench5 took 42 seconds\n\\ sieve took 20 seconds\n\\\n\\ pForthV9 on PB5300, 100 MHz PPC 603 based Mac Powerbook\n\\ bench1 took 8.6 seconds\n\\ bench2 took 9.0 seconds\n\\ bench3 took 9.7 seconds\n\\ bench4 took 8.8 seconds\n\\ bench5 took 10.3 seconds\n\\ sieve took 2.3 seconds\n\\\n\\ HForth on PB5300\n\\ bench1 took 1.1 seconds\n\\ bench2 took 3.6 seconds\n\\ bench3 took 1.7 seconds\n\\ bench4 took 1.2 seconds\n\\ bench5 took 1.3 seconds\n\\ sieve took 0.2 seconds\n\n\\ anew task-bench.fth\n\ndecimal\n\n\\ benchmark primitives\ncreate #do 2000000 ,\n\n: t1 #do @ 0 do loop ;\n: t2 23 45 #do @ 0 do swap loop 2drop ;\n: t3 23 #do @ 0 do dup drop loop drop ;\n: t4 23 45 #do @ 0 do over drop loop 2drop ;\n: t5 #do @ 0 do 23 45 + drop loop ;\n: t6 23 #do @ 0 do >r r> loop drop ;\n: t7 23 45 67 #do @ 0 do rot loop 2drop drop ;\n: t8 #do @ 0 do 23 2* drop loop ;\n: t9 #do @ 10 \/ 0 do 23 5 \/mod 2drop loop ;\n: t10 #do #do @ 0 do dup @ drop loop drop ;\n\n: foo ( noop ) ;\n: t11 #do @ 0 do foo loop ;\n\n\\ more complex benchmarks -----------------------\n\n\\ BENCH1 - sum data ---------------------------------------\ncreate data1 23 , 45 , 67 , 89 , 111 , 222 , 333 , 444 ,\n: sum.cells ( addr num -- sum )\n\t0 swap \\ sum\n\t0 DO\n\t\tover \\ get address\n\t\ti cells + @ +\n\tLOOP\n\tswap drop\n;\n\n: bench1 ( -- )\n\t200000 0\n\tDO\n\t\tdata1 8 sum.cells drop\n\tLOOP\n;\n\n\\ BENCH2 - recursive factorial --------------------------\n: factorial ( n -- n! )\n\tdup 1 >\n\tIF\n\t\tdup 1- recurse *\n\tELSE\n\t\tdrop 1\n\tTHEN\n;\n\n: bench2 ( -- )\n\t200000 0\n\tDO\n\t\t10 factorial drop\n\tLOOP\n;\n\n\\ BENCH3 - DEFER ----------------------------------\ndefer calc.answer\n: answer ( n -- m )\n\tdup +\n\t$a5a5 xor\n\t1000 max\n;\n' answer is calc.answer\n: bench3\n\t1500000 0\n\tDO\n\t\ti calc.answer drop\n\tLOOP\n;\n\n\\ BENCH4 - locals ---------------------------------\n: use.locals { x1 x2 | aa bb -- result }\n\tx1 2* -> aa\n\tx2 2\/ -> bb\n\tx1 aa *\n\tx2 bb * +\n;\n\n: bench4\n\t400000 0\n\tDO\n\t\t234 567 use.locals drop\n\tLOOP\n;\n\n\\ BENCH5 - string compare -------------------------------\n: match.strings { $s1 $s2 | adr1 len1 adr2 len2 -- flag }\n\t$s1 count -> len1 -> adr1\n\t$s2 count -> len2 -> adr2\n\tlen1 len2 -\n\tIF\n\t\tFALSE\n\tELSE\n\t\tTRUE\n\t\tlen1 0\n\t\tDO\n\t\t\tadr1 i + c@\n\t\t\tadr2 i + c@ -\n\t\t\tIF\n\t\t\t\tdrop FALSE\n\t\t\t\tleave\n\t\t\tTHEN\n\t\tLOOP\n\tTHEN\n;\n\n: bench5 ( -- )\n\t60000 0\n\tDO\n\t\t\" This is a string. X foo\"\n\t\t\" This is a string. Y foo\" match.strings drop\n\tLOOP\n;\n\n\\ SIEVE OF ERATOSTHENES from BYTE magazine -----------------------\n\nDECIMAL 8190 CONSTANT TSIZE\n\nVARIABLE FLAGS TSIZE ALLOT\n\n: ( --- #primes ) FLAGS TSIZE 1 FILL\n 0 TSIZE 0\n DO ( n ) I FLAGS + C@\n IF I DUP + 3 + DUP I + ( I2*+3 I3*+3 )\n BEGIN DUP TSIZE < ( same flag )\n WHILE 0 OVER FLAGS + C! ( i' i'' ) OVER +\n REPEAT 2DROP 1+\n THEN\n LOOP ;\n\n: SIEVE .\" 10 iterations \" CR 0 10 0\n DO swap drop\n LOOP . .\" primes \" CR ;\n\n: SIEVE50 .\" 50 iterations \" CR 0 50 0\n DO swap drop\n LOOP . .\" primes \" CR ;\n\n\\ 10 iterations\n\\ 21.5 sec Amiga Multi-Forth Indirect Threaded\n\\ 8.82 sec Amiga 1000 running JForth\n\\ ~5 sec SGI Indy running pForthV9","old_contents":"\\ @(#) bench.fth 97\/12\/10 1.1\n\\ Benchmark Forth\n\\ by Phil Burk\n\\ 11\/17\/95\n\\\n\\ pForthV9 on Indy, compiled with gcc\n\\ bench1 took 15 seconds\n\\ bench2 took 16 seconds\n\\ bench3 took 17 seconds\n\\ bench4 took 17 seconds\n\\ bench5 took 19 seconds\n\\ sieve took 4 seconds\n\\\n\\ Darren Gibbs reports that on an SGI Octane loaded with multiple users:\n\\ bench1 took 2.8sec\n\\ bench2 took 2.7\n\\ bench3 took 2.9\n\\ bench4 took 2.1\n\\ bench 5 took 2.5\n\\ seive took .6\n\\\n\\ HForth on Mac Quadra 800, 68040\n\\ bench1 took 1.73 seconds\n\\ bench2 took 6.48 seconds\n\\ bench3 took 2.65 seconds\n\\ bench4 took 2.50 seconds\n\\ bench5 took 1.91 seconds\n\\ sieve took 0.45 seconds\n\\\n\\ pForthV9 on Mac Quadra 800\n\\ bench1 took 40 seconds\n\\ bench2 took 43 seconds\n\\ bench3 took 43 seconds\n\\ bench4 took 44 seconds\n\\ bench5 took 42 seconds\n\\ sieve took 20 seconds\n\\\n\\ pForthV9 on PB5300, 100 MHz PPC 603 based Mac Powerbook\n\\ bench1 took 8.6 seconds\n\\ bench2 took 9.0 seconds\n\\ bench3 took 9.7 seconds\n\\ bench4 took 8.8 seconds\n\\ bench5 took 10.3 seconds\n\\ sieve took 2.3 seconds\n\\\n\\ HForth on PB5300\n\\ bench1 took 1.1 seconds\n\\ bench2 took 3.6 seconds\n\\ bench3 took 1.7 seconds\n\\ bench4 took 1.2 seconds\n\\ bench5 took 1.3 seconds\n\\ sieve took 0.2 seconds\n\n\\ anew task-bench.fth\n\ndecimal\n\n\\ benchmark primitives\ncreate #do 2000000 ,\n\n: t1 #do @ 0 do loop ;\n: t2 23 45 #do @ 0 do swap loop 2drop ;\n: t3 23 #do @ 0 do dup drop loop drop ;\n: t4 23 45 #do @ 0 do over drop loop 2drop ;\n: t5 #do @ 0 do 23 45 + drop loop ;\n: t6 23 #do @ 0 do >r r> loop drop ;\n: t7 23 45 67 #do @ 0 do rot loop 2drop drop ;\n: t8 #do @ 0 do 23 2* drop loop ;\n: t9 #do @ 10 \/ 0 do 23 5 \/mod 2drop loop ;\n: t10 #do #do @ 0 do dup @ drop loop drop ;\n\n: foo ( noop ) ;\n: t11 #do @ 0 do foo loop ;\n\n\\ more complex benchmarks -----------------------\n\n\\ BENCH1 - sum data ---------------------------------------\ncreate data1 23 , 45 , 67 , 89 , 111 , 222 , 333 , 444 ,\n: sum.cells ( addr num -- sum )\n\t0 swap \\ sum\n\t0 DO\n\t\tover \\ get address\n\t\ti cells + @ +\n\tLOOP\n\tswap drop\n;\n\n: bench1 ( -- )\n\t200000 0\n\tDO\n\t\tdata1 8 sum.cells drop\n\tLOOP\n;\n\n\\ BENCH2 - recursive factorial --------------------------\n: factorial ( n -- n! )\n\tdup 1 >\n\tIF\n\t\tdup 1- recurse *\n\tELSE\n\t\tdrop 1\n\tTHEN\n;\n\n: bench2 ( -- )\n\t200000 0\n\tDO\n\t\t10 factorial drop\n\tLOOP\n;\n\n\\ BENCH3 - DEFER ----------------------------------\n\\ defer calc.answer\n: answer ( n -- m )\n\tdup +\n\t$a5a5 xor\n\t1000 max\n;\n\\ ' answer is calc.answer\n: bench3\n\t1500000 0\n\tDO\n\t\t\\ i calc.answer drop\n\t\ti answer drop\n\tLOOP\n;\n\n\\ BENCH4 - locals ---------------------------------\n: use.locals { x1 x2 | aa bb -- result }\n\tx1 2* -> aa\n\tx2 2\/ -> bb\n\tx1 aa *\n\tx2 bb * +\n;\n\n: bench4\n\t400000 0\n\tDO\n\t\t234 567 use.locals drop\n\tLOOP\n;\n\n\\ BENCH5 - string compare -------------------------------\n: match.strings { $s1 $s2 | adr1 len1 adr2 len2 -- flag }\n\t$s1 count -> len1 -> adr1\n\t$s2 count -> len2 -> adr2\n\tlen1 len2 -\n\tIF\n\t\tFALSE\n\tELSE\n\t\tTRUE\n\t\tlen1 0\n\t\tDO\n\t\t\tadr1 i + c@\n\t\t\tadr2 i + c@ -\n\t\t\tIF\n\t\t\t\tdrop FALSE\n\t\t\t\tleave\n\t\t\tTHEN\n\t\tLOOP\n\tTHEN\n;\n\n: bench5 ( -- )\n\t60000 0\n\tDO\n\t\t\" This is a string. X foo\"\n\t\t\" This is a string. Y foo\" match.strings drop\n\tLOOP\n;\n\n\\ SIEVE OF ERATOSTHENES from BYTE magazine -----------------------\n\nDECIMAL 8190 CONSTANT TSIZE\n\nVARIABLE FLAGS TSIZE ALLOT\n\n: ( --- #primes ) FLAGS TSIZE 1 FILL\n 0 TSIZE 0\n DO ( n ) I FLAGS + C@\n IF I DUP + 3 + DUP I + ( I2*+3 I3*+3 )\n BEGIN DUP TSIZE < ( same flag )\n WHILE 0 OVER FLAGS + C! ( i' i'' ) OVER +\n REPEAT 2DROP 1+\n THEN\n LOOP ;\n\n: SIEVE .\" 10 iterations \" CR 0 10 0\n DO swap drop\n LOOP . .\" primes \" CR ;\n\n: SIEVE50 .\" 50 iterations \" CR 0 50 0\n DO swap drop\n LOOP . .\" primes \" CR ;\n\n\\ 10 iterations\n\\ 21.5 sec Amiga Multi-Forth Indirect Threaded\n\\ 8.82 sec Amiga 1000 running JForth\n\\ ~5 sec SGI Indy running pForthV9","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"694aaa795b5542fc525195c97e63d92f20b10d7a","subject":"Remove (erroneous) duplicate definition for SPACES","message":"Remove (erroneous) duplicate definition for SPACES\n","repos":"rm-hull\/byok3,rm-hull\/byok3","old_file":"core\/src\/main\/resources\/forth\/system.fth","new_file":"core\/src\/main\/resources\/forth\/system.fth","new_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\\n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n\n: COUNT dup 1+ swap c@ ;\n\n\\ Miscellaneous support words\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: <= ( a b -- f , true if A <= b ) > 0= ;\n: >= ( a b -- f , true if A >= b ) < 0= ;\n: NOT ( n -- !n , logical negation ) 0= ;\n: DNEGATE ( d -- -d , negate by doing 0-d )\n 0 swap -\n;\n: CELL+ ( n -- n+cell ) cell + ;\n: CELL- ( n -- n-cell ) cell - ;\n: CELL* ( n -- n*cell ) cells ;\n\n: CHAR+ ( n -- n+size_of_char ) 1+ ;\n: CHARS ( n -- n*size_of_char, don't do anything ) ; immediate\n\n\\ useful stack manipulation words\n: -ROT ( a b c -- c a b ) rot rot ;\n: 3DUP ( a b c -- a b c a b c ) 2 pick 2 pick 2 pick ;\n\n\\ ------------------------------------------------------------------\n: ID. ( nfa -- ) count 31 and type ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: PAD ( -- addr ) here 128 + ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n\n: BETWEEN ( n lo hi -- flag , true if between lo & hi )\n >r over r> > >r\n < r> or 0=\n;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: ? ( -- ) @ . ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ ' (lit) , cell 1- , ] +\n [ ' (lit) , cell 1- invert , ] and ;\n\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n: ALLOT ( nbytes -- , allot space in dictionary ) dp +! align ;\n\n: C, ( c -- ) here c! 1 dp +! ;\n\\ : W, ( w -- ) dp @ even-up dup dp ! w! 2 dp +! ;\n\\ : , ( n -- , lay into dictionary ) align here ! cell allot ;\n\n: SEE ( -- )\n ' dup\n >body swap >size\n disassemble ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token )\n [compile] literal ( compile a call to literal )\n ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick )\n ?comp ' [compile] literal\n; immediate\n\n: (DOES>) ( xt -- , modify previous definition to execute code at xt )\n latest >body \\ get address of code for new word\n 3 cell* + \\ offset to EXIT cell in create word\n ! \\ store execution token of DOES> code in new word\n;\n\n: DOES> ( -- , define execution code for CREATE word )\n 0 [compile] literal \\ dummy literal to hold xt\n here cell- \\ address of zero in literal\n compile (does>) \\ call (DOES>) from new creation word\n\t\t>r \\ move addrz to return stack so ; doesn't see stack garbage\n [compile] ; \\ terminate part of code before does>\n\t\tr>\n :noname ( addrz xt )\n compile rdrop \\ drop a stack frame (call becomes goto)\n swap ! \\ save execution token in literal\n; immediate\n\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 )\n swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 )\n dup cell+ @ swap @ ;\n\n: 2* ( n -- n*2 )\n 2 *\n;\n: 2\/ ( n -- n\/2 )\n 2 \/\n;\n\n\n\\ define some useful constants ------------------------------\n1 0= constant FALSE\n0 0= constant TRUE\n32 constant BL\n\n\\ Stack data structure ----------------------------------------\n\\ This is a general purpose stack utility used to implement necessary\n\\ stacks for the compiler or the user. Not real fast.\n\\ These stacks grow up which is different then normal.\n\\ cell 0 - stack pointer, offset from pfa of word\n\\ cell 1 - limit for range checking\n\\ cell 2 - first data location\n\n: :STACK ( #cells -- )\n CREATE 2 cells , ( offset of first data location )\n dup , ( limit for range checking, not currently used )\n cells cell+ allot ( allot an extra cell for safety )\n;\n\n: >STACK ( n stack -- , push onto stack, postincrement )\n dup @ 2dup cell+ swap ! ( -- n stack offset )\n + !\n;\n\n: STACK> ( stack -- n , pop , predecrement )\n dup @ cell- 2dup swap !\n + @\n;\n\n: STACK@ ( stack -- n , copy )\n dup @ cell- + @\n;\n\n: STACK.PICK ( index stack -- n , grab Nth from top of stack )\n dup @ cell- +\n swap cells - \\ offset for index\n @\n;\n: STACKP ( stack -- ptr , to next empty location on stack )\n\tdup @ +\n;\n\n: 0STACKP ( stack -- , clear stack)\n 8 swap !\n;\n\n32 :stack ustack\nustack 0stackp\n\n\\ Define JForth like words.\n: >US ustack >stack ;\n: US> ustack stack> ;\n: US@ ustack stack@ ;\n: 0USP ustack 0stackp ;\n\n\n\n\\ DO LOOP ------------------------------------------------\n\n3 constant do_flag\n4 constant leave_flag\n5 constant ?do_flag\n\n: DO ( -- , loop-back do_flag jump-from ?do_flag )\n ?comp\n compile (do)\n here >us do_flag >us ( for backward branch )\n; immediate\n\n: ?DO ( -- , loop-back do_flag jump-from ?do_flag , on user stack )\n ?comp\n ( leave address to set for forward branch )\n compile (?do)\n here 0 ,\n here >us do_flag >us ( for backward branch )\n >us ( for forward branch ) ?do_flag >us\n; immediate\n\n: LEAVE ( -- addr leave_flag )\n compile (leave)\n here 0 , >us\n leave_flag >us\n; immediate\n\n: LOOP-FORWARD ( -us- jump-from ?do_flag -- )\n BEGIN\n us@ leave_flag =\n us@ ?do_flag =\n OR\n WHILE\n us> leave_flag =\n IF\n us> here over - cell+ swap !\n ELSE\n us> dup\n here swap -\n cell+ swap !\n THEN\n REPEAT\n;\n\n: LOOP-BACK ( loop-addr do_flag -us- )\n us> do_flag ?pairs\n us> here - here\n !\n cell allot\n;\n\n: LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (loop)\n loop-forward loop-back\n; immediate\n\n\\ : DOTEST 5 0 do 333 . loop 888 . ;\n\\ : ?DOTEST0 0 0 ?do 333 . loop 888 . ;\n\\ : ?DOTEST1 5 0 ?do 333 . loop 888 . ;\n\n: +LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (+loop)\n loop-forward loop-back\n; immediate\n\n: UNLOOP ( loop-sys -r- )\n r> \\ save return pointer\n rdrop rdrop\n >r\n;\n\n\n: RECURSE ( ? -- ? , call the word currently being defined )\n latest compile,\n; immediate\n\n: SPACE bl emit ;\n: 0SP depth 0 ?do drop loop ;\n\n\\ : >NEWLINE ( -- , CR if needed )\n\\ out @ 0>\n\\ IF cr\n\\ THEN\n\\ ;\n\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 ) swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 ) dup cell+ @ swap @ ;\n\n: DABS ( d -- |d| )\n dup 0<\n IF dnegate\n THEN\n;\n\n: S>D ( s -- d , extend signed single precision to double )\n dup 0<\n IF -1\n ELSE 0\n THEN\n;\n\n: D>S ( d -- s ) drop ;\n\n: PARSE-WORD ( \"name\" -- c-addr u ) bl parse ;\n: \/STRING ( addr len n -- addr' len' ) over min rot over + -rot - ;\n: PLACE ( addr len to -- , move string ) 3dup 1+ swap cmove c! drop ;\n\n: ASCII ( -- char, state smart )\n bl parse drop c@\n state @ 1 =\n IF [compile] literal\n ELSE\n THEN\n; immediate\n\n: CHAR ( -- char , interpret mode ) bl parse drop c@ ;\n: [CHAR] ( -- char , for compile mode )\n char [compile] literal\n; immediate\n\n: $TYPE ( $string -- ) count type ;\n: 'word ( -- addr ) here ;\n\n: EVEN ( addr -- addr' ) dup 1 and + ;\n\n: (C\") ( -- $addr ) r> dup count + aligned >r ;\n: (S\") ( -- c-addr cnt ) r> count 2dup + aligned >r ;\n: (.\") ( -- , type following string ) r> count 2dup + aligned >r type ;\n: \", ( addr len -- , place string into dict ) tuck 'word place 1+ allot align ;\n: ,\" ( -- ) [char] \" parse \", ;\n\n: .( ( --, type string delimited by parens )\n [char] ) parse type\n; immediate\n\n: .\" ( -- , type string )\n state @ 1 =\n IF compile (.\") ,\"\n ELSE [char] \" parse type\n THEN\n; immediate\n\n: .' ( -- , type string delimited by single quote )\n state @\n IF compile (.\") [char] ' parse \",\n ELSE [char] ' parse type\n THEN\n; immediate\n\n: C\" ( -- addr , return string address, ANSI )\n state @\n IF compile (c\") ,\"\n ELSE [char] \" parse pad place pad\n THEN\n; immediate\n\n: S\" ( -- , -- addr , return string address, ANSI )\n state @\n IF compile (s\") ,\"\n ELSE [char] \" parse pad place pad count\n THEN\n; immediate\n\n: \" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n: P\" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n\n\\ : \"\" ( -- addr )\n\\ state @\n\\ IF\n\\ compile (C\")\n\\ bl parse-word \",\n\\ ELSE\n\\ bl parse-word pad place pad\n\\ THEN\n\\ ; immediate\n\n: SLITERAL ( addr cnt -- , compile string )\n\tcompile (S\")\n\t\",\n; IMMEDIATE\n\n: $APPEND ( addr count $1 -- , append text to $1 )\n over >r\n dup >r\n count + ( -- a2 c2 end1 )\n swap cmove\n r> dup c@ ( a1 c1 )\n r> + ( -- a1 totalcount )\n swap c!\n;\n\n\\ ANSI word to replace [COMPILE] and COMPILE ----------------\n\\ : POSTPONE ( -- )\n\\\tbl word find\n\\\tdup 0=\n\\\tIF\n\\\t\t.\" Postpone could not find \" count type cr abort\n\\\tELSE\n\\\t\t0>\n\\\t\tIF compile, \\ immediate\n\\\t\tELSE (compile) \\ normal\n\\\t\tTHEN\n\\\tTHEN\n\\ ; immediate\n\n\\ -----------------------------------------------------------------\n\\ Auto Initialization\n: AUTO.INIT ( -- )\n\\ Kernel finds AUTO.INIT and executes it after loading dictionary.\n\\\t.\" Begin AUTO.INIT ------\" cr\n;\n: AUTO.TERM ( -- )\n\\ Kernel finds AUTO.TERM and executes it on bye.\n\\\t.\" End AUTO.TERM ------\" cr\n;\n\n\n: CLEARSTACK ( i*x -- )\n BEGIN depth\n WHILE drop\n REPEAT ;\n\nvariable pictured_output \\ hidden?\nvariable pictured_output_len \\ hidden?\n\n: <# ( -- ) pad pictured_output ! 0 pictured_output_len ! ;\n: #> ( -- addr n ) drop pictured_output @ pictured_output_len @ ;\n\n: HOLD ( c -- )\n pictured_output @ dup dup 1+ pictured_output_len @ cmove c!\n 1 pictured_output_len +!\n;\n\n\\ ------------------------ INPUT -------------------------------\n\n: SIGN ( n -- ) < 0 IF 45 hold THEN\n;\n\n: DIGIT ( n -- ascii )\n dup 10 < IF 48 ELSE 87 THEN + ;\n\n: # ( n -- n )\n base @ \/mod swap digit hold ;\n\n: #S ( n -- )\n BEGIN base @ \/mod dup\n WHILE swap digit hold\n REPEAT\n digit hold ;\n\n\n: (WARNING\") ( flag $message -- )\n swap\n IF count type\n ELSE drop\n THEN\n;\n\n: WARNING\" ( flag -- , print warning if true. )\n\t[compile] \" ( compile message )\n\tstate @\n\tIF compile (warning\")\n\tELSE (warning\")\n\tTHEN\n; IMMEDIATE\n\n: ABORT\" ( flag -- , print warning if true. )\n\t[compile] \" ( compile message )\n\tstate @\n\tIF compile (abort\")\n\tELSE (abort\")\n\tTHEN\n; IMMEDIATE\n\n: DEFER ( \"name\" -- )\n CREATE ['] ABORT ,\n DOES> ( ... -- ... ) @ EXECUTE ;\n\n: DEFER! ( xt2 xt1 -- )\n >BODY 4 CELL* + ! ;\n\n: DEFER@ ( xt1 -- xt2 )\n >BODY 4 CELL* + @ ;\n\n","old_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\\n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n\n: COUNT dup 1+ swap c@ ;\n\n\\ Miscellaneous support words\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: <= ( a b -- f , true if A <= b ) > 0= ;\n: >= ( a b -- f , true if A >= b ) < 0= ;\n: NOT ( n -- !n , logical negation ) 0= ;\n: DNEGATE ( d -- -d , negate by doing 0-d )\n 0 swap -\n;\n: CELL+ ( n -- n+cell ) cell + ;\n: CELL- ( n -- n-cell ) cell - ;\n: CELL* ( n -- n*cell ) cells ;\n\n: CHAR+ ( n -- n+size_of_char ) 1+ ;\n: CHARS ( n -- n*size_of_char, don't do anything ) ; immediate\n\n\\ useful stack manipulation words\n: -ROT ( a b c -- c a b ) rot rot ;\n: 3DUP ( a b c -- a b c a b c ) 2 pick 2 pick 2 pick ;\n\n\\ ------------------------------------------------------------------\n: ID. ( nfa -- ) count 31 and type ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: PAD ( -- addr ) here 128 + ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n\n: BETWEEN ( n lo hi -- flag , true if between lo & hi )\n >r over r> > >r\n < r> or 0=\n;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: ? ( -- ) @ . ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ ' (lit) , cell 1- , ] +\n [ ' (lit) , cell 1- invert , ] and ;\n\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n: ALLOT ( nbytes -- , allot space in dictionary ) dp +! align ;\n\n: C, ( c -- ) here c! 1 dp +! ;\n\\ : W, ( w -- ) dp @ even-up dup dp ! w! 2 dp +! ;\n\\ : , ( n -- , lay into dictionary ) align here ! cell allot ;\n\n: SEE ( -- )\n ' dup\n >body swap >size\n disassemble ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token )\n [compile] literal ( compile a call to literal )\n ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick )\n ?comp ' [compile] literal\n; immediate\n\n: (DOES>) ( xt -- , modify previous definition to execute code at xt )\n latest >body \\ get address of code for new word\n 3 cell* + \\ offset to EXIT cell in create word\n ! \\ store execution token of DOES> code in new word\n;\n\n: DOES> ( -- , define execution code for CREATE word )\n 0 [compile] literal \\ dummy literal to hold xt\n here cell- \\ address of zero in literal\n compile (does>) \\ call (DOES>) from new creation word\n\t\t>r \\ move addrz to return stack so ; doesn't see stack garbage\n [compile] ; \\ terminate part of code before does>\n\t\tr>\n :noname ( addrz xt )\n compile rdrop \\ drop a stack frame (call becomes goto)\n swap ! \\ save execution token in literal\n; immediate\n\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 )\n swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 )\n dup cell+ @ swap @ ;\n\n: 2* ( n -- n*2 )\n 2 *\n;\n: 2\/ ( n -- n\/2 )\n 2 \/\n;\n\n\n\\ define some useful constants ------------------------------\n1 0= constant FALSE\n0 0= constant TRUE\n32 constant BL\n\n\\ Stack data structure ----------------------------------------\n\\ This is a general purpose stack utility used to implement necessary\n\\ stacks for the compiler or the user. Not real fast.\n\\ These stacks grow up which is different then normal.\n\\ cell 0 - stack pointer, offset from pfa of word\n\\ cell 1 - limit for range checking\n\\ cell 2 - first data location\n\n: :STACK ( #cells -- )\n CREATE 2 cells , ( offset of first data location )\n dup , ( limit for range checking, not currently used )\n cells cell+ allot ( allot an extra cell for safety )\n;\n\n: >STACK ( n stack -- , push onto stack, postincrement )\n dup @ 2dup cell+ swap ! ( -- n stack offset )\n + !\n;\n\n: STACK> ( stack -- n , pop , predecrement )\n dup @ cell- 2dup swap !\n + @\n;\n\n: STACK@ ( stack -- n , copy )\n dup @ cell- + @\n;\n\n: STACK.PICK ( index stack -- n , grab Nth from top of stack )\n dup @ cell- +\n swap cells - \\ offset for index\n @\n;\n: STACKP ( stack -- ptr , to next empty location on stack )\n\tdup @ +\n;\n\n: 0STACKP ( stack -- , clear stack)\n 8 swap !\n;\n\n32 :stack ustack\nustack 0stackp\n\n\\ Define JForth like words.\n: >US ustack >stack ;\n: US> ustack stack> ;\n: US@ ustack stack@ ;\n: 0USP ustack 0stackp ;\n\n\n\n\\ DO LOOP ------------------------------------------------\n\n3 constant do_flag\n4 constant leave_flag\n5 constant ?do_flag\n\n: DO ( -- , loop-back do_flag jump-from ?do_flag )\n ?comp\n compile (do)\n here >us do_flag >us ( for backward branch )\n; immediate\n\n: ?DO ( -- , loop-back do_flag jump-from ?do_flag , on user stack )\n ?comp\n ( leave address to set for forward branch )\n compile (?do)\n here 0 ,\n here >us do_flag >us ( for backward branch )\n >us ( for forward branch ) ?do_flag >us\n; immediate\n\n: LEAVE ( -- addr leave_flag )\n compile (leave)\n here 0 , >us\n leave_flag >us\n; immediate\n\n: LOOP-FORWARD ( -us- jump-from ?do_flag -- )\n BEGIN\n us@ leave_flag =\n us@ ?do_flag =\n OR\n WHILE\n us> leave_flag =\n IF\n us> here over - cell+ swap !\n ELSE\n us> dup\n here swap -\n cell+ swap !\n THEN\n REPEAT\n;\n\n: LOOP-BACK ( loop-addr do_flag -us- )\n us> do_flag ?pairs\n us> here - here\n !\n cell allot\n;\n\n: LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (loop)\n loop-forward loop-back\n; immediate\n\n\\ : DOTEST 5 0 do 333 . loop 888 . ;\n\\ : ?DOTEST0 0 0 ?do 333 . loop 888 . ;\n\\ : ?DOTEST1 5 0 ?do 333 . loop 888 . ;\n\n: +LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (+loop)\n loop-forward loop-back\n; immediate\n\n: UNLOOP ( loop-sys -r- )\n r> \\ save return pointer\n rdrop rdrop\n >r\n;\n\n\n: RECURSE ( ? -- ? , call the word currently being defined )\n latest compile,\n; immediate\n\n: SPACE bl emit ;\n: SPACES 512 min 0 max 0 ?DO space LOOP ;\n: 0SP depth 0 ?do drop loop ;\n\n\\ : >NEWLINE ( -- , CR if needed )\n\\ out @ 0>\n\\ IF cr\n\\ THEN\n\\ ;\n\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 ) swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 ) dup cell+ @ swap @ ;\n\n: DABS ( d -- |d| )\n dup 0<\n IF dnegate\n THEN\n;\n\n: S>D ( s -- d , extend signed single precision to double )\n dup 0<\n IF -1\n ELSE 0\n THEN\n;\n\n: D>S ( d -- s ) drop ;\n\n: PARSE-WORD ( \"name\" -- c-addr u ) bl parse ;\n: \/STRING ( addr len n -- addr' len' ) over min rot over + -rot - ;\n: PLACE ( addr len to -- , move string ) 3dup 1+ swap cmove c! drop ;\n\n: ASCII ( -- char, state smart )\n bl parse drop c@\n state @ 1 =\n IF [compile] literal\n ELSE\n THEN\n; immediate\n\n: CHAR ( -- char , interpret mode ) bl parse drop c@ ;\n: [CHAR] ( -- char , for compile mode )\n char [compile] literal\n; immediate\n\n: $TYPE ( $string -- ) count type ;\n: 'word ( -- addr ) here ;\n\n: EVEN ( addr -- addr' ) dup 1 and + ;\n\n: (C\") ( -- $addr ) r> dup count + aligned >r ;\n: (S\") ( -- c-addr cnt ) r> count 2dup + aligned >r ;\n: (.\") ( -- , type following string ) r> count 2dup + aligned >r type ;\n: \", ( addr len -- , place string into dict ) tuck 'word place 1+ allot align ;\n: ,\" ( -- ) [char] \" parse \", ;\n\n: .( ( --, type string delimited by parens )\n [char] ) parse type\n; immediate\n\n: .\" ( -- , type string )\n state @ 1 =\n IF compile (.\") ,\"\n ELSE [char] \" parse type\n THEN\n; immediate\n\n: .' ( -- , type string delimited by single quote )\n state @\n IF compile (.\") [char] ' parse \",\n ELSE [char] ' parse type\n THEN\n; immediate\n\n: C\" ( -- addr , return string address, ANSI )\n state @\n IF compile (c\") ,\"\n ELSE [char] \" parse pad place pad\n THEN\n; immediate\n\n: S\" ( -- , -- addr , return string address, ANSI )\n state @\n IF compile (s\") ,\"\n ELSE [char] \" parse pad place pad count\n THEN\n; immediate\n\n: \" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n: P\" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n\n\\ : \"\" ( -- addr )\n\\ state @\n\\ IF\n\\ compile (C\")\n\\ bl parse-word \",\n\\ ELSE\n\\ bl parse-word pad place pad\n\\ THEN\n\\ ; immediate\n\n: SLITERAL ( addr cnt -- , compile string )\n\tcompile (S\")\n\t\",\n; IMMEDIATE\n\n: $APPEND ( addr count $1 -- , append text to $1 )\n over >r\n dup >r\n count + ( -- a2 c2 end1 )\n swap cmove\n r> dup c@ ( a1 c1 )\n r> + ( -- a1 totalcount )\n swap c!\n;\n\n\\ ANSI word to replace [COMPILE] and COMPILE ----------------\n\\ : POSTPONE ( -- )\n\\\tbl word find\n\\\tdup 0=\n\\\tIF\n\\\t\t.\" Postpone could not find \" count type cr abort\n\\\tELSE\n\\\t\t0>\n\\\t\tIF compile, \\ immediate\n\\\t\tELSE (compile) \\ normal\n\\\t\tTHEN\n\\\tTHEN\n\\ ; immediate\n\n\\ -----------------------------------------------------------------\n\\ Auto Initialization\n: AUTO.INIT ( -- )\n\\ Kernel finds AUTO.INIT and executes it after loading dictionary.\n\\\t.\" Begin AUTO.INIT ------\" cr\n;\n: AUTO.TERM ( -- )\n\\ Kernel finds AUTO.TERM and executes it on bye.\n\\\t.\" End AUTO.TERM ------\" cr\n;\n\n\n: CLEARSTACK ( i*x -- )\n BEGIN depth\n WHILE drop\n REPEAT ;\n\nvariable pictured_output \\ hidden?\nvariable pictured_output_len \\ hidden?\n\n: <# ( -- ) pad pictured_output ! 0 pictured_output_len ! ;\n: #> ( -- addr n ) drop pictured_output @ pictured_output_len @ ;\n\n: HOLD ( c -- )\n pictured_output @ dup dup 1+ pictured_output_len @ cmove c!\n 1 pictured_output_len +!\n;\n\n\\ ------------------------ INPUT -------------------------------\n\n: SIGN ( n -- ) < 0 IF 45 hold THEN\n;\n\n: DIGIT ( n -- ascii )\n dup 10 < IF 48 ELSE 87 THEN + ;\n\n: # ( n -- n )\n base @ \/mod swap digit hold ;\n\n: #S ( n -- )\n BEGIN base @ \/mod dup\n WHILE swap digit hold\n REPEAT\n digit hold ;\n\n\n: (WARNING\") ( flag $message -- )\n swap\n IF count type\n ELSE drop\n THEN\n;\n\n: WARNING\" ( flag -- , print warning if true. )\n\t[compile] \" ( compile message )\n\tstate @\n\tIF compile (warning\")\n\tELSE (warning\")\n\tTHEN\n; IMMEDIATE\n\n: ABORT\" ( flag -- , print warning if true. )\n\t[compile] \" ( compile message )\n\tstate @\n\tIF compile (abort\")\n\tELSE (abort\")\n\tTHEN\n; IMMEDIATE\n\n: DEFER ( \"name\" -- )\n CREATE ['] ABORT ,\n DOES> ( ... -- ... ) @ EXECUTE ;\n\n: DEFER! ( xt2 xt1 -- )\n >BODY 4 CELL* + ! ;\n\n: DEFER@ ( xt1 -- xt2 )\n >BODY 4 CELL* + @ ;\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"19e53f54f0c06a9e4526507875fe3b0fb0de9d80","subject":"Re-instate CHARS word","message":"Re-instate CHARS word\n","repos":"rm-hull\/byok3,rm-hull\/byok3","old_file":"core\/src\/main\/resources\/forth\/system.fth","new_file":"core\/src\/main\/resources\/forth\/system.fth","new_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\\n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n\n: COUNT dup 1+ swap c@ ;\n\n\\ Miscellaneous support words\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: <= ( a b -- f , true if A <= b ) > 0= ;\n: >= ( a b -- f , true if A >= b ) < 0= ;\n: NOT ( n -- !n , logical negation ) 0= ;\n: DNEGATE ( d -- -d , negate by doing 0-d )\n 0 swap -\n;\n: CELL+ ( n -- n+cell ) cell + ;\n: CELL- ( n -- n-cell ) cell - ;\n: CELL* ( n -- n*cell ) cells ;\n\n: CHAR+ ( n -- n+size_of_char ) 1+ ;\n: CHARS ( n -- n*size_of_char, don't do anything ) ; immediate\n\n\\ useful stack manipulation words\n: -ROT ( a b c -- c a b ) rot rot ;\n: 3DUP ( a b c -- a b c a b c ) 2 pick 2 pick 2 pick ;\n\n\\ ------------------------------------------------------------------\n: ID. ( nfa -- ) count 31 and type ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: PAD ( -- addr ) here 128 + ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n\n: BETWEEN ( n lo hi -- flag , true if between lo & hi )\n >r over r> > >r\n < r> or 0=\n;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: ? ( -- ) @ . ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ ' (lit) , cell 1- , ] +\n [ ' (lit) , cell 1- invert , ] and ;\n\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n: ALLOT ( nbytes -- , allot space in dictionary ) dp +! align ;\n\n: C, ( c -- ) here c! 1 dp +! ;\n\\ : W, ( w -- ) dp @ even-up dup dp ! w! 2 dp +! ;\n\\ : , ( n -- , lay into dictionary ) align here ! cell allot ;\n\n: SEE ( -- )\n ' dup\n >body swap >size\n disassemble ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token )\n [compile] literal ( compile a call to literal )\n ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick )\n ?comp ' [compile] literal\n; immediate\n\n: (DOES>) ( xt -- , modify previous definition to execute code at xt )\n latest >body \\ get address of code for new word\n 3 cell* + \\ offset to EXIT cell in create word\n ! \\ store execution token of DOES> code in new word\n;\n\n: DOES> ( -- , define execution code for CREATE word )\n 0 [compile] literal \\ dummy literal to hold xt\n here cell- \\ address of zero in literal\n compile (does>) \\ call (DOES>) from new creation word\n\t\t>r \\ move addrz to return stack so ; doesn't see stack garbage\n [compile] ; \\ terminate part of code before does>\n\t\tr>\n :noname ( addrz xt )\n compile rdrop \\ drop a stack frame (call becomes goto)\n swap ! \\ save execution token in literal\n; immediate\n\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 )\n swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 )\n dup cell+ @ swap @ ;\n\n: 2* ( n -- n*2 )\n 2 *\n;\n: 2\/ ( n -- n\/2 )\n 2 \/\n;\n\n\n\\ define some useful constants ------------------------------\n1 0= constant FALSE\n0 0= constant TRUE\n32 constant BL\n\n\\ Stack data structure ----------------------------------------\n\\ This is a general purpose stack utility used to implement necessary\n\\ stacks for the compiler or the user. Not real fast.\n\\ These stacks grow up which is different then normal.\n\\ cell 0 - stack pointer, offset from pfa of word\n\\ cell 1 - limit for range checking\n\\ cell 2 - first data location\n\n: :STACK ( #cells -- )\n CREATE 2 cells , ( offset of first data location )\n dup , ( limit for range checking, not currently used )\n cells cell+ allot ( allot an extra cell for safety )\n;\n\n: >STACK ( n stack -- , push onto stack, postincrement )\n dup @ 2dup cell+ swap ! ( -- n stack offset )\n + !\n;\n\n: STACK> ( stack -- n , pop , predecrement )\n dup @ cell- 2dup swap !\n + @\n;\n\n: STACK@ ( stack -- n , copy )\n dup @ cell- + @\n;\n\n: STACK.PICK ( index stack -- n , grab Nth from top of stack )\n dup @ cell- +\n swap cells - \\ offset for index\n @\n;\n: STACKP ( stack -- ptr , to next empty location on stack )\n\tdup @ +\n;\n\n: 0STACKP ( stack -- , clear stack)\n 8 swap !\n;\n\n32 :stack ustack\nustack 0stackp\n\n\\ Define JForth like words.\n: >US ustack >stack ;\n: US> ustack stack> ;\n: US@ ustack stack@ ;\n: 0USP ustack 0stackp ;\n\n\n\n\\ DO LOOP ------------------------------------------------\n\n3 constant do_flag\n4 constant leave_flag\n5 constant ?do_flag\n\n: DO ( -- , loop-back do_flag jump-from ?do_flag )\n ?comp\n compile (do)\n here >us do_flag >us ( for backward branch )\n; immediate\n\n: ?DO ( -- , loop-back do_flag jump-from ?do_flag , on user stack )\n ?comp\n ( leave address to set for forward branch )\n compile (?do)\n here 0 ,\n here >us do_flag >us ( for backward branch )\n >us ( for forward branch ) ?do_flag >us\n; immediate\n\n: LEAVE ( -- addr leave_flag )\n compile (leave)\n here 0 , >us\n leave_flag >us\n; immediate\n\n: LOOP-FORWARD ( -us- jump-from ?do_flag -- )\n BEGIN\n us@ leave_flag =\n us@ ?do_flag =\n OR\n WHILE\n us> leave_flag =\n IF\n us> here over - cell+ swap !\n ELSE\n us> dup\n here swap -\n cell+ swap !\n THEN\n REPEAT\n;\n\n: LOOP-BACK ( loop-addr do_flag -us- )\n us> do_flag ?pairs\n us> here - here\n !\n cell allot\n;\n\n: LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (loop)\n loop-forward loop-back\n; immediate\n\n\\ : DOTEST 5 0 do 333 . loop 888 . ;\n\\ : ?DOTEST0 0 0 ?do 333 . loop 888 . ;\n\\ : ?DOTEST1 5 0 ?do 333 . loop 888 . ;\n\n: +LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (+loop)\n loop-forward loop-back\n; immediate\n\n: UNLOOP ( loop-sys -r- )\n r> \\ save return pointer\n rdrop rdrop\n >r\n;\n\n\n: RECURSE ( ? -- ? , call the word currently being defined )\n latest compile,\n; immediate\n\n: SPACE bl emit ;\n: SPACES 512 min 0 max 0 ?DO space LOOP ;\n: 0SP depth 0 ?do drop loop ;\n\n\\ : >NEWLINE ( -- , CR if needed )\n\\ out @ 0>\n\\ IF cr\n\\ THEN\n\\ ;\n\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 ) swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 ) dup cell+ @ swap @ ;\n\n: DABS ( d -- |d| )\n dup 0<\n IF dnegate\n THEN\n;\n\n: S>D ( s -- d , extend signed single precision to double )\n dup 0<\n IF -1\n ELSE 0\n THEN\n;\n\n: D>S ( d -- s ) drop ;\n\n: PARSE-WORD ( \"name\" -- c-addr u ) bl parse ;\n: \/STRING ( addr len n -- addr' len' ) over min rot over + -rot - ;\n: PLACE ( addr len to -- , move string ) 3dup 1+ swap cmove c! drop ;\n\n: ASCII ( -- char, state smart )\n bl parse drop c@\n state @ 1 =\n IF [compile] literal\n ELSE\n THEN\n; immediate\n\n: CHAR ( -- char , interpret mode ) bl parse drop c@ ;\n: [CHAR] ( -- char , for compile mode )\n char [compile] literal\n; immediate\n\n: $TYPE ( $string -- ) count type ;\n: 'word ( -- addr ) here ;\n\n: EVEN ( addr -- addr' ) dup 1 and + ;\n\n: (C\") ( -- $addr ) r> dup count + aligned >r ;\n: (S\") ( -- c-addr cnt ) r> count 2dup + aligned >r ;\n: (.\") ( -- , type following string ) r> count 2dup + aligned >r type ;\n: \", ( addr len -- , place string into dict ) tuck 'word place 1+ allot align ;\n: ,\" ( -- ) [char] \" parse \", ;\n\n: .( ( --, type string delimited by parens )\n [char] ) parse type\n; immediate\n\n: .\" ( -- , type string )\n state @ 1 =\n IF compile (.\") ,\"\n ELSE [char] \" parse type\n THEN\n; immediate\n\n: .' ( -- , type string delimited by single quote )\n state @\n IF compile (.\") [char] ' parse \",\n ELSE [char] ' parse type\n THEN\n; immediate\n\n: C\" ( -- addr , return string address, ANSI )\n state @\n IF compile (c\") ,\"\n ELSE [char] \" parse pad place pad\n THEN\n; immediate\n\n: S\" ( -- , -- addr , return string address, ANSI )\n state @\n IF compile (s\") ,\"\n ELSE [char] \" parse pad place pad count\n THEN\n; immediate\n\n: \" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n: P\" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n\n\\ : \"\" ( -- addr )\n\\ state @\n\\ IF\n\\ compile (C\")\n\\ bl parse-word \",\n\\ ELSE\n\\ bl parse-word pad place pad\n\\ THEN\n\\ ; immediate\n\n: SLITERAL ( addr cnt -- , compile string )\n\tcompile (S\")\n\t\",\n; IMMEDIATE\n\n: $APPEND ( addr count $1 -- , append text to $1 )\n over >r\n dup >r\n count + ( -- a2 c2 end1 )\n swap cmove\n r> dup c@ ( a1 c1 )\n r> + ( -- a1 totalcount )\n swap c!\n;\n\n\\ ANSI word to replace [COMPILE] and COMPILE ----------------\n\\ : POSTPONE ( -- )\n\\\tbl word find\n\\\tdup 0=\n\\\tIF\n\\\t\t.\" Postpone could not find \" count type cr abort\n\\\tELSE\n\\\t\t0>\n\\\t\tIF compile, \\ immediate\n\\\t\tELSE (compile) \\ normal\n\\\t\tTHEN\n\\\tTHEN\n\\ ; immediate\n\n\\ -----------------------------------------------------------------\n\\ Auto Initialization\n: AUTO.INIT ( -- )\n\\ Kernel finds AUTO.INIT and executes it after loading dictionary.\n\\\t.\" Begin AUTO.INIT ------\" cr\n;\n: AUTO.TERM ( -- )\n\\ Kernel finds AUTO.TERM and executes it on bye.\n\\\t.\" End AUTO.TERM ------\" cr\n;\n\n\n: CLEARSTACK ( i*x -- )\n BEGIN depth\n WHILE drop\n REPEAT ;\n\nvariable pictured_output \\ hidden?\nvariable pictured_output_len \\ hidden?\n\n: <# ( -- ) pad pictured_output ! 0 pictured_output_len ! ;\n: #> ( -- addr n ) drop pictured_output @ pictured_output_len @ ;\n\n: HOLD ( c -- )\n pictured_output @ dup dup 1+ pictured_output_len @ cmove c!\n 1 pictured_output_len +!\n;\n\n\\ ------------------------ INPUT -------------------------------\n\n: SIGN ( n -- ) < 0 IF 45 hold THEN\n;\n\n: DIGIT ( n -- ascii )\n dup 10 < IF 48 ELSE 87 THEN + ;\n\n: # ( n -- n )\n base @ \/mod swap digit hold ;\n\n: #S ( n -- )\n BEGIN base @ \/mod dup\n WHILE swap digit hold\n REPEAT\n digit hold ;\n\n\n: (WARNING\") ( flag $message -- )\n swap\n IF count type\n ELSE drop\n THEN\n;\n\n: WARNING\" ( flag -- , print warning if true. )\n\t[compile] \" ( compile message )\n\tstate @\n\tIF compile (warning\")\n\tELSE (warning\")\n\tTHEN\n; IMMEDIATE\n\n: ABORT\" ( flag -- , print warning if true. )\n\t[compile] \" ( compile message )\n\tstate @\n\tIF compile (abort\")\n\tELSE (abort\")\n\tTHEN\n; IMMEDIATE\n\n: DEFER ( \"name\" -- )\n CREATE ['] ABORT ,\n DOES> ( ... -- ... ) @ EXECUTE ;\n\n: DEFER! ( xt2 xt1 -- )\n >BODY 4 CELL* + ! ;\n\n: DEFER@ ( xt1 -- xt2 )\n >BODY 4 CELL* + @ ;\n\n","old_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\\n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n\n: COUNT dup 1+ swap c@ ;\n\n\\ Miscellaneous support words\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: <= ( a b -- f , true if A <= b ) > 0= ;\n: >= ( a b -- f , true if A >= b ) < 0= ;\n: NOT ( n -- !n , logical negation ) 0= ;\n: DNEGATE ( d -- -d , negate by doing 0-d )\n 0 swap -\n;\n: CELL+ ( n -- n+cell ) cell + ;\n: CELL- ( n -- n-cell ) cell - ;\n: CELL* ( n -- n*cell ) cells ;\n\n: CHAR+ ( n -- n+size_of_char ) 1+ ;\n\\ : CHARS ( n -- n*size_of_char, don't do anything ) ; immediate\n\n\\ useful stack manipulation words\n: -ROT ( a b c -- c a b ) rot rot ;\n: 3DUP ( a b c -- a b c a b c ) 2 pick 2 pick 2 pick ;\n\n\\ ------------------------------------------------------------------\n: ID. ( nfa -- ) count 31 and type ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: PAD ( -- addr ) here 128 + ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n\n: BETWEEN ( n lo hi -- flag , true if between lo & hi )\n >r over r> > >r\n < r> or 0=\n;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: ? ( -- ) @ . ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ ' (lit) , cell 1- , ] +\n [ ' (lit) , cell 1- invert , ] and ;\n\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n: ALLOT ( nbytes -- , allot space in dictionary ) dp +! align ;\n\n: C, ( c -- ) here c! 1 dp +! ;\n\\ : W, ( w -- ) dp @ even-up dup dp ! w! 2 dp +! ;\n\\ : , ( n -- , lay into dictionary ) align here ! cell allot ;\n\n: SEE ( -- )\n ' dup\n >body swap >size\n disassemble ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token )\n [compile] literal ( compile a call to literal )\n ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick )\n ?comp ' [compile] literal\n; immediate\n\n: (DOES>) ( xt -- , modify previous definition to execute code at xt )\n latest >body \\ get address of code for new word\n 3 cell* + \\ offset to EXIT cell in create word\n ! \\ store execution token of DOES> code in new word\n;\n\n: DOES> ( -- , define execution code for CREATE word )\n 0 [compile] literal \\ dummy literal to hold xt\n here cell- \\ address of zero in literal\n compile (does>) \\ call (DOES>) from new creation word\n\t\t>r \\ move addrz to return stack so ; doesn't see stack garbage\n [compile] ; \\ terminate part of code before does>\n\t\tr>\n :noname ( addrz xt )\n compile rdrop \\ drop a stack frame (call becomes goto)\n swap ! \\ save execution token in literal\n; immediate\n\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 )\n swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 )\n dup cell+ @ swap @ ;\n\n: 2* ( n -- n*2 )\n 2 *\n;\n: 2\/ ( n -- n\/2 )\n 2 \/\n;\n\n\n\\ define some useful constants ------------------------------\n1 0= constant FALSE\n0 0= constant TRUE\n32 constant BL\n\n\\ Stack data structure ----------------------------------------\n\\ This is a general purpose stack utility used to implement necessary\n\\ stacks for the compiler or the user. Not real fast.\n\\ These stacks grow up which is different then normal.\n\\ cell 0 - stack pointer, offset from pfa of word\n\\ cell 1 - limit for range checking\n\\ cell 2 - first data location\n\n: :STACK ( #cells -- )\n CREATE 2 cells , ( offset of first data location )\n dup , ( limit for range checking, not currently used )\n cells cell+ allot ( allot an extra cell for safety )\n;\n\n: >STACK ( n stack -- , push onto stack, postincrement )\n dup @ 2dup cell+ swap ! ( -- n stack offset )\n + !\n;\n\n: STACK> ( stack -- n , pop , predecrement )\n dup @ cell- 2dup swap !\n + @\n;\n\n: STACK@ ( stack -- n , copy )\n dup @ cell- + @\n;\n\n: STACK.PICK ( index stack -- n , grab Nth from top of stack )\n dup @ cell- +\n swap cells - \\ offset for index\n @\n;\n: STACKP ( stack -- ptr , to next empty location on stack )\n\tdup @ +\n;\n\n: 0STACKP ( stack -- , clear stack)\n 8 swap !\n;\n\n32 :stack ustack\nustack 0stackp\n\n\\ Define JForth like words.\n: >US ustack >stack ;\n: US> ustack stack> ;\n: US@ ustack stack@ ;\n: 0USP ustack 0stackp ;\n\n\n\n\\ DO LOOP ------------------------------------------------\n\n3 constant do_flag\n4 constant leave_flag\n5 constant ?do_flag\n\n: DO ( -- , loop-back do_flag jump-from ?do_flag )\n ?comp\n compile (do)\n here >us do_flag >us ( for backward branch )\n; immediate\n\n: ?DO ( -- , loop-back do_flag jump-from ?do_flag , on user stack )\n ?comp\n ( leave address to set for forward branch )\n compile (?do)\n here 0 ,\n here >us do_flag >us ( for backward branch )\n >us ( for forward branch ) ?do_flag >us\n; immediate\n\n: LEAVE ( -- addr leave_flag )\n compile (leave)\n here 0 , >us\n leave_flag >us\n; immediate\n\n: LOOP-FORWARD ( -us- jump-from ?do_flag -- )\n BEGIN\n us@ leave_flag =\n us@ ?do_flag =\n OR\n WHILE\n us> leave_flag =\n IF\n us> here over - cell+ swap !\n ELSE\n us> dup\n here swap -\n cell+ swap !\n THEN\n REPEAT\n;\n\n: LOOP-BACK ( loop-addr do_flag -us- )\n us> do_flag ?pairs\n us> here - here\n !\n cell allot\n;\n\n: LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (loop)\n loop-forward loop-back\n; immediate\n\n\\ : DOTEST 5 0 do 333 . loop 888 . ;\n\\ : ?DOTEST0 0 0 ?do 333 . loop 888 . ;\n\\ : ?DOTEST1 5 0 ?do 333 . loop 888 . ;\n\n: +LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (+loop)\n loop-forward loop-back\n; immediate\n\n: UNLOOP ( loop-sys -r- )\n r> \\ save return pointer\n rdrop rdrop\n >r\n;\n\n\n: RECURSE ( ? -- ? , call the word currently being defined )\n latest compile,\n; immediate\n\n: SPACE bl emit ;\n: SPACES 512 min 0 max 0 ?DO space LOOP ;\n: 0SP depth 0 ?do drop loop ;\n\n\\ : >NEWLINE ( -- , CR if needed )\n\\ out @ 0>\n\\ IF cr\n\\ THEN\n\\ ;\n\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 ) swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 ) dup cell+ @ swap @ ;\n\n: DABS ( d -- |d| )\n dup 0<\n IF dnegate\n THEN\n;\n\n: S>D ( s -- d , extend signed single precision to double )\n dup 0<\n IF -1\n ELSE 0\n THEN\n;\n\n: D>S ( d -- s ) drop ;\n\n: PARSE-WORD ( \"name\" -- c-addr u ) bl parse ;\n: \/STRING ( addr len n -- addr' len' ) over min rot over + -rot - ;\n: PLACE ( addr len to -- , move string ) 3dup 1+ swap cmove c! drop ;\n\n: ASCII ( -- char, state smart )\n bl parse drop c@\n state @ 1 =\n IF [compile] literal\n ELSE\n THEN\n; immediate\n\n: CHAR ( -- char , interpret mode ) bl parse drop c@ ;\n: [CHAR] ( -- char , for compile mode )\n char [compile] literal\n; immediate\n\n: $TYPE ( $string -- ) count type ;\n: 'word ( -- addr ) here ;\n\n: EVEN ( addr -- addr' ) dup 1 and + ;\n\n: (C\") ( -- $addr ) r> dup count + aligned >r ;\n: (S\") ( -- c-addr cnt ) r> count 2dup + aligned >r ;\n: (.\") ( -- , type following string ) r> count 2dup + aligned >r type ;\n: \", ( addr len -- , place string into dict ) tuck 'word place 1+ allot align ;\n: ,\" ( -- ) [char] \" parse \", ;\n\n: .( ( --, type string delimited by parens )\n [char] ) parse type\n; immediate\n\n: .\" ( -- , type string )\n state @ 1 =\n IF compile (.\") ,\"\n ELSE [char] \" parse type\n THEN\n; immediate\n\n: .' ( -- , type string delimited by single quote )\n state @\n IF compile (.\") [char] ' parse \",\n ELSE [char] ' parse type\n THEN\n; immediate\n\n: C\" ( -- addr , return string address, ANSI )\n state @\n IF compile (c\") ,\"\n ELSE [char] \" parse pad place pad\n THEN\n; immediate\n\n: S\" ( -- , -- addr , return string address, ANSI )\n state @\n IF compile (s\") ,\"\n ELSE [char] \" parse pad place pad count\n THEN\n; immediate\n\n: \" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n: P\" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n\n\\ : \"\" ( -- addr )\n\\ state @\n\\ IF\n\\ compile (C\")\n\\ bl parse-word \",\n\\ ELSE\n\\ bl parse-word pad place pad\n\\ THEN\n\\ ; immediate\n\n: SLITERAL ( addr cnt -- , compile string )\n\tcompile (S\")\n\t\",\n; IMMEDIATE\n\n: $APPEND ( addr count $1 -- , append text to $1 )\n over >r\n dup >r\n count + ( -- a2 c2 end1 )\n swap cmove\n r> dup c@ ( a1 c1 )\n r> + ( -- a1 totalcount )\n swap c!\n;\n\n\\ ANSI word to replace [COMPILE] and COMPILE ----------------\n\\ : POSTPONE ( -- )\n\\\tbl word find\n\\\tdup 0=\n\\\tIF\n\\\t\t.\" Postpone could not find \" count type cr abort\n\\\tELSE\n\\\t\t0>\n\\\t\tIF compile, \\ immediate\n\\\t\tELSE (compile) \\ normal\n\\\t\tTHEN\n\\\tTHEN\n\\ ; immediate\n\n\\ -----------------------------------------------------------------\n\\ Auto Initialization\n: AUTO.INIT ( -- )\n\\ Kernel finds AUTO.INIT and executes it after loading dictionary.\n\\\t.\" Begin AUTO.INIT ------\" cr\n;\n: AUTO.TERM ( -- )\n\\ Kernel finds AUTO.TERM and executes it on bye.\n\\\t.\" End AUTO.TERM ------\" cr\n;\n\n\n: CLEARSTACK ( i*x -- )\n BEGIN depth\n WHILE drop\n REPEAT ;\n\nvariable pictured_output \\ hidden?\nvariable pictured_output_len \\ hidden?\n\n: <# ( -- ) pad pictured_output ! 0 pictured_output_len ! ;\n: #> ( -- addr n ) drop pictured_output @ pictured_output_len @ ;\n\n: HOLD ( c -- )\n pictured_output @ dup dup 1+ pictured_output_len @ cmove c!\n 1 pictured_output_len +!\n;\n\n\\ ------------------------ INPUT -------------------------------\n\n: SIGN ( n -- ) < 0 IF 45 hold THEN\n;\n\n: DIGIT ( n -- ascii )\n dup 10 < IF 48 ELSE 87 THEN + ;\n\n: # ( n -- n )\n base @ \/mod swap digit hold ;\n\n: #S ( n -- )\n BEGIN base @ \/mod dup\n WHILE swap digit hold\n REPEAT\n digit hold ;\n\n\n: (WARNING\") ( flag $message -- )\n swap\n IF count type\n ELSE drop\n THEN\n;\n\n: WARNING\" ( flag -- , print warning if true. )\n\t[compile] \" ( compile message )\n\tstate @\n\tIF compile (warning\")\n\tELSE (warning\")\n\tTHEN\n; IMMEDIATE\n\n: ABORT\" ( flag -- , print warning if true. )\n\t[compile] \" ( compile message )\n\tstate @\n\tIF compile (abort\")\n\tELSE (abort\")\n\tTHEN\n; IMMEDIATE\n\n: DEFER ( \"name\" -- )\n CREATE ['] ABORT ,\n DOES> ( ... -- ... ) @ EXECUTE ;\n\n: DEFER! ( xt2 xt1 -- )\n >BODY 4 CELL* + ! ;\n\n: DEFER@ ( xt1 -- xt2 )\n >BODY 4 CELL* + @ ;\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"39b82d4701005e09a697ca4363ac46de2085aba5","subject":"Basic tools for calibration.","message":"Basic tools for calibration.","repos":"rbsexton\/gecko,rbsexton\/gecko,rbsexton\/gecko","old_file":"zero\/clock-umb\/forth\/Clock.fth","new_file":"zero\/clock-umb\/forth\/Clock.fth","new_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( -- )\n load-defaults \n icroot 0 over inter.rtcsem ! \\ Reset the free-running counters.\n 0 over inter.rtcdsem ! \\ Reset the free-running counters.\n\n begin \n \tdup inter.rtcsem @offex! ?dup if advancehms then\n \tdup inter.rtcdsem @offex! ?dup if advancedhms then\n [asm wfi asm]\n uiupdate if use-uivals else use-clockvals then \n key? until drop\n;\n \n\\ These two contain loops to ensure that we don't\n\\ drop any timer ticks on the floor.\n: ADVANCEHMS ( n -- ) 0 do hms advancetime loop ;\n: ADVANCEDHMS ( n -- ) 0 do dhms advancetime loop ;\n \n: LOAD-DEFAULTS ( -- )\n nvramvalid? if _nvramload then \n interp-init\n;\n\n\\ ----------------------------------------------------------\n\\ Define the structures before they get used.\n\\ ----------------------------------------------------------\nstruct ODN \\ On-Deck Needle \n\tint odn.s\n\tint odn.m\n\tint odn.h\nend-struct\n\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxsec \\ Max Value for secs+minutes\n\tint hms.maxhour \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_m \\ increment the minutes + hours\nend-struct\n\nstruct _interp_set\n\t4 cells field interp.a\n\t4 cells field interp.b\n\t4 cells field interp.c\nend-struct\n\n\\ ----------------------------------------------------------\n\\ Defaults get saved in the user data page.\n\\ ----------------------------------------------------------\n: NVRAMVALID? ( -- t\/f ) \n\\ *G See if there is valid data in the NVRAM.\n\\ ** It consists of 3 words. If any of them are \n\\ ** set to 0xffff:ffff, we go with the defaults.\n _USERDATA\n dup @ -1 <> \n over 4 + @ -1 <> and\n swap 8 + @ -1 <> and\n;\n\n: _NVRAMLOAD ( -- ) \n\\ *G Pull the needle maximums from flash.\n $C 0 do I ud@ needle_max I + ! 4 +loop \n; \n\n: NVRAM! ( addr -- )\n\\ *G Save the contents of the needle cal values.\n 0 UDPAGE_ERASE\n ( addr )\n $C 0 do dup I + @ I ud! 4 +loop\n drop \n;\n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nidata\ncreate ODN_HMS odn allot \\ On-Deck, HMS\ncreate ODN_DHMS odn allot \\ On-Deck, DHMS\ncreate ODN_UI odn allot \\ On-Deck, Generated by the UI.\ncdata\n\nidata \\ Has to match an odn.\ncreate NEEDLE_MAX #850 , #850 , #850 ,\ncdata\n\n(( \n: interp-next drop 1 ; \n: interp-reset drop .\" Reset\" ; \n\t\n))\n\n: RANGECHECK ( max n -- n or zero ) 2dup <= if 2drop 0 else swap drop then ; \n: CLIP ( n -- n) \\ Force the contents to be legal ( 0-999 )\n dup 0 < if drop 0 exit then \n dup #999 > if drop #999 then \n;\n \n: INTER-BUMP ( max old interp -- new )\n\\ *G Get the next value from the interpolator, and \n\\ ** reset the interpolator if it wraps around to zero.\n >R R@ interp-next \\ Get the max \n + rangecheck \n dup 0= if R> interp-reset else R> drop then \n ; \n\n: NFETCH ( odn off -- max old )\n\\ *G Combine the current value with the maximum.\n >R R@ \\ stash the offset.\n + @ \\ Calculate the offset address, get the current val.\n needle_max R> + @\n swap \n;\n\n: ++NEEDLE_S \\ Called every time.\n odn_hms 0 odn.s nfetch ( max old )\n\tinterp_hms interp.a inter-bump ( new )\n\todn_hms odn.s ! \n\t;\n\n: ++NEEDLE_M ( -- )\n\\ *G Every time we roll the seconds, bump the minutes and the hour\n\todn_hms 0 odn.m nfetch ( max old )\n\tinterp_hms interp.b inter-bump \n\todn_hms odn.m ! \n\n\todn_hms 0 odn.h nfetch ( max old )\n\tinterp_hms interp.c inter-bump \n\todn_hms odn.h ! \n\t;\n\n: ++NEEDLE_DS ; \\ Called every time.\n: ++NEEDLE_DM ; \\ Every time we roll the seconds.\n\n: _USE ( odn-addr -- ) \n dup odn.s w@ pwm0!\n dup odn.m w@ pwm1!\n odn.h w@ pwm2!\n ;\n\n: USE-CLOCKVALS odn_hms _use ; \n: USE-UIVALS odn_ui _use ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Quadrature\n\\ ----------------------------------------------------------\n\n_timer1 $24 + equ QUAD-IN\n\n\\ The Quadrature encoder produces two per detent.\n: QUAD@ ( -- n ) \\ Fetch and zero\n quad-in @off \n [asm sxth tos, tos asm]\n [asm asr .s tos, tos, # 1 asm] \\ Divide by two,\n ;\n \n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_ds , ' ++needle_dm , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n: ADVANCETIME ( struct-addr -- )\n dup hms.w_s @ execute \\ Invoke the official update word.\n 1 over hms.subsec +! \\ Increment\n dup hms.subsec @\n over hms.maxsubsec @ < if drop exit then \\ If less then max, we're done\n 0 over hms.subsec ! \\ Reset the subsecs \n\n 1 over hms.s +!\n dup hms.s @ over hms.maxsec @ < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n dup hms.w_m @ execute\n 1 over hms.m +!\n dup hms.m @ over hms.maxsec @ < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ over hms.maxhour @ < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ----------------------------------------------------------\n\\ The interpolator. \n\\ Implement bresenhams algorithm. All of this code already\n\\ exists in C, but we'll own the data structures. They contain\n\\ A total of 4 words - fixed, err, num, & denom\n\\ ----------------------------------------------------------\nudata \ncreate interp_hms _interp_set allot\ncreate interp_dhms _interp_set allot \ncdata\n\n#16 #60 * equ raw_sec\n#10 #100 * equ raw_dsec\n\n: INTERP-INIT ( -- )\n (interp_init) interp_hms\n 2dup interp.a needle_max @ raw_sec call3-- \n 2dup interp.b needle_max 4 + @ #60 call3-- \n interp.c needle_max 8 + @ #12 call3--\n\n (interp_init) interp_dhms\n 2dup interp.a needle_max @ raw_dsec call3-- \n 2dup interp.b needle_max 4 + @ #100 call3-- \n interp.c needle_max 8 + @ #10 call3--\n;\n\n\\ Call the reset fn.\n: INTERP-RESET ( interp_addr -- )\n (interp_reset) swap call1-- \n;\n\n: INTERP-NEXT ( addr -- n )\n (interp_next) swap call1--n\n;\n\n\n\\ ============================ UNTESTED =======================\n\\ VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n\n\\ ----------------------------------------------------------\n\\ User Interface\n\\ ----------------------------------------------------------\nvariable uistate\nvariable uicount \n\n_GPIO $64 + equ _BUTTONIO\n: BUTTONUP? ( -- t\/f ) _buttonio @ 1 and ; \n: BUTTONDOWN? ( -- t\/f ) buttonup? 1 xor ; \n\n\\ The wrapper for all of the UI stuff.\n\\ Returns true if the UI is active - ie, use the values generated by the UI.\n: UIUPDATE ( -- t\/f )\n StateHandlers uistate @ + @ execute \n; \n\n: uitest \n uistate @ 4 \/ . .\" ->\" uiupdate uistate @ 4 \/ .\n uicount @ . if .\" True\" else .\" False\" then \n; \n\n\\ -----------------------------------------------\n\\ State numbers. These are defined x4 so that\n\\ we can just use the state number as an index \n\\ into a table of words.\n\\ -----------------------------------------------\n0 4 * equ _s_init\n1 4 * equ _s_b1\n2 4 * equ _s_1sec\n\n3 4 * equ _s_set_h\n4 4 * equ _s_pendset_m\n5 4 * equ _s_setmin\n\n6 4 * equ _s_pendcal0\n7 4 * equ _s_cal0\n8 4 * equ _s_pendcalh\n9 4 * equ _s_calh\n10 4 * equ _s_pendcalm\n11 4 * equ _s_calm\n12 4 * equ _s_pendcals\n13 4 * equ _s_cals\n\n4 equ downcount_1s\n16 equ downcount_3s \n\n\\ All of the state handlers.\n\\ Everybody needs to know the state of the button, so that must\n\\ get passed in, thus they all look like this:\n\\ state ( t\/f -- t\/f )\n: shInit false \n buttondown? if \n _s_b1 uistate !\n uicount off \\ Reset this.\n then\n ;\n\n\\ Waiting for a full second to go by.\n: shB1 false\n buttonup? if _s_init uistate ! exit then\n \\ The Button is down. \n uicount @ downcount_1s >= if\n _s_1sec uistate !\n else \n 1 uicount +!\n\tthen\n ;\n\n\\ We're in the 1 second state\n: sh1sec true \n buttonup? if _s_set_h uistate ! exit then\n uicount @ downcount_3s >= if\n _s_pendcal0 uistate !\n else \n 1 uicount +!\n\tthen \n;\n\n\\ -------------------------------------------------\n\\ Setting the time\n\\ -------------------------------------------------\n: shSetH true buttondown? if _s_pendset_m uistate ! exit then ;\n\n: shPendSetM true buttonup? if _s_setmin uistate ! then ;\n: shSetMin true buttondown? if _s_init uistate ! exit then ;\n\n\\ -------------------------------------------------\n\\ Calibration\n\\ -------------------------------------------------\n: shPendCal0 true buttonup? if _s_cal0 uistate ! helpODNClear then ;\n: shCal0 true buttondown? if _s_pendcalh uistate ! exit then ;\n\n: shPendCalH true buttonup? if _s_calh uistate ! helpODNMid then ; \n: shCalH true buttondown? if _s_pendcalm uistate ! exit then \n odn_ui odn.h helpQuad@ ; \n\n: shPendCalM true buttonup? if _s_calm uistate ! then ; \n: shCalM true buttondown? if _s_pendcals uistate ! exit then \n odn_ui odn.m helpQuad@ ; \n\n: shPendCalS true buttonup? if _s_cals uistate ! then ; \n: shCalS true buttondown? if \n _s_init uistate !\n odn_ui nvram! exit then \n \n odn_ui odn.s helpQuad@ ; \n\n\\ -------------------------------------------------\n\\ Helpers\n\\ -------------------------------------------------\n: helpODNClear ( -- ) \\ Set them all to zero\n odn_ui odn bounds do I off 4 +loop ; \n: helpODNMid ( -- ) \\ Set them all to 500\n odn_ui odn bounds do #750 I ! 4 +loop ; \n: helpQuad@ ( addr -- ) \\ update a location with the quadrature value\n dup @ quad@ + clip swap ! ;\n\n\ncreate StateHandlers \n' shInit , \n' shB1 ,\n' sh1sec ,\n\n' shSetH ,\n' shPendSetM , ' shSetMin ,\n\n' shPendCal0 , ' shCal0 ,\n' shPendCalH , ' shCalH , \n' shPendCalM , ' shCalM , \n' shPendCalS , ' shCalS , \n\n\\ -------------------------------------------------\n\\ Setting the time.\n\\ -------------------------------------------------\nvariable adj_i \\ THe working index into the points array.\n\nudata \ncreate adj_points #50 cells allot \\ 100 16-bit words. \ncreate interp_set _interp_set allot\ncdata \n\n\\ Generate a list of points.\n: MAKE-SET-LIST ( max steps ) \n 2dup \n >R (interp_init) swap interp_set swap R> call3--\n\n \\ Since zero is first, do the w! first.\n swap drop 0 swap \\ Keep a running counter.\n 0 do\n dup I adj_points[]! \\ Save the existing value\n interp_set interp-next + \n loop\n drop\n ;\n\n: ADJ_POINTS[]! ( data index -- ) 2* adj_points + w! ;\n: ADJ_POINTS[]@ ( index -- n ) 2* adj_points + w@ ;\n","old_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( -- )\n load-defaults \n icroot 0 over inter.rtcsem ! \\ Reset the free-running counters.\n 0 over inter.rtcdsem ! \\ Reset the free-running counters.\n\n begin \n \tdup inter.rtcsem @offex! ?dup if advancehms then\n \tdup inter.rtcdsem @offex! ?dup if advancedhms then\n [asm wfi asm]\n uiupdate if use-uivals else use-clockvals then \n key? until drop\n;\n \n\\ These two contain loops to ensure that we don't\n\\ drop any timer ticks on the floor.\n: ADVANCEHMS ( n -- ) 0 do hms advancetime loop ;\n: ADVANCEDHMS ( n -- ) 0 do dhms advancetime loop ;\n \n: LOAD-DEFAULTS ( -- )\n interp-init\n;\n\n\\ ----------------------------------------------------------\n\\ Define the structures before they get used.\n\\ ----------------------------------------------------------\nstruct ODN \\ On-Deck Needle \n\tint odn.s\n\tint odn.m\n\tint odn.h\nend-struct\n\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxsec \\ Max Value for secs+minutes\n\tint hms.maxhour \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_m \\ increment the minutes + hours\nend-struct\n\nstruct _interp_set\n\t4 cells field interp.a\n\t4 cells field interp.b\n\t4 cells field interp.c\nend-struct\n\n\\ ----------------------------------------------------------\n\\ Defaults get saved in the user data page.\n\\ ----------------------------------------------------------\n: NVRAMVALID? ( addr -- t\/f ) \n\\ *G See if there is valid data in the NVRAM.\n\\ ** It consists of 3 words. If any of them are \n\\ ** set to 0xffff:ffff, we go with the defaults.\n _USERDATA\n dup @ -1 <> \n over 4 + @ -1 <> and\n swap 8 + @ -1 <> and\n;\n\n: _NVRAMLOAD ( -- ) \n\\ *G Pull the needle maximums from flash.\n $C 0 do I ud@ needle_max I + ! 4 +loop \n; \n\n: NVRAM! ( -- )\n\\ *G Save the contents of the needle cal values.\n 0 UDPAGE_ERASE\n needle_max\n $C 0 do dup I + @ I ud! 4 +loop\n drop \n;\n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nidata\ncreate ODN_HMS odn allot \\ On-Deck, HMS\ncreate ODN_DHMS odn allot \\ On-Deck, DHMS\ncreate ODN_UI odn allot \\ On-Deck, Generated by the UI.\ncdata\n\nidata \\ Has to match an odn.\ncreate NEEDLE_MAX #850 , #850 , #850 ,\ncdata\n\n(( \n: interp-next drop 1 ; \n: interp-reset drop .\" Reset\" ; \n\t\n))\n\n: RANGECHECK ( max n -- n or zero ) 2dup <= if 2drop 0 else swap drop then ; \n: CLIP ( n -- n) \\ Force the contents to be legal ( 0-999 )\n dup 0 < if drop 0 exit then \n dup #999 > if drop #999 then \n;\n \n: INTER-BUMP ( max old interp -- new )\n\\ *G Get the next value from the interpolator, and \n\\ ** reset the interpolator if it wraps around to zero.\n >R R@ interp-next \\ Get the max \n + rangecheck \n dup 0= if R> interp-reset else R> drop then \n ; \n\n: NFETCH ( odn off -- max old )\n\\ *G Combine the current value with the maximum.\n >R R@ \\ stash the offset.\n + @ \\ Calculate the offset address, get the current val.\n needle_max R> + @\n swap \n;\n\n: ++NEEDLE_S \\ Called every time.\n odn_hms 0 odn.s nfetch ( max old )\n\tinterp_hms interp.a inter-bump ( new )\n\todn_hms odn.s ! \n\t;\n\n: ++NEEDLE_M ( -- )\n\\ *G Every time we roll the seconds, bump the minutes and the hour\n\todn_hms 0 odn.m nfetch ( max old )\n\tinterp_hms interp.b inter-bump \n\todn_hms odn.m ! \n\n\todn_hms 0 odn.h nfetch ( max old )\n\tinterp_hms interp.c inter-bump \n\todn_hms odn.h ! \n\t;\n\n: ++NEEDLE_DS ; \\ Called every time.\n: ++NEEDLE_DM ; \\ Every time we roll the seconds.\n\n: _USE ( odn-addr -- ) \n dup odn.s w@ pwm0!\n dup odn.m w@ pwm1!\n odn.h w@ pwm2!\n ;\n\n: USE-CLOCKVALS odn_hms _use ; \n: USE-UIVALS odn_ui _use ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Quadrature\n\\ ----------------------------------------------------------\n\n_timer1 $24 + equ QUAD-IN\n\n\\ The Quadrature encoder produces two per detent.\n: QUAD@ ( -- n ) \\ Fetch and zero\n quad-in @off \n [asm sxth tos, tos asm]\n [asm asr .s tos, tos, # 1 asm] \\ Divide by two,\n ;\n \n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_ds , ' ++needle_dm , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n: ADVANCETIME ( struct-addr -- )\n dup hms.w_s @ execute \\ Invoke the official update word.\n 1 over hms.subsec +! \\ Increment\n dup hms.subsec @\n over hms.maxsubsec @ < if drop exit then \\ If less then max, we're done\n 0 over hms.subsec ! \\ Reset the subsecs \n\n 1 over hms.s +!\n dup hms.s @ over hms.maxsec @ < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n dup hms.w_m @ execute\n 1 over hms.m +!\n dup hms.m @ over hms.maxsec @ < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ over hms.maxhour @ < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ----------------------------------------------------------\n\\ The interpolator. \n\\ Implement bresenhams algorithm. All of this code already\n\\ exists in C, but we'll own the data structures. They contain\n\\ A total of 4 words - fixed, err, num, & denom\n\\ ----------------------------------------------------------\nudata \ncreate interp_hms _interp_set allot\ncreate interp_dhms _interp_set allot \ncdata\n\n#16 #60 * equ raw_sec\n#10 #100 * equ raw_dsec\n\n: INTERP-INIT ( -- )\n (interp_init) interp_hms\n 2dup interp.a needle_max @ raw_sec call3-- \n 2dup interp.b needle_max 4 + @ #60 call3-- \n interp.c needle_max 8 + @ #12 call3--\n\n (interp_init) interp_dhms\n 2dup interp.a needle_max @ raw_dsec call3-- \n 2dup interp.b needle_max 4 + @ #100 call3-- \n interp.c needle_max 8 + @ #10 call3--\n;\n\n\\ Call the reset fn.\n: INTERP-RESET ( interp_addr -- )\n (interp_reset) swap call1-- \n;\n\n: INTERP-NEXT ( addr -- n )\n (interp_next) swap call1--n\n;\n\n\n\\ ============================ UNTESTED =======================\n\\ VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n\n\\ ----------------------------------------------------------\n\\ User Interface\n\\ ----------------------------------------------------------\nvariable uistate\nvariable uicount \n\n_GPIO $64 + equ _BUTTONIO\n: BUTTONUP? ( -- t\/f ) _buttonio @ 1 and ; \n: BUTTONDOWN? ( -- t\/f ) buttonup? 1 xor ; \n\n\\ The wrapper for all of the UI stuff.\n\\ Returns true if the UI is active - ie, use the values generated by the UI.\n: UIUPDATE ( -- t\/f )\n StateHandlers uistate @ + @ execute \n; \n\n: uitest \n uistate @ 4 \/ . .\" ->\" uiupdate uistate @ 4 \/ .\n uicount @ . if .\" True\" else .\" False\" then \n; \n\n\\ -----------------------------------------------\n\\ State numbers. These are defined x4 so that\n\\ we can just use the state number as an index \n\\ into a table of words.\n\\ -----------------------------------------------\n0 4 * equ _s_init\n1 4 * equ _s_b1\n2 4 * equ _s_1sec\n\n3 4 * equ _s_set_h\n4 4 * equ _s_pendset_m\n5 4 * equ _s_setmin\n\n6 4 * equ _s_pendcal0\n7 4 * equ _s_cal0\n8 4 * equ _s_pendcalh\n9 4 * equ _s_calh\n10 4 * equ _s_pendcalm\n11 4 * equ _s_calm\n12 4 * equ _s_pendcals\n13 4 * equ _s_cals\n\n4 equ downcount_1s\n16 equ downcount_3s \n\n\\ All of the state handlers.\n\\ Everybody needs to know the state of the button, so that must\n\\ get passed in, thus they all look like this:\n\\ state ( t\/f -- t\/f )\n: shInit false \n buttondown? if \n _s_b1 uistate !\n uicount off \\ Reset this.\n then\n ;\n\n\\ Waiting for a full second to go by.\n: shB1 false\n buttonup? if _s_init uistate ! exit then\n \\ The Button is down. \n uicount @ downcount_1s >= if\n _s_1sec uistate !\n else \n 1 uicount +!\n\tthen\n ;\n\n\\ We're in the 1 second state\n: sh1sec true \n buttonup? if _s_set_h uistate ! exit then\n uicount @ downcount_3s >= if\n _s_pendcal0 uistate !\n else \n 1 uicount +!\n\tthen \n;\n\n\\ -------------------------------------------------\n\\ Setting the time\n\\ -------------------------------------------------\n: shSetH true buttondown? if _s_pendset_m uistate ! exit then ;\n\n: shPendSetM true buttonup? if _s_setmin uistate ! then ;\n: shSetMin true buttondown? if _s_init uistate ! exit then ;\n\n\\ -------------------------------------------------\n\\ Calibration\n\\ -------------------------------------------------\n: shPendCal0 true buttonup? if _s_cal0 uistate ! helpODNClear then ;\n: shCal0 true buttondown? if _s_pendcalh uistate ! exit then ;\n\n: shPendCalH true buttonup? if _s_calh uistate ! helpODNMid then ; \n: shCalH true buttondown? if _s_pendcalm uistate ! exit then \n odn_ui odn.h helpQuad@ ; \n\n: shPendCalM true buttonup? if _s_calm uistate ! then ; \n: shCalM true buttondown? if _s_pendcals uistate ! exit then \n odn_ui odn.m helpQuad@ ; \n\n: shPendCalS true buttonup? if _s_cals uistate ! then ; \n: shCalS true buttondown? if _s_init uistate ! exit then \n odn_ui odn.s helpQuad@ ; \n\n\\ -------------------------------------------------\n\\ Helpers\n\\ -------------------------------------------------\n: helpODNClear ( -- ) \\ Set them all to zero\n odn_ui odn bounds do I off 4 +loop ; \n: helpODNMid ( -- ) \\ Set them all to 500\n odn_ui odn bounds do #750 I ! 4 +loop ; \n: helpQuad@ ( addr -- ) \\ update a location with the quadrature value\n dup @ quad@ + clip swap ! ;\n\n\ncreate StateHandlers \n' shInit , \n' shB1 ,\n' sh1sec ,\n\n' shSetH ,\n' shPendSetM , ' shSetMin ,\n\n' shPendCal0 , ' shCal0 ,\n' shPendCalH , ' shCalH , \n' shPendCalM , ' shCalM , \n' shPendCalS , ' shCalS , \n\n\\ -------------------------------------------------\n\\ Setting the time.\n\\ -------------------------------------------------\nvariable adj_i \\ THe working index into the points array.\n\nudata \ncreate adj_points #50 cells allot \\ 100 16-bit words. \ncreate interp_set _interp_set allot\ncdata \n\n\\ Generate a list of points.\n: MAKE-SET-LIST ( max steps ) \n 2dup \n >R (interp_init) swap interp_set swap R> call3--\n\n \\ Since zero is first, do the w! first.\n swap drop 0 swap \\ Keep a running counter.\n 0 do\n dup I adj_points[]! \\ Save the existing value\n interp_set interp-next + \n loop\n drop\n ;\n\n: ADJ_POINTS[]! ( data index -- ) 2* adj_points + w! ;\n: ADJ_POINTS[]@ ( index -- n ) 2* adj_points + w@ ;\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"5690f2820a416315d024e49e4b6588cc73b0e172","subject":"Add optional support for default override of standard setup; but only if corresponding functions are provided. If override function does not exist, boot remains unmodified. This patch should not result in any changes.","message":"Add optional support for default override of standard setup; but only if\ncorresponding functions are provided. If override function does not exist,\nboot remains unmodified. This patch should not result in any changes.\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/beastie.4th","new_file":"sys\/boot\/forth\/beastie.4th","new_contents":"\\ Copyright (c) 2003 Scott Long \n\\ Copyright (c) 2003 Aleksander Fafula \n\\ Copyright (c) 2006-2013 Devin Teske \n\\ All rights reserved.\n\\ \n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\ \n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\ \n\\ $FreeBSD$\n\nmarker task-beastie.4th\n\ninclude \/boot\/delay.4th\n\nvariable logoX\nvariable logoY\n\n\\ Initialize logo placement to defaults\n46 logoX !\n4 logoY !\n\n: beastie-logo ( x y -- ) \\ color BSD mascot (19 rows x 34 columns)\n\n2dup at-xy .\" \u001b[31m, ,\" 1+\n2dup at-xy .\" \/( )`\" 1+\n2dup at-xy .\" \\ \\___ \/ |\" 1+\n2dup at-xy .\" \/- \u001b[37m_\u001b[31m `-\/ '\" 1+\n2dup at-xy .\" (\u001b[37m\/\\\/ \\\u001b[31m \\ \/\\\" 1+\n2dup at-xy .\" \u001b[37m\/ \/ |\u001b[31m ` \\\" 1+\n2dup at-xy .\" \u001b[34mO O \u001b[37m) \u001b[31m\/ |\" 1+\n2dup at-xy .\" \u001b[37m`-^--'\u001b[31m`< '\" 1+\n2dup at-xy .\" (_.) _ ) \/\" 1+\n2dup at-xy .\" `.___\/` \/\" 1+\n2dup at-xy .\" `-----' \/\" 1+\n2dup at-xy .\" \u001b[33m<----.\u001b[31m __ \/ __ \\\" 1+\n2dup at-xy .\" \u001b[33m<----|====\u001b[31mO)))\u001b[33m==\u001b[31m) \\) \/\u001b[33m====|\" 1+\n2dup at-xy .\" \u001b[33m<----'\u001b[31m `--' `.__,' \\\" 1+\n2dup at-xy .\" | |\" 1+\n2dup at-xy .\" \\ \/ \/\\\" 1+\n2dup at-xy .\" \u001b[36m______\u001b[31m( (_ \/ \\______\/\" 1+\n2dup at-xy .\" \u001b[36m,' ,-----' |\" 1+\n at-xy .\" `--{__________)\u001b[37m\"\n\n\t\\ Put the cursor back at the bottom\n\t0 25 at-xy\n;\n\n: beastiebw-logo ( x y -- ) \\ B\/W BSD mascot (19 rows x 34 columns)\n\n\t2dup at-xy .\" , ,\" 1+\n\t2dup at-xy .\" \/( )`\" 1+\n\t2dup at-xy .\" \\ \\___ \/ |\" 1+\n\t2dup at-xy .\" \/- _ `-\/ '\" 1+\n\t2dup at-xy .\" (\/\\\/ \\ \\ \/\\\" 1+\n\t2dup at-xy .\" \/ \/ | ` \\\" 1+\n\t2dup at-xy .\" O O ) \/ |\" 1+\n\t2dup at-xy .\" `-^--'`< '\" 1+\n\t2dup at-xy .\" (_.) _ ) \/\" 1+\n\t2dup at-xy .\" `.___\/` \/\" 1+\n\t2dup at-xy .\" `-----' \/\" 1+\n\t2dup at-xy .\" <----. __ \/ __ \\\" 1+\n\t2dup at-xy .\" <----|====O)))==) \\) \/====|\" 1+\n\t2dup at-xy .\" <----' `--' `.__,' \\\" 1+\n\t2dup at-xy .\" | |\" 1+\n\t2dup at-xy .\" \\ \/ \/\\\" 1+\n\t2dup at-xy .\" ______( (_ \/ \\______\/\" 1+\n\t2dup at-xy .\" ,' ,-----' |\" 1+\n\t at-xy .\" `--{__________)\"\n\n\t\\ Put the cursor back at the bottom\n\t0 25 at-xy\n;\n\n: fbsdbw-logo ( x y -- ) \\ \"FreeBSD\" logo in B\/W (13 rows x 21 columns)\n\n\t\\ We used to use the beastie himself as our default... until the\n\t\\ eventual complaint derided his reign of the advanced boot-menu.\n\t\\ \n\t\\ This is the replacement of beastie to satiate the haters of our\n\t\\ beloved helper-daemon (ready to track down and spear bugs with\n\t\\ his trident and sporty sneakers; see above).\n\t\\ \n\t\\ Since we merely just changed the default and not the default-\n\t\\ location, below is an adjustment to the passed-in coordinates,\n\t\\ forever influenced by the proper location of beastie himself\n\t\\ kept as the default loader_logo_x\/loader_logo_y values.\n\t\\ \n\t5 + swap 6 + swap\n\n\t2dup at-xy .\" ______\" 1+\n\t2dup at-xy .\" | ____| __ ___ ___ \" 1+\n\t2dup at-xy .\" | |__ | '__\/ _ \\\/ _ \\\" 1+\n\t2dup at-xy .\" | __|| | | __\/ __\/\" 1+\n\t2dup at-xy .\" | | | | | | |\" 1+\n\t2dup at-xy .\" |_| |_| \\___|\\___|\" 1+\n\t2dup at-xy .\" ____ _____ _____\" 1+\n\t2dup at-xy .\" | _ \\ \/ ____| __ \\\" 1+\n\t2dup at-xy .\" | |_) | (___ | | | |\" 1+\n\t2dup at-xy .\" | _ < \\___ \\| | | |\" 1+\n\t2dup at-xy .\" | |_) |____) | |__| |\" 1+\n\t2dup at-xy .\" | | | |\" 1+\n\t at-xy .\" |____\/|_____\/|_____\/\"\n\n\t\\ Put the cursor back at the bottom\n\t0 25 at-xy\n;\n\n: orb-logo ( x y -- ) \\ color Orb mascot (15 rows x 30 columns)\n\n\t3 + \\ beastie adjustment (see `fbsdbw-logo' comments above)\n\n\t2dup at-xy .\" \u001b[31m``` \u001b[31;1m`\u001b[31m\" 1+\n\t2dup at-xy .\" s` `.....---...\u001b[31;1m....--.``` -\/\u001b[31m\" 1+\n\t2dup at-xy .\" +o .--` \u001b[31;1m\/y:` +.\u001b[31m\" 1+\n\t2dup at-xy .\" yo`:. \u001b[31;1m:o `+-\u001b[31m\" 1+\n\t2dup at-xy .\" y\/ \u001b[31;1m-\/` -o\/\u001b[31m\" 1+\n\t2dup at-xy .\" .- \u001b[31;1m::\/sy+:.\u001b[31m\" 1+\n\t2dup at-xy .\" \/ \u001b[31;1m`-- \/\u001b[31m\" 1+\n\t2dup at-xy .\" `: \u001b[31;1m:`\u001b[31m\" 1+\n\t2dup at-xy .\" `: \u001b[31;1m:`\u001b[31m\" 1+\n\t2dup at-xy .\" \/ \u001b[31;1m\/\u001b[31m\" 1+\n\t2dup at-xy .\" .- \u001b[31;1m-.\u001b[31m\" 1+\n\t2dup at-xy .\" -- \u001b[31;1m-.\u001b[31m\" 1+\n\t2dup at-xy .\" `:` \u001b[31;1m`:`\" 1+\n\t2dup at-xy .\" \u001b[31;1m.-- `--.\" 1+\n\t at-xy .\" .---.....----.\u001b[37m\"\n\n \t\\ Put the cursor back at the bottom\n \t0 25 at-xy\n;\n\n: orbbw-logo ( x y -- ) \\ B\/W Orb mascot (15 rows x 32 columns)\n\n\t3 + \\ beastie adjustment (see `fbsdbw-logo' comments above)\n\n\t2dup at-xy .\" ``` `\" 1+\n\t2dup at-xy .\" s` `.....---.......--.``` -\/\" 1+\n\t2dup at-xy .\" +o .--` \/y:` +.\" 1+\n\t2dup at-xy .\" yo`:. :o `+-\" 1+\n\t2dup at-xy .\" y\/ -\/` -o\/\" 1+\n\t2dup at-xy .\" .- ::\/sy+:.\" 1+\n\t2dup at-xy .\" \/ `-- \/\" 1+\n\t2dup at-xy .\" `: :`\" 1+\n\t2dup at-xy .\" `: :`\" 1+\n\t2dup at-xy .\" \/ \/\" 1+\n\t2dup at-xy .\" .- -.\" 1+\n\t2dup at-xy .\" -- -.\" 1+\n\t2dup at-xy .\" `:` `:`\" 1+\n\t2dup at-xy .\" .-- `--.\" 1+\n\t at-xy .\" .---.....----.\"\n\n \t\\ Put the cursor back at the bottom\n \t0 25 at-xy\n;\n\n\\ This function draws any number of beastie logos at (loader_logo_x,\n\\ loader_logo_y) if defined, else (46,4) (to the right of the menu). To choose\n\\ your beastie, set the variable `loader_logo' to the respective logo name.\n\\ \n\\ Currently available:\n\\ \n\\ \tNAME DESCRIPTION\n\\ \tbeastie Color ``Helper Daemon'' mascot (19 rows x 34 columns)\n\\ \tbeastiebw B\/W ``Helper Daemon'' mascot (19 rows x 34 columns)\n\\ \tfbsdbw \"FreeBSD\" logo in B\/W (13 rows x 21 columns)\n\\ \torb Color ``Orb'' mascot (15 rows x 30 columns) (2nd default)\n\\ \torbbw B\/W ``Orb'' mascot (15 rows x 32 columns)\n\\ \ttribute Color ``Tribute'' (must fit 19 rows x 34 columns) (default)\n\\ \ttributebw B\/W ``Tribute'' (must fit 19 rows x 34 columns)\n\\ \n\\ NOTE: Setting `loader_logo' to an undefined value (such as \"none\") will\n\\ prevent beastie from being drawn.\n\\ \n: draw-beastie ( -- ) \\ at (loader_logo_x,loader_logo_y), else (46,4)\n\n\ts\" loader_logo_x\" getenv dup -1 <> if\n\t\t?number 1 = if logoX ! then\n\telse\n\t\tdrop\n\tthen\n\ts\" loader_logo_y\" getenv dup -1 <> if\n\t\t?number 1 = if logoY ! then\n\telse\n\t\tdrop\n\tthen\n\n\ts\" loader_logo\" getenv dup -1 = if\n\t\tlogoX @ logoY @\n\t\tloader_color? if\n\t\t\ts\" tribute-logo\"\n\t\t\tsfind if\n\t\t\t\texecute\n\t\t\telse\n\t\t\t\tdrop\n\t\t\t\torb-logo\n\t\t\tthen\n\t\telse\n\t\t\ts\" tributebw-logo\"\n\t\t\tsfind if\n\t\t\t\texecute\n\t\t\telse\n\t\t\t\tdrop\n\t\t\t\torbbw-logo\n\t\t\tthen\n\t\tthen\n\t\tdrop exit\n\tthen\n\n\t2dup s\" beastie\" compare-insensitive 0= if\n\t\tlogoX @ logoY @ beastie-logo\n\t\t2drop exit\n\tthen\n\t2dup s\" beastiebw\" compare-insensitive 0= if\n\t\tlogoX @ logoY @ beastiebw-logo\n\t\t2drop exit\n\tthen\n\t2dup s\" fbsdbw\" compare-insensitive 0= if\n\t\tlogoX @ logoY @ fbsdbw-logo\n\t\t2drop exit\n\tthen\n\t2dup s\" orb\" compare-insensitive 0= if\n\t\tlogoX @ logoY @ orb-logo\n\t\t2drop exit\n\tthen\n\t2dup s\" orbbw\" compare-insensitive 0= if\n\t\tlogoX @ logoY @ orbbw-logo\n\t\t2drop exit\n\tthen\n\t2dup s\" tribute\" compare-insensitive 0= if\n\t\tlogoX @ logoY @\n\t\ts\" tribute-logo\" sfind if\n\t\t\texecute\n\t\telse\n\t\t\torb-logo\n\t\tthen\n\t\t2drop exit\n\tthen\n\t2dup s\" tributebw\" compare-insensitive 0= if\n\t\tlogoX @ logoY @\n\t\ts\" tributebw-logo\" sfind if\n\t\t\texecute\n\t\telse\n\t\t\torbbw-logo\n\t\tthen\n\t\t2drop exit\n\tthen\n\n\t2drop\n;\n\n: clear-beastie ( -- ) \\ clears beastie from the screen\n\tlogoX @ logoY @\n\t2dup at-xy 34 spaces 1+\t\t2dup at-xy 34 spaces 1+\n\t2dup at-xy 34 spaces 1+\t\t2dup at-xy 34 spaces 1+\n\t2dup at-xy 34 spaces 1+\t\t2dup at-xy 34 spaces 1+\n\t2dup at-xy 34 spaces 1+\t\t2dup at-xy 34 spaces 1+\n\t2dup at-xy 34 spaces 1+\t\t2dup at-xy 34 spaces 1+\n\t2dup at-xy 34 spaces 1+\t\t2dup at-xy 34 spaces 1+\n\t2dup at-xy 34 spaces 1+\t\t2dup at-xy 34 spaces 1+\n\t2dup at-xy 34 spaces 1+\t\t2dup at-xy 34 spaces 1+\n\t2dup at-xy 34 spaces 1+\t\t2dup at-xy 34 spaces 1+\n\t2dup at-xy 34 spaces\t\t2drop\n\n\t\\ Put the cursor back at the bottom\n\t0 25 at-xy\n;\n\n: beastie-start ( -- ) \\ starts the menu\n\ts\" beastie_disable\" getenv\n\tdup -1 <> if\n\t\ts\" YES\" compare-insensitive 0= if\n\t\t\texit\n\t\tthen\n\telse\n\t\tdrop\n\tthen\n\n\ts\" loader_delay\" getenv\n\t-1 = if\n\t\ts\" include \/boot\/menu.rc\" evaluate\n\telse\n\t\tdrop\n\t\t.\" Loading Menu (Ctrl-C to Abort)\" cr\n\t\ts\" set delay_command='include \/boot\/menu.rc'\" evaluate\n\t\ts\" set delay_showdots\" evaluate\n\t\tdelay_execute\n\tthen\n;\n","old_contents":"\\ Copyright (c) 2003 Scott Long \n\\ Copyright (c) 2003 Aleksander Fafula \n\\ Copyright (c) 2006-2013 Devin Teske \n\\ All rights reserved.\n\\ \n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\ \n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\ \n\\ $FreeBSD$\n\nmarker task-beastie.4th\n\ninclude \/boot\/delay.4th\n\nvariable logoX\nvariable logoY\n\n\\ Initialize logo placement to defaults\n46 logoX !\n4 logoY !\n\n: beastie-logo ( x y -- ) \\ color BSD mascot (19 rows x 34 columns)\n\n2dup at-xy .\" \u001b[31m, ,\" 1+\n2dup at-xy .\" \/( )`\" 1+\n2dup at-xy .\" \\ \\___ \/ |\" 1+\n2dup at-xy .\" \/- \u001b[37m_\u001b[31m `-\/ '\" 1+\n2dup at-xy .\" (\u001b[37m\/\\\/ \\\u001b[31m \\ \/\\\" 1+\n2dup at-xy .\" \u001b[37m\/ \/ |\u001b[31m ` \\\" 1+\n2dup at-xy .\" \u001b[34mO O \u001b[37m) \u001b[31m\/ |\" 1+\n2dup at-xy .\" \u001b[37m`-^--'\u001b[31m`< '\" 1+\n2dup at-xy .\" (_.) _ ) \/\" 1+\n2dup at-xy .\" `.___\/` \/\" 1+\n2dup at-xy .\" `-----' \/\" 1+\n2dup at-xy .\" \u001b[33m<----.\u001b[31m __ \/ __ \\\" 1+\n2dup at-xy .\" \u001b[33m<----|====\u001b[31mO)))\u001b[33m==\u001b[31m) \\) \/\u001b[33m====|\" 1+\n2dup at-xy .\" \u001b[33m<----'\u001b[31m `--' `.__,' \\\" 1+\n2dup at-xy .\" | |\" 1+\n2dup at-xy .\" \\ \/ \/\\\" 1+\n2dup at-xy .\" \u001b[36m______\u001b[31m( (_ \/ \\______\/\" 1+\n2dup at-xy .\" \u001b[36m,' ,-----' |\" 1+\n at-xy .\" `--{__________)\u001b[37m\"\n\n\t\\ Put the cursor back at the bottom\n\t0 25 at-xy\n;\n\n: beastiebw-logo ( x y -- ) \\ B\/W BSD mascot (19 rows x 34 columns)\n\n\t2dup at-xy .\" , ,\" 1+\n\t2dup at-xy .\" \/( )`\" 1+\n\t2dup at-xy .\" \\ \\___ \/ |\" 1+\n\t2dup at-xy .\" \/- _ `-\/ '\" 1+\n\t2dup at-xy .\" (\/\\\/ \\ \\ \/\\\" 1+\n\t2dup at-xy .\" \/ \/ | ` \\\" 1+\n\t2dup at-xy .\" O O ) \/ |\" 1+\n\t2dup at-xy .\" `-^--'`< '\" 1+\n\t2dup at-xy .\" (_.) _ ) \/\" 1+\n\t2dup at-xy .\" `.___\/` \/\" 1+\n\t2dup at-xy .\" `-----' \/\" 1+\n\t2dup at-xy .\" <----. __ \/ __ \\\" 1+\n\t2dup at-xy .\" <----|====O)))==) \\) \/====|\" 1+\n\t2dup at-xy .\" <----' `--' `.__,' \\\" 1+\n\t2dup at-xy .\" | |\" 1+\n\t2dup at-xy .\" \\ \/ \/\\\" 1+\n\t2dup at-xy .\" ______( (_ \/ \\______\/\" 1+\n\t2dup at-xy .\" ,' ,-----' |\" 1+\n\t at-xy .\" `--{__________)\"\n\n\t\\ Put the cursor back at the bottom\n\t0 25 at-xy\n;\n\n: fbsdbw-logo ( x y -- ) \\ \"FreeBSD\" logo in B\/W (13 rows x 21 columns)\n\n\t\\ We used to use the beastie himself as our default... until the\n\t\\ eventual complaint derided his reign of the advanced boot-menu.\n\t\\ \n\t\\ This is the replacement of beastie to satiate the haters of our\n\t\\ beloved helper-daemon (ready to track down and spear bugs with\n\t\\ his trident and sporty sneakers; see above).\n\t\\ \n\t\\ Since we merely just changed the default and not the default-\n\t\\ location, below is an adjustment to the passed-in coordinates,\n\t\\ forever influenced by the proper location of beastie himself\n\t\\ kept as the default loader_logo_x\/loader_logo_y values.\n\t\\ \n\t5 + swap 6 + swap\n\n\t2dup at-xy .\" ______\" 1+\n\t2dup at-xy .\" | ____| __ ___ ___ \" 1+\n\t2dup at-xy .\" | |__ | '__\/ _ \\\/ _ \\\" 1+\n\t2dup at-xy .\" | __|| | | __\/ __\/\" 1+\n\t2dup at-xy .\" | | | | | | |\" 1+\n\t2dup at-xy .\" |_| |_| \\___|\\___|\" 1+\n\t2dup at-xy .\" ____ _____ _____\" 1+\n\t2dup at-xy .\" | _ \\ \/ ____| __ \\\" 1+\n\t2dup at-xy .\" | |_) | (___ | | | |\" 1+\n\t2dup at-xy .\" | _ < \\___ \\| | | |\" 1+\n\t2dup at-xy .\" | |_) |____) | |__| |\" 1+\n\t2dup at-xy .\" | | | |\" 1+\n\t at-xy .\" |____\/|_____\/|_____\/\"\n\n\t\\ Put the cursor back at the bottom\n\t0 25 at-xy\n;\n\n: orb-logo ( x y -- ) \\ color Orb mascot (15 rows x 30 columns)\n\n\t3 + \\ beastie adjustment (see `fbsdbw-logo' comments above)\n\n\t2dup at-xy .\" \u001b[31m``` \u001b[31;1m`\u001b[31m\" 1+\n\t2dup at-xy .\" s` `.....---...\u001b[31;1m....--.``` -\/\u001b[31m\" 1+\n\t2dup at-xy .\" +o .--` \u001b[31;1m\/y:` +.\u001b[31m\" 1+\n\t2dup at-xy .\" yo`:. \u001b[31;1m:o `+-\u001b[31m\" 1+\n\t2dup at-xy .\" y\/ \u001b[31;1m-\/` -o\/\u001b[31m\" 1+\n\t2dup at-xy .\" .- \u001b[31;1m::\/sy+:.\u001b[31m\" 1+\n\t2dup at-xy .\" \/ \u001b[31;1m`-- \/\u001b[31m\" 1+\n\t2dup at-xy .\" `: \u001b[31;1m:`\u001b[31m\" 1+\n\t2dup at-xy .\" `: \u001b[31;1m:`\u001b[31m\" 1+\n\t2dup at-xy .\" \/ \u001b[31;1m\/\u001b[31m\" 1+\n\t2dup at-xy .\" .- \u001b[31;1m-.\u001b[31m\" 1+\n\t2dup at-xy .\" -- \u001b[31;1m-.\u001b[31m\" 1+\n\t2dup at-xy .\" `:` \u001b[31;1m`:`\" 1+\n\t2dup at-xy .\" \u001b[31;1m.-- `--.\" 1+\n\t at-xy .\" .---.....----.\u001b[37m\"\n\n \t\\ Put the cursor back at the bottom\n \t0 25 at-xy\n;\n\n: orbbw-logo ( x y -- ) \\ B\/W Orb mascot (15 rows x 32 columns)\n\n\t3 + \\ beastie adjustment (see `fbsdbw-logo' comments above)\n\n\t2dup at-xy .\" ``` `\" 1+\n\t2dup at-xy .\" s` `.....---.......--.``` -\/\" 1+\n\t2dup at-xy .\" +o .--` \/y:` +.\" 1+\n\t2dup at-xy .\" yo`:. :o `+-\" 1+\n\t2dup at-xy .\" y\/ -\/` -o\/\" 1+\n\t2dup at-xy .\" .- ::\/sy+:.\" 1+\n\t2dup at-xy .\" \/ `-- \/\" 1+\n\t2dup at-xy .\" `: :`\" 1+\n\t2dup at-xy .\" `: :`\" 1+\n\t2dup at-xy .\" \/ \/\" 1+\n\t2dup at-xy .\" .- -.\" 1+\n\t2dup at-xy .\" -- -.\" 1+\n\t2dup at-xy .\" `:` `:`\" 1+\n\t2dup at-xy .\" .-- `--.\" 1+\n\t at-xy .\" .---.....----.\"\n\n \t\\ Put the cursor back at the bottom\n \t0 25 at-xy\n;\n\n\\ This function draws any number of beastie logos at (loader_logo_x,\n\\ loader_logo_y) if defined, else (46,4) (to the right of the menu). To choose\n\\ your beastie, set the variable `loader_logo' to the respective logo name.\n\\ \n\\ Currently available:\n\\ \n\\ \tNAME DESCRIPTION\n\\ \tbeastie Color ``Helper Daemon'' mascot (19 rows x 34 columns)\n\\ \tbeastiebw B\/W ``Helper Daemon'' mascot (19 rows x 34 columns)\n\\ \tfbsdbw \"FreeBSD\" logo in B\/W (13 rows x 21 columns)\n\\ \torb Color ``Orb'' mascot (15 rows x 30 columns) (default)\n\\ \torbbw B\/W ``Orb'' mascot (15 rows x 32 columns)\n\\ \n\\ NOTE: Setting `loader_logo' to an undefined value (such as \"none\") will\n\\ prevent beastie from being drawn.\n\\ \n: draw-beastie ( -- ) \\ at (loader_logo_x,loader_logo_y), else (46,4)\n\n\ts\" loader_logo_x\" getenv dup -1 <> if\n\t\t?number 1 = if logoX ! then\n\telse\n\t\tdrop\n\tthen\n\ts\" loader_logo_y\" getenv dup -1 <> if\n\t\t?number 1 = if logoY ! then\n\telse\n\t\tdrop\n\tthen\n\n\ts\" loader_logo\" getenv dup -1 = if\n\t\tlogoX @ logoY @\n\t\tloader_color? if\n\t\t\torb-logo\n\t\telse\n\t\t\torbbw-logo\n\t\tthen\n\t\tdrop exit\n\tthen\n\n\t2dup s\" beastie\" compare-insensitive 0= if\n\t\tlogoX @ logoY @ beastie-logo\n\t\t2drop exit\n\tthen\n\t2dup s\" beastiebw\" compare-insensitive 0= if\n\t\tlogoX @ logoY @ beastiebw-logo\n\t\t2drop exit\n\tthen\n\t2dup s\" fbsdbw\" compare-insensitive 0= if\n\t\tlogoX @ logoY @ fbsdbw-logo\n\t\t2drop exit\n\tthen\n\t2dup s\" orb\" compare-insensitive 0= if\n\t\tlogoX @ logoY @ orb-logo\n\t\t2drop exit\n\tthen\n\t2dup s\" orbbw\" compare-insensitive 0= if\n\t\tlogoX @ logoY @ orbbw-logo\n\t\t2drop exit\n\tthen\n\n\t2drop\n;\n\n: clear-beastie ( -- ) \\ clears beastie from the screen\n\tlogoX @ logoY @\n\t2dup at-xy 34 spaces 1+\t\t2dup at-xy 34 spaces 1+\n\t2dup at-xy 34 spaces 1+\t\t2dup at-xy 34 spaces 1+\n\t2dup at-xy 34 spaces 1+\t\t2dup at-xy 34 spaces 1+\n\t2dup at-xy 34 spaces 1+\t\t2dup at-xy 34 spaces 1+\n\t2dup at-xy 34 spaces 1+\t\t2dup at-xy 34 spaces 1+\n\t2dup at-xy 34 spaces 1+\t\t2dup at-xy 34 spaces 1+\n\t2dup at-xy 34 spaces 1+\t\t2dup at-xy 34 spaces 1+\n\t2dup at-xy 34 spaces 1+\t\t2dup at-xy 34 spaces 1+\n\t2dup at-xy 34 spaces 1+\t\t2dup at-xy 34 spaces 1+\n\t2dup at-xy 34 spaces\t\t2drop\n\n\t\\ Put the cursor back at the bottom\n\t0 25 at-xy\n;\n\n: beastie-start ( -- ) \\ starts the menu\n\ts\" beastie_disable\" getenv\n\tdup -1 <> if\n\t\ts\" YES\" compare-insensitive 0= if\n\t\t\texit\n\t\tthen\n\telse\n\t\tdrop\n\tthen\n\n\ts\" loader_delay\" getenv\n\t-1 = if\n\t\ts\" include \/boot\/menu.rc\" evaluate\n\telse\n\t\tdrop\n\t\t.\" Loading Menu (Ctrl-C to Abort)\" cr\n\t\ts\" set delay_command='include \/boot\/menu.rc'\" evaluate\n\t\ts\" set delay_showdots\" evaluate\n\t\tdelay_execute\n\tthen\n;\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"d614c818b44b3bd2fe86c661d1acc615b7519634","subject":"Switch to ints for the On-Deck values.","message":"Switch to ints for the On-Deck values.","repos":"rbsexton\/gecko,rbsexton\/gecko,rbsexton\/gecko","old_file":"zero\/clock-umb\/forth\/Clock.fth","new_file":"zero\/clock-umb\/forth\/Clock.fth","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"mit","lang":"Forth"} {"commit":"f9693a54ffabf622bdc521dc7ad5d691bd1cf671","subject":"Removed the unused core.fth file.","message":"Removed the unused core.fth file.\n","repos":"hth313\/hthforth","old_file":"src\/lib\/core.fth","new_file":"src\/lib\/core.fth","new_contents":"","old_contents":"( block 1 -- Main load block )\n\nVARIABLE STATE ( compilation state variable )\n0 STATE ! ( interpreting by default )\n\nVARIABLE BLK\n: FH BLK @ + ; \\ relative block\n: LOAD BLK @ SWAP DUP BLK ! (LOAD) BLK ! ;\n\n30 LOAD\n( shadow 1 )\n( block 2 )\n( shadow 2 )\n( block 3 )\n( shadow 3 )\n\n( block 10 )\n( shadow 10 )\n( block 11 )\n( shadow 11 )\n( block 12 )\n( shadow 12 )\n\n( block 30 CORE words )\n\n1 FH 8 FH THRU\n10 FH LOAD \\ compiler\n( shadow 30 )\n( block 31 stack primitives )\n\n: ROT >R SWAP R> SWAP ;\n: ?DUP DUP IF DUP THEN ;\n\n( Not part of CORE, disabled at the moment )\n\\ : -ROT SWAP >R SWAP R> ; \\ or ROT ROT\n\\ : NIP ( n1 n2 -- n2 ) SWAP DROP ;\n\\ : TUCK ( n1 n2 -- n2 n1 n2 ) SWAP OVER ;\n\n: 2DROP DROP DROP ;\n: 2DUP OVER OVER ;\n: 2SWAP ROT >R ROT R> ;\n: 2OVER >R >R 2DUP R> R> 2SWAP ;\n( shadow 31 )\n( block 32 comparisons )\n\n-1 CONSTANT TRUE 0 CONSTANT FALSE\n\n: = ( n n -- f) XOR 0= ;\n: < ( n n -- f ) - 0< ;\n: > ( n n -- f ) SWAP < ;\n\n: MAX ( n n -- n ) 2DUP < IF SWAP THEN DROP ;\n: MIN ( n n -- n ) 2DUP > IF SWAP THEN DROP ;\n\n: WITHIN ( u ul uh -- f ) OVER - >R - R> U< ;\n( shadow 32 )\n( block 33 ALU )\n\n: 1+ 1 + ;\n: 1- 1 - ;\n: INVERT TRUE XOR ;\n: NEGATE INVERT 1+ ;\n: DNEGATE INVERT SWAP NEGATE SWAP OVER 0= - ;\n: S>D ( n -- d ) DUP 0< ; \\ sign extend\n: ABS S>D IF NEGATE THEN ;\n: DABS DUP 0< IF DNEGATE THEN ;\n\n: +- 0< IF NEGATE THEN ;\n: D+- 0< IF DNEGATE THEN ;\n\n( shadow 33 )\n( block 34 variables )\n\nVARIABLE BASE\n: DECIMAL 10 BASE ! ; : HEX 16 BASE ! ;\n\nVARIABLE DP\n( shadow 34 )\n( block 35 math )\n\n: SM\/REM ( d n -- r q ) \\ symmetric\n OVER >R >R DABS R@ ABS UM\/MOD\n R> R@ XOR 0< IF NEGATE THEN\n R> 0< IF >R NEGATE R> THEN ;\n\n: FM\/MOD ( d n -- r q ) \\ floored\n DUP 0< DUP >R IF NEGATE >R DNEGATE R> THEN\n >R DUP 0< IF R@ + THEN\n R> UM\/MOD R> IF >R NEGATE R> THEN ;\n\n: \/MOD OVER 0< SWAP FM\/MOD ;\n: MOD \/MOD DROP ;\n: \/ \/MOD SWAP DROP ;\n\n( shadow 35 )\n( block 36 math continued )\n\n: * UM* DROP ;\n: M* 2DUP XOR R> ABS SWAP ABS UM* R> D+- ;\n: *\/MOD >R M* R> FM\/MOD ;\n: *\/ *\/MOD SWAP DROP ;\n\n: 2* DUP + ;\n\\ 2\/ which is right shift is native\n\n: LSHIFT ( x1 u -- x2 )\n BEGIN DUP WHILE SWAP 2* SWAP 1- REPEAT DROP ;\n\n: RSHIFT ( x1 u -- x2 )\n BEGIN DUP WHILE SWAP 2\/ SWAP 1- REPEAT DROP ;\n ( shadow 36 )\n( block 37 numeric output primitives )\n\nVARIABLE HLD\n: HERE ( -- addr ) DP @ ;\n: PAD ( -- c-addr ) HERE 64 CHARS + ;\n\n: <# ( -- ) PAD HLD ! ;\n: #> ( xd -- c-addr u ) 2DROP HLD @ PAD OVER - ;\n: HOLD ( c -- ) HLD @ -1 CHARS - DUP HLD ! C! ;\n: DIGIT ( u -- c ) 9 OVER < 7 AND + 30 + ;\n: # ( ud1 -- ud2 )\n 0 BASE @ UM\/MOD >R BASE @ UM\/MOD SWAP DIGIT HOLD R> ;\n: #S ( ud1 -- ud2 ) BEGIN # 2DUP OR 0= UNTIL ;\n: SIGN ( n -- ) 0< IF 45 ( - ) HOLD THEN ;\n\n( shadow 37 )\n( block 38 memory access )\n\n: +! ( n a-addr -- ) DUP >R @ + R> ! ;\n: 2! ( x1 x2 a-addr -- ) SWAP OVER ! CELL+ ! ;\n: 2@ ( a-addr -- x1 x2 ) DUP CELL+ @ SWAP @ ;\n: COUNT ( c-addr1 -- c-addr2 u ) DUP CHAR+ SWAP C@ ;\n( shadow 38 )\n( block 39 )\n( shadow 39 )\n( block 40 compiler )\n\n: [ FALSE STATE ! ; IMMEDIATE\n: ] TRUE STATE ! ;\n\n: ALLOT ( n -- ) DP +! ;\n: HERE ( -- a ) DP @ ;\n: , ( n -- ) HERE [ 1 CELLS ] LITERAL ALLOT ! ;\n: COMPILE, ( xt -- ) HERE [ 1 INSTRS ] LITERAL ALLOT ! ;\n: LITERAL ( x -- ) ['] _LIT COMPILE, , ; IMMEDIATE\n\n: VARIABLE CREATE 1 CELLS ALLOT ;\n: CONSTANT CREATE , DOES> @ ;\n\n( Colon definitions )\n: : CREATE ] ;\n: ; POSTPONE EXIT SMUDGE [ ; IMMEDIATE\n\n( shadow 40 )\n( block 41 )\n( shadow 41 )\n( block 42 interpreter )\n\nCREATE _INPUT-BUFFER 80 CHARS ALLOT ( may do this internally? )\n\n: EVALUATE >IN @ >R 0 >IN ! SOURCE >R >R #IN 2! _INTERPRET\n R> R> #IN 2! R> >IN ! ;\n\n: QUIT _RESET-RSTACK\n BEGIN\n BEGIN\n\t _READ-LINE 0 >IN ! _INPUT-BUFFER 0 EVALUATE CR\n\t STATE @\n UNTIL .\" ok \" ( exhausted input in interpretation mode )\n AGAIN ;\n( shadow 42 )\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"b7094e0505258894c7f914afa147cc427c3e3423","subject":"Re-order things.","message":"Re-order things.","repos":"rbsexton\/sockpuppet,rbsexton\/sockpuppet","old_file":"forth\/SAPI-core.fth","new_file":"forth\/SAPI-core.fth","new_contents":"\\ Wrappers for SAPI Core functions\n\\ SVC 0: Return the version of the API in use.\n\\ SVC 1: Return the address of the shared variables table\n\\ SVC 2: putchar\n\\ SVC 3: getchar\n\\ SVC 4: charsavail\n\n\\ SVC 5: Reserved\n\\ SVC 6: Reserved\n\\ SVC 7: Reserved\n\n\\ SVC 8: Watchdog Refresh\n\\ SVC 9: Return Millisecond ticker value.\n\\ SVC 10: The number of CPU cycles consumed in the last second.\n\n\\ 2-4 are for use by the serial io routines, and are \n\\ defined elsewhere.\n\n\\ Note that the system call number is embedded into the instruction,\n\\ so this is not so easily parameterized.\n\n#0 equ SAPI_VEC_VERSION\n#1 equ SAPI_VEC_VARS\n#2 equ SAPI_VEC_PUTCHAR\n#3 equ SAPI_VEC_GETCHAR\n#4 equ SAPI_VEC_CHARSAVAIL\n\n#8 equ SAPI_VEC_PETWATCHDOG\n#9 equ SAPI_VEC_USAGE\n#10 equ SAPI_VEC_GETMS\n\n\\ **********************************************************************\n\\ SVC 0: Return the version of the API in use.\n\\ **********************************************************************\nCODE SAPI-Version \\ -- n \n\t\\ Push TOS, and place the result there.\t\n\tsvc # SAPI_VEC_VERSION \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 1: Get the address of the shared variable list\n\\ **********************************************************************\nCODE GetSharedVars \\ -- n \n\tsvc # SAPI_VEC_VARS \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 8: Refresh the watchdog\n\\ **********************************************************************\nCODE PetWatchDog \\ -- \n\tsvc # SAPI_VEC_PETWATCHDOG\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 9: Return Millisecond ticker value.\n\\ **********************************************************************\nCODE Ticks \\ -- n \n\tsvc # SAPI_VEC_GETMS\n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 10: The number of CPU cycles consumed in the last second.\n\\ **********************************************************************\nCODE GetUsage \\ -- n \n\tsvc # SAPI_VEC_USAGE\n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n","old_contents":"\\ Wrappers for SAPI Core functions\n\\ SVC 0: Return the version of the API in use.\n\\ SVC 1: Return the address of the shared variables table\n\\ SVC 2: putchar\n\\ SVC 3: getchar\n\\ SVC 4: charsavail\n\n\\ SVC 5: Reserved\n\\ SVC 6: Reserved\n\\ SVC 7: Reserved\n\n\\ SVC 8: Watchdog Refresh\n\\ SVC 9: Return Millisecond ticker value.\n\\ SVC 10: The number of CPU cycles consumed in the last second.\n\n\\ 2-4 are for use by the serial io routines, and are \n\\ defined elsewhere.\n\n\\ Note that the system call number is embedded into the instruction,\n\\ so this is not so easily parameterized.\n\n#0 equ SAPI_VEC_VERSION\n#1 equ SAPI_VEC_PUTCHAR\n#2 equ SAPI_VEC_GETCHAR\n#3 equ SAPI_VEC_CHARSAVAIL\n\n#8 equ SAPI_VEC_VARS\n#9 equ SAPI_VEC_USAGE\n#10 equ SAPI_VEC_GETMS\n\n\\ **********************************************************************\n\\ SVC 0: Return the version of the API in use.\n\\ **********************************************************************\nCODE SAPI-Version \\ -- n \n\t\\ Push TOS, and place the result there.\t\n\tsvc # SAPI_VEC_VERSION \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 1: Get the address of the shared variable list\n\\ **********************************************************************\nCODE GetSharedVars \\ -- n \n\tsvc # SAPI_VEC_VARS \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 9: Return Millisecond ticker value.\n\\ **********************************************************************\nCODE Ticks \\ -- n \n\tsvc # SAPI_VEC_GETMS\n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 10: The number of CPU cycles consumed in the last second.\n\\ **********************************************************************\nCODE GetUsage \\ -- n \n\tsvc # SAPI_VEC_USAGE\n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"da7ee8111ca014cfed869962d945e2b3be8f84b3","subject":"update vector to use shorthand props","message":"update vector to use shorthand props\n","repos":"cooper\/ferret","old_file":"std\/Math\/Vector.frt","new_file":"std\/Math\/Vector.frt","new_contents":"package Math\nclass Vector\n#< Represents a [vector](https:\/\/en.wikipedia.org\/wiki\/Vector_space) of any\n#| dimension.\n\n$docOption_instanceName = \"v\"\n\n#> Creates a vector with the given components.\ninit {\n want @items: Num...\n if @dimension < 1\n throw Error(:DimensionError, \"Need dimension >= 1D\")\n}\n\n#> dimension of the vector\n.dimension -> @items.length\n\n#> human-readable dimension of the vector\n.dimensionHR -> @dimension + \"D\"\n\n#> magnitude of the vector\n.magnitude -> @items.map! { -> $_ ^ 2 }.sum.sqrt\n\n#> unit vector in the direction of this vector\n.unitVector -> *self \/ @magnitude\n\n#> returns the unit vector in the direction of the given axis\nmethod axisUnitVector {\n need $axis: VectorAxis #< axis number or letter, starting at 1 or \"i\"\n return Vector.axisUnitVector(@dimension, $axis)\n}\n\n.x -> *self[0] #< for a >=1D vector, the first comonent\n.y -> *self[1] #< for a >=2D vector, the second component\n.z -> *self[2] #< for a >=3D vector, the third component\n\n#> for a 2D vector, its direction, measured in radians\n.direction {\n if @dimension != 2\n throw Error(:DimensionError, \"Direction only exists in 2D\")\n return Math.atan2(@y, @x)\n}\n\n#> addition of two vectors\noperator + {\n need $ehs: Vector\n if $ehs.dimension != @dimension\n throw Error(:DimensionError, \"Dimension mismatch $ehs.dimensionHR != @dimensionHR\")\n $items = gather for $i in 0..@items.lastIndex {\n take *self[$i] + $ehs[$i]\n }\n return Vector(items: $items)\n}\n\n#> allows you to take the opposite vector `-$u`\noperator - {\n need $lhs: Num\n if $lhs != 0\n throw(:InvalidOperation, \"Unsupported operation\")\n return Vector(items: gather for $x in @items {\n take -$x\n })\n}\n\n#> subtraction of a vector from another\noperator - {\n need $rhs: Vector\n if $rhs.dimension != @dimension\n throw Error(:DimensionError, \"Dimension mismatch $rhs.dimensionHR != @dimensionHR\")\n $items = gather for $i in 0..@items.lastIndex {\n take *self[$i] - $rhs[$i]\n }\n return Vector(items: $items)\n}\n\n#> scalar multiplication of the vector\noperator * {\n need $ehs: Num\n return Vector(items: @items.map! { -> $_ * $ehs })\n}\n\n#> scalar division of the vector\noperator \/ {\n need $rhs: Num\n return *self * (1 \/ $rhs)\n}\n\n#> dot product of two vectors\noperator * {\n need $ehs: Vector\n return @dot($ehs)\n}\n\n#> vector equality\noperator == {\n need $ehs: Vector\n if $ehs.dimension != @dimension\n return false\n for $i in 0..@items.lastIndex {\n if *self[$i] == $ehs[$i]\n next\n return false\n }\n return true\n}\n\n#> dot product of this vector and another of the same dimension\nmethod dot {\n need $ehs: Vector\n if $ehs.dimension != @dimension\n throw Error(:DimensionError, \"Dimension mismatch $ehs.dimensionHR != @dimensionHR\")\n $dot = 0\n for $i in 0..@items.lastIndex {\n $dot += *self[$i] * $ehs[$i]\n }\n return $dot\n}\n\n#> cross product of two 3D vectors\nmethod cross {\n need $ehs: Vector\n if $ehs.dimension != 3 || @dimension != 3\n throw Error(:DimensionError, \"Cross product only exists in 3D\")\n @a = *self[1] * $ehs[2] - *self[2] * $ehs[1]\n @b = *self[2] * $ehs[0] - *self[0] * $ehs[2]\n @c = *self[0] * $ehs[1] - *self[1] * $ehs[0]\n return Vector(@a, @b, @c)\n}\n\n#> angle between this vector and another of the same dimension, measured in\n#| radians\nmethod angleBetween {\n need $ehs: Vector\n # a\u00b7b = |a||b|cos\u03b8\n $cos\u03b8 = @dot($ehs) \/ (@magnitude * $ehs.magnitude)\n return Math.acos($cos\u03b8)\n}\n\n#> true if this vector is orthogonal to another of the same dimension\n# consider: the dot product is also zero if either is a zero vector. should\n# we still return true in that case?\nmethod orthogonalTo {\n need $ehs: Vector\n return @dot($ehs) == 0\n}\n\n#> true if this vector is parallel to another of the same dimension\nmethod parallelTo {\n need $ehs: Vector\n if $ehs.dimension != @dimension\n throw Error(:DimensionError, \"Dimension mismatch $ehs.dimensionHR != @dimensionHR\")\n $u1 = @unitVector\n $u2 = $ehs.unitVector\n if $u1 == $u2 || -$u1 == $u2\n return true\n return false\n}\n\n#> fetches the component at the given index. Allows Vector to conform to\n#| IndexedRead such that `$vector[N]` is the N+1th component.\nmethod getValue {\n need $index: Num\n $n = $index + 1\n if @dimension < $n\n throw Error(:DimensionError, \"@dimensionHR vector has no component $n\")\n return @items[$index]\n}\n\n#> returns a copy of the vector\nmethod copy {\n return Vector(items: @items.copy!)\n}\n\nmethod description {\n return \"<\" + @items.join(\", \") + \">\"\n}\n\n#> returns the zero vector in the given dimension\nfunc zeroVector {\n need $dimension: Num\n if $dimension < 1\n throw Error(:DimensionError, \"Need dimension >= 1D\")\n return Vector(items: gather for $i in 1..$dimension { take 0 })\n}\n\n#> returns the unit vector for the given dimension and axis\nfunc axisUnitVector {\n need $dimension: Num\n need $axis: VectorAxis #< axis number or letter, starting at 1 or \"i\"\n if $dimension < 1\n throw Error(:DimensionError, \"Need dimension >= 1D\")\n $items = gather for $i in 1..$dimension {\n if $i == $axis {\n take 1\n next\n }\n take 0\n }\n return Vector(items: $items)\n}\n\nfunc _axisToNumber {\n need $axis: Num | Char\n if $axis.*isa(Num)\n return $axis\n $o = $axis.ord\n if $o > 119\n return $o - 119\n return $o - 104\n}\n\n#> An interface which accepts an axis letter starting at \"i\" or number starting\n#| at 1. For instance, a 3D vector is represented by axes i, j, and k, which\n#| correspond to the numbers 1, 2, and 3, respectively.\ntype VectorAxis {\n #> converts letters starting at 'i' to axis numbers\n transform _axisToNumber($_)\n}\n","old_contents":"package Math\nclass Vector\n#< Represents a [vector](https:\/\/en.wikipedia.org\/wiki\/Vector_space) of any\n#| dimension.\n\n$docOption_instanceName = \"v\"\n\n#> Creates a vector with the given components.\ninit {\n want @items: Num...\n if @dimension < 1\n throw Error(:DimensionError, \"Need dimension >= 1D\")\n}\n\n#> dimension of the vector\nprop dimension {\n return @items.length\n}\n\n#> human-readable dimension of the vector\nprop dimensionHR {\n return @dimension + \"D\"\n}\n\n#> magnitude of the vector\nprop magnitude {\n return @items.map! { -> $_ ^ 2 }.sum.sqrt\n}\n\n#> unit vector in the direction of this vector\nprop unitVector {\n return *self \/ @magnitude\n}\n\n#> returns the unit vector in the direction of the given axis\nmethod axisUnitVector {\n need $axis: VectorAxis #< axis number or letter, starting at 1 or \"i\"\n return Vector.axisUnitVector(@dimension, $axis)\n}\n\n#> for a >=1D vector, the first comonent\nprop x {\n return *self[0]\n}\n\n#> for a >=2D vector, the second component\nprop y {\n return *self[1]\n}\n\n#> for a >=3D vector, the third component\nprop z {\n return *self[2]\n}\n\n#> for a 2D vector, its direction, measured in radians\nprop direction {\n if @dimension != 2\n throw Error(:DimensionError, \"Direction only exists in 2D\")\n return Math.atan2(@y, @x)\n}\n\n#> addition of two vectors\noperator + {\n need $ehs: Vector\n if $ehs.dimension != @dimension\n throw Error(:DimensionError, \"Dimension mismatch $ehs.dimensionHR != @dimensionHR\")\n $items = gather for $i in 0..@items.lastIndex {\n take *self[$i] + $ehs[$i]\n }\n return Vector(items: $items)\n}\n\n#> allows you to take the opposite vector `-$u`\noperator - {\n need $lhs: Num\n if $lhs != 0\n throw(:InvalidOperation, \"Unsupported operation\")\n return Vector(items: gather for $x in @items {\n take -$x\n })\n}\n\n#> subtraction of a vector from another\noperator - {\n need $rhs: Vector\n if $rhs.dimension != @dimension\n throw Error(:DimensionError, \"Dimension mismatch $rhs.dimensionHR != @dimensionHR\")\n $items = gather for $i in 0..@items.lastIndex {\n take *self[$i] - $rhs[$i]\n }\n return Vector(items: $items)\n}\n\n#> scalar multiplication of the vector\noperator * {\n need $ehs: Num\n return Vector(items: @items.map! { -> $_ * $ehs })\n}\n\n#> scalar division of the vector\noperator \/ {\n need $rhs: Num\n return *self * (1 \/ $rhs)\n}\n\n#> dot product of two vectors\noperator * {\n need $ehs: Vector\n return @dot($ehs)\n}\n\n#> vector equality\noperator == {\n need $ehs: Vector\n if $ehs.dimension != @dimension\n return false\n for $i in 0..@items.lastIndex {\n if *self[$i] == $ehs[$i]\n next\n return false\n }\n return true\n}\n\n#> dot product of this vector and another of the same dimension\nmethod dot {\n need $ehs: Vector\n if $ehs.dimension != @dimension\n throw Error(:DimensionError, \"Dimension mismatch $ehs.dimensionHR != @dimensionHR\")\n $dot = 0\n for $i in 0..@items.lastIndex {\n $dot += *self[$i] * $ehs[$i]\n }\n return $dot\n}\n\n#> cross product of two 3D vectors\nmethod cross {\n need $ehs: Vector\n if $ehs.dimension != 3 || @dimension != 3\n throw Error(:DimensionError, \"Cross product only exists in 3D\")\n @a = *self[1] * $ehs[2] - *self[2] * $ehs[1]\n @b = *self[2] * $ehs[0] - *self[0] * $ehs[2]\n @c = *self[0] * $ehs[1] - *self[1] * $ehs[0]\n return Vector(@a, @b, @c)\n}\n\n#> angle between this vector and another of the same dimension, measured in\n#| radians\nmethod angleBetween {\n need $ehs: Vector\n # a\u00b7b = |a||b|cos\u03b8\n $cos\u03b8 = @dot($ehs) \/ (@magnitude * $ehs.magnitude)\n return Math.acos($cos\u03b8)\n}\n\n#> true if this vector is orthogonal to another of the same dimension\n# consider: the dot product is also zero if either is a zero vector. should\n# we still return true in that case?\nmethod orthogonalTo {\n need $ehs: Vector\n return @dot($ehs) == 0\n}\n\n#> true if this vector is parallel to another of the same dimension\nmethod parallelTo {\n need $ehs: Vector\n if $ehs.dimension != @dimension\n throw Error(:DimensionError, \"Dimension mismatch $ehs.dimensionHR != @dimensionHR\")\n $u1 = @unitVector\n $u2 = $ehs.unitVector\n if $u1 == $u2 || -$u1 == $u2\n return true\n return false\n}\n\n#> fetches the component at the given index. Allows Vector to conform to\n#| IndexedRead such that `$vector[N]` is the N+1th component.\nmethod getValue {\n need $index: Num\n $n = $index + 1\n if @dimension < $n\n throw Error(:DimensionError, \"@dimensionHR vector has no component $n\")\n return @items[$index]\n}\n\n#> returns a copy of the vector\nmethod copy {\n return Vector(items: @items.copy!)\n}\n\nmethod description {\n return \"<\" + @items.join(\", \") + \">\"\n}\n\n#> returns the zero vector in the given dimension\nfunc zeroVector {\n need $dimension: Num\n if $dimension < 1\n throw Error(:DimensionError, \"Need dimension >= 1D\")\n return Vector(items: gather for $i in 1..$dimension { take 0 })\n}\n\n#> returns the unit vector for the given dimension and axis\nfunc axisUnitVector {\n need $dimension: Num\n need $axis: VectorAxis #< axis number or letter, starting at 1 or \"i\"\n if $dimension < 1\n throw Error(:DimensionError, \"Need dimension >= 1D\")\n $items = gather for $i in 1..$dimension {\n if $i == $axis {\n take 1\n next\n }\n take 0\n }\n return Vector(items: $items)\n}\n\nfunc _axisToNumber {\n need $axis: Num | Char\n if $axis.*isa(Num)\n return $axis\n $o = $axis.ord\n if $o > 119\n return $o - 119\n return $o - 104\n}\n\n#> An interface which accepts an axis letter starting at \"i\" or number starting\n#| at 1. For instance, a 3D vector is represented by axes i, j, and k, which\n#| correspond to the numbers 1, 2, and 3, respectively.\ntype VectorAxis {\n #> converts letters starting at 'i' to axis numbers\n transform _axisToNumber($_)\n}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"62455c20192f9fc404a3fb650d76deec4639d655","subject":"Put some version checking.","message":"Put some version checking.\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/loader.4th","new_file":"sys\/boot\/forth\/loader.4th","new_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\ns\" arch-alpha\" environment? [if]\ns\" loader_version\" environment? 3 < abort\" Loader version 0.3+ required\"\n[then]\n\ns\" arch-i386\" environment? [if]\ns\" loader_version\" environment? 8 < abort\" Loader version 0.8+ required\"\n[then]\n\ninclude \/boot\/support.4th\n\nonly forth definitions also support-functions\n\n\\ ***** boot-conf\n\\\n\\\tPrepares to boot as specified by loaded configuration files.\n\nalso support-functions definitions\n\n: bootpath s\" \/boot\/\" ;\n: modulepath s\" module_path\" ;\n: saveenv ( addr len | 0 -1 -- addr' len | 0 -1 )\n dup -1 = if exit then\n dup allocate abort\" Out of memory\"\n swap 2dup 2>r\n move\n 2r>\n;\n: freeenv ( addr len | 0 -1 )\n -1 = if drop else free abort\" Freeing error\" then\n;\n: restoreenv ( addr len | 0 -1 -- )\n dup -1 = if ( it wasn't set )\n 2drop\n modulepath unsetenv\n else\n over >r\n modulepath setenv\n r> free abort\" Freeing error\"\n then\n;\n\nonly forth also support-functions also builtins definitions\n\n: boot-conf ( args 1 | 0 \"args\" -- flag )\n 0 1 unload drop\n\n 0= if ( interpreted )\n \\ Get next word on the command line\n bl word count\n ?dup 0= if ( there wasn't anything )\n drop 0\n else ( put in the number of strings )\n 1\n then\n then ( interpreted )\n\n if ( there are arguments )\n \\ Try to load the kernel\n s\" kernel_options\" getenv dup -1 = if drop 2dup 1 else 2over 2 then\n\n 1 load if ( load command failed )\n \\ Remove garbage from the stack\n\n \\ Set the environment variable module_path, and try loading\n \\ the kernel again.\n\n \\ First, save module_path value\n modulepath getenv saveenv dup -1 = if 0 swap then 2>r\n\n \\ Sets the new value\n 2dup modulepath setenv\n\n \\ Try to load the kernel\n s\" load ${kernel} ${kernel_options}\" ['] evaluate catch\n if ( load failed yet again )\n\t\\ Remove garbage from the stack\n\t2drop\n\n\t\\ Try prepending \/boot\/\n\tbootpath 2over nip over + allocate\n\tif ( out of memory )\n\t 2drop 2drop\n\t 2r> restoreenv\n\t 100 exit\n\tthen\n\n\t0 2swap strcat 2swap strcat\n\t2dup modulepath setenv\n\n\tdrop free if ( freeing memory error )\n\t 2drop\n\t 2r> restoreenv\n\t 100 exit\n\tthen\n \n\t\\ Now, once more, try to load the kernel\n\ts\" load ${kernel} ${kernel_options}\" ['] evaluate catch\n\tif ( failed once more )\n\t 2drop\n\t 2r> restoreenv\n\t 100 exit\n\tthen\n\n else ( we found the kernel on the path passed )\n\n\t2drop ( discard command line arguments )\n\n then ( could not load kernel from directory passed )\n\n \\ Load the remaining modules, if the kernel was loaded at all\n ['] load_modules catch if 2r> restoreenv 100 exit then\n\n \\ Call autoboot to perform the booting\n 0 1 autoboot\n\n \\ Keep new module_path\n 2r> freeenv\n\n exit\n then ( could not load kernel with name passed )\n\n 2drop ( discard command line arguments )\n\n else ( try just a straight-forward kernel load )\n s\" load ${kernel} ${kernel_options}\" ['] evaluate catch\n if ( kernel load failed ) 2drop 100 exit then\n\n then ( there are command line arguments )\n\n \\ Load the remaining modules, if the kernel was loaded at all\n ['] load_modules catch if 100 exit then\n\n \\ Call autoboot to perform the booting\n 0 1 autoboot\n;\n\nalso forth definitions\nbuiltin: boot-conf\nonly forth definitions also support-functions\n\n\\ ***** check-password\n\\\n\\\tIf a password was defined, execute autoboot and ask for\n\\\tpassword if autoboot returns.\n\n: check-password\n password .addr @ if\n 0 autoboot\n false >r\n begin\n bell emit bell emit\n .\" Password: \"\n password .len @ read-password\n dup password .len @ = if\n 2dup password .addr @ password .len @\n compare 0= if r> drop true >r then\n then\n drop free drop\n r@\n until\n r> drop\n then\n;\n\n\\ ***** start\n\\\n\\ Initializes support.4th global variables, sets loader_conf_files,\n\\ process conf files, and, if any one such file was succesfully\n\\ read to the end, load kernel and modules.\n\n: start ( -- ) ( throws: abort & user-defined )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n \\ Will *NOT* try to load kernel and modules if no configuration file\n \\ was succesfully loaded!\n any_conf_read? if\n load_kernel\n load_modules\n then\n;\n\n\\ ***** initialize\n\\\n\\\tOverrides support.4th initialization word with one that does\n\\\teverything start one does, short of loading the kernel and\n\\\tmodules. Returns a flag\n\n: initialize ( -- flag )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n any_conf_read?\n;\n\n\\ ***** read-conf\n\\\n\\\tRead a configuration file, whose name was specified on the command\n\\\tline, if interpreted, or given on the stack, if compiled in.\n\n: (read-conf) ( addr len -- )\n conf_files .addr @ ?dup if free abort\" Fatal error freeing memory\" then\n strdup conf_files .len ! conf_files .addr !\n include_conf_files \\ Will recurse on new loader_conf_files definitions\n;\n\n: read-conf ( | addr len -- ) ( throws: abort & user-defined )\n state @ if\n \\ Compiling\n postpone (read-conf)\n else\n \\ Interpreting\n bl parse (read-conf)\n then\n; immediate\n\n\\ ***** enable-module\n\\\n\\ Turn a module loading on.\n\n: enable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n true r> module.flag !\n .\" will be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** disable-module\n\\\n\\ Turn a module loading off.\n\n: disable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n false r> module.flag !\n .\" will not be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** toggle-module\n\\\n\\ Turn a module loading on\/off.\n\n: toggle-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n r@ module.flag @ 0= dup r> module.flag !\n if\n .\" will be loaded.\" cr\n else\n .\" will not be loaded.\" cr\n then\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** show-module\n\\\n\\\tShow loading information about a module.\n\n: show-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n .\" Name: \" r@ module.name dup .addr @ swap .len @ type cr\n .\" Path: \" r@ module.loadname dup .addr @ swap .len @ type cr\n .\" Type: \" r@ module.type dup .addr @ swap .len @ type cr\n .\" Flags: \" r@ module.args dup .addr @ swap .len @ type cr\n .\" Before load: \" r@ module.beforeload dup .addr @ swap .len @ type cr\n .\" After load: \" r@ module.afterload dup .addr @ swap .len @ type cr\n .\" Error: \" r@ module.loaderror dup .addr @ swap .len @ type cr\n .\" Status: \" r> module.flag @ if .\" Load\" else .\" Don't load\" then cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ Words to be used inside configuration files\n\n: retry false ; \\ For use in load error commands\n: ignore true ; \\ For use in load error commands\n\n\\ Return to strict forth vocabulary\n\nonly forth also\n\n","old_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\ninclude \/boot\/support.4th\n\nonly forth definitions also support-functions\n\n\\ ***** boot-conf\n\\\n\\\tPrepares to boot as specified by loaded configuration files.\n\nalso support-functions definitions\n\n: bootpath s\" \/boot\/\" ;\n: modulepath s\" module_path\" ;\n: saveenv ( addr len | 0 -1 -- addr' len | 0 -1 )\n dup -1 = if exit then\n dup allocate abort\" Out of memory\"\n swap 2dup 2>r\n move\n 2r>\n;\n: freeenv ( addr len | 0 -1 )\n -1 = if drop else free abort\" Freeing error\" then\n;\n: restoreenv ( addr len | 0 -1 -- )\n dup -1 = if ( it wasn't set )\n 2drop\n modulepath unsetenv\n else\n over >r\n modulepath setenv\n r> free abort\" Freeing error\"\n then\n;\n\nonly forth also support-functions also builtins definitions\n\n: boot-conf ( args 1 | 0 \"args\" -- flag )\n 0 1 unload drop\n\n 0= if ( interpreted )\n \\ Get next word on the command line\n bl word count\n ?dup 0= if ( there wasn't anything )\n drop 0\n else ( put in the number of strings )\n 1\n then\n then ( interpreted )\n\n if ( there are arguments )\n \\ Try to load the kernel\n s\" kernel_options\" getenv dup -1 = if drop 2dup 1 else 2over 2 then\n\n 1 load if ( load command failed )\n \\ Remove garbage from the stack\n\n \\ Set the environment variable module_path, and try loading\n \\ the kernel again.\n\n \\ First, save module_path value\n modulepath getenv saveenv dup -1 = if 0 swap then 2>r\n\n \\ Sets the new value\n 2dup modulepath setenv\n\n \\ Try to load the kernel\n s\" load ${kernel} ${kernel_options}\" ['] evaluate catch\n if ( load failed yet again )\n\t\\ Remove garbage from the stack\n\t2drop\n\n\t\\ Try prepending \/boot\/\n\tbootpath 2over nip over + allocate\n\tif ( out of memory )\n\t 2drop 2drop\n\t 2r> restoreenv\n\t 100 exit\n\tthen\n\n\t0 2swap strcat 2swap strcat\n\t2dup modulepath setenv\n\n\tdrop free if ( freeing memory error )\n\t 2drop\n\t 2r> restoreenv\n\t 100 exit\n\tthen\n \n\t\\ Now, once more, try to load the kernel\n\ts\" load ${kernel} ${kernel_options}\" ['] evaluate catch\n\tif ( failed once more )\n\t 2drop\n\t 2r> restoreenv\n\t 100 exit\n\tthen\n\n else ( we found the kernel on the path passed )\n\n\t2drop ( discard command line arguments )\n\n then ( could not load kernel from directory passed )\n\n \\ Load the remaining modules, if the kernel was loaded at all\n ['] load_modules catch if 2r> restoreenv 100 exit then\n\n \\ Call autoboot to perform the booting\n 0 1 autoboot\n\n \\ Keep new module_path\n 2r> freeenv\n\n exit\n then ( could not load kernel with name passed )\n\n 2drop ( discard command line arguments )\n\n else ( try just a straight-forward kernel load )\n s\" load ${kernel} ${kernel_options}\" ['] evaluate catch\n if ( kernel load failed ) 2drop 100 exit then\n\n then ( there are command line arguments )\n\n \\ Load the remaining modules, if the kernel was loaded at all\n ['] load_modules catch if 100 exit then\n\n \\ Call autoboot to perform the booting\n 0 1 autoboot\n;\n\nalso forth definitions\nbuiltin: boot-conf\nonly forth definitions also support-functions\n\n\\ ***** check-password\n\\\n\\\tIf a password was defined, execute autoboot and ask for\n\\\tpassword if autoboot returns.\n\n: check-password\n password .addr @ if\n 0 autoboot\n false >r\n begin\n bell emit bell emit\n .\" Password: \"\n password .len @ read-password\n dup password .len @ = if\n 2dup password .addr @ password .len @\n compare 0= if r> drop true >r then\n then\n drop free drop\n r@\n until\n r> drop\n then\n;\n\n\\ ***** start\n\\\n\\ Initializes support.4th global variables, sets loader_conf_files,\n\\ process conf files, and, if any one such file was succesfully\n\\ read to the end, load kernel and modules.\n\n: start ( -- ) ( throws: abort & user-defined )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n \\ Will *NOT* try to load kernel and modules if no configuration file\n \\ was succesfully loaded!\n any_conf_read? if\n load_kernel\n load_modules\n then\n;\n\n\\ ***** initialize\n\\\n\\\tOverrides support.4th initialization word with one that does\n\\\teverything start one does, short of loading the kernel and\n\\\tmodules. Returns a flag\n\n: initialize ( -- flag )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n any_conf_read?\n;\n\n\\ ***** read-conf\n\\\n\\\tRead a configuration file, whose name was specified on the command\n\\\tline, if interpreted, or given on the stack, if compiled in.\n\n: (read-conf) ( addr len -- )\n conf_files .addr @ ?dup if free abort\" Fatal error freeing memory\" then\n strdup conf_files .len ! conf_files .addr !\n include_conf_files \\ Will recurse on new loader_conf_files definitions\n;\n\n: read-conf ( | addr len -- ) ( throws: abort & user-defined )\n state @ if\n \\ Compiling\n postpone (read-conf)\n else\n \\ Interpreting\n bl parse (read-conf)\n then\n; immediate\n\n\\ ***** enable-module\n\\\n\\ Turn a module loading on.\n\n: enable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n true r> module.flag !\n .\" will be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** disable-module\n\\\n\\ Turn a module loading off.\n\n: disable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n false r> module.flag !\n .\" will not be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** toggle-module\n\\\n\\ Turn a module loading on\/off.\n\n: toggle-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n r@ module.flag @ 0= dup r> module.flag !\n if\n .\" will be loaded.\" cr\n else\n .\" will not be loaded.\" cr\n then\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** show-module\n\\\n\\\tShow loading information about a module.\n\n: show-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n .\" Name: \" r@ module.name dup .addr @ swap .len @ type cr\n .\" Path: \" r@ module.loadname dup .addr @ swap .len @ type cr\n .\" Type: \" r@ module.type dup .addr @ swap .len @ type cr\n .\" Flags: \" r@ module.args dup .addr @ swap .len @ type cr\n .\" Before load: \" r@ module.beforeload dup .addr @ swap .len @ type cr\n .\" After load: \" r@ module.afterload dup .addr @ swap .len @ type cr\n .\" Error: \" r@ module.loaderror dup .addr @ swap .len @ type cr\n .\" Status: \" r> module.flag @ if .\" Load\" else .\" Don't load\" then cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ Words to be used inside configuration files\n\n: retry false ; \\ For use in load error commands\n: ignore true ; \\ For use in load error commands\n\n\\ Return to strict forth vocabulary\n\nonly forth also\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"e9053da3e5d470b228582bcab982fa878e205736","subject":"Switch to callbacks for outgoing flow control.","message":"Switch to callbacks for outgoing flow control.","repos":"rbsexton\/sockpuppet,rbsexton\/sockpuppet","old_file":"forth\/serCM3_sapi_p.fth","new_file":"forth\/serCM3_sapi_p.fth","new_contents":"\\ serCM3_sapi_p.fth - SAPI polled RX, polled TX, serial communication drivers\n\\ Written to run against the SockPuppet API.\n\n((\nAdapted from: the LPC polled driver.\n))\n\nonly forth definitions\nvariable cnt.pause \n\n\\ ==============\n\\ *! serCM3_sapi_p\n\\ *T SAPI polled serial driver\n\\ ==============\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\n\\ ** using the internal UARTs via the SAPI call layer.\n\n\n\\ ****************\n\\ *S Configuration\n\\ ****************\n\\ *P Configuration is managed by the SAPI\n\n\\ ********\n\\ *S Tools\n\\ ********\n\ntarget\n\n\\ ********************\n\\ *S Serial primitives\n\\ ********************\ninternal\n\n: +FaultConsole\t( -- ) ;\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\n\\ ** for more details.\n\ntarget\n\nCODE (seremitfc)\t\\ char base --\n\\ *G Service call for a single char - just fill in the registers\n\\ from the stack and make the call, and get back the flow control feedback\n\\ Put TOS into r0, pull r1 off the stack, and refresh the stack.\n\tmov r0, tos\n\tldr r1, [ psp ], # 4\t\n\tsvc # SAPI_VEC_PUTCHAR\t\n\tmov tos, r0\n next,\nEND-CODE\n\n: (seremit)\t\\ char base -- \n\\ *G Wrapped call that checks for throttling, and if so,\n\\ calls PAUSE to let another task run. Count these events for debugging purposes.\n\tDUP >R (seremitfc)\n\t0<> IF 1 cnt.pause +!\n\t\tself tcb.bbstatus @ R> 0 setiocallback drop stop \n\t\telse R> DROP then\n\t;\n\n: (sertype)\t\\ caddr len base --\n\\ *G Transmit a string on the given UART.\n -rot bounds\n ?do i c@ over (seremit) loop\n drop\n;\n\n: (sercr)\t\\ base --\n\\ *G Transmit a CR\/LF pair on the given UART.\n $0D over (seremit) $0A swap (seremit)\n;\n\nCODE (sergetchar) \\ base -- c\n\\ *G Get a character from the port\n\tmov r0, tos\t\n\tsvc # SAPI_VEC_GETCHAR\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE (serkey?) \\ base -- t\/f\n\\ *G Return true if the given UART has a character avilable to read.\n\\ The call returns 0 or 1. \n\tmov r0, tos\n\tsvc # SAPI_VEC_CHARSAVAIL\t\t\n\tmov tos, r0\n\tnext,\t\nEND-CODE\n\n: (serkey-basic)\n\tbegin pause \n\tdup (serkey?) until \n\t(sergetchar)\n;\n\n: (serkey-sleep?)\n\tself tcb.bbstatus @ over 1 setiocallback drop ( base )\n\tself halt \n\tdup (serkey?) IF self restart ELSE PAUSE THEN \\ We are now armed and ready to block\n (serkey?) \n;\n\n\\ *G Wait for a character to come available on the given UART and\n\\ ** return the character.\n\\ Advanced usage - Register a callback. \n\\ The tricky part is not screwing things up by missing a character\n\\ in the window between when you register, and when you pick up your\n\\ character. The way to do that is by registering, then self \n\\ halting, and then checking for a new character. That ensures that\n\\ if a character has slipped in, you will catch it.\n: (serkey)\t\\ base -- char\n\tbegin dup (serkey-sleep?) until (sergetchar)\n;\n\nexternal \n\n: seremit0\t\\ char --\n\\ *G Transmit a character on UART0.\n 0 (seremit) ;\n: sertype0\t\\ c-addr len --\n\\ *G Transmit a string on UART0.\n 0 (sertype) ;\n: sercr0\t\\ --\n\\ *G Issue a CR\/LF pair to UART0.\n 0 (sercr) ;\n: serkey?0\t\\ -- flag\n\\ *G Return true if UART0 has a character available.\n 0 (serkey?) ;\n: serkey0\t\\ -- char\n\\ *G Wait for a character on UART0.\n 0 (serkey) ;\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\n\\ *G Generic I\/O device for UART0.\n ' serkey0 ,\t\t\\ -- char ; receive char\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\n ' seremit0 ,\t\t\\ -- char ; display char\n ' sertype0 ,\t\t\\ caddr len -- ; display string\n ' sercr0 ,\t\t\\ -- ; display new line\n\n\\ UART2\n: seremit2 #2 (seremit) ;\n: sertype2\t#2 (sertype) ;\n: sercr2\t#2 (sercr) ;\n: serkey?2\t#2 (serkey?) ;\n: serkey2\t#2 (serkey) ;\ncreate Console2 ' serkey2 , ' serkey?2 , ' seremit2 , ' sertype2 , ' sercr2 ,\t\n\n\\ Versions for use with the TCP Port (10)\n: seremit10 #10 (seremit) ;\n: sertype10\t#10 (sertype) ;\n: sercr10\t#10 (sercr) ;\n: serkey?10\t#10 (serkey?) ;\n: serkey10\t#10 (serkey) ;\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\n\nconsole-port 0 = [if]\n console0 constant console\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\n\\ ** It may be changed by one of the phrases of the form:\n\\ *C dup opvec ! ipvec !\n\\ *C SetConsole\n[then]\n\nconsole-port #1 = [if]\n console1 constant console\n[then]\n\nconsole-port #10 = [if]\n console10 constant console\n[then]\n\n\\ ************************\n\\ *S System initialisation\n\\ ************************\n\n\\ This is a NOP in the SAPI environment\n: init-ser ;\t\\ --\n\\ *G Initialise all serial ports\n\n\n\\ ======\n\\ *> ###\n\\ ======\n\ndecimal\n","old_contents":"\\ serCM3_sapi_p.fth - SAPI polled RX, polled TX, serial communication drivers\n\\ Written to run against the SockPuppet API.\n\n((\nAdapted from: the LPC polled driver.\n))\n\nonly forth definitions\nvariable cnt.pause \n\n\\ ==============\n\\ *! serCM3_sapi_p\n\\ *T SAPI polled serial driver\n\\ ==============\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\n\\ ** using the internal UARTs via the SAPI call layer.\n\n\n\\ ****************\n\\ *S Configuration\n\\ ****************\n\\ *P Configuration is managed by the SAPI\n\n\\ ********\n\\ *S Tools\n\\ ********\n\ntarget\n\n\\ ********************\n\\ *S Serial primitives\n\\ ********************\ninternal\n\n: +FaultConsole\t( -- ) ;\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\n\\ ** for more details.\n\ntarget\n\nCODE (seremitfc)\t\\ char base --\n\\ *G Service call for a single char - just fill in the registers\n\\ from the stack and make the call, and get back the flow control feedback\n\\ Put TOS into r0, pull r1 off the stack, and refresh the stack.\n\tmov r0, tos\n\tldr r1, [ psp ], # 4\t\n\tsvc # SAPI_VEC_PUTCHAR\t\n\tmov tos, r0\n next,\nEND-CODE\n\n: (seremit)\t\\ char base -- \n\\ *G Wrapped call that checks for throttling, and if so,\n\\ calls PAUSE to let another task run. Count these events for debugging purposes.\n\t(seremitfc)\n\t0<> IF 1 cnt.pause +! #5 ms THEN\n\t;\n\n: (sertype)\t\\ caddr len base --\n\\ *G Transmit a string on the given UART.\n -rot bounds\n ?do i c@ over (seremit) loop\n drop\n;\n\n: (sercr)\t\\ base --\n\\ *G Transmit a CR\/LF pair on the given UART.\n $0D over (seremit) $0A swap (seremit)\n;\n\nCODE (sergetchar) \\ base -- c\n\\ *G Get a character from the port\n\tmov r0, tos\t\n\tsvc # SAPI_VEC_GETCHAR\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE (serkey?) \\ base -- t\/f\n\\ *G Return true if the given UART has a character avilable to read.\n\\ The call returns 0 or 1. \n\tmov r0, tos\n\tsvc # SAPI_VEC_CHARSAVAIL\t\t\n\tmov tos, r0\n\tnext,\t\nEND-CODE\n\n: (serkey-basic)\n\tbegin pause \n\tdup (serkey?) until \n\t(sergetchar)\n;\n\n: (serkey-sleep?)\n\tself tcb.bbstatus @ over 1 setiocallback drop ( base )\n\tself halt \n\tdup (serkey?) IF self restart ELSE PAUSE THEN \\ We are now armed and ready to block\n (serkey?) \n;\n\n\\ *G Wait for a character to come available on the given UART and\n\\ ** return the character.\n\\ Advanced usage - Register a callback. \n\\ The tricky part is not screwing things up by missing a character\n\\ in the window between when you register, and when you pick up your\n\\ character. The way to do that is by registering, then self \n\\ halting, and then checking for a new character. That ensures that\n\\ if a character has slipped in, you will catch it.\n: (serkey)\t\\ base -- char\n\tbegin dup (serkey-sleep?) until (sergetchar)\n;\n\nexternal \n\n: seremit0\t\\ char --\n\\ *G Transmit a character on UART0.\n 0 (seremit) ;\n: sertype0\t\\ c-addr len --\n\\ *G Transmit a string on UART0.\n 0 (sertype) ;\n: sercr0\t\\ --\n\\ *G Issue a CR\/LF pair to UART0.\n 0 (sercr) ;\n: serkey?0\t\\ -- flag\n\\ *G Return true if UART0 has a character available.\n 0 (serkey?) ;\n: serkey0\t\\ -- char\n\\ *G Wait for a character on UART0.\n 0 (serkey) ;\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\n\\ *G Generic I\/O device for UART0.\n ' serkey0 ,\t\t\\ -- char ; receive char\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\n ' seremit0 ,\t\t\\ -- char ; display char\n ' sertype0 ,\t\t\\ caddr len -- ; display string\n ' sercr0 ,\t\t\\ -- ; display new line\n\n\\ UART2\n: seremit2 #2 (seremit) ;\n: sertype2\t#2 (sertype) ;\n: sercr2\t#2 (sercr) ;\n: serkey?2\t#2 (serkey?) ;\n: serkey2\t#2 (serkey) ;\ncreate Console2 ' serkey2 , ' serkey?2 , ' seremit2 , ' sertype2 , ' sercr2 ,\t\n\n\\ Versions for use with the TCP Port (10)\n: seremit10 #10 (seremit) ;\n: sertype10\t#10 (sertype) ;\n: sercr10\t#10 (sercr) ;\n: serkey?10\t#10 (serkey?) ;\n: serkey10\t#10 (serkey) ;\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\n\nconsole-port 0 = [if]\n console0 constant console\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\n\\ ** It may be changed by one of the phrases of the form:\n\\ *C dup opvec ! ipvec !\n\\ *C SetConsole\n[then]\n\nconsole-port #1 = [if]\n console1 constant console\n[then]\n\nconsole-port #10 = [if]\n console10 constant console\n[then]\n\n\\ ************************\n\\ *S System initialisation\n\\ ************************\n\n\\ This is a NOP in the SAPI environment\n: init-ser ;\t\\ --\n\\ *G Initialise all serial ports\n\n\n\\ ======\n\\ *> ###\n\\ ======\n\ndecimal\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"8c24ec865f9f8534bf7f9edcb41dc459186ae958","subject":"Missing semicolon","message":"Missing semicolon\n","repos":"rm-hull\/byok,rm-hull\/byok,rm-hull\/byok,rm-hull\/byok","old_file":"forth\/src\/forth\/system.fth","new_file":"forth\/src\/forth\/system.fth","new_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\ \n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n \n: COUNT dup 1+ swap c@ ;\n\n\\ Miscellaneous support words\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: CELL+ ( n -- n+cell ) cell + ;\n: CELL- ( n -- n-cell ) cell - ;\n: CELL* ( n -- n*cell ) cells ;\n\n: CHAR+ ( n -- n+size_of_char ) 1+ ;\n\\ : CHARS ( n -- n*size_of_char, don't do anything ) ; immediate\n\n\\ useful stack manipulation words\n: -ROT ( a b c -- c a b ) rot rot ;\n: 3DUP ( a b c -- a b c a b c ) 2 pick 2 pick 2 pick ;\n\n\\ ------------------------------------------------------------------\n: ID. ( nfa -- ) count 31 and type ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: PAD ( -- addr ) here 128 + ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: ? ( -- ) @ . ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ ' (lit) , cell 1- , ] +\n [ ' (lit) , cell 1- invert , ] and ;\n\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n: ALLOT ( nbytes -- , allot space in dictionary ) dp +! align ;\n\n: C, ( c -- ) here c! 1 dp +! ;\n\\ : W, ( w -- ) dp @ even-up dup dp ! w! 2 dp +! ;\n\\ : , ( n -- , lay into dictionary ) align here ! cell allot ;\n\n: SEE ( -- )\n ' dup\n 16 + @ \\ offset in execution token for alloc size\n cells swap >body swap\n disassemble ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token )\n [compile] literal ( compile a call to literal )\n ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n: :NONAME ( -- xt , begin compilation of headerless secondary ) align here ] ;\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick ) \n ?comp ' [compile] literal \n; immediate\n\n: RECURSE ( ? -- ? , call the word currently being defined ) \n latest compile, \n; immediate\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 ) swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 ) dup cell+ @ swap @ ;\n\n: \/STRING ( addr len n -- addr' len' ) over min rot over + -rot - ;\n: PLACE ( addr len to -- , move string ) 3dup 1+ swap cmove c! drop ;\n\n: ASCII ( -- char, state smart )\n bl parse drop c@\n state @ 1 =\n IF [compile] literal\n ELSE \n THEN \n; immediate\n\n: CHAR ( -- char , interpret mode ) bl parse drop c@ ;\n: [CHAR] ( -- char , for compile mode )\n char [compile] literal \n; immediate\n\n: 'word ( -- addr ) here ;\n\n: (C\") ( -- $addr ) r> dup count + aligned >r ;\n: (S\") ( -- c-addr cnt ) r> count 2dup + aligned >r ;\n: (.\") ( -- , type following string ) r> count 2dup + aligned >r type ;\n: \", ( addr len -- , place string into dict ) tuck 'word place 1+ allot align ;\n: ,\" ( -- ) 34 parse \", ;\n\n: .( ( --, type string delimited by parens )\n 41 parse type\n; immediate\n\n: .\" ( -- , type string )\n state @ 1 =\n IF compile (.\") ,\"\n ELSE 34 parse type\n THEN \n; immediate\n\n: CLEARSTACK ( i*x -- )\n BEGIN depth\n WHILE drop\n REPEAT ;\n\nvariable pictured_output \\ hidden?\nvariable pictured_output_len \\ hidden?\n\n: <# ( -- ) pad pictured_output ! 0 pictured_output_len ! ;\n: #> ( -- addr n ) drop pictured_output @ pictured_output_len @ ;\n\n: HOLD ( c -- )\n pictured_output @ dup dup 1+ pictured_output_len @ cmove c!\n 1 pictured_output_len +!\n;\n\n: DIGIT ( n -- ascii )\n dup 10 < IF 48 ELSE 87 THEN + ;\n\n: SIGN ( n -- ) < 0 IF 45 hold THEN\n;\n: # ( n -- n )\n base @ \/mod swap digit hold ;\n\n: #S ( n -- )\n BEGIN base @ \/mod dup \n WHILE swap digit hold \n REPEAT \n digit hold ;\n\n","old_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\ \n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n \n: COUNT dup 1+ swap c@ ;\n\n\\ Miscellaneous support words\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: CELL+ ( n -- n+cell ) cell + ;\n: CELL- ( n -- n-cell ) cell - ;\n: CELL* ( n -- n*cell ) cells ;\n\n: CHAR+ ( n -- n+size_of_char ) 1+\n\\ : CHARS ( n -- n*size_of_char, don't do anything ) ; immediate\n\n\\ useful stack manipulation words\n: -ROT ( a b c -- c a b ) rot rot ;\n: 3DUP ( a b c -- a b c a b c ) 2 pick 2 pick 2 pick ;\n\n\\ ------------------------------------------------------------------\n: ID. ( nfa -- ) count 31 and type ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: PAD ( -- addr ) here 128 + ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: ? ( -- ) @ . ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ ' (lit) , cell 1- , ] +\n [ ' (lit) , cell 1- invert , ] and ;\n\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n: ALLOT ( nbytes -- , allot space in dictionary ) dp +! align ;\n\n: C, ( c -- ) here c! 1 dp +! ;\n\\ : W, ( w -- ) dp @ even-up dup dp ! w! 2 dp +! ;\n\\ : , ( n -- , lay into dictionary ) align here ! cell allot ;\n\n: SEE ( -- )\n ' dup\n 16 + @ \\ offset in execution token for alloc size\n cells swap >body swap\n disassemble ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token )\n [compile] literal ( compile a call to literal )\n ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n: :NONAME ( -- xt , begin compilation of headerless secondary ) align here ] ;\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick ) \n ?comp ' [compile] literal \n; immediate\n\n: RECURSE ( ? -- ? , call the word currently being defined ) \n latest compile, \n; immediate\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 ) swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 ) dup cell+ @ swap @ ;\n\n: \/STRING ( addr len n -- addr' len' ) over min rot over + -rot - ;\n: PLACE ( addr len to -- , move string ) 3dup 1+ swap cmove c! drop ;\n\n: ASCII ( -- char, state smart )\n bl parse drop c@\n state @ 1 =\n IF [compile] literal\n ELSE \n THEN \n; immediate\n\n: CHAR ( -- char , interpret mode ) bl parse drop c@ ;\n: [CHAR] ( -- char , for compile mode )\n char [compile] literal \n; immediate\n\n: 'word ( -- addr ) here ;\n\n: (C\") ( -- $addr ) r> dup count + aligned >r ;\n: (S\") ( -- c-addr cnt ) r> count 2dup + aligned >r ;\n: (.\") ( -- , type following string ) r> count 2dup + aligned >r type ;\n: \", ( addr len -- , place string into dict ) tuck 'word place 1+ allot align ;\n: ,\" ( -- ) 34 parse \", ;\n\n: .( ( --, type string delimited by parens )\n 41 parse type\n; immediate\n\n: .\" ( -- , type string )\n state @ 1 =\n IF compile (.\") ,\"\n ELSE 34 parse type\n THEN \n; immediate\n\n: CLEARSTACK ( i*x -- )\n BEGIN depth\n WHILE drop\n REPEAT ;\n\nvariable pictured_output \\ hidden?\nvariable pictured_output_len \\ hidden?\n\n: <# ( -- ) pad pictured_output ! 0 pictured_output_len ! ;\n: #> ( -- addr n ) drop pictured_output @ pictured_output_len @ ;\n\n: HOLD ( c -- )\n pictured_output @ dup dup 1+ pictured_output_len @ cmove c!\n 1 pictured_output_len +!\n;\n\n: DIGIT ( n -- ascii )\n dup 10 < IF 48 ELSE 87 THEN + ;\n\n: SIGN ( n -- ) < 0 IF 45 hold THEN\n;\n: # ( n -- n )\n base @ \/mod swap digit hold ;\n\n: #S ( n -- )\n BEGIN base @ \/mod dup \n WHILE swap digit hold \n REPEAT \n digit hold ;\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"49db11af3d580477f3e33a0ba73e78347c4e641d","subject":"Make the \"Options:\" separator-text configurable by setting $menu_optionstext.","message":"Make the \"Options:\" separator-text configurable by setting $menu_optionstext.\n\nReviewed by:\teadler, adrian (co-mentor)\nApproved by:\tadrian (co-mentor)\nMFC after:\t3 days\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/menu.4th","new_file":"sys\/boot\/forth\/menu.4th","new_contents":"\\ Copyright (c) 2003 Scott Long \n\\ Copyright (c) 2003 Aleksander Fafula \n\\ Copyright (c) 2006-2012 Devin Teske \n\\ All rights reserved.\n\\ \n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\ \n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\ \n\\ $FreeBSD$\n\nmarker task-menu.4th\n\n\\ Frame drawing\ninclude \/boot\/frames.4th\n\nf_double \\ Set frames to double (see frames.4th). Replace with\n \\ f_single if you want single frames.\n46 constant dot \\ ASCII definition of a period (in decimal)\n\n 4 constant menu_timeout_default_x \\ default column position of timeout\n23 constant menu_timeout_default_y \\ default row position of timeout msg\n10 constant menu_timeout_default \\ default timeout (in seconds)\n\n\\ Customize the following values with care\n\n 1 constant menu_start \\ Numerical prefix of first menu item\ndot constant bullet \\ Menu bullet (appears after numerical prefix)\n 5 constant menu_x \\ Row position of the menu (from the top)\n 10 constant menu_y \\ Column position of the menu (from left side)\n\n\\ Menu Appearance\nvariable menuidx \\ Menu item stack for number prefixes\nvariable menurow \\ Menu item stack for positioning\nvariable menubllt \\ Menu item bullet\n\n\\ Menu Positioning\nvariable menuX \\ Menu X offset (columns)\nvariable menuY \\ Menu Y offset (rows)\n\n\\ Menu-item key association\/detection\nvariable menukey1\nvariable menukey2\nvariable menukey3\nvariable menukey4\nvariable menukey5\nvariable menukey6\nvariable menukey7\nvariable menukey8\nvariable menureboot\nvariable menurebootadded\nvariable menuacpi\nvariable menuoptions\n\n\\ Menu timer [count-down] variables\nvariable menu_timeout_enabled \\ timeout state (internal use only)\nvariable menu_time \\ variable for tracking the passage of time\nvariable menu_timeout \\ determined configurable delay duration\nvariable menu_timeout_x \\ column position of timeout message\nvariable menu_timeout_y \\ row position of timeout message\n\n\\ Boolean option status variables\nvariable toggle_state1\nvariable toggle_state2\nvariable toggle_state3\nvariable toggle_state4\nvariable toggle_state5\nvariable toggle_state6\nvariable toggle_state7\nvariable toggle_state8\n\n\\ Array option status variables\nvariable cycle_state1\nvariable cycle_state2\nvariable cycle_state3\nvariable cycle_state4\nvariable cycle_state5\nvariable cycle_state6\nvariable cycle_state7\nvariable cycle_state8\n\n\\ Containers for storing the initial caption text\ncreate init_text1 255 allot\ncreate init_text2 255 allot\ncreate init_text3 255 allot\ncreate init_text4 255 allot\ncreate init_text5 255 allot\ncreate init_text6 255 allot\ncreate init_text7 255 allot\ncreate init_text8 255 allot\n\n: arch-i386? ( -- BOOL ) \\ Returns TRUE (-1) on i386, FALSE (0) otherwise.\n\ts\" arch-i386\" environment? dup if\n\t\tdrop\n\tthen\n;\n\n\\ This function prints a menu item at menuX (row) and menuY (column), returns\n\\ the incremental decimal ASCII value associated with the menu item, and\n\\ increments the cursor position to the next row for the creation of the next\n\\ menu item. This function is called by the menu-create function. You need not\n\\ call it directly.\n\\ \n: printmenuitem ( menu_item_str -- ascii_keycode )\n\n\tmenurow dup @ 1+ swap ! ( increment menurow )\n\tmenuidx dup @ 1+ swap ! ( increment menuidx )\n\n\t\\ Calculate the menuitem row position\n\tmenurow @ menuY @ +\n\n\t\\ Position the cursor at the menuitem position\n\tdup menuX @ swap at-xy\n\n\t\\ Print the value of menuidx\n\tloader_color? if\n\t\t.\" \u001b[1m\" ( \u001b[22m )\n\tthen\n\tmenuidx @ .\n\tloader_color? if\n\t\t.\" \u001b[37m\" ( \u001b[39m )\n\tthen\n\n\t\\ Move the cursor forward 1 column\n\tdup menuX @ 1+ swap at-xy\n\n\tmenubllt @ emit\t\\ Print the menu bullet using the emit function\n\n\t\\ Move the cursor to the 3rd column from the current position\n\t\\ to allow for a space between the numerical prefix and the\n\t\\ text caption\n\tmenuX @ 3 + swap at-xy\n\n\t\\ Print the menu caption (we expect a string to be on the stack\n\t\\ prior to invoking this function)\n\ttype\n\n\t\\ Here we will add the ASCII decimal of the numerical prefix\n\t\\ to the stack (decimal ASCII for `1' is 49) as a \"return value\"\n\tmenuidx @ 48 +\n;\n\n: toggle_menuitem ( N -- N ) \\ toggles caption text and internal menuitem state\n\n\t\\ ASCII numeral equal to user-selected menu item must be on the stack.\n\t\\ We do not modify the stack, so the ASCII numeral is left on top.\n\n\ts\" init_textN\" \\ base name of buffer\n\t-rot 2dup 9 + c! rot \\ replace 'N' with ASCII num\n\n\tevaluate c@ 0= if\n\t\t\\ NOTE: no need to check toggle_stateN since the first time we\n\t\t\\ are called, we will populate init_textN. Further, we don't\n\t\t\\ need to test whether menu_caption[x] (ansi_caption[x] when\n\t\t\\ loader_color=1) is available since we would not have been\n\t\t\\ called if the caption was NULL.\n\n\t\t\\ base name of environment variable\n\t\tloader_color? if\n\t\t\ts\" ansi_caption[x]\"\n\t\telse\n\t\t\ts\" menu_caption[x]\"\n\t\tthen\t\n\t\t-rot 2dup 13 + c! rot \\ replace 'x' with ASCII numeral\n\n\t\tgetenv dup -1 <> if\n\n\t\t\ts\" init_textN\" \\ base name of buffer\n\t\t\t4 pick \\ copy ASCII num to top\n\t\t\trot tuck 9 + c! swap \\ replace 'N' with ASCII num\n\t\t\tevaluate\n\n\t\t\t\\ now we have the buffer c-addr on top\n\t\t\t\\ ( followed by c-addr\/u of current caption )\n\n\t\t\t\\ Copy the current caption into our buffer\n\t\t\t2dup c! -rot \\ store strlen at first byte\n\t\t\tbegin\n\t\t\t\trot 1+ \\ bring alt addr to top and increment\n\t\t\t\t-rot -rot \\ bring buffer addr to top\n\t\t\t\t2dup c@ swap c! \\ copy current character\n\t\t\t\t1+ \\ increment buffer addr\n\t\t\t\trot 1- \\ bring buffer len to top and decrement\n\t\t\t\tdup 0= \\ exit loop if buffer len is zero\n\t\t\tuntil\n\t\t\t2drop \\ buffer len\/addr\n\t\t\tdrop \\ alt addr\n\n\t\telse\n\t\t\tdrop\n\t\tthen\n\tthen\n\n\t\\ Now we are certain to have init_textN populated with the initial\n\t\\ value of menu_caption[x] (ansi_caption[x] with loader_color enabled).\n\t\\ We can now use init_textN as the untoggled caption and\n\t\\ toggled_text[x] (toggled_ansi[x] with loader_color enabled) as the\n\t\\ toggled caption and store the appropriate value into menu_caption[x]\n\t\\ (again, ansi_caption[x] with loader_color enabled). Last, we'll\n\t\\ negate the toggled state so that we reverse the flow on subsequent\n\t\\ calls.\n\n\ts\" toggle_stateN @\" \\ base name of toggle state var\n\t-rot 2dup 12 + c! rot \\ replace 'N' with ASCII numeral\n\n\tevaluate 0= if\n\t\t\\ state is OFF, toggle to ON\n\n\t\t\\ base name of toggled text var\n\t\tloader_color? if\n\t\t\ts\" toggled_ansi[x]\"\n\t\telse\n\t\t\ts\" toggled_text[x]\"\n\t\tthen\n\t\t-rot 2dup 13 + c! rot \\ replace 'x' with ASCII num\n\n\t\tgetenv dup -1 <> if\n\t\t\t\\ Assign toggled text to menu caption\n\n\t\t\t\\ base name of caption var\n\t\t\tloader_color? if\n\t\t\t\ts\" ansi_caption[x]\"\n\t\t\telse\n\t\t\t\ts\" menu_caption[x]\"\n\t\t\tthen\n\t\t\t4 pick \\ copy ASCII num to top\n\t\t\trot tuck 13 + c! swap \\ replace 'x' with ASCII num\n\n\t\t\tsetenv \\ set new caption\n\t\telse\n\t\t\t\\ No toggled text, keep the same caption\n\n\t\t\tdrop\n\t\tthen\n\n\t\ttrue \\ new value of toggle state var (to be stored later)\n\telse\n\t\t\\ state is ON, toggle to OFF\n\n\t\ts\" init_textN\" \\ base name of initial text buffer\n\t\t-rot 2dup 9 + c! rot \\ replace 'N' with ASCII numeral\n\t\tevaluate \\ convert string to c-addr\n\t\tcount \\ convert c-addr to c-addr\/u\n\n\t\t\\ base name of caption var\n\t\tloader_color? if\n\t\t\ts\" ansi_caption[x]\"\n\t\telse\n\t\t\ts\" menu_caption[x]\"\n\t\tthen\n\t\t4 pick \\ copy ASCII num to top\n\t\trot tuck 13 + c! swap \\ replace 'x' with ASCII numeral\n\n\t\tsetenv \\ set new caption\n\t\tfalse \\ new value of toggle state var (to be stored below)\n\tthen\n\n\t\\ now we'll store the new toggle state (on top of stack)\n\ts\" toggle_stateN\" \\ base name of toggle state var\n\t3 pick \\ copy ASCII numeral to top\n\trot tuck 12 + c! swap \\ replace 'N' with ASCII numeral\n\tevaluate \\ convert string to addr\n\t! \\ store new value\n;\n\n: cycle_menuitem ( N -- N ) \\ cycles through array of choices for a menuitem\n\n\t\\ ASCII numeral equal to user-selected menu item must be on the stack.\n\t\\ We do not modify the stack, so the ASCII numeral is left on top.\n\n\ts\" cycle_stateN\" \\ base name of array state var\n\t-rot 2dup 11 + c! rot \\ replace 'N' with ASCII numeral\n\n\tevaluate \\ we now have a pointer to the proper variable\n\tdup @ \\ resolve the pointer (but leave it on the stack)\n\t1+ \\ increment the value\n\n\t\\ Before assigning the (incremented) value back to the pointer,\n\t\\ let's test for the existence of this particular array element.\n\t\\ If the element exists, we'll store index value and move on.\n\t\\ Otherwise, we'll loop around to zero and store that.\n\n\tdup 48 + \\ duplicate Array index and convert to ASCII numeral\n\n\t\\ base name of array caption text\n\tloader_color? if\n\t\ts\" ansi_caption[x][y]\" \n\telse\n\t\ts\" menu_caption[x][y]\" \n\tthen\n\t-rot tuck 16 + c! swap \\ replace 'y' with Array index\n\t4 pick rot tuck 13 + c! swap \\ replace 'x' with menu choice\n\n\t\\ Now test for the existence of our incremented array index in the\n\t\\ form of $menu_caption[x][y] ($ansi_caption[x][y] with loader_color\n\t\\ enabled) as set in loader.rc(5), et. al.\n\n\tgetenv dup -1 = if\n\t\t\\ No caption set for this array index. Loop back to zero.\n\n\t\tdrop ( getenv cruft )\n\t\tdrop ( incremented array index )\n\t\t0 ( new array index that will be stored later )\n\n\t\t\\ base name of caption var\n\t\tloader_color? if\n\t\t\ts\" ansi_caption[x][0]\"\n\t\telse\n\t\t\ts\" menu_caption[x][0]\"\n\t\tthen\n\t\t4 pick rot tuck 13 + c! swap \\ replace 'x' with menu choice\n\n\t\tgetenv dup -1 = if\n\t\t\t\\ This is highly unlikely to occur, but to make\n\t\t\t\\ sure that things move along smoothly, allocate\n\t\t\t\\ a temporary NULL string\n\n\t\t\ts\" \"\n\t\tthen\n\tthen\n\n\t\\ At this point, we should have the following on the stack (in order,\n\t\\ from bottom to top):\n\t\\ \n\t\\ N - Ascii numeral representing the menu choice (inherited)\n\t\\ Addr - address of our internal cycle_stateN variable\n\t\\ N - zero-based number we intend to store to the above\n\t\\ C-Addr - string value we intend to store to menu_caption[x]\n\t\\ (or ansi_caption[x] with loader_color enabled)\n\t\\ \n\t\\ Let's perform what we need to with the above.\n\n\t\\ base name of menuitem caption var\n\tloader_color? if\n\t\ts\" ansi_caption[x]\"\n\telse\n\t\ts\" menu_caption[x]\"\n\tthen\n\t6 pick rot tuck 13 + c! swap \\ replace 'x' with menu choice\n\tsetenv \\ set the new caption\n\n\tswap ! \\ update array state variable\n;\n\n: acpipresent? ( -- flag ) \\ Returns TRUE if ACPI is present, FALSE otherwise\n\ts\" hint.acpi.0.rsdp\" getenv\n\tdup -1 = if\n\t\tdrop false exit\n\tthen\n\t2drop\n\ttrue\n;\n\n: acpienabled? ( -- flag ) \\ Returns TRUE if ACPI is enabled, FALSE otherwise\n\ts\" hint.acpi.0.disabled\" getenv\n\tdup -1 <> if\n\t\ts\" 0\" compare 0<> if\n\t\t\tfalse exit\n\t\tthen\n\telse\n\t\tdrop\n\tthen\n\ttrue\n;\n\n\\ This function prints the appropriate menuitem basename to the stack if an\n\\ ACPI option is to be presented to the user, otherwise returns -1. Used\n\\ internally by menu-create, you need not (nor should you) call this directly.\n\\ \n: acpimenuitem ( -- C-Addr\/U | -1 )\n\n\tarch-i386? if\n\t\tacpipresent? if\n\t\t\tacpienabled? if\n\t\t\t\tloader_color? if\n\t\t\t\t\ts\" toggled_ansi[x]\"\n\t\t\t\telse\n\t\t\t\t\ts\" toggled_text[x]\"\n\t\t\t\tthen\n\t\t\telse\n\t\t\t\tloader_color? if\n\t\t\t\t\ts\" ansi_caption[x]\"\n\t\t\t\telse\n\t\t\t\t\ts\" menu_caption[x]\"\n\t\t\t\tthen\n\t\t\tthen\n\t\telse\n\t\t\tmenuidx dup @ 1+ swap ! ( increment menuidx )\n\t\t\t-1\n\t\tthen\n\telse\n\t\t-1\n\tthen\n;\n\n\\ This function creates the list of menu items. This function is called by the\n\\ menu-display function. You need not be call it directly.\n\\ \n: menu-create ( -- )\n\n\t\\ Print the frame caption at (x,y)\n\ts\" loader_menu_title\" getenv dup -1 = if\n\t\tdrop s\" Welcome to FreeBSD\"\n\tthen\n\t24 over 2 \/ - 9 at-xy type \n\n\t\\ Print our menu options with respective key\/variable associations.\n\t\\ `printmenuitem' ends by adding the decimal ASCII value for the\n\t\\ numerical prefix to the stack. We store the value left on the stack\n\t\\ to the key binding variable for later testing against a character\n\t\\ captured by the `getkey' function.\n\n\t\\ Note that any menu item beyond 9 will have a numerical prefix on the\n\t\\ screen consisting of the first digit (ie. 1 for the tenth menu item)\n\t\\ and the key required to activate that menu item will be the decimal\n\t\\ ASCII of 48 plus the menu item (ie. 58 for the tenth item, aka. `:')\n\t\\ which is misleading and not desirable.\n\t\\ \n\t\\ Thus, we do not allow more than 8 configurable items on the menu\n\t\\ (with \"Reboot\" as the optional ninth and highest numbered item).\n\n\t\\ \n\t\\ Initialize the ACPI option status.\n\t\\ \n\t0 menuacpi !\n\ts\" menu_acpi\" getenv -1 <> if\n\t\tc@ dup 48 > over 57 < and if ( '1' <= c1 <= '8' )\n\t\t\tmenuacpi !\n\t\t\tarch-i386? if acpipresent? if\n\t\t\t\t\\ \n\t\t\t\t\\ Set menu toggle state to active state\n\t\t\t\t\\ (required by generic toggle_menuitem)\n\t\t\t\t\\ \n\t\t\t\tmenuacpi @\n\t\t\t\ts\" acpienabled? toggle_stateN !\"\n\t\t\t\t-rot tuck 25 + c! swap\n\t\t\t\tevaluate\n\t\t\tthen then\n\t\telse\n\t\t\tdrop\n\t\tthen\n\tthen\n\n\t\\ \n\t\\ Initialize the menu_options visual separator.\n\t\\ \n\t0 menuoptions !\n\ts\" menu_options\" getenv -1 <> if\n\t\tc@ dup 48 > over 57 < and if ( '1' <= c1 <= '8' )\n\t\t\tmenuoptions !\n\t\telse\n\t\t\tdrop\n\t\tthen\n\tthen\n\n\t\\ Initialize \"Reboot\" menu state variable (prevents double-entry)\n\tfalse menurebootadded !\n\n\t49 \\ Iterator start (loop range 49 to 56; ASCII '1' to '8')\n\tbegin\n\t\t\\ If the \"Options:\" separator, print it.\n\t\tdup menuoptions @ = if\n\t\t\t\\ Optionally add a reboot option to the menu\n\t\t\ts\" menu_reboot\" getenv -1 <> if\n\t\t\t\tdrop\n\t\t\t\ts\" Reboot\" printmenuitem menureboot !\n\t\t\t\ttrue menurebootadded !\n\t\t\tthen\n\n\t\t\tmenuX @\n\t\t\tmenurow @ 2 + menurow !\n\t\t\tmenurow @ menuY @ +\n\t\t\tat-xy\n\t\t\ts\" menu_optionstext\" getenv dup -1 <> if\n\t\t\t\ttype\n\t\t\telse\n\t\t\t\tdrop .\" Options:\"\n\t\t\tthen\n\t\tthen\n\n\t\t\\ If this is the ACPI menu option, act accordingly.\n\t\tdup menuacpi @ = if\n\t\t\tacpimenuitem ( -- C-Addr\/U | -1 )\n\t\telse\n\t\t\tloader_color? if\n\t\t\t\ts\" ansi_caption[x]\"\n\t\t\telse\n\t\t\t\ts\" menu_caption[x]\"\n\t\t\tthen\n\t\tthen\n\n\t\t( C-Addr\/U | -1 )\n\t\tdup -1 <> if\n\t\t\t\\ replace 'x' with current iteration\n\t\t\t-rot 2dup 13 + c! rot\n \n\t\t\t\\ test for environment variable\n\t\t\tgetenv dup -1 <> if\n\t\t\t\tprintmenuitem ( C-Addr\/U -- N )\n \n\t\t\t\ts\" menukeyN !\" \\ generate cmd to store result\n\t\t\t\t-rot 2dup 7 + c! rot\n \n\t\t\t\tevaluate\n\t\t\telse\n\t\t\t\tdrop\n\t\t\tthen\n\t\telse\n\t\t\tdrop\n\n\t\t\ts\" menu_command[x]\"\n\t\t\t-rot 2dup 13 + c! rot ( replace 'x' )\n\t\t\tunsetenv\n\t\tthen\n\n\t\t1+ dup 56 > \\ add 1 to iterator, continue if less than 57\n\tuntil\n\tdrop \\ iterator\n\n\t\\ Optionally add a reboot option to the menu\n\tmenurebootadded @ true <> if\n\t\ts\" menu_reboot\" getenv -1 <> if\n\t\t\tdrop \\ no need for the value\n\t\t\ts\" Reboot\" \\ menu caption (required by printmenuitem)\n\n\t\t\tprintmenuitem\n\t\t\tmenureboot !\n\t\telse\n\t\t\t0 menureboot !\n\t\tthen\n\tthen\n;\n\n\\ Takes a single integer on the stack and updates the timeout display. The\n\\ integer must be between 0 and 9 (we will only update a single digit in the\n\\ source message).\n\\ \n: menu-timeout-update ( N -- )\n\n\tdup 9 > if ( N N 9 -- N )\n\t\tdrop ( N -- )\n\t\t9 ( maximum: -- N )\n\tthen\n\n\tdup 0 < if ( N N 0 -- N )\n\t\tdrop ( N -- )\n\t\t0 ( minimum: -- N )\n\tthen\n\n\t48 + ( convert single-digit numeral to ASCII: N 48 -- N )\n\n\ts\" Autoboot in N seconds. [Space] to pause\" ( N -- N Addr C )\n\n\t2 pick 48 - 0> if ( N Addr C N 48 -- N Addr C )\n\n\t\t\\ Modify 'N' (Addr+12) above to reflect time-left\n\n\t\t-rot\t( N Addr C -- C N Addr )\n\t\ttuck\t( C N Addr -- C Addr N Addr )\n\t\t12 +\t( C Addr N Addr -- C Addr N Addr2 )\n\t\tc!\t( C Addr N Addr2 -- C Addr )\n\t\tswap\t( C Addr -- Addr C )\n\n\t\tmenu_timeout_x @\n\t\tmenu_timeout_y @\n\t\tat-xy ( position cursor: Addr C N N -- Addr C )\n\n\t\ttype ( print message: Addr C -- )\n\n\telse ( N Addr C N -- N Addr C )\n\n\t\tmenu_timeout_x @\n\t\tmenu_timeout_y @\n\t\tat-xy ( position cursor: N Addr C N N -- N Addr C )\n\n\t\tspaces ( erase message: N Addr C -- N Addr )\n\t\t2drop ( N Addr -- )\n\n\tthen\n\n\t0 25 at-xy ( position cursor back at bottom-left )\n;\n\n\\ This function blocks program flow (loops forever) until a key is pressed.\n\\ The key that was pressed is added to the top of the stack in the form of its\n\\ decimal ASCII representation. This function is called by the menu-display\n\\ function. You need not call it directly.\n\\ \n: getkey ( -- ascii_keycode )\n\n\tbegin \\ loop forever\n\n\t\tmenu_timeout_enabled @ 1 = if\n\t\t\t( -- )\n\t\t\tseconds ( get current time: -- N )\n\t\t\tdup menu_time @ <> if ( has time elapsed?: N N N -- N )\n\n\t\t\t\t\\ At least 1 second has elapsed since last loop\n\t\t\t\t\\ so we will decrement our \"timeout\" (really a\n\t\t\t\t\\ counter, insuring that we do not proceed too\n\t\t\t\t\\ fast) and update our timeout display.\n\n\t\t\t\tmenu_time ! ( update time record: N -- )\n\t\t\t\tmenu_timeout @ ( \"time\" remaining: -- N )\n\t\t\t\tdup 0> if ( greater than 0?: N N 0 -- N )\n\t\t\t\t\t1- ( decrement counter: N -- N )\n\t\t\t\t\tdup menu_timeout !\n\t\t\t\t\t\t( re-assign: N N Addr -- N )\n\t\t\t\tthen\n\t\t\t\t( -- N )\n\n\t\t\t\tdup 0= swap 0< or if ( N <= 0?: N N -- )\n\t\t\t\t\t\\ halt the timer\n\t\t\t\t\t0 menu_timeout ! ( 0 Addr -- )\n\t\t\t\t\t0 menu_timeout_enabled ! ( 0 Addr -- )\n\t\t\t\tthen\n\n\t\t\t\t\\ update the timer display ( N -- )\n\t\t\t\tmenu_timeout @ menu-timeout-update\n\n\t\t\t\tmenu_timeout @ 0= if\n\t\t\t\t\t\\ We've reached the end of the timeout\n\t\t\t\t\t\\ (user did not cancel by pressing ANY\n\t\t\t\t\t\\ key)\n\n\t\t\t\t\ts\" menu_timeout_command\" getenv dup\n\t\t\t\t\t-1 = if\n\t\t\t\t\t\tdrop \\ clean-up\n\t\t\t\t\telse\n\t\t\t\t\t\tevaluate\n\t\t\t\t\tthen\n\t\t\t\tthen\n\n\t\t\telse ( -- N )\n\t\t\t\t\\ No [detectable] time has elapsed (in seconds)\n\t\t\t\tdrop ( N -- )\n\t\t\tthen\n\t\t\t( -- )\n\t\tthen\n\n\t\tkey? if \\ Was a key pressed? (see loader(8))\n\n\t\t\t\\ An actual key was pressed (if the timeout is running,\n\t\t\t\\ kill it regardless of which key was pressed)\n\t\t\tmenu_timeout @ 0<> if\n\t\t\t\t0 menu_timeout !\n\t\t\t\t0 menu_timeout_enabled !\n\n\t\t\t\t\\ clear screen of timeout message\n\t\t\t\t0 menu-timeout-update\n\t\t\tthen\n\n\t\t\t\\ get the key that was pressed and exit (if we\n\t\t\t\\ get a non-zero ASCII code)\n\t\t\tkey dup 0<> if\n\t\t\t\texit\n\t\t\telse\n\t\t\t\tdrop\n\t\t\tthen\n\t\tthen\n\t\t50 ms \\ sleep for 50 milliseconds (see loader(8))\n\n\tagain\n;\n\n: menu-erase ( -- ) \\ Erases menu and resets positioning variable to positon 1.\n\n\t\\ Clear the screen area associated with the interactive menu\n\tmenuX @ menuY @\n\t2dup at-xy 38 spaces 1+\t\t2dup at-xy 38 spaces 1+\n\t2dup at-xy 38 spaces 1+\t\t2dup at-xy 38 spaces 1+\n\t2dup at-xy 38 spaces 1+\t\t2dup at-xy 38 spaces 1+\n\t2dup at-xy 38 spaces 1+\t\t2dup at-xy 38 spaces 1+\n\t2dup at-xy 38 spaces 1+\t\t2dup at-xy 38 spaces 1+\n\t2dup at-xy 38 spaces 1+\t\t2dup at-xy 38 spaces\n\t2drop\n\n\t\\ Reset the starting index and position for the menu\n\tmenu_start 1- menuidx !\n\t0 menurow !\n;\n\n\\ Erase and redraw the menu. Useful if you change a caption and want to\n\\ update the menu to reflect the new value.\n\\ \n: menu-redraw ( -- )\n\tmenu-erase\n\tmenu-create\n;\n\n\\ This function initializes the menu. Call this from your `loader.rc' file\n\\ before calling any other menu-related functions.\n\\ \n: menu-init ( -- )\n\tmenu_start\n\t1- menuidx ! \\ Initialize the starting index for the menu\n\t0 menurow ! \\ Initialize the starting position for the menu\n\t42 13 2 9 box \\ Draw frame (w,h,x,y)\n\t0 25 at-xy \\ Move cursor to the bottom for output\n;\n\n\\ Main function. Call this from your `loader.rc' file.\n\\ \n: menu-display ( -- )\n\n\t0 menu_timeout_enabled ! \\ start with automatic timeout disabled\n\n\t\\ check indication that automatic execution after delay is requested\n\ts\" menu_timeout_command\" getenv -1 <> if ( Addr C -1 -- | Addr )\n\t\tdrop ( just testing existence right now: Addr -- )\n\n\t\t\\ initialize state variables\n\t\tseconds menu_time ! ( store the time we started )\n\t\t1 menu_timeout_enabled ! ( enable automatic timeout )\n\n\t\t\\ read custom time-duration (if set)\n\t\ts\" autoboot_delay\" getenv dup -1 = if\n\t\t\tdrop \\ no custom duration (remove dup'd bunk -1)\n\t\t\tmenu_timeout_default \\ use default setting\n\t\telse\n\t\t\t2dup ?number 0= if ( if not a number )\n\t\t\t\t\\ disable timeout if \"NO\", else use default\n\t\t\t\ts\" NO\" compare-insensitive 0= if\n\t\t\t\t\t0 menu_timeout_enabled !\n\t\t\t\t\t0 ( assigned to menu_timeout below )\n\t\t\t\telse\n\t\t\t\t\tmenu_timeout_default\n\t\t\t\tthen\n\t\t\telse\n\t\t\t\t-rot 2drop\n\n\t\t\t\t\\ boot immediately if less than zero\n\t\t\t\tdup 0< if\n\t\t\t\t\tdrop\n\t\t\t\t\tmenu-create\n\t\t\t\t\t0 25 at-xy\n\t\t\t\t\t0 boot\n\t\t\t\tthen\n\t\t\tthen\n\t\tthen\n\t\tmenu_timeout ! ( store value on stack from above )\n\n\t\tmenu_timeout_enabled @ 1 = if\n\t\t\t\\ read custom column position (if set)\n\t\t\ts\" loader_menu_timeout_x\" getenv dup -1 = if\n\t\t\t\tdrop \\ no custom column position\n\t\t\t\tmenu_timeout_default_x \\ use default setting\n\t\t\telse\n\t\t\t\t\\ make sure custom position is a number\n\t\t\t\t?number 0= if\n\t\t\t\t\tmenu_timeout_default_x \\ or use default\n\t\t\t\tthen\n\t\t\tthen\n\t\t\tmenu_timeout_x ! ( store value on stack from above )\n \n\t\t\t\\ read custom row position (if set)\n\t\t\ts\" loader_menu_timeout_y\" getenv dup -1 = if\n\t\t\t\tdrop \\ no custom row position\n\t\t\t\tmenu_timeout_default_y \\ use default setting\n\t\t\telse\n\t\t\t\t\\ make sure custom position is a number\n\t\t\t\t?number 0= if\n\t\t\t\t\tmenu_timeout_default_y \\ or use default\n\t\t\t\tthen\n\t\t\tthen\n\t\t\tmenu_timeout_y ! ( store value on stack from above )\n\t\tthen\n\tthen\n\n\tmenu-create\n\n\tbegin \\ Loop forever\n\n\t\t0 25 at-xy \\ Move cursor to the bottom for output\n\t\tgetkey \\ Block here, waiting for a key to be pressed\n\n\t\tdup -1 = if\n\t\t\tdrop exit \\ Caught abort (abnormal return)\n\t\tthen\n\n\t\t\\ Boot if the user pressed Enter\/Ctrl-M (13) or\n\t\t\\ Ctrl-Enter\/Ctrl-J (10)\n\t\tdup over 13 = swap 10 = or if\n\t\t\tdrop ( no longer needed )\n\t\t\ts\" boot\" evaluate\n\t\t\texit ( pedantic; never reached )\n\t\tthen\n\n\t\t\\ Evaluate the decimal ASCII value against known menu item\n\t\t\\ key associations and act accordingly\n\n\t\t49 \\ Iterator start (loop range 49 to 56; ASCII '1' to '8')\n\t\tbegin\n\t\t\ts\" menukeyN @\"\n\n\t\t\t\\ replace 'N' with current iteration\n\t\t\t-rot 2dup 7 + c! rot\n\n\t\t\tevaluate rot tuck = if\n\n\t\t\t\t\\ Adjust for missing ACPI menuitem on non-i386\n\t\t\t\tarch-i386? true <> menuacpi @ 0<> and if\n\t\t\t\t\tmenuacpi @ over 2dup < -rot = or\n\t\t\t\t\tover 58 < and if\n\t\t\t\t\t( key >= menuacpi && key < 58: N -- N )\n\t\t\t\t\t\t1+\n\t\t\t\t\tthen\n\t\t\t\tthen\n\n\t\t\t\t\\ base env name for the value (x is a number)\n\t\t\t\ts\" menu_command[x]\"\n\n\t\t\t\t\\ Copy ASCII number to string at offset 13\n\t\t\t\t-rot 2dup 13 + c! rot\n\n\t\t\t\t\\ Test for the environment variable\n\t\t\t\tgetenv dup -1 <> if\n\t\t\t\t\t\\ Execute the stored procedure\n\t\t\t\t\tevaluate\n\n\t\t\t\t\t\\ We expect there to be a non-zero\n\t\t\t\t\t\\ value left on the stack after\n\t\t\t\t\t\\ executing the stored procedure.\n\t\t\t\t\t\\ If so, continue to run, else exit.\n\n\t\t\t\t\t0= if\n\t\t\t\t\t\tdrop \\ key pressed\n\t\t\t\t\t\tdrop \\ loop iterator\n\t\t\t\t\t\texit\n\t\t\t\t\telse\n\t\t\t\t\t\tswap \\ need iterator on top\n\t\t\t\t\tthen\n\t\t\t\tthen\n\n\t\t\t\t\\ Re-adjust for missing ACPI menuitem\n\t\t\t\tarch-i386? true <> menuacpi @ 0<> and if\n\t\t\t\t\tswap\n\t\t\t\t\tmenuacpi @ 1+ over 2dup < -rot = or\n\t\t\t\t\tover 59 < and if\n\t\t\t\t\t\t1-\n\t\t\t\t\tthen\n\t\t\t\t\tswap\n\t\t\t\tthen\n\t\t\telse\n\t\t\t\tswap \\ need iterator on top\n\t\t\tthen\n\n\t\t\t\\ \n\t\t\t\\ Check for menu keycode shortcut(s)\n\t\t\t\\ \n\t\t\ts\" menu_keycode[x]\"\n\t\t\t-rot 2dup 13 + c! rot\n\t\t\tgetenv dup -1 = if\n\t\t\t\tdrop\n\t\t\telse\n\t\t\t\t?number 0<> if\n\t\t\t\t\trot tuck = if\n\t\t\t\t\t\tswap\n\t\t\t\t\t\ts\" menu_command[x]\"\n\t\t\t\t\t\t-rot 2dup 13 + c! rot\n\t\t\t\t\t\tgetenv dup -1 <> if\n\t\t\t\t\t\t\tevaluate\n\t\t\t\t\t\t\t0= if\n\t\t\t\t\t\t\t\t2drop\n\t\t\t\t\t\t\t\texit\n\t\t\t\t\t\t\tthen\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tdrop\n\t\t\t\t\t\tthen\n\t\t\t\t\telse\n\t\t\t\t\t\tswap\n\t\t\t\t\tthen\n\t\t\t\tthen\n\t\t\tthen\n\n\t\t\t1+ dup 56 > \\ increment iterator\n\t\t\t \\ continue if less than 57\n\t\tuntil\n\t\tdrop \\ loop iterator\n\n\t\tmenureboot @ = if 0 reboot then\n\n\tagain\t\\ Non-operational key was pressed; repeat\n;\n\n\\ This function unsets all the possible environment variables associated with\n\\ creating the interactive menu.\n\\ \n: menu-unset ( -- )\n\n\t49 \\ Iterator start (loop range 49 to 56; ASCII '1' to '8')\n\tbegin\n\t\t\\ Unset variables in-order of appearance in menu.4th(8)\n\n\t\ts\" menu_caption[x]\"\t\\ basename for caption variable\n\t\t-rot 2dup 13 + c! rot\t\\ replace 'x' with current iteration\n\t\tunsetenv\t\t\\ not erroneous to unset unknown var\n\n\t\ts\" menu_command[x]\"\t\\ command basename\n\t\t-rot 2dup 13 + c! rot\t\\ replace 'x'\n\t\tunsetenv\n\n\t\ts\" menu_keycode[x]\"\t\\ keycode basename\n\t\t-rot 2dup 13 + c! rot\t\\ replace 'x'\n\t\tunsetenv\n\n\t\ts\" ansi_caption[x]\"\t\\ ANSI caption basename\n\t\t-rot 2dup 13 + c! rot\t\\ replace 'x'\n\t\tunsetenv\n\n\t\ts\" toggled_text[x]\"\t\\ toggle_menuitem caption basename\n\t\t-rot 2dup 13 + c! rot\t\\ replace 'x'\n\t\tunsetenv\n\n\t\ts\" toggled_ansi[x]\"\t\\ toggle_menuitem ANSI caption basename\n\t\t-rot 2dup 13 + c! rot\t\\ replace 'x'\n\t\tunsetenv\n\n\t\ts\" menu_caption[x][y]\"\t\\ cycle_menuitem caption\n\t\t-rot 2dup 13 + c! rot\t\\ replace 'x'\n\t\t49 -rot\n\t\tbegin\n\t\t\t16 2over rot + c! \\ replace 'y'\n\t\t\t2dup unsetenv\n\n\t\t\trot 1+ dup 56 > 2swap rot\n\t\tuntil\n\t\t2drop drop\n\n\t\ts\" ansi_caption[x][y]\"\t\\ cycle_menuitem ANSI caption\n\t\t-rot 2dup 13 + c! rot\t\\ replace 'x'\n\t\t49 -rot\n\t\tbegin\n\t\t\t16 2over rot + c! \\ replace 'y'\n\t\t\t2dup unsetenv\n\n\t\t\trot 1+ dup 56 > 2swap rot\n\t\tuntil\n\t\t2drop drop\n\n\t\ts\" 0 menukeyN !\"\t\\ basename for key association var\n\t\t-rot 2dup 9 + c! rot\t\\ replace 'N' with current iteration\n\t\tevaluate\t\t\\ assign zero (0) to key assoc. var\n\n\t\t1+ dup 56 >\t\\ increment, continue if less than 57\n\tuntil\n\tdrop \\ iterator\n\n\t\\ unset the timeout command\n\ts\" menu_timeout_command\" unsetenv\n\n\t\\ clear the \"Reboot\" menu option flag\n\ts\" menu_reboot\" unsetenv\n\t0 menureboot !\n\n\t\\ clear the ACPI menu option flag\n\ts\" menu_acpi\" unsetenv\n\t0 menuacpi !\n\n\t\\ clear the \"Options\" menu separator flag\n\ts\" menu_options\" unsetenv\n\ts\" menu_optionstext\" unsetenv\n\t0 menuoptions !\n\n;\n\n\\ This function both unsets menu variables and visually erases the menu area\n\\ in-preparation for another menu.\n\\ \n: menu-clear ( -- )\n\tmenu-unset\n\tmenu-erase\n;\n\n\\ Assign configuration values\nbullet menubllt !\n10 menuY !\n5 menuX !\n\n\\ Initialize our boolean state variables\n0 toggle_state1 !\n0 toggle_state2 !\n0 toggle_state3 !\n0 toggle_state4 !\n0 toggle_state5 !\n0 toggle_state6 !\n0 toggle_state7 !\n0 toggle_state8 !\n\n\\ Initialize our array state variables\n0 cycle_state1 !\n0 cycle_state2 !\n0 cycle_state3 !\n0 cycle_state4 !\n0 cycle_state5 !\n0 cycle_state6 !\n0 cycle_state7 !\n0 cycle_state8 !\n\n\\ Initialize string containers\n0 init_text1 c!\n0 init_text2 c!\n0 init_text3 c!\n0 init_text4 c!\n0 init_text5 c!\n0 init_text6 c!\n0 init_text7 c!\n0 init_text8 c!\n","old_contents":"\\ Copyright (c) 2003 Scott Long \n\\ Copyright (c) 2003 Aleksander Fafula \n\\ Copyright (c) 2006-2012 Devin Teske \n\\ All rights reserved.\n\\ \n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\ \n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\ \n\\ $FreeBSD$\n\nmarker task-menu.4th\n\n\\ Frame drawing\ninclude \/boot\/frames.4th\n\nf_double \\ Set frames to double (see frames.4th). Replace with\n \\ f_single if you want single frames.\n46 constant dot \\ ASCII definition of a period (in decimal)\n\n 4 constant menu_timeout_default_x \\ default column position of timeout\n23 constant menu_timeout_default_y \\ default row position of timeout msg\n10 constant menu_timeout_default \\ default timeout (in seconds)\n\n\\ Customize the following values with care\n\n 1 constant menu_start \\ Numerical prefix of first menu item\ndot constant bullet \\ Menu bullet (appears after numerical prefix)\n 5 constant menu_x \\ Row position of the menu (from the top)\n 10 constant menu_y \\ Column position of the menu (from left side)\n\n\\ Menu Appearance\nvariable menuidx \\ Menu item stack for number prefixes\nvariable menurow \\ Menu item stack for positioning\nvariable menubllt \\ Menu item bullet\n\n\\ Menu Positioning\nvariable menuX \\ Menu X offset (columns)\nvariable menuY \\ Menu Y offset (rows)\n\n\\ Menu-item key association\/detection\nvariable menukey1\nvariable menukey2\nvariable menukey3\nvariable menukey4\nvariable menukey5\nvariable menukey6\nvariable menukey7\nvariable menukey8\nvariable menureboot\nvariable menurebootadded\nvariable menuacpi\nvariable menuoptions\n\n\\ Menu timer [count-down] variables\nvariable menu_timeout_enabled \\ timeout state (internal use only)\nvariable menu_time \\ variable for tracking the passage of time\nvariable menu_timeout \\ determined configurable delay duration\nvariable menu_timeout_x \\ column position of timeout message\nvariable menu_timeout_y \\ row position of timeout message\n\n\\ Boolean option status variables\nvariable toggle_state1\nvariable toggle_state2\nvariable toggle_state3\nvariable toggle_state4\nvariable toggle_state5\nvariable toggle_state6\nvariable toggle_state7\nvariable toggle_state8\n\n\\ Array option status variables\nvariable cycle_state1\nvariable cycle_state2\nvariable cycle_state3\nvariable cycle_state4\nvariable cycle_state5\nvariable cycle_state6\nvariable cycle_state7\nvariable cycle_state8\n\n\\ Containers for storing the initial caption text\ncreate init_text1 255 allot\ncreate init_text2 255 allot\ncreate init_text3 255 allot\ncreate init_text4 255 allot\ncreate init_text5 255 allot\ncreate init_text6 255 allot\ncreate init_text7 255 allot\ncreate init_text8 255 allot\n\n: arch-i386? ( -- BOOL ) \\ Returns TRUE (-1) on i386, FALSE (0) otherwise.\n\ts\" arch-i386\" environment? dup if\n\t\tdrop\n\tthen\n;\n\n\\ This function prints a menu item at menuX (row) and menuY (column), returns\n\\ the incremental decimal ASCII value associated with the menu item, and\n\\ increments the cursor position to the next row for the creation of the next\n\\ menu item. This function is called by the menu-create function. You need not\n\\ call it directly.\n\\ \n: printmenuitem ( menu_item_str -- ascii_keycode )\n\n\tmenurow dup @ 1+ swap ! ( increment menurow )\n\tmenuidx dup @ 1+ swap ! ( increment menuidx )\n\n\t\\ Calculate the menuitem row position\n\tmenurow @ menuY @ +\n\n\t\\ Position the cursor at the menuitem position\n\tdup menuX @ swap at-xy\n\n\t\\ Print the value of menuidx\n\tloader_color? if\n\t\t.\" \u001b[1m\" ( \u001b[22m )\n\tthen\n\tmenuidx @ .\n\tloader_color? if\n\t\t.\" \u001b[37m\" ( \u001b[39m )\n\tthen\n\n\t\\ Move the cursor forward 1 column\n\tdup menuX @ 1+ swap at-xy\n\n\tmenubllt @ emit\t\\ Print the menu bullet using the emit function\n\n\t\\ Move the cursor to the 3rd column from the current position\n\t\\ to allow for a space between the numerical prefix and the\n\t\\ text caption\n\tmenuX @ 3 + swap at-xy\n\n\t\\ Print the menu caption (we expect a string to be on the stack\n\t\\ prior to invoking this function)\n\ttype\n\n\t\\ Here we will add the ASCII decimal of the numerical prefix\n\t\\ to the stack (decimal ASCII for `1' is 49) as a \"return value\"\n\tmenuidx @ 48 +\n;\n\n: toggle_menuitem ( N -- N ) \\ toggles caption text and internal menuitem state\n\n\t\\ ASCII numeral equal to user-selected menu item must be on the stack.\n\t\\ We do not modify the stack, so the ASCII numeral is left on top.\n\n\ts\" init_textN\" \\ base name of buffer\n\t-rot 2dup 9 + c! rot \\ replace 'N' with ASCII num\n\n\tevaluate c@ 0= if\n\t\t\\ NOTE: no need to check toggle_stateN since the first time we\n\t\t\\ are called, we will populate init_textN. Further, we don't\n\t\t\\ need to test whether menu_caption[x] (ansi_caption[x] when\n\t\t\\ loader_color=1) is available since we would not have been\n\t\t\\ called if the caption was NULL.\n\n\t\t\\ base name of environment variable\n\t\tloader_color? if\n\t\t\ts\" ansi_caption[x]\"\n\t\telse\n\t\t\ts\" menu_caption[x]\"\n\t\tthen\t\n\t\t-rot 2dup 13 + c! rot \\ replace 'x' with ASCII numeral\n\n\t\tgetenv dup -1 <> if\n\n\t\t\ts\" init_textN\" \\ base name of buffer\n\t\t\t4 pick \\ copy ASCII num to top\n\t\t\trot tuck 9 + c! swap \\ replace 'N' with ASCII num\n\t\t\tevaluate\n\n\t\t\t\\ now we have the buffer c-addr on top\n\t\t\t\\ ( followed by c-addr\/u of current caption )\n\n\t\t\t\\ Copy the current caption into our buffer\n\t\t\t2dup c! -rot \\ store strlen at first byte\n\t\t\tbegin\n\t\t\t\trot 1+ \\ bring alt addr to top and increment\n\t\t\t\t-rot -rot \\ bring buffer addr to top\n\t\t\t\t2dup c@ swap c! \\ copy current character\n\t\t\t\t1+ \\ increment buffer addr\n\t\t\t\trot 1- \\ bring buffer len to top and decrement\n\t\t\t\tdup 0= \\ exit loop if buffer len is zero\n\t\t\tuntil\n\t\t\t2drop \\ buffer len\/addr\n\t\t\tdrop \\ alt addr\n\n\t\telse\n\t\t\tdrop\n\t\tthen\n\tthen\n\n\t\\ Now we are certain to have init_textN populated with the initial\n\t\\ value of menu_caption[x] (ansi_caption[x] with loader_color enabled).\n\t\\ We can now use init_textN as the untoggled caption and\n\t\\ toggled_text[x] (toggled_ansi[x] with loader_color enabled) as the\n\t\\ toggled caption and store the appropriate value into menu_caption[x]\n\t\\ (again, ansi_caption[x] with loader_color enabled). Last, we'll\n\t\\ negate the toggled state so that we reverse the flow on subsequent\n\t\\ calls.\n\n\ts\" toggle_stateN @\" \\ base name of toggle state var\n\t-rot 2dup 12 + c! rot \\ replace 'N' with ASCII numeral\n\n\tevaluate 0= if\n\t\t\\ state is OFF, toggle to ON\n\n\t\t\\ base name of toggled text var\n\t\tloader_color? if\n\t\t\ts\" toggled_ansi[x]\"\n\t\telse\n\t\t\ts\" toggled_text[x]\"\n\t\tthen\n\t\t-rot 2dup 13 + c! rot \\ replace 'x' with ASCII num\n\n\t\tgetenv dup -1 <> if\n\t\t\t\\ Assign toggled text to menu caption\n\n\t\t\t\\ base name of caption var\n\t\t\tloader_color? if\n\t\t\t\ts\" ansi_caption[x]\"\n\t\t\telse\n\t\t\t\ts\" menu_caption[x]\"\n\t\t\tthen\n\t\t\t4 pick \\ copy ASCII num to top\n\t\t\trot tuck 13 + c! swap \\ replace 'x' with ASCII num\n\n\t\t\tsetenv \\ set new caption\n\t\telse\n\t\t\t\\ No toggled text, keep the same caption\n\n\t\t\tdrop\n\t\tthen\n\n\t\ttrue \\ new value of toggle state var (to be stored later)\n\telse\n\t\t\\ state is ON, toggle to OFF\n\n\t\ts\" init_textN\" \\ base name of initial text buffer\n\t\t-rot 2dup 9 + c! rot \\ replace 'N' with ASCII numeral\n\t\tevaluate \\ convert string to c-addr\n\t\tcount \\ convert c-addr to c-addr\/u\n\n\t\t\\ base name of caption var\n\t\tloader_color? if\n\t\t\ts\" ansi_caption[x]\"\n\t\telse\n\t\t\ts\" menu_caption[x]\"\n\t\tthen\n\t\t4 pick \\ copy ASCII num to top\n\t\trot tuck 13 + c! swap \\ replace 'x' with ASCII numeral\n\n\t\tsetenv \\ set new caption\n\t\tfalse \\ new value of toggle state var (to be stored below)\n\tthen\n\n\t\\ now we'll store the new toggle state (on top of stack)\n\ts\" toggle_stateN\" \\ base name of toggle state var\n\t3 pick \\ copy ASCII numeral to top\n\trot tuck 12 + c! swap \\ replace 'N' with ASCII numeral\n\tevaluate \\ convert string to addr\n\t! \\ store new value\n;\n\n: cycle_menuitem ( N -- N ) \\ cycles through array of choices for a menuitem\n\n\t\\ ASCII numeral equal to user-selected menu item must be on the stack.\n\t\\ We do not modify the stack, so the ASCII numeral is left on top.\n\n\ts\" cycle_stateN\" \\ base name of array state var\n\t-rot 2dup 11 + c! rot \\ replace 'N' with ASCII numeral\n\n\tevaluate \\ we now have a pointer to the proper variable\n\tdup @ \\ resolve the pointer (but leave it on the stack)\n\t1+ \\ increment the value\n\n\t\\ Before assigning the (incremented) value back to the pointer,\n\t\\ let's test for the existence of this particular array element.\n\t\\ If the element exists, we'll store index value and move on.\n\t\\ Otherwise, we'll loop around to zero and store that.\n\n\tdup 48 + \\ duplicate Array index and convert to ASCII numeral\n\n\t\\ base name of array caption text\n\tloader_color? if\n\t\ts\" ansi_caption[x][y]\" \n\telse\n\t\ts\" menu_caption[x][y]\" \n\tthen\n\t-rot tuck 16 + c! swap \\ replace 'y' with Array index\n\t4 pick rot tuck 13 + c! swap \\ replace 'x' with menu choice\n\n\t\\ Now test for the existence of our incremented array index in the\n\t\\ form of $menu_caption[x][y] ($ansi_caption[x][y] with loader_color\n\t\\ enabled) as set in loader.rc(5), et. al.\n\n\tgetenv dup -1 = if\n\t\t\\ No caption set for this array index. Loop back to zero.\n\n\t\tdrop ( getenv cruft )\n\t\tdrop ( incremented array index )\n\t\t0 ( new array index that will be stored later )\n\n\t\t\\ base name of caption var\n\t\tloader_color? if\n\t\t\ts\" ansi_caption[x][0]\"\n\t\telse\n\t\t\ts\" menu_caption[x][0]\"\n\t\tthen\n\t\t4 pick rot tuck 13 + c! swap \\ replace 'x' with menu choice\n\n\t\tgetenv dup -1 = if\n\t\t\t\\ This is highly unlikely to occur, but to make\n\t\t\t\\ sure that things move along smoothly, allocate\n\t\t\t\\ a temporary NULL string\n\n\t\t\ts\" \"\n\t\tthen\n\tthen\n\n\t\\ At this point, we should have the following on the stack (in order,\n\t\\ from bottom to top):\n\t\\ \n\t\\ N - Ascii numeral representing the menu choice (inherited)\n\t\\ Addr - address of our internal cycle_stateN variable\n\t\\ N - zero-based number we intend to store to the above\n\t\\ C-Addr - string value we intend to store to menu_caption[x]\n\t\\ (or ansi_caption[x] with loader_color enabled)\n\t\\ \n\t\\ Let's perform what we need to with the above.\n\n\t\\ base name of menuitem caption var\n\tloader_color? if\n\t\ts\" ansi_caption[x]\"\n\telse\n\t\ts\" menu_caption[x]\"\n\tthen\n\t6 pick rot tuck 13 + c! swap \\ replace 'x' with menu choice\n\tsetenv \\ set the new caption\n\n\tswap ! \\ update array state variable\n;\n\n: acpipresent? ( -- flag ) \\ Returns TRUE if ACPI is present, FALSE otherwise\n\ts\" hint.acpi.0.rsdp\" getenv\n\tdup -1 = if\n\t\tdrop false exit\n\tthen\n\t2drop\n\ttrue\n;\n\n: acpienabled? ( -- flag ) \\ Returns TRUE if ACPI is enabled, FALSE otherwise\n\ts\" hint.acpi.0.disabled\" getenv\n\tdup -1 <> if\n\t\ts\" 0\" compare 0<> if\n\t\t\tfalse exit\n\t\tthen\n\telse\n\t\tdrop\n\tthen\n\ttrue\n;\n\n\\ This function prints the appropriate menuitem basename to the stack if an\n\\ ACPI option is to be presented to the user, otherwise returns -1. Used\n\\ internally by menu-create, you need not (nor should you) call this directly.\n\\ \n: acpimenuitem ( -- C-Addr\/U | -1 )\n\n\tarch-i386? if\n\t\tacpipresent? if\n\t\t\tacpienabled? if\n\t\t\t\tloader_color? if\n\t\t\t\t\ts\" toggled_ansi[x]\"\n\t\t\t\telse\n\t\t\t\t\ts\" toggled_text[x]\"\n\t\t\t\tthen\n\t\t\telse\n\t\t\t\tloader_color? if\n\t\t\t\t\ts\" ansi_caption[x]\"\n\t\t\t\telse\n\t\t\t\t\ts\" menu_caption[x]\"\n\t\t\t\tthen\n\t\t\tthen\n\t\telse\n\t\t\tmenuidx dup @ 1+ swap ! ( increment menuidx )\n\t\t\t-1\n\t\tthen\n\telse\n\t\t-1\n\tthen\n;\n\n\\ This function creates the list of menu items. This function is called by the\n\\ menu-display function. You need not be call it directly.\n\\ \n: menu-create ( -- )\n\n\t\\ Print the frame caption at (x,y)\n\ts\" loader_menu_title\" getenv dup -1 = if\n\t\tdrop s\" Welcome to FreeBSD\"\n\tthen\n\t24 over 2 \/ - 9 at-xy type \n\n\t\\ Print our menu options with respective key\/variable associations.\n\t\\ `printmenuitem' ends by adding the decimal ASCII value for the\n\t\\ numerical prefix to the stack. We store the value left on the stack\n\t\\ to the key binding variable for later testing against a character\n\t\\ captured by the `getkey' function.\n\n\t\\ Note that any menu item beyond 9 will have a numerical prefix on the\n\t\\ screen consisting of the first digit (ie. 1 for the tenth menu item)\n\t\\ and the key required to activate that menu item will be the decimal\n\t\\ ASCII of 48 plus the menu item (ie. 58 for the tenth item, aka. `:')\n\t\\ which is misleading and not desirable.\n\t\\ \n\t\\ Thus, we do not allow more than 8 configurable items on the menu\n\t\\ (with \"Reboot\" as the optional ninth and highest numbered item).\n\n\t\\ \n\t\\ Initialize the ACPI option status.\n\t\\ \n\t0 menuacpi !\n\ts\" menu_acpi\" getenv -1 <> if\n\t\tc@ dup 48 > over 57 < and if ( '1' <= c1 <= '8' )\n\t\t\tmenuacpi !\n\t\t\tarch-i386? if acpipresent? if\n\t\t\t\t\\ \n\t\t\t\t\\ Set menu toggle state to active state\n\t\t\t\t\\ (required by generic toggle_menuitem)\n\t\t\t\t\\ \n\t\t\t\tmenuacpi @\n\t\t\t\ts\" acpienabled? toggle_stateN !\"\n\t\t\t\t-rot tuck 25 + c! swap\n\t\t\t\tevaluate\n\t\t\tthen then\n\t\telse\n\t\t\tdrop\n\t\tthen\n\tthen\n\n\t\\ \n\t\\ Initialize the menu_options visual separator.\n\t\\ \n\t0 menuoptions !\n\ts\" menu_options\" getenv -1 <> if\n\t\tc@ dup 48 > over 57 < and if ( '1' <= c1 <= '8' )\n\t\t\tmenuoptions !\n\t\telse\n\t\t\tdrop\n\t\tthen\n\tthen\n\n\t\\ Initialize \"Reboot\" menu state variable (prevents double-entry)\n\tfalse menurebootadded !\n\n\t49 \\ Iterator start (loop range 49 to 56; ASCII '1' to '8')\n\tbegin\n\t\t\\ If the \"Options:\" separator, print it.\n\t\tdup menuoptions @ = if\n\t\t\t\\ Optionally add a reboot option to the menu\n\t\t\ts\" menu_reboot\" getenv -1 <> if\n\t\t\t\tdrop\n\t\t\t\ts\" Reboot\" printmenuitem menureboot !\n\t\t\t\ttrue menurebootadded !\n\t\t\tthen\n\n\t\t\tmenuX @\n\t\t\tmenurow @ 2 + menurow !\n\t\t\tmenurow @ menuY @ +\n\t\t\tat-xy\n\t\t\t.\" Options:\"\n\t\tthen\n\n\t\t\\ If this is the ACPI menu option, act accordingly.\n\t\tdup menuacpi @ = if\n\t\t\tacpimenuitem ( -- C-Addr\/U | -1 )\n\t\telse\n\t\t\tloader_color? if\n\t\t\t\ts\" ansi_caption[x]\"\n\t\t\telse\n\t\t\t\ts\" menu_caption[x]\"\n\t\t\tthen\n\t\tthen\n\n\t\t( C-Addr\/U | -1 )\n\t\tdup -1 <> if\n\t\t\t\\ replace 'x' with current iteration\n\t\t\t-rot 2dup 13 + c! rot\n \n\t\t\t\\ test for environment variable\n\t\t\tgetenv dup -1 <> if\n\t\t\t\tprintmenuitem ( C-Addr\/U -- N )\n \n\t\t\t\ts\" menukeyN !\" \\ generate cmd to store result\n\t\t\t\t-rot 2dup 7 + c! rot\n \n\t\t\t\tevaluate\n\t\t\telse\n\t\t\t\tdrop\n\t\t\tthen\n\t\telse\n\t\t\tdrop\n\n\t\t\ts\" menu_command[x]\"\n\t\t\t-rot 2dup 13 + c! rot ( replace 'x' )\n\t\t\tunsetenv\n\t\tthen\n\n\t\t1+ dup 56 > \\ add 1 to iterator, continue if less than 57\n\tuntil\n\tdrop \\ iterator\n\n\t\\ Optionally add a reboot option to the menu\n\tmenurebootadded @ true <> if\n\t\ts\" menu_reboot\" getenv -1 <> if\n\t\t\tdrop \\ no need for the value\n\t\t\ts\" Reboot\" \\ menu caption (required by printmenuitem)\n\n\t\t\tprintmenuitem\n\t\t\tmenureboot !\n\t\telse\n\t\t\t0 menureboot !\n\t\tthen\n\tthen\n;\n\n\\ Takes a single integer on the stack and updates the timeout display. The\n\\ integer must be between 0 and 9 (we will only update a single digit in the\n\\ source message).\n\\ \n: menu-timeout-update ( N -- )\n\n\tdup 9 > if ( N N 9 -- N )\n\t\tdrop ( N -- )\n\t\t9 ( maximum: -- N )\n\tthen\n\n\tdup 0 < if ( N N 0 -- N )\n\t\tdrop ( N -- )\n\t\t0 ( minimum: -- N )\n\tthen\n\n\t48 + ( convert single-digit numeral to ASCII: N 48 -- N )\n\n\ts\" Autoboot in N seconds. [Space] to pause\" ( N -- N Addr C )\n\n\t2 pick 48 - 0> if ( N Addr C N 48 -- N Addr C )\n\n\t\t\\ Modify 'N' (Addr+12) above to reflect time-left\n\n\t\t-rot\t( N Addr C -- C N Addr )\n\t\ttuck\t( C N Addr -- C Addr N Addr )\n\t\t12 +\t( C Addr N Addr -- C Addr N Addr2 )\n\t\tc!\t( C Addr N Addr2 -- C Addr )\n\t\tswap\t( C Addr -- Addr C )\n\n\t\tmenu_timeout_x @\n\t\tmenu_timeout_y @\n\t\tat-xy ( position cursor: Addr C N N -- Addr C )\n\n\t\ttype ( print message: Addr C -- )\n\n\telse ( N Addr C N -- N Addr C )\n\n\t\tmenu_timeout_x @\n\t\tmenu_timeout_y @\n\t\tat-xy ( position cursor: N Addr C N N -- N Addr C )\n\n\t\tspaces ( erase message: N Addr C -- N Addr )\n\t\t2drop ( N Addr -- )\n\n\tthen\n\n\t0 25 at-xy ( position cursor back at bottom-left )\n;\n\n\\ This function blocks program flow (loops forever) until a key is pressed.\n\\ The key that was pressed is added to the top of the stack in the form of its\n\\ decimal ASCII representation. This function is called by the menu-display\n\\ function. You need not call it directly.\n\\ \n: getkey ( -- ascii_keycode )\n\n\tbegin \\ loop forever\n\n\t\tmenu_timeout_enabled @ 1 = if\n\t\t\t( -- )\n\t\t\tseconds ( get current time: -- N )\n\t\t\tdup menu_time @ <> if ( has time elapsed?: N N N -- N )\n\n\t\t\t\t\\ At least 1 second has elapsed since last loop\n\t\t\t\t\\ so we will decrement our \"timeout\" (really a\n\t\t\t\t\\ counter, insuring that we do not proceed too\n\t\t\t\t\\ fast) and update our timeout display.\n\n\t\t\t\tmenu_time ! ( update time record: N -- )\n\t\t\t\tmenu_timeout @ ( \"time\" remaining: -- N )\n\t\t\t\tdup 0> if ( greater than 0?: N N 0 -- N )\n\t\t\t\t\t1- ( decrement counter: N -- N )\n\t\t\t\t\tdup menu_timeout !\n\t\t\t\t\t\t( re-assign: N N Addr -- N )\n\t\t\t\tthen\n\t\t\t\t( -- N )\n\n\t\t\t\tdup 0= swap 0< or if ( N <= 0?: N N -- )\n\t\t\t\t\t\\ halt the timer\n\t\t\t\t\t0 menu_timeout ! ( 0 Addr -- )\n\t\t\t\t\t0 menu_timeout_enabled ! ( 0 Addr -- )\n\t\t\t\tthen\n\n\t\t\t\t\\ update the timer display ( N -- )\n\t\t\t\tmenu_timeout @ menu-timeout-update\n\n\t\t\t\tmenu_timeout @ 0= if\n\t\t\t\t\t\\ We've reached the end of the timeout\n\t\t\t\t\t\\ (user did not cancel by pressing ANY\n\t\t\t\t\t\\ key)\n\n\t\t\t\t\ts\" menu_timeout_command\" getenv dup\n\t\t\t\t\t-1 = if\n\t\t\t\t\t\tdrop \\ clean-up\n\t\t\t\t\telse\n\t\t\t\t\t\tevaluate\n\t\t\t\t\tthen\n\t\t\t\tthen\n\n\t\t\telse ( -- N )\n\t\t\t\t\\ No [detectable] time has elapsed (in seconds)\n\t\t\t\tdrop ( N -- )\n\t\t\tthen\n\t\t\t( -- )\n\t\tthen\n\n\t\tkey? if \\ Was a key pressed? (see loader(8))\n\n\t\t\t\\ An actual key was pressed (if the timeout is running,\n\t\t\t\\ kill it regardless of which key was pressed)\n\t\t\tmenu_timeout @ 0<> if\n\t\t\t\t0 menu_timeout !\n\t\t\t\t0 menu_timeout_enabled !\n\n\t\t\t\t\\ clear screen of timeout message\n\t\t\t\t0 menu-timeout-update\n\t\t\tthen\n\n\t\t\t\\ get the key that was pressed and exit (if we\n\t\t\t\\ get a non-zero ASCII code)\n\t\t\tkey dup 0<> if\n\t\t\t\texit\n\t\t\telse\n\t\t\t\tdrop\n\t\t\tthen\n\t\tthen\n\t\t50 ms \\ sleep for 50 milliseconds (see loader(8))\n\n\tagain\n;\n\n: menu-erase ( -- ) \\ Erases menu and resets positioning variable to positon 1.\n\n\t\\ Clear the screen area associated with the interactive menu\n\tmenuX @ menuY @\n\t2dup at-xy 38 spaces 1+\t\t2dup at-xy 38 spaces 1+\n\t2dup at-xy 38 spaces 1+\t\t2dup at-xy 38 spaces 1+\n\t2dup at-xy 38 spaces 1+\t\t2dup at-xy 38 spaces 1+\n\t2dup at-xy 38 spaces 1+\t\t2dup at-xy 38 spaces 1+\n\t2dup at-xy 38 spaces 1+\t\t2dup at-xy 38 spaces 1+\n\t2dup at-xy 38 spaces 1+\t\t2dup at-xy 38 spaces\n\t2drop\n\n\t\\ Reset the starting index and position for the menu\n\tmenu_start 1- menuidx !\n\t0 menurow !\n;\n\n\\ Erase and redraw the menu. Useful if you change a caption and want to\n\\ update the menu to reflect the new value.\n\\ \n: menu-redraw ( -- )\n\tmenu-erase\n\tmenu-create\n;\n\n\\ This function initializes the menu. Call this from your `loader.rc' file\n\\ before calling any other menu-related functions.\n\\ \n: menu-init ( -- )\n\tmenu_start\n\t1- menuidx ! \\ Initialize the starting index for the menu\n\t0 menurow ! \\ Initialize the starting position for the menu\n\t42 13 2 9 box \\ Draw frame (w,h,x,y)\n\t0 25 at-xy \\ Move cursor to the bottom for output\n;\n\n\\ Main function. Call this from your `loader.rc' file.\n\\ \n: menu-display ( -- )\n\n\t0 menu_timeout_enabled ! \\ start with automatic timeout disabled\n\n\t\\ check indication that automatic execution after delay is requested\n\ts\" menu_timeout_command\" getenv -1 <> if ( Addr C -1 -- | Addr )\n\t\tdrop ( just testing existence right now: Addr -- )\n\n\t\t\\ initialize state variables\n\t\tseconds menu_time ! ( store the time we started )\n\t\t1 menu_timeout_enabled ! ( enable automatic timeout )\n\n\t\t\\ read custom time-duration (if set)\n\t\ts\" autoboot_delay\" getenv dup -1 = if\n\t\t\tdrop \\ no custom duration (remove dup'd bunk -1)\n\t\t\tmenu_timeout_default \\ use default setting\n\t\telse\n\t\t\t2dup ?number 0= if ( if not a number )\n\t\t\t\t\\ disable timeout if \"NO\", else use default\n\t\t\t\ts\" NO\" compare-insensitive 0= if\n\t\t\t\t\t0 menu_timeout_enabled !\n\t\t\t\t\t0 ( assigned to menu_timeout below )\n\t\t\t\telse\n\t\t\t\t\tmenu_timeout_default\n\t\t\t\tthen\n\t\t\telse\n\t\t\t\t-rot 2drop\n\n\t\t\t\t\\ boot immediately if less than zero\n\t\t\t\tdup 0< if\n\t\t\t\t\tdrop\n\t\t\t\t\tmenu-create\n\t\t\t\t\t0 25 at-xy\n\t\t\t\t\t0 boot\n\t\t\t\tthen\n\t\t\tthen\n\t\tthen\n\t\tmenu_timeout ! ( store value on stack from above )\n\n\t\tmenu_timeout_enabled @ 1 = if\n\t\t\t\\ read custom column position (if set)\n\t\t\ts\" loader_menu_timeout_x\" getenv dup -1 = if\n\t\t\t\tdrop \\ no custom column position\n\t\t\t\tmenu_timeout_default_x \\ use default setting\n\t\t\telse\n\t\t\t\t\\ make sure custom position is a number\n\t\t\t\t?number 0= if\n\t\t\t\t\tmenu_timeout_default_x \\ or use default\n\t\t\t\tthen\n\t\t\tthen\n\t\t\tmenu_timeout_x ! ( store value on stack from above )\n \n\t\t\t\\ read custom row position (if set)\n\t\t\ts\" loader_menu_timeout_y\" getenv dup -1 = if\n\t\t\t\tdrop \\ no custom row position\n\t\t\t\tmenu_timeout_default_y \\ use default setting\n\t\t\telse\n\t\t\t\t\\ make sure custom position is a number\n\t\t\t\t?number 0= if\n\t\t\t\t\tmenu_timeout_default_y \\ or use default\n\t\t\t\tthen\n\t\t\tthen\n\t\t\tmenu_timeout_y ! ( store value on stack from above )\n\t\tthen\n\tthen\n\n\tmenu-create\n\n\tbegin \\ Loop forever\n\n\t\t0 25 at-xy \\ Move cursor to the bottom for output\n\t\tgetkey \\ Block here, waiting for a key to be pressed\n\n\t\tdup -1 = if\n\t\t\tdrop exit \\ Caught abort (abnormal return)\n\t\tthen\n\n\t\t\\ Boot if the user pressed Enter\/Ctrl-M (13) or\n\t\t\\ Ctrl-Enter\/Ctrl-J (10)\n\t\tdup over 13 = swap 10 = or if\n\t\t\tdrop ( no longer needed )\n\t\t\ts\" boot\" evaluate\n\t\t\texit ( pedantic; never reached )\n\t\tthen\n\n\t\t\\ Evaluate the decimal ASCII value against known menu item\n\t\t\\ key associations and act accordingly\n\n\t\t49 \\ Iterator start (loop range 49 to 56; ASCII '1' to '8')\n\t\tbegin\n\t\t\ts\" menukeyN @\"\n\n\t\t\t\\ replace 'N' with current iteration\n\t\t\t-rot 2dup 7 + c! rot\n\n\t\t\tevaluate rot tuck = if\n\n\t\t\t\t\\ Adjust for missing ACPI menuitem on non-i386\n\t\t\t\tarch-i386? true <> menuacpi @ 0<> and if\n\t\t\t\t\tmenuacpi @ over 2dup < -rot = or\n\t\t\t\t\tover 58 < and if\n\t\t\t\t\t( key >= menuacpi && key < 58: N -- N )\n\t\t\t\t\t\t1+\n\t\t\t\t\tthen\n\t\t\t\tthen\n\n\t\t\t\t\\ base env name for the value (x is a number)\n\t\t\t\ts\" menu_command[x]\"\n\n\t\t\t\t\\ Copy ASCII number to string at offset 13\n\t\t\t\t-rot 2dup 13 + c! rot\n\n\t\t\t\t\\ Test for the environment variable\n\t\t\t\tgetenv dup -1 <> if\n\t\t\t\t\t\\ Execute the stored procedure\n\t\t\t\t\tevaluate\n\n\t\t\t\t\t\\ We expect there to be a non-zero\n\t\t\t\t\t\\ value left on the stack after\n\t\t\t\t\t\\ executing the stored procedure.\n\t\t\t\t\t\\ If so, continue to run, else exit.\n\n\t\t\t\t\t0= if\n\t\t\t\t\t\tdrop \\ key pressed\n\t\t\t\t\t\tdrop \\ loop iterator\n\t\t\t\t\t\texit\n\t\t\t\t\telse\n\t\t\t\t\t\tswap \\ need iterator on top\n\t\t\t\t\tthen\n\t\t\t\tthen\n\n\t\t\t\t\\ Re-adjust for missing ACPI menuitem\n\t\t\t\tarch-i386? true <> menuacpi @ 0<> and if\n\t\t\t\t\tswap\n\t\t\t\t\tmenuacpi @ 1+ over 2dup < -rot = or\n\t\t\t\t\tover 59 < and if\n\t\t\t\t\t\t1-\n\t\t\t\t\tthen\n\t\t\t\t\tswap\n\t\t\t\tthen\n\t\t\telse\n\t\t\t\tswap \\ need iterator on top\n\t\t\tthen\n\n\t\t\t\\ \n\t\t\t\\ Check for menu keycode shortcut(s)\n\t\t\t\\ \n\t\t\ts\" menu_keycode[x]\"\n\t\t\t-rot 2dup 13 + c! rot\n\t\t\tgetenv dup -1 = if\n\t\t\t\tdrop\n\t\t\telse\n\t\t\t\t?number 0<> if\n\t\t\t\t\trot tuck = if\n\t\t\t\t\t\tswap\n\t\t\t\t\t\ts\" menu_command[x]\"\n\t\t\t\t\t\t-rot 2dup 13 + c! rot\n\t\t\t\t\t\tgetenv dup -1 <> if\n\t\t\t\t\t\t\tevaluate\n\t\t\t\t\t\t\t0= if\n\t\t\t\t\t\t\t\t2drop\n\t\t\t\t\t\t\t\texit\n\t\t\t\t\t\t\tthen\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tdrop\n\t\t\t\t\t\tthen\n\t\t\t\t\telse\n\t\t\t\t\t\tswap\n\t\t\t\t\tthen\n\t\t\t\tthen\n\t\t\tthen\n\n\t\t\t1+ dup 56 > \\ increment iterator\n\t\t\t \\ continue if less than 57\n\t\tuntil\n\t\tdrop \\ loop iterator\n\n\t\tmenureboot @ = if 0 reboot then\n\n\tagain\t\\ Non-operational key was pressed; repeat\n;\n\n\\ This function unsets all the possible environment variables associated with\n\\ creating the interactive menu.\n\\ \n: menu-unset ( -- )\n\n\t49 \\ Iterator start (loop range 49 to 56; ASCII '1' to '8')\n\tbegin\n\t\t\\ Unset variables in-order of appearance in menu.4th(8)\n\n\t\ts\" menu_caption[x]\"\t\\ basename for caption variable\n\t\t-rot 2dup 13 + c! rot\t\\ replace 'x' with current iteration\n\t\tunsetenv\t\t\\ not erroneous to unset unknown var\n\n\t\ts\" menu_command[x]\"\t\\ command basename\n\t\t-rot 2dup 13 + c! rot\t\\ replace 'x'\n\t\tunsetenv\n\n\t\ts\" menu_keycode[x]\"\t\\ keycode basename\n\t\t-rot 2dup 13 + c! rot\t\\ replace 'x'\n\t\tunsetenv\n\n\t\ts\" ansi_caption[x]\"\t\\ ANSI caption basename\n\t\t-rot 2dup 13 + c! rot\t\\ replace 'x'\n\t\tunsetenv\n\n\t\ts\" toggled_text[x]\"\t\\ toggle_menuitem caption basename\n\t\t-rot 2dup 13 + c! rot\t\\ replace 'x'\n\t\tunsetenv\n\n\t\ts\" toggled_ansi[x]\"\t\\ toggle_menuitem ANSI caption basename\n\t\t-rot 2dup 13 + c! rot\t\\ replace 'x'\n\t\tunsetenv\n\n\t\ts\" menu_caption[x][y]\"\t\\ cycle_menuitem caption\n\t\t-rot 2dup 13 + c! rot\t\\ replace 'x'\n\t\t49 -rot\n\t\tbegin\n\t\t\t16 2over rot + c! \\ replace 'y'\n\t\t\t2dup unsetenv\n\n\t\t\trot 1+ dup 56 > 2swap rot\n\t\tuntil\n\t\t2drop drop\n\n\t\ts\" ansi_caption[x][y]\"\t\\ cycle_menuitem ANSI caption\n\t\t-rot 2dup 13 + c! rot\t\\ replace 'x'\n\t\t49 -rot\n\t\tbegin\n\t\t\t16 2over rot + c! \\ replace 'y'\n\t\t\t2dup unsetenv\n\n\t\t\trot 1+ dup 56 > 2swap rot\n\t\tuntil\n\t\t2drop drop\n\n\t\ts\" 0 menukeyN !\"\t\\ basename for key association var\n\t\t-rot 2dup 9 + c! rot\t\\ replace 'N' with current iteration\n\t\tevaluate\t\t\\ assign zero (0) to key assoc. var\n\n\t\t1+ dup 56 >\t\\ increment, continue if less than 57\n\tuntil\n\tdrop \\ iterator\n\n\t\\ unset the timeout command\n\ts\" menu_timeout_command\" unsetenv\n\n\t\\ clear the \"Reboot\" menu option flag\n\ts\" menu_reboot\" unsetenv\n\t0 menureboot !\n\n\t\\ clear the ACPI menu option flag\n\ts\" menu_acpi\" unsetenv\n\t0 menuacpi !\n\n\t\\ clear the \"Options\" menu separator flag\n\ts\" menu_options\" unsetenv\n\t0 menuoptions !\n\n;\n\n\\ This function both unsets menu variables and visually erases the menu area\n\\ in-preparation for another menu.\n\\ \n: menu-clear ( -- )\n\tmenu-unset\n\tmenu-erase\n;\n\n\\ Assign configuration values\nbullet menubllt !\n10 menuY !\n5 menuX !\n\n\\ Initialize our boolean state variables\n0 toggle_state1 !\n0 toggle_state2 !\n0 toggle_state3 !\n0 toggle_state4 !\n0 toggle_state5 !\n0 toggle_state6 !\n0 toggle_state7 !\n0 toggle_state8 !\n\n\\ Initialize our array state variables\n0 cycle_state1 !\n0 cycle_state2 !\n0 cycle_state3 !\n0 cycle_state4 !\n0 cycle_state5 !\n0 cycle_state6 !\n0 cycle_state7 !\n0 cycle_state8 !\n\n\\ Initialize string containers\n0 init_text1 c!\n0 init_text2 c!\n0 init_text3 c!\n0 init_text4 c!\n0 init_text5 c!\n0 init_text6 c!\n0 init_text7 c!\n0 init_text8 c!\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"303c9b4205c222d3e309ac31b11b0bbccbb3b7e7","subject":"pushn\/popn","message":"pushn\/popn\n","repos":"AshleyF\/Forthkit,AshleyF\/Forthkit,AshleyF\/Forthkit","old_file":"hardware\/register\/outer.4th","new_file":"hardware\/register\/outer.4th","new_contents":"( outer interpreter - reads tokens, compiles headers, literals, ... )\n( requires assembler )\n\n( --- register allocation\/init ----------------------------------------------- )\n\n 0 const c ( char last read )\n 1 const sp ( space 32 ASCII )\n 2 const tib ( terminal input buffer )\n 3 const len ( token length )\n 4 const len' ( name length )\n 5 const zero ( constant 0 )\n 6 const d ( dictionary pointer )\n 7 const nm ( match flag for search )\n 8 const p ( pointer )\n 9 const c ( char being compared )\n 10 const p' ( pointer )\n 11 const c' ( char being compared )\n 12 const cur ( cursor )\n 13 const lnk ( link pointer )\n 14 const true ( truth value )\n 15 const false ( false value )\n 16 const n ( parsed number )\n 17 const zeroch ( '0' ASCII )\n 18 const base ( number base )\n 19 const s ( stack pointer )\n 20 const nreg ( register n number )\n 21 const ldc ( ldc instruction [0] )\n 22 const call ( call instruction [27] )\n 23 const ret ( return instruction [29] )\n 24 const two ( constant 2 )\n 25 const comp ( compiling flag )\n 26 const x ( temp )\n 27 const y ( temp )\n\n 32 sp ldc, ( space ASCII )\n 48 zeroch ldc, ( '0' ASCII )\n -1 true ldc, ( all bits set [logical\/bitwise equivalent] )\n 10 base ldc, ( decimal by default )\n 32767 s ldc, ( top of data stack )\n n nreg ldc, ( register number of n )\n 27 call ldc, ( call instruction )\n 28 ret ldc, ( ret instruction )\n 2 two ldc, ( constant 2 )\n\nleap,\n\n( --- tokenization ----------------------------------------------------------- )\n\n label &skipws ( skip until non-whitespace )\n c in, ( read char )\n c sp &skipws ble, ( keep skipping whitespace )\n ret,\n \n label &name ( read input name into buffer )\n c tib st, ( append char )\n tib tib inc, ( advance tib )\n len len inc, ( increment length )\n c in, ( read char )\n c sp &name bgt, ( continue until whitespace )\n len tib st, ( append length )\n ret,\n \n label &token ( read token into buffer )\n d tib cp, ( end of dictionary as buffer )\n zero len cp, ( initial zero length )\n &skipws call, ( skip initial whitespace )\n &name jump, ( append name )\n\n( --- dictionary search ------------------------------------------------------ )\n \n label &nomatch\n true nm cp, ( set no-match flag )\n ret,\n \n label &compcs ( compare chars to input word )\n p c ld, ( get char of input word )\n p' c' ld, ( get char of dictionary word )\n c c' &nomatch bne, ( don't match? )\n p' p' inc, ( next char of dictionary word )\n p p inc, ( next char of input word )\n p tib &compcs blt, ( not end of word? continue... )\n ret, ( we have a match! )\n \n label &nextw ( advance to next word )\n cur cur ld, ( follow link address )\n ( fall through to &comp )\n \n label &comp\nzero cur &nomatch beq, ( no match if start of dict )\n tib len p sub, ( point p at start of token )\n cur p' dec, ( point p' at length field )\n p' len' ld, ( get length )\n len' len &nextw bne, ( lengths don't match? )\n p' len p' sub, ( move to beginning of word )\n false nm cp, ( reset no-match flag )\n &compcs call, ( compare characters )\n true nm &nextw beq, ( if no match, try next word )\n ret, ( we have a match! )\n \n label &find ( find word [tib within dictionary] )\n lnk cur cp, ( initialize cursor to last )\n &comp jump, ( compare with tib )\n \n( --- number processing ------------------------------------------------------ )\n\n label &digits\n p c ld, ( get char )\n c zeroch c sub, ( convert to digit )\n n base n mul, ( base shift left )\n n c n add, ( add in one's place )\n p p inc, ( next char )\n p tib &digits blt, ( not end? continue... )\n ret,\n \n label &parsenum ( parse token as number )\n tib len p sub, ( point p at start of word )\n zero n cp, ( init number )\n &digits jump,\n \n label &pushn ( push interactive number )\n n s st, ( store n at stack pointer )\n s s dec, ( adjust stack pointer )\n ret,\n \n label &popn ( pop number )\n s s inc, ( adjust stack pointer )\n s n ld, ( load value )\n ret,\n\n( --- literals --------------------------------------------------------------- )\n\n: append, d st, d d inc, ; ( macro: append and advance d )\n\n label &litn ( compile literal )\n ldc append, ( append ldc instruction )\n nreg append, ( append n register number )\n n append, ( append value )\n call append, ( append call instruction )\n &pushn x ldc, ( load address of &pushn )\n x append, ( append pushn address )\n ret,\n \n label &num ( process token as number )\n &parsenum call, ( parse number )\n true comp &litn beq, ( if compiling, compile literal )\n &pushn jump, ( else, push literal )\n \n( --- word processing -------------------------------------------------------- )\n\n label &exec ( execute word )\n two cur x add, ( point to code field )\n x exec, ( exec word )\n ret,\n \n label &compw ( compile word )\n cur x inc, ( point to immediate flag )\n x y ld, ( read immediate flag )\n true y &exec beq, ( execute if immediate )\n call append, ( append call instruction )\n x x inc, ( point to code field )\n x append, ( append code field address )\n ret,\n \n label &word ( process potential word token )\n true comp &compw beq, ( if compiling, compile word )\n &exec jump, ( else, execute word )\n \n label &eval ( process input tokens )\n &find call, ( try to find in dictionary )\n true nm &num beq, ( if not found, assume number )\n &word jump, ( else, process as a word )\n \n( --- REPL ------------------------------------------------------------------- )\n\n label &repl ( loop forever )\n &token call, ( read a token )\n &eval call, ( evaluate it )\n &repl jump, ( forever )\n \n( --- initial dictionary ----------------------------------------------------- )\n\nvar link\n: header, dup 0 do swap , loop , link @ here link ! , , ;\n\n 0 sym create header, ( word to create words )\n &token call, ( read a token )\n tib d cp, ( move dict ptr to end of name )\n d d inc, ( move past length field )\n lnk d st, ( append link address )\n d lnk cp, ( update link to here )\n d d inc, ( advance dictionary pointer )\n zero append, ( append 0 immediate flag ) \n ret,\n\n 0 sym immediate header, ( set immediate flag )\n lnk x inc, ( point to immediate flag )\n true x st, ( set immediate flag )\n ret,\n\n 0 sym compile header, ( switch to compiling mode )\n true comp cp, ( set comp flag )\n ret,\n\n 0 sym interact header, ( switch to interactive mode )\n label &interact\n false comp ldc, ( reset comp flag )\n ret,\n\n -1 sym ; header, ( return )\n ret append, ( append ret instruction )\n &interact jump, ( switch out of compiling mode )\n \n 0 sym pushn header, ( push number to stack from n )\n &pushn jump, ( jump to push )\n \n 0 sym popn header, ( pop number from stack to n )\n &popn jump, ( jump pop )\n \n 0 sym , header, ( append value from stack )\n &popn call, ( pop value from stack )\n n append, ( append n ) \n ret,\n \n 0 sym find header, ( find word )\n &token call, ( read a token )\n &find call, ( find token )\n cur n cp, ( prep to push cursor )\n two n n add, ( address of code field )\n &pushn jump, ( push cursor )\n \n 0 sym dump header, ( dump core to boot.bin )\n dump, ( TODO: build outside of outer interpreter )\n\nahead,\n\n( --- set `lnk` to within last header and `d` to just past this code --------- )\n\nlink @ lnk ldc, ( compile-time link ptr to runtime )\nhere 5 + d ldc, ( compile-time dict ptr to runtime [advance over init code below] )\n\n&repl jump, ( start the REPL )\n\nassemble\n\n","old_contents":"( outer interpreter - reads tokens, compiles headers, literals, ... )\n( requires assembler )\n\n( --- register allocation\/init ----------------------------------------------- )\n\n 0 const c ( char last read )\n 1 const sp ( space 32 ASCII )\n 2 const tib ( terminal input buffer )\n 3 const len ( token length )\n 4 const len' ( name length )\n 5 const zero ( constant 0 )\n 6 const d ( dictionary pointer )\n 7 const nm ( match flag for search )\n 8 const p ( pointer )\n 9 const c ( char being compared )\n 10 const p' ( pointer )\n 11 const c' ( char being compared )\n 12 const cur ( cursor )\n 13 const lnk ( link pointer )\n 14 const true ( truth value )\n 15 const false ( false value )\n 16 const n ( parsed number )\n 17 const zeroch ( '0' ASCII )\n 18 const base ( number base )\n 19 const s ( stack pointer )\n 20 const nreg ( register n number )\n 21 const ldc ( ldc instruction [0] )\n 22 const call ( call instruction [27] )\n 23 const ret ( return instruction [29] )\n 24 const two ( constant 2 )\n 25 const comp ( compiling flag )\n 26 const x ( temp )\n 27 const y ( temp )\n 28 const z ( temp - reserved bootstrap )\n\n 32 sp ldc, ( space ASCII )\n 48 zeroch ldc, ( '0' ASCII )\n -1 true ldc, ( all bits set [logical\/bitwise equivalent] )\n 10 base ldc, ( decimal by default )\n 32767 s ldc, ( top of data stack )\n n nreg ldc, ( register number of n )\n 27 call ldc, ( call instruction )\n 28 ret ldc, ( ret instruction )\n 2 two ldc, ( constant 2 )\n\nleap,\n\n( --- tokenization ----------------------------------------------------------- )\n\n label &skipws ( skip until non-whitespace )\n c in, ( read char )\n c sp &skipws ble, ( keep skipping whitespace )\n ret,\n \n label &name ( read input name into buffer )\n c tib st, ( append char )\n tib tib inc, ( advance tib )\n len len inc, ( increment length )\n c in, ( read char )\n c sp &name bgt, ( continue until whitespace )\n len tib st, ( append length )\n ret,\n \n label &token ( read token into buffer )\n d tib cp, ( end of dictionary as buffer )\n zero len cp, ( initial zero length )\n &skipws call, ( skip initial whitespace )\n &name jump, ( append name )\n\n( --- dictionary search ------------------------------------------------------ )\n \n label &nomatch\n true nm cp, ( set no-match flag )\n ret,\n \n label &compcs ( compare chars to input word )\n p c ld, ( get char of input word )\n p' c' ld, ( get char of dictionary word )\n c c' &nomatch bne, ( don't match? )\n p' p' inc, ( next char of dictionary word )\n p p inc, ( next char of input word )\n p tib &compcs blt, ( not end of word? continue... )\n ret, ( we have a match! )\n \n label &nextw ( advance to next word )\n cur cur ld, ( follow link address )\n ( fall through to &comp )\n \n label &comp\nzero cur &nomatch beq, ( no match if start of dict )\n tib len p sub, ( point p at start of token )\n cur p' dec, ( point p' at length field )\n p' len' ld, ( get length )\n len' len &nextw bne, ( lengths don't match? )\n p' len p' sub, ( move to beginning of word )\n false nm cp, ( reset no-match flag )\n &compcs call, ( compare characters )\n true nm &nextw beq, ( if no match, try next word )\n ret, ( we have a match! )\n \n label &find ( find word [tib within dictionary] )\n lnk cur cp, ( initialize cursor to last )\n &comp jump, ( compare with tib )\n \n( --- number processing ------------------------------------------------------ )\n\n label &digits\n p c ld, ( get char )\n c zeroch c sub, ( convert to digit )\n n base n mul, ( base shift left )\n n c n add, ( add in one's place )\n p p inc, ( next char )\n p tib &digits blt, ( not end? continue... )\n ret,\n \n label &parsenum ( parse token as number )\n tib len p sub, ( point p at start of word )\n zero n cp, ( init number )\n &digits jump,\n \n label &pushn ( push interactive number )\n n s st, ( store n at stack pointer )\n s s dec, ( adjust stack pointer )\n ret,\n \n label &popn ( pop number )\n s s inc, ( adjust stack pointer )\n s n ld, ( load value )\n ret,\n\n( --- literals --------------------------------------------------------------- )\n\n: append, d st, d d inc, ; ( macro: append and advance d )\n\n label &litn ( compile literal )\n ldc append, ( append ldc instruction )\n nreg append, ( append n register number )\n n append, ( append value )\n call append, ( append call instruction )\n &pushn x ldc, ( load address of &pushn )\n x append, ( append pushn address )\n ret,\n \n label &num ( process token as number )\n &parsenum call, ( parse number )\n true comp &litn beq, ( if compiling, compile literal )\n &pushn jump, ( else, push literal )\n \n( --- word processing -------------------------------------------------------- )\n\n label &exec ( execute word )\n two cur x add, ( point to code field )\n x exec, ( exec word )\n ret,\n \n label &compw ( compile word )\n cur x inc, ( point to immediate flag )\n x y ld, ( read immediate flag )\n true y &exec beq, ( execute if immediate )\n call append, ( append call instruction )\n x x inc, ( point to code field )\n x append, ( append code field address )\n ret,\n \n label &word ( process potential word token )\n true comp &compw beq, ( if compiling, compile word )\n &exec jump, ( else, execute word )\n \n label &eval ( process input tokens )\n &find call, ( try to find in dictionary )\n true nm &num beq, ( if not found, assume number )\n &word jump, ( else, process as a word )\n \n( --- REPL ------------------------------------------------------------------- )\n\n label &repl ( loop forever )\n &token call, ( read a token )\n &eval call, ( evaluate it )\n &repl jump, ( forever )\n \n( --- initial dictionary ----------------------------------------------------- )\n\nvar link\n: header, dup 0 do swap , loop , link @ here link ! , , ;\n\n 0 sym create header, ( word to create words )\n &token call, ( read a token )\n tib d cp, ( move dict ptr to end of name )\n d d inc, ( move past length field )\n lnk d st, ( append link address )\n d lnk cp, ( update link to here )\n d d inc, ( advance dictionary pointer )\n zero append, ( append 0 immediate flag ) \n ret,\n\n 0 sym immediate header, ( set immediate flag )\n lnk x inc, ( point to immediate flag )\n true x st, ( set immediate flag )\n ret,\n\n 0 sym compile header, ( switch to compiling mode )\n true comp cp, ( set comp flag )\n ret,\n\n 0 sym interact header, ( switch to interactive mode )\n label &interact\n false comp ldc, ( reset comp flag )\n ret,\n\n -1 sym ; header, ( return )\n ret append, ( append ret instruction )\n &interact jump, ( switch out of compiling mode )\n \n 0 sym pushn, header, ( push number [n] to stack from )\n &pushn jump, ( jump to push )\n \n 0 sym popn, header, ( pop number from stack to n )\n &popn jump, ( jump pop )\n \n 0 sym , header, ( append value from stack )\n &popn call, ( pop value from stack )\n n append, ( append n ) \n ret,\n \n 0 sym find header, ( find word )\n &token call, ( read a token )\n &find call, ( find token )\n cur n cp, ( prep to push cursor )\n two n n add, ( address of code field )\n &pushn jump, ( push cursor )\n \n 0 sym dump header, ( dump core to boot.bin )\n dump, ( TODO: build outside of outer interpreter )\n\nahead,\n\n( --- set `lnk` to within last header and `d` to just past this code --------- )\n\nlink @ lnk ldc, ( compile-time link ptr to runtime )\nhere 5 + d ldc, ( compile-time dict ptr to runtime [advance over init code below] )\n\n&repl jump, ( start the REPL )\n\nassemble\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"59122a1a7d239139a0735f05b509a9e1496d158a","subject":"Removed seek words","message":"Removed seek words\n","repos":"tehologist\/forthkit","old_file":"eforth.forth","new_file":"eforth.forth","new_contents":": + UM+ DROP ; \n: CELLS DUP + ; \n: CELL+ 2 + ; \n: CELL- -2 + ; \n: CELL 2 ; \n: BOOT 0 CELLS ; \n: FORTH 4 CELLS ; \n: DPL 5 CELLS ; \n: SP0 6 CELLS ; \n: RP0 7 CELLS ; \n: '?KEY 8 CELLS ; \n: 'EMIT 9 CELLS ; \n: 'EXPECT 10 CELLS ; \n: 'TAP 11 CELLS ; \n: 'ECHO 12 CELLS ; \n: 'PROMPT 13 CELLS ; \n: BASE 14 CELLS ; \n: tmp 15 CELLS ; \n: SPAN 16 CELLS ; \n: >IN 17 CELLS ; \n: #TIBB 18 CELLS ; \n: TIBB 19 CELLS ; \n: CSP 20 CELLS ; \n: 'EVAL 21 CELLS ; \n: 'NUMBER 22 CELLS ; \n: HLD 23 CELLS ; \n: HANDLER 24 CELLS ; \n: CONTEXT 25 CELLS ; \n: CURRENT 27 CELLS ; \n: CP 29 CELLS ; \n: NP 30 CELLS ; \n: LAST 31 CELLS ; \n: STATE 32 CELLS ; \n: SPP 33 CELLS ; \n: RPP 34 CELLS ; \n: TRUE -1 ; \n: FALSE 0 ; \n: BL 32 ; \n: BS 8 ; \n: =IMMED 3 ; \n: =WORDLIST 2 ; \n: IMMEDIATE =IMMED LAST @ CELL- ! ; \n: HERE CP @ ; \n: ALLOT CP @ + CP ! ; \n: , HERE CELL ALLOT ! ; \n: C, HERE 1 ALLOT C! ; \n: +! SWAP OVER @ + SWAP ! ; \n: COMPILE R> DUP @ , CELL+ >R ; \n: STATE? STATE @ ; \n: LITERAL COMPILE LIT , ; IMMEDIATE \n: [ FALSE STATE ! ; IMMEDIATE \n: ] TRUE STATE ! ; IMMEDIATE \n: IF COMPILE 0BRANCH HERE 0 , ; IMMEDIATE \n: THEN HERE SWAP ! ; IMMEDIATE \n: FOR COMPILE >R HERE ; IMMEDIATE \n: NEXT COMPILE next , ; IMMEDIATE \n: BEGIN HERE ; IMMEDIATE \n: AGAIN COMPILE BRANCH , ; IMMEDIATE \n: UNTIL COMPILE 0BRANCH , ; IMMEDIATE \n: AHEAD COMPILE BRANCH HERE 0 , ; IMMEDIATE \n: REPEAT COMPILE BRANCH , HERE SWAP ! ; IMMEDIATE \n: AFT DROP COMPILE BRANCH HERE 0 , HERE SWAP ; IMMEDIATE \n: ELSE COMPILE BRANCH HERE 0 , SWAP HERE SWAP ! ; IMMEDIATE \n: WHILE COMPILE 0BRANCH HERE 0 , SWAP ; IMMEDIATE \n: EXECUTE >R ; \n: @EXECUTE @ DUP IF EXECUTE THEN ; \n: R@ R> R> DUP >R SWAP >R ; \n: #TIB #TIBB @ ; \n: TIB TIBB @ ; \n: \\ #TIB @ >IN ! ; IMMEDIATE \n: ROT >R SWAP R> SWAP ; \n: -ROT SWAP >R SWAP R> ; \n: NIP SWAP DROP ; \n: TUCK SWAP OVER ; \n: 2>R SWAP R> SWAP >R SWAP >R >R ; \n: 2R> R> R> SWAP R> SWAP >R SWAP ; \n: 2R@ R> R> R@ SWAP >R SWAP R@ SWAP >R ; \n: 2DROP DROP DROP ; \n: 2DUP OVER OVER ; \n: 2SWAP ROT >R ROT R> ; \n: 2OVER >R >R 2DUP R> R> 2SWAP ; \n: 2ROT 2>R 2SWAP 2R> 2SWAP ; \n: -2ROT 2ROT 2ROT ; \n: 2NIP 2SWAP 2DROP ; \n: 2TUCK 2SWAP 2OVER ; \n: NOT DUP NAND ; \n: AND NAND NOT ; \n: OR NOT SWAP NOT NAND ; \n: NOR OR NOT ; \n: XOR 2DUP AND -ROT NOR NOR ; \n: XNOR XOR NOT ; \n: NEGATE NOT 1 + ; \n: - NEGATE + ; \n: 1+ 1 + ; \n: 1- 1 - ; \n: 2+ 2 + ; \n: 2- 2 - ; \n: D+ >R SWAP >R UM+ R> R> + + ; \n: DNEGATE NOT >R NOT 1 UM+ R> + ; \n: D- DNEGATE D+ ; \n: 2! SWAP OVER ! CELL+ ! ; \n: 2@ DUP CELL+ @ SWAP @ ; \n: ?DUP DUP IF DUP THEN ; \n: S>D DUP 0< ; \n: ABS DUP 0< IF NEGATE THEN ; \n: DABS DUP 0< IF DNEGATE THEN ; \n: U< 2DUP XOR 0< IF SWAP DROP 0< EXIT THEN - 0< ; \n: U> SWAP U< ; \n: = XOR IF FALSE EXIT THEN TRUE ; \n: < 2DUP XOR 0< IF DROP 0< EXIT THEN - 0< ; \n: > SWAP < ; \n: 0> NEGATE 0< ; \n: 0<> IF TRUE EXIT THEN FALSE ; \n: 0= 0 = ; \n: <> = 0= ; \n: D0< SWAP DROP 0< ; \n: D0> DNEGATE D0< ; \n: D0= OR 0= ; \n: D= D- D0= ; \n: D< ROT 2DUP XOR IF SWAP 2SWAP 2DROP < ; \n: DU< ROT 2DUP XOR IF SWAP 2SWAP THEN THEN 2DROP U< ; \n: DMIN 2OVER 2OVER 2SWAP D< IF 2SWAP THEN 2DROP ; \n: DMAX 2OVER 2OVER D< IF 2SWAP THEN 2DROP ; \n: M+ S>D D+ ; \n: M- S>D D- ; \n: MIN 2DUP SWAP < IF SWAP THEN DROP ; \n: MAX 2DUP < IF SWAP THEN DROP ; \n: UMIN 2DUP SWAP U< IF SWAP THEN DROP ; \n: UMAX 2DUP U< IF SWAP THEN DROP ; \n: WITHIN OVER - >R - R> U< ; \n: UM\/MOD \n 2DUP U< \n IF NEGATE \n 15 FOR \n >R DUP UM+ \n >R >R DUP UM+ \n R> + DUP R> R@ SWAP \n >R UM+ \n R> OR \n IF >R DROP 1+ R> \n ELSE DROP \n THEN R> \n NEXT DROP SWAP EXIT \n THEN DROP 2DROP -1 DUP ; \n: M\/MOD \n DUP 0< DUP >R \n IF NEGATE >R \n DNEGATE R> \n THEN >R DUP 0< \n IF R@ + \n THEN R> UM\/MOD \n R> \n IF SWAP NEGATE SWAP THEN ; \n: \/MOD OVER 0< SWAP M\/MOD ; \n: MOD \/MOD DROP ; \n: \/ \/MOD NIP ; \n: UM* \n 0 SWAP \n 15 FOR \n DUP UM+ >R >R \n DUP UM+ \n R> + \n R> \n IF >R OVER UM+ \n R> + \n THEN \n NEXT \n ROT DROP ; \n: * UM* DROP ; \n: M* \n 2DUP XOR 0< >R \n ABS SWAP ABS UM* \n R> IF DNEGATE THEN ; \n: *\/MOD >R M* R> M\/MOD ; \n: *\/ *\/MOD SWAP DROP ; \n: 2* 2 * ; \n: 2\/ 2 \/ ; \n: MU\/MOD >R 0 R@ UM\/MOD R> SWAP >R UM\/MOD R> ; \n: D2* 2DUP D+ ; \n: DU2\/ 2 MU\/MOD ROT DROP ; \n: D2\/ DUP >R 1 AND DU2\/ R> 2\/ OR ; \n: ALIGNED DUP 0 2 UM\/MOD DROP DUP IF 2 SWAP - THEN + ; \n: parse \n tmp ! OVER >R DUP \n IF \n 1- tmp @ BL = \n IF \n FOR BL OVER C@ - 0< NOT \n WHILE 1+ \n NEXT R> DROP 0 DUP EXIT \n THEN R> \n THEN \n OVER SWAP \n FOR tmp @ OVER C@ - tmp @ BL = \n IF 0< THEN \n WHILE 1+ \n NEXT DUP >R \n ELSE R> DROP DUP 1+ >R \n THEN OVER - R> R> - EXIT \n THEN OVER R> - ; \n: PARSE >R TIB >IN @ + #TIB C@ >IN @ - R> parse >IN +! ; \n: CHAR BL PARSE DROP C@ ; \n: TX! 1 PUTC ; \n: EMIT 'EMIT @EXECUTE ; \n: TYPE FOR AFT DUP C@ EMIT 1+ THEN NEXT DROP ; \n: ?RX 0 GETC ; \n: ?KEY '?KEY @EXECUTE ; \n: KEY BEGIN ?KEY UNTIL ; \n: COUNT DUP 1+ SWAP C@ ; \n: CMOVE \n FOR \n AFT \n >R DUP C@ R@ C! 1+ R> 1+ \n THEN \n NEXT 2DROP ; \n: FILL \n SWAP \n FOR SWAP \n AFT 2DUP C! 1+ THEN \n NEXT 2DROP ; \n: -TRAILING \n FOR \n AFT \n BL OVER R@ + C@ < \n IF \n R> 1+ EXIT \n THEN \n THEN \n NEXT 0 ; \n: PACK$ \n DUP >R \n 2DUP C! 1+ 2DUP + 0 SWAP ! SWAP CMOVE \n R> ; \n: WORD PARSE HERE PACK$ ; \n: TOKEN BL PARSE 31 MIN NP @ OVER - 1- PACK$ ; \n: LINK> 3 CELLS - ; \n: CODE> 2 CELLS - ; \n: TYPE> 1 CELLS - ; \n: DATA> CELL+ ; \n: SAME? \n FOR AFT \n OVER R@ CELLS + @ \n OVER R@ CELLS + @ \n - ?DUP \n IF R> DROP EXIT THEN \n THEN \n NEXT 0 ; \n: find \n @ BEGIN DUP WHILE \n 2DUP C@ SWAP C@ = IF \n 2DUP 1+ SWAP COUNT ALIGNED CELL \/ >R SWAP R> \n SAME? 0= IF \n 2DROP SWAP DROP DUP CODE> @ SWAP -1 EXIT \n THEN 2DROP THEN \n LINK> @ REPEAT ; \n: ' TOKEN CONTEXT @ find IF DROP ELSE SWAP DROP 0 THEN ; \n: ! ! ; \n' TX! 'EMIT ! \n' ?RX '?KEY ! \n: ['] COMPILE ' ; IMMEDIATE \n: POSTPONE ' , ; IMMEDIATE \n: [CHAR] CHAR POSTPONE LITERAL ; IMMEDIATE \n: ( [CHAR] ) PARSE 2DROP ; IMMEDIATE \n: :NONAME HERE POSTPONE ] ; \n: OVERT LAST @ CURRENT @ ! ; \n: $,n \n DUP LAST ! CELL- \n DUP =WORDLIST \n SWAP ! \n CELL- DUP HERE \n SWAP ! \n CELL- DUP CURRENT @ @ \n SWAP ! \n CELL- NP ! ; \n: : TOKEN $,n POSTPONE ] ; \n: ; COMPILE EXIT POSTPONE [ OVERT ; IMMEDIATE \n: RECURSE LAST @ CURRENT @ ! ; IMMEDIATE \n: doVAR R> ; \n: CREATE TOKEN $,n COMPILE doVAR OVERT ; \n: DOES LAST @ CODE> @ R> SWAP ! ; \n: DOES> COMPILE DOES COMPILE R> ; IMMEDIATE \n: CONSTANT CREATE , DOES> @ ; \n: VARIABLE CREATE 0 , ; \n: 2LITERAL SWAP POSTPONE LITERAL \n POSTPONE LITERAL ; IMMEDIATE \n: 2CONSTANT CREATE , , DOES> 2@ ; \n: 2VARIABLE CREATE 2 CELLS ALLOT ; \n: SPACE BL EMIT ; \n: SPACES 0 MAX FOR SPACE NEXT ; \n: PAD HERE 80 + ; \n: DECIMAL 10 BASE ! ; \n: HEX 16 BASE ! ; \n: BINARY 2 BASE ! ; \n: OCTAL 8 BASE ! ; \nDECIMAL \n: CHAR- 1- ; \n: CHAR+ 1+ ; \n: CHARS ; \n: >CHAR 127 AND DUP 127 BL WITHIN IF DROP 95 THEN ; \n: DIGIT 9 OVER < 7 AND + [CHAR] 0 + ; \n: <# PAD HLD ! ; \n: HOLD HLD @ CHAR- DUP HLD ! C! ; \n: # 0 BASE @ UM\/MOD >R BASE @ UM\/MOD SWAP DIGIT HOLD R> ; \n: #S BEGIN # 2DUP OR 0= UNTIL ; \n: SIGN 0< IF [CHAR] - HOLD THEN ; \n: #> 2DROP HLD @ PAD OVER - ; \n: S.R OVER - SPACES TYPE ; \n: D.R >R DUP >R DABS <# #S R> SIGN #> R> S.R ; \n: U.R 0 SWAP D.R ; \n: .R >R S>D R> D.R ; \n: D. 0 D.R SPACE ; \n: U. 0 D. ; \n: . BASE @ 10 XOR IF U. EXIT THEN S>D D. ; \n: ? @ . ; \n: DU.R >R <# #S #> R> S.R ; \n: DU. DU.R SPACE ; \n: do$ R> R@ R> COUNT + ALIGNED >R SWAP >R ; \n: .\"| do$ COUNT TYPE ; \n: $,\" [CHAR] \" WORD COUNT + ALIGNED CP ! ; \n: .\" COMPILE .\"| $,\" ; IMMEDIATE \n: .( [CHAR] ) PARSE TYPE ; IMMEDIATE \n: $\"| do$ ; \n: $\" COMPILE $\"| $,\" ; IMMEDIATE \n: s\" [CHAR] \" PARSE HERE PACK$ ; \n: CR 10 EMIT ; \n: TAP OVER C! 1+ ; \n: KTAP \n 10 XOR \n IF \n BL TAP EXIT \n THEN \n NIP DUP ; \n: ACCEPT \n OVER + OVER \n BEGIN \n 2DUP XOR \n WHILE \n KEY \n DUP BL - 95 U< \n IF TAP ELSE KTAP THEN \n REPEAT DROP OVER - ; \n: EXPECT ACCEPT SPAN ! DROP ; \n: QUERY TIB 80 ACCEPT #TIB C! DROP 0 >IN ! ; \n: DIGIT? \n >R [CHAR] 0 - \n 9 OVER < \n IF 7 - DUP 10 < OR THEN \n DUP R> U< ; \n: \/STRING DUP >R - SWAP R> + SWAP ; \n: >NUMBER \n BEGIN DUP \n WHILE >R DUP >R C@ BASE @ DIGIT? \n WHILE SWAP BASE @ UM* DROP ROT \n BASE @ UM* D+ R> CHAR+ R> 1 - \n REPEAT DROP R> R> THEN ; \n: NUMBER? \n OVER C@ [CHAR] - = DUP >R IF 1 \/STRING THEN \n >R >R 0 DUP R> R> -1 DPL ! \n BEGIN >NUMBER DUP \n WHILE OVER C@ [CHAR] . XOR \n IF ROT DROP ROT R> 2DROP FALSE EXIT \n THEN 1 - DPL ! CHAR+ DPL @ \n REPEAT 2DROP R> IF DNEGATE THEN TRUE ; \n' NUMBER? 'NUMBER ! \n: $INTERPRET \n CONTEXT @ find \n IF DROP EXECUTE EXIT THEN \n COUNT 'NUMBER @EXECUTE IF \n DPL @ 0< IF DROP THEN EXIT THEN .\" ?\" TYPE ; \n: $COMPILE \n CONTEXT @ find \n IF CELL- @ =IMMED = \n IF EXECUTE ELSE , THEN EXIT \n THEN COUNT 'NUMBER @EXECUTE \n IF \n DPL @ 0< \n IF DROP POSTPONE LITERAL \n ELSE POSTPONE 2LITERAL \n THEN EXIT \n THEN .\" ?\" TYPE ; \n: eval STATE? IF $COMPILE ELSE $INTERPRET THEN ; \n' eval 'EVAL ! \n: EVAL \n BEGIN TOKEN DUP C@ WHILE \n 'EVAL @EXECUTE \n REPEAT DROP ; \n: OK CR .\" OK.\" SPACE ; \n' OK 'PROMPT ! \n: QUIT \n BEGIN 'PROMPT @EXECUTE QUERY \n EVAL AGAIN ; \n: BYE .\" Good Bye \" CR HALT ; \n' QUIT BOOT ! \n: SP@ SPP @ ; \n: DEPTH SP@ SP0 @ - CELL \/ ; \n: PICK CELLS SP@ SWAP - 2 CELLS - @ ; \n: .S CR DEPTH FOR AFT R@ PICK . THEN NEXT SPACE .\" \n @ SPACE REPEAT DROP CR ; \n\nVARIABLE FILE \n: OPEN F_OPEN FILE ! ; \n: CLOSE FILE @ F_CLOSE ; \n: FPUT FILE @ PUTC ; \n: FGET FILE @ GETC ; \n: FPUTS COUNT FOR AFT DUP C@ FPUT 1+ THEN NEXT DROP ; \n\n: SAVEVM $\" eforth.img\" $\" wb\" OPEN 0 \n 16384 FOR AFT DUP C@ FPUT 1+ THEN NEXT CLOSE DROP ; \n\nSAVEVM \n\n","old_contents":": + UM+ DROP ; \n: CELLS DUP + ; \n: CELL+ 2 + ; \n: CELL- -2 + ; \n: CELL 2 ; \n: BOOT 0 CELLS ; \n: FORTH 4 CELLS ; \n: DPL 5 CELLS ; \n: SP0 6 CELLS ; \n: RP0 7 CELLS ; \n: '?KEY 8 CELLS ; \n: 'EMIT 9 CELLS ; \n: 'EXPECT 10 CELLS ; \n: 'TAP 11 CELLS ; \n: 'ECHO 12 CELLS ; \n: 'PROMPT 13 CELLS ; \n: BASE 14 CELLS ; \n: tmp 15 CELLS ; \n: SPAN 16 CELLS ; \n: >IN 17 CELLS ; \n: #TIBB 18 CELLS ; \n: TIBB 19 CELLS ; \n: CSP 20 CELLS ; \n: 'EVAL 21 CELLS ; \n: 'NUMBER 22 CELLS ; \n: HLD 23 CELLS ; \n: HANDLER 24 CELLS ; \n: CONTEXT 25 CELLS ; \n: CURRENT 27 CELLS ; \n: CP 29 CELLS ; \n: NP 30 CELLS ; \n: LAST 31 CELLS ; \n: STATE 32 CELLS ; \n: SPP 33 CELLS ; \n: RPP 34 CELLS ; \n: TRUE -1 ; \n: FALSE 0 ; \n: BL 32 ; \n: BS 8 ; \n: =IMMED 3 ; \n: =WORDLIST 2 ; \n: IMMEDIATE =IMMED LAST @ CELL- ! ; \n: HERE CP @ ; \n: ALLOT CP @ + CP ! ; \n: , HERE CELL ALLOT ! ; \n: C, HERE 1 ALLOT C! ; \n: +! SWAP OVER @ + SWAP ! ; \n: COMPILE R> DUP @ , CELL+ >R ; \n: STATE? STATE @ ; \n: LITERAL COMPILE LIT , ; IMMEDIATE \n: [ FALSE STATE ! ; IMMEDIATE \n: ] TRUE STATE ! ; IMMEDIATE \n: IF COMPILE 0BRANCH HERE 0 , ; IMMEDIATE \n: THEN HERE SWAP ! ; IMMEDIATE \n: FOR COMPILE >R HERE ; IMMEDIATE \n: NEXT COMPILE next , ; IMMEDIATE \n: BEGIN HERE ; IMMEDIATE \n: AGAIN COMPILE BRANCH , ; IMMEDIATE \n: UNTIL COMPILE 0BRANCH , ; IMMEDIATE \n: AHEAD COMPILE BRANCH HERE 0 , ; IMMEDIATE \n: REPEAT COMPILE BRANCH , HERE SWAP ! ; IMMEDIATE \n: AFT DROP COMPILE BRANCH HERE 0 , HERE SWAP ; IMMEDIATE \n: ELSE COMPILE BRANCH HERE 0 , SWAP HERE SWAP ! ; IMMEDIATE \n: WHILE COMPILE 0BRANCH HERE 0 , SWAP ; IMMEDIATE \n: EXECUTE >R ; \n: @EXECUTE @ DUP IF EXECUTE THEN ; \n: R@ R> R> DUP >R SWAP >R ; \n: #TIB #TIBB @ ; \n: TIB TIBB @ ; \n: \\ #TIB @ >IN ! ; IMMEDIATE \n: ROT >R SWAP R> SWAP ; \n: -ROT SWAP >R SWAP R> ; \n: NIP SWAP DROP ; \n: TUCK SWAP OVER ; \n: 2>R SWAP R> SWAP >R SWAP >R >R ; \n: 2R> R> R> SWAP R> SWAP >R SWAP ; \n: 2R@ R> R> R@ SWAP >R SWAP R@ SWAP >R ; \n: 2DROP DROP DROP ; \n: 2DUP OVER OVER ; \n: 2SWAP ROT >R ROT R> ; \n: 2OVER >R >R 2DUP R> R> 2SWAP ; \n: 2ROT 2>R 2SWAP 2R> 2SWAP ; \n: -2ROT 2ROT 2ROT ; \n: 2NIP 2SWAP 2DROP ; \n: 2TUCK 2SWAP 2OVER ; \n: NOT DUP NAND ; \n: AND NAND NOT ; \n: OR NOT SWAP NOT NAND ; \n: NOR OR NOT ; \n: XOR 2DUP AND -ROT NOR NOR ; \n: XNOR XOR NOT ; \n: NEGATE NOT 1 + ; \n: - NEGATE + ; \n: 1+ 1 + ; \n: 1- 1 - ; \n: 2+ 2 + ; \n: 2- 2 - ; \n: D+ >R SWAP >R UM+ R> R> + + ; \n: DNEGATE NOT >R NOT 1 UM+ R> + ; \n: D- DNEGATE D+ ; \n: 2! SWAP OVER ! CELL+ ! ; \n: 2@ DUP CELL+ @ SWAP @ ; \n: ?DUP DUP IF DUP THEN ; \n: S>D DUP 0< ; \n: ABS DUP 0< IF NEGATE THEN ; \n: DABS DUP 0< IF DNEGATE THEN ; \n: U< 2DUP XOR 0< IF SWAP DROP 0< EXIT THEN - 0< ; \n: U> SWAP U< ; \n: = XOR IF FALSE EXIT THEN TRUE ; \n: < 2DUP XOR 0< IF DROP 0< EXIT THEN - 0< ; \n: > SWAP < ; \n: 0> NEGATE 0< ; \n: 0<> IF TRUE EXIT THEN FALSE ; \n: 0= 0 = ; \n: <> = 0= ; \n: D0< SWAP DROP 0< ; \n: D0> DNEGATE D0< ; \n: D0= OR 0= ; \n: D= D- D0= ; \n: D< ROT 2DUP XOR IF SWAP 2SWAP 2DROP < ; \n: DU< ROT 2DUP XOR IF SWAP 2SWAP THEN THEN 2DROP U< ; \n: DMIN 2OVER 2OVER 2SWAP D< IF 2SWAP THEN 2DROP ; \n: DMAX 2OVER 2OVER D< IF 2SWAP THEN 2DROP ; \n: M+ S>D D+ ; \n: M- S>D D- ; \n: MIN 2DUP SWAP < IF SWAP THEN DROP ; \n: MAX 2DUP < IF SWAP THEN DROP ; \n: UMIN 2DUP SWAP U< IF SWAP THEN DROP ; \n: UMAX 2DUP U< IF SWAP THEN DROP ; \n: WITHIN OVER - >R - R> U< ; \n: UM\/MOD \n 2DUP U< \n IF NEGATE \n 15 FOR \n >R DUP UM+ \n >R >R DUP UM+ \n R> + DUP R> R@ SWAP \n >R UM+ \n R> OR \n IF >R DROP 1+ R> \n ELSE DROP \n THEN R> \n NEXT DROP SWAP EXIT \n THEN DROP 2DROP -1 DUP ; \n: M\/MOD \n DUP 0< DUP >R \n IF NEGATE >R \n DNEGATE R> \n THEN >R DUP 0< \n IF R@ + \n THEN R> UM\/MOD \n R> \n IF SWAP NEGATE SWAP THEN ; \n: \/MOD OVER 0< SWAP M\/MOD ; \n: MOD \/MOD DROP ; \n: \/ \/MOD NIP ; \n: UM* \n 0 SWAP \n 15 FOR \n DUP UM+ >R >R \n DUP UM+ \n R> + \n R> \n IF >R OVER UM+ \n R> + \n THEN \n NEXT \n ROT DROP ; \n: * UM* DROP ; \n: M* \n 2DUP XOR 0< >R \n ABS SWAP ABS UM* \n R> IF DNEGATE THEN ; \n: *\/MOD >R M* R> M\/MOD ; \n: *\/ *\/MOD SWAP DROP ; \n: 2* 2 * ; \n: 2\/ 2 \/ ; \n: MU\/MOD >R 0 R@ UM\/MOD R> SWAP >R UM\/MOD R> ; \n: D2* 2DUP D+ ; \n: DU2\/ 2 MU\/MOD ROT DROP ; \n: D2\/ DUP >R 1 AND DU2\/ R> 2\/ OR ; \n: ALIGNED DUP 0 2 UM\/MOD DROP DUP IF 2 SWAP - THEN + ; \n: parse \n tmp ! OVER >R DUP \n IF \n 1- tmp @ BL = \n IF \n FOR BL OVER C@ - 0< NOT \n WHILE 1+ \n NEXT R> DROP 0 DUP EXIT \n THEN R> \n THEN \n OVER SWAP \n FOR tmp @ OVER C@ - tmp @ BL = \n IF 0< THEN \n WHILE 1+ \n NEXT DUP >R \n ELSE R> DROP DUP 1+ >R \n THEN OVER - R> R> - EXIT \n THEN OVER R> - ; \n: PARSE >R TIB >IN @ + #TIB C@ >IN @ - R> parse >IN +! ; \n: CHAR BL PARSE DROP C@ ; \n: TX! 1 PUTC ; \n: EMIT 'EMIT @EXECUTE ; \n: TYPE FOR AFT DUP C@ EMIT 1+ THEN NEXT DROP ; \n: ?RX 0 GETC ; \n: ?KEY '?KEY @EXECUTE ; \n: KEY BEGIN ?KEY UNTIL ; \n: COUNT DUP 1+ SWAP C@ ; \n: CMOVE \n FOR \n AFT \n >R DUP C@ R@ C! 1+ R> 1+ \n THEN \n NEXT 2DROP ; \n: FILL \n SWAP \n FOR SWAP \n AFT 2DUP C! 1+ THEN \n NEXT 2DROP ; \n: -TRAILING \n FOR \n AFT \n BL OVER R@ + C@ < \n IF \n R> 1+ EXIT \n THEN \n THEN \n NEXT 0 ; \n: PACK$ \n DUP >R \n 2DUP C! 1+ 2DUP + 0 SWAP ! SWAP CMOVE \n R> ; \n: WORD PARSE HERE PACK$ ; \n: TOKEN BL PARSE 31 MIN NP @ OVER - 1- PACK$ ; \n: LINK> 3 CELLS - ; \n: CODE> 2 CELLS - ; \n: TYPE> 1 CELLS - ; \n: DATA> CELL+ ; \n: SAME? \n FOR AFT \n OVER R@ CELLS + @ \n OVER R@ CELLS + @ \n - ?DUP \n IF R> DROP EXIT THEN \n THEN \n NEXT 0 ; \n: find \n @ BEGIN DUP WHILE \n 2DUP C@ SWAP C@ = IF \n 2DUP 1+ SWAP COUNT ALIGNED CELL \/ >R SWAP R> \n SAME? 0= IF \n 2DROP SWAP DROP DUP CODE> @ SWAP -1 EXIT \n THEN 2DROP THEN \n LINK> @ REPEAT ; \n: ' TOKEN CONTEXT @ find IF DROP ELSE SWAP DROP 0 THEN ; \n: ! ! ; \n' TX! 'EMIT ! \n' ?RX '?KEY ! \n: ['] COMPILE ' ; IMMEDIATE \n: POSTPONE ' , ; IMMEDIATE \n: [CHAR] CHAR POSTPONE LITERAL ; IMMEDIATE \n: ( [CHAR] ) PARSE 2DROP ; IMMEDIATE \n: :NONAME HERE POSTPONE ] ; \n: OVERT LAST @ CURRENT @ ! ; \n: $,n \n DUP LAST ! CELL- \n DUP =WORDLIST \n SWAP ! \n CELL- DUP HERE \n SWAP ! \n CELL- DUP CURRENT @ @ \n SWAP ! \n CELL- NP ! ; \n: : TOKEN $,n POSTPONE ] ; \n: ; COMPILE EXIT POSTPONE [ OVERT ; IMMEDIATE \n: RECURSE LAST @ CURRENT @ ! ; IMMEDIATE \n: doVAR R> ; \n: CREATE TOKEN $,n COMPILE doVAR OVERT ; \n: DOES LAST @ CODE> @ R> SWAP ! ; \n: DOES> COMPILE DOES COMPILE R> ; IMMEDIATE \n: CONSTANT CREATE , DOES> @ ; \n: VARIABLE CREATE 0 , ; \n: 2LITERAL SWAP POSTPONE LITERAL \n POSTPONE LITERAL ; IMMEDIATE \n: 2CONSTANT CREATE , , DOES> 2@ ; \n: 2VARIABLE CREATE 2 CELLS ALLOT ; \n: SPACE BL EMIT ; \n: SPACES 0 MAX FOR SPACE NEXT ; \n: PAD HERE 80 + ; \n: DECIMAL 10 BASE ! ; \n: HEX 16 BASE ! ; \n: BINARY 2 BASE ! ; \n: OCTAL 8 BASE ! ; \nDECIMAL \n: CHAR- 1- ; \n: CHAR+ 1+ ; \n: CHARS ; \n: >CHAR 127 AND DUP 127 BL WITHIN IF DROP 95 THEN ; \n: DIGIT 9 OVER < 7 AND + [CHAR] 0 + ; \n: <# PAD HLD ! ; \n: HOLD HLD @ CHAR- DUP HLD ! C! ; \n: # 0 BASE @ UM\/MOD >R BASE @ UM\/MOD SWAP DIGIT HOLD R> ; \n: #S BEGIN # 2DUP OR 0= UNTIL ; \n: SIGN 0< IF [CHAR] - HOLD THEN ; \n: #> 2DROP HLD @ PAD OVER - ; \n: S.R OVER - SPACES TYPE ; \n: D.R >R DUP >R DABS <# #S R> SIGN #> R> S.R ; \n: U.R 0 SWAP D.R ; \n: .R >R S>D R> D.R ; \n: D. 0 D.R SPACE ; \n: U. 0 D. ; \n: . BASE @ 10 XOR IF U. EXIT THEN S>D D. ; \n: ? @ . ; \n: DU.R >R <# #S #> R> S.R ; \n: DU. DU.R SPACE ; \n: do$ R> R@ R> COUNT + ALIGNED >R SWAP >R ; \n: .\"| do$ COUNT TYPE ; \n: $,\" [CHAR] \" WORD COUNT + ALIGNED CP ! ; \n: .\" COMPILE .\"| $,\" ; IMMEDIATE \n: .( [CHAR] ) PARSE TYPE ; IMMEDIATE \n: $\"| do$ ; \n: $\" COMPILE $\"| $,\" ; IMMEDIATE \n: s\" [CHAR] \" PARSE HERE PACK$ ; \n: CR 10 EMIT ; \n: TAP OVER C! 1+ ; \n: KTAP \n 10 XOR \n IF \n BL TAP EXIT \n THEN \n NIP DUP ; \n: ACCEPT \n OVER + OVER \n BEGIN \n 2DUP XOR \n WHILE \n KEY \n DUP BL - 95 U< \n IF TAP ELSE KTAP THEN \n REPEAT DROP OVER - ; \n: EXPECT ACCEPT SPAN ! DROP ; \n: QUERY TIB 80 ACCEPT #TIB C! DROP 0 >IN ! ; \n: DIGIT? \n >R [CHAR] 0 - \n 9 OVER < \n IF 7 - DUP 10 < OR THEN \n DUP R> U< ; \n: \/STRING DUP >R - SWAP R> + SWAP ; \n: >NUMBER \n BEGIN DUP \n WHILE >R DUP >R C@ BASE @ DIGIT? \n WHILE SWAP BASE @ UM* DROP ROT \n BASE @ UM* D+ R> CHAR+ R> 1 - \n REPEAT DROP R> R> THEN ; \n: NUMBER? \n OVER C@ [CHAR] - = DUP >R IF 1 \/STRING THEN \n >R >R 0 DUP R> R> -1 DPL ! \n BEGIN >NUMBER DUP \n WHILE OVER C@ [CHAR] . XOR \n IF ROT DROP ROT R> 2DROP FALSE EXIT \n THEN 1 - DPL ! CHAR+ DPL @ \n REPEAT 2DROP R> IF DNEGATE THEN TRUE ; \n' NUMBER? 'NUMBER ! \n: $INTERPRET \n CONTEXT @ find \n IF DROP EXECUTE EXIT THEN \n COUNT 'NUMBER @EXECUTE IF \n DPL @ 0< IF DROP THEN EXIT THEN .\" ?\" TYPE ; \n: $COMPILE \n CONTEXT @ find \n IF CELL- @ =IMMED = \n IF EXECUTE ELSE , THEN EXIT \n THEN COUNT 'NUMBER @EXECUTE \n IF \n DPL @ 0< \n IF DROP POSTPONE LITERAL \n ELSE POSTPONE 2LITERAL \n THEN EXIT \n THEN .\" ?\" TYPE ; \n: eval STATE? IF $COMPILE ELSE $INTERPRET THEN ; \n' eval 'EVAL ! \n: EVAL \n BEGIN TOKEN DUP C@ WHILE \n 'EVAL @EXECUTE \n REPEAT DROP ; \n: OK CR .\" OK.\" SPACE ; \n' OK 'PROMPT ! \n: QUIT \n BEGIN 'PROMPT @EXECUTE QUERY \n EVAL AGAIN ; \n: BYE .\" Good Bye \" CR HALT ; \n' QUIT BOOT ! \n: SP@ SPP @ ; \n: DEPTH SP@ SP0 @ - CELL \/ ; \n: PICK CELLS SP@ SWAP - 2 CELLS - @ ; \n: .S CR DEPTH FOR AFT R@ PICK . THEN NEXT SPACE .\" \n @ SPACE REPEAT DROP CR ; \n\nVARIABLE FILE \n: OPEN F_OPEN FILE ! ; \n: CLOSE FILE @ F_CLOSE ; \n: FPUT FILE @ PUTC ; \n: FGET FILE @ GETC ; \n: FPUTS COUNT FOR AFT DUP C@ FPUT 1+ THEN NEXT DROP ; \n: FTELL FILE @ F_TELL ; \n: FSEEK FILE @ F_SEEK ; \n\n: SAVEVM $\" eforth.img\" $\" wb\" OPEN 0 \n 16384 FOR AFT DUP C@ FPUT 1+ THEN NEXT CLOSE DROP ; \n\nSAVEVM \n\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"61ce1fe360b7c3a57d0548d58641f418d1f206a2","subject":"Clarify usage","message":"Clarify usage\n","repos":"rm-hull\/byok3,rm-hull\/byok3","old_file":"core\/src\/main\/resources\/forth\/system.fth","new_file":"core\/src\/main\/resources\/forth\/system.fth","new_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\\n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n\n: COUNT dup 1+ swap c@ ;\n\n\\ Miscellaneous support words\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: <= ( a b -- f , true if A <= b ) > 0= ;\n: >= ( a b -- f , true if A >= b ) < 0= ;\n: NOT ( n -- !n , logical negation ) 0= ;\n: DNEGATE ( d -- -d , negate by doing 0-d )\n 0 swap -\n;\n: CELL+ ( n -- n+cell ) cell + ;\n: CELL- ( n -- n-cell ) cell - ;\n: CELL* ( n -- n*cell ) cells ;\n\n: CHAR+ ( n -- n+size_of_char ) 1+ ;\n\\ : CHARS ( n -- n*size_of_char, don't do anything ) ; immediate\n\n\\ useful stack manipulation words\n: -ROT ( a b c -- c a b ) rot rot ;\n: 3DUP ( a b c -- a b c a b c ) 2 pick 2 pick 2 pick ;\n\n\\ ------------------------------------------------------------------\n: ID. ( nfa -- ) count 31 and type ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: PAD ( -- addr ) here 128 + ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n\n: BETWEEN ( n lo hi -- flag , true if between lo & hi )\n >r over r> > >r\n < r> or 0=\n;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: ? ( -- ) @ . ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ ' (lit) , cell 1- , ] +\n [ ' (lit) , cell 1- invert , ] and ;\n\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n: ALLOT ( nbytes -- , allot space in dictionary ) dp +! align ;\n\n: C, ( c -- ) here c! 1 dp +! ;\n\\ : W, ( w -- ) dp @ even-up dup dp ! w! 2 dp +! ;\n\\ : , ( n -- , lay into dictionary ) align here ! cell allot ;\n\n: SEE ( -- )\n ' dup\n 16 + @ \\ offset in execution token for alloc size\n cells swap >body swap\n disassemble ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token )\n [compile] literal ( compile a call to literal )\n ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n: :NONAME ( -- xt , begin compilation of headerless secondary ) align here ] ;\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick )\n ?comp ' [compile] literal\n; immediate\n\n\n: (DOES>) ( xt -- , modify previous definition to execute code at xt )\n latest >body \\ get address of code for new word\n cell + \\ offset to second cell in create word\n ! \\ store execution token of DOES> code in new word\n;\n\n: DOES> ( -- , define execution code for CREATE word )\n 0 [compile] literal \\ dummy literal to hold xt\n here cell- \\ address of zero in literal\n compile (does>) \\ call (DOES>) from new creation word\n\t\t>r \\ move addrz to return stack so ; doesn't see stack garbage\n [compile] ; \\ terminate part of code before does>\n\t\tr>\n :noname ( addrz xt )\n swap ! \\ save execution token in literal\n; immediate\n\n0 1- constant -1\n0 2- constant -2\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 )\n swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 )\n dup cell+ @ swap @ ;\n\n: 2* ( n -- n*2 )\n 2 *\n;\n: 2\/ ( n -- n\/2 )\n 2 \/\n;\n\n\n\\ define some useful constants ------------------------------\n1 0= constant FALSE\n0 0= constant TRUE\n32 constant BL\n\n\\ Stack data structure ----------------------------------------\n\\ This is a general purpose stack utility used to implement necessary\n\\ stacks for the compiler or the user. Not real fast.\n\\ These stacks grow up which is different then normal.\n\\ cell 0 - stack pointer, offset from pfa of word\n\\ cell 1 - limit for range checking\n\\ cell 2 - first data location\n\n: :STACK ( #cells -- )\n CREATE 2 cells , ( offset of first data location )\n dup , ( limit for range checking, not currently used )\n cells cell+ allot ( allot an extra cell for safety )\n;\n\n: >STACK ( n stack -- , push onto stack, postincrement )\n dup @ 2dup cell+ swap ! ( -- n stack offset )\n + !\n;\n\n: STACK> ( stack -- n , pop , predecrement )\n dup @ cell- 2dup swap !\n + @\n;\n\n: STACK@ ( stack -- n , copy )\n dup @ cell- + @\n;\n\n: STACK.PICK ( index stack -- n , grab Nth from top of stack )\n dup @ cell- +\n swap cells - \\ offset for index\n @\n;\n: STACKP ( stack -- ptr , to next empty location on stack )\n\tdup @ +\n;\n\n: 0STACKP ( stack -- , clear stack)\n 8 swap !\n;\n\n32 :stack ustack\nustack 0stackp\n\n\\ Define JForth like words.\n: >US ustack >stack ;\n: US> ustack stack> ;\n: US@ ustack stack@ ;\n: 0USP ustack 0stackp ;\n\n\n\n\\ DO LOOP ------------------------------------------------\n\n3 constant do_flag\n4 constant leave_flag\n5 constant ?do_flag\n\n: DO ( -- , loop-back do_flag jump-from ?do_flag )\n ?comp\n compile (do)\n here >us do_flag >us ( for backward branch )\n; immediate\n\n: ?DO ( -- , loop-back do_flag jump-from ?do_flag , on user stack )\n ?comp\n ( leave address to set for forward branch )\n compile (?do)\n here 0 ,\n here >us do_flag >us ( for backward branch )\n >us ( for forward branch ) ?do_flag >us\n; immediate\n\n: LEAVE ( -- addr leave_flag )\n compile (leave)\n here 0 , >us\n leave_flag >us\n; immediate\n\n: LOOP-FORWARD ( -us- jump-from ?do_flag -- )\n BEGIN\n us@ leave_flag =\n us@ ?do_flag =\n OR\n WHILE\n us> leave_flag =\n IF\n us> here over - cell+ swap !\n ELSE\n us> dup\n here swap -\n cell+ swap !\n THEN\n REPEAT\n;\n\n: LOOP-BACK ( loop-addr do_flag -us- )\n us> do_flag ?pairs\n us> here - here\n !\n cell allot\n;\n\n: LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (loop)\n loop-forward loop-back\n; immediate\n\n\\ : DOTEST 5 0 do 333 . loop 888 . ;\n\\ : ?DOTEST0 0 0 ?do 333 . loop 888 . ;\n\\ : ?DOTEST1 5 0 ?do 333 . loop 888 . ;\n\n: +LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (+loop)\n loop-forward loop-back\n; immediate\n\n: UNLOOP ( loop-sys -r- )\n r> \\ save return pointer\n rdrop rdrop\n >r\n;\n\n\n: RECURSE ( ? -- ? , call the word currently being defined )\n latest compile,\n; immediate\n\n: SPACE bl emit ;\n: SPACES 512 min 0 max 0 ?DO space LOOP ;\n: 0SP depth 0 ?do drop loop ;\n\n\\ : >NEWLINE ( -- , CR if needed )\n\\ out @ 0>\n\\ IF cr\n\\ THEN\n\\ ;\n\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 ) swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 ) dup cell+ @ swap @ ;\n\n: DABS ( d -- |d| )\n dup 0<\n IF dnegate\n THEN\n;\n\n: S>D ( s -- d , extend signed single precision to double )\n dup 0<\n IF -1\n ELSE 0\n THEN\n;\n\n: D>S ( d -- s ) drop ;\n\n: PARSE-WORD ( \"name\" -- c-addr u ) bl parse ;\n: \/STRING ( addr len n -- addr' len' ) over min rot over + -rot - ;\n: PLACE ( addr len to -- , move string ) 3dup 1+ swap cmove c! drop ;\n\n: ASCII ( -- char, state smart )\n bl parse drop c@\n state @ 1 =\n IF [compile] literal\n ELSE\n THEN\n; immediate\n\n: CHAR ( -- char , interpret mode ) bl parse drop c@ ;\n: [CHAR] ( -- char , for compile mode )\n char [compile] literal\n; immediate\n\n: $TYPE ( $string -- ) count type ;\n: 'word ( -- addr ) here ;\n\n: EVEN ( addr -- addr' ) dup 1 and + ;\n\n: (C\") ( -- $addr ) r> dup count + aligned >r ;\n: (S\") ( -- c-addr cnt ) r> count 2dup + aligned >r ;\n: (.\") ( -- , type following string ) r> count 2dup + aligned >r type ;\n: \", ( addr len -- , place string into dict ) tuck 'word place 1+ allot align ;\n: ,\" ( -- ) [char] \" parse \", ;\n\n: .( ( --, type string delimited by parens )\n [char] ) parse type\n; immediate\n\n: .\" ( -- , type string )\n state @ 1 =\n IF compile (.\") ,\"\n ELSE [char] \" parse type\n THEN\n; immediate\n\n: .' ( -- , type string delimited by single quote )\n state @\n IF compile (.\") [char] ' parse \",\n ELSE [char] ' parse type\n THEN\n; immediate\n\n: C\" ( -- addr , return string address, ANSI )\n state @\n IF compile (c\") ,\"\n ELSE [char] \" parse pad place pad\n THEN\n; immediate\n\n: S\" ( -- , -- addr , return string address, ANSI )\n state @\n IF compile (s\") ,\"\n ELSE [char] \" parse pad place pad count\n THEN\n; immediate\n\n: \" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n: P\" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n\n\\ : \"\" ( -- addr )\n\\ state @\n\\ IF\n\\ compile (C\")\n\\ bl parse-word \",\n\\ ELSE\n\\ bl parse-word pad place pad\n\\ THEN\n\\ ; immediate\n\n: SLITERAL ( addr cnt -- , compile string )\n\tcompile (S\")\n\t\",\n; IMMEDIATE\n\n: $APPEND ( addr count $1 -- , append text to $1 )\n over >r\n dup >r\n count + ( -- a2 c2 end1 )\n swap cmove\n r> dup c@ ( a1 c1 )\n r> + ( -- a1 totalcount )\n swap c!\n;\n\n\\ ANSI word to replace [COMPILE] and COMPILE ----------------\n\\ : POSTPONE ( -- )\n\\\tbl word find\n\\\tdup 0=\n\\\tIF\n\\\t\t.\" Postpone could not find \" count type cr abort\n\\\tELSE\n\\\t\t0>\n\\\t\tIF compile, \\ immediate\n\\\t\tELSE (compile) \\ normal\n\\\t\tTHEN\n\\\tTHEN\n\\ ; immediate\n\n\\ -----------------------------------------------------------------\n\\ Auto Initialization\n: AUTO.INIT ( -- )\n\\ Kernel finds AUTO.INIT and executes it after loading dictionary.\n\\\t.\" Begin AUTO.INIT ------\" cr\n;\n: AUTO.TERM ( -- )\n\\ Kernel finds AUTO.TERM and executes it on bye.\n\\\t.\" End AUTO.TERM ------\" cr\n;\n\n\n: CLEARSTACK ( i*x -- )\n BEGIN depth\n WHILE drop\n REPEAT ;\n\nvariable pictured_output \\ hidden?\nvariable pictured_output_len \\ hidden?\n\n: <# ( -- ) pad pictured_output ! 0 pictured_output_len ! ;\n: #> ( -- addr n ) drop pictured_output @ pictured_output_len @ ;\n\n: HOLD ( c -- )\n pictured_output @ dup dup 1+ pictured_output_len @ cmove c!\n 1 pictured_output_len +!\n;\n\n\\ ------------------------ INPUT -------------------------------\n\n: SIGN ( n -- ) < 0 IF 45 hold THEN\n;\n\n: DIGIT ( n -- ascii )\n dup 10 < IF 48 ELSE 87 THEN + ;\n\n: # ( n -- n )\n base @ \/mod swap digit hold ;\n\n: #S ( n -- )\n BEGIN base @ \/mod dup\n WHILE swap digit hold\n REPEAT\n digit hold ;","old_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\\n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n\n: COUNT dup 1+ swap c@ ;\n\n\\ Miscellaneous support words\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: <= ( a b -- f , true if A <= b ) > 0= ;\n: >= ( a b -- f , true if A >= b ) < 0= ;\n: NOT ( n -- !n , logical negation ) 0= ;\n: DNEGATE ( d -- -d , negate by doing 0-d )\n 0 swap -\n;\n: CELL+ ( n -- n+cell ) cell + ;\n: CELL- ( n -- n-cell ) cell - ;\n: CELL* ( n -- n*cell ) cells ;\n\n: CHAR+ ( n -- n+size_of_char ) 1+ ;\n\\ : CHARS ( n -- n*size_of_char, don't do anything ) ; immediate\n\n\\ useful stack manipulation words\n: -ROT ( a b c -- c a b ) rot rot ;\n: 3DUP ( a b c -- a b c a b c ) 2 pick 2 pick 2 pick ;\n\n\\ ------------------------------------------------------------------\n: ID. ( nfa -- ) count 31 and type ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: PAD ( -- addr ) here 128 + ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n\n: BETWEEN ( n lo hi -- flag , true if between lo & hi )\n >r over r> > >r\n < r> or 0=\n;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: ? ( -- ) @ . ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ ' (lit) , cell 1- , ] +\n [ ' (lit) , cell 1- invert , ] and ;\n\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n: ALLOT ( nbytes -- , allot space in dictionary ) dp +! align ;\n\n: C, ( c -- ) here c! 1 dp +! ;\n\\ : W, ( w -- ) dp @ even-up dup dp ! w! 2 dp +! ;\n\\ : , ( n -- , lay into dictionary ) align here ! cell allot ;\n\n: SEE ( -- )\n ' dup\n 16 + @ \\ offset in execution token for alloc size\n cells swap >body swap\n disassemble ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token )\n [compile] literal ( compile a call to literal )\n ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n: :NONAME ( -- xt , begin compilation of headerless secondary ) align here ] ;\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick )\n ?comp ' [compile] literal\n; immediate\n\n\n: (DOES>) ( xt -- , modify previous definition to execute code at xt )\n latest >body \\ get address of code for new word\n cell + \\ offset to second cell in create word\n ! \\ store execution token of DOES> code in new word\n;\n\n: DOES> ( -- , define execution code for CREATE word )\n 0 [compile] literal \\ dummy literal to hold xt\n here cell- \\ address of zero in literal\n compile (does>) \\ call (DOES>) from new creation word\n\t\t>r \\ move addrz to return stack so ; doesn't see stack garbage\n [compile] ; \\ terminate part of code before does>\n\t\tr>\n :noname ( addrz xt )\n swap ! \\ save execution token in literal\n; immediate\n\n0 1- constant -1\n0 2- constant -2\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 )\n swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 )\n dup cell+ @ swap @ ;\n\n: 2* ( n -- n*2 )\n 2 *\n;\n: 2\/ ( n -- n\/2 )\n 2 \/\n;\n\n\n\\ define some useful constants ------------------------------\n1 0= constant FALSE\n0 0= constant TRUE\n32 constant BL\n\n\\ Stack data structure ----------------------------------------\n\\ This is a general purpose stack utility used to implement necessary\n\\ stacks for the compiler or the user. Not real fast.\n\\ These stacks grow up which is different then normal.\n\\ cell 0 - stack pointer, offset from pfa of word\n\\ cell 1 - limit for range checking\n\\ cell 2 - first data location\n\n: :STACK ( #cells -- )\n CREATE 2 cells , ( offset of first data location )\n dup , ( limit for range checking, not currently used )\n cells cell+ allot ( allot an extra cell for safety )\n;\n\n: >STACK ( n stack -- , push onto stack, postincrement )\n dup @ 2dup cell+ swap ! ( -- n stack offset )\n + !\n;\n\n: STACK> ( stack -- n , pop , predecrement )\n dup @ cell- 2dup swap !\n + @\n;\n\n: STACK@ ( stack -- n , copy )\n dup @ cell- + @\n;\n\n: STACK.PICK ( index stack -- n , grab Nth from top of stack )\n dup @ cell- +\n swap cells - \\ offset for index\n @\n;\n: STACKP ( stack -- ptr , to next empty location on stack )\n\tdup @ +\n;\n\n: 0STACKP ( stack -- , clear stack)\n 8 swap !\n;\n\n32 :stack ustack\nustack 0stackp\n\n\\ Define JForth like words.\n: >US ustack >stack ;\n: US> ustack stack> ;\n: US@ ustack stack@ ;\n: 0USP ustack 0stackp ;\n\n\n\n\\ DO LOOP ------------------------------------------------\n\n3 constant do_flag\n4 constant leave_flag\n5 constant ?do_flag\n\n: DO ( -- , loop-back do_flag jump-from ?do_flag )\n ?comp\n compile (do)\n here >us do_flag >us ( for backward branch )\n; immediate\n\n: ?DO ( -- , loop-back do_flag jump-from ?do_flag , on user stack )\n ?comp\n ( leave address to set for forward branch )\n compile (?do)\n here 0 ,\n here >us do_flag >us ( for backward branch )\n >us ( for forward branch ) ?do_flag >us\n; immediate\n\n: LEAVE ( -- addr leave_flag )\n compile (leave)\n here 0 , >us\n leave_flag >us\n; immediate\n\n: LOOP-FORWARD ( -us- jump-from ?do_flag -- )\n BEGIN\n us@ leave_flag =\n us@ ?do_flag =\n OR\n WHILE\n us> leave_flag =\n IF\n us> here over - cell+ swap !\n ELSE\n us> dup\n here swap -\n cell+ swap !\n THEN\n REPEAT\n;\n\n: LOOP-BACK ( loop-addr do_flag -us- )\n us> do_flag ?pairs\n us> here - here\n !\n cell allot\n;\n\n: LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (loop)\n loop-forward loop-back\n; immediate\n\n\\ : DOTEST 5 0 do 333 . loop 888 . ;\n\\ : ?DOTEST0 0 0 ?do 333 . loop 888 . ;\n\\ : ?DOTEST1 5 0 ?do 333 . loop 888 . ;\n\n: +LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (+loop)\n loop-forward loop-back\n; immediate\n\n: UNLOOP ( loop-sys -r- )\n r> \\ save return pointer\n rdrop rdrop\n >r\n;\n\n\n: RECURSE ( ? -- ? , call the word currently being defined )\n latest compile,\n; immediate\n\n: SPACE bl emit ;\n: SPACES 512 min 0 max 0 ?DO space LOOP ;\n: 0SP depth 0 ?do drop loop ;\n\n\\ : >NEWLINE ( -- , CR if needed )\n\\ out @ 0>\n\\ IF cr\n\\ THEN\n\\ ;\n\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 ) swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 ) dup cell+ @ swap @ ;\n\n: DABS ( d -- |d| )\n dup 0<\n IF dnegate\n THEN\n;\n\n: S>D ( s -- d , extend signed single precision to double )\n dup 0<\n IF -1\n ELSE 0\n THEN\n;\n\n: D>S ( d -- s ) drop ;\n\n: PARSE-WORD ( \"name\" -- c-addr u ) bl parse ;\n: \/STRING ( addr len n -- addr' len' ) over min rot over + -rot - ;\n: PLACE ( addr len to -- , move string ) 3dup 1+ swap cmove c! drop ;\n\n: ASCII ( -- char, state smart )\n bl parse drop c@\n state @ 1 =\n IF [compile] literal\n ELSE\n THEN\n; immediate\n\n: CHAR ( -- char , interpret mode ) bl parse drop c@ ;\n: [CHAR] ( -- char , for compile mode )\n char [compile] literal\n; immediate\n\n: $TYPE ( $string -- ) count type ;\n: 'word ( -- addr ) here ;\n\n: EVEN ( addr -- addr' ) dup 1 and + ;\n\n: (C\") ( -- $addr ) r> dup count + aligned >r ;\n: (S\") ( -- c-addr cnt ) r> count 2dup + aligned >r ;\n: (.\") ( -- , type following string ) r> count 2dup + aligned >r type ;\n: \", ( addr len -- , place string into dict ) tuck 'word place 1+ allot align ;\n: ,\" ( -- ) 34 parse \", ;\n\n: .( ( --, type string delimited by parens )\n 41 parse type\n; immediate\n\n: .\" ( -- , type string )\n state @ 1 =\n IF compile (.\") ,\"\n ELSE 34 parse type\n THEN\n; immediate\n\n: .' ( -- , type string delimited by single quote )\n state @\n IF compile (.\") [char] ' parse \",\n ELSE [char] ' parse type\n THEN\n; immediate\n\n: C\" ( -- addr , return string address, ANSI )\n state @\n IF compile (c\") ,\"\n ELSE [char] \" parse pad place pad\n THEN\n; immediate\n\n: S\" ( -- , -- addr , return string address, ANSI )\n state @\n IF compile (s\") ,\"\n ELSE [char] \" parse pad place pad count\n THEN\n; immediate\n\n: \" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n: P\" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n\n\\ : \"\" ( -- addr )\n\\ state @\n\\ IF\n\\ compile (C\")\n\\ bl parse-word \",\n\\ ELSE\n\\ bl parse-word pad place pad\n\\ THEN\n\\ ; immediate\n\n: SLITERAL ( addr cnt -- , compile string )\n\tcompile (S\")\n\t\",\n; IMMEDIATE\n\n: $APPEND ( addr count $1 -- , append text to $1 )\n over >r\n dup >r\n count + ( -- a2 c2 end1 )\n swap cmove\n r> dup c@ ( a1 c1 )\n r> + ( -- a1 totalcount )\n swap c!\n;\n\n\\ ANSI word to replace [COMPILE] and COMPILE ----------------\n\\ : POSTPONE ( -- )\n\\\tbl word find\n\\\tdup 0=\n\\\tIF\n\\\t\t.\" Postpone could not find \" count type cr abort\n\\\tELSE\n\\\t\t0>\n\\\t\tIF compile, \\ immediate\n\\\t\tELSE (compile) \\ normal\n\\\t\tTHEN\n\\\tTHEN\n\\ ; immediate\n\n\\ -----------------------------------------------------------------\n\\ Auto Initialization\n: AUTO.INIT ( -- )\n\\ Kernel finds AUTO.INIT and executes it after loading dictionary.\n\\\t.\" Begin AUTO.INIT ------\" cr\n;\n: AUTO.TERM ( -- )\n\\ Kernel finds AUTO.TERM and executes it on bye.\n\\\t.\" End AUTO.TERM ------\" cr\n;\n\n\n: CLEARSTACK ( i*x -- )\n BEGIN depth\n WHILE drop\n REPEAT ;\n\nvariable pictured_output \\ hidden?\nvariable pictured_output_len \\ hidden?\n\n: <# ( -- ) pad pictured_output ! 0 pictured_output_len ! ;\n: #> ( -- addr n ) drop pictured_output @ pictured_output_len @ ;\n\n: HOLD ( c -- )\n pictured_output @ dup dup 1+ pictured_output_len @ cmove c!\n 1 pictured_output_len +!\n;\n\n\\ ------------------------ INPUT -------------------------------\n\n: SIGN ( n -- ) < 0 IF 45 hold THEN\n;\n\n: DIGIT ( n -- ascii )\n dup 10 < IF 48 ELSE 87 THEN + ;\n\n: # ( n -- n )\n base @ \/mod swap digit hold ;\n\n: #S ( n -- )\n BEGIN base @ \/mod dup\n WHILE swap digit hold\n REPEAT\n digit hold ;","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"e5a5e7d8cfbfbcc0e6d55a324dc8cade8fc1f98f","subject":"?NOT-TWO-ADJACENT-1-BITS added","message":"?NOT-TWO-ADJACENT-1-BITS added\n","repos":"bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas","old_file":"KataDiversion.fth","new_file":"KataDiversion.fth","new_contents":"\\ KataDiversion in Forth\n\n\\ -- utils\n\n\\ empty the stack\n: EMPTY\n DEPTH 0 <> IF BEGIN\n DROP DEPTH 0 =\n UNTIL\n THEN ;\n\n\\ power\n: ** ( n1 n2 -- n1_pow_n2 ) 1 SWAP ?DUP IF 0 DO OVER * LOOP THEN NIP ;\n\n\\ compute the highest power of 2 below N.\n\\ e.g. : 31 -> 16, 4 -> 4\n: MAXPOW2 ( n -- log2_n ) DUP 1 < IF 1 ABORT\" Maxpow2 need a positive value.\"\n ELSE DUP 1 = IF 1\n ELSE\n 1 >R\n BEGIN ( n |R: i=1)\n DUP DUP I - 2 *\n ( n n 2*[n-i])\n R> 2 * >R ( \u2026 |R: i*2)\n > ( n n>2*[n-i] )\n UNTIL\n R> 2 \/\n THEN\n THEN NIP ;\n\n\\ -- kata\n\n\\ test if the given N has two adjacent 1 bits\n\\ e.g. : 11 -> 1011 -> -1\n\\ 9 -> 1001 -> 0\n: ?TWO-ADJACENT-1-BITS ( n -- bool )\n \\ the word uses the following algorithm :\n \\ (stack|return stack)\n \\ ( A N | X ) A: 0, X: N LOG2\n \\ loop: if N-X > 0 then A++ else A=0 ; X \/= 2\n \\ return -1 if A=2\n \\ if X=1 end loop and return 0\n 0 SWAP DUP DUP 0 <> IF\n MAXPOW2 >R\n BEGIN\n DUP I - 0 >= IF \n SWAP DUP 1 = IF 1+ SWAP\n ELSE 1+ SWAP I -\n THEN\n ELSE NIP 0 SWAP\n THEN\n OVER\n 2 =\n I 1 = OR\n R> 2 \/ >R\n UNTIL\n R> 2DROP\n 2 =\n THEN ;\n\n: ?NOT-TWO-ADJACENT-1-BITS ( n -- bool ) ?TWO-ADJACENT-1-BITS INVERT ;\n\n\\ return the maximum number which can be made with N (given number) bits\n: ?MAX-NB ( n -- m ) DUP 1 < IF DROP 0 ( 0 )\n ELSE \n DUP IF DUP 2 SWAP ** NIP ( 2**n )\n THEN\n THEN ;\n\n\n\\ return the number of numbers which can be made with N (given number) bits\n\\ or less, and which have not two adjacent 1 bits.\n\\ see http:\/\/www.codekata.com\/2007\/01\/code_kata_fifte.html\n: ?HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS ( n -- m ) ( TODO ) ;\n","old_contents":"\\ KataDiversion in Forth\n\n\\ -- utils\n\n\\ empty the stack\n: EMPTY\n DEPTH 0 <> IF BEGIN\n DROP DEPTH 0 =\n UNTIL\n THEN ;\n\n\\ power\n: ** ( n1 n2 -- n1_pow_n2 ) 1 SWAP ?DUP IF 0 DO OVER * LOOP THEN NIP ;\n\n\\ compute the highest power of 2 below N.\n\\ e.g. : 31 -> 16, 4 -> 4\n: MAXPOW2 ( n -- log2_n ) DUP 1 < IF 1 ABORT\" Maxpow2 need a positive value.\"\n ELSE DUP 1 = IF 1\n ELSE\n 1 >R\n BEGIN ( n |R: i=1)\n DUP DUP I - 2 *\n ( n n 2*[n-i])\n R> 2 * >R ( \u2026 |R: i*2)\n > ( n n>2*[n-i] )\n UNTIL\n R> 2 \/\n THEN\n THEN NIP ;\n\n\\ -- kata\n\n\\ test if the given N has two adjacent 1 bits\n\\ e.g. : 11 -> 1011 -> -1\n\\ 9 -> 1001 -> 0\n: ?TWO-ADJACENT-1-BITS ( n -- bool )\n \\ the word uses the following algorithm :\n \\ (stack|return stack)\n \\ ( A N | X ) A: 0, X: N LOG2\n \\ loop: if N-X > 0 then A++ else A=0 ; X \/= 2\n \\ return -1 if A=2\n \\ if X=1 end loop and return 0\n 0 SWAP DUP DUP 0 <> IF\n MAXPOW2 >R\n BEGIN\n DUP I - 0 >= IF \n SWAP DUP 1 = IF 1+ SWAP\n ELSE 1+ SWAP I -\n THEN\n ELSE NIP 0 SWAP\n THEN\n OVER\n 2 =\n I 1 = OR\n R> 2 \/ >R\n UNTIL\n R> 2DROP\n 2 =\n THEN ;\n\n\\ return the maximum number which can be made with N (given number) bits\n: ?MAX-NB ( n -- m ) DUP 1 < IF DROP 0 ( 0 )\n ELSE \n DUP IF DUP 2 SWAP ** NIP ( 2**n )\n THEN\n THEN ;\n\n\n\\ return the number of numbers which can be made with N (given number) bits\n\\ or less, and which have not two adjacent 1 bits.\n\\ see http:\/\/www.codekata.com\/2007\/01\/code_kata_fifte.html\n: ?HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS ( n -- m ) ( TODO ) ;\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"f8c5353ebaaaa2f7ea832947acda5de6a58ce802","subject":"State bug.","message":"State bug.","repos":"rbsexton\/gecko,rbsexton\/gecko,rbsexton\/gecko","old_file":"zero\/clock-umb\/forth\/Clock.fth","new_file":"zero\/clock-umb\/forth\/Clock.fth","new_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( -- )\n load-defaults \n icroot 0 over inter.rtcsem ! \\ Reset the free-running counters.\n 0 over inter.rtcdsem ! \\ Reset the free-running counters.\n\n begin \n \tdup inter.rtcsem @offex! ?dup if advancehms then\n \tdup inter.rtcdsem @offex! ?dup if advancedhms then\n [asm wfi asm]\n uiupdate if use-uivals else use-clockvals then \n key? until drop\n;\n \n\\ These two contain loops to ensure that we don't\n\\ drop any timer ticks on the floor.\n: ADVANCEHMS ( n -- ) 0 do hms advancetime loop ;\n: ADVANCEDHMS ( n -- ) 0 do dhms advancetime loop ;\n \n: LOAD-DEFAULTS ( -- )\n interp-init\n;\n\n\\ ----------------------------------------------------------\n\\ Define the structures before they get used.\n\\ ----------------------------------------------------------\nstruct ODN \\ On-Deck Needle \n\tint odn.s\n\tint odn.m\n\tint odn.h\nend-struct\n\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxsec \\ Max Value for secs+minutes\n\tint hms.maxhour \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_m \\ increment the minutes + hours\nend-struct\n\nstruct _interp_set\n\t4 cells field interp.a\n\t4 cells field interp.b\n\t4 cells field interp.c\nend-struct\n\n\\ ----------------------------------------------------------\n\\ Defaults get saved in the user data page.\n\\ ----------------------------------------------------------\n: NVRAMVALID? ( addr -- t\/f ) \n\\ *G See if there is valid data in the NVRAM.\n\\ ** It consists of 3 words. If any of them are \n\\ ** set to 0xffff:ffff, we go with the defaults.\n _USERDATA\n dup @ -1 <> \n over 4 + @ -1 <> and\n swap 8 + @ -1 <> and\n;\n\n: _NVRAMLOAD ( -- ) \n\\ *G Pull the needle maximums from flash.\n $C 0 do I ud@ needle_max I + ! 4 +loop \n; \n\n: NVRAM! ( -- )\n\\ *G Save the contents of the needle cal values.\n 0 UDPAGE_ERASE\n needle_max\n $C 0 do dup I + @ I ud! 4 +loop\n drop \n;\n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nidata\ncreate ODN_HMS odn allot \\ On-Deck, HMS\ncreate ODN_DHMS odn allot \\ On-Deck, DHMS\ncreate ODN_UI odn allot \\ On-Deck, Generated by the UI.\ncdata\n\nidata \\ Has to match an odn.\ncreate NEEDLE_MAX #850 , #850 , #850 ,\ncdata\n\n(( \n: interp-next drop 1 ; \n: interp-reset drop .\" Reset\" ; \n\t\n))\n\n: RANGECHECK ( max n -- n or zero ) 2dup <= if 2drop 0 else swap drop then ; \n\n: INTER-BUMP ( max old interp -- new )\n\\ *G Get the next value from the interpolator, and \n\\ ** reset the interpolator if it wraps around to zero.\n >R R@ interp-next \\ Get the max \n + rangecheck \n dup 0= if R> interp-reset else R> drop then \n ; \n\n: NFETCH ( odn off -- max old )\n\\ *G Combine the current value with the maximum.\n >R R@ \\ stash the offset.\n + @ \\ Calculate the offset address, get the current val.\n needle_max R> + @\n swap \n;\n\n: ++NEEDLE_S \\ Called every time.\n odn_hms 0 odn.s nfetch ( max old )\n\tinterp_hms interp.a inter-bump ( new )\n\todn_hms odn.s ! \n\t;\n\n: ++NEEDLE_M ( -- )\n\\ *G Every time we roll the seconds, bump the minutes and the hour\n\todn_hms 0 odn.m nfetch ( max old )\n\tinterp_hms interp.b inter-bump \n\todn_hms odn.m ! \n\n\todn_hms 0 odn.h nfetch ( max old )\n\tinterp_hms interp.c inter-bump \n\todn_hms odn.h ! \n\t;\n\n: ++NEEDLE_DS ; \\ Called every time.\n: ++NEEDLE_DM ; \\ Every time we roll the seconds.\n\n: _USE ( odn-addr -- ) \n dup odn.s w@ pwm0!\n dup odn.m w@ pwm1!\n odn.h w@ pwm2!\n ;\n\n: USE-CLOCKVALS odn_hms _use ; \n: USE-UIVALS odn_ui _use ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Quadrature\n\\ ----------------------------------------------------------\n\n: QUAD@ ( addr -- n ) \\ Fetch and zero\n @off [asm sxth tos, tos asm] ;\n \n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_ds , ' ++needle_dm , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n: ADVANCETIME ( struct-addr -- )\n dup hms.w_s @ execute \\ Invoke the official update word.\n 1 over hms.subsec +! \\ Increment\n dup hms.subsec @\n over hms.maxsubsec @ < if drop exit then \\ If less then max, we're done\n 0 over hms.subsec ! \\ Reset the subsecs \n\n 1 over hms.s +!\n dup hms.s @ over hms.maxsec @ < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n dup hms.w_m @ execute\n 1 over hms.m +!\n dup hms.m @ over hms.maxsec @ < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ over hms.maxhour @ < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ----------------------------------------------------------\n\\ The interpolator. \n\\ Implement bresenhams algorithm. All of this code already\n\\ exists in C, but we'll own the data structures. They contain\n\\ A total of 4 words - fixed, err, num, & denom\n\\ ----------------------------------------------------------\nudata \ncreate interp_hms _interp_set allot\ncreate interp_dhms _interp_set allot \ncreate adj_list #50 cells allot \\ 100 16-bit words. \ncdata\n\n#16 #60 * equ raw_sec\n#10 #100 * equ raw_dsec\n\n: INTERP-INIT ( -- )\n (interp_init) interp_hms\n 2dup interp.a needle_max @ raw_sec call3-- \n 2dup interp.b needle_max 4 + @ #60 call3-- \n interp.c needle_max 8 + @ #12 call3--\n\n (interp_init) interp_dhms\n 2dup interp.a needle_max @ raw_dsec call3-- \n 2dup interp.b needle_max 4 + @ #100 call3-- \n interp.c needle_max 8 + @ #10 call3--\n;\n\n\\ Call the reset fn.\n: INTERP-RESET ( interp_addr -- )\n (interp_reset) swap call1-- \n;\n\n: INTERP-NEXT ( addr -- n )\n (interp_next) swap call1--n\n;\n\n\n\\ ============================ UNTESTED =======================\n\\ VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n\n\\ ----------------------------------------------------------\n\\ User Interface\n\\ ----------------------------------------------------------\nvariable uistate\nvariable uicount \n\n_GPIO $64 + equ _BUTTONIO\n: BUTTONUP? ( -- t\/f ) _buttonio @ 1 and ; \n: BUTTONDOWN? ( -- t\/f ) buttonup? 1 xor ; \n\n\\ The wrapper for all of the UI stuff.\n\\ Returns true if the UI is active - ie, use the values generated by the UI.\n: UIUPDATE ( -- t\/f )\n StateHandlers uistate @ + @ execute \n; \n\n\\ -----------------------------------------------\n\\ State numbers. These are defined x4 so that\n\\ we can just use the state number as an index \n\\ into a table of words.\n\\ -----------------------------------------------\n0 4 * equ _s_init\n1 4 * equ _s_b1\n2 4 * equ _s_1sec\n3 4 * equ _s_seth\n4 4 * equ _s_pendset_m\n5 4 * equ _s_setmin\n6 4 * equ _s_pendcal0\n7 4 * equ _s_cal0\n8 4 * equ _s_pendcalh\n9 4 * equ _s_calh\n10 4 * equ _s_pendcalm\n11 4 * equ _s_calm\n12 4 * equ _s_pendcals\n13 4 * equ _s_cals\n\n\\ All of the state handlers.\n\\ Everybody needs to know the state of the button, so that must\n\\ get passed in, thus they all look like this:\n\\ state ( t\/f -- t\/f )\n: shInit false \n buttondown? if \n _s_b1 uistate !\n uicount off \\ Reset this.\n then\n ;\n\n\\ Waiting for a full second to go by.\n: shB1 false\n buttonup? if _s_init uistate ! exit then\n \\ The Button is down. \n uicount @ 16 > if\n _s_1sec uistate !\n else \n 1 uicount +!\n\tthen\n ;\n\n\\ We're in the 1 second state\n: sh1sec true \n buttonup? if _s_seth uistate ! true exit then\n uicount @ 48 > if\n _s_pendcal0 uistate !\n else \n 1 uicount +!\n\tthen \n;\n\n\\ -------------------------------------------------\n\\ Setting the time\n\\ -------------------------------------------------\n: shSetH true buttondown? if _s_pendset_m uistate ! exit then ;\n\n: shPendSetM true buttonup? if _s_setmin uistate ! then ;\n: shSetMin true buttondown? if _s_init uistate ! exit then ;\n\n\\ -------------------------------------------------\n\\ Calibration\n\\ -------------------------------------------------\n: shPendCal0 true buttonup? if _s_cal0 uistate ! then ;\n: shCal0 true buttondown? if _s_pendcalh uistate ! exit then ;\n\n: shPendCalH true buttonup? if _s_calh uistate ! then ; \n: shCalH true buttondown? if _s_pendcalm uistate ! exit then ; \n\n: shPendCalM true buttonup? if _s_calm uistate ! then ; \n: shCalM true buttondown? if _s_pendcals uistate ! exit then ; \n\n: shPendCalS true buttonup? if _s_calm uistate ! then ; \n: shCalS true buttondown? if _s_init uistate ! exit then ; \n\ncreate StateHandlers \n' shInit , \n' shB1 ,\n' sh1sec ,\n' shSetH ,\n' shPendSetM , ' shSetMin ,\n\n' shPendCal0 , ' shCal0 ,\n' shPendCalH , ' shCalH , \n' shPendCalM , ' shCalM , \n' shPendCalS , ' shCalS , \n\n","old_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( -- )\n load-defaults \n icroot 0 over inter.rtcsem ! \\ Reset the free-running counters.\n 0 over inter.rtcdsem ! \\ Reset the free-running counters.\n\n begin \n \tdup inter.rtcsem @offex! ?dup if advancehms then\n \tdup inter.rtcdsem @offex! ?dup if advancedhms then\n [asm wfi asm]\n uiupdate if use-uivals else use-clockvals then \n key? until drop\n;\n \n\\ These two contain loops to ensure that we don't\n\\ drop any timer ticks on the floor.\n: ADVANCEHMS ( n -- ) 0 do hms advancetime loop ;\n: ADVANCEDHMS ( n -- ) 0 do dhms advancetime loop ;\n \n: LOAD-DEFAULTS ( -- )\n interp-init\n;\n\n\\ ----------------------------------------------------------\n\\ Define the structures before they get used.\n\\ ----------------------------------------------------------\nstruct ODN \\ On-Deck Needle \n\tint odn.s\n\tint odn.m\n\tint odn.h\nend-struct\n\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxsec \\ Max Value for secs+minutes\n\tint hms.maxhour \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_m \\ increment the minutes + hours\nend-struct\n\nstruct _interp_set\n\t4 cells field interp.a\n\t4 cells field interp.b\n\t4 cells field interp.c\nend-struct\n\n\\ ----------------------------------------------------------\n\\ Defaults get saved in the user data page.\n\\ ----------------------------------------------------------\n: NVRAMVALID? ( addr -- t\/f ) \n\\ *G See if there is valid data in the NVRAM.\n\\ ** It consists of 3 words. If any of them are \n\\ ** set to 0xffff:ffff, we go with the defaults.\n _USERDATA\n dup @ -1 <> \n over 4 + @ -1 <> and\n swap 8 + @ -1 <> and\n;\n\n: _NVRAMLOAD ( -- ) \n\\ *G Pull the needle maximums from flash.\n $C 0 do I ud@ needle_max I + ! 4 +loop \n; \n\n: NVRAM! ( -- )\n\\ *G Save the contents of the needle cal values.\n 0 UDPAGE_ERASE\n needle_max\n $C 0 do dup I + @ I ud! 4 +loop\n drop \n;\n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nidata\ncreate ODN_HMS odn allot \\ On-Deck, HMS\ncreate ODN_DHMS odn allot \\ On-Deck, DHMS\ncreate ODN_UI odn allot \\ On-Deck, Generated by the UI.\ncdata\n\nidata \\ Has to match an odn.\ncreate NEEDLE_MAX #850 , #850 , #850 ,\ncdata\n\n(( \n: interp-next drop 1 ; \n: interp-reset drop .\" Reset\" ; \n\t\n))\n\n: RANGECHECK ( max n -- n or zero ) 2dup <= if 2drop 0 else swap drop then ; \n\n: INTER-BUMP ( max old interp -- new )\n\\ *G Get the next value from the interpolator, and \n\\ ** reset the interpolator if it wraps around to zero.\n >R R@ interp-next \\ Get the max \n + rangecheck \n dup 0= if R> interp-reset else R> drop then \n ; \n\n: NFETCH ( odn off -- max old )\n\\ *G Combine the current value with the maximum.\n >R R@ \\ stash the offset.\n + @ \\ Calculate the offset address, get the current val.\n needle_max R> + @\n swap \n;\n\n: ++NEEDLE_S \\ Called every time.\n odn_hms 0 odn.s nfetch ( max old )\n\tinterp_hms interp.a inter-bump ( new )\n\todn_hms odn.s ! \n\t;\n\n: ++NEEDLE_M ( -- )\n\\ *G Every time we roll the seconds, bump the minutes and the hour\n\todn_hms 0 odn.m nfetch ( max old )\n\tinterp_hms interp.b inter-bump \n\todn_hms odn.m ! \n\n\todn_hms 0 odn.h nfetch ( max old )\n\tinterp_hms interp.c inter-bump \n\todn_hms odn.h ! \n\t;\n\n: ++NEEDLE_DS ; \\ Called every time.\n: ++NEEDLE_DM ; \\ Every time we roll the seconds.\n\n: _USE ( odn-addr -- ) \n dup odn.s w@ pwm0!\n dup odn.m w@ pwm1!\n odn.h w@ pwm2!\n ;\n\n: USE-CLOCKVALS odn_hms _use ; \n: USE-UIVALS odn_ui _use ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Quadrature\n\\ ----------------------------------------------------------\n\n: QUAD@ ( addr -- n ) \\ Fetch and zero\n @off [asm sxth tos, tos asm] ;\n \n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_ds , ' ++needle_dm , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n: ADVANCETIME ( struct-addr -- )\n dup hms.w_s @ execute \\ Invoke the official update word.\n 1 over hms.subsec +! \\ Increment\n dup hms.subsec @\n over hms.maxsubsec @ < if drop exit then \\ If less then max, we're done\n 0 over hms.subsec ! \\ Reset the subsecs \n\n 1 over hms.s +!\n dup hms.s @ over hms.maxsec @ < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n dup hms.w_m @ execute\n 1 over hms.m +!\n dup hms.m @ over hms.maxsec @ < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ over hms.maxhour @ < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ----------------------------------------------------------\n\\ The interpolator. \n\\ Implement bresenhams algorithm. All of this code already\n\\ exists in C, but we'll own the data structures. They contain\n\\ A total of 4 words - fixed, err, num, & denom\n\\ ----------------------------------------------------------\nudata \ncreate interp_hms _interp_set allot\ncreate interp_dhms _interp_set allot \ncreate adj_list #50 cells allot \\ 100 16-bit words. \ncdata\n\n#16 #60 * equ raw_sec\n#10 #100 * equ raw_dsec\n\n: INTERP-INIT ( -- )\n (interp_init) interp_hms\n 2dup interp.a needle_max @ raw_sec call3-- \n 2dup interp.b needle_max 4 + @ #60 call3-- \n interp.c needle_max 8 + @ #12 call3--\n\n (interp_init) interp_dhms\n 2dup interp.a needle_max @ raw_dsec call3-- \n 2dup interp.b needle_max 4 + @ #100 call3-- \n interp.c needle_max 8 + @ #10 call3--\n;\n\n\\ Call the reset fn.\n: INTERP-RESET ( interp_addr -- )\n (interp_reset) swap call1-- \n;\n\n: INTERP-NEXT ( addr -- n )\n (interp_next) swap call1--n\n;\n\n\n\\ ============================ UNTESTED =======================\n\\ VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n\n\\ ----------------------------------------------------------\n\\ User Interface\n\\ ----------------------------------------------------------\nvariable uistate\nvariable uicount \n\n_GPIO $64 + equ _BUTTONIO\n: BUTTONUP? ( -- t\/f ) _buttonio @ 1 and ; \n: BUTTONDOWN? ( -- t\/f ) buttonup? 1 xor ; \n\n\\ The wrapper for all of the UI stuff.\n\\ Returns true if the UI is active - ie, use the values generated by the UI.\n: UIUPDATE ( -- t\/f )\n StateHandlers uistate @ + @ execute \n; \n\n\\ -----------------------------------------------\n\\ State numbers. These are defined x4 so that\n\\ we can just use the state number as an index \n\\ into a table of words.\n\\ -----------------------------------------------\n0 4 * equ _s_init\n1 4 * equ _s_b1\n2 4 * equ _s_1sec\n3 4 * equ _s_seth\n4 4 * equ _s_pendset_m\n5 4 * equ _s_setmin\n6 4 * equ _s_pendcal0\n7 4 * equ _s_cal0\n8 4 * equ _s_pendcalh\n9 4 * equ _s_calh\n10 4 * equ _s_pendcalm\n11 4 * equ _s_calm\n12 4 * equ _s_pendcals\n13 4 * equ _s_cals\n\n\\ All of the state handlers.\n\\ Everybody needs to know the state of the button, so that must\n\\ get passed in, thus they all look like this:\n\\ state ( t\/f -- t\/f )\n: shInit false \n buttondown? if \n _s_b1 uistate !\n uicount off \\ Reset this.\n then\n ;\n\n\\ Waiting for a full second to go by.\n: shB1 false\n buttonup? if _s_init uistate ! exit then\n \\ The Button is down. \n uicount @ 16 > if\n _s_1sec uistate !\n else \n 1 uicount +!\n\tthen\n ;\n\n\\ We're in the 1 second state\n: sh1sec true \n buttonup? if _s_seth uistate ! true exit then\n uicount @ 48 > if\n _s_pendcal0 uistate !\n else \n 1 uicount +!\n\tthen \n;\n\n\\ -------------------------------------------------\n\\ Setting the time\n\\ -------------------------------------------------\n: shSetH true buttondown? if _s_pendset_m uistate ! exit then ;\n\n: shPendSetM true buttonup? if _s_setmin uistate ! then ;\n: shSetMin true buttondown? if _s_pendset_m uistate ! exit then ;\n\n\\ -------------------------------------------------\n\\ Calibration\n\\ -------------------------------------------------\n: shPendCal0 true buttonup? if _s_cal0 uistate ! then ;\n: shCal0 true buttondown? if _s_pendcalh uistate ! exit then ;\n\n: shPendCalH true buttonup? if _s_calh uistate ! then ; \n: shCalH true buttondown? if _s_pendcalm uistate ! exit then ; \n\n: shPendCalM true buttonup? if _s_calm uistate ! then ; \n: shCalM true buttondown? if _s_pendcals uistate ! exit then ; \n\n: shPendCalS true buttonup? if _s_calm uistate ! then ; \n: shCalS true buttondown? if _s_init uistate ! exit then ; \n\ncreate StateHandlers \n' shInit , \n' shB1 ,\n' sh1sec ,\n' shSetH ,\n' shPendSetM , ' shSetMin ,\n\n' shPendCal0 , ' shCal0 ,\n' shPendCalH , ' shCalH , \n' shPendCalM , ' shCalM , \n' shPendCalS , ' shCalS , \n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"51acac5dcce5d1e25c18480efe96c54e02b7d400","subject":"Added numeric output primitives, <# and friends","message":"Added numeric output primitives, <# and friends\n","repos":"hth313\/hthforth","old_file":"src\/lib\/core.fth","new_file":"src\/lib\/core.fth","new_contents":"( block 1 -- Main load block )\n\nVARIABLE BLK\n: FH BLK @ + ; \\ relative block\n: LOAD BLK @ SWAP DUP BLK ! (LOAD) BLK ! ;\n\n30 LOAD\n( shadow 1 )\n( block 2 )\n( shadow 2 )\n( block 3 )\n( shadow 3 )\n\n( block 10 )\n( shadow 10 )\n( block 11 )\n( shadow 11 )\n( block 12 )\n( shadow 12 )\n\n( block 30 CORE words )\n\n1 FH 7 FH THRU\n\n( shadow 30 )\n( block 31 stack primitives )\n\n: ROT >R SWAP R> SWAP ;\n: ?DUP DUP IF DUP THEN ;\n\n( Not part of CORE, disabled at the moment )\n\\ : -ROT SWAP >R SWAP R> ; \\ or ROT ROT\n\\ : NIP ( n1 n2 -- n2 ) SWAP DROP ;\n\\ : TUCK ( n1 n2 -- n2 n1 n2 ) SWAP OVER ;\n\n: 2DROP DROP DROP ;\n: 2DUP OVER OVER ;\n: 2SWAP ROT >R ROT R> ;\n: 2OVER >R >R 2DUP R> R> 2SWAP ;\n( shadow 31 )\n( block 32 comparisons )\n\n-1 CONSTANT TRUE 0 CONSTANT FALSE\n\n: = ( n n -- f) XOR 0= ;\n: < ( n n -- f ) - 0< ;\n: > ( n n -- f ) SWAP < ;\n\n: MAX ( n n -- n ) 2DUP < IF SWAP THEN DROP ;\n: MIN ( n n -- n ) 2DUP > IF SWAP THEN DROP ;\n\n: WITHIN ( u ul uh -- f ) OVER - >R - R> U< ;\n( shadow 32 )\n( block 33 ALU )\n\n: 1+ 1 + ;\n: 1- 1 - ;\n: INVERT TRUE XOR ;\n: NEGATE INVERT 1+ ;\n: DNEGATE INVERT SWAP NEGATE SWAP OVER 0= - ;\n: S>D ( n -- d ) DUP 0< ; \\ sign extend\n: ABS S>D IF NEGATE THEN ;\n: DABS DUP 0< IF DNEGATE THEN ;\n\n: +- 0< IF NEGATE THEN ;\n: D+- 0< IF DNEGATE THEN ;\n\n( shadow 33 )\n( block 34 variables )\n\nVARIABLE BASE\n: DECIMAL 10 BASE ! ; : HEX 16 BASE ! ;\n\nVARIABLE DP\n( shadow 34 )\n( block 35 math )\n\n: SM\/REM ( d n -- r q ) \\ symmetric\n OVER >R >R DABS R@ ABS UM\/MOD\n R> R@ XOR 0< IF NEGATE THEN\n R> 0< IF >R NEGATE R> THEN ;\n\n: FM\/MOD ( d n -- r q ) \\ floored\n DUP 0< DUP >R IF NEGATE >R DNEGATE R> THEN\n >R DUP 0< IF R@ + THEN\n R> UM\/MOD R> IF >R NEGATE R> THEN ;\n\n: \/MOD OVER 0< SWAP FM\/MOD ;\n: MOD \/MOD DROP ;\n: \/ \/MOD SWAP DROP ;\n\n( shadow 35 )\n( block 36 math continued )\n\n: * UM* DROP ;\n: M* 2DUP XOR R> ABS SWAP ABS UM* R> D+- ;\n: *\/MOD >R M* R> FM\/MOD ;\n: *\/ *\/MOD SWAP DROP ;\n\n: 2* DUP + ;\n\\ 2\/ which is right shift is native\n\n: LSHIFT ( x1 u -- x2 )\n BEGIN DUP WHILE SWAP 2* SWAP 1- REPEAT DROP ;\n\n: RSHIFT ( x1 u -- x2 )\n BEGIN DUP WHILE SWAP 2\/ SWAP 1- REPEAT DROP ;\n ( shadow 36 )\n( block 37 numeric output primitives )\n\nVARIABLE HLD\n: HERE ( -- addr ) DP @ ;\n: PAD ( -- c-addr ) HERE 64 CHARS + ;\n\n: <# ( -- ) PAD HLD ! ;\n: #> ( xd -- c-addr u ) 2DROP HLD @ PAD OVER - ;\n: HOLD ( c -- ) HLD @ -1 CHARS - DUP HLD ! C! ;\n: DIGIT ( u -- c ) 9 OVER < 7 AND + 30 + ;\n: # ( ud1 -- ud2 )\n 0 BASE @ UM\/MOD >R BASE @ UM\/MOD SWAP DIGIT HOLD R> ;\n: #S ( ud1 -- ud2 ) BEGIN # 2DUP OR 0= UNTIL ;\n: SIGN ( n -- ) 0< IF 45 ( - ) HOLD THEN ;\n\n( shadow 37 )\n( block 38 )\n( shadow 38 )\n( block 39 )\n( shadow 39 )\n( block 40 compiler )\n\n: VARIABLE CREATE 1 CELLS ALLOT ;\n\nVARIABLE STATE ( compilation state variable )\n0 STATE ! ( interpreting by default )\n: [ FALSE STATE ! ;\n: ] TRUE STATE ! ;\n\n( Colon definitions )\n: : CREATE ] ;\n: ; POSTPONE EXIT SMUDGE [ ; IMMEDIATE\n\n( shadow 40 )\n( block 41 )\n( shadow 41 )\n( block 42 interpreter )\n\nCREATE _INPUT-BUFFER 80 CHARS ALLOT ( may do this internally? )\n\n: EVALUATE >IN @ >R 0 >IN ! SOURCE >R >R #IN 2! _INTERPRET\n R> R> #IN 2! R> >IN ! ;\n\n: QUIT _RESET-RSTACK\n BEGIN\n BEGIN\n\t _READ-LINE 0 >IN ! _INPUT-BUFFER 0 EVALUATE CR\n\t STATE @\n UNTIL .\" ok \" ( exhausted input in interpretation mode )\n AGAIN ;\n( shadow 42 )\n","old_contents":"( block 1 -- Main load block )\n\nVARIABLE BLK\n: FH BLK @ + ; \\ relative block\n: LOAD BLK @ SWAP DUP BLK ! (LOAD) BLK ! ;\n\n30 LOAD\n( shadow 1 )\n( block 2 )\n( shadow 2 )\n( block 3 )\n( shadow 3 )\n\n( block 10 )\n( shadow 10 )\n( block 11 )\n( shadow 11 )\n( block 12 )\n( shadow 12 )\n\n( block 30 CORE words )\n\n1 FH 6 FH THRU\n\n( shadow 30 )\n( block 31 stack primitives )\n\n: ROT >R SWAP R> SWAP ;\n: ?DUP DUP IF DUP THEN ;\n\n( Not part of CORE, disabled at the moment )\n\\ : -ROT SWAP >R SWAP R> ; \\ or ROT ROT\n\\ : NIP ( n1 n2 -- n2 ) SWAP DROP ;\n\\ : TUCK ( n1 n2 -- n2 n1 n2 ) SWAP OVER ;\n\n: 2DROP DROP DROP ;\n: 2DUP OVER OVER ;\n: 2SWAP ROT >R ROT R> ;\n: 2OVER >R >R 2DUP R> R> 2SWAP ;\n( shadow 31 )\n( block 32 comparisons )\n\n-1 CONSTANT TRUE 0 CONSTANT FALSE\n\n: = ( n n -- f) XOR 0= ;\n: < ( n n -- f ) - 0< ;\n: > ( n n -- f ) SWAP < ;\n\n: MAX ( n n -- n ) 2DUP < IF SWAP THEN DROP ;\n: MIN ( n n -- n ) 2DUP > IF SWAP THEN DROP ;\n\n: WITHIN ( u ul uh -- f ) OVER - >R - R> U< ;\n( shadow 32 )\n( block 33 ALU )\n\n: 1+ 1 + ;\n: 1- 1 - ;\n: INVERT TRUE XOR ;\n: NEGATE INVERT 1+ ;\n: DNEGATE INVERT SWAP NEGATE SWAP OVER 0= - ;\n: S>D ( n -- d ) DUP 0< ; \\ sign extend\n: ABS S>D IF NEGATE THEN ;\n: DABS DUP 0< IF DNEGATE THEN ;\n\n: +- 0< IF NEGATE THEN ;\n: D+- 0< IF DNEGATE THEN ;\n\n( shadow 33 )\n( block 34 variables )\n\nVARIABLE BASE\n: DECIMAL 10 BASE ! ; : HEX 16 BASE ! ;\n( shadow 34 )\n( block 35 math )\n\n: SM\/REM ( d n -- r q ) \\ symmetric\n OVER >R >R DABS R@ ABS UM\/MOD\n R> R@ XOR 0< IF NEGATE THEN\n R> 0< IF >R NEGATE R> THEN ;\n\n: FM\/MOD ( d n -- r q ) \\ floored\n DUP 0< DUP >R IF NEGATE >R DNEGATE R> THEN\n >R DUP 0< IF R@ + THEN\n R> UM\/MOD R> IF >R NEGATE R> THEN ;\n\n: \/MOD OVER 0< SWAP FM\/MOD ;\n: MOD \/MOD DROP ;\n: \/ \/MOD SWAP DROP ;\n\n( shadow 35 )\n( block 36 math continued )\n\n: * UM* DROP ;\n: M* 2DUP XOR R> ABS SWAP ABS UM* R> D+- ;\n: *\/MOD >R M* R> FM\/MOD ;\n: *\/ *\/MOD SWAP DROP ;\n\n: 2* DUP + ;\n\\ 2\/ which is right shift is native\n\n: LSHIFT ( x1 u -- x2 )\n BEGIN DUP WHILE SWAP 2* SWAP 1- REPEAT DROP ;\n\n: RSHIFT ( x1 u -- x2 )\n BEGIN DUP WHILE SWAP 2\/ SWAP 1- REPEAT DROP ;\n ( shadow 36 )\n( block 37 )\n( shadow 37 )\n( block 38 )\n( shadow 38 )\n( block 39 )\n( shadow 39 )\n( block 40 compiler )\n\n: VARIABLE CREATE 1 CELLS ALLOT ;\n\nVARIABLE STATE ( compilation state variable )\n0 STATE ! ( interpreting by default )\n: [ FALSE STATE ! ;\n: ] TRUE STATE ! ;\n\n( Colon definitions )\n: : CREATE ] ;\n: ; POSTPONE EXIT SMUDGE [ ; IMMEDIATE\n\n( shadow 40 )\n( block 41 )\n( shadow 41 )\n( block 42 interpreter )\n\nCREATE _INPUT-BUFFER 80 CHARS ALLOT ( may do this internally? )\n\n: EVALUATE >IN @ >R 0 >IN ! SOURCE >R >R #IN 2! _INTERPRET\n R> R> #IN 2! R> >IN ! ;\n\n: QUIT _RESET-RSTACK\n BEGIN\n BEGIN\n\t _READ-LINE 0 >IN ! _INPUT-BUFFER 0 EVALUATE CR\n\t STATE @\n UNTIL .\" ok \" ( exhausted input in interpretation mode )\n AGAIN ;\n( shadow 42 )\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"b6da7c888654925cd0d25caefb34f02e64108b4c","subject":"Fix up the conditional compilation code.","message":"Fix up the conditional compilation code.","repos":"rbsexton\/sockpuppet,rbsexton\/sockpuppet","old_file":"forth\/serCM3_SAPI-level1.fth","new_file":"forth\/serCM3_SAPI-level1.fth","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"bsd-2-clause","lang":"Forth"} {"commit":"16c0b6318593072ca409c2f311642508e6702d41","subject":"More demos!","message":"More demos!","repos":"rbsexton\/gecko,rbsexton\/gecko,rbsexton\/gecko","old_file":"tiny\/basic\/forth\/startup.fth","new_file":"tiny\/basic\/forth\/startup.fth","new_contents":"(( App Startup ))\n\n0 value JT \\ The Jumptable\n\n\\ -------------------------------------------\n\\ The word that sets everything up.\n\\ This runs before the intro banner, after\n\\ Init-multi.\n\\ -------------------------------------------\n: StartApp\n\thex\n\tinit-dp @ dp ! \\ Set the dictionary pointer so that we can function.\n\t\\ I have no idea why I am doing this instead of the compilation system.\n\n\t1 getruntimelinks to jt\n\t.\" StartApp!\" \n\n\t4 [ SCSSCR _SCS + ] literal ! \\ Set deepsleep\n\t\t\t\n;\n\n\\ ------------------------------------------\n\\ Application code\n\\ ------------------------------------------\nstruct tod\n 1 field h\n 1 field m\n 1 field s\nend-struct\n \nudata\ncreate hms tod allot\ncdata\n\n: +CAP ( n max -- n ) >R 1 + dup r> = if drop 0 then ; \n\n: ADVANCE ( tod -- )\n dup s c@ #60 +cap 2dup swap s c! \\ Advance the seconds. base n -- \n if drop exit then\n \n dup m c@ #60 +cap 2dup swap m c! \\ advance minutes\n if drop exit then\n\n dup h c@ #24 +cap 2dup swap h c! \\ advance minutes\n\n 2drop \n;\n\n\\ ----------------------------------------------\n\\ Tools for writing to the LCD\n\\ ----------------------------------------------\n: LCD#! ( n -- ) jt LCD_# @ swap call1-- ;\nvariable thecount\n\n: wakestart 1 $10 wakereq drop ; \\ Request a wake \n: wakestop 1 0 wakereq drop ; \\ No more, please. \n\n: COUNT-WORD\n wakestart\n begin\n pause\n thecount dup @ 1+ dup lcd#! swap ! \n stop \n again\n;\n\n: COUNT-WORDd\n begin\n pause self msg? if get-message drop \\ We don't care who sent it.\n case \n 0 of wakestop endof\n 1 of wakestart endof\n endcase\n then\n\n thecount dup @ 1+ dup lcd#! swap ! \n stop \n again\n;\n\n: interp-next ( addr -- ) \\ A fixed version. Returns amount to step\n dup @ \\ err\n #103 - dup 1 > if swap ! #13 exit then\n \\ Otherwise, we need to adjust\n #125 + swap ! #14 \n;\n\nvariable err \n\n: COUNT-DT\n begin \n 0 err interp-next wakereq drop \\ Don't keep the return code. \n pause\n thecount dup @ 1+ dup lcd#! swap ! \n again\n;\n\n((\ntask foo \n' count-word foo initiate\n\n\n\n\n))\n\n \n\n\n","old_contents":"(( App Startup ))\n\n0 value JT \\ The Jumptable\n\n\\ -------------------------------------------\n\\ The word that sets everything up.\n\\ This runs before the intro banner, after\n\\ Init-multi.\n\\ -------------------------------------------\n: StartApp\n\thex\n\tinit-dp @ dp ! \\ Set the dictionary pointer so that we can function.\n\t\\ I have no idea why I am doing this instead of the compilation system.\n\n\t1 getruntimelinks to jt\n\t.\" StartApp!\" \n\n\t4 [ SCSSCR _SCS + ] literal ! \\ Set deepsleep\n\t\t\t\n;\n\n\\ ------------------------------------------\n\\ Application code\n\\ ------------------------------------------\nstruct tod\n 1 field h\n 1 field m\n 1 field s\nend-struct\n \nudata\ncreate hms tod allot\ncdata\n\n: +CAP ( n max -- n ) >R 1 + dup r> = if drop 0 then ; \n\n: ADVANCE ( tod -- )\n dup s c@ #60 +cap 2dup swap s c! \\ Advance the seconds. base n -- \n if drop exit then\n \n dup m c@ #60 +cap 2dup swap m c! \\ advance minutes\n if drop exit then\n\n dup h c@ #24 +cap 2dup swap h c! \\ advance minutes\n\n 2drop \n;\n\n\\ ----------------------------------------------\n\\ Tools for writing to the LCD\n\\ ----------------------------------------------\n: LCD#! ( n -- ) jt LCD_# @ swap call1-- ;\nvariable thecount\n\n: wakestart 1 $10 wakereq ; \\ Request a wake \n: wakestop 1 0 wakereq ; \\ No more, please. \n\n: COUNT-WORD\n wakestart\n begin\n pause\n thecount dup @ 1+ dup lcd#! swap ! \n stop \n again\n;\n\n: COUNT-WORDd\n begin\n pause self msg? if get-message drop \\ We don't care who sent it.\n case \n 0 of wakestop endof\n 1 of wakestart endof\n endcase\n then\n\n thecount dup @ 1+ dup lcd#! swap ! \n stop \n again\n;\n\n\n((\ntask foo \n' count-word foo initiate\n))\n\n \n\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"c62f0d9fd963916410f4ee5f0da64fe313601e90","subject":"Added Lowest Common Multiple, added FOR...NEXT","message":"Added Lowest Common Multiple, added FOR...NEXT\n\nAdded FOR...NEXT loops, still in testing, as well as a Lowest Common Multiple\nfunction.\n","repos":"howerj\/libforth","old_file":"forth.fth","new_file":"forth.fth","new_contents":"#!.\/forth\n( Welcome to libforth, A dialect of Forth. Like all versions\nof Forth this version is a little idiosyncratic, but how\nthe interpreter works is documented here and in various\nother files.\n\nThis file contains most of the start up code, some basic\nstart up code is executed in the C file as well which makes\nprogramming at least bearable. Most of Forth is programmed in\nitself, which may seem odd if your back ground in programming\ncomes from more traditional language [such as C], although\nless so if you know already know lisp.\n\nFor more information about this interpreter and Forth see:\n\nhttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\nAnd within this code base:\n\n\treadme.md : for a manual for this interpreter\n\tlibforth.h : for information about the C API\n\tlibforth.c : for the interpreter itself\n\tunit.c : unit tests for libforth.c\n\tunit.fth : unit tests against this file\n\tmain.c : an example interpreter\n\nThe interpreter and this code originally descend from a Forth\ninterpreter written in 1992 for the International obfuscated\nC Coding Competition.\n\nSee:\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\nThe manual for the interpreter should be read first before\nlooking into this code. It is important to understand the\nexecution model of Forth, especially the differences between\ncommand and compile mode, and how immediate and compiling\nwords work.\n\nEach of these sections is clearly labeled and they are\ngenerally in dependency order.\n\nUnfortunately the code in this file is not as portable as it\ncould be, it makes assumptions about the size of cells provided\nby the virtual machine, which will take time to rectify. Some\nof the constructs are subtly different from the DPANs Forth\nspecification, which is usually noted. Eventually this should\nalso be fixed.\n\nA little note on how code is formatted, a line of Forth code\nshould not exceed 64 characters. All words stack effect, how\nmany variables on the stack it accepts and returns, should\nbe commented with the following types:\n\n\tchar \/ c A character\n\tc-addr An address of a character\n\taddr An address of a cell\n\tr-addr A real address*\n\tu A unsigned number\n\tn A signed number\n\tc\" xxx\" The word parses a word\n\tc\" x\" The word parses a single character\n\txt An execution token\n\tbool A boolean value\n\tior A file error return status [0 on no error]\n\tfileid A file identifier.\n\tCODE A number from a words code field\n\tPWD A number from a words previous word field\n\t* A real address is one outside the range of the\n\tForth address space.\n\nIn the comments Forth words should be written in uppercase. As\nthis is supposed to be a tutorial about Forth and describe the\ninternals of a Forth interpreter, be as verbose as possible.\n\nThe code in this file will need to be modified to abide by\nthese standards, but new code should follow it from the start.\n\nDoxygen style tags for documenting bugs, todos and warnings\nshould be used within comments. This makes finding code that\nneeds working on much easier.)\n\n( ==================== Basic Word Set ======================== )\n\n( We'll begin by defining very simple words we can use later,\nthese a very basic words, that perform simple tasks, they\nwill not require much explanation.\n\nEven though the words are simple, their stack comment and\na description for them will still be included so external\ntools can process and automatically extract the document\nstring for a given work. )\n\n: postpone ( c\" xxx\" -- : postpone execution of a word )\n\timmediate find , ;\n\n: constant\n\t:: ( compile word header )\n\there 1 - h ! ( decrement dictionary pointer )\n\t( change instruction to CONST )\n\there @ instruction-mask invert and doconst or here !\n\there 1 + h ! ( increment dictionary pointer )\n\t, ( write in value )\n\tpostpone [ ; ( back into command mode )\n\n( These constants are defined as a space saving measure,\nnumbers in a definition usually take up two cells, one\nfor the instruction to push the next cell and the cell\nitself, for the most frequently used numbers it is worth\ndefining them as constants, it is just as fast but saves\na lot of space )\n-1 constant -1\n 0 constant 0\n 1 constant 1\n 2 constant 2\n 3 constant 3\n\n0 constant false\n1 constant true ( @warning not standards compliant )\n\n( Confusingly the word CR prints a line feed )\n10 constant lf ( line feed )\nlf constant nl ( new line - line feed on Unixen )\n13 constant cret ( carriage return )\n\n-1 -1 1 rshift invert and constant min-signed-integer\nmin-signed-integer invert constant max-signed-integer\n\n( The following version number is used to mark whether core\nfiles will be compatible with each other, The version number\ngets stored in the core file and is used by the loader to\ndetermine compatibility )\n4 constant version ( version number for the interpreter )\n\n( This constant defines the number of bits in an address )\ncell size 8 * * constant address-unit-bits \n\n( Bit corresponding to the sign in a number )\n-1 -1 1 rshift and invert constant sign-bit \n\n( @todo test by how much, if at all, making words like 1+,\n1-, <>, and other simple words, part of the interpreter would\nspeed things up )\n\n: 1+ ( x -- x : increment a number )\n\t1 + ;\n\n: 1- ( x -- x : decrement a number )\n\t1 - ;\n\n: chars ( c-addr -- addr : convert a c-addr to an addr )\n\tsize \/ ;\n\n: chars> ( addr -- c-addr: convert an addr to a c-addr )\n\tsize * ;\n\n: tab ( -- : print a tab character )\n\t9 emit ;\n\n: 0= ( n -- bool : is 'n' equal to zero? )\n\t0 = ;\n\n: not ( n -- bool : is 'n' true? )\n\t0= ;\n\n: <> ( n n -- bool : not equal )\n\t= 0= ;\n\n: logical ( n -- bool : turn a value into a boolean )\n\tnot not ;\n\n: 2, ( n n -- : write two values into the dictionary )\n\t, , ;\n\n: [literal] ( n -- : write a literal into the dictionary )\n\tdolit 2, ;\n\n: literal ( n -- : immediately compile a literal )\n\timmediate [literal] ;\n\n: sliteral immediate ( I: c-addr u --, Run: -- c-addr u )\n\tswap [literal] [literal] ;\n\n( @todo throw if not found )\n: ['] ( I: c\" xxx\", Run: -- xt )\n\timmediate find [literal] ;\n\n: >instruction ( CODE -- u : extract instruction CODE field )\n\tinstruction-mask and ;\n\n( IMMEDIATE-MASK pushes the mask for the compile bit,\nwhich can be used on a CODE field of a word )\n1 compile-bit lshift constant immediate-mask\n\n: hidden? ( PWD -- PWD bool : is a word hidden? )\n\tdup 1+ @ hidden-mask and logical ;\n\n: compiling? ( PWD -- PWD bool : is a word immediate? )\n\tdup 1+ @ immediate-mask and logical ;\n\n: cr ( -- : emit a newline character )\n\tnl emit ;\n\n: < ( x1 x2 -- bool : signed less than comparison )\n\t- dup if max-signed-integer u> else logical then ;\n\n: > ( x1 x2 -- bool : signed greater than comparison )\n\t- dup if max-signed-integer u< else logical then ;\n\n( The pad area is an area used for temporary storage, some\nwords use it, although which ones do should be kept to a\nminimum. It is an area of space #pad amount of characters\nafter the latest dictionary definition. The area between\nthe end of the dictionary and start of PAD space is used for\npictured numeric output [<#, #, #S, #>]. It is best not to\nuse the pad area that much. )\n128 constant #pad\n\n: pad ( -- addr : push pointer to the pad area )\n\there #pad + ;\n\n( @todo this can be improved a lot, currently it uses more\nspace than it has to, 4 cells instead of three.\n\nIt does:\n\n\tpush value\n\tpush value\n\nInstead of:\n\n\tmagic-2literal-word\n\tvalue\n\tvalue\n\n)\n: 2literal immediate ( n n -- : compile two literals )\n\tswap [literal] [literal] ;\n\n: latest ( get latest defined word )\n\tpwd @ ;\n\n: stdin ( -- fileid : push fileid for standard input )\n\t`stdin @ ;\n\n: stdout ( -- fileid : push fileid for standard output )\n\t`stdout @ ;\n\n: stderr ( -- fileid : push fileid for the standard error )\n\t`stderr @ ;\n\n: stdin? ( -- bool : are we reading from standard input )\n\t`fin @ stdin = ;\n\n: *+ ( n1 n2 n3 -- n )\n\t* + ;\n\t\n: 2- ( n -- n : decrement by two )\n\t2 - ;\n\n: 2+ ( n -- n : increment by two )\n\t2 + ;\n\n: 3+ ( n -- n : increment by three )\n\t3 + ;\n\n: 2* ( n -- n : multiply by two )\n\t1 lshift ;\n\n: 2\/ ( n -- n : divide by two )\n\t1 rshift ;\n\n: 4* ( n -- n : multiply by four )\n\t2 lshift ;\n\n: 4\/ ( n -- n : divide by four )\n\t2 rshift ;\n\n: 8* ( n -- n : multiply by eight )\n\t3 lshift ;\n\n: 8\/ ( n -- n : divide by eight )\n\t3 rshift ;\n\n: 256* ( n -- n : multiply by 256 )\n\t8 lshift ;\n\n: 256\/ ( n -- n : divide by 256 )\n\t8 rshift ;\n\n: 2dup ( n1 n2 -- n1 n2 n1 n2 : duplicate two values )\n\tover over ;\n\n: mod ( u1 u2 -- u : calculate the remainder of u1\/u2 )\n\t2dup \/ * - ;\n\n( @todo implement UM\/MOD in the VM, then use this to implement\n'\/' and MOD )\n: um\/mod ( u1 u2 -- rem quot : remainder and quotient of u1\/u2 )\n\t2dup \/ >r mod r> ;\n\n( @warning this does not use a double cell for the multiply )\n: *\/ ( n1 n2 n3 -- n4 : [n2*n3]\/n1 )\n\t * \/ ;\n\n: char ( -- n : read in a character from the input steam )\n\tkey drop key ;\n\n: [char] ( c\" x\" -- R: -- char : immediately compile next char )\n\timmediate char [literal] ;\n\n( COMPOSE is a high level function that can take two executions\ntokens and produce a unnamed function that can do what they\nboth do.\n\nIt can be used like so:\n\n\t:noname 2 ;\n\t:noname 3 + ;\n\tcompose\n\texecute \n\t.\n\t5 <-- 5 is printed!\n\nI have not found a use for it yet, but it sure is neat.)\n\n: compose ( xt1 xt2 -- xt3 : create a function from xt-tokens )\n\t>r >r ( save execution tokens )\n\tpostpone :noname ( create a new :noname word )\n\tr> , ( write first token )\n\tr> , ( write second token )\n\t(;) ; ( terminate new :noname )\n\n( CELLS is a word that is not needed in this interpreter but\nit required to write portable code [I have probably missed\nquite a few places where it should be used]. The reason it\nis not needed in this interpreter is a cell address can only\nbe in multiples of cells, not in characters. This should be\naddressed in the libforth interpreter as it adds complications\nwhen having to convert to and from character and cell address.)\n\n: cells ( n1 -- n2 : convert cell count to address count)\n\timmediate ;\n\n: cell+ ( a-addr1 -- a-addr2 )\n\tcell + ;\n\n: cell- ( a-addr1 -- addr2 )\n\tcell - ;\n\n: negative? ( x -- bool : is a number negative? )\n\tsign-bit and logical ;\n\n: mask-byte ( x -- x : generate mask byte )\n\t8* 255 swap lshift ;\n\n: select-byte ( u i -- c )\n\t8* rshift 0xff and ;\n\n: xt-instruction ( PWD -- CODE : extract instruction from PWD )\n\tcell+ @ >instruction ;\n\n: defined-word? ( PWD -- bool : is defined or a built-in word)\n\txt-instruction dolist = ;\n\n: char+ ( c-addr -- c-addr : increment a c-addr one c-addr )\n\t1+ ;\n\n: 2chars ( c-addr1 c-addr2 -- addr addr : chars on two c-addr) \n\tchars swap chars swap ;\n\n: 2chars> ( addr addr -- c-addr c-addr: chars> on two addr )\n\tchars> swap chars> swap ;\n\n: hex ( -- : print out hex )\n\t16 base ! ;\n\n: octal ( -- : print out octal )\n\t8 base ! ;\n\n: binary ( -- : print out binary )\n\t2 base ! ;\n\n: decimal ( -- : print out decimal )\n\t0 base ! ;\n\n: negate ( x -- x )\n\t-1 * ;\n\n: abs ( x -- u : return the absolute value of a number )\n\tdup negative? if negate then ;\n\n: square ( x -- x )\n\tdup * ;\n\n: sum-of-squares ( a b -- c : compute a^2 + b^2 to get c )\n\tsquare swap square + ;\n\n: drup ( x y -- x x )\n\tdrop dup ;\n\n: +! ( x addr -- : add x to a value stored at addr )\n\ttuck @ + swap ! ;\n\n: 1+! ( addr -- : increment a value at an address )\n\t1 swap +! ;\n\n: 1-! ( addr -- : decrement a value at an address )\n\t-1 swap +! ;\n\n: c+! ( x c-addr -- : add x to a value stored at c-addr )\n\ttuck c@ + swap c! ;\n\n: toggle ( addr u -- : xor value at addr with u )\n\tover @ xor swap ! ;\n\n: lsb ( x -- x : mask off the least significant byte of a cell )\n\t255 and ;\n\n: \\ ( -- : immediate word, used for single line comments )\n\timmediate begin key nl = until ;\n\n: ?dup ( x -- ? )\n\tdup if dup then ;\n\n: min ( n n -- n : return the minimum of two integers )\n\t2dup < if drop else nip then ;\n\n: max ( n n -- n : return the maximum of two integers )\n\t2dup > if drop else nip then ;\n\n: umin ( u u -- u : return the minimum of two unsigned numbers )\n\t2dup u< if drop else nip then ;\n\n: umax ( u u -- u : return the maximum of two unsigned numbers )\n\t2dup > if drop else nip then ;\n\n: limit ( x min max -- x : limit x with a minimum and maximum )\n\trot min max ;\n\n: >= ( n n -- bool )\n\t< not ;\n\n: <= ( n n -- bool )\n\t> not ;\n\n: 2@ ( a-addr -- u1 u2 : load two consecutive memory cells )\n\tdup 1+ @ swap @ ;\n\n: 2! ( u1 u2 a-addr -- : store two values at two consecutive memory cells )\n\t2dup ! nip 1+ ! ;\n\n( @bug I don't think this is correct. )\n: r@ ( -- u, R: u -- )\n\tr> r @ swap >r ;\n\n: rp@ ( -- u, R: u -- )\n\tr> r @ swap >r ;\n\n( @todo r!, rp! )\n\n: 0> ( n -- bool )\n\t0 > ;\n\n: 0<= ( n -- bool )\n\t0> not ;\n\n: 0< ( n -- bool )\n\t0 < ;\n\n: 0>= ( n -- bool )\n\t0< not ;\n\n: 0<> ( n -- bool )\n\t0 <> ;\n\n: signum ( n -- -1 | 0 | 1 : Signum function )\n\tdup 0> if drop 1 exit then\n\t 0< if -1 exit then\n\t0 ;\n\n: nand ( u u -- u : bitwise NAND )\n\tand invert ;\n\n: odd ( u -- bool : is 'n' odd? )\n\t1 and ;\n\n: even ( u -- bool : is 'n' even? )\n\todd not ;\n\n: nor ( u u -- u : bitwise NOR )\n\tor invert ;\n\n: ms ( u -- : wait at least 'u' milliseconds )\n\tclock + begin dup clock u< until drop ;\n\n: sleep ( u -- : sleep for 'u' seconds )\n\t1000 * ms ;\n\n: align ( addr -- addr : align an address, nop in this implemented )\n\timmediate ;\n\n: ) ( -- : do nothing, this allows easy commenting out of code )\n\timmediate ;\n\n: bell ( -- : emit an ASCII BEL character )\n\t7 emit ;\n\n: b\/buf ( -- u : bytes per buffer )\n\t1024 ;\n\n: .d ( x -- x : debug print )\n\tdup . ;\n\n: compile, ( x -- : )\n\t, ;\n\n: >mark ( -- : write a hole into the dictionary and push a pointer to it )\n\there 0 , ;\n\n: r - r> u< ;\n\n: invalidate ( -- : invalidate this Forth core )\n\t1 `invalid ! ;\n\n: signed ( x -- bool : return true if sign bit set )\n\t[ 1 size 8 * 1- lshift ] literal and logical ;\n\n: u>= ( x y -- bool : unsigned greater than or equal to )\n\t2dup u> >r = r> or ;\n\n: u<= ( x y -- bool : unsigned less than or equal to )\n\tu>= not ;\n\n: rdrop ( R: x -- : drop a value from the return stack )\n\tr> ( get caller's return address )\n\tr> ( get value to drop )\n\tdrop ( drop it like it's hot )\n\t>r ; ( return return address )\n\n: rdup\n\tr> ( get caller's return address )\n\tr> ( get value to duplicate )\n\tdup ( ... )\n\t>r >r >r ; ( make it all work )\n\n: chere ( -- c-addr : here as in character address units )\n\there chars> ;\n\n: source ( -- c-addr u )\n\t#tib ( size of input buffer, in characters )\n\ttib ; ( start of input buffer, in characters )\n\n: stdin? ( -- bool : are we reading from standard in? )\n\t`fin @ `stdin @ = ;\n\n: source-id ( -- 0 | -1 | file-id )\n\t( \t\n\tValue Input Source\n\t-1 String\n\t0 Reading from user input \/ standard in\n\tfile-id )\n\t`source-id @\n\t0= if\n\t\tstdin? if 0 else `fin @ then\n\telse\n\t\t-1\n\tthen ;\n\n: under ( x1 x2 -- x1 x1 x2 )\n\t>r dup r> ;\n\n: 2nip ( n1 n2 n3 n4 -- n3 n4 )\n\t>r >r 2drop r> r> ;\n\n: 2over ( n1 n2 n3 n4 \u2013 n1 n2 n3 n4 n1 n2 )\n\t>r >r 2dup r> swap >r swap r> r> -rot ;\n\n: 2swap ( n1 n2 n3 n4 \u2013 n3 n4 n1 n2 )\n\t>r -rot r> -rot ;\n\n: 2tuck ( n1 n2 n3 n4 \u2013 n3 n4 n1 n2 n3 n4 )\n\t2swap 2over ;\n\n: 3drop ( n1 n2 n3 -- )\n\tdrop 2drop ;\n\n: 4drop ( n1 n2 n3 n4 -- )\n\t2drop 2drop ;\n\n: nos1+ ( x1 x2 -- x1+1 x2 : increment the next variable on that stack )\n\tswap 1+ swap ;\n\n: ?dup-if immediate ( x -- x | - : ?dup and if rolled into one! )\n\t['] ?dup , postpone if ;\n\n: ?if ( -- : non destructive if )\n\timmediate ['] dup , postpone if ;\n\n: (hide) ( token -- hide-token : this hides a word from being found by the interpreter )\n\t?dup-if\n\t\tdup @ hidden-mask or swap tuck ! exit\n\tthen 0 ;\n\n: hide ( WORD -- : hide with drop )\n\tfind dup if (hide) then drop ;\n\n: reveal ( hide-token -- : reveal a hidden word )\n\tdup @ hidden-mask invert and swap ! ;\n\n: ?exit ( x -- : exit current definition if not zero )\n\tif rdrop exit then ;\n\n: decimal? ( c -- f : is character a number? )\n\t[char] 0 [ char 9 1+ ] literal within ;\n\n: lowercase? ( c -- f : is character lower case? )\n\t[char] a [ char z 1+ ] literal within ;\n\n: uppercase? ( C -- f : is character upper case? )\n\t[char] A [ char Z 1+ ] literal within ;\n\n: alpha? ( C -- f : is character part of the alphabet? )\n\tdup lowercase? swap uppercase? or ;\n\n: alphanumeric? ( C -- f : is character alphabetic or a number ? )\n\tdup alpha? swap decimal? or ;\n\n: printable? ( c -- bool : is printable, excluding new lines and tables )\n\t32 127 within ;\n\n: >upper ( c -- C : convert char to uppercase iff lower case )\n\tdup lowercase? if bl xor then ;\n\n: >lower ( C -- c : convert char to lowercase iff upper case )\n\tdup uppercase? if bl xor then ;\n\n: <=> ( x y -- z : spaceship operator! )\n\t2dup\n\t> if 2drop -1 exit then\n\t< ;\n\n: start-address ( -- c-addr : push the start address )\n\t`start-address @ ;\n\n: >real-address ( c-addr -- r-addr : convert an interpreter address to a real address )\n\tstart-address + ;\n\n: real-address> ( c-addr -- r-addr : convert a real address to an interpreter address )\n\tstart-address - ;\n\n: peek ( r-addr -- n : )\n\tpad chars> >real-address swap size memory-copy pad @ ;\n\n: poke ( n r-addr -- : )\n\tswap pad ! pad chars> >real-address size memory-copy ;\n\n: die! ( x -- : controls actions when encountering certain errors )\n\t`error-handler ! ;\n\n: start! ( cfa -- : set the word to execute at startup )\n\t`instruction ! ;\t\n\n: warm ( -- : restart the interpreter, warm restart )\n\t1 restart ;\n\n: trip ( x -- x x x : triplicate a number )\n\tdup dup ;\n\n: roll ( xu xu-1 ... x0 u -- xu-1 ... x0 xu : move u+1 items on the top of the stack by u )\n\t[ smudge ] ( un-hide this word so we can call it recursively )\n\tdup 0 >\n\tif\n\t\tswap >r 1- roll r> swap\n\telse\n\t\tdrop\n\tthen ;\nsmudge\n\n: 2rot ( n1 n2 n3 n4 n5 n6 \u2013 n3 n4 n5 n6 n1 n2 )\n\t5 roll 5 roll ;\n\n: s>d ( x -- d : convert a signed value to a double width cell )\n\t( @note the if...else...then is only necessary as this Forths\n\tbooleans are 0 and 1, not 0 and -1 as it usually is )\n\tdup 0< if -1 else 0 then ;\n\n: trace ( level -- : set tracing level )\n\t`debug ! ;\n\n: verbose ( -- : get the log level )\n\t`debug @ ;\n\n: count ( c-addr1 -- c-addr2 u : get a string whose first char is its length )\n\tdup c@ nos1+ ;\n\n: bounds ( x y -- y+x x : make an upper and lower bound )\n\tover + swap ;\n\n: aligned ( unaligned -- aligned : align a pointer )\n\t[ size 1- ] literal +\n\t[ size 1- ] literal invert and ;\n\n: rdepth\n\tmax-core `stack-size @ - r @ swap - ;\n\n: argv ( -- r-addr : push pointer to array of string pointers to program )\n\t`argv @ ;\n\n: argc ( -- u : push the number of arguments in the argv array )\n\t`argc @ ;\n\n: +- ( x1 x2 -- x3 : copy the sign of x1 to x2 giving x3 )\n\t[ sign-bit 1- ] literal and\n\tswap\n\tsign-bit and or ;\n\n: \/string ( c-addr1 u1 u2 -- c-addr2 u2 : advance a string by n characters )\n\tover min rot over + -rot - ;\n\nhide stdin?\n\n: cfa immediate ( find-address -- cfa )\n\t( Given the address of the PWD field of a word this\n\tfunction will return an execution token for the word )\n\t( @todo if < dictionary start PWD is invalid )\n\t ;\n\n: again immediate\n\t( loop unconditionally in a begin-loop:\n\t\tbegin ... again )\n\t' branch , body ( xt -- a-addr : a-addr is data field of a CREATEd word )\n\\\tcfa 5 + ;\n\n\n: execute ( xt -- : given an execution token, execute the word )\n\t( create a word that pushes the address of a hole to write to.\n\tA literal takes up two words, '!' takes up one, that's right,\n\tsome self modifying code! )\n\t[ here 3 cells + literal ] ( calculate place to write to )\n\t! ( write an execution token to a hole )\n\t[ 0 , ] ; ( this is the hole we write )\n\n( See: http:\/\/lars.nocrew.org\/dpans\/dpans9.htm\n@todo turn this into a lookup table of strings\n\n Code Reserved for\n ---- ------------\n -1 ABORT\n -2 ABORT\"\n -3 stack overflow\n -4 stack underflow\n -5 return stack overflow\n -6 return stack underflow\n -7 do-loops nested too deeply during execution\n -8 dictionary overflow\n -9 invalid memory address\n -10 division by zero\n -11 result out of range\n -12 argument type mismatch\n -13 undefined word\n -14 interpreting a compile-only word\n -15 invalid FORGET\n -16 attempt to use zero-length string as a name\n -17 pictured numeric output string overflow\n -18 parsed string overflow\n -19 definition name too long\n -20 write to a read-only location\n -21 unsupported operation [e.g., AT-XY on a\n too-dumb terminal]\n -22 control structure mismatch\n -23 address alignment exception\n -24 invalid numeric argument\n -25 return stack imbalance\n -26 loop parameters unavailable\n -27 invalid recursion\n -28 user interrupt\n -29 compiler nesting\n -30 obsolescent feature\n -31 >BODY used on non-CREATEd definition\n -32 invalid name argument [e.g., TO xxx]\n -33 block read exception\n -34 block write exception\n -35 invalid block number\n -36 invalid file position\n -37 file I\/O exception\n -38 non-existent file\n -39 unexpected end of file\n -40 invalid BASE for floating point conversion\n -41 loss of precision\n -42 floating-point divide by zero\n -43 floating-point result out of range\n -44 floating-point stack overflow\n -45 floating-point stack underflow\n -46 floating-point invalid argument\n -47 compilation word list deleted\n -48 invalid POSTPONE\n -49 search-order overflow\n -50 search-order underflow\n -51 compilation word list changed\n -52 control-flow stack overflow\n -53 exception stack overflow\n -54 floating-point underflow\n -55 floating-point unidentified fault\n -56 QUIT\n -57 exception in sending or receiving a character\n -58 [IF], [ELSE], or [THEN] exception )\n\n( @todo integrate catch\/throw into the interpreter as primitives )\n: catch ( xt -- exception# | 0 : return addr on stack )\n\tsp@ >r ( xt : save data stack pointer )\n\t`handler @ >r ( xt : and previous handler )\n\tr@ `handler ! ( xt : set current handler )\n\texecute ( execute returns if no throw )\n\tr> `handler ! ( restore previous handler )\n\tr> drop ( discard saved stack ptr )\n\t0 ; ( 0 : normal completion )\n\n( @todo use this everywhere )\n: throw ( ??? exception# -- ??? exception# )\n\t?dup-if ( exc# \\ 0 throw is no-op )\n\t\t`handler @ r ! ( exc# : restore prev return stack )\n\t\tr> `handler ! ( exc# : restore prev handler )\n\t\tr> swap >r ( saved-sp : exc# on return stack )\n\t\tsp! drop r> ( exc# : restore stack )\n\t\t( return to the caller of catch because return )\n\t\t( stack is restored to the state that existed )\n\t\t( when catch began execution )\n\tthen ;\n\n: interpret ( c1\" xxx\" ... cn\" xxx\" -- : This word implements the interpreter loop )\n\tbegin\n\t' read catch\n\t?dup-if [char] ! emit tab . cr then ( exception handler of last resort )\n\tagain ;\n\n: [interpret] ( c1\" xxx\" ... cn\" xxx\" -- : immediate version of interpret )\n\timmediate interpret ;\n\ninterpret ( use the new interpret word, which can catch exceptions )\n\nfind [interpret] cell+ start! ( the word executed on restart is now our new word )\n\n( The following words are using in various control structure related\nwords to make sure they only execute in the correct state )\n\n: ?comp ( -- : error if not compiling )\n\tstate @ 0= if -14 throw then ;\n\n: ?exec ( -- : error if not executing )\n\tstate @ if -22 throw then ;\n\n( begin...while...repeat These are defined in a very \"Forth\" way )\n: while\n\t?comp\n\timmediate postpone if ( branch to repeats THEN ) ;\n\n: whilst postpone while ;\n\n: repeat immediate\n\t?comp\n\tswap ( swap BEGIN here and WHILE here )\n\tpostpone again ( again jumps to begin )\n\tpostpone then ; ( then writes to the hole made in if )\n\n: never ( never...then : reserve space in word )\n\timmediate ?comp 0 [literal] postpone if ;\n\n: unless ( bool -- : like IF but execute clause if false )\n\timmediate ?comp ['] 0= , postpone if ;\n\n: endif ( synonym for THEN )\n\timmediate ?comp postpone then ;\n\n( ==================== Basic Word Set ======================== )\n\n( ==================== DOER\/MAKE ============================= )\n( DOER\/MAKE is a word set that is quite powerful and is\ndescribed in Leo Brodie's book \"Thinking Forth\". It can be\nused to make words whose behavior can change after they\nare defined. It essentially makes the structured use of\nself-modifying code possible, along with the more common\ndefinitions of \"defer\/is\".\n\nAccording to \"Thinking Forth\", it has two purposes:\n\n1. To change the state of a function.\n2. To factor out common phrases of a words definition.\n\nAn example of the first instance:\n\n\tdoer say\n\t: sad \" Good bye, cruel World!\" cr ;\n\t: happy \" Hello, World!\" cr ;\n\n\t: person say ;\n\n\tmake person happy\n\tperson \\ prints \"Good bye, cruel World!\"\n\n\tmake person sad\n\tperson \\ prints \"Hello, World!\"\n\nAn example of the second:\n\n\tdoer op\n\n\t: sum \\ n0 ... nX X -- sum<0..X>\n\t\tmake op + 1 do op loop ;\n\n\t: mul \\ n0 ... nX X -- mul<0..X>\n\t\tmake op * 1 do op loop ;\n\nThe above example is a bit contrived, the definitions and\nfunctionality are too simple for this to be worth factoring\nout, but it shows how you can use DOER\/MAKE. )\n\n: noop ; ( -- : default word to execute for doer, does nothing )\n\n: doer ( c\" xxx\" -- : make a work whose behavior can be changed by make )\n\timmediate ?exec :: ['] noop , (;) ;\n\n: found? ( xt -- xt : thrown an exception if the xt is zero )\n\tdup 0= if -13 throw then ;\n\n( It would be nice to provide a MAKE that worked with\nexecution tokens as well, although \"defer\" and \"is\" can be\nused for that. MAKE expects two word names to be given as\narguments. It will then change the behavior of the first word\nto use the second. MAKE is a state aware word. )\n\n: make immediate ( c1\" xxx\" c2\" xxx\" : change parsed word c1 to execute c2 )\n\tfind found? cell+\n\tfind found?\n\tstate @ if ( compiling )\n\t\tswap postpone 2literal ['] ! ,\n\telse ( command mode )\n\t\tswap !\n\tthen ;\n\n( ==================== DOER\/MAKE ============================= )\n\n( ==================== Extended Word Set ===================== )\n\n: r.s ( -- : print the contents of the return stack )\n\tr>\n\t[char] < emit rdepth (.) drop [char] > emit\n\tspace\n\trdepth dup 0> if dup\n\tbegin dup while r> -rot 1- repeat drop dup\n\tbegin dup while rot dup . >r 1- repeat drop\n\tthen drop cr\n\t>r ;\n\n: log ( u base -- u : command the _integer_ logarithm of u in base )\n\t>r\n\tdup 0= if -11 throw then ( logarithm of zero is an error )\n\t0 swap\n\tbegin\n\t\tnos1+ rdup r> \/ dup 0= ( keep dividing until 'u' is zero )\n\tuntil\n\tdrop 1- rdrop ;\n\n: log2 ( u -- u : compute the _integer_ logarithm of u )\n\t2 log ;\n\n: alignment-bits ( c-addr -- u : get the bits used for aligning a cell )\n\t[ 1 size log2 lshift 1- literal ] and ;\n\n: time ( \" ccc\" -- n : time the number of milliseconds it takes to execute a word )\n\tclock >r\n\tfind found? execute\n\tclock r> - ;\n\n( defer...is is probably not standards compliant, it is still neat! )\n: (do-defer) ( -- self : pushes the location into which it is compiled )\n\tr> dup >r 1- ;\n\n: defer immediate ( \" ccc\" -- , Run Time -- location :\n\tcreates a word that pushes a location to write an execution token into )\n\t?exec\n\t:: ' (do-defer) , (;) ;\n\n: is ( location \" ccc\" -- : make a deferred word execute a word )\n\tfind found? swap ! ;\n\nhide (do-defer)\n\n( This RECURSE word is the standard Forth word for allowing\nfunctions to be called recursively. A word is hidden from the\ncompiler until the matching ';' is hit. This allows for previous\ndefinitions of words to be used when redefining new words, it\nalso means that words cannot be called recursively unless the\nrecurse word is used.\n\nRECURSE calls the word being defined, which means that it\ntakes up space on the return stack. Words using recursion\nshould be careful not to take up too much space on the return\nstack, and of course they should terminate after a finite\nnumber of steps.\n\nWe can test \"recurse\" with this factorial function:\n\n : factorial dup 2 < if drop 1 exit then dup 1- recurse * ;\n\n)\n: recurse immediate\n\t?comp\n\tlatest cell+ , ;\n\n: myself ( -- : myself is a synonym for recurse )\n\timmediate postpone recurse ;\n\n( The \"tail\" function implements tail calls, which is just a\njump to the beginning of the words definition, for example\nthis word will never overflow the stack and will print \"1\"\nfollowed by a new line forever,\n\n\t: forever 1 . cr tail ;\n\nWhereas\n\n\t: forever 1 . cr recurse ;\n\nor\n\n\t: forever 1 . cr forever ;\n\nWould overflow the return stack. )\n\nhide tail\n: tail ( -- : perform tail recursion in current word definition )\n\timmediate\n\t?comp\n\tlatest cell+\n\t' branch ,\n\there - cell+ , ;\n\n: factorial ( u -- u : factorial of u )\n\tdup 2 u< if drop 1 exit then dup 1- recurse * ;\n\n: gcd ( u1 u2 -- u : greatest common divisor )\n\tdup if tuck mod tail then drop ;\n\n: lcm ( u1 u2 -- u : lowest common multiple of u1 and u2 )\n\t2dup gcd \/ * ;\n\n( From: https:\/\/en.wikipedia.org\/wiki\/Integer_square_root\n\nThis function computes the integer square root of a number.\n\n@note this should be changed to the iterative algorithm so\nit takes up less space on the stack - not that is takes up\na hideous amount as it is. )\n\n: sqrt ( n -- u : integer square root )\n\tdup 0< if -11 throw then ( does not work for signed values )\n\tdup 2 < if exit then ( return 0 or 1 )\n\tdup ( u u )\n\t2 rshift recurse 2* ( u sc : 'sc' == unsigned small candidate )\n\tdup ( u sc sc )\n\t1+ dup square ( u sc lc lc^2 : 'lc' == unsigned large candidate )\n\t>r rot r> < ( sc lc bool )\n\tif drop else nip then ; ( return small or large candidate respectively )\n\n\n( ==================== Extended Word Set ===================== )\n\n( ==================== For Each Loop ========================= )\n( The foreach word set allows the user to take action over an\nentire array without setting up loops and checking bounds. It\nbehaves like the foreach loops that are popular in other\nlanguages.\n\nThe foreach word accepts a string and an execution token,\nfor each character in the string it passes the current address\nof the character that it should operate on.\n\nThe complexity of the foreach loop is due to the requirements\nplaced on it. It cannot pollute the variable stack with\nvalues it needs to operate on, and it cannot store values in\nlocal variables as a foreach loop could be called from within\nthe execution token it was passed. It therefore has to store\nall of it uses on the return stack for the duration of EXECUTE.\n\nAt the moment it only acts on strings as \"\/string\" only\nincrements the address passed to the word foreach executes\nto the next character address. )\n\n\\ (FOREACH) leaves the point at which the foreach loop\n\\ terminated on the stack, this allows programmer to determine\n\\ if the loop terminated early or not, and at which point.\n\n: (foreach) ( c-addr u xt -- c-addr u : execute xt for each cell in c-addr u\n\treturning number of items not processed )\n\tbegin\n\t\t3dup >r >r >r ( c-addr u xt R: c-addr u xt )\n\t\tnip ( c-addr xt R: c-addr u xt )\n\t\texecute ( R: c-addr u xt )\n\t\tr> r> r> ( c-addr u xt )\n\t\t-rot ( xt c-addr u )\n\t\t1 \/string ( xt c-addr u )\n\t\tdup 0= if rot drop exit then ( End of string - drop and exit! )\n\t\trot ( c-addr u xt )\n\tagain ;\n\n\\ If we do not care about returning early from the foreach\n\\ loop we can instead call FOREACH instead of (FOREACH),\n\\ it simply drops the results (FOREACH) placed on the stack.\n: foreach ( c-addr u xt -- : execute xt for each cell in c-addr u )\n\t(foreach) 2drop ;\n\n\\ RETURN is used for an early exit from within the execution\n\\ token, it leaves the point at which it exited\n: return ( -- n : return early from within a foreach loop function, returning number of items left )\n\trdrop ( pop off this words return value )\n\trdrop ( pop off the calling words return value )\n\trdrop ( pop off the xt token )\n\tr> ( save u )\n\tr> ( save c-addr )\n\trdrop ; ( pop off the foreach return value )\n\n\\ SKIP is an example of a word that uses the foreach loop\n\\ mechanism. It takes a string and a character and returns a\n\\ string that starts at the first occurrence of that character\n\\ in that string - or until it reaches the end of the string.\n\n\\ SKIP is defined in two steps, first there is a word,\n\\ (SKIP), that exits the foreach loop if there is a match,\n\\ if there is no match it does nothing. In either case it\n\\ leaves the character to skip until on the stack.\n\n: (skip) ( char c-addr -- char : exit out of foreach loop if there is a match )\n\tover swap c@ = if return then ;\n\n\\ SKIP then setups up the foreach loop, the char argument\n\\ will present on the stack when (SKIP) is executed, it must\n\\ leave a copy on the stack whatever happens, this is then\n\\ dropped at the end. (FOREACH) leaves the point at which\n\\ the loop terminated on the stack, which is what we want.\n\n: skip ( c-addr u char -- c-addr u : skip until char is found or until end of string )\n\t-rot ['] (skip) (foreach) rot drop ;\nhide (skip)\n\n( ==================== For Each Loop ========================= )\n\n( ==================== Hiding Words ========================== )\n( The two functions hide{ and }hide allow lists of words to\nbe hidden, instead of just hiding individual words. It stops\nthe dictionary from being polluted with meaningless words in\nan easy way. )\n\n: }hide ( should only be matched with 'hide{' )\n\timmediate -22 throw ;\n\n: hide{ ( -- : hide a list of words, the list is terminated with \"}hide\" )\n\t?exec\n\tbegin\n\t\tfind ( find next word )\n\t\tdup [ find }hide ] literal = if\n\t\t\tdrop exit ( terminate hide{ )\n\t\tthen\n\t\tdup 0= if -15 throw then\n\t\t(hide) drop\n\tagain ;\n\nhide (hide)\n\n( ==================== Hiding Words ========================== )\n\n( The words described here on out get more complex and will\nrequire more of an explanation as to how they work. )\n\n( ==================== Create Does> ========================== )\n\n( The following section defines a pair of words \"create\"\nand \"does>\" which are a powerful set of words that can be\nused to make words that can create other words. \"create\"\nhas both run time and compile time behavior, whilst \"does>\"\nonly works at compile time in conjunction with \"create\". These\ntwo words can be used to add constants, variables and arrays\nto the language, amongst other things.\n\nA simple version of create is as follows\n\n\t: create :: dolist , here 2 cells + , ' exit , 0 state ! ;\n\nBut this version is much more limited.\n\n\"create\"...\"does>\" is one of the constructs that makes Forth\nForth, it allows the creation of words which can define new\nwords in themselves, and thus allows us to extend the language\neasily. )\n\n: write-quote ( -- : A word that writes ' into the dictionary )\n\t['] ' , ;\n\n: write-exit ( -- : A word that write exit into the dictionary )\n\t['] _exit , ;\n\n: write-compile, ( -- : A word that writes , into the dictionary )\n\t' , , ;\n\n: command-mode ( -- : put the interpreter into command mode )\n\tfalse state ! ;\n\n: command-mode-create ( create a new work that pushes its data field )\n\t:: ( compile a word )\n\tdolit , ( write push into new word )\n\there 2 cells + , ( push a pointer to data field )\n\t(;) ; ( write exit and switch to command mode )\n\n: mark write-compile, ( Write in a place holder 0 and push a pointer to to be used by does> )\n\twrite-quote write-exit write-compile, ( Write in an exit in the word we're compiling. )\n\t['] command-mode , ; ( Make sure to change the state back to command mode )\n\n: create immediate ( create word is quite a complex forth word )\n\tstate @\n\tif\n\t\tpostpone ( hole-to-patch -- )\n\timmediate\n\t?comp\n\twrite-exit ( we don't want the defining word to exit, but the *defined* word to )\n\there swap ! ( patch in the code fields to point to )\n\tdolist , ; ( write a run in )\n\nhide{ command-mode-create write-quote write-compile, write-exit }hide\n\n( Now that we have create...does> we can use it to create\narrays, variables and constants, as we mentioned before. )\n\n: array ( u c\" xxx\" -- : create a named array of length u )\n\tcreate allot does> + ;\n\n: variable ( x c\" xxx\" -- : create a variable will initial value of x )\n\tcreate , does> ;\n\n\\ : constant ( x c\" xxx\" -- : create a constant with value of x )\n\\\tcreate , does> @ ;\n\n: table ( u c\" xxx\" --, Run Time: -- addr u : create a named table )\n\tcreate dup , allot does> dup @ ;\n\n: string ( u c\" xxx\" --, Run Time: -- c-addr u : create a named string )\n\tcreate dup , chars allot does> dup @ swap 1+ chars> swap ;\n\n\\ : +field \\ n <\"name\"> -- ; exec: addr -- 'addr\n\\ create over , +\n\\ does> @ + ;\n\\\n\\ : begin-structure \\ -- addr 0 ; -- size\n\\ \tcreate\n\\ \there 0 0 , \\ mark stack, lay dummy\n\\ \tdoes> @ ; \\ -- rec-len\n\\\n\\ : end-structure \\ addr n --\n\\ swap ! ; \\ set len\n\\\n\\ begin-structure point\n\\ \tpoint +field p.x\n\\ \tpoint +field p.y\n\\ end-structure\n\\\n\\ This should work...\n\\ : buffer: ( u c\" xxx\" --, Run Time: -- addr )\n\\\tcreate allot ;\n\n: 2constant\n\tcreate , , does> dup 1+ @ swap @ ;\n\n: 2variable\n\tcreate , , does> ;\n\n: enum ( x \" ccc\" -- x+1 : define a series of enumerations )\n\tdup constant 1+ ;\n\n( ==================== Create Does> ========================== )\n\n( ==================== Do ... Loop =========================== )\n\n( The following section implements Forth's do...loop\nconstructs, the word definitions are quite complex as it\ninvolves a lot of juggling of the return stack. Along with\nbegin...until do loops are one of the main looping constructs.\n\nUnlike begin...until do accepts two values a limit and a\nstarting value, they are also words only to be used within a\nword definition, some Forths extend the semantics so looping\nconstructs operate in command mode, this Forth does not do\nthat as it complicates things unnecessarily.\n\nExample:\n\n\t: example-1\n\t\t10 1 do\n\t\t\ti . i 5 > if cr leave then loop\n\t\t100 . cr ;\n\n\texample-1\n\nPrints:\n\t1 2 3 4 5 6\n\nIn \"example-1\" we can see the following:\n\n1. A limit, 10, and a start value, 1, passed to \"do\".\n2. A word called 'i', which is the current count of the loop.\n3. If the count is greater than 5, we call a word call\nLEAVE, this word exits the current loop context as well as\nthe current calling word.\n4. \"100 . cr\" is never called. This should be changed in\nfuture revision, but this version of leave exits the calling\nword as well.\n\n'i', 'j', and LEAVE *must* be used within a do...loop\nconstruct.\n\nIn order to remedy point 4. loop should not use branch but\ninstead should use a value to return to which it pushes to\nthe return stack )\n\n: (do)\n\tswap ( swap the limit and start )\n\tr> ( save our return stack to temporary variable )\n\t-rot ( limit start return -- return start limit )\n\t>r ( push limit onto return stack )\n\t>r ( push start onto return stack )\n\t>r ; ( restore our return address )\n\n: do immediate ( Run time: high low -- : begin do...loop construct )\n\t?comp\n\t' (do) ,\n\tpostpone begin ;\n\n: (unloop) ( -- , R: i limit -- : remove limit and i from )\n\tr> ( save our return address )\n\trdrop ( pop off i )\n\trdrop ( pop off limit )\n\t>r ; ( restore our return stack )\n\n: (+loop) ( x -- bool : increment loop variable by x and test it )\n\tr@ 1- ( get the pointer to i )\n\t+! ( add value to it )\n\tr@ 1- @ ( find i again )\n\tr@ 2- @ ( find the limit value )\n\tu>= ;\n\n: (loop) ( -- bool : increment loop variable by 1 and test it )\n\tr@ 1- ( get the pointer to i )\n\t1+! ( add one to it )\n\tr@ 1- @ ( find the value again )\n\tr@ 2- @ ( find the limit value )\n\tu>= ;\n\n: loop ( -- : end do...loop construct )\n\timmediate ?comp ' (loop) , postpone until ' (unloop) , ;\n\n: +loop ( x -- : end do...+loop loop construct )\n\timmediate ?comp ' (+loop) , postpone until ' (unloop) , ;\n\n: leave ( -- , R: i limit return -- : break out of a do-loop construct )\n\t(unloop)\n\trdrop ; ( return to the caller's caller routine )\n\n: ?leave ( x -- , R: i limit return -- | i limit return : conditional leave )\n\tif\n\t\t(unloop)\n\t\trdrop ( return to the caller's caller routine )\n\tthen ;\n\n\\ @todo define '(i)', '(j)' and '(k)', then make their\n\\ wrappers, 'i', 'j' and 'k' call ?comp then compile a pointer\n\\ to the thing that implements them, likewise for leave,\n\\ loop and +loop.\n: i ( -- i : Get current, or innermost, loop index in do...loop construct )\n\tr> r> ( pop off return address and i )\n\ttuck ( tuck i away )\n\t>r >r ; ( restore return stack )\n\n: j ( -- j : Get outermost loop index in do...loop construct )\n\t4 rpick ;\n\n( This is a simple test function for the looping, for interactive\ntesting and debugging:\n : mm 5 1 do i . cr 4 1 do j . tab i . cr loop loop ; )\n\n: range ( nX nY -- nX nX+1 ... nY )\n\tnos1+ do i loop ;\n\n: repeater ( n0 X -- n0 ... nX )\n\t1 do dup loop ;\n\n: sum ( n0 ... nX X -- sum<0..X> )\n\t1 do + loop ;\n\n: mul ( n0 ... nX X -- mul<0..X> )\n\t1 do * loop ;\n\n: reverse ( x1 ... xn n -- xn ... x1 : reverse n items on the stack )\n\t0 do i roll loop ;\n\n( ==================== Do ... Loop =========================== )\n\n( ==================== String Substitution =================== )\n\n: (subst) ( char1 char2 c-addr )\n\t3dup ( char1 char2 c-addr char1 char2 c-addr )\n\tc@ = if ( char1 char2 c-addr char1 )\n\t\tswap c! ( match, substitute character )\n\telse ( char1 char2 c-addr char1 )\n\t\t2drop ( no match )\n\tthen ;\n\n: subst ( c-addr u char1 char2 -- replace all char1 with char2 in string )\n\tswap\n\t2swap\n\t['] (subst) foreach 2drop ;\nhide (subst)\n\n0 variable c\n0 variable sub\n0 variable #sub\n\n: (subst-all) ( c-addr : search in sub\/#sub for a character to replace at c-addr )\n\tsub @ #sub @ bounds ( get limits )\n\tdo\n\t\tdup ( duplicate supplied c-addr )\n\t\tc@ i c@ = if ( check if match )\n\t\t\tdup\n\t\t\tc chars c@ swap c! ( write out replacement char )\n\t\tthen\n\tloop drop ;\n\n: subst-all ( c-addr1 u c-addr2 u char -- replace chars in str1 if in str2 with char )\n\tc chars c! #sub ! sub ! ( store strings away )\n\t['] (subst-all) foreach ;\n\nhide{ c sub #sub (subst-all) }hide\n\n( ==================== String Substitution =================== )\n\n0 variable column-counter\n4 variable column-width\n\n: column ( i -- )\t\n\tcolumn-width @ mod not if cr then ;\n\n: column.reset\t\t\n\t0 column-counter ! ;\n\n: auto-column\t\t\n\tcolumn-counter dup @ column 1+! ;\n\n0 variable x\n: x! ( x -- )\n\tx ! ;\n\n: x@ ( -- x )\n\tx @ ;\n\n: 2>r ( x1 x2 -- R: x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tswap\n\t\t>r\n\t\t>r\n\tx@ >r ; ( restore return address )\n\n: 2r> ( R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tr>\n\t\tr>\n\t\tswap\n\tx@ >r ; ( restore return address )\n\n: 2r@ ( -- x1 x2 , R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\tr> r>\n\t2dup\n\t>r >r\n\tswap\n\tx@ >r ; ( restore return address )\n\n: unused ( -- u : push the amount of core left )\n\tmax-core here - ;\n\n: accumulator ( initial \" ccc\" -- : make a word that increments by a value and pushes the result )\n\tcreate , does> tuck +! @ ;\n\n: counter ( \" ccc\" --, Run Time: -- x : make a word that increments itself by one, starting from zero )\n\tcreate -1 , does> dup 1+! @ ;\n\n0 variable delim\n: accepter ( c-addr max delimiter -- i )\n\t( store a \"max\" number of chars at c-addr until \"delimiter\" encountered,\n\tthe number of characters stored is returned )\n\tdelim ! ( store delimiter used to stop string storage when encountered)\n\t0\n\tdo\n\t\tkey dup delim @ <>\n\t\tif\n\t\t\tover c! 1+\n\t\telse ( terminate string )\n\t\t\tdrop 0 swap c!\n\t\t\ti\n\t\t\tleave\n\t\tthen\n\tloop\n\t-18 throw ; ( read in too many chars )\nhide delim\n\n: skip ( char -- : read input until string is reached )\n\tkey drop >r 0 begin drop key dup rdup r> <> until rdrop ;\n\n: word ( c -- c-addr : parse until 'c' is encountered, push transient counted string )\n\tdup skip chere 1+ c!\n\t>r\n\tchere 2+\n\tpad here - chars>\n\tr> accepter 1+\n\tchere c!\n\tchere ;\nhide skip\n\n: accept ( c-addr +n1 -- +n2 : see accepter definition )\n\tnl accepter ;\n\n0xFFFF constant max-string-length\n\n: (.\") ( char -- c-addr u )\n\t( @todo This really needs simplifying, to do this\n\ta set of words that operate on a temporary buffer can\n\tbe used )\n\t( Write a string into word being currently defined, this\n\tcode has to jump over the string it has just put into the\n\tdictionary so normal execution of a word can continue. The\n\tlength and character address of the string are left on the\n\tstack )\n\t>r ( save delimiter )\n\t' branch , ( write in jump, this will jump past the string )\n\t>mark ( make hole )\n\tdup 1+ chars> ( calculate address to write to )\n\tmax-string-length\n\tr> ( restore delimiter )\n\taccepter dup >r ( write string into dictionary, save index )\n\taligned 2dup size \/ ( stack: length hole char-len hole )\n\t1+ dup allot ( update dictionary pointer with string length )\n\t1+ swap ! ( write place to jump to )\n\tdrop ( do not need string length anymore )\n\t1+ chars> ( calculate place to print )\n\tr> ; ( restore index and address of string )\n\n: length ( c-addr u -- u : push the length of an ASCIIZ string )\n tuck 0 do dup c@ 0= if 2drop i leave then 1+ loop ;\n\n: asciiz? ( c-addr u -- : is a Forth string also a ASCIIZ string )\n\ttuck length <> ;\n\n: asciiz ( c-addr u -- : trim a string until NUL terminator )\n\t2dup length nip ;\n\n\n: (type) ( c-addr -- : emit a single character )\n\tc@ emit ;\n\n: type ( c-addr u -- : print out 'u' characters at c-addr )\n\t['] (type) foreach ;\nhide (type)\n\n: do-string ( char -- : write a string into the dictionary reading it until char is encountered )\n\t(.\")\n\tstate @ if swap [literal] [literal] then ;\n\n: fill ( c-addr u char -- : fill in an area of memory with a character, only if u is greater than zero )\n\t-rot\n\t0 do 2dup i + c! loop\n\t2drop ;\n\n: compare ( c-addr1 u1 c-addr2 u2 -- n : compare two strings, not quite compliant yet )\n\t>r swap r> min >r\n\tstart-address + swap start-address + r>\n\tmemory-compare ;\n\n128 string sbuf\n: s\" ( \"ccc\" --, Run Time -- c-addr u )\n\tkey drop sbuf 0 fill sbuf [char] \" accepter sbuf drop swap ;\nhide sbuf\n\n( @todo these strings really need rethinking, state awareness needs to be removed... )\n: type,\n\tstate @ if ' type , else type then ;\n\n: c\"\n\timmediate key drop [char] \" do-string ;\n\n: \"\n\timmediate key drop [char] \" do-string type, ;\n\n: sprint ( c -- : print out chars until 'c' is encountered )\n\tkey drop ( drop next space )\n\t>r ( save delimiter )\n\tbegin\n\t\tkey dup ( get next character )\n\t\trdup r> ( get delimiter )\n\t\t<> if emit 0 then\n\tuntil rdrop ;\n\n: .(\n\timmediate [char] ) sprint ;\nhide sprint\n\n: .\"\n\timmediate key drop [char] \" do-string type, ;\n\nhide type,\n\n( This word really should be removed along with any usages\nof this word, it is not a very \"Forth\" like word, it accepts\na pointer to an ASCIIZ string and prints it out, it also does\nnot checking of the returned values from write-file )\n: print ( c-addr -- : print out a string to the standard output )\n\t-1 over >r length r> swap stdout write-file 2drop ;\n\n: ok\n\t\" ok\" cr ;\n\n: empty-stack ( x-n ... x-0 -- : empty the variable stack )\n\tbegin depth while drop repeat ;\n\n: (quit) ( -- : do the work of quit, without the restart )\n\t0 `source-id ! ( set source to read from file )\n\t`stdin @ `fin ! ( read from stdin )\n\tpostpone [ ( back into command mode )\n\t' interpret start! ; ( set interpreter starting word )\n\n: quit ( -- : Empty return stack, go back to command mode, read from stdin, interpret input )\n\t(quit)\n\t-1 restart ; ( restart the interpreter )\n\n: abort\n\t-1 throw ;\n\n: (abort\") ( do the work of abort )\n\t(quit)\n\t-2 throw ;\n\n: abort\" immediate\n\tpostpone \"\n\t' cr , ' (abort\") , ;\n\n( ==================== CASE statements ======================= )\n( This simple set of words adds case statements to the\ninterpreter, the implementation is not particularly efficient,\nbut it works and is simple.\n\nBelow is an example of how to use the CASE statement,\nthe following word, \"example\" will read in a character and\nswitch to different statements depending on the character\ninput. There are two cases, when 'a' and 'b' are input, and\na default case which occurs when none of the statements match:\n\n\t: example\n\t\tchar\n\t\tcase\n\t\t\t[char] a of \" a was selected \" cr endof\n\t\t\t[char] b of \" b was selected \" cr endof\n\n\t\t\tdup \\ encase will drop the selector\n\t\t\t\" unknown char: \" emit cr\n\t\tendcase ;\n\n\texample a \\ prints \"a was selected\"\n\texample b \\ prints \"b was selected\"\n\texample c \\ prints \"unknown char: c\"\n\nOther examples of how to use case statements can be found\nthroughout the code.\n\nFor a simpler case statement see, Volume 2, issue 3, page 48\nof Forth Dimensions at http:\/\/www.forth.org\/fd\/contents.html )\n\n: case immediate\n\t?comp\n\t' branch , 3 cells , ( branch over the next branch )\n\there ' branch , ( mark: place endof branches back to with again )\n\t>mark swap ; ( mark: place endcase writes jump to with then )\n\n: over= ( x y -- [x 0] | 1 : )\n\tover = if drop 1 else 0 then ;\n\n: of\n\timmediate ?comp ' over= , postpone if ;\n\n: endof\n\timmediate ?comp over postpone again postpone then ;\n\n: endcase\n\timmediate ?comp ' drop , 1+ postpone then drop ;\n\n( ==================== CASE statements ======================= )\n\ndoer (banner)\nmake (banner) space\n\n: banner ( n -- : )\n\tdup 0<= if drop exit then\n\t0 do (banner) loop ;\n\n: zero ( -- : emit a single 0 character )\n\t[char] 0 emit ;\n\n: spaces ( n -- : print n spaces if n is greater than zero )\n\tmake (banner) space\n\tbanner ;\n\n: zeros ( n -- : print n spaces if n is greater than zero )\n\tmake (banner) zero\n\tbanner ;\n\nhide{ (banner) banner }hide\n\n: erase ( addr u : erase a block of memory )\n\t2chars> 0 fill ;\n\n: blank ( c-addr u : fills a string with spaces )\n\tbl fill ;\n\n( move should check that u is not negative )\n: move ( addr1 addr2 u -- : copy u words of memory from 'addr2' to 'addr1' )\n\t0 do\n\t\t2dup i + @ swap i + !\n\tloop\n\t2drop ;\n\n( It would be nice if move and cmove could share more code, as they do exactly\n the same thing but with different load and store functions, cmove> )\n: cmove ( c-addr1 c-addr2 u -- : copy u characters of memory from 'c-addr2' to 'c-addr1' )\n\t0 do\n\t\t2dup i + c@ swap i + c!\n\tloop\n\t2drop ;\n\n( ==================== Conditional Compilation =============== )\n( The words \"[if]\", \"[else]\" and \"[then]\" implement conditional\ncompilation, they can be nested as well\n\nSee http:\/\/lars.nocrew.org\/dpans\/dpans15.htm for more\ninformation\n\nA much simpler conditional compilation method is the following\nsingle word definition:\n\n : compile-line? 0= if [ find \\\\ , ] then ;\n\nWhich will skip a line if a conditional is false, and compile\nit if true )\n\n( These words really, really need refactoring, I could use the newly defined\n \"defer\" to help out with this )\n0 variable nest ( level of [if] nesting )\n0 variable [if]-word ( populated later with \"find [if]\" )\n0 variable [else]-word ( populated later with \"find [else]\")\n: [then] immediate ;\n: reset-nest 1 nest ! ;\n: unnest? [ find [then] ] literal = if nest 1-! then ;\n: nest? [if]-word @ = if nest 1+! then ;\n: end-nest? nest @ 0= ;\n: match-[else]? [else]-word @ = nest @ 1 = and ;\n\n: [if] ( bool -- : conditional execution )\n\t?exec\n\tunless\n\t\treset-nest\n\t\tbegin\n\t\t\tfind\n\t\t\tdup nest?\n\t\t\tdup match-[else]? if drop exit then\n\t\t\t unnest?\n\t\t\tend-nest?\n\t\tuntil\n\tthen ;\n\n: [else] ( discard input until [then] encounter, nesting for [if] )\n\t?exec\n\treset-nest\n\tbegin\n\t\tfind\n\t\tdup nest? unnest?\n\t\tend-nest?\n\tuntil ;\n\nfind [if] [if]-word !\nfind [else] [else]-word !\n\n: ?( if postpone ( then ; \\ conditionally read until ')'\n: ?\\ if postpone \\ then ;\n: 16bit\\ size 2 <> if postpone \\ then ;\n: 32bit\\ size 4 <> if postpone \\ then ;\n: 64bit\\ size 8 <> if postpone \\ then ;\n\nhide{\n\t[if]-word [else]-word nest\n\treset-nest unnest? match-[else]?\n\tend-nest? nest?\n}hide\n\n( ==================== Conditional Compilation =============== )\n\n( ==================== Endian Words ========================== )\n( This words are allow the user to determinate the endianess\nof the machine that is currently being used to execute libforth,\nthey make heavy use of conditional compilation )\n\nsize 2 = [if] 0x0123 `x ! [then]\nsize 4 = [if] 0x01234567 `x ! [then]\nsize 8 = [if] 0x01234567abcdef `x ! [then]\n\n: endian ( -- bool : returns the endianess of the processor, little = 0, big = 1 )\n\t[ `x chars> c@ 0x01 = ] literal ;\n\n: swap16 ( x -- x : swap the byte order a 16 bit number )\n\tdup 256* 0xff00 and >r 256\/ lsb r> or ;\n\nsize 4 >= [if]\n\t: swap32\n\t\tdup 0xffff and swap16 16 lshift swap\n\t\t16 rshift 0xffff and swap16 or ;\n[then]\n\nsize 8 >= [if]\n\t: swap64 ( x -- x : swap the byte order of a 64 bit number )\n\t\t dup 0xffffffff and swap32 32 lshift swap\n\t\t 32 rshift 0xffffffff and swap32 or ;\n[then]\n\nsize 2 = [if]\n\tendian\n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order )\n\t\tswap16 ;\n\t: >big ( x -- x : host byte order to big endian order )\n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order )\n\t\t;\n\t: >big ( x -- x : host byte order to big endian order )\n\t\tswap16 ;\n\t[then]\n[then]\n\nsize 4 = [if]\n\tendian\n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order )\n\t\tswap32 ;\n\t: >big ( x -- x : host byte order to big endian order )\n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order )\n\t\t;\n\t: >big ( x -- x : host byte order to big endian order )\n\t\tswap32 ;\n\t[then]\n[then]\n\nsize 8 = [if]\n\tendian\n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order )\n\t\tswap64 ;\n\t: >big ( x -- x : host byte order to big endian order )\n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order )\n\t\t;\n\t: >big ( x -- x : host byte order to big endian order )\n\t\tswap64 ;\n\t[then]\n[then]\n\n( ==================== Endian Words ========================== )\n\n( ==================== Misc words ============================ )\n\n: (base) ( -- base : unmess up libforth's base variable )\n\tbase @ dup 0= if drop 10 then ;\n\n: #digits ( u -- u : number of characters needed to represent 'u' in current base )\n\tdup 0= if 1+ exit then\n\t(base) log 1+ ;\n\n: digits ( -- u : number of characters needed to represent largest unsigned number in current base )\n\t-1 #digits ;\n\n: cdigits ( -- u : number of characters needed to represent largest characters in current base )\n\t0xff #digits ;\n\n: .r ( u -- print a number taking up a fixed amount of space on the screen )\n\tdup #digits digits swap - spaces . ;\n\n: ?.r ( u -- : print out address, right aligned )\n\t@ .r ;\n\n0 variable counter\n\n: counted-column ( index -- : special column printing for dump )\n\tcounter @ column-width @ mod\n\tnot if cr .r \" :\" space else drop then\n\tcounter 1+! ;\n\n: .chars ( x n -- : print a cell out as characters, upto n chars )\n\t0 ( from zero to the size of a cell )\n\tdo\n\t\tdup ( copy variable to print out )\n\t\tsize i 1+ - select-byte ( select correct byte )\n\t\tdup printable? not ( is it not printable )\n\t\tif drop [char] . then ( print a '.' if it is not )\n\t\temit ( otherwise print it out )\n\tloop\n\tdrop ; ( drop cell we have printed out )\n\n: lister ( addr u addr -- )\n\t0 counter ! 1- swap\n\tdo\n\t\tdup counted-column 1+ i ?.r i @ size .chars space\n\tloop ;\n\n( @todo this function should make use of DEFER and IS, then different\nversion of dump could be made that swapped out LISTER )\n: dump ( addr u -- : dump out 'u' cells of memory starting from 'addr' )\n\t1+ over + under lister drop\n\tcr ;\n\nhide{ counted-column counter }hide\n\n( Fence can be used to prevent any word defined before it from being forgotten\nUsage:\n\there fence ! )\n0 variable fence\n\n: ?fence ( addr -- : throw an exception of address is before fence )\n\tfence @ u< if -15 throw then ;\n\n: (forget) ( pwd-token -- : forget a found word and everything after it )\n\tdup 0= if -15 throw then ( word not found! )\n\tdup ?fence\n\tdup @ pwd ! h ! ;\n\n: forget ( c\" xxx\" -- : forget word and every word defined after it )\n\tfind 1- (forget) ;\n\n0 variable fp ( FIND Pointer )\n\n: rendezvous ( -- : set up a rendezvous point )\n\there ?fence\n\there fence !\n\tlatest fp ! ;\n\n: retreat ( -- : retreat to the rendezvous point, forgetting any words )\n\tfence @ h !\n\tfp @ pwd ! ;\n\nhide{ fp }hide\n\n: marker ( c\" xxx\" -- : make word the forgets itself and words after it)\n\t:: latest [literal] ' (forget) , (;) ;\nhere fence ! ( This should also be done at the end of the file )\nhide (forget)\n\n: ** ( b e -- x : exponent, raise 'b' to the power of 'e')\n\t?dup-if\n\t\tover swap\n\t\t1 do over * loop\n\t\tnip\n\telse\n\t\tdrop 1\n\tthen ;\n\n0 variable a\n0 variable b\n0 variable m\n: equal ( a1...an b1...bn n -- a1...an b1...bn bool : determine if two lists are equal )\n\t( example:\n\t\t1 2 3\n\t\t1 2 3\n\t\t3 equal\n\treturns: 1 )\n\tdup m ! 1+ 1 ( store copy of length and use as loop index )\n\tdo\n\t\ti 1- pick b ! ( store ith element of list in b1...bn )\n\t\ti m @ + 1- pick a ! ( store ith element of list in a1...an )\n\t\ta @ b @ <> ( compare a and b for equality )\n\t\tif 0 leave then ( unequal, finish early )\n\tloop 1 ; ( lists must be equal )\n\nhide{ a b m }hide\n\n: ndrop ( u1...un n -- : drop n items )\n\t?dup-if 0 do drop loop then ;\n\n: caesar ( c key -- o : encode a alphabetic character with a key using a generalization of the Caesar cipher )\n\t>r\n\tdup uppercase? if [char] A - r> + 26 mod [char] A + exit then\n\tdup lowercase? if [char] a - r> + 26 mod [char] a + exit then\n\trdrop ; ( it goes without saying that this should not be used for anything serious! )\n\n: caesar-type ( c-addr u key : type out encoded text with a Caesar cipher )\n\t-rot bounds do i c@ over caesar emit loop drop ;\n\n: rot13 ( c -- c : encode a character with ROT-13 )\n\t13 caesar ;\n\n: rot13-type ( c-addr u : print string in ROT-13 encoded form )\n\t13 caesar-type ;\n\n\\ s\" abcdefghijklmnopqrstuvwxyz\" rot13-type -> nopqrstuvwxyzabcdefghijklm\n\\ s\" hello\" rot13-type -> uryyb\n\n( ==================== Misc words ============================ )\n\n( ==================== Pictured Numeric Output =============== )\n( Pictured numeric output is what Forths use to display\nnumbers to the screen, this Forth has number output methods\nbuilt into the Forth kernel and mostly uses them instead,\nbut the mechanism is still useful so it has been added.\n\n@todo Pictured number output should act on a double cell\nnumber not a single cell number )\n\n0 variable hld\n\n: overflow ( -- : check if we overflow the hold area )\n \there chars> pad chars> hld @ - u> if -17 throw then ;\n\n: hold ( char -- : add a character to the numeric output string )\n\toverflow pad chars> hld @ - c! hld 1+! ;\n\n: holds ( c-addr u -- : hold an entire string )\n begin dup while 1- 2dup + c@ hold repeat 2drop ;\n\n: <# ( -- : setup pictured numeric output )\n\t0 hld ! ;\n\n: sign ( -- : add a sign to the pictured numeric output string )\n\t[char] - hold ;\n\n: # ( x -- x : divide x by base, turn into a character, put in pictured output string )\n\t(base) um\/mod swap\n \tdup 9 u>\n \tif 7 + then\n \t48 + hold ;\n\n: #s ( x -- 0 : repeatedly call # on x until x is zero )\n\tbegin # dup 0= until ;\n\n: #> ( -- c-addr u : end pictured output conversion, push output string to stack )\n\t0 hold ( NUL terminate string, just in case )\n\thld 1-! ( but do not include that in the count )\n\tpad chars> hld @\n\ttuck - 1+ swap ;\n\ndoer characters\nmake characters spaces\n\n: u.rc\n\t>r <# #s #> rot drop r> over - characters type ;\n\n: u.r ( u n -- print a number taking up a fixed amount of space on the screen )\n\tmake characters spaces u.rc ;\n\n: u.rz ( u n -- print a number taking up a fixed amount of space on the screen, using leading zeros )\n\tmake characters zeros u.rc ;\n\n: u. ( u -- : display an unsigned number in current base )\n\t0 u.r ;\n\nhide{ overflow u.rc characters }hide\n\n( ==================== Pictured Numeric Output =============== )\n\n( ==================== Numeric Input ========================= )\n( The Forth executable can handle numeric input and does not\nneed the routines defined here, however the user might want\nto write routines that use >NUMBER. >NUMBER is a generic word,\nbut it is a bit difficult to use on its own. )\n\n: map ( char -- n|-1 : convert character in 0-9 a-z range to number )\n\tdup lowercase? if [char] a - 10 + exit then\n\tdup decimal? if [char] 0 - exit then\n\tdrop -1 ;\n\n: number? ( char -- bool : is a character a number in the current base )\n\t>lower map (base) u< ;\n\n: >number ( n c-addr u -- n c-addr u : convert string )\n\tbegin\n\t\t( get next character )\n\t\t2dup >r >r drop c@ dup number? ( n char bool, R: c-addr u )\n\t\tif ( n char )\n\t\t\tswap (base) * swap map + ( accumulate number )\n\t\telse ( n char )\n\t\t\tdrop\n\t\t\tr> r> ( restore string )\n\t\t\texit\n\t\tthen\n\t\tr> r> ( restore string )\n\t\t1 \/string dup 0= ( advance string and test for end )\n\tuntil ;\n\nhide{ map }hide\n\n( ==================== Numeric Input ========================= )\n\n( ==================== ANSI Escape Codes ===================== )\n( Terminal colorization module, via ANSI Escape Codes\n\nsee: https:\/\/en.wikipedia.org\/wiki\/ANSI_escape_code\nThese codes will provide a relatively portable means of\nmanipulating a terminal )\n\n27 constant 'escape'\n: CSI 'escape' emit .\" [\" ;\n0 constant black\n1 constant red\n2 constant green\n3 constant yellow\n4 constant blue\n5 constant magenta\n6 constant cyan\n7 constant white\n: foreground 30 + ;\n: background 40 + ;\n0 constant dark\n1 constant bright\nfalse variable colorize\n\n: 10u. ( n -- : print a number in decimal )\n\tbase @ >r decimal u. r> base ! ;\n\n: color ( brightness color-code -- : set the terminal color )\n\t( set color on an ANSI compliant terminal,\n\tfor example:\n\t\tbright red foreground color\n\tsets the foreground text to bright red )\n\tcolorize @ 0= if 2drop exit then\n\tCSI 10u. if .\" ;1\" then .\" m\" ;\n\n: at-xy ( x y -- : set ANSI terminal cursor position to x y )\n\tCSI 10u. [char] ; emit 10u. .\" H\" ;\n\n: page ( -- : clear ANSI terminal screen and move cursor to beginning )\n\tCSI .\" 2J\" 1 1 at-xy ;\n\n: hide-cursor ( -- : hide the cursor from view )\n\tCSI .\" ?25l\" ;\n\n: show-cursor ( -- : show the cursor )\n\tCSI .\" ?25h\" ;\n\n: save-cursor ( -- : save cursor position )\n\tCSI .\" s\" ;\n\n: restore-cursor ( -- : restore saved cursor position )\n\tCSI .\" u\" ;\n\n: reset-color ( -- : reset terminal color to its default value)\n\tcolorize @ 0= if exit then\n\tCSI .\" 0m\" ;\n\nhide{ CSI 10u. }hide\n( ==================== ANSI Escape Codes ===================== )\n\n( ==================== Unit test framework =================== )\n\n256 string estring ( string to test )\n0 variable #estring ( actual string length )\n0 variable start ( starting depth )\n0 variable result ( result depth )\n0 variable check ( only check depth if -> is called )\n0 variable dictionary ( dictionary pointer on entering { )\n0 variable previous ( PWD register on entering { )\n\n: T ; ( hack until T{ can process words )\n\n: -> ( -- : save depth in variable )\n\t1 check ! depth result ! ;\n\n: test estring drop #estring @ ;\n\n: fail ( -- : invalidate the forth interpreter and exit )\n\tinvalidate bye ;\n\n: neutral ( -- : neutral color )\n\t;\n\n: bad ( -- : bad color )\n\tdark red foreground color ;\n\n: good ( -- : good color )\n\tdark green foreground color ;\n\n: die bad test type reset-color cr fail ;\n\n: evaluate? ( bool -- : test if evaluation has failed )\n\tif .\" evaluation failed\" cr fail then ;\n\n: failed bad .\" failed\" reset-color cr ;\n\n: adjust ( x -- x : adjust a depth to take into account starting depth )\n\tstart @ - ;\n\n: no-check? ( -- bool : if true we need to check the depth )\n\tcheck @ 0= ;\n\n: depth? ( -- : check if depth is correct )\n\tno-check? if exit then\n\tdepth adjust ( get depth and adjust for starting depth )\n\tresult @ adjust 2* = ( get results depth, same adjustment, should be\n\t half size of the depth )\n\tif exit then ( pass )\n\tfailed\n\t.\" Unequal depths:\" cr\n\t.\" depth: \" depth . cr\n\t.\" result: \" result @ . cr\n\tdie ;\n\n: equal? ( -- : determine if results equals expected )\n\tno-check? if exit then\n\tresult @ adjust equal\n\tif exit then\n\tfailed\n\t.\" Result is not equal to expected values. \" cr\n\t.\" Stack: \" cr .s cr\n\tdie ;\n\n: display ( c-addr u -- : print out testing message in estring )\n\tverbose if neutral type else 2drop then ;\n\n: pass ( -- : print out passing message )\n\tverbose if good .\" ok \" cr reset-color then ;\n\n: save ( -- : save current dictionary )\n\tpwd @ previous !\n\there dictionary ! ;\n\n: restore ( -- : restore dictionary )\n\tprevious @ pwd !\n\tdictionary @ h ! ;\n\n\n: T{ ( -- : perform a unit test )\n\tdepth start ! ( save start of stack depth )\n\t0 result ! ( reset result variable )\n\t0 check ! ( reset check variable )\n\testring 0 fill ( zero input string )\n\tsave ( save dictionary state )\n\tkey drop ( drop next character, which is a space )\n\testring [char] } accepter #estring ! ( read in string to test )\n\ttest display ( print which string we are testing )\n\ttest evaluate ( perform test )\n\tevaluate? ( evaluate successfully? )\n\tdepth? ( correct depth )\n\tequal? ( results equal to expected values? )\n\tpass ( print pass message )\n\tresult @ adjust 2* ndrop ( remove items on stack generated by test )\n\trestore ; ( restore dictionary to previous state )\n\nT{ }T\nT{ -> }T\nT{ 1 -> 1 }T\nT{ 1 2 -> 1 2 }T\nT{ : c 1 2 ; c -> 1 2 }T\n( @bug ';' smudges the previous word, but :noname does\nnot. )\nT{ :noname 2 ; :noname 3 + ; compose execute -> 5 }T\n\nhide{\n\tpass test display\n\tadjust start save restore dictionary previous\n\tevaluate? equal? depth? estring #estring result\n\tcheck no-check? die neutral bad good failed\n}hide\n\n( ==================== Unit test framework =================== )\n\n\n( ==================== Pseudo Random Numbers ================= )\n( This section implements a Pseudo Random Number generator, it\nuses the xor-shift algorithm to do so.\nSee:\nhttps:\/\/en.wikipedia.org\/wiki\/Xorshift\nhttp:\/\/excamera.com\/sphinx\/article-xorshift.html\nhttp:\/\/xoroshiro.di.unimi.it\/\nhttp:\/\/www.arklyffe.com\/main\/2010\/08\/29\/xorshift-pseudorandom-number-generator\/\n\nThe constants used have been collected from various places\non the web and are specific to the size of a cell. )\n\nsize 2 = [if] 13 constant a 9 constant b 7 constant c [then]\nsize 4 = [if] 13 constant a 17 constant b 5 constant c [then]\nsize 8 = [if] 12 constant a 25 constant b 27 constant c [then]\n\n7 variable seed ( must not be zero )\n\n: seed! ( x -- : set the value of the PRNG seed )\n\tdup 0= if drop 7 ( zero not allowed ) then seed ! ;\n\n: random ( -- x : assumes word size is 32 bit )\n\tseed @\n\tdup a lshift xor\n\tdup b rshift xor\n\tdup c lshift xor\n\tdup seed! ;\n\nhide{ a b c seed }hide\n\n( ==================== Random Numbers ======================== )\n\n( ==================== Prime Numbers ========================= )\n( From original \"third\" code from the IOCCC at\nhttp:\/\/www.ioccc.org\/1992\/buzzard.2.design, the module works\nout and prints prime numbers. )\n\n: prime? ( u -- u | 0 : return number if it is prime, zero otherwise )\n\tdup 1 = if 1- exit then\n\tdup 2 = if exit then\n\tdup 2\/ 2 ( loop from 2 to n\/2 )\n\tdo\n\t\tdup ( value to check if prime )\n\t\ti mod ( mod by divisor )\n\t\tnot if\n\t\t\tdrop 0 leave\n\t\tthen\n\tloop ;\n\n0 variable counter\n\n: primes ( x1 x2 -- : print the primes from x2 to x1 )\n\t0 counter !\n\t\" The primes from \" dup . \" to \" over . \" are: \"\n\tcr\n\tcolumn.reset\n\tdo\n\t\ti prime?\n\t\tif\n\t\t\ti . counter @ column counter 1+!\n\t\tthen\n\tloop\n\tcr\n\t\" There are \" counter @ . \" primes.\"\n\tcr ;\n\nhide{ counter }hide\n( ==================== Prime Numbers ========================= )\n\n( ==================== Debugging info ======================== )\n( This section implements various debugging utilities that the\nprogrammer can use to inspect the environment and debug Forth\nwords. )\n\n( String handling should really be done with PARSE, and CMOVE )\n: sh ( cnl -- ior : execute a line as a system command )\n\tnl word count system ;\n\nhide{ .s }hide\n: .s ( -- : print out the stack for debugging )\n\t[char] < emit depth (.) drop [char] > emit space\n\tdepth if\n\t\tdepth 0 do i column tab depth i 1+ - pick . loop\n\tthen\n\tcr ;\n\n1 variable hide-words ( do we want to hide hidden words or not )\n\n: name ( PWD -- c-addr : given a pointer to the PWD field of a word get a pointer to the name of the word )\n\tdup 1+ @ 256\/ word-mask and lsb - chars> ;\n\n( This function prints out all of the defined words, excluding\nhidden words. An understanding of the layout of a Forth word\nhelps here. The dictionary contains a linked list of words,\neach forth word has a pointer to the previous word until the\nfirst word. The layout of a Forth word looks like this:\n\nNAME: Forth Word - A variable length ASCII NUL terminated\n string.\nPWD: Previous Word Pointer, points to the previous\n word.\nCODE: Flags, code word and offset from previous word\n pointer to start of Forth word string.\nDATA: The body of the forth word definition, not interested\n in this.\n\nThere is a register which stores the latest defined word which\ncan be accessed with the code \"pwd @\". In order to print out\na word we need to access a words CODE field, the offset to\nthe NAME is stored here in bits 8 to 14 and the offset is\ncalculated from the PWD field.\n\n\"print\" expects a character address, so we need to multiply\nany calculated address by the word size in bytes. )\n\n: words.immediate ( bool -- : emit or mark a word being printed as being immediate )\n\tnot if dark red foreground color then ;\n\n: words.defined ( bool -- : emit or mark a word being printed as being a built in word )\n\tnot if bright green background color then ;\n\n: words.hidden ( bool -- : emit or mark a word being printed as being a hidden word )\n\tif dark magenta foreground color then ;\n\n: words ( -- : print out all defined an visible words )\n\tlatest\n\tspace\n\tbegin\n\t\tdup\n\t\thidden? hide-words @ and\n\t\tnot if\n\t\t\thidden? words.hidden\n\t\t\tcompiling? words.immediate\n\t\t\tdup defined-word? words.defined\n\t\t\tname\n\t\t\tprint space\n\t\t\treset-color\n\t\telse\n\t\t\tdrop\n\t\tthen\n\t\t@ ( Get pointer to previous word )\n\t\tdup dictionary-start u< ( stop if pwd no longer points to a word )\n\tuntil\n\tdrop cr ;\n\n( Simpler version of words\n: words\n\tpwd @\n\tbegin\n\t\tdup name print space @ dup dictionary-start u<\n\tuntil drop cr ; )\n\nhide{ words.immediate words.defined words.hidden hidden? hidden-bit }hide\n\n: TrueFalse ( bool -- : print true or false )\n\tif \" true\" else \" false\" then ;\n\n: registers ( -- : print out important registers and information about the virtual machine )\n\t\" return stack pointer: \" r@ . cr\n\t\" dictionary pointer \" here . cr\n\t\" previous word: \" pwd ? cr\n\t\" state: \" state ? cr\n\t\" base: \" base ? cr\n\t\" depth: \" depth . cr\n\t\" cell size (in bytes): \" size . cr\n\t\" last cell address: \" max-core . cr\n\t\" unused cells: \" unused . cr\n\t\" invalid: \" `invalid @ TrueFalse cr\n\t\" size of variable stack: \" `stack-size ? cr\n\t\" size of return stack: \" `stack-size ? cr\n\t\" start of variable stack: \" max-core `stack-size @ 2* - . cr\n\t\" start of return stack: \" max-core `stack-size @ - . cr\n\t\" current input source: \" source-id -1 = if \" string\" else \" file\" then cr\n\t\" tracing on: \" `debug @ TrueFalse cr\n\t\" starting word: \" `instruction ? cr\n\t\" real start address: \" `start-address ? cr\n\t\" error handling: \" `error-handler ? cr\n\t\" throw handler: \" `handler ? cr\n\t\" signal recieved: \" `signal ? cr ;\n\t\n( `sin `sidx `slen `fout\n `stdout `stderr `argc `argv )\n\n\n: y\/n? ( -- bool : ask a yes or no question )\n\tkey drop\n\t\" y\/n? \"\n\tbegin\n\t\tkey\n\t\tdup\n\t\t[char] y = if true exit then\n\t\t[char] n = if false exit then\n\t\t\" y\/n? \"\n\tagain ;\n\n: step\n\t( step through a word: this word could be augmented\n\twith commands such as \"dump\", \"halt\", and optional\n\t\".s\" and \"registers\" )\n\tregisters\n\t\" .s: \" .s cr\n\t\" -- press any key to continue -- \"\n\tkey drop ;\n\n: more ( -- : wait for more input )\n\t\" -- press any key to continue -- \" key drop cr page ;\n\n: debug-help ( -- : print out the help for the debug command )\n \" debug mode commands\n\th - print help\n\tq - exit interpreter word\n\tr - print registers\n\ts - print stack\n\tR - print return stack\n\tc - continue on with execution\n\" ;\n\ndoer debug-prompt\n: prompt-default\n\t.\" debug> \" ;\n\nmake debug-prompt prompt-default\n\n: debug ( -- : enter interactive debug prompt )\n\tcr\n\t\" Entered Debug Prompt. Type 'h' for help. \" cr\n\tbegin\n\t\tkey\n\t\tcase\n\t\t\tnl of debug-prompt endof\n\t\t\t[char] h of debug-help endof\n\t\t\t[char] q of bye endof\n\t\t\t[char] r of registers endof\n\t\t\t[char] s of .s endof\n\t\t\t[char] R of r.s endof\n\t\t\t[char] c of exit endof\n\t\t\t( @todo add throw here )\n\t\tendcase\n\tagain ;\nhide debug-prompt\n\n: code>pwd ( CODE -- PWD\/0 : calculate PWD from code address )\n\tdup dictionary-start here within not if drop 0 exit then\n\t1 cells - ;\n\n: word-printer ( CODE -- : print out a words name given its code field )\n\tdup 1 cells - @ -1 = if . \" noname\" exit then ( nonames are marked by a -1 before its code field )\n\tdup code>pwd ?dup-if .d name print else drop \" data\" then\n\t drop ;\n\nhide{ code>pwd }hide\n\n( these words push the execution tokens for various special\ncases for decompilation )\n: get-branch [ find branch ] literal ;\n: get-?branch [ find ?branch ] literal ;\n: get-original-exit [ find _exit ] literal ;\n: get-quote [ find ' ] literal ;\n\n( @todo replace 2- nos1+ nos1+ with appropriate word, like\nthe string word that increments a string by an amount, but\nthat operates on CELLS )\n: branch-increment ( addr branch -- increment : calculate decompile increment for \"branch\" )\n\t1+ dup negative?\n\tif\n\t\tover cr . [char] : emit space . cr 2\n\telse\n\t\t2dup 2- nos1+ nos1+ dump\n\tthen ;\n\n( these words take a code field to a primitive they implement,\ndecompile it and any data belonging to that operation, and push\na number to increment the decompilers code stream pointer by )\n\n: decompile-literal ( code -- increment )\n\t1+ ? \" literal\" 2 ;\n\n: decompile-branch ( code -- increment )\n\tdark red foreground color\n\t1+ ? \" branch \" dup 1+ @ branch-increment ;\n\n: decompile-quote ( code -- increment )\n\tdark green foreground color\n\tdup\n\t[char] ' emit 1+ @ word-printer 2 reset-color ;\n\n: decompile-?branch ( code -- increment )\n\t1+ ? \" ?branch\" 2 ;\n\n: decompile-exit ( code -- 0 )\n\t\" _exit\" cr \" End of word: \" . 0 ;\n\n( The decompile word expects a pointer to the code field of\na word, it decompiles a words code field, it needs a lot of\nwork however. There are several complications to implementing\nthis decompile function.\n\n\t'\t The next cell should be pushed\n\n\t:noname This has a marker before its code field of\n\t -1 which cannot occur normally, this is\n\t handled in word-printer\n\n\tbranch\t branches are used to skip over data, but\n\t also for some branch constructs, any data\n\t in between can only be printed out\n\t generally speaking\n\n\texit\t There are two definitions of exit, the one\n\t used in ';' and the one everything else uses,\n\t this is used to determine the actual end\n\t of the word\n\n\tliterals Literals can be distinguished by their\n\t low value, which cannot possibly be a word\n\t with a name, the next field is the\n\t actual literal\n\nOf special difficult is processing IF, THEN and ELSE\nstatements, this will require keeping track of '?branch'.\n\nAlso of note, a number greater than \"here\" must be data )\n\n: decompile ( code-pointer -- code-pointer increment|0 : )\n\t.d [char] : emit space dup @\n\tcase\n\t\tdolit of dup decompile-literal cr endof\n\t\tget-branch of dup decompile-branch endof\n\t\tget-quote of dup decompile-quote cr endof\n\t\tget-?branch of dup decompile-?branch cr endof\n\t\tget-original-exit of dup decompile-exit endof\n\t\tdup word-printer 1 swap cr\n\tendcase reset-color ;\n\n: decompiler ( code-field-ptr -- : decompile a word in its entirety )\n\tbegin decompile over + tuck = until drop ;\n\nhide{\n\tword-printer get-branch get-?branch get-original-exit\n\tget-quote branch-increment decompile-literal\n\tdecompile-branch decompile-?branch decompile-quote\n\tdecompile-exit\n}hide\n\n( these words expect a pointer to the PWD field of a word )\n: see.name \" name: \" name print cr ;\n: see.start \" word start: \" name chars . cr ;\n: see.previous \" previous word: \" @ . cr ;\n: see.immediate \" immediate: \" compiling? nip not TrueFalse cr ;\n: see.instruction \" instruction: \" xt-instruction . cr ;\n: see.defined \" defined: \" defined-word? TrueFalse cr ;\n\n: see.header ( PWD -- is-immediate-word? )\n\tdup see.name\n\tdup see.start\n\tdup see.previous\n\tdup see.immediate\n\tdup see.instruction ( @todo look up instruction name )\n\tsee.defined ;\n\n( @todo This does not work for all words, so needs fixing.\n Specifically:\n\n\t2variable\n\t2constant\n\ttable\n\tconstant\n\tvariable\n\tarray\nWhich are all complex CREATE words\n\nA good way to test decompilation is with the following\nUnix pipe:\n\n\t.\/forth -f forth.fth -e words\n\t\t| sed 's\/ \/ see \/g'\n\t\t| .\/forth -t forth.fth &> decompiled.log\n)\n\n( @todo refactor into word that takes a PWD pointer and one that attempts to parse\/find name )\n: see ( c\" xxx\" -- : decompile a word )\n\tfind\n\tdup 0= if -32 throw then\n\tcell- ( move to PWD field )\n\tdup see.header\n\tdup defined-word?\n\tif ( decompile if a compiled word )\n\t\t2 cells + ( move to code field )\n\t\t\" code field:\" cr\n\t\tdecompiler\n\telse ( the instruction describes the word if it is not a compiled word )\n\t\tdup 1 cells + @ instruction-mask and doconst = if ( special case for constants )\n\t\t\t\" constant: \" 2 cells + @ .\n\t\telse\n\t\t\tdrop\n\t\tthen\n\tthen cr ;\n\n( @todo This has a bug, if any data within a word happens\nto match the address of _exit word.end calculates the wrong\naddress, this needs to mirror the DECOMPILE word )\n: word.end ( addr -- addr : find the end of a word )\n\tbegin\n\t\tdup\n\t\t@ [ find _exit ] literal = if exit then\n\t\tcell+\n\tagain ;\n\n: (inline) ( xt -- : inline an word from its execution token )\n\tdup cell- defined-word? if\n\t\tcell+\n\t\tdup word.end over - here -rot dup allot move\n\telse\n\t\t,\n\tthen ;\n\n: ;inline ( -- : terminate :inline )\n\timmediate -22 throw ;\n\n: :inline immediate\n\t?comp\n\tbegin\n\t\tfind found?\n\t\tdup [ find ;inline ] literal = if\n\t\t\tdrop exit ( terminate :inline )\n\t\tthen\n\t\t(inline)\n\tagain ;\n\nhide{\n\tsee.header see.name see.start see.previous see.immediate\n\tsee.instruction defined-word? see.defined _exit found?\n\t(inline) word.end\n}hide\n\n( These help messages could be moved to blocks, the blocks\ncould then be loaded from disk and printed instead of defining\nthe help here, this would allow much larger help )\n\n: help ( -- : print out a short help message )\n\tpage\n\tkey drop\n\" Welcome to Forth, an imperative stack based language. It is\nboth a low level and a high level language, with a very small\nmemory footprint. Most of Forth is defined as a combination\nof various primitives.\n\nA short description of the available function (or Forth words)\nfollows, words marked (1) are immediate and cannot be used in\ncommand mode, words marked with (2) define new words. Words\nmarked with (3) have both command and compile functionality.\n\n\"\nmore \" Some of the built in words that accessible are:\n\n(1,2)\t: define a new word, switching to compile mode\n\timmediate make latest defined word immediate\n\tread read in a word, execute in command mode else compile\n\t@ ! fetch, store\n\tc@ c! character based fetch and store\n\t- + * \/ standard arithmetic operations,\n\tand or xor invert standard bitwise operations\n\tlshift rshift left and right bit shift\n\tu< u> < > = comparison predicates\n\texit exit from a word\n\temit print character from top of stack\n\tkey get a character from input\n\tr> >r pop a value from or to the return stack\n\tfind find a word in the dictionary and push the location\n\t' store the address of the following word on the stack\n\t, write the top of the stack to the dictionary\n\tswap swap first two values on the stack\n\tdup duplicate the top of the stack\n\tdrop pop and drop a value\n\tover copy the second stack value over the first\n\t. pop the top of the stack and print it\n\"\nmore \"\n\tprint print a NUL terminated string at a character address\n\tdepth get the current stack depth\n\tclock get the time since execution start in milliseconds\n\tevaluate evaluate a string\n\tsystem execute a system command\n\tclose-file close a file handle\n\topen-file open a file handle\n\tdelete-file delete a file off disk given a string\n\tread-file read in characters from a file\n\twrite-file write characters to a file\n\tfile-position get the file offset\n\treposition-file reposition the file pointer\n\tflush-file flush a file to disk\n\trename-file rename a file on disk\n \"\n\nmore \" All of the other words in the interpreter are built\nfrom these primitive words. A few examples:\n\n(1)\tif...else...then FORTH branching construct\n(1)\tbegin...until loop until top of stack is non zero\n(1)\tbegin...again infinite loop\n(1)\tdo...loop FORTH looping construct\n(2,3)\tcreate create a new word that pushes its location\n(1)\tdoes> declare a created words run time behaviour\n(1,2)\tvariable declare variable with initial value from top of stack\n(1,2)\tconstant declare a constant, taken from top of stack\n(1,2)\tarray declare an array with size taken from top of stack\n(1)\t; terminate a word definition and return to command mode\n\twords print out a list of all the defined words\n\thelp this help message\n\tdump print out memory contents starting at an address\n\tregisters print out the contents of the registers\n\tsee decompile a word, viewing what words compose it\n\t.s print out the contents of the stack\n\n\"\n\nmore \" Some more advanced words:\n\n\there push the dictionary pointer\n\th push the address of the dictionary pointer\n\tr push the return stack pointer\n\tallot allocate space in the dictionary\n(1)\t[ switch to command mode\n\t] switch to compile mode\n\t:: compile ':' into the dictionary\n\n\" more \"\nFor more information either consult the manual pages forth(1)\nand libforth(1) or consult the following sources:\n\n\thttps:\/\/github.com\/howerj\/libforth\n\thttp:\/\/work.anapnea.net\/html\/html\/projects.html\n\nAnd for a larger tutorial:\n\n\thttps:\/\/github.com\/howerj\/libforth\/blob\/master\/readme.md\n\nFor resources on Forth:\n\n\thttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\thttps:\/\/rwmj.wordpress.com\/2010\/08\/07\/jonesforth-git-repository\/\n\n -- end --\n\" cr\n;\n\n( ==================== Debugging info ======================== )\n\n( ==================== Files ================================= )\n( These words implement more of the standard file access words\nin terms of the ones provided by the virtual machine. These\nwords are not the most easy to use words, although the ones\ndefined here and the ones that are part of the interpreter are\nthe standard ones.\n\nSome thoughts:\n\nI believe extensions to this word set, once I have figured\nout the semantics, should be made to make them easier to use,\nones which automatically clean up after failure and call throw\nwould be more useful [and safer] when dealing with a single\ninput or output stream. The most common action after calling\none of the file access words is to call throw any way.\n\nFor example, a word like:\n\n\t: #write-file \\ c-addr u fileid -- fileid u\n\t\tdup >r\n\t\twrite-file dup if r> close-file throw throw then\n\t\tr> swap ;\n\nWould be easier to deal with, it preserves the file identifier\nand throws if there is any problem. It would be a bit more\ndifficult to use when there are two files open at a time.\n\n@todo implement the other file access methods in terms of the\nbuilt in ones.\n@todo read-line and write-line need their flag and ior setting\ncorrectly\n\n\tFILE-SIZE [ use file-positions ]\n\nAlso of note, Source ID needs extending.\n\nSee: [http:\/\/forth.sourceforge.net\/std\/dpans\/dpans11.htm] )\n\n: read-char ( c-addr fileid -- ior : read a char )\n\t1 swap read-file 0<> swap 1 <> or ;\n\n0 variable x\n\n: getchar ( fileid -- char ior )\n\tx chars> swap read-char x chars> c@ swap ;\n\n: write-char ( c-addr fileid -- ior : write a char )\n\t1 swap write-file 0<> swap 1 <> or ;\n\n: putchar ( char fileid -- ior )\n\tswap x chars> c! x chars> swap write-char ;\n\nhide{ x }hide\n\n: rewind-file ( file-id -- : rewind a file to the beginning )\n\t0 reposition-file throw ;\n\n: read-line ( c-addr u1 fileid -- u2 flag ior : read in a line of text )\n\t-rot bounds\n\tdo\n\t\tdup i swap read-char drop\n\t\ti c@ nl = if drop i 0 0 leave then\n\tloop drop ;\n\n: write-line ( c-addr u fileid -- u2 flag ior : write a line of text )\n\t-rot bounds\n\tdo\n\t\tdup i swap write-char drop\n\t\ti c@ nl = if drop i 0 0 leave then\n\tloop ;\n\n: resize-file ( ud fileid -- ior : attempt to resize a file )\n\t( There is no portable way to truncate a file :C )\n\t2drop -1 ( -1 to indicate failure ) ;\n\n: create-file ( c-addr u fam -- fileid ior )\n\t>r 2dup w\/o open-file throw close-file throw\n\tr> open-file ;\n\n: include-file ( file-id -- : evaluate a file )\n\tdup >r 0 1 evaluator r> close-file throw throw ;\n\n: included ( c-addr u -- : attempt to open up a name file and evaluate it )\n\tr\/o open-file throw\n\tinclude-file ;\n\n: include ( c\" ccc\" -- : attempt to evaluate a named file )\n\t( @bug requires trailing space, should use parse-name )\n\tbl word count included ;\n\n: bin ( fam1 -- fam2 : modify a file access method to be binary not line oriented )\n\t( Do nothing, all file access methods are binary )\n\t;\n\n( ==================== Files ================================= )\n\n( ==================== Matcher =============================== )\n( The following section implements a very simple regular\nexpression engine, which expects an ASCIIZ Forth string. It\nis translated from C code and performs an identical function.\n\nThe regular expression language is as follows:\n\n\tc\tmatch a literal character\n\t.\tmatch any character\n\t*\tmatch any characters\n\nThe \"*\" operator performs the same function as \".*\" does in\nmost other regular expression engines. Most other regular\nexpression engines also do not anchor their selections to the\nbeginning and the end of the string to match, instead using\nthe operators '^' and '$' to do so, to emulate this behavior\n'*' can be added as either a suffix, or a prefix, or both,\nto the matching expression.\n\nAs an example \"*, World!\" matches both \"Hello, World!\" and\n\"Good bye, cruel World!\". \"Hello, ....\" matches \"Hello, Bill\"\nand \"Hello, Fred\" but not \"Hello, Tim\" as there are two few\ncharacters in the last string.\n\n@todo make a matcher that expects a Forth string, which do\nnot have to be NUL terminated )\n\n\\ Translated from http:\/\/c-faq.com\/lib\/regex.html\n\\ int match(char *pat, char *str)\n\\ {\n\\ \tswitch(*pat) {\n\\ \tcase '\\0': return !*str;\n\\ \tcase '*': return match(pat+1, str) || *str && match(pat, str+1);\n\\ \tcase '.': return *str && match(pat+1, str+1);\n\\ \tdefault: return *pat == *str && match(pat+1, str+1);\n\\ \t}\n\\ }\n\n: *pat ( regex -- regex char : grab next character of pattern )\n\tdup c@ ;\n\n: *str ( string regex -- string regex char : grab next character string to match )\n\tover c@ ;\n\n: pass ( c-addr1 c-addr2 -- bool : pass condition, characters matched )\n\t2drop 1 ;\n\n: reject ( c-addr1 c-addr2 -- bool : fail condition, character not matched )\n\t2drop 0 ;\n\n: *pat==*str ( c-addr1 c-addr2 -- c-addr1 c-addr2 bool )\n\t2dup c@ swap c@ = ;\n\n: ++ ( u1 u2 u3 u4 -- u1+u3 u2+u4 : not quite d+ [does no carry] )\n\tswap >r + swap r> + swap ;\n\ndefer matcher\n\n: advance ( string regex char -- bool : advance both regex and string )\n\tif 1 1 ++ matcher else reject then ;\n\n: advance-string ( string regex char -- bool : advance only the string )\n\tif 1 0 ++ matcher else reject then ;\n\n: advance-regex ( string regex -- bool : advance matching )\n\t2dup 0 1 ++ matcher if pass else *str advance-string then ;\n\n: match ( string regex -- bool : match a ASCIIZ pattern against an ASCIIZ string )\n\t( @todo Add limits and accept two Forth strings, making sure they are both\n\t ASCIIZ strings as well\n\t @warning This uses a non-standards compliant version of case! )\n\t*pat\n\tcase\n\t\t 0 of drop c@ not endof\n\t\t[char] * of advance-regex endof\n\t\t[char] . of *str advance endof\n\t\t\n\t\tdrop *pat==*str advance exit\n\n\tendcase ;\n\nmatcher is match\n\nhide{\n\t*str *pat *pat==*str pass reject advance\n\tadvance-string advance-regex matcher ++\n}hide\n\n( ==================== Matcher =============================== )\n\n\n( ==================== Cons Cells ============================ )\n( From http:\/\/sametwice.com\/cons.fs, this could be improved\nif the optional memory allocation words were added to\nthe interpreter. This provides a simple \"cons cell\" data\nstructure. There is currently no way to free allocated\ncells. I do not think this is particularly useful, but it is\ninteresting. )\n\n: car! ( value cons-addr -- : store a value in the car cell of a cons cell )\n\t! ;\n\n: cdr! ( value cons-addr -- : store a value in the cdr cell of a cons cell )\n\tcell+ ! ;\n\n: car@ ( cons-addr -- car-val : retrieve car value from cons cell )\n\t@ ;\n\n: cdr@ ( cons-addr -- cdr-val : retrieve cdr value from cons cell )\n\tcell+ @ ;\n\n: cons ( car-val cdr-val -- cons-addr : allocate a new cons cell )\n\tswap here >r , , r> ;\n\n: cons0 0 0 cons ;\n\n( ==================== Cons Cells ============================ )\n\n( ==================== License =============================== )\n( The license has been chosen specifically to make this library\nand any associated programs easy to integrate into arbitrary\nproducts without any hassle. For the main libforth program\nthe LGPL license would have been also suitable [although it\nis MIT licensed as well], but to keep confusion down the same\nlicense, the MIT license, is used in both the Forth code and\nC code. This has not been done for any ideological reasons,\nand I am not that bothered about licenses. )\n\n: license ( -- : print out license information )\n\"\nThe MIT License (MIT)\n\nCopyright (c) 2016, 2017 Richard James Howe\n\nPermission is hereby granted, free of charge, to any person\nobtaining a copy of this software and associated documentation\nfiles (the 'Software'), to deal in the Software without\nrestriction, including without limitation the rights to use,\ncopy, modify, merge, publish, distribute, sublicense, and\/or\nsell copies of the Software, and to permit persons to whom\nthe Software is furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY\nKIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\nWARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE\nAND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\nHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE\nOR OTHER DEALINGS IN THE SOFTWARE.\n\n\"\n;\n\n( ==================== License =============================== )\n\n( ==================== Core utilities ======================== )\n( Read the header of a core file and process it, printing the\nresults out )\n\n8 constant header-size ( size of Forth core file header )\n8 constant size-field-size ( the size in bytes of the size field in the core file )\n0 variable core-file ( core fileid we are reading in )\n0 variable core-cell-size ( cell size of Forth core )\n0 variable core-version ( version of core file )\n0 variable core-endianess ( endianess of core we are reading in )\n\n( save space to read in header )\ncreate header header-size chars allot\n: cheader ( -- c-addr : header char address )\n\theader chars> ;\ncreate size-field size-field-size chars allot\n: csize-field ( -- c-addr : address of place size field is stored in )\n\tsize-field chars> ;\n\n0\nenum header-magic0 ( magic number 0 : FF )\nenum header-magic1 ( magic number 1 : '4' )\nenum header-magic2 ( magic number 2 : 'T' )\nenum header-magic3 ( magic number 3 : 'H' )\nenum header-cell-size ( size of a forth cell, either 2, 4 or 8 bytes )\nenum header-version ( version of the forth core )\nenum header-endianess ( endianess of the core )\nenum header-log2size ( binary logarithm of the core size )\n\n: cleanup ( -- : cleanup before abort )\n\tcore-file @ ?dup 0<> if close-file drop then ;\n\n: invalid-header ( bool -- : abort if header is invalid )\n\t<> if cleanup abort\" invalid header\" then ;\n\n: save-core-cell-size ( char -- : save the core file cell size, checking if it is valid )\n\tcore-cell-size !\n\t\" cell size:\" tab\n\tcore-cell-size @ 2 = if 2 . cr exit then\n\tcore-cell-size @ 4 = if 4 . cr exit then\n\tcore-cell-size @ 8 = if 8 . cr exit then\n\tcleanup core-cell-size @ . abort\" : invalid cell size\" ;\n\n: check-version-compatibility ( char -- : checks the version compatibility of the core file )\n\tcore-version !\n\tcore-version @ version = if \" version: \" version . cr exit then\n\tcleanup core-version @ . abort\" : unknown version number\" ;\n\n: save-endianess ( char -- : save the endianess, checking if it is valid )\n\tcore-endianess !\n\t\" endianess:\" tab\n\tcore-endianess @ 0 = if \" big\" cr exit then\n\tcore-endianess @ 1 = if \" little\" cr exit then\n\tcleanup core-endianess @ . abort\" invalid endianess\" then ;\n\n: read-or-abort ( c-addr size fileid -- : )\n\tover >r read-file\n\t 0<> if cleanup abort\" file read failed\" then\n\tr> <> if cleanup abort\" header too small\" then ;\n\n: header? ( -- : print out header information )\n\tcheader header-size core-file @ read-or-abort\n\t( \" raw header:\" header 2 dump )\n\tcheader header-magic0 + c@ 255 invalid-header\n\tcheader header-magic1 + c@ [char] 4 invalid-header\n\tcheader header-magic2 + c@ [char] T invalid-header\n\tcheader header-magic3 + c@ [char] H invalid-header\n\tcheader header-cell-size + c@ save-core-cell-size\n\tcheader header-version + c@ check-version-compatibility\n\tcheader header-endianess + c@ save-endianess\n\t\" valid header\" cr ;\n\n: size? ( -- : print out core file size )\n\t\" size: \" cheader header-log2size + c@ 1 swap lshift . cr ;\n\n: core ( c-addr u -- : analyze a Forth core file from disk given its file name )\n\t2dup \" core file:\" tab type cr\n\tr\/o open-file throw core-file !\n\theader?\n\tsize?\n\tcore-file @ close-file drop ;\n\n( s\" forth.core\" core )\n\nhide{\nheader-size header?\nheader-magic0 header-magic1 header-magic2 header-magic3\nheader-version header-cell-size header-endianess header-log2size\nheader\ncore-file save-core-cell-size check-version-compatibility\ncore-cell-size cheader\ncore-endianess core-version save-endianess invalid-header\ncleanup size-field csize-field size-field-size\nread-or-abort size?\n}hide\n\n( ==================== Core utilities ======================== )\n\n( ==================== RLE =================================== )\n\n( These set of words implement Run Length Compression, which\ncan be used for saving space when compressing the core files\ngenerated by Forth programs, which contain mostly runs of\nNUL characters.\n\nThe format of the encoded data is quite simple, there is a\ncommand byte followed by data. The command byte encodes only\ntwo commands; encode a run of literal data and repeat the\nnext character.\n\nIf the command byte is greater than X the command is a run\nof characters, X is then subtracted from the command byte\nand this is the number of characters that is to be copied\nverbatim when decompressing.\n\nIf the command byte is less than or equal to X then this\nnumber, plus one, is used to repeat the next data byte in\nthe input stream.\n\nX is 128 for this application, but could be adjusted for\nbetter compression depending on what the data looks like.\n\nExample:\n\n\t2 'a' 130 'b' 'c' 3 'd'\n\nBecomes:\n\n\taabcddd\n\nExample usage:\n\n\t: extract\n\t\tc\" forth.core\" w\/o open-file throw c\"\n\t\tforth.core.rle\" r\/o open-file throw\n\t\tdecompress ;\n\textract\n\n@note file redirection could be used for the input as well\n@todo compression, and reading\/writing to strings )\n\n: cpad pad chars> ;\n\n0 variable out\n128 constant run-length\n\n: next.char ( file-id -- char : read in a single character )\n\t>r cpad r> read-char throw cpad c@ ;\n\n: repeated ( count file-id -- : repeat a character count times )\n\tnext.char swap 0 do dup emit loop drop ;\n\n: literals ( count file-id -- : extract a literal run )\n\t>r cpad swap r> read-file throw cpad swap type ;\n\n: command ( file-id -- : process an RLE command )\n\tdup\n\t>r next.char\n\tdup run-length u>\n\tif\n\t\trun-length - r> literals\n\telse\n\t\t1+ r> repeated\n\tthen ;\n\n: redirect ( file-id-out -- : save current output pointer, redirect to output )\n\t`fout @ out ! `fout ! ;\n\n: restore ( -- : restore previous output pointer )\n\tout @ `fout ! ;\n\n: decompress ( file-id-out file-id-in -- : decompress an RLE encoded file )\n\tswap\n\tredirect\n\tbegin dup ' command catch until ( process commands until input exhausted )\n\t2drop ( drop twice because catch will restore stack before COMMAND )\n\trestore ; ( restore input stream )\n\nhide{ literals repeated next.char out run-length command }hide\n\n( ==================== RLE =================================== )\n\n( ==================== Generate C Core file ================== )\n( The word core2c reads in a core file and turns it into a\nC file which can then be compiled into the forth interpreter\nin a bootstrapping like process. The process is described\nelsewhere as well, but it goes like this.\n\n1. We want to generate an executable program that contains the\ncore Forth interpreter, written in C, and the contents of this\nfile in compiled form. However, in order to compile this code\nwe need a Forth interpreter to do so. This is the problem.\n2. To solve the problem we first make a program which is capable\nof compiling \"forth.fth\".\n3. We then generate a core file from this.\n4. We then convert the generated core file to C code.\n5. We recompile the original program to includes this core\nfile, and which runs the core file at start up.\n6. We run the new executable.\n\nUsage:\n c\" forth.core\" c\" core.gen.c\" core2c )\n\n0 variable count\n\n: wbyte ( u char -- : write a byte )\n\t(.) drop\n\t[char] , emit\n\t16 mod 0= if cr then ;\n\n: advance ( char -- : advance counter and print byte )\n\tcount 1+! count @ swap wbyte ;\n\n: hexify ( fileid -- fileid : turn core file into C numbers in array )\n\t0 count !\n\tbegin dup getchar 0= while advance repeat drop ;\n\n: quote ( -- : emit a quote character )\n\t[char] \" emit ;\n\n: core2c ( c-addr u c-addr u -- ior : generate a C file from a core file )\n\tw\/o open-file throw >r\n\tr\/o open-file ?dup-if r> close-file throw throw then\n\tr> redirect\n\t\" #include \" quote \" libforth.h\" quote cr\n\t\" unsigned char forth_core_data[] = {\" cr\n\thexify\n\t\" };\" cr\n\t\" forth_cell_t forth_core_size = \" count @ . \" ;\" cr cr\n\tclose-file\n\t`fout @ close-file\n\trestore or ;\n\nhide{ wbyte hexify count quote advance }hide\n\n( ==================== Generate C Core file ================== )\n\n( ==================== Word Count Program ==================== )\n\n( @todo implement FILE-SIZE in terms of this program )\n( @todo extend wc to include line count and word count )\n: wc ( c-addr u -- u : count the bytes in a file )\n\tr\/o open-file throw\n\t0 swap\n\tbegin\n\t\tdup getchar nip 0=\n\twhile\n\t\tnos1+\n\trepeat\n\tclose-file throw ;\n\n( ==================== Word Count Program ==================== )\n\n( ==================== Save Core file ======================== )\n( The following functionality allows the user to save the\ncore file from within the running interpreter. The Forth\ncore files have a very simple format which means the words\nfor doing this do not have to be too long, a header has to\nemitted with a few calculated values and then the contents\nof the Forths memory after this )\n\n( This write the header out to the current output device, this\nwill be redirected to a file )\n: header ( -- : write the header out )\n\t0xff emit ( magic 0 )\n\t[char] 4 emit ( magic 1 )\n\t[char] T emit ( magic 2 )\n\t[char] H emit ( magic 3 )\n\tsize emit ( cell size in bytes )\n\tversion emit ( core version )\n\tendian not emit ( endianess )\n\tmax-core log2 emit ; ( size field )\n\n: data ( -- : write the data out )\n\t0 max-core chars> `fout @ write-file throw drop ;\n\n: encore ( -- : write the core file out )\n\theader\n\tdata ;\n\n: save-core ( c-addr u -- : save core file or throw error )\n\tw\/o open-file throw dup\n\tredirect\n\t\t' encore catch swap close-file throw\n\trestore ;\n\n( The following code illustrates an example of setting up a\nForth core file to execute a word when the core file is loaded.\nIn the example the word \"hello-world\" will be executed,\nwhich will also quit the interpreter:\n\nThis only works for immediate words for now, we define\nthe word we wish to be executed when the forth core\nis loaded:\n\n\t: hello-world immediate\n\t\t\" Hello, World!\" cr bye ;\n\nThe following sets the starting word to our newly\ndefined word:\n\n\tfind hello-world cfa start!\n\n\t\\ Now we can save the core file out:\n\ts\" forth.core\" save-core\n\nThis can be used, in conjunction with aspects of the build\nsystem, to produce a standalone executable that will run only\na single Forth word. This is known as creating a 'turn-key'\napplication. )\n\nhide{ redirect restore data encore header }hide\n\n( ==================== Save Core file ======================== )\n\n( ==================== Hex dump ============================== )\n\n( @todo hexdump can read in too many characters and it does not\nprint out the correct address\n@todo utilities for easy redirecting of file input\/output )\n\\ : input >r cpad 128 r> read-file ; ( file-id -- u 0 | error )\n\\ : clean cpad 128 0 fill ; ( -- )\n\\ : cdump cpad chars swap aligned chars dump ; ( u -- )\n\\ : hexdump ( file-id -- : [hex]dump a file to the screen )\n\\ \tdup\n\\ \tclean\n\\ \tinput if 2drop exit then\n\\ \t?dup-if cdump else drop exit then\n\\ \ttail ;\n\\\n\\ 0 variable u\n\\ 0 variable u1\n\\ 0 variable cdigs\n\\ 0 variable digs\n\\\n\\ : address ( -- bool : is it time to print out a new line and an address )\n\\ \tu @ u1 @ - 4 size * mod 0= ;\n\\\n\\ : (dump) ( u c-addr u : u -- )\n\\ \trot dup u ! u1 !\n\\ \tcdigits cdigs !\n\\ \tdigits digs !\n\\ \tbounds\n\\ \tdo\n\\ \t\taddress if cr u @ digs @ u.rz [char] : emit space then\n\\ \t\ti c@ cdigs @ u.rz\n\\ \t\t\n\\ \t\ti 1+ size mod 0= if space then\n\\ \t\tu 1+!\n\\ \tloop\n\\ \tu @\n\\ \t;\n\\\n\\ : hexdump-file ( c-addr u )\n\\ \tr\/o open-file throw\n\\ \t\n\\ \t;\n\\\n\\ hide{ u u1 cdigs digs address }hide\n\\ hex\n\\ 999 0 197 (dump)\n\\ decimal\n\\\n\\ hide{ cpad clean cdump input }hide\n\\\n( ==================== Hex dump ============================== )\n\n( ==================== Date ================================== )\n( This word set implements a words for date processing, so\nyou can print out nicely formatted date strings. It implements\nthe standard Forth word time&date and two words which interact\nwith the libforth DATE instruction, which pushes the current\ntime information onto the stack.\n\nRather annoyingly months are start from 1 but weekdays from\n0. )\n\n: >month ( month -- c-addr u : convert month to month string )\n\tcase\n\t\t 1 of c\" Jan \" endof\n\t\t 2 of c\" Feb \" endof\n\t\t 3 of c\" Mar \" endof\n\t\t 4 of c\" Apr \" endof\n\t\t 5 of c\" May \" endof\n\t\t 6 of c\" Jun \" endof\n\t\t 7 of c\" Jul \" endof\n\t\t 8 of c\" Aug \" endof\n\t\t 9 of c\" Sep \" endof\n\t\t10 of c\" Oct \" endof\n\t\t11 of c\" Nov \" endof\n\t\t12 of c\" Dec \" endof\n\t\t-11 throw\n\tendcase ;\n\n: .day ( day -- c-addr u : add ordinal to day )\n\t10 mod\n\tcase\n\t\t1 of c\" st \" endof\n\t\t2 of c\" nd \" endof\n\t\t3 of c\" rd \" endof\n\t\tdrop c\" th \" exit\n\tendcase ;\n\n: >day ( day -- c-addr u: add ordinal to day of month )\n\tdup 1 10 within if .day exit then\n\tdup 10 20 within if drop c\" th\" exit then\n\t.day ;\n\n: >weekday ( weekday -- c-addr u : print the weekday )\n\tcase\n\t\t0 of c\" Sun \" endof\n\t\t1 of c\" Mon \" endof\n\t\t2 of c\" Tue \" endof\n\t\t3 of c\" Wed \" endof\n\t\t4 of c\" Thu \" endof\n\t\t5 of c\" Fri \" endof\n\t\t6 of c\" Sat \" endof\n\t\t-11 throw\n\tendcase ;\n\n: >gmt ( bool -- GMT or DST? )\n\tif c\" DST \" else c\" GMT \" then ;\n\n: colon ( -- char : push a colon character )\n\t[char] : ;\n\n: 0? ( n -- : hold a space if number is less than base )\n\t(base) u< if [char] 0 hold then ;\n\n( .NB You can format the date in hex if you want! )\n: date-string ( date -- c-addr u : format a date string in transient memory )\n\t9 reverse ( reverse the date string )\n\t<#\n\t\tdup #s drop 0? ( seconds )\n\t\tcolon hold\n\t\tdup #s drop 0? ( minute )\n\t\tcolon hold\n\t\tdup #s drop 0? ( hour )\n\t\tdup >day holds\n\t\t#s drop ( day )\n\t\t>month holds\n\t\tbl hold\n\t\t#s drop ( year )\n\t\t>weekday holds\n\t\tdrop ( no need for days of year )\n\t\t>gmt holds\n\t\t0\n\t#> ;\n\n: .date ( date -- : print the date )\n\tdate-string type ;\n\n: time&date ( -- second minute hour day month year )\n\tdate\n\t3drop ;\n\nhide{ >weekday .day >day >month colon >gmt 0? }hide\n\n( ==================== Date ================================== )\n\n\n( ==================== CRC =================================== )\n\n( @todo implement all common CRC algorithms, but only if the\nword size allows it [ie. 32 bit CRCs on a 32 or 64 bit machine,\n64 bit CRCs on a 64 bit machine] )\n\n( Make a word to limit arithmetic to a 16-bit value )\nsize 2 = [if]\n\t: limit immediate ; ( do nothing, no need to limit )\n[else]\n\t: limit 0xffff and ; ( limit to 16-bit value )\n[then]\n\n: ccitt ( crc c-addr -- crc : calculate polynomial 0x1021 AKA \"x16 + x12 + x5 + 1\" )\n\tc@ ( get char )\n\tlimit over 256\/ xor ( crc x )\n\tdup 4 rshift xor ( crc x )\n\tdup 5 lshift limit xor ( crc x )\n\tdup 12 lshift limit xor ( crc x )\n\tswap 8 lshift limit xor ; ( crc )\n\n( See http:\/\/stackoverflow.com\/questions\/10564491\n and https:\/\/www.lammertbies.nl\/comm\/info\/crc-calculation.html )\n: crc16-ccitt ( c-addr u -- u )\n\t0xffff -rot\n\t['] ccitt foreach ;\nhide{ limit ccitt }hide\n\n( ==================== CRC =================================== )\n\n( ==================== Rational Data Type ==================== )\n( This word set allows the manipulation of a rational data\ntype, which are basically fractions. This allows numbers like\n1\/3 to be represented without any loss of precision. Conversion\nto and from the data type to an integer type is trivial,\nalthough information can be lost during the conversion.\n\nTo convert to a rational, use DUP, to convert from a\nrational, use '\/'.\n\nThe denominator is the first number on the stack, the numerator\nthe second number. Fractions are simplified after any rational\noperation, and all rational words can accept unsimplified\narguments. For example the fraction 1\/3 can be represented as\n6\/18, they are equivalent, so the rational equality operator\n\"=rat\" can accept both and returns true.\n\n\tT{ 1 3 6 18 =rat -> 1 }T\n\nSee: https:\/\/en.wikipedia.org\/wiki\/Rational_data_type For\nmore information.\n\nThis set of words use two cells to represent a fraction,\nhowever a single cell could be used, with the numerator and the\ndenominator stored in upper and lower half of a single cell.\n\n@todo add saturating Q numbers to the interpreter, as well as\narithmetic word for acting on double cells [d+, d-, etcetera]\nhttps:\/\/en.wikipedia.org\/wiki\/Q_%28number_format%29, this\ncan be used in lieu of floating point numbers. )\n\n: simplify ( a b -- a\/gcd{a,b} b\/gcd{a\/b} : simplify a rational )\n 2dup\n gcd\n tuck\n \/\n -rot\n \/\n swap ; \\ ? check this\n\n: crossmultiply ( a b c d -- a*d b*d c*b d*b )\n rot ( a c d b )\n 2dup ( a c d b d b )\n * ( a c d b d*b )\n >r ( a c d b , d*b )\n rot ( a d b c , d*b )\n * ( a d b*c , d*b )\n -rot ( b*c a d , d*b )\n * ( b*c a*d , d*b )\n r> ( b*c a*d d*b )\n tuck ( b*c d*b a*d d*b )\n 2swap ; ( done! )\n\n: *rat ( a\/b c\/d -- a\/b : multiply two rationals together )\n rot * -rot * swap simplify ;\n\n: \/rat ( a\/b c\/d -- a\/b : divide one rational by another )\n swap *rat ;\n\n: +rat ( a\/b c\/d -- a\/b : add two rationals together )\n crossmultiply\n rot\n drop ( or check if equal, if not there is an error )\n -rot\n +\n swap\n simplify ;\n\n: -rat ( a\/b c\/d -- a\/b : subtract one rational from another )\n crossmultiply\n rot\n drop ( or check if equal, if not there is an error )\n -rot\n -\n swap\n simplify ;\n\n: .rat ( a\/b -- : print out a rational number )\n simplify swap (.) drop [char] \/ emit . ;\n\n: =rat ( a\/b c\/d -- bool : rational equal )\n crossmultiply rot = -rot = = ;\n\n: >rat ( a\/b c\/d -- bool : rational greater than )\n crossmultiply rot 2drop > ;\n\n: <=rat ( a\/b c\/d -- bool : rational less than or equal to )\n\t>rat not ;\n\n: =rat ( a\/b c\/d -- bool : rational greater or equal to )\n\trational is a work in progress, make it better )\n: 0>number 0 -rot >number ;\n0 0 2variable saved\n: failed 0 0 saved 2@ ;\n: >rational ( c-addr u -- a\/b c-addr u )\n\t2dup saved 2!\n\t0>number 2dup 0= if 4drop failed exit then ( @note could convert to rational n\/1 )\n\tc@ [char] \/ <> if 3drop failed exit then\n\t1 \/string\n\t0>number ;\n\nhide{ 0>number saved failed }hide\n\n( ==================== Rational Data Type ==================== )\n\n( ==================== Block Layer =========================== )\n( This is the block layer, it assumes that the file access\nwords exists and use them, it would have to be rewritten\nfor an embedded device that used EEPROM or something\nsimilar. Currently it does not interact well with the current\ninput methods used by the interpreter which will need changing.\n\nThe block layer is the traditional way Forths implement a\nsystem to interact with mass storage, one which imposes little\non the underlying system only requiring that blocks 1024 bytes\ncan be loaded and saved to it [which make it suitable for\nmicrocomputers that lack a file system or an embedded device].\n\nThe block layer is used less than it once as a lot more Forths\nare hosted under a guest operating system so have access to\nmethods for reading and writing to files through it.\n\nEach block number accepted by BLOCK is backed by a file\n[or created if it does not exist]. The name of the file is\nthe block number with \".blk\" appended to it.\n\nSome Notes:\n\nBLOCK only uses one block buffer, most other Forths have\nmultiple block buffers, this could be improved on, but\nwould take up more space.\n\nAnother way of storing the blocks could be made, which is to\nstore the blocks in a single file and seek to the correct\nplace within it. This might be implemented in the future,\nor offered as an alternative. \n\nYet another way is to not have on disk blocks, but instead\nhave in memory blocks, this simplifies things significantly,\nand would mean saving the blocks to disk would use the same\nmechanism as saving the core file to disk. Computers certainly\nhave enough memory to do this. The block word set could\nbe factored so it could use either the on disk method or\nthe memory option. \n\nTo simplify the current code, and make the code portable\nto devices with EEPROM an instruction in the virtual machine\ncould be made which does the task of transfering a block to\ndisk. )\n\n0 variable dirty\nb\/buf string buf ( block buffer, only one exists )\n0 , ( make sure buffer is NUL terminated, just in case )\n0 variable blk ( 0 = invalid block number, >0 block number stored in buf)\n\n: invalid? ( n -- : throw if block number is invalid )\n\t0= if -35 throw then ;\n\n: update ( -- : mark currently loaded block buffer as dirty )\n\ttrue dirty ! ;\n\n: updated? ( n -- bool : is a block updated? )\n \tblk @ <> if 0 else dirty @ then ;\n\n: block.name ( n -- c-addr u : make a block name )\n\tc\" .blk\" <# holds #s #> rot drop ;\n\n( @warning this will not work if we do not have permission,\nor in various other cases where we cannot open the file,\nfor whatever reason )\n: file-exists ( c-addr u : does a file exist? )\n\tr\/o open-file if drop 0 else close-file throw 1 then ;\n\n: block.exists ( n -- bool : does a block buffer exist on disk? )\n\tblock.name file-exists ;\n\n( @note block.write and block.read do not check if they have\nwrote or read in 1024 bytes, nor do they check that they can\nonly write or read 1024 and not a byte more )\n\n: block.read ( file-id -- file-id : read in buffer )\n\tdup >r buf r> read-file nip if close-file -33 throw then ;\n\n: block.write ( file-id -- file-id : write out buffer )\n\tdup >r buf r> write-file nip if close-file -34 throw then ;\n\n: block.open ( n fam -- file-id )\n\t>r block.name r> open-file throw ;\n\n: save-buffers\n\tblk @ 0= if exit then ( not a valid block number, exit )\n\tdirty @ not if exit then ( not dirty, no need to save )\n\tblk @ w\/o block.open ( open file backing block buffer )\n\tblock.write ( write it out )\n\tclose-file throw ( close it )\n\tfalse dirty ! ; ( but only mark it clean if everything succeeded )\n\n: empty-buffers ( -- : deallocate any saved buffers )\n\t0 blk ! ;\n\n: flush ( -- : perform save-buffers followed by empty-buffers )\n\tsave-buffers\n\tempty-buffers ;\n\n( Block is a complex word that does a lot, although it has\na simple interface. It does the following given a block number:\n\n1. Checks the provided block buffer number to make sure it\nis valid.\n2. If the block is already loaded from the disk, then return\nthe address of the block buffer it is loaded into.\n3. If not, it checks to see if the currently loaded block\nbuffer is dirty, if it is then it flushes the buffer to disk.\n4. If the block buffer does not exists on disk then it\ncreates it.\n5. It then stores the block number in blk and returns an\naddress to the block buffer. )\n: block ( n -- c-addr : load a block )\n\tdup invalid?\n\tdup blk @ = if drop buf drop exit then\n\tflush\n\tdup block.exists if ( if the buffer exits on disk load it in )\n\t\tdup r\/o block.open\n\t\tblock.read\n\t\tclose-file throw\n\telse ( else it does not exist )\n\t\tbuf 0 fill ( clean the buffer )\n\tthen\n\tblk ! ( save the block number )\n\tbuf drop ;\n\n: buffer block ;\n\n( @warning uses hack, block buffer is NUL terminated, and evaluate requires\na NUL terminated string, evaluate checks that the last character is NUL,\nhence the 1+ )\n: load ( n -- : load and execute a block )\n\tblock b\/buf 1+ evaluate throw ;\n\n: +block ( n -- u : calculate new block number relative to current block )\n\tblk @ + ;\n\n: --> ( -- : load next block )\n\t1 +block load ;\n\n: blocks.make ( n1 n2 -- : make blocks on disk from n1 to n2 inclusive )\n\t1+ swap do i block b\/buf bl fill update loop save-buffers ;\n\n: block.copy ( n1 n2 -- bool : copy block n2 to n1 if n2 exists )\n\tswap dup block.exists 0= if 2drop false exit then ( n2 n1 )\n\tblock drop ( load in block n1 )\n\tw\/o block.open block.write close-file throw\n\ttrue ;\n\n: block.delete ( n -- : delete block )\n\tdup block.exists 0= if drop exit then\n\tblock.name delete-file drop ;\n\n\\ @todo implement a word that splits a file into blocks\n\\ : split ( c-addr u : split a file into blocks )\n\\\t;\n\nhide{\n\tblock.name invalid? block.write\n\tblock.read block.exists block.open dirty\n}hide\n\n( ==================== Block Layer =========================== )\n\n( ==================== List ================================== )\n( The list word set allows the viewing of Forth blocks,\nthis version of list can create two Formats, a simple mode\nwhere it just spits out the block with a carriage return\nafter each line and a more fancy version which also prints\nout line numbers and draws a box around the data. LIST is\nnot aware of any formatting and characters that might be\npresent in the data, or none printable characters.\n\nA very primitive version of list can be defined as follows:\n\n\t: list block b\/buf type ;\n\n)\n\n1 variable fancy-list\n0 variable scr\n64 constant c\/l ( characters per line )\n\n: pipe ( -- : emit a pipe character )\n\t[char] | emit ;\n\n: line.number ( n -- : print line number )\n\tfancy-list @ not if drop exit then\n\t2 u.r space pipe ;\n\n: list.end ( -- : print the right hand side of the box )\n\tfancy-list @ not if exit then\n\tpipe ;\n\n: line ( c-addr -- c-addr u : given a line number, display that line number and calculate offset )\n\tdup\n\tline.number ( display line number )\n\tc\/l * + ( calculate offset )\n\tc\/l ; ( add line length )\n\n: list.type ( c-addr u -- : list a block )\n\tb\/buf c\/l \/ 0 do dup i line type list.end cr loop drop ;\n\n: list.border ( -- : print a section of the border )\n\t\" +---|---\" ;\n\n: list.box ( )\n\tfancy-list @ not if exit then\n\t4 spaces\n\t8 0 do list.border loop cr ;\n\n: list ( n -- : display a block number and update scr )\n\tdup >r block r> scr ! list.box list.type list.box ;\n\n: thru\n\tkey drop\n\t1+ swap do i list more loop ;\n\nhide{\n\tbuf line line.number list.type\n\t(base) list.box list.border list.end pipe\n}hide\n\n( ==================== List ================================== )\n\n( ==================== Signal Handling ======================= )\n( Signal handling at the moment is quite primitive. When\na signal occurs it has to be explicitly tested for by the\nprogrammer, this could be improved on quite a bit. One way\nof doing this would be to check for signals in the virtual\nmachine and cause a THROW from within it. )\n\n( signals are biased to fall outside the range of the error\nnumbers defined in the ANS Forth standard. )\n-512 constant signal-bias\n\n: signal ( -- signal\/0 : push the results of the signal register )\n\t`signal @\n \t0 `signal ! ;\n\n( ==================== Signal Handling ======================= )\n\n( Looking at most Forths dictionary with \"words\" command they\ntend to have a lot of words that do not mean anything but to\nthe implementers of that specific Forth, here we clean up as\nmany non standard words as possible. )\nhide{\n do-string ')' alignment-bits\n dictionary-start hidden-mask instruction-mask immediate-mask compiling?\n compile-bit\n max-core dolist doconst x x! x@\n max-string-length\n evaluator\n TrueFalse >instruction\n xt-instruction\n `source-id `sin `sidx `slen `start-address `fin `fout `stdin\n `stdout `stderr `argc `argv `debug `invalid `top `instruction\n `stack-size `error-handler `x `handler _emit `signal\n}hide\n\n(\n## Forth To List\n\nThe following is a To-Do list for the Forth code itself,\nalong with any other ideas.\n\n* FORTH, VOCABULARY\n\n* \"Value\", \"To\", \"Is\"\n\n* Double cell words\n\n* The interpreter should use character based addresses,\ninstead of word based, and use values that are actual valid\npointers, this will allow easier interaction with the world\noutside the virtual machine\n\n* common words and actions should be factored out to simplify\ndefinitions of other words, their standards compliant version\nfound if any.\n\n* A soft floating point library would be useful which could be\nused to optionally implement floats [which is not something I\nreally want to add to the virtual machine]. If floats were to\nbe added, only the minimal set of functions should be added\n[f+,f-,f\/,f*,f<,f>,>float,...]\n\n* Allow the processing of argc and argv, the mechanism by which\nthat this can be achieved needs to be worked out. However all\nprocessing that is currently done in \"main.c\" should be done\nwithin the Forth interpreter instead. Words for manipulating\nrationals and double width cells should be made first.\n\n* A built in version of \"dump\" and \"words\" should be added\nto the Forth starting vocabulary, simplified versions that\ncan be hidden.\n\n* Here documents, string literals. Examples of these can be\nfound online\n\n* Document the words in this file and built in words better,\nalso turn this document into a literate Forth file.\n\n* Sort out \"'\", \"[']\", \"find\", \"compile,\"\n\n* Proper booleans should be used throughout, that is -1 is\ntrue, and 0 is false.\n\n* Attempt to add crypto primitives, not for serious use,\nlike TEA, XTEA, XXTEA, RC4, MD5, ...\n\n* Add hash functions: CRC-32, CRC-16, ...\nhttp:\/\/stackoverflow.com\/questions\/10564491\/\n\n* Implement as many things from\nhttp:\/\/lars.nocrew.org\/forth2012\/implement.html as is sensible.\n\n* The current words that implement I\/O redirection need to\nbe improved, and documented, I think this is quite a useful\nand powerful mechanism to use within Forth that simplifies\nprograms. This is a must and will make writing utilities in\nForth a *lot* easier\n\n* Words for manipulating words should be added, for navigating\nto different fields within them, to the end of the word,\netcetera.\n\n* The data structure used for parsing Forth words needs\nchanging in libforth so a counted string is produced. Counted\nstrings should be used more often. The current layout of a\nForth word prevents a counted string being used and uses a\nbyte more than it has to.\n\n* Whether certain simple words [such as '1+', '1-', '>',\n'<', '<>', NOT, <=', '>='] should be added as virtual\nmachine instructions for speed [and size] reasons should\nbe investigated.\n\n* An analysis of the interpreter and the code it executes\ncould be done to find the most commonly executed words\nand instructions, as well as the most common two and three\nsequences of words and instructions. This could be used to use\nto optimize the interpreter, in terms of both speed and size.\n\n* As a thought, a word for inlining other words could be\nmade by copying everything into the current definition until\nit reaches a _exit, it would need to be aware of literals\nwritten into a word, like SEE is.\n\n* The source code for this file should go through a code\nreview, which should focus on formatting, stack comments and\nreorganizing the code. Currently it is not clear that variables\nlike COLORIZE and FANCY-LIST exist and can be changed by\nthe user. Lines should be 64 characters in length - maximum,\nincluding the new line at the end of the file.\n\n### libforth.c todo\n\n* A halt, a parse, and a print\/type instruction could be\nadded to the Forth virtual machine.\n\n* u.r, or a more generic version should be added to the\ninterpreter instead of the current simpler primitive. As\nshould >number - for fast numeric input and output.\n\n* Throw\/Catch need to be added and used in the virtual machine\n\n* Various edge cases and exceptions should be removed [for\nexample counted strings are not used internally, and '0x'\ncan be used as a prefix only when base is zero].\n\n* A potential optimization is to order the words in the\ndictionary by frequency order, this would mean chaning the\nX Macro that contains the list of words, after collecting\nstatistics. This should make find faster.\n\n* Investigate adding operating system specific code into the\ninterpreter and isolating it to make it semi-portable.\n\n* Make equivalents for various Unix utilities in Forth,\nlike a CRC check, cat, tr, etcetera.\n\n* It would be interesting to make a primitive file system based\nupon Forth blocks, this could then be ported to systems that\ndo not have file systems, such as microcontrollers [which\nusually have EEPROM].\n\n* In a _very_ unportable way it would be possible to have an\ninstruction that takes the top of the stack, treats it as a\nfunction pointer and then attempts to call said function. This\nwould allow us to assemble machine dependant code within the\ncore file, generate a new function, then call it. It is just\na thought.\n )\n\nverbose [if]\n\t.( FORTH: libforth successfully loaded.) cr\n\tdate .date cr\n\t.( Type 'help' and press return for a basic introduction.) cr\n\t.( Core: ) here . \" \/ \" here unused + . cr\n\t license\n[then]\n\n( ==================== Test Code ============================= )\n\n( The following will not work as we might actually be reading\nfrom a string [`sin] not `fin.\n\n: key 32 chars> 1 `fin @\n\tread-file drop 0 = if 0 else 32 chars> c@ then ; )\n\n\\ : ' immediate state @ if postpone ['] else find then ;\n\n( This really does not implement a correct FORTH\/VOCABULARY,\nfor that wordlists will need to be introduced and used in\nlibforth.c. The best that this word set can do is to hide\nand reveal words to the user, this was just an experiment.\n\n\t: forth\n\t\t[ find forth 1- @ ] literal\n\t\t[ find forth 1- ] literal ! ;\n\n\t: vocabulary\n\t\tcreate does> drop 0 [ find forth 1- ] literal ! ; )\n\n\\ @todo The built in primitives should be redefined so to make sure\n\\ they are called and nested correctly, using the following words\n\\ 0 variable csp\n\\ : !csp sp@ csp ! ;\n\\ : ?csp sp@ csp @ <> if -22 throw then ;\n\n\\ @todo Make this work\n\\ : >body ??? ;\n\\ : noop ( -- ) ;\n\\ : defer create ( \"name\" -- ) ['] noop , does> ( -- ) @ execute ;\n\\ : is ( xt \"name\" -- ) find >body ! ;\n\\ defer lessthan\n\\ find < is lessthan\n\n( ==================== Test Code ============================= )\n\n( ==================== Block Editor ========================== )\n( Experimental block editor Mark II\n\nThis is a simple block editor, it really shows off the power\nand simplicity of Forth systems - both the concept of a block\neditor and the implementation.\n\nForth source code used to organized into things called 'blocks',\nnowadays most people use normal resizeable stream based files.\nA block simply consists of 1024 bytes of data that can be\ntransfered to and from mass storage. This works on systems that\ndo not have a file system. A block can be used for storing\narbitrary data as well, so the user had to know what was stored\nin what block.\n\n1024 bytes is quite a limiting Form factor for storing source\ncode, which is probably one reason Forth earned a reputation\nfor being terse. A few conventions arose around dealing with\nForth source code stored in blocks - both in how the code should\nbe formatted within them, and in how programs that required\nmore than one block of storage should be dealt with.\n\nOne of the conventions is how many columns and rows each block\nconsists of, the traditional way is to organize the code into\n16 lines of text, with a column width of 64 characters. The only\nspace character used is the space [or ASCII character 32], tabs\nand new lines are not used, as they are not needed - the editor\nknows how long a line is so it can wrap the text.\n\nVarious standards and common practice evolved as to what goes\ninto a block - for example the first line is usually a comment\ndescribing what the block does, with the date is was last edited\nand who edited it.\n\nThe way the editor works is by defining a simple set of words\nthat act on the currently loaded block, LIST is used to display\nthe loaded block. An editor loop which executes forth words\nand automatically displays the currently block can be entered\nby calling EDITOR. This loop is essential an extension of\nthe INTERPRET word, it does no special processing such as\nlooking for keys - all commands are Forth words. The editor\nloop could have been implemented in the following fashion\n[or something similar]:\n\n\t: editor-command\n\t\tkey\n\t\tcase\n\t\t\t[char] h of print-editor-help endof\n\t\t\t[char] i of insert-text endof\n\t\t\t[char] d of delete-line endof\n\t\t\t... more editor commands\n\t\t\t[char] q of quit-editor-loop endof\n\t\t\tpush-number-by-default\n\t\tendof ;\n\nHowever this is rather limiting, it only works for single\ncharacter commands and numeric input is handled as a special\ncase. It is far simpler to just call the READ word with the\neditor commands in search order, and it can be extended not\nby adding more parsing code in CASE statements but just by\ndefining new words in the ordinary manner.\n\nThe editor loop does not have to be used while editing code,\nbut it does make things easier. The commands defined can be\nused on there own.\n\t\nThe code was adapted from: \t\n\nhttp:\/\/retroforth.org\/pages\/?PortsOfRetroEditor\n\nWhich contains ports of an editor written for Retro Forth.\n\n@todo Improve the block editor\n\n- '\\' needs extending to work with the block editor, for now,\nuse parenthesis for comments\n- add multi line insertion mode\n- Add to an editor vocabulary, which will need the vocabulary\nsystem to exist.\n- Using PAGE should be optional as not all terminals support\nANSI escape codes - thanks to CMD.EXE. Damned Windows.\n\nAdapted from http:\/\/retroforth.org\/pages\/?PortsOfRetroEditor )\n\n\n: help ( @todo rename to H once vocabularies are implemented )\npage cr\n\" Block Editor Help Menu\n\n n move to next block\n p move to previous block\n # d delete line in current block\n x erase current block\n e evaluate current block\n # i insert line\n # #2 ia insert at line #2 at column #\n q quit editor loop\n # b set block number\n s save block and write it out\n\n -- press any key to continue -- \" cr ( \" )\nchar drop ;\n\n: (block) blk @ block ;\n: (check) dup b\/buf c\/l \/ u>= if -24 throw then ;\n: (line) (check) c\/l * (block) + ; ( n -- c-addr : push current line address )\n: (clean)\n\t(block) b\/buf\n\t2dup nl bl subst\n\t2dup cret bl subst\n\t 0 bl subst ;\n: n 1 +block block ;\n: p -1 +block block ;\n: d (line) c\/l bl fill ;\n: x (block) b\/buf bl fill ;\n: s update save-buffers ;\n: q rdrop rdrop ;\n: e blk @ load char drop ;\n: ia c\/l * + dup b\/buf swap - >r (block) + r> accept drop (clean) ;\n: i 0 swap ia ;\n: editor\n\t1 block ( load first block by default )\n\trendezvous ( set up a rendezvous so we can forget words up to this point )\n\tbegin\n\t\tpage cr\n\t\t\" BLOCK EDITOR: TYPE 'HELP' FOR A LIST OF COMMANDS\" cr\n\t\tblk @ list\n\t\t\" [BLOCK: \" blk @ u. \" ] [DICTIONARY: \" here u. \" ]\" cr\n\t\tpostpone [ ( need to be in command mode )\n\t\tread\n\tagain ;\n\n( Extra niceties )\nc\/l string yank\nyank bl fill\n: u update ;\n: b block ;\n: l blk @ list ;\n: y (line) yank >r swap r> cmove ;\n: c (line) yank cmove ;\n: ct swap y c ;\n: m retreat ;\n\nhide{ (block) (line) (clean) yank }hide\n\n( ==================== Block Editor ========================== )\n\n( ==================== Error checking ======================== )\n( This is a series of redefinitions that make the use of control\nstructures a bit safer. )\n\n: if immediate ?comp postpone if [ hide if ] ;\n: else immediate ?comp postpone else [ hide else ] ;\n: then immediate ?comp postpone then [ hide then ] ;\n: begin immediate ?comp postpone begin [ hide begin ] ;\n: until immediate ?comp postpone until [ hide until ] ;\n\\ : ; immediate ?comp postpone ; [ hide ; ] ; ( @todo do nesting checking for control statements )\n\n( ==================== Error checking ======================== )\n\n( ==================== DUMP ================================== )\n\\ : newline ( x -- x+1 : print a new line every fourth value )\n\\ \tdup 3 and 0= if cr then 1+ ;\n\\\n\\ : address ( num count -- count : print current address we are dumping every fourth value )\n\\ \tdup >r\n\\ \t1- 3 and 0= if . [char] : emit space else drop then\n\\ \tr> ;\n\\\n\\ : dump ( start count -- : print the contents of a section of memory )\n\\ \\\thex ( switch to hex mode )\n\\ \t1 >r ( save counter on return stack )\n\\ \tover + swap ( calculate limits: start start+count )\n\\ \tbegin\n\\ \t\t2dup u> ( stop if gone past limits )\n\\ \twhile\n\\ \t\tdup r> address >r\n\\ \t\tdup @ . 1+\n\\ \t\tr> newline >r\n\\ \trepeat\n\\ \tr> drop\n\\ \t2drop ;\n\\\n\\ hide newline\n\\ hide address\n( ==================== DUMP ================================== )\n\n( ==================== End of File Functions ================= )\n\n( set up a rendezvous point, we can call the word RETREAT to\nrestore the dictionary to this point. This word also updates\nfence to this location in the dictionary )\nrendezvous\n\n: task ; ( Task is a word that can safely be forgotten )\n\n( ==================== End of File Functions ================= )\n\n( Experimental FOR ... NEXT )\n: for immediate\n\t?comp\n\t['] >r ,\n\there\n\t;\n\n: (next) ( -- bool, R: val -- | val+1 )\n\tr> r> 1- dup 0= if drop >r 1 else >r >r 0 then ;\n\n: next immediate\n\t?comp\n\t' (next) , ' ?branch , here - , ;\n \n","old_contents":"#!.\/forth\n( Welcome to libforth, A dialect of Forth. Like all versions\nof Forth this version is a little idiosyncratic, but how\nthe interpreter works is documented here and in various\nother files.\n\nThis file contains most of the start up code, some basic\nstart up code is executed in the C file as well which makes\nprogramming at least bearable. Most of Forth is programmed in\nitself, which may seem odd if your back ground in programming\ncomes from more traditional language [such as C], although\nless so if you know already know lisp.\n\nFor more information about this interpreter and Forth see:\n\nhttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\nAnd within this code base:\n\n\treadme.md : for a manual for this interpreter\n\tlibforth.h : for information about the C API\n\tlibforth.c : for the interpreter itself\n\tunit.c : unit tests for libforth.c\n\tunit.fth : unit tests against this file\n\tmain.c : an example interpreter\n\nThe interpreter and this code originally descend from a Forth\ninterpreter written in 1992 for the International obfuscated\nC Coding Competition.\n\nSee:\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\nThe manual for the interpreter should be read first before\nlooking into this code. It is important to understand the\nexecution model of Forth, especially the differences between\ncommand and compile mode, and how immediate and compiling\nwords work.\n\nEach of these sections is clearly labeled and they are\ngenerally in dependency order.\n\nUnfortunately the code in this file is not as portable as it\ncould be, it makes assumptions about the size of cells provided\nby the virtual machine, which will take time to rectify. Some\nof the constructs are subtly different from the DPANs Forth\nspecification, which is usually noted. Eventually this should\nalso be fixed.\n\nA little note on how code is formatted, a line of Forth code\nshould not exceed 64 characters. All words stack effect, how\nmany variables on the stack it accepts and returns, should\nbe commented with the following types:\n\n\tchar \/ c A character\n\tc-addr An address of a character\n\taddr An address of a cell\n\tr-addr A real address*\n\tu A unsigned number\n\tn A signed number\n\tc\" xxx\" The word parses a word\n\tc\" x\" The word parses a single character\n\txt An execution token\n\tbool A boolean value\n\tior A file error return status [0 on no error]\n\tfileid A file identifier.\n\tCODE A number from a words code field\n\tPWD A number from a words previous word field\n\t* A real address is one outside the range of the\n\tForth address space.\n\nIn the comments Forth words should be written in uppercase. As\nthis is supposed to be a tutorial about Forth and describe the\ninternals of a Forth interpreter, be as verbose as possible.\n\nThe code in this file will need to be modified to abide by\nthese standards, but new code should follow it from the start.\n\nDoxygen style tags for documenting bugs, todos and warnings\nshould be used within comments. This makes finding code that\nneeds working on much easier.)\n\n( ==================== Basic Word Set ======================== )\n\n( We'll begin by defining very simple words we can use later,\nthese a very basic words, that perform simple tasks, they\nwill not require much explanation.\n\nEven though the words are simple, their stack comment and\na description for them will still be included so external\ntools can process and automatically extract the document\nstring for a given work. )\n\n: postpone ( c\" xxx\" -- : postpone execution of a word )\n\timmediate find , ;\n\n: constant\n\t:: ( compile word header )\n\there 1 - h ! ( decrement dictionary pointer )\n\t( change instruction to CONST )\n\there @ instruction-mask invert and doconst or here !\n\there 1 + h ! ( increment dictionary pointer )\n\t, ( write in value )\n\tpostpone [ ; ( back into command mode )\n\n( These constants are defined as a space saving measure,\nnumbers in a definition usually take up two cells, one\nfor the instruction to push the next cell and the cell\nitself, for the most frequently used numbers it is worth\ndefining them as constants, it is just as fast but saves\na lot of space )\n-1 constant -1\n 0 constant 0\n 1 constant 1\n 2 constant 2\n 3 constant 3\n\n0 constant false\n1 constant true ( @warning not standards compliant )\n\n( Confusingly the word CR prints a line feed )\n10 constant lf ( line feed )\nlf constant nl ( new line - line feed on Unixen )\n13 constant cret ( carriage return )\n\n-1 -1 1 rshift invert and constant min-signed-integer\nmin-signed-integer invert constant max-signed-integer\n\n( The following version number is used to mark whether core\nfiles will be compatible with each other, The version number\ngets stored in the core file and is used by the loader to\ndetermine compatibility )\n4 constant version ( version number for the interpreter )\n\n( This constant defines the number of bits in an address )\ncell size 8 * * constant address-unit-bits \n\n( Bit corresponding to the sign in a number )\n-1 -1 1 rshift and invert constant sign-bit \n\n( @todo test by how much, if at all, making words like 1+,\n1-, <>, and other simple words, part of the interpreter would\nspeed things up )\n\n: 1+ ( x -- x : increment a number )\n\t1 + ;\n\n: 1- ( x -- x : decrement a number )\n\t1 - ;\n\n: chars ( c-addr -- addr : convert a c-addr to an addr )\n\tsize \/ ;\n\n: chars> ( addr -- c-addr: convert an addr to a c-addr )\n\tsize * ;\n\n: tab ( -- : print a tab character )\n\t9 emit ;\n\n: 0= ( n -- bool : is 'n' equal to zero? )\n\t0 = ;\n\n: not ( n -- bool : is 'n' true? )\n\t0= ;\n\n: <> ( n n -- bool : not equal )\n\t= 0= ;\n\n: logical ( n -- bool : turn a value into a boolean )\n\tnot not ;\n\n: 2, ( n n -- : write two values into the dictionary )\n\t, , ;\n\n: [literal] ( n -- : write a literal into the dictionary )\n\tdolit 2, ;\n\n: literal ( n -- : immediately compile a literal )\n\timmediate [literal] ;\n\n: sliteral immediate ( I: c-addr u --, Run: -- c-addr u )\n\tswap [literal] [literal] ;\n\n( @todo throw if not found )\n: ['] ( I: c\" xxx\", Run: -- xt )\n\timmediate find [literal] ;\n\n: >instruction ( CODE -- u : extract instruction CODE field )\n\tinstruction-mask and ;\n\n( IMMEDIATE-MASK pushes the mask for the compile bit,\nwhich can be used on a CODE field of a word )\n1 compile-bit lshift constant immediate-mask\n\n: hidden? ( PWD -- PWD bool : is a word hidden? )\n\tdup 1+ @ hidden-mask and logical ;\n\n: compiling? ( PWD -- PWD bool : is a word immediate? )\n\tdup 1+ @ immediate-mask and logical ;\n\n: cr ( -- : emit a newline character )\n\tnl emit ;\n\n: < ( x1 x2 -- bool : signed less than comparison )\n\t- dup if max-signed-integer u> else logical then ;\n\n: > ( x1 x2 -- bool : signed greater than comparison )\n\t- dup if max-signed-integer u< else logical then ;\n\n( The pad area is an area used for temporary storage, some\nwords use it, although which ones do should be kept to a\nminimum. It is an area of space #pad amount of characters\nafter the latest dictionary definition. The area between\nthe end of the dictionary and start of PAD space is used for\npictured numeric output [<#, #, #S, #>]. It is best not to\nuse the pad area that much. )\n128 constant #pad\n\n: pad ( -- addr : push pointer to the pad area )\n\there #pad + ;\n\n( @todo this can be improved a lot, currently it uses more\nspace than it has to, 4 cells instead of three.\n\nIt does:\n\n\tpush value\n\tpush value\n\nInstead of:\n\n\tmagic-2literal-word\n\tvalue\n\tvalue\n\n)\n: 2literal immediate ( n n -- : compile two literals )\n\tswap [literal] [literal] ;\n\n: latest ( get latest defined word )\n\tpwd @ ;\n\n: stdin ( -- fileid : push fileid for standard input )\n\t`stdin @ ;\n\n: stdout ( -- fileid : push fileid for standard output )\n\t`stdout @ ;\n\n: stderr ( -- fileid : push fileid for the standard error )\n\t`stderr @ ;\n\n: stdin? ( -- bool : are we reading from standard input )\n\t`fin @ stdin = ;\n\n: *+ ( n1 n2 n3 -- n )\n\t* + ;\n\t\n: 2- ( n -- n : decrement by two )\n\t2 - ;\n\n: 2+ ( n -- n : increment by two )\n\t2 + ;\n\n: 3+ ( n -- n : increment by three )\n\t3 + ;\n\n: 2* ( n -- n : multiply by two )\n\t1 lshift ;\n\n: 2\/ ( n -- n : divide by two )\n\t1 rshift ;\n\n: 4* ( n -- n : multiply by four )\n\t2 lshift ;\n\n: 4\/ ( n -- n : divide by four )\n\t2 rshift ;\n\n: 8* ( n -- n : multiply by eight )\n\t3 lshift ;\n\n: 8\/ ( n -- n : divide by eight )\n\t3 rshift ;\n\n: 256* ( n -- n : multiply by 256 )\n\t8 lshift ;\n\n: 256\/ ( n -- n : divide by 256 )\n\t8 rshift ;\n\n: 2dup ( n1 n2 -- n1 n2 n1 n2 : duplicate two values )\n\tover over ;\n\n: mod ( u1 u2 -- u : calculate the remainder of u1\/u2 )\n\t2dup \/ * - ;\n\n( @todo implement UM\/MOD in the VM, then use this to implement\n'\/' and MOD )\n: um\/mod ( u1 u2 -- rem quot : remainder and quotient of u1\/u2 )\n\t2dup \/ >r mod r> ;\n\n( @warning this does not use a double cell for the multiply )\n: *\/ ( n1 n2 n3 -- n4 : [n2*n3]\/n1 )\n\t * \/ ;\n\n: char ( -- n : read in a character from the input steam )\n\tkey drop key ;\n\n: [char] ( c\" x\" -- R: -- char : immediately compile next char )\n\timmediate char [literal] ;\n\n( COMPOSE is a high level function that can take two executions\ntokens and produce a unnamed function that can do what they\nboth do.\n\nIt can be used like so:\n\n\t:noname 2 ;\n\t:noname 3 + ;\n\tcompose\n\texecute \n\t.\n\t5 <-- 5 is printed!\n\nI have not found a use for it yet, but it sure is neat.)\n\n: compose ( xt1 xt2 -- xt3 : create a function from xt-tokens )\n\t>r >r ( save execution tokens )\n\tpostpone :noname ( create a new :noname word )\n\tr> , ( write first token )\n\tr> , ( write second token )\n\t(;) ; ( terminate new :noname )\n\n( CELLS is a word that is not needed in this interpreter but\nit required to write portable code [I have probably missed\nquite a few places where it should be used]. The reason it\nis not needed in this interpreter is a cell address can only\nbe in multiples of cells, not in characters. This should be\naddressed in the libforth interpreter as it adds complications\nwhen having to convert to and from character and cell address.)\n\n: cells ( n1 -- n2 : convert cell count to address count)\n\timmediate ;\n\n: cell+ ( a-addr1 -- a-addr2 )\n\tcell + ;\n\n: cell- ( a-addr1 -- addr2 )\n\tcell - ;\n\n: negative? ( x -- bool : is a number negative? )\n\tsign-bit and logical ;\n\n: mask-byte ( x -- x : generate mask byte )\n\t8* 255 swap lshift ;\n\n: select-byte ( u i -- c )\n\t8* rshift 0xff and ;\n\n: xt-instruction ( PWD -- CODE : extract instruction from PWD )\n\tcell+ @ >instruction ;\n\n: defined-word? ( PWD -- bool : is defined or a built-in word)\n\txt-instruction dolist = ;\n\n: char+ ( c-addr -- c-addr : increment a c-addr one c-addr )\n\t1+ ;\n\n: 2chars ( c-addr1 c-addr2 -- addr addr : chars on two c-addr) \n\tchars swap chars swap ;\n\n: 2chars> ( addr addr -- c-addr c-addr: chars> on two addr )\n\tchars> swap chars> swap ;\n\n: hex ( -- : print out hex )\n\t16 base ! ;\n\n: octal ( -- : print out octal )\n\t8 base ! ;\n\n: binary ( -- : print out binary )\n\t2 base ! ;\n\n: decimal ( -- : print out decimal )\n\t0 base ! ;\n\n: negate ( x -- x )\n\t-1 * ;\n\n: abs ( x -- u : return the absolute value of a number )\n\tdup negative? if negate then ;\n\n: square ( x -- x )\n\tdup * ;\n\n: sum-of-squares ( a b -- c : compute a^2 + b^2 to get c )\n\tsquare swap square + ;\n\n: drup ( x y -- x x )\n\tdrop dup ;\n\n: +! ( x addr -- : add x to a value stored at addr )\n\ttuck @ + swap ! ;\n\n: 1+! ( addr -- : increment a value at an address )\n\t1 swap +! ;\n\n: 1-! ( addr -- : decrement a value at an address )\n\t-1 swap +! ;\n\n: c+! ( x c-addr -- : add x to a value stored at c-addr )\n\ttuck c@ + swap c! ;\n\n: toggle ( addr u -- : xor value at addr with u )\n\tover @ xor swap ! ;\n\n: lsb ( x -- x : mask off the least significant byte of a cell )\n\t255 and ;\n\n: \\ ( -- : immediate word, used for single line comments )\n\timmediate begin key nl = until ;\n\n: ?dup ( x -- ? )\n\tdup if dup then ;\n\n: min ( n n -- n : return the minimum of two integers )\n\t2dup < if drop else nip then ;\n\n: max ( n n -- n : return the maximum of two integers )\n\t2dup > if drop else nip then ;\n\n: umin ( u u -- u : return the minimum of two unsigned numbers )\n\t2dup u< if drop else nip then ;\n\n: umax ( u u -- u : return the maximum of two unsigned numbers )\n\t2dup > if drop else nip then ;\n\n: limit ( x min max -- x : limit x with a minimum and maximum )\n\trot min max ;\n\n: >= ( n n -- bool )\n\t< not ;\n\n: <= ( n n -- bool )\n\t> not ;\n\n: 2@ ( a-addr -- u1 u2 : load two consecutive memory cells )\n\tdup 1+ @ swap @ ;\n\n: 2! ( u1 u2 a-addr -- : store two values at two consecutive memory cells )\n\t2dup ! nip 1+ ! ;\n\n: r@ ( -- u, R: u -- )\n\tr> r @ swap >r ;\n\n: rp@ ( -- u, R: u -- )\n\tr> r @ swap >r ;\n\n( @todo r!, rp! )\n\n: 0> ( n -- bool )\n\t0 > ;\n\n: 0<= ( n -- bool )\n\t0> not ;\n\n: 0< ( n -- bool )\n\t0 < ;\n\n: 0>= ( n -- bool )\n\t0< not ;\n\n: 0<> ( n -- bool )\n\t0 <> ;\n\n: signum ( n -- -1 | 0 | 1 : Signum function )\n\tdup 0> if drop 1 exit then\n\t 0< if -1 exit then\n\t0 ;\n\n: nand ( u u -- u : bitwise NAND )\n\tand invert ;\n\n: odd ( u -- bool : is 'n' odd? )\n\t1 and ;\n\n: even ( u -- bool : is 'n' even? )\n\todd not ;\n\n: nor ( u u -- u : bitwise NOR )\n\tor invert ;\n\n: ms ( u -- : wait at least 'u' milliseconds )\n\tclock + begin dup clock u< until drop ;\n\n: sleep ( u -- : sleep for 'u' seconds )\n\t1000 * ms ;\n\n: align ( addr -- addr : align an address, nop in this implemented )\n\timmediate ;\n\n: ) ( -- : do nothing, this allows easy commenting out of code )\n\timmediate ;\n\n: bell ( -- : emit an ASCII BEL character )\n\t7 emit ;\n\n: b\/buf ( -- u : bytes per buffer )\n\t1024 ;\n\n: .d ( x -- x : debug print )\n\tdup . ;\n\n: compile, ( x -- : )\n\t, ;\n\n: >mark ( -- : write a hole into the dictionary and push a pointer to it )\n\there 0 , ;\n\n: r - r> u< ;\n\n: invalidate ( -- : invalidate this Forth core )\n\t1 `invalid ! ;\n\n: signed ( x -- bool : return true if sign bit set )\n\t[ 1 size 8 * 1- lshift ] literal and logical ;\n\n: u>= ( x y -- bool : unsigned greater than or equal to )\n\t2dup u> >r = r> or ;\n\n: u<= ( x y -- bool : unsigned less than or equal to )\n\tu>= not ;\n\n: rdrop ( R: x -- : drop a value from the return stack )\n\tr> ( get caller's return address )\n\tr> ( get value to drop )\n\tdrop ( drop it like it's hot )\n\t>r ; ( return return address )\n\n: rdup\n\tr> ( get caller's return address )\n\tr> ( get value to duplicate )\n\tdup ( ... )\n\t>r >r >r ; ( make it all work )\n\n: chere ( -- c-addr : here as in character address units )\n\there chars> ;\n\n: source ( -- c-addr u )\n\t#tib ( size of input buffer, in characters )\n\ttib ; ( start of input buffer, in characters )\n\n: stdin? ( -- bool : are we reading from standard in? )\n\t`fin @ `stdin @ = ;\n\n: source-id ( -- 0 | -1 | file-id )\n\t( \t\n\tValue Input Source\n\t-1 String\n\t0 Reading from user input \/ standard in\n\tfile-id )\n\t`source-id @\n\t0= if\n\t\tstdin? if 0 else `fin @ then\n\telse\n\t\t-1\n\tthen ;\n\n: under ( x1 x2 -- x1 x1 x2 )\n\t>r dup r> ;\n\n: 2nip ( n1 n2 n3 n4 -- n3 n4 )\n\t>r >r 2drop r> r> ;\n\n: 2over ( n1 n2 n3 n4 \u2013 n1 n2 n3 n4 n1 n2 )\n\t>r >r 2dup r> swap >r swap r> r> -rot ;\n\n: 2swap ( n1 n2 n3 n4 \u2013 n3 n4 n1 n2 )\n\t>r -rot r> -rot ;\n\n: 2tuck ( n1 n2 n3 n4 \u2013 n3 n4 n1 n2 n3 n4 )\n\t2swap 2over ;\n\n: 3drop ( n1 n2 n3 -- )\n\tdrop 2drop ;\n\n: 4drop ( n1 n2 n3 n4 -- )\n\t2drop 2drop ;\n\n: nos1+ ( x1 x2 -- x1+1 x2 : increment the next variable on that stack )\n\tswap 1+ swap ;\n\n: ?dup-if immediate ( x -- x | - : ?dup and if rolled into one! )\n\t['] ?dup , postpone if ;\n\n: ?if ( -- : non destructive if )\n\timmediate ['] dup , postpone if ;\n\n: (hide) ( token -- hide-token : this hides a word from being found by the interpreter )\n\t?dup-if\n\t\tdup @ hidden-mask or swap tuck ! exit\n\tthen 0 ;\n\n: hide ( WORD -- : hide with drop )\n\tfind dup if (hide) then drop ;\n\n: reveal ( hide-token -- : reveal a hidden word )\n\tdup @ hidden-mask invert and swap ! ;\n\n: ?exit ( x -- : exit current definition if not zero )\n\tif rdrop exit then ;\n\n: decimal? ( c -- f : is character a number? )\n\t[char] 0 [ char 9 1+ ] literal within ;\n\n: lowercase? ( c -- f : is character lower case? )\n\t[char] a [ char z 1+ ] literal within ;\n\n: uppercase? ( C -- f : is character upper case? )\n\t[char] A [ char Z 1+ ] literal within ;\n\n: alpha? ( C -- f : is character part of the alphabet? )\n\tdup lowercase? swap uppercase? or ;\n\n: alphanumeric? ( C -- f : is character alphabetic or a number ? )\n\tdup alpha? swap decimal? or ;\n\n: printable? ( c -- bool : is printable, excluding new lines and tables )\n\t32 127 within ;\n\n: >upper ( c -- C : convert char to uppercase iff lower case )\n\tdup lowercase? if bl xor then ;\n\n: >lower ( C -- c : convert char to lowercase iff upper case )\n\tdup uppercase? if bl xor then ;\n\n: <=> ( x y -- z : spaceship operator! )\n\t2dup\n\t> if 2drop -1 exit then\n\t< ;\n\n: start-address ( -- c-addr : push the start address )\n\t`start-address @ ;\n\n: >real-address ( c-addr -- r-addr : convert an interpreter address to a real address )\n\tstart-address + ;\n\n: real-address> ( c-addr -- r-addr : convert a real address to an interpreter address )\n\tstart-address - ;\n\n: peek ( r-addr -- n : )\n\tpad chars> >real-address swap size memory-copy pad @ ;\n\n: poke ( n r-addr -- : )\n\tswap pad ! pad chars> >real-address size memory-copy ;\n\n: die! ( x -- : controls actions when encountering certain errors )\n\t`error-handler ! ;\n\n: start! ( cfa -- : set the word to execute at startup )\n\t`instruction ! ;\t\n\n: warm ( -- : restart the interpreter, warm restart )\n\t1 restart ;\n\n: trip ( x -- x x x : triplicate a number )\n\tdup dup ;\n\n: roll ( xu xu-1 ... x0 u -- xu-1 ... x0 xu : move u+1 items on the top of the stack by u )\n\t[ smudge ] ( un-hide this word so we can call it recursively )\n\tdup 0 >\n\tif\n\t\tswap >r 1- roll r> swap\n\telse\n\t\tdrop\n\tthen ;\nsmudge\n\n: 2rot ( n1 n2 n3 n4 n5 n6 \u2013 n3 n4 n5 n6 n1 n2 )\n\t5 roll 5 roll ;\n\n: s>d ( x -- d : convert a signed value to a double width cell )\n\t( @note the if...else...then is only necessary as this Forths\n\tbooleans are 0 and 1, not 0 and -1 as it usually is )\n\tdup 0< if -1 else 0 then ;\n\n: trace ( level -- : set tracing level )\n\t`debug ! ;\n\n: verbose ( -- : get the log level )\n\t`debug @ ;\n\n: count ( c-addr1 -- c-addr2 u : get a string whose first char is its length )\n\tdup c@ nos1+ ;\n\n: bounds ( x y -- y+x x : make an upper and lower bound )\n\tover + swap ;\n\n: aligned ( unaligned -- aligned : align a pointer )\n\t[ size 1- ] literal +\n\t[ size 1- ] literal invert and ;\n\n: rdepth\n\tmax-core `stack-size @ - r @ swap - ;\n\n: argv ( -- r-addr : push pointer to array of string pointers to program )\n\t`argv @ ;\n\n: argc ( -- u : push the number of arguments in the argv array )\n\t`argc @ ;\n\n: +- ( x1 x2 -- x3 : copy the sign of x1 to x2 giving x3 )\n\t[ sign-bit 1- ] literal and\n\tswap\n\tsign-bit and or ;\n\n: \/string ( c-addr1 u1 u2 -- c-addr2 u2 : advance a string by n characters )\n\tover min rot over + -rot - ;\n\nhide stdin?\n\n: cfa immediate ( find-address -- cfa )\n\t( Given the address of the PWD field of a word this\n\tfunction will return an execution token for the word )\n\t( @todo if < dictionary start PWD is invalid )\n\t ;\n\n: again immediate\n\t( loop unconditionally in a begin-loop:\n\t\tbegin ... again )\n\t' branch , body ( xt -- a-addr : a-addr is data field of a CREATEd word )\n\\\tcfa 5 + ;\n\n\n: execute ( xt -- : given an execution token, execute the word )\n\t( create a word that pushes the address of a hole to write to.\n\tA literal takes up two words, '!' takes up one, that's right,\n\tsome self modifying code! )\n\t[ here 3 cells + literal ] ( calculate place to write to )\n\t! ( write an execution token to a hole )\n\t[ 0 , ] ; ( this is the hole we write )\n\n( See: http:\/\/lars.nocrew.org\/dpans\/dpans9.htm\n@todo turn this into a lookup table of strings\n\n Code Reserved for\n ---- ------------\n -1 ABORT\n -2 ABORT\"\n -3 stack overflow\n -4 stack underflow\n -5 return stack overflow\n -6 return stack underflow\n -7 do-loops nested too deeply during execution\n -8 dictionary overflow\n -9 invalid memory address\n -10 division by zero\n -11 result out of range\n -12 argument type mismatch\n -13 undefined word\n -14 interpreting a compile-only word\n -15 invalid FORGET\n -16 attempt to use zero-length string as a name\n -17 pictured numeric output string overflow\n -18 parsed string overflow\n -19 definition name too long\n -20 write to a read-only location\n -21 unsupported operation [e.g., AT-XY on a\n too-dumb terminal]\n -22 control structure mismatch\n -23 address alignment exception\n -24 invalid numeric argument\n -25 return stack imbalance\n -26 loop parameters unavailable\n -27 invalid recursion\n -28 user interrupt\n -29 compiler nesting\n -30 obsolescent feature\n -31 >BODY used on non-CREATEd definition\n -32 invalid name argument [e.g., TO xxx]\n -33 block read exception\n -34 block write exception\n -35 invalid block number\n -36 invalid file position\n -37 file I\/O exception\n -38 non-existent file\n -39 unexpected end of file\n -40 invalid BASE for floating point conversion\n -41 loss of precision\n -42 floating-point divide by zero\n -43 floating-point result out of range\n -44 floating-point stack overflow\n -45 floating-point stack underflow\n -46 floating-point invalid argument\n -47 compilation word list deleted\n -48 invalid POSTPONE\n -49 search-order overflow\n -50 search-order underflow\n -51 compilation word list changed\n -52 control-flow stack overflow\n -53 exception stack overflow\n -54 floating-point underflow\n -55 floating-point unidentified fault\n -56 QUIT\n -57 exception in sending or receiving a character\n -58 [IF], [ELSE], or [THEN] exception )\n\n( @todo integrate catch\/throw into the interpreter as primitives )\n: catch ( xt -- exception# | 0 : return addr on stack )\n\tsp@ >r ( xt : save data stack pointer )\n\t`handler @ >r ( xt : and previous handler )\n\tr@ `handler ! ( xt : set current handler )\n\texecute ( execute returns if no throw )\n\tr> `handler ! ( restore previous handler )\n\tr> drop ( discard saved stack ptr )\n\t0 ; ( 0 : normal completion )\n\n( @todo use this everywhere )\n: throw ( ??? exception# -- ??? exception# )\n\t?dup-if ( exc# \\ 0 throw is no-op )\n\t\t`handler @ r ! ( exc# : restore prev return stack )\n\t\tr> `handler ! ( exc# : restore prev handler )\n\t\tr> swap >r ( saved-sp : exc# on return stack )\n\t\tsp! drop r> ( exc# : restore stack )\n\t\t( return to the caller of catch because return )\n\t\t( stack is restored to the state that existed )\n\t\t( when catch began execution )\n\tthen ;\n\n: interpret ( c1\" xxx\" ... cn\" xxx\" -- : This word implements the interpreter loop )\n\tbegin\n\t' read catch\n\t?dup-if [char] ! emit tab . cr then ( exception handler of last resort )\n\tagain ;\n\n: [interpret] ( c1\" xxx\" ... cn\" xxx\" -- : immediate version of interpret )\n\timmediate interpret ;\n\ninterpret ( use the new interpret word, which can catch exceptions )\n\nfind [interpret] cell+ start! ( the word executed on restart is now our new word )\n\n( The following words are using in various control structure related\nwords to make sure they only execute in the correct state )\n\n: ?comp ( -- : error if not compiling )\n\tstate @ 0= if -14 throw then ;\n\n: ?exec ( -- : error if not executing )\n\tstate @ if -22 throw then ;\n\n( begin...while...repeat These are defined in a very \"Forth\" way )\n: while\n\t?comp\n\timmediate postpone if ( branch to repeats THEN ) ;\n\n: whilst postpone while ;\n\n: repeat immediate\n\t?comp\n\tswap ( swap BEGIN here and WHILE here )\n\tpostpone again ( again jumps to begin )\n\tpostpone then ; ( then writes to the hole made in if )\n\n: never ( never...then : reserve space in word )\n\timmediate ?comp 0 [literal] postpone if ;\n\n: unless ( bool -- : like IF but execute clause if false )\n\timmediate ?comp ['] 0= , postpone if ;\n\n: endif ( synonym for THEN )\n\timmediate ?comp postpone then ;\n\n( ==================== Basic Word Set ======================== )\n\n( ==================== DOER\/MAKE ============================= )\n( DOER\/MAKE is a word set that is quite powerful and is\ndescribed in Leo Brodie's book \"Thinking Forth\". It can be\nused to make words whose behavior can change after they\nare defined. It essentially makes the structured use of\nself-modifying code possible, along with the more common\ndefinitions of \"defer\/is\".\n\nAccording to \"Thinking Forth\", it has two purposes:\n\n1. To change the state of a function.\n2. To factor out common phrases of a words definition.\n\nAn example of the first instance:\n\n\tdoer say\n\t: sad \" Good bye, cruel World!\" cr ;\n\t: happy \" Hello, World!\" cr ;\n\n\t: person say ;\n\n\tmake person happy\n\tperson \\ prints \"Good bye, cruel World!\"\n\n\tmake person sad\n\tperson \\ prints \"Hello, World!\"\n\nAn example of the second:\n\n\tdoer op\n\n\t: sum \\ n0 ... nX X -- sum<0..X>\n\t\tmake op + 1 do op loop ;\n\n\t: mul \\ n0 ... nX X -- mul<0..X>\n\t\tmake op * 1 do op loop ;\n\nThe above example is a bit contrived, the definitions and\nfunctionality are too simple for this to be worth factoring\nout, but it shows how you can use DOER\/MAKE. )\n\n: noop ; ( -- : default word to execute for doer, does nothing )\n\n: doer ( c\" xxx\" -- : make a work whose behavior can be changed by make )\n\timmediate ?exec :: ['] noop , (;) ;\n\n: found? ( xt -- xt : thrown an exception if the xt is zero )\n\tdup 0= if -13 throw then ;\n\n( It would be nice to provide a MAKE that worked with\nexecution tokens as well, although \"defer\" and \"is\" can be\nused for that. MAKE expects two word names to be given as\narguments. It will then change the behavior of the first word\nto use the second. MAKE is a state aware word. )\n\n: make immediate ( c1\" xxx\" c2\" xxx\" : change parsed word c1 to execute c2 )\n\tfind found? cell+\n\tfind found?\n\tstate @ if ( compiling )\n\t\tswap postpone 2literal ['] ! ,\n\telse ( command mode )\n\t\tswap !\n\tthen ;\n\n( ==================== DOER\/MAKE ============================= )\n\n( ==================== Extended Word Set ===================== )\n\n: r.s ( -- : print the contents of the return stack )\n\tr>\n\t[char] < emit rdepth (.) drop [char] > emit\n\tspace\n\trdepth dup 0> if dup\n\tbegin dup while r> -rot 1- repeat drop dup\n\tbegin dup while rot dup . >r 1- repeat drop\n\tthen drop cr\n\t>r ;\n\n: log ( u base -- u : command the _integer_ logarithm of u in base )\n\t>r\n\tdup 0= if -11 throw then ( logarithm of zero is an error )\n\t0 swap\n\tbegin\n\t\tnos1+ rdup r> \/ dup 0= ( keep dividing until 'u' is zero )\n\tuntil\n\tdrop 1- rdrop ;\n\n: log2 ( u -- u : compute the _integer_ logarithm of u )\n\t2 log ;\n\n: alignment-bits ( c-addr -- u : get the bits used for aligning a cell )\n\t[ 1 size log2 lshift 1- literal ] and ;\n\n: time ( \" ccc\" -- n : time the number of milliseconds it takes to execute a word )\n\tclock >r\n\tfind found? execute\n\tclock r> - ;\n\n( defer...is is probably not standards compliant, it is still neat! )\n: (do-defer) ( -- self : pushes the location into which it is compiled )\n\tr> dup >r 1- ;\n\n: defer immediate ( \" ccc\" -- , Run Time -- location :\n\tcreates a word that pushes a location to write an execution token into )\n\t?exec\n\t:: ' (do-defer) , (;) ;\n\n: is ( location \" ccc\" -- : make a deferred word execute a word )\n\tfind found? swap ! ;\n\nhide (do-defer)\n\n( This RECURSE word is the standard Forth word for allowing\nfunctions to be called recursively. A word is hidden from the\ncompiler until the matching ';' is hit. This allows for previous\ndefinitions of words to be used when redefining new words, it\nalso means that words cannot be called recursively unless the\nrecurse word is used.\n\nRECURSE calls the word being defined, which means that it\ntakes up space on the return stack. Words using recursion\nshould be careful not to take up too much space on the return\nstack, and of course they should terminate after a finite\nnumber of steps.\n\nWe can test \"recurse\" with this factorial function:\n\n : factorial dup 2 < if drop 1 exit then dup 1- recurse * ;\n\n)\n: recurse immediate\n\t?comp\n\tlatest cell+ , ;\n\n: myself ( -- : myself is a synonym for recurse )\n\timmediate postpone recurse ;\n\n( The \"tail\" function implements tail calls, which is just a\njump to the beginning of the words definition, for example\nthis word will never overflow the stack and will print \"1\"\nfollowed by a new line forever,\n\n\t: forever 1 . cr tail ;\n\nWhereas\n\n\t: forever 1 . cr recurse ;\n\nor\n\n\t: forever 1 . cr forever ;\n\nWould overflow the return stack. )\n\nhide tail\n: tail ( -- : perform tail recursion in current word definition )\n\timmediate\n\t?comp\n\tlatest cell+\n\t' branch ,\n\there - cell+ , ;\n\n: factorial ( x -- x : compute the factorial of a number )\n\tdup 2 < if drop 1 exit then dup 1- recurse * ;\n\n: gcd ( x1 x2 -- x : greatest common divisor )\n\tdup if tuck mod tail then drop ;\n\n( From: https:\/\/en.wikipedia.org\/wiki\/Integer_square_root\n\nThis function computes the integer square root of a number.\n\n@note this should be changed to the iterative algorithm so\nit takes up less space on the stack - not that is takes up\na hideous amount as it is. )\n\n: sqrt ( n -- u : integer square root )\n\tdup 0< if -11 throw then ( does not work for signed values )\n\tdup 2 < if exit then ( return 0 or 1 )\n\tdup ( u u )\n\t2 rshift recurse 2* ( u sc : 'sc' == unsigned small candidate )\n\tdup ( u sc sc )\n\t1+ dup square ( u sc lc lc^2 : 'lc' == unsigned large candidate )\n\t>r rot r> < ( sc lc bool )\n\tif drop else nip then ; ( return small or large candidate respectively )\n\n\n( ==================== Extended Word Set ===================== )\n\n( ==================== For Each Loop ========================= )\n( The foreach word set allows the user to take action over an\nentire array without setting up loops and checking bounds. It\nbehaves like the foreach loops that are popular in other\nlanguages.\n\nThe foreach word accepts a string and an execution token,\nfor each character in the string it passes the current address\nof the character that it should operate on.\n\nThe complexity of the foreach loop is due to the requirements\nplaced on it. It cannot pollute the variable stack with\nvalues it needs to operate on, and it cannot store values in\nlocal variables as a foreach loop could be called from within\nthe execution token it was passed. It therefore has to store\nall of it uses on the return stack for the duration of EXECUTE.\n\nAt the moment it only acts on strings as \"\/string\" only\nincrements the address passed to the word foreach executes\nto the next character address. )\n\n\\ (FOREACH) leaves the point at which the foreach loop\n\\ terminated on the stack, this allows programmer to determine\n\\ if the loop terminated early or not, and at which point.\n\n: (foreach) ( c-addr u xt -- c-addr u : execute xt for each cell in c-addr u\n\treturning number of items not processed )\n\tbegin\n\t\t3dup >r >r >r ( c-addr u xt R: c-addr u xt )\n\t\tnip ( c-addr xt R: c-addr u xt )\n\t\texecute ( R: c-addr u xt )\n\t\tr> r> r> ( c-addr u xt )\n\t\t-rot ( xt c-addr u )\n\t\t1 \/string ( xt c-addr u )\n\t\tdup 0= if rot drop exit then ( End of string - drop and exit! )\n\t\trot ( c-addr u xt )\n\tagain ;\n\n\\ If we do not care about returning early from the foreach\n\\ loop we can instead call FOREACH instead of (FOREACH),\n\\ it simply drops the results (FOREACH) placed on the stack.\n: foreach ( c-addr u xt -- : execute xt for each cell in c-addr u )\n\t(foreach) 2drop ;\n\n\\ RETURN is used for an early exit from within the execution\n\\ token, it leaves the point at which it exited\n: return ( -- n : return early from within a foreach loop function, returning number of items left )\n\trdrop ( pop off this words return value )\n\trdrop ( pop off the calling words return value )\n\trdrop ( pop off the xt token )\n\tr> ( save u )\n\tr> ( save c-addr )\n\trdrop ; ( pop off the foreach return value )\n\n\\ SKIP is an example of a word that uses the foreach loop\n\\ mechanism. It takes a string and a character and returns a\n\\ string that starts at the first occurrence of that character\n\\ in that string - or until it reaches the end of the string.\n\n\\ SKIP is defined in two steps, first there is a word,\n\\ (SKIP), that exits the foreach loop if there is a match,\n\\ if there is no match it does nothing. In either case it\n\\ leaves the character to skip until on the stack.\n\n: (skip) ( char c-addr -- char : exit out of foreach loop if there is a match )\n\tover swap c@ = if return then ;\n\n\\ SKIP then setups up the foreach loop, the char argument\n\\ will present on the stack when (SKIP) is executed, it must\n\\ leave a copy on the stack whatever happens, this is then\n\\ dropped at the end. (FOREACH) leaves the point at which\n\\ the loop terminated on the stack, which is what we want.\n\n: skip ( c-addr u char -- c-addr u : skip until char is found or until end of string )\n\t-rot ['] (skip) (foreach) rot drop ;\nhide (skip)\n\n( ==================== For Each Loop ========================= )\n\n( ==================== Hiding Words ========================== )\n( The two functions hide{ and }hide allow lists of words to\nbe hidden, instead of just hiding individual words. It stops\nthe dictionary from being polluted with meaningless words in\nan easy way. )\n\n: }hide ( should only be matched with 'hide{' )\n\timmediate -22 throw ;\n\n: hide{ ( -- : hide a list of words, the list is terminated with \"}hide\" )\n\t?exec\n\tbegin\n\t\tfind ( find next word )\n\t\tdup [ find }hide ] literal = if\n\t\t\tdrop exit ( terminate hide{ )\n\t\tthen\n\t\tdup 0= if -15 throw then\n\t\t(hide) drop\n\tagain ;\n\nhide (hide)\n\n( ==================== Hiding Words ========================== )\n\n( The words described here on out get more complex and will\nrequire more of an explanation as to how they work. )\n\n( ==================== Create Does> ========================== )\n\n( The following section defines a pair of words \"create\"\nand \"does>\" which are a powerful set of words that can be\nused to make words that can create other words. \"create\"\nhas both run time and compile time behavior, whilst \"does>\"\nonly works at compile time in conjunction with \"create\". These\ntwo words can be used to add constants, variables and arrays\nto the language, amongst other things.\n\nA simple version of create is as follows\n\n\t: create :: dolist , here 2 cells + , ' exit , 0 state ! ;\n\nBut this version is much more limited.\n\n\"create\"...\"does>\" is one of the constructs that makes Forth\nForth, it allows the creation of words which can define new\nwords in themselves, and thus allows us to extend the language\neasily. )\n\n: write-quote ( -- : A word that writes ' into the dictionary )\n\t['] ' , ;\n\n: write-exit ( -- : A word that write exit into the dictionary )\n\t['] _exit , ;\n\n: write-compile, ( -- : A word that writes , into the dictionary )\n\t' , , ;\n\n: command-mode ( -- : put the interpreter into command mode )\n\tfalse state ! ;\n\n: command-mode-create ( create a new work that pushes its data field )\n\t:: ( compile a word )\n\tdolit , ( write push into new word )\n\there 2 cells + , ( push a pointer to data field )\n\t(;) ; ( write exit and switch to command mode )\n\n: mark write-compile, ( Write in a place holder 0 and push a pointer to to be used by does> )\n\twrite-quote write-exit write-compile, ( Write in an exit in the word we're compiling. )\n\t['] command-mode , ; ( Make sure to change the state back to command mode )\n\n: create immediate ( create word is quite a complex forth word )\n\tstate @\n\tif\n\t\tpostpone ( hole-to-patch -- )\n\timmediate\n\t?comp\n\twrite-exit ( we don't want the defining word to exit, but the *defined* word to )\n\there swap ! ( patch in the code fields to point to )\n\tdolist , ; ( write a run in )\n\nhide{ command-mode-create write-quote write-compile, write-exit }hide\n\n( Now that we have create...does> we can use it to create\narrays, variables and constants, as we mentioned before. )\n\n: array ( u c\" xxx\" -- : create a named array of length u )\n\tcreate allot does> + ;\n\n: variable ( x c\" xxx\" -- : create a variable will initial value of x )\n\tcreate , does> ;\n\n\\ : constant ( x c\" xxx\" -- : create a constant with value of x )\n\\\tcreate , does> @ ;\n\n: table ( u c\" xxx\" --, Run Time: -- addr u : create a named table )\n\tcreate dup , allot does> dup @ ;\n\n: string ( u c\" xxx\" --, Run Time: -- c-addr u : create a named string )\n\tcreate dup , chars allot does> dup @ swap 1+ chars> swap ;\n\n\\ : +field \\ n <\"name\"> -- ; exec: addr -- 'addr\n\\ create over , +\n\\ does> @ + ;\n\\\n\\ : begin-structure \\ -- addr 0 ; -- size\n\\ \tcreate\n\\ \there 0 0 , \\ mark stack, lay dummy\n\\ \tdoes> @ ; \\ -- rec-len\n\\\n\\ : end-structure \\ addr n --\n\\ swap ! ; \\ set len\n\\\n\\ begin-structure point\n\\ \tpoint +field p.x\n\\ \tpoint +field p.y\n\\ end-structure\n\\\n\\ This should work...\n\\ : buffer: ( u c\" xxx\" --, Run Time: -- addr )\n\\\tcreate allot ;\n\n: 2constant\n\tcreate , , does> dup 1+ @ swap @ ;\n\n: 2variable\n\tcreate , , does> ;\n\n: enum ( x \" ccc\" -- x+1 : define a series of enumerations )\n\tdup constant 1+ ;\n\n( ==================== Create Does> ========================== )\n\n( ==================== Do ... Loop =========================== )\n\n( The following section implements Forth's do...loop\nconstructs, the word definitions are quite complex as it\ninvolves a lot of juggling of the return stack. Along with\nbegin...until do loops are one of the main looping constructs.\n\nUnlike begin...until do accepts two values a limit and a\nstarting value, they are also words only to be used within a\nword definition, some Forths extend the semantics so looping\nconstructs operate in command mode, this Forth does not do\nthat as it complicates things unnecessarily.\n\nExample:\n\n\t: example-1\n\t\t10 1 do\n\t\t\ti . i 5 > if cr leave then loop\n\t\t100 . cr ;\n\n\texample-1\n\nPrints:\n\t1 2 3 4 5 6\n\nIn \"example-1\" we can see the following:\n\n1. A limit, 10, and a start value, 1, passed to \"do\".\n2. A word called 'i', which is the current count of the loop.\n3. If the count is greater than 5, we call a word call\nLEAVE, this word exits the current loop context as well as\nthe current calling word.\n4. \"100 . cr\" is never called. This should be changed in\nfuture revision, but this version of leave exits the calling\nword as well.\n\n'i', 'j', and LEAVE *must* be used within a do...loop\nconstruct.\n\nIn order to remedy point 4. loop should not use branch but\ninstead should use a value to return to which it pushes to\nthe return stack )\n\n: (do)\n\tswap ( swap the limit and start )\n\tr> ( save our return stack to temporary variable )\n\t-rot ( limit start return -- return start limit )\n\t>r ( push limit onto return stack )\n\t>r ( push start onto return stack )\n\t>r ; ( restore our return address )\n\n: do immediate ( Run time: high low -- : begin do...loop construct )\n\t?comp\n\t' (do) ,\n\tpostpone begin ;\n\n: (unloop) ( -- , R: i limit -- : remove limit and i from )\n\tr> ( save our return address )\n\trdrop ( pop off i )\n\trdrop ( pop off limit )\n\t>r ; ( restore our return stack )\n\n: (+loop) ( x -- bool : increment loop variable by x and test it )\n\tr@ 1- ( get the pointer to i )\n\t+! ( add value to it )\n\tr@ 1- @ ( find i again )\n\tr@ 2- @ ( find the limit value )\n\tu>= ;\n\n: (loop) ( -- bool : increment loop variable by 1 and test it )\n\tr@ 1- ( get the pointer to i )\n\t1+! ( add one to it )\n\tr@ 1- @ ( find the value again )\n\tr@ 2- @ ( find the limit value )\n\tu>= ;\n\n: loop ( -- : end do...loop construct )\n\timmediate ?comp ' (loop) , postpone until ' (unloop) , ;\n\n: +loop ( x -- : end do...+loop loop construct )\n\timmediate ?comp ' (+loop) , postpone until ' (unloop) , ;\n\n: leave ( -- , R: i limit return -- : break out of a do-loop construct )\n\t(unloop)\n\trdrop ; ( return to the caller's caller routine )\n\n: ?leave ( x -- , R: i limit return -- | i limit return : conditional leave )\n\tif\n\t\t(unloop)\n\t\trdrop ( return to the caller's caller routine )\n\tthen ;\n\n\\ @todo define '(i)', '(j)' and '(k)', then make their\n\\ wrappers, 'i', 'j' and 'k' call ?comp then compile a pointer\n\\ to the thing that implements them, likewise for leave,\n\\ loop and +loop.\n: i ( -- i : Get current, or innermost, loop index in do...loop construct )\n\tr> r> ( pop off return address and i )\n\ttuck ( tuck i away )\n\t>r >r ; ( restore return stack )\n\n: j ( -- j : Get outermost loop index in do...loop construct )\n\t4 rpick ;\n\n( This is a simple test function for the looping, for interactive\ntesting and debugging:\n : mm 5 1 do i . cr 4 1 do j . tab i . cr loop loop ; )\n\n: range ( nX nY -- nX nX+1 ... nY )\n\tnos1+ do i loop ;\n\n: repeater ( n0 X -- n0 ... nX )\n\t1 do dup loop ;\n\n: sum ( n0 ... nX X -- sum<0..X> )\n\t1 do + loop ;\n\n: mul ( n0 ... nX X -- mul<0..X> )\n\t1 do * loop ;\n\n: reverse ( x1 ... xn n -- xn ... x1 : reverse n items on the stack )\n\t0 do i roll loop ;\n\n( ==================== Do ... Loop =========================== )\n\n( ==================== String Substitution =================== )\n\n: (subst) ( char1 char2 c-addr )\n\t3dup ( char1 char2 c-addr char1 char2 c-addr )\n\tc@ = if ( char1 char2 c-addr char1 )\n\t\tswap c! ( match, substitute character )\n\telse ( char1 char2 c-addr char1 )\n\t\t2drop ( no match )\n\tthen ;\n\n: subst ( c-addr u char1 char2 -- replace all char1 with char2 in string )\n\tswap\n\t2swap\n\t['] (subst) foreach 2drop ;\nhide (subst)\n\n0 variable c\n0 variable sub\n0 variable #sub\n\n: (subst-all) ( c-addr : search in sub\/#sub for a character to replace at c-addr )\n\tsub @ #sub @ bounds ( get limits )\n\tdo\n\t\tdup ( duplicate supplied c-addr )\n\t\tc@ i c@ = if ( check if match )\n\t\t\tdup\n\t\t\tc chars c@ swap c! ( write out replacement char )\n\t\tthen\n\tloop drop ;\n\n: subst-all ( c-addr1 u c-addr2 u char -- replace chars in str1 if in str2 with char )\n\tc chars c! #sub ! sub ! ( store strings away )\n\t['] (subst-all) foreach ;\n\nhide{ c sub #sub (subst-all) }hide\n\n( ==================== String Substitution =================== )\n\n0 variable column-counter\n4 variable column-width\n\n: column ( i -- )\t\n\tcolumn-width @ mod not if cr then ;\n\n: column.reset\t\t\n\t0 column-counter ! ;\n\n: auto-column\t\t\n\tcolumn-counter dup @ column 1+! ;\n\n0 variable x\n: x! ( x -- )\n\tx ! ;\n\n: x@ ( -- x )\n\tx @ ;\n\n: 2>r ( x1 x2 -- R: x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tswap\n\t\t>r\n\t\t>r\n\tx@ >r ; ( restore return address )\n\n: 2r> ( R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\t\tr>\n\t\tr>\n\t\tswap\n\tx@ >r ; ( restore return address )\n\n: 2r@ ( -- x1 x2 , R: x1 x2 -- x1 x2 )\n\tr> x! ( pop off this words return address )\n\tr> r>\n\t2dup\n\t>r >r\n\tswap\n\tx@ >r ; ( restore return address )\n\n: unused ( -- u : push the amount of core left )\n\tmax-core here - ;\n\n: accumulator ( initial \" ccc\" -- : make a word that increments by a value and pushes the result )\n\tcreate , does> tuck +! @ ;\n\n: counter ( \" ccc\" --, Run Time: -- x : make a word that increments itself by one, starting from zero )\n\tcreate -1 , does> dup 1+! @ ;\n\n0 variable delim\n: accepter ( c-addr max delimiter -- i )\n\t( store a \"max\" number of chars at c-addr until \"delimiter\" encountered,\n\tthe number of characters stored is returned )\n\tdelim ! ( store delimiter used to stop string storage when encountered)\n\t0\n\tdo\n\t\tkey dup delim @ <>\n\t\tif\n\t\t\tover c! 1+\n\t\telse ( terminate string )\n\t\t\tdrop 0 swap c!\n\t\t\ti\n\t\t\tleave\n\t\tthen\n\tloop\n\t-18 throw ; ( read in too many chars )\nhide delim\n\n: skip ( char -- : read input until string is reached )\n\tkey drop >r 0 begin drop key dup rdup r> <> until rdrop ;\n\n: word ( c -- c-addr : parse until 'c' is encountered, push transient counted string )\n\tdup skip chere 1+ c!\n\t>r\n\tchere 2+\n\tpad here - chars>\n\tr> accepter 1+\n\tchere c!\n\tchere ;\nhide skip\n\n: accept ( c-addr +n1 -- +n2 : see accepter definition )\n\tnl accepter ;\n\n0xFFFF constant max-string-length\n\n: (.\") ( char -- c-addr u )\n\t( @todo This really needs simplifying, to do this\n\ta set of words that operate on a temporary buffer can\n\tbe used )\n\t( Write a string into word being currently defined, this\n\tcode has to jump over the string it has just put into the\n\tdictionary so normal execution of a word can continue. The\n\tlength and character address of the string are left on the\n\tstack )\n\t>r ( save delimiter )\n\t' branch , ( write in jump, this will jump past the string )\n\t>mark ( make hole )\n\tdup 1+ chars> ( calculate address to write to )\n\tmax-string-length\n\tr> ( restore delimiter )\n\taccepter dup >r ( write string into dictionary, save index )\n\taligned 2dup size \/ ( stack: length hole char-len hole )\n\t1+ dup allot ( update dictionary pointer with string length )\n\t1+ swap ! ( write place to jump to )\n\tdrop ( do not need string length anymore )\n\t1+ chars> ( calculate place to print )\n\tr> ; ( restore index and address of string )\n\n: length ( c-addr u -- u : push the length of an ASCIIZ string )\n tuck 0 do dup c@ 0= if 2drop i leave then 1+ loop ;\n\n: asciiz? ( c-addr u -- : is a Forth string also a ASCIIZ string )\n\ttuck length <> ;\n\n: asciiz ( c-addr u -- : trim a string until NUL terminator )\n\t2dup length nip ;\n\n\n: (type) ( c-addr -- : emit a single character )\n\tc@ emit ;\n\n: type ( c-addr u -- : print out 'u' characters at c-addr )\n\t['] (type) foreach ;\nhide (type)\n\n: do-string ( char -- : write a string into the dictionary reading it until char is encountered )\n\t(.\")\n\tstate @ if swap [literal] [literal] then ;\n\n: fill ( c-addr u char -- : fill in an area of memory with a character, only if u is greater than zero )\n\t-rot\n\t0 do 2dup i + c! loop\n\t2drop ;\n\n: compare ( c-addr1 u1 c-addr2 u2 -- n : compare two strings, not quite compliant yet )\n\t>r swap r> min >r\n\tstart-address + swap start-address + r>\n\tmemory-compare ;\n\n128 string sbuf\n: s\" ( \"ccc\" --, Run Time -- c-addr u )\n\tkey drop sbuf 0 fill sbuf [char] \" accepter sbuf drop swap ;\nhide sbuf\n\n( @todo these strings really need rethinking, state awareness needs to be removed... )\n: type,\n\tstate @ if ' type , else type then ;\n\n: c\"\n\timmediate key drop [char] \" do-string ;\n\n: \"\n\timmediate key drop [char] \" do-string type, ;\n\n: sprint ( c -- : print out chars until 'c' is encountered )\n\tkey drop ( drop next space )\n\t>r ( save delimiter )\n\tbegin\n\t\tkey dup ( get next character )\n\t\trdup r> ( get delimiter )\n\t\t<> if emit 0 then\n\tuntil rdrop ;\n\n: .(\n\timmediate [char] ) sprint ;\nhide sprint\n\n: .\"\n\timmediate key drop [char] \" do-string type, ;\n\nhide type,\n\n( This word really should be removed along with any usages\nof this word, it is not a very \"Forth\" like word, it accepts\na pointer to an ASCIIZ string and prints it out, it also does\nnot checking of the returned values from write-file )\n: print ( c-addr -- : print out a string to the standard output )\n\t-1 over >r length r> swap stdout write-file 2drop ;\n\n: ok\n\t\" ok\" cr ;\n\n: empty-stack ( x-n ... x-0 -- : empty the variable stack )\n\tbegin depth while drop repeat ;\n\n: (quit) ( -- : do the work of quit, without the restart )\n\t0 `source-id ! ( set source to read from file )\n\t`stdin @ `fin ! ( read from stdin )\n\tpostpone [ ( back into command mode )\n\t' interpret start! ; ( set interpreter starting word )\n\n: quit ( -- : Empty return stack, go back to command mode, read from stdin, interpret input )\n\t(quit)\n\t-1 restart ; ( restart the interpreter )\n\n: abort\n\t-1 throw ;\n\n: (abort\") ( do the work of abort )\n\t(quit)\n\t-2 throw ;\n\n: abort\" immediate\n\tpostpone \"\n\t' cr , ' (abort\") , ;\n\n( ==================== CASE statements ======================= )\n( This simple set of words adds case statements to the\ninterpreter, the implementation is not particularly efficient,\nbut it works and is simple.\n\nBelow is an example of how to use the CASE statement,\nthe following word, \"example\" will read in a character and\nswitch to different statements depending on the character\ninput. There are two cases, when 'a' and 'b' are input, and\na default case which occurs when none of the statements match:\n\n\t: example\n\t\tchar\n\t\tcase\n\t\t\t[char] a of \" a was selected \" cr endof\n\t\t\t[char] b of \" b was selected \" cr endof\n\n\t\t\tdup \\ encase will drop the selector\n\t\t\t\" unknown char: \" emit cr\n\t\tendcase ;\n\n\texample a \\ prints \"a was selected\"\n\texample b \\ prints \"b was selected\"\n\texample c \\ prints \"unknown char: c\"\n\nOther examples of how to use case statements can be found\nthroughout the code.\n\nFor a simpler case statement see, Volume 2, issue 3, page 48\nof Forth Dimensions at http:\/\/www.forth.org\/fd\/contents.html )\n\n: case immediate\n\t?comp\n\t' branch , 3 cells , ( branch over the next branch )\n\there ' branch , ( mark: place endof branches back to with again )\n\t>mark swap ; ( mark: place endcase writes jump to with then )\n\n: over= ( x y -- [x 0] | 1 : )\n\tover = if drop 1 else 0 then ;\n\n: of\n\timmediate ?comp ' over= , postpone if ;\n\n: endof\n\timmediate ?comp over postpone again postpone then ;\n\n: endcase\n\timmediate ?comp ' drop , 1+ postpone then drop ;\n\n( ==================== CASE statements ======================= )\n\ndoer (banner)\nmake (banner) space\n\n: banner ( n -- : )\n\tdup 0<= if drop exit then\n\t0 do (banner) loop ;\n\n: zero ( -- : emit a single 0 character )\n\t[char] 0 emit ;\n\n: spaces ( n -- : print n spaces if n is greater than zero )\n\tmake (banner) space\n\tbanner ;\n\n: zeros ( n -- : print n spaces if n is greater than zero )\n\tmake (banner) zero\n\tbanner ;\n\nhide{ (banner) banner }hide\n\n: erase ( addr u : erase a block of memory )\n\t2chars> 0 fill ;\n\n: blank ( c-addr u : fills a string with spaces )\n\tbl fill ;\n\n( move should check that u is not negative )\n: move ( addr1 addr2 u -- : copy u words of memory from 'addr2' to 'addr1' )\n\t0 do\n\t\t2dup i + @ swap i + !\n\tloop\n\t2drop ;\n\n( It would be nice if move and cmove could share more code, as they do exactly\n the same thing but with different load and store functions, cmove> )\n: cmove ( c-addr1 c-addr2 u -- : copy u characters of memory from 'c-addr2' to 'c-addr1' )\n\t0 do\n\t\t2dup i + c@ swap i + c!\n\tloop\n\t2drop ;\n\n( ==================== Conditional Compilation =============== )\n( The words \"[if]\", \"[else]\" and \"[then]\" implement conditional\ncompilation, they can be nested as well\n\nSee http:\/\/lars.nocrew.org\/dpans\/dpans15.htm for more\ninformation\n\nA much simpler conditional compilation method is the following\nsingle word definition:\n\n : compile-line? 0= if [ find \\\\ , ] then ;\n\nWhich will skip a line if a conditional is false, and compile\nit if true )\n\n( These words really, really need refactoring, I could use the newly defined\n \"defer\" to help out with this )\n0 variable nest ( level of [if] nesting )\n0 variable [if]-word ( populated later with \"find [if]\" )\n0 variable [else]-word ( populated later with \"find [else]\")\n: [then] immediate ;\n: reset-nest 1 nest ! ;\n: unnest? [ find [then] ] literal = if nest 1-! then ;\n: nest? [if]-word @ = if nest 1+! then ;\n: end-nest? nest @ 0= ;\n: match-[else]? [else]-word @ = nest @ 1 = and ;\n\n: [if] ( bool -- : conditional execution )\n\t?exec\n\tunless\n\t\treset-nest\n\t\tbegin\n\t\t\tfind\n\t\t\tdup nest?\n\t\t\tdup match-[else]? if drop exit then\n\t\t\t unnest?\n\t\t\tend-nest?\n\t\tuntil\n\tthen ;\n\n: [else] ( discard input until [then] encounter, nesting for [if] )\n\t?exec\n\treset-nest\n\tbegin\n\t\tfind\n\t\tdup nest? unnest?\n\t\tend-nest?\n\tuntil ;\n\nfind [if] [if]-word !\nfind [else] [else]-word !\n\n: ?( if postpone ( then ; \\ conditionally read until ')'\n: ?\\ if postpone \\ then ;\n: 16bit\\ size 2 <> if postpone \\ then ;\n: 32bit\\ size 4 <> if postpone \\ then ;\n: 64bit\\ size 8 <> if postpone \\ then ;\n\nhide{\n\t[if]-word [else]-word nest\n\treset-nest unnest? match-[else]?\n\tend-nest? nest?\n}hide\n\n( ==================== Conditional Compilation =============== )\n\n( ==================== Endian Words ========================== )\n( This words are allow the user to determinate the endianess\nof the machine that is currently being used to execute libforth,\nthey make heavy use of conditional compilation )\n\nsize 2 = [if] 0x0123 `x ! [then]\nsize 4 = [if] 0x01234567 `x ! [then]\nsize 8 = [if] 0x01234567abcdef `x ! [then]\n\n: endian ( -- bool : returns the endianess of the processor, little = 0, big = 1 )\n\t[ `x chars> c@ 0x01 = ] literal ;\n\n: swap16 ( x -- x : swap the byte order a 16 bit number )\n\tdup 256* 0xff00 and >r 256\/ lsb r> or ;\n\nsize 4 >= [if]\n\t: swap32\n\t\tdup 0xffff and swap16 16 lshift swap\n\t\t16 rshift 0xffff and swap16 or ;\n[then]\n\nsize 8 >= [if]\n\t: swap64 ( x -- x : swap the byte order of a 64 bit number )\n\t\t dup 0xffffffff and swap32 32 lshift swap\n\t\t 32 rshift 0xffffffff and swap32 or ;\n[then]\n\nsize 2 = [if]\n\tendian\n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order )\n\t\tswap16 ;\n\t: >big ( x -- x : host byte order to big endian order )\n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order )\n\t\t;\n\t: >big ( x -- x : host byte order to big endian order )\n\t\tswap16 ;\n\t[then]\n[then]\n\nsize 4 = [if]\n\tendian\n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order )\n\t\tswap32 ;\n\t: >big ( x -- x : host byte order to big endian order )\n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order )\n\t\t;\n\t: >big ( x -- x : host byte order to big endian order )\n\t\tswap32 ;\n\t[then]\n[then]\n\nsize 8 = [if]\n\tendian\n\t[if] ( host is big endian )\n\t: >little ( x -- x : host byte order to little endian order )\n\t\tswap64 ;\n\t: >big ( x -- x : host byte order to big endian order )\n\t\t;\n\t[else] ( host is little endian )\n\t: >little ( x -- x : host byte order to little endian order )\n\t\t;\n\t: >big ( x -- x : host byte order to big endian order )\n\t\tswap64 ;\n\t[then]\n[then]\n\n( ==================== Endian Words ========================== )\n\n( ==================== Misc words ============================ )\n\n: (base) ( -- base : unmess up libforth's base variable )\n\tbase @ dup 0= if drop 10 then ;\n\n: #digits ( u -- u : number of characters needed to represent 'u' in current base )\n\tdup 0= if 1+ exit then\n\t(base) log 1+ ;\n\n: digits ( -- u : number of characters needed to represent largest unsigned number in current base )\n\t-1 #digits ;\n\n: cdigits ( -- u : number of characters needed to represent largest characters in current base )\n\t0xff #digits ;\n\n: .r ( u -- print a number taking up a fixed amount of space on the screen )\n\tdup #digits digits swap - spaces . ;\n\n: ?.r ( u -- : print out address, right aligned )\n\t@ .r ;\n\n0 variable counter\n\n: counted-column ( index -- : special column printing for dump )\n\tcounter @ column-width @ mod\n\tnot if cr .r \" :\" space else drop then\n\tcounter 1+! ;\n\n: .chars ( x n -- : print a cell out as characters, upto n chars )\n\t0 ( from zero to the size of a cell )\n\tdo\n\t\tdup ( copy variable to print out )\n\t\tsize i 1+ - select-byte ( select correct byte )\n\t\tdup printable? not ( is it not printable )\n\t\tif drop [char] . then ( print a '.' if it is not )\n\t\temit ( otherwise print it out )\n\tloop\n\tdrop ; ( drop cell we have printed out )\n\n: lister ( addr u addr -- )\n\t0 counter ! 1- swap\n\tdo\n\t\tdup counted-column 1+ i ?.r i @ size .chars space\n\tloop ;\n\n( @todo this function should make use of DEFER and IS, then different\nversion of dump could be made that swapped out LISTER )\n: dump ( addr u -- : dump out 'u' cells of memory starting from 'addr' )\n\t1+ over + under lister drop\n\tcr ;\n\nhide{ counted-column counter }hide\n\n( Fence can be used to prevent any word defined before it from being forgotten\nUsage:\n\there fence ! )\n0 variable fence\n\n: ?fence ( addr -- : throw an exception of address is before fence )\n\tfence @ u< if -15 throw then ;\n\n: (forget) ( pwd-token -- : forget a found word and everything after it )\n\tdup 0= if -15 throw then ( word not found! )\n\tdup ?fence\n\tdup @ pwd ! h ! ;\n\n: forget ( c\" xxx\" -- : forget word and every word defined after it )\n\tfind 1- (forget) ;\n\n0 variable fp ( FIND Pointer )\n\n: rendezvous ( -- : set up a rendezvous point )\n\there ?fence\n\there fence !\n\tlatest fp ! ;\n\n: retreat ( -- : retreat to the rendezvous point, forgetting any words )\n\tfence @ h !\n\tfp @ pwd ! ;\n\nhide{ fp }hide\n\n: marker ( c\" xxx\" -- : make word the forgets itself and words after it)\n\t:: latest [literal] ' (forget) , (;) ;\nhere fence ! ( This should also be done at the end of the file )\nhide (forget)\n\n: ** ( b e -- x : exponent, raise 'b' to the power of 'e')\n\t?dup-if\n\t\tover swap\n\t\t1 do over * loop\n\t\tnip\n\telse\n\t\tdrop 1\n\tthen ;\n\n0 variable a\n0 variable b\n0 variable m\n: equal ( a1...an b1...bn n -- a1...an b1...bn bool : determine if two lists are equal )\n\t( example:\n\t\t1 2 3\n\t\t1 2 3\n\t\t3 equal\n\treturns: 1 )\n\tdup m ! 1+ 1 ( store copy of length and use as loop index )\n\tdo\n\t\ti 1- pick b ! ( store ith element of list in b1...bn )\n\t\ti m @ + 1- pick a ! ( store ith element of list in a1...an )\n\t\ta @ b @ <> ( compare a and b for equality )\n\t\tif 0 leave then ( unequal, finish early )\n\tloop 1 ; ( lists must be equal )\n\nhide{ a b m }hide\n\n: ndrop ( u1...un n -- : drop n items )\n\t?dup-if 0 do drop loop then ;\n\n: caesar ( c key -- o : encode a alphabetic character with a key using a generalization of the Caesar cipher )\n\t>r\n\tdup uppercase? if [char] A - r> + 26 mod [char] A + exit then\n\tdup lowercase? if [char] a - r> + 26 mod [char] a + exit then\n\trdrop ; ( it goes without saying that this should not be used for anything serious! )\n\n: caesar-type ( c-addr u key : type out encoded text with a Caesar cipher )\n\t-rot bounds do i c@ over caesar emit loop drop ;\n\n: rot13 ( c -- c : encode a character with ROT-13 )\n\t13 caesar ;\n\n: rot13-type ( c-addr u : print string in ROT-13 encoded form )\n\t13 caesar-type ;\n\n\\ s\" abcdefghijklmnopqrstuvwxyz\" rot13-type -> nopqrstuvwxyzabcdefghijklm\n\\ s\" hello\" rot13-type -> uryyb\n\n( ==================== Misc words ============================ )\n\n( ==================== Pictured Numeric Output =============== )\n( Pictured numeric output is what Forths use to display\nnumbers to the screen, this Forth has number output methods\nbuilt into the Forth kernel and mostly uses them instead,\nbut the mechanism is still useful so it has been added.\n\n@todo Pictured number output should act on a double cell\nnumber not a single cell number )\n\n0 variable hld\n\n: overflow ( -- : check if we overflow the hold area )\n \there chars> pad chars> hld @ - u> if -17 throw then ;\n\n: hold ( char -- : add a character to the numeric output string )\n\toverflow pad chars> hld @ - c! hld 1+! ;\n\n: holds ( c-addr u -- : hold an entire string )\n begin dup while 1- 2dup + c@ hold repeat 2drop ;\n\n: <# ( -- : setup pictured numeric output )\n\t0 hld ! ;\n\n: sign ( -- : add a sign to the pictured numeric output string )\n\t[char] - hold ;\n\n: # ( x -- x : divide x by base, turn into a character, put in pictured output string )\n\t(base) um\/mod swap\n \tdup 9 u>\n \tif 7 + then\n \t48 + hold ;\n\n: #s ( x -- 0 : repeatedly call # on x until x is zero )\n\tbegin # dup 0= until ;\n\n: #> ( -- c-addr u : end pictured output conversion, push output string to stack )\n\t0 hold ( NUL terminate string, just in case )\n\thld 1-! ( but do not include that in the count )\n\tpad chars> hld @\n\ttuck - 1+ swap ;\n\ndoer characters\nmake characters spaces\n\n: u.rc\n\t>r <# #s #> rot drop r> over - characters type ;\n\n: u.r ( u n -- print a number taking up a fixed amount of space on the screen )\n\tmake characters spaces u.rc ;\n\n: u.rz ( u n -- print a number taking up a fixed amount of space on the screen, using leading zeros )\n\tmake characters zeros u.rc ;\n\n: u. ( u -- : display an unsigned number in current base )\n\t0 u.r ;\n\nhide{ overflow u.rc characters }hide\n\n( ==================== Pictured Numeric Output =============== )\n\n( ==================== Numeric Input ========================= )\n( The Forth executable can handle numeric input and does not\nneed the routines defined here, however the user might want\nto write routines that use >NUMBER. >NUMBER is a generic word,\nbut it is a bit difficult to use on its own. )\n\n: map ( char -- n|-1 : convert character in 0-9 a-z range to number )\n\tdup lowercase? if [char] a - 10 + exit then\n\tdup decimal? if [char] 0 - exit then\n\tdrop -1 ;\n\n: number? ( char -- bool : is a character a number in the current base )\n\t>lower map (base) u< ;\n\n: >number ( n c-addr u -- n c-addr u : convert string )\n\tbegin\n\t\t( get next character )\n\t\t2dup >r >r drop c@ dup number? ( n char bool, R: c-addr u )\n\t\tif ( n char )\n\t\t\tswap (base) * swap map + ( accumulate number )\n\t\telse ( n char )\n\t\t\tdrop\n\t\t\tr> r> ( restore string )\n\t\t\texit\n\t\tthen\n\t\tr> r> ( restore string )\n\t\t1 \/string dup 0= ( advance string and test for end )\n\tuntil ;\n\nhide{ map }hide\n\n( ==================== Numeric Input ========================= )\n\n( ==================== ANSI Escape Codes ===================== )\n( Terminal colorization module, via ANSI Escape Codes\n\nsee: https:\/\/en.wikipedia.org\/wiki\/ANSI_escape_code\nThese codes will provide a relatively portable means of\nmanipulating a terminal )\n\n27 constant 'escape'\n: CSI 'escape' emit .\" [\" ;\n0 constant black\n1 constant red\n2 constant green\n3 constant yellow\n4 constant blue\n5 constant magenta\n6 constant cyan\n7 constant white\n: foreground 30 + ;\n: background 40 + ;\n0 constant dark\n1 constant bright\nfalse variable colorize\n\n: 10u. ( n -- : print a number in decimal )\n\tbase @ >r decimal u. r> base ! ;\n\n: color ( brightness color-code -- : set the terminal color )\n\t( set color on an ANSI compliant terminal,\n\tfor example:\n\t\tbright red foreground color\n\tsets the foreground text to bright red )\n\tcolorize @ 0= if 2drop exit then\n\tCSI 10u. if .\" ;1\" then .\" m\" ;\n\n: at-xy ( x y -- : set ANSI terminal cursor position to x y )\n\tCSI 10u. [char] ; emit 10u. .\" H\" ;\n\n: page ( -- : clear ANSI terminal screen and move cursor to beginning )\n\tCSI .\" 2J\" 1 1 at-xy ;\n\n: hide-cursor ( -- : hide the cursor from view )\n\tCSI .\" ?25l\" ;\n\n: show-cursor ( -- : show the cursor )\n\tCSI .\" ?25h\" ;\n\n: save-cursor ( -- : save cursor position )\n\tCSI .\" s\" ;\n\n: restore-cursor ( -- : restore saved cursor position )\n\tCSI .\" u\" ;\n\n: reset-color ( -- : reset terminal color to its default value)\n\tcolorize @ 0= if exit then\n\tCSI .\" 0m\" ;\n\nhide{ CSI 10u. }hide\n( ==================== ANSI Escape Codes ===================== )\n\n( ==================== Unit test framework =================== )\n\n256 string estring ( string to test )\n0 variable #estring ( actual string length )\n0 variable start ( starting depth )\n0 variable result ( result depth )\n0 variable check ( only check depth if -> is called )\n0 variable dictionary ( dictionary pointer on entering { )\n0 variable previous ( PWD register on entering { )\n\n: T ; ( hack until T{ can process words )\n\n: -> ( -- : save depth in variable )\n\t1 check ! depth result ! ;\n\n: test estring drop #estring @ ;\n\n: fail ( -- : invalidate the forth interpreter and exit )\n\tinvalidate bye ;\n\n: neutral ( -- : neutral color )\n\t;\n\n: bad ( -- : bad color )\n\tdark red foreground color ;\n\n: good ( -- : good color )\n\tdark green foreground color ;\n\n: die bad test type reset-color cr fail ;\n\n: evaluate? ( bool -- : test if evaluation has failed )\n\tif .\" evaluation failed\" cr fail then ;\n\n: failed bad .\" failed\" reset-color cr ;\n\n: adjust ( x -- x : adjust a depth to take into account starting depth )\n\tstart @ - ;\n\n: no-check? ( -- bool : if true we need to check the depth )\n\tcheck @ 0= ;\n\n: depth? ( -- : check if depth is correct )\n\tno-check? if exit then\n\tdepth adjust ( get depth and adjust for starting depth )\n\tresult @ adjust 2* = ( get results depth, same adjustment, should be\n\t half size of the depth )\n\tif exit then ( pass )\n\tfailed\n\t.\" Unequal depths:\" cr\n\t.\" depth: \" depth . cr\n\t.\" result: \" result @ . cr\n\tdie ;\n\n: equal? ( -- : determine if results equals expected )\n\tno-check? if exit then\n\tresult @ adjust equal\n\tif exit then\n\tfailed\n\t.\" Result is not equal to expected values. \" cr\n\t.\" Stack: \" cr .s cr\n\tdie ;\n\n: display ( c-addr u -- : print out testing message in estring )\n\tverbose if neutral type else 2drop then ;\n\n: pass ( -- : print out passing message )\n\tverbose if good .\" ok \" cr reset-color then ;\n\n: save ( -- : save current dictionary )\n\tpwd @ previous !\n\there dictionary ! ;\n\n: restore ( -- : restore dictionary )\n\tprevious @ pwd !\n\tdictionary @ h ! ;\n\n\n: T{ ( -- : perform a unit test )\n\tdepth start ! ( save start of stack depth )\n\t0 result ! ( reset result variable )\n\t0 check ! ( reset check variable )\n\testring 0 fill ( zero input string )\n\tsave ( save dictionary state )\n\tkey drop ( drop next character, which is a space )\n\testring [char] } accepter #estring ! ( read in string to test )\n\ttest display ( print which string we are testing )\n\ttest evaluate ( perform test )\n\tevaluate? ( evaluate successfully? )\n\tdepth? ( correct depth )\n\tequal? ( results equal to expected values? )\n\tpass ( print pass message )\n\tresult @ adjust 2* ndrop ( remove items on stack generated by test )\n\trestore ; ( restore dictionary to previous state )\n\nT{ }T\nT{ -> }T\nT{ 1 -> 1 }T\nT{ 1 2 -> 1 2 }T\nT{ : c 1 2 ; c -> 1 2 }T\n( @bug ';' smudges the previous word, but :noname does\nnot. )\nT{ :noname 2 ; :noname 3 + ; compose execute -> 5 }T\n\nhide{\n\tpass test display\n\tadjust start save restore dictionary previous\n\tevaluate? equal? depth? estring #estring result\n\tcheck no-check? die neutral bad good failed\n}hide\n\n( ==================== Unit test framework =================== )\n\n\n( ==================== Pseudo Random Numbers ================= )\n( This section implements a Pseudo Random Number generator, it\nuses the xor-shift algorithm to do so.\nSee:\nhttps:\/\/en.wikipedia.org\/wiki\/Xorshift\nhttp:\/\/excamera.com\/sphinx\/article-xorshift.html\nhttp:\/\/xoroshiro.di.unimi.it\/\nhttp:\/\/www.arklyffe.com\/main\/2010\/08\/29\/xorshift-pseudorandom-number-generator\/\n\nThe constants used have been collected from various places\non the web and are specific to the size of a cell. )\n\nsize 2 = [if] 13 constant a 9 constant b 7 constant c [then]\nsize 4 = [if] 13 constant a 17 constant b 5 constant c [then]\nsize 8 = [if] 12 constant a 25 constant b 27 constant c [then]\n\n7 variable seed ( must not be zero )\n\n: seed! ( x -- : set the value of the PRNG seed )\n\tdup 0= if drop 7 ( zero not allowed ) then seed ! ;\n\n: random ( -- x : assumes word size is 32 bit )\n\tseed @\n\tdup a lshift xor\n\tdup b rshift xor\n\tdup c lshift xor\n\tdup seed! ;\n\nhide{ a b c seed }hide\n\n( ==================== Random Numbers ======================== )\n\n( ==================== Prime Numbers ========================= )\n( From original \"third\" code from the IOCCC at\nhttp:\/\/www.ioccc.org\/1992\/buzzard.2.design, the module works\nout and prints prime numbers. )\n\n: prime? ( u -- u | 0 : return number if it is prime, zero otherwise )\n\tdup 1 = if 1- exit then\n\tdup 2 = if exit then\n\tdup 2\/ 2 ( loop from 2 to n\/2 )\n\tdo\n\t\tdup ( value to check if prime )\n\t\ti mod ( mod by divisor )\n\t\tnot if\n\t\t\tdrop 0 leave\n\t\tthen\n\tloop ;\n\n0 variable counter\n\n: primes ( x1 x2 -- : print the primes from x2 to x1 )\n\t0 counter !\n\t\" The primes from \" dup . \" to \" over . \" are: \"\n\tcr\n\tcolumn.reset\n\tdo\n\t\ti prime?\n\t\tif\n\t\t\ti . counter @ column counter 1+!\n\t\tthen\n\tloop\n\tcr\n\t\" There are \" counter @ . \" primes.\"\n\tcr ;\n\nhide{ counter }hide\n( ==================== Prime Numbers ========================= )\n\n( ==================== Debugging info ======================== )\n( This section implements various debugging utilities that the\nprogrammer can use to inspect the environment and debug Forth\nwords. )\n\n( String handling should really be done with PARSE, and CMOVE )\n: sh ( cnl -- ior : execute a line as a system command )\n\tnl word count system ;\n\nhide{ .s }hide\n: .s ( -- : print out the stack for debugging )\n\t[char] < emit depth (.) drop [char] > emit space\n\tdepth if\n\t\tdepth 0 do i column tab depth i 1+ - pick . loop\n\tthen\n\tcr ;\n\n1 variable hide-words ( do we want to hide hidden words or not )\n\n: name ( PWD -- c-addr : given a pointer to the PWD field of a word get a pointer to the name of the word )\n\tdup 1+ @ 256\/ word-mask and lsb - chars> ;\n\n( This function prints out all of the defined words, excluding\nhidden words. An understanding of the layout of a Forth word\nhelps here. The dictionary contains a linked list of words,\neach forth word has a pointer to the previous word until the\nfirst word. The layout of a Forth word looks like this:\n\nNAME: Forth Word - A variable length ASCII NUL terminated\n string.\nPWD: Previous Word Pointer, points to the previous\n word.\nCODE: Flags, code word and offset from previous word\n pointer to start of Forth word string.\nDATA: The body of the forth word definition, not interested\n in this.\n\nThere is a register which stores the latest defined word which\ncan be accessed with the code \"pwd @\". In order to print out\na word we need to access a words CODE field, the offset to\nthe NAME is stored here in bits 8 to 14 and the offset is\ncalculated from the PWD field.\n\n\"print\" expects a character address, so we need to multiply\nany calculated address by the word size in bytes. )\n\n: words.immediate ( bool -- : emit or mark a word being printed as being immediate )\n\tnot if dark red foreground color then ;\n\n: words.defined ( bool -- : emit or mark a word being printed as being a built in word )\n\tnot if bright green background color then ;\n\n: words.hidden ( bool -- : emit or mark a word being printed as being a hidden word )\n\tif dark magenta foreground color then ;\n\n: words ( -- : print out all defined an visible words )\n\tlatest\n\tspace\n\tbegin\n\t\tdup\n\t\thidden? hide-words @ and\n\t\tnot if\n\t\t\thidden? words.hidden\n\t\t\tcompiling? words.immediate\n\t\t\tdup defined-word? words.defined\n\t\t\tname\n\t\t\tprint space\n\t\t\treset-color\n\t\telse\n\t\t\tdrop\n\t\tthen\n\t\t@ ( Get pointer to previous word )\n\t\tdup dictionary-start u< ( stop if pwd no longer points to a word )\n\tuntil\n\tdrop cr ;\n\n( Simpler version of words\n: words\n\tpwd @\n\tbegin\n\t\tdup name print space @ dup dictionary-start u<\n\tuntil drop cr ; )\n\nhide{ words.immediate words.defined words.hidden hidden? hidden-bit }hide\n\n: TrueFalse ( bool -- : print true or false )\n\tif \" true\" else \" false\" then ;\n\n: registers ( -- : print out important registers and information about the virtual machine )\n\t\" return stack pointer: \" r@ . cr\n\t\" dictionary pointer \" here . cr\n\t\" previous word: \" pwd ? cr\n\t\" state: \" state ? cr\n\t\" base: \" base ? cr\n\t\" depth: \" depth . cr\n\t\" cell size (in bytes): \" size . cr\n\t\" last cell address: \" max-core . cr\n\t\" unused cells: \" unused . cr\n\t\" invalid: \" `invalid @ TrueFalse cr\n\t\" size of variable stack: \" `stack-size ? cr\n\t\" size of return stack: \" `stack-size ? cr\n\t\" start of variable stack: \" max-core `stack-size @ 2* - . cr\n\t\" start of return stack: \" max-core `stack-size @ - . cr\n\t\" current input source: \" source-id -1 = if \" string\" else \" file\" then cr\n\t\" tracing on: \" `debug @ TrueFalse cr\n\t\" starting word: \" `instruction ? cr\n\t\" real start address: \" `start-address ? cr\n\t\" error handling: \" `error-handler ? cr\n\t\" throw handler: \" `handler ? cr\n\t\" signal recieved: \" `signal ? cr ;\n\t\n( `sin `sidx `slen `fout\n `stdout `stderr `argc `argv )\n\n\n: y\/n? ( -- bool : ask a yes or no question )\n\tkey drop\n\t\" y\/n? \"\n\tbegin\n\t\tkey\n\t\tdup\n\t\t[char] y = if true exit then\n\t\t[char] n = if false exit then\n\t\t\" y\/n? \"\n\tagain ;\n\n: step\n\t( step through a word: this word could be augmented\n\twith commands such as \"dump\", \"halt\", and optional\n\t\".s\" and \"registers\" )\n\tregisters\n\t\" .s: \" .s cr\n\t\" -- press any key to continue -- \"\n\tkey drop ;\n\n: more ( -- : wait for more input )\n\t\" -- press any key to continue -- \" key drop cr page ;\n\n: debug-help ( -- : print out the help for the debug command )\n \" debug mode commands\n\th - print help\n\tq - exit interpreter word\n\tr - print registers\n\ts - print stack\n\tR - print return stack\n\tc - continue on with execution\n\" ;\n\ndoer debug-prompt\n: prompt-default\n\t.\" debug> \" ;\n\nmake debug-prompt prompt-default\n\n: debug ( -- : enter interactive debug prompt )\n\tcr\n\t\" Entered Debug Prompt. Type 'h' for help. \" cr\n\tbegin\n\t\tkey\n\t\tcase\n\t\t\tnl of debug-prompt endof\n\t\t\t[char] h of debug-help endof\n\t\t\t[char] q of bye endof\n\t\t\t[char] r of registers endof\n\t\t\t[char] s of .s endof\n\t\t\t[char] R of r.s endof\n\t\t\t[char] c of exit endof\n\t\t\t( @todo add throw here )\n\t\tendcase\n\tagain ;\nhide debug-prompt\n\n: code>pwd ( CODE -- PWD\/0 : calculate PWD from code address )\n\tdup dictionary-start here within not if drop 0 exit then\n\t1 cells - ;\n\n: word-printer ( CODE -- : print out a words name given its code field )\n\tdup 1 cells - @ -1 = if . \" noname\" exit then ( nonames are marked by a -1 before its code field )\n\tdup code>pwd ?dup-if .d name print else drop \" data\" then\n\t drop ;\n\nhide{ code>pwd }hide\n\n( these words push the execution tokens for various special\ncases for decompilation )\n: get-branch [ find branch ] literal ;\n: get-?branch [ find ?branch ] literal ;\n: get-original-exit [ find _exit ] literal ;\n: get-quote [ find ' ] literal ;\n\n( @todo replace 2- nos1+ nos1+ with appropriate word, like\nthe string word that increments a string by an amount, but\nthat operates on CELLS )\n: branch-increment ( addr branch -- increment : calculate decompile increment for \"branch\" )\n\t1+ dup negative?\n\tif\n\t\tover cr . [char] : emit space . cr 2\n\telse\n\t\t2dup 2- nos1+ nos1+ dump\n\tthen ;\n\n( these words take a code field to a primitive they implement,\ndecompile it and any data belonging to that operation, and push\na number to increment the decompilers code stream pointer by )\n\n: decompile-literal ( code -- increment )\n\t1+ ? \" literal\" 2 ;\n\n: decompile-branch ( code -- increment )\n\tdark red foreground color\n\t1+ ? \" branch \" dup 1+ @ branch-increment ;\n\n: decompile-quote ( code -- increment )\n\tdark green foreground color\n\tdup\n\t[char] ' emit 1+ @ word-printer 2 reset-color ;\n\n: decompile-?branch ( code -- increment )\n\t1+ ? \" ?branch\" 2 ;\n\n: decompile-exit ( code -- 0 )\n\t\" _exit\" cr \" End of word: \" . 0 ;\n\n( The decompile word expects a pointer to the code field of\na word, it decompiles a words code field, it needs a lot of\nwork however. There are several complications to implementing\nthis decompile function.\n\n\t'\t The next cell should be pushed\n\n\t:noname This has a marker before its code field of\n\t -1 which cannot occur normally, this is\n\t handled in word-printer\n\n\tbranch\t branches are used to skip over data, but\n\t also for some branch constructs, any data\n\t in between can only be printed out\n\t generally speaking\n\n\texit\t There are two definitions of exit, the one\n\t used in ';' and the one everything else uses,\n\t this is used to determine the actual end\n\t of the word\n\n\tliterals Literals can be distinguished by their\n\t low value, which cannot possibly be a word\n\t with a name, the next field is the\n\t actual literal\n\nOf special difficult is processing IF, THEN and ELSE\nstatements, this will require keeping track of '?branch'.\n\nAlso of note, a number greater than \"here\" must be data )\n\n: decompile ( code-pointer -- code-pointer increment|0 : )\n\t.d [char] : emit space dup @\n\tcase\n\t\tdolit of dup decompile-literal cr endof\n\t\tget-branch of dup decompile-branch endof\n\t\tget-quote of dup decompile-quote cr endof\n\t\tget-?branch of dup decompile-?branch cr endof\n\t\tget-original-exit of dup decompile-exit endof\n\t\tdup word-printer 1 swap cr\n\tendcase reset-color ;\n\n: decompiler ( code-field-ptr -- : decompile a word in its entirety )\n\tbegin decompile over + tuck = until drop ;\n\nhide{\n\tword-printer get-branch get-?branch get-original-exit\n\tget-quote branch-increment decompile-literal\n\tdecompile-branch decompile-?branch decompile-quote\n\tdecompile-exit\n}hide\n\n( these words expect a pointer to the PWD field of a word )\n: see.name \" name: \" name print cr ;\n: see.start \" word start: \" name chars . cr ;\n: see.previous \" previous word: \" @ . cr ;\n: see.immediate \" immediate: \" compiling? nip not TrueFalse cr ;\n: see.instruction \" instruction: \" xt-instruction . cr ;\n: see.defined \" defined: \" defined-word? TrueFalse cr ;\n\n: see.header ( PWD -- is-immediate-word? )\n\tdup see.name\n\tdup see.start\n\tdup see.previous\n\tdup see.immediate\n\tdup see.instruction ( @todo look up instruction name )\n\tsee.defined ;\n\n( @todo This does not work for all words, so needs fixing.\n Specifically:\n\n\t2variable\n\t2constant\n\ttable\n\tconstant\n\tvariable\n\tarray\nWhich are all complex CREATE words\n\nA good way to test decompilation is with the following\nUnix pipe:\n\n\t.\/forth -f forth.fth -e words\n\t\t| sed 's\/ \/ see \/g'\n\t\t| .\/forth -t forth.fth &> decompiled.log\n)\n\n( @todo refactor into word that takes a PWD pointer and one that attempts to parse\/find name )\n: see ( c\" xxx\" -- : decompile a word )\n\tfind\n\tdup 0= if -32 throw then\n\tcell- ( move to PWD field )\n\tdup see.header\n\tdup defined-word?\n\tif ( decompile if a compiled word )\n\t\t2 cells + ( move to code field )\n\t\t\" code field:\" cr\n\t\tdecompiler\n\telse ( the instruction describes the word if it is not a compiled word )\n\t\tdup 1 cells + @ instruction-mask and doconst = if ( special case for constants )\n\t\t\t\" constant: \" 2 cells + @ .\n\t\telse\n\t\t\tdrop\n\t\tthen\n\tthen cr ;\n\n( @todo This has a bug, if any data within a word happens\nto match the address of _exit word.end calculates the wrong\naddress, this needs to mirror the DECOMPILE word )\n: word.end ( addr -- addr : find the end of a word )\n\tbegin\n\t\tdup\n\t\t@ [ find _exit ] literal = if exit then\n\t\tcell+\n\tagain ;\n\n: (inline) ( xt -- : inline an word from its execution token )\n\tdup cell- defined-word? if\n\t\tcell+\n\t\tdup word.end over - here -rot dup allot move\n\telse\n\t\t,\n\tthen ;\n\n: ;inline ( -- : terminate :inline )\n\timmediate -22 throw ;\n\n: :inline immediate\n\t?comp\n\tbegin\n\t\tfind found?\n\t\tdup [ find ;inline ] literal = if\n\t\t\tdrop exit ( terminate :inline )\n\t\tthen\n\t\t(inline)\n\tagain ;\n\nhide{\n\tsee.header see.name see.start see.previous see.immediate\n\tsee.instruction defined-word? see.defined _exit found?\n\t(inline) word.end\n}hide\n\n( These help messages could be moved to blocks, the blocks\ncould then be loaded from disk and printed instead of defining\nthe help here, this would allow much larger help )\n\n: help ( -- : print out a short help message )\n\tpage\n\tkey drop\n\" Welcome to Forth, an imperative stack based language. It is\nboth a low level and a high level language, with a very small\nmemory footprint. Most of Forth is defined as a combination\nof various primitives.\n\nA short description of the available function (or Forth words)\nfollows, words marked (1) are immediate and cannot be used in\ncommand mode, words marked with (2) define new words. Words\nmarked with (3) have both command and compile functionality.\n\n\"\nmore \" Some of the built in words that accessible are:\n\n(1,2)\t: define a new word, switching to compile mode\n\timmediate make latest defined word immediate\n\tread read in a word, execute in command mode else compile\n\t@ ! fetch, store\n\tc@ c! character based fetch and store\n\t- + * \/ standard arithmetic operations,\n\tand or xor invert standard bitwise operations\n\tlshift rshift left and right bit shift\n\tu< u> < > = comparison predicates\n\texit exit from a word\n\temit print character from top of stack\n\tkey get a character from input\n\tr> >r pop a value from or to the return stack\n\tfind find a word in the dictionary and push the location\n\t' store the address of the following word on the stack\n\t, write the top of the stack to the dictionary\n\tswap swap first two values on the stack\n\tdup duplicate the top of the stack\n\tdrop pop and drop a value\n\tover copy the second stack value over the first\n\t. pop the top of the stack and print it\n\"\nmore \"\n\tprint print a NUL terminated string at a character address\n\tdepth get the current stack depth\n\tclock get the time since execution start in milliseconds\n\tevaluate evaluate a string\n\tsystem execute a system command\n\tclose-file close a file handle\n\topen-file open a file handle\n\tdelete-file delete a file off disk given a string\n\tread-file read in characters from a file\n\twrite-file write characters to a file\n\tfile-position get the file offset\n\treposition-file reposition the file pointer\n\tflush-file flush a file to disk\n\trename-file rename a file on disk\n \"\n\nmore \" All of the other words in the interpreter are built\nfrom these primitive words. A few examples:\n\n(1)\tif...else...then FORTH branching construct\n(1)\tbegin...until loop until top of stack is non zero\n(1)\tbegin...again infinite loop\n(1)\tdo...loop FORTH looping construct\n(2,3)\tcreate create a new word that pushes its location\n(1)\tdoes> declare a created words run time behaviour\n(1,2)\tvariable declare variable with initial value from top of stack\n(1,2)\tconstant declare a constant, taken from top of stack\n(1,2)\tarray declare an array with size taken from top of stack\n(1)\t; terminate a word definition and return to command mode\n\twords print out a list of all the defined words\n\thelp this help message\n\tdump print out memory contents starting at an address\n\tregisters print out the contents of the registers\n\tsee decompile a word, viewing what words compose it\n\t.s print out the contents of the stack\n\n\"\n\nmore \" Some more advanced words:\n\n\there push the dictionary pointer\n\th push the address of the dictionary pointer\n\tr push the return stack pointer\n\tallot allocate space in the dictionary\n(1)\t[ switch to command mode\n\t] switch to compile mode\n\t:: compile ':' into the dictionary\n\n\" more \"\nFor more information either consult the manual pages forth(1)\nand libforth(1) or consult the following sources:\n\n\thttps:\/\/github.com\/howerj\/libforth\n\thttp:\/\/work.anapnea.net\/html\/html\/projects.html\n\nAnd for a larger tutorial:\n\n\thttps:\/\/github.com\/howerj\/libforth\/blob\/master\/readme.md\n\nFor resources on Forth:\n\n\thttps:\/\/en.wikipedia.org\/wiki\/Forth_%28programming_language%29\n\thttp:\/\/www.ioccc.org\/1992\/buzzard.2.design\n\thttps:\/\/rwmj.wordpress.com\/2010\/08\/07\/jonesforth-git-repository\/\n\n -- end --\n\" cr\n;\n\n( ==================== Debugging info ======================== )\n\n( ==================== Files ================================= )\n( These words implement more of the standard file access words\nin terms of the ones provided by the virtual machine. These\nwords are not the most easy to use words, although the ones\ndefined here and the ones that are part of the interpreter are\nthe standard ones.\n\nSome thoughts:\n\nI believe extensions to this word set, once I have figured\nout the semantics, should be made to make them easier to use,\nones which automatically clean up after failure and call throw\nwould be more useful [and safer] when dealing with a single\ninput or output stream. The most common action after calling\none of the file access words is to call throw any way.\n\nFor example, a word like:\n\n\t: #write-file \\ c-addr u fileid -- fileid u\n\t\tdup >r\n\t\twrite-file dup if r> close-file throw throw then\n\t\tr> swap ;\n\nWould be easier to deal with, it preserves the file identifier\nand throws if there is any problem. It would be a bit more\ndifficult to use when there are two files open at a time.\n\n@todo implement the other file access methods in terms of the\nbuilt in ones.\n@todo read-line and write-line need their flag and ior setting\ncorrectly\n\n\tFILE-SIZE [ use file-positions ]\n\nAlso of note, Source ID needs extending.\n\nSee: [http:\/\/forth.sourceforge.net\/std\/dpans\/dpans11.htm] )\n\n: read-char ( c-addr fileid -- ior : read a char )\n\t1 swap read-file 0<> swap 1 <> or ;\n\n0 variable x\n\n: getchar ( fileid -- char ior )\n\tx chars> swap read-char x chars> c@ swap ;\n\n: write-char ( c-addr fileid -- ior : write a char )\n\t1 swap write-file 0<> swap 1 <> or ;\n\n: putchar ( char fileid -- ior )\n\tswap x chars> c! x chars> swap write-char ;\n\nhide{ x }hide\n\n: rewind-file ( file-id -- : rewind a file to the beginning )\n\t0 reposition-file throw ;\n\n: read-line ( c-addr u1 fileid -- u2 flag ior : read in a line of text )\n\t-rot bounds\n\tdo\n\t\tdup i swap read-char drop\n\t\ti c@ nl = if drop i 0 0 leave then\n\tloop drop ;\n\n: write-line ( c-addr u fileid -- u2 flag ior : write a line of text )\n\t-rot bounds\n\tdo\n\t\tdup i swap write-char drop\n\t\ti c@ nl = if drop i 0 0 leave then\n\tloop ;\n\n: resize-file ( ud fileid -- ior : attempt to resize a file )\n\t( There is no portable way to truncate a file :C )\n\t2drop -1 ( -1 to indicate failure ) ;\n\n: create-file ( c-addr u fam -- fileid ior )\n\t>r 2dup w\/o open-file throw close-file throw\n\tr> open-file ;\n\n: include-file ( file-id -- : evaluate a file )\n\tdup >r 0 1 evaluator r> close-file throw throw ;\n\n: included ( c-addr u -- : attempt to open up a name file and evaluate it )\n\tr\/o open-file throw\n\tinclude-file ;\n\n: include ( c\" ccc\" -- : attempt to evaluate a named file )\n\t( @bug requires trailing space, should use parse-name )\n\tbl word count included ;\n\n: bin ( fam1 -- fam2 : modify a file access method to be binary not line oriented )\n\t( Do nothing, all file access methods are binary )\n\t;\n\n( ==================== Files ================================= )\n\n( ==================== Matcher =============================== )\n( The following section implements a very simple regular\nexpression engine, which expects an ASCIIZ Forth string. It\nis translated from C code and performs an identical function.\n\nThe regular expression language is as follows:\n\n\tc\tmatch a literal character\n\t.\tmatch any character\n\t*\tmatch any characters\n\nThe \"*\" operator performs the same function as \".*\" does in\nmost other regular expression engines. Most other regular\nexpression engines also do not anchor their selections to the\nbeginning and the end of the string to match, instead using\nthe operators '^' and '$' to do so, to emulate this behavior\n'*' can be added as either a suffix, or a prefix, or both,\nto the matching expression.\n\nAs an example \"*, World!\" matches both \"Hello, World!\" and\n\"Good bye, cruel World!\". \"Hello, ....\" matches \"Hello, Bill\"\nand \"Hello, Fred\" but not \"Hello, Tim\" as there are two few\ncharacters in the last string.\n\n@todo make a matcher that expects a Forth string, which do\nnot have to be NUL terminated )\n\n\\ Translated from http:\/\/c-faq.com\/lib\/regex.html\n\\ int match(char *pat, char *str)\n\\ {\n\\ \tswitch(*pat) {\n\\ \tcase '\\0': return !*str;\n\\ \tcase '*': return match(pat+1, str) || *str && match(pat, str+1);\n\\ \tcase '.': return *str && match(pat+1, str+1);\n\\ \tdefault: return *pat == *str && match(pat+1, str+1);\n\\ \t}\n\\ }\n\n: *pat ( regex -- regex char : grab next character of pattern )\n\tdup c@ ;\n\n: *str ( string regex -- string regex char : grab next character string to match )\n\tover c@ ;\n\n: pass ( c-addr1 c-addr2 -- bool : pass condition, characters matched )\n\t2drop 1 ;\n\n: reject ( c-addr1 c-addr2 -- bool : fail condition, character not matched )\n\t2drop 0 ;\n\n: *pat==*str ( c-addr1 c-addr2 -- c-addr1 c-addr2 bool )\n\t2dup c@ swap c@ = ;\n\n: ++ ( u1 u2 u3 u4 -- u1+u3 u2+u4 : not quite d+ [does no carry] )\n\tswap >r + swap r> + swap ;\n\ndefer matcher\n\n: advance ( string regex char -- bool : advance both regex and string )\n\tif 1 1 ++ matcher else reject then ;\n\n: advance-string ( string regex char -- bool : advance only the string )\n\tif 1 0 ++ matcher else reject then ;\n\n: advance-regex ( string regex -- bool : advance matching )\n\t2dup 0 1 ++ matcher if pass else *str advance-string then ;\n\n: match ( string regex -- bool : match a ASCIIZ pattern against an ASCIIZ string )\n\t( @todo Add limits and accept two Forth strings, making sure they are both\n\t ASCIIZ strings as well\n\t @warning This uses a non-standards compliant version of case! )\n\t*pat\n\tcase\n\t\t 0 of drop c@ not endof\n\t\t[char] * of advance-regex endof\n\t\t[char] . of *str advance endof\n\t\t\n\t\tdrop *pat==*str advance exit\n\n\tendcase ;\n\nmatcher is match\n\nhide{\n\t*str *pat *pat==*str pass reject advance\n\tadvance-string advance-regex matcher ++\n}hide\n\n( ==================== Matcher =============================== )\n\n\n( ==================== Cons Cells ============================ )\n( From http:\/\/sametwice.com\/cons.fs, this could be improved\nif the optional memory allocation words were added to\nthe interpreter. This provides a simple \"cons cell\" data\nstructure. There is currently no way to free allocated\ncells. I do not think this is particularly useful, but it is\ninteresting. )\n\n: car! ( value cons-addr -- : store a value in the car cell of a cons cell )\n\t! ;\n\n: cdr! ( value cons-addr -- : store a value in the cdr cell of a cons cell )\n\tcell+ ! ;\n\n: car@ ( cons-addr -- car-val : retrieve car value from cons cell )\n\t@ ;\n\n: cdr@ ( cons-addr -- cdr-val : retrieve cdr value from cons cell )\n\tcell+ @ ;\n\n: cons ( car-val cdr-val -- cons-addr : allocate a new cons cell )\n\tswap here >r , , r> ;\n\n: cons0 0 0 cons ;\n\n( ==================== Cons Cells ============================ )\n\n( ==================== License =============================== )\n( The license has been chosen specifically to make this library\nand any associated programs easy to integrate into arbitrary\nproducts without any hassle. For the main libforth program\nthe LGPL license would have been also suitable [although it\nis MIT licensed as well], but to keep confusion down the same\nlicense, the MIT license, is used in both the Forth code and\nC code. This has not been done for any ideological reasons,\nand I am not that bothered about licenses. )\n\n: license ( -- : print out license information )\n\"\nThe MIT License (MIT)\n\nCopyright (c) 2016, 2017 Richard James Howe\n\nPermission is hereby granted, free of charge, to any person\nobtaining a copy of this software and associated documentation\nfiles (the 'Software'), to deal in the Software without\nrestriction, including without limitation the rights to use,\ncopy, modify, merge, publish, distribute, sublicense, and\/or\nsell copies of the Software, and to permit persons to whom\nthe Software is furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY\nKIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\nWARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE\nAND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\nHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE\nOR OTHER DEALINGS IN THE SOFTWARE.\n\n\"\n;\n\n( ==================== License =============================== )\n\n( ==================== Core utilities ======================== )\n( Read the header of a core file and process it, printing the\nresults out )\n\n8 constant header-size ( size of Forth core file header )\n8 constant size-field-size ( the size in bytes of the size field in the core file )\n0 variable core-file ( core fileid we are reading in )\n0 variable core-cell-size ( cell size of Forth core )\n0 variable core-version ( version of core file )\n0 variable core-endianess ( endianess of core we are reading in )\n\n( save space to read in header )\ncreate header header-size chars allot\n: cheader ( -- c-addr : header char address )\n\theader chars> ;\ncreate size-field size-field-size chars allot\n: csize-field ( -- c-addr : address of place size field is stored in )\n\tsize-field chars> ;\n\n0\nenum header-magic0 ( magic number 0 : FF )\nenum header-magic1 ( magic number 1 : '4' )\nenum header-magic2 ( magic number 2 : 'T' )\nenum header-magic3 ( magic number 3 : 'H' )\nenum header-cell-size ( size of a forth cell, either 2, 4 or 8 bytes )\nenum header-version ( version of the forth core )\nenum header-endianess ( endianess of the core )\nenum header-log2size ( binary logarithm of the core size )\n\n: cleanup ( -- : cleanup before abort )\n\tcore-file @ ?dup 0<> if close-file drop then ;\n\n: invalid-header ( bool -- : abort if header is invalid )\n\t<> if cleanup abort\" invalid header\" then ;\n\n: save-core-cell-size ( char -- : save the core file cell size, checking if it is valid )\n\tcore-cell-size !\n\t\" cell size:\" tab\n\tcore-cell-size @ 2 = if 2 . cr exit then\n\tcore-cell-size @ 4 = if 4 . cr exit then\n\tcore-cell-size @ 8 = if 8 . cr exit then\n\tcleanup core-cell-size @ . abort\" : invalid cell size\" ;\n\n: check-version-compatibility ( char -- : checks the version compatibility of the core file )\n\tcore-version !\n\tcore-version @ version = if \" version: \" version . cr exit then\n\tcleanup core-version @ . abort\" : unknown version number\" ;\n\n: save-endianess ( char -- : save the endianess, checking if it is valid )\n\tcore-endianess !\n\t\" endianess:\" tab\n\tcore-endianess @ 0 = if \" big\" cr exit then\n\tcore-endianess @ 1 = if \" little\" cr exit then\n\tcleanup core-endianess @ . abort\" invalid endianess\" then ;\n\n: read-or-abort ( c-addr size fileid -- : )\n\tover >r read-file\n\t 0<> if cleanup abort\" file read failed\" then\n\tr> <> if cleanup abort\" header too small\" then ;\n\n: header? ( -- : print out header information )\n\tcheader header-size core-file @ read-or-abort\n\t( \" raw header:\" header 2 dump )\n\tcheader header-magic0 + c@ 255 invalid-header\n\tcheader header-magic1 + c@ [char] 4 invalid-header\n\tcheader header-magic2 + c@ [char] T invalid-header\n\tcheader header-magic3 + c@ [char] H invalid-header\n\tcheader header-cell-size + c@ save-core-cell-size\n\tcheader header-version + c@ check-version-compatibility\n\tcheader header-endianess + c@ save-endianess\n\t\" valid header\" cr ;\n\n: size? ( -- : print out core file size )\n\t\" size: \" cheader header-log2size + c@ 1 swap lshift . cr ;\n\n: core ( c-addr u -- : analyze a Forth core file from disk given its file name )\n\t2dup \" core file:\" tab type cr\n\tr\/o open-file throw core-file !\n\theader?\n\tsize?\n\tcore-file @ close-file drop ;\n\n( s\" forth.core\" core )\n\nhide{\nheader-size header?\nheader-magic0 header-magic1 header-magic2 header-magic3\nheader-version header-cell-size header-endianess header-log2size\nheader\ncore-file save-core-cell-size check-version-compatibility\ncore-cell-size cheader\ncore-endianess core-version save-endianess invalid-header\ncleanup size-field csize-field size-field-size\nread-or-abort size?\n}hide\n\n( ==================== Core utilities ======================== )\n\n( ==================== RLE =================================== )\n\n( These set of words implement Run Length Compression, which\ncan be used for saving space when compressing the core files\ngenerated by Forth programs, which contain mostly runs of\nNUL characters.\n\nThe format of the encoded data is quite simple, there is a\ncommand byte followed by data. The command byte encodes only\ntwo commands; encode a run of literal data and repeat the\nnext character.\n\nIf the command byte is greater than X the command is a run\nof characters, X is then subtracted from the command byte\nand this is the number of characters that is to be copied\nverbatim when decompressing.\n\nIf the command byte is less than or equal to X then this\nnumber, plus one, is used to repeat the next data byte in\nthe input stream.\n\nX is 128 for this application, but could be adjusted for\nbetter compression depending on what the data looks like.\n\nExample:\n\n\t2 'a' 130 'b' 'c' 3 'd'\n\nBecomes:\n\n\taabcddd\n\nExample usage:\n\n\t: extract\n\t\tc\" forth.core\" w\/o open-file throw c\"\n\t\tforth.core.rle\" r\/o open-file throw\n\t\tdecompress ;\n\textract\n\n@note file redirection could be used for the input as well\n@todo compression, and reading\/writing to strings )\n\n: cpad pad chars> ;\n\n0 variable out\n128 constant run-length\n\n: next.char ( file-id -- char : read in a single character )\n\t>r cpad r> read-char throw cpad c@ ;\n\n: repeated ( count file-id -- : repeat a character count times )\n\tnext.char swap 0 do dup emit loop drop ;\n\n: literals ( count file-id -- : extract a literal run )\n\t>r cpad swap r> read-file throw cpad swap type ;\n\n: command ( file-id -- : process an RLE command )\n\tdup\n\t>r next.char\n\tdup run-length u>\n\tif\n\t\trun-length - r> literals\n\telse\n\t\t1+ r> repeated\n\tthen ;\n\n: redirect ( file-id-out -- : save current output pointer, redirect to output )\n\t`fout @ out ! `fout ! ;\n\n: restore ( -- : restore previous output pointer )\n\tout @ `fout ! ;\n\n: decompress ( file-id-out file-id-in -- : decompress an RLE encoded file )\n\tswap\n\tredirect\n\tbegin dup ' command catch until ( process commands until input exhausted )\n\t2drop ( drop twice because catch will restore stack before COMMAND )\n\trestore ; ( restore input stream )\n\nhide{ literals repeated next.char out run-length command }hide\n\n( ==================== RLE =================================== )\n\n( ==================== Generate C Core file ================== )\n( The word core2c reads in a core file and turns it into a\nC file which can then be compiled into the forth interpreter\nin a bootstrapping like process. The process is described\nelsewhere as well, but it goes like this.\n\n1. We want to generate an executable program that contains the\ncore Forth interpreter, written in C, and the contents of this\nfile in compiled form. However, in order to compile this code\nwe need a Forth interpreter to do so. This is the problem.\n2. To solve the problem we first make a program which is capable\nof compiling \"forth.fth\".\n3. We then generate a core file from this.\n4. We then convert the generated core file to C code.\n5. We recompile the original program to includes this core\nfile, and which runs the core file at start up.\n6. We run the new executable.\n\nUsage:\n c\" forth.core\" c\" core.gen.c\" core2c )\n\n0 variable count\n\n: wbyte ( u char -- : write a byte )\n\t(.) drop\n\t[char] , emit\n\t16 mod 0= if cr then ;\n\n: advance ( char -- : advance counter and print byte )\n\tcount 1+! count @ swap wbyte ;\n\n: hexify ( fileid -- fileid : turn core file into C numbers in array )\n\t0 count !\n\tbegin dup getchar 0= while advance repeat drop ;\n\n: quote ( -- : emit a quote character )\n\t[char] \" emit ;\n\n: core2c ( c-addr u c-addr u -- ior : generate a C file from a core file )\n\tw\/o open-file throw >r\n\tr\/o open-file ?dup-if r> close-file throw throw then\n\tr> redirect\n\t\" #include \" quote \" libforth.h\" quote cr\n\t\" unsigned char forth_core_data[] = {\" cr\n\thexify\n\t\" };\" cr\n\t\" forth_cell_t forth_core_size = \" count @ . \" ;\" cr cr\n\tclose-file\n\t`fout @ close-file\n\trestore or ;\n\nhide{ wbyte hexify count quote advance }hide\n\n( ==================== Generate C Core file ================== )\n\n( ==================== Word Count Program ==================== )\n\n( @todo implement FILE-SIZE in terms of this program )\n( @todo extend wc to include line count and word count )\n: wc ( c-addr u -- u : count the bytes in a file )\n\tr\/o open-file throw\n\t0 swap\n\tbegin\n\t\tdup getchar nip 0=\n\twhile\n\t\tnos1+\n\trepeat\n\tclose-file throw ;\n\n( ==================== Word Count Program ==================== )\n\n( ==================== Save Core file ======================== )\n( The following functionality allows the user to save the\ncore file from within the running interpreter. The Forth\ncore files have a very simple format which means the words\nfor doing this do not have to be too long, a header has to\nemitted with a few calculated values and then the contents\nof the Forths memory after this )\n\n( This write the header out to the current output device, this\nwill be redirected to a file )\n: header ( -- : write the header out )\n\t0xff emit ( magic 0 )\n\t[char] 4 emit ( magic 1 )\n\t[char] T emit ( magic 2 )\n\t[char] H emit ( magic 3 )\n\tsize emit ( cell size in bytes )\n\tversion emit ( core version )\n\tendian not emit ( endianess )\n\tmax-core log2 emit ; ( size field )\n\n: data ( -- : write the data out )\n\t0 max-core chars> `fout @ write-file throw drop ;\n\n: encore ( -- : write the core file out )\n\theader\n\tdata ;\n\n: save-core ( c-addr u -- : save core file or throw error )\n\tw\/o open-file throw dup\n\tredirect\n\t\t' encore catch swap close-file throw\n\trestore ;\n\n( The following code illustrates an example of setting up a\nForth core file to execute a word when the core file is loaded.\nIn the example the word \"hello-world\" will be executed,\nwhich will also quit the interpreter:\n\nThis only works for immediate words for now, we define\nthe word we wish to be executed when the forth core\nis loaded:\n\n\t: hello-world immediate\n\t\t\" Hello, World!\" cr bye ;\n\nThe following sets the starting word to our newly\ndefined word:\n\n\tfind hello-world cfa start!\n\n\t\\ Now we can save the core file out:\n\ts\" forth.core\" save-core\n\nThis can be used, in conjunction with aspects of the build\nsystem, to produce a standalone executable that will run only\na single Forth word. This is known as creating a 'turn-key'\napplication. )\n\nhide{ redirect restore data encore header }hide\n\n( ==================== Save Core file ======================== )\n\n( ==================== Hex dump ============================== )\n\n( @todo hexdump can read in too many characters and it does not\nprint out the correct address\n@todo utilities for easy redirecting of file input\/output )\n\\ : input >r cpad 128 r> read-file ; ( file-id -- u 0 | error )\n\\ : clean cpad 128 0 fill ; ( -- )\n\\ : cdump cpad chars swap aligned chars dump ; ( u -- )\n\\ : hexdump ( file-id -- : [hex]dump a file to the screen )\n\\ \tdup\n\\ \tclean\n\\ \tinput if 2drop exit then\n\\ \t?dup-if cdump else drop exit then\n\\ \ttail ;\n\\\n\\ 0 variable u\n\\ 0 variable u1\n\\ 0 variable cdigs\n\\ 0 variable digs\n\\\n\\ : address ( -- bool : is it time to print out a new line and an address )\n\\ \tu @ u1 @ - 4 size * mod 0= ;\n\\\n\\ : (dump) ( u c-addr u : u -- )\n\\ \trot dup u ! u1 !\n\\ \tcdigits cdigs !\n\\ \tdigits digs !\n\\ \tbounds\n\\ \tdo\n\\ \t\taddress if cr u @ digs @ u.rz [char] : emit space then\n\\ \t\ti c@ cdigs @ u.rz\n\\ \t\t\n\\ \t\ti 1+ size mod 0= if space then\n\\ \t\tu 1+!\n\\ \tloop\n\\ \tu @\n\\ \t;\n\\\n\\ : hexdump-file ( c-addr u )\n\\ \tr\/o open-file throw\n\\ \t\n\\ \t;\n\\\n\\ hide{ u u1 cdigs digs address }hide\n\\ hex\n\\ 999 0 197 (dump)\n\\ decimal\n\\\n\\ hide{ cpad clean cdump input }hide\n\\\n( ==================== Hex dump ============================== )\n\n( ==================== Date ================================== )\n( This word set implements a words for date processing, so\nyou can print out nicely formatted date strings. It implements\nthe standard Forth word time&date and two words which interact\nwith the libforth DATE instruction, which pushes the current\ntime information onto the stack.\n\nRather annoyingly months are start from 1 but weekdays from\n0. )\n\n: >month ( month -- c-addr u : convert month to month string )\n\tcase\n\t\t 1 of c\" Jan \" endof\n\t\t 2 of c\" Feb \" endof\n\t\t 3 of c\" Mar \" endof\n\t\t 4 of c\" Apr \" endof\n\t\t 5 of c\" May \" endof\n\t\t 6 of c\" Jun \" endof\n\t\t 7 of c\" Jul \" endof\n\t\t 8 of c\" Aug \" endof\n\t\t 9 of c\" Sep \" endof\n\t\t10 of c\" Oct \" endof\n\t\t11 of c\" Nov \" endof\n\t\t12 of c\" Dec \" endof\n\t\t-11 throw\n\tendcase ;\n\n: .day ( day -- c-addr u : add ordinal to day )\n\t10 mod\n\tcase\n\t\t1 of c\" st \" endof\n\t\t2 of c\" nd \" endof\n\t\t3 of c\" rd \" endof\n\t\tdrop c\" th \" exit\n\tendcase ;\n\n: >day ( day -- c-addr u: add ordinal to day of month )\n\tdup 1 10 within if .day exit then\n\tdup 10 20 within if drop c\" th\" exit then\n\t.day ;\n\n: >weekday ( weekday -- c-addr u : print the weekday )\n\tcase\n\t\t0 of c\" Sun \" endof\n\t\t1 of c\" Mon \" endof\n\t\t2 of c\" Tue \" endof\n\t\t3 of c\" Wed \" endof\n\t\t4 of c\" Thu \" endof\n\t\t5 of c\" Fri \" endof\n\t\t6 of c\" Sat \" endof\n\t\t-11 throw\n\tendcase ;\n\n: >gmt ( bool -- GMT or DST? )\n\tif c\" DST \" else c\" GMT \" then ;\n\n: colon ( -- char : push a colon character )\n\t[char] : ;\n\n: 0? ( n -- : hold a space if number is less than base )\n\t(base) u< if [char] 0 hold then ;\n\n( .NB You can format the date in hex if you want! )\n: date-string ( date -- c-addr u : format a date string in transient memory )\n\t9 reverse ( reverse the date string )\n\t<#\n\t\tdup #s drop 0? ( seconds )\n\t\tcolon hold\n\t\tdup #s drop 0? ( minute )\n\t\tcolon hold\n\t\tdup #s drop 0? ( hour )\n\t\tdup >day holds\n\t\t#s drop ( day )\n\t\t>month holds\n\t\tbl hold\n\t\t#s drop ( year )\n\t\t>weekday holds\n\t\tdrop ( no need for days of year )\n\t\t>gmt holds\n\t\t0\n\t#> ;\n\n: .date ( date -- : print the date )\n\tdate-string type ;\n\n: time&date ( -- second minute hour day month year )\n\tdate\n\t3drop ;\n\nhide{ >weekday .day >day >month colon >gmt 0? }hide\n\n( ==================== Date ================================== )\n\n\n( ==================== CRC =================================== )\n\n( @todo implement all common CRC algorithms, but only if the\nword size allows it [ie. 32 bit CRCs on a 32 or 64 bit machine,\n64 bit CRCs on a 64 bit machine] )\n\n( Make a word to limit arithmetic to a 16-bit value )\nsize 2 = [if]\n\t: limit immediate ; ( do nothing, no need to limit )\n[else]\n\t: limit 0xffff and ; ( limit to 16-bit value )\n[then]\n\n: ccitt ( crc c-addr -- crc : calculate polynomial 0x1021 AKA \"x16 + x12 + x5 + 1\" )\n\tc@ ( get char )\n\tlimit over 256\/ xor ( crc x )\n\tdup 4 rshift xor ( crc x )\n\tdup 5 lshift limit xor ( crc x )\n\tdup 12 lshift limit xor ( crc x )\n\tswap 8 lshift limit xor ; ( crc )\n\n( See http:\/\/stackoverflow.com\/questions\/10564491\n and https:\/\/www.lammertbies.nl\/comm\/info\/crc-calculation.html )\n: crc16-ccitt ( c-addr u -- u )\n\t0xffff -rot\n\t['] ccitt foreach ;\nhide{ limit ccitt }hide\n\n( ==================== CRC =================================== )\n\n( ==================== Rational Data Type ==================== )\n( This word set allows the manipulation of a rational data\ntype, which are basically fractions. This allows numbers like\n1\/3 to be represented without any loss of precision. Conversion\nto and from the data type to an integer type is trivial,\nalthough information can be lost during the conversion.\n\nTo convert to a rational, use DUP, to convert from a\nrational, use '\/'.\n\nThe denominator is the first number on the stack, the numerator\nthe second number. Fractions are simplified after any rational\noperation, and all rational words can accept unsimplified\narguments. For example the fraction 1\/3 can be represented as\n6\/18, they are equivalent, so the rational equality operator\n\"=rat\" can accept both and returns true.\n\n\tT{ 1 3 6 18 =rat -> 1 }T\n\nSee: https:\/\/en.wikipedia.org\/wiki\/Rational_data_type For\nmore information.\n\nThis set of words use two cells to represent a fraction,\nhowever a single cell could be used, with the numerator and the\ndenominator stored in upper and lower half of a single cell.\n\n@todo add saturating Q numbers to the interpreter, as well as\narithmetic word for acting on double cells [d+, d-, etcetera]\nhttps:\/\/en.wikipedia.org\/wiki\/Q_%28number_format%29, this\ncan be used in lieu of floating point numbers. )\n\n: simplify ( a b -- a\/gcd{a,b} b\/gcd{a\/b} : simplify a rational )\n 2dup\n gcd\n tuck\n \/\n -rot\n \/\n swap ; \\ ? check this\n\n: crossmultiply ( a b c d -- a*d b*d c*b d*b )\n rot ( a c d b )\n 2dup ( a c d b d b )\n * ( a c d b d*b )\n >r ( a c d b , d*b )\n rot ( a d b c , d*b )\n * ( a d b*c , d*b )\n -rot ( b*c a d , d*b )\n * ( b*c a*d , d*b )\n r> ( b*c a*d d*b )\n tuck ( b*c d*b a*d d*b )\n 2swap ; ( done! )\n\n: *rat ( a\/b c\/d -- a\/b : multiply two rationals together )\n rot * -rot * swap simplify ;\n\n: \/rat ( a\/b c\/d -- a\/b : divide one rational by another )\n swap *rat ;\n\n: +rat ( a\/b c\/d -- a\/b : add two rationals together )\n crossmultiply\n rot\n drop ( or check if equal, if not there is an error )\n -rot\n +\n swap\n simplify ;\n\n: -rat ( a\/b c\/d -- a\/b : subtract one rational from another )\n crossmultiply\n rot\n drop ( or check if equal, if not there is an error )\n -rot\n -\n swap\n simplify ;\n\n: .rat ( a\/b -- : print out a rational number )\n simplify swap (.) drop [char] \/ emit . ;\n\n: =rat ( a\/b c\/d -- bool : rational equal )\n crossmultiply rot = -rot = = ;\n\n: >rat ( a\/b c\/d -- bool : rational greater than )\n crossmultiply rot 2drop > ;\n\n: <=rat ( a\/b c\/d -- bool : rational less than or equal to )\n\t>rat not ;\n\n: =rat ( a\/b c\/d -- bool : rational greater or equal to )\n\trational is a work in progress, make it better )\n: 0>number 0 -rot >number ;\n0 0 2variable saved\n: failed 0 0 saved 2@ ;\n: >rational ( c-addr u -- a\/b c-addr u )\n\t2dup saved 2!\n\t0>number 2dup 0= if 4drop failed exit then ( @note could convert to rational n\/1 )\n\tc@ [char] \/ <> if 3drop failed exit then\n\t1 \/string\n\t0>number ;\n\nhide{ 0>number saved failed }hide\n\n( ==================== Rational Data Type ==================== )\n\n( ==================== Block Layer =========================== )\n( This is the block layer, it assumes that the file access\nwords exists and use them, it would have to be rewritten\nfor an embedded device that used EEPROM or something\nsimilar. Currently it does not interact well with the current\ninput methods used by the interpreter which will need changing.\n\nThe block layer is the traditional way Forths implement a\nsystem to interact with mass storage, one which imposes little\non the underlying system only requiring that blocks 1024 bytes\ncan be loaded and saved to it [which make it suitable for\nmicrocomputers that lack a file system or an embedded device].\n\nThe block layer is used less than it once as a lot more Forths\nare hosted under a guest operating system so have access to\nmethods for reading and writing to files through it.\n\nEach block number accepted by BLOCK is backed by a file\n[or created if it does not exist]. The name of the file is\nthe block number with \".blk\" appended to it.\n\nSome Notes:\n\nBLOCK only uses one block buffer, most other Forths have\nmultiple block buffers, this could be improved on, but\nwould take up more space.\n\nAnother way of storing the blocks could be made, which is to\nstore the blocks in a single file and seek to the correct\nplace within it. This might be implemented in the future,\nor offered as an alternative. \n\nYet another way is to not have on disk blocks, but instead\nhave in memory blocks, this simplifies things significantly,\nand would mean saving the blocks to disk would use the same\nmechanism as saving the core file to disk. Computers certainly\nhave enough memory to do this. The block word set could\nbe factored so it could use either the on disk method or\nthe memory option. \n\nTo simplify the current code, and make the code portable\nto devices with EEPROM an instruction in the virtual machine\ncould be made which does the task of transfering a block to\ndisk. )\n\n0 variable dirty\nb\/buf string buf ( block buffer, only one exists )\n0 , ( make sure buffer is NUL terminated, just in case )\n0 variable blk ( 0 = invalid block number, >0 block number stored in buf)\n\n: invalid? ( n -- : throw if block number is invalid )\n\t0= if -35 throw then ;\n\n: update ( -- : mark currently loaded block buffer as dirty )\n\ttrue dirty ! ;\n\n: updated? ( n -- bool : is a block updated? )\n \tblk @ <> if 0 else dirty @ then ;\n\n: block.name ( n -- c-addr u : make a block name )\n\tc\" .blk\" <# holds #s #> rot drop ;\n\n( @warning this will not work if we do not have permission,\nor in various other cases where we cannot open the file,\nfor whatever reason )\n: file-exists ( c-addr u : does a file exist? )\n\tr\/o open-file if drop 0 else close-file throw 1 then ;\n\n: block.exists ( n -- bool : does a block buffer exist on disk? )\n\tblock.name file-exists ;\n\n( @note block.write and block.read do not check if they have\nwrote or read in 1024 bytes, nor do they check that they can\nonly write or read 1024 and not a byte more )\n\n: block.read ( file-id -- file-id : read in buffer )\n\tdup >r buf r> read-file nip if close-file -33 throw then ;\n\n: block.write ( file-id -- file-id : write out buffer )\n\tdup >r buf r> write-file nip if close-file -34 throw then ;\n\n: block.open ( n fam -- file-id )\n\t>r block.name r> open-file throw ;\n\n: save-buffers\n\tblk @ 0= if exit then ( not a valid block number, exit )\n\tdirty @ not if exit then ( not dirty, no need to save )\n\tblk @ w\/o block.open ( open file backing block buffer )\n\tblock.write ( write it out )\n\tclose-file throw ( close it )\n\tfalse dirty ! ; ( but only mark it clean if everything succeeded )\n\n: empty-buffers ( -- : deallocate any saved buffers )\n\t0 blk ! ;\n\n: flush ( -- : perform save-buffers followed by empty-buffers )\n\tsave-buffers\n\tempty-buffers ;\n\n( Block is a complex word that does a lot, although it has\na simple interface. It does the following given a block number:\n\n1. Checks the provided block buffer number to make sure it\nis valid.\n2. If the block is already loaded from the disk, then return\nthe address of the block buffer it is loaded into.\n3. If not, it checks to see if the currently loaded block\nbuffer is dirty, if it is then it flushes the buffer to disk.\n4. If the block buffer does not exists on disk then it\ncreates it.\n5. It then stores the block number in blk and returns an\naddress to the block buffer. )\n: block ( n -- c-addr : load a block )\n\tdup invalid?\n\tdup blk @ = if drop buf drop exit then\n\tflush\n\tdup block.exists if ( if the buffer exits on disk load it in )\n\t\tdup r\/o block.open\n\t\tblock.read\n\t\tclose-file throw\n\telse ( else it does not exist )\n\t\tbuf 0 fill ( clean the buffer )\n\tthen\n\tblk ! ( save the block number )\n\tbuf drop ;\n\n: buffer block ;\n\n( @warning uses hack, block buffer is NUL terminated, and evaluate requires\na NUL terminated string, evaluate checks that the last character is NUL,\nhence the 1+ )\n: load ( n -- : load and execute a block )\n\tblock b\/buf 1+ evaluate throw ;\n\n: +block ( n -- u : calculate new block number relative to current block )\n\tblk @ + ;\n\n: --> ( -- : load next block )\n\t1 +block load ;\n\n: blocks.make ( n1 n2 -- : make blocks on disk from n1 to n2 inclusive )\n\t1+ swap do i block b\/buf bl fill update loop save-buffers ;\n\n: block.copy ( n1 n2 -- bool : copy block n2 to n1 if n2 exists )\n\tswap dup block.exists 0= if 2drop false exit then ( n2 n1 )\n\tblock drop ( load in block n1 )\n\tw\/o block.open block.write close-file throw\n\ttrue ;\n\n: block.delete ( n -- : delete block )\n\tdup block.exists 0= if drop exit then\n\tblock.name delete-file drop ;\n\n\\ @todo implement a word that splits a file into blocks\n\\ : split ( c-addr u : split a file into blocks )\n\\\t;\n\nhide{\n\tblock.name invalid? block.write\n\tblock.read block.exists block.open dirty\n}hide\n\n( ==================== Block Layer =========================== )\n\n( ==================== List ================================== )\n( The list word set allows the viewing of Forth blocks,\nthis version of list can create two Formats, a simple mode\nwhere it just spits out the block with a carriage return\nafter each line and a more fancy version which also prints\nout line numbers and draws a box around the data. LIST is\nnot aware of any formatting and characters that might be\npresent in the data, or none printable characters.\n\nA very primitive version of list can be defined as follows:\n\n\t: list block b\/buf type ;\n\n)\n\n1 variable fancy-list\n0 variable scr\n64 constant c\/l ( characters per line )\n\n: pipe ( -- : emit a pipe character )\n\t[char] | emit ;\n\n: line.number ( n -- : print line number )\n\tfancy-list @ not if drop exit then\n\t2 u.r space pipe ;\n\n: list.end ( -- : print the right hand side of the box )\n\tfancy-list @ not if exit then\n\tpipe ;\n\n: line ( c-addr -- c-addr u : given a line number, display that line number and calculate offset )\n\tdup\n\tline.number ( display line number )\n\tc\/l * + ( calculate offset )\n\tc\/l ; ( add line length )\n\n: list.type ( c-addr u -- : list a block )\n\tb\/buf c\/l \/ 0 do dup i line type list.end cr loop drop ;\n\n: list.border ( -- : print a section of the border )\n\t\" +---|---\" ;\n\n: list.box ( )\n\tfancy-list @ not if exit then\n\t4 spaces\n\t8 0 do list.border loop cr ;\n\n: list ( n -- : display a block number and update scr )\n\tdup >r block r> scr ! list.box list.type list.box ;\n\n: thru\n\tkey drop\n\t1+ swap do i list more loop ;\n\nhide{\n\tbuf line line.number list.type\n\t(base) list.box list.border list.end pipe\n}hide\n\n( ==================== List ================================== )\n\n( ==================== Signal Handling ======================= )\n( Signal handling at the moment is quite primitive. When\na signal occurs it has to be explicitly tested for by the\nprogrammer, this could be improved on quite a bit. One way\nof doing this would be to check for signals in the virtual\nmachine and cause a THROW from within it. )\n\n( signals are biased to fall outside the range of the error\nnumbers defined in the ANS Forth standard. )\n-512 constant signal-bias\n\n: signal ( -- signal\/0 : push the results of the signal register )\n\t`signal @\n \t0 `signal ! ;\n\n( ==================== Signal Handling ======================= )\n\n( Looking at most Forths dictionary with \"words\" command they\ntend to have a lot of words that do not mean anything but to\nthe implementers of that specific Forth, here we clean up as\nmany non standard words as possible. )\nhide{\n do-string ')' alignment-bits\n dictionary-start hidden-mask instruction-mask immediate-mask compiling?\n compile-bit\n max-core dolist doconst x x! x@\n max-string-length\n evaluator\n TrueFalse >instruction\n xt-instruction\n `source-id `sin `sidx `slen `start-address `fin `fout `stdin\n `stdout `stderr `argc `argv `debug `invalid `top `instruction\n `stack-size `error-handler `x `handler _emit `signal\n}hide\n\n(\n## Forth To List\n\nThe following is a To-Do list for the Forth code itself,\nalong with any other ideas.\n\n* FORTH, VOCABULARY\n\n* \"Value\", \"To\", \"Is\"\n\n* Double cell words\n\n* The interpreter should use character based addresses,\ninstead of word based, and use values that are actual valid\npointers, this will allow easier interaction with the world\noutside the virtual machine\n\n* common words and actions should be factored out to simplify\ndefinitions of other words, their standards compliant version\nfound if any.\n\n* A soft floating point library would be useful which could be\nused to optionally implement floats [which is not something I\nreally want to add to the virtual machine]. If floats were to\nbe added, only the minimal set of functions should be added\n[f+,f-,f\/,f*,f<,f>,>float,...]\n\n* Allow the processing of argc and argv, the mechanism by which\nthat this can be achieved needs to be worked out. However all\nprocessing that is currently done in \"main.c\" should be done\nwithin the Forth interpreter instead. Words for manipulating\nrationals and double width cells should be made first.\n\n* A built in version of \"dump\" and \"words\" should be added\nto the Forth starting vocabulary, simplified versions that\ncan be hidden.\n\n* Here documents, string literals. Examples of these can be\nfound online\n\n* Document the words in this file and built in words better,\nalso turn this document into a literate Forth file.\n\n* Sort out \"'\", \"[']\", \"find\", \"compile,\"\n\n* Proper booleans should be used throughout, that is -1 is\ntrue, and 0 is false.\n\n* Attempt to add crypto primitives, not for serious use,\nlike TEA, XTEA, XXTEA, RC4, MD5, ...\n\n* Add hash functions: CRC-32, CRC-16, ...\nhttp:\/\/stackoverflow.com\/questions\/10564491\/\n\n* Implement as many things from\nhttp:\/\/lars.nocrew.org\/forth2012\/implement.html as is sensible.\n\n* The current words that implement I\/O redirection need to\nbe improved, and documented, I think this is quite a useful\nand powerful mechanism to use within Forth that simplifies\nprograms. This is a must and will make writing utilities in\nForth a *lot* easier\n\n* Words for manipulating words should be added, for navigating\nto different fields within them, to the end of the word,\netcetera.\n\n* The data structure used for parsing Forth words needs\nchanging in libforth so a counted string is produced. Counted\nstrings should be used more often. The current layout of a\nForth word prevents a counted string being used and uses a\nbyte more than it has to.\n\n* Whether certain simple words [such as '1+', '1-', '>',\n'<', '<>', NOT, <=', '>='] should be added as virtual\nmachine instructions for speed [and size] reasons should\nbe investigated.\n\n* An analysis of the interpreter and the code it executes\ncould be done to find the most commonly executed words\nand instructions, as well as the most common two and three\nsequences of words and instructions. This could be used to use\nto optimize the interpreter, in terms of both speed and size.\n\n* As a thought, a word for inlining other words could be\nmade by copying everything into the current definition until\nit reaches a _exit, it would need to be aware of literals\nwritten into a word, like SEE is.\n\n* The source code for this file should go through a code\nreview, which should focus on formatting, stack comments and\nreorganizing the code. Currently it is not clear that variables\nlike COLORIZE and FANCY-LIST exist and can be changed by\nthe user. Lines should be 64 characters in length - maximum,\nincluding the new line at the end of the file.\n\n### libforth.c todo\n\n* A halt, a parse, and a print\/type instruction could be\nadded to the Forth virtual machine.\n\n* u.r, or a more generic version should be added to the\ninterpreter instead of the current simpler primitive. As\nshould >number - for fast numeric input and output.\n\n* Throw\/Catch need to be added and used in the virtual machine\n\n* Various edge cases and exceptions should be removed [for\nexample counted strings are not used internally, and '0x'\ncan be used as a prefix only when base is zero].\n\n* A potential optimization is to order the words in the\ndictionary by frequency order, this would mean chaning the\nX Macro that contains the list of words, after collecting\nstatistics. This should make find faster.\n\n* Investigate adding operating system specific code into the\ninterpreter and isolating it to make it semi-portable.\n\n* Make equivalents for various Unix utilities in Forth,\nlike a CRC check, cat, tr, etcetera.\n\n* It would be interesting to make a primitive file system based\nupon Forth blocks, this could then be ported to systems that\ndo not have file systems, such as microcontrollers [which\nusually have EEPROM].\n\n* In a _very_ unportable way it would be possible to have an\ninstruction that takes the top of the stack, treats it as a\nfunction pointer and then attempts to call said function. This\nwould allow us to assemble machine dependant code within the\ncore file, generate a new function, then call it. It is just\na thought.\n )\n\nverbose [if]\n\t.( FORTH: libforth successfully loaded.) cr\n\tdate .date cr\n\t.( Type 'help' and press return for a basic introduction.) cr\n\t.( Core: ) here . \" \/ \" here unused + . cr\n\t license\n[then]\n\n( ==================== Test Code ============================= )\n\n( The following will not work as we might actually be reading\nfrom a string [`sin] not `fin.\n\n: key 32 chars> 1 `fin @\n\tread-file drop 0 = if 0 else 32 chars> c@ then ; )\n\n\\ : ' immediate state @ if postpone ['] else find then ;\n\n( This really does not implement a correct FORTH\/VOCABULARY,\nfor that wordlists will need to be introduced and used in\nlibforth.c. The best that this word set can do is to hide\nand reveal words to the user, this was just an experiment.\n\n\t: forth\n\t\t[ find forth 1- @ ] literal\n\t\t[ find forth 1- ] literal ! ;\n\n\t: vocabulary\n\t\tcreate does> drop 0 [ find forth 1- ] literal ! ; )\n\n\\ @todo The built in primitives should be redefined so to make sure\n\\ they are called and nested correctly, using the following words\n\\ 0 variable csp\n\\ : !csp sp@ csp ! ;\n\\ : ?csp sp@ csp @ <> if -22 throw then ;\n\n\\ @todo Make this work\n\\ : >body ??? ;\n\\ : noop ( -- ) ;\n\\ : defer create ( \"name\" -- ) ['] noop , does> ( -- ) @ execute ;\n\\ : is ( xt \"name\" -- ) find >body ! ;\n\\ defer lessthan\n\\ find < is lessthan\n\n( ==================== Test Code ============================= )\n\n( ==================== Block Editor ========================== )\n( Experimental block editor Mark II\n\nThis is a simple block editor, it really shows off the power\nand simplicity of Forth systems - both the concept of a block\neditor and the implementation.\n\nForth source code used to organized into things called 'blocks',\nnowadays most people use normal resizeable stream based files.\nA block simply consists of 1024 bytes of data that can be\ntransfered to and from mass storage. This works on systems that\ndo not have a file system. A block can be used for storing\narbitrary data as well, so the user had to know what was stored\nin what block.\n\n1024 bytes is quite a limiting Form factor for storing source\ncode, which is probably one reason Forth earned a reputation\nfor being terse. A few conventions arose around dealing with\nForth source code stored in blocks - both in how the code should\nbe formatted within them, and in how programs that required\nmore than one block of storage should be dealt with.\n\nOne of the conventions is how many columns and rows each block\nconsists of, the traditional way is to organize the code into\n16 lines of text, with a column width of 64 characters. The only\nspace character used is the space [or ASCII character 32], tabs\nand new lines are not used, as they are not needed - the editor\nknows how long a line is so it can wrap the text.\n\nVarious standards and common practice evolved as to what goes\ninto a block - for example the first line is usually a comment\ndescribing what the block does, with the date is was last edited\nand who edited it.\n\nThe way the editor works is by defining a simple set of words\nthat act on the currently loaded block, LIST is used to display\nthe loaded block. An editor loop which executes forth words\nand automatically displays the currently block can be entered\nby calling EDITOR. This loop is essential an extension of\nthe INTERPRET word, it does no special processing such as\nlooking for keys - all commands are Forth words. The editor\nloop could have been implemented in the following fashion\n[or something similar]:\n\n\t: editor-command\n\t\tkey\n\t\tcase\n\t\t\t[char] h of print-editor-help endof\n\t\t\t[char] i of insert-text endof\n\t\t\t[char] d of delete-line endof\n\t\t\t... more editor commands\n\t\t\t[char] q of quit-editor-loop endof\n\t\t\tpush-number-by-default\n\t\tendof ;\n\nHowever this is rather limiting, it only works for single\ncharacter commands and numeric input is handled as a special\ncase. It is far simpler to just call the READ word with the\neditor commands in search order, and it can be extended not\nby adding more parsing code in CASE statements but just by\ndefining new words in the ordinary manner.\n\nThe editor loop does not have to be used while editing code,\nbut it does make things easier. The commands defined can be\nused on there own.\n\t\nThe code was adapted from: \t\n\nhttp:\/\/retroforth.org\/pages\/?PortsOfRetroEditor\n\nWhich contains ports of an editor written for Retro Forth.\n\n@todo Improve the block editor\n\n- '\\' needs extending to work with the block editor, for now,\nuse parenthesis for comments\n- add multi line insertion mode\n- Add to an editor vocabulary, which will need the vocabulary\nsystem to exist.\n- Using PAGE should be optional as not all terminals support\nANSI escape codes - thanks to CMD.EXE. Damned Windows.\n\nAdapted from http:\/\/retroforth.org\/pages\/?PortsOfRetroEditor )\n\n\n: help ( @todo rename to H once vocabularies are implemented )\npage cr\n\" Block Editor Help Menu\n\n n move to next block\n p move to previous block\n # d delete line in current block\n x erase current block\n e evaluate current block\n # i insert line\n # #2 ia insert at line #2 at column #\n q quit editor loop\n # b set block number\n s save block and write it out\n\n -- press any key to continue -- \" cr ( \" )\nchar drop ;\n\n: (block) blk @ block ;\n: (check) dup b\/buf c\/l \/ u>= if -24 throw then ;\n: (line) (check) c\/l * (block) + ; ( n -- c-addr : push current line address )\n: (clean)\n\t(block) b\/buf\n\t2dup nl bl subst\n\t2dup cret bl subst\n\t 0 bl subst ;\n: n 1 +block block ;\n: p -1 +block block ;\n: d (line) c\/l bl fill ;\n: x (block) b\/buf bl fill ;\n: s update save-buffers ;\n: q rdrop rdrop ;\n: e blk @ load char drop ;\n: ia c\/l * + dup b\/buf swap - >r (block) + r> accept drop (clean) ;\n: i 0 swap ia ;\n: editor\n\t1 block ( load first block by default )\n\trendezvous ( set up a rendezvous so we can forget words up to this point )\n\tbegin\n\t\tpage cr\n\t\t\" BLOCK EDITOR: TYPE 'HELP' FOR A LIST OF COMMANDS\" cr\n\t\tblk @ list\n\t\t\" [BLOCK: \" blk @ u. \" ] [DICTIONARY: \" here u. \" ]\" cr\n\t\tpostpone [ ( need to be in command mode )\n\t\tread\n\tagain ;\n\n( Extra niceties )\nc\/l string yank\nyank bl fill\n: u update ;\n: b block ;\n: l blk @ list ;\n: y (line) yank >r swap r> cmove ;\n: c (line) yank cmove ;\n: ct swap y c ;\n: m retreat ;\n\nhide{ (block) (line) (clean) yank }hide\n\n( ==================== Block Editor ========================== )\n\n( ==================== Error checking ======================== )\n( This is a series of redefinitions that make the use of control\nstructures a bit safer. )\n\n: if immediate ?comp postpone if [ hide if ] ;\n: else immediate ?comp postpone else [ hide else ] ;\n: then immediate ?comp postpone then [ hide then ] ;\n: begin immediate ?comp postpone begin [ hide begin ] ;\n: until immediate ?comp postpone until [ hide until ] ;\n\\ : ; immediate ?comp postpone ; [ hide ; ] ; ( @todo do nesting checking for control statements )\n\n( ==================== Error checking ======================== )\n\n( ==================== DUMP ================================== )\n\\ : newline ( x -- x+1 : print a new line every fourth value )\n\\ \tdup 3 and 0= if cr then 1+ ;\n\\\n\\ : address ( num count -- count : print current address we are dumping every fourth value )\n\\ \tdup >r\n\\ \t1- 3 and 0= if . [char] : emit space else drop then\n\\ \tr> ;\n\\\n\\ : dump ( start count -- : print the contents of a section of memory )\n\\ \\\thex ( switch to hex mode )\n\\ \t1 >r ( save counter on return stack )\n\\ \tover + swap ( calculate limits: start start+count )\n\\ \tbegin\n\\ \t\t2dup u> ( stop if gone past limits )\n\\ \twhile\n\\ \t\tdup r> address >r\n\\ \t\tdup @ . 1+\n\\ \t\tr> newline >r\n\\ \trepeat\n\\ \tr> drop\n\\ \t2drop ;\n\\\n\\ hide newline\n\\ hide address\n( ==================== DUMP ================================== )\n\n( ==================== End of File Functions ================= )\n\n( set up a rendezvous point, we can call the word RETREAT to\nrestore the dictionary to this point. This word also updates\nfence to this location in the dictionary )\nrendezvous\n\n: task ; ( Task is a word that can safely be forgotten )\n\n( ==================== End of File Functions ================= )\n\n\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"f52e5ae84b417cfe1e980bae37deb342ff1d32a5","subject":"Remove AGAIN definition, as FICL 2.04 provides it.","message":"Remove AGAIN definition, as FICL 2.04 provides it.\n\nAdd strlen, to help handling data generated by C code.\n\nAdd 2>r 2r>, because OO programming without them sucks.\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/support.4th","new_file":"sys\/boot\/forth\/support.4th","new_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\ \n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\n\\ Loader.rc support functions:\n\\\n\\ initialize_support ( -- )\tinitialize global variables\n\\ initialize ( addr len -- )\tas above, plus load_conf_files\n\\ load_conf ( addr len -- )\tload conf file given\n\\ include_conf_files ( -- )\tload all conf files in load_conf_files\n\\ print_syntax_error ( -- )\tprint line and marker of where a syntax\n\\\t\t\t\terror was detected\n\\ print_line ( -- )\t\tprint last line processed\n\\ load_kernel ( -- )\t\tload kernel\n\\ load_modules ( -- )\t\tload modules flagged\n\\\n\\ Exported structures:\n\\\n\\ string\t\t\tcounted string structure\n\\\tcell .addr\t\t\tstring address\n\\\tcell .len\t\t\tstring length\n\\ module\t\t\tmodule loading information structure\n\\\tcell module.flag\t\tshould we load it?\n\\\tstring module.name\t\tmodule's name\n\\\tstring module.loadname\t\tname to be used in loading the module\n\\\tstring module.type\t\tmodule's type\n\\\tstring module.args\t\tflags to be passed during load\n\\\tstring module.beforeload\tcommand to be executed before load\n\\\tstring module.afterload\t\tcommand to be executed after load\n\\\tstring module.loaderror\t\tcommand to be executed if load fails\n\\\tcell module.next\t\tlist chain\n\\\n\\ Exported global variables;\n\\\n\\ string conf_files\t\tconfiguration files to be loaded\n\\ string password\t\tpassword\n\\ cell modules_options\t\tpointer to first module information\n\\ value verbose?\t\tindicates if user wants a verbose loading\n\\ value any_conf_read?\t\tindicates if a conf file was succesfully read\n\\\n\\ Other exported words:\n\\\n\\ strdup ( addr len -- addr' len)\t\t\tsimilar to strdup(3)\n\\ strcat ( addr len addr' len' -- addr len+len' )\tsimilar to strcat(3)\n\\ strlen ( addr -- len )\t\t\t\tsimilar to strlen(3)\n\\ s' ( | string' -- addr len | )\t\t\tsimilar to s\"\n\\ rudimentary structure support\n\n\\ Exception values\n\n1 constant syntax_error\n2 constant out_of_memory\n3 constant free_error\n4 constant set_error\n5 constant read_error\n6 constant open_error\n7 constant exec_error\n8 constant before_load_error\n9 constant after_load_error\n\n\\ Crude structure support\n\n: structure: create here 0 , 0 does> create @ allot ;\n: member: create dup , over , + does> cell+ @ + ;\n: ;structure swap ! ;\n: sizeof ' >body @ state @ if postpone literal then ; immediate\n: offsetof ' >body cell+ @ state @ if postpone literal then ; immediate\n: ptr 1 cells member: ;\n: int 1 cells member: ;\n\n\\ String structure\n\nstructure: string\n\tptr .addr\n\tint .len\n;structure\n\n\\ Module options linked list\n\nstructure: module\n\tint module.flag\n\tsizeof string member: module.name\n\tsizeof string member: module.loadname\n\tsizeof string member: module.type\n\tsizeof string member: module.args\n\tsizeof string member: module.beforeload\n\tsizeof string member: module.afterload\n\tsizeof string member: module.loaderror\n\tptr module.next\n;structure\n\n\\ Global variables\n\nstring conf_files\nstring password\ncreate module_options sizeof module.next allot\ncreate last_module_option sizeof module.next allot\n0 value verbose?\n\n\\ Support string functions\n\n: strdup ( addr len -- addr' len )\n >r r@ allocate if out_of_memory throw then\n tuck r@ move\n r>\n;\n\n: strcat { addr len addr' len' -- addr len+len' }\n addr' addr len + len' move\n addr len len' +\n;\n\n: strlen ( addr -- len )\n 0 >r\n begin\n dup c@ while\n 1+ r> 1+ >r repeat\n drop r>\n;\n\n: s' \n [char] ' parse\n state @ if\n postpone sliteral\n then\n; immediate\n\n: 2>r postpone >r postpone >r ; immediate\n: 2r> postpone r> postpone r> ; immediate\n\n\\ Private definitions\n\nvocabulary support-functions\nonly forth also support-functions definitions\n\n\\ Some control characters constants\n\n7 constant bell\n8 constant backspace\n9 constant tab\n10 constant lf\n13 constant \n\n\\ Read buffer size\n\n80 constant read_buffer_size\n\n\\ Standard suffixes\n\n: load_module_suffix s\" _load\" ;\n: module_loadname_suffix s\" _name\" ;\n: module_type_suffix s\" _type\" ;\n: module_args_suffix s\" _flags\" ;\n: module_beforeload_suffix s\" _before\" ;\n: module_afterload_suffix s\" _after\" ;\n: module_loaderror_suffix s\" _error\" ;\n\n\\ Support operators\n\n: >= < 0= ;\n: <= > 0= ;\n\n\\ Assorted support funcitons\n\n: free-memory free if free_error throw then ;\n\n\\ Assignment data temporary storage\n\nstring name_buffer\nstring value_buffer\n\n\\ File data temporary storage\n\nstring line_buffer\nstring read_buffer\n0 value read_buffer_ptr\n\n\\ File's line reading function\n\n0 value end_of_file?\nvariable fd\n\n: skip_newlines\n begin\n read_buffer .len @ read_buffer_ptr >\n while\n read_buffer .addr @ read_buffer_ptr + c@ lf = if\n read_buffer_ptr char+ to read_buffer_ptr\n else\n exit\n then\n repeat\n;\n\n: scan_buffer ( -- addr len )\n read_buffer_ptr >r\n begin\n read_buffer .len @ r@ >\n while\n read_buffer .addr @ r@ + c@ lf = if\n read_buffer .addr @ read_buffer_ptr + ( -- addr )\n r@ read_buffer_ptr - ( -- len )\n r> to read_buffer_ptr\n exit\n then\n r> char+ >r\n repeat\n read_buffer .addr @ read_buffer_ptr + ( -- addr )\n r@ read_buffer_ptr - ( -- len )\n r> to read_buffer_ptr\n;\n\n: line_buffer_resize ( len -- len )\n >r\n line_buffer .len @ if\n line_buffer .addr @\n line_buffer .len @ r@ +\n resize if out_of_memory throw then\n else\n r@ allocate if out_of_memory throw then\n then\n line_buffer .addr !\n r>\n;\n \n: append_to_line_buffer ( addr len -- )\n line_buffer .addr @ line_buffer .len @\n 2swap strcat\n line_buffer .len !\n drop\n;\n\n: read_from_buffer\n scan_buffer ( -- addr len )\n line_buffer_resize ( len -- len )\n append_to_line_buffer ( addr len -- )\n;\n\n: refill_required?\n read_buffer .len @ read_buffer_ptr =\n end_of_file? 0= and\n;\n\n: refill_buffer\n 0 to read_buffer_ptr\n read_buffer .addr @ 0= if\n read_buffer_size allocate if out_of_memory throw then\n read_buffer .addr !\n then\n fd @ read_buffer .addr @ read_buffer_size fread\n dup -1 = if read_error throw then\n dup 0= if true to end_of_file? then\n read_buffer .len !\n;\n\n: reset_line_buffer\n 0 line_buffer .addr !\n 0 line_buffer .len !\n;\n\n: read_line\n reset_line_buffer\n skip_newlines\n begin\n read_from_buffer\n refill_required?\n while\n refill_buffer\n repeat\n;\n\n\\ Conf file line parser:\n\\ ::= '='[] |\n\\ []\n\\ ::= {||'_'}\n\\ ::= '\"'{|'\\'}'\"' | \n\\ ::= ASCII 32 to 126, except '\\' and '\"'\n\\ ::= '#'{}\n\n0 value parsing_function\n\n0 value end_of_line\n0 value line_pointer\n\n: end_of_line?\n line_pointer end_of_line =\n;\n\n: letter?\n line_pointer c@ >r\n r@ [char] A >=\n r@ [char] Z <= and\n r@ [char] a >=\n r> [char] z <= and\n or\n;\n\n: digit?\n line_pointer c@ >r\n r@ [char] 0 >=\n r> [char] 9 <= and\n;\n\n: quote?\n line_pointer c@ [char] \" =\n;\n\n: assignment_sign?\n line_pointer c@ [char] = =\n;\n\n: comment?\n line_pointer c@ [char] # =\n;\n\n: space?\n line_pointer c@ bl =\n line_pointer c@ tab = or\n;\n\n: backslash?\n line_pointer c@ [char] \\ =\n;\n\n: underscore?\n line_pointer c@ [char] _ =\n;\n\n: dot?\n line_pointer c@ [char] . =\n;\n\n: skip_character\n line_pointer char+ to line_pointer\n;\n\n: skip_to_end_of_line\n end_of_line to line_pointer\n;\n\n: eat_space\n begin\n space?\n while\n skip_character\n end_of_line? if exit then\n repeat\n;\n\n: parse_name ( -- addr len )\n line_pointer\n begin\n letter? digit? underscore? dot? or or or\n while\n skip_character\n end_of_line? if \n line_pointer over -\n strdup\n exit\n then\n repeat\n line_pointer over -\n strdup\n;\n\n: remove_backslashes { addr len | addr' len' -- addr' len' }\n len allocate if out_of_memory throw then\n to addr'\n addr >r\n begin\n addr c@ [char] \\ <> if\n addr c@ addr' len' + c!\n len' char+ to len'\n then\n addr char+ to addr\n r@ len + addr =\n until\n r> drop\n addr' len'\n;\n\n: parse_quote ( -- addr len )\n line_pointer\n skip_character\n end_of_line? if syntax_error throw then\n begin\n quote? 0=\n while\n backslash? if\n skip_character\n end_of_line? if syntax_error throw then\n then\n skip_character\n end_of_line? if syntax_error throw then \n repeat\n skip_character\n line_pointer over -\n remove_backslashes\n;\n\n: read_name\n parse_name\t\t( -- addr len )\n name_buffer .len !\n name_buffer .addr !\n;\n\n: read_value\n quote? if\n parse_quote\t\t( -- addr len )\n else\n parse_name\t\t( -- addr len )\n then\n value_buffer .len !\n value_buffer .addr !\n;\n\n: comment\n skip_to_end_of_line\n;\n\n: white_space_4\n eat_space\n comment? if ['] comment to parsing_function exit then\n end_of_line? 0= if syntax_error throw then\n;\n\n: variable_value\n read_value\n ['] white_space_4 to parsing_function\n;\n\n: white_space_3\n eat_space\n letter? digit? quote? or or if\n ['] variable_value to parsing_function exit\n then\n syntax_error throw\n;\n\n: assignment_sign\n skip_character\n ['] white_space_3 to parsing_function\n;\n\n: white_space_2\n eat_space\n assignment_sign? if ['] assignment_sign to parsing_function exit then\n syntax_error throw\n;\n\n: variable_name\n read_name\n ['] white_space_2 to parsing_function\n;\n\n: white_space_1\n eat_space\n letter? if ['] variable_name to parsing_function exit then\n comment? if ['] comment to parsing_function exit then\n end_of_line? 0= if syntax_error throw then\n;\n\n: get_assignment\n line_buffer .addr @ line_buffer .len @ + to end_of_line\n line_buffer .addr @ to line_pointer\n ['] white_space_1 to parsing_function\n begin\n end_of_line? 0=\n while\n parsing_function execute\n repeat\n parsing_function ['] comment =\n parsing_function ['] white_space_1 =\n parsing_function ['] white_space_4 =\n or or 0= if syntax_error throw then\n;\n\n\\ Process line\n\n: assignment_type? ( addr len -- flag )\n name_buffer .addr @ name_buffer .len @\n compare 0=\n;\n\n: suffix_type? ( addr len -- flag )\n name_buffer .len @ over <= if 2drop false exit then\n name_buffer .len @ over - name_buffer .addr @ +\n over compare 0=\n;\n\n: loader_conf_files?\n s\" loader_conf_files\" assignment_type?\n;\n\n: verbose_flag?\n s\" verbose_loading\" assignment_type?\n;\n\n: execute?\n s\" exec\" assignment_type?\n;\n\n: password?\n s\" password\" assignment_type?\n;\n\n: module_load?\n load_module_suffix suffix_type?\n;\n\n: module_loadname?\n module_loadname_suffix suffix_type?\n;\n\n: module_type?\n module_type_suffix suffix_type?\n;\n\n: module_args?\n module_args_suffix suffix_type?\n;\n\n: module_beforeload?\n module_beforeload_suffix suffix_type?\n;\n\n: module_afterload?\n module_afterload_suffix suffix_type?\n;\n\n: module_loaderror?\n module_loaderror_suffix suffix_type?\n;\n\n: set_conf_files\n conf_files .addr @ ?dup if\n free-memory\n then\n value_buffer .addr @ c@ [char] \" = if\n value_buffer .addr @ char+ value_buffer .len @ 2 chars -\n else\n value_buffer .addr @ value_buffer .len @\n then\n strdup\n conf_files .len ! conf_files .addr !\n;\n\n: append_to_module_options_list ( addr -- )\n module_options @ 0= if\n dup module_options !\n last_module_option !\n else\n dup last_module_option @ module.next !\n last_module_option !\n then\n;\n\n: set_module_name ( addr -- )\n name_buffer .addr @ name_buffer .len @\n strdup\n >r over module.name .addr !\n r> swap module.name .len !\n;\n\n: yes_value?\n value_buffer .addr @ value_buffer .len @\n 2dup s' \"YES\"' compare >r\n 2dup s' \"yes\"' compare >r\n 2dup s\" YES\" compare >r\n s\" yes\" compare r> r> r> and and and 0=\n;\n\n: find_module_option ( -- addr | 0 )\n module_options @\n begin\n dup\n while\n dup module.name dup .addr @ swap .len @\n name_buffer .addr @ name_buffer .len @\n compare 0= if exit then\n module.next @\n repeat\n;\n\n: new_module_option ( -- addr )\n sizeof module allocate if out_of_memory throw then\n dup sizeof module erase\n dup append_to_module_options_list\n dup set_module_name\n;\n\n: get_module_option ( -- addr )\n find_module_option\n ?dup 0= if new_module_option then\n;\n\n: set_module_flag\n name_buffer .len @ load_module_suffix nip - name_buffer .len !\n yes_value? get_module_option module.flag !\n;\n\n: set_module_args\n name_buffer .len @ module_args_suffix nip - name_buffer .len !\n get_module_option module.args\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_loadname\n name_buffer .len @ module_loadname_suffix nip - name_buffer .len !\n get_module_option module.loadname\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_type\n name_buffer .len @ module_type_suffix nip - name_buffer .len !\n get_module_option module.type\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_beforeload\n name_buffer .len @ module_beforeload_suffix nip - name_buffer .len !\n get_module_option module.beforeload\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_afterload\n name_buffer .len @ module_afterload_suffix nip - name_buffer .len !\n get_module_option module.afterload\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_loaderror\n name_buffer .len @ module_loaderror_suffix nip - name_buffer .len !\n get_module_option module.loaderror\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_environment_variable\n name_buffer .len @\n value_buffer .len @ +\n 5 chars +\n allocate if out_of_memory throw then\n dup 0 ( addr -- addr addr len )\n s\" set \" strcat\n name_buffer .addr @ name_buffer .len @ strcat\n s\" =\" strcat\n value_buffer .addr @ value_buffer .len @ strcat\n ['] evaluate catch if\n 2drop free drop\n set_error throw\n else\n free-memory\n then\n;\n\n: set_verbose\n yes_value? to verbose?\n;\n\n: execute_command\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 - swap char+ swap\n then\n ['] evaluate catch if exec_error throw then\n;\n\n: set_password\n password .addr @ ?dup if free if free_error throw then then\n value_buffer .addr @ c@ [char] \" = if\n value_buffer .addr @ char+ value_buffer .len @ 2 - strdup\n value_buffer .addr @ free if free_error throw then\n else\n value_buffer .addr @ value_buffer .len @\n then\n password .len ! password .addr !\n 0 value_buffer .addr !\n;\n\n: process_assignment\n name_buffer .len @ 0= if exit then\n loader_conf_files?\tif set_conf_files exit then\n verbose_flag?\t\tif set_verbose exit then\n execute?\t\tif execute_command exit then\n password?\t\tif set_password exit then\n module_load?\t\tif set_module_flag exit then\n module_loadname?\tif set_module_loadname exit then\n module_type?\t\tif set_module_type exit then\n module_args?\t\tif set_module_args exit then\n module_beforeload?\tif set_module_beforeload exit then\n module_afterload?\tif set_module_afterload exit then\n module_loaderror?\tif set_module_loaderror exit then\n set_environment_variable\n;\n\n\\ free_buffer ( -- )\n\\\n\\ Free some pointers if needed. The code then tests for errors\n\\ in freeing, and throws an exception if needed. If a pointer is\n\\ not allocated, it's value (0) is used as flag.\n\n: free_buffers\n line_buffer .addr @ dup if free then\n name_buffer .addr @ dup if free then\n value_buffer .addr @ dup if free then\n or or if free_error throw then\n;\n\n: reset_assignment_buffers\n 0 name_buffer .addr !\n 0 name_buffer .len !\n 0 value_buffer .addr !\n 0 value_buffer .len !\n;\n\n\\ Higher level file processing\n\n: process_conf\n begin\n end_of_file? 0=\n while\n reset_assignment_buffers\n read_line\n get_assignment\n ['] process_assignment catch\n ['] free_buffers catch\n swap throw throw\n repeat\n;\n\n: create_null_terminated_string { addr len -- addr' len }\n len char+ allocate if out_of_memory throw then\n >r\n addr r@ len move\n 0 r@ len + c!\n r> len\n;\n\n\\ Interface to loading conf files\n\n: load_conf ( addr len -- )\n 0 to end_of_file?\n 0 to read_buffer_ptr\n create_null_terminated_string\n over >r\n fopen fd !\n r> free-memory\n fd @ -1 = if open_error throw then\n ['] process_conf catch\n fd @ fclose\n throw\n;\n\n: initialize_support\n 0 read_buffer .addr !\n 0 conf_files .addr !\n 0 password .addr !\n 0 module_options !\n 0 last_module_option !\n 0 to verbose?\n;\n\n: print_line\n line_buffer .addr @ line_buffer .len @ type cr\n;\n\n: print_syntax_error\n line_buffer .addr @ line_buffer .len @ type cr\n line_buffer .addr @\n begin\n line_pointer over <>\n while\n bl emit\n char+\n repeat\n drop\n .\" ^\" cr\n;\n\n\\ Depuration support functions\n\nonly forth definitions also support-functions\n\n: test-file \n ['] load_conf catch dup .\n syntax_error = if cr print_syntax_error then\n;\n\n: show-module-options\n module_options @\n begin\n ?dup\n while\n .\" Name: \" dup module.name dup .addr @ swap .len @ type cr\n .\" Path: \" dup module.loadname dup .addr @ swap .len @ type cr\n .\" Type: \" dup module.type dup .addr @ swap .len @ type cr\n .\" Flags: \" dup module.args dup .addr @ swap .len @ type cr\n .\" Before load: \" dup module.beforeload dup .addr @ swap .len @ type cr\n .\" After load: \" dup module.afterload dup .addr @ swap .len @ type cr\n .\" Error: \" dup module.loaderror dup .addr @ swap .len @ type cr\n .\" Status: \" dup module.flag @ if .\" Load\" else .\" Don't load\" then cr\n module.next @\n repeat\n;\n\nonly forth also support-functions definitions\n\n\\ Variables used for processing multiple conf files\n\nstring current_file_name\nvariable current_conf_files\n\n\\ Indicates if any conf file was succesfully read\n\n0 value any_conf_read?\n\n\\ loader_conf_files processing support functions\n\n: set_current_conf_files\n conf_files .addr @ current_conf_files !\n;\n\n: get_conf_files\n conf_files .addr @ conf_files .len @ strdup\n;\n\n: recurse_on_conf_files?\n current_conf_files @ conf_files .addr @ <>\n;\n\n: skip_leading_spaces { addr len pos -- addr len pos' }\n begin\n pos len = if addr len pos exit then\n addr pos + c@ bl =\n while\n pos char+ to pos\n repeat\n addr len pos\n;\n\n: get_file_name { addr len pos -- addr len pos' addr' len' || 0 }\n pos len = if \n addr free abort\" Fatal error freeing memory\"\n 0 exit\n then\n pos >r\n begin\n addr pos + c@ bl <>\n while\n pos char+ to pos\n pos len = if\n addr len pos addr r@ + pos r> - exit\n then\n repeat\n addr len pos addr r@ + pos r> -\n;\n\n: get_next_file ( addr len ptr -- addr len ptr' addr' len' | 0 )\n skip_leading_spaces\n get_file_name\n;\n\n: set_current_file_name\n over current_file_name .addr !\n dup current_file_name .len !\n;\n\n: print_current_file\n current_file_name .addr @ current_file_name .len @ type\n;\n\n: process_conf_errors\n dup 0= if true to any_conf_read? drop exit then\n >r 2drop r>\n dup syntax_error = if\n .\" Warning: syntax error on file \" print_current_file cr\n print_syntax_error drop exit\n then\n dup set_error = if\n .\" Warning: bad definition on file \" print_current_file cr\n print_line drop exit\n then\n dup read_error = if\n .\" Warning: error reading file \" print_current_file cr drop exit\n then\n dup open_error = if\n verbose? if .\" Warning: unable to open file \" print_current_file cr then\n drop exit\n then\n dup free_error = abort\" Fatal error freeing memory\"\n dup out_of_memory = abort\" Out of memory\"\n throw \\ Unknown error -- pass ahead\n;\n\n\\ Process loader_conf_files recursively\n\\ Interface to loader_conf_files processing\n\n: include_conf_files\n set_current_conf_files\n get_conf_files 0\n begin\n get_next_file ?dup\n while\n set_current_file_name\n ['] load_conf catch\n process_conf_errors\n recurse_on_conf_files? if recurse then\n repeat\n;\n\n\\ Module loading functions\n\n: load_module?\n module.flag @\n;\n\n: load_parameters ( addr -- addr addrN lenN ... addr1 len1 N )\n dup >r\n r@ module.args .addr @ r@ module.args .len @\n r@ module.loadname .len @ if\n r@ module.loadname .addr @ r@ module.loadname .len @\n else\n r@ module.name .addr @ r@ module.name .len @\n then\n r@ module.type .len @ if\n r@ module.type .addr @ r@ module.type .len @\n s\" -t \"\n 4 ( -t type name flags )\n else\n 2 ( name flags )\n then\n r> drop\n;\n\n: before_load ( addr -- addr )\n dup module.beforeload .len @ if\n dup module.beforeload .addr @ over module.beforeload .len @\n ['] evaluate catch if before_load_error throw then\n then\n;\n\n: after_load ( addr -- addr )\n dup module.afterload .len @ if\n dup module.afterload .addr @ over module.afterload .len @\n ['] evaluate catch if after_load_error throw then\n then\n;\n\n: load_error ( addr -- addr )\n dup module.loaderror .len @ if\n dup module.loaderror .addr @ over module.loaderror .len @\n evaluate \\ This we do not intercept so it can throw errors\n then\n;\n\n: pre_load_message ( addr -- addr )\n verbose? if\n dup module.name .addr @ over module.name .len @ type\n .\" ...\"\n then\n;\n\n: load_error_message verbose? if .\" failed!\" cr then ;\n\n: load_succesful_message verbose? if .\" ok\" cr then ;\n\n: load_module\n load_parameters load\n;\n\n: process_module ( addr -- addr )\n pre_load_message\n before_load\n begin\n ['] load_module catch if\n dup module.loaderror .len @ if\n load_error\t\t\t\\ Command should return a flag!\n else \n load_error_message true\t\t\\ Do not retry\n then\n else\n after_load\n load_succesful_message true\t\\ Succesful, do not retry\n then\n until\n;\n\n: process_module_errors ( addr ior -- )\n dup before_load_error = if\n drop\n .\" Module \"\n dup module.name .addr @ over module.name .len @ type\n dup module.loadname .len @ if\n .\" (\" dup module.loadname .addr @ over module.loadname .len @ type .\" )\"\n then\n cr\n .\" Error executing \"\n dup module.beforeload .addr @ over module.afterload .len @ type cr\n abort\n then\n\n dup after_load_error = if\n drop\n .\" Module \"\n dup module.name .addr @ over module.name .len @ type\n dup module.loadname .len @ if\n .\" (\" dup module.loadname .addr @ over module.loadname .len @ type .\" )\"\n then\n cr\n .\" Error executing \"\n dup module.afterload .addr @ over module.afterload .len @ type cr\n abort\n then\n\n throw \\ Don't know what it is all about -- pass ahead\n;\n\n\\ Module loading interface\n\n: load_modules ( -- ) ( throws: abort & user-defined )\n module_options @\n begin\n ?dup\n while\n dup load_module? if\n ['] process_module catch\n process_module_errors\n then\n module.next @\n repeat\n;\n\n\\ Additional functions used in \"start\"\n\n: initialize ( addr len -- )\n initialize_support\n strdup conf_files .len ! conf_files .addr !\n;\n\n: load_kernel ( -- ) ( throws: abort )\n s\" load ${kernel} ${kernel_options}\" ['] evaluate catch\n if s\" echo Unable to load kernel: ${kernel_name}\" evaluate abort then\n;\n\n: read-password { size | buf len -- }\n size allocate if out_of_memory throw then\n to buf\n 0 to len\n begin\n key\n dup backspace = if\n drop\n len if\n backspace emit bl emit backspace emit\n len 1 - to len\n else\n bell emit\n then\n else\n dup = if cr drop buf len exit then\n [char] * emit\n len size < if\n buf len chars + c!\n else\n drop\n then\n len 1+ to len\n then\n again\n;\n\n\\ Go back to straight forth vocabulary\n\nonly forth also definitions\n\n","old_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\ \n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\n\\ Loader.rc support functions:\n\\\n\\ initialize_support ( -- )\tinitialize global variables\n\\ initialize ( addr len -- )\tas above, plus load_conf_files\n\\ load_conf ( addr len -- )\tload conf file given\n\\ include_conf_files ( -- )\tload all conf files in load_conf_files\n\\ print_syntax_error ( -- )\tprint line and marker of where a syntax\n\\\t\t\t\terror was detected\n\\ print_line ( -- )\t\tprint last line processed\n\\ load_kernel ( -- )\t\tload kernel\n\\ load_modules ( -- )\t\tload modules flagged\n\\\n\\ Exported structures:\n\\\n\\ string\t\t\tcounted string structure\n\\\tcell .addr\t\t\tstring address\n\\\tcell .len\t\t\tstring length\n\\ module\t\t\tmodule loading information structure\n\\\tcell module.flag\t\tshould we load it?\n\\\tstring module.name\t\tmodule's name\n\\\tstring module.loadname\t\tname to be used in loading the module\n\\\tstring module.type\t\tmodule's type\n\\\tstring module.args\t\tflags to be passed during load\n\\\tstring module.beforeload\tcommand to be executed before load\n\\\tstring module.afterload\t\tcommand to be executed after load\n\\\tstring module.loaderror\t\tcommand to be executed if load fails\n\\\tcell module.next\t\tlist chain\n\\\n\\ Exported global variables;\n\\\n\\ string conf_files\t\tconfiguration files to be loaded\n\\ string password\t\tpassword\n\\ cell modules_options\t\tpointer to first module information\n\\ value verbose?\t\tindicates if user wants a verbose loading\n\\ value any_conf_read?\t\tindicates if a conf file was succesfully read\n\\\n\\ Other exported words:\n\\\n\\ strdup ( addr len -- addr' len)\t\t\tsimilar to strdup(3)\n\\ strcat ( addr len addr' len' -- addr len+len' )\tsimilar to strcat(3)\n\\ s' ( | string' -- addr len | )\t\t\tsimilar to s\"\n\\ rudimentary structure support\n\n\\ Exception values\n\n1 constant syntax_error\n2 constant out_of_memory\n3 constant free_error\n4 constant set_error\n5 constant read_error\n6 constant open_error\n7 constant exec_error\n8 constant before_load_error\n9 constant after_load_error\n\n\\ Crude structure support\n\n: structure: create here 0 , 0 does> create @ allot ;\n: member: create dup , over , + does> cell+ @ + ;\n: ;structure swap ! ;\n: sizeof ' >body @ state @ if postpone literal then ; immediate\n: offsetof ' >body cell+ @ state @ if postpone literal then ; immediate\n: ptr 1 cells member: ;\n: int 1 cells member: ;\n\n\\ String structure\n\nstructure: string\n\tptr .addr\n\tint .len\n;structure\n\n\\ Module options linked list\n\nstructure: module\n\tint module.flag\n\tsizeof string member: module.name\n\tsizeof string member: module.loadname\n\tsizeof string member: module.type\n\tsizeof string member: module.args\n\tsizeof string member: module.beforeload\n\tsizeof string member: module.afterload\n\tsizeof string member: module.loaderror\n\tptr module.next\n;structure\n\n\\ Global variables\n\nstring conf_files\nstring password\ncreate module_options sizeof module.next allot\ncreate last_module_option sizeof module.next allot\n0 value verbose?\n\n\\ Support string functions\n\n: strdup ( addr len -- addr' len )\n >r r@ allocate if out_of_memory throw then\n tuck r@ move\n r>\n;\n\n: strcat { addr len addr' len' -- addr len+len' }\n addr' addr len + len' move\n addr len len' +\n;\n\n: s' \n [char] ' parse\n state @ if\n postpone sliteral\n then\n; immediate\n\n\\ How come ficl doesn't have again?\n\n: again false postpone literal postpone until ; immediate\n\n\\ Private definitions\n\nvocabulary support-functions\nonly forth also support-functions definitions\n\n\\ Some control characters constants\n\n7 constant bell\n8 constant backspace\n9 constant tab\n10 constant lf\n13 constant \n\n\\ Read buffer size\n\n80 constant read_buffer_size\n\n\\ Standard suffixes\n\n: load_module_suffix s\" _load\" ;\n: module_loadname_suffix s\" _name\" ;\n: module_type_suffix s\" _type\" ;\n: module_args_suffix s\" _flags\" ;\n: module_beforeload_suffix s\" _before\" ;\n: module_afterload_suffix s\" _after\" ;\n: module_loaderror_suffix s\" _error\" ;\n\n\\ Support operators\n\n: >= < 0= ;\n: <= > 0= ;\n\n\\ Assorted support funcitons\n\n: free-memory free if free_error throw then ;\n\n\\ Assignment data temporary storage\n\nstring name_buffer\nstring value_buffer\n\n\\ File data temporary storage\n\nstring line_buffer\nstring read_buffer\n0 value read_buffer_ptr\n\n\\ File's line reading function\n\n0 value end_of_file?\nvariable fd\n\n: skip_newlines\n begin\n read_buffer .len @ read_buffer_ptr >\n while\n read_buffer .addr @ read_buffer_ptr + c@ lf = if\n read_buffer_ptr char+ to read_buffer_ptr\n else\n exit\n then\n repeat\n;\n\n: scan_buffer ( -- addr len )\n read_buffer_ptr >r\n begin\n read_buffer .len @ r@ >\n while\n read_buffer .addr @ r@ + c@ lf = if\n read_buffer .addr @ read_buffer_ptr + ( -- addr )\n r@ read_buffer_ptr - ( -- len )\n r> to read_buffer_ptr\n exit\n then\n r> char+ >r\n repeat\n read_buffer .addr @ read_buffer_ptr + ( -- addr )\n r@ read_buffer_ptr - ( -- len )\n r> to read_buffer_ptr\n;\n\n: line_buffer_resize ( len -- len )\n >r\n line_buffer .len @ if\n line_buffer .addr @\n line_buffer .len @ r@ +\n resize if out_of_memory throw then\n else\n r@ allocate if out_of_memory throw then\n then\n line_buffer .addr !\n r>\n;\n \n: append_to_line_buffer ( addr len -- )\n line_buffer .addr @ line_buffer .len @\n 2swap strcat\n line_buffer .len !\n drop\n;\n\n: read_from_buffer\n scan_buffer ( -- addr len )\n line_buffer_resize ( len -- len )\n append_to_line_buffer ( addr len -- )\n;\n\n: refill_required?\n read_buffer .len @ read_buffer_ptr =\n end_of_file? 0= and\n;\n\n: refill_buffer\n 0 to read_buffer_ptr\n read_buffer .addr @ 0= if\n read_buffer_size allocate if out_of_memory throw then\n read_buffer .addr !\n then\n fd @ read_buffer .addr @ read_buffer_size fread\n dup -1 = if read_error throw then\n dup 0= if true to end_of_file? then\n read_buffer .len !\n;\n\n: reset_line_buffer\n 0 line_buffer .addr !\n 0 line_buffer .len !\n;\n\n: read_line\n reset_line_buffer\n skip_newlines\n begin\n read_from_buffer\n refill_required?\n while\n refill_buffer\n repeat\n;\n\n\\ Conf file line parser:\n\\ ::= '='[] |\n\\ []\n\\ ::= {||'_'}\n\\ ::= '\"'{|'\\'}'\"' | \n\\ ::= ASCII 32 to 126, except '\\' and '\"'\n\\ ::= '#'{}\n\n0 value parsing_function\n\n0 value end_of_line\n0 value line_pointer\n\n: end_of_line?\n line_pointer end_of_line =\n;\n\n: letter?\n line_pointer c@ >r\n r@ [char] A >=\n r@ [char] Z <= and\n r@ [char] a >=\n r> [char] z <= and\n or\n;\n\n: digit?\n line_pointer c@ >r\n r@ [char] 0 >=\n r> [char] 9 <= and\n;\n\n: quote?\n line_pointer c@ [char] \" =\n;\n\n: assignment_sign?\n line_pointer c@ [char] = =\n;\n\n: comment?\n line_pointer c@ [char] # =\n;\n\n: space?\n line_pointer c@ bl =\n line_pointer c@ tab = or\n;\n\n: backslash?\n line_pointer c@ [char] \\ =\n;\n\n: underscore?\n line_pointer c@ [char] _ =\n;\n\n: dot?\n line_pointer c@ [char] . =\n;\n\n: skip_character\n line_pointer char+ to line_pointer\n;\n\n: skip_to_end_of_line\n end_of_line to line_pointer\n;\n\n: eat_space\n begin\n space?\n while\n skip_character\n end_of_line? if exit then\n repeat\n;\n\n: parse_name ( -- addr len )\n line_pointer\n begin\n letter? digit? underscore? dot? or or or\n while\n skip_character\n end_of_line? if \n line_pointer over -\n strdup\n exit\n then\n repeat\n line_pointer over -\n strdup\n;\n\n: remove_backslashes { addr len | addr' len' -- addr' len' }\n len allocate if out_of_memory throw then\n to addr'\n addr >r\n begin\n addr c@ [char] \\ <> if\n addr c@ addr' len' + c!\n len' char+ to len'\n then\n addr char+ to addr\n r@ len + addr =\n until\n r> drop\n addr' len'\n;\n\n: parse_quote ( -- addr len )\n line_pointer\n skip_character\n end_of_line? if syntax_error throw then\n begin\n quote? 0=\n while\n backslash? if\n skip_character\n end_of_line? if syntax_error throw then\n then\n skip_character\n end_of_line? if syntax_error throw then \n repeat\n skip_character\n line_pointer over -\n remove_backslashes\n;\n\n: read_name\n parse_name\t\t( -- addr len )\n name_buffer .len !\n name_buffer .addr !\n;\n\n: read_value\n quote? if\n parse_quote\t\t( -- addr len )\n else\n parse_name\t\t( -- addr len )\n then\n value_buffer .len !\n value_buffer .addr !\n;\n\n: comment\n skip_to_end_of_line\n;\n\n: white_space_4\n eat_space\n comment? if ['] comment to parsing_function exit then\n end_of_line? 0= if syntax_error throw then\n;\n\n: variable_value\n read_value\n ['] white_space_4 to parsing_function\n;\n\n: white_space_3\n eat_space\n letter? digit? quote? or or if\n ['] variable_value to parsing_function exit\n then\n syntax_error throw\n;\n\n: assignment_sign\n skip_character\n ['] white_space_3 to parsing_function\n;\n\n: white_space_2\n eat_space\n assignment_sign? if ['] assignment_sign to parsing_function exit then\n syntax_error throw\n;\n\n: variable_name\n read_name\n ['] white_space_2 to parsing_function\n;\n\n: white_space_1\n eat_space\n letter? if ['] variable_name to parsing_function exit then\n comment? if ['] comment to parsing_function exit then\n end_of_line? 0= if syntax_error throw then\n;\n\n: get_assignment\n line_buffer .addr @ line_buffer .len @ + to end_of_line\n line_buffer .addr @ to line_pointer\n ['] white_space_1 to parsing_function\n begin\n end_of_line? 0=\n while\n parsing_function execute\n repeat\n parsing_function ['] comment =\n parsing_function ['] white_space_1 =\n parsing_function ['] white_space_4 =\n or or 0= if syntax_error throw then\n;\n\n\\ Process line\n\n: assignment_type? ( addr len -- flag )\n name_buffer .addr @ name_buffer .len @\n compare 0=\n;\n\n: suffix_type? ( addr len -- flag )\n name_buffer .len @ over <= if 2drop false exit then\n name_buffer .len @ over - name_buffer .addr @ +\n over compare 0=\n;\n\n: loader_conf_files?\n s\" loader_conf_files\" assignment_type?\n;\n\n: verbose_flag?\n s\" verbose_loading\" assignment_type?\n;\n\n: execute?\n s\" exec\" assignment_type?\n;\n\n: password?\n s\" password\" assignment_type?\n;\n\n: module_load?\n load_module_suffix suffix_type?\n;\n\n: module_loadname?\n module_loadname_suffix suffix_type?\n;\n\n: module_type?\n module_type_suffix suffix_type?\n;\n\n: module_args?\n module_args_suffix suffix_type?\n;\n\n: module_beforeload?\n module_beforeload_suffix suffix_type?\n;\n\n: module_afterload?\n module_afterload_suffix suffix_type?\n;\n\n: module_loaderror?\n module_loaderror_suffix suffix_type?\n;\n\n: set_conf_files\n conf_files .addr @ ?dup if\n free-memory\n then\n value_buffer .addr @ c@ [char] \" = if\n value_buffer .addr @ char+ value_buffer .len @ 2 chars -\n else\n value_buffer .addr @ value_buffer .len @\n then\n strdup\n conf_files .len ! conf_files .addr !\n;\n\n: append_to_module_options_list ( addr -- )\n module_options @ 0= if\n dup module_options !\n last_module_option !\n else\n dup last_module_option @ module.next !\n last_module_option !\n then\n;\n\n: set_module_name ( addr -- )\n name_buffer .addr @ name_buffer .len @\n strdup\n >r over module.name .addr !\n r> swap module.name .len !\n;\n\n: yes_value?\n value_buffer .addr @ value_buffer .len @\n 2dup s' \"YES\"' compare >r\n 2dup s' \"yes\"' compare >r\n 2dup s\" YES\" compare >r\n s\" yes\" compare r> r> r> and and and 0=\n;\n\n: find_module_option ( -- addr | 0 )\n module_options @\n begin\n dup\n while\n dup module.name dup .addr @ swap .len @\n name_buffer .addr @ name_buffer .len @\n compare 0= if exit then\n module.next @\n repeat\n;\n\n: new_module_option ( -- addr )\n sizeof module allocate if out_of_memory throw then\n dup sizeof module erase\n dup append_to_module_options_list\n dup set_module_name\n;\n\n: get_module_option ( -- addr )\n find_module_option\n ?dup 0= if new_module_option then\n;\n\n: set_module_flag\n name_buffer .len @ load_module_suffix nip - name_buffer .len !\n yes_value? get_module_option module.flag !\n;\n\n: set_module_args\n name_buffer .len @ module_args_suffix nip - name_buffer .len !\n get_module_option module.args\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_loadname\n name_buffer .len @ module_loadname_suffix nip - name_buffer .len !\n get_module_option module.loadname\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_type\n name_buffer .len @ module_type_suffix nip - name_buffer .len !\n get_module_option module.type\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_beforeload\n name_buffer .len @ module_beforeload_suffix nip - name_buffer .len !\n get_module_option module.beforeload\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_afterload\n name_buffer .len @ module_afterload_suffix nip - name_buffer .len !\n get_module_option module.afterload\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_loaderror\n name_buffer .len @ module_loaderror_suffix nip - name_buffer .len !\n get_module_option module.loaderror\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_environment_variable\n name_buffer .len @\n value_buffer .len @ +\n 5 chars +\n allocate if out_of_memory throw then\n dup 0 ( addr -- addr addr len )\n s\" set \" strcat\n name_buffer .addr @ name_buffer .len @ strcat\n s\" =\" strcat\n value_buffer .addr @ value_buffer .len @ strcat\n ['] evaluate catch if\n 2drop free drop\n set_error throw\n else\n free-memory\n then\n;\n\n: set_verbose\n yes_value? to verbose?\n;\n\n: execute_command\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 - swap char+ swap\n then\n ['] evaluate catch if exec_error throw then\n;\n\n: set_password\n password .addr @ ?dup if free if free_error throw then then\n value_buffer .addr @ c@ [char] \" = if\n value_buffer .addr @ char+ value_buffer .len @ 2 - strdup\n value_buffer .addr @ free if free_error throw then\n else\n value_buffer .addr @ value_buffer .len @\n then\n password .len ! password .addr !\n 0 value_buffer .addr !\n;\n\n: process_assignment\n name_buffer .len @ 0= if exit then\n loader_conf_files?\tif set_conf_files exit then\n verbose_flag?\t\tif set_verbose exit then\n execute?\t\tif execute_command exit then\n password?\t\tif set_password exit then\n module_load?\t\tif set_module_flag exit then\n module_loadname?\tif set_module_loadname exit then\n module_type?\t\tif set_module_type exit then\n module_args?\t\tif set_module_args exit then\n module_beforeload?\tif set_module_beforeload exit then\n module_afterload?\tif set_module_afterload exit then\n module_loaderror?\tif set_module_loaderror exit then\n set_environment_variable\n;\n\n\\ free_buffer ( -- )\n\\\n\\ Free some pointers if needed. The code then tests for errors\n\\ in freeing, and throws an exception if needed. If a pointer is\n\\ not allocated, it's value (0) is used as flag.\n\n: free_buffers\n line_buffer .addr @ dup if free then\n name_buffer .addr @ dup if free then\n value_buffer .addr @ dup if free then\n or or if free_error throw then\n;\n\n: reset_assignment_buffers\n 0 name_buffer .addr !\n 0 name_buffer .len !\n 0 value_buffer .addr !\n 0 value_buffer .len !\n;\n\n\\ Higher level file processing\n\n: process_conf\n begin\n end_of_file? 0=\n while\n reset_assignment_buffers\n read_line\n get_assignment\n ['] process_assignment catch\n ['] free_buffers catch\n swap throw throw\n repeat\n;\n\n: create_null_terminated_string { addr len -- addr' len }\n len char+ allocate if out_of_memory throw then\n >r\n addr r@ len move\n 0 r@ len + c!\n r> len\n;\n\n\\ Interface to loading conf files\n\n: load_conf ( addr len -- )\n 0 to end_of_file?\n 0 to read_buffer_ptr\n create_null_terminated_string\n over >r\n fopen fd !\n r> free-memory\n fd @ -1 = if open_error throw then\n ['] process_conf catch\n fd @ fclose\n throw\n;\n\n: initialize_support\n 0 read_buffer .addr !\n 0 conf_files .addr !\n 0 password .addr !\n 0 module_options !\n 0 last_module_option !\n 0 to verbose?\n;\n\n: print_line\n line_buffer .addr @ line_buffer .len @ type cr\n;\n\n: print_syntax_error\n line_buffer .addr @ line_buffer .len @ type cr\n line_buffer .addr @\n begin\n line_pointer over <>\n while\n bl emit\n char+\n repeat\n drop\n .\" ^\" cr\n;\n\n\\ Depuration support functions\n\nonly forth definitions also support-functions\n\n: test-file \n ['] load_conf catch dup .\n syntax_error = if cr print_syntax_error then\n;\n\n: show-module-options\n module_options @\n begin\n ?dup\n while\n .\" Name: \" dup module.name dup .addr @ swap .len @ type cr\n .\" Path: \" dup module.loadname dup .addr @ swap .len @ type cr\n .\" Type: \" dup module.type dup .addr @ swap .len @ type cr\n .\" Flags: \" dup module.args dup .addr @ swap .len @ type cr\n .\" Before load: \" dup module.beforeload dup .addr @ swap .len @ type cr\n .\" After load: \" dup module.afterload dup .addr @ swap .len @ type cr\n .\" Error: \" dup module.loaderror dup .addr @ swap .len @ type cr\n .\" Status: \" dup module.flag @ if .\" Load\" else .\" Don't load\" then cr\n module.next @\n repeat\n;\n\nonly forth also support-functions definitions\n\n\\ Variables used for processing multiple conf files\n\nstring current_file_name\nvariable current_conf_files\n\n\\ Indicates if any conf file was succesfully read\n\n0 value any_conf_read?\n\n\\ loader_conf_files processing support functions\n\n: set_current_conf_files\n conf_files .addr @ current_conf_files !\n;\n\n: get_conf_files\n conf_files .addr @ conf_files .len @ strdup\n;\n\n: recurse_on_conf_files?\n current_conf_files @ conf_files .addr @ <>\n;\n\n: skip_leading_spaces { addr len pos -- addr len pos' }\n begin\n pos len = if addr len pos exit then\n addr pos + c@ bl =\n while\n pos char+ to pos\n repeat\n addr len pos\n;\n\n: get_file_name { addr len pos -- addr len pos' addr' len' || 0 }\n pos len = if \n addr free abort\" Fatal error freeing memory\"\n 0 exit\n then\n pos >r\n begin\n addr pos + c@ bl <>\n while\n pos char+ to pos\n pos len = if\n addr len pos addr r@ + pos r> - exit\n then\n repeat\n addr len pos addr r@ + pos r> -\n;\n\n: get_next_file ( addr len ptr -- addr len ptr' addr' len' | 0 )\n skip_leading_spaces\n get_file_name\n;\n\n: set_current_file_name\n over current_file_name .addr !\n dup current_file_name .len !\n;\n\n: print_current_file\n current_file_name .addr @ current_file_name .len @ type\n;\n\n: process_conf_errors\n dup 0= if true to any_conf_read? drop exit then\n >r 2drop r>\n dup syntax_error = if\n .\" Warning: syntax error on file \" print_current_file cr\n print_syntax_error drop exit\n then\n dup set_error = if\n .\" Warning: bad definition on file \" print_current_file cr\n print_line drop exit\n then\n dup read_error = if\n .\" Warning: error reading file \" print_current_file cr drop exit\n then\n dup open_error = if\n verbose? if .\" Warning: unable to open file \" print_current_file cr then\n drop exit\n then\n dup free_error = abort\" Fatal error freeing memory\"\n dup out_of_memory = abort\" Out of memory\"\n throw \\ Unknown error -- pass ahead\n;\n\n\\ Process loader_conf_files recursively\n\\ Interface to loader_conf_files processing\n\n: include_conf_files\n set_current_conf_files\n get_conf_files 0\n begin\n get_next_file ?dup\n while\n set_current_file_name\n ['] load_conf catch\n process_conf_errors\n recurse_on_conf_files? if recurse then\n repeat\n;\n\n\\ Module loading functions\n\n: load_module?\n module.flag @\n;\n\n: load_parameters ( addr -- addr addrN lenN ... addr1 len1 N )\n dup >r\n r@ module.args .addr @ r@ module.args .len @\n r@ module.loadname .len @ if\n r@ module.loadname .addr @ r@ module.loadname .len @\n else\n r@ module.name .addr @ r@ module.name .len @\n then\n r@ module.type .len @ if\n r@ module.type .addr @ r@ module.type .len @\n s\" -t \"\n 4 ( -t type name flags )\n else\n 2 ( name flags )\n then\n r> drop\n;\n\n: before_load ( addr -- addr )\n dup module.beforeload .len @ if\n dup module.beforeload .addr @ over module.beforeload .len @\n ['] evaluate catch if before_load_error throw then\n then\n;\n\n: after_load ( addr -- addr )\n dup module.afterload .len @ if\n dup module.afterload .addr @ over module.afterload .len @\n ['] evaluate catch if after_load_error throw then\n then\n;\n\n: load_error ( addr -- addr )\n dup module.loaderror .len @ if\n dup module.loaderror .addr @ over module.loaderror .len @\n evaluate \\ This we do not intercept so it can throw errors\n then\n;\n\n: pre_load_message ( addr -- addr )\n verbose? if\n dup module.name .addr @ over module.name .len @ type\n .\" ...\"\n then\n;\n\n: load_error_message verbose? if .\" failed!\" cr then ;\n\n: load_succesful_message verbose? if .\" ok\" cr then ;\n\n: load_module\n load_parameters load\n;\n\n: process_module ( addr -- addr )\n pre_load_message\n before_load\n begin\n ['] load_module catch if\n dup module.loaderror .len @ if\n load_error\t\t\t\\ Command should return a flag!\n else \n load_error_message true\t\t\\ Do not retry\n then\n else\n after_load\n load_succesful_message true\t\\ Succesful, do not retry\n then\n until\n;\n\n: process_module_errors ( addr ior -- )\n dup before_load_error = if\n drop\n .\" Module \"\n dup module.name .addr @ over module.name .len @ type\n dup module.loadname .len @ if\n .\" (\" dup module.loadname .addr @ over module.loadname .len @ type .\" )\"\n then\n cr\n .\" Error executing \"\n dup module.beforeload .addr @ over module.afterload .len @ type cr\n abort\n then\n\n dup after_load_error = if\n drop\n .\" Module \"\n dup module.name .addr @ over module.name .len @ type\n dup module.loadname .len @ if\n .\" (\" dup module.loadname .addr @ over module.loadname .len @ type .\" )\"\n then\n cr\n .\" Error executing \"\n dup module.afterload .addr @ over module.afterload .len @ type cr\n abort\n then\n\n throw \\ Don't know what it is all about -- pass ahead\n;\n\n\\ Module loading interface\n\n: load_modules ( -- ) ( throws: abort & user-defined )\n module_options @\n begin\n ?dup\n while\n dup load_module? if\n ['] process_module catch\n process_module_errors\n then\n module.next @\n repeat\n;\n\n\\ Additional functions used in \"start\"\n\n: initialize ( addr len -- )\n initialize_support\n strdup conf_files .len ! conf_files .addr !\n;\n\n: load_kernel ( -- ) ( throws: abort )\n s\" load ${kernel} ${kernel_options}\" ['] evaluate catch\n if s\" echo Unable to load kernel: ${kernel_name}\" evaluate abort then\n;\n\n: read-password { size | buf len -- }\n size allocate if out_of_memory throw then\n to buf\n 0 to len\n begin\n key\n dup backspace = if\n drop\n len if\n backspace emit bl emit backspace emit\n len 1 - to len\n else\n bell emit\n then\n else\n dup = if cr drop buf len exit then\n [char] * emit\n len size < if\n buf len chars + c!\n else\n drop\n then\n len 1+ to len\n then\n again\n;\n\n\\ Go back to straight forth vocabulary\n\nonly forth also definitions\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"347df45fce50f71aa73637cb8c765b6c65a37302","subject":"Get rid of interp_max","message":"Get rid of interp_max","repos":"rbsexton\/gecko,rbsexton\/gecko,rbsexton\/gecko","old_file":"zero\/clock-umb\/forth\/Clock.fth","new_file":"zero\/clock-umb\/forth\/Clock.fth","new_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( -- )\n load-defaults \n icroot 0 over inter.rtcsem ! \\ Reset the free-running counters.\n 0 over inter.rtcdsem ! \\ Reset the free-running counters.\n\n begin \n \tdup inter.rtcsem @offex! ?dup if advancehms then\n \tdup inter.rtcdsem @offex! ?dup if advancedhms then\n [asm wfi asm]\n uiupdate if use-uivals else use-clockvals then \n key? until drop\n;\n \n\\ These two contain loops to ensure that we don't\n\\ drop any timer ticks on the floor.\n: ADVANCEHMS ( n -- ) 0 do hms advancetime loop ;\n: ADVANCEDHMS ( n -- ) 0 do dhms advancetime loop ;\n \n: LOAD-DEFAULTS ( -- )\n interp-init\n;\n\n\\ ----------------------------------------------------------\n\\ Define the structures before they get used.\n\\ ----------------------------------------------------------\nstruct ODN \\ On-Deck Needle \n\t2 field odn.s\n\t2 field odn.m\n\t2 field odn.h\nend-struct\n\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxsec \\ Max Value for secs+minutes\n\tint hms.maxhour \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_m \\ increment the minutes + hours\nend-struct\n\nstruct _interp_set\n\t4 cells field interp.a\n\t4 cells field interp.b\n\t4 cells field interp.c\nend-struct\n\n\\ ----------------------------------------------------------\n\\ Defaults get saved in the user data page.\n\\ ----------------------------------------------------------\n\n: NVRAMVALID? ( addr -- t\/f ) \n\\ *G See if there is valid data in the NVRAM.\n\\ ** It consists of 3 words. If any of them are \n\\ ** set to 0xffff:ffff, we go with the defaults.\n dup @ -1 = \n over 4 + @ -1 = or\n swap 8 + @ -1 = or \n;\n\n: NVRAMLOAD ( addr -- ) $C 0 do dup I + @ needle_max I + ! 4 + loop ; \n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nidata\ncreate ODN_HMS odn allot \\ On-Deck, HMS\ncreate ODN_DHMS odn allot \\ On-Deck, DHMS\ncreate ODN_UI odn allot \\ On-Deck, Generated by the UI.\ncdata\n\nidata\ncreate NEEDLE_MAX #850 , #850 , #850 ,\ncdata\n\n\n: rangecheck ( max n -- n or zero ) dup >R <= if R> drop 0 else R> then ; \n\n: ++NEEDLE_S \\ Called every time.\n odn_hms odn.s \\ Stash this address for the moment. \n\n\tneedle_max odn.s @ \\ Get the max \n\tover w@ \\ Current value \n\n\tinterp_hms interp.a interp-next + \\ Returns a value.\n\t\n\t\\ If we've wrapped to zero, reset the interpolator \n\t\\ so that we don't accumulate errors during setting\/\n\t\\ calibration operations.\n rangecheck dup 0= if interp_hms interp.a interp-reset then \t\t\n\tswap w! \n\t;\n\n: ++NEEDLE_DS ; \\ Called every time.\n\n: ++NEEDLE_M ; \\ Every time we roll the seconds.\n: ++NEEDLE_DM ; \\ Every time we roll the seconds.\n\n: _USE ( odn-addr -- ) \n dup w@ pwm0!\n dup 2 + w@ pwm1!\n 4 + w@ pwm2!\n ;\n\n: USE-CLOCKVALS odn_hms _use ; \n: USE-UIVALS odn_ui _use ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Quadrature\n\\ ----------------------------------------------------------\n\n: QUAD@ ( addr -- n ) \\ Fetch and zero\n @off [asm sxth tos, tos asm] ;\n \n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_ds , ' ++needle_dm , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n: ADVANCETIME ( struct-addr -- )\n dup hms.w_s @ execute \\ Invoke the official update word.\n 1 over hms.subsec +! \\ Increment\n dup hms.subsec @\n over hms.maxsubsec @ < if drop exit then \\ If less then max, we're done\n 0 over hms.subsec ! \\ Reset the subsecs \n\n dup hms.w_m @ execute\n 1 over hms.s +!\n dup hms.s @ over hms.maxsec @ < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n 1 over hms.m +!\n dup hms.m @ over hms.maxsec @ < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ over hms.maxhour @ < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ----------------------------------------------------------\n\\ The interpolator. \n\\ Implement bresenhams algorithm. All of this code already\n\\ exists in C, but we'll own the data structures. They contain\n\\ A total of 4 words - fixed, err, num, & denom\n\\ ----------------------------------------------------------\nudata \ncreate interp_hms _interp_set allot\ncreate interp_dhms _interp_set allot \ncreate adj_list #50 cells allot \\ 100 16-bit words. \ncdata\n\n#16 #60 * equ raw_sec\n#10 #100 * equ raw_dsec\n\n: INTERP-INIT ( -- )\n (interp_init) interp_hms\n 2dup interp.a needle_max @ raw_sec call3-- \n 2dup interp.b needle_max 4 + @ #60 call3-- \n interp.c needle_max 8 + @ #12 call3--\n\n (interp_init) interp_dhms\n 2dup interp.a needle_max @ raw_dsec call3-- \n 2dup interp.b needle_max 4 + @ #100 call3-- \n interp.c needle_max 8 + @ #10 call3--\n;\n\n\\ Call the reset fn.\n: INTERP-RESET ( interp_addr -- )\n (interp_reset) swap call1-- \n;\n\n: INTERP-NEXT ( addr -- n )\n (interp_next) swap call1--n\n;\n\n\n\\ ============================ UNTESTED =======================\n\\ VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n\n\\ ----------------------------------------------------------\n\\ User Interface\n\\ ----------------------------------------------------------\nvariable uistate\nvariable uicount \n\n_GPIO $64 + equ _BUTTONIO\n: BUTTONUP? ( -- t\/f ) _buttonio @ 1 and ; \n: BUTTONDOWN? ( -- t\/f ) buttonup? 1 or ; \n\n\\ The wrapper for all of the UI stuff.\n\\ Returns true if the UI is active - ie, use the values generated by the UI.\n: UIUPDATE ( -- t\/f )\n StateHandlers uistate @ + @ execute \n; \n\n\\ -----------------------------------------------\n\\ State numbers. These are defined x4 so that\n\\ we can just use the state number as an index \n\\ into a table of words.\n\\ -----------------------------------------------\n0 4 * equ _s_init\n1 4 * equ _s_b1\n2 4 * equ _s_1sec\n3 4 * equ _s_seth\n4 4 * equ _s_pendset_m\n5 4 * equ _s_setmin\n6 4 * equ _s_pendcal0\n7 4 * equ _s_cal0\n8 4 * equ _s_pendcalh\n9 4 * equ _s_calh\n10 4 * equ _s_pendcalm\n11 4 * equ _s_calm\n12 4 * equ _s_pendcals\n13 4 * equ _s_cals\n\n\\ All of the state handlers.\n\\ Everybody needs to know the state of the button, so that must\n\\ get passed in, thus they all look like this:\n\\ state ( t\/f -- t\/f )\n: shInit false \n buttondown? if \n _s_b1 uistate !\n uicount off \\ Reset this.\n then\n ;\n\n\\ Waiting for a full second to go by.\n: shB1 false\n buttonup? if _s_init uistate ! exit then\n \\ The Button is down. \n uicount @ 16 > if\n _s_1sec uistate !\n else \n 1 uicount +!\n\tthen\n ;\n\n\\ We're in the 1 second state\n: sh1sec true \n buttonup? if _s_seth uistate ! true exit then\n uicount @ 48 > if\n _s_pendcal0 uistate !\n else \n 1 uicount +!\n\tthen \n;\n\n\\ -------------------------------------------------\n\\ Setting the time\n\\ -------------------------------------------------\n: shSetH true buttondown? if _s_pendset_m uistate ! exit then ;\n\n: shPendSetM true buttonup? if _s_setmin uistate ! then ;\n: shSetMin true buttondown? if _s_pendset_m uistate ! exit then ;\n\n\\ -------------------------------------------------\n\\ Calibration\n\\ -------------------------------------------------\n: shPendCal0 true buttonup? if _s_cal0 uistate ! then ;\n: shCal0 true buttondown? if _s_pendcalh uistate ! exit then ;\n\n: shPendCalH true buttonup? if _s_calh uistate ! then ; \n: shCalH true buttondown? if _s_pendcalm uistate ! exit then ; \n\n: shPendCalM true buttonup? if _s_calm uistate ! then ; \n: shCalM true buttondown? if _s_pendcals uistate ! exit then ; \n\n: shPendCalS true buttonup? if _s_calm uistate ! then ; \n: shCalS true buttondown? if _s_init uistate ! exit then ; \n\ncreate StateHandlers \n' shInit , \n' shB1 ,\n' sh1sec ,\n' shSetH ,\n' shPendSetM , ' shSetMin ,\n\n' shPendCal0 , ' shCal0 ,\n' shPendCalH , ' shCalH , \n' shPendCalM , ' shCalM , \n' shPendCalS , ' shCalS , \n\n","old_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( -- )\n load-defaults \n icroot 0 over inter.rtcsem ! \\ Reset the free-running counters.\n 0 over inter.rtcdsem ! \\ Reset the free-running counters.\n\n begin \n \tdup inter.rtcsem @offex! ?dup if advancehms then\n \tdup inter.rtcdsem @offex! ?dup if advancedhms then\n [asm wfi asm]\n uiupdate if use-uivals else use-clockvals then \n key? until drop\n;\n \n\\ These two contain loops to ensure that we don't\n\\ drop any timer ticks on the floor.\n: ADVANCEHMS ( n -- ) 0 do hms advancetime loop ;\n: ADVANCEDHMS ( n -- ) 0 do dhms advancetime loop ;\n \n: LOAD-DEFAULTS ( -- )\n #1000 needlemax\n 2dup ! 4 + 2dup ! 4 + ! \n interp-init\n;\n\n\\ ----------------------------------------------------------\n\\ Define the structures before they get used.\n\\ ----------------------------------------------------------\nstruct ODN \\ On-Deck Needle \n\t2 field odn.s\n\t2 field odn.m\n\t2 field odn.h\nend-struct\n\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxsec \\ Max Value for secs+minutes\n\tint hms.maxhour \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_m \\ increment the minutes + hours\nend-struct\n\nstruct _interp_set\n\t4 cells field interp.a\n\t4 cells field interp.b\n\t4 cells field interp.c\nend-struct\n\n\\ ----------------------------------------------------------\n\\ Defaults get saved in the user data page.\n\\ ----------------------------------------------------------\n\n: NVRAMVALID? ( addr -- t\/f ) \n\\ *G See if there is valid data in the NVRAM.\n\\ ** It consists of 3 words. If any of them are \n\\ ** set to 0xffff:ffff, we go with the defaults.\n dup @ -1 = \n over 4 + @ -1 = or\n swap 8 + @ -1 = or \n;\n\n: NVRAMLOAD ( addr -- ) $C 0 do dup I + @ needle_max I + ! 4 + loop ; \n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nidata\ncreate ODN_HMS odn allot \\ On-Deck, HMS\ncreate ODN_DHMS odn allot \\ On-Deck, DHMS\ncreate ODN_UI odn allot \\ On-Deck, Generated by the UI.\ncdata\n\nidata\ncreate NEEDLE_MAX #850 , #850 , #850 ,\ncdata\n\n\n: rangecheck ( max n -- n or zero ) dup >R <= if R> drop 0 else R> then ; \n\n: ++NEEDLE_S \\ Called every time.\n odn_hms odn.s \\ Stash this address for the moment. \n\n\tneedle_max odn.s @ \\ Get the max \n\tover w@ \\ Current value \n\n\tinterp_hms interp.a interp-next + \\ Returns a value.\n\t\n\t\\ If we've wrapped to zero, reset the interpolator \n\t\\ so that we don't accumulate errors during setting\/\n\t\\ calibration operations.\n rangecheck dup 0= if interp_hms interp.a interp-reset then \t\t\n\tswap w! \n\t;\n\n: ++NEEDLE_DS ; \\ Called every time.\n\n: ++NEEDLE_M ; \\ Every time we roll the seconds.\n: ++NEEDLE_DM ; \\ Every time we roll the seconds.\n\n: _USE ( odn-addr -- ) \n dup w@ pwm0!\n dup 2 + w@ pwm1!\n 4 + w@ pwm2!\n ;\n\n: USE-CLOCKVALS odn_hms _use ; \n: USE-UIVALS odn_ui _use ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Quadrature\n\\ ----------------------------------------------------------\n\n: QUAD@ ( addr -- n ) \\ Fetch and zero\n @off [asm sxth tos, tos asm] ;\n \n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_ds , ' ++needle_dm , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n: ADVANCETIME ( struct-addr -- )\n dup hms.w_s @ execute \\ Invoke the official update word.\n 1 over hms.subsec +! \\ Increment\n dup hms.subsec @\n over hms.maxsubsec @ < if drop exit then \\ If less then max, we're done\n 0 over hms.subsec ! \\ Reset the subsecs \n\n dup hms.w_m @ execute\n 1 over hms.s +!\n dup hms.s @ over hms.maxsec @ < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n 1 over hms.m +!\n dup hms.m @ over hms.maxsec @ < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ over hms.maxhour @ < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ----------------------------------------------------------\n\\ The interpolator. \n\\ Implement bresenhams algorithm. All of this code already\n\\ exists in C, but we'll own the data structures. They contain\n\\ A total of 4 words - fixed, err, num, & denom\n\\ ----------------------------------------------------------\nudata \ncreate interp_hms _interp_set allot\ncreate interp_dhms _interp_set allot \ncreate adj_list #50 cells allot \\ 100 16-bit words. \ncdata\n\n\\ Heres the default values. These are universal.\nidata\ncreate interp_max #850 , #850 , #850 ,\ncdata\n\n#16 #60 * equ raw_sec\n#10 #100 * equ raw_dsec\n\n: INTERP-INIT ( -- )\n (interp_init) interp_hms\n 2dup interp.a interp_max @ raw_sec call3-- \n 2dup interp.b interp_max 4 + @ #60 call3-- \n interp.c interp_max 8 + @ #12 call3--\n\n (interp_init) interp_dhms\n 2dup interp.a interp_max @ raw_dsec call3-- \n 2dup interp.b interp_max 4 + @ #100 call3-- \n interp.c interp_max 8 + @ #10 call3--\n;\n\n\\ Call the reset fn.\n: INTERP-RESET ( interp_addr -- )\n (interp_reset) swap call1-- \n;\n\n: INTERP-NEXT ( addr -- n )\n (interp_next) swap call1--n\n;\n\n\n\\ ============================ UNTESTED =======================\n\\ VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n\n\\ ----------------------------------------------------------\n\\ User Interface\n\\ ----------------------------------------------------------\nvariable uistate\nvariable uicount \n\n_GPIO $64 + equ _BUTTONIO\n: BUTTONUP? ( -- t\/f ) _buttonio @ 1 and ; \n: BUTTONDOWN? ( -- t\/f ) buttonup? 1 or ; \n\n\\ The wrapper for all of the UI stuff.\n\\ Returns true if the UI is active - ie, use the values generated by the UI.\n: UIUPDATE ( -- t\/f )\n StateHandlers uistate @ + @ execute \n; \n\n\\ -----------------------------------------------\n\\ State numbers. These are defined x4 so that\n\\ we can just use the state number as an index \n\\ into a table of words.\n\\ -----------------------------------------------\n0 4 * equ _s_init\n1 4 * equ _s_b1\n2 4 * equ _s_1sec\n3 4 * equ _s_seth\n4 4 * equ _s_pendset_m\n5 4 * equ _s_setmin\n6 4 * equ _s_pendcal0\n7 4 * equ _s_cal0\n8 4 * equ _s_pendcalh\n9 4 * equ _s_calh\n10 4 * equ _s_pendcalm\n11 4 * equ _s_calm\n12 4 * equ _s_pendcals\n13 4 * equ _s_cals\n\n\\ All of the state handlers.\n\\ Everybody needs to know the state of the button, so that must\n\\ get passed in, thus they all look like this:\n\\ state ( t\/f -- t\/f )\n: shInit false \n buttondown? if \n _s_b1 uistate !\n uicount off \\ Reset this.\n then\n ;\n\n\\ Waiting for a full second to go by.\n: shB1 false\n buttonup? if _s_init uistate ! exit then\n \\ The Button is down. \n uicount @ 16 > if\n _s_1sec uistate !\n else \n 1 uicount +!\n\tthen\n ;\n\n\\ We're in the 1 second state\n: sh1sec true \n buttonup? if _s_seth uistate ! true exit then\n uicount @ 48 > if\n _s_pendcal0 uistate !\n else \n 1 uicount +!\n\tthen \n;\n\n\\ -------------------------------------------------\n\\ Setting the time\n\\ -------------------------------------------------\n: shSetH true buttondown? if _s_pendset_m uistate ! exit then ;\n\n: shPendSetM true buttonup? if _s_setmin uistate ! then ;\n: shSetMin true buttondown? if _s_pendset_m uistate ! exit then ;\n\n\\ -------------------------------------------------\n\\ Calibration\n\\ -------------------------------------------------\n: shPendCal0 true buttonup? if _s_cal0 uistate ! then ;\n: shCal0 true buttondown? if _s_pendcalh uistate ! exit then ;\n\n: shPendCalH true buttonup? if _s_calh uistate ! then ; \n: shCalH true buttondown? if _s_pendcalm uistate ! exit then ; \n\n: shPendCalM true buttonup? if _s_calm uistate ! then ; \n: shCalM true buttondown? if _s_pendcals uistate ! exit then ; \n\n: shPendCalS true buttonup? if _s_calm uistate ! then ; \n: shCalS true buttondown? if _s_init uistate ! exit then ; \n\ncreate StateHandlers \n' shInit , \n' shB1 ,\n' sh1sec ,\n' shSetH ,\n' shPendSetM , ' shSetMin ,\n\n' shPendCal0 , ' shCal0 ,\n' shPendCalH , ' shCalH , \n' shPendCalM , ' shCalM , \n' shPendCalS , ' shCalS , \n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"d65e385527ac8cdde4f8a0f28fbe69f5faa17779","subject":"boot: change branding for -devel","message":"boot: change branding for -devel\n","repos":"opnsense\/core,opnsense\/core,opnsense\/core,opnsense\/core,opnsense\/core,opnsense\/core","old_file":"src\/boot\/logo-hourglass.4th","new_file":"src\/boot\/logo-hourglass.4th","new_contents":"\\ Copyright (c) 2006-2015 Devin Teske \n\\ Copyright (c) 2016 Deciso B.V.\n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\n48 logoX ! 9 logoY ! \\ Initialize logo placement defaults\n\n: logo+ ( x y c-addr\/u -- x y' )\n\t2swap 2dup at-xy 2swap \\ position the cursor\n\t[char] # escc! \\ replace # with Esc\n\ttype \\ print to the screen\n\t1+ \\ increase y for next time we're called\n;\n\n: logo ( x y -- ) \\ color hourglass logo (15 rows x 32 columns)\n\n\ts\" #[37;1m @@@@@@@@@@@@@@@@@@@@@@@@@@@@\" logo+\n\ts\" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\" logo+\n\ts\" @@@@@ @@@@@\" logo+\n\ts\" @@@@@ @@@@@ \" logo+\n\ts\" @@@@@@@@@@@ @@@@@@@@@@@\" logo+\n\ts\" #[31;1m\\\\\\\\\\ \/\/\/\/\/ \" logo+\n\ts\" )))))))))))) (((((((((((\" logo+\n\ts\" \/\/\/\/\/ \\\\\\\\\\ #[m\" logo+\n\ts\" #[37;1m @@@@@@@@@@@ @@@@@@@@@@@\" logo+\n\ts\" @@@@@ @@@@@ \" logo+\n\ts\" @@@@@ @@@@@\" logo+\n\ts\" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\" logo+\n\ts\" @@@@@@@@@@@@@@@@@@@@@@@@@@@@ \" logo+\n\ts\" #[m \" logo+\n\ts\" 17.1 ``Insert Name Here'' #[m\" logo+\n\n\t2drop\n;\n","old_contents":"\\ Copyright (c) 2006-2015 Devin Teske \n\\ Copyright (c) 2016 Deciso B.V.\n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\n48 logoX ! 9 logoY ! \\ Initialize logo placement defaults\n\n: logo+ ( x y c-addr\/u -- x y' )\n\t2swap 2dup at-xy 2swap \\ position the cursor\n\t[char] # escc! \\ replace # with Esc\n\ttype \\ print to the screen\n\t1+ \\ increase y for next time we're called\n;\n\n: logo ( x y -- ) \\ color hourglass logo (15 rows x 32 columns)\n\n\ts\" #[37;1m @@@@@@@@@@@@@@@@@@@@@@@@@@@@\" logo+\n\ts\" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\" logo+\n\ts\" @@@@@ @@@@@\" logo+\n\ts\" @@@@@ @@@@@ \" logo+\n\ts\" @@@@@@@@@@@ @@@@@@@@@@@\" logo+\n\ts\" #[31;1m\\\\\\\\\\ \/\/\/\/\/ \" logo+\n\ts\" )))))))))))) (((((((((((\" logo+\n\ts\" \/\/\/\/\/ \\\\\\\\\\ #[m\" logo+\n\ts\" #[37;1m @@@@@@@@@@@ @@@@@@@@@@@\" logo+\n\ts\" @@@@@ @@@@@ \" logo+\n\ts\" @@@@@ @@@@@\" logo+\n\ts\" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\" logo+\n\ts\" @@@@@@@@@@@@@@@@@@@@@@@@@@@@ \" logo+\n\ts\" #[m \" logo+\n\ts\" 16.7 ``Dancing Dolphin'' #[m\" logo+\n\n\t2drop\n;\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"a490e550c37ac6406e18bb851d88bb8ecddd307e","subject":"Comments.","message":"Comments.","repos":"rbsexton\/sockpuppet,rbsexton\/sockpuppet","old_file":"forth\/serCM3_sapi_p.fth","new_file":"forth\/serCM3_sapi_p.fth","new_contents":"\\ serCM3_sapi_p.fth - SAPI polled RX, polled TX, serial communication drivers\n\\ Written to run against the SockPuppet API.\n\n((\nAdapted from: the LPC polled driver.\n))\n\nonly forth definitions\nvariable cnt.pause \n\n\\ ==============\n\\ *! serCM3_sapi_p\n\\ *T SAPI polled serial driver\n\\ ==============\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\n\\ ** using the internal UARTs via the SAPI call layer.\n\n\n\\ ****************\n\\ *S Configuration\n\\ ****************\n\\ *P Configuration is managed by the SAPI\n\n\\ ********\n\\ *S Tools\n\\ ********\n\ntarget\n\n\\ ********************\n\\ *S Serial primitives\n\\ ********************\n\n0 value sercallback \n\ninternal\n\n: +FaultConsole\t( -- ) ;\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\n\\ ** for more details.\n\ntarget\n\nCODE (seremitfc)\t\\ char base --\n\\ *G Service call for a single char - just fill in the registers\n\\ from the stack and make the call, and get back the flow control feedback\n\\ Put TOS into r0, pull r1 off the stack, and refresh the stack.\n\tmov r0, tos\n\tldr r1, [ psp ], # 4\t\n\tsvc # SAPI_VEC_PUTCHAR\t\n\tmov tos, r0\n next,\nEND-CODE\n\n: (seremit)\t\\ char base -- \n\\ *G Wrapped call that checks for throttling, and if so,\n\\ calls PAUSE to let another task run. Count these events for debugging purposes.\n\t(seremitfc)\n\t0<> IF 1 cnt.pause +! #5 ms THEN\n\t;\n\n: (sertype)\t\\ caddr len base --\n\\ *G Transmit a string on the given UART.\n -rot bounds\n ?do i c@ over (seremit) loop\n drop\n;\n\n: (sercr)\t\\ base --\n\\ *G Transmit a CR\/LF pair on the given UART.\n $0D over (seremit) $0A swap (seremit)\n;\n\nCODE (sergetchar) \\ base -- c\n\\ *G Get a character from the port\n\tmov r0, tos\t\n\tsvc # SAPI_VEC_GETCHAR\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE (serkey?) \\ base -- t\/f\n\\ *G Return true if the given UART has a character avilable to read.\n\\ The call returns 0 or 1. \n\tmov r0, tos\n\tsvc # SAPI_VEC_CHARSAVAIL\t\t\n\tmov tos, r0\n\tnext,\t\nEND-CODE\n\n: (serkey-basic)\n\tbegin pause \n\tdup (serkey?) until \n\t(sergetchar)\n;\n\n: (serkey-sleep?)\n\tself tcb.bbstatus @ over 1 setiocallback drop ( base )\n\tself halt \n\tdup (serkey?) IF self restart ELSE PAUSE THEN \\ We are now armed and ready to block\n (serkey?) \n;\n\n\\ *G Wait for a character to come available on the given UART and\n\\ ** return the character.\n\\ Advanced usage - Register a callback. \n\\ The tricky part is not screwing things up by missing a character\n\\ in the window between when you register, and when you pick up your\n\\ character. The way to do that is by registering, then self \n\\ halting, and then checking for a new character. That ensures that\n\\ if a character has slipped in, you will catch it.\n: (serkey)\t\\ base -- char\n\tbegin dup (serkey-sleep?) until (sergetchar)\n;\n\nexternal \n\n: seremit0\t\\ char --\n\\ *G Transmit a character on UART0.\n 0 (seremit) ;\n: sertype0\t\\ c-addr len --\n\\ *G Transmit a string on UART0.\n 0 (sertype) ;\n: sercr0\t\\ --\n\\ *G Issue a CR\/LF pair to UART0.\n 0 (sercr) ;\n: serkey?0\t\\ -- flag\n\\ *G Return true if UART0 has a character available.\n 0 (serkey?) ;\n: serkey0\t\\ -- char\n\\ *G Wait for a character on UART0.\n 0 (serkey) ;\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\n\\ *G Generic I\/O device for UART0.\n ' serkey0 ,\t\t\\ -- char ; receive char\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\n ' seremit0 ,\t\t\\ -- char ; display char\n ' sertype0 ,\t\t\\ caddr len -- ; display string\n ' sercr0 ,\t\t\\ -- ; display new line\n\n\\ UART2\n: seremit2 #2 (seremit) ;\n: sertype2\t#2 (sertype) ;\n: sercr2\t#2 (sercr) ;\n: serkey?2\t#2 (serkey?) ;\n: serkey2\t#2 (serkey) ;\ncreate Console2 ' serkey2 , ' serkey?2 , ' seremit2 , ' sertype2 , ' sercr2 ,\t\n\n\\ Versions for use with the TCP Port (10)\n: seremit10 #10 (seremit) ;\n: sertype10\t#10 (sertype) ;\n: sercr10\t#10 (sercr) ;\n: serkey?10\t#10 (serkey?) ;\n: serkey10\t#10 (serkey) ;\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\n\nconsole-port 0 = [if]\n console0 constant console\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\n\\ ** It may be changed by one of the phrases of the form:\n\\ *C dup opvec ! ipvec !\n\\ *C SetConsole\n[then]\n\nconsole-port #1 = [if]\n console1 constant console\n[then]\n\nconsole-port #10 = [if]\n console10 constant console\n[then]\n\n\\ ************************\n\\ *S System initialisation\n\\ ************************\n\n\\ This is a NOP in the SAPI environment\n: init-ser ;\t\\ --\n\\ *G Initialise all serial ports\n\n\n\\ ======\n\\ *> ###\n\\ ======\n\ndecimal\n","old_contents":"\\ serCM3_sapi_p.fth - SAPI polled RX, polled TX, serial communication drivers\n\\ Written to run against the SockPuppet API.\n\n((\nAdapted from: the LPC polled driver.\n))\n\nonly forth definitions\nvariable cnt.pause \n\n\\ ==============\n\\ *! serCM3_sapi_p\n\\ *T SAPI polled serial driver\n\\ ==============\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\n\\ ** using the internal UARTs via the SAPI call layer.\n\n\n\\ ****************\n\\ *S Configuration\n\\ ****************\n\\ *P Configuration is managed by the SAPI\n\n\\ ********\n\\ *S Tools\n\\ ********\n\ntarget\n\n\\ ********************\n\\ *S Serial primitives\n\\ ********************\n\n0 value sercallback \n\ninternal\n\n: +FaultConsole\t( -- ) ;\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\n\\ ** for more details.\n\ntarget\n\nCODE (seremitfc)\t\\ char base --\n\\ *G Service call for a single char - just fill in the registers\n\\ from the stack and make the call, and get back the flow control feedback\n\\ Put TOS into r0, pull r1 off the stack, and refresh the stack.\n\tmov r0, tos\n\tldr r1, [ psp ], # 4\t\n\tsvc # SAPI_VEC_PUTCHAR\t\n\tmov tos, r0\n next,\nEND-CODE\n\n: (seremit)\t\\ char base -- \n\\ *G Wrapped call that checks for throttling, and if so,\n\\ calls PAUSE to let another task run. Count these events for debugging purposes.\n\t(seremitfc)\n\t0<> IF 1 cnt.pause +! #5 ms THEN\n\t;\n\n: (sertype)\t\\ caddr len base --\n\\ *G Transmit a string on the given UART.\n -rot bounds\n ?do i c@ over (seremit) loop\n drop\n;\n\n: (sercr)\t\\ base --\n\\ *G Transmit a CR\/LF pair on the given UART.\n $0D over (seremit) $0A swap (seremit)\n;\n\nCODE (sergetchar) \\ base -- c\n\\ *G Get a character from the port\n\tmov r0, tos\t\n\tsvc # SAPI_VEC_GETCHAR\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE (serkey?) \\ base -- t\/f\n\\ *G Return true if the given UART has a character avilable to read.\n\\ The call returns 0 or 1. \n\tmov r0, tos\n\tsvc # SAPI_VEC_CHARSAVAIL\t\t\n\tmov tos, r0\n\tnext,\t\nEND-CODE\n\n: (serkey-basic)\n\tbegin pause \n\tdup (serkey?) until \n\t(sergetchar)\n;\n\n: (serkey-sleep?)\n\tself tcb.bbstatus @ over 1 setiocallback drop ( base oldcb )\n\tself halt \n\tdup (serkey?) IF self restart ELSE PAUSE THEN \\ We are now armed and ready to block\n (serkey?)\n;\n\n\\ *G Wait for a character to come available on the given UART and\n\\ ** return the character.\n\\ Advanced usage - Register a callback. \n\\ The tricky part is not screwing things up by missing a character\n\\ in the window between when you register, and when you pick up your\n\\ character. The way to do that is by registering, then self \n\\ halting, and then checking for a new character. That ensures that\n\\ if a character has slipped in, you will catch it.\n: (serkey)\t\\ base -- char\n\tbegin dup (serkey-sleep?) until (sergetchar)\n;\n\nexternal \n\n: seremit0\t\\ char --\n\\ *G Transmit a character on UART0.\n 0 (seremit) ;\n: sertype0\t\\ c-addr len --\n\\ *G Transmit a string on UART0.\n 0 (sertype) ;\n: sercr0\t\\ --\n\\ *G Issue a CR\/LF pair to UART0.\n 0 (sercr) ;\n: serkey?0\t\\ -- flag\n\\ *G Return true if UART0 has a character available.\n 0 (serkey?) ;\n: serkey0\t\\ -- char\n\\ *G Wait for a character on UART0.\n 0 (serkey) ;\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\n\\ *G Generic I\/O device for UART0.\n ' serkey0 ,\t\t\\ -- char ; receive char\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\n ' seremit0 ,\t\t\\ -- char ; display char\n ' sertype0 ,\t\t\\ caddr len -- ; display string\n ' sercr0 ,\t\t\\ -- ; display new line\n\n\\ UART2\n: seremit2 #2 (seremit) ;\n: sertype2\t#2 (sertype) ;\n: sercr2\t#2 (sercr) ;\n: serkey?2\t#2 (serkey?) ;\n: serkey2\t#2 (serkey) ;\ncreate Console2 ' serkey2 , ' serkey?2 , ' seremit2 , ' sertype2 , ' sercr2 ,\t\n\n\\ Versions for use with the TCP Port (10)\n: seremit10 #10 (seremit) ;\n: sertype10\t#10 (sertype) ;\n: sercr10\t#10 (sercr) ;\n: serkey?10\t#10 (serkey?) ;\n: serkey10\t#10 (serkey) ;\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\n\nconsole-port 0 = [if]\n console0 constant console\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\n\\ ** It may be changed by one of the phrases of the form:\n\\ *C dup opvec ! ipvec !\n\\ *C SetConsole\n[then]\n\nconsole-port #1 = [if]\n console1 constant console\n[then]\n\nconsole-port #10 = [if]\n console10 constant console\n[then]\n\n\\ ************************\n\\ *S System initialisation\n\\ ************************\n\n\\ This is a NOP in the SAPI environment\n: init-ser ;\t\\ --\n\\ *G Initialise all serial ports\n\n\n\\ ======\n\\ *> ###\n\\ ======\n\ndecimal\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"4f33ffeeac2cfe7fab55713e0443c93017a2405b","subject":"midifile: change use of CELL","message":"midifile: change use of CELL\n\nThe old code was using CELL, which was 4 in the old days.\nNow CELL is 8. But we still need 4 because that is the\nsize of the chunk and length fields in a MIDI file.\n","repos":"philburk\/hmsl,philburk\/hmsl,philburk\/hmsl","old_file":"hmsl\/tools\/midifile.fth","new_file":"hmsl\/tools\/midifile.fth","new_contents":"\\ MIDI File Standard Support\n\\\n\\ This code allows the sharing of music data between applications.\n\\\n\\ Author: Phil Burk\n\\ Copyright 1989 Phil Burk\n\\\n\\ MOD: PLB 6\/11\/90 Added SWAP to $MF.LOAD.SHAPE\n\\ MOD: PLB 10\/23\/90 Added $MF.OPEN.VR\n\\ MOD: PLB 6\/91 Add MIDIFILE1{\n\\ 00001 PLB 9\/5\/91 Fix MIDIFILE1{ by c\/i\/j\/\n\\ 00002 PLB 3\/17\/92 Changed MF.WRITE.REL.SHAPE to make notes legato\n\\ for notation programs. Add $SAVE.REL.SHAPE and $..ABS..\n\nANEW TASK-MIDIFILE\ndecimal\n\n\\ Variable Length Number Conversion\nvariable VLN-PAD ( accumulator for variable length number )\nvariable VLN-COUNT ( number of bytes )\n\n: BYTE>VLN ( byte -- , add byte to VLN buffer )\n vln-count @ 0>\n IF $ 80 or ( set continuation bit )\n THEN\n vln-pad 4+ vln-count @ 1+ dup vln-count !\n - c!\n;\n\n: NUMBER->VLN ( N -- address count , convert )\n dup $ 0FFFFFFF >\n IF .\" NUMBER->VL - Number too big for MIDI File! = \"\n dup .hex cr\n $ 0FFFFFFF and\n THEN\n dup 0<\n IF .\" NUMBER->VL - Negative length or time! = \"\n dup .hex cr\n drop 0\n THEN\n vln-count off\n BEGIN dup $ 7F and byte>vln\n -7 shift dup 0=\n UNTIL drop\n vln-pad 4+ vln-count @ dup>r - r>\n;\n\n: VLN.CLEAR ( -- , clear for read )\n vln-count off vln-pad off\n;\n\n: VLN.ACCUM ( byte -- accumulate another byte )\n $ 7F and\n vln-pad @ 7 shift or vln-pad !\n;\n\n\\ -------------------------------------------------\nvariable MF-BYTESLEFT\nvariable MF-EVENT-TIME\nvariable MF-#DATA\n\n: CHKID ( -- , define chkid )\n 32 lword count drop be@ constant\n;\n\nchkid MThd 'MThd'\nchkid MTrk 'MTrk'\n\nvariable mf-FILEID\n4 constant MF_CHKID_SIZE \\ size of a length number in an SMF file\n4 constant MF_LENGTH_SIZE \\ size of a length number in an SMF file\nmf_chkid_size mf_length_size + constant MF_HEADER_SIZE\n16 constant MF_PAD_SIZE\nvariable mf-PAD mf_pad_size allot\n\nDEFER MF.PROCESS.TRACK ( size track# -- )\nDEFER MF.ERROR\n\n' abort is mf.error\n\n: .CHKID ( 'chkid' -- , print chunk id )\n pad be! pad 4 type\n;\n\n: $MF.OPEN ( $filename -- )\n dup c@ 0=\n IF drop .\" $MF.OPEN - No filename given!\" cr mf.error\n THEN\n dup count r\/o bin open-file\n IF drop .\" Couldn't open file: \" $type cr mf.error\n THEN\n mf-fileid !\n drop\n;\n\n: $MF.CREATE ( $filename -- , create new file )\n dup c@ 0=\n IF drop .\" $MF.OPEN - No filename given!\" cr mf.error\n THEN\n dup count w\/o bin create-file\n IF drop .\" Couldn't create file: \" $type cr mf.error\n THEN\n mf-fileid !\n drop\n;\n: MF.SET.FILE ( fileid -- )\n mf-fileid !\n;\n\n: MF.READ ( addr #bytes -- #bytes , read from open mf file)\n dup negate mf-bytesleft +!\n mf-fileid @ read-file abort\" Could not read MIDI file.\"\n;\n\n: MF.READ.CHKID ( -- size chkid )\n dup>r mf-pad mf_header_size mf.read\n mf_header_size -\n IF .\" Truncated chunk \" r@ .chkid cr mf.error\n THEN\n rdrop\n mf-pad mf_chkid_size + be@\n mf-pad be@\n;\n\n\n: MF.WRITE ( addr #bytes -- #bytes , write to open mf file)\n dup>r mf-fileid @ write-file abort\" Could not write MIDI file.\"\n r>\n;\n\n: MF.WRITE? ( addr #bytes -- , write to open mf file or mf.ERROR)\n mf-fileid @ write-file abort\" Could not write MIDI file.\"\n;\n\n: MF.READ.BYTE ( -- byte )\n mf-pad 1 mf.read 1-\n IF .\" MF.READ.BYTE - Unexpected EOF!\" cr mf.error\n THEN\n mf-pad c@\n;\n\n: MF.WRITE.BYTE ( byte -- )\n mf-pad c! mf-pad 1 mf.write?\n;\n\n: MF.WRITE.WORD ( 16word -- )\n mf-pad w! mf-pad 2 mf.write?\n;\n\n: MF.READ.WORD ( -- 16word )\n mf-pad 2 mf.read 2-\n IF .\" MF.READ.WORD - Unexpected EOF!\" cr mf.error\n THEN\n mf-pad w@\n;\n\n: MF.WRITE.CHKID ( size chkid -- , write chunk header )\n mf-pad be!\n mf-pad mf_chkid_size + be!\n mf-pad mf_header_size mf.write?\n;\n\n: MF.WRITE.CHUNK ( address size chkid -- , write complete chunk )\n over >r mf.write.chkid\n r> mf.write?\n;\n\n: MF.READ.TYPE ( -- typeid )\n mf-pad 4 mf.read\n 4 -\n IF .\" Truncated type!\" cr mf.error\n THEN\n mf-pad be@\n;\n\n: MF.WHERE ( -- current_pos , in file )\n mf-fileid @ file-position abort\" file-position failed\"\n d>s \\ file-position returns a double word\n;\n\n: MF.SEEK ( position -- , in file )\n s>d \\ reposition-file takes a double word\n mf-fileid @ reposition-file abort\" reposition-file failed\"\n;\n\n: MF.SKIP ( n -- , skip n bytes in file )\n dup negate mf-bytesleft +!\n mf.where + mf.seek\n;\n\n: MF.CLOSE\n mf-fileid @ ?dup\n IF close-file abort\" close-file failed\"\n 0 mf-fileid !\n THEN\n;\n\nvariable MF-NTRKS \\ number of tracks in file\nvariable MF-FORMAT \\ file format = 0 | 1 | 2\nvariable MF-DIVISION \\ packed division\n\n: MF.PROCESS.HEADER ( size -- )\n dup mf_pad_size >\n IF .\" MF.PROCESS.HEADER - Bad Header Size = \"\n dup . cr mf.error\n THEN\n mf-pad swap mf.read drop\n mf-pad bew@ mf-format w!\n mf-pad 2+ bew@ mf-ntrks !\n mf-pad 4+ bew@ mf-division !\n;\n\n: MF.SCAN.HEADER ( -- , read header )\n mf.read.chkid ( -- size chkid)\n 'MThd' =\n IF mf.process.header\n ELSE .\" MF.SCAN - Headerless MIDIFile!\" cr mf.error\n THEN\n;\n\n: MF.SCAN.TRACKS ( -- , read tracks )\n\\ This word leaves the file position just after the chunk data.\n mf-ntrks @ 0\n DO mf.read.chkid 'MTrk' =\n IF dup mf.where + >r\n i mf.process.track\n r> mf.seek ( move past chunk)\n ELSE .\" MF.SCAN - Unexpected CHKID!\" cr mf.error\n THEN\n LOOP\n;\n\n: MF.SCAN ( -- , read header then tracks)\n mf.scan.header\n mf.scan.tracks\n;\n\n: MF.VALIDATE ( -- ok? , make sure open file has header chunk )\n mf.where\n 0 mf.seek\n mf.read.type 'MThd' =\n swap mf.seek\n;\n\n: (MF.DOFILE) ( -- ,process current file )\n mf.validate\n IF mf.scan\n ELSE .\" Not a MIDIFile!\" cr\n mf.close mf.error\n THEN\n mf.close\n;\n\n: $MF.DOFILE ( $filename -- , process file using deferred words)\n $mf.open (mf.dofile)\n;\n\n: MF.DOFILE ( -- )\n fileword $mf.dofile\n;\n\n: MF.READ.VLN ( -- vln , read vln from file )\n vln.clear\n BEGIN mf.read.byte dup $ 80 and\n WHILE vln.accum\n REPEAT vln.accum\n vln-pad @\n;\n\ndefer MF.PROCESS.META ( size metaID -- , process Meta event )\ndefer MF.PROCESS.SYSEX\ndefer MF.PROCESS.ESCAPE\n\nvariable MF-SEQUENCE#\nvariable MF-CHANNEL\n: MF.LOOK.TEXT ( size metaID -- , read and show text )\n >newline .\" MetaEvent = \" . cr\n pad swap mf.read\n pad swap type cr\n;\n\n: MF.HANDLE.META ( size MetaID -- default Meta event handler )\n dup $ 01 $ 0f within?\n IF mf.look.text\n ELSE CASE\n $ 00 OF drop mf.read.word mf-sequence# ! ENDOF\n $ 20 OF drop mf.read.byte 1+ mf-channel ! ENDOF\n .\" MetaEvent = \" dup . cr\n swap mf.skip ( skip over other event types )\n ENDCASE\n THEN\n;\n\n' mf.handle.meta is MF.PROCESS.META\n' mf.skip is MF.PROCESS.SYSEX\n' mf.skip is MF.PROCESS.ESCAPE\n\n: MF.PARSE.EVENT ( -- , parse MIDI event )\n mf.read.byte dup $ 80 and ( is it a command or running status data )\n IF CASE\n $ FF OF mf.read.byte ( get type )\n mf.read.vln ( get size ) swap mf.process.meta ENDOF\n $ F0 OF .\" F0 byte\" cr mf.read.vln mf.process.sysex ENDOF\n $ F7 OF .\" F7 byte\" cr mf.read.vln mf.process.escape ENDOF\n\\ Regular command.\n dup mp.#bytes mf-#data !\n dup mp.handle.command\n mf-#data @ 0\n DO mf.read.byte mp.handle.data\n LOOP\n ENDCASE\n ELSE\n mp.handle.data ( call MIDI parser with byte read )\n mf-#data @ 1- 0 max 0\n DO mf.read.byte mp.handle.data\n LOOP\n THEN\n;\n\n: MF.PARSE.TRACK ( size track# -- )\n drop mf-bytesleft !\n 0 mf-event-time !\n BEGIN mf.read.vln mf-event-time +!\n mf.parse.event\n mf-bytesleft @ 1 <\n UNTIL\n;\n\n\\ Some Track Handlers\n: MF.PRINT.NOTEON ( note velocity -- )\n ?pause\n mf-event-time @ 4 .r .\" , \"\n .\" ON N,V = \" swap . . cr\n;\n: MF.PRINT.NOTEOFF ( note velocity -- )\n ?pause\n mf-event-time @ 4 .r .\" , \"\n .\" OFF N,V = \" swap . . cr\n;\n\n: MF.PRINT.TRACK ( size track# -- )\n 2dup\n >newline dup 0=\n IF .\" MIDIFile Format = \" mf-format @ . cr\n .\" Division = $\" mf-division @ dup .hex . cr\n THEN\n .\" Track# \" . .\" is \" . .\" bytes.\" cr\n 'c mf.print.noteon mp-on-vector !\n 'c mf.print.noteoff mp-off-vector !\n mf.parse.track\n mp.reset\n;\n\n' mf.print.track is mf.process.track\n\n: MF.CHECK ( -- , print chunks )\n what's mf.process.track\n ' mf.print.track is mf.process.track\n mf.dofile\n is mf.process.track\n;\n\n\\ Track Handler that loads a shape -----------------------\nvariable MF-TRACK-CHOSEN\nob.shape MF-SHAPE\n\n: MF.LOAD.NOTEON ( note velocity -- )\n mf-shape ensure.room\n mf-event-time @ -rot add: mf-shape\n;\n\n: MF.LOAD.NOTEOFF ( note velocity -- )\n mf-shape ensure.room\n drop mf-event-time @ swap 0 add: mf-shape\n;\n\n: MF.LOAD.TRACK ( size track# -- )\n max.elements: mf-shape 0=\n IF 64 3 new: mf-shape\n ELSE clear: mf-shape\n THEN\n 'c mf.load.noteon mp-on-vector !\n 'c mf.load.noteoff mp-off-vector !\n mf.parse.track\n;\n\n: MF.PICK.TRACK ( size track# -- )\n dup mf-track-chosen @ =\n IF mf.load.track\n ELSE 2drop\n THEN\n;\n\n: $MF.LOAD.SHAPE ( track# $filename -- , load track into mf-shape )\n swap mf-track-chosen !\n what's mf.process.track SWAP ( -- oldcfa $filename )\n 'c mf.pick.track is mf.process.track\n $mf.dofile\n is mf.process.track\n;\n\n: MF.LOAD.SHAPE ( track# -- , load track into mf-shape )\n fileword $mf.load.shape\n;\n\n: LOAD.ABS.SHAPE ( shape -- )\n 0 mf.load.shape\n clone: mf-shape\n free: mf-shape\n;\n\n\\ -------------------------------------------------\n\n\\ Tools for writing a MIDIFile.\n: MF.WRITE.HEADER ( format ntrks division -- )\n 6 'MThd' mf.write.chkid\n mf-pad 4+ bew! ( division )\n over 0=\n IF drop 1 ( force NTRKS to 1 for format zero )\n THEN\n mf-pad 2+ bew! ( ntrks )\n mf-pad bew! ( format )\n mf-pad 6 mf.write?\n;\n\n: MF.BEGIN.TRACK ( -- curpos , write track start )\n 0 'MTrk' mf.write.chkid\n mf.where\n 0 mf-event-time !\n;\n\n: MF.WRITE.VLN ( n -- , write variable length quantity )\n number->vln mf.write?\n;\n\n: MF.WRITE.TIME ( time -- , write time as vln delta )\n dup mf-event-time @ - mf.write.vln\n mf-event-time !\n;\n\n: MF.WRITE.EVENT ( addr count time -- , write MIDI event )\n\\ This might be called from custom MIDI.FLUSH\n mf.write.time\n mf.write?\n;\n\nvariable MF-EVENT-PAD\n\n: MF.WRITE.META ( addr count event-type -- )\n mf-event-time @ mf.write.time\n $ FF mf.write.byte\n mf.write.byte ( event type )\n dup mf.write.vln ( len )\n mf.write?\n;\n\n: MF.WRITE.SYSEX ( addr count -- )\n mf-event-time @ mf.write.time\n $ F0 mf.write.byte\n dup mf.write.vln ( len )\n mf.write?\n;\n\n: MF.WRITE.ESCAPE ( addr count -- )\n mf-event-time @ mf.write.time\n $ F7 mf.write.byte\n dup mf.write.vln ( len )\n mf.write?\n;\n\n: MF.WRITE.SEQ# ( seq# -- )\n mf-event-pad w!\n mf-event-pad 2 0 mf.write.meta\n;\n\n: MF.WRITE.END ( -- , write end of track )\n mf-event-pad 0\n $ 2F mf.write.meta\n;\n\n: MF.END.TRACK ( startpos -- , write length to track beginning )\n mf.where dup>r ( so we can return )\n over - ( -- start #bytes )\n swap mf_length_size - mf.seek\n mf-pad be! mf-pad 4 mf.write?\n r> mf.seek\n;\n\n: MF.CVM+2D ( time d1 d2 cvm -- )\n mf-event-pad c!\n mf-event-pad 2+ c!\n mf-event-pad 1+ c!\n mf-event-pad 3 rot mf.write.event\n;\n\n: MF.WRITE.NOTEON ( time note velocity -- )\n $ 90 mf.cvm+2d\n;\n\n: MF.WRITE.NOTEOFF ( time note velocity -- )\n $ 80 mf.cvm+2d\n;\n\n: $MF.BEGIN.FORMAT0 ( $name -- pos , begin format0 file )\n $mf.create\n 0 1 ticks\/beat @ mf.write.header\n mf.begin.track ( startpos )\n;\n\n: MF.BEGIN.FORMAT0 ( -- pos , begin format0 file )\n fileword $mf.begin.format0\n;\n\n: MF.END.FORMAT0 ( pos -- , end format0 file )\n mf.write.end\n mf.end.track\n mf.close\n;\n\n: MF.WRITE.ABS.SHAPE { shape -- , assume shape Nx3+ absolute time }\n\\ Assume separate note on\/off in shape\n shape reset: []\n shape many: [] 0\n DO i 0 shape ed.at: [] ( -- time )\n i 1 shape ed.at: [] ( -- time note )\n i 2 shape ed.at: [] ( -- time note vel )\n dup 0=\n IF mf.write.noteoff\n ELSE mf.write.noteon\n THEN\n LOOP\n;\n\nvariable MF-SHAPE-TIME\n\n: MF.WRITE.REL.SHAPE { shape | note vel -- , assume shape Nx3 relative time }\n 0 mf-shape-time !\n shape reset: []\n shape many: [] 0\n DO\n i 1 shape ed.at: [] -> note ( -- time note )\n i 2 shape ed.at: [] -> vel ( -- time note vel )\n mf-shape-time @ note vel mf.write.noteon\n\\\n\\ add to shape time so OFF occurs right before next notes ON 00002\n i 0 shape ed.at: [] ( -- reltime )\n mf-shape-time @ +\n dup mf-shape-time !\n note vel mf.write.noteoff\n LOOP\n;\n\n: $SAVE.REL.SHAPE ( shape $filename -- , complete file output )\n\\ This word writes out a relative time, 1 event\/note shape\n\\ as note on,off\n $mf.begin.format0\n swap mf.write.rel.shape\n mf.end.format0\n;\n\n: $SAVE.ABS.SHAPE ( shape $filename -- , complete file output )\n\\ This word writes out a shape as note on,off\n $mf.begin.format0\n swap mf.write.abs.shape\n mf.end.format0\n;\n\n: SAVE.REL.SHAPE ( shape -- , complete file output )\n fileword $save.rel.shape\n;\n\n: SAVE.ABS.SHAPE ( shape -- , complete file output )\n fileword $save.abs.shape\n;\n\n: MF.WRITE.TIMESIG ( nn dd cc bb -- )\n mf-event-pad 3 + c! ( time sig, numerator )\n mf-event-pad 2+ c! ( denom log2 )\n mf-event-pad 1+ c! ( MIDI clocks\/metronome click )\n mf-event-pad c! ( 32nd notes in 24 clocks )\n mf-event-pad 4 $ 58 mf.write.meta\n;\n\n: MF.WRITE.TEMPO ( mics\/beat -- )\n mf-event-pad !\n mf-event-pad 1+ 3 $ 51 mf.write.meta\n;\n\n\\ Capture all MIDI output to a Format0 file\nvariable MF-START-POS\nvariable MF-FIRST-WRITE\n\n: (MF.CAPTURED>FILE0) ( -- write captured MIDI to file format 0)\n 0 0 ed.at: captured-midi mf-event-time !\n many: captured-midi 0\n DO i get: captured-midi midi.unpack\n rot mf.write.event\n LOOP\n mf-start-pos @ mf.end.format0\n;\n\n: }MIDIFILE0 ( -- )\n if-capturing @\n IF (mf.captured>file0)\n }capture\n THEN\n;\n\n: $CAPTURED>MIDIFILE0 ( $filename -- )\n $mf.begin.format0 mf-start-pos ! ( use filename while still valid )\n (mf.captured>file0)\n;\n\n: $MIDIFILE0{ ( $filename -- , start capturing MIDI data )\n }midifile0\n $mf.begin.format0 mf-start-pos ! ( use filename while still valid )\n capture{\n;\n\n: MIDIFILE0{ ( -- )\n fileword $midifile0{\n;\n\nCREATE MF-COUNT-CAPS 16 allot\n\n: CAP.GET.CHAN ( status-byte -- channel# )\n $ 0F and 1+\n;\n\n: CAP.COUNT.CHANS ( -- #channels , count captured track\/channels )\n 16 0\n DO 0 i mf-count-caps + c!\n LOOP\n\\\n many: captured-midi 0\n DO i get: captured-midi midi.unpack drop c@\n cap.get.chan 1-\n nip\n mf-count-caps + 1 swap c! ( set flag in array )\n LOOP\n\\\n 0\n 16 0\n DO i mf-count-caps + c@ +\n LOOP\n;\n\n: (MF.CAPTURED>FILE1) ( -- , write tracks with data to metafile )\n cap.count.chans ( #chans )\n \\ write a track zero that should contain tempo maps\n 1+ \\ for track zero\n mf.begin.track ( -- pos )\n mf.write.end\n mf.end.track\n \\ Write each track with sequence number\n 16 0\n DO i mf-count-caps + c@\n IF\n mf.begin.track ( -- pos )\n 0 0 ed.at: captured-midi mf-event-time !\n i 1+ mf.write.seq#\n many: captured-midi 0\n DO\n i get: captured-midi midi.unpack\n over c@ cap.get.chan 1- j = \\ 00001\n IF\n ( time addr count -- )\n rot mf.write.event\n ELSE 2drop drop\n THEN\n LOOP\n mf.write.end\n mf.end.track\n THEN\n LOOP\n 0 mf.seek\n 1 swap ticks\/beat @ mf.write.header\n mf.close\n;\n\n: }MIDIFILE1 ( -- )\n if-capturing @\n IF (mf.captured>file1)\n }capture\n THEN\n;\n\n: $CAPTURED>MIDIFILE1 ( $filename -- )\n $mf.create\n 1 1 ticks\/beat @ mf.write.header\n (mf.captured>file1)\n;\n\n: $MIDIFILE1{ ( $filename -- , start capturing MIDI data )\n }midifile1\n $mf.create\n 1 1 ticks\/beat @ mf.write.header\n capture{\n;\n\n: MIDIFILE1{ ( -- )\n fileword $midifile1{\n;\n\n\\ set aliases to format 0 for compatibility with old code\n: MIDIFILE{ midifile0{ ;\n: $MIDIFILE{ $midifile0{ ;\n: }MIDIFILE }midifile0 ;\n\nif.forgotten }midifile0\n\n\n: tmf\n \" testzz5.mid\" $midifile0{\n rnow 55 60 midi.noteon\n 200 vtime+!\n 55 0 midi.noteoff\n }midifile0\n;\n\n","old_contents":"\\ MIDI File Standard Support\n\\\n\\ This code allows the sharing of music data between applications.\n\\\n\\ Author: Phil Burk\n\\ Copyright 1989 Phil Burk\n\\\n\\ MOD: PLB 6\/11\/90 Added SWAP to $MF.LOAD.SHAPE\n\\ MOD: PLB 10\/23\/90 Added $MF.OPEN.VR\n\\ MOD: PLB 6\/91 Add MIDIFILE1{\n\\ 00001 PLB 9\/5\/91 Fix MIDIFILE1{ by c\/i\/j\/\n\\ 00002 PLB 3\/17\/92 Changed MF.WRITE.REL.SHAPE to make notes legato\n\\ for notation programs. Add $SAVE.REL.SHAPE and $..ABS..\n\nANEW TASK-MIDIFILE\ndecimal\n\n\\ Variable Length Number Conversion\nvariable VLN-PAD ( accumulator for variable length number )\nvariable VLN-COUNT ( number of bytes )\n\n: BYTE>VLN ( byte -- , add byte to VLN buffer )\n vln-count @ 0>\n IF $ 80 or ( set continuation bit )\n THEN\n vln-pad 4+ vln-count @ 1+ dup vln-count !\n - c!\n;\n\n: NUMBER->VLN ( N -- address count , convert )\n dup $ 0FFFFFFF >\n IF .\" NUMBER->VL - Number too big for MIDI File! = \"\n dup .hex cr\n $ 0FFFFFFF and\n THEN\n dup 0<\n IF .\" NUMBER->VL - Negative length or time! = \"\n dup .hex cr\n drop 0\n THEN\n vln-count off\n BEGIN dup $ 7F and byte>vln\n -7 shift dup 0=\n UNTIL drop\n vln-pad 4+ vln-count @ dup>r - r>\n;\n\n: VLN.CLEAR ( -- , clear for read )\n vln-count off vln-pad off\n;\n\n: VLN.ACCUM ( byte -- accumulate another byte )\n $ 7F and\n vln-pad @ 7 shift or vln-pad !\n;\n\n\\ -------------------------------------------------\nvariable MF-BYTESLEFT\nvariable MF-EVENT-TIME\nvariable MF-#DATA\n\n: CHKID ( -- , define chkid )\n 32 lword count drop be@ constant\n;\n\nchkid MThd 'MThd'\nchkid MTrk 'MTrk'\n\nvariable mf-FILEID\n16 constant MF_PAD_SIZE\nvariable mf-PAD mf_pad_size allot\n\nDEFER MF.PROCESS.TRACK ( size track# -- )\nDEFER MF.ERROR\n\n' abort is mf.error\n\n: .CHKID ( 'chkid' -- , print chunk id )\n pad be! pad 4 type\n;\n\n: $MF.OPEN ( $filename -- )\n dup c@ 0=\n IF drop .\" $MF.OPEN - No filename given!\" cr mf.error\n THEN\n dup count r\/o bin open-file\n IF drop .\" Couldn't open file: \" $type cr mf.error\n THEN\n mf-fileid !\n drop\n;\n\n: $MF.CREATE ( $filename -- , create new file )\n dup c@ 0=\n IF drop .\" $MF.OPEN - No filename given!\" cr mf.error\n THEN\n dup count w\/o bin create-file\n IF drop .\" Couldn't create file: \" $type cr mf.error\n THEN\n mf-fileid !\n drop\n;\n: MF.SET.FILE ( fileid -- )\n mf-fileid !\n;\n\n: MF.READ ( addr #bytes -- #bytes , read from open mf file)\n dup negate mf-bytesleft +!\n mf-fileid @ read-file abort\" Could not read MIDI file.\"\n;\n\n: MF.READ.CHKID ( -- size chkid )\n dup>r mf-pad 8 mf.read\n 8 -\n IF .\" Truncated chunk \" r@ .chkid cr mf.error\n THEN\n rdrop\n mf-pad cell+ be@\n mf-pad be@\n;\n\n\n: MF.WRITE ( addr #bytes -- #bytes , write to open mf file)\n dup>r mf-fileid @ write-file abort\" Could not write MIDI file.\"\n r>\n;\n\n: MF.WRITE? ( addr #bytes -- , write to open mf file or mf.ERROR)\n mf-fileid @ write-file abort\" Could not write MIDI file.\"\n;\n\n: MF.READ.BYTE ( -- byte )\n mf-pad 1 mf.read 1-\n IF .\" MF.READ.BYTE - Unexpected EOF!\" cr mf.error\n THEN\n mf-pad c@\n;\n\n: MF.WRITE.BYTE ( byte -- )\n mf-pad c! mf-pad 1 mf.write?\n;\n\n: MF.WRITE.WORD ( 16word -- )\n mf-pad w! mf-pad 2 mf.write?\n;\n\n: MF.READ.WORD ( -- 16word )\n mf-pad 2 mf.read 2-\n IF .\" MF.READ.WORD - Unexpected EOF!\" cr mf.error\n THEN\n mf-pad w@\n;\n\n: MF.WRITE.CHKID ( size chkid -- , write chunk header )\n mf-pad be!\n mf-pad cell+ be!\n mf-pad 8 mf.write?\n;\n\n: MF.WRITE.CHUNK ( address size chkid -- , write complete chunk )\n over >r mf.write.chkid\n r> mf.write?\n;\n\n: MF.READ.TYPE ( -- typeid )\n mf-pad 4 mf.read\n 4 -\n IF .\" Truncated type!\" cr mf.error\n THEN\n mf-pad be@\n;\n\n: MF.WHERE ( -- current_pos , in file )\n mf-fileid @ file-position abort\" file-position failed\"\n d>s \\ file-position returns a double word\n;\n\n: MF.SEEK ( position -- , in file )\n s>d \\ reposition-file takes a double word\n mf-fileid @ reposition-file abort\" reposition-file failed\"\n;\n\n: MF.SKIP ( n -- , skip n bytes in file )\n dup negate mf-bytesleft +!\n mf.where + mf.seek\n;\n\n: MF.CLOSE\n mf-fileid @ ?dup\n IF close-file abort\" close-file failed\"\n 0 mf-fileid !\n THEN\n;\n\nvariable MF-NTRKS \\ number of tracks in file\nvariable MF-FORMAT \\ file format = 0 | 1 | 2\nvariable MF-DIVISION \\ packed division\n\n: MF.PROCESS.HEADER ( size -- )\n dup mf_pad_size >\n IF .\" MF.PROCESS.HEADER - Bad Header Size = \"\n dup . cr mf.error\n THEN\n mf-pad swap mf.read drop\n mf-pad bew@ mf-format w!\n mf-pad 2+ bew@ mf-ntrks !\n mf-pad 4+ bew@ mf-division !\n;\n\n: MF.SCAN.HEADER ( -- , read header )\n mf.read.chkid ( -- size chkid)\n 'MThd' =\n IF mf.process.header\n ELSE .\" MF.SCAN - Headerless MIDIFile!\" cr mf.error\n THEN\n;\n\n: MF.SCAN.TRACKS ( -- , read tracks )\n\\ This word leaves the file position just after the chunk data.\n mf-ntrks @ 0\n DO mf.read.chkid 'MTrk' =\n IF dup mf.where + >r\n i mf.process.track\n r> mf.seek ( move past chunk)\n ELSE .\" MF.SCAN - Unexpected CHKID!\" cr mf.error\n THEN\n LOOP\n;\n\n: MF.SCAN ( -- , read header then tracks)\n mf.scan.header\n mf.scan.tracks\n;\n\n: MF.VALIDATE ( -- ok? , make sure open file has header chunk )\n mf.where\n 0 mf.seek\n mf.read.type 'MThd' =\n swap mf.seek\n;\n\n: (MF.DOFILE) ( -- ,process current file )\n mf.validate\n IF mf.scan\n ELSE .\" Not a MIDIFile!\" cr\n mf.close mf.error\n THEN\n mf.close\n;\n\n: $MF.DOFILE ( $filename -- , process file using deferred words)\n $mf.open (mf.dofile)\n;\n\n: MF.DOFILE ( -- )\n fileword $mf.dofile\n;\n\n: MF.READ.VLN ( -- vln , read vln from file )\n vln.clear\n BEGIN mf.read.byte dup $ 80 and\n WHILE vln.accum\n REPEAT vln.accum\n vln-pad @\n;\n\ndefer MF.PROCESS.META ( size metaID -- , process Meta event )\ndefer MF.PROCESS.SYSEX\ndefer MF.PROCESS.ESCAPE\n\nvariable MF-SEQUENCE#\nvariable MF-CHANNEL\n: MF.LOOK.TEXT ( size metaID -- , read and show text )\n >newline .\" MetaEvent = \" . cr\n pad swap mf.read\n pad swap type cr\n;\n\n: MF.HANDLE.META ( size MetaID -- default Meta event handler )\n dup $ 01 $ 0f within?\n IF mf.look.text\n ELSE CASE\n $ 00 OF drop mf.read.word mf-sequence# ! ENDOF\n $ 20 OF drop mf.read.byte 1+ mf-channel ! ENDOF\n .\" MetaEvent = \" dup . cr\n swap mf.skip ( skip over other event types )\n ENDCASE\n THEN\n;\n\n' mf.handle.meta is MF.PROCESS.META\n' mf.skip is MF.PROCESS.SYSEX\n' mf.skip is MF.PROCESS.ESCAPE\n\n: MF.PARSE.EVENT ( -- , parse MIDI event )\n mf.read.byte dup $ 80 and ( is it a command or running status data )\n IF CASE\n $ FF OF mf.read.byte ( get type )\n mf.read.vln ( get size ) swap mf.process.meta ENDOF\n $ F0 OF .\" F0 byte\" cr mf.read.vln mf.process.sysex ENDOF\n $ F7 OF .\" F7 byte\" cr mf.read.vln mf.process.escape ENDOF\n\\ Regular command.\n dup mp.#bytes mf-#data !\n dup mp.handle.command\n mf-#data @ 0\n DO mf.read.byte mp.handle.data\n LOOP\n ENDCASE\n ELSE\n mp.handle.data ( call MIDI parser with byte read )\n mf-#data @ 1- 0 max 0\n DO mf.read.byte mp.handle.data\n LOOP\n THEN\n;\n\n: MF.PARSE.TRACK ( size track# -- )\n drop mf-bytesleft !\n 0 mf-event-time !\n BEGIN mf.read.vln mf-event-time +!\n mf.parse.event\n mf-bytesleft @ 1 <\n UNTIL\n;\n\n\\ Some Track Handlers\n: MF.PRINT.NOTEON ( note velocity -- )\n ?pause\n mf-event-time @ 4 .r .\" , \"\n .\" ON N,V = \" swap . . cr\n;\n: MF.PRINT.NOTEOFF ( note velocity -- )\n ?pause\n mf-event-time @ 4 .r .\" , \"\n .\" OFF N,V = \" swap . . cr\n;\n\n: MF.PRINT.TRACK ( size track# -- )\n 2dup\n >newline dup 0=\n IF .\" MIDIFile Format = \" mf-format @ . cr\n .\" Division = $\" mf-division @ dup .hex . cr\n THEN\n .\" Track# \" . .\" is \" . .\" bytes.\" cr\n 'c mf.print.noteon mp-on-vector !\n 'c mf.print.noteoff mp-off-vector !\n mf.parse.track\n mp.reset\n;\n\n' mf.print.track is mf.process.track\n\n: MF.CHECK ( -- , print chunks )\n what's mf.process.track\n ' mf.print.track is mf.process.track\n mf.dofile\n is mf.process.track\n;\n\n\\ Track Handler that loads a shape -----------------------\nvariable MF-TRACK-CHOSEN\nob.shape MF-SHAPE\n\n: MF.LOAD.NOTEON ( note velocity -- )\n mf-shape ensure.room\n mf-event-time @ -rot add: mf-shape\n;\n\n: MF.LOAD.NOTEOFF ( note velocity -- )\n mf-shape ensure.room\n drop mf-event-time @ swap 0 add: mf-shape\n;\n\n: MF.LOAD.TRACK ( size track# -- )\n max.elements: mf-shape 0=\n IF 64 3 new: mf-shape\n ELSE clear: mf-shape\n THEN\n 'c mf.load.noteon mp-on-vector !\n 'c mf.load.noteoff mp-off-vector !\n mf.parse.track\n;\n\n: MF.PICK.TRACK ( size track# -- )\n dup mf-track-chosen @ =\n IF mf.load.track\n ELSE 2drop\n THEN\n;\n\n: $MF.LOAD.SHAPE ( track# $filename -- , load track into mf-shape )\n swap mf-track-chosen !\n what's mf.process.track SWAP ( -- oldcfa $filename )\n 'c mf.pick.track is mf.process.track\n $mf.dofile\n is mf.process.track\n;\n\n: MF.LOAD.SHAPE ( track# -- , load track into mf-shape )\n fileword $mf.load.shape\n;\n\n: LOAD.ABS.SHAPE ( shape -- )\n 0 mf.load.shape\n clone: mf-shape\n free: mf-shape\n;\n\n\\ -------------------------------------------------\n\n\\ Tools for writing a MIDIFile.\n: MF.WRITE.HEADER ( format ntrks division -- )\n 6 'MThd' mf.write.chkid\n mf-pad 4+ bew! ( division )\n over 0=\n IF drop 1 ( force NTRKS to 1 for format zero )\n THEN\n mf-pad 2+ bew! ( ntrks )\n mf-pad bew! ( format )\n mf-pad 6 mf.write?\n;\n\n: MF.BEGIN.TRACK ( -- curpos , write track start )\n 0 'MTrk' mf.write.chkid\n mf.where\n 0 mf-event-time !\n;\n\n: MF.WRITE.VLN ( n -- , write variable length quantity )\n number->vln mf.write?\n;\n\n: MF.WRITE.TIME ( time -- , write time as vln delta )\n dup mf-event-time @ - mf.write.vln\n mf-event-time !\n;\n\n: MF.WRITE.EVENT ( addr count time -- , write MIDI event )\n\\ This might be called from custom MIDI.FLUSH\n mf.write.time\n mf.write?\n;\n\nvariable MF-EVENT-PAD\n\n: MF.WRITE.META ( addr count event-type -- )\n mf-event-time @ mf.write.time\n $ FF mf.write.byte\n mf.write.byte ( event type )\n dup mf.write.vln ( len )\n mf.write?\n;\n\n: MF.WRITE.SYSEX ( addr count -- )\n mf-event-time @ mf.write.time\n $ F0 mf.write.byte\n dup mf.write.vln ( len )\n mf.write?\n;\n\n: MF.WRITE.ESCAPE ( addr count -- )\n mf-event-time @ mf.write.time\n $ F7 mf.write.byte\n dup mf.write.vln ( len )\n mf.write?\n;\n\n: MF.WRITE.SEQ# ( seq# -- )\n mf-event-pad w!\n mf-event-pad 2 0 mf.write.meta\n;\n\n: MF.WRITE.END ( -- , write end of track )\n mf-event-pad 0\n $ 2F mf.write.meta\n;\n\n: MF.END.TRACK ( startpos -- , write length to track beginning )\n mf.where dup>r ( so we can return )\n over - ( -- start #bytes )\n swap cell- mf.seek\n mf-pad be! mf-pad 4 mf.write?\n r> mf.seek\n;\n\n: MF.CVM+2D ( time d1 d2 cvm -- )\n mf-event-pad c!\n mf-event-pad 2+ c!\n mf-event-pad 1+ c!\n mf-event-pad 3 rot mf.write.event\n;\n\n: MF.WRITE.NOTEON ( time note velocity -- )\n $ 90 mf.cvm+2d\n;\n\n: MF.WRITE.NOTEOFF ( time note velocity -- )\n $ 80 mf.cvm+2d\n;\n\n: $MF.BEGIN.FORMAT0 ( $name -- pos , begin format0 file )\n $mf.create\n 0 1 ticks\/beat @ mf.write.header\n mf.begin.track ( startpos )\n;\n\n: MF.BEGIN.FORMAT0 ( -- pos , begin format0 file )\n fileword $mf.begin.format0\n;\n\n: MF.END.FORMAT0 ( pos -- , end format0 file )\n mf.write.end\n mf.end.track\n mf.close\n;\n\n: MF.WRITE.ABS.SHAPE { shape -- , assume shape Nx3+ absolute time }\n\\ Assume separate note on\/off in shape\n shape reset: []\n shape many: [] 0\n DO i 0 shape ed.at: [] ( -- time )\n i 1 shape ed.at: [] ( -- time note )\n i 2 shape ed.at: [] ( -- time note vel )\n dup 0=\n IF mf.write.noteoff\n ELSE mf.write.noteon\n THEN\n LOOP\n;\n\nvariable MF-SHAPE-TIME\n\n: MF.WRITE.REL.SHAPE { shape | note vel -- , assume shape Nx3 relative time }\n 0 mf-shape-time !\n shape reset: []\n shape many: [] 0\n DO\n i 1 shape ed.at: [] -> note ( -- time note )\n i 2 shape ed.at: [] -> vel ( -- time note vel )\n mf-shape-time @ note vel mf.write.noteon\n\\\n\\ add to shape time so OFF occurs right before next notes ON 00002\n i 0 shape ed.at: [] ( -- reltime )\n mf-shape-time @ +\n dup mf-shape-time !\n note vel mf.write.noteoff\n LOOP\n;\n\n: $SAVE.REL.SHAPE ( shape $filename -- , complete file output )\n\\ This word writes out a relative time, 1 event\/note shape\n\\ as note on,off\n $mf.begin.format0\n swap mf.write.rel.shape\n mf.end.format0\n;\n\n: $SAVE.ABS.SHAPE ( shape $filename -- , complete file output )\n\\ This word writes out a shape as note on,off\n $mf.begin.format0\n swap mf.write.abs.shape\n mf.end.format0\n;\n\n: SAVE.REL.SHAPE ( shape -- , complete file output )\n fileword $save.rel.shape\n;\n\n: SAVE.ABS.SHAPE ( shape -- , complete file output )\n fileword $save.abs.shape\n;\n\n: MF.WRITE.TIMESIG ( nn dd cc bb -- )\n mf-event-pad 3 + c! ( time sig, numerator )\n mf-event-pad 2+ c! ( denom log2 )\n mf-event-pad 1+ c! ( MIDI clocks\/metronome click )\n mf-event-pad c! ( 32nd notes in 24 clocks )\n mf-event-pad 4 $ 58 mf.write.meta\n;\n\n: MF.WRITE.TEMPO ( mics\/beat -- )\n mf-event-pad !\n mf-event-pad 1+ 3 $ 51 mf.write.meta\n;\n\n\\ Capture all MIDI output to a Format0 file\nvariable MF-START-POS\nvariable MF-FIRST-WRITE\n\n: (MF.CAPTURED>FILE0) ( -- write captured MIDI to file format 0)\n 0 0 ed.at: captured-midi mf-event-time !\n many: captured-midi 0\n DO i get: captured-midi midi.unpack\n rot mf.write.event\n LOOP\n mf-start-pos @ mf.end.format0\n;\n\n: }MIDIFILE0 ( -- )\n if-capturing @\n IF (mf.captured>file0)\n }capture\n THEN\n;\n\n: $CAPTURED>MIDIFILE0 ( $filename -- )\n $mf.begin.format0 mf-start-pos ! ( use filename while still valid )\n (mf.captured>file0)\n;\n\n: $MIDIFILE0{ ( $filename -- , start capturing MIDI data )\n }midifile0\n $mf.begin.format0 mf-start-pos ! ( use filename while still valid )\n capture{\n;\n\n: MIDIFILE0{ ( -- )\n fileword $midifile0{\n;\n\nCREATE MF-COUNT-CAPS 16 allot\n\n: CAP.GET.CHAN ( status-byte -- channel# )\n $ 0F and 1+\n;\n\n: CAP.COUNT.CHANS ( -- #channels , count captured track\/channels )\n 16 0\n DO 0 i mf-count-caps + c!\n LOOP\n\\\n many: captured-midi 0\n DO i get: captured-midi midi.unpack drop c@\n cap.get.chan 1-\n nip\n mf-count-caps + 1 swap c! ( set flag in array )\n LOOP\n\\\n 0\n 16 0\n DO i mf-count-caps + c@ +\n LOOP\n;\n\n: (MF.CAPTURED>FILE1) ( -- , write tracks with data to metafile )\n cap.count.chans ( #chans )\n \\ write a track zero that should contain tempo maps\n 1+ \\ for track zero\n mf.begin.track ( -- pos )\n mf.write.end\n mf.end.track\n \\ Write each track with sequence number\n 16 0\n DO i mf-count-caps + c@\n IF\n mf.begin.track ( -- pos )\n 0 0 ed.at: captured-midi mf-event-time !\n i 1+ mf.write.seq#\n many: captured-midi 0\n DO\n i get: captured-midi midi.unpack\n over c@ cap.get.chan 1- j = \\ 00001\n IF\n ( time addr count -- )\n rot mf.write.event\n ELSE 2drop drop\n THEN\n LOOP\n mf.write.end\n mf.end.track\n THEN\n LOOP\n 0 mf.seek\n 1 swap ticks\/beat @ mf.write.header\n mf.close\n;\n\n: }MIDIFILE1 ( -- )\n if-capturing @\n IF (mf.captured>file1)\n }capture\n THEN\n;\n\n: $CAPTURED>MIDIFILE1 ( $filename -- )\n $mf.create\n 1 1 ticks\/beat @ mf.write.header\n (mf.captured>file1)\n;\n\n: $MIDIFILE1{ ( $filename -- , start capturing MIDI data )\n }midifile1\n $mf.create\n 1 1 ticks\/beat @ mf.write.header\n capture{\n;\n\n: MIDIFILE1{ ( -- )\n fileword $midifile1{\n;\n\n\\ set aliases to format 0 for compatibility with old code\n: MIDIFILE{ midifile0{ ;\n: $MIDIFILE{ $midifile0{ ;\n: }MIDIFILE }midifile0 ;\n\nif.forgotten }midifile0\n\n\n: tmf\n \" testzz5.mid\" $midifile0{\n rnow 55 60 midi.noteon\n 200 vtime+!\n 55 0 midi.noteoff\n }midifile0\n;\n\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Forth"} {"commit":"aabe3729fee4f3fb330a71a30b9d1439b037b6d1","subject":"Add ?DO word","message":"Add ?DO word\n","repos":"rm-hull\/byok3,rm-hull\/byok3","old_file":"src\/main\/resources\/forth\/system.fth","new_file":"src\/main\/resources\/forth\/system.fth","new_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\\n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n\n: COUNT dup 1+ swap c@ ;\n\n\\ Miscellaneous support words\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: CELL+ ( n -- n+cell ) cell + ;\n: CELL- ( n -- n-cell ) cell - ;\n: CELL* ( n -- n*cell ) cells ;\n\n: CHAR+ ( n -- n+size_of_char ) 1+ ;\n\\ : CHARS ( n -- n*size_of_char, don't do anything ) ; immediate\n\n\\ useful stack manipulation words\n: -ROT ( a b c -- c a b ) rot rot ;\n: 3DUP ( a b c -- a b c a b c ) 2 pick 2 pick 2 pick ;\n\n\\ ------------------------------------------------------------------\n: ID. ( nfa -- ) count 31 and type ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: PAD ( -- addr ) here 128 + ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: ? ( -- ) @ . ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ ' (lit) , cell 1- , ] +\n [ ' (lit) , cell 1- invert , ] and ;\n\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n: ALLOT ( nbytes -- , allot space in dictionary ) dp +! align ;\n\n: C, ( c -- ) here c! 1 dp +! ;\n\\ : W, ( w -- ) dp @ even-up dup dp ! w! 2 dp +! ;\n\\ : , ( n -- , lay into dictionary ) align here ! cell allot ;\n\n: SEE ( -- )\n ' dup\n 16 + @ \\ offset in execution token for alloc size\n cells swap >body swap\n disassemble ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token )\n [compile] literal ( compile a call to literal )\n ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n: :NONAME ( -- xt , begin compilation of headerless secondary ) align here ] ;\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick )\n ?comp ' [compile] literal\n; immediate\n\n: RECURSE ( ? -- ? , call the word currently being defined )\n latest compile,\n; immediate\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 ) swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 ) dup cell+ @ swap @ ;\n\n: \/STRING ( addr len n -- addr' len' ) over min rot over + -rot - ;\n: PLACE ( addr len to -- , move string ) 3dup 1+ swap cmove c! drop ;\n\n: ASCII ( -- char, state smart )\n bl parse drop c@\n state @ 1 =\n IF [compile] literal\n ELSE\n THEN\n; immediate\n\n: CHAR ( -- char , interpret mode ) bl parse drop c@ ;\n: [CHAR] ( -- char , for compile mode )\n char [compile] literal\n; immediate\n\n: 'word ( -- addr ) here ;\n\n: (C\") ( -- $addr ) r> dup count + aligned >r ;\n: (S\") ( -- c-addr cnt ) r> count 2dup + aligned >r ;\n: (.\") ( -- , type following string ) r> count 2dup + aligned >r type ;\n: \", ( addr len -- , place string into dict ) tuck 'word place 1+ allot align ;\n: ,\" ( -- ) 34 parse \", ;\n\n: .( ( --, type string delimited by parens )\n 41 parse type\n; immediate\n\n: .\" ( -- , type string )\n state @ 1 =\n IF compile (.\") ,\"\n ELSE 34 parse type\n THEN\n; immediate\n\n: CLEARSTACK ( i*x -- )\n BEGIN depth\n WHILE drop\n REPEAT ;\n\nvariable pictured_output \\ hidden?\nvariable pictured_output_len \\ hidden?\n\n: <# ( -- ) pad pictured_output ! 0 pictured_output_len ! ;\n: #> ( -- addr n ) drop pictured_output @ pictured_output_len @ ;\n\n: HOLD ( c -- )\n pictured_output @ dup dup 1+ pictured_output_len @ cmove c!\n 1 pictured_output_len +!\n;\n\n: DIGIT ( n -- ascii )\n dup 10 < IF 48 ELSE 87 THEN + ;\n\n: SIGN ( n -- ) < 0 IF 45 hold THEN\n;\n: # ( n -- n )\n base @ \/mod swap digit hold ;\n\n: #S ( n -- )\n BEGIN base @ \/mod dup\n WHILE swap digit hold\n REPEAT\n digit hold ;\n\n: (DOES>) ( xt -- , modify previous definition to execute code at xt )\n latest >body \\ get address of code for new word\n cell + \\ offset to second cell in create word\n ! \\ store execution token of DOES> code in new word\n;\n\n: DOES> ( -- , define execution code for CREATE word )\n 0 [compile] literal \\ dummy literal to hold xt\n here cell- \\ address of zero in literal\n compile (does>) \\ call (DOES>) from new creation word\n\t\t>r \\ move addrz to return stack so ; doesn't see stack garbage\n [compile] ; \\ terminate part of code before does>\n\t\tr>\n :noname ( addrz xt )\n swap ! \\ save execution token in literal\n; immediate\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 )\n swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 )\n dup cell+ @ swap @ ;\n\n\n\\ Stack data structure ----------------------------------------\n\\ This is a general purpose stack utility used to implement necessary\n\\ stacks for the compiler or the user. Not real fast.\n\\ These stacks grow up which is different then normal.\n\\ cell 0 - stack pointer, offset from pfa of word\n\\ cell 1 - limit for range checking\n\\ cell 2 - first data location\n\n: :STACK ( #cells -- )\n CREATE 2 cells , ( offset of first data location )\n dup , ( limit for range checking, not currently used )\n cells cell+ allot ( allot an extra cell for safety )\n;\n\n: >STACK ( n stack -- , push onto stack, postincrement )\n dup @ 2dup cell+ swap ! ( -- n stack offset )\n + !\n;\n\n: STACK> ( stack -- n , pop , predecrement )\n dup @ cell- 2dup swap !\n + @\n;\n\n: STACK@ ( stack -- n , copy )\n dup @ cell- + @\n;\n\n: STACK.PICK ( index stack -- n , grab Nth from top of stack )\n dup @ cell- +\n swap cells - \\ offset for index\n @\n;\n: STACKP ( stack -- ptr , to next empty location on stack )\n\tdup @ +\n;\n\n: 0STACKP ( stack -- , clear stack)\n 8 swap !\n;\n\n32 :stack ustack\nustack 0stackp\n\n\\ Define JForth like words.\n: >US ustack >stack ;\n: US> ustack stack> ;\n: US@ ustack stack@ ;\n: 0USP ustack 0stackp ;\n\n\n\n\\ DO LOOP ------------------------------------------------\n\n3 constant do_flag\n4 constant leave_flag\n5 constant ?do_flag\n\n: DO ( -- , loop-back do_flag jump-from ?do_flag )\n ?comp\n compile (do)\n here >us do_flag >us ( for backward branch )\n; immediate\n\n: ?DO ( -- , loop-back do_flag jump-from ?do_flag , on user stack )\n ?comp\n ( leave address to set for forward branch )\n compile (?do)\n here 0 ,\n here >us do_flag >us ( for backward branch )\n >us ( for forward branch ) ?do_flag >us\n; immediate\n\n: LEAVE ( -- addr leave_flag )\n compile (leave)\n here 0 , >us\n leave_flag >us\n; immediate\n\n: LOOP-FORWARD ( -us- jump-from ?do_flag -- )\n BEGIN\n us@ leave_flag =\n us@ ?do_flag =\n OR\n WHILE\n us> leave_flag =\n IF\n us> here over - cell+ swap !\n ELSE\n us> dup\n here swap -\n cell+ swap !\n THEN\n REPEAT\n;\n\n: LOOP-BACK ( loop-addr do_flag -us- )\n us> do_flag ?pairs\n us> here - here\n !\n cell allot\n;\n\n: LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (loop)\n loop-forward loop-back\n; immediate\n\n\\ : DOTEST 5 0 do 333 . loop 888 . ;\n\\ : ?DOTEST0 0 0 ?do 333 . loop 888 . ;\n\\ : ?DOTEST1 5 0 ?do 333 . loop 888 . ;\n\n: +LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (+loop)\n loop-forward loop-back\n; immediate\n\n: UNLOOP ( loop-sys -r- )\n r> \\ save return pointer\n rdrop rdrop\n >r\n;","old_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\\n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n\n: COUNT dup 1+ swap c@ ;\n\n\\ Miscellaneous support words\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: CELL+ ( n -- n+cell ) cell + ;\n: CELL- ( n -- n-cell ) cell - ;\n: CELL* ( n -- n*cell ) cells ;\n\n: CHAR+ ( n -- n+size_of_char ) 1+ ;\n\\ : CHARS ( n -- n*size_of_char, don't do anything ) ; immediate\n\n\\ useful stack manipulation words\n: -ROT ( a b c -- c a b ) rot rot ;\n: 3DUP ( a b c -- a b c a b c ) 2 pick 2 pick 2 pick ;\n\n\\ ------------------------------------------------------------------\n: ID. ( nfa -- ) count 31 and type ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: PAD ( -- addr ) here 128 + ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: ? ( -- ) @ . ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ ' (lit) , cell 1- , ] +\n [ ' (lit) , cell 1- invert , ] and ;\n\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n: ALLOT ( nbytes -- , allot space in dictionary ) dp +! align ;\n\n: C, ( c -- ) here c! 1 dp +! ;\n\\ : W, ( w -- ) dp @ even-up dup dp ! w! 2 dp +! ;\n\\ : , ( n -- , lay into dictionary ) align here ! cell allot ;\n\n: SEE ( -- )\n ' dup\n 16 + @ \\ offset in execution token for alloc size\n cells swap >body swap\n disassemble ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token )\n [compile] literal ( compile a call to literal )\n ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n: :NONAME ( -- xt , begin compilation of headerless secondary ) align here ] ;\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick )\n ?comp ' [compile] literal\n; immediate\n\n: RECURSE ( ? -- ? , call the word currently being defined )\n latest compile,\n; immediate\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 ) swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 ) dup cell+ @ swap @ ;\n\n: \/STRING ( addr len n -- addr' len' ) over min rot over + -rot - ;\n: PLACE ( addr len to -- , move string ) 3dup 1+ swap cmove c! drop ;\n\n: ASCII ( -- char, state smart )\n bl parse drop c@\n state @ 1 =\n IF [compile] literal\n ELSE\n THEN\n; immediate\n\n: CHAR ( -- char , interpret mode ) bl parse drop c@ ;\n: [CHAR] ( -- char , for compile mode )\n char [compile] literal\n; immediate\n\n: 'word ( -- addr ) here ;\n\n: (C\") ( -- $addr ) r> dup count + aligned >r ;\n: (S\") ( -- c-addr cnt ) r> count 2dup + aligned >r ;\n: (.\") ( -- , type following string ) r> count 2dup + aligned >r type ;\n: \", ( addr len -- , place string into dict ) tuck 'word place 1+ allot align ;\n: ,\" ( -- ) 34 parse \", ;\n\n: .( ( --, type string delimited by parens )\n 41 parse type\n; immediate\n\n: .\" ( -- , type string )\n state @ 1 =\n IF compile (.\") ,\"\n ELSE 34 parse type\n THEN\n; immediate\n\n: CLEARSTACK ( i*x -- )\n BEGIN depth\n WHILE drop\n REPEAT ;\n\nvariable pictured_output \\ hidden?\nvariable pictured_output_len \\ hidden?\n\n: <# ( -- ) pad pictured_output ! 0 pictured_output_len ! ;\n: #> ( -- addr n ) drop pictured_output @ pictured_output_len @ ;\n\n: HOLD ( c -- )\n pictured_output @ dup dup 1+ pictured_output_len @ cmove c!\n 1 pictured_output_len +!\n;\n\n: DIGIT ( n -- ascii )\n dup 10 < IF 48 ELSE 87 THEN + ;\n\n: SIGN ( n -- ) < 0 IF 45 hold THEN\n;\n: # ( n -- n )\n base @ \/mod swap digit hold ;\n\n: #S ( n -- )\n BEGIN base @ \/mod dup\n WHILE swap digit hold\n REPEAT\n digit hold ;\n\n: (DOES>) ( xt -- , modify previous definition to execute code at xt )\n latest >body \\ get address of code for new word\n cell + \\ offset to second cell in create word\n ! \\ store execution token of DOES> code in new word\n;\n\n: DOES> ( -- , define execution code for CREATE word )\n 0 [compile] literal \\ dummy literal to hold xt\n here cell- \\ address of zero in literal\n compile (does>) \\ call (DOES>) from new creation word\n\t\t>r \\ move addrz to return stack so ; doesn't see stack garbage\n [compile] ; \\ terminate part of code before does>\n\t\tr>\n :noname ( addrz xt )\n swap ! \\ save execution token in literal\n; immediate\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 )\n swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 )\n dup cell+ @ swap @ ;\n\n\n\\ Stack data structure ----------------------------------------\n\\ This is a general purpose stack utility used to implement necessary\n\\ stacks for the compiler or the user. Not real fast.\n\\ These stacks grow up which is different then normal.\n\\ cell 0 - stack pointer, offset from pfa of word\n\\ cell 1 - limit for range checking\n\\ cell 2 - first data location\n\n: :STACK ( #cells -- )\n CREATE 2 cells , ( offset of first data location )\n dup , ( limit for range checking, not currently used )\n cells cell+ allot ( allot an extra cell for safety )\n;\n\n: >STACK ( n stack -- , push onto stack, postincrement )\n dup @ 2dup cell+ swap ! ( -- n stack offset )\n + !\n;\n\n: STACK> ( stack -- n , pop , predecrement )\n dup @ cell- 2dup swap !\n + @\n;\n\n: STACK@ ( stack -- n , copy )\n dup @ cell- + @\n;\n\n: STACK.PICK ( index stack -- n , grab Nth from top of stack )\n dup @ cell- +\n swap cells - \\ offset for index\n @\n;\n: STACKP ( stack -- ptr , to next empty location on stack )\n\tdup @ +\n;\n\n: 0STACKP ( stack -- , clear stack)\n 8 swap !\n;\n\n32 :stack ustack\nustack 0stackp\n\n\\ Define JForth like words.\n: >US ustack >stack ;\n: US> ustack stack> ;\n: US@ ustack stack@ ;\n: 0USP ustack 0stackp ;\n\n\n\n\\ DO LOOP ------------------------------------------------\n\n3 constant do_flag\n4 constant leave_flag\n5 constant ?do_flag\n\n: DO ( -- , loop-back do_flag jump-from ?do_flag )\n ?comp\n compile (do)\n here >us do_flag >us ( for backward branch )\n; immediate\n\n\\ : ?DO ( -- , loop-back do_flag jump-from ?do_flag , on user stack )\n\\ ?comp\n\\ ( leave address to set for forward branch )\n\\ compile (?do)\n\\ here 0 ,\n\\ here >us do_flag >us ( for backward branch )\n\\ >us ( for forward branch ) ?do_flag >us\n\\ ; immediate\n\n: LEAVE ( -- addr leave_flag )\n compile (leave)\n here 0 , >us\n leave_flag >us\n; immediate\n\n: LOOP-FORWARD ( -us- jump-from ?do_flag -- )\n BEGIN\n us@ leave_flag =\n us@ ?do_flag =\n OR\n WHILE\n us> leave_flag =\n IF\n us> here over - cell+ swap !\n ELSE\n us> dup\n here swap -\n cell+ swap !\n THEN\n REPEAT\n;\n\n: LOOP-BACK ( loop-addr do_flag -us- )\n us> do_flag ?pairs\n us> here - here\n !\n cell allot\n;\n\n: LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (loop)\n loop-forward loop-back\n; immediate\n\n\\ : DOTEST 5 0 do 333 . loop 888 . ;\n\\ : ?DOTEST0 0 0 ?do 333 . loop 888 . ;\n\\ : ?DOTEST1 5 0 ?do 333 . loop 888 . ;\n\n: +LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (+loop)\n loop-forward loop-back\n; immediate\n\n: UNLOOP ( loop-sys -r- )\n r> \\ save return pointer\n rdrop rdrop\n >r\n;","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"c204df87e440fb0a9d1bd9790772dd229730b0be","subject":"ignore garbage from serial","message":"ignore garbage from serial\n","repos":"nas4free\/nas4free,nas4free\/nas4free,nas4free\/nas4free,nas4free\/nas4free,nas4free\/nas4free,nas4free\/nas4free,nas4free\/nas4free","old_file":"boot\/menu.4th","new_file":"boot\/menu.4th","new_contents":"marker task-menu.4th\n\ninclude \/boot\/screen.4th\ninclude \/boot\/frames.4th\n\nhide\n\nvariable menuidx\nvariable menubllt\nvariable menuX\nvariable menuY\nvariable promptwidth\n\nvariable bootkey\nvariable bootacpikey\nvariable bootsafekey\nvariable bootverbosekey\nvariable escapekey\nvariable rebootkey\n\n46 constant dot\n\n\\ The logo. It can be 19 rows high and 34 columns wide.\n: display-logo ( x y -- )\n2dup at-xy .\" \" 1+\n2dup at-xy .\" \" 1+\n2dup at-xy .\" \" 1+\n2dup at-xy .\" \" 1+\n2dup at-xy .\" \" 1+\n2dup at-xy .\" \" 1+\n2dup at-xy .\" \" 1+\n2dup at-xy .\" \" 1+\n2dup at-xy .\" \" 1+\n2dup at-xy .\" \" 1+\n2dup at-xy .\" \" 1+\n2dup at-xy .\" \" 1+\n2dup at-xy .\" \" 1+\n2dup at-xy .\" \" 1+\n2dup at-xy .\" \" 1+\n2dup at-xy .\" \" 1+\n2dup at-xy .\" \" 1+\n2dup at-xy .\" \" 1+\nat-xy .\" \"\n;\n\nvariable vmguest\n: set-vmguest ( -- )\n\t0 vmguest !\n\ts\" smbios.system.product\" getenv dup -1 <> if\n\t\t2dup s\" VMware Virtual Platform\" compare 0= if\n\t\t\t1 vmguest !\n\t\tthen\n\t\t2dup s\" VirtualBox\" compare 0= if\n\t\t\t1 vmguest !\n\t\tthen\n\t\t2dup s\" Virtual Machine\" compare 0= if\n\t\t\ts\" smbios.system.maker\" getenv dup -1 <> if\n\t\t\t\ts\" Microsoft Corporation\" compare 0= if\n\t\t\t\t\t1 vmguest !\n\t\t\t\tthen\n\t\t\telse\n\t\t\t\tdrop\n\t\t\tthen\n\t\tthen\n\t\t2drop\n\telse\n\t\tdrop\n\tthen\n\tvmguest @ 0 <> if\n\t\ts\" 1\" s\" nas4free.vmguest\" setenv\n\t\ts\" kern.hz\" getenv dup -1 <> if\n\t\t\t?number if\n\t\t\t\t100 > if\n\t\t\t\t\ts\" 100\" s\" kern.hz\" setenv\n\t\t\t\tthen\n\t\t\tthen\n\t\telse\n\t\t\tdrop\n\t\t\ts\" 100\" s\" kern.hz\" setenv\n\t\tthen\n\telse\n\t\ts\" 0\" s\" nas4free.vmguest\" setenv\n\tthen\n;\n\n: acpienabled? ( -- flag )\n\ts\" acpi_load\" getenv\n\tdup -1 = if\n\t\tdrop false exit\n\tthen\n\ts\" YES\" compare-insensitive 0<> if\n\t\tfalse exit\n\tthen\n\ts\" hint.acpi.0.disabled\" getenv\n\tdup -1 <> if\n\t\ts\" 0\" compare 0<> if\n\t\t\tfalse exit\n\t\tthen\n\telse\n\t\tdrop\n\tthen\n\ttrue\n;\n\n: printmenuitem ( -- n )\n\tmenuidx @\n\t1+ dup\n\tmenuidx !\n\tmenuY @ + dup menuX @ swap at-xy\n\tmenuidx @ .\n\tmenuX @ 1+ swap at-xy\n\tmenubllt @ emit\n\tmenuidx @ 48 +\n;\n\n: display-menu ( -- )\n\t0 menuidx !\n\tdot menubllt !\n\t8 menuY !\n\t5 menuX !\n\tclear\n\t77 20 2 2 box\n\t45 3 display-logo\n\t5 7 at-xy .\" Welcome to NAS4Free!\"\n\tprintmenuitem .\" Boot NAS4Free in Normal Mode\" bootkey !\n\ts\" arch-i386\" environment? if\n\t\tdrop\n\t\tprintmenuitem .\" Boot NAS4Free with ACPI \" bootacpikey !\n\t\tacpienabled? if\n\t\t\t.\" disabled\"\n\t\telse\n\t\t\t.\" enabled\"\n\t\tthen\n\telse\n\t\t-2 bootacpikey !\n\tthen\n\tprintmenuitem .\" Boot NAS4Free in Safe Mode\" bootsafekey !\n\tprintmenuitem .\" Boot NAS4Free with verbose logging\" bootverbosekey !\n\tprintmenuitem .\" Escape to loader prompt\" escapekey !\n\tprintmenuitem .\" Reboot system\" rebootkey !\n\tmenuX @ 20 at-xy\n\t.\" Select option, [Enter] for default\"\n\tmenuX @ 21 at-xy\n\ts\" or [Space] to pause timer \" dup 2 - promptwidth !\n\ttype\n;\n\n: tkey\n\tseconds +\n\tbegin 1 while\n\t\tover 0<> if\n\t\t\tdup seconds u< if\n\t\t\t\tdrop\n\t\t\t\t-1\n\t\t\t\texit\n\t\t\tthen\n\t\t\tmenuX @ promptwidth @ + 21 at-xy dup seconds - .\n\t\tthen\n\t\tkey? if\n\t\t\tdrop\n\t\t\tkey\n\t\t\texit\n\t\tthen\n\t50 ms\n\trepeat\n;\n\nset-current\nset-vmguest\n\n: menu-start\n\ts\" menu_disable\" getenv\n\tdup -1 <> if\n\t\ts\" YES\" compare-insensitive 0= if\n\t\t\texit\n\t\tthen\n\telse\n\t\tdrop\n\tthen\n\tdisplay-menu\n\ts\" autoboot_delay\" getenv\n\tdup -1 = if\n\t\tdrop\n\t\t10\n\telse\n\t\t0 0 2swap >number drop drop drop\n\tthen\n\tbegin\n\t\tdup tkey\n\t\t0 25 at-xy\n\t\tdup 32 = if nip 0 swap then\n\t\tdup -1 = if 0 boot then\n\t\tdup 13 = if 0 boot then\n\t\tdup 255 = if 0 boot then\n\t\tdup bootkey @ = if 0 boot then\n\t\tdup bootacpikey @ = if\n\t\t\tacpienabled? if\n\t\t\t\ts\" acpi_load\" unsetenv\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\telse\n\t\t\t\ts\" YES\" s\" acpi_load\" setenv\n\t\t\t\ts\" 0\" s\" hint.acpi.0.disabled\" setenv\n\t\t\tthen\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootsafekey @ = if\n\t\t\ts\" arch-i386\" environment? if\n\t\t\t\tdrop\n\t\t\t\ts\" acpi_load\" unsetenv\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\t\ts\" 1\" s\" hint.apic.0.disabled\" setenv\n\t\t\tthen\n\t\t\ts\" 0\" s\" hw.ata.ata_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.atapi_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.wc\" setenv\n\t\t\ts\" 0\" s\" hw.eisa_slots\" setenv\n\t\t\ts\" 1\" s\" hint.kbdmux.0.disabled\" setenv\n\t\t\ts\" 1\" s\" hint.est.0.disabled\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootverbosekey @ = if\n\t\t\ts\" YES\" s\" boot_verbose\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup escapekey @ = if\n\t\t\t2drop\n\t\t\ts\" NO\" s\" autoboot_delay\" setenv\n\t\t\texit\n\t\tthen\n\t\trebootkey @ = if 0 reboot then\n\tagain\n;\n\nprevious\n","old_contents":"marker task-menu.4th\n\ninclude \/boot\/screen.4th\ninclude \/boot\/frames.4th\n\nhide\n\nvariable menuidx\nvariable menubllt\nvariable menuX\nvariable menuY\nvariable promptwidth\n\nvariable bootkey\nvariable bootacpikey\nvariable bootsafekey\nvariable bootverbosekey\nvariable escapekey\nvariable rebootkey\n\n46 constant dot\n\n\\ The logo. It can be 19 rows high and 34 columns wide.\n: display-logo ( x y -- )\n2dup at-xy .\" \" 1+\n2dup at-xy .\" \" 1+\n2dup at-xy .\" \" 1+\n2dup at-xy .\" \" 1+\n2dup at-xy .\" \" 1+\n2dup at-xy .\" \" 1+\n2dup at-xy .\" \" 1+\n2dup at-xy .\" \" 1+\n2dup at-xy .\" \" 1+\n2dup at-xy .\" \" 1+\n2dup at-xy .\" \" 1+\n2dup at-xy .\" \" 1+\n2dup at-xy .\" \" 1+\n2dup at-xy .\" \" 1+\n2dup at-xy .\" \" 1+\n2dup at-xy .\" \" 1+\n2dup at-xy .\" \" 1+\n2dup at-xy .\" \" 1+\nat-xy .\" \"\n;\n\nvariable vmguest\n: set-vmguest ( -- )\n\t0 vmguest !\n\ts\" smbios.system.product\" getenv dup -1 <> if\n\t\t2dup s\" VMware Virtual Platform\" compare 0= if\n\t\t\t1 vmguest !\n\t\tthen\n\t\t2dup s\" VirtualBox\" compare 0= if\n\t\t\t1 vmguest !\n\t\tthen\n\t\t2dup s\" Virtual Machine\" compare 0= if\n\t\t\ts\" smbios.system.maker\" getenv dup -1 <> if\n\t\t\t\ts\" Microsoft Corporation\" compare 0= if\n\t\t\t\t\t1 vmguest !\n\t\t\t\tthen\n\t\t\telse\n\t\t\t\tdrop\n\t\t\tthen\n\t\tthen\n\t\t2drop\n\telse\n\t\tdrop\n\tthen\n\tvmguest @ 0 <> if\n\t\ts\" 1\" s\" nas4free.vmguest\" setenv\n\t\ts\" kern.hz\" getenv dup -1 <> if\n\t\t\t?number if\n\t\t\t\t100 > if\n\t\t\t\t\ts\" 100\" s\" kern.hz\" setenv\n\t\t\t\tthen\n\t\t\tthen\n\t\telse\n\t\t\tdrop\n\t\t\ts\" 100\" s\" kern.hz\" setenv\n\t\tthen\n\telse\n\t\ts\" 0\" s\" nas4free.vmguest\" setenv\n\tthen\n;\n\n: acpienabled? ( -- flag )\n\ts\" acpi_load\" getenv\n\tdup -1 = if\n\t\tdrop false exit\n\tthen\n\ts\" YES\" compare-insensitive 0<> if\n\t\tfalse exit\n\tthen\n\ts\" hint.acpi.0.disabled\" getenv\n\tdup -1 <> if\n\t\ts\" 0\" compare 0<> if\n\t\t\tfalse exit\n\t\tthen\n\telse\n\t\tdrop\n\tthen\n\ttrue\n;\n\n: printmenuitem ( -- n )\n\tmenuidx @\n\t1+ dup\n\tmenuidx !\n\tmenuY @ + dup menuX @ swap at-xy\n\tmenuidx @ .\n\tmenuX @ 1+ swap at-xy\n\tmenubllt @ emit\n\tmenuidx @ 48 +\n;\n\n: display-menu ( -- )\n\t0 menuidx !\n\tdot menubllt !\n\t8 menuY !\n\t5 menuX !\n\tclear\n\t77 20 2 2 box\n\t45 3 display-logo\n\t5 7 at-xy .\" Welcome to NAS4Free!\"\n\tprintmenuitem .\" Boot NAS4Free in Normal Mode\" bootkey !\n\ts\" arch-i386\" environment? if\n\t\tdrop\n\t\tprintmenuitem .\" Boot NAS4Free with ACPI \" bootacpikey !\n\t\tacpienabled? if\n\t\t\t.\" disabled\"\n\t\telse\n\t\t\t.\" enabled\"\n\t\tthen\n\telse\n\t\t-2 bootacpikey !\n\tthen\n\tprintmenuitem .\" Boot NAS4Free in Safe Mode\" bootsafekey !\n\tprintmenuitem .\" Boot NAS4Free with verbose logging\" bootverbosekey !\n\tprintmenuitem .\" Escape to loader prompt\" escapekey !\n\tprintmenuitem .\" Reboot system\" rebootkey !\n\tmenuX @ 20 at-xy\n\t.\" Select option, [Enter] for default\"\n\tmenuX @ 21 at-xy\n\ts\" or [Space] to pause timer \" dup 2 - promptwidth !\n\ttype\n;\n\n: tkey\n\tseconds +\n\tbegin 1 while\n\t\tover 0<> if\n\t\t\tdup seconds u< if\n\t\t\t\tdrop\n\t\t\t\t-1\n\t\t\t\texit\n\t\t\tthen\n\t\t\tmenuX @ promptwidth @ + 21 at-xy dup seconds - .\n\t\tthen\n\t\tkey? if\n\t\t\tdrop\n\t\t\tkey\n\t\t\texit\n\t\tthen\n\t50 ms\n\trepeat\n;\n\nset-current\nset-vmguest\n\n: menu-start\n\ts\" menu_disable\" getenv\n\tdup -1 <> if\n\t\ts\" YES\" compare-insensitive 0= if\n\t\t\texit\n\t\tthen\n\telse\n\t\tdrop\n\tthen\n\tdisplay-menu\n\ts\" autoboot_delay\" getenv\n\tdup -1 = if\n\t\tdrop\n\t\t10\n\telse\n\t\t0 0 2swap >number drop drop drop\n\tthen\n\tbegin\n\t\tdup tkey\n\t\t0 25 at-xy\n\t\tdup 32 = if nip 0 swap then\n\t\tdup -1 = if 0 boot then\n\t\tdup 13 = if 0 boot then\n\t\tdup bootkey @ = if 0 boot then\n\t\tdup bootacpikey @ = if\n\t\t\tacpienabled? if\n\t\t\t\ts\" acpi_load\" unsetenv\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\telse\n\t\t\t\ts\" YES\" s\" acpi_load\" setenv\n\t\t\t\ts\" 0\" s\" hint.acpi.0.disabled\" setenv\n\t\t\tthen\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootsafekey @ = if\n\t\t\ts\" arch-i386\" environment? if\n\t\t\t\tdrop\n\t\t\t\ts\" acpi_load\" unsetenv\n\t\t\t\ts\" 1\" s\" hint.acpi.0.disabled\" setenv\n\t\t\t\ts\" 1\" s\" loader.acpi_disabled_by_user\" setenv\n\t\t\t\ts\" 1\" s\" hint.apic.0.disabled\" setenv\n\t\t\tthen\n\t\t\ts\" 0\" s\" hw.ata.ata_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.atapi_dma\" setenv\n\t\t\ts\" 0\" s\" hw.ata.wc\" setenv\n\t\t\ts\" 0\" s\" hw.eisa_slots\" setenv\n\t\t\ts\" 1\" s\" hint.kbdmux.0.disabled\" setenv\n\t\t\ts\" 1\" s\" hint.est.0.disabled\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup bootverbosekey @ = if\n\t\t\ts\" YES\" s\" boot_verbose\" setenv\n\t\t\t0 boot\n\t\tthen\n\t\tdup escapekey @ = if\n\t\t\t2drop\n\t\t\ts\" NO\" s\" autoboot_delay\" setenv\n\t\t\texit\n\t\tthen\n\t\trebootkey @ = if 0 reboot then\n\tagain\n;\n\nprevious\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"bbb1bced12c2d5e4426558a72955df5707f2d14a","subject":"Re-instituted IS word","message":"Re-instituted IS word\n","repos":"rm-hull\/byok3,rm-hull\/byok3","old_file":"core\/src\/main\/resources\/forth\/system.fth","new_file":"core\/src\/main\/resources\/forth\/system.fth","new_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\\n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n\n: COUNT dup 1+ swap c@ ;\n\n\\ Miscellaneous support words\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: <= ( a b -- f , true if A <= b ) > 0= ;\n: >= ( a b -- f , true if A >= b ) < 0= ;\n: NOT ( n -- !n , logical negation ) 0= ;\n: DNEGATE ( d -- -d , negate by doing 0-d )\n 0 swap -\n;\n: CELL+ ( n -- n+cell ) cell + ;\n: CELL- ( n -- n-cell ) cell - ;\n: CELL* ( n -- n*cell ) cells ;\n\n: CHAR+ ( n -- n+size_of_char ) 1+ ;\n: CHARS ( n -- n*size_of_char, don't do anything ) ; immediate\n\n\\ useful stack manipulation words\n: -ROT ( a b c -- c a b ) rot rot ;\n: 3DUP ( a b c -- a b c a b c ) 2 pick 2 pick 2 pick ;\n\n\\ ------------------------------------------------------------------\n: ID. ( nfa -- ) count 31 and type ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n\n: BETWEEN ( n lo hi -- flag , true if between lo & hi )\n >r over r> > >r\n < r> or 0=\n;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: ? ( -- ) @ . ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ ' (lit) , cell 1- , ] +\n [ ' (lit) , cell 1- invert , ] and ;\n\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n: ALLOT ( nbytes -- , allot space in dictionary ) dp +! align ;\n\n: C, ( c -- ) here c! 1 dp +! ;\n\\ : W, ( w -- ) dp @ even-up dup dp ! w! 2 dp +! ;\n\\ : , ( n -- , lay into dictionary ) align here ! cell allot ;\n\n: SEE ( -- )\n ' dup\n >body swap >size\n disassemble ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token )\n [compile] literal ( compile a call to literal )\n ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick )\n ?comp ' [compile] literal\n; immediate\n\n: (DOES>) ( xt -- , modify previous definition to execute code at xt )\n latest >body \\ get address of code for new word\n 3 cell* + \\ offset to EXIT cell in create word\n ! \\ store execution token of DOES> code in new word\n;\n\n: DOES> ( -- , define execution code for CREATE word )\n 0 [compile] literal \\ dummy literal to hold xt\n here cell- \\ address of zero in literal\n compile (does>) \\ call (DOES>) from new creation word\n >r \\ move addrz to return stack so ; doesn't see stack garbage\n [compile] ; \\ terminate part of code before does>\n r>\n :noname ( addrz xt )\n compile rdrop \\ drop a stack frame (call becomes goto)\n swap ! \\ save execution token in literal\n; immediate\n\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 )\n swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 )\n dup cell+ @ swap @ ;\n\n: 2* ( n -- n*2 )\n 2 *\n;\n: 2\/ ( n -- n\/2 )\n 2 \/\n;\n\n\n\\ define some useful constants ------------------------------\n1 0= constant FALSE\n0 0= constant TRUE\n32 constant BL\n\n\\ Stack data structure ----------------------------------------\n\\ This is a general purpose stack utility used to implement necessary\n\\ stacks for the compiler or the user. Not real fast.\n\\ These stacks grow up which is different then normal.\n\\ cell 0 - stack pointer, offset from pfa of word\n\\ cell 1 - limit for range checking\n\\ cell 2 - first data location\n\n: :STACK ( #cells -- )\n CREATE 2 cells , ( offset of first data location )\n dup , ( limit for range checking, not currently used )\n cells cell+ allot ( allot an extra cell for safety )\n;\n\n: >STACK ( n stack -- , push onto stack, postincrement )\n dup @ 2dup cell+ swap ! ( -- n stack offset )\n + !\n;\n\n: STACK> ( stack -- n , pop , predecrement )\n dup @ cell- 2dup swap !\n + @\n;\n\n: STACK@ ( stack -- n , copy )\n dup @ cell- + @\n;\n\n: STACK.PICK ( index stack -- n , grab Nth from top of stack )\n dup @ cell- +\n swap cells - \\ offset for index\n @\n;\n: STACKP ( stack -- ptr , to next empty location on stack )\n dup @ +\n;\n\n: 0STACKP ( stack -- , clear stack)\n 8 swap !\n;\n\n32 :stack ustack\nustack 0stackp\n\n\\ Define JForth like words.\n: >US ustack >stack ;\n: US> ustack stack> ;\n: US@ ustack stack@ ;\n: 0USP ustack 0stackp ;\n\n\n\n\\ DO LOOP ------------------------------------------------\n\n3 constant do_flag\n4 constant leave_flag\n5 constant ?do_flag\n\n: DO ( -- , loop-back do_flag jump-from ?do_flag )\n ?comp\n compile (do)\n here >us do_flag >us ( for backward branch )\n; immediate\n\n: ?DO ( -- , loop-back do_flag jump-from ?do_flag , on user stack )\n ?comp\n ( leave address to set for forward branch )\n compile (?do)\n here 0 ,\n here >us do_flag >us ( for backward branch )\n >us ( for forward branch ) ?do_flag >us\n; immediate\n\n: LEAVE ( -- addr leave_flag )\n compile (leave)\n here 0 , >us\n leave_flag >us\n; immediate\n\n: LOOP-FORWARD ( -us- jump-from ?do_flag -- )\n BEGIN\n us@ leave_flag =\n us@ ?do_flag =\n OR\n WHILE\n us> leave_flag =\n IF\n us> here over - cell+ swap !\n ELSE\n us> dup\n here swap -\n cell+ swap !\n THEN\n REPEAT\n;\n\n: LOOP-BACK ( loop-addr do_flag -us- )\n us> do_flag ?pairs\n us> here - here\n !\n cell allot\n;\n\n: LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (loop)\n loop-forward loop-back\n; immediate\n\n\\ : DOTEST 5 0 do 333 . loop 888 . ;\n\\ : ?DOTEST0 0 0 ?do 333 . loop 888 . ;\n\\ : ?DOTEST1 5 0 ?do 333 . loop 888 . ;\n\n: +LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (+loop)\n loop-forward loop-back\n; immediate\n\n: UNLOOP ( loop-sys -r- )\n r> \\ save return pointer\n rdrop rdrop\n >r\n;\n\n\n: RECURSE ( ? -- ? , call the word currently being defined )\n latest compile,\n; immediate\n\n: SPACE bl emit ;\n: 0SP depth 0 ?do drop loop ;\n\n\\ : >NEWLINE ( -- , CR if needed )\n\\ out @ 0>\n\\ IF cr\n\\ THEN\n\\ ;\n\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 ) swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 ) dup cell+ @ swap @ ;\n\n: DABS ( d -- |d| )\n dup 0<\n IF dnegate\n THEN\n;\n\n: S>D ( s -- d , extend signed single precision to double )\n dup 0<\n IF -1\n ELSE 0\n THEN\n;\n\n: D>S ( d -- s ) drop ;\n\n: PARSE-WORD ( \"name\" -- c-addr u ) bl parse ;\n: \/STRING ( addr len n -- addr' len' ) over min rot over + -rot - ;\n: PLACE ( addr len to -- , move string ) 3dup 1+ swap cmove c! drop ;\n\n: ASCII ( -- char, state smart )\n bl parse drop c@\n state @ 1 =\n IF [compile] literal\n ELSE\n THEN\n; immediate\n\n: CHAR ( -- char , interpret mode ) bl parse drop c@ ;\n: [CHAR] ( -- char , for compile mode )\n char [compile] literal\n; immediate\n\n: $TYPE ( $string -- ) count type ;\n: 'word ( -- addr ) here ;\n\n: EVEN ( addr -- addr' ) dup 1 and + ;\n\n: (C\") ( -- $addr ) r> dup count + aligned >r ;\n: (S\") ( -- c-addr cnt ) r> count 2dup + aligned >r ;\n: (.\") ( -- , type following string ) r> count 2dup + aligned >r type ;\n: \", ( addr len -- , place string into dict ) tuck 'word place 1+ allot align ;\n: ,\" ( -- ) [char] \" parse \", ;\n\n: .( ( --, type string delimited by parens )\n [char] ) parse type\n; immediate\n\n: .\" ( -- , type string )\n state @ 1 =\n IF compile (.\") ,\"\n ELSE [char] \" parse type\n THEN\n; immediate\n\n: .' ( -- , type string delimited by single quote )\n state @\n IF compile (.\") [char] ' parse \",\n ELSE [char] ' parse type\n THEN\n; immediate\n\n: C\" ( -- addr , return string address, ANSI )\n state @\n IF compile (c\") ,\"\n ELSE [char] \" parse pad place pad\n THEN\n; immediate\n\n: S\" ( -- , -- addr , return string address, ANSI )\n state @\n IF compile (s\") ,\"\n ELSE [char] \" parse pad place pad count\n THEN\n; immediate\n\n: \" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n: P\" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n\n: \"\" ( -- addr )\n state @\n IF\n compile (C\")\n bl parse-word \",\n ELSE\n bl parse-word pad place pad\n THEN\n; immediate\n\n: SLITERAL ( addr cnt -- , compile string )\n compile (S\")\n \",\n; IMMEDIATE\n\n: $APPEND ( addr count $1 -- , append text to $1 )\n over >r\n dup >r\n count + ( -- a2 c2 end1 )\n swap cmove\n r> dup c@ ( a1 c1 )\n r> + ( -- a1 totalcount )\n swap c!\n;\n\n\\ ANSI word to replace [COMPILE] and COMPILE ----------------\n: POSTPONE ( -- )\n\tbl word find\n\tdup\n 0= -13 ?ERROR\n 0>\n IF compile, \\ immediate\n ELSE (compile) \\ normal\n THEN\n\n; immediate\n\n\\ -----------------------------------------------------------------\n\\ Auto Initialization\n: AUTO.INIT ( -- )\n\\ Kernel finds AUTO.INIT and executes it after loading dictionary.\n\\ .\" Begin AUTO.INIT ------\" cr\n;\n: AUTO.TERM ( -- )\n\\ Kernel finds AUTO.TERM and executes it on bye.\n\\ .\" End AUTO.TERM ------\" cr\n;\n\n: INCLUDE? ( -- , load file if word not defined )\n bl word find\n IF drop bl word drop ( eat word from source )\n ELSE drop include\n THEN\n; immediate\n\n: CLEARSTACK ( i*x -- )\n BEGIN depth\n WHILE drop\n REPEAT ;\n\nvariable pictured_output \\ hidden?\nvariable pictured_output_len \\ hidden?\n\n: <# ( -- ) pad pictured_output ! 0 pictured_output_len ! ;\n: #> ( -- addr n ) drop pictured_output @ pictured_output_len @ ;\n\n: HOLD ( c -- )\n pictured_output @ dup dup 1+ pictured_output_len @ cmove c!\n 1 pictured_output_len +!\n;\n\n\\ ------------------------ INPUT -------------------------------\n\n: SIGN ( n -- ) < 0 IF 45 hold THEN\n;\n\n: DIGIT ( n -- ascii )\n dup 10 < IF 48 ELSE 87 THEN + ;\n\n: # ( n -- n )\n base @ \/mod swap digit hold ;\n\n: #S ( n -- )\n BEGIN base @ \/mod dup\n WHILE swap digit hold\n REPEAT\n digit hold ;\n\n\n: LWORD ( char -- addr )\n parse-word here place here \\ 00002 , use PARSE-WORD\n;\n\n: (WARNING\") ( flag $message -- )\n swap\n IF count type\n ELSE drop\n THEN\n;\n\n: WARNING\" ( flag -- , print warning if true. )\n [compile] \" ( compile message )\n state @\n IF compile (warning\")\n ELSE (warning\")\n THEN\n; IMMEDIATE\n\n: ABORT\" ( flag -- , print warning if true. )\n [compile] \" ( compile message )\n state @\n IF compile (abort\")\n ELSE (abort\")\n THEN\n; IMMEDIATE\n\n: DEFER ( \"name\" -- )\n CREATE ['] ABORT ,\n DOES> ( ... -- ... ) @ EXECUTE ;\n\n: DEFER! ( xt2 xt1 -- )\n >BODY 4 CELL* + ! ;\n\n: DEFER@ ( xt1 -- xt2 )\n >BODY 4 CELL* + @ ;\n\n: IS ( xt \"name\" -- , Skip leading spaces and parse name delimited by a space. Set name to execute xt. )\n STATE @ IF\n POSTPONE ['] POSTPONE DEFER!\n ELSE\n ' DEFER!\n THEN ; IMMEDIATE\n\n\n\\ : $ ( -- N , convert next number as hex )\n\\ base @ hex\n\\ 32 lword number? num_type_single = not\n\\ abort\" Not a single number!\"\n\\ swap base !\n\\ state @\n\\ IF [compile] literal\n\\ THEN\n\\ ; immediate","old_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\\n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n\n: COUNT dup 1+ swap c@ ;\n\n\\ Miscellaneous support words\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: <= ( a b -- f , true if A <= b ) > 0= ;\n: >= ( a b -- f , true if A >= b ) < 0= ;\n: NOT ( n -- !n , logical negation ) 0= ;\n: DNEGATE ( d -- -d , negate by doing 0-d )\n 0 swap -\n;\n: CELL+ ( n -- n+cell ) cell + ;\n: CELL- ( n -- n-cell ) cell - ;\n: CELL* ( n -- n*cell ) cells ;\n\n: CHAR+ ( n -- n+size_of_char ) 1+ ;\n: CHARS ( n -- n*size_of_char, don't do anything ) ; immediate\n\n\\ useful stack manipulation words\n: -ROT ( a b c -- c a b ) rot rot ;\n: 3DUP ( a b c -- a b c a b c ) 2 pick 2 pick 2 pick ;\n\n\\ ------------------------------------------------------------------\n: ID. ( nfa -- ) count 31 and type ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n\n: BETWEEN ( n lo hi -- flag , true if between lo & hi )\n >r over r> > >r\n < r> or 0=\n;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: ? ( -- ) @ . ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ ' (lit) , cell 1- , ] +\n [ ' (lit) , cell 1- invert , ] and ;\n\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n: ALLOT ( nbytes -- , allot space in dictionary ) dp +! align ;\n\n: C, ( c -- ) here c! 1 dp +! ;\n\\ : W, ( w -- ) dp @ even-up dup dp ! w! 2 dp +! ;\n\\ : , ( n -- , lay into dictionary ) align here ! cell allot ;\n\n: SEE ( -- )\n ' dup\n >body swap >size\n disassemble ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token )\n [compile] literal ( compile a call to literal )\n ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick )\n ?comp ' [compile] literal\n; immediate\n\n: (DOES>) ( xt -- , modify previous definition to execute code at xt )\n latest >body \\ get address of code for new word\n 3 cell* + \\ offset to EXIT cell in create word\n ! \\ store execution token of DOES> code in new word\n;\n\n: DOES> ( -- , define execution code for CREATE word )\n 0 [compile] literal \\ dummy literal to hold xt\n here cell- \\ address of zero in literal\n compile (does>) \\ call (DOES>) from new creation word\n >r \\ move addrz to return stack so ; doesn't see stack garbage\n [compile] ; \\ terminate part of code before does>\n r>\n :noname ( addrz xt )\n compile rdrop \\ drop a stack frame (call becomes goto)\n swap ! \\ save execution token in literal\n; immediate\n\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 )\n swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 )\n dup cell+ @ swap @ ;\n\n: 2* ( n -- n*2 )\n 2 *\n;\n: 2\/ ( n -- n\/2 )\n 2 \/\n;\n\n\n\\ define some useful constants ------------------------------\n1 0= constant FALSE\n0 0= constant TRUE\n32 constant BL\n\n\\ Stack data structure ----------------------------------------\n\\ This is a general purpose stack utility used to implement necessary\n\\ stacks for the compiler or the user. Not real fast.\n\\ These stacks grow up which is different then normal.\n\\ cell 0 - stack pointer, offset from pfa of word\n\\ cell 1 - limit for range checking\n\\ cell 2 - first data location\n\n: :STACK ( #cells -- )\n CREATE 2 cells , ( offset of first data location )\n dup , ( limit for range checking, not currently used )\n cells cell+ allot ( allot an extra cell for safety )\n;\n\n: >STACK ( n stack -- , push onto stack, postincrement )\n dup @ 2dup cell+ swap ! ( -- n stack offset )\n + !\n;\n\n: STACK> ( stack -- n , pop , predecrement )\n dup @ cell- 2dup swap !\n + @\n;\n\n: STACK@ ( stack -- n , copy )\n dup @ cell- + @\n;\n\n: STACK.PICK ( index stack -- n , grab Nth from top of stack )\n dup @ cell- +\n swap cells - \\ offset for index\n @\n;\n: STACKP ( stack -- ptr , to next empty location on stack )\n dup @ +\n;\n\n: 0STACKP ( stack -- , clear stack)\n 8 swap !\n;\n\n32 :stack ustack\nustack 0stackp\n\n\\ Define JForth like words.\n: >US ustack >stack ;\n: US> ustack stack> ;\n: US@ ustack stack@ ;\n: 0USP ustack 0stackp ;\n\n\n\n\\ DO LOOP ------------------------------------------------\n\n3 constant do_flag\n4 constant leave_flag\n5 constant ?do_flag\n\n: DO ( -- , loop-back do_flag jump-from ?do_flag )\n ?comp\n compile (do)\n here >us do_flag >us ( for backward branch )\n; immediate\n\n: ?DO ( -- , loop-back do_flag jump-from ?do_flag , on user stack )\n ?comp\n ( leave address to set for forward branch )\n compile (?do)\n here 0 ,\n here >us do_flag >us ( for backward branch )\n >us ( for forward branch ) ?do_flag >us\n; immediate\n\n: LEAVE ( -- addr leave_flag )\n compile (leave)\n here 0 , >us\n leave_flag >us\n; immediate\n\n: LOOP-FORWARD ( -us- jump-from ?do_flag -- )\n BEGIN\n us@ leave_flag =\n us@ ?do_flag =\n OR\n WHILE\n us> leave_flag =\n IF\n us> here over - cell+ swap !\n ELSE\n us> dup\n here swap -\n cell+ swap !\n THEN\n REPEAT\n;\n\n: LOOP-BACK ( loop-addr do_flag -us- )\n us> do_flag ?pairs\n us> here - here\n !\n cell allot\n;\n\n: LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (loop)\n loop-forward loop-back\n; immediate\n\n\\ : DOTEST 5 0 do 333 . loop 888 . ;\n\\ : ?DOTEST0 0 0 ?do 333 . loop 888 . ;\n\\ : ?DOTEST1 5 0 ?do 333 . loop 888 . ;\n\n: +LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (+loop)\n loop-forward loop-back\n; immediate\n\n: UNLOOP ( loop-sys -r- )\n r> \\ save return pointer\n rdrop rdrop\n >r\n;\n\n\n: RECURSE ( ? -- ? , call the word currently being defined )\n latest compile,\n; immediate\n\n: SPACE bl emit ;\n: 0SP depth 0 ?do drop loop ;\n\n\\ : >NEWLINE ( -- , CR if needed )\n\\ out @ 0>\n\\ IF cr\n\\ THEN\n\\ ;\n\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 ) swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 ) dup cell+ @ swap @ ;\n\n: DABS ( d -- |d| )\n dup 0<\n IF dnegate\n THEN\n;\n\n: S>D ( s -- d , extend signed single precision to double )\n dup 0<\n IF -1\n ELSE 0\n THEN\n;\n\n: D>S ( d -- s ) drop ;\n\n: PARSE-WORD ( \"name\" -- c-addr u ) bl parse ;\n: \/STRING ( addr len n -- addr' len' ) over min rot over + -rot - ;\n: PLACE ( addr len to -- , move string ) 3dup 1+ swap cmove c! drop ;\n\n: ASCII ( -- char, state smart )\n bl parse drop c@\n state @ 1 =\n IF [compile] literal\n ELSE\n THEN\n; immediate\n\n: CHAR ( -- char , interpret mode ) bl parse drop c@ ;\n: [CHAR] ( -- char , for compile mode )\n char [compile] literal\n; immediate\n\n: $TYPE ( $string -- ) count type ;\n: 'word ( -- addr ) here ;\n\n: EVEN ( addr -- addr' ) dup 1 and + ;\n\n: (C\") ( -- $addr ) r> dup count + aligned >r ;\n: (S\") ( -- c-addr cnt ) r> count 2dup + aligned >r ;\n: (.\") ( -- , type following string ) r> count 2dup + aligned >r type ;\n: \", ( addr len -- , place string into dict ) tuck 'word place 1+ allot align ;\n: ,\" ( -- ) [char] \" parse \", ;\n\n: .( ( --, type string delimited by parens )\n [char] ) parse type\n; immediate\n\n: .\" ( -- , type string )\n state @ 1 =\n IF compile (.\") ,\"\n ELSE [char] \" parse type\n THEN\n; immediate\n\n: .' ( -- , type string delimited by single quote )\n state @\n IF compile (.\") [char] ' parse \",\n ELSE [char] ' parse type\n THEN\n; immediate\n\n: C\" ( -- addr , return string address, ANSI )\n state @\n IF compile (c\") ,\"\n ELSE [char] \" parse pad place pad\n THEN\n; immediate\n\n: S\" ( -- , -- addr , return string address, ANSI )\n state @\n IF compile (s\") ,\"\n ELSE [char] \" parse pad place pad count\n THEN\n; immediate\n\n: \" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n: P\" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n\n: \"\" ( -- addr )\n state @\n IF\n compile (C\")\n bl parse-word \",\n ELSE\n bl parse-word pad place pad\n THEN\n; immediate\n\n: SLITERAL ( addr cnt -- , compile string )\n compile (S\")\n \",\n; IMMEDIATE\n\n: $APPEND ( addr count $1 -- , append text to $1 )\n over >r\n dup >r\n count + ( -- a2 c2 end1 )\n swap cmove\n r> dup c@ ( a1 c1 )\n r> + ( -- a1 totalcount )\n swap c!\n;\n\n\\ ANSI word to replace [COMPILE] and COMPILE ----------------\n: POSTPONE ( -- )\n\tbl word find\n\tdup\n 0= -13 ?ERROR\n 0>\n IF compile, \\ immediate\n ELSE (compile) \\ normal\n THEN\n\n; immediate\n\n\\ -----------------------------------------------------------------\n\\ Auto Initialization\n: AUTO.INIT ( -- )\n\\ Kernel finds AUTO.INIT and executes it after loading dictionary.\n\\ .\" Begin AUTO.INIT ------\" cr\n;\n: AUTO.TERM ( -- )\n\\ Kernel finds AUTO.TERM and executes it on bye.\n\\ .\" End AUTO.TERM ------\" cr\n;\n\n: INCLUDE? ( -- , load file if word not defined )\n bl word find\n IF drop bl word drop ( eat word from source )\n ELSE drop include\n THEN\n; immediate\n\n: CLEARSTACK ( i*x -- )\n BEGIN depth\n WHILE drop\n REPEAT ;\n\nvariable pictured_output \\ hidden?\nvariable pictured_output_len \\ hidden?\n\n: <# ( -- ) pad pictured_output ! 0 pictured_output_len ! ;\n: #> ( -- addr n ) drop pictured_output @ pictured_output_len @ ;\n\n: HOLD ( c -- )\n pictured_output @ dup dup 1+ pictured_output_len @ cmove c!\n 1 pictured_output_len +!\n;\n\n\\ ------------------------ INPUT -------------------------------\n\n: SIGN ( n -- ) < 0 IF 45 hold THEN\n;\n\n: DIGIT ( n -- ascii )\n dup 10 < IF 48 ELSE 87 THEN + ;\n\n: # ( n -- n )\n base @ \/mod swap digit hold ;\n\n: #S ( n -- )\n BEGIN base @ \/mod dup\n WHILE swap digit hold\n REPEAT\n digit hold ;\n\n\n: LWORD ( char -- addr )\n parse-word here place here \\ 00002 , use PARSE-WORD\n;\n\n: (WARNING\") ( flag $message -- )\n swap\n IF count type\n ELSE drop\n THEN\n;\n\n: WARNING\" ( flag -- , print warning if true. )\n [compile] \" ( compile message )\n state @\n IF compile (warning\")\n ELSE (warning\")\n THEN\n; IMMEDIATE\n\n: ABORT\" ( flag -- , print warning if true. )\n [compile] \" ( compile message )\n state @\n IF compile (abort\")\n ELSE (abort\")\n THEN\n; IMMEDIATE\n\n: DEFER ( \"name\" -- )\n CREATE ['] ABORT ,\n DOES> ( ... -- ... ) @ EXECUTE ;\n\n: DEFER! ( xt2 xt1 -- )\n >BODY 4 CELL* + ! ;\n\n: DEFER@ ( xt1 -- xt2 )\n >BODY 4 CELL* + @ ;\n\n\\ : IS ( xt \"name\" -- , Skip leading spaces and parse name delimited by a space. Set name to execute xt. )\n\\ STATE @ IF\n\\ POSTPONE ['] POSTPONE DEFER!\n\\ ELSE\n\\ ' DEFER!\n\\ THEN ; IMMEDIATE\n\n\n\\ : $ ( -- N , convert next number as hex )\n\\ base @ hex\n\\ 32 lword number? num_type_single = not\n\\ abort\" Not a single number!\"\n\\ swap base !\n\\ state @\n\\ IF [compile] literal\n\\ THEN\n\\ ; immediate","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"ad25ed1a4e2dade7bab25c4a1254f797e56e2e20","subject":"Added min, max, negate, abs","message":"Added min, max, negate, abs\n","repos":"AshleyF\/Forthkit,AshleyF\/Forthkit,AshleyF\/Forthkit","old_file":"hardware\/register\/bootstrap.4th","new_file":"hardware\/register\/bootstrap.4th","new_contents":"( bootstrap remainder of interpreter )\n( load into machine running outer interpreter image )\n\ncreate : compile create compile ; ( magic! )\n\n( assembler )\n\n: x 1 ; ( shared by outer interpreter )\n: d 2 ; ( dictionary pointer - shared by outer interpreter )\n: zero 4 ; ( shared by outer interpreter )\n: y 30 ; \n: z 31 ; \n\n: [ interact ; immediate\n: ] compile ;\n\n: cp, 3 , , , ; \n: popxy popx [ x y cp, ] popx ;\n: pushxy pushx [ y x cp, ] pushx ;\n\n: xor, 15 , , , , ; \n: swap popxy [ x y x xor, x y y xor, x y x xor, ] pushxy ;\n\n: ldc, 0 , , , ;\n: ld, 1 , , , ;\n: st, 2 , , , ;\n: in, 4 , , ;\n: out, 5 , , ;\n: inc, 6 , , , ;\n: dec, 7 , , , ;\n: add, 8 , , , , ;\n: sub, 9 , , swap , , ;\n: mul, 10 , , , , ;\n: div, 11 , , swap , , ;\n: mod, 12 , , swap , , ;\n: and, 13 , , , , ;\n: or, 14 , , , , ;\n: not, 16 , , , ;\n: shr, 17 , , swap , , ;\n: shl, 18 , , swap , , ;\n: beq, 19 , , , , ;\n: bne, 20 , , , , ;\n: bgt, 21 , , swap , , ;\n: bge, 22 , , swap , , ;\n: blt, 23 , , swap , , ;\n: ble, 24 , , swap , , ;\n: exec, 25 , , ;\n: jump, 26 , , ;\n: call, 27 , , ;\n: ret, 28 , ;\n: halt, 29 , ;\n: dump, 30 , ;\n\n( instruction words )\n\n: + popxy [ x y x add, ] pushx ;\n: - popxy [ x y x sub, ] pushx ;\n: * popxy [ x y x mul, ] pushx ;\n: \/ popxy [ x y x div, ] pushx ;\n: mod popxy [ x y x mod, ] pushx ;\n: 2\/ popxy [ x y x shr, ] pushx ;\n: 2* popxy [ x y x shl, ] pushx ;\n: and popxy [ x y x and, ] pushx ;\n: or popxy [ x y x or, ] pushx ;\n: xor popxy [ x y x xor, ] pushx ;\n: not popx [ x x not, ] pushx ;\n: 1+ popx [ x x inc, ] pushx ;\n: 1- popx [ x x dec, ] pushx ;\n: exec popx [ x exec, ] ;\n: dump [ dump, ] ;\n: exit [ halt, ] ;\n\n( stack manipulation )\n\n: drop ( a- ) popx ;\n: 2drop ( ab- ) drop drop ;\n: dup ( a-aa ) popx pushx pushx ;\n: over ( ab-aba ) popxy pushx pushx [ y x cp, ] pushx swap ;\n: 2dup ( ab-abab ) over over ;\n: nip ( ab-b ) swap drop ;\n: tuck ( ab-bab ) swap over ;\n: -rot ( abc-cab ) swap popxy pushx [ y z cp, ] swap [ z x cp, ] pushx ;\n\n( vocabulary )\n\n: true -1 ;\n: false 0 ;\n\n: key [ x in, ] pushx ;\n: emit popx [ x out, ] ;\n: cr 10 emit ;\n: space 32 emit ;\n\n: @ popx [ x x ld, ] pushx ;\n: ! popxy [ x y st, ] ;\n\n: allot [ d x cp, ] pushx swap popx [ x d d add, ] ;\n\n: here@ [ d x cp, ] pushx ;\n: here! popx [ x d cp, ] ;\n\n: >dfa 2 + ;\n: ' find >dfa ;\n\n: if [ ' popxy literal ] call, here@ 1+ zero x 0 beq, ; immediate\n: else here@ 1+ 0 jump, swap here@ swap ! ; immediate\n: then here@ swap ! ; immediate\n\n: = popxy 0 [ x y here@ 6 + bne, ] not ;\n: <> popxy 0 [ x y here@ 6 + beq, ] not ;\n: > popxy 0 [ x y here@ 6 + ble, ] not ;\n: < popxy 0 [ x y here@ 6 + bge, ] not ;\n: >= popxy 0 [ x y here@ 6 + blt, ] not ;\n: <= popxy 0 [ x y here@ 6 + bgt, ] not ;\n\n: sign 0 < if -1 else 1 then ;\n: \/mod 2dup \/ -rot mod ;\n\n: min 2dup > if swap then drop ;\n: max 2dup < if swap then drop ;\n\n: negate -1 * ;\n: abs dup 0 < if negate then ;\n\n: .sign dup sign negate 44 + emit ; ( happens 44 +\/- 1 is ASCII '-'\/'+' )\n: .dig 10 \/mod swap ;\n: .digemit 48 + emit ; ( 48 is ASCII '0' )\n: . .sign .dig .dig .dig .dig .dig drop .digemit .digemit .digemit .digemit .digemit cr ;\n","old_contents":"( bootstrap remainder of interpreter )\n( load into machine running outer interpreter image )\n\ncreate : compile create compile ; ( magic! )\n\n( assembler )\n\n: x 1 ; ( shared by outer interpreter )\n: d 2 ; ( dictionary pointer - shared by outer interpreter )\n: zero 4 ; ( shared by outer interpreter )\n: y 30 ; \n: z 31 ; \n\n: [ interact ; immediate\n: ] compile ;\n\n: cp, 3 , , , ; \n: popxy popx [ x y cp, ] popx ;\n: pushxy pushx [ y x cp, ] pushx ;\n\n: xor, 15 , , , , ; \n: swap popxy [ x y x xor, x y y xor, x y x xor, ] pushxy ;\n\n: ldc, 0 , , , ;\n: ld, 1 , , , ;\n: st, 2 , , , ;\n: in, 4 , , ;\n: out, 5 , , ;\n: inc, 6 , , , ;\n: dec, 7 , , , ;\n: add, 8 , , , , ;\n: sub, 9 , , swap , , ;\n: mul, 10 , , , , ;\n: div, 11 , , swap , , ;\n: mod, 12 , , swap , , ;\n: and, 13 , , , , ;\n: or, 14 , , , , ;\n: not, 16 , , , ;\n: shr, 17 , , swap , , ;\n: shl, 18 , , swap , , ;\n: beq, 19 , , , , ;\n: bne, 20 , , , , ;\n: bgt, 21 , , swap , , ;\n: bge, 22 , , swap , , ;\n: blt, 23 , , swap , , ;\n: ble, 24 , , swap , , ;\n: exec, 25 , , ;\n: jump, 26 , , ;\n: call, 27 , , ;\n: ret, 28 , ;\n: halt, 29 , ;\n: dump, 30 , ;\n\n( instruction words )\n\n: + popxy [ x y x add, ] pushx ;\n: - popxy [ x y x sub, ] pushx ;\n: * popxy [ x y x mul, ] pushx ;\n: \/ popxy [ x y x div, ] pushx ;\n: mod popxy [ x y x mod, ] pushx ;\n: 2\/ popxy [ x y x shr, ] pushx ;\n: 2* popxy [ x y x shl, ] pushx ;\n: and popxy [ x y x and, ] pushx ;\n: or popxy [ x y x or, ] pushx ;\n: xor popxy [ x y x xor, ] pushx ;\n: not popx [ x x not, ] pushx ;\n: 1+ popx [ x x inc, ] pushx ;\n: 1- popx [ x x dec, ] pushx ;\n: exec popx [ x exec, ] ;\n: dump [ dump, ] ;\n: exit [ halt, ] ;\n\n( stack manipulation )\n\n: drop ( a- ) popx ;\n: 2drop ( ab- ) drop drop ;\n: dup ( a-aa ) popx pushx pushx ;\n: over ( ab-aba ) popxy pushx pushx [ y x cp, ] pushx swap ;\n: 2dup ( ab-abab ) over over ;\n: nip ( ab-b ) swap drop ;\n: tuck ( ab-bab ) swap over ;\n: -rot ( abc-cab ) swap popxy pushx [ y z cp, ] swap [ z x cp, ] pushx ;\n\n( vocabulary )\n\n: true -1 ;\n: false 0 ;\n\n: key [ x in, ] pushx ;\n: emit popx [ x out, ] ;\n: cr 10 emit ;\n: space 32 emit ;\n\n: @ popx [ x x ld, ] pushx ;\n: ! popxy [ x y st, ] ;\n\n: allot [ d x cp, ] pushx swap popx [ x d d add, ] ;\n\n: here@ [ d x cp, ] pushx ;\n: here! popx [ x d cp, ] ;\n\n: >dfa 2 + ;\n: ' find >dfa ;\n\n: if [ ' popxy literal ] call, here@ 1+ zero x 0 beq, ; immediate\n: else here@ 1+ 0 jump, swap here@ swap ! ; immediate\n: then here@ swap ! ; immediate\n\n: = popxy 0 [ x y here@ 6 + bne, ] not ;\n: <> popxy 0 [ x y here@ 6 + beq, ] not ;\n: > popxy 0 [ x y here@ 6 + ble, ] not ;\n: < popxy 0 [ x y here@ 6 + bge, ] not ;\n: >= popxy 0 [ x y here@ 6 + blt, ] not ;\n: <= popxy 0 [ x y here@ 6 + bgt, ] not ;\n\n: sign 0 < if -1 else 1 then ;\n: \/mod 2dup \/ -rot mod ;\n\n: .sign dup sign -1 * 44 + emit ; ( happens 44 +\/- 1 is ASCII '-'\/'+' )\n: .dig 10 \/mod swap ;\n: .digemit 48 + emit ; ( 48 is ASCII '0' )\n: . .sign .dig .dig .dig .dig .dig drop .digemit .digemit .digemit .digemit .digemit cr ;\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"cbe397ff0397bb0504d7fe525489daa1a001b9fa","subject":"Whoops. Hours needs to move less often.","message":"Whoops. Hours needs to move less often.","repos":"rbsexton\/gecko,rbsexton\/gecko,rbsexton\/gecko","old_file":"zero\/clock-umb\/forth\/Clock.fth","new_file":"zero\/clock-umb\/forth\/Clock.fth","new_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( -- ) \n init-idata\n load-defaults \n icroot 0 over inter.rtcsem ! \\ Reset the free-running counters.\n 0 over inter.rtcdsem ! \\ Reset the free-running counters.\n\n begin \n \tdup inter.rtcsem @offex! ?dup if advancehms then\n \tdup inter.rtcdsem @offex! ?dup if advancedhms then\n [asm wfi asm]\n uiupdate if use-uivals else use-clockvals then \n key? until drop\n;\n \n\\ These two contain loops to ensure that we don't\n\\ drop any timer ticks on the floor.\n: ADVANCEHMS ( n -- ) 0 do hms advancetime loop ;\n: ADVANCEDHMS ( n -- ) 0 do dhms advancetime loop ;\n \n: LOAD-DEFAULTS ( -- )\n nvramvalid? if _nvramload then \n interp-init\n;\n\n\\ ----------------------------------------------------------\n\\ Define the structures before they get used.\n\\ ----------------------------------------------------------\nstruct ODN \\ On-Deck Needle \n\tint odn.s\n\tint odn.m\n\tint odn.h\nend-struct\n\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxsec \\ Max Value for secs+minutes\n\tint hms.maxhour \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_m \\ increment the minutes + hours\nend-struct\n\nstruct _interp_set\n\t4 cells field interp.a\n\t4 cells field interp.b\n\t4 cells field interp.c\nend-struct\n\n\\ ----------------------------------------------------------\n\\ Defaults get saved in the user data page.\n\\ ----------------------------------------------------------\n: NVRAMVALID? ( -- t\/f ) \n\\ *G See if there is valid data in the NVRAM.\n\\ ** It consists of 3 words. If any of them are \n\\ ** set to 0xffff:ffff, we go with the defaults.\n _USERDATA\n dup @ -1 <> \n over 4 + @ -1 <> and\n swap 8 + @ -1 <> and\n;\n\n: _NVRAMLOAD ( -- ) \n\\ *G Pull the needle maximums from flash.\n $C 0 do I ud@ needle_max I + ! 4 +loop \n; \n\n: NVRAM! ( addr -- )\n\\ *G Save the contents of the needle cal values.\n 0 UDPAGE_ERASE\n ( addr )\n $C 0 do dup I + @ I ud! 4 +loop\n drop \n;\n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nidata\ncreate ODN_HMS odn allot \\ On-Deck, HMS\ncreate ODN_DHMS odn allot \\ On-Deck, DHMS\ncreate ODN_UI odn allot \\ On-Deck, Generated by the UI.\ncdata\n\nidata \\ Has to match an odn.\ncreate NEEDLE_MAX #850 , #850 , #850 ,\ncdata\n\n(( \n: interp-next drop 1 ; \n: interp-reset drop .\" Reset\" ; \n\t\n))\n\n: RANGECHECK ( max n -- n or zero ) 2dup <= if 2drop 0 else swap drop then ; \n: CLIP ( n -- n) \\ Force the contents to be legal ( 0-999 )\n dup 0 < if drop 0 exit then \n dup #999 > if drop #999 then \n;\n \n: INTER-BUMP ( max old interp -- new )\n\\ *G Get the next value from the interpolator, and \n\\ ** reset the interpolator if it wraps around to zero.\n >R R@ interp-next \\ Get the max \n + rangecheck \n dup 0= if R> interp-reset else R> drop then \n ; \n\n: NFETCH ( odn off -- max old )\n\\ *G Combine the current value with the maximum.\n >R R@ \\ stash the offset.\n + @ \\ Calculate the offset address, get the current val.\n needle_max R> + @\n swap \n;\n\n: ++NEEDLE_S \\ Called every time.\n odn_hms 0 odn.s nfetch ( max old )\n\tinterp_hms interp.a inter-bump ( new )\n\todn_hms odn.s ! \n\t;\n\n: ++NEEDLE_M ( -- )\n\\ *G Every time we roll the seconds, bump the minutes and the hour\n\todn_hms 0 odn.m nfetch ( max old )\n\tinterp_hms interp.b inter-bump \n\todn_hms odn.m ! \n\n\todn_hms 0 odn.h nfetch ( max old )\n\tinterp_hms interp.c inter-bump \n\todn_hms odn.h ! \n\t;\n\n: ++NEEDLE_DS ; \\ Called every time.\n: ++NEEDLE_DM ; \\ Every time we roll the seconds.\n\n: _USE ( odn-addr -- ) \n dup odn.s w@ pwm0!\n dup odn.m w@ pwm1!\n odn.h w@ pwm2!\n ;\n\n: USE-CLOCKVALS odn_hms _use ; \n: USE-UIVALS odn_ui _use ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Quadrature\n\\ ----------------------------------------------------------\n\n_timer1 $24 + equ QUAD-IN\n\n\\ The Quadrature encoder produces two per detent.\n: QUAD@ ( -- n ) \\ Fetch and zero\n quad-in @off \n [asm sxth tos, tos asm]\n [asm asr .s tos, tos, # 1 asm] \\ Divide by two,\n ;\n \n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_ds , ' ++needle_dm , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n: ADVANCETIME ( struct-addr -- )\n dup hms.w_s @ execute \\ Invoke the official update word.\n 1 over hms.subsec +! \\ Increment\n dup hms.subsec @\n over hms.maxsubsec @ < if drop exit then \\ If less then max, we're done\n 0 over hms.subsec ! \\ Reset the subsecs \n\n 1 over hms.s +!\n dup hms.s @ over hms.maxsec @ < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n dup hms.w_m @ execute\n 1 over hms.m +!\n dup hms.m @ over hms.maxsec @ < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ over hms.maxhour @ < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ----------------------------------------------------------\n\\ The interpolator. \n\\ Implement bresenhams algorithm. All of this code already\n\\ exists in C, but we'll own the data structures. They contain\n\\ A total of 4 words - fixed, err, num, & denom\n\\ ----------------------------------------------------------\nudata \ncreate interp_hms _interp_set allot\ncreate interp_dhms _interp_set allot \ncdata\n\n#16 #60 * equ raw_sec\n#10 #100 * equ raw_dsec\n\n: INTERP-INIT ( -- )\n (interp_init) interp_hms\n 2dup interp.a needle_max @ raw_sec call3-- \n 2dup interp.b needle_max 4 + @ #60 call3-- \n interp.c needle_max 8 + @ #24 #60 * call3--\n\n (interp_init) interp_dhms\n 2dup interp.a needle_max @ raw_dsec call3-- \n 2dup interp.b needle_max 4 + @ #100 call3-- \n interp.c needle_max 8 + @ #10 #100 * call3--\n;\n\n\\ Call the reset fn.\n: INTERP-RESET ( interp_addr -- )\n (interp_reset) swap call1-- \n;\n\n: INTERP-NEXT ( addr -- n )\n (interp_next) swap call1--n\n;\n\n\n\\ ============================ UNTESTED =======================\n\\ VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n\n\\ ----------------------------------------------------------\n\\ User Interface\n\\ ----------------------------------------------------------\nvariable uistate\nvariable uicount \n\n_GPIO $64 + equ _BUTTONIO\n: BUTTONUP? ( -- t\/f ) _buttonio @ 1 and ; \n: BUTTONDOWN? ( -- t\/f ) buttonup? 1 xor ; \n\n\\ The wrapper for all of the UI stuff.\n\\ Returns true if the UI is active - ie, use the values generated by the UI.\n: UIUPDATE ( -- t\/f )\n StateHandlers uistate @ + @ execute \n; \n\n: uitest \n uistate @ 4 \/ . .\" ->\" uiupdate uistate @ 4 \/ .\n uicount @ . if .\" True\" else .\" False\" then \n; \n\n\\ -----------------------------------------------\n\\ State numbers. These are defined x4 so that\n\\ we can just use the state number as an index \n\\ into a table of words.\n\\ -----------------------------------------------\n0 4 * equ _s_init\n1 4 * equ _s_b1\n2 4 * equ _s_1sec\n\n3 4 * equ _s_set_h\n4 4 * equ _s_pendset_m\n5 4 * equ _s_setmin\n\n6 4 * equ _s_pendcal0\n7 4 * equ _s_cal0\n8 4 * equ _s_pendcalh\n9 4 * equ _s_calh\n10 4 * equ _s_pendcalm\n11 4 * equ _s_calm\n12 4 * equ _s_pendcals\n13 4 * equ _s_cals\n\n4 equ downcount_1s\n16 equ downcount_3s \n\n\\ All of the state handlers.\n\\ Everybody needs to know the state of the button, so that must\n\\ get passed in, thus they all look like this:\n\\ state ( t\/f -- t\/f )\n: shInit false \n buttondown? if \n _s_b1 uistate !\n uicount off \\ Reset this.\n then\n ;\n\n\\ Waiting for a full second to go by.\n: shB1 false\n buttonup? if _s_init uistate ! exit then\n \\ The Button is down. \n uicount @ downcount_1s >= if\n _s_1sec uistate !\n else \n 1 uicount +!\n\tthen\n ;\n\n\\ We're in the 1 second state\n: sh1sec true \n buttonup? if _s_set_h uistate ! exit then\n uicount @ downcount_3s >= if\n _s_pendcal0 uistate !\n else \n 1 uicount +!\n\tthen \n;\n\n\\ -------------------------------------------------\n\\ Setting the time\n\\ -------------------------------------------------\n: shSetH true buttondown? if _s_pendset_m uistate ! exit then ;\n\n: shPendSetM true buttonup? if _s_setmin uistate ! then ;\n: shSetMin true buttondown? if _s_init uistate ! exit then ;\n\n\\ -------------------------------------------------\n\\ Calibration\n\\ -------------------------------------------------\n: shPendCal0 true buttonup? if _s_cal0 uistate ! helpODNClear then ;\n: shCal0 true buttondown? if _s_pendcalh uistate ! exit then ;\n\n: shPendCalH true buttonup? if _s_calh uistate ! helpODNMid then ; \n: shCalH true buttondown? if _s_pendcalm uistate ! exit then \n odn_ui odn.h helpQuad@ ; \n\n: shPendCalM true buttonup? if _s_calm uistate ! then ; \n: shCalM true buttondown? if _s_pendcals uistate ! exit then \n odn_ui odn.m helpQuad@ ; \n\n: shPendCalS true buttonup? if _s_cals uistate ! then ; \n: shCalS true buttondown? if \n _s_init uistate !\n odn_ui nvram! exit then \n \n odn_ui odn.s helpQuad@ ; \n\n\\ -------------------------------------------------\n\\ Helpers\n\\ -------------------------------------------------\n: helpODNClear ( -- ) \\ Set them all to zero\n odn_ui odn bounds do I off 4 +loop ; \n: helpODNMid ( -- ) \\ Set them all to 500\n odn_ui odn bounds do #750 I ! 4 +loop ; \n: helpQuad@ ( addr -- ) \\ update a location with the quadrature value\n dup @ quad@ + clip swap ! ;\n\n\ncreate StateHandlers \n' shInit , \n' shB1 ,\n' sh1sec ,\n\n' shSetH ,\n' shPendSetM , ' shSetMin ,\n\n' shPendCal0 , ' shCal0 ,\n' shPendCalH , ' shCalH , \n' shPendCalM , ' shCalM , \n' shPendCalS , ' shCalS , \n\n\\ -------------------------------------------------\n\\ Setting the time.\n\\ -------------------------------------------------\nvariable adj_i \\ THe working index into the points array.\n\nudata \ncreate adj_points #50 cells allot \\ 100 16-bit words. \ncreate interp_set _interp_set allot\ncdata \n\n\\ Generate a list of points.\n: MAKE-SET-LIST ( max steps ) \n 2dup \n >R (interp_init) swap interp_set swap R> call3--\n\n \\ Since zero is first, do the w! first.\n swap drop 0 swap \\ Keep a running counter.\n 0 do\n dup I adj_points[]! \\ Save the existing value\n interp_set interp-next + \n loop\n drop\n ;\n\n: ADJ_POINTS[]! ( data index -- ) 2* adj_points + w! ;\n: ADJ_POINTS[]@ ( index -- n ) 2* adj_points + w@ ;\n","old_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( -- )\n load-defaults \n icroot 0 over inter.rtcsem ! \\ Reset the free-running counters.\n 0 over inter.rtcdsem ! \\ Reset the free-running counters.\n\n begin \n \tdup inter.rtcsem @offex! ?dup if advancehms then\n \tdup inter.rtcdsem @offex! ?dup if advancedhms then\n [asm wfi asm]\n uiupdate if use-uivals else use-clockvals then \n key? until drop\n;\n \n\\ These two contain loops to ensure that we don't\n\\ drop any timer ticks on the floor.\n: ADVANCEHMS ( n -- ) 0 do hms advancetime loop ;\n: ADVANCEDHMS ( n -- ) 0 do dhms advancetime loop ;\n \n: LOAD-DEFAULTS ( -- )\n nvramvalid? if _nvramload then \n interp-init\n;\n\n\\ ----------------------------------------------------------\n\\ Define the structures before they get used.\n\\ ----------------------------------------------------------\nstruct ODN \\ On-Deck Needle \n\tint odn.s\n\tint odn.m\n\tint odn.h\nend-struct\n\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxsec \\ Max Value for secs+minutes\n\tint hms.maxhour \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_m \\ increment the minutes + hours\nend-struct\n\nstruct _interp_set\n\t4 cells field interp.a\n\t4 cells field interp.b\n\t4 cells field interp.c\nend-struct\n\n\\ ----------------------------------------------------------\n\\ Defaults get saved in the user data page.\n\\ ----------------------------------------------------------\n: NVRAMVALID? ( -- t\/f ) \n\\ *G See if there is valid data in the NVRAM.\n\\ ** It consists of 3 words. If any of them are \n\\ ** set to 0xffff:ffff, we go with the defaults.\n _USERDATA\n dup @ -1 <> \n over 4 + @ -1 <> and\n swap 8 + @ -1 <> and\n;\n\n: _NVRAMLOAD ( -- ) \n\\ *G Pull the needle maximums from flash.\n $C 0 do I ud@ needle_max I + ! 4 +loop \n; \n\n: NVRAM! ( addr -- )\n\\ *G Save the contents of the needle cal values.\n 0 UDPAGE_ERASE\n ( addr )\n $C 0 do dup I + @ I ud! 4 +loop\n drop \n;\n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nidata\ncreate ODN_HMS odn allot \\ On-Deck, HMS\ncreate ODN_DHMS odn allot \\ On-Deck, DHMS\ncreate ODN_UI odn allot \\ On-Deck, Generated by the UI.\ncdata\n\nidata \\ Has to match an odn.\ncreate NEEDLE_MAX #850 , #850 , #850 ,\ncdata\n\n(( \n: interp-next drop 1 ; \n: interp-reset drop .\" Reset\" ; \n\t\n))\n\n: RANGECHECK ( max n -- n or zero ) 2dup <= if 2drop 0 else swap drop then ; \n: CLIP ( n -- n) \\ Force the contents to be legal ( 0-999 )\n dup 0 < if drop 0 exit then \n dup #999 > if drop #999 then \n;\n \n: INTER-BUMP ( max old interp -- new )\n\\ *G Get the next value from the interpolator, and \n\\ ** reset the interpolator if it wraps around to zero.\n >R R@ interp-next \\ Get the max \n + rangecheck \n dup 0= if R> interp-reset else R> drop then \n ; \n\n: NFETCH ( odn off -- max old )\n\\ *G Combine the current value with the maximum.\n >R R@ \\ stash the offset.\n + @ \\ Calculate the offset address, get the current val.\n needle_max R> + @\n swap \n;\n\n: ++NEEDLE_S \\ Called every time.\n odn_hms 0 odn.s nfetch ( max old )\n\tinterp_hms interp.a inter-bump ( new )\n\todn_hms odn.s ! \n\t;\n\n: ++NEEDLE_M ( -- )\n\\ *G Every time we roll the seconds, bump the minutes and the hour\n\todn_hms 0 odn.m nfetch ( max old )\n\tinterp_hms interp.b inter-bump \n\todn_hms odn.m ! \n\n\todn_hms 0 odn.h nfetch ( max old )\n\tinterp_hms interp.c inter-bump \n\todn_hms odn.h ! \n\t;\n\n: ++NEEDLE_DS ; \\ Called every time.\n: ++NEEDLE_DM ; \\ Every time we roll the seconds.\n\n: _USE ( odn-addr -- ) \n dup odn.s w@ pwm0!\n dup odn.m w@ pwm1!\n odn.h w@ pwm2!\n ;\n\n: USE-CLOCKVALS odn_hms _use ; \n: USE-UIVALS odn_ui _use ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Quadrature\n\\ ----------------------------------------------------------\n\n_timer1 $24 + equ QUAD-IN\n\n\\ The Quadrature encoder produces two per detent.\n: QUAD@ ( -- n ) \\ Fetch and zero\n quad-in @off \n [asm sxth tos, tos asm]\n [asm asr .s tos, tos, # 1 asm] \\ Divide by two,\n ;\n \n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_ds , ' ++needle_dm , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n: ADVANCETIME ( struct-addr -- )\n dup hms.w_s @ execute \\ Invoke the official update word.\n 1 over hms.subsec +! \\ Increment\n dup hms.subsec @\n over hms.maxsubsec @ < if drop exit then \\ If less then max, we're done\n 0 over hms.subsec ! \\ Reset the subsecs \n\n 1 over hms.s +!\n dup hms.s @ over hms.maxsec @ < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n dup hms.w_m @ execute\n 1 over hms.m +!\n dup hms.m @ over hms.maxsec @ < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ over hms.maxhour @ < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ----------------------------------------------------------\n\\ The interpolator. \n\\ Implement bresenhams algorithm. All of this code already\n\\ exists in C, but we'll own the data structures. They contain\n\\ A total of 4 words - fixed, err, num, & denom\n\\ ----------------------------------------------------------\nudata \ncreate interp_hms _interp_set allot\ncreate interp_dhms _interp_set allot \ncdata\n\n#16 #60 * equ raw_sec\n#10 #100 * equ raw_dsec\n\n: INTERP-INIT ( -- )\n (interp_init) interp_hms\n 2dup interp.a needle_max @ raw_sec call3-- \n 2dup interp.b needle_max 4 + @ #60 call3-- \n interp.c needle_max 8 + @ #12 call3--\n\n (interp_init) interp_dhms\n 2dup interp.a needle_max @ raw_dsec call3-- \n 2dup interp.b needle_max 4 + @ #100 call3-- \n interp.c needle_max 8 + @ #10 call3--\n;\n\n\\ Call the reset fn.\n: INTERP-RESET ( interp_addr -- )\n (interp_reset) swap call1-- \n;\n\n: INTERP-NEXT ( addr -- n )\n (interp_next) swap call1--n\n;\n\n\n\\ ============================ UNTESTED =======================\n\\ VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n\n\\ ----------------------------------------------------------\n\\ User Interface\n\\ ----------------------------------------------------------\nvariable uistate\nvariable uicount \n\n_GPIO $64 + equ _BUTTONIO\n: BUTTONUP? ( -- t\/f ) _buttonio @ 1 and ; \n: BUTTONDOWN? ( -- t\/f ) buttonup? 1 xor ; \n\n\\ The wrapper for all of the UI stuff.\n\\ Returns true if the UI is active - ie, use the values generated by the UI.\n: UIUPDATE ( -- t\/f )\n StateHandlers uistate @ + @ execute \n; \n\n: uitest \n uistate @ 4 \/ . .\" ->\" uiupdate uistate @ 4 \/ .\n uicount @ . if .\" True\" else .\" False\" then \n; \n\n\\ -----------------------------------------------\n\\ State numbers. These are defined x4 so that\n\\ we can just use the state number as an index \n\\ into a table of words.\n\\ -----------------------------------------------\n0 4 * equ _s_init\n1 4 * equ _s_b1\n2 4 * equ _s_1sec\n\n3 4 * equ _s_set_h\n4 4 * equ _s_pendset_m\n5 4 * equ _s_setmin\n\n6 4 * equ _s_pendcal0\n7 4 * equ _s_cal0\n8 4 * equ _s_pendcalh\n9 4 * equ _s_calh\n10 4 * equ _s_pendcalm\n11 4 * equ _s_calm\n12 4 * equ _s_pendcals\n13 4 * equ _s_cals\n\n4 equ downcount_1s\n16 equ downcount_3s \n\n\\ All of the state handlers.\n\\ Everybody needs to know the state of the button, so that must\n\\ get passed in, thus they all look like this:\n\\ state ( t\/f -- t\/f )\n: shInit false \n buttondown? if \n _s_b1 uistate !\n uicount off \\ Reset this.\n then\n ;\n\n\\ Waiting for a full second to go by.\n: shB1 false\n buttonup? if _s_init uistate ! exit then\n \\ The Button is down. \n uicount @ downcount_1s >= if\n _s_1sec uistate !\n else \n 1 uicount +!\n\tthen\n ;\n\n\\ We're in the 1 second state\n: sh1sec true \n buttonup? if _s_set_h uistate ! exit then\n uicount @ downcount_3s >= if\n _s_pendcal0 uistate !\n else \n 1 uicount +!\n\tthen \n;\n\n\\ -------------------------------------------------\n\\ Setting the time\n\\ -------------------------------------------------\n: shSetH true buttondown? if _s_pendset_m uistate ! exit then ;\n\n: shPendSetM true buttonup? if _s_setmin uistate ! then ;\n: shSetMin true buttondown? if _s_init uistate ! exit then ;\n\n\\ -------------------------------------------------\n\\ Calibration\n\\ -------------------------------------------------\n: shPendCal0 true buttonup? if _s_cal0 uistate ! helpODNClear then ;\n: shCal0 true buttondown? if _s_pendcalh uistate ! exit then ;\n\n: shPendCalH true buttonup? if _s_calh uistate ! helpODNMid then ; \n: shCalH true buttondown? if _s_pendcalm uistate ! exit then \n odn_ui odn.h helpQuad@ ; \n\n: shPendCalM true buttonup? if _s_calm uistate ! then ; \n: shCalM true buttondown? if _s_pendcals uistate ! exit then \n odn_ui odn.m helpQuad@ ; \n\n: shPendCalS true buttonup? if _s_cals uistate ! then ; \n: shCalS true buttondown? if \n _s_init uistate !\n odn_ui nvram! exit then \n \n odn_ui odn.s helpQuad@ ; \n\n\\ -------------------------------------------------\n\\ Helpers\n\\ -------------------------------------------------\n: helpODNClear ( -- ) \\ Set them all to zero\n odn_ui odn bounds do I off 4 +loop ; \n: helpODNMid ( -- ) \\ Set them all to 500\n odn_ui odn bounds do #750 I ! 4 +loop ; \n: helpQuad@ ( addr -- ) \\ update a location with the quadrature value\n dup @ quad@ + clip swap ! ;\n\n\ncreate StateHandlers \n' shInit , \n' shB1 ,\n' sh1sec ,\n\n' shSetH ,\n' shPendSetM , ' shSetMin ,\n\n' shPendCal0 , ' shCal0 ,\n' shPendCalH , ' shCalH , \n' shPendCalM , ' shCalM , \n' shPendCalS , ' shCalS , \n\n\\ -------------------------------------------------\n\\ Setting the time.\n\\ -------------------------------------------------\nvariable adj_i \\ THe working index into the points array.\n\nudata \ncreate adj_points #50 cells allot \\ 100 16-bit words. \ncreate interp_set _interp_set allot\ncdata \n\n\\ Generate a list of points.\n: MAKE-SET-LIST ( max steps ) \n 2dup \n >R (interp_init) swap interp_set swap R> call3--\n\n \\ Since zero is first, do the w! first.\n swap drop 0 swap \\ Keep a running counter.\n 0 do\n dup I adj_points[]! \\ Save the existing value\n interp_set interp-next + \n loop\n drop\n ;\n\n: ADJ_POINTS[]! ( data index -- ) 2* adj_points + w! ;\n: ADJ_POINTS[]@ ( index -- n ) 2* adj_points + w@ ;\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"3ecc5fcc78d89f3382c66793cb660f358d7127dd","subject":"New system call.","message":"New system call.","repos":"rbsexton\/sockpuppet,rbsexton\/sockpuppet","old_file":"forth\/SAPI-core.fth","new_file":"forth\/SAPI-core.fth","new_contents":"\\ Wrappers for SAPI Core functions\n\\ SVC 0: Return the version of the API in use.\n\\ SVC 1: Return the address of the shared variables table\n\\ SVC 2: putchar\n\\ SVC 3: getchar\n\\ SVC 4: charsavail\n\n\\ SVC 5: LaunchUserApp\n\\ SVC 6: Reserved\n\\ SVC 7: Reserved\n\n\\ SVC 8: Watchdog Refresh\n\\ SVC 9: Return Millisecond ticker value.\n\\ SVC 10: The number of CPU cycles consumed in the last second.\n\n\\ 2-4 are for use by the serial io routines, and are \n\\ defined elsewhere.\n\n\\ Note that the system call number is embedded into the instruction,\n\\ so this is not so easily parameterized.\n\n#0 equ SAPI_VEC_VERSION\n#1 equ SAPI_VEC_VARS\n#2 equ SAPI_VEC_PUTCHAR\n#3 equ SAPI_VEC_GETCHAR\n#4 equ SAPI_VEC_CHARSAVAIL\n#5 equ SAPI_VEC_STARTAPP\n#6 equ SAPI_VEC_PRIVMODE\n#7 equ SAPI_VEC_MPULOAD\n#8 equ SAPI_VEC_PETWATCHDOG\n#9 equ SAPI_VEC_USAGE\n#10 equ SAPI_VEC_GETMS\n#11 equ SAPI_VEC_SET_IO_CALLBACK\n\n\\ **********************************************************************\n\\ SVC 0: Return the version of the API in use.\n\\ **********************************************************************\nCODE SAPI-Version \\ -- n \n\t\\ Push TOS, and place the result there.\t\n\tsvc # SAPI_VEC_VERSION \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 1: Get the address of the shared variable list\n\\ **********************************************************************\nCODE GetSharedVars \\ -- n \n\tsvc # SAPI_VEC_VARS \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 5: Do a stack switch and startup the user App. Its a one-way\n\\ trip, so don't worry about stack cleanup.\n\\ **********************************************************************\nCODE RestartForth ( c-addr ) \\ -- \n\tmov r0, tos\n\tsvc # SAPI_VEC_STARTAPP\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 6: Request Privileged Mode. In some systems, this is a huge\n\\ Security hole.\n\\ **********************************************************************\nCODE privmode \\ -- \n\tsvc # SAPI_VEC_PRIVMODE\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 7: Ask for MPU entry updates.\n\\ **********************************************************************\nCODE MPULoad \\ -- \n\tmov r0, tos\n\tsvc # SAPI_VEC_MPULOAD\n\tldr tos, [ psp ], # $04\t\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 8: Refresh the watchdog\n\\ **********************************************************************\nCODE PetWatchDog \\ -- \n\tsvc # SAPI_VEC_PETWATCHDOG\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 9: Return Millisecond ticker value.\n\\ **********************************************************************\nCODE Ticks \\ -- n \n\tsvc # SAPI_VEC_GETMS\n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 10: The number of CPU cycles consumed in the last second.\n\\ **********************************************************************\nCODE GetUsage \\ -- n \n\tsvc # SAPI_VEC_USAGE\n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 11: Set the IO Callback address for a stream.\n\\ iovec, read\/write (r=1), address to set as zero.\n\\ Note the minor parameter swizzle here to keep the old value on TOS.\n\\ **********************************************************************\nCODE SetIOCallback \\ addr iovec read\/write -- n \n\tmov r1, tos\n\tldr r0, [ psp ], # 4 !\n\tldr r2, [ psp ], # 4 !\n \tsvc # SAPI_VEC_SET_IO_CALLBACK\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\n\n","old_contents":"\\ Wrappers for SAPI Core functions\n\\ SVC 0: Return the version of the API in use.\n\\ SVC 1: Return the address of the shared variables table\n\\ SVC 2: putchar\n\\ SVC 3: getchar\n\\ SVC 4: charsavail\n\n\\ SVC 5: LaunchUserApp\n\\ SVC 6: Reserved\n\\ SVC 7: Reserved\n\n\\ SVC 8: Watchdog Refresh\n\\ SVC 9: Return Millisecond ticker value.\n\\ SVC 10: The number of CPU cycles consumed in the last second.\n\n\\ 2-4 are for use by the serial io routines, and are \n\\ defined elsewhere.\n\n\\ Note that the system call number is embedded into the instruction,\n\\ so this is not so easily parameterized.\n\n#0 equ SAPI_VEC_VERSION\n#1 equ SAPI_VEC_VARS\n#2 equ SAPI_VEC_PUTCHAR\n#3 equ SAPI_VEC_GETCHAR\n#4 equ SAPI_VEC_CHARSAVAIL\n#5 equ SAPI_VEC_STARTAPP\n#6 equ SAPI_VEC_PRIVMODE\n#7 equ SAPI_VEC_MPULOAD\n#8 equ SAPI_VEC_PETWATCHDOG\n#9 equ SAPI_VEC_USAGE\n#10 equ SAPI_VEC_GETMS\n\n\\ **********************************************************************\n\\ SVC 0: Return the version of the API in use.\n\\ **********************************************************************\nCODE SAPI-Version \\ -- n \n\t\\ Push TOS, and place the result there.\t\n\tsvc # SAPI_VEC_VERSION \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 1: Get the address of the shared variable list\n\\ **********************************************************************\nCODE GetSharedVars \\ -- n \n\tsvc # SAPI_VEC_VARS \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 5: Do a stack switch and startup the user App. Its a one-way\n\\ trip, so don't worry about stack cleanup.\n\\ **********************************************************************\nCODE RestartForth ( c-addr ) \\ -- \n\tmov r0, tos\n\tsvc # SAPI_VEC_STARTAPP\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 6: Request Privileged Mode. In some systems, this is a huge\n\\ Security hole.\n\\ **********************************************************************\nCODE privmode \\ -- \n\tsvc # SAPI_VEC_PRIVMODE\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 7: Ask for MPU entry updates.\n\\ **********************************************************************\nCODE MPULoad \\ -- \n\tmov r0, tos\n\tsvc # SAPI_VEC_MPULOAD\n\tldr tos, [ psp ], # $04\t\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 8: Refresh the watchdog\n\\ **********************************************************************\nCODE PetWatchDog \\ -- \n\tsvc # SAPI_VEC_PETWATCHDOG\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 9: Return Millisecond ticker value.\n\\ **********************************************************************\nCODE Ticks \\ -- n \n\tsvc # SAPI_VEC_GETMS\n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ **********************************************************************\n\\ SVC 10: The number of CPU cycles consumed in the last second.\n\\ **********************************************************************\nCODE GetUsage \\ -- n \n\tsvc # SAPI_VEC_USAGE\n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"ccf6483ce250ea6e5c04a924085f5e45d7a7ed2c","subject":"Explicit floating point literals","message":"Explicit floating point literals","repos":"AshleyF\/Forthkit,AshleyF\/Forthkit,AshleyF\/Forthkit","old_file":"library\/turtle\/turtle.4th","new_file":"library\/turtle\/turtle.4th","new_contents":"( turtle graphics )\n( requires: pixels.4th )\n\nvar x var y var theta var dx var dy\n\n: point-x x @ width 2 \/ + 0.5 + int ;\n: point-y y @ height 2 \/ + 0.5 + int ;\n: valid-x point-x 0.5 width 1.0 - between ;\n: valid-y point-y 0.5 height 1.0 - between ;\n: valid valid-x valid-y and ;\n: plot valid if point-x point-y set then ;\n\n: go y ! x ! ;\n: head dup theta ! deg2rad dup cos dx ! sin dy ! ;\n: pose head go ;\n\n: begin clear 0 0 0 pose ;\n: turn theta @ + head ;\n: move times dx @ x +! dy @ y +! plot loop ;\n: jump times dx @ x +! dy @ y +! loop ;\n\n","old_contents":"( turtle graphics )\n( requires: pixels.4th )\n\nvar x var y var theta var dx var dy\n\n: point-x x @ width 2 \/ + 0.5 + int ;\n: point-y y @ height 2 \/ + 0.5 + int ;\n: valid-x point-x 0.5 width 1 - between ;\n: valid-y point-y 0.5 height 1 - between ;\n: valid valid-x valid-y and ;\n: plot valid if point-x point-y set then ;\n\n: go y ! x ! ;\n: head dup theta ! deg2rad dup cos dx ! sin dy ! ;\n: pose head go ;\n\n: begin clear 0 0 0 pose ;\n: turn theta @ + head ;\n: move times dx @ x +! dy @ y +! plot loop ;\n: jump times dx @ x +! dy @ y +! loop ;\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"297982a2ffa9fc3a3af37621ff193cd6ada982ef","subject":"Added D2* word","message":"Added D2* word\n","repos":"rm-hull\/byok3,rm-hull\/byok3","old_file":"core\/src\/main\/resources\/forth\/system.fth","new_file":"core\/src\/main\/resources\/forth\/system.fth","new_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\\n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n\n: COUNT dup 1+ swap c@ ;\n\n\\ Miscellaneous support words\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: <= ( a b -- f , true if A <= b ) > 0= ;\n: >= ( a b -- f , true if A >= b ) < 0= ;\n: NOT ( n -- !n , logical negation ) 0= ;\n: DNEGATE ( d -- -d , negate by doing 0-d )\n 0 swap -\n;\n: CELL+ ( n -- n+cell ) cell + ;\n: CELL- ( n -- n-cell ) cell - ;\n: CELL* ( n -- n*cell ) cells ;\n\n: CHAR+ ( n -- n+size_of_char ) 1+ ;\n: CHARS ( n -- n*size_of_char, don't do anything ) ; immediate\n\n\\ useful stack manipulation words\n: -ROT ( a b c -- c a b ) rot rot ;\n: 3DUP ( a b c -- a b c a b c ) 2 pick 2 pick 2 pick ;\n\n\\ ------------------------------------------------------------------\n: ID. ( nfa -- ) count 31 and type ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n\n: BETWEEN ( n lo hi -- flag , true if between lo & hi )\n >r over r> > >r\n < r> or 0=\n;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: ? ( -- ) @ . ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ ' (lit) , cell 1- , ] +\n [ ' (lit) , cell 1- invert , ] and ;\n\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n: ALLOT ( nbytes -- , allot space in dictionary ) dp +! align ;\n\n: C, ( c -- ) here c! 1 dp +! ;\n\\ : W, ( w -- ) dp @ even-up dup dp ! w! 2 dp +! ;\n\\ : , ( n -- , lay into dictionary ) align here ! cell allot ;\n\n: SEE ( -- )\n ' dup\n >body swap >size\n disassemble ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token )\n [compile] literal ( compile a call to literal )\n ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick )\n ?comp ' [compile] literal\n; immediate\n\n: (DOES>) ( xt -- , modify previous definition to execute code at xt )\n latest >body \\ get address of code for new word\n 3 cell* + \\ offset to EXIT cell in create word\n ! \\ store execution token of DOES> code in new word\n;\n\n: DOES> ( -- , define execution code for CREATE word )\n 0 [compile] literal \\ dummy literal to hold xt\n here cell- \\ address of zero in literal\n compile (does>) \\ call (DOES>) from new creation word\n >r \\ move addrz to return stack so ; doesn't see stack garbage\n [compile] ; \\ terminate part of code before does>\n r>\n :noname ( addrz xt )\n compile rdrop \\ drop a stack frame (call becomes goto)\n swap ! \\ save execution token in literal\n; immediate\n\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 )\n swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 )\n dup cell+ @ swap @ ;\n\n: 2* ( n -- n*2 )\n 2 *\n;\n: 2\/ ( n -- n\/2 )\n 2 \/\n;\n\n\n\\ define some useful constants ------------------------------\n1 0= constant FALSE\n0 0= constant TRUE\n32 constant BL\n\n\\ Stack data structure ----------------------------------------\n\\ This is a general purpose stack utility used to implement necessary\n\\ stacks for the compiler or the user. Not real fast.\n\\ These stacks grow up which is different then normal.\n\\ cell 0 - stack pointer, offset from pfa of word\n\\ cell 1 - limit for range checking\n\\ cell 2 - first data location\n\n: :STACK ( #cells -- )\n CREATE 2 cells , ( offset of first data location )\n dup , ( limit for range checking, not currently used )\n cells cell+ allot ( allot an extra cell for safety )\n;\n\n: >STACK ( n stack -- , push onto stack, postincrement )\n dup @ 2dup cell+ swap ! ( -- n stack offset )\n + !\n;\n\n: STACK> ( stack -- n , pop , predecrement )\n dup @ cell- 2dup swap !\n + @\n;\n\n: STACK@ ( stack -- n , copy )\n dup @ cell- + @\n;\n\n: STACK.PICK ( index stack -- n , grab Nth from top of stack )\n dup @ cell- +\n swap cells - \\ offset for index\n @\n;\n: STACKP ( stack -- ptr , to next empty location on stack )\n dup @ +\n;\n\n: 0STACKP ( stack -- , clear stack)\n 8 swap !\n;\n\n32 :stack ustack\nustack 0stackp\n\n\\ Define JForth like words.\n: >US ustack >stack ;\n: US> ustack stack> ;\n: US@ ustack stack@ ;\n: 0USP ustack 0stackp ;\n\n\n\n\\ DO LOOP ------------------------------------------------\n\n3 constant do_flag\n4 constant leave_flag\n5 constant ?do_flag\n\n: DO ( -- , loop-back do_flag jump-from ?do_flag )\n ?comp\n compile (do)\n here >us do_flag >us ( for backward branch )\n; immediate\n\n: ?DO ( -- , loop-back do_flag jump-from ?do_flag , on user stack )\n ?comp\n ( leave address to set for forward branch )\n compile (?do)\n here 0 ,\n here >us do_flag >us ( for backward branch )\n >us ( for forward branch ) ?do_flag >us\n; immediate\n\n: LEAVE ( -- addr leave_flag )\n compile (leave)\n here 0 , >us\n leave_flag >us\n; immediate\n\n: LOOP-FORWARD ( -us- jump-from ?do_flag -- )\n BEGIN\n us@ leave_flag =\n us@ ?do_flag =\n OR\n WHILE\n us> leave_flag =\n IF\n us> here over - cell+ swap !\n ELSE\n us> dup\n here swap -\n cell+ swap !\n THEN\n REPEAT\n;\n\n: LOOP-BACK ( loop-addr do_flag -us- )\n us> do_flag ?pairs\n us> here - here\n !\n cell allot\n;\n\n: LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (loop)\n loop-forward loop-back\n; immediate\n\n\\ : DOTEST 5 0 do 333 . loop 888 . ;\n\\ : ?DOTEST0 0 0 ?do 333 . loop 888 . ;\n\\ : ?DOTEST1 5 0 ?do 333 . loop 888 . ;\n\n: +LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (+loop)\n loop-forward loop-back\n; immediate\n\n: UNLOOP ( loop-sys -r- )\n r> \\ save return pointer\n rdrop rdrop\n >r\n;\n\n\n: RECURSE ( ? -- ? , call the word currently being defined )\n latest compile,\n; immediate\n\n: SPACE bl emit ;\n: 0SP depth 0 ?do drop loop ;\n\n\\ : >NEWLINE ( -- , CR if needed )\n\\ out @ 0>\n\\ IF cr\n\\ THEN\n\\ ;\n\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 ) swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 ) dup cell+ @ swap @ ;\n\n: DABS ( d -- |d| )\n dup 0<\n IF dnegate\n THEN\n;\n\n: S>D ( s -- d , extend signed single precision to double )\n dup 0<\n IF -1\n ELSE 0\n THEN\n;\n\n: D>S ( d -- s ) drop ;\n\n: D2* ( d -- d*2 )\n 2* over 31 rshift or swap\n 2* swap\n;\n\n: PARSE-WORD ( \"name\" -- c-addr u ) bl parse ;\n: \/STRING ( addr len n -- addr' len' ) over min rot over + -rot - ;\n: PLACE ( addr len to -- , move string ) 3dup 1+ swap cmove c! drop ;\n\n: ASCII ( -- char, state smart )\n bl parse drop c@\n state @ 1 =\n IF [compile] literal\n ELSE\n THEN\n; immediate\n\n: CHAR ( -- char , interpret mode ) bl parse drop c@ ;\n: [CHAR] ( -- char , for compile mode )\n char [compile] literal\n; immediate\n\n: $TYPE ( $string -- ) count type ;\n: 'word ( -- addr ) here ;\n\n: EVEN ( addr -- addr' ) dup 1 and + ;\n\n: (C\") ( -- $addr ) r> dup count + aligned >r ;\n: (S\") ( -- c-addr cnt ) r> count 2dup + aligned >r ;\n: (.\") ( -- , type following string ) r> count 2dup + aligned >r type ;\n: \", ( addr len -- , place string into dict ) tuck 'word place 1+ allot align ;\n: ,\" ( -- ) [char] \" parse \", ;\n\n: .( ( --, type string delimited by parens )\n [char] ) parse type\n; immediate\n\n: .\" ( -- , type string )\n state @ 1 =\n IF compile (.\") ,\"\n ELSE [char] \" parse type\n THEN\n; immediate\n\n: .' ( -- , type string delimited by single quote )\n state @\n IF compile (.\") [char] ' parse \",\n ELSE [char] ' parse type\n THEN\n; immediate\n\n: C\" ( -- addr , return string address, ANSI )\n state @\n IF compile (c\") ,\"\n ELSE [char] \" parse pad place pad\n THEN\n; immediate\n\n: S\" ( -- , -- addr , return string address, ANSI )\n state @\n IF compile (s\") ,\"\n ELSE [char] \" parse pad place pad count\n THEN\n; immediate\n\n: \" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n: P\" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n\n: \"\" ( -- addr )\n state @\n IF\n compile (C\")\n bl parse-word \",\n ELSE\n bl parse-word pad place pad\n THEN\n; immediate\n\n: SLITERAL ( addr cnt -- , compile string )\n compile (S\")\n \",\n; IMMEDIATE\n\n: $APPEND ( addr count $1 -- , append text to $1 )\n over >r\n dup >r\n count + ( -- a2 c2 end1 )\n swap cmove\n r> dup c@ ( a1 c1 )\n r> + ( -- a1 totalcount )\n swap c!\n;\n\n\\ ANSI word to replace [COMPILE] and COMPILE ----------------\n: POSTPONE ( -- )\n\tbl word find\n\tdup\n 0= -13 ?ERROR\n 0>\n IF compile, \\ immediate\n ELSE (compile) \\ normal\n THEN\n\n; immediate\n\n\\ -----------------------------------------------------------------\n\\ Auto Initialization\n: AUTO.INIT ( -- )\n\\ Kernel finds AUTO.INIT and executes it after loading dictionary.\n\\ .\" Begin AUTO.INIT ------\" cr\n;\n: AUTO.TERM ( -- )\n\\ Kernel finds AUTO.TERM and executes it on bye.\n\\ .\" End AUTO.TERM ------\" cr\n;\n\n: INCLUDE? ( -- , load file if word not defined )\n bl word find\n IF drop bl word drop ( eat word from source )\n ELSE drop include\n THEN\n; immediate\n\n: CLEARSTACK ( i*x -- )\n BEGIN depth\n WHILE drop\n REPEAT ;\n\nvariable pictured_output \\ hidden?\nvariable pictured_output_len \\ hidden?\n\n: <# ( -- ) pad pictured_output ! 0 pictured_output_len ! ;\n: #> ( -- addr n ) drop pictured_output @ pictured_output_len @ ;\n\n: HOLD ( c -- )\n pictured_output @ dup dup 1+ pictured_output_len @ cmove c!\n 1 pictured_output_len +!\n;\n\n\\ ------------------------ INPUT -------------------------------\n\n: SIGN ( n -- ) < 0 IF 45 hold THEN\n;\n\n: DIGIT ( n -- ascii )\n dup 10 < IF 48 ELSE 87 THEN + ;\n\n: # ( n -- n )\n base @ \/mod swap digit hold ;\n\n: #S ( n -- )\n BEGIN base @ \/mod dup\n WHILE swap digit hold\n REPEAT\n digit hold ;\n\n\n: LWORD ( char -- addr )\n parse-word here place here \\ 00002 , use PARSE-WORD\n;\n\n: (WARNING\") ( flag $message -- )\n swap\n IF count type\n ELSE drop\n THEN\n;\n\n: WARNING\" ( flag -- , print warning if true. )\n [compile] \" ( compile message )\n state @\n IF compile (warning\")\n ELSE (warning\")\n THEN\n; IMMEDIATE\n\n: ABORT\" ( flag -- , print warning if true. )\n [compile] \" ( compile message )\n state @\n IF compile (abort\")\n ELSE (abort\")\n THEN\n; IMMEDIATE\n\n: DEFER ( \"name\" -- )\n CREATE ['] ABORT ,\n DOES> ( ... -- ... ) @ EXECUTE ;\n\n: DEFER! ( xt2 xt1 -- )\n >BODY 4 CELL* + ! ;\n\n: DEFER@ ( xt1 -- xt2 )\n >BODY 4 CELL* + @ ;\n\n: IS ( xt \"name\" -- , Skip leading spaces and parse name delimited by a space. Set name to execute xt. )\n STATE @ IF\n POSTPONE ['] POSTPONE DEFER!\n ELSE\n ' DEFER!\n THEN ; IMMEDIATE\n\n\n\\ : $ ( -- N , convert next number as hex )\n\\ base @ hex\n\\ 32 lword number? num_type_single = not\n\\ abort\" Not a single number!\"\n\\ swap base !\n\\ state @\n\\ IF [compile] literal\n\\ THEN\n\\ ; immediate","old_contents":": ( 41 parse 2drop ; immediate\n( That was the definition for the comment word. )\n( Now we can add comments to what we are doing! )\n( Note: default decimal numeric input mode. )\n\n: \\ ( -- , comment out the rest of line)\n 13 parse 2drop ; immediate\n\n\\ 1 echo ! \\ Uncomment this line to echo Forth code while compiling.\n\n\\ *********************************************************************\n\\ This is another style of comment that is common in Forth.\n\\ BYOK (portmanteau of BYE & OK) is a BYO kernel which happens to\n\\ implement a forth machine on i686 bare metal.\n\\\n\\ Substantial portions of this file were lifted straight from pForth\n\\ (http:\/\/pforth.googlecode.com\/svn\/trunk\/fth\/system.fth)\n\\ *********************************************************************\n: BL 32 ;\n\n: SPACE ( -- ) bl emit ;\n: CR ( -- , cause output to appear at the beginning of the next line ) 10 emit ;\n\n: $MOVE ( $src $dst ) over c@ 1+ cmove ;\n\n: COUNT dup 1+ swap c@ ;\n\n\\ Miscellaneous support words\n: ON ( addr -- , set true ) -1 swap ! ;\n: OFF ( addr -- , set false ) 0 swap ! ;\n\n: <= ( a b -- f , true if A <= b ) > 0= ;\n: >= ( a b -- f , true if A >= b ) < 0= ;\n: NOT ( n -- !n , logical negation ) 0= ;\n: DNEGATE ( d -- -d , negate by doing 0-d )\n 0 swap -\n;\n: CELL+ ( n -- n+cell ) cell + ;\n: CELL- ( n -- n-cell ) cell - ;\n: CELL* ( n -- n*cell ) cells ;\n\n: CHAR+ ( n -- n+size_of_char ) 1+ ;\n: CHARS ( n -- n*size_of_char, don't do anything ) ; immediate\n\n\\ useful stack manipulation words\n: -ROT ( a b c -- c a b ) rot rot ;\n: 3DUP ( a b c -- a b c a b c ) 2 pick 2 pick 2 pick ;\n\n\\ ------------------------------------------------------------------\n: ID. ( nfa -- ) count 31 and type ;\n\n: BINARY 2 base ! ;\n: OCTAL 8 base ! ;\n: DECIMAL 10 base ! ;\n: HEX 16 base ! ;\n\n: MOVE$ ( a1 n a2 -- ) swap cmove ;\n\n: BETWEEN ( n lo hi -- flag , true if between lo & hi )\n >r over r> > >r\n < r> or 0=\n;\n\n: [ ( -- , enter interpreter mode ) 0 state ! ; immediate\n: ] ( -- , enter compile mode ) 1 state ! ;\n\n: ? ( -- ) @ . ;\n\n: EVEN-UP ( n -- n | n+1, make even ) dup 1 and + ;\n: ALIGNED ( addr -- a-addr )\n [ ' (lit) , cell 1- , ] +\n [ ' (lit) , cell 1- invert , ] and ;\n\n: ALIGN ( -- , align DP ) dp @ aligned dp ! ;\n: ALLOT ( nbytes -- , allot space in dictionary ) dp +! align ;\n\n: C, ( c -- ) here c! 1 dp +! ;\n\\ : W, ( w -- ) dp @ even-up dup dp ! w! 2 dp +! ;\n\\ : , ( n -- , lay into dictionary ) align here ! cell allot ;\n\n: SEE ( -- )\n ' dup\n >body swap >size\n disassemble ;\n\n\\ Compiler support -------------------------------------------------\n: COMPILE, ( xt -- , compile call to xt ) , ;\n: [COMPILE] ( -- , compile now even if immediate ) ' compile, ; immediate\n: (COMPILE) ( xt -- , postpone compilation of token )\n [compile] literal ( compile a call to literal )\n ( store xt of word to be compiled )\n\n [ ' compile, ] literal \\ compile call to compile,\n compile, ;\n\n: COMPILE ( --, save xt and compile later ) ' (compile) ; immediate\n\n\\ Error codes defined in ANSI Exception word set -------------------\n: ERR_ABORT -1 ;\n: ERR_ABORTQ -2 ;\n: ERR_EXECUTING -14 ;\n: ERR_PAIRS -22 ;\n\n: ABORT ( i*x -- ) err_abort throw ;\n\n\\ Conditionals in '83 form -----------------------------------------\n: CONDITIONAL_KEY ( -- , lazy constant ) 29521 ;\n: ?CONDITION ( f -- ) conditional_key - err_pairs ?error ;\n: >MARK ( -- addr ) here 0 , ;\n: >RESOLVE ( addr -- ) here over - swap ! ;\n: mark ; immediate\n: THEN ( f orig -- ) swap ?condition >resolve ; immediate\n: BEGIN ( -- f dest ) ?comp conditional_key mark ; immediate\n\n\\ Conditionals built from primitives -------------------------------\n: ELSE ( f orig1 -- f orig2 ) [compile] ahead 2swap [compile] then ; immediate\n: WHILE ( f dest -- f origi f dest ) [compile] if 2swap ; immediate\n: REPEAT ( -- f orig f dest ) [compile] again [compile] then ; immediate\n\n: ['] ( -- xt , define compile time tick )\n ?comp ' [compile] literal\n; immediate\n\n: (DOES>) ( xt -- , modify previous definition to execute code at xt )\n latest >body \\ get address of code for new word\n 3 cell* + \\ offset to EXIT cell in create word\n ! \\ store execution token of DOES> code in new word\n;\n\n: DOES> ( -- , define execution code for CREATE word )\n 0 [compile] literal \\ dummy literal to hold xt\n here cell- \\ address of zero in literal\n compile (does>) \\ call (DOES>) from new creation word\n >r \\ move addrz to return stack so ; doesn't see stack garbage\n [compile] ; \\ terminate part of code before does>\n r>\n :noname ( addrz xt )\n compile rdrop \\ drop a stack frame (call becomes goto)\n swap ! \\ save execution token in literal\n; immediate\n\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 )\n swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 )\n dup cell+ @ swap @ ;\n\n: 2* ( n -- n*2 )\n 2 *\n;\n: 2\/ ( n -- n\/2 )\n 2 \/\n;\n\n\n\\ define some useful constants ------------------------------\n1 0= constant FALSE\n0 0= constant TRUE\n32 constant BL\n\n\\ Stack data structure ----------------------------------------\n\\ This is a general purpose stack utility used to implement necessary\n\\ stacks for the compiler or the user. Not real fast.\n\\ These stacks grow up which is different then normal.\n\\ cell 0 - stack pointer, offset from pfa of word\n\\ cell 1 - limit for range checking\n\\ cell 2 - first data location\n\n: :STACK ( #cells -- )\n CREATE 2 cells , ( offset of first data location )\n dup , ( limit for range checking, not currently used )\n cells cell+ allot ( allot an extra cell for safety )\n;\n\n: >STACK ( n stack -- , push onto stack, postincrement )\n dup @ 2dup cell+ swap ! ( -- n stack offset )\n + !\n;\n\n: STACK> ( stack -- n , pop , predecrement )\n dup @ cell- 2dup swap !\n + @\n;\n\n: STACK@ ( stack -- n , copy )\n dup @ cell- + @\n;\n\n: STACK.PICK ( index stack -- n , grab Nth from top of stack )\n dup @ cell- +\n swap cells - \\ offset for index\n @\n;\n: STACKP ( stack -- ptr , to next empty location on stack )\n dup @ +\n;\n\n: 0STACKP ( stack -- , clear stack)\n 8 swap !\n;\n\n32 :stack ustack\nustack 0stackp\n\n\\ Define JForth like words.\n: >US ustack >stack ;\n: US> ustack stack> ;\n: US@ ustack stack@ ;\n: 0USP ustack 0stackp ;\n\n\n\n\\ DO LOOP ------------------------------------------------\n\n3 constant do_flag\n4 constant leave_flag\n5 constant ?do_flag\n\n: DO ( -- , loop-back do_flag jump-from ?do_flag )\n ?comp\n compile (do)\n here >us do_flag >us ( for backward branch )\n; immediate\n\n: ?DO ( -- , loop-back do_flag jump-from ?do_flag , on user stack )\n ?comp\n ( leave address to set for forward branch )\n compile (?do)\n here 0 ,\n here >us do_flag >us ( for backward branch )\n >us ( for forward branch ) ?do_flag >us\n; immediate\n\n: LEAVE ( -- addr leave_flag )\n compile (leave)\n here 0 , >us\n leave_flag >us\n; immediate\n\n: LOOP-FORWARD ( -us- jump-from ?do_flag -- )\n BEGIN\n us@ leave_flag =\n us@ ?do_flag =\n OR\n WHILE\n us> leave_flag =\n IF\n us> here over - cell+ swap !\n ELSE\n us> dup\n here swap -\n cell+ swap !\n THEN\n REPEAT\n;\n\n: LOOP-BACK ( loop-addr do_flag -us- )\n us> do_flag ?pairs\n us> here - here\n !\n cell allot\n;\n\n: LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (loop)\n loop-forward loop-back\n; immediate\n\n\\ : DOTEST 5 0 do 333 . loop 888 . ;\n\\ : ?DOTEST0 0 0 ?do 333 . loop 888 . ;\n\\ : ?DOTEST1 5 0 ?do 333 . loop 888 . ;\n\n: +LOOP ( -- , loop-back do_flag jump-from ?do_flag )\n compile (+loop)\n loop-forward loop-back\n; immediate\n\n: UNLOOP ( loop-sys -r- )\n r> \\ save return pointer\n rdrop rdrop\n >r\n;\n\n\n: RECURSE ( ? -- ? , call the word currently being defined )\n latest compile,\n; immediate\n\n: SPACE bl emit ;\n: 0SP depth 0 ?do drop loop ;\n\n\\ : >NEWLINE ( -- , CR if needed )\n\\ out @ 0>\n\\ IF cr\n\\ THEN\n\\ ;\n\n\n: 2! ( x1 x2 addr -- , store x2 followed by x1 ) swap over ! cell+ ! ;\n: 2@ ( addr -- x1 x2 ) dup cell+ @ swap @ ;\n\n: DABS ( d -- |d| )\n dup 0<\n IF dnegate\n THEN\n;\n\n: S>D ( s -- d , extend signed single precision to double )\n dup 0<\n IF -1\n ELSE 0\n THEN\n;\n\n: D>S ( d -- s ) drop ;\n\n: PARSE-WORD ( \"name\" -- c-addr u ) bl parse ;\n: \/STRING ( addr len n -- addr' len' ) over min rot over + -rot - ;\n: PLACE ( addr len to -- , move string ) 3dup 1+ swap cmove c! drop ;\n\n: ASCII ( -- char, state smart )\n bl parse drop c@\n state @ 1 =\n IF [compile] literal\n ELSE\n THEN\n; immediate\n\n: CHAR ( -- char , interpret mode ) bl parse drop c@ ;\n: [CHAR] ( -- char , for compile mode )\n char [compile] literal\n; immediate\n\n: $TYPE ( $string -- ) count type ;\n: 'word ( -- addr ) here ;\n\n: EVEN ( addr -- addr' ) dup 1 and + ;\n\n: (C\") ( -- $addr ) r> dup count + aligned >r ;\n: (S\") ( -- c-addr cnt ) r> count 2dup + aligned >r ;\n: (.\") ( -- , type following string ) r> count 2dup + aligned >r type ;\n: \", ( addr len -- , place string into dict ) tuck 'word place 1+ allot align ;\n: ,\" ( -- ) [char] \" parse \", ;\n\n: .( ( --, type string delimited by parens )\n [char] ) parse type\n; immediate\n\n: .\" ( -- , type string )\n state @ 1 =\n IF compile (.\") ,\"\n ELSE [char] \" parse type\n THEN\n; immediate\n\n: .' ( -- , type string delimited by single quote )\n state @\n IF compile (.\") [char] ' parse \",\n ELSE [char] ' parse type\n THEN\n; immediate\n\n: C\" ( -- addr , return string address, ANSI )\n state @\n IF compile (c\") ,\"\n ELSE [char] \" parse pad place pad\n THEN\n; immediate\n\n: S\" ( -- , -- addr , return string address, ANSI )\n state @\n IF compile (s\") ,\"\n ELSE [char] \" parse pad place pad count\n THEN\n; immediate\n\n: \" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n: P\" ( -- , -- addr , return string address )\n [compile] C\"\n; immediate\n\n: \"\" ( -- addr )\n state @\n IF\n compile (C\")\n bl parse-word \",\n ELSE\n bl parse-word pad place pad\n THEN\n; immediate\n\n: SLITERAL ( addr cnt -- , compile string )\n compile (S\")\n \",\n; IMMEDIATE\n\n: $APPEND ( addr count $1 -- , append text to $1 )\n over >r\n dup >r\n count + ( -- a2 c2 end1 )\n swap cmove\n r> dup c@ ( a1 c1 )\n r> + ( -- a1 totalcount )\n swap c!\n;\n\n\\ ANSI word to replace [COMPILE] and COMPILE ----------------\n: POSTPONE ( -- )\n\tbl word find\n\tdup\n 0= -13 ?ERROR\n 0>\n IF compile, \\ immediate\n ELSE (compile) \\ normal\n THEN\n\n; immediate\n\n\\ -----------------------------------------------------------------\n\\ Auto Initialization\n: AUTO.INIT ( -- )\n\\ Kernel finds AUTO.INIT and executes it after loading dictionary.\n\\ .\" Begin AUTO.INIT ------\" cr\n;\n: AUTO.TERM ( -- )\n\\ Kernel finds AUTO.TERM and executes it on bye.\n\\ .\" End AUTO.TERM ------\" cr\n;\n\n: INCLUDE? ( -- , load file if word not defined )\n bl word find\n IF drop bl word drop ( eat word from source )\n ELSE drop include\n THEN\n; immediate\n\n: CLEARSTACK ( i*x -- )\n BEGIN depth\n WHILE drop\n REPEAT ;\n\nvariable pictured_output \\ hidden?\nvariable pictured_output_len \\ hidden?\n\n: <# ( -- ) pad pictured_output ! 0 pictured_output_len ! ;\n: #> ( -- addr n ) drop pictured_output @ pictured_output_len @ ;\n\n: HOLD ( c -- )\n pictured_output @ dup dup 1+ pictured_output_len @ cmove c!\n 1 pictured_output_len +!\n;\n\n\\ ------------------------ INPUT -------------------------------\n\n: SIGN ( n -- ) < 0 IF 45 hold THEN\n;\n\n: DIGIT ( n -- ascii )\n dup 10 < IF 48 ELSE 87 THEN + ;\n\n: # ( n -- n )\n base @ \/mod swap digit hold ;\n\n: #S ( n -- )\n BEGIN base @ \/mod dup\n WHILE swap digit hold\n REPEAT\n digit hold ;\n\n\n: LWORD ( char -- addr )\n parse-word here place here \\ 00002 , use PARSE-WORD\n;\n\n: (WARNING\") ( flag $message -- )\n swap\n IF count type\n ELSE drop\n THEN\n;\n\n: WARNING\" ( flag -- , print warning if true. )\n [compile] \" ( compile message )\n state @\n IF compile (warning\")\n ELSE (warning\")\n THEN\n; IMMEDIATE\n\n: ABORT\" ( flag -- , print warning if true. )\n [compile] \" ( compile message )\n state @\n IF compile (abort\")\n ELSE (abort\")\n THEN\n; IMMEDIATE\n\n: DEFER ( \"name\" -- )\n CREATE ['] ABORT ,\n DOES> ( ... -- ... ) @ EXECUTE ;\n\n: DEFER! ( xt2 xt1 -- )\n >BODY 4 CELL* + ! ;\n\n: DEFER@ ( xt1 -- xt2 )\n >BODY 4 CELL* + @ ;\n\n: IS ( xt \"name\" -- , Skip leading spaces and parse name delimited by a space. Set name to execute xt. )\n STATE @ IF\n POSTPONE ['] POSTPONE DEFER!\n ELSE\n ' DEFER!\n THEN ; IMMEDIATE\n\n\n\\ : $ ( -- N , convert next number as hex )\n\\ base @ hex\n\\ 32 lword number? num_type_single = not\n\\ abort\" Not a single number!\"\n\\ swap base !\n\\ state @\n\\ IF [compile] literal\n\\ THEN\n\\ ; immediate","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"0b5c550021509295049c4582bad9db5426c1644e","subject":"Revert to 1.8","message":"Revert to 1.8\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/loader.4th","new_file":"sys\/boot\/forth\/loader.4th","new_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\ns\" arch-alpha\" environment? [if] [if]\n\ts\" loader_version\" environment? [if]\n\t\t3 < [if]\n\t\t\t.( Loader version 0.3+ required) cr\n\t\t\tabort\n\t\t[then]\n\t[else]\n\t\t.( Could not get loader version!) cr\n\t\tabort\n\t[then]\n[then] [then]\n\ns\" arch-i386\" environment? [if] [if]\n\ts\" loader_version\" environment? [if]\n\t\t8 < [if]\n\t\t\t.( Loader version 0.8+ required) cr\n\t\t\tabort\n\t\t[then]\n\t[else]\n\t\t.( Could not get loader version!) cr\n\t\tabort\n\t[then]\n[then] [then]\n\ninclude \/boot\/support.4th\n\nonly forth definitions also support-functions\n\n\\ ***** boot-conf\n\\\n\\\tPrepares to boot as specified by loaded configuration files.\n\nalso support-functions definitions\n\n: bootpath s\" \/boot\/\" ;\n: modulepath s\" module_path\" ;\n: saveenv ( addr len | 0 -1 -- addr' len | 0 -1 )\n dup -1 = if exit then\n dup allocate abort\" Out of memory\"\n swap 2dup 2>r\n move\n 2r>\n;\n: freeenv ( addr len | 0 -1 )\n -1 = if drop else free abort\" Freeing error\" then\n;\n: restoreenv ( addr len | 0 -1 -- )\n dup -1 = if ( it wasn't set )\n 2drop\n modulepath unsetenv\n else\n over >r\n modulepath setenv\n r> free abort\" Freeing error\"\n then\n;\n\nonly forth also support-functions also builtins definitions\n\n: boot-conf ( args 1 | 0 \"args\" -- flag )\n 0 1 unload drop\n\n 0= if ( interpreted )\n \\ Get next word on the command line\n bl word count\n ?dup 0= if ( there wasn't anything )\n drop 0\n else ( put in the number of strings )\n 1\n then\n then ( interpreted )\n\n if ( there are arguments )\n \\ Try to load the kernel\n s\" kernel_options\" getenv dup -1 = if drop 2dup 1 else 2over 2 then\n\n 1 load if ( load command failed )\n \\ Remove garbage from the stack\n\n \\ Set the environment variable module_path, and try loading\n \\ the kernel again.\n\n \\ First, save module_path value\n modulepath getenv saveenv dup -1 = if 0 swap then 2>r\n\n \\ Sets the new value\n 2dup modulepath setenv\n\n \\ Try to load the kernel\n s\" load ${kernel} ${kernel_options}\" ['] evaluate catch\n if ( load failed yet again )\n\t\\ Remove garbage from the stack\n\t2drop\n\n\t\\ Try prepending \/boot\/\n\tbootpath 2over nip over + allocate\n\tif ( out of memory )\n\t 2drop 2drop\n\t 2r> restoreenv\n\t 100 exit\n\tthen\n\n\t0 2swap strcat 2swap strcat\n\t2dup modulepath setenv\n\n\tdrop free if ( freeing memory error )\n\t 2drop\n\t 2r> restoreenv\n\t 100 exit\n\tthen\n \n\t\\ Now, once more, try to load the kernel\n\ts\" load ${kernel} ${kernel_options}\" ['] evaluate catch\n\tif ( failed once more )\n\t 2drop\n\t 2r> restoreenv\n\t 100 exit\n\tthen\n\n else ( we found the kernel on the path passed )\n\n\t2drop ( discard command line arguments )\n\n then ( could not load kernel from directory passed )\n\n \\ Load the remaining modules, if the kernel was loaded at all\n ['] load_modules catch if 2r> restoreenv 100 exit then\n\n \\ Call autoboot to perform the booting\n 0 1 autoboot\n\n \\ Keep new module_path\n 2r> freeenv\n\n exit\n then ( could not load kernel with name passed )\n\n 2drop ( discard command line arguments )\n\n else ( try just a straight-forward kernel load )\n s\" load ${kernel} ${kernel_options}\" ['] evaluate catch\n if ( kernel load failed ) 2drop 100 exit then\n\n then ( there are command line arguments )\n\n \\ Load the remaining modules, if the kernel was loaded at all\n ['] load_modules catch if 100 exit then\n\n \\ Call autoboot to perform the booting\n 0 1 autoboot\n;\n\nalso forth definitions\nbuiltin: boot-conf\nonly forth definitions also support-functions\n\n\\ ***** check-password\n\\\n\\\tIf a password was defined, execute autoboot and ask for\n\\\tpassword if autoboot returns.\n\n: check-password\n password .addr @ if\n 0 autoboot\n false >r\n begin\n bell emit bell emit\n .\" Password: \"\n password .len @ read-password\n dup password .len @ = if\n 2dup password .addr @ password .len @\n compare 0= if r> drop true >r then\n then\n drop free drop\n r@\n until\n r> drop\n then\n;\n\n\\ ***** start\n\\\n\\ Initializes support.4th global variables, sets loader_conf_files,\n\\ process conf files, and, if any one such file was succesfully\n\\ read to the end, load kernel and modules.\n\n: start ( -- ) ( throws: abort & user-defined )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n \\ Will *NOT* try to load kernel and modules if no configuration file\n \\ was succesfully loaded!\n any_conf_read? if\n load_kernel\n load_modules\n then\n;\n\n\\ ***** initialize\n\\\n\\\tOverrides support.4th initialization word with one that does\n\\\teverything start one does, short of loading the kernel and\n\\\tmodules. Returns a flag\n\n: initialize ( -- flag )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n any_conf_read?\n;\n\n\\ ***** read-conf\n\\\n\\\tRead a configuration file, whose name was specified on the command\n\\\tline, if interpreted, or given on the stack, if compiled in.\n\n: (read-conf) ( addr len -- )\n conf_files .addr @ ?dup if free abort\" Fatal error freeing memory\" then\n strdup conf_files .len ! conf_files .addr !\n include_conf_files \\ Will recurse on new loader_conf_files definitions\n;\n\n: read-conf ( | addr len -- ) ( throws: abort & user-defined )\n state @ if\n \\ Compiling\n postpone (read-conf)\n else\n \\ Interpreting\n bl parse (read-conf)\n then\n; immediate\n\n\\ ***** enable-module\n\\\n\\ Turn a module loading on.\n\n: enable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n true r> module.flag !\n .\" will be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** disable-module\n\\\n\\ Turn a module loading off.\n\n: disable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n false r> module.flag !\n .\" will not be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** toggle-module\n\\\n\\ Turn a module loading on\/off.\n\n: toggle-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n r@ module.flag @ 0= dup r> module.flag !\n if\n .\" will be loaded.\" cr\n else\n .\" will not be loaded.\" cr\n then\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** show-module\n\\\n\\\tShow loading information about a module.\n\n: show-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n .\" Name: \" r@ module.name dup .addr @ swap .len @ type cr\n .\" Path: \" r@ module.loadname dup .addr @ swap .len @ type cr\n .\" Type: \" r@ module.type dup .addr @ swap .len @ type cr\n .\" Flags: \" r@ module.args dup .addr @ swap .len @ type cr\n .\" Before load: \" r@ module.beforeload dup .addr @ swap .len @ type cr\n .\" After load: \" r@ module.afterload dup .addr @ swap .len @ type cr\n .\" Error: \" r@ module.loaderror dup .addr @ swap .len @ type cr\n .\" Status: \" r> module.flag @ if .\" Load\" else .\" Don't load\" then cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ Words to be used inside configuration files\n\n: retry false ; \\ For use in load error commands\n: ignore true ; \\ For use in load error commands\n\n\\ Return to strict forth vocabulary\n\nonly forth also\n\n","old_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\n\\ s\" arch-alpha\" environment? [if] [if]\n\\\ts\" loader_version\" environment? [if]\n\\\t\t3 < [if]\n\\\t\t\t.( Loader version 0.3+ required) cr\n\\\t\t\tabort\n\\\t\t[then]\n\\\t[else]\n\\\t\t.( Could not get loader version!) cr\n\\\t\tabort\n\\\t[then]\n\\ [then] [then]\n\n\\ s\" arch-i386\" environment? [if] [if]\n\\\ts\" loader_version\" environment? [if]\n\\\t\t8 < [if]\n\\\t\t\t.( Loader version 0.8+ required) cr\n\\\t\t\tabort\n\\\t\t[then]\n\\\t[else]\n\\\t\t.( Could not get loader version!) cr\n\\\t\tabort\n\\\t[then]\n\\ [then] [then]\n\ninclude \/boot\/support.4th\n\nonly forth definitions also support-functions\n\n\\ ***** boot-conf\n\\\n\\\tPrepares to boot as specified by loaded configuration files.\n\nalso support-functions definitions\n\n: bootpath s\" \/boot\/\" ;\n: modulepath s\" module_path\" ;\n: saveenv ( addr len | 0 -1 -- addr' len | 0 -1 )\n dup -1 = if exit then\n dup allocate abort\" Out of memory\"\n swap 2dup 2>r\n move\n 2r>\n;\n: freeenv ( addr len | 0 -1 )\n -1 = if drop else free abort\" Freeing error\" then\n;\n: restoreenv ( addr len | 0 -1 -- )\n dup -1 = if ( it wasn't set )\n 2drop\n modulepath unsetenv\n else\n over >r\n modulepath setenv\n r> free abort\" Freeing error\"\n then\n;\n\nonly forth also support-functions also builtins definitions\n\n: boot-conf ( args 1 | 0 \"args\" -- flag )\n 0 1 unload drop\n\n 0= if ( interpreted )\n \\ Get next word on the command line\n bl word count\n ?dup 0= if ( there wasn't anything )\n drop 0\n else ( put in the number of strings )\n 1\n then\n then ( interpreted )\n\n if ( there are arguments )\n \\ Try to load the kernel\n s\" kernel_options\" getenv dup -1 = if drop 2dup 1 else 2over 2 then\n\n 1 load if ( load command failed )\n \\ Remove garbage from the stack\n\n \\ Set the environment variable module_path, and try loading\n \\ the kernel again.\n\n \\ First, save module_path value\n modulepath getenv saveenv dup -1 = if 0 swap then 2>r\n\n \\ Sets the new value\n 2dup modulepath setenv\n\n \\ Try to load the kernel\n s\" load ${kernel} ${kernel_options}\" ['] evaluate catch\n if ( load failed yet again )\n\t\\ Remove garbage from the stack\n\t2drop\n\n\t\\ Try prepending \/boot\/\n\tbootpath 2over nip over + allocate\n\tif ( out of memory )\n\t 2drop 2drop\n\t 2r> restoreenv\n\t 100 exit\n\tthen\n\n\t0 2swap strcat 2swap strcat\n\t2dup modulepath setenv\n\n\tdrop free if ( freeing memory error )\n\t 2drop\n\t 2r> restoreenv\n\t 100 exit\n\tthen\n \n\t\\ Now, once more, try to load the kernel\n\ts\" load ${kernel} ${kernel_options}\" ['] evaluate catch\n\tif ( failed once more )\n\t 2drop\n\t 2r> restoreenv\n\t 100 exit\n\tthen\n\n else ( we found the kernel on the path passed )\n\n\t2drop ( discard command line arguments )\n\n then ( could not load kernel from directory passed )\n\n \\ Load the remaining modules, if the kernel was loaded at all\n ['] load_modules catch if 2r> restoreenv 100 exit then\n\n \\ Call autoboot to perform the booting\n 0 1 autoboot\n\n \\ Keep new module_path\n 2r> freeenv\n\n exit\n then ( could not load kernel with name passed )\n\n 2drop ( discard command line arguments )\n\n else ( try just a straight-forward kernel load )\n s\" load ${kernel} ${kernel_options}\" ['] evaluate catch\n if ( kernel load failed ) 2drop 100 exit then\n\n then ( there are command line arguments )\n\n \\ Load the remaining modules, if the kernel was loaded at all\n ['] load_modules catch if 100 exit then\n\n \\ Call autoboot to perform the booting\n 0 1 autoboot\n;\n\nalso forth definitions\nbuiltin: boot-conf\nonly forth definitions also support-functions\n\n\\ ***** check-password\n\\\n\\\tIf a password was defined, execute autoboot and ask for\n\\\tpassword if autoboot returns.\n\n: check-password\n password .addr @ if\n 0 autoboot\n false >r\n begin\n bell emit bell emit\n .\" Password: \"\n password .len @ read-password\n dup password .len @ = if\n 2dup password .addr @ password .len @\n compare 0= if r> drop true >r then\n then\n drop free drop\n r@\n until\n r> drop\n then\n;\n\n\\ ***** start\n\\\n\\ Initializes support.4th global variables, sets loader_conf_files,\n\\ process conf files, and, if any one such file was succesfully\n\\ read to the end, load kernel and modules.\n\n: start ( -- ) ( throws: abort & user-defined )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n \\ Will *NOT* try to load kernel and modules if no configuration file\n \\ was succesfully loaded!\n any_conf_read? if\n load_kernel\n load_modules\n then\n;\n\n\\ ***** initialize\n\\\n\\\tOverrides support.4th initialization word with one that does\n\\\teverything start one does, short of loading the kernel and\n\\\tmodules. Returns a flag\n\n: initialize ( -- flag )\n s\" \/boot\/defaults\/loader.conf\" initialize\n include_conf_files\n any_conf_read?\n;\n\n\\ ***** read-conf\n\\\n\\\tRead a configuration file, whose name was specified on the command\n\\\tline, if interpreted, or given on the stack, if compiled in.\n\n: (read-conf) ( addr len -- )\n conf_files .addr @ ?dup if free abort\" Fatal error freeing memory\" then\n strdup conf_files .len ! conf_files .addr !\n include_conf_files \\ Will recurse on new loader_conf_files definitions\n;\n\n: read-conf ( | addr len -- ) ( throws: abort & user-defined )\n state @ if\n \\ Compiling\n postpone (read-conf)\n else\n \\ Interpreting\n bl parse (read-conf)\n then\n; immediate\n\n\\ ***** enable-module\n\\\n\\ Turn a module loading on.\n\n: enable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n true r> module.flag !\n .\" will be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** disable-module\n\\\n\\ Turn a module loading off.\n\n: disable-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n false r> module.flag !\n .\" will not be loaded.\" cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** toggle-module\n\\\n\\ Turn a module loading on\/off.\n\n: toggle-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n r@ module.name dup .addr @ swap .len @ type\n r@ module.flag @ 0= dup r> module.flag !\n if\n .\" will be loaded.\" cr\n else\n .\" will not be loaded.\" cr\n then\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ ***** show-module\n\\\n\\\tShow loading information about a module.\n\n: show-module ( -- )\n bl parse module_options @ >r\n begin\n r@\n while\n 2dup\n r@ module.name dup .addr @ swap .len @\n compare 0= if\n 2drop\n .\" Name: \" r@ module.name dup .addr @ swap .len @ type cr\n .\" Path: \" r@ module.loadname dup .addr @ swap .len @ type cr\n .\" Type: \" r@ module.type dup .addr @ swap .len @ type cr\n .\" Flags: \" r@ module.args dup .addr @ swap .len @ type cr\n .\" Before load: \" r@ module.beforeload dup .addr @ swap .len @ type cr\n .\" After load: \" r@ module.afterload dup .addr @ swap .len @ type cr\n .\" Error: \" r@ module.loaderror dup .addr @ swap .len @ type cr\n .\" Status: \" r> module.flag @ if .\" Load\" else .\" Don't load\" then cr\n exit\n then\n r> module.next @ >r\n repeat\n r> drop\n type .\" wasn't found.\" cr\n;\n\n\\ Words to be used inside configuration files\n\n: retry false ; \\ For use in load error commands\n: ignore true ; \\ For use in load error commands\n\n\\ Return to strict forth vocabulary\n\nonly forth also\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"6d10504bb1b45e961639b0a63d7f29ff768073a9","subject":"LOG2 tests added","message":"LOG2 tests added\n","repos":"bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas","old_file":"KataDiversion_tests.fth","new_file":"KataDiversion_tests.fth","new_contents":"\\ KataDiversion tests, in Forth\n\\ running tests:\n\\ gforth KataDiversion_tests.fth -e bye\n\nREQUIRE KataDiversion.fth\n\nVARIABLE ASSERT-COUNT\n\n: ASSERTS-INIT ( -- )\n 0 ASSERT-COUNT ! ;\n\n: ASSERTS-RESULT ( -- )\n ASSERT-COUNT @ . .\" assertions successfully passed.\" CR ;\n\n\\ destructive assert-equal\n: ASSERT-EQUAL-D ( n1 n2 -- )\n <> IF 1 ABORT\" AssertEqual: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-equal\n: ASSERT-EQUAL ( n1 n2 -- n1 n2 )\n 2DUP ASSERT-EQUAL-D ;\n\n\\ destructive assert-true\n: ASSERT-TRUE-D ( n -- )\n 0 = IF 1 ABORT\" AssertTrue: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-true\n: ASSERT-TRUE ( n -- n )\n DUP ASSERT-TRUE-D ;\n\n\\ destructive assert-false\n: ASSERT-False-D ( n -- )\n 0 <> IF 1 ABORT\" AssertFalse: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-false\n: ASSERT-FALSE ( n -- n )\n DUP ASSERT-FALSE-D ;\n\n\\ ---- tests ----\n\nASSERTS-INIT\n\n\\ ?EMPTY\nEMPTY DEPTH 0 ASSERT-EQUAL-D\nEMPTY EMPTY DEPTH 0 ASSERT-EQUAL-D\n0 EMPTY DEPTH 0 ASSERT-EQUAL-D\n1 2 3 4 EMPTY DEPTH 0 ASSERT-EQUAL-D\n\n\\ ?NEGATIVE\n-1 ?NEG ASSERT-TRUE-D\n 0 ?NEG ASSERT-TRUE-D\n 1 ?NEG ASSERT-FALSE-D\n\n\\ ?MAX-NB\n-1 ?MAX-NB 0 ASSERT-EQUAL-D\n 0 ?MAX-NB 0 ASSERT-EQUAL-D\n 1 ?MAX-NB 2 ASSERT-EQUAL-D\n 2 ?MAX-NB 4 ASSERT-EQUAL-D\n 3 ?MAX-NB 8 ASSERT-EQUAL-D\n\n\\ LOG2\n 1 LOG2 0 ASSERT-EQUAL-D\n 2 LOG2 1 ASSERT-EQUAL-D\n 3 LOG2 1 ASSERT-EQUAL-D\n 4 LOG2 2 ASSERT-EQUAL-D\n 5 LOG2 2 ASSERT-EQUAL-D\n 8 LOG2 3 ASSERT-EQUAL-D\n42 LOG2 5 ASSERT-EQUAL-D\n\n\n\nASSERTS-RESULT\n\\ ---------\n\n\n","old_contents":"\\ KataDiversion tests, in Forth\n\\ running tests:\n\\ gforth KataDiversion_tests.fth -e bye\n\nREQUIRE KataDiversion.fth\n\nVARIABLE ASSERT-COUNT\n\n: ASSERTS-INIT ( -- )\n 0 ASSERT-COUNT ! ;\n\n: ASSERTS-RESULT ( -- )\n ASSERT-COUNT @ . .\" assertions successfully passed.\" CR ;\n\n\\ destructive assert-equal\n: ASSERT-EQUAL-D ( n1 n2 -- )\n <> IF 1 ABORT\" AssertEqual: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-equal\n: ASSERT-EQUAL ( n1 n2 -- n1 n2 )\n 2DUP ASSERT-EQUAL-D ;\n\n\\ destructive assert-true\n: ASSERT-TRUE-D ( n -- )\n 0 = IF 1 ABORT\" AssertTrue: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-true\n: ASSERT-TRUE ( n -- n )\n DUP ASSERT-TRUE-D ;\n\n\\ destructive assert-false\n: ASSERT-False-D ( n -- )\n 0 <> IF 1 ABORT\" AssertFalse: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-false\n: ASSERT-FALSE ( n -- n )\n DUP ASSERT-FALSE-D ;\n\n\\ ---- tests ----\n\nASSERTS-INIT\n\n\\ ?EMPTY\nEMPTY DEPTH 0 ASSERT-EQUAL-D\nEMPTY EMPTY DEPTH 0 ASSERT-EQUAL-D\n0 EMPTY DEPTH 0 ASSERT-EQUAL-D\n1 2 3 4 EMPTY DEPTH 0 ASSERT-EQUAL-D\n\n\\ ?NEGATIVE\n-1 ?NEG ASSERT-TRUE-D\n 0 ?NEG ASSERT-TRUE-D\n 1 ?NEG ASSERT-FALSE-D\n\n\\ ?MAX-NB\n-1 ?MAX-NB 0 ASSERT-EQUAL-D\n 0 ?MAX-NB 0 ASSERT-EQUAL-D\n 1 ?MAX-NB 2 ASSERT-EQUAL-D\n 2 ?MAX-NB 4 ASSERT-EQUAL-D\n 3 ?MAX-NB 8 ASSERT-EQUAL-D\n\n\nASSERTS-RESULT\n\\ ---------\n\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"5eacccc1823eb4be3cf53b1f77d742ac83224905","subject":"logical equivalence of lists","message":"logical equivalence of lists\n","repos":"cooper\/ferret","old_file":"std\/Extension\/List.frt","new_file":"std\/Extension\/List.frt","new_contents":"class List \n\n#> Represents a list with an event number of elements, treated as pairs.\n#| This is similar to a hash with ordered keys.\ntype Pairs {\n isa *class\n satisfies .length.even\n}\n\n#> True if the list is empty.\n.empty -> @length == 0\n\n#> Returns a copy of the list by mapping each element to another value based on\n#| a transformation code.\n.map {\n need $code: Code\n -> gather for $el in *self {\n take $code($el)\n }\n}\n\n#> Returns a copy of the list containing only the elements that satisfy a code.\n.grep {\n need $code: Code\n -> gather for $el in *self {\n if $code($el): take $el\n }\n}\n\n#> Returns a flattened copy of the list.\nmethod flatten {\n $new = []\n for $el in *self {\n if $el.*isa(List)\n $new.push(items: $el.flatten())\n else\n $new.push($el)\n }\n -> $new\n}\n\n#> Returns a reversed copy of the list.\nmethod reverse {\n if @empty\n -> *self\n -> gather for $i in @lastIndex..0:\n take *self[$i]\n}\n\n#> Copies the list, ignoring all possible occurrences of a specified value.\nmethod withoutAll {\n need $what\n -> @grep! { -> $what != $_ }\n # -> @grep(func { -> $what != $_ })\n}\n\n#> Copies the list, ignoring the first occurrence of a specified value.\nmethod without {\n need $what\n var $found\n -> gather for ($i, $el) in *self {\n if !$found && $what == $el {\n $found = true\n next\n }\n take $el\n }\n}\n\n#> Removes the first element equal to a specified value.\nmethod remove {\n need $what\n removed -> false\n for ($i, $el) in *self {\n if $what != $el\n next\n @splice($i, 1)\n removed -> true\n last\n }\n}\n\n#> Removes all elements equal to a specified value.\nmethod removeAll {\n need $what\n\n # find the indices at which the value occurs\n $indices = gather for ($i, $el) in *self {\n if $what != $el\n next\n take $i\n }\n\n # remove\n for $i in $indices.reverse!\n @splice($i, 1)\n\n removed -> $indices.length #< number of removed elements\n}\n\n#> Returns true if the list contains at least one occurrence of the provided\n#| value.\nmethod contains {\n need $what\n -> @any! { -> $what == $_ }\n}\n\n#> Finds the first element to satisfy a code.\nmethod first {\n need $code: Code\n for $el in *self {\n if $code($el): -> $el\n }\n -> undefined\n}\n\n#> Returns the index of the first occurrence of the given value\nmethod indexOf {\n need $what\n for ($i, $el) in *self {\n if $what == $el: -> $i\n }\n -> undefined\n}\n\n#> Returns true if at least one element satisfies a code.\nmethod any {\n need $code: Code\n for $el in *self {\n if $code($el): -> true\n }\n -> false\n}\n\n#> Returns true if all elements satisfy a code.\nmethod all {\n need $code: Code\n for $el in *self {\n if !$code($el): -> false\n }\n -> true\n}\n\n#> Returns the sum of all elements in the list or `undefined` if the list is\n#| empty.\n.sum {\n if @empty\n -> undefined\n $c = *self[0]\n for $i in 1 .. @lastIndex {\n $c = $c + *self[$i]\n }\n -> $c\n}\n\n#> Returns the sum of all elements in the list or `0` (zero) if the list is\n#| empty. Useful for lists of numbers.\n.sum0 {\n $c = 0\n for $el in *self {\n $c = $c + $el\n }\n -> $c\n}\n\n#> Returns the first element in the list.\n.firstItem -> *self[0]\n\n#> Returns the last element in the list.\n.lastItem -> *self[@lastIndex]\n\n#> If the list has length one, returns an empty string, otherwise `\"s\"`\n.s {\n if @length == 1\n -> \"\"\n -> \"s\"\n}\n\n#> Returns an iterator for the list. This allows lists to be used in a for loop.\n.iterator -> ListIterator(*self) : Iterator\n\n#> Adding lists together results in an ordered consolidation of the lists.\nop + {\n need $rhs: List\n $new = @copy()\n $new.push(items: $rhs)\n -> $new\n}\n\n#> Subtracting list B from list A results in a new list containing all elements\n#| found in A but not found in B. Example: `[1,2,3,4,5] - [3,5]` -> `[1,2,4]`.\nop - {\n need $rhs: List\n $new = @copy()\n for $remove in $rhs:\n $new.removeAll($remove)\n -> $new\n}\n\n#> Lists are equal if all the elements are equal and in the same order.\nop == {\n need $ehs: List\n\n # first check if length is same\n if @length != $ehs.length\n -> false\n\n # check each item\n for ($i, $val) in *self {\n if $ehs[$i] != $val\n -> false\n }\n\n -> true\n}\n\n# Iterator methods\n\n.iterator -> *self\n\nmethod reset {\n @i = -1\n}\n\n.more -> @i < (@lastIndex || -1)\n\n.nextElement {\n @i += 1\n -> *self[@i]\n}\n\n.nextElements {\n @i += 1\n -> [ @i, *self[@i] ]\n}","old_contents":"class List \n\n#> Represents a list with an event number of elements, treated as pairs.\n#| This is similar to a hash with ordered keys.\ntype Pairs {\n isa *class\n satisfies .length.even\n}\n\n#> True if the list is empty.\n.empty -> @length == 0\n\n#> Returns a copy of the list by mapping each element to another value based on\n#| a transformation code.\n.map {\n need $code: Code\n -> gather for $el in *self {\n take $code($el)\n }\n}\n\n#> Returns a copy of the list containing only the elements that satisfy a code.\n.grep {\n need $code: Code\n -> gather for $el in *self {\n if $code($el): take $el\n }\n}\n\n#> Returns a flattened copy of the list.\nmethod flatten {\n $new = []\n for $el in *self {\n if $el.*isa(List)\n $new.push(items: $el.flatten())\n else\n $new.push($el)\n }\n -> $new\n}\n\n#> Returns a reversed copy of the list.\nmethod reverse {\n if @empty\n -> *self\n -> gather for $i in @lastIndex..0:\n take *self[$i]\n}\n\n#> Copies the list, ignoring all possible occurrences of a specified value.\nmethod withoutAll {\n need $what\n -> @grep! { -> $what != $_ }\n # -> @grep(func { -> $what != $_ })\n}\n\n#> Copies the list, ignoring the first occurrence of a specified value.\nmethod without {\n need $what\n var $found\n -> gather for ($i, $el) in *self {\n if !$found && $what == $el {\n $found = true\n next\n }\n take $el\n }\n}\n\n#> Removes the first element equal to a specified value.\nmethod remove {\n need $what\n removed -> false\n for ($i, $el) in *self {\n if $what != $el\n next\n @splice($i, 1)\n removed -> true\n last\n }\n}\n\n#> Removes all elements equal to a specified value.\nmethod removeAll {\n need $what\n\n # find the indices at which the value occurs\n $indices = gather for ($i, $el) in *self {\n if $what != $el\n next\n take $i\n }\n\n # remove\n for $i in $indices.reverse!\n @splice($i, 1)\n\n removed -> $indices.length #< number of removed elements\n}\n\n#> Returns true if the list contains at least one occurrence of the provided\n#| value.\nmethod contains {\n need $what\n -> @any! { -> $what == $_ }\n}\n\n#> Finds the first element to satisfy a code.\nmethod first {\n need $code: Code\n for $el in *self {\n if $code($el): -> $el\n }\n -> undefined\n}\n\n#> Returns the index of the first occurrence of the given value\nmethod indexOf {\n need $what\n for ($i, $el) in *self {\n if $what == $el: -> $i\n }\n -> undefined\n}\n\n#> Returns true if at least one element satisfies a code.\nmethod any {\n need $code: Code\n for $el in *self {\n if $code($el): -> true\n }\n -> false\n}\n\n#> Returns true if all elements satisfy a code.\nmethod all {\n need $code: Code\n for $el in *self {\n if !$code($el): -> false\n }\n -> true\n}\n\n#> Returns the sum of all elements in the list or `undefined` if the list is\n#| empty.\n.sum {\n if @empty\n -> undefined\n $c = *self[0]\n for $i in 1 .. @lastIndex {\n $c = $c + *self[$i]\n }\n -> $c\n}\n\n#> Returns the sum of all elements in the list or `0` (zero) if the list is\n#| empty. Useful for lists of numbers.\n.sum0 {\n $c = 0\n for $el in *self {\n $c = $c + $el\n }\n -> $c\n}\n\n#> Returns the first element in the list.\n.firstItem -> *self[0]\n\n#> Returns the last element in the list.\n.lastItem -> *self[@lastIndex]\n\n#> If the list has length one, returns an empty string, otherwise `\"s\"`\n.s {\n if @length == 1\n -> \"\"\n -> \"s\"\n}\n\n#> Returns an iterator for the list. This allows lists to be used in a for loop.\n.iterator -> ListIterator(*self) : Iterator\n\n#> Adding lists together results in an ordered consolidation of the lists.\nop + {\n need $rhs: List\n $new = @copy()\n $new.push(items: $rhs)\n -> $new\n}\n\n#> Subtracting list B from list A results in a new list containing all elements\n#| found in A but not found in B. Example: `[1,2,3,4,5] - [3,5]` -> `[1,2,4]`.\nop - {\n need $rhs: List\n $new = @copy()\n for $remove in $rhs:\n $new.removeAll($remove)\n -> $new\n}\n\n# Iterator methods\n\n.iterator -> *self\n\nmethod reset {\n @i = -1\n}\n\n.more -> @i < (@lastIndex || -1)\n\n.nextElement {\n @i += 1\n -> *self[@i]\n}\n\n.nextElements {\n @i += 1\n -> [ @i, *self[@i] ]\n}","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"d4958b394d05850fc8a7f9f37c87d8972ebdc0d3","subject":"Added some memory access words for Forth level CORE.","message":"Added some memory access words for Forth level CORE.\n","repos":"hth313\/hthforth","old_file":"src\/lib\/core.fth","new_file":"src\/lib\/core.fth","new_contents":"( block 1 -- Main load block )\n\nVARIABLE STATE ( compilation state variable )\n0 STATE ! ( interpreting by default )\n\nVARIABLE BLK\n: FH BLK @ + ; \\ relative block\n: LOAD BLK @ SWAP DUP BLK ! (LOAD) BLK ! ;\n\n30 LOAD\n( shadow 1 )\n( block 2 )\n( shadow 2 )\n( block 3 )\n( shadow 3 )\n\n( block 10 )\n( shadow 10 )\n( block 11 )\n( shadow 11 )\n( block 12 )\n( shadow 12 )\n\n( block 30 CORE words )\n\n1 FH 8 FH THRU\n\n( shadow 30 )\n( block 31 stack primitives )\n\n: ROT >R SWAP R> SWAP ;\n: ?DUP DUP IF DUP THEN ;\n\n( Not part of CORE, disabled at the moment )\n\\ : -ROT SWAP >R SWAP R> ; \\ or ROT ROT\n\\ : NIP ( n1 n2 -- n2 ) SWAP DROP ;\n\\ : TUCK ( n1 n2 -- n2 n1 n2 ) SWAP OVER ;\n\n: 2DROP DROP DROP ;\n: 2DUP OVER OVER ;\n: 2SWAP ROT >R ROT R> ;\n: 2OVER >R >R 2DUP R> R> 2SWAP ;\n( shadow 31 )\n( block 32 comparisons )\n\n-1 CONSTANT TRUE 0 CONSTANT FALSE\n\n: = ( n n -- f) XOR 0= ;\n: < ( n n -- f ) - 0< ;\n: > ( n n -- f ) SWAP < ;\n\n: MAX ( n n -- n ) 2DUP < IF SWAP THEN DROP ;\n: MIN ( n n -- n ) 2DUP > IF SWAP THEN DROP ;\n\n: WITHIN ( u ul uh -- f ) OVER - >R - R> U< ;\n( shadow 32 )\n( block 33 ALU )\n\n: 1+ 1 + ;\n: 1- 1 - ;\n: INVERT TRUE XOR ;\n: NEGATE INVERT 1+ ;\n: DNEGATE INVERT SWAP NEGATE SWAP OVER 0= - ;\n: S>D ( n -- d ) DUP 0< ; \\ sign extend\n: ABS S>D IF NEGATE THEN ;\n: DABS DUP 0< IF DNEGATE THEN ;\n\n: +- 0< IF NEGATE THEN ;\n: D+- 0< IF DNEGATE THEN ;\n\n( shadow 33 )\n( block 34 variables )\n\nVARIABLE BASE\n: DECIMAL 10 BASE ! ; : HEX 16 BASE ! ;\n\nVARIABLE DP\n( shadow 34 )\n( block 35 math )\n\n: SM\/REM ( d n -- r q ) \\ symmetric\n OVER >R >R DABS R@ ABS UM\/MOD\n R> R@ XOR 0< IF NEGATE THEN\n R> 0< IF >R NEGATE R> THEN ;\n\n: FM\/MOD ( d n -- r q ) \\ floored\n DUP 0< DUP >R IF NEGATE >R DNEGATE R> THEN\n >R DUP 0< IF R@ + THEN\n R> UM\/MOD R> IF >R NEGATE R> THEN ;\n\n: \/MOD OVER 0< SWAP FM\/MOD ;\n: MOD \/MOD DROP ;\n: \/ \/MOD SWAP DROP ;\n\n( shadow 35 )\n( block 36 math continued )\n\n: * UM* DROP ;\n: M* 2DUP XOR R> ABS SWAP ABS UM* R> D+- ;\n: *\/MOD >R M* R> FM\/MOD ;\n: *\/ *\/MOD SWAP DROP ;\n\n: 2* DUP + ;\n\\ 2\/ which is right shift is native\n\n: LSHIFT ( x1 u -- x2 )\n BEGIN DUP WHILE SWAP 2* SWAP 1- REPEAT DROP ;\n\n: RSHIFT ( x1 u -- x2 )\n BEGIN DUP WHILE SWAP 2\/ SWAP 1- REPEAT DROP ;\n ( shadow 36 )\n( block 37 numeric output primitives )\n\nVARIABLE HLD\n: HERE ( -- addr ) DP @ ;\n: PAD ( -- c-addr ) HERE 64 CHARS + ;\n\n: <# ( -- ) PAD HLD ! ;\n: #> ( xd -- c-addr u ) 2DROP HLD @ PAD OVER - ;\n: HOLD ( c -- ) HLD @ -1 CHARS - DUP HLD ! C! ;\n: DIGIT ( u -- c ) 9 OVER < 7 AND + 30 + ;\n: # ( ud1 -- ud2 )\n 0 BASE @ UM\/MOD >R BASE @ UM\/MOD SWAP DIGIT HOLD R> ;\n: #S ( ud1 -- ud2 ) BEGIN # 2DUP OR 0= UNTIL ;\n: SIGN ( n -- ) 0< IF 45 ( - ) HOLD THEN ;\n\n( shadow 37 )\n( block 38 memory access )\n\n: +! ( n a-addr -- ) DUP >R @ + R> ! ;\n: 2! ( x1 x2 a-addr -- ) SWAP OVER ! CELL+ ! ;\n: 2@ ( a-addr -- x1 x2 ) DUP CELL+ @ SWAP @ ;\n: COUNT ( c-addr1 -- c-addr2 u ) DUP CHAR+ SWAP C@ ;\n( shadow 38 )\n( block 39 )\n( shadow 39 )\n( block 40 compiler )\n\n: [ FALSE STATE ! ; IMMEDIATE\n: ] TRUE STATE ! ;\n\n: LITERAL ( x -- ) ['] (LIT) , ; IMMEDIATE\n: ALLOT ( n -- ) DP +! ;\n\n: COMPILE, ( xt -- ) HERE [ 1 XTS ] LITERAL ALLOT ! ;\n\n( Data allocation )\n: , ( n -- ) HERE [ 1 CELLS ] LITERAL ALLOT ! ;\n\n: VARIABLE CREATE 1 CELLS ALLOT ;\n: CONSTANT CREATE , DOES> @ ;\n\n( Colon definitions )\n: : CREATE ] ;\n: ; POSTPONE EXIT SMUDGE [ ; IMMEDIATE\n\n( shadow 40 )\n( block 41 )\n( shadow 41 )\n( block 42 interpreter )\n\nCREATE _INPUT-BUFFER 80 CHARS ALLOT ( may do this internally? )\n\n: EVALUATE >IN @ >R 0 >IN ! SOURCE >R >R #IN 2! _INTERPRET\n R> R> #IN 2! R> >IN ! ;\n\n: QUIT _RESET-RSTACK\n BEGIN\n BEGIN\n\t _READ-LINE 0 >IN ! _INPUT-BUFFER 0 EVALUATE CR\n\t STATE @\n UNTIL .\" ok \" ( exhausted input in interpretation mode )\n AGAIN ;\n( shadow 42 )\n","old_contents":"( block 1 -- Main load block )\n\nVARIABLE BLK\n: FH BLK @ + ; \\ relative block\n: LOAD BLK @ SWAP DUP BLK ! (LOAD) BLK ! ;\n\n30 LOAD\n( shadow 1 )\n( block 2 )\n( shadow 2 )\n( block 3 )\n( shadow 3 )\n\n( block 10 )\n( shadow 10 )\n( block 11 )\n( shadow 11 )\n( block 12 )\n( shadow 12 )\n\n( block 30 CORE words )\n\n1 FH 7 FH THRU\n\n( shadow 30 )\n( block 31 stack primitives )\n\n: ROT >R SWAP R> SWAP ;\n: ?DUP DUP IF DUP THEN ;\n\n( Not part of CORE, disabled at the moment )\n\\ : -ROT SWAP >R SWAP R> ; \\ or ROT ROT\n\\ : NIP ( n1 n2 -- n2 ) SWAP DROP ;\n\\ : TUCK ( n1 n2 -- n2 n1 n2 ) SWAP OVER ;\n\n: 2DROP DROP DROP ;\n: 2DUP OVER OVER ;\n: 2SWAP ROT >R ROT R> ;\n: 2OVER >R >R 2DUP R> R> 2SWAP ;\n( shadow 31 )\n( block 32 comparisons )\n\n-1 CONSTANT TRUE 0 CONSTANT FALSE\n\n: = ( n n -- f) XOR 0= ;\n: < ( n n -- f ) - 0< ;\n: > ( n n -- f ) SWAP < ;\n\n: MAX ( n n -- n ) 2DUP < IF SWAP THEN DROP ;\n: MIN ( n n -- n ) 2DUP > IF SWAP THEN DROP ;\n\n: WITHIN ( u ul uh -- f ) OVER - >R - R> U< ;\n( shadow 32 )\n( block 33 ALU )\n\n: 1+ 1 + ;\n: 1- 1 - ;\n: INVERT TRUE XOR ;\n: NEGATE INVERT 1+ ;\n: DNEGATE INVERT SWAP NEGATE SWAP OVER 0= - ;\n: S>D ( n -- d ) DUP 0< ; \\ sign extend\n: ABS S>D IF NEGATE THEN ;\n: DABS DUP 0< IF DNEGATE THEN ;\n\n: +- 0< IF NEGATE THEN ;\n: D+- 0< IF DNEGATE THEN ;\n\n( shadow 33 )\n( block 34 variables )\n\nVARIABLE BASE\n: DECIMAL 10 BASE ! ; : HEX 16 BASE ! ;\n\nVARIABLE DP\n( shadow 34 )\n( block 35 math )\n\n: SM\/REM ( d n -- r q ) \\ symmetric\n OVER >R >R DABS R@ ABS UM\/MOD\n R> R@ XOR 0< IF NEGATE THEN\n R> 0< IF >R NEGATE R> THEN ;\n\n: FM\/MOD ( d n -- r q ) \\ floored\n DUP 0< DUP >R IF NEGATE >R DNEGATE R> THEN\n >R DUP 0< IF R@ + THEN\n R> UM\/MOD R> IF >R NEGATE R> THEN ;\n\n: \/MOD OVER 0< SWAP FM\/MOD ;\n: MOD \/MOD DROP ;\n: \/ \/MOD SWAP DROP ;\n\n( shadow 35 )\n( block 36 math continued )\n\n: * UM* DROP ;\n: M* 2DUP XOR R> ABS SWAP ABS UM* R> D+- ;\n: *\/MOD >R M* R> FM\/MOD ;\n: *\/ *\/MOD SWAP DROP ;\n\n: 2* DUP + ;\n\\ 2\/ which is right shift is native\n\n: LSHIFT ( x1 u -- x2 )\n BEGIN DUP WHILE SWAP 2* SWAP 1- REPEAT DROP ;\n\n: RSHIFT ( x1 u -- x2 )\n BEGIN DUP WHILE SWAP 2\/ SWAP 1- REPEAT DROP ;\n ( shadow 36 )\n( block 37 numeric output primitives )\n\nVARIABLE HLD\n: HERE ( -- addr ) DP @ ;\n: PAD ( -- c-addr ) HERE 64 CHARS + ;\n\n: <# ( -- ) PAD HLD ! ;\n: #> ( xd -- c-addr u ) 2DROP HLD @ PAD OVER - ;\n: HOLD ( c -- ) HLD @ -1 CHARS - DUP HLD ! C! ;\n: DIGIT ( u -- c ) 9 OVER < 7 AND + 30 + ;\n: # ( ud1 -- ud2 )\n 0 BASE @ UM\/MOD >R BASE @ UM\/MOD SWAP DIGIT HOLD R> ;\n: #S ( ud1 -- ud2 ) BEGIN # 2DUP OR 0= UNTIL ;\n: SIGN ( n -- ) 0< IF 45 ( - ) HOLD THEN ;\n\n( shadow 37 )\n( block 38 )\n( shadow 38 )\n( block 39 )\n( shadow 39 )\n( block 40 compiler )\n\n: VARIABLE CREATE 1 CELLS ALLOT ;\n\nVARIABLE STATE ( compilation state variable )\n0 STATE ! ( interpreting by default )\n: [ FALSE STATE ! ;\n: ] TRUE STATE ! ;\n\n( Colon definitions )\n: : CREATE ] ;\n: ; POSTPONE EXIT SMUDGE [ ; IMMEDIATE\n\n( shadow 40 )\n( block 41 )\n( shadow 41 )\n( block 42 interpreter )\n\nCREATE _INPUT-BUFFER 80 CHARS ALLOT ( may do this internally? )\n\n: EVALUATE >IN @ >R 0 >IN ! SOURCE >R >R #IN 2! _INTERPRET\n R> R> #IN 2! R> >IN ! ;\n\n: QUIT _RESET-RSTACK\n BEGIN\n BEGIN\n\t _READ-LINE 0 >IN ! _INPUT-BUFFER 0 EVALUATE CR\n\t STATE @\n UNTIL .\" ok \" ( exhausted input in interpretation mode )\n AGAIN ;\n( shadow 42 )\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"c6b459655f26663dee5f7713dfb312f69fd2ef0b","subject":"DEC2BIN tests added","message":"DEC2BIN tests added\n","repos":"bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas","old_file":"KataDiversion_tests.fth","new_file":"KataDiversion_tests.fth","new_contents":"\\ KataDiversion tests, in Forth\n\\ running tests:\n\\ gforth KataDiversion_tests.fth -e bye\n\nREQUIRE KataDiversion.fth\n\nVARIABLE ASSERT-COUNT\n\n: ASSERTS-INIT ( -- )\n 0 ASSERT-COUNT ! ;\n\n: ASSERTS-RESULT ( -- )\n ASSERT-COUNT @ . .\" assertions successfully passed.\" CR ;\n\n\\ destructive assert-equal\n: ASSERT-EQUAL-D ( n1 n2 -- )\n <> IF 1 ABORT\" AssertEqual: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-equal\n: ASSERT-EQUAL ( n1 n2 -- n1 n2 )\n 2DUP ASSERT-EQUAL-D ;\n\n\\ destructive assert-true\n: ASSERT-TRUE-D ( n -- )\n 0 = IF 1 ABORT\" AssertTrue: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-true\n: ASSERT-TRUE ( n -- n )\n DUP ASSERT-TRUE-D ;\n\n\\ destructive assert-false\n: ASSERT-False-D ( n -- )\n 0 <> IF 1 ABORT\" AssertFalse: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-false\n: ASSERT-FALSE ( n -- n )\n DUP ASSERT-FALSE-D ;\n\n\\ ---- tests ----\n\nASSERTS-INIT\n\n\\ ?EMPTY\nEMPTY DEPTH 0 ASSERT-EQUAL-D\nEMPTY EMPTY DEPTH 0 ASSERT-EQUAL-D\n0 EMPTY DEPTH 0 ASSERT-EQUAL-D\n1 2 3 4 EMPTY DEPTH 0 ASSERT-EQUAL-D\n\n\\ ?NEGATIVE\n-1 ?NEG ASSERT-TRUE-D\n 0 ?NEG ASSERT-TRUE-D\n 1 ?NEG ASSERT-FALSE-D\n\n\\ ?MAX-NB\n-1 ?MAX-NB 0 ASSERT-EQUAL-D\n 0 ?MAX-NB 0 ASSERT-EQUAL-D\n 1 ?MAX-NB 2 ASSERT-EQUAL-D\n 2 ?MAX-NB 4 ASSERT-EQUAL-D\n 3 ?MAX-NB 8 ASSERT-EQUAL-D\n\n\\ LOG2\n 1 LOG2 0 ASSERT-EQUAL-D\n 2 LOG2 1 ASSERT-EQUAL-D\n 3 LOG2 1 ASSERT-EQUAL-D\n 4 LOG2 2 ASSERT-EQUAL-D\n 5 LOG2 2 ASSERT-EQUAL-D\n 8 LOG2 3 ASSERT-EQUAL-D\n42 LOG2 5 ASSERT-EQUAL-D\n\n\\ DEC2BIN\n\n 0 DEC2BIN 0 ASSERT-EQUAL-D\n 1 DEC2BIN 1 ASSERT-EQUAL-D\n 2 DEC2BIN 0 ASSERT-EQUAL-D ( 2 -> 10 )\n 1 ASSERT-EQUAL-D\n11 DEC2BIN 1 ASSERT-EQUAL-D ( 11 -> 1011 )\n 1 ASSERT-EQUAL-D\n 0 ASSERT-EQUAL-D\n 1 ASSERT-EQUAL-D\n\n\nASSERTS-RESULT\n\\ ---------\n\n\n","old_contents":"\\ KataDiversion tests, in Forth\n\\ running tests:\n\\ gforth KataDiversion_tests.fth -e bye\n\nREQUIRE KataDiversion.fth\n\nVARIABLE ASSERT-COUNT\n\n: ASSERTS-INIT ( -- )\n 0 ASSERT-COUNT ! ;\n\n: ASSERTS-RESULT ( -- )\n ASSERT-COUNT @ . .\" assertions successfully passed.\" CR ;\n\n\\ destructive assert-equal\n: ASSERT-EQUAL-D ( n1 n2 -- )\n <> IF 1 ABORT\" AssertEqual: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-equal\n: ASSERT-EQUAL ( n1 n2 -- n1 n2 )\n 2DUP ASSERT-EQUAL-D ;\n\n\\ destructive assert-true\n: ASSERT-TRUE-D ( n -- )\n 0 = IF 1 ABORT\" AssertTrue: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-true\n: ASSERT-TRUE ( n -- n )\n DUP ASSERT-TRUE-D ;\n\n\\ destructive assert-false\n: ASSERT-False-D ( n -- )\n 0 <> IF 1 ABORT\" AssertFalse: Fail\"\n ELSE ASSERT-COUNT @ 1+ ASSERT-COUNT ! THEN ;\n\n\\ non-destructive assert-false\n: ASSERT-FALSE ( n -- n )\n DUP ASSERT-FALSE-D ;\n\n\\ ---- tests ----\n\nASSERTS-INIT\n\n\\ ?EMPTY\nEMPTY DEPTH 0 ASSERT-EQUAL-D\nEMPTY EMPTY DEPTH 0 ASSERT-EQUAL-D\n0 EMPTY DEPTH 0 ASSERT-EQUAL-D\n1 2 3 4 EMPTY DEPTH 0 ASSERT-EQUAL-D\n\n\\ ?NEGATIVE\n-1 ?NEG ASSERT-TRUE-D\n 0 ?NEG ASSERT-TRUE-D\n 1 ?NEG ASSERT-FALSE-D\n\n\\ ?MAX-NB\n-1 ?MAX-NB 0 ASSERT-EQUAL-D\n 0 ?MAX-NB 0 ASSERT-EQUAL-D\n 1 ?MAX-NB 2 ASSERT-EQUAL-D\n 2 ?MAX-NB 4 ASSERT-EQUAL-D\n 3 ?MAX-NB 8 ASSERT-EQUAL-D\n\n\\ LOG2\n 1 LOG2 0 ASSERT-EQUAL-D\n 2 LOG2 1 ASSERT-EQUAL-D\n 3 LOG2 1 ASSERT-EQUAL-D\n 4 LOG2 2 ASSERT-EQUAL-D\n 5 LOG2 2 ASSERT-EQUAL-D\n 8 LOG2 3 ASSERT-EQUAL-D\n42 LOG2 5 ASSERT-EQUAL-D\n\n\n\nASSERTS-RESULT\n\\ ---------\n\n\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"330434ec424fec4447b6a20a8ad4511a9fd4f529","subject":"from NetBSD via Tim Weiss, tim at zetaflops dot net: deal with FS block sizes larger than 8K testing: krw","message":"from NetBSD via Tim Weiss, tim at zetaflops dot net: deal with FS block sizes larger than 8K\ntesting: krw\n","repos":"orumin\/openbsd-efivars,orumin\/openbsd-efivars,orumin\/openbsd-efivars,orumin\/openbsd-efivars","old_file":"arch\/sparc64\/stand\/bootblk\/bootblk.fth","new_file":"arch\/sparc64\/stand\/bootblk\/bootblk.fth","new_contents":"\\\t$OpenBSD: bootblk.fth,v 1.3 2003\/08\/28 23:47:31 jason Exp $\n\\\t$NetBSD: bootblk.fth,v 1.3 2001\/08\/15 20:10:24 eeh Exp $\n\\\n\\\tIEEE 1275 Open Firmware Boot Block\n\\\n\\\tParses disklabel and UFS and loads the file called `ofwboot'\n\\\n\\\n\\\tCopyright (c) 1998 Eduardo Horvath.\n\\\tAll rights reserved.\n\\\n\\\tRedistribution and use in source and binary forms, with or without\n\\\tmodification, are permitted provided that the following conditions\n\\\tare met:\n\\\t1. Redistributions of source code must retain the above copyright\n\\\t notice, this list of conditions and the following disclaimer.\n\\\t2. Redistributions in binary form must reproduce the above copyright\n\\\t notice, this list of conditions and the following disclaimer in the\n\\\t documentation and\/or other materials provided with the distribution.\n\\\t3. All advertising materials mentioning features or use of this software\n\\\t must display the following acknowledgement:\n\\\t This product includes software developed by Eduardo Horvath.\n\\\t4. The name of the author may not be used to endorse or promote products\n\\\t derived from this software without specific prior written permission\n\\\n\\\tTHIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n\\\tIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n\\\tOF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n\\\tIN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n\\\tINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n\\\tNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\\\tDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\\\tTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\\\t(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n\\\tTHIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\\\n\noffset16\nhex\nheaders\n\nfalse value boot-debug?\n\n\\\n\\ First some housekeeping: Open \/chosen and set up vectors into\n\\\tclient-services\n\n\" \/chosen\" find-package 0= if .\" Cannot find \/chosen\" 0 then\nconstant chosen-phandle\n\n\" \/openprom\/client-services\" find-package 0= if \n\t.\" Cannot find client-services\" cr abort\nthen constant cif-phandle\n\ndefer cif-claim ( align size virt -- base )\ndefer cif-release ( size virt -- )\ndefer cif-open ( cstr -- ihandle|0 )\ndefer cif-close ( ihandle -- )\ndefer cif-read ( len adr ihandle -- #read )\ndefer cif-seek ( low high ihandle -- -1|0|1 )\n\\ defer cif-peer ( phandle -- phandle )\n\\ defer cif-getprop ( len adr cstr phandle -- )\n\n: find-cif-method ( method,len -- xf )\n cif-phandle find-method drop \n;\n\n\" claim\" find-cif-method to cif-claim\n\" open\" find-cif-method to cif-open\n\" close\" find-cif-method to cif-close\n\" read\" find-cif-method to cif-read\n\" seek\" find-cif-method to cif-seek\n\n: twiddle ( -- ) .\" .\" ; \\ Need to do this right. Just spit out periods for now.\n\n\\\n\\ Support routines\n\\\n\n: strcmp ( s1 l1 s2 l2 -- true:false )\n rot tuck <> if 3drop false exit then\n comp 0=\n;\n\n\\ Move string into buffer\n\n: strmov ( s1 l1 d -- d l1 )\n dup 2over swap -rot\t\t( s1 l1 d s1 d l1 )\n move\t\t\t\t( s1 l1 d )\n rot drop swap\n;\n\n\\ Move s1 on the end of s2 and return the result\n\n: strcat ( s1 l1 s2 l2 -- d tot )\n 2over swap \t\t\t\t( s1 l1 s2 l2 l1 s1 )\n 2over + rot\t\t\t\t( s1 l1 s2 l2 s1 d l1 )\n move rot + \t\t\t\t( s1 s2 len )\n rot drop\t\t\t\t( s2 len )\n;\n\n: strchr ( s1 l1 c -- s2 l2 )\n begin\n dup 2over 0= if\t\t\t( s1 l1 c c s1 )\n 2drop drop exit then\n c@ = if\t\t\t\t( s1 l1 c )\n drop exit then\n -rot \/c - swap ca1+\t\t( c l2 s2 )\n swap rot\n again\n;\n\n \n: cstr ( ptr -- str len )\n dup \n begin dup c@ 0<> while + repeat\n over -\n;\n\n\\\n\\ BSD FFS parameters\n\\\n\nfload\tassym.fth.h\n\nsbsize buffer: sb-buf\n-1 value boot-ihandle\ndev_bsize value bsize\n0 value raid-offset\t\\ Offset if it's a raid-frame partition\n\n: strategy ( addr size start -- nread )\n raid-offset + bsize * 0 \" seek\" boot-ihandle $call-method\n -1 = if \n .\" strategy: Seek failed\" cr\n abort\n then\n \" read\" boot-ihandle $call-method\n;\n\n\\\n\\ Cylinder group macros\n\\\n\n: cgbase ( cg fs -- cgbase ) fs_fpg l@ * ;\n: cgstart ( cg fs -- cgstart ) \n 2dup fs_cgmask l@ not and\t\t( cg fs stuff -- )\n over fs_cgoffset l@ * -rot\t\t( stuffcg fs -- )\n cgbase +\n;\n: cgdmin ( cg fs -- 1st-data-block ) dup fs_dblkno l@ -rot cgstart + ;\n: cgimin ( cg fs -- inode-block ) dup fs_iblkno l@ -rot cgstart + ;\n: cgsblock ( cg fs -- super-block ) dup fs_sblkno l@ -rot cgstart + ;\n: cgstod ( cg fs -- cg-block ) dup fs_cblkno l@ -rot cgstart + ;\n\n\\\n\\ Block and frag position macros\n\\\n\n: blkoff ( pos fs -- off ) fs_qbmask x@ and ;\n: fragoff ( pos fs -- off ) fs_qfmask x@ and ;\n: lblktosize ( blk fs -- off ) fs_bshift l@ << ;\n: lblkno ( pos fs -- off ) fs_bshift l@ >> ;\n: numfrags ( pos fs -- off ) fs_fshift l@ >> ;\n: blkroundup ( pos fs -- off ) dup fs_bmask l@ -rot fs_qbmask x@ + and ;\n: fragroundup ( pos fs -- off ) dup fs_fmask l@ -rot fs_qfmask x@ + and ;\n\\ : fragroundup ( pos fs -- off ) tuck fs_qfmask x@ + swap fs_fmask l@ and ;\n: fragstoblks ( pos fs -- off ) fs_fragshift l@ >> ;\n: blkstofrags ( blk fs -- frag ) fs_fragshift l@ << ;\n: fragnum ( fsb fs -- off ) fs_frag l@ 1- and ;\n: blknum ( fsb fs -- off ) fs_frag l@ 1- not and ;\n: dblksize ( lbn dino fs -- size )\n -rot \t\t\t\t( fs lbn dino )\n di_size x@\t\t\t\t( fs lbn di_size )\n -rot dup 1+\t\t\t\t( di_size fs lbn lbn+1 )\n 2over fs_bshift l@\t\t\t( di_size fs lbn lbn+1 di_size b_shift )\n rot swap <<\t>=\t\t\t( di_size fs lbn res1 )\n swap ndaddr >= or if\t\t\t( di_size fs )\n swap drop fs_bsize l@ exit\t( size )\n then\ttuck blkoff swap fragroundup\t( size )\n;\n\n\n: ino-to-cg ( ino fs -- cg ) fs_ipg l@ \/ ;\n: ino-to-fsbo ( ino fs -- fsb0 ) fs_inopb l@ mod ;\n: ino-to-fsba ( ino fs -- ba )\t\\ Need to remove the stupid stack diags someday\n 2dup \t\t\t\t( ino fs ino fs )\n ino-to-cg\t\t\t\t( ino fs cg )\n over\t\t\t\t\t( ino fs cg fs )\n cgimin\t\t\t\t( ino fs inode-blk )\n -rot\t\t\t\t\t( inode-blk ino fs )\n tuck \t\t\t\t( inode-blk fs ino fs )\n fs_ipg l@ \t\t\t\t( inode-blk fs ino ipg )\n mod\t\t\t\t\t( inode-blk fs mod )\n swap\t\t\t\t\t( inode-blk mod fs )\n dup \t\t\t\t\t( inode-blk mod fs fs )\n fs_inopb l@ \t\t\t\t( inode-blk mod fs inopb )\n rot \t\t\t\t\t( inode-blk fs inopb mod )\n swap\t\t\t\t\t( inode-blk fs mod inopb )\n \/\t\t\t\t\t( inode-blk fs div )\n swap\t\t\t\t\t( inode-blk div fs )\n blkstofrags\t\t\t\t( inode-blk frag )\n +\n;\n: fsbtodb ( fsb fs -- db ) fs_fsbtodb l@ << ;\n\n\\\n\\ File stuff\n\\\n\nniaddr \/w* constant narraysize\n\nstruct \n 8\t\tfield\t>f_ihandle\t\\ device handle\n 8 \t\tfield \t>f_seekp\t\\ seek pointer\n 8 \t\tfield \t>f_fs\t\t\\ pointer to super block\n ufs1_dinode_SIZEOF \tfield \t>f_di\t\\ copy of on-disk inode\n 8\t\tfield\t>f_buf\t\t\\ buffer for data block\n 4\t\tfield \t>f_buf_size\t\\ size of data block\n 4\t\tfield\t>f_buf_blkno\t\\ block number of data block\nconstant file_SIZEOF\n\nfile_SIZEOF buffer: the-file\nsb-buf the-file >f_fs x!\n\nufs1_dinode_SIZEOF buffer: cur-inode\nh# 2000 buffer: indir-block\n-1 value indir-addr\n\n\\\n\\ Translate a fileblock to a disk block\n\\\n\\ We only allow single indirection\n\\\n\n: block-map ( fileblock -- diskblock )\n \\ Direct block?\n dup ndaddr < if \t\t\t( fileblock )\n cur-inode di_db\t\t\t( arr-indx arr-start )\n swap la+ l@ exit\t\t\t( diskblock )\n then \t\t\t\t( fileblock )\n ndaddr -\t\t\t\t( fileblock' )\n \\ Now we need to check the indirect block\n dup sb-buf fs_nindir l@ < if\t( fileblock' )\n cur-inode di_ib l@ dup\t\t( fileblock' indir-block indir-block )\n indir-addr <> if \t\t( fileblock' indir-block )\n to indir-addr\t\t\t( fileblock' )\n indir-block \t\t\t( fileblock' indir-block )\n sb-buf dup fs_bsize l@\t\t( fileblock' indir-block fs fs_bsize )\n swap indir-addr swap\t\t( fileblock' indir-block fs_bsize indiraddr fs )\n fsbtodb \t\t\t( fileblock' indir-block fs_bsize db )\n strategy\t\t\t( fileblock' nread )\n then\t\t\t\t( fileblock' nread|indir-block )\n drop \\ Really should check return value\n indir-block swap la+ l@ exit\n then\n dup sb-buf fs_nindir -\t\t( fileblock'' )\n \\ Now try 2nd level indirect block -- just read twice \n dup sb-buf fs_nindir l@ dup * < if\t( fileblock'' )\n cur-inode di_ib 1 la+ l@\t\t( fileblock'' indir2-block )\n to indir-addr\t\t\t( fileblock'' )\n \\ load 1st level indir block \n indir-block \t\t\t( fileblock'' indir-block )\n sb-buf dup fs_bsize l@\t\t( fileblock'' indir-block fs fs_bsize )\n swap indir-addr swap\t\t( fileblock'' indir-block fs_bsize indiraddr fs )\n fsbtodb \t\t\t\t( fileblock'' indir-block fs_bsize db )\n strategy\t\t\t\t( fileblock'' nread )\n drop\t\t\t\t( fileblock'' )\n dup sb-buf fs_nindir \/\t\t( fileblock'' indir-offset )\n indir-block swap la+ l@\t\t( fileblock'' indirblock )\n to indir-addr\t\t\t( fileblock'' )\n \\ load 2nd level indir block\n indir-block \t\t\t( fileblock'' indir-block )\n sb-buf dup fs_bsize l@\t\t( fileblock'' indir-block fs fs_bsize )\n swap indir-addr swap\t\t( fileblock'' indir-block fs_bsize indiraddr fs )\n fsbtodb \t\t\t\t( fileblock'' indir-block fs_bsize db )\n strategy\t\t\t\t( fileblock'' nread )\n drop\t\t\t\t( fileblock'' )\n sb-buf fs_nindir l@ mod indir-block swap la+ l@ exit\n then\n .\" block-map: exceeded max file size\" cr\n abort\n;\n\n\\\n\\ Read file into internal buffer and return pointer and len\n\\\n\n0 value cur-block\t\t\t\\ allocated dynamically in ufs-open\n0 value cur-blocksize\t\t\t\\ size of cur-block\n-1 value cur-blockno\n0 value cur-offset\n\n: buf-read-file ( fs -- len buf )\n cur-offset swap\t\t\t( seekp fs )\n 2dup blkoff\t\t\t\t( seekp fs off )\n -rot 2dup lblkno\t\t\t( off seekp fs block )\n swap 2dup cur-inode\t\t\t( off seekp block fs block fs inop )\n swap dblksize\t\t\t( off seekp block fs size )\n rot dup cur-blockno\t\t\t( off seekp fs size block block cur )\n <> if \t\t\t\t( off seekp fs size block )\n block-map\t\t\t\t( off seekp fs size diskblock )\n dup 0= if\t\t\t( off seekp fs size diskblock )\n over cur-block swap 0 fill\t( off seekp fs size diskblock )\n boot-debug? if .\" buf-read-file fell off end of file\" cr then\n else\n 2dup sb-buf fsbtodb cur-block -rot strategy\t( off seekp fs size diskblock nread )\n rot 2dup <> if \" buf-read-file: short read.\" cr abort then\n then\t\t\t\t( off seekp fs diskblock nread size )\n nip nip\t\t\t\t( off seekp fs size )\n else\t\t\t\t\t( off seekp fs size block block cur )\n 2drop\t\t\t\t( off seekp fs size )\n then\n\\ dup cur-offset + to cur-offset\t\\ Set up next xfer -- not done\n nip nip swap -\t\t\t( len )\n cur-block\n;\n\n\\\n\\ Read inode into cur-inode -- uses cur-block\n\\ \n\n: read-inode ( inode fs -- )\n twiddle\t\t\t\t( inode fs -- inode fs )\n\n cur-block\t\t\t\t( inode fs -- inode fs buffer )\n\n over\t\t\t\t\t( inode fs buffer -- inode fs buffer fs )\n fs_bsize l@\t\t\t\t( inode fs buffer -- inode fs buffer size )\n\n 2over\t\t\t\t( inode fs buffer size -- inode fs buffer size inode fs )\n 2over\t\t\t\t( inode fs buffer size inode fs -- inode fs buffer size inode fs buffer size )\n 2swap tuck\t\t\t\t( inode fs buffer size inode fs buffer size -- inode fs buffer size buffer size fs inode fs )\n\n ino-to-fsba \t\t\t\t( inode fs buffer size buffer size fs inode fs -- inode fs buffer size buffer size fs fsba )\n swap\t\t\t\t\t( inode fs buffer size buffer size fs fsba -- inode fs buffer size buffer size fsba fs )\n fsbtodb\t\t\t\t( inode fs buffer size buffer size fsba fs -- inode fs buffer size buffer size db )\n\n dup to cur-blockno\t\t\t( inode fs buffer size buffer size dstart -- inode fs buffer size buffer size dstart )\n strategy\t\t\t\t( inode fs buffer size buffer size dstart -- inode fs buffer size nread )\n <> if .\" read-inode - residual\" cr abort then\n dup 2over\t\t\t\t( inode fs buffer -- inode fs buffer buffer inode fs )\n ino-to-fsbo\t\t\t\t( inode fs buffer -- inode fs buffer buffer fsbo )\n ufs1_dinode_SIZEOF * +\t\t\t( inode fs buffer buffer fsbo -- inode fs buffer dinop )\n cur-inode ufs1_dinode_SIZEOF move \t( inode fs buffer dinop -- inode fs buffer )\n\t\\ clear out the old buffers\n drop\t\t\t\t\t( inode fs buffer -- inode fs )\n 2drop\n;\n\n\\ Identify inode type\n\n: is-dir? ( dinode -- true:false ) di_mode w@ ifmt and ifdir = ;\n: is-symlink? ( dinode -- true:false ) di_mode w@ ifmt and iflnk = ;\n\n\n\n\\\n\\ Hunt for directory entry:\n\\ \n\\ repeat\n\\ load a buffer\n\\ while entries do\n\\ if entry == name return\n\\ next entry\n\\ until no buffers\n\\\n\n: search-directory ( str len -- ino|0 )\n 0 to cur-offset\n begin cur-offset cur-inode di_size x@ < while\t( str len )\n sb-buf buf-read-file\t\t( str len len buf )\n over 0= if .\" search-directory: buf-read-file zero len\" cr abort then\n swap dup cur-offset + to cur-offset\t( str len buf len )\n 2dup + nip\t\t\t( str len buf bufend )\n swap 2swap rot\t\t\t( bufend str len buf )\n begin dup 4 pick < while\t\t( bufend str len buf )\n dup d_ino l@ 0<> if \t\t( bufend str len buf )\n boot-debug? if dup dup d_name swap d_namlen c@ type cr then\n 2dup d_namlen c@ = if\t( bufend str len buf )\n dup d_name 2over\t\t( bufend str len buf dname str len )\n comp 0= if\t\t( bufend str len buf )\n \\ Found it -- return inode\n d_ino l@ nip nip nip\t( dino )\n boot-debug? if .\" Found it\" cr then \n exit \t\t\t( dino )\n then\n then\t\t\t( bufend str len buf )\n then\t\t\t\t( bufend str len buf )\n dup d_reclen w@ +\t\t( bufend str len nextbuf )\n repeat\n drop rot drop\t\t\t( str len )\n repeat\n 2drop 2drop 0\t\t\t( 0 )\n;\n\n: ffs_oldcompat ( -- )\n\\ Make sure old ffs values in sb-buf are sane\n sb-buf fs_npsect dup l@ sb-buf fs_nsect l@ max swap l!\n sb-buf fs_interleave dup l@ 1 max swap l!\n sb-buf fs_postblformat l@ fs_42postblfmt = if\n 8 sb-buf fs_nrpos l!\n then\n sb-buf fs_inodefmt l@ fs_44inodefmt < if\n sb-buf fs_bsize l@ \n dup ndaddr * 1- sb-buf fs_maxfilesize x!\n niaddr 0 ?do\n\tsb-buf fs_nindir l@ * dup\t( sizebp sizebp -- )\n\tsb-buf fs_maxfilesize dup x@\t( sizebp sizebp *fs_maxfilesize fs_maxfilesize -- )\n\trot \t\t\t\t( sizebp *fs_maxfilesize fs_maxfilesize sizebp -- )\n\t+ \t\t\t\t( sizebp *fs_maxfilesize new_fs_maxfilesize -- ) \n swap x! \t\t\t( sizebp -- )\n loop drop \t\t\t( -- )\n sb-buf dup fs_bmask l@ not swap fs_qbmask x!\n sb-buf dup fs_fmask l@ not swap fs_qfmask x!\n then\n;\n\n: read-super ( sector -- )\n0 \" seek\" boot-ihandle $call-method\n -1 = if \n .\" Seek failed\" cr\n abort\n then\n sb-buf sbsize \" read\" boot-ihandle $call-method\n dup sbsize <> if\n .\" Read of superblock failed\" cr\n .\" requested\" space sbsize .\n .\" actual\" space . cr\n abort\n else \n drop\n then\n;\n\n: ufs-open ( bootpath,len -- )\n boot-ihandle -1 = if\n over cif-open dup 0= if \t\t( boot-path len ihandle? )\n .\" Could not open device\" space type cr \n abort\n then \t\t\t\t( boot-path len ihandle )\n to boot-ihandle\t\t\t\\ Save ihandle to boot device\n then 2drop\n sboff read-super\n sb-buf fs_magic l@ fs_magic_value <> if\n 64 dup to raid-offset \n dev_bsize * sboff + read-super\n sb-buf fs_magic l@ fs_magic_value <> if\n .\" Invalid superblock magic\" cr\n abort\n then\n then\n sb-buf fs_bsize l@ dup maxbsize > if\n .\" Superblock bsize\" space . .\" too large\" cr\n abort\n then \n dup fs_SIZEOF < if\n .\" Superblock bsize < size of superblock\" cr\n abort\n then\n ffs_oldcompat\t( fs_bsize -- fs_bsize )\n dup to cur-blocksize alloc-mem to cur-block \\ Allocate cur-block\n boot-debug? if .\" ufs-open complete\" cr then\n;\n\n: ufs-close ( -- ) \n boot-ihandle dup -1 <> if\n cif-close -1 to boot-ihandle \n then\n cur-block 0<> if\n cur-block cur-blocksize free-mem\n then\n;\n\n: boot-path ( -- boot-path )\n \" bootpath\" chosen-phandle get-package-property if\n .\" Could not find bootpath in \/chosen\" cr\n abort\n else\n decode-string 2swap 2drop\n then\n;\n\n: boot-args ( -- boot-args )\n \" bootargs\" chosen-phandle get-package-property if\n .\" Could not find bootargs in \/chosen\" cr\n abort\n else\n decode-string 2swap 2drop\n then\n;\n\n2000 buffer: boot-path-str\n2000 buffer: boot-path-tmp\n\n: split-path ( path len -- right len left len )\n\\ Split a string at the `\/'\n begin\n dup -rot\t\t\t\t( oldlen right len left )\n ascii \/ left-parse-string\t\t( oldlen right len left len )\n dup 0<> if 4 roll drop exit then\n 2drop\t\t\t\t( oldlen right len )\n rot over =\t\t\t( right len diff )\n until\n;\n\n: find-file ( load-file len -- )\n rootino dup sb-buf read-inode\t( load-file len -- load-file len ino )\n -rot\t\t\t\t\t( load-file len ino -- pino load-file len )\n \\\n \\ For each path component\n \\ \n begin split-path dup 0<> while\t( pino right len left len -- )\n cur-inode is-dir? not if .\" Inode not directory\" cr abort then\n boot-debug? if .\" Looking for\" space 2dup type space .\" in directory...\" cr then\n search-directory\t\t\t( pino right len left len -- pino right len ino|false )\n dup 0= if .\" Bad path\" cr abort then\t( pino right len cino )\n sb-buf read-inode\t\t\t( pino right len )\n cur-inode is-symlink? if\t\t\\ Symlink -- follow the damn thing\n \\ Save path in boot-path-tmp\n boot-path-tmp strmov\t\t( pino new-right len )\n\n \\ Now deal with symlink\n cur-inode di_size x@\t\t( pino right len linklen )\n dup sb-buf fs_maxsymlinklen l@\t( pino right len linklen linklen maxlinklen )\n < if\t\t\t\t\\ Now join the link to the path\n cur-inode di_shortlink l@\t( pino right len linklen linkp )\n swap boot-path-str strmov\t( pino right len new-linkp linklen )\n else\t\t\t\t\\ Read file for symlink -- Ugh\n \\ Read link into boot-path-str\n boot-path-str dup sb-buf fs_bsize l@\n 0 block-map\t\t\t( pino right len linklen boot-path-str bsize blockno )\n strategy drop swap\t\t( pino right len boot-path-str linklen )\n then \t\t\t\t( pino right len linkp linklen )\n \\ Concatenate the two paths\n strcat\t\t\t\t( pino new-right newlen )\n swap dup c@ ascii \/ = if\t\\ go to root inode?\n rot drop rootino -rot\t( rino len right )\n then\n rot dup sb-buf read-inode\t( len right pino )\n -rot swap\t\t\t( pino right len )\n then\t\t\t\t( pino right len )\n repeat\n 2drop drop\n;\n\n: read-file ( size addr -- )\n \\ Read x bytes from a file to buffer\n begin over 0> while\n cur-offset cur-inode di_size x@ > if .\" read-file EOF exceeded\" cr abort then\n sb-buf buf-read-file\t\t( size addr len buf )\n over 2over drop swap\t\t( size addr len buf addr len )\n move\t\t\t\t( size addr len )\n dup cur-offset + to cur-offset\t( size len newaddr )\n tuck +\t\t\t\t( size len newaddr )\n -rot - swap\t\t\t( newaddr newsize )\n repeat\n 2drop\n;\n\n\\\n\\ According to the 1275 addendum for SPARC processors:\n\\ Default load-base is 0x4000. At least 0x8.0000 or\n\\ 512KB must be available at that address. \n\\\n\\ The Fcode bootblock can take up up to 8KB (O.K., 7.5KB) \n\\ so load programs at 0x4000 + 0x2000=> 0x6000\n\\\n\nh# 6000 constant loader-base\n\n\\\n\\ Elf support -- find the load addr\n\\\n\n: is-elf? ( hdr -- res? ) h# 7f454c46 = ;\n\n\\\n\\ Finally we finish it all off\n\\\n\n: load-file-signon ( load-file len boot-path len -- load-file len boot-path len )\n .\" Loading file\" space 2over type cr .\" from device\" space 2dup type cr\n;\n\n: load-file-print-size ( size -- size )\n .\" Loading\" space dup . space .\" bytes of file...\" cr \n;\n\n: load-file ( load-file len boot-path len -- load-base )\n boot-debug? if load-file-signon then\n the-file file_SIZEOF 0 fill\t\t\\ Clear out file structure\n ufs-open \t\t\t\t( load-file len )\n find-file\t\t\t\t( )\n\n \\\n \\ Now we've found the file we should read it in in one big hunk\n \\\n\n cur-inode di_size x@\t\t\t( file-len )\n dup \" to file-size\" evaluate\t\t( file-len )\n boot-debug? if load-file-print-size then\n 0 to cur-offset\n loader-base\t\t\t\t( buf-len addr )\n 2dup read-file\t\t\t( buf-len addr )\n ufs-close\t\t\t\t( buf-len addr )\n dup is-elf? if .\" load-file: not an elf executable\" cr abort then\n\n \\ Luckily the prom should be able to handle ELF executables by itself\n\n nip\t\t\t\t\t( addr )\n;\n\n: do-boot ( bootfile -- )\n .\" OpenBSD IEEE 1275 Bootblock 1.1\" cr\n boot-path load-file ( -- load-base )\n dup 0<> if \" to load-base init-program\" evaluate then\n;\n\n\nboot-args ascii V strchr 0<> swap drop if\n true to boot-debug?\nthen\n\nboot-args ascii D strchr 0= swap drop if\n \" \/ofwboot\" do-boot\nthen exit\n\n\n","old_contents":"\\\t$OpenBSD: bootblk.fth,v 1.2 2003\/08\/26 19:55:21 drahn Exp $\n\\\t$NetBSD: bootblk.fth,v 1.3 2001\/08\/15 20:10:24 eeh Exp $\n\\\n\\\tIEEE 1275 Open Firmware Boot Block\n\\\n\\\tParses disklabel and UFS and loads the file called `ofwboot'\n\\\n\\\n\\\tCopyright (c) 1998 Eduardo Horvath.\n\\\tAll rights reserved.\n\\\n\\\tRedistribution and use in source and binary forms, with or without\n\\\tmodification, are permitted provided that the following conditions\n\\\tare met:\n\\\t1. Redistributions of source code must retain the above copyright\n\\\t notice, this list of conditions and the following disclaimer.\n\\\t2. Redistributions in binary form must reproduce the above copyright\n\\\t notice, this list of conditions and the following disclaimer in the\n\\\t documentation and\/or other materials provided with the distribution.\n\\\t3. All advertising materials mentioning features or use of this software\n\\\t must display the following acknowledgement:\n\\\t This product includes software developed by Eduardo Horvath.\n\\\t4. The name of the author may not be used to endorse or promote products\n\\\t derived from this software without specific prior written permission\n\\\n\\\tTHIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n\\\tIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n\\\tOF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n\\\tIN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n\\\tINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n\\\tNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\\\tDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\\\tTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\\\t(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n\\\tTHIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\\\n\noffset16\nhex\nheaders\n\nfalse value boot-debug?\n\n\\\n\\ First some housekeeping: Open \/chosen and set up vectors into\n\\\tclient-services\n\n\" \/chosen\" find-package 0= if .\" Cannot find \/chosen\" 0 then\nconstant chosen-phandle\n\n\" \/openprom\/client-services\" find-package 0= if \n\t.\" Cannot find client-services\" cr abort\nthen constant cif-phandle\n\ndefer cif-claim ( align size virt -- base )\ndefer cif-release ( size virt -- )\ndefer cif-open ( cstr -- ihandle|0 )\ndefer cif-close ( ihandle -- )\ndefer cif-read ( len adr ihandle -- #read )\ndefer cif-seek ( low high ihandle -- -1|0|1 )\n\\ defer cif-peer ( phandle -- phandle )\n\\ defer cif-getprop ( len adr cstr phandle -- )\n\n: find-cif-method ( method,len -- xf )\n cif-phandle find-method drop \n;\n\n\" claim\" find-cif-method to cif-claim\n\" open\" find-cif-method to cif-open\n\" close\" find-cif-method to cif-close\n\" read\" find-cif-method to cif-read\n\" seek\" find-cif-method to cif-seek\n\n: twiddle ( -- ) .\" .\" ; \\ Need to do this right. Just spit out periods for now.\n\n\\\n\\ Support routines\n\\\n\n: strcmp ( s1 l1 s2 l2 -- true:false )\n rot tuck <> if 3drop false exit then\n comp 0=\n;\n\n\\ Move string into buffer\n\n: strmov ( s1 l1 d -- d l1 )\n dup 2over swap -rot\t\t( s1 l1 d s1 d l1 )\n move\t\t\t\t( s1 l1 d )\n rot drop swap\n;\n\n\\ Move s1 on the end of s2 and return the result\n\n: strcat ( s1 l1 s2 l2 -- d tot )\n 2over swap \t\t\t\t( s1 l1 s2 l2 l1 s1 )\n 2over + rot\t\t\t\t( s1 l1 s2 l2 s1 d l1 )\n move rot + \t\t\t\t( s1 s2 len )\n rot drop\t\t\t\t( s2 len )\n;\n\n: strchr ( s1 l1 c -- s2 l2 )\n begin\n dup 2over 0= if\t\t\t( s1 l1 c c s1 )\n 2drop drop exit then\n c@ = if\t\t\t\t( s1 l1 c )\n drop exit then\n -rot \/c - swap ca1+\t\t( c l2 s2 )\n swap rot\n again\n;\n\n \n: cstr ( ptr -- str len )\n dup \n begin dup c@ 0<> while + repeat\n over -\n;\n\n\\\n\\ BSD FFS parameters\n\\\n\nfload\tassym.fth.h\n\nsbsize buffer: sb-buf\n-1 value boot-ihandle\ndev_bsize value bsize\n0 value raid-offset\t\\ Offset if it's a raid-frame partition\n\n: strategy ( addr size start -- nread )\n raid-offset + bsize * 0 \" seek\" boot-ihandle $call-method\n -1 = if \n .\" strategy: Seek failed\" cr\n abort\n then\n \" read\" boot-ihandle $call-method\n;\n\n\\\n\\ Cylinder group macros\n\\\n\n: cgbase ( cg fs -- cgbase ) fs_fpg l@ * ;\n: cgstart ( cg fs -- cgstart ) \n 2dup fs_cgmask l@ not and\t\t( cg fs stuff -- )\n over fs_cgoffset l@ * -rot\t\t( stuffcg fs -- )\n cgbase +\n;\n: cgdmin ( cg fs -- 1st-data-block ) dup fs_dblkno l@ -rot cgstart + ;\n: cgimin ( cg fs -- inode-block ) dup fs_iblkno l@ -rot cgstart + ;\n: cgsblock ( cg fs -- super-block ) dup fs_sblkno l@ -rot cgstart + ;\n: cgstod ( cg fs -- cg-block ) dup fs_cblkno l@ -rot cgstart + ;\n\n\\\n\\ Block and frag position macros\n\\\n\n: blkoff ( pos fs -- off ) fs_qbmask x@ and ;\n: fragoff ( pos fs -- off ) fs_qfmask x@ and ;\n: lblktosize ( blk fs -- off ) fs_bshift l@ << ;\n: lblkno ( pos fs -- off ) fs_bshift l@ >> ;\n: numfrags ( pos fs -- off ) fs_fshift l@ >> ;\n: blkroundup ( pos fs -- off ) dup fs_bmask l@ -rot fs_qbmask x@ + and ;\n: fragroundup ( pos fs -- off ) dup fs_fmask l@ -rot fs_qfmask x@ + and ;\n\\ : fragroundup ( pos fs -- off ) tuck fs_qfmask x@ + swap fs_fmask l@ and ;\n: fragstoblks ( pos fs -- off ) fs_fragshift l@ >> ;\n: blkstofrags ( blk fs -- frag ) fs_fragshift l@ << ;\n: fragnum ( fsb fs -- off ) fs_frag l@ 1- and ;\n: blknum ( fsb fs -- off ) fs_frag l@ 1- not and ;\n: dblksize ( lbn dino fs -- size )\n -rot \t\t\t\t( fs lbn dino )\n di_size x@\t\t\t\t( fs lbn di_size )\n -rot dup 1+\t\t\t\t( di_size fs lbn lbn+1 )\n 2over fs_bshift l@\t\t\t( di_size fs lbn lbn+1 di_size b_shift )\n rot swap <<\t>=\t\t\t( di_size fs lbn res1 )\n swap ndaddr >= or if\t\t\t( di_size fs )\n swap drop fs_bsize l@ exit\t( size )\n then\ttuck blkoff swap fragroundup\t( size )\n;\n\n\n: ino-to-cg ( ino fs -- cg ) fs_ipg l@ \/ ;\n: ino-to-fsbo ( ino fs -- fsb0 ) fs_inopb l@ mod ;\n: ino-to-fsba ( ino fs -- ba )\t\\ Need to remove the stupid stack diags someday\n 2dup \t\t\t\t( ino fs ino fs )\n ino-to-cg\t\t\t\t( ino fs cg )\n over\t\t\t\t\t( ino fs cg fs )\n cgimin\t\t\t\t( ino fs inode-blk )\n -rot\t\t\t\t\t( inode-blk ino fs )\n tuck \t\t\t\t( inode-blk fs ino fs )\n fs_ipg l@ \t\t\t\t( inode-blk fs ino ipg )\n mod\t\t\t\t\t( inode-blk fs mod )\n swap\t\t\t\t\t( inode-blk mod fs )\n dup \t\t\t\t\t( inode-blk mod fs fs )\n fs_inopb l@ \t\t\t\t( inode-blk mod fs inopb )\n rot \t\t\t\t\t( inode-blk fs inopb mod )\n swap\t\t\t\t\t( inode-blk fs mod inopb )\n \/\t\t\t\t\t( inode-blk fs div )\n swap\t\t\t\t\t( inode-blk div fs )\n blkstofrags\t\t\t\t( inode-blk frag )\n +\n;\n: fsbtodb ( fsb fs -- db ) fs_fsbtodb l@ << ;\n\n\\\n\\ File stuff\n\\\n\nniaddr \/w* constant narraysize\n\nstruct \n 8\t\tfield\t>f_ihandle\t\\ device handle\n 8 \t\tfield \t>f_seekp\t\\ seek pointer\n 8 \t\tfield \t>f_fs\t\t\\ pointer to super block\n ufs1_dinode_SIZEOF \tfield \t>f_di\t\\ copy of on-disk inode\n 8\t\tfield\t>f_buf\t\t\\ buffer for data block\n 4\t\tfield \t>f_buf_size\t\\ size of data block\n 4\t\tfield\t>f_buf_blkno\t\\ block number of data block\nconstant file_SIZEOF\n\nfile_SIZEOF buffer: the-file\nsb-buf the-file >f_fs x!\n\nufs1_dinode_SIZEOF buffer: cur-inode\nh# 2000 buffer: indir-block\n-1 value indir-addr\n\n\\\n\\ Translate a fileblock to a disk block\n\\\n\\ We only allow single indirection\n\\\n\n: block-map ( fileblock -- diskblock )\n \\ Direct block?\n dup ndaddr < if \t\t\t( fileblock )\n cur-inode di_db\t\t\t( arr-indx arr-start )\n swap la+ l@ exit\t\t\t( diskblock )\n then \t\t\t\t( fileblock )\n ndaddr -\t\t\t\t( fileblock' )\n \\ Now we need to check the indirect block\n dup sb-buf fs_nindir l@ < if\t( fileblock' )\n cur-inode di_ib l@ dup\t\t( fileblock' indir-block indir-block )\n indir-addr <> if \t\t( fileblock' indir-block )\n to indir-addr\t\t\t( fileblock' )\n indir-block \t\t\t( fileblock' indir-block )\n sb-buf dup fs_bsize l@\t\t( fileblock' indir-block fs fs_bsize )\n swap indir-addr swap\t\t( fileblock' indir-block fs_bsize indiraddr fs )\n fsbtodb \t\t\t( fileblock' indir-block fs_bsize db )\n strategy\t\t\t( fileblock' nread )\n then\t\t\t\t( fileblock' nread|indir-block )\n drop \\ Really should check return value\n indir-block swap la+ l@ exit\n then\n dup sb-buf fs_nindir -\t\t( fileblock'' )\n \\ Now try 2nd level indirect block -- just read twice \n dup sb-buf fs_nindir l@ dup * < if\t( fileblock'' )\n cur-inode di_ib 1 la+ l@\t\t( fileblock'' indir2-block )\n to indir-addr\t\t\t( fileblock'' )\n \\ load 1st level indir block \n indir-block \t\t\t( fileblock'' indir-block )\n sb-buf dup fs_bsize l@\t\t( fileblock'' indir-block fs fs_bsize )\n swap indir-addr swap\t\t( fileblock'' indir-block fs_bsize indiraddr fs )\n fsbtodb \t\t\t\t( fileblock'' indir-block fs_bsize db )\n strategy\t\t\t\t( fileblock'' nread )\n drop\t\t\t\t( fileblock'' )\n dup sb-buf fs_nindir \/\t\t( fileblock'' indir-offset )\n indir-block swap la+ l@\t\t( fileblock'' indirblock )\n to indir-addr\t\t\t( fileblock'' )\n \\ load 2nd level indir block\n indir-block \t\t\t( fileblock'' indir-block )\n sb-buf dup fs_bsize l@\t\t( fileblock'' indir-block fs fs_bsize )\n swap indir-addr swap\t\t( fileblock'' indir-block fs_bsize indiraddr fs )\n fsbtodb \t\t\t\t( fileblock'' indir-block fs_bsize db )\n strategy\t\t\t\t( fileblock'' nread )\n drop\t\t\t\t( fileblock'' )\n sb-buf fs_nindir l@ mod indir-block swap la+ l@ exit\n then\n .\" block-map: exceeded max file size\" cr\n abort\n;\n\n\\\n\\ Read file into internal buffer and return pointer and len\n\\\n\n2000 buffer: cur-block\t\t\\ Why do dynamic allocation?\n-1 value cur-blockno\n0 value cur-offset\n\n: buf-read-file ( fs -- len buf )\n cur-offset swap\t\t\t( seekp fs )\n 2dup blkoff\t\t\t\t( seekp fs off )\n -rot 2dup lblkno\t\t\t( off seekp fs block )\n swap 2dup cur-inode\t\t\t( off seekp block fs block fs inop )\n swap dblksize\t\t\t( off seekp block fs size )\n rot dup cur-blockno\t\t\t( off seekp fs size block block cur )\n <> if \t\t\t\t( off seekp fs size block )\n block-map\t\t\t\t( off seekp fs size diskblock )\n dup 0= if\t\t\t( off seekp fs size diskblock )\n over cur-block swap 0 fill\t( off seekp fs size diskblock )\n boot-debug? if .\" buf-read-file fell off end of file\" cr then\n else\n 2dup sb-buf fsbtodb cur-block -rot strategy\t( off seekp fs size diskblock nread )\n rot 2dup <> if \" buf-read-file: short read.\" cr abort then\n then\t\t\t\t( off seekp fs diskblock nread size )\n nip nip\t\t\t\t( off seekp fs size )\n else\t\t\t\t\t( off seekp fs size block block cur )\n 2drop\t\t\t\t( off seekp fs size )\n then\n\\ dup cur-offset + to cur-offset\t\\ Set up next xfer -- not done\n nip nip swap -\t\t\t( len )\n cur-block\n;\n\n\\\n\\ Read inode into cur-inode -- uses cur-block\n\\ \n\n: read-inode ( inode fs -- )\n twiddle\t\t\t\t( inode fs -- inode fs )\n\n cur-block\t\t\t\t( inode fs -- inode fs buffer )\n\n over\t\t\t\t\t( inode fs buffer -- inode fs buffer fs )\n fs_bsize l@\t\t\t\t( inode fs buffer -- inode fs buffer size )\n\n 2over\t\t\t\t( inode fs buffer size -- inode fs buffer size inode fs )\n 2over\t\t\t\t( inode fs buffer size inode fs -- inode fs buffer size inode fs buffer size )\n 2swap tuck\t\t\t\t( inode fs buffer size inode fs buffer size -- inode fs buffer size buffer size fs inode fs )\n\n ino-to-fsba \t\t\t\t( inode fs buffer size buffer size fs inode fs -- inode fs buffer size buffer size fs fsba )\n swap\t\t\t\t\t( inode fs buffer size buffer size fs fsba -- inode fs buffer size buffer size fsba fs )\n fsbtodb\t\t\t\t( inode fs buffer size buffer size fsba fs -- inode fs buffer size buffer size db )\n\n dup to cur-blockno\t\t\t( inode fs buffer size buffer size dstart -- inode fs buffer size buffer size dstart )\n strategy\t\t\t\t( inode fs buffer size buffer size dstart -- inode fs buffer size nread )\n <> if .\" read-inode - residual\" cr abort then\n dup 2over\t\t\t\t( inode fs buffer -- inode fs buffer buffer inode fs )\n ino-to-fsbo\t\t\t\t( inode fs buffer -- inode fs buffer buffer fsbo )\n ufs1_dinode_SIZEOF * +\t\t\t( inode fs buffer buffer fsbo -- inode fs buffer dinop )\n cur-inode ufs1_dinode_SIZEOF move \t( inode fs buffer dinop -- inode fs buffer )\n\t\\ clear out the old buffers\n drop\t\t\t\t\t( inode fs buffer -- inode fs )\n 2drop\n;\n\n\\ Identify inode type\n\n: is-dir? ( dinode -- true:false ) di_mode w@ ifmt and ifdir = ;\n: is-symlink? ( dinode -- true:false ) di_mode w@ ifmt and iflnk = ;\n\n\n\n\\\n\\ Hunt for directory entry:\n\\ \n\\ repeat\n\\ load a buffer\n\\ while entries do\n\\ if entry == name return\n\\ next entry\n\\ until no buffers\n\\\n\n: search-directory ( str len -- ino|0 )\n 0 to cur-offset\n begin cur-offset cur-inode di_size x@ < while\t( str len )\n sb-buf buf-read-file\t\t( str len len buf )\n over 0= if .\" search-directory: buf-read-file zero len\" cr abort then\n swap dup cur-offset + to cur-offset\t( str len buf len )\n 2dup + nip\t\t\t( str len buf bufend )\n swap 2swap rot\t\t\t( bufend str len buf )\n begin dup 4 pick < while\t\t( bufend str len buf )\n dup d_ino l@ 0<> if \t\t( bufend str len buf )\n boot-debug? if dup dup d_name swap d_namlen c@ type cr then\n 2dup d_namlen c@ = if\t( bufend str len buf )\n dup d_name 2over\t\t( bufend str len buf dname str len )\n comp 0= if\t\t( bufend str len buf )\n \\ Found it -- return inode\n d_ino l@ nip nip nip\t( dino )\n boot-debug? if .\" Found it\" cr then \n exit \t\t\t( dino )\n then\n then\t\t\t( bufend str len buf )\n then\t\t\t\t( bufend str len buf )\n dup d_reclen w@ +\t\t( bufend str len nextbuf )\n repeat\n drop rot drop\t\t\t( str len )\n repeat\n 2drop 2drop 0\t\t\t( 0 )\n;\n\n: ffs_oldcompat ( -- )\n\\ Make sure old ffs values in sb-buf are sane\n sb-buf fs_npsect dup l@ sb-buf fs_nsect l@ max swap l!\n sb-buf fs_interleave dup l@ 1 max swap l!\n sb-buf fs_postblformat l@ fs_42postblfmt = if\n 8 sb-buf fs_nrpos l!\n then\n sb-buf fs_inodefmt l@ fs_44inodefmt < if\n sb-buf fs_bsize l@ \n dup ndaddr * 1- sb-buf fs_maxfilesize x!\n niaddr 0 ?do\n\tsb-buf fs_nindir l@ * dup\t( sizebp sizebp -- )\n\tsb-buf fs_maxfilesize dup x@\t( sizebp sizebp *fs_maxfilesize fs_maxfilesize -- )\n\trot ( sizebp *fs_maxfilesize fs_maxfilesize sizebp -- )\n\t+ ( sizebp *fs_maxfilesize new_fs_maxfilesize -- ) swap x! ( sizebp -- )\n loop drop ( -- )\n sb-buf dup fs_bmask l@ not swap fs_qbmask x!\n sb-buf dup fs_fmask l@ not swap fs_qfmask x!\n then\n;\n\n: read-super ( sector -- )\n0 \" seek\" boot-ihandle $call-method\n -1 = if \n .\" Seek failed\" cr\n abort\n then\n sb-buf sbsize \" read\" boot-ihandle $call-method\n dup sbsize <> if\n .\" Read of superblock failed\" cr\n .\" requested\" space sbsize .\n .\" actual\" space . cr\n abort\n else \n drop\n then\n;\n\n: ufs-open ( bootpath,len -- )\n boot-ihandle -1 = if\n over cif-open dup 0= if \t\t( boot-path len ihandle? )\n .\" Could not open device\" space type cr \n abort\n then \t\t\t\t( boot-path len ihandle )\n to boot-ihandle\t\t\t\\ Save ihandle to boot device\n then 2drop\n sboff read-super\n sb-buf fs_magic l@ fs_magic_value <> if\n 64 dup to raid-offset \n dev_bsize * sboff + read-super\n sb-buf fs_magic l@ fs_magic_value <> if\n .\" Invalid superblock magic\" cr\n abort\n then\n then\n sb-buf fs_bsize l@ dup maxbsize > if\n .\" Superblock bsize\" space . .\" too large\" cr\n abort\n then \n fs_SIZEOF < if\n .\" Superblock bsize < size of superblock\" cr\n abort\n then\n ffs_oldcompat\n boot-debug? if .\" ufs-open complete\" cr then\n;\n\n: ufs-close ( -- ) \n boot-ihandle dup -1 <> if\n cif-close -1 to boot-ihandle \n then\n;\n\n: boot-path ( -- boot-path )\n \" bootpath\" chosen-phandle get-package-property if\n .\" Could not find bootpath in \/chosen\" cr\n abort\n else\n decode-string 2swap 2drop\n then\n;\n\n: boot-args ( -- boot-args )\n \" bootargs\" chosen-phandle get-package-property if\n .\" Could not find bootargs in \/chosen\" cr\n abort\n else\n decode-string 2swap 2drop\n then\n;\n\n2000 buffer: boot-path-str\n2000 buffer: boot-path-tmp\n\n: split-path ( path len -- right len left len )\n\\ Split a string at the `\/'\n begin\n dup -rot\t\t\t\t( oldlen right len left )\n ascii \/ left-parse-string\t\t( oldlen right len left len )\n dup 0<> if 4 roll drop exit then\n 2drop\t\t\t\t( oldlen right len )\n rot over =\t\t\t( right len diff )\n until\n;\n\n: find-file ( load-file len -- )\n rootino dup sb-buf read-inode\t( load-file len -- load-file len ino )\n -rot\t\t\t\t\t( load-file len ino -- pino load-file len )\n \\\n \\ For each path component\n \\ \n begin split-path dup 0<> while\t( pino right len left len -- )\n cur-inode is-dir? not if .\" Inode not directory\" cr abort then\n boot-debug? if .\" Looking for\" space 2dup type space .\" in directory...\" cr then\n search-directory\t\t\t( pino right len left len -- pino right len ino|false )\n dup 0= if .\" Bad path\" cr abort then\t( pino right len cino )\n sb-buf read-inode\t\t\t( pino right len )\n cur-inode is-symlink? if\t\t\\ Symlink -- follow the damn thing\n \\ Save path in boot-path-tmp\n boot-path-tmp strmov\t\t( pino new-right len )\n\n \\ Now deal with symlink\n cur-inode di_size x@\t\t( pino right len linklen )\n dup sb-buf fs_maxsymlinklen l@\t( pino right len linklen linklen maxlinklen )\n < if\t\t\t\t\\ Now join the link to the path\n cur-inode di_shortlink l@\t( pino right len linklen linkp )\n swap boot-path-str strmov\t( pino right len new-linkp linklen )\n else\t\t\t\t\\ Read file for symlink -- Ugh\n \\ Read link into boot-path-str\n boot-path-str dup sb-buf fs_bsize l@\n 0 block-map\t\t\t( pino right len linklen boot-path-str bsize blockno )\n strategy drop swap\t\t( pino right len boot-path-str linklen )\n then \t\t\t\t( pino right len linkp linklen )\n \\ Concatenate the two paths\n strcat\t\t\t\t( pino new-right newlen )\n swap dup c@ ascii \/ = if\t\\ go to root inode?\n rot drop rootino -rot\t( rino len right )\n then\n rot dup sb-buf read-inode\t( len right pino )\n -rot swap\t\t\t( pino right len )\n then\t\t\t\t( pino right len )\n repeat\n 2drop drop\n;\n\n: read-file ( size addr -- )\n \\ Read x bytes from a file to buffer\n begin over 0> while\n cur-offset cur-inode di_size x@ > if .\" read-file EOF exceeded\" cr abort then\n sb-buf buf-read-file\t\t( size addr len buf )\n over 2over drop swap\t\t( size addr len buf addr len )\n move\t\t\t\t( size addr len )\n dup cur-offset + to cur-offset\t( size len newaddr )\n tuck +\t\t\t\t( size len newaddr )\n -rot - swap\t\t\t( newaddr newsize )\n repeat\n 2drop\n;\n\nh# 5000 constant loader-base\n\n\\\n\\ Elf support -- find the load addr\n\\\n\n: is-elf? ( hdr -- res? ) h# 7f454c46 = ;\n\n\\\n\\ Finally we finish it all off\n\\\n\n: load-file-signon ( load-file len boot-path len -- load-file len boot-path len )\n .\" Loading file\" space 2over type cr .\" from device\" space 2dup type cr\n;\n\n: load-file-print-size ( size -- size )\n .\" Loading\" space dup . space .\" bytes of file...\" cr \n;\n\n: load-file ( load-file len boot-path len -- load-base )\n boot-debug? if load-file-signon then\n the-file file_SIZEOF 0 fill\t\t\\ Clear out file structure\n ufs-open \t\t\t\t( load-file len )\n find-file\t\t\t\t( )\n\n \\\n \\ Now we've found the file we should read it in in one big hunk\n \\\n\n cur-inode di_size x@\t\t\t( file-len )\n dup \" to file-size\" evaluate\t\t( file-len )\n boot-debug? if load-file-print-size then\n 0 to cur-offset\n loader-base\t\t\t\t( buf-len addr )\n 2dup read-file\t\t\t( buf-len addr )\n ufs-close\t\t\t\t( buf-len addr )\n dup is-elf? if .\" load-file: not an elf executable\" cr abort then\n\n \\ Luckily the prom should be able to handle ELF executables by itself\n\n nip\t\t\t\t\t( addr )\n;\n\n: do-boot ( bootfile -- )\n .\" OpenBSD IEEE 1275 Bootblock\" cr\n boot-path load-file ( -- load-base )\n dup 0<> if \" to load-base init-program\" evaluate then\n;\n\n\nboot-args ascii V strchr 0<> swap drop if\n true to boot-debug?\nthen\n\nboot-args ascii D strchr 0= swap drop if\n \" \/ofwboot\" do-boot\nthen exit\n\n\n","returncode":0,"stderr":"","license":"isc","lang":"Forth"} {"commit":"3e6288731d32f3c79ae3b8f659e8f36c111cb518","subject":"retrofit Safe Mode loader menu item actions","message":"retrofit Safe Mode loader menu item actions\n\nThe menu item is now made completely independent with the ACPI item - most\nmodern systems seem to require ACPI and become even more \"unsafe\"\nwithout it.\nSafe Mode no longer disables APIC for the same reason.\nkbdmux is not disabled as this feature has proven itself stable.\n\nNew actions:\n- SMP is disabled in the Safe Mode now\n- eventtimers are forced to periodic mode (some real and virtual systems\n seem to have problems otherwise)\n- geom extra vigorous integrity checking is disabled, this is to\n facilitate migration from previous versions\n\nPossible short term to do:\n- make SMP switch a separate menu item\n- restore APIC switch as a separate menu item\n\nLonger term to do:\n- turn various tweaks into separate menu items in a Safe Mode sub-menu\n\nPlease consider adding a safety tweak to Safe Mode when introducing\nnew major features or changes that may cause instabilities.\n\nDiscussed with:\tjhb, scottl, Devin Teske\nMFC after:\t3 weeks (stable\/9 only)\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/menu-commands.4th","new_file":"sys\/boot\/forth\/menu-commands.4th","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"bsd-3-clause","lang":"Forth"} {"commit":"6cae3b0267fdec9090271f231aff5c6244004555","subject":"Emulate CR and TYPE at the forth level.","message":"Emulate CR and TYPE at the forth level.","repos":"rbsexton\/sockpuppet,rbsexton\/sockpuppet","old_file":"forth\/serCM3_SAPI-level0.fth","new_file":"forth\/serCM3_SAPI-level0.fth","new_contents":"\\ serCM3_sapi_level0.fth - SAPI polled RX, polled TX, serial communication drivers\n\\ Written to run against the SockPuppet API.\n\n\\ Level 0 support, with WFI instead of pause.\n\\ The SAPI is a system call interace, so there is no blocking.\n\\ KEY requires blocking, so that must be implemented here.\n\n\\ Copyright (c) 2016, Robert Sexton. All rights reserved.\n\\ Covered by the terms of the supplied Licence.txt file\n\nonly forth definitions\n\n\\ ==============\n\\ *T SAPI polled serial driver\n\\ ==============\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\n\\ ** using the internal UARTs via the SAPI call layer. This is \n\\ ** The simplest implementation level.\n\\ ** It doesn't use the CR or TYPE calls, but rather emulates them.\n\n\\ ****************\n\\ *S Configuration\n\\ ****************\n\\ *P Configuration is managed by the SAPI\n\ntarget\n\n\\ ********************\n\\ *S Serial primitives\n\\ ********************\ninternal\n\n: +FaultConsole\t( -- ) ;\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\n\\ ** for more details.\n\ntarget\n\n\\ CODE (seremitfc)\t\\ char base --\n\\ This is a system call.\n\n: (seremit)\t\\ char base -- \n\\ *G Wrapped call that checks for throttling, and if so,\n\\ calls PAUSE to let another task run, or just does a WFI if no multitasker.\n\\ The only interesting thing is failure, or -1. That means retry.\n\tbegin \n\t2dup (seremitfc) dup 0 < \\ char base ret t\/f\n\tIF [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then] THEN \\ char base ret \n 0 >= until\n 2drop\n\t;\n\n: (sertype) \\ caddr len base --\n\\ *G Transmit a string on the given UART.\n -rot bounds\n ?do i c@ over (seremit) loop\n drop\n;\n\n: (sercr)\t\\ base --\n\\ *G Transmit a CR\/LF pair on the given UART.\n $0D over (seremit) $0A swap (seremit)\n;\n\n: (serkey) \\ base -- c\n\\ *G Get a character from the port. Retry until we get it.\n\\ See if its negative. If so, discard it and leave false to re-loop.\n\\ If not negative, leave true on the stack to exit.\n begin \\ base ret t\/f \n\tdup (serkeyfc) dup 0 < \\ base ret t\/f \n\t IF [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then] drop false \n\t ELSE true \n\t THEN \\ base ret t\/f \n\tuntil \\ base ret \n\tswap drop \n;\n\n\\ THis is a system call.\n\\ CODE (serkey?) \\ base -- t\/f\n\\ *G Return true if the given UART has a character avilable to read.\n\nexternal \n\n: seremit0\t\\ char --\n\\ *G Transmit a character on UART0.\n 0 (seremit) ;\n: sertype0\t\\ c-addr len --\n\\ *G Transmit a string on UART0.\n 0 (sertype) ;\n: sercr0\t\\ --\n\\ *G Issue a CR\/LF pair to UART0.\n 0 (sercr) ;\n: serkey?0\t\\ -- flag\n\\ *G Return true if UART0 has a character available.\n 0 (serkey?) ;\n: serkey0\t\\ -- char\n\\ *G Wait for a character on UART0.\n 0 (serkey) ;\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\n\\ *G Generic I\/O device for UART0.\n ' serkey0 ,\t\t\\ -- char ; receive char\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\n ' seremit0 ,\t\t\\ -- char ; display char\n ' sertype0 ,\t\t\\ caddr len -- ; display string\n ' sercr0 ,\t\t\\ -- ; display new line\n\n\\ Non-UARTs.\n: seremit10 #10 (seremit) ;\n: sertype10\t#10 (sertype) ;\n: sercr10\t#10 (sercr) ;\n: serkey?10\t#10 (serkey?) ;\n: serkey10\t#10 (serkey) ;\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\n\nconsole-port 0 = [if]\n console0 constant console\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\n\\ ** It may be changed by one of the phrases of the form:\n\\ *C dup opvec ! ipvec !\n\\ *C SetConsole\n[then]\n\nconsole-port #10 = [if]\n console10 constant console\n[then]\n\n\\ ************************\n\\ *S System initialisation\n\\ ************************\n\n\\ This is a NOP in the SAPI environment\n: init-ser ;\t\\ --\n\\ *G Initialise all serial ports\n\n\\ ======\n\\ *> ###\n\\ ======\n\ndecimal\n","old_contents":"\\ serCM3_sapi_level0.fth - SAPI polled RX, polled TX, serial communication drivers\n\\ Written to run against the SockPuppet API.\n\n\\ Level 0 support, with WFI instead of pause.\n\\ The SAPI is a system call interace, so there is no blocking.\n\\ KEY requires blocking, so that must be implemented here.\n\n\\ Copyright (c) 2016, Robert Sexton. All rights reserved.\n\\ Covered by the terms of the supplied Licence.txt file\n\nonly forth definitions\n\n\\ ==============\n\\ *T SAPI polled serial driver\n\\ ==============\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\n\\ ** using the internal UARTs via the SAPI call layer. This is \n\\ ** The simplest implementation level.\n\n\\ ****************\n\\ *S Configuration\n\\ ****************\n\\ *P Configuration is managed by the SAPI\n\ntarget\n\n\\ ********************\n\\ *S Serial primitives\n\\ ********************\ninternal\n\n: +FaultConsole\t( -- ) ;\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\n\\ ** for more details.\n\ntarget\n\n\\ CODE (seremitfc)\t\\ char base --\n\\ This is a system call.\n\n: (seremit)\t\\ char base -- \n\\ *G Wrapped call that checks for throttling, and if so,\n\\ calls PAUSE to let another task run, or just does a WFI if no multitasker.\n\\ The only interesting thing is failure, or -1. That means retry.\n\tbegin \n\t2dup (seremitfc) dup 0 < \\ char base ret t\/f\n\tIF [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then] THEN \\ char base ret \n 0 >= until\n 2drop\n\t;\n\n: (sertype) \\ caddr len base --\n\\ *G Transmit a string on the given UART.\n\\ * The system call wants base len caddr\n\\ * and it returns the number of characters sent.\n\t>R \\ We'll use this a few times.\n\tbegin \n\t2dup R@ (sertypefc) dup >R \\ caddr len ret\n\t- dup IF \\ If there are still characters left \n\t [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then]\n\t swap R> + swap \\ finish advancing the caddr len pair\n\tELSE R> drop \n\tTHEN \n\tdup 0= until \\ Do this until nothing is left.\n\t2drop \n\tR> drop \n;\n\n: (sercr)\t\\ base --\n\\ *G Transmit a CR\/LF pair on the given UART.\n\\ Wrapped version, just like (seremit)\n\tbegin \n\tdup (sercrfc) dup 0= \\ base ret t\/f\n IF [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then] THEN \\ base ret \n until\n drop\n\t;\n\n: (serkey) \\ base -- c\n\\ *G Get a character from the port. Retry until we get it.\n\\ See if its negative. If so, discard it and leave false to re-loop.\n\\ If not negative, leave true on the stack to exit.\n begin \\ base ret t\/f \n\tdup (serkeyfc) dup 0 < \\ base ret t\/f \n\t IF [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then] drop false \n\t ELSE true \n\t THEN \\ base ret t\/f \n\tuntil \\ base ret \n\tswap drop \n;\n\n\\ THis is a system call.\n\\ CODE (serkey?) \\ base -- t\/f\n\\ *G Return true if the given UART has a character avilable to read.\n\nexternal \n\n: seremit0\t\\ char --\n\\ *G Transmit a character on UART0.\n 0 (seremit) ;\n: sertype0\t\\ c-addr len --\n\\ *G Transmit a string on UART0.\n 0 (sertype) ;\n: sercr0\t\\ --\n\\ *G Issue a CR\/LF pair to UART0.\n 0 (sercr) ;\n: serkey?0\t\\ -- flag\n\\ *G Return true if UART0 has a character available.\n 0 (serkey?) ;\n: serkey0\t\\ -- char\n\\ *G Wait for a character on UART0.\n 0 (serkey) ;\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\n\\ *G Generic I\/O device for UART0.\n ' serkey0 ,\t\t\\ -- char ; receive char\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\n ' seremit0 ,\t\t\\ -- char ; display char\n ' sertype0 ,\t\t\\ caddr len -- ; display string\n ' sercr0 ,\t\t\\ -- ; display new line\n\n\\ Non-UARTs.\n: seremit10 #10 (seremit) ;\n: sertype10\t#10 (sertype) ;\n: sercr10\t#10 (sercr) ;\n: serkey?10\t#10 (serkey?) ;\n: serkey10\t#10 (serkey) ;\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\n\nconsole-port 0 = [if]\n console0 constant console\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\n\\ ** It may be changed by one of the phrases of the form:\n\\ *C dup opvec ! ipvec !\n\\ *C SetConsole\n[then]\n\nconsole-port #10 = [if]\n console10 constant console\n[then]\n\n\\ ************************\n\\ *S System initialisation\n\\ ************************\n\n\\ This is a NOP in the SAPI environment\n: init-ser ;\t\\ --\n\\ *G Initialise all serial ports\n\n\\ ======\n\\ *> ###\n\\ ======\n\ndecimal\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"db09d47f23a3d49220a076e9deecbc31ab1fcfb4","subject":"?TWO-ADJACENT-1-BITS added (not finished)","message":"?TWO-ADJACENT-1-BITS added (not finished)\n","repos":"bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas,bfontaine\/Katas","old_file":"KataDiversion.fth","new_file":"KataDiversion.fth","new_contents":"\\ KataDiversion in Forth\n\n\\ -- utils\n\n\\ empty the stack\n: EMPTY\n DEPTH 0 <> IF BEGIN\n DROP DEPTH 0 =\n UNTIL\n THEN ;\n\n\\ power\n: ** ( n1 n2 -- n1_pow_n2 ) 1 SWAP ?DUP IF 0 DO OVER * LOOP THEN NIP ;\n\n\\ test if the top is a negative number\n: ?NEG ( n -- bool ) DUP 0= IF -1 ELSE DUP ABS <> THEN ;\n\n\\ log2 (integer)\n: LOG2 ( n -- log2_n ) DUP 1 < IF 1 ABORT\" Log2 need a positive value.\"\n ELSE DUP 1 = IF 0\n ELSE\n 1 >R\n BEGIN ( n |R: i=1)\n DUP DUP 2 I ** - 2 *\n ( n n 2*[n-2**i])\n R> 1 + >R ( \u2026 |R: i+1)\n > ( n n>2*[n-2**i] )\n UNTIL\n R> 1 -\n THEN\n THEN NIP ;\n\n\\ decimal to binary\n\\ e.g. : ( 11 -- 1 0 1 1 )\n: DEC2BIN ( n -- n1 n2 n3 \u2026 ) DUP DUP 0 <> IF\n LOG2 2 SWAP ** >R ( n |R: X=2 ** n.log2 )\n BEGIN\n DUP I - 0 >= IF 1 SWAP I - ( 1 n-X )\n ELSE 0 SWAP ( 0 n )\n THEN\n I 1 =\n R> 2 \/ >R ( \u2026 | X\/2 )\n UNTIL\n R> 2DROP\n THEN\n ;\n\n\n\\ -- kata\n\n\\ test if the given N has two adjacent 1 bits\n\\ e.g. : 11 -> 1011 -> -1\n\\ 9 -> 1001 -> 0\n: ?TWO-ADJACENT-1-BITS ( \u2026 n -- bool ) ( FIXME ) DUP DEC2BIN ( n n_bin )\n 0 >R\n BEGIN\n 1 = IF I 1 = IF R> EMPTY 0 -1 >R\n ELSE R> DROP 1 >R -1\n THEN\n ELSE 0 >R -1\n THEN\n UNTIL\n R> ;\n\n\\ return the maximum number which can be made with N (given number) bits\n: ?MAX-NB ( n -- m ) DUP ?NEG IF DROP 0 ( 0 )\n ELSE \n DUP IF DUP 2 SWAP ** NIP ( 2**n )\n THEN\n THEN ;\n\n\n\\ return the number of numbers which can be made with N (given number) bits\n\\ or less, and which have not two adjacent 1 bits.\n\\ see http:\/\/www.codekata.com\/2007\/01\/code_kata_fifte.html\n: ?HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS ( n -- m ) ( TODO ) ;\n","old_contents":"\\ KataDiversion in Forth\n\n\\ -- utils\n\n\\ empty the stack\n: EMPTY\n DEPTH 0 <> IF BEGIN\n DROP DEPTH 0 =\n UNTIL\n THEN ;\n\n\\ power\n: ** ( n1 n2 -- n1_pow_n2 ) 1 SWAP ?DUP IF 0 DO OVER * LOOP THEN NIP ;\n\n\\ test if the top is a negative number\n: ?NEG ( n -- bool ) DUP 0= IF -1 ELSE DUP ABS <> THEN ;\n\n\\ log2 (integer)\n: LOG2 ( n -- log2_n ) DUP 1 < IF 1 ABORT\" Log2 need a positive value.\"\n ELSE DUP 1 = IF 0\n ELSE\n 1 >R\n BEGIN ( n |R: i=1)\n DUP DUP 2 I ** - 2 *\n ( n n 2*[n-2**i])\n R> 1 + >R ( \u2026 |R: i+1)\n > ( n n>2*[n-2**i] )\n UNTIL\n R> 1 -\n THEN\n THEN NIP ;\n\n\\ decimal to binary\n\\ e.g. : ( 11 -- 1 0 1 1 )\n: DEC2BIN ( n -- n1 n2 n3 \u2026 ) DUP DUP 0 <> IF\n LOG2 2 SWAP ** >R ( n |R: X=2 ** n.log2 )\n BEGIN\n DUP I - 0 >= IF 1 SWAP I - ( 1 n-X )\n ELSE 0 SWAP ( 0 n )\n THEN\n I 1 =\n R> 2 \/ >R ( \u2026 | X\/2 )\n UNTIL\n R> 2DROP\n THEN\n ;\n\n\\ -- kata\n\n\\ test if the given N has two adjacent 1 bits\n\\ e.g. : 1011 -> -1\n\\ 1001 -> 0\n: ?TWO-ADJACENT-1-BITS ( n -- bool ) ( TODO ) ;\n\n\\ return the maximum number which can be made with N (given number) bits\n: ?MAX-NB ( n -- m ) DUP ?NEG IF DROP 0 ( 0 )\n ELSE \n DUP IF DUP 2 SWAP ** NIP ( 2**n )\n THEN\n THEN ;\n\n\n\\ return the number of numbers which can be made with N (given number) bits\n\\ or less, and which have not two adjacent 1 bits.\n\\ see http:\/\/www.codekata.com\/2007\/01\/code_kata_fifte.html\n: ?HOW-MANY-NB-NOT-TWO-ADJACENT-1-BITS ( n -- m ) ( TODO ) ;\n","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"162617cdc24accd1188c9548fabd3ce4ce83707e","subject":"Clean up the comments.","message":"Clean up the comments.","repos":"rbsexton\/sockpuppet,rbsexton\/sockpuppet","old_file":"forth\/dylink.fth","new_file":"forth\/dylink.fth","new_contents":"\\ Code to support runtime\/dynamic into the C side via SAPI.\n\\\n\\ In the MPE environment, VALUEs work very well for this.\n\\ values are defined at compile time and can be updated at runtime.\n\n\n\\ ************************************************************************\n\\ ************************************************************************\n\\ Secondary support functions \n\\ ************************************************************************\n\\ ************************************************************************\n\n\\ *********************************************\n\\ Accessors - Tightly tied the data structure\n\\ *********************************************\n: dy.val @ ; \n: dy.size #4 + w@ ; \n: dy.count #6 + w@ ; \n: dy.type #8 + c@ ;\n: dy.namelen #9 + c@ ;\n: dy.name #12 + @ ;\n\n\\ Return the recordlength. Its the first thing.\n: dy-recordlen getsharedvars @ ;\n\n\\ Retrieve the string.\n: dy-string ( addr -- caddr n ) \n dup dy.name swap dy.namelen \n; \n\n\\ Create a constant from scratch by laying down some assembly\n\\ A key trick is that we have to lay down a pointer to \n\\ the first character of the defintion after we finish\n\\ See the definition above for the template\n: make-const \\ n s-addr c --\n\there 4+ >r \\ This should point to the newly-created header.\n\tmakeheader \\\n\n\\ This is what a constant looks like after emerging from the compiler.\t\n\\ ( 0002:0270 4CF8047D Lx.} ) str r7, [ r12, # $-04 ]!\n\\ ( 0002:0274 004F .O ) ldr r7, [ PC, # $00 ] ( @$20278=$7D04F84C )\n\\ ( 0002:0276 7047 pG ) bx LR\n\n\t$7D04F84C , \\ str r7, [ r12, # $-04 ]!\n\t$4f00 w, \\ ldr r7, [ PC, # $00 ]\n\t$4770 w, \\ bx LR\n\t, \t \\ Lay down the payload\n\n\tr> , \\ lay down the link field for the next word - required\n\t;\n\t\n\\ Dump out an entry as a set of constants\n: dy-print \\ c-addr --\n S\" $\" type\n DUP dy.val . \\ Fetch the value\n \n DUP dy.type [CHAR] V = \\ check the type \n \n IF\n \tS\" VALUE \"\n ELSE\n \tS\" CONSTANT \"\n THEN\n TYPE \\ Display the result\n DUP dy.size . S\" x\" DUP dy.count .\n dy-string TYPE\n CR\n ; \n\n\\ Take a pointer to a dynamic link record, and add a constant to the dictionary\n: dy-create \\ addr --\n\tDUP \\ addr addr \n\tdy.val \\ c-addr n \n\tSWAP dy-string \\ n c-addr b\n make-const\n ;\n\n\\ Given a record address and a string, figure out\n\\ if thats the one we're looking for\n: dy-compare ( caddr n addr -- n ) \n dy-string compare \n;\n\n\\ Find the record in the list to go with a string\n: dy-find ( c-addr n -- addr|0 ) \n getsharedvars dy-recordlen + \\ Skip over the empty first record\n >R \\ Put it onto the return stack\n BEGIN\n R@ dy.val 0<>\n WHILE \n 2DUP R@ dy-compare\n \\ If we find it, clean the stack and leave the address on R\n 0= IF 2DROP R> EXIT THEN\n R> dy-recordlen + >R\n REPEAT\n \\ If we fall out, there will be a string caddr\/n on the stack\n 2DROP R> DROP \n 0 \\ Leave behind a zero to indicate failure\n;\n\n\\ Walk the table and make the constants.\n: dy-populate\n getsharedvars dy-recordlen + \\ Skip over the empty first record\n BEGIN \n dup dy.val 0<> \n WHILE\n dup dy-create\n dy-recordlen +\n REPEAT\n 2DROP R> DROP 0\n ; \n \n","old_contents":"\\ Code to support runtime\/dynamic into the C side via SAPI.\n\n\\ ************************************************************************\n\\ ************************************************************************\n\\ Secondary support functions \n\\ ************************************************************************\n\\ ************************************************************************\n\n\\ *********************************************\n\\ Accessors - Tightly tied the data structure\n\\ *********************************************\n: dy.val @ ; \n: dy.size #4 + w@ ; \n: dy.count #6 + w@ ; \n: dy.type #8 + c@ ;\n: dy.namelen #9 + c@ ;\n: dy.name #12 + @ ;\n\n\\ Return the recordlength. Its the first thing.\n: dy-recordlen getsharedvars @ ;\n\n\\ Retrieve the string.\n: dy-string ( addr -- caddr n ) \n dup dy.name swap dy.namelen \n; \n\n\\ Heres some assembly code to use as a template.\n\\ I experimented a bit, and the simplest thing in the MPE\n\\ Forth environment is to lay down the assembly\n((\nCODE rawconstant\n\tstr tos, [ psp, # -4 ] ! \\ register push\n ldr tos, L$1\n\tbx lr\nL$1: str tos, [ psp, # -4 ] ! \\ 32-bit dummy instruction\nEND-CODE\n))\n\n\\ Create a constant from scratch by laying down some assembly\n\\ A key trick is that we have to lay down a pointer to \n\\ the first character of the defintion after we finish\n\\ See the definition above for the template\n: make-const \\ n s-addr c --\n\there 4+ >r \\ This should point to the newly-created header.\n\tmakeheader \\\n\t\n\\ ( 0002:0270 4CF8047D Lx.} ) str r7, [ r12, # $-04 ]!\n\\ ( 0002:0274 004F .O ) ldr r7, [ PC, # $00 ] ( @$20278=$7D04F84C )\n\\ ( 0002:0276 7047 pG ) bx LR\n\n\t$7D04F84C , \\ str r7, [ r12, # $-04 ]!\n\t$4f00 w, \\ ldr r7, [ PC, # $00 ]\n\t$4770 w, \\ bx LR\n\t, \t \\ Lay down the payload\n\n\tr> , \\ lay down the link field for the next word - required\n\t;\n\t\n\\ Dump out an entry as a set of constants\n: dy-print \\ c-addr --\n S\" $\" type\n DUP dy.val . \\ Fetch the value\n \n DUP dy.type [CHAR] V = \\ check the type \n \n IF\n \tS\" VALUE \"\n ELSE\n \tS\" CONSTANT \"\n THEN\n TYPE \\ Display the result\n DUP dy.size . S\" x\" DUP dy.count .\n dy-string TYPE\n CR\n ; \n\n\\ Take a pointer to a dynamic link record, and add a constant to the dictionary\n: dy-create \\ addr --\n\tDUP \\ addr addr \n\tdy.val \\ c-addr n \n\tSWAP dy-string \\ n c-addr b\n make-const\n ;\n\n\\ Given a record address and a string, figure out\n\\ if thats the one we're looking for\n: dy-compare ( caddr n addr -- n ) \n dy-string compare \n;\n\n\\ Find the record in the list to go with a string\n: dy-find ( c-addr n -- addr|0 ) \n getsharedvars dy-recordlen + \\ Skip over the empty first record\n >R \\ Put it onto the return stack\n BEGIN\n R@ dy.val 0<>\n WHILE \n 2DUP R@ dy-compare\n \\ If we find it, clean the stack and leave the address on R\n 0= IF 2DROP R> EXIT THEN\n R> dy-recordlen + >R\n REPEAT\n \\ If we fall out, there will be a string caddr\/n on the stack\n 2DROP R> DROP \n 0 \\ Leave behind a zero to indicate failure\n;\n\n\\ Walk the table and make the constants.\n: dy-populate\n getsharedvars dy-recordlen + \\ Skip over the empty first record\n BEGIN \n dup dy.val 0<> \n WHILE\n dup dy-create\n dy-recordlen +\n REPEAT\n 2DROP R> DROP 0\n ; \n \n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"96bba78abe47f2c895c63531755845e9a265267d","subject":"Fix an error message which was using the wrong variable to get the kernel name from.","message":"Fix an error message which was using the wrong variable to get the\nkernel name from.\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/support.4th","new_file":"sys\/boot\/forth\/support.4th","new_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\ \n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\n\\ Loader.rc support functions:\n\\\n\\ initialize_support ( -- )\tinitialize global variables\n\\ initialize ( addr len -- )\tas above, plus load_conf_files\n\\ load_conf ( addr len -- )\tload conf file given\n\\ include_conf_files ( -- )\tload all conf files in load_conf_files\n\\ print_syntax_error ( -- )\tprint line and marker of where a syntax\n\\\t\t\t\terror was detected\n\\ print_line ( -- )\t\tprint last line processed\n\\ load_kernel ( -- )\t\tload kernel\n\\ load_modules ( -- )\t\tload modules flagged\n\\\n\\ Exported structures:\n\\\n\\ string\t\t\tcounted string structure\n\\\tcell .addr\t\t\tstring address\n\\\tcell .len\t\t\tstring length\n\\ module\t\t\tmodule loading information structure\n\\\tcell module.flag\t\tshould we load it?\n\\\tstring module.name\t\tmodule's name\n\\\tstring module.loadname\t\tname to be used in loading the module\n\\\tstring module.type\t\tmodule's type\n\\\tstring module.args\t\tflags to be passed during load\n\\\tstring module.beforeload\tcommand to be executed before load\n\\\tstring module.afterload\t\tcommand to be executed after load\n\\\tstring module.loaderror\t\tcommand to be executed if load fails\n\\\tcell module.next\t\tlist chain\n\\\n\\ Exported global variables;\n\\\n\\ string conf_files\t\tconfiguration files to be loaded\n\\ string password\t\tpassword\n\\ cell modules_options\t\tpointer to first module information\n\\ value verbose?\t\tindicates if user wants a verbose loading\n\\ value any_conf_read?\t\tindicates if a conf file was succesfully read\n\\\n\\ Other exported words:\n\\\n\\ strdup ( addr len -- addr' len)\t\t\tsimilar to strdup(3)\n\\ strcat ( addr len addr' len' -- addr len+len' )\tsimilar to strcat(3)\n\\ strlen ( addr -- len )\t\t\t\tsimilar to strlen(3)\n\\ s' ( | string' -- addr len | )\t\t\tsimilar to s\"\n\\ rudimentary structure support\n\n\\ Exception values\n\n1 constant syntax_error\n2 constant out_of_memory\n3 constant free_error\n4 constant set_error\n5 constant read_error\n6 constant open_error\n7 constant exec_error\n8 constant before_load_error\n9 constant after_load_error\n\n\\ Crude structure support\n\n: structure:\n create here 0 , ['] drop , 0\n does> create here swap dup @ allot cell+ @ execute\n;\n: member: create dup , over , + does> cell+ @ + ;\n: ;structure swap ! ;\n: constructor! >body cell+ ! ;\n: constructor: over :noname ;\n: ;constructor postpone ; swap cell+ ! ; immediate\n: sizeof ' >body @ state @ if postpone literal then ; immediate\n: offsetof ' >body cell+ @ state @ if postpone literal then ; immediate\n: ptr 1 cells member: ;\n: int 1 cells member: ;\n\n\\ String structure\n\nstructure: string\n\tptr .addr\n\tint .len\n\tconstructor:\n\t 0 over .addr !\n\t 0 swap .len !\n\t;constructor\n;structure\n\n\n\\ Module options linked list\n\nstructure: module\n\tint module.flag\n\tsizeof string member: module.name\n\tsizeof string member: module.loadname\n\tsizeof string member: module.type\n\tsizeof string member: module.args\n\tsizeof string member: module.beforeload\n\tsizeof string member: module.afterload\n\tsizeof string member: module.loaderror\n\tptr module.next\n;structure\n\n\\ Internal loader structures\nstructure: preloaded_file\n\tptr pf.name\n\tptr pf.type\n\tptr pf.args\n\tptr pf.metadata\t\\ file_metadata\n\tint pf.loader\n\tint pf.addr\n\tint pf.size\n\tptr pf.modules\t\\ kernel_module\n\tptr pf.next\t\\ preloaded_file\n;structure\n\nstructure: kernel_module\n\tptr km.name\n\t\\ ptr km.args\n\tptr km.fp\t\\ preloaded_file\n\tptr km.next\t\\ kernel_module\n;structure\n\nstructure: file_metadata\n\tint\t\tmd.size\n\t2 member:\tmd.type\t\\ this is not ANS Forth compatible (XXX)\n\tptr\t\tmd.next\t\\ file_metadata\n\t0 member:\tmd.data\t\\ variable size\n;structure\n\nstructure: config_resource\n\tptr cf.name\n\tint cf.type\n0 constant RES_INT\n1 constant RES_STRING\n2 constant RES_LONG\n\t2 cells member: u\n;structure\n\nstructure: config_device\n\tptr cd.name\n\tint cd.unit\n\tint cd.resource_count\n\tptr cd.resources\t\\ config_resource\n;structure\n\nstructure: STAILQ_HEAD\n\tptr stqh_first\t\\ type*\n\tptr stqh_last\t\\ type**\n;structure\n\nstructure: STAILQ_ENTRY\n\tptr stqe_next\t\\ type*\n;structure\n\nstructure: pnphandler\n\tptr pnph.name\n\tptr pnph.enumerate\n;structure\n\nstructure: pnpident\n\tptr pnpid.ident\t\t\t\t\t\\ char*\n\tsizeof STAILQ_ENTRY cells member: pnpid.link\t\\ pnpident\n;structure\n\nstructure: pnpinfo\n\tptr pnpi.desc\n\tint pnpi.revision\n\tptr pnpi.module\t\t\t\t\\ (char*) module args\n\tint pnpi.argc\n\tptr pnpi.argv\n\tptr pnpi.handler\t\t\t\\ pnphandler\n\tsizeof STAILQ_HEAD member: pnpi.ident\t\\ pnpident\n\tsizeof STAILQ_ENTRY member: pnpi.link\t\\ pnpinfo\n;structure\n\n\\ Global variables\n\nstring conf_files\nstring password\ncreate module_options sizeof module.next allot 0 module_options !\ncreate last_module_option sizeof module.next allot 0 last_module_option !\n0 value verbose?\n\n\\ Support string functions\n\n: strdup ( addr len -- addr' len )\n >r r@ allocate if out_of_memory throw then\n tuck r@ move\n r>\n;\n\n: strcat { addr len addr' len' -- addr len+len' }\n addr' addr len + len' move\n addr len len' +\n;\n\n: strlen ( addr -- len )\n 0 >r\n begin\n dup c@ while\n 1+ r> 1+ >r repeat\n drop r>\n;\n\n: s' \n [char] ' parse\n state @ if\n postpone sliteral\n then\n; immediate\n\n: 2>r postpone >r postpone >r ; immediate\n: 2r> postpone r> postpone r> ; immediate\n\n\\ Private definitions\n\nvocabulary support-functions\nonly forth also support-functions definitions\n\n\\ Some control characters constants\n\n7 constant bell\n8 constant backspace\n9 constant tab\n10 constant lf\n13 constant \n\n\\ Read buffer size\n\n80 constant read_buffer_size\n\n\\ Standard suffixes\n\n: load_module_suffix s\" _load\" ;\n: module_loadname_suffix s\" _name\" ;\n: module_type_suffix s\" _type\" ;\n: module_args_suffix s\" _flags\" ;\n: module_beforeload_suffix s\" _before\" ;\n: module_afterload_suffix s\" _after\" ;\n: module_loaderror_suffix s\" _error\" ;\n\n\\ Support operators\n\n: >= < 0= ;\n: <= > 0= ;\n\n\\ Assorted support funcitons\n\n: free-memory free if free_error throw then ;\n\n\\ Assignment data temporary storage\n\nstring name_buffer\nstring value_buffer\n\n\\ Line by line file reading functions\n\\\n\\ exported:\n\\\tline_buffer\n\\\tend_of_file?\n\\\tfd\n\\\tread_line\n\\\treset_line_reading\n\nvocabulary line-reading\nalso line-reading definitions also\n\n\\ File data temporary storage\n\nstring read_buffer\n0 value read_buffer_ptr\n\n\\ File's line reading function\n\nsupport-functions definitions\n\nstring line_buffer\n0 value end_of_file?\nvariable fd\n\nline-reading definitions\n\n: skip_newlines\n begin\n read_buffer .len @ read_buffer_ptr >\n while\n read_buffer .addr @ read_buffer_ptr + c@ lf = if\n read_buffer_ptr char+ to read_buffer_ptr\n else\n exit\n then\n repeat\n;\n\n: scan_buffer ( -- addr len )\n read_buffer_ptr >r\n begin\n read_buffer .len @ r@ >\n while\n read_buffer .addr @ r@ + c@ lf = if\n read_buffer .addr @ read_buffer_ptr + ( -- addr )\n r@ read_buffer_ptr - ( -- len )\n r> to read_buffer_ptr\n exit\n then\n r> char+ >r\n repeat\n read_buffer .addr @ read_buffer_ptr + ( -- addr )\n r@ read_buffer_ptr - ( -- len )\n r> to read_buffer_ptr\n;\n\n: line_buffer_resize ( len -- len )\n >r\n line_buffer .len @ if\n line_buffer .addr @\n line_buffer .len @ r@ +\n resize if out_of_memory throw then\n else\n r@ allocate if out_of_memory throw then\n then\n line_buffer .addr !\n r>\n;\n \n: append_to_line_buffer ( addr len -- )\n line_buffer .addr @ line_buffer .len @\n 2swap strcat\n line_buffer .len !\n drop\n;\n\n: read_from_buffer\n scan_buffer ( -- addr len )\n line_buffer_resize ( len -- len )\n append_to_line_buffer ( addr len -- )\n;\n\n: refill_required?\n read_buffer .len @ read_buffer_ptr =\n end_of_file? 0= and\n;\n\n: refill_buffer\n 0 to read_buffer_ptr\n read_buffer .addr @ 0= if\n read_buffer_size allocate if out_of_memory throw then\n read_buffer .addr !\n then\n fd @ read_buffer .addr @ read_buffer_size fread\n dup -1 = if read_error throw then\n dup 0= if true to end_of_file? then\n read_buffer .len !\n;\n\n: reset_line_buffer\n line_buffer .addr @ ?dup if\n free-memory\n then\n 0 line_buffer .addr !\n 0 line_buffer .len !\n;\n\nsupport-functions definitions\n\n: reset_line_reading\n 0 to read_buffer_ptr\n;\n\n: read_line\n reset_line_buffer\n skip_newlines\n begin\n read_from_buffer\n refill_required?\n while\n refill_buffer\n repeat\n;\n\nonly forth also support-functions definitions\n\n\\ Conf file line parser:\n\\ ::= '='[] |\n\\ []\n\\ ::= {||'_'}\n\\ ::= '\"'{|'\\'}'\"' | \n\\ ::= ASCII 32 to 126, except '\\' and '\"'\n\\ ::= '#'{}\n\\\n\\ exported:\n\\\tline_pointer\n\\\tprocess_conf\n\n0 value line_pointer\n\nvocabulary file-processing\nalso file-processing definitions\n\n\\ parser functions\n\\\n\\ exported:\n\\\tget_assignment\n\nvocabulary parser\nalso parser definitions also\n\n0 value parsing_function\n0 value end_of_line\n\n: end_of_line?\n line_pointer end_of_line =\n;\n\n: letter?\n line_pointer c@ >r\n r@ [char] A >=\n r@ [char] Z <= and\n r@ [char] a >=\n r> [char] z <= and\n or\n;\n\n: digit?\n line_pointer c@ >r\n r@ [char] 0 >=\n r> [char] 9 <= and\n;\n\n: quote?\n line_pointer c@ [char] \" =\n;\n\n: assignment_sign?\n line_pointer c@ [char] = =\n;\n\n: comment?\n line_pointer c@ [char] # =\n;\n\n: space?\n line_pointer c@ bl =\n line_pointer c@ tab = or\n;\n\n: backslash?\n line_pointer c@ [char] \\ =\n;\n\n: underscore?\n line_pointer c@ [char] _ =\n;\n\n: dot?\n line_pointer c@ [char] . =\n;\n\n: skip_character\n line_pointer char+ to line_pointer\n;\n\n: skip_to_end_of_line\n end_of_line to line_pointer\n;\n\n: eat_space\n begin\n space?\n while\n skip_character\n end_of_line? if exit then\n repeat\n;\n\n: parse_name ( -- addr len )\n line_pointer\n begin\n letter? digit? underscore? dot? or or or\n while\n skip_character\n end_of_line? if \n line_pointer over -\n strdup\n exit\n then\n repeat\n line_pointer over -\n strdup\n;\n\n: remove_backslashes { addr len | addr' len' -- addr' len' }\n len allocate if out_of_memory throw then\n to addr'\n addr >r\n begin\n addr c@ [char] \\ <> if\n addr c@ addr' len' + c!\n len' char+ to len'\n then\n addr char+ to addr\n r@ len + addr =\n until\n r> drop\n addr' len'\n;\n\n: parse_quote ( -- addr len )\n line_pointer\n skip_character\n end_of_line? if syntax_error throw then\n begin\n quote? 0=\n while\n backslash? if\n skip_character\n end_of_line? if syntax_error throw then\n then\n skip_character\n end_of_line? if syntax_error throw then \n repeat\n skip_character\n line_pointer over -\n remove_backslashes\n;\n\n: read_name\n parse_name\t\t( -- addr len )\n name_buffer .len !\n name_buffer .addr !\n;\n\n: read_value\n quote? if\n parse_quote\t\t( -- addr len )\n else\n parse_name\t\t( -- addr len )\n then\n value_buffer .len !\n value_buffer .addr !\n;\n\n: comment\n skip_to_end_of_line\n;\n\n: white_space_4\n eat_space\n comment? if ['] comment to parsing_function exit then\n end_of_line? 0= if syntax_error throw then\n;\n\n: variable_value\n read_value\n ['] white_space_4 to parsing_function\n;\n\n: white_space_3\n eat_space\n letter? digit? quote? or or if\n ['] variable_value to parsing_function exit\n then\n syntax_error throw\n;\n\n: assignment_sign\n skip_character\n ['] white_space_3 to parsing_function\n;\n\n: white_space_2\n eat_space\n assignment_sign? if ['] assignment_sign to parsing_function exit then\n syntax_error throw\n;\n\n: variable_name\n read_name\n ['] white_space_2 to parsing_function\n;\n\n: white_space_1\n eat_space\n letter? if ['] variable_name to parsing_function exit then\n comment? if ['] comment to parsing_function exit then\n end_of_line? 0= if syntax_error throw then\n;\n\nfile-processing definitions\n\n: get_assignment\n line_buffer .addr @ line_buffer .len @ + to end_of_line\n line_buffer .addr @ to line_pointer\n ['] white_space_1 to parsing_function\n begin\n end_of_line? 0=\n while\n parsing_function execute\n repeat\n parsing_function ['] comment =\n parsing_function ['] white_space_1 =\n parsing_function ['] white_space_4 =\n or or 0= if syntax_error throw then\n;\n\nonly forth also support-functions also file-processing definitions also\n\n\\ Process line\n\n: assignment_type? ( addr len -- flag )\n name_buffer .addr @ name_buffer .len @\n compare 0=\n;\n\n: suffix_type? ( addr len -- flag )\n name_buffer .len @ over <= if 2drop false exit then\n name_buffer .len @ over - name_buffer .addr @ +\n over compare 0=\n;\n\n: loader_conf_files?\n s\" loader_conf_files\" assignment_type?\n;\n\n: verbose_flag?\n s\" verbose_loading\" assignment_type?\n;\n\n: execute?\n s\" exec\" assignment_type?\n;\n\n: password?\n s\" password\" assignment_type?\n;\n\n: module_load?\n load_module_suffix suffix_type?\n;\n\n: module_loadname?\n module_loadname_suffix suffix_type?\n;\n\n: module_type?\n module_type_suffix suffix_type?\n;\n\n: module_args?\n module_args_suffix suffix_type?\n;\n\n: module_beforeload?\n module_beforeload_suffix suffix_type?\n;\n\n: module_afterload?\n module_afterload_suffix suffix_type?\n;\n\n: module_loaderror?\n module_loaderror_suffix suffix_type?\n;\n\n: set_conf_files\n conf_files .addr @ ?dup if\n free-memory\n then\n value_buffer .addr @ c@ [char] \" = if\n value_buffer .addr @ char+ value_buffer .len @ 2 chars -\n else\n value_buffer .addr @ value_buffer .len @\n then\n strdup\n conf_files .len ! conf_files .addr !\n;\n\n: append_to_module_options_list ( addr -- )\n module_options @ 0= if\n dup module_options !\n last_module_option !\n else\n dup last_module_option @ module.next !\n last_module_option !\n then\n;\n\n: set_module_name ( addr -- )\n name_buffer .addr @ name_buffer .len @\n strdup\n >r over module.name .addr !\n r> swap module.name .len !\n;\n\n: yes_value?\n value_buffer .addr @ value_buffer .len @\n 2dup s' \"YES\"' compare >r\n 2dup s' \"yes\"' compare >r\n 2dup s\" YES\" compare >r\n s\" yes\" compare r> r> r> and and and 0=\n;\n\n: find_module_option ( -- addr | 0 )\n module_options @\n begin\n dup\n while\n dup module.name dup .addr @ swap .len @\n name_buffer .addr @ name_buffer .len @\n compare 0= if exit then\n module.next @\n repeat\n;\n\n: new_module_option ( -- addr )\n sizeof module allocate if out_of_memory throw then\n dup sizeof module erase\n dup append_to_module_options_list\n dup set_module_name\n;\n\n: get_module_option ( -- addr )\n find_module_option\n ?dup 0= if new_module_option then\n;\n\n: set_module_flag\n name_buffer .len @ load_module_suffix nip - name_buffer .len !\n yes_value? get_module_option module.flag !\n;\n\n: set_module_args\n name_buffer .len @ module_args_suffix nip - name_buffer .len !\n get_module_option module.args\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_loadname\n name_buffer .len @ module_loadname_suffix nip - name_buffer .len !\n get_module_option module.loadname\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_type\n name_buffer .len @ module_type_suffix nip - name_buffer .len !\n get_module_option module.type\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_beforeload\n name_buffer .len @ module_beforeload_suffix nip - name_buffer .len !\n get_module_option module.beforeload\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_afterload\n name_buffer .len @ module_afterload_suffix nip - name_buffer .len !\n get_module_option module.afterload\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_loaderror\n name_buffer .len @ module_loaderror_suffix nip - name_buffer .len !\n get_module_option module.loaderror\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_environment_variable\n name_buffer .len @\n value_buffer .len @ +\n 5 chars +\n allocate if out_of_memory throw then\n dup 0 ( addr -- addr addr len )\n s\" set \" strcat\n name_buffer .addr @ name_buffer .len @ strcat\n s\" =\" strcat\n value_buffer .addr @ value_buffer .len @ strcat\n ['] evaluate catch if\n 2drop free drop\n set_error throw\n else\n free-memory\n then\n;\n\n: set_verbose\n yes_value? to verbose?\n;\n\n: execute_command\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 - swap char+ swap\n then\n ['] evaluate catch if exec_error throw then\n;\n\n: set_password\n password .addr @ ?dup if free if free_error throw then then\n value_buffer .addr @ c@ [char] \" = if\n value_buffer .addr @ char+ value_buffer .len @ 2 - strdup\n value_buffer .addr @ free if free_error throw then\n else\n value_buffer .addr @ value_buffer .len @\n then\n password .len ! password .addr !\n 0 value_buffer .addr !\n;\n\n: process_assignment\n name_buffer .len @ 0= if exit then\n loader_conf_files?\tif set_conf_files exit then\n verbose_flag?\t\tif set_verbose exit then\n execute?\t\tif execute_command exit then\n password?\t\tif set_password exit then\n module_load?\t\tif set_module_flag exit then\n module_loadname?\tif set_module_loadname exit then\n module_type?\t\tif set_module_type exit then\n module_args?\t\tif set_module_args exit then\n module_beforeload?\tif set_module_beforeload exit then\n module_afterload?\tif set_module_afterload exit then\n module_loaderror?\tif set_module_loaderror exit then\n set_environment_variable\n;\n\n\\ free_buffer ( -- )\n\\\n\\ Free some pointers if needed. The code then tests for errors\n\\ in freeing, and throws an exception if needed. If a pointer is\n\\ not allocated, it's value (0) is used as flag.\n\n: free_buffers\n name_buffer .addr @ dup if free then\n value_buffer .addr @ dup if free then\n or if free_error throw then\n;\n\n: reset_assignment_buffers\n 0 name_buffer .addr !\n 0 name_buffer .len !\n 0 value_buffer .addr !\n 0 value_buffer .len !\n;\n\n\\ Higher level file processing\n\nsupport-functions definitions\n\n: process_conf\n begin\n end_of_file? 0=\n while\n reset_assignment_buffers\n read_line\n get_assignment\n ['] process_assignment catch\n ['] free_buffers catch\n swap throw throw\n repeat\n;\n\nonly forth also support-functions definitions\n\n: create_null_terminated_string { addr len -- addr' len }\n len char+ allocate if out_of_memory throw then\n >r\n addr r@ len move\n 0 r@ len + c!\n r> len\n;\n\n\\ Interface to loading conf files\n\n: load_conf ( addr len -- )\n 0 to end_of_file?\n reset_line_reading\n create_null_terminated_string\n over >r\n fopen fd !\n r> free-memory\n fd @ -1 = if open_error throw then\n ['] process_conf catch\n fd @ fclose\n throw\n;\n\n: print_line\n line_buffer .addr @ line_buffer .len @ type cr\n;\n\n: print_syntax_error\n line_buffer .addr @ line_buffer .len @ type cr\n line_buffer .addr @\n begin\n line_pointer over <>\n while\n bl emit\n char+\n repeat\n drop\n .\" ^\" cr\n;\n\n\\ Depuration support functions\n\nonly forth definitions also support-functions\n\n: test-file \n ['] load_conf catch dup .\n syntax_error = if cr print_syntax_error then\n;\n\n: show-module-options\n module_options @\n begin\n ?dup\n while\n .\" Name: \" dup module.name dup .addr @ swap .len @ type cr\n .\" Path: \" dup module.loadname dup .addr @ swap .len @ type cr\n .\" Type: \" dup module.type dup .addr @ swap .len @ type cr\n .\" Flags: \" dup module.args dup .addr @ swap .len @ type cr\n .\" Before load: \" dup module.beforeload dup .addr @ swap .len @ type cr\n .\" After load: \" dup module.afterload dup .addr @ swap .len @ type cr\n .\" Error: \" dup module.loaderror dup .addr @ swap .len @ type cr\n .\" Status: \" dup module.flag @ if .\" Load\" else .\" Don't load\" then cr\n module.next @\n repeat\n;\n\nonly forth also support-functions definitions\n\n\\ Variables used for processing multiple conf files\n\nstring current_file_name\nvariable current_conf_files\n\n\\ Indicates if any conf file was succesfully read\n\n0 value any_conf_read?\n\n\\ loader_conf_files processing support functions\n\n: set_current_conf_files\n conf_files .addr @ current_conf_files !\n;\n\n: get_conf_files\n conf_files .addr @ conf_files .len @ strdup\n;\n\n: recurse_on_conf_files?\n current_conf_files @ conf_files .addr @ <>\n;\n\n: skip_leading_spaces { addr len pos -- addr len pos' }\n begin\n pos len = if addr len pos exit then\n addr pos + c@ bl =\n while\n pos char+ to pos\n repeat\n addr len pos\n;\n\n: get_file_name { addr len pos -- addr len pos' addr' len' || 0 }\n pos len = if \n addr free abort\" Fatal error freeing memory\"\n 0 exit\n then\n pos >r\n begin\n addr pos + c@ bl <>\n while\n pos char+ to pos\n pos len = if\n addr len pos addr r@ + pos r> - exit\n then\n repeat\n addr len pos addr r@ + pos r> -\n;\n\n: get_next_file ( addr len ptr -- addr len ptr' addr' len' | 0 )\n skip_leading_spaces\n get_file_name\n;\n\n: set_current_file_name\n over current_file_name .addr !\n dup current_file_name .len !\n;\n\n: print_current_file\n current_file_name .addr @ current_file_name .len @ type\n;\n\n: process_conf_errors\n dup 0= if true to any_conf_read? drop exit then\n >r 2drop r>\n dup syntax_error = if\n .\" Warning: syntax error on file \" print_current_file cr\n print_syntax_error drop exit\n then\n dup set_error = if\n .\" Warning: bad definition on file \" print_current_file cr\n print_line drop exit\n then\n dup read_error = if\n .\" Warning: error reading file \" print_current_file cr drop exit\n then\n dup open_error = if\n verbose? if .\" Warning: unable to open file \" print_current_file cr then\n drop exit\n then\n dup free_error = abort\" Fatal error freeing memory\"\n dup out_of_memory = abort\" Out of memory\"\n throw \\ Unknown error -- pass ahead\n;\n\n\\ Process loader_conf_files recursively\n\\ Interface to loader_conf_files processing\n\n: include_conf_files\n set_current_conf_files\n get_conf_files 0\n begin\n get_next_file ?dup\n while\n set_current_file_name\n ['] load_conf catch\n process_conf_errors\n recurse_on_conf_files? if recurse then\n repeat\n;\n\n\\ Module loading functions\n\n: load_module?\n module.flag @\n;\n\n: load_parameters ( addr -- addr addrN lenN ... addr1 len1 N )\n dup >r\n r@ module.args .addr @ r@ module.args .len @\n r@ module.loadname .len @ if\n r@ module.loadname .addr @ r@ module.loadname .len @\n else\n r@ module.name .addr @ r@ module.name .len @\n then\n r@ module.type .len @ if\n r@ module.type .addr @ r@ module.type .len @\n s\" -t \"\n 4 ( -t type name flags )\n else\n 2 ( name flags )\n then\n r> drop\n;\n\n: before_load ( addr -- addr )\n dup module.beforeload .len @ if\n dup module.beforeload .addr @ over module.beforeload .len @\n ['] evaluate catch if before_load_error throw then\n then\n;\n\n: after_load ( addr -- addr )\n dup module.afterload .len @ if\n dup module.afterload .addr @ over module.afterload .len @\n ['] evaluate catch if after_load_error throw then\n then\n;\n\n: load_error ( addr -- addr )\n dup module.loaderror .len @ if\n dup module.loaderror .addr @ over module.loaderror .len @\n evaluate \\ This we do not intercept so it can throw errors\n then\n;\n\n: pre_load_message ( addr -- addr )\n verbose? if\n dup module.name .addr @ over module.name .len @ type\n .\" ...\"\n then\n;\n\n: load_error_message verbose? if .\" failed!\" cr then ;\n\n: load_succesful_message verbose? if .\" ok\" cr then ;\n\n: load_module\n load_parameters load\n;\n\n: process_module ( addr -- addr )\n pre_load_message\n before_load\n begin\n ['] load_module catch if\n dup module.loaderror .len @ if\n load_error\t\t\t\\ Command should return a flag!\n else \n load_error_message true\t\t\\ Do not retry\n then\n else\n after_load\n load_succesful_message true\t\\ Succesful, do not retry\n then\n until\n;\n\n: process_module_errors ( addr ior -- )\n dup before_load_error = if\n drop\n .\" Module \"\n dup module.name .addr @ over module.name .len @ type\n dup module.loadname .len @ if\n .\" (\" dup module.loadname .addr @ over module.loadname .len @ type .\" )\"\n then\n cr\n .\" Error executing \"\n dup module.beforeload .addr @ over module.afterload .len @ type cr\n abort\n then\n\n dup after_load_error = if\n drop\n .\" Module \"\n dup module.name .addr @ over module.name .len @ type\n dup module.loadname .len @ if\n .\" (\" dup module.loadname .addr @ over module.loadname .len @ type .\" )\"\n then\n cr\n .\" Error executing \"\n dup module.afterload .addr @ over module.afterload .len @ type cr\n abort\n then\n\n throw \\ Don't know what it is all about -- pass ahead\n;\n\n\\ Module loading interface\n\n: load_modules ( -- ) ( throws: abort & user-defined )\n module_options @\n begin\n ?dup\n while\n dup load_module? if\n ['] process_module catch\n process_module_errors\n then\n module.next @\n repeat\n;\n\n\\ Additional functions used in \"start\"\n\n: initialize ( addr len -- )\n strdup conf_files .len ! conf_files .addr !\n;\n\n: load_kernel ( -- ) ( throws: abort )\n s\" load ${kernel} ${kernel_options}\" ['] evaluate catch\n if s\" echo Unable to load kernel: ${kernel}\" evaluate abort then\n;\n\n: read-password { size | buf len -- }\n size allocate if out_of_memory throw then\n to buf\n 0 to len\n begin\n key\n dup backspace = if\n drop\n len if\n backspace emit bl emit backspace emit\n len 1 - to len\n else\n bell emit\n then\n else\n dup = if cr drop buf len exit then\n [char] * emit\n len size < if\n buf len chars + c!\n else\n drop\n then\n len 1+ to len\n then\n again\n;\n\n\\ Go back to straight forth vocabulary\n\nonly forth also definitions\n\n","old_contents":"\\ Copyright (c) 1999 Daniel C. Sobral \n\\ All rights reserved.\n\\ \n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\n\\ Loader.rc support functions:\n\\\n\\ initialize_support ( -- )\tinitialize global variables\n\\ initialize ( addr len -- )\tas above, plus load_conf_files\n\\ load_conf ( addr len -- )\tload conf file given\n\\ include_conf_files ( -- )\tload all conf files in load_conf_files\n\\ print_syntax_error ( -- )\tprint line and marker of where a syntax\n\\\t\t\t\terror was detected\n\\ print_line ( -- )\t\tprint last line processed\n\\ load_kernel ( -- )\t\tload kernel\n\\ load_modules ( -- )\t\tload modules flagged\n\\\n\\ Exported structures:\n\\\n\\ string\t\t\tcounted string structure\n\\\tcell .addr\t\t\tstring address\n\\\tcell .len\t\t\tstring length\n\\ module\t\t\tmodule loading information structure\n\\\tcell module.flag\t\tshould we load it?\n\\\tstring module.name\t\tmodule's name\n\\\tstring module.loadname\t\tname to be used in loading the module\n\\\tstring module.type\t\tmodule's type\n\\\tstring module.args\t\tflags to be passed during load\n\\\tstring module.beforeload\tcommand to be executed before load\n\\\tstring module.afterload\t\tcommand to be executed after load\n\\\tstring module.loaderror\t\tcommand to be executed if load fails\n\\\tcell module.next\t\tlist chain\n\\\n\\ Exported global variables;\n\\\n\\ string conf_files\t\tconfiguration files to be loaded\n\\ string password\t\tpassword\n\\ cell modules_options\t\tpointer to first module information\n\\ value verbose?\t\tindicates if user wants a verbose loading\n\\ value any_conf_read?\t\tindicates if a conf file was succesfully read\n\\\n\\ Other exported words:\n\\\n\\ strdup ( addr len -- addr' len)\t\t\tsimilar to strdup(3)\n\\ strcat ( addr len addr' len' -- addr len+len' )\tsimilar to strcat(3)\n\\ strlen ( addr -- len )\t\t\t\tsimilar to strlen(3)\n\\ s' ( | string' -- addr len | )\t\t\tsimilar to s\"\n\\ rudimentary structure support\n\n\\ Exception values\n\n1 constant syntax_error\n2 constant out_of_memory\n3 constant free_error\n4 constant set_error\n5 constant read_error\n6 constant open_error\n7 constant exec_error\n8 constant before_load_error\n9 constant after_load_error\n\n\\ Crude structure support\n\n: structure:\n create here 0 , ['] drop , 0\n does> create here swap dup @ allot cell+ @ execute\n;\n: member: create dup , over , + does> cell+ @ + ;\n: ;structure swap ! ;\n: constructor! >body cell+ ! ;\n: constructor: over :noname ;\n: ;constructor postpone ; swap cell+ ! ; immediate\n: sizeof ' >body @ state @ if postpone literal then ; immediate\n: offsetof ' >body cell+ @ state @ if postpone literal then ; immediate\n: ptr 1 cells member: ;\n: int 1 cells member: ;\n\n\\ String structure\n\nstructure: string\n\tptr .addr\n\tint .len\n\tconstructor:\n\t 0 over .addr !\n\t 0 swap .len !\n\t;constructor\n;structure\n\n\n\\ Module options linked list\n\nstructure: module\n\tint module.flag\n\tsizeof string member: module.name\n\tsizeof string member: module.loadname\n\tsizeof string member: module.type\n\tsizeof string member: module.args\n\tsizeof string member: module.beforeload\n\tsizeof string member: module.afterload\n\tsizeof string member: module.loaderror\n\tptr module.next\n;structure\n\n\\ Internal loader structures\nstructure: preloaded_file\n\tptr pf.name\n\tptr pf.type\n\tptr pf.args\n\tptr pf.metadata\t\\ file_metadata\n\tint pf.loader\n\tint pf.addr\n\tint pf.size\n\tptr pf.modules\t\\ kernel_module\n\tptr pf.next\t\\ preloaded_file\n;structure\n\nstructure: kernel_module\n\tptr km.name\n\t\\ ptr km.args\n\tptr km.fp\t\\ preloaded_file\n\tptr km.next\t\\ kernel_module\n;structure\n\nstructure: file_metadata\n\tint\t\tmd.size\n\t2 member:\tmd.type\t\\ this is not ANS Forth compatible (XXX)\n\tptr\t\tmd.next\t\\ file_metadata\n\t0 member:\tmd.data\t\\ variable size\n;structure\n\nstructure: config_resource\n\tptr cf.name\n\tint cf.type\n0 constant RES_INT\n1 constant RES_STRING\n2 constant RES_LONG\n\t2 cells member: u\n;structure\n\nstructure: config_device\n\tptr cd.name\n\tint cd.unit\n\tint cd.resource_count\n\tptr cd.resources\t\\ config_resource\n;structure\n\nstructure: STAILQ_HEAD\n\tptr stqh_first\t\\ type*\n\tptr stqh_last\t\\ type**\n;structure\n\nstructure: STAILQ_ENTRY\n\tptr stqe_next\t\\ type*\n;structure\n\nstructure: pnphandler\n\tptr pnph.name\n\tptr pnph.enumerate\n;structure\n\nstructure: pnpident\n\tptr pnpid.ident\t\t\t\t\t\\ char*\n\tsizeof STAILQ_ENTRY cells member: pnpid.link\t\\ pnpident\n;structure\n\nstructure: pnpinfo\n\tptr pnpi.desc\n\tint pnpi.revision\n\tptr pnpi.module\t\t\t\t\\ (char*) module args\n\tint pnpi.argc\n\tptr pnpi.argv\n\tptr pnpi.handler\t\t\t\\ pnphandler\n\tsizeof STAILQ_HEAD member: pnpi.ident\t\\ pnpident\n\tsizeof STAILQ_ENTRY member: pnpi.link\t\\ pnpinfo\n;structure\n\n\\ Global variables\n\nstring conf_files\nstring password\ncreate module_options sizeof module.next allot 0 module_options !\ncreate last_module_option sizeof module.next allot 0 last_module_option !\n0 value verbose?\n\n\\ Support string functions\n\n: strdup ( addr len -- addr' len )\n >r r@ allocate if out_of_memory throw then\n tuck r@ move\n r>\n;\n\n: strcat { addr len addr' len' -- addr len+len' }\n addr' addr len + len' move\n addr len len' +\n;\n\n: strlen ( addr -- len )\n 0 >r\n begin\n dup c@ while\n 1+ r> 1+ >r repeat\n drop r>\n;\n\n: s' \n [char] ' parse\n state @ if\n postpone sliteral\n then\n; immediate\n\n: 2>r postpone >r postpone >r ; immediate\n: 2r> postpone r> postpone r> ; immediate\n\n\\ Private definitions\n\nvocabulary support-functions\nonly forth also support-functions definitions\n\n\\ Some control characters constants\n\n7 constant bell\n8 constant backspace\n9 constant tab\n10 constant lf\n13 constant \n\n\\ Read buffer size\n\n80 constant read_buffer_size\n\n\\ Standard suffixes\n\n: load_module_suffix s\" _load\" ;\n: module_loadname_suffix s\" _name\" ;\n: module_type_suffix s\" _type\" ;\n: module_args_suffix s\" _flags\" ;\n: module_beforeload_suffix s\" _before\" ;\n: module_afterload_suffix s\" _after\" ;\n: module_loaderror_suffix s\" _error\" ;\n\n\\ Support operators\n\n: >= < 0= ;\n: <= > 0= ;\n\n\\ Assorted support funcitons\n\n: free-memory free if free_error throw then ;\n\n\\ Assignment data temporary storage\n\nstring name_buffer\nstring value_buffer\n\n\\ Line by line file reading functions\n\\\n\\ exported:\n\\\tline_buffer\n\\\tend_of_file?\n\\\tfd\n\\\tread_line\n\\\treset_line_reading\n\nvocabulary line-reading\nalso line-reading definitions also\n\n\\ File data temporary storage\n\nstring read_buffer\n0 value read_buffer_ptr\n\n\\ File's line reading function\n\nsupport-functions definitions\n\nstring line_buffer\n0 value end_of_file?\nvariable fd\n\nline-reading definitions\n\n: skip_newlines\n begin\n read_buffer .len @ read_buffer_ptr >\n while\n read_buffer .addr @ read_buffer_ptr + c@ lf = if\n read_buffer_ptr char+ to read_buffer_ptr\n else\n exit\n then\n repeat\n;\n\n: scan_buffer ( -- addr len )\n read_buffer_ptr >r\n begin\n read_buffer .len @ r@ >\n while\n read_buffer .addr @ r@ + c@ lf = if\n read_buffer .addr @ read_buffer_ptr + ( -- addr )\n r@ read_buffer_ptr - ( -- len )\n r> to read_buffer_ptr\n exit\n then\n r> char+ >r\n repeat\n read_buffer .addr @ read_buffer_ptr + ( -- addr )\n r@ read_buffer_ptr - ( -- len )\n r> to read_buffer_ptr\n;\n\n: line_buffer_resize ( len -- len )\n >r\n line_buffer .len @ if\n line_buffer .addr @\n line_buffer .len @ r@ +\n resize if out_of_memory throw then\n else\n r@ allocate if out_of_memory throw then\n then\n line_buffer .addr !\n r>\n;\n \n: append_to_line_buffer ( addr len -- )\n line_buffer .addr @ line_buffer .len @\n 2swap strcat\n line_buffer .len !\n drop\n;\n\n: read_from_buffer\n scan_buffer ( -- addr len )\n line_buffer_resize ( len -- len )\n append_to_line_buffer ( addr len -- )\n;\n\n: refill_required?\n read_buffer .len @ read_buffer_ptr =\n end_of_file? 0= and\n;\n\n: refill_buffer\n 0 to read_buffer_ptr\n read_buffer .addr @ 0= if\n read_buffer_size allocate if out_of_memory throw then\n read_buffer .addr !\n then\n fd @ read_buffer .addr @ read_buffer_size fread\n dup -1 = if read_error throw then\n dup 0= if true to end_of_file? then\n read_buffer .len !\n;\n\n: reset_line_buffer\n line_buffer .addr @ ?dup if\n free-memory\n then\n 0 line_buffer .addr !\n 0 line_buffer .len !\n;\n\nsupport-functions definitions\n\n: reset_line_reading\n 0 to read_buffer_ptr\n;\n\n: read_line\n reset_line_buffer\n skip_newlines\n begin\n read_from_buffer\n refill_required?\n while\n refill_buffer\n repeat\n;\n\nonly forth also support-functions definitions\n\n\\ Conf file line parser:\n\\ ::= '='[] |\n\\ []\n\\ ::= {||'_'}\n\\ ::= '\"'{|'\\'}'\"' | \n\\ ::= ASCII 32 to 126, except '\\' and '\"'\n\\ ::= '#'{}\n\\\n\\ exported:\n\\\tline_pointer\n\\\tprocess_conf\n\n0 value line_pointer\n\nvocabulary file-processing\nalso file-processing definitions\n\n\\ parser functions\n\\\n\\ exported:\n\\\tget_assignment\n\nvocabulary parser\nalso parser definitions also\n\n0 value parsing_function\n0 value end_of_line\n\n: end_of_line?\n line_pointer end_of_line =\n;\n\n: letter?\n line_pointer c@ >r\n r@ [char] A >=\n r@ [char] Z <= and\n r@ [char] a >=\n r> [char] z <= and\n or\n;\n\n: digit?\n line_pointer c@ >r\n r@ [char] 0 >=\n r> [char] 9 <= and\n;\n\n: quote?\n line_pointer c@ [char] \" =\n;\n\n: assignment_sign?\n line_pointer c@ [char] = =\n;\n\n: comment?\n line_pointer c@ [char] # =\n;\n\n: space?\n line_pointer c@ bl =\n line_pointer c@ tab = or\n;\n\n: backslash?\n line_pointer c@ [char] \\ =\n;\n\n: underscore?\n line_pointer c@ [char] _ =\n;\n\n: dot?\n line_pointer c@ [char] . =\n;\n\n: skip_character\n line_pointer char+ to line_pointer\n;\n\n: skip_to_end_of_line\n end_of_line to line_pointer\n;\n\n: eat_space\n begin\n space?\n while\n skip_character\n end_of_line? if exit then\n repeat\n;\n\n: parse_name ( -- addr len )\n line_pointer\n begin\n letter? digit? underscore? dot? or or or\n while\n skip_character\n end_of_line? if \n line_pointer over -\n strdup\n exit\n then\n repeat\n line_pointer over -\n strdup\n;\n\n: remove_backslashes { addr len | addr' len' -- addr' len' }\n len allocate if out_of_memory throw then\n to addr'\n addr >r\n begin\n addr c@ [char] \\ <> if\n addr c@ addr' len' + c!\n len' char+ to len'\n then\n addr char+ to addr\n r@ len + addr =\n until\n r> drop\n addr' len'\n;\n\n: parse_quote ( -- addr len )\n line_pointer\n skip_character\n end_of_line? if syntax_error throw then\n begin\n quote? 0=\n while\n backslash? if\n skip_character\n end_of_line? if syntax_error throw then\n then\n skip_character\n end_of_line? if syntax_error throw then \n repeat\n skip_character\n line_pointer over -\n remove_backslashes\n;\n\n: read_name\n parse_name\t\t( -- addr len )\n name_buffer .len !\n name_buffer .addr !\n;\n\n: read_value\n quote? if\n parse_quote\t\t( -- addr len )\n else\n parse_name\t\t( -- addr len )\n then\n value_buffer .len !\n value_buffer .addr !\n;\n\n: comment\n skip_to_end_of_line\n;\n\n: white_space_4\n eat_space\n comment? if ['] comment to parsing_function exit then\n end_of_line? 0= if syntax_error throw then\n;\n\n: variable_value\n read_value\n ['] white_space_4 to parsing_function\n;\n\n: white_space_3\n eat_space\n letter? digit? quote? or or if\n ['] variable_value to parsing_function exit\n then\n syntax_error throw\n;\n\n: assignment_sign\n skip_character\n ['] white_space_3 to parsing_function\n;\n\n: white_space_2\n eat_space\n assignment_sign? if ['] assignment_sign to parsing_function exit then\n syntax_error throw\n;\n\n: variable_name\n read_name\n ['] white_space_2 to parsing_function\n;\n\n: white_space_1\n eat_space\n letter? if ['] variable_name to parsing_function exit then\n comment? if ['] comment to parsing_function exit then\n end_of_line? 0= if syntax_error throw then\n;\n\nfile-processing definitions\n\n: get_assignment\n line_buffer .addr @ line_buffer .len @ + to end_of_line\n line_buffer .addr @ to line_pointer\n ['] white_space_1 to parsing_function\n begin\n end_of_line? 0=\n while\n parsing_function execute\n repeat\n parsing_function ['] comment =\n parsing_function ['] white_space_1 =\n parsing_function ['] white_space_4 =\n or or 0= if syntax_error throw then\n;\n\nonly forth also support-functions also file-processing definitions also\n\n\\ Process line\n\n: assignment_type? ( addr len -- flag )\n name_buffer .addr @ name_buffer .len @\n compare 0=\n;\n\n: suffix_type? ( addr len -- flag )\n name_buffer .len @ over <= if 2drop false exit then\n name_buffer .len @ over - name_buffer .addr @ +\n over compare 0=\n;\n\n: loader_conf_files?\n s\" loader_conf_files\" assignment_type?\n;\n\n: verbose_flag?\n s\" verbose_loading\" assignment_type?\n;\n\n: execute?\n s\" exec\" assignment_type?\n;\n\n: password?\n s\" password\" assignment_type?\n;\n\n: module_load?\n load_module_suffix suffix_type?\n;\n\n: module_loadname?\n module_loadname_suffix suffix_type?\n;\n\n: module_type?\n module_type_suffix suffix_type?\n;\n\n: module_args?\n module_args_suffix suffix_type?\n;\n\n: module_beforeload?\n module_beforeload_suffix suffix_type?\n;\n\n: module_afterload?\n module_afterload_suffix suffix_type?\n;\n\n: module_loaderror?\n module_loaderror_suffix suffix_type?\n;\n\n: set_conf_files\n conf_files .addr @ ?dup if\n free-memory\n then\n value_buffer .addr @ c@ [char] \" = if\n value_buffer .addr @ char+ value_buffer .len @ 2 chars -\n else\n value_buffer .addr @ value_buffer .len @\n then\n strdup\n conf_files .len ! conf_files .addr !\n;\n\n: append_to_module_options_list ( addr -- )\n module_options @ 0= if\n dup module_options !\n last_module_option !\n else\n dup last_module_option @ module.next !\n last_module_option !\n then\n;\n\n: set_module_name ( addr -- )\n name_buffer .addr @ name_buffer .len @\n strdup\n >r over module.name .addr !\n r> swap module.name .len !\n;\n\n: yes_value?\n value_buffer .addr @ value_buffer .len @\n 2dup s' \"YES\"' compare >r\n 2dup s' \"yes\"' compare >r\n 2dup s\" YES\" compare >r\n s\" yes\" compare r> r> r> and and and 0=\n;\n\n: find_module_option ( -- addr | 0 )\n module_options @\n begin\n dup\n while\n dup module.name dup .addr @ swap .len @\n name_buffer .addr @ name_buffer .len @\n compare 0= if exit then\n module.next @\n repeat\n;\n\n: new_module_option ( -- addr )\n sizeof module allocate if out_of_memory throw then\n dup sizeof module erase\n dup append_to_module_options_list\n dup set_module_name\n;\n\n: get_module_option ( -- addr )\n find_module_option\n ?dup 0= if new_module_option then\n;\n\n: set_module_flag\n name_buffer .len @ load_module_suffix nip - name_buffer .len !\n yes_value? get_module_option module.flag !\n;\n\n: set_module_args\n name_buffer .len @ module_args_suffix nip - name_buffer .len !\n get_module_option module.args\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_loadname\n name_buffer .len @ module_loadname_suffix nip - name_buffer .len !\n get_module_option module.loadname\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_type\n name_buffer .len @ module_type_suffix nip - name_buffer .len !\n get_module_option module.type\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_beforeload\n name_buffer .len @ module_beforeload_suffix nip - name_buffer .len !\n get_module_option module.beforeload\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_afterload\n name_buffer .len @ module_afterload_suffix nip - name_buffer .len !\n get_module_option module.afterload\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_module_loaderror\n name_buffer .len @ module_loaderror_suffix nip - name_buffer .len !\n get_module_option module.loaderror\n dup .addr @ ?dup if free-memory then\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 chars - swap char+ swap\n then\n strdup\n >r over .addr !\n r> swap .len !\n;\n\n: set_environment_variable\n name_buffer .len @\n value_buffer .len @ +\n 5 chars +\n allocate if out_of_memory throw then\n dup 0 ( addr -- addr addr len )\n s\" set \" strcat\n name_buffer .addr @ name_buffer .len @ strcat\n s\" =\" strcat\n value_buffer .addr @ value_buffer .len @ strcat\n ['] evaluate catch if\n 2drop free drop\n set_error throw\n else\n free-memory\n then\n;\n\n: set_verbose\n yes_value? to verbose?\n;\n\n: execute_command\n value_buffer .addr @ value_buffer .len @\n over c@ [char] \" = if\n 2 - swap char+ swap\n then\n ['] evaluate catch if exec_error throw then\n;\n\n: set_password\n password .addr @ ?dup if free if free_error throw then then\n value_buffer .addr @ c@ [char] \" = if\n value_buffer .addr @ char+ value_buffer .len @ 2 - strdup\n value_buffer .addr @ free if free_error throw then\n else\n value_buffer .addr @ value_buffer .len @\n then\n password .len ! password .addr !\n 0 value_buffer .addr !\n;\n\n: process_assignment\n name_buffer .len @ 0= if exit then\n loader_conf_files?\tif set_conf_files exit then\n verbose_flag?\t\tif set_verbose exit then\n execute?\t\tif execute_command exit then\n password?\t\tif set_password exit then\n module_load?\t\tif set_module_flag exit then\n module_loadname?\tif set_module_loadname exit then\n module_type?\t\tif set_module_type exit then\n module_args?\t\tif set_module_args exit then\n module_beforeload?\tif set_module_beforeload exit then\n module_afterload?\tif set_module_afterload exit then\n module_loaderror?\tif set_module_loaderror exit then\n set_environment_variable\n;\n\n\\ free_buffer ( -- )\n\\\n\\ Free some pointers if needed. The code then tests for errors\n\\ in freeing, and throws an exception if needed. If a pointer is\n\\ not allocated, it's value (0) is used as flag.\n\n: free_buffers\n name_buffer .addr @ dup if free then\n value_buffer .addr @ dup if free then\n or if free_error throw then\n;\n\n: reset_assignment_buffers\n 0 name_buffer .addr !\n 0 name_buffer .len !\n 0 value_buffer .addr !\n 0 value_buffer .len !\n;\n\n\\ Higher level file processing\n\nsupport-functions definitions\n\n: process_conf\n begin\n end_of_file? 0=\n while\n reset_assignment_buffers\n read_line\n get_assignment\n ['] process_assignment catch\n ['] free_buffers catch\n swap throw throw\n repeat\n;\n\nonly forth also support-functions definitions\n\n: create_null_terminated_string { addr len -- addr' len }\n len char+ allocate if out_of_memory throw then\n >r\n addr r@ len move\n 0 r@ len + c!\n r> len\n;\n\n\\ Interface to loading conf files\n\n: load_conf ( addr len -- )\n 0 to end_of_file?\n reset_line_reading\n create_null_terminated_string\n over >r\n fopen fd !\n r> free-memory\n fd @ -1 = if open_error throw then\n ['] process_conf catch\n fd @ fclose\n throw\n;\n\n: print_line\n line_buffer .addr @ line_buffer .len @ type cr\n;\n\n: print_syntax_error\n line_buffer .addr @ line_buffer .len @ type cr\n line_buffer .addr @\n begin\n line_pointer over <>\n while\n bl emit\n char+\n repeat\n drop\n .\" ^\" cr\n;\n\n\\ Depuration support functions\n\nonly forth definitions also support-functions\n\n: test-file \n ['] load_conf catch dup .\n syntax_error = if cr print_syntax_error then\n;\n\n: show-module-options\n module_options @\n begin\n ?dup\n while\n .\" Name: \" dup module.name dup .addr @ swap .len @ type cr\n .\" Path: \" dup module.loadname dup .addr @ swap .len @ type cr\n .\" Type: \" dup module.type dup .addr @ swap .len @ type cr\n .\" Flags: \" dup module.args dup .addr @ swap .len @ type cr\n .\" Before load: \" dup module.beforeload dup .addr @ swap .len @ type cr\n .\" After load: \" dup module.afterload dup .addr @ swap .len @ type cr\n .\" Error: \" dup module.loaderror dup .addr @ swap .len @ type cr\n .\" Status: \" dup module.flag @ if .\" Load\" else .\" Don't load\" then cr\n module.next @\n repeat\n;\n\nonly forth also support-functions definitions\n\n\\ Variables used for processing multiple conf files\n\nstring current_file_name\nvariable current_conf_files\n\n\\ Indicates if any conf file was succesfully read\n\n0 value any_conf_read?\n\n\\ loader_conf_files processing support functions\n\n: set_current_conf_files\n conf_files .addr @ current_conf_files !\n;\n\n: get_conf_files\n conf_files .addr @ conf_files .len @ strdup\n;\n\n: recurse_on_conf_files?\n current_conf_files @ conf_files .addr @ <>\n;\n\n: skip_leading_spaces { addr len pos -- addr len pos' }\n begin\n pos len = if addr len pos exit then\n addr pos + c@ bl =\n while\n pos char+ to pos\n repeat\n addr len pos\n;\n\n: get_file_name { addr len pos -- addr len pos' addr' len' || 0 }\n pos len = if \n addr free abort\" Fatal error freeing memory\"\n 0 exit\n then\n pos >r\n begin\n addr pos + c@ bl <>\n while\n pos char+ to pos\n pos len = if\n addr len pos addr r@ + pos r> - exit\n then\n repeat\n addr len pos addr r@ + pos r> -\n;\n\n: get_next_file ( addr len ptr -- addr len ptr' addr' len' | 0 )\n skip_leading_spaces\n get_file_name\n;\n\n: set_current_file_name\n over current_file_name .addr !\n dup current_file_name .len !\n;\n\n: print_current_file\n current_file_name .addr @ current_file_name .len @ type\n;\n\n: process_conf_errors\n dup 0= if true to any_conf_read? drop exit then\n >r 2drop r>\n dup syntax_error = if\n .\" Warning: syntax error on file \" print_current_file cr\n print_syntax_error drop exit\n then\n dup set_error = if\n .\" Warning: bad definition on file \" print_current_file cr\n print_line drop exit\n then\n dup read_error = if\n .\" Warning: error reading file \" print_current_file cr drop exit\n then\n dup open_error = if\n verbose? if .\" Warning: unable to open file \" print_current_file cr then\n drop exit\n then\n dup free_error = abort\" Fatal error freeing memory\"\n dup out_of_memory = abort\" Out of memory\"\n throw \\ Unknown error -- pass ahead\n;\n\n\\ Process loader_conf_files recursively\n\\ Interface to loader_conf_files processing\n\n: include_conf_files\n set_current_conf_files\n get_conf_files 0\n begin\n get_next_file ?dup\n while\n set_current_file_name\n ['] load_conf catch\n process_conf_errors\n recurse_on_conf_files? if recurse then\n repeat\n;\n\n\\ Module loading functions\n\n: load_module?\n module.flag @\n;\n\n: load_parameters ( addr -- addr addrN lenN ... addr1 len1 N )\n dup >r\n r@ module.args .addr @ r@ module.args .len @\n r@ module.loadname .len @ if\n r@ module.loadname .addr @ r@ module.loadname .len @\n else\n r@ module.name .addr @ r@ module.name .len @\n then\n r@ module.type .len @ if\n r@ module.type .addr @ r@ module.type .len @\n s\" -t \"\n 4 ( -t type name flags )\n else\n 2 ( name flags )\n then\n r> drop\n;\n\n: before_load ( addr -- addr )\n dup module.beforeload .len @ if\n dup module.beforeload .addr @ over module.beforeload .len @\n ['] evaluate catch if before_load_error throw then\n then\n;\n\n: after_load ( addr -- addr )\n dup module.afterload .len @ if\n dup module.afterload .addr @ over module.afterload .len @\n ['] evaluate catch if after_load_error throw then\n then\n;\n\n: load_error ( addr -- addr )\n dup module.loaderror .len @ if\n dup module.loaderror .addr @ over module.loaderror .len @\n evaluate \\ This we do not intercept so it can throw errors\n then\n;\n\n: pre_load_message ( addr -- addr )\n verbose? if\n dup module.name .addr @ over module.name .len @ type\n .\" ...\"\n then\n;\n\n: load_error_message verbose? if .\" failed!\" cr then ;\n\n: load_succesful_message verbose? if .\" ok\" cr then ;\n\n: load_module\n load_parameters load\n;\n\n: process_module ( addr -- addr )\n pre_load_message\n before_load\n begin\n ['] load_module catch if\n dup module.loaderror .len @ if\n load_error\t\t\t\\ Command should return a flag!\n else \n load_error_message true\t\t\\ Do not retry\n then\n else\n after_load\n load_succesful_message true\t\\ Succesful, do not retry\n then\n until\n;\n\n: process_module_errors ( addr ior -- )\n dup before_load_error = if\n drop\n .\" Module \"\n dup module.name .addr @ over module.name .len @ type\n dup module.loadname .len @ if\n .\" (\" dup module.loadname .addr @ over module.loadname .len @ type .\" )\"\n then\n cr\n .\" Error executing \"\n dup module.beforeload .addr @ over module.afterload .len @ type cr\n abort\n then\n\n dup after_load_error = if\n drop\n .\" Module \"\n dup module.name .addr @ over module.name .len @ type\n dup module.loadname .len @ if\n .\" (\" dup module.loadname .addr @ over module.loadname .len @ type .\" )\"\n then\n cr\n .\" Error executing \"\n dup module.afterload .addr @ over module.afterload .len @ type cr\n abort\n then\n\n throw \\ Don't know what it is all about -- pass ahead\n;\n\n\\ Module loading interface\n\n: load_modules ( -- ) ( throws: abort & user-defined )\n module_options @\n begin\n ?dup\n while\n dup load_module? if\n ['] process_module catch\n process_module_errors\n then\n module.next @\n repeat\n;\n\n\\ Additional functions used in \"start\"\n\n: initialize ( addr len -- )\n strdup conf_files .len ! conf_files .addr !\n;\n\n: load_kernel ( -- ) ( throws: abort )\n s\" load ${kernel} ${kernel_options}\" ['] evaluate catch\n if s\" echo Unable to load kernel: ${kernel_name}\" evaluate abort then\n;\n\n: read-password { size | buf len -- }\n size allocate if out_of_memory throw then\n to buf\n 0 to len\n begin\n key\n dup backspace = if\n drop\n len if\n backspace emit bl emit backspace emit\n len 1 - to len\n else\n bell emit\n then\n else\n dup = if cr drop buf len exit then\n [char] * emit\n len size < if\n buf len chars + c!\n else\n drop\n then\n len 1+ to len\n then\n again\n;\n\n\\ Go back to straight forth vocabulary\n\nonly forth also definitions\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"8149db52bb5b091b30e7f46b9af098572f436dbe","subject":"- m command accepts address - waste remaining memory with a help message ;-)","message":"- m command accepts address\n- waste remaining memory with a help message ;-)","repos":"cetic\/python-msp430-tools,cetic\/python-msp430-tools,cetic\/python-msp430-tools","old_file":"examples\/asm\/forth_to_asm_advanced\/demo.forth","new_file":"examples\/asm\/forth_to_asm_advanced\/demo.forth","new_contents":"( vi:ft=forth\n\n Serial input output [X-Protocol] Example.\n Hardware: Launchpad\n Serial Port Settings: 2400,8,N,1\n\n Copyright [C] 2011 Chris Liechti \n All Rights Reserved.\n Simplified BSD License [see LICENSE.txt for full text]\n)\n\n( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - )\nINCLUDE core.forth\nINCLUDE msp430.forth\nINCLUDE io.forth\n\n( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - )\n\nCODE WRITE ( s -- )\n TOS->R15\n .\" \\t call \\x23 write\\n \"\n ASM-NEXT\nEND-CODE\n\nCODE EMIT ( u -- )\n TOS->R15\n .\" \\t call \\x23 putchar\\n \"\n ASM-NEXT\nEND-CODE\n\nCODE TIMER_A_UART_INIT ( -- )\n .\" \\t call \\x23 timer_uart_rx_setup\\n \"\n ASM-NEXT\nEND-CODE\n\n\nCODE RX-CHAR ( -- u )\n .\" \\t mov.b timer_a_uart_rxd, W\\n \"\n .\" \\t push W\\n \"\n ASM-NEXT\nEND-CODE\n\n( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - )\n( Control the LEDs on the Launchpad )\n: RED_ON ( -- ) BIT0 P1OUT CSET ;\n: RED_OFF ( -- ) BIT0 P1OUT CRESET ;\n: GREEN_ON ( -- ) BIT6 P1OUT CSET ;\n: GREEN_OFF ( -- ) BIT6 P1OUT CRESET ;\n\n( Read in the button on the Launchpad )\n: S2 P1IN C@ BIT3 AND NOT ;\n\n( Delay functions )\n: SHORT-DELAY ( -- ) 0x4fff DELAY ;\n: LONG-DELAY ( -- ) 0xffff DELAY ;\n: VERY-LONG-DELAY ( -- ) LONG-DELAY LONG-DELAY ;\n( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - )\n( Simple event handler. A bit field is used to keep track of events. )\nVARIABLE EVENTS\n( Bit masks for the individual events )\nBIT0 CONSTANT KEY-EVENT\nBIT1 CONSTANT TIMER-EVENT\nBIT2 CONSTANT RX-EVENT\n\n( ------ Helper functions ------ )\n( Start an event )\n: START ( u -- ) EVENTS CSET ;\n( Test if event was started. Reset its flag anyway and return true when it was set. )\n: PENDING? ( -- b )\n DUP ( copy bit mask )\n EVENTS CTESTBIT IF ( test if bit is set )\n EVENTS CRESET ( it is, reset )\n TRUE ( indicate true as return value )\n ELSE\n DROP ( drop bit mask )\n FALSE ( indicate false as return value )\n ENDIF\n;\n( Return true if no events are pending )\n: IDLE? ( -- b )\n EVENTS C@ 0=\n;\n( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - )\n\n( Interrupt handler for P1 )\nPORT1_VECTOR INTERRUPT P1-IRQ-HANDLER\n KEY-EVENT START ( Set event flag for key )\n WAKEUP ( terminate LPM modes )\n 0 P1IFG C! ( clear all interrupt flags )\nEND-INTERRUPT\n\n( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - )\n\n( Watchdog interrupts with SMCLK = 1MHz are too fast for us.\n Only wakeup every n-th interrupt. This is the counter\n used to achieve this. )\nVARIABLE SLOWDOWN\n\n( Interrupt handler for Watchdog module in timer mode )\nWDT_VECTOR INTERRUPT WATCHDOG-TIMER-HANDLER\n SLOWDOWN C@ 1+ ( get and increment counter )\n DUP 30 > IF ( check value )\n TIMER-EVENT START ( set event flag for timer )\n WAKEUP ( terminate LPM modes )\n DROP 0 ( reset counter )\n ENDIF\n SLOWDOWN C! ( store new value )\nEND-INTERRUPT\n\n( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - )\n\n( Received data is put into a small line buffer. When a newline\n is received processing in the foreground is started.\n)\n0 VALUE RX-POS\nRAM CREATE RX-BUFFER 8 ALLOT\n\n100 INTERRUPT TAUART_RX_INTERRUPT\n RX-CHAR DUP ( get the received character )\n RX-BUFFER RX-POS + C! ( store character )\n RX-POS 7 < IF ( increment write pos if there is space )\n RX-POS 1+ TO RX-POS\n ENDIF\n '\\n' = IF ( check for EOL )\n RX-EVENT START ( set event flag for reception )\n WAKEUP ( terminate LPM modes )\n 0 TO RX-POS ( reset read position )\n ENDIF\nEND-INTERRUPT\n\n( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - )\n( Initializations run after reset )\n: INIT ( -- )\n ( Initialize pins )\n OUT TACCTL0 ! ( Init Timer A CCTL before pin is activated DIR, SEL)\n BIT1 P1OUT C! ( TXD )\n [ BIT1 BIT2 + ] LITERAL P1SEL C! ( TXD RXD )\n [ BIT0 BIT1 + BIT6 + ] LITERAL P1DIR C!\n BIT3 P1IES C! ( select neg edge )\n 0 P1IFG C! ( reset flags )\n BIT3 P1IE C! ( enable interrupts for S2 )\n\n ( Use Watchdog module as timer )\n [ WDTPW WDTTMSEL + ] LITERAL WDTCTL !\n WDTIE IE1 C!\n\n ( Initialize clock from calibration values )\n CALDCO_1MHZ DCOCTL C@!\n CALBC1_1MHZ BCSCTL1 C@!\n\n ( Set up Timer A - used for UART )\n [ TASSEL1 MC1 + ] LITERAL TACTL !\n TIMER_A_UART_INIT\n\n ( Indicate startup with LED )\n GREEN_ON\n VERY-LONG-DELAY\n GREEN_OFF\n\n ( Enable interrupts now )\n EINT\n;\n\n( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - )\n\n( Decode a hex digit, text -> number. supported input: 0123456789abcdefABCDEF )\n( This decoding does not check for invalid characters. It will simply return\n garbage, however in the range of 0 ... 15 )\n: HEXDIGIT ( char - u )\n DUP 'A' >= IF\n [ 'A' 10 - ] LITERAL -\n ENDIF\n 0xf AND\n;\n\n( Decode text, hex digits, at given address and return value )\n: HEX-DECODE ( adr -- u )\n DUP\n C@ HEXDIGIT 4 LSHIFT SWAP\n 1+ C@ HEXDIGIT OR\n;\n\n( Output OK message )\n: XOK ( -- ) .\" xOK\\n\" ;\n\n\n( Output one hex digit for the number on the stack )\n: .HEXDIGIT ( u -- )\n 0xf AND\n DUP 10 >= IF\n [ 'A' 10 - ] LITERAL\n ELSE\n '0'\n ENDIF\n + EMIT\n;\n\n( Output two hex digits for the byte on the stack )\n: .HEX ( u -- )\n DUP\n 4 RSHIFT .HEXDIGIT\n .HEXDIGIT\n;\n\n( Output a line with 16 bytes as hex and ASCII dump. Includes newline. )\n: .HEXLINE ( adr -- )\n [CHAR] h EMIT BL EMIT ( write prefix )\n OVER DUP 8 RSHIFT .HEX .HEX SPACE SPACE ( write address )\n DUP 16 + SWAP ( calculate end_adr start_adr )\n ( output hex dump )\n BEGIN\n 2DUP > ( end address not yet reached )\n WHILE\n DUP C@ .HEX ( hex dump of address )\n SPACE\n 1+ ( next address )\n REPEAT\n ( reset address )\n 16 -\n ( output ASCII dump )\n SPACE\n BEGIN\n 2DUP > ( end address not yet reached )\n WHILE\n DUP C@ ( get byte )\n DUP 32 < IF\n DROP [CHAR] .\n ENDIF\n EMIT\n 1+ ( next address )\n REPEAT\n 2DROP .\" \\n\" ( finish hex dump, drop address on stack )\n;\n\n( Print a hex dump of the given address range )\n: HEXDUMP ( adr_hi adr_low -- )\n BEGIN\n 2DUP >\n WHILE\n DUP .HEXLINE\n 16 +\n REPEAT\n;\n\n\n( Main application, run after INIT )\n: MAIN ( -- )\n BEGIN\n ( Test if events are pending )\n IDLE? IF\n ( XXX actually we could miss an event and go to sleep if it was set\n between test and LPM. The event flag is not lost, but it is\n executed later when some other event wakes up the CPU. )\n ( Wait in low power mode )\n ENTER-LPM0\n ENDIF\n ( After wakeup test for the different events )\n\n RX-EVENT PENDING? IF\n GREEN_ON ( Show activity )\n ( RX-CHAR EMIT ( send echo )\n RX-BUFFER C@ CASE\n\n [CHAR] s OF ( read switch command )\n [CHAR] i EMIT\n ( return state of button )\n S2 IF [CHAR] 1 ELSE [CHAR] 0 ENDIF EMIT\n '\\n' EMIT\n XOK\n ENDOF\n\n [CHAR] o OF ( output a message \/ echo )\n RX-BUFFER WRITE\n XOK\n ENDOF\n\n [CHAR] c OF ( memory dump of calibration values )\n ( hex dump of INFOMEM segment with calibration values )\n 0x10ff 0x10c0 HEXDUMP\n XOK\n ENDOF\n\n [CHAR] m OF ( memory dump of given address, 64B blocks )\n RX-BUFFER 1+ DUP HEX-DECODE 8 LSHIFT\n SWAP 2+ HEX-DECODE OR\n DUP 64 + SWAP HEXDUMP\n XOK\n ENDOF\n\n [CHAR] h OF ( help )\n .\" oCommands:\\n\"\n .\" o 's' \\t\\tread switch\\n\"\n .\" o 'oM..' \\tEcho message\\n\"\n .\" o 'c' \\t\\tDump calibration\\n\"\n .\" o 'mHHHH' \\thexdump of given address\\n\"\n XOK\n ENDOF\n\n ( default )\n .\" xERR (try 'h') unknown command: \"\n RX-BUFFER WRITE\n ENDCASE\n RX-BUFFER 8 ZERO ( erase buffer for next round )\n GREEN_OFF ( Activity done )\n ENDIF\n\n KEY-EVENT PENDING? IF\n ( Green flashing )\n GREEN_ON\n SHORT-DELAY\n GREEN_OFF\n ENDIF\n\n TIMER-EVENT PENDING? IF\n ( Red flashing )\n RED_ON\n SHORT-DELAY\n RED_OFF\n ENDIF\n( S2 IF\n ELSE\n ENDIF\n)\n AGAIN\n;\n\n( ========================================================================= )\n( Generate the assembler file now )\n\" Advanced demo \" HEADER\n\n( output important runtime core parts )\n\" Core \" HEADER\nCROSS-COMPILE-CORE\n\n( cross compile application )\n\" Application \" HEADER\nCROSS-COMPILE-VARIABLES\nCROSS-COMPILE INIT\nCROSS-COMPILE MAIN\nCROSS-COMPILE P1-IRQ-HANDLER\nCROSS-COMPILE WATCHDOG-TIMER-HANDLER\nCROSS-COMPILE TAUART_RX_INTERRUPT\nCROSS-COMPILE-MISSING ( This compiles all words that were used indirectly )\n","old_contents":"( vi:ft=forth\n\n Serial input output [X-Protocol] Example.\n Hardware: Launchpad\n Serial Port Settings: 2400,8,N,1\n\n Copyright [C] 2011 Chris Liechti \n All Rights Reserved.\n Simplified BSD License [see LICENSE.txt for full text]\n)\n\n( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - )\nINCLUDE core.forth\nINCLUDE msp430.forth\nINCLUDE io.forth\n\n( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - )\n\nCODE WRITE ( s -- )\n TOS->R15\n .\" \\t call \\x23 write\\n \"\n ASM-NEXT\nEND-CODE\n\nCODE EMIT ( u -- )\n TOS->R15\n .\" \\t call \\x23 putchar\\n \"\n ASM-NEXT\nEND-CODE\n\nCODE TIMER_A_UART_INIT ( -- )\n .\" \\t call \\x23 timer_uart_rx_setup\\n \"\n ASM-NEXT\nEND-CODE\n\n\nCODE RX-CHAR ( -- u )\n .\" \\t mov.b timer_a_uart_rxd, W\\n \"\n .\" \\t push W\\n \"\n ASM-NEXT\nEND-CODE\n\n( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - )\n( Control the LEDs on the Launchpad )\n: RED_ON ( -- ) BIT0 P1OUT CSET ;\n: RED_OFF ( -- ) BIT0 P1OUT CRESET ;\n: GREEN_ON ( -- ) BIT6 P1OUT CSET ;\n: GREEN_OFF ( -- ) BIT6 P1OUT CRESET ;\n\n( Read in the button on the Launchpad )\n: S2 P1IN C@ BIT3 AND NOT ;\n\n( Delay functions )\n: SHORT-DELAY ( -- ) 0x4fff DELAY ;\n: LONG-DELAY ( -- ) 0xffff DELAY ;\n: VERY-LONG-DELAY ( -- ) LONG-DELAY LONG-DELAY ;\n( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - )\n( Simple event handler. A bit field is used to keep track of events. )\nVARIABLE EVENTS\n( Bit masks for the individual events )\nBIT0 CONSTANT KEY-EVENT\nBIT1 CONSTANT TIMER-EVENT\nBIT2 CONSTANT RX-EVENT\n\n( ------ Helper functions ------ )\n( Start an event )\n: START ( u -- ) EVENTS CSET ;\n( Test if event was started. Reset its flag anyway and return true when it was set. )\n: PENDING? ( -- b )\n DUP ( copy bit mask )\n EVENTS CTESTBIT IF ( test if bit is set )\n EVENTS CRESET ( it is, reset )\n TRUE ( indicate true as return value )\n ELSE\n DROP ( drop bit mask )\n FALSE ( indicate false as return value )\n ENDIF\n;\n( Return true if no events are pending )\n: IDLE? ( -- b )\n EVENTS C@ 0=\n;\n( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - )\n\n( Interrupt handler for P1 )\nPORT1_VECTOR INTERRUPT P1-IRQ-HANDLER\n KEY-EVENT START ( Set event flag for key )\n WAKEUP ( terminate LPM modes )\n 0 P1IFG C! ( clear all interrupt flags )\nEND-INTERRUPT\n\n( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - )\n\n( Watchdog interrupts with SMCLK = 1MHz are too fast for us.\n Only wakeup every n-th interrupt. This is the counter\n used to achieve this. )\nVARIABLE SLOWDOWN\n\n( Interrupt handler for Watchdog module in timer mode )\nWDT_VECTOR INTERRUPT WATCHDOG-TIMER-HANDLER\n SLOWDOWN C@ 1+ ( get and increment counter )\n DUP 30 > IF ( check value )\n TIMER-EVENT START ( set event flag for timer )\n WAKEUP ( terminate LPM modes )\n DROP 0 ( reset counter )\n ENDIF\n SLOWDOWN C! ( store new value )\nEND-INTERRUPT\n\n( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - )\n\n( Received data is put into a small line buffer. When a newline\n is received processing in the foreground is started.\n)\n0 VALUE RX-POS\nRAM CREATE RX-BUFFER 8 ALLOT\n\n100 INTERRUPT TAUART_RX_INTERRUPT\n RX-CHAR DUP ( get the received character )\n RX-BUFFER RX-POS + C! ( store character )\n RX-POS 7 < IF ( increment write pos if there is space )\n RX-POS 1+ TO RX-POS\n ENDIF\n '\\n' = IF ( check for EOL )\n RX-EVENT START ( set event flag for reception )\n WAKEUP ( terminate LPM modes )\n 0 TO RX-POS ( reset read position )\n ENDIF\nEND-INTERRUPT\n\n( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - )\n( Initializations run after reset )\n: INIT ( -- )\n ( Initialize pins )\n OUT TACCTL0 ! ( Init Timer A CCTL before pin is activated DIR, SEL)\n BIT1 P1OUT C! ( TXD )\n [ BIT1 BIT2 + ] LITERAL P1SEL C! ( TXD RXD )\n [ BIT0 BIT1 + BIT6 + ] LITERAL P1DIR C!\n BIT3 P1IES C! ( select neg edge )\n 0 P1IFG C! ( reset flags )\n BIT3 P1IE C! ( enable interrupts for S2 )\n\n ( Use Watchdog module as timer )\n [ WDTPW WDTTMSEL + ] LITERAL WDTCTL !\n WDTIE IE1 C!\n\n ( Initialize clock from calibration values )\n CALDCO_1MHZ DCOCTL C@!\n CALBC1_1MHZ BCSCTL1 C@!\n\n ( Set up Timer A - used for UART )\n [ TASSEL1 MC1 + ] LITERAL TACTL !\n TIMER_A_UART_INIT\n\n ( Indicate startup with LED )\n GREEN_ON\n VERY-LONG-DELAY\n GREEN_OFF\n\n ( Enable interrupts now )\n EINT\n;\n\n( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - )\n\n( Output OK message )\n: XOK ( -- ) .\" xOK\\n\" ;\n\n\n( Output one hex digit for the number on the stack )\n: .HEXDIGIT ( u -- )\n 0xf AND\n DUP 10 >= IF\n [ 'A' 10 - ] LITERAL\n ELSE\n '0'\n ENDIF\n + EMIT\n;\n\n( Output two hex digits for the byte on the stack )\n: .HEX ( u -- )\n DUP\n 4 RSHIFT .HEXDIGIT\n .HEXDIGIT\n;\n\n( Output a line with 16 bytes as hex and ASCII dump. Includes newline. )\n: .HEXLINE ( adr -- )\n [CHAR] h EMIT BL EMIT ( write prefix )\n OVER DUP 8 RSHIFT .HEX .HEX SPACE SPACE ( write address )\n DUP 16 + SWAP ( calculate end_adr start_adr )\n ( output hex dump )\n BEGIN\n 2DUP > ( end address not yet reached )\n WHILE\n DUP C@ .HEX ( hex dump of address )\n SPACE\n 1+ ( next address )\n REPEAT\n ( reset address )\n 16 -\n ( output ASCII dump )\n SPACE\n BEGIN\n 2DUP > ( end address not yet reached )\n WHILE\n DUP C@ ( get byte )\n DUP 32 < IF\n DROP [CHAR] .\n ENDIF\n EMIT\n 1+ ( next address )\n REPEAT\n 2DROP .\" \\n\" ( finish hex dump, drop address on stack )\n;\n\n( Print a hex dump of the given address range )\n: HEXDUMP ( adr_hi adr_low -- )\n BEGIN\n 2DUP >\n WHILE\n DUP .HEXLINE\n 16 +\n REPEAT\n;\n\n\n( Main application, run after INIT )\n: MAIN ( -- )\n BEGIN\n ( Test if events are pending )\n IDLE? IF\n ( XXX actually we could miss an event and go to sleep if it was set\n between test and LPM. The event flag is not lost, but it is\n executed later when some other event wakes up the CPU. )\n ( Wait in low power mode )\n ENTER-LPM0\n ENDIF\n ( After wakeup test for the different events )\n\n RX-EVENT PENDING? IF\n GREEN_ON ( Show activity )\n ( RX-CHAR EMIT ( send echo )\n RX-BUFFER C@ CASE\n\n [CHAR] s OF ( read switch command )\n [CHAR] i EMIT\n ( return state of button )\n S2 IF [CHAR] 1 ELSE [CHAR] 0 ENDIF EMIT\n '\\n' EMIT\n XOK\n ENDOF\n\n [CHAR] o OF ( output a message \/ echo )\n RX-BUFFER WRITE\n XOK\n ENDOF\n\n [CHAR] m OF ( memory dump )\n ( XXX read start address and range from command )\n ( hex dump of INFOMEM segment with calibration values )\n 0x10ff 0x10c0 HEXDUMP\n XOK\n ENDOF\n\n ( default )\n .\" xERR unknown command: \"\n RX-BUFFER WRITE\n ENDCASE\n RX-BUFFER 8 ZERO ( erase buffer for next round )\n GREEN_OFF ( Activity done )\n ENDIF\n\n KEY-EVENT PENDING? IF\n ( Green flashing )\n GREEN_ON\n SHORT-DELAY\n GREEN_OFF\n ENDIF\n\n TIMER-EVENT PENDING? IF\n ( Red flashing )\n RED_ON\n SHORT-DELAY\n RED_OFF\n ENDIF\n( S2 IF\n ELSE\n ENDIF\n)\n AGAIN\n;\n\n( ========================================================================= )\n( Generate the assembler file now )\n\" Advanced demo \" HEADER\n\n( output important runtime core parts )\n\" Core \" HEADER\nCROSS-COMPILE-CORE\n\n( cross compile application )\n\" Application \" HEADER\nCROSS-COMPILE-VARIABLES\nCROSS-COMPILE INIT\nCROSS-COMPILE MAIN\nCROSS-COMPILE P1-IRQ-HANDLER\nCROSS-COMPILE WATCHDOG-TIMER-HANDLER\nCROSS-COMPILE TAUART_RX_INTERRUPT\nCROSS-COMPILE-MISSING ( This compiles all words that were used indirectly )\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"a70b5f7a52c7c1d792ce2cecc3c46cbf368fe3d3","subject":"fix irc nick bug","message":"fix irc nick bug\n","repos":"cooper\/ferret","old_file":"std\/IRC\/Handlers.frt","new_file":"std\/IRC\/Handlers.frt","new_contents":"package IRC::Handlers\n\nshare $handlers = (\n PING: ping,\n \"001\": welcome,\n \"004\": myInfo,\n \"376\": endOfMOTD, # end of motd\n \"396\": hiddenHost, # is now your hidden host\n \"422\": endOfMOTD, # no motd found\n \"433\": nickInUse # nickname already in use\n)\n\nfunc ping {\n need $msg\n %send(\"PONG :\" + $msg.params[-1])\n}\n\nfunc welcome {\n need $msg\n %registered = true # remember that we've finished registration\n %me.nick = $msg.params[0] # assume the target is our actual nickname\n\n # we can't actually depend on this always being the case, but a\n # lot of IRC servers have nick!ident@host as the final word here.\n # if not, we will get that info the first time we recv a message from %me.\n if $msg.params[-1] =~ \/(\\S+)!(.+)\\@(.+)$\/ {\n %me.nick = $1\n %me.user = $2\n %me.host = $3\n %me.realHost = $3\n }\n}\n\nfunc myInfo {\n need $msg\n %server.name = $msg.params[1]\n %server.version = $msg.params[2]\n}\n\nfunc endOfMOTD {\n if !%autojoin || %_didAutojoin\n return\n %sendJoin(channelNames: %autojoin)\n %_didAutojoin = true\n}\n\n# recv: :k.notroll.net 396 booby 73.88.xkw.t :is now your hidden host\nfunc hiddenHost {\n need $msg\n %me.host = $msg.params[1]\n}\n\n# during registration, add underscores to nickname as necessary\nfunc nickInUse {\n if %registered\n return\n %me.nick += \"_\"\n %sendNick(%me.nick)\n}\n","old_contents":"package IRC::Handlers\n\nshare $handlers = (\n PING: ping,\n \"001\": welcome,\n \"004\": myInfo,\n \"376\": endOfMOTD, # end of motd\n \"396\": hiddenHost, # is now your hidden host\n \"422\": endOfMOTD, # no motd found\n \"433\": nickInUse # nickname already in use\n)\n\nfunc ping {\n need $msg\n %send(\"PONG :\" + $msg.params[-1])\n}\n\nfunc welcome {\n need $msg\n %registered = true # remember that we've finished registration\n %me.nick = $msg.params[0] # assume the target is our actual nickname\n\n # we can't actually depend on this always being the case, but a\n # lot of IRC servers have nick!ident@host as the final word here.\n # if not, we will get that info the first time we recv a message from %me.\n if $msg.params[-1] =~ \/^(.+)!(.+)\\@(.+)$\/ {\n %me.nick = $1\n %me.user = $2\n %me.host = $3\n %me.realHost = $3\n }\n}\n\nfunc myInfo {\n need $msg\n %server.name = $msg.params[1]\n %server.version = $msg.params[2]\n}\n\nfunc endOfMOTD {\n if !%autojoin || %_didAutojoin\n return\n %sendJoin(channelNames: %autojoin)\n %_didAutojoin = true\n}\n\n# recv: :k.notroll.net 396 booby 73.88.xkw.t :is now your hidden host\nfunc hiddenHost {\n need $msg\n %me.host = $msg.params[1]\n}\n\n# during registration, add underscores to nickname as necessary\nfunc nickInUse {\n if %registered\n return\n %me.nick += \"_\"\n %sendNick(%me.nick)\n}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Forth"} {"commit":"d26428b2cfbc380adcb315fa0fd81c96797ea593","subject":"Turn off verbose logging","message":"Turn off verbose logging\n","repos":"rm-hull\/byok3,rm-hull\/byok3","old_file":"core\/src\/test\/resources\/forth\/F3.00_core_tests.fth","new_file":"core\/src\/test\/resources\/forth\/F3.00_core_tests.fth","new_contents":"\\ The test cases in John Hayes' original test suite were designed to test\n\\ features before they were used in later tests. Due to the structure of\n\\ this annex the progressive testing has been lost. This section attempts\n\\ to retain the integrity of the original test suite by laying out the\n\\ test progression for the core word set.\n\\\n\\ While this suite does test many aspects of the core word set, it is not\n\\ comprehensive. A standard system should pass all of the tests within this\n\\ suite. A system cannot claim to be standard simply because it passes this\n\\ test suite.\n\\\n\\ The test starts by verifying basic assumptions about number representation.\n\\ It then builds on this with tests of boolean logic, shifting, and comparisons.\n\\ It then tests the basic stack manipulations and arithmetic. Ultimately, it\n\\ tests the Forth interpreter and compiler.\n\\\n\\ Note that all of the tests in this suite assume the current base is hexadecimal.\n\n\\ ------------------------------------------------------------------------\n\nrequire forth\/tester.fth\n\n0 VERBOSE !\nHEX\n\nTESTING CORE WORDS","old_contents":"\\ The test cases in John Hayes' original test suite were designed to test\n\\ features before they were used in later tests. Due to the structure of\n\\ this annex the progressive testing has been lost. This section attempts\n\\ to retain the integrity of the original test suite by laying out the\n\\ test progression for the core word set.\n\\\n\\ While this suite does test many aspects of the core word set, it is not\n\\ comprehensive. A standard system should pass all of the tests within this\n\\ suite. A system cannot claim to be standard simply because it passes this\n\\ test suite.\n\\\n\\ The test starts by verifying basic assumptions about number representation.\n\\ It then builds on this with tests of boolean logic, shifting, and comparisons.\n\\ It then tests the basic stack manipulations and arithmetic. Ultimately, it\n\\ tests the Forth interpreter and compiler.\n\\\n\\ Note that all of the tests in this suite assume the current base is hexadecimal.\n\n\\ ------------------------------------------------------------------------\n\nrequire forth\/tester.fth\n\n1 VERBOSE !\nHEX\n\nTESTING CORE WORDS","returncode":0,"stderr":"","license":"mit","lang":"Forth"} {"commit":"c71033b26a5ed74bad160758249eb0ff2f56b2f0","subject":"Re-Write for the new API.","message":"Re-Write for the new API.","repos":"rbsexton\/sockpuppet,rbsexton\/sockpuppet","old_file":"forth\/serCM3_SAPI-level0.fth","new_file":"forth\/serCM3_SAPI-level0.fth","new_contents":"\\ serCM3_sapi_level0.fth - SAPI polled RX, polled TX, serial communication drivers\n\\ Written to run against the SockPuppet API.\n\n\\ Level 0 support, with WFI instead of pause.\n\\ The SAPI is a system call interace, so there is no blocking.\n\\ KEY requires blocking, so that must be implemented here.\n\nonly forth definitions\n\n\\ ==============\n\\ *T SAPI polled serial driver\n\\ ==============\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\n\\ ** using the internal UARTs via the SAPI call layer. This is \n\\ ** The simplest implementation level.\n\n\\ ****************\n\\ *S Configuration\n\\ ****************\n\\ *P Configuration is managed by the SAPI\n\ntarget\n\n\\ ********************\n\\ *S Serial primitives\n\\ ********************\ninternal\n\n: +FaultConsole\t( -- ) ;\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\n\\ ** for more details.\n\ntarget\n\n\\ CODE (seremitfc)\t\\ char base --\n\\ This is a system call.\n\n: (seremit)\t\\ char base -- \n\\ *G Wrapped call that checks for throttling, and if so,\n\\ calls PAUSE to let another task run, or just does a WFI if no multitasker.\n\\ The only interesting thing is failure, or -1. That means retry.\n\tbegin \n\t2dup (seremitfc) dup 0 < \\ char base ret t\/f\n\tIF [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then] THEN \\ char base ret \n 0 >= until\n 2drop\n\t;\n\n: (sertype) \\ caddr len base --\n\\ *G Transmit a string on the given UART.\n\\ * The system call wants base len caddr\n\\ * and it returns the number of characters sent.\n\t>R \\ We'll use this a few times.\n\tbegin \n\t2dup R@ (sertypefc) dup >R \\ caddr len ret\n\t- dup IF \\ If there are still characters left \n\t [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then]\n\t swap R> + swap \\ finish advancing the caddr len pair\n\tELSE R> drop \n\tTHEN \n\tdup 0= until \\ Do this until nothing is left.\n\t2drop \n\tR> drop \n;\n\n: (sercr)\t\\ base --\n\\ *G Transmit a CR\/LF pair on the given UART.\n\\ Wrapped version, just like (seremit)\n\tbegin \n\tdup (sercrfc) dup 0= \\ base ret t\/f\n IF [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then] THEN \\ base ret \n until\n drop\n\t;\n\n: (serkey) \\ base -- c\n\\ *G Get a character from the port. Retry until we get it.\n\\ See if its negative. If so, discard it and leave false to re-loop.\n\\ If not negative, leave true on the stack to exit.\n begin \\ base ret t\/f \n\tdup (serkeyfc) dup 0 < \\ base ret t\/f \n\t IF [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then] drop false \n\t ELSE true \n\t THEN \\ base ret t\/f \n\tuntil \\ base ret \n\tswap drop \n;\n\n\\ THis is a system call.\n\\ CODE (serkey?) \\ base -- t\/f\n\\ *G Return true if the given UART has a character avilable to read.\n\nexternal \n\n: seremit0\t\\ char --\n\\ *G Transmit a character on UART0.\n 0 (seremit) ;\n: sertype0\t\\ c-addr len --\n\\ *G Transmit a string on UART0.\n 0 (sertype) ;\n: sercr0\t\\ --\n\\ *G Issue a CR\/LF pair to UART0.\n 0 (sercr) ;\n: serkey?0\t\\ -- flag\n\\ *G Return true if UART0 has a character available.\n 0 (serkey?) ;\n: serkey0\t\\ -- char\n\\ *G Wait for a character on UART0.\n 0 (serkey) ;\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\n\\ *G Generic I\/O device for UART0.\n ' serkey0 ,\t\t\\ -- char ; receive char\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\n ' seremit0 ,\t\t\\ -- char ; display char\n ' sertype0 ,\t\t\\ caddr len -- ; display string\n ' sercr0 ,\t\t\\ -- ; display new line\n\n\\ Non-UARTs.\n: seremit10 #10 (seremit) ;\n: sertype10\t#10 (sertype) ;\n: sercr10\t#10 (sercr) ;\n: serkey?10\t#10 (serkey?) ;\n: serkey10\t#10 (serkey) ;\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\n\nconsole-port 0 = [if]\n console0 constant console\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\n\\ ** It may be changed by one of the phrases of the form:\n\\ *C dup opvec ! ipvec !\n\\ *C SetConsole\n[then]\n\nconsole-port #10 = [if]\n console10 constant console\n[then]\n\n\\ ************************\n\\ *S System initialisation\n\\ ************************\n\n\\ This is a NOP in the SAPI environment\n: init-ser ;\t\\ --\n\\ *G Initialise all serial ports\n\n\\ ======\n\\ *> ###\n\\ ======\n\ndecimal\n","old_contents":"\\ serCM3_sapi_level0.fth - SAPI polled RX, polled TX, serial communication drivers\n\\ Written to run against the SockPuppet API.\n\n\\ Level 0 support, with WFI instead of pause.\n\\ The SAPI is a system call interace, so there is no blocking.\n\\ KEY requires blocking, so that must be implemented here.\n\nonly forth definitions\n\n\\ ==============\n\\ *T SAPI polled serial driver\n\\ ==============\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\n\\ ** using the internal UARTs via the SAPI call layer. This is \n\\ ** The simplest implementation level.\n\n\\ ****************\n\\ *S Configuration\n\\ ****************\n\\ *P Configuration is managed by the SAPI\n\ntarget\n\n\\ ********************\n\\ *S Serial primitives\n\\ ********************\ninternal\n\n: +FaultConsole\t( -- ) ;\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\n\\ ** for more details.\n\ntarget\n\n\\ CODE (seremitfc)\t\\ char base --\n\\ This is a system call.\n\n: (seremit)\t\\ char base -- \n\\ *G Wrapped call that checks for throttling, and if so,\n\\ calls PAUSE to let another task run, or just does a WFI if no multitasker.\n\\ The only interesting thing is failure, or -1. That means retry.\n\tbegin \n\t2dup (seremitfc) dup 0 < \\ char base ret t\/f\n\tIF [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then] THEN \\ char base ret \n 0 >= until\n 2drop\n\t;\n\n: (sertype) \\ caddr len base --\n\\ *G Transmit a string on the given UART.\n\\ * The system call wants base len caddr\n\t>R \\ We'll use this a few times.\n\tbegin \n\t2dup R@ (sertypefc) dup \\ caddr len ret ret\n\tIF \n\t [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then]\n\t dup >R - swap R> + swap \\ Advance the caddr len pair\n\tTHEN \n\t0= until\n\t2drop \n\tR> drop \n;\n\n: (sercr)\t\\ base --\n\\ *G Transmit a CR\/LF pair on the given UART.\n\\ Wrapped version, just like (seremit)\n\tbegin \n\tdup (sercrfc) dup 0= \\ base ret t\/f\n IF [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then] THEN \\ base ret \n until\n drop\n\t;\n\n: (serkey) \\ base -- c\n\\ *G Get a character from the port. Retry until we get it.\n\\ See if its negative. If so, discard it and leave false to re-loop.\n\\ If not negative, leave true on the stack to exit.\n begin \\ base ret t\/f \n\tdup (serkeyfc) dup 0 < \\ base ret t\/f \n\t IF [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then] drop false \n\t ELSE true \n\t THEN \\ base ret t\/f \n\tuntil \\ base ret \n\tswap drop \n;\n\n\\ THis is a system call.\n\\ CODE (serkey?) \\ base -- t\/f\n\\ *G Return true if the given UART has a character avilable to read.\n\nexternal \n\n: seremit0\t\\ char --\n\\ *G Transmit a character on UART0.\n 0 (seremit) ;\n: sertype0\t\\ c-addr len --\n\\ *G Transmit a string on UART0.\n 0 (sertype) ;\n: sercr0\t\\ --\n\\ *G Issue a CR\/LF pair to UART0.\n 0 (sercr) ;\n: serkey?0\t\\ -- flag\n\\ *G Return true if UART0 has a character available.\n 0 (serkey?) ;\n: serkey0\t\\ -- char\n\\ *G Wait for a character on UART0.\n 0 (serkey) ;\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\n\\ *G Generic I\/O device for UART0.\n ' serkey0 ,\t\t\\ -- char ; receive char\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\n ' seremit0 ,\t\t\\ -- char ; display char\n ' sertype0 ,\t\t\\ caddr len -- ; display string\n ' sercr0 ,\t\t\\ -- ; display new line\n\n\\ Non-UARTs.\n: seremit10 #10 (seremit) ;\n: sertype10\t#10 (sertype) ;\n: sercr10\t#10 (sercr) ;\n: serkey?10\t#10 (serkey?) ;\n: serkey10\t#10 (serkey) ;\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\n\nconsole-port 0 = [if]\n console0 constant console\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\n\\ ** It may be changed by one of the phrases of the form:\n\\ *C dup opvec ! ipvec !\n\\ *C SetConsole\n[then]\n\nconsole-port #10 = [if]\n console10 constant console\n[then]\n\n\\ ************************\n\\ *S System initialisation\n\\ ************************\n\n\\ This is a NOP in the SAPI environment\n: init-ser ;\t\\ --\n\\ *G Initialise all serial ports\n\n\\ ======\n\\ *> ###\n\\ ======\n\ndecimal\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Forth"} {"commit":"da210453469a1e82883fd367360d5afcee5e0983","subject":"Added Forth example","message":"Added Forth example\n","repos":"rodionovd\/atom-script,anfedorov\/atom-script,Calyhre\/atom-script,efatsi\/atom-script,Calyhre\/atom-script,Calyhre\/atom-script,efatsi\/atom-script,rodionovd\/atom-script,Calyhre\/atom-script,rodionovd\/atom-script,efatsi\/atom-script,anfedorov\/atom-script,efatsi\/atom-script,anfedorov\/atom-script,chenruixuan\/atom-script,rodionovd\/atom-script,anfedorov\/atom-script,TomosBlack\/atom-script,rodionovd\/atom-script,Calyhre\/atom-script,rodionovd\/atom-script,Calyhre\/atom-script,MichaelSp\/atom-script,anfedorov\/atom-script,rodionovd\/atom-script,fscherwi\/atom-script,rodionovd\/atom-script,efatsi\/atom-script,anfedorov\/atom-script,anfedorov\/atom-script,Calyhre\/atom-script,Calyhre\/atom-script,efatsi\/atom-script,anfedorov\/atom-script,Calyhre\/atom-script,rodionovd\/atom-script,efatsi\/atom-script,anfedorov\/atom-script,rgbkrk\/atom-script,anfedorov\/atom-script,efatsi\/atom-script,efatsi\/atom-script,efatsi\/atom-script,rodionovd\/atom-script,rodionovd\/atom-script,anfedorov\/atom-script,idleberg\/atom-script,rodionovd\/atom-script,rodionovd\/atom-script,efatsi\/atom-script,anfedorov\/atom-script,Calyhre\/atom-script,Calyhre\/atom-script,efatsi\/atom-script,efatsi\/atom-script,anfedorov\/atom-script,Calyhre\/atom-script","old_file":"examples\/hello.fth","new_file":"examples\/hello.fth","new_contents":": HELLO-WORLD .\" Hello, World! \" CR ;\nHELLO-WORLD\n","old_contents":"","returncode":1,"stderr":"error: pathspec 'examples\/hello.fth' did not match any file(s) known to git\n","license":"mit","lang":"Forth"} {"commit":"e66472852eb8c17282cfeb99024ee35c50456847","subject":"Adds EVENP and ODDP.","message":"Adds EVENP and ODDP.\n","repos":"SamSkulls\/filth","old_file":"stdlib.fth","new_file":"stdlib.fth","new_contents":"","old_contents":"","returncode":128,"stderr":"remote: Support for password authentication was removed on August 13, 2021.\nremote: Please see https:\/\/docs.github.com\/en\/get-started\/getting-started-with-git\/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.\nfatal: Authentication failed for 'https:\/\/github.com\/SamSkulls\/filth.git\/'\n","license":"mit","lang":"Forth"} {"commit":"da5e4749e6f2f0999e6df4c6d7f457e914707be9","subject":"Initial system calls stuff.","message":"Initial system calls stuff.","repos":"rbsexton\/gecko,rbsexton\/gecko,rbsexton\/gecko","old_file":"leopard\/usbforth\/SysCalls.fth","new_file":"leopard\/usbforth\/SysCalls.fth","new_contents":"\\ Wrappers for SAPI functions, ABI 4.0\n\n\\ Note that the system call number is embedded into the instruction,\n\\ so this is not so easily parameterized.\n\n#0 equ SAPI_VEC_VERSION\n#1 equ SAPI_VEC_01_GetRuntimeLinks\n#2 equ SAPI_VEC_02_PutChar\n#3 equ SAPI_VEC_03_GetChar\n#4 equ SAPI_VEC_04_GetCharAvail\n#5 equ SAPI_VEC_05_PutString\n#6 equ SAPI_VEC_06_EOL\n#14 equ SAPI_VEC_14_PetWatchdog\n#15 equ SAPI_VEC_15_GetTimeMS\n\nCODE SAPI-Version \\ -- n\n\\ *G Get the version of the binary ABI in use. \n\tsvc # SAPI_VEC_VERSION \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE GETRUNTIMELINKS \\ type -- n\n\\ *G Get the runtime linking information. Type 0 - A Dynamic linking \n\\ ** table with name, address pairs. Type 1 - A Zero-Terminated Jump table.\n\tmov r0, tos\n\tsvc # SAPI_VEC_01_GetRuntimeLinks \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE (seremitfc) \\ char base --\n\\ *G Service call for a single char - This one has a special name because\n\\ ** It'll be wrapped by something that can respond to the flow control \n\\ ** return code and PAUSE + Retry \n\tmov r0, tos\n\tldr r1, [ psp ], # 4\n\tmov r2, # 0 \\ Don't request a wake.\n\tsvc # SAPI_VEC_02_PutChar\t\n\tmov tos, r0\n next,\nEND-CODE\n\nCODE (serkeyfc) \\ base -- char \n\\ *G Get a character from the port, or -1 for fail\n\tmov r0, tos\t\n\tmov r1, # 0 \\ No blocking.\n\tsvc # SAPI_VEC_03_GetChar\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE (serkey?) \\ base -- t\/f\n\\ *G Return true if the given stream has a character avilable to read.\n\\ The call returns the number of chars available. \n\tmov r0, tos\n\tsvc # SAPI_VEC_04_GetCharAvail\n\tmov tos, r0\n\tnext,\nEND-CODE\n \n\\ These two can be created from simpler things, and are optional.\n\\ CODE (type) \n\\ END-CODE\n\n\\ CODE (cr) \n\\ END-CODE\n\nCODE PetWatchDog \\ n --\n\\ *G Refresh the watchdog. Pass in a platform-specific number\n\\ ** To specify a timerout (if supported), or zero for the default value. \n\tmov r0, tos\n\tldr r1, [ psp ], # 4\n\tsvc # SAPI_VEC_14_PetWatchdog\n\tldr tos, [ psp ], # 4\n\tnext,\nEND-CODE\n\nCODE TICKS \\ -- n \n\\ *G The current value of the millisecond ticker.\n\tsvc # SAPI_VEC_15_GetTimeMS\n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\n\n\n","old_contents":"","returncode":1,"stderr":"error: pathspec 'leopard\/usbforth\/SysCalls.fth' did not match any file(s) known to git\n","license":"mit","lang":"Forth"} {"commit":"cb3adf0551605202ef4e20b55ef801bbac35cc6e","subject":"Add forth tic-tac-toe","message":"Add forth tic-tac-toe\n","repos":"WesleyAC\/toybox,WesleyAC\/toybox,WesleyAC\/toybox,WesleyAC\/toybox,WesleyAC\/toybox","old_file":"forth\/ttt.fth","new_file":"forth\/ttt.fth","new_contents":"variable board 8 allot\nboard 9 0 fill\nvariable turn\n1 turn !\n\n: output-player ( player -- )\ncase\n0 of .\" . \" endof\n1 of .\" X \" endof\n2 of .\" O \" endof\n .\" ? \"\nendcase ;\n\n: output-board 9 0 do board i + c@ output-player i 3 mod 2 = if cr then loop ;\n: output page output-board turn c@ output-player .\" to play \" cr ;\n: output-victory page output-board turn c@ output-player .\" wins \" cr ;\n: output-draw page output-board .\" cat's game \" cr ;\n\n: ascii-to-pos ( ascii -- pos )\ncase\n113 ( q ) of 0 endof\n119 ( w ) of 1 endof\n101 ( e ) of 2 endof\n97 ( a ) of 3 endof\n115 ( s ) of 4 endof\n100 ( d ) of 5 endof\n122 ( z ) of 6 endof\n120 ( x ) of 7 endof\n99 ( c ) of 8 endof\n -1\nendcase ;\n\n: swap-turn turn @ 2 mod 1 + turn ! ;\n: set-cell ( n v -- ) swap board + c! ;\n: cell-empty? ( n -- e? ) board + c@ 0 = ;\n\n: do-move ( pos -- ) turn c@ set-cell swap-turn ;\n: try-move ( pos -- ) dup cell-empty? if do-move else drop then ;\n\n: get-input ( -- pos ) key ascii-to-pos ;\n: try-input ( -- ) get-input dup -1 <> if try-move else drop then ;\n\n: 3check ( a b c -- win? ) over = rot rot over = rot and swap 0 <> and ; \n\n: ?victory ( -- v? )\nboard c@ board 3 + c@ board 6 + c@ 3check\nboard 1 + c@ board 4 + c@ board 7 + c@ 3check or\nboard 2 + c@ board 5 + c@ board 8 + c@ 3check or\nboard c@ board 1 + c@ board 2 + c@ 3check or\nboard 3 + c@ board 4 + c@ board 5 + c@ 3check or\nboard 6 + c@ board 7 + c@ board 8 + c@ 3check or\nboard c@ board 4 + c@ board 8 + c@ 3check or\nboard 2 + c@ board 4 + c@ board 6 + c@ 3check or\n;\n\n: ?draw ( -- d? ) 1 9 0 do board i + c@ 0 <> and loop ;\n: ?game-end ( -- e? ) ?victory ?draw or ;\n: show-end ?victory if swap-turn output-victory else output-draw then ;\n\n: reset-board 9 0 do 0 board i + c! loop ;\n: reset-turn 1 turn c! ;\n: reset-game reset-board reset-turn ;\n\n: game begin output try-input ?game-end until show-end ;\n: replay-loop begin reset-game game .\" play again? (y\/n) \" cr key 121 <> until bye ;\n\nreplay-loop\n","old_contents":"","returncode":1,"stderr":"error: pathspec 'forth\/ttt.fth' did not match any file(s) known to git\n","license":"mit","lang":"Forth"} {"commit":"f7226fa7805184fdc7cc47b122f0449cd367acd1","subject":"new file: add support for multiple numeric bases","message":"new file: add support for multiple numeric bases\n","repos":"crcx\/rx-nga,crcx\/rx-nga,crcx\/rx-nga,crcx\/rx-nga","old_file":"forthlets\/numeric-bases.forth","new_file":"forthlets\/numeric-bases.forth","new_contents":"","old_contents":"","returncode":128,"stderr":"remote: Support for password authentication was removed on August 13, 2021.\nremote: Please see https:\/\/docs.github.com\/en\/get-started\/getting-started-with-git\/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.\nfatal: Authentication failed for 'https:\/\/github.com\/crcx\/rx-nga.git\/'\n","license":"isc","lang":"Forth"} {"commit":"275895c9877ebc6114143202662912b60f9e9aac","subject":"Initial wall clock code.","message":"Initial wall clock code.","repos":"rbsexton\/gecko,rbsexton\/gecko,rbsexton\/gecko","old_file":"zero\/clock-umb\/forth\/Clock.fth","new_file":"zero\/clock-umb\/forth\/Clock.fth","new_contents":"(( Clock Code ))\n\n\\ The gadget that drives it all. This is rigged for debugging,\n\\ terminate it by setting clockterm to non-zero.\n: CLOCKSTART ( n -- ) \n icroot inter.rtcsem 0 over ! \\ Reset the free-running counter.\n swap \\ addr n -- \n 0 do \n dup @resetex! ?dup if advance else [asm wfi asm] then\n loop\n drop\n;\n\n: CLOCKINIT ( -- )\n #1000 needlemax\n 2dup ! 4 + 2dup ! 4 + ! \n;\n \n\\ Heres where we advance any needles.\n: ADVANCE ( n -- )\n pwm0@ + pwm0! \n;\n\n\\ ----------------------------------------------------------\n\\ Needle Management\n\\ ----------------------------------------------------------\nudata\ncreate NEEDLEMAX 3 cells allot\ncdata\n\n: ++NEEDLE_S ; \\ Called ever time.\n: ++NEEDLE_M ; \\ Every time we roll the seconds.\n\n\\ ----------------------------------------------------------\n\\ PWM\/Timer Manipulation\n\\ ----------------------------------------------------------\n_timer0 $34 + equ _PWM0 \n_timer0 $44 + equ _PWM1 \n_timer0 $54 + equ _PWM2 \n\n: PWM0! ( n -- ) _pwm0 ! ;\n: PWM1! ( n -- ) _pwm1 ! ;\n: PWM2! ( n -- ) _pwm2 ! ;\n\n: PWM0@ ( -- n ) _pwm0 w@ ;\n: PWM1@ ( -- n ) _pwm1 w@ ;\n: PWM2@ ( -- n ) _pwm2 w@ ;\n\n: SCALE0 #1000 0 do I pwm0! loop ; \n: SCALE1 #1000 0 do I pwm0! [asm wfi asm] loop ; \n\n\\ ----------------------------------------------------------\n\\ Keeping track of the time.\n\\ ----------------------------------------------------------\nstruct _HMS\n\tint hms.subsec\n\tint hms.s\n\tint hms.m\n\tint hms.h\n\tint hms.maxsubsec \\ Max Value for subseconds\n\tint hms.maxs+m \\ Max Value for secs+minutes\n\tint hms.maxh \\ Max for hours\n\tptr hms.w_s \\ Increment the seconds value\n\tptr hms.w_mh \\ increment the minutes + hours\nend-struct\n\nidata\ncreate HMS \n 0 , 0 , 0 , 0 , \\ Running Counters\n #16 , #60 , #24 , \\ Limits\n ' ++needle_s , ' ++needle_m , \\ Words to invoke\ncreate DHMS\n 0 , 0 , 0 , 0 , \\ Running Counters\n #10 , #100 , #10 , \\ Limits\n' ++needle_s , ' ++needle_m , \\ Words to invoke\ncdata \n\n\\ Core concept - We update the seconds \n\\ each time this gets called. \n\\ If the seconds wrap, we update the minutes\n\\ and the hours.\n: ADVANCETIME ( struct-addr -- )\n ++needle_s 1 over hms.subsec +!\n dup hms.subsec @ #16 < if drop exit then\n 0 over hms.subsec ! \\ Reset the subsecs \n\n ++needle_m 1 over hms.s +!\n dup hms.s @ #60 < if drop exit then \n 0 over hms.s ! \\ Reset the seconds\n\n 1 over hms.m +!\n dup hms.m @ #60 < if drop exit then \n 0 over hms.m ! \\ Reset the minutes\n\n 1 over hms.h +!\n dup hms.h @ #24 < if drop exit then \n 0 over hms.h ! \\ Reset the minutes\n\n drop \n\n;\n\n: ? @ . ; \n: .hms ( addr -- ) \n dup hms.h ?\n dup hms.m ?\n dup hms.s ?\n hms.subsec ?\n cr \n;\n\n\\ : foo 0 do hms advancetime loop ; \n\n\\ ============================ UNTESTED =======================\n\\ VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n\n","old_contents":"","returncode":1,"stderr":"error: pathspec 'zero\/clock-umb\/forth\/Clock.fth' did not match any file(s) known to git\n","license":"mit","lang":"Forth"} {"commit":"7e0a895c936a8ed6f8b56576fbd376fafc298e3d","subject":"new sample code: html generation","message":"new sample code: html generation\n","repos":"crcx\/rx-nga,crcx\/rx-nga,crcx\/rx-nga,crcx\/rx-nga","old_file":"forthlets\/html.forth","new_file":"forthlets\/html.forth","new_contents":"","old_contents":"","returncode":128,"stderr":"remote: Support for password authentication was removed on August 13, 2021.\nremote: Please see https:\/\/docs.github.com\/en\/get-started\/getting-started-with-git\/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.\nfatal: Authentication failed for 'https:\/\/github.com\/crcx\/rx-nga.git\/'\n","license":"isc","lang":"Forth"} {"commit":"8978b351a49be88bc4eac1577468f0982227a182","subject":"Update static\/vendors\/ace-builds\/demo\/kitchen-sink\/docs\/forth.frt","message":"Update static\/vendors\/ace-builds\/demo\/kitchen-sink\/docs\/forth.frt\n\nSigned-off-by: Bernard Ojengwa \n","repos":"apipanda\/openssl,apipanda\/openssl,apipanda\/openssl,apipanda\/openssl","old_file":"static\/vendors\/ace-builds\/demo\/kitchen-sink\/docs\/forth.frt","new_file":"static\/vendors\/ace-builds\/demo\/kitchen-sink\/docs\/forth.frt","new_contents":": HELLO ( -- ) CR .\" Hello, world!\" ; \n\nHELLO \nHello, world!\n\n: [CHAR] CHAR POSTPONE LITERAL ; IMMEDIATE\n\n0 value ii 0 value jj\n0 value KeyAddr 0 value KeyLen\ncreate SArray 256 allot \\ state array of 256 bytes\n: KeyArray KeyLen mod KeyAddr ;\n\n: get_byte + c@ ;\n: set_byte + c! ;\n: as_byte 255 and ;\n: reset_ij 0 TO ii 0 TO jj ;\n: i_update 1 + as_byte TO ii ;\n: j_update ii SArray get_byte + as_byte TO jj ;\n: swap_s_ij\n jj SArray get_byte\n ii SArray get_byte jj SArray set_byte\n ii SArray set_byte\n;\n\n: rc4_init ( KeyAddr KeyLen -- )\n 256 min TO KeyLen TO KeyAddr\n 256 0 DO i i SArray set_byte LOOP\n reset_ij\n BEGIN\n ii KeyArray get_byte jj + j_update\n swap_s_ij\n ii 255 < WHILE\n ii i_update\n REPEAT\n reset_ij\n;\n: rc4_byte\n ii i_update jj j_update\n swap_s_ij\n ii SArray get_byte jj SArray get_byte + as_byte SArray get_byte xor\n;","old_contents":"","returncode":1,"stderr":"error: pathspec 'static\/vendors\/ace-builds\/demo\/kitchen-sink\/docs\/forth.frt' did not match any file(s) known to git\n","license":"mit","lang":"Forth"} {"commit":"1d3c0a8d23481f6acd8d42f81a24627669b153a8","subject":"Strictly speaking, this works. It enumarates the PnP devices, and load the modules needed according to a file relating module names (actually, _file_ names, not really modules -- the dependency stuff is not exported to loader's UI) to PnP IDs.","message":"Strictly speaking, this works. It enumarates the PnP devices, and\nload the modules needed according to a file relating module names\n(actually, _file_ names, not really modules -- the dependency\nstuff is not exported to loader's UI) to PnP IDs.\n\nBut it still lacks a number of desired features, and it's too crude\nfor my tastes. But since I don't have time to work on it, it might\nbe preferable to make it available to those who might. It's not\ninstalled by default, much less loaded. In fact, it wouldn't even\nhad a copyright message (who? me? assume responsibility for _this_?),\nif the cvs commit hadn't aborted for lack of $FreeBSD$, and I decided\nto just cut&paste the stuff from elsewhere.\n","repos":"jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase,jrobhoward\/SCADAbase","old_file":"sys\/boot\/forth\/pnp.4th","new_file":"sys\/boot\/forth\/pnp.4th","new_contents":"\\ Copyright (c) 2000 Daniel C. Sobral \n\\ All rights reserved.\n\\\n\\ Redistribution and use in source and binary forms, with or without\n\\ modification, are permitted provided that the following conditions\n\\ are met:\n\\ 1. Redistributions of source code must retain the above copyright\n\\ notice, this list of conditions and the following disclaimer.\n\\ 2. Redistributions in binary form must reproduce the above copyright\n\\ notice, this list of conditions and the following disclaimer in the\n\\ documentation and\/or other materials provided with the distribution.\n\\\n\\ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\\ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\\ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\\ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\\ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\\ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\\ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\\ SUCH DAMAGE.\n\\\n\\ $FreeBSD$\n\npnpdevices drop\n\n: enumerate\n pnphandlers begin\n dup @\n while\n .\" Probing \" dup @ pnph.name @ dup strlen type .\" ...\" cr\n 0 over @ pnph.enumerate @ ccall drop\n cell+\n repeat\n;\n\n: summary\n .\" PNP scan summary:\" cr\n pnpdevices stqh_first @\n begin\n dup\n while\n dup pnpi.ident stqh_first @ pnpid.ident @ dup strlen type\n dup pnpi.desc @ ?dup if\n .\" : \"\n dup strlen type\n then\n cr\n pnpi.link stqe_next @\n repeat\n drop\n;\n\n: compare-pnpid ( addr addr' -- flag )\n begin\n over c@ over c@ <> if drop drop false exit then\n over c@ over c@ and\n while\n char+ swap char+ swap\n repeat\n c@ swap c@ or 0=\n;\n\n: search-pnpid ( id -- flag )\n >r\n pnpdevices stqh_first @\n begin ( pnpinfo )\n dup\n while\n dup pnpi.ident stqh_first @\n begin ( pnpinfo pnpident )\n dup pnpid.ident @ r@ compare-pnpid\n if\n\tr> drop\n\t\\ XXX Temporary debugging message\n\t.\" Found \" pnpid.ident @ dup strlen type\n\tpnpi.desc @ ?dup if\n\t .\" : \" dup strlen type\n\tthen cr\n\t\\ drop drop\n\ttrue\n\texit\n then\n pnpid.link stqe_next @\n ?dup 0=\n until\n pnpi.link stqe_next @\n repeat\n r> drop\n drop\n false\n;\n\n: skip-space ( addr -- addr' )\n begin\n dup c@ bl =\n over c@ 9 = or\n while\n char+\n repeat\n;\n\n: skip-to-space ( addr -- addr' )\n begin\n dup c@ bl <>\n over c@ 9 <> and\n over c@ and\n while\n char+\n repeat\n;\n\n: premature-end? ( addr -- addr flag )\n postpone dup postpone c@ postpone 0=\n postpone if postpone exit postpone then\n; immediate\n\n0 value filename\n0 value timestamp\n0 value id\n\nonly forth also support-functions\n\n: (load) load ;\n\n: check-pnpid ( -- )\n line_buffer .addr @ \n \\ Search for filename\n skip-space premature-end?\n dup to filename\n \\ Search for end of filename\n skip-to-space premature-end?\n 0 over c! char+\n \\ Search for timestamp\n skip-space premature-end?\n dup to timestamp\n skip-to-space premature-end?\n 0 over c! char+\n \\ Search for ids\n begin\n skip-space premature-end?\n dup to id\n skip-to-space dup c@ >r\n 0 over c! char+\n id search-pnpid if\n filename dup strlen 1 ['] (load) catch if\n\tdrop drop drop\n\t.\" Error loading \" filename dup strlen type cr\n then\n r> drop exit\n then\n r> 0=\n until\n;\n\n: load-pnp\n 0 to end_of_file?\n reset_line_reading\n s\" \/boot\/pnpid.conf\" fopen fd !\n fd @ -1 <> if\n begin\n end_of_file? 0=\n while\n read_line\n check-pnpid\n repeat\n fd @ fclose\n then\n;\n\n","old_contents":"","returncode":1,"stderr":"error: pathspec 'sys\/boot\/forth\/pnp.4th' did not match any file(s) known to git\n","license":"bsd-3-clause","lang":"Forth"} {"commit":"47e9e7b9a718deed8f751bf587b08ff0b96e8245","subject":"Added standard library directory to git","message":"Added standard library directory to git\n","repos":"roboguy13\/MetaForth,roboguy13\/MetaForth","old_file":"src\/std\/cond.4th","new_file":"src\/std\/cond.4th","new_contents":": true swap call ;\n: false call ;\n\n: if rot call ;\n","old_contents":"","returncode":1,"stderr":"error: pathspec 'src\/std\/cond.4th' did not match any file(s) known to git\n","license":"bsd-3-clause","lang":"Forth"} {"commit":"8e3986b6c3cc84deda8cb9c1b5f6657435c6a6a1","subject":"Add the updated Forth system calls code.","message":"Add the updated Forth system calls code.","repos":"rbsexton\/sockpuppet,rbsexton\/sockpuppet","old_file":"forth\/SysCalls.fth","new_file":"forth\/SysCalls.fth","new_contents":"\\ Wrappers for SAPI functions, ABI 2.x\n\n\\ Note that the system call number is embedded into the instruction,\n\\ so this is not so easily parameterized.\n\n#0 equ SAPI_VEC_VERSION\n#1 equ SAPI_VEC_01_GetRuntimeLinks\n#2 equ SAPI_VEC_02_PutChar\n#3 equ SAPI_VEC_03_GetChar\n#4 equ SAPI_VEC_04_GetCharAvail\n#5 equ SAPI_VEC_05_PutString\n#6 equ SAPI_VEC_06_EOL\n#14 equ SAPI_VEC_14_PetWatchdog\n#15 equ SAPI_VEC_15_GetTimeMS\n\nCODE SAPI-Version \\ -- n\n\\ *G Get the version of the binary ABI in use. \n\tsvc # SAPI_VEC_VERSION \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE GETRUNTIMELINKS \\ type -- n\n\\ *G Get the runtime linking information. Type 0 - A Dynamic linking \n\\ ** table with name, address pairs. Type 1 - A Zero-Terminated Jump table.\n\tmov r0, tos\n\tsvc # SAPI_VEC_01_GetRuntimeLinks \n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ --------------------------------------------\n\\ System calls that will require wrappers\n\\ --------------------------------------------\n\nCODE (SEREMITFC) \\ char base --\n\\ *G Service call for a single char - This one has a special name because\n\\ ** It'll be wrapped by something that can respond to the flow control \n\\ ** return code and PAUSE + Retry \n\tmov r0, tos\n\tldr r1, [ psp ], # 4\n\t[defined] SAPIWakeSupport? [if] mov r2, up [else] mov r2, # 0 [then] \n\tsvc # SAPI_VEC_02_PutChar\t\n\tmov tos, r0\n next,\nEND-CODE\n\nCODE (SERKEYFC) \\ base -- char \n\\ *G Get a character from the port, or -1 for fail\n\tmov r0, tos\t\n\t[defined] SAPIWakeSupport? [if] mov r1, up [else] mov r1, # 0 [then] \n\tsvc # SAPI_VEC_03_GetChar\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE (SERTYPEFC) \\ caddr len base -- return \n\\ *G Output characters. \n\tmov r0, tos\t\n\tldr r1, [ psp ], # 4\n\tldr r2, [ psp ], # 4\n\t[defined] SAPIWakeSupport? [if] mov r3, up [else] mov r3, # 0 [then] \n\tsvc # SAPI_VEC_05_PutString\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE (SERCRFC) \\ base -- return \n\\ *G Send a line terminator to the port. Return 0 for success, -1 for fail.\n\tmov r0, tos\t\n\t[defined] SAPIWakeSupport? [if] mov r1, up [else] mov r1, # 0 [then] \n\tsvc # SAPI_VEC_06_EOL\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\\ --------------------------------------------\n\\ Direct substitures for existing stuff.\n\\ --------------------------------------------\n\nCODE (SERKEY?) \\ base -- t\/f\n\\ *G Return true if the given stream has a character avilable to read.\n\\ The call returns the number of chars available. \n\tmov r0, tos\n\tsvc # SAPI_VEC_04_GetCharAvail\n\tmov tos, r0\n\tnext,\nEND-CODE\n\nCODE PETWATCHDOG \\ n --\n\\ *G Refresh the watchdog. Pass in a platform-specific number\n\\ ** To specify a timerout (if supported), or zero for the default value. \n\tmov r0, tos\n\tldr r1, [ psp ], # 4\n\tsvc # SAPI_VEC_14_PetWatchdog\n\tldr tos, [ psp ], # 4\n\tnext,\nEND-CODE\n\nCODE TICKS \\ -- n \n\\ *G The current value of the millisecond ticker.\n mov r0, # 0 \\ We want the actual value.\n\tsvc # SAPI_VEC_15_GetTimeMS\n\tstr tos, [ psp, # -4 ] !\n\tmov tos, r0\n\tnext,\nEND-CODE\n\n\n\n\n","old_contents":"","returncode":1,"stderr":"error: pathspec 'forth\/SysCalls.fth' did not match any file(s) known to git\n","license":"bsd-2-clause","lang":"Forth"} {"commit":"58a15b1046069bfbafc4ddc94e9dbdc36f47f092","subject":"https:\/\/pt.stackoverflow.com\/q\/356658\/101","message":"https:\/\/pt.stackoverflow.com\/q\/356658\/101","repos":"bigown\/SOpt,bigown\/SOpt,bigown\/SOpt,maniero\/SOpt,bigown\/SOpt,maniero\/SOpt,maniero\/SOpt,maniero\/SOpt,bigown\/SOpt,maniero\/SOpt,bigown\/SOpt,maniero\/SOpt,maniero\/SOpt,maniero\/SOpt,maniero\/SOpt,maniero\/SOpt,maniero\/SOpt,bigown\/SOpt,bigown\/SOpt,maniero\/SOpt,maniero\/SOpt,bigown\/SOpt,maniero\/SOpt,maniero\/SOpt,maniero\/SOpt,bigown\/SOpt","old_file":"Portugol\/ExampleForth.fth","new_file":"Portugol\/ExampleForth.fth","new_contents":"0 value ii 0 value jj\n0 value KeyAddr 0 value KeyLen\ncreate SArray 256 allot \\ state array of 256 bytes\n: KeyArray KeyLen mod KeyAddr ;\n\n: get_byte + c@ ;\n: set_byte + c! ;\n: as_byte 255 and ;\n: reset_ij 0 TO ii 0 TO jj ;\n: i_update 1 + as_byte TO ii ;\n: j_update ii SArray get_byte + as_byte TO jj ;\n: swap_s_ij\n jj SArray get_byte\n ii SArray get_byte jj SArray set_byte\n ii SArray set_byte\n;\n\n: rc4_init ( KeyAddr KeyLen -- )\n 256 min TO KeyLen TO KeyAddr\n 256 0 DO i i SArray set_byte LOOP\n reset_ij\n BEGIN\n ii KeyArray get_byte jj + j_update\n swap_s_ij\n ii 255 < WHILE\n ii i_update\n REPEAT\n reset_ij\n;\n: rc4_byte\n ii i_update jj j_update\n swap_s_ij\n ii SArray get_byte jj SArray get_byte + as_byte SArray get_byte xor\n;\n\n\\https:\/\/pt.stackoverflow.com\/q\/356658\/101\n","old_contents":"","returncode":1,"stderr":"error: pathspec 'Portugol\/ExampleForth.fth' did not match any file(s) known to git\n","license":"mit","lang":"Forth"} {"commit":"0214074b3aba5ae412cf533a234feed29981fc9d","subject":"a new example","message":"a new example\n","repos":"crcx\/rx-nga,crcx\/rx-nga,crcx\/rx-nga,crcx\/rx-nga","old_file":"forthlets\/chessboard.forth","new_file":"forthlets\/chessboard.forth","new_contents":"","old_contents":"","returncode":128,"stderr":"remote: Support for password authentication was removed on August 13, 2021.\nremote: Please see https:\/\/docs.github.com\/en\/get-started\/getting-started-with-git\/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.\nfatal: Authentication failed for 'https:\/\/github.com\/crcx\/rx-nga.git\/'\n","license":"isc","lang":"Forth"} {"commit":"7bae225c7345b9f897a0ceb89988f1fdca9a3205","subject":"Tested and working basic Serial IO.","message":"Tested and working basic Serial IO.","repos":"rbsexton\/sockpuppet,rbsexton\/sockpuppet","old_file":"forth\/serCM3_SAPI-level0.fth","new_file":"forth\/serCM3_SAPI-level0.fth","new_contents":"\\ serCM3_sapi_level0.fth - SAPI polled RX, polled TX, serial communication drivers\n\\ Written to run against the SockPuppet API.\n\n\\ Level 0 support, with WFI instead of pause.\n\\ The SAPI is a system call interace, so there is no blocking.\n\\ KEY requires blocking, so that must be implemented here.\n\nonly forth definitions\n\n\\ ==============\n\\ *T SAPI polled serial driver\n\\ ==============\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\n\\ ** using the internal UARTs via the SAPI call layer. This is \n\\ ** The simplest implementation level.\n\n\\ ****************\n\\ *S Configuration\n\\ ****************\n\\ *P Configuration is managed by the SAPI\n\ntarget\n\n\\ ********************\n\\ *S Serial primitives\n\\ ********************\ninternal\n\n: +FaultConsole\t( -- ) ;\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\n\\ ** for more details.\n\ntarget\n\n\\ CODE (seremitfc)\t\\ char base --\n\\ This is a system call.\n\n: (seremit)\t\\ char base -- \n\\ *G Wrapped call that checks for throttling, and if so,\n\\ calls PAUSE to let another task run, or just does a WFI if no multitasker.\n\\ The only interesting thing is failure, or -1. That means retry.\n\tbegin \n\t2dup (seremitfc) dup 0 < \\ char base ret t\/f\n[ tasking? ] [if]\n\tIF PAUSE THEN\n[else]\n\tIF [asm wfi asm] THEN\n[then] \\ char base ret \n 0 >= until\n 2drop\n\t;\n\n: (sertype)\t\\ caddr len base --\n\\ *G Transmit a string on the given UART.\n -rot bounds\n ?do i c@ over (seremit) loop\n drop\n;\n\n: (sercr)\t\\ base --\n\\ *G Transmit a CR\/LF pair on the given UART.\n $0D over (seremit) $0A swap (seremit)\n;\n\n: (serkey) \\ base -- c\n\\ *G Get a character from the port. Retry until we get it.\n\\ See if its negative. If so, discard it and leave false to re-loop.\n\\ If not negative, leave true on the stack to exit.\n begin \\ base ret t\/f \n\tdup (serkeyfc) dup 0 < \\ base ret t\/f \n\t[ tasking? ] [if]\n\t\tIF PAUSE drop false ELSE true THEN\n\t[else]\n\t\tIF [asm wfi asm] drop false ELSE true THEN\n\t[then] \\ base ret \n\tuntil \\ base ret \n\tswap drop \n;\n\n\\ THis is a system call.\n\\ CODE (serkey?) \\ base -- t\/f\n\\ *G Return true if the given UART has a character avilable to read.\n\nexternal \n\n: seremit0\t\\ char --\n\\ *G Transmit a character on UART0.\n 0 (seremit) ;\n: sertype0\t\\ c-addr len --\n\\ *G Transmit a string on UART0.\n 0 (sertype) ;\n: sercr0\t\\ --\n\\ *G Issue a CR\/LF pair to UART0.\n 0 (sercr) ;\n: serkey?0\t\\ -- flag\n\\ *G Return true if UART0 has a character available.\n 0 (serkey?) ;\n: serkey0\t\\ -- char\n\\ *G Wait for a character on UART0.\n 0 (serkey) ;\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\n\\ *G Generic I\/O device for UART0.\n ' serkey0 ,\t\t\\ -- char ; receive char\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\n ' seremit0 ,\t\t\\ -- char ; display char\n ' sertype0 ,\t\t\\ caddr len -- ; display string\n ' sercr0 ,\t\t\\ -- ; display new line\n\n\\ Non-UARTs.\n: seremit10 #10 (seremit) ;\n: sertype10\t#10 (sertype) ;\n: sercr10\t#10 (sercr) ;\n: serkey?10\t#10 (serkey?) ;\n: serkey10\t#10 (serkey) ;\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\n\nconsole-port 0 = [if]\n console0 constant console\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\n\\ ** It may be changed by one of the phrases of the form:\n\\ *C dup opvec ! ipvec !\n\\ *C SetConsole\n[then]\n\nconsole-port #10 = [if]\n console10 constant console\n[then]\n\n\\ ************************\n\\ *S System initialisation\n\\ ************************\n\n\\ This is a NOP in the SAPI environment\n: init-ser ;\t\\ --\n\\ *G Initialise all serial ports\n\n\\ ======\n\\ *> ###\n\\ ======\n\ndecimal\n","old_contents":"","returncode":1,"stderr":"error: pathspec 'forth\/serCM3_SAPI-level0.fth' did not match any file(s) known to git\n","license":"bsd-2-clause","lang":"Forth"} {"commit":"904bb754a3e2bfee2ef9e6198dbb36313de6bf12","subject":"Create primes.frt","message":"Create primes.frt","repos":"drom\/quark,drom\/quark","old_file":"examples\/primes.frt","new_file":"examples\/primes.frt","new_contents":"http:\/\/hoult.org\/primes.txt\nhttp:\/\/hoult.org\/countPrimes.s\nhttp:\/\/www.forth.org\/TM-10656.pdf\n\n","old_contents":"","returncode":1,"stderr":"error: pathspec 'examples\/primes.frt' did not match any file(s) known to git\n","license":"mit","lang":"Forth"} {"commit":"ffae10f467a5bab90aaa6d3450a781ca72695168","subject":"Work in progress forth implementation. It has the correct basic structure minus the lack of additional constraints, but something is causing it to abort early.","message":"Work in progress forth implementation. It has the correct basic structure minus the lack\nof additional constraints, but something is causing it to abort early.\n","repos":"Tim-Tom\/scratch,Tim-Tom\/scratch,Tim-Tom\/scratch,Tim-Tom\/scratch,Tim-Tom\/scratch,Tim-Tom\/scratch,Tim-Tom\/scratch,Tim-Tom\/scratch,Tim-Tom\/scratch,Tim-Tom\/scratch","old_file":"magic-puzzle\/magic-puzzle.fth","new_file":"magic-puzzle\/magic-puzzle.fth","new_contents":"3 constant width\n21 constant goal\nwidth 1- constant wm\nwidth 1+ constant wp\nwidth width * constant size\n\ncreate choices 3 , 4 , 5 ,\n 6 , 7 , 8 ,\n 9 , 10 , 11 ,\n\nvariable picked size allot\n\n: clearPicked\n size\n begin\n 1- dup 0>= while\n dup picked + 0 swap C!\n repeat\n drop ;\n\nvariable a size cells allot\n\n: choiceSearch\n 0\n begin\n dup size < while\n choices over cells + @\n rot tuck = if\n drop -1 exit\n endif\n swap 1+\n repeat\n 2drop 0 ;\n\n: reverseCrossInvalid\n 0\n wm wp * wm do\n a i cells + @ +\n wm +loop\n goal = ;\n\n: crossInvalid\n 0\n size 0 do\n a i cells + @ +\n wp +loop\n goal = ;\n \n: bottomRowInvalid\n 0\n size size width - do\n a i cells + @ +\n loop\n goal = ;\n\n: bottomRightInvalid\n bottomRowInvalid if\n -1\n else\n crossInvalid\n endif ;\n\n0 VALUE pickNextRef\n\n: pickInternal\n size 0 do\n dup cells a + choices i cells + @ swap !\n i picked + C@ 0= if\n 1 i picked + C!\n dup pickNextRef execute\n 0 i picked + C!\n endif\n loop\n drop ;\n\n: pickRight\n 0 over dup dup width mod - do\n a i cells + @ +\n loop\n goal swap - \n over over swap cells a + !\n choiceSearch if\n dup picked + C@ 0= if\n 1 over picked + C!\n over pickNextRef execute\n 0 swap picked + C!\n endif\n endif\n drop ;\n\n: pickBottom\n 0 over dup width mod do\n a i cells + @ +\n width +loop\n goal swap -\n over over swap cells a + !\n choiceSearch if\n dup picked + C@ 0= if\n 1 over picked + C!\n over pickNextRef execute\n 0 swap picked + C!\n endif\n endif\n drop ;\n\ncreate solution_count 0 ,\n\n: solution\n solution_count @ 1+ dup solution_count !\n .\" --- Solution \" . .\" ---\" CR\n size 0 do\n a i cells + @ .\n i 3 mod 2 = if CR endif\n loop ;\n\n: pickNext\n dup .\" pickNext \" .\n dup size 1- = if\n drop .\" -> solution\" CR solution exit\n endif\n dup width wm * >= if\n wm -\n else\n dup width dup 2 - * >= if\n width + .\" -> pickBottom \" dup . CR pickBottom exit\n else\n 1+\n endif\n endif\n dup width mod wm = if\n .\" -> pickRight \" dup . CR pickRight\n else\n .\" -> pickInternal \" dup . CR pickInternal\n endif ;\n\n' pickNext TO pickNextRef\n\n: initBoard\n 9 0 do\n i 1+ a i cells + !\n loop ;\n\n: solve-puzzle\n clearPicked initBoard 0 solution_count !\n 0 pickInternal ;\n","old_contents":"","returncode":1,"stderr":"error: pathspec 'magic-puzzle\/magic-puzzle.fth' did not match any file(s) known to git\n","license":"unlicense","lang":"Forth"} {"commit":"68d37a74b76b8b6d95e9790866111fb468a2bc85","subject":"forthlet: disassembler","message":"forthlet: disassembler\n","repos":"crcx\/rx-nga,crcx\/rx-nga,crcx\/rx-nga,crcx\/rx-nga","old_file":"forthlets\/disassemble.forth","new_file":"forthlets\/disassemble.forth","new_contents":"","old_contents":"","returncode":128,"stderr":"remote: Support for password authentication was removed on August 13, 2021.\nremote: Please see https:\/\/docs.github.com\/en\/get-started\/getting-started-with-git\/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.\nfatal: Authentication failed for 'https:\/\/github.com\/crcx\/rx-nga.git\/'\n","license":"isc","lang":"Forth"} {"commit":"0f30180f7ebb3425f2968cf1c66b6d125a3d195d","subject":"Fix WHEN and UNLESS. Add SQUARE, SUM, and AREA.","message":"Fix WHEN and UNLESS. Add SQUARE, SUM, and AREA.\n","repos":"SamSkulls\/filth","old_file":"stdlib.fth","new_file":"stdlib.fth","new_contents":"","old_contents":"","returncode":128,"stderr":"remote: Support for password authentication was removed on August 13, 2021.\nremote: Please see https:\/\/docs.github.com\/en\/get-started\/getting-started-with-git\/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.\nfatal: Authentication failed for 'https:\/\/github.com\/SamSkulls\/filth.git\/'\n","license":"mit","lang":"Forth"} {"commit":"299e172f61c1b1d4d88fba51adb9c6811c914d87","subject":"missing file for interrupt support","message":"missing file for interrupt support","repos":"cetic\/python-msp430-tools,cetic\/python-msp430-tools,cetic\/python-msp430-tools","old_file":"msp430\/asm\/forth\/_interrupts.forth","new_file":"msp430\/asm\/forth\/_interrupts.forth","new_contents":"( Words to work with interrupts.\n\n vi:ft=forth\n)\n\n( Example:\n PORT1_VECTOR INTERRUPT handler_name\n WAKEUP\n 0 P1IFG C!\n END-INTERRUPT\n\n - Words defined with INTERRUPT must not be called from user code.\n)\n\n( Interrupts save the MSP430 context [registers] on the data stack. This is no\n problem as an interrupt handler can work with values that have been on the\n stack and it must be stack balanced itself.\n)\n\n( The word INTERRUPT generates an entry code block specific for each interrupt.\n sub \\x23 4, RTOS ; prepare to push 2 values on return stack\n mov IP, 2[RTOS] ; save IP on return stack\n mov SP, 0[RTOS] ; save SP pointer on return stack it points to SR on stack\n mov #XXX, IP ; Move address of thread of interrupt handler in IP\n mov @IP+, PC ; NEXT\n)\n\n( Entering an interrupt handler )\nCODE DO-INTERRUPT ( R: - int-sys )\n .\" \\t ; save registers\\n \"\n .\" \\t push R6\\n \"\n .\" \\t push R7\\n \"\n .\" \\t push R8\\n \"\n .\" \\t push R9\\n \"\n .\" \\t push R10\\n \"\n .\" \\t push R11\\n \"\n .\" \\t push R12\\n \"\n .\" \\t push R13\\n \"\n .\" \\t push R14\\n \"\n .\" \\t push R15\\n \"\n ASM-NEXT\nEND-CODE\n\n( Restore state at exit of interrupt handler )\nCODE EXIT-INTERRUPT ( R: int-sys - )\n .\" \\t ; restore registers\\n \"\n .\" \\t pop R15\\n \"\n .\" \\t pop R14\\n \"\n .\" \\t pop R13\\n \"\n .\" \\t pop R12\\n \"\n .\" \\t pop R11\\n \"\n .\" \\t pop R10\\n \"\n .\" \\t pop R9\\n \"\n .\" \\t pop R8\\n \"\n .\" \\t pop R7\\n \"\n .\" \\t pop R6\\n \"\n .\" \\t incd RTOS ; forget about pointer to SR on stack \\n \"\n .\" \\t mov @RTOS+, IP \\t; get last position from return stack \\n \"\n .\" \\t reti\\n \"\nEND-CODE\n\n( Patch the saved status register so that LPM modes are exit after the\n interrupt handler is finished.\n\n Only allowed in INTERRUPT definition. Not in called functions.\n May be called multiple times.\n)\nCODE WAKEUP ( R: int-sys - int-sys )\n .\" \\t mov @RTOS, W \\t; read pointer to SR\\n \"\n .\" \\t bic \\x23 LPM4, 0(W) \\t; patch SR on stack\\n \"\n ASM-NEXT\nEND-CODE\n\n","old_contents":"","returncode":1,"stderr":"error: pathspec 'msp430\/asm\/forth\/_interrupts.forth' did not match any file(s) known to git\n","license":"bsd-3-clause","lang":"Forth"} {"commit":"7167d9744b2b4d570c4c19605fa836f8c76a7fc9","subject":"Stripped-down start cortex.","message":"Stripped-down start cortex.","repos":"rbsexton\/gecko,rbsexton\/gecko,rbsexton\/gecko","old_file":"leopard\/usbforth\/StartCortexThread.fth","new_file":"leopard\/usbforth\/StartCortexThread.fth","new_contents":"\\ StartCortexThread.fth - generic Cortex startup code\r\n\\ Stripped down version of MPE version.\r\n\\ The supervisor does most of the important work.\r\n\\ so StartCortex is simpler.\r\n\r\n\r\nonly forth definitions decimal\r\n\r\n\\ ===========\r\n\\ *! initcortex\r\n\\ *T Generic Cortex start up\r\n\\ ===========\r\n\r\nl: ExcVecs\t\\ -- addr ; start of vector table\r\n\\ *G The exception vector table is *\\fo{\/ExcVecs} bytes long. The\r\n\\ ** equate is defined in the control file.\r\n \/ExcVecs allot&erase\r\n\r\ninterpreter\r\n: SetExcVec\t\\ addr exc# --\r\n\\ *G Set the given exception vector number to the given address.\r\n\\ ** Note that for vectors other than 0, the Thumb bit is forced\r\n\\ ** to 1.\r\n dup if\t\t\t\t\\ If not the stack top\r\n swap 1 or swap\t\t\t\\ set the Thumb bit\r\n endif\r\n cells ExcVecs + ! ;\r\ntarget\r\n\r\nL: CLD1\t\t\\ holds xt of main word\r\n 0 ,\t\t\t\t\t\\ fixed by MAKE-TURNKEY\r\n\r\n\\ Calculate the initial value for the data stack pointer.\r\n\\ We allow for TOS being in a register and guard space.\r\n\r\n[undefined] sp-guard [if]\t\t\\ if no guard value is set\r\n0 equ sp-guard\r\n[then]\r\n\r\ninit-s0 tos-cached? sp-guard + cells -\r\n equ real-init-s0\t\\ -- addr\r\n\\ The data stack pointer set at start up.\r\n\r\ninternal\r\n: StartCortex\t\\ -- ; never exits\r\n\\ *G Set up the Forth registers and start Forth. Other primary\r\n\\ ** hardware initialisation can also be performed here.\r\n begin\r\n \\ INT_STACK_TOP SP_main sys! \\ set SP_main for interrupts - we don't own it.\r\n \\ INIT-R0 SP_process sys!\t \\ set SP_process for tasks - the loader will do this.\r\n \\ 2 control sys!\t\t\t \\ switch to SP_process - handled by the loader. \r\n REAL-INIT-S0 set-sp\t\t\t \\ Allow for cached TOS and guard space\r\n INIT-U0 up!\t\t\t\t\\ USER area\r\n CLD1 @ execute\r\n again\r\n;\r\nexternal\r\n\r\nINIT-R0 StackVec# SetExcVec\t\\ Define initial return stack\r\n' StartCortex ResetVec# SetExcVec\t\\ Define startup word\r\n\r\n\\ ------------------------------------------\r\n\\ reset values for user and system variables\r\n\\ ------------------------------------------\r\nL: USER-RESET\r\n init-s0 tos-cached? sp-guard + cells - ,\t\\ s0\r\n init-r0 ,\t\t\t\t\\ r0\r\n 0 , 0 , \\ #tib, 'tib\r\n 0 , 0 , \\ >in, out\r\n $0A , 0 , \\ base, hld\r\n\r\n\\ initial values of system variables\r\nL: INIT-FENCE 0 , \\ fence\r\nL: INIT-DP 0 , \\ dp\r\nL: INIT-VOC-LINK 0 , \\ voc-link\r\n\r\n\\ ======\r\n\\ *> ###\r\n\\ ======\r\n\r\ndecimal\r\n\r\n","old_contents":"","returncode":1,"stderr":"error: pathspec 'leopard\/usbforth\/StartCortexThread.fth' did not match any file(s) known to git\n","license":"mit","lang":"Forth"} {"commit":"ffb473719c09143dcdf20e915d561ad314a419dc","subject":"Added screen file with high level definitions of Core.","message":"Added screen file with high level definitions of Core.\n","repos":"hth313\/hthforth","old_file":"src\/lib\/core.fth","new_file":"src\/lib\/core.fth","new_contents":"( block 100 )\n\n: NIP ( n1 n2 -- n2) SWAP DROP ;\n: 2DROP DROP DROP ;\n: 2DUP OVER OVER ;\n: ?DUP DUP IF DUP THEN ;\n\n: 1+ 1 + ;\n: 1- 1 - ;\n: INVERT -1 XOR ;\n: NEGATE INVERT 1+ ;\n: ABS DUP 0< IF NEGATE THEN ;\n( shadow 100 )\n( block 101 )\n( shadow 101 )\n( block 102 )\n\n( shadow 102 )\n( block 103 )\n( shadow 103 )\n( block 104 )\n( shadow 104 )\n( block 105 interpreter )\n\nCREATE _INPUT-BUFFER 80 CHARS ALLOT ( may do this internally? )\n\n: EVALUATE >IN @ >R 0 >IN ! SOURCE >R >R #IN 2! _INTERPRET\n R> R> #IN 2! R> >IN ! ;\n\n: QUIT _RESET-RSTACK\n BEGIN\n BEGIN\n\t _READ-LINE 0 >IN ! _INPUT-BUFFER 0 EVALUATE CR\n\t STATE @\n UNTIL .\" ok \" ( exhausted input in interpretation mode )\n AGAIN ;\n\n ( shadow 105 )\n( block 106 )\n( shadow 106 )\n( block 107 )\n( shadow 107 )\n( block 108 )\n( shadow 108 )\n( block 109 )\n( shadow 109 )\n( block 110 compiler )\n\n: VARIABLE CREATE 1 CELLS ALLOT ;\n\nVARIABLE STATE ( compilation state variable )\n0 STATE ! ( interpreting by default )\n: [ FALSE STATE ! ;\n: ] TRUE STATE ! ;\n\n( Colon definitions )\n: : CREATE ] ;\n: ; POSTPONE EXIT SMUDGE [ ; IMMEDIATE\n\n( shadow 110 )\n( block 111 )\n( shadow 111 )\n( block 112 )\n( shadow 112 )\n","old_contents":"","returncode":1,"stderr":"error: pathspec 'src\/lib\/core.fth' did not match any file(s) known to git\n","license":"bsd-2-clause","lang":"Forth"} {"commit":"c8005f2bc02112f95361357df926c9203b8160b4","subject":"Adds congruentp.","message":"Adds congruentp.\n","repos":"SamSkulls\/filth","old_file":"stdlib.fth","new_file":"stdlib.fth","new_contents":"","old_contents":"","returncode":128,"stderr":"remote: Support for password authentication was removed on August 13, 2021.\nremote: Please see https:\/\/docs.github.com\/en\/get-started\/getting-started-with-git\/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.\nfatal: Authentication failed for 'https:\/\/github.com\/SamSkulls\/filth.git\/'\n","license":"mit","lang":"Forth"} {"commit":"fed1bf2a43c766315d826e2da3ff9ffc66e2cd69","subject":"Level 1 driver with support for auto-pause.","message":"Level 1 driver with support for auto-pause.","repos":"rbsexton\/sockpuppet,rbsexton\/sockpuppet","old_file":"forth\/serCM3_SAPI-level1.fth","new_file":"forth\/serCM3_SAPI-level1.fth","new_contents":"\\ serCM3_sapi_level1.fth - SAPI polled RX, polled TX, serial communication drivers\n\\ with support for blocking IO.\n\\ Written to run against the SockPuppet API.\n\n\\ Level 1 support. Requires TASKING. System calls request blocking.\n\\ KEY requires blocking, so that must be implemented here.\n\n\\ Copyright (c) 2017, Robert Sexton. All rights reserved.\n\\ Covered by the terms of the supplied Licence.txt file\n\nonly forth definitions\n\n\\ ==============\n\\ *T SAPI polled serial driver\n\\ ==============\n\\ *P This driver provides polled serial comms for Cortex-M3 CPUs\n\\ ** using the internal UARTs via the SAPI call layer. This is \n\\ ** The simplest implementation level.\n\\ ** It doesn't use the CR or TYPE calls, but rather emulates them.\n\n\\ ****************\n\\ *S Configuration\n\\ ****************\n\\ *P Configuration is managed by the SAPI\n\ntarget\n\n\\ ********************\n\\ *S Serial primitives\n\\ ********************\ninternal\n\n: +FaultConsole\t( -- ) ;\n\\ *G Because this is a polled driver, *\\fo{+FaultConsole} for\n\\ ** fault handling is a *\\fo{NOOP}. See *\\i{Cortex\/FaultCortex.fth}\n\\ ** for more details.\n\ntarget\n\n\\ CODE (seremitfc)\t\\ char base --\n\\ This is a system call.\n\n: (seremit)\t\\ char base -- \n\\ *G Wrapped call that checks for throttling, and if so,\n\\ calls PAUSE to let another task run, or just does a WFI if no multitasker.\n\\ The only interesting thing is failure, or -1. That means retry.\n (seremitfc) if pause then \n\t;\n\n: (sertype) \\ caddr len base --\n\\ *G Transmit a string on the given UART.\n -rot bounds\n ?do i c@ over (seremit) loop\n drop\n;\n\n: (sercr)\t\\ base --\n\\ *G Transmit a CR\/LF pair on the given UART.\n $0D over (seremit) $0A swap (seremit)\n;\n\n: (serkey) \\ base -- c\n\\ *G Get a character from the port. Retry until we get it.\n\\ See if its negative. If so, discard it and leave false to re-loop.\n\\ If not negative, leave true on the stack to exit.\n begin \\ base ret t\/f \n\tdup (serkeyfc) dup 0 < \\ base ret t\/f \n\t IF [ tasking? ] [if] PAUSE [else] [asm wfi asm] [then] drop false \n\t ELSE true \n\t THEN \\ base ret t\/f \n\tuntil \\ base ret \n\tswap drop \n;\n\n\\ THis is a system call.\n\\ CODE (serkey?) \\ base -- t\/f\n\\ *G Return true if the given UART has a character avilable to read.\n\nexternal \n\n: seremit0\t\\ char --\n\\ *G Transmit a character on UART0.\n 0 (seremit) ;\n: sertype0\t\\ c-addr len --\n\\ *G Transmit a string on UART0.\n 0 (sertype) ;\n: sercr0\t\\ --\n\\ *G Issue a CR\/LF pair to UART0.\n 0 (sercr) ;\n: serkey?0\t\\ -- flag\n\\ *G Return true if UART0 has a character available.\n 0 (serkey?) ;\n: serkey0\t\\ -- char\n\\ *G Wait for a character on UART0.\n 0 (serkey) ;\ncreate Console0\t\\ -- addr ; OUT managed by upper driver\n\\ *G Generic I\/O device for UART0.\n ' serkey0 ,\t\t\\ -- char ; receive char\n ' serkey?0 ,\t\t\\ -- flag ; check receive char\n ' seremit0 ,\t\t\\ -- char ; display char\n ' sertype0 ,\t\t\\ caddr len -- ; display string\n ' sercr0 ,\t\t\\ -- ; display new line\n\n\\ Non-UARTs.\n: seremit10 #10 (seremit) ;\n: sertype10\t#10 (sertype) ;\n: sercr10\t#10 (sercr) ;\n: serkey?10\t#10 (serkey?) ;\n: serkey10\t#10 (serkey) ;\ncreate Console10 ' serkey10 , ' serkey?10 , ' seremit10 , ' sertype10 , ' sercr10 ,\t\n\nconsole-port 0 = [if]\n console0 constant console\n\\ *G *\\fo{CONSOLE} is the device used by the Forth system for interaction.\n\\ ** It may be changed by one of the phrases of the form:\n\\ *C dup opvec ! ipvec !\n\\ *C SetConsole\n[then]\n\nconsole-port #10 = [if]\n console10 constant console\n[then]\n\n\\ ************************\n\\ *S System initialisation\n\\ ************************\n\n\\ This is a NOP in the SAPI environment\n: init-ser ;\t\\ --\n\\ *G Initialise all serial ports\n\n\\ ======\n\\ *> ###\n\\ ======\n\ndecimal\n","old_contents":"","returncode":1,"stderr":"error: pathspec 'forth\/serCM3_SAPI-level1.fth' did not match any file(s) known to git\n","license":"bsd-2-clause","lang":"Forth"} {"commit":"9ebdae3452b45646465468667e683eb07d7b040c","subject":"logto: add logto.fth to broken\/","message":"logto: add logto.fth to broken\/\n\nWork in progress.\n","repos":"philburk\/hmsl,philburk\/hmsl,philburk\/hmsl","old_file":"hmsl\/broken\/logto.fth","new_file":"hmsl\/broken\/logto.fth","new_contents":"\\ Send output to a file or device.\n\\\n\\ You can send to the printer with LOGTO PRT:\n\\\n\\ Author: Phil Burk\n\\ Copyright 1990 Phil Burk\n\\\n\\ MOD: PLB 12\/28\/86 Add filtering of CRs.\n\\ MOD: PLB 9\/9\/88 Add IF.FORGOTTEN , SAVE-FORTH fix.\n\\ MOD: PLB 1\/21\/89 Add PRINTER.ON, some reorganization\n\\ MOD: PLB 4\/3\/90 Converted to Mac HMSL\n\nANEW TASK-LOGTO\n\ndecimal\n\\ Provide a log of the output to a file.\nvariable LOGTO-ID\nvariable LOGTO-OLDTYPE\nvariable LOGTO-OLDCR\n\ndecimal\n\n: LOGGED? ( -- flag )\n logto-oldtype @ 0= 0=\n;\n\n: ( -- , Stop logging files )\n logged?\n IF logto-oldtype @ is type\n logto-oldtype off\n logto-oldcr @ is cr\n THEN\n;\n\n: FLOGTYPE ( addr count-- , send chars to console, if appropriate )\n logto-id @ -rot\n dup>r fwrite r> -\n IF \n .\" FLOGtype failed to write buffer; recommend LOGEND\" abort\n THEN\n;\n\n: FLOGCR ( -- , send carriage return )\n logto-id @ $ 0D femit\n;\n\n: LOGTO&TYPE ( addr count -- , send to both file and screen )\n 2dup logto-oldtype @execute\n flogtype\n;\n\n: LOGTO&CR ( -- )\n logto-oldcr @ execute\n flogcr\n;\n\n: LOGSTART ( -- , Start logging characters )\n LOGGED?\n IF .\" can't LOGSTART, already logged.\" cr\n ELSE what's type logto-oldtype ! ( save old cfa )\n ' logto&type is type ( set vector )\n what's cr logto-oldcr !\n ' logto&cr is cr\n THEN\n;\n\n: $LOGTO ( $filename -- , Open file and log characters to it. )\n logto-id @ 0=\n IF new $FOPEN ?dup\n IF logto-id ! logstart\n ELSE .\" Could not be opened!\" cr abort\n THEN\n ELSE .\" Can't LOGTO \" $type .\" , already logged.\"\n THEN\n;\n\n: LOGTO ( --IN-- , Log characters to a file. )\n fileword $logto\n;\n\n: LOGSTOP ( -- , temporarily stop logging )\n logged?\n IF \n THEN\n;\n\n: ( -- , used internally )\n cr logstop\n logto-id @ fclose\n logto-id off\n;\n\n: LOGEND ( -- . terminate logto, close file )\n logto-id @\n IF \n ELSE .\" Can't LOGEND, not logged!\" cr\n THEN\n;\n\n: LOGTERM ( -- , used internally for cleanup )\n logto-id @\n IF .\" Turning off LOGTO !!!\" cr\n \n THEN\n;\n\ndecimal\nif.forgotten logterm\n\n: AUTO.TERM logterm auto.term ;\n","old_contents":"","returncode":1,"stderr":"error: pathspec 'hmsl\/broken\/logto.fth' did not match any file(s) known to git\n","license":"apache-2.0","lang":"Forth"}