From 368fd234d5cb94a1b86e8258a83744e27f814a3e Mon Sep 17 00:00:00 2001 From: Michael Williamson Date: Wed, 6 Jan 2016 21:58:23 +0000 Subject: Allow concrete type builder to add constructors --- .../couscous/interpreter/values/ConcreteType.java | 23 +++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/main/java/org/zwobble/couscous/interpreter/values/ConcreteType.java b/src/main/java/org/zwobble/couscous/interpreter/values/ConcreteType.java index 6abb56c..9c688ab 100644 --- a/src/main/java/org/zwobble/couscous/interpreter/values/ConcreteType.java +++ b/src/main/java/org/zwobble/couscous/interpreter/values/ConcreteType.java @@ -27,6 +27,7 @@ public class ConcreteType { public static class Builder { private final ImmutableMap.Builder fields = ImmutableMap.builder(); + private MethodValue constructor = new MethodValue(ImmutableList.of(), (environment, arguments) -> InterpreterValues.UNIT); private final ImmutableMap.Builder methods = ImmutableMap.builder(); private final ImmutableMap.Builder staticMethods = ImmutableMap.builder(); private final Class interpreterValueType; @@ -42,13 +43,25 @@ public class ConcreteType { return this; } + public Builder constructor(List argumentsTypes, BiFunction, InterpreterValue> method) { + constructor = toMethodValue(argumentsTypes, method); + return this; + } + public Builder method(String name, List argumentsTypes, BiFunction, InterpreterValue> method) { - methods.put(new MethodSignature(name, argumentsTypes), new MethodValue(argumentsTypes, (environment, arguments) -> { - return Casts.tryCast(interpreterValueType, arguments.getReceiver()).map(typedReceiver -> method.apply(environment, MethodCallArguments.of(typedReceiver, arguments.getPositionalArguments()))).orElseThrow(() -> new RuntimeException("receiver is of wrong type")); - })); + methods.put(new MethodSignature(name, argumentsTypes), toMethodValue(argumentsTypes, method)); return this; } - + + private MethodValue toMethodValue(List argumentsTypes, BiFunction, InterpreterValue> method) { + return new MethodValue( + argumentsTypes, + (environment, arguments) -> + Casts.tryCast(interpreterValueType, arguments.getReceiver()) + .map(typedReceiver -> method.apply(environment, MethodCallArguments.of(typedReceiver, arguments.getPositionalArguments()))) + .orElseThrow(() -> new RuntimeException("receiver is of wrong type"))); + } + public Builder staticMethod(String name, List argumentsTypes, BiFunction method) { staticMethods.put(new MethodSignature(name, argumentsTypes), new StaticMethodValue(argumentsTypes, method)); return this; @@ -59,7 +72,7 @@ public class ConcreteType { name, Collections.emptySet(), fields.build(), - new MethodValue(ImmutableList.of(), (environment, arguments) -> InterpreterValues.UNIT), + constructor, methods.build(), staticMethods.build()); } -- cgit v1.2.3