Lab 1 - Lexer


Note

Flex grammar

  1. flex doesnt try to read %
  2. when refering to a symbol (rather than the meaning in flex grammar), use \\ before the symbol
  3. use [] to refer to a set of language
  4. ^ means “everything but”

Code

%option noyywrap

%{
/* Now in a section of C that will be embedded
   into the auto-generated code. Flex will not
   try to interpret code surrounded by %{ ... %} */

/* Bring in our declarations for token types and
   the yylval variable. */
#include "histogram.hpp"

// This is to work around an irritating bug in Flex
// <https://stackoverflow.com/questions/46213840/get-rid-of-warning-implicit-declaration-of-function-fileno-in-flex>
extern "C" int fileno(FILE *stream);

/* End the embedded code section. */
%}

DIGIT [0-9]
LETTER [a-zA-Z]

%%

"-"?{DIGIT}+("."{DIGIT}+)?  {
   fprintf(stderr, "Number : %s\\n", yytext); 
   char *tmp = yytext; 
   yylval.numberValue = std::atof(tmp); 
   fprintf(stderr, "value : %f\\n", std::atof(tmp)); 
   tmp = NULL; 
   return Number; 
}

"-"?{DIGIT}+"/"{DIGIT}+     {
   fprintf(stderr, "Number : %s\\n", yytext); 
   char *tmp = yytext; 
   long unsigned int i=0; 
   while (tmp[i]!='/')
   {
      i = i + 1; 
   }
   char tmp1[] = {""}; 
   strncpy(tmp1, tmp+i+1, strlen(tmp)-i-1); 
   float x = std::atof(tmp)/std::atof(tmp1); 
   yylval.numberValue = x; 
   tmp = NULL; 
   return Number; 
}

{LETTER}+       {
   fprintf(stderr, "Word : %s\\n", yytext); 
   yylval.wordValue = new std::string(yytext);
   return Word; 
}

"["[^]]*"]"  {
   fprintf(stderr, "Word : %s\\n", yytext); 
   yylval.wordValue = new std::string(yytext);
   return Word; 
}

.               { }

\\n              { fprintf(stderr, "Newline\\n"); }

%%

/* Error handler. This will get called if none of the rules match. */
void yyerror (char const *s)
{
  fprintf (stderr, "Flex Error: %s\\n", s); /* s is the text that wasn't matched */
  exit(1);
}

Lab 2 - Parser


Note

  1. To run TODO-B in ast/primitives:

    echo "a+2" | bin/eval_expr a 10

Code