以下是一个使用 Yacc 编写的包含加减乘除和打印函数的简单语言示例:

%{
#include <stdio.h>
#include <stdlib.h>
%}

%token NUM
%token PRINT

%left '+' '-'
%left '*' '/'

%%

program:
    statements
    ;

statements:
    statement
    | statements statement
    ;

statement:
    expression ';'
    | PRINT expression ';'
    ;

expression:
    NUM
    | expression '+' expression
    | expression '-' expression
    | expression '*' expression
    | expression '/' expression
    ;

%%

int main() {
    yyparse();
    return 0;
}

int yyerror(char *s) {
    printf("Error: %s\n", s);
    return 0;
}

int yylex() {
    int c = getchar();
    if (c == '+' || c == '-' || c == '*' || c == '/') {
        return c;
    }
    if (c == '\n') {
        return 0;
    }
    if (isdigit(c)) {
        int value = c - '0';
        while (isdigit(c = getchar())) {
            value = value * 10 + c - '0';
        }
        ungetc(c, stdin);
        yylval = value;
        return NUM;
    }
    if (c == 'p') {
        if (getchar() == 'r' && getchar() == 'i' && getchar() == 'n' && getchar() == 't') {
            return PRINT;
        }
    }
    return -1;
}

void yyerror(char *s) {
    printf("Error: %s\n", s);
}

void yyerror(char *s) {
    printf("Error: %s\n", s);
}

此语言支持基本的算术运算和打印函数。例如,以下是可以在此语言中运行的示例程序:

1 + 2 * 3;
print 4 + 5 / 2;

此程序将计算 1 + 2 * 3,然后打印 4 + 5 / 2 的结果。

使用 Yacc 构建支持算术运算和打印功能的简单语言

原文地址: https://www.cveoy.top/t/topic/lfpa 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录