←課題5.1のヒント | ↑目次

情報科学実験II コンパイラ作成

第5回

完成したコンパイラの確認方法

  1. テスト用のプログラムとして、fibo.cを次のように作成する。
    int in();
    int out(int x);
    int fib(int k){
        if(k<2){
            return 1;
        }
        return fib(k-2)+fib(k-1);
    }
    int main(){
    int v;
        v=in();
        out(fib(v));
        return 0;
    }
    
  2. printast.tgzをダウンロード、解凍する。
  3. 以下のプログラム(kadai5.cとする)を作成し、ast.c, gen.c, printast.c, bisonが出力したpicoc.tab.c, flexが出力したlex.yy.cファイルとともにコンパイルする。
    gen.cのコンパイルが通らず、結果が出せない場合には、字句解析と構文解析ができたことを示すことを考えてもらいたい。少なくともast.cのコンパイルを通す。kadai5.cの最後から3行目のelse genCode();を削除して、ast.c, printast.c, bisonが出力した.cファイル(例えばpicoc.tab.c), flexが出力したlex.yy.cファイルとともにコンパイルする。
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include "ast.h"
    #include "gen.h"  /* アセンブリコードを出力しないのであれば不要 */
    #include "printast.h"
    #if YYDEBUG
    extern int yydebug;
    #endif
    extern DefNodePtr sourcedefs;
    FILE  *af;
    
    /* もし、bisonへの入力ファイル例えばpicoc.yやflexへの入力ファイル例えばpicoc.lで
    yyerror()の中身を定義していれば、
    multiple definition of `yyerror'などのコンパイルエラーが出る。
    その場合はここでの定義は不要なので、mainの前までを削除する */
    int yyerror( char *msg ){
    	fprintf( stderr, msg );
    	exit( 1 );
    }
    
    int main( int argc, char **argv ){
    #if YYDEBUG
    int i;
    	for( i=1; i<argc; i++ ){
    		if( strcmp( argv[i], "-d" )==0 ) yydebug = 1;
    	}
    #endif
    	af = stdout;
    	/* 構文解析を実行 */
    	if( yyparse() ) return EXIT_FAILURE;
    	/* 結果を出力 */
    	if( argc > 1 ) printASTDef( argc, argv, sourcedefs );
    	else genCode();   /* アセンブリコードを出力しないのであれば不要 */
    	return EXIT_SUCCESS;
    }
    
  4. その結果できたファイル(この例ではkadai5と仮定する)を実行するときに、
トップページ