220187

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 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

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy