1
use super::super::context::CompileContext;
2
use super::super::emit::FunctionEmitter;
3
use super::super::expr::{
4
    compile_expr, compile_for_stack, compile_for_stack_as, describe_operand, eval_value, fold_call,
5
    fold_value, format_expr, string_designator,
6
};
7
use super::NativeSpec;
8
use super::comparison::bool_result;
9
use super::nullable::require_non_null;
10
use crate::ast::{Expr, WasmType};
11
use crate::error::{Error, Result};
12
use crate::runtime::SymbolTable;
13

            
14
pub(super) const NATIVES: &[NativeSpec] = &[
15
    NativeSpec {
16
        name: "UPCASE-STRING",
17
        eval: upcase_string,
18
        stack: Some(compile_upcase_string_to_stack),
19
        effect: Some(compile_upcase_string),
20
    },
21
    NativeSpec {
22
        name: "STRING=",
23
        eval: string_eq,
24
        stack: Some(compile_string_eq_to_stack),
25
        effect: None,
26
    },
27
];
28

            
29
3343
fn check_upcase_arity(args: &[Expr]) -> Result<()> {
30
3343
    if args.len() != 1 {
31
209
        return Err(Error::Arity {
32
209
            name: "UPCASE-STRING".to_string(),
33
209
            expected: 1,
34
209
            actual: args.len(),
35
209
        });
36
3134
    }
37
3134
    Ok(())
38
3343
}
39

            
40
1464
pub(super) fn upcase_string(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
41
1464
    check_upcase_arity(args)?;
42
1464
    let arg = eval_value(symbols, &args[0])?;
43
1045
    match arg {
44
627
        Expr::String(s) => Ok(Expr::String(s.to_uppercase())),
45
418
        other => Err(Error::Compile(format!(
46
418
            "UPCASE-STRING: expected string, got {}",
47
418
            format_expr(&other)
48
418
        ))),
49
    }
50
1464
}
51

            
52
838
pub(super) fn compile_upcase_string(
53
838
    ctx: &mut CompileContext,
54
838
    emit: &mut FunctionEmitter,
55
838
    symbols: &mut SymbolTable,
56
838
    args: &[Expr],
57
838
) -> Result<()> {
58
838
    check_upcase_arity(args)?;
59
629
    if let Some(folded) = fold_call(symbols, "UPCASE-STRING", args)? {
60
417
        return compile_expr(ctx, emit, symbols, &folded);
61
212
    }
62
212
    let rejection = upcase_rejection(ctx, emit, symbols, &args[0])?;
63
212
    emit.reject_if_live(rejection)
64
838
}
65

            
66
/// A value-position `UPCASE-STRING` has no lowering (ISS-083); a call that is
67
/// ill-typed says so first.
68
1041
fn compile_upcase_string_to_stack(
69
1041
    ctx: &mut CompileContext,
70
1041
    emit: &mut FunctionEmitter,
71
1041
    symbols: &mut SymbolTable,
72
1041
    args: &[Expr],
73
1041
) -> Result<WasmType> {
74
1041
    check_upcase_arity(args)?;
75
1041
    if fold_call(symbols, "UPCASE-STRING", args)?.is_some() {
76
        return Err(super::stackless_error("UPCASE-STRING"));
77
1041
    }
78
1041
    let rejection = upcase_rejection(ctx, emit, symbols, &args[0])?;
79
1041
    emit.reject_if_live(rejection)?;
80
    Ok(WasmType::StringRef)
81
1041
}
82

            
83
/// Why a non-folding `UPCASE-STRING` cannot compile, after its operand did.
84
1253
fn upcase_rejection(
85
1253
    ctx: &mut CompileContext,
86
1253
    emit: &mut FunctionEmitter,
87
1253
    symbols: &mut SymbolTable,
88
1253
    operand: &Expr,
89
1253
) -> Result<Error> {
90
    Ok(Error::Compile(
91
1253
        match compile_for_stack(ctx, emit, symbols, operand)? {
92
            // Upcasing a runtime string needs a host function (not built).
93
            WasmType::StringRef => "UPCASE-STRING of a runtime string".to_string(),
94
1253
            ty => format!(
95
                "UPCASE-STRING expects a string, got {}",
96
1253
                describe_operand(symbols, operand, ty)
97
            ),
98
        },
99
    ))
100
1253
}
101

            
102
30624
pub(super) fn string_eq(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
103
30624
    if args.len() != 2 {
104
        return Err(Error::Arity {
105
            name: "STRING=".to_string(),
106
            expected: 2,
107
            actual: args.len(),
108
        });
109
30624
    }
110
30624
    let a = eval_value(symbols, &args[0])?;
111
30624
    let b = eval_value(symbols, &args[1])?;
112

            
113
30624
    if let (Expr::String(sa), Expr::String(sb)) = (&a, &b) {
114
        return Ok(bool_result(sa == sb));
115
30624
    }
116

            
117
30624
    Ok(Expr::WasmRuntime(WasmType::Bool))
118
30624
}
119

            
120
23130
pub(super) fn compile_string_eq_to_stack(
121
23130
    ctx: &mut CompileContext,
122
23130
    emit: &mut FunctionEmitter,
123
23130
    symbols: &mut SymbolTable,
124
23130
    args: &[Expr],
125
23130
) -> Result<WasmType> {
126
23130
    if args.len() != 2 {
127
208
        return Err(Error::Arity {
128
208
            name: "STRING=".to_string(),
129
208
            expected: 2,
130
208
            actual: args.len(),
131
208
        });
132
22922
    }
133
22922
    let a = fold_value(symbols, &args[0])?;
134
22922
    let b = fold_value(symbols, &args[1])?;
135

            
136
22922
    if let (Some(Expr::String(sa)), Some(Expr::String(sb))) = (&a, &b) {
137
624
        emit.i32_const(i32::from(sa == sb));
138
624
        return Ok(WasmType::Bool);
139
22298
    }
140

            
141
22298
    let first = compile_string_arg_to_local(ctx, emit, symbols, &args[0], a.as_ref())?;
142
20420
    let second = compile_string_arg_to_local(ctx, emit, symbols, &args[1], b.as_ref())?;
143
20212
    let (local_a, local_b) = (first.local, second.local);
144
40424
    for arg in [first, second].iter().filter(|arg| arg.checked) {
145
20420
        emit.local_get(arg.local);
146
20420
        require_non_null(ctx, emit, WasmType::StringRef, ctx.ids.nil_string)?;
147
20420
        emit.local_set(arg.local);
148
    }
149
20212
    emit.local_get(local_a);
150
20212
    emit.local_get(local_b);
151
20212
    emit.call(ctx.ids.string_eq);
152
20212
    Ok(WasmType::Bool)
153
23130
}
154

            
155
/// A compiled `STRING=` argument: its scratch `StringRef` local and whether it
156
/// still needs a later null check.
157
struct StringArg {
158
    local: u32,
159
    checked: bool,
160
}
161

            
162
/// Compiles one `STRING=` argument into a scratch `StringRef` local. A folded
163
/// string literal never needs the null check (it's always freshly built,
164
/// non-null). Never checks here itself: the caller runs the checks only
165
/// after every argument has been evaluated.
166
42718
fn compile_string_arg_to_local(
167
42718
    ctx: &mut CompileContext,
168
42718
    emit: &mut FunctionEmitter,
169
42718
    symbols: &mut SymbolTable,
170
42718
    arg: &Expr,
171
42718
    folded: Option<&Expr>,
172
42718
) -> Result<StringArg> {
173
42718
    if let Some(Expr::String(s)) = folded {
174
20212
        let data_idx = ctx.add_data(s.as_bytes())?;
175
20212
        emit.i32_const(0);
176
20212
        emit.i32_const(s.len() as i32);
177
20212
        emit.array_new_data(ctx.ids.ty_i8_array, data_idx);
178
20212
        let local = ctx.alloc_local(WasmType::StringRef)?;
179
20212
        emit.local_set(local);
180
20212
        return Ok(StringArg {
181
20212
            local,
182
20212
            checked: false,
183
20212
        });
184
22506
    }
185
    // A literal `nil` argument (or anything that folds to it) lowers
186
    // type-directed straight to a nullable `StringRef`, rather than
187
    // folding to `Bool` and failing this as a COMPILE-time type mismatch —
188
    // it fails at RUNTIME instead, as a catchable `TYPE-ERROR`, exactly
189
    // like a runtime-nil string does (ADR-0033 Phase 5).
190
22506
    if matches!(eval_value(&mut symbols.clone(), arg), Ok(Expr::Nil)) {
191
208
        compile_for_stack_as(ctx, emit, symbols, arg, WasmType::StringRef)?;
192
208
        let local = ctx.alloc_local(WasmType::StringRef)?;
193
208
        emit.local_set(local);
194
208
        return Ok(StringArg {
195
208
            local,
196
208
            checked: true,
197
208
        });
198
22298
    }
199
22298
    let ty = compile_for_stack(ctx, emit, symbols, arg)?;
200
22090
    let ty = string_designator(ctx, emit, ty)?;
201
22090
    if ty != WasmType::StringRef {
202
1878
        emit.reject_if_live(Error::Compile(format!(
203
1878
            "STRING= arguments must be strings, got {ty}"
204
1878
        )))?;
205
20212
    }
206
20212
    let local = ctx.alloc_local(WasmType::StringRef)?;
207
20212
    emit.local_set(local);
208
20212
    Ok(StringArg {
209
20212
        local,
210
20212
        checked: true,
211
20212
    })
212
42718
}
213

            
214
#[cfg(test)]
215
#[path = "string_tests.rs"]
216
mod tests;