Logo

I like building stuff when I should probably be studying.

I'm currently a post-grad student at the University of Warwick, where I'm writing my dissertation on the applicability of formal methods to LLM outputs.

I'm interested in all things frontend, backend and AI. In my spare time, I work on my homelab and read about compilers.

“Also try Terraria!”

Recent Writing

See all →
Baby's first language: lexer and parserSep 14, 20265 min read

This is my first post in a series walking through how invariants' compiler actually works, phase by phase. If you haven't read the overview post: it's a small DSL for describing structured data and the relationships between its fields, compiled ahead of time into a schedule that ends up driving an LLM's token generation. This series is about the compiler itself, not the LLM part. If you want to actually build one of these yourself at some point, I really, really, REALLY strongly recommend reading Crafting Interpreters by Bob Nystrom - it's, IMO, the best book to get started with, it's where I learnt most of this from, it's free online, and basically everything in this post is the same shape of idea, just applied to a much smaller, much weirder language than the one in the book. Let's start at the very front: how does a string of source text turn into something a compiler can actually reason about? spec CloudProvision { field baseram: Integer { value = 8; } } There are two things that need to be done here: the lexer turns that raw text into a flat list of tokens, and the parser turns that flat list into a tree. The lexer's only job is to walk the source character by character and decide "what is this a piece of." It doesn't know anything about structure or fields or what's valid - it just recognizes "chunks". Feed it value = 8; and it should spit out four tokens: an identifier (value), an operator (=), a number (8), and a semicolon. The way you actually do this is literally just as simple as you think: you look at the current character, decide what kind of token it could be starting, and consume characters until that token is complete. Very importantly, keywords are not a special case, because the trick is to scan any run of letters as a plain identifier first, and only afterwards check whether that identifier happens to match something in a keyword table: cpp inline static const std::unorderedmap<std::stringview, TokenType keywords{ {"spec", TokenType::KWSPEC}, {"field", TokenType::KWFIELD}, {"invariant", TokenType::KWINVARIANT}, {"IN", TokenType::KWIN}, {"this", TokenType::KWTHIS}, // ... }; So from the above example, spec and CloudProvision go through the exact same code path in the scanner - it's only after scanning that one of them turns out to be a keyword and the other stays a plain identifier. By the end, value = 8; becomes a flat list: [IDENTIFIER(value), GREATEREQUAL, NUMBER(8), SEMICOLON]. Before writing the parser, you need to know what you're actually trying to parse into. This is where a formal grammar earns its keep. The statement grammar is the "scaffolding" of the invariants lang - spec, field, invariant, and nothing else: spec = "spec", IDENTIFIER, "{", { specmember }, "}"; field = "field", IDENTIFIER, ":", type, "{", { constraint }, "}"; constraint = expression, ";"; The expression grammar is where all the actual computation lives - arithmetic, comparisons, boolean logic - written out as a chain, each rule built out of the one below it: expression = implication; implication = disjunction, [ "-", implication ]; disjunction = conjunction, { "||", conjunction }; conjunction = equality, { "&&", equality }; equality = comparison, { ( "==" | "!=" ), comparison }; comparison = membership, { ( "" | "=" | "<" | "<=" ), membership }; membership = term, [ ( "in" | "not in" ), term ]; term = factor, { ( "+" | "-" ), factor }; factor = unary, { ( "" | "/" | "%" ), unary }; unary = ( "!" | "-" ), unary | postfix; postfix = primary, { postfixop }; primary = literal | IDENTIFIER | "this" | list | "(", expression, ")"; Here, the chain is the operator precedence table. implication sits above disjunction, which sits above conjunction, all the way down to primary at the bottom. Note that the ordering isn't arbitrary - it's exactly "loosest-binding operator first, tightest-binding last." - has to be the loosest, because you want a || b - c || d to group as (a || b) - (c || d), not something weirder. has to bind tighter than +, so it sits below term. Read top to bottom, the grammar already tells you the precedence order, and so you don't need a separate table anywhere. In recursive descent, every rule becomes a function, and every function calls the rule below it before it looks at its own operator: cpp ExprPtr Parser::expression() { return implication(); } ExprPtr Parser::implication() { ExprPtr left = disjunction(); if (match(TT::ARROW)) { ExprPtr right = implication(); return std::makeunique<Expr( BinaryExpr{std::move(left), BinaryOp::Imply, std::move(right)}); } return left; } ExprPtr Parser::disjunction() { ExprPtr left = conjunction(); while (match(TT::LOGICALOR)) { ExprPtr right = conjunction(); left = std::makeunique<Expr( BinaryExpr{std::move(left), BinaryOp::Or, std::move(right)}); } return left; } Notice implication doesn't know or care what a disjunction actually contains - it just asks disjunction() to go figure that out and hand back a fully-formed subtree, then checks if there's an - sitting after it. Every level in the chain does exactly this: delegate downward first, then handle your own operator if there is one. Let's trace value = 8 through this by hand, since it's small enough to do fully: 1. expression() calls implication(). 1. implication() calls disjunction(), which calls conjunction(), which calls equality() - none of these see an operator they recognize yet, so each just delegates straight down. 1. equality() calls comparison(). 1. comparison() calls membership(), which calls term(), which calls factor(), which calls unary(), which calls postfix(), which calls primary(). 1. primary() is the first function that actually consumes something: it sees the identifier value and returns it as a leaf node. That bubbles back up through postfix, unary, factor, and term untouched, since none of them see an operator they own. 1. Back in comparison(), having gotten value back from membership(), it now checks the next token - = - matches, so it consumes it, calls membership() again for the right-hand side (which bottoms out and returns 8), and wraps both into a single BinaryExpr{value, GreaterEqual, 8}. 1. That comparison node bubbles all the way back up through equality, conjunction, disjunction, and implication untouched, since = was the only operator in the whole expression, and it becomes the final tree. See how we dove thirteen functions deep, and only one of them - comparison - actually did anything, because it was the only precedence level with a matching operator in this particular expression. Everything else was pure pass-through. That's the entire trick and what makes RD so brilliant; most of the chain doesn't cost you anything at runtime beyond a function call, and you get correct precedence for free just by getting the order of the chain right once, up front. Once we're done with this, we should have a parse tree, or abstract syntax tree (AST). This tells us the structure of our language. The next few steps involve "phases" of computations surrounding this tree, either transforming it, or lowering it into other trees.

