3 import Base.REPLCompletions
6 size_mem = 1000000 # 1 mega-int
9 size_RS = 1000 # Return stack size
10 size_PS = 1000 # Parameter stack size
11 size_TIB = 1000 # Terminal input buffer size
12 size_FIB = 1000 # File input buffer size
15 mem = Array{Int64,1}(size_mem)
16 primitives = Array{Function,1}()
17 primNames = Array{AbstractString,1}()
19 # Memory geography and built-in variables
22 H = nextVarAddr; nextVarAddr += 1 # Next free memory address
23 FORTH_LATEST = nextVarAddr; nextVarAddr += 1 # FORTH dict latest
24 CURRENT = nextVarAddr; nextVarAddr += 1 # Current compilation dict
26 RSP0 = nextVarAddr # bottom of RS
27 PSP0 = RSP0 + size_RS # bottom of PS
28 TIB = PSP0 + size_PS # address of terminal input buffer
29 FIB = TIB + size_TIB # address of terminal input buffer
30 mem[H] = FIB + size_FIB # location of bottom of dictionary
31 mem[FORTH_LATEST] = 0 # zero FORTH dict latest (no previous def)
32 mem[CURRENT] = FORTH_LATEST-1 # Compile words to system dict initially
34 DICT = mem[H] # Save bottom of dictionary as constant
38 RSP::Int64 # Return stack pointer
39 PSP::Int64 # Parameter/data stack pointer
40 IP::Int64 # Instruction pointer
41 W::Int64 # Working register
43 reg = Reg(RSP0, PSP0, 0, 0)
45 # Stack manipulation functions
47 function ensurePSDepth(depth::Int64)
48 if reg.PSP - PSP0 < depth
49 error("Parameter stack underflow.")
53 function ensurePSCapacity(toAdd::Int64)
54 if reg.PSP + toAdd >= PSP0 + size_PS
55 error("Parameter stack overflow.")
59 function ensureRSDepth(depth::Int64)
60 if reg.RSP - RSP0 < depth
61 error("Return stack underflow.")
65 function ensureRSCapacity(toAdd::Int64)
66 if reg.RSP + toAdd >= RSP0 + size_RS
67 error("Return stack overflow.")
71 function pushRS(val::Int64)
84 function pushPS(val::Int64)
87 mem[reg.PSP += 1] = val
98 # Handy functions for adding/retrieving strings to/from memory.
100 getString(addr::Int64, len::Int64) = AbstractString([Char(c) for c in mem[addr:(addr+len-1)]])
102 function putString(str::AbstractString, addr::Int64)
103 mem[addr:(addr+length(str)-1)] = [Int64(c) for c in str]
106 function putString(str::AbstractString, addr::Int64, maxLen::Int64)
107 len = min(length(str), maxLen)
108 mem[addr:(addr+len-1)] = [Int64(c) for c in str]
111 stringAsInts(str::AbstractString) = [Int(c) for c in collect(str)]
113 # Primitive creation and calling functions
115 function defPrim(f::Function; name="nameless")
117 push!(primNames, replace(name, "\004", "EOF"))
119 return -length(primitives)
122 function callPrim(addr::Int64)
123 if addr >=0 || -addr>length(primitives)
124 error("Attempted to execute non-existent primitive at address $addr.")
129 getPrimName(addr::Int64) = primNames[-addr]
131 # Word creation functions
138 function dictWrite(ints::Array{Int64,1})
139 mem[mem[H]:(mem[H]+length(ints)-1)] = ints
140 mem[H] += length(ints)
142 dictWrite(int::Int64) = dictWrite([int])
143 dictWriteString(string::AbstractString) = dictWrite([Int64(c) for c in string])
145 function createHeader(name::AbstractString, flags::Int64)
146 mem[mem[H]] = mem[mem[CURRENT]+1]
147 mem[mem[CURRENT]+1] = mem[H]
150 dictWrite(length(name) | flags | NFA_MARK)
151 dictWriteString(name)
154 function defPrimWord(name::AbstractString, f::Function; flags::Int64=0)
155 createHeader(name, flags)
157 codeWordAddr = mem[H]
158 dictWrite(defPrim(f, name=name))
163 function defWord(name::AbstractString, wordAddrs::Array{Int64,1}; flags::Int64=0)
164 createHeader(name, flags)
174 # Variable creation functions
176 function defExistingVar(name::AbstractString, varAddr::Int64; flags::Int64=0)
178 defPrimWord(name, eval(:(() -> begin
184 function defNewVar(name::AbstractString, initial::Array{Int64,1}; flags::Int64=0)
185 createHeader(name, flags)
187 codeWordAddr = mem[H]
193 return varAddr, codeWordAddr
196 defNewVar(name::AbstractString, initial::Int64; flags::Int64=0) =
197 defNewVar(name, [initial]; flags=flags)
199 function defConst(name::AbstractString, val::Int64; flags::Int64=0)
200 createHeader(name, flags)
202 codeWordAddr = mem[H]
210 # Threading Primitives (inner interpreter)
212 NEXT = defPrim(() -> begin
218 DOCOL = defPrim(() -> begin
224 DOVAR = defPrim(() -> begin
229 DOCON = defPrim(() -> begin
230 pushPS(mem[reg.W + 1])
234 EXIT_CFA = defPrimWord("EXIT", () -> begin
239 # Dictionary entries for core built-in variables, constants
241 H_CFA = defExistingVar("H", H)
243 PSP0_CFA = defConst("PSP0", PSP0)
244 RSP0_CFA = defConst("RSP0", RSP0)
246 defConst("DOCOL", DOCOL)
247 defConst("DOCON", DOCON)
248 defConst("DOVAR", DOVAR)
250 defConst("DICT", DICT)
251 defConst("MEMSIZE", size_mem)
253 F_IMMED_CFA = defConst("F_IMMED", F_IMMED)
254 F_HIDDEN_CFA = defConst("F_HIDDEN", F_HIDDEN)
255 F_LENMASK_CFA = defConst("F_LENMASK", F_LENMASK)
256 NFA_MARK_CFA = defConst("NFA_MARK", NFA_MARK)
258 # Basic forth primitives
260 DROP_CFA = defPrimWord("DROP", () -> begin
265 SWAP_CFA = defPrimWord("SWAP", () -> begin
273 DUP_CFA = defPrimWord("DUP", () -> begin
279 OVER_CFA = defPrimWord("OVER", () -> begin
281 pushPS(mem[reg.PSP-1])
285 ROT_CFA = defPrimWord("ROT", () -> begin
295 NROT_CFA = defPrimWord("-ROT", () -> begin
306 TWODROP_CFA = defPrimWord("2DROP", () -> begin
312 TWODUP_CFA = defPrimWord("2DUP", () -> begin
321 TWOSWAP_CFA = defPrimWord("2SWAP", () -> begin
333 TWOOVER_CFA = defPrimWord("2OVER", () -> begin
342 QDUP_CFA = defPrimWord("?DUP", () -> begin
351 INCR_CFA = defPrimWord("1+", () -> begin
357 DECR_CFA = defPrimWord("1-", () -> begin
363 INCR2_CFA = defPrimWord("2+", () -> begin
369 DECR2_CFA = defPrimWord("2-", () -> begin
375 ADD_CFA = defPrimWord("+", () -> begin
382 SUB_CFA = defPrimWord("-", () -> begin
389 MUL_CFA = defPrimWord("*", () -> begin
396 DIVMOD_CFA = defPrimWord("/MOD", () -> begin
405 TWOMUL_CFA = defPrimWord("2*", () -> begin
410 TWODIV_CFA = defPrimWord("2/", () -> begin
415 EQ_CFA = defPrimWord("=", () -> begin
418 pushPS(a==b ? -1 : 0)
422 NE_CFA = defPrimWord("<>", () -> begin
425 pushPS(a!=b ? -1 : 0)
429 LT_CFA = defPrimWord("<", () -> begin
436 GT_CFA = defPrimWord(">", () -> begin
443 LE_CFA = defPrimWord("<=", () -> begin
446 pushPS(a<=b ? -1 : 0)
450 GE_CFA = defPrimWord(">=", () -> begin
453 pushPS(a>=b ? -1 : 0)
457 ZE_CFA = defPrimWord("0=", () -> begin
458 pushPS(popPS() == 0 ? -1 : 0)
462 ZNE_CFA = defPrimWord("0<>", () -> begin
463 pushPS(popPS() != 0 ? -1 : 0)
467 ZLT_CFA = defPrimWord("0<", () -> begin
468 pushPS(popPS() < 0 ? -1 : 0)
472 ZGT_CFA = defPrimWord("0>", () -> begin
473 pushPS(popPS() > 0 ? -1 : 0)
477 ZLE_CFA = defPrimWord("0<=", () -> begin
478 pushPS(popPS() <= 0 ? -1 : 0)
482 ZGE_CFA = defPrimWord("0>=", () -> begin
483 pushPS(popPS() >= 0 ? -1 : 0)
487 AND_CFA = defPrimWord("AND", () -> begin
494 OR_CFA = defPrimWord("OR", () -> begin
501 XOR_CFA = defPrimWord("XOR", () -> begin
508 INVERT_CFA = defPrimWord("INVERT", () -> begin
515 LIT_CFA = defPrimWord("LIT", () -> begin
523 STORE_CFA = defPrimWord("!", () -> begin
530 FETCH_CFA = defPrimWord("@", () -> begin
536 ADDSTORE_CFA = defPrimWord("+!", () -> begin
543 SUBSTORE_CFA = defPrimWord("-!", () -> begin
553 TOR_CFA = defPrimWord(">R", () -> begin
558 FROMR_CFA = defPrimWord("R>", () -> begin
563 RFETCH_CFA = defPrimWord("R@", () -> begin
568 RSPFETCH_CFA = defPrimWord("RSP@", () -> begin
573 RSPSTORE_CFA = defPrimWord("RSP!", () -> begin
578 RDROP_CFA = defPrimWord("RDROP", () -> begin
585 PSPFETCH_CFA = defPrimWord("PSP@", () -> begin
590 PSPSTORE_CFA = defPrimWord("PSP!", () -> begin
597 WFETCH_CFA = defPrimWord("W@", () -> begin
602 WSTORE_CFA = defPrimWord("W!", () -> begin
609 openFiles = Dict{Int64,IOStream}()
616 FAM_RO_CFA = defConst("R/O", FAM_RO)
617 FAM_WO_CFA = defConst("W/O", FAM_WO)
619 function fileOpener(create::Bool)
624 fname = getString(fnameAddr, fnameLen)
626 if create && !isfile(fname)
639 openFiles[nextFileID] = open(fname, mode)
646 OPEN_FILE_CFA = defPrimWord("OPEN-FILE", () -> begin
651 CREATE_FILE_CFA = defPrimWord("CREATE-FILE", () -> begin
656 CLOSE_FILE_CFA = defPrimWord("CLOSE-FILE", () -> begin
658 close(openFiles[fid])
659 delete!(openFiles, fid)
661 pushPS(0) # Result code 0
665 CLOSE_FILES_CFA = defPrimWord("CLOSE-FILES", () -> begin
666 for fh in values(openFiles)
671 pushPS(0) # Result code 0
675 READ_LINE_CFA = defPrimWord("READ-LINE", () -> begin
683 eofFlag = endswith(line, '\n') ? 0 : -1
686 #println("Reading: $line");
688 putString(line, addr, maxSize)
698 EMIT_CFA = defPrimWord("EMIT", () -> begin
703 function raw_mode!(mode::Bool)
704 if ccall(:jl_tty_set_mode, Int32, (Ptr{Void}, Int32), STDIN.handle, mode) != 0
705 throw("FATAL: Terminal unable to enter raw mode.")
711 byte = readbytes(STDIN, 1)[1]
723 KEY_CFA = defPrimWord("KEY", () -> begin
724 pushPS(Int(getKey()))
728 function getLineFromSTDIN()
732 slashIdx = findlast(chars, '\\')
735 return join(chars[slashIdx:length(chars)])
741 function backspaceStr(s, bsCount)
743 newLen = max(0, oldLen - bsCount)
744 return join(collect(s)[1:newLen])
753 return AbstractString(line)
757 return string("\x04")
763 line = backspaceStr(line, 1)
767 # Strip ANSI escape sequence
768 nextKey = Char(getKey())
771 nextKey = Char(getKey())
772 if nextKey >= '@' || nextKey <= '~'
779 # Currently do nothing
783 if haskey(REPLCompletions.latex_symbols, frag)
784 print(repeat("\b", length(frag)))
786 comp = REPLCompletions.latex_symbols[frag]
787 line = string(backspaceStr(line, length(frag)), comp)
794 line = string(line, key)
799 SPAN, SPAN_CFA = defNewVar("SPAN", 0)
800 EXPECT_CFA = defPrimWord("EXPECT", () -> begin
804 line = getLineFromSTDIN()
806 mem[SPAN] = min(length(line), maxLen)
807 putString(line, addr, maxLen)
812 BASE, BASE_CFA = defNewVar("BASE", 10)
813 NUMBER_CFA = defPrimWord("NUMBER", () -> begin
815 wordLen = mem[wordAddr-1]
817 s = getString(wordAddr, wordLen)
819 pushPS(parse(Int64, s, mem[BASE]))
824 # Dictionary searches
826 FROMLINK_CFA = defPrimWord("LINK>", () -> begin
829 lenAndFlags = mem[addr+1]
830 len = lenAndFlags & F_LENMASK
832 pushPS(addr + 2 + len)
837 NUMCONTEXT, NUMCONTEXT_CFA = defNewVar("#CONTEXT", 1)
839 createHeader("FORTH", 0)
841 dictWrite(defPrim(() -> begin
842 mem[CONTEXT + mem[NUMCONTEXT] - 1] = reg.W
845 dictWrite(0) # cell for latest
847 CURRENT_CFA = defExistingVar("CURRENT", CURRENT)
849 # Switch to new FORTH vocabulary cfa
850 mem[FORTH_CFA+1] = mem[mem[CURRENT]+1]
851 mem[CURRENT] = FORTH_CFA
853 CONTEXT, CONTEXT_CFA = defNewVar("CONTEXT", zeros(Int64, 10))
854 mem[CONTEXT] = FORTH_CFA
856 FINDVOCAB_CFA = defPrimWord("FINDVOCAB", () -> begin
858 countedAddr = popPS()
860 wordAddr = countedAddr + 1
861 wordLen = mem[countedAddr]
862 word = lowercase(getString(wordAddr, wordLen))
867 while (lfa = mem[lfa]) > 0
869 lenAndFlags = mem[lfa+1]
870 len = lenAndFlags & F_LENMASK
871 hidden = (lenAndFlags & F_HIDDEN) == F_HIDDEN
873 if hidden || len != wordLen
877 thisWord = lowercase(getString(lfa+2, len))
886 callPrim(mem[FROMLINK_CFA])
887 if (lenAndFlags & F_IMMED) == F_IMMED
900 FIND_CFA = defPrimWord("FIND", () -> begin
902 countedAddr = popPS()
903 context = mem[CONTEXT:(CONTEXT+mem[NUMCONTEXT]-1)]
905 for vocabCFA in reverse(context)
908 callPrim(mem[FINDVOCAB_CFA])
910 callPrim(mem[DUP_CFA])
928 BRANCH_CFA = defPrimWord("BRANCH", () -> begin
929 reg.IP += mem[reg.IP]
933 ZBRANCH_CFA = defPrimWord("0BRANCH", () -> begin
935 reg.IP += mem[reg.IP]
945 LITSTRING_CFA = defPrimWord("LITSTRING", () -> begin
955 TYPE_CFA = defPrimWord("TYPE", () -> begin
958 str = getString(addr, len)
963 # Interpreter/Compiler-specific I/O
965 TIB_CFA = defConst("TIB", TIB)
966 NUMTIB, NUMTIB_CFA = defNewVar("#TIB", 0)
968 FIB_CFA = defConst("FIB", FIB)
969 NUMFIB, NUMFIB_CFA = defNewVar("#FIB", 0)
971 IB_CFA = defPrimWord("IB", () -> begin
972 pushPS(mem[SOURCE_ID_VAR] == 0 ? TIB : FIB)
976 NUMIB_CFA = defPrimWord("#IB", () -> begin
977 pushPS(mem[SOURCE_ID_VAR] == 0 ? NUMTIB : NUMFIB)
981 TOIN, TOIN_CFA = defNewVar(">IN", 0)
983 SOURCE_ID_VAR, SOURCE_ID_VAR_CFA = defNewVar("SOURCE-ID-VAR", 0)
985 QUERY_CFA = defWord("QUERY",
986 [TIB_CFA, LIT_CFA, 160, EXPECT_CFA,
987 SPAN_CFA, FETCH_CFA, NUMTIB_CFA, STORE_CFA,
988 LIT_CFA, 0, TOIN_CFA, STORE_CFA,
991 EOF_FLAG, EOF_FLAG_CFA = defNewVar("EOF-FLAG", 0)
994 # EOF-FLAG set to true if EOF is reached
995 QUERY_FILE_CFA = defWord("QUERY-FILE",
996 [FIB_CFA, LIT_CFA, 160, ROT_CFA, READ_LINE_CFA,
997 DROP_CFA, EOF_FLAG_CFA, STORE_CFA,
998 NUMFIB_CFA, STORE_CFA,
999 LIT_CFA, 0, TOIN_CFA, STORE_CFA,
1002 WORD_CFA = defPrimWord("WORD", () -> begin
1005 if mem[SOURCE_ID_VAR] == 0
1013 # Chew up initial occurrences of delim
1014 while (mem[TOIN]<mem[sizeAddr] && mem[bufferAddr+mem[TOIN]] == delim)
1021 # Start reading in word
1023 while (mem[TOIN]<mem[sizeAddr])
1024 mem[addr] = mem[bufferAddr+mem[TOIN]]
1027 if (mem[addr] == delim)
1036 mem[countAddr] = count
1039 #println("Processing word: '$(getString(countAddr+1,mem[countAddr]))' (state $(mem[STATE]))")
1046 STATE, STATE_CFA = defNewVar("STATE", 0)
1048 COMMA_CFA = defPrimWord(",", () -> begin
1049 mem[mem[H]] = popPS()
1055 HERE_CFA = defWord("HERE",
1056 [H_CFA, FETCH_CFA, EXIT_CFA])
1058 HEADER_CFA = defPrimWord("HEADER", () -> begin
1059 wordAddr = popPS()+1
1060 wordLen = mem[wordAddr-1]
1061 word = getString(wordAddr, wordLen)
1063 createHeader(word, 0)
1068 CREATE_CFA = defWord("CREATE",
1069 [LIT_CFA, 32, WORD_CFA, HEADER_CFA,
1070 LIT_CFA, DOVAR, COMMA_CFA,
1073 DODOES = defPrim(() -> begin
1080 DOES_HELPER_CFA = defPrimWord("(DOES>)", () -> begin
1082 pushPS(mem[mem[CURRENT]+1])
1083 callPrim(mem[FROMLINK_CFA])
1086 runtimeAddr = popPS()
1088 mem[cfa] = defPrim(eval(:(() -> begin
1089 pushPS($(runtimeAddr))
1091 end)), name="doesPrim")
1094 end, flags=F_IMMED | F_HIDDEN)
1096 DOES_CFA = defWord("DOES>",
1097 [LIT_CFA, LIT_CFA, COMMA_CFA, HERE_CFA, LIT_CFA, 3, ADD_CFA, COMMA_CFA,
1098 LIT_CFA, DOES_HELPER_CFA, COMMA_CFA, LIT_CFA, EXIT_CFA, COMMA_CFA, EXIT_CFA],
1101 LBRAC_CFA = defPrimWord("[", () -> begin
1106 RBRAC_CFA = defPrimWord("]", () -> begin
1111 HIDDEN_CFA = defPrimWord("HIDDEN", () -> begin
1112 lenAndFlagsAddr = mem[mem[CURRENT]+1] + 1
1113 mem[lenAndFlagsAddr] = mem[lenAndFlagsAddr] $ F_HIDDEN
1117 COLON_CFA = defWord(":",
1118 [LIT_CFA, 32, WORD_CFA,
1120 LIT_CFA, DOCOL, COMMA_CFA,
1125 SEMICOLON_CFA = defWord(";",
1126 [LIT_CFA, EXIT_CFA, COMMA_CFA,
1129 EXIT_CFA], flags=F_IMMED)
1131 IMMEDIATE_CFA = defPrimWord("IMMEDIATE", () -> begin
1132 lenAndFlagsAddr = mem[mem[CURRENT]+1] + 1
1133 mem[lenAndFlagsAddr] = mem[lenAndFlagsAddr] $ F_IMMED
1137 CODE_CFA = defPrimWord("CODE", () -> begin
1139 callPrim(mem[WORD_CFA])
1140 callPrim(mem[HEADER_CFA])
1142 exprString = "() -> begin\n"
1144 if mem[TOIN] >= mem[NUMTIB]
1145 exprString = string(exprString, "\n")
1146 if currentSource() == STDIN
1152 callPrim(mem[EXPECT_CFA])
1153 mem[NUMTIB] = mem[SPAN]
1158 callPrim(mem[WORD_CFA])
1160 thisWord = getString(cAddr+1, mem[cAddr])
1162 if uppercase(thisWord) == "END-CODE"
1166 exprString = string(exprString, " ", thisWord)
1168 exprString = string(exprString, "\nreturn NEXT\nend")
1170 func = eval(parse(exprString))
1171 dictWrite(defPrim(func))
1178 EXECUTE_CFA = defPrimWord("EXECUTE", () -> begin
1183 INTERPRET_CFA = defWord("INTERPRET",
1184 [LIT_CFA, 32, WORD_CFA, # Read next space-delimited word
1186 DUP_CFA, FETCH_CFA, ZE_CFA, ZBRANCH_CFA, 3,
1187 DROP_CFA, EXIT_CFA, # Exit if input buffer is exhausted
1189 STATE_CFA, FETCH_CFA, ZBRANCH_CFA, 24,
1191 FIND_CFA, QDUP_CFA, ZBRANCH_CFA, 13,
1194 LIT_CFA, -1, EQ_CFA, INVERT_CFA, ZBRANCH_CFA, 4,
1196 # Immediate: Execute!
1197 EXECUTE_CFA, BRANCH_CFA, -26,
1199 # Not immediate: Compile!
1200 COMMA_CFA, BRANCH_CFA, -29,
1202 # No word found, parse number
1203 NUMBER_CFA, LIT_CFA, LIT_CFA, COMMA_CFA, COMMA_CFA, BRANCH_CFA, -36,
1206 FIND_CFA, QDUP_CFA, ZBRANCH_CFA, 5,
1208 # Found word. Execute!
1209 DROP_CFA, EXECUTE_CFA, BRANCH_CFA, -44,
1211 # No word found, parse number and leave on stack
1212 NUMBER_CFA, BRANCH_CFA, -47,
1215 PROMPT_CFA = defPrimWord("PROMPT", () -> begin
1224 QUIT_CFA = defWord("QUIT",
1225 [LIT_CFA, 0, STATE_CFA, STORE_CFA, # Set mode to interpret
1226 LIT_CFA, 0, SOURCE_ID_VAR_CFA, STORE_CFA, # Set terminal as input stream
1227 LIT_CFA, 0, NUMTIB_CFA, STORE_CFA, # Clear the input buffer
1228 RSP0_CFA, RSPSTORE_CFA, # Clear the return stack
1229 QUERY_CFA, # Read line of input
1230 INTERPRET_CFA, PROMPT_CFA, # Interpret line
1231 BRANCH_CFA,-4]) # Loop
1233 INCLUDED_CFA = defWord("INCLUDED",
1234 [LIT_CFA, 0, STATE_CFA, STORE_CFA, # Set mode to interpret
1235 FAM_RO_CFA, OPEN_FILE_CFA, DROP_CFA, # Open the file
1236 SOURCE_ID_VAR_CFA, FETCH_CFA, SWAP_CFA, # Store current source on stack
1237 SOURCE_ID_VAR_CFA, STORE_CFA, # Mark this as the current source
1238 SOURCE_ID_VAR_CFA, FETCH_CFA, QUERY_FILE_CFA, # Read line from file
1239 EOF_FLAG_CFA, FETCH_CFA,
1240 NUMFIB_CFA, FETCH_CFA, ZE_CFA, AND_CFA, # Test for EOF and empty line
1241 INVERT_CFA, ZBRANCH_CFA, 4, # Break out if EOF
1242 INTERPRET_CFA, # Interpret line
1243 BRANCH_CFA, -14, # Loop
1244 SOURCE_ID_VAR_CFA, FETCH_CFA,
1245 CLOSE_FILE_CFA, DROP_CFA, # Close file
1246 SOURCE_ID_VAR_CFA, STORE_CFA, # Restore input source
1249 INCLUDE_CFA = defWord("INCLUDE", [LIT_CFA, 32, WORD_CFA,
1251 SWAP_CFA, FETCH_CFA,
1252 INCLUDED_CFA, EXIT_CFA]);
1255 ABORT_CFA = defWord("ABORT",
1256 [CLOSE_FILES_CFA, DROP_CFA, PSP0_CFA, PSPSTORE_CFA, QUIT_CFA])
1258 BYE_CFA = defPrimWord("BYE", () -> begin
1263 EOF_CFA = defPrimWord("\x04", () -> begin
1270 initFileName = nothing
1271 if isfile("lib.4th")
1272 initFileName = "lib.4th"
1273 elseif isfile(Pkg.dir("forth","src", "lib.4th"))
1274 initFileName = Pkg.dir("forth","src","lib.4th")
1277 function run(;initialize=true)
1279 # Start with IP pointing to first instruction of outer interpreter
1282 # Load library files
1283 global initialized, initFileName
1284 if !initialized && initialize
1285 if initFileName != nothing
1286 print("Including definitions from $initFileName...")
1288 putString(initFileName, mem[H])
1290 pushPS(length(initFileName))
1291 pushRS(INCLUDED_CFA+1)
1295 println("No library file found. Only primitive words available.")
1300 # Primitive processing loop.
1301 # Everyting else is simply a consequence of this loop!
1305 #print("Entering prim $(getPrimName(jmp)), PS: ")
1311 showerror(STDOUT, ex)
1315 reg.IP = ABORT_CFA + 1
1323 TRACE_CFA = defPrimWord("TRACE", () -> begin
1324 println("reg.W: $(reg.W) reg.IP: $(reg.IP)")
1325 print("PS: "); printPS()
1326 print("RS: "); printRS()
1333 function dump(startAddr::Int64; count::Int64 = 100, cellsPerLine::Int64 = 10)
1334 chars = Array{Char,1}(cellsPerLine)
1336 lineStartAddr = cellsPerLine*div((startAddr-1),cellsPerLine) + 1
1337 endAddr = startAddr + count - 1
1339 q, r = divrem((endAddr-lineStartAddr+1), cellsPerLine)
1340 numLines = q + (r > 0 ? 1 : 0)
1346 for c in 1:cellsPerLine
1347 if i >= startAddr && i <= endAddr
1349 if mem[i]>=32 && mem[i]<128
1350 chars[c] = Char(mem[i])
1362 println("\t", AbstractString(chars))
1367 count = reg.PSP - PSP0
1371 for i in (PSP0+1):reg.PSP
1376 println("Parameter stack empty")
1381 count = reg.RSP - RSP0
1385 for i in (RSP0+1):reg.RSP
1390 println("Return stack empty")
1394 DUMP = defPrimWord("DUMP", () -> begin
1399 dump(addr, count=count)