为什么Clang将显式转换解释为隐式转换?

时间:2021-12-21 03:43:28

I have recently been working with Clang, and this little curiosity always occurs when an explicit cast is parsed.

我最近一直在和Clang一起工作,当解析一个显式的强制转换时,总会出现这种小小的好奇心。

To explicit my point, here is some basic code :

为了明确我的观点,这里有一些基本代码:

int main(){
    int my_int; 
    float my_float; 

    my_int = (int) my_float; 
    return 0; 
} 

Of course you would expect my_int = (int) my_float; to be parsed as a CStyleCastExpr, with a CastKind of CK_FloatingToIntegral, but it is not the case, and, in fact, the nature of the cast is stored inside an ImplicitCastExpr while the CStyleCastExpr holds a NoOp nature.

当然你会期望my_int =(int)my_float;要被解析为CStyleCastExpr,其CastKind为CK_FloatingToIntegral,但事实并非如此,事实上,当CStyleCastExpr具有NoOp特性时,强制转换的性质存储在ImplicitCastExpr中。

Here is the matching AST-dump for this code :

以下是此代码的匹配AST转储:

|-DeclStmt 0x2eb3528 <line:3:1, col:11>
| `-VarDecl 0x2eb34d0 <col:1, col:5> my_int 'int'
|-DeclStmt 0x2eb35a8 <line:4:1, col:15>
| `-VarDecl 0x2eb3550 <col:1, col:7> my_float 'float'
|-BinaryOperator 0x2eb3678 <line:5:1, col:16> 'int' lvalue '='
| |-DeclRefExpr 0x2eb35c0 <col:1> 'int' lvalue Var 0x2eb34d0 'my_int' 'int'
| `-CStyleCastExpr 0x2eb3650 <col:10, col:16> 'int' <NoOp>
|   `-ImplicitCastExpr 0x2eb3638 <col:16> 'int' <FloatingToIntegral>
|     `-ImplicitCastExpr 0x2eb3620 <col:16> 'float' <LValueToRValue>
|       `-DeclRefExpr 0x2eb35e8 <col:16> 'float' lvalue Var 0x2eb3550 'my_float' 'float'
`-ReturnStmt 0x2eb36c0 <line:6:1, col:8>
  `-IntegerLiteral 0x2eb36a0 <col:8> 'int' 0

It seems a little bit confusing since an ImplicitCastExpr should, for me, only be recognized when some unexpected cast occurs (See code below).

这看起来有点令人困惑,因为对于我来说,只有在发生一些意外的强制转换时才能识别出ImplicitCastExpr(参见下面的代码)。

int main(){
    int my_int;
    float my_float; 

    // implicit cast from float to int
    my_int = my_float;
    return 0; 
}

Would you have some explanation for this ?

你能解释一下吗?

1 个解决方案

#1


3  

This seems to be a side effect coming from clang's implementation :

这似乎是来自clang实现的副作用:

http://comments.gmane.org/gmane.comp.compilers.clang.devel/17369

The source code file generating the cast nodes is :

生成强制转换节点的源代码文件是:

https://github.com/llvm-mirror/clang/blob/master/lib/Sema/SemaCast.cpp

#1


3  

This seems to be a side effect coming from clang's implementation :

这似乎是来自clang实现的副作用:

http://comments.gmane.org/gmane.comp.compilers.clang.devel/17369

The source code file generating the cast nodes is :

生成强制转换节点的源代码文件是:

https://github.com/llvm-mirror/clang/blob/master/lib/Sema/SemaCast.cpp