### Install Gforth from Source, Tarball, Debian/Ubuntu, Snap, Flatpak, or Docker Source: https://context7.com/git/gforth/llms.txt Provides commands for installing Gforth using various methods including git, tarball, package managers, Snap, Flatpak, and Docker. Includes steps for building from source and starting the interpreter. ```bash # --- From git --- git clone https://git.savannah.gnu.org/git/gforth.git cd gforth source ./install-deps.sh # installs build dependencies ./BUILD-FROM-SCRATCH sudo make install # --- From tarball --- wget https://www.complang.tuwien.ac.at/forth/gforth/Snapshots/current/gforth.tar.xz tar xfJ gforth.tar.xz cd gforth-* BUILD_FROM=tarball source ./install-deps.sh ./configure make sudo make install # --- Debian/Ubuntu package --- apt install apt-transport-https cat >/etc/apt/sources.list.d/net2o.list < switch for cross-compiling, which disables incompatible features and sources a configuration file from a specified subdirectory. ```bash ./configure --with-cross= ``` -------------------------------- ### Add Net2o Flatpak Repository Source: https://github.com/git/gforth/blob/master/INSTALL.md Add the net2o Flatpak repository to your system. This enables the installation of Gforth via Flatpak. ```shell flatpak remote-add --if-not-exists net2o https://flathub.net2o.net/repo/net2o.flatpakrepo ``` -------------------------------- ### Configure Net2o Debian Repository Source: https://github.com/git/gforth/blob/master/INSTALL.md Create a sources.list file to point to the net2o Debian repository. This allows apt to find and install Gforth packages. ```shell cat >/etc/apt/sources.list.d/net2o.list < 25 \ Recursive word : factorial ( n -- n! ) dup 0= IF drop 1 EXIT THEN dup 1- recurse * ; 10 factorial . \ -> 3628800 \ Looping: DO...LOOP : countdown ( n -- ) 0 DO I . LOOP ; 5 countdown \ -> 4 3 2 1 0 \ Looping: BEGIN...WHILE...REPEAT : sum-to ( n -- sum ) 0 swap \ sum counter BEGIN dup 0> WHILE dup rot + swap 1- REPEAT drop ; 10 sum-to . \ -> 55 \ Looping: BEGIN...UNTIL : count-down-to-zero ( n -- ) BEGIN dup . 1- dup 0= UNTIL drop ; 5 count-down-to-zero \ -> 5 4 3 2 1 \ String output : greet ( -- ) ." Hello, Gforth!" cr ; greet \ -> Hello, Gforth! ``` -------------------------------- ### Install apt-transport-https for Debian Source: https://github.com/git/gforth/blob/master/INSTALL.md Ensure that apt can use the HTTPS transport protocol for accessing repositories. This is a prerequisite for adding external repositories. ```shell apt install apt-transport-https ``` -------------------------------- ### Mount Host Directory for Gforth Source: https://github.com/git/gforth/blob/master/docker/runner/README.md Runs Gforth in a container, mounting the current host directory (/work) to access files. This example shows executing a Forth script from the mounted directory. ```shell cat $(pwd)/test.fs .( huhu ) ``` ```shell docker run -ti --rm -v$(pwd):/work forthy42/gforth s" /work/test.fs" included huhu ok bye ``` -------------------------------- ### Gforth Cooperative Multitasking with Tasks Source: https://context7.com/git/gforth/llms.txt Implements a cooperative round-robin multitasker. Use 'NewTask' to create tasks, 'activate' or 'pass' to start them, and 'pause' to yield control. Requires 'tasker.fs'. ```Forth require tasker.fs \ Define task behavior : producer-loop ( -- ) BEGIN ." Producing... " cr pause \ yield to other tasks AGAIN ; : consumer-loop ( -- ) BEGIN ." Consuming... " cr pause AGAIN ; \ Create tasks (stacksize in cells) $200 NewTask Constant producer $200 NewTask Constant consumer \ Activate with the word to run producer ' producer-loop activate consumer ' consumer-loop activate \ Run the scheduler (main task becomes a participant) : run-for ( n -- ) 0 DO pause \ main task yields, others run LOOP ; 10 run-for \ interleaves producer and consumer 10 times \ Passing data to a task on startup : worker ( x -- ) . cr \ print the value passed in stop ; \ suspend self $200 NewTask Constant w1 1 1 w1 pass \ pass 1 item (value=1) to w1 and activate it pause \ let w1 run -> prints 1 \ Kill a task w1 kill ``` -------------------------------- ### Gforth GUI Flatpak Alias Source: https://github.com/git/gforth/blob/master/INSTALL.md Create a shell alias for running the Gforth GUI application when installed via Flatpak. This configures necessary sockets and devices. ```shell alias gforth-gui="flatpak run --socket=x11 --device=dri --socket=pulseaudio --filesystem=$PWD org.gforth.gforth" ``` -------------------------------- ### Gforth C-Library Definition Example Source: https://github.com/git/gforth/blob/master/distros/ReadMe.md This snippet shows the definition of a C-library within Gforth, specifically for 'cstr'. This is part of the process that may encounter errors. ```gforth c-library cstr cstr cstr a n n -- a ( c-addr u fclear -- c-addr2 ) end-c-library ``` -------------------------------- ### Run Interactive Gforth Session Source: https://github.com/git/gforth/blob/master/docker/runner/README.md Starts an interactive Gforth session inside a Docker container. The container is removed automatically upon exit (--rm). ```shell docker run -ti --rm forthy42/gforth ``` -------------------------------- ### Gforth Flatpak Terminal Alias Source: https://github.com/git/gforth/blob/master/INSTALL.md Create a shell alias for running Gforth from the terminal when installed via Flatpak. This ensures correct path handling. ```shell alias gforth="flatpak run --filesystem=$PWD org.gforth.gforth" ``` -------------------------------- ### Define Identifier Pattern with regexp.fs Source: https://context7.com/git/gforth/llms.txt Implement an identifier pattern matcher starting with a letter, followed by letters or digits, using character classes and repetition. ```Forth \ Identifier: letter followed by letters/digits : identifier? ( addr u -- addr' flag ) !end \D \ wait, use letter class instead letter c? BEGIN, FORK letter c? JOIN FORK \d JOIN DONE, true ; ``` -------------------------------- ### Run Gforth with Specific User ID Source: https://github.com/git/gforth/blob/master/docker/runner/README.md Executes Gforth within a container, specifying the host user's ID to ensure correct file permissions. This example runs a system command to display the user ID inside the container. ```shell id -u ``` ```shell docker run -ti --rm --user $(id -u) forthy42/gforth s" id -u" system uid=$(id -u) ok bye ``` -------------------------------- ### Configure for MacOS X Core 2 (64-bit) Source: https://github.com/git/gforth/blob/master/INSTALL.md For improved performance on MacOS X Core 2 processors, enable the 64-bit version by specifying the architecture and build type during configuration. ```bash ./configure CC='gcc-4.2 -arch x86_64' --build=x86_64-apple-darwin9.4.0 ``` -------------------------------- ### Gforth File I/O: Position and Seek Source: https://context7.com/git/gforth/llms.txt Demonstrates repositioning the file pointer using `reposition-file`, and checking current position and file size. ```Forth \ File position and seek s" seek-test.txt" r/w open-file throw Constant fid 100 0 fid reposition-file throw \ seek to byte 100 fid file-position throw d. ." position" cr fid file-size throw d. ." size" cr fid close-file throw ``` -------------------------------- ### Gforth Interactive REPL and Basic Arithmetic Source: https://context7.com/git/gforth/llms.txt Demonstrates basic integer arithmetic, stack manipulation, bitwise operations, and comparisons within the Gforth interactive interpreter. Stack comments use `( before -- after )` notation. ```forth \ Start gforth and try basic operations gforth \ Integer arithmetic (postfix / RPN) 2 3 + . \ -> 5 10 3 - . \ -> 7 6 7 * . \ -> 42 17 5 / . \ -> 3 (integer division) 17 5 mod . \ -> 2 17 5 /mod . . \ -> 3 2 (quotient and remainder) \ Stack manipulation 1 2 3 .s \ <3> 1 2 3 (shows stack, top on right) dup .s \ <4> 1 2 3 3 drop .s \ <3> 1 2 3 swap .s \ <3> 1 3 2 over .s \ <4> 1 3 2 3 rot .s \ <4> 1 2 3 1 (bring third item to top) nip .s \ <3> 1 2 1 \ Bitwise operations %1010 %0110 and . \ -> 2 %1010 %0110 or . \ -> 14 %1010 %0110 xor . \ -> 12 $FF invert . \ -> -256 (bitwise NOT, cell-sized) \ Comparisons (return -1 for true, 0 for false) 3 4 < . \ -> -1 (true) 3 3 = . \ -> -1 (true) 3 4 > . \ -> 0 (false) \ Conditional : max2 ( a b -- max ) 2dup < IF nip ELSE drop THEN ; 5 3 max2 . \ -> 5 3 5 max2 . \ -> 5 bye \ exit gforth ``` -------------------------------- ### Define and Use a Class with Inheritance and Interfaces in Gforth Source: https://context7.com/git/gforth/llms.txt Demonstrates defining a base class, a subclass, implementing virtual methods, and adding interface support. Ensure 'struct.fs' and 'objects.fs' are required. ```Forth require struct.fs require objects.fs \ Define a base class object% subclass shape% cell% field shape-color selector draw ( shape -- ) selector area ( shape -- n ) end-class \ Define a subclass: rectangle shape% subclass rect% cell% field rect-w cell% field rect-h end-class \ Implement draw for rect% :noname ( shape -- ) ." Rectangle " dup rect-w @ . ." x " rect-h @ . cr ; rect% overrides draw \ Implement area for rect% :noname ( shape -- n ) dup rect-w @ swap rect-h @ * ; rect% overrides area \ Create an instance rect% %alloc Constant r1 0 r1 shape-color ! 10 r1 rect-w ! 5 r1 rect-h ! r1 draw \ -> Rectangle 10 x 5 r1 area . \ -> 50 \ Interface example interface selector describe ( obj -- ) end-interface printable \ Make rect% implement printable printable rect% add-interface :noname ( obj -- ) ." I am a shape of color " shape-color @ . cr ; rect% printable :: describe overrides r1 describe \ -> I am a shape of color 0 r1 free throw ``` -------------------------------- ### Configure with Additional Compiler Flags Source: https://github.com/git/gforth/blob/master/INSTALL.md Pass additional options to the compiler, such as target architecture flags, during configuration. ```bash ./configure CC="gcc -b i486-linuxaout -V 2.7.0" ``` -------------------------------- ### Build and Run Arch Linux Docker Image Source: https://github.com/git/gforth/blob/master/distros/ReadMe.md Use these commands to build a Docker image for Arch Linux with Gforth and run it interactively. This is the first step to testing compilation within an Arch environment. ```bash cd archlinux docker build --tag archlinux-gforth:latest . docker run -it --rm archlinux-gforth:latest ``` -------------------------------- ### Gforth Variables, Constants, and Values Source: https://context7.com/git/gforth/llms.txt Demonstrates the usage of `Variable`, `Constant`, `Value`, `2Variable`, and `AVariable` for memory allocation and data binding. `!` stores, `@` fetches, `+!` increments, `TO` changes values. ```Forth Variable counter 0 counter ! \ store 0 counter @ . \ -> 0 1 counter +! \ increment by 1 counter @ . \ -> 1 \ Constant 42 Constant the-answer the-answer . \ -> 42 \ Value (changeable constant) 10 Value speed speed . \ -> 10 20 TO speed speed . \ -> 20 \ 2Variable (double-cell, 64-bit on 32-bit system) 2Variable coords 1000 2000 coords 2! coords 2@ d. \ -> 1000 2000 \ AVariable (address-sized variable) AVariable myptr here myptr ! myptr @ . \ prints address of here ``` -------------------------------- ### Gforth Memory Allocation: Struct Instances on Heap Source: https://context7.com/git/gforth/llms.txt Shows how to allocate structures (`node`) on the heap using `struct.fs` and `%alloc`, and how to access fields. ```Forth \ Allocating struct instances on heap require struct.fs struct cell% field node-val cell% field node-next end-struct node% ``` ```Forth : new-node ( val -- node ) node% %alloc tuck node-val ! 0 over node-next ! ; 42 new-node Constant n1 99 new-node Constant n2 n1 n2 node-next ! \ n1 -> n2 n1 node-val @ . \ -> 42 n1 node-next @ node-val @ . \ -> 99 n1 free throw n2 free throw ``` -------------------------------- ### Decompile and Debug Forth Definitions Source: https://context7.com/git/gforth/llms.txt Shows how to decompile Forth words using 'see', list words with 'words', find definitions with 'locate', and use the debugger with 'dbg'. Requires 'debug.fs' for debugging features. ```Forth : example ( n -- n' ) dup 0= IF drop 1 ELSE dup 1- recurse * THEN ; see example words locate dup require debug.fs dbg example .s f.s r.s ' dup .name cr ' + >name name>string type cr ``` -------------------------------- ### Gforth File I/O: Slurp Entire File Source: https://context7.com/git/gforth/llms.txt Uses the `string.fs` utility to read the entire content of `/etc/hosts` into a string on the heap. ```Forth \ Slurp entire file with string.fs require string.fs 0 AValue content s" /etc/hosts" content $slurp-file content $@ type content $free ``` -------------------------------- ### Gforth Docker Aliases Source: https://github.com/git/gforth/blob/master/INSTALL.md Create aliases for running Gforth Docker containers with necessary permissions and volume mounts for GUI applications. ```bash alias gforthdk="docker run -ti --rm forthy42/gforth" ``` ```bash alias gforth-guidk="docker run -ti -e USER=$USER -e DISPLAY=$DISPLAY -v /tmp/.X11-unix/:/tmp/.X11-unix/ -v /dev/dri:/dev/dri -v /usr/share/fonts:/usr/share/fonts -v $XAUTHORITY:/home/gforth/.Xauthority -v ${XDG_RUNTIME_DIR}/pulse:/run/user/1000/pulse --rm forthy42/gforth-gui" ``` ```bash alias gforth-gui-fontsdk="docker run -ti -e USER=$USER -e DISPLAY=$DISPLAY -v /tmp/.X11-unix/:/tmp/.X11-unix/ -v /dev/dri:/dev/dri -v $XAUTHORITY:/home/gforth/.Xauthority -v ${XDG_RUNTIME_DIR}/pulse:/run/user/1000/pulse --rm forthy42/gforth-gui-fonts" ``` -------------------------------- ### Gforth Memory Allocation: Basic Source: https://context7.com/git/gforth/llms.txt Shows basic heap memory allocation using `allocate`, zeroing the memory with `fill`, and releasing it with `free`. ```Forth \ Basic allocation 1024 allocate throw Constant buf \ allocate 1024 bytes buf 1024 0 fill \ zero it ``` ```Forth \ Resize buf 2048 resize throw to buf \ grow to 2048 bytes s" hello" buf swap move \ copy string in buf free throw \ release ``` -------------------------------- ### Declare C Library Functions with libcc.fs Source: https://context7.com/git/gforth/llms.txt Use C-LIBRARY blocks to declare C functions and values. Specify type codes for arguments and return values. Ensure necessary headers are included using \\c. ```Forth require libcc.fs \ --- Example: wrapping libc math functions --- C-LIBRARY mathwrap \c #include \c #include c-function c-sqrt sqrt r -- r ( F: x -- F: sqrt(x) ) c-function c-pow pow r r -- r ( F: base exp -- F: result ) c-function c-abs abs n -- n ( n -- |n| ) c-function c-rand rand -- n ( -- n ) c-function c-puts puts a -- n ( c-str -- n ) END-C-LIBRARY 2.0e0 c-sqrt f. \ -> 1.4142135... 2.0e0 3.0e0 c-pow f. \ -> 8.0 -42 c-abs . \ -> 42 \ --- Wrapping lseek (64-bit file offset) --- C-LIBRARY posixwrap \c #include c-function c-lseek lseek n d n -- d ( fd offset whence -- result ) END-C-LIBRARY \ --- Accessing a C global value --- C-LIBRARY glibcwrap \c #include c-value c-errno errno -- n ( -- errno ) END-C-LIBRARY \ --- Adding compiler/linker flags --- C-LIBRARY customwrap s" /usr/include/mylib" add-incdir \ -I flag s" mylib" add-lib \ -lmylib \c #include c-function mylib-init mylib_init -- void c-function mylib-add mylib_add n n -- n END-C-LIBRARY \ --- Using add-cflags for extra compilation options --- C-LIBRARY flagswrap s" -O2" add-cflags \c #include c-function c-strlen strlen a -- n ( c-addr -- u ) END-C-LIBRARY s" hello" drop c-strlen . \ -> 5 ``` -------------------------------- ### Define Signed Integer Pattern with regexp.fs Source: https://context7.com/git/gforth/llms.txt Create a pattern matcher for signed integers using FORK/JOIN for optional elements and character classes. ```Forth \ Match optional sign + digits : signed-integer? ( addr u -- addr' flag ) !end FORK ` - JOIN \ optionally match '-' \d BEGIN, \d DONE, true ; ``` -------------------------------- ### Download and Extract Tarball Source: https://github.com/git/gforth/blob/master/INSTALL.md Download the latest Gforth tarball and extract it to begin the build process. ```bash wget https://www.complang.tuwien.ac.at/forth/gforth/Snapshots/current/gforth.tar.xz tar xfJ gforth.tar.xz ``` -------------------------------- ### Gforth Closures with Heap Allocation Source: https://context7.com/git/gforth/llms.txt Demonstrates creating heap-allocated closures that capture local variables. Use `free-closure` to release memory. ```Forth require closures.fs \ Heap-allocated closure: adder factory : make-adder ( n -- xt ) {: n :}h ( -- ) n + \ captures n from enclosing scope ;h ; ``` ```Forth 5 make-adder Constant add5 10 make-adder Constant add10 3 add5 execute . \ -> 8 3 add10 execute . \ -> 13 add5 free-closure add10 free-closure ``` -------------------------------- ### Minimal OOP Framework in Gforth Source: https://context7.com/git/gforth/llms.txt A self-contained micro-OOP system for defining classes, methods, and instance variables. Requires 'mini-oof.fs'. Use 'new' to allocate instances and 'defines' to set method implementations. ```Forth require mini-oof.fs \ Extend object with a Point class object class cell method getx cell method gety cell var x-field cell var y-field end-class Point \ Define the method bodies : pt-getx ( o -- n ) x-field @ ; Point ' pt-getx defines getx : pt-gety ( o -- n ) y-field @ ; Point ' pt-gety defines gety \ Subclass: ColorPoint Point class cell method getcolor cell var color-field end-class ColorPoint : cp-getcolor ( o -- color ) color-field @ ; ColorPoint ' cp-getcolor defines getcolor \ Instantiate and use Point new Constant p1 10 p1 x-field ! 20 p1 y-field ! p1 getx . \ -> 10 p1 gety . \ -> 20 ColorPoint new Constant cp1 5 cp1 x-field ! 15 cp1 y-field ! 7 cp1 color-field ! cp1 getx . \ -> 5 cp1 getcolor . \ -> 7 ``` -------------------------------- ### Configure and Make Gforth in Arch Linux Container Source: https://github.com/git/gforth/blob/master/distros/ReadMe.md Inside the Arch Linux container, configure and attempt to compile Gforth. Note that the make process may not complete successfully, but a binary might still be produced. ```bash cd gforth-0.7.3 CFLAGS='-std=gnu99' ./configure --prefix=/usr # works make PREFIX=/usr -j1 # I cannot get this to complete successfully, but we end up with a gforth binary ``` -------------------------------- ### Configure with Custom Memory Sizes Source: https://github.com/git/gforth/blob/master/INSTALL.md Adjust the sizes of Gforth's memory areas (dictionary, stacks, etc.) using the FORTHSIZES environment variable during configuration. ```bash ./configure "FORTHSIZES=--dictionary-size=1048576 --data-stack-size=16k --fp-stack-size=16K --return-stack-size=15k --locals-stack-size=14848b" ``` -------------------------------- ### Add Net2o Repository Key Source: https://github.com/git/gforth/blob/master/INSTALL.md Add the GPG key for the net2o repository to Debian's trusted key database. This verifies the authenticity of the downloaded packages. ```shell wget -O - https://net2o.de/bernd@net2o.de-yubikey.pgp.asc | apt-key add - ``` -------------------------------- ### Gforth File I/O: Reading a File Line by Line Source: https://context7.com/git/gforth/llms.txt Reads a file (`output.txt`) line by line into a buffer using `open-file` and `read-line`, then closes the file. ```Forth \ Read a file line by line s" output.txt" r/o open-file throw Constant infd 256 allocate throw Constant buf BEGIN buf 256 infd read-line throw \ flag = more data WHILE buf swap type cr REPEAT buf free throw infd close-file throw ``` -------------------------------- ### Manage Word List Search Order in Gforth Source: https://context7.com/git/gforth/llms.txt Demonstrates how to manage word list search order using vocabularies, also/previous, and get-order/set-order. Use 'also' to enter a vocabulary and 'previous' to restore the search order. ```Forth Vocabulary MyLib also MyLib definitions : helper1 ( -- ) . " MyLib helper1" cr ; : helper2 ( n -- n2 ) 2 * ; previous also MyLib helper1 5 helper2 . previous get-order .s wordlist Constant my-wl my-wl get-current my-wl set-current : secret-word . " secret" cr ; set-current s" +" my-wl search-wordlist dup IF drop ." found" ELSE drop ." not found" THEN cr s" dup" find-name dup IF name>string type cr THEN ``` -------------------------------- ### Match and Capture Digits with regexp.fs Source: https://context7.com/git/gforth/llms.txt Use regexp.fs to find and capture sequences of digits. The { } syntax is used for local variables to manage pointers. ```Forth \ Match and capture with variables : find-digits ( addr u -- matched-addr matched-u ) { addr u } addr u !end addr \ start pointer on stack \d BEGIN, \d DONE, addr - ; \ length of match ``` -------------------------------- ### Pull Gforth Docker Images Source: https://github.com/git/gforth/blob/master/INSTALL.md Use these commands to pull the different Gforth Docker images available. ```bash docker pull forthy42/gforth ``` ```bash docker pull forthy42/gforth-gui ``` ```bash docker pull forthy42/gforth-gui-fonts ``` -------------------------------- ### Gforth Memory Allocation: Persistent Copy Source: https://context7.com/git/gforth/llms.txt Demonstrates `save-mem` for creating a persistent heap copy of a string, which must be manually freed. ```Forth \ save-mem: copy a string to a persistent heap copy s" original string" save-mem \ ( addr u -- addr2 u ) heap copy 2dup type cr swap free throw ``` -------------------------------- ### Configure Custom Compiler Source: https://github.com/git/gforth/blob/master/INSTALL.md If your GCC compiler has a different name, specify it using the CC environment variable during configuration. ```bash ./configure CC=gcc-2.7.1 ``` -------------------------------- ### Define Integer Pattern Matcher with regexp.fs Source: https://context7.com/git/gforth/llms.txt Define custom Forth words for pattern matching using regexp.fs. Use operators like \d for digits and BEGIN,/DONE, for repetition. ```Forth require regexp.fs \ Define a simple integer pattern matcher : integer? ( addr u -- addr' flag ) !end \ initialize start/end pointers \d \ match one digit BEGIN, \d DONE, \ match zero or more digits true ; \ success if we reach here \ Test it s" 12345" integer? IF ." matched" ELSE ." no match" THEN cr \ -> matched s" abc" integer? IF ." matched" ELSE ." no match" THEN cr \ -> no match ``` -------------------------------- ### Gforth Dynamic String Operations Source: https://context7.com/git/gforth/llms.txt Utilizes `string.fs` for heap-allocated counted strings. Key operations include storing (`$!`), fetching (`$@`), appending (`$+!`), freeing (`$free`), slurping files (`$slurp-file`), and managing string arrays (`$[]`). Output redirection to strings is possible with `$exec`, and temporary strings with `$tmp`. ```Forth require string.fs \ Basic string operations 0 AValue mystr \ create a variable to hold the string handle s" Hello" mystr $! \ store string mystr $@ type cr \ -> Hello s" , World!" mystr $+! \ append mystr $@ type cr \ -> Hello, World! mystr $@len . \ -> 13 (length) mystr $free \ release memory ``` ```Forth \ Slurp a file into a string 0 AValue file-contents s" /etc/hostname" file-contents $slurp-file file-contents $@ type cr \ prints hostname file-contents $free ``` ```Forth \ String arrays 0 AValue lines s" /etc/hostname" lines $[]slurp-file \ read line by line lines $[]# . \ number of lines 0 lines $[]@ type cr \ first line lines $[]free \ free all strings and array ``` ```Forth \ $exec: redirect TYPE/EMIT output into a string 0 AValue result [: ." the answer is " 42 . ;] result $exec result $@ type cr \ -> "the answer is 42 " result $free ``` ```Forth \ $tmp: temporary string (auto-freed on next $tmp call) [: ." temp value: " 99 . ;] $tmp type cr \ -> temp value: 99 ``` ```Forth \ String overwrite at offset 0 AValue buf s" Hello World" buf $! s" Forth" 6 buf $over \ overwrite at offset 6 buf $@ type cr \ -> Hello Forth ``` ```Forth \ $. shortcut s" Quick print" mystr $! mystr $. \ -> Quick print mystr $free ``` -------------------------------- ### Gforth File I/O: Binary Read Source: https://context7.com/git/gforth/llms.txt Performs a binary read from `data.bin` into an allocated buffer using `read-file` and then closes the file. ```Forth \ Binary read s" data.bin" r/o bin open-file throw Constant binfd 1024 allocate throw Constant data data 1024 binfd read-file throw Constant bytes-read bytes-read . ." bytes read" cr binfd close-file throw data free throw ``` -------------------------------- ### Clone Gforth Repository Source: https://github.com/git/gforth/blob/master/INSTALL.md Use this command to clone the Gforth source code from its official Savannah repository. ```bash git clone https://git.savannah.gnu.org/git/gforth.git ``` -------------------------------- ### Add INFOPATH Environment Variable Source: https://github.com/git/gforth/blob/master/INSTALL.md Configure the INFOPATH environment variable to include Gforth's info files. This is typically done in /etc/profile. ```shell INFOPATH=/usr/local/info:/usr/info ``` -------------------------------- ### Gforth Typed Local Variables Source: https://context7.com/git/gforth/llms.txt Illustrates Gforth's local variables using `{ ... }` syntax from `glocals.fs`. Supports type specifiers like `W:`, `W^`, `D:`, `F:`, `C:` and zero-initialization with `|`. ```Forth require glocals.fs \ Basic cell locals : hypotenuse ( a b -- c ) { a b } a a * b b * + sqrt f>s ; \ Mixed cell and float locals : linear ( F: m x b -- F: y ) \ computes y = m*x + b { F: m F: x F: b } m x f* b f+ ; \ Complex number multiplication : CX* ( F: Ar Ai Br Bi -- F: Cr Ci ) { F: Ar F: Ai F: Br F: Bi } Ar Br f* Ai Bi f* f- Ar Bi f* Ai Br f* f+ ; \ Address locals for output parameters : swap-cells ( a b -- b a ) { W^ out1 W^ out2 } \ out1 and out2 hold the values by address out2 @ out1 @ \ fetch original values out1 ! out2 ! ; \ Zero-initialized locals after | : accumulate ( n -- sum ) { n | sum } \ sum starts as 0 n 0 DO I sum + to sum LOOP sum ; 5 accumulate . \ -> 10 (0+1+2+3+4) \ Changing a local with TO : clamp { lo hi val -- result } val lo < IF lo EXIT THEN val hi > IF hi EXIT THEN val ; 0 100 150 clamp . \ -> 100 0 100 42 clamp . \ -> 42 ``` -------------------------------- ### Update Debian Repository Data Source: https://github.com/git/gforth/blob/master/INSTALL.md Refresh the local package index to include packages from the newly added net2o repository. ```shell apt update ``` -------------------------------- ### Gforth Structured Exception Handling Source: https://context7.com/git/gforth/llms.txt Demonstrates Gforth's `try`/`restore`/`endtry` and `try`/`iferror`/`then` constructs for structured exception handling. The `restore` clause executes regardless of exceptions, similar to a finally block, while `iferror` executes only when an exception occurs. Non-zero thrown values are error codes; negative values are standard ANS Forth exception codes. ```Forth \ Standard catch/throw : safe-divide ( a b -- quotient | 0 on error ) ['] / catch IF drop drop 0 \ on error: clean stack, return 0 THEN ; 10 2 safe-divide . \ -> 5 10 0 safe-divide . \ -> 0 ``` ```Forth \ Gforth structured: try...restore...endtry : with-resource ( -- ) open-resource \ hypothetical try do-work 0 \ no exception restore \ always executed (like "finally") close-resource endtry throw ; \ re-throw if error occurred ``` ```Forth \ try...iferror...then : parse-number ( addr u -- n true | false ) 0 0 2swap try >number drop 2drop true 0 \ success: no exception iferror 2drop 2drop false then endtry-iferror ; \ end region and enter handler ``` ```Forth \ User-defined exception s" division by zero" exception Constant err/divzero : checked-/ ( a b -- a/b ) dup 0= IF err/divzero throw THEN / ; : test-exception ( -- ) try 10 0 checked-/ 0 iferror dup err/divzero = IF drop ." Caught: division by zero" cr ELSE throw \ re-throw unknown errors THEN then endtry-iferror ; test-exception \ -> Caught: division by zero ``` ```Forth \ nothrow: signal that the next throw records a fresh backtrace ['] risky-operation catch nothrow ``` -------------------------------- ### Gforth Floating-Point Operations Source: https://context7.com/git/gforth/llms.txt Covers basic IEEE 754 floating-point arithmetic using Gforth's separate floating-point stack. Float literals end with '.', and conversions between integer and float stacks are handled by `s>f`, `f>s`, or `f>d`. Includes math functions, comparisons, stack conversions, and storing floats. ```Forth \ Basic float operations 3.14159 2.0e0 f* f. \ -> 6.28318 1.0e0 2.0e0 f/ f. \ -> 0.5 1.5e0 2.5e0 f+ f. \ -> 4.0 ``` ```Forth \ Math functions 2.0e0 fsqrt f. \ -> 1.4142135... 1.0e0 fexp f. \ -> 2.7182818... 2.718281828e0 fln f. \ -> 1.0 90.0e0 pi f* 180.0e0 f/ fsin f. \ -> 1.0 (sin 90°) ``` ```Forth \ Comparisons 1.0e0 2.0e0 f< . \ -> -1 (true) 2.0e0 2.0e0 f= . \ -> -1 (true) 2.0e0 f0> . \ -> -1 (true) ``` ```Forth \ Convert between stacks 42 s>f f. \ -> 42.0 3.7e0 f>s . \ -> 3 (truncates) ``` ```Forth \ Storing floats falign fvariable myf 3.14e0 myf f! myf f@ f. \ -> 3.14 ``` ```Forth \ Float array in dictionary here 4 floats allot Constant fa 1.0e0 fa 0 floats + f! 2.0e0 fa 1 floats + f! fa 0 floats + f@ f. \ -> 1.0 ``` ```Forth \ Locals with floats require glocals.fs : quadratic ( F: a b c x -- F: result ) { F: a F: b F: c F: x } a x f* x f* b x f* f+ c f+ ; \ ax^2 + bx + c 1.0e0 -3.0e0 2.0e0 2.0e0 quadratic f. \ -> 0.0 (1*4 - 3*2 + 2) ``` -------------------------------- ### Gforth Closures Capturing Multiple Values Source: https://context7.com/git/gforth/llms.txt Demonstrates closures capturing multiple local variables (`lo` and `hi`) to define a range check. ```Forth : make-range-checker ( lo hi -- xt ) {: lo hi :} dup lo >= swap hi <= and ;h ; 0 100 make-range-checker Constant in-range? 50 in-range? execute . \ -> -1 (true) 150 in-range? execute . \ -> 0 (false) in-range? free-closure ``` -------------------------------- ### Gforth Structures with `struct.fs` Source: https://context7.com/git/gforth/llms.txt Defines and uses C-like data structures using `struct`, `field`, `end-struct` from `struct.fs`. Supports type descriptors and allocation words like `%allot` and `%alloc`. ```Forth require struct.fs \ Define a 2D point structure struct cell% field pt-x cell% field pt-y end-struct point% \ Allocate a point in dictionary space point% %allot Constant mypoint 10 mypoint pt-x ! 20 mypoint pt-y ! mypoint pt-x @ . \ -> 10 mypoint pt-y @ . \ -> 20 \ Heap allocation point% %alloc Constant heappoint 100 heappoint pt-x ! 200 heappoint pt-y ! heappoint free throw \ Nested struct: a rectangle struct point% field rect-tl \ top-left point% field rect-br \ bottom-right end-struct rect% rect% %allot Constant myrect 0 myrect rect-tl pt-x ! 0 myrect rect-tl pt-y ! 100 myrect rect-br pt-x ! 50 myrect rect-br pt-y ! \ Array of structs 10 point% %size * allocate throw Constant pts \ access element 3's x field: 3 point% %size * pts + pt-x @ . \ begin-structure / field: style (Forth 200x) begin-structure vec3% field: v-x field: v-y field: v-z end-structure vec3% %allot Constant v 1 v v-x ! 2 v v-y ! 3 v v-z ! v v-x @ v v-y @ v v-z @ . . . \ -> 3 2 1 ``` -------------------------------- ### Pull Gforth Docker Image Source: https://github.com/git/gforth/blob/master/docker/runner/README.md Pulls the latest Gforth Docker image from Docker Hub. This is the first step before running Gforth in a container. ```shell docker pull forthy42/gforth ``` -------------------------------- ### Gforth Dictionary-Allocated Closures Source: https://context7.com/git/gforth/llms.txt Creates dictionary-allocated closures which persist as long as the dictionary. No explicit freeing is required. ```Forth : make-multiplier ( n -- xt ) {: n :}d n * ;d ; ``` ```Forth 3 make-multiplier Constant times3 7 times3 execute . \ -> 21 ``` -------------------------------- ### Configure without Long Long Support Source: https://github.com/git/gforth/blob/master/INSTALL.md If C's 'long long' type causes issues, disable its use during configuration by setting ac_cv_sizeof_long_long to 0. ```bash ./configure ac_cv_sizeof_long_long=0 ``` -------------------------------- ### Define Hexadecimal Pattern with regexp.fs Source: https://context7.com/git/gforth/llms.txt Define a custom character class for hexadecimal digits and use it to create a pattern matcher for hexadecimal strings. ```Forth \ Using charclass directly charclass hex-digit '0 '9 ..char 'a 'f ..char 'A 'F ..char : hex? ( addr u -- flag ) !end hex-digit c? BEGIN, hex-digit c? DONE, end$ = ; \ true if consumed entire string ``` -------------------------------- ### Gforth Anonymous Closures (Quotations) Source: https://context7.com/git/gforth/llms.txt Shows the use of anonymous closures (quotations) with `[: ... ;]` and applying them using a helper word. ```Forth : apply-twice ( xt n -- n' ) 2dup execute swap execute ; [: 1+ ;] 5 apply-twice . \ -> 7 ``` -------------------------------- ### Gforth One-Shot Closures Source: https://context7.com/git/gforth/llms.txt Implements one-shot closures that are automatically freed after their first execution. Useful for single-use callbacks. ```Forth : make-greeting ( addr u -- xt ) {: addr u :}h1 addr u type cr ;h1 ; ``` ```Forth s" Hello once" make-greeting Constant greet-once greet-once execute \ -> Hello once (and closure is freed) ``` -------------------------------- ### Gforth Memory Allocation: Safe Allocation Source: https://context7.com/git/gforth/llms.txt Implements a `safe-alloc` word that checks for allocation errors and throws an exception on failure. Memory is later freed. ```Forth \ Checked allocation with error handling : safe-alloc ( u -- addr ) allocate dup IF drop s" Out of memory" exception throw ELSE drop THEN ; ``` ```Forth 512 safe-alloc Constant safe-buf safe-buf free throw ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.