· KLDP.org · KLDP.net · KLDP Wiki · KLDP BBS ·
CUP Manual

CUP User's Manual

Scott E. Hudson

Graphics Visualization and Usability Center

Georgia Institute of Technology

Modified by Frank Flannery, C. Scott Ananian, Dan Wang with advice from Andrew W. Appel

Last updated July 1999 (v0.10j)

¹ø¿ª½ÃÀÛ;; : ÀÌö±â (lacovnk@freechal.com) ¿ø¹® : [http]http://www.cs.princeton.edu/~appel/modern/java/CUP/manual.html

Chapter 1 ¹ø¿ª : Á¶¼ºÀç (jachin@hanafos.com) - ¾Ö¸ÅÇÑ ¹®ÀåÀÌ ÀÖ´Ù¸é ¸ÞÀϺ¸³»ÁÖ¼¼¿ä. (Á¹¸±¶§ Çسö¼­...)


2. i. About CUP Version 0.10

CUP Version 0.10´Â Ver. 0.9 º¸´Ù ¿©·¯°¡Áö ¸¹Àº ½Ãµµ¿Í ¿ä¼ÒµéÀ» Ãß°¡Çß½À´Ï´Ù. À̹ø ¹öÀüÀº YACC¿¡ Á» ´õ °¡±õµµ·Ï ¸¸µé¾ú½À´Ï´Ù. ±× ¶§¹®¿¡ 0.9 ¹öÀüÀÇ CUP Æļ­¸¦ ÀÌ¿ëÇÑ specification°ú´Â ȣȯµÇÁö ¾Ê½À´Ï´Ù. »õ·Î¿î specificationÀ» ÀÛ¼ºÇϱâ À§Çؼ­´Â »õ ¸Þ´º¾óÀÇ Appendix C¸¦ ÀÐÀ¸¼Å¾ß ÇÕ´Ï´Ù. ÇÏÁö¸¸ »õ ¹öÀüÀº »ç¿ëÀÚ¿¡°Ô ´õ °­·ÂÇÑ ¼º´É°ú ¿É¼ÇÀ» Á¦°øÇϸç, ´õ ½±°Ô parser specificationÀ» ÀÛ¼ºÇÏ½Ç ¼ö ÀÖ½À´Ï´Ù.

3. 1. Introduction and Example

ÀÌ ¸Þ´º¾óÀº ÀÚ¹Ù¿¡ ±âÃÊÇÑ À¯¿ëÇÑ ParserÀÎ CUP¿¡ ´ëÇÑ ±âº»ÀûÀÎ ÀÛµ¿°ú »ç¿ë¹æ¹ýÀ» ±â¼úÇÕ´Ï´Ù. CUP´Â °£´ÜÇÑ specificationÀ¸·ÎºÎÅÍ LALR Æļ­¸¦ »ý¼ºÇÏ´Â ½Ã½ºÅÛÀÔ´Ï´Ù. ÀÌ ½Ã½ºÅÛÀº ³Î¸® ¾²ÀÌ°í ÀÖ´Â YACC¿Í °°Àº ±ÔÄ¢À» Á¦°øÇϸç, ½ÇÁ¦·Î YACCÀÇ ´ëºÎºÐÀÇ ¿ä¼ÒµéÀ» Á¦°øÇÕ´Ï´Ù.ÇÏÁö¸¸ CUP´Â ÀÚ¹Ù·Î ÀÛ¼ºµÇ¾úÀ¸¸ç, ÀÚ¹Ù Äڵ带 Æ÷ÇÔÇÑ specificationÀ» »ç¿ëÇϸç, ÀÚ¹Ù·Î ÇÕ¼ºÇÑ Æļ­¸¦ »ý¼ºÇÕ´Ï´Ù.

ºñ·Ï ÀÌ ¸Þ´º¾óÀÌ CUP ½Ã½ºÅÛÀÇ ¸ðµç ¸éÀ» ´Ù·é´Ù°í Çصµ, ±×°ÍÀº »ó´ëÀûÀÎ °ÍÀ̸ç, LR Parsing¿¡ ´ëÇÑ ÃÖ¼ÒÇÑÀÇ Áö½ÄÀ» ´ç½ÅÀÌ °®°í ÀÖ´Ù°í °¡Á¤ÇÕ´Ï´Ù. YACCÀÇ »ç¿ë °æÇèÀº ¾î¶»°Ô CUP specificationÀ» ¿î¿µÇÏ´ÂÁö¿¡ ´ëÇØ ¸Å¿ì µµ¿òÀÌ µË´Ï´Ù. ¸¹Àº ¼öÀÇ compiler ±¸Á¶ ±³Á¦´Â ÀÌ ºÎºÐÀ» ´Ù·ç°í ÀÖÀ¸¸ç, °£´ÜÇÑ ¿¹Á¦·Î¼­ (CUP¿Í ¸Å¿ì Èí»çÇÑ) YACC¿¡ ´ëÇØ ³íÀÇÇÏ°ï ÇÕ´Ï´Ù.

CUP¸¦ »ç¿ëÇÑ´Ù´Â °ÍÀº ±¸¹®ºÐ¼®±â(Scanner)°¡ ÀνÄÇÒ ¼ö ÀÖ´Â ÀÛÀº ´ÜÀ§ÀÇ ÅäÅ«µé(keywords³ª ¼ýÀÚ, Ư¼öÇÑ ±âÈ£µé)°ú ÇÔ²², ÅäÅ«¿¡ ´ëÇÑ Æļ­ÀÇ ¹®¹ý¿¡ ±âÃÊÇÑ °£´ÜÇÑ specificationÀ» ¸¸µå´Â °ÍÀ» Æ÷ÇÔÇÕ´Ï´Ù.

°£´ÜÇÑ ¿¹¸¦ µé¾î, Á¤¼ö¸¦ ´Ù·ç´Â °£´ÜÇÑ ¼öÇÐÀû Ç¥ÇöÀ» ½ÃÇèÇϱâ À§ÇÑ ½Ã½ºÅÛÀ» »ý°¢Çغ¾½Ã´Ù. ÀÌ ½Ã½ºÅÛÀº (°¢°¢ ¼¼¹ÌÄÝ·ÐÀ¸·Î ³¡³ª´Â) Ç¥ÁØÀÔ·ÂÀ¸·ÎºÎÅÍ Ç¥ÇöµéÀ» ÀоîµéÀÌ°í ±×°ÍµéÀ» ½ÃÇèÇϸç, Ç¥ÁØÃâ·ÂÀ¸·Î °á°ú¸¦ Ãâ·ÂÇÒ °ÍÀÔ´Ï´Ù. ÀÌ·± ½Ã½ºÅÛ¿¡ ´ëÇÑ ÀÔ·ÂÀÇ ¹®¹ýÀº ´ÙÀ½°ú °°À» °ÍÀÔ´Ï´Ù.

  expr_list ::= expr_list expr_part | expr_part
  expr_part ::= expr ';'
  expr      ::= expr '+' expr | expr '-' expr | expr '*' expr
              | expr '/' expr | expr '%' expr | '(' expr ')'
              | '-' expr | number


ÀÌ ¹®¹ý¿¡ ±âÃÊÇÑ Æļ­¸¦ ±¸Ã¼È­Çϱâ À§ÇØ, ¿ì¸®ÀÇ Ã¹¹ø° ¸ñÇ¥´Â ÀԷ¿¡ ³ªÅ¸³¯ terminal symbolÀÇ ¹­À½°ú non-terminal symbolÀÇ ¹­À½À» ºÐº°ÇÏ°í, À̸§Áþ´Â °ÍÀÔ´Ï´Ù.ÀÌ ¿¹¿¡¼­ non-terminal symbolÀ̶ó´Â °ÍµéÀº ´ÙÀ½°ú °°½À´Ï´Ù.

  expr_list, expr_part  and  expr .


¿ì¸®°¡ ¼±ÅÃÇÒ terminal À̸§µé¿¡ ´ëÇؼ­´Â ´ÙÀ½°ú °°½À´Ï´Ù.:

  SEMI, PLUS, MINUS, TIMES, DIVIDE, MOD, NUMBER, LPAREN,
and RPAREN


°æÇèÀ» °®Ãá »ç¿ëÀÚ´Â ¹®¹ý»ó¿¡ ÀÖ´Â ¹®Á¦¸¦ ÁÖÀÇÇÒ °ÍÀÔ´Ï´Ù. ±× ¹®Á¦¶õ ¾Ö¸Å¸ðÈ£ÇÔÀÔ´Ï´Ù. ¸ðÈ£ÇÑ ¹®¹ýÀº ÇÑ ÀԷ¿¡ ´ëÇØ µÎ °¡Áö Ãâ·Â°á°ú¸¦ ¾òÀ» ¼ö ÀÖ´Â µÎ °¡Áö Çؼ®¹æ¹ýÀÌ °øÁ¸ÇÏ´Â ¹®¹ýÀÔ´Ï´Ù. ¿¹¸¦ µé¾î, ´ÙÀ½ÀÇ ¹®¹ýÀ» °®°í ÁÖ¾îÁø ÀÔ·ÂÀ» Àü´ÞÇØ º¸½Ê½Ã¿À.

