บทความ · Tier 2 ระบบ · วิชาที่ 15 · โดย Suppachai Khamlo · เผยแพร่

Compilers สำหรับ dev ที่เรียนเอง

compiler ดูเป็นเรื่องของคนทำภาษาโปรแกรม จนวันที่ต้องเขียน parser ให้ config, ทำช่องค้นหาที่ผู้ใช้พิมพ์เงื่อนไขเองได้ หรือเขียน lint rule ให้ทีม ตัวอย่างในหน้านี้เขียน parser ที่จัดการ precedence ในไม่ถึง 25 บรรทัด และเปิด bytecode ของ CPython ดูว่า compiler คำนวณ 60 * 60 * 24 ให้ตั้งแต่ก่อนรัน

ทำไมต้องเรียน Compilers

ทักษะ parsing กับการแปลง AST ใช้กับงานนอก compiler ได้ ทั้ง template engine, query engine, formatter, linter และ codemod ที่ใช้แก้โค้ดทั้ง repo ทีเดียว พอเขียน interpreter เองสักตัว เรื่องอย่าง closure, scope หรือทำไม JVM ต้อง warm up จะเห็นเป็นโค้ดที่อ่านได้

AST ในตัวอย่างที่ 1 เป็น tree ที่สร้างและเดินด้วย recursion ซึ่งมาจาก Data Structures และ Programming Paradigms ส่วน symbol table ในบท semantic analysis ก็คือ hash table ถ้าอ่าน Theory of Computation เรื่อง regular language มาบ้าง บท lexer จะง่ายขึ้น แต่ไม่จำเป็นต้องจบวิชานั้นก่อน

เนื้อหาหลักมีอะไรบ้าง

หัวข้อเจอในงานจริงตรงไหน
Lexer และ regular expressiontokenizer ของ config หรือ DSL, syntax highlighting
Parser: recursive descent, Pratt, LRเขียน DSL, error message ที่บอกได้ว่าผิดบรรทัดไหน
AST และ visitor patternlinter, formatter, codemod, การแปลงโค้ดของ Babel และ TypeScript
Semantic analysis, symbol table, type checkinggo-to-definition ใน IDE, type error ตอน compile
IR และ SSAอ่าน LLVM IR, ดูว่า optimizer เห็นโค้ดในรูปไหน
Optimization: constant folding, dead code elimination, inliningรู้ว่า micro-optimization แบบไหนที่ compiler ทำให้อยู่แล้ว
Code generation, register allocation, calling conventionอ่าน assembly, FFI ระหว่างภาษา
Garbage collectionปรับ GC ของ JVM, .NET หรือ Go, ไล่ปัญหา GC pause
Bytecode VM, JIT, tiered compilationCPython, JVM, V8 และเหตุผลที่โปรแกรมช้าช่วงแรกแล้วค่อยเร็วขึ้น
WebAssemblycompile Rust, Go หรือ C ไปรันใน browser และบน edge

ตัวอย่างที่ 1: parser ที่รู้ว่าคูณมาก่อนบวก

โจทย์คลาสสิกของ parser คือ 10 - 2 - 3 * (4 - 1) ต้องคูณก่อนลบ และลบต้องทำจากซ้ายไปขวา โค้ดนี้ใช้เทคนิค precedence climbing ซึ่งเป็น recursive descent แบบหนึ่ง แต่ละ operator มีระดับความสำคัญ และ parser จะกินเฉพาะ operator ที่ระดับสูงพอ

import operator, re
OPS = {"+": (1, operator.add), "-": (1, operator.sub), "*": (2, operator.mul)}

def parse(tokens, min_prec=1):
    left = atom(tokens)
    while tokens and tokens[0] in OPS and OPS[tokens[0]][0] >= min_prec:
        op = tokens.pop(0)
        right = parse(tokens, OPS[op][0] + 1)  # +1 ทำให้เป็น left-associative
        left = (op, left, right)
    return left

def atom(tokens):
    tok = tokens.pop(0)
    if tok != "(":
        return int(tok)
    node = parse(tokens)
    tokens.pop(0)                              # ทิ้ง ")"
    return node

def evaluate(node):
    if isinstance(node, int):
        return node
    return OPS[node[0]][1](evaluate(node[1]), evaluate(node[2]))
