def fib n if n 2 return 1
構文解析器 def fib ( n ): if n < 2: return 1 else: return … 構文解析器 字句列(token stream) 構文木 “fib” def n if < n … 2
構文木の定義(文の例) u u typedef struct stmt_while { /* while文 */ … } stmt_while, * stmt_while_t; typedef struct stmt_for { /* for文 */ … } stmt_for, * stmt_for_t; typedef struct stmt_fundef { /* def文 */ … } stmt_fundef, * stmt_fundef_t; … typedef struct stmt { /* 文全体 */ stmt_kind_t k; /* 種類 */ union { … } } stmt, * stmt_t;
例 : リスト u 整数のリスト • int_list_t mk_int_list(); • void int_list_append(int_list_t l, int x); • int_list_get(int_list_t l, int i); u char * のリスト • string_list_t mk_string_list(); • void string_list_append(string_list_t l, char * x); • char * string_list_get(string_list_t l, int i);
つまり,以下は合法 u int_list_t l = mk_int_list(); int_list_append(l, “hello”); char * x = int_list_get(l, 0);
ベターな慣習 u “汎用版”を一度だけ定義 • 中身はvoid*としておくのが良い • generic_list_t mk_generic_list(); generic_list_append(generic_list_t l, void * x); generic_list_get(generic_list_t l, int i); u それらを用いて個々の型に対するコンテナを 定義
例 int_list の定義 u u typedef struct int_list * int_list_t; int_list_t mk_int_list() { return (int_list_t)mk_generic_list(); } int_list_append(int_list_t l, int x) { generic_list_append((generic_list_t)l, (void *)x); } int_list_get(int_list_t l, int i) { return (int)generic_list_get((generic_list_t)l, i); }
- Slides: 30