3 + 4 * 6


À§ÀÇ ¹®¹ýÀº 3 + 4 ¸¦ ¸ÕÀú ½ÃµµÇÏ¿© 7 * 6 ÀÇ ¿¬»êÀ» ÇÒ ¼öµµ ÀÖ°í, 4 * 6 À» ¸ÕÀú ¿¬»êÇÏ¿© 3À» ´õÇÒ ¼öµµ ÀÖ½À´Ï´Ù. CUPÀÇ ¿¹Àü¹öÀüÀº »ç¿ëÀÚ°¡ ¸ðÈ£ÇÏÁö ¾ÊÀº ¹®¹ýÀ» ¾²µµ·Ï °­¿äÇßÁö¸¸, Áö±ÝÀº terminalµé¿¡ ´ëÇØ ¿ì¼±¼øÀ§¿Í Á¶ÇÕÀ» ¸í¼¼Çϵµ·Ï »ç¿ëÀÚ¿¡°Ô Çã¿ëÇÏ´Â °³³äÀÔ´Ï´Ù. Áï, ¸ðÈ£ÇÑ ¹®¹ýÀ» »ç¿ëÇÒ ¼ö ÀÖÀ¸¸ç, ÈÄ¿¡ ±×°Í¿¡ ´ëÇÑ ¿ì¼±¼øÀ§¿Í Á¶ÇÕÀ» ±â¼úÇÔÀ» ¶æÇÕ´Ï´Ù. ÀÌ°Í¿¡ ´ëÇؼ± ÈÄ¿¡ ´õ ÀÚ¼¼È÷ ¼³¸íÇÏ°Ú½À´Ï´Ù. ÀÌ·¯ÇÑ ¹ýÄ¢À¸·ÎºÎÅÍ ¿ì¸®´Â ´ÙÀ½°ú °°Àº CUP specificationÀ» ±¸¼ºÇÒ ¼ö ÀÖ½À´Ï´Ù.

// CUP specification for a simple expression evaluator (no actions)

import java_cup.runtime.*;

/* Preliminaries to set up and use the scanner.  */
init with {: scanner.init();              :};
scan with {: return scanner.next_token(); :};

/* Terminals (tokens returned by the scanner). */
terminal            SEMI, PLUS, MINUS, TIMES, DIVIDE, MOD;
terminal            UMINUS, LPAREN, RPAREN;
terminal Integer    NUMBER;

/* Non terminals */
non terminal            expr_list, expr_part;
non terminal Integer    expr, term, factor;

/* Precedences */
precedence left PLUS, MINUS;
precedence left TIMES, DIVIDE, MOD;
precedence left UMINUS;

/* The grammar */
expr_list ::= expr_list expr_part |
              expr_part;
expr_part ::= expr SEMI;
expr      ::= expr PLUS expr
            | expr MINUS expr
            | expr TIMES expr
            | expr DIVIDE expr
            | expr MOD expr
            | MINUS expr %prec UMINUS
            | LPAREN expr RPAREN
            | NUMBER
            ;


³ªÁß¿¡ °¢ ¹®¹ý¿¡ ´ëÇØ ÀÚ¼¼È÷ º¼ °ÍÀÔ´Ï´Ù¸¸, Áö±Ý ¿©±â¼­ specificationÀÌ 4°³ÀÇ ÁÖ¿ä ºÎºÐÀ¸·Î ±¸¼ºµÇ¾î ÀÖ´Â °ÍÀ» ¹Ù·Î º¼ ¼ö ÀÖ½À´Ï´Ù. ù¹ø° ºÎºÐÀº ¾î¶»°Ô Æļ­°¡ »ý¼ºµÉ °ÍÀÎÁö, ·±Å¸ÀÓ ÄÚµå ºÎºÐÀ» ¾î¶»°Ô Á¦°øÇÒ °ÍÀÎÁö ¿ì¼±ÀûÀÎ ¿©·¯°¡ÁöÀÇ ¼±¾ðÀ» Á¦°øÇÕ´Ï´Ù. ÀÌ °æ¿ì¿¡´Â java_cup.runtime Ŭ·¡½ºµéÀÌ Æ÷Ç﵃ °ÍÀ̸ç, ½ºÄ³³Ê ÃʱâÈ­¿Í ½ºÄ³³ÊÀÇ ´ÙÀ½ ÀÔ·Â ÅäÅ«À» Ãâ·ÂÇÒ °ÍÀ» ¼­¼úÇÏ°í ÀÖ½À´Ï´Ù. SpecificationÀÇ µÎ¹ø° ºÎºÐÀº terminalµé°ú non-terminalµé, °¢°¢¿¡ °áÇÕµÉ object Ŭ·¡½º¸¦ Á¤ÀÇÇÕ´Ï´Ù. ÀÌ °æ¿ì terminalµéÀº typeÀÌ ¾ø°Å³ª, Á¤¼öÇüÀ¸·Î ¼±¾ðµÇ¾î ÀÖ½À´Ï´Ù. TerminalÀ̳ª non-terminalÀÇ Á¤ÀÇµÈ Å¸ÀÔÀº À̵é terminal°ú non-terminalÀÇ °ªÀÇ Å¸ÀÔÀÔ´Ï´Ù. ¸¸¾à ŸÀÔÀÌ ¾ø´Ù°í Á¤ÀÇµÉ °æ¿ì, terminalÀ̳ª non-terminalÀº ¾Æ¹«·± °ªÀ» °®Áö ¾Ê½À´Ï´Ù. ¿©±â ŸÀÔÀÌ ¾ø´Â terminal°ú non-terminalµéÀº ¾Æ¹« °ªµµ °®Áö ¾Ê½À´Ï´Ù. ¼¼¹ø° ºÎºÐÀº terminalµéÀÇ ¿ì¼±¼øÀ§¿Í Á¶ÇÕ¿¡ ´ëÇØ ¸í¼¼ÇÕ´Ï´Ù. ¸¶Áö¸· ¿ì¼±¼øÀ§ ¼±¾ðÀº ¼±¾ðµÈ Å͹̳ο¡°Ô ÃÖ°íÀÇ ¿ì¼±¼øÀ§¸¦ ºÎ¿©ÇÕ´Ï´Ù. SpecificationÀÇ ¸¶Áö¸· ºÎºÐÀº ¹®¹ýÀ» Æ÷ÇÔÇÕ´Ï´Ù.

ÀÌ specificationÀ¸·ÎºÎÅÍ Æļ­¸¦ »ý¼ºÇϱâ À§ÇØ ¿ì¸®´Â CUP »ý¼º±â¸¦ »ç¿ëÇÕ´Ï´Ù. ¸¸¾à ÀÌ specificationÀÌ parser.cup¿¡ ÀúÀåµÇ¾î ÀÖ´ø °ÍÀ̸é, (Àû¾îµµ À¯´Ð½º ½Ã½ºÅÛ¿¡¼­) ¿ì¸®´Â ´ÙÀ½ ¸í·É¾î·Î CUPÀ» È£ÃâÇÒ °ÍÀÔ´Ï´Ù.

 java java_cup.Main < parser.cup


ÀÌ ¿¹¿¡¼­, ½Ã½ºÅÛÀº µÎ °³ÀÇ ÀÚ¹Ù ¼Ò½º ÆÄÀÏ(»ý¼ºµÈ Æļ­ÀÎ sym.java¿Í parser.java ÆÄÀÏ)À» »ý¼ºÇÒ °ÍÀÔ´Ï´Ù. ´ç½ÅÀÌ ¿¹»óÇÑ °Íó·³ ÀÌ µÎ ÆÄÀÏÀº sym Ŭ·¡½º¿Í parser Ŭ·¡½º¿¡ ´ëÇÑ ¼±¾ðÀ» Æ÷ÇÔÇÏ°í ÀÖ½À´Ï´Ù. sym Ŭ·¡½º´Â °¢°¢ terminal ½Éº¼¿¡ ´ëÇÑ »ó¼ö ¼±¾ðÀÇ ³ª¿­À» Æ÷ÇÔÇÕ´Ï´Ù. ÀÌ°ÍÀº symbolÀ» ÂüÁ¶ÇÏ´Â ½ºÄ³³Ê¿¡ ÀÇÇØ ´ëºÎºÐ »ç¿ëµË´Ï´Ù(¿¹¸¦µé¾î "return new Symbol(sym.SEMI);"¿Í °°Àº ÄÚµåó·³). parser Ŭ·¡½º´Â parser ÀÚ½ÅÀ» ÇÕ¼ºÇÕ´Ï´Ù.

