single parser, multi purpose

This commit is contained in:
damirka 2022-02-15 20:54:00 +03:00
parent 3f6fc9ec76
commit 0878e4f85f
97 changed files with 874 additions and 5877 deletions

310
Cargo.lock generated
View File

@ -127,34 +127,13 @@ version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "block-buffer"
version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0940dc441f31689269e10ac70eb1002a3a1d3ad1390e030043662eb7fe4688b"
dependencies = [
"block-padding",
"byte-tools",
"byteorder",
"generic-array 0.12.4",
]
[[package]] [[package]]
name = "block-buffer" name = "block-buffer"
version = "0.10.0" version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1d36a02058e76b040de25a4464ba1c80935655595b661505c8b39b664828b95" checksum = "f1d36a02058e76b040de25a4464ba1c80935655595b661505c8b39b664828b95"
dependencies = [ dependencies = [
"generic-array 0.14.5", "generic-array",
]
[[package]]
name = "block-padding"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa79dedbb091f449f1f39e53edf88d5dbe95f895dae6135a8d7b881fb5af73f5"
dependencies = [
"byte-tools",
] ]
[[package]] [[package]]
@ -175,12 +154,6 @@ version = "3.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4a45a46ab1f2412e53d3a0ade76ffad2025804294569aae387231a0cd6e0899" checksum = "a4a45a46ab1f2412e53d3a0ade76ffad2025804294569aae387231a0cd6e0899"
[[package]]
name = "byte-tools"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3b5ca7a04898ad4bcd41c90c5285445ff5b791899bb1b0abdd2a2aa791211d7"
[[package]] [[package]]
name = "byteorder" name = "byteorder"
version = "1.4.3" version = "1.4.3"
@ -362,7 +335,7 @@ dependencies = [
"clap 2.34.0", "clap 2.34.0",
"criterion-plot", "criterion-plot",
"csv", "csv",
"itertools 0.10.3", "itertools",
"lazy_static", "lazy_static",
"num-traits", "num-traits",
"oorandom", "oorandom",
@ -384,7 +357,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d00996de9f2f7559f7f4dc286073197f83e92256a59ed395f9aac01fe717da57" checksum = "d00996de9f2f7559f7f4dc286073197f83e92256a59ed395f9aac01fe717da57"
dependencies = [ dependencies = [
"cast", "cast",
"itertools 0.10.3", "itertools",
] ]
[[package]] [[package]]
@ -437,7 +410,7 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "683d6b536309245c849479fba3da410962a43ed8e51c26b729208ec0ac2798d0" checksum = "683d6b536309245c849479fba3da410962a43ed8e51c26b729208ec0ac2798d0"
dependencies = [ dependencies = [
"generic-array 0.14.5", "generic-array",
] ]
[[package]] [[package]]
@ -468,9 +441,9 @@ version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fcc3dd5e9e9c0b295d6e1e4d811fb6f157d5ffd784b8d202fc62eac8035a770b" checksum = "fcc3dd5e9e9c0b295d6e1e4d811fb6f157d5ffd784b8d202fc62eac8035a770b"
dependencies = [ dependencies = [
"proc-macro2 1.0.36", "proc-macro2",
"quote 1.0.15", "quote",
"syn 1.0.86", "syn",
] ]
[[package]] [[package]]
@ -479,24 +452,15 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8" checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8"
[[package]]
name = "digest"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3d0c8c8752312f9713efd397ff63acb9f85585afbf179282e720e7704954dd5"
dependencies = [
"generic-array 0.12.4",
]
[[package]] [[package]]
name = "digest" name = "digest"
version = "0.10.1" version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b697d66081d42af4fba142d56918a3cb21dc8eb63372c6b85d14f44fb9c5979b" checksum = "b697d66081d42af4fba142d56918a3cb21dc8eb63372c6b85d14f44fb9c5979b"
dependencies = [ dependencies = [
"block-buffer 0.10.0", "block-buffer",
"crypto-common", "crypto-common",
"generic-array 0.14.5", "generic-array",
] ]
[[package]] [[package]]
@ -566,34 +530,6 @@ dependencies = [
"once_cell", "once_cell",
] ]
[[package]]
name = "failure"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d32e9bd16cc02eae7db7ef620b392808b89f6a5e16bb3497d159c6b92a0f4f86"
dependencies = [
"backtrace",
"failure_derive",
]
[[package]]
name = "failure_derive"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa4da3c766cd7a0db8242e326e9e4e081edd567072893ed320008189715366a4"
dependencies = [
"proc-macro2 1.0.36",
"quote 1.0.15",
"syn 1.0.86",
"synstructure",
]
[[package]]
name = "fake-simd"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e88a8acf291dafb59c2d96e8f59828f3838bb1a70398823ade51a84de6a6deed"
[[package]] [[package]]
name = "fastrand" name = "fastrand"
version = "1.7.0" version = "1.7.0"
@ -776,15 +712,6 @@ dependencies = [
"byteorder", "byteorder",
] ]
[[package]]
name = "generic-array"
version = "0.12.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ffdf9f34f1447443d37393cc6c2b8313aebddcd96906caf34e54c68d8e57d7bd"
dependencies = [
"typenum",
]
[[package]] [[package]]
name = "generic-array" name = "generic-array"
version = "0.14.5" version = "0.14.5"
@ -1036,15 +963,6 @@ version = "2.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68f2d64f2edebec4ce84ad108148e67e1064789bee435edc5b60ad398714a3a9" checksum = "68f2d64f2edebec4ce84ad108148e67e1064789bee435edc5b60ad398714a3a9"
[[package]]
name = "itertools"
version = "0.7.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d47946d458e94a1b7bcabbf6521ea7c037062c81f534615abcad76e84d4970d"
dependencies = [
"either",
]
[[package]] [[package]]
name = "itertools" name = "itertools"
version = "0.10.3" version = "0.10.3"
@ -1146,18 +1064,6 @@ dependencies = [
"thiserror", "thiserror",
] ]
[[package]]
name = "leo-input"
version = "1.5.3"
dependencies = [
"from-pest",
"pest",
"pest-ast",
"pest_derive",
"thiserror",
"tracing",
]
[[package]] [[package]]
name = "leo-lang" name = "leo-lang"
version = "1.5.3" version = "1.5.3"
@ -1217,7 +1123,6 @@ dependencies = [
"lazy_static", "lazy_static",
"leo-ast", "leo-ast",
"leo-errors", "leo-errors",
"leo-input",
"leo-span", "leo-span",
"leo-test-framework", "leo-test-framework",
"serde", "serde",
@ -1279,12 +1184,6 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4" checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4"
[[package]]
name = "maplit"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d"
[[package]] [[package]]
name = "matches" name = "matches"
version = "0.1.9" version = "0.1.9"
@ -1549,12 +1448,6 @@ version = "11.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575" checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575"
[[package]]
name = "opaque-debug"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2839e79665f131bdb5782e51f2c6c9599c133c6098982a54c794358bf432529c"
[[package]] [[package]]
name = "openssl" name = "openssl"
version = "0.10.38" version = "0.10.38"
@ -1612,53 +1505,6 @@ dependencies = [
"ucd-trie", "ucd-trie",
] ]
[[package]]
name = "pest-ast"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3fbf404899169771dd6a32c84248b83cd67a26cc7cc957aac87661490e1227e4"
dependencies = [
"itertools 0.7.11",
"proc-macro2 0.4.30",
"quote 0.6.13",
"single",
"syn 0.15.44",
]
[[package]]
name = "pest_derive"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "833d1ae558dc601e9a60366421196a8d94bc0ac980476d0b67e1d0988d72b2d0"
dependencies = [
"pest",
"pest_generator",
]
[[package]]
name = "pest_generator"
version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "99b8db626e31e5b81787b9783425769681b347011cc59471e33ea46d2ea0cf55"
dependencies = [
"pest",
"pest_meta",
"proc-macro2 1.0.36",
"quote 1.0.15",
"syn 1.0.86",
]
[[package]]
name = "pest_meta"
version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "54be6e404f5317079812fc8f9f5279de376d8856929e21c184ecf6bbd692a11d"
dependencies = [
"maplit",
"pest",
"sha-1",
]
[[package]] [[package]]
name = "pin-project-lite" name = "pin-project-lite"
version = "0.2.8" version = "0.2.8"
@ -1718,7 +1564,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5aab5be6e4732b473071984b3164dbbfb7a3674d30ea5ff44410b6bcd960c3c" checksum = "a5aab5be6e4732b473071984b3164dbbfb7a3674d30ea5ff44410b6bcd960c3c"
dependencies = [ dependencies = [
"difflib", "difflib",
"itertools 0.10.3", "itertools",
"predicates-core", "predicates-core",
] ]
@ -1754,9 +1600,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c"
dependencies = [ dependencies = [
"proc-macro-error-attr", "proc-macro-error-attr",
"proc-macro2 1.0.36", "proc-macro2",
"quote 1.0.15", "quote",
"syn 1.0.86", "syn",
"version_check", "version_check",
] ]
@ -1766,27 +1612,18 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869"
dependencies = [ dependencies = [
"proc-macro2 1.0.36", "proc-macro2",
"quote 1.0.15", "quote",
"version_check", "version_check",
] ]
[[package]]
name = "proc-macro2"
version = "0.4.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf3d2011ab5c909338f7887f4fc896d35932e29146c12c8d01da6b22a80ba759"
dependencies = [
"unicode-xid 0.1.0",
]
[[package]] [[package]]
name = "proc-macro2" name = "proc-macro2"
version = "1.0.36" version = "1.0.36"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c7342d5883fbccae1cc37a2353b09c87c9b0f3afd73f5fb9bba687a1f733b029" checksum = "c7342d5883fbccae1cc37a2353b09c87c9b0f3afd73f5fb9bba687a1f733b029"
dependencies = [ dependencies = [
"unicode-xid 0.2.2", "unicode-xid",
] ]
[[package]] [[package]]
@ -1798,22 +1635,13 @@ dependencies = [
"memchr", "memchr",
] ]
[[package]]
name = "quote"
version = "0.6.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce23b6b870e8f94f81fb0a363d65d86675884b34a09043c81e5562f11c1f8e1"
dependencies = [
"proc-macro2 0.4.30",
]
[[package]] [[package]]
name = "quote" name = "quote"
version = "1.0.15" version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "864d3e96a899863136fc6e99f3d7cae289dafe43bf2c5ac19b70df7210c0a145" checksum = "864d3e96a899863136fc6e99f3d7cae289dafe43bf2c5ac19b70df7210c0a145"
dependencies = [ dependencies = [
"proc-macro2 1.0.36", "proc-macro2",
] ]
[[package]] [[package]]
@ -2164,9 +1992,9 @@ version = "1.0.136"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08597e7152fcd306f41838ed3e37be9eaeed2b61c42e2117266a554fab4662f9" checksum = "08597e7152fcd306f41838ed3e37be9eaeed2b61c42e2117266a554fab4662f9"
dependencies = [ dependencies = [
"proc-macro2 1.0.36", "proc-macro2",
"quote 1.0.15", "quote",
"syn 1.0.86", "syn",
] ]
[[package]] [[package]]
@ -2205,18 +2033,6 @@ dependencies = [
"yaml-rust", "yaml-rust",
] ]
[[package]]
name = "sha-1"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f7d94d0bede923b3cea61f3f1ff57ff8cdfd77b400fb8f9998949e0cf04163df"
dependencies = [
"block-buffer 0.7.3",
"digest 0.8.1",
"fake-simd",
"opaque-debug",
]
[[package]] [[package]]
name = "sha2" name = "sha2"
version = "0.10.1" version = "0.10.1"
@ -2225,7 +2041,7 @@ checksum = "99c3bd8169c58782adad9290a9af5939994036b76187f7b4f0e6de91dbbfc0ec"
dependencies = [ dependencies = [
"cfg-if 1.0.0", "cfg-if 1.0.0",
"cpufeatures", "cpufeatures",
"digest 0.10.1", "digest",
] ]
[[package]] [[package]]
@ -2237,15 +2053,6 @@ dependencies = [
"lazy_static", "lazy_static",
] ]
[[package]]
name = "single"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bd5add732a1ab689845591a1b50339cf5310b563e08dc5813c65991f30369ea2"
dependencies = [
"failure",
]
[[package]] [[package]]
name = "slab" name = "slab"
version = "0.4.5" version = "0.4.5"
@ -2268,9 +2075,9 @@ source = "git+https://github.com/AleoHQ/snarkVM.git?rev=51633e2#51633e2fac247bc8
dependencies = [ dependencies = [
"proc-macro-crate", "proc-macro-crate",
"proc-macro-error", "proc-macro-error",
"proc-macro2 1.0.36", "proc-macro2",
"quote 1.0.15", "quote",
"syn 1.0.86", "syn",
] ]
[[package]] [[package]]
@ -2280,7 +2087,7 @@ source = "git+https://github.com/AleoHQ/snarkVM.git?rev=51633e2#51633e2fac247bc8
dependencies = [ dependencies = [
"anyhow", "anyhow",
"bincode", "bincode",
"itertools 0.10.3", "itertools",
"num-bigint", "num-bigint",
"rand 0.8.4", "rand 0.8.4",
"serde", "serde",
@ -2329,20 +2136,9 @@ checksum = "dcb5ae327f9cc13b68763b5749770cb9e048a99bd9dfdfa58d0cf05d5f64afe0"
dependencies = [ dependencies = [
"heck", "heck",
"proc-macro-error", "proc-macro-error",
"proc-macro2 1.0.36", "proc-macro2",
"quote 1.0.15", "quote",
"syn 1.0.86", "syn",
]
[[package]]
name = "syn"
version = "0.15.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ca4b3b69a77cbe1ffc9e198781b7acb0c7365a883670e8f1c1bc66fba79a5c5"
dependencies = [
"proc-macro2 0.4.30",
"quote 0.6.13",
"unicode-xid 0.1.0",
] ]
[[package]] [[package]]
@ -2351,21 +2147,9 @@ version = "1.0.86"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a65b3f4ffa0092e9887669db0eae07941f023991ab58ea44da8fe8e2d511c6b" checksum = "8a65b3f4ffa0092e9887669db0eae07941f023991ab58ea44da8fe8e2d511c6b"
dependencies = [ dependencies = [
"proc-macro2 1.0.36", "proc-macro2",
"quote 1.0.15", "quote",
"unicode-xid 0.2.2", "unicode-xid",
]
[[package]]
name = "synstructure"
version = "0.12.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f36bdaa60a83aca3921b5259d5400cbf5e90fc51931376a9bd4a0eb79aa7210f"
dependencies = [
"proc-macro2 1.0.36",
"quote 1.0.15",
"syn 1.0.86",
"unicode-xid 0.2.2",
] ]
[[package]] [[package]]
@ -2457,9 +2241,9 @@ version = "1.0.30"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa32fd3f627f367fe16f893e2597ae3c05020f8bba2666a4e6ea73d377e5714b" checksum = "aa32fd3f627f367fe16f893e2597ae3c05020f8bba2666a4e6ea73d377e5714b"
dependencies = [ dependencies = [
"proc-macro2 1.0.36", "proc-macro2",
"quote 1.0.15", "quote",
"syn 1.0.86", "syn",
] ]
[[package]] [[package]]
@ -2578,9 +2362,9 @@ version = "0.1.18"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f4f480b8f81512e825f337ad51e94c1eb5d3bbdf2b363dcd01e2b19a9ffe3f8e" checksum = "f4f480b8f81512e825f337ad51e94c1eb5d3bbdf2b363dcd01e2b19a9ffe3f8e"
dependencies = [ dependencies = [
"proc-macro2 1.0.36", "proc-macro2",
"quote 1.0.15", "quote",
"syn 1.0.86", "syn",
] ]
[[package]] [[package]]
@ -2671,12 +2455,6 @@ version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ed742d4ea2bd1176e236172c8429aaf54486e7ac098db29ffe6529e0ce50973" checksum = "3ed742d4ea2bd1176e236172c8429aaf54486e7ac098db29ffe6529e0ce50973"
[[package]]
name = "unicode-xid"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc"
[[package]] [[package]]
name = "unicode-xid" name = "unicode-xid"
version = "0.2.2" version = "0.2.2"
@ -2786,9 +2564,9 @@ dependencies = [
"bumpalo", "bumpalo",
"lazy_static", "lazy_static",
"log", "log",
"proc-macro2 1.0.36", "proc-macro2",
"quote 1.0.15", "quote",
"syn 1.0.86", "syn",
"wasm-bindgen-shared", "wasm-bindgen-shared",
] ]
@ -2810,7 +2588,7 @@ version = "0.2.79"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f4203d69e40a52ee523b2529a773d5ffc1dc0071801c87b3d270b471b80ed01" checksum = "2f4203d69e40a52ee523b2529a773d5ffc1dc0071801c87b3d270b471b80ed01"
dependencies = [ dependencies = [
"quote 1.0.15", "quote",
"wasm-bindgen-macro-support", "wasm-bindgen-macro-support",
] ]
@ -2820,9 +2598,9 @@ version = "0.2.79"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bfa8a30d46208db204854cadbb5d4baf5fcf8071ba5bf48190c3e59937962ebc" checksum = "bfa8a30d46208db204854cadbb5d4baf5fcf8071ba5bf48190c3e59937962ebc"
dependencies = [ dependencies = [
"proc-macro2 1.0.36", "proc-macro2",
"quote 1.0.15", "quote",
"syn 1.0.86", "syn",
"wasm-bindgen-backend", "wasm-bindgen-backend",
"wasm-bindgen-shared", "wasm-bindgen-shared",
] ]

View File

@ -63,9 +63,6 @@ version = "1.5.3"
#path = "./imports" #path = "./imports"
#version = "1.5.3" #version = "1.5.3"
# #
#[dependencies.leo-input]
#path = "./input"
#version = "1.5.3"
[dependencies.leo-package] [dependencies.leo-package]
path = "./package" path = "./package"

View File

@ -1,412 +0,0 @@
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{ArrayDimensions, Char, CharValue, GroupValue, IntegerType};
use leo_input::{
errors::InputParserError,
expressions::{ArrayInitializerExpression, ArrayInlineExpression, Expression, StringExpression, TupleExpression},
types::{ArrayType, CharType, DataType, IntegerType as InputIntegerType, TupleType, Type},
values::{
Address, AddressValue, BooleanValue, CharValue as InputCharValue, FieldValue, GroupValue as InputGroupValue,
IntegerValue, NumberValue, Value,
},
};
use leo_span::Span as AstSpan;
use pest::Span;
use std::fmt;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum InputValue {
Address(String),
Boolean(bool),
Char(CharValue),
Field(String),
Group(GroupValue),
Integer(IntegerType, String),
Array(Vec<InputValue>),
Tuple(Vec<InputValue>),
}
impl InputValue {
fn from_address(address: Address) -> Self {
InputValue::Address(address.value)
}
fn from_address_value(value: AddressValue) -> Self {
match value {
AddressValue::Explicit(address) => Self::from_address(address.address),
AddressValue::Implicit(address) => Self::from_address(address),
}
}
fn from_boolean(boolean: BooleanValue) -> Result<Self, InputParserError> {
let boolean = boolean.value.parse::<bool>()?;
Ok(InputValue::Boolean(boolean))
}
fn from_char(input_character: InputCharValue) -> Result<Self, InputParserError> {
let character = match input_character.value.inner()? {
leo_input::values::Char::Scalar(scalar) => Char::Scalar(scalar),
leo_input::values::Char::NonScalar(non_scalar) => Char::NonScalar(non_scalar),
};
let span = AstSpan::from(input_character.span);
Ok(InputValue::Char(CharValue { character, span }))
}
fn from_number(integer_type: InputIntegerType, number: String) -> Self {
InputValue::Integer(integer_type.into(), number)
}
fn from_group(group: InputGroupValue) -> Self {
InputValue::Group(GroupValue::from(group))
}
fn from_field(field: FieldValue) -> Self {
InputValue::Field(field.number.to_string())
}
fn from_implicit(data_type: DataType, implicit: NumberValue) -> Result<Self, InputParserError> {
match data_type {
DataType::Address(_) => Err(InputParserError::implicit_type(data_type, implicit)),
DataType::Boolean(_) => Err(InputParserError::implicit_type(data_type, implicit)),
DataType::Char(_) => Err(InputParserError::implicit_type(data_type, implicit)),
DataType::Integer(integer_type) => Ok(InputValue::from_number(integer_type, implicit.to_string())),
DataType::Group(_) => Err(InputParserError::implicit_group(implicit)),
DataType::Field(_) => Ok(InputValue::Field(implicit.to_string())),
}
}
fn from_value(data_type: DataType, value: Value) -> Result<Self, InputParserError> {
match (data_type, value) {
(DataType::Address(_), Value::Address(address)) => Ok(InputValue::from_address_value(address)),
(DataType::Boolean(_), Value::Boolean(boolean)) => InputValue::from_boolean(boolean),
(DataType::Char(_), Value::Char(character)) => InputValue::from_char(character),
(DataType::Integer(integer_type), Value::Integer(integer)) => {
match integer.clone() {
IntegerValue::Signed(signed) => {
if let InputIntegerType::Signed(inner) = integer_type.clone() {
let singed_type = signed.clone().type_;
if std::mem::discriminant(&inner) != std::mem::discriminant(&singed_type) {
return Err(InputParserError::integer_type_mismatch(
integer_type,
InputIntegerType::Signed(singed_type),
integer.span(),
));
}
}
}
IntegerValue::Unsigned(unsigned) => {
if let InputIntegerType::Unsigned(inner) = integer_type.clone() {
let unsinged_type = unsigned.clone().type_;
if std::mem::discriminant(&inner) != std::mem::discriminant(&unsinged_type) {
return Err(InputParserError::integer_type_mismatch(
integer_type,
InputIntegerType::Unsigned(unsinged_type),
integer.span(),
));
}
}
}
}
Ok(InputValue::from_number(integer_type, integer.to_string()))
}
(DataType::Group(_), Value::Group(group)) => Ok(InputValue::from_group(group)),
(DataType::Field(_), Value::Field(field)) => Ok(InputValue::from_field(field)),
(data_type, Value::Implicit(implicit)) => InputValue::from_implicit(data_type, implicit),
(data_type, value) => Err(InputParserError::data_type_mismatch(data_type, value)),
}
}
pub(crate) fn from_expression(type_: Type, expression: Expression) -> Result<Self, InputParserError> {
match (type_, expression) {
(Type::Basic(data_type), Expression::Value(value)) => InputValue::from_value(data_type, value),
(Type::Array(array_type), Expression::ArrayInline(inline)) => {
InputValue::from_array_inline(array_type, inline)
}
(Type::Array(array_type), Expression::ArrayInitializer(initializer)) => {
InputValue::from_array_initializer(array_type, initializer)
}
(Type::Array(array_type), Expression::StringExpression(string)) => {
InputValue::from_string(array_type, string)
}
(Type::Tuple(tuple_type), Expression::Tuple(tuple)) => InputValue::from_tuple(tuple_type, tuple),
(type_, expression) => Err(InputParserError::expression_type_mismatch(type_, expression)),
}
}
///
/// Returns a new `InputValue` from the given `ArrayType` and `StringExpression`.
///
pub(crate) fn from_string(mut array_type: ArrayType, string: StringExpression) -> Result<Self, InputParserError> {
// Create a new `ArrayDimensions` type from the input array_type dimensions.
let array_dimensions_type = ArrayDimensions::from(array_type.dimensions.clone());
assert!(matches!(*array_type.type_, Type::Basic(DataType::Char(CharType {}))));
// Convert the array dimensions to usize.
let array_dimensions = parse_array_dimensions(array_dimensions_type, &array_type.span)?;
// Return an error if the outer array dimension does not equal the number of array elements.
if array_dimensions[0] != string.chars.len() {
return Err(InputParserError::invalid_string_length(
array_dimensions[0],
string.chars.len(),
&string.span,
));
}
array_type.dimensions = array_type.dimensions.next_dimension();
let inner_array_type = if array_dimensions.len() == 1 {
// This is a single array
*array_type.type_
} else {
// This is a multi-dimensional array
return Err(InputParserError::invalid_string_dimensions(&array_type.span));
};
let mut elements = Vec::with_capacity(string.chars.len());
for character in string.chars.into_iter() {
let element = InputValue::from_expression(
inner_array_type.clone(),
Expression::Value(Value::Char(InputCharValue {
value: character.clone(),
span: character.span().clone(),
})),
)?;
elements.push(element)
}
Ok(InputValue::Array(elements))
}
///
/// Returns a new `InputValue` from the given `ArrayType` and `ArrayInlineExpression`.
///
pub(crate) fn from_array_inline(
mut array_type: ArrayType,
inline: ArrayInlineExpression,
) -> Result<Self, InputParserError> {
// Create a new `ArrayDimensions` type from the input array_type dimensions.
let array_dimensions_type = ArrayDimensions::from(array_type.dimensions.clone());
// Convert the array dimensions to usize.
let array_dimensions = parse_array_dimensions(array_dimensions_type, &array_type.span)?;
// Return an error if the outer array dimension does not equal the number of array elements.
if array_dimensions[0] != inline.expressions.len() {
return Err(InputParserError::array_inline_length(array_dimensions[0], inline));
}
array_type.dimensions = array_type.dimensions.next_dimension();
let inner_array_type = if array_dimensions.len() == 1 {
// This is a single array
*array_type.type_
} else {
// This is a multi-dimensional array
Type::Array(array_type)
};
let mut elements = Vec::with_capacity(inline.expressions.len());
for expression in inline.expressions.into_iter() {
let element = InputValue::from_expression(inner_array_type.clone(), expression)?;
elements.push(element)
}
Ok(InputValue::Array(elements))
}
pub(crate) fn from_array_initializer(
array_type: ArrayType,
initializer: ArrayInitializerExpression,
) -> Result<Self, InputParserError> {
let array_dimensions_type = ArrayDimensions::from(initializer.dimensions.clone());
let array_dimensions = parse_array_dimensions(array_dimensions_type, &array_type.span)?;
if array_dimensions.len() > 1 {
// The expression is an array initializer with tuple syntax
Self::from_array_initializer_tuple(array_type, initializer, array_dimensions)
} else {
// The expression is an array initializer with nested syntax
Self::from_array_initializer_nested(array_type, initializer, array_dimensions)
}
}
pub(crate) fn from_array_initializer_tuple(
array_type: ArrayType,
initializer: ArrayInitializerExpression,
initializer_dimensions: Vec<usize>,
) -> Result<Self, InputParserError> {
let (array_dimensions, array_element_type) = fetch_nested_array_type_dimensions(array_type.clone(), vec![])?;
// Return an error if the dimensions of the array are incorrect.
if array_dimensions.ne(&initializer_dimensions) {
return Err(InputParserError::array_init_length(
array_dimensions,
initializer_dimensions,
&initializer.span,
));
}
let value = InputValue::from_expression(array_element_type, *initializer.expression.clone())?;
let mut elements = vec![];
// Build the elements of the array using the `vec!` macro
for (i, dimension) in initializer_dimensions.into_iter().rev().enumerate() {
if i == 0 {
elements = vec![value.clone(); dimension];
} else {
let element = InputValue::Array(elements.clone());
elements = vec![element; dimension];
}
}
Ok(InputValue::Array(elements))
}
pub(crate) fn from_array_initializer_nested(
mut array_type: ArrayType,
initializer: ArrayInitializerExpression,
initializer_dimensions: Vec<usize>,
) -> Result<Self, InputParserError> {
// Create a new `ArrayDimensions` type from the input array_type dimensions.
let array_dimensions_type = ArrayDimensions::from(array_type.dimensions.clone());
// Convert the array dimensions to usize.
let array_dimensions = parse_array_dimensions(array_dimensions_type, &array_type.span)?;
let current_array_dimension = array_dimensions[0];
let current_initializer_dimension = initializer_dimensions[0];
// Return an error if the outer array dimension does not equal the number of array elements.
if current_array_dimension.ne(&current_initializer_dimension) {
return Err(InputParserError::array_init_length(
array_dimensions,
initializer_dimensions,
&initializer.span,
));
}
array_type.dimensions = array_type.dimensions.next_dimension();
let inner_array_type = if array_dimensions.len() == 1 {
// This is the innermost dimension
*array_type.type_
} else {
// This is an outer dimension of a multi-dimensional array
Type::Array(array_type)
};
// Evaluate the array initializer
let element = InputValue::from_expression(inner_array_type.clone(), *initializer.expression)?;
let elements = vec![element; current_initializer_dimension];
Ok(InputValue::Array(elements))
}
pub(crate) fn from_tuple(tuple_type: TupleType, tuple: TupleExpression) -> Result<Self, InputParserError> {
let num_types = tuple_type.types_.len();
let num_values = tuple.expressions.len();
if num_types != num_values {
return Err(InputParserError::tuple_length(num_types, num_values, &tuple_type.span));
}
let mut values = Vec::with_capacity(tuple_type.types_.len());
for (type_, value) in tuple_type.types_.into_iter().zip(tuple.expressions.into_iter()) {
let value = InputValue::from_expression(type_, value)?;
values.push(value)
}
Ok(InputValue::Tuple(values))
}
}
/// Returns a new vector of usize values from an [`ArrayDimensions`] type.
///
/// Attempts to parse each dimension in the array from a `String` to a `usize` value. If parsing
/// is successful, the `usize` value is appended to the return vector. If parsing fails, an error
/// is returned.
fn parse_array_dimensions(dimensions: ArrayDimensions, span: &Span) -> Result<Vec<usize>, InputParserError> {
// Convert the array dimensions to usize.
let mut result_array_dimensions = Vec::with_capacity(dimensions.len());
for dimension in dimensions.iter() {
// Convert the dimension to a string.
let dimension_string = dimension.to_string();
// Convert the string to usize.
let dimension_usize = match dimension_string.parse::<usize>() {
Ok(dimension_usize) => dimension_usize,
Err(_) => return Err(InputParserError::array_index(dimension_string, span)),
};
// Collect dimension usize values.
result_array_dimensions.push(dimension_usize);
}
Ok(result_array_dimensions)
}
///
/// Recursively fetch all dimensions from the array type.
///
fn fetch_nested_array_type_dimensions(
array_type: ArrayType,
mut array_dimensions: Vec<usize>,
) -> Result<(Vec<usize>, Type), InputParserError> {
// Create a new `ArrayDimensions` type from the input array_type dimensions.
let array_dimensions_type = ArrayDimensions::from(array_type.dimensions.clone());
// Convert the array dimensions to usize.
let mut current_dimension = parse_array_dimensions(array_dimensions_type, &array_type.span)?;
array_dimensions.append(&mut current_dimension);
match *array_type.type_ {
Type::Array(next_array_type) => fetch_nested_array_type_dimensions(next_array_type, array_dimensions),
type_ => Ok((array_dimensions, type_)),
}
}
impl fmt::Display for InputValue {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
InputValue::Address(ref address) => write!(f, "{}", address),
InputValue::Boolean(ref boolean) => write!(f, "{}", boolean),
InputValue::Char(ref character) => write!(f, "{}", character),
InputValue::Group(ref group) => write!(f, "{}", group),
InputValue::Field(ref field) => write!(f, "{}", field),
InputValue::Integer(ref type_, ref number) => write!(f, "{}{:?}", number, type_),
InputValue::Array(ref array) => {
let values = array.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(", ");
write!(f, "array [{}]", values)
}
InputValue::Tuple(ref tuple) => {
let values = tuple.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(", ");
write!(f, "({})", values)
}
}
}
}