tree = parse(re.findall(r"\d+|[-+*()]", "10 - 2 - 3 * (4 - 1)"))
print(tree, "=", evaluate(tree))
# ('-', ('-', 10, 2), ('*', 3, ('-', 4, 1))) = -1

บรรทัด re.findall คือ lexer ทั้งตัว มันหั่นข้อความเป็น token ฟังก์ชัน parse สร้าง AST เป็น tuple ซ้อนกัน ส่วน evaluate เดินไปตามต้นไม้แล้วคำนวณ ซึ่งก็คือ tree-walking interpreter ขนาดจิ๋ว

จุดที่ต้องดูคือ + 1 ตอนเรียก parse ซ้ำ มันทำให้ operator ระดับเดียวกันตัวถัดไปไม่ถูกดึงเข้าไปทางขวา 10 - 2 - 3 จึงกลายเป็น (10 - 2) - 3 ถ้าลบ + 1 ออก จะได้ 10 - (2 - 3) ซึ่งผิด เทคนิค Pratt parsing ที่ใช้ใน parser จริงหลายตัว ขยายความคิดเดียวกันนี้ให้รองรับ prefix operator และ syntax อื่นๆ

precedence ถูกเก็บไว้ในความลึกของ AST
  1. parser สร้างต้นไม้ของ 2 + 3 * 4 โดย * อยู่ลึกกว่า + เพราะ precedence สูงกว่า
  2. evaluate คำนวณ node ลูกก่อน node แม่ 3 * 4 จึงถูกยุบรวมเป็น 12 ก่อน
  3. ขึ้นมาอีกชั้น 2 + 12 ได้ 14 ลำดับการคำนวณมาจากรูปร่างของต้นไม้ล้วนๆ

ตัวอย่างที่ 2: compiler คำนวณให้ตั้งแต่ก่อนรัน

constant folding คือการคำนวณนิพจน์ที่รู้ค่าแน่นอนตั้งแต่ตอน compile ดูได้จาก bytecode ที่ CPython สร้าง

import dis

dis.dis(compile("seconds_per_day = 60 * 60 * 24", "<demo>", "exec"))
#   0           RESUME                   0
#
#   1           LOAD_CONST               0 (86400)
#               STORE_NAME               0 (seconds_per_day)
#               RETURN_CONST             1 (None)

ใน bytecode ไม่มีคำสั่งคูณเลย มีแค่โหลดค่า 86400 ที่คำนวณไว้แล้ว เพราะฉะนั้นการเขียน 60 * 60 * 24 ให้อ่านง่ายไม่ได้ทำให้ช้าลง ชื่อ opcode อาจต่างไปตามเวอร์ชันของ Python (ผลข้างบนมาจาก 3.13) แต่ผลของการ fold เหมือนกัน compiler ของ C, Java และ Go ก็ทำ constant folding เช่นกัน

bytecode VM มักเร็วกว่า tree-walking interpreter เพราะคำสั่งเรียงกันเป็น array ต่อเนื่องใน memory วนอ่านด้วย loop เดียว ไม่ต้องไล่ pointer ข้าม node ของต้นไม้และไม่ต้องเรียกฟังก์ชันซ้อนกันลึกๆ ทุกครั้งที่คำนวณ เรื่องนี้โยงกลับไปเรื่อง cache ใน Computer Architecture โดยตรง

ลำดับที่แนะนำ

  1. Lexer, parser และ AST แล้วทำ tree-walking interpreter ให้รันได้ (ครึ่งแรกของ Crafting Interpreters)
  2. Scope, closure, class ใน interpreter ตัวเดียวกัน
  3. ทำภาษาเดิมซ้ำอีกรอบเป็น bytecode VM พร้อม garbage collector (ครึ่งหลังของ Crafting Interpreters)
  4. Semantic analysis และ type checking
  5. IR, SSA และ optimization (ใช้ Engineering a Compiler)
  6. Code generation ผ่าน LLVM หรือ compile ไป WebAssembly
  7. JIT และ tiered compilation (อ่านให้เข้าใจหลักก็พอ)

โปรเจกต์ปิด: เขียน parser สำหรับ SQL ย่อยที่รับ SELECT ... WHERE ... แปลงเป็น AST แล้ว execute บนตารางในหน่วยความจำ งานนี้ต่อกับวิชา Databases ได้พอดี

หนังสือและแหล่งเรียน

รู้ได้ยังไงว่าผ่านแล้ว