#include #include #include #define MAX_PRODUCTIONS 100 #define MAX_WORD_LENGTH 100 typedef char Symbol; Symbol read_sym(FILE* file){ Symbol s; fscanf(file,"%c",&s); return s; } int is_terminal(Symbol s){ return (islower(s)); } int is_nonterminal(Symbol s){ return (isupper(s)); } int is_prodsym(Symbol s){ return (s == '>'); } int is_end_of_prod(Symbol s){ return (s == '\n'); } void print_sym (Symbol s){ printf("%c ",s); } typedef struct{ Symbol word [MAX_WORD_LENGTH]; unsigned length; } Word; void print_word (Word* w){ int i; for (i=0; i < w->length; i++) print_sym(w->word[i]); } typedef struct{ Word left; Word right; } Production; void print_production (Production* p){ print_word(&p->left); printf (" --> "); print_word(&p->right); } typedef struct{ Production productions[MAX_PRODUCTIONS]; unsigned numprod; } Grammar; void print_grammar(Grammar* g){ int i; if (g == NULL) printf ("Errore! Grammatica non valida! \n"); else{ printf ("Numero di produzioni: %d\n", g->numprod); for (i=0; inumprod; i++){ print_production(&g->productions[i]); printf ("\n"); } } } Grammar* load_grammar(FILE* file, Grammar* g){ Symbol s; enum States {START,LEFT,RIGHT,ERROR}; enum States current_state = START; Production* p; g->numprod = 0; while (current_state != ERROR && !feof(file)) s = read_sym(file); if feof(file) return 0 ; switch(current_state){ case START: if (is_terminal(s) || is_nonterminal(s)){ current_state = LEFT; p = &(g->productions[g->numprod++]); p->left.length = 0; p->left.word[p->left.length++] = s; }else current_state = ERROR; break; case LEFT: if (is_terminal(s) || is_nonterminal(s)){ current_state = LEFT; p->left.word[p->left.length++] = s; }else if (is_prodsym(s)){ current_state = RIGHT; p->right.length = 0; }else current_state = ERROR; break; case RIGHT: if (is_terminal(s) || is_nonterminal(s)){ current_state = RIGHT; (*p).right.word[p->right.length++] = s; }else if (is_end_of_prod(s)){ current_state = START; }else current_state = ERROR; break; } if (current_state == START || current_state == RIGHT) return g; else return NULL; } int main(int argc, char *argv[]){ char* filename = argv[1]; FILE* gram_file; Grammar grammar; if (filename == 0){ printf("nome file non specificato \n"); system("PAUSE"); return -1; } gram_file = fopen("C:\mygrammar.txt","r"); if (gram_file == NULL){ printf("nome di file errato\n"); system("PAUSE"); return -1; } print_grammar(load_grammar(gram_file,&grammar)); fclose(gram_file); system("PAUSE"); return 0; }