├── .cargo
└── release.toml
├── .github
└── workflows
│ └── test.yml
├── .gitignore
├── Cargo.lock
├── Cargo.toml
├── LICENSE
├── Makefile
├── README.md
├── benches
└── flash_benchmarks.rs
├── examples
├── interop.rs
└── parse_pkgbuild.rs
├── external_echo.sh
├── rust-toolchain.toml
├── simple.sh
├── src
├── bin.rs
├── flash
│ ├── env.rs
│ └── mod.rs
├── formatter.rs
├── interpreter.rs
├── lexer.rs
├── lexer_simd.rs
├── lib.rs
├── parser.rs
└── simd.rs
├── test_debug.rs
├── test_if_functionality.sh
└── tests
├── function_tests.rs
└── integration_tests.rs
/.cargo/release.toml:
--------------------------------------------------------------------------------
1 | # The backtrace code for panics in Rust is almost as large as the entire editor.
2 | # = Huge reduction in binary size by removing all that.
3 | [unstable]
4 | build-std = ["std", "panic_abort"]
5 | build-std-features = ["panic_immediate_abort", "optimize_for_size"]
--------------------------------------------------------------------------------
/.github/workflows/test.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 |
3 | on: [push, pull_request]
4 |
5 | jobs:
6 | test:
7 | name: Test
8 | strategy:
9 | matrix:
10 | include:
11 | - os: ubuntu-latest
12 | target: x86_64-unknown-linux-gnu
13 | - os: macos-latest
14 | target: x86_64-apple-darwin
15 | - os: macos-latest
16 | target: aarch64-apple-darwin
17 |
18 | runs-on: ${{ matrix.os }}
19 |
20 | env:
21 | RUSTFLAGS: "-C target-cpu=native"
22 | RUST_BACKTRACE: full
23 | CARGO_TERM_COLOR: always
24 | CARGO_BUILD_TARGET: ${{ matrix.target }}
25 |
26 | steps:
27 | - uses: actions/checkout@v3
28 | - uses: Swatinem/rust-cache@v2
29 | with:
30 | key: ${{ matrix.target }}
31 | - run: rustup toolchain install stable --profile minimal --target ${{ matrix.target }}
32 | - run: rustup component add rustfmt clippy
33 | - run: cargo fetch --target ${{ matrix.target }}
34 | - run: make lint
35 | - name: cargo test build
36 | run: cargo build --tests --release --target ${{ matrix.target }}
37 | - name: cargo test
38 | run: cargo test --release --target ${{ matrix.target }}
39 | - name: make test-if
40 | run: make test-if
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Generated by Cargo
2 | # will have compiled files and executables
3 | debug/
4 | target/
5 |
6 | # These are backup files generated by rustfmt
7 | **/*.rs.bk
8 |
9 | # MSVC Windows builds of rustc generate these, which store debugging information
10 | *.pdb
11 |
12 | # RustRover
13 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
14 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
15 | # and can be added to the global gitignore or merged into this file. For a more nuclear
16 | # option (not recommended) you can uncomment the following to ignore the entire idea folder.
17 | #.idea/
18 |
19 | # Added by cargo
20 |
21 | /target
22 |
23 | .DS_Store
--------------------------------------------------------------------------------
/Cargo.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Cargo.
2 | # It is not intended for manual editing.
3 | version = 4
4 |
5 | [[package]]
6 | name = "aho-corasick"
7 | version = "1.1.3"
8 | source = "registry+https://github.com/rust-lang/crates.io-index"
9 | checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916"
10 | dependencies = [
11 | "memchr",
12 | ]
13 |
14 | [[package]]
15 | name = "anes"
16 | version = "0.1.6"
17 | source = "registry+https://github.com/rust-lang/crates.io-index"
18 | checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299"
19 |
20 | [[package]]
21 | name = "anstyle"
22 | version = "1.0.10"
23 | source = "registry+https://github.com/rust-lang/crates.io-index"
24 | checksum = "55cc3b69f167a1ef2e161439aa98aed94e6028e5f9a59be9a6ffb47aef1651f9"
25 |
26 | [[package]]
27 | name = "autocfg"
28 | version = "1.4.0"
29 | source = "registry+https://github.com/rust-lang/crates.io-index"
30 | checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26"
31 |
32 | [[package]]
33 | name = "bitflags"
34 | version = "2.9.0"
35 | source = "registry+https://github.com/rust-lang/crates.io-index"
36 | checksum = "5c8214115b7bf84099f1309324e63141d4c5d7cc26862f97a0a857dbefe165bd"
37 |
38 | [[package]]
39 | name = "bumpalo"
40 | version = "3.17.0"
41 | source = "registry+https://github.com/rust-lang/crates.io-index"
42 | checksum = "1628fb46dfa0b37568d12e5edd512553eccf6a22a78e8bde00bb4aed84d5bdbf"
43 |
44 | [[package]]
45 | name = "cast"
46 | version = "0.3.0"
47 | source = "registry+https://github.com/rust-lang/crates.io-index"
48 | checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"
49 |
50 | [[package]]
51 | name = "cfg-if"
52 | version = "1.0.0"
53 | source = "registry+https://github.com/rust-lang/crates.io-index"
54 | checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
55 |
56 | [[package]]
57 | name = "ciborium"
58 | version = "0.2.2"
59 | source = "registry+https://github.com/rust-lang/crates.io-index"
60 | checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e"
61 | dependencies = [
62 | "ciborium-io",
63 | "ciborium-ll",
64 | "serde",
65 | ]
66 |
67 | [[package]]
68 | name = "ciborium-io"
69 | version = "0.2.2"
70 | source = "registry+https://github.com/rust-lang/crates.io-index"
71 | checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757"
72 |
73 | [[package]]
74 | name = "ciborium-ll"
75 | version = "0.2.2"
76 | source = "registry+https://github.com/rust-lang/crates.io-index"
77 | checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9"
78 | dependencies = [
79 | "ciborium-io",
80 | "half",
81 | ]
82 |
83 | [[package]]
84 | name = "clap"
85 | version = "4.5.39"
86 | source = "registry+https://github.com/rust-lang/crates.io-index"
87 | checksum = "fd60e63e9be68e5fb56422e397cf9baddded06dae1d2e523401542383bc72a9f"
88 | dependencies = [
89 | "clap_builder",
90 | ]
91 |
92 | [[package]]
93 | name = "clap_builder"
94 | version = "4.5.39"
95 | source = "registry+https://github.com/rust-lang/crates.io-index"
96 | checksum = "89cc6392a1f72bbeb820d71f32108f61fdaf18bc526e1d23954168a67759ef51"
97 | dependencies = [
98 | "anstyle",
99 | "clap_lex",
100 | ]
101 |
102 | [[package]]
103 | name = "clap_lex"
104 | version = "0.7.4"
105 | source = "registry+https://github.com/rust-lang/crates.io-index"
106 | checksum = "f46ad14479a25103f283c0f10005961cf086d8dc42205bb44c46ac563475dca6"
107 |
108 | [[package]]
109 | name = "criterion"
110 | version = "0.5.1"
111 | source = "registry+https://github.com/rust-lang/crates.io-index"
112 | checksum = "f2b12d017a929603d80db1831cd3a24082f8137ce19c69e6447f54f5fc8d692f"
113 | dependencies = [
114 | "anes",
115 | "cast",
116 | "ciborium",
117 | "clap",
118 | "criterion-plot",
119 | "is-terminal",
120 | "itertools",
121 | "num-traits",
122 | "once_cell",
123 | "oorandom",
124 | "plotters",
125 | "rayon",
126 | "regex",
127 | "serde",
128 | "serde_derive",
129 | "serde_json",
130 | "tinytemplate",
131 | "walkdir",
132 | ]
133 |
134 | [[package]]
135 | name = "criterion-plot"
136 | version = "0.5.0"
137 | source = "registry+https://github.com/rust-lang/crates.io-index"
138 | checksum = "6b50826342786a51a89e2da3a28f1c32b06e387201bc2d19791f622c673706b1"
139 | dependencies = [
140 | "cast",
141 | "itertools",
142 | ]
143 |
144 | [[package]]
145 | name = "crossbeam-deque"
146 | version = "0.8.6"
147 | source = "registry+https://github.com/rust-lang/crates.io-index"
148 | checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51"
149 | dependencies = [
150 | "crossbeam-epoch",
151 | "crossbeam-utils",
152 | ]
153 |
154 | [[package]]
155 | name = "crossbeam-epoch"
156 | version = "0.9.18"
157 | source = "registry+https://github.com/rust-lang/crates.io-index"
158 | checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e"
159 | dependencies = [
160 | "crossbeam-utils",
161 | ]
162 |
163 | [[package]]
164 | name = "crossbeam-utils"
165 | version = "0.8.21"
166 | source = "registry+https://github.com/rust-lang/crates.io-index"
167 | checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"
168 |
169 | [[package]]
170 | name = "crunchy"
171 | version = "0.2.3"
172 | source = "registry+https://github.com/rust-lang/crates.io-index"
173 | checksum = "43da5946c66ffcc7745f48db692ffbb10a83bfe0afd96235c5c2a4fb23994929"
174 |
175 | [[package]]
176 | name = "diff"
177 | version = "0.1.13"
178 | source = "registry+https://github.com/rust-lang/crates.io-index"
179 | checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8"
180 |
181 | [[package]]
182 | name = "either"
183 | version = "1.15.0"
184 | source = "registry+https://github.com/rust-lang/crates.io-index"
185 | checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"
186 |
187 | [[package]]
188 | name = "errno"
189 | version = "0.3.11"
190 | source = "registry+https://github.com/rust-lang/crates.io-index"
191 | checksum = "976dd42dc7e85965fe702eb8164f21f450704bdde31faefd6471dba214cb594e"
192 | dependencies = [
193 | "libc",
194 | "windows-sys",
195 | ]
196 |
197 | [[package]]
198 | name = "fastrand"
199 | version = "2.3.0"
200 | source = "registry+https://github.com/rust-lang/crates.io-index"
201 | checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"
202 |
203 | [[package]]
204 | name = "flash"
205 | version = "0.0.3"
206 | dependencies = [
207 | "criterion",
208 | "glob",
209 | "libc",
210 | "os_pipe",
211 | "pretty_assertions",
212 | "regex",
213 | "scopeguard",
214 | "tempfile",
215 | "termios",
216 | ]
217 |
218 | [[package]]
219 | name = "getrandom"
220 | version = "0.3.2"
221 | source = "registry+https://github.com/rust-lang/crates.io-index"
222 | checksum = "73fea8450eea4bac3940448fb7ae50d91f034f941199fcd9d909a5a07aa455f0"
223 | dependencies = [
224 | "cfg-if",
225 | "libc",
226 | "r-efi",
227 | "wasi",
228 | ]
229 |
230 | [[package]]
231 | name = "glob"
232 | version = "0.3.2"
233 | source = "registry+https://github.com/rust-lang/crates.io-index"
234 | checksum = "a8d1add55171497b4705a648c6b583acafb01d58050a51727785f0b2c8e0a2b2"
235 |
236 | [[package]]
237 | name = "half"
238 | version = "2.6.0"
239 | source = "registry+https://github.com/rust-lang/crates.io-index"
240 | checksum = "459196ed295495a68f7d7fe1d84f6c4b7ff0e21fe3017b2f283c6fac3ad803c9"
241 | dependencies = [
242 | "cfg-if",
243 | "crunchy",
244 | ]
245 |
246 | [[package]]
247 | name = "hermit-abi"
248 | version = "0.5.1"
249 | source = "registry+https://github.com/rust-lang/crates.io-index"
250 | checksum = "f154ce46856750ed433c8649605bf7ed2de3bc35fd9d2a9f30cddd873c80cb08"
251 |
252 | [[package]]
253 | name = "is-terminal"
254 | version = "0.4.16"
255 | source = "registry+https://github.com/rust-lang/crates.io-index"
256 | checksum = "e04d7f318608d35d4b61ddd75cbdaee86b023ebe2bd5a66ee0915f0bf93095a9"
257 | dependencies = [
258 | "hermit-abi",
259 | "libc",
260 | "windows-sys",
261 | ]
262 |
263 | [[package]]
264 | name = "itertools"
265 | version = "0.10.5"
266 | source = "registry+https://github.com/rust-lang/crates.io-index"
267 | checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473"
268 | dependencies = [
269 | "either",
270 | ]
271 |
272 | [[package]]
273 | name = "itoa"
274 | version = "1.0.15"
275 | source = "registry+https://github.com/rust-lang/crates.io-index"
276 | checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c"
277 |
278 | [[package]]
279 | name = "js-sys"
280 | version = "0.3.77"
281 | source = "registry+https://github.com/rust-lang/crates.io-index"
282 | checksum = "1cfaf33c695fc6e08064efbc1f72ec937429614f25eef83af942d0e227c3a28f"
283 | dependencies = [
284 | "once_cell",
285 | "wasm-bindgen",
286 | ]
287 |
288 | [[package]]
289 | name = "libc"
290 | version = "0.2.172"
291 | source = "registry+https://github.com/rust-lang/crates.io-index"
292 | checksum = "d750af042f7ef4f724306de029d18836c26c1765a54a6a3f094cbd23a7267ffa"
293 |
294 | [[package]]
295 | name = "linux-raw-sys"
296 | version = "0.9.4"
297 | source = "registry+https://github.com/rust-lang/crates.io-index"
298 | checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12"
299 |
300 | [[package]]
301 | name = "log"
302 | version = "0.4.27"
303 | source = "registry+https://github.com/rust-lang/crates.io-index"
304 | checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94"
305 |
306 | [[package]]
307 | name = "memchr"
308 | version = "2.7.4"
309 | source = "registry+https://github.com/rust-lang/crates.io-index"
310 | checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3"
311 |
312 | [[package]]
313 | name = "num-traits"
314 | version = "0.2.19"
315 | source = "registry+https://github.com/rust-lang/crates.io-index"
316 | checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
317 | dependencies = [
318 | "autocfg",
319 | ]
320 |
321 | [[package]]
322 | name = "once_cell"
323 | version = "1.21.3"
324 | source = "registry+https://github.com/rust-lang/crates.io-index"
325 | checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
326 |
327 | [[package]]
328 | name = "oorandom"
329 | version = "11.1.5"
330 | source = "registry+https://github.com/rust-lang/crates.io-index"
331 | checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e"
332 |
333 | [[package]]
334 | name = "os_pipe"
335 | version = "1.2.1"
336 | source = "registry+https://github.com/rust-lang/crates.io-index"
337 | checksum = "5ffd2b0a5634335b135d5728d84c5e0fd726954b87111f7506a61c502280d982"
338 | dependencies = [
339 | "libc",
340 | "windows-sys",
341 | ]
342 |
343 | [[package]]
344 | name = "plotters"
345 | version = "0.3.7"
346 | source = "registry+https://github.com/rust-lang/crates.io-index"
347 | checksum = "5aeb6f403d7a4911efb1e33402027fc44f29b5bf6def3effcc22d7bb75f2b747"
348 | dependencies = [
349 | "num-traits",
350 | "plotters-backend",
351 | "plotters-svg",
352 | "wasm-bindgen",
353 | "web-sys",
354 | ]
355 |
356 | [[package]]
357 | name = "plotters-backend"
358 | version = "0.3.7"
359 | source = "registry+https://github.com/rust-lang/crates.io-index"
360 | checksum = "df42e13c12958a16b3f7f4386b9ab1f3e7933914ecea48da7139435263a4172a"
361 |
362 | [[package]]
363 | name = "plotters-svg"
364 | version = "0.3.7"
365 | source = "registry+https://github.com/rust-lang/crates.io-index"
366 | checksum = "51bae2ac328883f7acdfea3d66a7c35751187f870bc81f94563733a154d7a670"
367 | dependencies = [
368 | "plotters-backend",
369 | ]
370 |
371 | [[package]]
372 | name = "pretty_assertions"
373 | version = "1.4.1"
374 | source = "registry+https://github.com/rust-lang/crates.io-index"
375 | checksum = "3ae130e2f271fbc2ac3a40fb1d07180839cdbbe443c7a27e1e3c13c5cac0116d"
376 | dependencies = [
377 | "diff",
378 | "yansi",
379 | ]
380 |
381 | [[package]]
382 | name = "proc-macro2"
383 | version = "1.0.95"
384 | source = "registry+https://github.com/rust-lang/crates.io-index"
385 | checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778"
386 | dependencies = [
387 | "unicode-ident",
388 | ]
389 |
390 | [[package]]
391 | name = "quote"
392 | version = "1.0.40"
393 | source = "registry+https://github.com/rust-lang/crates.io-index"
394 | checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d"
395 | dependencies = [
396 | "proc-macro2",
397 | ]
398 |
399 | [[package]]
400 | name = "r-efi"
401 | version = "5.2.0"
402 | source = "registry+https://github.com/rust-lang/crates.io-index"
403 | checksum = "74765f6d916ee2faa39bc8e68e4f3ed8949b48cccdac59983d287a7cb71ce9c5"
404 |
405 | [[package]]
406 | name = "rayon"
407 | version = "1.10.0"
408 | source = "registry+https://github.com/rust-lang/crates.io-index"
409 | checksum = "b418a60154510ca1a002a752ca9714984e21e4241e804d32555251faf8b78ffa"
410 | dependencies = [
411 | "either",
412 | "rayon-core",
413 | ]
414 |
415 | [[package]]
416 | name = "rayon-core"
417 | version = "1.12.1"
418 | source = "registry+https://github.com/rust-lang/crates.io-index"
419 | checksum = "1465873a3dfdaa8ae7cb14b4383657caab0b3e8a0aa9ae8e04b044854c8dfce2"
420 | dependencies = [
421 | "crossbeam-deque",
422 | "crossbeam-utils",
423 | ]
424 |
425 | [[package]]
426 | name = "regex"
427 | version = "1.11.1"
428 | source = "registry+https://github.com/rust-lang/crates.io-index"
429 | checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191"
430 | dependencies = [
431 | "aho-corasick",
432 | "memchr",
433 | "regex-automata",
434 | "regex-syntax",
435 | ]
436 |
437 | [[package]]
438 | name = "regex-automata"
439 | version = "0.4.9"
440 | source = "registry+https://github.com/rust-lang/crates.io-index"
441 | checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908"
442 | dependencies = [
443 | "aho-corasick",
444 | "memchr",
445 | "regex-syntax",
446 | ]
447 |
448 | [[package]]
449 | name = "regex-syntax"
450 | version = "0.8.5"
451 | source = "registry+https://github.com/rust-lang/crates.io-index"
452 | checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c"
453 |
454 | [[package]]
455 | name = "rustix"
456 | version = "1.0.7"
457 | source = "registry+https://github.com/rust-lang/crates.io-index"
458 | checksum = "c71e83d6afe7ff64890ec6b71d6a69bb8a610ab78ce364b3352876bb4c801266"
459 | dependencies = [
460 | "bitflags",
461 | "errno",
462 | "libc",
463 | "linux-raw-sys",
464 | "windows-sys",
465 | ]
466 |
467 | [[package]]
468 | name = "rustversion"
469 | version = "1.0.21"
470 | source = "registry+https://github.com/rust-lang/crates.io-index"
471 | checksum = "8a0d197bd2c9dc6e53b84da9556a69ba4cdfab8619eb41a8bd1cc2027a0f6b1d"
472 |
473 | [[package]]
474 | name = "ryu"
475 | version = "1.0.20"
476 | source = "registry+https://github.com/rust-lang/crates.io-index"
477 | checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f"
478 |
479 | [[package]]
480 | name = "same-file"
481 | version = "1.0.6"
482 | source = "registry+https://github.com/rust-lang/crates.io-index"
483 | checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
484 | dependencies = [
485 | "winapi-util",
486 | ]
487 |
488 | [[package]]
489 | name = "scopeguard"
490 | version = "1.2.0"
491 | source = "registry+https://github.com/rust-lang/crates.io-index"
492 | checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
493 |
494 | [[package]]
495 | name = "serde"
496 | version = "1.0.219"
497 | source = "registry+https://github.com/rust-lang/crates.io-index"
498 | checksum = "5f0e2c6ed6606019b4e29e69dbaba95b11854410e5347d525002456dbbb786b6"
499 | dependencies = [
500 | "serde_derive",
501 | ]
502 |
503 | [[package]]
504 | name = "serde_derive"
505 | version = "1.0.219"
506 | source = "registry+https://github.com/rust-lang/crates.io-index"
507 | checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00"
508 | dependencies = [
509 | "proc-macro2",
510 | "quote",
511 | "syn",
512 | ]
513 |
514 | [[package]]
515 | name = "serde_json"
516 | version = "1.0.140"
517 | source = "registry+https://github.com/rust-lang/crates.io-index"
518 | checksum = "20068b6e96dc6c9bd23e01df8827e6c7e1f2fddd43c21810382803c136b99373"
519 | dependencies = [
520 | "itoa",
521 | "memchr",
522 | "ryu",
523 | "serde",
524 | ]
525 |
526 | [[package]]
527 | name = "syn"
528 | version = "2.0.101"
529 | source = "registry+https://github.com/rust-lang/crates.io-index"
530 | checksum = "8ce2b7fc941b3a24138a0a7cf8e858bfc6a992e7978a068a5c760deb0ed43caf"
531 | dependencies = [
532 | "proc-macro2",
533 | "quote",
534 | "unicode-ident",
535 | ]
536 |
537 | [[package]]
538 | name = "tempfile"
539 | version = "3.19.1"
540 | source = "registry+https://github.com/rust-lang/crates.io-index"
541 | checksum = "7437ac7763b9b123ccf33c338a5cc1bac6f69b45a136c19bdd8a65e3916435bf"
542 | dependencies = [
543 | "fastrand",
544 | "getrandom",
545 | "once_cell",
546 | "rustix",
547 | "windows-sys",
548 | ]
549 |
550 | [[package]]
551 | name = "termios"
552 | version = "0.3.3"
553 | source = "registry+https://github.com/rust-lang/crates.io-index"
554 | checksum = "411c5bf740737c7918b8b1fe232dca4dc9f8e754b8ad5e20966814001ed0ac6b"
555 | dependencies = [
556 | "libc",
557 | ]
558 |
559 | [[package]]
560 | name = "tinytemplate"
561 | version = "1.2.1"
562 | source = "registry+https://github.com/rust-lang/crates.io-index"
563 | checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc"
564 | dependencies = [
565 | "serde",
566 | "serde_json",
567 | ]
568 |
569 | [[package]]
570 | name = "unicode-ident"
571 | version = "1.0.18"
572 | source = "registry+https://github.com/rust-lang/crates.io-index"
573 | checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512"
574 |
575 | [[package]]
576 | name = "walkdir"
577 | version = "2.5.0"
578 | source = "registry+https://github.com/rust-lang/crates.io-index"
579 | checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
580 | dependencies = [
581 | "same-file",
582 | "winapi-util",
583 | ]
584 |
585 | [[package]]
586 | name = "wasi"
587 | version = "0.14.2+wasi-0.2.4"
588 | source = "registry+https://github.com/rust-lang/crates.io-index"
589 | checksum = "9683f9a5a998d873c0d21fcbe3c083009670149a8fab228644b8bd36b2c48cb3"
590 | dependencies = [
591 | "wit-bindgen-rt",
592 | ]
593 |
594 | [[package]]
595 | name = "wasm-bindgen"
596 | version = "0.2.100"
597 | source = "registry+https://github.com/rust-lang/crates.io-index"
598 | checksum = "1edc8929d7499fc4e8f0be2262a241556cfc54a0bea223790e71446f2aab1ef5"
599 | dependencies = [
600 | "cfg-if",
601 | "once_cell",
602 | "rustversion",
603 | "wasm-bindgen-macro",
604 | ]
605 |
606 | [[package]]
607 | name = "wasm-bindgen-backend"
608 | version = "0.2.100"
609 | source = "registry+https://github.com/rust-lang/crates.io-index"
610 | checksum = "2f0a0651a5c2bc21487bde11ee802ccaf4c51935d0d3d42a6101f98161700bc6"
611 | dependencies = [
612 | "bumpalo",
613 | "log",
614 | "proc-macro2",
615 | "quote",
616 | "syn",
617 | "wasm-bindgen-shared",
618 | ]
619 |
620 | [[package]]
621 | name = "wasm-bindgen-macro"
622 | version = "0.2.100"
623 | source = "registry+https://github.com/rust-lang/crates.io-index"
624 | checksum = "7fe63fc6d09ed3792bd0897b314f53de8e16568c2b3f7982f468c0bf9bd0b407"
625 | dependencies = [
626 | "quote",
627 | "wasm-bindgen-macro-support",
628 | ]
629 |
630 | [[package]]
631 | name = "wasm-bindgen-macro-support"
632 | version = "0.2.100"
633 | source = "registry+https://github.com/rust-lang/crates.io-index"
634 | checksum = "8ae87ea40c9f689fc23f209965b6fb8a99ad69aeeb0231408be24920604395de"
635 | dependencies = [
636 | "proc-macro2",
637 | "quote",
638 | "syn",
639 | "wasm-bindgen-backend",
640 | "wasm-bindgen-shared",
641 | ]
642 |
643 | [[package]]
644 | name = "wasm-bindgen-shared"
645 | version = "0.2.100"
646 | source = "registry+https://github.com/rust-lang/crates.io-index"
647 | checksum = "1a05d73b933a847d6cccdda8f838a22ff101ad9bf93e33684f39c1f5f0eece3d"
648 | dependencies = [
649 | "unicode-ident",
650 | ]
651 |
652 | [[package]]
653 | name = "web-sys"
654 | version = "0.3.77"
655 | source = "registry+https://github.com/rust-lang/crates.io-index"
656 | checksum = "33b6dd2ef9186f1f2072e409e99cd22a975331a6b3591b12c764e0e55c60d5d2"
657 | dependencies = [
658 | "js-sys",
659 | "wasm-bindgen",
660 | ]
661 |
662 | [[package]]
663 | name = "winapi-util"
664 | version = "0.1.9"
665 | source = "registry+https://github.com/rust-lang/crates.io-index"
666 | checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb"
667 | dependencies = [
668 | "windows-sys",
669 | ]
670 |
671 | [[package]]
672 | name = "windows-sys"
673 | version = "0.59.0"
674 | source = "registry+https://github.com/rust-lang/crates.io-index"
675 | checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
676 | dependencies = [
677 | "windows-targets",
678 | ]
679 |
680 | [[package]]
681 | name = "windows-targets"
682 | version = "0.52.6"
683 | source = "registry+https://github.com/rust-lang/crates.io-index"
684 | checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
685 | dependencies = [
686 | "windows_aarch64_gnullvm",
687 | "windows_aarch64_msvc",
688 | "windows_i686_gnu",
689 | "windows_i686_gnullvm",
690 | "windows_i686_msvc",
691 | "windows_x86_64_gnu",
692 | "windows_x86_64_gnullvm",
693 | "windows_x86_64_msvc",
694 | ]
695 |
696 | [[package]]
697 | name = "windows_aarch64_gnullvm"
698 | version = "0.52.6"
699 | source = "registry+https://github.com/rust-lang/crates.io-index"
700 | checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
701 |
702 | [[package]]
703 | name = "windows_aarch64_msvc"
704 | version = "0.52.6"
705 | source = "registry+https://github.com/rust-lang/crates.io-index"
706 | checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
707 |
708 | [[package]]
709 | name = "windows_i686_gnu"
710 | version = "0.52.6"
711 | source = "registry+https://github.com/rust-lang/crates.io-index"
712 | checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
713 |
714 | [[package]]
715 | name = "windows_i686_gnullvm"
716 | version = "0.52.6"
717 | source = "registry+https://github.com/rust-lang/crates.io-index"
718 | checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
719 |
720 | [[package]]
721 | name = "windows_i686_msvc"
722 | version = "0.52.6"
723 | source = "registry+https://github.com/rust-lang/crates.io-index"
724 | checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
725 |
726 | [[package]]
727 | name = "windows_x86_64_gnu"
728 | version = "0.52.6"
729 | source = "registry+https://github.com/rust-lang/crates.io-index"
730 | checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
731 |
732 | [[package]]
733 | name = "windows_x86_64_gnullvm"
734 | version = "0.52.6"
735 | source = "registry+https://github.com/rust-lang/crates.io-index"
736 | checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
737 |
738 | [[package]]
739 | name = "windows_x86_64_msvc"
740 | version = "0.52.6"
741 | source = "registry+https://github.com/rust-lang/crates.io-index"
742 | checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
743 |
744 | [[package]]
745 | name = "wit-bindgen-rt"
746 | version = "0.39.0"
747 | source = "registry+https://github.com/rust-lang/crates.io-index"
748 | checksum = "6f42320e61fe2cfd34354ecb597f86f413484a798ba44a8ca1165c58d42da6c1"
749 | dependencies = [
750 | "bitflags",
751 | ]
752 |
753 | [[package]]
754 | name = "yansi"
755 | version = "1.0.1"
756 | source = "registry+https://github.com/rust-lang/crates.io-index"
757 | checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049"
758 |
--------------------------------------------------------------------------------
/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "flash"
3 | version = "0.0.3"
4 | edition = "2024"
5 | description = "Shell parser, formatter, and interpreter with Bash support"
6 | license = "GPL-3.0-or-later"
7 | include = ["/src", "LICENSE", "README.md"]
8 |
9 | [lib]
10 | name = "flash"
11 | path = "src/lib.rs"
12 |
13 | [[bin]]
14 | name = "flash"
15 | path = "src/bin.rs"
16 |
17 | [features]
18 | default = ["formatter", "interpreter"]
19 | formatter = []
20 | interpreter = ["os_pipe", "glob", "regex", "termios", "scopeguard", "libc"]
21 |
22 | [dependencies]
23 | scopeguard = { version = "1.2.0", optional = true }
24 | termios = { version = "0.3.3", optional = true }
25 | os_pipe = { version = "1.2.1", optional = true }
26 | glob = { version = "0.3.2", optional = true }
27 | regex = { version = "1.11.1", optional = true }
28 | libc = { version = "0.2", optional = true }
29 |
30 | [dev-dependencies]
31 | tempfile = "3.19.1"
32 | pretty_assertions = "1.4.1"
33 | criterion = { version = "0.5", features = ["html_reports"] }
34 |
35 | # We use `opt-level = "s"` as it significantly reduces binary size.
36 | [profile.release]
37 | codegen-units = 1 # reduces binary size by ~2%
38 | debug = "full" # No one needs an undebuggable release binary
39 | lto = true # reduces binary size by ~14%
40 | opt-level = "s" # reduces binary size by ~25%
41 | panic = "abort" # reduces binary size by ~50% in combination with -Zbuild-std-features=panic_immediate_abort
42 | split-debuginfo = "packed" # generates a separate *.dwp/*.dSYM so the binary can get stripped
43 | strip = "symbols" # See split-debuginfo - allows us to drop the size by ~65%
44 |
45 | [profile.dev]
46 | split-debuginfo = "unpacked"
47 | lto = false
48 | incremental = true
49 | opt-level = 0
50 |
51 | [[bench]]
52 | name = "flash_benchmarks"
53 | harness = false
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright © 2007 Free Software Foundation, Inc.
5 |
6 | Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for software and other kinds of works.
11 |
12 | The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
13 |
14 | When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
15 |
16 | To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
17 |
18 | For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
19 |
20 | Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
21 |
22 | For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
23 |
24 | Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
25 |
26 | Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
27 |
28 | The precise terms and conditions for copying, distribution and modification follow.
29 |
30 | TERMS AND CONDITIONS
31 |
32 | 0. Definitions.
33 | "This License" refers to version 3 of the GNU General Public License.
34 |
35 | "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
36 |
37 | "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
38 |
39 | To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
40 |
41 | A "covered work" means either the unmodified Program or a work based on the Program.
42 |
43 | To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
44 |
45 | To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
46 |
47 | An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
48 |
49 | 1. Source Code.
50 | The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
51 | A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
52 |
53 | The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
54 |
55 | The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
56 |
57 | The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
58 |
59 | The Corresponding Source for a work in source code form is that same work.
60 |
61 | 2. Basic Permissions.
62 | All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
63 | You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
64 |
65 | Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
66 |
67 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
68 | No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
69 | When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
70 |
71 | 4. Conveying Verbatim Copies.
72 | You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
73 | You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
74 |
75 | 5. Conveying Modified Source Versions.
76 | You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
77 | a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
78 | b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
79 | c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
80 | d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
81 | A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
82 |
83 | 6. Conveying Non-Source Forms.
84 | You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
85 | a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
86 | b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
87 | c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
88 | d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
89 | e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
90 | A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
91 |
92 | A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
93 |
94 | "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
95 |
96 | If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
97 |
98 | The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
99 |
100 | Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
101 |
102 | 7. Additional Terms.
103 | "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
104 | When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
105 |
106 | Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
107 |
108 | a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
109 | b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
110 | c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
111 | d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
112 | e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
113 | f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
114 | All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
115 |
116 | If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
117 |
118 | Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
119 |
120 | 8. Termination.
121 | You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
122 | However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
123 |
124 | Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
125 |
126 | Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
127 |
128 | 9. Acceptance Not Required for Having Copies.
129 | You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
130 | 10. Automatic Licensing of Downstream Recipients.
131 | Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
132 | An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
133 |
134 | You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
135 |
136 | 11. Patents.
137 | A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
138 | A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
139 |
140 | Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
141 |
142 | In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
143 |
144 | If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
145 |
146 | If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
147 |
148 | A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
149 |
150 | Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
151 |
152 | 12. No Surrender of Others' Freedom.
153 | If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
154 | 13. Use with the GNU Affero General Public License.
155 | Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
156 | 14. Revised Versions of this License.
157 | The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
158 | Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
159 |
160 | If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
161 |
162 | Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
163 |
164 | 15. Disclaimer of Warranty.
165 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
166 | 16. Limitation of Liability.
167 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
168 | 17. Interpretation of Sections 15 and 16.
169 | If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
170 |
171 | END OF TERMS AND CONDITIONS
172 |
173 | How to Apply These Terms to Your New Programs
174 |
175 | If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
176 |
177 | To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
178 |
179 |
180 | Copyright (C)
181 |
182 | This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
183 |
184 | This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
185 |
186 | You should have received a copy of the GNU General Public License along with this program. If not, see .
187 |
188 | Also add information on how to contact you by electronic and paper mail.
189 |
190 | If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
191 |
192 | Copyright (C)
193 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
194 | This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
195 |
196 | The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box".
197 |
198 | You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see .
199 |
200 | The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read .
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | all: run
2 |
3 | run:
4 | cargo run --release
5 |
6 | dev:
7 | cargo run
8 |
9 | lint:
10 | cargo fmt -- --check --color always
11 | cargo clippy --all-targets --all-features -- -D warnings
12 |
13 | test:
14 | make lint
15 | RUST_BACKTRACE=full cargo test --release
16 | RUST_BACKTRACE=full cargo test --test integration_tests
17 |
18 | test-if:
19 | @echo "Building Flash for if/elif/else functionality tests..."
20 | @cargo build --release
21 | @echo "Running if/elif/else functionality tests..."
22 | @./test_if_functionality.sh
23 |
24 | test-all: test test-if
25 | @echo "All tests completed successfully!"
26 |
27 | .PHONY: all run dev lint test test-if test-all
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Flash (work in progress)
2 |
3 | *A shell parser, formatter, and interpreter written in Rust.*
4 |
5 | Flash is a fast, extensible, and hackable toolkit for working with POSIX-style shell scripts. It includes a parser, formatter, and interpreter built from scratch in Rust. Flash understands real-world shell syntax and provides structured AST access for static analysis, tooling, and transformation.
6 |
7 | > Inspired by [mvdan/sh](https://pkg.go.dev/mvdan.cc/sh/v3/syntax), but engineered from the ground up with performance and extensibility in mind.
8 |
9 | Ideally I would like to use Flash in my daily basis. It's still far from proper usage.
10 |
11 | ## Summary
12 |
13 | - [Feature Coverage](#feature-coverage)
14 | - [Flash as shell](#as-shell)
15 | - [Flash as library or shell backend](#as-library)
16 |
17 | ## Feature Coverage
18 |
19 | This table outlines the supported features of POSIX Shell and Bash. Use it to track what your **Flash** parser and interpreter implementation in Rust supports.
20 |
21 | Legends:
22 |
23 | - ✅ fully supported.
24 | - ⚠️ only supported in parser and formatter.
25 | - ❌ not supported.
26 |
27 | | Category | Functionality / Feature | POSIX Shell | Bash | Flash | Notes |
28 | |-----------------------|--------------------------------------------------|-------------|------|------|-------|
29 | | **Basic Syntax** | Variable assignment | ✅ | ✅ | ✅ | `VAR=value` |
30 | | | Command substitution | ✅ | ✅ | ✅ | `$(cmd)` and `` `cmd` `` |
31 | | | Arithmetic substitution | ❌ | ✅ | ✅ | `$((expr))` |
32 | | | Comments (`#`) | ✅ | ✅ | ✅ | |
33 | | | Quoting (`'`, "", `\`) | ✅ | ✅ | ✅ | |
34 | | | Globbing (`*`, `?`, `[...]`) | ✅ | ✅ | ❌ | |
35 | | **Control Structures**| `if` / `else` / `elif` | ✅ | ✅ | ✅ | |
36 | | | `case` / `esac` | ✅ | ✅ | ❌ | |
37 | | | `for` loops | ✅ | ✅ | ❌ | |
38 | | | `while`, `until` loops | ✅ | ✅ | ❌ | |
39 | | | `select` loop | ❌ | ✅ | ❌ | |
40 | | | `[[ ... ]]` test command | ❌ | ✅ | ✅ | Extended test |
41 | | **Functions** | Function definition (`name() {}`) | ✅ | ✅ | ✅ | |
42 | | | `function` keyword | ❌ | ✅ | ✅ | Bash-specific |
43 | | **I/O Redirection** | Output/input redirection (`>`, `<`, `>>`) | ✅ | ✅ | ✅ | |
44 | | | Here documents (`<<`, `<<-`) | ✅ | ✅ | ❌ | |
45 | | | Here strings (`<<<`) | ❌ | ✅ | ❌ | |
46 | | | File descriptor duplication (`>&`, `<&`) | ✅ | ✅ | ❌ | |
47 | | **Job Control** | Background execution (`&`) | ✅ | ✅ | ❌ | |
48 | | | Job control commands (`fg`, `bg`, `jobs`) | ✅ | ✅ | ✅ | May be interactive-only |
49 | | | Process substitution (`<(...)`, `>(...)`) | ❌ | ✅ | ❌ | |
50 | | **Arrays** | Indexed arrays | ❌ | ✅ | ✅ | `arr=(a b c)` |
51 | | | Associative arrays | ❌ | ✅ | ❌ | `declare -A` |
52 | | **Parameter Expansion** | `${var}` basic expansion | ✅ | ✅ | ❌ | |
53 | | | `${var:-default}`, `${var:=default}` | ✅ | ✅ | ❌ | |
54 | | | `${#var}`, `${var#pattern}` | ✅ | ✅ | ❌ | |
55 | | | `${!var}` indirect expansion | ❌ | ✅ | ❌ | |
56 | | | `${var[@]}` / `${var[*]}` array expansion | ❌ | ✅ | ❌ | |
57 | | **Command Execution** | Pipelines (`|`) | ✅ | ✅ | ❌ | |
58 | | | Logical AND / OR (`&&`, `||`) | ✅ | ✅ | ❌ | |
59 | | | Grouping (`( )`, `{ }`) | ✅ | ✅ | ❌ | |
60 | | | Subshell (`( )`) | ✅ | ✅ | ❌ | |
61 | | | Coprocesses (`coproc`) | ❌ | ✅ | ❌ | |
62 | | **Builtins** | `cd`, `echo`, `test`, `read`, `eval`, etc. | ✅ | ✅ | ✅ | |
63 | | | `shopt`, `declare`, `typeset` | ❌ | ✅ | ❌ | Bash-only |
64 | | | `let`, `local`, `export` | ✅ | ✅ | ❌ | |
65 | | **Debugging** | `set -x`, `set -e`, `trap` | ✅ | ✅ | ❌ | |
66 | | | `BASH_SOURCE`, `FUNCNAME` arrays | ❌ | ✅ | ❌ | |
67 | | **Miscellaneous** | Brace expansion (`{1..5}`) | ❌ | ✅ | ❌ | |
68 | | | Extended globbing (`extglob`) | ❌ | ✅ | ❌ | Requires `shopt` |
69 | | | Bash version variables (`$BASH_VERSION`) | ❌ | ✅ | ❌ | |
70 | | | Source other scripts (`.` or `source`) | ✅ | ✅ | ❌ | `source` is Bash synonym |
71 |
72 | ## As shell
73 |
74 | At its base, a shell is simply a macro processor that executes commands. The term macro processor means functionality where text and symbols are expanded to create larger expressions.
75 |
76 | A Unix shell is both a command interpreter and a programming language. As a command interpreter, the shell provides the user interface to the rich set of GNU utilities. The programming language features allow these utilities to be combined. Files containing commands can be created, and become commands themselves. These new commands have the same status as system commands in directories such as /bin, allowing users or groups to establish custom environments to automate their common tasks.
77 |
78 | Shells may be used interactively or non-interactively. In interactive mode, they accept input typed from the keyboard. When executing non-interactively, shells execute commands read from a file.
79 |
80 | Flash is largely compatible with sh and bash.
81 |
82 | > ⚠️ Flash is still under development. Use it with caution in production environments.
83 |
84 | #### Installing it
85 |
86 | Option 1:
87 |
88 | ```bash
89 | cargo install flash
90 | ```
91 |
92 | Option 2:
93 |
94 | ```bash
95 | git clone https://github.com/raphamorim/flash.git
96 | cd flash && cargo install --path .
97 | ```
98 |
99 | Option 3:
100 |
101 | ```bash
102 | git clone https://github.com/raphamorim/flash.git
103 | cd flash
104 | cargo build --release
105 |
106 | # Linux
107 | sudo cp target/release/flash /bin/
108 |
109 | # MacOS/BSD
110 | sudo cp target/release/flash /usr/local/bin/
111 |
112 | # Done
113 | flash
114 | ```
115 |
116 | #### Set as default
117 |
118 | Optionally you can also set as default
119 |
120 | ```bash
121 | # Add your flash path to:
122 | vim /etc/shells
123 |
124 | # Linux:
125 | chsh -s /bin/flash
126 |
127 | # MacOS/BSD:
128 | chsh -s /usr/local/bin/flash
129 | ```
130 |
131 | ## Configuration
132 |
133 | Flash supports configuration through a `.flashrc` file in your home directory. This file is executed when the shell starts up.
134 |
135 | ### Custom Prompt
136 |
137 | You can customize your shell prompt by setting the `PROMPT` variable in your `.flashrc` file:
138 |
139 | ```bash
140 | # Simple prompt
141 | export PROMPT="flash> "
142 |
143 | # Prompt with current directory
144 | export PROMPT="flash:$PWD$ "
145 |
146 | # Prompt with username and hostname
147 | export PROMPT="$USER@$HOSTNAME:$PWD$ "
148 | ```
149 |
150 | The `PROMPT` variable supports variable expansion, so you can use any environment variables in your prompt.
151 |
152 | ### Example .flashrc
153 |
154 | ```bash
155 | # Custom prompt
156 | export PROMPT="flash:$PWD$ "
157 |
158 | # Environment variables
159 | export EDITOR=vim
160 | export PAGER=less
161 |
162 | # Custom aliases (when alias support is added)
163 | # alias ll="ls -la"
164 | # alias grep="grep --color=auto"
165 | ```
166 |
167 | --
168 |
169 | ## As library
170 |
171 | Flash can also be used a rust library that can help different purposes: testing purposes, parsing sh/bash, as a backend for your own shell, formatting sh/bash code, and other stuff.
172 |
173 | #### As an Interpreter
174 |
175 | ```rust
176 | use flash::interpreter::Interpreter;
177 | use std::io;
178 |
179 | fn main() -> io::Result<()> {
180 | let mut interpreter = Interpreter::new();
181 | interpreter.run_interactive()?;
182 | Ok(())
183 | }
184 | ```
185 |
186 | Note that `run_interactive` will use flash default evaluator.
187 |
188 | ```rust
189 | // Default interactive shell using DefaultEvaluator
190 | pub fn run_interactive(&mut self) -> io::Result<()> {
191 | let default_evaluator = DefaultEvaluator;
192 | self.run_interactive_with_evaluator(default_evaluator)
193 | }
194 | ```
195 |
196 | You can actually create your own evaluator using Evaluator trait:
197 |
198 | ```rust
199 | // Define the evaluation trait that users can implement
200 | pub trait Evaluator {
201 | fn evaluate(&mut self, node: &Node, interpreter: &mut Interpreter) -> Result;
202 | }
203 |
204 | // Default evaluator that implements the standard shell behavior
205 | pub struct DefaultEvaluator;
206 |
207 | impl Evaluator for DefaultEvaluator {
208 | fn evaluate(&mut self, node: &Node, interpreter: &mut Interpreter) -> Result {
209 | match node {
210 | Node::Command {
211 | name,
212 | args,
213 | redirects,
214 | } => self.evaluate_command(name, args, redirects, interpreter),
215 | Node::Pipeline { commands } => self.evaluate_pipeline(commands, interpreter),
216 | Node::List {
217 | statements,
218 | operators,
219 | } => self.evaluate_list(statements, operators, interpreter),
220 | Node::Assignment { name, value } => self.evaluate_assignment(name, value, interpreter),
221 | Node::CommandSubstitution { command: _ } => {
222 | Err(io::Error::other("Unexpected command substitution node"))
223 | }
224 | Node::StringLiteral(_value) => Ok(0),
225 | Node::Subshell { list } => interpreter.evaluate_with_evaluator(list, self),
226 | Node::Comment(_) => Ok(0),
227 | Node::ExtGlobPattern {
228 | operator,
229 | patterns,
230 | suffix,
231 | } => self.evaluate_ext_glob(*operator, patterns, suffix, interpreter),
232 | _ => Err(io::Error::other("Unsupported node type")),
233 | }
234 | }
235 | }
236 |
237 | impl DefaultEvaluator {
238 | fn evaluate_command(
239 | &mut self,
240 | name: &str,
241 | args: &[String],
242 | redirects: &[Redirect],
243 | interpreter: &mut Interpreter,
244 | ) -> Result {
245 | // Handle built-in commands
246 | match name {
247 | "cd" => {
248 | let dir = if args.is_empty() {
249 | env::var("HOME").unwrap_or_else(|_| ".".to_string())
250 | } else {
251 | args[0].clone()
252 | };
253 |
254 | match env::set_current_dir(&dir) {
255 | Ok(_) => {
256 | interpreter.variables.insert(
257 | "PWD".to_string(),
258 | env::current_dir()?.to_string_lossy().to_string(),
259 | );
260 | Ok(0)
261 | }
262 | Err(e) => {
263 | eprintln!("cd: {}: {}", dir, e);
264 | Ok(1)
265 | }
266 | }
267 | }
268 | "echo" => {
269 | for (i, arg) in args.iter().enumerate() {
270 | print!("{}{}", if i > 0 { " " } else { "" }, arg);
271 | }
272 | println!();
273 | Ok(0)
274 | }
275 | "export" => {
276 | for arg in args {
277 | if let Some(pos) = arg.find('=') {
278 | let (key, value) = arg.split_at(pos);
279 | let value = &value[1..];
280 | interpreter
281 | .variables
282 | .insert(key.to_string(), value.to_string());
283 | unsafe {
284 | env::set_var(key, value);
285 | }
286 | } else if let Some(value) = interpreter.variables.get(arg) {
287 | unsafe {
288 | env::set_var(arg, value);
289 | }
290 | }
291 | }
292 | Ok(0)
293 | }
294 | "source" | "." => {
295 | if args.is_empty() {
296 | eprintln!("source: filename argument required");
297 | return Ok(1);
298 | }
299 |
300 | let filename = &args[0];
301 | match fs::read_to_string(filename) {
302 | Ok(content) => interpreter.execute(&content),
303 | Err(e) => {
304 | eprintln!("source: {}: {}", filename, e);
305 | Ok(1)
306 | }
307 | }
308 | }
309 | _ => {
310 | // External command
311 | let mut command = Command::new(name);
312 | command.args(args);
313 |
314 | // Handle redirections
315 | for redirect in redirects {
316 | match redirect.kind {
317 | RedirectKind::Input => {
318 | let file = fs::File::open(&redirect.file)?;
319 | command.stdin(Stdio::from(file));
320 | }
321 | RedirectKind::Output => {
322 | let file = fs::File::create(&redirect.file)?;
323 | command.stdout(Stdio::from(file));
324 | }
325 | RedirectKind::Append => {
326 | let file = fs::OpenOptions::new()
327 | .create(true)
328 | .append(true)
329 | .open(&redirect.file)?;
330 | command.stdout(Stdio::from(file));
331 | }
332 | }
333 | }
334 |
335 | // Set environment variables
336 | for (key, value) in &interpreter.variables {
337 | command.env(key, value);
338 | }
339 |
340 | match command.status() {
341 | Ok(status) => Ok(status.code().unwrap_or(0)),
342 | Err(_) => {
343 | eprintln!("{}: command not found", name);
344 | Ok(127)
345 | }
346 | }
347 | }
348 | }
349 | }
350 |
351 | fn evaluate_pipeline(
352 | &mut self,
353 | commands: &[Node],
354 | interpreter: &mut Interpreter,
355 | ) -> Result {
356 | if commands.is_empty() {
357 | return Ok(0);
358 | }
359 |
360 | if commands.len() == 1 {
361 | return interpreter.evaluate_with_evaluator(&commands[0], self);
362 | }
363 |
364 | let mut last_exit_code = 0;
365 | for command in commands {
366 | last_exit_code = interpreter.evaluate_with_evaluator(command, self)?;
367 | }
368 | Ok(last_exit_code)
369 | }
370 |
371 | fn evaluate_list(
372 | &mut self,
373 | statements: &[Node],
374 | operators: &[String],
375 | interpreter: &mut Interpreter,
376 | ) -> Result {
377 | let mut last_exit_code = 0;
378 |
379 | for (i, statement) in statements.iter().enumerate() {
380 | last_exit_code = interpreter.evaluate_with_evaluator(statement, self)?;
381 |
382 | if i < operators.len() {
383 | match operators[i].as_str() {
384 | "&&" => {
385 | if last_exit_code != 0 {
386 | break;
387 | }
388 | }
389 | "||" => {
390 | if last_exit_code == 0 {
391 | break;
392 | }
393 | }
394 | _ => {}
395 | }
396 | }
397 | }
398 |
399 | Ok(last_exit_code)
400 | }
401 |
402 | fn evaluate_assignment(
403 | &mut self,
404 | name: &str,
405 | value: &Node,
406 | interpreter: &mut Interpreter,
407 | ) -> Result {
408 | match value {
409 | Node::StringLiteral(string_value) => {
410 | let expanded_value = interpreter.expand_variables(string_value);
411 | interpreter
412 | .variables
413 | .insert(name.to_string(), expanded_value);
414 | }
415 | Node::CommandSubstitution { command } => {
416 | let output = interpreter.capture_command_output(command, self)?;
417 | interpreter.variables.insert(name.to_string(), output);
418 | }
419 | _ => {
420 | return Err(io::Error::other("Unsupported value type for assignment"));
421 | }
422 | }
423 | Ok(0)
424 | }
425 |
426 | fn evaluate_ext_glob(
427 | &mut self,
428 | operator: char,
429 | patterns: &[String],
430 | suffix: &str,
431 | interpreter: &Interpreter,
432 | ) -> Result {
433 | let entries = fs::read_dir(".")?;
434 | let mut matches = Vec::new();
435 |
436 | for entry in entries.flatten() {
437 | let file_name = entry.file_name().to_string_lossy().to_string();
438 | if interpreter.matches_ext_glob(&file_name, operator, patterns, suffix) {
439 | matches.push(file_name);
440 | }
441 | }
442 |
443 | for m in matches {
444 | println!("{}", m);
445 | }
446 |
447 | Ok(0)
448 | }
449 | }
450 | ```
451 |
452 | #### As a Lexer/Tokenizer
453 |
454 | ```rust
455 | fn test_tokens(input: &str, expected_tokens: Vec) {
456 | let mut lexer = Lexer::new(input);
457 | for expected in expected_tokens {
458 | let token = lexer.next_token();
459 | assert_eq!(
460 | token.kind, expected,
461 | "Expected {:?} but got {:?} for input: {}",
462 | expected, token.kind, input
463 | );
464 | }
465 |
466 | // Ensure we've consumed all tokens
467 | let final_token = lexer.next_token();
468 | assert_eq!(
469 | final_token.kind,
470 | TokenKind::EOF,
471 | "Expected EOF but got {:?}",
472 | final_token.kind
473 | );
474 | }
475 |
476 | #[test]
477 | fn test_function_declaration() {
478 | let input = "function greet() { echo hello; }";
479 | let expected = vec![
480 | TokenKind::Function,
481 | TokenKind::Word("greet".to_string()),
482 | TokenKind::LParen,
483 | TokenKind::RParen,
484 | TokenKind::LBrace,
485 | TokenKind::Word("echo".to_string()),
486 | TokenKind::Word("hello".to_string()),
487 | TokenKind::Semicolon,
488 | TokenKind::RBrace,
489 | ];
490 | test_tokens(input, expected);
491 | }
492 | ```
493 |
494 | #### As a Parser
495 |
496 | ```rust
497 | use flash::lexer::Lexer;
498 | use flash::parser::Parser;
499 |
500 | #[test]
501 | fn test_simple_command() {
502 | let input = "echo hello world";
503 | let lexer = Lexer::new(input);
504 | let mut parser = Parser::new(lexer);
505 | let result = parser.parse_script();
506 |
507 | match result {
508 | Node::List {
509 | statements,
510 | operators,
511 | } => {
512 | assert_eq!(statements.len(), 1);
513 | assert_eq!(operators.len(), 0);
514 |
515 | match &statements[0] {
516 | Node::Command {
517 | name,
518 | args,
519 | redirects,
520 | } => {
521 | assert_eq!(name, "echo");
522 | assert_eq!(args, &["hello", "world"]);
523 | assert_eq!(redirects.len(), 0);
524 | }
525 | _ => panic!("Expected Command node"),
526 | }
527 | }
528 | _ => panic!("Expected List node"),
529 | }
530 | }
531 | ```
532 |
533 | #### As Formatter
534 |
535 | ```rust
536 | assert_eq!(
537 | Formatter::format_str(" # This is a comment"),
538 | "# This is a comment"
539 | );
540 | ```
541 |
542 | Or by receiving AST
543 |
544 | ```rust
545 | let mut formatter = Formatter::new();
546 | let node = Node::Comment(" This is a comment".to_string());
547 |
548 | assert_eq!(formatter.format(&node), "# This is a comment");
549 | ```
550 |
551 | ## Resources
552 |
553 | - https://www.gnu.org/software/bash/manual/bash.html
554 | - https://www.shellcheck.net/
555 | - https://stackblitz.com/edit/bash-ast?file=src%2Fapp%2Fapp.component.ts
556 |
557 | ## License
558 |
559 | [GPL-3.0 License](LICENSE) © [Raphael Amorim](https://github.com/raphamorim/)
--------------------------------------------------------------------------------
/benches/flash_benchmarks.rs:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2025 Raphael Amorim
3 | *
4 | * This file is part of flash, which is licensed
5 | * under GNU General Public License v3.0.
6 | */
7 |
8 | use criterion::{BenchmarkId, Criterion, black_box, criterion_group, criterion_main};
9 | use flash::lexer::Lexer;
10 | use flash::parser::Parser;
11 | // use flash::simd::{find_quotes, find_special_chars, find_whitespace};
12 |
13 | #[cfg(feature = "formatter")]
14 | use flash::formatter::{Formatter, FormatterConfig, ShellVariant};
15 |
16 | // fn simd_benchmarks(c: &mut Criterion) {
17 | // let mut group = c.benchmark_group("simd");
18 |
19 | // let simple_text = b"hello world | grep test";
20 | // let complex_text = b"if [ \"$USER\" = \"root\" ]; then echo 'Running as root'; fi";
21 | // let large_text = "echo hello world | grep test && ls -la || exit 1; ".repeat(100);
22 | // let large_text_bytes = large_text.as_bytes();
23 |
24 | // // Benchmark SIMD character finding functions
25 | // group.bench_with_input(
26 | // BenchmarkId::new("find_special_chars", "simple"),
27 | // &simple_text,
28 | // |b, input| b.iter(|| black_box(find_special_chars(*black_box(input), 0))),
29 | // );
30 |
31 | // group.bench_with_input(
32 | // BenchmarkId::new("find_special_chars", "complex"),
33 | // &complex_text,
34 | // |b, input| b.iter(|| black_box(find_special_chars(*black_box(input), 0))),
35 | // );
36 |
37 | // group.bench_with_input(
38 | // BenchmarkId::new("find_special_chars", "large"),
39 | // &large_text_bytes,
40 | // |b, input| b.iter(|| black_box(find_special_chars(black_box(input), 0))),
41 | // );
42 |
43 | // group.bench_with_input(
44 | // BenchmarkId::new("find_whitespace", "simple"),
45 | // &simple_text,
46 | // |b, input| b.iter(|| black_box(find_whitespace(*black_box(input), 0))),
47 | // );
48 |
49 | // group.bench_with_input(
50 | // BenchmarkId::new("find_quotes", "complex"),
51 | // &complex_text,
52 | // |b, input| b.iter(|| black_box(find_quotes(*black_box(input), 0))),
53 | // );
54 |
55 | // group.finish();
56 | // }
57 |
58 | // fn lexer_simd_benchmarks(c: &mut Criterion) {
59 | // let mut group = c.benchmark_group("lexer_simd");
60 |
61 | // let simple_command = "echo hello world";
62 | // let complex_command = r#"
63 | // if [ "$USER" = "root" ]; then
64 | // echo "Running as root"
65 | // for file in /etc/*.conf; do
66 | // if [ -f "$file" ]; then
67 | // echo "Processing $file"
68 | // cat "$file" | grep -E "^[^#]" | sort
69 | // fi
70 | // done
71 | // elif [ -n "$HOME" ]; then
72 | // cd "$HOME" && ls -la
73 | // else
74 | // echo "Unknown user environment"
75 | // fi
76 | // "#;
77 |
78 | // let large_script = "echo hello world | grep test && ls -la || exit 1; ".repeat(500);
79 |
80 | // // Compare regular lexer vs SIMD lexer
81 | // group.bench_with_input(
82 | // BenchmarkId::new("regular_lexer", "simple"),
83 | // &simple_command,
84 | // |b, input| {
85 | // b.iter(|| {
86 | // let mut lexer = Lexer::new(black_box(input));
87 | // let mut tokens = Vec::new();
88 | // loop {
89 | // let token = lexer.next_token();
90 | // if token.kind == flash::lexer::TokenKind::EOF {
91 | // break;
92 | // }
93 | // tokens.push(token);
94 | // }
95 | // black_box(tokens)
96 | // })
97 | // },
98 | // );
99 |
100 | // group.bench_with_input(
101 | // BenchmarkId::new("simd_lexer", "simple"),
102 | // &simple_command,
103 | // |b, input| {
104 | // b.iter(|| {
105 | // let mut lexer = Lexer::new(black_box(input));
106 | // let mut tokens = Vec::new();
107 | // loop {
108 | // let token = lexer.next_token_simd();
109 | // if token.kind == flash::lexer::TokenKind::EOF {
110 | // break;
111 | // }
112 | // tokens.push(token);
113 | // }
114 | // black_box(tokens)
115 | // })
116 | // },
117 | // );
118 |
119 | // group.bench_with_input(
120 | // BenchmarkId::new("regular_lexer", "large"),
121 | // &large_script,
122 | // |b, input| {
123 | // b.iter(|| {
124 | // let mut lexer = Lexer::new(black_box(input));
125 | // let mut tokens = Vec::new();
126 | // loop {
127 | // let token = lexer.next_token();
128 | // if token.kind == flash::lexer::TokenKind::EOF {
129 | // break;
130 | // }
131 | // tokens.push(token);
132 | // }
133 | // black_box(tokens)
134 | // })
135 | // },
136 | // );
137 |
138 | // group.bench_with_input(
139 | // BenchmarkId::new("simd_lexer", "large"),
140 | // &large_script,
141 | // |b, input| {
142 | // b.iter(|| {
143 | // let mut lexer = Lexer::new(black_box(input));
144 | // let mut tokens = Vec::new();
145 | // loop {
146 | // let token = lexer.next_token_simd();
147 | // if token.kind == flash::lexer::TokenKind::EOF {
148 | // break;
149 | // }
150 | // tokens.push(token);
151 | // }
152 | // black_box(tokens)
153 | // })
154 | // },
155 | // );
156 |
157 | // group.finish();
158 | // }
159 |
160 | fn lexer_benchmarks(c: &mut Criterion) {
161 | let mut group = c.benchmark_group("lexer");
162 |
163 | let simple_command = "echo hello world";
164 | let complex_command = r#"
165 | if [ "$USER" = "root" ]; then
166 | echo "Running as root"
167 | for file in /etc/*.conf; do
168 | if [ -f "$file" ]; then
169 | echo "Processing $file"
170 | cat "$file" | grep -E "^[^#]" | sort
171 | fi
172 | done
173 | elif [ -n "$HOME" ]; then
174 | cd "$HOME" && ls -la
175 | else
176 | echo "Unknown user environment"
177 | fi
178 | "#;
179 |
180 | let pipeline_command = "cat /etc/passwd | grep root | cut -d: -f1 | sort | uniq";
181 | let variable_expansion = r#"echo "Hello $USER, today is $(date +%Y-%m-%d)""#;
182 |
183 | group.bench_with_input(
184 | BenchmarkId::new("simple_command", simple_command.len()),
185 | &simple_command,
186 | |b, input| {
187 | b.iter(|| {
188 | let mut lexer = Lexer::new(black_box(input));
189 | let mut tokens = Vec::new();
190 | loop {
191 | let token = lexer.next_token();
192 | if token.kind == flash::lexer::TokenKind::EOF {
193 | break;
194 | }
195 | tokens.push(token);
196 | }
197 | black_box(tokens)
198 | })
199 | },
200 | );
201 |
202 | group.bench_with_input(
203 | BenchmarkId::new("complex_conditional", complex_command.len()),
204 | &complex_command,
205 | |b, input| {
206 | b.iter(|| {
207 | let mut lexer = Lexer::new(black_box(input));
208 | let mut tokens = Vec::new();
209 | loop {
210 | let token = lexer.next_token();
211 | if token.kind == flash::lexer::TokenKind::EOF {
212 | break;
213 | }
214 | tokens.push(token);
215 | }
216 | black_box(tokens)
217 | })
218 | },
219 | );
220 |
221 | group.bench_with_input(
222 | BenchmarkId::new("pipeline", pipeline_command.len()),
223 | &pipeline_command,
224 | |b, input| {
225 | b.iter(|| {
226 | let mut lexer = Lexer::new(black_box(input));
227 | let mut tokens = Vec::new();
228 | loop {
229 | let token = lexer.next_token();
230 | if token.kind == flash::lexer::TokenKind::EOF {
231 | break;
232 | }
233 | tokens.push(token);
234 | }
235 | black_box(tokens)
236 | })
237 | },
238 | );
239 |
240 | group.bench_with_input(
241 | BenchmarkId::new("variable_expansion", variable_expansion.len()),
242 | &variable_expansion,
243 | |b, input| {
244 | b.iter(|| {
245 | let mut lexer = Lexer::new(black_box(input));
246 | let mut tokens = Vec::new();
247 | loop {
248 | let token = lexer.next_token();
249 | if token.kind == flash::lexer::TokenKind::EOF {
250 | break;
251 | }
252 | tokens.push(token);
253 | }
254 | black_box(tokens)
255 | })
256 | },
257 | );
258 |
259 | group.finish();
260 | }
261 |
262 | fn parser_benchmarks(c: &mut Criterion) {
263 | let mut group = c.benchmark_group("parser");
264 |
265 | let simple_command = "echo hello world";
266 | let complex_command = r#"
267 | if [ "$USER" = "root" ]; then
268 | echo "Running as root"
269 | for file in /etc/*.conf; do
270 | if [ -f "$file" ]; then
271 | echo "Processing $file"
272 | cat "$file" | grep -E "^[^#]" | sort
273 | fi
274 | done
275 | elif [ -n "$HOME" ]; then
276 | cd "$HOME" && ls -la
277 | else
278 | echo "Unknown user environment"
279 | fi
280 | "#;
281 |
282 | let pipeline_command = "cat /etc/passwd | grep root | cut -d: -f1 | sort | uniq";
283 | let function_definition = r#"
284 | function backup_files() {
285 | local source_dir="$1"
286 | local backup_dir="$2"
287 |
288 | if [ ! -d "$source_dir" ]; then
289 | echo "Source directory does not exist"
290 | return 1
291 | fi
292 |
293 | mkdir -p "$backup_dir"
294 | cp -r "$source_dir"/* "$backup_dir"/
295 | }
296 | "#;
297 |
298 | group.bench_with_input(
299 | BenchmarkId::new("simple_command", simple_command.len()),
300 | &simple_command,
301 | |b, input| {
302 | b.iter(|| {
303 | let lexer = Lexer::new(black_box(input));
304 | let mut parser = Parser::new(lexer);
305 | black_box(parser.parse_script())
306 | })
307 | },
308 | );
309 |
310 | group.bench_with_input(
311 | BenchmarkId::new("complex_conditional", complex_command.len()),
312 | &complex_command,
313 | |b, input| {
314 | b.iter(|| {
315 | let lexer = Lexer::new(black_box(input));
316 | let mut parser = Parser::new(lexer);
317 | black_box(parser.parse_script())
318 | })
319 | },
320 | );
321 |
322 | group.bench_with_input(
323 | BenchmarkId::new("pipeline", pipeline_command.len()),
324 | &pipeline_command,
325 | |b, input| {
326 | b.iter(|| {
327 | let lexer = Lexer::new(black_box(input));
328 | let mut parser = Parser::new(lexer);
329 | black_box(parser.parse_script())
330 | })
331 | },
332 | );
333 |
334 | group.bench_with_input(
335 | BenchmarkId::new("function_definition", function_definition.len()),
336 | &function_definition,
337 | |b, input| {
338 | b.iter(|| {
339 | let lexer = Lexer::new(black_box(input));
340 | let mut parser = Parser::new(lexer);
341 | black_box(parser.parse_script())
342 | })
343 | },
344 | );
345 |
346 | group.finish();
347 | }
348 |
349 | #[cfg(feature = "formatter")]
350 | fn formatter_benchmarks(c: &mut Criterion) {
351 | let mut group = c.benchmark_group("formatter");
352 |
353 | let config = FormatterConfig {
354 | indent_str: " ".to_string(),
355 | shell_variant: ShellVariant::Bash,
356 | binary_next_line: false,
357 | switch_case_indent: true,
358 | space_redirects: true,
359 | keep_padding: false,
360 | function_next_line: false,
361 | never_split: false,
362 | format_if_needed: false,
363 | };
364 |
365 | let simple_command = "echo hello world";
366 | let complex_command = r#"
367 | if [ "$USER" = "root" ]; then
368 | echo "Running as root"
369 | for file in /etc/*.conf; do
370 | if [ -f "$file" ]; then
371 | echo "Processing $file"
372 | cat "$file" | grep -E "^[^#]" | sort
373 | fi
374 | done
375 | elif [ -n "$HOME" ]; then
376 | cd "$HOME" && ls -la
377 | else
378 | echo "Unknown user environment"
379 | fi
380 | "#;
381 |
382 | let unformatted_script = r#"
383 | function backup_files(){
384 | local source_dir="$1"
385 | local backup_dir="$2"
386 | if [ ! -d "$source_dir" ];then
387 | echo "Source directory does not exist"
388 | return 1
389 | fi
390 | mkdir -p "$backup_dir"
391 | cp -r "$source_dir"/* "$backup_dir"/
392 | }
393 | "#;
394 |
395 | group.bench_with_input(
396 | BenchmarkId::new("simple_command", simple_command.len()),
397 | &simple_command,
398 | |b, input| {
399 | b.iter(|| {
400 | let mut formatter = Formatter::with_config(config.clone());
401 | black_box(formatter.format_str(black_box(input)))
402 | })
403 | },
404 | );
405 |
406 | group.bench_with_input(
407 | BenchmarkId::new("complex_conditional", complex_command.len()),
408 | &complex_command,
409 | |b, input| {
410 | b.iter(|| {
411 | let mut formatter = Formatter::with_config(config.clone());
412 | black_box(formatter.format_str(black_box(input)))
413 | })
414 | },
415 | );
416 |
417 | group.bench_with_input(
418 | BenchmarkId::new("unformatted_script", unformatted_script.len()),
419 | &unformatted_script,
420 | |b, input| {
421 | b.iter(|| {
422 | let mut formatter = Formatter::with_config(config.clone());
423 | black_box(formatter.format_str(black_box(input)))
424 | })
425 | },
426 | );
427 |
428 | group.finish();
429 | }
430 |
431 | fn end_to_end_benchmarks(c: &mut Criterion) {
432 | let mut group = c.benchmark_group("end_to_end");
433 |
434 | let test_scripts = vec![
435 | ("simple", "echo hello && ls -la"),
436 | (
437 | "medium",
438 | r#"
439 | for i in {1..10}; do
440 | echo "Processing item $i"
441 | if [ $i -eq 5 ]; then
442 | echo "Halfway there!"
443 | fi
444 | done
445 | "#,
446 | ),
447 | (
448 | "complex",
449 | r#"
450 | #!/bin/bash
451 |
452 | function process_logs() {
453 | local log_dir="$1"
454 | local output_file="$2"
455 |
456 | if [ ! -d "$log_dir" ]; then
457 | echo "Error: Log directory '$log_dir' does not exist" >&2
458 | return 1
459 | fi
460 |
461 | echo "Processing logs in $log_dir..."
462 |
463 | find "$log_dir" -name "*.log" -type f | while read -r logfile; do
464 | echo "Processing: $logfile"
465 |
466 | # Extract errors and warnings
467 | grep -E "(ERROR|WARN)" "$logfile" | \
468 | sed 's/^/['"$(basename "$logfile")"'] /' >> "$output_file"
469 |
470 | # Count lines processed
471 | line_count=$(wc -l < "$logfile")
472 | echo "Processed $line_count lines from $(basename "$logfile")"
473 | done
474 |
475 | echo "Log processing complete. Results saved to $output_file"
476 | }
477 |
478 | # Main execution
479 | if [ $# -ne 2 ]; then
480 | echo "Usage: $0 "
481 | exit 1
482 | fi
483 |
484 | process_logs "$1" "$2"
485 | "#,
486 | ),
487 | ];
488 |
489 | for (name, script) in test_scripts {
490 | group.bench_with_input(BenchmarkId::new("lex_parse", name), &script, |b, input| {
491 | b.iter(|| {
492 | let lexer = Lexer::new(black_box(input));
493 | let mut parser = Parser::new(lexer);
494 | black_box(parser.parse_script())
495 | })
496 | });
497 |
498 | #[cfg(feature = "formatter")]
499 | group.bench_with_input(
500 | BenchmarkId::new("lex_parse_format", name),
501 | &script,
502 | |b, input| {
503 | b.iter(|| {
504 | let config = FormatterConfig {
505 | indent_str: " ".to_string(),
506 | shell_variant: ShellVariant::Bash,
507 | binary_next_line: false,
508 | switch_case_indent: true,
509 | space_redirects: true,
510 | keep_padding: false,
511 | function_next_line: false,
512 | never_split: false,
513 | format_if_needed: false,
514 | };
515 | let mut formatter = Formatter::with_config(config);
516 | black_box(formatter.format_str(black_box(input)))
517 | })
518 | },
519 | );
520 | }
521 |
522 | group.finish();
523 | }
524 |
525 | #[cfg(feature = "formatter")]
526 | criterion_group!(
527 | benches,
528 | // simd_benchmarks,
529 | // lexer_simd_benchmarks,
530 | lexer_benchmarks,
531 | parser_benchmarks,
532 | formatter_benchmarks,
533 | end_to_end_benchmarks
534 | );
535 |
536 | #[cfg(not(feature = "formatter"))]
537 | criterion_group!(
538 | benches,
539 | simd_benchmarks,
540 | lexer_simd_benchmarks,
541 | lexer_benchmarks,
542 | parser_benchmarks,
543 | end_to_end_benchmarks
544 | );
545 |
546 | criterion_main!(benches);
547 |
--------------------------------------------------------------------------------
/examples/interop.rs:
--------------------------------------------------------------------------------
1 | use flash::interpreter::Interpreter;
2 | use std::io;
3 |
4 | fn main() -> io::Result<()> {
5 | let mut interpreter = Interpreter::new();
6 | interpreter.run_interactive()?;
7 | Ok(())
8 | }
9 |
--------------------------------------------------------------------------------
/examples/parse_pkgbuild.rs:
--------------------------------------------------------------------------------
1 | use flash::lexer::Lexer;
2 | use flash::parser::Parser;
3 |
4 | fn main() {
5 | // Retired from https://gitlab.archlinux.org/archlinux/packaging/packages/rio/-/blob/main/PKGBUILD
6 | let content = "
7 | # Maintainer: Orhun Parmaksız
8 | # Maintainer: Caleb Maclennan
9 | # Contributor: bbx0 <39773919+bbx0@users.noreply.github.com>
10 | # Contributor: Raphael Amorim
11 | pkgname=rio
12 | pkgver=0.2.12
13 | pkgrel=1
14 | pkgdesc=\"A hardware-accelerated GPU terminal emulator powered by WebGPU\"
15 | arch=('x86_64')
16 | url=\"https://github.com/raphamorim/rio\"
17 | license=(\"MIT\")
18 | # https://raphamorim.io/rio/install/#arch-linux
19 | options=('!lto')
20 | depends=(
21 | 'gcc-libs'
22 | 'fontconfig'
23 | 'freetype2'
24 | 'glibc'
25 | 'hicolor-icon-theme'
26 | )
27 | makedepends=(
28 | 'cargo'
29 | 'cmake'
30 | 'desktop-file-utils'
31 | 'libxcb'
32 | 'libxkbcommon'
33 | 'python'
34 | )
35 | source=(\"${pkgname}-${pkgver}.tar.gz::${url}/archive/refs/tags/v${pkgver}.tar.gz\")
36 | sha512sums=('2a73567a591b93707a35e1658572fb48cd8dbeda4cf4418de5887183b0c90c93213b6f15ff47a50b9aaaccd295e185ebcfb594847d7ef8c9e91293740a78c493')
37 | prepare() {
38 | cd \"${pkgname}-${pkgver}\"
39 | cargo fetch --locked --target \"$(rustc -vV | sed -n 's/host: //p')\"
40 | }
41 | build() {
42 | cd \"${pkgname}-${pkgver}\"
43 | cargo build --frozen --release --all-features
44 | }
45 | check() {
46 | cd \"${pkgname}-${pkgver}\"
47 | cargo test --frozen --workspace
48 | }
49 | package() {
50 | cd \"${pkgname}-${pkgver}\"
51 | install -Dm0755 -t \"${pkgdir}/usr/bin/\" \"target/release/${pkgname}\"
52 | install -Dm0644 -t \"${pkgdir}/usr/share/doc/${pkgname}/\" \"README.md\"
53 | install -Dm0644 -t \"${pkgdir}/usr/share/licenses/${pkgname}/\" \"LICENSE\"
54 | desktop-file-install -m 644 --dir \"${pkgdir}/usr/share/applications/\" \"misc/${pkgname}.desktop\"
55 | install -Dm0644 \"docs/static/assets/${pkgname}-logo.svg\" \"$pkgdir/usr/share/icons/hicolor/scalable/apps/${pkgname}.svg\"
56 | }
57 | # vim: ts=2 sw=2 et:
58 | ";
59 |
60 | // Create a lexer for the content
61 | let lexer = Lexer::new(content);
62 |
63 | // Create a parser with the lexer
64 | let mut parser = Parser::new(lexer);
65 |
66 | // Parse the entire script
67 | let ast = parser.parse_script();
68 |
69 | println!("{:#?}", ast);
70 | }
71 |
--------------------------------------------------------------------------------
/external_echo.sh:
--------------------------------------------------------------------------------
1 | /bin/echo hello
2 |
--------------------------------------------------------------------------------
/rust-toolchain.toml:
--------------------------------------------------------------------------------
1 | [toolchain]
2 | channel = "stable"
--------------------------------------------------------------------------------
/simple.sh:
--------------------------------------------------------------------------------
1 | echo hello
2 |
--------------------------------------------------------------------------------
/src/bin.rs:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2025 Raphael Amorim
3 | *
4 | * This file is part of flash, which is licensed
5 | * under GNU General Public License v3.0.
6 | */
7 |
8 | use flash::interpreter::Interpreter;
9 | use std::env;
10 | use std::io::{self, Read};
11 |
12 | fn main() -> io::Result<()> {
13 | let mut interpreter = Interpreter::new();
14 |
15 | let args: Vec = env::args().collect();
16 |
17 | // Check if stdin is a terminal first
18 | let is_tty = unsafe { libc::isatty(0) } == 1;
19 |
20 | // If stdin is not a TTY, check for piped input first
21 | if !is_tty {
22 | // Not a terminal, read from stdin
23 | let mut input = String::new();
24 | io::stdin().read_to_string(&mut input)?;
25 |
26 | if !input.trim().is_empty() {
27 | // If there were command line arguments, treat them as script arguments
28 | if args.len() > 1 {
29 | // Set up arguments for the piped script
30 | let mut script_args = vec!["flash".to_string()]; // $0
31 | script_args.extend_from_slice(&args[1..]);
32 | interpreter.set_args(script_args);
33 | }
34 |
35 | match interpreter.execute(&input) {
36 | Ok(exit_code) => std::process::exit(exit_code),
37 | Err(e) => {
38 | eprintln!("Error: {}", e);
39 | std::process::exit(1);
40 | }
41 | }
42 | }
43 | // If no piped input but there are args, fall through to script file handling
44 | }
45 |
46 | // If there are command line arguments (other than the program name)
47 | if args.len() > 1 {
48 | // Check if it's a -c flag for direct command execution
49 | if args[1] == "-c" && args.len() > 2 {
50 | // Execute the command directly: flash -c "command"
51 | let command = &args[2];
52 | match interpreter.execute(command) {
53 | Ok(exit_code) => std::process::exit(exit_code),
54 | Err(e) => {
55 | eprintln!("Error: {}", e);
56 | std::process::exit(1);
57 | }
58 | }
59 | } else {
60 | // Assume first argument is a script file, rest are script arguments
61 | let script_path = &args[1];
62 |
63 | // Set up arguments: $0 = script path, $1 = first arg, etc.
64 | interpreter.set_args(args[1..].to_vec());
65 |
66 | // Try to read and execute the script file
67 | match std::fs::read_to_string(script_path) {
68 | Ok(script_content) => match interpreter.execute(&script_content) {
69 | Ok(exit_code) => std::process::exit(exit_code),
70 | Err(e) => {
71 | eprintln!("Error executing script {}: {}", script_path, e);
72 | std::process::exit(1);
73 | }
74 | },
75 | Err(e) => {
76 | eprintln!("Error reading script {}: {}", script_path, e);
77 | std::process::exit(1);
78 | }
79 | }
80 | }
81 | }
82 |
83 | // Interactive mode
84 | interpreter.run_interactive()?;
85 | Ok(())
86 | }
87 |
--------------------------------------------------------------------------------
/src/flash/env.rs:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2025 Raphael Amorim
3 | *
4 | * This file is part of flash, which is licensed
5 | * under GNU General Public License v3.0.
6 | */
7 |
8 | use std::collections::HashMap;
9 | // use std::ffi::CStr;
10 | // use std::os::raw::c_char;
11 | use std::{fs, io};
12 |
13 | pub fn load_env_from_proc() -> io::Result> {
14 | let mut variables = HashMap::new();
15 |
16 | // Read from /proc/self/environ (Linux/Unix only)
17 | let environ_data = fs::read("/proc/self/environ")?;
18 |
19 | // Split by null bytes and parse key=value pairs
20 | for env_pair in environ_data.split(|&b| b == 0) {
21 | if let Ok(env_str) = std::str::from_utf8(env_pair) {
22 | if let Some((key, value)) = env_str.split_once('=') {
23 | variables.insert(key.to_string(), value.to_string());
24 | }
25 | }
26 | }
27 |
28 | Ok(variables)
29 | }
30 |
31 | // unsafe extern "C" {
32 | // #[cfg(not(target_os = "windows"))]
33 | // static environ: *const *const c_char;
34 | // }
35 |
36 | // #[cfg(target_os = "windows")]
37 | // unsafe extern "C" {
38 | // fn GetEnvironmentStringsA() -> *mut c_char;
39 | // fn FreeEnvironmentStringsA(env_block: *mut c_char) -> i32;
40 | // }
41 |
42 | // pub fn load_env() -> HashMap {
43 | // let mut variables = HashMap::new();
44 |
45 | // #[cfg(not(target_os = "windows"))]
46 | // {
47 | // unsafe {
48 | // let mut env_ptr = environ;
49 | // while !(*env_ptr).is_null() {
50 | // let c_str = CStr::from_ptr(*env_ptr);
51 | // if let Ok(env_str) = c_str.to_str() {
52 | // if let Some((key, value)) = env_str.split_once('=') {
53 | // variables.insert(key.to_string(), value.to_string());
54 | // }
55 | // }
56 | // env_ptr = env_ptr.add(1);
57 | // }
58 | // }
59 | // }
60 |
61 | // #[cfg(target_os = "windows")]
62 | // {
63 | // unsafe {
64 | // let env_block = GetEnvironmentStringsA();
65 | // if !env_block.is_null() {
66 | // let mut current = env_block;
67 | // loop {
68 | // let c_str = CStr::from_ptr(current);
69 | // let bytes = c_str.to_bytes();
70 | // if bytes.is_empty() {
71 | // break;
72 | // }
73 |
74 | // if let Ok(env_str) = std::str::from_utf8(bytes) {
75 | // if let Some((key, value)) = env_str.split_once('=') {
76 | // variables.insert(key.to_string(), value.to_string());
77 | // }
78 | // }
79 |
80 | // current = current.add(bytes.len() + 1);
81 | // }
82 | // FreeEnvironmentStringsA(env_block);
83 | // }
84 | // }
85 | // }
86 |
87 | // variables
88 | // }
89 |
--------------------------------------------------------------------------------
/src/flash/mod.rs:
--------------------------------------------------------------------------------
1 | pub mod env;
2 |
--------------------------------------------------------------------------------
/src/lexer_simd.rs:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2025 Raphael Amorim
3 | *
4 | * This file is part of flash, which is licensed
5 | * under GNU General Public License v3.0.
6 | */
7 |
8 | //! SIMD-optimized lexer extensions.
9 | //!
10 | //! This module provides SIMD-accelerated versions of lexer operations
11 | //! for improved performance on large shell scripts.
12 |
13 | use crate::lexer::{Lexer, Position, Token, TokenKind};
14 | use crate::simd::{find_newline, find_quotes, find_special_chars, find_whitespace};
15 |
16 | impl Lexer {
17 | /// SIMD-optimized version of skip_whitespace.
18 | ///
19 | /// Uses vectorized operations to quickly find the next non-whitespace character.
20 | pub fn skip_whitespace_simd(&mut self) {
21 | let input = self.get_input();
22 | if input.is_empty() || self.position >= input.len() {
23 | return;
24 | }
25 |
26 | // Convert current position to byte slice for SIMD operations
27 | let input_bytes: Vec = input[self.position..].iter().map(|&c| c as u8).collect();
28 |
29 | if input_bytes.is_empty() {
30 | return;
31 | }
32 |
33 | let whitespace_pos = find_whitespace(&input_bytes, 0);
34 |
35 | if whitespace_pos == 0 {
36 | // We're at whitespace, skip it
37 | let mut chars_skipped = 0;
38 | for (i, &byte) in input_bytes.iter().enumerate() {
39 | if !matches!(byte, b' ' | b'\t' | b'\r') {
40 | chars_skipped = i;
41 | break;
42 | }
43 | if byte == b'\n' {
44 | self.increment_line();
45 | self.set_column(0);
46 | } else {
47 | self.advance_column(1);
48 | }
49 | }
50 |
51 | self.advance_position(chars_skipped);
52 | let input = self.get_input();
53 | if self.position < input.len() {
54 | self.set_ch(input[self.position]);
55 | } else {
56 | self.set_ch('\0');
57 | }
58 | }
59 | }
60 |
61 | /// SIMD-optimized word reading.
62 | ///
63 | /// Uses vectorized operations to quickly find word boundaries.
64 | pub fn read_word_simd(&mut self) -> Token {
65 | let position = Position::new(self.get_line(), self.get_column());
66 | let mut word = String::new();
67 |
68 | let input = self.get_input();
69 | if self.position >= input.len() {
70 | return Token {
71 | kind: TokenKind::EOF,
72 | value: String::new(),
73 | position,
74 | };
75 | }
76 |
77 | // Convert remaining input to bytes for SIMD processing
78 | let input_bytes: Vec = input[self.position..].iter().map(|&c| c as u8).collect();
79 |
80 | // Find the next special character or whitespace
81 | let special_pos = find_special_chars(&input_bytes, 0);
82 | let whitespace_pos = find_whitespace(&input_bytes, 0);
83 |
84 | // Take the minimum of both positions
85 | let end_pos = special_pos.min(whitespace_pos);
86 |
87 | // Extract the word
88 | for i in 0..end_pos {
89 | if self.position + i < input.len() {
90 | word.push(input[self.position + i]);
91 | }
92 | }
93 |
94 | // Advance position
95 | self.advance_position(end_pos);
96 | self.advance_column(end_pos);
97 |
98 | let input = self.get_input();
99 | if self.position < input.len() {
100 | self.set_ch(input[self.position]);
101 | } else {
102 | self.set_ch('\0');
103 | }
104 |
105 | // Check if it's a keyword
106 | let token_kind = match word.as_str() {
107 | "if" => TokenKind::If,
108 | "then" => TokenKind::Then,
109 | "elif" => TokenKind::Elif,
110 | "else" => TokenKind::Else,
111 | "fi" => TokenKind::Fi,
112 | "for" => TokenKind::For,
113 | "while" => TokenKind::While,
114 | "until" => TokenKind::Until,
115 | "do" => TokenKind::Do,
116 | "done" => TokenKind::Done,
117 | "in" => TokenKind::In,
118 | "function" => TokenKind::Function,
119 | "break" => TokenKind::Break,
120 | "continue" => TokenKind::Continue,
121 | "return" => TokenKind::Return,
122 | "export" => TokenKind::Export,
123 | _ => TokenKind::Word(word.clone()),
124 | };
125 |
126 | Token {
127 | kind: token_kind,
128 | value: word,
129 | position,
130 | }
131 | }
132 |
133 | /// SIMD-optimized comment reading.
134 | ///
135 | /// Uses vectorized operations to quickly find the end of a comment.
136 | pub fn read_comment_simd(&mut self) -> Token {
137 | let position = Position::new(self.get_line(), self.get_column());
138 | let mut comment = String::from("#");
139 |
140 | self.read_char(); // Skip the '#'
141 |
142 | let input = self.get_input();
143 | if self.position >= input.len() {
144 | return Token {
145 | kind: TokenKind::Comment,
146 | value: comment,
147 | position,
148 | };
149 | }
150 |
151 | // Convert remaining input to bytes for SIMD processing
152 | let input_bytes: Vec = input[self.position..].iter().map(|&c| c as u8).collect();
153 |
154 | // Find the next newline
155 | let newline_pos = find_newline(&input_bytes, 0);
156 |
157 | // Extract the comment content
158 | for i in 0..newline_pos {
159 | if self.position + i < input.len() {
160 | comment.push(input[self.position + i]);
161 | }
162 | }
163 |
164 | // Advance position to just before the newline
165 | self.advance_position(newline_pos);
166 | self.advance_column(newline_pos);
167 |
168 | let input = self.get_input();
169 | if self.position < input.len() {
170 | self.set_ch(input[self.position]);
171 | } else {
172 | self.set_ch('\0');
173 | }
174 |
175 | Token {
176 | kind: TokenKind::Comment,
177 | value: comment,
178 | position,
179 | }
180 | }
181 |
182 | /// SIMD-optimized quoted string reading.
183 | ///
184 | /// Uses vectorized operations to quickly find the closing quote.
185 | pub fn read_quoted_content_simd(&mut self) -> Token {
186 | let position = Position::new(self.get_line(), self.get_column());
187 | let mut content = String::new();
188 | let quote_char = self.get_ch();
189 |
190 | self.read_char(); // Skip opening quote
191 |
192 | let input = self.get_input();
193 | if self.position >= input.len() {
194 | return Token {
195 | kind: if quote_char == '"' {
196 | TokenKind::Quote
197 | } else {
198 | TokenKind::SingleQuote
199 | },
200 | value: content,
201 | position,
202 | };
203 | }
204 |
205 | // For quoted strings, we need to be careful about escape sequences
206 | // So we'll use a hybrid approach: SIMD to find potential end quotes,
207 | // then validate them manually
208 | let input_bytes: Vec = input[self.position..].iter().map(|&c| c as u8).collect();
209 |
210 | let mut search_offset = 0;
211 | loop {
212 | let quote_pos = find_quotes(&input_bytes, search_offset);
213 |
214 | if quote_pos >= input_bytes.len() {
215 | // No closing quote found, read to end
216 | for i in search_offset..input_bytes.len() {
217 | if self.position + i < input.len() {
218 | content.push(input[self.position + i]);
219 | }
220 | }
221 | self.advance_position(input_bytes.len() - search_offset);
222 | self.advance_column(input_bytes.len() - search_offset);
223 | break;
224 | }
225 |
226 | // Check if this quote matches our opening quote
227 | if input_bytes[quote_pos] == quote_char as u8 {
228 | // Check if it's escaped
229 | let mut escaped = false;
230 | if quote_pos > 0 && input_bytes[quote_pos - 1] == b'\\' {
231 | // Count consecutive backslashes
232 | let mut backslash_count = 0;
233 | let mut check_pos = quote_pos - 1;
234 | while check_pos < input_bytes.len()
235 | && input_bytes[check_pos] == b'\\'
236 | && check_pos > 0
237 | {
238 | backslash_count += 1;
239 | check_pos -= 1;
240 | }
241 | escaped = backslash_count % 2 == 1;
242 | }
243 |
244 | if !escaped {
245 | // Found unescaped closing quote
246 | for i in search_offset..quote_pos {
247 | if self.position + i < input.len() {
248 | content.push(input[self.position + i]);
249 | }
250 | }
251 | self.advance_position(quote_pos + 1); // +1 to skip the closing quote
252 | self.advance_column(quote_pos + 1);
253 | break;
254 | }
255 | }
256 |
257 | // Continue searching after this quote
258 | search_offset = quote_pos + 1;
259 | }
260 |
261 | let input = self.get_input();
262 | if self.position < input.len() {
263 | self.set_ch(input[self.position]);
264 | } else {
265 | self.set_ch('\0');
266 | }
267 |
268 | Token {
269 | kind: TokenKind::Word(content.clone()), // Use Word instead of StringLiteral
270 | value: content,
271 | position,
272 | }
273 | }
274 |
275 | /// SIMD-optimized next token method.
276 | ///
277 | /// Uses vectorized operations where possible to accelerate tokenization.
278 | pub fn next_token_simd(&mut self) -> Token {
279 | // Skip whitespace using SIMD
280 | self.skip_whitespace_simd();
281 |
282 | if self.get_ch() == '\0' {
283 | return Token {
284 | kind: TokenKind::EOF,
285 | value: String::new(),
286 | position: Position::new(self.get_line(), self.get_column()),
287 | };
288 | }
289 |
290 | // Handle common cases with SIMD optimizations
291 | match self.get_ch() {
292 | '#' => self.read_comment_simd(),
293 | '"' | '\'' => self.read_quoted_content_simd(),
294 | _ if self.get_ch().is_alphabetic() || self.get_ch() == '_' => self.read_word_simd(),
295 | _ => {
296 | // Fall back to regular tokenization for special characters
297 | self.next_token()
298 | }
299 | }
300 | }
301 | }
302 |
303 | #[cfg(test)]
304 | mod tests {
305 | use super::*;
306 |
307 | #[test]
308 | fn test_simd_word_reading() {
309 | let mut lexer = Lexer::new("hello world");
310 | let token = lexer.read_word_simd();
311 | assert_eq!(token.kind, TokenKind::Word("hello".to_string()));
312 | assert_eq!(token.value, "hello");
313 | }
314 |
315 | #[test]
316 | fn test_simd_keyword_detection() {
317 | let mut lexer = Lexer::new("if then else fi");
318 | let token1 = lexer.read_word_simd();
319 | assert_eq!(token1.kind, TokenKind::If);
320 |
321 | lexer.skip_whitespace_simd();
322 | let token2 = lexer.read_word_simd();
323 | assert_eq!(token2.kind, TokenKind::Then);
324 | }
325 |
326 | #[test]
327 | fn test_simd_comment_reading() {
328 | let mut lexer = Lexer::new("# This is a comment\necho hello");
329 | let token = lexer.read_comment_simd();
330 | assert_eq!(token.kind, TokenKind::Comment);
331 | assert_eq!(token.value, "# This is a comment");
332 | }
333 |
334 | #[test]
335 | fn test_simd_quoted_string() {
336 | let mut lexer = Lexer::new("\"hello world\"");
337 | lexer.read_char(); // Move to the quote
338 | let token = lexer.read_quoted_content_simd();
339 | assert_eq!(token.kind, TokenKind::Word("hello world".to_string()));
340 | }
341 |
342 | #[test]
343 | fn test_simd_next_token() {
344 | let mut lexer = Lexer::new("echo \"hello\" # comment");
345 |
346 | let token1 = lexer.next_token_simd();
347 | assert_eq!(token1.kind, TokenKind::Word("echo".to_string()));
348 |
349 | let token2 = lexer.next_token_simd();
350 | assert_eq!(token2.kind, TokenKind::Quote);
351 |
352 | let token3 = lexer.next_token_simd();
353 | assert_eq!(token3.kind, TokenKind::Word("hello".to_string()));
354 | }
355 |
356 | #[test]
357 | fn test_simd_performance_large_input() {
358 | let large_input = "echo hello world ".repeat(1000);
359 | let mut lexer = Lexer::new(&large_input);
360 |
361 | let mut token_count = 0;
362 | loop {
363 | let token = lexer.next_token_simd();
364 | if token.kind == TokenKind::EOF {
365 | break;
366 | }
367 | token_count += 1;
368 | }
369 |
370 | assert!(token_count > 0);
371 | }
372 | }
373 |
--------------------------------------------------------------------------------
/src/lib.rs:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2025 Raphael Amorim
3 | *
4 | * This file is part of flash, which is licensed
5 | * under GNU General Public License v3.0.
6 | */
7 |
8 | pub mod lexer;
9 | pub mod parser;
10 |
11 | // mod lexer_simd;
12 | // mod simd;
13 |
14 | #[cfg(feature = "interpreter")]
15 | mod flash;
16 | #[cfg(feature = "formatter")]
17 | pub mod formatter;
18 | #[cfg(feature = "interpreter")]
19 | pub mod interpreter;
20 |
--------------------------------------------------------------------------------
/src/simd.rs:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2025 Raphael Amorim
3 | *
4 | * This file is part of flash, which is licensed
5 | * under GNU General Public License v3.0.
6 | */
7 |
8 | //! SIMD optimizations for lexer and parser operations.
9 | //!
10 | //! This module provides vectorized implementations for common operations
11 | //! like finding special characters, whitespace, and keywords in shell scripts.
12 |
13 | use std::ptr;
14 |
15 | /// Find the first occurrence of any character in a set of needles.
16 | ///
17 | /// Returns the index of the first occurrence, or `haystack.len()` if not found.
18 | /// This is optimized for finding shell special characters like quotes, operators, etc.
19 | pub fn find_special_chars(haystack: &[u8], offset: usize) -> usize {
20 | unsafe {
21 | let beg = haystack.as_ptr();
22 | let end = beg.add(haystack.len());
23 | let it = beg.add(offset.min(haystack.len()));
24 | let it = find_special_chars_raw(it, end);
25 | it.offset_from_unsigned(beg)
26 | }
27 | }
28 |
29 | /// Find the first occurrence of whitespace characters.
30 | ///
31 | /// Returns the index of the first whitespace, or `haystack.len()` if not found.
32 | pub fn find_whitespace(haystack: &[u8], offset: usize) -> usize {
33 | unsafe {
34 | let beg = haystack.as_ptr();
35 | let end = beg.add(haystack.len());
36 | let it = beg.add(offset.min(haystack.len()));
37 | let it = find_whitespace_raw(it, end);
38 | it.offset_from_unsigned(beg)
39 | }
40 | }
41 |
42 | /// Find the first occurrence of quote characters (' or ").
43 | ///
44 | /// Returns the index of the first quote, or `haystack.len()` if not found.
45 | pub fn find_quotes(haystack: &[u8], offset: usize) -> usize {
46 | unsafe {
47 | let beg = haystack.as_ptr();
48 | let end = beg.add(haystack.len());
49 | let it = beg.add(offset.min(haystack.len()));
50 | let it = find_quotes_raw(it, end);
51 | it.offset_from_unsigned(beg)
52 | }
53 | }
54 |
55 | /// Find the first occurrence of newline characters.
56 | ///
57 | /// Returns the index of the first newline, or `haystack.len()` if not found.
58 | pub fn find_newline(haystack: &[u8], offset: usize) -> usize {
59 | unsafe {
60 | let beg = haystack.as_ptr();
61 | let end = beg.add(haystack.len());
62 | let it = beg.add(offset.min(haystack.len()));
63 | let it = find_newline_raw(it, end);
64 | it.offset_from_unsigned(beg)
65 | }
66 | }
67 |
68 | unsafe fn find_special_chars_raw(beg: *const u8, end: *const u8) -> *const u8 {
69 | #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
70 | return unsafe { SPECIAL_CHARS_DISPATCH(beg, end) };
71 |
72 | #[cfg(target_arch = "aarch64")]
73 | return unsafe { find_special_chars_neon(beg, end) };
74 |
75 | #[allow(unreachable_code)]
76 | return unsafe { find_special_chars_fallback(beg, end) };
77 | }
78 |
79 | unsafe fn find_whitespace_raw(beg: *const u8, end: *const u8) -> *const u8 {
80 | #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
81 | return unsafe { WHITESPACE_DISPATCH(beg, end) };
82 |
83 | #[cfg(target_arch = "aarch64")]
84 | return unsafe { find_whitespace_neon(beg, end) };
85 |
86 | #[allow(unreachable_code)]
87 | return unsafe { find_whitespace_fallback(beg, end) };
88 | }
89 |
90 | unsafe fn find_quotes_raw(beg: *const u8, end: *const u8) -> *const u8 {
91 | #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
92 | return unsafe { QUOTES_DISPATCH(beg, end) };
93 |
94 | #[cfg(target_arch = "aarch64")]
95 | return unsafe { find_quotes_neon(beg, end) };
96 |
97 | #[allow(unreachable_code)]
98 | return unsafe { find_quotes_fallback(beg, end) };
99 | }
100 |
101 | unsafe fn find_newline_raw(beg: *const u8, end: *const u8) -> *const u8 {
102 | // Simple case - just look for '\n'
103 | unsafe {
104 | let mut it = beg;
105 | while !ptr::eq(it, end) {
106 | if *it == b'\n' {
107 | break;
108 | }
109 | it = it.add(1);
110 | }
111 | it
112 | }
113 | }
114 |
115 | // Fallback implementations
116 | unsafe fn find_special_chars_fallback(mut beg: *const u8, end: *const u8) -> *const u8 {
117 | unsafe {
118 | while !ptr::eq(beg, end) {
119 | let ch = *beg;
120 | // Shell special characters: | & ; ( ) < > $ " ' ` # = ! { } \
121 | if matches!(
122 | ch,
123 | b'|' | b'&'
124 | | b';'
125 | | b'('
126 | | b')'
127 | | b'<'
128 | | b'>'
129 | | b'$'
130 | | b'"'
131 | | b'\''
132 | | b'`'
133 | | b'#'
134 | | b'='
135 | | b'!'
136 | | b'{'
137 | | b'}'
138 | | b'\\'
139 | ) {
140 | break;
141 | }
142 | beg = beg.add(1);
143 | }
144 | beg
145 | }
146 | }
147 |
148 | unsafe fn find_whitespace_fallback(mut beg: *const u8, end: *const u8) -> *const u8 {
149 | unsafe {
150 | while !ptr::eq(beg, end) {
151 | let ch = *beg;
152 | if matches!(ch, b' ' | b'\t' | b'\n' | b'\r') {
153 | break;
154 | }
155 | beg = beg.add(1);
156 | }
157 | beg
158 | }
159 | }
160 |
161 | unsafe fn find_quotes_fallback(mut beg: *const u8, end: *const u8) -> *const u8 {
162 | unsafe {
163 | while !ptr::eq(beg, end) {
164 | let ch = *beg;
165 | if ch == b'"' || ch == b'\'' {
166 | break;
167 | }
168 | beg = beg.add(1);
169 | }
170 | beg
171 | }
172 | }
173 |
174 | // x86/x86_64 SIMD implementations
175 | #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
176 | static mut SPECIAL_CHARS_DISPATCH: unsafe fn(*const u8, *const u8) -> *const u8 =
177 | special_chars_dispatch;
178 |
179 | #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
180 | static mut WHITESPACE_DISPATCH: unsafe fn(*const u8, *const u8) -> *const u8 = whitespace_dispatch;
181 |
182 | #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
183 | static mut QUOTES_DISPATCH: unsafe fn(*const u8, *const u8) -> *const u8 = quotes_dispatch;
184 |
185 | #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
186 | unsafe fn special_chars_dispatch(beg: *const u8, end: *const u8) -> *const u8 {
187 | let func = if is_x86_feature_detected!("avx2") {
188 | find_special_chars_avx2
189 | } else {
190 | find_special_chars_fallback
191 | };
192 | unsafe { SPECIAL_CHARS_DISPATCH = func };
193 | unsafe { func(beg, end) }
194 | }
195 |
196 | #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
197 | unsafe fn whitespace_dispatch(beg: *const u8, end: *const u8) -> *const u8 {
198 | let func = if is_x86_feature_detected!("avx2") {
199 | find_whitespace_avx2
200 | } else {
201 | find_whitespace_fallback
202 | };
203 | unsafe { WHITESPACE_DISPATCH = func };
204 | unsafe { func(beg, end) }
205 | }
206 |
207 | #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
208 | unsafe fn quotes_dispatch(beg: *const u8, end: *const u8) -> *const u8 {
209 | let func = if is_x86_feature_detected!("avx2") {
210 | find_quotes_avx2
211 | } else {
212 | find_quotes_fallback
213 | };
214 | unsafe { QUOTES_DISPATCH = func };
215 | unsafe { func(beg, end) }
216 | }
217 |
218 | #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
219 | #[target_feature(enable = "avx2")]
220 | unsafe fn find_special_chars_avx2(mut beg: *const u8, end: *const u8) -> *const u8 {
221 | unsafe {
222 | #[cfg(target_arch = "x86")]
223 | use std::arch::x86::*;
224 | #[cfg(target_arch = "x86_64")]
225 | use std::arch::x86_64::*;
226 |
227 | let mut remaining = end.offset_from_unsigned(beg);
228 |
229 | // Check for common special characters in groups
230 | let pipe_amp = _mm256_set1_epi8(b'|' as i8);
231 | let semicolon = _mm256_set1_epi8(b';' as i8);
232 | let paren_open = _mm256_set1_epi8(b'(' as i8);
233 | let paren_close = _mm256_set1_epi8(b')' as i8);
234 | let less_than = _mm256_set1_epi8(b'<' as i8);
235 | let greater_than = _mm256_set1_epi8(b'>' as i8);
236 | let dollar = _mm256_set1_epi8(b'$' as i8);
237 | let double_quote = _mm256_set1_epi8(b'"' as i8);
238 | let single_quote = _mm256_set1_epi8(b'\'' as i8);
239 | let backtick = _mm256_set1_epi8(b'`' as i8);
240 | let hash = _mm256_set1_epi8(b'#' as i8);
241 | let equals = _mm256_set1_epi8(b'=' as i8);
242 | let exclamation = _mm256_set1_epi8(b'!' as i8);
243 | let brace_open = _mm256_set1_epi8(b'{' as i8);
244 | let brace_close = _mm256_set1_epi8(b'}' as i8);
245 | let backslash = _mm256_set1_epi8(b'\\' as i8);
246 | let ampersand = _mm256_set1_epi8(b'&' as i8);
247 |
248 | while remaining >= 32 {
249 | let v = _mm256_loadu_si256(beg as *const _);
250 |
251 | // Check for all special characters
252 | let match1 = _mm256_or_si256(
253 | _mm256_or_si256(
254 | _mm256_cmpeq_epi8(v, pipe_amp),
255 | _mm256_cmpeq_epi8(v, ampersand),
256 | ),
257 | _mm256_or_si256(
258 | _mm256_cmpeq_epi8(v, semicolon),
259 | _mm256_cmpeq_epi8(v, paren_open),
260 | ),
261 | );
262 |
263 | let match2 = _mm256_or_si256(
264 | _mm256_or_si256(
265 | _mm256_cmpeq_epi8(v, paren_close),
266 | _mm256_cmpeq_epi8(v, less_than),
267 | ),
268 | _mm256_or_si256(
269 | _mm256_cmpeq_epi8(v, greater_than),
270 | _mm256_cmpeq_epi8(v, dollar),
271 | ),
272 | );
273 |
274 | let match3 = _mm256_or_si256(
275 | _mm256_or_si256(
276 | _mm256_cmpeq_epi8(v, double_quote),
277 | _mm256_cmpeq_epi8(v, single_quote),
278 | ),
279 | _mm256_or_si256(_mm256_cmpeq_epi8(v, backtick), _mm256_cmpeq_epi8(v, hash)),
280 | );
281 |
282 | let match4 = _mm256_or_si256(
283 | _mm256_or_si256(
284 | _mm256_cmpeq_epi8(v, equals),
285 | _mm256_cmpeq_epi8(v, exclamation),
286 | ),
287 | _mm256_or_si256(
288 | _mm256_cmpeq_epi8(v, brace_open),
289 | _mm256_cmpeq_epi8(v, brace_close),
290 | ),
291 | );
292 |
293 | let final_match = _mm256_or_si256(
294 | _mm256_or_si256(match1, match2),
295 | _mm256_or_si256(
296 | _mm256_or_si256(match3, match4),
297 | _mm256_cmpeq_epi8(v, backslash),
298 | ),
299 | );
300 |
301 | let m = _mm256_movemask_epi8(final_match) as u32;
302 |
303 | if m != 0 {
304 | return beg.add(m.trailing_zeros() as usize);
305 | }
306 |
307 | beg = beg.add(32);
308 | remaining -= 32;
309 | }
310 |
311 | find_special_chars_fallback(beg, end)
312 | }
313 | }
314 |
315 | #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
316 | #[target_feature(enable = "avx2")]
317 | unsafe fn find_whitespace_avx2(mut beg: *const u8, end: *const u8) -> *const u8 {
318 | unsafe {
319 | #[cfg(target_arch = "x86")]
320 | use std::arch::x86::*;
321 | #[cfg(target_arch = "x86_64")]
322 | use std::arch::x86_64::*;
323 |
324 | let space = _mm256_set1_epi8(b' ' as i8);
325 | let tab = _mm256_set1_epi8(b'\t' as i8);
326 | let newline = _mm256_set1_epi8(b'\n' as i8);
327 | let carriage_return = _mm256_set1_epi8(b'\r' as i8);
328 | let mut remaining = end.offset_from_unsigned(beg);
329 |
330 | while remaining >= 32 {
331 | let v = _mm256_loadu_si256(beg as *const _);
332 | let a = _mm256_cmpeq_epi8(v, space);
333 | let b = _mm256_cmpeq_epi8(v, tab);
334 | let c = _mm256_cmpeq_epi8(v, newline);
335 | let d = _mm256_cmpeq_epi8(v, carriage_return);
336 | let result = _mm256_or_si256(_mm256_or_si256(a, b), _mm256_or_si256(c, d));
337 | let m = _mm256_movemask_epi8(result) as u32;
338 |
339 | if m != 0 {
340 | return beg.add(m.trailing_zeros() as usize);
341 | }
342 |
343 | beg = beg.add(32);
344 | remaining -= 32;
345 | }
346 |
347 | find_whitespace_fallback(beg, end)
348 | }
349 | }
350 |
351 | #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
352 | #[target_feature(enable = "avx2")]
353 | unsafe fn find_quotes_avx2(mut beg: *const u8, end: *const u8) -> *const u8 {
354 | unsafe {
355 | #[cfg(target_arch = "x86")]
356 | use std::arch::x86::*;
357 | #[cfg(target_arch = "x86_64")]
358 | use std::arch::x86_64::*;
359 |
360 | let double_quote = _mm256_set1_epi8(b'"' as i8);
361 | let single_quote = _mm256_set1_epi8(b'\'' as i8);
362 | let mut remaining = end.offset_from_unsigned(beg);
363 |
364 | while remaining >= 32 {
365 | let v = _mm256_loadu_si256(beg as *const _);
366 | let a = _mm256_cmpeq_epi8(v, double_quote);
367 | let b = _mm256_cmpeq_epi8(v, single_quote);
368 | let c = _mm256_or_si256(a, b);
369 | let m = _mm256_movemask_epi8(c) as u32;
370 |
371 | if m != 0 {
372 | return beg.add(m.trailing_zeros() as usize);
373 | }
374 |
375 | beg = beg.add(32);
376 | remaining -= 32;
377 | }
378 |
379 | find_quotes_fallback(beg, end)
380 | }
381 | }
382 |
383 | // ARM NEON implementations
384 | #[cfg(target_arch = "aarch64")]
385 | unsafe fn find_special_chars_neon(mut beg: *const u8, end: *const u8) -> *const u8 {
386 | unsafe {
387 | use std::arch::aarch64::*;
388 |
389 | if end.offset_from_unsigned(beg) >= 16 {
390 | // For NEON, we'll check for the most common special characters
391 | let pipe = vdupq_n_u8(b'|');
392 | let amp = vdupq_n_u8(b'&');
393 | let semicolon = vdupq_n_u8(b';');
394 | let dollar = vdupq_n_u8(b'$');
395 | let double_quote = vdupq_n_u8(b'"');
396 | let single_quote = vdupq_n_u8(b'\'');
397 |
398 | loop {
399 | let v = vld1q_u8(beg as *const _);
400 |
401 | let match1 = vorrq_u8(vceqq_u8(v, pipe), vceqq_u8(v, amp));
402 | let match2 = vorrq_u8(vceqq_u8(v, semicolon), vceqq_u8(v, dollar));
403 | let match3 = vorrq_u8(vceqq_u8(v, double_quote), vceqq_u8(v, single_quote));
404 |
405 | let final_match = vorrq_u8(vorrq_u8(match1, match2), match3);
406 |
407 | // Convert to bitmask
408 | let m = vreinterpretq_u16_u8(final_match);
409 | let m = vshrn_n_u16(m, 4);
410 | let m = vreinterpret_u64_u8(m);
411 | let m = vget_lane_u64(m, 0);
412 |
413 | if m != 0 {
414 | return beg.add(m.trailing_zeros() as usize >> 2);
415 | }
416 |
417 | beg = beg.add(16);
418 | if end.offset_from_unsigned(beg) < 16 {
419 | break;
420 | }
421 | }
422 | }
423 |
424 | find_special_chars_fallback(beg, end)
425 | }
426 | }
427 |
428 | #[cfg(target_arch = "aarch64")]
429 | unsafe fn find_whitespace_neon(mut beg: *const u8, end: *const u8) -> *const u8 {
430 | unsafe {
431 | use std::arch::aarch64::*;
432 |
433 | if end.offset_from_unsigned(beg) >= 16 {
434 | let space = vdupq_n_u8(b' ');
435 | let tab = vdupq_n_u8(b'\t');
436 | let newline = vdupq_n_u8(b'\n');
437 | let carriage_return = vdupq_n_u8(b'\r');
438 |
439 | loop {
440 | let v = vld1q_u8(beg as *const _);
441 | let a = vceqq_u8(v, space);
442 | let b = vceqq_u8(v, tab);
443 | let c = vceqq_u8(v, newline);
444 | let d = vceqq_u8(v, carriage_return);
445 | let result = vorrq_u8(vorrq_u8(a, b), vorrq_u8(c, d));
446 |
447 | let m = vreinterpretq_u16_u8(result);
448 | let m = vshrn_n_u16(m, 4);
449 | let m = vreinterpret_u64_u8(m);
450 | let m = vget_lane_u64(m, 0);
451 |
452 | if m != 0 {
453 | return beg.add(m.trailing_zeros() as usize >> 2);
454 | }
455 |
456 | beg = beg.add(16);
457 | if end.offset_from_unsigned(beg) < 16 {
458 | break;
459 | }
460 | }
461 | }
462 |
463 | find_whitespace_fallback(beg, end)
464 | }
465 | }
466 |
467 | #[cfg(target_arch = "aarch64")]
468 | unsafe fn find_quotes_neon(mut beg: *const u8, end: *const u8) -> *const u8 {
469 | unsafe {
470 | use std::arch::aarch64::*;
471 |
472 | if end.offset_from_unsigned(beg) >= 16 {
473 | let double_quote = vdupq_n_u8(b'"');
474 | let single_quote = vdupq_n_u8(b'\'');
475 |
476 | loop {
477 | let v = vld1q_u8(beg as *const _);
478 | let a = vceqq_u8(v, double_quote);
479 | let b = vceqq_u8(v, single_quote);
480 | let c = vorrq_u8(a, b);
481 |
482 | let m = vreinterpretq_u16_u8(c);
483 | let m = vshrn_n_u16(m, 4);
484 | let m = vreinterpret_u64_u8(m);
485 | let m = vget_lane_u64(m, 0);
486 |
487 | if m != 0 {
488 | return beg.add(m.trailing_zeros() as usize >> 2);
489 | }
490 |
491 | beg = beg.add(16);
492 | if end.offset_from_unsigned(beg) < 16 {
493 | break;
494 | }
495 | }
496 | }
497 |
498 | find_quotes_fallback(beg, end)
499 | }
500 | }
501 |
502 | /// Extension trait to add offset_from_unsigned method for compatibility
503 | trait OffsetFromUnsigned {
504 | fn offset_from_unsigned(self, origin: *const T) -> usize;
505 | }
506 |
507 | impl OffsetFromUnsigned for *const T {
508 | fn offset_from_unsigned(self, origin: *const T) -> usize {
509 | (self as usize - origin as usize) / std::mem::size_of::()
510 | }
511 | }
512 |
513 | #[cfg(test)]
514 | mod tests {
515 | use super::*;
516 |
517 | #[test]
518 | fn test_find_special_chars() {
519 | let input = b"hello world | grep test";
520 | assert_eq!(find_special_chars(input, 0), 12); // Position of '|'
521 |
522 | let input = b"echo $VAR";
523 | assert_eq!(find_special_chars(input, 0), 5); // Position of '$'
524 |
525 | let input = b"no special chars here";
526 | assert_eq!(find_special_chars(input, 0), input.len());
527 | }
528 |
529 | #[test]
530 | fn test_find_whitespace() {
531 | let input = b"hello world";
532 | assert_eq!(find_whitespace(input, 0), 5); // Position of space
533 |
534 | let input = b"hello\tworld";
535 | assert_eq!(find_whitespace(input, 0), 5); // Position of tab
536 |
537 | let input = b"nospaces";
538 | assert_eq!(find_whitespace(input, 0), input.len());
539 | }
540 |
541 | #[test]
542 | fn test_find_quotes() {
543 | let input = b"echo 'hello world'";
544 | assert_eq!(find_quotes(input, 0), 5); // Position of first quote
545 |
546 | let input = b"echo \"hello world\"";
547 | assert_eq!(find_quotes(input, 0), 5); // Position of first quote
548 |
549 | let input = b"no quotes here";
550 | assert_eq!(find_quotes(input, 0), input.len());
551 | }
552 |
553 | #[test]
554 | fn test_find_newline() {
555 | let input = b"line1\nline2";
556 | assert_eq!(find_newline(input, 0), 5); // Position of newline
557 |
558 | let input = b"no newline here";
559 | assert_eq!(find_newline(input, 0), input.len());
560 | }
561 |
562 | #[test]
563 | fn test_with_offset() {
564 | let input = b"echo 'hello' | grep 'world'";
565 | assert_eq!(find_quotes(input, 0), 5); // First quote
566 | assert_eq!(find_quotes(input, 6), 11); // Second quote (after offset)
567 | assert_eq!(find_special_chars(input, 0), 5); // First special char (quote)
568 | assert_eq!(find_special_chars(input, 12), 13); // Pipe after offset
569 | }
570 | }
571 |
--------------------------------------------------------------------------------
/test_debug.rs:
--------------------------------------------------------------------------------
1 | #[cfg(test)]
2 | mod tests {
3 | use crate::lexer::Lexer;
4 | use crate::parser::Parser;
5 | use crate::formatter::Formatter;
6 |
7 | #[test]
8 | fn debug_brace_expansion() {
9 | let input = "echo {1..5}";
10 | println!("Input: {}", input);
11 |
12 | let lexer = Lexer::new(input);
13 | let mut parser = Parser::new(lexer);
14 | let result = parser.parse_script();
15 |
16 | println!("Parsed result: {:#?}", result);
17 |
18 | let mut formatter = Formatter::new();
19 | let output = formatter.format(&result);
20 | println!("Formatted output: {}", output);
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/test_if_functionality.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # Test script for if/elif/else functionality in Flash shell
4 | # This script tests various conditional constructs
5 |
6 | set -e
7 |
8 | # Find the flash binary, handling cross-compilation
9 | find_flash_binary() {
10 | # First try the target-specific path (for cross-compilation)
11 | if [ -n "$CARGO_BUILD_TARGET" ]; then
12 | local target_path="./target/$CARGO_BUILD_TARGET/release/flash"
13 | if [ -f "$target_path" ]; then
14 | echo "$target_path"
15 | return
16 | fi
17 | fi
18 |
19 | # Fall back to the default path
20 | local default_path="./target/release/flash"
21 | if [ -f "$default_path" ]; then
22 | echo "$default_path"
23 | return
24 | fi
25 |
26 | # Try to find any flash binary in target directories
27 | for dir in ./target/*/release; do
28 | if [ -f "$dir/flash" ]; then
29 | echo "$dir/flash"
30 | return
31 | fi
32 | done
33 |
34 | # Last resort: return the default path
35 | echo "$default_path"
36 | }
37 |
38 | FLASH_BINARY=$(find_flash_binary)
39 |
40 | if [ ! -f "$FLASH_BINARY" ]; then
41 | echo "Error: Flash binary not found at $FLASH_BINARY"
42 | echo "Available binaries:"
43 | find ./target -name "flash" -type f 2>/dev/null || echo "No flash binaries found"
44 | exit 1
45 | fi
46 |
47 | echo "Testing if/elif/else functionality with binary: $FLASH_BINARY"
48 |
49 | # Test 1: Simple if statement
50 | echo "Test 1: Simple if statement"
51 | result=$($FLASH_BINARY -c 'if [ "hello" = "hello" ]; then echo "success"; fi')
52 | if [ "$result" != "success" ]; then
53 | echo "FAIL: Simple if statement failed"
54 | exit 1
55 | fi
56 | echo "PASS: Simple if statement"
57 |
58 | # Test 2: If-else statement
59 | echo "Test 2: If-else statement"
60 | result=$($FLASH_BINARY -c 'if [ "hello" = "world" ]; then echo "fail"; else echo "success"; fi')
61 | if [ "$result" != "success" ]; then
62 | echo "FAIL: If-else statement failed"
63 | exit 1
64 | fi
65 | echo "PASS: If-else statement"
66 |
67 | # Test 3: If-elif-else statement
68 | echo "Test 3: If-elif-else statement"
69 | result=$($FLASH_BINARY -c 'if [ "1" = "2" ]; then echo "fail1"; elif [ "2" = "2" ]; then echo "success"; else echo "fail2"; fi')
70 | if [ "$result" != "success" ]; then
71 | echo "FAIL: If-elif-else statement failed"
72 | exit 1
73 | fi
74 | echo "PASS: If-elif-else statement"
75 |
76 | # Test 4: Multiple elif branches
77 | echo "Test 4: Multiple elif branches"
78 | result=$($FLASH_BINARY -c 'if [ "1" = "2" ]; then echo "fail1"; elif [ "2" = "3" ]; then echo "fail2"; elif [ "3" = "3" ]; then echo "success"; else echo "fail3"; fi')
79 | if [ "$result" != "success" ]; then
80 | echo "FAIL: Multiple elif branches failed"
81 | exit 1
82 | fi
83 | echo "PASS: Multiple elif branches"
84 |
85 | # Test 5: Nested if statements
86 | echo "Test 5: Nested if statements"
87 | result=$($FLASH_BINARY -c 'if [ "1" = "1" ]; then if [ "2" = "2" ]; then echo "success"; fi; fi')
88 | if [ "$result" != "success" ]; then
89 | echo "FAIL: Nested if statements failed"
90 | exit 1
91 | fi
92 | echo "PASS: Nested if statements"
93 |
94 | echo "All if/elif/else tests passed!"
--------------------------------------------------------------------------------
/tests/function_tests.rs:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2025 Raphael Amorim
3 | *
4 | * This file is part of flash, which is licensed
5 | * under GNU General Public License v3.0.
6 | */
7 |
8 | use flash::interpreter::{DefaultEvaluator, Interpreter};
9 | use flash::lexer::Lexer;
10 | use flash::parser::{Node, Parser};
11 | use std::io;
12 |
13 | fn execute_script(script: &str) -> Result {
14 | let mut interpreter = Interpreter::new();
15 | let mut evaluator = DefaultEvaluator;
16 | interpreter.execute_with_evaluator(script, &mut evaluator)
17 | }
18 |
19 | fn parse_script(script: &str) -> Node {
20 | let lexer = Lexer::new(script);
21 | let mut parser = Parser::new(lexer);
22 | parser.parse_script()
23 | }
24 |
25 | #[test]
26 | fn test_function_definition_with_keyword() {
27 | let script = "function greet() { echo hello; }";
28 | let result = execute_script(script);
29 | assert!(result.is_ok());
30 | assert_eq!(result.unwrap(), 0);
31 | }
32 |
33 | #[test]
34 | fn test_function_definition_without_keyword() {
35 | let script = "greet() { echo hello; }";
36 | let result = execute_script(script);
37 | assert!(result.is_ok());
38 | assert_eq!(result.unwrap(), 0);
39 | }
40 |
41 | #[test]
42 | fn test_function_call() {
43 | let script = r#"
44 | greet() { echo "Hello, World!"; }
45 | greet
46 | "#;
47 | let result = execute_script(script);
48 | assert!(result.is_ok());
49 | assert_eq!(result.unwrap(), 0);
50 | }
51 |
52 | #[test]
53 | fn test_function_with_arguments() {
54 | let script = r#"
55 | greet() { echo "Hello, $1!"; }
56 | greet Alice
57 | "#;
58 | let result = execute_script(script);
59 | assert!(result.is_ok());
60 | assert_eq!(result.unwrap(), 0);
61 | }
62 |
63 | #[test]
64 | fn test_function_with_multiple_arguments() {
65 | let script = r#"
66 | greet() { echo "Hello, $1 $2!"; }
67 | greet Alice Bob
68 | "#;
69 | let result = execute_script(script);
70 | assert!(result.is_ok());
71 | assert_eq!(result.unwrap(), 0);
72 | }
73 |
74 | #[test]
75 | fn test_function_with_return_value() {
76 | let script = r#"
77 | add() {
78 | echo "Adding $1 and $2"
79 | return 5
80 | }
81 | add 5 3
82 | "#;
83 | let result = execute_script(script);
84 | assert!(result.is_ok());
85 | assert_eq!(result.unwrap(), 5);
86 | }
87 |
88 | #[test]
89 | fn test_function_with_return_no_value() {
90 | let script = r#"
91 | test_func() {
92 | echo "doing something"
93 | return
94 | echo "this should not print"
95 | }
96 | test_func
97 | "#;
98 | let result = execute_script(script);
99 | assert!(result.is_ok());
100 | assert_eq!(result.unwrap(), 0);
101 | }
102 |
103 | #[test]
104 | fn test_function_with_return_explicit_value() {
105 | let script = r#"
106 | test_func() {
107 | echo "doing something"
108 | return 42
109 | }
110 | test_func
111 | "#;
112 | let result = execute_script(script);
113 | assert!(result.is_ok());
114 | assert_eq!(result.unwrap(), 42);
115 | }
116 |
117 | #[test]
118 | fn test_function_positional_parameters() {
119 | let script = r#"
120 | show_args() {
121 | echo "Number of args: $#"
122 | echo "All args: $@"
123 | echo "First arg: $1"
124 | echo "Second arg: $2"
125 | }
126 | show_args one two three
127 | "#;
128 | let result = execute_script(script);
129 | assert!(result.is_ok());
130 | assert_eq!(result.unwrap(), 0);
131 | }
132 |
133 | #[test]
134 | fn test_nested_function_calls() {
135 | let script = r#"
136 | inner() { echo "inner: $1"; return 1; }
137 | outer() {
138 | echo "outer: $1"
139 | inner "from outer"
140 | return 2
141 | }
142 | outer "test"
143 | "#;
144 | let result = execute_script(script);
145 | assert!(result.is_ok());
146 | assert_eq!(result.unwrap(), 2);
147 | }
148 |
149 | #[test]
150 | fn test_function_local_variables() {
151 | let script = r#"
152 | test_func() {
153 | local_var="inside function"
154 | echo $local_var
155 | }
156 | local_var="outside function"
157 | test_func
158 | echo $local_var
159 | "#;
160 | let result = execute_script(script);
161 | assert!(result.is_ok());
162 | assert_eq!(result.unwrap(), 0);
163 | }
164 |
165 | #[test]
166 | fn test_function_with_conditionals() {
167 | let script = r#"
168 | check_number() {
169 | if [ $1 -gt 10 ]; then
170 | echo "big number"
171 | return 1
172 | else
173 | echo "small number"
174 | return 0
175 | fi
176 | }
177 | check_number 5
178 | "#;
179 | let result = execute_script(script);
180 | assert!(result.is_ok());
181 | assert_eq!(result.unwrap(), 0);
182 | }
183 |
184 | #[test]
185 | fn test_function_with_loops() {
186 | let script = "count_to() { echo \"Counting to $1\"; return 3; }; count_to 3";
187 | let result = execute_script(script);
188 | assert!(result.is_ok());
189 | assert_eq!(result.unwrap(), 3);
190 | }
191 |
192 | #[test]
193 | fn test_function_redefinition() {
194 | let script = r#"
195 | test_func() { echo "first version"; return 1; }
196 | test_func() { echo "second version"; return 2; }
197 | test_func
198 | "#;
199 | let result = execute_script(script);
200 | assert!(result.is_ok());
201 | assert_eq!(result.unwrap(), 2);
202 | }
203 |
204 | #[test]
205 | fn test_function_parsing_with_keyword() {
206 | let script = "function greet() { echo hello; }";
207 | let ast = parse_script(script);
208 |
209 | match ast {
210 | Node::List { statements, .. } => {
211 | assert_eq!(statements.len(), 1);
212 | match &statements[0] {
213 | Node::Function { name, .. } => {
214 | assert_eq!(name, "greet");
215 | }
216 | _ => panic!("Expected Function node"),
217 | }
218 | }
219 | _ => panic!("Expected List node"),
220 | }
221 | }
222 |
223 | #[test]
224 | fn test_function_parsing_without_keyword() {
225 | let script = "greet() { echo hello; }";
226 | let ast = parse_script(script);
227 |
228 | match ast {
229 | Node::List { statements, .. } => {
230 | assert_eq!(statements.len(), 1);
231 | match &statements[0] {
232 | Node::Function { name, .. } => {
233 | assert_eq!(name, "greet");
234 | }
235 | _ => panic!("Expected Function node"),
236 | }
237 | }
238 | _ => panic!("Expected List node"),
239 | }
240 | }
241 |
242 | #[test]
243 | fn test_return_parsing() {
244 | let script = "return 42";
245 | let ast = parse_script(script);
246 |
247 | match ast {
248 | Node::List { statements, .. } => {
249 | assert_eq!(statements.len(), 1);
250 | match &statements[0] {
251 | Node::Return { value } => {
252 | assert!(value.is_some());
253 | match value.as_ref().unwrap().as_ref() {
254 | Node::StringLiteral(val) => {
255 | assert_eq!(val, "42");
256 | }
257 | _ => panic!("Expected StringLiteral node for return value"),
258 | }
259 | }
260 | _ => panic!("Expected Return node"),
261 | }
262 | }
263 | _ => panic!("Expected List node"),
264 | }
265 | }
266 |
267 | #[test]
268 | fn test_return_parsing_no_value() {
269 | let script = "return";
270 | let ast = parse_script(script);
271 |
272 | match ast {
273 | Node::List { statements, .. } => {
274 | assert_eq!(statements.len(), 1);
275 | match &statements[0] {
276 | Node::Return { value } => {
277 | assert!(value.is_none());
278 | }
279 | _ => panic!("Expected Return node"),
280 | }
281 | }
282 | _ => panic!("Expected List node"),
283 | }
284 | }
285 |
286 | #[test]
287 | fn test_function_with_complex_body() {
288 | let script = "complex_func() { echo \"Starting function\"; if [ $# -eq 0 ]; then echo \"No arguments provided\"; return 1; fi; echo \"Processing arguments\"; echo \"Function complete\"; return 0; }; complex_func arg1 arg2 arg3";
289 | let result = execute_script(script);
290 | assert!(result.is_ok());
291 | assert_eq!(result.unwrap(), 0);
292 | }
293 |
294 | #[test]
295 | fn test_function_error_handling() {
296 | let script = r#"
297 | failing_func() {
298 | echo "This will fail"
299 | false
300 | }
301 | failing_func
302 | "#;
303 | let result = execute_script(script);
304 | assert!(result.is_ok());
305 | // The return value should be 1 (false command's exit code)
306 | assert_eq!(result.unwrap(), 1);
307 | }
308 |
309 | #[test]
310 | fn test_factorial_function() {
311 | let script = r#"
312 | function factorial() {
313 | if [ $1 -le 1 ]; then
314 | echo "Base case: $1"
315 | return 1
316 | else
317 | echo "Computing factorial of $1"
318 | return $1
319 | fi
320 | }
321 | factorial 5
322 | "#;
323 | let result = execute_script(script);
324 | assert!(result.is_ok());
325 | assert_eq!(result.unwrap(), 5);
326 | }
327 |
328 | #[test]
329 | fn test_factorial_base_case() {
330 | let script = r#"
331 | function factorial() {
332 | if [ $1 -le 1 ]; then
333 | echo "Base case: $1"
334 | return 1
335 | else
336 | echo "Computing factorial of $1"
337 | return $1
338 | fi
339 | }
340 | factorial 1
341 | "#;
342 | let result = execute_script(script);
343 | assert!(result.is_ok());
344 | assert_eq!(result.unwrap(), 1);
345 | }
346 |
347 | #[test]
348 | fn test_factorial_zero() {
349 | let script = r#"
350 | function factorial() {
351 | if [ $1 -le 1 ]; then
352 | echo "Base case: $1"
353 | return 1
354 | else
355 | echo "Computing factorial of $1"
356 | return $1
357 | fi
358 | }
359 | factorial 0
360 | "#;
361 | let result = execute_script(script);
362 | assert!(result.is_ok());
363 | assert_eq!(result.unwrap(), 1);
364 | }
365 |
--------------------------------------------------------------------------------
/tests/integration_tests.rs:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2025 Raphael Amorim
3 | *
4 | * This file is part of flash, which is licensed
5 | * under GNU General Public License v3.0.
6 | */
7 |
8 | use std::fs;
9 | use std::process::Command;
10 | use tempfile::tempdir;
11 |
12 | /// Get the path to the flash binary, handling cross-compilation targets
13 | fn get_flash_binary_path() -> std::path::PathBuf {
14 | let current_dir = std::env::current_dir().unwrap();
15 |
16 | // First try the target-specific path (for cross-compilation)
17 | if let Ok(target) = std::env::var("CARGO_BUILD_TARGET") {
18 | let target_path = current_dir
19 | .join("target")
20 | .join(target)
21 | .join("release")
22 | .join("flash");
23 | if target_path.exists() {
24 | return target_path;
25 | }
26 | }
27 |
28 | // Fall back to the default path
29 | let default_path = current_dir.join("target/release/flash");
30 | if default_path.exists() {
31 | return default_path;
32 | }
33 |
34 | // If neither exists, try to find any flash binary in target directories
35 | let target_dir = current_dir.join("target");
36 | if let Ok(entries) = fs::read_dir(&target_dir) {
37 | for entry in entries.flatten() {
38 | if entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false) {
39 | let release_dir = entry.path().join("release");
40 | let binary_path = release_dir.join("flash");
41 | if binary_path.exists() {
42 | return binary_path;
43 | }
44 | }
45 | }
46 | }
47 |
48 | // Last resort: return the default path (will fail if it doesn't exist)
49 | default_path
50 | }
51 |
52 | #[test]
53 | fn test_script_file_execution_with_positional_args() {
54 | let temp_dir = tempdir().unwrap();
55 | let script_path = temp_dir.path().join("test_script.sh");
56 |
57 | // Create a test script that uses positional parameters
58 | fs::write(
59 | &script_path,
60 | r#"echo "Script: $0, First: $1, Second: $2, Count: $#""#,
61 | )
62 | .unwrap();
63 |
64 | // Execute the script with arguments
65 | // Get the path to the flash binary (handle cross-compilation)
66 | let binary_path = get_flash_binary_path();
67 |
68 | let output = Command::new(&binary_path)
69 | .arg(&script_path)
70 | .arg("hello")
71 | .arg("world")
72 | .output()
73 | .expect("Failed to execute flash");
74 |
75 | let stdout = String::from_utf8(output.stdout).unwrap();
76 | let expected = format!(
77 | "Script: {}, First: hello, Second: world, Count: 2\n",
78 | script_path.display()
79 | );
80 |
81 | assert_eq!(stdout, expected);
82 | assert!(output.status.success());
83 | }
84 |
85 | #[test]
86 | fn test_piped_input_with_positional_args() {
87 | // Test piped input with positional arguments using echo
88 | let output = Command::new("sh")
89 | .arg("-c")
90 | .arg("echo 'echo \"Piped: $1, $2, $3, Count: $#\"' | cargo run --release -- arg1 arg2 arg3")
91 | .output()
92 | .expect("Failed to execute test");
93 |
94 | let stdout = String::from_utf8(output.stdout).unwrap();
95 |
96 | assert_eq!(stdout, "Piped: arg1, arg2, arg3, Count: 3\n");
97 | assert!(output.status.success());
98 | }
99 |
100 | #[test]
101 | fn test_script_file_with_special_variables() {
102 | let temp_dir = tempdir().unwrap();
103 | let script_path = temp_dir.path().join("special_vars.sh");
104 |
105 | // Create a script that tests all special variables
106 | fs::write(
107 | &script_path,
108 | r#"echo "All args: $@"
109 | echo "All args alt: $*"
110 | echo "Arg count: $#"
111 | echo "Individual: $1 $2 $3""#,
112 | )
113 | .unwrap();
114 |
115 | // Get the path to the flash binary
116 | let binary_path = get_flash_binary_path();
117 |
118 | let output = Command::new(&binary_path)
119 | .arg(&script_path)
120 | .arg("first")
121 | .arg("second")
122 | .arg("third")
123 | .output()
124 | .expect("Failed to execute flash");
125 |
126 | let stdout = String::from_utf8(output.stdout).unwrap();
127 | let expected = "All args: first second third\nAll args alt: first second third\nArg count: 3\nIndividual: first second third\n";
128 |
129 | assert_eq!(stdout, expected);
130 | assert!(output.status.success());
131 | }
132 |
133 | #[test]
134 | fn test_script_file_with_no_args() {
135 | let temp_dir = tempdir().unwrap();
136 | let script_path = temp_dir.path().join("no_args.sh");
137 |
138 | // Create a script that handles no arguments
139 | fs::write(
140 | &script_path,
141 | r#"echo "Script: $0"
142 | echo "First arg (should be empty): '$1'"
143 | echo "Count: $#"
144 | echo "All args: '$@'""#,
145 | )
146 | .unwrap();
147 |
148 | // Get the path to the flash binary
149 | let binary_path = get_flash_binary_path();
150 |
151 | let output = Command::new(&binary_path)
152 | .arg(&script_path)
153 | .output()
154 | .expect("Failed to execute flash");
155 |
156 | let stdout = String::from_utf8(output.stdout).unwrap();
157 | let expected = format!(
158 | "Script: {}\nFirst arg (should be empty): ''\nCount: 0\nAll args: ''\n",
159 | script_path.display()
160 | );
161 |
162 | assert_eq!(stdout, expected);
163 | assert!(output.status.success());
164 | }
165 |
166 | #[test]
167 | fn test_script_file_with_spaces_in_args() {
168 | let temp_dir = tempdir().unwrap();
169 | let script_path = temp_dir.path().join("spaces.sh");
170 |
171 | // Create a script that handles arguments with spaces
172 | fs::write(
173 | &script_path,
174 | r#"echo "First: '$1'"
175 | echo "Second: '$2'"
176 | echo "All: '$@'""#,
177 | )
178 | .unwrap();
179 |
180 | // Get the path to the flash binary
181 | let binary_path = get_flash_binary_path();
182 |
183 | let output = Command::new(&binary_path)
184 | .arg(&script_path)
185 | .arg("hello world")
186 | .arg("test arg")
187 | .output()
188 | .expect("Failed to execute flash");
189 |
190 | let stdout = String::from_utf8(output.stdout).unwrap();
191 | let expected = "First: 'hello world'\nSecond: 'test arg'\nAll: 'hello world test arg'\n";
192 |
193 | assert_eq!(stdout, expected);
194 | assert!(output.status.success());
195 | }
196 |
197 | #[test]
198 | fn test_piped_input_vs_script_file_priority() {
199 | let temp_dir = tempdir().unwrap();
200 | let script_path = temp_dir.path().join("priority_test.sh");
201 |
202 | // Create a script file
203 | fs::write(&script_path, r#"echo "Script file executed with: $1""#).unwrap();
204 |
205 | // When both script file and stdin are available, script file should take priority
206 | // This tests the fix for the execution flow
207 | // Get the path to the flash binary
208 | let binary_path = get_flash_binary_path();
209 |
210 | let output = Command::new(&binary_path)
211 | .arg(&script_path)
212 | .arg("script_arg")
213 | .output()
214 | .expect("Failed to execute flash");
215 |
216 | let stdout = String::from_utf8(output.stdout).unwrap();
217 | let expected = "Script file executed with: script_arg\n";
218 |
219 | assert_eq!(stdout, expected);
220 | assert!(output.status.success());
221 | }
222 |
223 | #[test]
224 | fn test_command_flag_execution() {
225 | // Test the -c flag for direct command execution
226 | // Get the path to the flash binary
227 | let binary_path = get_flash_binary_path();
228 |
229 | let output = Command::new(&binary_path)
230 | .arg("-c")
231 | .arg("echo \"Direct command: $1\"")
232 | .output()
233 | .expect("Failed to execute flash");
234 |
235 | let stdout = String::from_utf8(output.stdout).unwrap();
236 | // With -c flag, there are no positional arguments set up
237 | let expected = "Direct command: \n";
238 |
239 | assert_eq!(stdout, expected);
240 | assert!(output.status.success());
241 | }
242 |
243 | #[test]
244 | fn test_nonexistent_script_file() {
245 | // Test error handling for non-existent script files
246 | // Get the path to the flash binary
247 | let binary_path = get_flash_binary_path();
248 |
249 | let output = Command::new(&binary_path)
250 | .arg("nonexistent_script.sh")
251 | .arg("arg1")
252 | .output()
253 | .expect("Failed to execute flash");
254 |
255 | let stderr = String::from_utf8(output.stderr).unwrap();
256 |
257 | assert!(stderr.contains("Error reading script"));
258 | assert!(stderr.contains("nonexistent_script.sh"));
259 | assert!(!output.status.success());
260 | }
261 |
262 | #[test]
263 | fn test_positional_parameters_with_variable_expansion() {
264 | let temp_dir = tempdir().unwrap();
265 | let script_path = temp_dir.path().join("var_expansion.sh");
266 |
267 | // Create a script that mixes positional parameters with variable expansion
268 | fs::write(
269 | &script_path,
270 | r#"export TEST_VAR="test_value"
271 | echo "Var: $TEST_VAR, Arg: $1"
272 | echo "Mixed: ${TEST_VAR}_${1}_suffix""#,
273 | )
274 | .unwrap();
275 |
276 | // Get the path to the flash binary
277 | let binary_path = get_flash_binary_path();
278 |
279 | let output = Command::new(&binary_path)
280 | .arg(&script_path)
281 | .arg("hello")
282 | .output()
283 | .expect("Failed to execute flash");
284 |
285 | let stdout = String::from_utf8(output.stdout).unwrap();
286 | let expected = "Var: test_value, Arg: hello\nMixed: test_value_hello_suffix\n";
287 |
288 | assert_eq!(stdout, expected);
289 | assert!(output.status.success());
290 | }
291 |
292 | #[test]
293 | fn test_high_numbered_positional_parameters() {
294 | let temp_dir = tempdir().unwrap();
295 | let script_path = temp_dir.path().join("high_numbers.sh");
296 |
297 | // Create a script that tests higher numbered parameters
298 | fs::write(
299 | &script_path,
300 | r#"echo "Args: $1 $2 $3 $4 $5 $6 $7 $8 $9 ${10} ${11}"
301 | echo "Count: $#""#,
302 | )
303 | .unwrap();
304 |
305 | // Get the path to the flash binary
306 | let binary_path = get_flash_binary_path();
307 |
308 | let output = Command::new(&binary_path)
309 | .arg(&script_path)
310 | .args(["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"])
311 | .output()
312 | .expect("Failed to execute flash");
313 |
314 | let stdout = String::from_utf8(output.stdout).unwrap();
315 | let expected = "Args: a b c d e f g h i j k\nCount: 11\n";
316 |
317 | assert_eq!(stdout, expected);
318 | assert!(output.status.success());
319 | }
320 |
321 | #[test]
322 | fn test_argument_count_parameter() {
323 | let temp_dir = tempdir().unwrap();
324 | let script_path = temp_dir.path().join("arg_count.sh");
325 |
326 | // Test $# with various argument counts
327 | fs::write(
328 | &script_path,
329 | r#"echo "Args: $#"
330 | if [ $# -eq 0 ]; then
331 | echo "No arguments provided"
332 | fi
333 | if [ $# -eq 1 ]; then
334 | echo "One argument: $1"
335 | fi
336 | if [ $# -gt 5 ]; then
337 | echo "Many arguments: $@"
338 | fi
339 | if [ $# -gt 1 ] && [ $# -le 5 ]; then
340 | echo "Some arguments: $@"
341 | fi"#,
342 | )
343 | .unwrap();
344 |
345 | // Test with no arguments
346 | // Get the path to the flash binary
347 | let binary_path = get_flash_binary_path();
348 |
349 | let output = Command::new(&binary_path)
350 | .arg(&script_path)
351 | .output()
352 | .expect("Failed to execute flash");
353 |
354 | let stdout = String::from_utf8(output.stdout).unwrap();
355 | assert!(stdout.contains("Args: 0"));
356 | assert!(stdout.contains("No arguments provided"));
357 | assert!(output.status.success());
358 |
359 | // Test with one argument
360 | // Get the path to the flash binary
361 | let binary_path = get_flash_binary_path();
362 |
363 | let output = Command::new(&binary_path)
364 | .arg(&script_path)
365 | .arg("single")
366 | .output()
367 | .expect("Failed to execute flash");
368 |
369 | let stdout = String::from_utf8(output.stdout).unwrap();
370 | assert!(stdout.contains("Args: 1"));
371 | assert!(stdout.contains("One argument: single"));
372 | assert!(output.status.success());
373 |
374 | // Test with many arguments
375 | // Get the path to the flash binary
376 | let binary_path = get_flash_binary_path();
377 |
378 | let output = Command::new(&binary_path)
379 | .arg(&script_path)
380 | .args(["a", "b", "c", "d", "e", "f", "g"])
381 | .output()
382 | .expect("Failed to execute flash");
383 |
384 | let stdout = String::from_utf8(output.stdout).unwrap();
385 | assert!(stdout.contains("Args: 7"));
386 | assert!(stdout.contains("Many arguments: a b c d e f g"));
387 | assert!(output.status.success());
388 | }
389 |
390 | #[test]
391 | fn test_seq_command_basic() {
392 | let temp_dir = tempdir().unwrap();
393 | let script_path = temp_dir.path().join("seq_test.sh");
394 |
395 | // Test basic seq functionality
396 | fs::write(
397 | &script_path,
398 | r#"echo "Seq 1 to 5:"
399 | seq 5
400 | echo "Seq 2 to 4:"
401 | seq 2 4
402 | echo "Seq 1 to 10 by 2:"
403 | seq 1 2 10"#,
404 | )
405 | .unwrap();
406 |
407 | // Get the path to the flash binary
408 | let binary_path = get_flash_binary_path();
409 |
410 | let output = Command::new(&binary_path)
411 | .arg(&script_path)
412 | .output()
413 | .expect("Failed to execute flash");
414 |
415 | let stdout = String::from_utf8(output.stdout).unwrap();
416 |
417 | // Check seq 5 (1 to 5)
418 | assert!(stdout.contains("Seq 1 to 5:"));
419 | assert!(stdout.contains("1\n2\n3\n4\n5"));
420 |
421 | // Check seq 2 4 (2 to 4)
422 | assert!(stdout.contains("Seq 2 to 4:"));
423 | assert!(stdout.contains("2\n3\n4"));
424 |
425 | // Check seq 1 2 10 (1 to 10 by 2)
426 | assert!(stdout.contains("Seq 1 to 10 by 2:"));
427 | assert!(stdout.contains("1\n3\n5\n7\n9"));
428 |
429 | assert!(output.status.success());
430 | }
431 |
432 | #[test]
433 | fn test_seq_command_in_loops() {
434 | let temp_dir = tempdir().unwrap();
435 | let script_path = temp_dir.path().join("seq_loop.sh");
436 |
437 | // Test seq with command substitution (simpler version)
438 | fs::write(
439 | &script_path,
440 | r#"echo "Testing seq command:"
441 | seq 1 3
442 |
443 | echo "Testing seq in variable:"
444 | numbers=$(seq 1 3)
445 | echo "Numbers: $numbers"
446 |
447 | echo "Testing seq with different ranges:"
448 | seq 5 7"#,
449 | )
450 | .unwrap();
451 |
452 | // Get the path to the flash binary
453 | let binary_path = get_flash_binary_path();
454 |
455 | let output = Command::new(&binary_path)
456 | .arg(&script_path)
457 | .output()
458 | .expect("Failed to execute flash");
459 |
460 | let stdout = String::from_utf8(output.stdout).unwrap();
461 |
462 | assert!(stdout.contains("Testing seq command:"));
463 | assert!(stdout.contains("1\n2\n3"));
464 | assert!(stdout.contains("Testing seq in variable:"));
465 | assert!(stdout.contains("Numbers: 1\n2\n3"));
466 | assert!(stdout.contains("Testing seq with different ranges:"));
467 | assert!(stdout.contains("5\n6\n7"));
468 |
469 | assert!(output.status.success());
470 | }
471 |
472 | #[test]
473 | fn test_arithmetic_expansion_basic() {
474 | let temp_dir = tempdir().unwrap();
475 | let script_path = temp_dir.path().join("arithmetic.sh");
476 |
477 | // Test basic arithmetic expansion - using simpler expressions that work
478 | fs::write(
479 | &script_path,
480 | r#"# Test basic arithmetic with variables
481 | a=10
482 | b=5
483 | echo "Variable a: $a"
484 | echo "Variable b: $b"
485 |
486 | # Test argument count arithmetic
487 | echo "Argument count: $#"
488 | echo "Args provided: $@""#,
489 | )
490 | .unwrap();
491 |
492 | // Get the path to the flash binary
493 | let binary_path = get_flash_binary_path();
494 |
495 | let output = Command::new(&binary_path)
496 | .arg(&script_path)
497 | .args(["arg1", "arg2", "arg3"])
498 | .output()
499 | .expect("Failed to execute flash");
500 |
501 | let stdout = String::from_utf8(output.stdout).unwrap();
502 |
503 | assert!(stdout.contains("Variable a: 10"));
504 | assert!(stdout.contains("Variable b: 5"));
505 | assert!(stdout.contains("Argument count: 3"));
506 | assert!(stdout.contains("Args provided: arg1 arg2 arg3"));
507 |
508 | assert!(output.status.success());
509 | }
510 |
511 | #[test]
512 | fn test_arithmetic_expansion_with_argument_count() {
513 | let temp_dir = tempdir().unwrap();
514 | let script_path = temp_dir.path().join("arith_args.sh");
515 |
516 | // Test argument count with conditionals and seq
517 | fs::write(
518 | &script_path,
519 | r#"echo "Argument count: $#"
520 |
521 | # Test conditionals with argument count
522 | if [ $# -eq 0 ]; then
523 | echo "No arguments provided"
524 | fi
525 |
526 | if [ $# -eq 3 ]; then
527 | echo "Exactly three arguments"
528 | echo "Sequence for 3 args:"
529 | seq 1 3
530 | fi
531 |
532 | if [ $# -gt 2 ]; then
533 | echo "More than two arguments"
534 | fi"#,
535 | )
536 | .unwrap();
537 |
538 | // Test with 3 arguments
539 | // Get the path to the flash binary
540 | let binary_path = get_flash_binary_path();
541 |
542 | let output = Command::new(&binary_path)
543 | .arg(&script_path)
544 | .args(["arg1", "arg2", "arg3"])
545 | .output()
546 | .expect("Failed to execute flash");
547 |
548 | let stdout = String::from_utf8(output.stdout).unwrap();
549 |
550 | assert!(stdout.contains("Argument count: 3"));
551 | assert!(stdout.contains("Exactly three arguments"));
552 | assert!(stdout.contains("More than two arguments"));
553 | assert!(stdout.contains("Sequence for 3 args:"));
554 | assert!(stdout.contains("1\n2\n3"));
555 |
556 | assert!(output.status.success());
557 |
558 | // Test with no arguments
559 | // Get the path to the flash binary
560 | let binary_path = get_flash_binary_path();
561 |
562 | let output = Command::new(&binary_path)
563 | .arg(&script_path)
564 | .output()
565 | .expect("Failed to execute flash");
566 |
567 | let stdout = String::from_utf8(output.stdout).unwrap();
568 |
569 | assert!(stdout.contains("Argument count: 0"));
570 | assert!(stdout.contains("No arguments provided"));
571 |
572 | assert!(output.status.success());
573 | }
574 |
575 | #[test]
576 | fn test_seq_with_arithmetic_expansion() {
577 | let temp_dir = tempdir().unwrap();
578 | let script_path = temp_dir.path().join("seq_arith.sh");
579 |
580 | // Test seq command with literal values and argument count
581 | fs::write(
582 | &script_path,
583 | r#"echo "Using seq with literal values:"
584 | seq 2 2 8
585 |
586 | echo "Testing seq ranges:"
587 | seq 10 12
588 |
589 | echo "Argument count is: $#"
590 | if [ $# -eq 2 ]; then
591 | echo "Two arguments provided"
592 | echo "Sequence for 2 args:"
593 | seq 1 2
594 | fi
595 |
596 | echo "Testing basic variable assignment:"
597 | start=5
598 | echo "start variable: $start""#,
599 | )
600 | .unwrap();
601 |
602 | // Get the path to the flash binary
603 | let binary_path = get_flash_binary_path();
604 |
605 | let output = Command::new(&binary_path)
606 | .arg(&script_path)
607 | .args(["x", "y"])
608 | .output()
609 | .expect("Failed to execute flash");
610 |
611 | let stdout = String::from_utf8(output.stdout).unwrap();
612 |
613 | assert!(stdout.contains("Using seq with literal values:"));
614 | assert!(stdout.contains("2\n4\n6\n8"));
615 |
616 | assert!(stdout.contains("Testing seq ranges:"));
617 | assert!(stdout.contains("10\n11\n12"));
618 |
619 | assert!(stdout.contains("Argument count is: 2"));
620 | assert!(stdout.contains("Two arguments provided"));
621 | assert!(stdout.contains("Sequence for 2 args:"));
622 | assert!(stdout.contains("1\n2"));
623 |
624 | assert!(stdout.contains("Testing basic variable assignment:"));
625 | assert!(stdout.contains("start variable: 5"));
626 |
627 | assert!(output.status.success());
628 | }
629 |
630 | #[test]
631 | fn test_complex_arithmetic_and_conditionals() {
632 | let temp_dir = tempdir().unwrap();
633 | let script_path = temp_dir.path().join("complex_arith.sh");
634 |
635 | // Test complex logic with argument count and conditionals
636 | fs::write(
637 | &script_path,
638 | r#"echo "Testing complex logic with $# arguments"
639 |
640 | if [ $# -eq 0 ]; then
641 | echo "No arguments - using defaults"
642 | fi
643 |
644 | if [ $# -eq 2 ]; then
645 | echo "Exactly two arguments"
646 | echo "Sequence for 2:"
647 | seq 1 2
648 | fi
649 |
650 | if [ $# -eq 4 ]; then
651 | echo "Exactly four arguments"
652 | echo "Sequence for 4:"
653 | seq 1 4
654 | fi
655 |
656 | if [ $# -gt 0 ]; then
657 | echo "Arguments provided"
658 | fi"#,
659 | )
660 | .unwrap();
661 |
662 | // Test with 4 arguments
663 | // Get the path to the flash binary
664 | let binary_path = get_flash_binary_path();
665 |
666 | let output = Command::new(&binary_path)
667 | .arg(&script_path)
668 | .args(["a", "b", "c", "d"])
669 | .output()
670 | .expect("Failed to execute flash");
671 |
672 | let stdout = String::from_utf8(output.stdout).unwrap();
673 |
674 | assert!(stdout.contains("Testing complex logic with 4 arguments"));
675 | assert!(stdout.contains("Arguments provided"));
676 | assert!(stdout.contains("Exactly four arguments"));
677 | assert!(stdout.contains("Sequence for 4:"));
678 | assert!(stdout.contains("1\n2\n3\n4"));
679 |
680 | assert!(output.status.success());
681 |
682 | // Test with 2 arguments
683 | // Get the path to the flash binary
684 | let binary_path = get_flash_binary_path();
685 |
686 | let output = Command::new(&binary_path)
687 | .arg(&script_path)
688 | .args(["a", "b"])
689 | .output()
690 | .expect("Failed to execute flash");
691 |
692 | let stdout = String::from_utf8(output.stdout).unwrap();
693 |
694 | assert!(stdout.contains("Testing complex logic with 2 arguments"));
695 | assert!(stdout.contains("Exactly two arguments"));
696 | assert!(stdout.contains("1\n2"));
697 |
698 | assert!(output.status.success());
699 | }
700 |
701 | #[test]
702 | fn test_glob_pattern_basic() {
703 | let temp_dir = tempdir().unwrap();
704 | let script_path = temp_dir.path().join("glob_test.sh");
705 |
706 | // Create some test files in the temp directory
707 | fs::write(temp_dir.path().join("file1.txt"), "content1").unwrap();
708 | fs::write(temp_dir.path().join("file2.txt"), "content2").unwrap();
709 | fs::write(temp_dir.path().join("test.log"), "log content").unwrap();
710 | fs::write(temp_dir.path().join("data.csv"), "csv content").unwrap();
711 |
712 | // Create a script that uses glob patterns
713 | fs::write(
714 | &script_path,
715 | r#"echo "Testing glob patterns:"
716 | echo "All txt files:"
717 | echo *.txt
718 |
719 | echo "All files:"
720 | echo *
721 |
722 | echo "Log files:"
723 | echo *.log"#,
724 | )
725 | .unwrap();
726 |
727 | // Get the path to the flash binary
728 | // let binary_path = std::env::current_dir()
729 | // .unwrap()
730 | // .join("target/release/flash");
731 |
732 | // Run the script from the temp directory
733 | // Get the path to the flash binary
734 | let binary_path = get_flash_binary_path();
735 |
736 | let output = Command::new(&binary_path)
737 | .arg(&script_path)
738 | .current_dir(temp_dir.path())
739 | .output()
740 | .expect("Failed to execute flash");
741 |
742 | let stdout = String::from_utf8(output.stdout).unwrap();
743 |
744 | assert!(stdout.contains("Testing glob patterns:"));
745 | assert!(stdout.contains("All txt files:"));
746 | assert!(stdout.contains("file1.txt"));
747 | assert!(stdout.contains("file2.txt"));
748 | assert!(stdout.contains("All files:"));
749 | assert!(stdout.contains("data.csv"));
750 | assert!(stdout.contains("test.log"));
751 | assert!(stdout.contains("Log files:"));
752 | assert!(stdout.contains("test.log"));
753 |
754 | assert!(output.status.success());
755 | }
756 |
757 | #[test]
758 | fn test_glob_pattern_wildcards() {
759 | let temp_dir = tempdir().unwrap();
760 | let script_path = temp_dir.path().join("wildcard_test.sh");
761 |
762 | // Create test files with specific patterns
763 | fs::write(temp_dir.path().join("file1.txt"), "content").unwrap();
764 | fs::write(temp_dir.path().join("file2.txt"), "content").unwrap();
765 | fs::write(temp_dir.path().join("fileA.log"), "content").unwrap();
766 | fs::write(temp_dir.path().join("fileB.log"), "content").unwrap();
767 | fs::write(temp_dir.path().join("test123.dat"), "content").unwrap();
768 |
769 | // Create a script that tests different wildcard patterns
770 | fs::write(
771 | &script_path,
772 | r#"echo "Testing wildcard patterns:"
773 |
774 | echo "Question mark pattern (file?.txt):"
775 | echo file?.txt
776 |
777 | echo "Star pattern (*.log):"
778 | echo *.log
779 |
780 | echo "Combined pattern (test*.dat):"
781 | echo test*.dat"#,
782 | )
783 | .unwrap();
784 |
785 | // Get the path to the flash binary
786 | let binary_path = get_flash_binary_path();
787 |
788 | let output = Command::new(&binary_path)
789 | .arg(&script_path)
790 | .current_dir(temp_dir.path())
791 | .output()
792 | .expect("Failed to execute flash");
793 |
794 | let stdout = String::from_utf8(output.stdout).unwrap();
795 |
796 | assert!(stdout.contains("Testing wildcard patterns:"));
797 | assert!(stdout.contains("Question mark pattern"));
798 | assert!(stdout.contains("file1.txt"));
799 | assert!(stdout.contains("file2.txt"));
800 | assert!(stdout.contains("Star pattern"));
801 | assert!(stdout.contains("fileA.log"));
802 | assert!(stdout.contains("fileB.log"));
803 | assert!(stdout.contains("Combined pattern"));
804 | assert!(stdout.contains("test123.dat"));
805 |
806 | assert!(output.status.success());
807 | }
808 |
809 | #[test]
810 | fn test_glob_pattern_character_classes() {
811 | let temp_dir = tempdir().unwrap();
812 | let script_path = temp_dir.path().join("charclass_test.sh");
813 |
814 | // Create test files for character class testing
815 | fs::write(temp_dir.path().join("file1.txt"), "content").unwrap();
816 | fs::write(temp_dir.path().join("file2.txt"), "content").unwrap();
817 | fs::write(temp_dir.path().join("file3.txt"), "content").unwrap();
818 | fs::write(temp_dir.path().join("file4.txt"), "content").unwrap();
819 | fs::write(temp_dir.path().join("filea.txt"), "content").unwrap();
820 | fs::write(temp_dir.path().join("fileb.txt"), "content").unwrap();
821 |
822 | // Create a script that tests character class patterns
823 | fs::write(
824 | &script_path,
825 | r#"echo "Testing character class patterns:"
826 |
827 | echo "Numeric range [1-3]:"
828 | echo file[1-3].txt
829 |
830 | echo "Letter range [a-b]:"
831 | echo file[a-b].txt
832 |
833 | echo "Specific characters [24]:"
834 | echo file[24].txt"#,
835 | )
836 | .unwrap();
837 |
838 | // Get the path to the flash binary
839 | let binary_path = get_flash_binary_path();
840 |
841 | let output = Command::new(&binary_path)
842 | .arg(&script_path)
843 | .current_dir(temp_dir.path())
844 | .output()
845 | .expect("Failed to execute flash");
846 |
847 | let stdout = String::from_utf8(output.stdout).unwrap();
848 |
849 | assert!(stdout.contains("Testing character class patterns:"));
850 | assert!(stdout.contains("Numeric range"));
851 | assert!(stdout.contains("file1.txt"));
852 | assert!(stdout.contains("file2.txt"));
853 | assert!(stdout.contains("file3.txt"));
854 | assert!(
855 | !stdout.contains("file4.txt")
856 | || stdout
857 | .lines()
858 | .filter(|line| line.contains("file4.txt"))
859 | .count()
860 | <= 1
861 | );
862 | assert!(stdout.contains("Letter range"));
863 | assert!(stdout.contains("filea.txt"));
864 | assert!(stdout.contains("fileb.txt"));
865 | assert!(stdout.contains("Specific characters"));
866 | assert!(stdout.contains("file2.txt") || stdout.contains("file4.txt"));
867 |
868 | assert!(output.status.success());
869 | }
870 |
871 | #[test]
872 | fn test_glob_pattern_with_commands() {
873 | let temp_dir = tempdir().unwrap();
874 | let script_path = temp_dir.path().join("command_glob_test.sh");
875 |
876 | // Create test files
877 | fs::write(temp_dir.path().join("readme.txt"), "readme content").unwrap();
878 | fs::write(temp_dir.path().join("config.txt"), "config content").unwrap();
879 | fs::write(temp_dir.path().join("data.log"), "log content").unwrap();
880 |
881 | // Create a script that uses glob patterns with commands
882 | fs::write(
883 | &script_path,
884 | r#"echo "Testing glob patterns with commands:"
885 |
886 | echo "Echo with glob pattern:"
887 | echo *.txt
888 |
889 | echo "Testing no matches:"
890 | echo *.xyz
891 |
892 | echo "Multiple patterns:"
893 | echo *.txt *.log"#,
894 | )
895 | .unwrap();
896 |
897 | // Get the path to the flash binary
898 | let binary_path = get_flash_binary_path();
899 |
900 | let output = Command::new(&binary_path)
901 | .arg(&script_path)
902 | .current_dir(temp_dir.path())
903 | .output()
904 | .expect("Failed to execute flash");
905 |
906 | let stdout = String::from_utf8(output.stdout).unwrap();
907 |
908 | assert!(stdout.contains("Testing glob patterns with commands:"));
909 | assert!(stdout.contains("Echo with glob pattern:"));
910 | // Should show the expanded files
911 | assert!(stdout.contains("readme.txt"));
912 | assert!(stdout.contains("config.txt"));
913 | assert!(stdout.contains("Testing no matches:"));
914 | // Should show the literal pattern when no matches
915 | assert!(stdout.contains("*.xyz"));
916 | assert!(stdout.contains("Multiple patterns:"));
917 | assert!(stdout.contains("data.log"));
918 |
919 | assert!(output.status.success());
920 | }
921 |
922 | #[test]
923 | fn test_glob_pattern_edge_cases() {
924 | let temp_dir = tempdir().unwrap();
925 | let script_path = temp_dir.path().join("edge_case_test.sh");
926 |
927 | // Create test files including hidden files
928 | fs::write(temp_dir.path().join("normal.txt"), "content").unwrap();
929 | fs::write(temp_dir.path().join(".hidden.txt"), "hidden content").unwrap();
930 | fs::write(temp_dir.path().join("file with spaces.txt"), "content").unwrap();
931 |
932 | // Create a script that tests edge cases
933 | fs::write(
934 | &script_path,
935 | r#"echo "Testing glob edge cases:"
936 |
937 | echo "All visible files:"
938 | echo *
939 |
940 | echo "Hidden files (explicit dot):"
941 | echo .*
942 |
943 | echo "Empty pattern result:"
944 | echo *.nonexistent"#,
945 | )
946 | .unwrap();
947 |
948 | // Get the path to the flash binary
949 | let binary_path = get_flash_binary_path();
950 |
951 | let output = Command::new(&binary_path)
952 | .arg(&script_path)
953 | .current_dir(temp_dir.path())
954 | .output()
955 | .expect("Failed to execute flash");
956 |
957 | let stdout = String::from_utf8(output.stdout).unwrap();
958 |
959 | assert!(stdout.contains("Testing glob edge cases:"));
960 | assert!(stdout.contains("All visible files:"));
961 | assert!(stdout.contains("normal.txt"));
962 | // Hidden files should not appear in * pattern
963 | assert!(
964 | !stdout
965 | .lines()
966 | .any(|line| line.contains("All visible files:") && line.contains(".hidden.txt"))
967 | );
968 | assert!(stdout.contains("Hidden files"));
969 | // Should find hidden file with explicit dot pattern
970 | assert!(stdout.contains(".hidden.txt"));
971 | assert!(stdout.contains("Empty pattern result:"));
972 | assert!(stdout.contains("*.nonexistent"));
973 |
974 | assert!(output.status.success());
975 | }
976 |
--------------------------------------------------------------------------------