Parser Àüü¸¦ Çü¼ºÇÏ´Â µ¿¾ÈÀÇ specificationÀº ³»¿ë¿¡ °ü·ÃÇÑ ¾î¶°ÇÑ ÀÛ¾÷(Action)µµ »ý¼ºÇÏÁö ¾Ê½À´Ï´Ù. ´ÜÁö parseÀÇ ¼º°ø°ú ½ÇÆи¦ ³ªÅ¸³¾ »ÓÀÔ´Ï´Ù. °¢°¢ÀÇ Ç¥ÇöÀ» °è»ê(ó¸®)ÇÏ°í Ãâ·ÂÇϱâ À§ÇØ, ¿©·¯ °÷¿¡ ÀÛ¾÷(Action)À» À§ÇÑ ÀÚ¹ÙÄڵ带 ³»Àå½ÃÄÑ¾ß ÇÕ´Ï´Ù. CUP¿¡¼­ ÀÛ¾÷(Action)µéÀº {:°ú :} ÇüÅÂÀÇ ±¸ºÐÀÚ¿¡ ÀÇÇØ µÑ·¯½Î¿©Áø ÄÚµå ¹®ÀåÀ¸·Î Æ÷ÇԵ˴ϴÙ. (ÀÌ ºÎºÐ¿¡ ´ëÇؼ­ °ýÈ£¿¡ µÑ·¯½Î¿©Áø init¿Í scanÀÇ ¿¹Á¦¸¦ º¼ ¼ö ÀÖ½À´Ï´Ù.) º¸Åë ½Ã½ºÅÛÀº ±¸ºÐÀÚ ¾È¿¡ ÀÖ´Â ¸ðµç ¹®ÀÚ¸¦ ±â·ÏÇÏÁö¸¸, ¾È¿¡ µé¾îÀÖ´Â ³»¿ëÀÌ »ç¿ë °¡´ÉÇÑ ÀÚ¹Ù ÄÚµåÀÎÁö´Â üũÇÏÁö ¾Ê½À´Ï´Ù.

¿ì¸®ÀÇ (¹®¹ý ¾È¿¡¼­ ¿©·¯ ÁöÁ¡¿¡ ³»ÀåµÈ ÀÛ¾÷µéÀÌ °°ÀÌ µé¾î°£) ¿¹Á¦ ½Ã½ºÅÛ¿¡ ´ëÇØ ´õ¿í ¿Ï¼ºÀûÀÎ specificationÀ» ´ÙÀ½¿¡ º¸¿©ÁÝ´Ï´Ù.

// CUP specification for a simple expression evaluator (w/ actions)

import java_cup.runtime.*;

/* Preliminaries to set up and use the scanner.  */
init with {: scanner.init();              :};
scan with {: return scanner.next_token(); :};

/* Terminals (tokens returned by the scanner). */
terminal           SEMI, PLUS, MINUS, TIMES, DIVIDE, MOD;
terminal           UMINUS, LPAREN, RPAREN;
terminal Integer   NUMBER;

/* Non-terminals */
non terminal            expr_list, expr_part;
non terminal Integer    expr;

/* Precedences */
precedence left PLUS, MINUS;
precedence left TIMES, DIVIDE, MOD;
precedence left UMINUS;

/* The grammar */
expr_list ::= expr_list expr_part
              |
              expr_part;

expr_part ::= expr:e
              {: System.out.println("= " + e); :}
              SEMI
              ;

expr      ::= expr:e1 PLUS expr:e2
              {: RESULT = new Integer(e1.intValue() + e2.intValue()); :}
              |
              expr:e1 MINUS expr:e2
              {: RESULT = new Integer(e1.intValue() - e2.intValue()); :}
              |
              expr:e1 TIMES expr:e2
              {: RESULT = new Integer(e1.intValue() * e2.intValue()); :}
              |
              expr:e1 DIVIDE expr:e2
              {: RESULT = new Integer(e1.intValue() / e2.intValue()); :}
              |
              expr:e1 MOD expr:e2
              {: RESULT = new Integer(e1.intValue() % e2.intValue()); :}
              |
              NUMBER:n
              {: RESULT = n; :}
              |
              MINUS expr:e
              {: RESULT = new Integer(0 - e.intValue()); :}
              %prec UMINUS
              |
              LPAREN expr:e RPAREN
              {: RESULT = e; :}
              ;


¿©±â¼­ ¿ì¸®´Â ¸î°¡Áö ¹Ù²ïÁ¡À» º¼ ¼ö ÀÖ½À´Ï´Ù. °¡Àå Áß¿äÇÑ ºÎºÐÀº Æļ­ÀÇ ¿©·¯°÷¿¡¼­ ½ÇÇàµÉ Äڵ尡 {: ¿Í :}¿¡ ÀÇÇØ ±¸ºÐµÈ ÄÚµå ¾È¿¡ Æ÷ÇԵǾî ÀÖ´Ù´Â °ÍÀÔ´Ï´Ù. °Ô´Ù°¡, ·¹À̺í(label)µéÀÌ °á°ú¹°ÀÇ ¿ìº¯¿¡ ÀÖ´Â ´Ù¾çÇÑ symbolµé¿¡ À§Ä¡ÇÏ°í ÀÖ½À´Ï´Ù. ¿¹¸¦ µé¾î,

  expr:e1 PLUS expr:e2
        {: RESULT = new Integer(e1.intValue() + e2.intValue()); :}


ù¹ø° non-terminal ÀÎ exprÀº e1À¸·Î ·¹À̺í Ç¥±â µÇ¾úÀ¸¸ç, µÎ¹ø°´Â e2·Î µÇ¾ú½À´Ï´Ù. °¢ Ãâ·Â¹°ÀÇ Áº¯À» ¾Ï¹¬ÀûÀ¸·Î Ç×»ó RESULT¶ó°í ·¹À̺í Ç¥±âÇÕ´Ï´Ù.

»ý¼º¹°¿¡ ³ªÅ¸³­ °¢°¢ÀÇ ½Éº¼Àº parse ½ºÅÿ¡¼­ ½ÇÇà½Ã¿¡ ½Éº¼Å¸ÀÔÀÇ °´Ã¼(object)¿¡ ÀÇÇØ ³ªÅ¸³³´Ï´Ù. ·¹À̺íÀº ÀÌ °´Ã¼(object)µé¿¡¼­ Instance º¯¼ö °ªÀ» ÂüÁ¶ÇÕ´Ï´Ù. À§ÀÇ ¼Ò½ºÇ¥Çö expr:e1 PLUS expr:e2 ¿¡¼­, e2¿Í e1Àº Á¤¼öÇü °´Ã¼¸¦ ÂüÁ¶ÇÕ´Ï´Ù. ÀÌ °´Ã¼µéÀº parse ½ºÅÿ¡¼­ À̵éÀÇ non-terminal·Î º¸ÀÌ´Â ½Éº¼Çü(Symbol type)ÀÇ °ª ¿µ¿ª¿¡ ÀÖ½À´Ï´Ù. RESULT´Â non-terminal exprÀÌ Á¤¼öÇüÀ¸·Î ¼±¾ðµÇ¸é¼­ºÎÅÍ Á¤¼öÇüÀÔ´Ï´Ù. ÀÌ °´Ã¼´Â »õ·Î¿î ½Éº¼°´Ã¼ÀÇ Instance º¯¼ö°ªÀÌ µË´Ï´Ù.

°¢°¢ÀÇ ·¹ÀÌºí¿¡ ´ëÇØ, »ç¿ëÀÚ°¡ Á¢±Ù °¡´ÉÇÑ µÎ °³ ÀÌ»óÀÇ º¯¼ö¸¦ ¼±¾ðÇÕ´Ï´Ù. ±× Á¿찪 ·¹À̺íÀº ÄÚµå ¹®ÀÚ¿­·Î Àü´ÞµÇ¾î¼­, »ç¿ëÀÚ°¡ ÀÔ·Â ½ºÆ®¸²¿¡ ÀÖ´Â °¢°¢ÀÇ terminal °ú non-terminalÀÇ Á¿캯ÀÌ ¾îµð ÀÖ´ÂÁö ãÀ» ¼ö ÀÖ½À´Ï´Ù. ÀÌ º¯¼öµéÀÇ À̸§Àº ·¹À̺í À̸§¿¡ left¿Í right¸¦ ºÙÀÔ´Ï´Ù. ¿¹¸¦ µé¾î, »ý¼º¹°ÀÇ ¿ìº¯¿¡ ÀÖ´Â expr:e1 PLUS expr:e2´Â »ç¿ëÀÚ°¡ e1°ú e2·Î Á¢±ÙÇÒ »Ó¸¸ ¾Æ´Ï¶ó, e1left, e1right, e2left, e2ritght·Îµµ Á¢±ÙÀÌ °¡´ÉÇÕ´Ï´Ù. ÀÌ º¯¼öµéÀÇ Å¸ÀÔÀº Á¤¼öÇüÀÔ´Ï´Ù.

