1use std::collections::BTreeSet;
15
16use crate::concept_records::{
17 ConceptRecord, SourceAlias, concept_record, concept_records, concept_records_for_source_name,
18};
19use crate::foundation_models::{FoundationRegister, foundation_register};
20use crate::grammar::{Grammar, GrammarExpr, RuleKind};
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub struct RequiredDistinction {
25 pub concepts: [&'static str; 2],
27 pub reason: &'static str,
29}
30
31pub const REQUIRED_CONCEPT_DISTINCTIONS: &[RequiredDistinction] =
33 include!("data/required-concept-distinctions.rs");
34
35pub const REQUIRED_FOUNDATION_DISTINCTIONS: &[[&str; 2]] = &[
37 [
38 "integer-model.natural-number",
39 "integer-model.unbounded-integer",
40 ],
41 ["overflow-model.abort", "overflow-model.wrapping"],
42 [
43 "effect-model.abort",
44 "effect-model.panic-with-default-value",
45 ],
46 [
47 "universe-model.non-cumulative-sort-hierarchy",
48 "universe-model.cumulative-type-hierarchy",
49 ],
50 [
51 "proof-system.bounded-property-check",
52 "proof-system.lean-kernel",
53 ],
54 [
55 "logic-model.constructive-propositions",
56 "logic-model.classical-propositions",
57 ],
58];
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub enum CorrespondenceRelation {
63 Shared,
65 Distinct,
67 Ambiguous,
69 Unknown,
71}
72
73impl CorrespondenceRelation {
74 #[must_use]
76 pub const fn as_str(self) -> &'static str {
77 match self {
78 Self::Shared => "shared",
79 Self::Distinct => "distinct",
80 Self::Ambiguous => "ambiguous",
81 Self::Unknown => "unknown",
82 }
83 }
84}
85
86#[derive(Debug, Clone, PartialEq, Eq)]
88pub struct ConceptCorrespondence {
89 pub relation: CorrespondenceRelation,
91 pub first: Vec<String>,
93 pub second: Vec<String>,
95 pub shared: Option<String>,
97 pub justification: Option<String>,
99 pub correspondence: Option<String>,
101}
102
103#[derive(Debug, Clone, PartialEq, Eq)]
105pub struct ConceptDistinctionProblem {
106 pub kind: &'static str,
108 pub subject: String,
110 pub message: String,
112}
113
114#[derive(Debug, Clone, PartialEq, Eq)]
116pub struct PrecedenceUse {
117 pub rule: String,
119 pub label: String,
121 pub concept: &'static str,
123}
124
125fn within_matches(id: &str, within: Option<&str>) -> bool {
126 within.is_none_or(|prefix| {
127 id == prefix
128 || id
129 .strip_prefix(prefix)
130 .is_some_and(|rest| rest.starts_with('.'))
131 })
132}
133
134#[must_use]
140pub fn source_meanings_in(
141 records: &[ConceptRecord],
142 register: &FoundationRegister,
143 alias: &SourceAlias,
144 within: Option<&str>,
145) -> Vec<String> {
146 let concepts: Vec<&ConceptRecord> = if std::ptr::eq(records, concept_records()) {
149 concept_records_for_source_name(&alias.source, &alias.name)
150 } else {
151 records
152 .iter()
153 .filter(|record| {
154 record.source_aliases.iter().any(|candidate| {
155 candidate.source == alias.source && candidate.name == alias.name
156 })
157 })
158 .collect()
159 };
160 let models = register.models.iter().filter(|model| {
161 model.source_aliases.iter().any(|candidate| {
162 candidate.source == alias.source
163 && candidate
164 .name
165 .split(", ")
166 .any(|spelling| spelling == alias.name)
167 })
168 });
169 concepts
170 .into_iter()
171 .map(|record| record.id.clone())
172 .chain(models.map(|model| model.id.clone()))
173 .filter(|id| within_matches(id, within))
174 .collect()
175}
176
177fn same_pair(pair: &[impl AsRef<str>], first: &str, second: &str) -> bool {
178 pair.len() == 2
179 && ((pair[0].as_ref() == first && pair[1].as_ref() == second)
180 || (pair[0].as_ref() == second && pair[1].as_ref() == first))
181}
182
183fn meaning_definition(
184 records: &[ConceptRecord],
185 register: &FoundationRegister,
186 id: &str,
187) -> Option<String> {
188 let concept = if std::ptr::eq(records, concept_records()) {
189 concept_record(id).filter(|record| record.id == id)
190 } else {
191 records.iter().find(|record| record.id == id)
192 };
193 concept.map(|record| record.definition.clone()).or_else(|| {
194 register
195 .models
196 .iter()
197 .find(|model| model.id == id)
198 .map(|model| model.definition.clone())
199 })
200}
201
202#[must_use]
204pub fn concept_correspondence_in(
205 records: &[ConceptRecord],
206 register: &FoundationRegister,
207 first: &SourceAlias,
208 second: &SourceAlias,
209 within: Option<&str>,
210) -> ConceptCorrespondence {
211 let first_meanings = source_meanings_in(records, register, first, within);
212 let second_meanings = source_meanings_in(records, register, second, within);
213 let mut result = ConceptCorrespondence {
214 relation: CorrespondenceRelation::Unknown,
215 first: first_meanings.clone(),
216 second: second_meanings.clone(),
217 shared: None,
218 justification: None,
219 correspondence: None,
220 };
221 if first_meanings.is_empty() || second_meanings.is_empty() {
222 return result;
223 }
224 if first_meanings.len() > 1 || second_meanings.len() > 1 {
225 result.relation = CorrespondenceRelation::Ambiguous;
226 return result;
227 }
228 let (one, other) = (&first_meanings[0], &second_meanings[0]);
229 if one == other {
230 result.relation = CorrespondenceRelation::Shared;
231 result.shared = Some(one.clone());
232 result.justification = meaning_definition(records, register, one);
233 return result;
234 }
235 result.relation = CorrespondenceRelation::Distinct;
236 result.justification = REQUIRED_CONCEPT_DISTINCTIONS
237 .iter()
238 .find(|entry| same_pair(&entry.concepts, one, other))
239 .map(|entry| entry.reason.to_owned())
240 .or_else(|| {
241 register
242 .distinctions
243 .iter()
244 .find(|entry| same_pair(&entry.models, one, other))
245 .map(|entry| entry.reason.clone())
246 });
247 result.correspondence = register
248 .correspondences
249 .iter()
250 .find(|entry| same_pair(&[&entry.from, &entry.to], one, other))
251 .map(|entry| entry.kind.clone());
252 result
253}
254
255#[must_use]
257pub fn concept_correspondence(
258 first: &SourceAlias,
259 second: &SourceAlias,
260 within: Option<&str>,
261) -> ConceptCorrespondence {
262 concept_correspondence_in(
263 concept_records(),
264 foundation_register(),
265 first,
266 second,
267 within,
268 )
269}
270
271fn shared_sources(aliases: &[SourceAlias]) -> usize {
272 aliases
273 .iter()
274 .map(|alias| alias.source.as_str())
275 .filter(|source| *source != "meta-language" && !source.ends_with(" grammar surface"))
276 .collect::<BTreeSet<_>>()
277 .len()
278}
279
280fn is_justification(text: &str) -> bool {
282 let text = text.trim();
283 text.ends_with('.') && text.split_whitespace().count() >= 3
284}
285
286#[must_use]
296pub fn check_concept_distinctions(
297 records: &[ConceptRecord],
298 register: &FoundationRegister,
299) -> Vec<ConceptDistinctionProblem> {
300 let mut problems = Vec::new();
301 let mut report = |kind, subject: &str, message: String| {
302 problems.push(ConceptDistinctionProblem {
303 kind,
304 subject: subject.to_owned(),
305 message,
306 });
307 };
308 for entry in REQUIRED_CONCEPT_DISTINCTIONS {
309 let subject = entry.concepts.join(" / ");
310 let found: Vec<_> = entry
311 .concepts
312 .iter()
313 .map(|id| records.iter().find(|record| record.id == *id))
314 .collect();
315 for (id, record) in entry.concepts.iter().zip(&found) {
316 if record.is_none() {
317 report(
318 "unknown-concept",
319 &subject,
320 format!("{subject} must stay distinct, but {id} is not recorded"),
321 );
322 }
323 }
324 let [Some(first), Some(second)] = found[..] else {
325 continue;
326 };
327 if first.definition.trim().to_lowercase() == second.definition.trim().to_lowercase() {
328 report(
329 "indistinct-concepts",
330 &subject,
331 format!("{subject} record the same definition, which merges two meanings"),
332 );
333 }
334 for (record, other) in [(first, second), (second, first)] {
335 if record.former_names.contains(&other.id)
336 || record.represents.as_deref() == Some(other.id.as_str())
337 {
338 report(
339 "conflated-distinction",
340 &subject,
341 format!(
342 "{} records {} as itself, which merges two meanings",
343 record.id, other.id
344 ),
345 );
346 }
347 }
348 }
349 for pair in REQUIRED_FOUNDATION_DISTINCTIONS {
350 let subject = pair.join(" / ");
351 let found: Vec<_> = pair
352 .iter()
353 .map(|id| register.models.iter().find(|model| model.id == *id))
354 .collect();
355 for (id, model) in pair.iter().zip(&found) {
356 if model.is_none() {
357 report(
358 "unknown-model",
359 &subject,
360 format!("{subject} must stay distinct, but {id} is not recorded"),
361 );
362 }
363 }
364 if let [Some(first), Some(second)] = found[..]
365 && first.properties == second.properties
366 {
367 report(
368 "indistinct-concepts",
369 &subject,
370 format!("{subject} record the same properties, which merges two meanings"),
371 );
372 }
373 let recorded = register.distinctions.iter().any(|entry| {
374 same_pair(&entry.models, pair[0], pair[1]) && is_justification(&entry.reason)
375 });
376 if !recorded {
377 report(
378 "unrecorded-distinction",
379 &subject,
380 format!("the foundation register records no reason why {subject} differ"),
381 );
382 }
383 }
384 for record in records {
385 if shared_sources(&record.source_aliases) > 1
386 && (!is_justification(&record.definition) || record.constraints.is_empty())
387 {
388 report(
389 "unjustified-sharing",
390 &record.id,
391 format!(
392 "{} is shared by several sources but states no meaning that justifies the correspondence",
393 record.id
394 ),
395 );
396 }
397 }
398 for model in ®ister.models {
399 if shared_sources(&model.source_aliases) > 1
400 && (!is_justification(&model.definition) || model.properties.is_empty())
401 {
402 report(
403 "unjustified-sharing",
404 &model.id,
405 format!(
406 "{} is shared by several languages but states no meaning that justifies the correspondence",
407 model.id
408 ),
409 );
410 }
411 }
412 problems
413}
414
415fn is_precedence_label(label: &str) -> bool {
416 ["prec", "prec_left", "prec_right", "prec_dynamic"]
417 .iter()
418 .any(|name| {
419 label == *name
420 || label
421 .strip_prefix(name)
422 .is_some_and(|rest| rest.starts_with('='))
423 })
424}
425
426fn collect_precedence(
427 rule: &str,
428 expr: &GrammarExpr,
429 in_token: bool,
430 uses: &mut Vec<PrecedenceUse>,
431) {
432 match expr {
433 GrammarExpr::Capture { label, expr } => {
434 let label = label.as_deref().unwrap_or_default();
435 if is_precedence_label(label) {
436 let lexical = in_token && !label.starts_with("prec_dynamic");
437 uses.push(PrecedenceUse {
438 rule: rule.to_owned(),
439 label: label.to_owned(),
440 concept: if lexical {
441 "grammar.lexical-precedence"
442 } else {
443 "grammar.syntactic-precedence"
444 },
445 });
446 }
447 let token = in_token || label == "token" || label == "immediate_token";
448 collect_precedence(rule, expr, token, uses);
449 }
450 GrammarExpr::Choice { alternatives, .. } => {
451 for alternative in alternatives {
452 collect_precedence(rule, alternative, in_token, uses);
453 }
454 }
455 GrammarExpr::Sequence(items) => {
456 for item in items {
457 collect_precedence(rule, item, in_token, uses);
458 }
459 }
460 GrammarExpr::Optional(item)
461 | GrammarExpr::ZeroOrMore(item)
462 | GrammarExpr::OneOrMore(item)
463 | GrammarExpr::Repeat { expr: item, .. }
464 | GrammarExpr::And(item)
465 | GrammarExpr::Not(item) => collect_precedence(rule, item, in_token, uses),
466 _ => {}
467 }
468}
469
470#[must_use]
477pub fn grammar_precedence_concepts(grammar: &Grammar) -> Vec<PrecedenceUse> {
478 let mut uses = Vec::new();
479 for rule in grammar.rules() {
480 collect_precedence(
481 rule.name(),
482 rule.expr(),
483 rule.kind() == RuleKind::Token,
484 &mut uses,
485 );
486 }
487 uses
488}