Skip to content

rahulkbharti/compiler-from-scratch

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

README

Installation of Bison and Flex

Linux (Ubuntu/Debian)

Run the following command to install Bison and Flex:

sudo apt update
sudo apt install bison flex -y

Linux (Fedora)

sudo dnf install bison flex -y

Linux (Arch Linux)

sudo pacman -S bison flex

macOS (Homebrew)

brew install bison flex

Windows (Using Cygwin or MSYS2)

For Cygwin:

  1. Open Cygwin setup and search for "bison" and "flex" in the package selection.
  2. Install them and complete the setup.

For MSYS2:

pacman -S mingw-w64-x86_64-bison mingw-w64-x86_64-flex

Verify Installation

After installation, check the installed versions:

bison --version
flex --version

If both commands return version numbers, the installation is successful.

Usage Example

To compile a Bison and Flex project:

bison -d parser.y
flex lexer.l
gcc lex.yy.c parser.tab.c -o my_parser
./my_parser

Example Bison and Flex Files

lexer.l (Flex File)

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

%%

[0-9]+      { yylval.num = atoi(yytext); return NUMBER; }
[+\-*/()]   { return yytext[0]; }
[ \t\n]     { /* Ignore whitespace */ }
.           { printf("Unknown character: %s\n", yytext); }

%%

int yywrap() {
    return 1;
}

parser.y (Bison File)

%{
    #include <stdio.h>
    #include <stdlib.h>
    void yyerror(const char *s);
    int yylex();
%}

%union {
    int num;
}

%token <num> NUMBER
%token PLUS MINUS MULTIPLY DIVIDE LPAREN RPAREN
%left PLUS MINUS
%left MULTIPLY DIVIDE
%right UMINUS

%type <num> expr

%%

expr:
      expr PLUS expr      { $$ = $1 + $3; printf("Result: %d\n", $$); }
    | expr MINUS expr     { $$ = $1 - $3; printf("Result: %d\n", $$); }
    | expr MULTIPLY expr  { $$ = $1 * $3; printf("Result: %d\n", $$); }
    | expr DIVIDE expr    { 
        if ($3 == 0) { 
            printf("Error: Division by zero\n"); 
            $$ = 0;
        } else {
            $$ = $1 / $3; 
            printf("Result: %d\n", $$);
        }
      }
    | LPAREN expr RPAREN  { $$ = $2; }
    | MINUS expr %prec UMINUS { $$ = -$2; }
    | NUMBER              { $$ = $1; }
    ;

%%

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

int main() {
    printf("Enter an expression:\n");
    return yyparse();
}

Running the Example

Once compiled, run the program:

./my_parser

Example input:

3 + 4 * 2

Expected output:

Result: 11

About

Built a basic compiler using Flex (for lexical analysis) and Bison (for syntax parsing). It takes simple arithmetic expressions and control flow statements as input, parses them, and checks for syntactic correctness.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors