浏览代码

Merge pull request #18 from mtardy/type-switch

Add TYPESIG and CASE macros to switch between types combinations more elegantly
pull/19/head
piumarta 4 年前
committed by GitHub
父节点
当前提交
11dd4554a0
找不到此签名对应的密钥 GPG 密钥 ID: 4AEE18F83AFDEB23
共有 2 个文件被更改,包括 29 次插入16 次删除
  1. +2
    -0
      object.c
  2. +27
    -16
      parse.leg

+ 2
- 0
object.c 查看文件

@ -77,6 +77,8 @@ typedef enum {
Map Map
} type_t; } type_t;
#define NTYPES (Map + 1)
union object; union object;
typedef union object *oop; typedef union object *oop;

+ 27
- 16
parse.leg 查看文件

@ -989,32 +989,43 @@ void runtimeError(char *msg)
exit(1); exit(1);
} }
#define TYPESIG(L, R) L*NTYPES+R
#define CASE(L, R) case TYPESIG(L, R)
oop addOperation(oop ast, oop lhs, oop rhs) oop addOperation(oop ast, oop lhs, oop rhs)
{ {
if (getType(lhs) == Integer && getType(rhs) == Integer) {
return makeInteger(getInteger(lhs) + getInteger(rhs));
} else if (getType(lhs) == String && getType(rhs) == String) {
return string_concat(lhs, rhs);
} else {
runtimeError("addition between two incompatible types");
assert(0); // to prevent: control may reach end of non-void function
switch (TYPESIG(getType(lhs), getType(rhs))) {
CASE(Integer, Integer): {
return makeInteger(getInteger(lhs) + getInteger(rhs));
}
CASE(String, String): {
return string_concat(lhs, rhs);
}
} }
runtimeError("addition between two incompatible types");
assert(0); // to prevent: control may reach end of non-void function
} }
oop mulOperation(oop ast, oop lhs, oop rhs) oop mulOperation(oop ast, oop lhs, oop rhs)
{ {
if (getType(lhs) == Integer && getType(rhs) == Integer) {
return makeInteger(getInteger(lhs) * getInteger(rhs));
} else if (getType(lhs) == String && getType(rhs) == Integer) {
return string_mul(lhs, rhs);
} else if (getType(lhs) == Integer && getType(rhs) == String) {
return string_mul(rhs, lhs);
} else {
runtimeError("multiplication between two incompatible types");
assert(0);
switch (TYPESIG(getType(lhs), getType(rhs))) {
CASE(Integer, Integer): {
return makeInteger(getInteger(lhs) * getInteger(rhs));
}
CASE(String, Integer): {
return string_mul(lhs, rhs);
}
CASE(Integer, String): {
return string_mul(rhs, lhs);
}
} }
runtimeError("multiplication between two incompatible types");
assert(0);
} }
#undef TYPESIG
#undef CASE
oop expandUnquotes(oop scope, oop obj) oop expandUnquotes(oop scope, oop obj)
{ {
obj = clone(obj); obj = clone(obj);

正在加载...
取消
保存