2. 萬花筒:實作解析器和 AST

2.1. 第 2 章 簡介

歡迎來到「使用 LLVM 實作語言」教學的第 2 章。本章將向您展示如何使用在第 1 章中建構的詞法分析器,為我們的萬花筒語言建構一個完整的解析器。一旦我們有了解析器,我們將定義並建構一個抽象語法樹 (AST)。

我們將建構的解析器使用遞迴下降解析運算子優先順序解析的組合來解析萬花筒語言(後者用於二元表達式,前者用於其他所有內容)。在我們開始解析之前,讓我們先談談解析器的輸出:抽象語法樹。

2.2. 抽象語法樹 (AST)

程式的 AST 以一種易於編譯器後期階段(例如程式碼生成)解釋的方式捕捉其行為。我們基本上希望語言中的每個構造都有一個物件,並且 AST 應該緊密地模擬語言。在萬花筒中,我們有表達式、原型和函數物件。我們先從表達式開始

/// ExprAST - Base class for all expression nodes.
class ExprAST {
public:
  virtual ~ExprAST() = default;
};

/// NumberExprAST - Expression class for numeric literals like "1.0".
class NumberExprAST : public ExprAST {
  double Val;

public:
  NumberExprAST(double Val) : Val(Val) {}
};

上面的程式碼顯示了基底 ExprAST 類別和我們用於數值常數的一個子類別的定義。關於這段程式碼,需要注意的重要一點是 NumberExprAST 類別將常數的數值作為實體變數捕捉。這允許編譯器的後期階段知道儲存的數值是什麼。

現在我們只建立 AST,因此它們沒有有用的存取器方法。例如,新增一個虛擬方法來漂亮地列印程式碼將非常容易。以下是我們將在萬花筒語言的基本形式中使用的其他表達式 AST 節點定義

/// VariableExprAST - Expression class for referencing a variable, like "a".
class VariableExprAST : public ExprAST {
  std::string Name;

public:
  VariableExprAST(const std::string &Name) : Name(Name) {}
};

/// BinaryExprAST - Expression class for a binary operator.
class BinaryExprAST : public ExprAST {
  char Op;
  std::unique_ptr<ExprAST> LHS, RHS;

public:
  BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
                std::unique_ptr<ExprAST> RHS)
    : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
};

/// CallExprAST - Expression class for function calls.
class CallExprAST : public ExprAST {
  std::string Callee;
  std::vector<std::unique_ptr<ExprAST>> Args;

public:
  CallExprAST(const std::string &Callee,
              std::vector<std::unique_ptr<ExprAST>> Args)
    : Callee(Callee), Args(std::move(Args)) {}
};

這一切(有意地)都相當簡單:變數捕捉變數名稱,二元運算子捕捉它們的操作碼(例如 '+'),而呼叫捕捉函數名稱以及任何參數表達式的清單。關於我們的 AST 的一件好事是,它在不談論語言語法的情況下捕捉了語言特性。請注意,這裡沒有討論二元運算子的優先順序、詞彙結構等。

對於我們的基本語言來說,這些就是我們要定義的所有表達式節點。由於它沒有條件控制流程,所以它不是圖靈完備的;我們將在後續的文章中解決這個問題。我們接下來需要兩樣東西:一種是描述函數介面的方法,另一種是描述函數本身的方法。

/// PrototypeAST - This class represents the "prototype" for a function,
/// which captures its name, and its argument names (thus implicitly the number
/// of arguments the function takes).
class PrototypeAST {
  std::string Name;
  std::vector<std::string> Args;

public:
  PrototypeAST(const std::string &Name, std::vector<std::string> Args)
    : Name(Name), Args(std::move(Args)) {}

  const std::string &getName() const { return Name; }
};

/// FunctionAST - This class represents a function definition itself.
class FunctionAST {
  std::unique_ptr<PrototypeAST> Proto;
  std::unique_ptr<ExprAST> Body;

public:
  FunctionAST(std::unique_ptr<PrototypeAST> Proto,
              std::unique_ptr<ExprAST> Body)
    : Proto(std::move(Proto)), Body(std::move(Body)) {}
};

在 Kaleidoscope 中,函數的類型只由其參數的數量來決定。由於所有值都是雙精度浮點數,因此不需要在任何地方存儲每個參數的類型。在更積極和更實際的語言中,“ExprAST”類可能會有個類型欄位。

有了這個架構,我們現在可以談談在 Kaleidoscope 中解析表達式和函數主體。