More on invariantsSep 13, 20265 min read

My dissertation is called invariants, and the short version is: it's a compiler for making LLMs stop generating numbers that don't add up. Ask a model for JSON with a unitprice, a quantity, and a totalprice, and every existing structured-output tool - grammars, JSON Schema, whatever - can guarantee you get three numbers in the right shape. None of them can guarantee totalprice actually equals unitprice quantity. That's not a syntax problem, it's a semantics problem, and grammars only know about syntax. So in practice, everyone just validates after the fact and regenerates when it's wrong, which is slow, and still doesn't actually prevent the bad output - it just catches it after the model already wasted a forward pass being wrong. Treat it as a compiler problem instead of a validation problem. You write a schema in a small DSL I built - fields, types, and invariants, like: spec CloudProvision { field baseram: Integer { value = 8; } field instancecount: Integer { value IN [1, 2, 4, 8]; } field totalram: Integer { } invariant calcram { this.totalram == this.baseram this.instancecount; } } That gets compiled ahead of time - lexed, parsed, semantically bound, and then run through a dependency analysis pass that builds a graph over the fields and topologically sorts it into an execution schedule. totalram depends on baseram and instancecount, so it gets scheduled after both, and because the compiler can see it's a closed-form equality, it gets flagged as deterministically computable - meaning the model is never asked to generate it at all. The runtime just computes it. For everything the model does have to generate, the runtime masks its logits token by token: every candidate token gets checked against the field's constraints (in progress, not just once it's finished) before it's even allowed to be sampled. So a value = 8 field literally cannot produce a 7, not because something rejected it afterwards, but because 7 was never a legal next token to begin with. Every one of the actually hard bugs showed up at the boundary between "compiled schedule" and "a live, non-deterministic model," and most of them are pretty funny in hindsight: - My original binder registered a field and bound its constraints in the same pass, which meant a field referencing another field declared later in the same spec just silently failed to resolve. Fix was a two-pass binder - register every signature first, then bind constraints once everything's visible. - Dependency tracking originally identified fields by an integer id scoped to their own symbol table, which broke the second a spec could be nested or reused twice in the same document - same id, two different actual fields. Had to switch to fully-qualified string paths instead. - BPE and SentencePiece tokenizers mark word boundaries with completely different characters, which quietly broke my structural validity checks until I handled both explicitly. This is also the entire reason I benchmarked against two separate model families instead of one - a single tokenizer would never have caught it. - For a while, only the top 1,000 highest-probability tokens ever got checked against the mask, for speed. Anything ranked lower kept its original score completely untouched - meaning a model that really wanted an invalid token could just reach past the window and grab it. Nobody was stopping it. - A non-contiguous NumPy array got silently copied by pybind11 instead of mutated in place, so for a while the model was running on completely unmasked logits with zero errors raised anywhere. I only caught this because a heavily-constrained field produced a value that should've been impossible. - llama.cpp's end-of-sequence token decodes to an empty string, which slid straight through my masking loop looking like a harmless no-op and quietly ended generation early. - A numeric bound like <= 80 was being checked digit-by-digit, but a value like 160 only got rejected once it had already finished generating - which defeats the entire point. Took a genuinely annoying amount of thinking about monotonicity (appending a digit to a non-negative number can only make it bigger) to prune those early instead of after the fact. None of these got caught by unit tests. All of them got caught by actually running the thing against a live model and watching it do something it shouldn't have been able to do. Benchmarked across twelve suites (some synthetic, some pulled from real JSON Schemas - Stripe invoices, Kubernetes resource limits, GitHub Actions configs) against two model families and four other systems (a plain unconstrained prompt, llama.cpp's own grammar, and two third-party libraries, Outlines and Guidance): - 90% of field-level assertions pass, against 84% (Guidance), 80% (grammar baseline), 75% (Outlines), and 1% for a plain prompt with no constraints at all. - On constraints that are pure cross-field math - the entire reason this project exists - every grammar-based system craters to 54-59%, while invariants holds at 88.7%. Makes sense: that's the one category a context-free grammar was never going to be able to express in the first place. - It's also 22% faster on average than the grammar baseline, mostly because a field that gets computed instead of generated costs zero tokens. The one place it loses is long, totally unconstrained free-text fields, where there's nothing to skip and the full-vocabulary mask has to run on every single token for no benefit - the overhead has nothing to offset it. Good to know your failure mode, at least. The only real "big" problem that I still haven't quite solved is that nothing generated can ever be un-generated, if a value turns out to violate a constraint discovered later, the only option is to crash. No backtracking. Solving that would require speculative generation with rollback (which I actually wanted to do, just didn't have the time/scope to do so). Anyway - this thing is basically a small language with a real frontend, binder, and dependency-aware scheduler bolted onto an LLM's sampling loop, and I think each of those phases is interesting enough to talk about on its own. So that's next.

My C++ frontend ideaAug 20, 20261 min read

Owning my tools, for me, starts with the language. I've been playing with the idea of a language frontend for C++ for a while now. Ironically, that's how C++ was born! I envision a front-end for C++ which enforces the newer "style" of programming in the language we've seen become more and more popular since C++11. - Raw pointers are illegal, or are implicitly shared. - The array operators use std::array under the hood. - No header files. And much more... This isn't exactly a new idea, which is comforting in a "I'm not crazy" kind of way. Bjarne's original cfront did more or less this in reverse - it translated "C with Classes" into plain C, so you could bootstrap an entirely new language on top of existing C compilers and linkers. Herb Sutter's cppfront is the modern spiritual successor: a "syntax 2" for C++ that transpiles down into today's syntax, opting you into memory-safety defaults, bounds-checking, and sane initialization rules without needing a whole new compiler backend. I'd be lying if I said I wasn't basically nodding along to cppfront's entire thesis. Where I differ is more about which defaults I want flipped, and how opinionated the frontend should be about ownership. I think the bulk of the work remains to be sketched out, and really as it stands, it's just an idea I'm playing around with, but one I've been passionate about pursuing for a while now, so we'll see where it goes.

The poweruser endgameAug 19, 20261 min read

I often wonder what the endgame for developers and engineers are. I know, even of many of the people who truly are in this field for their love thereof, it's not much beyond a job at the end of the day. So what about power users? People, like myself, who love optimizing hell out of everything they do? More often than not, those who maintain a dotfiles repo, maybe use Nix, build their own personal library functions, etc... Looking back, most of my side projects aren't really "projects" so much as complaints about my own workflow that got out of hand. The obvious problem is that this doesn't scale. Every hour spent patching your WM or rewriting your editor's fuzzy-finder is an hour not spent on whatever you were actually supposed to be doing. Yak-shaving is a very real, very seductive trap, and I've fallen into it more times than I'd like to admit. The less obvious benefit, though, is depth. Once you've written your own editor, your build system stops being a black box. Once you've patched your WM, X11/Wayland internals stop being magic. You end up understanding the entire stack you live in, top to bottom, instead of just the surface area most people ever touch. I am genuinely someone who loves understanding as much of my tools as I can, so doing all of this in a "non-product" kind of way, and one which is just for me, feels great.

Life updates!Jun 30, 20261 min read

Long time no post! It's been an incredibly hectic past few weeks, what with exams and interviews and whatnot. I've got so, so, so many things I've been meaning to write about ubt simply haven't had the time to. A quick overview of the things I've been meaning to write about: - I am finally done with exams, and can full-send it into my dissertation! - I got a job! I want to discuss my experience as an international and new-grad in the UK tech market. - Snip looks so, totally different - I went to a hackathon for the sole-purpose of reworking it like I mentioned before. - I want to start writing more about stuff I learn, or about things I am learning about. Also, I feel like having to spin up VSCode each time I want to write a blog post is getting a bit tiring. I'm thinking of self-hosting a super simple platform where I can write and push my posts from my phone or wherever. In any case, stay tuned!

Refocusing snip's directionMay 23, 20261 min read

I'd been working on a text-editor called snip for quite some time now. It was, like most of my projects, a re-invention of the wheel. I don't really like the idea of framing a project as a "product" from the get-go, I think they serve me (personally) better as learning experiences. But now that I'd been working with snip for a while, and gotten more and more acquianted with the idea of maybe actually using it, I did want to start thinking in a more practical sense. I didn't need to implement my own event-reactor-backend (think libuv), my own ASCII-rendering pipeline, or a lot of the other hand-written "pipelines" I wrote to understand the overarching system. So, taking a step back, I re-framed what I wanted snip to be. Snip should be a Nix-first editor. I wanted to rely on nixpkgs for my LSPs, linters, or any other code-tooling. It should be performant, simple enough to reason-about, and get out of your way. As such, I've recently begun work on refactoring snip to: 1. Get out of the terminal, we're using Qt now instead 1. Focus on tooling instead of movement (for now) Using Qt has been pretty cool so far, it's actually very pleasant and the qtl is awesome. Obviously, it's my first time working with a framework this big outside of the STL, so there's a lot of hiccups and things slowing me down, namely the black-hole that is text rendering. Also exams and interview prep have forced me to put it on the backburner for now, but I'm looking forward to grinding it out this Summer.

Projects

See all →

Experience

See all →

Stellerus Technology/ Software Engineer (Part-Time)

Jan 2025 - Aug 2025
Re-designed LLM execution pipelines using custom tool-orchestration DSL and multi-agent paradigms with decomposed tasks.

CASTLE Labs/ Research Assistant

May 2024 - Sep 2024
Built static analysis and code-structure graph pipelines for large-scale code analysis and extraction tasks from thousands of scraped Java repositories.

Stellerus Technology/ Software Engineering Intern

May 2023 - Aug 2023
Designed high-throughput backend services and multi-processing features for real-time satellite data ingestion and processing.

Get in touch

Always happy to chat! You can find my resume and socials below: