Flex和Bison忽略了函数体

Flex and Bison ignore function body

本文关键字:函数体 Bison Flex      更新时间:2023-10-16

嗨,我正在尝试使用 flex 和 bison 制作简单的 C 编译器来检查是否实现了每个声明的函数。我的问题是我想跳过函数体中的所有内容。例

int main()
{
    int n, flag;
    printf("Enter a positive integer: ");
    scanf("%d", &n);
    // Check prime number
    flag = checkPrimeNumber(n);
    if (flag == 1)
        printf("%d is a prime number.n", n);
    else
        printf("%d is not a prime number.n", n);
    // Check Armstrong number
    flag = checkArmstrongNumber(n);
    if (flag == 1)
        printf("%d is an Armstrong number.", n);
    else
        printf("%d is not an Armstrong number.",n);
    return 0;
}

所有"{"和"}"的一切。但是在函数内部,我们可以有 if(({} 和 while 等。

如何防止这种情况

现在我的 lex 文件

%{
#include "compilator_p.hpp"
#include <stdlib.h>
#include <string.h> 
void yyerror(const char *);
%}
alpha [a-zA-Z_] 
digit [0-9]
%%
[t]        ;
[n] { yylineno = yylineno + 1;}
int return INT;
float return FLOAT;
char return CHAR;
void return VOID;
"{".*"}" return BODY;
^"#include ".+ ;
[/][*][^*]*[*]+([^*/][^*]*[*]+)*[/]       { /* DO NOTHING */ }
";" return yytext[0];
"(" return yytext[0];
")" return yytext[0];
"," return yytext[0];
%%

除非你需要从头开始为学校作业编写解析器,否则我建议你使用现有的语法(如 https://www.lysator.liu.se/c/ANSI-C-grammar-y.html(,并将大部分操作留空。