1
0
forked from GitHub/gf-core

calculator ex

This commit is contained in:
aarne
2007-09-03 19:21:50 +00:00
parent ee9416d523
commit 14f185d326
3 changed files with 96 additions and 0 deletions

View File

@@ -0,0 +1,25 @@
abstract Calculator = {
flags startcat = Prog ;
cat Prog ; Exp ; Var ;
fun
PEmpty : Prog ;
PDecl : Exp -> (Var -> Prog) -> Prog ;
PAss : Var -> Exp -> Prog -> Prog ;
EPlus, EMinus, ETimes : Exp -> Exp -> Exp ;
EInt : Int -> Exp ;
EVar : Var -> Exp ;
ex1 : Prog ;
def
ex1 =
PDecl (EPlus (EInt 2) (EInt 3)) (\x ->
PDecl (EPlus (EVar x) (EInt 1)) (\y ->
PAss x (EPlus (EVar x) (ETimes (EInt 9) (EVar y))) PEmpty)) ;
}

View File

@@ -0,0 +1,47 @@
--# -path=.:prelude
concrete CalculatorC of Calculator = open Prelude in {
flags lexer=codevars ; unlexer=code ;
lincat
Prog, Var = SS ;
Exp = TermPrec ;
lin
PEmpty = ss [] ;
PDecl exp prog = ss ("int" ++ prog.$0 ++ "=" ++ exp.s ++ ";" ++ prog.s) ;
PAss vr exp prog = ss (vr.s ++ "=" ++ exp.s ++ ";" ++ prog.s) ;
EPlus = infixl 0 "+" ;
EMinus = infixl 0 "-" ;
ETimes = infixl 1 "*" ;
EInt i = constant i.s ;
EVar x = constant x.s ;
oper
Prec : PType = Predef.Ints 2 ;
TermPrec : Type = {s : Str ; p : Prec} ;
usePrec : TermPrec -> Prec -> Str = \x,p ->
case <<x.p,p> : Prec * Prec> of {
<1,1> | <1,0> | <0,0> => x.s ;
<1,_> | <0,_> => "(" ++ x.s ++ ")" ;
_ => x.s
} ;
mkPrec : Prec -> Str -> TermPrec = \p,s ->
{s = s ; p = p} ;
constant : Str -> TermPrec = mkPrec 2 ;
infixl : Prec -> Str -> (_,_ : TermPrec) -> TermPrec = \p,f,x,y ->
mkPrec p (usePrec x p ++ f ++ usePrec y (nextPrec p)) ;
nextPrec : Prec -> Prec = \p -> case <p : Prec> of {
2 => 2 ;
n => Predef.plus n 1
} ;
}

View File

@@ -0,0 +1,24 @@
--# -path=.:prelude
concrete CalculatorJ of Calculator = open Prelude in {
flags lexer=codevars ; unlexer=code ;
lincat
Prog, Exp, Var = SS ;
lin
PEmpty = ss [] ;
PDecl exp prog = ss (exp.s ++ ";" ++ prog.s) ;
PAss vr exp prog = ss (exp.s ++ ";" ++ "istore" ++ vr.s ++ ";" ++ prog.s) ;
EPlus = postfix "iadd" ;
EMinus = postfix "isub" ;
ETimes = postfix "imul" ;
EInt = prefixSS "iconst" ;
EVar = prefixSS "iload" ;
oper
postfix : Str -> SS -> SS -> SS = \op,x,y -> ss (x.s ++ ";" ++ y.s ++ ";" ++ op) ;
}