View File

@ -1,18 +0,0 @@
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
pub mod parameter;
pub use parameter::*;

View File

@ -1,36 +0,0 @@
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{Identifier, Type};
use leo_input::parameters::Parameter as GrammarParameter;
use leo_span::Span;
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Parameter {
pub variable: Identifier,
pub type_: Type,
pub span: Span,
}
impl<'ast> From<GrammarParameter<'ast>> for Parameter {
fn from(parameter: GrammarParameter<'ast>) -> Self {
Self {
variable: Identifier::from(parameter.variable),
type_: Type::from(parameter.type_),
span: Span::from(parameter.span),
}
}
}

190
ast/src/input/input.rs Normal file
View File

@ -0,0 +1,190 @@
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{Expression, Identifier, InputValue, Type};
use leo_errors::{LeoError, Result, emitter::Handler};
use leo_span::{sym, Span, Symbol};
use std::path::PathBuf;
use indexmap::IndexMap;
#[derive(Debug, Clone, Default)]
pub struct Input {
pub program_input: ProgramInput,
pub program_state: ProgramState,
}
impl Input {
/// Create an empty struct for future `parse` calls.
pub fn new() -> Self {
Self {
program_input: Default::default(),
program_state: Default::default(),
}
}
pub fn parse_input(
&mut self,
handler: &Handler,
input_file_path: PathBuf,
input_file_string: String,
) -> Result<&mut Self> {
Ok(self)
}
pub fn parse_state(
&mut self,
handler: &Handler,
state_file_path: PathBuf,
state_file_string: String,
) -> Result<&mut Self> {
Ok(self)
}
}
#[derive(Clone, Debug)]
pub struct ParsedInputFile {
pub sections: Vec<Section>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Definition {
pub type_: Type,
pub name: Identifier,
pub value: Expression,
pub span: Span,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct Parameter {
pub variable: Identifier,
pub type_: Type,
pub span: Span,
}
impl From<Definition> for Parameter {
fn from(definition: Definition) -> Self {
Self {
variable: definition.name,
type_: definition.type_,
span: definition.span,
}
}
}
#[derive(Debug, Clone)]
pub struct Section {
pub name: Symbol,
pub definitions: Vec<Definition>,
pub is_public: bool,
pub span: Span,
}
type Definitions = IndexMap<Parameter, InputValue>;
#[derive(Debug, Clone, Default)]
pub struct ProgramState {
state: Definitions,
record: Definitions,
state_leaf: Definitions,
}
impl TryFrom<ParsedInputFile> for ProgramState {
type Error = LeoError;
fn try_from(input: ParsedInputFile) -> Result<Self> {
let mut state = IndexMap::new();
let mut record = IndexMap::new();
let mut state_leaf = IndexMap::new();
for section in input.sections {
let mut assignments = IndexMap::new();
for definition in section.definitions {
assignments.insert(
Parameter::from(definition.clone()),
InputValue::try_from((definition.type_, definition.value))?,
);
}
match section.name {
sym::state => {
state = assignments;
}
sym::record => {
record = assignments;
}
sym::state_leaf => {
state_leaf = assignments;
}
_ => todo!("throw an error for illegal section"),
};
}
Ok(ProgramState {
state,
record,
state_leaf,
})
}
}
#[derive(Debug, Clone, Default)]
pub struct ProgramInput {
main: Definitions,
registers: Definitions,
constants: Definitions,
}
impl TryFrom<ParsedInputFile> for ProgramInput {
type Error = LeoError;
fn try_from(input: ParsedInputFile) -> Result<Self> {
let mut main = IndexMap::new();
let mut registers = IndexMap::new();
let mut constants = IndexMap::new();
for section in input.sections {
let mut assignments = IndexMap::new();
for definition in section.definitions {
assignments.insert(
Parameter::from(definition.clone()),
InputValue::try_from((definition.type_, definition.value))?,
);
}
match section.name {
sym::main => {
main = assignments;
}
sym::registers => {
registers = assignments;
}
sym::constants => {
constants = assignments;
}
_ => todo!("throw an error for illegal section"),
};
}
Ok(ProgramInput {
main,
registers,
constants,
})
}
}

View File

@ -14,9 +14,9 @@
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>. // along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{ArrayDimensions, Char, CharValue, GroupValue, IntegerType}; use crate::{CharValue, Expression, GroupValue, IntegerType, Node, SpreadOrExpression, Type, ValueExpression};
use leo_span::Span as AstSpan;
use pest::Span; use leo_errors::{AstError, LeoError, ParserError, Result};
use std::fmt; use std::fmt;
@ -32,350 +32,132 @@ pub enum InputValue {
Tuple(Vec<InputValue>), Tuple(Vec<InputValue>),
} }
impl InputValue { type InputData = (Type, Expression);
fn from_address(address: Address) -> Self {
InputValue::Address(address.value)
}
fn from_address_value(value: AddressValue) -> Self { impl TryFrom<InputData> for InputValue {
match value { type Error = LeoError;
AddressValue::Explicit(address) => Self::from_address(address.address), fn try_from(value: InputData) -> Result<Self> {
AddressValue::Implicit(address) => Self::from_address(address), Ok(match value {
} (type_, Expression::Value(value)) => {
} match (type_, value) {
(Type::Address, ValueExpression::Address(value, _)) => Self::Address(value.to_string()),
fn from_boolean(boolean: BooleanValue) -> Result<Self, InputParserError> { (Type::Boolean, ValueExpression::Boolean(value, span)) => {
let boolean = boolean.value.parse::<bool>()?; let bool_value = value.parse::<bool>().map_err(|_| ParserError::unexpected_eof(&span))?; // TODO: change error
Ok(InputValue::Boolean(boolean)) Self::Boolean(bool_value)
} }
(Type::Char, ValueExpression::Char(value)) => Self::Char(value),
fn from_char(input_character: InputCharValue) -> Result<Self, InputParserError> { (Type::Field, ValueExpression::Field(value, _) | ValueExpression::Implicit(value, _)) => {
let character = match input_character.value.inner()? { Self::Field(value.to_string())
leo_input::values::Char::Scalar(scalar) => Char::Scalar(scalar), }
leo_input::values::Char::NonScalar(non_scalar) => Char::NonScalar(non_scalar), (Type::Group, ValueExpression::Group(value)) => Self::Group(*value),
}; (Type::IntegerType(type_), ValueExpression::Implicit(value, _)) => {
Self::Integer(type_, value.to_string())
let span = AstSpan::from(input_character.span); }
Ok(InputValue::Char(CharValue { character, span })) (Type::IntegerType(expected), ValueExpression::Integer(actual, value, _)) => {
} if expected == actual {
Self::Integer(expected, value.to_string())
fn from_number(integer_type: InputIntegerType, number: String) -> Self { } else {
InputValue::Integer(integer_type.into(), number) todo!("make a decent error here");
}
fn from_group(group: InputGroupValue) -> Self {
InputValue::Group(GroupValue::from(group))
}
fn from_field(field: FieldValue) -> Self {
InputValue::Field(field.number.to_string())
}
fn from_implicit(data_type: Type, implicit: NumberValue) -> Result<Self, InputParserError> {
match data_type {
Type::Address(_) => Err(InputParserError::implicit_type(data_type, implicit)),
Type::Boolean(_) => Err(InputParserError::implicit_type(data_type, implicit)),
Type::Char(_) => Err(InputParserError::implicit_type(data_type, implicit)),
Type::Integer(integer_type) => Ok(InputValue::from_number(integer_type, implicit.to_string())),
Type::Group(_) => Err(InputParserError::implicit_group(implicit)),
Type::Field(_) => Ok(InputValue::Field(implicit.to_string())),
}
}
fn from_value(data_type: Type, value: Value) -> Result<Self, InputParserError> {
match (data_type, value) {
(Type::Address(_), Value::Address(address)) => Ok(InputValue::from_address_value(address)),
(Type::Boolean(_), Value::Boolean(boolean)) => InputValue::from_boolean(boolean),
(Type::Char(_), Value::Char(character)) => InputValue::from_char(character),
(Type::Integer(integer_type), Value::Integer(integer)) => {
match integer.clone() {
IntegerValue::Signed(signed) => {
if let InputIntegerType::Signed(inner) = integer_type.clone() {
let singed_type = signed.clone().type_;
if std::mem::discriminant(&inner) != std::mem::discriminant(&singed_type) {
return Err(InputParserError::integer_type_mismatch(
integer_type,
InputIntegerType::Signed(singed_type),
integer.span(),
));
}
} }
} }
IntegerValue::Unsigned(unsigned) => { (Type::Array(type_, _), ValueExpression::String(string, span)) => {
if let InputIntegerType::Unsigned(inner) = integer_type.clone() { if !matches!(*type_, Type::Char) {
let unsinged_type = unsigned.clone().type_; todo!("string can only be used for arrays of chars");
if std::mem::discriminant(&inner) != std::mem::discriminant(&unsinged_type) {
return Err(InputParserError::integer_type_mismatch(
integer_type,
InputIntegerType::Unsigned(unsinged_type),
integer.span(),
));
}
} }
Self::Array(
string
.into_iter()
.map(|c| {
Self::Char(CharValue {
character: c,
span: span.clone(),
})
})
.collect(),
)
}
(x, y) => {
todo!("type mismatch, expected type {}, got {}", x, y);
} }
} }
Ok(InputValue::from_number(integer_type, integer.to_string()))
} }
(Type::Group(_), Value::Group(group)) => Ok(InputValue::from_group(group)), (Type::Array(type_, type_dimensions), Expression::ArrayInit(mut array_init)) => {
(Type::Field(_), Value::Field(field)) => Ok(InputValue::from_field(field)), // let mut dimensions = array_init.dimensions;
(data_type, Value::Implicit(implicit)) => InputValue::from_implicit(data_type, implicit), // let expression = array_init.element;
(data_type, value) => Err(InputParserError::data_type_mismatch(data_type, value)), let span = array_init.span.clone();
}
}
pub(crate) fn from_expression(type_: Type, expression: Expression) -> Result<Self, InputParserError> { if type_dimensions != array_init.dimensions || array_init.dimensions.is_zero() {
match (type_, expression) { return Err(AstError::invalid_array_dimension_size(&span).into());
(Type::Basic(data_type), Expression::Value(value)) => InputValue::from_value(data_type, value), }
(Type::Array(array_type), Expression::ArrayInline(inline)) => {
InputValue::from_array_inline(array_type, inline) if let Some(dimension) = array_init.dimensions.remove_first() {
if let Some(number) = dimension.as_specified() {
let size = number.value.parse::<usize>().unwrap();
let mut values = Vec::with_capacity(size);
// For when Dimensions are specified in a canonical way: [[u8; 3], 2];
// Else treat as math notation: [u8; (2, 3)];
if array_init.dimensions.len() == 0 {
for _ in 0..size {
values.push(InputValue::try_from((*type_.clone(), *array_init.element.clone()))?);
}
// Faking canonical array init is relatively easy: instead of using a straightforward
// recursion, with each iteration we manually modify ArrayInitExpression cutting off
// dimension by dimension.
} else {
for _ in 0..size {
values.push(InputValue::try_from((
Type::Array(type_.clone(), array_init.dimensions.clone()),
Expression::ArrayInit(array_init.clone()),
))?);
}
};
Self::Array(values)
} else {
unreachable!("dimensions must be specified");
}
} else {
unreachable!("dimensions are checked for zero");
}
} }
(Type::Array(array_type), Expression::ArrayInitializer(initializer)) => { (Type::Tuple(types), Expression::TupleInit(tuple_init)) => {
InputValue::from_array_initializer(array_type, initializer) let size = tuple_init.elements.len();
let mut elements = Vec::with_capacity(size);
if size != types.len() {
todo!(
"tuple length mismatch, defined {} types, got {} values",
size,
types.len()
);
}
for (i, element) in tuple_init.elements.into_iter().enumerate() {
elements.push(Self::try_from((types[i].clone(), element))?);
}
Self::Tuple(elements)
} }
(Type::Array(array_type), Expression::StringExpression(string)) => { (Type::Array(type_, _dimensions), Expression::ArrayInline(array_inline)) => {
InputValue::from_string(array_type, string) let mut elements = Vec::with_capacity(array_inline.elements.len());
let _span = array_inline.span().clone(); // todo!: use for spanning the error
for element in array_inline.elements.into_iter() {
if let SpreadOrExpression::Expression(value_expression) = element {
elements.push(Self::try_from((*type_.clone(), value_expression))?);
} else {
todo!("make error that only expression is allowed in inline, no spread please");
}
}
Self::Array(elements)
} }
(Type::Tuple(tuple_type), Expression::Tuple(tuple)) => InputValue::from_tuple(tuple_type, tuple), (_type_, expr) => {
(type_, expression) => Err(InputParserError::expression_type_mismatch(type_, expression)), dbg!(&expr);
} todo!("forbidden expression in inputs");
}
///
/// Returns a new `InputValue` from the given `ArrayType` and `StringExpression`.
///
pub(crate) fn from_string(mut array_type: ArrayType, string: StringExpression) -> Result<Self, InputParserError> {
// Create a new `ArrayDimensions` type from the input array_type dimensions.
let array_dimensions_type = ArrayDimensions::from(array_type.dimensions.clone());
assert!(matches!(*array_type.type_, Type::Basic(Type::Char(CharType {}))));
// Convert the array dimensions to usize.
let array_dimensions = parse_array_dimensions(array_dimensions_type, &array_type.span)?;
// Return an error if the outer array dimension does not equal the number of array elements.
if array_dimensions[0] != string.chars.len() {
return Err(InputParserError::invalid_string_length(
array_dimensions[0],
string.chars.len(),
&string.span,
));
}
array_type.dimensions = array_type.dimensions.next_dimension();
let inner_array_type = if array_dimensions.len() == 1 {
// This is a single array
*array_type.type_
} else {
// This is a multi-dimensional array
return Err(InputParserError::invalid_string_dimensions(&array_type.span));
};
let mut elements = Vec::with_capacity(string.chars.len());
for character in string.chars.into_iter() {
let element = InputValue::from_expression(
inner_array_type.clone(),
Expression::Value(Value::Char(InputCharValue {
value: character.clone(),
span: character.span().clone(),
})),
)?;
elements.push(element)
}
Ok(InputValue::Array(elements))
}
///
/// Returns a new `InputValue` from the given `ArrayType` and `ArrayInlineExpression`.
///
pub(crate) fn from_array_inline(
mut array_type: ArrayType,
inline: ArrayInlineExpression,
) -> Result<Self, InputParserError> {
// Create a new `ArrayDimensions` type from the input array_type dimensions.
let array_dimensions_type = ArrayDimensions::from(array_type.dimensions.clone());
// Convert the array dimensions to usize.
let array_dimensions = parse_array_dimensions(array_dimensions_type, &array_type.span)?;
// Return an error if the outer array dimension does not equal the number of array elements.
if array_dimensions[0] != inline.expressions.len() {
return Err(InputParserError::array_inline_length(array_dimensions[0], inline));
}
array_type.dimensions = array_type.dimensions.next_dimension();
let inner_array_type = if array_dimensions.len() == 1 {
// This is a single array
*array_type.type_
} else {
// This is a multi-dimensional array
Type::Array(array_type)
};
let mut elements = Vec::with_capacity(inline.expressions.len());
for expression in inline.expressions.into_iter() {
let element = InputValue::from_expression(inner_array_type.clone(), expression)?;
elements.push(element)
}
Ok(InputValue::Array(elements))
}
pub(crate) fn from_array_initializer(
array_type: ArrayType,
initializer: ArrayInitializerExpression,
) -> Result<Self, InputParserError> {
let array_dimensions_type = ArrayDimensions::from(initializer.dimensions.clone());
let array_dimensions = parse_array_dimensions(array_dimensions_type, &array_type.span)?;
if array_dimensions.len() > 1 {
// The expression is an array initializer with tuple syntax
Self::from_array_initializer_tuple(array_type, initializer, array_dimensions)
} else {
// The expression is an array initializer with nested syntax
Self::from_array_initializer_nested(array_type, initializer, array_dimensions)
}
}
pub(crate) fn from_array_initializer_tuple(
array_type: ArrayType,
initializer: ArrayInitializerExpression,
initializer_dimensions: Vec<usize>,
) -> Result<Self, InputParserError> {
let (array_dimensions, array_element_type) = fetch_nested_array_type_dimensions(array_type.clone(), vec![])?;
// Return an error if the dimensions of the array are incorrect.
if array_dimensions.ne(&initializer_dimensions) {
return Err(InputParserError::array_init_length(
array_dimensions,
initializer_dimensions,
&initializer.span,
));
}
let value = InputValue::from_expression(array_element_type, *initializer.expression.clone())?;
let mut elements = vec![];
// Build the elements of the array using the `vec!` macro
for (i, dimension) in initializer_dimensions.into_iter().rev().enumerate() {
if i == 0 {
elements = vec![value.clone(); dimension];
} else {
let element = InputValue::Array(elements.clone());
elements = vec![element; dimension];
} }
} })
Ok(InputValue::Array(elements))
}
pub(crate) fn from_array_initializer_nested(
mut array_type: ArrayType,
initializer: ArrayInitializerExpression,
initializer_dimensions: Vec<usize>,
) -> Result<Self, InputParserError> {
// Create a new `ArrayDimensions` type from the input array_type dimensions.
let array_dimensions_type = ArrayDimensions::from(array_type.dimensions.clone());
// Convert the array dimensions to usize.
let array_dimensions = parse_array_dimensions(array_dimensions_type, &array_type.span)?;
let current_array_dimension = array_dimensions[0];
let current_initializer_dimension = initializer_dimensions[0];
// Return an error if the outer array dimension does not equal the number of array elements.
if current_array_dimension.ne(&current_initializer_dimension) {
return Err(InputParserError::array_init_length(
array_dimensions,
initializer_dimensions,
&initializer.span,
));
}
array_type.dimensions = array_type.dimensions.next_dimension();
let inner_array_type = if array_dimensions.len() == 1 {
// This is the innermost dimension
*array_type.type_
} else {
// This is an outer dimension of a multi-dimensional array
Type::Array(array_type)
};
// Evaluate the array initializer
let element = InputValue::from_expression(inner_array_type.clone(), *initializer.expression)?;
let elements = vec![element; current_initializer_dimension];
Ok(InputValue::Array(elements))
}
pub(crate) fn from_tuple(tuple_type: TupleType, tuple: TupleExpression) -> Result<Self, InputParserError> {
let num_types = tuple_type.types_.len();
let num_values = tuple.expressions.len();
if num_types != num_values {
return Err(InputParserError::tuple_length(num_types, num_values, &tuple_type.span));
}
let mut values = Vec::with_capacity(tuple_type.types_.len());
for (type_, value) in tuple_type.types_.into_iter().zip(tuple.expressions.into_iter()) {
let value = InputValue::from_expression(type_, value)?;
values.push(value)
}
Ok(InputValue::Tuple(values))
}
}
/// Returns a new vector of usize values from an [`ArrayDimensions`] type.
///
/// Attempts to parse each dimension in the array from a `String` to a `usize` value. If parsing
/// is successful, the `usize` value is appended to the return vector. If parsing fails, an error
/// is returned.
fn parse_array_dimensions(dimensions: ArrayDimensions, span: &Span) -> Result<Vec<usize>, InputParserError> {
// Convert the array dimensions to usize.
let mut result_array_dimensions = Vec::with_capacity(dimensions.len());
for dimension in dimensions.iter() {
// Convert the dimension to a string.
let dimension_string = dimension.to_string();
// Convert the string to usize.
let dimension_usize = match dimension_string.parse::<usize>() {
Ok(dimension_usize) => dimension_usize,
Err(_) => return Err(InputParserError::array_index(dimension_string, span)),
};
// Collect dimension usize values.
result_array_dimensions.push(dimension_usize);
}
Ok(result_array_dimensions)
}
///
/// Recursively fetch all dimensions from the array type.
///
fn fetch_nested_array_type_dimensions(
array_type: ArrayType,
mut array_dimensions: Vec<usize>,
) -> Result<(Vec<usize>, Type), InputParserError> {
// Create a new `ArrayDimensions` type from the input array_type dimensions.
let array_dimensions_type = ArrayDimensions::from(array_type.dimensions.clone());
// Convert the array dimensions to usize.
let mut current_dimension = parse_array_dimensions(array_dimensions_type, &array_type.span)?;
array_dimensions.append(&mut current_dimension);
match *array_type.type_ {
Type::Array(next_array_type) => fetch_nested_array_type_dimensions(next_array_type, array_dimensions),
type_ => Ok((array_dimensions, type_)),
} }
} }
@ -390,12 +172,10 @@ impl fmt::Display for InputValue {
InputValue::Integer(ref type_, ref number) => write!(f, "{}{:?}", number, type_), InputValue::Integer(ref type_, ref number) => write!(f, "{}{:?}", number, type_),
InputValue::Array(ref array) => { InputValue::Array(ref array) => {
let values = array.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(", "); let values = array.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(", ");
write!(f, "array [{}]", values) write!(f, "array [{}]", values)
} }
InputValue::Tuple(ref tuple) => { InputValue::Tuple(ref tuple) => {
let values = tuple.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(", "); let values = tuple.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(", ");
write!(f, "({})", values) write!(f, "({})", values)
} }
} }

View File

@ -14,161 +14,8 @@
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>. // along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{ pub mod input_value;
CharValue, Expression, GroupValue, Identifier, IntegerType, Node, SpreadOrExpression, Type, ValueExpression, pub use input_value::*;
};
use indexmap::IndexMap;
use leo_errors::{AstError, LeoError, ParserError, Result};
#[derive(Clone, Debug)] pub mod input;
pub struct Input { pub use input::*;
values: IndexMap<Identifier, IndexMap<Identifier, (Type, Expression)>>,
}
impl Input {
pub fn new(values: IndexMap<Identifier, IndexMap<Identifier, (Type, Expression)>>) -> Self {
for (_ident, definitions) in values.iter() {
// println!("ident: {}", ident);
for (_var, (type_, value)) in definitions.iter() {
let value = InputValue::try_from((type_.clone(), value.clone()))
.map_err(|_| ParserError::unexpected_eof(value.span()));
dbg!(value.unwrap());
}
}
Input { values }
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum InputValue {
Address(String),
Boolean(bool),
Char(CharValue),
Field(String),
Group(GroupValue),
Integer(IntegerType, String),
Array(Vec<InputValue>),
Tuple(Vec<InputValue>),
}
impl TryFrom<(Type, Expression)> for InputValue {
type Error = LeoError;
fn try_from(value: (Type, Expression)) -> Result<Self> {
Ok(match value {
(type_, Expression::Value(value)) => {
match (type_, value) {
(Type::Address, ValueExpression::Address(value, _)) => Self::Address(value.to_string()),
(Type::Boolean, ValueExpression::Boolean(value, span)) => {
let bool_value = value.parse::<bool>().map_err(|_| ParserError::unexpected_eof(&span))?; // TODO: change error
Self::Boolean(bool_value)
}
(Type::Char, ValueExpression::Char(value)) => Self::Char(value),
(Type::Field, ValueExpression::Field(value, _) | ValueExpression::Implicit(value, _)) => Self::Field(value.to_string()),
(Type::Group, ValueExpression::Group(value)) => Self::Group(*value),
(Type::IntegerType(type_), ValueExpression::Implicit(value, _)) => Self::Integer(type_, value.to_string()),
(Type::IntegerType(expected), ValueExpression::Integer(actual, value, _)) => {
if expected == actual {
Self::Integer(expected, value.to_string())
} else {
todo!("make a decent error here");
}
},
(Type::Array(type_, _), ValueExpression::String(string, span)) => {
if !matches!(*type_, Type::Char) {
todo!("string can only be used for arrays of chars");
}
Self::Array(
string
.into_iter()
.map(|c| {
Self::Char(CharValue {
character: c,
span: span.clone(),
})
})
.collect(),
)
},
(x, y) => {
todo!("type mismatch, expected type {}, got {}", x, y);
}
}
}
(Type::Array(type_, type_dimensions), Expression::ArrayInit(mut array_init)) => {
// let mut dimensions = array_init.dimensions;
// let expression = array_init.element;
let span = array_init.span.clone();
if type_dimensions != array_init.dimensions || array_init.dimensions.is_zero() {
return Err(AstError::invalid_array_dimension_size(&span).into());
}
if let Some(dimension) = array_init.dimensions.remove_first() {
if let Some(number) = dimension.as_specified() {
let size = number.value.parse::<usize>().unwrap();
let mut values = Vec::with_capacity(size);
// For when Dimensions are specified in a canonical way: [[u8; 3], 2];
// Else treat as math notation: [u8; (2, 3)];
if array_init.dimensions.len() == 0 {
for _ in 0..size {
values.push(InputValue::try_from((*type_.clone(), *array_init.element.clone()))?);
}
// Faking canonical array init is relatively easy: instead of using a straightforward
// recursion, before each iteration we manually modify ArrayInitExpression cutting off
// dimension by dimension.
} else {
for _ in 0..size {
values.push(InputValue::try_from((
Type::Array(type_.clone(), array_init.dimensions.clone()),
Expression::ArrayInit(array_init.clone())
))?);
}
};
Self::Array(values)
} else {
unreachable!("dimensions must be specified");
}
} else {
unreachable!("dimensions are checked for zero");
}
}
(Type::Tuple(types), Expression::TupleInit(tuple_init)) => {
let size = tuple_init.elements.len();
let mut elements = Vec::with_capacity(size);
if size != types.len() {
todo!("tuple length mismatch, defined {} types, got {} values", size, types.len());
}
for (i, element) in tuple_init.elements.into_iter().enumerate() {
elements.push(Self::try_from((types[i].clone(), element))?);
}
Self::Tuple(elements)
}
(Type::Array(type_, _dimensions), Expression::ArrayInline(array_inline)) => {
let mut elements = Vec::with_capacity(array_inline.elements.len());
let _span = array_inline.span().clone(); // todo!: use for spanning the error
for element in array_inline.elements.into_iter() {
if let SpreadOrExpression::Expression(value_expression) = element {
elements.push(Self::try_from((*type_.clone(), value_expression))?);
} else {
todo!("make error that only expression is allowed in inline, no spread please");
}
}
Self::Array(elements)
}
(_type_, expr) => {
dbg!(&expr);
todo!("forbidden expression in inputs");
}
})
}
}

View File

@ -30,9 +30,6 @@ version = "1.5.3"
#path = "../imports" #path = "../imports"
#version = "1.5.3" #version = "1.5.3"
# #
#[dependencies.leo-input]
#path = "../input"
#version = "1.5.3"
# #
#[dependencies.leo-package] #[dependencies.leo-package]
#path = "../package" #path = "../package"

View File

@ -1,37 +0,0 @@
[package]
name = "leo-input"
version = "1.5.3"
authors = [ "The Aleo Team <hello@aleo.org>" ]
description = "Input parser of the Leo programming language"
homepage = "https://aleo.org"
repository = "https://github.com/AleoHQ/leo"
keywords = [
"aleo",
"cryptography",
"leo",
"programming-language",
"zero-knowledge"
]
categories = [ "cryptography::cryptocurrencies", "web-programming" ]
include = [ "Cargo.toml", "src", "README.md", "LICENSE.md" ]
license = "GPL-3.0"
edition = "2021"
rust-version = "1.56.1"
[dependencies.from-pest]
version = "0.3.1"
[dependencies.pest]
version = "2.0"
[dependencies.pest-ast]
version = "0.3.3"
[dependencies.pest_derive]
version = "2.0"
[dependencies.thiserror]
version = "1.0"
[dependencies.tracing]
version = "0.1"

View File

@ -1,596 +0,0 @@
GNU General Public License
==========================
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. &lt;<https://fsf.org/>&gt;
Everyone is permitted to copy and distribute verbatim copies of this license
document, but changing it is not allowed.
## Preamble
The GNU General Public License is a free, copyleft license for software and other
kinds of works.
The licenses for most software and other practical works are designed to take away
your freedom to share and change the works. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change all versions of a
program--to make sure it remains free software for all its users. We, the Free
Software Foundation, use the GNU General Public License for most of our software; it
applies also to any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General
Public Licenses are designed to make sure that you have the freedom to distribute
copies of free software (and charge for them if you wish), that you receive source
code or can get it if you want it, that you can change the software or use pieces of
it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or
asking you to surrender the rights. Therefore, you have certain responsibilities if
you distribute copies of the software, or if you modify it: responsibilities to
respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee,
you must pass on to the recipients the same freedoms that you received. You must make
sure that they, too, receive or can get the source code. And you must show them these
terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: **(1)** assert
copyright on the software, and **(2)** offer you this License giving you legal permission
to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is
no warranty for this free software. For both users' and authors' sake, the GPL
requires that modified versions be marked as changed, so that their problems will not
be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of
the software inside them, although the manufacturer can do so. This is fundamentally
incompatible with the aim of protecting users' freedom to change the software. The
systematic pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we have designed
this version of the GPL to prohibit the practice for those products. If such problems
arise substantially in other domains, we stand ready to extend this provision to
those domains in future versions of the GPL, as needed to protect the freedom of
users.
Finally, every program is threatened constantly by software patents. States should
not allow patents to restrict development and use of software on general-purpose
computers, but in those that do, we wish to avoid the special danger that patents
applied to a free program could make it effectively proprietary. To prevent this, the
GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
## TERMS AND CONDITIONS
### 0. Definitions
“This License” refers to version 3 of the GNU General Public License.
“Copyright” also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this
License. Each licensee is addressed as “you”. “Licensees” and
“recipients” may be individuals or organizations.
To “modify” a work means to copy from or adapt all or part of the work in
a fashion requiring copyright permission, other than the making of an exact copy. The
resulting work is called a “modified version” of the earlier work or a
work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based on
the Program.
To “propagate” a work means to do anything with it that, without
permission, would make you directly or secondarily liable for infringement under
applicable copyright law, except executing it on a computer or modifying a private
copy. Propagation includes copying, distribution (with or without modification),
making available to the public, and in some countries other activities as well.
To “convey” a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through a computer
network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices” to the
extent that it includes a convenient and prominently visible feature that **(1)**
displays an appropriate copyright notice, and **(2)** tells the user that there is no
warranty for the work (except to the extent that warranties are provided), that
licensees may convey the work under this License, and how to view a copy of this
License. If the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
### 1. Source Code
The “source code” for a work means the preferred form of the work for
making modifications to it. “Object code” means any non-source form of a
work.
A “Standard Interface” means an interface that either is an official
standard defined by a recognized standards body, or, in the case of interfaces
specified for a particular programming language, one that is widely used among
developers working in that language.
The “System Libraries” of an executable work include anything, other than
the work as a whole, that **(a)** is included in the normal form of packaging a Major
Component, but which is not part of that Major Component, and **(b)** serves only to
enable use of the work with that Major Component, or to implement a Standard
Interface for which an implementation is available to the public in source code form.
A “Major Component”, in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system (if any) on which
the executable work runs, or a compiler used to produce the work, or an object code
interpreter used to run it.
The “Corresponding Source” for a work in object code form means all the
source code needed to generate, install, and (for an executable work) run the object
code and to modify the work, including scripts to control those activities. However,
it does not include the work's System Libraries, or general-purpose tools or
generally available free programs which are used unmodified in performing those
activities but which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for the work, and
the source code for shared libraries and dynamically linked subprograms that the work
is specifically designed to require, such as by intimate data communication or
control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate
automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
### 2. Basic Permissions
All rights granted under this License are granted for the term of copyright on the
Program, and are irrevocable provided the stated conditions are met. This License
explicitly affirms your unlimited permission to run the unmodified Program. The
output from running a covered work is covered by this License only if the output,
given its content, constitutes a covered work. This License acknowledges your rights
of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without
conditions so long as your license otherwise remains in force. You may convey covered
works to others for the sole purpose of having them make modifications exclusively
for you, or provide you with facilities for running those works, provided that you
comply with the terms of this License in conveying all material for which you do not
control copyright. Those thus making or running the covered works for you must do so
exclusively on your behalf, under your direction and control, on terms that prohibit
them from making any copies of your copyrighted material outside their relationship
with you.
Conveying under any other circumstances is permitted solely under the conditions
stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
### 3. Protecting Users' Legal Rights From Anti-Circumvention Law
No covered work shall be deemed part of an effective technological measure under any
applicable law fulfilling obligations under article 11 of the WIPO copyright treaty
adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention
of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of
technological measures to the extent such circumvention is effected by exercising
rights under this License with respect to the covered work, and you disclaim any
intention to limit operation or modification of the work as a means of enforcing,
against the work's users, your or third parties' legal rights to forbid circumvention
of technological measures.
### 4. Conveying Verbatim Copies
You may convey verbatim copies of the Program's source code as you receive it, in any
medium, provided that you conspicuously and appropriately publish on each copy an
appropriate copyright notice; keep intact all notices stating that this License and
any non-permissive terms added in accord with section 7 apply to the code; keep
intact all notices of the absence of any warranty; and give all recipients a copy of
this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer
support or warranty protection for a fee.
### 5. Conveying Modified Source Versions
You may convey a work based on the Program, or the modifications to produce it from
the Program, in the form of source code under the terms of section 4, provided that
you also meet all of these conditions:
* **a)** The work must carry prominent notices stating that you modified it, and giving a
relevant date.
* **b)** The work must carry prominent notices stating that it is released under this
License and any conditions added under section 7. This requirement modifies the
requirement in section 4 to “keep intact all notices”.
* **c)** You must license the entire work, as a whole, under this License to anyone who
comes into possession of a copy. This License will therefore apply, along with any
applicable section 7 additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no permission to license the
work in any other way, but it does not invalidate such permission if you have
separately received it.
* **d)** If the work has interactive user interfaces, each must display Appropriate Legal
Notices; however, if the Program has interactive interfaces that do not display
Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are
not by their nature extensions of the covered work, and which are not combined with
it such as to form a larger program, in or on a volume of a storage or distribution
medium, is called an “aggregate” if the compilation and its resulting
copyright are not used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work in an aggregate
does not cause this License to apply to the other parts of the aggregate.
### 6. Conveying Non-Source Forms
You may convey a covered work in object code form under the terms of sections 4 and
5, provided that you also convey the machine-readable Corresponding Source under the
terms of this License, in one of these ways:
* **a)** Convey the object code in, or embodied in, a physical product (including a
physical distribution medium), accompanied by the Corresponding Source fixed on a
durable physical medium customarily used for software interchange.
* **b)** Convey the object code in, or embodied in, a physical product (including a
physical distribution medium), accompanied by a written offer, valid for at least
three years and valid for as long as you offer spare parts or customer support for
that product model, to give anyone who possesses the object code either **(1)** a copy of
the Corresponding Source for all the software in the product that is covered by this
License, on a durable physical medium customarily used for software interchange, for
a price no more than your reasonable cost of physically performing this conveying of
source, or **(2)** access to copy the Corresponding Source from a network server at no
charge.
* **c)** Convey individual copies of the object code with a copy of the written offer to
provide the Corresponding Source. This alternative is allowed only occasionally and
noncommercially, and only if you received the object code with such an offer, in
accord with subsection 6b.
* **d)** Convey the object code by offering access from a designated place (gratis or for
a charge), and offer equivalent access to the Corresponding Source in the same way
through the same place at no further charge. You need not require recipients to copy
the Corresponding Source along with the object code. If the place to copy the object
code is a network server, the Corresponding Source may be on a different server
(operated by you or a third party) that supports equivalent copying facilities,
provided you maintain clear directions next to the object code saying where to find
the Corresponding Source. Regardless of what server hosts the Corresponding Source,
you remain obligated to ensure that it is available for as long as needed to satisfy
these requirements.
* **e)** Convey the object code using peer-to-peer transmission, provided you inform
other peers where the object code and Corresponding Source of the work are being
offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the
Corresponding Source as a System Library, need not be included in conveying the
object code work.
A “User Product” is either **(1)** a “consumer product”, which
means any tangible personal property which is normally used for personal, family, or
household purposes, or **(2)** anything designed or sold for incorporation into a
dwelling. In determining whether a product is a consumer product, doubtful cases
shall be resolved in favor of coverage. For a particular product received by a
particular user, “normally used” refers to a typical or common use of
that class of product, regardless of the status of the particular user or of the way
in which the particular user actually uses, or expects or is expected to use, the
product. A product is a consumer product regardless of whether the product has
substantial commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
“Installation Information” for a User Product means any methods,
procedures, authorization keys, or other information required to install and execute
modified versions of a covered work in that User Product from a modified version of
its Corresponding Source. The information must suffice to ensure that the continued
functioning of the modified object code is in no case prevented or interfered with
solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for
use in, a User Product, and the conveying occurs as part of a transaction in which
the right of possession and use of the User Product is transferred to the recipient
in perpetuity or for a fixed term (regardless of how the transaction is
characterized), the Corresponding Source conveyed under this section must be
accompanied by the Installation Information. But this requirement does not apply if
neither you nor any third party retains the ability to install modified object code
on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to
continue to provide support service, warranty, or updates for a work that has been
modified or installed by the recipient, or for the User Product in which it has been
modified or installed. Access to a network may be denied when the modification itself
materially and adversely affects the operation of the network or violates the rules
and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with
this section must be in a format that is publicly documented (and with an
implementation available to the public in source code form), and must require no
special password or key for unpacking, reading or copying.
### 7. Additional Terms
“Additional permissions” are terms that supplement the terms of this
License by making exceptions from one or more of its conditions. Additional
permissions that are applicable to the entire Program shall be treated as though they
were included in this License, to the extent that they are valid under applicable
law. If additional permissions apply only to part of the Program, that part may be
used separately under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any
additional permissions from that copy, or from any part of it. (Additional
permissions may be written to require their own removal in certain cases when you
modify the work.) You may place additional permissions on material, added by you to a
covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a
covered work, you may (if authorized by the copyright holders of that material)
supplement the terms of this License with terms:
* **a)** Disclaiming warranty or limiting liability differently from the terms of
sections 15 and 16 of this License; or
* **b)** Requiring preservation of specified reasonable legal notices or author
attributions in that material or in the Appropriate Legal Notices displayed by works
containing it; or
* **c)** Prohibiting misrepresentation of the origin of that material, or requiring that
modified versions of such material be marked in reasonable ways as different from the
original version; or
* **d)** Limiting the use for publicity purposes of names of licensors or authors of the
material; or
* **e)** Declining to grant rights under trademark law for use of some trade names,
trademarks, or service marks; or
* **f)** Requiring indemnification of licensors and authors of that material by anyone
who conveys the material (or modified versions of it) with contractual assumptions of
liability to the recipient, for any liability that these contractual assumptions
directly impose on those licensors and authors.
All other non-permissive additional terms are considered “further
restrictions” within the meaning of section 10. If the Program as you received
it, or any part of it, contains a notice stating that it is governed by this License
along with a term that is a further restriction, you may remove that term. If a
license document contains a further restriction but permits relicensing or conveying
under this License, you may add to a covered work material governed by the terms of
that license document, provided that the further restriction does not survive such
relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in
the relevant source files, a statement of the additional terms that apply to those
files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a
separately written license, or stated as exceptions; the above requirements apply
either way.
### 8. Termination
You may not propagate or modify a covered work except as expressly provided under
this License. Any attempt otherwise to propagate or modify it is void, and will
automatically terminate your rights under this License (including any patent licenses
granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a
particular copyright holder is reinstated **(a)** provisionally, unless and until the
copyright holder explicitly and finally terminates your license, and **(b)** permanently,
if the copyright holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently
if the copyright holder notifies you of the violation by some reasonable means, this
is the first time you have received notice of violation of this License (for any
work) from that copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of
parties who have received copies or rights from you under this License. If your
rights have been terminated and not permanently reinstated, you do not qualify to
receive new licenses for the same material under section 10.
### 9. Acceptance Not Required for Having Copies
You are not required to accept this License in order to receive or run a copy of the
Program. Ancillary propagation of a covered work occurring solely as a consequence of
using peer-to-peer transmission to receive a copy likewise does not require
acceptance. However, nothing other than this License grants you permission to
propagate or modify any covered work. These actions infringe copyright if you do not
accept this License. Therefore, by modifying or propagating a covered work, you
indicate your acceptance of this License to do so.
### 10. Automatic Licensing of Downstream Recipients
Each time you convey a covered work, the recipient automatically receives a license
from the original licensors, to run, modify and propagate that work, subject to this
License. You are not responsible for enforcing compliance by third parties with this
License.
An “entity transaction” is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an organization, or
merging organizations. If propagation of a covered work results from an entity
transaction, each party to that transaction who receives a copy of the work also
receives whatever licenses to the work the party's predecessor in interest had or
could give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if the predecessor
has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or
affirmed under this License. For example, you may not impose a license fee, royalty,
or other charge for exercise of rights granted under this License, and you may not
initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging
that any patent claim is infringed by making, using, selling, offering for sale, or
importing the Program or any portion of it.
### 11. Patents
A “contributor” is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The work thus
licensed is called the contributor's “contributor version”.
A contributor's “essential patent claims” are all patent claims owned or
controlled by the contributor, whether already acquired or hereafter acquired, that
would be infringed by some manner, permitted by this License, of making, using, or
selling its contributor version, but do not include claims that would be infringed
only as a consequence of further modification of the contributor version. For
purposes of this definition, “control” includes the right to grant patent
sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license
under the contributor's essential patent claims, to make, use, sell, offer for sale,
import and otherwise run, modify and propagate the contents of its contributor
version.
In the following three paragraphs, a “patent license” is any express
agreement or commitment, however denominated, not to enforce a patent (such as an
express permission to practice a patent or covenant not to sue for patent
infringement). To “grant” such a patent license to a party means to make
such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the
Corresponding Source of the work is not available for anyone to copy, free of charge
and under the terms of this License, through a publicly available network server or
other readily accessible means, then you must either **(1)** cause the Corresponding
Source to be so available, or **(2)** arrange to deprive yourself of the benefit of the
patent license for this particular work, or **(3)** arrange, in a manner consistent with
the requirements of this License, to extend the patent license to downstream
recipients. “Knowingly relying” means you have actual knowledge that, but
for the patent license, your conveying the covered work in a country, or your
recipient's use of the covered work in a country, would infringe one or more
identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you
convey, or propagate by procuring conveyance of, a covered work, and grant a patent
license to some of the parties receiving the covered work authorizing them to use,
propagate, modify or convey a specific copy of the covered work, then the patent
license you grant is automatically extended to all recipients of the covered work and
works based on it.
A patent license is “discriminatory” if it does not include within the
scope of its coverage, prohibits the exercise of, or is conditioned on the
non-exercise of one or more of the rights that are specifically granted under this
License. You may not convey a covered work if you are a party to an arrangement with
a third party that is in the business of distributing software, under which you make
payment to the third party based on the extent of your activity of conveying the
work, and under which the third party grants, to any of the parties who would receive
the covered work from you, a discriminatory patent license **(a)** in connection with
copies of the covered work conveyed by you (or copies made from those copies), or **(b)**
primarily for and in connection with specific products or compilations that contain
the covered work, unless you entered into that arrangement, or that patent license
was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied
license or other defenses to infringement that may otherwise be available to you
under applicable patent law.
### 12. No Surrender of Others' Freedom
If conditions are imposed on you (whether by court order, agreement or otherwise)
that contradict the conditions of this License, they do not excuse you from the
conditions of this License. If you cannot convey a covered work so as to satisfy
simultaneously your obligations under this License and any other pertinent
obligations, then as a consequence you may not convey it at all. For example, if you
agree to terms that obligate you to collect a royalty for further conveying from
those to whom you convey the Program, the only way you could satisfy both those terms
and this License would be to refrain entirely from conveying the Program.
### 13. Use with the GNU Affero General Public License
Notwithstanding any other provision of this License, you have permission to link or
combine any covered work with a work licensed under version 3 of the GNU Affero
General Public License into a single combined work, and to convey the resulting work.
The terms of this License will continue to apply to the part which is the covered
work, but the special requirements of the GNU Affero General Public License, section
13, concerning interaction through a network will apply to the combination as such.
### 14. Revised Versions of this License
The Free Software Foundation may publish revised and/or new versions of the GNU
General Public License from time to time. Such new versions will be similar in spirit
to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that
a certain numbered version of the GNU General Public License “or any later
version” applies to it, you have the option of following the terms and
conditions either of that numbered version or of any later version published by the
Free Software Foundation. If the Program does not specify a version number of the GNU
General Public License, you may choose any version ever published by the Free
Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU
General Public License can be used, that proxy's public statement of acceptance of a
version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no
additional obligations are imposed on any author or copyright holder as a result of
your choosing to follow a later version.
### 15. Disclaimer of Warranty
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER
EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE
QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
### 16. Limitation of Liability
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY
COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS
PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL,
INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE
OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE
WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
### 17. Interpretation of Sections 15 and 16
If the disclaimer of warranty and limitation of liability provided above cannot be
given local legal effect according to their terms, reviewing courts shall apply local
law that most closely approximates an absolute waiver of all civil liability in
connection with the Program, unless a warranty or assumption of liability accompanies
a copy of the Program in return for a fee.
_END OF TERMS AND CONDITIONS_
## How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to
the public, the best way to achieve this is to make it free software which everyone
can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them
to the start of each source file to most effectively state the exclusion of warranty;
and each file should have at least the “copyright” line and a pointer to
where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this
when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type 'show c' for details.
The hypothetical commands `show w` and `show c` should show the appropriate parts of
the General Public License. Of course, your program's commands might be different;
for a GUI interface, you would use an “about box”.
You should also get your employer (if you work as a programmer) or school, if any, to
sign a “copyright disclaimer” for the program, if necessary. For more
information on this, and how to apply and follow the GNU GPL, see
&lt;<http://www.gnu.org/licenses/>&gt;.
The GNU General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may consider it
more useful to permit linking proprietary applications with the library. If this is
what you want to do, use the GNU Lesser General Public License instead of this
License. But first, please read
&lt;<http://www.gnu.org/philosophy/why-not-lgpl.html>&gt;.

View File

@ -1,5 +0,0 @@
# leo-input
[![Crates.io](https://img.shields.io/crates/v/leo-input.svg?color=neon)](https://crates.io/crates/leo-input)
[![Authors](https://img.shields.io/badge/authors-Aleo-orange.svg)](../AUTHORS)
[![License](https://img.shields.io/badge/License-GPLv3-blue.svg)](./LICENSE.md)

View File

@ -1,30 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
#![allow(clippy::upper_case_acronyms)]
//! Abstract syntax tree (ast) representation from leo-input.pest.
use pest::{error::Error, iterators::Pairs, Parser, Span};
#[derive(Parser)]
#[grammar = "leo-input.pest"]
pub struct LanguageParser;
pub fn parse(input: &str) -> Result<Pairs<Rule>, Error<Rule>> {
LanguageParser::parse(Rule::file, input)
}
pub fn span_into_string(span: Span) -> String {
span.as_str().to_string()
}

View File

@ -1,24 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
#![allow(clippy::upper_case_acronyms)]
use crate::ast::Rule;
use pest_ast::FromPest;
#[derive(Clone, Debug, FromPest, PartialEq)]
#[pest_ast(rule(Rule::EOI))]
pub struct EOI;

View File

@ -1,36 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::ast::{span_into_string, Rule};
use pest::Span;
use pest_ast::FromPest;
use std::fmt;
#[derive(Clone, Debug, FromPest, PartialEq)]
#[pest_ast(rule(Rule::identifier))]
pub struct Identifier<'ast> {
#[pest_ast(outer(with(span_into_string)))]
pub value: String,
#[pest_ast(outer())]
pub span: Span<'ast>,
}
impl<'ast> fmt::Display for Identifier<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.value)
}
}

View File

@ -1,23 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::ast::Rule;
use pest_ast::FromPest;
#[derive(Clone, Debug, FromPest, PartialEq)]
#[pest_ast(rule(Rule::LINE_END))]
pub struct LineEnd;

View File

@ -1,24 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
pub mod eoi;
pub use eoi::*;
pub mod identifier;
pub use identifier::*;
pub mod line_end;
pub use line_end::*;

View File

@ -1,30 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{ast::Rule, common::LineEnd, expressions::Expression, parameters::Parameter};
use pest::Span;
use pest_ast::FromPest;
#[derive(Clone, Debug, FromPest, PartialEq)]
#[pest_ast(rule(Rule::definition))]
pub struct Definition<'ast> {
pub parameter: Parameter<'ast>,
pub expression: Expression<'ast>,
pub line_end: LineEnd,
#[pest_ast(outer())]
pub span: Span<'ast>,
}

View File

@ -1,18 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
pub mod definition;
pub use definition::*;

View File

@ -1,21 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
pub mod parser;
pub use parser::*;
pub mod syntax;
pub use syntax::*;

View File

@ -1,212 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{
ast::Rule,
errors::SyntaxError as InputSyntaxError,
expressions::{ArrayInlineExpression, Expression},
sections::Header,
tables::Table,
types::{DataType, IntegerType, Type},
values::{NumberValue, Value},
};
use pest::{
error::{Error, ErrorVariant},
Span,
};
use std::{num::ParseIntError, path::PathBuf, str::ParseBoolError};
#[derive(Debug, Error)]
pub enum InputParserError {
#[error("Program input value {} not found", _0)]
InputNotFound(String),
#[error("Cannot read from the provided file path - {:?}", _0)]
FileReadError(PathBuf),
#[error("{}", _0)]
ParseIntError(#[from] ParseIntError),
#[error("{}", _0)]
ParseBoolError(#[from] ParseBoolError),
#[error("{}", _0)]
SyntaxError(#[from] InputSyntaxError),
#[error("Unable to construct program input abstract syntax tree")]
SyntaxTreeError,
}
impl InputParserError {
pub fn set_path(&mut self, path: &str, _content: &[String]) {
if let InputParserError::SyntaxError(error) = self {
let new_error: Error<Rule> = match error {
InputSyntaxError::Error(error) => {
let new_error = error.clone();
new_error.with_path(path)
}
};
tracing::error!("{}", new_error);
*error = InputSyntaxError::Error(new_error);
}
}
pub fn get_path(&self) -> Option<&str> {
None
}
fn new_from_span(message: String, span: &Span) -> Self {
let error = Error::new_from_span(ErrorVariant::CustomError { message }, span.to_owned());
InputParserError::SyntaxError(InputSyntaxError::from(error))
}
pub fn array_index(actual: String, span: &Span) -> Self {
let message = format!("Expected constant number for array index, found `{}`", actual);
Self::new_from_span(message, span)
}
pub fn integer_type_mismatch(expected: IntegerType, received: IntegerType, span: &Span) -> Self {
let message = format!("expected data type `{}`, found `{}`", expected, received);
Self::new_from_span(message, span)
}
pub fn invalid_char(character: String, span: &Span) -> Self {
let message = format!("Expected valid character found `{}`", character);
Self::new_from_span(message, span)
}
pub fn invalid_string_dimensions(span: &Span) -> Self {
let message = "String type defintion of a char array should not be multi-dimensional".to_string();
Self::new_from_span(message, span)
}
pub fn invalid_string_length(expected: usize, received: usize, span: &Span) -> Self {
let message = format!(
"Expected size of char array `{}` to match string size instead received `{}`",
expected, received
);
Self::new_from_span(message, span)
}
pub fn implicit_type(data_type: DataType, implicit: NumberValue) -> Self {
let message = format!("expected `{}`, found `{}`", data_type, implicit);
Self::new_from_span(message, implicit.span())
}
pub fn implicit_group(number: NumberValue) -> Self {
let message = format!("group coordinates should be in (x, y)group format, found `{}`", number);
Self::new_from_span(message, number.span())
}
pub fn data_type_mismatch(data_type: DataType, value: Value) -> Self {
let message = format!("expected data type `{}`, found `{}`", data_type, value);
Self::new_from_span(message, value.span())
}
pub fn expression_type_mismatch(type_: Type, expression: Expression) -> Self {
let message = format!("expected expression type `{}`, found `{}`", type_, expression);
let span = expression.span().to_owned();
Self::new_from_span(message, &span)
}
pub fn array_inline_length(number: usize, array: ArrayInlineExpression) -> Self {
let message = format!(
"expected an array with a fixed size of {} elements, found one with {} elements",
number,
array.expressions.len()
);
let span = array.span.to_owned();
Self::new_from_span(message, &span)
}
pub fn array_init_length(expected: Vec<usize>, actual: Vec<usize>, span: &Span) -> Self {
let message = format!(
"expected an array with a fixed size of {:?} elements, found one with {:?} elements",
expected, actual
);
Self::new_from_span(message, span)
}
pub fn input_section_header(header: Header) -> Self {
let message = format!("the section header `{}` is not valid in an input `.in` file", header);
let span = header.span();
Self::new_from_span(message, &span)
}
pub fn public_section(header: Header) -> Self {
let message = format!("the section header `{}` is not a public section", header);
let span = header.span();
Self::new_from_span(message, &span)
}
pub fn private_section(header: Header) -> Self {
let message = format!("the section header `{}` is not a private section", header);
let span = header.span();
Self::new_from_span(message, &span)
}
pub fn table(table: Table) -> Self {
let message = format!(
"the double bracket section `{}` is not valid in an input `.in` file",
table
);
Self::new_from_span(message, &table.span)
}
pub fn tuple_length(expected: usize, actual: usize, span: &Span) -> Self {
let message = format!(
"expected a tuple with {} elements, found a tuple with {} elements",
expected, actual
);
Self::new_from_span(message, span)
}
pub fn section(header: Header) -> Self {
let message = format!(
"the section header `{}` must have a double bracket visibility in a state `.state` file",
header
);
let span = header.span();
Self::new_from_span(message, &span)
}
}
impl From<Error<Rule>> for InputParserError {
fn from(error: Error<Rule>) -> Self {
InputParserError::SyntaxError(InputSyntaxError::from(error))
}
}

View File

@ -1,44 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::ast::Rule;
use pest::error::Error;
#[derive(Debug, Error)]
pub enum SyntaxError {
#[error("aborting due to syntax error")]
Error(Error<Rule>),
}
impl From<Error<Rule>> for SyntaxError {
fn from(mut error: Error<Rule>) -> Self {
error = error.renamed_rules(|rule| match *rule {
Rule::LINE_END => "`;`".to_owned(),
Rule::type_integer => "`u32`".to_owned(),
Rule::type_field => "`field`".to_owned(),
Rule::type_group => "`group`".to_owned(),
Rule::file => "a table or section".to_owned(),
Rule::identifier => "a variable name".to_owned(),
Rule::type_ => "a type".to_owned(),
Rule::header => "[[public]] or [[private]]".to_owned(),
rule => format!("{:?}", rule),
});
SyntaxError::Error(error)
}
}

View File

@ -1,29 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{ast::Rule, expressions::Expression, types::ArrayDimensions};
use pest::Span;
use pest_ast::FromPest;
#[derive(Clone, Debug, FromPest, PartialEq)]
#[pest_ast(rule(Rule::expression_array_initializer))]
pub struct ArrayInitializerExpression<'ast> {
pub expression: Box<Expression<'ast>>,
pub dimensions: ArrayDimensions<'ast>,
#[pest_ast(outer())]
pub span: Span<'ast>,
}

View File

@ -1,28 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{ast::Rule, expressions::Expression};
use pest::Span;
use pest_ast::FromPest;
#[derive(Clone, Debug, FromPest, PartialEq)]
#[pest_ast(rule(Rule::expression_array_inline))]
pub struct ArrayInlineExpression<'ast> {
pub expressions: Vec<Expression<'ast>>,
#[pest_ast(outer())]
pub span: Span<'ast>,
}

View File

@ -1,75 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{ast::Rule, expressions::*, values::Value};
use pest::Span;
use pest_ast::FromPest;
use std::fmt;
#[derive(Clone, Debug, FromPest, PartialEq)]
#[pest_ast(rule(Rule::expression))]
pub enum Expression<'ast> {
ArrayInitializer(ArrayInitializerExpression<'ast>),
ArrayInline(ArrayInlineExpression<'ast>),
StringExpression(StringExpression<'ast>),
Tuple(TupleExpression<'ast>),
Value(Value<'ast>),
}
impl<'ast> Expression<'ast> {
pub fn span(&self) -> &Span {
match self {
Expression::ArrayInitializer(expression) => &expression.span,
Expression::ArrayInline(expression) => &expression.span,
Expression::StringExpression(string) => &string.span,
Expression::Tuple(tuple) => &tuple.span,
Expression::Value(value) => value.span(),
}
}
}
impl<'ast> fmt::Display for Expression<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Expression::ArrayInitializer(ref expression) => {
write!(f, "array [{} ; {}]", expression.expression, expression.dimensions)
}
Expression::ArrayInline(ref array) => {
let values = array
.expressions
.iter()
.map(|x| x.to_string())
.collect::<Vec<_>>()
.join(", ");
write!(f, "array [{}]", values)
}
Expression::StringExpression(ref string) => write!(f, "{}", string),
Expression::Tuple(ref tuple) => {
let values = tuple
.expressions
.iter()
.map(|x| x.to_string())
.collect::<Vec<_>>()
.join(", ");
write!(f, "({})", values)
}
Expression::Value(ref expression) => write!(f, "{}", expression),
}
}
}

View File

@ -1,30 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
pub mod array_initializer_expression;
pub use array_initializer_expression::*;
pub mod array_inline_expression;
pub use array_inline_expression::*;
pub mod expression;
pub use expression::*;
pub mod tuple_expression;
pub use tuple_expression::*;
pub mod string_expression;
pub use string_expression::*;

View File

@ -1,41 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{ast::Rule, values::CharTypes};
use pest::Span;
use pest_ast::FromPest;
use std::fmt;
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::expression_string))]
pub struct StringExpression<'ast> {
pub chars: Vec<CharTypes<'ast>>,
#[pest_ast(outer())]
pub span: Span<'ast>,
}
impl<'ast> fmt::Display for StringExpression<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "\"")?;
for character in self.chars.iter() {
write!(f, "{:?}", character)?;
}
write!(f, "\"")
}
}

