use crate::ast_types::*;
use clang_sys::*;
use std::ffi::CStr;
use std::ptr;
use super::types::convert_type;
use super::visit_statement;
use super::expressions::{
extract_binary_op, extract_binary_operator, extract_int_literal, extract_float_literal,
extract_char_literal, extract_variable_ref, extract_function_call, extract_unary_op,
extract_field_access, extract_array_index, extract_statement,
extract_expression_from_cursor, extract_single_statement,
visit_expression, visit_binary_operand, try_extract_expression,
};
pub(crate) fn extract_var_decl(cursor: CXCursor) -> Option<Statement> {
let storage_class = unsafe { clang_Cursor_getStorageClass(cursor) };
let is_extern = storage_class == 2;
let name_cxstring = unsafe { clang_getCursorSpelling(cursor) };
let name = 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
};
let cx_type = unsafe { clang_getCursorType(cursor) };
let var_type = convert_type(cx_type)?;
if is_extern {
let mut has_real_initializer = false;
extern "C" fn check_initializer(
cursor: CXCursor,
_parent: CXCursor,
client_data: CXClientData,
) -> CXChildVisitResult {
let has_init = unsafe { &mut *(client_data as *mut bool) };
let kind = unsafe { clang_getCursorKind(cursor) };
if kind == CXCursor_IntegerLiteral
|| kind == 107 || kind == CXCursor_StringLiteral
|| kind == CXCursor_CallExpr
|| kind == CXCursor_BinaryOperator
|| kind == CXCursor_UnaryOperator
{
*has_init = true;
return CXChildVisit_Break;
}
CXChildVisit_Continue
}
let init_ptr = &mut has_real_initializer as *mut bool;
unsafe {
clang_visitChildren(cursor, check_initializer, init_ptr as CXClientData);
}
if !has_real_initializer {
return None;
}
}
let mut initializer: Option<Expression> = None;
let init_ptr = &mut initializer as *mut Option<Expression>;
unsafe {
clang_visitChildren(cursor, visit_expression, init_ptr as CXClientData);
}
let initializer = match (&var_type, &initializer) {
(Type::Array { size: Some(array_size), .. }, Some(Expression::IntLiteral(init_val)))
if i64::from(*init_val) == *array_size =>
{
None
}
_ => initializer,
};
Some(Statement::VariableDeclaration { name, var_type, initializer })
}
pub(crate) fn extract_return_stmt(cursor: CXCursor) -> Option<Statement> {
let mut return_expr: Option<Expression> = None;
let expr_ptr = &mut return_expr as *mut Option<Expression>;
unsafe {
clang_visitChildren(cursor, visit_expression, expr_ptr as CXClientData);
}
Some(Statement::Return(return_expr))
}
pub(crate) fn extract_assignment_stmt(cursor: CXCursor) -> Option<Statement> {
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_assignment = 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_assignment = true;
clang_disposeString(token_cxstring);
break;
} else if token_str == "=="
|| token_str == "!="
|| token_str == "<="
|| token_str == ">="
{
clang_disposeString(token_cxstring);
break;
}
}
clang_disposeString(token_cxstring);
}
}
}
unsafe {
clang_disposeTokens(tu, tokens, num_tokens);
}
if !is_assignment {
return None;
}
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;
}
if let Expression::Dereference(inner) = &operands[0] {
return Some(Statement::DerefAssignment {
target: (**inner).clone(), value: operands[1].clone(),
});
}
if let Expression::ArrayIndex { array, index } = &operands[0] {
return Some(Statement::ArrayIndexAssignment {
array: array.clone(),
index: index.clone(),
value: operands[1].clone(),
});
}
if matches!(
&operands[0],
Expression::PointerFieldAccess { .. } | Expression::FieldAccess { .. }
) {
let field = match &operands[0] {
Expression::PointerFieldAccess { field, .. } => field.clone(),
Expression::FieldAccess { field, .. } => field.clone(),
_ => unreachable!(),
};
let object = match &operands[0] {
Expression::PointerFieldAccess { pointer, .. } => (**pointer).clone(),
Expression::FieldAccess { object, .. } => (**object).clone(),
_ => unreachable!(),
};
return Some(Statement::FieldAssignment { object, field, value: operands[1].clone() });
}
let target = match &operands[0] {
Expression::Variable(name) => name.clone(),
_ => return None, };
Some(Statement::Assignment { target, value: operands[1].clone() })
}
pub(crate) fn extract_inc_dec_stmt(cursor: CXCursor) -> Option<Statement> {
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<String> = None;
let mut operator_position = 0;
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 == "++" || token_str == "--" {
operator = Some(token_str.to_string()); operator_position = i;
clang_disposeString(token_cxstring);
break;
}
}
clang_disposeString(token_cxstring);
}
}
}
let is_pre = operator_position == 0;
unsafe {
clang_disposeTokens(tu, tokens, num_tokens);
}
let mut member_expr: Option<Expression> = None;
let mut simple_var: Option<String> = None;
extern "C" fn visit_for_inc_target(
cursor: CXCursor,
_parent: CXCursor,
client_data: CXClientData,
) -> CXChildVisitResult {
let data = unsafe { &mut *(client_data as *mut (Option<Expression>, Option<String>)) };
let kind = unsafe { clang_getCursorKind(cursor) };
if kind == CXCursor_ArraySubscriptExpr {
if let Some(expr) = extract_array_index(cursor) {
data.0 = Some(expr);
return CXChildVisit_Break;
}
}
if kind == CXCursor_MemberRefExpr {
if let Some(expr) = extract_field_access(cursor) {
data.0 = Some(expr);
return CXChildVisit_Break;
}
}
if kind == CXCursor_DeclRefExpr {
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
};
data.1 = Some(name);
CXChildVisit_Break
} else {
CXChildVisit_Recurse
}
}
let mut target_data = (member_expr, simple_var);
let target_ptr = &mut target_data as *mut (Option<Expression>, Option<String>);
unsafe {
clang_visitChildren(cursor, visit_for_inc_target, target_ptr as CXClientData);
}
member_expr = target_data.0;
simple_var = target_data.1;
let operator = operator?;
let op_str = operator.as_str();
if let Some(expr) = member_expr {
let delta = match op_str {
"++" => 1,
"--" => -1,
_ => return None,
};
match expr {
Expression::PointerFieldAccess { pointer, field } => {
let value = if delta > 0 {
Expression::BinaryOp {
left: Box::new(Expression::PointerFieldAccess {
pointer: pointer.clone(),
field: field.clone(),
}),
op: BinaryOperator::Add,
right: Box::new(Expression::IntLiteral(1)),
}
} else {
Expression::BinaryOp {
left: Box::new(Expression::PointerFieldAccess {
pointer: pointer.clone(),
field: field.clone(),
}),
op: BinaryOperator::Subtract,
right: Box::new(Expression::IntLiteral(1)),
}
};
return Some(Statement::FieldAssignment { object: *pointer, field, value });
}
Expression::FieldAccess { object, field } => {
let value = if delta > 0 {
Expression::BinaryOp {
left: Box::new(Expression::FieldAccess {
object: object.clone(),
field: field.clone(),
}),
op: BinaryOperator::Add,
right: Box::new(Expression::IntLiteral(1)),
}
} else {
Expression::BinaryOp {
left: Box::new(Expression::FieldAccess {
object: object.clone(),
field: field.clone(),
}),
op: BinaryOperator::Subtract,
right: Box::new(Expression::IntLiteral(1)),
}
};
return Some(Statement::FieldAssignment { object: *object, field, value });
}
Expression::ArrayIndex { array, index } => {
let value = if delta > 0 {
Expression::BinaryOp {
left: Box::new(Expression::ArrayIndex {
array: array.clone(),
index: index.clone(),
}),
op: BinaryOperator::Add,
right: Box::new(Expression::IntLiteral(1)),
}
} else {
Expression::BinaryOp {
left: Box::new(Expression::ArrayIndex {
array: array.clone(),
index: index.clone(),
}),
op: BinaryOperator::Subtract,
right: Box::new(Expression::IntLiteral(1)),
}
};
return Some(Statement::ArrayIndexAssignment { array, index, value });
}
_ => {} }
}
let target = simple_var?;
match op_str {
"++" => {
if is_pre {
Some(Statement::PreIncrement { target })
} else {
Some(Statement::PostIncrement { target })
}
}
"--" => {
if is_pre {
Some(Statement::PreDecrement { target })
} else {
Some(Statement::PostDecrement { target })
}
}
_ => None,
}
}
pub(crate) fn extract_compound_assignment_stmt(cursor: CXCursor) -> Option<Statement> {
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<BinaryOperator> = 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() {
operator = match token_str {
"+=" => Some(BinaryOperator::Add),
"-=" => Some(BinaryOperator::Subtract),
"*=" => Some(BinaryOperator::Multiply),
"/=" => Some(BinaryOperator::Divide),
"%=" => Some(BinaryOperator::Modulo),
_ => None,
};
if operator.is_some() {
clang_disposeString(token_cxstring);
break;
}
}
clang_disposeString(token_cxstring);
}
}
}
unsafe {
clang_disposeTokens(tu, tokens, num_tokens);
}
let op = operator?;
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;
}
if let Expression::Dereference(inner) = &operands[0] {
return Some(Statement::DerefCompoundAssignment {
target: (**inner).clone(), op,
value: operands[1].clone(),
});
}
if let Expression::PointerFieldAccess { .. } = &operands[0] {
return Some(Statement::DerefCompoundAssignment {
target: operands[0].clone(), op,
value: operands[1].clone(),
});
}
if let Expression::FieldAccess { .. } = &operands[0] {
return Some(Statement::DerefCompoundAssignment {
target: operands[0].clone(), op,
value: operands[1].clone(),
});
}
if let Expression::ArrayIndex { .. } = &operands[0] {
return Some(Statement::DerefCompoundAssignment {
target: operands[0].clone(), op,
value: operands[1].clone(),
});
}
let target = match &operands[0] {
Expression::Variable(name) => name.clone(),
_ => return None, };
Some(Statement::CompoundAssignment { target, op, value: operands[1].clone() })
}
pub(crate) fn extract_if_stmt(cursor: CXCursor) -> Option<Statement> {
#[repr(C)]
struct IfData {
condition: Option<Expression>,
then_block: Vec<Statement>,
else_block: Option<Vec<Statement>>,
child_index: u32,
}
let mut if_data =
IfData { condition: None, then_block: Vec::new(), else_block: None, child_index: 0 };
let data_ptr = &mut if_data as *mut IfData;
unsafe {
clang_visitChildren(cursor, visit_if_children, data_ptr as CXClientData);
}
Some(Statement::If {
condition: if_data.condition?,
then_block: if_data.then_block,
else_block: if_data.else_block,
})
}
pub(crate) extern "C" fn visit_if_children(
cursor: CXCursor,
_parent: CXCursor,
client_data: CXClientData,
) -> CXChildVisitResult {
#[repr(C)]
struct IfData {
condition: Option<Expression>,
then_block: Vec<Statement>,
else_block: Option<Vec<Statement>>,
child_index: u32,
}
let if_data = unsafe { &mut *(client_data as *mut IfData) };
let kind = unsafe { clang_getCursorKind(cursor) };
match if_data.child_index {
0 => {
if_data.condition = 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 cond_expr: Option<Expression> = None;
let expr_ptr = &mut cond_expr as *mut Option<Expression>;
unsafe {
clang_visitChildren(cursor, visit_expression, expr_ptr as CXClientData);
}
cond_expr
}
};
if_data.child_index += 1;
CXChildVisit_Continue
}
1 => {
if kind == CXCursor_CompoundStmt {
let body_ptr = &mut if_data.then_block as *mut Vec<Statement>;
unsafe {
clang_visitChildren(cursor, visit_statement, body_ptr as CXClientData);
}
} else {
if let Some(stmt) = extract_single_statement(cursor) {
if_data.then_block.push(stmt);
}
}
if_data.child_index += 1;
CXChildVisit_Continue
}
2 => {
if kind == CXCursor_CompoundStmt {
let mut else_stmts = Vec::new();
let body_ptr = &mut else_stmts as *mut Vec<Statement>;
unsafe {
clang_visitChildren(cursor, visit_statement, body_ptr as CXClientData);
}
if_data.else_block = Some(else_stmts);
} else if kind == CXCursor_IfStmt {
let mut else_stmts = Vec::new();
let body_ptr = &mut else_stmts as *mut Vec<Statement>;
unsafe {
clang_visitChildren(cursor, visit_statement, body_ptr as CXClientData);
}
if_data.else_block = Some(else_stmts);
} else {
if let Some(stmt) = extract_single_statement(cursor) {
if_data.else_block = Some(vec![stmt]);
}
}
if_data.child_index += 1;
CXChildVisit_Continue
}
_ => CXChildVisit_Continue,
}
}
pub(crate) fn extract_for_stmt(cursor: CXCursor) -> Option<Statement> {
#[repr(C)]
struct ForChildInfo {
cursor: CXCursor,
kind: i32,
}
#[repr(C)]
struct ForCollector {
children: Vec<ForChildInfo>,
}
extern "C" fn collect_for_children(
cursor: CXCursor,
_parent: CXCursor,
client_data: CXClientData,
) -> CXChildVisitResult {
let collector = unsafe { &mut *(client_data as *mut ForCollector) };
let kind = unsafe { clang_getCursorKind(cursor) };
collector.children.push(ForChildInfo { cursor, kind });
CXChildVisit_Continue
}
let mut collector = ForCollector { children: Vec::new() };
unsafe {
clang_visitChildren(cursor, collect_for_children, &mut collector as *mut _ as CXClientData);
}
let mut init: Vec<Statement> = Vec::new();
let mut condition: Option<Expression> = None;
let mut increment: Vec<Statement> = Vec::new();
let mut body: Vec<Statement> = Vec::new();
let num_children = collector.children.len();
fn is_assignment_op(cursor: CXCursor) -> bool {
if let Some(op) = extract_binary_operator(cursor) {
matches!(op, BinaryOperator::Assign)
} else {
false
}
}
fn is_condition_op(cursor: CXCursor) -> bool {
if let Some(op) = extract_binary_operator(cursor) {
matches!(
op,
BinaryOperator::Equal
| BinaryOperator::NotEqual
| BinaryOperator::LessThan
| BinaryOperator::GreaterThan
| BinaryOperator::LessEqual
| BinaryOperator::GreaterEqual
| BinaryOperator::LogicalAnd
| BinaryOperator::LogicalOr
)
} else {
false
}
}
fn extract_increment_stmts(cursor: CXCursor) -> Vec<Statement> {
let kind = unsafe { clang_getCursorKind(cursor) };
let mut stmts = Vec::new();
if kind == CXCursor_BinaryOperator {
if let Some(BinaryOperator::Comma) = extract_binary_operator(cursor) {
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);
}
for child in children {
stmts.extend(extract_increment_stmts(child));
}
return stmts;
}
if let Some(stmt) = extract_assignment_stmt(cursor) {
stmts.push(stmt);
}
} else if kind == CXCursor_UnaryOperator {
if let Some(stmt) = extract_inc_dec_stmt(cursor) {
stmts.push(stmt);
}
}
stmts
}
if num_children == 0 {
return Some(Statement::For { init, condition, increment, body });
}
let body_idx = num_children - 1;
let body_child = &collector.children[body_idx];
if body_child.kind == CXCursor_CompoundStmt {
let body_ptr = &mut body as *mut Vec<Statement>;
unsafe {
clang_visitChildren(body_child.cursor, visit_statement, body_ptr as CXClientData);
}
} else {
if let Some(stmt) = extract_single_statement(body_child.cursor) {
body.push(stmt);
}
}
let pre_body = &collector.children[..body_idx];
match pre_body.len() {
0 => {
}
1 => {
let child = &pre_body[0];
if child.kind == CXCursor_DeclStmt {
let mut init_stmts = Vec::new();
let ptr = &mut init_stmts as *mut Vec<Statement>;
unsafe {
clang_visitChildren(child.cursor, visit_statement, ptr as CXClientData);
}
} else if child.kind == CXCursor_BinaryOperator {
if is_assignment_op(child.cursor) {
if let Some(stmt) = extract_assignment_stmt(child.cursor) {
init.push(stmt);
}
} else if is_condition_op(child.cursor) {
condition = extract_binary_op(child.cursor);
} else {
condition = extract_binary_op(child.cursor);
}
} else if child.kind == CXCursor_UnaryOperator {
increment = extract_increment_stmts(child.cursor);
} else {
condition = extract_expression_from_cursor(child.cursor);
}
}
2 => {
let child0 = &pre_body[0];
let child1 = &pre_body[1];
let first_is_init = child0.kind == CXCursor_DeclStmt
|| (child0.kind == CXCursor_BinaryOperator && is_assignment_op(child0.cursor));
if first_is_init {
if child0.kind == CXCursor_DeclStmt {
let ptr = &mut init as *mut Vec<Statement>;
unsafe {
clang_visitChildren(child0.cursor, visit_statement, ptr as CXClientData);
}
} else if let Some(stmt) = extract_assignment_stmt(child0.cursor) {
init.push(stmt);
}
condition = extract_expression_from_cursor(child1.cursor);
} else {
condition = extract_expression_from_cursor(child0.cursor);
increment = extract_increment_stmts(child1.cursor);
}
}
3 => {
let child0 = &pre_body[0];
let child1 = &pre_body[1];
let child2 = &pre_body[2];
if child0.kind == CXCursor_DeclStmt {
let ptr = &mut init as *mut Vec<Statement>;
unsafe {
clang_visitChildren(child0.cursor, visit_statement, ptr as CXClientData);
}
} else if child0.kind == CXCursor_BinaryOperator {
if let Some(stmt) = extract_assignment_stmt(child0.cursor) {
init.push(stmt);
}
}
condition = extract_expression_from_cursor(child1.cursor);
increment = extract_increment_stmts(child2.cursor);
}
_ => {
}
}
Some(Statement::For { init, condition, increment, body })
}
pub(crate) fn extract_while_stmt(cursor: CXCursor) -> Option<Statement> {
#[repr(C)]
struct WhileData {
condition: Option<Expression>,
body: Vec<Statement>,
child_index: u32,
}
let mut while_data = WhileData { condition: None, body: Vec::new(), child_index: 0 };
let data_ptr = &mut while_data as *mut WhileData;
unsafe {
clang_visitChildren(cursor, visit_while_children, data_ptr as CXClientData);
}
Some(Statement::While { condition: while_data.condition?, body: while_data.body })
}
pub(crate) extern "C" fn visit_while_children(
cursor: CXCursor,
_parent: CXCursor,
client_data: CXClientData,
) -> CXChildVisitResult {
#[repr(C)]
struct WhileData {
condition: Option<Expression>,
body: Vec<Statement>,
child_index: u32,
}
let while_data = unsafe { &mut *(client_data as *mut WhileData) };
let kind = unsafe { clang_getCursorKind(cursor) };
match while_data.child_index {
0 => {
while_data.condition = 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 cond_expr: Option<Expression> = None;
let expr_ptr = &mut cond_expr as *mut Option<Expression>;
unsafe {
clang_visitChildren(cursor, visit_expression, expr_ptr as CXClientData);
}
cond_expr
}
};
while_data.child_index += 1;
CXChildVisit_Continue
}
1 => {
if kind == CXCursor_CompoundStmt {
let body_ptr = &mut while_data.body as *mut Vec<Statement>;
unsafe {
clang_visitChildren(cursor, visit_statement, body_ptr as CXClientData);
}
}
while_data.child_index += 1;
CXChildVisit_Continue
}
_ => CXChildVisit_Continue,
}
}
pub(crate) fn extract_switch_stmt(cursor: CXCursor) -> Option<Statement> {
#[repr(C)]
struct SwitchData {
condition: Option<Expression>,
cases: Vec<SwitchCase>,
default_case: Option<Vec<Statement>>,
child_index: u32,
}
let mut switch_data =
SwitchData { condition: None, cases: Vec::new(), default_case: None, child_index: 0 };
let data_ptr = &mut switch_data as *mut SwitchData;
unsafe {
clang_visitChildren(cursor, visit_switch_children, data_ptr as CXClientData);
}
Some(Statement::Switch {
condition: switch_data.condition?,
cases: switch_data.cases,
default_case: switch_data.default_case,
})
}
pub(crate) extern "C" fn visit_switch_children(
cursor: CXCursor,
_parent: CXCursor,
client_data: CXClientData,
) -> CXChildVisitResult {
#[repr(C)]
struct SwitchData {
condition: Option<Expression>,
cases: Vec<SwitchCase>,
default_case: Option<Vec<Statement>>,
child_index: u32,
}
let switch_data = unsafe { &mut *(client_data as *mut SwitchData) };
let kind = unsafe { clang_getCursorKind(cursor) };
match switch_data.child_index {
0 => {
if let Some(expr) = try_extract_expression(cursor) {
switch_data.condition = Some(expr);
}
switch_data.child_index += 1;
CXChildVisit_Continue
}
1 => {
if kind == CXCursor_CompoundStmt {
unsafe {
clang_visitChildren(cursor, visit_switch_body, client_data);
}
}
switch_data.child_index += 1;
CXChildVisit_Continue
}
_ => CXChildVisit_Continue,
}
}
pub(crate) extern "C" fn visit_switch_body(
cursor: CXCursor,
_parent: CXCursor,
client_data: CXClientData,
) -> CXChildVisitResult {
#[repr(C)]
struct SwitchData {
condition: Option<Expression>,
cases: Vec<SwitchCase>,
default_case: Option<Vec<Statement>>,
child_index: u32,
}
let switch_data = unsafe { &mut *(client_data as *mut SwitchData) };
let kind = unsafe { clang_getCursorKind(cursor) };
match kind {
CXCursor_CaseStmt => {
if let Some(case) = extract_case_stmt(cursor) {
switch_data.cases.push(case);
}
CXChildVisit_Continue
}
CXCursor_DefaultStmt => {
if let Some(body) = extract_default_stmt(cursor) {
switch_data.default_case = Some(body);
}
CXChildVisit_Continue
}
_ => CXChildVisit_Continue,
}
}
pub(crate) fn extract_case_stmt(cursor: CXCursor) -> Option<SwitchCase> {
#[repr(C)]
struct CaseData {
value: Option<Expression>,
body: Vec<Statement>,
child_index: u32,
}
let mut case_data = CaseData { value: None, body: Vec::new(), child_index: 0 };
let data_ptr = &mut case_data as *mut CaseData;
unsafe {
clang_visitChildren(cursor, visit_case_children, data_ptr as CXClientData);
}
Some(SwitchCase { value: case_data.value, body: case_data.body })
}
pub(crate) extern "C" fn visit_case_children(
cursor: CXCursor,
_parent: CXCursor,
client_data: CXClientData,
) -> CXChildVisitResult {
#[repr(C)]
struct CaseData {
value: Option<Expression>,
body: Vec<Statement>,
child_index: u32,
}
let case_data = unsafe { &mut *(client_data as *mut CaseData) };
let _kind = unsafe { clang_getCursorKind(cursor) };
match case_data.child_index {
0 => {
if let Some(expr) = try_extract_expression(cursor) {
case_data.value = Some(expr);
}
case_data.child_index += 1;
CXChildVisit_Continue
}
_ => {
if let Some(stmt) = extract_statement(cursor) {
case_data.body.push(stmt);
}
CXChildVisit_Recurse
}
}
}
pub(crate) fn extract_default_stmt(cursor: CXCursor) -> Option<Vec<Statement>> {
let mut body: Vec<Statement> = Vec::new();
let body_ptr = &mut body as *mut Vec<Statement>;
unsafe {
clang_visitChildren(cursor, visit_default_children, body_ptr as CXClientData);
}
Some(body)
}
pub(crate) extern "C" fn visit_default_children(
cursor: CXCursor,
_parent: CXCursor,
client_data: CXClientData,
) -> CXChildVisitResult {
let body = unsafe { &mut *(client_data as *mut Vec<Statement>) };
if let Some(stmt) = extract_statement(cursor) {
body.push(stmt);
}
CXChildVisit_Continue
}