自幹 C 語言編譯器

- Abdulaziz Ghuloum 的啟發

about me

EE degree back in 1982

Z80 was the most popular CPU

Pascal/Fortran/COBOL were popular languages

Apple ][ + BASIC and CP/M

intel 80386SX PC mother board designer

......

Interested in Linux since 2016

Z80 CPU

intel 80386SX CPU

 

photo source: wikipedia.org

Apple ][

marconi.jiang@gmail.com

An Incremental Approach to Compiler Construction

Abdulaziz Ghuloum

緣起

- 大陸網站 - 伯樂在線 - 的這篇文章 “学习较底层编程:动手写一个C语言编译器

- 原文 “Baby Steps to a C Compiler

再到

- 原始論文 An Incremental Approach to Compiler Construction“ by Abdulaziz Ghuloum

決定

有可能自幹一個 C 語言 Compiler,  得以一償大學時代宿願 

 An Incremental Approach to Compiler Construction

  • 關於 Compiler 編譯器的介紹, 都被形容成複雜且神祕的黑技術, 非一般凡人可以完成。
  • 沒錯、要達到目前市面上的 Compiler 實用的標準, 絕非易事
  • 學校要怎麼教 Compiler 呢?算了, 只教 Interpreter 直譯器就好了, 簡單多了
  • Prof. Ghuloum 的此篇論文就是要打破這壁壘, 教大家如何寫出 Compiler - 從最陽春的開始做起。
  • (雖然, 你完成的第一個 Compiler 還是需要利用市面上現有的 Compiler 來幫忙)
  • 先挑選一開始要支援 Scheme 語言的子集合, compile 成 80x86 Assembly 組合語言 及 machine code 機器碼, 就可以在現今大多數的電腦上執行, 成為麻雀雖小卻 bona fide 貨真價實的 Compiler
  • 接下來每一次的修改, 只增加一部份功能, 重複 compile、assembly 步驟, 逐步地了解 Compiler 的完整功能, 並在自己的手上完成

這應該超有成就感

Scheme?!

什麼是 Scheme?

沒聽過!

Prof. Ghuloum 的論文是做 Scheme 的 Compiler,

不是 C Compiler

再回到 Baby Step to a C Compiler 那篇文章, 改從這裡出發

一開始就卡關

先從上圖顯示最簡單的第一個程式開始編譯起, 沒有變數、功能呼叫、if 判斷、迴圈等複雜指令, 應該簡單吧.

 

首先、需要用到語法分析(parsing)的程式 Flex 跟 Bison

int main() {
    return 2;
}

Flex?!Bison?!

I

Linux 核心

後記

再看到另一篇文章介紹《自己動手寫編譯器、鏈接器》一書(原版大陸簡體), 即使知道該書大量抄襲開源編譯器 TCC, 本書還是提供大家一個縮減版 C Compiler - Simple C Compiler 接上現實生活的軌道。該文作者後來發現這系列文章《手把手教你构建 C 语言编译器》, 覺得是比較好的學習方式, lexer, parser, virtual machine 都是由手工自己完成, 不會有任何的黑箱是你無法理解。該系列文章的 github 位址在此

《手把手教你构建 C 语言编译器》該系列文章作者源自於有一次在 Github 上看到了一個 c4 的項目,號稱用 4 個函數來實現一個小型的 C Compiler。最令人震驚的是能夠自己編譯自己,並且用很短的程式碼就完成功能相當完整的 C Compiler。

Made with Slides.com