Skip to main content

yomi_core/
compile.rs

1//! Compilation: turns the syntax tree into bytecode while checking types.
2
3use std::collections::{HashMap, HashSet};
4
5use crate::backend::Backend as _;
6use crate::backend::register::{MAX_REGS, RegBackend, TooManyRegisters};
7use crate::diag::{DiagArg, DiagCode, Diagnostic, Severity};
8use crate::ir::{
9    Body, Builtin, Choice, ChoiceOpt as IrChoiceOpt, ExprId, ExprKind, ForKind, IfArm, Ir,
10    MatchArm as IrArm, Method, Operand, PatTest, StmtId, StmtKind, Stop, StopArg, Tail, TextPiece,
11};
12use crate::program::{
13    Action, ArithOp, CallSite, ChoiceInfo, ChoiceOptInfo, FnCode, GlobalInfo, IdSite, IdentityInfo,
14    LabelCode, LocalInfo, PathStep, PlaceRef, Program, RegCode, StopInfo, StopKind, TextArg,
15    TextPart, fnv1a,
16};
17use crate::registry::{Binding, CommandKind, Registry};
18use crate::suggest::suggest;
19use crate::syntax::ast::{
20    AssignOp, BinOp, ChoiceOpt, CommandCall, Expr, FieldInit, IdentRef, IdentityDecl, LabelCall,
21    LabelDecl, LabelRef, MatchArm, Module, PathElem, Pattern, Pos, StableId, Stmt, StrPart, TyName,
22    TypeDeclKind, TypeRef, UnOp, VarDecl,
23};
24use crate::syntax::keywords::is_reserved;
25use crate::syntax::parser::{IdentMap, parse_with, scan_identities};
26use crate::value::{
27    Identity, MAX_TYPE_DEPTH, Ty, TypeDecl, TypeKind, Value, VariantDecl, find_type, finite_float,
28};
29
30/// Compiles the source of one module. Diagnostics are returned in position order. If there is any error, `Err`.
31///
32/// Warnings are dropped. To receive warnings as well, use [`compile_with_warnings`]. For multiple modules, use
33/// [`compile_modules`].
34pub fn compile(
35    source: &str,
36    module: &str,
37    registry: &Registry,
38) -> Result<Program, Vec<Diagnostic>> {
39    compile_with_warnings(source, module, registry).map(|(program, _)| program)
40}
41
42/// Compiles the source of one module. On success, returns the program and the warnings (in position order).
43///
44/// If there is any error, `Err`. In that case the diagnostics include the warnings too (in position order).
45pub fn compile_with_warnings(
46    source: &str,
47    module: &str,
48    registry: &Registry,
49) -> Result<(Program, Vec<Diagnostic>), Vec<Diagnostic>> {
50    compile_modules_with_warnings(&[(module, source)], registry)
51}
52
53/// Compiles multiple modules (`(module name, source)`) into one program.
54///
55/// Module names are identifiers and must not collide. Reading files is done by the host (the core does not read files).
56/// Cyclic `import`s can be written, because they are resolved after all modules are read.
57/// Diagnostics are returned in the order the modules were given, and in position order within each. Warnings are dropped.
58/// To receive warnings as well, use [`compile_modules_with_warnings`].
59pub fn compile_modules(
60    modules: &[(&str, &str)],
61    registry: &Registry,
62) -> Result<Program, Vec<Diagnostic>> {
63    compile_modules_with_warnings(modules, registry).map(|(program, _)| program)
64}
65
66/// Compile options. Built from `Default` with methods.
67#[derive(Debug, Clone, Default)]
68#[non_exhaustive]
69pub struct CompileOptions {
70    /// Labels that the host starts from outside (`module.label`; if there is only one module, just the label name also works).
71    /// They are excluded from the warning `label_falls_through` (spec 4.5). When empty, labels named `start` are excluded as
72    /// start labels (the default of `VmConfig::start`).
73    pub entry_labels: Vec<String>,
74    /// Makes plain lines, quote lines and option texts without a stable ID a compile error (`missing_text_id`). Text
75    /// replacement (localization; `spec/host/05-texts.md`) is keyed by stable IDs, so enable this for scripts that will be
76    /// translated. Disabled by default. It is checked as a writing rule even with a registry that ignores the sugar.
77    pub require_text_ids: bool,
78    /// The content of `migrations.yomi` (`spec/language/07-migrate.md`).
79    pub migrations: Option<String>,
80    /// Frozen schema files (path such as `schema/v2.yomi`, content).
81    pub frozen_schemas: Vec<(String, String)>,
82}
83
84impl CompileOptions {
85    /// Sets whether text lines without a stable ID are errors ([`CompileOptions::require_text_ids`]).
86    pub fn require_text_ids(mut self, on: bool) -> Self {
87        self.require_text_ids = on;
88        self
89    }
90
91    /// Sets the content of `migrations.yomi`. It can be given once.
92    pub fn migrations(mut self, source: &str) -> Self {
93        self.migrations = Some(source.to_string());
94        self
95    }
96
97    /// Adds a frozen schema file. `path` is relative to the project root, like `schema/v2.yomi`.
98    pub fn frozen_schema_file(mut self, path: &str, source: &str) -> Self {
99        self.frozen_schemas
100            .push((path.to_string(), source.to_string()));
101        self
102    }
103
104    /// Adds one start label (`module.label`).
105    pub fn entry_label(mut self, label: &str) -> Self {
106        self.entry_labels.push(label.to_string());
107        self
108    }
109}
110
111/// The type of a local variable (bound by `let`, `for` or `match`) as decided by the compiler. For editors and tools.
112#[derive(Clone, Debug, PartialEq, Eq)]
113pub struct LocalType {
114    /// Module name.
115    pub module: String,
116    /// The line of the name (1-based).
117    pub line: u32,
118    /// The column of the name (1-based, in characters).
119    pub col: u32,
120    /// The type (`int`, `list<str>`, `module.TypeName`).
121    pub ty: String,
122}
123
124/// Finds the types of local variables. Even if compilation fails, returns those whose types were decided.
125pub fn infer_local_types(modules: &[(&str, &str)], registry: &Registry) -> Vec<LocalType> {
126    let mut types = Vec::new();
127    let _ = compile_modules_core(
128        modules,
129        registry,
130        &CompileOptions::default(),
131        &mut Vec::new(),
132        &mut types,
133        None,
134        &mut None,
135    );
136    types
137}
138
139/// A version of [`compile_modules`] that also returns warnings. When it fails with errors, the diagnostics include the
140/// warnings too.
141///
142/// Uses the default options ([`CompileOptions::default`]). With options, use [`compile_modules_with_options`].
143pub fn compile_modules_with_warnings(
144    modules: &[(&str, &str)],
145    registry: &Registry,
146) -> Result<(Program, Vec<Diagnostic>), Vec<Diagnostic>> {
147    compile_modules_with_options(modules, registry, &CompileOptions::default())
148}
149
150/// A version of [`compile_modules_with_warnings`] with options.
151pub fn compile_modules_with_options(
152    modules: &[(&str, &str)],
153    registry: &Registry,
154    options: &CompileOptions,
155) -> Result<(Program, Vec<Diagnostic>), Vec<Diagnostic>> {
156    compile_modules_impl(modules, registry, options, &mut Vec::new())
157}
158
159/// The result of compilation, and the lines that can have stable IDs when it failed.
160pub(crate) type SitedResult = (
161    Result<(Program, Vec<Diagnostic>), Vec<Diagnostic>>,
162    Vec<IdSite>,
163);
164
165/// In addition to [`compile_modules_with_options`], also returns the lines that can have stable IDs when compilation
166/// fails (used by `assign-ids` to find where to add IDs when the only errors are caused by missing IDs). Empty on success.
167pub(crate) fn compile_modules_with_sites(
168    modules: &[(&str, &str)],
169    registry: &Registry,
170    options: &CompileOptions,
171) -> SitedResult {
172    let mut failed_sites = Vec::new();
173    let result = compile_modules_impl(modules, registry, options, &mut failed_sites);
174    (result, failed_sites)
175}
176
177/// The body that compiles multiple modules in order. On success, the program and warnings. On failure, the diagnostics
178/// (errors and warnings). When compilation fails, adds the lines that can have stable IDs to `failed_sites` (for
179/// `assign-ids`).
180fn compile_modules_impl(
181    modules: &[(&str, &str)],
182    registry: &Registry,
183    options: &CompileOptions,
184    failed_sites: &mut Vec<IdSite>,
185) -> Result<(Program, Vec<Diagnostic>), Vec<Diagnostic>> {
186    compile_modules_core(
187        modules,
188        registry,
189        options,
190        failed_sites,
191        &mut Vec::new(),
192        None,
193        &mut None,
194    )
195}
196
197impl Compiler<'_> {
198    /// The table of declarations of the module being read.
199    fn md(&self) -> &ModDecl {
200        &self.modules[self.cur_mod]
201    }
202
203    /// Returns the declarations of the current module in a mutable form.
204    fn md_mut(&mut self) -> &mut ModDecl {
205        &mut self.modules[self.cur_mod]
206    }
207
208    /// Adds a diagnostic (error or warning) with its position, code and arguments.
209    fn diag(
210        &mut self,
211        severity: Severity,
212        pos: Pos,
213        code: DiagCode,
214        args: Vec<(&'static str, DiagArg)>,
215    ) {
216        self.diags.push(Diagnostic {
217            module: self.modules[self.cur_mod].name.clone(),
218            line: pos.line,
219            col: pos.col,
220            severity,
221            code,
222            args,
223        });
224    }
225
226    /// Adds an error diagnostic.
227    fn error(&mut self, pos: Pos, code: DiagCode, args: Vec<(&'static str, DiagArg)>) {
228        self.diag(Severity::Error, pos, code, args);
229    }
230
231    /// A type mismatch error (`expected` and `found` are type names).
232    fn type_mismatch(&mut self, pos: Pos, expected: &str, found: &str) {
233        self.error(
234            pos,
235            DiagCode::TypeMismatch,
236            vec![("expected", s(expected)), ("found", s(found))],
237        );
238    }
239
240    /// An error for a wrong number of arguments.
241    fn arg_count_error(&mut self, name: &str, expected: usize, found: usize, pos: Pos) {
242        self.error(
243            pos,
244            DiagCode::ArgCount,
245            vec![
246                ("name", s(name)),
247                ("expected", DiagArg::Int(expected as i64)),
248                ("found", DiagArg::Int(found as i64)),
249            ],
250        );
251    }
252
253    /// An error whose only argument is a name (`name`).
254    fn name_error(&mut self, pos: Pos, code: DiagCode, name: &str) {
255        self.error(pos, code, vec![("name", s(name))]);
256    }
257
258    /// Compares the type of an argument with the expected type. Does nothing if either is unknown (the error is already
259    /// reported).
260    fn check_arg_type(&mut self, arg: &Expr, want: Option<&Ty>, got: Option<&Ty>) {
261        if let (Some(w), Some(g)) = (want, got)
262            && g != w
263        {
264            self.type_mismatch(arg.pos(), &w.name(), &g.name());
265        }
266    }
267
268    /// Adds a warning diagnostic. Warnings about unreachable patterns at the same position are not repeated.
269    fn warn(&mut self, pos: Pos, code: DiagCode, args: Vec<(&'static str, DiagArg)>) {
270        // Even if a pattern is unreachable for two reasons (already exhaustive, or a repeated pattern), there is only one warning
271        if code == DiagCode::UnreachablePattern
272            && self.diags.iter().any(|d| {
273                d.code == code
274                    && d.line == pos.line
275                    && d.col == pos.col
276                    && d.module == self.modules[self.cur_mod].name
277            })
278        {
279            return;
280        }
281        self.diag(Severity::Warning, pos, code, args);
282    }
283
284    /// The warning for declaring a variable with the same name as a built-in function.
285    fn warn_if_builtin(&mut self, name: &str, pos: Pos) {
286        if BUILTIN_NAMES.contains(&name) {
287            self.warn(pos, DiagCode::ShadowedBuiltin, vec![("name", s(name))]);
288        }
289    }
290
291    /// Returns the state of the label being compiled (not called outside a label).
292    fn ctx(&mut self) -> &mut LabelCtx {
293        self.cur.as_mut().expect("ラベルの中")
294    }
295
296    /// Makes an IR expression.
297    fn node(&mut self, kind: ExprKind, line: u32) -> ExprId {
298        self.ctx().ir.expr(kind, line)
299    }
300
301    /// An expression that produced a diagnostic (not turned into code).
302    fn error_node(&mut self) -> ExprId {
303        self.node(ExprKind::Error, 0)
304    }
305
306    /// Makes an IR statement and adds it to `out`.
307    fn push_stmt(&mut self, out: &mut Vec<StmtId>, kind: StmtKind, line: u32) {
308        let id = self.ctx().ir.stmt(kind, line);
309        out.push(id);
310    }
311
312    /// The stop point information of a stop point expression.
313    fn stop_info_mut(&mut self, id: ExprId) -> &mut StopInfo {
314        match &mut self.ctx().ir.exprs[id].kind {
315            ExprKind::Stop(stop) => &mut stop.info,
316            other => unreachable!("停止点の式のはず: {other:?}"),
317        }
318    }
319}
320
321mod body;
322mod call;
323mod command;
324mod declare;
325mod expr;
326mod lambda;
327mod migrate;
328pub(crate) use migrate::signature as signature_of;
329mod model;
330mod modules;
331mod pattern;
332pub(crate) mod repl;
333mod shape;
334mod stmt;
335mod text;
336mod types;
337
338use crate::program::MigrateCode;
339use model::*;
340use modules::*;
341use shape::*;
342
343#[cfg(test)]
344mod tests;