From 924ec66ffaf86d41c6eda1ba4b45564f1aa20710 Mon Sep 17 00:00:00 2001 From: f0gel Date: Mon, 1 Jul 2024 15:28:21 +0200 Subject: [PATCH 01/14] CBuilder Unit Tests --- src/test/java/CBuilder/TestReference.java | 47 +++ .../java/CBuilder/TestWithCToolchains.java | 2 + .../java/CBuilder/bool/TestAndKeyword.java | 48 +++ .../java/CBuilder/bool/TestNotKeyword.java | 59 ++++ .../java/CBuilder/bool/TestOrKeyword.java | 45 +++ .../conditions/TestIfThenElseStatement.java | 63 ++++ .../TestElifStatement.java | 73 ++++ .../TestElseStatement.java | 55 ++++ .../conditionalStatement/TestIfStatement.java | 75 +++++ .../TestWhileStatement.java | 95 ++++++ .../CBuilder/literals/TestBoolLiteral.java | 52 +++ .../CBuilder/literals/TestIntLiteral.java | 53 +++ .../CBuilder/literals/TestStringLiteral.java | 52 +++ .../CBuilder/literals/TestTupleLiteral.java | 77 +++++ .../objects/TestAttributeAssignment.java | 47 +++ .../objects/TestAttributeReference.java | 120 +++++++ src/test/java/CBuilder/objects/TestCall.java | 66 ++++ .../java/CBuilder/objects/TestMPyClass.java | 311 ++++++++++++++++++ .../java/CBuilder/objects/TestSuperCall.java | 64 ++++ .../objects/functions/TestArgument.java | 60 ++++ .../objects/functions/TestFunction.java | 231 +++++++++++++ .../functions/TestReturnStatement.java | 50 +++ .../CBuilder/variables/TestAssignment.java | 125 +++++++ .../variables/TestVariableDeclaration.java | 101 ++++++ 24 files changed, 1971 insertions(+) create mode 100644 src/test/java/CBuilder/TestReference.java create mode 100644 src/test/java/CBuilder/bool/TestAndKeyword.java create mode 100644 src/test/java/CBuilder/bool/TestNotKeyword.java create mode 100644 src/test/java/CBuilder/bool/TestOrKeyword.java create mode 100644 src/test/java/CBuilder/conditions/TestIfThenElseStatement.java create mode 100644 src/test/java/CBuilder/conditions/conditionalStatement/TestElifStatement.java create mode 100644 src/test/java/CBuilder/conditions/conditionalStatement/TestElseStatement.java create mode 100644 src/test/java/CBuilder/conditions/conditionalStatement/TestIfStatement.java create mode 100644 src/test/java/CBuilder/conditions/conditionalStatement/TestWhileStatement.java create mode 100644 src/test/java/CBuilder/literals/TestBoolLiteral.java create mode 100644 src/test/java/CBuilder/literals/TestIntLiteral.java create mode 100644 src/test/java/CBuilder/literals/TestStringLiteral.java create mode 100644 src/test/java/CBuilder/literals/TestTupleLiteral.java create mode 100644 src/test/java/CBuilder/objects/TestAttributeAssignment.java create mode 100644 src/test/java/CBuilder/objects/TestAttributeReference.java create mode 100644 src/test/java/CBuilder/objects/TestCall.java create mode 100644 src/test/java/CBuilder/objects/TestMPyClass.java create mode 100644 src/test/java/CBuilder/objects/TestSuperCall.java create mode 100644 src/test/java/CBuilder/objects/functions/TestArgument.java create mode 100644 src/test/java/CBuilder/objects/functions/TestFunction.java create mode 100644 src/test/java/CBuilder/objects/functions/TestReturnStatement.java create mode 100644 src/test/java/CBuilder/variables/TestAssignment.java create mode 100644 src/test/java/CBuilder/variables/TestVariableDeclaration.java diff --git a/src/test/java/CBuilder/TestReference.java b/src/test/java/CBuilder/TestReference.java new file mode 100644 index 0000000..1603d89 --- /dev/null +++ b/src/test/java/CBuilder/TestReference.java @@ -0,0 +1,47 @@ +/* (C)2024 */ +package CBuilder; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TestReference { + String testClass = "[REFERENCE]\n"; + + private static Stream sources() { + return Stream.of("ref1", "ref2"); + } + + @ParameterizedTest + @MethodSource("sources") + void constructor(String name) { + Reference ref = new Reference(name); + + System.out.println(testClass + ref.getName()); + + assertEquals(name, ref.getName()); + } + + @ParameterizedTest + @MethodSource("sources") + void build_expression(String name) { + Reference ref = new Reference(name); + + System.out.println(testClass + ref.buildExpression()); + + assertEquals(name, ref.buildExpression()); + } + + @ParameterizedTest + @MethodSource("sources") + void build_statement(String name) { + Reference ref = new Reference(name); + + System.out.println(testClass + ref.buildStatement()); + + assertEquals(name + ";\n", ref.buildStatement()); + } +} diff --git a/src/test/java/CBuilder/TestWithCToolchains.java b/src/test/java/CBuilder/TestWithCToolchains.java index b58ca95..b2131d2 100644 --- a/src/test/java/CBuilder/TestWithCToolchains.java +++ b/src/test/java/CBuilder/TestWithCToolchains.java @@ -1,5 +1,6 @@ package CBuilder; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; @@ -11,6 +12,7 @@ import static CBuilder.ManualTest.generateProgram; import static org.junit.jupiter.api.Assertions.assertEquals; +@Disabled public class TestWithCToolchains { private void generateAndCompileProgram(Path outputDirectory) throws IOException, InterruptedException { diff --git a/src/test/java/CBuilder/bool/TestAndKeyword.java b/src/test/java/CBuilder/bool/TestAndKeyword.java new file mode 100644 index 0000000..aa0e7b8 --- /dev/null +++ b/src/test/java/CBuilder/bool/TestAndKeyword.java @@ -0,0 +1,48 @@ +/* (C)2024 */ +package CBuilder.bool; + +import CBuilder.keywords.bool.AndKeyword; +import CBuilder.literals.IntLiteral; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Snapshot 23.02.2024 + */ +public class TestAndKeyword { + String testClass = "[ANDKEYWORD]\n"; + + /** + *

1 && 1

+ */ + @Test + void build_expression() { + String expected = + "__mpy_obj_init_boolean(__mpy_boolean_raw(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_int(1)," + + " \"__bool__\"), __mpy_obj_init_tuple(0), NULL)) &&" + + " __mpy_boolean_raw(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_int(1)," + + " \"__bool__\"), __mpy_obj_init_tuple(0), NULL)))"; + + AndKeyword andK = new AndKeyword(new IntLiteral(1), new IntLiteral(1)); + + System.out.println(testClass + andK.buildExpression()); + + assertEquals(expected, andK.buildExpression()); + } + + @Test + void build_statement() { + String expected = + "__mpy_obj_ref_dec(__mpy_obj_init_boolean(__mpy_boolean_raw(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_int(1)," + + " \"__bool__\"), __mpy_obj_init_tuple(0), NULL)) &&" + + " __mpy_boolean_raw(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_int(1)," + + " \"__bool__\"), __mpy_obj_init_tuple(0), NULL))));\n"; + + AndKeyword andK = new AndKeyword(new IntLiteral(1), new IntLiteral(1)); + + System.out.println(testClass + andK.buildStatement()); + + assertEquals(expected, andK.buildStatement()); + } +} diff --git a/src/test/java/CBuilder/bool/TestNotKeyword.java b/src/test/java/CBuilder/bool/TestNotKeyword.java new file mode 100644 index 0000000..ef4e781 --- /dev/null +++ b/src/test/java/CBuilder/bool/TestNotKeyword.java @@ -0,0 +1,59 @@ +/* (C)2024 */ +package CBuilder.bool; + +import CBuilder.keywords.bool.NotKeyword; +import CBuilder.literals.BoolLiteral; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Parameterized tests not really useful here. + * Snapshot 22.02.2024 + */ +public class TestNotKeyword { + String testClass = "[NOTKEYWORD]\n"; + + private static Stream sources() { + return Stream.of(true, false); + } + + /** + * @param b_value - Boolean + */ + @ParameterizedTest + @MethodSource("sources") + void build_expression(boolean b_value) { + String expected = + "__mpy_obj_init_boolean(!__mpy_boolean_raw(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_boolean(" + + b_value + + "), \"__bool__\"), __mpy_obj_init_tuple(0), NULL)))"; + + NotKeyword notK = new NotKeyword(new BoolLiteral(b_value)); + + System.out.println(testClass + notK.buildExpression()); + + assertEquals(expected, notK.buildExpression()); + } + + /** + * @param b_value - Boolean + */ + @ParameterizedTest + @MethodSource("sources") + void build_statement(Boolean b_value) { + String expected = + "__mpy_obj_ref_dec(__mpy_obj_init_boolean(!__mpy_boolean_raw(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_boolean(" + + b_value + + "), \"__bool__\"), __mpy_obj_init_tuple(0), NULL))));\n"; + + NotKeyword notK = new NotKeyword(new BoolLiteral(b_value)); + + System.out.println(testClass + notK.buildStatement()); + + assertEquals(expected, notK.buildStatement()); + } +} diff --git a/src/test/java/CBuilder/bool/TestOrKeyword.java b/src/test/java/CBuilder/bool/TestOrKeyword.java new file mode 100644 index 0000000..5e14751 --- /dev/null +++ b/src/test/java/CBuilder/bool/TestOrKeyword.java @@ -0,0 +1,45 @@ +/* (C)2024 */ +package CBuilder.bool; + +import CBuilder.keywords.bool.OrKeyword; +import CBuilder.literals.BoolLiteral; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Snapshot 23.02.2024 + */ +public class TestOrKeyword { + String testClass = "[ORKEYWORD]\n"; + + @Test + void build_expression() { + String expected = + "__mpy_obj_init_boolean(__mpy_boolean_raw(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_boolean(true)," + + " \"__bool__\"), __mpy_obj_init_tuple(0), NULL)) ||" + + " __mpy_boolean_raw(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_boolean(false)," + + " \"__bool__\"), __mpy_obj_init_tuple(0), NULL)))"; + + OrKeyword orK = new OrKeyword(new BoolLiteral(true), new BoolLiteral(false)); + + System.out.println(testClass + orK.buildExpression()); + + assertEquals(expected, orK.buildExpression()); + } + + @Test + void build_statement() { + String expected = + "__mpy_obj_ref_dec(__mpy_obj_init_boolean(__mpy_boolean_raw(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_boolean(true)," + + " \"__bool__\"), __mpy_obj_init_tuple(0), NULL)) ||" + + " __mpy_boolean_raw(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_boolean(false)," + + " \"__bool__\"), __mpy_obj_init_tuple(0), NULL))));\n"; + + OrKeyword orK = new OrKeyword(new BoolLiteral(true), new BoolLiteral(false)); + + System.out.println(testClass + orK.buildStatement()); + + assertEquals(expected, orK.buildStatement()); + } +} diff --git a/src/test/java/CBuilder/conditions/TestIfThenElseStatement.java b/src/test/java/CBuilder/conditions/TestIfThenElseStatement.java new file mode 100644 index 0000000..249bb6e --- /dev/null +++ b/src/test/java/CBuilder/conditions/TestIfThenElseStatement.java @@ -0,0 +1,63 @@ +/* (C)2024 */ +package CBuilder.conditions; + +import CBuilder.conditions.conditionalStatement.ElifStatement; +import CBuilder.conditions.conditionalStatement.ElseStatement; +import CBuilder.conditions.conditionalStatement.IfStatement; +import CBuilder.literals.BoolLiteral; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.List; +import java.util.Optional; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TestIfThenElseStatement { + String testClass = "[IFTHENELSESTATEMENT]\n"; + + private static Stream sources_build_statement() { + return Stream.of( + Arguments.of( + new IfStatement(new BoolLiteral(true), List.of()), + Optional.of(List.of(new ElifStatement(new BoolLiteral(true), List.of()))), + Optional.of(new ElseStatement(List.of())), + """ + if (__mpy_boolean_raw(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_boolean(true), "__bool__"), __mpy_obj_init_tuple(0), NULL))) { + }else if (__mpy_boolean_raw(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_boolean(true), "__bool__"), __mpy_obj_init_tuple(0), NULL))) { + }else { + }"""), + Arguments.of( + new IfStatement(new BoolLiteral(true), List.of()), + Optional.empty(), + Optional.of(new ElseStatement(List.of())), + """ + if (__mpy_boolean_raw(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_boolean(true), "__bool__"), __mpy_obj_init_tuple(0), NULL))) { + }else { + }"""), + Arguments.of( + new IfStatement(new BoolLiteral(true), List.of()), + Optional.empty(), + Optional.empty(), + "if (__mpy_boolean_raw(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_boolean(true)," + + " \"__bool__\"), __mpy_obj_init_tuple(0), NULL))) {\n" + + "}")); + } + + @ParameterizedTest + @MethodSource("sources_build_statement") + void build_statement( + IfStatement ifStatement, + Optional> elifStatementList, + Optional elseStatement, + String expected) { + IfThenElseStatement ifThenElseS = + new IfThenElseStatement(ifStatement, elifStatementList, elseStatement); + + System.out.println(testClass + ifThenElseS.buildStatement()); + + assertEquals(expected, ifThenElseS.buildStatement()); + } +} diff --git a/src/test/java/CBuilder/conditions/conditionalStatement/TestElifStatement.java b/src/test/java/CBuilder/conditions/conditionalStatement/TestElifStatement.java new file mode 100644 index 0000000..9ba4df6 --- /dev/null +++ b/src/test/java/CBuilder/conditions/conditionalStatement/TestElifStatement.java @@ -0,0 +1,73 @@ +/* (C)2024 */ +package CBuilder.conditions.conditionalStatement; + +import CBuilder.Expression; +import CBuilder.Statement; +import CBuilder.literals.BoolLiteral; +import CBuilder.literals.IntLiteral; +import CBuilder.objects.AttributeReference; +import CBuilder.objects.Call; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.List; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +public class TestElifStatement { + String testClass = "[ELIFSTATEMENT]\n"; + + private static Stream sources_build() { + return Stream.of( + Arguments.of( + new BoolLiteral(true), + List.of(), + "else if" + + " (__mpy_boolean_raw(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_boolean(true)," + + " \"__bool__\"), __mpy_obj_init_tuple(0), NULL))) {\n" + + "}"), + Arguments.of( + new BoolLiteral(true), + List.of( + new Call( + new AttributeReference("__add__", new IntLiteral(1)), + List.of(new Expression[] {new IntLiteral(3)}))), + """ + else if (__mpy_boolean_raw(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_boolean(true), "__bool__"), __mpy_obj_init_tuple(0), NULL))) { + \t__mpy_obj_ref_dec(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_int(1), "__add__"), __mpy_tuple_assign(0, __mpy_obj_init_int(3), __mpy_obj_init_tuple(1)), NULL)); + }"""), + Arguments.of( + new BoolLiteral(false), + List.of( + new Call( + new AttributeReference("__add__", new IntLiteral(1)), + List.of(new Expression[] {new IntLiteral(3)}))), + """ + else if (__mpy_boolean_raw(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_boolean(false), "__bool__"), __mpy_obj_init_tuple(0), NULL))) { + \t__mpy_obj_ref_dec(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_int(1), "__add__"), __mpy_tuple_assign(0, __mpy_obj_init_int(3), __mpy_obj_init_tuple(1)), NULL)); + }""")); + } + + @ParameterizedTest + @MethodSource("sources_build") + void build(Expression condition, List statementList, String expected) { + ElifStatement elifS = new ElifStatement(condition, statementList); + + System.out.println(testClass + elifS.build()); + + assertEquals(expected, elifS.build()); + } + + @Test + void build_statement() { + ElifStatement elifS = new ElifStatement(new BoolLiteral(true), List.of()); + + System.out.println(testClass + elifS.buildStatement()); + + assertNull(elifS.buildStatement()); + } +} diff --git a/src/test/java/CBuilder/conditions/conditionalStatement/TestElseStatement.java b/src/test/java/CBuilder/conditions/conditionalStatement/TestElseStatement.java new file mode 100644 index 0000000..fa86877 --- /dev/null +++ b/src/test/java/CBuilder/conditions/conditionalStatement/TestElseStatement.java @@ -0,0 +1,55 @@ +/* (C)2024 */ +package CBuilder.conditions.conditionalStatement; + +import CBuilder.Expression; +import CBuilder.Statement; +import CBuilder.literals.IntLiteral; +import CBuilder.objects.AttributeReference; +import CBuilder.objects.Call; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.List; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +public class TestElseStatement { + String testClass = "[ELSESTATEMENT]\n"; + + private static Stream sources_build() { + return Stream.of( + Arguments.of(List.of(), "else {\n" + "}"), + Arguments.of( + List.of( + new Call( + new AttributeReference("__add__", new IntLiteral(1)), + List.of(new Expression[] {new IntLiteral(3)}))), + """ + else { + \t__mpy_obj_ref_dec(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_int(1), "__add__"), __mpy_tuple_assign(0, __mpy_obj_init_int(3), __mpy_obj_init_tuple(1)), NULL)); + }""")); + } + + @ParameterizedTest + @MethodSource("sources_build") + void build(List statementList, String expected) { + ElseStatement elseS = new ElseStatement(statementList); + + System.out.println(testClass + elseS.build()); + + assertEquals(expected, elseS.build()); + } + + @Test + void build_statement() { + ElseStatement elseS = new ElseStatement(List.of()); + + System.out.println(testClass + elseS.buildStatement()); + + assertNull(elseS.buildStatement()); + } +} diff --git a/src/test/java/CBuilder/conditions/conditionalStatement/TestIfStatement.java b/src/test/java/CBuilder/conditions/conditionalStatement/TestIfStatement.java new file mode 100644 index 0000000..f513a8f --- /dev/null +++ b/src/test/java/CBuilder/conditions/conditionalStatement/TestIfStatement.java @@ -0,0 +1,75 @@ +/* (C)2024 */ +package CBuilder.conditions.conditionalStatement; + +import CBuilder.Expression; +import CBuilder.Statement; +import CBuilder.literals.BoolLiteral; +import CBuilder.literals.IntLiteral; +import CBuilder.objects.AttributeReference; +import CBuilder.objects.Call; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.List; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +/** + * Snapshot 23.02.2024 + */ +public class TestIfStatement { + String testClass = "[IFSTATEMENT]\n"; + + private static Stream sources_build() { + return Stream.of( + Arguments.of( + new BoolLiteral(true), + List.of(), + "if (__mpy_boolean_raw(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_boolean(true)," + + " \"__bool__\"), __mpy_obj_init_tuple(0), NULL))) {\n" + + "}"), + Arguments.of( + new BoolLiteral(true), + List.of( + new Call( + new AttributeReference("__add__", new IntLiteral(1)), + List.of(new Expression[] {new IntLiteral(3)}))), + """ + if (__mpy_boolean_raw(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_boolean(true), "__bool__"), __mpy_obj_init_tuple(0), NULL))) { + \t__mpy_obj_ref_dec(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_int(1), "__add__"), __mpy_tuple_assign(0, __mpy_obj_init_int(3), __mpy_obj_init_tuple(1)), NULL)); + }"""), + Arguments.of( + new BoolLiteral(false), + List.of( + new Call( + new AttributeReference("__add__", new IntLiteral(1)), + List.of(new Expression[] {new IntLiteral(3)}))), + """ + if (__mpy_boolean_raw(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_boolean(false), "__bool__"), __mpy_obj_init_tuple(0), NULL))) { + \t__mpy_obj_ref_dec(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_int(1), "__add__"), __mpy_tuple_assign(0, __mpy_obj_init_int(3), __mpy_obj_init_tuple(1)), NULL)); + }""")); + } + + @ParameterizedTest + @MethodSource("sources_build") + void build(Expression condition, List statementList, String expected) { + IfStatement ifS = new IfStatement(condition, statementList); + + System.out.println(testClass + ifS.build()); + + assertEquals(expected, ifS.build()); + } + + @Test + void build_statement() { + IfStatement ifS = new IfStatement(new BoolLiteral(false), List.of()); + + System.out.println(testClass + ifS.buildStatement()); + + assertNull(ifS.buildStatement()); + } +} diff --git a/src/test/java/CBuilder/conditions/conditionalStatement/TestWhileStatement.java b/src/test/java/CBuilder/conditions/conditionalStatement/TestWhileStatement.java new file mode 100644 index 0000000..15c04c6 --- /dev/null +++ b/src/test/java/CBuilder/conditions/conditionalStatement/TestWhileStatement.java @@ -0,0 +1,95 @@ +/* (C)2024 */ +package CBuilder.conditions.conditionalStatement; + +import CBuilder.Expression; +import CBuilder.Reference; +import CBuilder.Statement; +import CBuilder.literals.BoolLiteral; +import CBuilder.literals.IntLiteral; +import CBuilder.objects.AttributeReference; +import CBuilder.objects.Call; +import CBuilder.variables.Assignment; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.List; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TestWhileStatement { + String testClass = "[WHILESTATEMENT]\n"; + + private static Stream sources_build() { + return Stream.of( + Arguments.of( + new BoolLiteral(true), + List.of(), + "while" + + " (__mpy_boolean_raw(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_boolean(true)," + + " \"__bool__\"), __mpy_obj_init_tuple(0), NULL))) {\n" + + "}"), + Arguments.of( + new BoolLiteral(true), + List.of( + new Call( + new AttributeReference("__add__", new IntLiteral(1)), + List.of(new Expression[] {new IntLiteral(3)}))), + """ + while (__mpy_boolean_raw(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_boolean(true), "__bool__"), __mpy_obj_init_tuple(0), NULL))) { + \t__mpy_obj_ref_dec(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_int(1), "__add__"), __mpy_tuple_assign(0, __mpy_obj_init_int(3), __mpy_obj_init_tuple(1)), NULL)); + }"""), + Arguments.of( + new BoolLiteral(false), + List.of( + new Call( + new AttributeReference("__add__", new IntLiteral(1)), + List.of(new Expression[] {new IntLiteral(3)}))), + """ + while (__mpy_boolean_raw(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_boolean(false), "__bool__"), __mpy_obj_init_tuple(0), NULL))) { + \t__mpy_obj_ref_dec(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_int(1), "__add__"), __mpy_tuple_assign(0, __mpy_obj_init_int(3), __mpy_obj_init_tuple(1)), NULL)); + }"""), + Arguments.of( + new Call( + new AttributeReference("__gt__", new Reference("a")), + List.of(new Expression[] {new IntLiteral(1)})), + List.of( + new Call( + new Reference("print"), + List.of(new Expression[] {new Reference("a")})), + new Assignment( + new Reference("a"), + new Call( + new AttributeReference( + "__sub__", new Reference("a")), + List.of(new Expression[] {new IntLiteral(1)})))), + """ + while (__mpy_boolean_raw(__mpy_call(__mpy_obj_get_attr(__mpy_call(__mpy_obj_get_attr(a, "__gt__"), __mpy_tuple_assign(0, __mpy_obj_init_int(1), __mpy_obj_init_tuple(1)), NULL), "__bool__"), __mpy_obj_init_tuple(0), NULL))) { + \t__mpy_obj_ref_dec(__mpy_call(print, __mpy_tuple_assign(0, a, __mpy_obj_init_tuple(1)), NULL)); + \t__mpy_obj_ref_dec(a); + a = __mpy_call(__mpy_obj_get_attr(a, "__sub__"), __mpy_tuple_assign(0, __mpy_obj_init_int(1), __mpy_obj_init_tuple(1)), NULL); + __mpy_obj_ref_inc(a); + }""")); + } + + @ParameterizedTest + @MethodSource("sources_build") + void build(Expression condition, List statementList, String expected) { + WhileStatement whileS = new WhileStatement(condition, statementList); + + System.out.println(testClass + whileS.build()); + + assertEquals(expected, whileS.build()); + } + + @ParameterizedTest + @MethodSource("sources_build") + void build_statement(Expression condition, List statementList, String expected) { + WhileStatement whileS = new WhileStatement(condition, statementList); + + System.out.println(testClass + whileS.buildStatement()); + + assertEquals(expected, whileS.buildStatement()); + } +} diff --git a/src/test/java/CBuilder/literals/TestBoolLiteral.java b/src/test/java/CBuilder/literals/TestBoolLiteral.java new file mode 100644 index 0000000..f6f0941 --- /dev/null +++ b/src/test/java/CBuilder/literals/TestBoolLiteral.java @@ -0,0 +1,52 @@ +/* (C)2024 */ +package CBuilder.literals; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TestBoolLiteral { + String testClass = "[BOOLLITERAL]\n"; + + private static Stream sources() { + return Stream.of(true, false); + } + + @ParameterizedTest + @MethodSource("sources") + void constructor(boolean b_value) { + + BoolLiteral boolL = new BoolLiteral(b_value); + + System.out.println(testClass + boolL.value); + + assertEquals(b_value, boolL.value); + } + + @ParameterizedTest + @MethodSource("sources") + void build_expression(boolean b_value) { + String expected = "__mpy_obj_init_boolean(" + b_value + ")"; + + BoolLiteral boolL = new BoolLiteral(b_value); + + System.out.println(testClass + boolL.buildExpression()); + + assertEquals(expected, boolL.buildExpression()); + } + + @ParameterizedTest + @MethodSource("sources") + void build_statement(boolean b_value) { + String expected = "__mpy_obj_init_boolean(" + b_value + ");\n"; + + BoolLiteral boolL = new BoolLiteral(b_value); + + System.out.println(testClass + boolL.buildStatement()); + + assertEquals(expected, boolL.buildStatement()); + } +} diff --git a/src/test/java/CBuilder/literals/TestIntLiteral.java b/src/test/java/CBuilder/literals/TestIntLiteral.java new file mode 100644 index 0000000..237ee77 --- /dev/null +++ b/src/test/java/CBuilder/literals/TestIntLiteral.java @@ -0,0 +1,53 @@ +/* (C)2024 */ +package CBuilder.literals; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TestIntLiteral { + String testClass = "[INTLITERAL]\n"; + + private static Stream sources() { + return Stream.of(Integer.MAX_VALUE, Integer.MIN_VALUE); + } + + @ParameterizedTest + @MethodSource("sources") + void constructor(Integer i_value) { + long expected = i_value; + + IntLiteral intL = new IntLiteral(i_value); + + System.out.println(testClass + intL.value); + + assertEquals(expected, intL.value); + } + + @ParameterizedTest + @MethodSource("sources") + void build_expression(Integer i_value) { + String expected = "__mpy_obj_init_int(" + i_value + ")"; + + IntLiteral intL = new IntLiteral(i_value); + + System.out.println(testClass + intL.buildExpression()); + + assertEquals(expected, intL.buildExpression()); + } + + @ParameterizedTest + @MethodSource("sources") + void build_statement(Integer i_value) { + String expected = "__mpy_obj_init_int(" + i_value + ");\n"; + + IntLiteral intL = new IntLiteral(i_value); + + System.out.println(testClass + intL.buildStatement()); + + assertEquals(expected, intL.buildStatement()); + } +} diff --git a/src/test/java/CBuilder/literals/TestStringLiteral.java b/src/test/java/CBuilder/literals/TestStringLiteral.java new file mode 100644 index 0000000..6c3494f --- /dev/null +++ b/src/test/java/CBuilder/literals/TestStringLiteral.java @@ -0,0 +1,52 @@ +/* (C)2024 */ +package CBuilder.literals; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TestStringLiteral { + String testClass = "[STRINGLITERAL]\n"; + + private static Stream sources() { + return Stream.of("true", "false"); + } + + @ParameterizedTest + @MethodSource("sources") + void constructor(String name) { + + StringLiteral stringL = new StringLiteral(name); + + System.out.println(testClass + stringL.value); + + assertEquals(name, stringL.value); + } + + @ParameterizedTest + @MethodSource("sources") + void build_expression(String name) { + String expected = "__mpy_obj_init_str_static(\"" + name + "\")"; + + StringLiteral stringL = new StringLiteral(name); + + System.out.println(testClass + stringL.buildExpression()); + + assertEquals(expected, stringL.buildExpression()); + } + + @ParameterizedTest + @MethodSource("sources") + void build_statement(String name) { + String expected = "__mpy_obj_ref_dec__mpy_obj_init_str_static(\"" + name + "\"));\n"; + + StringLiteral stringL = new StringLiteral(name); + + System.out.println(testClass + stringL.buildStatement()); + + assertEquals(expected, stringL.buildStatement()); + } +} diff --git a/src/test/java/CBuilder/literals/TestTupleLiteral.java b/src/test/java/CBuilder/literals/TestTupleLiteral.java new file mode 100644 index 0000000..66e1088 --- /dev/null +++ b/src/test/java/CBuilder/literals/TestTupleLiteral.java @@ -0,0 +1,77 @@ +/* (C)2024 */ +package CBuilder.literals; + +import CBuilder.Expression; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.List; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Snapshot 23.02.2024 + * print(tupleLiteral) does not work will look into + */ +public class TestTupleLiteral { + String testClass = "[TUPLELITERAL]\n"; + + private static Stream sources_expression() { + return Stream.of( + Arguments.of( + List.of(new IntLiteral(1)), + "__mpy_tuple_assign(0, __mpy_obj_init_int(1), __mpy_obj_init_tuple(1))"), + Arguments.of( + List.of(new IntLiteral(1), new IntLiteral(2), new IntLiteral(3)), + "__mpy_tuple_assign(0, __mpy_obj_init_int(1), __mpy_tuple_assign(1," + + " __mpy_obj_init_int(2), __mpy_tuple_assign(2, __mpy_obj_init_int(3)," + + " __mpy_obj_init_tuple(3))))"), + Arguments.of( + List.of(new StringLiteral("Test1"), new StringLiteral("Test2")), + "__mpy_tuple_assign(0, __mpy_obj_init_str_static(\"Test1\")," + + " __mpy_tuple_assign(1, __mpy_obj_init_str_static(\"Test2\")," + + " __mpy_obj_init_tuple(2)))")); + } + + private static Stream sources_statement() { + return Stream.of( + Arguments.of( + List.of(new IntLiteral(1)), + "__mpy_obj_ref_dec(__mpy_tuple_assign(0, __mpy_obj_init_int(1)," + + " __mpy_obj_init_tuple(1)));\n"), + Arguments.of( + List.of(new IntLiteral(1), new IntLiteral(2), new IntLiteral(3)), + "__mpy_obj_ref_dec(__mpy_tuple_assign(0, __mpy_obj_init_int(1)," + + " __mpy_tuple_assign(1, __mpy_obj_init_int(2), __mpy_tuple_assign(2," + + " __mpy_obj_init_int(3), __mpy_obj_init_tuple(3)))));\n"), + Arguments.of( + List.of(new StringLiteral("Test1"), new StringLiteral("Test2")), + "__mpy_obj_ref_dec(__mpy_tuple_assign(0," + + " __mpy_obj_init_str_static(\"Test1\"), __mpy_tuple_assign(1," + + " __mpy_obj_init_str_static(\"Test2\")," + + " __mpy_obj_init_tuple(2))));\n")); + } + + @ParameterizedTest + @MethodSource("sources_expression") + void build_expression(List expressionList, String expected) { + + TupleLiteral tupleL = new TupleLiteral(expressionList); + + System.out.println(testClass + tupleL.buildExpression()); + + assertEquals(expected, tupleL.buildExpression()); + } + + @ParameterizedTest + @MethodSource("sources_statement") + void build_statement(List expressionList, String expected) { + TupleLiteral tupleL = new TupleLiteral(expressionList); + + System.out.println(testClass + tupleL.buildStatement()); + + assertEquals(expected, tupleL.buildStatement()); + } +} diff --git a/src/test/java/CBuilder/objects/TestAttributeAssignment.java b/src/test/java/CBuilder/objects/TestAttributeAssignment.java new file mode 100644 index 0000000..c9a858e --- /dev/null +++ b/src/test/java/CBuilder/objects/TestAttributeAssignment.java @@ -0,0 +1,47 @@ +/* (C)2024 */ +package CBuilder.objects; + +import CBuilder.Expression; +import CBuilder.literals.BoolLiteral; +import CBuilder.literals.IntLiteral; +import CBuilder.literals.StringLiteral; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TestAttributeAssignment { + String testClass = "[ATTRIBUTEASSIGNMENT]\n"; + + private static Stream sources() { + return Stream.of( + Arguments.of( + new AttributeReference("referenceName1", new IntLiteral(23)), + new IntLiteral(34), + "__mpy_obj_set_attr(__mpy_obj_init_int(23), \"referenceName1\"," + + " __mpy_obj_init_int(34));"), + Arguments.of( + new AttributeReference("referenceName2", new BoolLiteral(false)), + new BoolLiteral(true), + "__mpy_obj_set_attr(__mpy_obj_init_boolean(false), \"referenceName2\"," + + " __mpy_obj_init_boolean(true));"), + Arguments.of( + new AttributeReference("referenceName3", new StringLiteral("stringL")), + new StringLiteral("34"), + "__mpy_obj_set_attr(__mpy_obj_init_str_static(\"stringL\")," + + " \"referenceName3\", __mpy_obj_init_str_static(\"34\"));")); + } + + @ParameterizedTest + @MethodSource("sources") + void build_statement(AttributeReference attributeR, Expression value, String expected) { + AttributeAssignment attributeA = new AttributeAssignment(attributeR, value); + + System.out.println(testClass + attributeA.buildStatement()); + + assertEquals(expected, attributeA.buildStatement()); + } +} diff --git a/src/test/java/CBuilder/objects/TestAttributeReference.java b/src/test/java/CBuilder/objects/TestAttributeReference.java new file mode 100644 index 0000000..b8bb6b2 --- /dev/null +++ b/src/test/java/CBuilder/objects/TestAttributeReference.java @@ -0,0 +1,120 @@ +/* (C)2024 */ +package CBuilder.objects; + +import CBuilder.Expression; +import CBuilder.literals.BoolLiteral; +import CBuilder.literals.IntLiteral; +import CBuilder.literals.StringLiteral; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TestAttributeReference { + String testClass = "[ATTRIBUTEREFERENCE]\n"; + + private static Stream sources_get_name() { + return Stream.of( + Arguments.of("referenceName", new IntLiteral(23), "referenceName"), + Arguments.of("referenceName1", new BoolLiteral(false), "referenceName1"), + Arguments.of("referenceName2", new StringLiteral("stringL"), "referenceName2")); + } + + private static Stream sources_build_expression() { + return Stream.of( + Arguments.of( + "referenceName", + new IntLiteral(23), + "__mpy_obj_get_attr(__mpy_obj_init_int(23), \"referenceName\")"), + Arguments.of( + "referenceName1", + new BoolLiteral(true), + "__mpy_obj_get_attr(__mpy_obj_init_boolean(true), \"referenceName1\")"), + Arguments.of( + "referenceName2", + new StringLiteral("stringL"), + "__mpy_obj_get_attr(__mpy_obj_init_str_static(\"stringL\")," + + " \"referenceName2\")")); + } + + private static Stream sources_build_statement() { + return Stream.of( + Arguments.of( + "referenceName", + new IntLiteral(23), + "__mpy_obj_get_attr(__mpy_obj_init_int(23), \"referenceName\");\n"), + Arguments.of( + "referenceName1", + new BoolLiteral(true), + "__mpy_obj_get_attr(__mpy_obj_init_boolean(true), \"referenceName1\");\n"), + Arguments.of( + "referenceName2", + new StringLiteral("stringL"), + "__mpy_obj_get_attr(__mpy_obj_init_str_static(\"stringL\")," + + " \"referenceName2\");\n")); + } + + private static Stream sources_build_object() { + return Stream.of( + Arguments.of("referenceName", new IntLiteral(23), "__mpy_obj_init_int(23)"), + Arguments.of( + "referenceName1", new BoolLiteral(true), "__mpy_obj_init_boolean(true)"), + Arguments.of( + "referenceName2", + new StringLiteral("stringL"), + "__mpy_obj_init_str_static(\"stringL\")")); + } + + @ParameterizedTest + @MethodSource("sources_get_name") + void get_name(String name, Expression expression, String expected) { + AttributeReference attributeR = new AttributeReference(name, expression); + + System.out.println(testClass + attributeR.getName()); + + assertEquals(expected, attributeR.getName()); + } + + @ParameterizedTest + @MethodSource("sources_build_expression") + void build_expression(String name, Expression expression, String expected) { + AttributeReference attributeR = new AttributeReference(name, expression); + + System.out.println(testClass + attributeR.buildExpression()); + + assertEquals(expected, attributeR.buildExpression()); + } + + @ParameterizedTest + @MethodSource("sources_build_statement") + void build_statement(String name, Expression expression, String expected) { + AttributeReference attributeR = new AttributeReference(name, expression); + + System.out.println(testClass + attributeR.buildStatement()); + + assertEquals(expected, attributeR.buildStatement()); + } + + @ParameterizedTest + @MethodSource("sources_build_object") + void build_object(String name, Expression expression, String expected) { + AttributeReference attributeR = new AttributeReference(name, expression); + + System.out.println(attributeR.buildObject()); + + assertEquals(expected, attributeR.buildObject()); + } + + @Test + void build_name() { + AttributeReference attributeR = new AttributeReference("attributeR", new IntLiteral(23)); + + System.out.println(testClass + attributeR.buildName()); + + assertEquals("\"attributeR\"", attributeR.buildName()); + } +} diff --git a/src/test/java/CBuilder/objects/TestCall.java b/src/test/java/CBuilder/objects/TestCall.java new file mode 100644 index 0000000..94bf6c7 --- /dev/null +++ b/src/test/java/CBuilder/objects/TestCall.java @@ -0,0 +1,66 @@ +/* (C)2024 */ +package CBuilder.objects; + +import CBuilder.Expression; +import CBuilder.Reference; +import CBuilder.literals.IntLiteral; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.List; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TestCall { + String testClass = "[CALL]\n"; + + private static Stream sources_build_expression() { + return Stream.of( + Arguments.of( + new Reference("print"), + List.of(new Expression[] {new IntLiteral(23)}), + "__mpy_call(print, __mpy_tuple_assign(0, __mpy_obj_init_int(23)," + + " __mpy_obj_init_tuple(1)), NULL)"), + Arguments.of( + new Reference("type"), + List.of(new Expression[] {new IntLiteral(23)}), + "__mpy_call(type, __mpy_tuple_assign(0, __mpy_obj_init_int(23)," + + " __mpy_obj_init_tuple(1)), NULL)")); + } + + private static Stream sources_build_statement() { + return Stream.of( + Arguments.of( + new Reference("print"), + List.of(new Expression[] {new IntLiteral(23)}), + "__mpy_obj_ref_dec(__mpy_call(print, __mpy_tuple_assign(0," + + " __mpy_obj_init_int(23), __mpy_obj_init_tuple(1)), NULL));\n"), + Arguments.of( + new Reference("type"), + List.of(new Expression[] {new IntLiteral(23)}), + "__mpy_obj_ref_dec(__mpy_call(type, __mpy_tuple_assign(0," + + " __mpy_obj_init_int(23), __mpy_obj_init_tuple(1)), NULL));\n")); + } + + @ParameterizedTest + @MethodSource("sources_build_expression") + void build_expression(Expression callable, List args, String expected) { + Call call = new Call(callable, args); + + System.out.println(testClass + call.buildExpression()); + + assertEquals(expected, call.buildExpression()); + } + + @ParameterizedTest + @MethodSource("sources_build_statement") + void build_statement(Expression callable, List args, String expected) { + Call call = new Call(callable, args); + + System.out.println(testClass + call.buildStatement()); + + assertEquals(expected, call.buildStatement()); + } +} diff --git a/src/test/java/CBuilder/objects/TestMPyClass.java b/src/test/java/CBuilder/objects/TestMPyClass.java new file mode 100644 index 0000000..ce2f0ab --- /dev/null +++ b/src/test/java/CBuilder/objects/TestMPyClass.java @@ -0,0 +1,311 @@ +/* (C)2024 */ +package CBuilder.objects; + +import CBuilder.Expression; +import CBuilder.Reference; +import CBuilder.Statement; +import CBuilder.objects.functions.Argument; +import CBuilder.objects.functions.Function; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +public class TestMPyClass { + String testClass = "[TESTMPYCLASS]\n"; + + @ParameterizedTest + @MethodSource("sources_build_declaration") + void build_declaration( + String name, + Reference parent, + List functions, + Map classAttributes, + String expected) { + MPyClass mpyC = new MPyClass(name, parent, functions, classAttributes); + + System.out.println(testClass + mpyC.buildDeclaration()); + + assertEquals(expected, mpyC.buildDeclaration()); + } + + @ParameterizedTest + @MethodSource("sources_build_initialisation") + void build_initialisation( + String name, + Reference parent, + List functions, + Map classAttributes, + String expected) { + MPyClass mpyC = new MPyClass(name, parent, functions, classAttributes); + + System.out.println(testClass + mpyC.buildInitialisation()); + + assertEquals(expected, mpyC.buildInitialisation()); + } + + @ParameterizedTest + @MethodSource("sources_build_refdec") + void build_refdec( + String name, + Reference parent, + List functions, + Map classAttributes, + String expected) { + MPyClass mpyC = new MPyClass(name, parent, functions, classAttributes); + + System.out.println(testClass + mpyC.buildRefDec()); + + assertEquals(expected, mpyC.buildRefDec()); + } + + @ParameterizedTest + @MethodSource("sources_build_expression") + void build_expression( + String name, + Reference parent, + List functions, + Map classAttributes, + String expected) { + MPyClass mpyC = new MPyClass(name, parent, functions, classAttributes); + + System.out.println(testClass + mpyC.buildExpression()); + + assertEquals(expected, mpyC.buildExpression()); + } + + @ParameterizedTest + @MethodSource("sources_build_statement") + void build_statement( + String name, + Reference parent, + List functions, + Map classAttributes) { + MPyClass mpyC = new MPyClass(name, parent, functions, classAttributes); + + System.out.println(testClass + mpyC.buildStatement()); + + assertNull(mpyC.buildStatement()); + } + + private static Stream sources_build_declaration() { + return Stream.of( + Arguments.of( + "MyClass1", + new Reference("__MPyType_Object"), + List.of( + new Function[] { + new Function( + "__init__", + List.of(new Statement[] {new SuperCall(List.of())}), + List.of(new Argument[] {new Argument("self", 0)}), + List.of()) + }), + new HashMap<>(), + """ + __MPyObj *MyClass1; + __MPyObj* func_MyClass1___init__(__MPyObj *args, __MPyObj *kwargs) { + \tassert(args != NULL && kwargs != NULL); + \t + \t__MPyGetArgsState argHelper = __mpy_args_init("__init__", args, kwargs, 1); + \t__MPyObj *self = __mpy_args_get_positional(&argHelper, 0, "self"); + \t__mpy_args_finish(&argHelper); + \t + \t__MPyObj *retValue = NULL; + \t + \t__mpy_obj_ref_dec(__mpy_call(__mpy_super, __mpy_tuple_assign(0, self, __mpy_obj_init_tuple(1)), NULL)); + \t + \t__mpy_obj_ref_dec(self); + \t + \tgoto ret; + \tret: + \tif (retValue == NULL) { + \t\tretValue = __mpy_obj_init_object(); + \t} + \treturn __mpy_obj_return(retValue); + } + """), + Arguments.of( + "MyClass2", + new Reference("MyClass1"), + List.of( + new Function[] { + new Function( + "__init__", + List.of(new Statement[] {new SuperCall(List.of())}), + List.of(new Argument[] {new Argument("self", 0)}), + List.of()) + }), + new HashMap<>(), + """ + __MPyObj *MyClass2; + __MPyObj* func_MyClass2___init__(__MPyObj *args, __MPyObj *kwargs) { + \tassert(args != NULL && kwargs != NULL); + \t + \t__MPyGetArgsState argHelper = __mpy_args_init("__init__", args, kwargs, 1); + \t__MPyObj *self = __mpy_args_get_positional(&argHelper, 0, "self"); + \t__mpy_args_finish(&argHelper); + \t + \t__MPyObj *retValue = NULL; + \t + \t__mpy_obj_ref_dec(__mpy_call(__mpy_super, __mpy_tuple_assign(0, self, __mpy_obj_init_tuple(1)), NULL)); + \t + \t__mpy_obj_ref_dec(self); + \t + \tgoto ret; + \tret: + \tif (retValue == NULL) { + \t\tretValue = __mpy_obj_init_object(); + \t} + \treturn __mpy_obj_return(retValue); + } + """)); + } + + private static Stream sources_build_initialisation() { + return Stream.of( + Arguments.of( + "MyClass1", + new Reference("__MPyType_Object"), + List.of( + new Function[] { + new Function( + "__init__", + List.of(new Statement[] {new SuperCall(List.of())}), + List.of(new Argument[] {new Argument("self", 0)}), + List.of()) + }), + new HashMap<>(), + """ + MyClass1 = __mpy_obj_init_type("MyClass1", __MPyType_Object); + __mpy_obj_ref_inc(MyClass1); + { + \t__MPyObj *__init__; + \t__init__ = __mpy_obj_init_func(&func_MyClass1___init__); + \t__mpy_obj_ref_inc(__init__); + \t__mpy_obj_set_attr(MyClass1, "__init__", __init__); + \t__mpy_obj_ref_dec(__init__); + } + """), + Arguments.of( + "MyClass2", + new Reference("MyClass1"), + List.of( + new Function[] { + new Function( + "__init__", + List.of(new Statement[] {new SuperCall(List.of())}), + List.of(new Argument[] {new Argument("self", 0)}), + List.of()) + }), + new HashMap<>(), + """ + MyClass2 = __mpy_obj_init_type("MyClass2", MyClass1); + __mpy_obj_ref_inc(MyClass2); + { + \t__MPyObj *__init__; + \t__init__ = __mpy_obj_init_func(&func_MyClass2___init__); + \t__mpy_obj_ref_inc(__init__); + \t__mpy_obj_set_attr(MyClass2, "__init__", __init__); + \t__mpy_obj_ref_dec(__init__); + } + """)); + } + + private static Stream sources_build_refdec() { + return Stream.of( + Arguments.of( + "MyClass1", + new Reference("__MPyType_Object"), + List.of( + new Function[] { + new Function( + "__init__", + List.of(new Statement[] {new SuperCall(List.of())}), + List.of(new Argument[] {new Argument("self", 0)}), + List.of()) + }), + new HashMap<>(), + "__mpy_obj_ref_dec(MyClass1);\n"), + Arguments.of( + "MyClass2", + new Reference("MyClass1"), + List.of( + new Function[] { + new Function( + "__init__", + List.of(new Statement[] {new SuperCall(List.of())}), + List.of(new Argument[] {new Argument("self", 0)}), + List.of()) + }), + new HashMap<>(), + "__mpy_obj_ref_dec(MyClass2);\n")); + } + + private static Stream sources_build_expression() { + return Stream.of( + Arguments.of( + "MyClass1", + new Reference("__MPyType_Object"), + List.of( + new Function[] { + new Function( + "__init__", + List.of(new Statement[] {new SuperCall(List.of())}), + List.of(new Argument[] {new Argument("self", 0)}), + List.of()) + }), + new HashMap<>(), + "MyClass1"), + Arguments.of( + "MyClass2", + new Reference("MyClass1"), + List.of( + new Function[] { + new Function( + "__init__", + List.of(new Statement[] {new SuperCall(List.of())}), + List.of(new Argument[] {new Argument("self", 0)}), + List.of()) + }), + new HashMap<>(), + "MyClass2")); + } + + private static Stream sources_build_statement() { + return Stream.of( + Arguments.of( + "MyClass1", + new Reference("__MPyType_Object"), + List.of( + new Function[] { + new Function( + "__init__", + List.of(new Statement[] {new SuperCall(List.of())}), + List.of(new Argument[] {new Argument("self", 0)}), + List.of()) + }), + new HashMap<>(), + "__mpy_obj_ref_dec(MyClass1);\n"), + Arguments.of( + "MyClass2", + new Reference("MyClass1"), + List.of( + new Function[] { + new Function( + "__init__", + List.of(new Statement[] {new SuperCall(List.of())}), + List.of(new Argument[] {new Argument("self", 0)}), + List.of()) + }), + new HashMap<>(), + "__mpy_obj_ref_dec(MyClass2);\n")); + } +} diff --git a/src/test/java/CBuilder/objects/TestSuperCall.java b/src/test/java/CBuilder/objects/TestSuperCall.java new file mode 100644 index 0000000..8ec24a1 --- /dev/null +++ b/src/test/java/CBuilder/objects/TestSuperCall.java @@ -0,0 +1,64 @@ +/* (C)2024 */ +package CBuilder.objects; + +import CBuilder.Expression; +import CBuilder.literals.BoolLiteral; +import CBuilder.literals.IntLiteral; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.List; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TestSuperCall { + String testClass = "[SUPERCALL]\n"; + + private static Stream sources_expression() { + return Stream.of( + Arguments.of( + List.of(new Expression[] {new IntLiteral(23)}), + "__mpy_call(__mpy_super, __mpy_tuple_assign(0, self, __mpy_tuple_assign(1," + + " __mpy_obj_init_int(23), __mpy_obj_init_tuple(2))), NULL)"), + Arguments.of( + List.of(new Expression[] {new BoolLiteral(true)}), + "__mpy_call(__mpy_super, __mpy_tuple_assign(0, self, __mpy_tuple_assign(1," + + " __mpy_obj_init_boolean(true), __mpy_obj_init_tuple(2))), NULL)")); + } + + private static Stream sources_statement() { + return Stream.of( + Arguments.of( + List.of(new Expression[] {new IntLiteral(23)}), + "__mpy_obj_ref_dec(__mpy_call(__mpy_super, __mpy_tuple_assign(0, self," + + " __mpy_tuple_assign(1, __mpy_obj_init_int(23)," + + " __mpy_obj_init_tuple(2))), NULL));\n"), + Arguments.of( + List.of(new Expression[] {new BoolLiteral(true)}), + "__mpy_obj_ref_dec(__mpy_call(__mpy_super, __mpy_tuple_assign(0, self," + + " __mpy_tuple_assign(1, __mpy_obj_init_boolean(true)," + + " __mpy_obj_init_tuple(2))), NULL));\n")); + } + + @ParameterizedTest + @MethodSource("sources_expression") + void build_expression(List args, String expected) { + SuperCall superC = new SuperCall(args); + + System.out.println(testClass + superC.buildExpression()); + + assertEquals(expected, superC.buildExpression()); + } + + @ParameterizedTest + @MethodSource("sources_statement") + void build_statement(List args, String expected) { + SuperCall superC = new SuperCall(args); + + System.out.println(testClass + superC.buildStatement()); + + assertEquals(expected, superC.buildStatement()); + } +} diff --git a/src/test/java/CBuilder/objects/functions/TestArgument.java b/src/test/java/CBuilder/objects/functions/TestArgument.java new file mode 100644 index 0000000..bbbcf80 --- /dev/null +++ b/src/test/java/CBuilder/objects/functions/TestArgument.java @@ -0,0 +1,60 @@ +/* (C)2024 */ +package CBuilder.objects.functions; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TestArgument { + String testClass = "[ARGUMENT]\n"; + + private static Stream sources_arg_extraction() { + return Stream.of( + Arguments.of( + "argName1", + 1, + "__MPyObj *argName1 = __mpy_args_get_positional(&argHelper, 1," + + " \"argName1\");\n"), + Arguments.of( + "argName2", + 2, + "__MPyObj *argName2 = __mpy_args_get_positional(&argHelper, 2," + + " \"argName2\");\n"), + Arguments.of( + "argName3", + 3, + "__MPyObj *argName3 = __mpy_args_get_positional(&argHelper, 3," + + " \"argName3\");\n")); + } + + private static Stream sources_build_arg_cleanup() { + return Stream.of( + Arguments.of("argName1", 1, "__mpy_obj_ref_dec(argName1);\n"), + Arguments.of("argName2", 2, "__mpy_obj_ref_dec(argName2);\n"), + Arguments.of("argName3", 3, "__mpy_obj_ref_dec(argName3);\n")); + } + + @ParameterizedTest + @MethodSource("sources_arg_extraction") + void build_arg_extraction(String name, int position, String expected) { + Argument argument = new Argument(name, position); + + System.out.println(testClass + argument.buildArgExtraction()); + + assertEquals(expected, argument.buildArgExtraction()); + } + + @ParameterizedTest + @MethodSource("sources_build_arg_cleanup") + void build_arg_cleanup(String name, int position, String expected) { + Argument argument = new Argument(name, position); + + System.out.println(testClass + argument.buildArgCleanup()); + + assertEquals(expected, argument.buildArgCleanup()); + } +} diff --git a/src/test/java/CBuilder/objects/functions/TestFunction.java b/src/test/java/CBuilder/objects/functions/TestFunction.java new file mode 100644 index 0000000..0c2fd62 --- /dev/null +++ b/src/test/java/CBuilder/objects/functions/TestFunction.java @@ -0,0 +1,231 @@ +/* (C)2024 */ +package CBuilder.objects.functions; + +import CBuilder.Expression; +import CBuilder.Statement; +import CBuilder.literals.IntLiteral; +import CBuilder.objects.AttributeReference; +import CBuilder.objects.Call; +import CBuilder.variables.VariableDeclaration; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.List; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TestFunction { + String testClass = "[FUNCTION]\n"; + + @ParameterizedTest + @MethodSource("sources_build_cfunction") + void build_cfunction( + String funcName, + List body, + List positionalArgs, + List localVariables, + String expected) { + Function function = new Function(funcName, body, positionalArgs, localVariables); + + System.out.println(testClass + function.buildCFunction()); + + assertEquals(expected, function.buildCFunction()); + } + + @ParameterizedTest + @MethodSource("sources_build_func_object_declaration") + void build_func_object_declaration( + String funcName, + List body, + List positionalArgs, + List localVariables, + String expected) { + Function function = new Function(funcName, body, positionalArgs, localVariables); + + System.out.println(testClass + function.buildFuncObjectDeclaration()); + + assertEquals(expected, function.buildFuncObjectDeclaration()); + } + + @ParameterizedTest + @MethodSource("sources_build_initialisation") + void build_initialisation( + String funcName, + List body, + List positionalArgs, + List localVariables, + String expected) { + Function function = new Function(funcName, body, positionalArgs, localVariables); + + System.out.println(testClass + function.buildInitialisation()); + + assertEquals(expected, function.buildInitialisation()); + } + + @ParameterizedTest + @MethodSource("sources_build_refdec") + void build_refdec( + String funcName, + List body, + List positionalArgs, + List localVariables, + String expected) { + Function function = new Function(funcName, body, positionalArgs, localVariables); + + System.out.println(testClass + function.buildRefDec()); + + assertEquals(expected, function.buildRefDec()); + } + + @ParameterizedTest + @MethodSource("sources_build_expression") + void build_expression( + String funcName, + List body, + List positionalArgs, + List localVariables, + String expected) { + Function function = new Function(funcName, body, positionalArgs, localVariables); + + System.out.println(testClass + function.buildExpression()); + + assertEquals(expected, function.buildExpression()); + } + + @ParameterizedTest + @MethodSource("sources_get_name") + void get_name( + String funcName, + List body, + List positionalArgs, + List localVariables, + String expected) { + Function function = new Function(funcName, body, positionalArgs, localVariables); + + System.out.println(testClass + function.getName()); + + assertEquals(expected, function.getName()); + } + + private static Stream sources_build_cfunction() { + return Stream.of( + Arguments.of( + "funcName1", + List.of( + new Call( + new AttributeReference("__add__", new IntLiteral(1)), + List.of(new Expression[] {new IntLiteral(3)}))), + List.of(new Argument("argName1", 0), new Argument("argName2", 1)), + List.of( + new VariableDeclaration("local1"), + new VariableDeclaration("local2")), + """ + __MPyObj* func_funcName1(__MPyObj *args, __MPyObj *kwargs) { + \tassert(args != NULL && kwargs != NULL); + \t + \t__MPyGetArgsState argHelper = __mpy_args_init("funcName1", args, kwargs, 2); + \t__MPyObj *argName1 = __mpy_args_get_positional(&argHelper, 0, "argName1"); + \t__MPyObj *argName2 = __mpy_args_get_positional(&argHelper, 1, "argName2"); + \t__mpy_args_finish(&argHelper); + \t + \t__MPyObj *retValue = NULL; + \t + \t__MPyObj *local1 = __mpy_obj_init_object(); + \t__mpy_obj_ref_inc(local1); + \t__MPyObj *local2 = __mpy_obj_init_object(); + \t__mpy_obj_ref_inc(local2); + \t__mpy_obj_ref_dec(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_int(1), "__add__"), __mpy_tuple_assign(0, __mpy_obj_init_int(3), __mpy_obj_init_tuple(1)), NULL)); + \t + \t__mpy_obj_ref_dec(argName1); + \t__mpy_obj_ref_dec(argName2); + \t + \tgoto ret; + \tret: + \tif (retValue == NULL) { + \t\tretValue = __mpy_obj_init_object(); + \t} + \treturn __mpy_obj_return(retValue); + } + """)); + } + + private static Stream sources_build_func_object_declaration() { + return Stream.of( + Arguments.of( + "funcName1", + List.of( + new Call( + new AttributeReference("__add__", new IntLiteral(1)), + List.of(new Expression[] {new IntLiteral(3)}))), + List.of(new Argument("argName1", 0), new Argument("argName2", 1)), + List.of( + new VariableDeclaration("local1"), + new VariableDeclaration("local2")), + "__MPyObj *funcName1;\n")); + } + + private static Stream sources_build_initialisation() { + return Stream.of( + Arguments.of( + "funcName1", + List.of( + new Call( + new AttributeReference("__add__", new IntLiteral(1)), + List.of(new Expression[] {new IntLiteral(3)}))), + List.of(new Argument("argName1", 0), new Argument("argName2", 1)), + List.of( + new VariableDeclaration("local1"), + new VariableDeclaration("local2")), + """ + funcName1 = __mpy_obj_init_func(&func_funcName1); + __mpy_obj_ref_inc(funcName1); + """)); + } + + private static Stream sources_build_refdec() { + return Stream.of( + Arguments.of( + "funcName1", + List.of( + new Call( + new AttributeReference("__add__", new IntLiteral(1)), + List.of(new Expression[] {new IntLiteral(3)}))), + List.of(new Argument("argName1", 0), new Argument("argName2", 1)), + List.of( + new VariableDeclaration("local1"), + new VariableDeclaration("local2")), + "__mpy_obj_ref_dec(funcName1);\n")); + } + + private static Stream sources_build_expression() { + return Stream.of( + Arguments.of( + "funcName1", + List.of( + new Call( + new AttributeReference("__add__", new IntLiteral(1)), + List.of(new Expression[] {new IntLiteral(3)}))), + List.of(new Argument("argName1", 0), new Argument("argName2", 1)), + List.of( + new VariableDeclaration("local1"), + new VariableDeclaration("local2")), + "funcName1")); + } + + private static Stream sources_get_name() { + return Stream.of( + Arguments.of( + "funcName1", + List.of( + new Call( + new AttributeReference("__add__", new IntLiteral(1)), + List.of(new Expression[] {new IntLiteral(3)}))), + List.of(new Argument("argName1", 0), new Argument("argName2", 1)), + List.of( + new VariableDeclaration("local1"), + new VariableDeclaration("local2")), + "funcName1")); + } +} diff --git a/src/test/java/CBuilder/objects/functions/TestReturnStatement.java b/src/test/java/CBuilder/objects/functions/TestReturnStatement.java new file mode 100644 index 0000000..1cadfa5 --- /dev/null +++ b/src/test/java/CBuilder/objects/functions/TestReturnStatement.java @@ -0,0 +1,50 @@ +/* (C)2024 */ +package CBuilder.objects.functions; + +import CBuilder.Expression; +import CBuilder.literals.BoolLiteral; +import CBuilder.literals.IntLiteral; +import CBuilder.literals.StringLiteral; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TestReturnStatement { + String testClass = "[RETURNSTATEMENT]\n"; + + private static Stream sources() { + return Stream.of( + Arguments.of( + new IntLiteral(34), + """ + retValue = __mpy_obj_init_int(34); + goto ret; + """), + Arguments.of( + new BoolLiteral(true), + """ + retValue = __mpy_obj_init_boolean(true); + goto ret; + """), + Arguments.of( + new StringLiteral("34"), + """ + retValue = __mpy_obj_init_str_static("34"); + goto ret; + """)); + } + + @ParameterizedTest + @MethodSource("sources") + void build_statement(Expression returnValue, String expected) { + ReturnStatement returnS = new ReturnStatement(returnValue); + + System.out.println(testClass + returnS.buildStatement()); + + assertEquals(expected, returnS.buildStatement()); + } +} diff --git a/src/test/java/CBuilder/variables/TestAssignment.java b/src/test/java/CBuilder/variables/TestAssignment.java new file mode 100644 index 0000000..1632a7e --- /dev/null +++ b/src/test/java/CBuilder/variables/TestAssignment.java @@ -0,0 +1,125 @@ +/* (C)2024 */ +package CBuilder.variables; + +import CBuilder.Expression; +import CBuilder.Reference; +import CBuilder.Statement; +import CBuilder.literals.IntLiteral; +import CBuilder.objects.AttributeReference; +import CBuilder.objects.Call; +import CBuilder.objects.functions.Argument; +import CBuilder.objects.functions.Function; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Snapshot 22.02.2024 + */ +public class TestAssignment { + String testClass = "[ASSIGNMENT]\n"; + + /** + *

Test right hand side reference
a = b

+ */ + @Test + void assignment_rhs_ref() { + String expected = + """ + __mpy_obj_ref_inc(b); + __mpy_obj_ref_dec(a); + a = b; + """; + + Assignment assignment = new Assignment(new Reference("a"), new Reference("b")); + + String actual = assignment.buildStatement(); + + System.out.println(testClass + actual); + + assertEquals(expected, actual); + } + + /** + *

Test right hand side literal (no reference)
a = 133

+ */ + @Test + void assignment_rhs_int_literal() { + String expected = + """ + __mpy_obj_ref_dec(a); + a = __mpy_obj_init_int(133); + __mpy_obj_ref_inc(a); + """; + + Assignment assignment = new Assignment(new Reference("a"), new IntLiteral(133)); + + String actual = assignment.buildStatement(); + + System.out.println(testClass + actual); + + assertEquals(expected, actual); + } + + /** + *

Test right hand side function (which is also reference)
a = printA

+ */ + @Test + void assignment_rhs_function() { + String expected = + """ + __mpy_obj_ref_inc(printA); + __mpy_obj_ref_dec(a); + a = printA; + """; + + Function printA = + new Function( + "printA", + List.of( + new Statement[] { + new Call( + new Reference("print"), + List.of(new Expression[] {new Reference("a")})) + }), + List.of(new Argument[] {new Argument("a", 0)}), + List.of()); + + Assignment assignment = new Assignment(new Reference("a"), printA); + + String actual = assignment.buildStatement(); + + System.out.println(testClass + actual); + + assertEquals(expected, actual); + } + + // d = a+b + + /** + *

Test right hand side expression (no reference)
d = a + b

+ */ + @Test + void assignment_rhs_expression() { + String expected = + """ + __mpy_obj_ref_dec(d); + d = __mpy_call(__mpy_obj_get_attr(a, "__add__"), __mpy_tuple_assign(0, b, __mpy_obj_init_tuple(1)), NULL); + __mpy_obj_ref_inc(d); + """; + + AttributeReference addA = new AttributeReference("__add__", new Reference("a")); + Assignment assignD = + new Assignment( + new Reference("d"), + new Call(addA, List.of(new Expression[] {new Reference("b")}))); + + String actual = assignD.buildStatement(); + + System.out.println(testClass + actual); + + assertEquals(expected, actual); + } +} diff --git a/src/test/java/CBuilder/variables/TestVariableDeclaration.java b/src/test/java/CBuilder/variables/TestVariableDeclaration.java new file mode 100644 index 0000000..f5be10e --- /dev/null +++ b/src/test/java/CBuilder/variables/TestVariableDeclaration.java @@ -0,0 +1,101 @@ +/* (C)2024 */ +package CBuilder.variables; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Snapshot 22.02.2024 + */ +public class TestVariableDeclaration { + private static Stream sources() { + return Stream.of("someVar", "anotherOne", "", "'"); + } + + /** + *

var_name # just init

+ * @param var_name - variable name + */ + @ParameterizedTest + @MethodSource("sources") + void build_initialisation_parameterized(String var_name) { + String expected = + var_name + + " = __mpy_obj_init_object();\n" + + "__mpy_obj_ref_inc(" + + var_name + + ");\n"; + + VariableDeclaration var = new VariableDeclaration(var_name); + + String actual = var.buildInitialisation(); + + System.out.println(actual); + + assertEquals(expected, actual); + } + + /** + *

var_name # with init

+ * @param var_name - variable name + */ + @ParameterizedTest + @MethodSource("sources") + void build_true_parameterized(String var_name) { + String expected = + "__MPyObj *" + + var_name + + " = __mpy_obj_init_object();\n" + + "__mpy_obj_ref_inc(" + + var_name + + ");\n"; + + VariableDeclaration var = new VariableDeclaration(var_name); + + String actual = var.build(true); + + System.out.println(actual); + + assertEquals(expected, actual); + } + + /** + *

var_name # without init

+ * @param var_name - variable name + */ + @ParameterizedTest + @MethodSource("sources") + void build_false_parameterized(String var_name) { + String expected = "__MPyObj *" + var_name + ";\n"; + + VariableDeclaration var = new VariableDeclaration(var_name); + + String actual = var.build(false); + + System.out.println(actual); + + assertEquals(expected, actual); + } + + /** + *

Test decrementing reference counter of the variable

+ * @param var_name - variable name + */ + @ParameterizedTest + @MethodSource("sources") + void build_ref_dec_parameterized(String var_name) { + String expected = "__mpy_obj_ref_dec(" + var_name + ");\n"; + + VariableDeclaration var = new VariableDeclaration(var_name); + + String actual = var.buildRefDec(); + + System.out.println(actual); + + assertEquals(expected, actual); + } +} From aef2f6c16d8c900ea4d2bf9f2d75bcf2f04aeb73 Mon Sep 17 00:00:00 2001 From: f0gel Date: Mon, 1 Jul 2024 15:40:28 +0200 Subject: [PATCH 02/14] CBuilder System-Tests --- .../ArithmeticOps/TestArithmeticOps.java | 83 +++++ .../BuiltInFunctions/TestCastInt.java | 105 ++++++ .../BuiltInFunctions/TestCastStr.java | 83 +++++ .../TestDifferentialExamplePrint.java | 84 +++++ .../BuiltInFunctions/TestId.java | 78 +++++ .../BuiltInFunctions/TestInput.java | 85 +++++ .../TestMetamorphicExamplePrint.java | 116 +++++++ .../BuiltInFunctions/TestPrint.java | 70 ++++ .../BuiltInFunctions/TestType.java | 89 +++++ .../Classes/TestClassInheritance.java | 130 ++++++++ .../Classes/TestClassInit.java | 170 ++++++++++ .../Classes/TestClassMembers.java | 210 ++++++++++++ .../ComparisonOps/TestComparisonOps.java | 83 +++++ .../Conditions/TestElifStatement.java | 132 ++++++++ .../Conditions/TestElseStatement.java | 128 ++++++++ .../Conditions/TestIfStatement.java | 117 +++++++ .../Conditions/TestWhileStatement.java | 93 ++++++ .../TestDeclarationAndAssignment.java | 290 ++++++++++++++++ .../FunctionCalls/TestFunctionBody.java | 191 +++++++++++ .../FunctionCalls/TestFunctionParams.java | 214 ++++++++++++ .../FunctionCalls/TestFunctionRecursion.java | 139 ++++++++ .../FunctionCalls/TestFunctionReturn.java | 192 +++++++++++ .../LogicalOps/TestLogicalOps.java | 84 +++++ .../LanguageFeatures/TestEmpty.java | 13 + src/test/java/Systemtests/TestHelpers.java | 81 +++++ .../TestLanguageFeaturesCombined.java | 309 ++++++++++++++++++ 26 files changed, 3369 insertions(+) create mode 100644 src/test/java/Systemtests/LanguageFeatures/ArithmeticOps/TestArithmeticOps.java create mode 100644 src/test/java/Systemtests/LanguageFeatures/BuiltInFunctions/TestCastInt.java create mode 100644 src/test/java/Systemtests/LanguageFeatures/BuiltInFunctions/TestCastStr.java create mode 100644 src/test/java/Systemtests/LanguageFeatures/BuiltInFunctions/TestDifferentialExamplePrint.java create mode 100644 src/test/java/Systemtests/LanguageFeatures/BuiltInFunctions/TestId.java create mode 100644 src/test/java/Systemtests/LanguageFeatures/BuiltInFunctions/TestInput.java create mode 100644 src/test/java/Systemtests/LanguageFeatures/BuiltInFunctions/TestMetamorphicExamplePrint.java create mode 100644 src/test/java/Systemtests/LanguageFeatures/BuiltInFunctions/TestPrint.java create mode 100644 src/test/java/Systemtests/LanguageFeatures/BuiltInFunctions/TestType.java create mode 100644 src/test/java/Systemtests/LanguageFeatures/Classes/TestClassInheritance.java create mode 100644 src/test/java/Systemtests/LanguageFeatures/Classes/TestClassInit.java create mode 100644 src/test/java/Systemtests/LanguageFeatures/Classes/TestClassMembers.java create mode 100644 src/test/java/Systemtests/LanguageFeatures/ComparisonOps/TestComparisonOps.java create mode 100644 src/test/java/Systemtests/LanguageFeatures/Conditions/TestElifStatement.java create mode 100644 src/test/java/Systemtests/LanguageFeatures/Conditions/TestElseStatement.java create mode 100644 src/test/java/Systemtests/LanguageFeatures/Conditions/TestIfStatement.java create mode 100644 src/test/java/Systemtests/LanguageFeatures/Conditions/TestWhileStatement.java create mode 100644 src/test/java/Systemtests/LanguageFeatures/DeclarationAndAssignment/TestDeclarationAndAssignment.java create mode 100644 src/test/java/Systemtests/LanguageFeatures/FunctionCalls/TestFunctionBody.java create mode 100644 src/test/java/Systemtests/LanguageFeatures/FunctionCalls/TestFunctionParams.java create mode 100644 src/test/java/Systemtests/LanguageFeatures/FunctionCalls/TestFunctionRecursion.java create mode 100644 src/test/java/Systemtests/LanguageFeatures/FunctionCalls/TestFunctionReturn.java create mode 100644 src/test/java/Systemtests/LanguageFeatures/LogicalOps/TestLogicalOps.java create mode 100644 src/test/java/Systemtests/LanguageFeatures/TestEmpty.java create mode 100644 src/test/java/Systemtests/TestHelpers.java create mode 100644 src/test/java/Systemtests/TestLanguageFeaturesCombined.java diff --git a/src/test/java/Systemtests/LanguageFeatures/ArithmeticOps/TestArithmeticOps.java b/src/test/java/Systemtests/LanguageFeatures/ArithmeticOps/TestArithmeticOps.java new file mode 100644 index 0000000..e74be5c --- /dev/null +++ b/src/test/java/Systemtests/LanguageFeatures/ArithmeticOps/TestArithmeticOps.java @@ -0,0 +1,83 @@ +/* (C)2024 */ +package Systemtests.LanguageFeatures.ArithmeticOps; + +import CBuilder.Expression; +import CBuilder.ProgramBuilder; +import CBuilder.Reference; +import CBuilder.literals.IntLiteral; +import CBuilder.objects.AttributeReference; +import CBuilder.objects.Call; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; +import java.util.stream.Stream; + +import static Systemtests.TestHelpers.getProgramOutput; +import static Systemtests.TestHelpers.makeProgram; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TestArithmeticOps { + String testClass = '[' + this.getClass().getSimpleName().toUpperCase() + "]\n"; + + private static Stream sources() { + return Stream.of( + Arguments.of("__add__", 1, 2, "3\n"), + Arguments.of("__add__", Integer.MAX_VALUE, 0, Integer.MAX_VALUE + "\n"), + Arguments.of("__add__", Integer.MIN_VALUE, 0, Integer.MIN_VALUE + "\n"), + Arguments.of("__sub__", 2, 1, "1\n"), + Arguments.of("__sub__", Integer.MAX_VALUE, 0, Integer.MAX_VALUE + "\n"), + Arguments.of("__sub__", Integer.MIN_VALUE, 0, Integer.MIN_VALUE + "\n"), + Arguments.of("__mul__", 2, 2, "4\n"), + Arguments.of("__mul__", Integer.MAX_VALUE, 0, "0\n"), + Arguments.of("__mul__", Integer.MIN_VALUE, 0, "0\n"), + Arguments.of("__div__", 5, 2, "2\n"), + Arguments.of("__div__", 0, Integer.MAX_VALUE, "0\n"), + Arguments.of("__div__", 0, Integer.MIN_VALUE, "0\n")); + } + + @ParameterizedTest + @MethodSource("sources") + void arithmetic_operation( + String operation, Integer a, Integer b, String expected, @TempDir Path workDirectory) + throws IOException, InterruptedException { + String result; + + generate_arithmetic_operation(workDirectory, operation, a, b); + + makeProgram(workDirectory); + + result = getProgramOutput(workDirectory); + + System.out.println(testClass + "Operation : " + operation + " Result : " + result); + + // Thread.sleep(5000); + assertEquals(expected, result); + } + + /** + *

Mini Python source code : + *
print(a (+,-,*,/) b)

+ * @param a Summand + * @param b Summand + */ + void generate_arithmetic_operation(Path output, String operation, Integer a, Integer b) { + ProgramBuilder builder = new ProgramBuilder(); + + builder.addStatement( + new Call( + new Reference("print"), + List.of( + new Expression[] { + new Call( + new AttributeReference(operation, new IntLiteral(a)), + List.of(new Expression[] {new IntLiteral(b)})) + }))); + + builder.writeProgram(output); + } +} diff --git a/src/test/java/Systemtests/LanguageFeatures/BuiltInFunctions/TestCastInt.java b/src/test/java/Systemtests/LanguageFeatures/BuiltInFunctions/TestCastInt.java new file mode 100644 index 0000000..8e44aec --- /dev/null +++ b/src/test/java/Systemtests/LanguageFeatures/BuiltInFunctions/TestCastInt.java @@ -0,0 +1,105 @@ +/* (C)2024 */ +package Systemtests.LanguageFeatures.BuiltInFunctions; + +import CBuilder.Expression; +import CBuilder.ProgramBuilder; +import CBuilder.Reference; +import CBuilder.literals.BoolLiteral; +import CBuilder.literals.IntLiteral; +import CBuilder.literals.Literal; +import CBuilder.literals.StringLiteral; +import CBuilder.objects.AttributeReference; +import CBuilder.objects.Call; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; +import java.util.stream.Stream; + +import static Systemtests.TestHelpers.getProgramOutput; +import static Systemtests.TestHelpers.makeProgram; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +public class TestCastInt { + String testClass = '[' + this.getClass().getSimpleName().toUpperCase() + "]\n"; + + @ParameterizedTest + @MethodSource("sources_equals") + void cast_int_equals(Literal value, String expected, @TempDir Path workDirectory) + throws IOException, InterruptedException { + String result; + + generate_cast_int(workDirectory, value); + + makeProgram(workDirectory); + + result = getProgramOutput(workDirectory); + + System.out.println(testClass + "Value : " + value + " Result : " + result); + + // Thread.sleep(5000); + assertEquals(expected, result); + } + + @ParameterizedTest + @MethodSource("sources_throws") + void cast_int_throws(Literal value, @TempDir Path workDirectory) + throws IOException, InterruptedException { + String result = ""; + + generate_cast_int(workDirectory, value); + + makeProgram(workDirectory); + + assertThrows(RuntimeException.class, () -> getProgramOutput(workDirectory)); + + System.out.println(testClass + "Value : " + value + " Result : " + result); + + // Thread.sleep(5000); + } + + /** + *

Mini Python source code : + *
print(int( True, False, "23", "0", "-23", 23[error], "false"[error]))

+ */ + void generate_cast_int(Path output, Literal value) { + ProgramBuilder builder = new ProgramBuilder(); + + // builder.addVariable(new VariableDeclaration("a")); + // builder.addStatement(new Assignment(new Reference("a"), value)); + + // new Assignment(new Reference("a"), new Call(new AttributeReference("__int__", new + // Reference("a")), List.of(new Expression[]{}))); + + builder.addStatement( + new Call( + new Reference("print"), + List.of( + new Expression[] { + new Call( + new AttributeReference("__int__", value), + List.of(new Expression[] {})) + }))); + + builder.writeProgram(output); + } + + private static Stream sources_equals() { + return Stream.of( + Arguments.of(new BoolLiteral(true), "1\n"), + Arguments.of(new BoolLiteral(false), "0\n"), + Arguments.of(new StringLiteral("23"), "23\n"), + Arguments.of(new StringLiteral("0"), "0\n"), + Arguments.of(new StringLiteral("-23"), "-23\n")); + } + + private static Stream sources_throws() { + return Stream.of( + Arguments.of(new IntLiteral(23)), Arguments.of(new StringLiteral("false"))); + } +} diff --git a/src/test/java/Systemtests/LanguageFeatures/BuiltInFunctions/TestCastStr.java b/src/test/java/Systemtests/LanguageFeatures/BuiltInFunctions/TestCastStr.java new file mode 100644 index 0000000..21faf8c --- /dev/null +++ b/src/test/java/Systemtests/LanguageFeatures/BuiltInFunctions/TestCastStr.java @@ -0,0 +1,83 @@ +/* (C)2024 */ +package Systemtests.LanguageFeatures.BuiltInFunctions; + +import CBuilder.Expression; +import CBuilder.ProgramBuilder; +import CBuilder.Reference; +import CBuilder.literals.BoolLiteral; +import CBuilder.literals.IntLiteral; +import CBuilder.literals.Literal; +import CBuilder.literals.StringLiteral; +import CBuilder.objects.AttributeReference; +import CBuilder.objects.Call; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; +import java.util.stream.Stream; + +import static Systemtests.TestHelpers.getProgramOutput; +import static Systemtests.TestHelpers.makeProgram; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TestCastStr { + String testClass = '[' + this.getClass().getSimpleName().toUpperCase() + "]\n"; + + private static Stream sources() { + return Stream.of( + Arguments.of(new BoolLiteral(true), "True\n"), + Arguments.of(new BoolLiteral(false), "False\n"), + Arguments.of(new StringLiteral("testString"), "testString\n"), + Arguments.of(new IntLiteral(0), "0\n"), + Arguments.of(new IntLiteral(-23), "-23\n"), + Arguments.of(new IntLiteral(23), "23\n")); + } + + @ParameterizedTest + @MethodSource("sources") + void cast_str(Literal value, String expected, @TempDir Path workDirectory) + throws IOException, InterruptedException { + String result; + + generate_cast_str(workDirectory, value); + + makeProgram(workDirectory); + + result = getProgramOutput(workDirectory); + + System.out.println(testClass + "Value : " + value + " Result : " + result); + + // Thread.sleep(5000); + assertEquals(expected, result); + } + + /** + *

Mini Python source code : + *
print(str( True, False, 23, 0, -23, "testString"))

+ */ + void generate_cast_str(Path output, Literal value) { + ProgramBuilder builder = new ProgramBuilder(); + + // builder.addVariable(new VariableDeclaration("a")); + // builder.addStatement(new Assignment(new Reference("a"), value)); + + // new Assignment(new Reference("a"), new Call(new AttributeReference("__int__", new + // Reference("a")), List.of(new Expression[]{}))); + + builder.addStatement( + new Call( + new Reference("print"), + List.of( + new Expression[] { + new Call( + new AttributeReference("__str__", value), + List.of(new Expression[] {})) + }))); + + builder.writeProgram(output); + } +} diff --git a/src/test/java/Systemtests/LanguageFeatures/BuiltInFunctions/TestDifferentialExamplePrint.java b/src/test/java/Systemtests/LanguageFeatures/BuiltInFunctions/TestDifferentialExamplePrint.java new file mode 100644 index 0000000..05b89f1 --- /dev/null +++ b/src/test/java/Systemtests/LanguageFeatures/BuiltInFunctions/TestDifferentialExamplePrint.java @@ -0,0 +1,84 @@ +/* (C)2024 */ +package Systemtests.LanguageFeatures.BuiltInFunctions; + +import CBuilder.Expression; +import CBuilder.ProgramBuilder; +import CBuilder.Reference; +import CBuilder.literals.IntLiteral; +import CBuilder.objects.Call; +import CBuilder.variables.Assignment; +import CBuilder.variables.VariableDeclaration; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.*; +import java.nio.file.Path; +import java.util.List; + +import static Systemtests.TestHelpers.getProgramOutput; +import static Systemtests.TestHelpers.makeProgram; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TestDifferentialExamplePrint { + + @Test + void call_print(@TempDir Path workDirectory) throws IOException, InterruptedException { + String result; + + generate_call_print(workDirectory); + + makeProgram(workDirectory); + + result = getProgramOutput(workDirectory); + + System.out.println(result); + + ProcessBuilder builder = + new ProcessBuilder( + "bash", "-c", "printf 'a=133\nprint(a)' >> test.py ; python3 test.py"); + builder.directory(workDirectory.toFile()); + // builder.inheritIO(); + + Process p = builder.start(); + + StringBuilder python3Output = new StringBuilder(); + String line; // https://github.com/actions/runner-images + + InputStream processStdOutput = p.getInputStream(); + Reader r = new InputStreamReader(processStdOutput); + BufferedReader br = new BufferedReader(r); + + while ((line = br.readLine()) != null) { + python3Output.append(line).append("\n"); + } + + if (p.waitFor() != 0) { + System.out.println("Could not create file test.py or run python3 test.py !"); + throw new RuntimeException("Could not create file test.py !"); + } + + System.out.println(python3Output); + + // Thread.sleep(5000); + assertEquals(python3Output.toString(), result); + + // After Test + } + + /** + *

Mini Python source code : + *
a = 133 + *
print(a)

+ */ + static void generate_call_print(Path output) { + ProgramBuilder builder = new ProgramBuilder(); + + builder.addVariable(new VariableDeclaration("a")); + builder.addStatement(new Assignment(new Reference("a"), new IntLiteral(133))); + + builder.addStatement( + new Call(new Reference("print"), List.of(new Expression[] {new Reference("a")}))); + + builder.writeProgram(output); + } +} diff --git a/src/test/java/Systemtests/LanguageFeatures/BuiltInFunctions/TestId.java b/src/test/java/Systemtests/LanguageFeatures/BuiltInFunctions/TestId.java new file mode 100644 index 0000000..26f26f7 --- /dev/null +++ b/src/test/java/Systemtests/LanguageFeatures/BuiltInFunctions/TestId.java @@ -0,0 +1,78 @@ +/* (C)2024 */ +package Systemtests.LanguageFeatures.BuiltInFunctions; + +import CBuilder.Expression; +import CBuilder.ProgramBuilder; +import CBuilder.Reference; +import CBuilder.literals.BoolLiteral; +import CBuilder.literals.IntLiteral; +import CBuilder.literals.StringLiteral; +import CBuilder.objects.AttributeReference; +import CBuilder.objects.Call; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; +import java.util.stream.Stream; + +import static Systemtests.TestHelpers.getProgramOutput; +import static Systemtests.TestHelpers.makeProgram; +import static org.junit.jupiter.api.Assertions.assertEquals; + +@Disabled +public class TestId { + String testClass = '[' + this.getClass().getSimpleName().toUpperCase() + "]\n"; + + private static Stream sources() { + return Stream.of( + Arguments.of(new IntLiteral(133), "61\n"), + Arguments.of(new BoolLiteral(true), "61\n"), + Arguments.of(new StringLiteral("toPrint"), "61\n"), + Arguments.of( + new Call( + new AttributeReference("__add__", new IntLiteral(1)), + List.of(new Expression[] {new IntLiteral(1)})), + "102\n")); + } + + @ParameterizedTest + @MethodSource("sources") + void id(Expression toId, String expected, @TempDir Path workDirectory) + throws IOException, InterruptedException { + String result; + + generate_id(workDirectory, toId); + + makeProgram(workDirectory); + + result = getProgramOutput(workDirectory); + + System.out.println(testClass + "toId : " + toId + " Result : " + result); + + // Thread.sleep(5000); + assertEquals(expected, result); + } + + /** + *

Mini Python source code : + *
print(id(133, True, "toPrint", 1+1))

+ */ + void generate_id(Path output, Expression toId) { + ProgramBuilder builder = new ProgramBuilder(); + + builder.addStatement( + new Call( + new Reference("print"), + List.of( + new Expression[] { + new Call(new Reference("id"), List.of(new Expression[] {toId})) + }))); + + builder.writeProgram(output); + } +} diff --git a/src/test/java/Systemtests/LanguageFeatures/BuiltInFunctions/TestInput.java b/src/test/java/Systemtests/LanguageFeatures/BuiltInFunctions/TestInput.java new file mode 100644 index 0000000..acaed43 --- /dev/null +++ b/src/test/java/Systemtests/LanguageFeatures/BuiltInFunctions/TestInput.java @@ -0,0 +1,85 @@ +/* (C)2024 */ +package Systemtests.LanguageFeatures.BuiltInFunctions; + +import CBuilder.Expression; +import CBuilder.ProgramBuilder; +import CBuilder.Reference; +import CBuilder.objects.Call; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.IOException; +import java.nio.file.Path; +import java.time.Duration; +import java.util.List; +import java.util.stream.Stream; + +import static Systemtests.TestHelpers.getProgramOutputBasedOnInput; +import static Systemtests.TestHelpers.makeProgram; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; + +@Disabled +public class TestInput { + String testClass = '[' + this.getClass().getSimpleName().toUpperCase() + "]\n"; + + private static Stream sources() { + return Stream.of( + Arguments.of("61\n", "61\n"), + Arguments.of("True\n", "True\n"), + Arguments.of("!!\n", "!!\n"), + Arguments.of("\n", "\n")); + } + + @ParameterizedTest + @MethodSource("sources") + void input(String input, String expected, @TempDir Path workDirectory) + throws IOException, InterruptedException { + String result = ""; + + generate_input(workDirectory); + + makeProgram(workDirectory); + + result = getProgramOutputBasedOnInput(workDirectory, result, input); + + System.out.println(testClass + "input : " + input + " Result : " + result); + + // Thread.sleep(5000); + assertEquals(expected, result); + } + + @Test + void input_timeout(@TempDir Path workDirectory) throws IOException, InterruptedException { + String input = ""; + String result = ""; + + generate_input(workDirectory); + + makeProgram(workDirectory); + + System.out.println(testClass + "input : " + input + " Result : " + result); + + assertTimeoutPreemptively( + Duration.ofSeconds(5), + () -> getProgramOutputBasedOnInput(workDirectory, result, input)); + } + + void generate_input(Path output) { + ProgramBuilder builder = new ProgramBuilder(); + + builder.addStatement( + new Call( + new Reference("print"), + List.of( + new Expression[] { + new Call(new Reference("input"), List.of(new Expression[] {})) + }))); + + builder.writeProgram(output); + } +} diff --git a/src/test/java/Systemtests/LanguageFeatures/BuiltInFunctions/TestMetamorphicExamplePrint.java b/src/test/java/Systemtests/LanguageFeatures/BuiltInFunctions/TestMetamorphicExamplePrint.java new file mode 100644 index 0000000..86823cb --- /dev/null +++ b/src/test/java/Systemtests/LanguageFeatures/BuiltInFunctions/TestMetamorphicExamplePrint.java @@ -0,0 +1,116 @@ +/* (C)2024 */ +package Systemtests.LanguageFeatures.BuiltInFunctions; + +import CBuilder.Expression; +import CBuilder.ProgramBuilder; +import CBuilder.Reference; +import CBuilder.Statement; +import CBuilder.literals.IntLiteral; +import CBuilder.objects.Call; +import CBuilder.objects.functions.Argument; +import CBuilder.objects.functions.Function; +import CBuilder.variables.Assignment; +import CBuilder.variables.VariableDeclaration; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; + +import static Systemtests.TestHelpers.getProgramOutput; +import static Systemtests.TestHelpers.makeProgram; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TestMetamorphicExamplePrint { + + @Test + void call_print(@TempDir Path workDirectory) throws IOException, InterruptedException { + String result; + String expected = "133\n"; + + generate_call_print(workDirectory); + + makeProgram(workDirectory); + + result = getProgramOutput(workDirectory); + + System.out.println(result); + + // Thread.sleep(5000); + assertEquals(expected, result); + + // After Test + } + + @Test + void print_through_function(@TempDir Path workDirectory) + throws IOException, InterruptedException { + String result; + String expected = "133\n"; + + generate_print_through_function(workDirectory); + + makeProgram(workDirectory); + + result = getProgramOutput(workDirectory); + + System.out.println(result); + + // Thread.sleep(5000); + assertEquals(expected, result); + + // After Test + } + + /** + *

Mini Python source code : + *
a = 133 + *
print(a)

+ */ + static void generate_call_print(Path output) { + ProgramBuilder builder = new ProgramBuilder(); + + builder.addVariable(new VariableDeclaration("a")); + builder.addStatement(new Assignment(new Reference("a"), new IntLiteral(133))); + + builder.addStatement( + new Call(new Reference("print"), List.of(new Expression[] {new Reference("a")}))); + + builder.writeProgram(output); + } + + /** + *

Mini Python source code : + *
a = 133 + *
+ *
def printA(a): + *
print(a) + *
+ *
printA(a) + *

+ */ + static void generate_print_through_function(Path output) { + ProgramBuilder builder = new ProgramBuilder(); + + builder.addVariable(new VariableDeclaration("a")); + builder.addStatement(new Assignment(new Reference("a"), new IntLiteral(133))); + + builder.addFunction( + new Function( + "printA", + List.of( + new Statement[] { + new Call( + new Reference("print"), + List.of(new Expression[] {new Reference("a")})) + }), + List.of(new Argument[] {new Argument("a", 0)}), + List.of())); + + builder.addStatement( + new Call(new Reference("printA"), List.of(new Expression[] {new Reference("a")}))); + + builder.writeProgram(output); + } +} diff --git a/src/test/java/Systemtests/LanguageFeatures/BuiltInFunctions/TestPrint.java b/src/test/java/Systemtests/LanguageFeatures/BuiltInFunctions/TestPrint.java new file mode 100644 index 0000000..f0bc147 --- /dev/null +++ b/src/test/java/Systemtests/LanguageFeatures/BuiltInFunctions/TestPrint.java @@ -0,0 +1,70 @@ +/* (C)2024 */ +package Systemtests.LanguageFeatures.BuiltInFunctions; + +import CBuilder.Expression; +import CBuilder.ProgramBuilder; +import CBuilder.Reference; +import CBuilder.literals.BoolLiteral; +import CBuilder.literals.IntLiteral; +import CBuilder.literals.StringLiteral; +import CBuilder.objects.AttributeReference; +import CBuilder.objects.Call; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; +import java.util.stream.Stream; + +import static Systemtests.TestHelpers.getProgramOutput; +import static Systemtests.TestHelpers.makeProgram; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TestPrint { + String testClass = '[' + this.getClass().getSimpleName().toUpperCase() + "]\n"; + + private static Stream sources() { + return Stream.of( + Arguments.of(new IntLiteral(133), "133\n"), + Arguments.of(new BoolLiteral(true), "True\n"), + Arguments.of(new StringLiteral("toPrint"), "toPrint\n"), + Arguments.of( + new Call( + new AttributeReference("__add__", new IntLiteral(1)), + List.of(new Expression[] {new IntLiteral(1)})), + "2\n")); + } + + @ParameterizedTest + @MethodSource("sources") + void print(Expression toPrint, String expected, @TempDir Path workDirectory) + throws IOException, InterruptedException { + String result; + + generate_print(workDirectory, toPrint); + + makeProgram(workDirectory); + + result = getProgramOutput(workDirectory); + + System.out.println(testClass + "toPrint : " + toPrint + " Result : " + result); + + // Thread.sleep(5000); + assertEquals(expected, result); + } + + /** + *

Mini Python source code : + *
print(133, True, False, "toPrint", 1+1)

+ */ + void generate_print(Path output, Expression toPrint) { + ProgramBuilder builder = new ProgramBuilder(); + + builder.addStatement(new Call(new Reference("print"), List.of(new Expression[] {toPrint}))); + + builder.writeProgram(output); + } +} diff --git a/src/test/java/Systemtests/LanguageFeatures/BuiltInFunctions/TestType.java b/src/test/java/Systemtests/LanguageFeatures/BuiltInFunctions/TestType.java new file mode 100644 index 0000000..bdb55cf --- /dev/null +++ b/src/test/java/Systemtests/LanguageFeatures/BuiltInFunctions/TestType.java @@ -0,0 +1,89 @@ +/* (C)2024 */ +package Systemtests.LanguageFeatures.BuiltInFunctions; + +import CBuilder.Expression; +import CBuilder.ProgramBuilder; +import CBuilder.Reference; +import CBuilder.literals.BoolLiteral; +import CBuilder.literals.IntLiteral; +import CBuilder.literals.Literal; +import CBuilder.literals.StringLiteral; +import CBuilder.objects.AttributeReference; +import CBuilder.objects.Call; +import CBuilder.variables.Assignment; +import CBuilder.variables.VariableDeclaration; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; +import java.util.stream.Stream; + +import static Systemtests.TestHelpers.getProgramOutput; +import static Systemtests.TestHelpers.makeProgram; +import static org.junit.jupiter.api.Assertions.assertEquals; + +@Disabled +public class TestType { + // TODO print(type(a)) seems not to be working see TODO(./src/function-args.c:36) + String testClass = '[' + this.getClass().getSimpleName().toUpperCase() + "]\n"; + + private static Stream sources() { + return Stream.of( + Arguments.of(new IntLiteral(133), "61\n"), + Arguments.of(new BoolLiteral(true), "61\n"), + Arguments.of(new StringLiteral("toPrint"), "61\n"), + Arguments.of( + new Call( + new AttributeReference("__add__", new IntLiteral(1)), + List.of(new Expression[] {new IntLiteral(1)})), + "102\n")); + } + + @ParameterizedTest + @MethodSource("sources") + void type(Literal value, String expected, @TempDir Path workDirectory) + throws IOException, InterruptedException { + String result; + + generate_type(workDirectory, value); + + makeProgram(workDirectory); + + result = getProgramOutput(workDirectory); + + System.out.println(testClass + "toType : " + value + " Result : " + result); + + // Thread.sleep(5000); + assertEquals(expected, result); + } + + /** + *

Mini Python source code : + *
a = (133, True, "toPrint", 1+1) + *
print(type(a)) + *

+ */ + void generate_type(Path output, Expression value) { + ProgramBuilder builder = new ProgramBuilder(); + + builder.addVariable(new VariableDeclaration("a")); + builder.addStatement(new Assignment(new Reference("a"), value)); + + builder.addStatement( + new Call( + new Reference("print"), + List.of( + new Expression[] { + new Call( + new Reference("type"), + List.of(new Expression[] {new Reference("a")})) + }))); + + builder.writeProgram(output); + } +} diff --git a/src/test/java/Systemtests/LanguageFeatures/Classes/TestClassInheritance.java b/src/test/java/Systemtests/LanguageFeatures/Classes/TestClassInheritance.java new file mode 100644 index 0000000..f3f720a --- /dev/null +++ b/src/test/java/Systemtests/LanguageFeatures/Classes/TestClassInheritance.java @@ -0,0 +1,130 @@ +/* (C)2024 */ +package Systemtests.LanguageFeatures.Classes; + +import CBuilder.Expression; +import CBuilder.ProgramBuilder; +import CBuilder.Reference; +import CBuilder.literals.StringLiteral; +import CBuilder.objects.Call; +import CBuilder.objects.MPyClass; +import CBuilder.objects.SuperCall; +import CBuilder.objects.functions.Argument; +import CBuilder.objects.functions.Function; +import CBuilder.variables.Assignment; +import CBuilder.variables.VariableDeclaration; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +import static Systemtests.TestHelpers.getProgramOutput; +import static Systemtests.TestHelpers.makeProgram; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TestClassInheritance { + String testClass = '[' + this.getClass().getSimpleName().toUpperCase() + "]\n"; + + private static Stream sources_equals() { + return Stream.of( + Arguments.of( + new MPyClass( + "ClassA", + new Reference("__MPyType_Object"), + List.of( + new Function( + "__init__", + List.of( + new SuperCall(List.of()), + new Call( + new Reference("print"), + List.of( + new Expression[] { + new StringLiteral( + "[ClassA] Print" + + " from" + + " __init__") + }))), + List.of(new Argument("self", 0)), + List.of())), + Map.of()), + new MPyClass( + "ClassB", + new Reference("ClassA"), + List.of( + new Function( + "__init__", + List.of( + new SuperCall(List.of()), + new Call( + new Reference("print"), + List.of( + new Expression[] { + new StringLiteral( + "[ClassB] Print" + + " from" + + " __init__") + }))), + List.of(new Argument("self", 0)), + List.of())), + Map.of()), + """ + [ClassA] Print from __init__ + [ClassB] Print from __init__ + """)); + } + + @ParameterizedTest + @MethodSource("sources_equals") + void inheritance(MPyClass A, MPyClass B, String expected, @TempDir Path workDirectory) + throws IOException, InterruptedException { + String result; + + generate_inheritance(workDirectory, A, B); + + makeProgram(workDirectory); + + result = getProgramOutput(workDirectory); + + System.out.println(testClass + " Result : " + result); + + // Thread.sleep(5000); + assertEquals(expected, result); + } + + /** + *

Mini Python source code for tests from top to bottom : + *
+ *
class ClassA(__MPyType_Object): + *
+ *
def __init__(self, val): + *
super() + *
print("[ClassA] Print from __init__\n") + *
+ *
class ClassB(A): + *
+ *
def __init__(self, val): + *
super() + *
print("[ClassB] Print from __init__\n") + *
+ *
x = ClassB(123) + */ + void generate_inheritance(Path output, MPyClass parent, MPyClass child) { + ProgramBuilder builder = new ProgramBuilder(); + + builder.addClass(parent); + builder.addClass(child); + + builder.addVariable(new VariableDeclaration("x")); + + builder.addStatement( + new Assignment(new Reference("x"), new Call(new Reference("ClassB"), List.of()))); + + builder.writeProgram(output); + } +} diff --git a/src/test/java/Systemtests/LanguageFeatures/Classes/TestClassInit.java b/src/test/java/Systemtests/LanguageFeatures/Classes/TestClassInit.java new file mode 100644 index 0000000..780011b --- /dev/null +++ b/src/test/java/Systemtests/LanguageFeatures/Classes/TestClassInit.java @@ -0,0 +1,170 @@ +/* (C)2024 */ +package Systemtests.LanguageFeatures.Classes; + +import CBuilder.Expression; +import CBuilder.ProgramBuilder; +import CBuilder.Reference; +import CBuilder.literals.IntLiteral; +import CBuilder.literals.StringLiteral; +import CBuilder.objects.Call; +import CBuilder.objects.MPyClass; +import CBuilder.objects.SuperCall; +import CBuilder.objects.functions.Argument; +import CBuilder.objects.functions.Function; +import CBuilder.variables.Assignment; +import CBuilder.variables.VariableDeclaration; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +import static Systemtests.TestHelpers.getProgramOutput; +import static Systemtests.TestHelpers.makeProgram; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TestClassInit { + String testClass = '[' + this.getClass().getSimpleName().toUpperCase() + "]\n"; + + private static Stream sources_equals() { + return Stream.of( + Arguments.of( + "ClassA", + new Reference("__MPyType_Object"), + List.of( + new Function( + "__init__", + List.of( + new SuperCall(List.of()), + new Call( + new Reference("print"), + List.of( + new Expression[] { + new StringLiteral( + "[ClassA] Print from" + + " __init__") + }))), + List.of(new Argument("self", 0)), + List.of())), + Map.of(), + List.of(), + "[ClassA] Print from __init__\n"), + Arguments.of( + "ClassB", + new Reference("__MPyType_Object"), + List.of( + new Function( + "__init__", + List.of( + new SuperCall(List.of()), + new Call( + new Reference("print"), + List.of( + new Expression[] { + new StringLiteral( + "[ClassB] Print from" + + " __init__"), + new Reference("x") + }))), + List.of(new Argument("self", 0), new Argument("x", 1)), + List.of())), + Map.of(), + List.of(new StringLiteral("test")), + "[ClassB] Print from __init__ test\n"), + Arguments.of( + "ClassB", + new Reference("__MPyType_Object"), + List.of( + new Function( + "__init__", + List.of( + new SuperCall(List.of()), + new Call( + new Reference("print"), + List.of( + new Expression[] { + new StringLiteral( + "[ClassB] Print from" + + " __init__ Param1" + + " :"), + new Reference("x"), + new StringLiteral(" Param2 : "), + new Reference("y") + }))), + List.of( + new Argument("self", 0), + new Argument("x", 1), + new Argument("y", 2)), + List.of())), + Map.of(), + List.of(new StringLiteral("test"), new IntLiteral(123)), + "[ClassB] Print from __init__ Param1 : test Param2 : 123\n")); + } + + @ParameterizedTest + @MethodSource("sources_equals") + void class_definition( + String className, + Reference parent, + List functions, + Map classAttributes, + List initArgs, + String expected, + @TempDir Path workDirectory) + throws IOException, InterruptedException { + String result; + + generate_class(workDirectory, className, parent, functions, classAttributes, initArgs); + + makeProgram(workDirectory); + + result = getProgramOutput(workDirectory); + + System.out.println(testClass + " Result : " + result); + + // Thread.sleep(5000); + assertEquals(expected, result); + } + + /** + *

Mini Python source code for tests from top to bottom : + *
+ *
class ClassA(__MPyType_Object): + *
+ *
def __init__(self): + *
print("[ClassA] Print from __init__\n") + *
+ *
class ClassB(__MPyType_Object): + *
def __init__(self, x): + *
print("[ClassB] Print from __init__" + str(param1)) + *
+ *
class ClassB(__MPyTypeObject): + *
def __init__(self, x, y): + *
print("[ClassB] Print from __init__ Param1 : " + str(x) + " Param2 : " + str(y)) + *
+ *
x = className(( , param1, (param1,param2))) + */ + void generate_class( + Path output, + String className, + Reference parent, + List functions, + Map classAttributes, + List initArgs) { + ProgramBuilder builder = new ProgramBuilder(); + + builder.addClass(new MPyClass(className, parent, functions, classAttributes)); + + builder.addVariable(new VariableDeclaration("x")); + + builder.addStatement( + new Assignment(new Reference("x"), new Call(new Reference(className), initArgs))); + + builder.writeProgram(output); + } +} diff --git a/src/test/java/Systemtests/LanguageFeatures/Classes/TestClassMembers.java b/src/test/java/Systemtests/LanguageFeatures/Classes/TestClassMembers.java new file mode 100644 index 0000000..2529089 --- /dev/null +++ b/src/test/java/Systemtests/LanguageFeatures/Classes/TestClassMembers.java @@ -0,0 +1,210 @@ +/* (C)2024 */ +package Systemtests.LanguageFeatures.Classes; + +import CBuilder.Expression; +import CBuilder.ProgramBuilder; +import CBuilder.Reference; +import CBuilder.literals.IntLiteral; +import CBuilder.literals.StringLiteral; +import CBuilder.objects.*; +import CBuilder.objects.functions.Argument; +import CBuilder.objects.functions.Function; +import CBuilder.objects.functions.ReturnStatement; +import CBuilder.variables.Assignment; +import CBuilder.variables.VariableDeclaration; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; + +import static Systemtests.TestHelpers.getProgramOutput; +import static Systemtests.TestHelpers.makeProgram; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TestClassMembers { + String testClass = '[' + this.getClass().getSimpleName().toUpperCase() + "]\n"; + + @Test + void getter_setter(@TempDir Path workDirectory) throws IOException, InterruptedException { + String result; + + generate_getter_and_setter( + workDirectory, + new MPyClass( + "ClassB", + new Reference("__MPyType_Object"), + List.of( + new Function( + "__init__", + List.of( + new SuperCall(List.of()), + new Call( + new Reference("print"), + List.of( + new Expression[] { + new StringLiteral( + "[ClassB] Print from" + + " __init__") + })), + new AttributeAssignment( + new AttributeReference( + "x", new Reference("self")), + new Reference("val"))), + List.of(new Argument("self", 0), new Argument("val", 1)), + List.of()), + new Function( + "getX", + List.of( + new ReturnStatement( + new AttributeReference( + "x", new Reference("self")))), + List.of(new Argument("self", 0)), + List.of()), + new Function( + "setX", + List.of( + new AttributeAssignment( + new AttributeReference( + "x", new Reference("self")), + new Reference("newVal"))), + List.of(new Argument("self", 0), new Argument("newVal", 1)), + List.of())), + Map.of()), + List.of(new IntLiteral(133))); + + makeProgram(workDirectory); + + result = getProgramOutput(workDirectory); + + System.out.println(testClass + " Result : " + result); + + // Thread.sleep(5000); + assertEquals("[ClassB] Print from __init__\n23\n", result); + } + + /** + *

Mini Python source code for tests from top to bottom : + *
+ *
class A(__MPyType_Object): + *
+ *
def __init__(self, val): + *
super() + *
print("[ClassB] Print from __init__\n") + *
self.x = val + *
+ *
def getX(self): + *
return self.x + *
+ *
def setX(self, newVal): + *
self.x = newVal + *
+ *
+ *
x = A(123) + *
x.setX(23) + *
print(x.getX()) + */ + void generate_getter_and_setter(Path output, MPyClass mpyClass, List initArgs) { + ProgramBuilder builder = new ProgramBuilder(); + + builder.addClass(mpyClass); + + builder.addVariable(new VariableDeclaration("x")); + + builder.addStatement( + new Assignment( + new Reference("x"), new Call(new Reference(mpyClass.getName()), initArgs))); + + builder.addStatement( + new Call( + new AttributeReference("setX", new Reference("x")), + List.of(new IntLiteral(23)))); + + builder.addStatement( + new Call( + new Reference("print"), + List.of( + new Expression[] { + new Call( + new AttributeReference("getX", new Reference("x")), + List.of()) + }))); + + builder.writeProgram(output); + } + + @Test + void getter(@TempDir Path workDirectory) throws IOException, InterruptedException { + String result; + + generate_getter( + workDirectory, + new MPyClass( + "ClassA", + new Reference("__MPyType_Object"), + List.of( + new Function( + "__init__", + List.of( + new SuperCall(List.of()), + new Call( + new Reference("print"), + List.of( + new Expression[] { + new StringLiteral( + "[ClassA] Print from" + + " __init__") + })), + new AttributeAssignment( + new AttributeReference( + "x", new Reference("self")), + new Reference("val"))), + List.of(new Argument("self", 0), new Argument("val", 1)), + List.of()), + new Function( + "getX", + List.of( + new ReturnStatement( + new AttributeReference( + "x", new Reference("self")))), + List.of(new Argument("self", 0)), + List.of())), + Map.of()), + List.of(new IntLiteral(133))); + + makeProgram(workDirectory); + + result = getProgramOutput(workDirectory); + + System.out.println(testClass + " Result : " + result); + + // Thread.sleep(5000); + assertEquals("[ClassA] Print from __init__\n133\n", result); + } + + void generate_getter(Path output, MPyClass mpyClass, List initArgs) { + ProgramBuilder builder = new ProgramBuilder(); + + builder.addClass(mpyClass); + + builder.addVariable(new VariableDeclaration("x")); + + builder.addStatement( + new Assignment( + new Reference("x"), new Call(new Reference(mpyClass.getName()), initArgs))); + + builder.addStatement( + new Call( + new Reference("print"), + List.of( + new Expression[] { + new Call( + new AttributeReference("getX", new Reference("x")), + List.of()) + }))); + + builder.writeProgram(output); + } +} diff --git a/src/test/java/Systemtests/LanguageFeatures/ComparisonOps/TestComparisonOps.java b/src/test/java/Systemtests/LanguageFeatures/ComparisonOps/TestComparisonOps.java new file mode 100644 index 0000000..971c521 --- /dev/null +++ b/src/test/java/Systemtests/LanguageFeatures/ComparisonOps/TestComparisonOps.java @@ -0,0 +1,83 @@ +/* (C)2024 */ +package Systemtests.LanguageFeatures.ComparisonOps; + +import CBuilder.Expression; +import CBuilder.ProgramBuilder; +import CBuilder.Reference; +import CBuilder.literals.IntLiteral; +import CBuilder.literals.Literal; +import CBuilder.objects.AttributeReference; +import CBuilder.objects.Call; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; +import java.util.stream.Stream; + +import static Systemtests.TestHelpers.getProgramOutput; +import static Systemtests.TestHelpers.makeProgram; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TestComparisonOps { + String testClass = '[' + this.getClass().getSimpleName().toUpperCase() + "]\n"; + + private static Stream sources() { + return Stream.of( + Arguments.of("__eq__", new IntLiteral(1), new IntLiteral(1), "True\n"), + Arguments.of("__eq__", new IntLiteral(1), new IntLiteral(0), "False\n"), + Arguments.of("__ne__", new IntLiteral(1), new IntLiteral(1), "False\n"), + Arguments.of("__ne__", new IntLiteral(1), new IntLiteral(0), "True\n"), + Arguments.of("__ge__", new IntLiteral(1), new IntLiteral(2), "False\n"), + Arguments.of("__ge__", new IntLiteral(2), new IntLiteral(1), "True\n"), + Arguments.of("__gt__", new IntLiteral(1), new IntLiteral(2), "False\n"), + Arguments.of("__gt__", new IntLiteral(2), new IntLiteral(1), "True\n"), + Arguments.of("__le__", new IntLiteral(1), new IntLiteral(2), "True\n"), + Arguments.of("__le__", new IntLiteral(2), new IntLiteral(1), "False\n"), + Arguments.of("__lt__", new IntLiteral(1), new IntLiteral(2), "True\n"), + Arguments.of("__lt__", new IntLiteral(2), new IntLiteral(1), "False\n")); + } + + @ParameterizedTest + @MethodSource("sources") + void comparison_operation( + String operation, Literal a, Literal b, String expected, @TempDir Path workDirectory) + throws IOException, InterruptedException { + String result; + + generate_comparison_operation(workDirectory, operation, a, b); + + makeProgram(workDirectory); + + result = getProgramOutput(workDirectory); + + System.out.println(testClass + "Operation : " + operation + " Result : " + result); + + // Thread.sleep(5000); + assertEquals(expected, result); + } + + /** + *

Mini Python source code : + *
a = 133 + *
print(a (==, !=, <, <=, >, >=) b)

+ */ + void generate_comparison_operation(Path output, String operation, Literal a, Literal b) { + ProgramBuilder builder = new ProgramBuilder(); + + builder.addStatement( + new Call( + new Reference("print"), + List.of( + new Expression[] { + new Call( + new AttributeReference(operation, a), + List.of(new Expression[] {b})) + }))); + + builder.writeProgram(output); + } +} diff --git a/src/test/java/Systemtests/LanguageFeatures/Conditions/TestElifStatement.java b/src/test/java/Systemtests/LanguageFeatures/Conditions/TestElifStatement.java new file mode 100644 index 0000000..d1fc362 --- /dev/null +++ b/src/test/java/Systemtests/LanguageFeatures/Conditions/TestElifStatement.java @@ -0,0 +1,132 @@ +/* (C)2024 */ +package Systemtests.LanguageFeatures.Conditions; + +import CBuilder.Expression; +import CBuilder.ProgramBuilder; +import CBuilder.Reference; +import CBuilder.conditions.IfThenElseStatement; +import CBuilder.conditions.conditionalStatement.ElifStatement; +import CBuilder.conditions.conditionalStatement.IfStatement; +import CBuilder.literals.BoolLiteral; +import CBuilder.literals.StringLiteral; +import CBuilder.objects.Call; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; +import java.util.Optional; +import java.util.stream.Stream; + +import static Systemtests.TestHelpers.getProgramOutput; +import static Systemtests.TestHelpers.makeProgram; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TestElifStatement { + String testClass = '[' + this.getClass().getSimpleName().toUpperCase() + "]\n"; + + private static Stream sources() { + return Stream.of( + Arguments.of( + new IfStatement( + new BoolLiteral(false), + List.of( + new Call( + new Reference("print"), + List.of( + new Expression[] { + new StringLiteral( + "Went into if Statement") + })))), + Optional.of( + List.of( + new ElifStatement( + new BoolLiteral(true), + List.of( + new Call( + new Reference("print"), + List.of( + new Expression[] { + new StringLiteral( + "Went into Elif" + + " Statement") + })))))), + "Went into Elif Statement\n"), + Arguments.of( + new IfStatement( + new BoolLiteral(true), + List.of( + new Call( + new Reference("print"), + List.of( + new Expression[] { + new StringLiteral( + "Went into if Statement") + })))), + Optional.of( + List.of( + new ElifStatement( + new BoolLiteral(false), + List.of( + new Call( + new Reference("print"), + List.of( + new Expression[] { + new StringLiteral( + "Went into Elif" + + " Statement") + })))))), + "Went into if Statement\n")); + } + + @ParameterizedTest + @MethodSource("sources") + void elif_statement( + IfStatement ifStatement, + Optional> elifStatement, + String expected, + @TempDir Path workDirectory) + throws IOException, InterruptedException { + String result; + + generate_elif_statement(workDirectory, ifStatement, elifStatement); + + makeProgram(workDirectory); + + result = getProgramOutput(workDirectory); + + System.out.println( + testClass + + "If Statement : " + + ifStatement + + " Elif Statement : " + + elifStatement + + " Result : " + + result); + + // Thread.sleep(5000); + assertEquals(expected, result); + } + + /** + *

Mini Python source code : + *
+ *
if(false/true): + *
print("Went inside if!") + *
+ *
elif(true/false): + *
print("Went inside elif!") + *

+ */ + void generate_elif_statement( + Path output, IfStatement ifStatement, Optional> elifStatement) { + ProgramBuilder builder = new ProgramBuilder(); + + builder.addStatement(new IfThenElseStatement(ifStatement, elifStatement, Optional.empty())); + + builder.writeProgram(output); + } +} diff --git a/src/test/java/Systemtests/LanguageFeatures/Conditions/TestElseStatement.java b/src/test/java/Systemtests/LanguageFeatures/Conditions/TestElseStatement.java new file mode 100644 index 0000000..de9dc7c --- /dev/null +++ b/src/test/java/Systemtests/LanguageFeatures/Conditions/TestElseStatement.java @@ -0,0 +1,128 @@ +/* (C)2024 */ +package Systemtests.LanguageFeatures.Conditions; + +import CBuilder.Expression; +import CBuilder.ProgramBuilder; +import CBuilder.Reference; +import CBuilder.conditions.IfThenElseStatement; +import CBuilder.conditions.conditionalStatement.ElseStatement; +import CBuilder.conditions.conditionalStatement.IfStatement; +import CBuilder.literals.BoolLiteral; +import CBuilder.literals.StringLiteral; +import CBuilder.objects.Call; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; +import java.util.Optional; +import java.util.stream.Stream; + +import static Systemtests.TestHelpers.getProgramOutput; +import static Systemtests.TestHelpers.makeProgram; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TestElseStatement { + String testClass = '[' + this.getClass().getSimpleName().toUpperCase() + "]\n"; + + private static Stream sources() { + return Stream.of( + Arguments.of( + new IfStatement( + new BoolLiteral(false), + List.of( + new Call( + new Reference("print"), + List.of( + new Expression[] { + new StringLiteral( + "Went into if Statement") + })))), + Optional.of( + new ElseStatement( + List.of( + new Call( + new Reference("print"), + List.of( + new Expression[] { + new StringLiteral( + "Went into else" + + " Statement") + }))))), + "Went into else Statement\n"), + Arguments.of( + new IfStatement( + new BoolLiteral(true), + List.of( + new Call( + new Reference("print"), + List.of( + new Expression[] { + new StringLiteral( + "Went into if Statement") + })))), + Optional.of( + new ElseStatement( + List.of( + new Call( + new Reference("print"), + List.of( + new Expression[] { + new StringLiteral( + "Went into else" + + " Statement") + }))))), + "Went into if Statement\n")); + } + + @ParameterizedTest + @MethodSource("sources") + void else_statement( + IfStatement ifStatement, + Optional elseStatement, + String expected, + @TempDir Path workDirectory) + throws IOException, InterruptedException { + String result; + + generate_else_statement(workDirectory, ifStatement, elseStatement); + + makeProgram(workDirectory); + + result = getProgramOutput(workDirectory); + + System.out.println( + testClass + + "If Statement : " + + ifStatement + + " Elif Statement : " + + elseStatement + + " Result : " + + result); + + // Thread.sleep(5000); + assertEquals(expected, result); + } + + /** + *

Mini Python source code : + *
+ *
if(false/true): + *
print("Went inside if!") + *
+ *
else: + *
print("Went inside else!") + *

+ */ + void generate_else_statement( + Path output, IfStatement ifStatement, Optional elseStatement) { + ProgramBuilder builder = new ProgramBuilder(); + + builder.addStatement(new IfThenElseStatement(ifStatement, Optional.empty(), elseStatement)); + + builder.writeProgram(output); + } +} diff --git a/src/test/java/Systemtests/LanguageFeatures/Conditions/TestIfStatement.java b/src/test/java/Systemtests/LanguageFeatures/Conditions/TestIfStatement.java new file mode 100644 index 0000000..c1da704 --- /dev/null +++ b/src/test/java/Systemtests/LanguageFeatures/Conditions/TestIfStatement.java @@ -0,0 +1,117 @@ +/* (C)2024 */ +package Systemtests.LanguageFeatures.Conditions; + +import CBuilder.Expression; +import CBuilder.ProgramBuilder; +import CBuilder.Reference; +import CBuilder.Statement; +import CBuilder.conditions.IfThenElseStatement; +import CBuilder.conditions.conditionalStatement.IfStatement; +import CBuilder.literals.BoolLiteral; +import CBuilder.literals.IntLiteral; +import CBuilder.literals.StringLiteral; +import CBuilder.objects.Call; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; +import java.util.Optional; +import java.util.stream.Stream; + +import static Systemtests.TestHelpers.getProgramOutput; +import static Systemtests.TestHelpers.makeProgram; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TestIfStatement { + String testClass = '[' + this.getClass().getSimpleName().toUpperCase() + "]\n"; + + private static Stream sources() { + return Stream.of( + Arguments.of( + new BoolLiteral(false), + List.of( + new Call( + new Reference("print"), + List.of( + new Expression[] { + new StringLiteral("Went into if Statement") + }))), + ""), + Arguments.of( + new BoolLiteral(true), + List.of( + new Call( + new Reference("print"), + List.of( + new Expression[] { + new StringLiteral("Went into if Statement") + }))), + "Went into if Statement\n"), + Arguments.of( + new IntLiteral(0), + List.of( + new Call( + new Reference("print"), + List.of( + new Expression[] { + new StringLiteral("Went into if Statement") + }))), + ""), + Arguments.of( + new IntLiteral(1), + List.of( + new Call( + new Reference("print"), + List.of( + new Expression[] { + new StringLiteral("Went into if Statement") + }))), + "Went into if Statement\n")); + } + + @ParameterizedTest + @MethodSource("sources") + void if_statement( + Expression condition, + List statementList, + String expected, + @TempDir Path workDirectory) + throws IOException, InterruptedException { + String result; + + generate_if_statement(workDirectory, condition, statementList); + + makeProgram(workDirectory); + + result = getProgramOutput(workDirectory); + + System.out.println(testClass + "Condition : " + condition + " Result : " + result); + + // Thread.sleep(5000); + assertEquals(expected, result); + } + + /** + *

Mini Python source code : + *
+ *
if(false/true, 0, 1): + *
print("Went into if Statement") + *
+ *

+ */ + void generate_if_statement(Path output, Expression condition, List statementList) { + ProgramBuilder builder = new ProgramBuilder(); + + builder.addStatement( + new IfThenElseStatement( + new IfStatement(condition, statementList), + Optional.empty(), + Optional.empty())); + + builder.writeProgram(output); + } +} diff --git a/src/test/java/Systemtests/LanguageFeatures/Conditions/TestWhileStatement.java b/src/test/java/Systemtests/LanguageFeatures/Conditions/TestWhileStatement.java new file mode 100644 index 0000000..4f51fc5 --- /dev/null +++ b/src/test/java/Systemtests/LanguageFeatures/Conditions/TestWhileStatement.java @@ -0,0 +1,93 @@ +/* (C)2024 */ +package Systemtests.LanguageFeatures.Conditions; + +import CBuilder.Expression; +import CBuilder.ProgramBuilder; +import CBuilder.Reference; +import CBuilder.Statement; +import CBuilder.conditions.conditionalStatement.WhileStatement; +import CBuilder.literals.IntLiteral; +import CBuilder.objects.AttributeReference; +import CBuilder.objects.Call; +import CBuilder.variables.Assignment; +import CBuilder.variables.VariableDeclaration; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; +import java.util.stream.Stream; + +import static Systemtests.TestHelpers.getProgramOutput; +import static Systemtests.TestHelpers.makeProgram; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TestWhileStatement { + String testClass = '[' + this.getClass().getSimpleName().toUpperCase() + "]\n"; + + private static Stream sources() { + return Stream.of( + Arguments.of( + new Call( + new AttributeReference("__gt__", new Reference("a")), + List.of(new Expression[] {new IntLiteral(1)})), + List.of( + new Call( + new Reference("print"), + List.of(new Expression[] {new Reference("a")})), + new Assignment( + new Reference("a"), + new Call( + new AttributeReference( + "__sub__", new Reference("a")), + List.of(new Expression[] {new IntLiteral(1)})))), + "3\n2\n")); + } + + @ParameterizedTest + @MethodSource("sources") + void while_statement( + Expression condition, + List statementList, + String expected, + @TempDir Path workDirectory) + throws IOException, InterruptedException { + String result; + + generate_while_statement(workDirectory, condition, statementList); + + makeProgram(workDirectory); + + result = getProgramOutput(workDirectory); + + System.out.println(testClass + "Condition : " + condition + " Result : " + result); + + // Thread.sleep(5000); + assertEquals(expected, result); + } + + /** + *

Mini Python source code : + *
+ *
a = 3 + *
+ *
while(a > 1): + *
print(a) + *
a = a - 1 + *

+ */ + void generate_while_statement( + Path output, Expression condition, List statementList) { + ProgramBuilder builder = new ProgramBuilder(); + + builder.addVariable(new VariableDeclaration("a")); + builder.addStatement(new Assignment(new Reference("a"), new IntLiteral(3))); + + builder.addStatement(new WhileStatement(condition, statementList)); + + builder.writeProgram(output); + } +} diff --git a/src/test/java/Systemtests/LanguageFeatures/DeclarationAndAssignment/TestDeclarationAndAssignment.java b/src/test/java/Systemtests/LanguageFeatures/DeclarationAndAssignment/TestDeclarationAndAssignment.java new file mode 100644 index 0000000..07e25d6 --- /dev/null +++ b/src/test/java/Systemtests/LanguageFeatures/DeclarationAndAssignment/TestDeclarationAndAssignment.java @@ -0,0 +1,290 @@ +/* (C)2024 */ +package Systemtests.LanguageFeatures.DeclarationAndAssignment; + +import CBuilder.Expression; +import CBuilder.ProgramBuilder; +import CBuilder.Reference; +import CBuilder.Statement; +import CBuilder.literals.BoolLiteral; +import CBuilder.literals.IntLiteral; +import CBuilder.literals.Literal; +import CBuilder.literals.StringLiteral; +import CBuilder.objects.Call; +import CBuilder.objects.functions.Argument; +import CBuilder.objects.functions.Function; +import CBuilder.variables.Assignment; +import CBuilder.variables.VariableDeclaration; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; +import java.util.stream.Stream; + +import static Systemtests.TestHelpers.getProgramOutput; +import static Systemtests.TestHelpers.makeProgram; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TestDeclarationAndAssignment { + String testClass = '[' + this.getClass().getSimpleName().toUpperCase() + "]\n"; + + private static Stream source_literals() { + return Stream.of( + Arguments.of(new IntLiteral(133), "133\n"), + Arguments.of(new StringLiteral("stringVal"), "stringVal\n"), + Arguments.of(new BoolLiteral(true), "True\n")); + } + + @Test + void declaration_and_assignment(@TempDir Path workDirectory) + throws IOException, InterruptedException { + String result; + String expected = + """ + 133 + 133 + 133 + 133 + """; + + generate_declaration_and_assignment(workDirectory); + + makeProgram(workDirectory); + + result = getProgramOutput(workDirectory); + + System.out.println(testClass + result); + + // Thread.sleep(5000); + assertEquals(expected, result); + + // After Test + } + + @ParameterizedTest + @MethodSource("source_literals") + void assignment_literal(Literal literal, String expected, @TempDir Path workDirectory) + throws IOException, InterruptedException { + String result; + + generate_assignment_literal(workDirectory, literal); + + makeProgram(workDirectory); + + result = getProgramOutput(workDirectory); + + System.out.println(testClass + result); + + // Thread.sleep(5000); + assertEquals(expected, result); + + // After Test + } + + @Test + void assignment_reference(@TempDir Path workDirectory) + throws IOException, InterruptedException { + String result; + String expected = "133\n"; + + generate_assignment_reference(workDirectory); + + makeProgram(workDirectory); + + result = getProgramOutput(workDirectory); + + System.out.println(testClass + result); + + // Thread.sleep(5000); + assertEquals(expected, result); + + // After Test + } + + @Test + void assignment_function_call(@TempDir Path workDirectory) + throws IOException, InterruptedException { + String result; + String expected = "133\n"; + + generate_assignment_function_call(workDirectory); + + makeProgram(workDirectory); + + result = getProgramOutput(workDirectory); + + System.out.println(testClass + result); + + // Thread.sleep(5000); + assertEquals(expected, result); + + // After Test + } + + @Test + void assignment_function(@TempDir Path workDirectory) throws IOException, InterruptedException { + String result; + String expected = "133\n"; + + generate_assignment_function_call(workDirectory); + + makeProgram(workDirectory); + + result = getProgramOutput(workDirectory); + + System.out.println(testClass + result); + + // Thread.sleep(5000); + assertEquals(expected, result); + + // After Test + } + + /** + * Mini-Python code of program generated : + * a + * a = 133 + *

+ * b + * b = a + *

+ * c = print(a) + *

+ *

+ * d + * def printA(a): + * print(a) + * d = printA + *

+ * print(a) + * print(b) + * c + * d(a) + */ + static void generate_declaration_and_assignment(Path output) { + ProgramBuilder builder = new ProgramBuilder(); + builder.addVariable(new VariableDeclaration("a")); + builder.addStatement(new Assignment(new Reference("a"), new IntLiteral(133))); // a = 133 + + builder.addVariable(new VariableDeclaration("b")); // b + builder.addStatement(new Assignment(new Reference("b"), new Reference("a"))); // b = a + + builder.addVariable(new VariableDeclaration("c")); + builder.addStatement( + new Assignment( + new Reference("c"), + new Call( + new Reference("print"), + List.of(new Expression[] {new Reference("a")})))); // c = print(a) + + builder.addVariable(new VariableDeclaration("d")); + builder.addFunction( + new Function( + "printA", + List.of( + new Statement[] { + new Call( + new Reference("print"), + List.of(new Expression[] {new Reference("a")})) + }), + List.of(new Argument[] {new Argument("a", 0)}), + List.of())); // d def printA(a): printa(a) + + builder.addStatement( + new Assignment(new Reference("d"), new Reference("printA"))); // d = printA + + builder.addStatement( + new Call(new Reference("print"), List.of(new Expression[] {new Reference("a")}))); + + builder.addStatement( + new Call(new Reference("print"), List.of(new Expression[] {new Reference("b")}))); + + builder.addStatement( + new Call( + new Reference("d"), + List.of(new Expression[] {new Reference("a")}))); // d(a) + + builder.writeProgram(output); + } + + /** + *

Mini Python source code : + *
a = 133 + *
print(a)

+ * @param output writeProgram to here + */ + static void generate_assignment_literal(Path output, Literal literal) { + ProgramBuilder builder = new ProgramBuilder(); + + builder.addVariable(new VariableDeclaration("a")); + builder.addStatement(new Assignment(new Reference("a"), literal)); + + builder.addStatement( + new Call(new Reference("print"), List.of(new Expression[] {new Reference("a")}))); + + builder.writeProgram(output); + } + + /** + *

Mini python source code : + *
a = 133 + *
b = a + *
print(b)

+ * @param output writeProgram to here + */ + static void generate_assignment_reference(Path output) { + ProgramBuilder builder = new ProgramBuilder(); + + builder.addVariable(new VariableDeclaration("a")); + builder.addStatement(new Assignment(new Reference("a"), new IntLiteral(133))); + + builder.addVariable(new VariableDeclaration("b")); + builder.addStatement(new Assignment(new Reference("b"), new Reference("a"))); + + builder.addStatement( + new Call(new Reference("print"), List.of(new Expression[] {new Reference("b")}))); + + builder.writeProgram(output); + } + + /** + *

Mini python source code : + *
a = 133 + *
b + *
def printA(a): + *
print(a) + *
b = printA + *
b(a)

+ * + * @param output writeProgram to here + */ + static void generate_assignment_function_call(Path output) { + ProgramBuilder builder = new ProgramBuilder(); + + builder.addVariable(new VariableDeclaration("a")); + builder.addStatement(new Assignment(new Reference("a"), new IntLiteral(133))); + + builder.addVariable(new VariableDeclaration("b")); + builder.addFunction( + new Function( + "printA", + List.of( + new Statement[] { + new Call( + new Reference("print"), + List.of(new Expression[] {new Reference("a")})) + }), + List.of(new Argument[] {new Argument("a", 0)}), + List.of())); + + builder.addStatement(new Assignment(new Reference("b"), new Reference("printA"))); + builder.addStatement( + new Call(new Reference("b"), List.of(new Expression[] {new Reference("a")}))); + + builder.writeProgram(output); + } +} diff --git a/src/test/java/Systemtests/LanguageFeatures/FunctionCalls/TestFunctionBody.java b/src/test/java/Systemtests/LanguageFeatures/FunctionCalls/TestFunctionBody.java new file mode 100644 index 0000000..5dd42cb --- /dev/null +++ b/src/test/java/Systemtests/LanguageFeatures/FunctionCalls/TestFunctionBody.java @@ -0,0 +1,191 @@ +/* (C)2024 */ +package Systemtests.LanguageFeatures.FunctionCalls; + +import CBuilder.Expression; +import CBuilder.ProgramBuilder; +import CBuilder.Reference; +import CBuilder.Statement; +import CBuilder.conditions.IfThenElseStatement; +import CBuilder.conditions.conditionalStatement.IfStatement; +import CBuilder.literals.IntLiteral; +import CBuilder.literals.StringLiteral; +import CBuilder.objects.AttributeReference; +import CBuilder.objects.Call; +import CBuilder.objects.functions.Argument; +import CBuilder.objects.functions.Function; +import CBuilder.objects.functions.ReturnStatement; +import CBuilder.variables.Assignment; +import CBuilder.variables.VariableDeclaration; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; +import java.util.Optional; +import java.util.stream.Stream; + +import static Systemtests.TestHelpers.getProgramOutput; +import static Systemtests.TestHelpers.makeProgram; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TestFunctionBody { + String testClass = '[' + this.getClass().getSimpleName().toUpperCase() + "]\n"; + + /** + *

Mini Python source code for tests from top to bottom : + *
+ *
def function1(): + *
return "" + *
+ *
def function1(): + *
print("Print from function body") + *
+ *
def function1(): + *
y = 133 + *
return y + *
+ *
def function1(x): + *
return x + *
+ *
def function1(x, y): + *
return x + y + *
+ *
def function1(x, y): + *
if(x >= 0): + *
return x + y + *
+ *
print(function1()) + *

+ */ + private static Stream sources_equals() { + return Stream.of( + Arguments.of( + "function1", + List.of(new ReturnStatement(new StringLiteral(""))), + List.of(), + List.of(), + List.of(), + "\n"), + Arguments.of( + "function1", + List.of( + new Call( + new Reference("print"), + List.of( + new Expression[] { + new StringLiteral("Print from function body") + })), + new ReturnStatement(new StringLiteral(""))), + List.of(), + List.of(), + List.of(), + "Print from function body\n\n"), + Arguments.of( + "function1", + List.of( + new Assignment(new Reference("y"), new IntLiteral(133)), + new ReturnStatement(new Reference("y"))), + List.of(), + List.of(new VariableDeclaration("y")), + List.of(), + "133\n"), + Arguments.of( + "function1", + List.of(new ReturnStatement(new Reference("x"))), + List.of(new Argument("x", 0)), + List.of(), + List.of(new IntLiteral(133)), + "133\n"), + Arguments.of( + "function1", + List.of( + new ReturnStatement( + new Call( + new AttributeReference( + "__add__", new Reference("x")), + List.of(new Expression[] {new Reference("y")})))), + List.of(new Argument("x", 0), new Argument("y", 1)), + List.of(), + List.of(new IntLiteral(1), new IntLiteral(3)), + "4\n"), + Arguments.of( + "function1", + List.of( + new IfThenElseStatement( + new IfStatement( + new Call( + new AttributeReference( + "__ge__", new Reference("x")), + List.of( + new Expression[] { + new IntLiteral(0) + })), + List.of( + new ReturnStatement( + new Call( + new AttributeReference( + "__add__", + new Reference("x")), + List.of( + new Expression[] { + new Reference( + "y") + }))))), + Optional.empty(), + Optional.empty())), + List.of(new Argument("x", 0), new Argument("y", 1)), + List.of(), + List.of(new IntLiteral(1), new IntLiteral(3)), + "4\n")); + } + + @ParameterizedTest + @MethodSource("sources_equals") + void function( + String funcName, + List body, + List positionalArgs, + List localVariables, + List args, + String expected, + @TempDir Path workDirectory) + throws IOException, InterruptedException { + String result; + + generate_function(workDirectory, funcName, body, positionalArgs, localVariables, args); + + makeProgram(workDirectory); + + result = getProgramOutput(workDirectory); + + System.out.println(testClass + " Result : " + result); + + // Thread.sleep(5000); + assertEquals(expected, result); + } + + void generate_function( + Path output, + String funcName, + List body, + List positionalArgs, + List localVariables, + List args) { + ProgramBuilder builder = new ProgramBuilder(); + + // builder.addVariable(new VariableDeclaration("a")); + // builder.addStatement(new Assignment(new Reference("a"), value)); + + builder.addFunction(new Function(funcName, body, positionalArgs, localVariables)); + + builder.addStatement( + new Call( + new Reference("print"), + List.of(new Expression[] {new Call(new Reference("function1"), args)}))); + + builder.writeProgram(output); + } +} diff --git a/src/test/java/Systemtests/LanguageFeatures/FunctionCalls/TestFunctionParams.java b/src/test/java/Systemtests/LanguageFeatures/FunctionCalls/TestFunctionParams.java new file mode 100644 index 0000000..ab69adb --- /dev/null +++ b/src/test/java/Systemtests/LanguageFeatures/FunctionCalls/TestFunctionParams.java @@ -0,0 +1,214 @@ +/* (C)2024 */ +package Systemtests.LanguageFeatures.FunctionCalls; + +import CBuilder.Expression; +import CBuilder.ProgramBuilder; +import CBuilder.Reference; +import CBuilder.Statement; +import CBuilder.literals.BoolLiteral; +import CBuilder.literals.IntLiteral; +import CBuilder.literals.StringLiteral; +import CBuilder.objects.AttributeReference; +import CBuilder.objects.Call; +import CBuilder.objects.functions.Argument; +import CBuilder.objects.functions.Function; +import CBuilder.objects.functions.ReturnStatement; +import CBuilder.variables.VariableDeclaration; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; +import java.util.stream.Stream; + +import static Systemtests.TestHelpers.getProgramOutput; +import static Systemtests.TestHelpers.makeProgram; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +public class TestFunctionParams { + String testClass = '[' + this.getClass().getSimpleName().toUpperCase() + "]\n"; + + @ParameterizedTest + @MethodSource("sources_equals") + void function_equals( + String funcName, + List body, + List positionalArgs, + List localVariables, + List args, + String expected, + @TempDir Path workDirectory) + throws IOException, InterruptedException { + String result; + + generate_function(workDirectory, funcName, body, positionalArgs, localVariables, args); + + makeProgram(workDirectory); + + result = getProgramOutput(workDirectory); + + System.out.println(testClass + " Result : " + result); + + // Thread.sleep(5000); + assertEquals(expected, result); + } + + @ParameterizedTest + @MethodSource("sources_fails") + void function_throws( + String funcName, + List body, + List positionalArgs, + List localVariables, + List args, + @TempDir Path workDirectory) + throws IOException, InterruptedException { + String result = ""; + + generate_function(workDirectory, funcName, body, positionalArgs, localVariables, args); + + makeProgram(workDirectory); + + // result = getProgramOutput(workDirectory); + assertThrows(RuntimeException.class, () -> getProgramOutput(workDirectory)); + + System.out.println(testClass + " Result from throws : " + result); + // Thread.sleep(5000); + + } + + /** + *

Mini Python source code for tests from top to bottom : + *
+ *
def function1(): + *
return "" + *
+ *
def function1(param1): + *
return param1 + *
+ *
def function1(param1, param2): + *
return param1 + param2 + *
Calls : + *
+ *
print(function1()) + *
print(function1(123)) + *
print(function1(123,123)) + *
+ *
Functions will Throw runtime error if more or less parameters are passed. + *
Also if a print called is passed as parameter and something is done that cant be done with a function pointer. + */ + void generate_function( + Path output, + String funcName, + List body, + List positionalArgs, + List localVariables, + List args) { + ProgramBuilder builder = new ProgramBuilder(); + + // builder.addVariable(new VariableDeclaration("a")); + // builder.addStatement(new Assignment(new Reference("a"), value)); + + builder.addFunction(new Function(funcName, body, positionalArgs, localVariables)); + + builder.addStatement( + new Call( + new Reference("print"), + List.of(new Expression[] {new Call(new Reference("function1"), args)}))); + + builder.writeProgram(output); + } + + private static Stream sources_equals() { + return Stream.of( + Arguments.of( + "function1", + List.of(new ReturnStatement(new StringLiteral(""))), + List.of(), + List.of(), + List.of(), + "\n"), + Arguments.of( + "function1", + List.of(new ReturnStatement(new Reference("param1"))), + List.of(new Argument("param1", 0)), + List.of(), + List.of(new IntLiteral(0)), + "0\n"), + Arguments.of( + "function1", + List.of(new ReturnStatement(new Reference("param1"))), + List.of(new Argument("param1", 0)), + List.of(), + List.of(new StringLiteral("String")), + "String\n"), + Arguments.of( + "function1", + List.of(new ReturnStatement(new Reference("param1"))), + List.of(new Argument("param1", 0)), + List.of(), + List.of(new BoolLiteral(true)), + "True\n"), + Arguments.of( + "function1", + List.of( + new ReturnStatement( + new Call( + new AttributeReference( + "__add__", new Reference("param1")), + List.of( + new Expression[] { + new Reference("param2") + })))), + List.of(new Argument("param1", 0), new Argument("param2", 1)), + List.of(), + List.of(new IntLiteral(1), new IntLiteral(2)), + "3\n")); + } + + private static Stream sources_fails() { + return Stream.of( + Arguments.of( + "function1", + List.of(new ReturnStatement(new StringLiteral(""))), + List.of(), + List.of(), + List.of(new IntLiteral(133))), + Arguments.of( + "function1", + List.of(new ReturnStatement(new Reference("param1"))), + List.of(new Argument("param1", 0)), + List.of(), + List.of()), + Arguments.of( + "function1", + List.of(new ReturnStatement(new Reference("param1"))), + List.of(new Argument("param1", 0)), + List.of(), + List.of(new StringLiteral("String1"), new StringLiteral("String2"))), + Arguments.of( + "function1", + List.of(new ReturnStatement(new Reference("param1"))), + List.of(new Argument("param1", 0)), + List.of(), + List.of(new Call(new Reference("print"), List.of(new Expression[] {})))), + Arguments.of( + "function1", + List.of( + new ReturnStatement( + new Call( + new AttributeReference( + "__add__", new Reference("param1")), + List.of( + new Expression[] { + new Reference("param2") + })))), + List.of(new Argument("param1", 0), new Argument("param2", 1)), + List.of(), + List.of(new IntLiteral(1)))); + } +} diff --git a/src/test/java/Systemtests/LanguageFeatures/FunctionCalls/TestFunctionRecursion.java b/src/test/java/Systemtests/LanguageFeatures/FunctionCalls/TestFunctionRecursion.java new file mode 100644 index 0000000..447c6ea --- /dev/null +++ b/src/test/java/Systemtests/LanguageFeatures/FunctionCalls/TestFunctionRecursion.java @@ -0,0 +1,139 @@ +/* (C)2024 */ +package Systemtests.LanguageFeatures.FunctionCalls; + +import CBuilder.Expression; +import CBuilder.ProgramBuilder; +import CBuilder.Reference; +import CBuilder.Statement; +import CBuilder.conditions.IfThenElseStatement; +import CBuilder.conditions.conditionalStatement.IfStatement; +import CBuilder.literals.IntLiteral; +import CBuilder.objects.AttributeReference; +import CBuilder.objects.Call; +import CBuilder.objects.functions.Argument; +import CBuilder.objects.functions.Function; +import CBuilder.objects.functions.ReturnStatement; +import CBuilder.variables.Assignment; +import CBuilder.variables.VariableDeclaration; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; +import java.util.Optional; +import java.util.stream.Stream; + +import static Systemtests.TestHelpers.getProgramOutput; +import static Systemtests.TestHelpers.makeProgram; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TestFunctionRecursion { + String testClass = '[' + this.getClass().getSimpleName().toUpperCase() + "]\n"; + + private static Stream sources_equals() { + return Stream.of( + Arguments.of( + "function1", + List.of( + new IfThenElseStatement( + new IfStatement( + new Call( + new AttributeReference( + "__gt__", new Reference("x")), + List.of( + new Expression[] { + new IntLiteral(0) + })), + List.of( + new Assignment( + new Reference("x"), + new Call( + new AttributeReference( + "__sub__", + new Reference("x")), + List.of( + new Expression[] { + new IntLiteral( + 1) + }))), + new Call( + new Reference("print"), + List.of( + new Expression[] { + new Reference("x") + })), + new ReturnStatement( + new Call( + new Reference("function1"), + List.of( + new Expression[] { + new Reference( + "x") + }))))), + Optional.empty(), + Optional.empty()), + new ReturnStatement(new Reference("x"))), + List.of(new Argument("x", 0)), + List.of(), + List.of(new IntLiteral(5)), + "4\n3\n2\n1\n0\n")); + } + + @ParameterizedTest + @MethodSource("sources_equals") + void function( + String funcName, + List body, + List positionalArgs, + List localVariables, + List args, + String expected, + @TempDir Path workDirectory) + throws IOException, InterruptedException { + String result; + + generate_function(workDirectory, funcName, body, positionalArgs, localVariables, args); + + makeProgram(workDirectory); + + result = getProgramOutput(workDirectory); + + System.out.println(testClass + " Result : " + result); + + // Thread.sleep(5000); + assertEquals(expected, result); + } + + /** + *

Mini Python source code : + *
+ *
def function1(x): + *
if(x > 0): + *
x = x - 1 + *
print(x) + *
return function1(x) + *
+ *
function1(5) + */ + void generate_function( + Path output, + String funcName, + List body, + List positionalArgs, + List localVariables, + List args) { + ProgramBuilder builder = new ProgramBuilder(); + + // builder.addVariable(new VariableDeclaration("a")); + // builder.addStatement(new Assignment(new Reference("a"), value)); + + builder.addFunction(new Function(funcName, body, positionalArgs, localVariables)); + + builder.addStatement(new Call(new Reference("function1"), args)); + + builder.writeProgram(output); + } +} diff --git a/src/test/java/Systemtests/LanguageFeatures/FunctionCalls/TestFunctionReturn.java b/src/test/java/Systemtests/LanguageFeatures/FunctionCalls/TestFunctionReturn.java new file mode 100644 index 0000000..cebd76a --- /dev/null +++ b/src/test/java/Systemtests/LanguageFeatures/FunctionCalls/TestFunctionReturn.java @@ -0,0 +1,192 @@ +/* (C)2024 */ +package Systemtests.LanguageFeatures.FunctionCalls; + +import CBuilder.Expression; +import CBuilder.ProgramBuilder; +import CBuilder.Reference; +import CBuilder.Statement; +import CBuilder.keywords.bool.AndKeyword; +import CBuilder.literals.BoolLiteral; +import CBuilder.literals.IntLiteral; +import CBuilder.literals.StringLiteral; +import CBuilder.literals.TupleLiteral; +import CBuilder.objects.Call; +import CBuilder.objects.functions.Argument; +import CBuilder.objects.functions.Function; +import CBuilder.objects.functions.ReturnStatement; +import CBuilder.variables.VariableDeclaration; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; +import java.util.stream.Stream; + +import static Systemtests.TestHelpers.getProgramOutput; +import static Systemtests.TestHelpers.makeProgram; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +public class TestFunctionReturn { + // TODO cannot return tuple literal from function without runtime exception + String testClass = '[' + this.getClass().getSimpleName().toUpperCase() + "]\n"; + + @ParameterizedTest + @MethodSource("sources_equals") + void function_equals( + String funcName, + List body, + List positionalArgs, + List localVariables, + List args, + String expected, + @TempDir Path workDirectory) + throws IOException, InterruptedException { + String result; + + generate_function(workDirectory, funcName, body, positionalArgs, localVariables, args); + + makeProgram(workDirectory); + + result = getProgramOutput(workDirectory); + + System.out.println(testClass + " Result : " + result); + + // Thread.sleep(5000); + assertEquals(expected, result); + } + + @ParameterizedTest + @MethodSource("sources_fails") + void function_fails( + String funcName, + List body, + List positionalArgs, + List localVariables, + List args, + @TempDir Path workDirectory) + throws IOException, InterruptedException { + String result = ""; + + generate_function(workDirectory, funcName, body, positionalArgs, localVariables, args); + + makeProgram(workDirectory); + + assertThrows(RuntimeException.class, () -> getProgramOutput(workDirectory)); + + System.out.println(testClass + " Result : " + result); + } + + void generate_function( + Path output, + String funcName, + List body, + List positionalArgs, + List localVariables, + List args) { + ProgramBuilder builder = new ProgramBuilder(); + + // builder.addVariable(new VariableDeclaration("a")); + // builder.addStatement(new Assignment(new Reference("a"), value)); + + builder.addFunction(new Function(funcName, body, positionalArgs, localVariables)); + + builder.addStatement( + new Call( + new Reference("print"), + List.of( + new Expression[] { + new Call( + new Reference("function1"), + args) // This call works, printing the value crashes! + }))); + + builder.writeProgram(output); + } + + /** + *

Mini Python source code for tests from top to bottom : + *
+ *
def function1(): + *
return "" + *
+ *
def function1(): + *
return 123 + *
+ *
def function1(): + *
return False + *
+ *
def function1(param1): + *
return param1 + *
+ *
def function1(): + *
return (True and True) + *
+ *
print(function1()) + *

+ */ + private static Stream sources_equals() { + return Stream.of( + Arguments.of( + "function1", + List.of(new ReturnStatement(new StringLiteral(""))), + List.of(), + List.of(), + List.of(), + "\n"), + Arguments.of( + "function1", + List.of(new ReturnStatement(new IntLiteral(123))), + List.of(), + List.of(), + List.of(), + "123\n"), + Arguments.of( + "function1", + List.of(new ReturnStatement(new BoolLiteral(false))), + List.of(), + List.of(), + List.of(), + "False\n"), + Arguments.of( + "function1", + List.of(new ReturnStatement(new Reference("param1"))), + List.of(new Argument("param1", 0)), + List.of(), + List.of(new BoolLiteral(true)), + "True\n"), + Arguments.of( + "function1", + List.of( + new ReturnStatement( + new AndKeyword( + new BoolLiteral(true), new BoolLiteral(true)))), + List.of(), + List.of(), + List.of(), + "True\n")); + } + + private static Stream sources_fails() { + return Stream.of( + Arguments.of( + "function1", + List.of(new ReturnStatement(new TupleLiteral(List.of()))), + List.of(), + List.of(), + List.of()), + Arguments.of( + "function1", + List.of( + new ReturnStatement( + new Call( + new Reference("print"), + List.of(new Expression[] {})))), + List.of(), + List.of(), + List.of())); + } +} diff --git a/src/test/java/Systemtests/LanguageFeatures/LogicalOps/TestLogicalOps.java b/src/test/java/Systemtests/LanguageFeatures/LogicalOps/TestLogicalOps.java new file mode 100644 index 0000000..0f4af6d --- /dev/null +++ b/src/test/java/Systemtests/LanguageFeatures/LogicalOps/TestLogicalOps.java @@ -0,0 +1,84 @@ +/* (C)2024 */ +package Systemtests.LanguageFeatures.LogicalOps; + +import CBuilder.Expression; +import CBuilder.ProgramBuilder; +import CBuilder.Reference; +import CBuilder.keywords.bool.AndKeyword; +import CBuilder.keywords.bool.NotKeyword; +import CBuilder.keywords.bool.OrKeyword; +import CBuilder.literals.BoolLiteral; +import CBuilder.objects.Call; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; +import java.util.stream.Stream; + +import static Systemtests.TestHelpers.getProgramOutput; +import static Systemtests.TestHelpers.makeProgram; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TestLogicalOps { + String testClass = '[' + this.getClass().getSimpleName().toUpperCase() + "]\n"; + + private static Stream sources() { + return Stream.of( + Arguments.of( + new AndKeyword(new BoolLiteral(true), new BoolLiteral(true)), "True\n"), + Arguments.of( + new AndKeyword(new BoolLiteral(true), new BoolLiteral(false)), "False\n"), + Arguments.of( + new AndKeyword(new BoolLiteral(false), new BoolLiteral(false)), "False\n"), + Arguments.of( + new AndKeyword(new BoolLiteral(false), new BoolLiteral(true)), "False\n"), + Arguments.of(new OrKeyword(new BoolLiteral(true), new BoolLiteral(true)), "True\n"), + Arguments.of( + new OrKeyword(new BoolLiteral(true), new BoolLiteral(false)), "True\n"), + Arguments.of( + new OrKeyword(new BoolLiteral(false), new BoolLiteral(false)), "False\n"), + Arguments.of( + new OrKeyword(new BoolLiteral(false), new BoolLiteral(true)), "True\n"), + Arguments.of(new NotKeyword(new BoolLiteral(true)), "False\n"), + Arguments.of(new NotKeyword(new BoolLiteral(false)), "True\n")); + } + + @ParameterizedTest + @MethodSource("sources") + void logical_operation(Expression operation, String expected, @TempDir Path workDirectory) + throws IOException, InterruptedException { + String result; + + generate_logical_operation(workDirectory, operation); + + makeProgram(workDirectory); + + result = getProgramOutput(workDirectory); + + System.out.println(testClass + "Operation : " + operation + " Result : " + result); + + // Thread.sleep(5000); + assertEquals(expected, result); + } + + /** + *

Mini Python source code : + *
print(a &&, ||, not b)

+ * @param output writeProgram to here + * + * @param operation logical operation to test for + */ + void generate_logical_operation(Path output, Expression operation) { + ProgramBuilder builder = new ProgramBuilder(); + + builder.addStatement( + new Call(new Reference("print"), List.of(new Expression[] {operation}))); + + builder.writeProgram(output); + System.out.println(builder.buildProgram()); + } +} diff --git a/src/test/java/Systemtests/LanguageFeatures/TestEmpty.java b/src/test/java/Systemtests/LanguageFeatures/TestEmpty.java new file mode 100644 index 0000000..6c327b2 --- /dev/null +++ b/src/test/java/Systemtests/LanguageFeatures/TestEmpty.java @@ -0,0 +1,13 @@ +/* (C)2024 */ +package Systemtests.LanguageFeatures; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TestEmpty { + @Test + void testempty() { + assertEquals(1, 1); + } +} diff --git a/src/test/java/Systemtests/TestHelpers.java b/src/test/java/Systemtests/TestHelpers.java new file mode 100644 index 0000000..275cc28 --- /dev/null +++ b/src/test/java/Systemtests/TestHelpers.java @@ -0,0 +1,81 @@ +/* (C)2024 */ +package Systemtests; + +import java.io.*; +import java.nio.file.Path; + +public class TestHelpers { + + public static String getProgramOutput(Path workDirectory) + throws IOException, InterruptedException { + String line; + StringBuilder result = new StringBuilder(); + ProcessBuilder runner = new ProcessBuilder("./bin/program"); + runner.directory(workDirectory.toFile()); + // runner.inheritIO(); //You can not redirect the stdout/stderr because the Reader will not + + Process rp = runner.start(); + + InputStream processStdOutput = rp.getInputStream(); + Reader r = new InputStreamReader(processStdOutput); + BufferedReader br = new BufferedReader(r); + + while ((line = br.readLine()) != null) { + result.append(line).append("\n"); + } + + // String result = new String(rp.getInputStream().readAllBytes()); + + if (rp.waitFor() != 0) { + throw new RuntimeException("Program returned with value != 0"); + } + return result.toString(); + } + + public static String getProgramOutputBasedOnInput( + Path workDirectory, String result, String input) + throws IOException, InterruptedException { + String line; + ProcessBuilder runner = new ProcessBuilder("./bin/program"); + runner.directory(workDirectory.toFile()); + // runner.inheritIO(); //You can not redirect the stdout/stderr because the Reader will not + // be able to get the output. :) + + Process rp = runner.start(); + + OutputStream os = rp.getOutputStream(); + PrintWriter pw = new PrintWriter(os); + pw.write(input); + pw.flush(); + + InputStream processStdOutput = rp.getInputStream(); + Reader r = new InputStreamReader(processStdOutput); + BufferedReader br = new BufferedReader(r); + + StringBuilder resultBuilder = new StringBuilder(result); + while ((line = br.readLine()) != null) { + resultBuilder.append(line).append("\n"); + } + result = resultBuilder.toString(); + + // String result = new String(rp.getInputStream().readAllBytes()); + + if (rp.waitFor() != 0) { + throw new RuntimeException("Program returned with value != 0"); + } + return result; + } + + public static void makeProgram(Path workDirectory) throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder("make"); + builder.directory(workDirectory.toFile()); + // builder.inheritIO(); + + Process p = builder.start(); + + if (p.waitFor() != 0) { + System.out.println("Could not make program !"); + throw new RuntimeException("Could not make program !"); + } + } +} diff --git a/src/test/java/Systemtests/TestLanguageFeaturesCombined.java b/src/test/java/Systemtests/TestLanguageFeaturesCombined.java new file mode 100644 index 0000000..cf6893b --- /dev/null +++ b/src/test/java/Systemtests/TestLanguageFeaturesCombined.java @@ -0,0 +1,309 @@ +/* (C)2024 */ +package Systemtests; + +import CBuilder.Expression; +import CBuilder.ProgramBuilder; +import CBuilder.Reference; +import CBuilder.Statement; +import CBuilder.literals.IntLiteral; +import CBuilder.objects.*; +import CBuilder.objects.functions.Argument; +import CBuilder.objects.functions.Function; +import CBuilder.variables.Assignment; +import CBuilder.variables.VariableDeclaration; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.List; + +import static Systemtests.TestHelpers.getProgramOutput; +import static Systemtests.TestHelpers.makeProgram; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TestLanguageFeaturesCombined { + @Test + void program(@TempDir Path workDirectory) throws IOException, InterruptedException { + String result; + String expected = + """ + 62 + 62 + -30 + -30 + -50 + 62 + + * a = b + * d = -30 + *

+ * type(a) + * type(d) + *

+ * idA = id(a) + * print(idA) + *

+ * print(id(a)) + * id(print(d)) + * id(type(a)) + *

+ * e = id(type(print(d))) + * e = print(-50) + *

+ * type(type) + *

+ * def printA(a): + * print(a) + * printA(idA) + *

+ * class B: + * def print(self): + * print(self) + *

+ * def __init__(self): + * self.b = 100 + *

+ * class C(B): + * def __init__(self): + *

+ * bObj = B() + * bObj.print() + *

+ * print(bObj.b) + *

+ * cObj = C() + * cOBJ.print() + *

+ * print(cObj.b) + * ``` + */ + static void generateProgram(Path output) { + ProgramBuilder builder = new ProgramBuilder(); + + builder.addVariable(new VariableDeclaration("a")); // a + builder.addVariable(new VariableDeclaration("b")); // b + builder.addStatement(new Assignment(new Reference("a"), new Reference("b"))); // a = b + + // does cause build errors with -Wall + // builder.addVariable(new VariableDeclaration("c")); + // builder.addStatement(new Assignment(new VariableReference("c"), new + // VariableReference("c"))); + + builder.addVariable(new VariableDeclaration("d")); + builder.addStatement(new Assignment(new Reference("d"), new IntLiteral(-30))); // d = -30 + + builder.addStatement( + new Call( + new Reference("type"), + List.of(new Expression[] {new Reference("a")}))); // type(a) + builder.addStatement( + new Call( + new Reference("type"), + List.of(new Expression[] {new Reference("d")}))); // type(d) + + builder.addVariable(new VariableDeclaration("idA")); + builder.addStatement( + new Assignment( + new Reference("idA"), + new Call( + new Reference("id"), + List.of(new Expression[] {new Reference("a")})))); // idA = id(a) + builder.addStatement( + new Call( + new Reference("print"), + List.of(new Expression[] {new Reference("idA")}))); // print(idA) + + // call each built-in function in a nested context to make sure it correctly + // implements refCounts + builder.addStatement( + new Call( + new Reference("print"), + List.of( + new Expression[] { + new Call( + new Reference("id"), + List.of(new Expression[] {new Reference("a")})) + }))); // print(id(a)) + builder.addStatement( + new Call( + new Reference("id"), + List.of( + new Expression[] { + new Call( + new Reference("print"), + List.of(new Expression[] {new Reference("d")})) + }))); // id(print(d)) + builder.addStatement( + new Call( + new Reference("id"), + List.of( + new Expression[] { + new Call( + new Reference("type"), + List.of(new Expression[] {new Reference("a")})) + }))); // id(type(a)) + + // assign a nested function call to a variable + builder.addVariable(new VariableDeclaration("e")); // e + builder.addStatement( + new Call( + new Reference("id"), + List.of( + new Expression[] { + new Call( + new Reference("type"), + List.of( + new Expression[] { + new Call( + new Reference("print"), + List.of( + new Expression[] { + new Reference("d") + })) + })) + }))); // e = id(type(print(d))) + + // call a function on a literal and assign that to a variable + builder.addStatement( + new Assignment( + new Reference("e"), + new Call( + new Reference("print"), + List.of( + new Expression[] { + new IntLiteral(-50) + })))); // e = print(-50) + + builder.addStatement( + new Call( + new Reference("type"), + List.of(new Expression[] {new Reference("type")}))); // type(type) + + builder.addFunction( + new Function( + "printA", + List.of( + new Statement[] { + new Call( + new Reference("print"), + List.of(new Expression[] {new Reference("a")})) + }), + List.of(new Argument[] {new Argument("a", 0)}), + List.of())); // def printA(a): + // print(a) + + builder.addStatement( + new Call( + new Reference("printA"), + List.of(new Expression[] {new Reference("idA")}))); // printA(idA) + + builder.addClass( + new MPyClass( + "ClassB", + new Reference("__MPyType_Object"), + List.of( + new Function[] { + new Function( + "print", + List.of( + new Statement[] { + new Call( + new Reference("print"), + List.of( + new Expression[] { + new Reference("self") + })) + }), + List.of(new Argument[] {new Argument("self", 0)}), + List.of()), + new Function( + "__init__", + List.of( + new Statement[] { + new SuperCall(List.of()), + new AttributeAssignment( + new AttributeReference( + "b", new Reference("self")), + new IntLiteral(100)) + }), + List.of(new Argument[] {new Argument("self", 0)}), + List.of()) + }), + new HashMap<>())); + + builder.addClass( + new MPyClass( + "C", + new Reference("ClassB"), + List.of( + new Function[] { + new Function( + "__init__", + List.of(new Statement[] {new SuperCall(List.of())}), + List.of(new Argument[] {new Argument("self", 0)}), + List.of()) + }), + new HashMap<>())); + + builder.addVariable(new VariableDeclaration("bObj")); + builder.addStatement( + new Assignment( + new Reference("bObj"), new Call(new Reference("ClassB"), List.of()))); + + builder.addStatement( + new Call(new AttributeReference("print", new Reference("bObj")), List.of())); + + // print(bObj.b) + builder.addStatement( + new Call( + new Reference("print"), + List.of( + new Expression[] { + new AttributeReference("b", new Reference("bObj")) + }))); + + builder.addVariable(new VariableDeclaration("cObj")); + builder.addStatement( + new Assignment(new Reference("cObj"), new Call(new Reference("C"), List.of()))); + + builder.addStatement( + new Call(new AttributeReference("print", new Reference("cObj")), List.of())); + + builder.addStatement( + new Call( + new Reference("print"), + List.of( + new Expression[] { + new AttributeReference("b", new Reference("cObj")) + }))); + + builder.writeProgram(output); + } +} From cae7bdb2432983e0cfcb657fe1270b6d913e97dc Mon Sep 17 00:00:00 2001 From: f0gel Date: Mon, 15 Jul 2024 11:05:28 +0200 Subject: [PATCH 03/14] Prepare Rebase --- c-runtime/Makefile | 50 +- .../ArithmeticOps/TestArithmeticOps.cpp | 126 + .../BuiltInFunctions/TestCastInt.cpp | 103 + .../BuiltInFunctions/TestCastString.cpp | 127 + .../Systemtests/BuiltInFunctions/TestId.cpp | 140 + .../BuiltInFunctions/TestPrint.cpp | 72 + .../Systemtests/BuiltInFunctions/TestType.cpp | 44 + .../Classes/TestClassInheritance.cpp | 73 + .../Systemtests/Classes/TestClassInit.cpp | 129 + .../Classes/TestClassInitThrows.cpp | 138 + .../Systemtests/Classes/TestClassMembers.cpp | 145 + .../ComparisonOps/TestComparisonOps.cpp | 87 + .../ComparisonOps/TestGreaterEqualOp.cpp | 45 + .../ComparisonOps/TestGreaterOp.cpp | 46 + .../ComparisonOps/TestLessEqualOp.cpp | 45 + .../Systemtests/ComparisonOps/TestLessOp.cpp | 46 + .../Conditions/TestElifStatement.cpp | 61 + .../Conditions/TestElseStatement.cpp | 57 + .../Conditions/TestIfStatement.cpp | 59 + .../Conditions/TestWhileStatement.cpp | 50 + .../TestDeclarationAndAssignment.cpp | 144 + .../FunctionCalls/TestFunctionBody.cpp | 175 + .../FunctionCalls/TestFunctionParams.cpp | 209 + .../TestFunctionParamsThrows.cpp | 148 + .../FunctionCalls/TestFunctionRecursion.cpp | 53 + .../FunctionCalls/TestFunctionReturn.cpp | 104 + .../Systemtests/LogicalOps/TestLogicalOps.cpp | 101 + c-runtime/test/Systemtests/makefile | 152 + c-runtime/test/Systemtests/wuppie.cpp | 46 + c-runtime/test/include/catch.hpp | 17976 ++++++++++++++++ .../Classes/TestClassInheritanceHelpers.h | 22 + .../test/Classes/TestClassInitHelpers.h | 24 + .../test/Classes/TestClassMembersHelpers.h | 24 + .../FunctionCalls/TestFunctionBodyHelpers.h | 30 + .../FunctionCalls/TestFunctionParamsHelpers.h | 36 + .../TestFunctionRecursionHelpers.h | 22 + .../FunctionCalls/TestFunctionReturnHelpers.h | 24 + c-runtime/test/include/test/test_helpers.h | 44 + .../Classes/TestClassInheritanceHelpers.c | 45 + .../src/test/Classes/TestClassInitHelpers.c | 74 + .../test/Classes/TestClassMembersHelpers.c | 70 + .../FunctionCalls/TestFunctionBodyHelpers.c | 138 + .../FunctionCalls/TestFunctionParamsHelpers.c | 199 + .../TestFunctionRecursionHelpers.c | 32 + .../FunctionCalls/TestFunctionReturnHelpers.c | 61 + c-runtime/test/src/test/test_helpers.c | 30 + 46 files changed, 21618 insertions(+), 8 deletions(-) create mode 100644 c-runtime/test/Systemtests/ArithmeticOps/TestArithmeticOps.cpp create mode 100644 c-runtime/test/Systemtests/BuiltInFunctions/TestCastInt.cpp create mode 100644 c-runtime/test/Systemtests/BuiltInFunctions/TestCastString.cpp create mode 100644 c-runtime/test/Systemtests/BuiltInFunctions/TestId.cpp create mode 100644 c-runtime/test/Systemtests/BuiltInFunctions/TestPrint.cpp create mode 100644 c-runtime/test/Systemtests/BuiltInFunctions/TestType.cpp create mode 100644 c-runtime/test/Systemtests/Classes/TestClassInheritance.cpp create mode 100644 c-runtime/test/Systemtests/Classes/TestClassInit.cpp create mode 100644 c-runtime/test/Systemtests/Classes/TestClassInitThrows.cpp create mode 100644 c-runtime/test/Systemtests/Classes/TestClassMembers.cpp create mode 100644 c-runtime/test/Systemtests/ComparisonOps/TestComparisonOps.cpp create mode 100644 c-runtime/test/Systemtests/ComparisonOps/TestGreaterEqualOp.cpp create mode 100644 c-runtime/test/Systemtests/ComparisonOps/TestGreaterOp.cpp create mode 100644 c-runtime/test/Systemtests/ComparisonOps/TestLessEqualOp.cpp create mode 100644 c-runtime/test/Systemtests/ComparisonOps/TestLessOp.cpp create mode 100644 c-runtime/test/Systemtests/Conditions/TestElifStatement.cpp create mode 100644 c-runtime/test/Systemtests/Conditions/TestElseStatement.cpp create mode 100644 c-runtime/test/Systemtests/Conditions/TestIfStatement.cpp create mode 100644 c-runtime/test/Systemtests/Conditions/TestWhileStatement.cpp create mode 100644 c-runtime/test/Systemtests/DeclarationAndAssignment/TestDeclarationAndAssignment.cpp create mode 100644 c-runtime/test/Systemtests/FunctionCalls/TestFunctionBody.cpp create mode 100644 c-runtime/test/Systemtests/FunctionCalls/TestFunctionParams.cpp create mode 100644 c-runtime/test/Systemtests/FunctionCalls/TestFunctionParamsThrows.cpp create mode 100644 c-runtime/test/Systemtests/FunctionCalls/TestFunctionRecursion.cpp create mode 100644 c-runtime/test/Systemtests/FunctionCalls/TestFunctionReturn.cpp create mode 100644 c-runtime/test/Systemtests/LogicalOps/TestLogicalOps.cpp create mode 100644 c-runtime/test/Systemtests/makefile create mode 100644 c-runtime/test/Systemtests/wuppie.cpp create mode 100644 c-runtime/test/include/catch.hpp create mode 100644 c-runtime/test/include/test/Classes/TestClassInheritanceHelpers.h create mode 100644 c-runtime/test/include/test/Classes/TestClassInitHelpers.h create mode 100644 c-runtime/test/include/test/Classes/TestClassMembersHelpers.h create mode 100644 c-runtime/test/include/test/FunctionCalls/TestFunctionBodyHelpers.h create mode 100644 c-runtime/test/include/test/FunctionCalls/TestFunctionParamsHelpers.h create mode 100644 c-runtime/test/include/test/FunctionCalls/TestFunctionRecursionHelpers.h create mode 100644 c-runtime/test/include/test/FunctionCalls/TestFunctionReturnHelpers.h create mode 100644 c-runtime/test/include/test/test_helpers.h create mode 100644 c-runtime/test/src/test/Classes/TestClassInheritanceHelpers.c create mode 100644 c-runtime/test/src/test/Classes/TestClassInitHelpers.c create mode 100644 c-runtime/test/src/test/Classes/TestClassMembersHelpers.c create mode 100644 c-runtime/test/src/test/FunctionCalls/TestFunctionBodyHelpers.c create mode 100644 c-runtime/test/src/test/FunctionCalls/TestFunctionParamsHelpers.c create mode 100644 c-runtime/test/src/test/FunctionCalls/TestFunctionRecursionHelpers.c create mode 100644 c-runtime/test/src/test/FunctionCalls/TestFunctionReturnHelpers.c create mode 100644 c-runtime/test/src/test/test_helpers.c diff --git a/c-runtime/Makefile b/c-runtime/Makefile index 8e7e88a..3a40c0d 100644 --- a/c-runtime/Makefile +++ b/c-runtime/Makefile @@ -12,18 +12,26 @@ MKDIR_P := mkdir -p # make SRCDIR and INCLUDEDIR available to doxygen export SRCDIR := $(realpath ./src) export INCLUDEDIR := $(realpath ./include) -DOXYFILE := $(realpath ./Doxyfile) +export TESTDIR := $(realpath ./test) +export INCLUDEDIRTEST := $(realpath ./test/include) +export SRCDIRTEST := $(realpath ./test/src) + +export C_FILES_TEST := $(wildcard ./test/src/test/*.c ./test/src/test/*/*.c* ./src/*.c ./src/*/*.c*) +export C_FILES_TEST := $(filter-out ./src/program.c, $(C_FILES_TEST)) +export C_FILES := $(wildcard ./src/*.c ./src/*/*.c*) +export C_FILES := $(filter-out ./src/program.c, $(C_FILES)) +export DOXYFILE := $(realpath ./Doxyfile) # make DOCDIR available to doxygen export DOCDIR := $(abspath ./doc) -BINDIR := $(abspath ./bin) -OUTDIR := $(abspath ./out) +export BINDIR := $(abspath ./bin) +export OUTDIR := $(abspath ./out) ################# # Default Flags # ################# -CFLAGS ?= -pedantic -Wall -Werror +CFLAGS ?= -Wall -Werror -pedantic CFLAGS += -std=c11 -I$(INCLUDEDIR) CFLAGS += -ffile-prefix-map=$(SRCDIR)=. # make getline() (see man getline(3)) available @@ -37,6 +45,12 @@ else # not for now CFLAGS += -DNDEBUG endif +################# +# Default g++ Flags # +################# + +CXXFLAGS ?= -std=c++14 + ########### # Targets # ########### @@ -49,7 +63,6 @@ SRC := $(wildcard $(SRCDIR)/*.c) $(wildcard $(SRCDIR)/*/*.c) $(wildcard $(SRCDIR OBJECT := $(patsubst $(SRCDIR)/%.c,$(OUTDIR)/%.o,$(SRC)) DEPENDENCY := $(OBJECT:.o=.d) - ######### # Rules # ######### @@ -79,6 +92,7 @@ run: $(BIN) .PHONY: clean clean: $(RM) -r $(BIN) $(OBJECT) $(DEPENDENCY) $(wildcard $(DOCDIR)/*) + $(RM) $(TESTDIR)/main .PHONY: doc doc: @@ -89,11 +103,31 @@ doc: lint: clang-tidy --checks=*,-bugprone-reserved-identifier,-cert-dcl37-c,-cert-dcl51-cpp,-altera-struct-pack-align $(SRC) - .PHONY: test -test: test_clean +test: + d=$$(date +%s)\ + ; make -f $(TESTDIR)/Systemtests/makefile \ + && echo "Build took $$(($$(date +%s)-d)) seconds" .PHONY: test_clean test_clean: - echo "dummy to allow gh workflow to do its job" + make -f $(TESTDIR)/Systemtests/makefile clean + +.PHONY: test_echo +test_echo: + make -f $(TESTDIR)/Systemtests/makefile echo + +.PHONY: test_run +test_run: + make -f $(TESTDIR)/Systemtests/makefile run + +.PHONY: test_target +test_target: + d=$$(date +%s)\ + ; make -f $(TESTDIR)/Systemtests/makefile test_greater_equal_op \ + && echo "Build took $$(($$(date +%s)-d)) seconds" + +.PHONY: run_target +run_target: + ./test/Systemtests/ComparisonOps/TestGreaterEqualOp.out diff --git a/c-runtime/test/Systemtests/ArithmeticOps/TestArithmeticOps.cpp b/c-runtime/test/Systemtests/ArithmeticOps/TestArithmeticOps.cpp new file mode 100644 index 0000000..6a71b3e --- /dev/null +++ b/c-runtime/test/Systemtests/ArithmeticOps/TestArithmeticOps.cpp @@ -0,0 +1,126 @@ +#define CATCH_CONFIG_MAIN + +#include + +#include "catch.hpp" +#include "assert.h" +#include "mpy_aliases.h" +#include "mpy_obj.h" +#include "builtins-setup.h" +#include "function-args.h" +#include "literals/tuple.h" +#include "literals/int.h" +#include "literals/boolean.h" +#include "literals/str.h" +#include "type-hierarchy/object.h" +#include "type-hierarchy/type.h" +#include "test/test_helpers.h" + +int add_op(int i, int j){ + __MPyObj *a; + + __mpy_builtins_setup(); + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + a = __mpy_call(__mpy_obj_get_attr(__mpy_obj_init_int(i), "__add__"), __mpy_tuple_assign(0, __mpy_obj_init_int(j), __mpy_obj_init_tuple(1)), NULL); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + printf("[ADD] i : %d --- j : %d\n",i,j); + print_mpyobj_int(a); + + __mpy_builtins_cleanup(); + + return (*(int*)(a->content)) == (i+j) ? 1 : 0; +} + +int sub_op(int i, int j){ + __MPyObj *a; + + __mpy_builtins_setup(); + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + a = __mpy_call(__mpy_obj_get_attr(__mpy_obj_init_int(i), "__sub__"), __mpy_tuple_assign(0, __mpy_obj_init_int(j), __mpy_obj_init_tuple(1)), NULL); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + printf("[SUB] i : %d --- j : %d\n",i,j); + print_mpyobj_int(a); + + __mpy_builtins_cleanup(); + + return (*(int*)(a->content)) == (i-j) ? 1 : 0; +} + +int mul_op(int i, int j){ + __MPyObj *a; + + __mpy_builtins_setup(); + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + a = __mpy_call(__mpy_obj_get_attr(__mpy_obj_init_int(i), "__mul__"), __mpy_tuple_assign(0, __mpy_obj_init_int(j), __mpy_obj_init_tuple(1)), NULL); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + printf("[MUL] i : %d --- j : %d\n",i,j); + print_mpyobj_int(a); + + __mpy_builtins_cleanup(); + + return (*(int*)(a->content)) == (i*j) ? 1 : 0; +} + +int div_op(int i, int j){ + __MPyObj *a; + + __mpy_builtins_setup(); + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + a = __mpy_call(__mpy_obj_get_attr(__mpy_obj_init_int(i), "__div__"), __mpy_tuple_assign(0, __mpy_obj_init_int(j), __mpy_obj_init_tuple(1)), NULL); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + printf("[DIV] i : %d --- j : %d\n",i,j); + print_mpyobj_int(a); + + __mpy_builtins_cleanup(); + + return (*(int*)(a->content)) == (i/j) ? 1 : 0; +} + + +TEST_CASE("GENERATE ADD OP"){ + auto i = GENERATE(1, 3, 5); + auto j = GENERATE(2, 4, 6); + CHECK(add_op(i, j) == 1); +} + +TEST_CASE("GENERATE SUB OP"){ + auto i = GENERATE(1, 3, 5); + auto j = GENERATE(2, 4, 6); + CHECK(sub_op(i, j) == 1); +} + +TEST_CASE("GENERATE MUL OP"){ + auto i = GENERATE(1, 3, 5); + auto j = GENERATE(2, 4, 6); + CHECK(mul_op(i, j) == 1); +} + +TEST_CASE("GENERATE DIV OP"){ + auto i = GENERATE(3, 8, 12); + auto j = GENERATE(2, 4, 6); + CHECK(div_op(i, j) == 1); +} diff --git a/c-runtime/test/Systemtests/BuiltInFunctions/TestCastInt.cpp b/c-runtime/test/Systemtests/BuiltInFunctions/TestCastInt.cpp new file mode 100644 index 0000000..bd39437 --- /dev/null +++ b/c-runtime/test/Systemtests/BuiltInFunctions/TestCastInt.cpp @@ -0,0 +1,103 @@ +#define CATCH_CONFIG_MAIN + +#include + +#include "catch.hpp" +#include "assert.h" +#include "mpy_aliases.h" +#include "mpy_obj.h" +#include "builtins-setup.h" +#include "function-args.h" +#include "literals/tuple.h" +#include "literals/int.h" +#include "literals/boolean.h" +#include "literals/str.h" +#include "type-hierarchy/object.h" +#include "type-hierarchy/type.h" +#include "test/test_helpers.h" + +void exit(int status) { + throw std::runtime_error("Error"); +} + +int cast_bool_to_int(bool input){ + __MPyObj *a; + + __mpy_builtins_setup(); + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + a = __mpy_obj_init_boolean(input); + __mpy_obj_ref_inc(a); + + a = __mpy_call(__mpy_obj_get_attr(a, "__int__"), __mpy_obj_init_tuple(0), NULL); + + __mpy_obj_ref_dec(a); + + print_mpyobj_int(a); + + __mpy_builtins_cleanup(); + + return (*(int*)(a->content)); +} + +int cast_string_to_int(const char* input){ + __MPyObj *a; + + __mpy_builtins_setup(); + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + a = __mpy_obj_init_str_static(input); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + a = __mpy_call(__mpy_obj_get_attr(a, "__int__"), __mpy_obj_init_tuple(0), NULL); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + print_mpyobj_int(a); + + __mpy_builtins_cleanup(); + + return (*(int*)(a->content)); +} + +TEST_CASE("TEST CAST BOOL TO INT") +{ + auto [input, expected_output] = GENERATE(table({ + { true, 1 }, + { false, 0 }, + {10, 1}, + })); + + CAPTURE(input); + CHECK(cast_bool_to_int(input) == expected_output); +} + +TEST_CASE("TEST CAST STRING TO INT") +{ + auto [input, expected_output] = GENERATE(table({ + { "1", 1 }, + { "0", 0 }, + { "10", 10}, + })); + + CAPTURE(input); + CHECK(cast_string_to_int(input) == expected_output); +} + +TEST_CASE("TEST CAST STRING TO INT ERROR") { + REQUIRE_THROWS_AS(cast_string_to_int("false"), std::runtime_error); +} + +/* +And + +int cast_int_to_int(int i){ +} + +*/ diff --git a/c-runtime/test/Systemtests/BuiltInFunctions/TestCastString.cpp b/c-runtime/test/Systemtests/BuiltInFunctions/TestCastString.cpp new file mode 100644 index 0000000..51d5988 --- /dev/null +++ b/c-runtime/test/Systemtests/BuiltInFunctions/TestCastString.cpp @@ -0,0 +1,127 @@ +#define CATCH_CONFIG_MAIN + +#include + +#include "catch.hpp" +#include "assert.h" +#include "mpy_aliases.h" +#include "mpy_obj.h" +#include "builtins-setup.h" +#include "function-args.h" +#include "literals/tuple.h" +#include "literals/int.h" +#include "literals/boolean.h" +#include "literals/str.h" +#include "type-hierarchy/object.h" +#include "type-hierarchy/type.h" +#include "test/test_helpers.h" + +int cast_bool_to_string(bool input, const char* expected){ + __MPyObj *a; + + __mpy_builtins_setup(); + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + a = __mpy_obj_init_boolean(input); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + a = __mpy_call(__mpy_obj_get_attr(a, "__str__"), __mpy_obj_init_tuple(0), NULL); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + print_mpyobj_str(a); + + __mpy_builtins_cleanup(); + + return strcmp(((__MPyStrContent*)a->content)->string, expected); +} + +int cast_int_to_string(int input, const char* expected){ + __MPyObj *a; + + __mpy_builtins_setup(); + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + a = __mpy_obj_init_int(input); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + a = __mpy_call(__mpy_obj_get_attr(a, "__str__"), __mpy_obj_init_tuple(0), NULL); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + print_mpyobj_str(a); + + __mpy_builtins_cleanup(); + + return strcmp(((__MPyStrContent*)a->content)->string, expected); +} + +int cast_string_to_string(const char* input, const char* expected){ + __MPyObj *a; + + __mpy_builtins_setup(); + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + a = __mpy_obj_init_str_static(input); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + a = __mpy_call(__mpy_obj_get_attr(a, "__str__"), __mpy_obj_init_tuple(0), NULL); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + print_mpyobj_str(a); + + __mpy_builtins_cleanup(); + return strcmp(((__MPyStrContent*)a->content)->string, expected); +} + +TEST_CASE("TEST CAST BOOL TO STRING") +{ + auto [input, expected_output] = GENERATE(table({ + { true, "True" }, + { false, "False" }, + { 10, "True" }, + { 0, "False" }, + })); + + CAPTURE(input); + CHECK(cast_bool_to_string(input, expected_output) == 0); +} + +TEST_CASE("TEST CAST INT TO STRING") +{ + auto [input, expected_output] = GENERATE(table({ + { 123, "123" }, + { 0, "0" }, + { -10, "-10" }, + { 1236789, "1236789" }, + })); + + CAPTURE(input); + CHECK(cast_int_to_string(input, expected_output) == 0); +} + +TEST_CASE("TEST CAST STRING TO STRING") +{ + auto [input, expected_output] = GENERATE(table({ + { "123", "123" }, + { "0", "0" }, + { "-10", "-10" }, + { "1236789", "1236789" }, + })); + + CAPTURE(input); + CHECK(cast_string_to_string(input, expected_output) == 0); +} diff --git a/c-runtime/test/Systemtests/BuiltInFunctions/TestId.cpp b/c-runtime/test/Systemtests/BuiltInFunctions/TestId.cpp new file mode 100644 index 0000000..d96879f --- /dev/null +++ b/c-runtime/test/Systemtests/BuiltInFunctions/TestId.cpp @@ -0,0 +1,140 @@ +/* + The Tests defined here only work if the assignment of the id to an mpyobj is not random. +*/ +#define CATCH_CONFIG_MAIN + +#include + +#include "catch.hpp" +#include "assert.h" +#include "mpy_aliases.h" +#include "mpy_obj.h" +#include "builtins-setup.h" +#include "function-args.h" +#include "literals/tuple.h" +#include "literals/int.h" +#include "literals/boolean.h" +#include "literals/str.h" +#include "type-hierarchy/object.h" +#include "type-hierarchy/type.h" +#include "test/test_helpers.h" + +int test_id_string(){ + __MPyObj *a; + __MPyObj *b; + + __mpy_builtins_setup(); + + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + b = __mpy_obj_init_object(); + __mpy_obj_ref_inc(b); + + __mpy_obj_ref_dec(a); + a = __mpy_obj_init_str_static("123"); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(b); + b = __mpy_call(id, __mpy_tuple_assign(0, a, __mpy_obj_init_tuple(1)), NULL); + __mpy_obj_ref_inc(b); + + __mpy_obj_ref_dec(a); + __mpy_obj_ref_dec(b); + + print_mpyobj_int(b); + + __mpy_builtins_cleanup(); + + return (*(int*)(b->content) == 63 ? 1 : 0); +} + +int test_id_int(){ + __MPyObj *a; + __MPyObj *b; + + __mpy_builtins_setup(); + + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + b = __mpy_obj_init_object(); + __mpy_obj_ref_inc(b); + + __mpy_obj_ref_dec(a); + a = __mpy_obj_init_int(123); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(b); + b = __mpy_call(id, __mpy_tuple_assign(0, a, __mpy_obj_init_tuple(1)), NULL); + __mpy_obj_ref_inc(b); + + __mpy_obj_ref_dec(a); + __mpy_obj_ref_dec(b); + + print_mpyobj_int(b); + + __mpy_builtins_cleanup(); + + return (*(int*)(b->content) == 158 ? 1 : 0); +} + +int test_id_bool(){ + __MPyObj *a; + __MPyObj *b; + + __mpy_builtins_setup(); + + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + b = __mpy_obj_init_object(); + __mpy_obj_ref_inc(b); + + __mpy_obj_ref_dec(a); + a = __mpy_obj_init_boolean(true); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(b); + b = __mpy_call(id, __mpy_tuple_assign(0, a, __mpy_obj_init_tuple(1)), NULL); + __mpy_obj_ref_inc(b); + + __mpy_obj_ref_dec(a); + __mpy_obj_ref_dec(b); + + print_mpyobj_int(b); + + __mpy_builtins_cleanup(); + + return (*(int*)(b->content) == 260 ? 1 : 0); +} + +int test_id_call(){ + __MPyObj *a; + + __mpy_builtins_setup(); + + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + a = __mpy_call(id, __mpy_tuple_assign(0, __mpy_call(__mpy_obj_get_attr(__mpy_obj_init_int(1), "__add__"), __mpy_tuple_assign(0, __mpy_obj_init_int(1), __mpy_obj_init_tuple(1)), NULL), __mpy_obj_init_tuple(1)), NULL); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + print_mpyobj_int(a); + + __mpy_builtins_cleanup(); + + return (*(int*)(a->content) == 390 ? 1 : 0); +} + +TEST_CASE("TEST ID OF mpy_obj") +{ + CHECK(test_id_string() == 1); + CHECK(test_id_int() == 1); + CHECK(test_id_bool() == 1); + CHECK(test_id_call() == 1); + +} diff --git a/c-runtime/test/Systemtests/BuiltInFunctions/TestPrint.cpp b/c-runtime/test/Systemtests/BuiltInFunctions/TestPrint.cpp new file mode 100644 index 0000000..899da22 --- /dev/null +++ b/c-runtime/test/Systemtests/BuiltInFunctions/TestPrint.cpp @@ -0,0 +1,72 @@ +/* + Since print returns void only the return value of the program can be checked. + A successful test indicates that calling print with an literal/function call worked. + Calling print(type(mpyobj)) should result in a crash for instance. +*/ +#define CATCH_CONFIG_MAIN + +#include + +#include "catch.hpp" +#include "assert.h" +#include "mpy_aliases.h" +#include "mpy_obj.h" +#include "builtins-setup.h" +#include "function-args.h" +#include "literals/tuple.h" +#include "literals/int.h" +#include "literals/boolean.h" +#include "literals/str.h" +#include "type-hierarchy/object.h" +#include "type-hierarchy/type.h" +#include "test/test_helpers.h" + +int print_int(){ + + __mpy_obj_ref_dec(__mpy_call(print, __mpy_tuple_assign(0, __mpy_obj_init_int(133), __mpy_obj_init_tuple(1)), NULL)); + + return 0; +} + +int print_string(){ + + __mpy_obj_ref_dec(__mpy_call(print, __mpy_tuple_assign(0, __mpy_obj_init_str_static("Test"), __mpy_obj_init_tuple(1)), NULL)); + + return 0; +} + +int print_bool(){ + + __mpy_obj_ref_dec(__mpy_call(print, __mpy_tuple_assign(0, __mpy_obj_init_boolean(true), __mpy_obj_init_tuple(1)), NULL)); + + return 0; +} + +int print_expression(){ + + __mpy_obj_ref_dec(__mpy_call(print, __mpy_tuple_assign(0, __mpy_call(__mpy_obj_get_attr(__mpy_obj_init_int(1), "__add__"), __mpy_tuple_assign(0, __mpy_obj_init_int(1), __mpy_obj_init_tuple(1)), NULL), __mpy_obj_init_tuple(1)), NULL)); + + return 0; +} + +// Throws error see TODO(./src/function-args.c:36) +int print_type(){ + + //__mpy_obj_ref_dec(__mpy_call(print, __mpy_tuple_assign(0, __mpy_call(type, __mpy_tuple_assign(0, __mpy_obj_init_int(123), __mpy_obj_init_tuple(1)), NULL), __mpy_obj_init_tuple(1)), NULL)); + __mpy_obj_ref_dec(__mpy_call(print, __mpy_tuple_assign(0, __mpy_call(type, __mpy_tuple_assign(0, print, __mpy_obj_init_tuple(1)), NULL), __mpy_obj_init_tuple(1)), NULL)); + return 0; +} + + +TEST_CASE("TEST PRINT") +{ + __mpy_builtins_setup(); + + CHECK(print_int() == 0); + CHECK(print_string() == 0); + CHECK(print_bool() == 0); + CHECK(print_expression() == 0); + //CHECK(print_type() == 0); + + __mpy_builtins_cleanup(); +} diff --git a/c-runtime/test/Systemtests/BuiltInFunctions/TestType.cpp b/c-runtime/test/Systemtests/BuiltInFunctions/TestType.cpp new file mode 100644 index 0000000..e75bb4c --- /dev/null +++ b/c-runtime/test/Systemtests/BuiltInFunctions/TestType.cpp @@ -0,0 +1,44 @@ +#define CATCH_CONFIG_MAIN + +#include + +#include "catch.hpp" +#include "assert.h" +#include "mpy_aliases.h" +#include "mpy_obj.h" +#include "builtins-setup.h" +#include "function-args.h" +#include "literals/tuple.h" +#include "literals/int.h" +#include "literals/boolean.h" +#include "literals/str.h" +#include "type-hierarchy/object.h" +#include "type-hierarchy/type.h" +#include "test/test_helpers.h" + +// Throws error see TODO(./src/function-args.c:36) + +int test_type(){ + __MPyObj *a; + + __mpy_builtins_setup(); + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + a = __mpy_call(type, __mpy_tuple_assign(0, a, __mpy_obj_init_tuple(1)), NULL); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + print_mpyobj_int(a); + + __mpy_builtins_cleanup(); + + return 0; +} + +TEST_CASE("TEST PRINT") +{ + //CHECK(test_type() == 0); +} diff --git a/c-runtime/test/Systemtests/Classes/TestClassInheritance.cpp b/c-runtime/test/Systemtests/Classes/TestClassInheritance.cpp new file mode 100644 index 0000000..2fdd199 --- /dev/null +++ b/c-runtime/test/Systemtests/Classes/TestClassInheritance.cpp @@ -0,0 +1,73 @@ +#define CATCH_CONFIG_RUNNER + +#include + +#include "catch.hpp" +#include "test/test_helpers.h" +#include "test/Classes/TestClassInheritanceHelpers.h" + +__MPyObj *A; + +__MPyObj *B; + +int main( int argc, char* argv[] ) { + // global setup... + __mpy_builtins_setup(); + + int result = 0; + + try{ + result = Catch::Session().run( argc, argv ); + } + catch (const std::runtime_error& error){ + printf(""); + } + + __mpy_builtins_cleanup(); + // global clean-up... Why is this working ? .... + + return result; +} + +int inheritance(){ + __MPyObj *child; + + child = __mpy_obj_init_object(); + __mpy_obj_ref_inc(child); + + + A = __mpy_obj_init_type("A", __MPyType_Object); + __mpy_obj_ref_inc(A); + { + __MPyObj *__init__; + __init__ = __mpy_obj_init_func(&func_A___init__); + __mpy_obj_ref_inc(__init__); + __mpy_obj_set_attr(A, "__init__", __init__); + __mpy_obj_ref_dec(__init__); + } + B = __mpy_obj_init_type("B", A); + __mpy_obj_ref_inc(B); + { + __MPyObj *__init__; + __init__ = __mpy_obj_init_func(&func_B___init__); + __mpy_obj_ref_inc(__init__); + __mpy_obj_set_attr(B, "__init__", __init__); + __mpy_obj_ref_dec(__init__); + } + + __mpy_obj_ref_dec(child); + child = __mpy_call(B, __mpy_obj_init_tuple(0), NULL); + __mpy_obj_ref_inc(child); + + __mpy_obj_ref_dec(child); + + + __mpy_obj_ref_dec(A); + __mpy_obj_ref_dec(B); + + return 0; +} + +TEST_CASE("CLASS INHERITANCE"){ + CHECK_NOTHROW(inheritance()); +} diff --git a/c-runtime/test/Systemtests/Classes/TestClassInit.cpp b/c-runtime/test/Systemtests/Classes/TestClassInit.cpp new file mode 100644 index 0000000..1973482 --- /dev/null +++ b/c-runtime/test/Systemtests/Classes/TestClassInit.cpp @@ -0,0 +1,129 @@ +#define CATCH_CONFIG_RUNNER + +#include + +#include "catch.hpp" +#include "test/test_helpers.h" +#include "test/Classes/TestClassInitHelpers.h" + +__MPyObj *init_no_params; + +__MPyObj *init_one_param; + +__MPyObj *init_multiple_params; + +int main( int argc, char* argv[] ) { + // global setup... + __mpy_builtins_setup(); + + int result = 0; + + try{ + result = Catch::Session().run( argc, argv ); + } + catch (const std::runtime_error& error){ + printf(""); + } + + __mpy_builtins_cleanup(); + // global clean-up... Why is this working ? .... + + return result; +} + +int init_class_no_params(){ + __MPyObj *x; + + x = __mpy_obj_init_object(); + __mpy_obj_ref_inc(x); + + + init_no_params = __mpy_obj_init_type("init_no_params", __MPyType_Object); + __mpy_obj_ref_inc(init_no_params); + { + __MPyObj *__init__; + __init__ = __mpy_obj_init_func(&func_init_no_params___init__); + __mpy_obj_ref_inc(__init__); + __mpy_obj_set_attr(init_no_params, "__init__", __init__); + __mpy_obj_ref_dec(__init__); + } + + __mpy_obj_ref_dec(x); + x = __mpy_call(init_no_params, __mpy_obj_init_tuple(0), NULL); + __mpy_obj_ref_inc(x); + + __mpy_obj_ref_dec(x); + + print_mpyobj(x); + + __mpy_obj_ref_dec(init_no_params); + + return 0; +} + +int init_class_one_param(){ + __MPyObj *x; + + x = __mpy_obj_init_object(); + __mpy_obj_ref_inc(x); + + + init_one_param = __mpy_obj_init_type("init_one_param", __MPyType_Object); + __mpy_obj_ref_inc(init_one_param); + { + __MPyObj *__init__; + __init__ = __mpy_obj_init_func(&func_init_one_param___init__); + __mpy_obj_ref_inc(__init__); + __mpy_obj_set_attr(init_one_param, "__init__", __init__); + __mpy_obj_ref_dec(__init__); + } + + __mpy_obj_ref_dec(x); + x = __mpy_call(init_one_param, __mpy_tuple_assign(0, __mpy_obj_init_str_static("test"), __mpy_obj_init_tuple(1)), NULL); + __mpy_obj_ref_inc(x); + + __mpy_obj_ref_dec(x); + + + __mpy_obj_ref_dec(init_one_param); + + print_mpyobj(x); + + return 0; +} + +int init_class_multiple_params(){ + __MPyObj *x; + + x = __mpy_obj_init_object(); + __mpy_obj_ref_inc(x); + + + init_multiple_params = __mpy_obj_init_type("init_multiple_params", __MPyType_Object); + __mpy_obj_ref_inc(init_multiple_params); + { + __MPyObj *__init__; + __init__ = __mpy_obj_init_func(&func_init_multiple_params___init__); + __mpy_obj_ref_inc(__init__); + __mpy_obj_set_attr(init_multiple_params, "__init__", __init__); + __mpy_obj_ref_dec(__init__); + } + + __mpy_obj_ref_dec(x); + x = __mpy_call(init_multiple_params, __mpy_tuple_assign(0, __mpy_obj_init_str_static("test"), __mpy_tuple_assign(1, __mpy_obj_init_int(123), __mpy_obj_init_tuple(2))), NULL); + __mpy_obj_ref_inc(x); + + __mpy_obj_ref_dec(x); + + __mpy_obj_ref_dec(init_multiple_params); + + print_mpyobj(x); + + return 0; +} + +TEST_CASE("CLASS INIT"){ + CHECK_NOTHROW(init_class_no_params()); + CHECK_NOTHROW(init_class_one_param()); + CHECK_NOTHROW(init_class_multiple_params()); +} diff --git a/c-runtime/test/Systemtests/Classes/TestClassInitThrows.cpp b/c-runtime/test/Systemtests/Classes/TestClassInitThrows.cpp new file mode 100644 index 0000000..3948efa --- /dev/null +++ b/c-runtime/test/Systemtests/Classes/TestClassInitThrows.cpp @@ -0,0 +1,138 @@ +#define CATCH_CONFIG_RUNNER + +#include + +#include "catch.hpp" +#include "test/test_helpers.h" +#include "test/Classes/TestClassInitHelpers.h" + +__MPyObj *init_no_params; + +__MPyObj *init_one_param; + +__MPyObj *init_multiple_params; + +void exit(int status); + +int main( int argc, char* argv[] ) { + // global setup... + __mpy_builtins_setup(); + + int result = 0; + + try{ + result = Catch::Session().run( argc, argv ); + } + catch (const std::runtime_error& error){ + printf(""); + } + + __mpy_builtins_cleanup(); + // global clean-up... Why is this working ? .... + + return result; +} + +int init_class_no_params_but_one_provided(){ + __MPyObj *x; + + x = __mpy_obj_init_object(); + __mpy_obj_ref_inc(x); + + + init_no_params = __mpy_obj_init_type("init_no_params", __MPyType_Object); + __mpy_obj_ref_inc(init_no_params); + { + __MPyObj *__init__; + __init__ = __mpy_obj_init_func(&func_init_no_params___init__); + __mpy_obj_ref_inc(__init__); + __mpy_obj_set_attr(init_no_params, "__init__", __init__); + __mpy_obj_ref_dec(__init__); + } + + __mpy_obj_ref_dec(x); + + x = __mpy_call(init_no_params, __mpy_tuple_assign(0, __mpy_obj_init_str_static("test"), __mpy_obj_init_tuple(1)), NULL); + + __mpy_obj_ref_inc(x); + + __mpy_obj_ref_dec(x); + + print_mpyobj(x); + + __mpy_obj_ref_dec(init_no_params); + + return 0; +} + +int init_class_one_param_but_none_provided(){ + __MPyObj *x; + + x = __mpy_obj_init_object(); + __mpy_obj_ref_inc(x); + + + init_one_param = __mpy_obj_init_type("init_one_param", __MPyType_Object); + __mpy_obj_ref_inc(init_one_param); + { + __MPyObj *__init__; + __init__ = __mpy_obj_init_func(&func_init_one_param___init__); + __mpy_obj_ref_inc(__init__); + __mpy_obj_set_attr(init_one_param, "__init__", __init__); + __mpy_obj_ref_dec(__init__); + } + + __mpy_obj_ref_dec(x); + x = __mpy_call(init_one_param, __mpy_obj_init_tuple(0), NULL); + __mpy_obj_ref_inc(x); + + __mpy_obj_ref_dec(x); + + + __mpy_obj_ref_dec(init_one_param); + + print_mpyobj(x); + + return 0; +} + +int init_class_multiple_params_but_less_provided(){ + __MPyObj *x; + + x = __mpy_obj_init_object(); + __mpy_obj_ref_inc(x); + + + init_multiple_params = __mpy_obj_init_type("init_multiple_params", __MPyType_Object); + __mpy_obj_ref_inc(init_multiple_params); + { + __MPyObj *__init__; + __init__ = __mpy_obj_init_func(&func_init_multiple_params___init__); + __mpy_obj_ref_inc(__init__); + __mpy_obj_set_attr(init_multiple_params, "__init__", __init__); + __mpy_obj_ref_dec(__init__); + } + + __mpy_obj_ref_dec(x); + x = __mpy_call(init_multiple_params, __mpy_tuple_assign(0, __mpy_obj_init_str_static("test"), __mpy_obj_init_tuple(1)), NULL); + __mpy_obj_ref_inc(x); + + __mpy_obj_ref_dec(x); + + __mpy_obj_ref_dec(init_multiple_params); + + print_mpyobj(x); + + return 0; +} + +TEST_CASE("CLASS INIT THROWS"){ + CHECK_THROWS_AS(init_class_no_params_but_one_provided(), std::runtime_error); // Actually this is the same as testing if function throw... + CHECK_THROWS_AS(init_class_one_param_but_none_provided(), std::runtime_error); // "" + CHECK_THROWS_AS(init_class_multiple_params_but_less_provided(), std::runtime_error); // "" +} + +void exit(int status) { + throw std::runtime_error(""); +} + diff --git a/c-runtime/test/Systemtests/Classes/TestClassMembers.cpp b/c-runtime/test/Systemtests/Classes/TestClassMembers.cpp new file mode 100644 index 0000000..dd10df0 --- /dev/null +++ b/c-runtime/test/Systemtests/Classes/TestClassMembers.cpp @@ -0,0 +1,145 @@ +#define CATCH_CONFIG_RUNNER + +#include + +#include "catch.hpp" +#include "test/test_helpers.h" +#include "test/Classes/TestClassMembersHelpers.h" + +__MPyObj *getter_setter; + +int main( int argc, char* argv[] ) { + // global setup... + __mpy_builtins_setup(); + + int result = 0; + + try{ + result = Catch::Session().run( argc, argv ); + } + catch (const std::runtime_error& error){ + printf(""); + } + + __mpy_builtins_cleanup(); + // global clean-up... Why is this working ? .... + + return result; +} + +int getX_from_class(){ + __MPyObj *myClass; + __MPyObj *returnValueGetter; + + myClass = __mpy_obj_init_object(); + __mpy_obj_ref_inc(myClass); + + returnValueGetter = __mpy_obj_init_object(); + __mpy_obj_ref_inc(returnValueGetter); + + getter_setter = __mpy_obj_init_type("getter_setter", __MPyType_Object); + __mpy_obj_ref_inc(getter_setter); + { + __MPyObj *__init__; + __init__ = __mpy_obj_init_func(&func_getter_setter___init__); + __mpy_obj_ref_inc(__init__); + __mpy_obj_set_attr(getter_setter, "__init__", __init__); + __mpy_obj_ref_dec(__init__); + } + { + __MPyObj *getX; + getX = __mpy_obj_init_func(&func_getter_setter_getX); + __mpy_obj_ref_inc(getX); + __mpy_obj_set_attr(getter_setter, "getX", getX); + __mpy_obj_ref_dec(getX); + } + { + __MPyObj *setX; + setX = __mpy_obj_init_func(&func_getter_setter_setX); + __mpy_obj_ref_inc(setX); + __mpy_obj_set_attr(getter_setter, "setX", setX); + __mpy_obj_ref_dec(setX); + } + + __mpy_obj_ref_dec(myClass); + myClass = __mpy_call(getter_setter, __mpy_tuple_assign(0, __mpy_obj_init_int(1), __mpy_obj_init_tuple(1)), NULL); + __mpy_obj_ref_inc(myClass); + + __mpy_obj_ref_dec(returnValueGetter); + returnValueGetter = __mpy_call(__mpy_obj_get_attr(myClass, "getX"), __mpy_obj_init_tuple(0), NULL); + __mpy_obj_ref_inc(returnValueGetter); + + __mpy_obj_ref_dec(myClass); + __mpy_obj_ref_dec(returnValueGetter); + + __mpy_obj_ref_dec(getter_setter); + + print_mpyobj_int(returnValueGetter); + + return (*(int*)(returnValueGetter->content)); +} + +int setX_from_class(){ + __MPyObj *myClass; + __MPyObj *returnValueGetter; + + myClass = __mpy_obj_init_object(); + __mpy_obj_ref_inc(myClass); + + returnValueGetter = __mpy_obj_init_object(); + __mpy_obj_ref_inc(returnValueGetter); + + getter_setter = __mpy_obj_init_type("getter_setter", __MPyType_Object); + __mpy_obj_ref_inc(getter_setter); + { + __MPyObj *__init__; + __init__ = __mpy_obj_init_func(&func_getter_setter___init__); + __mpy_obj_ref_inc(__init__); + __mpy_obj_set_attr(getter_setter, "__init__", __init__); + __mpy_obj_ref_dec(__init__); + } + { + __MPyObj *getX; + getX = __mpy_obj_init_func(&func_getter_setter_getX); + __mpy_obj_ref_inc(getX); + __mpy_obj_set_attr(getter_setter, "getX", getX); + __mpy_obj_ref_dec(getX); + } + { + __MPyObj *setX; + setX = __mpy_obj_init_func(&func_getter_setter_setX); + __mpy_obj_ref_inc(setX); + __mpy_obj_set_attr(getter_setter, "setX", setX); + __mpy_obj_ref_dec(setX); + } + + __mpy_obj_ref_dec(myClass); + myClass = __mpy_call(getter_setter, __mpy_tuple_assign(0, __mpy_obj_init_int(133), __mpy_obj_init_tuple(1)), NULL); + __mpy_obj_ref_inc(myClass); + + __mpy_obj_ref_dec(returnValueGetter); + returnValueGetter = __mpy_call(__mpy_obj_get_attr(myClass, "getX"), __mpy_obj_init_tuple(0), NULL); + __mpy_obj_ref_inc(returnValueGetter); + + print_mpyobj_int(returnValueGetter); + + __mpy_obj_ref_dec(__mpy_call(__mpy_obj_get_attr(myClass, "setX"), __mpy_tuple_assign(0, __mpy_obj_init_int(1), __mpy_obj_init_tuple(1)), NULL)); + + __mpy_obj_ref_dec(returnValueGetter); + returnValueGetter = __mpy_call(__mpy_obj_get_attr(myClass, "getX"), __mpy_obj_init_tuple(0), NULL); + __mpy_obj_ref_inc(returnValueGetter); + + __mpy_obj_ref_dec(myClass); + __mpy_obj_ref_dec(returnValueGetter); + + __mpy_obj_ref_dec(getter_setter); + + print_mpyobj_int(returnValueGetter); + + return (*(int*)(returnValueGetter->content)); +} + +TEST_CASE("CLASS MEMBERS"){ + CHECK(getX_from_class() == 1); + CHECK(setX_from_class() == 1); +} diff --git a/c-runtime/test/Systemtests/ComparisonOps/TestComparisonOps.cpp b/c-runtime/test/Systemtests/ComparisonOps/TestComparisonOps.cpp new file mode 100644 index 0000000..c4d767f --- /dev/null +++ b/c-runtime/test/Systemtests/ComparisonOps/TestComparisonOps.cpp @@ -0,0 +1,87 @@ +#define CATCH_CONFIG_RUNNER + +#include + +#include "catch.hpp" +#include "assert.h" +#include "mpy_aliases.h" +#include "mpy_obj.h" +#include "builtins-setup.h" +#include "function-args.h" +#include "literals/tuple.h" +#include "literals/int.h" +#include "literals/boolean.h" +#include "literals/str.h" +#include "type-hierarchy/object.h" +#include "type-hierarchy/type.h" +#include "test/test_helpers.h" + +int main( int argc, char* argv[] ) { + // global setup... + __mpy_builtins_setup(); + + int result = 0; + + try{ + result = Catch::Session().run( argc, argv ); + } + catch (const std::runtime_error& error){ + printf("Hello World"); + } + + __mpy_builtins_cleanup(); + // global clean-up... Why is this working ? .... + + return result; +} + +int eq_op(int i, int j){ + __MPyObj *a; + + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + a = __mpy_call(__mpy_obj_get_attr(__mpy_obj_init_int(i), "__eq__"), __mpy_tuple_assign(0, __mpy_obj_init_int(j), __mpy_obj_init_tuple(1)), NULL); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + printf("[EQ] i : %d --- j : %d\n",i,j); + + print_mpyobj_int(a); + + + return (*(int*)(a->content)) == (i == j) ? 1 : 0; +} + +int ne_op(int i, int j){ + __MPyObj *a; + + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + a = __mpy_call(__mpy_obj_get_attr(__mpy_obj_init_int(i), "__ne__"), __mpy_tuple_assign(0, __mpy_obj_init_int(j), __mpy_obj_init_tuple(1)), NULL); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + printf("[NE] i : %d --- j : %d\n",i,j); + + print_mpyobj_int(a); + + return (*(int*)(a->content)) == (i != j) ? 1 : 0; +} + +TEST_CASE("GENERATE EQ OP"){ + auto i = GENERATE(1, 3, 5); + auto j = GENERATE(2, 4, 5); + CHECK(eq_op(i, j) == 1); +} + +TEST_CASE("GENERATE NE OP"){ + auto i = GENERATE(1, 3, 5); + auto j = GENERATE(2, 4, 5); + CHECK(ne_op(i, j) == 1); +} diff --git a/c-runtime/test/Systemtests/ComparisonOps/TestGreaterEqualOp.cpp b/c-runtime/test/Systemtests/ComparisonOps/TestGreaterEqualOp.cpp new file mode 100644 index 0000000..5ff0e93 --- /dev/null +++ b/c-runtime/test/Systemtests/ComparisonOps/TestGreaterEqualOp.cpp @@ -0,0 +1,45 @@ +#define CATCH_CONFIG_MAIN + +#include + +#include "catch.hpp" +#include "assert.h" +#include "mpy_aliases.h" +#include "mpy_obj.h" +#include "builtins-setup.h" +#include "function-args.h" +#include "literals/tuple.h" +#include "literals/int.h" +#include "literals/boolean.h" +#include "literals/str.h" +#include "type-hierarchy/object.h" +#include "type-hierarchy/type.h" +#include "test/test_helpers.h" + +int ge_op(int i, int j){ + __MPyObj *a; + + __mpy_builtins_setup(); + + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + a = __mpy_call(__mpy_obj_get_attr(__mpy_obj_init_int(i), "__ge__"), __mpy_tuple_assign(0, __mpy_obj_init_int(j), __mpy_obj_init_tuple(1)), NULL); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + printf("[GE] i : %d --- j : %d\n",i,j); + print_mpyobj_int(a); + + __mpy_builtins_cleanup(); + + return (*(int*)(a->content)) == (i >= j) ? 1 : 0; +} + +TEST_CASE("GENERATE GE OP"){ + auto i = GENERATE(1, 3, 5); + auto j = GENERATE(2, 4, 5); + CHECK(ge_op(i, j) == 1); +} \ No newline at end of file diff --git a/c-runtime/test/Systemtests/ComparisonOps/TestGreaterOp.cpp b/c-runtime/test/Systemtests/ComparisonOps/TestGreaterOp.cpp new file mode 100644 index 0000000..fbaf119 --- /dev/null +++ b/c-runtime/test/Systemtests/ComparisonOps/TestGreaterOp.cpp @@ -0,0 +1,46 @@ +#define CATCH_CONFIG_MAIN + +#include + +#include "catch.hpp" +#include "assert.h" +#include "mpy_aliases.h" +#include "mpy_obj.h" +#include "builtins-setup.h" +#include "function-args.h" +#include "literals/tuple.h" +#include "literals/int.h" +#include "literals/boolean.h" +#include "literals/str.h" +#include "type-hierarchy/object.h" +#include "type-hierarchy/type.h" +#include "test/test_helpers.h" + + +int gt_op(int i, int j){ + __MPyObj *a; + + __mpy_builtins_setup(); + + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + a = __mpy_call(__mpy_obj_get_attr(__mpy_obj_init_int(i), "__gt__"), __mpy_tuple_assign(0, __mpy_obj_init_int(j), __mpy_obj_init_tuple(1)), NULL); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + printf("[GT] i : %d --- j : %d\n",i,j); + print_mpyobj_int(a); + + __mpy_builtins_cleanup(); + + return (*(int*)(a->content)) == (i > j) ? 1 : 0; +} + +TEST_CASE("GENERATE GT OP"){ + auto i = GENERATE(1, 3, 5); + auto j = GENERATE(2, 4, 6); + CHECK(gt_op(i, j) == 1); +} \ No newline at end of file diff --git a/c-runtime/test/Systemtests/ComparisonOps/TestLessEqualOp.cpp b/c-runtime/test/Systemtests/ComparisonOps/TestLessEqualOp.cpp new file mode 100644 index 0000000..e41406c --- /dev/null +++ b/c-runtime/test/Systemtests/ComparisonOps/TestLessEqualOp.cpp @@ -0,0 +1,45 @@ +#define CATCH_CONFIG_MAIN + +#include + +#include "catch.hpp" +#include "assert.h" +#include "mpy_aliases.h" +#include "mpy_obj.h" +#include "builtins-setup.h" +#include "function-args.h" +#include "literals/tuple.h" +#include "literals/int.h" +#include "literals/boolean.h" +#include "literals/str.h" +#include "type-hierarchy/object.h" +#include "type-hierarchy/type.h" +#include "test/test_helpers.h" + +int le_op(int i, int j){ + __MPyObj *a; + + __mpy_builtins_setup(); + + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + a = __mpy_call(__mpy_obj_get_attr(__mpy_obj_init_int(i), "__le__"), __mpy_tuple_assign(0, __mpy_obj_init_int(j), __mpy_obj_init_tuple(1)), NULL); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + printf("[LE] i : %d --- j : %d\n",i,j); + print_mpyobj_int(a); + + __mpy_builtins_cleanup(); + + return (*(int*)(a->content)) == (i <= j) ? 1 : 0; +} + +TEST_CASE("GENERATE LE OP"){ + auto i = GENERATE(1, 3, 5); + auto j = GENERATE(2, 4, 5); + CHECK(le_op(i, j) == 1); +} \ No newline at end of file diff --git a/c-runtime/test/Systemtests/ComparisonOps/TestLessOp.cpp b/c-runtime/test/Systemtests/ComparisonOps/TestLessOp.cpp new file mode 100644 index 0000000..84569c1 --- /dev/null +++ b/c-runtime/test/Systemtests/ComparisonOps/TestLessOp.cpp @@ -0,0 +1,46 @@ +#define CATCH_CONFIG_MAIN + +#include + +#include "catch.hpp" +#include "assert.h" +#include "mpy_aliases.h" +#include "mpy_obj.h" +#include "builtins-setup.h" +#include "function-args.h" +#include "literals/tuple.h" +#include "literals/int.h" +#include "literals/boolean.h" +#include "literals/str.h" +#include "type-hierarchy/object.h" +#include "type-hierarchy/type.h" +#include "test/test_helpers.h" + +int lt_op(int i, int j){ + __MPyObj *a; + + __mpy_builtins_setup(); + + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + a = __mpy_call(__mpy_obj_get_attr(__mpy_obj_init_int(i), "__lt__"), __mpy_tuple_assign(0, __mpy_obj_init_int(j), __mpy_obj_init_tuple(1)), NULL); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + printf("[LT] i : %d --- j : %d\n",i,j); + + print_mpyobj_int(a); + + __mpy_builtins_cleanup(); + + return (*(int*)(a->content)) == (i < j) ? 1 : 0; +} + +TEST_CASE("GENERATE LT OP"){ + auto i = GENERATE(1, 3, 5); + auto j = GENERATE(2, 4, 5); + CHECK(lt_op(i, j) == 1); +} \ No newline at end of file diff --git a/c-runtime/test/Systemtests/Conditions/TestElifStatement.cpp b/c-runtime/test/Systemtests/Conditions/TestElifStatement.cpp new file mode 100644 index 0000000..0c1cade --- /dev/null +++ b/c-runtime/test/Systemtests/Conditions/TestElifStatement.cpp @@ -0,0 +1,61 @@ +#define CATCH_CONFIG_MAIN + +#include + +#include "catch.hpp" +#include "assert.h" +#include "mpy_aliases.h" +#include "mpy_obj.h" +#include "builtins-setup.h" +#include "function-args.h" +#include "literals/tuple.h" +#include "literals/int.h" +#include "literals/boolean.h" +#include "literals/str.h" +#include "type-hierarchy/object.h" +#include "type-hierarchy/type.h" +#include "test/test_helpers.h" + +int elif_statement(int i, const char* expected){ + __MPyObj *a; + + __mpy_builtins_setup(); + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + a = __mpy_obj_init_str_static("Skipped if!"); + __mpy_obj_ref_inc(a); + if (__mpy_boolean_raw(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_boolean(false), "__bool__"), __mpy_obj_init_tuple(0), NULL))) { + __mpy_obj_ref_dec(a); + a = __mpy_obj_init_str_static("Went inside if!"); + __mpy_obj_ref_inc(a); + }else if (__mpy_boolean_raw(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_boolean(i), "__bool__"), __mpy_obj_init_tuple(0), NULL))) { + __mpy_obj_ref_dec(a); + a = __mpy_obj_init_str_static("Went inside elif!"); + __mpy_obj_ref_inc(a); + }else { + __mpy_obj_ref_dec(a); + a = __mpy_obj_init_str_static("Went inside else!"); + __mpy_obj_ref_inc(a); + } + __mpy_obj_ref_dec(a); + + printf("[ELIF STATEMENT] if condition : %d, expected : %s\n",i, expected); + print_mpyobj_str(a); + + __mpy_builtins_cleanup(); + + return strcmp(((__MPyStrContent*)a->content)->string, expected); +} + +TEST_CASE("ELIF CONDITION") { + auto i = 0; + SECTION("elif(false)") { + CHECK(elif_statement(i,"Went inside else!") == 0); + } + i = 1; + SECTION("elif(true)") { + CHECK(elif_statement(i,"Went inside elif!") == 0); + } +} diff --git a/c-runtime/test/Systemtests/Conditions/TestElseStatement.cpp b/c-runtime/test/Systemtests/Conditions/TestElseStatement.cpp new file mode 100644 index 0000000..f7833dc --- /dev/null +++ b/c-runtime/test/Systemtests/Conditions/TestElseStatement.cpp @@ -0,0 +1,57 @@ +#define CATCH_CONFIG_MAIN + +#include + +#include "catch.hpp" +#include "assert.h" +#include "mpy_aliases.h" +#include "mpy_obj.h" +#include "builtins-setup.h" +#include "function-args.h" +#include "literals/tuple.h" +#include "literals/int.h" +#include "literals/boolean.h" +#include "literals/str.h" +#include "type-hierarchy/object.h" +#include "type-hierarchy/type.h" +#include "test/test_helpers.h" + +int else_statement(int i, const char* expected){ + __MPyObj *a; + + __mpy_builtins_setup(); + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + a = __mpy_obj_init_str_static("Skipped if!"); + __mpy_obj_ref_inc(a); + if (__mpy_boolean_raw(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_boolean(i), "__bool__"), __mpy_obj_init_tuple(0), NULL))) { + __mpy_obj_ref_dec(a); + a = __mpy_obj_init_str_static("Went inside if!"); + __mpy_obj_ref_inc(a); + }else { + __mpy_obj_ref_dec(a); + a = __mpy_obj_init_str_static("Went inside else!"); + __mpy_obj_ref_inc(a); + } + __mpy_obj_ref_dec(a); + + printf("[ELSE STATEMENT] if condition : %d, expected : %s\n",i, expected); + print_mpyobj_str(a); + + __mpy_builtins_cleanup(); + + return strcmp(((__MPyStrContent*)a->content)->string, expected); +} + +TEST_CASE("ELSE CONDITION") { + auto i = 0; + SECTION("else") { + CHECK(else_statement(i,"Went inside else!") == 0); + } + i = 1; + SECTION("else") { + CHECK(else_statement(i,"Went inside if!") == 0); + } +} diff --git a/c-runtime/test/Systemtests/Conditions/TestIfStatement.cpp b/c-runtime/test/Systemtests/Conditions/TestIfStatement.cpp new file mode 100644 index 0000000..b6d6487 --- /dev/null +++ b/c-runtime/test/Systemtests/Conditions/TestIfStatement.cpp @@ -0,0 +1,59 @@ +#define CATCH_CONFIG_MAIN + +#include + +#include "catch.hpp" +#include "assert.h" +#include "mpy_aliases.h" +#include "mpy_obj.h" +#include "builtins-setup.h" +#include "function-args.h" +#include "literals/tuple.h" +#include "literals/int.h" +#include "literals/boolean.h" +#include "literals/str.h" +#include "type-hierarchy/object.h" +#include "type-hierarchy/type.h" +#include "test/test_helpers.h" + +int if_statement(int i, const char* expected){ + __MPyObj *a; + + __mpy_builtins_setup(); + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + a = __mpy_obj_init_str_static("Skipped if!"); + __mpy_obj_ref_inc(a); + if (__mpy_boolean_raw(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_boolean(i), "__bool__"), __mpy_obj_init_tuple(0), NULL))) { + __mpy_obj_ref_dec(a); + a = __mpy_obj_init_str_static("Went inside if!"); + __mpy_obj_ref_inc(a); + } + __mpy_obj_ref_dec(a); + + printf("[IF STATEMENT] If condition : %d, expected : %s\n",i, expected); + print_mpyobj_str(a); + + __mpy_builtins_cleanup(); + + return strcmp(((__MPyStrContent*)a->content)->string, expected); +} +/* +TEST_CASE("GENERATE IF CONDITION"){ + auto i = GENERATE(0, 1); + auto j = GENERATE("Skipped if!", "Went inside if!"); + CHECK(if_statement(i, j) == 0); +}*/ + +TEST_CASE("IF CONDITION") { + auto i = 0; + SECTION("if(false)") { + CHECK(if_statement(i, "Skipped if!") == 0); + } + i = 1; + SECTION("if(true)") { + CHECK(if_statement(i,"Went inside if!") == 0); + } +} diff --git a/c-runtime/test/Systemtests/Conditions/TestWhileStatement.cpp b/c-runtime/test/Systemtests/Conditions/TestWhileStatement.cpp new file mode 100644 index 0000000..f326159 --- /dev/null +++ b/c-runtime/test/Systemtests/Conditions/TestWhileStatement.cpp @@ -0,0 +1,50 @@ +#define CATCH_CONFIG_MAIN + +#include + +#include "catch.hpp" +#include "assert.h" +#include "mpy_aliases.h" +#include "mpy_obj.h" +#include "builtins-setup.h" +#include "function-args.h" +#include "literals/tuple.h" +#include "literals/int.h" +#include "literals/boolean.h" +#include "literals/str.h" +#include "type-hierarchy/object.h" +#include "type-hierarchy/type.h" +#include "test/test_helpers.h" + + +int while_statement(){ + __MPyObj *a; + int counter = 0; + + __mpy_builtins_setup(); + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + a = __mpy_obj_init_int(3); + __mpy_obj_ref_inc(a); + + while (__mpy_boolean_raw(__mpy_call(__mpy_obj_get_attr(__mpy_call(__mpy_obj_get_attr(a, "__gt__"), __mpy_tuple_assign(0, __mpy_obj_init_int(1), __mpy_obj_init_tuple(1)), NULL), "__bool__"), __mpy_obj_init_tuple(0), NULL))) { + __mpy_obj_ref_dec(a); + a = __mpy_call(__mpy_obj_get_attr(a, "__sub__"), __mpy_tuple_assign(0, __mpy_obj_init_int(1), __mpy_obj_init_tuple(1)), NULL); + __mpy_obj_ref_inc(a); + counter = counter +1; + } + __mpy_obj_ref_dec(a); + + printf("Visited while loop : %d times", counter); + print_mpyobj_int(a); + + __mpy_builtins_cleanup(); + + return (counter == 2) ? 1 : 0; +} + +TEST_CASE( "TEST WHILE STATEMENT" ){ + REQUIRE(while_statement() == 1); +} diff --git a/c-runtime/test/Systemtests/DeclarationAndAssignment/TestDeclarationAndAssignment.cpp b/c-runtime/test/Systemtests/DeclarationAndAssignment/TestDeclarationAndAssignment.cpp new file mode 100644 index 0000000..a62a9d8 --- /dev/null +++ b/c-runtime/test/Systemtests/DeclarationAndAssignment/TestDeclarationAndAssignment.cpp @@ -0,0 +1,144 @@ +// 010-TestCase.cpp + +// Let Catch provide main(): +#define CATCH_CONFIG_MAIN +//#define CATCH_CONFING_RUNNER + +#include + +#include "catch.hpp" +#include "assert.h" +#include "mpy_aliases.h" +#include "mpy_obj.h" +#include "builtins-setup.h" +#include "function-args.h" +#include "literals/tuple.h" +#include "literals/int.h" +#include "literals/boolean.h" +#include "literals/str.h" +#include "type-hierarchy/object.h" +#include "type-hierarchy/type.h" +#include "test/test_helpers.h" +#include "literals/str.h" + +int declaration_checked_malloc() { + __MPyObj *a; + + __mpy_builtins_setup(); + + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + print_mpyobj(a); + + __mpy_builtins_cleanup(); + + return a != NULL; // This will never be the case since checked_malloc will terminate the program if malloc fails. +} + +int declaration_assigned_id() { + __MPyObj *a; + + __mpy_builtins_setup(); + + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + print_mpyobj(a); + + __mpy_builtins_cleanup(); + + return (a->id == 123) ? 1 : 0; +} + +int assignment_int_literal(int i){ + __MPyObj *a; + + __mpy_builtins_setup(); + + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + a = __mpy_obj_init_int(i); + __mpy_obj_ref_inc(a); + + print_mpyobj_int(a); + + __mpy_builtins_cleanup(); + + return (*(int*)(a->content)) == i ? 1 : 0; +} + +int assignment_string_literal(){ + __MPyObj *a; + + __mpy_builtins_setup(); + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + a = __mpy_obj_init_str_static("stringVal"); + __mpy_obj_ref_inc(a); + + print_mpyobj_str(a); + + __mpy_obj_ref_dec(a); + + __mpy_builtins_cleanup(); + + return strcmp(((__MPyStrContent*)a->content)->string, "stringVal"); +} + +int assignment_bool_literal(){ + __MPyObj *a; + + __mpy_builtins_setup(); + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + a = __mpy_obj_init_boolean(true); + __mpy_obj_ref_inc(a); + + print_mpyobj_bool(a); + + __mpy_obj_ref_dec(a); + + __mpy_builtins_cleanup(); + return (((MPyBooleanContent*)a->content)->value) ? 1 : 0; +} + +int assignment_tuple_literal(){ +// see literals/tuple.c + __MPyObj *a; + + __mpy_builtins_setup(); + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + a = __mpy_tuple_assign(0, __mpy_obj_init_int(123), __mpy_tuple_assign(1, __mpy_obj_init_str_static("stringVal"), __mpy_tuple_assign(2, __mpy_obj_init_boolean(true), __mpy_obj_init_tuple(3)))); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + + + __mpy_builtins_cleanup(); + + return 0; +} + +TEST_CASE( "TEST" ){ + REQUIRE(declaration_checked_malloc() == 1); + CHECK(declaration_assigned_id() == 1); + CHECK(assignment_int_literal(133) == 1); + CHECK(assignment_string_literal() == 0); // 0 means the const char* are the same + CHECK(assignment_bool_literal() == 1); +} + +TEST_CASE("GENERATE"){ + auto i = GENERATE(1, 3, 5); + CHECK(assignment_int_literal(i) == 1); +} diff --git a/c-runtime/test/Systemtests/FunctionCalls/TestFunctionBody.cpp b/c-runtime/test/Systemtests/FunctionCalls/TestFunctionBody.cpp new file mode 100644 index 0000000..435871d --- /dev/null +++ b/c-runtime/test/Systemtests/FunctionCalls/TestFunctionBody.cpp @@ -0,0 +1,175 @@ +#define CATCH_CONFIG_RUNNER + +#include + +#include "catch.hpp" +#include "test/test_helpers.h" +#include "test/FunctionCalls/TestFunctionBodyHelpers.h" + +__MPyObj *minimalistic_body; + +__MPyObj *print_from_func; + +__MPyObj *return_local_var; + +__MPyObj *return_param_body; + +__MPyObj *return_add; + +__MPyObj *return_add_conditional; + +int main( int argc, char* argv[] ) { + // global setup... + __mpy_builtins_setup(); + + int result = 0; + + try{ + result = Catch::Session().run( argc, argv ); + } + catch (const std::runtime_error& error){ + printf("Hello World"); + } + + __mpy_builtins_cleanup(); + // global clean-up... Why is this working ? .... + + return result; +} + +int minimal_body(){ + __MPyObj *a; + + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + minimalistic_body = __mpy_obj_init_func(&func_minimalistic_body); + __mpy_obj_ref_inc(minimalistic_body); + + + __mpy_obj_ref_dec(a); + a = __mpy_call(minimalistic_body, __mpy_obj_init_tuple(0), NULL); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + __mpy_obj_ref_dec(minimalistic_body); + + return (*(int*)(a->content)); +} + +int print_from_func_body(){ + __MPyObj *a; + + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + print_from_func = __mpy_obj_init_func(&func_print_from_func); + __mpy_obj_ref_inc(print_from_func); + + __mpy_obj_ref_dec(a); + a = __mpy_call(print_from_func, __mpy_obj_init_tuple(0), NULL); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + __mpy_obj_ref_dec(print_from_func); + + return (*(int*)(a->content)); +} + +int local_var_body(){ + __MPyObj *a; + + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + return_local_var = __mpy_obj_init_func(&func_return_local_var); + __mpy_obj_ref_inc(return_local_var); + + + __mpy_obj_ref_dec(a); + a = __mpy_call(return_local_var, __mpy_obj_init_tuple(0), NULL); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + __mpy_obj_ref_dec(return_local_var); + + return (*(int*)(a->content)); +} + +int param_body(){ + __MPyObj *a; + + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + return_param_body = __mpy_obj_init_func(&func_return_param_body); + __mpy_obj_ref_inc(return_param_body); + + + __mpy_obj_ref_dec(a); + a = __mpy_call(return_param_body, __mpy_tuple_assign(0, __mpy_obj_init_int(1), __mpy_obj_init_tuple(1)), NULL); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + __mpy_obj_ref_dec(return_param_body); + + return (*(int*)(a->content)); +} + +int return_add_body(){ + __MPyObj *a; + + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + return_add = __mpy_obj_init_func(&func_return_add); + __mpy_obj_ref_inc(return_add); + + + __mpy_obj_ref_dec(a); + a = __mpy_call(return_add, __mpy_tuple_assign(0, __mpy_obj_init_int(1), __mpy_tuple_assign(1, __mpy_obj_init_int(3), __mpy_obj_init_tuple(2))), NULL); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + __mpy_obj_ref_dec(return_add); + + return (*(int*)(a->content)) == 4 ? 1 : 0; +} + +int return_add_conditional_body(){ + __MPyObj *a; + + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + return_add_conditional = __mpy_obj_init_func(&func_return_add_conditional); + __mpy_obj_ref_inc(return_add_conditional); + + + __mpy_obj_ref_dec(a); + a = __mpy_call(return_add_conditional, __mpy_tuple_assign(0, __mpy_obj_init_int(1), __mpy_tuple_assign(1, __mpy_obj_init_int(3), __mpy_obj_init_tuple(2))), NULL); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + __mpy_obj_ref_dec(return_add_conditional); + + return (*(int*)(a->content)) == 4 ? 1 : 0; +} + +TEST_CASE("DIFFERENT FUNCTION BODIES"){ + CAPTURE(minimal_body()); + CAPTURE(print_from_func_body()); // CAPTURE prints one additional time. + + CHECK(minimal_body() == 1); + CHECK(print_from_func_body() == 1); + CHECK(local_var_body() == 1); + CHECK(param_body() == 1); + CHECK(return_add_body() == 1); + CHECK(return_add_conditional_body() == 1); +} diff --git a/c-runtime/test/Systemtests/FunctionCalls/TestFunctionParams.cpp b/c-runtime/test/Systemtests/FunctionCalls/TestFunctionParams.cpp new file mode 100644 index 0000000..69918bf --- /dev/null +++ b/c-runtime/test/Systemtests/FunctionCalls/TestFunctionParams.cpp @@ -0,0 +1,209 @@ +#define CATCH_CONFIG_RUNNER + +#include + +#include "catch.hpp" +#include "test/test_helpers.h" +#include "test/FunctionCalls/TestFunctionParamsHelpers.h" + +__MPyObj *func1; + +__MPyObj *func2; + +__MPyObj *func3; + +__MPyObj *func4; + +int main( int argc, char* argv[] ) { + // global setup... + __mpy_builtins_setup(); + + int result = 0; + + try{ + result = Catch::Session().run( argc, argv ); + } + catch (const std::runtime_error& error){ + printf("Hello World"); + } + + __mpy_builtins_cleanup(); + // global clean-up... Why is this working ? .... + + return result; +} + +int empty_params(const char* expected){ + __MPyObj *a; + + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + func1 = __mpy_obj_init_func(&func_func1); + __mpy_obj_ref_inc(func1); + + __mpy_obj_ref_dec(a); + a = __mpy_call(func1, __mpy_obj_init_tuple(0), NULL); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + __mpy_obj_ref_dec(func1); + + print_mpyobj_str(a); + + return strcmp(((__MPyStrContent*)a->content)->string, expected); +} + +int one_param(__MPyObj *param1, __MPyObj *expected, int isNumeric){ + __MPyObj *a; + + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + func2 = __mpy_obj_init_func(&func_func2); + __mpy_obj_ref_inc(func2); + + + __mpy_obj_ref_dec(a); + a = __mpy_call(func2, __mpy_tuple_assign(0, param1, __mpy_obj_init_tuple(1)), NULL); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + __mpy_obj_ref_dec(func2); + + if(!isNumeric){ + print_mpyobj_str(a); + return strcmp(((__MPyStrContent*)a->content)->string, ((__MPyStrContent*)expected->content)->string); + } + + print_mpyobj_int(a); + return (*(int*)(a->content)) == (*(int*)(expected->content)) ? 1 : 0; +} + +int one_param_print_call(){ + __MPyObj *a; + + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + func4 = __mpy_obj_init_func(&func_func4); + __mpy_obj_ref_inc(func4); + + + __mpy_obj_ref_dec(a); + a = __mpy_call(func4, __mpy_tuple_assign(0, __mpy_call(print, __mpy_tuple_assign(0, __mpy_obj_init_str_static("Wuppie"), __mpy_obj_init_tuple(1)), NULL), __mpy_obj_init_tuple(1)), NULL); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + __mpy_obj_ref_dec(func4); + + return 0; +} + +int multiple_params(__MPyObj *param1, __MPyObj *param2, __MPyObj *expected, int isNumeric){ + __MPyObj *a; + + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + func3 = __mpy_obj_init_func(&func_func3); + __mpy_obj_ref_inc(func3); + + __mpy_obj_ref_dec(a); + a = __mpy_call(func3, __mpy_tuple_assign(0, param1, __mpy_tuple_assign(1, param2, __mpy_obj_init_tuple(2))), NULL); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + __mpy_obj_ref_dec(func3); + + if(!isNumeric){ + print_mpyobj_str(a); + return strcmp(((__MPyStrContent*)a->content)->string, ((__MPyStrContent*)expected->content)->string); + } + + print_mpyobj_int(a); + return (*(int*)(a->content)) == (*(int*)(expected->content)) ? 1 : 0; +} + +TEST_CASE("TEST FUNCTION EMPTY PARAMS") +{ + CHECK(empty_params("Function called !") == 0); + CHECK(one_param_print_call() == 0); // This does not crash return value is irrelevant. +} + +TEST_CASE("TEST FUNCTION ONE PARAM") +{ + auto [input, expected_output, isNumeric] = GENERATE(table<__MPyObj *, __MPyObj *, int>({ + { __mpy_obj_init_int(123), __mpy_obj_init_int(123), 1}, + { __mpy_obj_init_boolean(true), __mpy_obj_init_boolean(true), 1}, + { __mpy_obj_init_str_static("String"), __mpy_obj_init_str_static("String"), 0}, + })); + + __MPyObj *param1; + __MPyObj *expected; + + param1 = __mpy_obj_init_object(); + __mpy_obj_ref_inc(param1); + + __mpy_obj_ref_dec(param1); + param1 = input; + __mpy_obj_ref_inc(param1); + + expected = __mpy_obj_init_object(); + __mpy_obj_ref_inc(expected); + + __mpy_obj_ref_dec(expected); + expected = expected_output; + __mpy_obj_ref_inc(expected); + + CAPTURE(input); + if(!isNumeric) + CHECK(one_param(param1, expected, isNumeric) == 0); + else + CHECK(one_param(param1, expected, isNumeric) == 1); +} + +TEST_CASE("TEST FUNCTION MULTIPLE PARAMS") +{ + auto [input1, input2, expected_output, isNumeric] = GENERATE(table<__MPyObj *, __MPyObj *, __MPyObj *, int>({ + { __mpy_obj_init_int(1), __mpy_obj_init_int(2), __mpy_obj_init_int(3), 1}, + { __mpy_obj_init_str_static("Hello"), __mpy_obj_init_str_static(" World !"), __mpy_obj_init_str_static("Hello World !"), 0}, + })); + + __MPyObj *param1; + __MPyObj *param2; + __MPyObj *expected; + + param1 = __mpy_obj_init_object(); + __mpy_obj_ref_inc(param1); + + __mpy_obj_ref_dec(param1); + param1 = input1; + __mpy_obj_ref_inc(param1); + + param2 = __mpy_obj_init_object(); + __mpy_obj_ref_inc(param2); + + __mpy_obj_ref_dec(param2); + param2 = input2; + __mpy_obj_ref_inc(param2); + + expected = __mpy_obj_init_object(); + __mpy_obj_ref_inc(expected); + + __mpy_obj_ref_dec(expected); + expected = expected_output; + __mpy_obj_ref_inc(expected); + + CAPTURE(input1); + CAPTURE(input2); + + if(!isNumeric) + CHECK(multiple_params(param1, param2, expected, isNumeric) == 0); + else + CHECK(multiple_params(param1, param2, expected, isNumeric) == 1); +} diff --git a/c-runtime/test/Systemtests/FunctionCalls/TestFunctionParamsThrows.cpp b/c-runtime/test/Systemtests/FunctionCalls/TestFunctionParamsThrows.cpp new file mode 100644 index 0000000..c7071cb --- /dev/null +++ b/c-runtime/test/Systemtests/FunctionCalls/TestFunctionParamsThrows.cpp @@ -0,0 +1,148 @@ +#define CATCH_CONFIG_RUNNER + +#include + +#include "catch.hpp" +#include "test/test_helpers.h" +#include "test/FunctionCalls/TestFunctionParamsHelpers.h" + +__MPyObj *func_throws1; +__MPyObj *throws2; +__MPyObj *throws3; +__MPyObj *throws4; +__MPyObj *throws5; + +void exit(int status); + +int main( int argc, char* argv[] ) { + // global setup... + __mpy_builtins_setup(); + + int result = 0; + + try{ + result = Catch::Session().run( argc, argv ); + } + catch (const std::runtime_error& error){ + printf("Hello World"); + } + + __mpy_builtins_cleanup(); + // global clean-up... Why is this working ? .... + + return result; +} + +int no_param_but_provided(){ + __MPyObj *a; + + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + func_throws1 = __mpy_obj_init_func(&func_func_throws1); + __mpy_obj_ref_inc(func_throws1); + + __mpy_obj_ref_dec(a); + a = __mpy_call(func_throws1, __mpy_tuple_assign(0, __mpy_obj_init_int(123), __mpy_obj_init_tuple(1)), NULL); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + __mpy_obj_ref_dec(func_throws1); + + return 0; +} + +int one_param_but_none_provided(){ + __MPyObj *a; + + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + throws2 = __mpy_obj_init_func(&func_throws2); + __mpy_obj_ref_inc(throws2); + + + __mpy_obj_ref_dec(a); + a = __mpy_call(throws2, __mpy_obj_init_tuple(0), NULL); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + __mpy_obj_ref_dec(throws2); + + return 0; +} + +int one_param_but_two_provided(){ + __MPyObj *a; + + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + throws3 = __mpy_obj_init_func(&func_throws3); + __mpy_obj_ref_inc(throws3); + + + __mpy_obj_ref_dec(a); + a = __mpy_call(throws3, __mpy_tuple_assign(0, __mpy_obj_init_str_static("String1"), __mpy_tuple_assign(1, __mpy_obj_init_str_static("String2"), __mpy_obj_init_tuple(2))), NULL); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + __mpy_obj_ref_dec(throws3); + +} + +int one_param_but_void_function_provided(){ + __MPyObj *a; + + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + throws4 = __mpy_obj_init_func(&func_throws4); + __mpy_obj_ref_inc(throws4); + + __mpy_obj_ref_dec(a); + a = __mpy_call(print, __mpy_tuple_assign(0, __mpy_call(throws4, __mpy_tuple_assign(0, __mpy_call(print, __mpy_obj_init_tuple(0), NULL), __mpy_obj_init_tuple(1)), NULL), __mpy_obj_init_tuple(1)), NULL); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + __mpy_obj_ref_dec(throws4); + + return 0; +} + +int two_params_but_one_provided(){ + __MPyObj *a; + + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + throws5 = __mpy_obj_init_func(&func_throws5); + __mpy_obj_ref_inc(throws5); + + __mpy_obj_ref_dec(a); + a = __mpy_call(throws5, __mpy_tuple_assign(0, __mpy_obj_init_int(1), __mpy_obj_init_tuple(1)), NULL); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + __mpy_obj_ref_dec(throws5); + + return 0; +} + +TEST_CASE("TEST FUNCTION THROWS") +{ + CHECK_THROWS_AS(no_param_but_provided(), std::runtime_error); + CHECK_THROWS_AS(one_param_but_none_provided(), std::runtime_error); + CHECK_THROWS_AS(one_param_but_two_provided(), std::runtime_error); + CHECK_THROWS_AS(one_param_but_void_function_provided(), std::runtime_error); // This belongs to built in print testing! + CHECK_THROWS_AS(two_params_but_one_provided(), std::runtime_error); +} + +void exit(int status) { + throw std::runtime_error(""); +} diff --git a/c-runtime/test/Systemtests/FunctionCalls/TestFunctionRecursion.cpp b/c-runtime/test/Systemtests/FunctionCalls/TestFunctionRecursion.cpp new file mode 100644 index 0000000..354347f --- /dev/null +++ b/c-runtime/test/Systemtests/FunctionCalls/TestFunctionRecursion.cpp @@ -0,0 +1,53 @@ +#define CATCH_CONFIG_RUNNER + +#include + +#include "catch.hpp" +#include "test/test_helpers.h" +#include "test/FunctionCalls/TestFunctionRecursionHelpers.h" + +int main( int argc, char* argv[] ) { + // global setup... + __mpy_builtins_setup(); + + int result = 0; + + try{ + result = Catch::Session().run( argc, argv ); + } + catch (const std::runtime_error& error){ + printf(""); + } + + __mpy_builtins_cleanup(); + // global clean-up... Why is this working ? .... + + return result; +} + +int rec(){ + __MPyObj *a; + + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + recursion = __mpy_obj_init_func(&func_recursion); + __mpy_obj_ref_inc(recursion); + + + __mpy_obj_ref_dec(a); + a = __mpy_call(recursion, __mpy_tuple_assign(0, __mpy_obj_init_int(5), __mpy_obj_init_tuple(1)), NULL); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + __mpy_obj_ref_dec(recursion); + + print_mpyobj_int(a); + + return (*(int*)(a->content)) == 0 ? 1 : 0; +} + +TEST_CASE("FUNCTION RECURSION"){ + CHECK(rec() == 1); +} diff --git a/c-runtime/test/Systemtests/FunctionCalls/TestFunctionReturn.cpp b/c-runtime/test/Systemtests/FunctionCalls/TestFunctionReturn.cpp new file mode 100644 index 0000000..d1ad429 --- /dev/null +++ b/c-runtime/test/Systemtests/FunctionCalls/TestFunctionReturn.cpp @@ -0,0 +1,104 @@ +#define CATCH_CONFIG_RUNNER + +#include + +#include "catch.hpp" +#include "test/test_helpers.h" +#include "test/FunctionCalls/TestFunctionReturnHelpers.h" + +__MPyObj *return_expression; + +__MPyObj *return_tuple_literal_throws; + +__MPyObj *return_void_function_call_print; + +int main( int argc, char* argv[] ) { + // global setup... + __mpy_builtins_setup(); + + int result = 0; + + try{ + result = Catch::Session().run( argc, argv ); + } + catch (const std::runtime_error& error){ + printf("Hello World"); + } + + __mpy_builtins_cleanup(); + // global clean-up... Why is this working ? .... + + return result; +} + +int return_expr(){ + __MPyObj *a; + + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + return_expression = __mpy_obj_init_func(&func_return_expression); + __mpy_obj_ref_inc(return_expression); + + + __mpy_obj_ref_dec(a); + a = __mpy_call(return_expression, __mpy_obj_init_tuple(0), NULL); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + __mpy_obj_ref_dec(return_expression); + + return (*(int*)(a->content)); +} + +int return_tuple_literal(){ + __MPyObj *a; + + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + return_tuple_literal_throws = __mpy_obj_init_func(&func_return_tuple_literal_throws); + __mpy_obj_ref_inc(return_tuple_literal_throws); + + __mpy_obj_ref_dec(a); + a = __mpy_call(return_tuple_literal_throws, __mpy_obj_init_tuple(0), NULL); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + print_mpyobj(a); + + __mpy_obj_ref_dec(return_tuple_literal_throws); + + return 1; +} + +int return_print(){ + __MPyObj *a; + + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + return_void_function_call_print = __mpy_obj_init_func(&func_return_void_function_call_print); + __mpy_obj_ref_inc(return_void_function_call_print); + + + __mpy_obj_ref_dec(a); + a = __mpy_call(return_void_function_call_print, __mpy_obj_init_tuple(0), NULL); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + print_mpyobj(a); + + __mpy_obj_ref_dec(return_void_function_call_print); + + return 1; +} + +TEST_CASE("RETURN VALUES"){ + CHECK(return_expr() == 1); //This is actually return_mpyobj when the expression is evaluated... Also if you call func or return string, bool, int literal ... + CHECK(return_tuple_literal() == 1); // Returning does not throw an error but trying to print the "returned" values will result in a crashing program. See TestFunctionReturn.java + CHECK(return_print() == 1); // "" +} // Testing return of literals is already done in TestFunctionParams.cpp diff --git a/c-runtime/test/Systemtests/LogicalOps/TestLogicalOps.cpp b/c-runtime/test/Systemtests/LogicalOps/TestLogicalOps.cpp new file mode 100644 index 0000000..aa9994f --- /dev/null +++ b/c-runtime/test/Systemtests/LogicalOps/TestLogicalOps.cpp @@ -0,0 +1,101 @@ +#define CATCH_CONFIG_MAIN + +#include + +#include "catch.hpp" +#include "assert.h" +#include "mpy_aliases.h" +#include "mpy_obj.h" +#include "builtins-setup.h" +#include "function-args.h" +#include "literals/tuple.h" +#include "literals/int.h" +#include "literals/boolean.h" +#include "literals/str.h" +#include "type-hierarchy/object.h" +#include "type-hierarchy/type.h" +#include "test/test_helpers.h" + +int and_op(int i, int j){ + __MPyObj *a; + + __mpy_builtins_setup(); + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + + + __mpy_obj_ref_dec(a); + a = __mpy_obj_init_boolean(__mpy_boolean_raw(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_boolean(i), "__bool__"), __mpy_obj_init_tuple(0), NULL)) && __mpy_boolean_raw(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_boolean(j), "__bool__"), __mpy_obj_init_tuple(0), NULL))); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + printf("[AND] i : %d --- j : %d\n",i,j); + print_mpyobj_int(a); + + __mpy_builtins_cleanup(); + + return (*(int*)(a->content)) == (i && j) ? 1 : 0; + +} + +int or_op(int i, int j){ + __MPyObj *a; + + __mpy_builtins_setup(); + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + a = __mpy_obj_init_boolean(__mpy_boolean_raw(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_boolean(i), "__bool__"), __mpy_obj_init_tuple(0), NULL)) || __mpy_boolean_raw(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_boolean(j), "__bool__"), __mpy_obj_init_tuple(0), NULL))); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + printf("[OR] i : %d --- j : %d\n",i,j); + print_mpyobj_int(a); + + __mpy_builtins_cleanup(); + + return (*(int*)(a->content)) == (i || j) ? 1 : 0; + +} + +int not_op(int i){ + __MPyObj *a; + + __mpy_builtins_setup(); + a = __mpy_obj_init_object(); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + a = __mpy_obj_init_boolean(!__mpy_boolean_raw(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_boolean(i), "__bool__"), __mpy_obj_init_tuple(0), NULL))); + __mpy_obj_ref_inc(a); + + __mpy_obj_ref_dec(a); + + printf("[NOT] i : %d\n",i); + print_mpyobj_int(a); + + __mpy_builtins_cleanup(); + + return (*(int*)(a->content)) == (!i) ? 1 : 0; +} + +TEST_CASE("GENERATE AND OP"){ + auto i = GENERATE(0, 1); + auto j = GENERATE(0, 1); + CHECK(and_op(i, j) == 1); +} + +TEST_CASE("GENERATE OR OP"){ + auto i = GENERATE(0, 1); + auto j = GENERATE(0, 1); + CHECK(or_op(i, j) == 1); +} + +TEST_CASE("GENERATE NOT OP"){ + auto i = GENERATE(0,1); + CHECK(not_op(i) == 1); +} diff --git a/c-runtime/test/Systemtests/makefile b/c-runtime/test/Systemtests/makefile new file mode 100644 index 0000000..a545b93 --- /dev/null +++ b/c-runtime/test/Systemtests/makefile @@ -0,0 +1,152 @@ +RUNDECLA := /test/Systemtests/DeclarationAndAssignment/TestDeclarationAndAssignment.out +RUNARITOPS := /test/Systemtests/ArithmeticOps/TestArithmeticOps.out +RUNCOMPOPS := /test/Systemtests/ComparisonOps/TestComparisonOps.out +RUNGEOP := /test/Systemtests/ComparisonOps/TestGreaterEqualOp.out +RUNGTOP := /test/Systemtests/ComparisonOps/TestGreaterOp.out +RUNLEOP := /test/Systemtests/ComparisonOps/TestLessEqualOp.out +RUNLTOP := /test/Systemtests/ComparisonOps/TestLessOp.out +RUNLOGOPS := /test/Systemtests/LogicalOps/TestLogicalOps.out +RUNIFST := /test/Systemtests/Conditions/TestIfStatement.out +RUNELST := /test/Systemtests/Conditions/TestElseStatement.out +RUNELIFST := /test/Systemtests/Conditions/TestElifStatement.out +RUNWHILEST := /test/Systemtests/Conditions/TestWhileStatement.out +RUNCASTINT := /test/Systemtests/BuiltInFunctions/TestCastInt.out +RUNCASTSTRING := /test/Systemtests/BuiltInFunctions/TestCastString.out +RUNID := /test/Systemtests/BuiltInFunctions/TestId.out +RUNPRINT := /test/Systemtests/BuiltInFunctions/TestPrint.out +RUNTYPE := /test/Systemtests/BuiltInFunctions/TestType.out +RUNFUNPARAMS := /test/Systemtests/FunctionCalls/TestFunctionParams.out +RUNFUNPARAMSTHROWS := /test/Systemtests/FunctionCalls/TestFunctionParamsThrows.out +RUNFUNBODY := /test/Systemtests/FunctionCalls/TestFunctionBody.out +RUNFUNRET := /test/Systemtests/FunctionCalls/TestFunctionReturn.out +RUNFUNREC := /test/Systemtests/FunctionCalls/TestFunctionRecursion.out +RUNCLASSINIT := /test/Systemtests/Classes/TestClassInit.out +RUNCLASSINITTHROWS := /test/Systemtests/Classes/TestClassInitThrows.out +RUNCLASSMEMBERS := /test/Systemtests/Classes/TestClassMembers.out +RUNCLASSINHERITANCE := /test/Systemtests/Classes/TestClassInheritance.out + +CXXFLAGS ?= -std=c++14 + +.PHONY : all run echo test_declaration_and_assignment test_arithmetic_ops test_comparison_ops test_greater_equal_op test_greater_op test_less_equal_op test_less_op test_logical_ops test_if_statement test_else_statement test_elif_statement test_while_statement test_cast_int test_cast_string test_id test_print test_type test_function_params test_function_params_throws test_function_body test_function_return test_function_recursion test_class_init test_class_init_throws test_class_members test_class_inheritance clean + +all: test_declaration_and_assignment test_arithmetic_ops test_comparison_ops test_greater_equal_op test_greater_op test_less_equal_op test_less_op test_logical_ops test_if_statement test_else_statement test_elif_statement test_while_statement test_cast_int test_cast_string test_print test_type test_function_params test_function_params_throws test_function_body test_function_return test_function_recursion test_class_init test_class_init_throws test_class_members test_class_inheritance run + +run: + .$(RUNDECLA) + .$(RUNARITOPS) + .$(RUNCOMPOPS) + .$(RUNGEOP) + .$(RUNGTOP) + .$(RUNLEOP) + .$(RUNLTOP) + .$(RUNLOGOPS) + .$(RUNIFST) + .$(RUNELST) + .$(RUNELIFST) + .$(RUNWHILEST) + .$(RUNCASTINT) + .$(RUNCASTSTRING) + .$(RUNPRINT) + .$(RUNTYPE) + .$(RUNFUNPARAMS) + .$(RUNFUNPARAMSTHROWS) + .$(RUNFUNBODY) + .$(RUNFUNRET) + .$(RUNFUNREC) + .$(RUNCLASSINIT) + .$(RUNCLASSINITTHROWS) + .$(RUNCLASSMEMBERS) + .$(RUNCLASSINHERITANCE) + +echo: + @echo ${C_FILES} + @echo ${TESTDIR} + @echo ${RUN} + +test_declaration_and_assignment: + g++-13 -I $(INCLUDEDIR) -I $(INCLUDEDIRTEST) -o $(TESTDIR)/Systemtests/DeclarationAndAssignment/TestDeclarationAndAssignment.out -w -fpermissive $(TESTDIR)/Systemtests/DeclarationAndAssignment/TestDeclarationAndAssignment.c* $(C_FILES_TEST) + +test_arithmetic_ops: + g++-13 -I $(INCLUDEDIR) -I $(INCLUDEDIRTEST) -o $(TESTDIR)/Systemtests/ArithmeticOps/TestArithmeticOps.out -w -fpermissive $(TESTDIR)/Systemtests/ArithmeticOps/TestArithmeticOps.c* $(C_FILES_TEST) + +test_comparison_ops: + g++-13 --version + g++-13 -I $(INCLUDEDIR) -I $(INCLUDEDIRTEST) -o $(TESTDIR)/Systemtests/ComparisonOps/TestComparisonOps.out -w -fpermissive $(TESTDIR)/Systemtests/ComparisonOps/TestComparisonOps.c* $(C_FILES_TEST) + +test_greater_equal_op: + g++-13 -I $(INCLUDEDIR) -I $(INCLUDEDIRTEST) -o $(TESTDIR)/Systemtests/ComparisonOps/TestGreaterEqualOp.out -w -fpermissive $(TESTDIR)/Systemtests/ComparisonOps/TestGreaterEqualOp.c* $(C_FILES_TEST) + +test_greater_op: + g++-13 -I $(INCLUDEDIR) -I $(INCLUDEDIRTEST) -o $(TESTDIR)/Systemtests/ComparisonOps/TestGreaterOp.out -w -fpermissive $(TESTDIR)/Systemtests/ComparisonOps/TestGreaterOp.c* $(C_FILES_TEST) + +test_less_equal_op: + g++-13 -I $(INCLUDEDIR) -I $(INCLUDEDIRTEST) -o $(TESTDIR)/Systemtests/ComparisonOps/TestLessEqualOp.out -w -fpermissive $(TESTDIR)/Systemtests/ComparisonOps/TestLessEqualOp.c* $(C_FILES_TEST) + +test_less_op: + g++-13 -I $(INCLUDEDIR) -I $(INCLUDEDIRTEST) -o $(TESTDIR)/Systemtests/ComparisonOps/TestLessOp.out -w -fpermissive $(TESTDIR)/Systemtests/ComparisonOps/TestLessOp.c* $(C_FILES_TEST) + +test_logical_ops: + g++-13 -I $(INCLUDEDIR) -I $(INCLUDEDIRTEST) -o $(TESTDIR)/Systemtests/LogicalOps/TestLogicalOps.out -w -fpermissive $(TESTDIR)/Systemtests/LogicalOps/TestLogicalOps.c* $(C_FILES_TEST) + +test_if_statement: + g++-13 -I $(INCLUDEDIR) -I $(INCLUDEDIRTEST) -o $(TESTDIR)/Systemtests/Conditions/TestIfStatement.out -w -fpermissive $(TESTDIR)/Systemtests/Conditions/TestIfStatement.c* $(C_FILES_TEST) + +test_else_statement: + g++-13 -I $(INCLUDEDIR) -I $(INCLUDEDIRTEST) -o $(TESTDIR)/Systemtests/Conditions/TestElseStatement.out -w -fpermissive $(TESTDIR)/Systemtests/Conditions/TestElseStatement.c* $(C_FILES_TEST) + +test_elif_statement: + g++-13 -I $(INCLUDEDIR) -I $(INCLUDEDIRTEST) -o $(TESTDIR)/Systemtests/Conditions/TestElifStatement.out -w -fpermissive $(TESTDIR)/Systemtests/Conditions/TestElifStatement.c* $(C_FILES_TEST) + +test_while_statement: + g++-13 -I $(INCLUDEDIR) -I $(INCLUDEDIRTEST) -o $(TESTDIR)/Systemtests/Conditions/TestWhileStatement.out -w -fpermissive $(TESTDIR)/Systemtests/Conditions/TestWhileStatement.c* $(C_FILES_TEST) + +test_cast_int: + g++-13 -I $(INCLUDEDIR) -I $(INCLUDEDIRTEST) -o $(TESTDIR)/Systemtests/BuiltInFunctions/TestCastInt.out -w -fpermissive $(TESTDIR)/Systemtests/BuiltInFunctions/TestCastInt.c* $(C_FILES_TEST) + +test_cast_string: + g++-13 -I $(INCLUDEDIR) -I $(INCLUDEDIRTEST) -o $(TESTDIR)/Systemtests/BuiltInFunctions/TestCastString.out -w -fpermissive $(TESTDIR)/Systemtests/BuiltInFunctions/TestCastString.c* $(C_FILES_TEST) + +test_id: + g++-13 -I $(INCLUDEDIR) -I $(INCLUDEDIRTEST) -o $(TESTDIR)/Systemtests/BuiltInFunctions/TestId.out -w -fpermissive $(TESTDIR)/Systemtests/BuiltInFunctions/TestId.c* $(C_FILES_TEST) + +test_print: + g++-13 -I $(INCLUDEDIR) -I $(INCLUDEDIRTEST) -o $(TESTDIR)/Systemtests/BuiltInFunctions/TestPrint.out -w -fpermissive $(TESTDIR)/Systemtests/BuiltInFunctions/TestPrint.c* $(C_FILES_TEST) + +test_type: + g++-13 -I $(INCLUDEDIR) -I $(INCLUDEDIRTEST) -o $(TESTDIR)/Systemtests/BuiltInFunctions/TestType.out -w -fpermissive $(TESTDIR)/Systemtests/BuiltInFunctions/TestType.c* $(C_FILES_TEST) + +test_function_params: + g++-13 -I $(INCLUDEDIR) -I $(INCLUDEDIRTEST) -o $(TESTDIR)/Systemtests/FunctionCalls/TestFunctionParams.out -w -fpermissive $(TESTDIR)/Systemtests/FunctionCalls/TestFunctionParams.c* $(C_FILES_TEST) + +test_function_params_throws: + g++-13 -I $(INCLUDEDIR) -I $(INCLUDEDIRTEST) -o $(TESTDIR)/Systemtests/FunctionCalls/TestFunctionParamsThrows.out -w -fpermissive $(TESTDIR)/Systemtests/FunctionCalls/TestFunctionParamsThrows.c* $(C_FILES_TEST) + +test_function_body: + g++-13 -I $(INCLUDEDIR) -I $(INCLUDEDIRTEST) -o $(TESTDIR)/Systemtests/FunctionCalls/TestFunctionBody.out -w -fpermissive $(TESTDIR)/Systemtests/FunctionCalls/TestFunctionBody.c* $(C_FILES_TEST) + +test_function_return: + g++-13 -I $(INCLUDEDIR) -I $(INCLUDEDIRTEST) -o $(TESTDIR)/Systemtests/FunctionCalls/TestFunctionReturn.out -w -fpermissive $(TESTDIR)/Systemtests/FunctionCalls/TestFunctionReturn.c* $(C_FILES_TEST) + +test_function_recursion: + g++-13 -I $(INCLUDEDIR) -I $(INCLUDEDIRTEST) -o $(TESTDIR)/Systemtests/FunctionCalls/TestFunctionRecursion.out -w -fpermissive $(TESTDIR)/Systemtests/FunctionCalls/TestFunctionRecursion.c* $(C_FILES_TEST) + +test_class_init: + g++-13 -I $(INCLUDEDIR) -I $(INCLUDEDIRTEST) -o $(TESTDIR)/Systemtests/Classes/TestClassInit.out -w -fpermissive $(TESTDIR)/Systemtests/Classes/TestClassInit.c* $(C_FILES_TEST) + +test_class_init_throws: + g++-13 -I $(INCLUDEDIR) -I $(INCLUDEDIRTEST) -o $(TESTDIR)/Systemtests/Classes/TestClassInitThrows.out -w -fpermissive $(TESTDIR)/Systemtests/Classes/TestClassInitThrows.c* $(C_FILES_TEST) + +test_class_members: + g++-13 -I $(INCLUDEDIR) -I $(INCLUDEDIRTEST) -o $(TESTDIR)/Systemtests/Classes/TestClassMembers.out -w -fpermissive $(TESTDIR)/Systemtests/Classes/TestClassMembers.c* $(C_FILES_TEST) + +test_class_inheritance: + g++-13 --version + g++-13 -I $(INCLUDEDIR) -I $(INCLUDEDIRTEST) -o $(TESTDIR)/Systemtests/Classes/TestClassInheritance.out -w -fpermissive $(TESTDIR)/Systemtests/Classes/TestClassInheritance.c* $(C_FILES_TEST) + +test_wuppie: + g++-13 -I $(INCLUDEDIR) -I $(INCLUDEDIRTEST) -o $(TESTDIR)/Systemtests/wuppie.out -w -fpermissive $(TESTDIR)/Systemtests/wuppie.c* $(C_FILES_TEST) + + +clean: + $(RM) -r $(TESTDIR)/*.out + $(RM) -r $(TESTDIR)/*/*/*.out diff --git a/c-runtime/test/Systemtests/wuppie.cpp b/c-runtime/test/Systemtests/wuppie.cpp new file mode 100644 index 0000000..09e0473 --- /dev/null +++ b/c-runtime/test/Systemtests/wuppie.cpp @@ -0,0 +1,46 @@ +#define CATCH_CONFIG_MAIN + +#include + +#include "catch.hpp" +#include "assert.h" +#include "mpy_aliases.h" +#include "mpy_obj.h" +#include "builtins-setup.h" +#include "function-args.h" +#include "literals/tuple.h" +#include "literals/int.h" +#include "literals/boolean.h" +#include "literals/str.h" +#include "type-hierarchy/object.h" +#include "type-hierarchy/type.h" +#include "test/test_helpers.h" + +/* +test_comparison_ops: + g++-13 --version + g++-13 -I $(INCLUDEDIR) -o $(TESTDIR)/Systemtests/ComparisonOps/TestComparisonOps.out -w -fpermissive $(TESTDIR)/Systemtests/ComparisonOps/TestComparisonOps.c* $(C_FILES) +*/ +int test(){ + __MPyObj *a; + __MPyObj *b; + + __mpy_builtins_setup(); + + if (__mpy_boolean_raw(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_int(0), "__bool__"), __mpy_obj_init_tuple(0), NULL))) { + __mpy_obj_ref_dec(__mpy_call(print, __mpy_tuple_assign(0, __mpy_obj_init_str_static("Somehow went here"), __mpy_obj_init_tuple(1)), NULL)); + }else if (__mpy_boolean_raw(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_int(1), "__bool__"), __mpy_obj_init_tuple(0), NULL))) { + __mpy_obj_ref_dec(__mpy_call(print, __mpy_tuple_assign(0, __mpy_obj_init_str_static("elif!"), __mpy_obj_init_tuple(1)), NULL)); + }else { + __mpy_obj_ref_dec(__mpy_call(print, __mpy_tuple_assign(0, __mpy_call(__mpy_obj_get_attr(__mpy_call(__mpy_obj_get_attr(__mpy_obj_init_int(123), "__sub__"), __mpy_tuple_assign(0, __mpy_obj_init_int(22), __mpy_obj_init_tuple(1)), NULL), "__lt__"), __mpy_tuple_assign(0, __mpy_obj_init_int(0), __mpy_obj_init_tuple(1)), NULL), __mpy_obj_init_tuple(1)), NULL)); + } + + + __mpy_builtins_cleanup(); + + return 0; +} + +TEST_CASE("wuppie"){ + CHECK(test() == 0); +} diff --git a/c-runtime/test/include/catch.hpp b/c-runtime/test/include/catch.hpp new file mode 100644 index 0000000..9b309bd --- /dev/null +++ b/c-runtime/test/include/catch.hpp @@ -0,0 +1,17976 @@ +/* + * Catch v2.13.10 + * Generated: 2022-10-16 11:01:23.452308 + * ---------------------------------------------------------- + * This file has been merged from multiple headers. Please don't edit it directly + * Copyright (c) 2022 Two Blue Cubes Ltd. All rights reserved. + * + * Distributed under the Boost Software License, Version 1.0. (See accompanying + * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + */ +#ifndef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED +#define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED +// start catch.hpp + + +#define CATCH_VERSION_MAJOR 2 +#define CATCH_VERSION_MINOR 13 +#define CATCH_VERSION_PATCH 10 + +#ifdef __clang__ +# pragma clang system_header +#elif defined __GNUC__ +# pragma GCC system_header +#endif + +// start catch_suppress_warnings.h + +#ifdef __clang__ +# ifdef __ICC // icpc defines the __clang__ macro +# pragma warning(push) +# pragma warning(disable: 161 1682) +# else // __ICC +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wpadded" +# pragma clang diagnostic ignored "-Wswitch-enum" +# pragma clang diagnostic ignored "-Wcovered-switch-default" +# endif +#elif defined __GNUC__ + // Because REQUIREs trigger GCC's -Wparentheses, and because still + // supported version of g++ have only buggy support for _Pragmas, + // Wparentheses have to be suppressed globally. +# pragma GCC diagnostic ignored "-Wparentheses" // See #674 for details + +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wunused-variable" +# pragma GCC diagnostic ignored "-Wpadded" +#endif +// end catch_suppress_warnings.h +#if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER) +# define CATCH_IMPL +# define CATCH_CONFIG_ALL_PARTS +#endif + +// In the impl file, we want to have access to all parts of the headers +// Can also be used to sanely support PCHs +#if defined(CATCH_CONFIG_ALL_PARTS) +# define CATCH_CONFIG_EXTERNAL_INTERFACES +# if defined(CATCH_CONFIG_DISABLE_MATCHERS) +# undef CATCH_CONFIG_DISABLE_MATCHERS +# endif +# if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER) +# define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER +# endif +#endif + +#if !defined(CATCH_CONFIG_IMPL_ONLY) +// start catch_platform.h + +// See e.g.: +// https://opensource.apple.com/source/CarbonHeaders/CarbonHeaders-18.1/TargetConditionals.h.auto.html +#ifdef __APPLE__ +# include +# if (defined(TARGET_OS_OSX) && TARGET_OS_OSX == 1) || \ + (defined(TARGET_OS_MAC) && TARGET_OS_MAC == 1) +# define CATCH_PLATFORM_MAC +# elif (defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE == 1) +# define CATCH_PLATFORM_IPHONE +# endif + +#elif defined(linux) || defined(__linux) || defined(__linux__) +# define CATCH_PLATFORM_LINUX + +#elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__) +# define CATCH_PLATFORM_WINDOWS +#endif + +// end catch_platform.h + +#ifdef CATCH_IMPL +# ifndef CLARA_CONFIG_MAIN +# define CLARA_CONFIG_MAIN_NOT_DEFINED +# define CLARA_CONFIG_MAIN +# endif +#endif + +// start catch_user_interfaces.h + +namespace Catch { + unsigned int rngSeed(); +} + +// end catch_user_interfaces.h +// start catch_tag_alias_autoregistrar.h + +// start catch_common.h + +// start catch_compiler_capabilities.h + +// Detect a number of compiler features - by compiler +// The following features are defined: +// +// CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported? +// CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported? +// CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported? +// CATCH_CONFIG_DISABLE_EXCEPTIONS : Are exceptions enabled? +// **************** +// Note to maintainers: if new toggles are added please document them +// in configuration.md, too +// **************** + +// In general each macro has a _NO_ form +// (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature. +// Many features, at point of detection, define an _INTERNAL_ macro, so they +// can be combined, en-mass, with the _NO_ forms later. + +#ifdef __cplusplus + +# if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L) +# define CATCH_CPP14_OR_GREATER +# endif + +# if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) +# define CATCH_CPP17_OR_GREATER +# endif + +#endif + +// Only GCC compiler should be used in this block, so other compilers trying to +// mask themselves as GCC should be ignored. +#if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) && !defined(__CUDACC__) && !defined(__LCC__) +# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic push" ) +# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic pop" ) + +# define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__) + +#endif + +#if defined(__clang__) + +# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic push" ) +# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic pop" ) + +// As of this writing, IBM XL's implementation of __builtin_constant_p has a bug +// which results in calls to destructors being emitted for each temporary, +// without a matching initialization. In practice, this can result in something +// like `std::string::~string` being called on an uninitialized value. +// +// For example, this code will likely segfault under IBM XL: +// ``` +// REQUIRE(std::string("12") + "34" == "1234") +// ``` +// +// Therefore, `CATCH_INTERNAL_IGNORE_BUT_WARN` is not implemented. +# if !defined(__ibmxl__) && !defined(__CUDACC__) +# define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__) /* NOLINT(cppcoreguidelines-pro-type-vararg, hicpp-vararg) */ +# endif + +# define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ + _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \ + _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"") + +# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ + _Pragma( "clang diagnostic ignored \"-Wparentheses\"" ) + +# define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \ + _Pragma( "clang diagnostic ignored \"-Wunused-variable\"" ) + +# define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ + _Pragma( "clang diagnostic ignored \"-Wgnu-zero-variadic-macro-arguments\"" ) + +# define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ + _Pragma( "clang diagnostic ignored \"-Wunused-template\"" ) + +#endif // __clang__ + +//////////////////////////////////////////////////////////////////////////////// +// Assume that non-Windows platforms support posix signals by default +#if !defined(CATCH_PLATFORM_WINDOWS) + #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS +#endif + +//////////////////////////////////////////////////////////////////////////////// +// We know some environments not to support full POSIX signals +#if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__) + #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS +#endif + +#ifdef __OS400__ +# define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS +# define CATCH_CONFIG_COLOUR_NONE +#endif + +//////////////////////////////////////////////////////////////////////////////// +// Android somehow still does not support std::to_string +#if defined(__ANDROID__) +# define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING +# define CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE +#endif + +//////////////////////////////////////////////////////////////////////////////// +// Not all Windows environments support SEH properly +#if defined(__MINGW32__) +# define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH +#endif + +//////////////////////////////////////////////////////////////////////////////// +// PS4 +#if defined(__ORBIS__) +# define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE +#endif + +//////////////////////////////////////////////////////////////////////////////// +// Cygwin +#ifdef __CYGWIN__ + +// Required for some versions of Cygwin to declare gettimeofday +// see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin +# define _BSD_SOURCE +// some versions of cygwin (most) do not support std::to_string. Use the libstd check. +// https://gcc.gnu.org/onlinedocs/gcc-4.8.2/libstdc++/api/a01053_source.html line 2812-2813 +# if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \ + && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF)) + +# define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING + +# endif +#endif // __CYGWIN__ + +//////////////////////////////////////////////////////////////////////////////// +// Visual C++ +#if defined(_MSC_VER) + +// Universal Windows platform does not support SEH +// Or console colours (or console at all...) +# if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) +# define CATCH_CONFIG_COLOUR_NONE +# else +# define CATCH_INTERNAL_CONFIG_WINDOWS_SEH +# endif + +# if !defined(__clang__) // Handle Clang masquerading for msvc + +// MSVC traditional preprocessor needs some workaround for __VA_ARGS__ +// _MSVC_TRADITIONAL == 0 means new conformant preprocessor +// _MSVC_TRADITIONAL == 1 means old traditional non-conformant preprocessor +# if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL) +# define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR +# endif // MSVC_TRADITIONAL + +// Only do this if we're not using clang on Windows, which uses `diagnostic push` & `diagnostic pop` +# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION __pragma( warning(push) ) +# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION __pragma( warning(pop) ) +# endif // __clang__ + +#endif // _MSC_VER + +#if defined(_REENTRANT) || defined(_MSC_VER) +// Enable async processing, as -pthread is specified or no additional linking is required +# define CATCH_INTERNAL_CONFIG_USE_ASYNC +#endif // _MSC_VER + +//////////////////////////////////////////////////////////////////////////////// +// Check if we are compiled with -fno-exceptions or equivalent +#if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND) +# define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED +#endif + +//////////////////////////////////////////////////////////////////////////////// +// DJGPP +#ifdef __DJGPP__ +# define CATCH_INTERNAL_CONFIG_NO_WCHAR +#endif // __DJGPP__ + +//////////////////////////////////////////////////////////////////////////////// +// Embarcadero C++Build +#if defined(__BORLANDC__) + #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN +#endif + +//////////////////////////////////////////////////////////////////////////////// + +// Use of __COUNTER__ is suppressed during code analysis in +// CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly +// handled by it. +// Otherwise all supported compilers support COUNTER macro, +// but user still might want to turn it off +#if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L ) + #define CATCH_INTERNAL_CONFIG_COUNTER +#endif + +//////////////////////////////////////////////////////////////////////////////// + +// RTX is a special version of Windows that is real time. +// This means that it is detected as Windows, but does not provide +// the same set of capabilities as real Windows does. +#if defined(UNDER_RTSS) || defined(RTX64_BUILD) + #define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH + #define CATCH_INTERNAL_CONFIG_NO_ASYNC + #define CATCH_CONFIG_COLOUR_NONE +#endif + +#if !defined(_GLIBCXX_USE_C99_MATH_TR1) +#define CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER +#endif + +// Various stdlib support checks that require __has_include +#if defined(__has_include) + // Check if string_view is available and usable + #if __has_include() && defined(CATCH_CPP17_OR_GREATER) + # define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW + #endif + + // Check if optional is available and usable + # if __has_include() && defined(CATCH_CPP17_OR_GREATER) + # define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL + # endif // __has_include() && defined(CATCH_CPP17_OR_GREATER) + + // Check if byte is available and usable + # if __has_include() && defined(CATCH_CPP17_OR_GREATER) + # include + # if defined(__cpp_lib_byte) && (__cpp_lib_byte > 0) + # define CATCH_INTERNAL_CONFIG_CPP17_BYTE + # endif + # endif // __has_include() && defined(CATCH_CPP17_OR_GREATER) + + // Check if variant is available and usable + # if __has_include() && defined(CATCH_CPP17_OR_GREATER) + # if defined(__clang__) && (__clang_major__ < 8) + // work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852 + // fix should be in clang 8, workaround in libstdc++ 8.2 + # include + # if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9) + # define CATCH_CONFIG_NO_CPP17_VARIANT + # else + # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT + # endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9) + # else + # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT + # endif // defined(__clang__) && (__clang_major__ < 8) + # endif // __has_include() && defined(CATCH_CPP17_OR_GREATER) +#endif // defined(__has_include) + +#if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER) +# define CATCH_CONFIG_COUNTER +#endif +#if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH) +# define CATCH_CONFIG_WINDOWS_SEH +#endif +// This is set by default, because we assume that unix compilers are posix-signal-compatible by default. +#if defined(CATCH_INTERNAL_CONFIG_POSIX_SIGNALS) && !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS) +# define CATCH_CONFIG_POSIX_SIGNALS +#endif +// This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions. +#if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR) +# define CATCH_CONFIG_WCHAR +#endif + +#if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING) +# define CATCH_CONFIG_CPP11_TO_STRING +#endif + +#if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL) +# define CATCH_CONFIG_CPP17_OPTIONAL +#endif + +#if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW) +# define CATCH_CONFIG_CPP17_STRING_VIEW +#endif + +#if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT) +# define CATCH_CONFIG_CPP17_VARIANT +#endif + +#if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) && !defined(CATCH_CONFIG_CPP17_BYTE) +# define CATCH_CONFIG_CPP17_BYTE +#endif + +#if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT) +# define CATCH_INTERNAL_CONFIG_NEW_CAPTURE +#endif + +#if defined(CATCH_INTERNAL_CONFIG_NEW_CAPTURE) && !defined(CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NEW_CAPTURE) +# define CATCH_CONFIG_NEW_CAPTURE +#endif + +#if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) +# define CATCH_CONFIG_DISABLE_EXCEPTIONS +#endif + +#if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN) +# define CATCH_CONFIG_POLYFILL_ISNAN +#endif + +#if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC) +# define CATCH_CONFIG_USE_ASYNC +#endif + +#if defined(CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_NO_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_ANDROID_LOGWRITE) +# define CATCH_CONFIG_ANDROID_LOGWRITE +#endif + +#if defined(CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_NO_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_GLOBAL_NEXTAFTER) +# define CATCH_CONFIG_GLOBAL_NEXTAFTER +#endif + +// Even if we do not think the compiler has that warning, we still have +// to provide a macro that can be used by the code. +#if !defined(CATCH_INTERNAL_START_WARNINGS_SUPPRESSION) +# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION +#endif +#if !defined(CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION) +# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION +#endif +#if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS) +# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS +#endif +#if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS) +# define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS +#endif +#if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS) +# define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS +#endif +#if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS) +# define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS +#endif + +// The goal of this macro is to avoid evaluation of the arguments, but +// still have the compiler warn on problems inside... +#if !defined(CATCH_INTERNAL_IGNORE_BUT_WARN) +# define CATCH_INTERNAL_IGNORE_BUT_WARN(...) +#endif + +#if defined(__APPLE__) && defined(__apple_build_version__) && (__clang_major__ < 10) +# undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS +#elif defined(__clang__) && (__clang_major__ < 5) +# undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS +#endif + +#if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS) +# define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS +#endif + +#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) +#define CATCH_TRY if ((true)) +#define CATCH_CATCH_ALL if ((false)) +#define CATCH_CATCH_ANON(type) if ((false)) +#else +#define CATCH_TRY try +#define CATCH_CATCH_ALL catch (...) +#define CATCH_CATCH_ANON(type) catch (type) +#endif + +#if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) +#define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR +#endif + +// end catch_compiler_capabilities.h +#define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line +#define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) +#ifdef CATCH_CONFIG_COUNTER +# define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ ) +#else +# define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ ) +#endif + +#include +#include +#include + +// We need a dummy global operator<< so we can bring it into Catch namespace later +struct Catch_global_namespace_dummy {}; +std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy); + +namespace Catch { + + struct CaseSensitive { enum Choice { + Yes, + No + }; }; + + class NonCopyable { + NonCopyable( NonCopyable const& ) = delete; + NonCopyable( NonCopyable && ) = delete; + NonCopyable& operator = ( NonCopyable const& ) = delete; + NonCopyable& operator = ( NonCopyable && ) = delete; + + protected: + NonCopyable(); + virtual ~NonCopyable(); + }; + + struct SourceLineInfo { + + SourceLineInfo() = delete; + SourceLineInfo( char const* _file, std::size_t _line ) noexcept + : file( _file ), + line( _line ) + {} + + SourceLineInfo( SourceLineInfo const& other ) = default; + SourceLineInfo& operator = ( SourceLineInfo const& ) = default; + SourceLineInfo( SourceLineInfo&& ) noexcept = default; + SourceLineInfo& operator = ( SourceLineInfo&& ) noexcept = default; + + bool empty() const noexcept { return file[0] == '\0'; } + bool operator == ( SourceLineInfo const& other ) const noexcept; + bool operator < ( SourceLineInfo const& other ) const noexcept; + + char const* file; + std::size_t line; + }; + + std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ); + + // Bring in operator<< from global namespace into Catch namespace + // This is necessary because the overload of operator<< above makes + // lookup stop at namespace Catch + using ::operator<<; + + // Use this in variadic streaming macros to allow + // >> +StreamEndStop + // as well as + // >> stuff +StreamEndStop + struct StreamEndStop { + std::string operator+() const; + }; + template + T const& operator + ( T const& value, StreamEndStop ) { + return value; + } +} + +#define CATCH_INTERNAL_LINEINFO \ + ::Catch::SourceLineInfo( __FILE__, static_cast( __LINE__ ) ) + +// end catch_common.h +namespace Catch { + + struct RegistrarForTagAliases { + RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo ); + }; + +} // end namespace Catch + +#define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \ + CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ + CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ + namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \ + CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION + +// end catch_tag_alias_autoregistrar.h +// start catch_test_registry.h + +// start catch_interfaces_testcase.h + +#include + +namespace Catch { + + class TestSpec; + + struct ITestInvoker { + virtual void invoke () const = 0; + virtual ~ITestInvoker(); + }; + + class TestCase; + struct IConfig; + + struct ITestCaseRegistry { + virtual ~ITestCaseRegistry(); + virtual std::vector const& getAllTests() const = 0; + virtual std::vector const& getAllTestsSorted( IConfig const& config ) const = 0; + }; + + bool isThrowSafe( TestCase const& testCase, IConfig const& config ); + bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ); + std::vector filterTests( std::vector const& testCases, TestSpec const& testSpec, IConfig const& config ); + std::vector const& getAllTestCasesSorted( IConfig const& config ); + +} + +// end catch_interfaces_testcase.h +// start catch_stringref.h + +#include +#include +#include +#include + +namespace Catch { + + /// A non-owning string class (similar to the forthcoming std::string_view) + /// Note that, because a StringRef may be a substring of another string, + /// it may not be null terminated. + class StringRef { + public: + using size_type = std::size_t; + using const_iterator = const char*; + + private: + static constexpr char const* const s_empty = ""; + + char const* m_start = s_empty; + size_type m_size = 0; + + public: // construction + constexpr StringRef() noexcept = default; + + StringRef( char const* rawChars ) noexcept; + + constexpr StringRef( char const* rawChars, size_type size ) noexcept + : m_start( rawChars ), + m_size( size ) + {} + + StringRef( std::string const& stdString ) noexcept + : m_start( stdString.c_str() ), + m_size( stdString.size() ) + {} + + explicit operator std::string() const { + return std::string(m_start, m_size); + } + + public: // operators + auto operator == ( StringRef const& other ) const noexcept -> bool; + auto operator != (StringRef const& other) const noexcept -> bool { + return !(*this == other); + } + + auto operator[] ( size_type index ) const noexcept -> char { + assert(index < m_size); + return m_start[index]; + } + + public: // named queries + constexpr auto empty() const noexcept -> bool { + return m_size == 0; + } + constexpr auto size() const noexcept -> size_type { + return m_size; + } + + // Returns the current start pointer. If the StringRef is not + // null-terminated, throws std::domain_exception + auto c_str() const -> char const*; + + public: // substrings and searches + // Returns a substring of [start, start + length). + // If start + length > size(), then the substring is [start, size()). + // If start > size(), then the substring is empty. + auto substr( size_type start, size_type length ) const noexcept -> StringRef; + + // Returns the current start pointer. May not be null-terminated. + auto data() const noexcept -> char const*; + + constexpr auto isNullTerminated() const noexcept -> bool { + return m_start[m_size] == '\0'; + } + + public: // iterators + constexpr const_iterator begin() const { return m_start; } + constexpr const_iterator end() const { return m_start + m_size; } + }; + + auto operator += ( std::string& lhs, StringRef const& sr ) -> std::string&; + auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&; + + constexpr auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef { + return StringRef( rawChars, size ); + } +} // namespace Catch + +constexpr auto operator "" _catch_sr( char const* rawChars, std::size_t size ) noexcept -> Catch::StringRef { + return Catch::StringRef( rawChars, size ); +} + +// end catch_stringref.h +// start catch_preprocessor.hpp + + +#define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__ +#define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__))) +#define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__))) +#define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__))) +#define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__))) +#define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__))) + +#ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR +#define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__ +// MSVC needs more evaluations +#define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__))) +#define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__)) +#else +#define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__) +#endif + +#define CATCH_REC_END(...) +#define CATCH_REC_OUT + +#define CATCH_EMPTY() +#define CATCH_DEFER(id) id CATCH_EMPTY() + +#define CATCH_REC_GET_END2() 0, CATCH_REC_END +#define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2 +#define CATCH_REC_GET_END(...) CATCH_REC_GET_END1 +#define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT +#define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0) +#define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next) + +#define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ ) +#define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ ) +#define CATCH_REC_LIST2(f, x, peek, ...) f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ ) + +#define CATCH_REC_LIST0_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ ) +#define CATCH_REC_LIST1_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0_UD) ) ( f, userdata, peek, __VA_ARGS__ ) +#define CATCH_REC_LIST2_UD(f, userdata, x, peek, ...) f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ ) + +// Applies the function macro `f` to each of the remaining parameters, inserts commas between the results, +// and passes userdata as the first parameter to each invocation, +// e.g. CATCH_REC_LIST_UD(f, x, a, b, c) evaluates to f(x, a), f(x, b), f(x, c) +#define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0)) + +#define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0)) + +#define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param) +#define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__ +#define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__ +#define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF +#define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__) +#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR +#define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__ +#define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) +#else +// MSVC is adding extra space and needs another indirection to expand INTERNAL_CATCH_NOINTERNAL_CATCH_DEF +#define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__) +#define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__ +#define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1) +#endif + +#define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__ +#define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name) + +#define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__) + +#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR +#define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) decltype(get_wrapper()) +#define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)) +#else +#define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) INTERNAL_CATCH_EXPAND_VARGS(decltype(get_wrapper())) +#define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))) +#endif + +#define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...)\ + CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,__VA_ARGS__) + +#define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0) +#define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1) +#define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2) +#define INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_0, _1, _2, _3) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_1, _2, _3) +#define INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_0, _1, _2, _3, _4) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_1, _2, _3, _4) +#define INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_0, _1, _2, _3, _4, _5) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_1, _2, _3, _4, _5) +#define INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_0, _1, _2, _3, _4, _5, _6) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_1, _2, _3, _4, _5, _6) +#define INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_0, _1, _2, _3, _4, _5, _6, _7) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_1, _2, _3, _4, _5, _6, _7) +#define INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_1, _2, _3, _4, _5, _6, _7, _8) +#define INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9) +#define INTERNAL_CATCH_REMOVE_PARENS_11_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10) + +#define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N + +#define INTERNAL_CATCH_TYPE_GEN\ + template struct TypeList {};\ + template\ + constexpr auto get_wrapper() noexcept -> TypeList { return {}; }\ + template class...> struct TemplateTypeList{};\ + template class...Cs>\ + constexpr auto get_wrapper() noexcept -> TemplateTypeList { return {}; }\ + template\ + struct append;\ + template\ + struct rewrap;\ + template class, typename...>\ + struct create;\ + template class, typename>\ + struct convert;\ + \ + template \ + struct append { using type = T; };\ + template< template class L1, typename...E1, template class L2, typename...E2, typename...Rest>\ + struct append, L2, Rest...> { using type = typename append, Rest...>::type; };\ + template< template class L1, typename...E1, typename...Rest>\ + struct append, TypeList, Rest...> { using type = L1; };\ + \ + template< template class Container, template class List, typename...elems>\ + struct rewrap, List> { using type = TypeList>; };\ + template< template class Container, template class List, class...Elems, typename...Elements>\ + struct rewrap, List, Elements...> { using type = typename append>, typename rewrap, Elements...>::type>::type; };\ + \ + template