2.3. 解析器基礎

現在我們有了一個要構建的 AST,我們需要定義解析器代碼來構建它。這裡的想法是,我們想將像 “x+y” 這樣的東西(由詞法分析器作為三個詞彙單元返回)解析成一個 AST,這個 AST 可以通過以下調用生成

auto LHS = std::make_unique<VariableExprAST>("x");
auto RHS = std::make_unique<VariableExprAST>("y");
auto Result = std::make_unique<BinaryExprAST>('+', std::move(LHS),
                                              std::move(RHS));

為此,我們將首先定義一些基本的輔助函數

/// CurTok/getNextToken - Provide a simple token buffer.  CurTok is the current
/// token the parser is looking at.  getNextToken reads another token from the
/// lexer and updates CurTok with its results.
static int CurTok;
static int getNextToken() {
  return CurTok = gettok();
}

這實現了一個圍繞詞法分析器的簡單詞彙單元緩衝區。這使我們能夠預先查看詞法分析器返回的下一個詞彙單元。解析器中的每個函數都將假設 CurTok 是當前需要解析的詞彙單元。

/// LogError* - These are little helper functions for error handling.
std::unique_ptr<ExprAST> LogError(const char *Str) {
  fprintf(stderr, "Error: %s\n", Str);
  return nullptr;
}
std::unique_ptr<PrototypeAST> LogErrorP(const char *Str) {
  LogError(Str);
  return nullptr;
}

LogError 函數是解析器用來處理錯誤的簡單輔助函數。解析器中的錯誤恢復不是最好的,對用戶也不是特別友好,但對於我們的教程來說已經足夠了。這些函數使得處理具有各種返回類型的函數中的錯誤變得更容易:它們總是返回 null。

有了這些基本的輔助函數,我們就可以實現語法的第一部分:數值常數。

2.4. 基本表達式解析

我們從數值常數開始,因為它們是最容易處理的。對於我們語法中的每個產生式,我們都將定義一個解析該產生式的函數。對於數值常數,我們有

/// numberexpr ::= number
static std::unique_ptr<ExprAST> ParseNumberExpr() {
  auto Result = std::make_unique<NumberExprAST>(NumVal);
  getNextToken(); // consume the number
  return std::move(Result);
}

這個函數很簡單:它期望在當前詞彙單元是 tok_number 詞彙單元時被調用。它獲取當前的數值,創建一個 NumberExprAST 節點,將詞法分析器推進到下一個詞彙單元,最後返回。

這裡有一些有趣的方面。最重要的一點是,這個函數會消耗掉與產生式相對應的所有詞彙單元,並返回詞法分析器緩衝區,其中下一個詞彙單元(不屬於語法產生式的一部分)已經準備好了。這是遞歸下降解析器中相當標準的做法。舉個更好的例子,括號運算符的定義如下

/// parenexpr ::= '(' expression ')'
static std::unique_ptr<ExprAST> ParseParenExpr() {
  getNextToken(); // eat (.
  auto V = ParseExpression();
  if (!V)
    return nullptr;

  if (CurTok != ')')
    return LogError("expected ')'");
  getNextToken(); // eat ).
  return V;
}

這個函數說明了關於解析器的一些有趣的事情

1) 它展示了我們如何使用 LogError 函數。當被調用時,這個函數期望當前詞彙單元是一個 '(' 詞彙單元,但在解析了子表達式之後,有可能沒有 ')' 在等待。例如,如果用戶輸入了 “(4 x” 而不是 “(4)”,解析器應該發出一個錯誤。因為錯誤可能會發生,解析器需要一種方法來指示它們發生了:在我們的解析器中,我們在錯誤時返回 null。

2) 這個函式的另一個有趣之處在於,它透過呼叫 ParseExpression 來使用遞迴(我們很快就會看到 ParseExpression 可以呼叫 ParseParenExpr)。這很強大,因為它允許我們處理遞迴文法,並使每個產生式都非常簡單。請注意,括號本身不會導致建構 AST 節點。雖然我們可以這樣做,但括號最重要的作用是引導解析器並提供分組。一旦解析器建構了 AST,就不再需要括號。

下一個簡單的產生式是用於處理變數參考和函式呼叫

