49 lines
2.0 KiB
Java
49 lines
2.0 KiB
Java
package io.gitlab.jfronny.muscript.test;
|
|
|
|
import io.gitlab.jfronny.muscript.data.additional.DFinal;
|
|
import io.gitlab.jfronny.muscript.data.additional.context.Scope;
|
|
import io.gitlab.jfronny.muscript.parser.Parser;
|
|
import org.junit.jupiter.api.Test;
|
|
|
|
import static io.gitlab.jfronny.muscript.ast.context.ExprUtils.asDynamic;
|
|
import static io.gitlab.jfronny.muscript.runtime.Runtime.evaluate;
|
|
import static io.gitlab.jfronny.muscript.runtime.Runtime.run;
|
|
import static io.gitlab.jfronny.muscript.test.util.MuTestUtil.*;
|
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
|
|
|
class ClosureTest {
|
|
@Test
|
|
void testScript() {
|
|
assertEquals(8, run(parseScript("function(2, 1); function(2, 2); function(2, 3)"), makeArgs())
|
|
.asNumber()
|
|
.getValue());
|
|
}
|
|
|
|
@Test
|
|
void testClosure() {
|
|
assertEquals(2, number("{->2}()"));
|
|
assertEquals(2, number("{n->n}(2)"));
|
|
assertEquals(2, number("{n->n()}({->2})"));
|
|
assertThrows(Parser.ParseException.class, () -> number("{->num = 2 num = num * 2 num = num - 2}()"));
|
|
assertEquals(2, number("{->num = 2; num = num * 2; num = num - 2}()"));
|
|
}
|
|
|
|
@Test
|
|
void fizzbuzzInμScriptByEmbeddingADomainSpecificLanguage() {
|
|
var fn = evaluate(asDynamic(parse("""
|
|
{ n ->
|
|
test = { b, s, o -> n % b == 0 ? { _ -> s || o('')} : o }
|
|
fizz = { o -> test(3, 'Fizz', o) }
|
|
buzz = { o -> test(5, 'Buzz', o) }
|
|
fizz(buzz({n -> n}))(n)
|
|
}
|
|
""")), new Scope())
|
|
.asCallable();
|
|
assertEquals("8", fn.call(DFinal.of(8)).asString().getValue());
|
|
assertEquals("Buzz", fn.call(DFinal.of(10)).asString().getValue());
|
|
assertEquals("Fizz", fn.call(DFinal.of(12)).asString().getValue());
|
|
assertEquals("FizzBuzz", fn.call(DFinal.of(15)).asString().getValue());
|
|
}
|
|
}
|