Omawiamy przykład, np. kalkulator dla ONP
%{ #define YYDEBUG 1 #include <stdio.h> double atof(const char *s); int yylex(); void yyerror(const char *s); #define YYSTYPE double %} %token NUM %% input: /* empty */ | input line ; line: '\n' | exp '\n' { printf("\t%.10g\n", $1);} ; exp: NUM { $$ = $1; } | exp exp '+' { $$ = $1 + $2; } | exp exp '-' { $$ = $1 - $2; } | exp exp '*' { $$ = $1 * $2; } | exp exp '/' { $$ = $1 / $2; } %% void yyerror(const char * s) { puts(s); } int main() { yydebug=0; /* 1 for debugging */ yyparse(); }
Omwiamy przykład, np.
import java_cup.runtime.*; terminal Integer NUM; terminal SEMI, PLUS, STAR; non terminal prog; non terminal Integer exp; prog ::= exp:e {: System.out.println("value = " + e); :} SEMI ; exp ::= NUM:n {: RESULT = n; :} | exp:e1 exp:e2 PLUS {: RESULT = new Integer(e1.intValue() + e2.intValue()); :} | exp:e1 exp:e2 STAR {: RESULT = new Integer(e1.intValue() * e2.intValue()); :} ;
Omawiamy przykład np.
{ module Main where import Data.Char } %name calc %tokentype { Token } %error { parseError } %token int { TokenInt $$ } '+' { TokenPlus } '*' { TokenTimes } %% Exp : Exp Exp '+' { $1 + $2 } | Exp Exp '*' { $1 * $2 } | int { $1 } ; { parseError :: [Token] -> a parseError _ = error "Parse error" data Token = TokenInt Int | TokenPlus | TokenTimes deriving Show lexer :: String -> [Token] lexer [] = [] lexer (c:cs) | isSpace c = lexer cs | isDigit c = lexNum (c:cs) lexer ('+':cs) = TokenPlus : lexer cs lexer ('*':cs) = TokenTimes : lexer cs lexNum cs = TokenInt (read num) : lexer rest where (num,rest) = span isDigit cs main = getContents >>= print . calc . lexer }
E -> E + T | T ...