/// identifierexpr
///   ::= identifier
///   ::= identifier '(' expression* ')'
static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
  std::string IdName = IdentifierStr;

  getNextToken();  // eat identifier.

  if (CurTok != '(') // Simple variable ref.
    return std::make_unique<VariableExprAST>(IdName);

  // Call.
  getNextToken();  // eat (
  std::vector<std::unique_ptr<ExprAST>> Args;
  if (CurTok != ')') {
    while (true) {
      if (auto Arg = ParseExpression())
        Args.push_back(std::move(Arg));
      else
        return nullptr;

      if (CurTok == ')')
        break;

      if (CurTok != ',')
        return LogError("Expected ')' or ',' in argument list");
      getNextToken();
    }
  }

  // Eat the ')'.
  getNextToken();

  return std::make_unique<CallExprAST>(IdName, std::move(Args));
}

此例程遵循與其他例程相同的風格。(它預期在當前權杖是 tok_identifier 權杖時被呼叫)。它還具有遞迴和錯誤處理。一個有趣的地方是它使用*預讀*來確定當前識別符號是獨立的變數參考還是函式呼叫表達式。它透過檢查識別符號之後的權杖是否是 '(' 權杖來處理這個問題,並根據需要建構 VariableExprASTCallExprAST 節點。

現在我們已經有了所有簡單的表達式解析邏輯,我們可以定義一個輔助函式來將它們包裝成一個入口點。我們將這類表達式稱為「主要」表達式,原因將在本教學的稍後部分更清楚地說明。為了解析任意主要表達式,我們需要確定它是哪種類型的表達式

/// primary
///   ::= identifierexpr
///   ::= numberexpr
///   ::= parenexpr
static std::unique_ptr<ExprAST> ParsePrimary() {
  switch (CurTok) {
  default:
    return LogError("unknown token when expecting an expression");
  case tok_identifier:
    return ParseIdentifierExpr();
  case tok_number:
    return ParseNumberExpr();
  case '(':
    return ParseParenExpr();
  }
}

現在您看到了這個函式的定義,我們為什麼可以假設各個函式中的 CurTok 狀態就更加明顯了。它使用預讀來確定正在檢查哪種類型的表達式,然後使用函式呼叫來解析它。

現在已經處理了基本表達式,我們需要處理二元表達式。它們稍微複雜一些。

2.5. 二元表達式解析

二元表達式的解析難度要大得多,因為它們通常含糊不清。例如,給定字串「x+y*z」時,解析器可以選擇將其解析為「(x+y)*z」或「x+(y*z)」。根據數學中的常見定義,我們預期後者解析,因為「*」(乘法)的*優先順序*高於「+」(加法)。

有很多方法可以處理這個問題,但一種優雅且有效的方法是使用運算子優先順序解析。這種解析技術使用二元運算子的優先順序來指導遞迴。首先,我們需要一個優先順序表

/// BinopPrecedence - This holds the precedence for each binary operator that is
/// defined.
static std::map<char, int> BinopPrecedence;

/// GetTokPrecedence - Get the precedence of the pending binary operator token.
static int GetTokPrecedence() {
  if (!isascii(CurTok))
    return -1;

  // Make sure it's a declared binop.
  int TokPrec = BinopPrecedence[CurTok];
  if (TokPrec <= 0) return -1;
  return TokPrec;
}

int main() {
  // Install standard binary operators.
  // 1 is lowest precedence.
  BinopPrecedence['<'] = 10;
  BinopPrecedence['+'] = 20;
  BinopPrecedence['-'] = 20;
  BinopPrecedence['*'] = 40;  // highest.
  ...
}

對於 Kaleidoscope 的基本形式,我們只支援 4 個二元運算子(顯然可以由您,我們勇敢而無畏的讀者,來擴展)。GetTokPrecedence 函式返回當前權杖的優先順序,如果權杖不是二元運算子,則返回 -1。使用映射可以輕鬆新增新的運算子,並且可以清楚地看出演算法不依賴於所涉及的特定運算子,但是消除映射並在 GetTokPrecedence 函式中進行比較也很容易。(或者只使用固定大小的陣列)。

定義好上述的輔助函數後,我們現在可以開始解析二元運算式。運算子優先順序解析的基本概念是將一個具有潛在歧義二元運算子的運算式分解成多個部分。例如,考慮運算式「a+b+(c+d)*e*f+g」。運算子優先順序解析將其視為由二元運算子分隔的一系列主要運算式。因此,它會先解析主要運算式「a」,然後會看到成對的 [+, b] [+, (c+d)] [*, e] [*, f] 和 [+, g]。請注意,由於括號是主要運算式,因此二元運算式解析器根本不需要擔心 (c+d) 之類的巢狀子運算式。

