/cpexp

Primary LanguagePython

CPExp

这是什么

CPExp: Compile Principle Experiment,即编译原理实验。

本仓库存储《编译原理》实验涉及的代码,其功能如下:

  • 课程要求功能:将课程给出的代码编译为三地址码(Exp->TAC)
  • 扩展功能:将C语言简化版代码编译为AMD64汇编(C4e->AMD64)
    • 调试用中间功能:C4e->TACP

环境配置

对于任何运行的前提:

  • 安装python,最低版本为3.10
  • 安装python包,pip install -r requirements.txt

对于生成可执行文件(AMD64ELF)的额外要求

  • 目前仅支持Linux操作系统下
  • 安装nasm
  • 安装ld(通常系统自带)

系统构建(Build)方式

cpexp/antlr包中存储构建系统自动构建部分的管理功能和生成后的内容。 由于自动生成部分不包括在源代码中,直接运行clone后的repo会报错,需要先使用脚本构建。

具体使用要求如下:

  • 当前无任何构建时(cpexp/antlr中仅有build.py时),必须使用根目录下build.py脚本构建
  • 当前有构建但不是所需语言时,系统(main.py)运行时会自动重新构建并退出,要求重新运行系统
  • 当前有构建且是所需语言时,系统正常运行

以下为根目录下build.py脚本使用方法:

usage: build.py [-h] [--language LANGUAGE] [--verbose] [--force]

options:
  -h, --help            show this help message and exit
  --language LANGUAGE, -l LANGUAGE
  --verbose, -v
  --force, -f

脚本语言默认为exp,可以先不指定语言运行(构建exp),随后让系统自动重新构建到正确的源语言。

系统运行方式

以下为根目录下main.py脚本使用方法:

usage: main.py [-h] [--STDIN] [-s {c4e,exp}] [-t {tac,tacp,amd64asm,amd64elf}]
  [-o OUTPUT] [--tokens] [-r] [-v] [input]

positional arguments:
  input                 Path to the input file

options:
  -h, --help                        show this help message and exit
  --STDIN                           get input from STDIN instead of file
  -s {c4e,exp}, --source {c4e,exp}  source language
  -t {tac,tacp,amd64asm,amd64elf}   target language
  -o OUTPUT, --output OUTPUT        path to the output file
  --tokens                          only lex and print tokens instead of compile
  -r, --run                         run after compile
  -v, --verbose                     verbosity

项目结构

 +--------+
 | Source |  ---- Examples + Test cases
 +--------+           (In Exp, C4e)
      |
      |           Lexer + Parser  <------- Grammar
      |  (CPExpXxx.py, Generated by ANTLR)
      |     (and lexer.py + parser.py)
      |
     \|/
   +-----+
   | AST |
   +-----+
      | 
      |     Semantic Analyzer
      |       (semantic.py)
      |
     \|/
 +---------+
 | TAC(IR) |
 +---------+
      |
      |        Generator
      |      (generator.py)
      |
     \|/
  +--------+
  | Target |  --- Expected result
  +--------+      (In TAC, TACP)