View File

@ -1,28 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{ast::Rule, expressions::Expression};
use pest::Span;
use pest_ast::FromPest;
#[derive(Clone, Debug, FromPest, PartialEq)]
#[pest_ast(rule(Rule::expression_tuple))]
pub struct TupleExpression<'ast> {
pub expressions: Vec<Expression<'ast>>,
#[pest_ast(outer())]
pub span: Span<'ast>,
}

View File

@ -1,29 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{ast::Rule, common::EOI, files::TableOrSection};
use pest::Span;
use pest_ast::FromPest;
#[derive(Clone, Debug, FromPest, PartialEq)]
#[pest_ast(rule(Rule::file))]
pub struct File<'ast> {
pub entries: Vec<TableOrSection<'ast>>,
pub eoi: EOI,
#[pest_ast(outer())]
pub span: Span<'ast>,
}

View File

@ -1,21 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
pub mod file;
pub use file::*;
pub mod table_or_section;
pub use table_or_section::*;

View File

@ -1,26 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{ast::Rule, sections::Section, tables::Table};
use pest_ast::FromPest;
#[derive(Clone, Debug, FromPest, PartialEq)]
#[pest_ast(rule(Rule::table_or_section))]
pub enum TableOrSection<'ast> {
Section(Section<'ast>),
Table(Table<'ast>),
}

View File

@ -1,277 +0,0 @@
/// Common
// Declared in common/identifier.rs
identifier = @{ ((!protected_name ~ ASCII_ALPHA) | (protected_name ~ (ASCII_ALPHANUMERIC | "_"))) ~ (ASCII_ALPHANUMERIC | "_")* }
protected_name = {
"address"
| "as"
| "const"
| "else"
| "false"
| type_field
| type_char
| "for"
| "function"
| type_group
| "if"
| "import"
| "in"
| "let"
| main
| "mut"
| private
| public
| record
| registers
| "return"
| state
| state_leaf
| "static"
| "test"
| "true"
}
// Declared in common/line_end.rs
LINE_END = { ";" ~ NEWLINE* }
/// Types
// Declared in types/type_.rs
type_ = { type_tuple | type_array | type_data }
// Declared in types/integer_type.rs
type_integer = {
type_integer_signed
| type_integer_unsigned
}
// Declared in types/unsigned_integer_type.rs
type_u8 = { "u8" }
type_u16 = { "u16" }
type_u32 = { "u32" }
type_u64 = { "u64" }
type_u128 = { "u128" }
type_integer_unsigned = {
type_u8
| type_u16
| type_u32
| type_u64
| type_u128
}
// Declared in types/signed_integer_type.rs
type_i8 = { "i8" }
type_i16 = { "i16" }
type_i32 = { "i32" }
type_i64 = { "i64" }
type_i128 = { "i128" }
type_integer_signed = {
type_i8
| type_i16
| type_i32
| type_i64
| type_i128
}
// Declared in types/char_type.rs
type_char = { "char" }
// Declared in types/field_type.rs
type_field = { "field" }
// Declared in types/group_type.rs
type_group = { "group" }
// Declared in types/boolean_type.rs
type_boolean = { "bool" }
// Declared in types/address_type.rs
type_address = { "address" }
// Declared in types/data_type.rs
type_data = { type_field | type_group | type_boolean | type_address | type_integer | type_char }
// Declared in types/array_type.rs
type_array = { "[" ~ type_ ~ ";" ~ array_dimensions ~ "]" }
// Declared in types/array_dimensions.rs
array_dimensions = {
dimension_single
| dimension_multiple
}
// Declared in types/array_dimensions.rs
dimension_single = {
number_positive
}
// Declared in types/array_dimensions.rs
dimension_multiple = { "(" ~ number_positive ~ ("," ~ number_positive)* ~ ")"}
type_tuple = { "(" ~ NEWLINE* ~ (type_ ~ ("," ~ NEWLINE* ~ type_)+ ~ ","?)? ~ NEWLINE* ~ ")" }
/// Values
// Declared in values/value.rs
value = {
value_address
| value_boolean
| value_field
| value_group
| value_char
| value_integer
| value_number // must be last as a catch all
}
// Declared in values/number_value.rs
value_number = { number_negative | number_positive }
// Declared in values/number_negative.rs
number_negative = @{ "-" ~ ASCII_DIGIT+ }
// Declared in values/number_positive.rs
number_positive = @{ ASCII_DIGIT+ }
// Decalred in values/char_types.rs
// ANY is equivalent to '\u{00}'..'\u{10FFFF}'
basic_char = { ANY }
escaped_char = @{ "\\" ~ ("\"" | "\'" | "\\" | "/" | "b" | "f" | "n" | "r" | "t") }
hex_char = @{ "\\" ~ "x" ~ ASCII_HEX_DIGIT{2} }
unicode_char = @{ "\\" ~ "u" ~ "{" ~ ASCII_HEX_DIGIT{1, 6} ~ "}" }
char_types = {
escaped_char
| unicode_char
| hex_char
| basic_char
}
// Declared in values/char_value.rs
value_char = ${ "\'" ~ char_types ~ "\'" }
// Declared in values/integer_value.rs
value_integer = { value_integer_signed | value_integer_unsigned}
// Declared in values/signed_integer_value.rs
value_integer_signed = ${ value_number ~ type_integer_signed }
// Declared in values/unsigned_integer_value.rs
value_integer_unsigned = ${ number_positive ~ type_integer_unsigned }
// Declared in values/boolean_value.rs
value_boolean = { "true" | "false" }
// Declared in values/field_value.rs
value_field = ${ value_number ~ type_field }
// Declared in values/group_value.rs
value_group = ${ group_single_or_tuple ~ type_group }
group_single_or_tuple = {value_number | group_tuple}
group_tuple = !{"(" ~ group_coordinate ~ "," ~ group_coordinate ~ ")"}
// Declared in values/group_coordinate.rs
group_coordinate = {
value_number
| sign_high
| sign_low
| inferred
}
sign_high = @{"+"}
sign_low = @{"-"}
inferred = @{"_"}
// Declared in values/address.rs
address = @{ "aleo" ~ ASCII_DIGIT ~ (LOWERCASE_LETTER | ASCII_DIGIT){58} }
// Declared in values/address_typed.rs
address_typed = ${ type_address ~ "(" ~ address ~ ")" }
// Declared in values/address_value.rs
value_address = {address | address_typed}
/// Expressions
// Declared in expressions/array_initializer_expression.rs
expression_array_initializer = { "[" ~ expression ~ ";" ~ array_dimensions ~ "]" }
// Declared in expressions/array_inline_expression.rs
expression_array_inline = { "[" ~ NEWLINE* ~ inline_array_inner ~ NEWLINE* ~ "]"}
inline_array_inner = _{ (expression ~ ("," ~ NEWLINE* ~ expression)*)? }
// Declared in expressions/string_expression.rs
expression_string = ${ "\"" ~ (!"\"" ~ char_types)+ ~ "\"" }
// Declared in expressions/expression.rs
expression = {
value
| expression_tuple
| expression_array_inline
| expression_array_initializer
| expression_string
}
expression_tuple = { "(" ~ expression ~ ("," ~ expression)+ ~")" }
/// Parameters
// Declared in parameters/parameters.rs
parameter = { identifier ~ ":" ~ type_ }
/// Section
// Declared in sections/section.rs
section = { "[" ~ header ~ "]" ~ NEWLINE+ ~ (definition ~ NEWLINE*)* }
// Declared in sections/main_.rs
main = { "main" }
// Declared in sections/record.rs
record = { "record" }
// Declared in sections/registers.rs
registers = { "registers" }
// Declared in sections/state.rs
state = { "state" }
// Declared in sections/constants.rs
constants = { "constants" }
// Declared in sections/state_leaf.rs
state_leaf = { "state_leaf" }
// Declared in sections/header.rs
header = { main | constants | record | registers | state_leaf | state | identifier }
/// Definitions
// Declared in definition/definition.rs
definition = { parameter ~ "=" ~ expression ~ LINE_END }
/// Table
// Declared in tables/public.rs
public = { "public" }
// Declared in tables/private.rs
private = { "private" }
// Declared in tables/visibility.rs
visibility = { public | private }
// Declared in sections/table.rs
table = {"[[" ~ visibility ~ "]]" ~ NEWLINE+ ~ section*}
/// Utilities
COMMENT = _{ ("/*" ~ (!"*/" ~ ANY)* ~ "*/") | ("//" ~ (!NEWLINE ~ ANY)*) }
WHITESPACE = _{ " " | "\t" ~ (NEWLINE)* }
/// Files
// Declared in files/table_or_section.rs
table_or_section = { table | section }
// Declared in files/file.rs
file = { SOI ~ NEWLINE* ~ table_or_section* ~ NEWLINE* ~ EOI }

View File

@ -1,59 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
#![doc = include_str!("../README.md")]
#[macro_use]
extern crate pest_derive;
#[macro_use]
extern crate thiserror;
pub mod errors;
pub use errors::*;
mod ast;
pub mod common;
pub mod definitions;
pub mod expressions;
pub mod files;
pub mod parameters;
pub mod sections;
pub mod tables;
pub mod types;
pub mod values;
use from_pest::FromPest;
use std::{fs, path::Path};
pub struct LeoInputParser;
impl LeoInputParser {
/// Reads in the given file path into a string.
pub fn load_file(file_path: &Path) -> Result<String, InputParserError> {
fs::read_to_string(file_path).map_err(|_| InputParserError::FileReadError(file_path.to_owned()))
}
/// Parses the input file and constructs a syntax tree.
pub fn parse_file(input_file: &str) -> Result<files::File, InputParserError> {
// Parse the file using leo-input.pest
let mut file = ast::parse(input_file)?;
// Build the abstract syntax tree
let syntax_tree = files::File::from_pest(&mut file).map_err(|_| InputParserError::SyntaxTreeError)?;
Ok(syntax_tree)
}
}

View File

@ -1,18 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
pub mod parameter;
pub use parameter::*;

View File

@ -1,29 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{ast::Rule, common::Identifier, types::Type};
use pest::Span;
use pest_ast::FromPest;
#[derive(Clone, Debug, FromPest, PartialEq)]
#[pest_ast(rule(Rule::parameter))]
pub struct Parameter<'ast> {
pub variable: Identifier<'ast>,
pub type_: Type<'ast>,
#[pest_ast(outer())]
pub span: Span<'ast>,
}

