yacc 与lex单元1示例

总结 lex.l 生产词法分析器 扫描输入文件 分割一个个的词 return给语法分析 最后返回0 表示词法结束。。然后语法分析 匹配 将所有词的组合 匹配第一个(初始)规则,如果 匹配成功 则执行对应动作 出错则调用yyerror函数

yacc.y

%{

#include<stdio.h>
%}


%token NOUN PRONOUN VERB ADVERB ADJECTIVE PREPOSITION CONJUNCTION
%%


sentence: simple_sentence { printf("Parsed a simple sentence.\n");}
        | compound_sentence { printf("Parsed a compound sentence.\n");}
        ;
simple_sentence: subject verb object
               | subject verb object prep_phrase
        ;
compound_sentence: simple_sentence CONJUNCTION simple_sentence
                 | compound_sentence CONJUNCTION simple_sentence
        ;
subject : NOUN
        | PRONOUN
        | ADJECTIVE subject
        ;
verb: VERB
    | ADJECTIVE object
    ;
object:     NOUN
      | ADJECTIVE object
      ;
prep_phrase: PREPOSITION NOUN;
%%
//extern FILE *yyin;
int main()
{
    //while(!feof(yyin)) { 此行不需要 
        yyparse();
        return 0;
   // }
}


int yyerror(char *s)
{
    fprintf(stderr, "%s\n", s);

}


lex.l代码


%{
/*
带符号表的单词识别程序
*/
#include<stdlib.h> //malloc 函数
#include "y.tab.h" //yacc 产生的头文件


#define LOOKUP 0
int state;
int add_word(int state, char *word);
int lookup_word(char *word);
%}


%%
\n { state = LOOKUP;}
\.\n { state = LOOKUP;return 0;/*句子结尾*/}
^verb { state = VERB;}
^adj { state = ADJECTIVE;}
^adv { state = ADVERB;}
^noun { state = NOUN;}
^prep { state = PREPOSITION;}
^pron { state = PRONOUN;}
^conj { state = CONJUNCTION;}


[a-zA-Z]+ {
    if(state != LOOKUP) {
        add_word(state, yytext);/* yytext 等于当前匹配到的模式 */
    } else {
        switch (lookup_word(yytext)) {
            case VERB: return (VERB); /* () 保证宏定义不会有歧义 */
            case ADJECTIVE:return (ADJECTIVE); 
            case ADVERB: return (ADVERB); 
            case NOUN: return (NOUN); 
            case PREPOSITION: return (PREPOSITION); 
            case PRONOUN: return (PRONOUN); 
            case CONJUNCTION: return (CONJUNCTION); 
            default:
                    printf ("%s dont reconquize\n", yytext);break;
        }
    }
}


%%
/*
int main()
{
    yylex();
}
*/
struct word {
    char *word_name;
    int word_type;
    struct word *next;
};


struct word *word_list;
int add_word(int type, char *word)
{
    struct word *wp;
    if(lookup_word(word) != LOOKUP) {
        printf("!!! warning :word  %s already defined \n", word);
    }
    wp = (struct word*) malloc(sizeof(struct word));
    wp->next = word_list;
    wp->word_name = (char *)malloc(strlen(word)+1);
    strcpy(wp->word_name, word);
    wp->word_type   = type;
    word_list = wp;
    return 1;
}
int lookup_word(char *word)
{
    struct word *wp = word_list;
    for(;wp;wp = wp->next) {
        if (strcmp(wp->word_name, word) == 0) {
            return wp->word_type;
        }
    }
    return LOOKUP; //未找到
}

你可能感兴趣的:(yacc 与lex单元1示例)