从 c 代码获取人类可读的 AST
Clang 之前通过 -emit-asm 标志提供了此功能,该标志已被删除。那么问题就来了:目前有没有一种简单的方法来完成这个任务?
解决方案中有两个实例,一个是简单的,一个是具有挑战性的(C 的“最令人烦恼的解析”)。以下是来自 http://talkbinary.com/programming/c/fibonacci-in-c/ 的斐波那契程序示例:
int fib(int n) { if ( n == 0 || n == 1 ) return n; int fib1 = 0; int fib2 = 1; int fib = 0; for ( int i = 2; i < n; i++ ) { fib = fib1 + fib2; fib1 = fib2; fib2 = fib; } return fib; }
以此作为输入,DMS 软件重组工具包(带有完整的 C 11/17 解析器)生成此 AST:
(translation_unit (function_definition (function_head (simple_type_specifier ('int' 'int') ) (noptr_declarator (IDENTIFIER 'fib') ('(' (parameter_declaration (simple_type_specifier ('int' 'int') ) (IDENTIFIER 'n') ) ) (function_qualifiers) ) ) (compound_statement ('{' (statement_seq (statement_seq (statement_seq (statement_seq (selection_statement ('if' ('(' (logical_or_expression (equality_expression (IDENTIFIER 'n') ('==' 'int') (INT_LITERAL '0') ) ('||' '||') (equality_expression (IDENTIFIER 'n') ('==' 'int') (INT_LITERAL '1') ) ) ) (jump_statement ('return' (IDENTIFIER 'n') (';' 'int') ) ) ) ) (simple_declaration (simple_type_specifier ('int' 'int') ) (init_declarator (IDENTIFIER 'fib1') (initializer ('=' 'int') (INT_LITERAL '0') ) ) (';' 'int') ) ) (simple_declaration (simple_type_specifier ('int' 'int') ) (init_declarator (IDENTIFIER 'fib2') (initializer ('=' 'int') (INT_LITERAL '1') ) ) (';' 'int') ) ) (simple_declaration (simple_type_specifier ('int' 'int') ) (init_declarator (IDENTIFIER 'fib') (initializer ('=' 'int') (INT_LITERAL '0') ) ) (';' 'int') ) ) (iteration_statement ('for' ('(' (simple_declaration (simple_type_specifier ('int' 'int') ) (init_declarator (IDENTIFIER 'i') (initializer ('=' 'int') (INT_LITERAL '2') ) ) (';' 'int') ) (relational_expression (IDENTIFIER 'i') ('<' '<') (IDENTIFIER 'n') ) (';' 'int') (postfix_expression (IDENTIFIER 'i') ('++' 'inc') ) ) (compound_statement ('{' (statement_seq (statement_seq (expression_statement (assignment_expression (IDENTIFIER 'fib') ('=' 'int') (additive_expression (IDENTIFIER 'fib1') ('+') (IDENTIFIER 'fib2') ) ) (';' 'int') ) ) (expression_statement (assignment_expression (IDENTIFIER 'fib1') ('=' 'int') (IDENTIFIER 'fib2') ) (';' 'int') ) ) (expression_statement (assignment_expression (IDENTIFIER 'fib2') ('=' 'int') (IDENTIFIER 'fib') ) (';' 'int') ) ) ) ) ) (jump_statement ('return' (IDENTIFIER 'fib') (';' 'int') ) ) ) ) ) )
以上是如何从 C 代码中轻松获得人类可读的抽象语法树 (AST)?的详细内容。更多信息请关注PHP中文网其他相关文章!