Lithe 3: A Rewrite


What if I just copied the Svelte compiler, written in TypeScript, changed all of the file extensions from .ts to .rs, and fixed all the bugs? It'd be a slog, sure, but at the end of the day I'd have a compiler that was very nearly the same, but presumably more performant.

This attempt I gave a real try, spending maybe three nights just chugging away. What I got was just more and more errors, which was fairly disheartening. I also realized just how different Rust is, and that a 1-to-1 rewrite would result in something that wouldn't be as ideal as it could be. For example, take this very simple TypeScript class:

class Node extends BaseNode {
 name: String? = null,
 children: Node[] = [],
}

The equivalent Rust struct might look like:

struct Node {
 base: BaseNode,
 name: Option<String>,
 children: Vec<Node>
}

I don't think that's great. What fields belong on Node? Which belong on BaseNode? Plus TypeScript's got a garbage collector, so for parity any T should probably be wrapped in an Rc<T>. Plus everything's mutable, so we'd want to wrap that in a RefCell<T>.

struct Node {
 base: BaseNode,
 name: Option<String>,
 children: Vec<Rc<RefCell<Node>>>
}

While probably fine, this just looks it'd like a pain to work with. I think we can do better. These nodes don't really reference each other, so we don't actually need an Rc, and without that we wouldn't need a RefCell. Also I'm up to 1337 errors, so I'm pretty happy ending this attempt here.


Recommended reading

Lithe 2: From Scratch

I've written a little Rust, but never professionally, so I'm sure what I write is going to be ugly to those in the know. But it compiles, which is half the battle.

Before starting this project let's take a quick peek at the Svelte repo. Oh, huh, looks like the compiler smaller than I would have thought, weighing in at only ~800KB (if you include the runtime), but 800KB of code to rewrite is still fairly massive for a weekend warrior like myself. So, for my initial attempt I crafted the world's smallest svelte app…

Lithe 4: On the Shoulders of Giants

Starting from characters and parsing that into an AST that could render a Svelte program could definitely open open possibilities for some low-level optimizations, but even just parsing a normal HTML document is not a small project, and Svelte includes JavaScript, TypeScript, Handlebars-esque blocks, CSS, and SCSS, too. Doing all that at once would be the mother of all slogs. But, luckily, I don't have to! There exist many, many pre-build alternatives. The Svelte compiler itself even uses a couple.

So here's the new plan…