View File

@ -1,27 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::ast::Rule;
use pest::Span;
use pest_ast::FromPest;
#[derive(Clone, Debug, FromPest, PartialEq)]
#[pest_ast(rule(Rule::constants))]
pub struct Constants<'ast> {
#[pest_ast(outer())]
pub span: Span<'ast>,
}

View File

@ -1,65 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{
ast::Rule,
common::Identifier,
sections::{Constants, Main, Record, Registers, State, StateLeaf},
};
use pest::Span;
use pest_ast::FromPest;
use std::fmt;
#[derive(Clone, Debug, FromPest, PartialEq)]
#[pest_ast(rule(Rule::header))]
pub enum Header<'ast> {
Constants(Constants<'ast>),
Main(Main<'ast>),
Record(Record<'ast>),
Registers(Registers<'ast>),
State(State<'ast>),
StateLeaf(StateLeaf<'ast>),
Identifier(Identifier<'ast>),
}
impl<'ast> Header<'ast> {
pub fn span(self) -> Span<'ast> {
match self {
Header::Constants(constants) => constants.span,
Header::Main(main) => main.span,
Header::Record(record) => record.span,
Header::Registers(registers) => registers.span,
Header::State(state) => state.span,
Header::StateLeaf(state_leaf) => state_leaf.span,
Header::Identifier(identifier) => identifier.span,
}
}
}
impl<'ast> fmt::Display for Header<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Header::Constants(_constants) => write!(f, "constants"),
Header::Main(_main) => write!(f, "main"),
Header::Record(_record) => write!(f, "record"),
Header::Registers(_registers) => write!(f, "registers"),
Header::State(_state) => write!(f, "state"),
Header::StateLeaf(_state_leaf) => write!(f, "state_leaf"),
Header::Identifier(identifier) => write!(f, "{}", identifier.value),
}
}
}

View File

@ -1,27 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::ast::Rule;
use pest::Span;
use pest_ast::FromPest;
#[derive(Clone, Debug, FromPest, PartialEq)]
#[pest_ast(rule(Rule::main))]
pub struct Main<'ast> {
#[pest_ast(outer())]
pub span: Span<'ast>,
}

View File

@ -1,39 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
pub mod constants;
pub use constants::*;
pub mod header;
pub use header::*;
pub mod main_;
pub use main_::*;
pub mod record;
pub use record::*;
pub mod registers;
pub use registers::*;
pub mod state;
pub use state::*;
pub mod state_leaf;
pub use state_leaf::*;
pub mod section;
pub use section::*;

View File

@ -1,27 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::ast::Rule;
use pest::Span;
use pest_ast::FromPest;
#[derive(Clone, Debug, FromPest, PartialEq)]
#[pest_ast(rule(Rule::record))]
pub struct Record<'ast> {
#[pest_ast(outer())]
pub span: Span<'ast>,
}

View File

@ -1,27 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::ast::Rule;
use pest::Span;
use pest_ast::FromPest;
#[derive(Clone, Debug, FromPest, PartialEq)]
#[pest_ast(rule(Rule::registers))]
pub struct Registers<'ast> {
#[pest_ast(outer())]
pub span: Span<'ast>,
}

View File

@ -1,29 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{ast::Rule, definitions::Definition, sections::Header};
use pest::Span;
use pest_ast::FromPest;
#[derive(Clone, Debug, FromPest, PartialEq)]
#[pest_ast(rule(Rule::section))]
pub struct Section<'ast> {
pub header: Header<'ast>,
pub definitions: Vec<Definition<'ast>>,
#[pest_ast(outer())]
pub span: Span<'ast>,
}

View File

@ -1,27 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::ast::Rule;
use pest::Span;
use pest_ast::FromPest;
#[derive(Clone, Debug, FromPest, PartialEq)]
#[pest_ast(rule(Rule::state))]
pub struct State<'ast> {
#[pest_ast(outer())]
pub span: Span<'ast>,
}

View File

@ -1,27 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::ast::Rule;
use pest::Span;
use pest_ast::FromPest;
#[derive(Clone, Debug, FromPest, PartialEq)]
#[pest_ast(rule(Rule::state_leaf))]
pub struct StateLeaf<'ast> {
#[pest_ast(outer())]
pub span: Span<'ast>,
}

View File

@ -1,27 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
pub mod private;
pub use private::*;
pub mod public;
pub use public::*;
pub mod table;
pub use table::*;
pub mod visibility;
pub use visibility::*;

View File

@ -1,34 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::ast::Rule;
use pest::Span;
use pest_ast::FromPest;
use std::fmt;
#[derive(Clone, Debug, FromPest, PartialEq)]
#[pest_ast(rule(Rule::private))]
pub struct Private<'ast> {
#[pest_ast(outer())]
pub span: Span<'ast>,
}
impl<'ast> fmt::Display for Private<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.span.as_str())
}
}

View File

@ -1,34 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::ast::Rule;
use pest::Span;
use pest_ast::FromPest;
use std::fmt;
#[derive(Clone, Debug, FromPest, PartialEq)]
#[pest_ast(rule(Rule::public))]
pub struct Public<'ast> {
#[pest_ast(outer())]
pub span: Span<'ast>,
}
impl<'ast> fmt::Display for Public<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.span.as_str())
}
}

View File

@ -1,36 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{ast::Rule, sections::Section, tables::Visibility};
use pest::Span;
use pest_ast::FromPest;
use std::fmt;
#[derive(Clone, Debug, FromPest, PartialEq)]
#[pest_ast(rule(Rule::table))]
pub struct Table<'ast> {
pub visibility: Visibility<'ast>,
pub sections: Vec<Section<'ast>>,
#[pest_ast(outer())]
pub span: Span<'ast>,
}
impl<'ast> fmt::Display for Table<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[[{}]]", self.visibility)
}
}

View File

@ -1,39 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{
ast::Rule,
tables::{Private, Public},
};
use pest_ast::FromPest;
use std::fmt;
#[derive(Clone, Debug, FromPest, PartialEq)]
#[pest_ast(rule(Rule::visibility))]
pub enum Visibility<'ast> {
Private(Private<'ast>),
Public(Public<'ast>),
}
impl<'ast> fmt::Display for Visibility<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Visibility::Private(private) => write!(f, "{}", private),
Visibility::Public(public) => write!(f, "{}", public),
}
}
}

View File

@ -1,23 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::ast::Rule;
use pest_ast::FromPest;
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::type_address))]
pub struct AddressType {}

View File

