From 1cfa806548d63fa13925e2116d579ff0b5dee7bc Mon Sep 17 00:00:00 2001 From: Michael Williamson Date: Mon, 5 Oct 2015 18:27:35 +0100 Subject: Add support for String::substring to Python backend --- .../backends/python/PythonCodeGenerator.java | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) (limited to 'src/main/java/org') diff --git a/src/main/java/org/zwobble/couscous/backends/python/PythonCodeGenerator.java b/src/main/java/org/zwobble/couscous/backends/python/PythonCodeGenerator.java index 023d257..067e826 100644 --- a/src/main/java/org/zwobble/couscous/backends/python/PythonCodeGenerator.java +++ b/src/main/java/org/zwobble/couscous/backends/python/PythonCodeGenerator.java @@ -1,5 +1,6 @@ package org.zwobble.couscous.backends.python; +import java.util.List; import java.util.stream.Collectors; import org.zwobble.couscous.ast.AssignmentNode; @@ -159,17 +160,25 @@ public class PythonCodeGenerator { if (isPrimitive(methodCall.getReceiver())) { val isStringLength = methodCall.getReceiver().getType().equals(StringValue.REF) && methodCall.getMethodName() == "length"; + val isSubstring = methodCall.getReceiver().getType().equals(StringValue.REF) && + methodCall.getMethodName() == "substring"; if (isStringLength) { return pythonCall( pythonVariableReference("len"), asList(generateExpression(methodCall.getReceiver()))); + } else if (isSubstring) { + return pythonCall( + pythonAttributeAccess( + generateExpression(methodCall.getReceiver()), + "__getitem__"), + asList(pythonCall( + pythonVariableReference("slice"), + generateArguments(methodCall)))); } else { throw new UnsupportedOperationException(); } } else { - val arguments = methodCall.getArguments().stream() - .map(PythonCodeGenerator::generateExpression) - .collect(Collectors.toList()); + val arguments = generateArguments(methodCall); return pythonCall( pythonAttributeAccess( generateExpression(methodCall.getReceiver()), @@ -178,6 +187,13 @@ public class PythonCodeGenerator { } } + private List generateArguments( + MethodCallNode methodCall) { + return methodCall.getArguments().stream() + .map(PythonCodeGenerator::generateExpression) + .collect(Collectors.toList()); + } + @Override public PythonExpressionNode visit(StaticMethodCallNode staticMethodCall) { throw new UnsupportedOperationException(); -- cgit v1.2.3