View on GitHub

flex-bison-examples

a list of flex/bison examples to show reentrant/C++/error-handling

Flex/Bison Examples

Here is a list of flex/bison examples to show some advanced features in the newest versions of flex/bison. There are several topics in this list:

  1. Reentrancy - this is important for parsing in multithread programs
  2. C++ - many old flex/bison tutorials only show how to use the C API, but bison do provide a nice and clean C++ api now. Using the variant and token constructor now!
  3. Optional semicolon - this is still an open question from the first year I learn bison (5years ago), but I wish to try some ideas in this repo
  4. UTF-8 support - flex is hard to implement utf-8 but I do need Chinese!
  5. Error recovery - the most difficult thing in bison
  6. Better error message - IBM has an old but nice article to show how to achieve it: https://developer.ibm.com/tutorials/l-flexbison/
  7. Indentation - python-like grammar is always a hard topic in flex, we will show how to achieve it.

Makefile and CMakeLists are provided to build the project. Please install the newest flex/bison in your system. Each project can be compilated separately.

Examples currently available:

Optional semicolon example, it can add the semicolon only at the end of line which needs a semicolon (the second line will not be inserted a ‘;’) :

defun work(name) {
    printf("hello world ~ %s\n",
        name)
    printf("optional semicolon example");
}

work("xiaofan")

Python-like indentation example, it can parse the following code (if you didn’t finish the line, the indentation will not influence your code block):

def work(name):
    for i in range(1, 30)
        print(i)
	
        a = a + b + c + 
             q + parse(1, 2)  // you can continue writing without considering indentation
        print(q)

Utf-8 example:

类型 速度 = 12
类型 文本 = "flex中文支持"

Error recovery example, it can parse all lines and output the error messages for each line:

(59 + 33) / 2 = 
123 + (12 =
59 + 33 / 3 =
1231 - ( 23 +  / 4 =
91 * ) ( - 3 =

目前拥有的示例:

在这个项目的wiki中我将介绍一下复杂的问题是如何被解决的,以及背后的一些实现思路,Flex、Bison使用的经验等。

Bison中句尾可选分号的实现

flex/bison实现Python风格缩进代码的解析