首先,運算式是一個主要運算式,後面可能會跟隨著一系列的 [binop,primaryexpr] 對。

/// expression
///   ::= primary binoprhs
///
static std::unique_ptr<ExprAST> ParseExpression() {
  auto LHS = ParsePrimary();
  if (!LHS)
    return nullptr;

  return ParseBinOpRHS(0, std::move(LHS));
}

ParseBinOpRHS 函數會解析我們的一系列對。它接受一個優先順序和一個指向已解析部分的運算式指標。請注意,「x」是一個完全有效的運算式:因此,「binoprhs」允許為空,在這種情況下,它會返回傳入的運算式。在上面的範例中,程式碼將「a」的運算式傳入 ParseBinOpRHS,而目前的詞彙是「+」。

傳入 ParseBinOpRHS 的優先順序值表示函數允許使用的*最小運算子優先順序*。例如,如果目前的對串流是 [+, x],並且 ParseBinOpRHS 傳入的優先順序是 40,則它不會使用任何詞彙(因為「+」的優先順序僅為 20)。考慮到這一點,ParseBinOpRHS 從以下開始

/// binoprhs
///   ::= ('+' primary)*
static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
                                              std::unique_ptr<ExprAST> LHS) {
  // If this is a binop, find its precedence.
  while (true) {
    int TokPrec = GetTokPrecedence();

    // If this is a binop that binds at least as tightly as the current binop,
    // consume it, otherwise we are done.
    if (TokPrec < ExprPrec)
      return LHS;

此程式碼會取得目前詞彙的優先順序,並檢查它是否過低。因為我們將無效詞彙的優先順序定義為 -1,所以此檢查會隱含地知道當詞彙串流用盡二元運算子時,對串流就會結束。如果此檢查成功,我們就知道該詞彙是一個二元運算子,並且它將包含在此運算式中。

// Okay, we know this is a binop.
int BinOp = CurTok;
getNextToken();  // eat binop

// Parse the primary expression after the binary operator.
auto RHS = ParsePrimary();
if (!RHS)
  return nullptr;

因此,此程式碼會使用(並記住)二元運算子,然後解析後面的主要運算式。這會建立整個對,第一個對是範例中的 [+, b]。

現在我們已經解析了運算式的左側和 RHS 序列中的一對,我們必須決定運算式的結合方式。特別是,我們可以有「(a+b) binop unparsed」或「a + (b binop unparsed)」。為了確定這一點,我們查看「binop」以確定其優先順序,並將其與 BinOp 的優先順序進行比較(在這種情況下為「+」)。

// If BinOp binds less tightly with RHS than the operator after RHS, let
// the pending operator take RHS as its LHS.
int NextPrec = GetTokPrecedence();
if (TokPrec < NextPrec) {

如果「RHS」右側的 binop 優先順序低於或等於我們目前運算子的優先順序,則我們知道括號的結合方式為「(a+b) binop ...」。在我們的範例中,目前的運算子是「+」,下一個運算子是「+」,我們知道它們的優先順序相同。在這種情況下,我們將為「a+b」建立 AST 節點,然後繼續解析。

      ... if body omitted ...
    }

    // Merge LHS/RHS.
    LHS = std::make_unique<BinaryExprAST>(BinOp, std::move(LHS),
                                           std::move(RHS));
  }  // loop around to the top of the while loop.
}

在上面的範例中,這會將「a+b+」轉換為「(a+b)」,並執行迴圈的下一次迭代,其中「+」為目前的詞彙。上面的程式碼會將「(c+d)」作為主要運算式使用、記住和解析,這使得目前的對等於 [+, (c+d)]。然後,它會以「*」作為主要運算式右側的 binop 來評估上面的「if」條件。在這種情況下,「*」的優先順序高於「+」的優先順序,因此將進入 if 條件。

這裡留下的關鍵問題是「if 條件如何完整解析右側」?特別是,為了為我們的範例正確建立 AST,它需要將所有「(c+d)*e*f」作為 RHS 運算式變數。執行此操作的程式碼非常簡單(上面兩個區塊中的程式碼重複出現以供參考)。

    // If BinOp binds less tightly with RHS than the operator after RHS, let
    // the pending operator take RHS as its LHS.
    int NextPrec = GetTokPrecedence();
    if (TokPrec < NextPrec) {
      RHS = ParseBinOpRHS(TokPrec+1, std::move(RHS));
      if (!RHS)
        return nullptr;
    }
    // Merge LHS/RHS.
    LHS = std::make_unique<BinaryExprAST>(BinOp, std::move(LHS),
                                           std::move(RHS));
  }  // loop around to the top of the while loop.
}

