【问题标题】:Flex and Bison ignore function bodyFlex 和 Bison 忽略函数体
【发布时间】:2018-01-19 16:18:15
【问题描述】:

您好,我正在尝试使用 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];

%%

【问题讨论】:

  • 你不能只复制[/][*][^*]*[*]+([^*/][^*]*[*]+)*[/] { /* DO NOTHING */ } 并更改正则表达式以匹配{...} 吗?如果你真的想让 flex 解析函数的内容,你应该在你的野牛文件中这样做

标签: c++ bison flex-lexer


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2016-05-30
    • 2019-10-26
    • 2013-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多