diff --git a/Cargo.lock b/Cargo.lock index 0becff807e..f21260fd7c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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.1.1" +version = "3.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d76c22c9b9b215eeb8d016ad3a90417bd13cb24cf8142756e6472445876cab7" +checksum = "5177fac1ab67102d8989464efd043c6ff44191b1557ec1ddd489b4f7e1447e77" 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]] @@ -437,7 +410,7 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57952ca27b5e3606ff4dd79b0020231aaf9d6aa76dc05fd30137538c50bd3ce8" dependencies = [ - "generic-array 0.14.5", + "generic-array", "typenum", ] @@ -469,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]] @@ -480,22 +453,13 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8" -[[package]] -name = "digest" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3d0c8c8752312f9713efd397ff63acb9f85585afbf179282e720e7704954dd5" -dependencies = [ - "generic-array 0.12.4", -] - [[package]] name = "digest" version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2fb860ca6fafa5552fb6d0e816a69c8e49f0908bf524e30a90d97c85892d506" dependencies = [ - "block-buffer 0.10.0", + "block-buffer", "crypto-common", ] @@ -558,42 +522,14 @@ dependencies = [ [[package]] name = "eyre" -version = "0.6.6" +version = "0.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc225d8f637923fe585089fcf03e705c222131232d2c1fb622e84ecf725d0eb8" +checksum = "9289ed2c0440a6536e65119725cf91fc2c6b5e513bfd2e36e1134d7cca6ca12f" dependencies = [ "indenter", "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,9 +1020,7 @@ dependencies = [ "criterion", "indexmap", "leo-errors", - "leo-input", "leo-span", - "pest", "serde", "serde_json", "smallvec", @@ -1153,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.1.1", + "clap 3.1.2", "color-backtrace", "colored", "console", "dirs", - "from-pest", "indexmap", "lazy_static", "leo-compiler", @@ -1230,13 +1121,13 @@ dependencies = [ "lazy_static", "leo-ast", "leo-errors", - "leo-input", "leo-span", "leo-test-framework", "serde", "serde_json", "serde_yaml", "smallvec", + "structopt", "tendril", "tracing", ] @@ -1247,7 +1138,6 @@ version = "1.5.3" dependencies = [ "fxhash", "indexmap", - "pest", "scoped-tls", "serde", "tendril", @@ -1292,12 +1182,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" @@ -1562,12 +1446,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" @@ -1625,53 +1503,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" @@ -1731,7 +1562,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a5aab5be6e4732b473071984b3164dbbfb7a3674d30ea5ff44410b6bcd960c3c" dependencies = [ "difflib", - "itertools 0.10.3", + "itertools", "predicates-core", ] @@ -1767,9 +1598,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", ] @@ -1779,27 +1610,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]] @@ -1811,22 +1633,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]] @@ -2177,9 +1990,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]] @@ -2218,18 +2031,6 @@ 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.2" @@ -2238,7 +2039,7 @@ checksum = "55deaec60f81eefe3cce0dc50bda92d6d8e88f2a27df7c5033b42afeb1ed2676" dependencies = [ "cfg-if 1.0.0", "cpufeatures", - "digest 0.10.3", + "digest", ] [[package]] @@ -2250,15 +2051,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" @@ -2281,9 +2073,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]] @@ -2293,7 +2085,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", @@ -2342,20 +2134,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]] @@ -2364,21 +2145,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]] @@ -2470,9 +2239,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]] @@ -2591,9 +2360,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]] @@ -2684,12 +2453,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" @@ -2732,12 +2495,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" @@ -2799,9 +2556,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", ] @@ -2823,7 +2580,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", ] @@ -2833,9 +2590,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", ] diff --git a/Cargo.toml b/Cargo.toml index 0892fb13f2..29af70de81 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -64,9 +64,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"] diff --git a/compiler/ast/Cargo.toml b/compiler/ast/Cargo.toml index e364b81515..748d65c171 100644 --- a/compiler/ast/Cargo.toml +++ b/compiler/ast/Cargo.toml @@ -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 = "../../leo/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" ] diff --git a/compiler/ast/src/chars/char_value.rs b/compiler/ast/src/chars/char_value.rs index 06391a50fc..37857a3c5d 100644 --- a/compiler/ast/src/chars/char_value.rs +++ b/compiler/ast/src/chars/char_value.rs @@ -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(character: &char, serializer: S) -> Result diff --git a/compiler/ast/src/common/array_dimensions.rs b/compiler/ast/src/common/array_dimensions.rs index 261b78df3a..4b661f703f 100644 --- a/compiler/ast/src/common/array_dimensions.rs +++ b/compiler/ast/src/common/array_dimensions.rs @@ -15,7 +15,6 @@ // along with the Leo library. If not, see . 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> 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 { diff --git a/compiler/ast/src/common/identifier.rs b/compiler/ast/src/common/identifier.rs index 7273012d44..b2f2ba5c61 100644 --- a/compiler/ast/src/common/identifier.rs +++ b/compiler/ast/src/common/identifier.rs @@ -14,7 +14,6 @@ // You should have received a copy of the GNU General Public License // along with the Leo library. If not, see . -use leo_input::common::Identifier as InputIdentifier; use leo_span::{Span, Symbol}; use crate::Node; @@ -68,15 +67,6 @@ impl Identifier { } } -impl<'ast> From> 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) diff --git a/compiler/ast/src/common/positive_number.rs b/compiler/ast/src/common/positive_number.rs index 1ecc719398..a083e45b26 100644 --- a/compiler/ast/src/common/positive_number.rs +++ b/compiler/ast/src/common/positive_number.rs @@ -14,8 +14,6 @@ // You should have received a copy of the GNU General Public License // along with the Leo library. If not, see . -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> 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) diff --git a/compiler/ast/src/groups/group_coordinate.rs b/compiler/ast/src/groups/group_coordinate.rs index a19c88c269..8fb39aee29 100644 --- a/compiler/ast/src/groups/group_coordinate.rs +++ b/compiler/ast/src/groups/group_coordinate.rs @@ -14,10 +14,6 @@ // You should have received a copy of the GNU General Public License // along with the Leo library. If not, see . -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> 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> 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> for GroupCoordinate { - fn from(_sign: InputSignHigh<'ast>) -> Self { - GroupCoordinate::SignHigh - } -} - -impl<'ast> From> for GroupCoordinate { - fn from(_sign: InputSignLow<'ast>) -> Self { - GroupCoordinate::SignLow - } -} - -impl<'ast> From> for GroupCoordinate { - fn from(_sign: InputInferred<'ast>) -> Self { - GroupCoordinate::Inferred - } -} diff --git a/compiler/ast/src/groups/group_value.rs b/compiler/ast/src/groups/group_value.rs index 74e9a34779..567527fd90 100644 --- a/compiler/ast/src/groups/group_value.rs +++ b/compiler/ast/src/groups/group_value.rs @@ -15,9 +15,6 @@ // along with the Leo library. If not, see . 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> 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> 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) diff --git a/compiler/ast/src/input/program_input/main_input.rs b/compiler/ast/src/input/definition.rs similarity index 66% rename from compiler/ast/src/input/program_input/main_input.rs rename to compiler/ast/src/input/definition.rs index f84233bbf9..b98eab8279 100644 --- a/compiler/ast/src/input/program_input/main_input.rs +++ b/compiler/ast/src/input/definition.rs @@ -14,9 +14,15 @@ // You should have received a copy of the GNU General Public License // along with the Leo library. If not, see . -use crate::InputValue; -use leo_input::{definitions::Definition, InputParserError}; +use super::*; +use crate::{Expression, Identifier, Type}; -use indexmap::IndexMap; - -main_input_section!(MainInput); +/// A single definition inside a section in a state or an input file. +/// Definitions should be structured as: `: = ;` +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Definition { + pub type_: Type, + pub name: Identifier, + pub value: Expression, + pub span: Span, +} diff --git a/compiler/ast/src/input/input.rs b/compiler/ast/src/input/input.rs deleted file mode 100644 index e4465300a9..0000000000 --- a/compiler/ast/src/input/input.rs +++ /dev/null @@ -1,139 +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 . - -use crate::{ConstantInput, InputValue, MainInput, ProgramInput, ProgramState, Record, Registers, State, StateLeaf}; -use leo_input::{ - files::{File, TableOrSection}, - InputParserError, -}; -use leo_span::Symbol; - -#[derive(Clone, PartialEq, Eq)] -pub struct Input { - name: String, - program_input: ProgramInput, - program_state: ProgramState, -} - -impl Default for Input { - fn default() -> Self { - Self { - name: "default".to_owned(), - program_input: ProgramInput::new(), - program_state: ProgramState::new(), - } - } -} - -#[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> { - 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> { - 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() - } -} diff --git a/compiler/ast/src/input/parameters/parameter.rs b/compiler/ast/src/input/input_ast.rs similarity index 51% rename from compiler/ast/src/input/parameters/parameter.rs rename to compiler/ast/src/input/input_ast.rs index 321eaa6946..f5c6d9658f 100644 --- a/compiler/ast/src/input/parameters/parameter.rs +++ b/compiler/ast/src/input/input_ast.rs @@ -14,23 +14,26 @@ // You should have received a copy of the GNU General Public License // along with the Leo library. If not, see . -use crate::{Identifier, Type}; -use leo_input::parameters::Parameter as GrammarParameter; -use leo_span::Span; +use super::*; +use leo_errors::AstError; -#[derive(Clone, PartialEq, Eq, Hash)] -pub struct Parameter { - pub variable: Identifier, - pub type_: Type, - pub span: Span, +/// Input data which includes [`ProgramInput`] and [`ProgramState`]. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct Input { + pub program_input: ProgramInput, + pub program_state: ProgramState, } -impl<'ast> From> for Parameter { - fn from(parameter: GrammarParameter<'ast>) -> Self { - Self { - variable: Identifier::from(parameter.variable), - type_: Type::from(parameter.type_), - span: Span::from(parameter.span), - } +/// 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
, +} + +impl Input { + /// Serializes the ast into a JSON string. + pub fn to_json_string(&self) -> Result { + Ok(serde_json::to_string_pretty(&self).map_err(|e| AstError::failed_to_convert_ast_to_json_string(&e))?) } } diff --git a/compiler/ast/src/input/input_value.rs b/compiler/ast/src/input/input_value.rs index 2578931f08..8007a43110 100644 --- a/compiler/ast/src/input/input_value.rs +++ b/compiler/ast/src/input/input_value.rs @@ -14,22 +14,13 @@ // You should have received a copy of the GNU General Public License // along with the Leo library. If not, see . -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), } -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 { - let boolean = boolean.value.parse::()?; - Ok(InputValue::Boolean(boolean)) - } - - fn from_char(input_character: InputCharValue) -> Result { - 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 { - 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 { - 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 { + 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::().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 { - 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::().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 { - // 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 { - // 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 { - 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, - ) -> Result { - 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, - ) -> Result { - // 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(¤t_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 { - 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, 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::() { - 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, -) -> Result<(Vec, 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::>().join(", "); - write!(f, "array [{}]", values) } InputValue::Tuple(ref tuple) => { let values = tuple.iter().map(|x| x.to_string()).collect::>().join(", "); - write!(f, "({})", values) } } diff --git a/compiler/ast/src/input/macros.rs b/compiler/ast/src/input/macros.rs deleted file mode 100644 index 94d5b7454e..0000000000 --- a/compiler/ast/src/input/macros.rs +++ /dev/null @@ -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 . - -/// 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>, - } - - 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) -> 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> { - 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 { - 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>, - } - - #[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) { - self.input.insert(key, value); - } - - /// Parses main input definitions and stores them in `self`. - pub fn parse(&mut self, definitions: Vec) -> 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> { - self.input.get(&name).cloned() - } - - pub fn iter(&self) -> impl Iterator)> { - self.input.iter() - } - } - )*) -} diff --git a/compiler/ast/src/input/mod.rs b/compiler/ast/src/input/mod.rs index e27b113efb..2b9c2bd8f0 100644 --- a/compiler/ast/src/input/mod.rs +++ b/compiler/ast/src/input/mod.rs @@ -14,23 +14,27 @@ // You should have received a copy of the GNU General Public License // along with the Leo library. If not, see . -#![allow(clippy::module_inception)] +pub mod definition; +pub use definition::*; -#[macro_use] -pub mod macros; -pub use macros::*; - -pub mod input; -pub use input::*; +pub mod input_ast; +pub use input_ast::*; 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; diff --git a/compiler/ast/src/input/program_input.rs b/compiler/ast/src/input/program_input.rs new file mode 100644 index 0000000000..96ff686758 --- /dev/null +++ b/compiler/ast/src/input/program_input.rs @@ -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 . + +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 for ProgramInput { + type Error = LeoError; + fn try_from(input: ParsedInputFile) -> Result { + 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, + §ion.span, + ) + .into()) + } + }; + + for definition in section.definitions { + target.insert( + definition.name.name, + InputValue::try_from((definition.type_, definition.value))?, + ); + } + } + + Ok(ProgramInput { + main, + registers, + constants, + }) + } +} diff --git a/compiler/ast/src/input/program_input/mod.rs b/compiler/ast/src/input/program_input/mod.rs deleted file mode 100644 index c672586aa3..0000000000 --- a/compiler/ast/src/input/program_input/mod.rs +++ /dev/null @@ -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 . - -#![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::*; diff --git a/compiler/ast/src/input/program_input/program_input.rs b/compiler/ast/src/input/program_input/program_input.rs deleted file mode 100644 index 99996278ce..0000000000 --- a/compiler/ast/src/input/program_input/program_input.rs +++ /dev/null @@ -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 . - -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> { - self.main.get(name) - } - - #[allow(clippy::ptr_arg)] - pub fn get_constant(&self, name: Symbol) -> Option> { - self.constants.get(name) - } - - /// Returns the runtime register input values - pub fn get_registers(&self) -> &Registers { - &self.registers - } -} diff --git a/compiler/ast/src/input/program_input/registers.rs b/compiler/ast/src/input/program_input/registers.rs deleted file mode 100644 index 7fdd7fc276..0000000000 --- a/compiler/ast/src/input/program_input/registers.rs +++ /dev/null @@ -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 . - -use crate::{InputValue, Parameter}; -use leo_input::{definitions::Definition, InputParserError}; - -use indexmap::IndexMap; - -record_input_section!(Registers); diff --git a/compiler/ast/src/input/program_state.rs b/compiler/ast/src/input/program_state.rs new file mode 100644 index 0000000000..7dbfc5caf8 --- /dev/null +++ b/compiler/ast/src/input/program_state.rs @@ -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 . + +use super::*; + +/// Processed Program state. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct ProgramState { + pub state: Definitions, +} + +impl TryFrom for ProgramState { + type Error = LeoError; + fn try_from(input: ParsedInputFile) -> Result { + 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, + §ion.span, + ) + .into()); + } + } + + Ok(ProgramState { state }) + } +} diff --git a/compiler/ast/src/input/program_state/mod.rs b/compiler/ast/src/input/program_state/mod.rs deleted file mode 100644 index 15b01e33ea..0000000000 --- a/compiler/ast/src/input/program_state/mod.rs +++ /dev/null @@ -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 . - -#![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::*; diff --git a/compiler/ast/src/input/program_state/private_state/mod.rs b/compiler/ast/src/input/program_state/private_state/mod.rs deleted file mode 100644 index f2ae76c725..0000000000 --- a/compiler/ast/src/input/program_state/private_state/mod.rs +++ /dev/null @@ -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 . - -#![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::*; diff --git a/compiler/ast/src/input/program_state/private_state/private_state.rs b/compiler/ast/src/input/program_state/private_state/private_state.rs deleted file mode 100644 index a31f97ea65..0000000000 --- a/compiler/ast/src/input/program_state/private_state/private_state.rs +++ /dev/null @@ -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 . - -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
) -> 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 - } -} diff --git a/compiler/ast/src/input/program_state/private_state/record.rs b/compiler/ast/src/input/program_state/private_state/record.rs deleted file mode 100644 index 1f903d0af6..0000000000 --- a/compiler/ast/src/input/program_state/private_state/record.rs +++ /dev/null @@ -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 . - -use crate::{InputValue, Parameter}; -use leo_input::{definitions::Definition, InputParserError}; - -use indexmap::IndexMap; - -record_input_section!(Record); diff --git a/compiler/ast/src/input/program_state/private_state/state_leaf.rs b/compiler/ast/src/input/program_state/private_state/state_leaf.rs deleted file mode 100644 index d545d79b1c..0000000000 --- a/compiler/ast/src/input/program_state/private_state/state_leaf.rs +++ /dev/null @@ -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 . - -use crate::{InputValue, Parameter}; -use leo_input::{definitions::Definition, InputParserError}; - -use indexmap::IndexMap; - -record_input_section!(StateLeaf); diff --git a/compiler/ast/src/input/program_state/program_state.rs b/compiler/ast/src/input/program_state/program_state.rs deleted file mode 100644 index bce55706a2..0000000000 --- a/compiler/ast/src/input/program_state/program_state.rs +++ /dev/null @@ -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 . - -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() - } -} diff --git a/compiler/ast/src/input/program_state/public_state/mod.rs b/compiler/ast/src/input/program_state/public_state/mod.rs deleted file mode 100644 index f12d7d2e2e..0000000000 --- a/compiler/ast/src/input/program_state/public_state/mod.rs +++ /dev/null @@ -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 . - -#![allow(clippy::module_inception)] - -pub mod public_state; -pub use public_state::*; - -pub mod state; -pub use state::*; diff --git a/compiler/ast/src/input/program_state/public_state/public_state.rs b/compiler/ast/src/input/program_state/public_state/public_state.rs deleted file mode 100644 index e4ede088b5..0000000000 --- a/compiler/ast/src/input/program_state/public_state/public_state.rs +++ /dev/null @@ -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 . - -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
) -> 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 - } -} diff --git a/compiler/ast/src/input/program_state/public_state/state.rs b/compiler/ast/src/input/program_state/public_state/state.rs deleted file mode 100644 index aed560a535..0000000000 --- a/compiler/ast/src/input/program_state/public_state/state.rs +++ /dev/null @@ -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 . - -use crate::{InputValue, Parameter}; -use leo_input::{definitions::Definition, InputParserError}; - -use indexmap::IndexMap; - -record_input_section!(State); diff --git a/compiler/ast/src/input/program_input/constant_input.rs b/compiler/ast/src/input/section.rs similarity index 73% rename from compiler/ast/src/input/program_input/constant_input.rs rename to compiler/ast/src/input/section.rs index 728feffd7e..217d8e7be1 100644 --- a/compiler/ast/src/input/program_input/constant_input.rs +++ b/compiler/ast/src/input/section.rs @@ -14,9 +14,13 @@ // You should have received a copy of the GNU General Public License // along with the Leo library. If not, see . -use crate::InputValue; -use leo_input::{definitions::Definition, InputParserError}; +use super::*; -use indexmap::IndexMap; - -main_input_section!(ConstantInput); +/// 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, + pub span: Span, +} diff --git a/compiler/ast/src/lib.rs b/compiler/ast/src/lib.rs index 409e4e927a..52e817c2ff 100644 --- a/compiler/ast/src/lib.rs +++ b/compiler/ast/src/lib.rs @@ -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, diff --git a/compiler/ast/src/types/integer_type.rs b/compiler/ast/src/types/integer_type.rs index 078d866305..f3dea925cc 100644 --- a/compiler/ast/src/types/integer_type.rs +++ b/compiler/ast/src/types/integer_type.rs @@ -14,10 +14,6 @@ // You should have received a copy of the GNU General Public License // along with the Leo library. If not, see . -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 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 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 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 { diff --git a/compiler/ast/src/types/type_.rs b/compiler/ast/src/types/type_.rs index b1fcf01ba2..bb5c573984 100644 --- a/compiler/ast/src/types/type_.rs +++ b/compiler/ast/src/types/type_.rs @@ -15,9 +15,6 @@ // along with the Leo library. If not, see . 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 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> 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> 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> 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 { diff --git a/compiler/input/LICENSE.md b/compiler/input/LICENSE.md index b95c626e2a..e69de29bb2 100644 --- a/compiler/input/LICENSE.md +++ b/compiler/input/LICENSE.md @@ -1,596 +0,0 @@ -GNU General Public License -========================== - -Version 3, 29 June 2007 - -Copyright © 2007 Free Software Foundation, Inc. <> - -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. - - - Copyright (C) - - 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 . - -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: - - Copyright (C) - 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 -<>. - -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 -<>. diff --git a/compiler/input/README.md b/compiler/input/README.md index ec4927aee7..e69de29bb2 100644 --- a/compiler/input/README.md +++ b/compiler/input/README.md @@ -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) diff --git a/compiler/input/src/ast.rs b/compiler/input/src/ast.rs index 1a5ec0d99e..e69de29bb2 100644 --- a/compiler/input/src/ast.rs +++ b/compiler/input/src/ast.rs @@ -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 . -#![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, Error> { - LanguageParser::parse(Rule::file, input) -} - -pub fn span_into_string(span: Span) -> String { - span.as_str().to_string() -} diff --git a/compiler/input/src/common/eoi.rs b/compiler/input/src/common/eoi.rs index 3eda4b51e9..e69de29bb2 100644 --- a/compiler/input/src/common/eoi.rs +++ b/compiler/input/src/common/eoi.rs @@ -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 . -#![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; diff --git a/compiler/input/src/common/identifier.rs b/compiler/input/src/common/identifier.rs index 606ac424ee..e69de29bb2 100644 --- a/compiler/input/src/common/identifier.rs +++ b/compiler/input/src/common/identifier.rs @@ -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 . - -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) - } -} diff --git a/compiler/input/src/common/line_end.rs b/compiler/input/src/common/line_end.rs index 3cfde86f5e..e69de29bb2 100644 --- a/compiler/input/src/common/line_end.rs +++ b/compiler/input/src/common/line_end.rs @@ -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 . - -use crate::ast::Rule; - -use pest_ast::FromPest; - -#[derive(Clone, Debug, FromPest, PartialEq)] -#[pest_ast(rule(Rule::LINE_END))] -pub struct LineEnd; diff --git a/compiler/input/src/common/mod.rs b/compiler/input/src/common/mod.rs index 6956627b12..e69de29bb2 100644 --- a/compiler/input/src/common/mod.rs +++ b/compiler/input/src/common/mod.rs @@ -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 . - -pub mod eoi; -pub use eoi::*; - -pub mod identifier; -pub use identifier::*; - -pub mod line_end; -pub use line_end::*; diff --git a/compiler/input/src/definitions/definition.rs b/compiler/input/src/definitions/definition.rs index c0c64bbe67..e69de29bb2 100644 --- a/compiler/input/src/definitions/definition.rs +++ b/compiler/input/src/definitions/definition.rs @@ -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 . - -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>, -} diff --git a/compiler/input/src/definitions/mod.rs b/compiler/input/src/definitions/mod.rs index d59ffd9d5d..e69de29bb2 100644 --- a/compiler/input/src/definitions/mod.rs +++ b/compiler/input/src/definitions/mod.rs @@ -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 . - -pub mod definition; -pub use definition::*; diff --git a/compiler/input/src/errors/mod.rs b/compiler/input/src/errors/mod.rs index 9a69051aaa..e69de29bb2 100644 --- a/compiler/input/src/errors/mod.rs +++ b/compiler/input/src/errors/mod.rs @@ -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 . - -pub mod parser; -pub use parser::*; - -pub mod syntax; -pub use syntax::*; diff --git a/compiler/input/src/errors/parser.rs b/compiler/input/src/errors/parser.rs index cca4dc850a..e69de29bb2 100644 --- a/compiler/input/src/errors/parser.rs +++ b/compiler/input/src/errors/parser.rs @@ -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 . - -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 = 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, actual: Vec, 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> for InputParserError { - fn from(error: Error) -> Self { - InputParserError::SyntaxError(InputSyntaxError::from(error)) - } -} diff --git a/compiler/input/src/errors/syntax.rs b/compiler/input/src/errors/syntax.rs index df03534215..e69de29bb2 100644 --- a/compiler/input/src/errors/syntax.rs +++ b/compiler/input/src/errors/syntax.rs @@ -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 . - -use crate::ast::Rule; - -use pest::error::Error; - -#[derive(Debug, Error)] -pub enum SyntaxError { - #[error("aborting due to syntax error")] - Error(Error), -} - -impl From> for SyntaxError { - fn from(mut error: Error) -> 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) - } -} diff --git a/compiler/input/src/expressions/array_initializer_expression.rs b/compiler/input/src/expressions/array_initializer_expression.rs index 7870ac76ba..e69de29bb2 100644 --- a/compiler/input/src/expressions/array_initializer_expression.rs +++ b/compiler/input/src/expressions/array_initializer_expression.rs @@ -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 . - -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>, - pub dimensions: ArrayDimensions<'ast>, - #[pest_ast(outer())] - pub span: Span<'ast>, -} diff --git a/compiler/input/src/expressions/array_inline_expression.rs b/compiler/input/src/expressions/array_inline_expression.rs index 573085bc79..e69de29bb2 100644 --- a/compiler/input/src/expressions/array_inline_expression.rs +++ b/compiler/input/src/expressions/array_inline_expression.rs @@ -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 . - -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>, - #[pest_ast(outer())] - pub span: Span<'ast>, -} diff --git a/compiler/input/src/expressions/expression.rs b/compiler/input/src/expressions/expression.rs index 6f4397800a..e69de29bb2 100644 --- a/compiler/input/src/expressions/expression.rs +++ b/compiler/input/src/expressions/expression.rs @@ -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 . - -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::>() - .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::>() - .join(", "); - - write!(f, "({})", values) - } - Expression::Value(ref expression) => write!(f, "{}", expression), - } - } -} diff --git a/compiler/input/src/expressions/mod.rs b/compiler/input/src/expressions/mod.rs index 18a1505dd5..e69de29bb2 100644 --- a/compiler/input/src/expressions/mod.rs +++ b/compiler/input/src/expressions/mod.rs @@ -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 . - -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::*; diff --git a/compiler/input/src/expressions/string_expression.rs b/compiler/input/src/expressions/string_expression.rs index 8c4b1cc38c..e69de29bb2 100644 --- a/compiler/input/src/expressions/string_expression.rs +++ b/compiler/input/src/expressions/string_expression.rs @@ -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 . - -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>, - #[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, "\"") - } -} diff --git a/compiler/input/src/expressions/tuple_expression.rs b/compiler/input/src/expressions/tuple_expression.rs index 5cbb95dffb..e69de29bb2 100644 --- a/compiler/input/src/expressions/tuple_expression.rs +++ b/compiler/input/src/expressions/tuple_expression.rs @@ -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 . - -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>, - #[pest_ast(outer())] - pub span: Span<'ast>, -} diff --git a/compiler/input/src/files/file.rs b/compiler/input/src/files/file.rs index 61142390b8..e69de29bb2 100644 --- a/compiler/input/src/files/file.rs +++ b/compiler/input/src/files/file.rs @@ -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 . - -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>, - pub eoi: EOI, - #[pest_ast(outer())] - pub span: Span<'ast>, -} diff --git a/compiler/input/src/files/mod.rs b/compiler/input/src/files/mod.rs index 64275480c6..e69de29bb2 100644 --- a/compiler/input/src/files/mod.rs +++ b/compiler/input/src/files/mod.rs @@ -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 . - -pub mod file; -pub use file::*; - -pub mod table_or_section; -pub use table_or_section::*; diff --git a/compiler/input/src/files/table_or_section.rs b/compiler/input/src/files/table_or_section.rs index 93dd31dfc9..e69de29bb2 100644 --- a/compiler/input/src/files/table_or_section.rs +++ b/compiler/input/src/files/table_or_section.rs @@ -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 . - -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>), -} diff --git a/compiler/input/src/leo-input.pest b/compiler/input/src/leo-input.pest index cbfdb02b9b..e69de29bb2 100644 --- a/compiler/input/src/leo-input.pest +++ b/compiler/input/src/leo-input.pest @@ -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 } diff --git a/compiler/input/src/lib.rs b/compiler/input/src/lib.rs index 1b73fdb778..e69de29bb2 100644 --- a/compiler/input/src/lib.rs +++ b/compiler/input/src/lib.rs @@ -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 . - -#![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 { - 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 { - // 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) - } -} diff --git a/compiler/input/src/parameters/mod.rs b/compiler/input/src/parameters/mod.rs index 15f8820a53..e69de29bb2 100644 --- a/compiler/input/src/parameters/mod.rs +++ b/compiler/input/src/parameters/mod.rs @@ -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 . - -pub mod parameter; -pub use parameter::*; diff --git a/compiler/input/src/parameters/parameter.rs b/compiler/input/src/parameters/parameter.rs index 410ef775a9..e69de29bb2 100644 --- a/compiler/input/src/parameters/parameter.rs +++ b/compiler/input/src/parameters/parameter.rs @@ -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 . - -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>, -} diff --git a/compiler/input/src/sections/constants.rs b/compiler/input/src/sections/constants.rs index 5e238f59c1..e69de29bb2 100644 --- a/compiler/input/src/sections/constants.rs +++ b/compiler/input/src/sections/constants.rs @@ -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 . - -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>, -} diff --git a/compiler/input/src/sections/header.rs b/compiler/input/src/sections/header.rs index e0296bf165..e69de29bb2 100644 --- a/compiler/input/src/sections/header.rs +++ b/compiler/input/src/sections/header.rs @@ -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 . - -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), - } - } -} diff --git a/compiler/input/src/sections/main_.rs b/compiler/input/src/sections/main_.rs index 0e8763a638..e69de29bb2 100644 --- a/compiler/input/src/sections/main_.rs +++ b/compiler/input/src/sections/main_.rs @@ -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 . - -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>, -} diff --git a/compiler/input/src/sections/mod.rs b/compiler/input/src/sections/mod.rs index 45025d9cb0..e69de29bb2 100644 --- a/compiler/input/src/sections/mod.rs +++ b/compiler/input/src/sections/mod.rs @@ -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 . - -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::*; diff --git a/compiler/input/src/sections/record.rs b/compiler/input/src/sections/record.rs index 8f431dd040..e69de29bb2 100644 --- a/compiler/input/src/sections/record.rs +++ b/compiler/input/src/sections/record.rs @@ -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 . - -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>, -} diff --git a/compiler/input/src/sections/registers.rs b/compiler/input/src/sections/registers.rs index 0c14fe007f..e69de29bb2 100644 --- a/compiler/input/src/sections/registers.rs +++ b/compiler/input/src/sections/registers.rs @@ -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 . - -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>, -} diff --git a/compiler/input/src/sections/section.rs b/compiler/input/src/sections/section.rs index e53a6331cd..e69de29bb2 100644 --- a/compiler/input/src/sections/section.rs +++ b/compiler/input/src/sections/section.rs @@ -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 . - -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>, - #[pest_ast(outer())] - pub span: Span<'ast>, -} diff --git a/compiler/input/src/sections/state.rs b/compiler/input/src/sections/state.rs index 25b454245f..e69de29bb2 100644 --- a/compiler/input/src/sections/state.rs +++ b/compiler/input/src/sections/state.rs @@ -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 . - -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>, -} diff --git a/compiler/input/src/sections/state_leaf.rs b/compiler/input/src/sections/state_leaf.rs index c44ef71a4e..e69de29bb2 100644 --- a/compiler/input/src/sections/state_leaf.rs +++ b/compiler/input/src/sections/state_leaf.rs @@ -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 . - -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>, -} diff --git a/compiler/input/src/tables/mod.rs b/compiler/input/src/tables/mod.rs index 4edfa339dd..e69de29bb2 100644 --- a/compiler/input/src/tables/mod.rs +++ b/compiler/input/src/tables/mod.rs @@ -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 . - -pub mod private; -pub use private::*; - -pub mod public; -pub use public::*; - -pub mod table; -pub use table::*; - -pub mod visibility; -pub use visibility::*; diff --git a/compiler/input/src/tables/private.rs b/compiler/input/src/tables/private.rs index 3735989fae..e69de29bb2 100644 --- a/compiler/input/src/tables/private.rs +++ b/compiler/input/src/tables/private.rs @@ -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 . - -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()) - } -} diff --git a/compiler/input/src/tables/public.rs b/compiler/input/src/tables/public.rs index aaee16f425..e69de29bb2 100644 --- a/compiler/input/src/tables/public.rs +++ b/compiler/input/src/tables/public.rs @@ -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 . - -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()) - } -} diff --git a/compiler/input/src/tables/table.rs b/compiler/input/src/tables/table.rs index 9ea777cbda..e69de29bb2 100644 --- a/compiler/input/src/tables/table.rs +++ b/compiler/input/src/tables/table.rs @@ -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 . - -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>, - #[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) - } -} diff --git a/compiler/input/src/tables/visibility.rs b/compiler/input/src/tables/visibility.rs index 0abe3828ee..e69de29bb2 100644 --- a/compiler/input/src/tables/visibility.rs +++ b/compiler/input/src/tables/visibility.rs @@ -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 . - -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), - } - } -} diff --git a/compiler/input/src/types/address_type.rs b/compiler/input/src/types/address_type.rs index a3bc14b2ad..e69de29bb2 100644 --- a/compiler/input/src/types/address_type.rs +++ b/compiler/input/src/types/address_type.rs @@ -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 . - -use crate::ast::Rule; - -use pest_ast::FromPest; - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::type_address))] -pub struct AddressType {} diff --git a/compiler/input/src/types/array_dimensions.rs b/compiler/input/src/types/array_dimensions.rs index 776ca0d899..e69de29bb2 100644 --- a/compiler/input/src/types/array_dimensions.rs +++ b/compiler/input/src/types/array_dimensions.rs @@ -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 . - -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>, - #[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::>() - .join(", "); - - write!(f, "{}", string) - } - } - } -} diff --git a/compiler/input/src/types/array_type.rs b/compiler/input/src/types/array_type.rs index 0132228e0d..e69de29bb2 100644 --- a/compiler/input/src/types/array_type.rs +++ b/compiler/input/src/types/array_type.rs @@ -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 . - -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>, - 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) - } -} diff --git a/compiler/input/src/types/boolean_type.rs b/compiler/input/src/types/boolean_type.rs index a482295004..e69de29bb2 100644 --- a/compiler/input/src/types/boolean_type.rs +++ b/compiler/input/src/types/boolean_type.rs @@ -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 . - -use crate::ast::Rule; - -use pest_ast::FromPest; - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::type_boolean))] -pub struct BooleanType {} diff --git a/compiler/input/src/types/char_type.rs b/compiler/input/src/types/char_type.rs index 56e20a68e0..e69de29bb2 100644 --- a/compiler/input/src/types/char_type.rs +++ b/compiler/input/src/types/char_type.rs @@ -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 . - -use crate::ast::Rule; - -use pest_ast::FromPest; - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::type_char))] -pub struct CharType {} diff --git a/compiler/input/src/types/data_type.rs b/compiler/input/src/types/data_type.rs index a0977be017..e69de29bb2 100644 --- a/compiler/input/src/types/data_type.rs +++ b/compiler/input/src/types/data_type.rs @@ -1,47 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{ - ast::Rule, - types::{BooleanType, CharType, FieldType, GroupType, IntegerType}, -}; - -use crate::types::AddressType; -use pest_ast::FromPest; - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::type_data))] -pub enum DataType { - Address(AddressType), - Boolean(BooleanType), - Char(CharType), - Field(FieldType), - Group(GroupType), - Integer(IntegerType), -} - -impl std::fmt::Display for DataType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - match self { - DataType::Address(_) => write!(f, "address"), - DataType::Boolean(_) => write!(f, "bool"), - DataType::Char(_) => write!(f, "char"), - DataType::Field(_) => write!(f, "field"), - DataType::Group(_) => write!(f, "group"), - DataType::Integer(ref integer) => write!(f, "{}", integer), - } - } -} diff --git a/compiler/input/src/types/field_type.rs b/compiler/input/src/types/field_type.rs index 867868394e..e69de29bb2 100644 --- a/compiler/input/src/types/field_type.rs +++ b/compiler/input/src/types/field_type.rs @@ -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 . - -use crate::ast::Rule; - -use pest_ast::FromPest; - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::type_field))] -pub struct FieldType {} diff --git a/compiler/input/src/types/group_type.rs b/compiler/input/src/types/group_type.rs index cc99e58d24..e69de29bb2 100644 --- a/compiler/input/src/types/group_type.rs +++ b/compiler/input/src/types/group_type.rs @@ -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 . - -use crate::ast::Rule; - -use pest_ast::FromPest; - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::type_group))] -pub struct GroupType {} diff --git a/compiler/input/src/types/integer_type.rs b/compiler/input/src/types/integer_type.rs index a66e28d079..e69de29bb2 100644 --- a/compiler/input/src/types/integer_type.rs +++ b/compiler/input/src/types/integer_type.rs @@ -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 . - -use crate::{ - ast::Rule, - types::{SignedIntegerType, UnsignedIntegerType}, -}; - -use pest_ast::FromPest; -use std::fmt; - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::type_integer))] -pub enum IntegerType { - Signed(SignedIntegerType), - Unsigned(UnsignedIntegerType), -} - -impl fmt::Display for IntegerType { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - IntegerType::Signed(integer) => write!(f, "{}", integer), - IntegerType::Unsigned(integer) => write!(f, "{}", integer), - } - } -} diff --git a/compiler/input/src/types/mod.rs b/compiler/input/src/types/mod.rs index 3f8bb810f8..e69de29bb2 100644 --- a/compiler/input/src/types/mod.rs +++ b/compiler/input/src/types/mod.rs @@ -1,54 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -pub mod address_type; -pub use address_type::*; - -pub mod array_dimensions; -pub use array_dimensions::*; - -pub mod array_type; -pub use array_type::*; - -pub mod boolean_type; -pub use boolean_type::*; - -pub mod char_type; -pub use char_type::*; - -pub mod data_type; -pub use data_type::*; - -pub mod field_type; -pub use field_type::*; - -pub mod group_type; -pub use group_type::*; - -pub mod integer_type; -pub use integer_type::*; - -pub mod signed_integer_type; -pub use signed_integer_type::*; - -pub mod tuple_type; -pub use tuple_type::*; - -pub mod type_; -pub use type_::*; - -pub mod unsigned_integer_type; -pub use unsigned_integer_type::*; diff --git a/compiler/input/src/types/signed_integer_type.rs b/compiler/input/src/types/signed_integer_type.rs index eaac0faadc..e69de29bb2 100644 --- a/compiler/input/src/types/signed_integer_type.rs +++ b/compiler/input/src/types/signed_integer_type.rs @@ -1,62 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::ast::Rule; - -use pest_ast::FromPest; -use std::fmt; - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::type_integer_signed))] -pub enum SignedIntegerType { - I8Type(I8Type), - I16Type(I16Type), - I32Type(I32Type), - I64Type(I64Type), - I128Type(I128Type), -} - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::type_i8))] -pub struct I8Type {} - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::type_i16))] -pub struct I16Type {} - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::type_i32))] -pub struct I32Type {} - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::type_i64))] -pub struct I64Type {} - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::type_i128))] -pub struct I128Type {} - -impl fmt::Display for SignedIntegerType { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - SignedIntegerType::I8Type(_) => write!(f, "i8"), - SignedIntegerType::I16Type(_) => write!(f, "i16"), - SignedIntegerType::I32Type(_) => write!(f, "i32"), - SignedIntegerType::I64Type(_) => write!(f, "i64"), - SignedIntegerType::I128Type(_) => write!(f, "i128"), - } - } -} diff --git a/compiler/input/src/types/tuple_type.rs b/compiler/input/src/types/tuple_type.rs index c5086c077a..e69de29bb2 100644 --- a/compiler/input/src/types/tuple_type.rs +++ b/compiler/input/src/types/tuple_type.rs @@ -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 . - -use crate::{ast::Rule, types::Type}; - -use pest::Span; -use pest_ast::FromPest; - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::type_tuple))] -pub struct TupleType<'ast> { - pub types_: Vec>, - #[pest_ast(outer())] - pub span: Span<'ast>, -} - -impl<'ast> std::fmt::Display for TupleType<'ast> { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - let tuple = self.types_.iter().map(|x| x.to_string()).collect::>().join(", "); - - write!(f, "({})", tuple) - } -} diff --git a/compiler/input/src/types/type_.rs b/compiler/input/src/types/type_.rs index 605f919f1d..e69de29bb2 100644 --- a/compiler/input/src/types/type_.rs +++ b/compiler/input/src/types/type_.rs @@ -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 . - -use crate::{ast::Rule, types::*}; - -use pest_ast::FromPest; -use std::fmt; - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::type_))] -pub enum Type<'ast> { - Basic(DataType), - Array(ArrayType<'ast>), - Tuple(TupleType<'ast>), -} - -impl<'ast> fmt::Display for Type<'ast> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - Type::Basic(ref basic) => write!(f, "{}", basic), - Type::Array(ref array) => write!(f, "{}", array), - Type::Tuple(ref tuple) => write!(f, "{}", tuple), - } - } -} diff --git a/compiler/input/src/types/unsigned_integer_type.rs b/compiler/input/src/types/unsigned_integer_type.rs index 819bb372de..e69de29bb2 100644 --- a/compiler/input/src/types/unsigned_integer_type.rs +++ b/compiler/input/src/types/unsigned_integer_type.rs @@ -1,62 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::ast::Rule; - -use pest_ast::FromPest; -use std::fmt; - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::type_integer_unsigned))] -pub enum UnsignedIntegerType { - U8Type(U8Type), - U16Type(U16Type), - U32Type(U32Type), - U64Type(U64Type), - U128Type(U128Type), -} - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::type_u8))] -pub struct U8Type {} - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::type_u16))] -pub struct U16Type {} - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::type_u32))] -pub struct U32Type {} - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::type_u64))] -pub struct U64Type {} - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::type_u128))] -pub struct U128Type {} - -impl fmt::Display for UnsignedIntegerType { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - UnsignedIntegerType::U8Type(_) => write!(f, "u8"), - UnsignedIntegerType::U16Type(_) => write!(f, "u16"), - UnsignedIntegerType::U32Type(_) => write!(f, "u32"), - UnsignedIntegerType::U64Type(_) => write!(f, "u64"), - UnsignedIntegerType::U128Type(_) => write!(f, "u128"), - } - } -} diff --git a/compiler/input/src/values/address.rs b/compiler/input/src/values/address.rs index becdf5f31f..e69de29bb2 100644 --- a/compiler/input/src/values/address.rs +++ b/compiler/input/src/values/address.rs @@ -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 . - -use crate::ast::{span_into_string, Rule}; - -use pest::Span; -use pest_ast::FromPest; -use std::fmt; - -#[derive(Clone, Debug, FromPest, PartialEq)] -#[pest_ast(rule(Rule::address))] -pub struct Address<'ast> { - #[pest_ast(outer(with(span_into_string)))] - pub value: String, - #[pest_ast(outer())] - pub span: Span<'ast>, -} - -impl<'ast> fmt::Display for Address<'ast> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.value) - } -} diff --git a/compiler/input/src/values/address_typed.rs b/compiler/input/src/values/address_typed.rs index 17e678e86c..e69de29bb2 100644 --- a/compiler/input/src/values/address_typed.rs +++ b/compiler/input/src/values/address_typed.rs @@ -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 . - -use crate::{ast::Rule, types::AddressType, values::address::Address}; - -use pest::Span; -use pest_ast::FromPest; -use std::fmt; - -#[derive(Clone, Debug, FromPest, PartialEq)] -#[pest_ast(rule(Rule::address_typed))] -pub struct AddressTyped<'ast> { - pub type_: AddressType, - pub address: Address<'ast>, - #[pest_ast(outer())] - pub span: Span<'ast>, -} - -impl<'ast> fmt::Display for AddressTyped<'ast> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "address({})", self.address) - } -} diff --git a/compiler/input/src/values/address_value.rs b/compiler/input/src/values/address_value.rs index 6134c41278..e69de29bb2 100644 --- a/compiler/input/src/values/address_value.rs +++ b/compiler/input/src/values/address_value.rs @@ -1,49 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{ - ast::Rule, - values::{Address, AddressTyped}, -}; - -use pest::Span; -use pest_ast::FromPest; -use std::fmt; - -#[derive(Clone, Debug, FromPest, PartialEq)] -#[pest_ast(rule(Rule::value_address))] -pub enum AddressValue<'ast> { - Implicit(Address<'ast>), - Explicit(AddressTyped<'ast>), -} - -impl<'ast> AddressValue<'ast> { - pub(crate) fn span(&self) -> &Span<'ast> { - match self { - AddressValue::Implicit(address) => &address.span, - AddressValue::Explicit(address) => &address.span, - } - } -} - -impl<'ast> fmt::Display for AddressValue<'ast> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - AddressValue::Explicit(address) => write!(f, "{}", address), - AddressValue::Implicit(address) => write!(f, "{}", address), - } - } -} diff --git a/compiler/input/src/values/boolean_value.rs b/compiler/input/src/values/boolean_value.rs index 769cddd049..e69de29bb2 100644 --- a/compiler/input/src/values/boolean_value.rs +++ b/compiler/input/src/values/boolean_value.rs @@ -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 . - -use crate::ast::{span_into_string, Rule}; - -use pest::Span; -use pest_ast::FromPest; -use std::fmt; - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::value_boolean))] -pub struct BooleanValue<'ast> { - #[pest_ast(outer(with(span_into_string)))] - pub value: String, - #[pest_ast(outer())] - pub span: Span<'ast>, -} - -impl<'ast> fmt::Display for BooleanValue<'ast> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.value) - } -} diff --git a/compiler/input/src/values/char_types.rs b/compiler/input/src/values/char_types.rs index e6725cf08e..e69de29bb2 100644 --- a/compiler/input/src/values/char_types.rs +++ b/compiler/input/src/values/char_types.rs @@ -1,137 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{ - ast::{span_into_string, Rule}, - errors::InputParserError, -}; - -use pest::Span; -use pest_ast::FromPest; - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::basic_char))] -pub struct BasicChar<'ast> { - #[pest_ast(outer(with(span_into_string)))] - pub value: String, - #[pest_ast(outer())] - pub span: Span<'ast>, -} - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::escaped_char))] -pub struct EscapedChar<'ast> { - #[pest_ast(outer(with(span_into_string)))] - pub value: String, - #[pest_ast(outer())] - pub span: Span<'ast>, -} - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::hex_char))] -pub struct HexChar<'ast> { - #[pest_ast(outer(with(span_into_string)))] - pub value: String, - #[pest_ast(outer())] - pub span: Span<'ast>, -} - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::unicode_char))] -pub struct UnicodeChar<'ast> { - #[pest_ast(outer(with(span_into_string)))] - pub value: String, - #[pest_ast(outer())] - pub span: Span<'ast>, -} - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::char_types))] -pub enum CharTypes<'ast> { - Basic(BasicChar<'ast>), - Escaped(EscapedChar<'ast>), - Hex(HexChar<'ast>), - Unicode(UnicodeChar<'ast>), -} - -impl<'ast> CharTypes<'ast> { - pub fn span(&self) -> &Span<'ast> { - match self { - CharTypes::Basic(value) => &value.span, - CharTypes::Escaped(value) => &value.span, - CharTypes::Hex(value) => &value.span, - CharTypes::Unicode(value) => &value.span, - } - } -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum Char { - Scalar(char), - NonScalar(u32), -} - -impl<'ast> CharTypes<'ast> { - pub fn inner(self) -> Result { - match self { - Self::Basic(character) => { - if let Some(character) = character.value.chars().next() { - return Ok(Char::Scalar(character)); - } - - Err(InputParserError::invalid_char(character.value, &character.span)) - } - Self::Escaped(character) => { - if let Some(inner) = character.value.chars().nth(1) { - return match inner { - '0' => Ok(Char::Scalar(0 as char)), - 't' => Ok(Char::Scalar(9 as char)), - 'n' => Ok(Char::Scalar(10 as char)), - 'r' => Ok(Char::Scalar(13 as char)), - '\"' => Ok(Char::Scalar(34 as char)), - '\'' => Ok(Char::Scalar(39 as char)), - '\\' => Ok(Char::Scalar(92 as char)), - _ => Err(InputParserError::invalid_char(character.value, &character.span)), - }; - } - - Err(InputParserError::invalid_char(character.value, &character.span)) - } - Self::Hex(character) => { - let hex_string_number = character.value[2..character.value.len()].to_string(); - if let Ok(number) = u8::from_str_radix(&hex_string_number, 16) { - if number <= 127 { - return Ok(Char::Scalar(number as char)); - } - } - - Err(InputParserError::invalid_char(character.value, &character.span)) - } - Self::Unicode(character) => { - let unicode_string_number = character.value[3..=character.value.len() - 2].to_string(); - if let Ok(hex) = u32::from_str_radix(&unicode_string_number, 16) { - if let Some(unicode) = std::char::from_u32(hex) { - return Ok(Char::Scalar(unicode)); - } else if hex <= 0x10FFFF { - return Ok(Char::NonScalar(hex)); - } - } - - Err(InputParserError::invalid_char(character.value, &character.span)) - } - } - } -} diff --git a/compiler/input/src/values/char_value.rs b/compiler/input/src/values/char_value.rs index 4389150142..e69de29bb2 100644 --- a/compiler/input/src/values/char_value.rs +++ b/compiler/input/src/values/char_value.rs @@ -1,35 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{ast::Rule, values::CharTypes}; - -use pest::Span; -use pest_ast::FromPest; -use std::fmt; - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::value_char))] -pub struct CharValue<'ast> { - pub value: CharTypes<'ast>, - #[pest_ast(outer())] - pub span: Span<'ast>, -} - -impl<'ast> fmt::Display for CharValue<'ast> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{:?}", self.value) - } -} diff --git a/compiler/input/src/values/field_value.rs b/compiler/input/src/values/field_value.rs index f3bc21ebb4..e69de29bb2 100644 --- a/compiler/input/src/values/field_value.rs +++ b/compiler/input/src/values/field_value.rs @@ -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 . - -use crate::{ast::Rule, types::FieldType, values::NumberValue}; - -use pest::Span; -use pest_ast::FromPest; -use std::fmt; - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::value_field))] -pub struct FieldValue<'ast> { - pub number: NumberValue<'ast>, - pub type_: FieldType, - #[pest_ast(outer())] - pub span: Span<'ast>, -} - -impl<'ast> fmt::Display for FieldValue<'ast> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.number) - } -} diff --git a/compiler/input/src/values/group_coordinate.rs b/compiler/input/src/values/group_coordinate.rs index 70217b85cf..e69de29bb2 100644 --- a/compiler/input/src/values/group_coordinate.rs +++ b/compiler/input/src/values/group_coordinate.rs @@ -1,73 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{ast::Rule, values::NumberValue}; - -use pest::Span; -use pest_ast::FromPest; -use std::fmt; - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::group_coordinate))] -pub enum GroupCoordinate<'ast> { - Number(NumberValue<'ast>), - SignHigh(SignHigh<'ast>), - SignLow(SignLow<'ast>), - Inferred(Inferred<'ast>), -} - -impl<'ast> GroupCoordinate<'ast> { - pub fn span(&self) -> &Span<'ast> { - match self { - GroupCoordinate::Number(number) => number.span(), - GroupCoordinate::SignHigh(sign_high) => &sign_high.span, - GroupCoordinate::SignLow(sign_low) => &sign_low.span, - GroupCoordinate::Inferred(inferred) => &inferred.span, - } - } -} - -impl<'ast> fmt::Display for GroupCoordinate<'ast> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - GroupCoordinate::Number(number) => write!(f, "{}", number), - GroupCoordinate::SignHigh(_) => write!(f, "+"), - GroupCoordinate::SignLow(_) => write!(f, "-"), - GroupCoordinate::Inferred(_) => write!(f, "_"), - } - } -} - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::sign_high))] -pub struct SignHigh<'ast> { - #[pest_ast(outer())] - pub span: Span<'ast>, -} - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::sign_low))] -pub struct SignLow<'ast> { - #[pest_ast(outer())] - pub span: Span<'ast>, -} - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::inferred))] -pub struct Inferred<'ast> { - #[pest_ast(outer())] - pub span: Span<'ast>, -} diff --git a/compiler/input/src/values/group_value.rs b/compiler/input/src/values/group_value.rs index bc4c72eb17..e69de29bb2 100644 --- a/compiler/input/src/values/group_value.rs +++ b/compiler/input/src/values/group_value.rs @@ -1,71 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{ - ast::Rule, - types::GroupType, - values::{GroupCoordinate, NumberValue}, -}; - -use pest::Span; -use pest_ast::FromPest; -use std::fmt; - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::value_group))] -pub struct GroupValue<'ast> { - pub value: GroupRepresentation<'ast>, - pub type_: GroupType, - #[pest_ast(outer())] - pub span: Span<'ast>, -} - -impl<'ast> fmt::Display for GroupValue<'ast> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.value) - } -} - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::group_single_or_tuple))] -pub enum GroupRepresentation<'ast> { - Single(NumberValue<'ast>), - Tuple(GroupTuple<'ast>), -} - -impl<'ast> fmt::Display for GroupRepresentation<'ast> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - GroupRepresentation::Single(number) => write!(f, "{}", number), - GroupRepresentation::Tuple(tuple) => write!(f, "{}", tuple), - } - } -} - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::group_tuple))] -pub struct GroupTuple<'ast> { - pub x: GroupCoordinate<'ast>, - pub y: GroupCoordinate<'ast>, - #[pest_ast(outer())] - pub span: Span<'ast>, -} - -impl<'ast> fmt::Display for GroupTuple<'ast> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "({}, {})", self.x, self.y) - } -} diff --git a/compiler/input/src/values/integer_value.rs b/compiler/input/src/values/integer_value.rs index 9e1004a929..e69de29bb2 100644 --- a/compiler/input/src/values/integer_value.rs +++ b/compiler/input/src/values/integer_value.rs @@ -1,49 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{ - ast::Rule, - values::{SignedIntegerValue, UnsignedIntegerValue}, -}; - -use pest::Span; -use pest_ast::FromPest; -use std::fmt; - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::value_integer))] -pub enum IntegerValue<'ast> { - Signed(SignedIntegerValue<'ast>), - Unsigned(UnsignedIntegerValue<'ast>), -} - -impl<'ast> IntegerValue<'ast> { - pub fn span(&self) -> &Span<'ast> { - match self { - IntegerValue::Signed(integer) => &integer.span, - IntegerValue::Unsigned(integer) => &integer.span, - } - } -} - -impl<'ast> fmt::Display for IntegerValue<'ast> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - IntegerValue::Signed(integer) => write!(f, "{}", integer), - IntegerValue::Unsigned(integer) => write!(f, "{}", integer), - } - } -} diff --git a/compiler/input/src/values/mod.rs b/compiler/input/src/values/mod.rs index 1ba8019df1..e69de29bb2 100644 --- a/compiler/input/src/values/mod.rs +++ b/compiler/input/src/values/mod.rs @@ -1,63 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -pub mod address; -pub use address::*; - -pub mod address_typed; -pub use address_typed::*; - -pub mod address_value; -pub use address_value::*; - -pub mod boolean_value; -pub use boolean_value::*; - -pub mod char_types; -pub use char_types::*; - -pub mod char_value; -pub use char_value::*; - -pub mod field_value; -pub use field_value::*; - -pub mod group_coordinate; -pub use group_coordinate::*; - -pub mod group_value; -pub use group_value::*; - -pub mod integer_value; -pub use integer_value::*; - -pub mod negative_number; -pub use negative_number::*; - -pub mod number_value; -pub use number_value::*; - -pub mod positive_number; -pub use positive_number::*; - -pub mod signed_integer_value; -pub use signed_integer_value::*; - -pub mod value; -pub use value::*; - -pub mod unsigned_integer_value; -pub use unsigned_integer_value::*; diff --git a/compiler/input/src/values/negative_number.rs b/compiler/input/src/values/negative_number.rs index 704580fb9e..e69de29bb2 100644 --- a/compiler/input/src/values/negative_number.rs +++ b/compiler/input/src/values/negative_number.rs @@ -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 . - -use crate::ast::{span_into_string, Rule}; - -use pest::Span; -use pest_ast::FromPest; -use std::fmt; - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::number_negative))] -pub struct NegativeNumber<'ast> { - #[pest_ast(outer(with(span_into_string)))] - pub value: String, - #[pest_ast(outer())] - pub span: Span<'ast>, -} - -impl<'ast> fmt::Display for NegativeNumber<'ast> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.value) - } -} diff --git a/compiler/input/src/values/number_value.rs b/compiler/input/src/values/number_value.rs index 2071dca1a3..e69de29bb2 100644 --- a/compiler/input/src/values/number_value.rs +++ b/compiler/input/src/values/number_value.rs @@ -1,49 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{ - ast::Rule, - values::{NegativeNumber, PositiveNumber}, -}; - -use pest::Span; -use pest_ast::FromPest; -use std::fmt; - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::value_number))] -pub enum NumberValue<'ast> { - Negative(NegativeNumber<'ast>), - Positive(PositiveNumber<'ast>), -} - -impl<'ast> NumberValue<'ast> { - pub fn span(&self) -> &Span<'ast> { - match self { - NumberValue::Negative(number) => &number.span, - NumberValue::Positive(number) => &number.span, - } - } -} - -impl<'ast> fmt::Display for NumberValue<'ast> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - NumberValue::Negative(number) => write!(f, "{}", number), - NumberValue::Positive(number) => write!(f, "{}", number), - } - } -} diff --git a/compiler/input/src/values/positive_number.rs b/compiler/input/src/values/positive_number.rs index 9ccf38cff2..e69de29bb2 100644 --- a/compiler/input/src/values/positive_number.rs +++ b/compiler/input/src/values/positive_number.rs @@ -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 . - -use crate::ast::{span_into_string, Rule}; - -use pest::Span; -use pest_ast::FromPest; -use std::fmt; - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::number_positive))] -pub struct PositiveNumber<'ast> { - #[pest_ast(outer(with(span_into_string)))] - pub value: String, - #[pest_ast(outer())] - pub span: Span<'ast>, -} - -impl<'ast> fmt::Display for PositiveNumber<'ast> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.value) - } -} diff --git a/compiler/input/src/values/signed_integer_value.rs b/compiler/input/src/values/signed_integer_value.rs index acd4301c0e..e69de29bb2 100644 --- a/compiler/input/src/values/signed_integer_value.rs +++ b/compiler/input/src/values/signed_integer_value.rs @@ -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 . - -use crate::{ast::Rule, types::SignedIntegerType, values::NumberValue}; - -use pest::Span; -use pest_ast::FromPest; -use std::fmt; - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::value_integer_signed))] -pub struct SignedIntegerValue<'ast> { - pub number: NumberValue<'ast>, - pub type_: SignedIntegerType, - #[pest_ast(outer())] - pub span: Span<'ast>, -} - -impl<'ast> fmt::Display for SignedIntegerValue<'ast> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.number) - } -} diff --git a/compiler/input/src/values/unsigned_integer_value.rs b/compiler/input/src/values/unsigned_integer_value.rs index 7b0193069c..e69de29bb2 100644 --- a/compiler/input/src/values/unsigned_integer_value.rs +++ b/compiler/input/src/values/unsigned_integer_value.rs @@ -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 . - -use crate::{ast::Rule, types::UnsignedIntegerType, values::PositiveNumber}; - -use pest::Span; -use pest_ast::FromPest; -use std::fmt; - -#[derive(Clone, Debug, FromPest, PartialEq, Eq)] -#[pest_ast(rule(Rule::value_integer_unsigned))] -pub struct UnsignedIntegerValue<'ast> { - pub number: PositiveNumber<'ast>, - pub type_: UnsignedIntegerType, - #[pest_ast(outer())] - pub span: Span<'ast>, -} - -impl<'ast> fmt::Display for UnsignedIntegerValue<'ast> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.number) - } -} diff --git a/compiler/input/src/values/value.rs b/compiler/input/src/values/value.rs index 993d5ee04b..e69de29bb2 100644 --- a/compiler/input/src/values/value.rs +++ b/compiler/input/src/values/value.rs @@ -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 . - -use crate::{ - ast::Rule, - values::{BooleanValue, CharValue, FieldValue, GroupValue, IntegerValue, NumberValue}, -}; - -use crate::values::AddressValue; -use pest::Span; -use pest_ast::FromPest; -use std::fmt; - -#[derive(Clone, Debug, FromPest, PartialEq)] -#[pest_ast(rule(Rule::value))] -pub enum Value<'ast> { - Address(AddressValue<'ast>), - Boolean(BooleanValue<'ast>), - Char(CharValue<'ast>), - Field(FieldValue<'ast>), - Group(GroupValue<'ast>), - Implicit(NumberValue<'ast>), - Integer(IntegerValue<'ast>), -} - -impl<'ast> Value<'ast> { - pub fn span(&self) -> &Span<'ast> { - match self { - Value::Address(value) => value.span(), - Value::Boolean(value) => &value.span, - Value::Char(value) => &value.span, - Value::Field(value) => &value.span, - Value::Group(value) => &value.span, - Value::Implicit(value) => value.span(), - Value::Integer(value) => value.span(), - } - } -} - -impl<'ast> fmt::Display for Value<'ast> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - Value::Address(ref value) => write!(f, "{}", value), - Value::Boolean(ref value) => write!(f, "{}", value), - Value::Char(ref value) => write!(f, "{}", value), - Value::Field(ref value) => write!(f, "{}", value), - Value::Group(ref value) => write!(f, "{}", value), - Value::Implicit(ref value) => write!(f, "{}", value), - Value::Integer(ref value) => write!(f, "{}", value), - } - } -} diff --git a/compiler/parser/Cargo.toml b/compiler/parser/Cargo.toml index 12c844a75e..45ab499c39 100644 --- a/compiler/parser/Cargo.toml +++ b/compiler/parser/Cargo.toml @@ -2,7 +2,7 @@ name = "leo-parser" version = "1.5.3" authors = [ "The Aleo Team " ] -description = "AST generated by pest from the Leo grammar rules" +description = "Leo parser" homepage = "https://aleo.org" repository = "https://github.com/AleoHQ/leo" keywords = [ @@ -34,10 +34,6 @@ version = "1.5.3" path = "../../leo/errors" version = "1.5.3" -[dependencies.leo-input] -path = "../input" -version = "1.5.1" - [dependencies.leo-span] path = "../../leo/span" version = "1.5.3" @@ -72,6 +68,9 @@ features = [ "preserve_order" ] [dev-dependencies.serde_yaml] version = "0.8" +[dev-dependencies.structopt] +version = "0.3" + [features] default = [ ] ci_skip = [ ] diff --git a/compiler/parser/examples/input_parser.rs b/compiler/parser/examples/input_parser.rs new file mode 100644 index 0000000000..6cc6661bcd --- /dev/null +++ b/compiler/parser/examples/input_parser.rs @@ -0,0 +1,74 @@ +// 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 . + +use leo_errors::{emitter::Handler, Result}; +use leo_span::symbol::create_session_if_not_set_then; + +use std::{ + fs, + path::{Path, PathBuf}, +}; +use structopt::StructOpt; + +#[derive(Debug, StructOpt)] +#[structopt( + name = "input parser", + about = "Parse an Input file and save its JSON representation" +)] +struct Opt { + /// Path to the input file. + #[structopt(parse(from_os_str))] + input_path: PathBuf, + + /// Optional path to the output directory. + #[structopt(parse(from_os_str))] + out_dir_path: Option, + + /// Whether to print result to STDOUT. + #[structopt(short, long)] + print_stdout: bool, +} + +fn main() -> Result<(), String> { + let opt = Opt::from_args(); + let input_string = fs::read_to_string(&opt.input_path).expect("failed to open an input file"); + let input_tree = create_session_if_not_set_then(|_| { + Handler::with(|handler| { + let input = + leo_parser::parse_program_inputs(&handler, input_string.clone(), opt.input_path.to_str().unwrap())?; + Ok(input.to_json_string()?) + }) + .map_err(|e| e.to_string()) + })?; + + if opt.print_stdout { + println!("{}", input_tree); + } + + let out_path = if let Some(out_dir) = opt.out_dir_path { + format!( + "{}/{}.json", + out_dir.as_path().display(), + opt.input_path.file_stem().unwrap().to_str().unwrap() + ) + } else { + format!("./{}.json", opt.input_path.file_stem().unwrap().to_str().unwrap()) + }; + + fs::write(Path::new(&out_path), input_tree).expect("failed to write output"); + + Ok(()) +} diff --git a/compiler/parser/examples/parser.rs b/compiler/parser/examples/parser.rs index 1a18f74dd8..3f040aba69 100644 --- a/compiler/parser/examples/parser.rs +++ b/compiler/parser/examples/parser.rs @@ -18,56 +18,58 @@ use leo_ast::Ast; use leo_errors::emitter::Handler; use leo_span::symbol::create_session_if_not_set_then; -use std::{env, fs, path::Path}; +use std::{ + fs, + path::{Path, PathBuf}, +}; +use structopt::StructOpt; -fn to_leo_tree(filepath: &Path) -> Result { - // Loads the Leo code as a string from the given file path. - let program_filepath = filepath.to_path_buf(); - let code = fs::read_to_string(&program_filepath).expect("failed to open input file"); +#[derive(Debug, StructOpt)] +#[structopt(name = "leo parser", about = "Parse Leo AST and store it as a JSON")] +struct Opt { + /// Path to the Leo file. + #[structopt(parse(from_os_str))] + input_path: PathBuf, + + /// Optional path to the output directory. + #[structopt(parse(from_os_str))] + out_dir_path: Option, + + /// Whether to print result to STDOUT. + #[structopt(short, long)] + print_stdout: bool, +} + +fn main() -> Result<(), String> { + let opt = Opt::from_args(); + let code = fs::read_to_string(&opt.input_path).expect("failed to open file"); // Parses the Leo file constructing an ast which is then serialized. - create_session_if_not_set_then(|_| { + let serialized_leo_tree = create_session_if_not_set_then(|_| { Handler::with(|h| { - let ast = leo_parser::parse_ast(&h, filepath.to_str().unwrap(), &code)?; + let ast = leo_parser::parse_ast(&h, opt.input_path.to_str().unwrap(), &code)?; let json = Ast::to_json_string(&ast)?; println!("{}", json); Ok(json) }) .map_err(|b| b.to_string()) - }) -} + })?; -fn main() -> Result<(), String> { - // Parse the command-line arguments as strings. - let cli_arguments = env::args().collect::>(); - - // Check that the correct number of command-line arguments were passed in. - if cli_arguments.len() < 2 || cli_arguments.len() > 3 { - eprintln!("Warning - an invalid number of command-line arguments were provided."); - println!( - "\nCommand-line usage:\n\n\tleo_ast {{PATH/TO/INPUT_FILENAME}}.leo {{PATH/TO/OUTPUT_DIRECTORY (optional)}}\n" - ); - return Ok(()); // Exit innocently + if opt.print_stdout { + println!("{}", serialized_leo_tree); } - // Construct the input filepath. - let input_filepath = Path::new(&cli_arguments[1]); - - // Construct the serialized syntax tree. - let serialized_leo_tree = to_leo_tree(input_filepath)?; - - // Determine the output directory. - let output_directory = match cli_arguments.len() == 3 { - true => format!( + let out_path = if let Some(out_dir) = opt.out_dir_path { + format!( "{}/{}.json", - cli_arguments[2], - input_filepath.file_stem().unwrap().to_str().unwrap() - ), - false => format!("./{}.json", input_filepath.file_stem().unwrap().to_str().unwrap()), + out_dir.as_path().display(), + opt.input_path.file_stem().unwrap().to_str().unwrap() + ) + } else { + format!("./{}.json", opt.input_path.file_stem().unwrap().to_str().unwrap()) }; - // Write the serialized syntax tree to the output directory. - fs::write(Path::new(&output_directory), serialized_leo_tree).expect("failed to write output"); + fs::write(Path::new(&out_path), serialized_leo_tree).expect("failed to write output"); Ok(()) } diff --git a/compiler/parser/src/lib.rs b/compiler/parser/src/lib.rs index 21a1001bde..917a6a1a7a 100644 --- a/compiler/parser/src/lib.rs +++ b/compiler/parser/src/lib.rs @@ -23,14 +23,13 @@ #![doc = include_str!("../README.md")] pub(crate) mod tokenizer; -use leo_input::LeoInputParser; pub use tokenizer::KEYWORD_TOKENS; pub(crate) use tokenizer::*; pub mod parser; pub use parser::*; -use leo_ast::{Ast, Input}; +use leo_ast::{Ast, Input, ProgramInput, ProgramState}; use leo_errors::emitter::Handler; use leo_errors::Result; @@ -42,63 +41,17 @@ pub fn parse_ast, Y: AsRef>(handler: &Handler, path: T, sourc Ok(Ast::new(parser::parse(handler, path.as_ref(), source.as_ref())?)) } -/// Parses program input from from the input file path and state file path -pub fn parse_program_input, Y: AsRef, T2: AsRef, Y2: AsRef>( +/// Parses program inputs from from the input file path and state file path +pub fn parse_program_inputs, Y: AsRef>( + handler: &Handler, input_string: T, input_path: Y, - state_string: T2, - state_path: Y2, ) -> Result { - let input_syntax_tree = LeoInputParser::parse_file(input_string.as_ref()).map_err(|mut e| { - e.set_path( - input_path.as_ref(), - &input_string - .as_ref() - .lines() - .map(|x| x.to_string()) - .collect::>()[..], - ); + let program_input: ProgramInput = + parser::parse_input(handler, input_path.as_ref(), input_string.as_ref())?.try_into()?; - e - })?; - let state_syntax_tree = LeoInputParser::parse_file(state_string.as_ref()).map_err(|mut e| { - e.set_path( - state_path.as_ref(), - &state_string - .as_ref() - .lines() - .map(|x| x.to_string()) - .collect::>()[..], - ); - - e - })?; - - let mut input = Input::new(); - input.parse_input(input_syntax_tree).map_err(|mut e| { - e.set_path( - input_path.as_ref(), - &input_string - .as_ref() - .lines() - .map(|x| x.to_string()) - .collect::>()[..], - ); - - e - })?; - input.parse_state(state_syntax_tree).map_err(|mut e| { - e.set_path( - state_path.as_ref(), - &state_string - .as_ref() - .lines() - .map(|x| x.to_string()) - .collect::>()[..], - ); - - e - })?; - - Ok(input) + Ok(Input { + program_input, + program_state: ProgramState::default(), + }) } diff --git a/compiler/parser/src/parser/expression.rs b/compiler/parser/src/parser/expression.rs index c7d977a490..7fdb919966 100644 --- a/compiler/parser/src/parser/expression.rs +++ b/compiler/parser/src/parser/expression.rs @@ -386,10 +386,10 @@ impl ParserContext<'_> { } /// - /// Returns a [`SpreadOrExpression`] AST node if the next tokens represent an + /// Returns a [`SpreadOrExpression`] AST node if the next tokens represent a /// spread or expression. /// - /// This method should only be called in the context of an array access expression. + /// This method should only be called in the context of an array construction expression. /// pub fn parse_spread_or_expression(&mut self) -> Result { Ok(if self.eat(Token::DotDotDot).is_some() { @@ -416,8 +416,8 @@ impl ParserContext<'_> { } /// - /// Returns an [`Expression`] AST node if the next tokens represent an - /// tuple initialization expression. + /// Returns an [`Expression`] AST node if the next tokens represent a + /// tuple initialization expression or an affine group literal. /// pub fn parse_tuple_expression(&mut self, span: &Span) -> Result { if let Some((left, right, span)) = self.eat_group_partial().transpose()? { diff --git a/compiler/parser/src/parser/file.rs b/compiler/parser/src/parser/file.rs index 59cc7752db..295ec3b650 100644 --- a/compiler/parser/src/parser/file.rs +++ b/compiler/parser/src/parser/file.rs @@ -162,7 +162,7 @@ impl ParserContext<'_> { /// Returns an [`ImportTree`] AST node if the next tokens represent a valid package import /// with accesses. - // Public soely foro writing import parsing tests. + // Public solely for writing import parsing tests. pub fn parse_import_tree(&mut self) -> Result { // Parse the first part of the path. let first_name = self.parse_package_name()?; @@ -216,7 +216,7 @@ impl ParserContext<'_> { } /// Returns a [`CircuitMember`] AST node if the next tokens represent a circuit member variable - /// or circuit member function. + /// or circuit member function or circuit member constant. pub fn parse_circuit_declaration(&mut self) -> Result> { let mut members = Vec::new(); @@ -462,7 +462,7 @@ impl ParserContext<'_> { /// /// Returns an [`(String, DefinitionStatement)`] AST node if the next tokens represent a global - /// const definition statement and assignment. + /// constant declaration. /// pub fn parse_global_const_declaration(&mut self) -> Result<(Vec, DefinitionStatement)> { let statement = self.parse_definition_statement()?; @@ -476,8 +476,7 @@ impl ParserContext<'_> { } /// - /// Returns an [`(String, Alias)`] AST node if the next tokens represent a global - /// const definition statement and assignment. + /// Returns a [`(String, Alias)`] AST node if the next tokens represent a type alias declaration. /// pub fn parse_type_alias(&mut self) -> Result<(Identifier, Alias)> { let start = self.expect(Token::Type)?; diff --git a/compiler/parser/src/parser/input.rs b/compiler/parser/src/parser/input.rs new file mode 100644 index 0000000000..66b81896e0 --- /dev/null +++ b/compiler/parser/src/parser/input.rs @@ -0,0 +1,83 @@ +// 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 . + +use super::*; + +use leo_errors::{ParserError, Result}; + +impl ParserContext<'_> { + /// Returns a [`ParsedInputFile`] struct filled with the data acquired in the file. + pub fn parse_input(&mut self) -> Result { + let mut sections = Vec::new(); + + while self.has_next() { + let token = self.peek()?; + if matches!(token.token, Token::LeftSquare) { + sections.push(self.parse_section()?); + } else { + return Err(ParserError::unexpected_token(token.token.clone(), &token.span).into()); + } + } + + Ok(ParsedInputFile { sections }) + } + + /// Parses particular section in the Input or State file. + /// ` + /// [] + /// <...definition> + /// ` + /// Returns [`Section`]. + pub fn parse_section(&mut self) -> Result
{ + self.expect(Token::LeftSquare)?; + let section = self.expect_ident()?; + self.expect(Token::RightSquare)?; + + let mut definitions = Vec::new(); + + while let Some(SpannedToken { + token: Token::Ident(_), .. + }) = self.peek_option() + { + definitions.push(self.parse_input_definition()?); + } + + Ok(Section { + name: section.name, + span: section.span, + definitions, + }) + } + + /// Parses a single parameter definition: + /// ` : = ;` + /// Returns [`Definition`]. + pub fn parse_input_definition(&mut self) -> Result { + let name = self.expect_ident()?; + self.expect(Token::Colon)?; + let (type_, span) = self.parse_type()?; + self.expect(Token::Assign)?; + let value = self.parse_primary_expression()?; + self.expect(Token::Semicolon)?; + + Ok(Definition { + name, + type_, + value, + span, + }) + } +} diff --git a/compiler/parser/src/parser/mod.rs b/compiler/parser/src/parser/mod.rs index 429d28bbf3..adcd32e72f 100644 --- a/compiler/parser/src/parser/mod.rs +++ b/compiler/parser/src/parser/mod.rs @@ -34,6 +34,7 @@ pub use context::*; pub mod expression; pub mod file; +pub mod input; pub mod statement; pub mod type_; @@ -54,3 +55,10 @@ pub fn parse(handler: &Handler, path: &str, source: &str) -> Result { tokens.parse_program() } + +/// Parses an input file at the given file `path` and `source` code text. +pub fn parse_input(handler: &Handler, path: &str, source: &str) -> Result { + let mut tokens = ParserContext::new(handler, crate::tokenize(path, source.into())?); + + tokens.parse_input() +} diff --git a/compiler/parser/src/test.rs b/compiler/parser/src/test.rs index 2a95cd4654..07d6100094 100644 --- a/compiler/parser/src/test.rs +++ b/compiler/parser/src/test.rs @@ -230,6 +230,18 @@ impl Namespace for SerializeNamespace { } } +struct InputNamespace; + +impl Namespace for InputNamespace { + fn parse_type(&self) -> ParseType { + ParseType::Whole + } + + fn run_test(&self, test: Test) -> Result { + create_session_if_not_set_then(|_| with_handler(tokenize(test)?, |p| p.parse_input()).map(yaml_or_fail)) + } +} + struct TestRunner; impl Runner for TestRunner { @@ -240,6 +252,7 @@ impl Runner for TestRunner { "ParseExpression" => Box::new(ParseExpressionNamespace), "ParseStatement" => Box::new(ParseStatementNamespace), "Serialize" => Box::new(SerializeNamespace), + "Input" => Box::new(InputNamespace), "Token" => Box::new(TokenNamespace), _ => return None, }) diff --git a/compiler/parser/src/tokenizer/lexer.rs b/compiler/parser/src/tokenizer/lexer.rs index 37e899a03f..be73b78d95 100644 --- a/compiler/parser/src/tokenizer/lexer.rs +++ b/compiler/parser/src/tokenizer/lexer.rs @@ -15,6 +15,7 @@ // along with the Leo library. If not, see . use crate::tokenizer::{Char, Token}; +use leo_errors::{ParserError, Result}; use leo_span::{Span, Symbol}; use serde::{Deserialize, Serialize}; @@ -147,13 +148,13 @@ impl Token { /// Returns a tuple: [(integer length, integer token)] if an integer can be eaten, otherwise returns [`None`]. /// An integer can be eaten if its bytes are at the front of the given `input_tendril` string. /// - fn eat_integer(input_tendril: &StrTendril) -> (usize, Option) { + fn eat_integer(input_tendril: &StrTendril) -> Result<(usize, Token)> { if input_tendril.is_empty() { - return (0, None); + return Err(ParserError::lexer_empty_input_tendril().into()); } let input = input_tendril[..].as_bytes(); if !input[0].is_ascii_digit() { - return (0, None); + return Err(ParserError::lexer_eat_integer_leading_zero(String::from_utf8_lossy(input)).into()); } let mut i = 1; let mut is_hex = false; @@ -173,7 +174,7 @@ impl Token { i += 1; } - (i, Some(Token::Int(input_tendril.subtendril(0, i as u32)))) + Ok((i, Token::Int(input_tendril.subtendril(0, i as u32)))) } /// Returns the number of bytes in an emoji via a bit mask. @@ -197,13 +198,13 @@ impl Token { /// Returns a tuple: [(token length, token)] if the next token can be eaten, otherwise returns [`None`]. /// The next token can be eaten if the bytes at the front of the given `input_tendril` string can be scanned into a token. /// - pub(crate) fn eat(input_tendril: StrTendril) -> (usize, Option) { + pub(crate) fn eat(input_tendril: StrTendril) -> Result<(usize, Token)> { if input_tendril.is_empty() { - return (0, None); + return Err(ParserError::lexer_empty_input_tendril().into()); } let input = input_tendril[..].as_bytes(); match input[0] { - x if x.is_ascii_whitespace() => return (1, None), + x if x.is_ascii_whitespace() => return Ok((1, Token::WhiteSpace)), b'"' => { let mut i = 1; let mut len: u8 = 1; @@ -270,7 +271,12 @@ impl Token { unicode = false; string.push(character.into()); } - None => return (0, None), + None => { + return Err(ParserError::lexer_expected_valid_escaped_char( + input_tendril.subtendril(start as u32, len as u32), + ) + .into()) + } } } @@ -282,10 +288,10 @@ impl Token { } if i == input.len() || !end { - return (0, None); + return Err(ParserError::lexer_string_not_closed(String::from_utf8_lossy(&input[0..i])).into()); } - return (i + 1, Some(Token::StringLit(string))); + return Ok((i + 1, Token::StringLit(string))); } b'\'' => { let mut i = 1; @@ -310,7 +316,7 @@ impl Token { if input[i + 1] == b'{' { unicode = true; } else { - return (0, None); + return Err(ParserError::lexer_expected_valid_escaped_char(input[i]).into()); } } else { escaped = true; @@ -323,12 +329,12 @@ impl Token { } if !end { - return (0, None); + return Err(ParserError::lexer_char_not_closed(String::from_utf8_lossy(&input[0..i])).into()); } return match Self::eat_char(input_tendril.subtendril(1, (i - 1) as u32), escaped, hex, unicode) { - Some(character) => (i + 1, Some(Token::CharLit(character))), - None => (0, None), + Some(character) => Ok((i + 1, Token::CharLit(character))), + None => Err(ParserError::lexer_invalid_char(String::from_utf8_lossy(&input[0..i - 1])).into()), }; } x if x.is_ascii_digit() => { @@ -336,119 +342,122 @@ impl Token { } b'!' => { if let Some(len) = eat(input, "!=") { - return (len, Some(Token::NotEq)); + return Ok((len, Token::NotEq)); } - return (1, Some(Token::Not)); + return Ok((1, Token::Not)); } b'?' => { - return (1, Some(Token::Question)); + return Ok((1, Token::Question)); } b'&' => { if let Some(len) = eat(input, "&&") { - return (len, Some(Token::And)); + return Ok((len, Token::And)); } - return (1, Some(Token::Ampersand)); + return Ok((1, Token::Ampersand)); } - b'(' => return (1, Some(Token::LeftParen)), - b')' => return (1, Some(Token::RightParen)), - b'_' => return (1, Some(Token::Underscore)), + b'(' => return Ok((1, Token::LeftParen)), + b')' => return Ok((1, Token::RightParen)), + b'_' => return Ok((1, Token::Underscore)), b'*' => { if let Some(len) = eat(input, "**") { if let Some(inner_len) = eat(&input[len..], "=") { - return (len + inner_len, Some(Token::ExpEq)); + return Ok((len + inner_len, Token::ExpEq)); } - return (len, Some(Token::Exp)); + return Ok((len, Token::Exp)); } else if let Some(len) = eat(input, "*=") { - return (len, Some(Token::MulEq)); + return Ok((len, Token::MulEq)); } - return (1, Some(Token::Mul)); + return Ok((1, Token::Mul)); } b'+' => { if let Some(len) = eat(input, "+=") { - return (len, Some(Token::AddEq)); + return Ok((len, Token::AddEq)); } - return (1, Some(Token::Add)); + return Ok((1, Token::Add)); } - b',' => return (1, Some(Token::Comma)), + b',' => return Ok((1, Token::Comma)), b'-' => { if let Some(len) = eat(input, "->") { - return (len, Some(Token::Arrow)); + return Ok((len, Token::Arrow)); } else if let Some(len) = eat(input, "-=") { - return (len, Some(Token::MinusEq)); + return Ok((len, Token::MinusEq)); } - return (1, Some(Token::Minus)); + return Ok((1, Token::Minus)); } b'.' => { if let Some(len) = eat(input, "...") { - return (len, Some(Token::DotDotDot)); + return Ok((len, Token::DotDotDot)); } else if let Some(len) = eat(input, "..") { - return (len, Some(Token::DotDot)); + return Ok((len, Token::DotDot)); } - return (1, Some(Token::Dot)); + return Ok((1, Token::Dot)); } b'/' => { if eat(input, "//").is_some() { let eol = input.iter().position(|x| *x == b'\n'); let len = if let Some(eol) = eol { eol + 1 } else { input.len() }; - return (len, Some(Token::CommentLine(input_tendril.subtendril(0, len as u32)))); + return Ok((len, Token::CommentLine(input_tendril.subtendril(0, len as u32)))); } else if eat(input, "/*").is_some() { if input.is_empty() { - return (0, None); + return Err(ParserError::lexer_empty_block_comment().into()); } let eol = input.windows(2).skip(2).position(|x| x[0] == b'*' && x[1] == b'/'); let len = if let Some(eol) = eol { eol + 4 } else { - return (0, None); + return Err(ParserError::lexer_block_comment_does_not_close_before_eof( + String::from_utf8_lossy(&input[0..]), + ) + .into()); }; - return (len, Some(Token::CommentBlock(input_tendril.subtendril(0, len as u32)))); + return Ok((len, Token::CommentBlock(input_tendril.subtendril(0, len as u32)))); } else if let Some(len) = eat(input, "/=") { - return (len, Some(Token::DivEq)); + return Ok((len, Token::DivEq)); } - return (1, Some(Token::Div)); + return Ok((1, Token::Div)); } b':' => { if let Some(len) = eat(input, "::") { - return (len, Some(Token::DoubleColon)); + return Ok((len, Token::DoubleColon)); } else { - return (1, Some(Token::Colon)); + return Ok((1, Token::Colon)); } } - b';' => return (1, Some(Token::Semicolon)), + b';' => return Ok((1, Token::Semicolon)), b'<' => { if let Some(len) = eat(input, "<=") { - return (len, Some(Token::LtEq)); + return Ok((len, Token::LtEq)); } - return (1, Some(Token::Lt)); + return Ok((1, Token::Lt)); } b'>' => { if let Some(len) = eat(input, ">=") { - return (len, Some(Token::GtEq)); + return Ok((len, Token::GtEq)); } - return (1, Some(Token::Gt)); + return Ok((1, Token::Gt)); } b'=' => { if let Some(len) = eat(input, "==") { - return (len, Some(Token::Eq)); + return Ok((len, Token::Eq)); } - return (1, Some(Token::Assign)); + return Ok((1, Token::Assign)); } - b'@' => return (1, Some(Token::At)), - b'[' => return (1, Some(Token::LeftSquare)), - b']' => return (1, Some(Token::RightSquare)), - b'{' => return (1, Some(Token::LeftCurly)), - b'}' => return (1, Some(Token::RightCurly)), + b'@' => return Ok((1, Token::At)), + b'[' => return Ok((1, Token::LeftSquare)), + b']' => return Ok((1, Token::RightSquare)), + b'{' => return Ok((1, Token::LeftCurly)), + b'}' => return Ok((1, Token::RightCurly)), b'|' => { if let Some(len) = eat(input, "||") { - return (len, Some(Token::Or)); + return Ok((len, Token::Or)); } } _ => (), } if let Some(ident) = eat_identifier(&input_tendril) { - return ( + return Ok(( ident.len(), - Some(match &*ident { + match &*ident { x if x.starts_with("aleo1") => Token::AddressLit(ident), "address" => Token::Address, "as" => Token::As, @@ -486,11 +495,11 @@ impl Token { "u64" => Token::U64, "u128" => Token::U128, _ => Token::Ident(Symbol::intern(&ident)), - }), - ); + }, + )); } - (0, None) + Err(ParserError::could_not_lex(String::from_utf8_lossy(&input[0..])).into()) } } diff --git a/compiler/parser/src/tokenizer/mod.rs b/compiler/parser/src/tokenizer/mod.rs index 52fded2834..f48b3222e4 100644 --- a/compiler/parser/src/tokenizer/mod.rs +++ b/compiler/parser/src/tokenizer/mod.rs @@ -28,21 +28,55 @@ pub(crate) use self::token::*; pub(crate) mod lexer; pub(crate) use self::lexer::*; -use leo_errors::{LeoError, ParserError}; +use leo_errors::{ParserError, Result}; use leo_span::Span; use tendril::StrTendril; /// Creates a new vector of spanned tokens from a given file path and source code text. -pub(crate) fn tokenize(path: &str, input: StrTendril) -> Result, LeoError> { +pub(crate) fn tokenize(path: &str, input: StrTendril) -> Result> { let path = Arc::new(path.to_string()); let mut tokens = vec![]; let mut index = 0usize; let mut line_no = 1usize; let mut line_start = 0usize; while input.len() > index { - match Token::eat(input.subtendril(index as u32, (input.len() - index) as u32)) { - (token_len, Some(token)) => { + match Token::eat(input.subtendril(index as u32, (input.len() - index) as u32))? { + (token_len, Token::WhiteSpace) => { + if token_len == 0 && index == input.len() { + break; + } else if token_len == 0 { + return Err(ParserError::unexpected_token( + &input[index..].chars().next().unwrap(), + &Span::new( + line_no, + line_no, + index - line_start + 1, + index - line_start + 2, + path, + input.subtendril( + line_start as u32, + input[line_start..].find('\n').unwrap_or_else(|| input.len()) as u32, + ), + ), + ) + .into()); + } + + let bytes = input.as_bytes(); + if bytes[index] == 0x000D && matches!(bytes.get(index + 1), Some(0x000A)) { + // Check carriage return followed by newline. + line_no += 1; + line_start = index + token_len; + index += token_len; + } else if matches!(bytes[index], 0x000A | 0x000D) { + // Check new-line or carriage-return + line_no += 1; + line_start = index + token_len; + } + index += token_len; + } + (token_len, token) => { let mut span = Span::new( line_no, line_no, @@ -79,32 +113,6 @@ pub(crate) fn tokenize(path: &str, input: StrTendril) -> Result { - if token_len == 0 && index == input.len() { - break; - } else if token_len == 0 { - return Err(ParserError::unexpected_token( - &input[index..].chars().next().unwrap(), - &Span::new( - line_no, - line_no, - index - line_start + 1, - index - line_start + 2, - path, - input.subtendril( - line_start as u32, - input[line_start..].find('\n').unwrap_or_else(|| input.len()) as u32, - ), - ), - ) - .into()); - } - if input.as_bytes()[index] == b'\n' { - line_no += 1; - line_start = index + token_len; - } - index += token_len; - } } } Ok(tokens) @@ -214,7 +222,7 @@ mod tests { .unwrap(); let mut output = String::new(); for SpannedToken { token, .. } in tokens.iter() { - output += &format!("{} ", token.to_string()); + output += &format!("{} ", token); } assert_eq!( @@ -229,7 +237,7 @@ mod tests { fn test_spans() { create_session_if_not_set_then(|_| { let raw = r#" - test +ppp test // test test /* test */ diff --git a/compiler/parser/src/tokenizer/token.rs b/compiler/parser/src/tokenizer/token.rs index ce3347beb0..3dca55e1cf 100644 --- a/compiler/parser/src/tokenizer/token.rs +++ b/compiler/parser/src/tokenizer/token.rs @@ -59,6 +59,7 @@ pub enum Token { False, AddressLit(#[serde(with = "leo_span::tendril_json")] StrTendril), CharLit(Char), + WhiteSpace, // Symbols At, @@ -200,6 +201,7 @@ impl Token { Some(match self { Token::Address => sym::address, Token::As => sym::As, + Token::At => sym::At, Token::Bool => sym::bool, Token::Char => sym::char, Token::Circuit => sym::circuit, @@ -258,6 +260,7 @@ impl fmt::Display for Token { False => write!(f, "false"), AddressLit(s) => write!(f, "{}", s), CharLit(s) => write!(f, "{}", s), + WhiteSpace => write!(f, "whitespace"), At => write!(f, "@"), diff --git a/docs/error-guides/ast/empty_string.md b/docs/error-guides/ast/empty_string.md new file mode 100644 index 0000000000..6f013c5ee9 --- /dev/null +++ b/docs/error-guides/ast/empty_string.md @@ -0,0 +1,52 @@ +# An empty string `""` + +## Example + +This error occurs when an empty string literal was specified. + +Erroneous code example: + +```js +function main() { + let empty_string = ""; +} +``` + +The compiler will reject this code with: + +```java +Error: --> main.leo:2:24 + | + 2 | let empty_string = ""; + | ^^ + | + = Cannot constrcut an empty string: it has the type of [char; 0] which is not possible. +``` + +As the error indicates, the type of `""`, the empty string, would be `[char; 0]`. +The type is not, as one might expect in languages like Rust or Java, +a `String` or `str`, where the size is statically unknown. +Rather, string literals in Leo are arrays of `char`s. +So given that `""` is an array type with size `0`, +the Leo compiler will reject the program, as it would have done with e.g...: +```js +function main() { + let empty: [u8; 0] = []; +} +``` + +## Solutions + +You will not be able to use `""`, but all is not lost. +Depending on what you want to achieve in your program, there may be solutions. +For example, if you want to select between two strings, +you can pad the other strings with whitespace to represent emptiness. + +```js +function main() { + let condition = false; + let a_or_empty = condition ? "a" : " "; +} +``` + +Here, `" "` represents the empty string but is of the same type as `"a"`. diff --git a/docs/error-guides/parser/array_tuple_dimensions_empty.md b/docs/error-guides/parser/array_tuple_dimensions_empty.md new file mode 100644 index 0000000000..98b74f38fb --- /dev/null +++ b/docs/error-guides/parser/array_tuple_dimensions_empty.md @@ -0,0 +1,51 @@ +# Empty array dimensions + +## Example + +This error occurs when specifying an empty tuple as the dimensions of an array. + +Erroneous code example: + +```js +function main() { + let foo = [42; ()]; +} +``` + +The compiler will reject this code with, for example...: + +```js +Error [EPAR0370023]: Array dimensions specified as a tuple cannot be empty. + --> test.leo:2:20 + | + 2 | let foo = [42; ()]; + | ^^ +``` + +## Solution + +If you wanted a single dimensional array, you can achieve that by specifying the length like so: + +```js +function main() { + let foo = [42; 4]; +} +``` + +This will give you the array `[42, 42, 42, 42]`. + +If instead you wanted a multi-dimensional array, e.g., a 2 x 3 matrix, you can achieve that with: + +```js +function main() { + let foo = [42; (2, 3)]; +} +``` + +Alternatively, you can use the simple syntax all the way instead: + +```js +function main() { + let foo = [[42; 2]; 3]; +} +``` diff --git a/docs/error-guides/parser/context_annotation.md b/docs/error-guides/parser/context_annotation.md new file mode 100644 index 0000000000..78746b6f82 --- /dev/null +++ b/docs/error-guides/parser/context_annotation.md @@ -0,0 +1,35 @@ +# `@context function` is deprecated + +## Example + +This error occurs when a function is prefixed with `@context`. + +Erroneous code example: + +```js +@context() +function foo() { + // logic... +} +``` + +The compiler will reject this code with, for example...: + +```js +Error [EPAR0370017]: "@context(...)" is deprecated. Did you mean @test annotation? + --> test.leo:1:2 + | + 1 | @context() + | ^^^^^^^ +``` + +## Solution + +The `@context function` syntax is deprecated, but you can use `@test function` instead: + +```js +@test +function foo() { + // logic... +} +``` diff --git a/docs/error-guides/parser/invalid_address_lit.md b/docs/error-guides/parser/invalid_address_lit.md new file mode 100644 index 0000000000..b138965aef --- /dev/null +++ b/docs/error-guides/parser/invalid_address_lit.md @@ -0,0 +1,44 @@ +# Invalid address literal + +## Example + +This error occurs when a syntactically invalid address is specified. + +Erroneous code example: + +```js +function main() { + let addr = aleo1Qnr4dkkvkgfqph0vzc3y6z2eu975wnpz2925ntjccd5cfqxtyu8s7pyjh9; +} +``` + +The compiler will reject this code with, for example...: + +```js +Error [EPAR0370001]: invalid address literal: 'aleo1Qnr4dkkvkgfqph0vzc3y6z2eu975wnpz2925ntjccd5cfqxtyu8s7pyjh9' + --> test.leo:2:16 + | + 2 | let addr = aleo1Qnr4dkkvkgfqph0vzc3y6z2eu975wnpz2925ntjccd5cfqxtyu8s7pyjh9; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +``` + +A valid address literal must start with `aleo1`, +followed by 58 characters any of which can be either a lowercase letter, +or an ASCII digit (`0` to `9`). + +In the example above, the problem is `Q`, an uppercase letter, +and the second character after `aleo1`. + +## Solution + +To fix the issue, we can write...: + +```js +function main() { + let addr = aleo1qnr4dkkvkgfqph0vzc3y6z2eu975wnpz2925ntjccd5cfqxtyu8s7pyjh9; +} +``` + +...and the compiler will accept it. + +Note however that the compiler does not check whether the address is valid on-chain, but merely that the written program follows the rules of the language grammar. diff --git a/docs/error-guides/parser/invalid_assignment_target.md b/docs/error-guides/parser/invalid_assignment_target.md new file mode 100644 index 0000000000..78dffbd689 --- /dev/null +++ b/docs/error-guides/parser/invalid_assignment_target.md @@ -0,0 +1,32 @@ +# Invalid assignment target + +## Example + +This error currently occurs when a `static const` member or a member function +is used as the target of an assignment statement. + +Erroneous code example: + +```js +circuit Foo { + static const static_const: u8 = 0; +} + +function main() { + Foo::static_const = 0; +} +``` + +The compiler will reject this code with, for example...: + +```js +Error [EPAR0370011]: invalid assignment target + --> test.leo:6:5 + | + 6 | Foo::static_const = 0; + | ^^^^^^^^^^^^^^^^^ +``` + +It's not possible to assign to `static const` members or member functions, +so this is not allowed syntax. +The solution is likely to rethink your approach to the problem you are solving. diff --git a/docs/error-guides/parser/invalid_import_list.md b/docs/error-guides/parser/invalid_import_list.md new file mode 100644 index 0000000000..2d73b8e588 --- /dev/null +++ b/docs/error-guides/parser/invalid_import_list.md @@ -0,0 +1,53 @@ +# An empty `import` list + +## Example + +This error occurs when no sub-packages +or items were specified in an import list. + +Erroneous code example: + +```js +import gardening.(); +``` + +The compiler will reject this code with, for example...: + +```js +Error [EPAR0370002]: Cannot import empty list + --> test.leo:1:18 + | + 1 | import gardening.(); + | ^^ +``` + +...as the compiler does not know what to import in `gardening`. + +## Solutions + +There are different solutions to this problems. +Here are 2 of them to consider. + +### Comment out the `import` + +If don't know yet what to import from `gardening`, +comment out the `import` like so: + +```js +// import gardening.(); +``` + +Later, you can come back and specify what to import like below. + +You can also remove the `import` line entirely, +which will have the same effect. + +### Specify items to `import` + +If you know that you'd like to import, for example, +the functions `water_flowers` and `prune`, +you can specify them in the import list like so: + +```js +import gardening.(water_flowers, prune); +``` diff --git a/docs/error-guides/parser/let_mut_statement.md b/docs/error-guides/parser/let_mut_statement.md new file mode 100644 index 0000000000..644a42bd56 --- /dev/null +++ b/docs/error-guides/parser/let_mut_statement.md @@ -0,0 +1,33 @@ +# `let mut` is deprecated + +## Example + +This error occurs when a variable declaration is marked with `mut`. + +Erroneous code example: + +```js +function main() { + let mut x = 0; +} +``` + +The compiler will reject this code with, for example...: + +```js +Error [EPAR0370015]: let mut = ... is deprecated. `let` keyword implies mutabality by default. + --> test.leo:2:5 + | + 2 | let mut x = 0; + | ^^^^^^^ +``` + +## Solution + +As the `mut` modifier is implicitly assumed, the solution is to remove the `mut` modifier: + +```js +function main() { + let x = 0; +} +``` diff --git a/docs/error-guides/parser/member_const_after_fun.md b/docs/error-guides/parser/member_const_after_fun.md new file mode 100644 index 0000000000..397d25ce7b --- /dev/null +++ b/docs/error-guides/parser/member_const_after_fun.md @@ -0,0 +1,37 @@ +# `static const` after circuit functions + +## Example + +This error occurs when `static const` circuit members occur after circuit member functions. + +Erroneous code example: + +```js +circuit Foo { + function bar() {} + + static const baz: bool = true; +} +``` + +The compiler will reject this code with, for example...: + +```js +Error [EPAR0370021]: Member functions must come after member consts. + --> test.leo:4:18 + | + 4 | static const baz: bool = true; + | ^^^^^^^^^^^^^^^^ +``` + +## Solution + +The issue can be solved by moving all `static const` members before circuit member functions...: + +```js +circuit Foo { + static const baz: bool = true; + + function bar() {} +} +``` diff --git a/docs/error-guides/parser/member_const_after_var.md b/docs/error-guides/parser/member_const_after_var.md new file mode 100644 index 0000000000..566d77d713 --- /dev/null +++ b/docs/error-guides/parser/member_const_after_var.md @@ -0,0 +1,37 @@ +# `static const` after normal variables + +## Example + +This error occurs when `static const` circuit members occur after normal member variables. + +Erroneous code example: + +```js +circuit Foo { + bar: u8, + + static const baz: bool = true; +} +``` + +The compiler will reject this code with, for example...: + +```js +Error [EPAR0370020]: Member variables must come after member consts. + --> test.leo:4:18 + | + 4 | static const baz: bool = true; + | ^^^^^^^^^^^^^^^^ +``` + +## Solution + +The issue can be solved by moving all `static const` members before normal member variables...: + +```js +circuit Foo { + static const baz: bool = true; + + bar: u8, +} +``` diff --git a/docs/error-guides/parser/member_var_after_fun.md b/docs/error-guides/parser/member_var_after_fun.md new file mode 100644 index 0000000000..9ed9a0655d --- /dev/null +++ b/docs/error-guides/parser/member_var_after_fun.md @@ -0,0 +1,37 @@ +# Member variables after circuit functions + +## Example + +This error occurs when circuit member variables occur after circuit member functions. + +Erroneous code example: + +```js +circuit Foo { + function bar() {} + + baz: bool; +} +``` + +The compiler will reject this code with, for example...: + +```js +Error [EPAR0370022]: Member functions must come after member variables. + --> test.leo:4:5 + | + 4 | baz: bool; + | ^^^ +``` + +## Solution + +The issue can be solved by moving all member variables before any circuit member functions...: + +```js +circuit Foo { + baz: bool; + + function bar() {} +} +``` diff --git a/docs/error-guides/parser/mixed_commas_and_semicolons.md b/docs/error-guides/parser/mixed_commas_and_semicolons.md new file mode 100644 index 0000000000..ed060dcd47 --- /dev/null +++ b/docs/error-guides/parser/mixed_commas_and_semicolons.md @@ -0,0 +1,48 @@ +# Mixed commas and semicolons in circuit definitions + +## Example + +This error occurs when mixing semicolons, `;`, +and commas, `,` together in the list of member variables in a circuit definition. + +Erroneous code example: + +```js +circuit A { + foo: u8, + bar: u16; +} +``` + +The compiler will reject this code with: + +```js +Error [EPAR0370006]: Cannot mix use of commas and semi-colons for circuit member variable declarations. + --> test.leo:3:13 + | + 3 | bar: u16; + | ^ +``` + +## Solutions + +The solution is simply to consistently use `;` or `,` after each member variable, +and avoid mixing `;` and `,` together. So we could write either...: + +```js +circuit A { + foo: u8, + bar: u16, +} +``` + +...or write...: + +```js +circuit A { + foo: u8; + bar: u16; +} +``` + +...and the compiler would accept it. diff --git a/docs/error-guides/parser/mut_function_input.md b/docs/error-guides/parser/mut_function_input.md new file mode 100644 index 0000000000..c98fc0ef68 --- /dev/null +++ b/docs/error-guides/parser/mut_function_input.md @@ -0,0 +1,37 @@ +# Deprecated `mut` parameter + +## Example + +This error occurs when a function parameter is marked as `mut`. + +Erroneous code example: + +```js +circuit Foo { + function bar(mut x: u8) { + x = 0; + } +} +``` + +The compiler will reject this code with, for example...: + +```js +Error [EPAR0370014]: function func(mut a: u32) { ... } is deprecated. Passed variables are mutable by default. + --> test.leo:2:18 + | + 2 | function bar(mut x: u8) { + | ^^^^^ +``` + +## Solution + +As the `mut` modifier is implicitly assumed, the solution is to remove the `mut` modifier: + +```js +circuit Foo { + function bar(x: u8) { + x = 0; + } +} +``` diff --git a/docs/error-guides/parser/mut_self_parameter.md b/docs/error-guides/parser/mut_self_parameter.md new file mode 100644 index 0000000000..65849c868b --- /dev/null +++ b/docs/error-guides/parser/mut_self_parameter.md @@ -0,0 +1,41 @@ +# Deprecated `mut` parameter + +## Example + +This error occurs when a function parameter is marked as `mut`. + +Erroneous code example: + +```js +circuit Foo { + bar: u8, + + function bar(mut self) { + self.bar = 0; + } +} +``` + +The compiler will reject this code with, for example...: + +```js +Error [EPAR0370019]: `mut self` is no longer accepted. Use `&self` if you would like to pass in a mutable reference to `self` + --> test.leo:4:18 + | + 4 | function bar(mut self) { + | ^^^^^^^^ +``` + +## Solution + +As the `mut` modifier is implicitly assumed, the solution is to remove the `mut` modifier from `self`: + +```js +circuit Foo { + bar: u8, + + function bar(self) { + self.bar = 0; + } +} +``` diff --git a/docs/error-guides/parser/spread_in_array_init.md b/docs/error-guides/parser/spread_in_array_init.md new file mode 100644 index 0000000000..7b966b107d --- /dev/null +++ b/docs/error-guides/parser/spread_in_array_init.md @@ -0,0 +1,43 @@ +# Illegal spread expression in array initializer + +## Example + +This error occurs when a spread expression, e.g., `...foo` occurs in an array initializer. + +Erroneous code example: + +```js +function main() { + let foo = [0, 1]; + let array = [...foo; 3]; +} +``` + +The compiler will reject this code with, for example...: + +```js +Error [EPAR0370010]: illegal spread in array initializer + --> test.leo:3:17 + | + 3 | let array = [...foo; 3]; + | ^^^^^^^ +``` + +## Solution + +The Leo language does not allow `...foo` as the element to repeat +in an array repeat expression like the one above. +This is because `foo` is not an element but rather a full array. +One could imagine that the expression above means `[...foo, ...foo, ...foo]`. +That is, `...foo` repeated as many times as was specified in the array size. +However, that is ambiguous with `[element; 3]` resulting in an array with size `3`. + +To solve the issue, disambiguate your intention. +Most likely, you really wanted `[...foo, ...foo, ...foo]`, so the solution is to write that out...: + +```js +function main() { + let foo = [0, 1]; + let array = [...foo, ...foo, ...foo]; +} +``` diff --git a/docs/error-guides/parser/test_function.md b/docs/error-guides/parser/test_function.md new file mode 100644 index 0000000000..78d022c2da --- /dev/null +++ b/docs/error-guides/parser/test_function.md @@ -0,0 +1,34 @@ +# `test function` is deprecated + +## Example + +This error occurs when a function is prefixed with `test`. + +Erroneous code example: + +```js +test function foo() { + // logic... +} +``` + +The compiler will reject this code with, for example...: + +```js +Error [EPAR0370016]: "test function..." is deprecated. Did you mean @test annotation? + --> test.leo:1:1 + | + 1 | test function foo() { + | ^^^^ +``` + +## Solution + +The `test function` syntax is deprecated, but you can achieve the same result with `@test function`: + +```js +@test +function foo() { + // logic... +} +``` diff --git a/docs/error-guides/parser/unable_to_parse_array_dimensions.md b/docs/error-guides/parser/unable_to_parse_array_dimensions.md new file mode 100644 index 0000000000..92aacd06c8 --- /dev/null +++ b/docs/error-guides/parser/unable_to_parse_array_dimensions.md @@ -0,0 +1,34 @@ +# Unable to parse array dimensions + +## Example + +This error occurs when there is a syntax error in the array dimensions of an array initializer. + +Erroneous code example: + +```js +function main() { + let x = [1; +]; +} +``` + +The compiler will reject this code with, for example...: + +```js +Error [EPAR0370018]: unable to parse array dimensions + --> test.leo:2:13 + | + 2 | let x = [1; +]; + | ^ +``` + +## Solution + +In the case above, the error occurs due to the `+`. +The issue can be resolved by specifying the number of elements desired, e.g., `5`...: + +```js +function main() { + let x = [1; 5]; +} +``` diff --git a/docs/error-guides/parser/unexpected.md b/docs/error-guides/parser/unexpected.md new file mode 100644 index 0000000000..691ffcfd16 --- /dev/null +++ b/docs/error-guides/parser/unexpected.md @@ -0,0 +1,37 @@ +# Expected "x" -- got "y" + +## Example + +This error occurs when a specific token, e.g., `class` was encountered but a different one, +e.g., `circuit` was expected instead. + +Erroneous code example: + +```js +class A {} +``` + +The compiler will reject this code with: + +```js +Error: --> main.leo:1:1 + | + 1 | class A {} + | ^^^^^ + | + = expected 'import', 'circuit', 'function', 'test', '@' -- got 'class' +``` + +## Solutions + +The error message above says that `class` cannot be used at that location, +and also lists a few tokens that are valid. Note that this is context specific, +and depends on what tokens preceded the current token. +Using the list of tokens that are valid, and knowing that `circuit A {}` is valid syntax, +we replace `class` with `circuit`...: + +```js +circuit A {} +``` + +...and the error is now resolved. diff --git a/docs/error-guides/parser/unexpected_eof.md b/docs/error-guides/parser/unexpected_eof.md new file mode 100644 index 0000000000..b1d76f16a5 --- /dev/null +++ b/docs/error-guides/parser/unexpected_eof.md @@ -0,0 +1,49 @@ +# An unexpected end of file + +## Example + +This error occurs when the Leo compiler tries to parse your program +and unexpectedly reaches the end of a `.leo` file. + +Erroneous code example: + +```js +function main() { +``` + +The compiler will reject this code with: + +```js +Error [EPAR0370003]: unexpected EOF + --> test.leo:1:17 + | + 1 | function main() { + | ^ +``` + +## Solutions + +The problem typically occurs when there are unbalanced delimiters, +which we have an instance of above. +More specifically, in the example, +the issue is that there is no `}` to close the opening brace `{`. + +An even simpler variant of this is: + +```js +function main( +``` + +The solution here is to close the opening delimiter, in this case `(`. + +## The general issue + +To illustrate the heart of the problem, consider this invalid file: + +```js +// ↳ main.leo +function +``` + +When parsing the file, the compiler expects something, in this case, +the function's name, but instead, the parser reaches the end of the file. diff --git a/docs/error-guides/parser/unexpected_ident.md b/docs/error-guides/parser/unexpected_ident.md new file mode 100644 index 0000000000..ead09d0dd7 --- /dev/null +++ b/docs/error-guides/parser/unexpected_ident.md @@ -0,0 +1,42 @@ +# Unexpected identifier: expected "x" -- got "y" + +## Example + +This error occurs when a specific *identifier*, e.g., `error` was expected but a different one, +e.g., `fail` was encountered instead. + +Erroneous code example: + +```js +function main() { + console.fail("Houston we have a problem!"); +} +``` + +The compiler will reject this code with: + +```js +Error [EPAR0370007]: unexpected identifier: expected 'assert', 'error', 'log' -- got 'fail' + --> test.leo:2:11 + | + 2 | console.fail("Houston we have a problem!"); + | ^^^^ +``` + +## Solutions + +The error message above says that `fail` cannot be used at that location, +and also lists a few identifiers that are valid. Note that this is context specific, +and depends on what preceded the valid tokens in the location. + +The error message lists identifiers that are valid, e.g., `error`. +Here, since we used `.fail(...)`, we most likely wanted to trigger a compile error, +which `.error(...)` will achieve, so we use that instead...: + +```js +function main() { + console.error("Houston we have a problem!"); +} +``` + +Note that this error currently only occurs when using `console`. diff --git a/docs/error-guides/parser/unexpected_statement.md b/docs/error-guides/parser/unexpected_statement.md new file mode 100644 index 0000000000..c7c03aa9af --- /dev/null +++ b/docs/error-guides/parser/unexpected_statement.md @@ -0,0 +1,42 @@ +# Unexpected statement: expected "x" -- got "y" + +## Example + +This error occurs when a statement, which isn't `if`, follows `else` directly. + +Erroneous code example: + +```js +function main () { + if true { + console.log("It was true."); + } else + console.log("It was false."); +} +``` + +The compiler will reject this code with: + +```js +Error [EPAR0370008]: unexpected statement: expected 'Block or Conditional', got 'console.log("It was false.", );' + --> test.leo:5:9 + | + 5 | console.log("It was false."); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +``` + +## Solutions + +To fix the problem, wrap the statement in a block, so by turning the snippet above into...: + +```js +function main () { + if true { + console.log("It was true."); + } else { + console.log("It was false."); + } +} +``` + +...the error is fixed. diff --git a/docs/error-guides/parser/unexpected_str.md b/docs/error-guides/parser/unexpected_str.md new file mode 100644 index 0000000000..02dfbc08a7 --- /dev/null +++ b/docs/error-guides/parser/unexpected_str.md @@ -0,0 +1,36 @@ +# Expected string "x" -- got "y" + +## Example + +This error occurs when a specific "string" (in reality a token), +was expected but a different one was expected instead. + +Erroneous code example: + +```js +function main () { + let x: [u8; (!)] = [0]; +} +``` + +The compiler will reject this code with: + +```js +Error [EPAR0370009]: unexpected string: expected 'int', got '!' + --> test.leo:2:18 + | + 2 | let x: [u8; (!)] = [0]; + | ^ + +``` + +## Solutions + +The error message "unexpected string" depends on the context. +In the example above, we need to replace `!` with `1`...: + +```js +function main () { + let x: [u8; 1] = [0]; +} +``` diff --git a/docs/error-guides/parser/unexpected_token.md b/docs/error-guides/parser/unexpected_token.md new file mode 100644 index 0000000000..8e06ef2ab5 --- /dev/null +++ b/docs/error-guides/parser/unexpected_token.md @@ -0,0 +1,40 @@ +# An unexpected token + +## Example + +This error occurs when the Leo compiler tries to parse your program. +More specifically, during a phase called 'lexing'. +In this phase, the compiler first takes your code, +consisting of characters, and interprets it as a list of tokens. +These tokens are a sort of *alphabet* internal to Leo. + +Consider the English language. It only has 26 letters in its alphabet. +So there are some letters, e.g., `Γ` from the greek alphabet, +which would not fit if we tried to "tokenize" English. + +Leo, while being a programming language, is similar here. +There are characters or sequences of characters, +that Leo does not understand and cannot lex into tokens. +Since this error occured, that is what has happened. + +Erroneous code example: + +```js +~ +``` + +The compiler will reject this code with: + +```js +Error [EPAR0370000]: ~ + --> test.leo:1:1 + | + 1 | ~ + | ^ +``` + +## Solutions + +What the solution to an unexpected token is depends on what you wanted to achieve. +Most likely, you made a typo somewhere. +For a more complete overview of valid Leo tokens, consult the [Leo grammar](https://github.com/AleoHQ/leo/blob/master/grammar/README.md). diff --git a/docs/error-guides/parser/unexpected_whitespace.md b/docs/error-guides/parser/unexpected_whitespace.md new file mode 100644 index 0000000000..422d21bb98 --- /dev/null +++ b/docs/error-guides/parser/unexpected_whitespace.md @@ -0,0 +1,34 @@ +# Unexpected whitespace + +## Example + +This error occurs when there was unexpected white space when in your program. +Typically, the white space occurs in a literal with a typed suffix. + +Erroneous code example: + +```js +function main() { + let x = 1 u8; +} +``` + +The compiler will reject this code with: + +```js +Error [EPAR0370004]: Unexpected white space between terms 1 and u8 + --> test.leo:2:13 + | + 2 | let x = 1 u8; + | ^ +``` + +## Solutions + +The problem is solved by removing the white space between the literal and its suffix. So given the example above, we can fix it by writing: + +```js +function main() { + let x = 1u8; +} +``` diff --git a/docs/grammar/README.md b/docs/grammar/README.md index 105de2cbe4..9f10032127 100644 --- a/docs/grammar/README.md +++ b/docs/grammar/README.md @@ -1598,7 +1598,7 @@ The latter takes either no argument, or a format string followed by expressions, whose number must match the number of containers `{}` in the format string. Note that the console function names are identifiers, not keywords. -There are three kinds of print commands. +There are two kinds of print commands. ```abnf @@ -1627,7 +1627,7 @@ Go to: _[expression](#user-content-expression)_; ```abnf -print-function = %s"debug" / %s"error" / %s"log" +print-function = %s"error" / %s"log" ``` diff --git a/docs/grammar/abnf-grammar.txt b/docs/grammar/abnf-grammar.txt index af4bd430a1..b5f0993019 100644 --- a/docs/grammar/abnf-grammar.txt +++ b/docs/grammar/abnf-grammar.txt @@ -962,7 +962,7 @@ assignment-statement = expression assignment-operator expression ";" ; or a format string followed by expressions, ; whose number must match the number of containers `{}` in the format string. ; Note that the console function names are identifiers, not keywords. -; There are three kinds of print commands. +; There are two kinds of print commands. console-statement = %s"console" "." console-call ";" @@ -971,7 +971,7 @@ console-call = assert-call assert-call = %s"assert" "(" expression ")" -print-function = %s"debug" / %s"error" / %s"log" +print-function = %s"error" / %s"log" print-arguments = "(" string-literal *( "," expression ) ")" diff --git a/leo/errors/Cargo.toml b/leo/errors/Cargo.toml index e18615f1eb..db0b886495 100644 --- a/leo/errors/Cargo.toml +++ b/leo/errors/Cargo.toml @@ -25,10 +25,6 @@ version = "0.3.62" path = "../span" version = "1.5.3" -[dependencies.leo-input] -path = "../../compiler/input" -version = "1.5.3" - [dependencies.colored] version = "2.0.0" @@ -39,12 +35,9 @@ version = "0.5.1" version = "2.2.0" [dependencies.eyre] -version = "0.6.6" +version = "0.6.7" default-features = false -[dependencies.pest] -version = "2.0" - [dependencies.serde] version = "1.0.133" features = [ "derive", "rc" ] diff --git a/leo/errors/README.md b/leo/errors/README.md index aa15119ea8..edfd180bff 100644 --- a/leo/errors/README.md +++ b/leo/errors/README.md @@ -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 diff --git a/leo/errors/src/input/input_errors.rs b/leo/errors/src/input/input_errors.rs new file mode 100644 index 0000000000..c8ebb79799 --- /dev/null +++ b/leo/errors/src/input/input_errors.rs @@ -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 . + +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::>() + .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, + } +); diff --git a/compiler/ast/src/input/parameters/mod.rs b/leo/errors/src/input/mod.rs similarity index 87% rename from compiler/ast/src/input/parameters/mod.rs rename to leo/errors/src/input/mod.rs index 44b61cc20f..a263dcde02 100644 --- a/compiler/ast/src/input/parameters/mod.rs +++ b/leo/errors/src/input/mod.rs @@ -14,5 +14,6 @@ // You should have received a copy of the GNU General Public License // along with the Leo library. If not, see . -pub mod parameter; -pub use parameter::*; +/// This module contains the Input error definitions. +pub mod input_errors; +pub use self::input_errors::*; diff --git a/leo/errors/src/lib.rs b/leo/errors/src/lib.rs index 73ecd4d342..c76a766a44 100644 --- a/leo/errors/src/lib.rs +++ b/leo/errors/src/lib.rs @@ -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. diff --git a/leo/errors/src/parser/parser_errors.rs b/leo/errors/src/parser/parser_errors.rs index 17757a94ba..15cbb19241 100644 --- a/leo/errors/src/parser/parser_errors.rs +++ b/leo/errors/src/parser/parser_errors.rs @@ -16,7 +16,7 @@ use crate::create_errors; -use std::fmt::Display; +use std::fmt::{Debug, Display}; create_errors!( /// ParserError enum that represents all the errors for the `leo-parser` crate. @@ -223,4 +223,76 @@ create_errors!( msg: "Array dimensions specified as a tuple cannot be empty.", help: None, } + + /// When an empty input tendril was expected but not found. + @backtraced + lexer_empty_input_tendril { + args: (), + msg: "Expected more characters to lex but found none.", + help: None, + } + + /// When an integer is started with a leading zero. + @backtraced + lexer_eat_integer_leading_zero { + args: (input: impl Display), + msg: format!("Tried to eat integer but found a leading zero on {}.", input), + help: None, + } + + /// When an integer is started with a leading zero. + @backtraced + lexer_expected_valid_escaped_char { + args: (input: impl Display), + msg: format!("Expected a valid escape character but found {}.", input), + help: None, + } + + /// When a string is not properly closed. + @backtraced + lexer_string_not_closed { + args: (input: impl Display), + msg: format!("Expected a closed string but found {}.", input), + help: None, + } + + /// When a string is not properly closed. + @backtraced + lexer_char_not_closed { + args: (input: impl Display), + msg: format!("Expected a closed char but found {}.", input), + help: None, + } + + /// When a string is not properly closed. + @backtraced + lexer_invalid_char { + args: (input: impl Display), + msg: format!("Expected valid character but found {}.", input), + help: None, + } + + /// When a block comment is empty. + @backtraced + lexer_empty_block_comment { + args: (), + msg: "Empty block comment.", + help: None, + } + + /// When a block comment is not closed before end of file. + @backtraced + lexer_block_comment_does_not_close_before_eof { + args: (input: impl Display), + msg: format!("Block comment does not close with content: {}.", input), + help: None, + } + + /// When the lexer could not lex some text. + @backtraced + could_not_lex { + args: (input: impl Display), + msg: format!("Could not lex the following content: {}.", input), + help: None, + } ); diff --git a/leo/span/Cargo.toml b/leo/span/Cargo.toml index 8d356c0149..f6b8744bf6 100644 --- a/leo/span/Cargo.toml +++ b/leo/span/Cargo.toml @@ -32,9 +32,5 @@ features = [ "derive", "rc" ] [dependencies.scoped-tls] version = "1.0.0" -[dependencies.pest] -version = "2.0" - [dependencies.tendril] version = "0.4.2" - diff --git a/leo/span/src/span.rs b/leo/span/src/span.rs index 45e9a6da8d..7ad057be8e 100644 --- a/leo/span/src/span.rs +++ b/leo/span/src/span.rs @@ -18,7 +18,6 @@ use std::{fmt, sync::Arc, usize}; -use pest::Span as PestSpan; use serde::ser::{Serialize, SerializeStruct, Serializer}; use serde::Deserialize; use tendril::StrTendril; @@ -110,23 +109,6 @@ impl fmt::Display for Span { } } -/// Conversion from a pest span where the leo-input library uses these. -impl<'ast> From> for Span { - fn from(span: PestSpan) -> Self { - let start = span.start_pos().line_col(); - let end = span.end_pos().line_col(); - - Span::new( - start.0, - end.0, - start.1, - end.1, - Arc::new(String::new()), - span.as_str().into(), - ) - } -} - impl std::ops::Add for &Span { type Output = Span; diff --git a/leo/span/src/symbol.rs b/leo/span/src/symbol.rs index 3e99ae8674..0c7f0068e1 100644 --- a/leo/span/src/symbol.rs +++ b/leo/span/src/symbol.rs @@ -101,15 +101,17 @@ macro_rules! symbols { symbols! { address, AlwaysConst, - Ampersand: "@", + Ampersand: "&", array, As: "as", assert, + At: "@", bool, char, circuit, Class: "class", context, + constants, CoreFunction, console, Const: "const", @@ -160,6 +162,9 @@ symbols! { record, state, state_leaf, + + public, + private, } /// An interned string. diff --git a/tests/expectations/parser/parser/expression/literal/char_fail.leo.out b/tests/expectations/parser/parser/expression/literal/char_fail.leo.out index 46390f4fb9..4642d0114d 100644 --- a/tests/expectations/parser/parser/expression/literal/char_fail.leo.out +++ b/tests/expectations/parser/parser/expression/literal/char_fail.leo.out @@ -2,38 +2,38 @@ namespace: Token expectation: Fail outputs: - - "Error [EPAR0370000]: '\n --> test:1:1\n |\n 1 | '\\'\n | ^" - - "Error [EPAR0370000]: '\n --> test:1:1\n |\n 1 | 'a\n | ^" - - "Error [EPAR0370000]: '\n --> test:1:1\n |\n 1 | ''\n | ^" - - "Error [EPAR0370000]: '\n --> test:1:1\n |\n 1 | '\\x9A'\n | ^" - - "Error [EPAR0370000]: '\n --> test:1:1\n |\n 1 | '\\x7'\n | ^" - - "Error [EPAR0370000]: '\n --> test:1:1\n |\n 1 | '\\x7g'\n | ^" - - "Error [EPAR0370000]: '\n --> test:1:1\n |\n 1 | '\\xz'\n | ^" - - "Error [EPAR0370000]: '\n --> test:1:1\n |\n 1 | '\\x80'\n | ^" - - "Error [EPAR0370000]: '\n --> test:1:1\n |\n 1 | '\\xc1'\n | ^" - - "Error [EPAR0370000]: '\n --> test:1:1\n |\n 1 | '\\xc2'\n | ^" - - "Error [EPAR0370000]: '\n --> test:1:1\n |\n 1 | '\\xDF'\n | ^" - - "Error [EPAR0370000]: '\n --> test:1:1\n |\n 1 | '\\xC0'\n | ^" - - "Error [EPAR0370000]: '\n --> test:1:1\n |\n 1 | '\\xe0'\n | ^" - - "Error [EPAR0370000]: '\n --> test:1:1\n |\n 1 | '\\x9f'\n | ^" - - "Error [EPAR0370000]: '\n --> test:1:1\n |\n 1 | 'abcdefg'\n | ^" - - "Error [EPAR0370000]: '\n --> test:1:1\n |\n 1 | '\\t\\t'\n | ^" - - "Error [EPAR0370000]: '\n --> test:1:1\n |\n 1 | '\\a'\n | ^" - - "Error [EPAR0370000]: '\n --> test:1:1\n |\n 1 | '\\z'\n | ^" - - "Error [EPAR0370000]: '\n --> test:1:1\n |\n 1 | '\\A'\n | ^" - - "Error [EPAR0370000]: '\n --> test:1:1\n |\n 1 | '\\Z'\n | ^" - - "Error [EPAR0370000]: '\n --> test:1:1\n |\n 1 | '\\1'\n | ^" - - "Error [EPAR0370000]: '\n --> test:1:1\n |\n 1 | '\\9'\n | ^" - - "Error [EPAR0370000]: '\n --> test:1:1\n |\n 1 | '\\*'\n | ^" - - "Error [EPAR0370000]: '\n --> test:1:1\n |\n 1 | '\\x'\n | ^" - - "Error [EPAR0370000]: '\n --> test:1:1\n |\n 1 | '\\u'\n | ^" - - "Error [EPAR0370000]: '\n --> test:1:1\n |\n 1 | '\\u{bbbbb}\\u{aaaa}'\n | ^" - - "Error [EPAR0370000]: '\n --> test:1:1\n |\n 1 | '\\uz'\n | ^" - - "Error [EPAR0370000]: '\n --> test:1:1\n |\n 1 | '\\u1'\n | ^" - - "Error [EPAR0370000]: '\n --> test:1:1\n |\n 1 | '\\u123'\n | ^" - - "Error [EPAR0370000]: '\n --> test:1:1\n |\n 1 | '\\u{2764z'\n | ^" - - "Error [EPAR0370000]: '\n --> test:1:1\n |\n 1 | '\\u{276g}'\n | ^" - - "Error [EPAR0370000]: '\n --> test:1:1\n |\n 1 | '\\u00000000'\n | ^" - - "Error [EPAR0370000]: '\n --> test:1:1\n |\n 1 | '\\u01000000'\n | ^" - - "Error [EPAR0370000]: '\n --> test:1:1\n |\n 1 | '\\u9999999'\n | ^" - - "Error [EPAR0370000]: '\n --> test:1:1\n |\n 1 | '😭😂😘'\n | ^" + - "Error [EPAR0370028]: Expected a closed char but found '\\'." + - "Error [EPAR0370028]: Expected a closed char but found 'a." + - "Error [EPAR0370029]: Expected valid character but found ." + - "Error [EPAR0370029]: Expected valid character but found '\\x9." + - "Error [EPAR0370029]: Expected valid character but found '\\x." + - "Error [EPAR0370029]: Expected valid character but found '\\x7." + - "Error [EPAR0370029]: Expected valid character but found '\\x." + - "Error [EPAR0370029]: Expected valid character but found '\\x8." + - "Error [EPAR0370029]: Expected valid character but found '\\xc." + - "Error [EPAR0370029]: Expected valid character but found '\\xc." + - "Error [EPAR0370029]: Expected valid character but found '\\xD." + - "Error [EPAR0370029]: Expected valid character but found '\\xC." + - "Error [EPAR0370029]: Expected valid character but found '\\xe." + - "Error [EPAR0370029]: Expected valid character but found '\\x9." + - "Error [EPAR0370029]: Expected valid character but found 'abcdef." + - "Error [EPAR0370029]: Expected valid character but found '\\t\\." + - "Error [EPAR0370029]: Expected valid character but found '\\." + - "Error [EPAR0370029]: Expected valid character but found '\\." + - "Error [EPAR0370029]: Expected valid character but found '\\." + - "Error [EPAR0370029]: Expected valid character but found '\\." + - "Error [EPAR0370029]: Expected valid character but found '\\." + - "Error [EPAR0370029]: Expected valid character but found '\\." + - "Error [EPAR0370029]: Expected valid character but found '\\." + - "Error [EPAR0370029]: Expected valid character but found '\\." + - "Error [EPAR0370026]: Expected a valid escape character but found 117." + - "Error [EPAR0370029]: Expected valid character but found '\\u{bbbbb}\\u{aaaa." + - "Error [EPAR0370026]: Expected a valid escape character but found 117." + - "Error [EPAR0370026]: Expected a valid escape character but found 117." + - "Error [EPAR0370026]: Expected a valid escape character but found 117." + - "Error [EPAR0370029]: Expected valid character but found '\\u{2764." + - "Error [EPAR0370029]: Expected valid character but found '\\u{276g." + - "Error [EPAR0370026]: Expected a valid escape character but found 117." + - "Error [EPAR0370026]: Expected a valid escape character but found 117." + - "Error [EPAR0370026]: Expected a valid escape character but found 117." + - "Error [EPAR0370029]: Expected valid character but found '😭😂�." diff --git a/tests/expectations/parser/parser/expression/literal/string_fail.leo.out b/tests/expectations/parser/parser/expression/literal/string_fail.leo.out index 4d8c97fc71..2b1fcd8d31 100644 --- a/tests/expectations/parser/parser/expression/literal/string_fail.leo.out +++ b/tests/expectations/parser/parser/expression/literal/string_fail.leo.out @@ -2,10 +2,10 @@ namespace: Token expectation: Fail outputs: - - "Error [EPAR0370000]: \"\n --> test:1:1\n |\n 1 | \"Hello world!\n | ^" - - "Error [EPAR0370000]: \"\n --> test:1:1\n |\n 1 | \"\\\"\n | ^" - - "Error [EPAR0370000]: \"\n --> test:1:1\n |\n 1 | \"\\l\"\n | ^" - - "Error [EPAR0370000]: \"\n --> test:1:1\n |\n 1 | \"\\uaaa\"\n | ^" - - "Error [EPAR0370000]: \"\n --> test:1:1\n |\n 1 | \"\\u\"\n | ^" - - "Error [EPAR0370000]: \"\n --> test:1:1\n |\n 1 | \"\\xFF\"\n | ^" - - "Error [EPAR0370000]: \"\n --> test:1:1\n |\n 1 | \"\\x\"\n | ^" + - "Error [EPAR0370027]: Expected a closed string but found \"Hello world!." + - "Error [EPAR0370027]: Expected a closed string but found \"\\\"." + - "Error [EPAR0370026]: Expected a valid escape character but found \\l." + - "Error [EPAR0370027]: Expected a closed string but found \"\\uaaa\"." + - "Error [EPAR0370027]: Expected a closed string but found \"\\u\"." + - "Error [EPAR0370026]: Expected a valid escape character but found \\xFF." + - "Error [EPAR0370027]: Expected a closed string but found \"\\x\"." diff --git a/tests/expectations/parser/parser/inputs/input_success.leo.out b/tests/expectations/parser/parser/inputs/input_success.leo.out new file mode 100644 index 0000000000..6fde85fcfe --- /dev/null +++ b/tests/expectations/parser/parser/inputs/input_success.leo.out @@ -0,0 +1,764 @@ +--- +namespace: Input +expectation: Pass +outputs: + - sections: + - name: main + definitions: + - type_: Boolean + name: "{\"name\":\"a\",\"span\":\"{\\\"line_start\\\":4,\\\"line_stop\\\":4,\\\"col_start\\\":1,\\\"col_stop\\\":2,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"a: bool = true; \\\"}\"}" + value: + Value: + Boolean: + - "true" + - span: + line_start: 4 + line_stop: 4 + col_start: 12 + col_stop: 16 + path: "" + content: "a: bool = true; " + span: + line_start: 4 + line_stop: 4 + col_start: 4 + col_stop: 8 + path: "" + content: "a: bool = true; " + - type_: + IntegerType: U8 + name: "{\"name\":\"b\",\"span\":\"{\\\"line_start\\\":5,\\\"line_stop\\\":5,\\\"col_start\\\":1,\\\"col_stop\\\":2,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"b: u8 = 2; \\\"}\"}" + value: + Value: + Implicit: + - "2" + - span: + line_start: 5 + line_stop: 5 + col_start: 12 + col_stop: 13 + path: "" + content: "b: u8 = 2; " + span: + line_start: 5 + line_stop: 5 + col_start: 4 + col_stop: 6 + path: "" + content: "b: u8 = 2; " + - type_: Field + name: "{\"name\":\"c\",\"span\":\"{\\\"line_start\\\":6,\\\"line_stop\\\":6,\\\"col_start\\\":1,\\\"col_stop\\\":2,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"c: field = 0; \\\"}\"}" + value: + Value: + Implicit: + - "0" + - span: + line_start: 6 + line_stop: 6 + col_start: 12 + col_stop: 13 + path: "" + content: "c: field = 0; " + span: + line_start: 6 + line_stop: 6 + col_start: 4 + col_stop: 9 + path: "" + content: "c: field = 0; " + - type_: Group + name: "{\"name\":\"d\",\"span\":\"{\\\"line_start\\\":7,\\\"line_stop\\\":7,\\\"col_start\\\":1,\\\"col_stop\\\":2,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"d: group = (0, 1)group; \\\"}\"}" + value: + Value: + Group: + Tuple: + x: + Number: + - "0" + - span: + line_start: 7 + line_stop: 7 + col_start: 13 + col_stop: 14 + path: "" + content: "d: group = (0, 1)group; " + y: + Number: + - "1" + - span: + line_start: 7 + line_stop: 7 + col_start: 16 + col_stop: 17 + path: "" + content: "d: group = (0, 1)group; " + span: + line_start: 7 + line_stop: 7 + col_start: 13 + col_stop: 23 + path: "" + content: "d: group = (0, 1)group; " + span: + line_start: 7 + line_stop: 7 + col_start: 4 + col_stop: 9 + path: "" + content: "d: group = (0, 1)group; " + - type_: Address + name: "{\"name\":\"e\",\"span\":\"{\\\"line_start\\\":8,\\\"line_stop\\\":8,\\\"col_start\\\":1,\\\"col_stop\\\":2,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"e: address = aleo1qnr4dkkvkgfqph0vzc3y6z2eu975wnpz2925ntjccd5cfqxtyu8sta57j8;\\\"}\"}" + value: + Value: + Address: + - aleo1qnr4dkkvkgfqph0vzc3y6z2eu975wnpz2925ntjccd5cfqxtyu8sta57j8 + - span: + line_start: 8 + line_stop: 8 + col_start: 14 + col_stop: 77 + path: "" + content: "e: address = aleo1qnr4dkkvkgfqph0vzc3y6z2eu975wnpz2925ntjccd5cfqxtyu8sta57j8;" + span: + line_start: 8 + line_stop: 8 + col_start: 4 + col_stop: 11 + path: "" + content: "e: address = aleo1qnr4dkkvkgfqph0vzc3y6z2eu975wnpz2925ntjccd5cfqxtyu8sta57j8;" + - type_: + Array: + - IntegerType: U8 + - - value: "32" + name: "{\"name\":\"f\",\"span\":\"{\\\"line_start\\\":9,\\\"line_stop\\\":9,\\\"col_start\\\":1,\\\"col_stop\\\":2,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"f: [u8; 32] = [0; 32]; \\\"}\"}" + value: + ArrayInit: + element: + Value: + Implicit: + - "0" + - span: + line_start: 9 + line_stop: 9 + col_start: 16 + col_stop: 17 + path: "" + content: "f: [u8; 32] = [0; 32]; " + dimensions: + - value: "32" + span: + line_start: 9 + line_stop: 9 + col_start: 15 + col_stop: 22 + path: "" + content: "f: [u8; 32] = [0; 32]; " + span: + line_start: 9 + line_stop: 9 + col_start: 4 + col_stop: 12 + path: "" + content: "f: [u8; 32] = [0; 32]; " + - type_: + Array: + - Array: + - IntegerType: U8 + - - value: "2" + - - value: "3" + name: "{\"name\":\"g\",\"span\":\"{\\\"line_start\\\":10,\\\"line_stop\\\":10,\\\"col_start\\\":1,\\\"col_stop\\\":2,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"g: [[u8; 2]; 3] = [[0; 2]; 3]; \\\"}\"}" + value: + ArrayInit: + element: + ArrayInit: + element: + Value: + Implicit: + - "0" + - span: + line_start: 10 + line_stop: 10 + col_start: 21 + col_stop: 22 + path: "" + content: "g: [[u8; 2]; 3] = [[0; 2]; 3]; " + dimensions: + - value: "2" + span: + line_start: 10 + line_stop: 10 + col_start: 20 + col_stop: 26 + path: "" + content: "g: [[u8; 2]; 3] = [[0; 2]; 3]; " + dimensions: + - value: "3" + span: + line_start: 10 + line_stop: 10 + col_start: 19 + col_stop: 30 + path: "" + content: "g: [[u8; 2]; 3] = [[0; 2]; 3]; " + span: + line_start: 10 + line_stop: 10 + col_start: 4 + col_stop: 16 + path: "" + content: "g: [[u8; 2]; 3] = [[0; 2]; 3]; " + - type_: + Tuple: + - Boolean + - Boolean + name: "{\"name\":\"h\",\"span\":\"{\\\"line_start\\\":11,\\\"line_stop\\\":11,\\\"col_start\\\":1,\\\"col_stop\\\":2,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"h: (bool, bool) = (true, false); \\\"}\"}" + value: + TupleInit: + elements: + - Value: + Boolean: + - "true" + - span: + line_start: 11 + line_stop: 11 + col_start: 20 + col_stop: 24 + path: "" + content: "h: (bool, bool) = (true, false); " + - Value: + Boolean: + - "false" + - span: + line_start: 11 + line_stop: 11 + col_start: 26 + col_stop: 31 + path: "" + content: "h: (bool, bool) = (true, false); " + span: + line_start: 11 + line_stop: 11 + col_start: 19 + col_stop: 32 + path: "" + content: "h: (bool, bool) = (true, false); " + span: + line_start: 11 + line_stop: 11 + col_start: 4 + col_stop: 16 + path: "" + content: "h: (bool, bool) = (true, false); " + span: + line_start: 3 + line_stop: 3 + col_start: 2 + col_stop: 6 + path: "" + content: "[main]" + - name: registers + definitions: + - type_: Boolean + name: "{\"name\":\"r0\",\"span\":\"{\\\"line_start\\\":14,\\\"line_stop\\\":14,\\\"col_start\\\":1,\\\"col_stop\\\":3,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"r0: bool = true; \\\"}\"}" + value: + Value: + Boolean: + - "true" + - span: + line_start: 14 + line_stop: 14 + col_start: 13 + col_stop: 17 + path: "" + content: "r0: bool = true; " + span: + line_start: 14 + line_stop: 14 + col_start: 5 + col_stop: 9 + path: "" + content: "r0: bool = true; " + - type_: + IntegerType: U8 + name: "{\"name\":\"r1\",\"span\":\"{\\\"line_start\\\":15,\\\"line_stop\\\":15,\\\"col_start\\\":1,\\\"col_stop\\\":3,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"r1: u8 = 2; \\\"}\"}" + value: + Value: + Implicit: + - "2" + - span: + line_start: 15 + line_stop: 15 + col_start: 13 + col_stop: 14 + path: "" + content: "r1: u8 = 2; " + span: + line_start: 15 + line_stop: 15 + col_start: 5 + col_stop: 7 + path: "" + content: "r1: u8 = 2; " + - type_: Field + name: "{\"name\":\"r2\",\"span\":\"{\\\"line_start\\\":16,\\\"line_stop\\\":16,\\\"col_start\\\":1,\\\"col_stop\\\":3,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"r2: field = 0; \\\"}\"}" + value: + Value: + Implicit: + - "0" + - span: + line_start: 16 + line_stop: 16 + col_start: 13 + col_stop: 14 + path: "" + content: "r2: field = 0; " + span: + line_start: 16 + line_stop: 16 + col_start: 5 + col_stop: 10 + path: "" + content: "r2: field = 0; " + - type_: Group + name: "{\"name\":\"r3\",\"span\":\"{\\\"line_start\\\":17,\\\"line_stop\\\":17,\\\"col_start\\\":1,\\\"col_stop\\\":3,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"r3: group = (0, 1)group; \\\"}\"}" + value: + Value: + Group: + Tuple: + x: + Number: + - "0" + - span: + line_start: 17 + line_stop: 17 + col_start: 14 + col_stop: 15 + path: "" + content: "r3: group = (0, 1)group; " + y: + Number: + - "1" + - span: + line_start: 17 + line_stop: 17 + col_start: 17 + col_stop: 18 + path: "" + content: "r3: group = (0, 1)group; " + span: + line_start: 17 + line_stop: 17 + col_start: 14 + col_stop: 24 + path: "" + content: "r3: group = (0, 1)group; " + span: + line_start: 17 + line_stop: 17 + col_start: 5 + col_stop: 10 + path: "" + content: "r3: group = (0, 1)group; " + - type_: Address + name: "{\"name\":\"r4\",\"span\":\"{\\\"line_start\\\":18,\\\"line_stop\\\":18,\\\"col_start\\\":1,\\\"col_stop\\\":3,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"r4: address = aleo1qnr4dkkvkgfqph0vzc3y6z2eu975wnpz2925ntjccd5cfqxtyu8sta57j8;\\\"}\"}" + value: + Value: + Address: + - aleo1qnr4dkkvkgfqph0vzc3y6z2eu975wnpz2925ntjccd5cfqxtyu8sta57j8 + - span: + line_start: 18 + line_stop: 18 + col_start: 15 + col_stop: 78 + path: "" + content: "r4: address = aleo1qnr4dkkvkgfqph0vzc3y6z2eu975wnpz2925ntjccd5cfqxtyu8sta57j8;" + span: + line_start: 18 + line_stop: 18 + col_start: 5 + col_stop: 12 + path: "" + content: "r4: address = aleo1qnr4dkkvkgfqph0vzc3y6z2eu975wnpz2925ntjccd5cfqxtyu8sta57j8;" + - type_: + Array: + - IntegerType: U8 + - - value: "32" + name: "{\"name\":\"r5\",\"span\":\"{\\\"line_start\\\":19,\\\"line_stop\\\":19,\\\"col_start\\\":1,\\\"col_stop\\\":3,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"r5: [u8; 32] = [0; 32]; \\\"}\"}" + value: + ArrayInit: + element: + Value: + Implicit: + - "0" + - span: + line_start: 19 + line_stop: 19 + col_start: 17 + col_stop: 18 + path: "" + content: "r5: [u8; 32] = [0; 32]; " + dimensions: + - value: "32" + span: + line_start: 19 + line_stop: 19 + col_start: 16 + col_stop: 23 + path: "" + content: "r5: [u8; 32] = [0; 32]; " + span: + line_start: 19 + line_stop: 19 + col_start: 5 + col_stop: 13 + path: "" + content: "r5: [u8; 32] = [0; 32]; " + - type_: + Array: + - Array: + - IntegerType: U8 + - - value: "2" + - - value: "3" + name: "{\"name\":\"r6\",\"span\":\"{\\\"line_start\\\":20,\\\"line_stop\\\":20,\\\"col_start\\\":1,\\\"col_stop\\\":3,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"r6: [[u8; 2]; 3] = [[0; 2]; 3]; \\\"}\"}" + value: + ArrayInit: + element: + ArrayInit: + element: + Value: + Implicit: + - "0" + - span: + line_start: 20 + line_stop: 20 + col_start: 22 + col_stop: 23 + path: "" + content: "r6: [[u8; 2]; 3] = [[0; 2]; 3]; " + dimensions: + - value: "2" + span: + line_start: 20 + line_stop: 20 + col_start: 21 + col_stop: 27 + path: "" + content: "r6: [[u8; 2]; 3] = [[0; 2]; 3]; " + dimensions: + - value: "3" + span: + line_start: 20 + line_stop: 20 + col_start: 20 + col_stop: 31 + path: "" + content: "r6: [[u8; 2]; 3] = [[0; 2]; 3]; " + span: + line_start: 20 + line_stop: 20 + col_start: 5 + col_stop: 17 + path: "" + content: "r6: [[u8; 2]; 3] = [[0; 2]; 3]; " + - type_: + Tuple: + - Boolean + - Boolean + name: "{\"name\":\"r7\",\"span\":\"{\\\"line_start\\\":21,\\\"line_stop\\\":21,\\\"col_start\\\":1,\\\"col_stop\\\":3,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"r7: (bool, bool) = (true, false); \\\"}\"}" + value: + TupleInit: + elements: + - Value: + Boolean: + - "true" + - span: + line_start: 21 + line_stop: 21 + col_start: 21 + col_stop: 25 + path: "" + content: "r7: (bool, bool) = (true, false); " + - Value: + Boolean: + - "false" + - span: + line_start: 21 + line_stop: 21 + col_start: 27 + col_stop: 32 + path: "" + content: "r7: (bool, bool) = (true, false); " + span: + line_start: 21 + line_stop: 21 + col_start: 20 + col_stop: 33 + path: "" + content: "r7: (bool, bool) = (true, false); " + span: + line_start: 21 + line_stop: 21 + col_start: 5 + col_stop: 17 + path: "" + content: "r7: (bool, bool) = (true, false); " + span: + line_start: 13 + line_stop: 13 + col_start: 2 + col_stop: 11 + path: "" + content: "[registers]" + - name: constants + definitions: + - type_: Boolean + name: "{\"name\":\"c0\",\"span\":\"{\\\"line_start\\\":24,\\\"line_stop\\\":24,\\\"col_start\\\":1,\\\"col_stop\\\":3,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"c0: bool = true; \\\"}\"}" + value: + Value: + Boolean: + - "true" + - span: + line_start: 24 + line_stop: 24 + col_start: 13 + col_stop: 17 + path: "" + content: "c0: bool = true; " + span: + line_start: 24 + line_stop: 24 + col_start: 5 + col_stop: 9 + path: "" + content: "c0: bool = true; " + - type_: + IntegerType: U8 + name: "{\"name\":\"c1\",\"span\":\"{\\\"line_start\\\":25,\\\"line_stop\\\":25,\\\"col_start\\\":1,\\\"col_stop\\\":3,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"c1: u8 = 2; \\\"}\"}" + value: + Value: + Implicit: + - "2" + - span: + line_start: 25 + line_stop: 25 + col_start: 13 + col_stop: 14 + path: "" + content: "c1: u8 = 2; " + span: + line_start: 25 + line_stop: 25 + col_start: 5 + col_stop: 7 + path: "" + content: "c1: u8 = 2; " + - type_: Field + name: "{\"name\":\"c2\",\"span\":\"{\\\"line_start\\\":26,\\\"line_stop\\\":26,\\\"col_start\\\":1,\\\"col_stop\\\":3,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"c2: field = 0; \\\"}\"}" + value: + Value: + Implicit: + - "0" + - span: + line_start: 26 + line_stop: 26 + col_start: 13 + col_stop: 14 + path: "" + content: "c2: field = 0; " + span: + line_start: 26 + line_stop: 26 + col_start: 5 + col_stop: 10 + path: "" + content: "c2: field = 0; " + - type_: Group + name: "{\"name\":\"c3\",\"span\":\"{\\\"line_start\\\":27,\\\"line_stop\\\":27,\\\"col_start\\\":1,\\\"col_stop\\\":3,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"c3: group = (0, 1)group; \\\"}\"}" + value: + Value: + Group: + Tuple: + x: + Number: + - "0" + - span: + line_start: 27 + line_stop: 27 + col_start: 14 + col_stop: 15 + path: "" + content: "c3: group = (0, 1)group; " + y: + Number: + - "1" + - span: + line_start: 27 + line_stop: 27 + col_start: 17 + col_stop: 18 + path: "" + content: "c3: group = (0, 1)group; " + span: + line_start: 27 + line_stop: 27 + col_start: 14 + col_stop: 24 + path: "" + content: "c3: group = (0, 1)group; " + span: + line_start: 27 + line_stop: 27 + col_start: 5 + col_stop: 10 + path: "" + content: "c3: group = (0, 1)group; " + - type_: Address + name: "{\"name\":\"c4\",\"span\":\"{\\\"line_start\\\":28,\\\"line_stop\\\":28,\\\"col_start\\\":1,\\\"col_stop\\\":3,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"c4: address = aleo1qnr4dkkvkgfqph0vzc3y6z2eu975wnpz2925ntjccd5cfqxtyu8sta57j8;\\\"}\"}" + value: + Value: + Address: + - aleo1qnr4dkkvkgfqph0vzc3y6z2eu975wnpz2925ntjccd5cfqxtyu8sta57j8 + - span: + line_start: 28 + line_stop: 28 + col_start: 15 + col_stop: 78 + path: "" + content: "c4: address = aleo1qnr4dkkvkgfqph0vzc3y6z2eu975wnpz2925ntjccd5cfqxtyu8sta57j8;" + span: + line_start: 28 + line_stop: 28 + col_start: 5 + col_stop: 12 + path: "" + content: "c4: address = aleo1qnr4dkkvkgfqph0vzc3y6z2eu975wnpz2925ntjccd5cfqxtyu8sta57j8;" + - type_: + Array: + - IntegerType: U8 + - - value: "32" + name: "{\"name\":\"c5\",\"span\":\"{\\\"line_start\\\":29,\\\"line_stop\\\":29,\\\"col_start\\\":1,\\\"col_stop\\\":3,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"c5: [u8; 32] = [0; 32]; \\\"}\"}" + value: + ArrayInit: + element: + Value: + Implicit: + - "0" + - span: + line_start: 29 + line_stop: 29 + col_start: 17 + col_stop: 18 + path: "" + content: "c5: [u8; 32] = [0; 32]; " + dimensions: + - value: "32" + span: + line_start: 29 + line_stop: 29 + col_start: 16 + col_stop: 23 + path: "" + content: "c5: [u8; 32] = [0; 32]; " + span: + line_start: 29 + line_stop: 29 + col_start: 5 + col_stop: 13 + path: "" + content: "c5: [u8; 32] = [0; 32]; " + - type_: + Array: + - Array: + - IntegerType: U8 + - - value: "2" + - - value: "3" + name: "{\"name\":\"c6\",\"span\":\"{\\\"line_start\\\":30,\\\"line_stop\\\":30,\\\"col_start\\\":1,\\\"col_stop\\\":3,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"c6: [[u8; 2]; 3] = [[0; 2]; 3]; \\\"}\"}" + value: + ArrayInit: + element: + ArrayInit: + element: + Value: + Implicit: + - "0" + - span: + line_start: 30 + line_stop: 30 + col_start: 22 + col_stop: 23 + path: "" + content: "c6: [[u8; 2]; 3] = [[0; 2]; 3]; " + dimensions: + - value: "2" + span: + line_start: 30 + line_stop: 30 + col_start: 21 + col_stop: 27 + path: "" + content: "c6: [[u8; 2]; 3] = [[0; 2]; 3]; " + dimensions: + - value: "3" + span: + line_start: 30 + line_stop: 30 + col_start: 20 + col_stop: 31 + path: "" + content: "c6: [[u8; 2]; 3] = [[0; 2]; 3]; " + span: + line_start: 30 + line_stop: 30 + col_start: 5 + col_stop: 17 + path: "" + content: "c6: [[u8; 2]; 3] = [[0; 2]; 3]; " + - type_: + Tuple: + - Boolean + - Boolean + name: "{\"name\":\"c7\",\"span\":\"{\\\"line_start\\\":31,\\\"line_stop\\\":31,\\\"col_start\\\":1,\\\"col_stop\\\":3,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"c7: (bool, bool) = (true, false); \\\"}\"}" + value: + TupleInit: + elements: + - Value: + Boolean: + - "true" + - span: + line_start: 31 + line_stop: 31 + col_start: 21 + col_stop: 25 + path: "" + content: "c7: (bool, bool) = (true, false); " + - Value: + Boolean: + - "false" + - span: + line_start: 31 + line_stop: 31 + col_start: 27 + col_stop: 32 + path: "" + content: "c7: (bool, bool) = (true, false); " + span: + line_start: 31 + line_stop: 31 + col_start: 20 + col_stop: 33 + path: "" + content: "c7: (bool, bool) = (true, false); " + span: + line_start: 31 + line_stop: 31 + col_start: 5 + col_stop: 17 + path: "" + content: "c7: (bool, bool) = (true, false); " + span: + line_start: 23 + line_stop: 23 + col_start: 2 + col_stop: 11 + path: "" + content: "[constants]" diff --git a/tests/parser/inputs/input_success.leo b/tests/parser/inputs/input_success.leo new file mode 100644 index 0000000000..fae8348174 --- /dev/null +++ b/tests/parser/inputs/input_success.leo @@ -0,0 +1,34 @@ +/* +namespace: Input +expectation: Pass +*/ + +[main] +a: bool = true; +b: u8 = 2; +c: field = 0; +d: group = (0, 1)group; +e: address = aleo1qnr4dkkvkgfqph0vzc3y6z2eu975wnpz2925ntjccd5cfqxtyu8sta57j8; +f: [u8; 32] = [0; 32]; +g: [[u8; 2]; 3] = [[0; 2]; 3]; +h: (bool, bool) = (true, false); + +[registers] +r0: bool = true; +r1: u8 = 2; +r2: field = 0; +r3: group = (0, 1)group; +r4: address = aleo1qnr4dkkvkgfqph0vzc3y6z2eu975wnpz2925ntjccd5cfqxtyu8sta57j8; +r5: [u8; 32] = [0; 32]; +r6: [[u8; 2]; 3] = [[0; 2]; 3]; +r7: (bool, bool) = (true, false); + +[constants] +c0: bool = true; +c1: u8 = 2; +c2: field = 0; +c3: group = (0, 1)group; +c4: address = aleo1qnr4dkkvkgfqph0vzc3y6z2eu975wnpz2925ntjccd5cfqxtyu8sta57j8; +c5: [u8; 32] = [0; 32]; +c6: [[u8; 2]; 3] = [[0; 2]; 3]; +c7: (bool, bool) = (true, false);