至此,我們知道主運算式右側的二元運算符的優先級高於我們目前正在解析的二元運算符。因此,我們知道任何運算符優先級都高於「+」的運算符對序列都應該被解析在一起並作為「RHS」返回。為此,我們遞迴調用 ParseBinOpRHS 函數,並指定「TokPrec+1」作為其繼續所需的最低優先級。在我們上面的例子中,這將導致它返回「(c+d)*e*f」的 AST 節點作為 RHS,然後將其設置為「+」運算式的 RHS。

最後,在 while 迴圈的下一次迭代中,「+g」部分被解析並添加到 AST 中。通過這一點點代碼(14 行非平凡的代碼),我們以一種非常優雅的方式正確地處理了完全通用的二元運算式解析。這只是對此代碼的旋風式瀏覽,它有點微妙。我建議使用一些棘手的例子來運行它,看看它是如何工作的。

這樣就完成了對運算式的處理。此時,我們可以將解析器指向一個任意的詞法單元流,並從中構建一個運算式,在第一個不屬於運算式的詞法單元處停止。接下來,我們需要處理函數定義等。

2.6. 解析其餘部分

接下來缺少的是對函數原型的處理。在 Kaleidoscope 中,這些原型既用於「extern」函數聲明,也用於函數體定義。執行此操作的代碼非常簡單,並且沒有什麼特別有趣的地方(一旦您了解了運算式)。

/// prototype
///   ::= id '(' id* ')'
static std::unique_ptr<PrototypeAST> ParsePrototype() {
  if (CurTok != tok_identifier)
    return LogErrorP("Expected function name in prototype");

  std::string FnName = IdentifierStr;
  getNextToken();

  if (CurTok != '(')
    return LogErrorP("Expected '(' in prototype");

  // Read the list of argument names.
  std::vector<std::string> ArgNames;
  while (getNextToken() == tok_identifier)
    ArgNames.push_back(IdentifierStr);
  if (CurTok != ')')
    return LogErrorP("Expected ')' in prototype");

  // success.
  getNextToken();  // eat ')'.

  return std::make_unique<PrototypeAST>(FnName, std::move(ArgNames));
}

鑑於此,函數定義非常簡單,只是一個原型加上一個用於實現函數體的運算式。

/// definition ::= 'def' prototype expression
static std::unique_ptr<FunctionAST> ParseDefinition() {
  getNextToken();  // eat def.
  auto Proto = ParsePrototype();
  if (!Proto) return nullptr;

  if (auto E = ParseExpression())
    return std::make_unique<FunctionAST>(std::move(Proto), std::move(E));
  return nullptr;
}

此外,我們還支持「extern」來聲明「sin」和「cos」等函數,以及支持用戶函數的前向聲明。這些「extern」只是沒有函數體的原型。

/// external ::= 'extern' prototype
static std::unique_ptr<PrototypeAST> ParseExtern() {
  getNextToken();  // eat extern.
  return ParsePrototype();
}

最後,我們還將允許用戶輸入任意的頂級運算式,並動態地對它們進行求值。我們將通過為它們定義匿名的零元(零參數)函數來處理這個問題。

/// toplevelexpr ::= expression
static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
  if (auto E = ParseExpression()) {
    // Make an anonymous proto.
    auto Proto = std::make_unique<PrototypeAST>("", std::vector<std::string>());
    return std::make_unique<FunctionAST>(std::move(Proto), std::move(E));
  }
  return nullptr;
}

現在我們已經擁有了所有部分,讓我們構建一個小驅動程序,讓我們實際執行我們構建的這個代碼!

2.7. 驅動程序

這個驅動程序只是使用頂級調度迴圈來調用所有解析部分。這裡沒有什麼特別有趣的地方,所以我只包含頂級迴圈。有關「頂級解析」部分中的完整代碼,請參見下方

/// top ::= definition | external | expression | ';'
static void MainLoop() {
  while (true) {
    fprintf(stderr, "ready> ");
    switch (CurTok) {
    case tok_eof:
      return;
    case ';': // ignore top-level semicolons.
      getNextToken();
      break;
    case tok_def:
      HandleDefinition();
      break;
    case tok_extern:
      HandleExtern();
      break;
    default:
      HandleTopLevelExpression();
      break;
    }
  }
}

