Skip to content

Commit

Permalink
string repetition (x) operator
Browse files Browse the repository at this point in the history
  • Loading branch information
prakashk committed Feb 28, 2013
1 parent 0a82bfa commit 36c8be6
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/main/scala/org/moe/parser/Expressions.scala
Expand Up @@ -25,7 +25,7 @@ trait Expressions extends Literals with JavaTokenParsers with PackratParsers {
case left ~ op ~ right => BinaryOpNode(left, op, right)
}| mulOp

lazy val mulOp: PackratParser[AST] = mulOp ~ "[*/%]".r ~ expOp ^^ {
lazy val mulOp: PackratParser[AST] = mulOp ~ "[*/%x]".r ~ expOp ^^ {
case left ~ op ~ right => BinaryOpNode(left, op, right)
} | expOp

Expand Down
11 changes: 11 additions & 0 deletions src/main/scala/org/moe/runtime/builtins/StrClass.scala
Expand Up @@ -58,6 +58,17 @@ object StrClass {
)
)

// repetition

strClass.addMethod(
new MoeMethod(
"infix:<x>",
new MoeSignature(List(new MoeParameter("$other"))),
env,
(e) => e.getCurrentInvocant.get.asInstanceOf[MoeStrObject].repeat(r, e.get("$other").get)
)
)

/**
* List of Operators to support:
* - infix:<.>
Expand Down
Expand Up @@ -15,6 +15,12 @@ class MoeStrObject(
def concat (r: MoeRuntime, other: MoeObject): MoeObject =
r.NativeObjects.getStr(getNativeValue + other.unboxToString.get)

def repeat (r: MoeRuntime, other: MoeObject): MoeObject = {
val str = getNativeValue
val n = other.unboxToInt.get
r.NativeObjects.getStr(List.fill(n)(str).reduce((x, y) => x + y))
}

// MoeObject overrides

override def isFalse: Boolean = getNativeValue match {
Expand Down
20 changes: 20 additions & 0 deletions src/test/scala/org/moe/parser/SimpleExpressionStrTestSuite.scala
Expand Up @@ -21,4 +21,24 @@ class SimpleExpressionStrTestSuite extends FunSuite with BeforeAndAfter with Par
result.unboxToString.get should equal ("foobar")
}

test("... literal string concatenation ... ['1' . 2]") {
val result = interpretCode("'1' . 2")
result.unboxToString.get should equal ("12")
}

test("... literal string concatenation ... ['1' . 2 * 3]") {
val result = interpretCode("'1' . 2 * 3")
result.unboxToString.get should equal ("16")
}

test("""... literal string repetition ... ["Moe" x 5]""") {
val result = interpretCode(""""Moe" x 5""")
result.unboxToString.get should equal ("MoeMoeMoeMoeMoe")
}

test("""... literal string repetition ... ["Moe" x "5"]""") {
val result = interpretCode(""""Moe" x "5"""")
result.unboxToString.get should equal ("MoeMoeMoeMoeMoe")
}

}

0 comments on commit 36c8be6

Please sign in to comment.