2016-10-22 2 views
1

私は単純なコンパイラを開発しており、適切な方法で自動型変換を実装したいと考えています。私が持っている型は、例えばbyte、int、uint16_t、uint64_t、int16_t、float、doubleなどです。コンパイラは型をチェックし、ある型の値を別の型として使用できるかどうかを判断する必要があります。コンパイラの基本型の自動型変換のための良いアルゴリズムとは何ですか?

たとえば、精度が失われないため、int16_t値はint32_t値として問題なく使用できます。 int16_t値を使用してint16_tを使用すると、警告またはエラーが発生します。

私がこれまで持っているコードは以下の通りです:

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#コンパイラのソースコードを読み込もうとしましたが、この問題を処理するソースコードが見つかりませんでした。

この問題の解決方法やこれが実装されているソースへのポインタはありますか?

答えて

0

シンプル!最も狭いものから広いものへのインデックスタイプ。たとえば:

byte = 0; 
int = 1; 
float = 2; 
double = 3; 

は次にあなたがしなければならないすべては、二つを比較することです:

if (from <= to) 
{ 
    // This is a legal cast, no loss of precision 
} 
else 
{ 
    // Error, narrowing! 
} 

私は非常にthis本を示唆しています。

+0

Cool!ヒントをありがとう! – Windel

関連する問題