最有趣的部分是我們忽略了頂級分號。你可能會問,為什麼會這樣?根本原因是,如果你在命令行中輸入「4 + 5」,解析器不知道這是否是你要輸入的內容的結尾。例如,在下一行,你可以輸入「def foo...」,在這種情況下,4+5 就是一個頂級運算式的結尾。或者,你可以輸入「* 6」,這將繼續這個運算式。使用頂級分號允許你輸入「4+5;」,解析器就會知道你已經輸入完畢。

2.8. 結論

僅用了不到 400 行的注釋代碼(240 行非注釋、非空行代碼),我們就完整地定義了我們的最小語言,包括詞法分析器、解析器和 AST 構建器。完成後,可執行文件將驗證 Kaleidoscope 代碼並告訴我們它在語法上是否有效。例如,以下是一個交互示例。

$ ./a.out
ready> def foo(x y) x+foo(y, 4.0);
Parsed a function definition.
ready> def foo(x y) x+y y;
Parsed a function definition.
Parsed a top-level expr
ready> def foo(x y) x+y );
Parsed a function definition.
Error: unknown token when expecting an expression
ready> extern sin(a);
ready> Parsed an extern
ready> ^D
$

這裡還有很大的擴展空間。你可以定義新的 AST 節點,以多種方式擴展語言等等。在下一部分中,我們將描述如何從 AST 生成 LLVM 中間表示(IR)。

2.9. 完整程式碼列表

以下是我們執行範例的完整程式碼列表。

# Compile
clang++ -g -O3 toy.cpp
# Run
./a.out

程式碼如下

#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>

//===----------------------------------------------------------------------===//
// Lexer
//===----------------------------------------------------------------------===//

// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
// of these for known things.
enum Token {
  tok_eof = -1,

  // commands
  tok_def = -2,
  tok_extern = -3,

  // primary
  tok_identifier = -4,
  tok_number = -5
};

static std::string IdentifierStr; // Filled in if tok_identifier
static double NumVal;             // Filled in if tok_number

/// gettok - Return the next token from standard input.
static int gettok() {
  static int LastChar = ' ';

  // Skip any whitespace.
  while (isspace(LastChar))
    LastChar = getchar();

  if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
    IdentifierStr = LastChar;
    while (isalnum((LastChar = getchar())))
      IdentifierStr += LastChar;

    if (IdentifierStr == "def")
      return tok_def;
    if (IdentifierStr == "extern")
      return tok_extern;
    return tok_identifier;
  }

  if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
    std::string NumStr;
    do {
      NumStr += LastChar;
      LastChar = getchar();
    } while (isdigit(LastChar) || LastChar == '.');

    NumVal = strtod(NumStr.c_str(), nullptr);
    return tok_number;
  }

  if (LastChar == '#') {
    // Comment until end of line.
    do
      LastChar = getchar();
    while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');

    if (LastChar != EOF)
      return gettok();
  }

  // Check for end of file.  Don't eat the EOF.
  if (LastChar == EOF)
    return tok_eof;

  // Otherwise, just return the character as its ascii value.
  int ThisChar = LastChar;
  LastChar = getchar();
  return ThisChar;
}

//===----------------------------------------------------------------------===//
// Abstract Syntax Tree (aka Parse Tree)
//===----------------------------------------------------------------------===//

namespace {

/// ExprAST - Base class for all expression nodes.
class ExprAST {
public:
  virtual ~ExprAST() = default;
};

/// NumberExprAST - Expression class for numeric literals like "1.0".
class NumberExprAST : public ExprAST {
  double Val;

public:
  NumberExprAST(double Val) : Val(Val) {}
};

/// VariableExprAST - Expression class for referencing a variable, like "a".
class VariableExprAST : public ExprAST {
  std::string Name;

public:
  VariableExprAST(const std::string &Name) : Name(Name) {}
};

/// BinaryExprAST - Expression class for a binary operator.
class BinaryExprAST : public ExprAST {
  char Op;
  std::unique_ptr<ExprAST> LHS, RHS;

public:
  BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
                std::unique_ptr<ExprAST> RHS)
      : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
};

