Demo entry 6318393

parser-genertor

   

Submitted by anonymous on Nov 07, 2016 at 05:31
Language: Swift. Code size: 1.8 kB.

// "a" followed by "b"
let rule = "a" ~ "b"

// "a" followed by "b", with possible whitespace in between
// to change what is considered whitespace, change the parser.whitespace rule
let rule = "a" ~~ "b"

// at least one "a", but possibly more
let rule = "a"++

// "a" or "b"
let rule = "a" | "b"

// "a" followed by something other than "b"
let rule = "a" ~ !"b"

// "a" followed by one or more "b"
let rule = "a" ~ "b"+

// "a" followed by zero or more "b"
let rule = "a" ~ "b"*

// "a" followed by a numeric digit
let rule = "a" ~ ("0"-"9")

// "a" followed by the rule named "blah"
let rule = "a" ~ ^"blah"

// "a" optionally followed by "b"
let rule = "a" ~ "b"/~

// "a" followed by the end of input
let rule = "a"*!*

// a single "," 
let rule = %","

// regular expression: consecutive word or space characters
let rule = %!"[\\w\\s]+"

  override func rules() {
      start_rule = (^"primary")*!*

      let number = ("0"-"9")+ => push
      add_named_rule("primary",   rule: ^"secondary" ~ (("+" ~ ^"secondary" => add) | ("-" ~ ^"secondary" => sub))*)
      add_named_rule("secondary", rule: ^"tertiary" ~ (("*" ~ ^"tertiary" => mul) | ("/" ~ ^"tertiary" => div))*)
      add_named_rule("tertiary",  rule: ("(" ~ ^"primary" ~ ")") | number)
  }

import SwiftParser
class Adder : Parser {
    var stack: Int[] = []

    func push() {
        stack.append(self.text.toInt()!)
    }

    func add() {
        let left = stack.removeLast()
        let right = stack.removeLast()

        stack.append(left + right)
    }

    override func rules() {
        let number = ("0"-"9")+ => push
        let expr = (number ~ "+" ~ number) => add

        start_rule = expr
    }
}

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).