diff --git a/eg/struct-equality.castile b/eg/struct-equality.castile new file mode 100644 index 0000000..c327c0a --- /dev/null +++ b/eg/struct-equality.castile @@ -0,0 +1,7 @@ +fun main() { + a = 40 as string|integer + b = 40 as string|integer + if a == b { + print("it is") + } +} diff --git a/src/castile/backends/c.py b/src/castile/backends/c.py index 28e95a4..af5dce1 100644 --- a/src/castile/backends/c.py +++ b/src/castile/backends/c.py @@ -73,6 +73,11 @@ return !strcmp(tag, tv->tag); } +int equal_tagged_value(struct tagged_value *tv1, struct tagged_value *tv2) +{ + return is_tag(tv1->tag, tv2) && tv1->value == tv2->value; +} + """ @@ -262,6 +267,12 @@ def compile(self, ast): self.write(', ') self.compile(ast.children[1]) self.write(')') + elif ast.value == '==' and isinstance(ast.children[0].type, Union): + self.write('equal_tagged_value(') + self.compile(ast.children[0]) + self.write(', ') + self.compile(ast.children[1]) + self.write(')') else: self.write('(') self.compile(ast.children[0]) diff --git a/src/castile/builtins.py b/src/castile/builtins.py index bc5bcd7..193ba2a 100644 --- a/src/castile/builtins.py +++ b/src/castile/builtins.py @@ -11,6 +11,9 @@ def __init__(self, tag, value): def __repr__(self): return '(%r, %r)' % (self.tag, self.value) + def __eq__(self, other): + return self.tag == other.tag and self.value == other.value + def builtin_len(s): return len(s) diff --git a/tests/Castile.md b/tests/Castile.md index decae59..9067f26 100644 --- a/tests/Castile.md +++ b/tests/Castile.md @@ -601,16 +601,16 @@ Equality cannot be checked between two values of different types. | } ? mismatch -Equality can be checked between unions. (TODO) - - /| fun main() { - /| a = 40 as string|integer - /| b = 40 as string|integer - /| if a == b { - /| print("it is") - /| } - /| } - /= ok +Equality can be checked between unions. + + | fun main() { + | a = 40 as string|integer + | b = 40 as string|integer + | if a == b { + | print("it is") + | } + | } + = it is | fun main() { | a = 40 as string|integer