⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 scan.c

📁 本程序是 《编译原理与实践》一书中2.35 习题的解答。主要用到了 yyless()和 start condition 来解决。 作者:xiangyazi24@163.com NJU
💻 C
字号:
/* File: scan.c
   The scanner implementation for the TINY compiler
*/

#include "globals.h"
#include "util.h"
#include "scan.h"

/* states in scanner DFA */
typedef enum
{ START, INASSIGN, INCOMMENT, INNUM, INID, DONE }StateType;

/* lexeme of identifier or reserved word */
char tokenString[MAXTOKENLEN+1];

/* BUFLEN = length of the input buffer for source code lines */
//#define BUFLEN 256

//static char lineBuf[BUFLEN];  /* holds the current line */
//static int linepos = 0;  /* current position in lineBuf */
//static int bufsize = 0;  /* current size of the buffer string */

static int lastPos = 0;
static int first = TRUE;

/* getNextChar gets the next non-blank character from lineBuf, reading in a new 
   line if lineBuf is exhausted */
/*
static char getNextChar(void)
{
       if(!(linepos < bufsize))
       {
         lineno++;
         if(fgets(lineBuf, BUFLEN-1, source))
         {
           if(EchoSource) fprintf(listing,"%4d: %s",lineno, lineBuf);
           bufsize = strlen(lineBuf);
           linepos=0;
           return lineBuf[linepos++];
         }
         else return EOF;
       }
       else return lineBuf[linepos++];
}
*/
static void printLine(void)
{
       char c;
       int i;
       lineno++;
       fprintf(listing,"%d: ",lineno);
       do{
           c=getc(source);
           fprintf(listing,"%c", c);
         }while(c!='\n'&&c!=EOF);
       rewind(source);
       for(i=0;i<lastPos;i++)
         getc(source);
}

static int getNextChar(void)
{
	   char c;
       if(first){
         printLine();
         first=FALSE;
       }
    
       c=getc(source);
       lastPos++;
       if(c){
         if(c=='\n')
           printLine();
         return c;
       }
       else
         return EOF;
}

/* ungetNextChar backtracks one character in lineBuf */
static void ungetNextChar(int c)
{ ungetc(c, source);}

/* look table of reserved words */
static struct
{
  char* str;
  TokenType tok;
}reservedWords[MAXRESERVED]
={{"if",IF},{"then",THEN},{"else",ELSE},{"end",END},{"repeat",REPEAT},
  {"until",UNTIL},{"read",READ},{"write",WRITE}};
  
/* look up an identifier to see if it is a reserved word
   use linear search
 */
 static TokenType reservedLookup (char * s)
 {
   int i;
   for( i = 0; i < MAXRESERVED; i++)
   {
     if(!strcmp(s,reservedWords[i].str))
       return reservedWords[i].tok;
   }
   return ID;
 }
 
 

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -