use std::collections::BTreeMap;
use tramlines_core::grammar::Lowerer;
use tramlines_md::grammar::lower_common;
use super::{Block, Limit, RegexCache, RuleCommon, Schema, States, TypeRegistry, Unit};
use crate::{Finding, RepoPath, Spanned};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Dispatch {
Type(String),
Globs(Vec<String>),
}
#[derive(Debug, Clone)]
pub struct LinkRule {
pub common: RuleCommon,
pub rel: String,
pub to_type: Vec<String>,
pub min: usize,
pub max: Option<Limit>,
pub guidance: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CitedFrom {
Types(Vec<String>),
Marker(String),
}
#[derive(Debug, Clone)]
pub struct CitationRule {
pub common: RuleCommon,
pub from: CitedFrom,
pub keys: Option<String>,
pub message: Option<String>,
}
#[derive(Debug, Clone)]
pub struct PathPlan {
pub common: RuleCommon,
pub section: String,
}
#[derive(Debug, Clone)]
pub struct SokfSchema {
pub core: Schema,
pub dispatch: Dispatch,
pub asset_files: Vec<String>,
pub root: Option<String>,
pub paths: Vec<String>,
pub links: Vec<LinkRule>,
pub links_open: bool,
pub cited_by: Vec<CitationRule>,
pub markers: Option<Vec<String>>,
pub plans_paths: Vec<PathPlan>,
pub current_links: Vec<regex::Regex>,
pub unit_types: BTreeMap<usize, Vec<String>>,
}
fn fail(
path: &RepoPath,
line: usize,
criterion: &'static str,
message: impl Into<String>,
) -> Finding {
Finding::error(path.clone(), Some(line), criterion, message)
}
fn glob_problem(g: &str) -> Option<String> {
if !g.starts_with('/') {
return Some("does not start with /".into());
}
globset::Glob::new(g)
.err()
.map(|e| format!("does not parse: {e}"))
}
fn list(node: &Spanned) -> Vec<String> {
node.as_str_or_list().unwrap_or_default()
}
fn kebab(rel: &str) -> Option<String> {
let mut out = String::new();
let mut prev_lower = false;
for c in rel.chars() {
if c.is_ascii_uppercase() && prev_lower {
out.push('-');
}
prev_lower = c.is_ascii_lowercase() || c.is_ascii_digit();
out.push(match c {
'_' | ' ' => '-',
c => c.to_ascii_lowercase(),
});
}
crate::markdown::is_slug(&out).then_some(out)
}
pub fn glob_inside(glob: &str, dir: &RepoPath) -> bool {
let prefix: String = glob
.chars()
.take_while(|c| !matches!(c, '*' | '?' | '[' | '{'))
.collect();
let dir = format!("{}/", dir.as_str().trim_end_matches('/'));
prefix.starts_with(&dir)
}
impl LinkRule {
pub fn banned(&self) -> bool {
self.max.as_ref().and_then(Limit::hard) == Some(0)
}
}
impl SokfSchema {
pub fn type_root(&self) -> Option<RepoPath> {
RepoPath::parse(self.root.as_deref()?)
}
pub fn of_schema_document(core: Schema) -> Self {
SokfSchema {
core,
dispatch: Dispatch::Type("Schema".into()),
asset_files: vec![],
root: None,
paths: vec![],
links: vec![],
links_open: true,
cited_by: vec![],
markers: None,
plans_paths: vec![],
current_links: vec![],
unit_types: BTreeMap::new(),
}
}
pub fn lower(core: Schema, yaml: &Spanned, path: &RepoPath) -> (Self, Vec<Finding>) {
let mut lw = Lowering {
core: &core,
yaml,
path,
findings: Vec::new(),
};
let (dispatch, asset_files) = lw.dispatch();
let paths = path_dimensions(&core);
let root = lw.ext("root").and_then(|r| r.as_str()).map(str::to_string);
lw.check_archived();
lw.check_labels();
lw.check_lifecycle(&paths, root.as_deref());
lw.findings.extend(asset_globs(
path,
lw.ext("asset-files").map_or(yaml.line, |a| a.line),
&asset_files,
root.as_deref(),
));
let links = lw.links();
let links_open = lw
.ext("links-open")
.and_then(Spanned::as_bool)
.unwrap_or(false);
let cited_by = lw.cited_by();
let markers = lw.markers();
let plans_paths = lw.plans_paths();
let current_links = lw
.ext("current-links")
.map(list)
.unwrap_or_default()
.iter()
.filter_map(|p| regex::Regex::new(p).ok())
.collect();
let findings = lw.findings;
let unit_types = unit_types(&core);
let schema = SokfSchema {
core,
dispatch,
asset_files,
root,
paths,
links,
links_open,
cited_by,
markers,
plans_paths,
current_links,
unit_types,
};
(schema, findings)
}
pub fn has_assets(&self) -> bool {
!self.asset_files.is_empty()
}
pub fn written_links<'s>(&'s self, states: &'s States) -> impl Iterator<Item = &'s LinkRule> {
self.links
.iter()
.filter(|r| r.common.only.admits(states) && !r.banned())
}
pub fn is_path(&self, key: &str) -> bool {
self.paths.iter().any(|p| p == key)
}
}
struct Lowering<'a> {
core: &'a Schema,
yaml: &'a Spanned,
path: &'a RepoPath,
findings: Vec<Finding>,
}
impl<'a> Lowering<'a> {
fn ext(&self, key: &str) -> Option<&'a Spanned> {
self.core.extensions.get(key)
}
fn dispatch(&mut self) -> (Dispatch, Vec<String>) {
let (path, yaml) = (self.path, self.yaml);
let globs = self.ext("additional-files").map(list);
let assets = self.ext("asset-files").map(list);
let dispatch = match (self.core.core.type_const().map(str::to_string), globs) {
(Some(_), Some(_)) => {
self.findings.push(fail(
path,
yaml.line,
"SOKF_SCHEMA_3",
"the schema declares both a `type` const and `additional-files`. Declare only one of them",
));
Dispatch::Globs(vec![])
}
(None, None) => {
let message = if assets.is_some() {
"`asset-files` needs a `type` const as well"
} else {
"the schema declares neither a `type` const nor `additional-files`. Declare one of them"
};
self.findings
.push(fail(path, yaml.line, "SOKF_SCHEMA_3", message));
Dispatch::Globs(vec![])
}
(Some(t), None) => Dispatch::Type(t),
(None, Some(globs)) => {
let line = self.ext("additional-files").map_or(yaml.line, |a| a.line);
for g in &globs {
if let Some(why) = glob_problem(g) {
self.findings.push(fail(
path,
line,
"SOKF_SCHEMA_5",
format!("`additional-files` glob `{g}` {why}"),
));
}
}
Dispatch::Globs(globs)
}
};
let asset_files = match assets {
None => vec![],
Some(globs) => {
if self.ext("additional-files").is_some() {
let line = self.ext("asset-files").map_or(yaml.line, |a| a.line);
self.findings.push(fail(
path,
line,
"SOKF_SCHEMA_4",
"the schema declares `asset-files` together with `additional-files`. Declare only one of them",
));
}
globs
}
};
(dispatch, asset_files)
}
fn check_archived(&mut self) {
let path = self.path;
for d in &self.core.core.lifecycle {
let Some(node) = d.extensions.get("archived") else {
continue;
};
for state in list(node) {
if !d.states.contains(&state) {
self.findings.push(fail(
path,
node.line,
"SOKF_SCHEMA_50",
format!(
"`archived` state `{state}` is not a state of the dimension `{}`",
d.key
),
));
}
}
}
if let Some(a) = self.ext("archived")
&& !self.core.core.lifecycle.is_empty()
{
self.findings.push(fail(
path,
a.line,
"SOKF_SCHEMA_50",
"the schema declares `archived` together with `lifecycle`. Declare `archived` on a dimension",
));
}
}
fn check_labels(&mut self) {
let Some(labels) = self.yaml.get("labels") else {
return;
};
let items = labels.as_seq().unwrap_or_default();
for key in crate::config::LABELS {
if !items.iter().any(|i| i.as_str() == Some(key)) {
self.findings.push(fail(
self.path,
labels.line,
"SOKF_SCHEMA_104",
format!(
"`labels` holds no `{key}`; a schema declares both of sokf's labels, `human` and `agent`"
),
));
}
}
for item in items {
let Some(key) = item.as_str() else {
continue;
};
if !crate::config::LABELS.contains(&key) {
self.findings.push(fail(
self.path,
item.line,
"SOKF_SCHEMA_104",
format!(
"`labels` holds `{key}`, which is no label of sokf's; sokf's labels are `human` and `agent`"
),
));
}
}
}
fn check_lifecycle(&mut self, paths: &[String], root: Option<&str>) {
let path = self.path;
if let Some(l) = self.yaml.get("lifecycle") {
if self.ext("additional-files").is_some() {
self.findings.push(fail(
path,
l.line,
"SOKF_SCHEMA_4",
"the schema declares `lifecycle` together with `additional-files`. Declare only one of them",
));
}
if !paths.is_empty() && root.is_none() {
self.findings.push(fail(
path,
l.line,
"SOKF_SCHEMA_27",
"a path-enforced dimension needs `root`",
));
}
}
if let Some(r) = self.ext("root")
&& root.and_then(RepoPath::parse).is_none()
{
self.findings.push(fail(
path,
r.line,
"SOKF_SCHEMA_27",
"`root` is not a valid repository path: it must start with / and have no empty, `.`, or `..` segment",
));
}
}
fn links(&mut self) -> Vec<LinkRule> {
let mut links = Vec::new();
let regexes = RegexCache::default();
let mut limits = Lowerer::new(®exes, self.path, TypeRegistry::default());
for node in self.ext("links").and_then(|l| l.as_seq()).unwrap_or(&[]) {
let (common, problems) = lower_common(node, &self.core.core, self.path);
self.findings.extend(problems);
let usize_of = |key: &str| {
node.get(key)
.and_then(Spanned::as_int)
.map(|i| usize::try_from(i).unwrap_or(0))
};
let min = usize_of("min").unwrap_or(1);
let max = limits.limit(node, "max");
limits.check_bounds(node.line, min, max.as_ref());
links.push(LinkRule {
common,
rel: node
.get("rel")
.and_then(|r| r.as_str())
.unwrap_or_default()
.to_string(),
to_type: node.get("to-type").map(list).unwrap_or_default(),
min,
max,
guidance: node
.get("guidance")
.and_then(|g| g.as_str())
.map(str::to_string),
});
}
self.findings.append(&mut limits.findings);
links
}
fn cited_by(&mut self) -> Vec<CitationRule> {
let path = self.path;
let mut cited_by = Vec::new();
for node in self.ext("cited-by").and_then(|l| l.as_seq()).unwrap_or(&[]) {
let (common, problems) = lower_common(node, &self.core.core, path);
self.findings.extend(problems);
let keys = node
.get("keys")
.and_then(|k| k.as_str())
.map(str::to_string);
if let Some(k) = &keys
&& let Err(why) = self.core.rule_captures_key(k)
{
self.findings.push(fail(
path,
node.line,
"SOKF_SCHEMA_35",
why.message("keys", k),
));
}
let from = match (node.get("from-type"), node.get("from-marker")) {
(None, Some(m)) => CitedFrom::Marker(m.as_str().unwrap_or_default().to_string()),
(t, _) => CitedFrom::Types(t.map(list).unwrap_or_default()),
};
let message = node
.get("message")
.and_then(|m| m.as_str())
.map(str::to_string);
cited_by.push(CitationRule {
common,
from,
keys,
message,
});
}
cited_by
}
fn markers(&mut self) -> Option<Vec<String>> {
let markers_node = self.ext("markers");
let markers = markers_node.map(list);
for item in markers_node.and_then(|n| n.as_seq()).unwrap_or(&[]) {
let Some(rel) = item.as_str() else { continue };
if crate::markdown::is_slug(rel) {
continue;
}
let fix = match kebab(rel) {
Some(k) => format!("Write it as `{k}`"),
None => "Write it as lowercase words of letters and digits joined by `-`".into(),
};
self.findings.push(fail(
self.path,
item.line,
"EXT-9_AC-11",
format!(
"`markers` names the relationship `{rel}`, which isn't lowercase kebab case, so it matches no marker. {fix}"
),
));
}
markers
}
fn plans_paths(&mut self) -> Vec<PathPlan> {
let path = self.path;
let mut plans_paths = Vec::new();
for node in self
.ext("plans-paths")
.and_then(|l| l.as_seq())
.unwrap_or(&[])
{
let (common, problems) = lower_common(node, &self.core.core, path);
self.findings.extend(problems);
let section = node
.get("section")
.and_then(|s| s.as_str())
.unwrap_or_default()
.to_string();
if !self
.core
.sections
.iter()
.any(|s| s.rule_id.as_deref() == Some(section.as_str()))
{
self.findings.push(fail(
path,
node.line,
"SOKF_SCHEMA_52",
format!("`section: {section}` names no section of the schema; give the `rule-id` of a section"),
));
}
plans_paths.push(PathPlan { common, section });
}
plans_paths
}
}
fn path_dimensions(schema: &Schema) -> Vec<String> {
schema
.core
.lifecycle
.iter()
.filter(|d| {
d.extensions
.get("path")
.and_then(Spanned::as_bool)
.unwrap_or(false)
})
.map(|d| d.key.clone())
.collect()
}
fn unit_types(schema: &Schema) -> BTreeMap<usize, Vec<String>> {
let mut out = BTreeMap::new();
let mut blocks: Vec<&Block> = schema
.sections
.iter()
.filter_map(|s| s.blocks.as_deref())
.chain(schema.preamble.iter().filter_map(|p| p.blocks.as_deref()))
.flatten()
.collect();
while let Some(b) = blocks.pop() {
blocks.extend(b.blocks.iter().flatten());
let mut units: Vec<&Unit> = b.units().collect();
while let Some(u) = units.pop() {
units.extend(u.lines.iter().flatten());
blocks.extend(u.blocks.iter().flatten());
if let Some(types) = u.extensions.get("to-type") {
out.insert(u.index, list(types));
}
}
}
out
}
fn asset_globs(path: &RepoPath, line: usize, globs: &[String], root: Option<&str>) -> Vec<Finding> {
let mut findings = Vec::new();
let knowledge = path.parent().and_then(|d| d.parent());
for g in globs {
if let Some(why) = glob_problem(g) {
findings.push(fail(
path,
line,
"SOKF_SCHEMA_8",
format!("`asset-files` glob `{g}` {why}"),
));
continue;
}
if let Some(k) = &knowledge
&& !glob_inside(g, k)
{
findings.push(fail(
path,
line,
"SOKF_SCHEMA_8",
format!("`asset-files` glob `{g}` lies outside the knowledge root `{k}`"),
));
}
if let Some(r) = root
&& !g.starts_with(&format!("{}/**/", r.trim_end_matches('/')))
{
findings.push(fail(
path,
line,
"SOKF_SCHEMA_10",
format!(
"`asset-files` glob `{g}` does not begin with `{r}/**/`, where `{r}` is the lifecycle root"
),
));
}
}
findings
}