1use 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
30pub 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
42pub 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
53pub 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#[derive(Debug, Clone, Default)]
68#[non_exhaustive]
69pub struct CompileOptions {
70 pub entry_labels: Vec<String>,
74 pub require_text_ids: bool,
78 pub migrations: Option<String>,
80 pub frozen_schemas: Vec<(String, String)>,
82}
83
84impl CompileOptions {
85 pub fn require_text_ids(mut self, on: bool) -> Self {
87 self.require_text_ids = on;
88 self
89 }
90
91 pub fn migrations(mut self, source: &str) -> Self {
93 self.migrations = Some(source.to_string());
94 self
95 }
96
97 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 pub fn entry_label(mut self, label: &str) -> Self {
106 self.entry_labels.push(label.to_string());
107 self
108 }
109}
110
111#[derive(Clone, Debug, PartialEq, Eq)]
113pub struct LocalType {
114 pub module: String,
116 pub line: u32,
118 pub col: u32,
120 pub ty: String,
122}
123
124pub 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
139pub 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
150pub 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
159pub(crate) type SitedResult = (
161 Result<(Program, Vec<Diagnostic>), Vec<Diagnostic>>,
162 Vec<IdSite>,
163);
164
165pub(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
177fn 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 fn md(&self) -> &ModDecl {
200 &self.modules[self.cur_mod]
201 }
202
203 fn md_mut(&mut self) -> &mut ModDecl {
205 &mut self.modules[self.cur_mod]
206 }
207
208 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 fn error(&mut self, pos: Pos, code: DiagCode, args: Vec<(&'static str, DiagArg)>) {
228 self.diag(Severity::Error, pos, code, args);
229 }
230
231 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 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 fn name_error(&mut self, pos: Pos, code: DiagCode, name: &str) {
255 self.error(pos, code, vec![("name", s(name))]);
256 }
257
258 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 fn warn(&mut self, pos: Pos, code: DiagCode, args: Vec<(&'static str, DiagArg)>) {
270 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 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 fn ctx(&mut self) -> &mut LabelCtx {
293 self.cur.as_mut().expect("ラベルの中")
294 }
295
296 fn node(&mut self, kind: ExprKind, line: u32) -> ExprId {
298 self.ctx().ir.expr(kind, line)
299 }
300
301 fn error_node(&mut self) -> ExprId {
303 self.node(ExprKind::Error, 0)
304 }
305
306 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 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;