Skip to main content

hexicon_vm/
charset.rs

1//! Character sets: converting between text and the bytes of an encoding,
2//! and the CharacterSet built-in class that names one.
3//!
4//! UTF-8 and UTF-16 are built in. Every other set is a table embedded in
5//! the VM, in `data/charmaps.bin`: for each, a byte giving the length of
6//! its name, the name, the table's length as a 32-bit little-endian
7//! integer, and the table. A table does more than list the characters
8//! a set has: it also gives a stand-in for many it lacks, so that `à`
9//! becomes `a` in ASCII instead of a question mark.
10
11use std::collections::{HashMap, HashSet};
12use std::rc::Rc;
13
14use crate::error::{VmError, VmResult, code};
15use crate::object::Object;
16use crate::value::{NativeDesc, ObjId, Value};
17use crate::vm::Vm;
18
19/// The embedded tables: for each, a name length, the name, the table's
20/// length, and the table.
21static TABLES: &[u8] = include_bytes!("../data/charmaps.bin");
22
23/// A mapping between text and bytes.
24#[derive(Debug)]
25pub(crate) enum CharMap {
26    Utf8,
27    Utf16 { big_endian: bool },
28    Table(Box<Table>),
29}
30
31/// A character set defined by a table.
32#[derive(Debug)]
33pub(crate) struct Table {
34    /// The bytes for each character the table knows, including the
35    /// stand-ins for characters the set does not really have.
36    to_bytes: HashMap<u16, Vec<u8>>,
37    /// The bytes for any other character.
38    unknown: Vec<u8>,
39    /// The character for each byte.
40    to_char: [u16; 256],
41    /// Characters the console would spell out with several others, such
42    /// as `(c)` for the copyright sign. They do not survive a round trip.
43    expanded: HashSet<u16>,
44}
45
46const REPLACEMENT: u16 = 0xfffd;
47
48fn u16_at(data: &[u8], at: usize) -> Option<u16> {
49    let b = data.get(at..at + 2)?;
50    Some(u16::from_le_bytes([b[0], b[1]]))
51}
52
53fn u32_at(data: &[u8], at: usize) -> Option<usize> {
54    let b = data.get(at..at + 4)?;
55    Some(u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize)
56}
57
58impl Table {
59    /// Read a table in the reference's compiled format.
60    fn parse(data: &[u8]) -> Option<Self> {
61        // First, pairs of a character and its byte.
62        let to_bytes_at = u32_at(data, 0)?;
63        let pair_count = usize::from(u16_at(data, 4)?);
64        let mut to_char = [REPLACEMENT; 256];
65        for index in 0..pair_count {
66            let at = 6 + index * 4;
67            let character = u16_at(data, at)?;
68            let local = u16_at(data, at + 2)?;
69            if let Some(slot) = to_char.get_mut(usize::from(local)) {
70                *slot = character;
71            }
72        }
73
74        // Then each character and the bytes to write for it. The first
75        // entry is what to write for a character that has no entry.
76        let entry_count = usize::from(u16_at(data, to_bytes_at)?);
77        let mut at = to_bytes_at + 6;
78        let mut to_bytes = HashMap::with_capacity(entry_count);
79        let mut unknown = vec![b'?'];
80        for index in 0..entry_count {
81            let character = u16_at(data, at)?;
82            let len = usize::from(*data.get(at + 2)?);
83            let bytes = data.get(at + 3..at + 3 + len)?.to_vec();
84            at += 3 + len;
85            if index == 0 {
86                unknown = bytes;
87            } else {
88                to_bytes.insert(character, bytes);
89            }
90        }
91
92        // Last, the characters with expansions.
93        let mut expanded = HashSet::new();
94        if data.get(at..at + 4).is_some_and(|mark| mark != b"$EOF") {
95            let count = usize::from(u16_at(data, at)?);
96            at += 6;
97            for _ in 0..count {
98                let character = u16_at(data, at)?;
99                let len = usize::from(*data.get(at + 2)?);
100                at += 3 + len * 2;
101                expanded.insert(character);
102            }
103        }
104        Some(Self {
105            to_bytes,
106            unknown,
107            to_char,
108            expanded,
109        })
110    }
111
112    fn bytes_of(&self, c: char) -> &[u8] {
113        u16::try_from(u32::from(c))
114            .ok()
115            .and_then(|code| self.to_bytes.get(&code))
116            .unwrap_or(&self.unknown)
117    }
118}
119
120/// Find an embedded table by its file name.
121fn embedded(name: &str) -> Option<&'static [u8]> {
122    let mut rest = TABLES;
123    while let Some((&name_len, after)) = rest.split_first() {
124        let (entry_name, after) = after.split_at_checked(usize::from(name_len))?;
125        let len = u32_at(after, 0)?;
126        let (data, after) = after.get(4..)?.split_at_checked(len)?;
127        if entry_name == name.as_bytes() {
128            return Some(data);
129        }
130        rest = after;
131    }
132    None
133}
134
135/// Find the table for a character set name, trying the usual other
136/// spellings: `latin-2` and `iso-8859-2` are `iso2`, and `windows-1252`
137/// and plain `1252` are `cp1252`.
138fn find_table(name: &str) -> Option<&'static [u8]> {
139    if let Some(table) = embedded(name) {
140        return Some(table);
141    }
142    let prefix = name.trim_end_matches(|c: char| c.is_ascii_digit());
143    let digits = &name[prefix.len()..];
144    let number: u32 = digits.parse().unwrap_or(0);
145    // The reference compares the two lengths here, which leaves out a
146    // name like `l1`. That one is found as a name for Latin-1 later.
147    if prefix.len() == digits.len() || number == 0 {
148        return None;
149    }
150    const ISO: [&str; 10] = [
151        "latin",
152        "latin-",
153        "iso",
154        "iso-",
155        "8859-",
156        "iso8859-",
157        "iso-8859-",
158        "iso_8859-",
159        "iso_8859_",
160        "l",
161    ];
162    const CODE_PAGE: [&str; 7] = ["", "win", "win-", "windows", "windows-", "dos", "dos-"];
163    if ISO.contains(&prefix)
164        && let Some(table) = embedded(&format!("iso{number}"))
165    {
166        return Some(table);
167    }
168    if CODE_PAGE.contains(&prefix) {
169        return embedded(&format!("cp{number}"));
170    }
171    None
172}
173
174/// Text in a named character set, as a string; `None` if the name is not
175/// one of a character set that is known. A byte that the set has no
176/// character for becomes U+FFFD.
177///
178/// This is for the compiler, which reads source files in whatever
179/// character set they say they are in, and uses the same tables as
180/// programs do.
181pub fn decode_text(charset: &str, bytes: &[u8]) -> Option<String> {
182    let map = CharMap::load(charset)?;
183    Some(match map {
184        // Source text keeps what is there; it is not a program's string.
185        CharMap::Utf8 => String::from_utf8_lossy(bytes).into_owned(),
186        other => other.decode(bytes),
187    })
188}
189
190impl CharMap {
191    /// The mapping for a character set name, if the name is known.
192    pub(crate) fn load(name: &str) -> Option<Self> {
193        let name = name.to_ascii_lowercase();
194        let name = name.as_str();
195        if matches!(name, "utf-8" | "utf8") {
196            return Some(Self::Utf8);
197        }
198        const UTF16_LE: [&str; 8] = [
199            "utf-16le",
200            "utf16le",
201            "utf_16le",
202            "unicodel",
203            "unicode-l",
204            "unicode-le",
205            "ucs-2le",
206            "ucs2le",
207        ];
208        const UTF16_BE: [&str; 8] = [
209            "utf-16be",
210            "utf16be",
211            "utf_16be",
212            "unicodeb",
213            "unicode-b",
214            "unicode-be",
215            "ucs-2be",
216            "ucs2be",
217        ];
218        if UTF16_LE.contains(&name) {
219            return Some(Self::Utf16 { big_endian: false });
220        }
221        if UTF16_BE.contains(&name) {
222            return Some(Self::Utf16 { big_endian: true });
223        }
224        const ASCII: [&str; 7] = [
225            "us-ascii",
226            "asc7dflt",
227            "ascii",
228            "iso646-us",
229            "iso-ir-6",
230            "cp367",
231            "us",
232        ];
233        const LATIN1: [&str; 13] = [
234            "iso-8859-1",
235            "iso_8859-1",
236            "iso_8859_1",
237            "iso8859-1",
238            "iso8859_1",
239            "8859-1",
240            "8859_1",
241            "iso-ir-100",
242            "latin1",
243            "latin-1",
244            "l1",
245            "iso1",
246            "cp819",
247        ];
248        let table = find_table(name).or_else(|| {
249            // For these names with no table of their own, the reference
250            // has two maps built in, which the embedded tables include.
251            if ASCII.contains(&name) {
252                embedded("#ascii")
253            } else if LATIN1.contains(&name) {
254                embedded("#latin1")
255            } else {
256                None
257            }
258        })?;
259        Table::parse(table).map(|table| Self::Table(Box::new(table)))
260    }
261
262    /// The bytes of text in this character set.
263    pub(crate) fn encode(&self, text: &str) -> Vec<u8> {
264        match self {
265            Self::Utf8 => text.as_bytes().to_vec(),
266            Self::Utf16 { big_endian } => text
267                .chars()
268                .flat_map(|c| {
269                    let unit = u32::from(c) as u16;
270                    if *big_endian {
271                        unit.to_be_bytes()
272                    } else {
273                        unit.to_le_bytes()
274                    }
275                })
276                .collect(),
277            Self::Table(table) => text
278                .chars()
279                .flat_map(|c| table.bytes_of(c).iter().copied())
280                .collect(),
281        }
282    }
283
284    /// The text that bytes in this character set stand for.
285    pub(crate) fn decode(&self, bytes: &[u8]) -> String {
286        let from_unit = |unit: u16| char::from_u32(unit.into()).unwrap_or('\u{fffd}');
287        match self {
288            // Anything that is not UTF-8 becomes a question mark, and an
289            // unfinished character at the end is left off.
290            Self::Utf8 => {
291                let mut end = bytes.len();
292                for back in 1..=bytes.len().min(3) {
293                    let byte = bytes[bytes.len() - back];
294                    if byte & 0xc0 != 0x80 {
295                        let need = match byte {
296                            0xc0..=0xdf => 2,
297                            0xe0..=0xff => 3,
298                            _ => 1,
299                        };
300                        if need > back {
301                            end = bytes.len() - back;
302                        }
303                        break;
304                    }
305                }
306                String::from_utf8_lossy(&bytes[..end]).replace('\u{fffd}', "?")
307            }
308            Self::Utf16 { big_endian } => bytes
309                .as_chunks::<2>()
310                .0
311                .iter()
312                .map(|pair| {
313                    from_unit(if *big_endian {
314                        u16::from_be_bytes([pair[0], pair[1]])
315                    } else {
316                        u16::from_le_bytes([pair[0], pair[1]])
317                    })
318                })
319                .collect(),
320            Self::Table(table) => bytes
321                .iter()
322                .map(|&byte| from_unit(table.to_char[usize::from(byte)]))
323                .collect(),
324        }
325    }
326
327    /// Whether the set has the character, or a stand-in for it.
328    ///
329    /// The reference VM answers no for every character in UTF-16, which
330    /// has them all: its UTF-16 mapping never says otherwise. A program
331    /// can see the answer, so it is the same here.
332    fn is_mappable(&self, c: char) -> bool {
333        match self {
334            Self::Table(table) => {
335                u16::try_from(u32::from(c)).is_ok_and(|code| table.to_bytes.contains_key(&code))
336            }
337            Self::Utf8 => true,
338            Self::Utf16 { .. } => false,
339        }
340    }
341
342    /// Whether the character comes back unchanged from being converted
343    /// to bytes and back.
344    fn is_round_trip(&self, c: char) -> bool {
345        if !self.is_mappable(c) {
346            return false;
347        }
348        if let Self::Table(table) = self
349            && u16::try_from(u32::from(c)).is_ok_and(|code| table.expanded.contains(&code))
350        {
351            return false;
352        }
353        let mut text = [0; 4];
354        let text = c.encode_utf8(&mut text);
355        self.decode(&self.encode(text)) == *text
356    }
357}
358
359/// The name and calling interface of each method, by method number.
360const METHODS: &[(&str, NativeDesc)] = &[
361    ("", NativeDesc::fixed(0)),
362    ("getName", NativeDesc::fixed(0)),
363    ("isMappingKnown", NativeDesc::fixed(0)),
364    ("isMappable", NativeDesc::fixed(1)),
365    ("isRoundTripMappable", NativeDesc::fixed(1)),
366];
367
368impl Vm {
369    /// Make a CharacterSet object for a name. The name need not be one
370    /// the VM knows: that only matters when the set is used.
371    pub(crate) fn new_charset(&mut self, name: &[u8]) -> ObjId {
372        let name = String::from_utf8_lossy(name).into_owned();
373        let map = CharMap::load(&name).map(Rc::new);
374        self.alloc_obj(Object::CharSet { name, map })
375    }
376
377    /// `new CharacterSet(name)`.
378    pub(crate) fn create_charset(&mut self, argc: u32) -> VmResult<ObjId> {
379        if argc != 1 {
380            return Err(VmError::new(code::WRONG_NUM_OF_ARGS));
381        }
382        let Some(name) = self.as_str(self.arg(0)) else {
383            return Err(VmError::new(code::BAD_TYPE_BIF));
384        };
385        let name = name.to_vec();
386        Ok(self.new_charset(&name))
387    }
388
389    /// The mapping an argument asks for: a CharacterSet, the name of
390    /// one, or nil for none. Asking for a set the VM does not know throws
391    /// the program's exception for that.
392    pub(crate) fn charset_arg(&mut self, value: Value) -> VmResult<Option<Rc<CharMap>>> {
393        let id = match value {
394            Value::Nil => return Ok(None),
395            Value::Obj(id) if matches!(self.objects.get(id), Some(Object::CharSet { .. })) => id,
396            other => match self.as_str(other) {
397                Some(name) => {
398                    let name = name.to_vec();
399                    self.new_charset(&name)
400                }
401                None => return Err(VmError::new(code::BAD_TYPE_BIF)),
402            },
403        };
404        self.charset_map(id).map(Some)
405    }
406
407    pub(crate) fn charset_map(&mut self, id: ObjId) -> VmResult<Rc<CharMap>> {
408        if let Some(Object::CharSet { map: Some(map), .. }) = self.objects.get(id) {
409            return Ok(map.clone());
410        }
411        let class = self.predef.charset_unknown_exception;
412        Err(self.throw_class(class, "unknown character set"))
413    }
414
415    /// Whether two character sets have the same name, in any case.
416    pub(crate) fn charset_equals(&self, id: ObjId, other: Value) -> bool {
417        let name_of = |id: ObjId| match self.objects.get(id) {
418            Some(Object::CharSet { name, .. }) => Some(name.as_str()),
419            _ => None,
420        };
421        match (name_of(id), other) {
422            (Some(name), Value::Obj(other)) => {
423                other == id || name_of(other).is_some_and(|other| other.eq_ignore_ascii_case(name))
424            }
425            _ => false,
426        }
427    }
428
429    pub(crate) fn charset_method(
430        &mut self,
431        id: ObjId,
432        index: u16,
433        argc: Option<&mut u32>,
434    ) -> VmResult<Option<Value>> {
435        let Some(&(_, desc)) = METHODS.get(index as usize).filter(|_| index != 0) else {
436            return Ok(None);
437        };
438        self.native_method(argc, desc, |vm, _| vm.charset_call(id, index))
439            .map(Some)
440    }
441
442    fn charset_call(&mut self, id: ObjId, index: u16) -> VmResult<Value> {
443        let Some(Object::CharSet { name, map }) = self.objects.get(id) else {
444            return Ok(Value::Nil);
445        };
446        let known = map.is_some();
447        Ok(match index {
448            // getName()
449            1 => {
450                let name = name.clone();
451                self.try_new_str(&name)?
452            }
453            // isMappingKnown()
454            2 => Value::logical(known),
455            // isMappable(val) and isRoundTripMappable(val): of a
456            // character code, or of every character of a string.
457            _ => {
458                let map = self.charset_map(id)?;
459                let test = |c: char| {
460                    if index == 3 {
461                        map.is_mappable(c)
462                    } else {
463                        map.is_round_trip(c)
464                    }
465                };
466                let arg = self.arg(0);
467                if let Some(text) = self.as_str(arg) {
468                    Value::logical(String::from_utf8_lossy(&text).chars().all(test))
469                } else if let Value::Int(code_point) = arg {
470                    let c = u16::try_from(code_point)
471                        .ok()
472                        .and_then(|code| char::from_u32(code.into()));
473                    Value::logical(c.is_some_and(test))
474                } else {
475                    Value::Nil
476                }
477            }
478        })
479    }
480}