0% found this document useful (0 votes)
8 views3 pages

220187

Uploaded by

bushraahmedbj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views3 pages

220187

Uploaded by

bushraahmedbj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

‫امباركة عبالباسط محمد‬

220187

**simple_lang.l (Lex file):**

%{
#include "y.tab.h"
%}

%%

[a-zA-Z][a-zA-Z0-9]* { yylval.string = strdup(yytext); return IDENTIFIER; }


[0-9]+\.[0-9]+ { yylval.fval = atof(yytext); return FLOAT; }
[0-9]+ { yylval.ival = atoi(yytext); return INTEGER; }
"+" { return PLUS; }
"-" { return MINUS; }
"*" { return MULT; }
"/" { return DIV; }
"=" { return ASSIGN; }
"if" { return IF; }
"then" { return THEN; }
"else" { return ELSE; }
"(" { return LPAREN; }
")" { return RPAREN; }
";" { return SEMICOLON; }
[ \t\n]+ { /* ignore whitespace */ }
. { return yytext[0]; }

%%

int yywrap() {
return 1;
}
```

**simple_lang.y (Yacc file):**

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

int yylex();
void yyerror(char *s);

typedef struct {
char *name;
int ival;
float fval;
} Symbol;
Symbol symtab[100];
int symcount = 0;
%}

%union {
int ival;
float fval;
char *string;
}

%token <string> IDENTIFIER


%token <ival> INTEGER
%token <fval> FLOAT
%token PLUS MINUS MULT DIV ASSIGN
%token IF THEN ELSE
%token LPAREN RPAREN SEMICOLON

%type <ival> expression condition


%type <string> statement

%%

program:
statement program
| /* empty */
;

statement:
IDENTIFIER ASSIGN expression SEMICOLON { /* handle variable assignment */ }
| IF condition THEN statement ELSE statement SEMICOLON { /* handle if-statement */ }
| /* empty */
;

expression:
expression PLUS expression { /* handle addition */ }
| expression MINUS expression { /* handle subtraction */ }
| expression MULT expression { /* handle multiplication */ }
| expression DIV expression { /* handle division */ }
| LPAREN expression RPAREN
| IDENTIFIER { /* handle variable access */ }
| INTEGER { /* handle integer literal */ }
| FLOAT { /* handle float literal */ }
;

condition:
expression { /* return 1 if expression is true, 0 if false */ }
;

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

void yyerror(char *s) {


fprintf(stderr, "%s\n", s);
}

You might also like