llvm cookbook 2.2 实现lexer

编写toy.cpp

#include <string>
#include <iostream>

enum Token_type {
  EOF_TOKEN = 0,       // states the end of file
  NUMERIC_TOKEN,       // current token is numeric type
  IDENTIFIER_TOKEN,    // current token is identifier
  PARAN_TOKEN,         // parenthesis
  DEF_TOKEN            // states whatever follows is function definition
};

static int Numeric_Val;
static std::string Identifier_string;
FILE *file;

static int get_token() {
  static int LastChar = ' ';

  while (isspace(LastChar))
    LastChar = fgetc(file);
  if (isalpha(LastChar)) {
    Identifier_string = LastChar;
    while (isalnum((LastChar = fgetc(file))))   {
      Identifier_string += LastChar;
    }
    if (Identifier_string == "def") {
      return DEF_TOKEN;
    }
    return IDENTIFIER_TOKEN;
  }

  if (isdigit(LastChar)) {
    std::string NumStr;
    do {
      NumStr += LastChar;
      LastChar = fgetc(file);
    } while (isdigit(LastChar));
    Numeric_Val = strtod(NumStr.c_str(), 0);
    return NUMERIC_TOKEN;
  }

  if (LastChar == '#') {
    do {
      LastChar = fgetc(file);
    } while (LastChar != EOF && LastChar != '\n'
            && LastChar != '\r');
    if (LastChar != EOF) {
      return get_token();
    }
  }

  if (LastChar != EOF) {
    return EOF_TOKEN;
  }

  int ThisChar = LastChar;
  LastChar = fgetc(file);
  return ThisChar;
}

int main(int argc, char* argv[]) {
  file = fopen(argv[1], "r");
  if (file == NULL) perror("Error opening file");
  else {
      std::cout << get_token() << std::endl;
  }
  return 0;
}

编译

g++ -std=c++11 toy.cpp -o toy

测试代码source.ty:

def foo(x, y)
x + y * 16

运行

./toy source.ty
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 昨晚,《太阳的后裔》已经完结了,今天追剧完在微信发了一组漫画版剧图,配了“好的故事应该被记住”简单的几个字,表姐在...
    阿吉叙事阅读 268评论 0 0
  • 想变成一片叶子 然后就可以在平滑的夜里 睡到天亮 想手握一颗星星 跟着它去海上 迎接一颗崭新的太阳 想把溢出来的失...
    厘沫沫阅读 494评论 2 7
  • 我在的城市,今天的最低气温,零下11度,这样的低温,在这个冬天,我已经坚持了好几天,真的怕冷,怕自己倒下,...
    静谧的夏阅读 197评论 0 1