meadow02のプロフィール

@meadow02 meadow02
ありがとう数0
質問数0
回答数1
ベストアンサー数
0
ベストアンサー率
0%
お礼率
0%

  • 登録日2008/12/16
  • 字句解析プログラムについて

    学校の課題でわからないところがあり教えていただけるととてもうれしいです。だれかお願いします 字句解析サンプルプログラム(lex2.c)について答えなさい。  lex2.が認識するトークンをBNFで表記しなさい。  lex2.cを以下のように拡張しなさい。 整数表記を <integer>::= <digit> {<digit>|'_'}* 以下のようなトークンも判別できるようにしてみる。 句切り文字:'(', 句切り文字:')', 句切り文字:';', 演算子:'=' ソースプログラムの拡張部分の抜粋とコンパイルコマンドと実行結果を提出すること。 (ソースプログラムへのコメントまたは簡単な説明を付けると評価は少しプラス) lex2.c #include <stdio.h> /********************************************************** * 識別子(identifier)を判別するプログラム * <ident>::= <alphabet>|'_' {<alphabet>|<digit>|'_'>}* **********************************************************/ #define isAlphabet(c) (('a'<=c && c<='z') || ('A'<=c && c<='Z')) #define isDigit(c) ('0'<=c && c<='9') // inputの先頭から識別子を読みこむ // identに識別子を表す文字列を入れ、読みこんだ文字数を返す // (識別子でなければ 0 が返る) int getIdent(char *input, char *ident) { char *start=input; /* 1文字目が英字または「_」なら識別子*/ if (isAlphabet(*input) || *input=='_') { *ident ++= *input++; /* 2文字目以降が、英字または「」または数字ならば識別子 */ while (isAlphabet(*input)|| isDigit(*input) || *input=='_') { *ident++=*input++; } } *ident='\0'; /*読んだ文字数を返すことにする*/ return input - start; } /********************************************************** * 正の整数定数を判別するプログラム * <integer>::= {<digit>}* **********************************************************/ //inputから正の整数定数を読みこむ //valueに整数定数の値を入れ、読みこんだ文字数を返す int getInt(char *input, int *value) { int v=0; char * start = input; /*練習に作ってみること*/ while (isDigit(*input)) { v=(v*10)+ (*input++ - '0'); } *value = v; return input - start; } int lex(char *input) { int i, n, num_of_tokens; char ident[1026]; int value; num_of_tokens = 0; while (*input !='\0') { //空白文字を読みとばす while (*input == ' ' || *input == '\t' || *input =='\r') input++; //先頭をトークンに変換する if ((n=getIdent(input, ident))>0) { printf("識別子: %s (%d文字)\n", ident, n); input += n; num_of_tokens++; } else if ((n=getInt(input, &value))>0) { printf("整数定数: %d (%d文字)\n", value, n); input += n; num_of_tokens++; } else if ( *input == '+' || *input == '-' || *input == '*' || *input== '/') { printf ("演算子:%c\n", *input); input++; num_of_tokens++; } else if (*input=='\n'){ printf("改行\n"); input++; } else { printf("エラー:%cは不正な文字\n", *input); input++; } } return num_of_tokens; } char line[1024]; int main(int argc, char* argv[]) { if (argc != 2) { printf("使いかた: %s '一行のテキスト'\n", argv[0]); exit(1); } printf("トークン数は%d個!\n", lex(argv[1])); }