use std::collections::{BTreeMap, HashMap, HashSet};
use std::ops::Range;
use std::path::Path;
use std::sync::OnceLock;
use indexmap::IndexMap;
use regex::Regex;
use sha2::{Digest, Sha256};
use memstead_schema::TypeDefinition;
use super::id::{WikiLinkError, file_path_to_id, wiki_link_to_id, wiki_link_to_id_lenient};
use super::{Entity, EntityId, HeadingSpan, MetadataValue, ParseResult, Relationship};
pub fn parse_markdown(
content: &str,
relative_path: &str,
schema: &TypeDefinition,
mem: &str,
) -> Result<ParseResult, ParseError> {
let id = file_path_to_id(relative_path, mem);
let content_hash = compute_hash(content);
let (metadata, body) = split_frontmatter(content)?;
let masked_body = mask_code_blocks(&body);
let title = extract_title(&body, &masked_body).unwrap_or_else(|| id.name().to_string());
let (sections_map, duplicate_headings, raw_section_headings) =
split_sections(&body, &masked_body);
let rel_heading_key = "relationships";
let entity_id_for_rel_warnings = file_path_to_id(relative_path, mem);
let (relationships, rel_parse_warnings) = parse_relationships_with_warnings(
sections_map
.get(rel_heading_key)
.map(|(_, content)| content.as_str())
.unwrap_or(""),
mem,
Some(&entity_id_for_rel_warnings),
);
let catch_all_content = build_catch_all(§ions_map, schema);
let mut result_sections = IndexMap::new();
for s in &schema.sections {
if s.catch_all {
if sections_map.contains_key(s.key.as_str()) || !catch_all_content.trim().is_empty() {
result_sections.insert(s.key.clone(), catch_all_content.clone());
}
} else if let Some((_, content)) = sections_map.get(s.key.as_str()) {
result_sections.insert(s.key.clone(), content.clone());
}
}
let mut parsed_metadata = parse_metadata(&metadata);
let type_name = parsed_metadata
.get("type")
.and_then(|v| v.as_str())
.unwrap_or(schema.name.as_str())
.to_string();
parsed_metadata.insert("type".to_string(), MetadataValue::String(type_name.clone()));
let inline_link_text: String = schema
.text_fields
.iter()
.filter_map(|f| result_sections.get(f.as_str()))
.cloned()
.collect::<Vec<_>>()
.join("\n");
let inline_links = extract_inline_links_lenient(&inline_link_text, mem);
let explicit_targets: HashSet<_> = relationships.iter().map(|r| &r.target).collect();
let inline_links: Vec<EntityId> = inline_links
.into_iter()
.filter(|link| !explicit_targets.contains(link))
.collect();
let heading_spans = extract_heading_spans(&result_sections);
let declared_keys: HashSet<&str> = schema
.sections
.iter()
.filter(|s| !s.catch_all)
.map(|s| s.key.as_str())
.collect();
let entity_id_for_warnings = file_path_to_id(relative_path, mem);
let mut parse_warnings: Vec<crate::ops::WarningHint> = duplicate_headings
.into_iter()
.filter(|d| declared_keys.contains(d.key.as_str()))
.map(|d| crate::ops::WarningHint::DuplicateSectionHeading {
entity_id: entity_id_for_warnings.clone(),
section_key: d.key,
heading: d.heading,
occurrences: d.occurrences,
})
.collect();
parse_warnings.extend(rel_parse_warnings);
let entity = Entity {
id,
title,
entity_type: type_name,
mem: mem.to_string(),
file_path: relative_path.to_string(),
metadata: parsed_metadata,
sections: result_sections,
relationships,
content_hash,
stub: false,
stub_kind: None,
heading_spans,
raw_section_headings,
};
Ok(ParseResult {
entity,
inline_links,
parse_warnings,
})
}
pub fn parse_file(
path: &Path,
mem_dir: &Path,
schema: &TypeDefinition,
mem: &str,
) -> Result<ParseResult, ParseError> {
let content = std::fs::read_to_string(path)?;
let relative_path = path.strip_prefix(mem_dir).unwrap_or(path).to_string_lossy();
parse_markdown(&content, &relative_path, schema, mem)
}
#[derive(Debug, PartialEq, Eq)]
pub enum Frontmatter<'a> {
Present { meta: &'a str, body: &'a str },
NoOpeningDelimiter,
Unclosed,
}
pub fn split_frontmatter_core(content: &str) -> (&str, Frontmatter<'_>) {
let content = content.strip_prefix('\u{feff}').unwrap_or(content);
let after_open = if content.starts_with("---\r\n") {
5
} else if content.starts_with("---\n") {
4
} else {
return (content, Frontmatter::NoOpeningDelimiter);
};
let rest = &content[after_open..];
let Some(close_pos) = rest.find("\n---") else {
return (content, Frontmatter::Unclosed);
};
let meta = &rest[..close_pos];
let body_rest = &rest[close_pos + "\n---".len()..];
let body = body_rest
.strip_prefix("\r\n")
.or_else(|| body_rest.strip_prefix('\n'))
.unwrap_or(body_rest);
(content, Frontmatter::Present { meta, body })
}
pub fn frontmatter_parts(content: &str) -> Option<(&str, &str)> {
match split_frontmatter_core(content) {
(_, Frontmatter::Present { meta, body }) => Some((meta, body)),
_ => None,
}
}
pub fn peek_type_from_frontmatter(content: &str) -> Option<String> {
let (_, split) = split_frontmatter_core(content);
let Frontmatter::Present {
meta: frontmatter, ..
} = split
else {
return None;
};
for line in frontmatter.lines() {
let trimmed = line.trim();
if trimmed.is_empty() || trimmed.starts_with('#') {
continue;
}
let Some(colon_idx) = trimmed.find(':') else {
continue;
};
let key = trimmed[..colon_idx].trim();
if key != "type" {
continue;
}
let mut value = trimmed[colon_idx + 1..].trim();
if let Some(hash_idx) = value.find('#') {
value = value[..hash_idx].trim();
}
let value = value.trim_matches(|c| c == '"' || c == '\'');
if value.is_empty() {
return None;
}
return Some(value.to_string());
}
None
}
pub fn peek_title_and_type(content: &str) -> (Option<String>, Option<String>) {
let entity_type = peek_type_from_frontmatter(content);
let body = body_after_frontmatter(content);
let title = extract_title(body, &mask_code_blocks(body));
(title, entity_type)
}
pub fn body_after_frontmatter(content: &str) -> &str {
match split_frontmatter_core(content) {
(_, Frontmatter::Present { body, .. }) => body,
(stripped, _) => stripped,
}
}
pub(crate) fn split_frontmatter(content: &str) -> Result<(String, String), ParseError> {
match split_frontmatter_core(content) {
(_, Frontmatter::Present { meta, body }) => Ok((meta.to_string(), body.to_string())),
(stripped, _) => Ok((String::new(), stripped.to_string())),
}
}
fn parse_metadata(text: &str) -> IndexMap<String, MetadataValue> {
let mut meta = IndexMap::new();
if text.is_empty() {
return meta;
}
for line in text.lines() {
let trimmed = line.trim();
if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with("---") {
continue;
}
let Some(colon_idx) = trimmed.find(':') else {
continue;
};
let key = trimmed[..colon_idx].trim().to_string();
let raw_value = trimmed[colon_idx + 1..].trim();
let value = strip_inline_comment(raw_value).trim().to_string();
if value.is_empty() {
meta.insert(key, MetadataValue::String(String::new()));
continue;
}
if value == "true" {
meta.insert(key, MetadataValue::Bool(true));
} else if value == "false" {
meta.insert(key, MetadataValue::Bool(false));
} else if is_float_literal(&value) {
if let Ok(f) = value.parse::<f64>() {
meta.insert(key, MetadataValue::Float(f));
} else {
meta.insert(key, MetadataValue::String(strip_quotes(&value)));
}
} else if is_integer_literal(&value) {
if let Ok(n) = value.parse::<i64>() {
meta.insert(key, MetadataValue::Integer(n));
} else {
meta.insert(key, MetadataValue::String(strip_quotes(&value)));
}
} else {
meta.insert(key, MetadataValue::String(strip_quotes(&value)));
}
}
meta
}
fn is_float_literal(s: &str) -> bool {
let s = s.strip_prefix('-').unwrap_or(s);
if let Some((before, after)) = s.split_once('.') {
!before.is_empty()
&& before.chars().all(|c| c.is_ascii_digit())
&& !after.is_empty()
&& after.chars().all(|c| c.is_ascii_digit())
} else {
false
}
}
fn is_integer_literal(s: &str) -> bool {
let s = s.strip_prefix('-').unwrap_or(s);
!s.is_empty() && s.chars().all(|c| c.is_ascii_digit())
}
pub(crate) fn would_coerce_from_string(s: &str) -> bool {
s == "true" || s == "false" || is_integer_literal(s) || is_float_literal(s)
}
fn strip_inline_comment(s: &str) -> &str {
if let Some(idx) = s.find(" #") {
s[..idx].trim_end()
} else {
s
}
}
fn strip_quotes(s: &str) -> String {
if s.len() >= 2
&& ((s.starts_with('"') && s.ends_with('"')) || (s.starts_with('\'') && s.ends_with('\'')))
{
s[1..s.len() - 1].to_string()
} else {
s.to_string()
}
}
pub use crate::markdown::{mask_code_blocks, mask_code_blocks_and_spans};
pub fn has_merge_conflict_markers(text: &str) -> bool {
let body = body_after_frontmatter(text);
let frontmatter = &text[..text.len() - body.len()];
let view = format!("{frontmatter}{}", mask_code_blocks(body));
let mut seen_start = false;
let mut seen_separator = false;
for line in view.lines() {
if line.starts_with("<<<<<<< ") {
seen_start = true;
seen_separator = false;
} else if seen_start && line.trim_end() == "=======" {
seen_separator = true;
} else if seen_separator && line.starts_with(">>>>>>> ") {
return true;
}
}
false
}
pub(crate) type SplitSections = IndexMap<String, (String, String)>;
pub(crate) struct DuplicateSection {
pub key: String,
pub heading: String,
pub occurrences: usize,
}
fn section_heading_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| Regex::new(r"(?m)^## (.+)$").unwrap())
}
fn section_content(body: &str, content_start: usize, content_end: usize) -> (&str, usize) {
let raw = &body[content_start..content_end];
let visible_start = raw
.split_inclusive('\n')
.take_while(|line| line.trim().is_empty())
.map(str::len)
.sum::<usize>();
(
raw[visible_start..].trim_end(),
content_start + visible_start,
)
}
fn section_boundaries(body: &str, masked_body: &str) -> Vec<Range<usize>> {
let mut bounds: BTreeMap<usize, usize> = section_heading_re()
.find_iter(masked_body)
.map(|m| (m.start(), m.end()))
.collect();
if bounds.is_empty() {
return Vec::new();
}
let read_as_heading = crate::markdown::heading_starts(body);
let mut work: Vec<usize> = bounds
.keys()
.copied()
.filter(|start| read_as_heading.binary_search(start).is_err())
.collect();
while let Some(start) = work.pop() {
let end = bounds[&start];
let content_end = bounds
.range(start + 1..)
.next()
.map_or(body.len(), |(next, _)| *next);
let heading_line = &body[start..end];
let (content, content_start) = section_content(body, end, content_end);
let piece = format!("{heading_line}\n{content}");
let masked = mask_code_blocks(&piece);
let Some(extra) = section_heading_re()
.find_iter(&masked)
.find(|m| m.start() > 0)
else {
continue;
};
let abs_start = content_start + (extra.start() - heading_line.len() - 1);
bounds.insert(abs_start, abs_start + extra.len());
work.push(abs_start);
}
bounds.into_iter().map(|(start, end)| start..end).collect()
}
pub(crate) fn split_sections(
body: &str,
masked_body: &str,
) -> (SplitSections, Vec<DuplicateSection>, Vec<String>) {
let mut sections = IndexMap::new();
let mut duplicates: HashMap<String, DuplicateSection> = HashMap::new();
let mut raw_headings = Vec::new();
let boundaries = section_boundaries(body, masked_body);
for (i, m) in boundaries.iter().enumerate() {
let heading_line = &body[m.clone()];
let name = heading_line
.strip_prefix("## ")
.unwrap_or(heading_line)
.trim();
let content_end = boundaries.get(i + 1).map_or(body.len(), |next| next.start);
let (content, _) = section_content(body, m.end, content_end);
let content = content.to_string();
let key = memstead_schema::derive_section_key(name);
raw_headings.push(name.to_string());
match sections.entry(key.clone()) {
indexmap::map::Entry::Vacant(slot) => {
slot.insert((heading_line.to_string(), content));
duplicates.insert(
key.clone(),
DuplicateSection {
key: key.clone(),
heading: name.to_string(),
occurrences: 1,
},
);
}
indexmap::map::Entry::Occupied(_) => {
if let Some(d) = duplicates.get_mut(&key) {
d.occurrences += 1;
}
}
}
}
let dup_list: Vec<DuplicateSection> = duplicates
.into_values()
.filter(|d| d.occurrences > 1)
.collect();
(sections, dup_list, raw_headings)
}
fn extract_title(body: &str, masked_body: &str) -> Option<String> {
for (line, masked) in body.lines().zip(masked_body.lines()) {
if masked.starts_with("# ") {
return Some(line[2..].trim().to_string());
}
}
None
}
fn extract_heading_spans(sections: &IndexMap<String, String>) -> HashMap<String, Vec<HeadingSpan>> {
static RE: OnceLock<Regex> = OnceLock::new();
let re = RE.get_or_init(|| Regex::new(r"(?m)^(#{3,6})[ \t]+(.+)$").unwrap());
let mut out: HashMap<String, Vec<HeadingSpan>> = HashMap::new();
for (key, content) in sections {
if content.is_empty() {
continue;
}
let masked = mask_code_blocks(content);
let raw: Vec<(usize, u8, String)> = re
.captures_iter(&masked)
.map(|cap| {
let whole = cap.get(0).unwrap();
let level = cap[1].len() as u8; let line_end = content[whole.start()..]
.find('\n')
.map(|i| whole.start() + i)
.unwrap_or(content.len());
let hashes_end = whole.start() + level as usize;
let title = content[hashes_end..line_end].trim().to_string();
(whole.start(), level, title)
})
.collect();
if raw.is_empty() {
continue;
}
let mut spans: Vec<HeadingSpan> = Vec::with_capacity(raw.len());
for (i, &(start, level, ref title)) in raw.iter().enumerate() {
let end = raw[i + 1..]
.iter()
.find(|(_, l, _)| *l <= level)
.map(|(s, _, _)| *s)
.unwrap_or(content.len());
spans.push(HeadingSpan {
level,
title: title.clone(),
start_offset: start,
end_offset: end,
});
}
out.insert(key.clone(), spans);
}
out
}
fn build_catch_all(sections: &SplitSections, schema: &TypeDefinition) -> String {
let catch_all = match schema.catch_all_section() {
Some(s) => s,
None => return String::new(),
};
let known_sections: HashSet<&str> = schema
.sections
.iter()
.map(|s| s.key.as_str())
.chain(std::iter::once("relationships"))
.collect();
let mut parts = Vec::new();
if let Some((_, content)) = sections.get(catch_all.key.as_str())
&& !content.is_empty()
{
parts.push(content.clone());
}
for (key, (heading_line, content)) in sections {
if !known_sections.contains(key.as_str()) && !content.is_empty() {
parts.push(format!("{heading_line}\n{content}"));
}
}
let mut joined = String::new();
for piece in parts {
if joined.is_empty() {
joined = piece;
} else {
joined.push_str("\n\n");
joined.push_str(&piece);
}
if let Some(closer) = crate::markdown::closing_context_if_unterminated(&joined) {
joined.push('\n');
joined.push_str(&closer);
}
}
joined
}
pub(crate) fn parse_relationships_with_warnings(
text: &str,
mem: &str,
entity_id: Option<&EntityId>,
) -> (Vec<Relationship>, Vec<crate::ops::WarningHint>) {
static RE: OnceLock<Regex> = OnceLock::new();
let re = RE.get_or_init(|| {
Regex::new(r"(?m)^\s*-\s*\*\*(\w+)\*\*:\s*\[\[([^\]\n]+)\]\](?P<tail>[^\n]*)").unwrap()
});
let mut relationships = Vec::new();
let mut warnings = Vec::new();
let masked = mask_code_blocks_and_spans(text);
for cap in re.captures_iter(&masked) {
let rel_type = text[cap.get(1).unwrap().range()].to_uppercase();
let target = wiki_link_to_id_lenient(&text[cap.get(2).unwrap().range()], mem);
if target.path().is_empty() {
continue;
}
let tail = cap.name("tail").map(|m| &text[m.range()]).unwrap_or("");
let description = match classify_description_tail(tail) {
DescriptionTail::None => None,
DescriptionTail::EmDash(text) => Some(text),
DescriptionTail::Ambiguous(literal) => {
if let Some(id) = entity_id {
warnings.push(crate::ops::WarningHint::AmbiguousDescriptionDelimiter {
from: id.clone(),
rel_type: rel_type.clone(),
target: target.clone(),
trailing: literal,
});
}
None
}
};
relationships.push(Relationship {
rel_type,
target,
description,
});
}
(relationships, warnings)
}
enum DescriptionTail {
None,
EmDash(String),
Ambiguous(String),
}
fn classify_description_tail(tail: &str) -> DescriptionTail {
let trimmed_end = tail.trim_end();
if trimmed_end.is_empty() {
return DescriptionTail::None;
}
if let Some(rest) = trimmed_end.strip_prefix(" \u{2014} ") {
if rest.is_empty() {
return DescriptionTail::None;
}
return DescriptionTail::EmDash(rest.to_string());
}
if let Some(rest) = trimmed_end.strip_prefix(" \u{2014}") {
return DescriptionTail::Ambiguous(format!(" \u{2014}{rest}"));
}
let starters = [" --", " -", " \u{2013}", " \u{2212}"];
if starters
.iter()
.any(|prefix| trimmed_end.starts_with(prefix))
{
return DescriptionTail::Ambiguous(trimmed_end.to_string());
}
DescriptionTail::Ambiguous(trimmed_end.to_string())
}
fn wiki_link_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| Regex::new(r"\[\[([^\]]*)\]\]").unwrap())
}
pub(crate) fn extract_inline_links(
text: &str,
mem: &str,
) -> Result<Vec<EntityId>, Vec<WikiLinkError>> {
let stripped = mask_code_blocks_and_spans(text);
let link_re = wiki_link_re();
let mut seen = HashSet::new();
let mut links = Vec::new();
let mut errors = Vec::new();
for cap in link_re.captures_iter(&stripped) {
match wiki_link_to_id(&cap[1], mem) {
Ok(id) => {
if errors.is_empty() && seen.insert(id.0.clone()) {
links.push(id);
}
}
Err(e) => errors.push(e),
}
}
if errors.is_empty() {
Ok(links)
} else {
Err(errors)
}
}
pub fn extract_inline_links_lenient(text: &str, mem: &str) -> Vec<EntityId> {
let stripped = mask_code_blocks_and_spans(text);
let link_re = wiki_link_re();
let mut seen = HashSet::new();
let mut links = Vec::new();
for cap in link_re.captures_iter(&stripped) {
if cap[1].is_empty() {
continue;
}
let id = wiki_link_to_id_lenient(&cap[1], mem);
if seen.insert(id.0.clone()) {
links.push(id);
}
}
links
}
pub fn compute_hash(content: &str) -> String {
let mut hasher = Sha256::new();
hasher.update(content.as_bytes());
let result = hasher.finalize();
crate::hex_lower(&result)[..16].to_string()
}
#[derive(Debug, thiserror::Error)]
pub enum ParseError {
#[error("missing frontmatter")]
MissingFrontmatter,
#[error("invalid frontmatter: {0}")]
InvalidFrontmatter(String),
#[error("missing title")]
MissingTitle,
#[error("io error: {0}")]
Io(#[from] std::io::Error),
}
#[cfg(test)]
mod commonmark_referee;
#[cfg(test)]
mod tests;