Skip to content
Tech News
← Back to articles

It's not me, it's the compiler

read original more articles

It's not me, it's the compiler!

Every programmer has, at least once, thought to themselves that "it's not me, it's the compiler!". Usually, we're wrong, but this is the story of the time I was actually right.

On a Saturday evening, as one usually does, I was refactoring my JavaScript engine's parser, eariler I had written this code in the project:

impl LexerConsumer { #[inline] pub fn consume ( & mut self ) { self . 0 += 1 ; } #[inline] pub fn consume_test ( & mut self , store : & LexStore , expected : TokenKind ) -> bool { if self . peek ( store ) == expected { self . consume ( ) ; true } else { false } } }

Which is on its own a fairly common pattern in a parser, but I didn't love the shape of this code, each branch is returning the value of the comparison, so what if I just returned the value myself?

I got to work and wrote this version instead, and I was happy with the aesthetics of the generated asm in isolation, it was a few bytes shorter and didn't have the branch.

#[inline] pub fn consume_test ( & mut self , store : & LexStore , expected : TokenKind ) -> bool { let x = self . peek ( store ) == expected ; self . 0 += x as u32 ; x }

mov eax,DWORD PTR [rdi] mov ecx,eax and ecx,0x3f movzx ecx,BYTE PTR [rsi+rcx*1] cmp cl,dl jne 233263 inc eax mov DWORD PTR [rdi],eax cmp cl,dl sete al ret mov ecx,DWORD PTR [rdi] mov r8d,ecx and r8d,0x3f xor eax,eax cmp BYTE PTR [rsi+r8*1],dl sete al add ecx,eax mov DWORD PTR [rdi],ecx ret

So I went ahead to try and parse a simple statement, and right at the top of my bash history was a command to parse a for-loop.

> joe parse - 'for (var lol; false; false) {}' Error was found Diagnostic { kind: E079, flag: Flag(11529215046068469773), byte: 5, current_token: Var } Parse error

... continue reading