Æļ­ ¼º»ýÀÇ ¸¶Áö¸· ´Ü°è´Â (Àß ¾Æ½Ã´Ù½ÃÇÇ lexical analyzer ¶Ç´Â °£´ÜÈ÷ lexer¶ó°í ÇÏ´Â) ½ºÄ³³Ê¸¦ Á¦ÀÛÇÏ´Â °ÍÀÔ´Ï´Ù. ÀÌ ·çƾÀº °³º° ¹®ÀÚ¸¦ ÀоîµéÀÌ°í °ø¹éÀ̳ª ÁÖ¼®À» Á¦°ÅÇÏ°í, °¢ ¹®ÀÚµéÀÇ ÁýÇÕÀÌ ³ªÅ¸³»´Â ¹®¹ýÀ¸·ÎºÎÅÍ terminal symbolÀ» ÀνÄÇÏ¿©, Æļ­¿¡°Ô ÀÌ·¯ÇÑ ½Éº¼µéÀ» ³ªÅ¸³»´Â ½Éº¼°´Ã¼µé(Symbol Objects)À» µÇµ¹·ÁÁà¾ß ÇÕ´Ï´Ù. ±× terminalµéÀº ½ºÄ³³Ê ÇÔ¼ö¸¦ È£ÃâÇϱâ À§ÇØ ¹ÝȯµË´Ï´Ù. ¿¹¸¦ µé¾î, Æļ­°¡ scanner.next_token()À» È£ÃâÇÒ °ÍÀÔ´Ï´Ù. ½ºÄ³³Ê´Â java_cup.runtime.Symbol ÇüÀÇ °´Ã¼¸¦ µÇµ¹·ÁÁà¾ß ÇÕ´Ï´Ù. ÀÌ ÀÚ·áÇüÀº ÀÌÀüÀÇ CUP¿¡¼­ java_cup.runtime.symbol°ú´Â ¾ÆÁÖ ´Ù¸¨´Ï´Ù. ÀÌ ½Éº¼ °´Ã¼´Â ¹®¹ýºÐ¼®±â¿¡ ÀÇÇØ ¼³Á¤µÉ °´Ã¼ÇüÀÇ º¯¼ö°ª ÀνºÅϽº¸¦ Æ÷ÇÔÇÏ°í ÀÖ½À´Ï´Ù. ÀÌ º¯¼ö´Â terminal°ú non terminal ¼±¾ð¿¡¼­ ¼±¾ðµÈ °°Àº ÀÚ·áÇüÀÇ °ªÀ¸·Î ½Éº¼°ª°ú °´Ã¼ÇüÀÌ Àû¿ëµË´Ï´Ù. ´ÙÀ½ÀÇ ¿¹Á¦¿¡¼­ ¸¸¾à ¹®¹ýºÐ¼®±â°¡ NUMBER ÅäÅ«Àº ³Ñ¾î°¡µµ·Ï ¿øÇÑ´Ù¸é, Á¤¼öÇüÀÇ °´Ã¼·Î ä¿öÁø ÀνºÅϽº º¯¼ö°ªÀ» °®´Â ½Éº¼À» ¸¸µé¾î¾ß ÇÕ´Ï´Ù. terminal°ú °ªÀ» °®Áö ¾Ê´Â non-terminalµé¿¡ ´ëÇÑ ½Éº¼ °´Ã¼µéÀº ³Î °ª ¿µ¿ªÀ» °®½À´Ï´Ù.

The code contained in the init with clause of the specification will be executed before any tokens are requested. Each token will be requested using whatever code is found in the scan with clause. Beyond this, the exact form the scanner takes is up to you; however note that each call to the scanner function should return a new instance of java_cup.runtime.Symbol (or a subclass). These symbol objects are annotated with parser information and pushed onto a stack; reusing objects will result in the parser annotations being scrambled. As of CUP 0.10j, Symbol reuse should be detected if it occurs; the parser will throw an Error telling you to fix your scanner.

In the next section a more detailed and formal explanation of all parts of a CUP specification will be given. Section 3 describes options for running the CUP system. Section 4 discusses the details of how to customize a CUP parser, while section 5 discusses the scanner interface added in CUP 0.10j. Section 6 considers error recovery. Finally, Section 7 provides a conclusion.

4. 2. Specification Syntax

Now that we have seen a small example, we present a complete description of all parts of a CUP specification. A specification has four sections with a total of eight specific parts (however, most of these are optional). A specification consists of:

  • package and import specifications,
  • user code components,
  • symbol (terminal and non-terminal) lists,
  • precedence declarations, and
  • the grammar.

Each of these parts must appear in the order presented here. (A complete grammar for the specification language is given in Appendix A.) The particulars of each part of the specification are described in the subsections below.

5. Package and Import Specifications

A specification begins with optional package and import declarations. These have the same syntax, and play the same role, as the package and import declarations found in a normal Java program. A package declaration is of the form:

    package name;


where name name is a Java package identifier, possibly in several parts separated by ".". In general, CUP employs Java lexical conventions. So for example, both styles of Java comments are supported, and identifiers are constructed beginning with a letter, dollar sign ($), or underscore (_), which can then be followed by zero or more letters, numbers, dollar signs, and underscores.

After an optional package declaration, there can be zero or more import declarations. As in a Java program these have the form:

    import package_name.class_name;


or

    import package_name.*;


The package declaration indicates what package the sym and parser classes that are generated by the system will be in. Any import declarations that appear in the specification will also appear in the source file for the parser class allowing various names from that package to be used directly in user supplied action code. User Code Components Following the optional package and import declarations are a series of optional declarations that allow user code to be included as part of the generated parser (see Section 4 for a full description of how the parser uses this code). As a part of the parser file, a separate non-public class to contain all embedded user actions is produced. The first action code declaration section allows code to be included in this class. Routines and variables for use by the code embedded in the grammar would normally be placed in this section (a typical example might be symbol table manipulation routines). This declaration takes the form:

    action code {: ... :};


where {: ... :} is a code string whose contents will be placed directly within the action class class declaration.

After the action code declaration is an optional parser code declaration. This declaration allows methods and variable to be placed directly within the generated parser class. Although this is less common, it can be helpful when customizing the parser &emdash; it is possible for example, to include scanning methods inside the parser and/or override the default error reporting routines. This declaration is very similar to the action code declaration and takes the form:

    parser code {: ... :};


Again, code from the code string is placed directly into the generated parser class definition.

Next in the specification is the optional init declaration which has the form:

    init with {: ... :};


This declaration provides code that will be executed by the parser before it asks for the first token. Typically, this is used to initialize the scanner as well as various tables and other data structures that might be needed by semantic actions. In this case, the code given in the code string forms the body of a void method inside the parser class.

The final (optional) user code section of the specification indicates how the parser should ask for the next token from the scanner. This has the form:

    scan with {: ... :};


As with the init clause, the contents of the code string forms the body of a method in the generated parser. However, in this case the method returns an object of type java_cup.runtime.Symbol. Consequently the code found in the scan with clause should return such a value. See section 5 for information on the default behavior if the scan with section is omitted.

As of CUP 0.10j the action code, parser code, init code, and scan with sections may appear in any order. They must, however, precede the symbol lists.

6. Symbol Lists

Following user supplied code comes the first required part of the specification: the symbol lists. These declarations are responsible for naming and supplying a type for each terminal and non-terminal symbol that appears in the grammar. As indicated above, each terminal and non-terminal symbol is represented at runtime with a Symbol object. In the case of terminals, these are returned by the scanner and placed on the parse stack. The lexer should put the value of the terminal in the value instance variable. In the case of non-terminals these replace a series of Symbol objects on the parse stack whenever the right hand side of some production is recognized. In order to tell the parser which object types should be used for which symbol, terminal and non terminal declarations are used. These take the forms:

    terminal classname name1, name2, ...;
    non terminal classname name1, name2, ...;
    terminal name1, name2, ...;


and

    non terminal name1, name2, ...;


where classname can be a multiple part name separated with "."s. The classname specified represents the type of the value of that terminal or non-terminal. When accessing these values through labels, the users uses the type declared. the classname can be of any type. If no classname is given, then the terminal or non-terminal holds no value. a label referring to such a symbol with have a null value. As of CUP 0.10j, you may specify non-terminals the declaration "nonterminal" (note, no space) as well as the original "non terminal" spelling.

Names of terminals and non-terminals cannot be CUP reserved words; these include "code", "action", "parser", "terminal", "non", "nonterminal", "init", "scan", "with", "start", "precedence", "left", "right", "nonassoc", "import", and "package".

Precedence and Associativity declarations The third section, which is optional, specifies the precedences and associativity of terminals. This is useful for parsing with ambiguous grammars, as done in the example above. There are three type of precedence/associativity declarations:

        precedence left     terminal[, terminal...];
        precedence right    terminal[, terminal...];
        precedence nonassoc terminal[, terminal...];


The comma separated list indicates that those terminals should have the associativity specified at that precedence level and the precedence of that declaration. The order of precedence, from highest to lowest, is bottom to top. Hence, this declares that multiplication and division have higher precedence than addition and subtraction:

        precedence left  ADD, SUBTRACT;
        precedence left  TIMES, DIVIDE;


