4 size_mem = 1000000 # 1 mega-int
7 size_RS = 1000 # Return stack size
8 size_PS = 1000 # Parameter stack size
9 size_TIB = 1000 # Terminal input buffer size
11 # The mem array constitutes the memory of the VM. It has the following geography:
13 # mem = +-----------------------+
14 # | Built-in Variables |
15 # +-----------------------+
17 # +-----------------------+
19 # +-----------------------+
20 # | Terminal Input Buffer |
21 # +-----------------------+
23 # +-----------------------+
25 # Note that all words (user-defined, primitive, variables, etc) are included in
28 # Simple linear addressing is used with one exception: references to primitive code
29 # blocks, which are represented as anonymous functions, appear as negative indicies
30 # into the primitives array which contains these functions.
32 mem = Array{Int64,1}(size_mem)
33 primitives = Array{Function,1}()
34 primNames = Array{ASCIIString,1}()
39 RSP0 = nextVarAddr; nextVarAddr += 1
40 PSP0 = nextVarAddr; nextVarAddr += 1
41 HERE = nextVarAddr; nextVarAddr += 1
42 LATEST = nextVarAddr; nextVarAddr += 1
44 mem[RSP0] = nextVarAddr # bottom of RS
45 mem[PSP0] = mem[RSP0] + size_RS # bottom of PS
46 TIB = mem[PSP0] + size_PS # address of terminal input buffer
47 mem[HERE] = TIB + size_TIB # location of bottom of dictionary
48 mem[LATEST] = 0 # no previous definition
50 DICT = mem[HERE] # Save bottom of dictionary as constant
54 RSP::Int64 # Return stack pointer
55 PSP::Int64 # Parameter/data stack pointer
56 IP::Int64 # Instruction pointer
57 W::Int64 # Working register
59 reg = Reg(mem[RSP0], mem[PSP0], 0, 0)
61 # Stack manipulation functions
63 type ParamStackUnderflow <: Exception end
64 type ReturnStackUnderflow <: Exception end
66 Base.showerror(io::IO, ex::ParamStackUnderflow) = print(io, "Parameter stack underflow.")
67 Base.showerror(io::IO, ex::ReturnStackUnderflow) = print(io, "Return stack underflow.")
69 getRSDepth() = reg.RSP - mem[RSP0]
70 getPSDepth() = reg.PSP - mem[PSP0]
72 function ensurePSDepth(depth::Int64)
74 throw(ParamStackUnderflow())
78 function ensureRSDepth(depth::Int64)
80 throw(ReturnStackUnderflow())
84 function pushRS(val::Int64)
96 function pushPS(val::Int64)
97 mem[reg.PSP += 1] = val
108 # Handy functions for adding/retrieving strings to/from memory.
110 getString(addr::Int64, len::Int64) = ASCIIString([Char(c) for c in mem[addr:(addr+len-1)]])
111 function putString(str::ASCIIString, addr::Int64)
112 mem[addr:(addr+length(str)-1)] = [Int64(c) for c in str]
115 # Primitive creation and calling functions
117 function defPrim(f::Function; name="nameless")
119 push!(primNames, replace(replace(name, "\004", "EOF"), "\n", "\\n"))
121 return -length(primitives)
124 callPrim(addr::Int64) = primitives[-addr]()
125 getPrimName(addr::Int64) = primNames[-addr]
127 # Word creation functions
133 function createHeader(name::AbstractString, flags::Int64)
134 mem[mem[HERE]] = mem[LATEST]
135 mem[LATEST] = mem[HERE]
138 mem[mem[HERE]] = length(name) | flags; mem[HERE] += 1
139 putString(name, mem[HERE]); mem[HERE] += length(name)
142 function defPrimWord(name::AbstractString, f::Function; flags::Int64=0)
143 createHeader(name, flags)
145 codeWordAddr = mem[HERE]
146 mem[codeWordAddr] = defPrim(f, name=name)
152 function defWord(name::AbstractString, wordAddrs::Array{Int64,1}; flags::Int64=0)
153 createHeader(name, flags)
156 mem[mem[HERE]] = DOCOL
159 for wordAddr in wordAddrs
160 mem[mem[HERE]] = wordAddr
167 # Variable creation functions
169 function defExistingVar(name::AbstractString, varAddr::Int64; flags::Int64=0)
171 defPrimWord(name, eval(:(() -> begin
177 function defNewVar(name::AbstractString, initial::Int64; flags::Int64=0)
178 createHeader(name, flags)
180 codeWordAddr = mem[HERE]
181 varAddr = mem[HERE] + 1
183 mem[mem[HERE]] = DOVAR; mem[HERE] += 1
184 mem[mem[HERE]] = initial; mem[HERE] += 1
186 return varAddr, codeWordAddr
189 function defConst(name::AbstractString, val::Int64; flags::Int64=0)
190 createHeader(name, flags)
192 codeWordAddr = mem[HERE]
194 mem[mem[HERE]] = DOCON; mem[HERE] += 1
195 mem[mem[HERE]] = val; mem[HERE] += 1
200 # Threading Primitives (inner interpreter)
202 NEXT = defPrim(() -> begin
208 DOCOL = defPrim(() -> begin
214 DOVAR = defPrim(() -> begin
219 DOCON = defPrim(() -> begin
220 pushPS(mem[reg.W + 1])
224 EXIT = defPrimWord("EXIT", () -> begin
229 # Dictionary entries for core built-in variables, constants
231 HERE_CFA = defExistingVar("HERE", HERE)
232 LATEST_CFA = defExistingVar("LATEST", LATEST)
233 PSP0_CFA = defExistingVar("PSP0", PSP0)
234 RSP0_CFA = defExistingVar("RSP0", RSP0)
236 defConst("DOCOL", DOCOL)
237 defConst("DOCON", DOCON)
238 defConst("DOVAR", DOVAR)
240 defConst("DICT", DICT)
241 defConst("MEMSIZE", size_mem)
243 F_IMMED_CFA = defConst("F_IMMED", F_IMMED)
244 F_HIDDEN_CFA = defConst("F_HIDDEN", F_HIDDEN)
245 F_LENMASK_CFA = defConst("F_LENMASK", F_LENMASK)
247 # Basic forth primitives
249 DROP = defPrimWord("DROP", () -> begin
254 SWAP = defPrimWord("SWAP", () -> begin
262 DUP = defPrimWord("DUP", () -> begin
268 OVER = defPrimWord("OVER", () -> begin
270 pushPS(mem[reg.PSP-1])
274 ROT = defPrimWord("ROT", () -> begin
284 NROT = defPrimWord("-ROT", () -> begin
295 TWODROP = defPrimWord("2DROP", () -> begin
301 TWODUP = defPrimWord("2DUP", () -> begin
310 TWOSWAP = defPrimWord("2SWAP", () -> begin
322 TWOOVER = defPrimWord("2OVER", () -> begin
331 QDUP = defPrimWord("?DUP", () -> begin
340 INCR = defPrimWord("1+", () -> begin
346 DECR = defPrimWord("1-", () -> begin
352 INCR2 = defPrimWord("2+", () -> begin
358 DECR2 = defPrimWord("2-", () -> begin
364 ADD = defPrimWord("+", () -> begin
371 SUB = defPrimWord("-", () -> begin
378 MUL = defPrimWord("*", () -> begin
385 DIVMOD = defPrimWord("/MOD", () -> begin
394 TWOMUL = defPrimWord("2*", () -> begin
399 TWODIV = defPrimWord("2/", () -> begin
404 EQ = defPrimWord("=", () -> begin
407 pushPS(a==b ? -1 : 0)
411 NE = defPrimWord("<>", () -> begin
414 pushPS(a!=b ? -1 : 0)
418 LT = defPrimWord("<", () -> begin
425 GT = defPrimWord(">", () -> begin
432 LE = defPrimWord("<=", () -> begin
435 pushPS(a<=b ? -1 : 0)
439 GE = defPrimWord(">=", () -> begin
442 pushPS(a>=b ? -1 : 0)
446 ZE = defPrimWord("0=", () -> begin
447 pushPS(popPS() == 0 ? -1 : 0)
451 ZNE = defPrimWord("0<>", () -> begin
452 pushPS(popPS() != 0 ? -1 : 0)
456 ZLT = defPrimWord("0<", () -> begin
457 pushPS(popPS() < 0 ? -1 : 0)
461 ZGT = defPrimWord("0>", () -> begin
462 pushPS(popPS() > 0 ? -1 : 0)
466 ZLE = defPrimWord("0<=", () -> begin
467 pushPS(popPS() <= 0 ? -1 : 0)
471 ZGE = defPrimWord("0>=", () -> begin
472 pushPS(popPS() >= 0 ? -1 : 0)
476 AND = defPrimWord("AND", () -> begin
483 OR = defPrimWord("OR", () -> begin
490 XOR = defPrimWord("XOR", () -> begin
497 INVERT = defPrimWord("INVERT", () -> begin
504 LIT = defPrimWord("LIT", () -> begin
512 STORE = defPrimWord("!", () -> begin
519 FETCH = defPrimWord("@", () -> begin
525 ADDSTORE = defPrimWord("+!", () -> begin
532 SUBSTORE = defPrimWord("-!", () -> begin
542 TOR = defPrimWord(">R", () -> begin
547 FROMR = defPrimWord("R>", () -> begin
552 RFETCH = defPrimWord("R@", () -> begin
557 RSPFETCH = defPrimWord("RSP@", () -> begin
562 RSPSTORE = defPrimWord("RSP!", () -> begin
567 RDROP = defPrimWord("RDROP", () -> begin
574 PSPFETCH = defPrimWord("PSP@", () -> begin
579 PSPSTORE = defPrimWord("PSP!", () -> begin
586 WFETCH = defPrimWord("W@", () -> begin
591 WSTORE = defPrimWord("W!", () -> begin
598 sources = Array{Any,1}()
599 currentSource() = sources[length(sources)]
601 EOF_CFA = defConst("EOF", 4)
603 EMIT = defPrimWord("EMIT", () -> begin
608 SPAN, SPAN_CFA = defNewVar("SPAN", 0)
609 EXPECT = defPrimWord("EXPECT", () -> begin
613 if !eof(currentSource())
614 line = chomp(readline(currentSource()))
615 mem[SPAN] = min(length(line), maxLen)
616 putString(line[1:mem[SPAN]], addr)
625 BASE, BASE_CFA = defNewVar("BASE", 10)
626 NUMBER = defPrimWord("NUMBER", () -> begin
628 wordLen = mem[wordAddr-1]
630 s = getString(wordAddr, wordLen)
632 pushPS(parse(Int64, s, mem[BASE]))
637 # Dictionary searches
639 FIND = defPrimWord("FIND", () -> begin
641 countedAddr = popPS()
642 wordAddr = countedAddr + 1
643 wordLen = mem[countedAddr]
644 word = lowercase(getString(wordAddr, wordLen))
649 while (latest = mem[latest]) > 0
650 lenAndFlags = mem[latest+1]
651 len = lenAndFlags & F_LENMASK
652 hidden = (lenAndFlags & F_HIDDEN) == F_HIDDEN
654 if hidden || len != wordLen
659 thisWord = lowercase(getString(thisAddr, len))
661 if lowercase(thisWord) == lowercase(word)
671 TOCFA = defPrimWord(">CFA", () -> begin
674 lenAndFlags = mem[addr+1]
675 len = lenAndFlags & F_LENMASK
677 pushPS(addr + 2 + len)
682 TODFA = defWord(">DFA", [TOCFA, INCR, EXIT])
686 BRANCH = defPrimWord("BRANCH", () -> begin
687 reg.IP += mem[reg.IP]
691 ZBRANCH = defPrimWord("0BRANCH", () -> begin
693 reg.IP += mem[reg.IP]
703 LITSTRING = defPrimWord("LITSTRING", () -> begin
713 TYPE = defPrimWord("TYPE", () -> begin
716 str = getString(addr, len)
723 TRACE = defPrimWord("TRACE", () -> begin
724 print("RS: "); printRS()
725 print("PS: "); printPS()
732 COMMA = defPrimWord(",", () -> begin
733 mem[mem[HERE]] = popPS()
739 BTICK = defWord("[']",
740 [FROMR, DUP, INCR, TOR, FETCH, EXIT])
742 EXECUTE = defPrimWord("EXECUTE", () -> begin
747 TIB_CFA = defConst("TIB", TIB)
748 NUMTIB, NUMTIB_CFA = defNewVar("#TIB", 0)
749 TOIN, TOIN_CFA = defNewVar(">IN", 0)
751 QUERY = defWord("QUERY",
752 [TIB_CFA, LIT, 80, EXPECT,
753 SPAN_CFA, FETCH, NUMTIB_CFA, STORE,
754 LIT, 0, TOIN_CFA, STORE,
757 WORD = defPrimWord("WORD", () -> begin
760 # Chew up initial occurrences of delim
761 while (mem[TOIN]<mem[NUMTIB] && mem[TIB+mem[TOIN]] == delim)
765 countAddr = mem[HERE]
768 # Start reading in word
770 while (mem[TOIN]<mem[NUMTIB] && mem[TIB+mem[TOIN]] != delim)
771 mem[addr] = mem[TIB+mem[TOIN]]
778 mem[countAddr] = count
784 STATE, STATE_CFA = defNewVar("STATE", 0)
786 INTERPRET = defWord("INTERPRET",
787 [LIT, 32, WORD, # Read next space-delimited word
789 DUP, FETCH, ZE, ZBRANCH, 3,
790 DROP, EXIT, # Exit if TIB is exhausted
792 STATE_CFA, FETCH, ZBRANCH, 27,
794 DUP, FIND, ZBRANCH, 17,
797 DUP, TOCFA, SWAP, INCR, FETCH, LIT, F_IMMED, AND, ZBRANCH, 4,
798 # Immediate: Execute!
799 EXECUTE, BRANCH, -30,
801 # Not immediate: Compile!
804 # No word found, parse number
805 NUMBER, BTICK, LIT, COMMA, BRANCH, -39,
808 DUP, FIND, QDUP, ZBRANCH, 7,
810 # Found word. Execute!
811 SWAP, DROP, TOCFA, EXECUTE, BRANCH, -50,
813 # No word found, parse number and leave on stack
818 PROMPT = defPrimWord("PROMPT", () -> begin
819 if (mem[STATE] == 0 && currentSource() == STDIN)
826 QUIT = defWord("QUIT",
832 BYE = defPrimWord("BYE", () -> begin
837 INCLUDE = defPrimWord("INCLUDE", () -> begin
841 word = getString(wordAddr, wordLen)
843 push!(sources, open(word, "r"))
853 HEADER = defPrimWord("HEADER", () -> begin
856 wordLen = mem[wordAddr-1]
857 word = getString(wordAddr, wordLen)
859 createHeader(word, 0)
864 LBRAC = defPrimWord("[", () -> begin
869 RBRAC = defPrimWord("]", () -> begin
874 HIDDEN = defPrimWord("HIDDEN", () -> begin
876 mem[addr] = mem[addr] $ F_HIDDEN
880 HIDE = defWord("HIDE",
890 LATEST_CFA, FETCH, HIDDEN,
894 SEMICOLON = defWord(";",
896 LATEST_CFA, FETCH, HIDDEN,
898 EXIT], flags=F_IMMED)
900 IMMEDIATE = defPrimWord("IMMEDIATE", () -> begin
901 lenAndFlagsAddr = mem[LATEST] + 1
902 mem[lenAndFlagsAddr] = mem[lenAndFlagsAddr] $ F_IMMED
907 [WORD, FIND, TOCFA, EXIT])
913 initFileName = nothing
915 initFileName = "lib.4th"
916 elseif isfile(Pkg.dir("forth/src/lib.4th"))
917 initFileName = Pkg.dir("forth/src/lib.4th")
920 function run(;initialize=false)
921 # Begin with STDIN as source
922 push!(sources, STDIN)
924 global initialized, initFileName
925 if !initialized && initialize
926 if initFileName != nothing
927 print("Including definitions from $initFileName...")
928 push!(sources, open(initFileName, "r"))
931 println("No library file found. Only primitive words available.")
935 # Start with IP pointing to first instruction of outer interpreter
938 # Primitive processing loop.
939 # Everyting else is simply a consequence of this loop!
943 #println("Entering prim $(getPrimName(jmp))")
947 showerror(STDOUT, ex)
950 while !isempty(sources) && currentSource() != STDIN
966 function dump(startAddr::Int64; count::Int64 = 100, cellsPerLine::Int64 = 10)
967 chars = Array{Char,1}(cellsPerLine)
969 lineStartAddr = cellsPerLine*div((startAddr-1),cellsPerLine) + 1
970 endAddr = startAddr + count - 1
972 q, r = divrem((endAddr-lineStartAddr+1), cellsPerLine)
973 numLines = q + (r > 0 ? 1 : 0)
979 for c in 1:cellsPerLine
980 if i >= startAddr && i <= endAddr
982 if mem[i]>=32 && mem[i]<128
983 chars[c] = Char(mem[i])
995 println("\t", ASCIIString(chars))
1000 count = reg.PSP - mem[PSP0]
1004 for i in (mem[PSP0]+1):reg.PSP
1009 println("Parameter stack empty")
1014 count = reg.RSP - mem[RSP0]
1018 for i in (mem[RSP0]+1):reg.RSP
1023 println("Return stack empty")
1027 DUMP = defPrimWord("DUMP", () -> begin
1031 dump(addr, count=count)