Compiler design

From j4flmao/agent-skills · View interactive version

Compiler design is an AI agent skill from the GitHub repository j4flmao/agent-skills. Use when the user asks about writing a compiler or interpreter, lexers, parsers, ASTs, grammars, type checkers, SSA, LLVM IR, MLIR, optimization passes or register allocation. Produces compiler pipeline design and working front-end and IR code. Not for reading assembly output (use lang-assembly) or

How to use this skill

Skill file

Compiler Design

Purpose

Build a language implementation that is correct first and fast second. This skill gives decision rules for each phase — which parsing technique, what the AST and IR should look like, which optimisations matter, and when to lean on LLVM/MLIR/Cranelift instead of writing a backend.

Agent Protocol

Trigger

"compiler", "lexer", "parser", "AST", "grammar", "LLVM IR", "SSA", "optimization pass", "codegen", "register allocation", "interpreter", "MLIR", "type checker".

Input Context

Output Artifact

Phase design, grammar, data structures, pass code or LLVM IR examples. No file unless requested.

Response Format

Pipeline: {lex -> parse -> resolve/typecheck -> IR -> passes -> codegen}
Choice per phase: {technique + reason}
Code/IR: {snippet}
Tests: {golden files, fuzzing, differential testing}

1. Pipeline

source → lexer (tokens) → parser (CST/AST) → name resolution + type checking (typed AST / HIR)
       → lowering to IR (SSA) → optimisation passes → instruction selection
       → register allocation + scheduling → object code / bytecode

Keep each stage's data structure explicit; most bugs come from phases sharing mutable state.

2. Lexing

3. Parsing

| Technique | Strength | Use |

|-----------|----------|-----|

| Recursive descent (LL) | readable, great errors, easy recovery | most production compilers (GCC, Clang, Go, Rust, TypeScript use hand-written parsers) |

| Pratt / precedence climbing | expressions with many precedence levels | embedded inside recursive descent |

| LR/LALR (yacc/bison), GLR | handles left recursion, grammar-checked | when a formal grammar is the source of truth |

| PEG / packrat | ordered choice, no ambiguity | DSLs; watch memory and error quality |

| Parser combinators | compact in functional languages | small/medium languages |

Pratt expression parser core:

def parse_expr(self, min_bp=0):
    lhs = self.parse_prefix()                  # literals, identifiers, unary ops, parens
    while True:
        op = self.peek()
        if op.kind not in INFIX: break
        l_bp, r_bp = INFIX[op.kind]            # e.g. '+': (10, 11) left-assoc, '^': (31, 30) right-assoc
        if l_bp < min_bp: break
        self.advance()
        rhs = self.parse_expr(r_bp)
        lhs = Binary(op, lhs, rhs)
    return lhs

4. Semantic Analysis

5. Intermediate Representation

Example LLVM IR for int max(int a, int b) { return a > b ? a : b; }:

define i32 @max(i32 %a, i32 %b) {
entry:
  %cmp = icmp sgt i32 %a, %b
  br i1 %cmp, label %then, label %else
then:
  br label %end
else:
  br label %end
end:
  %r = phi i32 [ %a, %then ], [ %b, %else ]
  ret i32 %r
}

(After simplifycfg this becomes a single select.)

6. Optimisation Passes

struct CountAdds : llvm::PassInfoMixin<CountAdds> {
  llvm::PreservedAnalyses run(llvm::Function &F, llvm::FunctionAnalysisManager &) {
    unsigned n = 0;
    for (auto &BB : F) for (auto &I : BB)
      if (I.getOpcode() == llvm::Instruction::Add) ++n;
    llvm::errs() << F.getName() << ": " << n << " adds\n";
    return llvm::PreservedAnalyses::all();          // analysis-only: nothing changed
  }
};

Run with opt -passes='default<O2>' or register plugins via -load-pass-plugin.

7. Backend

8. Interpreters

9. Testing

10. Anti-Patterns

11. Checklist

References

Merged Material

Content folded in from overlapping skills and notes.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.