Precedence resolves shift reduce problems. For example, given the input to the above example parser 3 + 4 * 8, the parser doesn't know whether to reduce 3 + 4 or shift the '*' onto the stack. However, since '*' has a higher precedence than '+', it will be shifted and the multiplication will be performed before the addition.

CUP assigns each one of its terminals a precedence according to these declarations. Any terminals not in this declaration have lowest precedence. CUP also assigns each of its productions a precedence. That precedence is equal to the precedence of the last terminal in that production. If the production has no terminals, then it has lowest precedence. For example, expr ::= expr TIMES expr would have the same precedence as TIMES. When there is a shift/reduce conflict, the parser determines whether the terminal to be shifted has a higher precedence, or if the production to reduce by does. If the terminal has higher precedence, it it shifted, if the production has higher precedence, a reduce is performed. If they have equal precedence, associativity of the terminal determine what happens.

An associativity is assigned to each terminal used in the precedence/associativity declarations. The three associativities are left, right and nonassoc Associativities are also used to resolve shift/reduce conflicts, but only in the case of equal precedences. If the associativity of the terminal that can be shifted is left, then a reduce is performed. This means, if the input is a string of additions, like 3 + 4 + 5 + 6 + 7, the parser will always reduce them from left to right, in this case, starting with 3 + 4. If the associativity of the terminal is right, it is shifted onto the stack. hence, the reductions will take place from right to left. So, if PLUS were declared with associativity of right, the 6 + 7 would be reduced first in the above string. If a terminal is declared as nonassoc, then two consecutive occurrences of equal precedence non-associative terminals generates an error. This is useful for comparison operations. For example, if the input string is 6 == 7 == 8 == 9, the parser should generate an error. If '==' is declared as nonassoc then an error will be generated.

All terminals not used in the precedence/associativity declarations are treated as lowest precedence. If a shift/reduce error results, involving two such terminals, it cannot be resolved, as the above conflicts are, so it will be reported.

7. The Grammar

The final section of a CUP declaration provides the grammar. This section optionally starts with a declaration of the form:

    start with non-terminal;


ÀÌ°ÍÀº ¾î¶² non-terminalÀÌ ÆĽÌÀÇ ½ÃÀÛÀ̳ª ȤÀº Á¾°áÇÏ´Â non-terminalÀÎÁö °¡¸®Å²´Ù. ¸¸¾à ½ÃÀÛÇÏ´Â non-terminalÀÌ explicitlyÇÏ°Ô ¼±¾ðµÇÁö ¾ÊÀ¸¸é, ô¹ø° productionÀÇ Áº¯ÀÇ non-terminalÀÌ »ç¿ëµÉ °ÍÀÌ´Ù. ÆĽÌÀ» ¼º°øÀûÀ¸·Î ³¡³½ ÈÄ¿¡, CUP´Â java_cup.runtime.SymbolÀ» ¸®ÅÏÇÑ´Ù. ÀÌ SymbolÀÇ value instance variableÀº ¸¶Áö¸· reduction result¸¦ °®´Â´Ù

The grammar itself follows the optional start declaration. ¹®¹ýÀÇ °¢°¢ÀÇ productionÀº Áº¯¿¡ non-terminalÀÌ, ±×¸®°í "::="°¡ ºÙ°í, zero or more°³ÀÇ actions, terminal, or non-terminal symbols, followed by an optional contextual precedence assignment, and terminated with a semicolon (;).. µéÀÌ ¿Â´Ù.

¿ìº¯ÀÇ °¢°¢ÀÇ symbolÀº À̸§À» ºÙ¿© labeled µÉ ¼ö ÀÖ´Ù. label nameÀº symbol name µÚ¿¡ colon (:) ´ÙÀ½¿¡ ºÙÀδÙ. label nameÀº ±× production¿¡¼­ À¯ÀÏÇؾßÇϸç, action code¿¡¼­ symbolÀÇ value¸¦ ÂüÁ¶Çϴµ¥ ¾²ÀÏ ¼ö ÀÖ´Ù. Along with the label, two more variables are created, which are the label plus left and the label plus right. These are int values that contain the right and left locations of what the terminal or non-terminal covers in the input file. These values must be properly initialized in the terminals by the lexer. The left and right values then propagate to non-terminals to which productions reduce.

¸¸¾à °°Àº non-terminal¿¡ ´ëÇØ ¿©·¯°³ÀÇ productionÀÌ ÀÖÀ¸¸é ÇÔ²² ¼±¾ðÇÒ ¼ö ÀÖ´Ù. ÀÌ °æ¿ì, productionÀº non-terminal°ú ::= ·Î ½ÃÀ۵ȴÙ. ±×¸®°í ¿©·¯°³ÀÇ ¿ìº¯µéÀÌ, °¢°¢ bar (|) ·Î ³ª´µ¾î µþ¸°´Ù. productionÀÇ full setÀº semicolon¿¡ ÀÇÇØ ³¡³­´Ù.

actionÀº code strings (e.g., Java code inside {: ... :} delimiters) ·Î ³ªÅ¸³­´Ù. À̰͵éÀº the portion of the production to the left of the actionÀÌ ÀÎ½Ä µÇ´Â ½ÃÁ¡¿¡ ½ÇÇàµÈ´Ù. (Note that the scanner will have returned the token one past the point of the action since the parser needs this extra lookahead token for recognition.)

Contextual precedence assignments follow all the symbols and actions of the right hand side of the production whose precedence it is assigning. Contextual precedence assignment allows a production to be assigned a precedence not based on the last terminal in it. A good example is shown in the above sample parser specification:

        precedence left PLUS, MINUS;
        precedence left TIMES, DIVIDE, MOD;
        precedence left UMINUS;

        expr ::=  MINUS expr:e
                  {: RESULT = new Integer(0 - e.intValue()); :}
                  %prec UMINUS


Here, there production is declared as having the precedence of UMINUS. Hence, the parser can give the MINUS sign two different precedences, depending on whether it is a unary minus or a subtraction operation.

8. 3. Running CUP

As mentioned above, CUP is written in Java. To invoke it, one needs to use the Java interpreter to invoke the static method java_cup.Main(), passing an array of strings containing options. Assuming a Unix machine, the simplest way to do this is typically to invoke it directly from the command line with a command such as:

    java java_cup.Main options < inputfile


Once running, CUP expects to find a specification file on standard input and produces two Java source files as output.

In addition to the specification file, CUP's behavior can also be changed by passing various options to it. Legal options are documented in Main.java and include:

  • -package name

Specify that the parser and sym classes are to be placed in the named package. By default, no package specification is put in the generated code (hence the classes default to the special "unnamed" package).
  • -parser name

parser¿Í action code¸¦ ÁÖ¾îÁø À̸§ÀÇ ÆÄÀÏ(Ŭ·¡½ºÀ̱⵵ ÇÑ)¿¡ Ãâ·ÂÇÑ´Ù. ±âº»°ªÀº "parser"
  • -symbols name

symbol constant code¸¦ ÁÖ¾îÁø À̸§ÀÇ Å¬·¡½º¿¡ ³»º¸³½´Ù. ±âº»°ªÀº "sym"
  • -interface

symbol constant code¸¦ class·Î ÇÏÁö ¾Ê°í interface·Î ³»º¸³½´Ù.
  • -nonterms

Place constants for non-terminals into the symbol constant class. The parser does not need these symbol constants, so they are not normally output. However, it can be very helpful to refer to these constants when debugging a generated parser.
  • -expect number

During parser construction the system may detect that an ambiguous situation would occur at runtime. This is called a conflict. In general, the parser may be unable to decide whether to shift (read another symbol) or reduce (replace the recognized right hand side of a production with its left hand side). This is called a shift/reduce conflict. Similarly, the parser may not be able to decide between reduction with two different productions. This is called a reduce/reduce conflict. Normally, if one or more of these conflicts occur, parser generation is aborted. However, in certain carefully considered cases it may be advantageous to arbitrarily break such a conflict. In this case CUP uses YACC convention and resolves shift/reduce conflicts by shifting, and reduce/reduce conflicts using the "highest priority" production (the one declared first in the specification). In order to enable automatic breaking of conflicts the -expect option must be given indicating exactly how many conflicts are expected. Conflicts resolved by precedences and associativities are not reported.
  • -compact_red

Including this option enables a table compaction optimization involving reductions. In particular, it allows the most common reduce entry in each row of the parse action table to be used as the default for that row. This typically saves considerable room in the tables, which can grow to be very large. This optimization has the effect of replacing all error entries in a row with the default reduce entry. While this may sound dangerous, if not down right incorrect, it turns out that this does not affect the correctness of the parser. In particular, some changes of this type are inherent in LALR parsers (when compared to canonical LR parsers), and the resulting parsers will still never read past the first token at which the error could be detected. The parser can, however, make extra erroneous reduces before detecting the error, so this can degrade the parser's ability to do error recovery. (Refer to reference 2 pp. 244-247 or reference 3 pp. 190-194 for a complete explanation of this compaction technique.)

