use std::collections::{BTreeMap, HashMap};
use std::rc::Rc;
use std::sync::LazyLock;
use serde_json::{Map, Value};
use crate::check::inline_diagnostics;
use crate::digest::{digest, sha256_hex};
use crate::inline::{TokenType, inline_tokens};
use crate::jcs::{canonical_json, json_digest};
use crate::js::{JS_DOT, JS_SPACES, blank, is_str, js_number, js_trim, js_value};
use crate::pattern::Pattern;
use crate::read::{ProseRef, ReadOptions, Reading, read, sort_diagnostics, value_fits};
use crate::registry::is_rule;
use crate::text::{ReferenceRecord, TextOptions, interpolate_values, literal, text_of, value_text};
use crate::types::{Diagnostic, Document, Identity, KeyOrder, Metadata, Node, Object, Range, Severity};
pub const RESOLVED_FORMAT: &str = "instruction-resolved/1";
const DEFAULT_URI: &str = "document.md";
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Source {
pub uri: String,
pub text: String,
pub version: String,
}
pub type Loader<'a> = &'a dyn Fn(&str) -> Option<Source>;
#[derive(Clone, Default)]
pub struct ResolveOptions<'a> {
pub uri: String,
pub version: String,
pub params: Object,
pub load: Option<Loader<'a>>,
pub max_depth: usize,
pub max_sources: usize,
}
#[derive(Clone, Debug, PartialEq)]
pub enum Selector {
Id(String),
Heading { heading: String, occurrence: Option<f64> },
Lines(f64, f64),
}
impl Selector {
pub fn to_json(&self) -> Value {
let mut m = Map::new();
match self {
Selector::Id(id) => {
m.insert("id".into(), id.clone().into());
}
Selector::Heading { heading, occurrence } => {
m.insert("heading".into(), heading.clone().into());
if let Some(o) = occurrence {
m.insert("occurrence".into(), crate::js::num(*o));
}
}
Selector::Lines(a, b) => {
m.insert("lines".into(), Value::Array(vec![crate::js::num(*a), crate::js::num(*b)]));
}
}
Value::Object(m)
}
fn describe(&self) -> String {
match self {
Selector::Id(id) => format!("has the id {id}"),
Selector::Heading { heading, .. } => format!("is the heading \"{heading}\""),
Selector::Lines(..) => "matches the selector".into(),
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Dependency {
pub uri: String,
pub resolved_uri: String,
pub sha256: String,
pub mode: String,
pub version: String,
pub selector: Option<Selector>,
pub instance: String,
}
impl Dependency {
pub fn to_json(&self) -> Value {
let mut m = Map::new();
m.insert("uri".into(), self.uri.clone().into());
m.insert("resolved_uri".into(), self.resolved_uri.clone().into());
m.insert("sha256".into(), self.sha256.clone().into());
m.insert("mode".into(), self.mode.clone().into());
if !self.version.is_empty() {
m.insert("version".into(), self.version.clone().into());
}
if let Some(s) = &self.selector {
m.insert("selector".into(), s.to_json());
}
m.insert("instance".into(), self.instance.clone().into());
Value::Object(m)
}
}
#[derive(Clone, Debug, PartialEq, Default)]
pub struct Provenance {
pub instance: String,
pub uri: String,
pub range: Option<Range>,
pub selector: Option<Selector>,
pub operation: String,
pub target: String,
pub reason: String,
pub modified_by: String,
pub original: Option<Node>,
}
impl Provenance {
pub fn to_json(&self) -> Value {
let mut m = Map::new();
m.insert("instance".into(), self.instance.clone().into());
m.insert("uri".into(), self.uri.clone().into());
if let Some(r) = self.range {
m.insert("range".into(), r.to_json());
}
if let Some(s) = &self.selector {
m.insert("selector".into(), s.to_json());
}
for (k, v) in
[("operation", &self.operation), ("target", &self.target), ("reason", &self.reason), ("modified_by", &self.modified_by)]
{
if !v.is_empty() {
m.insert(k.into(), v.clone().into());
}
}
if let Some(n) = &self.original {
m.insert("original".into(), n.to_json());
}
Value::Object(m)
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct ExtensionBinding {
pub instance: String,
pub alias: String,
pub id: String,
pub version: String,
pub sha256: String,
}
impl ExtensionBinding {
pub fn to_json(&self) -> Value {
let mut m = Map::new();
for (k, v) in
[("instance", &self.instance), ("alias", &self.alias), ("id", &self.id), ("version", &self.version), ("sha256", &self.sha256)]
{
m.insert(k.into(), v.clone().into());
}
Value::Object(m)
}
}
#[derive(Clone, Debug, PartialEq, Default)]
pub struct ResolvedDocument {
pub uri: String,
pub sha256: String,
pub version: String,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Resolved {
pub format: String,
pub status: String,
pub document: ResolvedDocument,
pub body: Vec<Node>,
pub extensions: Vec<ExtensionBinding>,
pub objects: Vec<ReferenceRecord>,
pub resources: Vec<ReferenceRecord>,
pub dependencies: Vec<Dependency>,
pub provenance: Vec<Provenance>,
pub diagnostics: Vec<Diagnostic>,
pub resolved_digest: String,
}
impl Resolved {
pub fn manifest(&self) -> Manifest {
Manifest {
format: self.format.clone(),
status: self.status.clone(),
document: self.document.clone(),
dependencies: self.dependencies.clone(),
resolved_digest: self.resolved_digest.clone(),
}
}
pub fn to_json(&self) -> Value {
let mut m = self.artifact();
m.insert("resolved_digest".into(), self.resolved_digest.clone().into());
Value::Object(m)
}
fn artifact(&self) -> Map<String, Value> {
let mut m = Map::new();
m.insert("format".into(), self.format.clone().into());
m.insert("status".into(), self.status.clone().into());
m.insert("document".into(), self.document.to_json());
m.insert("body".into(), Value::Array(self.body.iter().map(Node::to_json).collect()));
m.insert("extensions".into(), Value::Array(self.extensions.iter().map(ExtensionBinding::to_json).collect()));
m.insert("objects".into(), Value::Array(self.objects.iter().map(ReferenceRecord::to_json).collect()));
m.insert("resources".into(), Value::Array(self.resources.iter().map(ReferenceRecord::to_json).collect()));
m.insert("dependencies".into(), Value::Array(self.dependencies.iter().map(Dependency::to_json).collect()));
m.insert("provenance".into(), Value::Array(self.provenance.iter().map(Provenance::to_json).collect()));
m.insert("diagnostics".into(), Value::Array(self.diagnostics.iter().map(Diagnostic::to_json).collect()));
m
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Manifest {
pub format: String,
pub status: String,
pub document: ResolvedDocument,
pub dependencies: Vec<Dependency>,
pub resolved_digest: String,
}
impl Manifest {
pub fn to_json(&self) -> Value {
let mut m = Map::new();
m.insert("format".into(), self.format.clone().into());
m.insert("status".into(), self.status.clone().into());
m.insert("document".into(), self.document.to_json());
m.insert("dependencies".into(), Value::Array(self.dependencies.iter().map(Dependency::to_json).collect()));
m.insert("resolved_digest".into(), self.resolved_digest.clone().into());
Value::Object(m)
}
}
impl ResolvedDocument {
pub fn to_json(&self) -> Value {
let mut d = Map::new();
d.insert("uri".into(), self.uri.clone().into());
d.insert("sha256".into(), self.sha256.clone().into());
if !self.version.is_empty() {
d.insert("version".into(), self.version.clone().into());
}
Value::Object(d)
}
}
#[derive(Clone, Debug)]
pub struct Resolution {
pub ok: bool,
pub resolved: Resolved,
pub text: String,
pub diagnostics: Vec<Diagnostic>,
pub root: Reading,
}
pub fn resolve(text: &str, opts: &ResolveOptions) -> Resolution {
let uri = if opts.uri.is_empty() { DEFAULT_URI.to_string() } else { opts.uri.clone() };
let limit = if opts.max_sources == 0 { 64 } else { opts.max_sources };
let mut sources: BTreeMap<String, Option<Source>> = BTreeMap::new();
let mut pending = references_of(&read(text, &ReadOptions { uri: uri.clone(), ..ReadOptions::default() }), &uri);
if let Some(load) = opts.load {
while !pending.is_empty() && sources.len() < limit {
let round: Vec<String> = pending.drain(..).filter(|u| !sources.contains_key(u)).collect();
for u in round {
if sources.len() >= limit {
break;
}
if sources.contains_key(&u) {
continue;
}
let s = load(&u);
if let Some(s) = &s {
for next in references_of(&read(&s.text, &ReadOptions { uri: s.uri.clone(), ..ReadOptions::default() }), &s.uri) {
if !sources.contains_key(&next) && !pending.contains(&next) {
pending.push(next);
}
}
}
sources.insert(u, s);
}
}
}
let loaded: HashMap<String, Source> = sources.into_iter().filter_map(|(k, v)| v.map(|v| (k, v))).collect();
resolve_with(text, &loaded, opts)
}
pub fn resolve_with(text: &str, sources: &HashMap<String, Source>, opts: &ResolveOptions) -> Resolution {
let uri = if opts.uri.is_empty() { DEFAULT_URI.to_string() } else { opts.uri.clone() };
let root = Rc::new(Loaded {
uri: uri.clone(),
sha256: digest(text.as_bytes()),
version: opts.version.clone(),
read: read(text, &ReadOptions { uri, ..ReadOptions::default() }),
});
let lookup = |u: &str| -> Option<Rc<Loaded>> {
let s = sources.get(u)?;
Some(Rc::new(Loaded {
uri: s.uri.clone(),
sha256: digest(s.text.as_bytes()),
version: s.version.clone(),
read: read(&s.text, &ReadOptions { uri: s.uri.clone(), ..ReadOptions::default() }),
}))
};
run(root, &lookup, opts)
}
pub fn resolve_tree(document: &Document, sources: &HashMap<String, Document>, opts: &ResolveOptions) -> Resolution {
let as_loaded = |d: &Document, u: &str| -> Rc<Loaded> {
let u = if d.uri.is_empty() { u.to_string() } else { d.uri.clone() };
Rc::new(Loaded { uri: u.clone(), sha256: json_digest(&d.json_value()), version: String::new(), read: from_tree(d, &u) })
};
let uri = if !opts.uri.is_empty() {
opts.uri.clone()
} else if !document.uri.is_empty() {
document.uri.clone()
} else {
DEFAULT_URI.to_string()
};
let lookup = |u: &str| sources.get(u).map(|d| as_loaded(d, u));
run(as_loaded(document, &uri), &lookup, opts)
}
fn run(root: Rc<Loaded>, lookup: &dyn Fn(&str) -> Option<Rc<Loaded>>, opts: &ResolveOptions) -> Resolution {
let depth = if opts.max_depth == 0 { 8 } else { opts.max_depth };
let mut c = Composer {
lookup,
depth,
diagnostics: Vec::new(),
provenance: Vec::new(),
dependencies: Vec::new(),
partial: false,
identities: HashMap::new(),
loaded: HashMap::new(),
};
c.diagnostics.extend(root.read.diagnostics.iter().cloned());
c.diagnostics.extend(inline_diagnostics(&root.read));
let body = c.compose(&root, &[], "root", &opts.params).unwrap_or_default();
c.check_allowances(&body, &root.uri);
let mut diagnostics = c.diagnostics.clone();
sort_diagnostics(&mut diagnostics, true);
let mut partial = c.partial;
let mut ok = true;
for d in &diagnostics {
partial = partial || d.code == "reference-optional" || d.code == "parameter-optional";
ok = ok && d.severity != Severity::Error;
}
let mut resolved = Resolved {
format: RESOLVED_FORMAT.into(),
status: if partial { "partial".into() } else { "complete".into() },
document: ResolvedDocument { uri: root.uri.clone(), sha256: root.sha256.clone(), version: root.version.clone() },
body,
extensions: Vec::new(),
objects: Vec::new(),
resources: Vec::new(),
dependencies: std::mem::take(&mut c.dependencies),
provenance: std::mem::take(&mut c.provenance),
diagnostics: diagnostics.clone(),
resolved_digest: String::new(),
};
resolved.resolved_digest = format!("sha256:{}", sha256_hex(canonical_json(&Value::Object(resolved.artifact())).as_bytes()));
let identities = &c.identities;
let known = |instance: &str, id: &str| identities.get(instance).is_some_and(|l| l.read.identity(id).is_some());
let mut records = resolved.objects.clone();
records.extend(resolved.resources.iter().cloned());
let text = text_of(&resolved.body, &records, &resolved.provenance, &TextOptions { known: Some(&known), ..TextOptions::default() });
let root_read = root.read.clone();
Resolution { ok, resolved, text, diagnostics, root: root_read }
}
fn from_tree(document: &Document, uri: &str) -> Reading {
let mut r = Reading::empty();
let mut body = document.body.clone();
fn walk(nodes: &mut [Node], quoted: bool, r: &mut Reading) {
for n in nodes {
if n.is_markdown() {
if !quoted {
n.prose = true;
r.prose_order.push(ProseRef { source: n.source.clone(), range: n.range });
}
continue;
}
if let Some(Value::String(id)) = n.attrs.get("id") {
r.add_identity(Identity { id: id.clone(), kind: n.kind.clone(), line: n.range.map_or(0, |rg| rg.start) }, true);
}
let q = quoted || literal(n);
if let Some(children) = n.children.as_mut() {
walk(children, q, r);
}
}
}
walk(&mut body, false, &mut r);
r.document = Document {
format: document.format.clone(),
uri: uri.to_string(),
metadata: Metadata {
front: document.metadata.front.clone(),
back: document.metadata.back.clone(),
front_order: document.metadata.front_order.clone(),
},
body,
raw: None,
};
r
}
pub fn references_of(r: &Reading, base: &str) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
let mut add = |target: &str| {
let u = without_fragment(&resolve_uri(&named(r, target), base)).to_string();
if !out.contains(&u) {
out.push(u);
}
};
if let Some(Value::Array(list)) = r.document.metadata.front.get("extends") {
for e in list {
if let Some(Value::String(u)) = e.get("uri") {
add(u);
}
}
}
fn walk(nodes: &[Node], add: &mut dyn FnMut(&str)) {
for n in nodes {
if !n.is_directive() {
continue;
}
if n.kind == "include"
&& let Some(Value::String(src)) = n.attrs.get("src")
{
add(src);
}
walk(n.children(), add);
}
}
walk(&r.document.body, &mut add);
out
}
struct Loaded {
uri: String,
sha256: String,
version: String,
read: Reading,
}
struct ImportRef {
uri: String,
alias: String,
mode: Option<Value>,
sha256: Option<Value>,
version: Option<Value>,
select_value: Option<Value>,
required: bool,
with: Object,
inherit: bool,
line: u32,
}
struct Composer<'l> {
lookup: &'l dyn Fn(&str) -> Option<Rc<Loaded>>,
depth: usize,
diagnostics: Vec<Diagnostic>,
provenance: Vec<Provenance>,
dependencies: Vec<Dependency>,
partial: bool,
identities: HashMap<String, Rc<Loaded>>,
loaded: HashMap<String, Rc<Loaded>>,
}
fn where_(doc: &Loaded, instance: &str) -> String {
if instance == "root" { String::new() } else { doc.uri.clone() }
}
fn front_line(r: &Reading) -> u32 {
r.front_range.map_or(0, |fr| fr.start)
}
impl Composer<'_> {
fn widened(&mut self, before: &Object, after: &Object, id: &str, uri: String, line: u32) {
let w = crate::allowance::widenings(before, after);
if !w.is_empty() {
self.diag(
"allowance-widened",
Severity::Error,
format!("#{id}: an extending document may only narrow an inherited allowance; this widens {}", w.join(", ")),
uri,
line,
);
if let Some(d) = self.diagnostics.last_mut() {
d.target = format!("#{id}");
}
}
}
fn check_allowances(&mut self, body: &[Node], root: &str) {
let mut seen: std::collections::HashSet<(u32, &'static str)> =
self.diagnostics.iter().map(|d| (d.range.map_or(0, |r| r.start), d.code)).collect();
let mut found: Vec<(&'static str, String, String, u32, String)> = Vec::new();
self.visit_allowances(body, root, &mut found);
for (code, message, uri, line, target) in found {
if seen.insert((line, code)) {
self.diag(code, Severity::Error, message, uri, line);
if let Some(d) = self.diagnostics.last_mut() {
d.target = target;
}
}
}
}
fn kind_of(&self, instance: &str, reference: &str) -> Option<String> {
let r = reference.trim_start_matches(['#', '&']);
let parts: Vec<&str> = r.split('/').collect();
let (inst, id) = if parts.len() > 1 {
(format!("{instance}/{}", parts[..parts.len() - 1].join("/")), parts[parts.len() - 1])
} else {
(instance.to_string(), parts[0])
};
if let Some(found) = self.identities.get(&inst).and_then(|l| l.read.identity(id)) {
return Some(found.kind.clone());
}
let prefix = format!("{instance}/");
let kinds: Vec<String> = self
.identities
.iter()
.filter(|(k, _)| k.starts_with(&prefix))
.filter_map(|(_, l)| l.read.identity(id).map(|i| i.kind.clone()))
.collect();
if kinds.len() == 1 { kinds.into_iter().next() } else { None }
}
fn visit_allowances(&self, nodes: &[Node], root: &str, found: &mut Vec<(&'static str, String, String, u32, String)>) {
for n in nodes {
if !n.is_directive() {
continue;
}
if n.kind == "allowance" {
let instance = if n.instance.is_empty() { "root" } else { n.instance.as_str() };
let uri = if instance == "root" { String::new() } else { root.to_string() };
let line = n.range.map_or(0, |r| r.start);
let id = n.attrs.get("id").and_then(Value::as_str).unwrap_or("");
let target = if id.is_empty() { String::new() } else { format!("#{id}") };
let mut say = |code: &'static str, message: String| found.push((code, message, uri.clone(), line, target.clone()));
for p in crate::allowance::problems(&n.attrs) {
say(p.code, format!("allowance #{id}: {}", p.message));
}
for w in crate::allowance::list(n.attrs.get("wallet")).into_iter().filter(|w| !w.is_empty()) {
match self.kind_of(instance, &w) {
None => say("reference-missing", format!("allowance #{id}: wallet {w} names nothing")),
Some(k) if k != "wallet" => say("reference-kind", format!("allowance #{id}: {w} is a {k}, not a wallet")),
_ => {}
}
}
if let Some(a) = n.attrs.get("approver").and_then(Value::as_str).filter(|a| a.starts_with('#')) {
match self.kind_of(instance, a) {
None => say("reference-missing", format!("allowance #{id}: approver {a} names nothing")),
Some(k) if k != "person" && k != "role" => say(
"allowance-approver-not-person",
format!("allowance #{id}: the approver {a} is a {k}; a person or a role approves, never an agent"),
),
_ => {}
}
}
if n.attrs.contains_key("payees") {
for p in crate::allowance::list(n.attrs.get("payees")).into_iter().filter(|p| p.starts_with('&')) {
if self.kind_of(instance, &p).is_none() {
say("reference-missing", format!("allowance #{id}: payee {p} names nothing"));
}
}
}
}
self.visit_allowances(n.children(), root, found);
}
}
fn diag(&mut self, code: &'static str, severity: Severity, message: String, uri: String, line: u32) {
let mut d = Diagnostic::new(code, severity, message, line);
d.uri = uri;
self.diagnostics.push(d);
}
fn compose(&mut self, doc: &Rc<Loaded>, trail: &[String], instance: &str, values: &Object) -> Option<Vec<Node>> {
let r = &doc.read;
let uri = where_(doc, instance);
if trail.contains(&doc.uri) {
let mut path = trail.to_vec();
path.push(doc.uri.clone());
self.diag("composition-cycle", Severity::Error, format!("{} composes itself: {}", doc.uri, path.join(" → ")), uri, 0);
return None;
}
if trail.len() >= self.depth {
self.diag(
"limit-exceeded",
Severity::Error,
format!("composition is deeper than {} documents at {}", self.depth, doc.uri),
uri,
0,
);
return None;
}
self.loaded.entry(doc.uri.clone()).or_insert_with(|| doc.clone());
self.identities.insert(instance.to_string(), doc.clone());
let scope = self.parameters(doc, instance, values);
self.extensions(doc, instance);
let mut aliases: Vec<String> = Vec::new();
let mut inherited: Vec<Node> = Vec::new();
let bases = r.document.metadata.front.get("extends");
if bases.is_some() && !bases.is_some_and(Value::is_array) {
self.diag(
"invalid-metadata",
Severity::Error,
"extends is a list of base records: { uri, as, mode, sha256, version, select, with }".into(),
uri.clone(),
front_line(r),
);
}
if let Some(Value::Array(list)) = bases {
for b in list {
let u = b.get("uri").and_then(Value::as_str);
let alias = b.get("as").and_then(Value::as_str).filter(|a| !a.is_empty());
let (Some(u), Some(alias)) = (u, alias) else {
self.diag(
"invalid-metadata",
Severity::Error,
"each base in extends has a uri and an alias (as)".into(),
uri.clone(),
front_line(r),
);
continue;
};
if aliases.iter().any(|a| a == alias) {
self.diag(
"duplicate-id",
Severity::Error,
format!("the alias \"{alias}\" is used twice in {}", doc.uri),
uri.clone(),
front_line(r),
);
continue;
}
aliases.push(alias.to_string());
let rf = ImportRef {
uri: u.to_string(),
alias: alias.to_string(),
mode: b.get("mode").cloned(),
sha256: b.get("sha256").cloned(),
version: b.get("version").cloned(),
select_value: b.get("select").cloned(),
required: true,
with: b.get("with").and_then(Value::as_object).cloned().unwrap_or_default(),
inherit: true,
line: front_line(r),
};
if let Some(nodes) = self.import_source(doc, trail, instance, &rf) {
inherited.extend(nodes);
}
}
}
let mut local = Vec::new();
for node in &r.document.body {
if node.is_directive() && matches!(node.kind.as_str(), "replace" | "extend" | "remove") {
self.patch(doc, instance, &mut inherited, node, &scope);
continue;
}
if node.is_directive()
&& node.kind == "allowance"
&& let Some(id) = node.attrs.get("id").and_then(Value::as_str)
&& let Some(path) = find_kind(&inherited, "allowance", id)
{
let stamped = stamp(node, instance, &scope);
let (index, parent_path) = path.split_last().map(|(i, p)| (*i, p.to_vec())).unwrap_or((0, Vec::new()));
let before = siblings_at(&mut inherited, &parent_path).map(|sib| sib[index].attrs.clone());
if let Some(before) = before {
self.widened(&before, &stamped.attrs, id, where_(doc, instance), node.range.map_or(0, |r| r.start));
if let Some(sib) = siblings_at(&mut inherited, &parent_path) {
sib[index] = stamped;
}
continue;
}
}
local.push(stamp(node, instance, &scope));
}
let included = self.includes(doc, trail, instance, local, &mut aliases);
inherited.extend(included);
Some(inherited)
}
fn includes(&mut self, doc: &Rc<Loaded>, trail: &[String], instance: &str, nodes: Vec<Node>, aliases: &mut Vec<String>) -> Vec<Node> {
let mut out = Vec::new();
for mut n in nodes {
if n.is_directive() && n.kind == "include" {
let src = n.attrs.get("src").and_then(Value::as_str).map(str::to_string);
let alias = n.attrs.get("as").and_then(Value::as_str).unwrap_or("").to_string();
let Some(src) = src.filter(|_| !alias.is_empty()) else {
out.push(n);
continue;
};
let line = n.range.map_or(0, |r| r.start);
if aliases.contains(&alias) {
self.diag(
"duplicate-id",
Severity::Error,
format!("the alias \"{alias}\" is used twice in {}", doc.uri),
where_(doc, instance),
line,
);
out.push(n);
continue;
}
aliases.push(alias.clone());
let rf = ImportRef {
uri: src,
alias,
mode: n.attrs.get("mode").cloned(),
sha256: n.attrs.get("sha256").cloned(),
version: n.attrs.get("version").cloned(),
select_value: None,
required: n.attrs.get("required") == Some(&Value::Bool(true)),
with: Object::new(),
inherit: false,
line,
};
match self.import_source(doc, trail, instance, &rf) {
Some(nodes) => out.extend(nodes),
None => out.push(n),
}
continue;
}
if n.is_directive()
&& let Some(children) = n.children.take()
{
n.children = Some(self.includes(doc, trail, instance, children, aliases));
}
out.push(n);
}
out
}
fn import_source(&mut self, doc: &Rc<Loaded>, trail: &[String], instance: &str, rf: &ImportRef) -> Option<Vec<Node>> {
let uri = where_(doc, instance);
let line = rf.line;
let (what, operation) = if rf.inherit {
(format!("the base \"{}\"", rf.alias), "inherit")
} else {
(format!("the include \"{}\"", rf.alias), "include")
};
let resolved = resolve_uri(&named(&doc.read, &rf.uri), &doc.uri);
let (path, fragment) = split_fragment(&resolved);
let path = path.to_string();
let missing = |c: &mut Self, message: String| {
if rf.required {
c.diag("reference-missing", Severity::Error, message, uri.clone(), line);
} else {
c.diag("reference-optional", Severity::Warning, message, uri.clone(), line);
c.partial = true;
}
};
let Some(target) = self.source(&path) else {
missing(self, format!("{what}: {} could not be read", rf.uri));
return None;
};
let mode = if is_str(rf.mode.as_ref(), "pinned") { "pinned" } else { "live" };
if mode == "pinned" && !is_str(rf.sha256.as_ref(), &target.sha256) {
let pin = rf.sha256.as_ref().and_then(Value::as_str).unwrap_or("no digest");
self.diag(
"pin-mismatch",
Severity::Error,
format!("{what} is pinned to {pin}, and {} is {}", rf.uri, target.sha256),
uri,
line,
);
return None;
}
if let Some(Value::String(v)) = &rf.version
&& !target.version.is_empty()
&& &target.version != v
{
self.diag(
"pin-mismatch",
Severity::Error,
format!("{what} asks for version {v}, and {} is {}", rf.uri, target.version),
uri,
line,
);
return None;
}
let child = format!("{instance}/{}", rf.alias);
let Some(selector) = selector_of(rf.select_value.as_ref(), fragment) else {
self.diag(
"invalid-attributes",
Severity::Error,
format!("{what}: a selector is one of id, heading or lines for an instruction document"),
uri,
line,
);
return None;
};
let mut next_trail = trail.to_vec();
next_trail.push(doc.uri.clone());
let body = if let Some(Selector::Lines(a, b)) = selector {
let lines = &target.read.lines;
if !(a >= 1.0 && b >= a && b <= lines.len() as f64) {
missing(self, format!("{what}: lines {}–{} are outside {}", js_number(a), js_number(b), rf.uri));
return None;
}
let text = lines[a as usize - 1..b as usize].join("\n") + "\n";
let fragment_read = read(&text, &ReadOptions { fragment: true, uri: target.uri.clone() });
let fragment = Rc::new(Loaded {
uri: target.uri.clone(),
sha256: target.sha256.clone(),
version: target.version.clone(),
read: fragment_read,
});
self.compose(&fragment, &next_trail, &child, &rf.with)?
} else {
let composed = self.compose(&target, &next_trail, &child, &rf.with);
match (&selector, composed) {
(Some(s), Some(body)) => match select_from(body, &child, s) {
Some(body) => body,
None => {
missing(self, format!("{what}: {} has nothing that {}", rf.uri, s.describe()));
return None;
}
},
(_, Some(body)) => body,
(_, None) => return None,
}
};
self.dependencies.push(Dependency {
uri: rf.uri.clone(),
resolved_uri: path,
sha256: target.sha256.clone(),
mode: mode.into(),
version: target.version.clone(),
selector: selector.clone(),
instance: child.clone(),
});
self.provenance.push(Provenance {
instance: child,
uri: target.uri.clone(),
selector,
operation: operation.into(),
..Provenance::default()
});
Some(body)
}
fn patch(&mut self, doc: &Rc<Loaded>, instance: &str, inherited: &mut Vec<Node>, node: &Node, scope: &Object) {
let uri = where_(doc, instance);
let line = node.range.map_or(0, |r| r.start);
let raw = node.attrs.get("target").and_then(Value::as_str).unwrap_or("");
let target = raw.strip_prefix('#').unwrap_or(raw);
let parts: Vec<&str> = target.split('/').collect();
if !raw.starts_with('#') || parts.len() < 2 || parts.contains(&"") {
self.diag(
"patch-target",
Severity::Error,
format!(":::{}: its target is an inherited explicit id, #alias/id (it is \"{raw}\")", node.kind),
uri,
line,
);
return;
}
let wanted = format!("{instance}/{}", parts[..parts.len() - 1].join("/"));
let Some(path) = find_id(inherited, &wanted, parts[parts.len() - 1]) else {
self.diag("patch-target", Severity::Error, format!(":::{}: nothing inherited has the id #{target}", node.kind), uri, line);
return;
};
let (index, parent_path) = path.split_last().map(|(i, p)| (*i, p.to_vec())).unwrap_or((0, Vec::new()));
let Some(siblings) = siblings_at(inherited, &parent_path) else { return };
let original = siblings[index].clone();
match node.kind.as_str() {
"remove" => {
siblings.remove(index);
}
"replace" if original.value.is_some() => {
let format = original.value.as_ref().map(|v| v.format.clone()).unwrap_or_default();
if node.value.as_ref().is_none_or(|v| v.format != format) {
self.diag(
"patch-body",
Severity::Error,
format!(
":::replace{{target=\"#{target}\"}}: the target is a {} body, so its replacement is one too (format={format})",
format.to_uppercase()
),
uri,
line,
);
return;
}
let dest = &mut siblings[index];
dest.value = node.value.clone();
dest.children = None;
}
"replace" => {
if node.value.is_some() {
self.diag(
"patch-body",
Severity::Error,
format!(":::replace{{target=\"#{target}\"}}: the target is Markdown, so its replacement is Markdown"),
uri,
line,
);
return;
}
let children = stamp_all(node.children(), instance, scope);
let mut kept = Vec::new();
let mut properties: Vec<Node> = Vec::new();
for child in children {
if child.is_directive() && child.kind == "properties" && child.attrs.get("patch") == Some(&Value::Bool(true)) {
properties.push(child);
kept.push(None);
continue;
}
kept.push(Some(child));
}
let dest = &mut siblings[index];
let mut problem = None;
for p in &properties {
if let Err(message) = apply_properties(dest, p, target) {
problem = Some(message);
break;
}
}
if let Some(message) = problem {
self.diag("patch-body", Severity::Error, message, uri, line);
return;
}
dest.children = Some(kept.into_iter().flatten().collect());
}
_ => {
if original.value.is_some() {
self.diag(
"patch-body",
Severity::Error,
format!(":::extend{{target=\"#{target}\"}}: a structured target is changed with :::replace"),
uri,
line,
);
return;
}
let children = stamp_all(node.children(), instance, scope);
let dest = &mut siblings[index];
let existing = dest.children.take().unwrap_or_default();
dest.children = Some(if is_str(node.attrs.get("position"), "prepend") {
children.into_iter().chain(existing).collect()
} else {
existing.into_iter().chain(children).collect()
});
}
}
if node.kind == "replace" && original.kind == "allowance" {
let after = siblings_at(inherited, &parent_path).map(|sib| sib[index].attrs.clone());
if let Some(after) = after {
self.widened(&original.attrs, &after, target, where_(doc, instance), line);
}
}
let reason = node.attrs.get("reason").and_then(Value::as_str).unwrap_or("").to_string();
self.provenance.push(Provenance {
instance: wanted,
uri: doc.uri.clone(),
range: node.range,
selector: None,
operation: node.kind.clone(),
target: target.to_string(),
reason,
modified_by: doc.uri.clone(),
original: Some(original),
});
}
fn source(&mut self, uri: &str) -> Option<Rc<Loaded>> {
if let Some(known) = self.loaded.get(uri) {
return Some(known.clone());
}
let l = (self.lookup)(uri)?;
let mut found = l.read.diagnostics.clone();
found.extend(inline_diagnostics(&l.read));
for mut d in found {
d.uri = l.uri.clone();
self.diagnostics.push(d);
}
self.loaded.insert(uri.to_string(), l.clone());
Some(l)
}
fn parameters(&mut self, doc: &Loaded, instance: &str, values: &Object) -> Object {
let mut out = Object::new();
let uri = where_(doc, instance);
for p in &doc.read.parameters {
let line = if p.line == 0 { front_line(&doc.read) } else { p.line };
if let Some(given) = values.get(&p.name) {
if !value_fits(p, given) {
let allowed = p.values.as_ref().map_or(String::new(), |v| format!(" ({})", v.join(", ")));
self.diag(
"parameter-invalid",
Severity::Error,
format!("the value given for ${{{}}} is not a valid {}{allowed}", p.name, p.param_type),
uri.clone(),
line,
);
continue;
}
out.insert(p.name.clone(), given.clone());
} else if let Some(d) = &p.default {
out.insert(p.name.clone(), d.clone());
} else if p.required {
self.diag("parameter-missing", Severity::Error, format!("${{{}}} is required and has no value", p.name), uri.clone(), line);
} else if uses_parameter(&doc.read, &p.name) {
self.diag(
"parameter-optional",
Severity::Warning,
format!("${{{}}} has no value, so it stays as written", p.name),
uri.clone(),
line,
);
}
}
out
}
fn extensions(&mut self, doc: &Loaded, instance: &str) {
let meta = &doc.read.document.metadata;
for (key, value) in entries(meta.front.get("extensions"), &meta.front_order, "extensions") {
let required = value.get("required") == Some(&Value::Bool(true));
let id = match value.get("id") {
Some(v) if !v.is_null() => js_value(Some(v)),
_ => key.clone(),
};
if required {
self.diag(
"extension-unavailable",
Severity::Error,
format!("the extension {id} (\"{key}\") is required, and this resolver binds no extension manifests"),
where_(doc, instance),
front_line(&doc.read),
);
} else {
self.partial = true;
}
}
}
}
fn apply_properties(dest: &mut Node, p: &Node, target: &str) -> Result<(), String> {
let Some(value) = &p.value else {
return Err(format!("the properties patch for #{target} is a mapping of attributes"));
};
let Some(Value::Object(data)) = &value.data else {
return Err(format!("the properties patch for #{target} is a mapping of attributes"));
};
for k in value.order.keys("", data) {
if k == "id" {
return Err(format!("a properties patch cannot change #{target}'s id"));
}
dest.attrs.insert(k.clone(), data[&k].clone());
}
Ok(())
}
fn entries(v: Option<&Value>, order: &KeyOrder, path: &str) -> Vec<(String, Value)> {
match v {
Some(Value::Object(m)) => order.keys(path, m).into_iter().map(|k| (k.clone(), m[&k].clone())).collect(),
Some(Value::Array(list)) => list.iter().enumerate().map(|(i, e)| (i.to_string(), e.clone())).collect(),
_ => Vec::new(),
}
}
fn stamp_all(nodes: &[Node], instance: &str, scope: &Object) -> Vec<Node> {
nodes.iter().map(|n| stamp(n, instance, scope)).collect()
}
fn stamp(node: &Node, instance: &str, scope: &Object) -> Node {
let mut cp = Node { children: None, ..node.clone() };
cp.instance = instance.to_string();
if node.is_markdown() {
if node.prose {
cp.source = substitute(&node.source, scope);
}
return cp;
}
if is_rule(&node.kind) {
for k in ["if", "because"] {
if let Some(Value::String(s)) = cp.attrs.get(k).cloned() {
cp.attrs.insert(k.into(), Value::String(interpolate_values(&s, scope)));
}
}
}
if node.kind == "allowance" {
for k in ["max", "budget", "approve-above", "times", "from", "until", "currency", "per"] {
if let Some(Value::String(s)) = cp.attrs.get(k).cloned() {
cp.attrs.insert(k.into(), Value::String(interpolate_values(&s, scope)));
}
}
}
if let Some(children) = &node.children {
cp.children = Some(stamp_all(children, instance, scope));
}
cp
}
fn substitute(source: &str, values: &Object) -> String {
let mut out = String::new();
let mut at = 0;
for t in inline_tokens(source) {
if t.token_type != TokenType::Param || t.start < at {
continue;
}
let Some(text) = values.get(&t.name).and_then(value_text) else { continue };
out.push_str(&source[at..t.start]);
out.push_str(&text);
at = t.end;
}
out.push_str(&source[at..]);
out
}
fn uses_parameter(r: &Reading, name: &str) -> bool {
for n in &r.prose_order {
if inline_tokens(&n.source).iter().any(|t| t.token_type == TokenType::Param && t.name == name) {
return true;
}
}
let reference = format!("${{{name}}}");
fn rule_uses(nodes: &[Node], reference: &str) -> bool {
nodes.iter().filter(|n| n.is_directive()).any(|n| {
is_rule(&n.kind)
&& ["if", "because"].iter().any(|k| n.attrs.get(*k).and_then(Value::as_str).is_some_and(|s| s.contains(reference)))
|| rule_uses(n.children(), reference)
})
}
rule_uses(&r.document.body, &reference)
}
fn selector_of(select_value: Option<&Value>, fragment: Option<&str>) -> Option<Option<Selector>> {
if let Some(Value::Object(s)) = select_value {
if let Some(Value::String(id)) = s.get("id")
&& s.len() == 1
{
return Some(Some(Selector::Id(id.clone())));
}
if let Some(Value::String(heading)) = s.get("heading")
&& s.keys().all(|k| k == "heading" || k == "occurrence")
{
let occurrence = s.get("occurrence").and_then(Value::as_f64);
return Some(Some(Selector::Heading { heading: heading.clone(), occurrence }));
}
if let Some(Value::Array(lines)) = s.get("lines")
&& lines.len() == 2
&& s.len() == 1
&& let (Some(a), Some(b)) = (lines[0].as_f64(), lines[1].as_f64())
&& a.fract() == 0.0
&& b.fract() == 0.0
{
return Some(Some(Selector::Lines(a, b)));
}
return None;
}
if select_value.is_some() {
return None;
}
let Some(fragment) = fragment.filter(|f| !f.is_empty()) else {
return Some(None);
};
let f = decode_uri_component(fragment);
if let Some(id) = f.strip_prefix("id=") {
return Some(Some(Selector::Id(id.to_string())));
}
if let Some(heading) = f.strip_prefix("heading=") {
return Some(Some(Selector::Heading { heading: heading.to_string(), occurrence: None }));
}
Some(Some(Selector::Id(f)))
}
struct Rx {
escape_run: Pattern,
atx: Pattern,
code_toggle: Pattern,
heading_brace: Pattern,
heading_id: Pattern,
code_span: Pattern,
link_text: Pattern,
emphasis: Pattern,
space_run: Pattern,
edge_dashes: Pattern,
scheme: Pattern,
}
static RX: LazyLock<Rx> = LazyLock::new(|| Rx {
escape_run: Pattern::must(r"(?:%[0-9A-Fa-f]{2})+"),
atx: Pattern::must(&format!(r"^ {{0,3}}(#{{1,6}})[ \t]+({JS_DOT}*?)(?:[ \t]+#+)?[ \t]*$")),
code_toggle: Pattern::must(r"^ {0,3}(`{3,}|~{3,})"),
heading_brace: Pattern::must(r"[ \t]\{([^{}]*)\}$"),
heading_id: Pattern::must(&format!(r"(?:^|[{JS_SPACES}])#([A-Za-z0-9][A-Za-z0-9._-]*)")),
code_span: Pattern::must(r"`([^`]*)`"),
link_text: Pattern::must(r"!?\[([^\]]*)\]\([^)]*\)"),
emphasis: Pattern::must(r"[*_~]+"),
space_run: Pattern::must(&format!(r"[{JS_SPACES}]+")),
edge_dashes: Pattern::must(r"^-+|-+$"),
scheme: Pattern::must(r"^[A-Za-z][A-Za-z0-9+.-]*:"),
});
fn decode_uri_component(s: &str) -> String {
RX.escape_run.replace_all(s, |m| {
let run = m.get(s, 0).unwrap_or("");
let bytes: Vec<u8> = run
.as_bytes()
.chunks(3)
.filter_map(|c| std::str::from_utf8(&c[1..]).ok().and_then(|h| u8::from_str_radix(h, 16).ok()))
.collect();
String::from_utf8(bytes).unwrap_or_else(|_| run.to_string())
})
}
fn select_from(body: Vec<Node>, instance: &str, s: &Selector) -> Option<Vec<Node>> {
match s {
Selector::Id(id) => {
if let Some(found) = select_id(&body, instance, id) {
return Some(found);
}
select_heading(&body, &|h: &Heading| h.id == *id || h.anchor == *id, 1.0)
}
Selector::Heading { heading, occurrence } => select_heading(&body, &|h: &Heading| h.text == *heading, occurrence.unwrap_or(1.0)),
Selector::Lines(..) => None,
}
}
fn select_id(nodes: &[Node], instance: &str, id: &str) -> Option<Vec<Node>> {
for n in nodes {
if !n.is_directive() {
continue;
}
let within = if n.instance.is_empty() { instance } else { &n.instance };
if is_str(n.attrs.get("id"), id) && within == instance {
return Some(vec![n.clone()]);
}
if let Some(found) = select_id(n.children(), instance, id) {
if n.kind == "policy" {
let mut cp = n.clone();
cp.children = Some(found);
return Some(vec![cp]);
}
return Some(found);
}
}
None
}
struct Heading {
level: usize,
text: String,
id: String,
anchor: String,
node: usize,
line: usize,
}
fn select_heading(body: &[Node], matches: &dyn Fn(&Heading) -> bool, occurrence: f64) -> Option<Vec<Node>> {
let mut headings: Vec<Heading> = Vec::new();
let mut anchors: HashMap<String, usize> = HashMap::new();
for (i, n) in body.iter().enumerate() {
if !n.is_markdown() {
continue;
}
let mut code = false;
for (li, l) in n.source.split('\n').enumerate() {
if RX.code_toggle.is_match(l) {
code = !code;
}
if code {
continue;
}
let Some(m) = RX.atx.captures(l) else { continue };
let content = m.get(l, 2).unwrap_or("");
let mut visible = content.to_string();
let mut id = String::new();
if let Some(attrs) = RX.heading_brace.captures(content) {
visible = js_trim(&content[..attrs.whole().0]).to_string();
let inner = attrs.get(content, 1).unwrap_or("");
if let Some(h) = RX.heading_id.captures(inner) {
id = h.get(inner, 1).unwrap_or("").to_string();
}
}
let text = plain(&visible);
let mut anchor = slug(&text);
let seen = anchors.get(&anchor).copied().unwrap_or(0);
anchors.insert(anchor.clone(), seen + 1);
if seen > 0 {
anchor = format!("{anchor}-{}", seen + 1);
}
headings.push(Heading { level: m.get(l, 1).map_or(0, str::len), text, id, anchor, node: i, line: li });
}
}
let matched: Vec<&Heading> = headings.iter().filter(|h| matches(h)).collect();
let index = occurrence - 1.0;
if index.fract() != 0.0 || index < 0.0 || index >= matched.len() as f64 {
return None;
}
let hit = matched[index as usize];
let next = headings.iter().find(|h| (h.node > hit.node || h.node == hit.node && h.line > hit.line) && h.level <= hit.level);
let mut out = Vec::new();
for (i, n) in body.iter().enumerate().skip(hit.node) {
if next.is_some_and(|next| i > next.node) {
break;
}
if !n.is_markdown() {
if next.is_none_or(|next| i < next.node) {
out.push(n.clone());
}
continue;
}
let lines: Vec<&str> = n.source.split('\n').collect();
let from = if i == hit.node { hit.line } else { 0 };
let to = match next {
Some(next) if i == next.node => next.line,
_ => lines.len(),
};
let mut part = lines[from.min(to)..to].join("\n");
if !blank(&part) {
if !part.ends_with('\n') {
part.push('\n');
}
let mut cp = n.clone();
cp.source = part;
out.push(cp);
}
}
Some(out)
}
fn plain(s: &str) -> String {
let s = RX.code_span.replace_all(s, |m| m.get(s, 1).unwrap_or("").to_string());
let s2 = RX.link_text.replace_all(&s, |m| m.get(&s, 1).unwrap_or("").to_string());
js_trim(&RX.emphasis.replace_all(&s2, |_| String::new())).to_string()
}
pub fn slug(text: &str) -> String {
let lower = text.to_lowercase();
let dashed = RX.space_run.replace_all(&lower, |_| "-".to_string());
let kept: String = dashed.chars().filter(|c| c.is_alphabetic() || c.is_numeric() || *c == '_' || *c == '-').collect();
let s = RX.edge_dashes.replace_all(&kept, |_| String::new());
if s.is_empty() { "section".into() } else { s }
}
fn find_kind(nodes: &[Node], kind: &str, id: &str) -> Option<Vec<usize>> {
for (i, n) in nodes.iter().enumerate() {
if !n.is_directive() {
continue;
}
if n.kind == kind && is_str(n.attrs.get("id"), id) {
return Some(vec![i]);
}
if let Some(mut path) = find_kind(n.children(), kind, id) {
path.insert(0, i);
return Some(path);
}
}
None
}
fn find_id(nodes: &[Node], instance: &str, id: &str) -> Option<Vec<usize>> {
for (i, n) in nodes.iter().enumerate() {
if !n.is_directive() {
continue;
}
if n.instance == instance && is_str(n.attrs.get("id"), id) {
return Some(vec![i]);
}
if let Some(mut path) = find_id(n.children(), instance, id) {
path.insert(0, i);
return Some(path);
}
}
None
}
fn siblings_at<'n>(nodes: &'n mut Vec<Node>, parent: &[usize]) -> Option<&'n mut Vec<Node>> {
let mut cur = nodes;
for &i in parent {
cur = cur.get_mut(i)?.children.as_mut()?;
}
Some(cur)
}
fn named(r: &Reading, target: &str) -> String {
if RX.scheme.is_match(target) || target.starts_with('.') || target.starts_with('/') || target.contains(['/', '#']) {
return target.to_string();
}
match r.document.metadata.front.get("references").and_then(|refs| refs.get(target)) {
Some(Value::String(s)) => s.clone(),
Some(Value::Object(rec)) => match rec.get("uri") {
Some(Value::String(u)) => u.clone(),
_ => target.to_string(),
},
_ => target.to_string(),
}
}
pub fn resolve_uri(reference: &str, base: &str) -> String {
if RX.scheme.is_match(reference) {
return reference.to_string();
}
if RX.scheme.is_match(base) {
return rfc3986(reference, base).unwrap_or_else(|| reference.to_string());
}
let (path, fragment) = split_fragment(reference);
let joined = if path.is_empty() {
without_fragment(base).to_string()
} else if path.starts_with('/') {
path.to_string()
} else {
let b = without_fragment(base);
format!("{}{path}", &b[..b.rfind('/').map_or(0, |i| i + 1)])
};
let mut segments: Vec<&str> = Vec::new();
for s in joined.split('/') {
if s == "." || s.is_empty() && !segments.is_empty() {
continue;
}
if s == ".." {
if segments.last().is_some_and(|l| !l.is_empty()) {
segments.pop();
}
continue;
}
segments.push(s);
}
let mut out = segments.join("/");
if let Some(f) = fragment {
out.push('#');
out.push_str(f);
}
out
}
fn rfc3986(reference: &str, base: &str) -> Option<String> {
let bad_escape = |s: &str| {
let b = s.as_bytes();
(0..b.len()).any(|i| b[i] == b'%' && !(i + 2 < b.len() && b[i + 1].is_ascii_hexdigit() && b[i + 2].is_ascii_hexdigit()))
};
if bad_escape(reference) || bad_escape(base) {
return None;
}
let colon = base.find(':')?;
let scheme = &base[..colon];
let rest = without_fragment(&base[colon + 1..]);
let (rest, base_query) = match rest.split_once('?') {
Some((r, q)) => (r, Some(q)),
None => (rest, None),
};
let (authority, base_path) = match rest.strip_prefix("//") {
Some(r) => match r.find('/') {
Some(i) => (Some(&r[..i]), &r[i..]),
None => (Some(r), ""),
},
None => (None, rest),
};
if authority.is_none() && !base_path.starts_with('/') {
return None; }
let (rpath, rfragment) = split_fragment(reference);
let (rpath, rquery) = match rpath.split_once('?') {
Some((p, q)) => (p, Some(q)),
None => (rpath, None),
};
let (authority, path, query) = if let Some(r) = rpath.strip_prefix("//") {
let (a, p) = match r.find('/') {
Some(i) => (&r[..i], &r[i..]),
None => (r, ""),
};
(Some(a.to_string()), remove_dot_segments(p), rquery)
} else if rpath.is_empty() {
(authority.map(str::to_string), base_path.to_string(), rquery.or(base_query))
} else if rpath.starts_with('/') {
(authority.map(str::to_string), remove_dot_segments(rpath), rquery)
} else {
let merged = if authority.is_some() && base_path.is_empty() {
format!("/{rpath}")
} else {
format!("{}{rpath}", &base_path[..base_path.rfind('/').map_or(0, |i| i + 1)])
};
(authority.map(str::to_string), remove_dot_segments(&merged), rquery)
};
let mut out = format!("{scheme}:");
if let Some(a) = authority {
out.push_str("//");
out.push_str(&a);
}
out.push_str(&path);
if let Some(q) = query {
out.push('?');
out.push_str(q);
}
if let Some(f) = rfragment {
out.push('#');
out.push_str(f);
}
Some(out)
}
fn remove_dot_segments(path: &str) -> String {
let mut out: Vec<&str> = Vec::new();
let segments: Vec<&str> = path.split('/').collect();
let n = segments.len();
for (i, s) in segments.iter().enumerate() {
match *s {
"." => {
if i == n - 1 {
out.push("");
}
}
".." => {
if out.len() > 1 {
out.pop();
}
if i == n - 1 {
out.push("");
}
}
s => out.push(s),
}
}
let joined = out.join("/");
if path.starts_with('/') && !joined.starts_with('/') { format!("/{joined}") } else { joined }
}
fn split_fragment(uri: &str) -> (&str, Option<&str>) {
match uri.split_once('#') {
Some((p, f)) => (p, Some(f)),
None => (uri, None),
}
}
fn without_fragment(uri: &str) -> &str {
split_fragment(uri).0
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn uris() {
for (r, b, want) in [
("./base.md", "docs/child.md", "docs/base.md"),
("../shared/x.md#id=a", "docs/child.md", "shared/x.md#id=a"),
("./base", "instruction://acme/morning", "instruction://acme/base"),
("https://example.org/a.md", "instruction://acme/morning", "https://example.org/a.md"),
("#id=a", "docs/child.md", "docs/child.md#id=a"),
("/abs/x.md", "docs/child.md", "/abs/x.md"),
("../b.md", "instruction://local/x/a.md", "instruction://local/b.md"),
] {
assert_eq!(resolve_uri(r, b), want, "{r} against {b}");
}
}
#[test]
fn slugs() {
for (text, want) in
[("Calendar privacy", "calendar-privacy"), ("Ünïcode & more!", "ünïcode--more"), ("***", "section"), (" -x- ", "x")]
{
assert_eq!(slug(text), want);
}
}
}