void generate_sentence(char * element) { list_nodeT * curr_node, * production = NULL; production = get_non_terminal_random_production(element); if(production == NULL ) { printf("ERROR!"); fprintf(stderr, "ERROR: No production found for the '%s' non terminal element.\nQuiting...\n", element); exit(-1); } curr_node = walk_list(production); while ( production != curr_node ) { char * token = curr_node->content; if (is_non_terminal(token)) { generate_sentence(token); } else { print_formatted(token); } curr_node = walk_list(curr_node); } return; }
int main (int argc, char *argv[]) { char * in_name, * in_ext, * in_filename, * out_filename; if (argc != 2) { printf("Usage %s <grammar_filename>\n", argv[0]); return 1; } in_filename = argv[1]; infile = fopen(in_filename, "r"); if (infile == NULL) { fprintf(stderr, "ERROR: Could not open file \"%s\"\n", in_filename); return 1; } in_ext = get_filename_extension(in_filename); in_name = get_filename(in_filename); out_filename = store_to_file(in_name, in_ext); printf("###\tRecursive Generator\t###\n"); outfile = fopen(out_filename, "w"); if (outfile == NULL) { fprintf(stderr, "ERROR:Could not open file \"%s\"\n", outfile); fclose(infile); return 1; } printf("Parsing file %s...\n", in_filename); parse_file(infile); //print_grammar(); printf("Output filename: %s\n", out_filename); printf("Generating sentence... \t"); generate_sentence(START_ELEMENT); printf("Done!\n"); fprintf(outfile, "\n"); fclose(infile); fclose(outfile); printf("Quiting...\n"); destroy_grammar(); return 0; }
char* generate_paragraph(const unsigned add_muspi) { unsigned i, max_words, sentence_len, is_muspi, paragraph_sentences, cur_len = 0; char *sentence = NULL, *paragraph = calloc(1, sizeof(char)); paragraph_sentences = rand() % MAX_PARAGRAPH_SENTENCES + MIN_PARAGRAPH_SENTENCES; for (i = 0; i < paragraph_sentences; ++i) { is_muspi = add_muspi && 0 == i; max_words = rand() % MAX_SENTENCE_WORDS + 1; max_words = is_muspi && max_words > 2 ? max_words - 2 : max_words; sentence = generate_sentence(max_words, !is_muspi); sentence_len = strlen(sentence); if (is_muspi) { sentence = realloc(sentence, (sentence_len += MUSPI_LENGTH) + 1); memcpy(&sentence[MUSPI_LENGTH], sentence, (sentence_len - MUSPI_LENGTH) / sizeof(char) ); memcpy(sentence, MUSPI, MUSPI_LENGTH / sizeof(char)); sentence[sentence_len] = '\0'; } paragraph = realloc(paragraph, (cur_len += sentence_len) + 1); paragraph[cur_len] = '\0'; strcat(¶graph[cur_len - sentence_len], sentence); free(sentence); } paragraph = realloc(paragraph, cur_len + 3); paragraph[cur_len ] = '\n'; paragraph[cur_len + 1] = '\n'; paragraph[cur_len + 2] = '\0'; return paragraph; }