@ -1,87 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{ast::Rule, values::PositiveNumber};
use pest::Span;
use pest_ast::FromPest;
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::array_dimensions))]
pub enum ArrayDimensions<'ast> {
Single(Single<'ast>),
Multiple(Multiple<'ast>),
}
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::dimension_single))]
pub struct Single<'ast> {
pub number: PositiveNumber<'ast>,
#[pest_ast(outer())]
pub span: Span<'ast>,
}
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::dimension_multiple))]
pub struct Multiple<'ast> {
pub numbers: Vec<PositiveNumber<'ast>>,
#[pest_ast(outer())]
pub span: Span<'ast>,
}
impl<'ast> ArrayDimensions<'ast> {
pub fn next_dimension(&self) -> Self {
match self {
ArrayDimensions::Single(single) => ArrayDimensions::Multiple(Multiple {
numbers: vec![],
span: single.span.clone(),
}),
ArrayDimensions::Multiple(multiple) => {
let old_dimension = &multiple.numbers;
ArrayDimensions::Multiple(Multiple {
numbers: old_dimension[1..].to_vec(),
span: multiple.span.clone(),
})
}
}
}
pub fn is_empty(&self) -> bool {
match self {
ArrayDimensions::Single(_) => false,
ArrayDimensions::Multiple(multiple) => multiple.numbers.is_empty(),
}
}
}
impl<'ast> std::fmt::Display for ArrayDimensions<'ast> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match *self {
ArrayDimensions::Single(ref single) => write!(f, "{}", single.number),
ArrayDimensions::Multiple(ref multiple) => {
let string = multiple
.numbers
.iter()
.map(|x| x.value.clone())
.collect::<Vec<_>>()
.join(", ");
write!(f, "{}", string)
}
}
}
}

View File

@ -1,38 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{
ast::Rule,
types::{ArrayDimensions, Type},
};
use pest::Span;
use pest_ast::FromPest;
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::type_array))]
pub struct ArrayType<'ast> {
pub type_: Box<Type<'ast>>,
pub dimensions: ArrayDimensions<'ast>,
#[pest_ast(outer())]
pub span: Span<'ast>,
}
impl<'ast> std::fmt::Display for ArrayType<'ast> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "[{}; ({})]", self.type_, self.dimensions)
}
}

View File

@ -1,23 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::ast::Rule;
use pest_ast::FromPest;
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::type_boolean))]
pub struct BooleanType {}

View File

@ -1,23 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::ast::Rule;
use pest_ast::FromPest;
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::type_char))]
pub struct CharType {}

View File

@ -1,47 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{
ast::Rule,
types::{BooleanType, CharType, FieldType, GroupType, IntegerType},
};
use crate::types::AddressType;
use pest_ast::FromPest;
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::type_data))]
pub enum DataType {
Address(AddressType),
Boolean(BooleanType),
Char(CharType),
Field(FieldType),
Group(GroupType),
Integer(IntegerType),
}
impl std::fmt::Display for DataType {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
DataType::Address(_) => write!(f, "address"),
DataType::Boolean(_) => write!(f, "bool"),
DataType::Char(_) => write!(f, "char"),
DataType::Field(_) => write!(f, "field"),
DataType::Group(_) => write!(f, "group"),
DataType::Integer(ref integer) => write!(f, "{}", integer),
}
}
}

View File

@ -1,23 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::ast::Rule;
use pest_ast::FromPest;
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::type_field))]
pub struct FieldType {}

View File

@ -1,23 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::ast::Rule;
use pest_ast::FromPest;
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::type_group))]
pub struct GroupType {}

View File

@ -1,39 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{
ast::Rule,
types::{SignedIntegerType, UnsignedIntegerType},
};
use pest_ast::FromPest;
use std::fmt;
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::type_integer))]
pub enum IntegerType {
Signed(SignedIntegerType),
Unsigned(UnsignedIntegerType),
}
impl fmt::Display for IntegerType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
IntegerType::Signed(integer) => write!(f, "{}", integer),
IntegerType::Unsigned(integer) => write!(f, "{}", integer),
}
}
}

View File

@ -1,54 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
pub mod address_type;
pub use address_type::*;
pub mod array_dimensions;
pub use array_dimensions::*;
pub mod array_type;
pub use array_type::*;
pub mod boolean_type;
pub use boolean_type::*;
pub mod char_type;
pub use char_type::*;
pub mod data_type;
pub use data_type::*;
pub mod field_type;
pub use field_type::*;
pub mod group_type;
pub use group_type::*;
pub mod integer_type;
pub use integer_type::*;
pub mod signed_integer_type;
pub use signed_integer_type::*;
pub mod tuple_type;
pub use tuple_type::*;
pub mod type_;
pub use type_::*;
pub mod unsigned_integer_type;
pub use unsigned_integer_type::*;

View File

@ -1,62 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::ast::Rule;
use pest_ast::FromPest;
use std::fmt;
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::type_integer_signed))]
pub enum SignedIntegerType {
I8Type(I8Type),
I16Type(I16Type),
I32Type(I32Type),
I64Type(I64Type),
I128Type(I128Type),
}
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::type_i8))]
pub struct I8Type {}
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::type_i16))]
pub struct I16Type {}
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::type_i32))]
pub struct I32Type {}
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::type_i64))]
pub struct I64Type {}
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::type_i128))]
pub struct I128Type {}
impl fmt::Display for SignedIntegerType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
SignedIntegerType::I8Type(_) => write!(f, "i8"),
SignedIntegerType::I16Type(_) => write!(f, "i16"),
SignedIntegerType::I32Type(_) => write!(f, "i32"),
SignedIntegerType::I64Type(_) => write!(f, "i64"),
SignedIntegerType::I128Type(_) => write!(f, "i128"),
}
}
}

View File

@ -1,36 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{ast::Rule, types::Type};
use pest::Span;
use pest_ast::FromPest;
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::type_tuple))]
pub struct TupleType<'ast> {
pub types_: Vec<Type<'ast>>,
#[pest_ast(outer())]
pub span: Span<'ast>,
}
impl<'ast> std::fmt::Display for TupleType<'ast> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let tuple = self.types_.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(", ");
write!(f, "({})", tuple)
}
}

View File

@ -1,38 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{ast::Rule, types::*};
use pest_ast::FromPest;
use std::fmt;
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::type_))]
pub enum Type<'ast> {
Basic(DataType),
Array(ArrayType<'ast>),
Tuple(TupleType<'ast>),
}
impl<'ast> fmt::Display for Type<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Type::Basic(ref basic) => write!(f, "{}", basic),
Type::Array(ref array) => write!(f, "{}", array),
Type::Tuple(ref tuple) => write!(f, "{}", tuple),
}
}
}

View File

@ -1,62 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::ast::Rule;
use pest_ast::FromPest;
use std::fmt;
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::type_integer_unsigned))]
pub enum UnsignedIntegerType {
U8Type(U8Type),
U16Type(U16Type),
U32Type(U32Type),
U64Type(U64Type),
U128Type(U128Type),
}
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::type_u8))]
pub struct U8Type {}
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::type_u16))]
pub struct U16Type {}
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::type_u32))]
pub struct U32Type {}
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::type_u64))]
pub struct U64Type {}
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::type_u128))]
pub struct U128Type {}
impl fmt::Display for UnsignedIntegerType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
UnsignedIntegerType::U8Type(_) => write!(f, "u8"),
UnsignedIntegerType::U16Type(_) => write!(f, "u16"),
UnsignedIntegerType::U32Type(_) => write!(f, "u32"),
UnsignedIntegerType::U64Type(_) => write!(f, "u64"),
UnsignedIntegerType::U128Type(_) => write!(f, "u128"),
}
}
}

View File

@ -1,36 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::ast::{span_into_string, Rule};
use pest::Span;
use pest_ast::FromPest;
use std::fmt;
#[derive(Clone, Debug, FromPest, PartialEq)]
#[pest_ast(rule(Rule::address))]
pub struct Address<'ast> {
#[pest_ast(outer(with(span_into_string)))]
pub value: String,
#[pest_ast(outer())]
pub span: Span<'ast>,
}
impl<'ast> fmt::Display for Address<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.value)
}
}

View File

@ -1,36 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{ast::Rule, types::AddressType, values::address::Address};
use pest::Span;
use pest_ast::FromPest;
use std::fmt;
#[derive(Clone, Debug, FromPest, PartialEq)]
#[pest_ast(rule(Rule::address_typed))]
pub struct AddressTyped<'ast> {
pub type_: AddressType,
pub address: Address<'ast>,
#[pest_ast(outer())]
pub span: Span<'ast>,
}
impl<'ast> fmt::Display for AddressTyped<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "address({})", self.address)
}
}

View File

@ -1,49 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{
ast::Rule,
values::{Address, AddressTyped},
};
use pest::Span;
use pest_ast::FromPest;
use std::fmt;
#[derive(Clone, Debug, FromPest, PartialEq)]
#[pest_ast(rule(Rule::value_address))]
pub enum AddressValue<'ast> {
Implicit(Address<'ast>),
Explicit(AddressTyped<'ast>),
}
impl<'ast> AddressValue<'ast> {
pub(crate) fn span(&self) -> &Span<'ast> {
match self {
AddressValue::Implicit(address) => &address.span,
AddressValue::Explicit(address) => &address.span,
}
}
}
impl<'ast> fmt::Display for AddressValue<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
AddressValue::Explicit(address) => write!(f, "{}", address),
AddressValue::Implicit(address) => write!(f, "{}", address),
}
}
}

View File

@ -1,36 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::ast::{span_into_string, Rule};
use pest::Span;
use pest_ast::FromPest;
use std::fmt;
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::value_boolean))]
pub struct BooleanValue<'ast> {
#[pest_ast(outer(with(span_into_string)))]
pub value: String,
#[pest_ast(outer())]
pub span: Span<'ast>,
}
impl<'ast> fmt::Display for BooleanValue<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.value)
}
}

View File

@ -1,137 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{
ast::{span_into_string, Rule},
errors::InputParserError,
};
use pest::Span;
use pest_ast::FromPest;
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::basic_char))]
pub struct BasicChar<'ast> {
#[pest_ast(outer(with(span_into_string)))]
pub value: String,
#[pest_ast(outer())]
pub span: Span<'ast>,
}
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::escaped_char))]
pub struct EscapedChar<'ast> {
#[pest_ast(outer(with(span_into_string)))]
pub value: String,
#[pest_ast(outer())]
pub span: Span<'ast>,
}
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::hex_char))]
pub struct HexChar<'ast> {
#[pest_ast(outer(with(span_into_string)))]
pub value: String,
#[pest_ast(outer())]
pub span: Span<'ast>,
}
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::unicode_char))]
pub struct UnicodeChar<'ast> {
#[pest_ast(outer(with(span_into_string)))]
pub value: String,
#[pest_ast(outer())]
pub span: Span<'ast>,
}
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::char_types))]
pub enum CharTypes<'ast> {
Basic(BasicChar<'ast>),
Escaped(EscapedChar<'ast>),
Hex(HexChar<'ast>),
Unicode(UnicodeChar<'ast>),
}
impl<'ast> CharTypes<'ast> {
pub fn span(&self) -> &Span<'ast> {
match self {
CharTypes::Basic(value) => &value.span,
CharTypes::Escaped(value) => &value.span,
CharTypes::Hex(value) => &value.span,
CharTypes::Unicode(value) => &value.span,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Char {
Scalar(char),
NonScalar(u32),
}
impl<'ast> CharTypes<'ast> {
pub fn inner(self) -> Result<Char, InputParserError> {
match self {
Self::Basic(character) => {
if let Some(character) = character.value.chars().next() {
return Ok(Char::Scalar(character));
}
Err(InputParserError::invalid_char(character.value, &character.span))
}
Self::Escaped(character) => {
if let Some(inner) = character.value.chars().nth(1) {
return match inner {
'0' => Ok(Char::Scalar(0 as char)),
't' => Ok(Char::Scalar(9 as char)),
'n' => Ok(Char::Scalar(10 as char)),
'r' => Ok(Char::Scalar(13 as char)),
'\"' => Ok(Char::Scalar(34 as char)),
'\'' => Ok(Char::Scalar(39 as char)),
'\\' => Ok(Char::Scalar(92 as char)),
_ => Err(InputParserError::invalid_char(character.value, &character.span)),
};
}
Err(InputParserError::invalid_char(character.value, &character.span))
}
Self::Hex(character) => {
let hex_string_number = character.value[2..character.value.len()].to_string();
if let Ok(number) = u8::from_str_radix(&hex_string_number, 16) {
if number <= 127 {
return Ok(Char::Scalar(number as char));
}
}
Err(InputParserError::invalid_char(character.value, &character.span))
}
Self::Unicode(character) => {
let unicode_string_number = character.value[3..=character.value.len() - 2].to_string();
if let Ok(hex) = u32::from_str_radix(&unicode_string_number, 16) {
if let Some(unicode) = std::char::from_u32(hex) {
return Ok(Char::Scalar(unicode));
} else if hex <= 0x10FFFF {
return Ok(Char::NonScalar(hex));
}
}
Err(InputParserError::invalid_char(character.value, &character.span))
}
}
}
}

View File

@ -1,35 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{ast::Rule, values::CharTypes};
use pest::Span;
use pest_ast::FromPest;
use std::fmt;
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::value_char))]
pub struct CharValue<'ast> {
pub value: CharTypes<'ast>,
#[pest_ast(outer())]
pub span: Span<'ast>,
}
impl<'ast> fmt::Display for CharValue<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self.value)
}
}

View File

@ -1,36 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{ast::Rule, types::FieldType, values::NumberValue};
use pest::Span;
use pest_ast::FromPest;
use std::fmt;
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::value_field))]
pub struct FieldValue<'ast> {
pub number: NumberValue<'ast>,
pub type_: FieldType,
#[pest_ast(outer())]
pub span: Span<'ast>,
}
impl<'ast> fmt::Display for FieldValue<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.number)
}
}

View File

@ -1,73 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{ast::Rule, values::NumberValue};
use pest::Span;
use pest_ast::FromPest;
use std::fmt;
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::group_coordinate))]
pub enum GroupCoordinate<'ast> {
Number(NumberValue<'ast>),
SignHigh(SignHigh<'ast>),
SignLow(SignLow<'ast>),
Inferred(Inferred<'ast>),
}
impl<'ast> GroupCoordinate<'ast> {
pub fn span(&self) -> &Span<'ast> {
match self {
GroupCoordinate::Number(number) => number.span(),
GroupCoordinate::SignHigh(sign_high) => &sign_high.span,
GroupCoordinate::SignLow(sign_low) => &sign_low.span,
GroupCoordinate::Inferred(inferred) => &inferred.span,
}
}
}
impl<'ast> fmt::Display for GroupCoordinate<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
GroupCoordinate::Number(number) => write!(f, "{}", number),
GroupCoordinate::SignHigh(_) => write!(f, "+"),
GroupCoordinate::SignLow(_) => write!(f, "-"),
GroupCoordinate::Inferred(_) => write!(f, "_"),
}
}
}
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::sign_high))]
pub struct SignHigh<'ast> {
#[pest_ast(outer())]
pub span: Span<'ast>,
}
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::sign_low))]
pub struct SignLow<'ast> {
#[pest_ast(outer())]
pub span: Span<'ast>,
}
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::inferred))]
pub struct Inferred<'ast> {
#[pest_ast(outer())]
pub span: Span<'ast>,
}

View File

@ -1,71 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{
ast::Rule,
types::GroupType,
values::{GroupCoordinate, NumberValue},
};
use pest::Span;
use pest_ast::FromPest;
use std::fmt;
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::value_group))]
pub struct GroupValue<'ast> {
pub value: GroupRepresentation<'ast>,
pub type_: GroupType,
#[pest_ast(outer())]
pub span: Span<'ast>,
}
impl<'ast> fmt::Display for GroupValue<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.value)
}
}
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::group_single_or_tuple))]
pub enum GroupRepresentation<'ast> {
Single(NumberValue<'ast>),
Tuple(GroupTuple<'ast>),
}
impl<'ast> fmt::Display for GroupRepresentation<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
GroupRepresentation::Single(number) => write!(f, "{}", number),
GroupRepresentation::Tuple(tuple) => write!(f, "{}", tuple),
}
}
}
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::group_tuple))]
pub struct GroupTuple<'ast> {
pub x: GroupCoordinate<'ast>,
pub y: GroupCoordinate<'ast>,
#[pest_ast(outer())]
pub span: Span<'ast>,
}
impl<'ast> fmt::Display for GroupTuple<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
}

View File

@ -1,49 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{
ast::Rule,
values::{SignedIntegerValue, UnsignedIntegerValue},
};
use pest::Span;
use pest_ast::FromPest;
use std::fmt;
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::value_integer))]
pub enum IntegerValue<'ast> {
Signed(SignedIntegerValue<'ast>),
Unsigned(UnsignedIntegerValue<'ast>),
}
impl<'ast> IntegerValue<'ast> {
pub fn span(&self) -> &Span<'ast> {
match self {
IntegerValue::Signed(integer) => &integer.span,
IntegerValue::Unsigned(integer) => &integer.span,
}
}
}
impl<'ast> fmt::Display for IntegerValue<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
IntegerValue::Signed(integer) => write!(f, "{}", integer),
IntegerValue::Unsigned(integer) => write!(f, "{}", integer),
}
}
}

View File

@ -1,63 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
pub mod address;
pub use address::*;
pub mod address_typed;
pub use address_typed::*;
pub mod address_value;
pub use address_value::*;
pub mod boolean_value;
pub use boolean_value::*;
pub mod char_types;
pub use char_types::*;
pub mod char_value;
pub use char_value::*;
pub mod field_value;
pub use field_value::*;
pub mod group_coordinate;
pub use group_coordinate::*;
pub mod group_value;
pub use group_value::*;
pub mod integer_value;
pub use integer_value::*;
pub mod negative_number;
pub use negative_number::*;
pub mod number_value;
pub use number_value::*;
pub mod positive_number;
pub use positive_number::*;
pub mod signed_integer_value;
pub use signed_integer_value::*;
pub mod value;
pub use value::*;
pub mod unsigned_integer_value;
pub use unsigned_integer_value::*;

View File

@ -1,36 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::ast::{span_into_string, Rule};
use pest::Span;
use pest_ast::FromPest;
use std::fmt;
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::number_negative))]
pub struct NegativeNumber<'ast> {
#[pest_ast(outer(with(span_into_string)))]
pub value: String,
#[pest_ast(outer())]
pub span: Span<'ast>,
}
impl<'ast> fmt::Display for NegativeNumber<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.value)
}
}

View File

@ -1,49 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{
ast::Rule,
values::{NegativeNumber, PositiveNumber},
};
use pest::Span;
use pest_ast::FromPest;
use std::fmt;
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::value_number))]
pub enum NumberValue<'ast> {
Negative(NegativeNumber<'ast>),
Positive(PositiveNumber<'ast>),
}
impl<'ast> NumberValue<'ast> {
pub fn span(&self) -> &Span<'ast> {
match self {
NumberValue::Negative(number) => &number.span,
NumberValue::Positive(number) => &number.span,
}
}
}
impl<'ast> fmt::Display for NumberValue<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
NumberValue::Negative(number) => write!(f, "{}", number),
NumberValue::Positive(number) => write!(f, "{}", number),
}
}
}

View File

@ -1,36 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::ast::{span_into_string, Rule};
use pest::Span;
use pest_ast::FromPest;
use std::fmt;
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::number_positive))]
pub struct PositiveNumber<'ast> {
#[pest_ast(outer(with(span_into_string)))]
pub value: String,
#[pest_ast(outer())]
pub span: Span<'ast>,
}
impl<'ast> fmt::Display for PositiveNumber<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.value)
}
}

View File

@ -1,36 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{ast::Rule, types::SignedIntegerType, values::NumberValue};
use pest::Span;
use pest_ast::FromPest;
use std::fmt;
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::value_integer_signed))]
pub struct SignedIntegerValue<'ast> {
pub number: NumberValue<'ast>,
pub type_: SignedIntegerType,
#[pest_ast(outer())]
pub span: Span<'ast>,
}
impl<'ast> fmt::Display for SignedIntegerValue<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.number)
}
}

View File

@ -1,36 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{ast::Rule, types::UnsignedIntegerType, values::PositiveNumber};
use pest::Span;
use pest_ast::FromPest;
use std::fmt;
#[derive(Clone, Debug, FromPest, PartialEq, Eq)]
#[pest_ast(rule(Rule::value_integer_unsigned))]
pub struct UnsignedIntegerValue<'ast> {
pub number: PositiveNumber<'ast>,
pub type_: UnsignedIntegerType,
#[pest_ast(outer())]
pub span: Span<'ast>,
}
impl<'ast> fmt::Display for UnsignedIntegerValue<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.number)
}
}

View File