This option is typically used to work-around the java bytecode limitations on table initialization code sizes. However, CUP 0.10h introduced a string-encoding for the parser tables which is not subject to the standard method-size limitations. Consequently, use of this option should no longer be required for large grammars.
  • -nowarn

This options causes all warning messages (as opposed to error messages) produced by the system to be suppressed.
  • -nosummary

Normally, the system prints a summary listing such things as the number of terminals, non-terminals, parse states, etc. at the end of its run. This option suppresses that summary.
  • -progress

This option causes the system to print short messages indicating its progress through various parts of the parser generation process.
  • -dump_grammar
  • -dump_states
  • -dump_tables
  • -dump

These options cause the system to produce a human readable dump of the grammar, the constructed parse states (often needed to resolve parse conflicts), and the parse tables (rarely needed), respectively. The -dump option can be used to produce all of these dumps.
  • -time

This option adds detailed timing statistics to the normal summary of results. This is normally of great interest only to maintainers of the system itself.
  • -debug

This option produces voluminous internal debugging information about the system as it runs. This is normally of interest only to maintainers of the system itself.
  • -nopositions

This option keeps CUP from generating code to propagate the left and right hand values of terminals to non-terminals, and then from non-terminals to other terminals. If the left and right values aren't going to be used by the parser, then it will save some runtime computation to not generate these position propagations. This option also keeps the left and right label variables from being generated, so any reference to these will cause an error.
  • -noscanner

CUP 0.10j introduced improved scanner integration and a new interface, java_cup.runtime.Scanner. By default, the generated parser refers to this interface, which means you cannot use these parsers with CUP runtimes older than 0.10j. If your parser does not use the new scanner integration features, then you may specify the -noscanner option to suppress the java_cup.runtime.Scanner references and allow compatibility with old runtimes. Not many people should have reason to do this.
  • -version

Invoking CUP with the -version flag will cause it to print out the working version of CUP and halt. This allows automated CUP version checking for Makefiles, install scripts and other applications which may require it.

9. 4. Customizing the Parser

Each generated parser consists of three generated classes. The sym class (which can be renamed using the -symbols option) simply contains a series of int constants, one for each terminal. Non-terminals are also included if the -nonterms option is given. The source file for the parser class (which can be renamed using the -parser option) actually contains two class definitions, the public parser class that implements the actual parser, and another non-public class (called CUP$action) which encapsulates all user actions contained in the grammar, as well as code from the action code declaration. In addition to user supplied code, this class contains one method: CUP$do_action which consists of a large switch statement for selecting and executing various fragments of user supplied action code. In general, all names beginning with the prefix of CUP$ are reserved for internal uses by CUP generated code.

The parser class contains the actual generated parser. It is a subclass of java_cup.runtime.lr_parser which implements a general table driven framework for an LR parser. The generated parser class provides a series of tables for use by the general framework. Three tables are provided:

  • the production table

provides the symbol number of the left hand side non-terminal, along with the length of the right hand side, for each production in the grammar,
  • the action table

indicates what action (shift, reduce, or error) is to be taken on each lookahead symbol when encountered in each state, and
  • the reduce-goto table

indicates which state to shift to after reduces (under each non-terminal from each state).

(Note that the action and reduce-goto tables are not stored as simple arrays, but use a compacted "list" structure to save a significant amount of space. See comments the runtime system source code for details.)

Beyond the parse tables, generated (or inherited) code provides a series of methods that can be used to customize the generated parser. Some of these methods are supplied by code found in part of the specification and can be customized directly in that fashion. The others are provided by the lr_parser base class and can be overridden with new versions (via the parser code declaration) to customize the system. Methods available for customization include:

  • public void user_init()

ÀÌ method´Â parser°¡ scanner¿¡°Ô¼­ tokenÀ» óÀ½À¸·Î ¿äûÇϱâ Àü¿¡ È£ÃâµÈ´Ù. ÀÌ methodÀÇ body´Â specificationÀÇ init with ±¸¹®ÀÇ ³»¿ëÀÌ´Ù.
  • public java_cup.runtime.Symbol scan()

ÀÌ method´Â scanner¸¦ ĸ½¶È­ÇÏ°í, »õ·Î¿î terminalÀÌ ÇÊ¿äÇÒ ¶§¸¶´Ù parser¿¡ ÀÇÇØ È£ÃâµÈ´Ù. ÀÌ methodÀÇ body´Â scan with ±¸¹®ÀÇ ³»¿ëÀÌ´Ù. ¸¸¾à ¾øÀ» °æ¿ì ÀÌ´Â getScanner().next_token()À» ¸®ÅÏÇÑ´Ù.
  • public java_cup.runtime.Scanner getScanner()

default scanner¸¦ ¸®ÅÏÇÑ´Ù. See section 5.
  • public void setScanner(java_cup.runtime.Scanner s)

default scanner¸¦ ÁöÁ¤ÇÑ´Ù. See section 5.
  • public void report_error(String message, Object info)

ÀÌ method´Â error message°¡ ÇÊ¿ä ÇÒ ¶§¸¶´Ù È£ÃâµÈ´Ù. ÀÌ methodÀÇ ±âº»±¸ÇöÀº, ù¹ø° parameter´Â System.err¿¡ Ãâ·ÂµÉ messageÀÌ°í, µÎ¹ø° parameter´Â ¹«½ÃµÃ´Ù. ´õ º¹ÀâÇÑ error reporting mechanismÀ» À§ÇØ ÀÌ method¸¦ ÈçÈ÷ overrideÇÑ´Ù.
  • public void report_fatal_error(String message, Object info)

ÀÌ method´Â non-recoverable error°¡ ¹ß»ýÇÒ ¶§ ¸¶´Ù È£ÃâµÈ´Ù. ÀÌ´Â report_error()¸¦ È£ÃâÇÏ¸ç ¹ÝÀÀÇÏ°í, ±×¸®°í parser method done_parsing()À» È£ÃâÇÏ¿© parsingÀ» ÁߴܽÃÅ°°í, exceptionÀ» throwÇÑ´Ù. (º¸Åë, done_parsing()Àº parsingÀÌ ´õ ÀÏÂï ³¡³¯ ÇÊ¿ä°¡ ÀÖÀ»¶§ È£ÃâµÈ´Ù)
  • public void syntax_error(Symbol cur_token)

ÀÌ method´Â syntax error°¡ °¨ÁöµÇ¾úÀ» ¶§ parser°¡ È£ÃâÇÑ´Ù. (´Ü, error recovery°¡ ½ÃµµµÇ±â Àü¿¡) ±âº» ±¸ÇöÀº report_error("Syntax error", null); ÀÌ´Ù
  • public void unrecovered_syntax_error(Symbol cur_token)

ÀÌ method´Â syntax error¸¦ recoverÇÏÁö ¸øÇÒ ¶§ parser°¡ È£ÃâÇÑ´Ù. ±âº» ±¸ÇöÀº report_fatal_error("Couldn't repair and continue parse", null); ÀÌ´Ù
  • protected int error_sync_size()

This method is called by the parser to determine how many tokens it must successfully parse in order to consider an error recovery successful. ±âº» ±¸ÇöÀº 3À» return ÇÑ´Ù. 2ÀÌÇÏÀÇ °ªÀº ÃßõÇÏÁö ¾Ê´Â´Ù. See the section on error recovery for details.

parsing ÀÚü´Â method public Symbol parse()¿¡ ÀÇÇØ ¼öÇàµÈ´Ù. ÀÌ method´Â °¢°¢ parse table¿¡¼­ °¢°¢ÀÇ reference¸¦ ãÀ¸¸ç ½ÃÀÛÇÏ°í, CUP$action object¸¦ ÃʱâÈ­ÇÑ´Ù (protected void init_actions()¸¦ ºÎ¸¥´Ù). ±×´ÙÀ½ ÀÌ´Â user_init()¸¦ È£ÃâÇÏ°í, scan()À» È£ÃâÇÏ¿© fetches the first lookaheadÇÑ´Ù. Finally, it begins parsing. ParsingÀº done_parsing()ÀÌ È£ÃâµÉ ¶§±îÁö °è¼Ó µÈ´Ù. (ÀÌ°ÍÀº ÀÚµ¿À¸·Î ºÒ¸°´Ù. ¿¹¸¦ µé¾î parser°¡ acceptsÇÒ ¶§) ±×·¯¸é start productionÀÇ RESULT¸¦ Æ÷ÇÔÇÏ´Â value instance variableÀ» °¡Áö´Â Symbol ȤÀº ±× value°¡ ¾øÀ» °æ¿ì null À» ¸®ÅÏÇÑ´Ù.

normal parser¿¡ µ¡ºÙ¿©¼­, runtime systemÀº debugging versionÀÇ parser¸¦ Á¦°øÇÑ´Ù. ÀÌ´Â normal parser¿Í Á¤È®È÷ µ¿ÀÏÇÏ°Ô µ¿ÀÛÇÏ°í, ´Ù¸¸ ±âº»ÀûÀ¸·Î´Â System.err¿¡ Ãâ·ÂµÇ´Â debugging messages¸¦ Ãâ·ÂÇÑ´Ù. (void debug_message(String mess)¸¦ È£ÃâÇÑ´Ù)

