Compiler construction 编译器中基本类型的自动类型转换的好算法是什么?
我正在开发一个简单的编译器,并希望以适当的方式实现自动类型转换。我拥有的类型有byte、int、uint16\u t、uint64\u t、int16\u t、float、double等。编译器应该检查类型,并确定某个类型的值是否可以用作另一个类型 例如,可以毫无问题地将int16_t值用作int32_t值,因为不会丢失精度。在预期为int16的位置使用int32_t值会引发警告或错误 到目前为止,我掌握的代码如下:Compiler construction 编译器中基本类型的自动类型转换的好算法是什么?,compiler-construction,Compiler Construction,我正在开发一个简单的编译器,并希望以适当的方式实现自动类型转换。我拥有的类型有byte、int、uint16\u t、uint64\u t、int16\u t、float、double等。编译器应该检查类型,并确定某个类型的值是否可以用作另一个类型 例如,可以毫无问题地将int16_t值用作int32_t值,因为不会丢失精度。在预期为int16的位置使用int32_t值会引发警告或错误 到目前为止,我掌握的代码如下: def do_coerce(self, expr, typ): """
def do_coerce(self, expr, typ):
""" Try to convert expression into the given type.
expr: the expression value with a certain type
typ: the type that it must be
Raises an error is the conversion cannot be done.
"""
if self.context.equal_types(expr.typ, typ):
# no cast required
pass
elif isinstance(expr.typ, ast.PointerType) and \
isinstance(typ, ast.PointerType):
# Pointers are pointers, no matter the pointed data.
expr = ast.TypeCast(typ, expr, expr.loc)
elif self.context.equal_types('int', expr.typ) and \
isinstance(typ, ast.PointerType):
expr = ast.TypeCast(typ, expr, expr.loc)
elif self.context.equal_types('int', expr.typ) and \
self.context.equal_types('byte', typ):
expr = ast.TypeCast(typ, expr, expr.loc)
elif self.context.equal_types('int', expr.typ) and \
self.context.equal_types('float', typ):
expr = ast.TypeCast(typ, expr, expr.loc)
elif self.context.equal_types('int', expr.typ) and \
self.context.equal_types('double', typ):
expr = ast.TypeCast(typ, expr, expr.loc)
elif self.context.equal_types('double', expr.typ) and \
self.context.equal_types('float', typ):
expr = ast.TypeCast(typ, expr, expr.loc)
elif self.context.equal_types('float', expr.typ) and \
self.context.equal_types('double', typ):
expr = ast.TypeCast(typ, expr, expr.loc)
elif self.context.equal_types('byte', expr.typ) and \
self.context.equal_types('int', typ):
expr = ast.TypeCast(typ, expr, expr.loc)
else:
raise SemanticError(
"Cannot use '{}' as '{}'".format(expr.typ, typ), expr.loc)
self.check_expr(expr)
return expr
这段代码所做的是检查“源”类型和“目标”类型,如果它们属于某些类型,则执行自动强制转换,否则将引发错误。代码可以工作,但我想添加更多类型的变体,我预测if-else树将变得非常大
我在谷歌上搜索了一个好的解决方案,并试图阅读clang、gcc和C#编译器的源代码,但我找不到解决这个问题的源代码
有没有关于如何解决这个问题的想法,或者是指向实现这个问题的源代码的指针?简单!从最窄到最宽的索引类型。例如:
byte = 0;
int = 1;
float = 2;
double = 3;
那么你所要做的就是比较这两者:
if (from <= to)
{
// This is a legal cast, no loss of precision
}
else
{
// Error, narrowing!
}
if(fromSimple!索引类型从最窄到最宽。例如:
byte = 0;
int = 1;
float = 2;
double = 3;
那么你所要做的就是比较这两者:
if (from <= to)
{
// This is a legal cast, no loss of precision
}
else
{
// Error, narrowing!
}
if(来自酷!谢谢提示!酷!谢谢提示!