use std::collections::{HashMap, HashSet};
use crate::backend::Backend as _;
use crate::backend::register::{MAX_REGS, RegBackend, TooManyRegisters};
use crate::diag::{DiagArg, DiagCode, Diagnostic, Severity};
use crate::ir::{
Body, Builtin, Choice, ChoiceOpt as IrChoiceOpt, ExprId, ExprKind, ForKind, IfArm, Ir,
MatchArm as IrArm, Method, Operand, PatTest, StmtId, StmtKind, Stop, StopArg, Tail, TextPiece,
};
use crate::program::{
Action, ArithOp, CallSite, ChoiceInfo, ChoiceOptInfo, FnCode, GlobalInfo, IdSite, IdentityInfo,
LabelCode, LocalInfo, PathStep, PlaceRef, Program, RegCode, StopInfo, StopKind, TextArg,
TextPart, fnv1a,
};
use crate::registry::{Binding, CommandKind, Registry};
use crate::suggest::suggest;
use crate::syntax::ast::{
AssignOp, BinOp, ChoiceOpt, CommandCall, Expr, FieldInit, IdentRef, IdentityDecl, LabelCall,
LabelDecl, LabelRef, MatchArm, Module, PathElem, Pattern, Pos, StableId, Stmt, StrPart, TyName,
TypeDeclKind, TypeRef, UnOp, VarDecl,
};
use crate::syntax::keywords::is_reserved;
use crate::syntax::parser::{IdentMap, parse_with, scan_identities};
use crate::value::{
Identity, MAX_TYPE_DEPTH, Ty, TypeDecl, TypeKind, Value, VariantDecl, find_type, finite_float,
};
pub fn compile(
source: &str,
module: &str,
registry: &Registry,
) -> Result<Program, Vec<Diagnostic>> {
compile_with_warnings(source, module, registry).map(|(program, _)| program)
}
pub fn compile_with_warnings(
source: &str,
module: &str,
registry: &Registry,
) -> Result<(Program, Vec<Diagnostic>), Vec<Diagnostic>> {
compile_modules_with_warnings(&[(module, source)], registry)
}
pub fn compile_modules(
modules: &[(&str, &str)],
registry: &Registry,
) -> Result<Program, Vec<Diagnostic>> {
compile_modules_with_warnings(modules, registry).map(|(program, _)| program)
}
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct CompileOptions {
pub entry_labels: Vec<String>,
pub require_text_ids: bool,
pub migrations: Option<String>,
pub frozen_schemas: Vec<(String, String)>,
}
impl CompileOptions {
pub fn require_text_ids(mut self, on: bool) -> Self {
self.require_text_ids = on;
self
}
pub fn migrations(mut self, source: &str) -> Self {
self.migrations = Some(source.to_string());
self
}
pub fn frozen_schema_file(mut self, path: &str, source: &str) -> Self {
self.frozen_schemas
.push((path.to_string(), source.to_string()));
self
}
pub fn entry_label(mut self, label: &str) -> Self {
self.entry_labels.push(label.to_string());
self
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LocalType {
pub module: String,
pub line: u32,
pub col: u32,
pub ty: String,
}
pub fn infer_local_types(modules: &[(&str, &str)], registry: &Registry) -> Vec<LocalType> {
let mut types = Vec::new();
let _ = compile_modules_core(
modules,
registry,
&CompileOptions::default(),
&mut Vec::new(),
&mut types,
None,
&mut None,
);
types
}
pub fn compile_modules_with_warnings(
modules: &[(&str, &str)],
registry: &Registry,
) -> Result<(Program, Vec<Diagnostic>), Vec<Diagnostic>> {
compile_modules_with_options(modules, registry, &CompileOptions::default())
}
pub fn compile_modules_with_options(
modules: &[(&str, &str)],
registry: &Registry,
options: &CompileOptions,
) -> Result<(Program, Vec<Diagnostic>), Vec<Diagnostic>> {
compile_modules_impl(modules, registry, options, &mut Vec::new())
}
pub(crate) type SitedResult = (
Result<(Program, Vec<Diagnostic>), Vec<Diagnostic>>,
Vec<IdSite>,
);
pub(crate) fn compile_modules_with_sites(
modules: &[(&str, &str)],
registry: &Registry,
options: &CompileOptions,
) -> SitedResult {
let mut failed_sites = Vec::new();
let result = compile_modules_impl(modules, registry, options, &mut failed_sites);
(result, failed_sites)
}
fn compile_modules_impl(
modules: &[(&str, &str)],
registry: &Registry,
options: &CompileOptions,
failed_sites: &mut Vec<IdSite>,
) -> Result<(Program, Vec<Diagnostic>), Vec<Diagnostic>> {
compile_modules_core(
modules,
registry,
options,
failed_sites,
&mut Vec::new(),
None,
&mut None,
)
}
impl Compiler<'_> {
fn md(&self) -> &ModDecl {
&self.modules[self.cur_mod]
}
fn md_mut(&mut self) -> &mut ModDecl {
&mut self.modules[self.cur_mod]
}
fn diag(
&mut self,
severity: Severity,
pos: Pos,
code: DiagCode,
args: Vec<(&'static str, DiagArg)>,
) {
self.diags.push(Diagnostic {
module: self.modules[self.cur_mod].name.clone(),
line: pos.line,
col: pos.col,
severity,
code,
args,
});
}
fn error(&mut self, pos: Pos, code: DiagCode, args: Vec<(&'static str, DiagArg)>) {
self.diag(Severity::Error, pos, code, args);
}
fn type_mismatch(&mut self, pos: Pos, expected: &str, found: &str) {
self.error(
pos,
DiagCode::TypeMismatch,
vec![("expected", s(expected)), ("found", s(found))],
);
}
fn arg_count_error(&mut self, name: &str, expected: usize, found: usize, pos: Pos) {
self.error(
pos,
DiagCode::ArgCount,
vec![
("name", s(name)),
("expected", DiagArg::Int(expected as i64)),
("found", DiagArg::Int(found as i64)),
],
);
}
fn name_error(&mut self, pos: Pos, code: DiagCode, name: &str) {
self.error(pos, code, vec![("name", s(name))]);
}
fn check_arg_type(&mut self, arg: &Expr, want: Option<&Ty>, got: Option<&Ty>) {
if let (Some(w), Some(g)) = (want, got)
&& g != w
{
self.type_mismatch(arg.pos(), &w.name(), &g.name());
}
}
fn warn(&mut self, pos: Pos, code: DiagCode, args: Vec<(&'static str, DiagArg)>) {
if code == DiagCode::UnreachablePattern
&& self.diags.iter().any(|d| {
d.code == code
&& d.line == pos.line
&& d.col == pos.col
&& d.module == self.modules[self.cur_mod].name
})
{
return;
}
self.diag(Severity::Warning, pos, code, args);
}
fn warn_if_builtin(&mut self, name: &str, pos: Pos) {
if BUILTIN_NAMES.contains(&name) {
self.warn(pos, DiagCode::ShadowedBuiltin, vec![("name", s(name))]);
}
}
fn ctx(&mut self) -> &mut LabelCtx {
self.cur.as_mut().expect("ラベルの中")
}
fn node(&mut self, kind: ExprKind, line: u32) -> ExprId {
self.ctx().ir.expr(kind, line)
}
fn error_node(&mut self) -> ExprId {
self.node(ExprKind::Error, 0)
}
fn push_stmt(&mut self, out: &mut Vec<StmtId>, kind: StmtKind, line: u32) {
let id = self.ctx().ir.stmt(kind, line);
out.push(id);
}
fn stop_info_mut(&mut self, id: ExprId) -> &mut StopInfo {
match &mut self.ctx().ir.exprs[id].kind {
ExprKind::Stop(stop) => &mut stop.info,
other => unreachable!("停止点の式のはず: {other:?}"),
}
}
}
mod body;
mod call;
mod command;
mod declare;
mod expr;
mod lambda;
mod migrate;
pub(crate) use migrate::signature as signature_of;
mod model;
mod modules;
mod pattern;
pub(crate) mod repl;
mod shape;
mod stmt;
mod text;
mod types;
use crate::program::MigrateCode;
use model::*;
use modules::*;
use shape::*;
#[cfg(test)]
mod tests;