Based on these routines, invocation of a CUP parser is typically done with code such as:

      /* create a parsing object */
      parser parser_obj = new parser();

      /* open input files, etc. here */
      Symbol parse_tree = null;

      try {
        if (do_debug_parse)
          parse_tree = parser_obj.debug_parse();
        else
          parse_tree = parser_obj.parse();
      } catch (Exception e) {
        /* do cleanup here - - possibly rethrow e */
      } finally {
        /* do close out here */
      }


10. 5. Scanner Interface

In CUP 0.10j, scanner integration was improved according to suggestions made by David MacMahon. The changes make it easier to incorporate JLex and other automatically-generated scanners into CUP parsers.

To use the new code, your scanner should implement the java_cup.runtime.Scanner interface, defined as:

package java_cup.runtime;

public interface Scanner {
    public Symbol next_token() throws java.lang.Exception;
}


In addition to the methods described in section 4, the java_cup.runtime.lr_parser class has two new accessor methods, setScanner() and getScanner(). The default implementation of scan() is:

  public Symbol scan() throws java.lang.Exception {
    return getScanner().next_token();
  }


The generated parser also contains a constructor which takes a Scanner and calls setScanner() with it. In most cases, then, the init with and scan with directives may be omitted. You can simply create the parser with a reference to the desired scanner:

      /* create a parsing object */
      parser parser_obj = new parser(new my_scanner());


or set the scanner after the parser is created:

      /* create a parsing object */
      parser parser_obj = new parser();
      /* set the default scanner */
      parser_obj.setScanner(new my_scanner());


Note that because the parser uses look-ahead, resetting the scanner in the middle of a parse is not recommended. If you attempt to use the default implementation of scan() without first calling setScanner(), a NullPointerException will be thrown.

As an example of scanner integration, the following three lines in the lexer-generator input are all that is required to use a JLex scanner with CUP:

%implements java_cup.runtime.Scanner
%function next_token
%type java_cup.runtime.Symbol


It is anticipated that the JLex directive %cup will abbreviate the above three directive in the next version of JLex. Invoking the parser with the JLex scanner is then simply:

parser parser_obj = new parser( new Yylex( some_InputStream_or_Reader));


Note that you still have to handle EOF correctly; the JLex code to do so is something like:

%eofval{
  return sym.EOF;
%eofval}


where sym is the name of the symbol class for your generated parser.

The simple_calc example in the CUP distribution illustrates the use of the scanner integration features with a hand-coded scanner.

11. 6. Error Recovery

CUPÀ¸·Î parsers¸¦ ¸¸µé¶§ °¡Àå Áß¿äÇÑ Á¡Àº, syntactic errorÀÇ º¹±¸¸¦ Áö¿øÇÑ´Ù´Â Á¡ÀÌ´Ù. CUPÀº YACC°ú °°Àº error recovery mechanismÀ» »ç¿ëÇÑ´Ù. In particular, CUPÀº Ưº°ÇÑ error symbolÀ» Áö¿øÇÑ´Ù. (°£´ÜÈ÷ errorÀÌ´Ù) This symbol plays the role of a special non-terminal which, instead of being defined by productions, instead matches an erroneous input sequence.

ÀÌ error symbolÀº syntax error°¡ °¨ÁöµÇ¾úÀ» ¶§¿¡¸¸ Àû¿ëµÈ´Ù. ¸¸¾à syntax error°¡ °¨ÁöµÇ¸é parser´Â input token streamÀÇ ºÎºÐÀ» error·Î replaceÇÏ°í, parsingÀ» °è¼ÓÇÑ´Ù. ¿¹¸¦ µé¾î¼­ ¿ì¸®´Â ´ÙÀ½°ú °°Àº productionÀ» °¡Áø´Ù°í ÇÏÀÚ :

    stmt ::= expr SEMI | while_stmt SEMI | if_stmt SEMI | <b>..</b>. |
             error SEMI
             ;


ÀÌ°ÍÀº input¿¡ ÀÇÇؼ­ stmtÀÇ ¾î¶°ÇÑ normal°úµµ ÀÏÄ¡ÇÏÁö ¾ÊÀ»¶§, syntax error°¡ ¼±¾ðµÇ°í, recovery should be made by skipping erroneous tokens (equivalent to matching and replacing them with error) up to a point at which the parse can be continued with a semicolon (and additional context that legally follows a statement). An error is considered to be recovered from if and only if a sufficient number of tokens past the error symbol can be successfully parsed. (The number of tokens required is determined by the error_sync_size() method of the parser and defaults to 3).

Specifically, the parser first looks for the closest state to the top of the parse stack that has an outgoing transition under error. This generally corresponds to working from productions that represent more detailed constructs (such as a specific kind of statement) up to productions that represent more general or enclosing constructs (such as the general production for all statements or a production representing a whole section of declarations) until we get to a place where an error recovery production has been provided for. Once the parser is placed into a configuration that has an immediate error recovery (by popping the stack to the first such state), the parser begins skipping tokens to find a point at which the parse can be continued. After discarding each token, the parser attempts to parse ahead in the input (without executing any embedded semantic actions). If the parser can successfully parse past the required number of tokens, then the input is backed up to the point of recovery and the parse is resumed normally (executing all actions). If the parse cannot be continued far enough, then another token is discarded and the parser again tries to parse ahead. If the end of input is reached without making a successful recovery (or there was no suitable error recovery state found on the parse stack to begin with) then error recovery fails.

12. 7. Conclusion

ÀÌ manualÀº CUP LALR parser generation systemÀ» °£´ÜÈ÷ ¼­¼úÇÏ¿´´Ù. CUPÀº À¯¸íÇÑ YACC parser¿Í ºñ½ÁÇÑ ¿ªÇÒÀ» ÇÏÁö¸¸, C³ª C++ÀÌ ¾Æ´Ñ JAVA code·Î ¾²¿©Á³°í, µ¿ÀÛÇÑ´Ù. systemÀÇ operationÀÇ ¼¼ºÎÀûÀÎ »çÇ×Àº parser generator¿Í runtimeÀÇ source code¿¡¼­ ¾Ë ¼ö ÀÖ´Ù. See the CUP home page below for access to the API documentation for the system and its runtime.

This document covers version 0.10j of the system. Check the CUP home page: [http]http://www.cs.princeton.edu/~appel/modern/java/CUP/ for the latest release information, instructions for downloading the system, and additional news about CUP. Bug reports and other comments for the developers should be sent to the CUP maintainer, C. Scott Ananian, at cananian@alumni.princeton.edu

CUP was originally written by Scott Hudson, in August of 1995.

It was extended to support precedence by Frank Flannery, in July of 1996.

On-going improvements have been done by C. Scott Ananian, the CUP maintainer, from December of 1997 to the present.

13. References


1

S. C. Johnson, "YACC &emdash; Yet Another Compiler Compiler", CS Technical Report #32, Bell Telephone Laboratories, Murray Hill, NJ, 1975.

2
  • Aho, R. Sethi, and J. Ullman, Compilers: Principles, Techniques, and Tools, Addison-Wesley Publishing, Reading, MA, 1986.
3

C. Fischer, and R. LeBlanc, Crafting a Compiler with C, Benjamin/Cummings Publishing, Redwood City, CA, 1991.

14. Appendix A. Grammar for CUP Specification Files (0.10j)


java_cup_spec      ::= package_spec import_list code_parts
                       symbol_list precedence_list start_spec
                       production_list
package_spec       ::= PACKAGE multipart_id SEMI | empty
import_list        ::= import_list import_spec | empty
import_spec        ::= IMPORT import_id SEMI
code_part          ::= action_code_part | parser_code_part |
                       init_code | scan_code
code_parts         ::= code_parts code_part | empty
action_code_part   ::= ACTION CODE CODE_STRING opt_semi
parser_code_part   ::= PARSER CODE CODE_STRING opt_semi
init_code          ::= INIT WITH CODE_STRING opt_semi
scan_code          ::= SCAN WITH CODE_STRING opt_semi
symbol_list        ::= symbol_list symbol | symbol
symbol             ::= TERMINAL type_id declares_term |
                       NON TERMINAL type_id declares_non_term |
                       NONTERMINAL type_id declares_non_term |
                       TERMINAL declares_term |
                       NON TERMINAL declares_non_term |
                       NONTERMIANL declared_non_term
term_name_list     ::= term_name_list COMMA new_term_id | new_term_id
non_term_name_list ::= non_term_name_list COMMA new_non_term_id |
                       new_non_term_id
declares_term      ::= term_name_list SEMI
declares_non_term  ::= non_term_name_list SEMI
precedence_list    ::= precedence_l | empty
precedence_l       ::= precedence_l preced + preced;
preced             ::= PRECEDENCE LEFT terminal_list SEMI
                       | PRECEDENCE RIGHT terminal_list SEMI
                       | PRECEDENCE NONASSOC terminal_list SEMI
