use crate::ast_types::*;
use clang_sys::*;
use std::ffi::CStr;
use std::ptr;
use super::types::convert_type;
use super::statements::{
extract_var_decl, extract_return_stmt, extract_if_stmt, extract_for_stmt,
extract_while_stmt, extract_switch_stmt, extract_inc_dec_stmt,
extract_assignment_stmt,
};
pub(crate) fn try_extract_expression(cursor: CXCursor) -> Option<Expression> {
let kind = unsafe { clang_getCursorKind(cursor) };
match kind {
CXCursor_IntegerLiteral => extract_int_literal(cursor),
107 => extract_float_literal(cursor), CXCursor_StringLiteral => extract_string_literal(cursor),
110 => extract_char_literal(cursor), CXCursor_DeclRefExpr => extract_variable_ref(cursor),
CXCursor_BinaryOperator => extract_binary_op(cursor),
CXCursor_CallExpr => extract_function_call(cursor),
CXCursor_UnaryOperator => extract_unary_op(cursor),
CXCursor_ArraySubscriptExpr => extract_array_index(cursor),
CXCursor_MemberRefExpr => extract_field_access(cursor),
116 => extract_conditional_op(cursor), 117 => extract_cast(cursor), 118 => extract_compound_literal(cursor), 111 => {
let mut result: Option<Expression> = None;
let result_ptr = &mut result as *mut Option<Expression>;
unsafe {
clang_visitChildren(cursor, visit_variable_initializer, result_ptr as CXClientData);
}
result
}
CXCursor_UnexposedExpr => {
let mut result: Option<Expression> = None;
let result_ptr = &mut result as *mut Option<Expression>;
unsafe {
clang_visitChildren(cursor, visit_variable_initializer, result_ptr as CXClientData);
}
result
}
_ => None,
}
}
pub(crate) extern "C" fn visit_variable_initializer(
cursor: CXCursor,
_parent: CXCursor,
client_data: CXClientData,
) -> CXChildVisitResult {
let initializer = unsafe { &mut *(client_data as *mut Option<Expression>) };
if let Some(expr) = try_extract_expression(cursor) {
*initializer = Some(expr);
return CXChildVisit_Break;
}
CXChildVisit_Continue
}
pub(crate) fn extract_statement(cursor: CXCursor) -> Option<Statement> {
let kind = unsafe { clang_getCursorKind(cursor) };
match kind {
CXCursor_ReturnStmt => extract_return_stmt(cursor),
CXCursor_VarDecl => extract_var_decl(cursor),
CXCursor_IfStmt => extract_if_stmt(cursor),
CXCursor_ForStmt => extract_for_stmt(cursor),
CXCursor_WhileStmt => extract_while_stmt(cursor),
CXCursor_BreakStmt => Some(Statement::Break),
CXCursor_ContinueStmt => Some(Statement::Continue),
CXCursor_UnaryOperator => extract_inc_dec_stmt(cursor),
CXCursor_BinaryOperator => extract_assignment_stmt(cursor),
CXCursor_CallExpr => {
if let Some(Expression::FunctionCall { function, arguments }) =
extract_function_call(cursor)
{
return Some(Statement::FunctionCall { function, arguments });
}
None
}
_ => None,
}
}
pub(crate) fn extract_expression_from_cursor(cursor: CXCursor) -> Option<Expression> {
let kind = unsafe { clang_getCursorKind(cursor) };
match kind {
CXCursor_BinaryOperator => extract_binary_op(cursor),
CXCursor_IntegerLiteral => extract_int_literal(cursor),
107 => extract_float_literal(cursor), 110 => extract_char_literal(cursor), CXCursor_DeclRefExpr => extract_variable_ref(cursor),
CXCursor_CallExpr => extract_function_call(cursor),
CXCursor_UnaryOperator => extract_unary_op(cursor),
_ => {
let mut expr: Option<Expression> = None;
let expr_ptr = &mut expr as *mut Option<Expression>;
unsafe {
clang_visitChildren(cursor, visit_expression, expr_ptr as CXClientData);
}
expr
}
}
}
pub(crate) fn extract_single_statement(cursor: CXCursor) -> Option<Statement> {
let kind = unsafe { clang_getCursorKind(cursor) };
match kind {
CXCursor_IfStmt => extract_if_stmt(cursor),
CXCursor_ForStmt => extract_for_stmt(cursor),
CXCursor_WhileStmt => extract_while_stmt(cursor),
CXCursor_ReturnStmt => extract_return_stmt(cursor),
CXCursor_SwitchStmt => extract_switch_stmt(cursor),
CXCursor_UnaryOperator => extract_inc_dec_stmt(cursor),
CXCursor_BinaryOperator => extract_assignment_stmt(cursor),
CXCursor_CallExpr => {
if let Some(Expression::FunctionCall { function, arguments }) =
extract_function_call(cursor)
{
Some(Statement::FunctionCall { function, arguments })
} else {
None
}
}
CXCursor_BreakStmt => Some(Statement::Break),
CXCursor_ContinueStmt => Some(Statement::Continue),
CXCursor_DoStmt | CXCursor_NullStmt => None, _ => None,
}
}
pub(crate) extern "C" fn visit_expression(
cursor: CXCursor,
_parent: CXCursor,
client_data: CXClientData,
) -> CXChildVisitResult {
let expr_opt = unsafe { &mut *(client_data as *mut Option<Expression>) };
let kind = unsafe { clang_getCursorKind(cursor) };
match kind {
CXCursor_IntegerLiteral => {
if let Some(expr) = extract_int_literal(cursor) {
*expr_opt = Some(expr);
}
CXChildVisit_Continue
}
107 => {
if let Some(expr) = extract_float_literal(cursor) {
*expr_opt = Some(expr);
}
CXChildVisit_Continue
}
CXCursor_StringLiteral => {
if let Some(expr) = extract_string_literal(cursor) {
*expr_opt = Some(expr);
}
CXChildVisit_Continue
}
110 => {
if let Some(expr) = extract_char_literal(cursor) {
*expr_opt = Some(expr);
}
CXChildVisit_Continue
}
CXCursor_DeclRefExpr => {
if let Some(expr) = extract_variable_ref(cursor) {
*expr_opt = Some(expr);
}
CXChildVisit_Continue
}
CXCursor_BinaryOperator => {
if let Some(expr) = extract_binary_op(cursor) {
*expr_opt = Some(expr);
}
CXChildVisit_Continue
}
CXCursor_CallExpr => {
if let Some(expr) = extract_function_call(cursor) {
*expr_opt = Some(expr);
}
CXChildVisit_Continue
}
CXCursor_UnaryOperator => {
if let Some(expr) = extract_unary_op(cursor) {
*expr_opt = Some(expr);
}
CXChildVisit_Continue
}
CXCursor_ArraySubscriptExpr => {
if let Some(expr) = extract_array_index(cursor) {
*expr_opt = Some(expr);
}
CXChildVisit_Continue
}
CXCursor_MemberRefExpr => {
if let Some(expr) = extract_field_access(cursor) {
*expr_opt = Some(expr);
}
CXChildVisit_Continue
}
116 => {
if let Some(expr) = extract_conditional_op(cursor) {
*expr_opt = Some(expr);
}
CXChildVisit_Continue
}
117 => {
if let Some(expr) = extract_cast(cursor) {
*expr_opt = Some(expr);
}
CXChildVisit_Continue
}
132 => {
*expr_opt = Some(Expression::Variable("self".to_string()));
CXChildVisit_Continue
}
134 => {
if let Some(expr) = extract_cxx_new(cursor) {
*expr_opt = Some(expr);
}
CXChildVisit_Continue
}
135 => {
if let Some(expr) = extract_cxx_delete(cursor) {
*expr_opt = Some(expr);
}
CXChildVisit_Continue
}
130 => {
if let Some(expr) = extract_cxx_bool_literal(cursor) {
*expr_opt = Some(expr);
}
CXChildVisit_Continue
}
131 => {
*expr_opt = Some(Expression::NullLiteral);
CXChildVisit_Continue
}
CXCursor_UnexposedExpr => {
CXChildVisit_Recurse
}
CXCursor_ParenExpr => {
CXChildVisit_Recurse
}
136 => {
if let Some(expr) = extract_sizeof(cursor) {
*expr_opt = Some(expr);
CXChildVisit_Continue
} else {
CXChildVisit_Recurse
}
}
119 => {
if let Some(expr) = extract_init_list(cursor) {
*expr_opt = Some(expr);
}
CXChildVisit_Continue
}
_ => CXChildVisit_Recurse,
}
}
pub(crate) fn extract_int_literal(cursor: CXCursor) -> Option<Expression> {
let extent = unsafe { clang_getCursorExtent(cursor) };
let tu = unsafe {
let loc = clang_getCursorLocation(cursor);
let mut file = ptr::null_mut();
let mut line = 0;
let mut column = 0;
let mut offset = 0;
clang_getFileLocation(loc, &mut file, &mut line, &mut column, &mut offset);
clang_Cursor_getTranslationUnit(cursor)
};
if tu.is_null() {
return Some(Expression::IntLiteral(0));
}
let mut tokens = ptr::null_mut();
let mut num_tokens = 0;
unsafe {
clang_tokenize(tu, extent, &mut tokens, &mut num_tokens);
}
let mut value = 0;
if num_tokens > 0 {
unsafe {
let token_cxstring = clang_getTokenSpelling(tu, *tokens);
let c_str = CStr::from_ptr(clang_getCString(token_cxstring));
if let Ok(token_str) = c_str.to_str() {
value = token_str.parse().unwrap_or(0);
}
clang_disposeString(token_cxstring);
clang_disposeTokens(tu, tokens, num_tokens);
}
} else {
unsafe {
let eval_result = clang_Cursor_Evaluate(cursor);
if !eval_result.is_null() {
value = clang_EvalResult_getAsInt(eval_result);
clang_EvalResult_dispose(eval_result);
}
}
}
Some(Expression::IntLiteral(value))
}
pub(crate) fn extract_float_literal(cursor: CXCursor) -> Option<Expression> {
let extent = unsafe { clang_getCursorExtent(cursor) };
let tu = unsafe { clang_Cursor_getTranslationUnit(cursor) };
if tu.is_null() {
return Some(Expression::FloatLiteral("0.0".to_string()));
}
let mut tokens = ptr::null_mut();
let mut num_tokens = 0;
unsafe {
clang_tokenize(tu, extent, &mut tokens, &mut num_tokens);
}
let mut value = "0.0".to_string();
if num_tokens > 0 {
unsafe {
let token_cxstring = clang_getTokenSpelling(tu, *tokens);
let c_str = CStr::from_ptr(clang_getCString(token_cxstring));
if let Ok(token_str) = c_str.to_str() {
value = token_str.to_string();
}
clang_disposeString(token_cxstring);
clang_disposeTokens(tu, tokens, num_tokens);
}
} else {
unsafe {
let eval_result = clang_Cursor_Evaluate(cursor);
if !eval_result.is_null() {
let float_val = clang_EvalResult_getAsDouble(eval_result);
value = format!("{}", float_val);
clang_EvalResult_dispose(eval_result);
}
}
}
Some(Expression::FloatLiteral(value))
}
pub(crate) fn extract_string_literal(cursor: CXCursor) -> Option<Expression> {
let extent = unsafe { clang_getCursorExtent(cursor) };
let tu = unsafe { clang_Cursor_getTranslationUnit(cursor) };
if tu.is_null() {
return Some(Expression::StringLiteral(String::new()));
}
let mut tokens = ptr::null_mut();
let mut num_tokens = 0;
unsafe {
clang_tokenize(tu, extent, &mut tokens, &mut num_tokens);
}
let mut value = String::new();
if num_tokens > 0 {
unsafe {
let token_cxstring = clang_getTokenSpelling(tu, *tokens);
let c_str = CStr::from_ptr(clang_getCString(token_cxstring));
if let Ok(token_str) = c_str.to_str() {
value = token_str.trim_matches('"').to_string();
}
clang_disposeString(token_cxstring);
clang_disposeTokens(tu, tokens, num_tokens);
}
}
Some(Expression::StringLiteral(value))
}
pub(crate) fn extract_char_literal(cursor: CXCursor) -> Option<Expression> {
let extent = unsafe { clang_getCursorExtent(cursor) };
let tu = unsafe { clang_Cursor_getTranslationUnit(cursor) };
if tu.is_null() {
return Some(Expression::CharLiteral(0));
}
let mut tokens = ptr::null_mut();
let mut num_tokens = 0;
unsafe {
clang_tokenize(tu, extent, &mut tokens, &mut num_tokens);
}
let mut value: i8 = 0;
if num_tokens > 0 {
unsafe {
let token_cxstring = clang_getTokenSpelling(tu, *tokens);
let c_str = CStr::from_ptr(clang_getCString(token_cxstring));
if let Ok(token_str) = c_str.to_str() {
let inner = token_str.trim_matches('\'');
value = parse_char_literal(inner);
}
clang_disposeString(token_cxstring);
clang_disposeTokens(tu, tokens, num_tokens);
}
}
Some(Expression::CharLiteral(value))
}
#[allow(clippy::disallowed_methods)] pub(crate) fn parse_char_literal(s: &str) -> i8 {
if s.is_empty() {
return 0;
}
let mut chars = s.chars();
let first = chars.next().unwrap();
if first == '\\' {
match chars.next() {
Some('0') => 0, Some('n') => b'\n' as i8,
Some('t') => b'\t' as i8,
Some('r') => b'\r' as i8,
Some('\\') => b'\\' as i8,
Some('\'') => b'\'' as i8,
Some('"') => b'"' as i8,
Some('a') => 7, Some('b') => 8, Some('f') => 12, Some('v') => 11, Some('x') => {
let hex: String = chars.take(2).collect();
i8::from_str_radix(&hex, 16).unwrap_or(0)
}
Some(c) if c.is_ascii_digit() => {
let mut octal = String::new();
octal.push(c);
for _ in 0..2 {
if let Some(d) = chars.next() {
if d.is_ascii_digit() && d < '8' {
octal.push(d);
} else {
break;
}
}
}
i8::from_str_radix(&octal, 8).unwrap_or(0)
}
_ => first as i8,
}
} else {
first as i8
}
}
pub(crate) fn extract_variable_ref(cursor: CXCursor) -> Option<Expression> {
let name_cxstring = unsafe { clang_getCursorSpelling(cursor) };
let name = unsafe {
let c_str = CStr::from_ptr(clang_getCString(name_cxstring));
let var_name = c_str.to_string_lossy().into_owned();
clang_disposeString(name_cxstring);
var_name
};
Some(Expression::Variable(name))
}
pub(crate) fn extract_binary_op(cursor: CXCursor) -> Option<Expression> {
let op = extract_binary_operator(cursor)?;
let mut operands: Vec<Expression> = Vec::new();
let operands_ptr = &mut operands as *mut Vec<Expression>;
unsafe {
clang_visitChildren(cursor, visit_binary_operand, operands_ptr as CXClientData);
}
if operands.len() != 2 {
return None;
}
Some(Expression::BinaryOp {
op,
left: Box::new(operands[0].clone()),
right: Box::new(operands[1].clone()),
})
}
pub(crate) extern "C" fn visit_binary_operand(
cursor: CXCursor,
_parent: CXCursor,
client_data: CXClientData,
) -> CXChildVisitResult {
let operands = unsafe { &mut *(client_data as *mut Vec<Expression>) };
let kind = unsafe { clang_getCursorKind(cursor) };
match kind {
CXCursor_IntegerLiteral => {
if let Some(expr) = extract_int_literal(cursor) {
operands.push(expr);
}
CXChildVisit_Continue
}
107 => {
if let Some(expr) = extract_float_literal(cursor) {
operands.push(expr);
}
CXChildVisit_Continue
}
CXCursor_StringLiteral => {
if let Some(expr) = extract_string_literal(cursor) {
operands.push(expr);
}
CXChildVisit_Continue
}
110 => {
if let Some(expr) = extract_char_literal(cursor) {
operands.push(expr);
}
CXChildVisit_Continue
}
CXCursor_DeclRefExpr => {
if let Some(expr) = extract_variable_ref(cursor) {
operands.push(expr);
}
CXChildVisit_Continue
}
CXCursor_BinaryOperator => {
if let Some(expr) = extract_binary_op(cursor) {
operands.push(expr);
}
CXChildVisit_Continue
}
CXCursor_UnaryOperator => {
if let Some(expr) = extract_unary_op(cursor) {
operands.push(expr);
}
CXChildVisit_Continue
}
CXCursor_ArraySubscriptExpr => {
if let Some(expr) = extract_array_index(cursor) {
operands.push(expr);
}
CXChildVisit_Continue
}
CXCursor_MemberRefExpr => {
if let Some(expr) = extract_field_access(cursor) {
operands.push(expr);
}
CXChildVisit_Continue
}
CXCursor_UnexposedExpr | CXCursor_ParenExpr => {
if let Some(expr) = extract_sizeof(cursor) {
operands.push(expr);
CXChildVisit_Continue
} else {
CXChildVisit_Recurse
}
}
136 => {
if let Some(expr) = extract_sizeof(cursor) {
operands.push(expr);
CXChildVisit_Continue
} else {
CXChildVisit_Recurse
}
}
CXCursor_CallExpr => {
if let Some(expr) = extract_function_call(cursor) {
operands.push(expr);
}
CXChildVisit_Continue
}
116 => {
if let Some(expr) = extract_conditional_op(cursor) {
operands.push(expr);
}
CXChildVisit_Continue
}
_ => CXChildVisit_Recurse,
}
}
pub(crate) fn extract_binary_operator_from_children(
cursor: CXCursor,
tu: CXTranslationUnit,
) -> Option<BinaryOperator> {
let mut children: Vec<CXCursor> = Vec::new();
let children_ptr = &mut children as *mut Vec<CXCursor>;
extern "C" fn collect_children(
cursor: CXCursor,
_parent: CXCursor,
client_data: CXClientData,
) -> CXChildVisitResult {
let children = unsafe { &mut *(client_data as *mut Vec<CXCursor>) };
children.push(cursor);
CXChildVisit_Continue
}
unsafe {
clang_visitChildren(cursor, collect_children, children_ptr as CXClientData);
}
if children.len() != 2 {
return None;
}
let first_extent = unsafe { clang_getCursorExtent(children[0]) };
let second_extent = unsafe { clang_getCursorExtent(children[1]) };
let first_end = unsafe { clang_getRangeEnd(first_extent) };
let second_start = unsafe { clang_getRangeStart(second_extent) };
let operator_range = unsafe { clang_getRange(first_end, second_start) };
let mut tokens = ptr::null_mut();
let mut num_tokens = 0;
unsafe {
clang_tokenize(tu, operator_range, &mut tokens, &mut num_tokens);
}
if tokens.is_null() || num_tokens == 0 {
return None;
}
let mut result = None;
for i in 0..num_tokens {
unsafe {
let token = *tokens.add(i as usize);
let token_kind = clang_getTokenKind(token);
if token_kind == CXToken_Punctuation {
let token_cxstring = clang_getTokenSpelling(tu, token);
let c_str = CStr::from_ptr(clang_getCString(token_cxstring));
if let Ok(token_str) = c_str.to_str() {
result = match token_str {
"+" => Some(BinaryOperator::Add),
"-" => Some(BinaryOperator::Subtract),
"*" => Some(BinaryOperator::Multiply),
"/" => Some(BinaryOperator::Divide),
"%" => Some(BinaryOperator::Modulo),
"==" => Some(BinaryOperator::Equal),
"!=" => Some(BinaryOperator::NotEqual),
"<" => Some(BinaryOperator::LessThan),
">" => Some(BinaryOperator::GreaterThan),
"<=" => Some(BinaryOperator::LessEqual),
">=" => Some(BinaryOperator::GreaterEqual),
"&&" => Some(BinaryOperator::LogicalAnd),
"||" => Some(BinaryOperator::LogicalOr),
"<<" => Some(BinaryOperator::LeftShift),
">>" => Some(BinaryOperator::RightShift),
"&" => Some(BinaryOperator::BitwiseAnd),
"|" => Some(BinaryOperator::BitwiseOr),
"^" => Some(BinaryOperator::BitwiseXor),
"=" => Some(BinaryOperator::Assign),
"," => Some(BinaryOperator::Comma),
_ => None,
};
if result.is_some() {
clang_disposeString(token_cxstring);
break;
}
}
clang_disposeString(token_cxstring);
}
}
}
unsafe {
clang_disposeTokens(tu, tokens, num_tokens);
}
result
}
pub(crate) fn token_str_to_binary_operator(token_str: &str) -> Option<BinaryOperator> {
match token_str {
"+" => Some(BinaryOperator::Add),
"-" => Some(BinaryOperator::Subtract),
"*" => Some(BinaryOperator::Multiply),
"/" => Some(BinaryOperator::Divide),
"%" => Some(BinaryOperator::Modulo),
"==" => Some(BinaryOperator::Equal),
"!=" => Some(BinaryOperator::NotEqual),
"<" => Some(BinaryOperator::LessThan),
">" => Some(BinaryOperator::GreaterThan),
"<=" => Some(BinaryOperator::LessEqual),
">=" => Some(BinaryOperator::GreaterEqual),
"&&" => Some(BinaryOperator::LogicalAnd),
"||" => Some(BinaryOperator::LogicalOr),
"<<" => Some(BinaryOperator::LeftShift),
">>" => Some(BinaryOperator::RightShift),
"&" => Some(BinaryOperator::BitwiseAnd),
"|" => Some(BinaryOperator::BitwiseOr),
"^" => Some(BinaryOperator::BitwiseXor),
"=" => Some(BinaryOperator::Assign),
"," => Some(BinaryOperator::Comma),
_ => None,
}
}
pub(crate) fn find_first_matching(
candidates: &[(usize, BinaryOperator)],
predicate: fn(&BinaryOperator) -> bool,
) -> Option<BinaryOperator> {
candidates.iter().find(|(_, op)| predicate(op)).map(|(_, op)| *op)
}
pub(crate) fn select_lowest_precedence_operator(
mut candidates: Vec<(usize, BinaryOperator)>,
) -> Option<BinaryOperator> {
if candidates.is_empty() {
return None;
}
let has_arithmetic = candidates.iter().any(|(_, op)| {
matches!(
op,
BinaryOperator::Add
| BinaryOperator::Subtract
| BinaryOperator::Multiply
| BinaryOperator::Divide
| BinaryOperator::Modulo
)
});
let has_comparison = candidates.iter().any(|(_, op)| {
matches!(
op,
BinaryOperator::LessThan
| BinaryOperator::GreaterThan
| BinaryOperator::LessEqual
| BinaryOperator::GreaterEqual
| BinaryOperator::Equal
| BinaryOperator::NotEqual
)
});
if has_arithmetic || has_comparison {
candidates.retain(|(_, op)| !matches!(op, BinaryOperator::Comma));
}
let precedence_checks: Vec<fn(&BinaryOperator) -> bool> = vec![
|op| matches!(op, BinaryOperator::Assign),
|op| matches!(op, BinaryOperator::LogicalOr),
|op| matches!(op, BinaryOperator::LogicalAnd),
|op| matches!(op, BinaryOperator::BitwiseOr),
|op| matches!(op, BinaryOperator::BitwiseXor),
|op| matches!(op, BinaryOperator::BitwiseAnd),
|op| matches!(op, BinaryOperator::Equal | BinaryOperator::NotEqual),
|op| {
matches!(
op,
BinaryOperator::LessThan
| BinaryOperator::GreaterThan
| BinaryOperator::LessEqual
| BinaryOperator::GreaterEqual
)
},
|op| matches!(op, BinaryOperator::LeftShift | BinaryOperator::RightShift),
|op| matches!(op, BinaryOperator::Add | BinaryOperator::Subtract),
];
for check in &precedence_checks {
if let Some(op) = find_first_matching(&candidates, *check) {
return Some(op);
}
}
Some(candidates[0].1)
}
pub(crate) fn extract_binary_operator(cursor: CXCursor) -> Option<BinaryOperator> {
let tu = unsafe { clang_Cursor_getTranslationUnit(cursor) };
if tu.is_null() {
return None;
}
if let Some(op) = extract_binary_operator_from_children(cursor, tu) {
return Some(op);
}
let extent = unsafe { clang_getCursorExtent(cursor) };
let mut tokens = ptr::null_mut();
let mut num_tokens = 0;
unsafe {
clang_tokenize(tu, extent, &mut tokens, &mut num_tokens);
}
let cursor_loc = unsafe { clang_getCursorLocation(cursor) };
let mut cursor_file: CXFile = ptr::null_mut();
let mut _line = 0u32;
let mut _col = 0u32;
let mut _offset = 0u32;
unsafe {
clang_getExpansionLocation(
cursor_loc,
&mut cursor_file,
&mut _line,
&mut _col,
&mut _offset,
);
}
let mut candidates: Vec<(usize, BinaryOperator)> = Vec::new();
let mut found_first_operand = false;
let mut paren_depth: i32 = 0;
let extent_start = unsafe { clang_getRangeStart(extent) };
let extent_end = unsafe { clang_getRangeEnd(extent) };
let mut start_line = 0u32;
let mut end_line = 0u32;
unsafe {
clang_getExpansionLocation(
extent_start,
ptr::null_mut(),
&mut start_line,
ptr::null_mut(),
ptr::null_mut(),
);
clang_getExpansionLocation(
extent_end,
ptr::null_mut(),
&mut end_line,
ptr::null_mut(),
ptr::null_mut(),
);
}
for i in 0..num_tokens {
unsafe {
let token = *tokens.add(i as usize);
let token_kind = clang_getTokenKind(token);
let token_loc = clang_getTokenLocation(tu, token);
let mut token_file: CXFile = ptr::null_mut();
let mut token_line = 0u32;
clang_getExpansionLocation(
token_loc,
&mut token_file,
&mut token_line,
&mut _col,
&mut _offset,
);
if !cursor_file.is_null() && !token_file.is_null() && token_file != cursor_file {
continue;
}
if start_line > 0
&& end_line > 0
&& token_line > 0
&& (token_line < start_line || token_line > end_line)
{
continue;
}
if token_kind == CXToken_Identifier || token_kind == CXToken_Literal {
found_first_operand = true;
}
if token_kind == CXToken_Punctuation {
let token_cxstring = clang_getTokenSpelling(tu, token);
let c_str = CStr::from_ptr(clang_getCString(token_cxstring));
if let Ok(token_str) = c_str.to_str() {
match token_str {
"(" => paren_depth += 1,
")" => paren_depth = paren_depth.saturating_sub(1),
_ => {}
}
if found_first_operand && paren_depth == 0 {
if let Some(op) = token_str_to_binary_operator(token_str) {
candidates.push((i as usize, op));
}
}
}
clang_disposeString(token_cxstring);
}
}
}
let operator = select_lowest_precedence_operator(candidates);
unsafe {
clang_disposeTokens(tu, tokens, num_tokens);
}
operator
}
pub(crate) fn extract_function_call(cursor: CXCursor) -> Option<Expression> {
let name_cxstring = unsafe { clang_getCursorSpelling(cursor) };
let function = unsafe {
let c_str = CStr::from_ptr(clang_getCString(name_cxstring));
let name = c_str.to_string_lossy().into_owned();
clang_disposeString(name_cxstring);
name
};
#[repr(C)]
struct ArgData {
arguments: Vec<Expression>,
skip_first_declref: bool,
}
let mut arg_data = ArgData {
arguments: Vec::new(),
skip_first_declref: true, };
let args_ptr = &mut arg_data as *mut ArgData;
unsafe {
clang_visitChildren(cursor, visit_call_argument, args_ptr as CXClientData);
}
Some(Expression::FunctionCall { function, arguments: arg_data.arguments })
}
pub(crate) extern "C" fn visit_call_argument(
cursor: CXCursor,
_parent: CXCursor,
client_data: CXClientData,
) -> CXChildVisitResult {
#[repr(C)]
struct ArgData {
arguments: Vec<Expression>,
skip_first_declref: bool,
}
let arg_data = unsafe { &mut *(client_data as *mut ArgData) };
let kind = unsafe { clang_getCursorKind(cursor) };
match kind {
CXCursor_IntegerLiteral => {
if let Some(expr) = extract_int_literal(cursor) {
arg_data.arguments.push(expr);
}
CXChildVisit_Continue
}
107 => {
if let Some(expr) = extract_float_literal(cursor) {
arg_data.arguments.push(expr);
}
CXChildVisit_Continue
}
CXCursor_StringLiteral => {
if let Some(expr) = extract_string_literal(cursor) {
arg_data.arguments.push(expr);
}
CXChildVisit_Continue
}
110 => {
if let Some(expr) = extract_char_literal(cursor) {
arg_data.arguments.push(expr);
}
CXChildVisit_Continue
}
CXCursor_DeclRefExpr => {
if arg_data.skip_first_declref {
arg_data.skip_first_declref = false;
CXChildVisit_Continue
} else {
if let Some(expr) = extract_variable_ref(cursor) {
arg_data.arguments.push(expr);
}
CXChildVisit_Continue
}
}
CXCursor_BinaryOperator => {
if let Some(expr) = extract_binary_op(cursor) {
arg_data.arguments.push(expr);
}
CXChildVisit_Continue
}
CXCursor_CallExpr => {
if let Some(expr) = extract_function_call(cursor) {
arg_data.arguments.push(expr);
}
CXChildVisit_Continue
}
CXCursor_UnaryOperator => {
if let Some(expr) = extract_unary_op(cursor) {
arg_data.arguments.push(expr);
}
CXChildVisit_Continue
}
CXCursor_ArraySubscriptExpr => {
if let Some(expr) = extract_array_index(cursor) {
arg_data.arguments.push(expr);
}
CXChildVisit_Continue
}
CXCursor_MemberRefExpr => {
if let Some(expr) = extract_field_access(cursor) {
arg_data.arguments.push(expr);
}
CXChildVisit_Continue
}
116 => {
if let Some(expr) = extract_conditional_op(cursor) {
arg_data.arguments.push(expr);
}
CXChildVisit_Continue
}
CXCursor_UnexposedExpr | CXCursor_ParenExpr => {
if let Some(expr) = extract_sizeof(cursor) {
arg_data.arguments.push(expr);
CXChildVisit_Continue
} else {
CXChildVisit_Recurse
}
}
136 => {
if let Some(expr) = extract_sizeof(cursor) {
arg_data.arguments.push(expr);
CXChildVisit_Continue
} else {
CXChildVisit_Recurse
}
}
117 => {
if let Some(expr) = extract_cast(cursor) {
arg_data.arguments.push(expr);
}
CXChildVisit_Continue
}
_ => CXChildVisit_Continue, }
}
pub(crate) fn extract_unary_op(cursor: CXCursor) -> Option<Expression> {
let tu = unsafe { clang_Cursor_getTranslationUnit(cursor) };
if tu.is_null() {
return None;
}
let extent = unsafe { clang_getCursorExtent(cursor) };
let mut tokens = ptr::null_mut();
let mut num_tokens = 0;
unsafe {
clang_tokenize(tu, extent, &mut tokens, &mut num_tokens);
}
let mut operator: Option<UnaryOperator> = None;
let mut is_dereference = false;
let mut is_increment = false;
let mut is_decrement = false;
let mut operator_position = 0;
let mut found_star_at_zero = false;
let mut found_open_paren_at_zero = false;
let mut found_increment: Option<u32> = None;
let mut found_decrement: Option<u32> = None;
for i in 0..num_tokens {
unsafe {
let token = *tokens.add(i as usize);
let token_kind = clang_getTokenKind(token);
if token_kind == CXToken_Punctuation {
let token_cxstring = clang_getTokenSpelling(tu, token);
let c_str = CStr::from_ptr(clang_getCString(token_cxstring));
if let Ok(token_str) = c_str.to_str() {
match token_str {
"*" if i == 0 => found_star_at_zero = true,
"(" if i == 0 => found_open_paren_at_zero = true,
"++" => {
found_increment = Some(i);
}
"--" => {
found_decrement = Some(i);
}
"-" if i == 0 && operator.is_none() => {
operator = Some(UnaryOperator::Minus);
}
"!" if i == 0 && operator.is_none() => {
operator = Some(UnaryOperator::LogicalNot);
}
"~" if i == 0 && operator.is_none() => {
operator = Some(UnaryOperator::BitwiseNot);
}
"&" if i == 0 && operator.is_none() => {
operator = Some(UnaryOperator::AddressOf);
}
_ => {}
}
}
clang_disposeString(token_cxstring);
}
}
}
let has_unary_op_at_zero = operator.is_some();
if let Some(pos) = found_increment {
if pos == 0 {
is_increment = true;
operator_position = pos;
} else if found_open_paren_at_zero {
is_increment = true;
operator_position = pos;
} else if !has_unary_op_at_zero && !found_star_at_zero {
is_increment = true;
operator_position = pos;
}
}
if let Some(pos) = found_decrement {
if pos == 0 || found_open_paren_at_zero || (!has_unary_op_at_zero && !found_star_at_zero) {
is_decrement = true;
operator_position = pos;
}
}
if !is_increment && !is_decrement && found_star_at_zero {
is_dereference = true;
}
unsafe {
clang_disposeTokens(tu, tokens, num_tokens);
}
let mut operand: Option<Expression> = None;
let operand_ptr = &mut operand as *mut Option<Expression>;
unsafe {
clang_visitChildren(cursor, visit_expression, operand_ptr as CXClientData);
}
let operand_expr = operand?;
if is_dereference {
return Some(Expression::Dereference(Box::new(operand_expr)));
}
if is_increment {
let is_pre = operator_position == 0;
if is_pre {
return Some(Expression::PreIncrement { operand: Box::new(operand_expr) });
} else {
return Some(Expression::PostIncrement { operand: Box::new(operand_expr) });
}
}
if is_decrement {
let is_pre = operator_position == 0;
if is_pre {
return Some(Expression::PreDecrement { operand: Box::new(operand_expr) });
} else {
return Some(Expression::PostDecrement { operand: Box::new(operand_expr) });
}
}
if let Some(op) = operator {
return Some(Expression::UnaryOp { op, operand: Box::new(operand_expr) });
}
if let Expression::IntLiteral(_) = &operand_expr {
return Some(Expression::UnaryOp {
op: UnaryOperator::Minus,
operand: Box::new(operand_expr),
});
}
None
}
pub(crate) fn extract_array_index(cursor: CXCursor) -> Option<Expression> {
let mut operands: Vec<Expression> = Vec::new();
let operands_ptr = &mut operands as *mut Vec<Expression>;
unsafe {
clang_visitChildren(cursor, visit_binary_operand, operands_ptr as CXClientData);
}
if operands.len() != 2 {
return None;
}
Some(Expression::ArrayIndex {
array: Box::new(operands[0].clone()),
index: Box::new(operands[1].clone()),
})
}
pub(crate) fn extract_field_access(cursor: CXCursor) -> Option<Expression> {
let field_name_cxstring = unsafe { clang_getCursorSpelling(cursor) };
let field = unsafe {
let c_str = CStr::from_ptr(clang_getCString(field_name_cxstring));
let name = c_str.to_string_lossy().into_owned();
clang_disposeString(field_name_cxstring);
name
};
let tu = unsafe { clang_Cursor_getTranslationUnit(cursor) };
if tu.is_null() {
return None;
}
let extent = unsafe { clang_getCursorExtent(cursor) };
let mut tokens = ptr::null_mut();
let mut num_tokens = 0;
unsafe {
clang_tokenize(tu, extent, &mut tokens, &mut num_tokens);
}
let mut is_arrow = false;
for i in 0..num_tokens {
unsafe {
let token = *tokens.add(i as usize);
let token_kind = clang_getTokenKind(token);
if token_kind == CXToken_Punctuation {
let token_cxstring = clang_getTokenSpelling(tu, token);
let c_str = CStr::from_ptr(clang_getCString(token_cxstring));
if let Ok(token_str) = c_str.to_str() {
if token_str == "->" {
is_arrow = true;
} else if token_str == "." {
is_arrow = false;
}
}
clang_disposeString(token_cxstring);
}
}
}
unsafe {
clang_disposeTokens(tu, tokens, num_tokens);
}
let mut object_expr: Option<Expression> = None;
let expr_ptr = &mut object_expr as *mut Option<Expression>;
unsafe {
clang_visitChildren(cursor, visit_expression, expr_ptr as CXClientData);
}
let object = object_expr.unwrap_or_else(|| Expression::Variable("self".to_string()));
if is_arrow {
Some(Expression::PointerFieldAccess { pointer: Box::new(object), field })
} else {
Some(Expression::FieldAccess { object: Box::new(object), field })
}
}
pub(crate) fn extract_sizeof(cursor: CXCursor) -> Option<Expression> {
let tu = unsafe { clang_Cursor_getTranslationUnit(cursor) };
if tu.is_null() {
return None;
}
let extent = unsafe { clang_getCursorExtent(cursor) };
let mut tokens = ptr::null_mut();
let mut num_tokens = 0;
unsafe {
clang_tokenize(tu, extent, &mut tokens, &mut num_tokens);
}
if num_tokens == 0 {
unsafe {
clang_disposeTokens(tu, tokens, num_tokens);
}
return None;
}
let first_token_is_sizeof = unsafe {
let token = *tokens.add(0);
let token_cxstring = clang_getTokenSpelling(tu, token);
let c_str = CStr::from_ptr(clang_getCString(token_cxstring));
let is_sizeof = c_str.to_str().map(|s| s == "sizeof").unwrap_or(false);
clang_disposeString(token_cxstring);
is_sizeof
};
if !first_token_is_sizeof {
unsafe {
clang_disposeTokens(tu, tokens, num_tokens);
}
return None;
}
let mut type_name = String::new();
let mut paren_depth = 0;
let mut in_sizeof_parens = false;
for i in 1..num_tokens {
unsafe {
let token = *tokens.add(i as usize);
let token_kind = clang_getTokenKind(token);
let token_cxstring = clang_getTokenSpelling(tu, token);
let c_str = CStr::from_ptr(clang_getCString(token_cxstring));
if let Ok(token_str) = c_str.to_str() {
if token_str == "(" {
paren_depth += 1;
in_sizeof_parens = true;
} else if token_str == ")" {
paren_depth -= 1;
if paren_depth == 0 && in_sizeof_parens {
clang_disposeString(token_cxstring);
break;
}
} else if in_sizeof_parens
&& (token_kind == CXToken_Identifier || token_kind == CXToken_Keyword)
{
if !type_name.is_empty() {
type_name.push(' ');
}
type_name.push_str(token_str);
}
}
clang_disposeString(token_cxstring);
}
}
unsafe {
clang_disposeTokens(tu, tokens, num_tokens);
}
if !type_name.is_empty() {
Some(Expression::Sizeof { type_name })
} else {
None
}
}
pub(crate) fn extract_cast(cursor: CXCursor) -> Option<Expression> {
let target_cx_type = unsafe { clang_getCursorType(cursor) };
let target_type = convert_type(target_cx_type)?;
let mut inner_expr: Option<Expression> = None;
let inner_ptr = &mut inner_expr as *mut Option<Expression>;
unsafe {
clang_visitChildren(cursor, visit_cast_inner, inner_ptr as CXClientData);
}
inner_expr.map(|expr| Expression::Cast { target_type, expr: Box::new(expr) })
}
pub(crate) extern "C" fn visit_cast_inner(
cursor: CXCursor,
_parent: CXCursor,
client_data: CXClientData,
) -> CXChildVisitResult {
let inner_expr = unsafe { &mut *(client_data as *mut Option<Expression>) };
let kind = unsafe { clang_getCursorKind(cursor) };
if let Some(expr) = try_extract_expression(cursor) {
*inner_expr = Some(expr);
return CXChildVisit_Break; }
match kind {
CXCursor_UnexposedExpr | CXCursor_ParenExpr => CXChildVisit_Recurse,
_ => CXChildVisit_Continue,
}
}
pub(crate) fn extract_compound_literal(cursor: CXCursor) -> Option<Expression> {
let literal_cx_type = unsafe { clang_getCursorType(cursor) };
let literal_type = convert_type(literal_cx_type)?;
let mut initializers: Vec<Expression> = Vec::new();
let initializers_ptr = &mut initializers as *mut Vec<Expression>;
unsafe {
clang_visitChildren(
cursor,
visit_compound_literal_initializers,
initializers_ptr as CXClientData,
);
}
Some(Expression::CompoundLiteral { literal_type, initializers })
}
pub(crate) fn extract_conditional_op(cursor: CXCursor) -> Option<Expression> {
let mut operands: Vec<Expression> = Vec::new();
let operands_ptr = &mut operands as *mut Vec<Expression>;
unsafe {
clang_visitChildren(cursor, visit_conditional_operand, operands_ptr as CXClientData);
}
if operands.len() >= 3 {
Some(Expression::Ternary {
condition: Box::new(operands[0].clone()),
then_expr: Box::new(operands[1].clone()),
else_expr: Box::new(operands[2].clone()),
})
} else if operands.len() == 2 {
Some(Expression::Ternary {
condition: Box::new(operands[0].clone()),
then_expr: Box::new(operands[0].clone()),
else_expr: Box::new(operands[1].clone()),
})
} else {
None
}
}
pub(crate) extern "C" fn visit_conditional_operand(
cursor: CXCursor,
_parent: CXCursor,
client_data: CXClientData,
) -> CXChildVisitResult {
let operands = unsafe { &mut *(client_data as *mut Vec<Expression>) };
if let Some(expr) = try_extract_expression(cursor) {
operands.push(expr);
}
CXChildVisit_Continue
}
pub(crate) fn extract_init_list(cursor: CXCursor) -> Option<Expression> {
let literal_cx_type = unsafe { clang_getCursorType(cursor) };
let literal_type = convert_type(literal_cx_type)?;
let mut initializers: Vec<Expression> = Vec::new();
let initializers_ptr = &mut initializers as *mut Vec<Expression>;
unsafe {
clang_visitChildren(cursor, visit_init_list_children, initializers_ptr as CXClientData);
}
Some(Expression::CompoundLiteral { literal_type, initializers })
}
pub(crate) extern "C" fn visit_init_list_children(
cursor: CXCursor,
_parent: CXCursor,
client_data: CXClientData,
) -> CXChildVisitResult {
let initializers = unsafe { &mut *(client_data as *mut Vec<Expression>) };
let kind = unsafe { clang_getCursorKind(cursor) };
if kind == 115 {
let cx_type = unsafe { clang_getCursorType(cursor) };
if let Some(var_type) = convert_type(cx_type) {
let default_expr = match var_type {
Type::Int => Expression::IntLiteral(0),
Type::Float | Type::Double => Expression::IntLiteral(0), Type::Char => Expression::IntLiteral(0),
_ => Expression::IntLiteral(0), };
initializers.push(default_expr);
}
return CXChildVisit_Continue;
}
if kind == CXCursor_UnexposedExpr {
#[repr(C)]
struct ChildInfo {
kinds: Vec<u32>,
exprs: Vec<Expression>,
}
let mut info = ChildInfo { kinds: Vec::new(), exprs: Vec::new() };
let info_ptr = &mut info as *mut ChildInfo;
#[allow(clippy::disallowed_methods)] extern "C" fn collect_child_info(
cursor: CXCursor,
_parent: CXCursor,
client_data: CXClientData,
) -> CXChildVisitResult {
let info = unsafe { &mut *(client_data as *mut ChildInfo) };
let kind = unsafe { clang_getCursorKind(cursor) };
info.kinds.push(kind as u32);
if kind == 119 {
if let Some(expr) = extract_init_list(cursor) {
info.exprs.push(expr);
}
} else if let Some(expr) = try_extract_expression(cursor) {
info.exprs.push(expr);
}
CXChildVisit_Continue
}
unsafe {
clang_visitChildren(cursor, collect_child_info, info_ptr as CXClientData);
}
if info.exprs.len() == 2 && matches!(&info.exprs[0], Expression::IntLiteral(_)) {
initializers.push(info.exprs[1].clone());
return CXChildVisit_Continue;
}
if info.kinds.len() == 2 && info.kinds[0] == 47 && !info.exprs.is_empty() {
#[allow(clippy::disallowed_methods)]
initializers.push(info.exprs.last().unwrap().clone());
return CXChildVisit_Continue;
}
return CXChildVisit_Recurse;
}
if let Some(expr) = try_extract_expression(cursor) {
initializers.push(expr);
return CXChildVisit_Continue;
}
match kind {
CXCursor_ParenExpr => CXChildVisit_Recurse,
_ => CXChildVisit_Continue,
}
}
pub(crate) extern "C" fn visit_compound_literal_initializers(
cursor: CXCursor,
_parent: CXCursor,
client_data: CXClientData,
) -> CXChildVisitResult {
let initializers = unsafe { &mut *(client_data as *mut Vec<Expression>) };
let kind = unsafe { clang_getCursorKind(cursor) };
if kind == 119 {
return CXChildVisit_Recurse;
}
if let Some(expr) = try_extract_expression(cursor) {
initializers.push(expr);
return CXChildVisit_Continue;
}
match kind {
CXCursor_UnexposedExpr | CXCursor_ParenExpr => CXChildVisit_Recurse,
_ => CXChildVisit_Continue,
}
}
pub(crate) fn extract_cxx_new(cursor: CXCursor) -> Option<Expression> {
let cx_type = unsafe { clang_getCursorType(cursor) };
let pointee = unsafe { clang_getPointeeType(cx_type) };
let type_name_cx = unsafe { clang_getTypeSpelling(pointee) };
let type_name = unsafe {
let c_str = CStr::from_ptr(clang_getCString(type_name_cx));
let n = c_str.to_string_lossy().into_owned();
clang_disposeString(type_name_cx);
n
};
let clean_type = type_name
.strip_prefix("struct ")
.or_else(|| type_name.strip_prefix("class "))
.unwrap_or(&type_name)
.rsplit("::")
.next()
.unwrap_or(&type_name)
.to_string();
let mut args: Vec<Expression> = Vec::new();
let args_ptr = &mut args as *mut Vec<Expression>;
unsafe {
clang_visitChildren(cursor, visit_cxx_new_args, args_ptr as CXClientData);
}
if clean_type.is_empty() {
return None;
}
Some(Expression::CxxNew { type_name: clean_type, arguments: args })
}
extern "C" fn visit_cxx_new_args(
cursor: CXCursor,
_parent: CXCursor,
client_data: CXClientData,
) -> CXChildVisitResult {
let args = unsafe { &mut *(client_data as *mut Vec<Expression>) };
let kind = unsafe { clang_getCursorKind(cursor) };
if kind == 43 { return CXChildVisit_Continue; }
match kind {
CXCursor_IntegerLiteral => {
if let Some(e) = extract_int_literal(cursor) { args.push(e); }
}
CXCursor_DeclRefExpr => {
if let Some(e) = extract_variable_ref(cursor) { args.push(e); }
}
_ => {
let mut expr_opt: Option<Expression> = None;
let expr_ptr = &mut expr_opt as *mut Option<Expression>;
unsafe { clang_visitChildren(cursor, visit_expression, expr_ptr as CXClientData); }
if let Some(e) = expr_opt { args.push(e); }
}
}
CXChildVisit_Continue
}
pub(crate) fn extract_cxx_delete(cursor: CXCursor) -> Option<Expression> {
let mut operand: Option<Expression> = None;
let expr_ptr = &mut operand as *mut Option<Expression>;
unsafe { clang_visitChildren(cursor, visit_expression, expr_ptr as CXClientData); }
Some(Expression::CxxDelete { operand: Box::new(operand?) })
}
pub(crate) fn extract_cxx_bool_literal(cursor: CXCursor) -> Option<Expression> {
let tu = unsafe { clang_Cursor_getTranslationUnit(cursor) };
if tu.is_null() { return None; }
let extent = unsafe { clang_getCursorExtent(cursor) };
let mut tokens = ptr::null_mut();
let mut num_tokens = 0;
unsafe { clang_tokenize(tu, extent, &mut tokens, &mut num_tokens); }
let mut is_true = false;
if num_tokens > 0 {
unsafe {
let token = *tokens;
let token_cx = clang_getTokenSpelling(tu, token);
let c_str = CStr::from_ptr(clang_getCString(token_cx));
if let Ok(s) = c_str.to_str() { is_true = s == "true"; }
clang_disposeString(token_cx);
clang_disposeTokens(tu, tokens, num_tokens);
}
}
Some(Expression::BoolLiteral(is_true))
}