Compare commits
230
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b6ed825bf6 | ||
|
|
77e7430776 | ||
|
|
d58d4c74cd | ||
|
|
00ab0b84ce | ||
|
|
320758fd81 | ||
|
|
008b37b0de | ||
|
|
b257ff5c1a | ||
|
|
e58a4a8524 | ||
|
|
08e2eff4ab | ||
|
|
cb626757ba | ||
|
|
2718a5028a | ||
|
|
b69168f135 | ||
|
|
48c24235b1 | ||
|
|
5c6b3bbca1 | ||
|
|
c3f56dd3e9 | ||
|
|
173c983c6f | ||
|
|
5054185e0d | ||
|
|
6a7c45ffbe | ||
|
|
1546660435 | ||
|
|
ee95fc60fc | ||
|
|
c735441f37 | ||
|
|
cd7a62dc34 | ||
|
|
fae231d481 | ||
|
|
8f57517a9f | ||
|
|
16803aa0f6 | ||
|
|
d1335bb613 | ||
|
|
4b733f6b9c | ||
|
|
8f115353bb | ||
|
|
0dd1016980 | ||
|
|
4def6db820 | ||
|
|
8b95497725 | ||
|
|
e369c94d21 | ||
|
|
d434ec78e7 | ||
|
|
ecfff0ac0d | ||
|
|
bbb94a4f97 | ||
|
|
2bb29991da | ||
|
|
175e7fa858 | ||
|
|
2122698000 | ||
|
|
001165ee58 | ||
|
|
e4fbab190c | ||
|
|
fa6765cdd9 | ||
|
|
f07bde8d3f | ||
|
|
d7e5e72bbb | ||
|
|
aadccb7f38 | ||
|
|
eea72f5bb3 | ||
|
|
3b6fc03546 | ||
|
|
48e3522543 | ||
|
|
f45d83d261 | ||
|
|
0e3e0bdb56 | ||
|
|
b6eb46d985 | ||
|
|
6b618f3eb3 | ||
|
|
1163849039 | ||
|
|
12cf4e94d8 | ||
|
|
663dab52ec | ||
|
|
44f10d3fb7 | ||
|
|
bed7b17134 | ||
|
|
5f0b1fa67a | ||
|
|
37e0a574d5 | ||
|
|
33d6c931f5 | ||
|
|
db3ae3f37e | ||
|
|
4d50c8c1be | ||
|
|
70924e13c8 | ||
|
|
b6f755cef6 | ||
|
|
01e3c30e2b | ||
|
|
b2ff76d691 | ||
|
|
c8187379a5 | ||
|
|
5d3e393d5a | ||
|
|
3196b2b652 | ||
|
|
919447875a | ||
|
|
a31f6633fe | ||
|
|
1a7e6c5f37 | ||
|
|
52b472ed94 | ||
|
|
9785d0a430 | ||
|
|
ddcffaea92 | ||
|
|
d4992e76fc | ||
|
|
d0716fb735 | ||
|
|
fab7326357 | ||
|
|
d3ff834111 | ||
|
|
b19b1bb41d | ||
|
|
526b479ea4 | ||
|
|
37e3da5d67 | ||
|
|
5a1285a2a8 | ||
|
|
076f1f6d33 | ||
|
|
05fc8fa7f3 | ||
|
|
c06eebe50b | ||
|
|
da3923830d | ||
|
|
b547c7d934 | ||
|
|
9ad253e916 | ||
|
|
a5a3d6566b | ||
|
|
74d53fff97 | ||
|
|
c37392046a | ||
|
|
2256ef2a9f | ||
|
|
cb3f1bcde1 | ||
|
|
e7f1072050 | ||
|
|
14e88e2e4d | ||
|
|
1619250ba5 | ||
|
|
562bcd7f1e | ||
|
|
15a0f9e491 | ||
|
|
e3ef968033 | ||
|
|
afd3d05e2f | ||
|
|
286894c5db | ||
|
|
947e5f931e | ||
|
|
1b6340e7a6 | ||
|
|
7a613e93e8 | ||
|
|
4780f5ce68 | ||
|
|
be0550b57a | ||
|
|
1e58de02be | ||
|
|
41fd60dd12 | ||
|
|
9949027bc9 | ||
|
|
ba5145d9ad | ||
|
|
b20337b385 | ||
|
|
abda2c4c41 | ||
|
|
72fa94bdc6 | ||
|
|
e3e6caf4e6 | ||
|
|
f37a1019ae | ||
|
|
0215e295b5 | ||
|
|
9206ca440e | ||
|
|
a9f6cce1b3 | ||
|
|
0347892056 | ||
|
|
20762a01bd | ||
|
|
3e7863afed | ||
|
|
27e78dc377 | ||
|
|
9001c1c3e2 | ||
|
|
206b2fa414 | ||
|
|
fa4a7ee4c7 | ||
|
|
e70e813497 | ||
|
|
1977bd59be | ||
|
|
58e1f9ddd2 | ||
|
|
fafc03d5d8 | ||
|
|
982b0bf4a5 | ||
|
|
d0796aa5df | ||
|
|
e7b4e65b71 | ||
|
|
7acef24e09 | ||
|
|
5e5d22f3c5 | ||
|
|
330beaea75 | ||
|
|
7229cfd9f5 | ||
|
|
eb2552b19a | ||
|
|
6e26b283fa | ||
|
|
1a281cd344 | ||
|
|
c8b43a3e90 | ||
|
|
721700ea03 | ||
|
|
8c28e61e42 | ||
|
|
a9eb77f158 | ||
|
|
765e2ded93 | ||
|
|
d364c41c26 | ||
|
|
ac9ee5a4b6 | ||
|
|
56c22eb1ed | ||
|
|
cac497a560 | ||
|
|
b559215212 | ||
|
|
143d496ee8 | ||
|
|
a589d7173d | ||
|
|
40b2981252 | ||
|
|
94320bafa6 | ||
|
|
970441b905 | ||
|
|
2e09ee85d4 | ||
|
|
3fed475c1c | ||
|
|
1e09b7043a | ||
|
|
b311dbd16c | ||
|
|
595ddc789d | ||
|
|
d5501ef25e | ||
|
|
0955bca5bc | ||
|
|
8df4351563 | ||
|
|
2384c4438b | ||
|
|
14ae964be4 | ||
|
|
f128bb0008 | ||
|
|
1810520d2c | ||
|
|
202f41c0e6 | ||
|
|
6cacfd7135 | ||
|
|
d4dc1571b2 | ||
|
|
d3b54b4114 | ||
|
|
e571d98cd0 | ||
|
|
a8717aa5c4 | ||
|
|
20d9641dda | ||
|
|
fc4dd0aa3c | ||
|
|
7a5e03afd6 | ||
|
|
a4df59927e | ||
|
|
a568d465af | ||
|
|
0677d15405 | ||
|
|
5771d15d74 | ||
|
|
5dda3dd32e | ||
|
|
c07e0bcb3e | ||
|
|
269e43930f | ||
|
|
4683a3039e | ||
|
|
f4072b08a3 | ||
|
|
9a500c4bcf | ||
|
|
1608b10af8 | ||
|
|
a3455e1b68 | ||
|
|
248462e467 | ||
|
|
71e4f74c24 | ||
|
|
e0b52a0216 | ||
|
|
8a0eee547d | ||
|
|
280e11a95e | ||
|
|
cdcc69f975 | ||
|
|
ece3d2fbf6 | ||
|
|
7641d866b8 | ||
|
|
fe96e3aec6 | ||
|
|
72010faf03 | ||
|
|
e5df8df9b0 | ||
|
|
ee40450f3a | ||
|
|
be6d2de39c | ||
|
|
aff15f67c7 | ||
|
|
cfd1910f39 | ||
|
|
082981f0bd | ||
|
|
b384f55c77 | ||
|
|
c4756262e1 | ||
|
|
74f10cc74b | ||
|
|
acef0888a3 | ||
|
|
18ab88af64 | ||
|
|
5e6cdc84b9 | ||
|
|
2dc5cdc9d9 | ||
|
|
893c981a41 | ||
|
|
0b3c4b8143 | ||
|
|
86a1df7ad5 | ||
|
|
3fa04cddd0 | ||
|
|
371365b8cf | ||
|
|
b74da3255a | ||
|
|
83e5e98641 | ||
|
|
c774737074 | ||
|
|
9e1b9ad564 | ||
|
|
97b2cc4413 | ||
|
|
99ff0ead2d | ||
|
|
b0f3dccc87 | ||
|
|
86a781c3f2 | ||
|
|
583d51141f | ||
|
|
ad11a3bd6a | ||
|
|
7a2ba74d9c | ||
|
|
7007aa32f1 | ||
|
|
3444f93546 | ||
|
|
e09c7926e5 | ||
|
|
83e98573aa |
Generated
+104
-12
@@ -45,6 +45,12 @@ dependencies = [
|
|||||||
"generic-array",
|
"generic-array",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "bytecount"
|
||||||
|
version = "0.6.9"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "175812e0be2bccb6abe50bb8d566126198344f707e304f45c648fd8f2cc0365e"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "bytes"
|
name = "bytes"
|
||||||
version = "1.11.1"
|
version = "1.11.1"
|
||||||
@@ -122,7 +128,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "978747c1d849a7d2ee5e8adc0159961c48fb7e5db2f06af6723b80123bb53856"
|
checksum = "978747c1d849a7d2ee5e8adc0159961c48fb7e5db2f06af6723b80123bb53856"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cfg-if",
|
"cfg-if",
|
||||||
"hashbrown",
|
"hashbrown 0.14.5",
|
||||||
"lock_api",
|
"lock_api",
|
||||||
"once_cell",
|
"once_cell",
|
||||||
"parking_lot_core",
|
"parking_lot_core",
|
||||||
@@ -136,7 +142,7 @@ checksum = "5041cc499144891f3790297212f32a74fb938e5136a14943f338ef9e0ae276cf"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"cfg-if",
|
"cfg-if",
|
||||||
"crossbeam-utils",
|
"crossbeam-utils",
|
||||||
"hashbrown",
|
"hashbrown 0.14.5",
|
||||||
"lock_api",
|
"lock_api",
|
||||||
"once_cell",
|
"once_cell",
|
||||||
"parking_lot_core",
|
"parking_lot_core",
|
||||||
@@ -163,6 +169,12 @@ dependencies = [
|
|||||||
"syn",
|
"syn",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "equivalent"
|
||||||
|
version = "1.0.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "errno"
|
name = "errno"
|
||||||
version = "0.3.14"
|
version = "0.3.14"
|
||||||
@@ -274,6 +286,12 @@ version = "0.14.5"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
|
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "hashbrown"
|
||||||
|
version = "0.17.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "httparse"
|
name = "httparse"
|
||||||
version = "1.10.1"
|
version = "1.10.1"
|
||||||
@@ -383,6 +401,16 @@ dependencies = [
|
|||||||
"icu_properties",
|
"icu_properties",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "indexmap"
|
||||||
|
version = "2.14.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"
|
||||||
|
dependencies = [
|
||||||
|
"equivalent",
|
||||||
|
"hashbrown 0.17.1",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "itoa"
|
name = "itoa"
|
||||||
version = "1.0.18"
|
version = "1.0.18"
|
||||||
@@ -442,12 +470,13 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "mist-analyzer"
|
name = "mist-analyzer"
|
||||||
version = "0.0.3"
|
version = "0.3.5-alpha.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cargo_metadata",
|
"cargo_metadata",
|
||||||
"dashmap 6.1.0",
|
"dashmap 6.1.0",
|
||||||
"mist-codegen",
|
"mist-codegen",
|
||||||
"mist-parser",
|
"mist-parser",
|
||||||
|
"pest",
|
||||||
"ropey",
|
"ropey",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
@@ -456,27 +485,36 @@ dependencies = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "mist-codegen"
|
name = "mist-api"
|
||||||
version = "0.1.2"
|
version = "0.3.5-alpha.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"cargo_metadata",
|
||||||
|
"mist-codegen",
|
||||||
|
"mist-parser",
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
|
"toml",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "mist-codegen"
|
||||||
|
version = "0.3.5-alpha.0"
|
||||||
|
dependencies = [
|
||||||
|
"bytecount",
|
||||||
"mist-parser",
|
"mist-parser",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "mist-lang"
|
name = "mist-lang"
|
||||||
version = "0.0.5-alpha0"
|
version = "0.3.5-alpha.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cargo_metadata",
|
|
||||||
"mist-analyzer",
|
"mist-analyzer",
|
||||||
"mist-codegen",
|
"mist-api",
|
||||||
"mist-parser",
|
|
||||||
"serde",
|
|
||||||
"serde_json",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "mist-parser"
|
name = "mist-parser"
|
||||||
version = "0.1.6"
|
version = "0.3.5-alpha.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"pest",
|
"pest",
|
||||||
"pest_derive",
|
"pest_derive",
|
||||||
@@ -704,6 +742,15 @@ dependencies = [
|
|||||||
"syn",
|
"syn",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "serde_spanned"
|
||||||
|
version = "1.1.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26"
|
||||||
|
dependencies = [
|
||||||
|
"serde_core",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "sha2"
|
name = "sha2"
|
||||||
version = "0.10.9"
|
version = "0.10.9"
|
||||||
@@ -852,6 +899,45 @@ dependencies = [
|
|||||||
"tokio",
|
"tokio",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "toml"
|
||||||
|
version = "1.1.2+spec-1.1.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "81f3d15e84cbcd896376e6730314d59fb5a87f31e4b038454184435cd57defee"
|
||||||
|
dependencies = [
|
||||||
|
"indexmap",
|
||||||
|
"serde_core",
|
||||||
|
"serde_spanned",
|
||||||
|
"toml_datetime",
|
||||||
|
"toml_parser",
|
||||||
|
"toml_writer",
|
||||||
|
"winnow",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "toml_datetime"
|
||||||
|
version = "1.1.1+spec-1.1.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7"
|
||||||
|
dependencies = [
|
||||||
|
"serde_core",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "toml_parser"
|
||||||
|
version = "1.1.2+spec-1.1.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526"
|
||||||
|
dependencies = [
|
||||||
|
"winnow",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "toml_writer"
|
||||||
|
version = "1.1.1+spec-1.1.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "756daf9b1013ebe47a8776667b466417e2d4c5679d441c26230efd9ef78692db"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tower"
|
name = "tower"
|
||||||
version = "0.4.13"
|
version = "0.4.13"
|
||||||
@@ -1007,6 +1093,12 @@ dependencies = [
|
|||||||
"windows-link",
|
"windows-link",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "winnow"
|
||||||
|
version = "1.0.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0592e1c9d151f854e6fd382574c3a0855250e1d9b2f99d9281c6e6391af352f1"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "writeable"
|
name = "writeable"
|
||||||
version = "0.6.3"
|
version = "0.6.3"
|
||||||
|
|||||||
+7
-18
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "mist-lang"
|
name = "mist-lang"
|
||||||
version = "0.0.5-alpha0"
|
version = "0.3.5-alpha.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
description = "The Mist programming language compiler"
|
description = "The Mist programming language compiler"
|
||||||
license = "Apache-2.0"
|
license = "Apache-2.0"
|
||||||
@@ -16,19 +16,15 @@ include = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
mist-parser = { workspace = true }
|
|
||||||
mist-analyzer = { workspace = true }
|
mist-analyzer = { workspace = true }
|
||||||
mist-codegen = { workspace = true }
|
mist-api = { workspace = true }
|
||||||
|
|
||||||
serde = { version = "1.0.228", features = ["serde_derive"] }
|
|
||||||
serde_json = "1.0.149"
|
|
||||||
cargo_metadata = "0.23.1"
|
|
||||||
|
|
||||||
[workspace]
|
[workspace]
|
||||||
members = [
|
members = [
|
||||||
"crates/parser",
|
"crates/parser",
|
||||||
"crates/analyzer",
|
"crates/analyzer",
|
||||||
"crates/codegen",
|
"crates/codegen",
|
||||||
|
"crates/mist-api",
|
||||||
]
|
]
|
||||||
|
|
||||||
exclude = [
|
exclude = [
|
||||||
@@ -36,22 +32,15 @@ exclude = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
[workspace.dependencies]
|
[workspace.dependencies]
|
||||||
mist-parser = { path = "crates/parser", version = "0.1.6" }
|
mist-parser = { path = "crates/parser", version = "0.3.5-alpha.0" }
|
||||||
mist-analyzer = { path = "crates/analyzer", version = "0.0.3" }
|
mist-analyzer = { path = "crates/analyzer", version = "0.3.5-alpha.0" }
|
||||||
mist-codegen = { path = "crates/codegen", version = "0.1.2" }
|
mist-codegen = { path = "crates/codegen", version = "0.3.5-alpha.0" }
|
||||||
|
mist-api = { path = "crates/mist-api", version = "0.3.5-alpha.0" }
|
||||||
|
|
||||||
[[bin]]
|
[[bin]]
|
||||||
name = "mist"
|
name = "mist"
|
||||||
path = ".mist/src/main.rs"
|
path = ".mist/src/main.rs"
|
||||||
|
|
||||||
[[bin]]
|
|
||||||
name = "mist-lsp"
|
|
||||||
path = ".mist/lsp/main.rs"
|
|
||||||
|
|
||||||
[[bin]]
|
|
||||||
name = "mist-header"
|
|
||||||
path = "src/_header.rs"
|
|
||||||
|
|
||||||
[[bin]]
|
[[bin]]
|
||||||
name = "mist-analyzer"
|
name = "mist-analyzer"
|
||||||
path = ".mist/src/analyzer.rs"
|
path = ".mist/src/analyzer.rs"
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# Mist Language: <br/> A C++ inspired langauge in the Rust ecosystem
|
# Mist - A Pragmatic Systems Language built on Rust
|
||||||
|
|
||||||
<!--
|
<!--
|
||||||
Originally this readme was part of the Carbon Language project, licensed with Apache-2.0
|
Originally this readme was part of the Carbon Language project, licensed with Apache-2.0
|
||||||
@@ -9,7 +9,7 @@ Originally this readme was part of the Carbon Language project, licensed with Ap
|
|||||||
</p>
|
</p>
|
||||||
|
|
||||||
|
|
||||||
<img src="code.png" align="right" width="575" alt="">
|
<img src="code.png" align="right" width="450" alt="">
|
||||||
|
|
||||||
<!--
|
<!--
|
||||||
Don't let the text wrap too narrowly to the left of the above image.
|
Don't let the text wrap too narrowly to the left of the above image.
|
||||||
@@ -29,6 +29,6 @@ The `div` reduces the vertical height. The `picture` prevents autolinking.
|
|||||||
- Designed for fast, readable systems code
|
- Designed for fast, readable systems code
|
||||||
|
|
||||||
**Class and type system**
|
**Class and type system**
|
||||||
- class is syntactic sugar for a Rust struct
|
- class is syntactic sugar for a Rust struct with V Tables
|
||||||
- `struct B extends A` provides inheritance-style syntax over struct composition
|
- `class B : A` provides inheritance-style syntax over struct composition
|
||||||
- Classes and structs compile into the same underlying Rust type system model
|
- Classes and structs compile into the same underlying Rust type system model
|
||||||
+1
-1
@@ -4,6 +4,6 @@ cd D:\projects\mist\mist
|
|||||||
|
|
||||||
mist build >nul 2>&1
|
mist build >nul 2>&1
|
||||||
|
|
||||||
cd D:\projects\mist\mist-lsp-test
|
cd mist-test
|
||||||
|
|
||||||
D:\projects\mist\mist\target\debug\mist-analyzer.exe
|
D:\projects\mist\mist\target\debug\mist-analyzer.exe
|
||||||
|
|||||||
Binary file not shown.
|
Before Width: | Height: | Size: 70 KiB After Width: | Height: | Size: 53 KiB |
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "mist-analyzer"
|
name = "mist-analyzer"
|
||||||
version = "0.0.3"
|
version = "0.3.5-alpha.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
description = "The Mist programming language Analyzer LSP"
|
description = "The Mist programming language Analyzer LSP"
|
||||||
license = "Apache-2.0"
|
license = "Apache-2.0"
|
||||||
@@ -11,6 +11,7 @@ categories = ["compilers"]
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
mist-parser = { workspace = true }
|
mist-parser = { workspace = true }
|
||||||
mist-codegen = { workspace = true }
|
mist-codegen = { workspace = true }
|
||||||
|
pest = "2.8.6"
|
||||||
|
|
||||||
dashmap = "6.1.0"
|
dashmap = "6.1.0"
|
||||||
tokio = { version = "1.52.3", features = ["full", "macros", "rt", "rt-multi-thread"] }
|
tokio = { version = "1.52.3", features = ["full", "macros", "rt", "rt-multi-thread"] }
|
||||||
|
|||||||
@@ -1,139 +0,0 @@
|
|||||||
use std::{
|
|
||||||
collections::HashMap,
|
|
||||||
env, fs,
|
|
||||||
path::{MAIN_SEPARATOR, PathBuf},
|
|
||||||
process::{Command, Stdio},
|
|
||||||
};
|
|
||||||
|
|
||||||
use cargo_metadata::{CompilerMessage, Message};
|
|
||||||
use mist_parser::rev_mapper::{RustMap, find_mapping, get_mapping};
|
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub struct MistDiagnosticMessage {
|
|
||||||
pub message: String,
|
|
||||||
pub file_path: PathBuf,
|
|
||||||
pub file_name: String,
|
|
||||||
pub line: usize,
|
|
||||||
pub column: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub enum MistDiagnostic {
|
|
||||||
Error(MistDiagnosticMessage),
|
|
||||||
Warning(MistDiagnosticMessage),
|
|
||||||
Rust(CompilerMessage),
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn build(mut args: Vec<String>, root: PathBuf) -> Vec<MistDiagnostic> {
|
|
||||||
args.insert(1, "--message-format=json".to_string());
|
|
||||||
|
|
||||||
let is_root = root == env::current_dir().expect("Failed getting env");
|
|
||||||
|
|
||||||
let mut command = Command::new("cargo")
|
|
||||||
.args(args)
|
|
||||||
.stdout(Stdio::piped())
|
|
||||||
.spawn()
|
|
||||||
.expect("Failed to run cargo");
|
|
||||||
|
|
||||||
let mut reader = std::io::BufReader::new(command.stdout.take().expect("Failed to get reader"));
|
|
||||||
|
|
||||||
let mut diagnostics = Vec::new();
|
|
||||||
|
|
||||||
let mut mapping = HashMap::new();
|
|
||||||
|
|
||||||
let mist_src = format!(".mist{MAIN_SEPARATOR}lsp");
|
|
||||||
|
|
||||||
for message in cargo_metadata::Message::parse_stream(&mut reader) {
|
|
||||||
match message {
|
|
||||||
Ok(Message::CompilerMessage(msg)) => {
|
|
||||||
for span in &msg.message.spans {
|
|
||||||
if span.is_primary {
|
|
||||||
let rust_path = root.join(&span.file_name);
|
|
||||||
|
|
||||||
let mist_file = span
|
|
||||||
.file_name
|
|
||||||
.replacen(&mist_src, "src", 1)
|
|
||||||
.trim_end_matches(".rs")
|
|
||||||
.to_string()
|
|
||||||
+ ".mist";
|
|
||||||
|
|
||||||
let mist_path = root.join(&mist_file);
|
|
||||||
|
|
||||||
if !fs::exists(&mist_path).expect("Unable to check if mist file exists") {
|
|
||||||
diagnostics.push(MistDiagnostic::Rust(msg));
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
let map = mapping.entry(rust_path.clone()).or_insert_with(|| {
|
|
||||||
get_mapping(
|
|
||||||
&fs::read_to_string(rust_path)
|
|
||||||
.expect("Failed to read file for mapping"),
|
|
||||||
)
|
|
||||||
});
|
|
||||||
|
|
||||||
let mist_span =
|
|
||||||
find_mapping(&map, &RustMap(span.line_end, span.column_start))
|
|
||||||
.expect("Unable to find mapping");
|
|
||||||
|
|
||||||
let mist_msg = MistDiagnosticMessage {
|
|
||||||
message: format!(
|
|
||||||
"{}: {}",
|
|
||||||
msg.message.message,
|
|
||||||
span.label.clone().unwrap_or_default()
|
|
||||||
),
|
|
||||||
file_name: if is_root {
|
|
||||||
mist_file
|
|
||||||
} else {
|
|
||||||
mist_path.to_string_lossy().to_string()
|
|
||||||
},
|
|
||||||
file_path: mist_path,
|
|
||||||
line: mist_span.1.0,
|
|
||||||
column: mist_span.1.1,
|
|
||||||
};
|
|
||||||
|
|
||||||
match msg.message.level {
|
|
||||||
cargo_metadata::diagnostic::DiagnosticLevel::Error => {
|
|
||||||
diagnostics.push(MistDiagnostic::Error(mist_msg))
|
|
||||||
}
|
|
||||||
|
|
||||||
cargo_metadata::diagnostic::DiagnosticLevel::Warning => {
|
|
||||||
diagnostics.push(MistDiagnostic::Warning(mist_msg))
|
|
||||||
}
|
|
||||||
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(Message::BuildFinished(_)) => {
|
|
||||||
command.wait().unwrap();
|
|
||||||
|
|
||||||
return diagnostics;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(Message::TextLine(text)) => println!("{text}"),
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
diagnostics
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_line(
|
|
||||||
files: &mut HashMap<PathBuf, Vec<String>>,
|
|
||||||
msg: &MistDiagnosticMessage,
|
|
||||||
) -> Option<String> {
|
|
||||||
let src_path = msg.file_path.clone();
|
|
||||||
|
|
||||||
let lines = files.entry(src_path.clone()).or_insert_with(|| {
|
|
||||||
fs::read_to_string(src_path)
|
|
||||||
.expect("Unable to read mist file")
|
|
||||||
.lines()
|
|
||||||
.into_iter()
|
|
||||||
.map(String::from)
|
|
||||||
.collect()
|
|
||||||
});
|
|
||||||
|
|
||||||
lines.get(msg.line - 1).map(|v| v.trim().to_string())
|
|
||||||
}
|
|
||||||
+1277
-461
File diff suppressed because it is too large
Load Diff
@@ -35,11 +35,9 @@ type PendingMap = Arc<Mutex<HashMap<usize, oneshot::Sender<Result<Value, String>
|
|||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct RustAnalyzer {
|
pub struct RustAnalyzer {
|
||||||
// Wrapped in a Mutex to support safe concurrent sharing if the design expands
|
|
||||||
stdin: Arc<Mutex<tokio::process::ChildStdin>>,
|
stdin: Arc<Mutex<tokio::process::ChildStdin>>,
|
||||||
pending: PendingMap,
|
pending: PendingMap,
|
||||||
id: usize,
|
id: usize,
|
||||||
// Keep child handler to explicitly manage child process lifecycle and prevent zombie processes
|
|
||||||
_child: tokio::process::Child,
|
_child: tokio::process::Child,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -59,23 +57,32 @@ async fn read_lsp_message<R: AsyncBufReadExt + Unpin>(
|
|||||||
) -> Result<String, Box<dyn std::error::Error + Send + Sync>> {
|
) -> Result<String, Box<dyn std::error::Error + Send + Sync>> {
|
||||||
let mut line = String::new();
|
let mut line = String::new();
|
||||||
let mut content_length = 0;
|
let mut content_length = 0;
|
||||||
|
let mut eof = false;
|
||||||
|
|
||||||
// Guard against infinite header reading attacks/bugs (Max 100 headers)
|
|
||||||
for _ in 0..100 {
|
for _ in 0..100 {
|
||||||
line.clear();
|
line.clear();
|
||||||
let bytes_read = reader.read_line(&mut line).await?;
|
let bytes_read = reader.read_line(&mut line).await?;
|
||||||
if bytes_read == 0 || line == "\r\n" || line.is_empty() {
|
if bytes_read == 0 {
|
||||||
|
eof = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if line.trim().is_empty() {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
if line.to_ascii_lowercase().starts_with("content-length:") {
|
if line.to_ascii_lowercase().starts_with("content-length:") {
|
||||||
if let Some(val_str) = line.split(':').nth(1) {
|
if let Some(val_str) = line.split(':').nth(1) {
|
||||||
content_length = val_str.trim().parse::<usize>()?;
|
let trimmed = val_str.trim();
|
||||||
|
if !trimmed.is_empty() {
|
||||||
|
content_length = trimmed.parse::<usize>()?;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Explode early if payload size violates strict guard rails to prevent memory-exhaustion (OOM)
|
|
||||||
if content_length == 0 {
|
if content_length == 0 {
|
||||||
|
if eof {
|
||||||
|
return Err("LSP stream closed (EOF)".into());
|
||||||
|
}
|
||||||
return Err("Missing, invalid, or zero Content-Length header".into());
|
return Err("Missing, invalid, or zero Content-Length header".into());
|
||||||
}
|
}
|
||||||
if content_length > MAX_CONTENT_LENGTH {
|
if content_length > MAX_CONTENT_LENGTH {
|
||||||
@@ -86,7 +93,6 @@ async fn read_lsp_message<R: AsyncBufReadExt + Unpin>(
|
|||||||
.into());
|
.into());
|
||||||
}
|
}
|
||||||
|
|
||||||
// Explicitly secure pre-allocation limit
|
|
||||||
let mut buffer = vec![0u8; content_length];
|
let mut buffer = vec![0u8; content_length];
|
||||||
reader.read_exact(&mut buffer).await?;
|
reader.read_exact(&mut buffer).await?;
|
||||||
|
|
||||||
@@ -94,11 +100,13 @@ async fn read_lsp_message<R: AsyncBufReadExt + Unpin>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl RustAnalyzer {
|
impl RustAnalyzer {
|
||||||
pub fn new() -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
|
pub fn new(
|
||||||
|
notification_tx: tokio::sync::mpsc::UnboundedSender<Value>,
|
||||||
|
) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
|
||||||
let mut child = tokio::process::Command::new("rust-analyzer")
|
let mut child = tokio::process::Command::new("rust-analyzer")
|
||||||
.stdin(Stdio::piped())
|
.stdin(Stdio::piped())
|
||||||
.stdout(Stdio::piped())
|
.stdout(Stdio::piped())
|
||||||
.stderr(Stdio::null())
|
.stderr(Stdio::piped())
|
||||||
.spawn()?;
|
.spawn()?;
|
||||||
|
|
||||||
let stdin = child
|
let stdin = child
|
||||||
@@ -109,25 +117,54 @@ impl RustAnalyzer {
|
|||||||
.stdout
|
.stdout
|
||||||
.take()
|
.take()
|
||||||
.ok_or("Failed to open child stdout pipe")?;
|
.ok_or("Failed to open child stdout pipe")?;
|
||||||
|
let stderr = child
|
||||||
|
.stderr
|
||||||
|
.take()
|
||||||
|
.ok_or("Failed to open child stderr pipe")?;
|
||||||
|
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let mut stderr = stderr;
|
||||||
|
let mut buf = vec![0u8; 4096];
|
||||||
|
loop {
|
||||||
|
match stderr.read(&mut buf).await {
|
||||||
|
Ok(0) => break,
|
||||||
|
Ok(n) => {
|
||||||
|
eprintln!("[ra-stderr] {}", String::from_utf8_lossy(&buf[..n]).trim_end());
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
eprintln!("[ra-stderr] read error: {e}");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
eprintln!("[ra-stderr] stream closed");
|
||||||
|
});
|
||||||
|
|
||||||
let pending: PendingMap = Arc::new(Mutex::new(HashMap::new()));
|
let pending: PendingMap = Arc::new(Mutex::new(HashMap::new()));
|
||||||
let pending_clone = pending.clone();
|
let pending_clone = pending.clone();
|
||||||
|
|
||||||
// Background supervisor task loop
|
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
let mut stdout = BufReader::new(stdout);
|
let mut stdout = BufReader::new(stdout);
|
||||||
|
eprintln!("[ra-reader] started");
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
let raw = match read_lsp_message(&mut stdout).await {
|
let raw = match read_lsp_message(&mut stdout).await {
|
||||||
Ok(v) => v,
|
Ok(v) => v,
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
eprintln!("LSP fatal stream read failure: {err}");
|
eprintln!("LSP stream error: {err}");
|
||||||
// CRITICAL: Notify all pending channels that the bridge broke down
|
// Drain pending requests so they don't hang forever.
|
||||||
let mut lock = pending_clone.lock().await;
|
let mut lock = pending_clone.lock().await;
|
||||||
for (_, tx) in lock.drain() {
|
for (_, tx) in lock.drain() {
|
||||||
let _ = tx.send(Err(format!("LSP reader task dropped: {}", err)));
|
let _ = tx.send(Err(format!("LSP reader error: {}", err)));
|
||||||
}
|
}
|
||||||
break;
|
// EOF means the child process exited — stop the reader.
|
||||||
|
// Other errors (malformed frames) get a brief backoff then retry.
|
||||||
|
if err.to_string().contains("LSP stream closed (EOF)") {
|
||||||
|
eprintln!("LSP reader task: EOF detected, stopping reader");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -135,12 +172,14 @@ impl RustAnalyzer {
|
|||||||
Ok(v) => v,
|
Ok(v) => v,
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
eprintln!("Corrupted JSON received: {err}");
|
eprintln!("Corrupted JSON received: {err}");
|
||||||
continue; // Keep the connection running despite malformed frame
|
continue;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Filter server notification frames
|
let is_notification = value.get("method").is_some() && value.get("id").is_none();
|
||||||
if value.get("method").is_some() && value.get("id").is_none() {
|
|
||||||
|
if is_notification {
|
||||||
|
let _ = notification_tx.send(value);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -181,7 +220,6 @@ impl RustAnalyzer {
|
|||||||
|
|
||||||
let (tx, rx) = oneshot::channel();
|
let (tx, rx) = oneshot::channel();
|
||||||
|
|
||||||
// Scope the lock allocation tightly
|
|
||||||
{
|
{
|
||||||
self.pending.lock().await.insert(id, tx);
|
self.pending.lock().await.insert(id, tx);
|
||||||
}
|
}
|
||||||
@@ -193,19 +231,15 @@ impl RustAnalyzer {
|
|||||||
"params": params,
|
"params": params,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Acquire lock on writing stream to ensure thread safety
|
|
||||||
let mut stdin_lock = self.stdin.lock().await;
|
let mut stdin_lock = self.stdin.lock().await;
|
||||||
|
|
||||||
if let Err(err) = send_lsp_message(&mut *stdin_lock, &payload).await {
|
if let Err(err) = send_lsp_message(&mut *stdin_lock, &payload).await {
|
||||||
// Rollback the pending map operation to avoid internal memory memory-leaks if serialization/IO errors trigger
|
|
||||||
self.pending.lock().await.remove(&id);
|
self.pending.lock().await.remove(&id);
|
||||||
return Err(Box::new(err));
|
return Err(Box::new(err));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Explicit drop of write lock early so other operations can pipe messages synchronously
|
|
||||||
drop(stdin_lock);
|
drop(stdin_lock);
|
||||||
|
|
||||||
// Enforce an absolute time constraint limit to break free from hanging processes
|
|
||||||
let response_payload = match timeout(REQUEST_TIMEOUT, rx).await {
|
let response_payload = match timeout(REQUEST_TIMEOUT, rx).await {
|
||||||
Ok(Ok(Ok(value))) => value,
|
Ok(Ok(Ok(value))) => value,
|
||||||
Ok(Ok(Err(task_err))) => return Err(task_err.into()),
|
Ok(Ok(Err(task_err))) => return Err(task_err.into()),
|
||||||
@@ -215,7 +249,6 @@ impl RustAnalyzer {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
Err(_timeout_elapsed) => {
|
Err(_timeout_elapsed) => {
|
||||||
// Clear state tracking entries dynamically upon expiration failure
|
|
||||||
self.pending.lock().await.remove(&id);
|
self.pending.lock().await.remove(&id);
|
||||||
return Err(
|
return Err(
|
||||||
format!("Request ID {} timed out after {:?}", id, REQUEST_TIMEOUT).into(),
|
format!("Request ID {} timed out after {:?}", id, REQUEST_TIMEOUT).into(),
|
||||||
@@ -290,8 +323,68 @@ impl RustAnalyzer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn initialized(&mut self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
pub async fn initialized(&mut self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
self.notify(Initialized::METHOD, InitializedParams {})
|
self.notify(
|
||||||
.await?;
|
<Initialized as Notification>::METHOD,
|
||||||
|
InitializedParams {},
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl RustAnalyzer {
|
||||||
|
pub async fn did_open(
|
||||||
|
&mut self,
|
||||||
|
uri: Url,
|
||||||
|
text: &str,
|
||||||
|
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
self.notify(
|
||||||
|
"textDocument/didOpen",
|
||||||
|
json!({
|
||||||
|
"textDocument": {
|
||||||
|
"uri": uri,
|
||||||
|
"languageId": "rust",
|
||||||
|
"version": 1,
|
||||||
|
"text": text,
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn did_change(
|
||||||
|
&mut self,
|
||||||
|
uri: Url,
|
||||||
|
text: &str,
|
||||||
|
version: i32,
|
||||||
|
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
self.notify(
|
||||||
|
"textDocument/didChange",
|
||||||
|
json!({
|
||||||
|
"textDocument": {
|
||||||
|
"uri": uri,
|
||||||
|
"version": version,
|
||||||
|
},
|
||||||
|
"contentChanges": [{
|
||||||
|
"text": text,
|
||||||
|
}],
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn did_close(
|
||||||
|
&mut self,
|
||||||
|
uri: Url,
|
||||||
|
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
self.notify(
|
||||||
|
"textDocument/didClose",
|
||||||
|
json!({
|
||||||
|
"textDocument": {
|
||||||
|
"uri": uri,
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,160 +1,45 @@
|
|||||||
use std::{
|
use std::path::{Path, PathBuf};
|
||||||
fs,
|
|
||||||
path::{Path, PathBuf},
|
|
||||||
};
|
|
||||||
|
|
||||||
use mist_parser::{ast::TopLevel, error::ParseError};
|
use mist_codegen::RustCodegen;
|
||||||
|
use mist_parser::rev_mapper::Mapping;
|
||||||
|
use mist_parser::parse;
|
||||||
|
|
||||||
pub fn build(root: &PathBuf) {
|
pub struct TranspiledFile {
|
||||||
let src_dir = root.join("src");
|
pub mist_path: PathBuf,
|
||||||
let out_dir = root.join(".mist/lsp");
|
pub rust_path: PathBuf,
|
||||||
|
pub rust_content: String,
|
||||||
if let Err(e) = build_dir(root, &src_dir, &src_dir, &out_dir) {
|
pub mapping: Mapping,
|
||||||
eprintln!("Warning: Build directory run aborted safely: {e}");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn build_dir(
|
pub fn transpile_mist(
|
||||||
root: &Path,
|
mist_path: &Path,
|
||||||
base_src: &Path,
|
source: &str,
|
||||||
current_dir: &Path,
|
extra_mod_decl: &str,
|
||||||
out_dir: &Path,
|
) -> Result<TranspiledFile, String> {
|
||||||
) -> Result<(), String> {
|
let mut rust_path = crate::from_mist_to_rust(mist_path.to_path_buf());
|
||||||
let entries = fs::read_dir(current_dir)
|
// Package files (package.mist) must output as <dir>/mod.rs so the Rust module
|
||||||
.map_err(|e| format!("failed to read directory {}: {}", current_dir.display(), e))?;
|
// hierarchy resolves correctly (pub mod <child>; declarations look for sibling
|
||||||
|
// .rs files, and the parent module declaration looks for <dir>/mod.rs).
|
||||||
for entry in entries {
|
if mist_path.file_name().and_then(|n| n.to_str()) == Some("package.mist") {
|
||||||
let entry = match entry {
|
rust_path.set_file_name("mod.rs");
|
||||||
Ok(entry) => entry,
|
|
||||||
Err(e) => {
|
|
||||||
eprintln!("Warning: Skipping invalid directory entry: {e}");
|
|
||||||
continue; // Skip corrupted entry instead of crashing
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let path = entry.path();
|
|
||||||
|
|
||||||
// Recurse into nested directories
|
|
||||||
if path.is_dir() {
|
|
||||||
if let Err(e) = build_dir(root, base_src, &path, out_dir) {
|
|
||||||
eprintln!("Warning: Nested build directory failed: {e}");
|
|
||||||
}
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Safe prefix stripping fallback
|
|
||||||
let relative = match path.strip_prefix(base_src) {
|
|
||||||
Ok(p) => p,
|
|
||||||
Err(_) => {
|
|
||||||
eprintln!(
|
|
||||||
"Warning: Path {} is outside base source directory",
|
|
||||||
path.display()
|
|
||||||
);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Handle non-mist files with a cache check
|
|
||||||
if path.extension().and_then(|e| e.to_str()) != Some("mist") {
|
|
||||||
let dest_path = out_dir.join(relative);
|
|
||||||
|
|
||||||
// Create parent directories for static assets if needed
|
|
||||||
if let Some(parent) = dest_path.parent() {
|
|
||||||
let _ = fs::create_dir_all(parent);
|
|
||||||
}
|
|
||||||
|
|
||||||
if should_skip(&path, &dest_path) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Err(e) = fs::copy(&path, &dest_path) {
|
|
||||||
eprintln!(
|
|
||||||
"Warning: Failed to copy non-mist file {}: {}",
|
|
||||||
path.display(),
|
|
||||||
e
|
|
||||||
);
|
|
||||||
}
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
let output_path = out_dir.join(relative).with_extension("rs");
|
|
||||||
|
|
||||||
// Cache layer: Skip if the generated .rs file is newer than the .mist source
|
|
||||||
if should_skip(&path, &output_path) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Err(e) = transpile_file(&path, &output_path) {
|
|
||||||
eprintln!(
|
|
||||||
"Warning: Transpilation failed for {}: {}",
|
|
||||||
path.display(),
|
|
||||||
e
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
let parsed = parse(source).map_err(|e| format!("parse error: {e:?}"))?;
|
||||||
}
|
|
||||||
|
|
||||||
pub fn transpile_file(path: &Path, output_path: &Path) -> Result<(), String> {
|
for item in &parsed {
|
||||||
// Create parent directories
|
mist_parser::semantics::check_class_semantics(item)
|
||||||
if let Some(parent) = output_path.parent() {
|
.map_err(|e| format!("semantic error: {}", e[0].error_message))?;
|
||||||
fs::create_dir_all(parent).map_err(|e| {
|
|
||||||
format!(
|
|
||||||
"failed to create output directory {}: {}",
|
|
||||||
parent.display(),
|
|
||||||
e
|
|
||||||
)
|
|
||||||
})?;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read source
|
let mut codegen = RustCodegen::new(mist_path.to_path_buf());
|
||||||
let source = fs::read_to_string(path)
|
let output = codegen.generate(parsed);
|
||||||
.map_err(|e| format!("failed to read file {}: {}", path.display(), e))?;
|
|
||||||
|
|
||||||
let parser_result = mist_parser::parse(&source).map_err(|e| match e {
|
codegen.mapping.shift_rust(extra_mod_decl.lines().count() as isize, 0);
|
||||||
ParseError::Ast(e) => {
|
|
||||||
// Using components carefully to prevent out-of-bounds or zero layout crashes
|
|
||||||
let start_pos = e.span.start_pos().line_col();
|
|
||||||
let span = e.span.as_str();
|
|
||||||
|
|
||||||
format!(
|
Ok(TranspiledFile {
|
||||||
"\n{}:{}:{}\n Error: {}\n\t{}{}\t{}",
|
mist_path: mist_path.to_path_buf(),
|
||||||
path.display(),
|
rust_path,
|
||||||
start_pos.0,
|
rust_content: format!("{}{}", extra_mod_decl, output),
|
||||||
start_pos.1,
|
mapping: codegen.mapping,
|
||||||
e.error_message,
|
})
|
||||||
span,
|
|
||||||
if span.ends_with('\n') { "" } else { "\n" },
|
|
||||||
"^".repeat(span.trim().len()),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
ParseError::PreAst(e) => format!("{e}"),
|
|
||||||
});
|
|
||||||
|
|
||||||
// If parsing fails, return the error string back gracefully so the LSP can show it
|
|
||||||
let ast = parser_result.map_err(|e| format!("parse failed in {}:\n{}", path.display(), e))?;
|
|
||||||
|
|
||||||
let mut gc = mist_codegen::RustCodegen::new();
|
|
||||||
let output = gc.generate(ast);
|
|
||||||
|
|
||||||
fs::write(output_path, output)
|
|
||||||
.map_err(|e| format!("failed to write output {}: {}", output_path.display(), e))?;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn transpile_text<'a>(source: &'a str) -> Result<String, ParseError<'a, Vec<TopLevel>>> {
|
|
||||||
let mut gc = mist_codegen::RustCodegen::new();
|
|
||||||
|
|
||||||
Ok(gc.generate(mist_parser::parse(&source)?))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn should_skip(source: &Path, output: &Path) -> bool {
|
|
||||||
if let (Ok(src_meta), Ok(out_meta)) = (fs::metadata(source), fs::metadata(output)) {
|
|
||||||
if let (Ok(src_time), Ok(out_time)) = (src_meta.modified(), out_meta.modified()) {
|
|
||||||
return out_time >= src_time;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
false
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "mist-codegen"
|
name = "mist-codegen"
|
||||||
version = "0.1.2"
|
version = "0.3.5-alpha.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
description = "The Mist programming language Rust code generator"
|
description = "The Mist programming language Rust code generator"
|
||||||
license = "Apache-2.0"
|
license = "Apache-2.0"
|
||||||
@@ -9,4 +9,5 @@ keywords = ["compiler", "language", "mist"]
|
|||||||
categories = ["compilers"]
|
categories = ["compilers"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
bytecount = "0.6.9"
|
||||||
mist-parser = { workspace = true }
|
mist-parser = { workspace = true }
|
||||||
|
|||||||
@@ -0,0 +1,620 @@
|
|||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use mist_parser::ast::*;
|
||||||
|
|
||||||
|
use crate::{Context, GenRust, GenSpanTranslation, GetRust, RustCodegen};
|
||||||
|
|
||||||
|
pub struct ClassProcessedData {
|
||||||
|
visibility: Visibility,
|
||||||
|
name: Identifier,
|
||||||
|
generics: GenericsDecl,
|
||||||
|
inherits: Option<ExprPath>,
|
||||||
|
self_path: ExprPath,
|
||||||
|
self_ty: TypeExpr,
|
||||||
|
fields: Vec<Spanned<FieldDeclStmt>>,
|
||||||
|
constructor: Option<Spanned<ClassConstructor>>,
|
||||||
|
items: Vec<ClassItem>,
|
||||||
|
methods: Vec<Spanned<FunctionDecl>>,
|
||||||
|
v_table: Vec<Identifier>,
|
||||||
|
override_v_table: HashMap<Override, Spanned<Vec<Identifier>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ClassProcessedData {
|
||||||
|
pub fn analyze(
|
||||||
|
visibility: &Visibility,
|
||||||
|
name: &Identifier,
|
||||||
|
generics: &GenericsDecl,
|
||||||
|
inherits: &Option<ExprPath>,
|
||||||
|
fields: &Vec<Spanned<FieldDeclStmt>>,
|
||||||
|
constructor: &Option<Spanned<ClassConstructor>>,
|
||||||
|
items: &Vec<ClassItem>,
|
||||||
|
) -> Self {
|
||||||
|
let self_path = ExprPath(vec![ExprPathSegment {
|
||||||
|
ident: name.clone(),
|
||||||
|
generics: generics.clone().into(),
|
||||||
|
}]);
|
||||||
|
|
||||||
|
let self_ty = get_type_from_path(&self_path);
|
||||||
|
|
||||||
|
let methods = items
|
||||||
|
.iter()
|
||||||
|
.filter_map(|item| match item {
|
||||||
|
ClassItem::ImplDecl(_) => None,
|
||||||
|
ClassItem::Method(method) => Some(method.clone()),
|
||||||
|
})
|
||||||
|
.collect::<Vec<Spanned<FunctionDecl>>>();
|
||||||
|
|
||||||
|
let mut v_table = Vec::new();
|
||||||
|
let mut override_v_table = std::collections::HashMap::new();
|
||||||
|
|
||||||
|
for method in &methods {
|
||||||
|
if matches!(method.item.visibility, Visibility::Public) {
|
||||||
|
match &method.item.is_override {
|
||||||
|
None => {
|
||||||
|
if method.item.is_using_self() {
|
||||||
|
v_table.push(method.item.name.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(override_spec) => {
|
||||||
|
override_v_table
|
||||||
|
.entry(override_spec.clone())
|
||||||
|
.or_insert_with(|| Spanned {
|
||||||
|
line: method.line,
|
||||||
|
column: method.column,
|
||||||
|
item: Vec::new(),
|
||||||
|
})
|
||||||
|
.item
|
||||||
|
.push(method.item.name.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ClassProcessedData {
|
||||||
|
visibility: visibility.clone(),
|
||||||
|
name: name.clone(),
|
||||||
|
generics: generics.clone(),
|
||||||
|
inherits: inherits.clone(),
|
||||||
|
self_path,
|
||||||
|
self_ty,
|
||||||
|
fields: fields.clone(),
|
||||||
|
constructor: constructor.clone(),
|
||||||
|
items: items.clone(),
|
||||||
|
methods,
|
||||||
|
v_table,
|
||||||
|
override_v_table,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Stage 2: Code Emission ───────────────────────────────────────
|
||||||
|
|
||||||
|
pub fn emit(&self, ctx: &mut Context, cg: &mut RustCodegen) {
|
||||||
|
ctx.expr_super = self.inherits.clone();
|
||||||
|
|
||||||
|
self.emit_struct_decl(cg);
|
||||||
|
self.emit_impl_block(ctx, cg);
|
||||||
|
self.emit_impl_decls(ctx, cg);
|
||||||
|
self.emit_deref_impls(cg);
|
||||||
|
|
||||||
|
ctx.expr_super = None;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn emit_struct_decl(&self, cg: &mut RustCodegen) {
|
||||||
|
cg.addln(&format!(
|
||||||
|
"{}struct {}{} {{",
|
||||||
|
self.visibility.get_rust(),
|
||||||
|
self.name.get_rust(),
|
||||||
|
self.generics.get_rust()
|
||||||
|
));
|
||||||
|
cg.indent += 1;
|
||||||
|
|
||||||
|
if let Some(ref inherits) = self.inherits {
|
||||||
|
cg.add_indented("pub _super: ");
|
||||||
|
cg.add(&get_type_from_path(inherits).get_rust());
|
||||||
|
cg.addln(",");
|
||||||
|
} else {
|
||||||
|
cg.add_indentedln("pub _vptr: &'static [*const std::ffi::c_void],");
|
||||||
|
}
|
||||||
|
|
||||||
|
for field in &self.fields {
|
||||||
|
field.gen_span(cg);
|
||||||
|
cg.add_indentedln(&field.item.decl.get_rust());
|
||||||
|
}
|
||||||
|
|
||||||
|
cg.indent -= 1;
|
||||||
|
cg.addln("}\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn emit_impl_block(&self, ctx: &mut Context, cg: &mut RustCodegen) {
|
||||||
|
cg.addln(&format!(
|
||||||
|
"impl{} {} {{",
|
||||||
|
self.generics.get_rust(),
|
||||||
|
self.self_ty.get_rust()
|
||||||
|
));
|
||||||
|
cg.indent += 1;
|
||||||
|
|
||||||
|
self.emit_unified_vtable(cg);
|
||||||
|
self.emit_super_v_tests(cg);
|
||||||
|
|
||||||
|
if let Some(constructor) = &self.constructor {
|
||||||
|
self.emit_constructor(constructor, ctx, cg);
|
||||||
|
}
|
||||||
|
self.emit_methods(ctx, cg);
|
||||||
|
|
||||||
|
cg.indent -= 1;
|
||||||
|
cg.addln("}\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn emit_unified_vtable(&self, cg: &mut RustCodegen) {
|
||||||
|
let has_parent = self.inherits.is_some();
|
||||||
|
let parent_path = self
|
||||||
|
.inherits
|
||||||
|
.as_ref()
|
||||||
|
.map(|p| p.get_rust())
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
if has_parent {
|
||||||
|
cg.add_indentedln(&format!(
|
||||||
|
"pub const __PARENT_V_COUNT: usize = {}::__V_COUNT;",
|
||||||
|
parent_path
|
||||||
|
));
|
||||||
|
} else {
|
||||||
|
cg.add_indentedln("pub const __PARENT_V_COUNT: usize = 0;");
|
||||||
|
}
|
||||||
|
|
||||||
|
for (i, method_name) in self.v_table.iter().enumerate() {
|
||||||
|
cg.add_indentedln(&format!(
|
||||||
|
"pub const __FN_{}: usize = Self::__PARENT_V_COUNT + {i};",
|
||||||
|
method_name.0.to_uppercase()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
cg.add_indentedln(&format!(
|
||||||
|
"pub const __V_COUNT: usize = Self::__PARENT_V_COUNT + {};",
|
||||||
|
self.v_table.len()
|
||||||
|
));
|
||||||
|
|
||||||
|
cg.add_indentedln("pub const __V_TABLE: &'static [*const std::ffi::c_void] = &{");
|
||||||
|
cg.indent += 1;
|
||||||
|
|
||||||
|
if has_parent {
|
||||||
|
cg.add_indentedln("let mut table = [std::ptr::null(); Self::__V_COUNT];");
|
||||||
|
|
||||||
|
cg.add_indentedln(&format!("let parent_table = {}::__V_TABLE;", parent_path));
|
||||||
|
cg.add_indentedln(
|
||||||
|
"let mut i = 0; while i < Self::__PARENT_V_COUNT {{ table[i] = parent_table[i]; i += 1; }}",
|
||||||
|
);
|
||||||
|
|
||||||
|
for (override_tier, overriden_method_idents) in &self.override_v_table {
|
||||||
|
let base_class_path = override_tier
|
||||||
|
.0
|
||||||
|
.as_ref()
|
||||||
|
.unwrap_or(self.inherits.as_ref().unwrap())
|
||||||
|
.get_rust();
|
||||||
|
for method_ident in &overriden_method_idents.item {
|
||||||
|
cg.add_indentedln(&format!(
|
||||||
|
"table[{}::__FN_{}] = {}::__m_{} as *const std::ffi::c_void;",
|
||||||
|
base_class_path,
|
||||||
|
method_ident.0.to_uppercase(),
|
||||||
|
self.self_path.get_rust(),
|
||||||
|
method_ident.get_rust()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for method_name in &self.v_table {
|
||||||
|
cg.add_indentedln(&format!(
|
||||||
|
"table[Self::__FN_{}] = Self::__m_{} as *const std::ffi::c_void;",
|
||||||
|
method_name.0.to_uppercase(),
|
||||||
|
method_name.get_rust()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
cg.add_indentedln("table");
|
||||||
|
} else {
|
||||||
|
cg.add_indentedln("[");
|
||||||
|
cg.indent += 1;
|
||||||
|
for method_name in &self.v_table {
|
||||||
|
cg.add_indentedln(&format!(
|
||||||
|
"Self::__m_{} as *const std::ffi::c_void,",
|
||||||
|
method_name.get_rust()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
cg.indent -= 1;
|
||||||
|
cg.add_indentedln("]");
|
||||||
|
}
|
||||||
|
|
||||||
|
cg.indent -= 1;
|
||||||
|
cg.add_indentedln("};");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn emit_super_v_tests(&self, cg: &mut RustCodegen) {
|
||||||
|
cg.add_indentedln("#[allow(invalid_value)]");
|
||||||
|
cg.add_indentedln(&format!("fn __test_vt() {{"));
|
||||||
|
cg.indent += 1;
|
||||||
|
|
||||||
|
for (override_tier, _) in self.override_v_table.iter() {
|
||||||
|
let target_path = match &override_tier.0 {
|
||||||
|
Some(path) => path.clone(),
|
||||||
|
|
||||||
|
None => {
|
||||||
|
if let Some(parent_path) = &self.inherits {
|
||||||
|
parent_path.clone()
|
||||||
|
} else {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let target_rust_path = target_path.get_rust();
|
||||||
|
|
||||||
|
for method in &self.methods {
|
||||||
|
if method.item.is_override.as_ref() == Some(override_tier) {
|
||||||
|
let mut params = method
|
||||||
|
.item
|
||||||
|
.params
|
||||||
|
.0
|
||||||
|
.clone()
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|v| v.type_)
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
|
if params.is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let TypeExpr::Ref { mutable, .. } = params.remove(0) {
|
||||||
|
method.gen_span(cg);
|
||||||
|
cg.add_indented(&format!("{}::__m_", target_rust_path));
|
||||||
|
cg.add(&method.item.name.get_rust());
|
||||||
|
cg.add(" as ");
|
||||||
|
|
||||||
|
params.insert(
|
||||||
|
0,
|
||||||
|
TypeExpr::Ref {
|
||||||
|
lifetime: None,
|
||||||
|
mutable,
|
||||||
|
ty: Box::new(get_type_from_path(&target_path)),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
cg.add(
|
||||||
|
&TypeExpr::StaticFn(
|
||||||
|
params,
|
||||||
|
method.item.return_type.clone().map(Box::new),
|
||||||
|
)
|
||||||
|
.get_rust(),
|
||||||
|
);
|
||||||
|
cg.addln(";");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deref tests for override targets
|
||||||
|
if self.inherits.is_some() && !self.override_v_table.is_empty() {
|
||||||
|
cg.add_indentedln("let this: &Self = &unsafe { std::mem::MaybeUninit::<Self>::zeroed().assume_init() };");
|
||||||
|
|
||||||
|
for (override_tier, v) in &self.override_v_table {
|
||||||
|
if let Some(path) = &override_tier.0 {
|
||||||
|
v.gen_span(cg);
|
||||||
|
// This forces the compiler to statically verify that &Self can Deref into &Target
|
||||||
|
cg.add_indentedln(&format!("let _: &{} = this;", path.get_rust()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
cg.indent -= 1;
|
||||||
|
cg.add_indentedln("}");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn emit_constructor(
|
||||||
|
&self,
|
||||||
|
constructor: &Spanned<ClassConstructor>,
|
||||||
|
ctx: &mut Context,
|
||||||
|
cg: &mut RustCodegen,
|
||||||
|
) {
|
||||||
|
cg.add_indentedln("#[allow(invalid_value)]");
|
||||||
|
constructor.gen_span(cg);
|
||||||
|
|
||||||
|
cg.add_indented(&format!(
|
||||||
|
"{}fn new{}(",
|
||||||
|
constructor.item.visibility.get_rust(),
|
||||||
|
constructor.item.generics.get_rust()
|
||||||
|
));
|
||||||
|
|
||||||
|
let params = constructor
|
||||||
|
.item
|
||||||
|
.params
|
||||||
|
.0
|
||||||
|
.clone()
|
||||||
|
.into_iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(idx, mut v)| {
|
||||||
|
v.name = construct_pattern(&v.name, idx);
|
||||||
|
(idx, v)
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
|
for (i, param) in ¶ms {
|
||||||
|
if *i > 0 {
|
||||||
|
cg.add(", ");
|
||||||
|
}
|
||||||
|
param.gen_rust(ctx, cg);
|
||||||
|
}
|
||||||
|
|
||||||
|
cg.addln(") -> Self {");
|
||||||
|
cg.indent += 1;
|
||||||
|
|
||||||
|
cg.add_indentedln("let mut this: Self = unsafe { std::mem::MaybeUninit::<Self>::zeroed().assume_init() };");
|
||||||
|
cg.add_indentedln("this._vptr = &Self::__V_TABLE;");
|
||||||
|
|
||||||
|
for field in &self.fields {
|
||||||
|
if let Some(init) = &field.item.init {
|
||||||
|
field.gen_span(cg);
|
||||||
|
cg.add_indentedln(&format!("this.{} = ", field.item.decl.name.get_rust()));
|
||||||
|
init.gen_rust(ctx, cg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
cg.add_indented("this.constructor(");
|
||||||
|
for (i, param) in ¶ms {
|
||||||
|
if *i > 0 {
|
||||||
|
cg.add(", ");
|
||||||
|
}
|
||||||
|
ctx.expr_ensure_semicolon = false;
|
||||||
|
param.name.gen_rust(ctx, cg);
|
||||||
|
}
|
||||||
|
cg.addln(");");
|
||||||
|
|
||||||
|
cg.add_indentedln("this._vptr = &Self::__V_TABLE;");
|
||||||
|
|
||||||
|
constructor.gen_span(cg);
|
||||||
|
|
||||||
|
cg.add_indentedln("this");
|
||||||
|
cg.indent -= 1;
|
||||||
|
cg.add_indentedln("}\n");
|
||||||
|
|
||||||
|
let mut constructor_params = vec![VarDecl {
|
||||||
|
name: Pattern::Path(false, Path(vec![Identifier(String::from("self"))])),
|
||||||
|
type_: Some(TypeExpr::Ref {
|
||||||
|
lifetime: None,
|
||||||
|
mutable: true,
|
||||||
|
ty: Box::new(TypeExpr::Path(
|
||||||
|
Path(vec![Identifier(String::from("Self"))]),
|
||||||
|
None,
|
||||||
|
)),
|
||||||
|
}),
|
||||||
|
}];
|
||||||
|
|
||||||
|
constructor_params.append(&mut constructor.item.params.0.clone());
|
||||||
|
|
||||||
|
Spanned {
|
||||||
|
line: constructor.line,
|
||||||
|
column: constructor.column,
|
||||||
|
item: FunctionDecl {
|
||||||
|
visibility: constructor.item.visibility.clone(),
|
||||||
|
is_override: None,
|
||||||
|
name: Identifier(String::from("constructor")),
|
||||||
|
generics: constructor.item.generics.clone(),
|
||||||
|
params: ParamList(constructor_params),
|
||||||
|
return_type: Some(TypeExpr::Tuple(Vec::new())),
|
||||||
|
body: Some(constructor.item.body.clone()),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
.gen_rust(ctx, cg);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn emit_methods(&self, ctx: &mut Context, cg: &mut RustCodegen) {
|
||||||
|
for method in &self.methods {
|
||||||
|
match method.item.visibility {
|
||||||
|
Visibility::Public => {
|
||||||
|
if method.item.is_using_self() {
|
||||||
|
if method.item.is_override.is_none() {
|
||||||
|
gen_method_point(&method.item, ctx, cg);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut prefixed = method.clone();
|
||||||
|
prefixed.item.name.0.insert_str(0, "__m_");
|
||||||
|
prefixed.gen_rust(ctx, cg);
|
||||||
|
} else {
|
||||||
|
method.gen_rust(ctx, cg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
method.gen_rust(ctx, cg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn emit_impl_decls(&self, ctx: &mut Context, cg: &mut RustCodegen) {
|
||||||
|
for item in &self.items {
|
||||||
|
if let ClassItem::ImplDecl(impl_) = item {
|
||||||
|
let mut impl_ = impl_.clone();
|
||||||
|
impl_.item.trait_ = Some(impl_.item.target);
|
||||||
|
impl_.item.target = TypeExpr::Path(Path(vec![self.name.clone()]), None);
|
||||||
|
impl_.gen_rust(ctx, cg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn emit_deref_impls(&self, cg: &mut RustCodegen) {
|
||||||
|
if let Some(ref inherits) = self.inherits {
|
||||||
|
let generics_str = self.generics.get_rust();
|
||||||
|
let generics_expr_str = Generics::from(self.generics.clone()).get_rust();
|
||||||
|
|
||||||
|
cg.add(&format!(
|
||||||
|
"impl{} std::ops::Deref for {}{}",
|
||||||
|
generics_str,
|
||||||
|
self.name.get_rust(),
|
||||||
|
generics_expr_str
|
||||||
|
));
|
||||||
|
|
||||||
|
cg.addln(" {");
|
||||||
|
cg.indent += 1;
|
||||||
|
|
||||||
|
cg.add_indented("type Target = ");
|
||||||
|
cg.add(&inherits.get_rust());
|
||||||
|
cg.addln(";");
|
||||||
|
|
||||||
|
cg.add_indentedln("fn deref(&self) -> &Self::Target { &self._super }");
|
||||||
|
|
||||||
|
cg.indent -= 1;
|
||||||
|
cg.addln("}");
|
||||||
|
|
||||||
|
cg.add(&format!(
|
||||||
|
"impl{} std::ops::DerefMut for {}{}",
|
||||||
|
generics_str,
|
||||||
|
self.name.get_rust(),
|
||||||
|
generics_expr_str
|
||||||
|
));
|
||||||
|
|
||||||
|
cg.addln(" {");
|
||||||
|
cg.indent += 1;
|
||||||
|
|
||||||
|
cg.add_indentedln("fn deref_mut(&mut self) -> &mut Self::Target { &mut self._super }");
|
||||||
|
|
||||||
|
cg.indent -= 1;
|
||||||
|
cg.addln("}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn class_decl(
|
||||||
|
ctx: &mut Context,
|
||||||
|
cg: &mut RustCodegen,
|
||||||
|
visibility: &Visibility,
|
||||||
|
name: &Identifier,
|
||||||
|
generics: &GenericsDecl,
|
||||||
|
inherits: &Option<ExprPath>,
|
||||||
|
fields: &Vec<Spanned<FieldDeclStmt>>,
|
||||||
|
constructor: &Option<Spanned<ClassConstructor>>,
|
||||||
|
items: &Vec<ClassItem>,
|
||||||
|
) {
|
||||||
|
let data = ClassProcessedData::analyze(
|
||||||
|
visibility,
|
||||||
|
name,
|
||||||
|
generics,
|
||||||
|
inherits,
|
||||||
|
fields,
|
||||||
|
constructor,
|
||||||
|
items,
|
||||||
|
);
|
||||||
|
data.emit(ctx, cg);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn construct_pattern(pat: &Pattern, idx: usize) -> Pattern {
|
||||||
|
match pat {
|
||||||
|
Pattern::Literal(v) => Pattern::Literal(v.clone()),
|
||||||
|
Pattern::Path(is_mut, v) => Pattern::Path(*is_mut, v.clone().into()),
|
||||||
|
_ => Pattern::Path(false, Path(vec![Identifier(format!("_{idx}"))])),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn gen_method_point(method: &FunctionDecl, ctx: &mut Context, cg: &mut RustCodegen) {
|
||||||
|
cg.add_indented(&format!(
|
||||||
|
"{}fn {}{}(",
|
||||||
|
method.visibility.get_rust(),
|
||||||
|
method.name.get_rust(),
|
||||||
|
method.generics.get_rust(),
|
||||||
|
));
|
||||||
|
|
||||||
|
let params = method
|
||||||
|
.params
|
||||||
|
.0
|
||||||
|
.clone()
|
||||||
|
.into_iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(idx, mut v)| {
|
||||||
|
v.name = construct_pattern(&v.name, idx);
|
||||||
|
(idx, v)
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
|
for (i, param) in ¶ms {
|
||||||
|
if *i > 0 {
|
||||||
|
cg.add(", ");
|
||||||
|
}
|
||||||
|
param.gen_rust(ctx, cg);
|
||||||
|
}
|
||||||
|
|
||||||
|
cg.add(") ");
|
||||||
|
if let Some(return_type) = &method.return_type {
|
||||||
|
cg.add("-> ");
|
||||||
|
cg.add(&return_type.get_rust());
|
||||||
|
}
|
||||||
|
|
||||||
|
cg.addln("{");
|
||||||
|
cg.indent += 1;
|
||||||
|
|
||||||
|
cg.add_indentedln("unsafe {");
|
||||||
|
cg.indent += 1;
|
||||||
|
|
||||||
|
cg.add_indentedln(&format!(
|
||||||
|
"let func_ptr = self._vptr[Self::__FN_{}];",
|
||||||
|
method.name.0.to_uppercase()
|
||||||
|
));
|
||||||
|
|
||||||
|
cg.add_indented("let func: ");
|
||||||
|
|
||||||
|
let mut param_types: Vec<TypeExpr> = method
|
||||||
|
.params
|
||||||
|
.clone()
|
||||||
|
.0
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|v| v.type_)
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let TypeExpr::Ref { mutable, .. } = param_types.remove(0) else {
|
||||||
|
panic!("")
|
||||||
|
};
|
||||||
|
|
||||||
|
param_types.insert(
|
||||||
|
0,
|
||||||
|
TypeExpr::UnsafePtr {
|
||||||
|
mutable,
|
||||||
|
ty: Box::new(TypeExpr::Path(
|
||||||
|
Path(vec![
|
||||||
|
Identifier(String::from("std")),
|
||||||
|
Identifier(String::from("ffi")),
|
||||||
|
Identifier(String::from("c_void")),
|
||||||
|
]),
|
||||||
|
None,
|
||||||
|
)),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
cg.add(&TypeExpr::StaticFn(param_types, method.return_type.clone().map(Box::new)).get_rust());
|
||||||
|
cg.addln(" = std::mem::transmute(func_ptr);");
|
||||||
|
|
||||||
|
if mutable {
|
||||||
|
cg.add_indented("func(self as *mut Self as *const std::ffi::c_void");
|
||||||
|
} else {
|
||||||
|
cg.add_indented("func(self as *const Self as *const std::ffi::c_void");
|
||||||
|
}
|
||||||
|
|
||||||
|
for (i, param) in ¶ms {
|
||||||
|
if *i == 0 {
|
||||||
|
continue; // self already fulfills it
|
||||||
|
}
|
||||||
|
cg.add(", ");
|
||||||
|
ctx.expr_ensure_semicolon = false;
|
||||||
|
param.name.gen_rust(ctx, cg);
|
||||||
|
}
|
||||||
|
|
||||||
|
cg.addln(")");
|
||||||
|
|
||||||
|
cg.indent -= 1;
|
||||||
|
cg.add_indentedln("}");
|
||||||
|
|
||||||
|
cg.indent -= 1;
|
||||||
|
cg.add_indentedln("}");
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_type_from_path(path: &ExprPath) -> TypeExpr {
|
||||||
|
TypeExpr::Path(
|
||||||
|
Path(path.0.iter().map(|v| v.ident.clone()).collect::<Vec<_>>()),
|
||||||
|
path.0.last().unwrap().generics.clone(),
|
||||||
|
)
|
||||||
|
}
|
||||||
+99
-73
@@ -12,6 +12,20 @@ impl GetRust for ExprPath {
|
|||||||
.collect::<Vec<_>>()
|
.collect::<Vec<_>>()
|
||||||
.join("::")
|
.join("::")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn get_rust_ctx(&self, cx: &mut Context) -> String {
|
||||||
|
let mut a = self.clone();
|
||||||
|
|
||||||
|
if let Some(path) = &cx.expr_super {
|
||||||
|
if self.0[0].ident.0 == "super" && self.0.len() == 1 {
|
||||||
|
a.0[0].ident.0 = String::from("self._super");
|
||||||
|
} else if self.0[0].ident.0 == "Super" {
|
||||||
|
a.0[0] = path.0[0].clone();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
a.get_rust()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl GetRust for ExprPathSegment {
|
impl GetRust for ExprPathSegment {
|
||||||
@@ -38,30 +52,16 @@ impl GenRust for Literal {
|
|||||||
Self::Tuple(values) => {
|
Self::Tuple(values) => {
|
||||||
cg.add("(");
|
cg.add("(");
|
||||||
|
|
||||||
for val in values {
|
for (i, val) in values.iter().enumerate() {
|
||||||
|
if i > 0 {
|
||||||
|
cg.add(", ");
|
||||||
|
}
|
||||||
|
|
||||||
val.gen_rust(ctx, cg);
|
val.gen_rust(ctx, cg);
|
||||||
}
|
}
|
||||||
|
|
||||||
cg.add(")");
|
cg.add(")");
|
||||||
}
|
}
|
||||||
|
|
||||||
Self::Array(values) => {
|
|
||||||
cg.add("[");
|
|
||||||
|
|
||||||
for val in values {
|
|
||||||
val.gen_rust(ctx, cg);
|
|
||||||
}
|
|
||||||
|
|
||||||
cg.add("]");
|
|
||||||
}
|
|
||||||
|
|
||||||
Self::ArrayRepeat(value, repeat) => {
|
|
||||||
cg.add("[");
|
|
||||||
value.gen_rust(ctx, cg);
|
|
||||||
cg.add("; ");
|
|
||||||
repeat.gen_rust(ctx, cg);
|
|
||||||
cg.add("]");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -77,9 +77,29 @@ impl GenRust for Expression {
|
|||||||
};
|
};
|
||||||
|
|
||||||
match self {
|
match self {
|
||||||
Expression::Path(path) => cg.add(&path.get_rust()),
|
Expression::Path(path) => cg.add(&path.get_rust_ctx(ctx)),
|
||||||
Expression::Literal(literal) => literal.gen_rust(ctx, cg),
|
Expression::Literal(literal) => literal.gen_rust(ctx, cg),
|
||||||
Expression::Statement(stmt) => stmt.gen_rust(ctx, cg),
|
Expression::Statement(stmt) => stmt.gen_rust(ctx, cg),
|
||||||
|
Expression::Array(values) => {
|
||||||
|
cg.add("[");
|
||||||
|
|
||||||
|
for (i, val) in values.iter().enumerate() {
|
||||||
|
if i > 0 {
|
||||||
|
cg.add(", ");
|
||||||
|
}
|
||||||
|
|
||||||
|
val.gen_rust(ctx, cg);
|
||||||
|
}
|
||||||
|
|
||||||
|
cg.add("]");
|
||||||
|
}
|
||||||
|
Expression::ArrayRepeat(value, repeat) => {
|
||||||
|
cg.add("[");
|
||||||
|
value.gen_rust(ctx, cg);
|
||||||
|
cg.add("; ");
|
||||||
|
repeat.gen_rust(ctx, cg);
|
||||||
|
cg.add("]");
|
||||||
|
}
|
||||||
Expression::Fix {
|
Expression::Fix {
|
||||||
initial,
|
initial,
|
||||||
prefixes,
|
prefixes,
|
||||||
@@ -87,16 +107,49 @@ impl GenRust for Expression {
|
|||||||
} => {
|
} => {
|
||||||
prefixes.gen_rust(ctx, cg);
|
prefixes.gen_rust(ctx, cg);
|
||||||
initial.gen_rust(ctx, cg);
|
initial.gen_rust(ctx, cg);
|
||||||
cg.add(&Some(prefixes).get_rust());
|
|
||||||
for postfix in postfixes {
|
for postfix in postfixes {
|
||||||
postfix.gen_rust(ctx, cg);
|
postfix.gen_rust(ctx, cg);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Safely integrated to handle the tree structure built by the Pratt Parser
|
|
||||||
Expression::Binary { lhs, op, rhs } => {
|
Expression::Binary { lhs, op, rhs } => {
|
||||||
lhs.gen_rust(ctx, cg);
|
if op == "->" {
|
||||||
cg.add(op);
|
cg.add("unsafe { std::ptr::write(&mut ");
|
||||||
rhs.gen_rust(ctx, cg);
|
lhs.gen_rust(ctx, cg);
|
||||||
|
cg.add(", ");
|
||||||
|
rhs.gen_rust(ctx, cg);
|
||||||
|
cg.add(") }");
|
||||||
|
} else {
|
||||||
|
lhs.gen_rust(ctx, cg);
|
||||||
|
cg.add(op);
|
||||||
|
rhs.gen_rust(ctx, cg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Expression::Closure {
|
||||||
|
return_type,
|
||||||
|
params,
|
||||||
|
body,
|
||||||
|
} => {
|
||||||
|
cg.add("|");
|
||||||
|
for (i, arg) in params.iter().enumerate() {
|
||||||
|
if i > 0 {
|
||||||
|
cg.add(", ");
|
||||||
|
}
|
||||||
|
|
||||||
|
arg.gen_rust(ctx, cg);
|
||||||
|
}
|
||||||
|
cg.add("| ");
|
||||||
|
|
||||||
|
if let Some(ty) = return_type {
|
||||||
|
cg.add("-> ");
|
||||||
|
cg.add(&ty.get_rust());
|
||||||
|
cg.add(" ");
|
||||||
|
|
||||||
|
cg.ensure_brackets_expr(ctx, body);
|
||||||
|
} else {
|
||||||
|
body.gen_rust(ctx, cg);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -111,31 +164,13 @@ impl GenRust for Expression {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl GenRust for Prefix {
|
impl GenRust for Prefix {
|
||||||
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
|
fn gen_rust(&self, _ctx: &mut Context, cg: &mut RustCodegen) {
|
||||||
match self {
|
match self {
|
||||||
Self::Deref => cg.add("*"),
|
Self::Deref => cg.add("*"),
|
||||||
Self::Ref => cg.add("&"),
|
Self::Ref => cg.add("&"),
|
||||||
Self::RefMut => cg.add("&mut "),
|
Self::RefMut => cg.add("&mut "),
|
||||||
Self::Not => cg.add("!"),
|
Self::Not => cg.add("!"),
|
||||||
Self::New(_) => cg.add(""),
|
|
||||||
Self::Neg => cg.add("-"),
|
Self::Neg => cg.add("-"),
|
||||||
Self::Closure(ty, args) => {
|
|
||||||
cg.add("|");
|
|
||||||
for (i, arg) in args.iter().enumerate() {
|
|
||||||
if i > 0 {
|
|
||||||
cg.add(", ");
|
|
||||||
}
|
|
||||||
|
|
||||||
arg.gen_rust(ctx, cg);
|
|
||||||
}
|
|
||||||
cg.add("| ");
|
|
||||||
|
|
||||||
if let Some(ty) = ty {
|
|
||||||
cg.add("-> ");
|
|
||||||
cg.add(&ty.get_rust());
|
|
||||||
cg.add(" ");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -148,33 +183,17 @@ impl GenRust for Vec<Prefix> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl GetRust for Option<&Vec<Prefix>> {
|
|
||||||
fn get_rust(&self) -> String {
|
|
||||||
if let Some(prefixes) = self {
|
|
||||||
prefixes
|
|
||||||
.into_iter()
|
|
||||||
.last()
|
|
||||||
.map(|p| match p {
|
|
||||||
Prefix::New(generics) => format!(
|
|
||||||
"::new{}",
|
|
||||||
generics
|
|
||||||
.clone()
|
|
||||||
.map(|v| format!("::{}", v.get_rust()))
|
|
||||||
.unwrap_or_default(),
|
|
||||||
),
|
|
||||||
_ => String::new(),
|
|
||||||
})
|
|
||||||
.unwrap_or_default()
|
|
||||||
.to_string()
|
|
||||||
} else {
|
|
||||||
String::new()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl GenRust for Postfix {
|
impl GenRust for Postfix {
|
||||||
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
|
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
|
||||||
match self {
|
match self {
|
||||||
|
Postfix::TupleFieldAccess(field, generics) => cg.add(&format!(
|
||||||
|
".{}{}",
|
||||||
|
field,
|
||||||
|
generics
|
||||||
|
.iter()
|
||||||
|
.map(|v| format!("::{}", v.get_rust()))
|
||||||
|
.collect::<String>()
|
||||||
|
)),
|
||||||
Postfix::FieldAccess(field, generics) => cg.add(&format!(
|
Postfix::FieldAccess(field, generics) => cg.add(&format!(
|
||||||
".{}{}",
|
".{}{}",
|
||||||
field.get_rust(),
|
field.get_rust(),
|
||||||
@@ -198,10 +217,15 @@ impl GenRust for Postfix {
|
|||||||
cg.add(")");
|
cg.add(")");
|
||||||
}
|
}
|
||||||
|
|
||||||
Postfix::MacroCall(inner) => {
|
Postfix::MacroCall { inner, delimiter } => {
|
||||||
cg.add("!(");
|
let (open, close) = match delimiter {
|
||||||
|
MacroDelimiter::Paren => ("!(", ")"),
|
||||||
|
MacroDelimiter::Bracket => ("![", "]"),
|
||||||
|
MacroDelimiter::Brace => ("!{", "}"),
|
||||||
|
};
|
||||||
|
cg.add(open);
|
||||||
cg.add(inner);
|
cg.add(inner);
|
||||||
cg.add(")");
|
cg.add(close);
|
||||||
}
|
}
|
||||||
|
|
||||||
Postfix::StructCall(fields) => {
|
Postfix::StructCall(fields) => {
|
||||||
@@ -209,8 +233,10 @@ impl GenRust for Postfix {
|
|||||||
|
|
||||||
for (name, expr) in fields {
|
for (name, expr) in fields {
|
||||||
cg.add(&name.get_rust());
|
cg.add(&name.get_rust());
|
||||||
cg.add(": ");
|
if let Some(expr) = expr {
|
||||||
expr.gen_rust(ctx, cg);
|
cg.add(": ");
|
||||||
|
expr.gen_rust(ctx, cg);
|
||||||
|
}
|
||||||
cg.add(",");
|
cg.add(",");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+144
-86
@@ -1,15 +1,18 @@
|
|||||||
|
pub mod class_decl;
|
||||||
pub mod expr;
|
pub mod expr;
|
||||||
pub mod statement;
|
pub mod statement;
|
||||||
pub mod top_level;
|
pub mod top_level;
|
||||||
|
|
||||||
use mist_parser::ast::*;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
pub fn get_mutable(mutable: bool) -> String {
|
use mist_parser::{
|
||||||
if mutable { "mut " } else { "" }.to_string()
|
ast::*,
|
||||||
}
|
rev_mapper::{Mapping, MistMap, RustMap},
|
||||||
|
};
|
||||||
|
|
||||||
pub struct Context {
|
pub struct Context {
|
||||||
pub expr_ensure_semicolon: bool,
|
pub expr_ensure_semicolon: bool,
|
||||||
|
pub expr_super: Option<ExprPath>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait GenRust {
|
pub trait GenRust {
|
||||||
@@ -18,19 +21,26 @@ pub trait GenRust {
|
|||||||
|
|
||||||
pub trait GetRust {
|
pub trait GetRust {
|
||||||
fn get_rust(&self) -> String;
|
fn get_rust(&self) -> String;
|
||||||
|
fn get_rust_ctx(&self, cx: &mut Context) -> String {
|
||||||
|
let _ = cx;
|
||||||
|
self.get_rust()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Default)]
|
|
||||||
pub struct RustCodegen {
|
pub struct RustCodegen {
|
||||||
output: String,
|
output: String,
|
||||||
indent: usize,
|
indent: usize,
|
||||||
|
pub mapping: Mapping,
|
||||||
|
position: RustMap,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RustCodegen {
|
impl RustCodegen {
|
||||||
pub fn new() -> Self {
|
pub fn new(mist_path: PathBuf) -> Self {
|
||||||
Self {
|
Self {
|
||||||
output: String::new(),
|
output: String::new(),
|
||||||
indent: 0,
|
indent: 0,
|
||||||
|
mapping: Mapping::new(mist_path),
|
||||||
|
position: RustMap(1, 0),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -39,6 +49,17 @@ impl RustCodegen {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn add(&mut self, s: &str) {
|
fn add(&mut self, s: &str) {
|
||||||
|
let newline_count = bytecount::count(s.as_bytes(), b'\n');
|
||||||
|
|
||||||
|
if newline_count == 0 {
|
||||||
|
self.position.1 += s.len();
|
||||||
|
} else {
|
||||||
|
self.position.0 += newline_count;
|
||||||
|
|
||||||
|
let last_newline = s.rfind('\n').unwrap();
|
||||||
|
self.position.1 = s.len() - last_newline - 1;
|
||||||
|
}
|
||||||
|
|
||||||
self.output.push_str(s);
|
self.output.push_str(s);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -60,6 +81,7 @@ impl RustCodegen {
|
|||||||
pub fn generate(&mut self, toplevels: Vec<TopLevel>) -> String {
|
pub fn generate(&mut self, toplevels: Vec<TopLevel>) -> String {
|
||||||
let mut ctx = Context {
|
let mut ctx = Context {
|
||||||
expr_ensure_semicolon: true,
|
expr_ensure_semicolon: true,
|
||||||
|
expr_super: None,
|
||||||
};
|
};
|
||||||
|
|
||||||
for tl in toplevels {
|
for tl in toplevels {
|
||||||
@@ -94,17 +116,6 @@ impl RustCodegen {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn ensure_brackets_body(&mut self, ctx: &mut Context, body: &StatementBody) {
|
|
||||||
match body {
|
|
||||||
StatementBody::Expression(expr) => self.ensure_brackets_expr(ctx, expr),
|
|
||||||
|
|
||||||
StatementBody::Statement(expr) => {
|
|
||||||
ctx.expr_ensure_semicolon = true;
|
|
||||||
self.ensure_brackets_expr(ctx, expr);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl GenRust for Attribute {
|
impl GenRust for Attribute {
|
||||||
@@ -112,11 +123,12 @@ impl GenRust for Attribute {
|
|||||||
match self {
|
match self {
|
||||||
Self::Path(path) => cg.add(&path.get_rust()),
|
Self::Path(path) => cg.add(&path.get_rust()),
|
||||||
Self::NameValue { path, value } => {
|
Self::NameValue { path, value } => {
|
||||||
cg.add(&format!("{} =", path.get_rust()));
|
cg.add(&format!("{} = ", path.get_rust()));
|
||||||
value.gen_rust(ctx, cg);
|
value.gen_rust(ctx, cg);
|
||||||
}
|
}
|
||||||
Self::List { path, items } => {
|
Self::List { path, items } => {
|
||||||
cg.add(&path.get_rust());
|
cg.add(&path.get_rust());
|
||||||
|
cg.add("(");
|
||||||
for (i, item) in items.iter().enumerate() {
|
for (i, item) in items.iter().enumerate() {
|
||||||
if i > 0 {
|
if i > 0 {
|
||||||
cg.add(", ");
|
cg.add(", ");
|
||||||
@@ -124,26 +136,33 @@ impl GenRust for Attribute {
|
|||||||
|
|
||||||
item.gen_rust(ctx, cg);
|
item.gen_rust(ctx, cg);
|
||||||
}
|
}
|
||||||
|
cg.add(")");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: GetRust> GetRust for Spanned<T> {
|
pub trait GenSpanTranslation {
|
||||||
fn get_rust(&self) -> String {
|
fn gen_span(&self, _cg: &mut RustCodegen);
|
||||||
format!(
|
}
|
||||||
"/* {}:{} */ {}",
|
|
||||||
self.line,
|
impl<T> GenSpanTranslation for Spanned<T> {
|
||||||
self.column,
|
fn gen_span(&self, cg: &mut RustCodegen) {
|
||||||
self.item.get_rust()
|
cg.mapping
|
||||||
)
|
.map
|
||||||
|
.insert((cg.position, MistMap(self.line, self.column)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: GetRust> GenRust for T {
|
||||||
|
fn gen_rust(&self, _: &mut Context, cg: &mut RustCodegen) {
|
||||||
|
cg.add(&self.get_rust());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: GenRust> GenRust for Spanned<T> {
|
impl<T: GenRust> GenRust for Spanned<T> {
|
||||||
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
|
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
|
||||||
cg.add_indentedln(&format!("/* {}:{} */", self.line, self.column));
|
self.gen_span(cg);
|
||||||
cg.add_indented("");
|
|
||||||
self.item.gen_rust(ctx, cg);
|
self.item.gen_rust(ctx, cg);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -158,18 +177,6 @@ impl GetRust for Path {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl GetRust for TypePostfix {
|
|
||||||
fn get_rust(&self) -> String {
|
|
||||||
match self {
|
|
||||||
TypePostfix::Ref => format!("&"),
|
|
||||||
TypePostfix::RefMut => format!("&mut "),
|
|
||||||
TypePostfix::RefLifetime(lifetime) => format!("&'{} ", lifetime.get_rust()),
|
|
||||||
TypePostfix::RefMutLifetime(lifetime) => format!("&'{} mut ", lifetime.get_rust()),
|
|
||||||
TypePostfix::Dyn => format!("dyn "),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl GetRust for Visibility {
|
impl GetRust for Visibility {
|
||||||
fn get_rust(&self) -> String {
|
fn get_rust(&self) -> String {
|
||||||
match self {
|
match self {
|
||||||
@@ -187,43 +194,17 @@ impl GetRust for Identifier {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl GetRust for TypeExpr {
|
impl GetRust for TypeExpr {
|
||||||
fn get_rust(&self) -> String {
|
|
||||||
self.1
|
|
||||||
.iter()
|
|
||||||
.map(TypePostfix::get_rust)
|
|
||||||
.rev()
|
|
||||||
.collect::<String>()
|
|
||||||
+ &self.0.get_rust()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_static_type_path(path: &Path) -> String {
|
|
||||||
let rust_path = path.get_rust();
|
|
||||||
|
|
||||||
if rust_path == "void" {
|
|
||||||
format!("()")
|
|
||||||
} else {
|
|
||||||
rust_path
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl GetRust for TypeExprKind {
|
|
||||||
fn get_rust(&self) -> String {
|
fn get_rust(&self) -> String {
|
||||||
match self {
|
match self {
|
||||||
TypeExprKind::Path(path) => get_static_type_path(path),
|
Self::Path(path, generics) => {
|
||||||
TypeExprKind::Lifetime(name) => format!("'{}", name.get_rust()),
|
if let Some(generics) = generics {
|
||||||
TypeExprKind::PathParams(path, params) => {
|
format!("{}{}", path.get_rust(), generics.get_rust())
|
||||||
format!(
|
} else {
|
||||||
"{}<{}>",
|
path.get_rust()
|
||||||
get_static_type_path(path),
|
}
|
||||||
params
|
|
||||||
.into_iter()
|
|
||||||
.map(|t| t.get_rust())
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join(", ")
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
TypeExprKind::Tuple(types) => format!(
|
Self::Lifetime(name) => format!("'{}", name.get_rust()),
|
||||||
|
Self::Tuple(types) => format!(
|
||||||
"({})",
|
"({})",
|
||||||
types
|
types
|
||||||
.into_iter()
|
.into_iter()
|
||||||
@@ -231,6 +212,65 @@ impl GetRust for TypeExprKind {
|
|||||||
.collect::<Vec<_>>()
|
.collect::<Vec<_>>()
|
||||||
.join(", ")
|
.join(", ")
|
||||||
),
|
),
|
||||||
|
Self::StaticFn(types, return_type) => {
|
||||||
|
if let Some(return_type) = return_type {
|
||||||
|
format!(
|
||||||
|
"fn({}) -> {}",
|
||||||
|
types
|
||||||
|
.into_iter()
|
||||||
|
.map(|t| t.get_rust())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(", "),
|
||||||
|
return_type.get_rust()
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
format!(
|
||||||
|
"fn({})",
|
||||||
|
types
|
||||||
|
.into_iter()
|
||||||
|
.map(|t| t.get_rust())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(", "),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Self::UnsafePtr { mutable, ty } => {
|
||||||
|
let mutable = if *mutable { "mut " } else { "const " };
|
||||||
|
format!("*{mutable}{}", ty.get_rust())
|
||||||
|
}
|
||||||
|
|
||||||
|
Self::Ref {
|
||||||
|
lifetime,
|
||||||
|
mutable,
|
||||||
|
ty,
|
||||||
|
} => {
|
||||||
|
if let Some(lifetime) = lifetime {
|
||||||
|
match lifetime {
|
||||||
|
Lifetime::Lifetime(v) => {
|
||||||
|
format!(
|
||||||
|
"&'{} {}{}",
|
||||||
|
v.get_rust(),
|
||||||
|
if *mutable { "mut " } else { "" },
|
||||||
|
ty.get_rust()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Lifetime::Unsafe => {
|
||||||
|
format!(
|
||||||
|
"*{} {}",
|
||||||
|
if *mutable { "mut" } else { "const" },
|
||||||
|
ty.get_rust()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
format!("&{}{}", if *mutable { "mut " } else { "" }, ty.get_rust())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Self::Dyn(ty) => {
|
||||||
|
format!("dyn {}", ty.get_rust())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -238,34 +278,52 @@ impl GetRust for TypeExprKind {
|
|||||||
impl GenRust for Pattern {
|
impl GenRust for Pattern {
|
||||||
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
|
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
|
||||||
match self {
|
match self {
|
||||||
Self::Id(id) => cg.add(&id.get_rust()),
|
Self::Etc => cg.add(".."),
|
||||||
Self::Path(path) => cg.add(&path.get_rust()),
|
|
||||||
Self::Literal(lit) => lit.gen_rust(ctx, cg),
|
Self::Literal(lit) => lit.gen_rust(ctx, cg),
|
||||||
|
Self::Path(mutable, path) => {
|
||||||
|
if *mutable {
|
||||||
|
cg.add("mut ");
|
||||||
|
};
|
||||||
|
|
||||||
Self::Struct(path, ids) => {
|
cg.add(&path.get_rust())
|
||||||
|
}
|
||||||
|
Self::Struct(path, inner) => {
|
||||||
cg.add(&path.get_rust());
|
cg.add(&path.get_rust());
|
||||||
cg.add(" {");
|
cg.add(" {");
|
||||||
for id in ids {
|
|
||||||
cg.add(&id.get_rust());
|
for (idx, i) in inner.iter().enumerate() {
|
||||||
cg.add(",");
|
if idx > 0 {
|
||||||
|
cg.add(", ");
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some((name, pat)) = i {
|
||||||
|
cg.add(&name.get_rust());
|
||||||
|
if let Some(pat) = pat {
|
||||||
|
cg.add(": ");
|
||||||
|
pat.gen_rust(ctx, cg);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
cg.add("..");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
cg.add("}");
|
cg.add("}");
|
||||||
}
|
}
|
||||||
|
|
||||||
Self::NamedTuple(path, ids) => {
|
Self::NamedTuple(path, inner) => {
|
||||||
cg.add(&path.get_rust());
|
cg.add(&path.get_rust());
|
||||||
cg.add(" (");
|
cg.add(" (");
|
||||||
for id in ids {
|
for pat in inner {
|
||||||
cg.add(&id.get_rust());
|
pat.gen_rust(ctx, cg);
|
||||||
cg.add(",");
|
cg.add(",");
|
||||||
}
|
}
|
||||||
cg.add(")");
|
cg.add(")");
|
||||||
}
|
}
|
||||||
|
|
||||||
Self::Tuple(ids) => {
|
Self::Tuple(inner) => {
|
||||||
cg.add("(");
|
cg.add("(");
|
||||||
for id in ids {
|
for pat in inner {
|
||||||
cg.add(&id.get_rust());
|
pat.gen_rust(ctx, cg);
|
||||||
cg.add(",");
|
cg.add(",");
|
||||||
}
|
}
|
||||||
cg.add(")");
|
cg.add(")");
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use mist_parser::ast::*;
|
use mist_parser::ast::*;
|
||||||
|
|
||||||
use crate::{Context, get_mutable};
|
use crate::{Context, GenSpanTranslation};
|
||||||
|
|
||||||
use crate::{GenRust, GetRust, RustCodegen};
|
use crate::{GenRust, GetRust, RustCodegen};
|
||||||
|
|
||||||
@@ -9,14 +9,16 @@ impl GenRust for Block {
|
|||||||
cg.addln("{");
|
cg.addln("{");
|
||||||
cg.indent += 1;
|
cg.indent += 1;
|
||||||
|
|
||||||
for stmt in &self.0 {
|
for stmt in &self.statements {
|
||||||
ctx.expr_ensure_semicolon = true;
|
ctx.expr_ensure_semicolon = true;
|
||||||
|
cg.add_indented("");
|
||||||
stmt.gen_rust(ctx, cg);
|
stmt.gen_rust(ctx, cg);
|
||||||
cg.addln("");
|
cg.addln("");
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(soft_return) = &self.1 {
|
if let Some(soft_return) = &self.soft_return {
|
||||||
ctx.expr_ensure_semicolon = false;
|
ctx.expr_ensure_semicolon = false;
|
||||||
|
cg.add_indented("");
|
||||||
soft_return.gen_rust(ctx, cg);
|
soft_return.gen_rust(ctx, cg);
|
||||||
cg.addln("");
|
cg.addln("");
|
||||||
}
|
}
|
||||||
@@ -26,21 +28,14 @@ impl GenRust for Block {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl GenRust for StatementBody {
|
|
||||||
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
|
|
||||||
match self {
|
|
||||||
Self::Expression(expr) => expr.gen_rust(ctx, cg),
|
|
||||||
Self::Statement(stmt) => {
|
|
||||||
ctx.expr_ensure_semicolon = true;
|
|
||||||
stmt.gen_rust(ctx, cg);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl GenRust for Statement {
|
impl GenRust for Statement {
|
||||||
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
|
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
|
||||||
match self {
|
match self {
|
||||||
|
Statement::UnsafeBlock(block) => {
|
||||||
|
cg.add("unsafe ");
|
||||||
|
block.gen_rust(ctx, cg);
|
||||||
|
}
|
||||||
|
|
||||||
Statement::Block(block) => block.gen_rust(ctx, cg),
|
Statement::Block(block) => block.gen_rust(ctx, cg),
|
||||||
|
|
||||||
Statement::VarDecl(VarDeclStmt { decl, init }) => {
|
Statement::VarDecl(VarDeclStmt { decl, init }) => {
|
||||||
@@ -59,7 +54,11 @@ impl GenRust for Statement {
|
|||||||
cg.add(" {");
|
cg.add(" {");
|
||||||
cg.indent += 1;
|
cg.indent += 1;
|
||||||
|
|
||||||
for (pat, body) in match_items {
|
for match_item in match_items {
|
||||||
|
match_item.gen_span(cg);
|
||||||
|
|
||||||
|
let MatchItem(pat, body) = &match_item.item;
|
||||||
|
|
||||||
for (i, p) in pat.iter().enumerate() {
|
for (i, p) in pat.iter().enumerate() {
|
||||||
cg.addln("");
|
cg.addln("");
|
||||||
cg.add_indented("");
|
cg.add_indented("");
|
||||||
@@ -86,20 +85,22 @@ impl GenRust for Statement {
|
|||||||
else_branch,
|
else_branch,
|
||||||
} => {
|
} => {
|
||||||
cg.add("if ");
|
cg.add("if ");
|
||||||
|
ctx.expr_ensure_semicolon = false;
|
||||||
initial.condition.gen_rust(ctx, cg);
|
initial.condition.gen_rust(ctx, cg);
|
||||||
cg.add(" ");
|
cg.add(" ");
|
||||||
cg.ensure_brackets_body(ctx, &initial.body);
|
initial.body.gen_rust(ctx, cg);
|
||||||
|
|
||||||
for else_if_branch in else_if {
|
for else_if_branch in else_if {
|
||||||
cg.add("else if");
|
cg.add(" else if ");
|
||||||
|
ctx.expr_ensure_semicolon = false;
|
||||||
else_if_branch.condition.gen_rust(ctx, cg);
|
else_if_branch.condition.gen_rust(ctx, cg);
|
||||||
cg.add(" ");
|
cg.add(" ");
|
||||||
cg.ensure_brackets_body(ctx, &else_if_branch.body);
|
else_if_branch.body.gen_rust(ctx, cg);
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(else_br) = else_branch {
|
if let Some(else_br) = else_branch {
|
||||||
cg.add(" else ");
|
cg.add(" else ");
|
||||||
cg.ensure_brackets_body(ctx, else_br);
|
else_br.gen_rust(ctx, cg);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -107,12 +108,12 @@ impl GenRust for Statement {
|
|||||||
cg.add("while ");
|
cg.add("while ");
|
||||||
condition.gen_rust(ctx, cg);
|
condition.gen_rust(ctx, cg);
|
||||||
cg.add(" ");
|
cg.add(" ");
|
||||||
cg.ensure_brackets_body(ctx, body);
|
body.gen_rust(ctx, cg);
|
||||||
}
|
}
|
||||||
|
|
||||||
Statement::Loop(body) => {
|
Statement::Loop(body) => {
|
||||||
cg.add("loop ");
|
cg.add("loop ");
|
||||||
cg.ensure_brackets_body(ctx, body);
|
body.gen_rust(ctx, cg);
|
||||||
}
|
}
|
||||||
|
|
||||||
Statement::CStyleFor {
|
Statement::CStyleFor {
|
||||||
@@ -158,17 +159,15 @@ impl GenRust for Statement {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Statement::For {
|
Statement::For {
|
||||||
mutable,
|
|
||||||
pattern,
|
pattern,
|
||||||
iterator,
|
iterator,
|
||||||
body,
|
body,
|
||||||
} => {
|
} => {
|
||||||
cg.add("for ");
|
cg.add("for ");
|
||||||
cg.add(&get_mutable(*mutable));
|
|
||||||
pattern.gen_rust(ctx, cg);
|
pattern.gen_rust(ctx, cg);
|
||||||
cg.add(" in ");
|
cg.add(" in ");
|
||||||
iterator.gen_rust(ctx, cg);
|
iterator.gen_rust(ctx, cg);
|
||||||
cg.ensure_brackets_body(ctx, body);
|
body.gen_rust(ctx, cg);
|
||||||
}
|
}
|
||||||
|
|
||||||
Statement::Return(expr) => {
|
Statement::Return(expr) => {
|
||||||
@@ -186,8 +185,6 @@ impl GenRust for Statement {
|
|||||||
|
|
||||||
impl GenRust for VarDecl {
|
impl GenRust for VarDecl {
|
||||||
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
|
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
|
||||||
cg.add(&get_mutable(self.mutable));
|
|
||||||
|
|
||||||
self.name.gen_rust(ctx, cg);
|
self.name.gen_rust(ctx, cg);
|
||||||
|
|
||||||
cg.add(
|
cg.add(
|
||||||
|
|||||||
+28
-147
@@ -1,6 +1,6 @@
|
|||||||
use mist_parser::ast::*;
|
use mist_parser::ast::*;
|
||||||
|
|
||||||
use crate::Context;
|
use crate::{Context, class_decl};
|
||||||
|
|
||||||
use crate::{GenRust, GetRust, RustCodegen};
|
use crate::{GenRust, GetRust, RustCodegen};
|
||||||
|
|
||||||
@@ -73,7 +73,7 @@ impl GenRust for ImplDecl {
|
|||||||
|
|
||||||
impl GenRust for FunctionDecl {
|
impl GenRust for FunctionDecl {
|
||||||
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
|
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
|
||||||
cg.add(&format!(
|
cg.add_indented(&format!(
|
||||||
"{}fn {}{}(",
|
"{}fn {}{}(",
|
||||||
self.visibility.get_rust(),
|
self.visibility.get_rust(),
|
||||||
self.name.get_rust(),
|
self.name.get_rust(),
|
||||||
@@ -88,14 +88,18 @@ impl GenRust for FunctionDecl {
|
|||||||
param.gen_rust(ctx, cg);
|
param.gen_rust(ctx, cg);
|
||||||
}
|
}
|
||||||
|
|
||||||
cg.add(") -> ");
|
cg.add(") ");
|
||||||
cg.add(&self.return_type.get_rust());
|
if let Some(return_type) = &self.return_type {
|
||||||
|
cg.add("-> ");
|
||||||
|
cg.add(&return_type.get_rust());
|
||||||
|
}
|
||||||
|
|
||||||
if let Some(body) = &self.body {
|
if let Some(body) = &self.body {
|
||||||
cg.add(" ");
|
cg.add(" ");
|
||||||
body.gen_rust(ctx, cg);
|
body.gen_rust(ctx, cg);
|
||||||
|
cg.addln("");
|
||||||
} else {
|
} else {
|
||||||
cg.add(";");
|
cg.addln(";");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -167,77 +171,6 @@ impl GenRust for TopLevel {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl GenRust for (&Vec<Spanned<FieldDeclStmt>>, &Spanned<ClassConstructor>) {
|
|
||||||
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
|
|
||||||
cg.add_indented(&format!(
|
|
||||||
"{}fn new{}(",
|
|
||||||
self.1.item.visibility.get_rust(),
|
|
||||||
self.1.item.generics.get_rust()
|
|
||||||
));
|
|
||||||
|
|
||||||
self.1.item.params.gen_rust(ctx, cg);
|
|
||||||
|
|
||||||
cg.addln(") -> Self {");
|
|
||||||
cg.indent += 1;
|
|
||||||
|
|
||||||
cg.add_indentedln("let mut this: Self = unsafe { std::mem::MaybeUninit::<Self>::zeroed().assume_init() };");
|
|
||||||
|
|
||||||
for field in self.0 {
|
|
||||||
let comment = field.get_comment();
|
|
||||||
|
|
||||||
if let Some(init) = &field.item.init {
|
|
||||||
cg.add_indentedln(&comment);
|
|
||||||
|
|
||||||
cg.add_indentedln(&format!("this.{} = ", field.item.decl.name.get_rust()));
|
|
||||||
|
|
||||||
init.gen_rust(ctx, cg);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
cg.add_indented(&format!("this.constructor("));
|
|
||||||
|
|
||||||
for (i, param) in self.1.item.params.0.iter().enumerate() {
|
|
||||||
if i > 0 {
|
|
||||||
cg.add(", ");
|
|
||||||
}
|
|
||||||
|
|
||||||
param.name.gen_rust(ctx, cg);
|
|
||||||
}
|
|
||||||
|
|
||||||
cg.addln(");");
|
|
||||||
|
|
||||||
cg.add_indentedln("this");
|
|
||||||
|
|
||||||
cg.indent -= 1;
|
|
||||||
cg.add_indentedln("}\n");
|
|
||||||
|
|
||||||
let mut constructor_params = vec![VarDecl {
|
|
||||||
mutable: false,
|
|
||||||
name: Pattern::Id(Identifier(String::from("self"))),
|
|
||||||
type_: Some(TypeExpr(
|
|
||||||
TypeExprKind::Path(Path(vec![Identifier(String::from("Self"))])),
|
|
||||||
vec![TypePostfix::RefMut],
|
|
||||||
)),
|
|
||||||
}];
|
|
||||||
|
|
||||||
constructor_params.append(&mut self.1.item.params.0.clone());
|
|
||||||
|
|
||||||
Spanned {
|
|
||||||
line: self.1.line,
|
|
||||||
column: self.1.column,
|
|
||||||
item: FunctionDecl {
|
|
||||||
visibility: self.1.item.visibility.clone(),
|
|
||||||
name: Identifier(String::from("constructor")),
|
|
||||||
generics: self.1.item.generics.clone(),
|
|
||||||
params: ParamList(constructor_params),
|
|
||||||
return_type: TypeExpr::no_px(TypeExprKind::Tuple(Vec::new())),
|
|
||||||
body: Some(self.1.item.body.clone()),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
.gen_rust(ctx, cg);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl GenRust for TopLevelKind {
|
impl GenRust for TopLevelKind {
|
||||||
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
|
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
|
||||||
match self {
|
match self {
|
||||||
@@ -245,7 +178,7 @@ impl GenRust for TopLevelKind {
|
|||||||
Self::Import(vis, path) => {
|
Self::Import(vis, path) => {
|
||||||
cg.addln(&format!("{}use {};", vis.get_rust(), path.get_rust()))
|
cg.addln(&format!("{}use {};", vis.get_rust(), path.get_rust()))
|
||||||
}
|
}
|
||||||
Self::Mod(vis, id) => cg.addln(&format!("{}mod {};", vis.get_rust(), id.get_rust())),
|
Self::DeclareModule(_, _) => {}
|
||||||
Self::FunctionDecl(decl) => decl.gen_rust(ctx, cg),
|
Self::FunctionDecl(decl) => decl.gen_rust(ctx, cg),
|
||||||
Self::ImplDecl(impl_) => impl_.gen_rust(ctx, cg),
|
Self::ImplDecl(impl_) => impl_.gen_rust(ctx, cg),
|
||||||
Self::StructDecl {
|
Self::StructDecl {
|
||||||
@@ -263,7 +196,9 @@ impl GenRust for TopLevelKind {
|
|||||||
cg.indent += 1;
|
cg.indent += 1;
|
||||||
|
|
||||||
for field in fields {
|
for field in fields {
|
||||||
cg.add_indentedln(&field.get_rust());
|
cg.add_indented("");
|
||||||
|
field.gen_rust(ctx, cg);
|
||||||
|
cg.addln("");
|
||||||
}
|
}
|
||||||
|
|
||||||
cg.indent -= 1;
|
cg.indent -= 1;
|
||||||
@@ -284,7 +219,9 @@ impl GenRust for TopLevelKind {
|
|||||||
cg.indent += 1;
|
cg.indent += 1;
|
||||||
|
|
||||||
for field in fields {
|
for field in fields {
|
||||||
cg.add_indentedln(&(field.get_rust() + ","));
|
cg.add_indented("");
|
||||||
|
field.gen_rust(ctx, cg);
|
||||||
|
cg.addln(",");
|
||||||
}
|
}
|
||||||
|
|
||||||
cg.indent -= 1;
|
cg.indent -= 1;
|
||||||
@@ -326,77 +263,21 @@ impl GenRust for TopLevelKind {
|
|||||||
visibility,
|
visibility,
|
||||||
name,
|
name,
|
||||||
generics,
|
generics,
|
||||||
|
inherits,
|
||||||
fields,
|
fields,
|
||||||
constructor,
|
constructor,
|
||||||
items,
|
items,
|
||||||
} => {
|
} => class_decl::class_decl(
|
||||||
// Struct decl
|
ctx,
|
||||||
cg.addln(&format!(
|
cg,
|
||||||
"{}struct {}{} {{",
|
visibility,
|
||||||
visibility.get_rust(),
|
name,
|
||||||
name.clone().get_rust(),
|
generics,
|
||||||
generics.clone().get_rust()
|
inherits,
|
||||||
));
|
fields,
|
||||||
cg.indent += 1;
|
constructor,
|
||||||
|
items,
|
||||||
for field in fields.clone() {
|
),
|
||||||
cg.add_indentedln(&field.get_comment());
|
|
||||||
cg.add_indentedln(&field.item.decl.get_rust());
|
|
||||||
}
|
|
||||||
|
|
||||||
cg.indent -= 1;
|
|
||||||
cg.addln("}\n");
|
|
||||||
|
|
||||||
// Constructor
|
|
||||||
cg.addln(&format!(
|
|
||||||
"impl{} {}{} {{",
|
|
||||||
generics.clone().get_rust(),
|
|
||||||
name.clone().get_rust(),
|
|
||||||
format!(
|
|
||||||
"<{}>",
|
|
||||||
generics
|
|
||||||
.clone()
|
|
||||||
.0
|
|
||||||
.into_iter()
|
|
||||||
.map(|v| Generic::from(v).get_rust())
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join(", ")
|
|
||||||
)
|
|
||||||
));
|
|
||||||
cg.indent += 1;
|
|
||||||
|
|
||||||
let constructor_comment = constructor.get_comment();
|
|
||||||
|
|
||||||
cg.add_indentedln("#[allow(invalid_value)]");
|
|
||||||
cg.add_indentedln(&constructor_comment);
|
|
||||||
|
|
||||||
(fields, constructor).gen_rust(ctx, cg);
|
|
||||||
|
|
||||||
for item in items.clone() {
|
|
||||||
match item {
|
|
||||||
ClassItem::ImplDecl(_) => {}
|
|
||||||
ClassItem::Method(method) => method.gen_rust(ctx, cg),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
cg.indent -= 1;
|
|
||||||
cg.addln("}\n");
|
|
||||||
|
|
||||||
for item in items {
|
|
||||||
match item {
|
|
||||||
ClassItem::ImplDecl(impl_) => {
|
|
||||||
let mut impl_ = impl_.clone();
|
|
||||||
|
|
||||||
impl_.item.trait_ = Some(impl_.item.target);
|
|
||||||
impl_.item.target =
|
|
||||||
TypeExpr(TypeExprKind::Path(Path(vec![name.clone()])), Vec::new());
|
|
||||||
|
|
||||||
impl_.gen_rust(ctx, cg);
|
|
||||||
}
|
|
||||||
ClassItem::Method(_) => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
[package]
|
||||||
|
name = "mist-api"
|
||||||
|
version = "0.3.5-alpha.0"
|
||||||
|
edition = "2024"
|
||||||
|
description = "The Mist programming language module system"
|
||||||
|
license = "Apache-2.0"
|
||||||
|
repository = "https://github.com/mist-go/mist"
|
||||||
|
keywords = ["compiler", "language", "mist", "module-system"]
|
||||||
|
categories = ["compilers"]
|
||||||
|
|
||||||
|
include = [
|
||||||
|
".mist/src/**",
|
||||||
|
"Cargo.toml",
|
||||||
|
"README.md",
|
||||||
|
]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
serde = { version = "1.0.228", features = ["serde_derive"] }
|
||||||
|
serde_json = "1.0.149"
|
||||||
|
cargo_metadata = "0.23.1"
|
||||||
|
mist-parser = { workspace = true }
|
||||||
|
mist-codegen = { workspace = true }
|
||||||
|
toml = "1.1.2"
|
||||||
|
|
||||||
|
[lib]
|
||||||
|
name = "mist_api"
|
||||||
|
path = ".mist/src/lib.rs"
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
package = "lib.mist"
|
||||||
|
packages = []
|
||||||
@@ -1,20 +1,21 @@
|
|||||||
use std::{
|
pub module builder;
|
||||||
collections::HashMap,
|
|
||||||
env, fs,
|
|
||||||
path::{MAIN_SEPARATOR, PathBuf},
|
|
||||||
process::{Command, Stdio},
|
|
||||||
};
|
|
||||||
|
|
||||||
use cargo_metadata::{CompilerMessage, Message};
|
use std::collections::HashMap;
|
||||||
use mist_parser::rev_mapper::{RustMap, find_mapping, get_mapping};
|
use std::fs;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::process::Command;
|
||||||
|
use std::process::Stdio;
|
||||||
|
use cargo_metadata::CompilerMessage;
|
||||||
|
use cargo_metadata::Message;
|
||||||
|
use mist_parser::rev_mapper;
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct MistDiagnosticMessage {
|
pub struct MistDiagnosticMessage {
|
||||||
pub message: String,
|
pub message String,
|
||||||
pub file_path: PathBuf,
|
pub file_path PathBuf,
|
||||||
pub file_name: String,
|
pub file_name String ,
|
||||||
pub line: usize,
|
pub line usize,
|
||||||
pub column: usize,
|
pub column usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
@@ -24,12 +25,10 @@ pub enum MistDiagnostic {
|
|||||||
Rust(CompilerMessage),
|
Rust(CompilerMessage),
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn build(mut args: Vec<String>, root: PathBuf) -> bool {
|
pub fn bool build(mut args Vec<String>, root PathBuf) {
|
||||||
args.remove(0);
|
args.remove(0);
|
||||||
args.insert(1, "--message-format=json".to_string());
|
args.insert(1, "--message-format=json".to_string());
|
||||||
|
|
||||||
let is_root = root == env::current_dir().expect("Failed getting env");
|
|
||||||
|
|
||||||
let mut command = Command::new("cargo")
|
let mut command = Command::new("cargo")
|
||||||
.args(args)
|
.args(args)
|
||||||
.stdout(Stdio::piped())
|
.stdout(Stdio::piped())
|
||||||
@@ -44,8 +43,6 @@ pub fn build(mut args: Vec<String>, root: PathBuf) -> bool {
|
|||||||
|
|
||||||
let mut mapping = HashMap::new();
|
let mut mapping = HashMap::new();
|
||||||
|
|
||||||
let mist_src = format!(".mist{MAIN_SEPARATOR}src");
|
|
||||||
|
|
||||||
for message in cargo_metadata::Message::parse_stream(&mut reader) {
|
for message in cargo_metadata::Message::parse_stream(&mut reader) {
|
||||||
match message {
|
match message {
|
||||||
Ok(Message::CompilerMessage(msg)) => {
|
Ok(Message::CompilerMessage(msg)) => {
|
||||||
@@ -53,29 +50,23 @@ pub fn build(mut args: Vec<String>, root: PathBuf) -> bool {
|
|||||||
if span.is_primary {
|
if span.is_primary {
|
||||||
let rust_path = root.join(&span.file_name);
|
let rust_path = root.join(&span.file_name);
|
||||||
|
|
||||||
let mist_file = span
|
let mapping_path = rust_path.with_extension("map.json");
|
||||||
.file_name
|
|
||||||
.replacen(&mist_src, "src", 1)
|
|
||||||
.trim_end_matches(".rs")
|
|
||||||
.to_string()
|
|
||||||
+ ".mist";
|
|
||||||
|
|
||||||
let mist_path = root.join(&mist_file);
|
if !fs::exists(&mapping_path).expect("Unable to check if map file exists") {
|
||||||
|
|
||||||
if !fs::exists(&mist_path).expect("Unable to check if mist file exists") {
|
|
||||||
diagnostics.push(MistDiagnostic::Rust(msg));
|
diagnostics.push(MistDiagnostic::Rust(msg));
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
let map = mapping.entry(rust_path.clone()).or_insert_with(|| {
|
let map = mapping.entry(mapping_path.clone()).or_insert_with(fn() {
|
||||||
get_mapping(
|
let map_str = fs::read_to_string(mapping_path).expect("Failed to read map file");
|
||||||
&fs::read_to_string(rust_path)
|
|
||||||
.expect("Failed to read file for mapping"),
|
serde_json::from_str<rev_mapper::Mapping>(&map_str).expect("Failed to parse map file")
|
||||||
)
|
|
||||||
});
|
});
|
||||||
|
|
||||||
let mist_span =
|
let mist_file = map.mist_path.strip_prefix(&root);
|
||||||
find_mapping(&map, &RustMap(span.line_end, span.column_start))
|
|
||||||
|
let (_, rev_mapper::MistMap(line, column)) =
|
||||||
|
map.find(&rev_mapper::RustMap(span.line_end, span.column_start))
|
||||||
.expect("Unable to find mapping");
|
.expect("Unable to find mapping");
|
||||||
|
|
||||||
let mist_msg = MistDiagnosticMessage {
|
let mist_msg = MistDiagnosticMessage {
|
||||||
@@ -84,14 +75,14 @@ pub fn build(mut args: Vec<String>, root: PathBuf) -> bool {
|
|||||||
msg.message.message,
|
msg.message.message,
|
||||||
span.label.clone().unwrap_or_default()
|
span.label.clone().unwrap_or_default()
|
||||||
),
|
),
|
||||||
file_name: if is_root {
|
file_name: if let Ok(mist_file) = mist_file {
|
||||||
mist_file
|
mist_file.to_string_lossy().to_string()
|
||||||
} else {
|
} else {
|
||||||
mist_path.to_string_lossy().to_string()
|
map.mist_path.to_string_lossy().to_string()
|
||||||
},
|
},
|
||||||
file_path: mist_path,
|
file_path: map.mist_path.clone(),
|
||||||
line: mist_span.1.0,
|
line: line,
|
||||||
column: mist_span.1.1,
|
column: column
|
||||||
};
|
};
|
||||||
|
|
||||||
match msg.message.level {
|
match msg.message.level {
|
||||||
@@ -116,7 +107,7 @@ pub fn build(mut args: Vec<String>, root: PathBuf) -> bool {
|
|||||||
let mut stdout = std::io::stdout();
|
let mut stdout = std::io::stdout();
|
||||||
|
|
||||||
std::io::copy(&mut raw_reader, &mut stdout)
|
std::io::copy(&mut raw_reader, &mut stdout)
|
||||||
.map_err(|v| v.to_string())
|
.map_err(fn(v) -> v.to_string())
|
||||||
.expect("(Mist) Failed to copy IO");
|
.expect("(Mist) Failed to copy IO");
|
||||||
|
|
||||||
command.wait().unwrap();
|
command.wait().unwrap();
|
||||||
@@ -124,7 +115,7 @@ pub fn build(mut args: Vec<String>, root: PathBuf) -> bool {
|
|||||||
return finish.success;
|
return finish.success;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(Message::TextLine(text)) => println!("{text}"),
|
Ok(Message::TextLine(text)) => println!("{text}");
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -132,7 +123,7 @@ pub fn build(mut args: Vec<String>, root: PathBuf) -> bool {
|
|||||||
false
|
false
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn print_diagnostics(diagnostics: &Vec<MistDiagnostic>) {
|
pub fn void print_diagnostics(diagnostics *Vec<MistDiagnostic>) {
|
||||||
let mut files = HashMap::new();
|
let mut files = HashMap::new();
|
||||||
|
|
||||||
for diag in diagnostics {
|
for diag in diagnostics {
|
||||||
@@ -163,18 +154,18 @@ pub fn print_diagnostics(diagnostics: &Vec<MistDiagnostic>) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
MistDiagnostic::Rust(rs) => println!("{rs}"),
|
MistDiagnostic::Rust(rs) => println!("{rs}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_line(
|
pub fn Option<String> get_line(
|
||||||
files: &mut HashMap<PathBuf, Vec<String>>,
|
files *mut HashMap<PathBuf, Vec<String>>,
|
||||||
msg: &MistDiagnosticMessage,
|
msg *MistDiagnosticMessage,
|
||||||
) -> Option<String> {
|
) {
|
||||||
let src_path = msg.file_path.clone();
|
let src_path = msg.file_path.clone();
|
||||||
|
|
||||||
let lines = files.entry(src_path.clone()).or_insert_with(|| {
|
let lines = files.entry(src_path.clone()).or_insert_with(fn() {
|
||||||
fs::read_to_string(src_path)
|
fs::read_to_string(src_path)
|
||||||
.expect("Unable to read mist file")
|
.expect("Unable to read mist file")
|
||||||
.lines()
|
.lines()
|
||||||
@@ -183,5 +174,5 @@ pub fn get_line(
|
|||||||
.collect()
|
.collect()
|
||||||
});
|
});
|
||||||
|
|
||||||
lines.get(msg.line - 1).map(|v| v.trim().to_string())
|
lines.get(msg.line - 1).map(fn(v) -> v.trim().to_string())
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
pub module modules;
|
||||||
|
|
||||||
|
use std::path::Path;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::fs;
|
||||||
|
use std::process;
|
||||||
|
|
||||||
|
use crate::transpiler::MistConfig;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub class Module {
|
||||||
|
pub name String;
|
||||||
|
pub path PathBuf;
|
||||||
|
pub children Vec<Module>;
|
||||||
|
|
||||||
|
pub constructor(mist_path PathBuf, config *MistConfig) {
|
||||||
|
self.children = Vec::new();
|
||||||
|
self.name = mist_path.file_stem()
|
||||||
|
.and_then(fn(s) -> s.to_str())
|
||||||
|
.expect("Failed to get module name")
|
||||||
|
.to_string();
|
||||||
|
self.path = mist_path;
|
||||||
|
|
||||||
|
if self.path.is_dir() {
|
||||||
|
let dir = self.path.clone();
|
||||||
|
|
||||||
|
let pkg_gate = self.path.join("package.mist");
|
||||||
|
if pkg_gate.exists() {
|
||||||
|
self.path = pkg_gate;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.scan_directory(&dir, config);
|
||||||
|
} else if config.should_ignore(&self.path) {
|
||||||
|
let dir = self.path.parent().expect("Failed to get parent directory to scan").to_path_buf();
|
||||||
|
|
||||||
|
self.scan_directory(&dir, config);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn void scan_directory(*mut self, search_dir *Path, config *MistConfig) {
|
||||||
|
let entries = match fs::read_dir(search_dir) {
|
||||||
|
Ok(entries) => entries;
|
||||||
|
Err(e) => {
|
||||||
|
eprintln!("error: failed to read directory {}\n {}", search_dir.display(), e);
|
||||||
|
process::exit(1);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
for entry in entries {
|
||||||
|
let entry = match entry {
|
||||||
|
Ok(entry) => entry;
|
||||||
|
Err(e) => {
|
||||||
|
eprintln!("error: failed to read directory entry\n {}", e);
|
||||||
|
process::exit(1);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let child_path = entry.path();
|
||||||
|
|
||||||
|
if child_path == self.path || child_path == config.package {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.children.push(Module::new(child_path, config));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn bool is_package(*self) {
|
||||||
|
self.path.file_name().map(fn(v) -> v.to_str()).unwrap_or_default() == Some("package.mist")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn PathBuf output_dir(*self, parent_dir *PathBuf) {
|
||||||
|
if self.path.is_dir() || self.is_package() {
|
||||||
|
parent_dir.join(&self.name)
|
||||||
|
} else {
|
||||||
|
parent_dir.clone()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn PathBuf output_path(*self, parent_dir *PathBuf, curr_mod_decl *Option<(mist_parser::ast::Visibility, mist_parser::ast::Identifier)>) {
|
||||||
|
let name = if let Some((_, name)) = curr_mod_decl {
|
||||||
|
&name.0
|
||||||
|
} else {
|
||||||
|
&self.name
|
||||||
|
};
|
||||||
|
|
||||||
|
if self.path.is_dir() || self.is_package() {
|
||||||
|
parent_dir.join(name).join("mod.rs")
|
||||||
|
} else {
|
||||||
|
parent_dir.join(name).with_extension("rs")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,303 @@
|
|||||||
|
pub module transpiler;
|
||||||
|
|
||||||
|
use std::fs;
|
||||||
|
use std::path::Path;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::process;
|
||||||
|
use std::time;
|
||||||
|
use std::env;
|
||||||
|
|
||||||
|
use mist_parser::error;
|
||||||
|
use crate::modules;
|
||||||
|
use mist_codegen::GetRust;
|
||||||
|
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
#[serde(default)]
|
||||||
|
pub struct MistConfig {
|
||||||
|
pub package PathBuf,
|
||||||
|
pub packages Vec<PathBuf>,
|
||||||
|
pub main_mods String
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MistConfig {
|
||||||
|
pub fn bool should_ignore(*self, path *Path) {
|
||||||
|
if path == self.package {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
for pkg in &self.packages {
|
||||||
|
if path.ends_with(pkg) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Default for MistConfig {
|
||||||
|
fn Self default() {
|
||||||
|
Self {
|
||||||
|
package: PathBuf::from("main.mist"),
|
||||||
|
packages: Vec::new(),
|
||||||
|
main_mods: String::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn PathBuf transpile() {
|
||||||
|
let start = time::Instant::now();
|
||||||
|
|
||||||
|
let root = env::current_dir().expect("Unable to find project root");
|
||||||
|
|
||||||
|
let toml_path = root.join("Mist.toml");
|
||||||
|
let src = root.join("src");
|
||||||
|
let out = root.join(".mist/src");
|
||||||
|
|
||||||
|
let toml_content = fs::read_to_string(&toml_path)
|
||||||
|
.unwrap_or_else(fn(_) -> panic!("Could not read file at {:?}", toml_path));
|
||||||
|
|
||||||
|
let mut config MistConfig = toml::from_str(&toml_content)
|
||||||
|
.unwrap_or_else(fn(_) -> panic!("Failed to parse Mist.toml from {:?}", toml_path));
|
||||||
|
|
||||||
|
for pkg in &mut config.packages {
|
||||||
|
*pkg = src.join(&*pkg);
|
||||||
|
}
|
||||||
|
|
||||||
|
config.package = src.join(&*config.package);
|
||||||
|
|
||||||
|
let master = modules::Module::new(
|
||||||
|
config.package.clone(),
|
||||||
|
&config
|
||||||
|
);
|
||||||
|
|
||||||
|
master.transpile(&out, &mut config);
|
||||||
|
|
||||||
|
let elapsed = start.elapsed();
|
||||||
|
|
||||||
|
println!(
|
||||||
|
"\x1b[32m\nTranspile successful\x1b[0m in \x1b[34m{:.2?}\x1b[0m",
|
||||||
|
elapsed
|
||||||
|
);
|
||||||
|
|
||||||
|
root
|
||||||
|
}
|
||||||
|
|
||||||
|
impl modules::Module {
|
||||||
|
fn (bool, String) transpile(*self, parent_dir *PathBuf, config *mut MistConfig) {
|
||||||
|
if !self.path.is_dir() && self.path.extension().and_then(fn(v) -> v.to_str()) != Some("mist") {
|
||||||
|
let file_name = self.path.file_name()
|
||||||
|
.and_then(fn(s) -> s.to_str())
|
||||||
|
.expect("Failed to get file name");
|
||||||
|
|
||||||
|
fs::copy(&self.path, parent_dir.join(&file_name)).expect("Failed to copy SideFile");
|
||||||
|
|
||||||
|
return (true, String::new());
|
||||||
|
}
|
||||||
|
|
||||||
|
let dir = self.output_dir(parent_dir);
|
||||||
|
|
||||||
|
let _ = fs::create_dir_all(&dir);
|
||||||
|
|
||||||
|
let mut output = String::new();
|
||||||
|
|
||||||
|
let mut child_changed = false;
|
||||||
|
|
||||||
|
for child in &self.children {
|
||||||
|
if !config.should_ignore(&child.path) {
|
||||||
|
let out = child.transpile(&dir, config);
|
||||||
|
if out.0 {
|
||||||
|
child_changed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
output.push_str(&out.1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.path == config.package {
|
||||||
|
config.main_mods = output.clone();
|
||||||
|
} else if config.should_ignore(&self.path) {
|
||||||
|
output.push_str(&config.main_mods)
|
||||||
|
}
|
||||||
|
|
||||||
|
self.write_transpile(output, parent_dir, child_changed)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn (bool, String) write_transpile(*self, output String, parent_dir *PathBuf, child_changed bool) {
|
||||||
|
if self.path.is_dir() {
|
||||||
|
let output_file = self.output_path(parent_dir, &None);
|
||||||
|
|
||||||
|
if output.len() == 0 {
|
||||||
|
return (true, String::new());
|
||||||
|
}
|
||||||
|
|
||||||
|
let res = fs::write(&output_file, output);
|
||||||
|
|
||||||
|
if res.is_err() {
|
||||||
|
eprintln!(
|
||||||
|
"error: failed to write output {}\n {}",
|
||||||
|
output_file.display(),
|
||||||
|
res.unwrap_err(),
|
||||||
|
);
|
||||||
|
|
||||||
|
process::exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
(false, format!("pub mod {};\n", self.name))
|
||||||
|
} else {
|
||||||
|
let source = match fs::read_to_string(&self.path) {
|
||||||
|
Ok(s) => s;
|
||||||
|
Err(e) => {
|
||||||
|
eprintln!("error: failed to read file {}\n {}", self.path.display(), e);
|
||||||
|
|
||||||
|
process::exit(1);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let curr_mod_decl = mist_parser::parse_module(&source).expect("Failed parsing module");
|
||||||
|
|
||||||
|
let output_file = self.output_path(parent_dir, &curr_mod_decl);
|
||||||
|
|
||||||
|
let should_change = is_source_newer(&self.path, &output_file).expect("Failed to cache");
|
||||||
|
|
||||||
|
if should_change || child_changed {
|
||||||
|
transpile_file(&self.path, &source, output_file, &output, &curr_mod_decl);
|
||||||
|
}
|
||||||
|
|
||||||
|
(should_change, if let Some((vis, name)) = &curr_mod_decl {
|
||||||
|
format!("{}mod {};\n", vis.get_rust(), name.get_rust())
|
||||||
|
} else {
|
||||||
|
String::new()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn std::io::Result<bool> is_source_newer(source *Path, output *Path) {
|
||||||
|
if !output.exists() {
|
||||||
|
return Ok(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
let source_time = fs::metadata(source)?.modified()?;
|
||||||
|
let output_time = fs::metadata(output)?.modified()?;
|
||||||
|
|
||||||
|
Ok(source_time > output_time)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub enum TranspileError<'a> {
|
||||||
|
Parse(error::ParseError<'a, Vec<mist_parser::ast::TopLevel>>),
|
||||||
|
Semantic(Vec<mist_parser::semantics::SemanticError>)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn Result<(PathBuf, mist_codegen::RustCodegen, String), TranspileError<'a>>
|
||||||
|
transpile_code<'a>(path *PathBuf, source *'a str, mut output_file PathBuf, mod_decl *str, curr_mod_decl *Option<(mist_parser::ast::Visibility, mist_parser::ast::Identifier)>) {
|
||||||
|
|
||||||
|
if let Some((_, name)) = &curr_mod_decl {
|
||||||
|
if output_file.file_name().map(fn(v) -> v.to_str()).unwrap_or_default() != Some("mod.rs") {
|
||||||
|
if let Some(ext) = output_file.extension().map(fn(e) -> e.to_owned()) {
|
||||||
|
let mut new_name = std::ffi::OsString::from(&name.0);
|
||||||
|
|
||||||
|
new_name.push(".");
|
||||||
|
new_name.push(ext);
|
||||||
|
|
||||||
|
output_file.set_file_name(new_name);
|
||||||
|
} else {
|
||||||
|
output_file.set_file_name(&name.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut gc = mist_codegen::RustCodegen::new(path.clone());
|
||||||
|
|
||||||
|
let parsed = mist_parser::parse(source).map_err(TranspileError::Parse)?;
|
||||||
|
|
||||||
|
for i in &parsed {
|
||||||
|
let _ = mist_parser::semantics::check_class_semantics(i).map_err(TranspileError::Semantic)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
let output = gc.generate(parsed);
|
||||||
|
|
||||||
|
gc.mapping.shift_rust(mod_decl.lines().count() as isize, 0);
|
||||||
|
|
||||||
|
Ok((output_file, gc, output))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void transpile_file(path *PathBuf, source *str, output_file PathBuf, mod_decl *str, curr_mod_decl *Option<(mist_parser::ast::Visibility, mist_parser::ast::Identifier)>) {
|
||||||
|
let (output_file, gc, output) = match transpile_code(path, source, output_file, mod_decl, curr_mod_decl) {
|
||||||
|
Ok(output) => output;
|
||||||
|
Err(e) => {
|
||||||
|
decode_err(&e, path);
|
||||||
|
process::exit(1);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let res = fs::write(&output_file, format!("{mod_decl}{output}"));
|
||||||
|
|
||||||
|
let output_file_map = output_file.with_extension("map.json");
|
||||||
|
|
||||||
|
let res_map = fs::write(&output_file_map, serde_json::to_string(&gc.mapping).unwrap());
|
||||||
|
|
||||||
|
if res_map.is_err() {
|
||||||
|
eprintln!(
|
||||||
|
"error: failed to write mapping output {}\n {}",
|
||||||
|
output_file_map.display(),
|
||||||
|
res.as_ref().unwrap_err(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if res.is_err() {
|
||||||
|
eprintln!(
|
||||||
|
"error: failed to write output {}\n {}",
|
||||||
|
output_file.display(),
|
||||||
|
res.as_ref().unwrap_err(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if res_map.is_err() || res.is_err() {
|
||||||
|
process::exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void decode_err<'a>(err *TranspileError<'a>, path *PathBuf) {
|
||||||
|
let curr_dir = std::env::current_dir().unwrap();
|
||||||
|
|
||||||
|
match err {
|
||||||
|
TranspileError::Semantic(e_list) => {
|
||||||
|
for e in e_list {
|
||||||
|
eprintln!(
|
||||||
|
"\n{}:{}:{}\n \x1b[31mError\x1b[0m: {}",
|
||||||
|
path.strip_prefix(&curr_dir).unwrap_or_else(|_| path).as_os_str().display(),
|
||||||
|
e.line,
|
||||||
|
e.column,
|
||||||
|
e.error_message,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
TranspileError::Parse(e) => {
|
||||||
|
match e {
|
||||||
|
error::ParseError::Ast(e) => {
|
||||||
|
let start_pos = e.span.start_pos().line_col();
|
||||||
|
|
||||||
|
let span = e.span.as_str();
|
||||||
|
|
||||||
|
eprintln!(
|
||||||
|
"\n{}:{}:{}\n \x1b[31mError\x1b[0m: {}\n\t{}{}\t{}",
|
||||||
|
path.strip_prefix(curr_dir).unwrap_or_else(|_| path).as_os_str().display(),
|
||||||
|
start_pos.0,
|
||||||
|
start_pos.1,
|
||||||
|
e.error_message,
|
||||||
|
span,
|
||||||
|
if span.ends_with("\n") { "" } else { "\n" },
|
||||||
|
"^".repeat(span.trim().len()),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
error::ParseError::PreAst(e) => {
|
||||||
|
eprintln!("error: parse failed in {}\n{}", path.strip_prefix(curr_dir).unwrap_or_else(|_| path).display(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "mist-parser"
|
name = "mist-parser"
|
||||||
version = "0.1.6"
|
version = "0.3.5-alpha.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
description = "The Mist programming language parser"
|
description = "The Mist programming language parser"
|
||||||
license = "Apache-2.0"
|
license = "Apache-2.0"
|
||||||
|
|||||||
@@ -7,6 +7,13 @@ pub enum Expression {
|
|||||||
Literal(Literal),
|
Literal(Literal),
|
||||||
Path(ExprPath),
|
Path(ExprPath),
|
||||||
Statement(Box<Statement>),
|
Statement(Box<Statement>),
|
||||||
|
Array(Vec<Expression>),
|
||||||
|
ArrayRepeat(Box<Expression>, Box<Expression>),
|
||||||
|
Closure {
|
||||||
|
return_type: Option<TypeExpr>,
|
||||||
|
params: Vec<VarDecl>,
|
||||||
|
body: Box<Expression>,
|
||||||
|
},
|
||||||
Fix {
|
Fix {
|
||||||
initial: Box<Expression>,
|
initial: Box<Expression>,
|
||||||
prefixes: Vec<Prefix>,
|
prefixes: Vec<Prefix>,
|
||||||
@@ -26,26 +33,35 @@ pub enum Literal {
|
|||||||
Float(f64),
|
Float(f64),
|
||||||
Bool(bool),
|
Bool(bool),
|
||||||
Tuple(Vec<Expression>),
|
Tuple(Vec<Expression>),
|
||||||
Array(Vec<Expression>),
|
|
||||||
ArrayRepeat(Box<Expression>, Box<Expression>),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize)]
|
#[derive(Debug, Clone, Serialize)]
|
||||||
pub enum Pattern {
|
pub enum Pattern {
|
||||||
NamedTuple(Path, Vec<Identifier>),
|
NamedTuple(Path, Vec<Box<Pattern>>),
|
||||||
Struct(Path, Vec<Identifier>),
|
Struct(Path, Vec<Option<(Identifier, Option<Box<Pattern>>)>>),
|
||||||
Tuple(Vec<Identifier>),
|
Tuple(Vec<Box<Pattern>>),
|
||||||
Literal(Literal),
|
Literal(Literal),
|
||||||
Path(Path),
|
Path(bool, Path),
|
||||||
Id(Identifier),
|
Etc,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub enum MacroDelimiter {
|
||||||
|
Paren,
|
||||||
|
Bracket,
|
||||||
|
Brace,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize)]
|
#[derive(Debug, Clone, Serialize)]
|
||||||
pub enum Postfix {
|
pub enum Postfix {
|
||||||
FieldAccess(Identifier, Option<Generics>),
|
FieldAccess(Identifier, Option<Generics>),
|
||||||
|
TupleFieldAccess(u8, Option<Generics>),
|
||||||
Call(Vec<Expression>),
|
Call(Vec<Expression>),
|
||||||
MacroCall(String),
|
MacroCall {
|
||||||
StructCall(Vec<(Identifier, Expression)>),
|
inner: String,
|
||||||
|
delimiter: MacroDelimiter,
|
||||||
|
},
|
||||||
|
StructCall(Vec<(Identifier, Option<Expression>)>),
|
||||||
Assign(String, Box<Expression>),
|
Assign(String, Box<Expression>),
|
||||||
Index(Expression),
|
Index(Expression),
|
||||||
As(TypeExpr),
|
As(TypeExpr),
|
||||||
@@ -59,25 +75,23 @@ pub enum Prefix {
|
|||||||
Ref,
|
Ref,
|
||||||
RefMut,
|
RefMut,
|
||||||
Deref,
|
Deref,
|
||||||
New(Option<Generics>),
|
|
||||||
Not,
|
Not,
|
||||||
Neg,
|
Neg,
|
||||||
Closure(Option<TypeExpr>, Vec<VarDecl>),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize)]
|
#[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash)]
|
||||||
pub struct ExprPathSegment {
|
pub struct ExprPathSegment {
|
||||||
pub ident: Identifier,
|
pub ident: Identifier,
|
||||||
pub generics: Option<Generics>,
|
pub generics: Option<Generics>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize)]
|
#[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash)]
|
||||||
pub struct ExprPath(pub Vec<ExprPathSegment>);
|
pub struct ExprPath(pub Vec<ExprPathSegment>);
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize)]
|
#[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash)]
|
||||||
pub struct Generics(pub Vec<Generic>);
|
pub struct Generics(pub Vec<Generic>);
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize)]
|
#[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash)]
|
||||||
pub enum Generic {
|
pub enum Generic {
|
||||||
Lifetime(Identifier),
|
Lifetime(Identifier),
|
||||||
Type(TypeExpr),
|
Type(TypeExpr),
|
||||||
@@ -92,3 +106,17 @@ impl Expression {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl From<Path> for ExprPath {
|
||||||
|
fn from(path: Path) -> Self {
|
||||||
|
Self(
|
||||||
|
path.0
|
||||||
|
.into_iter()
|
||||||
|
.map(|v| ExprPathSegment {
|
||||||
|
ident: v,
|
||||||
|
generics: None,
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -8,31 +8,35 @@ pub use expr::*;
|
|||||||
pub use statement::*;
|
pub use statement::*;
|
||||||
pub use top_level::*;
|
pub use top_level::*;
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize)]
|
#[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash)]
|
||||||
pub struct Path(pub Vec<Identifier>);
|
pub struct Path(pub Vec<Identifier>);
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize)]
|
#[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash)]
|
||||||
pub struct Identifier(pub String);
|
pub struct Identifier(pub String);
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Default)]
|
#[derive(Debug, Clone, Serialize, Default)]
|
||||||
pub struct ParamList(pub Vec<VarDecl>);
|
pub struct ParamList(pub Vec<VarDecl>);
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize)]
|
#[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash)]
|
||||||
pub struct TypeExpr(pub TypeExprKind, pub Vec<TypePostfix>);
|
pub enum Lifetime {
|
||||||
|
Lifetime(Identifier),
|
||||||
#[derive(Debug, Clone, Serialize)]
|
Unsafe,
|
||||||
pub enum TypePostfix {
|
|
||||||
Ref,
|
|
||||||
RefMut,
|
|
||||||
RefLifetime(Identifier),
|
|
||||||
RefMutLifetime(Identifier),
|
|
||||||
Dyn,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize)]
|
#[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash)]
|
||||||
pub enum TypeExprKind {
|
pub enum TypeExpr {
|
||||||
Path(Path),
|
Ref {
|
||||||
PathParams(Path, Vec<TypeExpr>),
|
lifetime: Option<Lifetime>,
|
||||||
|
mutable: bool,
|
||||||
|
ty: Box<TypeExpr>,
|
||||||
|
},
|
||||||
|
UnsafePtr {
|
||||||
|
mutable: bool,
|
||||||
|
ty: Box<TypeExpr>,
|
||||||
|
},
|
||||||
|
Dyn(Box<TypeExpr>),
|
||||||
|
Path(Path, Option<Generics>),
|
||||||
|
StaticFn(Vec<TypeExpr>, Option<Box<TypeExpr>>),
|
||||||
Tuple(Vec<TypeExpr>),
|
Tuple(Vec<TypeExpr>),
|
||||||
Lifetime(Identifier),
|
Lifetime(Identifier),
|
||||||
}
|
}
|
||||||
@@ -44,25 +48,27 @@ pub struct Spanned<T> {
|
|||||||
pub item: T,
|
pub item: T,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TypeExpr {
|
|
||||||
pub fn no_px(kind: TypeExprKind) -> Self {
|
|
||||||
Self(kind, Vec::new())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<GenericDecl> for Generic {
|
impl From<GenericDecl> for Generic {
|
||||||
fn from(value: GenericDecl) -> Self {
|
fn from(value: GenericDecl) -> Self {
|
||||||
match value {
|
match value {
|
||||||
GenericDecl::Lifetime(life) => Generic::Lifetime(life),
|
GenericDecl::Lifetime(life) => Generic::Lifetime(life),
|
||||||
GenericDecl::Type(ty, _) => {
|
GenericDecl::Type(ty, _) => Generic::Type(TypeExpr::Path(Path(vec![ty]), None)),
|
||||||
Generic::Type(TypeExpr(TypeExprKind::Path(Path(vec![ty])), Vec::new()))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> Spanned<T> {
|
impl Into<Option<Generics>> for GenericsDecl {
|
||||||
pub fn get_comment(&self) -> String {
|
fn into(self) -> Option<Generics> {
|
||||||
format!("/* {}:{} */", self.line, self.column)
|
if self.0.len() == 0 {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(self.into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<GenericsDecl> for Generics {
|
||||||
|
fn from(value: GenericsDecl) -> Self {
|
||||||
|
Self(value.0.into_iter().map(Generic::from).collect())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,40 +3,34 @@ use serde::Serialize;
|
|||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Default)]
|
#[derive(Debug, Clone, Serialize, Default)]
|
||||||
pub struct Block(
|
pub struct Block {
|
||||||
pub Vec<Spanned<Expression>>,
|
pub statements: Vec<Spanned<Expression>>,
|
||||||
pub Option<Spanned<Expression>>,
|
pub soft_return: Option<Spanned<Expression>>,
|
||||||
);
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize)]
|
|
||||||
pub enum StatementBody {
|
|
||||||
Statement(Expression),
|
|
||||||
Expression(Expression),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize)]
|
#[derive(Debug, Clone, Serialize)]
|
||||||
pub enum Statement {
|
pub enum Statement {
|
||||||
|
UnsafeBlock(Block),
|
||||||
Block(Block),
|
Block(Block),
|
||||||
If {
|
If {
|
||||||
initial: StatementBranch,
|
initial: StatementBranch,
|
||||||
else_if: Vec<StatementBranch>,
|
else_if: Vec<StatementBranch>,
|
||||||
else_branch: Option<StatementBody>,
|
else_branch: Option<Block>,
|
||||||
},
|
},
|
||||||
Loop(StatementBody),
|
Loop(Block),
|
||||||
While(StatementBranch),
|
While(StatementBranch),
|
||||||
CStyleFor {
|
CStyleFor {
|
||||||
init: Expression,
|
init: Expression,
|
||||||
condition: Expression,
|
condition: Expression,
|
||||||
update: Expression,
|
update: Expression,
|
||||||
body: StatementBody,
|
body: Block,
|
||||||
},
|
},
|
||||||
For {
|
For {
|
||||||
mutable: bool,
|
|
||||||
pattern: Pattern,
|
pattern: Pattern,
|
||||||
iterator: Expression,
|
iterator: Expression,
|
||||||
body: StatementBody,
|
body: Block,
|
||||||
},
|
},
|
||||||
Match(Expression, Vec<(Vec<Pattern>, Expression)>),
|
Match(Expression, Vec<Spanned<MatchItem>>),
|
||||||
|
|
||||||
VarDecl(VarDeclStmt),
|
VarDecl(VarDeclStmt),
|
||||||
Return(Option<Expression>),
|
Return(Option<Expression>),
|
||||||
@@ -44,9 +38,11 @@ pub enum Statement {
|
|||||||
Continue,
|
Continue,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct MatchItem(pub Vec<Pattern>, pub Expression);
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize)]
|
#[derive(Debug, Clone, Serialize)]
|
||||||
pub struct VarDecl {
|
pub struct VarDecl {
|
||||||
pub mutable: bool,
|
|
||||||
pub name: Pattern,
|
pub name: Pattern,
|
||||||
pub type_: Option<TypeExpr>,
|
pub type_: Option<TypeExpr>,
|
||||||
}
|
}
|
||||||
@@ -60,29 +56,14 @@ pub struct VarDeclStmt {
|
|||||||
#[derive(Debug, Clone, Serialize)]
|
#[derive(Debug, Clone, Serialize)]
|
||||||
pub struct StatementBranch {
|
pub struct StatementBranch {
|
||||||
pub condition: Expression,
|
pub condition: Expression,
|
||||||
pub body: Box<StatementBody>,
|
pub body: Box<Block>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Statement {
|
impl Statement {
|
||||||
pub fn is_block(&self) -> bool {
|
pub fn is_block(&self) -> bool {
|
||||||
match self {
|
match self {
|
||||||
Self::Block(_)
|
Self::VarDecl(_) | Self::Return(_) | Self::Break | Self::Continue => false,
|
||||||
| Self::Match(_, _)
|
_ => true,
|
||||||
| Self::While(_)
|
|
||||||
| Self::For { .. }
|
|
||||||
| Self::Loop(..)
|
|
||||||
| Self::CStyleFor { .. }
|
|
||||||
| Self::If { .. } => true,
|
|
||||||
_ => false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl StatementBody {
|
|
||||||
pub fn is_soft_return(&self) -> bool {
|
|
||||||
match self {
|
|
||||||
Self::Expression(_) => true,
|
|
||||||
_ => false,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ pub struct TopLevel(pub Spanned<TopLevelKind>, pub Vec<Attribute>);
|
|||||||
pub enum TopLevelKind {
|
pub enum TopLevelKind {
|
||||||
ModAttribute,
|
ModAttribute,
|
||||||
Import(Visibility, Path),
|
Import(Visibility, Path),
|
||||||
Mod(Visibility, Identifier),
|
DeclareModule(Visibility, Identifier),
|
||||||
ImplDecl(ImplDecl),
|
ImplDecl(ImplDecl),
|
||||||
TraitDecl {
|
TraitDecl {
|
||||||
visibility: Visibility,
|
visibility: Visibility,
|
||||||
@@ -54,8 +54,9 @@ pub enum TopLevelKind {
|
|||||||
visibility: Visibility,
|
visibility: Visibility,
|
||||||
name: Identifier,
|
name: Identifier,
|
||||||
generics: GenericsDecl,
|
generics: GenericsDecl,
|
||||||
|
inherits: Option<ExprPath>,
|
||||||
fields: Vec<Spanned<FieldDeclStmt>>,
|
fields: Vec<Spanned<FieldDeclStmt>>,
|
||||||
constructor: Spanned<ClassConstructor>,
|
constructor: Option<Spanned<ClassConstructor>>,
|
||||||
items: Vec<ClassItem>,
|
items: Vec<ClassItem>,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -90,13 +91,17 @@ pub struct ClassConstructor {
|
|||||||
pub body: Block,
|
pub body: Block,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash)]
|
||||||
|
pub struct Override(pub Option<ExprPath>);
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize)]
|
#[derive(Debug, Clone, Serialize)]
|
||||||
pub struct FunctionDecl {
|
pub struct FunctionDecl {
|
||||||
pub visibility: Visibility,
|
pub visibility: Visibility,
|
||||||
|
pub is_override: Option<Override>,
|
||||||
pub name: Identifier,
|
pub name: Identifier,
|
||||||
pub generics: GenericsDecl,
|
pub generics: GenericsDecl,
|
||||||
pub params: ParamList,
|
pub params: ParamList,
|
||||||
pub return_type: TypeExpr,
|
pub return_type: Option<TypeExpr>,
|
||||||
pub body: Option<Block>,
|
pub body: Option<Block>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -120,3 +125,18 @@ pub struct FieldDeclStmt {
|
|||||||
pub decl: FieldDecl,
|
pub decl: FieldDecl,
|
||||||
pub init: Option<Expression>,
|
pub init: Option<Expression>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl FunctionDecl {
|
||||||
|
pub fn is_using_self(&self) -> bool {
|
||||||
|
match self.params.0.get(0) {
|
||||||
|
Some(VarDecl { name, .. }) => {
|
||||||
|
if let Pattern::Path(_, v) = name {
|
||||||
|
v.0.len() == 1 && v.0[0].0 == "self"
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ pub struct AstError<'a, T> {
|
|||||||
pub enum ErrorCode {
|
pub enum ErrorCode {
|
||||||
InvalidStatement,
|
InvalidStatement,
|
||||||
AstGenBug,
|
AstGenBug,
|
||||||
|
Module,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> From<pest::error::Error<Rule>> for ParseError<'_, T> {
|
impl<T> From<pest::error::Error<Rule>> for ParseError<'_, T> {
|
||||||
|
|||||||
+110
-71
@@ -25,11 +25,14 @@ keyword = {
|
|||||||
| "impl"
|
| "impl"
|
||||||
| "pub"
|
| "pub"
|
||||||
| "mut"
|
| "mut"
|
||||||
| "var"
|
| "let"
|
||||||
| "true"
|
| "true"
|
||||||
| "false"
|
| "false"
|
||||||
| "dyn"
|
| "dyn"
|
||||||
| "loop"
|
| "loop"
|
||||||
|
| "fn"
|
||||||
|
| "unsafe"
|
||||||
|
| "override"
|
||||||
}
|
}
|
||||||
|
|
||||||
identifier = @{
|
identifier = @{
|
||||||
@@ -69,21 +72,25 @@ program = {
|
|||||||
SOI ~ top_level* ~ EOI
|
SOI ~ top_level* ~ EOI
|
||||||
}
|
}
|
||||||
|
|
||||||
|
module_program = {
|
||||||
|
SOI ~ top_level?
|
||||||
|
}
|
||||||
|
|
||||||
// ======================================================
|
// ======================================================
|
||||||
// MODIFIERS
|
// MODIFIERS
|
||||||
// ======================================================
|
// ======================================================
|
||||||
|
|
||||||
visibility = { "pub" ~ ("(" ~ static_path ~ ")")? }
|
visibility = { "pub" ~ ("(" ~ static_path ~ ")")? }
|
||||||
mutable = { "mut" }
|
mutable = { "mut" }
|
||||||
var = { "var" }
|
unsafe_kw = { "unsafe" }
|
||||||
|
|
||||||
// ======================================================
|
// ======================================================
|
||||||
// GENERICS
|
// GENERICS
|
||||||
// ======================================================
|
// ======================================================
|
||||||
generic_decl = { lifetime | (identifier ~ (":" ~ type_expr_param ~ ("+" ~ type_expr_param)*)?) }
|
generic_decl = { lifetime | (identifier ~ (":" ~ generic ~ ("+" ~ generic)*)?) }
|
||||||
generics_decl = { "<" ~ (generic_decl ~ ("," ~ generic_decl)*)? ~ ">" }
|
generics_decl = { "<" ~ (generic_decl ~ ("," ~ generic_decl)*)? ~ ">" }
|
||||||
|
|
||||||
generic = { lifetime | type_expr_param }
|
generic = { lifetime | type_expr }
|
||||||
generics = { "<" ~ (generic ~ ("," ~ generic)*)? ~ ">" }
|
generics = { "<" ~ (generic ~ ("," ~ generic)*)? ~ ">" }
|
||||||
|
|
||||||
// ======================================================
|
// ======================================================
|
||||||
@@ -91,34 +98,31 @@ generics = { "<" ~ (generic ~ ("," ~ generic)*)? ~ ">" }
|
|||||||
// ======================================================
|
// ======================================================
|
||||||
|
|
||||||
tuple_type = {
|
tuple_type = {
|
||||||
"[" ~ (type_expr ~ ("," ~ type_expr)*)? ~ "]"
|
"(" ~ (type_expr ~ ("," ~ type_expr)*)? ~ ","? ~ ")"
|
||||||
}
|
}
|
||||||
|
|
||||||
path_type = {
|
path_type = {
|
||||||
static_path ~ ("<" ~ (type_expr_param ~ ("," ~ type_expr_param)*)? ~ ">")?
|
static_path ~ generics?
|
||||||
}
|
}
|
||||||
|
|
||||||
|
ref_lifetime = { lifetime | unsafe_kw }
|
||||||
|
|
||||||
ref_type = {
|
ref_type = {
|
||||||
mutable? ~ lifetime? ~ "*"
|
"*" ~ ref_lifetime? ~ mutable? ~ type_expr
|
||||||
}
|
}
|
||||||
|
|
||||||
dyn_type = {
|
dyn_type = {
|
||||||
"dyn"
|
"dyn" ~ type_expr
|
||||||
}
|
}
|
||||||
|
|
||||||
type_expr = {
|
type_expr = {
|
||||||
(path_type | tuple_type) ~ (ref_type | dyn_type)*
|
(path_type | tuple_type | ref_type | dyn_type)
|
||||||
}
|
}
|
||||||
|
|
||||||
lifetime = {
|
lifetime = {
|
||||||
"'" ~ identifier
|
"'" ~ identifier
|
||||||
}
|
}
|
||||||
|
|
||||||
type_expr_param = {
|
|
||||||
type_expr
|
|
||||||
| lifetime
|
|
||||||
}
|
|
||||||
|
|
||||||
// ======================================================
|
// ======================================================
|
||||||
// LITERALS
|
// LITERALS
|
||||||
// ======================================================
|
// ======================================================
|
||||||
@@ -134,16 +138,30 @@ literal = {
|
|||||||
// PATTERNS
|
// PATTERNS
|
||||||
// ======================================================
|
// ======================================================
|
||||||
|
|
||||||
|
etc_pattern = { ".." }
|
||||||
|
|
||||||
|
multi_pat_template = _{
|
||||||
|
((pattern | etc_pattern) ~ ("," ~ (pattern | etc_pattern))*)?
|
||||||
|
}
|
||||||
|
|
||||||
tuple_pattern = {
|
tuple_pattern = {
|
||||||
"[" ~ (identifier ~ ("," ~ identifier)*) ~ "]"
|
"(" ~ (pattern | etc_pattern) ~ "," ~ multi_pat_template ~ ")"
|
||||||
}
|
}
|
||||||
|
|
||||||
named_tuple_pattern = {
|
named_tuple_pattern = {
|
||||||
static_path ~ "[" ~ (identifier ~ ("," ~ identifier)*)? ~ "]"
|
static_path ~ "(" ~ multi_pat_template ~ ")"
|
||||||
|
}
|
||||||
|
|
||||||
|
struct_destruct = {
|
||||||
|
identifier ~ (":" ~ pattern)?
|
||||||
}
|
}
|
||||||
|
|
||||||
struct_pattern = {
|
struct_pattern = {
|
||||||
static_path ~ "{" ~ (identifier ~ ("," ~ identifier)*)? ~ "}"
|
static_path ~ "{" ~ ((struct_destruct | etc_pattern) ~ ("," ~ (struct_destruct | etc_pattern))*)? ~ "}"
|
||||||
|
}
|
||||||
|
|
||||||
|
path_pattern = {
|
||||||
|
mutable? ~ static_path
|
||||||
}
|
}
|
||||||
|
|
||||||
pattern = _{
|
pattern = _{
|
||||||
@@ -151,7 +169,7 @@ pattern = _{
|
|||||||
| tuple_pattern
|
| tuple_pattern
|
||||||
| struct_pattern
|
| struct_pattern
|
||||||
| literal
|
| literal
|
||||||
| static_path
|
| path_pattern
|
||||||
}
|
}
|
||||||
|
|
||||||
// ======================================================
|
// ======================================================
|
||||||
@@ -171,7 +189,7 @@ meta = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
meta_list = {
|
meta_list = {
|
||||||
meta ~ ("," ~ meta)* ~ ","?
|
(meta ~ ("," ~ meta)* ~ ","?)?
|
||||||
}
|
}
|
||||||
|
|
||||||
attributes = {
|
attributes = {
|
||||||
@@ -182,19 +200,23 @@ attributes = {
|
|||||||
// DECLARATION HELPERS
|
// DECLARATION HELPERS
|
||||||
// ======================================================
|
// ======================================================
|
||||||
var_decl = {
|
var_decl = {
|
||||||
(var | type_expr) ~ mutable? ~ pattern
|
"let" ~ pattern ~ type_expr?
|
||||||
}
|
}
|
||||||
|
|
||||||
field = {
|
field = {
|
||||||
visibility? ~ type_expr ~ identifier
|
visibility? ~ identifier ~ type_expr
|
||||||
|
}
|
||||||
|
|
||||||
|
param = {
|
||||||
|
pattern ~ type_expr?
|
||||||
}
|
}
|
||||||
|
|
||||||
field_list = {
|
field_list = {
|
||||||
field ~ ("," ~ field)* ~ ","?
|
(field ~ ("," ~ field)* ~ ","?)?
|
||||||
}
|
}
|
||||||
|
|
||||||
param_list = {
|
param_list = {
|
||||||
var_decl ~ ("," ~ var_decl)* ~ ","?
|
(param ~ ("," ~ param)* ~ ","?)?
|
||||||
}
|
}
|
||||||
|
|
||||||
// ======================================================
|
// ======================================================
|
||||||
@@ -202,11 +224,11 @@ param_list = {
|
|||||||
// ======================================================
|
// ======================================================
|
||||||
|
|
||||||
import = {
|
import = {
|
||||||
visibility? ~ "use" ~ "<" ~ static_path ~ ">" ~ semicolon
|
visibility? ~ "use" ~ static_path ~ semicolon
|
||||||
}
|
}
|
||||||
|
|
||||||
mod_package = {
|
declare_module = {
|
||||||
visibility? ~ "mod" ~ identifier ~ semicolon
|
visibility? ~ "module" ~ identifier ~ semicolon
|
||||||
}
|
}
|
||||||
|
|
||||||
// ======================================================
|
// ======================================================
|
||||||
@@ -252,7 +274,7 @@ enum_decl = {
|
|||||||
// ======================================================
|
// ======================================================
|
||||||
|
|
||||||
class_constructor = {
|
class_constructor = {
|
||||||
visibility? ~ "constructor" ~ generics_decl? ~ "(" ~ param_list? ~ ")" ~ block
|
visibility? ~ "constructor" ~ generics_decl? ~ "(" ~ param_list ~ ")" ~ block
|
||||||
}
|
}
|
||||||
|
|
||||||
class_fields = {
|
class_fields = {
|
||||||
@@ -264,45 +286,40 @@ class_field = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
self_param = {
|
self_param = {
|
||||||
"self" ~ mutable? ~ deref_px?
|
(deref_px ~ lifetime?)? ~ mutable? ~ "self"
|
||||||
}
|
}
|
||||||
|
|
||||||
method = {
|
method_args = _{
|
||||||
visibility? ~ type_expr ~ identifier ~ generics_decl? ~ "(" ~ self_param? ~ ("," ~ param_list?)? ~ ")" ~ block
|
((self_param ~ ("," ~ param_list)?) | param_list) ~ ","?
|
||||||
}
|
}
|
||||||
|
|
||||||
class_item = _{
|
class_item = _{
|
||||||
impl_decl
|
impl_decl
|
||||||
| method
|
| function_decl
|
||||||
}
|
}
|
||||||
|
|
||||||
class_decl = {
|
class_decl = {
|
||||||
visibility? ~ "class" ~ identifier ~ generics_decl? ~ "{" ~ class_fields ~ class_constructor ~ class_item* ~ "}"
|
visibility? ~ "class" ~ identifier ~ generics_decl? ~ (":" ~ expr_path)? ~ "{" ~ class_fields ~ class_constructor? ~ class_item* ~ "}"
|
||||||
}
|
}
|
||||||
|
|
||||||
// ======================================================
|
// ======================================================
|
||||||
// IMPL
|
// IMPL
|
||||||
// ======================================================
|
// ======================================================
|
||||||
impl_for_decl = {
|
impl_for_decl = {
|
||||||
"impl" ~ generics_decl? ~ type_expr ~ "for" ~ type_expr ~ "{" ~ method* ~ "}"
|
"impl" ~ generics_decl? ~ type_expr ~ "for" ~ type_expr ~ "{" ~ function_decl* ~ "}"
|
||||||
}
|
}
|
||||||
|
|
||||||
impl_decl = {
|
impl_decl = {
|
||||||
"impl" ~ generics_decl? ~ type_expr ~ "{" ~ method* ~ "}"
|
"impl" ~ generics_decl? ~ type_expr ~ "{" ~ function_decl* ~ "}"
|
||||||
}
|
}
|
||||||
|
|
||||||
// ======================================================
|
// ======================================================
|
||||||
// Traits
|
// Traits
|
||||||
// ======================================================
|
// ======================================================
|
||||||
trait_requirements = { ":" ~ type_expr_param ~ ("+" ~ type_expr_param)* }
|
trait_requirements = { ":" ~ generic ~ ("+" ~ generic)* }
|
||||||
|
|
||||||
method_no_body = {
|
|
||||||
visibility? ~ type_expr ~ identifier ~ generics_decl? ~ "(" ~ self_param? ~ ("," ~ param_list?)? ~ ")" ~ semicolon
|
|
||||||
}
|
|
||||||
|
|
||||||
trait_item = _{
|
trait_item = _{
|
||||||
method
|
function_decl
|
||||||
| method_no_body
|
|
||||||
}
|
}
|
||||||
|
|
||||||
trait_decl = {
|
trait_decl = {
|
||||||
@@ -313,8 +330,10 @@ trait_decl = {
|
|||||||
// FUNCTIONS
|
// FUNCTIONS
|
||||||
// ======================================================
|
// ======================================================
|
||||||
|
|
||||||
|
override_kw = { "override" ~ ("(" ~ expr_path ~ ")")? }
|
||||||
|
|
||||||
function_decl = {
|
function_decl = {
|
||||||
visibility? ~ type_expr ~ identifier ~ "(" ~ param_list? ~ ")" ~ block
|
visibility? ~ "fn" ~ ("void" | type_expr) ~ identifier ~ generics_decl? ~ "(" ~ method_args ~ ")" ~ override_kw? ~ (block | semicolon)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ======================================================
|
// ======================================================
|
||||||
@@ -322,7 +341,7 @@ function_decl = {
|
|||||||
// ======================================================
|
// ======================================================
|
||||||
|
|
||||||
top_level = {
|
top_level = {
|
||||||
(attributes ~ (import | impl_for_decl | impl_decl | trait_decl | struct_decl | enum_decl | class_decl | mod_package | function_decl))
|
(attributes ~ (import | impl_for_decl | impl_decl | trait_decl | struct_decl | enum_decl | class_decl | declare_module | function_decl))
|
||||||
| mod_attribute
|
| mod_attribute
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -334,6 +353,10 @@ block = {
|
|||||||
"{" ~ statement_list ~ expr? ~ "}"
|
"{" ~ statement_list ~ expr? ~ "}"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
unsafe_block = {
|
||||||
|
"unsafe" ~ block
|
||||||
|
}
|
||||||
|
|
||||||
statement_list = {
|
statement_list = {
|
||||||
statement*
|
statement*
|
||||||
}
|
}
|
||||||
@@ -343,10 +366,6 @@ statement = _{
|
|||||||
| (expr ~ semicolon)
|
| (expr ~ semicolon)
|
||||||
}
|
}
|
||||||
|
|
||||||
statement_wrapper = { statement }
|
|
||||||
|
|
||||||
statement_body = { statement_wrapper | expr }
|
|
||||||
|
|
||||||
// ------------------------------------------------------
|
// ------------------------------------------------------
|
||||||
// BASIC STATEMENTS
|
// BASIC STATEMENTS
|
||||||
// ------------------------------------------------------
|
// ------------------------------------------------------
|
||||||
@@ -386,11 +405,12 @@ control_flow = {
|
|||||||
| match_stmt
|
| match_stmt
|
||||||
| loop_stmt
|
| loop_stmt
|
||||||
| block
|
| block
|
||||||
|
| unsafe_block
|
||||||
}
|
}
|
||||||
|
|
||||||
statement_branch = { "(" ~ expr ~ ")" ~ statement_body }
|
statement_branch = { (expr_no_struct | ("(" ~ expr ~ ")")) ~ block }
|
||||||
|
|
||||||
else_if = {
|
else_if = _{
|
||||||
"else" ~ "if" ~ statement_branch
|
"else" ~ "if" ~ statement_branch
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -399,7 +419,7 @@ else_if_list = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if_stmt = {
|
if_stmt = {
|
||||||
"if" ~ statement_branch ~ else_if_list ~ ("else" ~ statement_body)?
|
"if" ~ statement_branch ~ else_if_list ~ ("else" ~ block)?
|
||||||
}
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------
|
// ------------------------------------------------------
|
||||||
@@ -411,15 +431,15 @@ while_stmt = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
c_for_stmt = {
|
c_for_stmt = {
|
||||||
"for" ~ "(" ~ statement ~ statement ~ expr ~ ")" ~ statement_body
|
"for" ~ "(" ~ statement ~ statement ~ expr ~ ")" ~ block
|
||||||
}
|
}
|
||||||
|
|
||||||
for_stmt = {
|
for_stmt = {
|
||||||
"for" ~ "(" ~ mutable? ~ pattern ~ ":" ~ expr ~ ")" ~ statement_body
|
"for" ~ pattern ~ "in" ~ expr ~ block
|
||||||
}
|
}
|
||||||
|
|
||||||
loop_stmt = {
|
loop_stmt = {
|
||||||
"loop" ~ statement_body
|
"loop" ~ block
|
||||||
}
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------
|
// ------------------------------------------------------
|
||||||
@@ -433,7 +453,7 @@ match_item = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
match_stmt = {
|
match_stmt = {
|
||||||
"match" ~ "(" ~ expr ~ ")" ~ "{" ~ match_item* ~ "}"
|
"match" ~ (expr_no_struct | "(" ~ expr ~ ")") ~ "{" ~ match_item* ~ "}"
|
||||||
}
|
}
|
||||||
|
|
||||||
// ======================================================
|
// ======================================================
|
||||||
@@ -444,20 +464,25 @@ match_stmt = {
|
|||||||
// CLOSURES
|
// CLOSURES
|
||||||
// ------------------------------------------------------
|
// ------------------------------------------------------
|
||||||
|
|
||||||
closure = { type_expr? ~ "|" ~ param_list ~ "|" }
|
closure = {
|
||||||
|
"fn" ~ "(" ~ param_list ~ ")" ~ type_expr? ~ block
|
||||||
|
| "fn" ~ "(" ~ param_list ~ ")" ~ type_expr? ~ "->" ~ expr
|
||||||
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------
|
// ------------------------------------------------------
|
||||||
// TUPLES & ARRAYS
|
// TUPLES & ARRAYS
|
||||||
// ------------------------------------------------------
|
// ------------------------------------------------------
|
||||||
|
|
||||||
tuple = {
|
tuple = {
|
||||||
"(" ~ (expr ~ ("," ~ expr)*)? ~ ")"
|
"(" ~ (expr ~ ("," ~ expr)*)? ~ ","? ~ ")"
|
||||||
|
}
|
||||||
|
|
||||||
|
array_repeat = {
|
||||||
|
"[" ~ expr ~ ";" ~ expr ~ "]"
|
||||||
}
|
}
|
||||||
|
|
||||||
array = {
|
array = {
|
||||||
"[" ~ expr ~ ";" ~ expr ~ "]" // Repeat notation: [0; 10]
|
"[" ~ (expr ~ ("," ~ expr)* ~ ","?)? ~ "]"
|
||||||
|
|
||||||
| "[" ~ (expr ~ ("," ~ expr)* ~ ","?)? ~ "]" // Standard elements initialization
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------
|
// ------------------------------------------------------
|
||||||
@@ -467,7 +492,9 @@ array = {
|
|||||||
macro_inner_v = @{
|
macro_inner_v = @{
|
||||||
string_lit
|
string_lit
|
||||||
| ("(" ~ macro_inner_v* ~ ")")
|
| ("(" ~ macro_inner_v* ~ ")")
|
||||||
| (!("(" | ")") ~ ANY)
|
| ("[" ~ macro_inner_v* ~ "]")
|
||||||
|
| ("{" ~ macro_inner_v* ~ "}")
|
||||||
|
| (!("(" | ")" | "[" | "]" | "{" | "}") ~ ANY)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------
|
// ------------------------------------------------------
|
||||||
@@ -475,7 +502,7 @@ macro_inner_v = @{
|
|||||||
// ------------------------------------------------------
|
// ------------------------------------------------------
|
||||||
|
|
||||||
expr_path_segment = {
|
expr_path_segment = {
|
||||||
identifier ~ ("::" ~ generics)?
|
identifier ~ generics?
|
||||||
}
|
}
|
||||||
|
|
||||||
expr_path = {
|
expr_path = {
|
||||||
@@ -484,10 +511,12 @@ expr_path = {
|
|||||||
|
|
||||||
primary = {
|
primary = {
|
||||||
control_flow
|
control_flow
|
||||||
|
| closure
|
||||||
| basic_stmt
|
| basic_stmt
|
||||||
| literal
|
| literal
|
||||||
| expr_path
|
| expr_path
|
||||||
| tuple
|
| tuple
|
||||||
|
| array_repeat
|
||||||
| array
|
| array
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -496,19 +525,23 @@ primary = {
|
|||||||
// ------------------------------------------------------
|
// ------------------------------------------------------
|
||||||
|
|
||||||
field_px = {
|
field_px = {
|
||||||
"." ~ identifier ~ ("::" ~ generics)?
|
"." ~ identifier ~ generics?
|
||||||
|
}
|
||||||
|
|
||||||
|
tuple_field_px = {
|
||||||
|
"." ~ integer ~ generics?
|
||||||
}
|
}
|
||||||
|
|
||||||
call_px = {
|
call_px = {
|
||||||
"(" ~ (expr ~ ("," ~ expr)*)? ~ ")"
|
"(" ~ (expr ~ ("," ~ expr)*)? ~ ")"
|
||||||
}
|
}
|
||||||
|
|
||||||
macro_call_px = {
|
macro_call_paren = { "!" ~ "(" ~ macro_inner_v* ~ ")" }
|
||||||
"!" ~ "(" ~ macro_inner_v* ~ ")"
|
macro_call_bracket = { "!" ~ "[" ~ macro_inner_v* ~ "]" }
|
||||||
}
|
macro_call_brace = { "!" ~ "{" ~ macro_inner_v* ~ "}" }
|
||||||
|
|
||||||
struct_field_decl = {
|
struct_field_decl = {
|
||||||
identifier ~ ":" ~ expr
|
identifier ~ (":" ~ expr)?
|
||||||
}
|
}
|
||||||
|
|
||||||
struct_px = {
|
struct_px = {
|
||||||
@@ -537,8 +570,11 @@ decrement = {
|
|||||||
|
|
||||||
postfix = {
|
postfix = {
|
||||||
field_px
|
field_px
|
||||||
|
| tuple_field_px
|
||||||
| call_px
|
| call_px
|
||||||
| macro_call_px
|
| macro_call_paren
|
||||||
|
| macro_call_bracket
|
||||||
|
| macro_call_brace
|
||||||
| struct_px
|
| struct_px
|
||||||
| index_px
|
| index_px
|
||||||
| as_px
|
| as_px
|
||||||
@@ -554,16 +590,13 @@ postfix = {
|
|||||||
deref_px = { "*" }
|
deref_px = { "*" }
|
||||||
mut_ref_px = { "&" ~ mutable }
|
mut_ref_px = { "&" ~ mutable }
|
||||||
ref_px = { "&" }
|
ref_px = { "&" }
|
||||||
new_px = { "new" ~ generics? }
|
|
||||||
not_px = { "!" }
|
not_px = { "!" }
|
||||||
neg_px = { "-" }
|
neg_px = { "-" }
|
||||||
|
|
||||||
prefix = {
|
prefix = {
|
||||||
closure
|
deref_px
|
||||||
| deref_px
|
|
||||||
| mut_ref_px
|
| mut_ref_px
|
||||||
| ref_px
|
| ref_px
|
||||||
| new_px
|
|
||||||
| not_px
|
| not_px
|
||||||
| neg_px
|
| neg_px
|
||||||
}
|
}
|
||||||
@@ -575,6 +608,7 @@ prefix = {
|
|||||||
bin_op = {
|
bin_op = {
|
||||||
"+="
|
"+="
|
||||||
| "-="
|
| "-="
|
||||||
|
| "*="
|
||||||
| "/="
|
| "/="
|
||||||
| "%="
|
| "%="
|
||||||
| "&="
|
| "&="
|
||||||
@@ -592,6 +626,7 @@ bin_op = {
|
|||||||
| "!="
|
| "!="
|
||||||
| "&&"
|
| "&&"
|
||||||
| "||"
|
| "||"
|
||||||
|
| "->"
|
||||||
| "+"
|
| "+"
|
||||||
| "-"
|
| "-"
|
||||||
| "*"
|
| "*"
|
||||||
@@ -612,3 +647,7 @@ bin_op = {
|
|||||||
expr = { term ~ (bin_op ~ term)* }
|
expr = { term ~ (bin_op ~ term)* }
|
||||||
|
|
||||||
term = { prefix* ~ primary ~ postfix* }
|
term = { prefix* ~ primary ~ postfix* }
|
||||||
|
|
||||||
|
expr_no_struct = { term_no_struct ~ (bin_op ~ term_no_struct)* }
|
||||||
|
|
||||||
|
term_no_struct = { prefix* ~ primary ~ (!struct_px ~ postfix)* }
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ pub mod ast;
|
|||||||
pub mod error;
|
pub mod error;
|
||||||
pub mod parser;
|
pub mod parser;
|
||||||
pub mod rev_mapper;
|
pub mod rev_mapper;
|
||||||
|
pub mod semantics;
|
||||||
|
|
||||||
use ast::*;
|
use ast::*;
|
||||||
|
|
||||||
@@ -29,7 +30,39 @@ pub fn parse<'a>(source: &'a str) -> Result<Vec<TopLevel>, ParseError<'a, Vec<To
|
|||||||
|
|
||||||
match analyzer.build(statements) {
|
match analyzer.build(statements) {
|
||||||
Ok(v) => Ok(v),
|
Ok(v) => Ok(v),
|
||||||
Err(e) => Err(ParseError::Ast(e)),
|
Err(e) => {
|
||||||
|
let rec = e.recovered.clone();
|
||||||
|
|
||||||
|
let mut e2 = e.get();
|
||||||
|
|
||||||
|
e2.recovered = rec;
|
||||||
|
|
||||||
|
Err(ParseError::Ast(e2))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parse_module<'a>(
|
||||||
|
source: &'a str,
|
||||||
|
) -> Result<Option<(Visibility, Identifier)>, ParseError<'a, Option<(Visibility, Identifier)>>> {
|
||||||
|
let mut pairs = MistParser::parse(Rule::module_program, source)?;
|
||||||
|
|
||||||
|
if let Some(v) = pairs
|
||||||
|
.next()
|
||||||
|
.unwrap()
|
||||||
|
.into_inner()
|
||||||
|
.next()
|
||||||
|
.map(TopLevel::try_from)
|
||||||
|
.transpose()
|
||||||
|
.get()?
|
||||||
|
{
|
||||||
|
if let TopLevelKind::DeclareModule(vis, name) = &v.0.item {
|
||||||
|
Ok(Some((vis.clone(), name.clone())))
|
||||||
|
} else {
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Ok(None)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -77,6 +110,14 @@ macro_rules! ast_expr {
|
|||||||
analyzer.build(v)
|
analyzer.build(v)
|
||||||
}};
|
}};
|
||||||
|
|
||||||
|
(( $($v:expr),* $(,)? )) => {{
|
||||||
|
let mut analyzer = $crate::error::AstErrorAnalyzer(None);
|
||||||
|
|
||||||
|
let v = ( $(analyzer.get($v).get()?),* );
|
||||||
|
|
||||||
|
analyzer.build(v)
|
||||||
|
}};
|
||||||
|
|
||||||
($($item:ident)::+) => {
|
($($item:ident)::+) => {
|
||||||
$($item)::+
|
$($item)::+
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -2,8 +2,7 @@ use crate::{
|
|||||||
Rule,
|
Rule,
|
||||||
ast::*,
|
ast::*,
|
||||||
ast_expr,
|
ast_expr,
|
||||||
error::{AstError, AstResult, IntoErr},
|
error::{AstError, IntoErr, collect_recovered},
|
||||||
parser::listen_rule,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for VarDeclStmt {
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for VarDeclStmt {
|
||||||
@@ -49,28 +48,12 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for VarDecl {
|
|||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
match pair.as_rule() {
|
match pair.as_rule() {
|
||||||
Rule::var_decl => {
|
Rule::var_decl | Rule::param => {
|
||||||
let mut inner = pair.into_inner();
|
let mut inner = pair.into_inner();
|
||||||
|
|
||||||
let type_ = inner
|
|
||||||
.next()
|
|
||||||
.and_then(|pair| {
|
|
||||||
if pair.as_str().trim() == "var" {
|
|
||||||
None
|
|
||||||
} else {
|
|
||||||
Some(TypeExpr::try_from(pair))
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.transpose();
|
|
||||||
|
|
||||||
let mutable: AstResult<'_, bool> = Ok(listen_rule(&mut inner, Rule::mutable));
|
|
||||||
|
|
||||||
let name = Pattern::try_from(inner.next().unwrap());
|
|
||||||
|
|
||||||
ast_expr!(VarDecl {
|
ast_expr!(VarDecl {
|
||||||
type_: type_,
|
name: Pattern::try_from(inner.next().unwrap()),
|
||||||
mutable: mutable,
|
type_: inner.next().map(TypeExpr::try_from).transpose(),
|
||||||
name: name,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,8 +72,8 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FieldDecl {
|
|||||||
|
|
||||||
ast_expr!(FieldDecl {
|
ast_expr!(FieldDecl {
|
||||||
visibility: Visibility::try_from(&mut inner),
|
visibility: Visibility::try_from(&mut inner),
|
||||||
type_: TypeExpr::try_from(inner.next().unwrap()),
|
|
||||||
name: Identifier::try_from(inner.next().unwrap()),
|
name: Identifier::try_from(inner.next().unwrap()),
|
||||||
|
type_: TypeExpr::try_from(inner.next().unwrap()),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -98,3 +81,11 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FieldDecl {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for ParamList {
|
||||||
|
type Error = AstError<'a, Self>;
|
||||||
|
|
||||||
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
|
Ok(ParamList(collect_recovered(pair.into_inner()).get()?))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Expression {
|
|||||||
let mut inner = pair.clone().into_inner();
|
let mut inner = pair.clone().into_inner();
|
||||||
|
|
||||||
match rule {
|
match rule {
|
||||||
Rule::expr => {
|
Rule::expr | Rule::expr_no_struct => {
|
||||||
static PRATT_PARSER: OnceLock<PrattParser<Rule>> = OnceLock::new();
|
static PRATT_PARSER: OnceLock<PrattParser<Rule>> = OnceLock::new();
|
||||||
let pratt = PRATT_PARSER.get_or_init(|| {
|
let pratt = PRATT_PARSER.get_or_init(|| {
|
||||||
use pest::pratt_parser::{Assoc::*, Op};
|
use pest::pratt_parser::{Assoc::*, Op};
|
||||||
@@ -36,7 +36,7 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Expression {
|
|||||||
.parse(inner)
|
.parse(inner)
|
||||||
}
|
}
|
||||||
|
|
||||||
Rule::term => {
|
Rule::term | Rule::term_no_struct => {
|
||||||
let mut prefix_pairs = Vec::new();
|
let mut prefix_pairs = Vec::new();
|
||||||
let mut primary_pair = None;
|
let mut primary_pair = None;
|
||||||
let mut postfix_pairs = Vec::new();
|
let mut postfix_pairs = Vec::new();
|
||||||
@@ -75,20 +75,32 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Expression {
|
|||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Rule::closure => {
|
||||||
|
ast_expr!(Expression::Closure {
|
||||||
|
params: collect_recovered(inner.next().unwrap().into_inner()),
|
||||||
|
return_type: consume_rule(&mut inner, Rule::type_expr)
|
||||||
|
.map(TypeExpr::try_from)
|
||||||
|
.transpose(),
|
||||||
|
body: Expression::try_from(inner.next().unwrap()).map(Box::new),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
Rule::array => {
|
||||||
|
ast_expr!(Expression::Array(collect_recovered(inner)))
|
||||||
|
}
|
||||||
|
|
||||||
|
Rule::array_repeat => {
|
||||||
|
ast_expr!(Expression::ArrayRepeat(
|
||||||
|
Expression::try_from(inner.next().unwrap()).map(Box::new),
|
||||||
|
Expression::try_from(inner.next().unwrap()).map(Box::new)
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
Rule::primary => pair.into_inner().next().unwrap().try_into(),
|
Rule::primary => pair.into_inner().next().unwrap().try_into(),
|
||||||
Rule::static_path => ast_expr!(Expression::Path(pair.try_into())),
|
Rule::static_path => ast_expr!(Expression::Path(pair.try_into())),
|
||||||
Rule::literal => ast_expr!(Expression::Literal(pair.try_into())),
|
Rule::literal => ast_expr!(Expression::Literal(pair.try_into())),
|
||||||
Rule::expr_path => ast_expr!(Expression::Path(pair.try_into())),
|
Rule::expr_path => ast_expr!(Expression::Path(pair.try_into())),
|
||||||
Rule::statement_wrapper => {
|
Rule::statement | Rule::basic_stmt | Rule::control_flow | Rule::block | Rule::unsafe_block => ast_expr!(
|
||||||
let i = inner.next().unwrap();
|
|
||||||
match i.as_rule() {
|
|
||||||
Rule::expr => i.try_into(),
|
|
||||||
_ => ast_expr!(Expression::Statement(
|
|
||||||
i.try_into().get_map(Box::new).map(Box::new)
|
|
||||||
)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Rule::statement | Rule::basic_stmt | Rule::control_flow => ast_expr!(
|
|
||||||
Expression::Statement(pair.try_into().get_map(Box::new).map(Box::new))
|
Expression::Statement(pair.try_into().get_map(Box::new).map(Box::new))
|
||||||
),
|
),
|
||||||
|
|
||||||
@@ -106,24 +118,8 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Prefix {
|
|||||||
Rule::deref_px => Self::Deref,
|
Rule::deref_px => Self::Deref,
|
||||||
Rule::mut_ref_px => Self::RefMut,
|
Rule::mut_ref_px => Self::RefMut,
|
||||||
Rule::ref_px => Self::Ref,
|
Rule::ref_px => Self::Ref,
|
||||||
Rule::new_px => Self::New(
|
|
||||||
pair.into_inner()
|
|
||||||
.next()
|
|
||||||
.map(|v| v.try_into().get())
|
|
||||||
.transpose()?,
|
|
||||||
),
|
|
||||||
Rule::not_px => Self::Not,
|
Rule::not_px => Self::Not,
|
||||||
Rule::neg_px => Self::Neg,
|
Rule::neg_px => Self::Neg,
|
||||||
Rule::closure => {
|
|
||||||
let mut inner = pair.into_inner();
|
|
||||||
|
|
||||||
return ast_expr!(Self::Closure(
|
|
||||||
consume_rule(&mut inner, Rule::type_expr)
|
|
||||||
.map(TypeExpr::try_from)
|
|
||||||
.transpose(),
|
|
||||||
collect_recovered(inner.next().unwrap().into_inner())
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
_ => return AstError::bug_unimplemented(pair),
|
_ => return AstError::bug_unimplemented(pair),
|
||||||
})
|
})
|
||||||
@@ -147,13 +143,21 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Postfix {
|
|||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Rule::tuple_field_px => {
|
||||||
|
ast_expr!(Postfix::TupleFieldAccess(
|
||||||
|
Ok(inner.next().unwrap().as_str().parse().unwrap_or(255_u8))
|
||||||
|
as AstResult<'_, u8>,
|
||||||
|
inner.next().map(Generics::try_from).transpose(),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
Rule::call_px => ast_expr!(Postfix::Call(collect_recovered(inner))),
|
Rule::call_px => ast_expr!(Postfix::Call(collect_recovered(inner))),
|
||||||
|
|
||||||
Rule::struct_px => ast_expr!(Postfix::StructCall(collect_recovered_map(inner, |p| {
|
Rule::struct_px => ast_expr!(Postfix::StructCall(collect_recovered_map(inner, |p| {
|
||||||
let mut pi = p.into_inner();
|
let mut pi = p.into_inner();
|
||||||
Ok((
|
Ok((
|
||||||
Identifier::try_from(pi.next().unwrap())?,
|
Identifier::try_from(pi.next().unwrap())?,
|
||||||
Expression::try_from(pi.next().unwrap()).get()?,
|
pi.next().map(Expression::try_from).transpose().get()?,
|
||||||
))
|
))
|
||||||
}))),
|
}))),
|
||||||
|
|
||||||
@@ -161,7 +165,18 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Postfix {
|
|||||||
ast_expr!(Postfix::Index(Expression::try_from(inner.next().unwrap())))
|
ast_expr!(Postfix::Index(Expression::try_from(inner.next().unwrap())))
|
||||||
}
|
}
|
||||||
|
|
||||||
Rule::macro_call_px => Ok(Postfix::MacroCall(inner.as_str().to_string())),
|
Rule::macro_call_paren => Ok(Postfix::MacroCall {
|
||||||
|
inner: inner.as_str().to_string(),
|
||||||
|
delimiter: MacroDelimiter::Paren,
|
||||||
|
}),
|
||||||
|
Rule::macro_call_bracket => Ok(Postfix::MacroCall {
|
||||||
|
inner: inner.as_str().to_string(),
|
||||||
|
delimiter: MacroDelimiter::Bracket,
|
||||||
|
}),
|
||||||
|
Rule::macro_call_brace => Ok(Postfix::MacroCall {
|
||||||
|
inner: inner.as_str().to_string(),
|
||||||
|
delimiter: MacroDelimiter::Brace,
|
||||||
|
}),
|
||||||
|
|
||||||
Rule::as_px => {
|
Rule::as_px => {
|
||||||
ast_expr!(Postfix::As(inner.next().unwrap().try_into()))
|
ast_expr!(Postfix::As(inner.next().unwrap().try_into()))
|
||||||
|
|||||||
@@ -7,8 +7,8 @@ use crate::{
|
|||||||
Rule,
|
Rule,
|
||||||
ast::*,
|
ast::*,
|
||||||
ast_ensure, ast_expr,
|
ast_ensure, ast_expr,
|
||||||
error::{AstError, IntoErr, collect_recovered},
|
error::{AstError, AstResult, IntoErr, collect_recovered, collect_recovered_map},
|
||||||
parser::consume_rule,
|
parser::{consume_rule, listen_rule},
|
||||||
};
|
};
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Identifier {
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Identifier {
|
||||||
@@ -60,23 +60,42 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Pattern {
|
|||||||
let mut inner = pair.clone().into_inner();
|
let mut inner = pair.clone().into_inner();
|
||||||
|
|
||||||
match rule {
|
match rule {
|
||||||
Rule::tuple_pattern => ast_expr!(Pattern::Tuple(collect_recovered(pair.into_inner()))),
|
Rule::tuple_pattern => ast_expr!(Pattern::Tuple(collect_recovered_map(inner, |v| {
|
||||||
|
Self::try_from(v).map(Box::new)
|
||||||
|
}))),
|
||||||
|
|
||||||
Rule::named_tuple_pattern => ast_expr!(Pattern::NamedTuple(
|
Rule::named_tuple_pattern => ast_expr!(Pattern::NamedTuple(
|
||||||
Path::try_from(inner.next().unwrap()),
|
Path::try_from(inner.next().unwrap()),
|
||||||
collect_recovered(inner),
|
collect_recovered_map(inner, |v| Self::try_from(v).map(Box::new)),
|
||||||
)),
|
)),
|
||||||
|
|
||||||
Rule::struct_pattern => ast_expr!(Pattern::Struct(
|
Rule::struct_pattern => ast_expr!(Pattern::Struct(
|
||||||
Path::try_from(inner.next().unwrap()),
|
Path::try_from(inner.next().unwrap()),
|
||||||
collect_recovered(inner),
|
collect_recovered_map(inner, |v| {
|
||||||
|
if v.as_rule() == Rule::etc_pattern {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut inner = v.into_inner();
|
||||||
|
Some(ast_expr!((
|
||||||
|
Identifier::try_from(inner.next().unwrap()),
|
||||||
|
inner
|
||||||
|
.next()
|
||||||
|
.map(|v| Self::try_from(v).map(Box::new).get_map(Box::new))
|
||||||
|
.transpose()
|
||||||
|
)))
|
||||||
|
.transpose()
|
||||||
|
}),
|
||||||
)),
|
)),
|
||||||
|
|
||||||
Rule::literal => ast_expr!(Pattern::Literal(pair.try_into())),
|
Rule::literal => ast_expr!(Pattern::Literal(pair.try_into())),
|
||||||
|
|
||||||
Rule::identifier => ast_expr!(Pattern::Id(pair.try_into())),
|
Rule::path_pattern => ast_expr!(Pattern::Path(
|
||||||
|
Ok(listen_rule(&mut inner, Rule::mutable)) as AstResult<'_, bool>,
|
||||||
|
inner.next().unwrap().try_into()
|
||||||
|
)),
|
||||||
|
|
||||||
Rule::static_path => ast_expr!(Pattern::Path(pair.try_into())),
|
Rule::etc_pattern => Ok(Pattern::Etc),
|
||||||
|
|
||||||
_ => AstError::bug_unimplemented(pair),
|
_ => AstError::bug_unimplemented(pair),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,8 +2,7 @@ use crate::{
|
|||||||
Rule,
|
Rule,
|
||||||
ast::*,
|
ast::*,
|
||||||
ast_ensure, ast_expr,
|
ast_ensure, ast_expr,
|
||||||
error::{AstError, AstResult, IntoErr, collect_recovered},
|
error::{AstError, IntoErr, collect_recovered},
|
||||||
parser::listen_rule,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Block {
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Block {
|
||||||
@@ -13,25 +12,10 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Block {
|
|||||||
let mut inner = pair.clone().into_inner();
|
let mut inner = pair.clone().into_inner();
|
||||||
|
|
||||||
ast_ensure!(pair, Rule::block => {
|
ast_ensure!(pair, Rule::block => {
|
||||||
ast_expr!(Block(collect_recovered(inner.next().unwrap().into_inner()), inner.next().map(Spanned::try_from).transpose()))
|
ast_expr!(Block {
|
||||||
})
|
statements: collect_recovered(inner.next().unwrap().into_inner()),
|
||||||
}
|
soft_return: inner.next().map(Spanned::try_from).transpose(),
|
||||||
}
|
})
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for StatementBody {
|
|
||||||
type Error = AstError<'a, Self>;
|
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
|
||||||
let mut inner = pair.clone().into_inner();
|
|
||||||
|
|
||||||
ast_ensure!(pair, Rule::statement_body => {
|
|
||||||
let i = inner.next().unwrap();
|
|
||||||
|
|
||||||
match i.as_rule() {
|
|
||||||
Rule::expr => ast_expr!(StatementBody::Expression(i.try_into())),
|
|
||||||
Rule::statement_wrapper => ast_expr!(StatementBody::Statement(i.try_into())),
|
|
||||||
_ => AstError::bug_unimplemented(i),
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -63,6 +47,8 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Statement {
|
|||||||
Statement::try_from(inner.next().unwrap())
|
Statement::try_from(inner.next().unwrap())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Rule::unsafe_block => ast_expr!(Statement::UnsafeBlock(inner.next().unwrap().try_into())),
|
||||||
|
|
||||||
Rule::block => ast_expr!(Statement::Block(pair.try_into())),
|
Rule::block => ast_expr!(Statement::Block(pair.try_into())),
|
||||||
|
|
||||||
Rule::var_decl_statement => ast_expr!(Statement::VarDecl(pair.try_into())),
|
Rule::var_decl_statement => ast_expr!(Statement::VarDecl(pair.try_into())),
|
||||||
@@ -81,7 +67,7 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Statement {
|
|||||||
ast_expr!(Statement::If {
|
ast_expr!(Statement::If {
|
||||||
initial: inner.next().unwrap().try_into(),
|
initial: inner.next().unwrap().try_into(),
|
||||||
else_if: collect_recovered(inner.next().unwrap().into_inner()),
|
else_if: collect_recovered(inner.next().unwrap().into_inner()),
|
||||||
else_branch: inner.next().map(StatementBody::try_from).transpose(),
|
else_branch: inner.next().map(Block::try_from).transpose(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -97,7 +83,6 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Statement {
|
|||||||
}),
|
}),
|
||||||
|
|
||||||
Rule::for_stmt => ast_expr!(Statement::For {
|
Rule::for_stmt => ast_expr!(Statement::For {
|
||||||
mutable: Ok(listen_rule(&mut inner, Rule::mutable)) as AstResult<'_, bool>,
|
|
||||||
pattern: inner.next().unwrap().try_into(),
|
pattern: inner.next().unwrap().try_into(),
|
||||||
iterator: inner.next().unwrap().try_into(),
|
iterator: inner.next().unwrap().try_into(),
|
||||||
body: inner.next().unwrap().try_into(),
|
body: inner.next().unwrap().try_into(),
|
||||||
@@ -105,18 +90,23 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Statement {
|
|||||||
|
|
||||||
Rule::match_stmt => ast_expr!(Statement::Match(
|
Rule::match_stmt => ast_expr!(Statement::Match(
|
||||||
inner.next().unwrap().try_into(),
|
inner.next().unwrap().try_into(),
|
||||||
inner
|
collect_recovered(inner),
|
||||||
.map(|match_itms| {
|
|
||||||
let mut match_inner = match_itms.into_inner();
|
|
||||||
Ok((
|
|
||||||
collect_recovered(match_inner.next().unwrap().into_inner()).get()?,
|
|
||||||
Expression::try_from(match_inner.next().unwrap()).get()?,
|
|
||||||
))
|
|
||||||
})
|
|
||||||
.collect::<AstResult<'a, Vec<_>>>(),
|
|
||||||
)),
|
)),
|
||||||
|
|
||||||
_ => AstError::bug_unimplemented(pair),
|
_ => AstError::bug_unimplemented(pair),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for MatchItem {
|
||||||
|
type Error = AstError<'a, Self>;
|
||||||
|
|
||||||
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
|
let mut match_inner = pair.into_inner();
|
||||||
|
|
||||||
|
Ok(MatchItem(
|
||||||
|
collect_recovered(match_inner.next().unwrap().into_inner()).get()?,
|
||||||
|
Expression::try_from(match_inner.next().unwrap()).get()?,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,71 +2,10 @@ use crate::{
|
|||||||
Rule,
|
Rule,
|
||||||
ast::*,
|
ast::*,
|
||||||
ast_ensure, ast_expr,
|
ast_ensure, ast_expr,
|
||||||
error::{AstError, GetLength, IntoErr, collect_recovered},
|
error::{AstError, AstResult, IntoErr, collect_recovered},
|
||||||
parser::{consume_rule, listen_rule},
|
parser::{consume_rule, listen_rule},
|
||||||
};
|
};
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TypePostfix {
|
|
||||||
type Error = AstError<'a, Self>;
|
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
|
||||||
let rule = pair.as_rule();
|
|
||||||
let mut inner = pair.clone().into_inner();
|
|
||||||
|
|
||||||
match rule {
|
|
||||||
Rule::ref_type => {
|
|
||||||
let mutable = listen_rule(&mut inner, Rule::mutable);
|
|
||||||
let lifetime = consume_rule(&mut inner, Rule::lifetime)
|
|
||||||
.map(|pair| Identifier::try_from(pair.into_inner().next().unwrap()))
|
|
||||||
.transpose()
|
|
||||||
.get()?;
|
|
||||||
|
|
||||||
Ok(if mutable {
|
|
||||||
if let Some(lifetime) = lifetime {
|
|
||||||
TypePostfix::RefMutLifetime(lifetime)
|
|
||||||
} else {
|
|
||||||
TypePostfix::RefMut
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if let Some(lifetime) = lifetime {
|
|
||||||
TypePostfix::RefLifetime(lifetime)
|
|
||||||
} else {
|
|
||||||
TypePostfix::Ref
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
Rule::dyn_type => Ok(TypePostfix::Dyn),
|
|
||||||
|
|
||||||
_ => AstError::bug_unimplemented(pair),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TypeExprKind {
|
|
||||||
type Error = AstError<'a, Self>;
|
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
|
||||||
let rule = pair.as_rule();
|
|
||||||
let mut inner = pair.clone().into_inner();
|
|
||||||
|
|
||||||
match rule {
|
|
||||||
Rule::tuple_type => ast_expr!(TypeExprKind::Tuple(collect_recovered(inner))),
|
|
||||||
Rule::path_type => {
|
|
||||||
let path = Path::try_from(inner.next().unwrap());
|
|
||||||
let params = collect_recovered(inner);
|
|
||||||
|
|
||||||
if params.len() == 0 {
|
|
||||||
ast_expr!(TypeExprKind::Path(path))
|
|
||||||
} else {
|
|
||||||
ast_expr!(TypeExprKind::PathParams(path, params))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => AstError::bug_unimplemented(pair),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TypeExpr {
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TypeExpr {
|
||||||
type Error = AstError<'a, Self>;
|
type Error = AstError<'a, Self>;
|
||||||
|
|
||||||
@@ -75,14 +14,33 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TypeExpr {
|
|||||||
let mut inner = pair.clone().into_inner();
|
let mut inner = pair.clone().into_inner();
|
||||||
|
|
||||||
match rule {
|
match rule {
|
||||||
Rule::type_expr => ast_expr!(TypeExpr(
|
Rule::generic => Self::try_from(inner.next().unwrap()),
|
||||||
inner.next().unwrap().try_into(),
|
Rule::type_expr => inner.next().unwrap().try_into(),
|
||||||
collect_recovered(inner),
|
Rule::lifetime => ast_expr!(TypeExpr::Lifetime(inner.next().unwrap().try_into())),
|
||||||
)),
|
|
||||||
Rule::type_expr_param => Self::try_from(inner.next().unwrap()),
|
Rule::tuple_type => ast_expr!(TypeExpr::Tuple(collect_recovered(inner))),
|
||||||
Rule::lifetime => ast_expr!(TypeExprKind::Lifetime(inner.next().unwrap().try_into()))
|
Rule::path_type => {
|
||||||
.get_map(TypeExpr::no_px)
|
ast_expr!(TypeExpr::Path(
|
||||||
.map(TypeExpr::no_px),
|
Path::try_from(inner.next().unwrap()),
|
||||||
|
inner.next().map(Generics::try_from).transpose()
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
Rule::ref_type => {
|
||||||
|
ast_expr!(TypeExpr::Ref {
|
||||||
|
lifetime: consume_rule(&mut inner, Rule::ref_lifetime)
|
||||||
|
.map(|v| v.into_inner().next().map(Lifetime::try_from))
|
||||||
|
.unwrap_or_default()
|
||||||
|
.transpose(),
|
||||||
|
mutable: Ok(listen_rule(&mut inner, Rule::mutable)) as AstResult<bool>,
|
||||||
|
ty: TypeExpr::try_from(inner.next().unwrap()).map(Box::new),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
Rule::dyn_type => {
|
||||||
|
ast_expr!(TypeExpr::Dyn(
|
||||||
|
TypeExpr::try_from(inner.next().unwrap()).map(Box::new),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
_ => AstError::bug_unimplemented(pair),
|
_ => AstError::bug_unimplemented(pair),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,11 +28,11 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Attribute {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Some(next) => match next.as_rule() {
|
Some(next) => match next.as_rule() {
|
||||||
Rule::primary => {
|
Rule::literal => {
|
||||||
// #[path = literal]
|
// #[path = literal]
|
||||||
Ok(Attribute::NameValue {
|
Ok(Attribute::NameValue {
|
||||||
path,
|
path,
|
||||||
value: inner.next().unwrap().try_into().get()?,
|
value: next.try_into().get()?,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for ClassItem {
|
|||||||
Ok(ClassItem::ImplDecl(pair.try_into().get()?))
|
Ok(ClassItem::ImplDecl(pair.try_into().get()?))
|
||||||
}
|
}
|
||||||
|
|
||||||
Rule::method => Ok(ClassItem::Method(pair.try_into().get()?)),
|
Rule::function_decl => Ok(ClassItem::Method(pair.try_into().get()?)),
|
||||||
|
|
||||||
_ => AstError::bug_unimplemented(pair),
|
_ => AstError::bug_unimplemented(pair),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ use crate::{
|
|||||||
Rule,
|
Rule,
|
||||||
ast::*,
|
ast::*,
|
||||||
ast_ensure, ast_expr,
|
ast_ensure, ast_expr,
|
||||||
error::{AstError, AstResult, IntoErr, collect_recovered},
|
error::{self, AstError, AstResult, IntoErr},
|
||||||
parser::{consume_rule, listen_rule},
|
parser::{consume_rule, listen_rule},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -10,10 +10,14 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FunctionDecl {
|
|||||||
type Error = AstError<'a, Self>;
|
type Error = AstError<'a, Self>;
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
ast_ensure!(pair, Rule::function_decl, Rule::method, Rule::method_no_body => {
|
ast_ensure!(pair, Rule::function_decl => {
|
||||||
let mut inner = pair.into_inner();
|
let mut inner = pair.into_inner();
|
||||||
let visibility = Visibility::try_from(&mut inner);
|
let visibility = Visibility::try_from(&mut inner);
|
||||||
let return_type = TypeExpr::try_from(inner.next().unwrap());
|
|
||||||
|
let return_type = consume_rule(&mut inner, Rule::type_expr)
|
||||||
|
.map(TypeExpr::try_from)
|
||||||
|
.transpose();
|
||||||
|
|
||||||
let name = Identifier::try_from(inner.next().unwrap());
|
let name = Identifier::try_from(inner.next().unwrap());
|
||||||
|
|
||||||
let generics = consume_rule(&mut inner, Rule::generics_decl)
|
let generics = consume_rule(&mut inner, Rule::generics_decl)
|
||||||
@@ -23,27 +27,26 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FunctionDecl {
|
|||||||
|
|
||||||
let self_param = consume_rule(&mut inner, Rule::self_param).map(|param| {
|
let self_param = consume_rule(&mut inner, Rule::self_param).map(|param| {
|
||||||
let mut param_inner = param.into_inner();
|
let mut param_inner = param.into_inner();
|
||||||
let name = Pattern::Id(Identifier(String::from("self")));
|
|
||||||
|
|
||||||
let mutable = listen_rule(&mut param_inner, Rule::mutable);
|
|
||||||
|
|
||||||
let is_ref = listen_rule(&mut param_inner, Rule::deref_px);
|
let is_ref = listen_rule(&mut param_inner, Rule::deref_px);
|
||||||
|
let lifetime = consume_rule(&mut param_inner, Rule::lifetime);
|
||||||
|
let mutable = listen_rule(&mut param_inner, Rule::mutable);
|
||||||
|
let name = Pattern::Path(mutable && !is_ref, Path(vec![Identifier(String::from("self"))]));
|
||||||
|
let self_ty = TypeExpr::Path(Path(vec![Identifier(String::from("Self"))]), None);
|
||||||
|
|
||||||
VarDecl {
|
VarDecl {
|
||||||
mutable: mutable && !is_ref,
|
|
||||||
name: name.clone(),
|
name: name.clone(),
|
||||||
type_: Some(TypeExpr(
|
type_: Some(if is_ref {
|
||||||
TypeExprKind::Path(Path(vec![Identifier("Self".to_string())])),
|
TypeExpr::Ref {
|
||||||
if is_ref {
|
lifetime:
|
||||||
vec![if mutable {
|
lifetime.map(|v| Lifetime::try_from(v.into_inner().next().unwrap()))
|
||||||
TypePostfix::RefMut
|
.transpose()
|
||||||
} else {
|
.expect("Failed to get lifetime identifier"),
|
||||||
TypePostfix::Ref
|
mutable,
|
||||||
}]
|
ty: Box::new(self_ty)
|
||||||
} else {
|
}
|
||||||
Vec::new()
|
} else {
|
||||||
},
|
self_ty
|
||||||
)),
|
}),
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -60,10 +63,13 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FunctionDecl {
|
|||||||
})
|
})
|
||||||
.unwrap_or_else(|| Ok(ParamList(self_param.into_iter().collect())));
|
.unwrap_or_else(|| Ok(ParamList(self_param.into_iter().collect())));
|
||||||
|
|
||||||
|
let is_override = consume_rule(&mut inner, Rule::override_kw).map(Override::try_from).transpose();
|
||||||
|
|
||||||
let body = inner.next().map(Block::try_from).transpose();
|
let body = inner.next().map(Block::try_from).transpose();
|
||||||
|
|
||||||
ast_expr!(Self {
|
ast_expr!(Self {
|
||||||
visibility: visibility,
|
visibility: visibility,
|
||||||
|
is_override: is_override,
|
||||||
return_type: return_type,
|
return_type: return_type,
|
||||||
name: name,
|
name: name,
|
||||||
generics: generics,
|
generics: generics,
|
||||||
@@ -74,10 +80,27 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FunctionDecl {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for ParamList {
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Override {
|
||||||
type Error = AstError<'a, Self>;
|
type Error = AstError<'a, Self>;
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
Ok(ParamList(collect_recovered(pair.into_inner()).get()?))
|
ast_ensure!(pair, Rule::override_kw => {
|
||||||
|
ast_expr!(Override(pair.into_inner().next().map(ExprPath::try_from).transpose()))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Lifetime {
|
||||||
|
type Error = AstError<'a, Self>;
|
||||||
|
|
||||||
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
|
let mut inner = pair.clone().into_inner();
|
||||||
|
|
||||||
|
match pair.as_rule() {
|
||||||
|
Rule::ref_lifetime => inner.next().unwrap().try_into(),
|
||||||
|
Rule::lifetime => ast_expr!(Lifetime::Lifetime(inner.next().unwrap().try_into())),
|
||||||
|
Rule::unsafe_kw => Ok(Lifetime::Unsafe),
|
||||||
|
_ => error::AstError::bug_unimplemented(pair),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -69,9 +69,15 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TopLevelKind {
|
|||||||
.transpose()
|
.transpose()
|
||||||
.map(|v| v.unwrap_or_default()),
|
.map(|v| v.unwrap_or_default()),
|
||||||
|
|
||||||
|
inherits: consume_rule(&mut inner, Rule::expr_path)
|
||||||
|
.map(ExprPath::try_from)
|
||||||
|
.transpose(),
|
||||||
|
|
||||||
fields: collect_recovered(inner.next().unwrap().into_inner()),
|
fields: collect_recovered(inner.next().unwrap().into_inner()),
|
||||||
|
|
||||||
constructor: inner.next().unwrap().try_into(),
|
constructor: consume_rule(&mut inner, Rule::class_constructor)
|
||||||
|
.map(Spanned::try_from)
|
||||||
|
.transpose(),
|
||||||
|
|
||||||
items: collect_recovered(inner),
|
items: collect_recovered(inner),
|
||||||
}),
|
}),
|
||||||
@@ -89,7 +95,7 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TopLevelKind {
|
|||||||
fields: collect_recovered(inner),
|
fields: collect_recovered(inner),
|
||||||
}),
|
}),
|
||||||
|
|
||||||
Rule::mod_package => ast_expr!(TopLevelKind::Mod(
|
Rule::declare_module => ast_expr!(TopLevelKind::DeclareModule(
|
||||||
Visibility::try_from(&mut inner),
|
Visibility::try_from(&mut inner),
|
||||||
inner.next().unwrap().try_into(),
|
inner.next().unwrap().try_into(),
|
||||||
)),
|
)),
|
||||||
|
|||||||
@@ -0,0 +1,78 @@
|
|||||||
|
use std::{collections::HashSet, path::PathBuf};
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(
|
||||||
|
Debug, Default, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize,
|
||||||
|
)]
|
||||||
|
pub struct MistMap(pub usize, pub usize);
|
||||||
|
|
||||||
|
#[derive(
|
||||||
|
Debug, Default, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize,
|
||||||
|
)]
|
||||||
|
pub struct RustMap(pub usize, pub usize);
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct Mapping {
|
||||||
|
pub mist_path: PathBuf,
|
||||||
|
pub map: HashSet<(RustMap, MistMap)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Mapping {
|
||||||
|
pub fn new(mist_path: PathBuf) -> Self {
|
||||||
|
Self {
|
||||||
|
mist_path,
|
||||||
|
map: HashSet::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn find(&self, target: &RustMap) -> Option<(RustMap, MistMap)> {
|
||||||
|
self.map
|
||||||
|
.iter()
|
||||||
|
.copied()
|
||||||
|
.filter(|(rust, _)| rust <= target)
|
||||||
|
.max_by_key(|(rust, _)| *rust)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn find_by_mist(&self, target: &MistMap) -> Option<(RustMap, MistMap)> {
|
||||||
|
self.map
|
||||||
|
.iter()
|
||||||
|
.copied()
|
||||||
|
.filter(|(_, mist)| mist <= target)
|
||||||
|
.max_by_key(|(_, mist)| *mist)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn shift_rust(&mut self, lines: isize, cols: isize) {
|
||||||
|
self.map = self
|
||||||
|
.map
|
||||||
|
.iter()
|
||||||
|
.map(|(rust, mist)| (rust.shifted(lines, cols), *mist))
|
||||||
|
.collect();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn shift_mist(&mut self, lines: isize, cols: isize) {
|
||||||
|
self.map = self
|
||||||
|
.map
|
||||||
|
.iter()
|
||||||
|
.map(|(rust, mist)| (*rust, mist.shifted(lines, cols)))
|
||||||
|
.collect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RustMap {
|
||||||
|
pub fn shifted(self, lines: isize, cols: isize) -> Self {
|
||||||
|
Self(
|
||||||
|
self.0.saturating_add_signed(lines),
|
||||||
|
self.1.saturating_add_signed(cols),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MistMap {
|
||||||
|
pub fn shifted(self, lines: isize, cols: isize) -> Self {
|
||||||
|
Self(
|
||||||
|
self.0.saturating_add_signed(lines),
|
||||||
|
self.1.saturating_add_signed(cols),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
WHITESPACE = _{ " " | "\t" | "\r" | "\n" }
|
|
||||||
|
|
||||||
integer = @{ ASCII_DIGIT+ }
|
|
||||||
|
|
||||||
map = { "/*" ~ integer ~ ":" ~ integer ~ "*/" }
|
|
||||||
|
|
||||||
non_map = { (!map ~ ANY)+ }
|
|
||||||
|
|
||||||
mapping = { SOI ~ (map | non_map)* ~ EOI }
|
|
||||||
@@ -1,51 +0,0 @@
|
|||||||
use std::collections::HashSet;
|
|
||||||
|
|
||||||
use pest::Parser;
|
|
||||||
use pest_derive::Parser;
|
|
||||||
|
|
||||||
#[derive(Parser)]
|
|
||||||
#[grammar = "./src/rev_mapper/grammar.pest"]
|
|
||||||
pub struct MistMapperParser;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
|
|
||||||
pub struct MistMap(pub usize, pub usize);
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
|
|
||||||
pub struct RustMap(pub usize, pub usize);
|
|
||||||
|
|
||||||
pub fn get_mapping(input: &str) -> HashSet<(RustMap, MistMap)> {
|
|
||||||
let mut mapping = HashSet::new();
|
|
||||||
|
|
||||||
let pairs = MistMapperParser::parse(Rule::mapping, input)
|
|
||||||
.unwrap()
|
|
||||||
.next()
|
|
||||||
.unwrap()
|
|
||||||
.into_inner();
|
|
||||||
|
|
||||||
for pair in pairs {
|
|
||||||
if pair.as_rule() == Rule::map {
|
|
||||||
let rs = pair.as_span().start_pos().line_col();
|
|
||||||
let mut inner = pair.into_inner();
|
|
||||||
|
|
||||||
let (line, col) = (
|
|
||||||
inner.next().unwrap().as_str().parse().unwrap(),
|
|
||||||
inner.next().unwrap().as_str().parse().unwrap(),
|
|
||||||
);
|
|
||||||
|
|
||||||
mapping.insert((RustMap(rs.0, rs.1), MistMap(line, col)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
mapping
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn find_mapping(
|
|
||||||
mapping: &HashSet<(RustMap, MistMap)>,
|
|
||||||
target: &RustMap,
|
|
||||||
) -> Option<(RustMap, MistMap)> {
|
|
||||||
mapping
|
|
||||||
.iter()
|
|
||||||
.copied()
|
|
||||||
.filter(|(rust, _)| rust <= target)
|
|
||||||
.max_by_key(|(rust, _)| *rust)
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,367 @@
|
|||||||
|
use crate::ast::{
|
||||||
|
Block, ClassItem, Expression, FunctionDecl, Identifier, MatchItem, Postfix, Prefix, Spanned,
|
||||||
|
Statement, StatementBranch, TopLevel, TopLevelKind, VarDeclStmt,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub trait GetMutability {
|
||||||
|
fn get_mutability(&self) -> Vec<Identifier>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct SemanticError {
|
||||||
|
pub line: usize,
|
||||||
|
pub column: usize,
|
||||||
|
pub error_message: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Class semantics - Ensuring fields are initialized
|
||||||
|
|
||||||
|
pub fn find_function_call<'a>(
|
||||||
|
items: &'a Vec<ClassItem>,
|
||||||
|
name: &Identifier,
|
||||||
|
) -> Option<&'a Spanned<FunctionDecl>> {
|
||||||
|
items.iter().find_map(|v| {
|
||||||
|
if let ClassItem::Method(m) = v {
|
||||||
|
if m.item.is_using_self() && &m.item.name == name {
|
||||||
|
Some(m)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn check_class_semantics<'a>(top_level: &TopLevel) -> Result<(), Vec<SemanticError>> {
|
||||||
|
if let TopLevelKind::ClassDecl {
|
||||||
|
fields,
|
||||||
|
constructor,
|
||||||
|
items,
|
||||||
|
name,
|
||||||
|
inherits,
|
||||||
|
..
|
||||||
|
} = &top_level.0.item
|
||||||
|
{
|
||||||
|
if let Some(constructor) = constructor {
|
||||||
|
let mut fields = fields
|
||||||
|
.iter()
|
||||||
|
.map(|field| Spanned {
|
||||||
|
item: field.item.decl.name.clone(),
|
||||||
|
line: field.line,
|
||||||
|
column: field.column,
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
|
if inherits.is_some() {
|
||||||
|
fields.push(Spanned {
|
||||||
|
line: top_level.0.line,
|
||||||
|
column: top_level.0.column,
|
||||||
|
item: Identifier("_super".to_string()),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut mutability = constructor.item.body.get_mutability();
|
||||||
|
|
||||||
|
let mut i = 0;
|
||||||
|
while i < mutability.len() {
|
||||||
|
let name = mutability[i].clone();
|
||||||
|
if let Some(method) = find_function_call(items, &name) {
|
||||||
|
if let Some(body) = &method.item.body {
|
||||||
|
for entry in body.get_mutability() {
|
||||||
|
if !mutability.contains(&entry) {
|
||||||
|
mutability.push(entry);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut errs = Vec::new();
|
||||||
|
|
||||||
|
for field in &fields {
|
||||||
|
if !mutability.contains(&field.item) {
|
||||||
|
errs.push(SemanticError {
|
||||||
|
line: field.line,
|
||||||
|
column: field.column,
|
||||||
|
error_message: format!(
|
||||||
|
"class field `{}.{}` is uninitialized",
|
||||||
|
name.0, field.item.0
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if errs.len() > 0 {
|
||||||
|
return Err(errs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: GetMutability> GetMutability for Vec<T> {
|
||||||
|
fn get_mutability(&self) -> Vec<Identifier> {
|
||||||
|
self.iter().flat_map(T::get_mutability).collect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GetMutability for Block {
|
||||||
|
fn get_mutability(&self) -> Vec<Identifier> {
|
||||||
|
let mut items: Vec<Identifier> = self
|
||||||
|
.statements
|
||||||
|
.iter()
|
||||||
|
.flat_map(|v| v.item.get_mutability())
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
if let Some(v) = &self.soft_return {
|
||||||
|
items.append(&mut v.item.get_mutability());
|
||||||
|
}
|
||||||
|
|
||||||
|
items
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GetMutability for Statement {
|
||||||
|
fn get_mutability(&self) -> Vec<Identifier> {
|
||||||
|
match self {
|
||||||
|
Statement::Block(body) | Statement::UnsafeBlock(body) => body.get_mutability(),
|
||||||
|
Statement::If {
|
||||||
|
initial,
|
||||||
|
else_if,
|
||||||
|
else_branch,
|
||||||
|
} => {
|
||||||
|
let mut all_sets: Vec<Vec<Identifier>> = Vec::new();
|
||||||
|
all_sets.push(initial.body.get_mutability());
|
||||||
|
|
||||||
|
for branch in else_if {
|
||||||
|
all_sets.push(branch.body.get_mutability());
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(else_block) = else_branch {
|
||||||
|
all_sets.push(else_block.get_mutability());
|
||||||
|
} else {
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut result = all_sets.remove(0);
|
||||||
|
for set in all_sets {
|
||||||
|
result.retain(|id| set.contains(id));
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
Statement::Loop(body) => body.get_mutability(),
|
||||||
|
Statement::While(branch) => branch.body.get_mutability(),
|
||||||
|
Statement::CStyleFor {
|
||||||
|
body,
|
||||||
|
init,
|
||||||
|
condition,
|
||||||
|
update,
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
let mut a = init.get_mutability();
|
||||||
|
a.append(&mut condition.get_mutability());
|
||||||
|
a.append(&mut update.get_mutability());
|
||||||
|
a.append(&mut body.get_mutability());
|
||||||
|
a
|
||||||
|
}
|
||||||
|
Statement::For { body, iterator, .. } => {
|
||||||
|
let mut a = iterator.get_mutability();
|
||||||
|
a.append(&mut body.get_mutability());
|
||||||
|
a
|
||||||
|
}
|
||||||
|
Statement::Match(_, items) => {
|
||||||
|
if items.is_empty() {
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
let mut all_sets: Vec<Vec<Identifier>> = items
|
||||||
|
.iter()
|
||||||
|
.map(|item| item.item.get_mutability())
|
||||||
|
.collect();
|
||||||
|
let mut result = all_sets.remove(0);
|
||||||
|
for set in all_sets {
|
||||||
|
result.retain(|id| set.contains(id));
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
Statement::VarDecl(stmt) => stmt
|
||||||
|
.init
|
||||||
|
.as_ref()
|
||||||
|
.map(|e| e.get_mutability())
|
||||||
|
.unwrap_or_default(),
|
||||||
|
Statement::Return(expr) => expr
|
||||||
|
.as_ref()
|
||||||
|
.map(|e| e.get_mutability())
|
||||||
|
.unwrap_or_default(),
|
||||||
|
Statement::Break | Statement::Continue => Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GetMutability for StatementBranch {
|
||||||
|
fn get_mutability(&self) -> Vec<Identifier> {
|
||||||
|
let mut a = self.condition.get_mutability();
|
||||||
|
a.append(&mut self.body.get_mutability());
|
||||||
|
a
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GetMutability for MatchItem {
|
||||||
|
fn get_mutability(&self) -> Vec<Identifier> {
|
||||||
|
self.1.get_mutability()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GetMutability for VarDeclStmt {
|
||||||
|
fn get_mutability(&self) -> Vec<Identifier> {
|
||||||
|
self.init
|
||||||
|
.as_ref()
|
||||||
|
.map(|e| e.get_mutability())
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_self_ref(initial: &Expression, postfixes: &[Postfix]) -> Option<Identifier> {
|
||||||
|
match initial {
|
||||||
|
Expression::Path(v) => {
|
||||||
|
let ident = v.0.first()?.ident.0.as_str();
|
||||||
|
if ident == "self" || ident == "super" {
|
||||||
|
if let Some(Postfix::FieldAccess(field, _)) = postfixes.first() {
|
||||||
|
if !matches!(postfixes.get(1), Some(Postfix::Call(_))) {
|
||||||
|
return Some(field.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_self_method_call(initial: &Expression, postfixes: &[Postfix]) -> Option<Identifier> {
|
||||||
|
match initial {
|
||||||
|
Expression::Path(v) => {
|
||||||
|
let ident = v.0.first()?.ident.0.as_str();
|
||||||
|
if ident == "self" || ident == "super" {
|
||||||
|
if let Some(Postfix::FieldAccess(method, _)) = postfixes.first() {
|
||||||
|
if matches!(postfixes.get(1), Some(Postfix::Call(_))) {
|
||||||
|
return Some(method.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Expression {
|
||||||
|
fn get_self_ref(&self) -> Option<Identifier> {
|
||||||
|
match self {
|
||||||
|
Self::Fix {
|
||||||
|
initial, postfixes, ..
|
||||||
|
} => get_self_ref(initial, postfixes),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GetMutability for Expression {
|
||||||
|
fn get_mutability(&self) -> Vec<Identifier> {
|
||||||
|
match self {
|
||||||
|
Self::Array(v) => v.get_mutability(),
|
||||||
|
Self::ArrayRepeat(v, i) => {
|
||||||
|
let mut a = v.get_mutability();
|
||||||
|
a.append(&mut i.get_mutability());
|
||||||
|
a
|
||||||
|
}
|
||||||
|
Self::Binary { lhs, op, rhs } => {
|
||||||
|
if mutates_lhs(op) {
|
||||||
|
let mut a = if let Some(self_ref) = lhs.get_self_ref() {
|
||||||
|
vec![self_ref]
|
||||||
|
} else {
|
||||||
|
lhs.get_mutability()
|
||||||
|
};
|
||||||
|
|
||||||
|
a.append(&mut rhs.get_mutability());
|
||||||
|
a
|
||||||
|
} else {
|
||||||
|
let mut a = lhs.get_mutability();
|
||||||
|
a.append(&mut rhs.get_mutability());
|
||||||
|
a
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Self::Statement(stmt) => stmt.get_mutability(),
|
||||||
|
Self::Fix {
|
||||||
|
initial,
|
||||||
|
prefixes,
|
||||||
|
postfixes,
|
||||||
|
} => {
|
||||||
|
let mut result = Vec::new();
|
||||||
|
|
||||||
|
// &mut self.field / &mut super.field / &mut super pattern
|
||||||
|
if prefixes.iter().any(|p| matches!(p, Prefix::RefMut)) {
|
||||||
|
if let Some(self_ref) = get_self_ref(initial, postfixes) {
|
||||||
|
result.push(self_ref);
|
||||||
|
} else if let Expression::Path(v) = &**initial {
|
||||||
|
if v.0.first().map_or(false, |s| s.ident.0 == "super") {
|
||||||
|
result.push(Identifier("_super".to_string()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Recurse into all postfix sub-expressions
|
||||||
|
for postfix in postfixes {
|
||||||
|
match postfix {
|
||||||
|
Postfix::Assign(_, rhs) => {
|
||||||
|
if let Some(self_ref) = get_self_ref(initial, postfixes) {
|
||||||
|
result.push(self_ref);
|
||||||
|
}
|
||||||
|
result.append(&mut rhs.get_mutability());
|
||||||
|
}
|
||||||
|
Postfix::Call(args) => {
|
||||||
|
for arg in args {
|
||||||
|
result.append(&mut arg.get_mutability());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Postfix::StructCall(fields) => {
|
||||||
|
for (_, expr) in fields {
|
||||||
|
if let Some(expr) = expr {
|
||||||
|
result.append(&mut expr.get_mutability());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Postfix::Index(expr) => {
|
||||||
|
result.append(&mut expr.get_mutability());
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Method calls on self: self.method_name(args)
|
||||||
|
if let Some(method) = get_self_method_call(initial, postfixes) {
|
||||||
|
result.push(method);
|
||||||
|
}
|
||||||
|
|
||||||
|
result
|
||||||
|
}
|
||||||
|
Self::Closure { body, .. } => body.get_mutability(),
|
||||||
|
Self::Literal(_) => Vec::new(),
|
||||||
|
Self::Path(v) => {
|
||||||
|
if v.0.first().map_or(false, |s| s.ident.0 == "super") {
|
||||||
|
vec![Identifier("_super".to_string())]
|
||||||
|
} else {
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn mutates_lhs(op: &str) -> bool {
|
||||||
|
matches!(op, "=" | "->")
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
package = "main.mist"
|
||||||
|
packages = []
|
||||||
@@ -1,123 +0,0 @@
|
|||||||
use <super::task>;
|
|
||||||
use <super::logger>;
|
|
||||||
use <super::event>;
|
|
||||||
|
|
||||||
pub class Application {
|
|
||||||
String name;
|
|
||||||
|
|
||||||
Vec<task::Task> tasks;
|
|
||||||
Vec<String> plugins;
|
|
||||||
|
|
||||||
logger::Logger logger;
|
|
||||||
|
|
||||||
bool running;
|
|
||||||
i32 ticks;
|
|
||||||
|
|
||||||
pub constructor(str* name) {
|
|
||||||
self.name = name.to_string();
|
|
||||||
self.tasks = new Vec();
|
|
||||||
self.plugins = new Vec();
|
|
||||||
|
|
||||||
self.logger = new logger::Logger("app");
|
|
||||||
|
|
||||||
self.running = false;
|
|
||||||
self.ticks = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub void boot(self mut*) {
|
|
||||||
self.logger.info("booting application");
|
|
||||||
|
|
||||||
self.running = true;
|
|
||||||
|
|
||||||
self.emit(event::Event::Startup);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub void run(self mut*) {
|
|
||||||
while(self.running) {
|
|
||||||
self.tick();
|
|
||||||
|
|
||||||
if(self.ticks >= 5) {
|
|
||||||
self.shutdown();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void tick(self mut*) {
|
|
||||||
self.logger.info("tick");
|
|
||||||
|
|
||||||
self.ticks++;
|
|
||||||
|
|
||||||
var task = task::create_task("background-job");
|
|
||||||
|
|
||||||
self.tasks.push(task);
|
|
||||||
|
|
||||||
println!("tasks: {}", self.tasks.len());
|
|
||||||
}
|
|
||||||
|
|
||||||
pub void shutdown(self mut*) {
|
|
||||||
self.emit(event::Event::Shutdown);
|
|
||||||
|
|
||||||
self.logger.warning("shutdown");
|
|
||||||
|
|
||||||
self.running = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub void register_plugin(self mut*, String name) {
|
|
||||||
self.plugins.push(name.clone());
|
|
||||||
|
|
||||||
self.emit(event::Event::PluginLoaded(name));
|
|
||||||
}
|
|
||||||
|
|
||||||
void emit(self*, event::Event event) {
|
|
||||||
match(event) {
|
|
||||||
event::Event::Startup => {
|
|
||||||
self.logger.info("startup event");
|
|
||||||
}
|
|
||||||
|
|
||||||
event::Event::Shutdown => {
|
|
||||||
self.logger.info("shutdown event");
|
|
||||||
}
|
|
||||||
|
|
||||||
event::Event::PluginLoaded[name] => {
|
|
||||||
println!("plugin loaded: {}", name);
|
|
||||||
}
|
|
||||||
|
|
||||||
event::Event::TaskExecuted[name] => {
|
|
||||||
println!("task executed: {}", name);
|
|
||||||
}
|
|
||||||
|
|
||||||
event::Event::Error[message] => {
|
|
||||||
self.logger.error(&message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
i32 test_stmt() {
|
|
||||||
if (0 == 0) {
|
|
||||||
0
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void loops_test() {
|
|
||||||
for (x : 0..10) {
|
|
||||||
println!("{x}");
|
|
||||||
}
|
|
||||||
|
|
||||||
for (var mut i = 0; i < 10; i++) {
|
|
||||||
println!("{i}");
|
|
||||||
}
|
|
||||||
|
|
||||||
var i = 0;
|
|
||||||
|
|
||||||
while (i == 1) {
|
|
||||||
println!("hi");
|
|
||||||
}
|
|
||||||
|
|
||||||
loop {
|
|
||||||
println!("loop!");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
pub module decl_test;
|
||||||
|
|
||||||
|
pub fn void test_let_basic() {
|
||||||
|
let x = 42;
|
||||||
|
assert_eq!(x, 42);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_let_typed() {
|
||||||
|
let x i32 = 42;
|
||||||
|
assert_eq!(x, 42);
|
||||||
|
|
||||||
|
let s *str = "hello";
|
||||||
|
assert_eq!(s, "hello");
|
||||||
|
|
||||||
|
let b bool = true;
|
||||||
|
assert_eq!(b, true);
|
||||||
|
|
||||||
|
let f f64 = 3.14;
|
||||||
|
assert_eq!(f, 3.14);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_let_mut() {
|
||||||
|
let mut _x = 42;
|
||||||
|
_x = 100;
|
||||||
|
assert_eq!(_x, 100);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_let_tuple_destructure() {
|
||||||
|
let (a, b) = (10, "hello");
|
||||||
|
assert_eq!(a, 10);
|
||||||
|
assert_eq!(b, "hello");
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_let_nested_tuple() {
|
||||||
|
let (a, (b, c)) = (1, (2, 3));
|
||||||
|
assert_eq!(a, 1);
|
||||||
|
assert_eq!(b, 2);
|
||||||
|
assert_eq!(c, 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_let_pattern_irrefutable() {
|
||||||
|
let x = 5;
|
||||||
|
let (y, z) = (1, 2);
|
||||||
|
assert_eq!(x, 5);
|
||||||
|
assert_eq!(y, 1);
|
||||||
|
assert_eq!(z, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_multiple_decls() {
|
||||||
|
let a = 1;
|
||||||
|
let b = 2;
|
||||||
|
let c = 3;
|
||||||
|
assert_eq!(a + b + c, 6);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_let_with_type_and_init() {
|
||||||
|
let x f64 = 10.0;
|
||||||
|
assert_eq!(x, 10.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_string_literal() {
|
||||||
|
let s = "hello, world!";
|
||||||
|
assert_eq!(s.len(), 13);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_let_bool() {
|
||||||
|
let t = true;
|
||||||
|
let f = false;
|
||||||
|
assert_eq!(t, !f);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void run_tests() {
|
||||||
|
test_let_basic();
|
||||||
|
test_let_typed();
|
||||||
|
test_let_mut();
|
||||||
|
test_let_tuple_destructure();
|
||||||
|
test_let_nested_tuple();
|
||||||
|
test_let_pattern_irrefutable();
|
||||||
|
test_multiple_decls();
|
||||||
|
test_let_with_type_and_init();
|
||||||
|
test_string_literal();
|
||||||
|
test_let_bool();
|
||||||
|
}
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
pub module expr_test;
|
||||||
|
|
||||||
|
pub fn void test_literals() {
|
||||||
|
assert_eq!(42, 42);
|
||||||
|
assert_eq!(3.14, 3.14);
|
||||||
|
assert_eq!(true, true);
|
||||||
|
assert_eq!(false, false);
|
||||||
|
assert_eq!("hello", "hello");
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_tuples() {
|
||||||
|
let t = (1, true, "three");
|
||||||
|
assert_eq!(t.0, 1);
|
||||||
|
assert_eq!(t.1, true);
|
||||||
|
assert_eq!(t.2, "three");
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_arrays() {
|
||||||
|
let arr = [1, 2, 3];
|
||||||
|
assert_eq!(arr[0], 1);
|
||||||
|
assert_eq!(arr[1], 2);
|
||||||
|
assert_eq!(arr[2], 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_array_repeat() {
|
||||||
|
let arr = [0; 5];
|
||||||
|
assert_eq!(arr[0], 0);
|
||||||
|
assert_eq!(arr[4], 0);
|
||||||
|
assert_eq!(arr.len(), 5);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_binary_arith() {
|
||||||
|
assert_eq!(10 + 5, 15);
|
||||||
|
assert_eq!(10 - 5, 5);
|
||||||
|
assert_eq!(10 * 5, 50);
|
||||||
|
assert_eq!(10 / 5, 2);
|
||||||
|
assert_eq!(10 % 3, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_binary_cmp() {
|
||||||
|
assert_eq!(5 < 10, true);
|
||||||
|
assert_eq!(10 <= 10, true);
|
||||||
|
assert_eq!(10 > 5, true);
|
||||||
|
assert_eq!(10 >= 10, true);
|
||||||
|
assert_eq!(5 == 5, true);
|
||||||
|
assert_eq!(5 != 10, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_binary_logic() {
|
||||||
|
assert_eq!(true && true, true);
|
||||||
|
assert_eq!(true && false, false);
|
||||||
|
assert_eq!(true || false, true);
|
||||||
|
assert_eq!(false || false, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_binary_bit() {
|
||||||
|
assert_eq!(5 & 3, 1);
|
||||||
|
assert_eq!(5 | 3, 7);
|
||||||
|
assert_eq!(5 ^ 3, 6);
|
||||||
|
assert_eq!(1 << 2, 4);
|
||||||
|
assert_eq!(4 >> 1, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_prefix() {
|
||||||
|
let x = 42;
|
||||||
|
assert_eq!(-x, -42);
|
||||||
|
assert_eq!(!true, false);
|
||||||
|
assert_eq!(!false, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_ref_deref() {
|
||||||
|
let x = 42;
|
||||||
|
let r = &x;
|
||||||
|
assert_eq!(*r, 42);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_postfix_inc_dec() {
|
||||||
|
let mut x = 5;
|
||||||
|
x++;
|
||||||
|
assert_eq!(x, 6);
|
||||||
|
x--;
|
||||||
|
assert_eq!(x, 5);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_as_cast() {
|
||||||
|
let x = 42;
|
||||||
|
assert_eq!(x as f64, 42.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_closure() {
|
||||||
|
let add = fn(a, b) -> a + b;
|
||||||
|
assert_eq!(add(2, 3), 5);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_block_expr() {
|
||||||
|
let x = {
|
||||||
|
let y = 10;
|
||||||
|
y + 5
|
||||||
|
};
|
||||||
|
assert_eq!(x, 15);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_if_expr() {
|
||||||
|
let x = if true { 1 } else { 2 };
|
||||||
|
assert_eq!(x, 1);
|
||||||
|
|
||||||
|
let y = if false { 1 } else { 2 };
|
||||||
|
assert_eq!(y, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_range_expr() {
|
||||||
|
let r = 0..5;
|
||||||
|
let mut count = 0;
|
||||||
|
for i in r {
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
assert_eq!(count, 5);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_binary_assign() {
|
||||||
|
let mut x = 10;
|
||||||
|
x += 5;
|
||||||
|
assert_eq!(x, 15);
|
||||||
|
x -= 3;
|
||||||
|
assert_eq!(x, 12);
|
||||||
|
x *= 2;
|
||||||
|
assert_eq!(x, 24);
|
||||||
|
x /= 4;
|
||||||
|
assert_eq!(x, 6);
|
||||||
|
x %= 4;
|
||||||
|
assert_eq!(x, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void run_tests() {
|
||||||
|
test_literals();
|
||||||
|
test_tuples();
|
||||||
|
test_arrays();
|
||||||
|
test_array_repeat();
|
||||||
|
test_binary_arith();
|
||||||
|
test_binary_cmp();
|
||||||
|
test_binary_logic();
|
||||||
|
test_binary_bit();
|
||||||
|
test_prefix();
|
||||||
|
test_ref_deref();
|
||||||
|
test_postfix_inc_dec();
|
||||||
|
test_as_cast();
|
||||||
|
test_closure();
|
||||||
|
test_block_expr();
|
||||||
|
test_if_expr();
|
||||||
|
test_range_expr();
|
||||||
|
test_binary_assign();
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
pub module common;
|
||||||
|
|
||||||
|
pub fn void test_package() {}
|
||||||
@@ -0,0 +1,167 @@
|
|||||||
|
pub module statement_test;
|
||||||
|
|
||||||
|
pub fn void test_var_decl() {
|
||||||
|
let x = 42;
|
||||||
|
assert_eq!(x, 42);
|
||||||
|
|
||||||
|
let y i32 = 10;
|
||||||
|
assert_eq!(y, 10);
|
||||||
|
|
||||||
|
let name *str = "mist";
|
||||||
|
assert_eq!(name, "mist");
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_var_decl_with_init() {
|
||||||
|
let mut x = 0;
|
||||||
|
x = 5;
|
||||||
|
assert_eq!(x, 5);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_if_statement() {
|
||||||
|
let mut x = 0;
|
||||||
|
|
||||||
|
if true {
|
||||||
|
x = 1;
|
||||||
|
}
|
||||||
|
assert_eq!(x, 1);
|
||||||
|
|
||||||
|
if false {
|
||||||
|
x = 2;
|
||||||
|
} else {
|
||||||
|
x = 3;
|
||||||
|
}
|
||||||
|
assert_eq!(x, 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_if_else_if() {
|
||||||
|
let mut x = 0;
|
||||||
|
|
||||||
|
if x == 1 {
|
||||||
|
x = 10;
|
||||||
|
} else if x == 0 {
|
||||||
|
x = 20;
|
||||||
|
} else {
|
||||||
|
x = 30;
|
||||||
|
}
|
||||||
|
assert_eq!(x, 20);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_while_loop() {
|
||||||
|
let mut count = 0;
|
||||||
|
|
||||||
|
while count < 5 {
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
assert_eq!(count, 5);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_for_loop() {
|
||||||
|
let mut sum = 0;
|
||||||
|
|
||||||
|
for i in 0..4 {
|
||||||
|
sum += i;
|
||||||
|
}
|
||||||
|
assert_eq!(sum, 6);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_loop_stmt() {
|
||||||
|
let mut count = 0;
|
||||||
|
|
||||||
|
loop {
|
||||||
|
count++;
|
||||||
|
if count >= 3 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert_eq!(count, 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_break_continue() {
|
||||||
|
let mut sum = 0;
|
||||||
|
|
||||||
|
for i in 0..10 {
|
||||||
|
if i % 2 == 0 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if i >= 7 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
sum += i;
|
||||||
|
}
|
||||||
|
assert_eq!(sum, 1 + 3 + 5);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn i32 test_return() {
|
||||||
|
return 42;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_block_scope() {
|
||||||
|
let x = {
|
||||||
|
let inner = 10;
|
||||||
|
inner + 5
|
||||||
|
};
|
||||||
|
assert_eq!(x, 15);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_match_literal() {
|
||||||
|
let x = 2;
|
||||||
|
let result;
|
||||||
|
|
||||||
|
match x {
|
||||||
|
1 => { result = 10; }
|
||||||
|
2 => { result = 20; }
|
||||||
|
3 => { result = 30; }
|
||||||
|
_ => panic!();
|
||||||
|
}
|
||||||
|
assert_eq!(result, 20);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_match_or_pattern() {
|
||||||
|
let x = 1;
|
||||||
|
let result i32;
|
||||||
|
|
||||||
|
match x {
|
||||||
|
1 | 2 => { result = 100; }
|
||||||
|
3 => { result = 200; }
|
||||||
|
_ => panic!();
|
||||||
|
}
|
||||||
|
assert_eq!(result, 100);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_match_default() {
|
||||||
|
let x = 99;
|
||||||
|
let result;
|
||||||
|
|
||||||
|
match x {
|
||||||
|
1 => { result = 10; }
|
||||||
|
y => { result = y; }
|
||||||
|
}
|
||||||
|
assert_eq!(result, 99);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_for_with_pattern_destructure() {
|
||||||
|
let pairs = [(1, "a"), (2, "b")];
|
||||||
|
let mut keys = 0;
|
||||||
|
|
||||||
|
for (k, _) in pairs {
|
||||||
|
keys += k;
|
||||||
|
}
|
||||||
|
assert_eq!(keys, 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void run_tests() {
|
||||||
|
test_var_decl();
|
||||||
|
test_var_decl_with_init();
|
||||||
|
test_if_statement();
|
||||||
|
test_if_else_if();
|
||||||
|
test_while_loop();
|
||||||
|
test_for_loop();
|
||||||
|
test_loop_stmt();
|
||||||
|
test_break_continue();
|
||||||
|
assert_eq!(test_return(), 42);
|
||||||
|
test_block_scope();
|
||||||
|
test_match_literal();
|
||||||
|
test_match_or_pattern();
|
||||||
|
test_match_default();
|
||||||
|
test_for_with_pattern_destructure();
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
pub module types_test;
|
||||||
|
|
||||||
|
pub fn void test_integer_type() {
|
||||||
|
let x i32 = 42;
|
||||||
|
assert_eq!(x, 42);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_float_type() {
|
||||||
|
let x f64 = 3.14;
|
||||||
|
assert_eq!(x, 3.14);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_bool_type() {
|
||||||
|
let x bool = true;
|
||||||
|
assert_eq!(x, true);
|
||||||
|
|
||||||
|
let y bool = false;
|
||||||
|
assert_eq!(y, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_string_type() {
|
||||||
|
let s *str = "hello";
|
||||||
|
assert_eq!(s, "hello");
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_tuple_type() {
|
||||||
|
let t (i32, *str) = (42, "answer");
|
||||||
|
assert_eq!(t.0, 42);
|
||||||
|
assert_eq!(t.1, "answer");
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_ref_type() {
|
||||||
|
let x i32 = 42;
|
||||||
|
let r *i32 = &x;
|
||||||
|
assert_eq!(*r, 42);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_mut_ref_type() {
|
||||||
|
let mut x = 42;
|
||||||
|
let r *mut i32 = &mut x;
|
||||||
|
*r = 100;
|
||||||
|
assert_eq!(x, 100);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_void_type() {}
|
||||||
|
|
||||||
|
fn i32 add(a i32, b i32) {
|
||||||
|
a + b
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_fn_return_type() {
|
||||||
|
assert_eq!(add(3, 4), 7);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void run_tests() {
|
||||||
|
test_integer_type();
|
||||||
|
test_float_type();
|
||||||
|
test_bool_type();
|
||||||
|
test_string_type();
|
||||||
|
test_tuple_type();
|
||||||
|
test_ref_type();
|
||||||
|
test_mut_ref_type();
|
||||||
|
test_void_type();
|
||||||
|
test_fn_return_type();
|
||||||
|
}
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
pub enum Event {
|
|
||||||
Startup,
|
|
||||||
Shutdown,
|
|
||||||
TaskExecuted[String],
|
|
||||||
PluginLoaded[String],
|
|
||||||
Error[String],
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
pub module attribute_test;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Debuggable {
|
||||||
|
value i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_derive_attribute() {
|
||||||
|
let d = Debuggable { value: 42 };
|
||||||
|
assert_eq!(d.value, 42);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(unused_variables)]
|
||||||
|
pub fn void test_allow_attribute() {
|
||||||
|
let x = 42;
|
||||||
|
let y = "unused";
|
||||||
|
assert_eq!(x, 42);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void run_tests() {
|
||||||
|
test_derive_attribute();
|
||||||
|
test_allow_attribute();
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
pub module class_test;
|
||||||
|
|
||||||
|
pub class Animal {
|
||||||
|
pub name String;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
self.name = "Rex".to_string();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn String speak(*self) {
|
||||||
|
"Unknown".to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_speak(*self) {
|
||||||
|
assert_eq!(self.speak(), "Woof!");
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void static_method() {}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub class Mammal : Animal {
|
||||||
|
constructor() {
|
||||||
|
super = Super::new();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void args_test(*self, x i32, y *str) {
|
||||||
|
assert_eq!(x, 10);
|
||||||
|
assert_eq!(y, "hello");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub class Dog : Mammal {
|
||||||
|
constructor() {
|
||||||
|
super = Super::new();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn String speak(*self) override(Animal) {
|
||||||
|
"Woof!".to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Display {
|
||||||
|
fn Result<(), std::fmt::Error> fmt(*self, f *mut std::fmt::Formatter<'_>) {
|
||||||
|
write!(f, "🐾 {}", self.name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void run_tests() {
|
||||||
|
let dawg = Dog::new();
|
||||||
|
|
||||||
|
dawg.args_test(10, "hello");
|
||||||
|
|
||||||
|
dawg.test_speak();
|
||||||
|
|
||||||
|
assert_eq!(format!("{dawg}"), "🐾 Rex");
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
pub module enum_test;
|
||||||
|
|
||||||
|
enum OptionInt {
|
||||||
|
None,
|
||||||
|
Some(i32),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_enum_named() {
|
||||||
|
let x = OptionInt::None;
|
||||||
|
match x {
|
||||||
|
OptionInt::None => { assert_eq!(1, 1); }
|
||||||
|
OptionInt::Some(_) => { assert_eq!(0, 1); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_enum_tuple() {
|
||||||
|
let x = OptionInt::Some(42);
|
||||||
|
match x {
|
||||||
|
OptionInt::None => { assert_eq!(0, 1); }
|
||||||
|
OptionInt::Some(v) => { assert_eq!(v, 42); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enum Shape {
|
||||||
|
Circle { radius i32 },
|
||||||
|
Rect { w i32, h i32 },
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_enum_struct() {
|
||||||
|
let c = Shape::Circle { radius: 5 };
|
||||||
|
match c {
|
||||||
|
Shape::Circle { radius } => { assert_eq!(radius, 5); }
|
||||||
|
Shape::Rect { .. } => { assert_eq!(0, 1); }
|
||||||
|
}
|
||||||
|
|
||||||
|
let r = Shape::Rect { w: 3, h: 4 };
|
||||||
|
match r {
|
||||||
|
Shape::Circle { .. } => { assert_eq!(0, 1); }
|
||||||
|
Shape::Rect { w, h } => { assert_eq!(w * h, 12); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enum Color {
|
||||||
|
Red,
|
||||||
|
Green,
|
||||||
|
Blue,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_enum_eq() {
|
||||||
|
let c = Color::Red;
|
||||||
|
match c {
|
||||||
|
Color::Red => { assert_eq!(1, 1); }
|
||||||
|
_ => { assert_eq!(0, 1); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void run_tests() {
|
||||||
|
test_enum_named();
|
||||||
|
test_enum_tuple();
|
||||||
|
test_enum_struct();
|
||||||
|
test_enum_eq();
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
pub module function_test;
|
||||||
|
|
||||||
|
fn void greet() {
|
||||||
|
let mut x = 1;
|
||||||
|
x++;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_basic_function() {
|
||||||
|
greet();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn i32 add(a i32, b i32) {
|
||||||
|
a + b
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_fn_params() {
|
||||||
|
assert_eq!(add(2, 3), 5);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn i32 test_fn_return() {
|
||||||
|
42
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn i32 test_fn_early_return() {
|
||||||
|
return 100;
|
||||||
|
0
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn i32 test_fn_mut_param(mut x i32) {
|
||||||
|
x = x + 10;
|
||||||
|
x
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_method_call() {
|
||||||
|
let s = "hello";
|
||||||
|
assert_eq!(s.len(), 5);
|
||||||
|
assert_eq!(s.to_uppercase(), "HELLO");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn i32 triple(x i32) {
|
||||||
|
add(x, add(x, x))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_nested_fn_calls() {
|
||||||
|
assert_eq!(triple(5), 15);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn i32 factorial(n i32) {
|
||||||
|
if n <= 1 { 1 }
|
||||||
|
else { n * factorial(n - 1) }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_recursive_fn() {
|
||||||
|
assert_eq!(factorial(5), 120);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void run_tests() {
|
||||||
|
test_basic_function();
|
||||||
|
test_fn_params();
|
||||||
|
assert_eq!(test_fn_return(), 42);
|
||||||
|
assert_eq!(test_fn_early_return(), 100);
|
||||||
|
assert_eq!(test_fn_mut_param(5), 15);
|
||||||
|
test_method_call();
|
||||||
|
test_nested_fn_calls();
|
||||||
|
test_recursive_fn();
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
pub module impl_test;
|
||||||
|
|
||||||
|
struct Vector2 {
|
||||||
|
x i32,
|
||||||
|
y i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Vector2 {
|
||||||
|
pub fn i32 magnitude(*self) {
|
||||||
|
self.x * self.x + self.y * self.y
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_inherent_impl() {
|
||||||
|
let v = Vector2 { x: 3, y: 4 };
|
||||||
|
assert_eq!(v.magnitude(), 25);
|
||||||
|
}
|
||||||
|
|
||||||
|
trait Display {
|
||||||
|
fn String display(*self);
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for Vector2 {
|
||||||
|
fn String display(*self) {
|
||||||
|
format!("({}, {})", self.x, self.y)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_trait_impl_block() {
|
||||||
|
let v = Vector2 { x: 1, y: 2 };
|
||||||
|
let s = v.display();
|
||||||
|
assert_eq!(s.len() > 0, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Vector2 {
|
||||||
|
pub fn Vector2 add(*self, other Vector2) {
|
||||||
|
Vector2 {
|
||||||
|
x: self.x + other.x,
|
||||||
|
y: self.y + other.y,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_multiple_impls() {
|
||||||
|
let a = Vector2 { x: 1, y: 2 };
|
||||||
|
let b = Vector2 { x: 3, y: 4 };
|
||||||
|
let c = a.add(b);
|
||||||
|
assert_eq!(c.x, 4);
|
||||||
|
assert_eq!(c.y, 6);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void run_tests() {
|
||||||
|
test_inherent_impl();
|
||||||
|
test_trait_impl_block();
|
||||||
|
test_multiple_impls();
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
pub module struct_test;
|
||||||
|
|
||||||
|
struct Point {
|
||||||
|
x i32,
|
||||||
|
y i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_struct_create_access() {
|
||||||
|
let p = Point { x: 10, y: 20 };
|
||||||
|
assert_eq!(p.x, 10);
|
||||||
|
assert_eq!(p.y, 20);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_struct_mut_field() {
|
||||||
|
let mut p = Point { x: 1, y: 2 };
|
||||||
|
p.x = 100;
|
||||||
|
assert_eq!(p.x, 100);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_struct_destructure() {
|
||||||
|
let p = Point { x: 3, y: 4 };
|
||||||
|
let Point { x, y } = p;
|
||||||
|
assert_eq!(x, 3);
|
||||||
|
assert_eq!(y, 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Line {
|
||||||
|
start Point,
|
||||||
|
end Point,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_struct_nested() {
|
||||||
|
let l = Line {
|
||||||
|
start: Point { x: 0, y: 0 },
|
||||||
|
end: Point { x: 5, y: 10 },
|
||||||
|
};
|
||||||
|
assert_eq!(l.start.x, 0);
|
||||||
|
assert_eq!(l.end.y, 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void run_tests() {
|
||||||
|
test_struct_create_access();
|
||||||
|
test_struct_mut_field();
|
||||||
|
test_struct_destructure();
|
||||||
|
test_struct_nested();
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
pub module trait_test;
|
||||||
|
|
||||||
|
trait Speak {
|
||||||
|
fn String speak(*self);
|
||||||
|
}
|
||||||
|
|
||||||
|
trait Greet : Speak {
|
||||||
|
fn String greet(*self);
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Dog {
|
||||||
|
name String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Speak for Dog {
|
||||||
|
fn String speak(*self) {
|
||||||
|
"woof".to_string()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Greet for Dog {
|
||||||
|
fn String greet(*self) {
|
||||||
|
"hello".to_string()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_trait_impl() {
|
||||||
|
let d = Dog { name: "Rex".to_string() };
|
||||||
|
assert_eq!(d.speak(), "woof");
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void test_trait_with_requirement() {
|
||||||
|
let d = Dog { name: "Buddy".to_string() };
|
||||||
|
assert_eq!(d.speak(), "woof");
|
||||||
|
assert_eq!(d.greet(), "hello");
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn void run_tests() {
|
||||||
|
test_trait_impl();
|
||||||
|
test_trait_with_requirement();
|
||||||
|
}
|
||||||
@@ -1,72 +0,0 @@
|
|||||||
use <std::fmt::Formatter>;
|
|
||||||
use <std::fmt>;
|
|
||||||
|
|
||||||
pub trait TestLogging<T: fmt::Display>: fmt::Display {
|
|
||||||
String get(self*);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub enum LogLevel {
|
|
||||||
Info,
|
|
||||||
Warning,
|
|
||||||
Error,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Display for LogLevel {
|
|
||||||
fmt::Result fmt(self*, Formatter<'_> mut* f) {
|
|
||||||
match (self) {
|
|
||||||
LogLevel::Info => write!(f, "[INFO]");
|
|
||||||
|
|
||||||
LogLevel::Warning => write!(f, "[WARN]");
|
|
||||||
|
|
||||||
LogLevel::Error => write!(f, "[ERROR]");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl TestLogging<LogLevel> for LogLevel {
|
|
||||||
String get(self*) {
|
|
||||||
return format!("{self}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub class Logger {
|
|
||||||
String prefix;
|
|
||||||
|
|
||||||
pub constructor(str* prefix) {
|
|
||||||
self.prefix = prefix.to_string();
|
|
||||||
}
|
|
||||||
|
|
||||||
pub void info(self*, str* message) {
|
|
||||||
self.log(LogLevel::Info, message);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub void warning(self*, str* message) {
|
|
||||||
self.log(LogLevel::Warning, message);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub void error(self*, str* message) {
|
|
||||||
self.log(LogLevel::Error, message);
|
|
||||||
}
|
|
||||||
|
|
||||||
void log(self*, LogLevel level, str* message) {
|
|
||||||
match(level) {
|
|
||||||
LogLevel::Info => {
|
|
||||||
println!("{level} {} {}", self.prefix, message);
|
|
||||||
}
|
|
||||||
|
|
||||||
LogLevel::Warning => {
|
|
||||||
println!("{} {} {}", level.get(), self.prefix, message);
|
|
||||||
}
|
|
||||||
|
|
||||||
LogLevel::Error => {
|
|
||||||
println!("{level} {} {}", self.prefix, message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Display {
|
|
||||||
fmt::Result fmt(self*, Formatter<'_> mut* f) {
|
|
||||||
write!(f, "logger ({})", self.prefix)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+16
-25
@@ -1,28 +1,19 @@
|
|||||||
pub mod app;
|
fn void main() {
|
||||||
pub mod task;
|
println!("running common tests...");
|
||||||
pub mod plugin;
|
common::test_package();
|
||||||
pub mod logger;
|
common::expr_test::run_tests();
|
||||||
pub mod event;
|
common::statement_test::run_tests();
|
||||||
|
common::decl_test::run_tests();
|
||||||
|
common::types_test::run_tests();
|
||||||
|
|
||||||
void main() {
|
println!("running items tests...");
|
||||||
var mut app_instance = new app::Application("mist-app");
|
items::function_test::run_tests();
|
||||||
|
items::struct_test::run_tests();
|
||||||
|
items::enum_test::run_tests();
|
||||||
|
items::class_test::run_tests();
|
||||||
|
items::trait_test::run_tests();
|
||||||
|
items::impl_test::run_tests();
|
||||||
|
items::attribute_test::run_tests();
|
||||||
|
|
||||||
app_instance.boot();
|
println!("\x1b[32m\nAll tests passed!\x1b[0m");
|
||||||
app_instance.run();
|
|
||||||
}
|
|
||||||
|
|
||||||
void do_stuff() {
|
|
||||||
vec!(1, 2, 3).into_iter().map(Option<i32> |var v| {Some(v)}).collect::<Vec<_>>();
|
|
||||||
|
|
||||||
if (43==69) testing1();
|
|
||||||
}
|
|
||||||
|
|
||||||
i32 testing1() {
|
|
||||||
|
|
||||||
i32 v = if (0 == 0) {
|
|
||||||
0
|
|
||||||
} else {
|
|
||||||
1
|
|
||||||
};
|
|
||||||
v
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,16 +0,0 @@
|
|||||||
pub struct PluginInfo {
|
|
||||||
pub String name,
|
|
||||||
pub String version,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub class PluginRegistry<T> {
|
|
||||||
T plugins;
|
|
||||||
|
|
||||||
pub constructor(T plugins) {
|
|
||||||
self.plugins = plugins;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub T plugins(self) {
|
|
||||||
return self.plugins;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
pub enum TaskState {
|
|
||||||
Pending,
|
|
||||||
Running,
|
|
||||||
Finished,
|
|
||||||
Failed,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct Task {
|
|
||||||
pub String name,
|
|
||||||
pub TaskState state,
|
|
||||||
pub i32 executions,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub Task create_task(str* name) {
|
|
||||||
Task {
|
|
||||||
name: name.to_string(),
|
|
||||||
state: TaskState::Pending,
|
|
||||||
executions: 0,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
pub mod builder;
|
|
||||||
|
|
||||||
fn main() {}
|
|
||||||
+1
-3
@@ -1,5 +1,3 @@
|
|||||||
use <mist_analyzer>;
|
fn void main() {
|
||||||
|
|
||||||
void main() {
|
|
||||||
mist_analyzer::start();
|
mist_analyzer::start();
|
||||||
}
|
}
|
||||||
|
|||||||
+23
-24
@@ -1,32 +1,31 @@
|
|||||||
use <std::process>;
|
use std::process;
|
||||||
use <std::env>;
|
use std::env;
|
||||||
use <std::fs>;
|
use std::fs;
|
||||||
|
use mist_api::builder;
|
||||||
|
use mist_api::transpiler;
|
||||||
|
|
||||||
pub mod builder;
|
fn void main() {
|
||||||
pub mod transpiler;
|
let args Vec<String> = env::args().collect();
|
||||||
|
|
||||||
void main() {
|
if args.len() < 2 {
|
||||||
Vec<String> args = env::args().collect();
|
|
||||||
|
|
||||||
if (args.len() < 2) {
|
|
||||||
print_usage();
|
print_usage();
|
||||||
process::exit(1);
|
process::exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
match (args[1].as_str()) {
|
match args[1].as_str() {
|
||||||
"run" | "build" | "check" | "r" | "b" | "c" => {
|
"run" | "build" | "check" | "r" | "b" | "c" => {
|
||||||
var root = transpiler::build(false);
|
let root = transpiler::transpile();
|
||||||
|
|
||||||
println!("");
|
println!("");
|
||||||
|
|
||||||
if (builder::build(args, root)) {
|
if builder::build(args, root) {
|
||||||
println!("\x1b[32m\nBuild successful\x1b[0m");
|
println!("\x1b[32m\nBuild successful\x1b[0m");
|
||||||
} else {
|
} else {
|
||||||
println!("\x1b[31m\nBuild failed\x1b[0m");
|
println!("\x1b[31m\nBuild failed\x1b[0m");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
"transpile" | "t" => {
|
"transpile" | "t" => {
|
||||||
transpiler::build(args.get(2).is_some());
|
transpiler::transpile();
|
||||||
}
|
}
|
||||||
"init" => {
|
"init" => {
|
||||||
init_project(args);
|
init_project(args);
|
||||||
@@ -45,7 +44,7 @@ void main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void print_usage() {
|
fn void print_usage() {
|
||||||
println!("Mist - the mist compiler\n");
|
println!("Mist - the mist compiler\n");
|
||||||
println!(" View our documentation! \x1b[35mhttps://mist.selimaj.dev\x1b[0m");
|
println!(" View our documentation! \x1b[35mhttps://mist.selimaj.dev\x1b[0m");
|
||||||
println!(" Follow us on github! \x1b[35mhttps://github.com/mist-go\x1b[0m\n");
|
println!(" Follow us on github! \x1b[35mhttps://github.com/mist-go\x1b[0m\n");
|
||||||
@@ -67,10 +66,10 @@ void print_usage() {
|
|||||||
println!(" \x1b[36m mist help\x1b[0m print this message\n");
|
println!(" \x1b[36m mist help\x1b[0m print this message\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
void init_project(Vec<String> mut args) {
|
fn void init_project(mut args Vec<String>) {
|
||||||
args.remove(0);
|
args.remove(0);
|
||||||
|
|
||||||
new process::Command("cargo")
|
process::Command::new("cargo")
|
||||||
.args(args)
|
.args(args)
|
||||||
.stdout(process::Stdio::inherit())
|
.stdout(process::Stdio::inherit())
|
||||||
.stderr(process::Stdio::inherit())
|
.stderr(process::Stdio::inherit())
|
||||||
@@ -78,14 +77,14 @@ void init_project(Vec<String> mut args) {
|
|||||||
.spawn()
|
.spawn()
|
||||||
.expect("Failed to run cargo").wait().expect("Unable to wait");
|
.expect("Failed to run cargo").wait().expect("Unable to wait");
|
||||||
|
|
||||||
bool is_lib = fs::metadata("src/lib.rs").is_ok();
|
let is_lib bool = fs::metadata("src/lib.rs").is_ok();
|
||||||
|
|
||||||
if (is_lib) {
|
if is_lib {
|
||||||
fs::remove_file("src/lib.rs").expect("Failed to remove src/lib.rs");
|
fs::remove_file("src/lib.rs").expect("Failed to remove src/lib.rs");
|
||||||
fs::write("src/lib.mist", "void test() {\n}").expect("Failed to create src/lib.mist");
|
fs::write("src/lib.mist", "fn test() {\n}").expect("Failed to create src/lib.mist");
|
||||||
} else {
|
} else {
|
||||||
fs::remove_file("src/main.rs").expect("Failed to remove src/main.rs");
|
fs::remove_file("src/main.rs").expect("Failed to remove src/main.rs");
|
||||||
fs::write("src/main.mist", "void main() {\n println!(\"Hello, World!\");\n}\n").expect("Failed to create src/main.mist");
|
fs::write("src/main.mist", "fn main() {\n println!(\"Hello, World!\");\n}\n").expect("Failed to create src/main.mist");
|
||||||
}
|
}
|
||||||
|
|
||||||
inject_mist_target(is_lib);
|
inject_mist_target(is_lib);
|
||||||
@@ -93,14 +92,14 @@ void init_project(Vec<String> mut args) {
|
|||||||
println!("\n\x1b[34minfo\x1b[0m: Please open Cargo.toml and adjust `\x1b[35mname\x1b[0m = ` as needed, Thank you for using Mist!\n");
|
println!("\n\x1b[34minfo\x1b[0m: Please open Cargo.toml and adjust `\x1b[35mname\x1b[0m = ` as needed, Thank you for using Mist!\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
void inject_mist_target(bool is_lib) {
|
fn void inject_mist_target(is_lib bool) {
|
||||||
String toml_content = fs::read_to_string("Cargo.toml").expect("Failed to read Cargo.toml");
|
let toml_content String = fs::read_to_string("Cargo.toml").expect("Failed to read Cargo.toml");
|
||||||
|
|
||||||
str* inject = if (is_lib) {
|
let inject *str = if is_lib {
|
||||||
"\n[lib]\nname = \"my_lib\"\npath = \".mist/src/lib.rs\"\n"
|
"\n[lib]\nname = \"my_lib\"\npath = \".mist/src/lib.rs\"\n"
|
||||||
} else {
|
} else {
|
||||||
"\n[[bin]]\nname = \"my_bin\"\npath = \".mist/src/main.rs\"\n"
|
"\n[[bin]]\nname = \"my_bin\"\npath = \".mist/src/main.rs\"\n"
|
||||||
};
|
};
|
||||||
|
|
||||||
fs::write("Cargo.toml", toml_content+inject).expect("Failed to inject to Cargo.toml");
|
fs::write("Cargo.toml", toml_content+inject).expect("Failed to inject to Cargo.toml");
|
||||||
}
|
}
|
||||||
@@ -1,162 +0,0 @@
|
|||||||
use <std::fs>;
|
|
||||||
use <std::path::Path>;
|
|
||||||
use <std::path::PathBuf>;
|
|
||||||
use <std::process>;
|
|
||||||
use <std::time>;
|
|
||||||
use <std::env>;
|
|
||||||
|
|
||||||
use <mist_parser::error>;
|
|
||||||
|
|
||||||
pub PathBuf build(bool force) {
|
|
||||||
var start = time::Instant::now();
|
|
||||||
|
|
||||||
var root = env::current_dir().expect("Unable to find project root");
|
|
||||||
|
|
||||||
PathBuf src = root.join("src");
|
|
||||||
PathBuf out = root.join(".mist/src");
|
|
||||||
|
|
||||||
build_dir(&root, &src, &src, &out, force);
|
|
||||||
|
|
||||||
var elapsed = start.elapsed();
|
|
||||||
|
|
||||||
println!(
|
|
||||||
"\x1b[32m\nTranspile successful\x1b[0m in \x1b[34m{:.2?}\x1b[0m",
|
|
||||||
elapsed
|
|
||||||
);
|
|
||||||
|
|
||||||
root
|
|
||||||
}
|
|
||||||
|
|
||||||
void build_dir(Path* root, Path* base_src, Path* current, Path* out, bool force) {
|
|
||||||
var entries = match (fs::read_dir(current)) {
|
|
||||||
Ok[entries] => entries;
|
|
||||||
Err[e] => {
|
|
||||||
eprintln!(
|
|
||||||
"error: failed to read directory {}\n {}",
|
|
||||||
current.display(),
|
|
||||||
e
|
|
||||||
);
|
|
||||||
|
|
||||||
process::exit(1);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
for (entry : entries) {
|
|
||||||
var entry = match (entry) {
|
|
||||||
Ok[entry] => entry;
|
|
||||||
Err[e] => {
|
|
||||||
eprintln!("error: failed to read directory entry\n {}", e);
|
|
||||||
|
|
||||||
process::exit(1);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
PathBuf path = entry.path();
|
|
||||||
|
|
||||||
if (path.is_dir()) {
|
|
||||||
build_dir(root, base_src, &path, out, force);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
Path* relative = path.strip_prefix(base_src).expect("Failed to strip base src from path");
|
|
||||||
|
|
||||||
if (path.extension().and_then(|var e| e.to_str()) != Some("mist")) {
|
|
||||||
PathBuf dest = out.join(relative);
|
|
||||||
|
|
||||||
Option<Path*> parent = dest.parent();
|
|
||||||
|
|
||||||
if (parent.is_some()) {
|
|
||||||
fs::create_dir_all(parent.unwrap()).expect("failed to create output directory");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!force && should_skip(&path, &dest)) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
fs::copy(&path, dest).expect("Failed to copy non-mist file");
|
|
||||||
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
PathBuf output_file = out.join(relative).with_extension("rs");
|
|
||||||
|
|
||||||
if (!force && should_skip(&path, &output_file)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
Option<Path*> parent = output_file.parent();
|
|
||||||
|
|
||||||
if (parent.is_some()) {
|
|
||||||
fs::create_dir_all(parent.unwrap()).expect("failed to create output directory");
|
|
||||||
}
|
|
||||||
|
|
||||||
String source = match (fs::read_to_string(&path)) {
|
|
||||||
Ok[s] => s;
|
|
||||||
Err[e] => {
|
|
||||||
eprintln!("error: failed to read file {}\n {}", path.display(), e);
|
|
||||||
|
|
||||||
process::exit(1);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
var mut gc = mist_codegen::RustCodegen::new();
|
|
||||||
|
|
||||||
String output = gc.generate(match (mist_parser::parse(&source)) {
|
|
||||||
Ok[ast] => ast;
|
|
||||||
Err[e] => {
|
|
||||||
match (e) {
|
|
||||||
error::ParseError::Ast[e] => {
|
|
||||||
var start_pos = e.span.start_pos().line_col();
|
|
||||||
|
|
||||||
var span = e.span.as_str();
|
|
||||||
|
|
||||||
eprintln!(
|
|
||||||
"\n{}:{}:{}\n \x1b[31mError\x1b[0m: {}\n\t{}{}\t{}",
|
|
||||||
path.as_os_str().display(),
|
|
||||||
start_pos.0,
|
|
||||||
start_pos.1,
|
|
||||||
e.error_message,
|
|
||||||
span,
|
|
||||||
if span.ends_with("\n") { "" } else { "\n" },
|
|
||||||
"^".repeat(span.trim().len()),
|
|
||||||
);
|
|
||||||
|
|
||||||
process::exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
error::ParseError::PreAst[e] => {
|
|
||||||
eprintln!("error: parse failed in {}\n{}", path.display(), e);
|
|
||||||
|
|
||||||
process::exit(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
var res = fs::write(&output_file, output);
|
|
||||||
|
|
||||||
if (res.is_err()) {
|
|
||||||
eprintln!(
|
|
||||||
"error: failed to write output {}\n {}",
|
|
||||||
output_file.display(),
|
|
||||||
res.unwrap_err(),
|
|
||||||
);
|
|
||||||
|
|
||||||
process::exit(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
bool should_skip(Path* source, Path* output) {
|
|
||||||
var src_time = fs::metadata(source)
|
|
||||||
.ok()
|
|
||||||
.and_then(|var v| v.modified().ok());
|
|
||||||
|
|
||||||
var out_time = fs::metadata(output)
|
|
||||||
.ok()
|
|
||||||
.and_then(|var v| v.modified().ok());
|
|
||||||
|
|
||||||
out_time
|
|
||||||
.map(|var out_time| out_time >= src_time.unwrap())
|
|
||||||
.unwrap_or_default()
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user