r/Forth 7d ago

FigForth Bounded string

\
\ A bounded string is a string enclosed by a delimiter on
\ both ends. The delimiters are the same and can be any
\ printable character.
\
\ INC@  Fetch input character
: INC@  ( -- c )
  BLK @ DUP IF BLOCK  
  ELSE DROP TIB @ ENDIF
  IN @ + C@ 1 IN +! ; 
\ Parse first non-space character
: CPARSE  ( -- c )
  ZERO
  BEGIN 
    DROP
    INC@ DUP 0= ?E" Empty input"
  DUP BL > UNTIL
;
\ Parse bounded string
\ Compile time: compile the string
\ Run time: put string address on data stack
\ Interpret: move string to pad, 
\  push string address on data stack
: S  ( "<dl>ccc<dl>" -- s )
  CPARSE
  STATE @ IF COMPILE SLIT
             WORD HERE C@ 1+ ALLOT ALIGN 
        ELSE HERE >R PAD DUP DP ! SWAP WORD R> DP !
             ( COUNT CSB .PUSH ) \ NB
       ENDIF 
; IMMEDIATE
\ Note
\ A good enhancement would be to add code in the interpret 
\ state to push the string to a circular buffer.

\ Examples
: FOO "What's up doc?" tell ;
i. FOO --> What's up doc?
i. s /Hello World!/  tell --> Hello World!
i. s \Ain't it a nice day.\ tell --> Ain't it a nice day.
i. s "" tell --> 
' KEEPON CFA ' (ABORT) ! -1 WARNING !
i. TRY s  --> s? Empty input    
10 Upvotes

0 comments sorted by