PageRenderTime 51ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/jonesforth.f

http://github.com/chengchangwu/jonesforth
FORTRAN Legacy | 1921 lines | 1715 code | 189 blank | 17 comment | 28 complexity | 43b6ae00422554cc4de1e355eaefd0da MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. \ -*- text -*-
  2. \ A sometimes minimal FORTH compiler and tutorial for Linux / i386 systems. -*- asm -*-
  3. \ By Richard W.M. Jones <rich@annexia.org> http://annexia.org/forth
  4. \ This is PUBLIC DOMAIN (see public domain release statement below).
  5. \ $Id: jonesforth.f,v 1.18 2009-09-11 08:32:33 rich Exp $
  6. \
  7. \ The first part of this tutorial is in jonesforth.S. Get if from http://annexia.org/forth
  8. \
  9. \ PUBLIC DOMAIN ----------------------------------------------------------------------
  10. \
  11. \ I, the copyright holder of this work, hereby release it into the public domain. This applies worldwide.
  12. \
  13. \ In case this is not legally possible, I grant any entity the right to use this work for any purpose,
  14. \ without any conditions, unless such conditions are required by law.
  15. \
  16. \ SETTING UP ----------------------------------------------------------------------
  17. \
  18. \ Let's get a few housekeeping things out of the way. Firstly because I need to draw lots of
  19. \ ASCII-art diagrams to explain concepts, the best way to look at this is using a window which
  20. \ uses a fixed width font and is at least this wide:
  21. \
  22. \<------------------------------------------------------------------------------------------------------------------------>
  23. \
  24. \ Secondly make sure TABS are set to 8 characters. The following should be a vertical
  25. \ line. If not, sort out your tabs.
  26. \
  27. \ |
  28. \ |
  29. \ |
  30. \
  31. \ Thirdly I assume that your screen is at least 50 characters high.
  32. \
  33. \ START OF FORTH CODE ----------------------------------------------------------------------
  34. \
  35. \ We've now reached the stage where the FORTH system is running and self-hosting. All further
  36. \ words can be written as FORTH itself, including words like IF, THEN, .", etc which in most
  37. \ languages would be considered rather fundamental.
  38. \
  39. \ Some notes about the code:
  40. \
  41. \ I use indenting to show structure. The amount of whitespace has no meaning to FORTH however
  42. \ except that you must use at least one whitespace character between words, and words themselves
  43. \ cannot contain whitespace.
  44. \
  45. \ FORTH is case-sensitive. Use capslock!
  46. \ The primitive word /MOD (DIVMOD) leaves both the quotient and the remainder on the stack. (On
  47. \ i386, the idivl instruction gives both anyway). Now we can define the / and MOD in terms of /MOD
  48. \ and a few other primitives.
  49. : / /MOD SWAP DROP ;
  50. : MOD /MOD DROP ;
  51. \ Define some character constants
  52. : '\n' 10 ;
  53. : BL 32 ; \ BL (BLank) is a standard FORTH word for space.
  54. \ CR prints a carriage return
  55. : CR '\n' EMIT ;
  56. \ SPACE prints a space
  57. : SPACE BL EMIT ;
  58. \ NEGATE leaves the negative of a number on the stack.
  59. : NEGATE 0 SWAP - ;
  60. \ Standard words for booleans.
  61. : TRUE -1 ;
  62. : FALSE 0 ;
  63. : NOT 0= ;
  64. \ LITERAL takes whatever is on the stack and compiles LIT <foo>
  65. : LITERAL IMMEDIATE
  66. ['] LIT , \ compile LIT
  67. , \ compile the literal itself (from the stack)
  68. ;
  69. \ HERE fetch the data stack pointer.
  70. : HERE DP @ ;
  71. \ Now we can use [ and ] to insert literals which are calculated at compile time. (Recall that
  72. \ [ and ] are the FORTH words which switch into and out of immediate mode.)
  73. \ Within definitions, use [ ... ] LITERAL anywhere that '...' is a constant expression which you
  74. \ would rather only compute once (at compile time, rather than calculating it each time your word runs).
  75. : ':'
  76. [ \ go into immediate mode (temporarily)
  77. CHAR : \ push the number 58 (ASCII code of colon) on the parameter stack
  78. ] \ go back to compile mode
  79. LITERAL \ compile LIT 58 as the definition of ':' word
  80. ;
  81. \ A few more character constants defined the same way as above.
  82. : ';' [ CHAR ; ] LITERAL ;
  83. : '(' [ CHAR ( ] LITERAL ;
  84. : ')' [ CHAR ) ] LITERAL ;
  85. : '"' [ CHAR " ] LITERAL ;
  86. : 'A' [ CHAR A ] LITERAL ;
  87. : '0' [ CHAR 0 ] LITERAL ;
  88. : '-' [ CHAR - ] LITERAL ;
  89. : '.' [ CHAR . ] LITERAL ;
  90. \ While compiling, '[COMPILE] word' compiles 'word' if it would otherwise be IMMEDIATE.
  91. : [COMPILE] IMMEDIATE
  92. WORD \ get the next word
  93. (FIND) \ find it in the dictionary
  94. >CFA \ get its codeword
  95. , \ and compile that
  96. ;
  97. \ RECURSE makes a recursive call to the current word that is being compiled.
  98. \
  99. \ Normally while a word is being compiled, it is marked HIDDEN so that references to the
  100. \ same word within are calls to the previous definition of the word. However we still have
  101. \ access to the word which we are currently compiling through the LATEST pointer so we
  102. \ can use that to compile a recursive call.
  103. : RECURSE IMMEDIATE
  104. LATEST @ \ LATEST points to the word being compiled at the moment
  105. >CFA \ get the codeword
  106. , \ compile it
  107. ;
  108. \ CONTROL STRUCTURES ----------------------------------------------------------------------
  109. \
  110. \ So far we have defined only very simple definitions. Before we can go further, we really need to
  111. \ make some control structures, like IF ... THEN and loops. Luckily we can define arbitrary control
  112. \ structures directly in FORTH.
  113. \
  114. \ Please note that the control structures as I have defined them here will only work inside compiled
  115. \ words. If you try to type in expressions using IF, etc. in immediate mode, then they won't work.
  116. \ Making these work in immediate mode is left as an exercise for the reader.
  117. \ condition IF true-part THEN rest
  118. \ -- compiles to: --> condition 0BRANCH OFFSET true-part rest
  119. \ where OFFSET is the offset of 'rest'
  120. \ condition IF true-part ELSE false-part THEN
  121. \ -- compiles to: --> condition 0BRANCH OFFSET true-part BRANCH OFFSET2 false-part rest
  122. \ where OFFSET if the offset of false-part and OFFSET2 is the offset of rest
  123. \ IF is an IMMEDIATE word which compiles 0BRANCH followed by a dummy offset, and places
  124. \ the address of the 0BRANCH on the stack. Later when we see THEN, we pop that address
  125. \ off the stack, calculate the offset, and back-fill the offset.
  126. : IF IMMEDIATE
  127. ['] 0BRANCH , \ compile 0BRANCH
  128. HERE \ save location of the offset on the stack
  129. 0 , \ compile a dummy offset
  130. ;
  131. : THEN IMMEDIATE
  132. DUP
  133. HERE SWAP - \ calculate the offset from the address saved on the stack
  134. SWAP ! \ store the offset in the back-filled location
  135. ;
  136. : ELSE IMMEDIATE
  137. ['] BRANCH , \ definite branch to just over the false-part
  138. HERE \ save location of the offset on the stack
  139. 0 , \ compile a dummy offset
  140. SWAP \ now back-fill the original (IF) offset
  141. DUP \ same as for THEN word above
  142. HERE SWAP -
  143. SWAP !
  144. ;
  145. \ BEGIN loop-part condition UNTIL
  146. \ -- compiles to: --> loop-part condition 0BRANCH OFFSET
  147. \ where OFFSET points back to the loop-part
  148. \ This is like do { loop-part } while (condition) in the C language
  149. : BEGIN IMMEDIATE
  150. HERE \ save location on the stack
  151. ;
  152. : UNTIL IMMEDIATE
  153. ['] 0BRANCH , \ compile 0BRANCH
  154. HERE - \ calculate the offset from the address saved on the stack
  155. , \ compile the offset here
  156. ;
  157. \ BEGIN loop-part AGAIN
  158. \ -- compiles to: --> loop-part BRANCH OFFSET
  159. \ where OFFSET points back to the loop-part
  160. \ In other words, an infinite loop which can only be returned from with EXIT
  161. : AGAIN IMMEDIATE
  162. ['] BRANCH , \ compile BRANCH
  163. HERE - \ calculate the offset back
  164. , \ compile the offset here
  165. ;
  166. \ BEGIN condition WHILE loop-part REPEAT
  167. \ -- compiles to: --> condition 0BRANCH OFFSET2 loop-part BRANCH OFFSET
  168. \ where OFFSET points back to condition (the beginning) and OFFSET2 points to after the whole piece of code
  169. \ So this is like a while (condition) { loop-part } loop in the C language
  170. : WHILE IMMEDIATE
  171. ['] 0BRANCH , \ compile 0BRANCH
  172. HERE \ save location of the offset2 on the stack
  173. SWAP \ get the original offset (from BEGIN)
  174. 0 , \ compile a dummy offset2
  175. ;
  176. : REPEAT IMMEDIATE
  177. ['] BRANCH , \ compile BRANCH
  178. HERE - , \ and compile it after BRANCH
  179. DUP
  180. HERE SWAP - \ calculate the offset2
  181. SWAP ! \ and back-fill it in the original location
  182. ;
  183. \ UNLESS is the same as IF but the test is reversed.
  184. \
  185. \ Note the use of [COMPILE]: Since IF is IMMEDIATE we don't want it to be executed while UNLESS
  186. \ is compiling, but while UNLESS is running (which happens to be when whatever word using UNLESS is
  187. \ being compiled -- whew!). So we use [COMPILE] to reverse the effect of marking IF as immediate.
  188. \ This trick is generally used when we want to write our own control words without having to
  189. \ implement them all in terms of the primitives 0BRANCH and BRANCH, but instead reusing simpler
  190. \ control words like (in this instance) IF.
  191. : UNLESS IMMEDIATE
  192. ['] NOT , \ compile NOT (to reverse the test)
  193. [COMPILE] IF \ continue by calling the normal IF
  194. ;
  195. \ COMMENTS ----------------------------------------------------------------------
  196. \
  197. \ FORTH allows ( ... ) as comments within function definitions. This works by having an IMMEDIATE
  198. \ word called ( which just drops input characters until it hits the corresponding ).
  199. : ( IMMEDIATE
  200. 1 \ allowed nested parens by keeping track of depth
  201. BEGIN
  202. KEY \ read next character
  203. DUP '(' = IF \ open paren?
  204. DROP \ drop the open paren
  205. 1+ \ depth increases
  206. ELSE
  207. ')' = IF \ close paren?
  208. 1- \ depth decreases
  209. THEN
  210. THEN
  211. DUP 0= UNTIL \ continue until we reach matching close paren, depth 0
  212. DROP \ drop the depth counter
  213. ;
  214. (
  215. From now on we can use ( ... ) for comments.
  216. STACK NOTATION ----------------------------------------------------------------------
  217. In FORTH style we can also use ( ... -- ... ) to show the effects that a word has on the
  218. parameter stack. For example:
  219. ( n -- ) means that the word consumes an integer (n) from the parameter stack.
  220. ( b a -- c ) means that the word uses two integers (a and b, where a is at the top of stack)
  221. and returns a single integer (c).
  222. ( -- ) means the word has no effect on the stack
  223. )
  224. ( Some more complicated stack examples, showing the stack notation. )
  225. : NIP ( x y -- y ) SWAP DROP ;
  226. : TUCK ( x y -- y x y ) SWAP OVER ;
  227. : PICK ( x_u ... x_1 x_0 u -- x_u ... x_1 x_0 x_u )
  228. 1+ ( add one because of 'u' on the stack )
  229. 4 * ( multiply by the word size )
  230. DSP@ + ( add to the stack pointer )
  231. @ ( and fetch )
  232. ;
  233. ( With the looping constructs, we can now write SPACES, which writes n spaces to stdout. )
  234. : SPACES ( n -- )
  235. BEGIN
  236. DUP 0> ( while n > 0 )
  237. WHILE
  238. SPACE ( print a space )
  239. 1- ( until we count down to 0 )
  240. REPEAT
  241. DROP
  242. ;
  243. ( Standard words for manipulating BASE. )
  244. : DECIMAL ( -- ) 10 BASE ! ;
  245. : HEX ( -- ) 16 BASE ! ;
  246. (
  247. PRINTING NUMBERS ----------------------------------------------------------------------
  248. The standard FORTH word . (DOT) is very important. It takes the number at the top
  249. of the stack and prints it out. However first I'm going to implement some lower-level
  250. FORTH words:
  251. U.R ( u width -- ) which prints an unsigned number, padded to a certain width
  252. U. ( u -- ) which prints an unsigned number
  253. .R ( n width -- ) which prints a signed number, padded to a certain width.
  254. For example:
  255. -123 6 .R
  256. will print out these characters:
  257. <space> <space> - 1 2 3
  258. In other words, the number padded left to a certain number of characters.
  259. The full number is printed even if it is wider than width, and this is what allows us to
  260. define the ordinary functions U. and . (we just set width to zero knowing that the full
  261. number will be printed anyway).
  262. Another wrinkle of . and friends is that they obey the current base in the variable BASE.
  263. BASE can be anything in the range 2 to 36.
  264. While we're defining . &c we can also define .S which is a useful debugging tool. This
  265. word prints the current stack (non-destructively) from top to bottom.
  266. )
  267. ( This is the underlying recursive definition of U. )
  268. : U. ( u -- )
  269. BASE @ U/MOD ( width rem quot )
  270. ?DUP IF ( if quotient <> 0 then )
  271. RECURSE ( print the quotient )
  272. THEN
  273. ( print the remainder )
  274. DUP 10 < IF
  275. '0' ( decimal digits 0..9 )
  276. ELSE
  277. 10 - ( hex and beyond digits A..Z )
  278. 'A'
  279. THEN
  280. +
  281. EMIT
  282. ;
  283. (
  284. FORTH word .S prints the contents of the stack. It doesn't alter the stack.
  285. Very useful for debugging.
  286. )
  287. : .S ( -- )
  288. DSP@ ( get current stack pointer )
  289. 0 S0 @ + 4- ( pointer to the stack element )
  290. BEGIN
  291. OVER OVER <= ( compare to current stack pointer )
  292. WHILE
  293. DUP @ U. ( print the stack element )
  294. SPACE
  295. 4- ( move down )
  296. REPEAT
  297. DROP DROP
  298. ;
  299. ( This word returns the width (in characters) of an unsigned number in the current base )
  300. : UWIDTH ( u -- width )
  301. BASE @ / ( rem quot )
  302. ?DUP IF ( if quotient <> 0 then )
  303. RECURSE 1+ ( return 1+recursive call )
  304. ELSE
  305. 1 ( return 1 )
  306. THEN
  307. ;
  308. : U.R ( u width -- )
  309. SWAP ( width u )
  310. DUP ( width u u )
  311. UWIDTH ( width u uwidth )
  312. ROT ( u uwidth width )
  313. SWAP - ( u width-uwidth )
  314. ( At this point if the requested width is narrower, we'll have a negative number on the stack.
  315. Otherwise the number on the stack is the number of spaces to print. But SPACES won't print
  316. a negative number of spaces anyway, so it's now safe to call SPACES ... )
  317. SPACES
  318. ( ... and then call the underlying implementation of U. )
  319. U.
  320. ;
  321. (
  322. .R prints a signed number, padded to a certain width. We can't just print the sign
  323. and call U.R because we want the sign to be next to the number ('-123' instead of '- 123').
  324. )
  325. : .R ( n width -- )
  326. SWAP ( width n )
  327. DUP 0< IF
  328. NEGATE ( width u )
  329. 1 ( save a flag to remember that it was negative | width n 1 )
  330. SWAP ( width 1 u )
  331. ROT ( 1 u width )
  332. 1- ( 1 u width-1 )
  333. ELSE
  334. 0 ( width u 0 )
  335. SWAP ( width 0 u )
  336. ROT ( 0 u width )
  337. THEN
  338. SWAP ( flag width u )
  339. DUP ( flag width u u )
  340. UWIDTH ( flag width u uwidth )
  341. ROT ( flag u uwidth width )
  342. SWAP - ( flag u width-uwidth )
  343. SPACES ( flag u )
  344. SWAP ( u flag )
  345. IF ( was it negative? print the - character )
  346. '-' EMIT
  347. THEN
  348. U.
  349. ;
  350. ( Finally we can define word . in terms of .R, with a trailing space. )
  351. : . 0 .R SPACE ;
  352. ( The real U., note the trailing space. )
  353. : U. U. SPACE ;
  354. ( ? fetches the integer at an address and prints it. )
  355. : ? ( addr -- ) @ . ;
  356. ( c a b WITHIN returns true if a <= c and c < b )
  357. ( or define without ifs: OVER - >R - R> U< )
  358. : WITHIN
  359. -ROT ( b c a )
  360. OVER ( b c a c )
  361. <= IF
  362. > IF ( b c -- )
  363. TRUE
  364. ELSE
  365. FALSE
  366. THEN
  367. ELSE
  368. 2DROP ( b c -- )
  369. FALSE
  370. THEN
  371. ;
  372. ( DEPTH returns the depth of the stack. )
  373. : DEPTH ( -- n )
  374. S0 @ DSP@ -
  375. 4- ( adjust because S0 was on the stack when we pushed DSP )
  376. 4 / ( A cell has four bytes )
  377. ;
  378. (
  379. ALIGNED takes an address and rounds it up (aligns it) to the next 4 byte boundary.
  380. )
  381. : ALIGNED ( addr -- addr )
  382. 3 + 3 INVERT AND ( (addr+3) & ~3 )
  383. ;
  384. (
  385. ALIGN aligns the DP pointer, so the next word appended will be aligned properly.
  386. )
  387. : ALIGN HERE ALIGNED DP ! ;
  388. (
  389. STRINGS ----------------------------------------------------------------------
  390. S" string" is used in FORTH to define strings. It leaves the address of the string and
  391. its length on the stack, (length at the top of stack). The space following S" is the normal
  392. space between FORTH words and is not a part of the string.
  393. This is tricky to define because it has to do different things depending on whether
  394. we are compiling or in immediate mode. (Thus the word is marked IMMEDIATE so it can
  395. detect this and do different things).
  396. In compile mode we append
  397. LITSTRING <string length> <string rounded up 4 bytes>
  398. to the current word. The primitive LITSTRING does the right thing when the current
  399. word is executed.
  400. In immediate mode there isn't a particularly good place to put the string, but in this
  401. case we put the string at DP (but we _don't_ change DP). This is meant as a temporary
  402. location, likely to be overwritten soon after.
  403. )
  404. ( C, appends a byte to the current compiled word. )
  405. : C,
  406. HERE C! ( store the character in the compiled image )
  407. 1 DP +! ( increment DP pointer by 1 byte )
  408. ;
  409. : S" IMMEDIATE ( -- addr len )
  410. STATE @ IF ( compiling? )
  411. ['] LITSTRING , ( compile LITSTRING )
  412. HERE ( save the address of the length word on the stack )
  413. 0 , ( dummy length - we don't know what it is yet )
  414. BEGIN
  415. KEY ( get next character of the string )
  416. DUP '"' <>
  417. WHILE
  418. C, ( copy character )
  419. REPEAT
  420. DROP ( drop the double quote character at the end )
  421. DUP ( get the saved address of the length word )
  422. HERE SWAP - ( calculate the length )
  423. 4- ( subtract 4 (because we measured from the start of the length word) )
  424. SWAP ! ( and back-fill the length location )
  425. ALIGN ( round up to next multiple of 4 bytes for the remaining code )
  426. ELSE ( immediate mode )
  427. HERE ( get the start address of the temporary space )
  428. BEGIN
  429. KEY
  430. DUP '"' <>
  431. WHILE
  432. OVER C! ( save next character )
  433. 1+ ( increment address )
  434. REPEAT
  435. DROP ( drop the final " character )
  436. HERE - ( calculate the length )
  437. HERE ( push the start address )
  438. SWAP ( addr len )
  439. THEN
  440. ;
  441. (
  442. ." is the print string operator in FORTH. Example: ." Something to print"
  443. The space after the operator is the ordinary space required between words and is not
  444. a part of what is printed.
  445. In immediate mode we just keep reading characters and printing them until we get to
  446. the next double quote.
  447. In compile mode we use S" to store the string, then add TELL afterwards:
  448. LITSTRING <string length> <string rounded up to 4 bytes> TELL
  449. It may be interesting to note the use of [COMPILE] to turn the call to the immediate
  450. word S" into compilation of that word. It compiles it into the definition of .",
  451. not into the definition of the word being compiled when this is running (complicated
  452. enough for you?)
  453. )
  454. : ." IMMEDIATE ( -- )
  455. STATE @ IF ( compiling? )
  456. [COMPILE] S" ( read the string, and compile LITSTRING, etc. )
  457. ['] TELL , ( compile the final TELL )
  458. ELSE
  459. ( In immediate mode, just read characters and print them until we get
  460. to the ending double quote. )
  461. BEGIN
  462. KEY
  463. DUP '"' = IF
  464. DROP ( drop the double quote character )
  465. EXIT ( return from this function )
  466. THEN
  467. EMIT
  468. AGAIN
  469. THEN
  470. ;
  471. (
  472. CONSTANTS AND VARIABLES ----------------------------------------------------------------------
  473. In FORTH, global constants and variables are defined like this:
  474. 10 CONSTANT TEN when TEN is executed, it leaves the integer 10 on the stack
  475. VARIABLE VAR when VAR is executed, it leaves the address of VAR on the stack
  476. Constants can be read but not written, eg:
  477. TEN . CR prints 10
  478. You can read a variable (in this example called VAR) by doing:
  479. VAR @ leaves the value of VAR on the stack
  480. VAR @ . CR prints the value of VAR
  481. VAR ? CR same as above, since ? is the same as @ .
  482. and update the variable by doing:
  483. 20 VAR ! sets VAR to 20
  484. Note that variables are uninitialised (but see VALUE later on which provides initialised
  485. variables with a slightly simpler syntax).
  486. How can we define the words CONSTANT and VARIABLE?
  487. The trick is to define a new word for the variable itself (eg. if the variable was called
  488. 'VAR' then we would define a new word called VAR). This is easy to do because we exposed
  489. dictionary entry creation through the HEADER, (HEADER_COMMA) word (part of the definition
  490. of : above). A call to WORD [TEN] HEADER, (where [TEN] means that "TEN" is the next word
  491. in the input) leaves the dictionary entry:
  492. +--- DP
  493. |
  494. V
  495. +---------+---+---+---+---+
  496. | LINK | 3 | T | E | N |
  497. +---------+---+---+---+---+
  498. len
  499. For CONSTANT we can continue by appending DOCOL (the codeword), then LIT followed by
  500. the constant itself and then EXIT, forming a little word definition that returns the
  501. constant:
  502. +---------+---+---+---+---+------------+------------+------------+------------+
  503. | LINK | 3 | T | E | N | DOCOL | LIT | 10 | EXIT |
  504. +---------+---+---+---+---+------------+------------+------------+------------+
  505. len codeword
  506. Notice that this word definition is exactly the same as you would have got if you had
  507. written : TEN 10 ;
  508. Note for people reading the code below: DOCOL is a constant word which we defined in the
  509. assembler part which returns the value of the assembler symbol of the same name.
  510. )
  511. : CONSTANT
  512. WORD ( get the name (the name follows CONSTANT) )
  513. HEADER, ( make the dictionary entry )
  514. DOCOL , ( append DOCOL (the codeword field of this word) )
  515. ['] LIT , ( append the codeword LIT )
  516. , ( append the value on the top of the stack )
  517. ['] EXIT , ( append the codeword EXIT )
  518. ;
  519. (
  520. VARIABLE is a little bit harder because we need somewhere to put the data. The run time
  521. behavior of a VARIABLE is to push the pointer to its data on to stack. DODOES with a zero
  522. behavior pointer does exactly this. So one possible definition of VARIABLE might create
  523. this:
  524. bahavior pointer
  525. +---------+---+---+---+---+------------+------------+-------|
  526. | LINK | 3 | V | A | R | DODOES | 0 | <var> |
  527. +---------+---+---+---+---+------------+------------+-------+
  528. len codeword
  529. where <var> is the place to store the variable.
  530. To make this more general let's define a couple of words which we can use to allocate
  531. arbitrary memory from the user memory.
  532. First ALLOT, where n ALLOT allocates n bytes of memory. (Note when calling this that
  533. it's a very good idea to make sure that n is a multiple of 4, or at least that next time
  534. a word is compiled that DP has been left as a multiple of 4).
  535. )
  536. : ALLOT ( n -- )
  537. DP +! ( adds n to DP )
  538. ;
  539. (
  540. Second, CELLS. In FORTH the phrase 'n CELLS ALLOT' means allocate n integers of whatever size
  541. is the natural size for integers on this machine architecture. On this 32 bit machine therefore
  542. CELLS just multiplies the top of stack by 4.
  543. )
  544. : CELLS ( n -- n ) 4 * ;
  545. (
  546. So now we can define VARIABLE easily in much the same way as CONSTANT above. Refer to the
  547. diagram above to see what the word that this creates will look like.
  548. )
  549. : VARIABLE
  550. WORD HEADER, ( make the dictionary entry (the name follows VARIABLE) )
  551. DODOES , 0 , ( append DOCOL (the codeword field of this word) )
  552. 1 CELLS ALLOT ( allocate 1 cell of memory )
  553. ;
  554. (
  555. DATA STRUCTURE WITH BEHAVIOR ---------------------------------------------------------
  556. Data structure with more complicated behavior than VARIABLE can be implemented using DODOES
  557. with a nonzero behaviour pointer. CREATE and DOES> are two words used to ease the development
  558. of such data structure.
  559. As an example of CREATE and DOES>, a new version of CONSTANT is defined below:
  560. : CONST CREATE , DOES> @ ;
  561. 10 CONST TEN
  562. +-------+---+---+---+---+---+---+-------+----------------+---------|
  563. | LINK | 5 | C | O | N | S | T | DOCOL | CREATE , DOES> | @ EXIT |
  564. +-------+---+---+---+---+---+---+-------+----------------+---------|
  565. ^
  566. |
  567. +------------+
  568. behavior pointer|
  569. +---------+---+---+---+---+------------+------|-----+-------+
  570. | LINK | 3 | T | E | N | DODOES | | 10 |
  571. +---------+---+---+---+---+------------+------------+-------+
  572. len codeword data
  573. DODOES pushes the pointer to 10 onto the stack, execute the behavior words pointed to by
  574. the behavior pointer, namely the @, which fetches the 10 from the pointer on the stack.
  575. CREATE creates a dictionary header, compiles DODOES and a zero behavior pointer without
  576. allocation more data memory. DOES> pointes the behavior pointer to the behavior words, return
  577. to its caller without executing the behavior words behind it.
  578. )
  579. : CREATE
  580. WORD HEADER, ( make the dictionary entry (the name follows VARIABLE) )
  581. DODOES , 0 , ( append DOCOL (the codeword field of this word) )
  582. ;
  583. : DOES>
  584. R> LATEST @ >DFA !
  585. ;
  586. (
  587. VALUES ----------------------------------------------------------------------
  588. VALUEs are like VARIABLEs but with a simpler syntax. You would generally use them when you
  589. want a variable which is read often, and written infrequently.
  590. 20 VALUE VAL creates VAL with initial value 20
  591. VAL pushes the value (20) directly on the stack
  592. 30 TO VAL updates VAL, setting it to 30
  593. VAL pushes the value (30) directly on the stack
  594. Notice that 'VAL' on its own doesn't return the address of the value, but the value itself,
  595. making values simpler and more obvious to use than variables (no indirection through '@').
  596. The price is a more complicated implementation, although despite the complexity there is no
  597. performance penalty at runtime.
  598. A naive implementation of 'TO' would be quite slow, involving a dictionary search each time.
  599. But because this is FORTH we have complete control of the compiler so we can compile TO more
  600. efficiently, turning:
  601. TO VAL
  602. into:
  603. LIT <addr> !
  604. and calculating <addr> (the address of the value) at compile time.
  605. Now this is the clever bit. We'll compile our value like this:
  606. +---------+---+---+---+---+------------+------------+------------+------------+
  607. | LINK | 3 | V | A | L | DOCOL | LIT | <value> | EXIT |
  608. +---------+---+---+---+---+------------+------------+------------+------------+
  609. len codeword
  610. where <value> is the actual value itself. Note that when VAL executes, it will push the
  611. value on the stack, which is what we want.
  612. But what will TO use for the address <addr>? Why of course a pointer to that <value>:
  613. code compiled - - - - --+------------+------------+------------+-- - - - -
  614. by TO VAL | LIT | <addr> | ! |
  615. - - - - --+------------+-----|------+------------+-- - - - -
  616. |
  617. V
  618. +---------+---+---+---+---+------------+------------+------------+------------+
  619. | LINK | 3 | V | A | L | DOCOL | LIT | <value> | EXIT |
  620. +---------+---+---+---+---+------------+------------+------------+------------+
  621. len codeword
  622. In other words, this is a kind of self-modifying code.
  623. (Note to the people who want to modify this FORTH to add inlining: values defined this
  624. way cannot be inlined).
  625. )
  626. : VALUE ( n -- )
  627. WORD HEADER, ( make the dictionary entry (the name follows VALUE) )
  628. DOCOL , ( append DOCOL )
  629. ['] LIT , ( append the codeword LIT )
  630. , ( append the initial value )
  631. ['] EXIT , ( append the codeword EXIT )
  632. ;
  633. : TO IMMEDIATE ( n -- )
  634. WORD ( get the name of the value )
  635. (FIND) ( look it up in the dictionary )
  636. >DFA ( get a pointer to the first data field (the 'LIT') )
  637. 4+ ( increment to point at the value )
  638. STATE @ IF ( compiling? )
  639. ['] LIT , ( compile LIT )
  640. , ( compile the address of the value )
  641. ['] ! , ( compile ! )
  642. ELSE ( immediate mode )
  643. ! ( update it straightaway )
  644. THEN
  645. ;
  646. ( x +TO VAL adds x to VAL )
  647. : +TO IMMEDIATE
  648. WORD ( get the name of the value )
  649. (FIND) ( look it up in the dictionary )
  650. >DFA ( get a pointer to the first data field (the 'LIT') )
  651. 4+ ( increment to point at the value )
  652. STATE @ IF ( compiling? )
  653. ['] LIT , ( compile LIT )
  654. , ( compile the address of the value )
  655. ['] +! , ( compile +! )
  656. ELSE ( immediate mode )
  657. +! ( update it straightaway )
  658. THEN
  659. ;
  660. (
  661. PRINTING THE DICTIONARY ----------------------------------------------------------------------
  662. ID. takes an address of a dictionary entry and prints the word's name.
  663. For example: LATEST @ ID. would print the name of the last word that was defined.
  664. )
  665. : ID.
  666. 4+ ( skip over the link pointer )
  667. DUP C@ ( get the flags/length byte )
  668. F_LENMASK AND ( mask out the flags - just want the length )
  669. BEGIN
  670. DUP 0> ( length > 0? )
  671. WHILE
  672. SWAP 1+ ( addr len -- len addr+1 )
  673. DUP C@ ( len addr -- len addr char | get the next character)
  674. EMIT ( len addr char -- len addr | and print it)
  675. SWAP 1- ( len addr -- addr len-1 | subtract one from length )
  676. REPEAT
  677. 2DROP ( len addr -- )
  678. ;
  679. (
  680. 'WORD word (FIND) ?HIDDEN' returns true if 'word' is flagged as hidden.
  681. 'WORD word (FIND) ?IMMEDIATE' returns true if 'word' is flagged as immediate.
  682. )
  683. : ?HIDDEN
  684. 4+ ( skip over the link pointer )
  685. C@ ( get the flags/length byte )
  686. F_HIDDEN AND ( mask the F_HIDDEN flag and return it (as a truth value) )
  687. ;
  688. : ?IMMEDIATE
  689. 4+ ( skip over the link pointer )
  690. C@ ( get the flags/length byte )
  691. F_IMMED AND ( mask the F_IMMED flag and return it (as a truth value) )
  692. ;
  693. (
  694. WORDS prints all the words defined in the dictionary, starting with the word defined most recently.
  695. However it doesn't print hidden words.
  696. The implementation simply iterates backwards from LATEST using the link pointers.
  697. )
  698. : WORDS
  699. LATEST @ ( start at LATEST dictionary entry )
  700. BEGIN
  701. ?DUP ( while link pointer is not null )
  702. WHILE
  703. DUP ?HIDDEN NOT IF ( ignore hidden words )
  704. DUP ID. ( but if not hidden, print the word )
  705. SPACE
  706. THEN
  707. @ ( dereference the link pointer - go to previous word )
  708. REPEAT
  709. CR
  710. ;
  711. (
  712. FORGET ----------------------------------------------------------------------
  713. So far we have only allocated words and memory. FORTH provides a rather primitive method
  714. to deallocate.
  715. 'FORGET word' deletes the definition of 'word' from the dictionary and everything defined
  716. after it, including any variables and other memory allocated after.
  717. The implementation is very simple - we look up the word (which returns the dictionary entry
  718. address). Then we set DP to point to that address, so in effect all future allocations
  719. and definitions will overwrite memory starting at the word. We also need to set LATEST to
  720. point to the previous word.
  721. Note that you cannot FORGET built-in words (well, you can try but it will probably cause
  722. a segfault).
  723. XXX: Because we wrote VARIABLE to store the variable in memory allocated before the word,
  724. in the current implementation VARIABLE FOO FORGET FOO will leak 1 cell of memory.
  725. )
  726. : FORGET
  727. WORD (FIND) ( find the word, gets the dictionary entry address )
  728. DUP @ LATEST ! ( set LATEST to point to the previous word )
  729. DP ! ( and store DP with the dictionary address )
  730. ;
  731. (
  732. DUMP ----------------------------------------------------------------------
  733. DUMP is used to dump out the contents of memory, in the 'traditional' hexdump format.
  734. Notice that the parameters to DUMP (address, length) are compatible with string words
  735. such as WORD and S".
  736. You can dump out the raw code for the last word you defined by doing something like:
  737. LATEST @ 128 DUMP
  738. )
  739. : DUMP ( addr len -- )
  740. BASE @ -ROT ( save the current BASE at the bottom of the stack )
  741. HEX ( and switch to hexadecimal mode )
  742. BEGIN
  743. ?DUP ( while len > 0 )
  744. WHILE
  745. OVER 8 U.R ( print the address )
  746. SPACE
  747. ( print up to 16 words on this line )
  748. 2DUP ( addr len addr len )
  749. 1- 15 AND 1+ ( addr len addr linelen )
  750. BEGIN
  751. ?DUP ( while linelen > 0 )
  752. WHILE
  753. SWAP ( addr len linelen addr )
  754. DUP C@ ( addr len linelen addr byte )
  755. 2 .R SPACE ( print the byte )
  756. 1+ SWAP 1- ( addr len linelen addr -- addr len addr+1 linelen-1 )
  757. REPEAT
  758. DROP ( addr len )
  759. ( print the ASCII equivalents )
  760. 2DUP 1- 15 AND 1+ ( addr len addr linelen )
  761. BEGIN
  762. ?DUP ( while linelen > 0)
  763. WHILE
  764. SWAP ( addr len linelen addr )
  765. DUP C@ ( addr len linelen addr byte )
  766. DUP 32 128 WITHIN IF ( 32 <= c < 128? )
  767. EMIT
  768. ELSE
  769. DROP '.' EMIT
  770. THEN
  771. 1+ SWAP 1- ( addr len linelen addr -- addr len addr+1 linelen-1 )
  772. REPEAT
  773. DROP ( addr len )
  774. CR
  775. DUP 1- 15 AND 1+ ( addr len linelen )
  776. TUCK ( addr linelen len linelen )
  777. - ( addr linelen len-linelen )
  778. >R + R> ( addr+linelen len-linelen )
  779. REPEAT
  780. DROP ( restore stack )
  781. BASE ! ( restore saved BASE )
  782. ;
  783. (
  784. CASE ----------------------------------------------------------------------
  785. CASE...ENDCASE is how we do switch statements in FORTH. There is no generally
  786. agreed syntax for this, so I've gone for the syntax mandated by the ISO standard
  787. FORTH (ANS-FORTH).
  788. ( some value on the stack )
  789. CASE
  790. test1 OF ... ENDOF
  791. test2 OF ... ENDOF
  792. testn OF ... ENDOF
  793. ... ( default case )
  794. ENDCASE
  795. The CASE statement tests the value on the stack by comparing it for equality with
  796. test1, test2, ..., testn and executes the matching piece of code within OF ... ENDOF.
  797. If none of the test values match then the default case is executed. Inside the ... of
  798. the default case, the value is still at the top of stack (it is implicitly DROP-ed
  799. by ENDCASE). When ENDOF is executed it jumps after ENDCASE (ie. there is no "fall-through"
  800. and no need for a break statement like in C).
  801. The default case may be omitted. In fact the tests may also be omitted so that you
  802. just have a default case, although this is probably not very useful.
  803. An example (assuming that 'q', etc. are words which push the ASCII value of the letter
  804. on the stack):
  805. 0 VALUE QUIT
  806. 0 VALUE SLEEP
  807. KEY CASE
  808. 'q' OF 1 TO QUIT ENDOF
  809. 's' OF 1 TO SLEEP ENDOF
  810. ( default case: )
  811. ." Sorry, I didn't understand key <" DUP EMIT ." >, try again." CR
  812. ENDCASE
  813. (In some versions of FORTH, more advanced tests are supported, such as ranges, etc.
  814. Other versions of FORTH need you to write OTHERWISE to indicate the default case.
  815. As I said above, this FORTH tries to follow the ANS FORTH standard).
  816. The implementation of CASE...ENDCASE is somewhat non-trivial. I'm following the
  817. implementations from here:
  818. http://www.uni-giessen.de/faq/archiv/forthfaq.case_endcase/msg00000.html
  819. The general plan is to compile the code as a series of IF statements:
  820. CASE (push 0 on the immediate-mode parameter stack)
  821. test1 OF ... ENDOF test1 OVER = IF DROP ... ELSE
  822. test2 OF ... ENDOF test2 OVER = IF DROP ... ELSE
  823. testn OF ... ENDOF testn OVER = IF DROP ... ELSE
  824. ... ( default case ) ...
  825. ENDCASE DROP THEN [THEN [THEN ...]]
  826. The CASE statement pushes 0 on the immediate-mode parameter stack, and that number
  827. is used to count how many THEN statements we need when we get to ENDCASE so that each
  828. IF has a matching THEN. The counting is done implicitly. If you recall from the
  829. implementation above of IF, each IF pushes a code address on the immediate-mode stack,
  830. and these addresses are non-zero, so by the time we get to ENDCASE the stack contains
  831. some number of non-zeroes, followed by a zero. The number of non-zeroes is how many
  832. times IF has been called, so how many times we need to match it with THEN.
  833. This code uses [COMPILE] so that we compile calls to IF, ELSE, THEN instead of
  834. actually calling them while we're compiling the words below.
  835. As is the case with all of our control structures, they only work within word
  836. definitions, not in immediate mode.
  837. )
  838. : CASE IMMEDIATE
  839. 0 ( push 0 to mark the bottom of the stack )
  840. ;
  841. : OF IMMEDIATE
  842. ['] OVER , ( compile OVER )
  843. ['] = , ( compile = )
  844. [COMPILE] IF ( compile IF )
  845. ['] DROP , ( compile DROP )
  846. ;
  847. : ENDOF IMMEDIATE
  848. [COMPILE] ELSE ( ENDOF is the same as ELSE )
  849. ;
  850. : ENDCASE IMMEDIATE
  851. ['] DROP , ( compile DROP )
  852. ( keep compiling THEN until we get to our zero marker )
  853. BEGIN
  854. ?DUP
  855. WHILE
  856. [COMPILE] THEN
  857. REPEAT
  858. ;
  859. (
  860. EXCEPTIONS ----------------------------------------------------------------------
  861. Amazingly enough, exceptions can be implemented directly in FORTH, in fact rather easily.
  862. The general usage is as follows:
  863. : FOO ( n -- ) THROW ;
  864. : TEST-EXCEPTIONS
  865. 25 ['] FOO CATCH \ execute 25 FOO, catching any exception
  866. ?DUP IF
  867. ." called FOO and it threw exception number: "
  868. . CR
  869. DROP \ we have to drop the argument of FOO (25)
  870. THEN
  871. ;
  872. \ prints: called FOO and it threw exception number: 25
  873. CATCH runs an execution token and detects whether it throws any exception or not. The
  874. stack signature of CATCH is rather complicated:
  875. ( a_n-1 ... a_1 a_0 xt -- r_m-1 ... r_1 r_0 0 ) if xt did NOT throw an exception
  876. ( a_n-1 ... a_1 a_0 xt -- ?_n-1 ... ?_1 ?_0 e ) if xt DID throw exception 'e'
  877. where a_i and r_i are the (arbitrary number of) argument and return stack contents
  878. before and after xt is EXECUTEd. Notice in particular the case where an exception
  879. is thrown, the stack pointer is restored so that there are n of _something_ on the
  880. stack in the positions where the arguments a_i used to be. We don't really guarantee
  881. what is on the stack -- perhaps the original arguments, and perhaps other nonsense --
  882. it largely depends on the implementation of the word that was executed.
  883. THROW, ABORT and a few others throw exceptions.
  884. Exception numbers are non-zero integers. By convention the positive numbers can be used
  885. for app-specific exceptions and the negative numbers have certain meanings defined in
  886. the ANS FORTH standard. (For example, -1 is the exception thrown by ABORT).
  887. 0 THROW does nothing. This is the stack signature of THROW:
  888. ( 0 -- )
  889. ( * e -- ?_n-1 ... ?_1 ?_0 e ) the stack is restored to the state from the corresponding CATCH
  890. The implementation hangs on the definitions of CATCH and THROW and the state shared
  891. between them.
  892. Up to this point, the return stack has consisted merely of a list of return addresses,
  893. with the top of the return stack being the return address where we will resume executing
  894. when the current word EXITs. However CATCH will push a more complicated 'exception stack
  895. frame' on the return stack. The exception stack frame records some things about the
  896. state of execution at the time that CATCH was called.
  897. When called, THROW walks up the return stack (the process is called 'unwinding') until
  898. it finds the exception stack frame. It then uses the data in the exception stack frame
  899. to restore the state allowing execution to continue after the matching CATCH. (If it
  900. unwinds the stack and doesn't find the exception stack frame then it prints a message
  901. and drops back to the prompt, which is also normal behaviour for so-called 'uncaught
  902. exceptions').
  903. This is what the exception stack frame looks like. (As is conventional, the return stack
  904. is shown growing downwards from higher to lower memory addresses).
  905. +------------------------------+
  906. | return address from CATCH | Notice this is already on the
  907. | | return stack when CATCH is called.
  908. +------------------------------+
  909. | original parameter stack |
  910. | pointer |
  911. +------------------------------+ ^
  912. | exception stack marker | |
  913. | (EXCEPTION-MARKER) | | Direction of stack
  914. +------------------------------+ | unwinding by THROW.
  915. |
  916. |
  917. The EXCEPTION-MARKER marks the entry as being an exception stack frame rather than an
  918. ordinary return address, and it is this which THROW "notices" as it is unwinding the
  919. stack. (If you want to implement more advanced exceptions such as TRY...WITH then
  920. you'll need to use a different value of marker if you want the old and new exception stack
  921. frame layouts to coexist).
  922. What happens if the executed word doesn't throw an exception? It will eventually
  923. return and call EXCEPTION-MARKER, so EXCEPTION-MARKER had better do something sensible
  924. without us needing to modify EXIT. This nicely gives us a suitable definition of
  925. EXCEPTION-MARKER, namely a function that just drops the stack frame and itself
  926. returns (thus "returning" from the original CATCH).
  927. One thing to take from this is that exceptions are a relatively lightweight mechanism
  928. in FORTH.
  929. )
  930. : EXCEPTION-MARKER
  931. RDROP ( drop the original parameter stack pointer )
  932. 0 ( there was no exception, this is the normal return path )
  933. ;
  934. : CATCH ( xt -- exn? )
  935. DSP@ 4+ >R ( save parameter stack pointer (+4 because of xt) on the return stack )
  936. ['] EXCEPTION-MARKER 4+ ( push the address of the RDROP inside EXCEPTION-MARKER ... )
  937. >R ( ... on to the return stack so it acts like a return address )
  938. EXECUTE ( execute the nested function )
  939. ;
  940. : THROW ( n -- )
  941. ?DUP IF ( only act if the exception code <> 0 )
  942. RSP@ ( get return stack pointer )
  943. BEGIN
  944. DUP R0 4- < ( RSP < R0 )
  945. WHILE
  946. DUP @ ( get the return stack entry )
  947. ['] EXCEPTION-MARKER 4+ = IF ( found the EXCEPTION-MARKER on the return stack )
  948. 4+ ( skip the EXCEPTION-MARKER on the return stack )
  949. RSP! ( restore the return stack pointer )
  950. ( Restore the parameter stack. )
  951. DUP DUP DUP ( reserve some working space so the stack for this word
  952. doesn't coincide with the part of the stack being restored )
  953. R> ( get the saved parameter stack pointer | n dsp )
  954. 4- ( reserve space on the stack to store n )
  955. SWAP OVER ( dsp n dsp )
  956. ! ( write n on the stack )
  957. DSP! EXIT ( restore the parameter stack pointer, immediately exit )
  958. THEN
  959. 4+
  960. REPEAT
  961. ( No matching catch - print a message and restart the INTERPRETer. )
  962. DROP
  963. CASE
  964. 0 1- OF ( ABORT )
  965. ." ABORTED" CR
  966. ENDOF
  967. ( default case )
  968. ." UNCAUGHT THROW "
  969. DUP . CR
  970. ENDCASE
  971. QUIT
  972. THEN
  973. ;
  974. : ABORT ( -- )
  975. 0 1- THROW
  976. ;
  977. (
  978. Some high level ANS Forth CORE words are not presented in the original jonesforth. They
  979. are included here without explanation. Most of them are adapted from bb4wforth.
  980. )
  981. : [CHAR] ( "<spaces>name" -- ) CHAR ['] LIT , , ; IMMEDIATE
  982. : 2OVER ( x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2 ) 3 PICK 3 PICK ;
  983. : CELL+ ( a-addr1 -- a-addr2 ) 1 CELLS + ;
  984. : CHARS ( n1 -- n2 ) ;
  985. : CHAR+ ( c-addr1 -- c-addr2 ) 1 CHARS + ;
  986. : 2! ( x1 x2 a-addr -- ) SWAP OVER ! CELL+ ! ;
  987. : 2@ ( a-addr -- x1 x2 ) DUP CELL+ @ SWAP @ ;
  988. : MOVE ( addr1 addr2 u -- ) CMOVE ;
  989. : 2>R ( x1 x2 -- ) ( R: -- x1 x2 ) ['] SWAP , ['] >R , ['] >R , ; IMMEDIATE
  990. : 2R> ( -- x1 x2 ) ( R: x1 x2 -- ) ['] R> , ['] R> , ['] SWAP , ; IMMEDIATE
  991. : 2R@ ( -- x1 x2 ) ( R: x1 x2 -- x1 x2 )
  992. 2R> 2DUP 2>R ;
  993. : ABS ( n -- u)
  994. DUP 0< IF NEGATE THEN ;
  995. CREATE LEAVE-SP 32 CELLS ALLOT
  996. LEAVE-SP LEAVE-SP !
  997. : LEAVE
  998. ['] UNLOOP ,
  999. ['] BRANCH ,
  1000. LEAVE-SP @ LEAVE-SP - 31 CELLS >
  1001. IF ABORT THEN
  1002. 1 CELLS LEAVE-SP +!
  1003. HERE LEAVE-SP @ !
  1004. 0 ,
  1005. ; IMMEDIATE
  1006. : RESOLVE-LEAVES ( here - )
  1007. BEGIN
  1008. LEAVE-SP @ @ OVER >
  1009. LEAVE-SP @ LEAVE-SP > AND
  1010. WHILE
  1011. HERE LEAVE-SP @ @ - LEAVE-SP @ @ !
  1012. 1 CELLS NEGATE LEAVE-SP +!
  1013. REPEAT
  1014. DROP
  1015. ;
  1016. : DO ( -- here 0 )
  1017. ['] (DO) ,
  1018. HERE 0
  1019. ; IMMEDIATE
  1020. : ?DO ( -- here 1 )
  1021. ['] 2DUP ,
  1022. ['] <> ,
  1023. ['] 0BRANCH ,
  1024. 0 ,
  1025. ['] (DO) ,
  1026. HERE 1
  1027. ; IMMEDIATE
  1028. : RESOLVE-DO ( here 0|1 -- here )
  1029. IF ( ?DO )
  1030. DUP HERE - ,
  1031. DUP 2 CELLS - HERE OVER - SWAP !
  1032. ELSE ( DO )
  1033. DUP HERE - ,
  1034. THEN ;
  1035. : LOOP ( here 0|1 -- )
  1036. ['] (LOOP) ,
  1037. RESOLVE-DO
  1038. RESOLVE-LEAVES
  1039. ; IMMEDIATE
  1040. : +LOOP ( here 0|1 -- )
  1041. ['] (+LOOP) ,
  1042. RESOLVE-DO
  1043. RESOLVE-LEAVES
  1044. ; IMMEDIATE
  1045. (
  1046. DECOMPILER ----------------------------------------------------------------------
  1047. CFA> is the opposite of >CFA. It takes a codeword and tries to find the matching
  1048. dictionary definition. (In truth, it works with any pointer into a word, not just
  1049. the codeword pointer, and this is needed to do stack traces).
  1050. In this FORTH this is not so easy. In fact we have to search through the dictionary
  1051. because we don't have a convenient back-pointer (as is often the case in other versions
  1052. of FORTH). Because of this search, CFA> should not be used when performance is critical,
  1053. so it is only used for debugging tools such as the decompiler and printing stack
  1054. traces.
  1055. This word returns 0 if it doesn't find a match.
  1056. )
  1057. : CFA>
  1058. LATEST @ ( start at LATEST dictionary entry )
  1059. BEGIN
  1060. ?DUP ( while link pointer is not null )
  1061. WHILE
  1062. 2DUP SWAP ( cfa curr curr cfa )
  1063. < IF ( current dictionary entry < cfa? )
  1064. NIP ( leave curr dictionary entry on the stack )
  1065. EXIT
  1066. THEN
  1067. @ ( follow link pointer back )
  1068. REPEAT
  1069. DROP ( restore stack )
  1070. 0 ( sorry, nothing found )
  1071. ;
  1072. (
  1073. SEE decompiles a FORTH word.
  1074. We search for the dictionary entry of the word, then search again for the next
  1075. word (effectively, the end of the compiled word). This results in two pointers:
  1076. +---------+---+---+---+---+------------+------------+------------+------------+
  1077. | LINK | 3 | T | E | N | DOCOL | LIT | 10 | EXIT |
  1078. +---------+---+---+---+---+------------+------------+------------+------------+
  1079. ^ ^
  1080. | |
  1081. Start of word End of word
  1082. With this information we can have a go at decompiling the word. We need to
  1083. recognise "meta-words" like LIT, LITSTRING, BRANCH, etc. and treat those separately.
  1084. )
  1085. : SEE
  1086. WORD (FIND) ( find the dictionary entry to decompile )
  1087. ( Now we search again, looking for the next word in the dictionary. This gives us
  1088. the length of the word that we will be decompiling. (Well, mostly it does). )
  1089. HERE ( address of the end of the last compiled word )
  1090. LATEST @ ( word last curr )
  1091. BEGIN
  1092. 2 PICK ( word last curr word )
  1093. OVER ( word last curr word curr )
  1094. <> ( word last curr word<>curr? )
  1095. WHILE ( word last curr )
  1096. NIP ( word curr )
  1097. DUP @ ( word curr prev (which becomes: word last curr) )
  1098. REPEAT
  1099. DROP ( at this point, the stack is: start-of-word end-of-word )
  1100. SWAP ( end-of-word start-of-word )
  1101. ( begin the definition with : NAME [IMMEDIATE] )
  1102. ':' EMIT SPACE DUP ID. SPACE
  1103. DUP ?IMMEDIATE IF ." IMMEDIATE " THEN
  1104. >DFA ( get the data address, ie. points after DOCOL | end-of-word start-of-data )
  1105. ( now we start decompiling until we hit the end of the word )
  1106. BEGIN ( end start )
  1107. 2DUP >
  1108. WHILE
  1109. DUP @ ( end start codeword )
  1110. CASE
  1111. ['] LIT OF ( is it LIT ? )
  1112. 4 + DUP @ ( get next word which is the integer constant )
  1113. . ( and print it )
  1114. ENDOF
  1115. ['] LITSTRING OF ( is it LITSTRING ? )
  1116. [ CHAR S ] LITERAL EMIT '"' EMIT SPACE ( print S"<space> )
  1117. 4 + DUP @ ( get the length word )
  1118. SWAP 4 + SWAP ( end start+4 length )
  1119. 2DUP TELL ( print the string )
  1120. '"' EMIT SPACE ( finish the string with a final quote )
  1121. + ALIGNED ( end start+4+len, aligned )
  1122. 4 - ( because we're about to add 4 below )
  1123. ENDOF
  1124. ['] 0BRANCH OF ( is it 0BRANCH ? )
  1125. ." 0BRANCH ( "
  1126. 4 + DUP @ ( print the offset )
  1127. .
  1128. ." ) "
  1129. ENDOF
  1130. ['] BRANCH OF ( is it BRANCH ? )
  1131. ." BRANCH ( "
  1132. 4 + DUP @ ( print the offset )
  1133. .
  1134. ." ) "
  1135. ENDOF
  1136. ['] (LOOP) OF ( is it (LOOP) ? )
  1137. ." (LOOP) ( "
  1138. 4 + DUP @ ( print the offset )
  1139. .
  1140. ." ) "
  1141. ENDOF
  1142. ['] (+LOOP) OF ( is it (+LOOP) ? )
  1143. ." (+LOOP) ( "
  1144. 4 + DUP @ ( print the offset )
  1145. .
  1146. ." ) "
  1147. ENDOF
  1148. ['] ['] OF ( is it ['] (BRACKET_TICK) ? )
  1149. ." ['] "
  1150. 4 + DUP @ ( get the next codeword )
  1151. CFA> ( and force it to be printed as a dictionary entry )
  1152. ID. SPACE
  1153. ENDOF
  1154. ['] EXIT OF ( is it EXIT? )
  1155. ( We expect the last word to be EXIT, and if it is then we don't print it
  1156. because EXIT is normally implied by ;. EXIT can also appear in the middle
  1157. of words, and then it needs to be printed. )
  1158. 2DUP ( end start end start )
  1159. 4 + ( end start end start+4 )
  1160. <> IF ( end start | we're not at the end )
  1161. ." EXIT "
  1162. THEN
  1163. ENDOF
  1164. ( default case: )
  1165. DUP ( in the default case we always need to DUP before using )
  1166. CFA> ( look up the codeword to get the dictionary entry )
  1167. ID. SPACE ( and print it )
  1168. ENDCASE
  1169. 4 + ( end start+4 )
  1170. REPEAT
  1171. ';' EMIT CR
  1172. 2DROP ( restore stack )
  1173. ;
  1174. (
  1175. EXECUTION TOKENS ----------------------------------------------------------------------
  1176. Standard FORTH defines a concept called an 'execution token' (or 'xt') which is very
  1177. similar to a function pointer in C. We map the execution token to a codeword address.
  1178. execution token of DOUBLE is the address of this codeword
  1179. |
  1180. V
  1181. +---------+---+---+---+---+---+---+---+---+------------+------------+------------+------------+
  1182. | LINK | 6 | D | O | U | B | L | E | 0 | DOCOL | DUP | + | EXIT |
  1183. +---------+---+---+---+---+---+---+---+---+------------+------------+------------+------------+
  1184. len pad codeword ^
  1185. There is one assembler primitive for execution tokens, EXECUTE ( xt -- ), which runs them.
  1186. You can make an execution token for an existing word the long way using >CFA,
  1187. ie: WORD [foo] (FIND) >CFA will push the xt for foo onto the stack where foo is the
  1188. next word in input. So a very slow way to run DOUBLE might be:
  1189. : DOUBLE DUP + ;
  1190. : SLOW WORD (FIND) >CFA EXECUTE ;
  1191. 5 SLOW DOUBLE . CR \ prints 10
  1192. We also offer a simpler and faster way to get the execution token of any word FOO:
  1193. ['] FOO
  1194. As stated before the version of ['] defined until now only works in compiling mode.
  1195. It also fails when the word after it is not an immediate word. We also offer a new
  1196. word ' (TICK) which works in immediate mode.
  1197. (Exercises for readers: (1) What is the difference between ['] FOO and ' FOO?
  1198. (2) What is the relationship between ', ['] and LIT? (3) How can a ['] working on
  1199. immediate word be defined?)
  1200. More useful is to define anonymous words and/or to assign xt's to variables.
  1201. To define an anonymous word (and push its xt on the stack) use :NONAME ... ; as in this
  1202. example:
  1203. :NONAME ." anon word was called" CR ; \ pushes xt on the stack
  1204. DUP EXECUTE EXECUTE \ executes the anon word twice
  1205. Stack parameters work as expected:
  1206. :NONAME ." called with parameter " . CR ;
  1207. DUP
  1208. 10 SWAP EXECUTE \ prints 'called with parameter 10'
  1209. 20 SWAP EXECUTE \ prints 'called with parameter 20'
  1210. Notice that the above code has a memory leak: the anonymous word is still compiled
  1211. into the data segment, so even if you lose track of the xt, the word continues to
  1212. occupy memory. A good way to keep track of the xt and thus avoid the memory leak is
  1213. to assign it to a CONSTANT, VARIABLE or VALUE:
  1214. 0 VALUE ANON
  1215. :NONAME ." anon word was called" CR ; TO ANON
  1216. ANON EXECUTE
  1217. ANON EXECUTE
  1218. Another use of :NONAME is to create an array of functions which can be called quickly
  1219. (think: fast switch statement). This example is adapted from the ANS FORTH standard:
  1220. HERE 10 CELLS ALLOT CONSTANT CMD-TABLE
  1221. : SET-CMD CELLS CMD-TABLE + ! ;
  1222. : CALL-CMD CELLS CMD-TABLE + @ EXECUTE ;
  1223. :NONAME ." alternate 0 was called" CR ; 0 SET-CMD
  1224. :NONAME ." alternate 1 was called" CR ; 1 SET-CMD
  1225. \ etc...
  1226. :NONAME ." alternate 9 was called" CR ; 9 SET-CMD
  1227. 0 CALL-CMD
  1228. 1 CALL-CMD
  1229. )
  1230. : :NONAME
  1231. 0 0 HEADER, ( create a word with no name - we need a dictionary header because ; expects it )
  1232. HERE ( current DP value is the address of the codeword, ie. the xt )
  1233. DOCOL , ( compile DOCOL (the codeword) )
  1234. ] ( go into compile mode )
  1235. ;
  1236. : ' ( "<spaces>name" -- xt )
  1237. WORD (FIND) >CFA
  1238. ;
  1239. ( Print a stack trace by walking up the return stack. )
  1240. : PRINT-STACK-TRACE
  1241. RSP@ ( start at caller of this function )
  1242. BEGIN
  1243. DUP R0 4- < ( RSP < R0 )
  1244. WHILE
  1245. DUP @ ( get the return stack entry )
  1246. CASE
  1247. ['] EXCEPTION-MARKER 4+ OF ( is it the exception stack …

Large files files are truncated, but you can click here to view the full file