Skip to content

Commit

Permalink
moving the array indexing code into the Array class
Browse files Browse the repository at this point in the history
  • Loading branch information
Stevan Little committed Feb 13, 2013
1 parent 4e3fd2a commit af38e09
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 12 deletions.
21 changes: 9 additions & 12 deletions src/main/scala/org/moe/interpreter/Interpreter.scala
Expand Up @@ -64,21 +64,18 @@ class Interpreter {
case ArrayElementAccessNode(arrayName: String, index: AST) => {
val index_result = eval(runtime, env, index)
val array_value = env.get(arrayName) match {
case Some(a: MoeArrayObject) => a.getNativeValue
case Some(a: MoeArrayObject) => a
case _ => throw new MoeErrors.UnexpectedType("MoeArrayObject expected")
}

// TODO: ListBuffer probably, like stevan said - JM
var native_index = objToInteger(index_result)
while (native_index < 0) {
native_index += array_value.size
}
try {
array_value(native_index)
}
catch {
case _: java.lang.IndexOutOfBoundsException => runtime.NativeObjects.getUndef // TODO: warn
}
array_value.callMethod(
array_value.getAssociatedClass.getOrElse(
throw new MoeErrors.ClassNotFound("Array")
).getMethod("postcircumfix:<[]>").getOrElse(
throw new MoeErrors.MethodNotFound("postcircumfix:<[]>")
),
List(index_result)
)
}

case PairLiteralNode(key, value) => runtime.NativeObjects.getPair(eval(runtime, env, key) -> eval(runtime, env, value))
Expand Down
25 changes: 25 additions & 0 deletions src/main/scala/org/moe/runtime/builtins/ArrayClass.scala
@@ -1,6 +1,7 @@
package org.moe.runtime.builtins

import org.moe.runtime._
import org.moe.interpreter.InterpreterUtils._

/**
* setup class Array
Expand All @@ -12,6 +13,30 @@ object ArrayClass {
throw new MoeErrors.MoeStartupError("Could not find class Array")
)

// basic access
arrayClass.addMethod(
new MoeMethod(
"postcircumfix:<[]>",
{ (invocant, args) =>

var index = objToInteger(args(0))
val array = invocant match {
case a: MoeArrayObject => a.getNativeValue
case _ => throw new MoeErrors.UnexpectedType("MoeArrayObject expected")
}

while (index < 0) {
index += array.size
}

try {
array(index)
} catch {
case _: java.lang.IndexOutOfBoundsException => r.NativeObjects.getUndef // TODO: warn
}
}
)
)
}

}

0 comments on commit af38e09

Please sign in to comment.