<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by ras malai on Medium]]></title>
        <description><![CDATA[Stories by ras malai on Medium]]></description>
        <link>https://medium.com/@rasmalai123?source=rss-ff41da4dec54------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*H4uudO7FE-wUQ1O3M9vuMA.jpeg</url>
            <title>Stories by ras malai on Medium</title>
            <link>https://medium.com/@rasmalai123?source=rss-ff41da4dec54------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 11:54:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rasmalai123/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[rustc & llvm flags in rustc compilation]]></title>
            <link>https://rasmalai123.medium.com/rustc-llvm-flags-in-rustc-compilation-dab31d9280f3?source=rss-ff41da4dec54------2</link>
            <guid isPermaLink="false">https://medium.com/p/dab31d9280f3</guid>
            <category><![CDATA[flags]]></category>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[llvm]]></category>
            <category><![CDATA[rustc]]></category>
            <category><![CDATA[clang]]></category>
            <dc:creator><![CDATA[ras malai]]></dc:creator>
            <pubDate>Thu, 20 Aug 2026 21:20:09 GMT</pubDate>
            <atom:updated>2026-08-20T21:20:09.185Z</atom:updated>
            <content:encoded><![CDATA[<p>-Z internal or unstable features, only used for experimental stuff, compiler rejects it on stable rust</p><p>-C codegen settings in rustc; instructions on how llvm turns code into machine instructions like -C opt-level=3or-C debuginfo=2`</p><p>-C link-args passes raw args directly to linker like ld lld or link.exe<br> -C llvm-args passes args to LLVM optimization engines</p><p>-C remark LLVM automatically tries to make your code run faster, by doing -C remark; it tells you how exactly it did that, and what points it couldn&#39;t make run faster. (-C remark=all , -C remark=pass-name)</p><p>-C advanced codegen options:<br> -C target-cpu=native: tells LLVM to look after physical computer&#39;s cpu and enable every single instruction it supports<br> <br> -C lto=fat enables link-time optimizations, instead of optimizing each crate individually, LLVM merges the dependency graph into a single giant blob and optimizes across crate boundaries<br> <br> -C panic=abort disables heavy unwinding machinery for panics, LLVM can strip out error-handling code paths, drastically shrinking binary size.</p><p>-L library paths, adds a directory to the library search path, tells the computer where to look for binaries, crates etc. rustc -L path/to/dep/ , it can look for things like rlibs dylibs native libraries etc.</p><p>-X Clang driver flags, its a forwarding flag,<br> -Xclang &lt;args&gt;: passes the directly to compiler frontend<br> -Xlinker &lt;args&gt;: passes the args directly to linker</p><p>-I this universally stands for include and manages search paths for external files,<br> like clang -I/usr/local/include main.c<br> rustc doesn&#39;t use headers, so -I is not used, rustc uses --extern or -L to find compiled libraries. if the project compiles native C dependencies via a build script cc-rs, the c compiler will use -I</p><p>-W stands for warning and how compiler alerts the problematic code.<br> in clang/llvm:<br> -Wextra / -Wall: enables broad suites of common warnings<br> -Werror: treats all warnings as hard compilation errors<br> -Wno-deprecated: disables warnings about deprecated features.<br> <br> in rustc:<br> -W help: lists all available lints<br> -W unused_variables: changes the unused variables lint from allowed to a warning<br> in rust, usually #[warn(..)] is used.</p><p>-D and -U they handle configuration flags before the actual compilation begins.<br> in clang/llvm:<br> -D: defines a macro like: -Ddebug<br> -U: undefines a macro, removing any default definition.<br> <br> in rustc:<br> rustc uses -D for deny. it upgrades the compiler lint into hardmode.<br> eg: rustc -D unused-imports main.rs</p><p>-A, -W, -F, -D<br> rust uses a 4 tier lint system on command line.<br> -A allow: suppresses a specific lint (-A dead-code)<br> -W warn: raises a warning for a lint<br> -D deny: raises an error for a lint, but allows it to be overriden in code<br> -F forbid: raises hard error</p><p>-O, optimization intensity:<br> -O0: no optimization - fastest compile time, easy debugging<br> -O2: standard production optimization balance<br> -O3: aggressive optimization<br> -Os/Oz: optimizes specifically to make binary file as small as possible<br> use -C opt-level=1/2/3/s/z</p><p>-g debuginfo levels:<br> -g0 no debuginfo<br> -g1 line tables only (file name and line numbers in crashes)<br> -g2 max debuginfo `rustc has -C debuginfo=0/1/2`</p><p>-f features in clang/llvm<br> -fPIC generates position independent code (req for shared lib)<br> || rustc: -C relocation-model=pic<br> <br> -fno-exceptions disables c++ exception handling to reduce binary overhead<br> || rustc (for Rust panics): -C panic=abort (or passed to C++ build scripts)<br> <br> -fsanitize=address: injects LLVM AddressSanitizer to catch memory bugs<br> || rustc (nightly): -Z sanitizer=address<br> <br> -mavx2 / -march=native (not -f) enable specific CPU instruction sets<br> || rustc: -C target-feature=+avx2 or -C target-cpu=native</p><p>--emit: tells rustc at what stage compilation pipeline should present or output its results after saving them; can be at any stage/mid compilation.<br> --emit=mir dumps rustc&#39;s Mid-level Intermediate Representation, how rustc looks after<br> borrow checking but before llvm sees it.<br> <br> --emit=llvm-ir dumps the text-based LLVM intermediate representation, this is<br> universally assembly like language that LLVM optimizes.<br> <br> --emit=asm dumps final hardware assembly code.</p><p>--target: &lt;triple&gt; essential for cross compilation, tells rustc exactly which arch and OS to build for</p><p>--crate-type &lt;type&gt; defines the exact output format, common are bin (executable) rlib (rust lib), cdylib (c compatiable dynamic ib)</p><p>--cfg &lt;spec&gt; rustc&#39;s version of -D flags, passes config options for conditional compiling using #[cfg(...)] attribute in code.</p><p>(ever growing list, whatever new i find<br>kind of my personal log book)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dab31d9280f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[measuring reproducibility stuff in rustc]]></title>
            <link>https://rasmalai123.medium.com/measuring-reproducibility-stuff-in-rustc-4101a7218b4c?source=rss-ff41da4dec54------2</link>
            <guid isPermaLink="false">https://medium.com/p/4101a7218b4c</guid>
            <category><![CDATA[wsl]]></category>
            <category><![CDATA[rust-programming]]></category>
            <category><![CDATA[ntfs]]></category>
            <category><![CDATA[ext4]]></category>
            <category><![CDATA[reproducibility]]></category>
            <dc:creator><![CDATA[ras malai]]></dc:creator>
            <pubDate>Sun, 11 Jan 2026 21:08:40 GMT</pubDate>
            <atom:updated>2026-01-11T21:08:40.682Z</atom:updated>
            <content:encoded><![CDATA[<h4>meaning: if i build a something 2 times, it should be identical to the bit and not have any differences anywhere in the whole build, like cloning it.</h4><h4>context: reproducing rustc in native wsl ubuntu and wsl mounted ntfs.</h4><h3>observation / happenings:</h3><ul><li>Linux vs Linux had the same build to the bit, meaning both builds had the same hashes after i ran the build.</li><li>but when i did, ntfs vs ext4, it gave out different hashes which shouldn’t happen because reproducing any build shouldn’t depend on the os you are using or where you are doing it (wsl, ntfs, macos, linux)</li><li>used x.py build library in for both runs. sha256 for hashes.</li><li>used RUSTFLAGS=&quot;--remap-path-prefix=$PWD=/rust&quot;. for relocating the local path of the compilation output if incase that was the cause of different hashes. here from location is $pwd which means present working directory in shell and changing that to /rust as destination. still different hashes.</li><li>then used rust.remap-debuginfo = true as bjorn3&#39;s recommendation: this also changes the local directory location but this is used in rust compiler own build system i.e. bootstrap.toml, usually changes the path from local path to something like /rust/$hash/. this also gave different hashes for ext4 vs mounted ntfs. there were /../../ in the diffoscope of ntfs builds but not likely the true cause of this reproducibility issue i was facing.</li><li>ran an experiment to check if this was being done by different Cmetadata being passed to rustc by cargo. but the hashes still differed. though this run had the same crate hash, same archive member order, but different hash for final .rlib.</li><li>did another experiment thinking the object file contents were different (the inherent binary files of both builds), turns out they were.</li><li>the crate hash is placed at the end of crate’s metadata, so if i diff the first bytes of metadata, i was seeing the diff of other components in metadata like filesize, crate name and symbol table.</li><li>ran Zls=root on both, the results still differed:</li></ul><pre>ext4:<br>Crate info:<br>name std-87388099cce461c0<br>hash e676cddf26b3a7e4f399755f7a87b269 stable_crate_id StableCrateId(651687009903211415)<br>proc_macro false<br>triple x86_64-unknown-linux-gnu<br>edition 2024<br>symbol_mangling_version V0<br>required_panic_strategy None panic_in_drop_strategy Unwind<br>has_global_allocator false has_alloc_error_handler true has_panic_handler true has_default_lib_allocator true<br>compiler_builtins false needs_allocator false needs_panic_runtime true no_builtins false panic_runtime false profiler_runtime false<br>=External Dependencies=<br>1 core-8c1a2d756194a4e6 hash 17026b6bae5911a8a27695595b8dcbe9 host_hash None kind Unconditional public linkage Some(RequireStatic)<br>2 alloc-fb722fbc9dbd09e3 hash 0b094d9e1beecad94460779513a64f9d host_hash None kind Unconditional public linkage Some(RequireStatic)<br>3 compiler_builtins-e7437f55b02ea193 hash 24555b6cdd175e26cf98ceabecd208be host_hash None kind Unconditional private linkage Some(RequireStatic)<br>4 libc-9783c5088fe7402b hash bd6da5edec1e3e6803e5c9e436b09b61 host_hash None kind Unconditional public linkage Some(RequireStatic)<br>5 rustc_std_workspace_core-69cc13ab079084d5 hash 6134fa0728d845b0dd99053306d5d9a4 host_hash None kind Unconditional public linkage Some(RequireStatic)<br>6 unwind-1c40c0059cfbdead hash 6458da1648b9d535cf01cef017f60c78 host_hash None kind Unconditional private linkage Some(RequireStatic)<br>7 miniz_oxide-5ef1834ba20a98ca hash a6414c49cc8b12ea280e1fa8252f7ad2 host_hash None kind Unconditional private linkage Some(RequireStatic)<br>8 adler2-c5178ef216b9eeb6 hash 3425ac800abe3172ceedba185e10f25f host_hash None kind Unconditional private linkage Some(RequireStatic)<br>9 hashbrown-af02015094b28da9 hash 1487f568684ba44981bd6fef6bf29488 host_hash None kind Unconditional private linkage Some(RequireStatic)<br>10 rustc_std_workspace_alloc-ed22fc2c1339b276 hash 1ab2d78b1f895529e91f26d6532bed66 host_hash None kind Unconditional public linkage Some(RequireStatic)<br>11 std_detect-76063e260660f5a4 hash 24235c951529af86f141a7337035cc18 host_hash None kind Unconditional public linkage Some(RequireStatic)<br>12 rustc_demangle-c270d820cbed3daa hash 0dd1c19fa134f496ed6f2b2d0f7e2190 host_hash None kind Unconditional private linkage Some(RequireStatic)<br>13 cfg_if-86821b7a9f378489 hash 785c0cf2168074ee2392779841ff59d0 host_hash None kind Unconditional private linkage Some(RequireStatic)<br>14 addr2line-74d4a2a4b931daee hash ae7de998d57bf59103243d3a3e8b19a4 host_hash None kind Unconditional private linkage Some(RequireStatic)<br>15 gimli-563ca6c70a0dc651 hash cdf9ce074651317f3314f5b7380d9a85 host_hash None kind Unconditional private linkage Some(RequireStatic)<br>16 object-c5a8e6d17b463f45 hash e9cef80cf11567efd374d4d72e754733 host_hash None kind Unconditional private linkage Some(RequireStatic)<br>17 memchr-0d87e60d5bbd9a52 hash cd1ba00645c40aec4d159f083a188319 host_hash None kind Unconditional private linkage Some(RequireStatic)<br>18 panic_unwind-720f7861a860e2ca hash ad6f2b3a80ba4a06374abb39d45566d2 host_hash None kind Conditional private linkage Some(RequireStatic)</pre><pre>ntfs:<br>Crate info:<br>name std-87388099cce461c0<br>hash 61e8ec52fc99f66bea4666adef577a67 stable_crate_id StableCrateId(651687009903211415)<br>proc_macro false<br>triple x86_64-unknown-linux-gnu<br>edition 2024<br>symbol_mangling_version V0<br>required_panic_strategy None panic_in_drop_strategy Unwind<br>has_global_allocator false has_alloc_error_handler true has_panic_handler true has_default_lib_allocator true<br>compiler_builtins false needs_allocator false needs_panic_runtime true no_builtins false panic_runtime false profiler_runtime false<br>=External Dependencies=<br>1 core-8c1a2d756194a4e6 hash a533bff47d481cdf376eb0855bd39117 host_hash None kind Unconditional public linkage Some(RequireStatic)<br>2 alloc-fb722fbc9dbd09e3 hash 0cac0ec3db75b387d1857301d99f692c host_hash None kind Unconditional public linkage Some(RequireStatic)<br>3 compiler_builtins-e7437f55b02ea193 hash a6c35625b1bb01e34bc0962b71e7e909 host_hash None kind Unconditional private linkage Some(RequireStatic)<br>4 libc-9783c5088fe7402b hash 3944c97c49d4e8b0f67ab85f6bbc7cf9 host_hash None kind Unconditional public linkage Some(RequireStatic)<br>5 rustc_std_workspace_core-69cc13ab079084d5 hash 3c5507d031c81b81b06a5e9d956bfeec host_hash None kind Unconditional public linkage Some(RequireStatic)<br>6 unwind-1c40c0059cfbdead hash 02005d1e4a624701cb77766c1fb74dc6 host_hash None kind Unconditional private linkage Some(RequireStatic)<br>7 miniz_oxide-5ef1834ba20a98ca hash 3d84871d7a0ddaddab108dd5d846890a host_hash None kind Unconditional private linkage Some(RequireStatic)<br>8 adler2-c5178ef216b9eeb6 hash 2efc23785d71cb8a746150a48a791749 host_hash None kind Unconditional private linkage Some(RequireStatic)<br>9 hashbrown-af02015094b28da9 hash 481112a31d11b4343e17fc1974c57a6b host_hash None kind Unconditional private linkage Some(RequireStatic)<br>10 rustc_std_workspace_alloc-ed22fc2c1339b276 hash 9f92c927283d5fa4324f6dbda1378dd0 host_hash None kind Unconditional public linkage Some(RequireStatic)<br>11 std_detect-76063e260660f5a4 hash 727f0382e32af85416a643353a2bf216 host_hash None kind Unconditional public linkage Some(RequireStatic)<br>12 rustc_demangle-c270d820cbed3daa hash 92f471b4179d7d772102713bed27487a host_hash None kind Unconditional private linkage Some(RequireStatic)<br>13 cfg_if-86821b7a9f378489 hash dbc4136bcb18cb647977749e2c972c89 host_hash None kind Unconditional private linkage Some(RequireStatic)<br>14 addr2line-74d4a2a4b931daee hash 6a5030378d97d9d01782c97bc78ba2c0 host_hash None kind Unconditional private linkage Some(RequireStatic)<br>15 gimli-563ca6c70a0dc651 hash 34eb0ab5a69c72cb6d92e5255541ffb7 host_hash None kind Unconditional private linkage Some(RequireStatic)<br>16 object-c5a8e6d17b463f45 hash 4ce479502688eb52d6908d72eefa1e23 host_hash None kind Unconditional private linkage Some(RequireStatic)<br>17 memchr-0d87e60d5bbd9a52 hash ee4bc1d3929aff6da2b59dfe2db548d7 host_hash None kind Unconditional private linkage Some(RequireStatic)<br>18 panic_unwind-720f7861a860e2ca hash 057de712f979a34cdd1f19a734d89b8d host_hash None kind Conditional private linkage Some(RequireStatic)</pre><ul><li>checked diffoscope between both stage1 binaries, ext4 vs ntfs. the binary files were showing differences in themselves. checked it for one of the binary files.</li></ul><h3>current problem: why stage1 compiler itself differs.</h3><ul><li>ran a few commands, found out the timestamps were being embedded by system and not a general declared timestamps.</li><li>filesystem metadata could be different: different permissions, different link counts, no birth time.</li><li>currently doing export SOURCE_DATE_EPOCH=1 on both and building again. : all the hashes were different.</li></ul><pre>paradox@abhinavHP:/mnt/c/Users/91877/rust_torture$ diff ~/rust/ext4.hashes /mnt/c/Users/91877/rust_torture/ntfs.hashes<br>1,6c1,5<br>&lt; 094217bd5624149751ad77c47dbdc8b5d600f644467e1d3f7a8e5df3a6495861  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libadler2-c5178ef216b9eeb6.rlib<br>&lt; 0a2141110b0aa3d681ee04b0d08e305970b16ad2a007b4a064505e8f4b627e54  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/liblibc-9783c5088fe7402b.rlib<br>&lt; 0e601342c8d3a6866597829413b55c867db4101841ae4ce43e69c77e3340e363  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libobject-c5a8e6d17b463f45.rlib<br>&lt; 0f9c7b68a378ea39dd8a60b38e28e60732b53cd104216ca32af9633cba0923ad  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libgimli-563ca6c70a0dc651.rlib<br>&lt; 28e880d41b509a797c3882e9be083b6beebcc4db42a3905e9c718e296be33a21  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libpanic_abort-8594d8315dd828ef.rlib<br>&lt; 299a8d077bb0823dc06e1eacb6229032fb961e60bb5f8f1fd5c5bb829d5cf649  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libproc_macro-4c60c34730764c09.rlib<br>---<br>&gt; 0cde04a8e5ce4bafcf9bc167a87ec7f6462be99add03ce5bcf85416eb539e4b4  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libgetopts-e1375dd58b9aa877.rlib<br>&gt; 1b8aabce0dc2d7fbcfd61a91e297035d071948d24ab81be0883aeda4675ace3b  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/liballoc-fb722fbc9dbd09e3.rlib<br>&gt; 1ee45eaeb1439986bf8c4c3f58f915c9ef42a208a10ed51e35910a60b2d144b5  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libhashbrown-af02015094b28da9.rlib<br>&gt; 24aa25d439190ea3d0d8c2b01f34537556cdce3e6e6e1a697129b4b479796511  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libcfg_if-86821b7a9f378489.rlib<br>&gt; 3c4c3e55cec00f385e55ace39f63e143984c0dfdb20aba3e94763b07e3462711  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libaddr2line-74d4a2a4b931daee.rlib<br>8,28c7,28<br>&lt; 48f7ca628705a602d5d09c6614a9477e93e4d7f5c4cdc25fa5a6fba945a28d01  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libhashbrown-af02015094b28da9.rlib<br>&lt; 4bdd7775d8b33652c6aa09e7b0dba78e01739c494343233beafbf762d5c024c1  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libsysroot-8e6d8fd5ed34236c.rlib<br>&lt; 53074c8a3152bc2f7f7d9e6ac0cfa1a609c4585414e26adf7b96d952c1d4772c  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/librustc_literal_escaper-bb39ebe195c609f0.rlib<br>&lt; 53b418c4eea98266f1094b989a9551e29699f970bb7b873c2cec989c5b95f858  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libtest-64016306040e0ddd.rlib<br>&lt; 56a9b678ddcd07e4d788bb467a9259b37552de0025defff108b7f9e814a1268b  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libmemchr-0d87e60d5bbd9a52.rlib<br>&lt; 6f01a705246fdb3f9c841129ba01b7013701f555ef5df7f72462e3f6031de8a5  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libcore-8c1a2d756194a4e6.rlib<br>&lt; 73bf4dfadcb1aabc8a273f19148b4d5a65d4309a31bdaf8452fbf68602f8c19b  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libaddr2line-74d4a2a4b931daee.rlib<br>&lt; 880f34d5e88bcd3e46fd00220daa0f87dd90b5224c7a7a1ebf7c43d37f6ef8e9  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/liballoc-fb722fbc9dbd09e3.rlib<br>&lt; 88b43c7dfa28410bbe75a440f12dcb8bf95ddaa385c08fc32968bd9c8dd853d8  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/librustc_demangle-c270d820cbed3daa.rlib<br>&lt; 989e45abc10923056b207b029a7c267d41f90bef3927fb03c86c0540c7cde483  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libstd-87388099cce461c0.rlib<br>&lt; 9c26040b27453053b9daebc0c7c841defec7915a98b9ff1c7280cbc4bdd0c690  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/librustc_std_workspace_std-213cc89e2fa16cad.rlib<br>&lt; 9cfa00a7b62102aa9950bab33466b16d2b5046046e488ed7a43745b7ba0c762e  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/librustc_std_workspace_alloc-ed22fc2c1339b276.rlib<br>&lt; ae6206577671bef4eca7a980fa63005c86f1e5c1ac3e2d899337ac355c5133f5  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/librustc_std_workspace_core-69cc13ab079084d5.rlib<br>&lt; b2ccf6deb269b4e81c1848ff21670b8786c917c923d2b3f208e1d5655f7e8c71  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libstd_detect-76063e260660f5a4.rlib<br>&lt; bc2a34f7e843b63e0f39abeb829e688d3c797e22b942bc186f60c511f9c85cf7  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libgetopts-e1375dd58b9aa877.rlib<br>&lt; c14568cb9d18bc793e3c54a3860e6e9b6352955bd4b36ea95ff45dbbe5fbf689  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libminiz_oxide-5ef1834ba20a98ca.rlib<br>&lt; cf11bbff133e944f80e83731ffc39a64acc7048dd3a44406343ba5f723e2a953  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libcfg_if-86821b7a9f378489.rlib<br>&lt; d09198cfd76028891f566b10f680694377d85e4b8b2b05aa55f21ec3b21b704b  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libcompiler_builtins-e7437f55b02ea193.rlib<br>&lt; ea0554a6ac4472a27cdc8276d86892efe528a9e630fee3bbc1c87f1bb763e66f  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libstd-87388099cce461c0.so<br>&lt; f815208ed745f6edeedbd0ed499b9654abe354d852c7d287cee5e3638d363b64  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libunwind-1c40c0059cfbdead.rlib<br>&lt; fd7b9d3ecac4de1036aed4c6ecb374bb8fca797850f4847fec9d9143a1294d14  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libpanic_unwind-720f7861a860e2ca.rlib<br>---<br>&gt; 5c392866c8a9986281820cb783bcf8a74211f2ff8b0d6b1ade14cd83a92d391c  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libadler2-c5178ef216b9eeb6.rlib<br>&gt; 639db2822b567c536c7279bb7640cd8b5e22f4348e16d3ab74ddb50e7630e34f  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/librustc_std_workspace_alloc-ed22fc2c1339b276.rlib<br>&gt; 698213adad5daeab691c4088e78bf884b93f5ad6218a1f26db6eee54006e9890  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libobject-c5a8e6d17b463f45.rlib<br>&gt; 709c86002ea128f2caa653b1c5dc3bde39c1a67adcec5956e1861461bca836dc  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libcompiler_builtins-e7437f55b02ea193.rlib<br>&gt; 80d81ddd8f17948eaad28d08913f543e05524705d8f88ba62be7e2a0e7bf7cd0  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libcore-8c1a2d756194a4e6.rlib<br>&gt; 83a64311d59ec07e654797ef1efd499c3baa4107c3a5f4d89d998ed894ab0437  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libminiz_oxide-5ef1834ba20a98ca.rlib<br>&gt; 86115bb13ce06caba8798477b3bf1b7adadd04462cf87efdb296d287002b687f  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libtest-64016306040e0ddd.rlib<br>&gt; 8cd8daf70df4c05ed1b4d3a0f3f99da9c9e75e92befeea56794681a2add145f1  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/librustc_std_workspace_core-69cc13ab079084d5.rlib<br>&gt; 8dd3c5126eabfff0ec008b1aa45868bdc3877bd63454f3fc85b3a880245ef930  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libunwind-1c40c0059cfbdead.rlib<br>&gt; 9d149a55e1699d652f02ee7b777bd2c0e32e3d77976a409ab8924f6525edeaab  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libstd-87388099cce461c0.so<br>&gt; b5c797c833049da4ca572ba1cf530995c56f548da430331d401253223df11b3d  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libsysroot-8e6d8fd5ed34236c.rlib<br>&gt; bb07f7d5d0cda6513abf03e077437b3593cf65340c8bb09505f0db545fcab9ef  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/librustc_demangle-c270d820cbed3daa.rlib<br>&gt; bb67b01e70d7e0d97d0a2df5f8a2b5a7b1c7fef6bff6e0a686bc4411c351972c  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libmemchr-0d87e60d5bbd9a52.rlib<br>&gt; bc3325498ed68f7211f22b5d79d0d184e8b63505d0a72d402bdf49e87d33b757  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/librustc_std_workspace_std-213cc89e2fa16cad.rlib<br>&gt; bd6ae67c4c607be1e9a46675d56462199e876de89c73cd79cc9c183d93735687  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libpanic_abort-8594d8315dd828ef.rlib<br>&gt; c5066a0247390048536f283ac1c362f0ce6952396ac6d0fd687f7f7eeea364a7  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libproc_macro-4c60c34730764c09.rlib<br>&gt; c585e4c591477625e291f28f1f4535dd0852b3bb2aaccfdfa1ad1dcb46030670  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libgimli-563ca6c70a0dc651.rlib<br>&gt; cca6404f8afb88194ac9cd48c903866b677273485bbbc004e5a26ab886267c72  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libstd-87388099cce461c0.rlib<br>&gt; e1fbb9a19c6185a93744e90b8a37efb96c5ada3e3d2876ac30efcfc9f53cc6a5  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/librustc_literal_escaper-bb39ebe195c609f0.rlib<br>&gt; eb94eb48fc2de40018fb78df67b1c0dc1ef4f43da692a1e3dec69a170737b261  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libpanic_unwind-720f7861a860e2ca.rlib<br>&gt; f3ff6a8624896e93de6fb922a17edd1c7c779bbd4705332b71e6d6fd0c01ff1f  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/liblibc-9783c5088fe7402b.rlib<br>&gt; fc5a1c6fc1beba2a9949b8ce72b6b2c5f0a71113f85b7f239d3e56f8df8562a7  build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/libstd_detect-76063e260660f5a4.rlib<br>paradox@abhinavHP:/mnt/c/Users/91877/rust_torture$</pre><ul><li>ntfs has fake huge inode numbers like 475692710641049129 vs wsl has 62229, ran stat library/std/src/lib.rs and stat library/std/src/lib.rs currently the root cause is looking like the file permission between both builds, update: false. this is for ntfs:</li></ul><pre>Access: (0777/-rwxrwxrwx)<br>Size: 28196</pre><p>this is for ext4:</p><pre>Access: (0644/-rw-r--r--)<br>Size: 28244</pre><p>permissions were different in both files, set the permission equal, still different hashes. i was on the different commit on both builds. i was on different commit. shit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4101a7218b4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[building a compiler from scratch in rust]]></title>
            <link>https://rasmalai123.medium.com/compiler-b9a614f9ef7b?source=rss-ff41da4dec54------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9a614f9ef7b</guid>
            <category><![CDATA[compiler-design]]></category>
            <category><![CDATA[rust-programming]]></category>
            <category><![CDATA[hihi]]></category>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[arm64]]></category>
            <dc:creator><![CDATA[ras malai]]></dc:creator>
            <pubDate>Mon, 08 Dec 2025 19:04:27 GMT</pubDate>
            <atom:updated>2026-03-24T09:00:26.253Z</atom:updated>
            <content:encoded><![CDATA[<h3>a masochist’s guide to understanding how compilers actually work.</h3><h3><strong>TABLE OF CONTENTS:</strong></h3><p>PART 1: LEXICAL ANALYSIS<br>— what are compilers?<br> — what is lexical analysis?<br> — regular expressions: your lexer’s tinder algorithm<br> — setting up the rust project<br> — writing token.rs<br> — writing lexer.rs (the final boss)<br> — testing with main.rs</p><p>PART 2: PARSER<br> — what does a parser do?<br> — Abstract Syntax Trees (AST)<br> — Recursive Descent Parsing<br> — forging the AST<br> — dissecting parser.rs<br> — parsing statements<br> — parsing expressions</p><p>PART 3: SEMANTIC ANALYSIS<br>— what is semantic analysis?<br> — types and errors<br> — symbol tables and scopes<br> — type checking<br> — testing the analyzer</p><p>PART 4: OPTIMIZER<br>— what is optimization?<br> — constant folding<br> — constant propagation<br> — dead code elimination<br> — algebraic simplification</p><p>PART 5: CODE GENERATION<br>— what is code generation?<br> — ARM64 Assembly Crash Course<br> — registers and stack frames<br> — setting up QEMU and GDB<br> — the codegen struct<br> — generating statements<br> — generating expressions<br> — running your compiler</p><h3>1. rust lexer</h3><h3>## what’s in this chaos:</h3><p>- what are compilers?<br>- what is lexical analysis?<br>- regular expressions: your lexer’s tinder algorithm<br>- setting up the rust project<br>- writing token.rs<br>- writing lexer.rs (the final boss)<br>- testing with main.rs</p><p>honestly this blog is more for me than presenting it <br> because i forget everything i do in 12 hours, so i am just teaching myself how i did it after i did it. a candy for my future self.</p><p>we have a million different languages to define one logic into in their own syntax, stupid right? yeah, useful? maybe. do i know how to write hello world in 8 different languages, unfortunately. my next step is binary out of spite. whether your goal is adding 2 numbers or finishing a client project whose payment is gonna be “in-process” for 3 months.</p><h3>my assumptions:</h3><ul><li>you have written some code before (optional)</li><li>you hate yourself a little (required)</li></ul><h3>so the f$ck are compilers, you think? me too.</h3><p>i have a lot to say for someone who dropped out engineering in the first 3 months of it.<br> compilers are something that translate your high-level code that is written in languages like rust, c, c++, etc and turns it into a low-level machine code that the computer processor can understand and execute.</p><p>humans: “hello(‘print’)”<br> computer: sorry bro i only understand 1s and 0s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*huJR6tRTRp4MxuFh.png" /></figure><p>so a compiler takes your code as input, and to make machine understand it, the compiler transforms it multiple times over many steps and converts it to a machine code that computer can understand and execute. here are the steps (if you really wanna learn):</p><ol><li><strong>lexical analysis:</strong> source / high-level code is broken down into tokens. stuff like keywords, identifiers, separators, operators, etc. the only part that didn’t kill me while building.</li><li><strong>parsing or syntax analysis</strong>: aka the grammar of your language, this just checks if your code is syntactically correct, if it follows the rules or not. if you forgot to put a semicolon again.</li><li><strong>semantic analysis:</strong> aka the brain of your language, this allows us to stay away from a common error of int x = hello, checks all the logical errors and grown-up stuff.</li><li><strong>code optimization:</strong> this turns your lame-ass javascript into a faster lame-ass javascript. this is used to improve the efficiency of your language, like removing unused code, constant folding, constant propagation.</li><li><strong>code generation:</strong> optimized code is translated into target machine code for the specific architecture of your computer.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*n6qvMUbJ0V7JHrAm.png" /></figure><p>in this article, i am gonna be covering only the lexical analysis part and implement a basic lexer. and i will be choosing rust as my language of choice because i hate myself. <br> but by the end of this page, you’d have made your own lexer from scratch!</p><h3>what is lexical analysis?</h3><p>╯°□°）╯ WHY IS THIS SO HARD???</p><p>this step involves taking your code as source at one end and makes tokens out of them on the other end,<br> the categories that we define are called as <strong>tokens</strong> and the words we put in each category are called <strong>lexemes.</strong> for one line understanding of it.</p><p>lets try to see this by an example:</p><pre>`a = 69 if 69 &lt; 420 else 420`</pre><p>and the above code passed through a lexer will give out:</p><pre>**`[IDENTIFIER, &#39;a&#39;] [ASSIGN_OP, &#39;=&#39;] [INTEGER, &#39;69&#39;] [IF]  [INTEGER, &#39;69&#39;]  [LESS_THAN]  [INTEGER, &#39;420&#39;]  [ELSE]  [INTEGER, &#39;420&#39;]`**</pre><p>the lexer looks at each word / symbol in the code and categorizes them into their respective token type. integer becomes IntegerLiteral string as StringLiteral and so on. this step is important because the compiler can throw everything in their own boxes regardless of different names you write, also it standardizes the vocab for later steps. its like a sorting hat of compilers where every lexeme wishes to go either in gryffindors or slytherin because they want the main character energy, <br> this stage usually ignores white spaces and comments, unless you write python, then something’s already wrong with you.</p><h3>Regular Language:</h3><p>the syntax of language is represented via something called Regular Language. basically the rules of writing something in a programming language, so you dont write</p><pre>hihihaha = 69<br>print???hello????<br>x = cat</pre><p>and get away with it,<br> those rules = regular language. aka the patterns your language allows.<br> and how do we define these patterns? an ancient cursed language of symbols — <strong>regex.</strong></p><p>rust analyzer staring me because i forgot to put a semicolon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/0*PUl4WJHrlEBaHbMO.png" /></figure><h3>**Regular Expressions: your lexer’s tinder algorithm</h3><p>(╬ ಠ益ಠ) i hate this but i must wield it.</p><p>regex pattern matches your source code string against the defined tokens to determine if its a valid or acceptable string or not. its swiping right on the code that matches your type. you basically tell your computer “hey, this is what valid shit looks like in my language: int x = 5 .”</p><p>you define patterns by these specific rules such as:</p><ul><li>start and end anchors: ^ and $ are used to denote beginning and end of line respectively. ^ matches the position before the string starts and $ comes after your string has ended.</li><li>character classes: [] are used to any one of the characters written in the brackets, for eg: [rule] will match any single ‘r’ ‘u’ ‘l’ and ‘e’, it doesnt have to be a specific word, can be any letter. you can also add a range to it by adding a dash between them like [a-z] or [0–9] for digits and this will allow everything in the specified range to be detected</li><li>predefined character classes: these are the shortcut for character classes which are more common like \w matches any word from [a-zA-Z], \d matches any digit from [0-9] and lastly \s matches whitespace characters</li><li>negated character classes: this is used when you want to finding something EXCEPT these specific characters, and this is done by placing ^ <strong>inside</strong> square brackets like [^yes], so this will match characters except ‘y’ ‘e’ ‘s’.</li><li>quantifiers: if there is a need to find something only if it has a number of a character like strawberry has 3 r in it so you this one. this is written like: *= matches zero or more times += matches one or more times ? = matches zero or one and {n}, {n, m} are used for specific quantities.</li></ul><pre>example containing all of them can be - <br>starts with a letter or underscore<br>then can have letters, digits, or underscores<br>regex for that:<br>*** [a-zA-Z_][a-zA-Z0-9_] /// you dont need to memorize this, you&#39;ll understand the logic<br>[a-zA-Z_] → first character rules<br>[a-zA-Z0-9_]* → zero or more of the allowed characters</pre><p>a quick and painless crash course of it: <br> <strong>anchors</strong></p><ul><li>^ → start of line</li><li>$ → end of line</li></ul><h3>character classes</h3><ul><li>[abc] → match &#39;a&#39; or &#39;b&#39; or &#39;c&#39;</li><li>[a-z] → lowercase letters</li><li>[0-9] → digits</li></ul><h3>shortcuts</h3><ul><li>\d → digits</li><li>\w → word chars (letters, digits, underscore)</li><li>\s → whitespace</li></ul><h3>quantifiers</h3><ul><li>* → 0 or more</li><li>+ → 1 or more</li><li>? → 0 or 1</li><li>{n} → exactly n times</li></ul><p>i know some of you are gonna be like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*WOt9c5uzA-n2QmeT.png" /></figure><p>but let loose, things are only gonna go downhill from here.</p><h3>enough with the theory, fire up your vsc (no cursor autocomplete)</h3><p>now we are gonna be</p><ul><li>creating a rust file</li><li>defining a Token enum</li><li>write regex pattern for each token</li><li>write a lexer that scans whole code</li><li>break everything</li><li>fix it</li><li>break it again</li><li>make it work</li></ul><p>time to hurt ourselves with rust now.</p><p>we’ll compile this following code -</p><pre>int x = 5;<br>int y = 6;<br>int x = x + y;<br>if (z &gt; 10) { <br>    print(&quot;hihi&quot;); <br>    } else {<br>    print(&quot;haha&quot;);<br>}</pre><p>based on this, we need a lexer that can capture:</p><ol><li>keywords like int, if, else</li><li>identifiers like x, y, z</li><li>numbers like 5, 6</li><li>operators: =, +, &gt;</li><li>strings: “hihi”, “haha”</li><li>brackets like (, ), {, }</li></ol><h3>setting up project:</h3><p>we start by the basic cargo command which will create a cargo.toml file and a src folder with a main dot rs file in it.</p><pre>cargo init rust-lexer<br>cd rust-lexer</pre><ol><li>cargo.toml is the config file of your project, this will have name, version, author and all the dependencies. if you need to add a package, you can do cargo add “package-name” or write it here directly.</li><li>src / main .rs: this is the default starting point of your rust code, cargo looks for this file to compile your code as binary</li></ol><p>we are gonna be increasing the file population in src folder …nothing china has to worry about.</p><p>lets first create a sub-folder in src folder by</p><pre>cd src<br>mkdir lexing</pre><p>in lexing folder, we are gonna add 3 more files, namely; token.rs , lexer.rs and mod.rs</p><p>your folder system should be looking like this rn</p><pre>.<br>├── Cargo.toml<br>├── src<br>│   ├── lexing<br>│   │   ├── [lexer.rs]<br>│   │   ├── [mod.rs]<br>│   │   └── [token.rs]<br>│   └── [main.rs]</pre><p>add regex = “1” in the dependencies section of your cargo.toml because you dont want your code to break (it will, somehow it will, dw).</p><h3>writing token.rs:</h3><p>(ง’̀-’́)ง fight me you 50 token types</p><p>we will be using enums for this task because why else do they exist, <br> we’ll start by creating a Token enum which will hold the token type for our lexemes, aka the types its gonna segregate string.</p><pre>#[derive(Debug, Clone)]<br>pub enum Token {<br>// keywords<br>    Print(String),<br>    If(String),<br>    Else(String),<br>    Int(String),<br>    Minus(String),<br><br>// literals<br>    IntegerLiteral(i32),<br>    StringLiteral(String),<br>    BooleanLiteral(bool),<br><br>// identifiers<br>    Identifier(String),<br><br>// operators <br>    Plus(String),<br>    Assign(String),<br><br>// punctuation<br>    SemiColon(String),<br>    LeftParen(String),<br>    RightParen(String),<br>    LeftBrace(String),<br>    RightBrace(String),<br><br>// logical operators<br>    GreaterThan(String),<br>    LessThan(String),<br>}<br>do not copy this and write it by yourself.</pre><p>this is a small list of basic stuff we need to at least get started with, this list can ofc be much bigger depending. and we have used String for most elements, this might NOT be the idiomatic way of writing rust but eh.</p><p>the #[derive(Debug)] is an attribute that implements a trait called debug, which lets us print the enum elements without any extra efforts. also we have to implement 2 functions now:</p><ul><li>when token_type string and value are given, return token object. for eg: given token_type string “StringLiteral” and value fuck , it’ll return as Token::StringLiteral(fuck)where ::is used to specify a particular variant of an enum, in this case StringLiteral.</li><li>return the regex to match lexeme for the token.</li></ul><p>now we implement these 2 functions in our rust code inside implfor Token</p><pre>impl Token {<br>pub fn get_token(token_type: &amp;str, value: Option&lt;&amp;str&gt;) -&gt; Token {<br>match token_type {<br>        // keywords<br>        &quot;Print&quot; =&gt; Token::Print(&quot;print&quot;.to_string()),<br>        &quot;If&quot; =&gt; Token::If(&quot;if&quot;.to_string()),<br>        &quot;Else&quot; =&gt; Token::Else(&quot;else&quot;.to_string()),<br>        &quot;Int&quot; =&gt; Token::Int(&quot;int&quot;.to_string()),<br><br>        // literals<br>        &quot;IntegerLiteral&quot; =&gt; {<br>            Token::IntegerLiteral(value.unwrap().parse::&lt;i32&gt;().unwrap())<br>        }<br>        &quot;StringLiteral&quot; =&gt; {<br>            Token::StringLiteral(value.unwrap().to_string())<br>        }<br>        &quot;BooleanLiteral&quot; =&gt; {<br>            let val = match value.unwrap() {<br>                &quot;true&quot; =&gt; true,<br>                &quot;false&quot; =&gt; false,<br>                _ =&gt; panic!(&quot;invalid boolean literal&quot;),<br>            };<br>            Token::BooleanLiteral(val)<br>        }<br><br>        // identifiers<br>        &quot;Identifier&quot; =&gt; Token::Identifier(value.unwrap().to_string()),<br><br>        // operators<br>        &quot;Plus&quot; =&gt; Token::Plus(&quot;+&quot;.to_string()),<br>        &quot;Minus&quot; =&gt; Token::Minus(&quot;-&quot;.to_string()),<br>        &quot;Assign&quot; =&gt; Token::Assign(&quot;=&quot;.to_string()),<br><br>        // punctuation<br>        &quot;SemiColon&quot; =&gt; Token::SemiColon(&quot;;&quot;.to_string()),<br>        &quot;LeftParen&quot; =&gt; Token::LeftParen(&quot;(&quot;.to_string()),<br>        &quot;RightParen&quot; =&gt; Token::RightParen(&quot;)&quot;.to_string()),<br>        &quot;LeftBrace&quot; =&gt; Token::LeftBrace(&quot;{&quot;.to_string()),<br>        &quot;RightBrace&quot; =&gt; Token::RightBrace(&quot;}&quot;.to_string()),<br><br>        // logical operators<br>        &quot;GreaterThan&quot; =&gt; Token::GreaterThan(&quot;&gt;&quot;.to_string()),<br>        &quot;LessThan&quot; =&gt; Token::LessThan(&quot;&lt;&quot;.to_string()),<br>        _ =&gt; panic!(&quot;invalid token type {}&quot;, token_type),<br>    }<br>    }<br>        pub fn get_token_regex(token_type: &amp;str) -&gt; String {<br>            match token_type {<br>                // keywords<br>                &quot;Print&quot; =&gt; r&quot;print&quot;,<br>                &quot;If&quot; =&gt; r&quot;if&quot;,<br>                &quot;Else&quot; =&gt; r&quot;else&quot;,<br>                &quot;Int&quot; =&gt; r&quot;int\\s+&quot;,<br><br>                // literals<br>                &quot;IntegerLiteral&quot; =&gt; r&quot;\\d+&quot;,<br>                &quot;StringLiteral&quot; =&gt; r#&quot;\\&quot;.*\\&quot;&quot;#,<br>                &quot;BooleanLiteral&quot; =&gt; r&quot;\\b(?:true|false)\\b&quot;,<br><br>                // identifiers<br>                &quot;Identifier&quot; =&gt; r&quot;[a-zA-Z_][a-zA-Z0-9_]*&quot;,<br><br>                // operators<br>                &quot;Plus&quot; =&gt; r&quot;\\+&quot;,<br>                &quot;Minus&quot; =&gt; r&quot;-&quot;,<br>                &quot;Assign&quot; =&gt; r&quot;=&quot;,<br><br>                // punctuation<br>                &quot;SemiColon&quot; =&gt; r&quot;;&quot;,<br>                &quot;LeftParen&quot; =&gt; r&quot;\\(&quot;,<br>                &quot;RightParen&quot; =&gt; r&quot;\\)&quot;,<br>                &quot;LeftBrace&quot; =&gt; r&quot;\\{&quot;,<br>                &quot;RightBrace&quot; =&gt; r&quot;\\}&quot;,<br><br>                // logical operators<br>                &quot;GreaterThan&quot; =&gt; r&quot;&gt;&quot;,<br>                &quot;LessThan&quot; =&gt; r&quot;&lt;&quot;,<br>                _ =&gt; panic!(&quot;invalid token type: {}&quot;, token_type),<br>            }.to_string()<br>        }<br>}</pre><p>here we are only matching strings and returning appropriate result based on whatever matches. <br> and something else you might notice is that we have written &amp;str and String differently, what are they you might ask? (us, i still google it) and on top of that we are using .to_string to convert &amp;str into String , you can think of &amp;str as an <em>immutable string</em> and String as a <em>mutable string</em>, ik rust has its own fetishes.</p><p>and at the last line of first fn, you can see the panic line there, that is used to when nothing matches the whole regex, thats called <strong>syntax error.</strong></p><p>you can also make a case that an “if” can be mistaken for being an identifier, you would be right for it, thats why it is written above identifier in list, so it catches those specific words early wherever present.</p><p>ik its getting a lot, you can take a break now<br> (Φ ω Φ) the cat judges your code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*-zlhFLjhOaa5ud_k.png" /></figure><p>or just keep going if youre a masochist like me.</p><p>you can see that a small function named get_token_regex sneaked beneath our code, so what is it actually doing? we made an enum, we made a function that returns token variants, but our lexer still does not know how to detect a token. and we do that by regex, cursed alien language.</p><h3>understanding regex:</h3><p>regular expression is a concise way to describe any kind of pattern inside text. you write a weird symbol soup and expect it to send you back what you actually wanted, and it surprisingly does that, <br> it scans your whole document to find something that matches your given pattern and gives it back to you. something like ^[a-zA-Z_]\w*$ ,</p><p>we can understand this simply by writing an an email validator. they follow a simple patten like:</p><ul><li>a small or large case letter first, NO number or symbols as first letter.</li><li>then can be lower / upper case including numbers, multiple characters.</li><li>then an @</li><li>followed by same lower / upper case which can include numbers.</li><li>then a dot .</li><li>generally some designated words like in, com, org.</li></ul><p>now we write that in regex form: that would go like</p><ol><li>[a-zA-Z]for first letter</li><li>[a-zA-Z0-9_]*for second and going forward</li><li>@</li><li>[a-zA-Z0-9]+ as domain extension, like @sigma420.com</li><li>. the literal dot</li><li>[in | com | edu]if you accept some specific individual characters only.</li></ol><p>the final result would look like [a-zA-Z][a-zA-Z0-9_]*@[a-zA-Z0-9]+.[in | com | edu]</p><p>its like summoning demons but for pattern matching. <br> laxmi_chit_fund@totally_safe.in please_send_money@gpay.in<br> viola, now you can understand and write regex by your own (i hope so).</p><h3>now we write regex for tokens:</h3><p>⊙_⊙; brain lag detected</p><ol><li><strong>keyword and operators: <br></strong>r”print”, r”if”, r”int\s+”: these are straightforward ones, they match the specific keyword strings. for int, s\+ is added to ensure that there is at least one whitespace if not more after it. also differentiate it from identifiers that can start with <em>int</em> like integerLiteral.</li><li><strong>numbers:</strong></li></ol><ul><li>\d+ → matches one or more digits, eg 5 , 69 , 420</li><li>\d+(\.\d+)?→ can be used to match decimals, but we are gonna stick with whole numbers rn.</li></ul><p><strong>3. identifiers (variable names, fn names):<br></strong>classic example of starts normal then goes brrr pattern<br> we denote that by [a-zA-Z_][a-zA-Z0-9_]*</p><pre>- meaning the first letter can be small / upper case, can also be an underscore.<br>- after that it can be letters, numbers or underscores, so it matches stuff like <br>`heheheha`, `y69`, and doesnt match stuff like `%yo` or `6n9` or `rule-34`.</pre><p><strong>4. strings:<br></strong>well these are the simplest regex in a way, you can just write “[^”]*” and done, this just basically EXCLUDES quote and returns anything that is not a quote. <br> eg being hihi haha .</p><p><strong>5. operators &amp; punctuations (brackets, braces or other fun shapes):<br></strong>r&quot;\+&quot;, r&quot;=&quot;, r&quot;;&quot;, r&quot;\(&quot;, r&quot;\)&quot;, r&quot;\{&quot;, r&quot;}&quot;, r&quot;&gt;&quot;, r&quot;&lt;&quot;: these patterns match operators and punctuations characters. some characters like +, (, ), {, } are special characters, to match them, they are escaped with a backslash.</p><p>sorry for too much technical blabber, im aiming to write as <em>random bullshit go.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*bRGIz7IUQpZ2KvCB.png" /></figure><h3>now we start writing our lexer.rs (THE FINAL BOSS): (ง🔥Д🔥)ง prepare for pain</h3><p>we have tokens, we have regex, now we need machine that eats your strings and poops out the tokens.</p><h3>logic:</h3><ol><li>take whole code as string</li><li>start at index 0</li><li>loop through list of Token regexes</li><li>does it match?</li></ol><ul><li>yeah: cut that part, save the token, move forward</li><li>no: try next regex</li></ul><p>5. nothing matches? panic at the desk-o.</p><p>6. regret everything</p><p>7. lose sanity</p><h3>5 stages of grief:</h3><h3>step 1: choose your victims aka tokens</h3><p>let me walk you through some code:</p><pre>let current_input = program;<br>let tokens = [<br>    &quot;Print&quot;, &quot;If&quot;, &quot;Else&quot;, &quot;Int&quot;, // keywords<br>    &quot;BooleanLiteral&quot;, &quot;IntegerLiteral&quot;, &quot;StringLiteral&quot;, // literals<br>    &quot;Plus&quot;, &quot;Minus&quot;, &quot;Assign&quot;, &quot;GreaterThan&quot;, &quot;LessThan&quot;, // operators<br>    &quot;LeftParen&quot;, &quot;RightParen&quot;, &quot;LeftBrace&quot;, &quot;RightBrace&quot;, &quot;SemiColon&quot;, // punctuation<br>    &quot;Identifier&quot;, // identifier<br>];</pre><p>here we made a string (current_input) <br> → a list of what to look for<br> → a place to store every match from every regex</p><p>and think of match_vec as a big group chat where every regex drops in like:<br> “hey i found something at index 27”</p><p>its like a vip list for words; keywords get in first, operators next and identifiers last</p><h3>step 2: send regex bots to scan everything:</h3><pre>for token in tokens.iter() {<br>    let re = Regex::new(pattern).unwrap();<br>    for m in re.find_iter(current_input) {<br>        match_vec.push((token, start, end));<br>    }<br>}</pre><p>here, for each token type:</p><ol><li>get the regex pattern</li><li>compile that regex</li><li>run it over the source code</li><li>every match yields: token type, start index in string, end index in string.</li></ol><p>this creates a giant list of all matches for all token types<br> even the wrong ones, even the cursed ones, like a data hungry pokemon trainer.</p><h3>step 3 — sorting hat of tokens</h3><p>then:</p><pre>match_vec.sort_by(|a, b| {<br>    a.1.cmp(&amp;b.1)<br>        .then_with(|| (b.2 - b.1).cmp(&amp;(a.2 - a.1)))<br>});</pre><p>now we take that giant list we made above and</p><ol><li>sort by starting index → left to right</li><li>if they start at the same place, choose the longer match fixes headaches like int vs integerLiteral , = vs ==</li></ol><h3>step 4 — keep the chosen ones.</h3><pre>for (token_type, start, end) in match_vec {<br>        if start &lt; last_end {<br>            continue;<br>        }<br>        last_end = end;<br>let lexeme = &amp;current_input[start..end];<br>        token_vec.push(Token::get_token(token_type, Some(lexeme)));<br>    }</pre><p>imagine all the tokens are standing in a queue, if a new token tries to overlap with previous one, you’d be like “we dont do that here” ****and throw it behind.</p><h3>step 5 — return the loot bag of chaos</h3><pre>token_vec</pre><p>this is the final treasure chest</p><ul><li>all tokens</li><li>all in correct order</li><li>overlapping drama resolved</li><li>ready to make parser cry</li></ul><pre>use regex::Regex;<br>use crate::lexing::token::Token;<br>pub fn lex_program(program: &amp;str) -&gt; Vec {<br>    let mut token_vec: Vec = Vec::new();<br>    let mut match_vec: Vec = Vec::new();<br>    let current_input = program;<br>    <br>    // step 1: choose your victims<br>    let tokens = [<br>        &quot;Print&quot;, &quot;If&quot;, &quot;Else&quot;, &quot;Int&quot;, // keywords<br>        &quot;BooleanLiteral&quot;, &quot;IntegerLiteral&quot;, &quot;StringLiteral&quot;, // literals<br>        &quot;Plus&quot;, &quot;Minus&quot;, &quot;Assign&quot;, &quot;GreaterThan&quot;, &quot;LessThan&quot;, // operators<br>        &quot;LeftParen&quot;, &quot;RightParen&quot;, &quot;LeftBrace&quot;, &quot;RightBrace&quot;, &quot;SemiColon&quot;, // punctuation<br>        &quot;Identifier&quot;, // identifier (last because it&#39;s greedy)<br>    ];<br><br>  // step 2: send regex bots to scan everything<br>    for token in tokens.iter() {<br>        let pattern = Token::get_token_regex(token);<br>        let re = Regex::new(&amp;pattern).unwrap();<br>        for m in re.find_iter(current_input) {<br>            match_vec.push((token, m.start(), m.end()));<br>        }<br>    }<br><br>  // step 3: sorting hat of tokens<br>    match_vec.sort_by(|a, b| {<br>        a.1.cmp(&amp;b.1) // sort by start position<br>            .then_with(|| (b.2 - b.1).cmp(&amp;(a.2 - a.1))) // longer match wins<br>    });<br>    // step 4: keep the chosen ones<br>    let mut last_end = 0;<br>    for (token_type, start, end) in match_vec {<br>        if start &lt; last_end {<br>            continue; // skip overlapping tokens<br>        }<br>        last_end = end;<br>        let lexeme = &amp;current_input[start..end];<br>        token_vec.push(Token::get_token(token_type, Some(lexeme)));<br>    }<br>    // step 5: return the loot bag<br>    token_vec<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/0*XRmjPgREK8649ulO.png" /></figure><p>you can dance now.</p><h3>now we write our main.rs</h3><p>ಥ‿ಥ please work please work please work</p><p>we’ll be writing our <a href="http://main.rs/">main.rs</a> to test our lexer, we need to define the code we want as a string and get results from lex_program method we wrote.</p><pre>mod lexing; // the only module we care about for now<br>use lexing::lexer::lex_program;<br>const PROGRAM: &amp;str = &quot;<br>    int x = 5;<br>    int y = 6;<br>    int z = x + y;<br>    if (z &gt; 0) {<br>        print(\&quot;hihi\&quot;);<br>    } else {<br>        print(\&quot;haha\&quot;);<br>    }<br>&quot;;<br>fn main() {<br>    println!(&quot;--- LEXING TIME ---&quot;);<br>    println!(&quot;feeding code into the lexer like it&#39;s a vending machine...\n&quot;);<br>    let tokens = lex_program(PROGRAM);<br>    println!(&quot;--- TOKENS THE LEXER SPAT OUT ---\n&quot;);<br>    for t in &amp;tokens {<br>        println!(&quot;{:?}&quot;, t);<br>    }<br>    println!(&quot;\nmission accomplished.&quot;);<br>    println!(&quot;parser, ast, semantic analysis &amp; codegen will stand outside the club until further notice.&quot;);<br>}</pre><p>write this in your main.rs file and see how it goes, <br> also remember that <strong>mod.rs</strong> file we made? <br> yeah, write</p><pre>pub mod lexer;<br>pub mod token;</pre><p>in that file to declare other 2 rust files as public files and to let main.rs file access these files and not say, tf are these.</p><p>now type cargo run and watch your lexer either work perfectly or produce errors that make you question your life choices</p><p>writing this at 5:26 am so (⌐■_■)<br>so if your code doesn’t compile, blame my sleep deprivation. <br>if you built something with this or just want to share your suffering, drop a comment. parser tutorial coming soon (i’ll have to study i forget how parsing works again).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/0*uo0aZJ6pdbh_x-ql.png" /></figure><pre>#[derive(Debug, Clone)]<br>pub enum Token {<br>    <br>    // keywords<br>    Print(String),<br>    If(String),<br>    Else(String),<br>    Int(String),<br>    Minus(String),<br>// literals<br>    IntegerLiteral(i32),<br>    StringLiteral(String),<br>    BooleanLiteral(bool),<br>    // identifiers<br>    Identifier(String),<br>    // operators <br>    Plus(String),<br>    Assign(String),<br>    <br>    // punctuation<br>    SemiColon(String),<br>    LeftParen(String),<br>    RightParen(String),<br>    LeftBrace(String),<br>    RightBrace(String),<br>    // logical operators<br>    GreaterThan(String),<br>    LessThan(String),<br>}<br>impl Token {<br>    pub fn get_token(token_type: &amp;str, value: Option&lt;&amp;str&gt;) -&gt; Token {<br>        match token_type {<br>            // keywords<br>            &quot;Print&quot; =&gt; Token::Print(&quot;print&quot;.to_string()),<br>            &quot;If&quot; =&gt; Token::If(&quot;if&quot;.to_string()),<br>            &quot;Else&quot; =&gt; Token::Else(&quot;else&quot;.to_string()),<br>            &quot;Int&quot; =&gt; Token::Int(&quot;int&quot;.to_string()),<br>            // literals<br>            &quot;IntegerLiteral&quot; =&gt; {<br>                Token::IntegerLiteral(value.unwrap().parse::&lt;i32&gt;().unwrap())<br>            }<br>            &quot;StringLiteral&quot; =&gt; {<br>                Token::StringLiteral(value.unwrap().to_string())<br>            }<br>            &quot;BooleanLiteral&quot; =&gt; {<br>                let val = match value.unwrap() {<br>                    &quot;true&quot; =&gt; true,<br>                    &quot;false&quot; =&gt; false,<br>                    _ =&gt; panic!(&quot;invalid boolean literal&quot;),<br>                };<br>                Token::BooleanLiteral(val)<br>            }<br>            // identifiers<br>            &quot;Identifier&quot; =&gt; Token::Identifier(value.unwrap().to_string()),<br>            // operators<br>            &quot;Plus&quot; =&gt; Token::Plus(&quot;+&quot;.to_string()),<br>            &quot;Minus&quot; =&gt; Token::Minus(&quot;-&quot;.to_string()),<br>            &quot;Assign&quot; =&gt; Token::Assign(&quot;=&quot;.to_string()),<br>            // punctuation<br>            &quot;SemiColon&quot; =&gt; Token::SemiColon(&quot;;&quot;.to_string()),<br>            &quot;LeftParen&quot; =&gt; Token::LeftParen(&quot;(&quot;.to_string()),<br>            &quot;RightParen&quot; =&gt; Token::RightParen(&quot;)&quot;.to_string()),<br>            &quot;LeftBrace&quot; =&gt; Token::LeftBrace(&quot;{&quot;.to_string()),<br>            &quot;RightBrace&quot; =&gt; Token::RightBrace(&quot;}&quot;.to_string()),<br>            // logical operators<br>            &quot;GreaterThan&quot; =&gt; Token::GreaterThan(&quot;&gt;&quot;.to_string()),<br>            &quot;LessThan&quot; =&gt; Token::LessThan(&quot;&lt;&quot;.to_string()),<br>            _ =&gt; panic!(&quot;invalid token type {}&quot;, token_type),<br>        }<br>    }<br>    pub fn get_token_regex(token_type: &amp;str) -&gt; String {<br>        match token_type {<br>            // keywords<br>            &quot;Print&quot; =&gt; r&quot;print&quot;,<br>            &quot;If&quot; =&gt; r&quot;if&quot;,<br>            &quot;Else&quot; =&gt; r&quot;else&quot;,<br>            &quot;Int&quot; =&gt; r&quot;int\s+&quot;,<br>            // literals<br>            &quot;IntegerLiteral&quot; =&gt; r&quot;\d+&quot;,<br>            &quot;StringLiteral&quot; =&gt; r#&quot;\&quot;.*\&quot;&quot;#,<br>            &quot;BooleanLiteral&quot; =&gt; r&quot;\b(?:true|false)\b&quot;,<br>            // identifiers<br>            &quot;Identifier&quot; =&gt; r&quot;[a-zA-Z_][a-zA-Z0-9_]*&quot;,<br>            // operators<br>            &quot;Plus&quot; =&gt; r&quot;\+&quot;,<br>            &quot;Minus&quot; =&gt; r&quot;-&quot;,<br>            &quot;Assign&quot; =&gt; r&quot;=&quot;,<br>            // punctuation<br>            &quot;SemiColon&quot; =&gt; r&quot;;&quot;,<br>            &quot;LeftParen&quot; =&gt; r&quot;\(&quot;,<br>            &quot;RightParen&quot; =&gt; r&quot;\)&quot;,<br>            &quot;LeftBrace&quot; =&gt; r&quot;\{&quot;,<br>            &quot;RightBrace&quot; =&gt; r&quot;\}&quot;,<br>            // logical operators<br>            &quot;GreaterThan&quot; =&gt; r&quot;&gt;&quot;,<br>            &quot;LessThan&quot; =&gt; r&quot;&lt;&quot;,<br>            _ =&gt; panic!(&quot;invalid token type: {}&quot;, token_type),<br>        }.to_string()<br>    }<br>}</pre><pre>lexer.rs<br>use regex::Regex;<br>use crate::lexing::token::Token;<br>pub fn lex_program(program: &amp;str) -&gt; Vec&lt;Token&gt; {<br>    let current_input = program;<br>    let tokens = [<br>        // keywords<br>        &quot;Print&quot;,<br>        &quot;If&quot;,<br>        &quot;Else&quot;,<br>        &quot;Int&quot;,<br>        // literals<br>        &quot;BooleanLiteral&quot;,<br>        &quot;IntegerLiteral&quot;,<br>        &quot;StringLiteral&quot;,<br>        // operators<br>        &quot;Plus&quot;,<br>        &quot;Minus&quot;,<br>        &quot;Assign&quot;,<br>        &quot;GreaterThan&quot;,<br>        &quot;LessThan&quot;,<br>        // punctuation<br>        &quot;LeftParen&quot;,<br>        &quot;RightParen&quot;,<br>        &quot;LeftBrace&quot;,<br>        &quot;RightBrace&quot;,<br>        &quot;SemiColon&quot;,<br>        // identifiers<br>        &quot;Identifier&quot;,<br>    ];<br>    let mut match_vec: Vec&lt;(&amp;str, usize, usize)&gt; = Vec::new();<br>    for token in tokens.iter() {<br>        let token_regex = Token::get_token_regex(token);<br>        let re = Regex::new(&amp;token_regex).unwrap();<br>        for m in re.find_iter(current_input) {<br>            match_vec.push((token, m.start(), m.end()));<br>        }<br>    }<br>    match_vec.sort_by(|a, b| {<br>        a.1.cmp(&amp;b.1)<br>            .then_with(|| (b.2 - b.1).cmp(&amp;(a.2 - a.1)))<br>    });<br>    let mut token_vec = Vec::new();<br>    let mut last_end = 0;<br>    for (token_type, start, end) in match_vec {<br>        if start &lt; last_end {<br>            continue;<br>        }<br>        last_end = end;<br>        let lexeme = &amp;current_input[start..end];<br>        token_vec.push(Token::get_token(token_type, Some(lexeme)));<br>    }<br>    token_vec<br>}</pre><h3>2. rust parser</h3><p>if you’re here after the lexer without rage quitting this shit, congrats you’re officially a masochist now. a bigger one if you enjoyed making lexer. lets give your lexer some brain cells.</p><p>what we did the last time was we created a list of stuff that can be used in your language, now we turn that list into a tree structure to give it meaning and logic. we did: [INT] [IDENTIFIER] [=] [69] [;] but compiler does not know what this means, that comes from parser, it tells them to line up in a structured sequence to form meaning.</p><h3>so what the fish does a parser do exactly? (ಠ_ಠ)</h3><p>imagine you have a sentence something like, “the fish ate the cat” lexer would be like: [the] [fish] [ate] [the] [cat].</p><p>your parser says:</p><ul><li><strong>the fish</strong> → subject</li><li><strong>ate</strong> → verb</li><li><strong>the cat</strong> → object</li></ul><p>aka it finds the grammar, not just words.</p><p>in code terms:<br>int x = 5 + 3;</p><p>lexer would say:<br>[INT, IDENTIFIER(&quot;x&quot;), ASSIGN_OP, INTEGER(5), PLUS INTEGER(3), SEMICOLON]</p><p>“this is a VARIABLE DECLARATION statement where:</p><ul><li>variable name is ‘x’</li><li>value is the result of ADDING 5 and 3</li><li>the addition is an EXPRESSION inside the declaration”</li></ul><p>parser builds a specific tree structure to form meaning. its called AST(abstract syntax tree) aka the holy tree with glorious purpose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bxg9bVzAnvwHzzyoQyMFhw.png" /></figure><p>this makes layers of structure, stuff gets nested into each other, like an onion funnily enough, this and onion both will make you cry. this is the core stuff that makes sense in your language and you can control everything from here, what gets passed and what makes sense.</p><h3>why cant we just… use tokens? (╯°□°）╯</h3><ul><li>because context matters.</li><li>x = 5 this is normal assignment</li><li>if (x = 5) { } this is also assignment (just illegal in many languages but yolo)</li><li>also operator precedence matters: 5 + 3 * 2 this should be 5 + (3 * 2) not (5 + 3) * 2 (illegal in at least 19 countries)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jBsdHgMBSGaO6BcXBIdL3g.png" /></figure><ul><li>everything is just symbols, parser understands the GRAMMAR</li></ul><h3>what we’re building today (╬ ಠ益ಠ)</h3><p>a <strong>recursive descent parser — conceptually simple, writing by hand.</strong></p><ul><li>parse_expression</li><li>which calls parse_addition</li><li>which calls parse_primary</li><li>which calls parse_expression again</li></ul><p>basically recursion until something explodes (hopefully not your laptop).</p><h3>my assumptions:</h3><ul><li>you built the lexer (or violently copy pasted it)</li><li>you know what recursion is — functions calling themselves, like inception</li><li>your self hate runs deeper than i expected</li></ul><h3>step 1: we forge ast first (づ ◕‿◕ )づ</h3><p>embrace the recursion</p><p>we need to define our tree first and in rust, we do that by god’s gift to people who hate themselves: enums.</p><p>mainly we need two types of them:</p><ul><li><strong>Expr</strong> (expressions): things that PRODUCE values<br>examples — 5, x+3, hihi</li><li><strong>Stmt</strong> (statements): things that DO stuff<br>examples — int x = 5 print(&quot;yoooooo&quot;)</li></ul><pre>5 + 3          // expression (returns 8)<br>int x = 5 + 3; // statement (declares x, contains an expression)</pre><h3>creating ast.rs (ง’̀-’́)ง</h3><pre>#[derive(Debug, Clone, PartialEq)]<br>pub enum Expr {<br>    IntegerLiteral(i32),       <br>    StringLiteral(String),     <br>    Identifier(String),        <br>    BooleanLiteral(bool),<br>Binary {<br>        left: Box&lt;Expr&gt;,<br>        op: BinOp,<br>        right: Box&lt;Expr&gt;,<br>    },<br>    Assign {<br>        name: String,<br>        value: Box&lt;Expr&gt;,<br>    },<br>}<br><br>#[derive(Debug, Clone, PartialEq)]<br>pub enum BinOp {<br>    Add,<br>    Sub,<br>    GreaterThan,<br>    LessThan,<br>}<br>#[derive(Debug, Clone, PartialEq)]<br>pub enum Stmt {<br>    Print(Expr),<br>    VarDeclaration {<br>        name: String,<br>        value: Expr,<br>    },<br>    If {<br>        condition: Expr,<br>        then_block: Vec&lt;Stmt&gt;,<br>        else_block: Option&lt;Vec&lt;Stmt&gt;&gt;,<br>    },<br>}</pre><p>make a new file in src folder by touch ast.rs then WRITE the above code. your first thought would be, tf is Box&lt;Expr&gt; ( ﾟдﾟ), rust is a control freak. and it needs to know the size before going ahead. and expressions can nest infinitely like 5 + (3 + (2 + (1 + 0))) , here each binary contains more binary expressions. rust would go like “how big is this?????”(thats what she said) and have a panic attack.</p><pre>5 + 3 * 2<br>↓ becomes ↓<br>    (+)<br>   /   \<br>  5    (*)<br>       / \<br>      3   2</pre><p>Box put data into heap and stores their pointer in stack. rust asks you how big is this and you answer dw about it, its stored in help you just take care of this pointer that points to the space all that shit is stored at.</p><p>now that we have the holy tree, we’re about to set this tree on fire with recursion</p><h3>step 2 — dissect <a href="http://parser.rs/">parser.rs</a> (⚆_⚆)</h3><p>why did we choose recursive descent parsing, you ask? because this gives the most pain, also simple to write if you understand, stuff just becomes repetitive and painful. (hahahaha)</p><h3>parser struct</h3><pre>pub struct Parser {<br>    tokens: Vec&lt;Token&gt;,<br>    position: usize,<br>}</pre><p>tokens → all of the tokens lexer produced<br>position → index of the current token.</p><p>it needs some tiny helper functions to <strong>not explode</strong>. <br>so these these functions together, as one squad</p><ul><li>current()</li><li>advance()</li><li>expect(&quot;something&quot;)</li></ul><p>because they ALWAYS work together. like the three idiots, but for compilers.</p><ol><li>current()</li></ol><pre>fn current(&amp;self) -&gt; Result&lt;&amp;Token, ParseError&gt; {<br>        self.tokens<br>            .get(self.position)<br>            .ok_or(ParseError::UnexpectedToken(<br>                &quot;unexpected end of input&quot;.into(),<br>            ))<br>    }</pre><p>this function:<br>peeks at the current token, and panicks if nothing is left</p><p>kinda like checking the fridge repeatedly hoping food magically appears.</p><p>2. advance()</p><pre>fn advance(&amp;mut self) {<br>        if self.position &lt; self.tokens.len() {<br>            self.position += 1;<br>        }<br>    }</pre><p>this checks current position of where your parser is atp and moves forward</p><p>3. expect()</p><pre>fn expect(&amp;mut self, expected: &amp;str) -&gt; Result&lt;(), ParseError&gt; {<br>    let token = self.current()?;<br>let matches = match (expected, token) {<br>        (&quot;semicolon&quot;, Token::SemiColon(_)) =&gt; true,<br>        (&quot;left_paren&quot;, Token::LeftParen(_)) =&gt; true,<br>        (&quot;right_paren&quot;, Token::RightParen(_)) =&gt; true,<br>        (&quot;left_brace&quot;, Token::LeftBrace(_)) =&gt; true,<br>        (&quot;right_brace&quot;, Token::RightBrace(_)) =&gt; true,<br>        _ =&gt; false,<br>    };<br>    if matches {<br>        self.advance();<br>        Ok(())<br>    } else {<br>        Err(ParseError::UnexpectedToken(format!(<br>            &quot;expected {}, found {:?}&quot;,<br>            expected, token<br>        )))<br>    }<br>}</pre><p>basically this function expect ; , ( , ) , { , } . if anything is missing, it gives out ParseError.</p><p>you: “i forgot the semicolon 🥺👉👈”<br>parser: <strong>“then perish.”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*v_9RhEL0ZD0iA_BeFYBUaw.png" /></figure><p>you can panic now.</p><h3>step 3: murdering statements by parsing them.</h3><p><strong>(ง🔥Д🔥)ง</strong></p><pre>pub fn parse(&amp;mut self) -&gt; Result&lt;Vec&lt;Stmt&gt;, ParseError&gt; {<br>    let mut statements = Vec::new();<br>    while self.position &lt; self.tokens.len() {<br>        statements.push(self.parse_statement()?);<br>    }<br>    Ok(statements)<br>}</pre><p>this is the main loop, all this does is it keeps reading tokens until it runs out of them or willpower. it pushes all the statements it has parsed and keeps moving forward.<br>every statement becomes an ast node, every ast node becomes a little part of your coping mechanism.</p><p>now we are officially entering land of panic attacks<br>“what the hell does this line of code even WANT?”</p><h3>- parse_statements:</h3><pre>fn parse_statement(&amp;mut self) -&gt; Result&lt;Stmt, ParseError&gt; {<br>    let token = self.current()?;<br>match token {<br>        Token::Print(_) =&gt; self.parse_print(),<br>        Token::If(_)    =&gt; self.parse_if(),<br>        Token::Int(_)   =&gt; self.parse_var_declaration(),<br>        _ =&gt; Err(ParseError::UnexpectedToken(<br>            format!(&quot;expected statement, found {:?}&quot;, token)<br>        )),<br>    }<br>}</pre><p>this parses your statements, checks 3 tokens, print if int , nothing else gets parsed. your parser becomes that annoying english correcting friend whose whole existence is correcting everyone’s grammar.</p><pre>they be super strict.<br>              +-----------------------+<br>              |   parser bouncer      |<br>              +-----------------------+<br>              |   PRINT?     yes ---&gt; |<br>              |   IF?        yes ---&gt; |<br>              |   INT?       yes ---&gt; |<br>              |   anything else?      |<br>              |              DENIED   |<br>              +-----------------------+</pre><h3>- parse print : everybody&#39;s fav child (◕‿◕)</h3><pre>fn parse_print(&amp;mut self) -&gt; Result&lt;Stmt, ParseError&gt; {<br>    self.advance(); // consume &quot;print&quot;<br>    self.expect(&quot;left_paren&quot;)?;<br>    let expr = self.parse_expression()?;<br>    self.expect(&quot;right_paren&quot;)?;<br>    self.expect(&quot;semicolon&quot;)?;<br>    Ok(Stmt::Print(expr))<br>}</pre><p>your parser’s easiest job, it just has to check the left bracket, right bracket and unfortunate semicolon.<br>and if anything goes missing, it collapses on the floor with its last words as <br>“WHERE. IS. MY. SEMICOLON.”</p><h3>- parse variable declaration:</h3><pre>fn parse_var_declaration(&amp;mut self) -&gt; Result&lt;Stmt, ParseError&gt; {<br>    self.advance(); // consume &quot;int&quot;<br>let name = match self.current()? {<br>        Token::Identifier(id) =&gt; id.clone(),<br>        _ =&gt; return Err(ParseError::UnexpectedToken(&quot;expected identifier after int&quot;.into())),<br>    };<br>    self.advance(); // consume identifier<br>    match self.current()? {<br>        Token::Assign(_) =&gt; self.advance(),<br>        _ =&gt; return Err(ParseError::UnexpectedToken(&quot;expected &#39;=&#39; in variable declaration&quot;.into())),<br>    };<br>    let value = self.parse_expression()?;<br>    self.expect(&quot;semicolon&quot;)?;<br>    Ok(Stmt::VarDeclaration { name, value })<br>}</pre><p>this function is literally a checklist:</p><ul><li>did you write int?</li><li>DID YOU NAME YOUR VARIABLE???</li><li>did you put =?</li><li>did you assign something?</li><li>did you END IT with a semicolon like a civilized human being?</li><li>did you cry, doesnt matter.</li></ul><pre>int x  =  5    ;<br>    ^  ^  ^    ^<br>    |  |   |   |<br>    |  |   |   expected semicolon<br>    |  |   expected expression<br>    |  expected &#39;=&#39;<br>    expected identifier</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZBpOkMjUE0O-CSodd-ltrA.png" /><figcaption>you couch banana</figcaption></figure><h3>- parsing if statements</h3><pre>fn parse_if(&amp;mut self) -&gt; Result&lt;Stmt, ParseError&gt; {<br>    self.advance(); // consume &quot;if&quot;<br>self.expect(&quot;left_paren&quot;)?;<br>    let condition = self.parse_expression()?;<br>    self.expect(&quot;right_paren&quot;)?;<br>    self.expect(&quot;left_brace&quot;)?;<br>    let then_block = self.parse_block()?;<br>    self.expect(&quot;right_brace&quot;)?;<br>    let else_block = if matches!(self.current(), Ok(Token::Else(_))) {<br>        self.advance(); // consume &quot;else&quot;<br>        self.expect(&quot;left_brace&quot;)?;<br>        let block = self.parse_block()?;<br>        self.expect(&quot;right_brace&quot;)?;<br>        Some(block)<br>    } else {<br>        None<br>    };<br>    Ok(Stmt::If {<br>        condition,<br>        then_block,<br>        else_block,<br>    })<br>}</pre><p>you forgot a brace? funny<br>now i will have to kill you</p><p>parse_if:</p><p>-&gt; reads conditions, goes to then_block, goes to else_block when required and builds your ast piece by piece while you wave goodbye to your peace.</p><pre>if (x &gt; 5) {<br>   print(&quot;yay&quot;);<br>} else {<br>   print(&quot;pain&quot;);<br>}</pre><pre>THE HOLY TREE <br>IF<br>├── condition (x &gt; 5)<br>├── then_block<br>│      └── print(&quot;yay&quot;)<br>└── else_block<br>       └── print(&quot;pain&quot;)</pre><h3>parse_block: PTSD</h3><pre>fn parse_block(&amp;mut self) -&gt; Result&lt;Vec&lt;Stmt&gt;, ParseError&gt; {<br>    let mut statements = Vec::new();<br>while let Ok(token) = self.current() {<br>        if matches!(token, Token::RightBrace(_)) {<br>            break;<br>        }<br>        statements.push(self.parse_statement()?);<br>    }<br>    Ok(statements)<br>}</pre><p>this just keeps running until it sees a } .<br>nothing fancy, just pain.</p><h3>step 4 — final boss battle: EXPRESSIONS (╥﹏╥)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*wJWOmdQGs9CWdhteBJmbQA.png" /></figure><p>this is where your parser starts calling functions, who call other functions, who call other function and so on.</p><p>they go by a hierarchy,</p><pre>expression<br>    └── assignment<br>            └── comparison<br>                    └── addition/subtraction<br>                                └── primary<br>   its like a food chain of trauma</pre><p>if you screw this order, congrats.</p><h3>- parse_expreisson</h3><pre>fn parse_expression(&amp;mut self) -&gt; Result&lt;Expr, ParseError&gt; {<br>    self.parse_assignment()<br>}</pre><p>this is literally useless, it just exists because everyone else calls it, also because we need a fixed entry point for recursion loop.<br>its like a receptionist who pretends to do work.</p><h3>- parse_assignment (屮ﾟДﾟ)屮</h3><pre>fn parse_assignment(&amp;mut self) -&gt; Result&lt;Expr, ParseError&gt; {<br>        let left = self.parse_comparison()?;<br>if matches!(self.current(), Ok(Token::Assign(_))) {<br>            self.advance(); // consume &#39;=&#39;<br>            let value = self.parse_assignment()?; // right-associative<br>            if let Expr::Identifier(name) = left {<br>                return Ok(Expr::Assign {<br>                    name,<br>                    value: Box::new(value),<br>                });<br>            } else {<br>                return Err(ParseError::UnexpectedToken(<br>                    &quot;left side of assignment must be an identifier&quot;.into(),<br>                ));<br>            }<br>        }<br>        Ok(left)<br>    }</pre><p>the character arc of your parser, it becomes a math, grammar teacher and your parent all at once. <br>it enforces you to put identifier at left end and assignment is at right. it’ll come out of your machine and slap you.</p><pre>5 = x<br>parser: you cannot assign to 5.<br>you: but —<br>parser: YOU CANNOT ASSIGN TO 5.</pre><h3>parse_comparison - the judge and jury</h3><pre>fn parse_comparison(&amp;mut self) -&gt; Result&lt;Expr, ParseError&gt; {<br>    let mut left = self.parse_addition()?;<br>loop {<br>        let op = match self.current() {<br>            Ok(Token::GreaterThan(_)) =&gt; Some(BinOp::GreaterThan),<br>            Ok(Token::LessThan(_)) =&gt; Some(BinOp::LessThan),<br>            _ =&gt; None,<br>        };<br>        if let Some(op) = op {<br>            self.advance();<br>            let right = self.parse_addition()?;<br>            left = Expr::Binary {<br>                left: Box::new(left),<br>                op,<br>                right: Box::new(right),<br>            };<br>        } else {<br>            break;<br>        }<br>    }<br>    Ok(left)<br>}</pre><p>it only cares out &lt; and &gt;, so x &gt; 5 &lt; y becomes ((x &gt; 5 ) &lt; y)<br>this works till all the comparisons are gone</p><pre>parser: are you greater than?<br>parser: are you less than?<br>parser: are you good enough?<br>you:    no.<br>parser: correct.</pre><h3>- parse_addition</h3><pre>fn parse_addition(&amp;mut self) -&gt; Result&lt;Expr, ParseError&gt; {<br>        let mut left = self.parse_primary()?;<br>loop {<br>            let op = match self.current() {<br>                Ok(Token::Plus(_)) =&gt; Some(BinOp::Add),<br>                Ok(Token::Minus(_)) =&gt; Some(BinOp::Sub),<br>                _ =&gt; None,<br>            };<br>            if let Some(op) = op {<br>                self.advance();<br>                let right = self.parse_primary()?;<br>                left = Expr::Binary {<br>                    left: Box::new(left),<br>                    op,<br>                    right: Box::new(right),<br>                };<br>            } else {<br>                break;<br>            }<br>        }<br>        Ok(left)<br>    }</pre><p>math lasagna. if there is + or - , you’re good to go else parser’s gonna lynch you in your sleep. this fn keeps left-associativity, meaning if 6 + 9 + 0 it takes ( 6 + 9 ) + 0</p><h3>- parse_primary: bottom of your food chain</h3><pre>fn parse_primary(&amp;mut self) -&gt; Result&lt;Expr, ParseError&gt; {<br>    let token = self.current()?.clone();<br>    self.advance();<br>    <br>    match token {<br>        Token::IntegerLiteral(n) =&gt; Ok(Expr::IntegerLiteral(n)),<br>        Token::StringLiteral(s) =&gt; Ok(Expr::StringLiteral(s)),<br>        Token::BooleanLiteral(b) =&gt; Ok(Expr::BooleanLiteral(b)),<br>        Token::Identifier(id) =&gt; Ok(Expr::Identifier(id)),<br>        <br>        Token::LeftParen(_) =&gt; {<br>            let expr = self.parse_expression()?;  // ← THE CIRCLE COMPLETES<br>            self.expect(&quot;right_paren&quot;)?;<br>            Ok(expr)<br>        }<br>        <br>        _ =&gt; Err(ParseError::UnexpectedToken(format!(<br>            &quot;expected expression, found {:?}&quot;,<br>            token<br>        ))),<br>    }<br>}</pre><p>it handles: literals, identifiers, parenthesis, <br>this will explode your machine if anything goes wrong.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*CMZSDYeijELMYUx7u9f0Xg.png" /></figure><h3>finally the event we all waited for,</h3><p>TIME TO CHECK THIS monstrosity (◕‿◕)</p><p>create src/parsing/mod.rs</p><pre>pub mod parser;</pre><p>and update your main.rs by</p><pre>mod lexing;<br>mod parsing;<br>mod ast;<br>use lexing::lexer::lex_program;<br>use parsing::parser::Parser;<br>const PROGRAM: &amp;str = &quot;<br>int x = 5;<br>int y = 6;<br>int z = x + y;<br>if (z &gt; 10) {<br>    print(\\&quot;hihi\\&quot;);<br>} else {<br>    print(\\&quot;haha\\&quot;);<br>}<br>&quot;;<br>fn main() {<br>    println!(&quot;lexing &quot;);<br>    let tokens = lex_program(PROGRAM);<br>    println!(&quot;tokens: {}\\n&quot;, tokens.len());<br>    <br>    println!(&quot; parsing &quot;);<br>    let mut parser = Parser::new(tokens);<br>    <br>    match parser.parse() {<br>        Ok(ast) =&gt; {<br>            println!(&quot; IT FUCKING WORKS \\n&quot;);<br>            for (i, stmt) in ast.iter().enumerate() {<br>                println!(&quot;statement {}:&quot;, i + 1);<br>                println!(&quot;{:#?}\\n&quot;, stmt);<br>            }<br>        }<br>        Err(e) =&gt; {<br>            println!(&quot; PARSE ERROR &quot;);<br>            println!(&quot;{:?}&quot;, e);<br>        }<br>    }<br>}</pre><p>now rn this is a very crucial moment, once you do cargo run you machine can explode this instant. carefully type cargo run</p><p>if it gives out this, viola you are eligible for next circle of hell</p><p>and thats it.<br>meet me on the next part for more mental harassment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*0gZYrLiKAX8JdMAIUxTN-g.png" /></figure><h3>semantic analyzer in rust.</h3><p>so uh … you are here, doing this, even after the lexer and parser, without throwing your laptop, nice. you’re clinically insane.</p><p>here we are giving a logical brain to your compiler, so it can perform better than you.<br>parser was helping us to make our code LOOK right, here we are helping it to detect SENSE in your language. what a tragic moment for all of us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*lT96LclIccE3uJTPeelf8g.png" /></figure><h3>what actually is semantic analysis?</h3><p>imagine you write:</p><p>int x = &quot;heheheha&quot;;</p><p>your parser would be like, yeah a space after int, an identifier after it, then an assignment after that, then whatever you write, then a semicolon, all checks are good and clear. but semantic analyzer would stab you in your stomach.</p><h3>crimes we are preventing today:</h3><p>┏(ಠ‿ಠ)┛BRING OUT THE CRIME LIST┗(ಠ‿ಠ)┓</p><ul><li>crime #1 identity fraud (undeclared variables): print(x); // x??? WHO THE FUCK IS X??? i have never seen this man in my life.</li><li>crime #2 personality disorder (type confusion): int x = 5; x = &quot;now i am a string lol&quot; go to jail.</li><li>crime #3 clone wars (redeclaration): int x = 69; int x = 420;</li><li>crime #4 if-statements with non-boolean conditions: if (69) { print(&quot;hihi&quot;) }</li></ul><h3>what we are building: unholy contraption.</h3><ul><li>a <strong>symbol table,</strong> keeps check of all variables declared and their types</li><li>a <strong>scope stack</strong>, things born inside if blocks should stay there and die there.</li><li><strong>type checker</strong>: annoying person correcting everyone</li><li><strong>error collector</strong>: a trauma diary for broken code</li></ul><h3>my assumptions:</h3><ul><li>your sanity is about to fall off a cliff</li><li>you MADE that parser</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*tIUm_XA_1tmO2JN8q3IpdQ.png" /></figure><h3>lets start hunting that demon (҂◡_◡)</h3><h3>step 1: types and errors</h3><p>make a new file of analyzer.rs and start typing out the possible enums here:</p><pre>pub enum Type {<br>    Int,<br>    String,<br>    Bool,<br>    Unknown,<br>}</pre><p>unknown just for, you know unknowns.</p><p><strong># defining errors, four horsemen of death.</strong></p><p>here you get a chance to curse people for breaking their code, also to do illegal shit</p><pre>pub enum SemanticError {<br>    UndeclaredVariable(String),<br>    Redeclaration(String),<br>    InvalidAssignmentTarget(String),<br>    TypeMismatch { expected: Type, found: Type, context: String },<br>}</pre><p>you may think there can be any kind of error in whole code, anything can break, but we can cover them in this umbrella by these 4 errors, these are the crimes we were preventing above. unfortunately you dont come under this.</p><h3>step 2: that semantic analyzer struct.</h3><p>this is gonna hold all of your symbols and errors.</p><pre>pub struct SemanticAnalyzer {<br>    scopes: Vec&lt;HashMap&lt;String, Type&gt;&gt;,<br>    errors: Vec&lt;SemanticError&gt;,<br>}</pre><p>scopes is the symbol table we were talking about to keep track of everything. and errors to keep them in check and sort stuff out.</p><p><strong># errors</strong>: we’re not rage quitting at the first error like a COWARD. we’re collecting EVERY SINGLE mistake you made because if you’re gonna fail, fail GLORIOUSLY with a full fucking essay of what you did wrong.</p><pre>you: writes code<br>analyzer: &quot;hmm. interesting. *scribbles notes* continue.&quot;<br>you: *makes mistake*<br>analyzer: &quot;noted. keep going.&quot;<br>you: *makes 47 more mistakes*<br>analyzer: &quot;okay so here&#39;s a list of everything wrong with your life choices&quot;</pre><h3>step 3: managing scopes, circle of life and death.</h3><pre>impl SemanticAnalyzer {<br>    pub fn new() -&gt; Self {<br>        SemanticAnalyzer {<br>            scopes: vec![HashMap::new()], // global scope<br>            errors: Vec::new(),<br>        }<br>    }<br>fn enter_scope(&amp;mut self) {<br>        self.scopes.push(HashMap::new());<br>    }<br>    fn exit_scope(&amp;mut self) {<br>        if self.scopes.len() &gt; 1 {<br>            self.scopes.pop();<br>        }<br>    }<br>}</pre><p>here we implement on the struct we made and tell our code to make a new hashmap for every scope you find and enter that hashmap when you see an if then kill that hashmap whenever you see a } . variables declared in that block - <strong>gone. dead. poof.</strong> just like your will to live.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*Mp7l1joyWE_4QRSMM9Fujw.png" /></figure><pre>┌─────────────────────────────┐<br>│   global scope (immortal)   │ this is how layered your code looks <br>│  ┌───────────────────────┐  │ only the shogun survives. i mean global. <br>│  │   if block scope      │  │<br>│  │  ┌─────────────────┐  │  │<br>│  │  │ nested if scope │  │  │<br>│  │  │  variables here │  │  │<br>│  │  │  die when } hit │  │  │<br>│  │  └─────────────────┘  │  │<br>│  │   these die too  ☠️   │  │<br>│  └───────────────────────┘  │<br>│   only global survives      │<br>└─────────────────────────────┘</pre><h3>step 4: looking up variables — search party</h3><pre>fn lookup_variable(&amp;self, name: &amp;str) -&gt; Option&lt;Type&gt; {<br>    for scope in self.scopes.iter().rev() {<br>        if let Some(t) = scope.get(name) {<br>            return Some(t.clone());<br>        }<br>    }<br>    None<br>}</pre><p>this goes from inner scope to outer scope for finding variables just like how you sit and cry about how you failed, then you start remembering everytime it happened and you realize you are a failure. just like that we start small then go to the global scope eventually.</p><p>and by this ↓ method you can also add variables to current scopes by declaring them ↓</p><pre>fn declare_variable(&amp;mut self, name: &amp;str, var_type: Type) -&gt; bool {<br>    let current_scope = self.scopes.last_mut().expect(&quot;always at least one scope&quot;);<br>    if current_scope.contains_key(name) {<br>        return false; // already exists, crime detected<br>    }<br>    current_scope.insert(name.to_string(), var_type);<br>    true<br>}</pre><h3>step 5: checking statements — THE INTERROGATION (ง🔥Д🔥)ง</h3><pre>fn check_statement(&amp;mut self, stmt: &amp;Stmt) {<br>    match stmt {<br>        Stmt::VarDeclaration { name, value } =&gt; {<br>            self.check_var_declaration(name, value);<br>        }<br>        Stmt::Print(expr) =&gt; {<br>            let _ = self.check_expression(expr);<br>        }<br>        Stmt::If { condition, then_block, else_block } =&gt; {<br>            self.check_if_statement(condition, then_block, else_block);<br>        }<br>    }<br>}</pre><p>here we are just checking statements before passing them to the next step which can be either of these: it can be a variable, a print statement or an if statement and if its an if statement, it would be of 3 things: the main condition, then then then-block, then maybe an else-block whenever needed, but here we are simplifying how many types of statements there are gonna be in our language</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*XTE0pep9DvelVGcRAXTkVg.png" /></figure><h3>variable declarations:</h3><pre>fn check_var_declaration(&amp;mut self, name: &amp;str, value: &amp;Expr) {<br>    // check if already declared in current scope<br>    let current_scope = self.scopes.last().expect(&quot;at least one scope&quot;);<br>    if current_scope.contains_key(name) {<br>        self.add_error(SemanticError::Redeclaration(name.to_string()));<br>        return;<br>    }<br>let value_type = self.check_expression(value);<br>    let declared_type = Type::Int; // we only support int declarations<br>    // type mismatch?<br>    if value_type != Type::Unknown &amp;&amp; value_type != declared_type {<br>        self.add_error(SemanticError::TypeMismatch {<br>            expected: declared_type.clone(),<br>            found: value_type,<br>            context: format!(&quot;initializer for &#39;{}&#39; must be Int&quot;, name),<br>        });<br>    }<br>    // declare it anyway (for error recovery)<br>    let current_scope_mut = self.scopes.last_mut().expect(&quot;at least one scope&quot;);<br>    current_scope_mut.insert(name.to_string(), declared_type);<br>}</pre><p>this is first of 3 different outcomes we said, declaring a variable, i scammed you all by saying this would be a simple project because haha, look at it</p><pre>analyzer: &quot;you declaring something?&quot;<br>you: &quot;yeah, int x = 5&quot;<br>analyzer: &quot;x already exist?&quot;<br>you: &quot;no&quot;<br>analyzer: &quot;you putting an INT in an INT variable?&quot;<br>you: &quot;yes&quot;<br>analyzer: &quot;...fine. you may pass.&quot;you: &quot;int x = &#39;chaos&#39;&quot;<br>analyzer: &quot;you putting a STRING in an INT variable??&quot;<br>you: &quot;maybe&quot;<br>analyzer: &quot;WRITE THAT DOWN WRITE THAT DOWN&quot; *adds to error list*</pre><h3># if statements with scopes:</h3><p>(ಥ_ಥ) here lies your temporary variables</p><pre>fn check_if_statement(&amp;mut self, condition: &amp;Expr, then_block: &amp;[Stmt], else_block: &amp;Option&lt;Vec&lt;Stmt&gt;&gt;) {<br>    let cond_type = self.check_expression(condition);<br>    <br>    // condition must be boolean<br>    if cond_type != Type::Bool &amp;&amp; cond_type != Type::Unknown {<br>        self.add_error(SemanticError::TypeMismatch {<br>            expected: Type::Bool,<br>            found: cond_type,<br>            context: &quot;if condition must be boolean&quot;.to_string(),<br>        });<br>    }<br>// then block with new scope<br>    self.enter_scope();<br>    for stmt in then_block {<br>        self.check_statement(stmt);<br>    }<br>    self.exit_scope();<br>    // else block if exists<br>    if let Some(else_stmts) = else_block {<br>        self.enter_scope();<br>        for stmt in else_stmts {<br>            self.check_statement(stmt);<br>        }<br>        self.exit_scope();<br>    }<br>}</pre><p>things get brutal here its like</p><pre>if block: &quot;hello&quot;<br>variable y: &quot;hi i&#39;m alive!&quot;<br>} // &lt;- this bracket is an EXECUTION<br>variable y: *ceases to exist*<br>you outside the block: &quot;hey y where&#39;d you go&quot;<br>analyzer: &quot;y is DEAD. you KILLED them. how does that make you feel?&quot;</pre><h3>step 6: expressions — recursion hell</h3><p>it was fun and games until now now you will feel true hell</p><pre>left side → am I valid?<br>right side → am I valid?<br>together → are we compatible or will we create an abomination?</pre><p><strong># the function that starts all the chaos: expressions</strong></p><pre>fn check_expression(&amp;mut self, expr: &amp;Expr) -&gt; Type {<br>        match expr {<br>            Expr::IntegerLiteral(_) =&gt; Type::Int,<br>            Expr::StringLiteral(_) =&gt; Type::String,<br>            Expr::BooleanLiteral(_) =&gt; Type::Bool, // &lt;- handle boolean literals<br>            Expr::Identifier(name) =&gt; self.check_identifier(name),<br>            Expr::Binary { left, op, right } =&gt; self.check_binary_expression(left, op, right),<br>            Expr::Assign { name, value } =&gt; self.check_assignment(name, value),<br>        }<br>    }</pre><p>this is the sorting hat of harry potter</p><p>hmm, integer? INT HOUSE. string? STRING HOUSE. this identifier doesn’t exist? AZKABAN. (these banned identifiers went on to become death eaters.)</p><h3>identifiers — the who are you check</h3><pre>fn check_identifier(&amp;mut self, name: &amp;str) -&gt; Type {<br>    match self.lookup_variable(name) {<br>        Some(t) =&gt; t,<br>        None =&gt; {<br>            self.add_error(SemanticError::UndeclaredVariable(name.to_string()));<br>            Type::Unknown // shrug emoji<br>        }<br>    }<br>}</pre><p>this function grabs you by your hair to look at you and scans your face, and throws you far away if it doesnt recognizes you aka no proof of your birth, undeclared variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*LcdTCi6PU5Y5EYTq6GY4LQ.png" /></figure><h3>expression checking (‡▼益▼):</h3><p>this is the place where your compiler looks at your code like a disappointed parent.</p><pre>fn check_binary_expression(&amp;mut self, left: &amp;Expr, op: &amp;BinOp, right: &amp;Expr) -&gt; Type {<br>        let left_type = self.check_expression(left);<br>        let right_type = self.check_expression(right);<br>match op {<br>            BinOp::Add =&gt; {<br>                if left_type == Type::Int &amp;&amp; right_type == Type::Int {<br>                    Type::Int<br>                } else if left_type == Type::String &amp;&amp; right_type == Type::String {<br>                    Type::String<br>                } else {<br>                    self.add_error(SemanticError::TypeMismatch {<br>                        expected: left_type.clone(), // not perfect but informative<br>                        found: right_type.clone(),<br>                        context: &quot;addition requires both sides to have the same type (Int+Int or String+String)&quot;.to_string(),<br>                    });<br>                    Type::Unknown<br>                }<br>            }<br>            BinOp::Sub =&gt; {<br>                if left_type == Type::Int &amp;&amp; right_type == Type::Int {<br>                    Type::Int<br>                } else {<br>                    self.add_error(SemanticError::TypeMismatch {<br>                        expected: Type::Int,<br>                        found: if left_type != Type::Int { left_type.clone() } else { right_type.clone() },<br>                        context: &quot;subtraction requires both operands to be Int&quot;.to_string(),<br>                    });<br>                    Type::Unknown<br>                }<br>            }<br>            BinOp::GreaterThan | BinOp::LessThan =&gt; {<br>                if left_type == Type::Int &amp;&amp; right_type == Type::Int {<br>                    Type::Bool<br>                } else {<br>                    self.add_error(SemanticError::TypeMismatch {<br>                        expected: Type::Int,<br>                        found: if left_type != Type::Int { left_type.clone() } else { right_type.clone() },<br>                        context: &quot;comparison requires both sides to be Int&quot;.to_string(),<br>                    });<br>                    Type::Unknown<br>                }<br>            }<br>        }<br>    }</pre><p><strong>/// binary expression rules:</strong> add: int+int -&gt; Int ; string+string -&gt; String sub: int-int -&gt; Int, greater/less: int op int -&gt; bool,</p><pre>Add:<br>    69 + 420 → nice → Int<br>    &quot;hi&quot; + &quot;hi&quot; → emotional support → String<br>    5 + &quot;lol&quot; → I KNEW YOU WERE RETARDED BUT THIS → error<br>Sub:<br>    only for ints like NORMAL PEOPLE <br>    “apple” - “banana” → rot in jail<br>Comparisons:<br>    5 &gt; 3 → Bool<br>    “banana” &gt; 5 → philosophically interesting, but illegal<br>    (ಠ_ಠ) ...bro be for real</pre><h3>assignment checking:</h3><pre>fn check_assignment(&amp;mut self, name: &amp;str, value: &amp;Expr) -&gt; Type {<br>    // does this variable even EXIST<br>    let var_type = match self.lookup_variable(name) {<br>        Some(t) =&gt; t,<br>        None =&gt; {<br>            self.add_error(SemanticError::UndeclaredVariable(name.to_string()));<br>            return Type::Unknown;<br>        }<br>    };<br>let value_type = self.check_expression(value);<br>    // types better MATCH<br>    if value_type != Type::Unknown &amp;&amp; var_type != value_type {<br>        self.add_error(SemanticError::TypeMismatch {<br>            expected: var_type.clone(),<br>            found: value_type.clone(),<br>            context: format!(&quot;cannot assign {:?} to variable &#39;{}&#39; of type {:?}&quot;, <br>                           value_type, name, var_type),<br>        });<br>    }<br>    <br>    value_type<br>}</pre><p>this code checks if you are changing types in the middle, like every other teenager finding a new gender and becoming a banana. “dad i am a string now”, ”NO YOU ARE NOT, YOU ARE AN INT, I DID NOT RAISE YOU TO BECOME A STRING”</p><p><strong>now finally, last step the part where i enjoy the most, seeing you all cry while your code doesnt work.</strong></p><h3>testing your code</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*-mG5vJ0KQv-Ev9GPRGNuJQ.png" /></figure><h3>update your main.rs with this code</h3><pre>mod lexing;<br>mod parsing;<br>mod ast;<br>mod semantic;<br><br>use lexing::lexer::lex_program;<br>use parsing::parser::Parser;<br>use semantic::SemanticAnalyzer;<br><br>const PROGRAM: &amp;str = &quot;<br>int x = 5;<br>int y = 6;<br>int z = x + y;<br>if (z &gt; 10) {<br>    print(\\&quot;hihi\\&quot;);<br>} else {<br>    print(\\&quot;haha\\&quot;);<br>}<br>&quot;;<br>fn main() {<br>    println!(&quot; lexing &quot;);<br>    let tokens = lex_program(PROGRAM);<br>    println!(&quot;tokens: {}&quot;, tokens.len());<br>    <br>    println!(&quot;\\n parsing &quot;);<br>    let mut parser = Parser::new(tokens);<br>    let ast = match parser.parse() {<br>        Ok(ast) =&gt; {<br>            println!(&quot; it works &quot;);<br>            ast<br>        }<br>        Err(e) =&gt; {<br>            println!(&quot; parse error: {:?}&quot;, e);<br>            return;<br>        }<br>    };<br>    <br>    println!(&quot;\\nsemantic analysis (the moment of truth) &quot;);<br>    let mut analyzer = SemanticAnalyzer::new();<br>    match analyzer.analyze(&amp;ast) {<br>        Ok(_) =&gt; {<br>            println!(&quot; no semantic errors &quot;);<br>            println!(&quot;holy shit your code actually makes sense&quot;);<br>            println!(&quot;i&#39;m genuinely impressed&quot;);<br>        }<br>        Err(errors) =&gt; {<br>            println!(&quot; semantic errors (told you so) \\n&quot;);<br>            for (i, err) in errors.iter().enumerate() {<br>                println!(&quot;ERROR #{}: {:?}\\n&quot;, i + 1, err);<br>            }<br>            println!(&quot;fix your shit and come back&quot;);<br>        }<br>    }<br>}</pre><p>test it w some intentional broken code for tears.</p><pre>const PROGRAM: &amp;str = &quot;<br>int x = 5;<br>int x = 10;          // CLONE DETECTED<br>print(y);            // WHO TF IS Y<br>int z = \\&quot;hello\\&quot;;   // STRING IN INT CONTAINER<br>if (69) {            // 69 IS NOT A BOOLEAN<br>    print(\\&quot;nice\\&quot;);<br>}<br>x = \\&quot;chaos\\&quot;;       // TYPE SWITCH MID PROGRAM<br>&quot;;</pre><p>and see your analyzer throw daggers at you</p><h3>next part is gonna be a short part, making an optimizer for your code to make it more efficient,</h3><p>this wont be an industry level one, a basic one that gets the job done.</p><p>until next time.</p><pre>semantic.rs <br>use std::collections::HashMap;<br>use crate::ast::{Expr, Stmt, BinOp};<br>// types supported by the language<br>#[derive(Debug, Clone, PartialEq)]<br>pub enum Type {<br>    Int,<br>    String,<br>    Bool,<br>    Unknown,<br>}<br>#[derive(Debug, Clone)]<br>pub enum SemanticError {<br>    UndeclaredVariable(String),<br>    Redeclaration(String),<br>    InvalidAssignmentTarget(String),<br>    TypeMismatch {<br>        expected: Type,<br>        found: Type,<br>        context: String,<br>    },<br>}<br>// the semantic analyzer holds scopes (a stack of symbol tables) and collected errors<br>pub struct SemanticAnalyzer {<br>    scopes: Vec&lt;HashMap&lt;String, Type&gt;&gt;,<br>    errors: Vec&lt;SemanticError&gt;,<br>}<br>impl SemanticAnalyzer {<br>    pub fn new() -&gt; Self {<br>        SemanticAnalyzer {<br>            scopes: vec![HashMap::new()], // global scope<br>            errors: Vec::new(),<br>        }<br>    }<br>    fn enter_scope(&amp;mut self) {<br>        self.scopes.push(HashMap::new());<br>    }<br>    fn exit_scope(&amp;mut self) {<br>        if self.scopes.len() &gt; 1 {<br>            self.scopes.pop();<br>        }<br>    }<br>    // lookup variable from innermost to outermost scope<br>    fn lookup_variable(&amp;self, name: &amp;str) -&gt; Option&lt;Type&gt; {<br>        for scope in self.scopes.iter().rev() {<br>            if let Some(t) = scope.get(name) {<br>                return Some(t.clone());<br>            }<br>        }<br>        None<br>    }<br>    // declare a variable in the innermost scope<br>    fn declare_variable(&amp;mut self, name: &amp;str, var_type: Type) -&gt; bool {<br>        let current_scope = self.scopes.last_mut().expect(&quot;always at least one scope&quot;);<br>        if current_scope.contains_key(name) {<br>            return false;<br>        }<br>        current_scope.insert(name.to_string(), var_type);<br>        true<br>    }<br>    fn add_error(&amp;mut self, err: SemanticError) {<br>        self.errors.push(err);<br>    }<br>    // analyze a list of statements (program), eturns Ok if no semantic errors; otherwise returns the errors.<br>    pub fn analyze(&amp;mut self, statements: &amp;[Stmt]) -&gt; Result&lt;(), Vec&lt;SemanticError&gt;&gt; {<br>        for stmt in statements {<br>            self.check_statement(stmt);<br>        }<br>        if self.errors.is_empty() {<br>            Ok(())<br>        } else {<br>            Err(self.errors.clone())<br>        }<br>    }<br>    // single entry for statements<br>    fn check_statement(&amp;mut self, stmt: &amp;Stmt) {<br>        match stmt {<br>            Stmt::VarDeclaration { name, value } =&gt; {<br>                self.check_var_declaration(name, value);<br>            }<br>            Stmt::Print(expr) =&gt; {<br>                // validate expression (type returned is ignored for print)<br>                let _ = self.check_expression(expr);<br>            }<br>            Stmt::If { condition, then_block, else_block } =&gt; {<br>                self.check_if_statement(condition, then_block, else_block);<br>            }<br>        }<br>    }<br>    // handle `int name = value;` declarations<br>    // note: parser only allows `int` declarations, so we treat the declared type as `Int`<br>    fn check_var_declaration(&amp;mut self, name: &amp;str, value: &amp;Expr) {<br>        // if already declared in current scope -&gt; redeclaration error<br>        let current_scope = self.scopes.last().expect(&quot;at least one scope&quot;);<br>        if current_scope.contains_key(name) {<br>            self.add_error(SemanticError::Redeclaration(name.to_string()));<br>            return;<br>        }<br>        // evaluate initializer type<br>        let value_type = self.check_expression(value);<br>        // declared type is Int (because your parser uses `int`)<br>        let declared_type = Type::Int;<br>        // if initializer&#39;s type is known and doesn&#39;t match declared type -&gt; type mismatch<br>        if value_type != Type::Unknown &amp;&amp; value_type != declared_type {<br>            self.add_error(SemanticError::TypeMismatch {<br>                expected: declared_type.clone(),<br>                found: value_type.clone(),<br>                context: format!(&quot;initializer for &#39;{}&#39; must be {:?}&quot;, name, declared_type),<br>            });<br>        }<br>        // insert the variable into current scope with the declared type (even if initializer mismatched)<br>        // (alternatively you could skip insertion on mismatch; this choice keeps semantics stable)<br>        let current_scope_mut = self.scopes.last_mut().expect(&quot;at least one scope&quot;);<br>        current_scope_mut.insert(name.to_string(), declared_type);<br>    }<br>    // check an if statement: validate condition and check then/else blocks with their own scope<br>    fn check_if_statement(&amp;mut self, condition: &amp;Expr, then_block: &amp;[Stmt], else_block: &amp;Option&lt;Vec&lt;Stmt&gt;&gt;) {<br>        let cond_type = self.check_expression(condition);<br>        // condition must be boolean; we added Type::Bool<br>        if cond_type != Type::Bool &amp;&amp; cond_type != Type::Unknown {<br>            self.add_error(SemanticError::TypeMismatch {<br>                expected: Type::Bool,<br>                found: cond_type,<br>                context: &quot;if condition must be boolean&quot;.to_string(),<br>            });<br>        }<br>        // then block runs in its own nested scope<br>        self.enter_scope();<br>        for stmt in then_block {<br>            self.check_statement(stmt);<br>        }<br>        self.exit_scope();<br>        // else block if present<br>        if let Some(else_stmts) = else_block {<br>            self.enter_scope();<br>            for stmt in else_stmts {<br>                self.check_statement(stmt);<br>            }<br>            self.exit_scope();<br>        }<br>    }<br>    // evaluate an expression and return its inferred Type. Add errors when rules are violated.<br>    fn check_expression(&amp;mut self, expr: &amp;Expr) -&gt; Type {<br>        match expr {<br>            Expr::IntegerLiteral(_) =&gt; Type::Int,<br>            Expr::StringLiteral(_) =&gt; Type::String,<br>            Expr::BooleanLiteral(_) =&gt; Type::Bool, // &lt;- handle boolean literals<br>            Expr::Identifier(name) =&gt; self.check_identifier(name),<br>            Expr::Binary { left, op, right } =&gt; self.check_binary_expression(left, op, right),<br>            Expr::Assign { name, value } =&gt; self.check_assignment(name, value),<br>        }<br>    }<br>    // identifier usage: return type if found, otherwise add undeclared error and return Unknown.<br>    fn check_identifier(&amp;mut self, name: &amp;str) -&gt; Type {<br>        match self.lookup_variable(name) {<br>            Some(t) =&gt; t,<br>            None =&gt; {<br>                self.add_error(SemanticError::UndeclaredVariable(name.to_string()));<br>                Type::Unknown<br>            }<br>        }<br>    }<br>    /// binary expression rules:<br>    /// - add: int+int -&gt; Int ; string+string -&gt; String<br>    /// - sub: int-int -&gt; Int<br>    /// - greater/less: int op int -&gt; bool<br>    fn check_binary_expression(&amp;mut self, left: &amp;Expr, op: &amp;BinOp, right: &amp;Expr) -&gt; Type {<br>        let left_type = self.check_expression(left);<br>        let right_type = self.check_expression(right);<br>        match op {<br>            BinOp::Add =&gt; {<br>                if left_type == Type::Int &amp;&amp; right_type == Type::Int {<br>                    Type::Int<br>                } else if left_type == Type::String &amp;&amp; right_type == Type::String {<br>                    Type::String<br>                } else {<br>                    self.add_error(SemanticError::TypeMismatch {<br>                        expected: left_type.clone(), // not perfect but informative<br>                        found: right_type.clone(),<br>                        context: &quot;addition requires both sides to have the same type (Int+Int or String+String)&quot;.to_string(),<br>                    });<br>                    Type::Unknown<br>                }<br>            }<br>            BinOp::Sub =&gt; {<br>                if left_type == Type::Int &amp;&amp; right_type == Type::Int {<br>                    Type::Int<br>                } else {<br>                    self.add_error(SemanticError::TypeMismatch {<br>                        expected: Type::Int,<br>                        found: if left_type != Type::Int { left_type.clone() } else { right_type.clone() },<br>                        context: &quot;subtraction requires both operands to be Int&quot;.to_string(),<br>                    });<br>                    Type::Unknown<br>                }<br>            }<br>            BinOp::GreaterThan | BinOp::LessThan =&gt; {<br>                if left_type == Type::Int &amp;&amp; right_type == Type::Int {<br>                    Type::Bool<br>                } else {<br>                    self.add_error(SemanticError::TypeMismatch {<br>                        expected: Type::Int,<br>                        found: if left_type != Type::Int { left_type.clone() } else { right_type.clone() },<br>                        context: &quot;comparison requires both sides to be Int&quot;.to_string(),<br>                    });<br>                    Type::Unknown<br>                }<br>            }<br>        }<br>    }<br>    fn check_assignment(&amp;mut self, name: &amp;str, value: &amp;Expr) -&gt; Type {<br>        // variable must exist<br>        let var_type = match self.lookup_variable(name) {<br>            Some(t) =&gt; t,<br>            None =&gt; {<br>                self.add_error(SemanticError::UndeclaredVariable(name.to_string()));<br>                return Type::Unknown;<br>            }<br>        };<br>        let value_type = self.check_expression(value);<br>        // if value&#39;s type known and mismatches variable type -&gt; error<br>        if value_type != Type::Unknown &amp;&amp; var_type != value_type {<br>            self.add_error(SemanticError::TypeMismatch {<br>                expected: var_type.clone(),<br>                found: value_type.clone(),<br>                context: format!(&quot;cannot assign value of type {:?} to variable &#39;{}&#39; of type {:?}&quot;, value_type, name, var_type),<br>            });<br>        }<br>        value_type<br>    }<br>}</pre><h3>optimizer in rust.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*iHA21T9y7oZ59bZelNkG-g.png" /></figure><p>welcome back to this beautiful disaster you masochist, congrats on making this far. this step is like cutting your code to the bone and only keeping the most efficient parts to make it faster, smoother, better, stronger. basically we’re turning your code into a daft punk song.</p><p>your compiler becomes eren yeager.</p><h3>what actually is optimization? (ಠ_ಠ)</h3><p>suppose you have written int x = 66 + 3 , its a valid syntax everything is good but your optimizer will take this and turn it into int x = 69 so no extra runtime every time you run your code, no extra efforts or int unused = 420; int x = 5; print(x); here it will thanos snap the unused int and sadly we will have to say goodbye to our 420.</p><h3>why do we need this shit? (눈_눈)</h3><p>your CPU after optimization — (•̀ᴗ•́)و ̑̑ ah yes finally a break.</p><p>humans write readable code but machine want violent, zero bullshit code. example:</p><pre>int r = 5;<br>int pi = 3;<br>int area = pi * r * r;</pre><p>its neat math for you, but you dont want your code to perform this action everytime you run your code, it it makes the value 75 and viola, no runtime calculations, just optimized code</p><pre>BEFORE OPTIMIZATION          AFTER OPTIMIZATION</pre><pre>int x = 2 + 2;               int x = 4;<br>  int y = x + 1;               int y = 5;<br>  int unused = 69;             // gone, done, dusted. <br>  if (true) {                  print(5);<br>      print(y);<br>  }</pre><h3>illegal stuff we are avoiding -</h3><p><strong>#1 runtime math</strong> doing calculations in program rather than compile time <em>your program: let me add 66 + 3 everytime optimizer: SOMEBODY STOP THIS TORTURE.</em></p><p><strong>#2 unused variables</strong> this eliminates every dead code present <em>unused variables are like that friend in a group project who shows up once, asks what we have to do and disappears. i am that friend.</em></p><p><strong>#3 missing facts</strong>x is always 69 , so it replaces x with 69 until any other calculations</p><p><strong>#4 comparing things we already know</strong></p><pre>if (true) {<br>    print(&quot;always runs&quot;);<br>}</pre><p>its always true, so why check it everytime?</p><p>bro if (true) is ALWAYS true. processor is not your therapist. it shouldn’t have to “check” how you’re feeling every time.</p><h3>what we’re building today?</h3><p>we need:</p><ul><li><strong>constant folding</strong>: 66 + 9 = 69</li><li><strong>constant propagation</strong>: if x = 123 replaces all x with 123</li><li><strong>dead code elimination</strong>: delete unused variables</li><li><strong>algebraic simplification</strong>: x + 0 -&gt; x</li><li><strong>iterative optimization</strong>: keep optimizing until nothing changes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*1joNULCv7DpOJIzi7dSlLw.png" /></figure><h3>step 1: optimizer struct</h3><p>make an <a href="http://optimizer.rs/">optimizer.rs</a> and start writing the code now, yes, WRITING.</p><pre>use std::collections::{HashMap, HashSet};<br>use crate::ast::{Expr, Stmt, BinOp};<br>#[derive(Debug, Clone, PartialEq)]<br>pub enum ConstValue {<br>    Int(i32),<br>    String(String),<br>    Bool(bool),<br>}<br>pub struct Optimizer {<br>    constants: HashMap&lt;String, ConstValue&gt;,  // tracks known constant values<br>    used_variables: HashSet&lt;String&gt;,         // tracks which variables are used<br>}<br>// used_variables: the VIP list. if your name&#39;s not here… enjoy the trash can.</pre><p><strong>constants</strong>: a storage book that stores “this variable has this value”</p><ul><li>if x = 5 and it never changes, we store x -&gt; ConstValue::Int(5)</li><li>then we replace every x with 5. <strong>used variables:</strong> a hitlist of, “these variables are used somewhere”</li><li>if a variable is declared but never used == KILL THAT SHIT, its becomes john wick. welcome to the optimizer: where your pretty code comes to get bullied. we don’t judge we just remove everything you love.</li></ul><pre>impl Optimizer {<br>    pub fn new() -&gt; Self {<br>        Optimizer {<br>            constants: HashMap::new(),<br>            used_variables: HashSet::new(),<br>        }<br>    }<br>}</pre><h3>step 2: main optimization loop</h3><pre>pub fn optimize(&amp;mut self, statements: Vec&lt;Stmt&gt;) -&gt; Vec&lt;Stmt&gt; {<br>    let mut current = statements;<br>    let mut iteration = 0;<br>loop {<br>        iteration += 1;<br>        // snapshot the current state<br>        let before = format!(&quot;{:?}&quot;, current);<br>        // collect which variables are used<br>        self.used_variables.clear();<br>        self.collect_used_variables(&amp;current);<br>        // run optimizations<br>        current = self.optimize_statements(current);<br>        current = self.eliminate_dead_code(current);<br>        // check if anything changed<br>        let after = format!(&quot;{:?}&quot;, current);<br>        if before == after {<br>            break; // CONVERGENCE! nothing left to optimize<br>        }<br>        if iteration &gt; 100 {<br>            break;<br>        }<br>    }<br>    current<br>}<br>(╥﹏╥) you  <br>(ง&#39;̀-&#39;́)ง optimizer</pre><p>this keeps running until nothing changes anymore, <strong>why iterative?</strong> because one optimization can enable more: <br>iteration 1 int x = 5;int y = x + 3; after propagation: int y = 5 + 3;<br>iteration 2 int x = 5;int y = 8; after folding: 5 + 3 = 8 <br>iteration 3 int x = 5; // y was unused, DELETED</p><p>this is the glowup factory of your code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*GqHVZnCvzDuC0XdShl_b3A.png" /></figure><h3>step 3: optimizing statements:</h3><pre>fn optimize_statements(&amp;mut self, statements: Vec&lt;Stmt&gt;) -&gt; Vec&lt;Stmt&gt; {<br>    statements<br>        .into_iter()<br>        .filter_map(|stmt| self.optimize_statement(&amp;stmt))<br>        .collect()<br>}<br>fn optimize_statement(&amp;mut self, stmt: &amp;Stmt) -&gt; Option&lt;Stmt&gt; {<br>    match stmt {<br>        Stmt::VarDeclaration { name, value } =&gt; {<br>            let optimized_value = self.optimize_expression(value);<br>            // if the value is constant, remember it<br>            if let Some(const_val) = self.try_evaluate_to_const(&amp;optimized_value) {<br>                self.constants.insert(name.clone(), const_val);<br>            } else {<br>                self.constants.remove(name); // not constant, forget it<br>            }<br>            Some(Stmt::VarDeclaration {<br>                name: name.clone(),<br>                value: optimized_value,<br>            })<br>        }<br>        Stmt::Print(expr) =&gt; {<br>            let optimized_expr = self.optimize_expression(expr);<br>            Some(Stmt::Print(optimized_expr))<br>        }<br>        Stmt::If { condition, then_block, else_block } =&gt; {<br>            self.optimize_if_statement(condition, then_block, else_block)<br>        }<br>    }<br>}</pre><h3>translation:</h3><ul><li>variable declarations get analyzed and constants get stored int x = 5 + 3; → int x = 8; if its a constant, remember it like constants[&quot;x&quot;] = 8</li><li>print statements get their expressions optimized like print(5 + 3); → `print(8);</li></ul><p><strong># if statements get aggressively bullied</strong> you need to do a lot of shit for if statements like</p><pre>fn optimize_if_statement(<br>    &amp;mut self,<br>    condition: &amp;Expr,<br>    then_block: &amp;[Stmt],<br>    else_block: &amp;Option&lt;Vec&lt;Stmt&gt;&gt;<br>) -&gt; Option&lt;Stmt&gt; {<br>    let optimized_condition = self.optimize_expression(condition);<br>// can we evaluate the condition at compile time?<br>    if let Some(const_val) = self.try_evaluate_to_const(&amp;optimized_condition) {<br>        match const_val {<br>            ConstValue::Bool(true) =&gt; {<br>                // condition is ALWAYS true, only keep then_block<br>                let optimized_then = self.optimize_statements(then_block.to_vec());<br>                return Some(Stmt::If {<br>                    condition: optimized_condition,<br>                    then_block: optimized_then,<br>                    else_block: None, // else block DELETED<br>                });<br>            }<br>            ConstValue::Bool(false) =&gt; {<br>                // condition is ALWAYS false, only keep else_block<br>                if let Some(else_stmts) = else_block {<br>                    let optimized_else = self.optimize_statements(else_stmts.clone());<br>                    return Some(Stmt::If {<br>                        condition: optimized_condition,<br>                        then_block: vec![], // then block DELETED<br>                        else_block: Some(optimized_else),<br>                    });<br>                } else {<br>                    return None; // entire if statement DELETED<br>                }<br>            }<br>            _ =&gt; {} // not a bool, can&#39;t optimize<br>        }<br>    }<br>    // can&#39;t optimize condition, but optimize the blocks<br>    let optimized_then = self.optimize_statements(then_block.to_vec());<br>    let optimized_else = else_block<br>        .as_ref()<br>        .map(|stmts| self.optimize_statements(stmts.clone()));<br>    Some(Stmt::If {<br>        condition: optimized_condition,<br>        then_block: optimized_then,<br>        else_block: optimized_else,<br>    })<br>}<br>// if (true) → unconditional love<br>// if (false) → the silent treatment</pre><p>optimizer: this whole branch? useless. if-statement: but optimizer: SILENCE, MORTAL. (╯°益°)╯彡</p><p>yeah that feels like a long ass code, but its simple if you look at it (it isnt, but if you runaway in the middle, people wont read my blogs)</p><p>is this condition ALWAYS true? don’t lie to me, i have your runtime logs.</p><pre>optimizer: this condition is always true<br>else block: but i exist—<br>optimizer: not anymore *avada kedavra*<br>else block: *green everywhere*</pre><h3>step 4: optimizing expressions: (‡▼益▼)</h3><pre>fn optimize_expression(&amp;self, expr: &amp;Expr) -&gt; Expr {<br>    match expr {<br>        // literals stay as-is<br>        Expr::IntegerLiteral(_) | Expr::StringLiteral(_) | Expr::BooleanLiteral(_) =&gt; {<br>            expr.clone()<br>        }<br>// identifiers: replace with constant if known<br>        Expr::Identifier(name) =&gt; {<br>            if let Some(const_val) = self.constants.get(name) {<br>                match const_val {<br>                    ConstValue::Int(n) =&gt; Expr::IntegerLiteral(*n),<br>                    ConstValue::String(s) =&gt; Expr::StringLiteral(s.clone()),<br>                    ConstValue::Bool(b) =&gt; Expr::BooleanLiteral(*b),<br>                }<br>            } else {<br>                expr.clone()<br>            }<br>        }<br>        // binary expressions: THE FINAL BOSS<br>        Expr::Binary { left, op, right } =&gt; {<br>            self.optimize_binary_expression(left, op, right)<br>        }<br>        // assignments: optimize the value<br>        Expr::Assign { name, value } =&gt; {<br>            let optimized_value = self.optimize_expression(value);<br>            Expr::Assign {<br>                name: name.clone(),<br>                value: Box::new(optimized_value),<br>            }<br>        }<br>    }<br>}</pre><p>your compiler rewrites your entire code because you piece of shit cant write FAST code, EVEN AFTER WRITING EVERYTHING IN RUST. expressions are a part of rust where everything suddenly gets buffed up, its like your compiler starts doing war crimes from this point, because no stuff from here is gonna look normal, drink some lava.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1zZ-C8NJAarjRmBH_FOxNg.png" /></figure><p>expression optimization? it walks into your code, cracks its knuckles like a mafia enforcer, and says <em>“what are we deleting today?”</em> why the hell should your program solve 5 + 3 during the test, when we can solve it right now, put the answer in your pocket, and pretend you studied? basically everything gets interrogated like a crime scene.</p><h3>binary optimizations.</h3><pre>fn optimize_binary_expression(&amp;self, left: &amp;Expr, op: &amp;BinOp, right: &amp;Expr) -&gt; Expr {<br>    // recursively optimize both sides<br>    let opt_left = self.optimize_expression(left);<br>    let opt_right = self.optimize_expression(right);<br>// try to evaluate both sides to constants<br>    let left_const = self.try_evaluate_to_const(&amp;opt_left);<br>    let right_const = self.try_evaluate_to_const(&amp;opt_right);<br>    // CONSTANT FOLDING: if both sides are constants, compute result now<br>    if let (Some(l), Some(r)) = (&amp;left_const, &amp;right_const) {<br>        if let Some(result) = self.fold_binary_operation(l, op, r) {<br>            return result;<br>        }<br>    }<br>    // ALGEBRAIC SIMPLIFICATION: special patterns<br>    match op {<br>        BinOp::Add =&gt; {<br>            // x + 0 = x<br>            if let Some(ConstValue::Int(0)) = right_const {<br>                return opt_left;<br>            }<br>            // 0 + x = x<br>            if let Some(ConstValue::Int(0)) = left_const {<br>                return opt_right;<br>            }<br>        }<br>        BinOp::Sub =&gt; {<br>            // x - 0 = x<br>            if let Some(ConstValue::Int(0)) = right_const {<br>                return opt_left;<br>            }<br>            // x - x = 0<br>            if let (Expr::Identifier(l), Expr::Identifier(r)) = (&amp;opt_left, &amp;opt_right) {<br>                if l == r {<br>                    return Expr::IntegerLiteral(0);<br>                }<br>            }<br>        }<br>        _ =&gt; {}<br>    }<br>    // can&#39;t optimize, return as-is<br>    Expr::Binary {<br>        left: Box::new(opt_left),<br>        op: op.clone(),<br>        right: Box::new(opt_right),<br>    }<br>}</pre><p>optimizer is so unlike me and because it just wants to solve every math problem RIGHT NOW, one and only bigger masochist than me, cant even lie. it literally breaks them down like a doctor looking at your body and saying “yeah its shit, this is the smoothest brain i have ever seen” like, left side? right side? operator? CAN I COMPUTE THEM RIGHT NOW? and your code is broken apart and fixed in some weird way like a doctor who episode. good luck with that.<br> lets take an example like, we’ll take a variable, so x + 0 but you are literally triggering your optimizer by adding your last tests marks to x because it reacts more violently than your parents seeing your marks. and cancles you.</p><p>binary ops get: simplified, evaluated, bullied, gaslit, resolved, folded, annihilated, all in one function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5n5PoRCvwdrtGIr8mHWeGQ.png" /></figure><h3>implementing constant folding</h3><pre>fn fold_binary_operation(<br>    &amp;self,<br>    left: &amp;ConstValue,<br>    op: &amp;BinOp,<br>    right: &amp;ConstValue,<br>) -&gt; Option&lt;Expr&gt; {<br>    match (left, op, right) {<br>        // integer arithmetic<br>        (ConstValue::Int(l), BinOp::Add, ConstValue::Int(r)) =&gt; {<br>            Some(Expr::IntegerLiteral(l + r))<br>        }<br>        (ConstValue::Int(l), BinOp::Sub, ConstValue::Int(r)) =&gt; {<br>            Some(Expr::IntegerLiteral(l - r))<br>        }<br>// integer comparisons<br>        (ConstValue::Int(l), BinOp::GreaterThan, ConstValue::Int(r)) =&gt; {<br>            Some(Expr::BooleanLiteral(l &gt; r))<br>        }<br>        (ConstValue::Int(l), BinOp::LessThan, ConstValue::Int(r)) =&gt; {<br>            Some(Expr::BooleanLiteral(l &lt; r))<br>        }<br>        // string concatenation<br>        (ConstValue::String(l), BinOp::Add, ConstValue::String(r)) =&gt; {<br>            Some(Expr::StringLiteral(format!(&quot;{}{}&quot;, l, r)))<br>        }<br>        _ =&gt; None // can&#39;t fold this<br>    }<br>}<br>you write int x = 4 + 10 + 11; and this guy gets stimulated and suddenly solves it as x = 25; like idk what high does this function gets seeing numbers and i never want to. shu away. its like that annoying kid who raised their hand before teacher finished their question but this is also a responsible part of your code, because come on, we dont write good code.<br>evaluating expressions to constants:<br>fn try_evaluate_to_const(&amp;self, expr: &amp;Expr) -&gt; Option&lt;ConstValue&gt; {<br>    match expr {<br>        Expr::IntegerLiteral(n) =&gt; Some(ConstValue::Int(*n)),<br>        Expr::StringLiteral(s) =&gt; Some(ConstValue::String(s.clone())),<br>        Expr::BooleanLiteral(b) =&gt; Some(ConstValue::Bool(*b)),<br>        Expr::Identifier(name) =&gt; {<br>            self.constants.get(name).cloned()<br>        }<br>        Expr::Binary { left, op, right } =&gt; {<br>            let left_val = self.try_evaluate_to_const(left)?;<br>            let right_val = self.try_evaluate_to_const(right)?;<br>            self.fold_binary_operation(&amp;left_val, op, &amp;right_val)<br>                .and_then(|expr| self.try_evaluate_to_const(&amp;expr))<br>        }<br>        Expr::Assign { .. } =&gt; None, // assignments aren&#39;t constants<br>    }<br>}</pre><p>this function is your compiler on its third cup of coffee, it figures everything out without blinking, it sees expressions and goes “fuck this can be simplified, why do humans write garbage” and simplify it like its peeling layers of onion. its a nightmare for your code, literally goes from room to room to bully every code by telling them how slow they are, how shitty they are written and reconstruct their faces, making them like you can cut vegetables just by their jawline AND fast as fuck boi.</p><h3>last step: dead code elimination: THE PURGE</h3><p>this is the part where your compiler stops being just a compiler and becomes rust chole, it walks around the place with your ast and starts slapping everybody yelling “who even likes you, you shitty zombie” and disappears those code like they born just to be bullied. funnily enough your program works exactly the same way afterwards, those disappeared code parts had no contribution to your code, they were just there to watch, cucks. tho the compiler is also judging you while doing all of this because what shitty code did you write to get this much deletion, you were on a shopping spree saying, yeah i’ll wear this when i go on a date, but you never go on one. because WHY WOULD ANYBODY EVEN TALK TO YOU.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*_1ghNI0irVuUbf2xdrQqMQ.png" /></figure><pre>fn collect_used_variables(&amp;mut self, statements: &amp;[Stmt]) {<br>    for stmt in statements {<br>        self.collect_used_in_statement(stmt);<br>    }<br>}<br>fn collect_used_in_statement(&amp;mut self, stmt: &amp;Stmt) {<br>    match stmt {<br>        Stmt::VarDeclaration { name: _, value } =&gt; {<br>            self.collect_used_in_expression(value);<br>        }<br>        Stmt::Print(expr) =&gt; {<br>            self.collect_used_in_expression(expr);<br>        }<br>        Stmt::If { condition, then_block, else_block } =&gt; {<br>            self.collect_used_in_expression(condition);<br>            for stmt in then_block {<br>                self.collect_used_in_statement(stmt);<br>            }<br>            if let Some(else_stmts) = else_block {<br>                for stmt in else_stmts {<br>                    self.collect_used_in_statement(stmt);<br>                }<br>            }<br>        }<br>    }<br>}<br>fn collect_used_in_expression(&amp;mut self, expr: &amp;Expr) {<br>    match expr {<br>        Expr::IntegerLiteral(_) | Expr::StringLiteral(_) | Expr::BooleanLiteral(_) =&gt; {}<br>        Expr::Identifier(name) =&gt; {<br>            self.used_variables.insert(name.clone());<br>        }<br>        Expr::Binary { left, right, .. } =&gt; {<br>            self.collect_used_in_expression(left);<br>            self.collect_used_in_expression(right);<br>        }<br>        Expr::Assign { name, value } =&gt; {<br>            self.used_variables.insert(name.clone());<br>            self.collect_used_in_expression(value);<br>        }<br>    }<br>}<br>fn eliminate_dead_code(&amp;self, statements: Vec&lt;Stmt&gt;) -&gt; Vec&lt;Stmt&gt; {<br>    statements<br>        .into_iter()<br>        .filter_map(|stmt| match stmt {<br>            Stmt::VarDeclaration { ref name, .. } =&gt; {<br>                if self.used_variables.contains(name) {<br>                    Some(stmt) // keep it ✓<br>                } else {<br>                    None // DELETE IT ☠️<br>                }<br>            }<br>            _ =&gt; Some(stmt), // keep all other statements<br>        })<br>        .collect()<br>}<br>unused var: ( •_•)<br>optimizer: (ง ಠ_ಠ)ง</pre><p>this becomes like my favorite card in clash royale, THE EXECUTIONER and beheads every unused part of your code.</p><h3>testing this shit now</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*kF4na8iu2qwxIyb34qv_-Q.png" /></figure><p>update your main.rs with this: go on, send me a screenshot of your errors filling the compiler page.</p><pre>mod lexing;<br>mod parsing;<br>mod ast;<br>mod semantic;<br>mod optimizer;<br><br>use lexing::lexer::lex_program;<br>use parsing::parser::Parser;<br>use semantic::SemanticAnalyzer;<br>use optimizer::Optimizer;<br>const PROGRAM: &amp;str = &quot;<br>int x = 5 + 3;<br>int y = x + 2;<br>int unused = 420;<br>int z = y - 0;<br>if (true) {<br>    print(z);<br>} else {<br>    print(unused);<br>}<br>&quot;;<br>fn main() {<br>    println!(&quot; lexing &quot;);<br>    let tokens = lex_program(PROGRAM);<br>    println!(&quot; parsing &quot;);<br>    let mut parser = Parser::new(tokens);<br>    let ast = match parser.parse() {<br>        Ok(ast) =&gt; ast,<br>        Err(e) =&gt; {<br>            println!(&quot; parse error: {:?}&quot;, e);<br>            return;<br>        }<br>    };<br>    println!(&quot; semantic analysis &quot;);<br>    let mut analyzer = SemanticAnalyzer::new();<br>    match analyzer.analyze(&amp;ast) {<br>        Ok(_) =&gt; println!(&quot;✓ no semantic errors&quot;),<br>        Err(errors) =&gt; {<br>            println!(&quot; semantic errors:&quot;);<br>            for err in errors {<br>                println!(&quot;{:?}&quot;, err);<br>            }<br>            return;<br>        }<br>    };<br>    println!(&quot;\\\\n⚡ optimization ⚡&quot;);<br>    let mut optimizer = Optimizer::new();<br>    let optimized_ast = optimizer.optimize(ast);<br>    println!(&quot;\\\\n optimized code &quot;);<br>    for (i, stmt) in optimized_ast.iter().enumerate() {<br>        println!(&quot;statement {}: {:#?}\\\\n&quot;, i + 1, stmt);<br>    }<br>}</pre><p>and do cargo run and watch this shit go.</p><p>just remember, everytime your code breaks, i am laughing. very loudly.</p><p>and thats it, your compiler is faster than sonic and more judgemental than your neighbor. you’ve built a lexer, parser, semantic analyzer and now an optimizer for it, you must really hate yourself. alas one last step is remaining, generating code from your language, and i am gonna do arm64 assembly for it, so be prepared. or not, your self hate must run deeper.</p><pre>[████████████████████] lexer      - DONE ✓<br>[████████████████████] parser     - DONE ✓<br>[████████████████████] semantic   - DONE ✓<br>[████████████████████] optimizer  - DONE ✓<br>[░░░░░░░░░░░░░░░░░░░░] codegen   - TODO</pre><p>until we meet again.</p><pre>optimizer.rs<br>use std::collections::{HashMap, ashSet};<br>use crate::ast::{Expr, Stmt, BinOp};<br>#[derive(Debug, Clone, PartialEq)]<br>pub enum ConstValue {<br>    Int(i32),<br>    String(String),<br>    Bool(bool),<br>}<br>pub struct Optimizer {<br>    // x -&gt; 5, &quot;hihi&quot;, true, etc.<br>    constants: HashMap&lt;String, ConstValue&gt;,<br>    // set of variables that are actually used<br>    used_variables: HashSet&lt;String&gt;,<br>}<br>impl Optimizer {<br>    pub fn new() -&gt; Self {<br>        Optimizer {<br>            constants: HashMap::new(),<br>            used_variables: HashSet::new(),<br>        }<br>    }<br>    /// Main optimization loop: keeps running passes until nothing changes<br>    pub fn optimize(&amp;mut self, statements: Vec&lt;Stmt&gt;) -&gt; Vec&lt;Stmt&gt; {<br>        let mut current = statements;<br>        let mut iteration = 0;<br>        loop {<br>            iteration += 1;<br>            // snapshot before<br>            let before = format!(&quot;{:?}&quot;, current);<br>            // track which variables are used<br>            self.used_variables.clear();<br>            self.collect_used_variables(&amp;current);<br>            // run all passes<br>            current = self.optimize_statements(current);<br>            current = self.eliminate_dead_code(current);<br>            // snapshot after<br>            let after = format!(&quot;{:?}&quot;, current);<br>            if before == after {<br>                // nothing changed → converged<br>                break;<br>            }<br>            if iteration &gt; 100 {<br>                // safety hatch in case we do something cursed<br>                eprintln!(&quot;warning: optimization didn&#39;t converge after 100 iterations&quot;);<br>                break;<br>            }<br>        }<br>        current<br>    }<br>    fn optimize_statements(&amp;mut self, statements: Vec&lt;Stmt&gt;) -&gt; Vec&lt;Stmt&gt; {<br>        statements<br>            .into_iter()<br>            .filter_map(|stmt| self.optimize_statement(&amp;stmt))<br>            .collect()<br>    }<br>    fn optimize_statement(&amp;mut self, stmt: &amp;Stmt) -&gt; Option&lt;Stmt&gt; {<br>        match stmt {<br>            Stmt::VarDeclaration { name, value } =&gt; {<br>                let optimized_value = self.optimize_expression(value);<br>                // if value is constant, remember it<br>                if let Some(const_val) = self.try_evaluate_to_const(&amp;optimized_value) {<br>                    self.constants.insert(name.clone(), const_val);<br>                } else {<br>                    // not constant anymore, forget old value<br>                    self.constants.remove(name);<br>                }<br>                Some(Stmt::VarDeclaration {<br>                    name: name.clone(),<br>                    value: optimized_value,<br>                })<br>            }<br>            Stmt::Print(expr) =&gt; {<br>                let optimized_expr = self.optimize_expression(expr);<br>                Some(Stmt::Print(optimized_expr))<br>            }<br>            Stmt::If {<br>                condition,<br>                then_block,<br>                else_block,<br>            } =&gt; self.optimize_if_statement(condition, then_block, else_block),<br>        }<br>    }<br>    fn optimize_if_statement(<br>        &amp;mut self,<br>        condition: &amp;Expr,<br>        then_block: &amp;[Stmt],<br>        else_block: &amp;Option&lt;Vec&lt;Stmt&gt;&gt;,<br>    ) -&gt; Option&lt;Stmt&gt; {<br>        let optimized_condition = self.optimize_expression(condition);<br>        // try to fold condition into a constant<br>        if let Some(const_val) = self.try_evaluate_to_const(&amp;optimized_condition) {<br>            match const_val {<br>                ConstValue::Bool(true) =&gt; {<br>                    // always true → keep only then_block<br>                    let optimized_then = self.optimize_statements(then_block.to_vec());<br>                    return Some(Stmt::If {<br>                        condition: optimized_condition,<br>                        then_block: optimized_then,<br>                        else_block: None,<br>                    });<br>                }<br>                ConstValue::Bool(false) =&gt; {<br>                    // always false → keep only else_block, or delete whole thing<br>                    if let Some(else_stmts) = else_block {<br>                        let optimized_else = self.optimize_statements(else_stmts.clone());<br>                        return Some(Stmt::If {<br>                            condition: optimized_condition,<br>                            then_block: vec![],<br>                            else_block: Some(optimized_else),<br>                        });<br>                    } else {<br>                        // no else → this entire branch is useless<br>                        return None;<br>                    }<br>                }<br>                _ =&gt; {<br>                    // not a boolean -&gt; can&#39;t decide statically<br>                }<br>            }<br>        }<br>        // can&#39;t fold condition, but can still optimize inner blocks<br>        let optimized_then = self.optimize_statements(then_block.to_vec());<br>        let optimized_else = else_block<br>            .as_ref()<br>            .map(|stmts| self.optimize_statements(stmts.clone()));<br>        Some(Stmt::If {<br>            condition: optimized_condition,<br>            then_block: optimized_then,<br>            else_block: optimized_else,<br>        })<br>    }<br>    /// Recursively optimize an expression: constant propagation + folding<br>    fn optimize_expression(&amp;self, expr: &amp;Expr) -&gt; Expr {<br>        match expr {<br>            // literals are already as simple as they get<br>            Expr::IntegerLiteral(_)<br>            | Expr::StringLiteral(_)<br>            | Expr::BooleanLiteral(_) =&gt; expr.clone(),<br>            // replace identifier by constant if known<br>            Expr::Identifier(name) =&gt; {<br>                if let Some(const_val) = self.constants.get(name) {<br>                    match const_val {<br>                        ConstValue::Int(n) =&gt; Expr::IntegerLiteral(*n),<br>                        ConstValue::String(s) =&gt; Expr::StringLiteral(s.clone()),<br>                        ConstValue::Bool(b) =&gt; Expr::BooleanLiteral(*b),<br>                    }<br>                } else {<br>                    expr.clone()<br>                }<br>            }<br>            // binary expressions: simplify children, then fold/simplify pattern<br>            Expr::Binary { left, op, right } =&gt; {<br>                self.optimize_binary_expression(left, op, right)<br>            }<br>            // assignment: optimize RHS<br>            Expr::Assign { name, value } =&gt; {<br>                let optimized_value = self.optimize_expression(value);<br>                Expr::Assign {<br>                    name: name.clone(),<br>                    value: Box::new(optimized_value),<br>                }<br>            }<br>        }<br>    }<br>    fn optimize_binary_expression(&amp;self, left: &amp;Expr, op: &amp;BinOp, right: &amp;Expr) -&gt; Expr {<br>        // first optimize children<br>        let opt_left = self.optimize_expression(left);<br>        let opt_right = self.optimize_expression(right);<br>        // try to evaluate both sides to constants<br>        let left_const = self.try_evaluate_to_const(&amp;opt_left);<br>        let right_const = self.try_evaluate_to_const(&amp;opt_right);<br>        // CONSTANT FOLDING: both sides are constants → compute now<br>        if let (Some(l), Some(r)) = (&amp;left_const, &amp;right_const) {<br>            if let Some(result) = self.fold_binary_operation(l, op, r) {<br>                return result;<br>            }<br>        }<br>        // ALGEBRAIC SIMPLIFICATION<br>        match op {<br>            BinOp::Add =&gt; {<br>                // x + 0 = x<br>                if let Some(ConstValue::Int(0)) = right_const {<br>                    return opt_left;<br>                }<br>                // 0 + x = x<br>                if let Some(ConstValue::Int(0)) = left_const {<br>                    return opt_right;<br>                }<br>            }<br>            BinOp::Sub =&gt; {<br>                // x - 0 = x<br>                if let Some(ConstValue::Int(0)) = right_const {<br>                    return opt_left;<br>                }<br>                // x - x = 0<br>                if let (Expr::Identifier(l), Expr::Identifier(r)) = (&amp;opt_left, &amp;opt_right) {<br>                    if l == r {<br>                        return Expr::IntegerLiteral(0);<br>                    }<br>                }<br>            }<br>            _ =&gt; {}<br>        }<br>        // nothing special → rebuild<br>        Expr::Binary {<br>            left: Box::new(opt_left),<br>            op: op.clone(),<br>            right: Box::new(opt_right),<br>        }<br>    }<br>    fn fold_binary_operation(<br>        &amp;self,<br>        left: &amp;ConstValue,<br>        op: &amp;BinOp,<br>        right: &amp;ConstValue,<br>    ) -&gt; Option&lt;Expr&gt; {<br>        match (left, op, right) {<br>            // integer arithmetic<br>            (ConstValue::Int(l), BinOp::Add, ConstValue::Int(r)) =&gt; {<br>                Some(Expr::IntegerLiteral(l + r))<br>            }<br>            (ConstValue::Int(l), BinOp::Sub, ConstValue::Int(r)) =&gt; {<br>                Some(Expr::IntegerLiteral(l - r))<br>            }<br>            // integer comparisons -&gt; bool<br>            (ConstValue::Int(l), BinOp::GreaterThan, ConstValue::Int(r)) =&gt; {<br>                Some(Expr::BooleanLiteral(l &gt; r))<br>            }<br>            (ConstValue::Int(l), BinOp::LessThan, ConstValue::Int(r)) =&gt; {<br>                Some(Expr::BooleanLiteral(l &lt; r))<br>            }<br>            // string concatenation<br>            (ConstValue::String(l), BinOp::Add, ConstValue::String(r)) =&gt; {<br>                Some(Expr::StringLiteral(format!(&quot;{}{}&quot;, l, r)))<br>            }<br>            _ =&gt; None,<br>        }<br>    }<br>    fn try_evaluate_to_const(&amp;self, expr: &amp;Expr) -&gt; Option&lt;ConstValue&gt; {<br>        match expr {<br>            Expr::IntegerLiteral(n) =&gt; Some(ConstValue::Int(*n)),<br>            Expr::StringLiteral(s) =&gt; Some(ConstValue::String(s.clone())),<br>            Expr::BooleanLiteral(b) =&gt; Some(ConstValue::Bool(*b)),<br>            Expr::Identifier(name) =&gt; self.constants.get(name).cloned(),<br>            Expr::Binary { left, op, right } =&gt; {<br>                let left_val = self.try_evaluate_to_const(left)?;<br>                let right_val = self.try_evaluate_to_const(right)?;<br>                self.fold_binary_operation(&amp;left_val, op, &amp;right_val)<br>                    .and_then(|expr| self.try_evaluate_to_const(&amp;expr))<br>            }<br>            Expr::Assign { .. } =&gt; None, // assignments aren&#39;t constants<br>        }<br>    }<br>    // ======== dead code elimination helpers ========<br>    fn collect_used_variables(&amp;mut self, statements: &amp;[Stmt]) {<br>        for stmt in statements {<br>            self.collect_used_in_statement(stmt);<br>        }<br>    }<br>    fn collect_used_in_statement(&amp;mut self, stmt: &amp;Stmt) {<br>        match stmt {<br>            Stmt::VarDeclaration { name: _, value } =&gt; {<br>                self.collect_used_in_expression(value);<br>            }<br>            Stmt::Print(expr) =&gt; {<br>                self.collect_used_in_expression(expr);<br>            }<br>            Stmt::If {<br>                condition,<br>                then_block,<br>                else_block,<br>            } =&gt; {<br>                self.collect_used_in_expression(condition);<br>                for stmt in then_block {<br>                    self.collect_used_in_statement(stmt);<br>                }<br>                if let Some(else_stmts) = else_block {<br>                    for stmt in else_stmts {<br>                        self.collect_used_in_statement(stmt);<br>                    }<br>                }<br>            }<br>        }<br>    }<br>    fn collect_used_in_expression(&amp;mut self, expr: &amp;Expr) {<br>        match expr {<br>            Expr::IntegerLiteral(_)<br>            | Expr::StringLiteral(_)<br>            | Expr::BooleanLiteral(_) =&gt; {}<br>            Expr::Identifier(name) =&gt; {<br>                self.used_variables.insert(name.clone());<br>            }<br>            Expr::Binary { left, right, .. } =&gt; {<br>                self.collect_used_in_expression(left);<br>                self.collect_used_in_expression(right);<br>            }<br>            Expr::Assign { name, value } =&gt; {<br>                self.used_variables.insert(name.clone());<br>                self.collect_used_in_expression(value);<br>            }<br>        }<br>    }<br>    fn eliminate_dead_code(&amp;self, statements: Vec&lt;Stmt&gt;) -&gt; Vec&lt;Stmt&gt; {<br>        statements<br>            .into_iter()<br>            .filter_map(|stmt| match stmt {<br>                Stmt::VarDeclaration { ref name, .. } =&gt; {<br>                    if self.used_variables.contains(name) {<br>                        Some(stmt) // actually used → keep<br>                    } else {<br>                        None // never used → DELETE<br>                    }<br>                }<br>                _ =&gt; Some(stmt),<br>            })<br>            .collect()<br>    }<br>}</pre><h3>codegen in rust.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*AAz57oscJClyAVJnPBo3vA.png" /></figure><p>THE FINAL CIRCLE OF HELL</p><p>if you are reading this, survived everything and finished all prior steps, youre just very unemployed. lets become a menace to society after finishing this last step then you’ll be unemployed with a compiler. win win.</p><p>can you hear the boss music? yeah thats gonna run the whole time.</p><p>you’ve tokenized. you’ve parsed. you’ve analyzed semantics like a disappointed parent. you’ve optimized until your code cried but we are gonna do something truly unhinged now, like right now: we’re gonna make your computer understand your bullshit. as surprising as it sounds, yeah even your shitty code can be turned into something beautiful.</p><h3>so what even is codegen?</h3><p>this is the part where your ast nodes evolves into <strong>arm64 assembly code</strong>, full magikarp to gyarados transformation. it runs on an actual hardware, now its just you, your compiler and raw machine instructions. this is the most intimate you have gotten, ever. I KNOW.</p><p>if you thought the previous steps were pain, oh you sweet summer child, this is where your compiler stops being a translator and becomes a WARTIME GENERAL issuing direct orders to silicon. and real things can SEGFAULT. (҂◡_◡)</p><pre>## codegen is your compiler&#39;s FINAL FORM<br>everything until now was your compiler being polite:<br>- lexer: oh i see you have tokens<br>- parser: what a lovely tree structure<br>- semantic analyzer: lets check if this makes sense<br>- optimizer: i can make this shit FASTER<br><br>codegen is your compiler dropping the act:<br>LISTEN UP YOU LITTLE SHIT. <br>you wanted a program? here&#39;s EXACTLY what the CPU needs to do.<br>move this here. add these numbers. jump to this address.<br>NO QUESTIONS. NO MERCY. JUST INSTRUCTIONS.<br>this is the translation layer between:<br>- &quot;int x = 5 + 3&quot; (nice human language)<br>- &quot;mov x9, #5; mov x10, #3; add x11, x9, x10&quot; (CPU language)<br>your CPU doesn&#39;t speak english. it speaks violence.<br>and assembly is the grammar of that violence.</pre><h3>why arm64 speficially? (ง’̀-’́)ง</h3><p>because it made more sense to me when i looked at both x86 and arm64, then i found out nearly every phone has arm64 running on it. m series macs have been running on this, i knew this but never mattered to me before, now its all coming together. you might think i chose the easier option by choosing arm64 because it looked easier, but NO. YOU TAKE MY MASOCHISM FOR GRANTED, i am on an intel machine, heh, i killed your assumptions. but this all will matter at the last step while actually running asm code, you can do all prior steps regardless.</p><pre>here&#39;s my full setup, in all its CURSED glory:<br>┌─────────────────────────────────────┐<br>│  my intel laptop (x86_64)           │<br>│  ┌───────────────────────────────┐  │<br>│  │  QEMU                         │  │<br>│  │  (pretending to be ARM64)     │  │<br>│  │  ┌─────────────────────────┐  │  │<br>│  │  │  chroot environment     │  │  │<br>│  │  │  (ARM64 userspace)      │  │  │<br>│  │  │  ┌───────────────────┐  │  │  │<br>│  │  │  │  my compiled ASM  │  │  │  │<br>│  │  │  │  (finally running)│  │  │  │<br>│  │  │  └───────────────────┘  │  │  │<br>│  │  └─────────────────────────┘  │  │<br>│  └───────────────────────────────┘  │<br>└─────────────────────────────────────┘<br><br>debugging looks like:<br>- compile ARM64 assembly on x86<br>- copy to ARM64 chroot<br>- run in QEMU<br>- attach multi-arch GDB<br>- set breakpoints<br>- pray to god (any god, i&#39;m not picky)<br>- watch it segfault anyway<br>- cry<br>- fix one byte<br>- repeat</pre><p>i have done this approximately 847 times now ig, so why intel even after all this shit? i get to see what is truly happening under the hood, how is stuff being done piece by piece, and the real reason is i cant afford any macbook.</p><h3>so what codegen ACTUALLY?</h3><p>everything you have built until now was kind of just reading your code — lexer, parser, analyzer, optimizer, all those were doing their own stuff with your language but none would be sufficient if you dont do this step, why? because youre turning your language into actual code.</p><p>lets take our classic example to understand this better: int x = 5 + 3 in your high-level language. your ast turns this into something like</p><pre>VarDeclaration {<br>	name : &quot;x&quot;,<br>	value: Binary {<br>		left: IntegerLiteral(5),<br>		op: Add,<br>		right: IntegerLiteral(3)<br>		}<br>	}</pre><p>this is nice, structured but it makes some sense to just us creatures of pain, it makes no sense to your cpu. instructions would make sense to your cpu, raw instructions, no lube.</p><p>the same stuff in arm64 asm would look like:</p><pre>mov x9, #5<br>mov x10, #3<br>add x11, x9, x10<br>str x11, [sp, #0]</pre><p>see? its still english. you can see mov, add, str stuff you just dont know how asm does things, mov move things, immediate move, add is add ofc str : at first when i was learning this, i kept thinking of this as “string” but its STORE.</p><p>now lets see whats the meaning of this syntax — x9 is a register, like an actual register physically built in your processing chip and #5 is the integer value you have in this context. and we read it in a little jumbled fashion like move #5 in x9 register.and similar thing for next line, it goes as move #3 in x10 register. then there&#39;s a different way of writing addin arm64 because you can see its has only registers up there. so here we take the first register to hold the value of next 2 registers respectively. by that. here we are adding the value that x9 register holds and what x10 register holds into x11 register. i know its cursed when you look at it and how it actually works but eh.</p><pre>dd x11, x9, x10  ; x11 = x9 + x10<br>sub x11, x9, x10  ; x11 = x9 - x10<br>IMPORTANT: arm64 has 3-address architecture, <br>destination comes first then two operands.</pre><p>and the next line probably more cursed when you look at it, but it is saying: STORE the value of x11 register into memory at an offset #0. like take whatever value you get at x11 and yeet it into memory at address sp + 0 sp means stack pointer, it points at whatever is currently on the top of your stack,</p><pre>high addresses<br>    ↓<br>┌─────────────┐<br>│   old data  │  <br>├─────────────┤  ← stack pointer WAS here<br>│  local var  │  <br>├─────────────┤  <br>│  local var  │  <br>├─────────────┤  ← stack pointer NOW here (sp)<br>│   (empty)   │  <br>└─────────────┘<br>low addresses<br>when you do            sub sp, sp, #16   ; reserve 16 bytes on stack<br>this moves it up again add sp, sp, #16   ; deallocate 16 bytes</pre><h3>why store stuff like this?</h3><p>idk man, i didnt create arm64 but i have an idea — maybe because everytime your function is running, it creates a stack frame. like a stack of playing cards or a deck of plates.</p><pre>+------------------------+<br>| local var: x  (offset 0)   &lt;-- [sp, #0]<br>| local var: y  (offset 8)   &lt;-- [sp, #8]<br>| local var: z  (offset 16)  &lt;-- [sp, #16]<br>+------------------------+<br>[sp]              ; address in sp (no offset)<br>[sp, #8]          ; address (sp + 8)<br>[sp, #-16]        ; address (sp - 16)<br>[sp, #16]!        ; address (sp + 16), THEN update sp (pre-increment)<br>[sp], #16         ; address sp, THEN sp = sp + 16 (post-increment)<br>## ldr x9, [sp, #0]  ; LOAD from memory address (sp + 0) into x9<br>## str x9, [sp, #0]  ; STORE x9 into memory address (sp + 0)</pre><p>your compiler tracks everything, where each variable lives using those offsets (#0, #8) in our case, we stored our value at sp #0 so the compiler knows that your value lives at 0 offsets from stack pointer. it generally moves with an 8byte space, so 0 then 8 then 16 and so on. try to think of it like youre wearing pants with many pockets, and you have your phone stored at first pocket, so you know where your phone is, you might have your earphones at second pocket (offset #8), so you know to go at second pocket whenever you want your earphones.</p><p>your stack grows downwards, everytime you reserve space for more local, sp moves towards lower memory, but your offset number goes up. the creator of arm64 didnt like newton a lot ig and wanted everybody confused and suffering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hVEuhSVzJO975QtAYaFrrQ.png" /></figure><pre>a simple crash course on this stuff<br>from here its just you, the CPU, and CONSEQUENCES.<br>## registers: your CPU&#39;s pockets<br>arm64 gives you 31 general-purpose registers:<br>x0, x1, x2, ... x30<br>think of them as really fast variables built into your cpu&#39;s brain.<br>but here&#39;s the catch: they have JOBS UNLIKE YOU.<br>x0-x7: function arguments and return values<br>       (x0 = first arg, also the return value)<br>       <br>x8: indirect result location (for big returns)<br>x9-x15: temporary registers (WE USE THESE)<br>        - no one cares about them<br>        - use them, abuse them, destroy them<br>        - perfect for our dirty work<br>        <br>x16-x17: intra-procedure-call registers (linker uses these, STAY AWAY)<br>x18: platform register (DON&#39;T TOUCH, OS might use it)<br>x19-x28: callee-saved (if you use these, you gotta save/restore them)<br>x29: frame pointer (FP) - like a bookmark for your stack frame<br>x30: link register (LR) - stores return addresses<br>sp: stack pointer - points to top of stack (NOT x31, it&#39;s special)<br>## why we love x9-x15<br>because they&#39;re TEMPORARY. we can:<br>- put whatever we want in them<br>- never save them<br>- never restore them<br>- just YEET values in and out<br>this might not be the most optimal way to make things work but you can increase code&#39;s <br>capabilities by your own means by building on this project.</pre><h3>first we have to setup QEMU and multi-arch gdb if you’re on intel.</h3><h3>1. on ubuntu / debian:</h3><pre>sudo apt update<br>sudo apt install qemu-user qemu-user-static gcc-aarch64-linux-gnu</pre><h3>2. setup binfmt</h3><p>sudo apt install binfmt-support</p><h3>3. compile your asm</h3><p>aarch64-linux-gnu-gcc output.s -o program -static</p><h3>4. run it</h3><p>qemu-aarch64 ./program</p><h3>5. lets start the debugging, the real hell.</h3><p>sudo apt install gdb-multiarch</p><p>run your program in qemu using debug server by qemu-aarch64 -g 1234 ./program</p><p>in another terminal you can step through each instruction, see register values, inspect memory, watch your program die in real-time it looked like magic to me when i first saw it.</p><pre>gdb-multiarch ./program<br>(gdb) target remote :1234<br>(gdb) break main<br>(gdb) continue<br>(gdb) info registers     # see all register values<br>(gdb) x/16x $sp          # examine stack memory<br>(gdb) stepi              # step ONE instruction<br>(gdb) layout asm         # see assembly while debugging</pre><p>try normal moving a simple value in some register and returning it, you can also do some add or sub these will work smoothly for starters.</p><h3>assumptions:</h3><ul><li><strong>you trust the process.</strong></li></ul><h3>step 1: codegen struct. our crime factory. (っ◞‸◟c)</h3><pre>use std::collections::HashMap;<br>use crate::ast::{Expr, Stmt, BinOp};<br>pub struct Codegen {<br>    data_strings: Vec&lt;(String, String)&gt;,            <br>    var_offsets: HashMap&lt;String, i32&gt;,              <br>    next_var_offset: i32,                           <br>    instrs: Vec&lt;String&gt;,                            <br>    label_counter: usize,                           <br>    temp_regs: Vec&lt;&amp;&#39;static str&gt;,                   <br>}</pre><p>make a new file of <a href="http://codegen.rs/">codegen.rs</a> this struct is like one packed bundle of existentialism, you have data_string which is like a prison cell for each string literal you have in your code, then there’s var_offsets , the accountant who stores location of variable is running their shady hotel, next_var_offsets is the receptionist who tells your program where to go, which places are free. instrs is the kill list at the end, every instruction you wrote gets burned to death here, or frozen, this place is like impel down. label_counter prevents compiler from naming joe or aditya two times and get confused, there can only be one. and finally temp_regs is a stack of registers you borrow from your cpu to use for your shady work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*kt91MFUk3uMVypB2VztlCg.png" /></figure><h3>step 2: implementing — dreams becoming nightmares.</h3><p>now we implement that cursed struct, your rust stops minding its business and starts doing cyber-violence, whenever you do ::new() , you’re just gathering a tiny army inside your compiler.</p><pre>impl Codegen {<br>    pub fn new() -&gt; Self {<br>        Codegen {<br>            data_strings: Vec::new(),<br>            var_offsets: HashMap::new(),<br>            next_var_offset: 0,<br>            instrs: Vec::new(),<br>            label_counter: 0,<br>            temp_regs: vec![&quot;x9&quot;,&quot;x10&quot;,&quot;x11&quot;,&quot;x12&quot;,&quot;x13&quot;,&quot;x14&quot;,&quot;x15&quot;],<br>        }<br>    }<br>}</pre><p>i dont think i have to explain rust syntax atp, but something odd here are seeing a spree of specific registers, and that is because arm64 has registers x9 to x15 open for temporary storage, can store anything, destroy anytime.</p><h3>step 3: main generate function: the ritual circle (ಥ_ಥ)</h3><p>“i hope to god they know what i am are doing, because i DONT”</p><pre>pub fn generate(mut self, stmts: &amp;[Stmt]) -&gt; String {<br>    self.emit_prologue();<br>    for s in stmts {<br>        self.gen_stmt(s);<br>    }<br>    self.emit_epilogue();<br>let mut data_section = Vec::new();<br>    data_section.push(r#&quot;fmt_int: .asciz &quot;%d\\n&quot;&quot;#.to_string());<br>    data_section.push(r#&quot;fmt_str: .asciz &quot;%s\\n&quot;&quot;#.to_string());<br>    for (label, text) in &amp;self.data_strings {<br>        data_section.push(format!(&quot;{}: .asciz {}&quot;, label, text));<br>    }<br>    <br>    let mut out = String::new();<br>    out.push_str(&quot;\\t.data\\n&quot;);<br>    for line in data_section {<br>        out.push_str(&amp;line);<br>        out.push(&#39;\\n&#39;);<br>    }<br>    out.push_str(&quot;\\n\\t.text\\n&quot;);<br>    out.push_str(&quot;\\t.global main\\n&quot;);<br>    <br>    for instr in &amp;self.instrs {<br>        out.push_str(instr);<br>        out.push(&#39;\\n&#39;);<br>    }<br>    out<br>}</pre><p>this is that of our code, i forgot the name the person who like waves their hands while facing the band, yeah that person.</p><blockquote>you call <em>emit_prologie()</em> and done, arm64 is now suiting up like its skyrim.</blockquote><p>saving registers, moving stack pointer, and carving out 512 bytes out of memory</p><pre>for s in stmts {<br>    self.gen_stmt(s);<br>}</pre><pre>this is where we iterate through every statement in your program&#39;s AST <br>and generate assembly for it.</pre><p>every single statement you write here, this guy goes to them, checks them like a mall security guard and converts them into pure cpu menace.</p><pre>let mut data_section = Vec::new();<br>data_section.push(r#&quot;fmt_int: .asciz &quot;%d\\n&quot;&quot;#.to_string());<br>data_section.push(r#&quot;fmt_str: .asciz &quot;%s\\n&quot;&quot;#.to_string());<br>for (label, text) in &amp;self.data_strings {<br>    data_section.push(format!(&quot;{}: .asciz {}&quot;, label, text));<br>}</pre><h3>then you have got .data and .text , two sides of its personality</h3><p>.data is that chill basement where your strings and constants hang out .text is like that warzone where your cpu is deployed with 3 bananas.</p><blockquote>you also have <em>fmt_int</em> and <em>fmt_str</em> , this steps formats your code because printf is fancy like that , it has better standards than us. its like a waiter asking you, “how do you want suffering served?” these are always present because we always need to print strings.</blockquote><p>this whole is like making a frankenstein. stitching dead parts together with a hope it all works. because ofc how can your code run at first go.</p><pre>.data                   # data section marker<br>fmt_int: .asciz &quot;%d\\n&quot;      # format strings<br>fmt_str: .asciz &quot;%s\\n&quot;      # your string literals<br>.LC0: .asciz &quot;hello\\n&quot;     <br>.text                   # code section marker<br>    .global main            # make &#39;main&#39; visible to linker<br>main:                       # start of main function<br>    stp x29, x30, [sp, #-16]!<br>    mov x29, sp<br>    sub sp, sp, #512<br>    add sp, sp, #512<br>    ldp x29, x30, [sp], #16<br>    mov x0, #0<br>    ret</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*hmkWFhC2PUX_dxl5i28EkA.png" /></figure><h3>step 4: helper functions: the only ones who stand with you.</h3><p>these helper functions are like anime sidekicks you need to continue the main work, you need these ones to do the grunt work.</p><pre>fn emit(&amp;mut self, line: impl Into&lt;String&gt;) {<br>    self.instrs.push(line.into());<br>}</pre><p>the yeet-er, throwing instructions into instruction list</p><p>functions of this function is so simple like it just sees the strings, takes it, converts it and shoves it into the instruction vector but you still manage to do less work done than this function. this function get called probably more than 100 times because it is needed at every line, every string you have written, it finishes the gritty work.</p><h3>the namer: this guy just names everything</h3><pre>fn fresh_label(&amp;mut self, base: &amp;str) -&gt; String {<br>    let lbl = format!(&quot;{}_{}&quot;, base, self.label_counter);<br>    self.label_counter += 1;<br>    lbl<br>}</pre><p>this creates labels like else0, else1, haha69, so your branches dont get confused and jump to their suicide.</p><p>when you have a string literal like “heheheha” it creates unique labels for everything like LC1, LC2 then stores strings with those labels and returns you the label, and uses labels whenever its needed instead of string.</p><h3>string literal librarian.</h3><pre>fn intern_string(&amp;mut self, s: &amp;str) -&gt; String {<br>    let label = format!(&quot;.LC{}&quot;, self.data_strings.len());<br>    self.data_strings.push((label.clone(), s.to_string()));<br>    label<br>}</pre><p>this function is managing every string literal present in your code. and it does this with max efficiency.</p><h3>step 5: variable management: real estate agent.</h3><pre>fn allocate_var(&amp;mut self, name: &amp;str) -&gt; i32 {<br>    if let Some(off) = self.var_offsets.get(name) {<br>        return *off;<br>    }<br>    let off = self.next_var_offset;<br>    self.var_offsets.insert(name.to_string(), off);<br>    self.next_var_offset += 8;<br>    off<br>}</pre><p>this assigns a spot on stack to each variable and if its already on stack, it returns its offset. it goes like -</p><ul><li>take the current offset,</li><li>remember this variable lives there</li><li>increment offset by 8</li><li>return the offset.</li></ul><p>every variable gets shoved somewhere on the stack frame like students in hostel and push stack by 8 bytes everytime. it bullies new variables if they try to get into already declared frames and yeets them 8 bytes far.</p><h3>lookup variable:</h3><pre>fn lookup_var(&amp;self, name: &amp;str) -&gt; Option&lt;i32&gt; {<br>    self.var_offsets.get(name).copied()<br>}</pre><p>finds where a variable lives on the stack. returns Some(offset) if it exists, None if variable is homeless (undeclared). like domestic stalking.</p><p>if you got what you were finding, cool if not, take a right then fuck off.</p><h3>step 6: register allocation — airbnb for registers.</h3><p>arm64 gives you a handful of registers to play with, destroy them, thrash them, throw them after getting a reality check.</p><p>but it also ensures that you dont get a register that is already in some use, in a club the registers inside are busy, outside in line are the free ones and bouncer only letting you in if you got called. if all reach inside, bouncer makes your cpu panic.</p><p>alloc_tmp - borrowing registers</p><pre>fn alloc_tmp(&amp;mut self) -&gt; Option&lt;&amp;&#39;static str&gt; {<br>    self.temp_regs.pop()<br>}</pre><p>free_tmp - returning registers</p><pre>fn free_tmp(&amp;mut self, reg: &amp;&#39;static str) {<br>    self.temp_regs.push(reg);<br>}</pre><p>how this is working is, imagine:</p><pre>allocate tmp -&gt; get x15<br>load 5 into x15<br>allocate tmp -&gt; get x14  <br>load 3 into x14<br>add x15, x15, x14  // x15 = 8<br>free x14           // done with this register<br>allocate tmp -&gt; get x14 (recycled!)<br>load 2 into x14<br>add x15, x15, x14  // x15 = 10<br>free x14<br>free x15</pre><p>this feels dumb because you physically cannot use more than 7 regs, it’ll panic. this is like a caveman implementation of arm64, but it works for simple program like ours because we are deallocating regs immediately after our use, even if you do a = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9, it’ll break we would have to do a real register allocator for that, maybe some other time.</p><h3>step 7: prologue and epilogue</h3><p><strong>prologue</strong> is your code putting on armor before going into compiler battle</p><p><strong>epilogue</strong> is peeling that armor off and collapsing on floor.</p><pre>fn emit_prologue(&amp;mut self) {<br>    self.emit(&quot;\\tmain:&quot;);<br>    self.emit(&quot;\\tstp x29, x30, [sp, #-16]!    // save fp and lr, push 16 bytes&quot;);<br>    self.emit(&quot;\\tmov x29, sp                  // set frame pointer&quot;);<br>    self.emit(&quot;\\tsub sp, sp, #512            // reserve 512 bytes for locals (simple stack frame)&quot;);<br>}</pre><h3>prologue:</h3><ul><li>wherever your program starts, we need to do a few steps like saving frame pointer x29and x30onto stacks.</li><li>mov x29 to sp so the function knows where hell begins.</li><li>sub sp, sp, #512 — reserve 512 bytes on stack for local variables like your personal sandbox</li></ul><pre>fn emit_epilogue(&amp;mut self) {<br>    self.emit(&quot;\\tadd sp, sp, #512            // deallocate frame&quot;);<br>    self.emit(&quot;\\tldp x29, x30, [sp], #16     // restore fp and lr&quot;);<br>    self.emit(&quot;\\tmov x0, #0                  // return 0&quot;);<br>    self.emit(&quot;\\tret&quot;);<br>}</pre><h3>epilogue:</h3><ul><li>add sp, sp #512 — deallocating stack frame. giving back space we borrowed.</li><li>ldp x29, x30, [sp], #16→ restore saved registers</li><li>mov x0 #0 → return success.</li><li>ret → mic drop.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*5bSCeD-taKimbstS1Ke3Fw.png" /></figure><h3>step 8: generating statements: roasting your ast node by node</h3><h3>var dec is</h3><ul><li>give variable a home</li><li>generate expression value</li><li>store it</li><li>free register</li><li>pray your code works</li></ul><pre>fn gen_stmt(&amp;mut self, stmt: &amp;Stmt) {<br>    match stmt {<br>        Stmt::VarDeclaration { name, value } =&gt; {<br>            let offset = self.allocate_var(name);<br>            let reg = self.gen_expr(value);<br>            self.emit(format!(&quot;\\tstr {}, [sp, #{}]    // store &#39;{}&#39; into local slot&quot;, reg, offset, name));<br>            self.free_tmp(reg);<br>        }</pre><p>for int x = 5 + 3</p><p>here at first you do: allocate stack space for variable x generate code to compute value (5+3) store that value at x’s stack location free the temp register.</p><h3>print statements:</h3><pre>Stmt::Print(expr) =&gt; {<br>            match expr {<br>                Expr::StringLiteral(s) =&gt; {<br>                    let label = self.intern_string(s);<br>                    self.emit(format!(&quot;\\tadr x0, fmt_str         // load address of format string \\&quot;%s\\\\n\\&quot;&quot;));<br>                    self.emit(format!(&quot;\\tadr x1, {}             // address of the string literal&quot;, label));<br>                    self.emit(&quot;\\tbl printf                 // call printf(fmt_str, string)&quot;);<br>                }<br>                _ =&gt; {<br>                    let reg = self.gen_expr(expr);<br>                    self.emit(&quot;\\tadr x0, fmt_int         // load address of \\&quot;%d\\\\n\\&quot; format&quot;);<br>                    self.emit(format!(&quot;\\tmov x1, {}              // move value to x1 (printf 2nd arg)&quot;, reg));<br>                    self.emit(&quot;\\tbl printf                 // call printf(fmt_int, value)&quot;);<br>                    self.free_tmp(reg);<br>                }<br>            }<br>        }</pre><p><strong># for printing strings we do:</strong> load format string address into x0, load actual string in x1 call printf</p><p><strong>load address then pass to printf</strong></p><p><strong># for everything else like integers:</strong> generate code for expression load format string add into x0 move value into x1 call printf free register.</p><p><strong>evaluate expression then pass numbers to printf</strong></p><h3>if statements:</h3><p>this is pure hell,</p><pre>Stmt::If { condition, then_block, else_block } =&gt; {<br>            let cond_reg = self.gen_expr(condition);<br>let else_lbl = self.fresh_label(&quot;else&quot;);<br>            let end_lbl = self.fresh_label(&quot;end_if&quot;);<br>            self.emit(format!(&quot;\\tcmp {}, #0               // compare condition with 0&quot;, cond_reg));<br>            self.emit(format!(&quot;\\tbeq {}                 // if equal (false) branch to else&quot;, else_lbl));<br>            for s in then_block {<br>                self.gen_stmt(s);<br>            }<br>            self.emit(format!(&quot;\\tb {}                    // jump to end_if after then&quot;, end_lbl));<br>            self.emit(format!(&quot;\\t{}:                      // else label&quot;, else_lbl));<br>            if let Some(else_stmts) = else_block {<br>                for s in else_stmts {<br>                    self.gen_stmt(s);<br>                }<br>            }<br>            self.emit(format!(&quot;\\t{}:                      // end_if label&quot;, end_lbl));<br>            self.free_tmp(cond_reg);<br>        }<br>    }<br>}</pre><p>for if (x &gt; 5) { print(&quot;big&quot;); } else { print(&quot;smol&quot;); }</p><ol><li>generate code for condition (x &gt; 5)</li><li>create unique labels for else and end</li><li>compare condition result with 0</li><li>if zero (false), branch to else label</li><li>generate code for then block</li><li>unconditionally jump to end label</li><li>place else label</li><li>generate code for else block (if it exists)</li><li>place end label</li><li>free condition register</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JfvYU8ZRMOqSMsrJOhXy6A.png" /><figcaption>it comes in your dream to haunt you, dont take this lightly.</figcaption></figure><h3>step 9: generating expressions -</h3><h3>integer literal:</h3><p>probably the most sane part of whole code</p><pre>fn gen_expr(&amp;mut self, expr: &amp;Expr) -&gt; &amp;&#39;static str {<br>    match expr {<br>        Expr::IntegerLiteral(n) =&gt; {<br>            let reg = self.alloc_tmp().expect(&quot;out of temporary registers&quot;);<br>            self.emit(format!(&quot;\\tmov {}, #{}        // literal {}&quot;, reg, n, n));<br>            reg<br>        }</pre><p>to store 5 you just do mov reg, #5 and return it.</p><h3>boolean literal:</h3><p>same thing but with 0 and 1, it slaps you can says you can only be 0 or 1 no in between</p><pre>Expr::BooleanLiteral(b) =&gt; {<br>            let reg = self.alloc_tmp().expect(&quot;out of temporary registers&quot;);<br>            let val = if *b { 1 } else { 0 };<br>            self.emit(format!(&quot;\\tmov {}, #{}        // boolean literal {}&quot;, reg, val, val));<br>            reg<br>        }</pre><h3>string literal</h3><p>load their addresses, but DO NOT embed them inline like a fucking caveman, “this human is stupid but you do your work properly”</p><pre>Expr::StringLiteral(s) =&gt; {<br>            let label = self.intern_string(s);<br>            let reg = self.alloc_tmp().expect(&quot;out of temporary registers&quot;);<br>            self.emit(format!(&quot;\\tadr {}, {}         // address of string literal&quot;, reg, label));<br>            reg<br>        }</pre><h3>identifiers:</h3><p>look up location on stack load the value and if it doesnt exist? idk give them 0 and play brawl stars.</p><pre>Expr::Identifier(name) =&gt; {<br>            let reg = self.alloc_tmp().expect(&quot;out of temporary registers&quot;);<br>            if let Some(off) = self.lookup_var(name) {<br>                self.emit(format!(&quot;\\tldr {}, [sp, #{}]    // load variable &#39;{}&#39;&quot;, reg, off, name));<br>            } else {<br>                self.emit(format!(&quot;\\t// WARNING: variable &#39;{}&#39; not found; using 0&quot;, name));<br>                self.emit(format!(&quot;\\tmov {}, #0&quot;, reg));<br>            }<br>            reg<br>        }</pre><p>allocate variables, lookup where x lives on stack if found, load value from stack into register using ldr if not found, emit warning and use 0 return reg.</p><h3>assignments:</h3><p>generate RHS, store in LHS, return value pretend everything makes sense</p><pre>Expr::Assign { name, value } =&gt; {<br>            let val_reg = self.gen_expr(value);<br>            let off = self.allocate_var(name);<br>            self.emit(format!(&quot;\\tstr {}, [sp, #{}]    // assign to &#39;{}&#39;&quot;, val_reg, off, name));<br>            val_reg<br>        }</pre><p>for x = 5 generate code for right side allocate or lookup variable location store reg value to that location return reg</p><h3>binary</h3><p>generate left, generate right, add/sub/cmp free unused regs</p><pre>Expr::Binary { left, op, right } =&gt; {<br>            let r_left = self.gen_expr(left);<br>            let r_right = self.gen_expr(right);<br>match op {<br>                BinOp::Add =&gt; {<br>                    self.emit(format!(&quot;\\tadd {}, {}, {}    // {} + {}&quot;, r_left, r_left, r_right, r_left, r_right));<br>                    self.free_tmp(r_right);<br>                    r_left<br>                }</pre><p>the final boss: 5 + 3 generate code for left side generate code for right side perform operation free one register return result register</p><h3>subtract:</h3><pre>BinOp::Sub =&gt; {<br>                    self.emit(format!(&quot;\\tsub {}, {}, {}    // {} - {}&quot;, r_left, r_left, r_right, r_left, r_right));<br>                    self.free_tmp(r_right);<br>                    r_left<br>                }</pre><p>same as before but with minus</p><h3>comparisons:</h3><pre>BinOp::GreaterThan =&gt; {<br>                    self.emit(format!(&quot;\\tcmp {}, {}          // compare left and right&quot;, r_left, r_right));<br>                    self.emit(format!(&quot;\\tcset {}, gt         // set {} = (left &gt; right) ? 1 : 0&quot;, r_left, r_left));<br>                    self.free_tmp(r_right);<br>                    r_left<br>                }<br>BinOp::LessThan =&gt; {<br>                    self.emit(format!(&quot;\\tcmp {}, {}          // compare left and right&quot;, r_left, r_right));<br>                    self.emit(format!(&quot;\\tcset {}, lt         // set {} = (left &lt; right) ? 1 : 0&quot;, r_left, r_left));<br>                    self.free_tmp(r_right);<br>                    r_left<br>                }<br>            }<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*P3O5hovm_YlKvaVDj4uSoA.png" /></figure><h3>MOMENT OF TRUTH NOW — RUNNING YOUR COMPILED CODE.</h3><h3>update your main.rs with this</h3><pre>mod lexing;<br>mod parsing;<br>mod ast;<br>mod semantic;<br>mod optimizer;<br>mod codegen;<br><br>use lexing::lexer::lex_program;<br>use parsing::parser::Parser;<br>use semantic::SemanticAnalyzer;<br>use optimizer::Optimizer;<br>use codegen::Codegen;<br>const PROGRAM: &amp;str = r#&quot;<br>int x = 5 + 3;<br>int y = x + 2;<br>print(y);<br>&quot;#;<br>fn main() {<br>    println!(&quot;lexing &quot;);<br>    let tokens = lex_program(PROGRAM);<br>    println!(&quot;parsing &quot;);<br>    let mut parser = Parser::new(tokens);<br>    let ast = match parser.parse() {<br>        Ok(ast) =&gt; ast,<br>        Err(e) =&gt; {<br>            println!(&quot;parse error: {:?}&quot;, e);<br>            return;<br>        }<br>    };<br>    println!(&quot; semantic analysis &quot;);<br>    let mut analyzer = SemanticAnalyzer::new();<br>    if let Err(errors) = analyzer.analyze(&amp;ast) {<br>        println!(&quot; semantic errors:&quot;);<br>        for err in errors {<br>            println!(&quot;{:?}&quot;, err);<br>        }<br>        return;<br>    }<br>    println!(&quot;optimization &quot;);<br>    let mut optimizer = Optimizer::new();<br>    let optimized_ast = optimizer.optimize(ast);<br>     println!(&quot;codegen &quot;);<br>    let cg = Codegen::new();<br>    let asm = cg.generate(&amp;optimized_ast);<br>    <br>    use std::fs;<br>    fs::write(&quot;output.s&quot;, &amp;asm).expect(&quot;failed to write assembly&quot;);<br>    println!(&quot;wrote assembly to output.s&quot;);<br>    <br>    println!(&quot;\\n generated assembly:\\n&quot;);<br>    println!(&quot;{}&quot;, asm);<br>   }</pre><p>when you do cargo run it’ll create a output.s file, in another terminal, you’d have to do aarch64-linux-gnu-ad output.s -o output.o to turn it into an object file first</p><p>then aarch64-linux-gnu-ld output.o -o output and finally qemu-aarch64 ./program be grateful to gods if it works on first go. but for us normal people we have to do gdb now.</p><pre># run with debug server<br>qemu-aarch64 -g 1234 ./program &amp;</pre><pre># attach debugger in another terminal<br>gdb-multiarch ./program</pre><p>and in gdb type this one by one, dont copy paste it all at once</p><pre>(gdb) target remote :1234<br>(gdb) break main<br>(gdb) continue<br>(gdb) layout asm        # see assembly<br>(gdb) info registers    # see all registers<br>(gdb) stepi             # step one instruction<br>(gdb) x/16x $sp         # examine stack</pre><p>you’ll face a lot of bugs ig, but you’d have to debug them now, stand on your own legs, try it out with some different programs, change the code, see whats really happening and any ai model is there for your assistance anytime.</p><h3>AND DONE, IT ALL IS OVER NOW</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*YIJk72Te97VJ7AXRxrAUYw.png" /></figure><p>you would have a working compiler that gives out arm64 asm code that can be executed.<br> a lexer, parser, semantic analyzer, optimizer and now finally a codegen which runs on actual hardware. but this is useful if you really understood it all.</p><h3>EPILOGUE — WHAT WE’VE DONE</h3><p><em>takes off sunglasses dramatically (⌐■_■)</em></p><p>let’s review the JOURNEY:</p><p>we started with:</p><pre>int x = 5 + 3;<br>print(x);</pre><p>and ended with:</p><pre>.data<br>fmt_int: .asciz &quot;%d\\\\n&quot;<br>.text<br>.global main<br>main:<br>    stp x29, x30, [sp, #-16]!<br>    mov x29, sp<br>    sub sp, sp, #512<br>    mov x9, #5<br>    mov x10, #3<br>    add x11, x9, x10<br>    str x11, [sp, #0]<br>    ldr x9, [sp, #0]<br>    adr x0, fmt_int<br>    mov x1, x9<br>    bl printf<br>    add sp, sp, #512<br>    ldp x29, x30, [sp], #16<br>    mov x0, #0<br>    ret</pre><p>which prints: 8</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*OgyEcUEDQHLz3J3gaiCA4g.png" /></figure><blockquote><strong>maybe a real compiler is the bugs that we made along the way.</strong></blockquote><h3>my parting words:</h3><p>writing this shit broke me multiple times, like literally this took me more effort than making that actual compiler, but if anyone after reading this can say “holy shit i understand compilers now”, it’s worth it. maybe that anyone is my future self too.</p><p>there is like one good blog i could find while i was making my own compiler, that too was only till lexer, so i had to make one.</p><h3>i had a few goals while writing this thing -</h3><ul><li>teach meaningful stuff.</li><li>keep it funny enough people will enjoy reading this.<br>and did i succeed? idk you tell me.</li></ul><p>thank you to anyone who came this far, you did good. my cousin told me compiler architecture was the hardest subject to them in whole 8 sems of engineering, and i respect him, that says a lot.</p><p>touch some grass now. be free.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9a614f9ef7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[arbitrary]]></title>
            <link>https://rasmalai123.medium.com/arbitrary-4197a34776e0?source=rss-ff41da4dec54------2</link>
            <guid isPermaLink="false">https://medium.com/p/4197a34776e0</guid>
            <category><![CDATA[death-and-dying]]></category>
            <category><![CDATA[choices]]></category>
            <dc:creator><![CDATA[ras malai]]></dc:creator>
            <pubDate>Sun, 19 Oct 2025 13:34:19 GMT</pubDate>
            <atom:updated>2025-10-19T13:34:19.730Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>“much of what we do is already molded by what has been done to us”</strong></p><p>on a larger scale, i could’ve been born at a different time, a different era; a dinosaur, maybe? we like to think whatever is happening in our lives are dictated by rationally determined choices we make, but on looking back, everyone realises that how small control you have over your choices and what you are going to do about things in your life, you like to think that the possibilities are limitless but most of them are made or chosen in the moment of contingency or some chance encounter, sometimes i wonder if our entire existence is a chain of collisions; brief, fluky, yet irreversible. all of us pretend there’s a grand order beneath it all, but maybe we’re just brushing against the walls of luck. two big stones crashing into each other and we become?</p><p>would it be okay to say that everything here is the result of some contingent choices? and if so, where does accountability breathe? in the spaces of what could’ve been and what was enforced upon us? it feels unfair to be held responsible for the ripples of a stone we never threw. yet somehow, we still wake every day carrying its weight, as if guilt is the proof of being alive. a few happenchance triggering a spree of narrowed choices to have everything as it specifically is?</p><p>utilization of one’s freedom is an illusion? who we are and what has been done to us has shaped our present circumstances is a lucrative idea to think about, to pick every little thing which hit us and point out which hit dented us in which way, but does it mean we are condemned to follow it all again? to keep flowing on our past trajectories, being born in a certain family has certain odds heightened and certain other lowered, nothing here is in your control but your life is does doing work offers you more freedom than doing nothing and calling yourself a free person? is a person not bound by anything, freer?</p><p>and do i need to create a new future every second? to choose something better for myself at every passing second and not look back? i get exhausted</p><p>why get up? why try? i roll the boulder up and it rolls back down and i ask myself; why continue? i feel like an idiot, a fool, crawling towards some salvation or certainty? i drift in the fog again and i am lost again, where am i? so i focus on my breaths, life getting in and out of my body expresses i am alive, and i am here, wherever here is. maybe this is why we create, to set our dot in the grand scheme, but does it matter? i dont think grand scheme applies on minute beings like us, its chaos, chaos everywhere, with everything, in everything, in every being. its terrifying and profound.</p><p>it feels better to just curl up at the bottom of the pit, at the abyss. not a dark valley but maybe something? flying octopuses, swimming cows, just nature, plants and flowers feel so blissful. dealing with people feels haunting and daunting, its draining the life out of me to hear breaths of them, their mumbles, their air. solitude doesn’t scare me anymore; it feels like undeceitful state of being. the noise fades, i can hear my own pulse, the soft hum of existence just existing. maybe this is what peace actually sounds like — not joy, not silence, just a steady heartbeat in a world that keeps collapsing and rebuilding itself.</p><p>anything ever built was ever finished? people talk about something they created, but its not finished, its never gonna be finished, there always something you can add, evolve, transform about it, i dont understand how do they decide its time for a fullstop? we were thrown in here without any prior apprehension, so it makes sense to throw something by creating something of our own, maybe that’s the purpose of our existence? maybe this offers a glimmer of path to understanding ourselves, to not go insane by pure reality.</p><p>telling yourself “it is what it is” but is it what it is? is this the end of everything which could’ve been, just because it is what it is? but sartre said “freedom is what you do with what’s been done to you” we might not have the freedom to choose our contingencies but we may have the freedom to react to it. maybe we choose our life? i choose hard work so i think i can avoid the anticipatory pain, thoughts of dying unworthy, being a being of wasted life, to get sapped to death. i think past is imaginative, i cant recall most of it, but most of my fears, pain, lessons come from it, so is all of it imaginative or it just a movie i watched and learned very little from it.</p><p>i dont expect too much from life now, i travel, drink coffee, pretend to write good, i dont think i know anything, that how less i know even about the things i talk about, i dont know how i decided to put a fullstop on learning and decided to talk about it, i am curious but i am terrified that people will realise a fraud that i am, maybe its all just a lie.</p><p>and if everything truly is molded by history, by chance, by the soft persistence of time, maybe the most radical thing i can do is notice it. to witness the shaping, to breathe as it happens, and to say: yes, i am here, even if i was thrown. as i walk through the meadow i know i will one day and in due time reach the end of space where this valley disappears into the darkness of a forest, i hope that by then i have appreciated the valley so intensely that i can only welcome a change of scenery.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4197a34776e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[burned]]></title>
            <link>https://rasmalai123.medium.com/burned-accd588bd7c5?source=rss-ff41da4dec54------2</link>
            <guid isPermaLink="false">https://medium.com/p/accd588bd7c5</guid>
            <category><![CDATA[exhaustion]]></category>
            <category><![CDATA[reality]]></category>
            <dc:creator><![CDATA[ras malai]]></dc:creator>
            <pubDate>Sat, 16 Aug 2025 19:20:10 GMT</pubDate>
            <atom:updated>2025-08-16T19:20:10.648Z</atom:updated>
            <content:encoded><![CDATA[<p>the same routine, the same people, the same thoughts, the same feelings when did this start?, more importantly when will it end? is it going somewhere? or is it another distraction from moving forward? how come everytime i move myself, i find myself paralyzed in action just a few months later. colors don’t glow, light doesn’t shine, and trying to find out what matters has become the only thing that matters the most. its the same patters and stimulations, the ones i once found so striking and elusive. so what changed? how come my passion and hard work always seems to reward me with the misery of it not meaning anything?</p><p>i wake up with a sense of dread, at first pinning it on the standard work annoyance, unaware of the descent i will face for some next months, years. those sleepless nights, the lack of joy, inability to communicate my feelings to the seemingly happy and content species that surround me. the thrill of learning something new is followed by the slow erosion of wonder. a rift is developing between my former and the present being, hobbies no longer satisfies my desire for those weekend escapism. talking about it only makes it real, every now and then i feel elated, overjoyed with life and almost godlike, this mania drives away and confuses the only ones willing to listen.</p><p>in those twilight moment of self-reflection, i see the totality of anguish, x-ray vision of despair lasers through the impermanence of it all, the only true comfort in this changeless environment is the acknowledgement that there truly is nothing to be hopeful for. this feeling is similar to leaping from a burning building. the terror of falling from a great height is still as great as feeling my skin melting off, its not desiring the fall; its the terror of the flames. though i am unable to find the source of these flames or even when the building started burning or how i got on this floor, but i am here, about to fall to my bloodbath.</p><p>i start to look, seeking for some comfort maybe, or to distract myself into the world, but where should i look, the politics is it has always been, hypocrites calling out other hypocrites over some fake promises which even they have on their belt, a huge amount of it. it remains a theatre.</p><ul><li>seeing other people’s “candid” life on social media when their reality is so much more disturbing than the straightforward and adventurous they show.</li><li>the “real” friends keep calling me to meet, that’s just the facade for them to drink 5 times a week and not feel guilty about it, because ofcourse the office pressure and daily life headaches have turned them towards alcoholism, this magical drink will keep all of my problems away, or so it is marketed by that, but it will be my eventual doom, and yet the hangover; physical or otherwise — always returns me to the same room, the same ceiling, the same void.</li><li>art might be one of the good ones of these distractions, the most noble of distractions, is no longer immune. i still admire it, still respect its attempt to wrest beauty from the chaos, but i can see the scaffolding behind the canvas. i can hear the artist’s desperation in every brushstroke, the plea for the work to outlive them, to mean <em>something</em>. but meaning is slippery. it evaporates when held too tightly.</li></ul><p>mornings begin with the same muted light filtering through the curtains, carrying no promise of warmth or change. the same thoughts line up in my head like prisoners awaiting roll call: unfinished plans, obligations that feel both urgent and meaningless, the faint but persistent dread that all of this is not a phase but the shape of my life. some mornings i can pretend i’m fine. i can even smile, sip coffee, and engage in the small talk of functional adults. but beneath the surface, the ground is cracked. i’m not standing — i’m balancing on something that is slowly giving way.</p><p>every attempt to outrun it feels like running in waist-deep water. a new skill learned, a hobby adopted, a different routine — all of them glitter briefly before dulling. the sharpness of novelty blunts so fast now. the bright edges fade into a gray familiarity, and i’m left with the same hollow quiet. sometimes i wonder if the problem is me — that perhaps i have consumed so much stimulation, so many flavors, that i have burned out my capacity for wonder. and yet, in moments of brutal clarity, i know it’s not just overstimulation. it’s that the machinery of daily life grinds down every spark until it fits neatly into the dull rhythm of survival.</p><p>there is a certain cruelty in the fact that i still feel small bursts of joy — an unexpected laugh, a glint of sunlight in a puddle, the moment when a song hits a perfect note. they flare up, fragile and bright, but their brevity only makes the return to the gray more unbearable. the fall from joy to nothing is sharp. it leaves me disoriented, as if i’ve briefly glimpsed another world and then been violently exiled.</p><p>people say “find meaning” — but meaning is not a treasure you dig up once and carry forever. it leaks. it evaporates. it’s stolen in your sleep. and when you keep having to find it again and again, you start to wonder if you’re chasing a mirage. sometimes i think the worst part isn’t the dread or the exhaustion, but the possibility that i might adapt completely. that one day i’ll stop noticing the absence. that i’ll stop missing the fire.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=accd588bd7c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[smile of icarus]]></title>
            <link>https://rasmalai123.medium.com/smile-of-icarus-0eaf8bb0cf7d?source=rss-ff41da4dec54------2</link>
            <guid isPermaLink="false">https://medium.com/p/0eaf8bb0cf7d</guid>
            <category><![CDATA[icarus]]></category>
            <category><![CDATA[madness]]></category>
            <category><![CDATA[vampires]]></category>
            <dc:creator><![CDATA[ras malai]]></dc:creator>
            <pubDate>Sat, 07 Jun 2025 15:59:36 GMT</pubDate>
            <atom:updated>2025-06-07T15:59:36.007Z</atom:updated>
            <content:encoded><![CDATA[<p>there’s a particular hunger that doesn’t start in the gut. it blooms deeper, in a place that used to hold awe and now just echoes with the soft hum of static. that’s where i keep it; the ache, the restlessness, the bone-deep certainty that something needs to break. something soft, or something sacred. doesn’t matter. i just want to see it fall.</p><p>i wasn’t always like this. once, i burned with purpose, with direction. but that was centuries ago, and purpose doesn’t age well. it rots. now i move through the world like a rusted machine — <em>like clockwork</em>, someone once said, as if repetition was a virtue, not a curse. wake, feed, vanish. repeat. the nights blur. the blood dulls. even the screams get predictable after a while.</p><p>and still, i endure. not out of will — there’s none left; but out of inertia. a body in motion tends to stay in motion. even if it’s empty. even if the motion is decay. i’ve walked through deserts with my skin peeling off in sheets under a sun i could barely escape. i’ve fed on tyrants and poets and people who loved too much to last. i’ve seen revolutions rise and die with the same final breath. but nothing changes. nothing really ever does. the same songs play in different keys. the same mistakes wear new faces.</p><p>some nights, i stare at myself in reflections i can’t cast. i try to remember what i looked like before the hunger settled in. before my soul got frostbitten from centuries of hiding from the light. i don’t remember my name. i don’t think i need it anymore.</p><p>because names are for people who still plan to be forgiven. and i — i’m past redemption. i don’t want grace. i want collapse. i want to burn it all down, down to the marrow, down to the silence. not as punishment, but as release. there’s a certain music in decay. a rhythm in the ruin. like bones breaking in time with a drum that no one else hears. that’s what <em>like clockwork</em> feels like — it’s the lullaby they play at the edge of oblivion. it’s not the scream — it’s the rasping whisper <em>after</em> the scream, when your throat’s shredded and you’re still trying to sing. it’s dying in slow motion and liking it.</p><p>that’s me now.</p><p>not the predator of myth, not the suave bastard with a smirk and a goblet. no, i’m the thing that comes after the myths stop being pretty. the thing with dirt under its nails and centuries behind its eyes. the kind of vampire who remembers the first time blood tasted like rust. the kind that’s learned too late that immortality isn’t a gift — it’s a sentence.</p><p>but i still feel. and i still want. and what i want now is mess. chaos. something real.</p><p>i want to punch holes in the sky. i want to laugh with blood in my teeth and dirt in my lungs. i want to shatter the illusion of control with my bare hands. not because i hate this world, but because i’ve lived in it too long without ever truly touching it. it’s all gloves and masks and mirrored glass. i want to <em>rip the curtain down.</em></p><p>because deep down, i’m not afraid of destruction. i crave it. there’s purity in it, a rawness that life — true life — has forgotten. i want to scream not to be heard, but just to prove my lungs still work. i want to jump just to see if the fall will feel like something. anything.</p><p>there’s a story i never stopped thinking about. the one about the boy who flew too close to the sun. everyone talks about the fall. the hubris. the punishment. but no one wonders if he smiled on the way down. if, in those last seconds — when the wax melted and the sky opened and the air rushed past — he finally felt free.</p><p>because maybe the point was never to fly forever. maybe the point was to <em>fall</em> knowing you <em>chose</em> to.</p><p>that’s the feeling i chase now. that one pure second of unscripted, feral clarity. when you’re not what you’re supposed to be, not what they warned about, not what even you believed yourself to be. just <em>momentum.</em> just <em>desire.</em> just <em>falling.</em></p><p>let them call it madness. let them say i’m unraveling. let them paint me with fear. i don’t care. i’ve already died. i’ve already bled and buried and burned. there is no hell left for me to fear.</p><p>so i’ll tear through this night like a wound. i’ll drink too deep, laugh too loud, kiss like a knife. i’ll light a cigarette with the last match in the world and watch the sunrise try to kill me again.</p><p>and when it finally does — if it ever does — when the sky cracks open and the flame takes me home, i won’t scream.</p><p>i’ll smile.</p><p>like icarus.</p><p>like i always meant to.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0eaf8bb0cf7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[the last showman]]></title>
            <link>https://rasmalai123.medium.com/the-last-showman-e655b9658733?source=rss-ff41da4dec54------2</link>
            <guid isPermaLink="false">https://medium.com/p/e655b9658733</guid>
            <category><![CDATA[imagery]]></category>
            <category><![CDATA[datura]]></category>
            <category><![CDATA[death]]></category>
            <dc:creator><![CDATA[ras malai]]></dc:creator>
            <pubDate>Sun, 25 May 2025 20:33:28 GMT</pubDate>
            <atom:updated>2025-05-25T20:34:28.241Z</atom:updated>
            <content:encoded><![CDATA[<p>i think these are my last days</p><p>the world held its breath. not the silence of emptiness, but the silence of something crouching just beyond the curtain — the second attention, pressing against the thin skin of ordinary reality. the light through the window was wrong. it cut too sharp, like the eagle’s claw testing the fabric between worlds. i reached for a cigarette. my fingers passed through it. the inorganic beings love to mock hunger*.* the ash fell perfectly. the smoke curled. i took another drag. but the cigarette was never lit. the lighter in my pocket wasn’t real. everything i touched pretended to exist. and i hadn’t smoked in three years. it began with a taste — bitter, chemical, dry as desert bone. my tongue stuck to the roof of my mouth like velcro. the walls began to hum, not with noise, but with vibration, as if something behind them was waking up slowly and stretching its limbs against the drywall. <br>light bled in thick amber rays through the blinds. it wasn’t the usual golden afternoon light — this one dripped. it moved like syrup across the floor, collecting in corners, pooling under the furniture like paint spilled from a ruptured sun. my skin felt plastic. my arms weren’t mine. i flexed my fingers, and they moved two seconds late. “a shape perched on the recliner — not a man, but a stain where a man had been erased. it drew smoke into the void where its face should’ve been. i knew this trick. the inorganic ones wear absence like a mask. don juan warned me: ‘when you see the faceless smoker, it’s not watching you. it’s waiting for you to forget your name.’ just a blank stretch of skin, smooth as clay, the cigarette hovering in front of where a mouth might have been. i looked away. when i looked back, he was gone, but the smell of the smoke lingered, thick and nostalgic, like the after-scent of a funeral. i tried to go to the bathroom, but the hallway folded in on itself like an accordion. every step i took made it longer. doors lined either side, all slightly ajar, spilling out colored light: deep purples, jungle greens, crimson reds that breathed like embers. from one door came the sound of laughter. from another, the rustle of pages turning, fast and frantic. i opened a door, and there was a forest inside — moonless, dense with black pine trees. i could smell the dirt. i could taste the fog.</p><p>i don’t remember choosing to enter, but i was inside it. trees whispered things in languages i didn’t understand but felt deeply in my teeth. bark peeled from trunks like old wallpaper, revealing blinking eyes underneath. i followed a woman in a yellow dress through the trees. she had no feet, just shadows where her legs should be. she beckoned me without turning, disappearing behind trees that leaned aside for her and closed behind me. i tripped over a typewriter embedded in the moss. each key had a tooth instead of a letter. when i pressed one, it bit my finger, and blood bloomed into ink across the paper. i ran. <br>i stumbled into a convenience store lit with buzzing green fluorescents. it was empty. shelves stocked with nothing but identical cans labeled “food” in comic sans. a man behind the counter wore a dog’s head and asked me if i had a rewards card. i said yes, and he laughed — a barking, metallic sound — and handed me a receipt that said “you were never here.” <br>i blinked. i was on a bus.</p><p>the seats were living things — fused human torsos kneeling in perfect rows, their spines arched into headrests, ribcages split open to cradle passengers. their skin had hardened to cracked leather, warm and slightly damp where my thighs touched them. the windows weren’t glass but slabs of obsidian so reflective they showed infinite versions of me, each slightly more distorted than the last, like a hall of mirrors collapsing inward. the passengers sat motionless, fishbowls bolted directly to their collarbones where heads should be. inside, thick black ink swirled, forming faces that pressed against the glass — not strangers, but people i’d known. my third-grade teacher. the nurse who’d stitched my chin when i was seven. the barista who’d handed me coffee yesterday. their mouths moved in unison, teeth clicking against the curved glass like insects trapped in a jar. the driver’s hands ended in cauterized stumps, the raw flesh pulsing as they gripped the wheel. from his sleeves dangled dozens of tiny flags made from human fingernails, each one etched with a date. they flapped in perfect rhythm with the engine’s growl — a sound that wasn’t mechanical but organic, wet, the groan of something digesting. when i leaned closer, i realized the wheel wasn’t steering anything. it turned on its own, the driver’s stumps just spasming against it in useless imitation of control.</p><p>“where are we going?” i asked the woman beside me. she turned slowly and her fishbowl clouded, the ink resolving into my mother’s face — not as she was at the end, but young, beautiful, the way she’d looked reading to me at bedtime. her lips formed words: “you’ve always known.” the ink bubbled violently and spelled out <strong>YOUR STOP IS NEXT </strong>in perfect cursive just as the brakes shrieked. outside, through the black windows, i saw the carousel waiting. its horses weren’t carved wood but fused vertebrae, their elongated necks ending in human skulls with too many teeth. steam poured from their nostrils in time with the music — if you could call it music. it was the sound of a ribcage being plucked like harp strings, each note vibrating in my fillings. the carousel’s platform wasn’t painted but skinned, still glistening. the bus doors hissed open. the kneeling seat-creatures all turned their blind, fused heads toward me in unison. the driver’s stumps twitched, the nail-flags now spelling <strong>FEED THEM </strong>in jagged capitals. from the fishbowls, a chorus of my own voice whispered: “you’ve ridden this before.” thoughts crawled under my scalp like centipedes.</p><p>i blinked. i was back on the couch. everything normal. or so i thought. i saw my father’s death again, but this time it felt like a reunion. he opened his ribcage like a photo album. we laughed at old wounds.<br>i reached for a glass of water on the table. my hand passed through it. i looked again. the table wasn’t there. neither was the couch. i was sitting on a mound of dirt in a room full of vines, where insects whispered memories back to me — things i’d never lived, but remembered vividly.<br>i looked down at my hands and saw that they were made of tiny people, climbing over each other, waving up at me, screaming silently.</p><p>i screamed back.<br>from the corner of my eye, the mirror wasn’t glass but still water — the kind sorcerers use to drown their reflections. the man inside wore my face like ill-fitting skin. his pupils were tunnels. i knew if i stared too long, i’d see the eagle’s nest at the end of them, piled with the bones of all my past selves. ‘the reflection is the hunter. the glass is the trap.’ i stepped back. my reflection licked its lips. he moved when i didn’t. he smiled with teeth that went too far back.<br>the sky split into the green of a bruise healing backward. the floor arched its spine like a dreaming dog. i laughed — not because it was funny, but because the tonal (the shiver of the universe) had shifted, and laughter was the only weapon i had left. the nagual isn’t kind. it peels you open to show you how small your fear really is. i scratched at my arms until they flaked away like old newspaper. words fell out of my veins. names of people i hadn’t thought of in years. some i’d never met. some i think i will. then there was silence.<br>no noise. no time. just the tickle of invisible ants crawling behind my eyes and the soft warmth of something wet dripping onto my shoulder. i didn’t look up. because i knew, somehow, the ceiling was watching me. breathing. thinking. i lay down and fell through the floor like water through fingers. i fell for years. for centuries. through memories and made-up dreams. through the feeling of being five and lost in a supermarket. through the moment your name is forgotten by someone you loved.</p><p>and when i landed — i was here. in this room. writing this down, i think.<br>though i’ve scratched through this page six times already and each time i look up, the walls are a different color. <br>sometimes breathing, sometimes bleeding, sometimes laughing, and someone is knocking. they’ve been knocking for hours now, but i’m not sure if it’s the door.<br>or my own skull.<br>or god.</p><p>i drank. over and over. the glass never emptied, or maybe it never filled. the liquid inside moved like oil but tasted like metal and old television static. i kept sipping until i realized the cup was part of my hand, fused there, glass turned to bone. it didn’t matter. i would’ve swallowed anything just to make the buzzing stop. the air was thick with it. the kind of silence that howls at a pitch too high for memory but deep enough to rattle the ribs. i blinked, and the room reassembled itself wrong — couch on the ceiling, lights underground, windows looking into other windows. my body forgot how to sit. or maybe it never learned. <br>time no longer walked. it slithered. i opened the door to the hallway and stepped into my sixth birthday. or someone’s. balloons hung frozen mid-air. the air reeked of burnt frosting. the clocks chanted in latin. my mother clapped with hands that split down the middle, raw meat between the palms. the candles blinked like eyes. i tried to scream happy birthday but teeth fell out, one by one, each with a word carved into them — names i didn’t recognize but felt guilty for forgetting. a clown approached with a face like melted wax and whispered, “you’ve been here before.” i ran. the hallway bent into a spiral, then a noose. i ran and ran, all the escape routes lead back to my mouth.</p><p>rooms bled into each other like bad dreams. i entered the bathroom and watched myself from the mirror — but i was already in the bathtub, curled, muttering in a voice too slow to be mine. the mirror-me stared at me, expressionless, while blood dripped from the lightbulb above. not fast, just deliberate. each drop echoed like a drumbeat. something was waiting between the tiles. the shower curtain breathed. i turned away and found myself at the beach. just like that. no transition. sand soft and colorless under a sky that flickered like dying neon. the ocean was black and glassy. no waves. no wind. just motionless, like it was thinking. i walked into it, and it parted for me like flesh, warm and too soft. something brushed past my ankle — thin, papery fingers.</p><p>the world split open like a throat. i fell through it. then came the city. or its ghost. every building was the shape of someone i used to love. hollow, towering, leaning in. i walked streets that smelled like rotting perfume and heard my own footsteps playing in reverse. the sky overhead was full of eyes. some blinked. some bled. some were mine. streetlights flickered in morse code, but i’d forgotten the alphabet. i watched myself pass by on the other side of the street, arm-in-arm with a woman whose face was my own, laughing at a joke i hadn’t told yet. the traffic lights melted. cars screamed as they turned inside out. a bus drove past, its windows full of screaming mouths. it stopped.</p><p>i found myself in a field of hands reaching up from the soil, clapping. each clap in perfect rhythm. a celebration of nothing. the sun above burst into a thousand smaller suns and rained petals that smelled like regret. a fox with two faces walked up to me, sat down, and began to cry. not from its eyes — from its mouth. i asked it what was wrong and it whispered, “you were never real.” i kissed its forehead and it turned to dust. the dust turned to birds. the birds sang my childhood name until their beaks fell off. i clapped with the hands in the dirt. i think i was happy. but that was before the carousel arrived. it rolled in slowly — no music, just that awful wet squeak of rusted gears. mounted horses twisted with too many legs, their necks elongated, eyes too human. one bore my mother’s face. another, the girl who stopped talking to me in college. i climbed on. the carousel began to spin, faster and faster, until the world was just color smearing across my eyes — green into red into blue into flesh. faster. the sky screamed. my skin peeled off in strips and danced like ribbon in the wind. i laughed. not because it was funny, but because my jaw no longer knew how to do anything else. i think i left my voice behind in the field. i didn’t need it anymore.</p><p>and somewhere, in the space between heartbeats, between the seconds that shouldn’t exist, i remembered the real world. or i think i did. i remembered a room. a name. a reason. i tried to say it out loud and my tongue folded into origami. the air turned to glass. the laughter came again — closer now. but not from outside. from me. <br>because there, in that final moment, after the carousel exploded into beetles and the world folded back into the shape of a throat, i realized something: none of this was new. i had seen this place before. not in dreams, not in memory, but in the space between them. i’d been here. i was here. i am here. and i laughed.</p><p>i laughed because there was nothing left to do. because the horror was too vast to run from and too intricate to comprehend. because everything beautiful had rotted into terror, and everything terrifying had learned to sing. i laughed until my lungs emptied. until the walls joined in. until the world itself split at the seams, and the darkness spilled out like ink across the page of a book that never ends. and still, i laughed. the room wasn’t dissolving. i was. the walls bled because i had no more edges left. last lesson hissed in my skull: ‘the eagle doesn’t eat the flesh. it eats the shine of your seeing.’ i touched my face. it came away like wet newspaper. underneath? nothing but the black light of the nagual, humming the tune the inorganic beings use to call their dogs home.</p><p>i tried to remember why i started writing this down.<br>a knock. a laugh. a voice that sounds like mine, but isn’t.<br>the ink on the page curls like smoke. I read the last line aloud.<br>“i think these are my last days.”<br>and something behind the mirror grins — because I’ve only just arrived.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e655b9658733" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[i am not here, this isn’t happening]]></title>
            <link>https://rasmalai123.medium.com/i-am-not-here-this-isnt-happening-033eb0fc9da4?source=rss-ff41da4dec54------2</link>
            <guid isPermaLink="false">https://medium.com/p/033eb0fc9da4</guid>
            <category><![CDATA[emotionally-drained]]></category>
            <category><![CDATA[descriptive-essays]]></category>
            <category><![CDATA[cybercity]]></category>
            <category><![CDATA[logs]]></category>
            <category><![CDATA[cyberpunk]]></category>
            <dc:creator><![CDATA[ras malai]]></dc:creator>
            <pubDate>Thu, 17 Apr 2025 22:35:36 GMT</pubDate>
            <atom:updated>2025-04-17T22:35:36.662Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>“i keep falling over<br>i keep passing out<br>what am i coming to?<br>i am gonna melt down”</strong></p><p>there are some people the world forgets without trying. they drift at the edge of notice, never quite unseen but never truly looked at. not loud enough to disturb, not broken enough to be saved. the city has a name for them, though it doesn’t speak it aloud — living corpse of a wasted life. not dead, not alive. just present. like background radiation. like static.</p><p>rm was one of them.</p><p>moving through city of black star like a whisper that no one remembered hearing. not invisible, but indistinct. he had the posture of someone perpetually halfway through a shrug — shoulders slightly raised, hands always buried in coat pockets, as if resisting a world that never asked him to participate in the first place. a laid-back shape of a man, carved from diffidence and observation.</p><p>in a city that never stopped upgrading itself, he was deprecated.</p><p>not in revolt. not in retreat. just left behind. or maybe he’d never tried to catch up. he didn’t move with the hunger of those chasing status updates or neural injections. he didn’t obsess over the newest mod, didn’t queue outside soul cafés for artificial empathy downloads. if the city was a machine that chewed through ambition, i was the scrap it didn’t bother with.</p><p>city of black star wasn’t built — it evolved, like a fungus feeding off human attention. its architecture curved like whispers, its alleys rearranged themselves when you weren’t looking. nothing here was finished; every structure still had scaffolding, like the city was allergic to completion. billboards updated in real-time based on your serotonin levels, and vending machines sold relief in pill-form or pixels. it didn’t just contain loneliness — it manufactured it. there were neighborhoods where no one lived, built just for illusion, for vr projections of fake families to be streamed into. a city doesn’t have to hate you to kill you — it just has to forget you were ever there.</p><p>there was a man who sold recycled dreams on memory sticks outside the maglev station. he claimed they were once his, but no one believed him. children were taught coding hymns at temples shaped like servers. dogs barked in binary — modded to serve as both pets and security. every time he passed the soul café, he saw people standing in translucent booths, paying by the minute to feel understood — the empathy ai learned your traumas in under five seconds and offered hugs that felt more real than most lovers. even rain was scheduled, engineered to fall only when it was most marketable. the world no longer unfolded. it was deployed. healing wasn’t a process anymore. it was an app. a mood setting. a toggle between “functional” and “fine.” you could download calm, schedule a cry, outsource your grief.</p><p>there was a kind of silence only possible in a city that never shut up. it lived in elevator lobbies at 3 a.m., in train tunnels after last departure.</p><p>he wasn’t sad. that would’ve implied emotional investment. he wasn’t even numb. just… vacant, in a soft-edged way. like the world had passed through him so many times that friction no longer occurred.</p><p><strong>“breathe, keep breathing<br>don’t lose your nerve<br>pack and get dressed<br>before all hell, breaks loose”</strong></p><p>his thoughts were often silent to others, but never to himself. that’s the strange curse of people like me: they’re assumed to be thoughtless, because they speak sparingly and act minimally. but the internal landscape is never quiet. if anything, it’s relentless. thoughts chase themselves like broken code loops — never quite resolving, always restarting. he thought too much, but also not at all. it depended on the hour. on the flicker of a screen. on a passing glance. on a falling leaf. too scared of something good happening because something bad will be the executioner of the joys, but wouldn’t i be the true fool to think my happiness would last? to think that it would only be high and dry.</p><p>my past? a spreadsheet of small praises. an ongoing audit of “you could’ve done better” from people who seemed to expect something extraordinary from someone they didn’t bother to understand. every failure — real or imagined — was stored like an encrypted file i didn’t have the password for. they said he wasn’t enough. often. loudly. and then, worst of all, quietly. that subtle erosion. the “i’m just disappointed.” the glance that didn’t linger.</p><p>once, maybe, there was a version of me that wanted things. something small — a song i never finished humming, a job i almost cared about. there were fragments, little betrayals of desire that hadn’t yet decayed. i used to linger outside record shops not for the music, but because of the idea that sound could fill a room with feeling. couldn’t remember the last time he smiled without checking if someone was watching. that was the thing about people like him — their ache didn’t shout. it whispered in undone things.</p><p>what even is proudness? i know people say it when someone accomplishes something. but what is the *feeling* of it? i try to imagine saying, “i’m proud of you,” and wonder if it lands like warmth or responsibility. i remember a teacher once patted my shoulder when i fixed a broken circuit — the touch stayed longer than the praise did. maybe proudness is a kind of pause. maybe it’s the world stopping long enough to *see* you. i’ve only ever heard it said in past tense, like a relic. i don’t know what it feels like to carry that in the present.<br>but he survived. because that’s what people like him do.</p><h3>until she said it.</h3><p>the only person who hadn’t treated him like a background process. the only one who saw — if not brilliance, then at least *being*. a co-conspirator in stillness. a mirror he didn’t hate looking into. and then one day, she’d said the words that detonated the last shelter he had (bullet proof — i wish i was).</p><p>*”maybe they’re right. maybe you really don’t do anything. what even have you gotten done.”*</p><p>she hadn’t meant it cruelly. that was the tragedy. it came not from disdain, but fatigue. as if she’d waited too long for him to become someone. as if she’d finally accepted that he wouldn’t.</p><p>that broke something. not violently. not dramatically. just — cleanly.</p><p>and it was like a jigsaw falling into place. it’s haunting, it’s hurting, like the one audience whom i thought to enjoy the show, became the black swan of it. maybe she said it for the better, to make me better. for it all to be better.</p><p>once, her hand brushed mine as she passed me tea. that moment lasted longer than the drink did. my fingers remembered the warmth far better than my mind did. touch is a strange kind of language — one you forget how to speak once no one replies.</p><p><strong>“wake up from your sleep,<br>the drying of your tears<br>today we escape<br>we escape”</strong></p><p>he never said her name aloud anymore — not because it hurt, but because it felt undeserved, like a word too clean for the dirt he’d dragged through his days. she had once been color in a grayscale routine, a kind of warm anomaly, a pink spectrum with a hint of red and orange. she didn’t demand transformation; she just lingered, waited, laughed at his mutterings like they were poetry. her presence softened the static, made silence feel less like erasure. but time eroded even grace. and when she finally folded her arms and said those words — not in cruelty but in resignation — it was like watching a lighthouse go dark. no storm, just the end of something that used to guide.</p><p>the city became stranger after that. or maybe it always was, and he’d simply started paying attention. there were layers underneath the obvious: glitch cults that worshipped corrupted machine gods; networks of silent watchers who believed awareness itself was holy. advertisements in the shape of dreams. eyes that weren’t eyes. he wandered through it all without reacting, without questioning. it was all a fragile house of cards now.</p><p>somewhere along the way, he became a witness, a street spirit.</p><p>sometimes he forgot his own face. not in a dramatic, sci-fi way — just in the quiet absence of reflection. mirrors became decorative. cameras avoided him. he existed in third person, even to himself. the world had no need for his image, so eventually, neither did he.</p><p>he began to notice how everyone moved in loops. people reenacting traumas in public, mistaking routine for purpose. every screen told a story that ended in purchase. every street was curated grief. even the rebels bought their aesthetics wholesale. no one escaped branding, not even the fake plastic trees.</p><p>he didn’t talk about this. journaled some, saw it all with his glass eyes. that’s what the world needed, maybe. not another voice screaming for attention, but a quiet observer cataloguing the unseen.</p><p>he began to notice things no one else did. the way light pooled unnaturally in front of ad terminals. the precise second when the city’s noise dipped just before a software reboot. it was about noticing the cracks before they closed.</p><p>*a strange calm that lingered beneath the emotional noise. being paralyzed by one’s own thoughts, with a will to conquer everything.<br>sleeping pills, red wine,<br>help me get back to your arms.*</p><p><strong>“you can laugh<br>now we are one<br>in everlasting peace<br>i will see you in the next life.”</strong></p><p>somewhere along the drift — between the sleepless nights and the low hum of neon regrets — he began writing. not poetry, not manifestos. just logs. observations. how the city trembled beneath full moons. how old modded bodies creaked louder than human ones. how grief was sold in subscription bundles. and maybe that was the shift — not salvation, but articulation. a slow evolution from ghost to witness. he didn’t need to be seen anymore. he only needed to see, to leave behind a record in case someone else ever slipped this far under. the silence became a lens. and in that stillness, maybe — just maybe — something began.<br>the silence felt different now — not hollow, but spacious. like maybe it was meant to be filled by someone else, someday. maybe that’s what bearing witness was. not screaming into the void, but leaving behind a map of it. his logs weren’t confessions, not quite. just echoes, left for someone else who might find themselves beneath the noise. and maybe that was enough. he didn’t need to be found. just… read. remembered. even if it was only once. even if the person forgot his name right after. some things didn’t ask for permanence. just contact.</p><p>he saved the final log as a .txt file, unsigned, untitled. the cursor blinked once — an invitation — then dissolved into static. somewhere, a streetlamp flickered off. not with drama, not with ceremony. just a quiet surrender to the inevitable dark. the city would keep humming, of course. it always did. but for the first time, he wondered if silence, too, could be a kind of an answer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=033eb0fc9da4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[i forgot to water my plants]]></title>
            <link>https://rasmalai123.medium.com/i-forgot-to-water-my-plants-9b527987c9fd?source=rss-ff41da4dec54------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b527987c9fd</guid>
            <category><![CDATA[descriptive-essays]]></category>
            <category><![CDATA[plants]]></category>
            <dc:creator><![CDATA[ras malai]]></dc:creator>
            <pubDate>Tue, 18 Mar 2025 09:46:38 GMT</pubDate>
            <atom:updated>2025-03-18T09:46:38.267Z</atom:updated>
            <content:encoded><![CDATA[<p>this life doesn’t seem mine, shouldn’t it have been more glorious, or more grotesque like, somewhere more on the extreme sides, that would have more sense than dangling in the middle and trying to guess all the whats and whens, not the what is the meaning of life bullshit, or why me drama, but just these when will i stop passing through different decibel of stuff which are not my beat, something which causes a little pain but gives harmony too, the music which seems just fine, just helps me pass through things.</p><p>fine, i will settle for “good enough” for now, this job, this music, this place just for now, as this job still pays the bills, it still is better than no music, and this place seems better than sleeping on a bus stop or just another place filled with other people. these are all just “fine”, still a pretty low bar, and settling for good enough just for now caught me in paralysis, turned into my real life, the just for now have been turned into since forever, the job which paid the bills have started to lack in its job, the music seems familiar now but not comforting, this place could and can never become my home,</p><p>its funny how one moment i was telling myself i would start exercising and the next i am years deep into just sitting on my chair in front of my laptop writing this, this life seems to belong to a stranger, i have not accepted this life and neither i want to, i always thought i was made and meant for something bigger, and i still want to uphold that thought to my highest principle, any thought of settling in this stranger’s life seems like a sheer horror and coincidently i do not like horror movies, there’s fear of the unknown, it kills us in the anticipation of what could happen, drowning us into our anxiety, fear of future and getting killed. this slight comfort of sitting here and the thought of running and sweating so much already gives me sweats, pulling my will, into just this place, because why not.</p><p>and somewhere in the day while shuffling between my tasks with my second cup of caffeine, i faint.</p><p>this life of someone else which i never signed up caught up to me. and it finally hit me, this is the why. the why of getting up and running, the why of watering my plants.</p><p>somedays i would pour more water, somedays less than they wanted to drink, then i would go on to complain about my plants dying, them not growing properly no matter how many tries i take. i wish fresh starts could solve what have been past me, but i still have to revisit my every step to calm myself of the feeling of where i went wrong, turns out i was doing it all wrong, but this conclusion brought a little peace to me than infuriating me, maybe finally i can do things right, looking at them like the plants they are and not just my daily task to do, being one with them might seem far-fetched but if i forget to learn and do them as chores, i better just sit on my chair and continue writing this.</p><p>i went for a walk and that knocked me off, i started to notice more of the stuff i thought i was meant to live, this started as a quiet rebellion more than fireworks bursting leading to a moment of eureka, no it was not a sudden jolt in my brain but rather a slow paced, pent up loath throwing me off the cliff. fine, i’ll stop settling in this life, i am done with knowing myself by these things more than what i really am,<br> recreating stuff was a lot less dramatic than what i saw tho, it didn’t happen all at once, but slowly little by little, a little off-script than what i thought, doing things out of my regular behavior of being, breaking the stuff i had in mind of me, an image of me, it all helps me breathe better, maybe to the outside world it was no different than just being another monday, but it gives me a sense of liberation, letting go of the being i was pretending to be or the image i was holding up to me so closely.</p><p>starting from zero feels so better now that i can be whoever i want, i might just start learning linear algebra while blending it with a little after effects, being non-reactive to people i do not want to deal with, just choosing any stuff from the whole catalogue of stuffs, just to end up finding all of these things are similar, they are what they are and they still connect with each other on different principles, it makes me chuckle to do stuff which i thought was beyond me, gives me the peace to tell myself things are not fine when they truly are not, its liberating to know that i do not need an official go-ahead before changing, i just can.</p><p>my girlfriend pumped a drive in me, an unwavering enthusiasm, stop wondering how do i have a girlfriend (that’s my job), and from then nike’s motto seemed more practical so i started writing what you are reading right now, and i would be the best one for my life, the thought scares me that my life would be dependent on my reactive emotions of life. i don’t wanna live the only war, like i am not opposed to the streamline of life but i don’t want that as my eventual, competition feels good but not with death. yeah it will be hard i guess, i am gonna get grilled but i chose this, and i am happy. it feels good to realize the time i have spending on my chair writing these, now can be spend in doing stuff, just a slight change but fills me with bliss.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b527987c9fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[goodbye blue sky]]></title>
            <link>https://rasmalai123.medium.com/goodbye-blue-sky-b3aab5514bf7?source=rss-ff41da4dec54------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3aab5514bf7</guid>
            <category><![CDATA[descriptive-essays]]></category>
            <category><![CDATA[sky]]></category>
            <dc:creator><![CDATA[ras malai]]></dc:creator>
            <pubDate>Tue, 18 Mar 2025 09:45:34 GMT</pubDate>
            <atom:updated>2025-03-18T09:45:34.428Z</atom:updated>
            <content:encoded><![CDATA[<p>there is time to kill today, tired of lying in the sunshine and swaying in the rain,<br>kicking around the ground of my hometown.<br>and then one day, i find; ten years have gone behind me,<br>no one told me when to run, i missed the starting gun.</p><p>i run the catch the sun, <br>but it’s sinking,<br>the sun is the same, but i am older now, short of breath and <br>many days closer to death,<br>hanging on in quiet desperation,<br>here is my reflection.</p><p>(…ened before)<br>there was noise, not the kind you notice, but the kind that just hums, just vibrates while you are sipping that coffee, the kind of vibration that fills the spaces where thoughts should be. i remember feeling of movement — of walking, running, but the ground never felt real</p><p>the last cloud i saw, it was a general, bleak-looking floating piece of water, but something about it felt final. maybe it wasn’t a cloud but a ghost of it, tho it marked the end of something, i can’t put an accurate finger on what. i wonder if the atmosphere has given up too, if even the weather had grown tired of performing for a world that no longer noticed.</p><p>“abandon all hope ye who enter here” was written on the last brick. i don’t know if i was the one who wrote it.</p><p>i sit behind this gigantic crusher of dreams, thinking of blankness, just looking around, nothing more than static-buzz sounds, <br>while looking for this so-called happiness, <br>i mean, i have heard about it, a lot actually, i keep hearing whispers about what drug happiness is, <br>the way people chase it, inject into their brains, using any emotion to just get that genuine laugh, to finally not just exist, but for their existence to be known, even that be for 5 seconds from their genuine laughter. once i heard someone saying a guy was just laughing all the time till he died, is this happiness? who knows. <br>the unknowingness of this happiness makes me sure that i forgot about it, makes me realise that i have had too much of the other side.</p><p>there’s this wall, i don’t know how long has it been here or who built it, maybe me? its surface a rorschach test of my unraveling, i see all kind of stuff on this, somedays a graffiti in a language i couldn’t decipher, somedays it is a bleak board, telling me about myself, a reflection of myself, i won’t be wrong to say that i saw nothing on it, it mirrored me back as a silhouette, does that mean i am not human anymore? well who knows?, who knows what staying behind this dream crusher does to you. <br>somedays it talks to me, tho it sounded like desolation and forgotten birthdays.</p><p>my body’s a cathedral of ruin, every muscle and bone of my body is screaming like they are getting burnt alive, i keep my eyes close most of the time, it feels comforting, like i am floating in a black velvet void, am i in the flesh? who knows? no friction, no wall, just the hum of my own cells dissolving, i don’t wanna go back, this bliss of floating pierces through what i found was an immoveable object, comfortably numb i am. goodbye cruel world.</p><p>the silence here is deafening, the hope here is cruel, and the quietness pulled me in, here is nothing, nothing has been here to describe what has happened here, i am nothing, this wall is nothing, it all is.<br>(this has happ…)</p><p>the lunatic is on the grass, remembering games, jasmine flowers and laughs. <br>and if the dam breaks open many hours too soon, <br>and if there is no room upon the hill, and if your head explodes with dark forebodings too<br>i’ll see you on the dark side of the moon.</p><p>the lunatic is in my head, you lock the door and take the gun,<br>throw away the key, there’s someone in my head, but i am not the one,<br>and if the clouds bursts thunder in your ear, you shout and no one seems to hear,<br>the line between my mind and here is blur, death on me seems to cheer,<br>time is ticking, what is it now? morning or noon? listen to my croon<br>meet me on the dark side of the moon.</p><p>the time is gone now, the song is over now, <br>thought i’d something more to say,<br>i can’t think of anything to say except, laughing is nice.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3aab5514bf7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>