aienux
Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
aienux / crates / allen-reflex / src / text.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! Tokenizer that keeps the original bytes: every token records its byte range in the |
| 17 | //! message, so an argument is always copied from the operator's own text (case and |
| 18 | //! inner punctuation preserved), never rebuilt from normalized words. |
| 19 | |
| 20 | use alloc::string::String; |
| 21 | use alloc::vec::Vec; |
| 22 | |
| 23 | /// Punctuation seen in the gap before a token. |
| 24 | pub mod gap { |
| 25 | /// `.`, `!` or `?` (end of a sentence). |
| 26 | pub const STOP: u8 = 1; |
| 27 | /// `,` |
| 28 | pub const COMMA: u8 = 2; |
| 29 | /// `:` |
| 30 | pub const COLON: u8 = 4; |
| 31 | /// `;` |
| 32 | pub const SEMI: u8 = 8; |
| 33 | /// a free-standing dash (`-`, `--`). |
| 34 | pub const DASH: u8 = 16; |
| 35 | /// `?` specifically. |
| 36 | pub const QUESTION: u8 = 32; |
| 37 | } |
| 38 | |
| 39 | /// One word of the message. |
| 40 | #[derive(Clone, Debug)] |
| 41 | pub struct Token { |
| 42 | /// Byte offset of the first byte in the original message. |
| 43 | pub start: usize, |
| 44 | /// Byte offset one past the last byte. |
| 45 | pub end: usize, |
| 46 | /// Lower-case form (contractions expanded; curly apostrophe made ASCII). |
| 47 | pub word: String, |
| 48 | /// Crude stem used for features. |
| 49 | pub stem: String, |
| 50 | /// Punctuation in the gap before this token (see [`gap`]). |
| 51 | pub gap: u8, |
| 52 | /// True if the token has at least one ASCII letter or digit. |
| 53 | pub alnum: bool, |
| 54 | } |
| 55 | |
| 56 | /// Bytes that end or start a token when they sit at its edge. |
| 57 | fn edge_punct(b: u8) -> bool { |
| 58 | matches!( |
| 59 | b, |
| 60 | b'.' | b',' |
| 61 | | b';' |
| 62 | | b':' |
| 63 | | b'!' |
| 64 | | b'?' |
| 65 | | b'"' |
| 66 | | b'\'' |
| 67 | | b'(' |
| 68 | | b')' |
| 69 | | b'[' |
| 70 | | b']' |
| 71 | | b'{' |
| 72 | | b'}' |
| 73 | | b'-' |
| 74 | | b'`' |
| 75 | | b'*' |
| 76 | ) |
| 77 | } |
| 78 | |
| 79 | fn gap_flags(s: &[u8]) -> u8 { |
| 80 | let mut f = 0; |
| 81 | for (i, &b) in s.iter().enumerate() { |
| 82 | f |= match b { |
| 83 | b'.' | b'!' => gap::STOP, |
| 84 | b'?' => gap::STOP | gap::QUESTION, |
| 85 | b',' => gap::COMMA, |
| 86 | b':' => gap::COLON, |
| 87 | b';' => gap::SEMI, |
| 88 | b'-' => { |
| 89 | // a dash counts only when free-standing (spaces around it) |
| 90 | let l = i == 0 || s[i - 1] == b' ' || s[i - 1] == b'-'; |
| 91 | let r = i + 1 == s.len() || s[i + 1] == b' ' || s[i + 1] == b'-'; |
| 92 | if l && r { |
| 93 | gap::DASH |
| 94 | } else { |
| 95 | 0 |
| 96 | } |
| 97 | } |
| 98 | _ => 0, |
| 99 | }; |
| 100 | } |
| 101 | f |
| 102 | } |
| 103 | |
| 104 | /// Lower-case ASCII; curly apostrophes (U+2019, U+2018) become `'`. |
| 105 | fn lower(s: &str) -> String { |
| 106 | let mut o = String::with_capacity(s.len()); |
| 107 | for c in s.chars() { |
| 108 | match c { |
| 109 | '\u{2019}' | '\u{2018}' => o.push('\''), |
| 110 | _ => o.push(c.to_ascii_lowercase()), |
| 111 | } |
| 112 | } |
| 113 | o |
| 114 | } |
| 115 | |
| 116 | /// Contraction expansion: returns up to two words. |
| 117 | fn expand(w: &str) -> (String, Option<&'static str>) { |
| 118 | const SUF: [(&str, &str, &str); 9] = [ |
| 119 | ("can't", "can", "not"), |
| 120 | ("won't", "will", "not"), |
| 121 | ("n't", "", "not"), |
| 122 | ("'m", "", "am"), |
| 123 | ("'re", "", "are"), |
| 124 | ("'ll", "", "will"), |
| 125 | ("'ve", "", "have"), |
| 126 | ("'d", "", "would"), |
| 127 | ("'s", "", ""), |
| 128 | ]; |
| 129 | for (suf, head, tail) in SUF { |
| 130 | if w.len() > suf.len() && w.ends_with(suf) { |
| 131 | let base = if head.is_empty() { |
| 132 | String::from(&w[..w.len() - suf.len()]) |
| 133 | } else { |
| 134 | String::from(head) |
| 135 | }; |
| 136 | if base.is_empty() { |
| 137 | break; |
| 138 | } |
| 139 | return (base, if tail.is_empty() { None } else { Some(tail) }); |
| 140 | } |
| 141 | } |
| 142 | (String::from(w), None) |
| 143 | } |
| 144 | |
| 145 | /// Very small suffix stripper (features only; never used for copying text). |
| 146 | pub fn stem(w: &str) -> String { |
| 147 | let n = w.len(); |
| 148 | let b = w.as_bytes(); |
| 149 | if !b.iter().all(|c| c.is_ascii_alphabetic()) || n <= 3 { |
| 150 | return String::from(w); |
| 151 | } |
| 152 | if n > 5 && w.ends_with("ing") { |
| 153 | return String::from(&w[..n - 3]); |
| 154 | } |
| 155 | if n > 4 && w.ends_with("ies") { |
| 156 | let mut s = String::from(&w[..n - 3]); |
| 157 | s.push('y'); |
| 158 | return s; |
| 159 | } |
| 160 | if n > 4 && w.ends_with("ed") && !w.ends_with("eed") { |
| 161 | return String::from(&w[..n - 2]); |
| 162 | } |
| 163 | if w.ends_with('s') && !w.ends_with("ss") && !w.ends_with("us") && !w.ends_with("is") { |
| 164 | return String::from(&w[..n - 1]); |
| 165 | } |
| 166 | String::from(w) |
| 167 | } |
| 168 | |
| 169 | /// Split a message into tokens. Bounded by `max_tokens`. |
| 170 | pub fn tokenize(msg: &str, max_tokens: usize) -> Vec<Token> { |
| 171 | let b = msg.as_bytes(); |
| 172 | let mut out = Vec::new(); |
| 173 | let mut i = 0; |
| 174 | let mut gap_start = 0; |
| 175 | while i < b.len() && out.len() < max_tokens { |
| 176 | if b[i].is_ascii_whitespace() { |
| 177 | i += 1; |
| 178 | continue; |
| 179 | } |
| 180 | // a whitespace-delimited chunk |
| 181 | let cs = i; |
| 182 | while i < b.len() && !b[i].is_ascii_whitespace() { |
| 183 | i += 1; |
| 184 | } |
| 185 | let ce = i; |
| 186 | let mut s = cs; |
| 187 | let mut e = ce; |
| 188 | while s < e && edge_punct(b[s]) { |
| 189 | s += 1; |
| 190 | } |
| 191 | while e > s && edge_punct(b[e - 1]) { |
| 192 | e -= 1; |
| 193 | } |
| 194 | if s == e { |
| 195 | continue; // pure punctuation: stays in the gap |
| 196 | } |
| 197 | // keep the slice on char boundaries (edge_punct bytes are ASCII, so this holds) |
| 198 | let raw = &msg[s..e]; |
| 199 | let g = gap_flags(&b[gap_start..s]); |
| 200 | gap_start = e; |
| 201 | let lw = lower(raw); |
| 202 | let alnum = lw.bytes().any(|c| c.is_ascii_alphanumeric()); |
| 203 | let (w1, w2) = expand(&lw); |
| 204 | let st = stem(&w1); |
| 205 | out.push(Token { |
| 206 | start: s, |
| 207 | end: e, |
| 208 | word: w1, |
| 209 | stem: st, |
| 210 | gap: g, |
| 211 | alnum, |
| 212 | }); |
| 213 | if let Some(t) = w2 { |
| 214 | if out.len() < max_tokens { |
| 215 | out.push(Token { |
| 216 | start: s, |
| 217 | end: e, |
| 218 | word: String::from(t), |
| 219 | stem: String::from(t), |
| 220 | gap: 0, |
| 221 | alnum: true, |
| 222 | }); |
| 223 | } |
| 224 | } |
| 225 | } |
| 226 | out |
| 227 | } |
| 228 | |
| 229 | /// Punctuation flags after the last token (end of message). |
| 230 | pub fn tail_gap(msg: &str, toks: &[Token]) -> u8 { |
| 231 | let from = toks.last().map(|t| t.end).unwrap_or(0); |
| 232 | gap_flags(&msg.as_bytes()[from..]) |
| 233 | } |
| 234 | |
| 235 | /// FNV-1a 64-bit hash. |
| 236 | pub fn fnv(s: &[u8]) -> u64 { |
| 237 | let mut h: u64 = 0xcbf2_9ce4_8422_2325; |
| 238 | for &c in s { |
| 239 | h ^= c as u64; |
| 240 | h = h.wrapping_mul(0x0000_0100_0000_01b3); |
| 241 | } |
| 242 | h |
| 243 | } |