From 105d6a00835e62fd212ed10e21c89b742885b145 Mon Sep 17 00:00:00 2001 From: Michael Williamson Date: Mon, 5 Oct 2015 18:39:11 +0100 Subject: Create separate class for generating primitive methods in Python --- .../couscous/backends/python/PrimitiveMethods.java | 56 ++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 src/main/java/org/zwobble/couscous/backends/python/PrimitiveMethods.java (limited to 'src/main/java/org/zwobble/couscous/backends/python/PrimitiveMethods.java') diff --git a/src/main/java/org/zwobble/couscous/backends/python/PrimitiveMethods.java b/src/main/java/org/zwobble/couscous/backends/python/PrimitiveMethods.java new file mode 100644 index 0000000..129fb19 --- /dev/null +++ b/src/main/java/org/zwobble/couscous/backends/python/PrimitiveMethods.java @@ -0,0 +1,56 @@ +package org.zwobble.couscous.backends.python; + +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.zwobble.couscous.backends.python.ast.PythonExpressionNode; +import org.zwobble.couscous.values.StringValue; +import org.zwobble.couscous.values.TypeReference; + +import com.google.common.collect.ImmutableMap; + +import static java.util.Arrays.asList; +import static org.zwobble.couscous.backends.python.ast.PythonAttributeAccessNode.pythonAttributeAccess; +import static org.zwobble.couscous.backends.python.ast.PythonCallNode.pythonCall; +import static org.zwobble.couscous.backends.python.ast.PythonVariableReferenceNode.pythonVariableReference; + +public class PrimitiveMethods { + private static final Map STRING_METHODS = + ImmutableMap.builder() + + .put("length", (receiver, arguments) -> + pythonCall( + pythonVariableReference("len"), + asList(receiver))) + + .put("substring", (receiver, arguments) -> + pythonCall( + pythonAttributeAccess( + receiver, + "__getitem__"), + asList(pythonCall( + pythonVariableReference("slice"), + arguments)))) + + .build(); + + private static final Map> METHODS = + ImmutableMap.>builder() + .put(StringValue.REF, STRING_METHODS) + .build(); + + public static boolean isPrimitive(TypeReference type) { + return METHODS.containsKey(type); + } + + public static Optional getPrimitiveMethod(TypeReference type, String methodName) { + return Optional.ofNullable(METHODS.get(type)) + .flatMap(methodsForType -> Optional.ofNullable(methodsForType.get(methodName))); + } + + @FunctionalInterface + public interface PrimitiveMethodGenerator { + PythonExpressionNode generate(PythonExpressionNode receiver, List arguments); + } +} -- cgit v1.2.3