/// CallExprAST - Expression class for function calls.
class CallExprAST : public ExprAST {
  std::string Callee;
  std::vector<std::unique_ptr<ExprAST>> Args;

public:
  CallExprAST(const std::string &Callee,
              std::vector<std::unique_ptr<ExprAST>> Args)
      : Callee(Callee), Args(std::move(Args)) {}
};

/// PrototypeAST - This class represents the "prototype" for a function,
/// which captures its name, and its argument names (thus implicitly the number
/// of arguments the function takes).
class PrototypeAST {
  std::string Name;
  std::vector<std::string> Args;

public:
  PrototypeAST(const std::string &Name, std::vector<std::string> Args)
      : Name(Name), Args(std::move(Args)) {}

  const std::string &getName() const { return Name; }
};

/// FunctionAST - This class represents a function definition itself.
class FunctionAST {
  std::unique_ptr<PrototypeAST> Proto;
  std::unique_ptr<ExprAST> Body;

public:
  FunctionAST(std::unique_ptr<PrototypeAST> Proto,
              std::unique_ptr<ExprAST> Body)
      : Proto(std::move(Proto)), Body(std::move(Body)) {}
};

} // end anonymous namespace

//===----------------------------------------------------------------------===//
// Parser
//===----------------------------------------------------------------------===//

/// CurTok/getNextToken - Provide a simple token buffer.  CurTok is the current
/// token the parser is looking at.  getNextToken reads another token from the
/// lexer and updates CurTok with its results.
static int CurTok;
static int getNextToken() { return CurTok = gettok(); }

/// BinopPrecedence - This holds the precedence for each binary operator that is
/// defined.
static std::map<char, int> BinopPrecedence;

/// GetTokPrecedence - Get the precedence of the pending binary operator token.
static int GetTokPrecedence() {
  if (!isascii(CurTok))
    return -1;

  // Make sure it's a declared binop.
  int TokPrec = BinopPrecedence[CurTok];
  if (TokPrec <= 0)
    return -1;
  return TokPrec;
}

/// LogError* - These are little helper functions for error handling.
std::unique_ptr<ExprAST> LogError(const char *Str) {
  fprintf(stderr, "Error: %s\n", Str);
  return nullptr;
}
std::unique_ptr<PrototypeAST> LogErrorP(const char *Str) {
  LogError(Str);
  return nullptr;
}

static std::unique_ptr<ExprAST> ParseExpression();

/// numberexpr ::= number
static std::unique_ptr<ExprAST> ParseNumberExpr() {
  auto Result = std::make_unique<NumberExprAST>(NumVal);
  getNextToken(); // consume the number
  return std::move(Result);
}

/// parenexpr ::= '(' expression ')'
static std::unique_ptr<ExprAST> ParseParenExpr() {
  getNextToken(); // eat (.
  auto V = ParseExpression();
  if (!V)
    return nullptr;

  if (CurTok != ')')
    return LogError("expected ')'");
  getNextToken(); // eat ).
  return V;
}

/// identifierexpr
///   ::= identifier
///   ::= identifier '(' expression* ')'
static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
  std::string IdName = IdentifierStr;

  getNextToken(); // eat identifier.

  if (CurTok != '(') // Simple variable ref.
    return std::make_unique<VariableExprAST>(IdName);

  // Call.
  getNextToken(); // eat (
  std::vector<std::unique_ptr<ExprAST>> Args;
  if (CurTok != ')') {
    while (true) {
      if (auto Arg = ParseExpression())
        Args.push_back(std::move(Arg));
      else
        return nullptr;

      if (CurTok == ')')
        break;

      if (CurTok != ',')
        return LogError("Expected ')' or ',' in argument list");
      getNextToken();
    }
  }

  // Eat the ')'.
  getNextToken();

  return std::make_unique<CallExprAST>(IdName, std::move(Args));
}

/// primary
///   ::= identifierexpr
///   ::= numberexpr
///   ::= parenexpr
static std::unique_ptr<ExprAST> ParsePrimary() {
  switch (CurTok) {
  default:
    return LogError("unknown token when expecting an expression");
  case tok_identifier:
    return ParseIdentifierExpr();
  case tok_number:
    return ParseNumberExpr();
  case '(':
    return ParseParenExpr();
  }
}

