#[derive(Debug, Clone, PartialEq)]
pub struct SwitchCase {
pub value: Option<Expression>,
pub body: Vec<Statement>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Statement {
VariableDeclaration {
name: String,
var_type: Type,
initializer: Option<Expression>,
},
Return(Option<Expression>),
Assignment {
target: String,
value: Expression,
},
If {
condition: Expression,
then_block: Vec<Statement>,
else_block: Option<Vec<Statement>>,
},
For {
init: Vec<Statement>,
condition: Option<Expression>,
increment: Vec<Statement>,
body: Vec<Statement>,
},
While {
condition: Expression,
body: Vec<Statement>,
},
DerefAssignment {
target: Expression,
value: Expression,
},
ArrayIndexAssignment {
array: Box<Expression>,
index: Box<Expression>,
value: Expression,
},
FieldAssignment {
object: Expression,
field: String,
value: Expression,
},
Break,
Continue,
Switch {
condition: Expression,
cases: Vec<SwitchCase>,
default_case: Option<Vec<Statement>>,
},
PostIncrement {
target: String,
},
PreIncrement {
target: String,
},
PostDecrement {
target: String,
},
PreDecrement {
target: String,
},
CompoundAssignment {
target: String,
op: BinaryOperator,
value: Expression,
},
DerefCompoundAssignment {
target: Expression,
op: BinaryOperator,
value: Expression,
},
FunctionCall {
function: String,
arguments: Vec<Expression>,
},
}
impl Statement {
pub fn is_string_function_call(&self) -> bool {
match self {
Statement::FunctionCall { function, .. } => {
matches!(function.as_str(), "strlen" | "strcmp" | "strcpy" | "strdup")
}
_ => false,
}
}
pub fn is_function_call(&self) -> bool {
matches!(self, Statement::FunctionCall { .. })
}
pub fn as_function_call(&self) -> Option<&Expression> {
None
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnaryOperator {
Minus,
LogicalNot,
BitwiseNot,
AddressOf,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinaryOperator {
Add,
Subtract,
Multiply,
Divide,
Modulo,
Equal,
NotEqual,
LessThan,
GreaterThan,
LessEqual,
GreaterEqual,
LogicalAnd,
LogicalOr,
LeftShift,
RightShift,
BitwiseAnd,
BitwiseOr,
BitwiseXor,
Assign,
Comma,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Expression {
IntLiteral(i32),
FloatLiteral(String),
StringLiteral(String),
CharLiteral(i8),
Variable(String),
BinaryOp {
op: BinaryOperator,
left: Box<Expression>,
right: Box<Expression>,
},
FunctionCall {
function: String,
arguments: Vec<Expression>,
},
Dereference(Box<Expression>),
UnaryOp {
op: UnaryOperator,
operand: Box<Expression>,
},
ArrayIndex {
array: Box<Expression>,
index: Box<Expression>,
},
FieldAccess {
object: Box<Expression>,
field: String,
},
PointerFieldAccess {
pointer: Box<Expression>,
field: String,
},
PostIncrement {
operand: Box<Expression>,
},
PreIncrement {
operand: Box<Expression>,
},
PostDecrement {
operand: Box<Expression>,
},
PreDecrement {
operand: Box<Expression>,
},
Sizeof {
type_name: String,
},
Cast {
target_type: Type,
expr: Box<Expression>,
},
CompoundLiteral {
literal_type: Type,
initializers: Vec<Expression>,
},
Ternary {
condition: Box<Expression>,
then_expr: Box<Expression>,
else_expr: Box<Expression>,
},
CxxNew {
type_name: String,
arguments: Vec<Expression>,
},
CxxDelete {
operand: Box<Expression>,
},
NullLiteral,
BoolLiteral(bool),
}
impl Expression {
pub fn is_string_function_call(&self) -> bool {
match self {
Expression::FunctionCall { function, .. } => {
matches!(function.as_str(), "strlen" | "strcmp" | "strcpy" | "strdup")
}
_ => false,
}
}
pub fn string_function_name(&self) -> Option<&str> {
match self {
Expression::FunctionCall { function, .. } if self.is_string_function_call() => {
Some(function.as_str())
}
_ => None,
}
}
pub fn has_string_literal_argument(&self) -> bool {
match self {
Expression::FunctionCall { arguments, .. } => {
arguments.iter().any(|arg| matches!(arg, Expression::StringLiteral(_)))
}
_ => false,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Typedef {
pub name: String,
pub underlying_type: Type,
}
impl Typedef {
pub fn new(name: String, underlying_type: Type) -> Self {
Self { name, underlying_type }
}
pub fn name(&self) -> &str {
&self.name
}
pub fn underlying_type(&self) -> &str {
match &self.underlying_type {
Type::Void => "void",
Type::Bool => "_Bool",
Type::Int => "int",
Type::UnsignedInt => "unsigned int", Type::Float => "float",
Type::Double => "double",
Type::Char => "char",
Type::SignedChar => "signed char", Type::Pointer(inner) => match **inner {
Type::Char => "char*",
Type::SignedChar => "signed char*", Type::Int => "int*",
Type::UnsignedInt => "unsigned int*", Type::Float => "float*",
Type::Double => "double*",
Type::Void => "void*",
_ => "pointer",
},
Type::Struct(name) => name,
Type::FunctionPointer { .. } => "function pointer",
Type::Array { .. } => "array",
Type::TypeAlias(name) => name,
}
}
pub fn is_pointer(&self) -> bool {
matches!(self.underlying_type, Type::Pointer(_))
}
pub fn is_struct(&self) -> bool {
matches!(self.underlying_type, Type::Struct(_))
}
pub fn is_function_pointer(&self) -> bool {
matches!(self.underlying_type, Type::FunctionPointer { .. })
}
pub fn is_array(&self) -> bool {
false
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct StructField {
pub name: String,
pub field_type: Type,
}
impl StructField {
pub fn new(name: String, field_type: Type) -> Self {
Self { name, field_type }
}
pub fn name(&self) -> &str {
&self.name
}
pub fn is_function_pointer(&self) -> bool {
matches!(self.field_type, Type::FunctionPointer { .. })
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Struct {
pub name: String,
pub fields: Vec<StructField>,
}
impl Struct {
pub fn new(name: String, fields: Vec<StructField>) -> Self {
Self { name, fields }
}
pub fn name(&self) -> &str {
&self.name
}
pub fn fields(&self) -> &[StructField] {
&self.fields
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AccessSpecifier {
Public,
Protected,
Private,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CxxOperatorKind {
Add,
Sub,
Mul,
Div,
Rem,
Equal,
NotEqual,
Less,
LessEqual,
Greater,
GreaterEqual,
Index,
Shl,
Shr,
AddAssign,
SubAssign,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Method {
pub function: Function,
pub access: AccessSpecifier,
pub is_const: bool,
pub is_static: bool,
pub is_virtual: bool,
pub operator_kind: Option<CxxOperatorKind>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Class {
pub name: String,
pub fields: Vec<StructField>,
pub methods: Vec<Method>,
pub constructor_params: Vec<Parameter>,
pub has_destructor: bool,
pub base_class: Option<String>,
}
impl Class {
pub fn new(name: String) -> Self {
Self {
name,
fields: Vec::new(),
methods: Vec::new(),
constructor_params: Vec::new(),
has_destructor: false,
base_class: None,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Namespace {
pub name: String,
pub functions: Vec<Function>,
pub structs: Vec<Struct>,
pub classes: Vec<Class>,
pub namespaces: Vec<Namespace>,
}
impl Namespace {
pub fn new(name: String) -> Self {
Self {
name,
functions: Vec::new(),
structs: Vec::new(),
classes: Vec::new(),
namespaces: Vec::new(),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Variable {
name: String,
var_type: Type,
initializer: Option<Expression>,
is_static: bool,
is_extern: bool,
is_const: bool,
}
impl Variable {
pub fn new(name: String, var_type: Type) -> Self {
Self {
name,
var_type,
initializer: None,
is_static: false,
is_extern: false,
is_const: false,
}
}
pub fn new_with_initializer(name: String, var_type: Type, initializer: Expression) -> Self {
Self {
name,
var_type,
initializer: Some(initializer),
is_static: false,
is_extern: false,
is_const: false,
}
}
pub fn new_with_storage_class(
name: String,
var_type: Type,
initializer: Option<Expression>,
is_static: bool,
is_extern: bool,
is_const: bool,
) -> Self {
Self { name, var_type, initializer, is_static, is_extern, is_const }
}
pub fn name(&self) -> &str {
&self.name
}
pub fn var_type(&self) -> &Type {
&self.var_type
}
pub fn is_function_pointer(&self) -> bool {
matches!(self.var_type, Type::FunctionPointer { .. })
}
pub fn function_pointer_param_count(&self) -> usize {
match &self.var_type {
Type::FunctionPointer { param_types, .. } => param_types.len(),
_ => 0,
}
}
pub fn function_pointer_has_void_return(&self) -> bool {
match &self.var_type {
Type::FunctionPointer { return_type, .. } => matches!(**return_type, Type::Void),
_ => false,
}
}
pub fn is_string_literal(&self) -> bool {
let is_char_ptr =
matches!(self.var_type, Type::Pointer(ref inner) if **inner == Type::Char);
if let Some(initializer) = &self.initializer {
is_char_ptr && matches!(initializer, Expression::StringLiteral(_))
} else {
false
}
}
pub fn is_string_buffer(&self) -> bool {
let is_char_ptr =
matches!(self.var_type, Type::Pointer(ref inner) if **inner == Type::Char);
if let Some(Expression::FunctionCall { function, .. }) = &self.initializer {
is_char_ptr && (function == "malloc" || function == "calloc")
} else {
false
}
}
pub fn initializer(&self) -> Option<&Expression> {
self.initializer.as_ref()
}
pub fn is_static(&self) -> bool {
self.is_static
}
pub fn is_extern(&self) -> bool {
self.is_extern
}
pub fn is_const(&self) -> bool {
self.is_const
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct EnumVariant {
pub name: String,
pub value: Option<i64>,
}
impl EnumVariant {
pub fn new(name: String, value: Option<i64>) -> Self {
Self { name, value }
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Enum {
pub name: String,
pub variants: Vec<EnumVariant>,
}
impl Enum {
pub fn new(name: String, variants: Vec<EnumVariant>) -> Self {
Self { name, variants }
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Ast {
functions: Vec<Function>,
typedefs: Vec<Typedef>,
structs: Vec<Struct>,
macros: Vec<MacroDefinition>,
variables: Vec<Variable>,
enums: Vec<Enum>,
classes: Vec<Class>,
namespaces: Vec<Namespace>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct MacroDefinition {
pub name: String,
pub parameters: Vec<String>,
pub body: String,
}
impl MacroDefinition {
pub fn new_object_like(name: String, body: String) -> Self {
Self { name, parameters: vec![], body }
}
pub fn new_function_like(name: String, parameters: Vec<String>, body: String) -> Self {
Self { name, parameters, body }
}
pub fn name(&self) -> &str {
&self.name
}
pub fn parameters(&self) -> &[String] {
&self.parameters
}
pub fn body(&self) -> &str {
&self.body
}
pub fn is_function_like(&self) -> bool {
!self.parameters.is_empty()
}
pub fn is_object_like(&self) -> bool {
self.parameters.is_empty()
}
}
impl Ast {
pub fn new() -> Self {
Self {
functions: Vec::new(),
typedefs: Vec::new(),
structs: Vec::new(),
macros: Vec::new(),
variables: Vec::new(),
enums: Vec::new(),
classes: Vec::new(),
namespaces: Vec::new(),
}
}
pub fn functions(&self) -> &[Function] {
&self.functions
}
pub fn functions_mut(&mut self) -> &mut [Function] {
&mut self.functions
}
pub fn add_function(&mut self, function: Function) {
self.functions.push(function);
}
pub fn typedefs(&self) -> &[Typedef] {
&self.typedefs
}
pub fn add_typedef(&mut self, typedef: Typedef) {
self.typedefs.push(typedef);
}
pub fn structs(&self) -> &[Struct] {
&self.structs
}
pub fn add_struct(&mut self, struct_def: Struct) {
if !self.structs.iter().any(|s| s.name() == struct_def.name()) {
self.structs.push(struct_def);
}
}
pub fn macros(&self) -> &[MacroDefinition] {
&self.macros
}
pub fn add_macro(&mut self, macro_def: MacroDefinition) {
self.macros.push(macro_def);
}
pub fn variables(&self) -> &[Variable] {
&self.variables
}
pub fn add_variable(&mut self, variable: Variable) {
self.variables.push(variable);
}
pub fn enums(&self) -> &[Enum] {
&self.enums
}
pub fn add_enum(&mut self, enum_def: Enum) {
self.enums.push(enum_def);
}
pub fn classes(&self) -> &[Class] {
&self.classes
}
pub fn add_class(&mut self, class: Class) {
if !self.classes.iter().any(|c| c.name == class.name) {
self.classes.push(class);
}
}
pub fn namespaces(&self) -> &[Namespace] {
&self.namespaces
}
pub fn add_namespace(&mut self, ns: Namespace) {
self.namespaces.push(ns);
}
}
impl Default for Ast {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CudaQualifier {
Global,
Device,
Host,
HostDevice,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Function {
pub name: String,
pub return_type: Type,
pub parameters: Vec<Parameter>,
pub body: Vec<Statement>,
pub cuda_qualifier: Option<CudaQualifier>,
}
impl Function {
pub fn new(name: String, return_type: Type, parameters: Vec<Parameter>) -> Self {
Self { name, return_type, parameters, body: Vec::new(), cuda_qualifier: None }
}
pub fn new_with_body(
name: String,
return_type: Type,
parameters: Vec<Parameter>,
body: Vec<Statement>,
) -> Self {
Self { name, return_type, parameters, body, cuda_qualifier: None }
}
}
#[derive(Debug, Clone, PartialEq)]
#[allow(clippy::enum_variant_names)] pub enum Type {
Void,
Bool,
Int,
UnsignedInt,
Float,
Double,
Char,
SignedChar,
Pointer(Box<Type>),
Struct(String),
FunctionPointer {
param_types: Vec<Type>,
return_type: Box<Type>,
},
Array {
element_type: Box<Type>,
size: Option<i64>,
},
TypeAlias(String),
}
#[derive(Debug, Clone, PartialEq)]
pub struct Parameter {
pub name: String,
pub param_type: Type,
pub is_pointee_const: bool,
}
impl Parameter {
pub fn new(name: String, param_type: Type) -> Self {
Self { name, param_type, is_pointee_const: false }
}
pub fn new_with_const(name: String, param_type: Type, is_pointee_const: bool) -> Self {
Self { name, param_type, is_pointee_const }
}
pub fn is_function_pointer(&self) -> bool {
matches!(self.param_type, Type::FunctionPointer { .. })
}
pub fn is_const_char_pointer(&self) -> bool {
self.is_pointee_const
&& matches!(self.param_type, Type::Pointer(ref inner) if matches!(**inner, Type::Char))
}
pub fn is_char_pointer(&self) -> bool {
matches!(self.param_type, Type::Pointer(ref inner) if matches!(**inner, Type::Char))
}
}