1use crate::ir::expr::{BinOp, ConcatPart, ConstVal, Expr};
9use crate::ir::stmt::Stmt;
10use crate::types::JavaType;
11
12#[derive(Debug, Clone)]
14pub enum Term {
15 Fallthrough,
16 Goto,
17 Cond {
19 cond: Expr,
20 },
21 Switch {
26 selector: Expr,
27 targets: SwitchTargets,
28 default: Option<u32>,
29 },
30 Return(Option<Expr>),
31 Throw(Expr),
32 Jsr,
34 Ret,
36}
37
38#[derive(Debug, Clone)]
39pub enum SwitchTargets {
40 Table { low: i32, targets: Vec<u32> },
42 Lookup { pairs: Vec<(i32, u32)> },
44}
45
46#[derive(Debug, Clone)]
47pub struct BlockResult {
48 pub stmts: Vec<Stmt>,
51 pub out_stack: Vec<Expr>,
55 pub term: Term,
56}
57
58#[derive(Debug)]
59pub struct BuildError(pub String);
60
61pub type BResult<T> = Result<T, BuildError>;
62
63pub fn int_const(i: i32) -> Expr {
65 Expr::Const(ConstVal::Int(i))
66}
67
68pub fn has_side_effects(e: &Expr) -> bool {
71 match e {
72 Expr::Const(_) | Expr::Local { .. } | Expr::This | Expr::Raw(_) | Expr::RawT(..) => false,
73 Expr::New { .. }
74 | Expr::Method { .. }
75 | Expr::Invokedynamic { .. }
76 | Expr::Lambda(_)
77 | Expr::AnonNew { .. } => true,
78 Expr::Assign { .. } | Expr::PreIncDec { .. } | Expr::PostIncDec { .. } => true,
79 Expr::Field { owner, .. } => {
80 owner.is_some()
82 }
83 Expr::ArrayIndex { .. } => true,
84 Expr::Un { e, .. } | Expr::Cast { e, .. } | Expr::InstanceOf { e, .. } => {
85 has_side_effects(e)
86 }
87 Expr::Bin { l, r, .. } => has_side_effects(l) || has_side_effects(r),
88 Expr::Cond { c, t, f } => has_side_effects(c) || has_side_effects(t) || has_side_effects(f),
89 Expr::NewArray { dims, init, .. } => {
90 dims.iter().any(has_side_effects)
91 || init
92 .as_ref()
93 .map(|v| v.iter().any(has_side_effects))
94 .unwrap_or(false)
95 }
96 Expr::NewMultiArray { dims, .. } => dims.iter().any(has_side_effects),
97 Expr::StringConcat(parts) => parts.iter().any(|p| match p {
98 ConcatPart::Str(e) => has_side_effects(e),
99 ConcatPart::Const(_) => false,
100 }),
101 }
102}
103
104pub fn unfold_cmp(v: Expr, op_if_int: BinOp) -> (Expr, Expr, BinOp) {
107 if let Expr::Invokedynamic { name, args, .. } = &v {
108 if name.starts_with("\u{0}cmp") && args.len() == 2 {
109 let mut args = match v {
110 Expr::Invokedynamic { args, .. } => args,
111 _ => unreachable!(),
112 };
113 let r = args.pop().unwrap();
114 let l = args.pop().unwrap();
115 return (l, r, op_if_int);
116 }
117 }
118 (v, int_const(0), op_if_int)
119}
120
121pub fn class_name_to_type(name: &str) -> JavaType {
123 if name.starts_with('[') {
124 crate::types::parse_field_descriptor(name).unwrap_or(JavaType::Object(name.to_string()))
125 } else {
126 JavaType::Object(name.to_string())
127 }
128}