use quote::ToTokens;
use syn::{Expr, spanned::Spanned};
use super::graft::{GraftEndpointSpan, GraftExpressions, GraftSpans, GraftSyntax};
use crate::syntax::{FaceSyntaxError, SyntaxLocation, compact_tokens, location, syntax_error};
fn endpoint(expr: &Expr) -> GraftEndpointSpan {
let end = expr.span().end();
GraftEndpointSpan {
start: location(expr.span()),
end: SyntaxLocation {
line: end.line,
column: end.column + 1,
},
}
}
pub(super) fn entries(
item: &syn::ItemConst,
imports: &super::super::imports::Imports,
) -> Result<Option<Vec<GraftSyntax>>, FaceSyntaxError> {
let last = match item.ty.as_ref() {
syn::Type::Reference(reference) => match reference.elem.as_ref() {
syn::Type::Slice(slice) => match slice.elem.as_ref() {
syn::Type::Path(path) => path
.path
.segments
.last()
.map(|segment| segment.ident.to_string()),
_ => None,
},
_ => None,
},
syn::Type::Path(path) => path
.path
.segments
.last()
.map(|segment| segment.ident.to_string()),
_ => None,
};
if !matches!(
last.as_deref(),
Some("Graft") | Some("Plan") | Some("PlanEntry")
) {
return Ok(None);
}
let expression = match item.expr.as_ref() {
Expr::Reference(reference) => reference.expr.as_ref(),
other => other,
};
let expression = match (last.as_deref(), expression) {
(Some("Graft") | Some("PlanEntry"), _) => expression,
(Some("Plan"), Expr::Call(call)) => {
let is_of = matches!(
call.func.as_ref(),
Expr::Path(path)
if path.path.segments.last().is_some_and(|s| s.ident == "of")
);
if !is_of || call.args.len() != 1 {
return Err(syntax_error(
item.expr.span(),
"a plan declaration is written `Plan::of([ … ])`",
));
}
match call.args.first() {
Some(Expr::Array(array)) => {
return decode_array(array, imports);
}
Some(other) => {
return Err(syntax_error(
other.span(),
"a plan declaration requires a literal array",
));
}
None => return Err(syntax_error(item.expr.span(), "`Plan::of` needs one array")),
}
}
_ => return Ok(None),
};
let Expr::Array(array) = expression else {
return Err(syntax_error(
expression.span(),
"a static graft declaration requires a literal array",
));
};
decode_array(array, imports)
}
fn decode_array(
array: &syn::ExprArray,
imports: &super::super::imports::Imports,
) -> Result<Option<Vec<GraftSyntax>>, FaceSyntaxError> {
array
.elems
.iter()
.map(|expr| entry(expr, imports))
.collect::<Result<Vec<_>, _>>()
.map(Some)
}
fn decode_chain(
expr: &Expr,
imports: &super::super::imports::Imports,
) -> Result<(String, bool), FaceSyntaxError> {
match expr {
Expr::Lit(literal) => match &literal.lit {
syn::Lit::Str(value) => Ok((value.value(), false)),
_ => Err(syntax_error(
expr.span(),
"static graft endpoints must be Rust paths or string literals",
)),
},
Expr::Path(_) => Ok((
crate::syntax::catalog_reference(&super::super::imports::expand(
&compact_tokens(expr.to_token_stream()),
imports,
)),
true,
)),
_ => Err(syntax_error(
expr.span(),
"static graft endpoints must be Rust paths or string literals",
)),
}
}
fn call<'a>(expr: &'a Expr, name: &str, count: usize) -> Option<Vec<&'a Expr>> {
let Expr::Call(call) = expr else {
return None;
};
let Expr::Path(path) = call.func.as_ref() else {
return None;
};
(path.path.segments.last()?.ident == name && call.args.len() == count)
.then(|| call.args.iter().collect())
}
fn split_chain(expr: &Expr) -> Option<(Option<&Expr>, Option<&Expr>, bool)> {
let mut innermost = expr;
while let Expr::MethodCall(method) = innermost {
innermost = &method.receiver;
}
call(innermost, "cut", 1)?;
let mut tail = expr;
let mut replacement: Option<&Expr> = None;
let mut end: Option<&Expr> = None;
let mut full = false;
while let Expr::MethodCall(method) = tail {
match method.method.to_string().as_str() {
"graft" if method.args.len() == 1 && replacement.is_none() => {
replacement = Some(&method.args[0]);
}
"to" if method.args.len() == 1 && end.is_none() => end = Some(&method.args[0]),
"full" if method.args.is_empty() => full = true,
_ => return None,
}
if std::ptr::eq(method.receiver.as_ref(), innermost) {
break;
}
tail = &method.receiver;
}
Some((replacement, end, full))
}
fn entry(
expr: &Expr,
imports: &super::super::imports::Imports,
) -> Result<GraftSyntax, FaceSyntaxError> {
let error = || {
syntax_error(
expr.span(),
"expected graft(node | range(start, end) | subtree(...)).with(replacement)",
)
};
if let Some((replacement, end, full)) = split_chain(expr) {
let target = call(
{
let mut innermost = expr;
while let Expr::MethodCall(method) = innermost {
innermost = &method.receiver;
}
innermost
},
"cut",
1,
)
.ok_or_else(error)?[0];
if full && end.is_some() {
return Err(syntax_error(
expr.span(),
"`to(…)` and `full()` name two different shapes; use one of them",
));
}
let replacement = replacement.ok_or_else(error)?;
let (cut, typed) = decode_chain(target, imports)?;
let cut_end = end.map(|e| decode_chain(e, imports)).transpose()?;
let (graft, replacement_typed) = decode_chain(replacement, imports)?;
if replacement_typed != typed || cut_end.as_ref().is_some_and(|(_, t)| *t != typed) {
return Err(syntax_error(
expr.span(),
"graft endpoints must all use identities or all use strings",
));
}
let cut_end = cut_end.map(|(value, _)| value);
return Ok(GraftSyntax {
expressions: typed.then(|| GraftExpressions {
cut: cut.clone(),
cut_end: cut_end.clone(),
graft: graft.clone(),
}),
cut,
cut_end,
graft,
full,
location: location(expr.span()),
cfg: None,
spans: typed.then(|| GraftSpans {
cut: endpoint(target),
cut_end: end.map(endpoint),
graft: endpoint(replacement),
}),
});
}
let Expr::MethodCall(method) = expr else {
return Err(error());
};
if method.method != "with" || method.args.len() != 1 || method.turbofish.is_some() {
return Err(error());
}
let target = call(&method.receiver, "graft", 1).ok_or_else(error)?[0];
let replacement = &method.args[0];
let full = call(target, "subtree", 1);
let target = full.as_ref().map_or(target, |args| args[0]);
let endpoints = call(target, "range", 2);
if full.is_some() && endpoints.is_some() {
return Err(syntax_error(
expr.span(),
"subtree(range(...)) has no defined static graft meaning; use one subtree per face",
));
}
let (start, end) = endpoints
.as_ref()
.map_or((target, None), |args| (args[0], Some(args[1])));
let decode = |expr: &Expr| -> Result<(String, bool), FaceSyntaxError> {
match expr {
Expr::Lit(literal) => match &literal.lit {
syn::Lit::Str(value) => Ok((value.value(), false)),
_ => Err(error()),
},
Expr::Path(_) => Ok((
crate::syntax::catalog_reference(&super::super::imports::expand(
&compact_tokens(expr.to_token_stream()),
imports,
)),
true,
)),
_ => Err(syntax_error(
expr.span(),
"static graft endpoints must be Rust paths or string literals",
)),
}
};
let (cut, typed) = decode(start)?;
let cut_end = end.map(decode).transpose()?;
let (graft, replacement_typed) = decode(replacement)?;
if replacement_typed != typed || cut_end.as_ref().is_some_and(|(_, t)| *t != typed) {
return Err(syntax_error(
expr.span(),
"graft endpoints must all use identities or all use strings",
));
}
let cut_end = cut_end.map(|(value, _)| value);
Ok(GraftSyntax {
expressions: typed.then(|| GraftExpressions {
cut: cut.clone(),
cut_end: cut_end.clone(),
graft: graft.clone(),
}),
cut,
cut_end,
graft,
full: full.is_some(),
location: location(expr.span()),
cfg: None,
spans: typed.then(|| GraftSpans {
cut: endpoint(start),
cut_end: end.map(endpoint),
graft: endpoint(replacement),
}),
})
}
pub fn render_native_graft_expression(
cut: &str,
end: Option<&str>,
full: bool,
replacement: &str,
) -> Result<String, FaceSyntaxError> {
if full && end.is_some() {
return Err(syntax_error(
proc_macro2::Span::call_site(),
"subtree(range(...)) has no defined static graft meaning",
));
}
for path in [Some(cut), end, Some(replacement)].into_iter().flatten() {
syn::parse_str::<syn::Expr>(path)
.and_then(|expr| {
if matches!(
expr,
Expr::Path(_)
| Expr::Lit(syn::ExprLit {
lit: syn::Lit::Str(_),
..
})
) {
Ok(expr)
} else {
Err(syn::Error::new(
expr.span(),
"expected an identity path or string literal",
))
}
})
.map_err(|error| syntax_error(error.span(), "expected a Rust identity path"))?;
}
let logical = |path: &str| {
if path.starts_with("crate::")
&& path.ends_with("::NODE_ID")
&& !path.starts_with("crate::catalog::")
{
path.replacen("crate::", "crate::catalog::", 1)
} else {
path.to_owned()
}
};
let mut target = end.map_or_else(
|| logical(cut),
|end| {
format!(
"xirang_toolchain::range({}, {})",
logical(cut),
logical(end)
)
},
);
if full {
target = format!("xirang_toolchain::subtree({target})");
}
Ok(format!(
"xirang_toolchain::graft({target}).with({})",
logical(replacement)
))
}
pub fn append_native_graft(source: &str, expression: &str) -> Result<String, FaceSyntaxError> {
let file = super::super::nesting::parse_file(source)?;
let mut index = 0;
let name = loop {
let name = format!("XIRANG_GRAFTS_{index}");
if !file
.items
.iter()
.any(|item| matches!(item, syn::Item::Const(item) if item.ident == name))
{
break name;
}
index += 1;
};
let addition = format!(
"\n/// Graft declaration.\n/// Graft 声明。\npub const {name}: &[xirang_toolchain::Graft] = &[\n {expression},\n];\n"
);
let entries = super::graft::graft_entries(&addition)?;
if entries.len() != 1 {
return Err(syntax_error(
proc_macro2::Span::call_site(),
"expected one new graft",
));
}
Ok(format!("{source}{addition}"))
}
pub fn repoint_native_graft(
source: &str,
cut: &str,
graft: &str,
) -> Result<Option<String>, FaceSyntaxError> {
use syn::visit::Visit;
let entries = super::graft::graft_entries(source)?;
let Some(selected) = entries
.iter()
.find(|entry| entry.cut == cut && entry.graft == graft)
else {
return Ok(None);
};
struct Repoint<'a> {
location: &'a crate::syntax::SyntaxLocation,
spans: Option<(proc_macro2::Span, proc_macro2::Span)>,
}
impl<'ast> Visit<'ast> for Repoint<'_> {
fn visit_expr_method_call(&mut self, method: &'ast syn::ExprMethodCall) {
if location(method.span()) == *self.location
&& method.method == "with"
&& method.args.len() == 1
&& let Some(args) = call(&method.receiver, "graft", 1)
{
let target = args[0];
let subtree = call(target, "subtree", 1);
let target = subtree.as_ref().map_or(target, |args| args[0]);
let range = call(target, "range", 2);
let start = range.as_ref().map_or(target, |args| args[0]);
self.spans = Some((start.span(), method.args[0].span()));
}
syn::visit::visit_expr_method_call(self, method);
}
}
let file = super::super::nesting::parse_file(source)?;
let mut visitor = Repoint {
location: &selected.location,
spans: None,
};
visitor.visit_file(&file);
let Some((target, replacement)) = visitor.spans else {
return Ok(None);
};
let range = |span: proc_macro2::Span| -> Result<std::ops::Range<usize>, FaceSyntaxError> {
use super::super::face::source_offset;
Ok(source_offset(source, &location(span))?
..source_offset(
source,
&crate::syntax::SyntaxLocation {
line: span.end().line,
column: span.end().column + 1,
},
)?)
};
let mut output = source.to_owned();
output.replace_range(range(replacement)?, &source[range(target)?]);
Ok(Some(output))
}
#[cfg(test)]
#[path = "native_graft_tests.rs"]
mod native_graft_tests;