-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodeInText.txt
More file actions
93 lines (79 loc) · 2.52 KB
/
Copy pathcodeInText.txt
File metadata and controls
93 lines (79 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
I am writing a project report, and I need help. I'll provide the codes for Bison and Flex. what the instructor asked us to do. and our powerpoint slides.
// instructor instructions for the project
Implement a Scanner/Parser for a simple language for expressions involving complex numbers using FLEX (Fast Lexical Analyzer Generator) and Bison (parser generator).
Your language should support all four basic arithmetic operations between complex numbers, as well as parentheses.
A complex number should be specified as (a ± bi), where a and b are integers.
Note that numbers that are missing either the real component or the imaginary component are considered valid.
Example: (5 – 2i) - (-2 + 3i)*(-5i) + (7)
// bison file
%{
#include <stdio.h>
#include <stdlib.h>
int yylex(void);
void yyerror(const char *s);
%}
%define parse.error verbose
%token INTEGER IMAGINARY
%token NEWLINE
%token PLUS MINUS TIMES DIVIDE
%token LPAREN RPAREN
%left PLUS MINUS
%left TIMES DIVIDE
%right UMINUS
%%
program:
program_line
| program program_line
;
program_line: NEWLINE { printf("Enter expressions in the form of complex numbers \"(a ± bi)\". (Ctrl+D to exit):\n"); }
| multi_expression NEWLINE { printf("Seems Good!\n"); }
| error NEWLINE { yyerrok; printf("Recovered from error.\n");}
;
multi_expression: enclosed_expression
| multi_expression addop enclosed_expression
| multi_expression multop enclosed_expression
;
enclosed_expression: LPAREN expression RPAREN
;
expression: term
| expression addop term
;
term: factor
| term multop factor
;
factor: INTEGER
| IMAGINARY
| MINUS factor %prec UMINUS
| LPAREN expression RPAREN
;
addop: PLUS | MINUS ;
multop: TIMES | DIVIDE ;
%%
void yyerror(const char *s) {
fprintf(stderr, "Parser Error: %s\n", s);
}
int main(void) {
printf("Enter expressions in the form of complex numbers \"(a ± bi)\". (Ctrl+D to exit):\n");
return yyparse();
}
// flex file
%{
#include "complex_parser.tab.h"
%}
%%
[0-9]+ { return INTEGER; }
[0-9]+i { return IMAGINARY; }
"i" { return IMAGINARY; }
"+" { return PLUS; }
"-" { return MINUS; }
"*" { return TIMES; }
"/" { return DIVIDE; }
"(" { return LPAREN; }
")" { return RPAREN; }
[ \t] ; /* Skip whitespace */
\n { return NEWLINE;}
. { fprintf(stderr, "Scanner Error: Invalid character '%s'\n", yytext); }
%%
int yywrap(void) {
return 1;
}