From c58796cf60fcb109ab56ae2b1c0872c58771f3e1 Mon Sep 17 00:00:00 2001 From: Michael Williamson Date: Wed, 30 Mar 2016 19:58:01 +0100 Subject: Add code generation for Python backend for arrays --- .../backends/python/PythonCodeGeneratorTests.java | 62 ++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 src/test/java/org/zwobble/couscous/tests/backends/python/PythonCodeGeneratorTests.java (limited to 'src/test/java/org') diff --git a/src/test/java/org/zwobble/couscous/tests/backends/python/PythonCodeGeneratorTests.java b/src/test/java/org/zwobble/couscous/tests/backends/python/PythonCodeGeneratorTests.java new file mode 100644 index 0000000..1b043bc --- /dev/null +++ b/src/test/java/org/zwobble/couscous/tests/backends/python/PythonCodeGeneratorTests.java @@ -0,0 +1,62 @@ +package org.zwobble.couscous.tests.backends.python; + +import org.hamcrest.FeatureMatcher; +import org.hamcrest.Matcher; +import org.junit.Test; +import org.zwobble.couscous.backends.python.PythonCodeGenerator; +import org.zwobble.couscous.backends.python.ast.PythonArrayNode; +import org.zwobble.couscous.backends.python.ast.PythonExpressionNode; +import org.zwobble.couscous.backends.python.ast.PythonStringLiteralNode; +import org.zwobble.couscous.types.Types; + +import java.util.List; +import java.util.function.Function; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; +import static org.zwobble.couscous.ast.ArrayNode.array; +import static org.zwobble.couscous.ast.LiteralNode.literal; +import static org.zwobble.couscous.util.ExtraLists.list; + +public class PythonCodeGeneratorTests { + @Test + public void arrayIsConvertedToPythonList() { + assertThat( + PythonCodeGenerator.generateExpression(array(Types.STRING, list( + literal("one"), + literal("two")))), + isPythonList(list(isPythonLiteral("one"), isPythonLiteral("two")))); + } + + private Matcher isPythonLiteral(String value) { + return isA(PythonStringLiteralNode.class, hasFeature( + "value", + node -> node.getValue(), + equalTo(value))); + } + + private static Matcher isA(Class type, Matcher downcastMatcher) { + return allOf(instanceOf(type), (Matcher) downcastMatcher); + } + + private static Matcher isPythonList( + List> expectedElements) + { + return isA(PythonArrayNode.class, hasFeature( + "elements", + list -> list.getElements(), + contains(expectedElements))); + } + + private static Matcher hasFeature( + String name, + Function extract, + Matcher subMatcher) { + return new FeatureMatcher(subMatcher, name, name) { + @Override + protected U featureValueOf(T actual) { + return extract.apply(actual); + } + }; + } +} -- cgit v1.2.3