transition to the operator precedence parser.

This commit is contained in:
Mark Thom
2017-09-06 00:36:14 -06:00
parent 8ee27af9fd
commit 92de7acd22
15 changed files with 335 additions and 3117 deletions

4
.gitmodules vendored Normal file
View File

@@ -0,0 +1,4 @@
[submodule "src/prolog/parser"]
path = src/prolog/parser
url = http://github.com/mthom/prolog-parser
branch = rusty-wam_branch

283
Cargo.lock generated
View File

@@ -1,9 +1,10 @@
[root]
name = "rusty-wam"
version = "0.6.7"
version = "0.7.0"
dependencies = [
"lalrpop 0.13.1 (registry+https://github.com/rust-lang/crates.io-index)",
"lalrpop-util 0.13.1 (registry+https://github.com/rust-lang/crates.io-index)",
"lazy_static 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)",
"num 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)",
"ordered-float 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)",
"regex 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
"termion 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
@@ -17,75 +18,23 @@ dependencies = [
]
[[package]]
name = "ascii-canvas"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"term 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "atty"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.24 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "bit-set"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"bit-vec 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "bit-vec"
version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "diff"
version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "docopt"
name = "bitflags"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "conv"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"lazy_static 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)",
"regex 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc-serialize 0.3.24 (registry+https://github.com/rust-lang/crates.io-index)",
"strsim 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)",
"custom_derive 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "either"
version = "1.1.0"
name = "custom_derive"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "ena"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "fixedbitset"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "itertools"
version = "0.5.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"either 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "kernel32-sys"
version = "0.2.2"
@@ -95,61 +44,6 @@ dependencies = [
"winapi-build 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "lalrpop"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"ascii-canvas 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
"atty 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
"bit-set 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
"diff 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)",
"docopt 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
"ena 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)",
"itertools 0.5.10 (registry+https://github.com/rust-lang/crates.io-index)",
"lalrpop-intern 0.13.1 (registry+https://github.com/rust-lang/crates.io-index)",
"lalrpop-snap 0.13.1 (registry+https://github.com/rust-lang/crates.io-index)",
"lalrpop-util 0.13.1 (registry+https://github.com/rust-lang/crates.io-index)",
"petgraph 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)",
"regex 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
"regex-syntax 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc-serialize 0.3.24 (registry+https://github.com/rust-lang/crates.io-index)",
"term 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
"unicode-xid 0.0.4 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "lalrpop-intern"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "lalrpop-snap"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"ascii-canvas 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
"atty 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
"bit-set 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
"diff 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)",
"docopt 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
"ena 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)",
"itertools 0.5.10 (registry+https://github.com/rust-lang/crates.io-index)",
"lalrpop-intern 0.13.1 (registry+https://github.com/rust-lang/crates.io-index)",
"lalrpop-util 0.13.1 (registry+https://github.com/rust-lang/crates.io-index)",
"petgraph 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)",
"regex 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
"regex-syntax 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc-serialize 0.3.24 (registry+https://github.com/rust-lang/crates.io-index)",
"term 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
"unicode-xid 0.0.4 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "lalrpop-util"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "lazy_static"
version = "0.2.8"
@@ -160,6 +54,23 @@ name = "libc"
version = "0.2.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "magenta"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"conv 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)",
"magenta-sys 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "magenta-sys"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"bitflags 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "memchr"
version = "1.0.1"
@@ -169,17 +80,87 @@ dependencies = [
]
[[package]]
name = "ordermap"
version = "0.2.10"
name = "num"
version = "0.1.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"num-bigint 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)",
"num-complex 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)",
"num-integer 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)",
"num-iter 0.1.34 (registry+https://github.com/rust-lang/crates.io-index)",
"num-rational 0.1.39 (registry+https://github.com/rust-lang/crates.io-index)",
"num-traits 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "num-bigint"
version = "0.1.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"num-integer 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)",
"num-traits 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)",
"rand 0.3.16 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc-serialize 0.3.24 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "num-complex"
version = "0.1.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"num-traits 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc-serialize 0.3.24 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "num-integer"
version = "0.1.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"num-traits 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "num-iter"
version = "0.1.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"num-integer 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)",
"num-traits 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "num-rational"
version = "0.1.39"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"num-bigint 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)",
"num-integer 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)",
"num-traits 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc-serialize 0.3.24 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "num-traits"
version = "0.1.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "petgraph"
version = "0.4.5"
name = "ordered-float"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"fixedbitset 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)",
"ordermap 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)",
"num-traits 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)",
"unreachable 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "rand"
version = "0.3.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"libc 0.2.24 (registry+https://github.com/rust-lang/crates.io-index)",
"magenta 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
@@ -204,20 +185,6 @@ name = "rustc-serialize"
version = "0.3.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "strsim"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "term"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "termion"
version = "1.4.0"
@@ -244,11 +211,6 @@ dependencies = [
"unreachable 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "unicode-xid"
version = "0.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "unreachable"
version = "0.1.1"
@@ -279,35 +241,30 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
[metadata]
"checksum aho-corasick 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)" = "500909c4f87a9e52355b26626d890833e9e1d53ac566db76c36faa984b889699"
"checksum ascii-canvas 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b385d69402821a1c254533a011a312531cbcc0e3e24f19bbb4747a5a2daf37e2"
"checksum atty 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "d0fd4c0631f06448cc45a6bbb3b710ebb7ff8ccb96a0800c994afe23a70d5df2"
"checksum bit-set 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d9bf6104718e80d7b26a68fdbacff3481cfc05df670821affc7e9cbc1884400c"
"checksum bit-vec 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)" = "02b4ff8b16e6076c3e14220b39fbc1fabb6737522281a388998046859400895f"
"checksum diff 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)" = "0a515461b6c8c08419850ced27bc29e86166dcdcde8fbe76f8b1f0589bb49472"
"checksum docopt 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ab32ea6e284d87987066f21a9e809a73c14720571ef34516f0890b3d355ccfd8"
"checksum either 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "18785c1ba806c258137c937e44ada9ee7e69a37e3c72077542cd2f069d78562a"
"checksum ena 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "cabe5a5078ac8c506d3e4430763b1ba9b609b1286913e7d08e581d1c2de9b7e5"
"checksum fixedbitset 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "fcf4412e2d11115c5ed81c2fbdaba8028de0c92553497aa771fc5f4e0c5c8793"
"checksum itertools 0.5.10 (registry+https://github.com/rust-lang/crates.io-index)" = "4833d6978da405305126af4ac88569b5d71ff758581ce5a987dbfa3755f694fc"
"checksum bitflags 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "aad18937a628ec6abcd26d1489012cc0e18c21798210f491af69ded9b881106d"
"checksum conv 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "78ff10625fd0ac447827aa30ea8b861fead473bb60aeb73af6c1c58caf0d1299"
"checksum custom_derive 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "ef8ae57c4978a2acd8b869ce6b9ca1dfe817bff704c220209fdef2c0b75a01b9"
"checksum kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d"
"checksum lalrpop 0.13.1 (registry+https://github.com/rust-lang/crates.io-index)" = "8ebe5a5c90d5edeecb7f62f6ebec0a3d0f6faf4759a052708348cda99fd311a0"
"checksum lalrpop-intern 0.13.1 (registry+https://github.com/rust-lang/crates.io-index)" = "05410c1e4aff497bdea1ccb274ac35536fda0ee858600df36966502d4f7acbe3"
"checksum lalrpop-snap 0.13.1 (registry+https://github.com/rust-lang/crates.io-index)" = "3f866ece35287f5223a1a022c5d86417c260cda2ca9c8a156af9959404ce5313"
"checksum lalrpop-util 0.13.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7c7743f235fc17f5f50f3b1e64a8690ee154f17f86bd68cbb78787c5b37907f7"
"checksum lazy_static 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)" = "3b37545ab726dd833ec6420aaba8231c5b320814b9029ad585555d2a03e94fbf"
"checksum libc 0.2.24 (registry+https://github.com/rust-lang/crates.io-index)" = "38f5c2b18a287cf78b4097db62e20f43cace381dc76ae5c0a3073067f78b7ddc"
"checksum magenta 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "4bf0336886480e671965f794bc9b6fce88503563013d1bfb7a502c81fe3ac527"
"checksum magenta-sys 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "40d014c7011ac470ae28e2f76a02bfea4a8480f73e701353b49ad7a8d75f4699"
"checksum memchr 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "1dbccc0e46f1ea47b9f17e6d67c5a96bd27030519c519c9c91327e31275a47b4"
"checksum ordermap 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)" = "c036a53e6bb62d7eee2edf7e087df56fd84c7bbae6a0bd93c2b9f54bddf62e03"
"checksum petgraph 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)" = "14c6ae5ccb73b438781abc93d35615019b1ad6e24b44116377fb819cfd7587de"
"checksum num 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)" = "a311b77ebdc5dd4cf6449d81e4135d9f0e3b153839ac90e648a8ef538f923525"
"checksum num-bigint 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)" = "8fd0f8dbb4c0960998958a796281d88c16fbe68d87b1baa6f31e2979e81fd0bd"
"checksum num-complex 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)" = "503e668405c5492d67cf662a81e05be40efe2e6bcf10f7794a07bd9865e704e6"
"checksum num-integer 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)" = "d1452e8b06e448a07f0e6ebb0bb1d92b8890eea63288c0b627331d53514d0fba"
"checksum num-iter 0.1.34 (registry+https://github.com/rust-lang/crates.io-index)" = "7485fcc84f85b4ecd0ea527b14189281cf27d60e583ae65ebc9c088b13dffe01"
"checksum num-rational 0.1.39 (registry+https://github.com/rust-lang/crates.io-index)" = "288629c76fac4b33556f4b7ab57ba21ae202da65ba8b77466e6d598e31990790"
"checksum num-traits 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)" = "99843c856d68d8b4313b03a17e33c4bb42ae8f6610ea81b28abe076ac721b9b0"
"checksum ordered-float 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "58d25b6c0e47b20d05226d288ff434940296e7e2f8b877975da32f862152241f"
"checksum rand 0.3.16 (registry+https://github.com/rust-lang/crates.io-index)" = "eb250fd207a4729c976794d03db689c9be1d634ab5a1c9da9492a13d8fecbcdf"
"checksum regex 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "1731164734096285ec2a5ec7fea5248ae2f5485b3feeb0115af4fda2183b2d1b"
"checksum regex-syntax 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)" = "ad890a5eef7953f55427c50575c680c42841653abd2b028b68cd223d157f62db"
"checksum rustc-serialize 0.3.24 (registry+https://github.com/rust-lang/crates.io-index)" = "dcf128d1287d2ea9d80910b5f1120d0b8eede3fbf1abe91c40d39ea7d51e6fda"
"checksum strsim 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b4d15c810519a91cf877e7e36e63fe068815c678181439f2f29e2562147c3694"
"checksum term 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)" = "fa63644f74ce96fbeb9b794f66aff2a52d601cbd5e80f4b97123e3899f4570f1"
"checksum termion 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "9105678ba52491a8e38e67be7842435ac44d7797b9b05bcdad370b0c84559615"
"checksum thread-id 3.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8df7875b676fddfadffd96deea3b1124e5ede707d4884248931077518cf1f773"
"checksum thread_local 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "c85048c6260d17cf486ceae3282d9fb6b90be220bf5b28c400f5485ffc29f0c7"
"checksum unicode-xid 0.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "8c1f860d7d29cf02cb2f3f359fd35991af3d30bac52c57d265a3c461074cb4dc"
"checksum unreachable 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "1f2ae5ddb18e1c92664717616dd9549dde73f539f01bd7b77c2edb2446bdff91"
"checksum utf8-ranges 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "662fab6525a98beff2921d7f61a39e7d59e0b425ebc7d0d9e66d316e55124122"
"checksum void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d"

View File

@@ -1,18 +1,13 @@
[package]
name = "rusty-wam"
version = "0.6.7"
version = "0.7.0"
authors = ["Mark Thom"]
build = "build.rs"
[dependencies]
lazy_static = "0.2"
num = "0.1"
regex = "0.2.1"
ordered-float = "0.5.0"
[dependencies.termion]
version = "1.4.0"
[dependencies.lalrpop-util]
version = "0.13.1"
[build-dependencies.lalrpop]
version = "0.13.1"
version = "1.4.0"

View File

@@ -17,8 +17,8 @@ Extend rusty-wam to include the following, among other features:
* call/N as a built-in meta-predicate (_done_).
* ISO Prolog compliant throw/catch (_done_).
* Built-in and user-defined operators of all fixities,
with custom associativity and precedence.
* Built-in and user-defined operators of all fixities, with custom
associativity and precedence (_in progress_).
* Bignum and floating point arithmetic.
* Built-in control operators (`,`, `;`, `->`, etc.).
* Attributed variables using the SICStus Prolog interface and

View File

@@ -1,5 +0,0 @@
extern crate lalrpop;
fn main() {
lalrpop::process_root().unwrap();
}

View File

@@ -1,8 +1,10 @@
#[macro_use] extern crate lazy_static;
extern crate termion;
mod prolog;
use prolog::io::*;
use prolog::machine::*;
use prolog::parser::toplevel::*;
#[cfg(test)]
mod tests {
@@ -12,8 +14,8 @@ mod tests {
fn submit(wam: &mut Machine, buffer: &str) -> bool {
wam.reset();
match parse_code(buffer.trim()) {
Some(tl) =>
match parse_code(buffer.trim(), wam.op_dir()) {
Ok(tl) =>
match eval(wam, &tl) {
EvalSession::InitialQuerySuccess(_, _) |
EvalSession::EntrySuccess |
@@ -21,7 +23,7 @@ mod tests {
true,
_ => false
},
None => panic!("Grammatical error of some kind!")
Err(e) => panic!("parse error: {:?}", e)
}
}
@@ -716,7 +718,7 @@ mod tests {
assert_eq!(submit(&mut wam, "?- catch(f(x), _, _)."), true);
assert_eq!(submit(&mut wam, "?- catch(f(y), _, _)."), true);
assert_eq!(submit(&mut wam, "?- catch(f(z), _, _)."), true);
submit(&mut wam, "f(success). f(E) :- catch(g(E), E, handle(E)).");
submit(&mut wam, "g(g_success). g(g_success_2). g(X) :- throw(X).");
submit(&mut wam, "handle(x). handle(y). handle(z). handle(v) :- throw(X).");
@@ -736,12 +738,12 @@ mod tests {
fn process_buffer(wam: &mut Machine, buffer: &str)
{
match parse_code(buffer.trim()) {
Some(tl) => {
match parse_code(buffer, wam.op_dir()) {
Ok(tl) => {
let result = eval(wam, &tl);
print(wam, result);
},
None => println!("Grammatical error!")
Err(s) => println!("{:?}", s)
};
}
@@ -760,7 +762,7 @@ fn prolog_repl() {
continue;
}
process_buffer(&mut wam, buffer.trim());
process_buffer(&mut wam, buffer.as_str());
wam.reset();
}
}

View File

@@ -1,13 +1,22 @@
use prolog::num::bigint::BigInt;
use prolog::ordered_float::*;
use std::cell::Cell;
use std::cmp::Ordering;
use std::collections::{HashMap, VecDeque};
use std::iter::*;
use std::fmt;
use std::io::Error as IOError;
use std::num::{ParseFloatError};
use std::ops::{Add, AddAssign};
use std::str::Utf8Error;
use std::vec::Vec;
pub type Atom = String;
pub type Var = String;
pub type Atom = String;
pub const LEXER_BUF_SIZE: usize = 4096;
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum GenContext {
@@ -58,38 +67,6 @@ pub enum TopLevel {
Rule(Rule)
}
impl TopLevel {
pub fn query_iter_mut<'a>(&'a mut self) -> Box<Iterator<Item=&'a mut QueryTerm> + 'a>
{
let mut iter: Box<Iterator<Item=&'a mut QueryTerm> + 'a> = Box::new(empty());
match self {
&mut TopLevel::Rule(Rule { head: (_, ref mut head), ref mut clauses }) => {
iter = Box::new(once(head));
iter = Box::new(iter.chain(clauses.iter_mut()));
},
&mut TopLevel::Query(ref mut clauses) =>
iter = Box::new(iter.chain(clauses.iter_mut())),
&mut TopLevel::Predicate(ref mut pred_clauses) =>
for pred_clause in pred_clauses.iter_mut() {
match pred_clause {
&mut PredicateClause::Rule(Rule { head: (_, ref mut head),
ref mut clauses })
=>
{
iter = Box::new(iter.chain(once(head)));
iter = Box::new(iter.chain(clauses.iter_mut()));
},
_ => {}
}
},
_ => {}
}
iter
}
}
#[derive(Clone, Copy)]
pub enum Level {
Deep, Shallow
@@ -142,13 +119,142 @@ impl Default for VarReg {
}
}
#[derive(Clone, Hash, PartialEq, Eq)]
pub type Specifier = u32;
pub const XFX: u32 = 0x0001;
pub const XFY: u32 = 0x0002;
pub const YFX: u32 = 0x0004;
pub const XF: u32 = 0x0010;
pub const YF: u32 = 0x0020;
pub const FX: u32 = 0x0040;
pub const FY: u32 = 0x0080;
pub const DELIMITER: u32 = 0x0100;
pub const TERM: u32 = 0x1000;
pub const LTERM: u32 = 0x3000;
macro_rules! is_term {
($x:expr) => ( ($x & TERM) != 0 )
}
macro_rules! is_lterm {
($x:expr) => ( ($x & LTERM) != 0 )
}
macro_rules! is_op {
($x:expr) => ( $x & (XF | YF | FX | FY | XFX | XFY | YFX) != 0 )
}
macro_rules! is_infix {
($x:expr) => ( ($x & (XFX | XFY | YFX)) != 0 )
}
macro_rules! is_xfx {
($x:expr) => ( ($x & XFX) != 0 )
}
macro_rules! is_xfy {
($x:expr) => ( ($x & XFY) != 0 )
}
macro_rules! is_yfx {
($x:expr) => ( ($x & YFX) != 0 )
}
macro_rules! is_yf {
($x:expr) => ( ($x & YF) != 0 )
}
macro_rules! is_xf {
($x:expr) => ( ($x & XF) != 0 )
}
macro_rules! is_fx {
($x:expr) => ( ($x & FX) != 0 )
}
macro_rules! is_fy {
($x:expr) => ( ($x & FY) != 0 )
}
macro_rules! prefix {
($x:expr) => ($x & (FX | FY))
}
/* 'TokenTooLong' is hard to detect reliably if we don't process the
input one character at a time. It would be easy to detect if the regex
library supported matching on iterator inputs, but it currently does
not. This is fine, mostly; the typical Prolog program will not contain
tokens exceeding 4096 chars in length. */
#[derive(Debug)]
pub enum ParserError
{
CommaArityMismatch,
UnexpectedEOF,
FailedMatch(String),
IO(IOError),
InadmissibleFact,
InadmissibleQueryTerm,
IncompleteReduction,
InconsistentPredicate,
ParseBigInt,
ParseFloat(ParseFloatError),
// TokenTooLong,
Utf8Conversion(Utf8Error)
}
impl From<IOError> for ParserError {
fn from(err: IOError) -> ParserError {
ParserError::IO(err)
}
}
impl From<Utf8Error> for ParserError {
fn from(err: Utf8Error) -> ParserError {
ParserError::Utf8Conversion(err)
}
}
impl From<ParseFloatError> for ParserError {
fn from(err: ParseFloatError) -> ParserError {
ParserError::ParseFloat(err)
}
}
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
pub enum Fixity {
In, Post, Pre
}
#[derive(Clone, Eq, Hash, PartialEq)]
pub enum Constant {
Atom(Atom),
BlockNum(usize),
Float(OrderedFloat<f64>),
Integer(BigInt),
String(String),
Usize(usize),
EmptyList
}
impl fmt::Display for Constant {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&Constant::Atom(ref atom) =>
write!(f, "{}", atom),
&Constant::EmptyList =>
write!(f, "[]"),
&Constant::Float(fl) =>
write!(f, "{}", fl),
&Constant::Integer(ref i) =>
write!(f, "{}", i),
&Constant::String(ref s) =>
write!(f, "{}", s),
&Constant::Usize(integer) =>
write!(f, "u{}", integer)
}
}
}
pub enum Term {
AnonVar,
Clause(Cell<RegType>, Atom, Vec<Box<Term>>),
@@ -193,7 +299,7 @@ pub enum ClauseType<'a> {
Catch,
Deep(Level, &'a Cell<RegType>, &'a Atom),
Root,
Throw
Throw,
}
impl<'a> ClauseType<'a> {
@@ -201,7 +307,7 @@ impl<'a> ClauseType<'a> {
match self {
ClauseType::CallN | ClauseType::Catch | ClauseType::Throw => Level::Shallow,
ClauseType::Deep(_, _, _) => Level::Deep,
ClauseType::Root => Level::Shallow
ClauseType::Root => Level::Shallow,
}
}
}
@@ -302,8 +408,8 @@ pub enum BuiltInInstruction {
IsAtomic,
IsVar,
ResetBlock,
SetBall,
Unify,
SetBall,
Unify,
UnwindStack
}
@@ -568,7 +674,7 @@ impl Term {
_ => None
}
}
pub fn arity(&self) -> usize {
match self {
&Term::Clause(_, _, ref child_terms) => child_terms.len(),

View File

@@ -10,9 +10,13 @@ pub enum PredicateKeyType {
User
}
pub type OpDirKey = (Atom, Fixity);
// name and fixity -> operator type and precedence.
pub type OpDir = HashMap<OpDirKey, (Specifier, usize)>;
pub type CodeDir = HashMap<PredicateKey, (PredicateKeyType, usize)>;
fn get_builtins() -> Code {
fn get_builtins() -> Code {
vec![internal_call_n!(), // callN/N, 0.
is_atomic!(), // atomic/1, 1.
proceed!(),
@@ -78,7 +82,7 @@ fn get_builtins() -> Code {
reset_block!(),
proceed!(),
trust_me!(), // 53.
allocate!(0),
allocate!(0),
query![get_var_in_query!(temp_v!(3), 1),
put_value!(temp_v!(2), 1)],
reset_block!(),
@@ -86,7 +90,7 @@ fn get_builtins() -> Code {
goto!(61, 0),
set_ball!(), // throw/1, 59.
unwind_stack!(),
fail!(), // false/0, 61.
fail!(), // false/0, 61.
try_me_else!(7), // not/1, 62.
allocate!(1),
get_level!(),
@@ -100,10 +104,16 @@ fn get_builtins() -> Code {
proceed!()]
}
pub fn build_code_dir() -> (Code, CodeDir) {
pub fn build_code_dir() -> (Code, CodeDir, OpDir)
{
let mut code_dir = HashMap::new();
let mut op_dir = HashMap::new();
let builtin_code = get_builtins();
op_dir.insert((String::from(":-"), Fixity::In), (XFX, 1200));
op_dir.insert((String::from("?-"), Fixity::Pre), (FX, 1200));
// there are 63 registers in the VM, so call/N is defined for all 0 <= N <= 62
// (an extra register is needed for the predicate name)
for arity in 0 .. 63 {
@@ -118,5 +128,5 @@ pub fn build_code_dir() -> (Code, CodeDir) {
code_dir.insert((String::from("catch"), 3), (PredicateKeyType::BuiltIn, 5));
code_dir.insert((String::from("throw"), 1), (PredicateKeyType::BuiltIn, 59));
(builtin_code, code_dir)
(builtin_code, code_dir, op_dir)
}

View File

@@ -2,7 +2,6 @@ use prolog::ast::*;
use prolog::codegen::*;
use prolog::debray_allocator::*;
use prolog::machine::*;
use prolog::prolog_parser::*;
use termion::raw::IntoRawMode;
use termion::input::TermRead;
@@ -10,20 +9,6 @@ use termion::event::Key;
use std::io::{Write, stdin, stdout};
use std::fmt;
use std::mem::swap;
impl fmt::Display for Constant {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&Constant::Atom(ref atom) =>
write!(f, "{}", atom),
&Constant::EmptyList =>
write!(f, "[]"),
&Constant::BlockNum(integer) =>
write!(f, "u{}", integer)
}
}
}
impl fmt::Display for FactInstruction {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
@@ -209,110 +194,6 @@ impl fmt::Display for RegType {
}
}
/*
// Wait until constexprs are supported in stable before trying to
// switch to this.
struct ClauseRewriter { field: fn(&mut Vec<Box<Term>>) -> QueryTerm }
impl Clone for ClauseRewriter {
fn clone(&self) -> Self {
ClauseRewriter { field: self.field }
}
}
struct ClauseRewriters {
rewriter_map: HashMap<&'static str, ClauseRewriter>
}
impl ClauseRewriters {
fn new() -> Self {
let mut rewriter_map =
[("call", ClauseRewriter { field: rewrite_call_N })]//,
//("catch", rewrite_catch),
//("throw", rewrite_throw)]
.iter().cloned().collect();
ClauseRewriters { rewriter_map: rewriter_map }
}
fn get(&self, name: &str) -> Option<&ClauseRewriter> {
self.rewriter_map.get(name)
}
}
*/
fn rewrite_call_n(terms: &mut Vec<Box<Term>>) -> QueryTerm {
let mut new_terms = Vec::with_capacity(0);
swap(&mut new_terms, terms);
QueryTerm::CallN(new_terms)
}
fn rewrite_catch(terms: &mut Vec<Box<Term>>) -> QueryTerm {
let mut new_terms = Vec::with_capacity(0);
swap(&mut new_terms, terms);
QueryTerm::Catch(new_terms)
}
fn rewrite_throw(terms: &mut Vec<Box<Term>>) -> QueryTerm {
let mut new_terms = Vec::with_capacity(0);
swap(&mut new_terms, terms);
QueryTerm::Throw(new_terms)
}
fn rewrite_clause(name: &Atom, terms: &mut Vec<Box<Term>>) -> Option<QueryTerm>
{
if name == "call" {
Some(rewrite_call_n(terms))
} else if name == "catch" && terms.len() == 3 {
Some(rewrite_catch(terms))
} else if name == "throw" && terms.len() == 1 {
Some(rewrite_throw(terms))
} else {
None
}
}
pub fn parse_code(input: &str) -> Option<TopLevel>
{
match parse_TopLevel(input) {
Ok(mut tl) => {
for query in tl.query_iter_mut() {
let new_query = match query {
&mut QueryTerm::Term(Term::Clause(_, ref name, ref mut cts)) =>
rewrite_clause(name, cts),
&mut QueryTerm::Term(Term::Var(_, _)) =>
Some(QueryTerm::CallN(Vec::new())),
_ => None
};
if let Some(mut new_query) = new_query {
swap(&mut new_query, query);
}
}
Some(tl)
},
Err(_) => None
}
}
fn is_consistent(predicate: &Vec<PredicateClause>) -> bool {
let name = predicate.first().unwrap().name();
let arity = predicate.first().unwrap().arity();
for clause in predicate.iter().skip(1) {
if !(name == clause.name() && arity == clause.arity()) {
return false;
}
}
true
}
#[allow(dead_code)]
pub fn print_code(code: &Code) {
for clause in code {
@@ -371,16 +252,9 @@ pub fn eval<'a, 'b: 'a>(wam: &'a mut Machine, tl: &'b TopLevel) -> EvalSession<'
match tl {
&TopLevel::Predicate(ref clauses) => {
let mut cg = CodeGenerator::<DebrayAllocator>::new();
if is_consistent(clauses) {
let compiled_pred = cg.compile_predicate(clauses);
wam.add_predicate(clauses, compiled_pred)
} else {
let msg = r"Error: predicate is inconsistent.
Each predicate must have the same name and arity.";
EvalSession::EntryFailure(String::from(msg))
}
let compiled_pred = cg.compile_predicate(clauses);
wam.add_predicate(clauses, compiled_pred)
},
&TopLevel::Fact(ref fact) => {
let mut cg = CodeGenerator::<DebrayAllocator>::new();

View File

@@ -53,15 +53,12 @@ impl<'a> QueryIterator<'a> {
fn from_term(term: &'a Term) -> Self {
let state = match term {
&Term::AnonVar =>
//IteratorState::AnonVar(Level::Shallow),
return QueryIterator { state_stack: vec![] },
&Term::Clause(_, _, ref terms) =>
IteratorState::Clause(0, ClauseType::Root, terms),
&Term::Cons(_, _, _) =>
//IteratorState::InitialCons(Level::Shallow, cell, head.as_ref(), tail.as_ref()),
return QueryIterator { state_stack: vec![] },
&Term::Constant(_, _) =>
//IteratorState::Constant(Level::Shallow, cell, constant),
return QueryIterator { state_stack: vec![] },
&Term::Var(ref cell, ref var) =>
IteratorState::Var(Level::Shallow, cell, var)

View File

@@ -36,7 +36,7 @@ struct MachineState {
tr: usize,
hb: usize,
block: usize, // an offset into the OR stack.
ball: (usize, Heap) // heap boundary, and a term copy
ball: (usize, Heap) // heap boundary, and a term copy
}
struct DuplicateTerm<'a> {
@@ -158,6 +158,7 @@ pub struct Machine {
ms: MachineState,
code: Code,
code_dir: CodeDir,
op_dir: OpDir,
cached_query: Option<Code>
}
@@ -205,12 +206,13 @@ impl Index<CodePtr> for Machine {
impl Machine {
pub fn new() -> Self {
let (code, code_dir) = build_code_dir();
let (code, code_dir, op_dir) = build_code_dir();
Machine {
ms: MachineState::new(),
code: code,
code_dir: code_dir,
op_dir: op_dir,
cached_query: None
}
}
@@ -484,12 +486,8 @@ impl Machine {
while let Some(view) = viewer.next() {
match view {
CellView::Con(&Constant::BlockNum(integer)) =>
result += integer.to_string().as_str(),
CellView::Con(&Constant::EmptyList) =>
result += "[]",
CellView::Con(&Constant::Atom(ref atom)) =>
result += atom.as_str(),
CellView::Con(ref r) =>
result += format!("{}", r).as_str(),
CellView::HeapVar(cell_num) => {
result += "_";
result += cell_num.to_string().as_str();
@@ -552,6 +550,10 @@ impl Machine {
pub fn reset(&mut self) {
self.ms.reset();
}
pub fn op_dir(&self) -> &OpDir {
&self.op_dir
}
}
impl MachineState {
@@ -1163,11 +1165,11 @@ impl MachineState {
fn throw_exception(&mut self, mut hcv: Vec<HeapCellValue>) {
let h = self.h;
self.registers[1] = Addr::HeapCell(h);
self.h += hcv.len();
self.heap.append(&mut hcv);
self.heap.append(&mut hcv);
self.goto_throw();
}
@@ -1256,7 +1258,7 @@ impl MachineState {
self.p += 1;
},
&BuiltInInstruction::GetCurrentBlock => {
let c = Constant::BlockNum(self.block);
let c = Constant::Usize(self.block);
let addr = self[temp_v!(1)].clone();
self.write_constant_to_var(addr, &c);
@@ -1297,10 +1299,9 @@ impl MachineState {
},
&BuiltInInstruction::SetBall => {
let addr = self[temp_v!(1)].clone();
self.ball.0 = self.h;
{
self.ball.0 = self.h;
let mut duplicator = DuplicateBallTerm::new(self);
duplicator.duplicate_term(addr);
}
@@ -1311,7 +1312,7 @@ impl MachineState {
let nb = self.store(self.deref(self[temp_v!(1)].clone()));
match nb {
Addr::Con(Constant::BlockNum(nb)) => {
Addr::Con(Constant::Usize(nb)) => {
let b = self.b - 1;
if nb > 0 && self.or_stack[b].b == nb {
@@ -1325,7 +1326,7 @@ impl MachineState {
},
&BuiltInInstruction::InstallNewBlock => {
self.block = self.b;
let c = Constant::BlockNum(self.block);
let c = Constant::Usize(self.block);
let addr = self[temp_v!(1)].clone();
self.write_constant_to_var(addr, &c);
@@ -1335,7 +1336,7 @@ impl MachineState {
let addr = self.deref(self[temp_v!(1)].clone());
match self.store(addr) {
Addr::Con(Constant::BlockNum(b)) => {
Addr::Con(Constant::Usize(b)) => {
self.block = b;
self.p += 1;
},

View File

@@ -1,6 +1,13 @@
extern crate num;
extern crate ordered_float;
pub mod allocator;
pub mod and_stack;
#[macro_use]
pub mod ast;
#[macro_use]
pub mod macros;
pub mod builtins;
pub mod codegen;
pub mod copier;
pub mod debray_allocator;
@@ -9,12 +16,7 @@ pub mod heapview;
pub mod indexing;
pub mod io;
pub mod iterators;
#[macro_use]
pub mod macros;
pub mod naive_allocator;
pub mod prolog_parser;
pub mod machine;
pub mod or_stack;
pub mod parser;
pub mod targets;
pub mod builtins;

1
src/prolog/parser Submodule

Submodule src/prolog/parser added at de2a1a7364

View File

@@ -1,93 +0,0 @@
use prolog::ast::*;
//use prolog::prolog_parser_utils::*;
use std::cell::Cell;
grammar;
pub TopLevel: TopLevel = {
"?-" <q:Query> "." => TopLevel::Query(q),
<Predicate> => TopLevel::Predicate(<>),
<Rule> "." => TopLevel::Rule(<>),
<Term> "." => TopLevel::Fact(<>)
};
Atom : Atom = {
r"[a-z][A-Za-z0-9_]*" => <>.trim().to_string(),
};
BoxedTerm : Box<Term> = {
<t:Term> => Box::new(t)
};
Clause : Term = {
<a: Atom> "(" <ts: (<BoxedTerm> ",")*> <t:BoxedTerm> ")" => {
let mut ts = ts;
ts.push(t);
Term::Clause(Cell::default(), a, ts)
}
};
List : Term = {
"[]" => Term::Constant(Cell::default(), Constant::EmptyList),
"[" <ListInternals> "]" => <>
};
ListInternals : Term = {
<t:BoxedTerm> => Term::Cons(Cell::default(),
t,
Box::new(Term::Constant(Cell::default(),
Constant::EmptyList))),
<t:BoxedTerm> "," <li: ListInternals> => Term::Cons(Cell::default(),
t,
Box::new(li)),
<t1:BoxedTerm> "|" <t2:BoxedTerm> => Term::Cons(Cell::default(), t1, t2)
};
Predicate : Vec<PredicateClause> = {
<pcs: (<PredicateClause>)+> <pc: PredicateClause> => {
let mut pcs = pcs;
pcs.push(pc);
pcs
}
};
PredicateClause : PredicateClause = {
<Rule> "." => PredicateClause::Rule(<>),
<Term> "." => PredicateClause::Fact(<>)
};
Query : Vec<QueryTerm> = {
<tcs: (<QueryTerm> ",")*> <tc: QueryTerm> => {
let mut tcs = tcs;
tcs.push(tc);
tcs
}
};
Rule : Rule = {
<c:Clause> ":-" <h:QueryTerm> <cs: ("," <QueryTerm>)*> =>
Rule { head: (c, h), clauses: cs },
<a:Atom> ":-" <h:QueryTerm> <cs: ("," <QueryTerm>)*> =>
Rule { head: (Term::Constant(Cell::default(), Constant::Atom(a)), h),
clauses: cs }
};
QueryTerm : QueryTerm = {
"!" => QueryTerm::Cut,
<Var> => QueryTerm::CallN(vec![Box::new(Term::Var(Cell::default(), <>))]),
<Clause> => QueryTerm::Term(<>),
<Atom> => QueryTerm::Term(Term::Constant(Cell::default(), Constant::Atom(<>)))
};
Term : Term = {
<Clause> => <>,
<Atom> => Term::Constant(Cell::default(), Constant::Atom(<>)),
<List> => <>,
<Var> => Term::Var(Cell::default(), <>),
"_" => Term::AnonVar
};
Var : Var = {
r"[A-Z][A-Za-z0-9_]*" => <>.trim().to_string()
};

File diff suppressed because it is too large Load Diff