diff --git a/grammar.y b/grammar.y new file mode 100644 index 0000000..812b294 --- /dev/null +++ b/grammar.y @@ -0,0 +1,69 @@ +//A01781041 +%{ +#include +#include + +// Declare yyin and yylineno if they're not already defined by Flex +extern FILE *yyin; +extern int yylineno; + +void yyerror(const char *s) { + fprintf(stderr, "Error: %s at line %d\n", s, yylineno); + exit(EXIT_FAILURE); +} + +int yylex(void); +%} + +%token ARTICLE BOY GIRL FLOWER TOUCHES LIKES SEES WITH + +%% + +SENTENCE: NOUN_PHRASE VERB_PHRASE + ; + +NOUN_PHRASE: ARTICLE NOUN + | ARTICLE NOUN PREP_PHRASE + ; + +NOUN: BOY + | GIRL + | FLOWER + ; + +VERB_PHRASE: VERB + | VERB NOUN_PHRASE + ; + +VERB: TOUCHES + | LIKES + | SEES + ; + +PREP_PHRASE: WITH NOUN_PHRASE + ; + +%% + +int main(int argc, char *argv[]) { + if (argc != 2) { + fprintf(stderr, "Usage: %s \n", argv[0]); + exit(EXIT_FAILURE); + } + + FILE *file = fopen(argv[1], "r"); + if (!file) { + perror(argv[1]); + exit(EXIT_FAILURE); + } + + yyin = file; + + // Parse through the input until there is no more: + do { + yyparse(); + } while (!feof(yyin)); + + fclose(file); + return 0; +} diff --git a/tokens.l b/tokens.l new file mode 100644 index 0000000..4234f6f --- /dev/null +++ b/tokens.l @@ -0,0 +1,24 @@ +%{ +#include "grammar.tab.h" +%} + +%option yylineno + +%% + +[aA] { return ARTICLE; } +boy { return BOY; } +girl { return GIRL; } +flower { return FLOWER; } +touches { return TOUCHES; } +likes { return LIKES; } +sees { return SEES; } +with { return WITH; } +[ \t\n]+ ; /* Ignore whitespaces and newlines */ +. ; /* Ignore other characters */ + +%% + +int yywrap(void) { + return 1; +}