当我在 Mac 上编译我的代码时,我不断收到“分段错误:11”,但它在 Windows 上运行良好,如果你能看看它并帮助我解决问题,我将不胜感激。在此先感谢弗朗西斯:D
mylang.l 代码:
%{
#include <stdio.h>
#include <string.h>
#include "lang.tab.h"
int lineno = 1;
%}
%%
"print" return PRINT;
[0-9]+ yylval=atoi(yytext); return NUMBER;
\".*\" yylval=strdup(yytext); return STRING;
\" return QUOTE;
\; return SEMICOLON;
[a-zA-Z][a-zA-Z0-9]* lineno++; yylval=strdup(yytext); return VARIABLE;
[\n] ;
"/*"([^*]|\*+[^*/])*\*+"/" ;
[ \t] ;
"=" return EQUALS;
"+" return PLUS;
"-" return MINUS;
"*" return MUL;
"/" return DIVIDE;
"%" return MODULUS;
. { printf("Error on line: %d", lineno); return 1; }
%%
mylang.y 代码:
%{
#include <stdio.h>
#include <string.h>
#include <math.h>
extern FILE *yyin; /* Input for yacc parser. */
#ifdef YYTEXT_POINTER
extern char *yytext; /* Current symbol for error reporting. */
#else
extern char yytext[];
#endif
extern int yylex(void); /* Lexical analyzer function. */
extern int yyparse(void); /* Parser function. */
int yydebug=0;
void yyerror(const char *str)
{
fprintf(stderr,"error: %s\n",str);
}
int yywrap()
{
return 1;
}
int main(int argc, char *argv[]) {
if (argc > 1)
{
yyin = fopen(argv[1], "r");
yyparse(); /* Calls yylex() for tokens. */
}
else
printf("syntax: %s filename\n", argv[0]);
return 0;
}
/* Custom functions for language will go here*/
/* and end here */
%}
%token PRINT
%token QUOTE
%token SEMICOLON
%token STRING
%token NUMBER
%token EQUALS
%token VARIABLE
%token PLUS
%token MINUS
%token MUL
%token DIVIDE
%token MODULUS
%left PLUS MINUS
%left MUL DIVIDE MODULUS
%start program
%%
program: /* empty */
|
program line
;
line: stmt
;
end_stmt: SEMICOLON
;
expr: NUMBER
{ $$ = $1; }
|
expr PLUS expr
{ $$ = $1 + $3; }
|
expr MINUS expr
{ $$ = $1 - $3; }
|
expr MUL expr
{ $$ = $1 * $3; }
|
expr DIVIDE expr
{ $$ = $1 / $3; }
|
expr MODULUS expr
{ $$ = $1 % $3; }
;
var: VARIABLE
{ $$ = $1; }
;
var_assignment: var EQUALS expr
{ varCounter($1); updateSymbolTable($1); }
;
stmt: print_stmt end_stmt
|
var_assignment end_stmt
;
print_stmt: PRINT STRING
{ printf("%s", $2); }
|
PRINT expr
{ printf("%d", $2); }
;
%%