use std::any::Any;
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::sync::{Arc, OnceLock};
use techy::core::node::{NodeId, NodeRef, NodeSlice, NodeTree};
use techy::error::{Diagnostic, DiagnosticValue, Severity, ToDiagnosticValue};
use techy::latexlike::Mode;
use techy::source::{Source, SourceSpan};
use crate::model::aspects::{BlockRole, BlockRoleAspect, FixedBlockRole};
use crate::model::element::ElementSpec;
use crate::model::names::{ElementName, FeatureName, Name};
use crate::lang::build::BuiltLang;
use crate::lang::flm::Flm;
use crate::lang::guard::GuardPolicy;
use crate::lang::mint::{
ArgDef, BodyDef, BodyLayout, CallableKind, ElementDef, OverrideDef, SyntaxDef,
};
use crate::lang::origin::{FlmDiagnostic, FlmOrigin, FlmSource};
use crate::lang::owned::LangOwned;
use crate::lang::rewrites::userdefs::diagnostics::{
BadDefinition, BadPlaceholder, DefinitionProblem, PlaceholderProblem,
};
use crate::lang::rewrites::userdefs::hook::{
Expand, ExpandCx, ExpandError, ExpandPolicy, Expander, Expansion, PlaceholderBindings,
PlaceholderValue,
};
use crate::lang::rewrites::userdefs::instantiate::instantiate;
use crate::lang::rewrites::userdefs::pass::DEFAULT_RECURSION_LIMIT;
use crate::lang::rewrites::userdefs::template::{
compile_in_modes, compile_template_with, minting_diagnostics, CompiledTemplate,
ExtraPlaceholder, PlaceholderTarget, PlaceholderVocabulary, TemplateLanguage, TemplateSpec,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DefinitionKind {
Macro,
Environment,
Specials,
}
impl DefinitionKind {
pub fn token(self) -> &'static str {
match self {
DefinitionKind::Macro => "macro",
DefinitionKind::Environment => "environment",
DefinitionKind::Specials => "specials",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum DefinitionModes {
Text,
Math,
#[default]
Both,
}
impl DefinitionModes {
pub fn modes(self) -> &'static [Mode] {
match self {
DefinitionModes::Text => &[Mode::Text],
DefinitionModes::Math => &[Mode::Math],
DefinitionModes::Both => &[Mode::Text, Mode::Math],
}
}
pub fn includes(self, mode: Mode) -> bool {
self.modes().contains(&mode)
}
pub fn overlaps(self, other: DefinitionModes) -> bool {
self.modes().iter().any(|mode| other.includes(*mode))
}
pub fn token(self) -> &'static str {
match self {
DefinitionModes::Text => "text",
DefinitionModes::Math => "math",
DefinitionModes::Both => "both",
}
}
}
#[derive(Debug, Clone)]
pub struct Definition {
pub name: Name,
pub kind: DefinitionKind,
pub args: Vec<ArgDef>,
pub content: Option<String>,
pub modes: DefinitionModes,
pub defaults: BTreeMap<String, String>,
pub argument_number_offset: usize,
pub block_role: BlockRole,
pub expand: ExpandPolicy,
pub overrides: bool,
pub docs: String,
pub extra_placeholders: Vec<ExtraPlaceholder>,
}
impl Definition {
pub fn new(kind: DefinitionKind, name: impl Into<Name>, args: Vec<ArgDef>) -> Definition {
Definition {
name: name.into(),
kind,
args,
content: None,
modes: DefinitionModes::default(),
defaults: BTreeMap::new(),
argument_number_offset: 0,
block_role: BlockRole::DEFAULT,
expand: ExpandPolicy::default(),
overrides: false,
docs: String::new(),
extra_placeholders: Vec::new(),
}
}
pub fn macro_(name: impl Into<Name>, args: Vec<ArgDef>) -> Definition {
Definition::new(DefinitionKind::Macro, name, args)
}
pub fn environment(name: impl Into<Name>, args: Vec<ArgDef>) -> Definition {
Definition::new(DefinitionKind::Environment, name, args)
}
pub fn specials(trigger: impl Into<Name>, args: Vec<ArgDef>) -> Definition {
Definition::new(DefinitionKind::Specials, trigger, args)
}
pub fn content(mut self, template: impl Into<String>) -> Definition {
self.content = Some(template.into());
self
}
pub fn modes(mut self, modes: DefinitionModes) -> Definition {
self.modes = modes;
self
}
pub fn text(self, template: impl Into<String>) -> Definition {
self.content(template).modes(DefinitionModes::Text)
}
pub fn math(self, template: impl Into<String>) -> Definition {
self.content(template).modes(DefinitionModes::Math)
}
pub fn default(mut self, key: impl Into<String>, template: impl Into<String>) -> Definition {
self.defaults.insert(key.into(), template.into());
self
}
pub fn argument_number_offset(mut self, offset: usize) -> Definition {
self.argument_number_offset = offset;
self
}
pub fn block_role(mut self, role: BlockRole) -> Definition {
self.block_role = role;
self
}
pub fn expand(mut self, policy: ExpandPolicy) -> Definition {
self.expand = policy;
self
}
pub fn overriding(mut self) -> Definition {
self.overrides = true;
self
}
pub fn docs(mut self, docs: impl Into<String>) -> Definition {
self.docs = crate::kept_docs(docs);
self
}
pub fn extra_placeholder(mut self, name: impl Into<String>, substitution: bool) -> Definition {
self.extra_placeholders.push(ExtraPlaceholder { name: name.into(), substitution });
self
}
pub fn arity(&self) -> usize {
self.args.len()
}
pub fn display_name(&self) -> String {
match self.kind {
DefinitionKind::Macro => format!("\\{}", self.name),
DefinitionKind::Environment => format!("\\begin{{{}}}", self.name),
DefinitionKind::Specials => self.name.to_string(),
}
}
pub fn callable_kind(&self) -> CallableKind {
match self.kind {
DefinitionKind::Macro => CallableKind::Macro,
DefinitionKind::Environment => CallableKind::Environment,
DefinitionKind::Specials => CallableKind::Specials,
}
}
pub fn argument_index(&self, key: &str) -> Option<usize> {
if let Some(index) = self.args.iter().position(|arg| arg.name.as_deref() == Some(key)) {
return Some(index);
}
let number: usize = key.parse().ok()?;
let index = number.checked_sub(1)?.checked_add(self.argument_number_offset)?;
(number >= 1 && index < self.args.len()).then_some(index)
}
pub fn vocabulary(&self) -> PlaceholderVocabulary {
let mut vocabulary = PlaceholderVocabulary::new(self.args.len())
.names(self.args.iter().map(|arg| arg.name.clone()).collect());
if self.kind == DefinitionKind::Environment {
vocabulary = vocabulary.with_body();
}
for extra in &self.extra_placeholders {
vocabulary = vocabulary.extra(extra.name.clone(), extra.substitution);
}
vocabulary
}
pub fn syntax(&self) -> SyntaxDef {
match self.kind {
DefinitionKind::Macro => SyntaxDef::Macro { args: self.args.clone() },
DefinitionKind::Environment => {
let layout = match self.block_role {
BlockRole::Block => BodyLayout::Blocks,
_ => BodyLayout::Inline,
};
SyntaxDef::Environment {
args: self.args.clone(),
body: BodyDef::new().layout(layout),
}
}
DefinitionKind::Specials => SyntaxDef::Specials {
trigger: self.name.to_string(),
args: self.args.clone(),
},
}
}
}
pub struct ModeVariant {
template: Arc<CompiledTemplate>,
defaults: BTreeMap<usize, Arc<CompiledTemplate>>,
}
impl ModeVariant {
pub fn template(&self) -> &Arc<CompiledTemplate> {
&self.template
}
pub fn default_of(&self, index: usize) -> Option<&Arc<CompiledTemplate>> {
self.defaults.get(&index)
}
pub fn defaults(&self) -> impl Iterator<Item = (usize, &Arc<CompiledTemplate>)> + '_ {
self.defaults.iter().map(|(index, template)| (*index, template))
}
pub fn instantiate_default(
&self,
site: NodeRef<'_, Flm>,
index: usize,
guard: GuardPolicy,
) -> Option<Result<NodeTree<Flm>, ExpandError>> {
let default = self.default_of(index)?;
let bindings = DefinitionBindings::new(site, self);
Some(instantiate(site.span(), default, &bindings, guard))
}
}
impl fmt::Debug for ModeVariant {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ModeVariant")
.field("template", &self.template)
.field("defaults", &self.defaults.keys().collect::<Vec<_>>())
.finish()
}
}
pub struct CompiledDefinition {
name: Name,
display: String,
arity: usize,
text: Option<Arc<ModeVariant>>,
math: Option<Arc<ModeVariant>>,
diagnostics: Vec<FlmDiagnostic>,
}
impl CompiledDefinition {
pub fn name(&self) -> &Name {
&self.name
}
pub fn display_name(&self) -> &str {
&self.display
}
pub fn arity(&self) -> usize {
self.arity
}
pub fn variant(&self, mode: Mode) -> Option<&Arc<ModeVariant>> {
match mode {
Mode::Text => self.text.as_ref(),
Mode::Math => self.math.as_ref(),
_ => None,
}
}
pub fn diagnostics(&self) -> &[FlmDiagnostic] {
&self.diagnostics
}
}
impl fmt::Debug for CompiledDefinition {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CompiledDefinition")
.field("name", &self.name)
.field("text", &self.text)
.field("math", &self.math)
.finish()
}
}
fn declaration_source(display: &str) -> Arc<FlmSource> {
let origin = FlmOrigin::synthetic(format!("declaration of {display}"));
Arc::new(Source::new(String::new()).with_origin(origin))
}
fn compile_variant(
definition: &Definition,
lang: &BuiltLang,
language: &TemplateLanguage,
mode: Mode,
text: &str,
default_indices: &BTreeMap<usize, &str>,
diagnostics: &mut Vec<FlmDiagnostic>,
) -> Option<ModeVariant> {
let display = definition.display_name();
let vocabulary = definition.vocabulary();
let label = format!("expansion of {display}");
let origin_label = format!("template of {display}");
let spec = TemplateSpec {
text,
mode,
vocabulary: &vocabulary,
offset: definition.argument_number_offset,
definition: &display,
label: &label,
origin_label: &origin_label,
user_definition: true,
};
let mut failed = false;
let template = match compile_template_with(&spec, lang, language) {
Ok(template) => {
diagnostics.extend(template.diagnostics().iter().cloned());
Some(template)
}
Err(errors) => {
diagnostics.extend(errors);
failed = true;
None
}
};
let mut defaults = BTreeMap::new();
for (index, default_text) in default_indices {
let label = match index.checked_sub(definition.argument_number_offset) {
Some(number) => format!("default value of #{} of {display}", number + 1),
None => {
let named = definition.args[*index].name.clone();
let what = named.unwrap_or_else(|| format!("argument {}", index + 1));
format!("default value of {what} of {display}")
}
};
let spec = TemplateSpec {
text: default_text,
mode,
vocabulary: &vocabulary,
offset: definition.argument_number_offset,
definition: &display,
label: &label,
origin_label: &label,
user_definition: true,
};
match compile_template_with(&spec, lang, language) {
Ok(compiled) => {
diagnostics.extend(compiled.diagnostics().iter().cloned());
defaults.insert(*index, compiled);
}
Err(errors) => {
diagnostics.extend(errors);
failed = true;
}
}
}
if let Some((template, placeholder)) = default_cycle(&defaults) {
let span = template
.tree()
.get(placeholder)
.map(|node| node.span().clone())
.unwrap_or_else(|| SourceSpan::new(template.source(), 0..0));
let written = template
.placeholder(placeholder)
.map(|reference| reference.written.clone())
.unwrap_or_default();
diagnostics.push(Diagnostic::error(
BadPlaceholder::new(display.clone(), written, PlaceholderProblem::DefaultCycle),
span,
));
failed = true;
}
match (failed, template) {
(false, Some(template)) => Some(ModeVariant {
template: Arc::new(template),
defaults: defaults.into_iter().map(|(index, default)| (index, Arc::new(default))).collect(),
}),
_ => None,
}
}
fn default_cycle(
defaults: &BTreeMap<usize, CompiledTemplate>,
) -> Option<(&CompiledTemplate, NodeId)> {
fn visit<'d>(
index: usize,
defaults: &'d BTreeMap<usize, CompiledTemplate>,
open: &mut Vec<usize>,
done: &mut BTreeSet<usize>,
) -> Option<(&'d CompiledTemplate, NodeId)> {
if done.contains(&index) {
return None;
}
let template = defaults.get(&index)?;
open.push(index);
for (node, reference) in template.placeholders() {
let PlaceholderTarget::Argument(target) = &reference.target else {
continue;
};
if !defaults.contains_key(target) {
continue;
}
if open.contains(target) {
return Some((template, node));
}
if let Some(cycle) = visit(*target, defaults, open, done) {
return Some(cycle);
}
}
open.pop();
done.insert(index);
None
}
let mut done = BTreeSet::new();
for index in defaults.keys() {
let mut open = Vec::new();
if let Some(cycle) = visit(*index, defaults, &mut open, &mut done) {
return Some(cycle);
}
}
None
}
pub fn compile(
definition: &Definition,
lang: &BuiltLang,
) -> Result<CompiledDefinition, Vec<FlmDiagnostic>> {
match TemplateLanguage::new(lang) {
Ok(language) => compile_with(definition, lang, &language),
Err(errors) => Err(minting_diagnostics(&definition.display_name(), &errors)),
}
}
pub fn compile_with(
definition: &Definition,
lang: &BuiltLang,
language: &TemplateLanguage,
) -> Result<CompiledDefinition, Vec<FlmDiagnostic>> {
let display = definition.display_name();
let mut diagnostics: Vec<FlmDiagnostic> = Vec::new();
let declaration = declaration_source(&display);
let at_declaration = || SourceSpan::new(&declaration, 0..0);
if definition.content.is_none() {
diagnostics.push(Diagnostic::error(
BadDefinition::new(display.clone(), DefinitionProblem::NoTemplate),
at_declaration(),
));
}
let mut default_indices: BTreeMap<usize, &str> = BTreeMap::new();
for (key, text) in &definition.defaults {
match definition.argument_index(key) {
Some(index) => {
default_indices.insert(index, text);
}
None => diagnostics.push(Diagnostic::error(
BadDefinition::new(
display.clone(),
DefinitionProblem::UnknownDefault { key: key.clone() },
),
at_declaration(),
)),
}
}
let declared_modes =
[Mode::Text, Mode::Math].into_iter().filter(|&mode| definition.modes.includes(mode));
let (variants, found) = match definition.content.as_deref() {
Some(text) => compile_in_modes(declared_modes, |mode, found| {
compile_variant(definition, lang, language, mode, text, &default_indices, found)
}),
None => (Vec::new(), Vec::new()),
};
diagnostics.extend(found);
let (mut text, mut math) = (None, None);
for (mode, variant) in variants {
match mode {
Mode::Text => text = Some(variant),
_ => math = Some(variant),
}
}
for variant in [text.as_ref(), math.as_ref()].into_iter().flatten() {
let trees =
std::iter::once(variant.template()).chain(variant.defaults().map(|(_, tree)| tree));
for tree in trees {
for (node, reference) in tree.placeholders() {
let PlaceholderTarget::Argument(index) = reference.target else { continue };
if !definition.args.get(index).is_some_and(is_tack_on) {
continue;
}
let span = tree
.tree()
.get(node)
.map(|node| node.span().clone())
.unwrap_or_else(|| SourceSpan::new(tree.source(), 0..0));
diagnostics.push(Diagnostic::error(
BadDefinition::new(
display.clone(),
DefinitionProblem::TackOnPlaceholder {
reference: reference.written.clone(),
},
),
span,
));
}
}
}
if diagnostics.iter().any(|diagnostic| diagnostic.severity() == Severity::Error) {
return Err(diagnostics);
}
Ok(CompiledDefinition {
name: definition.name.clone(),
display,
arity: definition.arity(),
text: text.map(Arc::new),
math: math.map(Arc::new),
diagnostics,
})
}
pub(crate) fn is_tack_on(arg: &ArgDef) -> bool {
arg.kind.tack_on_fields().is_some()
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct EffectiveSignature {
values: Vec<usize>,
flagged: Vec<usize>,
}
impl EffectiveSignature {
pub fn new(
values: impl IntoIterator<Item = usize>,
flagged: impl IntoIterator<Item = usize>,
) -> EffectiveSignature {
let values: BTreeSet<usize> = values.into_iter().collect();
let named: BTreeSet<usize> =
flagged.into_iter().filter(|index| values.contains(index)).collect();
EffectiveSignature {
values: values.into_iter().collect(),
flagged: named.into_iter().collect(),
}
}
pub fn values(&self) -> &[usize] {
&self.values
}
pub fn flagged(&self) -> &[usize] {
&self.flagged
}
pub fn arity(&self) -> usize {
self.values.len() + self.flagged.len()
}
pub fn value_position(&self, index: usize) -> Option<usize> {
let at = self.values.iter().position(|value| *value == index)?;
Some(at + 1)
}
pub fn flag_position(&self, index: usize) -> Option<usize> {
let at = self.flagged.iter().position(|flagged| *flagged == index)?;
Some(self.values.len() + at + 1)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NotRecomposable {
NotCompiled,
AlwaysExpanded,
Specials,
ArgumentShape {
index: usize,
shape: String,
},
HookPlaceholder {
reference: String,
},
Uses {
name: String,
},
}
impl NotRecomposable {
pub fn kind(&self) -> &'static str {
match self {
NotRecomposable::NotCompiled => "not-compiled",
NotRecomposable::AlwaysExpanded => "always-expanded",
NotRecomposable::Specials => "specials",
NotRecomposable::ArgumentShape { .. } => "argument-shape",
NotRecomposable::HookPlaceholder { .. } => "hook-placeholder",
NotRecomposable::Uses { .. } => "uses",
}
}
}
impl fmt::Display for NotRecomposable {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
NotRecomposable::NotCompiled => {
f.write_str("the definition's template was not compiled")
}
NotRecomposable::AlwaysExpanded => f.write_str("the definition is always expanded"),
NotRecomposable::Specials => {
f.write_str("a special character sequence is not a command of the output language")
}
NotRecomposable::ArgumentShape { index, shape } => {
write!(
f,
"argument {} has a shape ({shape}) the output language cannot express",
index + 1
)
}
NotRecomposable::HookPlaceholder { reference } => {
write!(
f,
"the template uses ‘#{reference}’, which is not an argument or the body"
)
}
NotRecomposable::Uses { name } => {
write!(
f,
"the template uses ‘{name}’, which cannot be written as a definition of the output language"
)
}
}
}
}
impl ToDiagnosticValue for NotRecomposable {
fn to_diagnostic_value(&self) -> DiagnosticValue {
let mut fields = vec![(String::from("kind"), self.kind().to_diagnostic_value())];
match self {
NotRecomposable::ArgumentShape { index, shape } => {
fields.push((String::from("index"), index.to_diagnostic_value()));
fields.push((String::from("shape"), shape.to_diagnostic_value()));
}
NotRecomposable::HookPlaceholder { reference } => {
fields.push((String::from("reference"), reference.to_diagnostic_value()));
}
NotRecomposable::Uses { name } => {
fields.push((String::from("name"), name.to_diagnostic_value()));
}
_ => {}
}
DiagnosticValue::Map(fields)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RegistryBuildFacts {
pub recomposition: Result<EffectiveSignature, NotRecomposable>,
pub shares_its_name: bool,
}
pub struct UserDefinition {
definition: Definition,
compiled: LangOwned<CompiledDefinition>,
registry_build_facts: OnceLock<RegistryBuildFacts>,
recursion_limit: OnceLock<usize>,
}
impl UserDefinition {
pub fn new(definition: Definition) -> Arc<UserDefinition> {
Arc::new(UserDefinition {
definition,
compiled: LangOwned::new(),
registry_build_facts: OnceLock::new(),
recursion_limit: OnceLock::new(),
})
}
pub fn recursion_limit(&self) -> usize {
self.recursion_limit.get().copied().unwrap_or(DEFAULT_RECURSION_LIMIT)
}
pub fn record_recursion_limit(&self, limit: usize) {
let _ = self.recursion_limit.set(limit);
}
pub fn definition(&self) -> &Definition {
&self.definition
}
pub fn compiled(&self) -> Option<Arc<CompiledDefinition>> {
self.compiled.get()
}
pub fn record_registry_build_facts(&self, facts: RegistryBuildFacts) -> bool {
self.registry_build_facts.set(facts).is_ok()
}
pub fn recomposable(&self) -> Result<(), NotRecomposable> {
match self.registry_build_facts.get() {
Some(facts) => facts.recomposition.as_ref().map(|_| ()).map_err(Clone::clone),
None => Err(NotRecomposable::NotCompiled),
}
}
pub fn effective_signature(&self) -> Option<&EffectiveSignature> {
self.registry_build_facts.get()?.recomposition.as_ref().ok()
}
pub fn shares_its_name(&self) -> bool {
self.registry_build_facts.get().is_some_and(|facts| facts.shares_its_name)
}
pub fn compile(&self, lang: &BuiltLang) -> Result<Vec<FlmDiagnostic>, Vec<FlmDiagnostic>> {
if self.compiled.get().is_some() {
return Ok(Vec::new());
}
match TemplateLanguage::new(lang) {
Ok(language) => self.compile_with(lang, &language),
Err(errors) => Err(minting_diagnostics(&self.definition.display_name(), &errors)),
}
}
pub fn compile_with(
&self,
lang: &BuiltLang,
language: &TemplateLanguage,
) -> Result<Vec<FlmDiagnostic>, Vec<FlmDiagnostic>> {
if self.compiled.get().is_some() {
return Ok(Vec::new());
}
let compiled = compile_with(&self.definition, lang, language)?;
let warnings = compiled.diagnostics().to_vec();
let _ = self.compiled.set(lang, compiled);
Ok(warnings)
}
pub fn element(self: &Arc<Self>, name: impl Into<ElementName>) -> Arc<ElementSpec> {
let hook: Arc<dyn Expand> = self.clone();
self.element_with(name, hook)
}
pub fn element_with(
self: &Arc<Self>,
name: impl Into<ElementName>,
hook: Arc<dyn Expand>,
) -> Arc<ElementSpec> {
let value: Arc<dyn Any + Send + Sync> = self.clone();
let role: Arc<dyn BlockRoleAspect> = Arc::new(FixedBlockRole(self.definition.block_role));
Arc::new(
ElementSpec::new(name)
.docs(self.definition.docs.clone())
.with_value(value)
.with::<dyn Expand>(hook)
.with::<dyn BlockRoleAspect>(role),
)
}
pub fn element_def(
self: &Arc<Self>,
owner: impl Into<FeatureName>,
element_name: impl Into<ElementName>,
) -> ElementDef {
let hook: Arc<dyn Expand> = self.clone();
self.element_def_with(owner, element_name, hook)
}
pub fn element_def_with(
self: &Arc<Self>,
owner: impl Into<FeatureName>,
element_name: impl Into<ElementName>,
hook: Arc<dyn Expand>,
) -> ElementDef {
let names: Vec<Name> = match self.definition.kind {
DefinitionKind::Specials => Vec::new(),
_ => vec![self.definition.name.clone()],
};
let element = self.element_with(element_name, hook);
ElementDef::new(owner, names, self.definition.syntax(), element)
.docs(self.definition.docs.clone())
.modes(self.definition.modes.modes().iter().copied())
}
pub fn variant_for_use(&self, node: &NodeRef<'_, Flm>) -> Result<Arc<ModeVariant>, BadDefinition> {
let display = self.definition.display_name();
let mode = node.parsing_state().mode();
let Some(compiled) = self.compiled.get() else {
return Err(BadDefinition::new(display, DefinitionProblem::NotCompiled));
};
compiled.variant(mode).cloned().ok_or_else(|| {
BadDefinition::new(display, DefinitionProblem::NotInForceInMode { mode })
})
}
pub fn override_def(&self, owner: impl Into<FeatureName>) -> Option<OverrideDef> {
self.definition.overrides.then(|| OverrideDef {
owner: owner.into(),
kind: self.definition.callable_kind(),
name: self.definition.name.clone(),
})
}
}
impl fmt::Debug for UserDefinition {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("UserDefinition")
.field("definition", &self.definition)
.field("compiled", &self.compiled.get().is_some())
.field("registry_build_facts", &self.registry_build_facts.get())
.finish()
}
}
pub struct DefinitionBindings<'t> {
site: NodeRef<'t, Flm>,
variant: &'t ModeVariant,
}
impl<'t> DefinitionBindings<'t> {
pub fn new(site: NodeRef<'t, Flm>, variant: &'t ModeVariant) -> DefinitionBindings<'t> {
DefinitionBindings { site, variant }
}
}
impl fmt::Debug for DefinitionBindings<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("DefinitionBindings").field("site", &self.site.id()).finish()
}
}
impl PlaceholderBindings for DefinitionBindings<'_> {
fn value<'a>(
&'a self,
target: &PlaceholderTarget,
_substitution: Option<NodeSlice<'_, Flm>>,
) -> PlaceholderValue<'a> {
match target {
PlaceholderTarget::Argument(index) => match substituted_argument_nodes(
&self.site,
*index,
) {
Some(content) => PlaceholderValue::Provided(content),
None => match self.variant.default_of(*index) {
Some(template) => PlaceholderValue::Default(template),
None => PlaceholderValue::NoValue,
},
},
PlaceholderTarget::Body => match self.site.body() {
Some(body) => PlaceholderValue::Provided(body),
None => PlaceholderValue::NoValue,
},
PlaceholderTarget::Extra(_) => PlaceholderValue::Unresolvable,
}
}
}
pub(crate) fn substituted_argument_nodes<'t>(
site: &NodeRef<'t, Flm>,
index: usize,
) -> Option<NodeSlice<'t, Flm>> {
site.argument_content_nodes(index)
}
impl Expand for UserDefinition {
fn policy(&self) -> ExpandPolicy {
self.definition.expand
}
fn expand(
&self,
node: NodeRef<'_, Flm>,
cx: &mut ExpandCx<'_>,
xp: &mut dyn Expander,
) -> Result<Expansion, ExpandError> {
let variant = match self.variant_for_use(&node) {
Ok(variant) => variant,
Err(condition) => {
let diagnostic = Diagnostic::error(condition, node.span().clone());
return Ok(Expansion::Emit(xp.recover(cx, node, diagnostic)?));
}
};
let bindings = DefinitionBindings::new(node, &variant);
Ok(Expansion::Emit(xp.instantiate(cx, node, variant.template(), &bindings)?))
}
}