summaryrefslogtreecommitdiff
path: root/docs/examples/parsing/lambda/TestParser.scala
blob: 22257c17319250df5093c767cf42d2e8665d4625 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package examples.parsing.lambda

import scala.util.parsing.input.Reader
import scala.util.parsing.combinator.lexical.StdLexical
import scala.util.parsing.combinator.syntactical.StdTokenParsers
import scala.util.parsing.combinator.ImplicitConversions

/**
 * Parser for an untyped lambda calculus
 *
 * @author Miles Sabin (adapted slightly by Adriaan Moors)
 */
trait TestParser extends StdTokenParsers  with ImplicitConversions with TestSyntax
{
  type Tokens = StdLexical
  val lexical = new StdLexical
  lexical.reserved ++= List("unit", "let", "in", "if", "then", "else")
  lexical.delimiters ++= List("=>", "->", "==", "(", ")", "=", "\\", "+", "-", "*", "/")


	def name : Parser[Name] = ident ^^ Name

  // meaning of the argumens to the closure during subsequent iterations
  // (...(expr2 op1 expr1) ... op1 expr1)
  //      ^a^^^ ^o^ ^b^^^
  //      ^^^^^^^a^^^^^^^      ^o^ ^^b^^
  def expr1 : Parser[Term] =
    chainl1(expr2, expr1, op1 ^^ {o => (a: Term, b: Term) => App(App(o, a), b)})

  def expr2 : Parser[Term] =
   chainl1(expr3, expr2, op2 ^^ {o => (a: Term, b: Term) => App(App(o, a), b)})

  def expr3 : Parser[Term] =
   chainl1(expr4, expr3, op3 ^^ {o => (a: Term, b: Term) => App(App(o, a), b)})

  def expr4 : Parser[Term] =
  ( "\\" ~> lambdas
  | ("let" ~> name) ~ ("=" ~> expr1) ~ ("in" ~> expr1) ^^ flatten3(Let)
  | ("if" ~> expr1) ~ ("then" ~> expr1) ~ ("else" ~> expr1) ^^ flatten3(If)
  | chainl1(aexpr, success(App(_: Term, _: Term)))
  )

  def lambdas : Parser[Term] =
    name ~ ("->" ~> expr1 | lambdas) ^^ flatten2(Lam)

  def aexpr : Parser[Term] =
  ( numericLit ^^ (_.toInt) ^^ Lit
  | name ^^ Ref
  | "unit" ^^^ Unit()
  | "(" ~> expr1 <~ ")"
  )

  def op1 : Parser[Term] =
    "=="  ^^^ Ref(Name("=="))

  def op2 : Parser[Term] =
  ( "+" ^^^ Ref(Name("+"))
  | "-" ^^^ Ref(Name("-"))
  )

  def op3 : Parser[Term] =
  ( "*" ^^^ Ref(Name("*"))
  | "/" ^^^ Ref(Name("/"))
  )

  def parse(r: Reader[char]) : ParseResult[Term] =
    phrase(expr1)(new lexical.Scanner(r))
}