Skip to main content

hexicon_compiler/
dynamic.rs

1//! The dynamic compiler: code compiled while a program runs, as
2//! `CompiledCode` and the system library's `Compiler` object ask, against
3//! the names of the program that is running.
4//!
5//! The reference compiles such code as it compiles a program, with a few
6//! differences that come of there being no image to add to: strings are
7//! written into the code itself, lists are made when the code runs, a
8//! function is called at the address it already has, and each function
9//! nested in the code is an object of its own, which the code refers to
10//! by its number. The names come from the program's table of global
11//! names, and the macros from its table of macros.
12
13use std::collections::HashMap;
14
15use crate::pp::{LinkMacro, Severity, SourceFiles};
16
17/// What a global name stands for in the program that is running.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub enum DynSymbol {
20    /// An object.
21    Object {
22        /// Its number.
23        id: u32,
24        /// What kind of object it is, as far as the compiler cares.
25        kind: DynObjKind,
26    },
27    /// The object that stands for a class built into the VM.
28    Class {
29        /// The class's place in the image's list of classes.
30        meta_index: u16,
31        /// The object's number.
32        id: u32,
33    },
34    /// A property, by its number.
35    Property(u16),
36    /// A function.
37    Function {
38        /// Its address in the code.
39        addr: u32,
40        /// How many arguments it needs.
41        argc: usize,
42        /// How many more it can take.
43        opt_argc: usize,
44        /// It takes any number more.
45        varargs: bool,
46    },
47    /// A value of an enumeration, by its number.
48    Enum(u32),
49    /// A function built into the VM.
50    BuiltIn {
51        /// Its set.
52        set: u16,
53        /// Its place in the set.
54        index: u16,
55        /// How many arguments it needs.
56        min_argc: usize,
57        /// How many more it can take.
58        opt_argc: usize,
59        /// It takes any number more.
60        varargs: bool,
61    },
62}
63
64/// The kinds of object the compiler treats differently.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub enum DynObjKind {
67    /// An object the program defines.
68    ProgramObject,
69    /// An object that can be called like a function.
70    Invokable,
71    /// A grammar production.
72    GrammarRule,
73    /// A dictionary.
74    Dictionary,
75    /// An object that holds what the program adds to a built-in class.
76    ClassModifier,
77    /// Any other.
78    Other,
79}
80
81/// What the code is compiled against.
82#[derive(Debug, Clone, Default)]
83pub struct DynContext {
84    /// The global names.
85    pub symbols: Vec<(Vec<u8>, DynSymbol)>,
86    /// The macros.
87    pub macros: Vec<LinkMacro>,
88    /// The classes built into the VM that the image uses, in its order:
89    /// the VM's names for them, with their versions.
90    pub metaclasses: Vec<Vec<u8>>,
91    /// For each of those classes, the properties of its methods, the
92    /// first method's first.
93    pub metaclass_props: Vec<Vec<u16>>,
94    /// The variables of running functions the code can use, which hide
95    /// global names. Of two with one name, the first counts.
96    pub locals: Vec<DynLocal>,
97    /// The innermost of those functions has a `self`, which code given
98    /// as `function(...) { ... }` then has as well.
99    pub frame_has_self: bool,
100}
101
102/// A variable of a running function, which the code reads and sets
103/// through the object that stands for the function's call.
104#[derive(Debug, Clone)]
105pub struct DynLocal {
106    /// The variable's name.
107    pub name: Vec<u8>,
108    /// The number of the object that stands for the call.
109    pub frame_ref: u32,
110    /// The variable's number among the call's: its locals, then its
111    /// arguments.
112    pub number: u16,
113    /// For a variable shared with an anonymous function, its index in
114    /// the context object the variable holds; otherwise 0.
115    pub context: u16,
116}
117
118/// What of the method context of the function the code was compiled in
119/// the code uses.
120#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
121pub enum DynCtxUse {
122    /// None of it.
123    #[default]
124    None,
125    /// `self`.
126    SelfOnly,
127    /// All of it, as `loadctx` takes it.
128    Full,
129}
130
131/// How to read the source.
132#[derive(Debug, Clone, Copy, PartialEq, Eq)]
133pub enum DynMode {
134    /// `function(...) { ... }`, `method(...) { ... }`, or an expression,
135    /// whichever the source starts like.
136    Auto,
137    /// An expression.
138    Expression,
139}
140
141/// The code of one function compiled, and where in it the numbers of
142/// objects are.
143#[derive(Debug, Clone, PartialEq, Eq)]
144pub struct DynCode {
145    /// The function: its header, its code, and its tables.
146    pub code: Vec<u8>,
147    /// The offsets of the objects' numbers in it.
148    pub obj_refs: Vec<usize>,
149}
150
151/// What the dynamic compiler made.
152#[derive(Debug, Clone, PartialEq, Eq)]
153pub struct DynCompiled {
154    /// The functions, the one the source is first, then those nested in
155    /// it, each with the number given for it.
156    pub funcs: Vec<(u32, DynCode)>,
157    /// The source was `method(...) { ... }`.
158    pub is_method: bool,
159    /// What of the method context of the function it was compiled in the
160    /// code uses, which its object keeps for it.
161    pub ctx_use: DynCtxUse,
162}
163
164/// One way a phrase of a grammar production can be made up, as a rule
165/// compiled while the program runs gives it.
166#[derive(Debug, Clone, PartialEq, Eq)]
167pub struct DynGramAlt {
168    /// How much worse than another it is (`[badness 50]`).
169    pub badness: i16,
170    /// The things to match, in order.
171    pub toks: Vec<DynGramTok>,
172}
173
174/// One thing to match in a rule, and the property the match goes in, or
175/// 0.
176#[derive(Debug, Clone, PartialEq, Eq)]
177pub struct DynGramTok {
178    /// The property of the match object that gets what this matched.
179    pub prop: u16,
180    /// What it matches.
181    pub kind: DynGramMatch,
182}
183
184/// What one thing in a rule matches.
185#[derive(Debug, Clone, PartialEq, Eq)]
186pub enum DynGramMatch {
187    /// A word, as it is written.
188    Literal(Vec<u8>),
189    /// Any word the dictionary has for a property.
190    Speech(u16),
191    /// Any word the dictionary has for one of several properties.
192    SpeechList(Vec<u16>),
193    /// A phrase of another production: its object.
194    Prod(u32),
195    /// A token of a kind: its enumerator.
196    TokType(u32),
197    /// Whatever is left of the input.
198    Star,
199}
200
201/// Compile the rules of a grammar production, as `GrammarRule.addAlt`
202/// gives them: alternatives as a `grammar` statement has them before its
203/// colon, against the program's global names. The error messages, if it
204/// cannot, a line each.
205pub fn compile_grammar(source: &[u8], context: &DynContext) -> Result<Vec<DynGramAlt>, String> {
206    use crate::parse::GramTokKind;
207    let mut files = OneSource { text: source };
208    let mut pp = crate::pp::Preprocessor::new(&mut files);
209    pp.set_default_charset("utf-8");
210    if !pp.set_source(SOURCE_NAME) {
211        return Err("error: unable to read the source".to_owned());
212    }
213    pp.set_compile_mode();
214    let parser = crate::parse::Parser::new_dynamic(&mut pp, context);
215    let (prog, alts) = parser.parse_dynamic_grammar();
216    let mut messages: Vec<String> = pp
217        .take_diagnostics()
218        .into_iter()
219        .filter(|d| {
220            matches!(
221                d.severity,
222                Severity::Error | Severity::Fatal | Severity::Internal
223            )
224        })
225        .map(|d| format!("error: {}", d.message))
226        .collect();
227    let known = prog
228        .dynamic
229        .as_ref()
230        .map_or(0, |dynamic| dynamic.known_props);
231    for prop in &prog.props[known..] {
232        messages.push(format!(
233            "error: undefined name \"{}\"",
234            crate::pp::show_name(&prop.name)
235        ));
236    }
237    let Some(alts) = alts else {
238        return Err(messages.join("\n"));
239    };
240    if !messages.is_empty() {
241        return Err(messages.join("\n"));
242    }
243    let enum_ids = prog
244        .dynamic
245        .as_ref()
246        .map(|dynamic| dynamic.enum_ids.clone())
247        .unwrap_or_default();
248    let prop_id = |prop: usize| prog.props[prop].id;
249    Ok(alts
250        .into_iter()
251        .map(|alt| DynGramAlt {
252            badness: alt.badness as i16,
253            toks: alt
254                .toks
255                .into_iter()
256                .map(|tok| DynGramTok {
257                    prop: tok.prop.map_or(0, prop_id),
258                    kind: match tok.kind {
259                        GramTokKind::Literal(text) => DynGramMatch::Literal(text),
260                        GramTokKind::Speech(prop) => DynGramMatch::Speech(prop_id(prop)),
261                        GramTokKind::SpeechList(props) => {
262                            DynGramMatch::SpeechList(props.into_iter().map(prop_id).collect())
263                        }
264                        GramTokKind::Prod(obj) => DynGramMatch::Prod(prog.objs[obj].id),
265                        GramTokKind::TokType(sym) => {
266                            DynGramMatch::TokType(enum_ids.get(sym).copied().unwrap_or(0))
267                        }
268                        GramTokKind::Star => DynGramMatch::Star,
269                    },
270                })
271                .collect(),
272        })
273        .collect())
274}
275
276/// A value the compiler gives a property of an object it has the
277/// program make.
278#[derive(Debug, Clone)]
279pub enum DynValue {
280    /// An integer.
281    Int(i32),
282    /// A string.
283    Str(Vec<u8>),
284}
285
286/// What the compiler asks of the program that is running.
287pub trait DynHost {
288    /// Numbers for so many new objects, which the compiled functions are
289    /// to be: the code refers to them by these.
290    fn new_func_ids(&mut self, count: usize) -> Vec<u32>;
291
292    /// Make an object of the program's own kind, of the class given, with
293    /// the properties given, and say its number. The code refers to it.
294    fn new_object(&mut self, class: u32, props: &[(u16, DynValue)]) -> u32;
295}
296
297/// A source held in memory, for the preprocessor to read.
298struct OneSource<'s> {
299    text: &'s [u8],
300}
301
302/// The name the source goes by, which no file has.
303const SOURCE_NAME: &str = "";
304
305impl SourceFiles for OneSource<'_> {
306    fn read(&mut self, name: &str) -> Option<Vec<u8>> {
307        (name == SOURCE_NAME).then(|| self.text.to_vec())
308    }
309
310    fn exists(&mut self, name: &str) -> bool {
311        name == SOURCE_NAME
312    }
313}
314
315/// Compile source code while a program runs. A failure is the messages
316/// the reference gives, a line each.
317pub fn compile_dynamic(
318    source: &[u8],
319    context: &DynContext,
320    mode: DynMode,
321    host: &mut dyn DynHost,
322) -> Result<DynCompiled, String> {
323    let mut files = OneSource { text: source };
324    let mut pp = crate::pp::Preprocessor::new(&mut files);
325    pp.set_default_charset("utf-8");
326    for mac in &context.macros {
327        pp.define_macro(mac);
328    }
329    if !pp.set_source(SOURCE_NAME) {
330        return Err("error: unable to read the source".to_owned());
331    }
332    pp.set_compile_mode();
333    let parser = crate::parse::Parser::new_dynamic(&mut pp, context);
334    let (mut prog, parsed) = parser.parse_dynamic(mode);
335    // Only errors are reported: a line each.
336    let mut messages = Vec::new();
337    let note = |messages: &mut Vec<String>, severity: Severity, message: &str| {
338        if matches!(
339            severity,
340            Severity::Error | Severity::Fatal | Severity::Internal
341        ) {
342            messages.push(format!("error: {message}"));
343        }
344    };
345    for diagnostic in pp.take_diagnostics() {
346        note(&mut messages, diagnostic.severity, &diagnostic.message);
347    }
348    let Some(is_method) = parsed else {
349        return Err(messages.join("\n"));
350    };
351    if !messages.is_empty() {
352        return Err(messages.join("\n"));
353    }
354
355    // The objects the code needs, such as those that choose among the
356    // alternatives of a `<<one of>>`, are made before its functions.
357    if let Some(dynamic) = prog.dynamic.as_mut() {
358        for (index, (class, props)) in std::mem::take(&mut dynamic.gen_objs)
359            .into_iter()
360            .enumerate()
361        {
362            let props: Vec<(u16, DynValue)> = props
363                .into_iter()
364                .map(|(prop, value)| (prog.props[prop].id, value))
365                .collect();
366            let id = host.new_object(class, &props);
367            dynamic.gen_obj_ids.insert(gen_obj_id(index), id);
368        }
369    }
370
371    // A number for each function: the one the source is, then those in
372    // it, in the order they will be made.
373    let bodies: Vec<usize> = prog
374        .top
375        .iter()
376        .filter_map(|item| match item {
377            crate::parse::Top::Func(body) => Some(*body),
378            crate::parse::Top::Obj(_) => None,
379        })
380        .collect();
381    let ids = host.new_func_ids(bodies.len());
382    if let Some(dynamic) = prog.dynamic.as_mut() {
383        dynamic.body_ids = bodies.iter().copied().zip(ids.iter().copied()).collect();
384    }
385
386    // Code given as a function, where the function it is compiled in has
387    // a `self`, takes that function's method context as its own.
388    let mut ctx_use = DynCtxUse::None;
389    if let Some(&main) = bodies.first() {
390        let body = &prog.bodies[main].0;
391        if context.frame_has_self && !is_method && body.self_valid {
392            if body.closure.full_ctx_referenced {
393                ctx_use = DynCtxUse::Full;
394            } else if body.closure.self_referenced {
395                ctx_use = DynCtxUse::SelfOnly;
396            }
397        }
398        if let Some(dynamic) = prog.dynamic.as_mut() {
399            dynamic.main_ctx = (main, ctx_use);
400        }
401    }
402
403    // Code compiled while the program runs has no source file of its
404    // own to point to, so it has no line records.
405    let generated = crate::emit::generate(&mut prog, false, false, 0);
406    for diagnostic in &generated.diagnostics {
407        note(&mut messages, diagnostic.severity, &diagnostic.message);
408    }
409    // No name can be made in code compiled while the program runs: a
410    // name that is nothing in the program is not a property, as it would
411    // be in a program being compiled.
412    let known = prog
413        .dynamic
414        .as_ref()
415        .map_or(0, |dynamic| dynamic.known_props);
416    for prop in &prog.props[known..] {
417        messages.push(format!(
418            "error: undefined name \"{}\"",
419            crate::pp::show_name(&prop.name)
420        ));
421    }
422    if !messages.is_empty() {
423        return Err(messages.join("\n"));
424    }
425    if !generated.fixups.is_empty() || !generated.consts.is_empty() {
426        return Err("error: this code cannot be compiled while the program runs yet".to_owned());
427    }
428
429    // Each function's code runs from its place to the next one's.
430    let code = &generated.code;
431    let mut funcs = Vec::new();
432    for (index, &body) in bodies.iter().enumerate() {
433        let Some(&anchor) = generated.body_anchor.get(&body) else {
434            continue;
435        };
436        let start = generated.code_anchors[anchor].ofs;
437        let end = generated
438            .code_anchors
439            .get(anchor + 1)
440            .map_or(code.len(), |next| next.ofs);
441        let obj_refs = generated
442            .id_fixups
443            .iter()
444            .filter(|(ofs, kind)| *kind == crate::emit::IdKind::Obj && (start..end).contains(ofs))
445            .map(|(ofs, _)| ofs - start)
446            .collect();
447        funcs.push((
448            ids[index],
449            DynCode {
450                code: code[start..end].to_vec(),
451                obj_refs,
452            },
453        ));
454    }
455    Ok(DynCompiled {
456        funcs,
457        is_method,
458        ctx_use,
459    })
460}
461
462/// The number the code has for an object it needs until the program
463/// has made it.
464pub(crate) fn gen_obj_id(index: usize) -> u32 {
465    0xF000_0000 + index as u32
466}
467
468/// What the parser and code generator keep for dynamic code.
469#[derive(Debug, Default, Clone)]
470pub(crate) struct DynProgram {
471    /// The functions of the running program, by their index in the
472    /// program's functions: their addresses.
473    pub func_addrs: HashMap<usize, u32>,
474    /// The number each value of an enumeration has.
475    pub enum_ids: Vec<u32>,
476    /// The number of the object each function compiled is, by its body.
477    pub body_ids: HashMap<usize, u32>,
478    /// How many properties the program has: any made after these are for
479    /// names it does not have.
480    pub known_props: usize,
481    /// The variables of running functions: the object for the call, the
482    /// variable's number, and its index in a context object or 0.
483    pub locals: Vec<(u32, u16, u16)>,
484    /// The innermost running function has a `self`.
485    pub frame_has_self: bool,
486    /// The properties of the methods of each class built into the VM
487    /// that the image uses.
488    pub meta_props: Vec<Vec<u16>>,
489    /// The objects the code needs, to be made before code is generated:
490    /// each one's class, and its properties, by index into the program's
491    /// properties, with their values.
492    pub gen_objs: Vec<(u32, Vec<(usize, DynValue)>)>,
493    /// The numbers of those objects, by the number the code has for each
494    /// until it is made.
495    pub gen_obj_ids: HashMap<u32, u32>,
496    /// The objects that can be called as functions, such as functions
497    /// compiled before: indexes into the program's objects.
498    pub func_objs: std::collections::HashSet<usize>,
499    /// The body the source is, and what of the method context it takes
500    /// from the function it was compiled in.
501    pub main_ctx: (usize, DynCtxUse),
502}