1
//! Entity accessor natives — `ENTITY-*`, `TRANSACTION-*`, `SPLIT-*`,
2
//! `TAG-*`, plus `CREATE-TAG` and `DELETE-ENTITY`.
3
//!
4
//! Split into topic-focused submodules so each file stays under the
5
//! ~500-line CLAUDE.md guideline:
6
//! - [`meta`] — `ENTITY-COUNT` / `CONTEXT-TYPE` / `PRIMARY-ENTITY-*` /
7
//!   `ENTITY-TYPE` / `ENTITY-PARENT-IDX` + `GET-INPUT-ENTITIES`.
8
//! - [`transaction`] — `TRANSACTION-*` accessors (5 fields).
9
//! - [`split`] — `SPLIT-*` accessors (5 fields).
10
//! - [`tag`] — `TAG-NAME` / `TAG-VALUE` + the shared GC-array string
11
//!   reader.
12
//! - [`create_tag`] — `CREATE-TAG` (constant + runtime codegen).
13
//! - [`delete_entity`] — `DELETE-ENTITY`.
14
//!
15
//! Common helpers (`arity_check`, `compile_idx_to_stack`,
16
//! `emit_entity_header_offset`, `emit_entity_data_offset`) live here
17
//! in mod.rs since every accessor uses them.
18

            
19
mod create_tag;
20
mod delete_entity;
21
mod meta;
22
mod split;
23
mod tag;
24
mod transaction;
25

            
26
#[cfg(test)]
27
mod tests;
28

            
29
use crate::ast::{Expr, Number, WasmType};
30
use crate::compiler::context::CompileContext;
31
use crate::compiler::emit::FunctionEmitter;
32
use crate::compiler::expr::{compile_for_stack, eval_value};
33
use crate::compiler::expr::{format_form, index_literal};
34
use crate::error::{Error, Result};
35
use crate::runtime::SymbolTable;
36

            
37
use super::NativeSpec;
38

            
39
pub(super) const NATIVES: &[NativeSpec] = &[
40
    NativeSpec {
41
        name: "ENTITY-COUNT",
42
        eval: meta::entity_count,
43
        stack: Some(meta::compile_entity_count_to_stack),
44
        effect: None,
45
    },
46
    NativeSpec {
47
        name: "CONTEXT-TYPE",
48
        eval: meta::context_type,
49
        stack: Some(meta::compile_context_type_to_stack),
50
        effect: None,
51
    },
52
    NativeSpec {
53
        name: "PRIMARY-ENTITY-TYPE",
54
        eval: meta::primary_entity_type,
55
        stack: Some(meta::compile_primary_entity_type_to_stack),
56
        effect: None,
57
    },
58
    NativeSpec {
59
        name: "PRIMARY-ENTITY-IDX",
60
        eval: meta::primary_entity_idx,
61
        stack: Some(meta::compile_primary_entity_idx_to_stack),
62
        effect: None,
63
    },
64
    NativeSpec {
65
        name: "ENTITY-TYPE",
66
        eval: meta::entity_type,
67
        stack: Some(meta::compile_entity_type_to_stack),
68
        effect: None,
69
    },
70
    NativeSpec {
71
        name: "ENTITY-PARENT-IDX",
72
        eval: meta::entity_parent_idx,
73
        stack: Some(meta::compile_entity_parent_idx_to_stack),
74
        effect: None,
75
    },
76
    NativeSpec {
77
        name: "TRANSACTION-SPLIT-COUNT",
78
        eval: transaction::transaction_split_count,
79
        stack: Some(transaction::compile_transaction_split_count_to_stack),
80
        effect: None,
81
    },
82
    NativeSpec {
83
        name: "TRANSACTION-TAG-COUNT",
84
        eval: transaction::transaction_tag_count,
85
        stack: Some(transaction::compile_transaction_tag_count_to_stack),
86
        effect: None,
87
    },
88
    NativeSpec {
89
        name: "TRANSACTION-IS-MULTI-CURRENCY",
90
        eval: transaction::transaction_is_multi_currency,
91
        stack: Some(transaction::compile_transaction_is_multi_currency_to_stack),
92
        effect: None,
93
    },
94
    NativeSpec {
95
        name: "TRANSACTION-POST-DATE",
96
        eval: transaction::transaction_post_date,
97
        stack: Some(transaction::compile_transaction_post_date_to_stack),
98
        effect: None,
99
    },
100
    NativeSpec {
101
        name: "TRANSACTION-ENTER-DATE",
102
        eval: transaction::transaction_enter_date,
103
        stack: Some(transaction::compile_transaction_enter_date_to_stack),
104
        effect: None,
105
    },
106
    NativeSpec {
107
        name: "SPLIT-VALUE-NUM",
108
        eval: split::split_value_num,
109
        stack: Some(split::compile_split_value_num_to_stack),
110
        effect: None,
111
    },
112
    NativeSpec {
113
        name: "SPLIT-VALUE-DENOM",
114
        eval: split::split_value_denom,
115
        stack: Some(split::compile_split_value_denom_to_stack),
116
        effect: None,
117
    },
118
    NativeSpec {
119
        name: "SPLIT-VALUE",
120
        eval: split::split_value,
121
        stack: Some(split::compile_split_value_to_stack),
122
        effect: None,
123
    },
124
    NativeSpec {
125
        name: "SPLIT-RECONCILE-STATE",
126
        eval: split::split_reconcile_state,
127
        stack: Some(split::compile_split_reconcile_state_to_stack),
128
        effect: None,
129
    },
130
    NativeSpec {
131
        name: "SPLIT-RECONCILE-DATE",
132
        eval: split::split_reconcile_date,
133
        stack: Some(split::compile_split_reconcile_date_to_stack),
134
        effect: None,
135
    },
136
    NativeSpec {
137
        name: "SPLIT-ACCOUNT-NAME",
138
        eval: split::split_account_name,
139
        stack: Some(split::compile_split_account_name_to_stack),
140
        effect: None,
141
    },
142
    NativeSpec {
143
        name: "TAG-NAME",
144
        eval: tag::tag_name,
145
        stack: Some(tag::compile_tag_name_to_stack),
146
        effect: None,
147
    },
148
    NativeSpec {
149
        name: "TAG-VALUE",
150
        eval: tag::tag_value,
151
        stack: Some(tag::compile_tag_value_to_stack),
152
        effect: None,
153
    },
154
    NativeSpec {
155
        name: "CREATE-TAG",
156
        eval: create_tag::create_tag,
157
        stack: None,
158
        effect: Some(create_tag::compile_create_tag),
159
    },
160
    NativeSpec {
161
        name: "DELETE-ENTITY",
162
        eval: delete_entity::delete_entity,
163
        stack: None,
164
        effect: Some(delete_entity::compile_delete_entity),
165
    },
166
    NativeSpec {
167
        name: "GET-INPUT-ENTITIES",
168
        eval: meta::get_input_entities,
169
        stack: Some(compile_get_input_entities_stack),
170
        effect: None,
171
    },
172
];
173

            
174
/// Adapter so the registry sees the standard `(ctx, emit, sym, args)`
175
/// shape on the `GET-INPUT-ENTITIES` slot; the underlying builder in
176
/// [`meta`] takes only `(ctx, emit)` because it ignores symbols/args.
177
1664
fn compile_get_input_entities_stack(
178
1664
    ctx: &mut CompileContext,
179
1664
    emit: &mut FunctionEmitter,
180
1664
    _symbols: &mut SymbolTable,
181
1664
    _args: &[Expr],
182
1664
) -> Result<WasmType> {
183
1664
    meta::compile_get_input_entities_to_stack(ctx, emit)
184
1664
}
185

            
186
1777569
pub(super) fn arity_check(name: &str, args: &[Expr], expected: usize) -> Result<()> {
187
1777569
    if args.len() != expected {
188
3
        return Err(Error::Arity {
189
3
            name: name.to_string(),
190
3
            expected,
191
3
            actual: args.len(),
192
3
        });
193
1777566
    }
194
1777566
    Ok(())
195
1777569
}
196

            
197
/// Compile an entity index argument to i32 on the WASM stack.
198
171300
pub(super) fn compile_idx_to_stack(
199
171300
    ctx: &mut CompileContext,
200
171300
    emit: &mut FunctionEmitter,
201
171300
    symbols: &mut SymbolTable,
202
171300
    expr: &Expr,
203
171300
) -> Result<()> {
204
171300
    let resolved = eval_value(symbols, expr)?;
205
171300
    match (&resolved, resolved.wasm_type()) {
206
        (_, Some(WasmType::I32)) => {
207
124494
            compile_for_stack(ctx, emit, symbols, expr)?;
208
        }
209
        (_, Some(WasmType::Ratio)) => {
210
            compile_for_stack(ctx, emit, symbols, expr)?;
211
            emit.struct_get(ctx.ids.ty_ratio, 0);
212
            emit.i32_wrap_i64();
213
        }
214
        (Expr::Number(Number::Index(i)), _) => {
215
46803
            emit.i32_const(index_literal(*i)?);
216
        }
217
        _ => {
218
3
            return Err(Error::Compile(format!(
219
3
                "entity index must be i32, got {}",
220
3
                format_form(&resolved)
221
3
            )));
222
        }
223
    }
224
171294
    Ok(())
225
171300
}
226

            
227
/// Emit WASM to compute the entity header offset for a given index.
228
/// Expects entity index on the WASM stack. Leaves header offset on stack.
229
/// `header_offset` = `entities_offset` + idx * 32
230
/// where `entities_offset` is an absolute offset read from `GlobalHeader`.
231
150061
pub(super) fn emit_entity_header_offset(
232
150061
    ctx: &CompileContext,
233
150061
    emit: &mut FunctionEmitter,
234
150061
    temp_local: u32,
235
150061
) -> Result<()> {
236
    // Stack: [idx]
237
150061
    emit.i32_const(32);
238
150061
    emit.i32_mul(); // [idx * 32]
239
150061
    emit.local_set(temp_local); // save idx*32
240
150061
    emit.call(ctx.ids.get_input_offset()?); // [input_base]
241
150061
    emit.i32_load(0x0C); // [entities_offset] (absolute)
242
150061
    emit.local_get(temp_local); // [entities_offset, idx*32]
243
150061
    emit.i32_add(); // [header_offset]
244
150061
    Ok(())
245
150061
}
246

            
247
/// Emit WASM to compute the entity data offset for a given index.
248
/// Expects entity index on the WASM stack. Leaves data offset on stack.
249
/// `data_offset` = `entity_header`[idx].`data_offset` (absolute memory address)
250
95312
pub(super) fn emit_entity_data_offset(
251
95312
    ctx: &CompileContext,
252
95312
    emit: &mut FunctionEmitter,
253
95312
    temp_local: u32,
254
95312
) -> Result<()> {
255
95312
    emit_entity_header_offset(ctx, emit, temp_local)?;
256
95312
    emit.i32_load(0x18); // data_offset at EntityHeader offset 0x18
257
95312
    Ok(())
258
95312
}