@ -1,65 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{
ast::Rule,
values::{BooleanValue, CharValue, FieldValue, GroupValue, IntegerValue, NumberValue},
};
use crate::values::AddressValue;
use pest::Span;
use pest_ast::FromPest;
use std::fmt;
#[derive(Clone, Debug, FromPest, PartialEq)]
#[pest_ast(rule(Rule::value))]
pub enum Value<'ast> {
Address(AddressValue<'ast>),
Boolean(BooleanValue<'ast>),
Char(CharValue<'ast>),
Field(FieldValue<'ast>),
Group(GroupValue<'ast>),
Implicit(NumberValue<'ast>),
Integer(IntegerValue<'ast>),
}
impl<'ast> Value<'ast> {
pub fn span(&self) -> &Span<'ast> {
match self {
Value::Address(value) => value.span(),
Value::Boolean(value) => &value.span,
Value::Char(value) => &value.span,
Value::Field(value) => &value.span,
Value::Group(value) => &value.span,
Value::Implicit(value) => value.span(),
Value::Integer(value) => value.span(),
}
}
}
impl<'ast> fmt::Display for Value<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Value::Address(ref value) => write!(f, "{}", value),
Value::Boolean(ref value) => write!(f, "{}", value),
Value::Char(ref value) => write!(f, "{}", value),
Value::Field(ref value) => write!(f, "{}", value),
Value::Group(ref value) => write!(f, "{}", value),
Value::Implicit(ref value) => write!(f, "{}", value),
Value::Integer(ref value) => write!(f, "{}", value),
}
}
}

View File

@ -34,10 +34,6 @@ version = "1.5.3"
path = "../errors" path = "../errors"
version = "1.5.3" version = "1.5.3"
[dependencies.leo-input]
path = "../input"
version = "1.5.1"
[dependencies.leo-span] [dependencies.leo-span]
path = "../span" path = "../span"
version = "1.5.3" version = "1.5.3"

View File

@ -1,415 +0,0 @@
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{assert_no_whitespace, tokenizer::*, Token, KEYWORD_TOKENS};
use leo_ast::*;
use leo_errors::emitter::Handler;
use leo_errors::{LeoError, ParserError, Result};
use leo_span::{Span, Symbol};
use std::{borrow::Cow, unreachable};
use tendril::format_tendril;
pub trait Context {
fn tokens(&self) -> &Vec<SpannedToken>;
fn tokens_mut(&mut self) -> &mut Vec<SpannedToken>;
fn handler(&self) -> &Handler;
fn end_span(&self) -> Span;
/// Returns the current token if there is one.
fn peek_option(&self) -> Option<&SpannedToken> {
self.tokens().last()
}
/// Emit the error `err`.
fn emit_err(&self, err: ParserError) {
self.handler().emit_err(err.into());
}
///
/// Returns an unexpected end of function [`SyntaxError`].
///
fn eof(&self) -> LeoError {
ParserError::unexpected_eof(&self.end_span()).into()
}
///
/// Returns a reference to the next SpannedToken or error if it does not exist.
///
fn peek_next(&self) -> Result<&SpannedToken> {
self.tokens().get(self.tokens().len() - 2).ok_or_else(|| self.eof())
}
///
/// Returns a reference to the current SpannedToken or error if it does not exist.
///
fn peek(&self) -> Result<&SpannedToken> {
self.tokens().last().ok_or_else(|| self.eof())
}
///
/// Returns a reference to the next Token.
///
fn peek_token(&self) -> Cow<'_, Token> {
self.peek_option()
.map(|x| &x.token)
.map(Cow::Borrowed)
.unwrap_or_else(|| Cow::Owned(Token::Eof))
}
///
/// Returns true if the next token exists.
///
fn has_next(&self) -> bool {
!self.tokens().is_empty()
}
/// Advances the current token.
fn bump(&mut self) -> Option<SpannedToken> {
self.tokens_mut().pop()
}
///
/// Removes the next token if it exists and returns it, or [None] if
/// the next token does not exist.
///
fn eat(&mut self, token: Token) -> Option<SpannedToken> {
if let Some(SpannedToken { token: inner, .. }) = self.peek_option() {
if &token == inner {
return self.bump();
}
}
None
}
///
/// Appends a token to the back of the vector.
///
fn backtrack(&mut self, token: SpannedToken) {
self.tokens_mut().push(token);
}
///
/// Removes the next token if it is a [`Token::Ident(_)`] and returns it, or [None] if
/// the next token is not a [`Token::Ident(_)`] or if the next token does not exist.
///
fn eat_identifier(&mut self) -> Option<Identifier> {
if let Some(SpannedToken {
token: Token::Ident(_), ..
}) = self.peek_option()
{
if let SpannedToken {
token: Token::Ident(name),
span,
} = self.bump().unwrap()
{
return Some(Identifier { name, span });
} else {
unreachable!("eat_identifier_ shouldn't produce this")
}
}
None
}
///
/// Returns a reference to the next token if it is a [`GroupCoordinate`], or [None] if
/// the next token is not a [`GroupCoordinate`].
///
fn peek_group_coordinate(&self, i: &mut usize) -> Option<GroupCoordinate> {
if *i < 1 {
return None;
}
let token = self.tokens().get(*i - 1)?;
*i -= 1;
Some(match &token.token {
Token::Add => GroupCoordinate::SignHigh,
Token::Minus if *i > 0 => match self.tokens().get(*i - 1) {
Some(SpannedToken {
token: Token::Int(value),
span,
}) => {
if *i < 1 {
return None;
}
*i -= 1;
GroupCoordinate::Number(format_tendril!("-{}", value), span.clone())
}
_ => GroupCoordinate::SignLow,
},
Token::Underscore => GroupCoordinate::Inferred,
Token::Int(value) => GroupCoordinate::Number(value.clone(), token.span.clone()),
_ => return None,
})
}
/// Returns `true` if the next token is Function or if it is a Const followed by Function.
/// Returns `false` otherwise.
fn peek_is_function(&self) -> Result<bool> {
let first = &self.peek()?.token;
let next = if self.tokens().len() >= 2 {
&self.peek_next()?.token
} else {
return Ok(false);
};
Ok(matches!(
(first, next),
(Token::Function | Token::At, _) | (Token::Const, Token::Function)
))
}
///
/// Removes the next two tokens if they are a pair of [`GroupCoordinate`] and returns them,
/// or [None] if the next token is not a [`GroupCoordinate`].
///
fn eat_group_partial(&mut self) -> Option<Result<(GroupCoordinate, GroupCoordinate, Span)>> {
let mut i = self.tokens().len();
if i < 1 {
return None;
}
let start_span = self.tokens().get(i - 1)?.span.clone();
let first = self.peek_group_coordinate(&mut i)?;
if i < 1 {
return None;
}
match self.tokens().get(i - 1) {
Some(SpannedToken {
token: Token::Comma, ..
}) => {
i -= 1;
}
_ => {
return None;
}
}
let second = self.peek_group_coordinate(&mut i)?;
if i < 1 {
return None;
}
let right_paren_span;
match self.tokens().get(i - 1) {
Some(SpannedToken {
token: Token::RightParen,
span,
}) => {
right_paren_span = span.clone();
i -= 1;
}
_ => {
return None;
}
}
if i < 1 {
return None;
}
let end_span;
match self.tokens().get(i - 1) {
Some(SpannedToken {
token: Token::Group,
span,
}) => {
end_span = span.clone();
i -= 1;
}
_ => {
return None;
}
}
self.tokens_mut().drain(i..);
if let Err(e) = assert_no_whitespace(
&right_paren_span,
&end_span,
&format!("({},{})", first, second),
"group",
) {
return Some(Err(e));
}
Some(Ok((first, second, start_span + end_span)))
}
///
/// Removes the next token if it is a [`Token::Int(_)`] and returns it, or [None] if
/// the next token is not a [`Token::Int(_)`] or if the next token does not exist.
///
fn eat_int(&mut self) -> Option<(PositiveNumber, Span)> {
if let Some(SpannedToken {
token: Token::Int(_), ..
}) = self.peek_option()
{
if let SpannedToken {
token: Token::Int(value),
span,
} = self.bump().unwrap()
{
return Some((PositiveNumber { value }, span));
} else {
unreachable!("eat_int_ shouldn't produce this")
}
}
None
}
///
/// Removes the next token if it exists and returns it, or [None] if
/// the next token does not exist.
///
fn eat_any(&mut self, token: &[Token]) -> Option<SpannedToken> {
if let Some(SpannedToken { token: inner, .. }) = self.peek_option() {
if token.iter().any(|x| x == inner) {
return self.bump();
}
}
None
}
///
/// Returns the span of the next token if it is equal to the given [`Token`], or error.
///
fn expect(&mut self, token: Token) -> Result<Span> {
if let Some(SpannedToken { token: inner, span }) = self.peek_option() {
if &token == inner {
Ok(self.bump().unwrap().span)
} else {
Err(ParserError::unexpected(inner, token, span).into())
}
} else {
Err(self.eof())
}
}
///
/// Returns the span of the next token if it is equal to one of the given [`Token`]s, or error.
///
fn expect_oneof(&mut self, token: &[Token]) -> Result<SpannedToken> {
if let Some(SpannedToken { token: inner, span }) = self.peek_option() {
if token.iter().any(|x| x == inner) {
Ok(self.bump().unwrap())
} else {
return Err(ParserError::unexpected(
inner,
token.iter().map(|x| format!("'{}'", x)).collect::<Vec<_>>().join(", "),
span,
)
.into());
}
} else {
Err(self.eof())
}
}
///
/// Returns the [`Identifier`] of the next token if it is a keyword,
/// [`Token::Int(_)`], or an [`Identifier`], or error.
///
fn expect_loose_identifier(&mut self) -> Result<Identifier> {
if let Some(token) = self.eat_any(KEYWORD_TOKENS) {
return Ok(Identifier {
name: token.token.keyword_to_symbol().unwrap(),
span: token.span,
});
}
if let Some((int, span)) = self.eat_int() {
let name = Symbol::intern(&int.value);
return Ok(Identifier { name, span });
}
self.expect_ident()
}
/// Returns the [`Identifier`] of the next token if it is an [`Identifier`], or error.
fn expect_ident(&mut self) -> Result<Identifier> {
if let Some(SpannedToken { token: inner, span }) = self.peek_option() {
if let Token::Ident(_) = inner {
if let SpannedToken {
token: Token::Ident(name),
span,
} = self.bump().unwrap()
{
Ok(Identifier { name, span })
} else {
unreachable!("expect_ident_ shouldn't produce this")
}
} else {
Err(ParserError::unexpected_str(inner, "ident", span).into())
}
} else {
Err(self.eof())
}
}
///
/// Returns the next token if it exists or return end of function.
///
fn expect_any(&mut self) -> Result<SpannedToken> {
if let Some(x) = self.tokens_mut().pop() {
Ok(x)
} else {
Err(self.eof())
}
}
/// Parses a list of `T`s using `inner`
/// The opening and closing delimiters are `bra` and `ket`,
/// and elements in the list are separated by `sep`.
/// When `(list, true)` is returned, `sep` was a terminator.
fn parse_list<T>(
&mut self,
open: Token,
close: Token,
sep: Token,
mut inner: impl FnMut(&mut Self) -> Result<Option<T>>,
) -> Result<(Vec<T>, bool, Span)> {
let mut list = Vec::new();
let mut trailing = false;
// Parse opening delimiter.
let open_span = self.expect(open)?;
while self.peek()?.token != close {
// Parse the element. We allow inner parser recovery through the `Option`.
if let Some(elem) = inner(self)? {
list.push(elem);
}
// Parse the separator.
if self.eat(sep.clone()).is_none() {
trailing = false;
break;
}
trailing = true;
}
// Parse closing delimiter.
let close_span = self.expect(close)?;
Ok((list, trailing, open_span + close_span))
}
/// Parse a list separated by `,` and delimited by parens.
fn parse_paren_comma_list<T>(
&mut self,
f: impl FnMut(&mut Self) -> Result<Option<T>>,
) -> Result<(Vec<T>, bool, Span)> {
self.parse_list(Token::LeftParen, Token::RightParen, Token::Comma, f)
}
/// Returns true if the current token is `(`.
fn peek_is_left_par(&self) -> bool {
matches!(self.peek_option().map(|t| &t.token), Some(Token::LeftParen))
}
}

View File

@ -1,18 +0,0 @@
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
pub mod context;
pub use context::*;

View File

@ -1,78 +0,0 @@
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{common::Context, tokenizer::*, Token};
use leo_errors::emitter::Handler;
use leo_span::Span;
/// Stores a program in tokenized format plus additional context.
/// May be converted into a [`Program`] AST by parsing all tokens.
pub struct InputParserContext<'a> {
#[allow(dead_code)]
pub(crate) handler: &'a Handler,
tokens: Vec<SpannedToken>,
end_span: Span,
}
impl Iterator for InputParserContext<'_> {
type Item = SpannedToken;
fn next(&mut self) -> Option<SpannedToken> {
self.bump()
}
}
impl<'a> Context for InputParserContext<'a> {
fn tokens(&self) -> &Vec<SpannedToken> {
&self.tokens
}
fn tokens_mut(&mut self) -> &mut Vec<SpannedToken> {
&mut self.tokens
}
fn handler(&self) -> &Handler {
&self.handler
}
fn end_span(&self) -> Span {
self.end_span.clone()
}
}
impl<'a> InputParserContext<'a> {
///
/// Returns a new [`InputParserContext`] type given a vector of tokens.
///
pub fn new(handler: &'a Handler, mut tokens: Vec<SpannedToken>) -> Self {
tokens.reverse();
// todo: performance optimization here: drain filter
tokens = tokens
.into_iter()
.filter(|x| !matches!(x.token, Token::CommentLine(_) | Token::CommentBlock(_)))
.collect();
Self {
handler,
end_span: tokens
.iter()
.find(|x| !x.span.content.trim().is_empty())
.map(|x| x.span.clone())
.unwrap_or_default(),
tokens,
}
}
}

View File

@ -1,341 +0,0 @@
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use super::*;
use crate::{assert_no_whitespace, common::Context, SpannedToken, Token};
use leo_errors::{ParserError, Result};
use smallvec::smallvec;
const INT_TYPES: &[Token] = &[
Token::I8,
Token::I16,
Token::I32,
Token::I64,
Token::I128,
Token::U8,
Token::U16,
Token::U32,
Token::U64,
Token::U128,
Token::Field,
Token::Group,
];
pub(crate) const TYPE_TOKENS: &[Token] = &[
Token::I8,
Token::I16,
Token::I32,
Token::I64,
Token::I128,
Token::U8,
Token::U16,
Token::U32,
Token::U64,
Token::U128,
Token::Field,
Token::Group,
Token::Address,
Token::Bool,
Token::Char,
];
impl InputParserContext<'_> {
pub fn token_to_int_type(token: Token) -> Option<IntegerType> {
Some(match token {
Token::I8 => IntegerType::I8,
Token::I16 => IntegerType::I16,
Token::I32 => IntegerType::I32,
Token::I64 => IntegerType::I64,
Token::I128 => IntegerType::I128,
Token::U8 => IntegerType::U8,
Token::U16 => IntegerType::U16,
Token::U32 => IntegerType::U32,
Token::U64 => IntegerType::U64,
Token::U128 => IntegerType::U128,
_ => return None,
})
}
/// Returns an [`Input`] struct filled with the data acquired in the file.
pub fn parse_input(&mut self) -> Result<Input> {
let mut values = IndexMap::new();
while self.has_next() {
let token = self.peek()?;
match token.token {
Token::LeftSquare => {
let (section, definitions) = self.parse_section()?;
println!("Section: {}, Definitions (len): {}", section, definitions.len());
values.insert(section, definitions);
}
_ => return Err(ParserError::unexpected_token(token.token.clone(), &token.span).into()),
};
}
Ok(Input::new(values))
}
/// Parses particular section in the Input file or the State file.
pub fn parse_section(&mut self) -> Result<(Identifier, IndexMap<Identifier, (Type, Expression)>)> {
self.expect(Token::LeftSquare)?;
let section = self.expect_ident()?;
self.expect(Token::RightSquare)?;
let mut assignments = IndexMap::new();
while self.has_next() {
let token = &self.peek()?.token;
if let Token::Ident(_) = token {
let (ident, (type_, value)) = self.parse_assignment()?;
assignments.insert(ident, (type_, value));
} else {
break;
}
}
Ok((section, assignments))
}
pub fn parse_assignment(&mut self) -> Result<(Identifier, (Type, Expression))> {
let var = self.expect_ident()?;
self.expect(Token::Colon)?;
let (type_, _span) = self.parse_type()?;
self.expect(Token::Assign)?;
let value = self.parse_primary_expression()?;
self.expect(Token::Semicolon)?;
Ok((var, (type_, value)))
}
/// Returns a [`(Type, Span)`] tuple of AST nodes if the next token represents a type.
/// Also returns the span of the parsed token.
pub fn parse_type(&mut self) -> Result<(Type, Span)> {
Ok(if let Some(token) = self.eat(Token::BigSelf) {
(Type::SelfType, token.span)
} else if let Some(ident) = self.eat_identifier() {
let span = ident.span.clone();
(Type::Identifier(ident), span)
} else if self.peek_is_left_par() {
let (types, _, span) = self.parse_paren_comma_list(|p| p.parse_type().map(|t| Some(t.0)))?;
(Type::Tuple(types), span)
} else if let Some(token) = self.eat(Token::LeftSquare) {
let (inner, _) = self.parse_type()?;
self.expect(Token::Semicolon)?;
let dimensions = self.parse_array_dimensions()?;
let end_span = self.expect(Token::RightSquare)?;
(Type::Array(Box::new(inner), dimensions), token.span + end_span)
} else {
let token = self.expect_oneof(TYPE_TOKENS)?;
(
match token.token {
Token::Field => Type::Field,
Token::Group => Type::Group,
Token::Address => Type::Address,
Token::Bool => Type::Boolean,
Token::Char => Type::Char,
x => Type::IntegerType(Self::token_to_int_type(x).expect("invalid int type")),
},
token.span,
)
})
}
/// Returns an [`ArrayDimensions`] AST node if the next tokens represent dimensions for an array type.
pub fn parse_array_dimensions(&mut self) -> Result<ArrayDimensions> {
Ok(if let Some(dim) = self.parse_array_dimension() {
ArrayDimensions(smallvec![dim])
} else {
let mut had_item_err = false;
let (dims, _, span) = self.parse_paren_comma_list(|p| {
Ok(if let Some(dim) = p.parse_array_dimension() {
Some(dim)
} else {
let token = p.expect_any()?;
p.emit_err(ParserError::unexpected_str(&token.token, "int", &token.span));
had_item_err = true;
None
})
})?;
if dims.is_empty() && !had_item_err {
self.emit_err(ParserError::array_tuple_dimensions_empty(&span));
}
ArrayDimensions(dims.into())
})
}
/// Parses a basic array dimension, i.e., an integer or `_`.
fn parse_array_dimension(&mut self) -> Option<Dimension> {
if let Some((int, _)) = self.eat_int() {
Some(Dimension::Number(int))
} else if self.eat(Token::Underscore).is_some() {
Some(Dimension::Unspecified)
} else {
None
}
}
///
/// Returns an [`Expression`] AST node if the next token is a primary expression:
/// - Literals: field, group, unsigned integer, signed integer, boolean, address
/// - Aggregate types: array, tuple
/// - Identifiers: variables, keywords
/// - self
///
/// Returns an expression error if the token cannot be matched.
///
pub fn parse_primary_expression(&mut self) -> Result<Expression> {
let SpannedToken { token, span } = self.expect_any()?;
Ok(match token {
Token::Int(value) => {
let type_ = self.eat_any(INT_TYPES);
match type_ {
Some(SpannedToken {
token: Token::Field,
span: type_span,
}) => {
assert_no_whitespace(&span, &type_span, &value, "field")?;
Expression::Value(ValueExpression::Field(value, span + type_span))
}
Some(SpannedToken {
token: Token::Group,
span: type_span,
}) => {
assert_no_whitespace(&span, &type_span, &value, "group")?;
Expression::Value(ValueExpression::Group(Box::new(GroupValue::Single(
value,
span + type_span,
))))
}
Some(SpannedToken { token, span: type_span }) => {
assert_no_whitespace(&span, &type_span, &value, &token.to_string())?;
Expression::Value(ValueExpression::Integer(
Self::token_to_int_type(token).expect("unknown int type token"),
value,
span + type_span,
))
}
None => Expression::Value(ValueExpression::Implicit(value, span)),
}
}
Token::True => Expression::Value(ValueExpression::Boolean("true".into(), span)),
Token::False => Expression::Value(ValueExpression::Boolean("false".into(), span)),
Token::AddressLit(value) => Expression::Value(ValueExpression::Address(value, span)),
Token::CharLit(value) => Expression::Value(ValueExpression::Char(CharValue {
character: value.into(),
span,
})),
Token::StringLit(value) => Expression::Value(ValueExpression::String(value, span)),
Token::LeftParen => self.parse_tuple_expression(&span)?,
Token::LeftSquare => self.parse_array_expression(&span)?,
// Token::Ident(name) => Expression::Identifier(Identifier { name, span }),
// Token::Input => Expression::Identifier(Identifier { name: sym::input, span }),
// t if crate::type_::TYPE_TOKENS.contains(&t) => Expression::Identifier(Identifier {
// name: t.keyword_to_symbol().unwrap(),
// span,
// }),
token => {
return Err(ParserError::unexpected_str(token, "expression", &span).into());
}
})
}
pub fn parse_tuple_expression(&mut self, span: &Span) -> Result<Expression> {
if let Some((left, right, span)) = self.eat_group_partial().transpose()? {
return Ok(Expression::Value(ValueExpression::Group(Box::new(GroupValue::Tuple(
GroupTuple {
span,
x: left,
y: right,
},
)))));
}
let mut args = Vec::new();
let end_span;
loop {
let end = self.eat(Token::RightParen);
if let Some(end) = end {
end_span = end.span;
break;
}
let expr = self.parse_primary_expression()?;
args.push(expr);
if self.eat(Token::Comma).is_none() {
end_span = self.expect(Token::RightParen)?;
break;
}
}
if args.len() == 1 {
Ok(args.remove(0))
} else {
Ok(Expression::TupleInit(TupleInitExpression {
span: span + &end_span,
elements: args,
}))
}
}
///
/// Returns an [`Expression`] AST node if the next tokens represent an
/// array initialization expression.
///
pub fn parse_array_expression(&mut self, span: &Span) -> Result<Expression> {
if let Some(end) = self.eat(Token::RightSquare) {
return Ok(Expression::ArrayInline(ArrayInlineExpression {
elements: Vec::new(),
span: span + &end.span,
}));
}
let first = self.parse_primary_expression()?;
if self.eat(Token::Semicolon).is_some() {
let dimensions = self
.parse_array_dimensions()
.map_err(|_| ParserError::unable_to_parse_array_dimensions(span))?;
let end = self.expect(Token::RightSquare)?;
Ok(Expression::ArrayInit(ArrayInitExpression {
span: span + &end,
element: Box::new(first),
dimensions,
}))
} else {
let end_span;
let mut elements = vec![first];
loop {
if let Some(token) = self.eat(Token::RightSquare) {
end_span = token.span;
break;
}
if elements.len() == 1 {
self.expect(Token::Comma)?;
if let Some(token) = self.eat(Token::RightSquare) {
end_span = token.span;
break;
}
}
elements.push(self.parse_primary_expression()?);
if self.eat(Token::Comma).is_none() {
end_span = self.expect(Token::RightSquare)?;
break;
}
}
Ok(Expression::ArrayInline(ArrayInlineExpression {
elements: elements
.into_iter()
.map(|expr| SpreadOrExpression::Expression(expr))
.collect(),
span: span + &end_span,
}))
}
}
}

