parser generatorであるyacc/bison、lexer generatorであるlex/flexなど(それぞれ後者がGNU実装?)

Flex

*.l ファイルに正規表現を使ってトークンを記述し、int yylex(void) を生成する

 
 
int main(void) {
  while (yylex());
}
 
int yywrap(void) { return 1; }

TODO : yywrap って何?(ないとコンパイルが通らない)

$ flex test.l
# `lex.yy.c` is created
$ clang lex.yy.c
$ ./a.out
132  <- input
[num] 132
 
hello  <- input
[str] hello

yylex() はグローバル変数である FILE* yyin から入力を受け取り、字句解析を行う
yyin がNULLだった場合、yylex()yyin = stdin してから字句解析を行う)
つまりファイルを入力としたい場合はこんなふうにすれば良い:

#include <stdio.h>
 
/* Declare the yylex function, which is generated by Lex. */
extern int yylex();
 
/* Declare yyin, the input file pointer used by Lex. */
extern FILE *yyin;
 
int main(int argc, char *argv[]) {
    /* Check if a filename was provided on the command line. */
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <input_file>\n", argv[0]);
        return 1;
    }
 
    /* Open the file provided as the first command-line argument. */
    FILE *input_file = fopen(argv[1], "r");
    if (input_file == NULL) {
        perror("Error opening file");
        return 1;
    }
 
    /* Set Lex's input to the opened file. */
    yyin = input_file;
 
    /* Call the lexical analyzer. */
    yylex();
 
    /* Close the file when done. */
    fclose(input_file);
 
    return 0;
}

Bison

*y
yylex() を呼んで?字句を受け取り、