terminal_list      ::= terminal_list COMMA terminal_id | terminal_id
start_spec         ::= START WITH nt_id SEMI | empty
production_list    ::= production_list production | production
production         ::= nt_id COLON_COLON_EQUALS rhs_list SEMI
rhs_list           ::= rhs_list BAR rhs | rhs
rhs                ::= prod_part_list PERCENT_PREC term_id |
                       prod_part_list
prod_part_list     ::= prod_part_list prod_part | empty
prod_part          ::= symbol_id opt_label | CODE_STRING
opt_label          ::= COLON label_id | empty
multipart_id       ::= multipart_id DOT ID | ID
import_id          ::= multipart_id DOT STAR | multipart_id
type_id            ::= multipart_id
terminal_id        ::= term_id
term_id            ::= symbol_id
new_term_id        ::= ID
new_non_term_id    ::= ID
nt_id              ::= ID
symbol_id          ::= ID
label_id           ::= ID
opt_semi           ::= SEMI | empty


15. Appendix B. A Very Simple Example Scanner


// Simple Example Scanner Class

import java_cup.runtime.*;
import sym;

public class scanner {
  /* single lookahead character */
  protected static int next_char;

  /* advance input by one character */
  protected static void advance()
    throws java.io.IOException
    { next_char = System.in.read(); }

  /* initialize the scanner */
  public static void init()
    throws java.io.IOException
    { advance(); }

  /* recognize and return the next complete token */
  public static Symbol next_token()
    throws java.io.IOException
    {
      for (;;)
        switch (next_char)
          {
            case '0': case '1': case '2': case '3': case '4':
            case '5': case '6': case '7': case '8': case '9':
              /* parse a decimal integer */
              int i_val = 0;
              do {
                i_val = i_val * 10 + (next_char - '0');
                advance();
              } while (next_char >= '0' && next_char <= '9');
            return new Symbol(sym.NUMBER, new Integer(i_val));

            case ';': advance(); return new Symbol(sym.SEMI);
            case '+': advance(); return new Symbol(sym.PLUS);
            case '-': advance(); return new Symbol(sym.MINUS);
            case '*': advance(); return new Symbol(sym.TIMES);
            case '/': advance(); return new Symbol(sym.DIVIDE);
            case '%': advance(); return new Symbol(sym.MOD);
            case '(': advance(); return new Symbol(sym.LPAREN);
            case ')': advance(); return new Symbol(sym.RPAREN);

            case -1: return new Symbol(sym.EOF);

            default:
              /* in this simple scanner we just ignore everything else */
              advance();
            break;
          }
    }
};


16. Appendix C: Incompatibilites between CUP 0.9 and CUP 0.10

CUP version 0.10a is a major overhaul of CUP. The changes are severe, meaning no backwards compatibility to older versions. The changes consist of:

  • A different lexical interface,
  • New terminal/non-terminal declarations,
  • Different label references,
  • A different way of passing RESULT,
  • New position values and propagation,
  • Parser now returns a value,
  • Terminal precedence declarations and
  • Rule contextual precedence assignment

17. Lexical Interface

CUP now interfaces with the lexer in a completely different manner. In the previous releases, a new class was used for every distinct type of terminal. This release, however, uses only one class: The Symbol class. The Symbol class has three instance variables which are significant to the parser when passing information from the lexer. The first is the value instance variable. This variable contains the value of that terminal. It is of the type declared as the terminal type in the parser specification file. The second two are the instance variables left and right. They should be filled with the int value of where in the input file, character-wise, that terminal was found.

For more information, refer to the manual on scanners.

18. Terminal/Non-Terminal Declarations

Terminal and non-terminal declarations now can be declared in two different ways to indicate the values of the terminals or non-terminals. The previous declarations of the form

terminal classname terminal [, terminal ...];


still works. The classname, however indicates the type of the value of the terminal or non-terminal, and does not indicate the type of object placed on the parse stack. A declaration, such as:

terminal terminal [, terminal ...];


indicates the terminals in the list hold no value.

For more information, refer to the manual on declarations.

19. Label References

Label references do not refer to the object on the parse stack, as in the old CUP, but rather to the value of the value instance variable of the Symbol that represents that terminal or non-terminal. Hence, references to terminal and non-terminal values is direct, as opposed to the old CUP, where the labels referred to objects containing the value of the terminal or non-terminal.

For more information, refer to the manual on labels.

20. RESULT Value

The RESULT variable refers directly to the value of the non-terminal to which a rule reduces, rather than to the object on the parse stack. Hence, RESULT is of the same type the non-terminal to which it reduces, as declared in the non-terminal declaration. Again, the reference is direct, rather than to something that will contain the data.

For more information, refer to the manual on RESULT.

21. Position Propagation

For every label, two more variables are declared, which are the label plus left or the label plus right. These correspond to the left and right locations in the input stream to which that terminal or non-terminal came from. These values are propagated from the input terminals, so that the starting non-terminal should have a left value of 0 and a right value of the location of the last character read.

For more information, refer to the manual on positions.

22. Return Value

A call to parse() or debug_parse() returns a Symbol. This Symbol is the start non-terminal, so the value instance variable contains the final RESULT assignment.

23. Precedence

CUP now has precedenced terminals. a new declaration section, occurring between the terminal and non-terminal declarations and the grammar specifies the precedence and associativity of rules. The declarations are of the form:

precedence {left| right | nonassoc} terminal[, terminal ...];
<b>..</b>.


The terminals are assigned a precedence, where terminals on the same line have equal precedences, and the precedence declarations farther down the list of precedence declarations have higher precedence. left, right and nonassoc specify the associativity of these terminals. left associativity corresponds to a reduce on conflict, right to a shift on conflict, and nonassoc to an error on conflict. Hence, ambiguous grammars may now be used.

For more information, refer to the manual on precedence.

24. Contextual Precedence

Finally the new CUP adds contextual precedence. A production may be declare as followed:

lhs ::= {right hand side list of terminals, non-terminals and actions}
        %prec {terminal};


this production would then have a precedence equal to the terminal specified after the %prec. Hence, shift/reduce conflicts can be contextually resolved. Note that the %prec terminal part comes after all actions strings. It does not come before the last action string.

For more information, refer to the manual on contextual precedence. These changes implemented by: Frank Flannery Department of Computer Science Princeton University

25. Appendix D: Bugs

In this version of CUP it's difficult for the semantic action phrases (Java code attached to productions) to access the report_error method and other similar methods and objects defined in the parser code directive.

This is because the parsing tables (and parsing engine) are in one object (belonging to class parser or whatever name is specified by the -parser directive), and the semantic actions are in another object (of class CUP$actions).

However, there is a way to do it, though it's a bit inelegant. The action object has a private final field named parser that points to the parsing object. Thus, methods and instance variables of the parser can be accessed within semantic actions as:

parser.report_error(message,info);
x = parser.mydata;

Perhaps this will not be necessary in a future release, and that such methods and variables as report_error and mydata will be available directly from the semantic actions; we will achieve this by combining the "parser" object and the "actions" object together.

For a list of any other currently known bugs in CUP, see [http]http://www.cs.princeton.edu/~appel/modern/java/CUP/bugs.html.

26. Appendix E: Change log


0.9e

March 1996, Scott Hudson's original version.

0.10a

August 1996, several major changes to the interface.

0.10b

November 1996, fixes a few minor bugs.

0.10c

July 1997, fixes a bug related to precedence declarations.

0.10e

September 1997, fixes a bug introduced in 0.10c relating to nonassoc precedence. Thanks to Tony Hosking for reporting the bug and providing the fix. Also recognizes carriage-return character as white space and fixes a number of other small bugs.

0.10f

December 1997, was a maintenance release. The CUP source was cleaned up for JDK 1.1.

0.10g

March 1998, adds new features and fixes old bugs. The behavior of RESULT assignments was normalized, and a problem with implicit start productions was fixed. The CUP grammar was extended to allow array types for terminals and non-terminals, and a command-line flag was added to allow the generation of a symbol interface, rather than class. Bugs associated with multiple invocations of a single parser object and multiple CUP classes in one package have been stomped on. Documentation was updated, as well.

0.10h-0.10i

February 1999, are maintenance releases.

0.10j

July 1999, broadened the CUP input grammar to allow more flexibility and improved scanner integration via the java_cup.runtime.Scanner interface.

Java and HotJava are trademarks of Sun Microsystems, Inc., and refer to Sun's Java programming language and HotJava browser technologies. CUP is not sponsored by or affiliated with Sun Microsystems, Inc.



ID
Password
Join
Someone is unenthusiastic about your work.


sponsored by andamiro
sponsored by cdnetworks
sponsored by HP

Valid XHTML 1.0! Valid CSS! powered by MoniWiki
last modified 2005-01-07 03:56:47
Processing time 0.0259 sec