progs/fun-bare.scala
changeset 628 8067d0a8ba04
parent 625 6709fa87410b
child 639 217e66d7aeff
equal deleted inserted replaced
627:f5214da1976e 628:8067d0a8ba04
     1 // A Small Compiler for a Simple Functional Language
     1 // A Small Compiler for a Simple Functional Language
     2 // (it does not use a parser and lexer)
     2 // (it does not include a parser and lexer)
     3 
     3 
     4 // Abstract syntax trees
     4 // Abstract syntax trees
     5 abstract class Exp
     5 abstract class Exp
     6 abstract class BExp 
     6 abstract class BExp 
     7 abstract class Decl
     7 abstract class Decl
    68 def Fresh(x: String) = {
    68 def Fresh(x: String) = {
    69   counter += 1
    69   counter += 1
    70   x ++ "_" ++ counter.toString()
    70   x ++ "_" ++ counter.toString()
    71 }
    71 }
    72 
    72 
    73 // convenient string interpolations 
    73 // convenient string interpolations for
    74 // for instructions, labels and methods
    74 // generating instructions, labels etc
    75 import scala.language.implicitConversions
    75 import scala.language.implicitConversions
    76 import scala.language.reflectiveCalls
    76 import scala.language.reflectiveCalls
    77 
    77 
    78 implicit def sring_inters(sc: StringContext) = new {
    78 implicit def sring_inters(sc: StringContext) = new {
    79     def i(args: Any*): String = "   " ++ sc.s(args:_*) ++ "\n"
    79   def i(args: Any*): String = "   " ++ sc.s(args:_*) ++ "\n"
    80     def l(args: Any*): String = sc.s(args:_*) ++ ":\n"
    80   def l(args: Any*): String = sc.s(args:_*) ++ ":\n"
    81     def m(args: Any*): String = sc.s(args:_*) ++ "\n"
    81   def m(args: Any*): String = sc.s(args:_*) ++ "\n"
    82 }
    82 }
    83 
    83 
       
    84 // variable / index environments
    84 type Env = Map[String, Int]
    85 type Env = Map[String, Int]
    85 
    86 
    86 // compile expressions
    87 // compile expressions
    87 def compile_exp(a: Exp, env : Env) : String = a match {
    88 def compile_exp(a: Exp, env : Env) : String = a match {
    88   case Num(i) => i"ldc $i"
    89   case Num(i) => i"ldc $i"