Mork Banner
Home
Small example
Large example
Tools
Links
Misc
Contributions
Download ChangeLog Mailing list Manual Sourceforge Feedback

Small example

Here's a calculator to compute expressions like 17+5*7. It's realized by a Java file, a grammar file and a mapper file. Compile and run it as follows:

  cd examples/calc
  javac Main.java
  mork Mapper.map
  java calc.Main

Main.java

package calc;

import de.mlhartme.mork.mapping.Mapper;
import de.mlhartme.mork.util.GenericException;

/**
 * Calculate simple expression.
 * A kind of Hello-World example for tools like Mork.
 */

public class Main {
    public static void main(String[] args) {
        Mapper mapper;

        mapper = new Mapper("calc.Mapper");
        System.out.println("(press ctrl-c to quit)");
        mapper.repl("> ", null);
    }

    public static int expr(int result) {
        return result;
    }

    public static int add(int left, int right) {
        return left + right;
    }

    public static int sub(int left, int right) {
        return left - right;
    }

    public static int mult(int left, int right) {
        return left * right;
    }

    public static int div(int left, int right) throws GenericException {
        if (right == 0) {
            throw new GenericException("division by zero");
        }
        return left / right;
    }
}


expression.grm

[PARSER]

Expr      ::= Sum ;
Sum       ::= Add | Sub | Prod ;
Add       ::= Sum "+" Prod ;
Sub       ::= Sum "-" Prod ;
Prod      ::= Mult | Div | Atom ;
Mult      ::= Prod "*" Atom ;
Div       ::= Prod "/" Atom ;
Atom      ::= Num | "(" Sum ")" ;
Num       ::= DIGITS ;

[SCANNER]
    white = SPACE, COMMENT;

SPACE     ::= ('\u0020' | '\b' | '\t' | '\n' | '\f' | '\r' )+ ;
COMMENT   ::= '#' '\u0020'..'\u007f'* ('\n'|'\r') ;
DIGITS    ::= '0'..'9'+ ;



Mapper.map

mapper calc.Mapper;

grm = "expression.grm";

import calc:
    Main;
import java.lang:
    Integer;

Expr      => Main.expr;
Add       => Main.add;
Sub       => Main.sub;
Mult      => Main.mult;
Div       => Main.div;
Num       => Integer.parseInt;
DIGITS    => [text];



Last modified: Fri Mar 29 20:48:06 2002.

Copyright © 2002 Michael Hartmeier.

Hosted at SourceForge.net Logo