use alloc::boxed::Box;
use alloc::collections::BTreeMap;
use alloc::vec::Vec;
use core::fmt;
use hir_lang::{DivZero, FloatToInt, Op, OpKind, Overflow, PathRoot, Prim, Shift, Vis};
use crate::arch::{Arch, TemplateUse};
use crate::pick::{KindSets, Pick};
use crate::template::{HoleKind, NONE, TArg, TNode, Template, TemplateError, TemplateId};
use crate::text::{self, Registry, SyntaxError};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum TokenRole {
Name,
Var {
sigil: u8,
},
Label {
sigil: u8,
},
Lifetime {
sigil: u8,
},
Int,
Float,
Number,
Str(Escapes),
RawStr,
Heredoc(Escapes),
StrPart(Escapes),
Char(Escapes),
Bytes(Escapes),
True,
False,
Null,
Wild,
Rest,
Type(TypeName),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Escapes {
None,
Quotes,
Standard,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum TypeName {
Prim(Prim),
Any,
Never,
SelfTy,
Infer,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Modifier {
Public,
Protected,
Private,
Package,
Mut,
Ref,
Rest,
RestNamed,
NamedOnly,
PositionalOnly,
Receiver,
Async,
Generator,
Throws,
Unsafe,
Static,
Abstract,
Final,
Glob,
Inclusive,
Spread,
SpreadNamed,
Union,
}
impl Modifier {
pub(crate) const fn bit(self) -> u32 {
1 << (self as u32)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum EffectMode {
#[default]
Declared,
Inferred,
Always,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum IdentPatterns {
#[default]
Ident,
Bind,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum PlaceArgs {
#[default]
Marked,
Places,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum BreakLevels {
#[default]
Labels,
Numeric,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Separators {
#[default]
Anywhere,
BetweenDigits,
None,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum LegacyOctal {
#[default]
Decimal,
Octal,
Error,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Literals {
pub separators: Separators,
pub legacy_octal: LegacyOctal,
pub hex_floats: bool,
}
impl Default for Literals {
fn default() -> Self {
Self {
separators: Separators::Anywhere,
legacy_octal: LegacyOctal::Decimal,
hex_floats: true,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct LangPolicy {
pub overflow: Overflow,
pub div_zero: DivZero,
pub shift: Shift,
pub float_to_int: FloatToInt,
pub throws: EffectMode,
pub yields: EffectMode,
pub asyncs: EffectMode,
pub implicit_locals: bool,
pub ident_patterns: IdentPatterns,
pub place_args: PlaceArgs,
pub function_scoped_bindings: bool,
pub literals: Literals,
pub implicit_receiver: Option<NameRef>,
pub break_levels: BreakLevels,
pub default_member_visibility: Vis,
}
impl LangPolicy {
#[must_use]
pub fn php() -> Self {
Self {
overflow: Overflow::Promote,
throws: EffectMode::Always,
yields: EffectMode::Inferred,
implicit_locals: true,
place_args: PlaceArgs::Places,
function_scoped_bindings: true,
literals: Literals {
separators: Separators::BetweenDigits,
legacy_octal: LegacyOctal::Octal,
hex_floats: false,
},
..Self::default()
}
}
}
impl Default for LangPolicy {
fn default() -> Self {
Self {
overflow: Overflow::Error,
div_zero: DivZero::Error,
shift: Shift::Error,
float_to_int: FloatToInt::Error,
throws: EffectMode::Declared,
yields: EffectMode::Declared,
asyncs: EffectMode::Declared,
implicit_locals: false,
ident_patterns: IdentPatterns::Ident,
place_args: PlaceArgs::Marked,
function_scoped_bindings: false,
literals: Literals::default(),
implicit_receiver: None,
break_levels: BreakLevels::Labels,
default_member_visibility: Vis::Private,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct NameRef(pub(crate) u32);
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Join {
Fold(NameRef),
Call(NameRef),
Template(TemplateId),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum OpSpec {
Op(OpKind),
OpWith(Op),
Compound(OpKind),
CompoundWith(Op),
Assign,
RefAssign,
Identity,
Borrow(hir_lang::BorrowKind),
Deref,
Await,
Template(TemplateId),
Extern(NameRef),
Intrinsic(NameRef),
CompoundExtern(NameRef),
CompoundIntrinsic(NameRef),
CompoundTemplate(TemplateId),
}
impl OpSpec {
pub(crate) const fn is_place_compound(self) -> bool {
matches!(
self,
Self::CompoundExtern(_) | Self::CompoundIntrinsic(_) | Self::CompoundTemplate(_)
)
}
}
pub(crate) const fn compound_ok(kind: OpKind) -> bool {
matches!(
kind,
OpKind::Add
| OpKind::Sub
| OpKind::Mul
| OpKind::Div
| OpKind::FloorDiv
| OpKind::Rem
| OpKind::FloorMod
| OpKind::And
| OpKind::Or
| OpKind::Xor
| OpKind::Shl
| OpKind::Shr
| OpKind::Pow
)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Fixity {
Prefix,
Binary,
Postfix,
}
impl Fixity {
#[must_use]
pub const fn arity(self) -> usize {
match self {
Self::Binary => 2,
Self::Prefix | Self::Postfix => 1,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum MappingError {
MissingField {
rule: usize,
field: &'static str,
},
DuplicateKind {
table: &'static str,
index: usize,
},
DuplicateTypeName {
index: usize,
},
UnknownTemplate {
template: usize,
},
HoleCount {
rule: usize,
expected: usize,
found: usize,
},
ApplyArgs {
template: usize,
},
BadOperator {
fixity: Fixity,
index: usize,
},
TooLarge,
BadJoin {
rule: usize,
},
EmptyOperatorText {
fixity: Fixity,
index: usize,
},
UnknownArchetype {
index: usize,
},
UnknownName {
index: usize,
},
}
impl fmt::Display for MappingError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::MissingField { rule, field } => {
write!(f, "rule {rule}: required field `{field}` has no pick")
}
Self::DuplicateKind { table, index } => {
write!(f, "{table} {index}: the kind already has an entry")
}
Self::DuplicateTypeName { index } => write!(f, "type name {index} is registered twice"),
Self::UnknownTemplate { template } => {
write!(f, "template {template} is not registered")
}
Self::HoleCount {
rule,
expected,
found,
} => write!(
f,
"rule {rule}: the template has {expected} holes, {found} picks given"
),
Self::ApplyArgs { template } => {
write!(
f,
"template {template}: an `apply` does not match the applied template's holes"
)
}
Self::BadOperator { fixity, index } => {
write!(
f,
"{fixity:?} operator {index} maps to a spec that cannot apply there"
)
}
Self::TooLarge => f.write_str("a mapping table outgrew its index type"),
Self::BadJoin { rule } => write!(
f,
"rule {rule}: an interpolation template needs two expression holes or one argument-list hole"
),
Self::EmptyOperatorText { fixity, index } => {
write!(f, "{fixity:?} operator text {index} is empty")
}
Self::UnknownArchetype { index } => write!(
f,
"per-archetype modifier {index} names no archetype (expected an LSF2 `arch` name such as `param` or `arg`)"
),
Self::UnknownName { index } => write!(
f,
"the implicit receiver is name {index}, which this mapping did not store"
),
}
}
}
impl core::error::Error for MappingError {}
#[derive(Clone, Copy, Debug)]
pub(crate) struct Rule<K> {
pub(crate) when: Pick<K>,
pub(crate) arch: Arch<K>,
}
#[derive(Clone, Debug)]
pub struct Mapping<K> {
pub(crate) rules: Vec<Rule<K>>,
pub(crate) by_kind: Vec<(K, u32)>,
pub(crate) roles: Vec<(K, TokenRole)>,
pub(crate) modifiers: Vec<(K, Modifier)>,
pub(crate) arch_modifiers: Vec<(K, &'static str, Modifier)>,
pub(crate) roots: Vec<(K, PathRoot)>,
pub(crate) containers: Vec<K>,
pub(crate) skips: Vec<K>,
pub(crate) errors: Vec<K>,
pub(crate) type_names: Vec<(Box<str>, TypeName)>,
pub(crate) suffixes: Vec<(Box<str>, Prim)>,
pub(crate) prefix: Vec<(K, OpSpec)>,
pub(crate) binary: Vec<(K, OpSpec)>,
pub(crate) postfix: Vec<(K, OpSpec)>,
pub(crate) prefix_text: Vec<(Box<str>, OpSpec)>,
pub(crate) binary_text: Vec<(Box<str>, OpSpec)>,
pub(crate) postfix_text: Vec<(Box<str>, OpSpec)>,
pub(crate) attr_kinds: Vec<K>,
pub(crate) templates: Vec<Template>,
pub(crate) template_names: Vec<u32>,
pub(crate) hole_picks: Vec<Pick<K>>,
pub(crate) strings: Vec<Box<str>>,
pub(crate) policy: LangPolicy,
}
fn find<'a, K: Ord, V>(table: &'a [(K, V)], kind: &K) -> Option<&'a V> {
table
.binary_search_by(|(k, _)| k.cmp(kind))
.ok()
.and_then(|i| table.get(i))
.map(|(_, v)| v)
}
impl<K: Copy + Ord> Mapping<K> {
#[must_use]
pub fn rule_for(&self, kind: &K) -> Option<&Arch<K>> {
let (start, _) = self.rule_range(kind);
self.by_kind
.get(start)
.filter(|(k, _)| k == kind)
.and_then(|(_, r)| self.rules.get(*r as usize))
.map(|r| &r.arch)
}
#[must_use]
pub fn role_for(&self, kind: &K) -> Option<TokenRole> {
find(&self.roles, kind).copied()
}
#[must_use]
pub fn modifier_for(&self, kind: &K) -> Option<Modifier> {
find(&self.modifiers, kind).copied()
}
#[must_use]
pub fn modifier_in(&self, kind: &K, archetype: &str) -> Option<Modifier> {
self.arch_modifier(kind, archetype)
.or_else(|| self.modifier_for(kind))
}
fn arch_modifier(&self, kind: &K, archetype: &str) -> Option<Modifier> {
if self.arch_modifiers.is_empty() {
return None;
}
let start = self.arch_modifiers.partition_point(|(k, _, _)| k < kind);
self.arch_modifiers
.get(start..)
.unwrap_or(&[])
.iter()
.take_while(|(k, _, _)| k == kind)
.find(|(_, a, _)| *a == archetype)
.map(|(_, _, m)| *m)
}
#[must_use]
pub fn template(&self, id: TemplateId) -> Option<&Template> {
self.templates.get(id.index())
}
#[must_use]
pub const fn policy(&self) -> &LangPolicy {
&self.policy
}
pub(crate) fn rule_range(&self, kind: &K) -> (usize, usize) {
let start = self.by_kind.partition_point(|(k, _)| k < kind);
let end = start
+ self
.by_kind
.get(start..)
.map_or(0, |rest| rest.partition_point(|(k, _)| k == kind));
(start, end)
}
pub(crate) fn op(&self, fixity: Fixity, kind: &K, text: &str) -> Option<OpSpec> {
let (table, texts) = match fixity {
Fixity::Prefix => (&self.prefix, &self.prefix_text),
Fixity::Binary => (&self.binary, &self.binary_text),
Fixity::Postfix => (&self.postfix, &self.postfix_text),
};
find(table, kind).copied().or_else(|| {
if texts.is_empty() {
return None;
}
texts
.binary_search_by(|(t, _)| (**t).cmp(text))
.ok()
.and_then(|i| texts.get(i))
.map(|(_, s)| *s)
})
}
pub(crate) fn has_op_text(&self) -> bool {
!(self.prefix_text.is_empty()
&& self.binary_text.is_empty()
&& self.postfix_text.is_empty())
}
pub(crate) fn root_for(&self, kind: &K) -> Option<PathRoot> {
find(&self.roots, kind).copied()
}
pub(crate) fn is_error(&self, kind: &K) -> bool {
self.errors.binary_search(kind).is_ok()
}
pub(crate) fn type_name(&self, text: &str) -> Option<TypeName> {
self.type_names
.binary_search_by(|(t, _)| (**t).cmp(text))
.ok()
.and_then(|i| self.type_names.get(i))
.map(|(_, n)| *n)
}
}
impl<K: Ord> KindSets<K> for Mapping<K> {
fn is_skip(&self, kind: &K) -> bool {
self.skips.binary_search(kind).is_ok()
}
fn is_container(&self, kind: &K) -> bool {
self.containers.binary_search(kind).is_ok()
}
fn is_attr(&self, kind: &K) -> bool {
!self.attr_kinds.is_empty() && self.attr_kinds.binary_search(kind).is_ok()
}
}
#[derive(Clone, Debug)]
pub struct MappingBuilder<K> {
m: Mapping<K>,
rule_picks_error: Option<MappingError>,
template_index: BTreeMap<Box<str>, u32>,
arch_modifiers: Vec<(K, Box<str>, Modifier)>,
}
impl<K: Copy + Ord> Default for MappingBuilder<K> {
fn default() -> Self {
Self::new()
}
}
impl<K: Copy + Ord> MappingBuilder<K> {
#[must_use]
pub fn new() -> Self {
Self {
m: Mapping {
rules: Vec::new(),
by_kind: Vec::new(),
roles: Vec::new(),
modifiers: Vec::new(),
arch_modifiers: Vec::new(),
roots: Vec::new(),
containers: Vec::new(),
skips: Vec::new(),
errors: Vec::new(),
type_names: Vec::new(),
suffixes: Vec::new(),
prefix: Vec::new(),
binary: Vec::new(),
postfix: Vec::new(),
prefix_text: Vec::new(),
binary_text: Vec::new(),
postfix_text: Vec::new(),
attr_kinds: Vec::new(),
templates: Vec::new(),
template_names: Vec::new(),
hole_picks: Vec::new(),
strings: Vec::new(),
policy: LangPolicy::default(),
},
rule_picks_error: None,
template_index: BTreeMap::new(),
arch_modifiers: Vec::new(),
}
}
fn add_rule(&mut self, kind: K, when: Pick<K>, arch: Arch<K>) -> &mut Self {
match u32::try_from(self.m.rules.len()) {
Ok(i) if i < NONE => {
self.m.rules.push(Rule { when, arch });
self.m.by_kind.push((kind, i));
}
_ => self.rule_picks_error = Some(MappingError::TooLarge),
}
self
}
pub fn node(&mut self, kind: K, arch: Arch<K>) -> &mut Self {
self.add_rule(kind, Pick::Absent, arch)
}
pub fn node_when(&mut self, kind: K, when: Pick<K>, arch: Arch<K>) -> &mut Self {
self.add_rule(kind, when, arch)
}
pub fn token(&mut self, kind: K, role: TokenRole) -> &mut Self {
self.m.roles.push((kind, role));
self
}
pub fn modifier(&mut self, kind: K, modifier: Modifier) -> &mut Self {
self.m.modifiers.push((kind, modifier));
self
}
pub fn modifier_in(&mut self, kind: K, archetype: &str, modifier: Modifier) -> &mut Self {
self.arch_modifiers.push((kind, archetype.into(), modifier));
self
}
pub fn root(&mut self, kind: K, root: PathRoot) -> &mut Self {
self.m.roots.push((kind, root));
self
}
pub fn container(&mut self, kind: K) -> &mut Self {
self.m.containers.push(kind);
self
}
pub fn skip(&mut self, kind: K) -> &mut Self {
self.m.skips.push(kind);
self
}
pub fn error(&mut self, kind: K) -> &mut Self {
self.m.errors.push(kind);
self
}
pub fn type_name(&mut self, text: &str, name: TypeName) -> &mut Self {
self.m.type_names.push((text.into(), name));
self
}
pub fn suffix(&mut self, suffix: &str, prim: Prim) -> &mut Self {
self.m.suffixes.push((suffix.into(), prim));
self
}
pub fn prefix_op(&mut self, kind: K, spec: OpSpec) -> &mut Self {
self.m.prefix.push((kind, spec));
self
}
pub fn binary_op(&mut self, kind: K, spec: OpSpec) -> &mut Self {
self.m.binary.push((kind, spec));
self
}
pub fn postfix_op(&mut self, kind: K, spec: OpSpec) -> &mut Self {
self.m.postfix.push((kind, spec));
self
}
pub fn prefix_op_text(&mut self, text: &str, spec: OpSpec) -> &mut Self {
self.m.prefix_text.push((text.into(), spec));
self
}
pub fn binary_op_text(&mut self, text: &str, spec: OpSpec) -> &mut Self {
self.m.binary_text.push((text.into(), spec));
self
}
pub fn postfix_op_text(&mut self, text: &str, spec: OpSpec) -> &mut Self {
self.m.postfix_text.push((text.into(), spec));
self
}
pub fn name(&mut self, text: &str) -> NameRef {
NameRef(self.string(text))
}
fn string(&mut self, text: &str) -> u32 {
let i = self.m.strings.len();
self.m.strings.push(text.into());
u32::try_from(i).unwrap_or_else(|_| {
self.rule_picks_error = Some(MappingError::TooLarge);
0
})
}
pub fn policy(&mut self, policy: LangPolicy) -> &mut Self {
self.m.policy = policy;
self
}
pub fn template(&mut self, mut template: Template) -> Result<TemplateId, MappingError> {
let index = self.m.templates.len();
for &node in &template.applies {
let Some(TNode::Apply {
template: callee,
args,
}) = template.node(node).copied()
else {
continue;
};
let callee_t =
self.m
.templates
.get(callee as usize)
.ok_or(MappingError::UnknownTemplate {
template: callee as usize,
})?;
let (start, len) = (args.0 as usize, args.1 as usize);
let given = template
.args
.get(start..start.saturating_add(len))
.ok_or(MappingError::ApplyArgs { template: index })?;
if given.len() != callee_t.holes.len() {
return Err(MappingError::ApplyArgs { template: index });
}
for (arg, hole) in given.iter().zip(&callee_t.holes) {
let fits = match arg.kind() {
Some(kind) => kind == hole.kind,
None => hole.optional,
};
let forwarded_ok = match *arg {
TArg::Stmts(h) => template
.holes
.get(usize::from(h.0))
.is_some_and(|d| d.kind == HoleKind::Stmts),
TArg::Args(h) => template
.holes
.get(usize::from(h.0))
.is_some_and(|d| d.kind == HoleKind::Args),
_ => true,
};
if !fits || !forwarded_ok {
return Err(MappingError::ApplyArgs { template: index });
}
}
}
let id = u32::try_from(index).map_err(|_| MappingError::TooLarge)?;
let base = u32::try_from(self.m.strings.len()).map_err(|_| MappingError::TooLarge)?;
template.text_base = base;
self.m.strings.extend(template.texts.iter().cloned());
let name = template.name.clone();
let name_ref = self.string(&name);
self.m.template_names.push(name_ref);
self.m.templates.push(template);
let _ = self.template_index.insert(name, id);
Ok(TemplateId(id))
}
pub fn parse_template(&mut self, name: &str, text: &str) -> Result<TemplateId, TemplateError> {
let registry = Registry {
templates: &self.m.templates,
by_name: &self.template_index,
};
let template = text::parse(name, text, Some(registry))?;
self.template(template).map_err(|e| match e {
MappingError::TooLarge => TemplateError::TooLarge,
_ => TemplateError::Syntax {
at: hir_lang::Span::new(0, u32::try_from(text.len()).unwrap_or(u32::MAX)),
error: SyntaxError::ApplyArgs,
},
})
}
pub fn template_node(&mut self, kind: K, template: TemplateId, holes: &[Pick<K>]) -> &mut Self {
self.template_node_when(kind, Pick::Absent, template, holes)
}
pub fn template_node_when(
&mut self,
kind: K,
when: Pick<K>,
template: TemplateId,
holes: &[Pick<K>],
) -> &mut Self {
let first = self.m.hole_picks.len();
self.m.hole_picks.extend_from_slice(holes);
match (u32::try_from(first), u32::try_from(holes.len())) {
(Ok(first), Ok(len)) => self.add_rule(
kind,
when,
Arch::Template(TemplateUse {
template,
first,
len,
}),
),
_ => {
self.rule_picks_error = Some(MappingError::TooLarge);
self
}
}
}
pub fn build(mut self) -> Result<Mapping<K>, MappingError> {
if let Some(e) = self.rule_picks_error {
return Err(e);
}
if let Some(NameRef(i)) = self.m.policy.implicit_receiver {
if i as usize >= self.m.strings.len() {
return Err(MappingError::UnknownName { index: i as usize });
}
}
let mut arch_mods = Vec::with_capacity(self.arch_modifiers.len());
for (index, (kind, name, modifier)) in self.arch_modifiers.iter().enumerate() {
let name =
crate::arch::lsf_name_of(name).ok_or(MappingError::UnknownArchetype { index })?;
arch_mods.push((*kind, name, *modifier, index));
}
arch_mods.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(b.1)).then(a.3.cmp(&b.3)));
if let Some(w) = arch_mods
.windows(2)
.find(|w| w[0].0 == w[1].0 && w[0].1 == w[1].1)
{
return Err(MappingError::DuplicateKind {
table: "archetype modifier",
index: w[1].3,
});
}
self.m.arch_modifiers = arch_mods
.into_iter()
.map(|(k, a, m, _)| (k, a, m))
.collect();
let m = &mut self.m;
for (i, rule) in m.rules.iter().enumerate() {
if let Some(field) = missing_field(&rule.arch) {
return Err(MappingError::MissingField { rule: i, field });
}
if let Arch::Template(used) = rule.arch {
let t = m.templates.get(used.template.index()).ok_or(
MappingError::UnknownTemplate {
template: used.template.index(),
},
)?;
if t.holes.len() != used.len as usize {
return Err(MappingError::HoleCount {
rule: i,
expected: t.holes.len(),
found: used.len as usize,
});
}
}
if let Arch::Interp {
join: Join::Template(id),
..
} = rule.arch
{
let t = m
.templates
.get(id.index())
.ok_or(MappingError::UnknownTemplate {
template: id.index(),
})?;
let fold = t.holes.len() == 2 && t.holes.iter().all(|h| h.kind == HoleKind::Expr);
let all = t.holes.len() == 1 && t.holes.iter().all(|h| h.kind == HoleKind::Args);
if !fold && !all {
return Err(MappingError::BadJoin { rule: i });
}
}
}
for (fixity, table) in [
(Fixity::Prefix, &m.prefix_text),
(Fixity::Binary, &m.binary_text),
(Fixity::Postfix, &m.postfix_text),
] {
for (index, (text, spec)) in table.iter().enumerate() {
if text.is_empty() {
return Err(MappingError::EmptyOperatorText { fixity, index });
}
if !op_fits(*spec, fixity, &m.templates) {
return Err(MappingError::BadOperator { fixity, index });
}
}
}
for (fixity, table) in [
(Fixity::Prefix, &m.prefix),
(Fixity::Binary, &m.binary),
(Fixity::Postfix, &m.postfix),
] {
for (index, (_, spec)) in table.iter().enumerate() {
if !op_fits(*spec, fixity, &m.templates) {
return Err(MappingError::BadOperator { fixity, index });
}
}
}
m.by_kind.sort_by_key(|e| e.0);
sort_unique(&mut m.roles, "token role")?;
sort_unique(&mut m.modifiers, "modifier")?;
sort_unique(&mut m.roots, "root")?;
sort_unique(&mut m.prefix, "prefix operator")?;
sort_unique(&mut m.binary, "binary operator")?;
sort_unique(&mut m.postfix, "postfix operator")?;
sort_unique_text(&mut m.prefix_text, "prefix operator text")?;
sort_unique_text(&mut m.binary_text, "binary operator text")?;
sort_unique_text(&mut m.postfix_text, "postfix operator text")?;
let mut attrs: Vec<K> = m
.by_kind
.iter()
.filter(|(_, r)| {
m.rules
.get(*r as usize)
.is_some_and(|r| matches!(r.arch, Arch::Attr { .. }))
})
.map(|(k, _)| *k)
.collect();
attrs.sort();
attrs.dedup();
m.attr_kinds = attrs;
m.containers.sort();
m.containers.dedup();
m.skips.sort();
m.skips.dedup();
m.errors.sort();
m.errors.dedup();
let mut names: Vec<(usize, &str)> = m
.type_names
.iter()
.enumerate()
.map(|(i, (t, _))| (i, &**t))
.collect();
names.sort_by(|a, b| a.1.cmp(b.1).then(a.0.cmp(&b.0)));
if let Some(w) = names.windows(2).find(|w| w[0].1 == w[1].1) {
return Err(MappingError::DuplicateTypeName { index: w[1].0 });
}
m.type_names.sort_by(|a, b| a.0.cmp(&b.0));
m.suffixes
.sort_by(|a, b| b.0.len().cmp(&a.0.len()).then(a.0.cmp(&b.0)));
Ok(self.m)
}
}
fn sort_unique<K: Ord + Copy, V>(
table: &mut [(K, V)],
name: &'static str,
) -> Result<(), MappingError> {
let mut order: Vec<(K, usize)> = table
.iter()
.enumerate()
.map(|(i, (k, _))| (*k, i))
.collect();
order.sort();
if let Some(w) = order.windows(2).find(|w| w[0].0 == w[1].0) {
return Err(MappingError::DuplicateKind {
table: name,
index: w[1].1,
});
}
table.sort_by_key(|e| e.0);
Ok(())
}
fn sort_unique_text<V>(
table: &mut [(Box<str>, V)],
name: &'static str,
) -> Result<(), MappingError> {
let mut order: Vec<(&str, usize)> = table
.iter()
.enumerate()
.map(|(i, (t, _))| (&**t, i))
.collect();
order.sort_unstable();
if let Some(w) = order.windows(2).find(|w| w[0].0 == w[1].0) {
return Err(MappingError::DuplicateKind {
table: name,
index: w[1].1,
});
}
table.sort_by(|a, b| a.0.cmp(&b.0));
Ok(())
}
fn op_fits(spec: OpSpec, fixity: Fixity, templates: &[Template]) -> bool {
let arity = fixity.arity();
match spec {
OpSpec::Op(kind) => kind.arity() == arity,
OpSpec::OpWith(op) => op.kind.arity() == arity && op.policy_matches(),
OpSpec::Compound(kind) => fixity == Fixity::Binary && compound_ok(kind),
OpSpec::CompoundWith(op) => {
fixity == Fixity::Binary && compound_ok(op.kind) && op.policy_matches()
}
OpSpec::Assign | OpSpec::RefAssign => fixity == Fixity::Binary,
OpSpec::Identity | OpSpec::Await => fixity != Fixity::Binary,
OpSpec::Borrow(_) | OpSpec::Deref => fixity == Fixity::Prefix,
OpSpec::Template(id) => templates.get(id.index()).is_some_and(|t| {
t.holes.len() == arity && t.holes.iter().all(|h| h.kind == HoleKind::Expr)
}),
OpSpec::Extern(_) | OpSpec::Intrinsic(_) => true,
OpSpec::CompoundExtern(_) | OpSpec::CompoundIntrinsic(_) => fixity == Fixity::Binary,
OpSpec::CompoundTemplate(id) => {
fixity == Fixity::Binary
&& templates.get(id.index()).is_some_and(|t| {
t.holes.len() == 2 && t.holes.iter().all(|h| h.kind == HoleKind::Expr)
})
}
}
}
fn missing_field<K>(arch: &Arch<K>) -> Option<&'static str> {
let need =
|pairs: &[(&'static str, bool)]| pairs.iter().find(|(_, absent)| *absent).map(|(f, _)| *f);
match arch {
Arch::Module { .. }
| Arch::Splice { .. }
| Arch::Unsupported
| Arch::GlobalDecl { .. }
| Arch::MixinUse { .. }
| Arch::UseTree { .. }
| Arch::Interp { .. }
| Arch::AttrArg { .. }
| Arch::FieldDecl { .. }
| Arch::Tuple { .. }
| Arch::Array { .. }
| Arch::Map { .. }
| Arch::RecordLit { .. }
| Arch::Block { .. }
| Arch::Break { .. }
| Arch::Continue { .. }
| Arch::Return { .. }
| Arch::Yield { .. }
| Arch::Template(_)
| Arch::WildPat
| Arch::RestPat { .. }
| Arch::TuplePat { .. }
| Arch::RecordPat { .. }
| Arch::OrPat { .. }
| Arch::RangePat { .. }
| Arch::SlicePat { .. }
| Arch::TupleTy { .. }
| Arch::FnTy { .. }
| Arch::ObjectTy { .. }
| Arch::ImplTy { .. }
| Arch::UnionTy { .. }
| Arch::IntersectionTy { .. } => None,
Arch::Pass { inner } => need(&[("inner", inner.is_absent())]),
Arch::Let { pat, .. } => need(&[("pat", pat.is_absent())]),
Arch::ExprStmt { expr } => need(&[("expr", expr.is_absent())]),
Arch::Defer { body } => need(&[("body", body.is_absent())]),
Arch::Static { name, .. }
| Arch::Fn { name, .. }
| Arch::Record { name, .. }
| Arch::Sum { name, .. }
| Arch::Interface { name, .. }
| Arch::Class { name, .. }
| Arch::AssocType { name, .. }
| Arch::Const { name, .. }
| Arch::GlobalVar { name, .. }
| Arch::VariantDecl { name, .. }
| Arch::GenericParam { name, .. }
| Arch::Capture { name }
| Arch::Segment { name, .. }
| Arch::BindPat { name, .. }
| Arch::FieldPat { name, .. }
| Arch::FieldInit { name, .. } => need(&[("name", name.is_absent())]),
Arch::Import { path, .. } => need(&[("path", path.is_absent())]),
Arch::MixinRule { method, .. } => need(&[("method", method.is_absent())]),
Arch::Attr { name, .. } => need(&[("name", name.is_absent())]),
Arch::Impl { self_ty, .. } => need(&[("self_ty", self_ty.is_absent())]),
Arch::Alias { name, ty, .. } | Arch::AssocBinding { name, ty } => {
need(&[("name", name.is_absent()), ("ty", ty.is_absent())])
}
Arch::WherePred { subject, .. } => need(&[("subject", subject.is_absent())]),
Arch::Param { pat, .. } => need(&[("pat", pat.is_absent())]),
Arch::Path {
segments, qself, ..
} => need(&[("segments", segments.is_absent() && qself.is_absent())]),
Arch::Unary { op, operand } | Arch::Postfix { operand, op } => {
need(&[("op", op.is_absent()), ("operand", operand.is_absent())])
}
Arch::Binary { lhs, op, rhs } => need(&[
("lhs", lhs.is_absent()),
("op", op.is_absent()),
("rhs", rhs.is_absent()),
]),
Arch::Assign { target, value, .. } => {
need(&[("target", target.is_absent()), ("value", value.is_absent())])
}
Arch::RefAssign { target, source } => need(&[
("target", target.is_absent()),
("source", source.is_absent()),
]),
Arch::Call { callee, .. } => need(&[("callee", callee.is_absent())]),
Arch::Arg { value, .. } | Arch::MapEntry { value, .. } => {
need(&[("value", value.is_absent())])
}
Arch::Member { base, member, .. } => {
need(&[("base", base.is_absent()), ("member", member.is_absent())])
}
Arch::MethodCall {
receiver, method, ..
} => need(&[
("receiver", receiver.is_absent()),
("method", method.is_absent()),
]),
Arch::DynMember { base, name, .. } => {
need(&[("base", base.is_absent()), ("name", name.is_absent())])
}
Arch::Index { base, index } => {
need(&[("base", base.is_absent()), ("index", index.is_absent())])
}
Arch::VarVar { inner }
| Arch::Deref { inner }
| Arch::Await { inner }
| Arch::YieldFrom { inner }
| Arch::Spawn { inner }
| Arch::RefPat { inner }
| Arch::PtrTy { inner }
| Arch::NullableTy { inner }
| Arch::RefTy { inner, .. } => need(&[("inner", inner.is_absent())]),
Arch::Append { base } => need(&[("base", base.is_absent())]),
Arch::Repeat { elem, count } => {
need(&[("elem", elem.is_absent()), ("count", count.is_absent())])
}
Arch::Cast { expr, ty } => need(&[("expr", expr.is_absent()), ("ty", ty.is_absent())]),
Arch::Borrow { expr } => need(&[("expr", expr.is_absent())]),
Arch::If { cond, then, .. } => {
need(&[("cond", cond.is_absent()), ("then", then.is_absent())])
}
Arch::Match { scrutinee, .. } => need(&[("scrutinee", scrutinee.is_absent())]),
Arch::Arm { pat, body, .. } => {
need(&[("pat", pat.is_absent()), ("body", body.is_absent())])
}
Arch::Loop { body, .. }
| Arch::Try { body, .. }
| Arch::Catch { body, .. }
| Arch::Closure { body, .. } => need(&[("body", body.is_absent())]),
Arch::Throw { value } => need(&[("value", value.is_absent())]),
Arch::CtorPat { path, .. } => need(&[("path", path.is_absent())]),
Arch::TypeTestPat { ty, .. } => need(&[("ty", ty.is_absent())]),
Arch::ArrayTy { elem, len } => {
need(&[("elem", elem.is_absent()), ("len", len.is_absent())])
}
Arch::SliceTy { elem } => need(&[("elem", elem.is_absent())]),
}
}
pub(crate) fn modifier_bits<K: Copy + Ord>(map: &Mapping<K>, kind: &K, arch: Option<&str>) -> u32 {
if let Some(m) = arch.and_then(|a| map.arch_modifier(kind, a)) {
return m.bit();
}
find(&map.modifiers, kind).map_or(0, |m| m.bit())
}
#[cfg(test)]
#[allow(unused_results)]
mod tests {
use super::*;
use crate::templates;
#[test]
fn test_duplicate_roles_are_refused() {
let mut b = MappingBuilder::<u8>::new();
b.token(1, TokenRole::Name).token(1, TokenRole::Int);
assert_eq!(
b.build().err(),
Some(MappingError::DuplicateKind {
table: "token role",
index: 1
})
);
}
#[test]
fn test_operator_specs_are_checked_against_their_position() {
let mut b = MappingBuilder::<u8>::new();
b.binary_op(1, OpSpec::Op(OpKind::Neg));
assert!(matches!(b.build(), Err(MappingError::BadOperator { .. })));
let mut b = MappingBuilder::<u8>::new();
b.binary_op(1, OpSpec::Compound(OpKind::Eq));
assert!(matches!(b.build(), Err(MappingError::BadOperator { .. })));
let mut b = MappingBuilder::<u8>::new();
b.prefix_op(1, OpSpec::Assign);
assert!(matches!(b.build(), Err(MappingError::BadOperator { .. })));
let mut b = MappingBuilder::<u8>::new();
let w = b.template(templates::while_loop()).ok();
if let Some(w) = w {
b.binary_op(1, OpSpec::Template(w));
}
assert!(matches!(b.build(), Err(MappingError::BadOperator { .. })));
}
#[test]
fn test_template_node_checks_hole_count() {
let mut b = MappingBuilder::<u8>::new();
let Ok(w) = b.template(templates::while_loop()) else {
panic!("registers");
};
b.template_node(1, w, &[Pick::Nth(0)]);
assert_eq!(
b.build().err(),
Some(MappingError::HoleCount {
rule: 0,
expected: 3,
found: 1
})
);
}
#[test]
fn test_conditional_rules_keep_registration_order() {
let mut b = MappingBuilder::<u8>::new();
b.node(9, Arch::WildPat);
b.node_when(4, Pick::First(1), Arch::Unsupported);
b.node(4, Arch::WildPat);
let Ok(m) = b.build() else { panic!("valid") };
let (s, e) = m.rule_range(&4);
assert_eq!(e - s, 2);
assert_eq!(m.rule_for(&4), Some(&Arch::Unsupported));
}
#[test]
fn test_duplicate_type_names_are_refused() {
let mut b = MappingBuilder::<u8>::new();
b.type_name("int", TypeName::Any)
.type_name("int", TypeName::Never);
assert_eq!(
b.build().err(),
Some(MappingError::DuplicateTypeName { index: 1 })
);
}
}