Merge remote-tracking branch 'origin/testnet3' into improve-parser-tests

This commit is contained in:
0rphon 2022-02-23 15:07:49 -08:00
commit c6926ef1fa
202 changed files with 6669 additions and 6486 deletions

View File

@ -5,7 +5,7 @@ updates:
schedule:
interval: daily
time: "10:00"
target-branch: "staging"
target-branch: "testnet3"
open-pull-requests-limit: 20
ignore:
- dependency-name: snarkvm-curves

368
Cargo.lock generated
View File

@ -56,9 +56,9 @@ dependencies = [
[[package]]
name = "anyhow"
version = "1.0.53"
version = "1.0.55"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94a45b455c14666b85fc40a019e8ab9eb75e3a124e05494f5397122bc9eb06e0"
checksum = "159bb86af3a200e19a068f4224eae4c8bb2d0fa054c7e5d1cacd5cef95e684cd"
[[package]]
name = "assert_cmd"
@ -127,34 +127,13 @@ version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
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]]
name = "block-buffer"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1d36a02058e76b040de25a4464ba1c80935655595b661505c8b39b664828b95"
dependencies = [
"generic-array 0.14.5",
]
[[package]]
name = "block-padding"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa79dedbb091f449f1f39e53edf88d5dbe95f895dae6135a8d7b881fb5af73f5"
dependencies = [
"byte-tools",
"generic-array",
]
[[package]]
@ -175,12 +154,6 @@ version = "3.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4a45a46ab1f2412e53d3a0ade76ffad2025804294569aae387231a0cd6e0899"
[[package]]
name = "byte-tools"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3b5ca7a04898ad4bcd41c90c5285445ff5b791899bb1b0abdd2a2aa791211d7"
[[package]]
name = "byteorder"
version = "1.4.3"
@ -267,9 +240,9 @@ dependencies = [
[[package]]
name = "clap"
version = "3.0.14"
version = "3.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b63edc3f163b3c71ec8aa23f9bd6070f77edbf3d1d198b164afa90ff00e4ec62"
checksum = "6d76c22c9b9b215eeb8d016ad3a90417bd13cb24cf8142756e6472445876cab7"
dependencies = [
"atty",
"bitflags",
@ -362,7 +335,7 @@ dependencies = [
"clap 2.34.0",
"criterion-plot",
"csv",
"itertools 0.10.3",
"itertools",
"lazy_static",
"num-traits",
"oorandom",
@ -384,7 +357,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d00996de9f2f7559f7f4dc286073197f83e92256a59ed395f9aac01fe717da57"
dependencies = [
"cast",
"itertools 0.10.3",
"itertools",
]
[[package]]
@ -433,11 +406,12 @@ dependencies = [
[[package]]
name = "crypto-common"
version = "0.1.1"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "683d6b536309245c849479fba3da410962a43ed8e51c26b729208ec0ac2798d0"
checksum = "57952ca27b5e3606ff4dd79b0020231aaf9d6aa76dc05fd30137538c50bd3ce8"
dependencies = [
"generic-array 0.14.5",
"generic-array",
"typenum",
]
[[package]]
@ -468,9 +442,9 @@ version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fcc3dd5e9e9c0b295d6e1e4d811fb6f157d5ffd784b8d202fc62eac8035a770b"
dependencies = [
"proc-macro2 1.0.36",
"quote 1.0.15",
"syn 1.0.86",
"proc-macro2",
"quote",
"syn",
]
[[package]]
@ -481,22 +455,12 @@ checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8"
[[package]]
name = "digest"
version = "0.8.1"
version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3d0c8c8752312f9713efd397ff63acb9f85585afbf179282e720e7704954dd5"
checksum = "f2fb860ca6fafa5552fb6d0e816a69c8e49f0908bf524e30a90d97c85892d506"
dependencies = [
"generic-array 0.12.4",
]
[[package]]
name = "digest"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b697d66081d42af4fba142d56918a3cb21dc8eb63372c6b85d14f44fb9c5979b"
dependencies = [
"block-buffer 0.10.0",
"block-buffer",
"crypto-common",
"generic-array 0.14.5",
]
[[package]]
@ -566,34 +530,6 @@ dependencies = [
"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]]
name = "fastrand"
version = "1.7.0"
@ -658,16 +594,6 @@ dependencies = [
"percent-encoding",
]
[[package]]
name = "from-pest"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aba9389cedcba1fb3a2aa2ed00f584f2606bce8e0106614a17327a24513bc60f"
dependencies = [
"pest",
"void",
]
[[package]]
name = "fsevent"
version = "0.4.0"
@ -776,15 +702,6 @@ dependencies = [
"byteorder",
]
[[package]]
name = "generic-array"
version = "0.12.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ffdf9f34f1447443d37393cc6c2b8313aebddcd96906caf34e54c68d8e57d7bd"
dependencies = [
"typenum",
]
[[package]]
name = "generic-array"
version = "0.14.5"
@ -1036,15 +953,6 @@ version = "2.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68f2d64f2edebec4ce84ad108148e67e1064789bee435edc5b60ad398714a3a9"
[[package]]
name = "itertools"
version = "0.7.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d47946d458e94a1b7bcabbf6521ea7c037062c81f534615abcad76e84d4970d"
dependencies = [
"either",
]
[[package]]
name = "itertools"
version = "0.10.3"
@ -1112,22 +1020,33 @@ dependencies = [
"criterion",
"indexmap",
"leo-errors",
"leo-input",
"leo-span",
"pest",
"serde",
"serde_json",
"smallvec",
"tendril",
]
[[package]]
name = "leo-ast-passes"
version = "1.5.3"
dependencies = [
"indexmap",
"leo-ast",
"leo-errors",
"leo-parser",
"leo-span",
]
[[package]]
name = "leo-compiler"
version = "1.5.3"
dependencies = [
"leo-ast",
"leo-ast-passes",
"leo-errors",
"leo-parser",
"leo-span",
"sha2",
]
@ -1140,38 +1059,23 @@ dependencies = [
"colored",
"derivative",
"eyre",
"leo-input",
"leo-span",
"pest",
"serde",
"tendril",
"thiserror",
]
[[package]]
name = "leo-input"
version = "1.5.3"
dependencies = [
"from-pest",
"pest",
"pest-ast",
"pest_derive",
"thiserror",
"tracing",
]
[[package]]
name = "leo-lang"
version = "1.5.3"
dependencies = [
"ansi_term",
"assert_cmd",
"clap 3.0.14",
"clap 3.1.1",
"color-backtrace",
"colored",
"console",
"dirs",
"from-pest",
"indexmap",
"lazy_static",
"leo-ast",
@ -1219,13 +1123,13 @@ dependencies = [
"lazy_static",
"leo-ast",
"leo-errors",
"leo-input",
"leo-span",
"leo-test-framework",
"serde",
"serde_json",
"serde_yaml",
"smallvec",
"structopt",
"tendril",
"tracing",
]
@ -1236,7 +1140,6 @@ version = "1.5.3"
dependencies = [
"fxhash",
"indexmap",
"pest",
"scoped-tls",
"serde",
"tendril",
@ -1281,12 +1184,6 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4"
[[package]]
name = "maplit"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d"
[[package]]
name = "matches"
version = "0.1.9"
@ -1551,12 +1448,6 @@ version = "11.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575"
[[package]]
name = "opaque-debug"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2839e79665f131bdb5782e51f2c6c9599c133c6098982a54c794358bf432529c"
[[package]]
name = "openssl"
version = "0.10.38"
@ -1614,53 +1505,6 @@ dependencies = [
"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]]
name = "pin-project-lite"
version = "0.2.8"
@ -1720,7 +1564,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5aab5be6e4732b473071984b3164dbbfb7a3674d30ea5ff44410b6bcd960c3c"
dependencies = [
"difflib",
"itertools 0.10.3",
"itertools",
"predicates-core",
]
@ -1756,9 +1600,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c"
dependencies = [
"proc-macro-error-attr",
"proc-macro2 1.0.36",
"quote 1.0.15",
"syn 1.0.86",
"proc-macro2",
"quote",
"syn",
"version_check",
]
@ -1768,27 +1612,18 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869"
dependencies = [
"proc-macro2 1.0.36",
"quote 1.0.15",
"proc-macro2",
"quote",
"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]]
name = "proc-macro2"
version = "1.0.36"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c7342d5883fbccae1cc37a2353b09c87c9b0f3afd73f5fb9bba687a1f733b029"
dependencies = [
"unicode-xid 0.2.2",
"unicode-xid",
]
[[package]]
@ -1800,22 +1635,13 @@ dependencies = [
"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]]
name = "quote"
version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "864d3e96a899863136fc6e99f3d7cae289dafe43bf2c5ac19b70df7210c0a145"
dependencies = [
"proc-macro2 1.0.36",
"proc-macro2",
]
[[package]]
@ -2166,9 +1992,9 @@ version = "1.0.136"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08597e7152fcd306f41838ed3e37be9eaeed2b61c42e2117266a554fab4662f9"
dependencies = [
"proc-macro2 1.0.36",
"quote 1.0.15",
"syn 1.0.86",
"proc-macro2",
"quote",
"syn",
]
[[package]]
@ -2207,27 +2033,15 @@ dependencies = [
"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]]
name = "sha2"
version = "0.10.1"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "99c3bd8169c58782adad9290a9af5939994036b76187f7b4f0e6de91dbbfc0ec"
checksum = "55deaec60f81eefe3cce0dc50bda92d6d8e88f2a27df7c5033b42afeb1ed2676"
dependencies = [
"cfg-if 1.0.0",
"cpufeatures",
"digest 0.10.1",
"digest",
]
[[package]]
@ -2239,15 +2053,6 @@ dependencies = [
"lazy_static",
]
[[package]]
name = "single"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bd5add732a1ab689845591a1b50339cf5310b563e08dc5813c65991f30369ea2"
dependencies = [
"failure",
]
[[package]]
name = "slab"
version = "0.4.5"
@ -2270,9 +2075,9 @@ source = "git+https://github.com/AleoHQ/snarkVM.git?rev=51633e2#51633e2fac247bc8
dependencies = [
"proc-macro-crate",
"proc-macro-error",
"proc-macro2 1.0.36",
"quote 1.0.15",
"syn 1.0.86",
"proc-macro2",
"quote",
"syn",
]
[[package]]
@ -2282,7 +2087,7 @@ source = "git+https://github.com/AleoHQ/snarkVM.git?rev=51633e2#51633e2fac247bc8
dependencies = [
"anyhow",
"bincode",
"itertools 0.10.3",
"itertools",
"num-bigint",
"rand 0.8.4",
"serde",
@ -2331,20 +2136,9 @@ checksum = "dcb5ae327f9cc13b68763b5749770cb9e048a99bd9dfdfa58d0cf05d5f64afe0"
dependencies = [
"heck",
"proc-macro-error",
"proc-macro2 1.0.36",
"quote 1.0.15",
"syn 1.0.86",
]
[[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",
"proc-macro2",
"quote",
"syn",
]
[[package]]
@ -2353,21 +2147,9 @@ version = "1.0.86"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a65b3f4ffa0092e9887669db0eae07941f023991ab58ea44da8fe8e2d511c6b"
dependencies = [
"proc-macro2 1.0.36",
"quote 1.0.15",
"unicode-xid 0.2.2",
]
[[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",
"proc-macro2",
"quote",
"unicode-xid",
]
[[package]]
@ -2459,9 +2241,9 @@ version = "1.0.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa32fd3f627f367fe16f893e2597ae3c05020f8bba2666a4e6ea73d377e5714b"
dependencies = [
"proc-macro2 1.0.36",
"quote 1.0.15",
"syn 1.0.86",
"proc-macro2",
"quote",
"syn",
]
[[package]]
@ -2580,9 +2362,9 @@ version = "0.1.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f4f480b8f81512e825f337ad51e94c1eb5d3bbdf2b363dcd01e2b19a9ffe3f8e"
dependencies = [
"proc-macro2 1.0.36",
"quote 1.0.15",
"syn 1.0.86",
"proc-macro2",
"quote",
"syn",
]
[[package]]
@ -2673,12 +2455,6 @@ version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ed742d4ea2bd1176e236172c8429aaf54486e7ac098db29ffe6529e0ce50973"
[[package]]
name = "unicode-xid"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc"
[[package]]
name = "unicode-xid"
version = "0.2.2"
@ -2721,12 +2497,6 @@ version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
[[package]]
name = "void"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d"
[[package]]
name = "wait-timeout"
version = "0.2.0"
@ -2788,9 +2558,9 @@ dependencies = [
"bumpalo",
"lazy_static",
"log",
"proc-macro2 1.0.36",
"quote 1.0.15",
"syn 1.0.86",
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-shared",
]
@ -2812,7 +2582,7 @@ version = "0.2.79"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f4203d69e40a52ee523b2529a773d5ffc1dc0071801c87b3d270b471b80ed01"
dependencies = [
"quote 1.0.15",
"quote",
"wasm-bindgen-macro-support",
]
@ -2822,9 +2592,9 @@ version = "0.2.79"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bfa8a30d46208db204854cadbb5d4baf5fcf8071ba5bf48190c3e59937962ebc"
dependencies = [
"proc-macro2 1.0.36",
"quote 1.0.15",
"syn 1.0.86",
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-backend",
"wasm-bindgen-shared",
]

View File

@ -30,7 +30,7 @@ members = [
# "asg",
# "asg-passes",
"ast",
# "ast-passes",
"ast-passes",
"compiler",
"errors",
"grammar",
@ -63,9 +63,6 @@ version = "1.5.3"
#path = "./imports"
#version = "1.5.3"
#
#[dependencies.leo-input]
#path = "./input"
#version = "1.5.3"
[dependencies.leo-package]
path = "./package"
@ -107,7 +104,7 @@ git = "https://github.com/AleoHQ/snarkVM.git"
rev = "51633e2"
[dependencies.clap]
version = "3.0.10"
version = "3.1"
[dependencies.color-backtrace]
version = "0.5.1"
@ -121,9 +118,6 @@ version = "4.0.0"
[dependencies.console]
version = "0.15.0"
[dependencies.from-pest]
version = "0.3.1"
[dependencies.indexmap]
version = "1.8"
features = ["serde"]

View File

@ -36,6 +36,10 @@ version = "1.5.3"
path = "../parser"
version = "1.5.3"
[dependencies.leo-span]
path = "../span"
version = "1.5.3"
#[dependencies.leo-stdlib]
#path = "../stdlib"
#version = "1.5.3"

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// 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
@ -14,8 +14,15 @@
// 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/>.
//! Creates a struct that implements a ReconstructingReducer
//! such that it applies changes to the AST nodes for canonicalization.
//! An example of these changes are transforming Self -> to the circuit name.
use leo_ast::*;
use leo_errors::{AstError, Result, Span};
use leo_errors::{AstError, Result};
use leo_span::{sym, Span, Symbol};
use indexmap::IndexMap;
/// Replace Self when it is in a enclosing circuit type.
/// Error when Self is outside an enclosing circuit type.
@ -30,14 +37,6 @@ pub struct Canonicalizer {
in_circuit: bool,
}
impl AstPass for Canonicalizer {
fn do_pass(ast: Program) -> Result<Ast> {
Ok(Ast::new(
ReconstructingDirector::new(Self::default()).reduce_program(&ast)?,
))
}
}
impl Canonicalizer {
pub fn canonicalize_accesses(
&mut self,
@ -50,34 +49,34 @@ impl Canonicalizer {
for access in accesses.iter() {
match self.canonicalize_assignee_access(access) {
AssigneeAccess::ArrayIndex(index) => {
left = Box::new(Expression::ArrayAccess(ArrayAccessExpression {
left = Box::new(Expression::Access(AccessExpression::Array(ArrayAccess {
array: left,
index: Box::new(index),
span: span.clone(),
}));
})));
}
AssigneeAccess::ArrayRange(start, stop) => {
left = Box::new(Expression::ArrayRangeAccess(ArrayRangeAccessExpression {
left = Box::new(Expression::Access(AccessExpression::ArrayRange(ArrayRangeAccess {
array: left,
left: start.map(Box::new),
right: stop.map(Box::new),
span: span.clone(),
}));
})));
}
AssigneeAccess::Tuple(positive_number, _) => {
left = Box::new(Expression::TupleAccess(TupleAccessExpression {
left = Box::new(Expression::Access(AccessExpression::Tuple(TupleAccess {
tuple: left,
index: positive_number,
span: span.clone(),
}));
})));
}
AssigneeAccess::Member(identifier) => {
left = Box::new(Expression::CircuitMemberAccess(CircuitMemberAccessExpression {
circuit: left,
left = Box::new(Expression::Access(AccessExpression::Member(MemberAccess {
inner: left,
name: identifier,
span: span.clone(),
type_: None,
}));
})));
}
}
}
@ -85,7 +84,7 @@ impl Canonicalizer {
Ok(left)
}
pub fn compound_operation_converstion(&mut self, operation: &AssignOperation) -> Result<BinaryOperation> {
pub fn compound_operation_conversion(&mut self, operation: &AssignOperation) -> Result<BinaryOperation> {
match operation {
AssignOperation::Assign => unreachable!(),
AssignOperation::Add => Ok(BinaryOperation::Add),
@ -125,11 +124,11 @@ impl Canonicalizer {
}
}
fn canonicalize_circuit_implied_variable_definition(
fn canonicalize_circuit_variable_initializer(
&mut self,
member: &CircuitImpliedVariableDefinition,
) -> CircuitImpliedVariableDefinition {
CircuitImpliedVariableDefinition {
member: &CircuitVariableInitializer,
) -> CircuitVariableInitializer {
CircuitVariableInitializer {
identifier: member.identifier.clone(),
expression: member
.expression
@ -156,7 +155,7 @@ impl Canonicalizer {
return Expression::Binary(BinaryExpression {
left,
right,
op: binary.op.clone(),
op: binary.op,
span: binary.span.clone(),
});
}
@ -184,6 +183,62 @@ impl Canonicalizer {
});
}
Expression::Access(access) => {
let access = match access {
AccessExpression::Array(array_access) => {
let array = Box::new(self.canonicalize_expression(&array_access.array));
let index = Box::new(self.canonicalize_expression(&array_access.index));
AccessExpression::Array(ArrayAccess {
array,
index,
span: array_access.span.clone(),
})
}
AccessExpression::ArrayRange(array_range_access) => {
let array = Box::new(self.canonicalize_expression(&array_range_access.array));
let left = array_range_access
.left
.as_ref()
.map(|left| Box::new(self.canonicalize_expression(left)));
let right = array_range_access
.right
.as_ref()
.map(|right| Box::new(self.canonicalize_expression(right)));
AccessExpression::ArrayRange(ArrayRangeAccess {
array,
left,
right,
span: array_range_access.span.clone(),
})
}
AccessExpression::Member(member_access) => AccessExpression::Member(MemberAccess {
inner: Box::new(self.canonicalize_expression(&member_access.inner)),
name: member_access.name.clone(),
span: member_access.span.clone(),
type_: None,
}),
AccessExpression::Tuple(tuple_access) => {
let tuple = Box::new(self.canonicalize_expression(&tuple_access.tuple));
AccessExpression::Tuple(TupleAccess {
tuple,
index: tuple_access.index.clone(),
span: tuple_access.span.clone(),
})
}
AccessExpression::Static(static_access) => AccessExpression::Static(StaticAccess {
inner: Box::new(self.canonicalize_expression(&static_access.inner)),
name: static_access.name.clone(),
type_: self.canonicalize_self_type(static_access.type_.as_ref()),
span: static_access.span.clone(),
}),
};
return Expression::Access(access);
}
Expression::ArrayInline(array_inline) => {
let elements = array_inline
.elements
@ -214,36 +269,6 @@ impl Canonicalizer {
});
}
Expression::ArrayAccess(array_access) => {
let array = Box::new(self.canonicalize_expression(&array_access.array));
let index = Box::new(self.canonicalize_expression(&array_access.index));
return Expression::ArrayAccess(ArrayAccessExpression {
array,
index,
span: array_access.span.clone(),
});
}
Expression::ArrayRangeAccess(array_range_access) => {
let array = Box::new(self.canonicalize_expression(&array_range_access.array));
let left = array_range_access
.left
.as_ref()
.map(|left| Box::new(self.canonicalize_expression(left)));
let right = array_range_access
.right
.as_ref()
.map(|right| Box::new(self.canonicalize_expression(right)));
return Expression::ArrayRangeAccess(ArrayRangeAccessExpression {
array,
left,
right,
span: array_range_access.span.clone(),
});
}
Expression::TupleInit(tuple_init) => {
let elements = tuple_init
.elements
@ -257,20 +282,10 @@ impl Canonicalizer {
});
}
Expression::TupleAccess(tuple_access) => {
let tuple = Box::new(self.canonicalize_expression(&tuple_access.tuple));
return Expression::TupleAccess(TupleAccessExpression {
tuple,
index: tuple_access.index.clone(),
span: tuple_access.span.clone(),
});
}
Expression::CircuitInit(circuit_init) => {
let mut name = circuit_init.name.clone();
if name.name.as_ref() == "Self" && self.circuit_name.is_some() {
name = self.circuit_name.as_ref().unwrap().clone();
if name.name == sym::SelfUpper && self.circuit_name.is_some() {
name = self.circuit_name.clone().unwrap();
}
return Expression::CircuitInit(CircuitInitExpression {
@ -278,26 +293,11 @@ impl Canonicalizer {
members: circuit_init
.members
.iter()
.map(|member| self.canonicalize_circuit_implied_variable_definition(member))
.map(|member| self.canonicalize_circuit_variable_initializer(member))
.collect(),
span: circuit_init.span.clone(),
});
}
Expression::CircuitMemberAccess(circuit_member_access) => {
return Expression::CircuitMemberAccess(CircuitMemberAccessExpression {
circuit: Box::new(self.canonicalize_expression(&circuit_member_access.circuit)),
name: circuit_member_access.name.clone(),
span: circuit_member_access.span.clone(),
type_: None,
});
}
Expression::CircuitStaticFunctionAccess(circuit_static_func_access) => {
return Expression::CircuitStaticFunctionAccess(CircuitStaticFunctionAccessExpression {
circuit: Box::new(self.canonicalize_expression(&circuit_static_func_access.circuit)),
name: circuit_static_func_access.name.clone(),
span: circuit_static_func_access.span.clone(),
});
}
Expression::Call(call) => {
return Expression::Call(CallExpression {
function: Box::new(self.canonicalize_expression(&call.function)),
@ -310,7 +310,7 @@ impl Canonicalizer {
});
}
Expression::Identifier(identifier) => {
if identifier.name.as_ref() == "Self" && self.circuit_name.is_some() {
if identifier.name == sym::SelfUpper && self.circuit_name.is_some() {
return Expression::Identifier(self.circuit_name.as_ref().unwrap().clone());
}
}
@ -376,6 +376,7 @@ impl Canonicalizer {
Statement::Definition(DefinitionStatement {
declaration_type: definition.declaration_type.clone(),
variable_names: definition.variable_names.clone(),
parened: definition.parened,
type_,
value,
span: definition.span.clone(),
@ -478,6 +479,13 @@ impl Canonicalizer {
fn canonicalize_circuit_member(&mut self, circuit_member: &CircuitMember) -> CircuitMember {
match circuit_member {
CircuitMember::CircuitConst(identifier, type_, value) => {
return CircuitMember::CircuitConst(
identifier.clone(),
type_.clone(),
self.canonicalize_expression(value),
);
}
CircuitMember::CircuitVariable(_, _) => {}
CircuitMember::CircuitFunction(function) => {
let input = function
@ -488,14 +496,16 @@ impl Canonicalizer {
let output = self.canonicalize_self_type(function.output.as_ref());
let block = self.canonicalize_block(&function.block);
return CircuitMember::CircuitFunction(Function {
return CircuitMember::CircuitFunction(Box::new(Function {
annotations: function.annotations.clone(),
identifier: function.identifier.clone(),
const_: function.const_,
input,
output,
block,
core_mapping: function.core_mapping.clone(),
span: function.span.clone(),
});
}));
}
}
@ -513,35 +523,20 @@ impl ReconstructingReducer for Canonicalizer {
}
fn reduce_type(&mut self, _type_: &Type, new: Type, span: &Span) -> Result<Type> {
match new {
Type::Array(type_, dimensions) => {
if let Some(mut dimensions) = dimensions {
if dimensions.is_zero() {
return Err(AstError::invalid_array_dimension_size(span).into());
}
let mut next = Type::Array(type_, Some(ArrayDimensions(vec![dimensions.remove_last().unwrap()])));
let mut array = next.clone();
loop {
if dimensions.is_empty() {
break;
}
array = Type::Array(
Box::new(next),
Some(ArrayDimensions(vec![dimensions.remove_last().unwrap()])),
);
next = array.clone();
}
Ok(array)
} else {
Ok(Type::Array(type_, None))
}
match new.clone() {
Type::Array(base, dims) if dims.is_empty() => Ok(Type::Array(base, dims)),
Type::Array(_, dims) if dims.is_zero() => Err(AstError::invalid_array_dimension_size(span).into()),
// Reduce `ArrayDimensions` into nested `Array` types.
Type::Array(base, dims) => {
let mut iter = dims.0.into_iter().rev();
let ctor = |ty, dim| Type::Array(ty, ArrayDimensions::single(dim));
let dim = iter.next().unwrap();
let base = ctor(base, dim);
Ok(iter.fold(base, |ty, dim| ctor(Box::new(ty), dim)))
}
Type::SelfType if !self.in_circuit => Err(AstError::big_self_outside_of_circuit(span).into()),
_ => Ok(new.clone()),
Type::Tuple(types) if types.len() == 1 => Err(AstError::invalid_tuple_dimension_size(span).into()),
_ => Ok(new),
}
}
@ -594,6 +589,10 @@ impl ReconstructingReducer for Canonicalizer {
)));
}
if elements.is_empty() {
return Err(AstError::invalid_array_dimension_size(span).into());
}
Ok(Expression::ArrayInline(ArrayInlineExpression {
elements,
span: span.clone(),
@ -605,46 +604,40 @@ impl ReconstructingReducer for Canonicalizer {
array_init: &ArrayInitExpression,
element: Expression,
) -> Result<ArrayInitExpression> {
if array_init.dimensions.is_zero() {
return Err(AstError::invalid_array_dimension_size(&array_init.span).into());
}
let element = Box::new(element);
if array_init.dimensions.0.len() == 1 {
return Ok(ArrayInitExpression {
element,
dimensions: array_init.dimensions.clone(),
span: array_init.span.clone(),
});
}
let mut dimensions = array_init.dimensions.clone();
let mut next = Expression::ArrayInit(ArrayInitExpression {
let mk_expr = |element, dim| ArrayInitExpression {
element,
dimensions: ArrayDimensions(vec![dimensions.remove_last().unwrap()]),
dimensions: ArrayDimensions::single(dim),
span: array_init.span.clone(),
});
};
let mut outer_element = Box::new(next.clone());
for (index, dimension) in dimensions.0.iter().rev().enumerate() {
if index == dimensions.0.len() - 1 {
break;
let mut iter = array_init.dimensions.iter().rev().cloned();
// We know the array has non-zero dimensions.
let init = mk_expr(Box::new(element), iter.next().unwrap());
Ok(iter.fold(init, |elem, dim| mk_expr(Box::new(Expression::ArrayInit(elem)), dim)))
}
fn reduce_definition(
&mut self,
definition: &DefinitionStatement,
variable_names: Vec<VariableName>,
type_: Option<Type>,
value: Expression,
) -> Result<DefinitionStatement> {
match &type_ {
Some(Type::Tuple(elements)) if elements.len() != 1 => {}
_ if definition.parened => {
return Err(AstError::invalid_parens_around_single_variable(&definition.span).into());
}
next = Expression::ArrayInit(ArrayInitExpression {
element: outer_element,
dimensions: ArrayDimensions(vec![dimension.clone()]),
span: array_init.span.clone(),
});
outer_element = Box::new(next.clone());
_ => {}
}
Ok(ArrayInitExpression {
element: outer_element,
dimensions: ArrayDimensions(vec![dimensions.remove_first().unwrap()]),
span: array_init.span.clone(),
Ok(DefinitionStatement {
declaration_type: definition.declaration_type.clone(),
variable_names,
parened: definition.parened,
type_,
value,
span: definition.span.clone(),
})
}
@ -662,7 +655,7 @@ impl ReconstructingReducer for Canonicalizer {
&assign.span,
)?;
let right = Box::new(value);
let op = self.compound_operation_converstion(&assign.operation)?;
let op = self.compound_operation_conversion(&assign.operation)?;
let new_value = Expression::Binary(BinaryExpression {
left,
@ -691,8 +684,9 @@ impl ReconstructingReducer for Canonicalizer {
&mut self,
function: &Function,
identifier: Identifier,
annotations: Vec<Annotation>,
annotations: IndexMap<Symbol, Annotation>,
input: Vec<FunctionInput>,
const_: bool,
output: Option<Type>,
block: Block,
) -> Result<Function> {
@ -705,22 +699,23 @@ impl ReconstructingReducer for Canonicalizer {
identifier,
annotations,
input,
const_,
output: new_output,
block,
core_mapping: function.core_mapping.clone(),
span: function.span.clone(),
})
}
fn reduce_circuit(
&mut self,
circuit: &Circuit,
_circuit: &Circuit,
circuit_name: Identifier,
members: Vec<CircuitMember>,
) -> Result<Circuit> {
self.circuit_name = Some(circuit_name.clone());
let circ = Circuit {
circuit_name,
core_mapping: circuit.core_mapping.clone(),
members: members
.iter()
.map(|member| self.canonicalize_circuit_member(member))

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// 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
@ -14,5 +14,18 @@
// 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/>.
//! Implements the AstPass trait for the Canonicalizer
//! which is a ReconstructingReducer trait to canonicalize AST nodes.
//! This allows for easy calling of the Canonicalization pass.
pub mod canonicalizer;
pub use canonicalizer::*;
use leo_ast::{Ast, AstPass, Program, ReconstructingDirector};
use leo_errors::Result;
impl AstPass for Canonicalizer {
fn do_pass(self, ast: Program) -> Result<Ast> {
Ok(Ast::new(ReconstructingDirector::new(self).reduce_program(&ast)?))
}
}

View File

@ -19,5 +19,7 @@
pub mod canonicalization;
pub use canonicalization::*;
pub mod import_resolution;
pub use import_resolution::*;
// Temporarily disable import resolution
// until we migrate stdlib and then import resolution.
/* pub mod import_resolution;
pub use import_resolution::*; */

View File

@ -21,10 +21,6 @@ rust-version = "1.56"
[dependencies]
smallvec = { version = "1.8.0", features = ["serde"] }
[dependencies.leo-input]
path = "../input"
version = "1.5.3"
[dependencies.leo-errors]
path = "../errors"
version = "1.5.3"
@ -37,9 +33,6 @@ version = "1.5.3"
version = "1.8.0"
features = [ "serde-1" ]
[dependencies.pest]
version = "2.0"
[dependencies.serde]
version = "1.0"
features = [ "derive", "rc" ]

View File

@ -17,7 +17,6 @@
use leo_span::Span;
use serde::{Deserialize, Serialize};
// use serde::de::{Deserialize as SerDeserialize, Deserializer};
use std::fmt;
fn char_to_u32<S>(character: &char, serializer: S) -> Result<S::Ok, S::Error>

View File

@ -15,7 +15,6 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::PositiveNumber;
use leo_input::types::ArrayDimensions as InputArrayDimensions;
use serde::{ser::SerializeSeq, Deserialize, Serialize, Serializer};
use smallvec::{smallvec, SmallVec};
@ -114,24 +113,6 @@ impl Serialize for ArrayDimensions {
}
}
/// Create a new [`ArrayDimensions`] from a [`InputArrayDimensions`] in a Leo program file.
impl<'ast> From<InputArrayDimensions<'ast>> for ArrayDimensions {
fn from(dimensions: InputArrayDimensions<'ast>) -> Self {
match dimensions {
InputArrayDimensions::Single(single) => {
Self(smallvec![Dimension::Number(PositiveNumber::from(single.number))])
}
InputArrayDimensions::Multiple(multiple) => Self(
multiple
.numbers
.into_iter()
.map(|num| Dimension::Number(PositiveNumber::from(num)))
.collect(),
),
}
}
}
impl fmt::Display for ArrayDimensions {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match &*self.0 {

View File

@ -14,7 +14,6 @@
// 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 leo_input::common::Identifier as InputIdentifier;
use leo_span::{Span, Symbol};
use crate::Node;
@ -68,15 +67,6 @@ impl Identifier {
}
}
impl<'ast> From<InputIdentifier<'ast>> for Identifier {
fn from(identifier: InputIdentifier<'ast>) -> Self {
Self {
name: Symbol::intern(&identifier.value),
span: Span::from(identifier.span),
}
}
}
impl fmt::Display for Identifier {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.name)

View File

@ -14,8 +14,6 @@
// 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 leo_input::values::PositiveNumber as InputPositiveNumber;
use serde::{Deserialize, Serialize};
use std::fmt;
use tendril::StrTendril;
@ -36,15 +34,6 @@ impl PositiveNumber {
}
}
/// Create a new [`PositiveNumber`] from an [`InputPositiveNumber`] in a Leo input file.
impl<'ast> From<InputPositiveNumber<'ast>> for PositiveNumber {
fn from(array: InputPositiveNumber<'ast>) -> Self {
Self {
value: array.value.into(),
}
}
}
impl fmt::Display for PositiveNumber {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.value)

View File

@ -14,10 +14,6 @@
// 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 leo_input::values::{
GroupCoordinate as InputGroupCoordinate, Inferred as InputInferred, NumberValue as InputNumberValue,
SignHigh as InputSignHigh, SignLow as InputSignLow,
};
use leo_span::Span;
use serde::{Deserialize, Serialize};
@ -40,17 +36,6 @@ pub enum GroupCoordinate {
Inferred,
}
impl<'ast> From<InputGroupCoordinate<'ast>> for GroupCoordinate {
fn from(coordinate: InputGroupCoordinate<'ast>) -> Self {
match coordinate {
InputGroupCoordinate::Number(number) => GroupCoordinate::from(number),
InputGroupCoordinate::SignHigh(sign_high) => GroupCoordinate::from(sign_high),
InputGroupCoordinate::SignLow(sign_low) => GroupCoordinate::from(sign_low),
InputGroupCoordinate::Inferred(inferred) => GroupCoordinate::from(inferred),
}
}
}
impl fmt::Display for GroupCoordinate {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
@ -61,30 +46,3 @@ impl fmt::Display for GroupCoordinate {
}
}
}
impl<'ast> From<InputNumberValue<'ast>> for GroupCoordinate {
fn from(number: InputNumberValue<'ast>) -> Self {
let value = number.to_string();
let span = Span::from(number.span().clone());
GroupCoordinate::Number(value.into(), span)
}
}
impl<'ast> From<InputSignHigh<'ast>> for GroupCoordinate {
fn from(_sign: InputSignHigh<'ast>) -> Self {
GroupCoordinate::SignHigh
}
}
impl<'ast> From<InputSignLow<'ast>> for GroupCoordinate {
fn from(_sign: InputSignLow<'ast>) -> Self {
GroupCoordinate::SignLow
}
}
impl<'ast> From<InputInferred<'ast>> for GroupCoordinate {
fn from(_sign: InputInferred<'ast>) -> Self {
GroupCoordinate::Inferred
}
}

View File

@ -15,9 +15,6 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::groups::GroupCoordinate;
use leo_input::values::{
GroupRepresentation as InputGroupRepresentation, GroupTuple as InputGroupTuple, GroupValue as InputGroupValue,
};
use leo_span::Span;
use serde::{Deserialize, Serialize};
@ -52,17 +49,6 @@ impl GroupValue {
}
}
impl<'ast> From<InputGroupValue<'ast>> for GroupValue {
fn from(ast_group: InputGroupValue) -> Self {
let span = Span::from(ast_group.span);
match ast_group.value {
InputGroupRepresentation::Single(number) => GroupValue::Single(number.to_string().into(), span),
InputGroupRepresentation::Tuple(tuple) => GroupValue::Tuple(GroupTuple::from(tuple)),
}
}
}
impl fmt::Display for GroupValue {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
@ -83,19 +69,6 @@ pub struct GroupTuple {
pub span: Span,
}
impl<'ast> From<InputGroupTuple<'ast>> for GroupTuple {
fn from(ast_group: InputGroupTuple<'ast>) -> Self {
let ast_x = ast_group.x;
let ast_y = ast_group.y;
Self {
x: GroupCoordinate::from(ast_x),
y: GroupCoordinate::from(ast_y),
span: Span::from(ast_group.span),
}
}
}
impl fmt::Display for GroupTuple {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {})", self.x, self.y)

View File

@ -14,9 +14,15 @@
// 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::{InputValue, Parameter};
use leo_input::{definitions::Definition, InputParserError};
use super::*;
use crate::{Expression, Identifier, Type};
use indexmap::IndexMap;
record_input_section!(Registers);
/// A single definition inside a section in a state or an input file.
/// Definitions should be structured as: `<name>: <type_> = <value>;`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Definition {
pub type_: Type,
pub name: Identifier,
pub value: Expression,
pub span: Span,
}

View File

@ -14,126 +14,26 @@
// 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::{ConstantInput, InputValue, MainInput, ProgramInput, ProgramState, Record, Registers, State, StateLeaf};
use leo_input::{
files::{File, TableOrSection},
InputParserError,
};
use leo_span::Symbol;
use super::*;
use leo_errors::AstError;
#[derive(Clone, PartialEq, Eq)]
/// Input data which includes [`ProgramInput`] and [`ProgramState`].
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Input {
name: String,
program_input: ProgramInput,
program_state: ProgramState,
pub program_input: ProgramInput,
pub program_state: ProgramState,
}
impl Default for Input {
fn default() -> Self {
Self {
name: "default".to_owned(),
program_input: ProgramInput::new(),
program_state: ProgramState::new(),
}
}
/// A raw unprocessed input or state file data. Used for future conversion
/// into [`ProgramInput`] or [`ProgramState`].
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ParsedInputFile {
pub sections: Vec<Section>,
}
#[allow(clippy::len_without_is_empty)]
impl Input {
pub fn new() -> Self {
Self::default()
}
/// Returns an empty version of this struct with `None` values.
/// Called during constraint synthesis to provide private input variables.
pub fn empty(&self) -> Self {
let input = self.program_input.empty();
let state = self.program_state.empty();
Self {
name: self.name.clone(),
program_input: input,
program_state: state,
}
}
/// Returns the number of input variables to pass into the `main` program function
pub fn len(&self) -> usize {
self.program_input.len() + self.program_state.len()
}
/// Manually set the input variables to the `main` program function
pub fn set_main_input(&mut self, input: MainInput) {
self.program_input.main = input;
}
/// Parse all input variables included in a file and store them in `self`.
pub fn parse_input(&mut self, file: File) -> Result<(), InputParserError> {
for entry in file.entries.into_iter() {
match entry {
TableOrSection::Section(section) => {
self.program_input.parse(section)?;
}
TableOrSection::Table(table) => return Err(InputParserError::table(table)),
}
}
Ok(())
}
/// Parse all state variables included in a file and store them in `self`.
pub fn parse_state(&mut self, file: File) -> Result<(), InputParserError> {
for entry in file.entries.into_iter() {
match entry {
TableOrSection::Section(section) => return Err(InputParserError::section(section.header)),
TableOrSection::Table(table) => {
self.program_state.parse(table)?;
}
}
}
Ok(())
}
/// Returns the main function input value with the given `name`.
#[allow(clippy::ptr_arg)]
pub fn get(&self, name: Symbol) -> Option<Option<InputValue>> {
self.program_input.get(name)
}
/// Returns the constant input value with the given `name`.
#[allow(clippy::ptr_arg)]
pub fn get_constant(&self, name: Symbol) -> Option<Option<InputValue>> {
self.program_input.get_constant(name)
}
/// Returns the main input values
pub fn get_main_inputs(&self) -> &MainInput {
&self.program_input.main
}
/// Returns the main input values
pub fn get_constant_inputs(&self) -> &ConstantInput {
&self.program_input.constants
}
/// Returns the runtime register input values
pub fn get_registers(&self) -> &Registers {
self.program_input.get_registers()
}
/// Returns the runtime record input values
pub fn get_record(&self) -> &Record {
self.program_state.get_record()
}
/// Returns the runtime state input values
pub fn get_state(&self) -> &State {
self.program_state.get_state()
}
/// Returns the runtime state leaf input values
pub fn get_state_leaf(&self) -> &StateLeaf {
self.program_state.get_state_leaf()
/// Serializes the ast into a JSON string.
pub fn to_json_string(&self) -> Result<String> {
Ok(serde_json::to_string_pretty(&self).map_err(|e| AstError::failed_to_convert_ast_to_json_string(&e))?)
}
}

View File

@ -14,22 +14,13 @@
// 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 crate::{CharValue, Expression, GroupValue, IntegerType, Node, SpreadOrExpression, Type, ValueExpression};
use leo_errors::{InputError, LeoError, ParserError, Result};
use serde::{Deserialize, Serialize};
use std::fmt;
#[derive(Clone, Debug, PartialEq, Eq)]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum InputValue {
Address(String),
Boolean(bool),
@ -41,350 +32,125 @@ pub enum 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(),
));
}
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, span)) => {
if expected == actual {
Self::Integer(expected, value.to_string())
} else {
return Err(InputError::unexpected_type(expected.to_string(), actual, &span).into());
}
}
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(),
));
}
(Type::Array(type_, _), ValueExpression::String(string, span)) => {
if !matches!(*type_, Type::Char) {
return Err(InputError::string_is_array_of_chars(type_, &span).into());
}
Self::Array(
string
.into_iter()
.map(|c| {
Self::Char(CharValue {
character: c,
span: span.clone(),
})
})
.collect(),
)
}
(x, y) => {
return Err(InputError::unexpected_type(x, &y, y.span()).into());
}
}
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)),
}
}
(Type::Array(type_, type_dimensions), Expression::ArrayInit(mut array_init)) => {
let span = array_init.span.clone();
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)
if type_dimensions != array_init.dimensions || array_init.dimensions.is_zero() {
return Err(InputError::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, 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)) => {
InputValue::from_array_initializer(array_type, initializer)
(Type::Tuple(types), Expression::TupleInit(tuple_init)) => {
let size = tuple_init.elements.len();
let mut elements = Vec::with_capacity(size);
if size != types.len() {
return Err(InputError::tuple_length_mismatch(size, types.len(), tuple_init.span()).into());
}
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)) => {
InputValue::from_string(array_type, string)
(Type::Array(element_type, dimensions), Expression::ArrayInline(array_inline)) => {
let mut elements = Vec::with_capacity(array_inline.elements.len());
let span = array_inline.span().clone();
if !dimensions.is_specified() {
return Err(InputError::array_dimensions_must_be_specified(&span).into());
}
for element in array_inline.elements.into_iter() {
if let SpreadOrExpression::Expression(value_expression) = element {
elements.push(Self::try_from((*element_type.clone(), value_expression))?);
} else {
return Err(InputError::array_spread_is_not_allowed(&span).into());
}
}
Self::Array(elements)
}
(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_)),
(_type_, expr) => return Err(InputError::illegal_expression(&expr, expr.span()).into()),
})
}
}
@ -399,12 +165,10 @@ impl fmt::Display for InputValue {
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,151 +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/>.
/// Constructs an input section to store data parsed from a Leo input file.
/// Constructs sections that pass variables to the main function through the input keyword.
#[macro_export]
macro_rules! record_input_section {
($($name: ident), *) => ($(
/// An input section declared in an input file with `[$name]`.
#[derive(Clone, PartialEq, Eq, Default)]
pub struct $name {
is_present: bool,
values: IndexMap<Parameter, Option<InputValue>>,
}
impl $name {
pub fn new() -> Self {
Self::default()
}
/// Returns an empty version of this struct with `None` values.
/// Called during constraint synthesis to provide private input variables.
pub fn empty(&self) -> Self {
let is_present = self.is_present;
let mut values = self.values.clone();
values.iter_mut().for_each(|(_parameter, value)| {
*value = None;
});
Self { is_present, values }
}
/// Returns `true` if the main function contains the `$name` variable.
pub fn is_present(&self) -> bool {
self.is_present
}
/// Parses register input definitions and stores them in `self`.
/// This function is called if the main function input contains the `$name` variable.
pub fn parse(&mut self, definitions: Vec<Definition>) -> Result<(), InputParserError> {
self.is_present = true;
for definition in definitions {
let value = InputValue::from_expression(definition.parameter.type_.clone(), definition.expression)?;
let parameter = Parameter::from(definition.parameter);
self.values.insert(parameter, Some(value));
}
Ok(())
}
/// Returns this section's [IndexMap] of values.
pub fn values(&self) -> IndexMap<Parameter, Option<InputValue>> {
self.values.clone()
}
/// a list of all defined name -> type pairs
pub fn types(&self) -> Vec<(String, crate::Type)> {
self.values.iter()
.map(|(parameter, _)| (parameter.variable.name.to_string(), parameter.type_.clone()))
.collect()
}
/// a map of all defined name -> value pairs, if present
pub fn raw_values(&self) -> IndexMap<String, InputValue> {
self.values.iter()
.filter(|(_, value)| value.is_some())
.map(|(parameter, value)| (parameter.variable.name.to_string(), value.as_ref().unwrap().clone()))
.collect()
}
}
)*)
}
/// Constructs an input section to store data parsed from a Leo input file.
/// Constructs sections that pass variables directly to the main function.
#[macro_export]
macro_rules! main_input_section {
($($name: ident), *) => ($(
/// `[$name]` program input section.
#[derive(Clone, PartialEq, Eq, Default)]
pub struct $name {
input: IndexMap<leo_span::Symbol, Option<InputValue>>,
}
#[allow(clippy::len_without_is_empty)]
impl $name {
pub fn new() -> Self {
Self::default()
}
/// Returns an empty version of this struct with `None` values.
/// Called during constraint synthesis to provide private input variables.
pub fn empty(&self) -> Self {
let mut input = self.input.clone();
input.iter_mut().for_each(|(_name, value)| {
*value = None;
});
Self { input }
}
pub fn len(&self) -> usize {
self.input.len()
}
pub fn insert(&mut self, key: leo_span::Symbol, value: Option<InputValue>) {
self.input.insert(key, value);
}
/// Parses main input definitions and stores them in `self`.
pub fn parse(&mut self, definitions: Vec<Definition>) -> Result<(), InputParserError> {
for definition in definitions {
let name = leo_span::Symbol::intern(&definition.parameter.variable.value);
let value = InputValue::from_expression(definition.parameter.type_, definition.expression)?;
self.insert(name, Some(value));
}
Ok(())
}
/// Returns an `Option` of the main function input at `name`.
pub fn get(&self, name: leo_span::Symbol) -> Option<Option<InputValue>> {
self.input.get(&name).cloned()
}
pub fn iter(&self) -> impl Iterator<Item=(&leo_span::Symbol, &Option<InputValue>)> {
self.input.iter()
}
}
)*)
}

View File

@ -14,11 +14,8 @@
// 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::module_inception)]
#[macro_use]
pub mod macros;
pub use macros::*;
pub mod definition;
pub use definition::*;
pub mod input;
pub use input::*;
@ -26,11 +23,18 @@ pub use input::*;
pub mod input_value;
pub use input_value::*;
pub mod parameters;
pub use parameters::*;
pub mod program_input;
pub use program_input::*;
pub mod program_state;
pub use program_state::*;
pub mod section;
pub use section::*;
use indexmap::IndexMap;
use leo_errors::{InputError, LeoError, Result};
use leo_span::{sym, Span, Symbol};
use serde::{Deserialize, Serialize};
type Definitions = IndexMap<Symbol, InputValue>;

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),
}
}
}

View File

@ -0,0 +1,63 @@
// 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::*;
/// Processed Program input.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ProgramInput {
pub main: Definitions,
pub registers: Definitions,
pub 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 target = match section.name {
sym::main => &mut main,
sym::registers => &mut registers,
sym::constants => &mut constants,
_ => {
return Err(InputError::unexpected_section(
&["main", "registers", "constants"],
section.name,
&section.span,
)
.into())
}
};
for definition in section.definitions {
target.insert(
definition.name.name,
InputValue::try_from((definition.type_, definition.value))?,
);
}
}
Ok(ProgramInput {
main,
registers,
constants,
})
}
}

View File

@ -1,22 +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::InputValue;
use leo_input::{definitions::Definition, InputParserError};
use indexmap::IndexMap;
main_input_section!(ConstantInput);

View File

@ -1,29 +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/>.
#![allow(clippy::module_inception)]
pub mod constant_input;
pub use constant_input::*;
pub mod main_input;
pub use main_input::*;
pub mod program_input;
pub use program_input::*;
pub mod registers;
pub use registers::*;

View File

@ -1,91 +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::{ConstantInput, InputValue, MainInput, Registers};
use leo_input::{
sections::{Header, Section},
InputParserError,
};
use leo_span::Symbol;
#[derive(Clone, PartialEq, Eq, Default)]
pub struct ProgramInput {
pub main: MainInput,
pub constants: ConstantInput,
registers: Registers,
}
#[allow(clippy::len_without_is_empty)]
impl ProgramInput {
pub fn new() -> Self {
Self::default()
}
/// Returns an empty version of this struct with `None` values.
/// Called during constraint synthesis to provide private input values.
pub fn empty(&self) -> Self {
let main = self.main.empty();
let constants = self.constants.empty();
let registers = self.registers.empty();
Self {
main,
constants,
registers,
}
}
pub fn len(&self) -> usize {
let mut len = 0;
// Add main input variables and constants.
len += self.main.len();
len += self.constants.len();
// Add registers.
if self.registers.is_present() {
len += 1;
}
len
}
/// Parse each input included in a file and store them in `self`.
pub fn parse(&mut self, section: Section) -> Result<(), InputParserError> {
match section.header {
Header::Constants(_constants) => self.constants.parse(section.definitions),
Header::Main(_main) => self.main.parse(section.definitions),
Header::Registers(_registers) => self.registers.parse(section.definitions),
header => Err(InputParserError::input_section_header(header)),
}
}
/// Returns the main function input value with the given `name`
#[allow(clippy::ptr_arg)]
pub fn get(&self, name: Symbol) -> Option<Option<InputValue>> {
self.main.get(name)
}
#[allow(clippy::ptr_arg)]
pub fn get_constant(&self, name: Symbol) -> Option<Option<InputValue>> {
self.constants.get(name)
}
/// Returns the runtime register input values
pub fn get_registers(&self) -> &Registers {
&self.registers
}
}

View File

@ -0,0 +1,50 @@
// 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::*;
/// Processed Program state.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ProgramState {
pub state: Definitions,
}
impl TryFrom<ParsedInputFile> for ProgramState {
type Error = LeoError;
fn try_from(input: ParsedInputFile) -> Result<Self> {
let mut state = IndexMap::new();
for section in input.sections {
if matches!(section.name, sym::state | sym::record | sym::state_leaf) {
for definition in section.definitions {
state.insert(
definition.name.name,
InputValue::try_from((definition.type_, definition.value))?,
);
}
} else {
return Err(InputError::unexpected_section(
&["state", "record", "state_leaf"],
section.name,
&section.span,
)
.into());
}
}
Ok(ProgramState { state })
}
}

View File

@ -1,26 +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/>.
#![allow(clippy::module_inception)]
pub mod private_state;
pub use private_state::*;
pub mod program_state;
pub use program_state::*;
pub mod public_state;
pub use public_state::*;

View File

@ -1,26 +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/>.
#![allow(clippy::module_inception)]
pub mod private_state;
pub use private_state::*;
pub mod record;
pub use record::*;
pub mod state_leaf;
pub use state_leaf::*;

View File

@ -1,82 +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::{Record, StateLeaf};
use leo_input::{
sections::{Header, Section},
InputParserError,
};
#[derive(Clone, PartialEq, Eq, Default)]
pub struct PrivateState {
record: Record,
state_leaf: StateLeaf,
}
#[allow(clippy::len_without_is_empty)]
impl PrivateState {
pub fn new() -> Self {
Self::default()
}
/// Returns an empty version of this struct with `None` values.
/// Called during constraint synthesis to provide private input variables.
pub fn empty(&self) -> Self {
let record = self.record.empty();
let state_leaf = self.state_leaf.empty();
Self { record, state_leaf }
}
pub fn len(&self) -> usize {
let mut len = 0;
// add record variable
if self.record.is_present() {
len += 1;
}
// add state_leaf variable
if self.state_leaf.is_present() {
len += 1;
}
len
}
/// Parse all input variables included in a file and store them in `self`.
pub fn parse(&mut self, sections: Vec<Section>) -> Result<(), InputParserError> {
for section in sections {
match section.header {
Header::Record(_state) => self.record.parse(section.definitions)?,
Header::StateLeaf(_state_leaf) => self.state_leaf.parse(section.definitions)?,
header => return Err(InputParserError::private_section(header)),
}
}
Ok(())
}
/// Returns the runtime record input values
pub fn get_record(&self) -> &Record {
&self.record
}
/// Returns the runtime state leaf input values
pub fn get_state_leaf(&self) -> &StateLeaf {
&self.state_leaf
}
}

View File

@ -1,22 +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::{InputValue, Parameter};
use leo_input::{definitions::Definition, InputParserError};
use indexmap::IndexMap;
record_input_section!(Record);

View File

@ -1,22 +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::{InputValue, Parameter};
use leo_input::{definitions::Definition, InputParserError};
use indexmap::IndexMap;
record_input_section!(StateLeaf);

View File

@ -1,70 +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::{PrivateState, PublicState, Record, State, StateLeaf};
use leo_input::{
tables::{Table, Visibility},
InputParserError,
};
#[derive(Clone, PartialEq, Eq, Default)]
pub struct ProgramState {
public: PublicState,
private: PrivateState,
}
#[allow(clippy::len_without_is_empty)]
impl ProgramState {
pub fn new() -> Self {
Self::default()
}
/// Returns an empty version of this struct with `None` values.
/// Called during constraint synthesis to provide private input variables.
pub fn empty(&self) -> Self {
let public = self.public.empty();
let private = self.private.empty();
Self { public, private }
}
pub fn len(&self) -> usize {
self.public.len() + self.private.len()
}
/// Parse all input variables included in a file and store them in `self`.
pub fn parse(&mut self, table: Table) -> Result<(), InputParserError> {
match table.visibility {
Visibility::Private(_private) => self.private.parse(table.sections),
Visibility::Public(_public) => self.public.parse(table.sections),
}
}
/// Returns the runtime record input values
pub fn get_record(&self) -> &Record {
self.private.get_record()
}
/// Returns the runtime state input values
pub fn get_state(&self) -> &State {
self.public.get_state()
}
/// Returns the runtime state leaf input values
pub fn get_state_leaf(&self) -> &StateLeaf {
self.private.get_state_leaf()
}
}

View File

@ -1,23 +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/>.
#![allow(clippy::module_inception)]
pub mod public_state;
pub use public_state::*;
pub mod state;
pub use state::*;

View File

@ -1,66 +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::State;
use leo_input::{
sections::{Header, Section},
InputParserError,
};
#[derive(Clone, PartialEq, Eq, Default)]
pub struct PublicState {
state: State,
}
#[allow(clippy::len_without_is_empty)]
impl PublicState {
pub fn new() -> Self {
Self::default()
}
/// Returns an empty version of this struct with `None` values.
/// Called during constraint synthesis to provide private input variables.
pub fn empty(&self) -> Self {
let state = self.state.empty();
Self { state }
}
pub fn len(&self) -> usize {
if self.state.is_present() {
1usize
} else {
0usize
}
}
/// Parse all input variables included in a file and store them in `self`.
pub fn parse(&mut self, sections: Vec<Section>) -> Result<(), InputParserError> {
for section in sections {
match section.header {
Header::State(_state) => self.state.parse(section.definitions)?,
header => return Err(InputParserError::public_section(header)),
}
}
Ok(())
}
/// Returns the runtime state input values
pub fn get_state(&self) -> &State {
&self.state
}
}

View File

@ -1,22 +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::{InputValue, Parameter};
use leo_input::{definitions::Definition, InputParserError};
use indexmap::IndexMap;
record_input_section!(State);

View File

@ -14,9 +14,13 @@
// 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::InputValue;
use leo_input::{definitions::Definition, InputParserError};
use super::*;
use indexmap::IndexMap;
main_input_section!(MainInput);
/// A single section in an input or a state file.
/// An example of a section would be: `[main]`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Section {
pub name: Symbol,
pub definitions: Vec<Definition>,
pub span: Span,
}

View File

@ -79,8 +79,6 @@ use leo_errors::{AstError, Result};
///
/// The [`Ast`] type represents a Leo program as a series of recursive data types.
/// These data types form a tree that begins from a [`Program`] type root.
///
/// A new [`Ast`] can be created from a [`Grammar`] generated by the pest parser in the `grammar` module.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Ast {
ast: Program,

View File

@ -14,6 +14,11 @@
// 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/>.
//! This module contains both a Director to reconstruct the AST
//! which maps over every node of the AST and calls a reducer.
//! The Trait for a reducer are methods that can be overridden
//! to make changes to how AST nodes are rebuilt.
pub mod reconstructing_reducer;
pub use reconstructing_reducer::*;

View File

@ -14,8 +14,8 @@
// 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/>.
//! This module contains the reducer which iterates through ast nodes - converting them into
//! asg nodes and saving relevant information.
//! This module contains a Director for how to map over the AST
//! and applies a reducer call to each node.
use crate::*;

View File

@ -14,6 +14,10 @@
// 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/>.
//! This module contains a Reducer Trait for the AST.
//! It implements default methods for each node to be made
//! given the information of the old node.
use crate::*;
use leo_errors::Result;
@ -282,6 +286,7 @@ pub trait ReconstructingReducer {
Ok(DefinitionStatement {
declaration_type: definition.declaration_type.clone(),
variable_names,
parened: definition.parened,
type_,
value,
span: definition.span.clone(),

View File

@ -33,6 +33,8 @@ pub struct DefinitionStatement {
pub declaration_type: Declare,
/// The bindings / variable names to declare.
pub variable_names: Vec<VariableName>,
/// Tracks whether the variable(s) are in parens.
pub parened: bool,
/// The types of the bindings, if specified, or inferred otherwise.
pub type_: Option<Type>,
/// An initializer value for the bindings.

View File

@ -14,10 +14,6 @@
// 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 leo_input::types::{
IntegerType as InputIntegerType, SignedIntegerType as InputSignedIntegerType,
UnsignedIntegerType as InputUnsignedIntegerType,
};
use leo_span::{sym, Symbol};
use serde::{Deserialize, Serialize};
@ -63,39 +59,6 @@ impl IntegerType {
}
}
impl From<InputIntegerType> for IntegerType {
fn from(integer_type: InputIntegerType) -> Self {
match integer_type {
InputIntegerType::Signed(signed) => Self::from(signed),
InputIntegerType::Unsigned(unsigned) => Self::from(unsigned),
}
}
}
impl From<InputUnsignedIntegerType> for IntegerType {
fn from(integer_type: InputUnsignedIntegerType) -> Self {
match integer_type {
InputUnsignedIntegerType::U8Type(_type) => IntegerType::U8,
InputUnsignedIntegerType::U16Type(_type) => IntegerType::U16,
InputUnsignedIntegerType::U32Type(_type) => IntegerType::U32,
InputUnsignedIntegerType::U64Type(_type) => IntegerType::U64,
InputUnsignedIntegerType::U128Type(_type) => IntegerType::U128,
}
}
}
impl From<InputSignedIntegerType> for IntegerType {
fn from(integer_type: InputSignedIntegerType) -> Self {
match integer_type {
InputSignedIntegerType::I8Type(_type) => IntegerType::I8,
InputSignedIntegerType::I16Type(_type) => IntegerType::I16,
InputSignedIntegerType::I32Type(_type) => IntegerType::I32,
InputSignedIntegerType::I64Type(_type) => IntegerType::I64,
InputSignedIntegerType::I128Type(_type) => IntegerType::I128,
}
}
}
impl fmt::Display for IntegerType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {

View File

@ -15,9 +15,6 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{ArrayDimensions, Identifier, IntegerType};
use leo_input::types::{
ArrayType as InputArrayType, DataType as InputDataType, TupleType as InputTupleType, Type as InputType,
};
use serde::{Deserialize, Serialize};
use std::fmt;
@ -122,48 +119,6 @@ impl Type {
}
}
/// input pest ast -> Explicit Type
impl From<InputDataType> for Type {
fn from(data_type: InputDataType) -> Self {
match data_type {
InputDataType::Address(_type) => Type::Address,
InputDataType::Boolean(_type) => Type::Boolean,
InputDataType::Char(_type) => Type::Char,
InputDataType::Field(_type) => Type::Field,
InputDataType::Group(_type) => Type::Group,
InputDataType::Integer(type_) => Type::IntegerType(IntegerType::from(type_)),
}
}
}
impl<'ast> From<InputArrayType<'ast>> for Type {
fn from(array_type: InputArrayType<'ast>) -> Self {
let element_type = Box::new(Type::from(*array_type.type_));
let dimensions = ArrayDimensions::from(array_type.dimensions);
Type::Array(element_type, dimensions)
}
}
impl<'ast> From<InputTupleType<'ast>> for Type {
fn from(tuple_type: InputTupleType<'ast>) -> Self {
let types = tuple_type.types_.into_iter().map(Type::from).collect();
Type::Tuple(types)
}
}
impl<'ast> From<InputType<'ast>> for Type {
fn from(type_: InputType<'ast>) -> Self {
match type_ {
InputType::Basic(type_) => Type::from(type_),
InputType::Array(type_) => Type::from(type_),
InputType::Tuple(type_) => Type::from(type_),
}
}
}
impl fmt::Display for Type {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {

View File

@ -22,6 +22,10 @@ rust-version = "1.56.1"
path = "../ast"
version = "1.5.3"
[dependencies.leo-ast-passes]
path = "../ast-passes"
version = "1.5.3"
[dependencies.leo-errors]
path = "../errors"
version = "1.5.3"
@ -30,6 +34,10 @@ version = "1.5.3"
path = "../parser"
version = "1.5.3"
[dependencies.leo-span]
path = "../span"
version = "1.5.3"
[dependencies.sha2]
version = "0.10"

View File

@ -22,8 +22,10 @@
#![allow(clippy::upper_case_acronyms)]
#![doc = include_str!("../README.md")]
use leo_ast::AstPass;
use leo_errors::emitter::Handler;
use leo_errors::{CompilerError, Result};
use leo_span::symbol::create_session_if_not_set_then;
use sha2::{Digest, Sha256};
use std::fs;
@ -33,16 +35,18 @@ use std::path::PathBuf;
pub struct Compiler<'a> {
handler: &'a Handler,
main_file_path: PathBuf,
output_directory: PathBuf,
}
impl<'a> Compiler<'a> {
///
/// Returns a new Leo compiler.
///
pub fn new(handler: &'a Handler, main_file_path: PathBuf) -> Self {
pub fn new(handler: &'a Handler, main_file_path: PathBuf, output_directory: PathBuf) -> Self {
Self {
handler,
main_file_path,
output_directory,
}
}
@ -63,20 +67,34 @@ impl<'a> Compiler<'a> {
}
///
/// Returns a compiled Leo program.
/// Runs the compiler stages.
///
pub fn compile(self) -> Result<leo_ast::Ast> {
fn compiler_stages(self) -> Result<leo_ast::Ast> {
// Load the program file.
let program_string = fs::read_to_string(&self.main_file_path)
.map_err(|e| CompilerError::file_read_error(self.main_file_path.clone(), e))?;
// Use the parser to construct the abstract syntax tree (ast).
let ast: leo_ast::Ast = leo_parser::parse_ast(
let mut ast: leo_ast::Ast = leo_parser::parse_ast(
self.handler,
self.main_file_path.to_str().unwrap_or_default(),
program_string,
)?;
// Write the AST snapshot post parsing.
ast.to_json_file_without_keys(self.output_directory.clone(), "inital_ast.json", &["span"])?;
// Canonicalize the AST.
ast = leo_ast_passes::Canonicalizer::do_pass(Default::default(), ast.into_repr())?;
// Write the AST snapshot post parsing
ast.to_json_file_without_keys(self.output_directory, "canonicalization_ast.json", &["span"])?;
Ok(ast)
}
///
/// Returns a compiled Leo program.
///
pub fn compile(self) -> Result<leo_ast::Ast> {
create_session_if_not_set_then(|_| self.compiler_stages())
}
}

View File

@ -30,9 +30,6 @@ version = "1.5.3"
#path = "../imports"
#version = "1.5.3"
#
#[dependencies.leo-input]
#path = "../input"
#version = "1.5.3"
#
#[dependencies.leo-package]
#path = "../package"
@ -102,9 +99,6 @@ features = [ "serde-1" ]
[dependencies.num-bigint]
version = "0.4"
[dependencies.pest]
version = "2.0"
[dependencies.rand]
version = "0.8"

View File

@ -24,7 +24,6 @@ use leo_asg::{Asg, AsgPass, Program as AsgProgram};
use leo_ast::{AstPass, Input, MainInput, Program as AstProgram};
use leo_errors::{CompilerError, Result};
use leo_imports::ImportParser;
use leo_input::LeoInputParser;
use leo_package::inputs::InputPairs;
use leo_parser::parse_ast;

View File

@ -20,7 +20,6 @@ use crate::{ConstrainedProgram, GroupType, Output, OutputFile};
use leo_asg::Program;
use leo_ast::Input;
use leo_errors::{CompilerError, Result};
use leo_input::LeoInputParser;
use leo_package::inputs::InputPairs;
use snarkvm_fields::PrimeField;

View File

@ -25,10 +25,6 @@ version = "0.3.62"
path = "../span"
version = "1.5.3"
[dependencies.leo-input]
path = "../input"
version = "1.5.3"
[dependencies.colored]
version = "2.0.0"
@ -42,9 +38,6 @@ version = "2.2.0"
version = "0.6.6"
default-features = false
[dependencies.pest]
version = "2.0"
[dependencies.serde]
version = "1.0.133"
features = [ "derive", "rc" ]

View File

@ -13,7 +13,7 @@ The common section of this crate contains a few sub files:
- [Backtraced Error](./src/common/backtraced.rs): Which contains the information needed to create a backtraceable error for Leo.
- [Formatted Error](./src/common/formatted.rs): Which contains the information needed to create a formatted error for Leo.
- [Macros](./src/common/macros.rs): Which contains the logic to make creating errors easy through a DSL. It also figures out the error codes for each error via a **top down** method. Meaning all new errors should be added to the bottom of the file. You can specify whether an error is formatted or backtraced through a decorator above a function name, where the formatted ones require a Span as an argument by default. The body takes any additional arguments you want provided to the function, the message, and the optional help message for the error. The additional arguments are just specified to implement traits to avoid as many type conversions in other Leo crates.
- [Span](./src/common/span.rs): Which contains the span object used throughout the other Leo crates(with the exception of the Input crate see more [below](#input)).
- [Span](./src/common/span.rs): Which contains the span object used throughout the other Leo crates (with the exception of the Input crate see more [below](#input)).
- [Tendril JSON](./src/common/tendril_json.rs): Which contains the common logic for how to searlize a StrTendril from the tendril crate.
- [Traits](./src/common/traits.rs): Which contains the common traits in errors to make defining errors easier.
@ -41,10 +41,9 @@ The errors for the `leo-compiler` crate. Its error codes will range from 6_000-6
The errors for the `leo-imports` crate. Its error codes will range from 4_000-4_999 and be prefixed with the characters `IMP`.
### Input
## Input
The errors for the `leo-input` crate. For right now, they have an exit code of 1, as they aren't ported.
The reason they aren't ported is due to a desire for 0 deps in case this crate moves to SnarkVM.
The errors for the `leo-ast` crate. Its error codes will range from 8_000-8_999 and be prefixed with the characters `INP`.
### Package

View File

@ -130,4 +130,20 @@ create_errors!(
msg: format!("failed to convert ast to a json value {}", error),
help: None,
}
/// For when a user tries to define a tuple dimension of 1.
@formatted
invalid_tuple_dimension_size {
args: (),
msg: "tuples of 1 element are not allowed",
help: None,
}
/// For when a user puts parens around a single defined variable.
@formatted
invalid_parens_around_single_variable {
args: (),
msg: "do not put parens around single variable names",
help: None,
}
);

View File

@ -0,0 +1,104 @@
// 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::create_errors;
use std::fmt::{Debug, Display};
create_errors!(
/// InputError enum that represents all the errors for the inputs part of `leo-ast` crate.
InputError,
exit_code_mask: 8000i32,
error_code_prefix: "INP",
/// For when declared variable type mismatches actual type.
@formatted
unexpected_type {
args: (expected: impl Display, received: impl Display),
msg: format!(
"unexpected type, expected: '{}', received: '{}'",
expected,
received,
),
help: None,
}
/// For when string value is assigned to an array of non Char type.
@formatted
string_is_array_of_chars {
args: (expected: impl Display),
msg: format!(
"strings transforms into array of 'char', expected: {}",
expected,
),
help: None,
}
/// For when [`ArrayDimensions`] are not specified.
@formatted
array_dimensions_must_be_specified {
args: (),
msg: "array dimensions must be specified",
help: None,
}
/// For when array init is using spread.
@formatted
array_spread_is_not_allowed {
args: (),
msg: "array spread is not allowed in inputs",
help: None,
}
/// For when any of the array dimensions is zero.
@formatted
invalid_array_dimension_size {
args: (),
msg: "received dimension size of 0, expected it to be 1 or larger.",
help: None,
}
/// For when the expression is not allowed in an input file.
@formatted
illegal_expression {
args: (expr: impl Display),
msg: format!("expression '{}' is not allowed in inputs", expr),
help: None,
}
/// For when section name is not an allowed one.
@formatted
unexpected_section {
args: (expected: &[impl Display], received: impl Display),
msg: format!(
"unexpected section: expected {} -- got '{}'",
expected
.iter()
.map(|x| format!("'{}'", x))
.collect::<Vec<_>>()
.join(", "),
received
),
help: None,
}
/// For when declared tuple length is not equal to the value's.
@formatted
tuple_length_mismatch {
args: (expected: impl Display, received: impl Display),
msg: format!("tuple length mismatch, defined {} types, got {} values", expected, received),
help: None,
}
);

View File

@ -14,5 +14,6 @@
// 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::*;
/// This module contains the Input error definitions.
pub mod input_errors;
pub use self::input_errors::*;

View File

@ -45,6 +45,10 @@ pub use self::compiler::*;
pub mod import;
pub use self::import::*;
/// Contains the Input error definitions.
pub mod input;
pub use self::input::*;
/// Contains the Package error definitions.
pub mod package;
pub use self::package::*;
@ -64,8 +68,6 @@ pub use self::state::*;
#[macro_use]
extern crate thiserror;
use leo_input::InputParserError;
/// The LeoError type that contains all sub error types.
/// This allows a unified error type throughout the Leo crates.
#[derive(Debug, Error)]
@ -92,7 +94,7 @@ pub enum LeoError {
/// Represents an Input Error in a Leo Error.
#[error(transparent)]
InputError(#[from] InputParserError),
InputError(#[from] InputError),
/// Represents an Package Error in a Leo Error.
#[error(transparent)]
@ -122,7 +124,7 @@ impl LeoError {
CliError(error) => error.error_code(),
CompilerError(error) => error.error_code(),
ImportError(error) => error.error_code(),
InputError(_error) => Default::default(), // TODO migrate me, or not cause we want inputs to have 0 deps.
InputError(error) => error.error_code(),
PackageError(error) => error.error_code(),
ParserError(error) => error.error_code(),
SnarkVMError(_error) => Default::default(), // TODO update once snarkvm implments a global top level error similar to LeoError.
@ -140,7 +142,7 @@ impl LeoError {
CliError(error) => error.exit_code(),
CompilerError(error) => error.exit_code(),
ImportError(error) => error.exit_code(),
InputError(_error) => 1, // TODO migrate me, or not cause we want inputs to have 0 deps.
InputError(error) => error.exit_code(),
PackageError(error) => error.exit_code(),
ParserError(error) => error.exit_code(),
SnarkVMError(_error) => 1, // TODO update once snarkvm implments a global top level error similar to LeoError.

View File

@ -625,25 +625,6 @@ identifier = letter *( letter / decimal-digit / "_" )
Go to: _[letter](#user-content-letter)_;
A package name consists of one or more segments separated by single dashes,
where each segment is a non-empty sequence of
lowercase letters and (decimal) digits.
Similarly to an identifier, a package name must not be a keyword
and must not be or start with `aleo1`.
<a name="package-name"></a>
```abnf
package-name = lowercase-letter *( lowercase-letter / decimal-digit )
*( "-" 1*( lowercase-letter / decimal-digit ) )
; but not a keyword or a boolean literal or aleo1...
```
Go to: _[lowercase-letter](#user-content-lowercase-letter)_;
Note that, grammatically, identifiers are also package names.
They are disambiguated from context, based on the syntactic grammar.
Annotations have names, which are identifiers immediately preceded by `@`.
<a name="annotation-name"></a>
@ -918,12 +899,11 @@ is a token, as defined by the following rule.
token = keyword
/ identifier
/ atomic-literal
/ package-name
/ annotation-name
/ symbol
```
Go to: _[annotation-name](#user-content-annotation-name), [atomic-literal](#user-content-atomic-literal), [identifier](#user-content-identifier), [keyword](#user-content-keyword), [package-name](#user-content-package-name), [symbol](#user-content-symbol)_;
Go to: _[annotation-name](#user-content-annotation-name), [atomic-literal](#user-content-atomic-literal), [identifier](#user-content-identifier), [keyword](#user-content-keyword), [symbol](#user-content-symbol)_;
Tokens, comments, and whitespace are lexemes, i.e. lexical units.
@ -1795,33 +1775,33 @@ An import declaration consists of the `import` keyword
followed by a package path, which may be one of the following:
a single wildcard;
an identifier, optionally followed by a local renamer;
a package name followed by a path, recursively;
an identifier followed by a path, recursively;
or a parenthesized list of package paths,
which are "fan out" of the initial path.
Note that we allow the last element of the parenthesized list
to be followed by a comma, for convenience.
The package path in the import declaration must start with a package name
The package path in the import declaration must start with an identifier
(e.g. it cannot be a `*`):
the rule for import declaration expresses this requirement
by using an explicit package name before the package path.
by using an explicit identifier before the package path.
<a name="import-declaration"></a>
```abnf
import-declaration = %s"import" package-name "." package-path ";"
import-declaration = %s"import" identifier "." package-path ";"
```
Go to: _[package-name](#user-content-package-name), [package-path](#user-content-package-path)_;
Go to: _[identifier](#user-content-identifier), [package-path](#user-content-package-path)_;
<a name="package-path"></a>
```abnf
package-path = "*"
/ identifier [ %s"as" identifier ]
/ package-name "." package-path
/ identifier "." package-path
/ "(" package-path *( "," package-path ) [","] ")"
```
Go to: _[identifier](#user-content-identifier), [package-name](#user-content-package-name), [package-path](#user-content-package-path)_;
Go to: _[identifier](#user-content-identifier), [package-path](#user-content-package-path)_;
A type alias declaration defines an identifier to stand for a type.

View File

@ -447,19 +447,6 @@ hexadecimal-digit = decimal-digit / "a" / "b" / "c" / "d" / "e" / "f"
identifier = letter *( letter / decimal-digit / "_" )
; but not a keyword or a boolean literal or aleo1...
; A package name consists of one or more segments separated by single dashes,
; where each segment is a non-empty sequence of
; lowercase letters and (decimal) digits.
; Similarly to an identifier, a package name must not be a keyword
; and must not be or start with `aleo1`.
package-name = lowercase-letter *( lowercase-letter / decimal-digit )
*( "-" 1*( lowercase-letter / decimal-digit ) )
; but not a keyword or a boolean literal or aleo1...
; Note that, grammatically, identifiers are also package names.
; They are disambiguated from context, based on the syntactic grammar.
; Annotations have names, which are identifiers immediately preceded by `@`.
annotation-name = "@" identifier
@ -606,7 +593,6 @@ symbol = "!" / "&" / "&&" / "||"
token = keyword
/ identifier
/ atomic-literal
/ package-name
/ annotation-name
/ symbol
@ -1063,21 +1049,21 @@ circuit-declaration = %s"circuit" identifier
; followed by a package path, which may be one of the following:
; a single wildcard;
; an identifier, optionally followed by a local renamer;
; a package name followed by a path, recursively;
; an identifier followed by a path, recursively;
; or a parenthesized list of package paths,
; which are "fan out" of the initial path.
; Note that we allow the last element of the parenthesized list
; to be followed by a comma, for convenience.
; The package path in the import declaration must start with a package name
; The package path in the import declaration must start with an identifier
; (e.g. it cannot be a `*`):
; the rule for import declaration expresses this requirement
; by using an explicit package name before the package path.
; by using an explicit identifier before the package path.
import-declaration = %s"import" package-name "." package-path ";"
import-declaration = %s"import" identifier "." package-path ";"
package-path = "*"
/ identifier [ %s"as" identifier ]
/ package-name "." package-path
/ identifier "." package-path
/ "(" package-path *( "," package-path ) [","] ")"
; A type alias declaration defines an identifier to stand for a type.

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 {}

Some files were not shown because too many files have changed in this diff Show More