interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / crates / allen-courier / src / code.rs

245 lines · 8203 bytes Raw Blame History
1//! Code from the Spark (native/kernel/svc/allen_code.h): a coding request's
2//! answer as the kernel takes it. The model answers with a short sentence and
3//! one fenced code block; the code is made plain (tabs to spaces, anything
4//! outside printable ASCII to '?'), held to the stated limits, and cut into
5//! numbered pieces with its length and checksum:
6//! "CODE <seq> <i>/<n> <bytes> <crc32> <lang|-> <piece>" piece: 128 bytes of code, "\n" and "\\" escaped
7//! "SAY <seq> 1/1 <sentence>" closes the answer
8//! Pure functions only; the wire and the model are in main.rs.
9
10/// Bytes of code at most (allen_code.h CK_CODE_MAX).
11pub const CODE_MAX: usize = 32768;
12/// Lines of code at most (CK_CODE_LINES).
13pub const CODE_LINES: usize = 800;
14/// Code bytes per piece (CK_CODE_PIECE).
15pub const PIECE: usize = 128;
16/// Language name bytes at most (CK_CODE_LANG - 1).
17pub const LANG_MAX: usize = 15;
18
19/// CRC-32 (IEEE 802.3, reflected, as zlib's crc32 and the kernel's ck_code_crc32).
20pub fn crc32(b: &[u8]) -> u32 {
21 let mut c = 0xffff_ffffu32;
22 for &x in b {
23 c ^= x as u32;
24 for _ in 0..8 {
25 c = if c & 1 != 0 {
26 (c >> 1) ^ 0xedb8_8320
27 } else {
28 c >> 1
29 };
30 }
31 }
32 !c
33}
34
35/// What the model's reply holds once read: Allen's sentence, the language, the code.
36#[derive(Debug, PartialEq)]
37pub struct Reply {
38 pub sentence: String,
39 pub lang: String,
40 pub code: String,
41 /// lines left off to keep within the limits (0: the code is whole)
42 pub cut_lines: usize,
43}
44
45/// The code made plain: CR dropped, tabs to four spaces, other control bytes
46/// and anything outside printable ASCII to '?'; one newline at the end.
47pub fn plain_code(s: &str) -> String {
48 let mut o = String::with_capacity(s.len());
49 for ch in s.chars() {
50 match ch {
51 '\r' => {}
52 '\n' => o.push('\n'),
53 '\t' => o.push_str(" "),
54 ' '..='~' => o.push(ch),
55 _ => o.push('?'),
56 }
57 }
58 let t = o.trim_end_matches('\n').trim_start_matches('\n');
59 let mut t = t.to_string();
60 if !t.is_empty() {
61 t.push('\n');
62 }
63 t
64}
65
66/// The language named after the opening fence, as one word of [a-z0-9+#._-].
67fn lang_of(word: &str) -> String {
68 let w = word.trim().to_ascii_lowercase();
69 let w = match w.as_str() {
70 "py" | "python3" => "python".to_string(),
71 "js" => "javascript".to_string(),
72 "ts" => "typescript".to_string(),
73 "sh" | "shell" | "zsh" => "bash".to_string(),
74 "c++" => "cpp".to_string(),
75 "rs" => "rust".to_string(),
76 _ => w,
77 };
78 w.chars()
79 .take_while(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || "+#._-".contains(*c))
80 .take(LANG_MAX)
81 .collect()
82}
83
84/// Keeps code within CODE_MAX bytes and CODE_LINES lines, cut at a line end.
85/// Returns the code kept and the lines left off.
86pub fn within_limits(code: &str) -> (String, usize) {
87 let all = code.lines().count();
88 let mut kept = String::new();
89 let mut n = 0;
90 for line in code.lines() {
91 if n == CODE_LINES || kept.len() + line.len() + 1 > CODE_MAX {
92 break;
93 }
94 kept.push_str(line);
95 kept.push('\n');
96 n += 1;
97 }
98 (kept, all - n)
99}
100
101/// Reads the model's reply: the words before the first fence are the
102/// sentence, the first fenced block the code (to its closing fence, or to the
103/// end when the model stopped short). None when there is no code at all.
104pub fn read_reply(reply: &str) -> Option<Reply> {
105 let open = reply.find("```")?;
106 let before = reply[..open].trim();
107 let after = &reply[open + 3..];
108 let (first, body) = match after.find('\n') {
109 Some(e) => (&after[..e], &after[e + 1..]),
110 None => (after, ""),
111 };
112 let lang = lang_of(first.split_whitespace().next().unwrap_or(""));
113 // the closing fence: "```" at the start of a line
114 let mut end = body.len();
115 let mut at = 0;
116 for line in body.split_inclusive('\n') {
117 if line.trim_start().starts_with("```") {
118 end = at;
119 break;
120 }
121 at += line.len();
122 }
123 let code = plain_code(&body[..end]);
124 if code.trim().is_empty() {
125 return None;
126 }
127 let (code, cut_lines) = within_limits(&code);
128 Some(Reply {
129 sentence: before.to_string(),
130 lang,
131 code,
132 cut_lines,
133 })
134}
135
136/// "\n" and "\\" escaped, as the kernel's ck_code_take reads them.
137fn escape(piece: &[u8]) -> String {
138 let mut o = String::with_capacity(piece.len() + 8);
139 for &b in piece {
140 match b {
141 b'\n' => o.push_str("\\n"),
142 b'\\' => o.push_str("\\\\"),
143 _ => o.push(b as char),
144 }
145 }
146 o
147}
148
149/// The CODE lines for job seq: every piece CODE_PIECE bytes but the last.
150pub fn pieces(seq: u32, code: &str, lang: &str) -> Vec<String> {
151 let b = code.as_bytes();
152 if b.is_empty() {
153 return Vec::new();
154 }
155 let n = b.len().div_ceil(PIECE);
156 let crc = crc32(b);
157 let lang = if lang.is_empty() { "-" } else { lang };
158 b.chunks(PIECE)
159 .enumerate()
160 .map(|(i, p)| {
161 format!(
162 "CODE {} {}/{} {} {:08x} {} {}",
163 seq,
164 i + 1,
165 n,
166 b.len(),
167 crc,
168 lang,
169 escape(p)
170 )
171 })
172 .collect()
173}
174
175#[cfg(test)]
176mod tests {
177 use super::*;
178
179 #[test]
180 fn crc_is_zlibs() {
181 assert_eq!(crc32(b"123456789"), 0xcbf4_3926);
182 assert_eq!(crc32(b""), 0);
183 }
184
185 #[test]
186 fn a_sentence_and_a_fenced_block_are_read() {
187 let r = read_reply(
188 "Here is a small calculator.\n\n```python\nprint(1 + 1)\n\tx = 2\n```\nEnjoy.",
189 )
190 .unwrap();
191 assert_eq!(r.sentence, "Here is a small calculator.");
192 assert_eq!(r.lang, "python");
193 assert_eq!(r.code, "print(1 + 1)\n x = 2\n");
194 assert_eq!(r.cut_lines, 0);
195 }
196
197 #[test]
198 fn short_names_and_odd_bytes_are_made_plain() {
199 let r = read_reply("```py\nprint(\"\u{201c}hi\u{201d}\")\r\n```").unwrap();
200 assert_eq!(r.lang, "python");
201 assert_eq!(r.code, "print(\"?hi?\")\n");
202 assert_eq!(r.sentence, "");
203 assert_eq!(read_reply("```c++\nint main(){}\n```").unwrap().lang, "cpp");
204 }
205
206 #[test]
207 fn an_unclosed_block_runs_to_the_end_and_no_block_is_none() {
208 assert_eq!(
209 read_reply("Sure.\n```c\nint main(void) {\n").unwrap().code,
210 "int main(void) {\n"
211 );
212 assert!(read_reply("I would rather not.").is_none());
213 assert!(read_reply("```\n\n```").is_none());
214 }
215
216 #[test]
217 fn long_code_is_cut_at_a_line_within_the_limits() {
218 let long: String = (0..1000).map(|i| format!("x = {}\n", i)).collect();
219 let r = read_reply(&format!("```python\n{}```", long)).unwrap();
220 assert_eq!(r.code.lines().count(), CODE_LINES);
221 assert_eq!(r.cut_lines, 200);
222 let wide: String = (0..400).map(|_| format!("{}\n", "y".repeat(100))).collect();
223 let (k, cut) = within_limits(&wide);
224 assert!(k.len() <= CODE_MAX && k.ends_with('\n'));
225 assert_eq!(k.lines().count() + cut, 400);
226 }
227
228 #[test]
229 fn pieces_carry_length_checksum_and_escapes() {
230 let code = "a\\b\n".repeat(40); // 160 bytes: two pieces
231 let p = pieces(7, &code, "c");
232 assert_eq!(p.len(), 2);
233 let crc = format!("{:08x}", crc32(code.as_bytes()));
234 assert!(p[0].starts_with(&format!("CODE 7 1/2 160 {} c ", crc)));
235 assert!(p[1].starts_with(&format!("CODE 7 2/2 160 {} c ", crc)));
236 assert!(p[0].contains("a\\\\b\\n"));
237 // every line fits the kernel's line (CK_COURIER_LINE_MAX 320, with its NUL)
238 let worst = "\\".repeat(CODE_MAX);
239 for l in pieces(4_000_000_000, &worst, "objective-c++") {
240 assert!(l.len() < 320, "{}", l.len());
241 }
242 assert!(pieces(1, "", "c").is_empty());
243 assert!(pieces(1, "x\n", "").pop().unwrap().contains(" - x\\n"));
244 }
245}