home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / pyth_os2.zip / python-1.0.2 / Parser / tokenizer.c < prev    next >
C/C++ Source or Header  |  1994-04-28  |  15KB  |  698 lines

  1. /***********************************************************
  2. Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
  3. Amsterdam, The Netherlands.
  4.  
  5.                         All Rights Reserved
  6.  
  7. Permission to use, copy, modify, and distribute this software and its 
  8. documentation for any purpose and without fee is hereby granted, 
  9. provided that the above copyright notice appear in all copies and that
  10. both that copyright notice and this permission notice appear in 
  11. supporting documentation, and that the names of Stichting Mathematisch
  12. Centrum or CWI not be used in advertising or publicity pertaining to
  13. distribution of the software without specific, written prior permission.
  14.  
  15. STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
  16. THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  17. FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
  18. FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  19. WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  20. ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  21. OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  22.  
  23. ******************************************************************/
  24.  
  25. /* Tokenizer implementation */
  26.  
  27. #include "pgenheaders.h"
  28.  
  29. #include <ctype.h>
  30.  
  31. #include "tokenizer.h"
  32. #include "errcode.h"
  33.  
  34. extern char *my_readline PROTO((char *));
  35. /* Return malloc'ed string including trailing \n;
  36.    empty malloc'ed string for EOF;
  37.    NULL if interrupted */
  38.  
  39. /* Don't ever change this -- it would break the portability of Python code */
  40. #define TABSIZE 8
  41.  
  42. /* Forward */
  43. static struct tok_state *tok_new PROTO((void));
  44. static int tok_nextc PROTO((struct tok_state *tok));
  45. static void tok_backup PROTO((struct tok_state *tok, int c));
  46.  
  47. /* Token names */
  48.  
  49. char *tok_name[] = {
  50.     "ENDMARKER",
  51.     "NAME",
  52.     "NUMBER",
  53.     "STRING",
  54.     "NEWLINE",
  55.     "INDENT",
  56.     "DEDENT",
  57.     "LPAR",
  58.     "RPAR",
  59.     "LSQB",
  60.     "RSQB",
  61.     "COLON",
  62.     "COMMA",
  63.     "SEMI",
  64.     "PLUS",
  65.     "MINUS",
  66.     "STAR",
  67.     "SLASH",
  68.     "VBAR",
  69.     "AMPER",
  70.     "LESS",
  71.     "GREATER",
  72.     "EQUAL",
  73.     "DOT",
  74.     "PERCENT",
  75.     "BACKQUOTE",
  76.     "LBRACE",
  77.     "RBRACE",
  78.     "EQEQUAL",
  79.     "NOTEQUAL",
  80.     "LESSEQUAL",
  81.     "GREATEREQUAL",
  82.     "TILDE",
  83.     "CIRCUMFLEX",
  84.     "LEFTSHIFT",
  85.     "RIGHTSHIFT",
  86.     /* This table must match the #defines in token.h! */
  87.     "OP",
  88.     "<ERRORTOKEN>",
  89.     "<N_TOKENS>"
  90. };
  91.  
  92.  
  93. /* Create and initialize a new tok_state structure */
  94.  
  95. static struct tok_state *
  96. tok_new()
  97. {
  98.     struct tok_state *tok = NEW(struct tok_state, 1);
  99.     if (tok == NULL)
  100.         return NULL;
  101.     tok->buf = tok->cur = tok->end = tok->inp = tok->start = NULL;
  102.     tok->done = E_OK;
  103.     tok->fp = NULL;
  104.     tok->tabsize = TABSIZE;
  105.     tok->indent = 0;
  106.     tok->indstack[0] = 0;
  107.     tok->atbol = 1;
  108.     tok->pendin = 0;
  109.     tok->prompt = tok->nextprompt = NULL;
  110.     tok->lineno = 0;
  111.     tok->level = 0;
  112.     return tok;
  113. }
  114.  
  115.  
  116. /* Set up tokenizer for string */
  117.  
  118. struct tok_state *
  119. tok_setups(str)
  120.     char *str;
  121. {
  122.     struct tok_state *tok = tok_new();
  123.     if (tok == NULL)
  124.         return NULL;
  125.     tok->buf = tok->cur = str;
  126.     tok->end = tok->inp = strchr(str, '\0');
  127.     return tok;
  128. }
  129.  
  130.  
  131. /* Set up tokenizer for file */
  132.  
  133. struct tok_state *
  134. tok_setupf(fp, ps1, ps2)
  135.     FILE *fp;
  136.     char *ps1, *ps2;
  137. {
  138.     struct tok_state *tok = tok_new();
  139.     if (tok == NULL)
  140.         return NULL;
  141.     if ((tok->buf = NEW(char, BUFSIZ)) == NULL) {
  142.         DEL(tok);
  143.         return NULL;
  144.     }
  145.     tok->cur = tok->inp = tok->buf;
  146.     tok->end = tok->buf + BUFSIZ;
  147.     tok->fp = fp;
  148.     tok->prompt = ps1;
  149.     tok->nextprompt = ps2;
  150.     return tok;
  151. }
  152.  
  153.  
  154. /* Free a tok_state structure */
  155.  
  156. void
  157. tok_free(tok)
  158.     struct tok_state *tok;
  159. {
  160.     if (tok->fp != NULL && tok->buf != NULL)
  161.         DEL(tok->buf);
  162.     DEL(tok);
  163. }
  164.  
  165.  
  166. /* Get next char, updating state; error code goes into tok->done */
  167.  
  168. static int
  169. tok_nextc(tok)
  170.     register struct tok_state *tok;
  171. {
  172.     for (;;) {
  173.         if (tok->cur != tok->inp)
  174.             return *tok->cur++; /* Fast path */
  175.         if (tok->done != E_OK)
  176.             return EOF;
  177.         if (tok->fp == NULL) {
  178.             tok->done = E_EOF;
  179.             return EOF;
  180.         }
  181.         if (tok->prompt != NULL) {
  182.             char *new = my_readline(tok->prompt);
  183.             if (tok->nextprompt != NULL)
  184.                 tok->prompt = tok->nextprompt;
  185.             if (new == NULL)
  186.                 tok->done = E_INTR;
  187.             else if (*new == '\0') {
  188.                 free(new);
  189.                 tok->done = E_EOF;
  190.             }
  191.             else if (tok->start != NULL) {
  192.                 int start = tok->start - tok->buf;
  193.                 int oldlen = tok->cur - tok->buf;
  194.                 int newlen = oldlen + strlen(new);
  195.                 char *buf = realloc(tok->buf, newlen+1);
  196.                 tok->lineno++;
  197.                 if (buf == NULL) {
  198.                     free(tok->buf);
  199.                     free(new);
  200.                     tok->done = E_NOMEM;
  201.                     return EOF;
  202.                 }
  203.                 tok->buf = buf;
  204.                 tok->cur = tok->buf + oldlen;
  205.                 strcpy(tok->buf + oldlen, new);
  206.                 free(new);
  207.                 tok->inp = tok->buf + newlen;
  208.                 tok->end = tok->inp + 1;
  209.                 tok->start = tok->buf + start;
  210.             }
  211.             else {
  212.                 tok->lineno++;
  213.                 if (tok->buf != NULL)
  214.                     free(tok->buf);
  215.                 tok->buf = new;
  216.                 tok->cur = tok->buf;
  217.                 tok->inp = strchr(tok->buf, '\0');
  218.                 tok->end = tok->inp + 1;
  219.             }
  220.         }
  221.         else {
  222.             int done = 0;
  223.             int cur = 0;
  224.             if (tok->start == NULL) {
  225.                 if (tok->buf == NULL) {
  226.                     tok->buf = NEW(char, BUFSIZ);
  227.                     if (tok->buf == NULL) {
  228.                         tok->done = E_NOMEM;
  229.                         return EOF;
  230.                     }
  231.                     tok->end = tok->buf + BUFSIZ;
  232.                 }
  233.                 if (fgets(tok->buf, (int)(tok->end - tok->buf),
  234.                       tok->fp) == NULL) {
  235.                     tok->done = E_EOF;
  236.                     done = 1;
  237.                 }
  238.                 else {
  239.                     tok->done = E_OK;
  240.                     tok->inp = strchr(tok->buf, '\0');
  241.                     done = tok->inp[-1] == '\n';
  242.                 }
  243.             }
  244.             else {
  245.                 cur = tok->cur - tok->buf;
  246.                 tok->done = E_OK;
  247.             }
  248.             tok->lineno++;
  249.             /* Read until '\n' or EOF */
  250.             while (!done) {
  251.                 int curstart = tok->start == NULL ? -1 :
  252.                            tok->start - tok->buf;
  253.                 int curvalid = tok->inp - tok->buf;
  254.                 int cursize = tok->end - tok->buf;
  255.                 int newsize = cursize + BUFSIZ;
  256.                 char *newbuf = tok->buf;
  257.                 RESIZE(newbuf, char, newsize);
  258.                 if (newbuf == NULL) {
  259.                     tok->done = E_NOMEM;
  260.                     tok->cur = tok->inp;
  261.                     return EOF;
  262.                 }
  263.                 tok->buf = newbuf;
  264.                 tok->inp = tok->buf + curvalid;
  265.                 tok->end = tok->buf + newsize;
  266.                 tok->start = curstart < 0 ? NULL :
  267.                          tok->buf + curstart;
  268.                 if (fgets(tok->inp,
  269.                            (int)(tok->end - tok->inp),
  270.                            tok->fp) == NULL)
  271.                     break;
  272.                 tok->inp = strchr(tok->inp, '\0');
  273.                 done = tok->inp[-1] == '\n';
  274.             }
  275.             tok->cur = tok->buf + cur;
  276.         }
  277.         if (tok->done != E_OK) {
  278.             if (tok->prompt != NULL)
  279.                 fprintf(stderr, "\n");
  280.             tok->cur = tok->inp;
  281.             return EOF;
  282.         }
  283.     }
  284.     /*NOTREACHED*/
  285. }
  286.  
  287.  
  288. /* Back-up one character */
  289.  
  290. static void
  291. tok_backup(tok, c)
  292.     register struct tok_state *tok;
  293.     register int c;
  294. {
  295.     if (c != EOF) {
  296.         if (--tok->cur < tok->buf) {
  297.             fprintf(stderr, "tok_backup: begin of buffer\n");
  298.             abort();
  299.         }
  300.         if (*tok->cur != c)
  301.             *tok->cur = c;
  302.     }
  303. }
  304.  
  305.  
  306. /* Return the token corresponding to a single character */
  307.  
  308. int
  309. tok_1char(c)
  310.     int c;
  311. {
  312.     switch (c) {
  313.     case '(':    return LPAR;
  314.     case ')':    return RPAR;
  315.     case '[':    return LSQB;
  316.     case ']':    return RSQB;
  317.     case ':':    return COLON;
  318.     case ',':    return COMMA;
  319.     case ';':    return SEMI;
  320.     case '+':    return PLUS;
  321.     case '-':    return MINUS;
  322.     case '*':    return STAR;
  323.     case '/':    return SLASH;
  324.     case '|':    return VBAR;
  325.     case '&':    return AMPER;
  326.     case '<':    return LESS;
  327.     case '>':    return GREATER;
  328.     case '=':    return EQUAL;
  329.     case '.':    return DOT;
  330.     case '%':    return PERCENT;
  331.     case '`':    return BACKQUOTE;
  332.     case '{':    return LBRACE;
  333.     case '}':    return RBRACE;
  334.     case '^':    return CIRCUMFLEX;
  335.     case '~':    return TILDE;
  336.     default:    return OP;
  337.     }
  338. }
  339.  
  340.  
  341. int
  342. tok_2char(c1, c2)
  343.     int c1, c2;
  344. {
  345.     switch (c1) {
  346.     case '=':
  347.         switch (c2) {
  348.         case '=':    return EQEQUAL;
  349.         }
  350.         break;
  351.     case '!':
  352.         switch (c2) {
  353.         case '=':    return NOTEQUAL;
  354.         }
  355.         break;
  356.     case '<':
  357.         switch (c2) {
  358.         case '>':    return NOTEQUAL;
  359.         case '=':    return LESSEQUAL;
  360.         case '<':    return LEFTSHIFT;
  361.         }
  362.         break;
  363.     case '>':
  364.         switch (c2) {
  365.         case '=':    return GREATEREQUAL;
  366.         case '>':    return RIGHTSHIFT;
  367.         }
  368.         break;
  369.     }
  370.     return OP;
  371. }
  372.  
  373.  
  374. /* Get next token, after space stripping etc. */
  375.  
  376. int
  377. tok_get(tok, p_start, p_end)
  378.     register struct tok_state *tok; /* In/out: tokenizer state */
  379.     char **p_start, **p_end; /* Out: point to start/end of token */
  380. {
  381.     register int c;
  382.     int blankline;
  383.  
  384.     *p_start = *p_end = NULL;
  385.   nextline:
  386.     tok->start = NULL;
  387.     blankline = 0;
  388.  
  389.     /* Get indentation level */
  390.     if (tok->atbol) {
  391.         register int col = 0;
  392.         tok->atbol = 0;
  393.         for (;;) {
  394.             c = tok_nextc(tok);
  395.             if (c == ' ')
  396.                 col++;
  397.             else if (c == '\t')
  398.                 col = (col/tok->tabsize + 1) * tok->tabsize;
  399.             else
  400.                 break;
  401.         }
  402.         tok_backup(tok, c);
  403.         if (c == '#' || c == '\n') {
  404.             /* Lines with only whitespace and/or comments
  405.                shouldn't affect the indentation and are
  406.                not passed to the parser as NEWLINE tokens,
  407.                except *totally* empty lines in interactive
  408.                mode, which signal the end of a command group. */
  409.             if (col == 0 && c == '\n' && tok->prompt != NULL)
  410.                 blankline = 0; /* Let it through */
  411.             else
  412.                 blankline = 1; /* Ignore completely */
  413.             /* We can't jump back right here since we still
  414.                may need to skip to the end of a comment */
  415.         }
  416.         if (!blankline && tok->level == 0) {
  417.             if (col == tok->indstack[tok->indent]) {
  418.                 /* No change */
  419.             }
  420.             else if (col > tok->indstack[tok->indent]) {
  421.                 /* Indent -- always one */
  422.                 if (tok->indent+1 >= MAXINDENT) {
  423.                     fprintf(stderr, "excessive indent\n");
  424.                     tok->done = E_TOKEN;
  425.                     tok->cur = tok->inp;
  426.                     return ERRORTOKEN;
  427.                 }
  428.                 tok->pendin++;
  429.                 tok->indstack[++tok->indent] = col;
  430.             }
  431.             else /* col < tok->indstack[tok->indent] */ {
  432.                 /* Dedent -- any number, must be consistent */
  433.                 while (tok->indent > 0 &&
  434.                     col < tok->indstack[tok->indent]) {
  435.                     tok->indent--;
  436.                     tok->pendin--;
  437.                 }
  438.                 if (col != tok->indstack[tok->indent]) {
  439.                     fprintf(stderr, "inconsistent dedent\n");
  440.                     tok->done = E_TOKEN;
  441.                     tok->cur = tok->inp;
  442.                     return ERRORTOKEN;
  443.                 }
  444.             }
  445.         }
  446.     }
  447.     
  448.     tok->start = tok->cur;
  449.     
  450.     /* Return pending indents/dedents */
  451.     if (tok->pendin != 0) {
  452.         if (tok->pendin < 0) {
  453.             tok->pendin++;
  454.             return DEDENT;
  455.         }
  456.         else {
  457.             tok->pendin--;
  458.             return INDENT;
  459.         }
  460.     }
  461.     
  462.  again:
  463.     tok->start = NULL;
  464.     /* Skip spaces */
  465.     do {
  466.         c = tok_nextc(tok);
  467.     } while (c == ' ' || c == '\t');
  468.     
  469.     /* Set start of current token */
  470.     tok->start = tok->cur - 1;
  471.     
  472.     /* Skip comment */
  473.     if (c == '#') {
  474.         /* Hack to allow overriding the tabsize in the file.
  475.            This is also recognized by vi, when it occurs near the
  476.            beginning or end of the file.  (Will vi never die...?)
  477.            For Python it must be at the beginning of the file! */
  478.         int x;
  479.         /* XXX The cast to (unsigned char *) is needed by THINK C 3.0 */
  480.         if (sscanf(/*(unsigned char *)*/tok->cur,
  481.                 " vi:set tabsize=%d:", &x) == 1 &&
  482.                         x >= 1 && x <= 40) {
  483.             /* fprintf(stderr, "# vi:set tabsize=%d:\n", x); */
  484.             tok->tabsize = x;
  485.         }
  486.         do {
  487.             c = tok_nextc(tok);
  488.         } while (c != EOF && c != '\n');
  489.     }
  490.     
  491.     /* Check for EOF and errors now */
  492.     if (c == EOF) {
  493.         return tok->done == E_EOF ? ENDMARKER : ERRORTOKEN;
  494.     }
  495.     
  496.     /* Identifier (most frequent token!) */
  497.     if (isalpha(c) || c == '_') {
  498.         do {
  499.             c = tok_nextc(tok);
  500.         } while (isalnum(c) || c == '_');
  501.         tok_backup(tok, c);
  502.         *p_start = tok->start;
  503.         *p_end = tok->cur;
  504.         return NAME;
  505.     }
  506.     
  507.     /* Newline */
  508.     if (c == '\n') {
  509.         tok->atbol = 1;
  510.         if (blankline || tok->level > 0)
  511.             goto nextline;
  512.         *p_start = tok->start;
  513.         *p_end = tok->cur - 1; /* Leave '\n' out of the string */
  514.         return NEWLINE;
  515.     }
  516.     
  517.     /* Period or number starting with period? */
  518.     if (c == '.') {
  519.         c = tok_nextc(tok);
  520.         if (isdigit(c)) {
  521.             goto fraction;
  522.         }
  523.         else {
  524.             tok_backup(tok, c);
  525.             *p_start = tok->start;
  526.             *p_end = tok->cur;
  527.             return DOT;
  528.         }
  529.     }
  530.     
  531.     /* Number */
  532.     if (isdigit(c)) {
  533.         if (c == '0') {
  534.             /* Hex or octal */
  535.             c = tok_nextc(tok);
  536.             if (c == '.')
  537.                 goto fraction;
  538.             if (c == 'x' || c == 'X') {
  539.                 /* Hex */
  540.                 do {
  541.                     c = tok_nextc(tok);
  542.                 } while (isxdigit(c));
  543.             }
  544.             else {
  545.                 /* XXX This is broken!  E.g.,
  546.                    09.9 should be accepted as float! */
  547.                 /* Octal; c is first char of it */
  548.                 /* There's no 'isoctdigit' macro, sigh */
  549.                 while ('0' <= c && c < '8') {
  550.                     c = tok_nextc(tok);
  551.                 }
  552.             }
  553.             if (c == 'l' || c == 'L')
  554.                 c = tok_nextc(tok);
  555.         }
  556.         else {
  557.             /* Decimal */
  558.             do {
  559.                 c = tok_nextc(tok);
  560.             } while (isdigit(c));
  561.             if (c == 'l' || c == 'L')
  562.                 c = tok_nextc(tok);
  563.             else {
  564.                 /* Accept floating point numbers.
  565.                    XXX This accepts incomplete things like
  566.                    XXX 12e or 1e+; worry run-time */
  567.                 if (c == '.') {
  568.         fraction:
  569.                     /* Fraction */
  570.                     do {
  571.                         c = tok_nextc(tok);
  572.                     } while (isdigit(c));
  573.                 }
  574.                 if (c == 'e' || c == 'E') {
  575.                     /* Exponent part */
  576.                     c = tok_nextc(tok);
  577.                     if (c == '+' || c == '-')
  578.                         c = tok_nextc(tok);
  579.                     while (isdigit(c)) {
  580.                         c = tok_nextc(tok);
  581.                     }
  582.                 }
  583.             }
  584.         }
  585.         tok_backup(tok, c);
  586.         *p_start = tok->start;
  587.         *p_end = tok->cur;
  588.         return NUMBER;
  589.     }
  590.     
  591.     /* String */
  592.     if (c == '\'' || c == '"') {
  593.         int quote = c;
  594.         int triple = 0;
  595.         int tripcount = 0;
  596.         for (;;) {
  597.             c = tok_nextc(tok);
  598.             if (c == '\n') {
  599.                 if (!triple) {
  600.                     tok->done = E_TOKEN;
  601.                     tok->cur = tok->inp;
  602.                     return ERRORTOKEN;
  603.                 }
  604.             }
  605.             else if (c == EOF) {
  606.                 tok->done = E_TOKEN;
  607.                 tok->cur = tok->inp;
  608.                 return ERRORTOKEN;
  609.             }
  610.             else if (c == quote) {
  611.                 tripcount++;
  612.                 if (tok->cur == tok->start+2) {
  613.                     c = tok_nextc(tok);
  614.                     if (c == quote) {
  615.                         triple = 1;
  616.                         tripcount = 0;
  617.                         continue;
  618.                     }
  619.                     tok_backup(tok, c);
  620.                 }
  621.                 if (!triple || tripcount == 3)
  622.                     break;
  623.             }
  624.             else if (c == '\\') {
  625.                 tripcount = 0;
  626.                 c = tok_nextc(tok);
  627.                 if (c == EOF) {
  628.                     tok->done = E_TOKEN;
  629.                     tok->cur = tok->inp;
  630.                     return ERRORTOKEN;
  631.                 }
  632.             }
  633.             else
  634.                 tripcount = 0;
  635.         }
  636.         *p_start = tok->start;
  637.         *p_end = tok->cur;
  638.         return STRING;
  639.     }
  640.     
  641.     /* Line continuation */
  642.     if (c == '\\') {
  643.         c = tok_nextc(tok);
  644.         if (c != '\n') {
  645.             tok->done = E_TOKEN;
  646.             tok->cur = tok->inp;
  647.             return ERRORTOKEN;
  648.         }
  649.         goto again; /* Read next line */
  650.     }
  651.     
  652.     /* Check for two-character token */
  653.     {
  654.         int c2 = tok_nextc(tok);
  655.         int token = tok_2char(c, c2);
  656.         if (token != OP) {
  657.             *p_start = tok->start;
  658.             *p_end = tok->cur;
  659.             return token;
  660.         }
  661.         tok_backup(tok, c2);
  662.     }
  663.     
  664.     /* Keep track of parentheses nesting level */
  665.     switch (c) {
  666.     case '(':
  667.     case '[':
  668.     case '{':
  669.         tok->level++;
  670.         break;
  671.     case ')':
  672.     case ']':
  673.     case '}':
  674.         tok->level--;
  675.         break;
  676.     }
  677.     
  678.     /* Punctuation character */
  679.     *p_start = tok->start;
  680.     *p_end = tok->cur;
  681.     return tok_1char(c);
  682. }
  683.  
  684.  
  685. #ifdef DEBUG
  686.  
  687. void
  688. tok_dump(type, start, end)
  689.     int type;
  690.     char *start, *end;
  691. {
  692.     printf("%s", tok_name[type]);
  693.     if (type == NAME || type == NUMBER || type == STRING || type == OP)
  694.         printf("(%.*s)", (int)(end - start), start);
  695. }
  696.  
  697. #endif
  698.