自己動手寫basic解釋器(七)

 

自己動手寫basic解釋器

刺蝟@http://blog.csdn.net/littlehedgehog

 





注: 文章basic解釋源碼摘自梁肇新先生的《編程高手箴言》(據他所說這個代碼也是網上摘錄的),源碼解讀參考《java編程藝術》。《java編程藝術》裏面自然是java版了(可能旭哥更加適合點兒),我這裏還是解讀的C版basic解釋器代碼。





終於把這個basic解釋器主幹源碼解述完了。其實說來這個解釋器實際意義並不大,但是通過閱讀源代碼我們可以深一步領悟程序語言執行內部機理。我覺得特別值得提的三點:
1、通過prog指針模擬CPU中的eip寄存器,巧妙地借鑑了世界最頂尖級的硬件工程師在處理程序運行問題上的思路。
2、模擬函數調用棧,這個在go_sub函數中得到了淋漓盡致地體現。
3、p_buf就相當於計算機內存,或者說是程序運行空間的text段,26個變量就相當於data段,而我們的模擬棧恰好就是程序中的棧空間。


最後我把主程序的代碼貼出來,方便兄弟夥們:


  1. #include <stdio.h>
  2. #include <setjmp.h>
  3. #include <math.h>
  4. #include <ctype.h>
  5. #include <stdlib.h>

  6. #define NUM_LAB 100
  7. #define LAB_LEN 10
  8. #define FOR_NEST 25
  9. #define SUB_NEST 25
  10. #define PROG_SIZE 10000
  11. #define DELIMITER 1
  12. #define VARIABLE 2
  13. #define NUMBER 3
  14. #define COMMAND 4
  15. #define STRING 5
  16. #define QUOTE 6

  17. #define PRINT 1
  18. #define INPUT 2
  19. #define IF 3
  20. #define THEN 4
  21. #define FOR 5
  22. #define NEXT 6
  23. #define TO 7
  24. #define GOTO 8
  25. #define EOL 9
  26. #define FINISHED 10
  27. #define GOSUB 11
  28. #define RETURN 12
  29. #define END 13

  30. char *prog;      /* holds expression to be analyzed  */
  31. jmp_buf e_buf;   /* hold environment for longjmp() */

  32. int variables[26]= {  /* 26 user variables,A-Z  */
  33.     0,0,0,0,0,0,0,0,0,0,
  34.     0,0,0,0,0,0,0,0,0,0,
  35.     0,0,0,0,0,0
  36. };

  37. struct commands { /* keyword lookup table  */
  38.     char command[20];
  39.     char tok;
  40. } table[] = {  /* command must be entered lowercase  */
  41.     "print",PRINT,   /* in this table  */
  42.     "input",INPUT,
  43.     "if",IF,
  44.     "then",THEN,
  45.     "goto",GOTO,
  46.     "for",FOR,
  47.     "next",NEXT,
  48.     "to",TO,
  49.     "gosub",GOSUB,
  50.     "return",RETURN,
  51.     "end",END,
  52.     NULL,END
  53. };

  54. char token[80];     //注意token是數組類型
  55. char token_type,tok;

  56. struct label {
  57.     char name [LAB_LEN];
  58.     char *p;    /* point to place to go in source */
  59. };

  60. struct label label_table[NUM_LAB];
  61. char *find_label(),*gpop();

  62. struct for_stack {
  63.     int var;   /* counter variable  */
  64.     int target;  /* target value  */
  65.     char *loc;
  66. } fstack[FOR_NEST];  /* stack for FOR/NEXT loop  */
  67. struct for_stack fpop();

  68. char *gstack[SUB_NEST];  /* stack for gosub  */
  69. int ftos;  /* index to top of FOR stack  */
  70. int gtos;  /* index to top of GOSUB  */

  71. void print(),scan_labels(),find_eol(),exec_goto();
  72. void gosub(),greturn(),gpush(),label_init(),fpush();

  73. /* Load a program */
  74. load_program (char *p,char *fname)
  75. {
  76.     FILE *fp;
  77.     int i=0;
  78.    
  79.     if (!(fp=fopen(fname,"rb")))  return 0;

  80.     i=0;
  81.     do  {
  82.         *p = getc(fp);
  83.         p++;i++;
  84.     } while (!feof(fp)&&i<PROG_SIZE);
  85.     *(p-2) = '/0';   /* null terminate the program  */
  86.     fclose (fp);
  87.     return 1;
  88. }


  89. /* 給變量賦值  比如 a=3  
  90.  * 注意這裏爲了簡化起見,我們的變量就設置爲26個字母
  91.  */
  92. assignment()
  93. {
  94.     int var,value;

  95.     /* getthe variable name */
  96.     get_token();
  97.     if (!isalpha(*token))  //因爲變量我們用字母代替 所以必定是字母類型
  98.     {
  99.         serror(4);
  100.         return;
  101.     }

  102.     var = toupper(*token)-'A';  //轉化爲大寫字母  然後減去'A' 這樣讓變量在hash表中有了座次 比如A減去A爲0 這樣A字符變量在變量hash表中第一個位置

  103.     /* get the equals sign 
  104.      * 這裏我們取a=3 中間的等號*/
  105.     get_token();
  106.     if (*token!='=')    //既然賦值麼 肯定有等號了
  107.     {
  108.         serror(3);
  109.         return;
  110.     }

  111.     /* a=3  等號取走了 我們來取數值  */
  112.     get_exp(&value);
  113.    
  114.     /* 把我們取到的變量 比如a 值爲3 存放在hash表中 */
  115.     variables[var] = value;
  116. }


  117. /* execute a simple version of the BASIC PRINT statement 
  118.  * 執行打印  這裏我們還是舉例說明*/
  119. void print()
  120. {
  121.     int answer;
  122.     int len=0,spaces;
  123.     char last_delim;
  124.    
  125.     do  {
  126.         get_token();  /* get next list item */
  127.         if (tok==EOL||tok==FINISHED)  break;  //如果取到的符號是一行結束或者文件結束  自然的打印結束

  128.                  
  129.         //BASIC 中print一般有兩種用法  第二種就是print "hello world"  打印字符串  
  130.         if (token_type==QUOTE)  
  131.         {  
  132.             printf ("%s",token);
  133.             len+=strlen(token);
  134.             get_token();    //注意我們打印了後又取了一次符號
  135.         }
  136.         else   //打印變量的
  137.         { 
  138.             putback();
  139.             get_exp(&answer);
  140.             get_token();    //注意我們打印了後又取了一次符號
  141.             len += printf ("%d",answer);
  142.         }
  143.         last_delim = *token;    
  144.         
  145.         
  146.         /* Basic 有兩種打印間隔標識 
  147.          * 比如 print a,b 表示按標準格式打印
  148.          * 而print a;b 表示按照緊湊格式打印  
  149.          * 所謂標準格式簡單來講就是間隔大點兒  緊湊自然間隔小點兒  
  150.          */
  151.         if (*token==',')  
  152.         {
  153.             /* compute number of move to next tab */
  154.             spaces = 8-(len%8);
  155.             len += spaces;  /* add in the tabbing position */
  156.             while (spaces)  {
  157.                 printf (" ");
  158.                 spaces--;
  159.             }
  160.         }
  161.         else if (*token==';')  
  162.             printf ("  ");
  163.         else if (tok != EOL && tok != FINISHED) serror (0);     //print a,b 打完一次後 要麼是逗號、分號 要麼就是行結束或者文件結束  如果四者不居其一  必然錯了
  164.     } while (*token==';'||*token==',');     //例如 print a,b,c 如果token是逗號、分號 那麼表示後面還有打印  繼續來

  165.     /* 當處於行結束或者文件結束  那麼前一次分界符不能是;或者,  
  166.      * 示例 如果 "print a," 這個明顯是語法錯誤 a後面不應該要逗號
  167.      * 那麼打印完a取出token是逗號  我們賦值給last_delim 繼續循環
  168.      *  下一個是行結束  跳出打印但是檢驗出last_delim是逗號  出錯 */
  169.     if (tok==EOL||tok==FINISHED)    
  170.     {
  171.         if (last_delim != ';' && last_delim != ',') printf ("/n");
  172.     }
  173.     else serror(0);  /* error is not, or ; */
  174. }


  175. /* 搜索所有標籤 
  176.  * 這個函數可以說是basic裏面的預處理  
  177.  * 我們搜索源代碼 找出裏面的標籤  將其存入標籤表
  178.  * 所謂標籤label 其實C語言也有 不過一般不常用 因爲label多半和goto一起出現的  而在結構化程序設計中 goto出現被人認爲是絕對不能的
  179.  * 不過內核中goto卻是常常出現
  180.  * 下面這個函數最大的困惑判斷標籤的特徵類型 我們設置爲數字  要知道這裏標籤我們都是設置爲數字的
  181.  * 但是如何把標籤與普通數值分開呢?
  182.  */
  183. void scan_labels()
  184. {
  185.     int addr;
  186.     char *temp;

  187.     label_init();  /* zero all labels */
  188.     temp = prog;  /* save poiter to top of program */

  189.     /* 如果源代碼中第一個是個數字的話  存入標籤表中  不過說實話   我沒理解這個有什麼意義*/
  190.     get_token();
  191.     if (token_type==NUMBER)  
  192.     {
  193.         strcpy (label_table[0].name,token);
  194.         label_table[0].p=prog;
  195.     }
  196.    
  197.     find_eol();     //提行
  198.     do  {
  199.         get_token();
  200.         if (token_type==NUMBER)     //如果是數字   這裏是一行開頭  開頭的數字不可能是一個數值  
  201.         {
  202.             addr = get_next_label(token);
  203.             if (addr==-1||addr==-2)  
  204.             {
  205.                 (addr==-1) ? serror(5):serror(6);
  206.             }
  207.             strcpy (label_table[addr].name,token);
  208.             label_table[addr].p = prog;  /* current point in program */
  209.         }
  210.         /* if not on a blank line , find next line */
  211.         if (tok!=EOL) find_eol();
  212.     } while (tok!=FINISHED);
  213.     prog = temp;  /* restore to original */
  214. }


  215. /* find the start of next line */
  216. void find_eol()
  217. {
  218.     while (*prog!='/n'&&*prog!='/0')  ++prog;
  219.     if (*prog)  prog++;
  220. }


  221. /* return index of next free posion in the label array
  222.       -1 is returned if the array is full.
  223.       -2 is returned when duplicate label is found.
  224. */
  225. get_next_label(char *s)
  226. {
  227.     register int t;

  228.     for (t=0;t<NUM_LAB;++t) {
  229.         if (label_table[t].name[0]==0)  return t;
  230.         if (!strcmp(label_table[t].name,s)) return -2;  /* dup */
  231.     }
  232.     return -1;
  233. }

  234. /* find location of given label. A null is returned if
  235.    label is not found; ohtherwise a pointer to the position
  236.    of the label is returned.
  237. */
  238. char *find_label(char *s)
  239. {
  240.     register int t;

  241.     for (t=0;t<NUM_LAB;++t)
  242.         if (!strcmp(label_table[t].name,s))  return label_table[t].p;
  243.     return '/0';  /* error condition */
  244. }


  245. /* execute a GOTO statement. 
  246.  * goto一般形式即是 goto label 
  247.  */
  248. void exec_goto()
  249. {
  250.     char *loc;

  251.     get_token();  /* 這裏獲取標號,即是標籤內容 */
  252.     
  253.     loc = find_label (token);  //標籤是爲跳轉所用,所以獲取標籤後我們馬上要想辦法得到標籤所代表地址
  254.     if (loc=='/0')
  255.         serror(7);  /* 出錯 */
  256.     else prog=loc;  /* 重新 設置prog指針  指出了下一個我們運行的地址  我們得完全聽他的*/
  257. }


  258. /* initialize the array that holds the labels.
  259.    by convention , a null label name indicates that
  260.    array posiiton is unused.
  261. */
  262. void label_init()
  263. {
  264.     register int t;

  265.     for (t=0;t<NUM_LAB;++t)  label_table[t].name[0]='/0';
  266. }


  267. /* execute an IF statement 
  268.  * 執行if語句
  269.  */
  270. void exec_if()
  271. {
  272.     int x,y,cond;
  273.     char op;
  274.     /* 這裏我們只是處理一個簡單的if  就是if (x operator y) */
  275.     get_exp(&x);  /* 獲取操作符左邊數值 */

  276.     get_token();  /* 獲取操作符  "比較符" */
  277.     if (!strcmp("<>",*token))   //這裏有點兒問題  一個字符串不可能跟一個字符比較吧
  278.     {
  279.         serror(0);  /* not a leagal oprator */
  280.         return;
  281.     }
  282.     op = *token;
  283.     get_exp(&y);  /* 操作符右邊  */

  284.     /* determine the outcome */
  285.     cond = 0;
  286.     switch(op)  {
  287.         case '<':
  288.             if (x<y) cond=1;
  289.             break;
  290.         case '>':
  291.             if (x>y) cond=1;
  292.             break;
  293.         case '==':      //這裏也是有點兒問題,op是字符類型 怎麼會可能會是'==',而且好笑的是basic沒有這個符號
  294.             if (x==y) cond=1;
  295.             break;
  296.     }
  297.     if (cond)  {  /* is true so process target of IF */
  298.         get_token();
  299.         if (tok != THEN)  {     //if 後面會連上then 所以有if沒then是錯誤的
  300.             serror(8);
  301.             return;
  302.         }  /* else program execution starts on next line */
  303.     }
  304.     else find_eol();  /* find start of next line */
  305. }


  306. /* execute a FOR loop
  307.  * for 循環  其主要格式 文章第一篇已經給出  
  308.  * for i=1 to 10
  309.  * next i
  310.  * 下面就引用此例了
  311.  */
  312. void exec_for()
  313. {
  314.     struct for_stack i;     //申請一個棧元素  到時候加入
  315.     int value;

  316.     get_token();  /*  獲取標號  這裏獲取到變量i */
  317.     if (!isalpha(*token))  //變量必定是字符型
  318.     {
  319.         serror(4);
  320.         return;
  321.     }

  322.     i.var = toupper(*token) - 'A';  /* 我們是把變量放在hash表中的  所以這裏來計算變量在hash表中位置   */

  323.     get_token();  /* 這裏得到了等號 */
  324.     if (*token!='=')  
  325.     {
  326.         serror(3);
  327.         return;
  328.     }
  329.     get_exp(&value);  /* 初始值  比如這裏是1 */

  330.     variables[i.var]=value;     //這裏把初始值放在變量數組中

  331.     get_token();

  332.     if (tok != TO) serror(9);  /* 讀取to單詞 */
  333.     get_exp(&i.target);  /* 取得最終要達到的數值  比如這裏是10 */

  334.     /* if loop can execute at least once, push into on stack */
  335.     if (value<=i.target)  {
  336.         i.loc = prog;       //記錄要執行的語句  這裏是for循環的裏面要執行的語句
  337.         fpush(i);       //壓棧
  338.     }
  339.     else  /* otherwise, skip loop code altogether */
  340.         while (tok!=NEXT)  get_token();     //每到next之前  都輸入for循環要執行的語句   所以一直執行
  341. }


  342. /* execute a NEXT statement */
  343. void next()
  344. {
  345.     struct for_stack i;

  346.     i = fpop();  /*read the loop info */

  347.     variables[i.var]++;  /* increment control variable */
  348.     if (variables[i.var]>i.target)  return;  /* all done */
  349.     fpush(i);   /* otherwise,return the info */
  350.     prog = i.loc;  /* loop */
  351. }


  352. /* push function for the FOR stack */
  353. void fpush(struct for_stack i)
  354. {
  355.     if (ftos>FOR_NEST)
  356.     serror(10);
  357.     fstack[ftos]=i;
  358.     ftos++;
  359. }


  360. struct for_stack fpop()
  361. {
  362.     ftos--;
  363.     if (ftos<0)  serror(11);
  364.     return (fstack[ftos]);
  365. }


  366. /* exec a simple form of BASIC INPUT command */
  367. void input()
  368. {
  369.     char str[80],var;
  370.     int i;

  371.     get_token();  /* see if prompt string id=s present */
  372.     if (token_type == QUOTE)  {
  373.         printf (token);  /* if so , print it and check for command */
  374.         get_token();
  375.         if (*token != ',')  serror(1);
  376.         get_token();
  377.     }
  378.     else printf ("? ");  /* otherwise, prompt with / */
  379.     var = toupper(*token) - 'A';  /* get the input var */

  380.     scanf ("%d",&i);  /* read input */
  381.     variables[var] = i;  /* store it */
  382. }


  383. /* execute a GOSUB command 
  384.  * 這個類似c語言中的函數調用 */
  385. void gosub()
  386. {
  387.     char *loc;

  388.     get_token();
  389.     /* find the label to call */
  390.     loc = find_label(token);
  391.     if (loc=='/0')
  392.         serror(7);  /* label not defined */
  393.     else  
  394.     {
  395.         gpush(prog);  /* 當前執行的地址壓棧 */
  396.         prog = loc;  /* 重新把要執行的地址賦值給prog */
  397.     }
  398. }


  399. /* return from GOSUB */
  400. void greturn()
  401. {
  402.     prog = gpop();
  403. }


  404. /* GOSUB stack push function */
  405. void gpush(char *s)
  406. {
  407.     gtos++;

  408.     if (gtos==SUB_NEST)  
  409.     {
  410.         serror(12);
  411.         return;
  412.     }

  413.     gstack[gtos] = s;
  414. }


  415. /* GOSUB stack pop function */
  416. char *gpop()
  417. {
  418.     if (gtos==0)  {
  419.         serror(13);
  420.         return 0;
  421.     }
  422.     return gstack[gtos--];
  423. }

  424. main (int argc,char *argv[])
  425. {
  426.     char in[80];
  427.     int answer;
  428.     char *p_buf;
  429.     char *t;

  430.     if (argc!=2)  {
  431.         printf ("usage: run <filename>/n");
  432.         exit (1);
  433.     }

  434.     /* allocate memory for the program */
  435.     if (!(p_buf=(char *)malloc(PROG_SIZE)))  {
  436.         printf ("allocation failure");
  437.         exit (1);
  438.     }

  439.     /* load the program to execute */
  440.     if (!load_program(p_buf,argv[1]))  exit(1);

  441.     if (setjmp(e_buf))  exit(1); /* initialize the long jump */

  442.     prog = p_buf;
  443.     scan_labels();  /*  搜索所有的標籤  */
  444.     ftos = 0;  /* 初始化棧  這個是爲for循環作準備的  */
  445.     gtos = 0;  /* 初始化棧  這個是爲gosub作準備的 */
  446.     do  {
  447.         token_type = get_token();
  448.         /* 如果當前是變量 */
  449.         if (token_type==VARIABLE)  {
  450.             putback();  /* 回退prog指針到變量前 */
  451.             assignment();  /* 賦值  */
  452.         }
  453.         else  /* 除了變量那就是關鍵字了  可能有同學會問  呃  那個比如一個數字怎麼沒考慮  請想想一個數字怎麼會單獨出現 */
  454.             switch (tok)  {
  455.                 case PRINT:
  456.                     print();
  457.                     break;
  458.                 case GOTO:
  459.                     exec_goto();
  460.                     break;
  461.                 case IF:
  462.                     exec_if();
  463.                     break;
  464.                 case FOR:
  465.                     exec_for();
  466.                     break;
  467.                 case NEXT:
  468.                     next();
  469.                     break;
  470.                 case INPUT:
  471.                     input();
  472.                     break;
  473.                 case GOSUB:
  474.                     gosub();
  475.                     break;
  476.                 case RETURN:
  477.                     greturn();
  478.                     break;
  479.                 case END:
  480.                     exit(0);
  481.             }
  482.     }while (tok != FINISHED);
  483. }






刺蝟@littlehedgehog
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章