/// binoprhs
///   ::= ('+' primary)*
static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
                                              std::unique_ptr<ExprAST> LHS) {
  // If this is a binop, find its precedence.
  while (true) {
    int TokPrec = GetTokPrecedence();

    // If this is a binop that binds at least as tightly as the current binop,
    // consume it, otherwise we are done.
    if (TokPrec < ExprPrec)
      return LHS;

    // Okay, we know this is a binop.
    int BinOp = CurTok;
    getNextToken(); // eat binop

    // Parse the primary expression after the binary operator.
    auto RHS = ParsePrimary();
    if (!RHS)
      return nullptr;

    // If BinOp binds less tightly with RHS than the operator after RHS, let
    // the pending operator take RHS as its LHS.
    int NextPrec = GetTokPrecedence();
    if (TokPrec < NextPrec) {
      RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
      if (!RHS)
        return nullptr;
    }

    // Merge LHS/RHS.
    LHS =
        std::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
  }
}

/// expression
///   ::= primary binoprhs
///
static std::unique_ptr<ExprAST> ParseExpression() {
  auto LHS = ParsePrimary();
  if (!LHS)
    return nullptr;

  return ParseBinOpRHS(0, std::move(LHS));
}

/// prototype
///   ::= id '(' id* ')'
static std::unique_ptr<PrototypeAST> ParsePrototype() {
  if (CurTok != tok_identifier)
    return LogErrorP("Expected function name in prototype");

  std::string FnName = IdentifierStr;
  getNextToken();

  if (CurTok != '(')
    return LogErrorP("Expected '(' in prototype");

  std::vector<std::string> ArgNames;
  while (getNextToken() == tok_identifier)
    ArgNames.push_back(IdentifierStr);
  if (CurTok != ')')
    return LogErrorP("Expected ')' in prototype");

  // success.
  getNextToken(); // eat ')'.

  return std::make_unique<PrototypeAST>(FnName, std::move(ArgNames));
}

/// definition ::= 'def' prototype expression
static std::unique_ptr<FunctionAST> ParseDefinition() {
  getNextToken(); // eat def.
  auto Proto = ParsePrototype();
  if (!Proto)
    return nullptr;

  if (auto E = ParseExpression())
    return std::make_unique<FunctionAST>(std::move(Proto), std::move(E));
  return nullptr;
}

/// toplevelexpr ::= expression
static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
  if (auto E = ParseExpression()) {
    // Make an anonymous proto.
    auto Proto = std::make_unique<PrototypeAST>("__anon_expr",
                                                std::vector<std::string>());
    return std::make_unique<FunctionAST>(std::move(Proto), std::move(E));
  }
  return nullptr;
}

/// external ::= 'extern' prototype
static std::unique_ptr<PrototypeAST> ParseExtern() {
  getNextToken(); // eat extern.
  return ParsePrototype();
}

//===----------------------------------------------------------------------===//
// Top-Level parsing
//===----------------------------------------------------------------------===//

static void HandleDefinition() {
  if (ParseDefinition()) {
    fprintf(stderr, "Parsed a function definition.\n");
  } else {
    // Skip token for error recovery.
    getNextToken();
  }
}

static void HandleExtern() {
  if (ParseExtern()) {
    fprintf(stderr, "Parsed an extern\n");
  } else {
    // Skip token for error recovery.
    getNextToken();
  }
}

static void HandleTopLevelExpression() {
  // Evaluate a top-level expression into an anonymous function.
  if (ParseTopLevelExpr()) {
    fprintf(stderr, "Parsed a top-level expr\n");
  } else {
    // Skip token for error recovery.
    getNextToken();
  }
}

/// top ::= definition | external | expression | ';'
static void MainLoop() {
  while (true) {
    fprintf(stderr, "ready> ");
    switch (CurTok) {
    case tok_eof:
      return;
    case ';': // ignore top-level semicolons.
      getNextToken();
      break;
    case tok_def:
      HandleDefinition();
      break;
    case tok_extern:
      HandleExtern();
      break;
    default:
      HandleTopLevelExpression();
      break;
    }
  }
}

//===----------------------------------------------------------------------===//
// Main driver code.
//===----------------------------------------------------------------------===//

int main() {
  // Install standard binary operators.
  // 1 is lowest precedence.
  BinopPrecedence['<'] = 10;
  BinopPrecedence['+'] = 20;
  BinopPrecedence['-'] = 20;
  BinopPrecedence['*'] = 40; // highest.

  // Prime the first token.
  fprintf(stderr, "ready> ");
  getNextToken();

  // Run the main "interpreter loop" now.
  MainLoop();

  return 0;
}

下一步:實作程式碼生成至 LLVM IR