View File

@ -1,34 +0,0 @@
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
mod context;
use context::*;
pub mod file;
use leo_ast::*;
use leo_errors::emitter::Handler;
use leo_errors::Result;
use leo_span::Span;
use indexmap::IndexMap;
/// Creates a new program from a given file path and source code text.
pub fn parse(handler: &Handler, path: &str, source: &str) -> Result<Input> {
let mut tokens = InputParserContext::new(handler, crate::tokenize(path, source.into())?);
tokens.parse_input()
}

View File

@ -30,12 +30,7 @@ pub(crate) use tokenizer::*;
pub mod parser; pub mod parser;
pub use parser::*; pub use parser::*;
pub mod input_parser; use leo_ast::{Ast, Input, ProgramInput, ProgramState};
pub use input_parser::*;
pub mod common;
use leo_ast::{Ast, Input};
use leo_errors::emitter::Handler; use leo_errors::emitter::Handler;
use leo_errors::Result; use leo_errors::Result;
@ -52,12 +47,18 @@ pub fn parse_program_input<T: AsRef<str>, Y: AsRef<str>, T2: AsRef<str>, Y2: AsR
handler: &Handler, handler: &Handler,
input_string: T, input_string: T,
input_path: Y, input_path: Y,
_state_string: T2, state_string: T2,
_state_path: Y2, state_path: Y2,
) -> Result<Input> { ) -> Result<Input> {
let input = input_parser::parse(handler, input_path.as_ref(), input_string.as_ref())?; let program_input: ProgramInput = parser::parse_input(handler, input_path.as_ref(), input_string.as_ref())?.try_into()?;
let program_state: ProgramState = parser::parse_input(handler, state_path.as_ref(), state_string.as_ref())?.try_into()?;
dbg!(&program_input);
Ok(input) Ok(Input {
program_input,
program_state: ProgramState::default(),
})
// let input_syntax_tree = LeoInputParser::parse_file(input_string.as_ref()).map_err(|mut e| { // let input_syntax_tree = LeoInputParser::parse_file(input_string.as_ref()).map_err(|mut e| {
// e.set_path( // e.set_path(
@ -80,7 +81,6 @@ pub fn parse_program_input<T: AsRef<str>, Y: AsRef<str>, T2: AsRef<str>, Y2: AsR
// .map(|x| x.to_string()) // .map(|x| x.to_string())
// .collect::<Vec<String>>()[..], // .collect::<Vec<String>>()[..],
// ); // );
// e // e
// })?; // })?;
@ -94,7 +94,6 @@ pub fn parse_program_input<T: AsRef<str>, Y: AsRef<str>, T2: AsRef<str>, Y2: AsR
// .map(|x| x.to_string()) // .map(|x| x.to_string())
// .collect::<Vec<String>>()[..], // .collect::<Vec<String>>()[..],
// ); // );
// e // e
// })?; // })?;
// input.parse_state(state_syntax_tree).map_err(|mut e| { // input.parse_state(state_syntax_tree).map_err(|mut e| {

View File

@ -14,13 +14,15 @@
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>. // along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{tokenizer::*, Token}; use crate::{assert_no_whitespace, tokenizer::*, Token, KEYWORD_TOKENS};
use leo_ast::*;
use leo_errors::emitter::Handler; use leo_errors::emitter::Handler;
use leo_errors::{LeoError, ParserError, Result};
use leo_span::{Span, Symbol};
use leo_span::Span; use std::{borrow::Cow, unreachable};
use tendril::format_tendril;
use crate::common::*;
/// Stores a program in tokenized format plus additional context. /// Stores a program in tokenized format plus additional context.
/// May be converted into a [`Program`] AST by parsing all tokens. /// May be converted into a [`Program`] AST by parsing all tokens.
@ -41,24 +43,6 @@ impl Iterator for ParserContext<'_> {
} }
} }
impl<'a> Context for ParserContext<'a> {
fn tokens(&self) -> &Vec<SpannedToken> {
&self.tokens
}
fn end_span(&self) -> Span {
self.end_span.clone()
}
fn tokens_mut(&mut self) -> &mut Vec<SpannedToken> {
&mut self.tokens
}
fn handler(&self) -> &Handler {
&self.handler
}
}
impl<'a> ParserContext<'a> { impl<'a> ParserContext<'a> {
/// ///
/// Returns a new [`ParserContext`] type given a vector of tokens. /// Returns a new [`ParserContext`] type given a vector of tokens.
@ -81,4 +65,386 @@ impl<'a> ParserContext<'a> {
fuzzy_struct_state: false, fuzzy_struct_state: false,
} }
} }
/// Returns the current token if there is one.
pub fn peek_option(&self) -> Option<&SpannedToken> {
self.tokens.last()
}
/// Emit the error `err`.
pub(crate) fn emit_err(&self, err: ParserError) {
self.handler.emit_err(err.into());
}
///
/// Returns an unexpected end of function [`SyntaxError`].
///
pub fn eof(&self) -> LeoError {
ParserError::unexpected_eof(&self.end_span).into()
}
///
/// Returns a reference to the next SpannedToken or error if it does not exist.
///
pub fn peek_next(&self) -> Result<&SpannedToken> {
self.tokens.get(self.tokens.len() - 2).ok_or_else(|| self.eof())
}
///
/// Returns a reference to the current SpannedToken or error if it does not exist.
///
pub fn peek(&self) -> Result<&SpannedToken> {
self.tokens.last().ok_or_else(|| self.eof())
}
///
/// Returns a reference to the next Token.
///
pub fn peek_token(&self) -> Cow<'_, Token> {
self.peek_option()
.map(|x| &x.token)
.map(Cow::Borrowed)
.unwrap_or_else(|| Cow::Owned(Token::Eof))
}
///
/// Returns true if the next token exists.
///
pub fn has_next(&self) -> bool {
!self.tokens.is_empty()
}
/// Advances the current token.
pub fn bump(&mut self) -> Option<SpannedToken> {
self.tokens.pop()
}
///
/// Removes the next token if it exists and returns it, or [None] if
/// the next token does not exist.
///
pub fn eat(&mut self, token: Token) -> Option<SpannedToken> {
if let Some(SpannedToken { token: inner, .. }) = self.peek_option() {
if &token == inner {
return self.bump();
}
}
None
}
///
/// Appends a token to the back of the vector.
///
pub fn backtrack(&mut self, token: SpannedToken) {
self.tokens.push(token);
}
///
/// Removes the next token if it is a [`Token::Ident(_)`] and returns it, or [None] if
/// the next token is not a [`Token::Ident(_)`] or if the next token does not exist.
///
pub fn eat_identifier(&mut self) -> Option<Identifier> {
if let Some(SpannedToken {
token: Token::Ident(_), ..
}) = self.peek_option()
{
if let SpannedToken {
token: Token::Ident(name),
span,
} = self.bump().unwrap()
{
return Some(Identifier { name, span });
} else {
unreachable!("eat_identifier_ shouldn't produce this")
}
}
None
}
///
/// Returns a reference to the next token if it is a [`GroupCoordinate`], or [None] if
/// the next token is not a [`GroupCoordinate`].
///
fn peek_group_coordinate(&self, i: &mut usize) -> Option<GroupCoordinate> {
if *i < 1 {
return None;
}
let token = self.tokens.get(*i - 1)?;
*i -= 1;
Some(match &token.token {
Token::Add => GroupCoordinate::SignHigh,
Token::Minus if *i > 0 => match self.tokens.get(*i - 1) {
Some(SpannedToken {
token: Token::Int(value),
span,
}) => {
if *i < 1 {
return None;
}
*i -= 1;
GroupCoordinate::Number(format_tendril!("-{}", value), span.clone())
}
_ => GroupCoordinate::SignLow,
},
Token::Underscore => GroupCoordinate::Inferred,
Token::Int(value) => GroupCoordinate::Number(value.clone(), token.span.clone()),
_ => return None,
})
}
/// Returns `true` if the next token is Function or if it is a Const followed by Function.
/// Returns `false` otherwise.
pub fn peek_is_function(&self) -> Result<bool> {
let first = &self.peek()?.token;
let next = if self.tokens.len() >= 2 {
&self.peek_next()?.token
} else {
return Ok(false);
};
Ok(matches!(
(first, next),
(Token::Function | Token::At, _) | (Token::Const, Token::Function)
))
}
///
/// Removes the next two tokens if they are a pair of [`GroupCoordinate`] and returns them,
/// or [None] if the next token is not a [`GroupCoordinate`].
///
pub fn eat_group_partial(&mut self) -> Option<Result<(GroupCoordinate, GroupCoordinate, Span)>> {
let mut i = self.tokens.len();
if i < 1 {
return None;
}
let start_span = self.tokens.get(i - 1)?.span.clone();
let first = self.peek_group_coordinate(&mut i)?;
if i < 1 {
return None;
}
match self.tokens.get(i - 1) {
Some(SpannedToken {
token: Token::Comma, ..
}) => {
i -= 1;
}
_ => {
return None;
}
}
let second = self.peek_group_coordinate(&mut i)?;
if i < 1 {
return None;
}
let right_paren_span;
match self.tokens.get(i - 1) {
Some(SpannedToken {
token: Token::RightParen,
span,
}) => {
right_paren_span = span.clone();
i -= 1;
}
_ => {
return None;
}
}
if i < 1 {
return None;
}
let end_span;
match self.tokens.get(i - 1) {
Some(SpannedToken {
token: Token::Group,
span,
}) => {
end_span = span.clone();
i -= 1;
}
_ => {
return None;
}
}
self.tokens.drain(i..);
if let Err(e) = assert_no_whitespace(
&right_paren_span,
&end_span,
&format!("({},{})", first, second),
"group",
) {
return Some(Err(e));
}
Some(Ok((first, second, start_span + end_span)))
}
///
/// Removes the next token if it is a [`Token::Int(_)`] and returns it, or [None] if
/// the next token is not a [`Token::Int(_)`] or if the next token does not exist.
///
pub fn eat_int(&mut self) -> Option<(PositiveNumber, Span)> {
if let Some(SpannedToken {
token: Token::Int(_), ..
}) = self.peek_option()
{
if let SpannedToken {
token: Token::Int(value),
span,
} = self.bump().unwrap()
{
return Some((PositiveNumber { value }, span));
} else {
unreachable!("eat_int_ shouldn't produce this")
}
}
None
}
///
/// Removes the next token if it exists and returns it, or [None] if
/// the next token does not exist.
///
pub fn eat_any(&mut self, token: &[Token]) -> Option<SpannedToken> {
if let Some(SpannedToken { token: inner, .. }) = self.peek_option() {
if token.iter().any(|x| x == inner) {
return self.bump();
}
}
None
}
///
/// Returns the span of the next token if it is equal to the given [`Token`], or error.
///
pub fn expect(&mut self, token: Token) -> Result<Span> {
if let Some(SpannedToken { token: inner, span }) = self.peek_option() {
if &token == inner {
Ok(self.bump().unwrap().span)
} else {
Err(ParserError::unexpected(inner, token, span).into())
}
} else {
Err(self.eof())
}
}
///
/// Returns the span of the next token if it is equal to one of the given [`Token`]s, or error.
///
pub fn expect_oneof(&mut self, token: &[Token]) -> Result<SpannedToken> {
if let Some(SpannedToken { token: inner, span }) = self.peek_option() {
if token.iter().any(|x| x == inner) {
Ok(self.bump().unwrap())
} else {
return Err(ParserError::unexpected(
inner,
token.iter().map(|x| format!("'{}'", x)).collect::<Vec<_>>().join(", "),
span,
)
.into());
}
} else {
Err(self.eof())
}
}
///
/// Returns the [`Identifier`] of the next token if it is a keyword,
/// [`Token::Int(_)`], or an [`Identifier`], or error.
///
pub fn expect_loose_identifier(&mut self) -> Result<Identifier> {
if let Some(token) = self.eat_any(KEYWORD_TOKENS) {
return Ok(Identifier {
name: token.token.keyword_to_symbol().unwrap(),
span: token.span,
});
}
if let Some((int, span)) = self.eat_int() {
let name = Symbol::intern(&int.value);
return Ok(Identifier { name, span });
}
self.expect_ident()
}
/// Returns the [`Identifier`] of the next token if it is an [`Identifier`], or error.
pub fn expect_ident(&mut self) -> Result<Identifier> {
if let Some(SpannedToken { token: inner, span }) = self.peek_option() {
if let Token::Ident(_) = inner {
if let SpannedToken {
token: Token::Ident(name),
span,
} = self.bump().unwrap()
{
Ok(Identifier { name, span })
} else {
unreachable!("expect_ident_ shouldn't produce this")
}
} else {
Err(ParserError::unexpected_str(inner, "ident", span).into())
}
} else {
Err(self.eof())
}
}
///
/// Returns the next token if it exists or return end of function.
///
pub fn expect_any(&mut self) -> Result<SpannedToken> {
if let Some(x) = self.tokens.pop() {
Ok(x)
} else {
Err(self.eof())
}
}
/// Parses a list of `T`s using `inner`
/// The opening and closing delimiters are `bra` and `ket`,
/// and elements in the list are separated by `sep`.
/// When `(list, true)` is returned, `sep` was a terminator.
pub(super) fn parse_list<T>(
&mut self,
open: Token,
close: Token,
sep: Token,
mut inner: impl FnMut(&mut Self) -> Result<Option<T>>,
) -> Result<(Vec<T>, bool, Span)> {
let mut list = Vec::new();
let mut trailing = false;
// Parse opening delimiter.
let open_span = self.expect(open)?;
while self.peek()?.token != close {
// Parse the element. We allow inner parser recovery through the `Option`.
if let Some(elem) = inner(self)? {
list.push(elem);
}
// Parse the separator.
if self.eat(sep.clone()).is_none() {
trailing = false;
break;
}
trailing = true;
}
// Parse closing delimiter.
let close_span = self.expect(close)?;
Ok((list, trailing, open_span + close_span))
}
/// Parse a list separated by `,` and delimited by parens.
pub(super) fn parse_paren_comma_list<T>(
&mut self,
f: impl FnMut(&mut Self) -> Result<Option<T>>,
) -> Result<(Vec<T>, bool, Span)> {
self.parse_list(Token::LeftParen, Token::RightParen, Token::Comma, f)
}
/// Returns true if the current token is `(`.
pub(super) fn peek_is_left_par(&self) -> bool {
matches!(self.peek_option().map(|t| &t.token), Some(Token::LeftParen))
}
} }

View File

@ -15,7 +15,6 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>. // along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use super::*; use super::*;
use crate::common::Context;
use leo_errors::{ParserError, Result}; use leo_errors::{ParserError, Result};
use leo_span::sym; use leo_span::sym;

View File

@ -16,7 +16,6 @@
use super::*; use super::*;
use crate::KEYWORD_TOKENS; use crate::KEYWORD_TOKENS;
use crate::common::Context;
use leo_errors::{ParserError, Result}; use leo_errors::{ParserError, Result};
use leo_span::sym; use leo_span::sym;

111
parser/src/parser/input.rs Normal file
View File

@ -0,0 +1,111 @@
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use super::*;
use leo_errors::{ParserError, Result};
impl ParserContext<'_> {
/// Returns a [`ParsedInputFile`] struct filled with the data acquired in the file.
pub fn parse_input(&mut self) -> Result<ParsedInputFile> {
let mut sections = Vec::new();
let mut is_public = true;
while self.has_next() {
let token = self.peek()?;
if matches!(token.token, Token::LeftSquare) {
// For visibility modifiers: [[public]] or [[private]]
if self.peek_next()?.token == Token::LeftSquare {
is_public = self.parse_visibility()?;
}
let mut section = self.parse_section()?;
section.is_public = is_public;
sections.push(section);
} else {
return Err(ParserError::unexpected_token(token.token.clone(), &token.span).into());
}
}
Ok(ParsedInputFile { sections })
}
/// Parses visibility tables in the State or Input file.
/// Expects: [[<public>]] or [[<private>]], returns true
/// if visibility is set to public, returns else otherwise.
pub fn parse_visibility(&mut self) -> Result<bool> {
self.expect(Token::LeftSquare)?;
self.expect(Token::LeftSquare)?;
let visiblity = self.expect_ident()?;
self.expect(Token::RightSquare)?;
self.expect(Token::RightSquare)?;
Ok(match visiblity.name {
x if x == Symbol::intern("public") => true,
x if x == Symbol::intern("private") => false,
_ => todo!("illegal visibility modifier"),
})
}
/// Parses particular section in the Input or State file.
/// `
/// [<identifier>]
/// <...definition>
/// `
/// Returns [`Section`].
pub fn parse_section(&mut self) -> Result<Section> {
self.expect(Token::LeftSquare)?;
let section = self.expect_ident()?;
self.expect(Token::RightSquare)?;
let mut definitions = Vec::new();
while self.has_next() {
let token = &self.peek()?.token;
if let Token::Ident(_) = token {
definitions.push(self.parse_input_definition()?);
} else {
break;
}
}
Ok(Section {
is_public: true,
name: section.name,
span: section.span.clone(),
definitions,
})
}
/// Parses a single parameter definition:
/// `<identifier> : <type> = <expression>;`
/// Returns [`Definition`].
pub fn parse_input_definition(&mut self) -> Result<Definition> {
let name = self.expect_ident()?;
self.expect(Token::Colon)?;
let (type_, span) = self.parse_type()?;
self.expect(Token::Assign)?;
let value = self.parse_primary_expression()?;
self.expect(Token::Semicolon)?;
Ok(Definition {
name,
type_,
value,
span,
})
}
}

View File

@ -36,6 +36,7 @@ pub mod expression;
pub mod file; pub mod file;
pub mod statement; pub mod statement;
pub mod type_; pub mod type_;
pub mod input;
pub(crate) fn assert_no_whitespace(left_span: &Span, right_span: &Span, left: &str, right: &str) -> Result<()> { pub(crate) fn assert_no_whitespace(left_span: &Span, right_span: &Span, left: &str, right: &str) -> Result<()> {
if left_span.col_stop != right_span.col_start { if left_span.col_stop != right_span.col_start {
@ -54,3 +55,9 @@ pub fn parse(handler: &Handler, path: &str, source: &str) -> Result<Program> {
tokens.parse_program() tokens.parse_program()
} }
pub fn parse_input(handler: &Handler, path: &str, source: &str) -> Result<ParsedInputFile> {
let mut tokens = ParserContext::new(handler, crate::tokenize(path, source.into())?);
tokens.parse_input()
}

View File

@ -15,7 +15,6 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>. // along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use super::*; use super::*;
use crate::common::Context;
use leo_errors::{ParserError, Result}; use leo_errors::{ParserError, Result};
use leo_span::sym; use leo_span::sym;

View File

@ -16,7 +16,6 @@
use super::*; use super::*;
use leo_errors::{ParserError, Result}; use leo_errors::{ParserError, Result};
use crate::common::Context;
use smallvec::smallvec; use smallvec::smallvec;

View File

@ -14,7 +14,7 @@
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>. // along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{common::Context, tokenizer, ParserContext, SpannedToken}; use crate::{tokenizer, ParserContext, SpannedToken};
use leo_ast::{Expression, ExpressionStatement, Statement, ValueExpression}; use leo_ast::{Expression, ExpressionStatement, Statement, ValueExpression};
use leo_errors::{emitter::Handler, LeoError}; use leo_errors::{emitter::Handler, LeoError};
use leo_span::{symbol::create_session_if_not_set_then, Span}; use leo_span::{symbol::create_session_if_not_set_then, Span};

View File

@ -110,6 +110,7 @@ symbols! {
circuit, circuit,
Class: "class", Class: "class",
context, context,
constants,
CoreFunction, CoreFunction,
console, console,
Const: "const", Const: "const",

View File

@ -25,10 +25,6 @@ version = "1.5.3"
path = "../errors" path = "../errors"
version = "1.5.3" version = "1.5.3"
[dependencies.leo-input]
path = "../input"
version = "1.5.3"
[dependencies.snarkvm-algorithms] [dependencies.snarkvm-algorithms]
git = "https://github.com/AleoHQ/snarkVM.git" git = "https://github.com/AleoHQ/snarkVM.git"
rev = "51633e2" rev = "51633e2"