use crate::bridge::Feature;
use crate::dims::fmt;
use crate::model::Analysis;
pub fn capital(s: &str) -> String {
let mut c = s.chars();
match c.next() {
Some(f) if f.is_alphabetic() => f.to_uppercase().chain(c).collect(),
Some(_) => format!("The dimension {s}"),
None => String::new(),
}
}
pub fn feature(f: &Feature) -> String {
let p = |name: &str| f.parameters.get(name).and_then(|v| v.as_f64());
let kind = words(&f.kind);
let sized = match f.kind.as_str() {
"hole" | "boss" | "turned_step" => p("diameter").map(|d| format!("⌀{} {kind}", fmt(d))),
"countersink" => p("major_diameter").map(|d| format!("⌀{} {kind}", fmt(d))),
"blend" | "fillet" | "circular_blind_step" => {
p("radius").map(|r| format!("R{} {kind}", fmt(r)))
}
"chamfer" => p("leg1").map(|l| format!("{} {kind}", fmt(l))),
"slot" => p("width").map(|w| format!("{} wide {kind}", fmt(w))),
"flat" => p("across").map(|a| format!("{} {kind}", fmt(a))),
"polygonal_boss" => p("across_flats").map(|a| format!("{} A/F {kind}", fmt(a))),
"angled_step" | "paired_ramp_step" => p("angle").map(|a| format!("{}° {kind}", fmt(a))),
"plate" => p("hi")
.zip(p("lo"))
.map(|(hi, lo)| format!("{} thick {kind}", fmt(hi - lo))),
_ => None,
};
format!("the {}", sized.unwrap_or(kind))
}
pub fn feature_id(a: &Analysis, id: &str) -> String {
if let Some(f) = a.features.iter().find(|f| f.id == id) {
return match f.kind.as_str() {
"slot_pattern" => {
let n = f.parameters.get("slots").and_then(|v| v.as_array());
match n {
Some(n) => format!("the {}× slot pattern", n.len()),
None => "the slot pattern".into(),
}
}
_ => feature(f),
};
}
if let Some(p) = a
.recognition
.iter()
.flat_map(|r| &r.patterns)
.find(|p| p.id == id)
{
let d = p
.members
.first()
.and_then(|m| a.features.iter().find(|f| f.id == *m))
.and_then(|f| f.parameters.get("diameter"))
.and_then(|v| v.as_f64());
return match d {
Some(d) => format!("the {}× ⌀{} hole pattern", p.members.len(), fmt(d)),
None => format!("the {}× hole pattern", p.members.len()),
};
}
kind_of(id)
}
pub fn kind_of(id: &str) -> String {
match id.strip_prefix("f:").and_then(|s| s.split(':').next()) {
Some(kind) => format!("the {}", words(kind)),
None if id == "envelope" => "the part's overall size".into(),
None if id == "step_level" => "the step heights".into(),
None => "a feature".into(),
}
}
pub fn view(id: &str) -> String {
let name = id.strip_prefix("v:").unwrap_or(id);
match name {
"iso" => "the isometric view".into(),
_ => match name.strip_prefix("section_") {
Some(letters) => {
let l: Vec<String> = letters
.chars()
.map(|c| c.to_uppercase().collect())
.collect();
format!("section {}", l.join("\u{2013}"))
}
None => format!("the {} view", words(name)),
},
}
}
pub fn block(id: &str) -> String {
if id.starts_with("v:") {
view(id)
} else if id == crate::lint::blends::RADIUS_TABLE {
"the radius table".into()
} else if let Some(k) = id.strip_prefix("t:") {
format!("table {k}")
} else if id.starts_with("hole_table") || id.starts_with("hole_schedule") {
"the hole table".into()
} else if id.starts_with("spring_data_") {
"the spring data table".into()
} else if id == crate::pmi_lowering::SCHEDULE_ID {
"the manufacturing requirements table".into()
} else {
"a block".into()
}
}
pub fn item(id: &str, kind: &str, label: &str) -> String {
let label = label.trim();
if id.starts_with("pmi:datum") {
return format!("datum feature symbol {label}");
}
if id.starts_with("pmi:geometric_tolerance") {
return format!("the feature control frame {label}");
}
if id.starts_with("v:") {
return view(id);
}
match kind {
"notes" => "the general notes".into(),
"table" => block(id),
"ink" => "a centre line".into(),
_ if id.starts_with("n:") => note(label),
_ if id.starts_with("t:") => block(id),
_ if !label.is_empty() => label.into(),
_ => "a dimension".into(),
}
}
pub fn line_work(kind: &str) -> String {
match kind {
"axis" => "a centre line".into(),
"cross" => "a centre mark".into(),
"pitch_circle" => "a pitch circle".into(),
"cutting_plane" => "the cutting-plane line".into(),
k => format!("a {} line", words(k)),
}
}
pub fn note(text: &str) -> String {
let text = text.trim();
if text.is_empty() {
return "a general note".into();
}
let short: String = text.chars().take(40).collect();
let more = if short.len() < text.len() { "…" } else { "" };
format!("the note \"{short}{more}\"")
}
pub fn dimension_id(a: &Analysis, id: &str) -> String {
let Some((feature, parameter)) = id.strip_prefix("d:").and_then(|s| s.rsplit_once('/')) else {
return "a dimension".into();
};
let role = parameter.split('.').next().unwrap_or(parameter);
match feature {
"envelope" if role.starts_with("notch") => format!("the {}", words(role)),
"envelope" => format!("the overall {}", words(role)),
"step_level" => format!("the {}", words(role)),
f if f.starts_with("pmi:") => "the PMI dimension".into(),
f => format!("the {} of {}", words(role), feature_id(a, f)),
}
}
pub fn left_out(state: &crate::items::State) -> &'static str {
use crate::items::State;
match state {
State::OmittedByUser => "the spec omits it",
State::NotAuthored => "the authored set does not list it",
State::Covered { .. } => "another dimension states what it would",
_ => "it is not drawn",
}
}
fn words(s: &str) -> String {
s.replace('_', " ")
}
pub fn carries_id(message: &str) -> Option<&str> {
const PREFIXES: [&str; 7] = ["d:", "f:", "v:", "pmi:", "n:", "t:", "face:"];
let mut start = 0;
for (i, c) in message.char_indices() {
if !(c.is_alphanumeric() || c == '_' || c == ':') {
start = i + c.len_utf8();
continue;
}
let token = &message[start..];
if i == start
&& let Some(p) = PREFIXES.iter().find(|p| token.starts_with(**p))
&& token[p.len()..]
.chars()
.next()
.is_some_and(|c| c.is_ascii_alphanumeric())
{
let end = token
.find(|c: char| c.is_whitespace() || c == ',' || c == ')' || c == ';')
.unwrap_or(token.len());
return Some(token[..end].trim_end_matches(['.', '\'']));
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ids_are_found_and_words_are_not() {
assert_eq!(
carries_id("The extension of d:f:hole_pattern:1/grid_pitch.length.col (2× 30)."),
Some("d:f:hole_pattern:1/grid_pitch.length.col")
);
assert_eq!(carries_id("It crosses f:hole:4."), Some("f:hole:4"));
assert_eq!(carries_id("over the v:plan view"), Some("v:plan"));
assert_eq!(carries_id("set sheet/title/tolerance, 2× 30 at 2:1"), None);
assert_eq!(carries_id("Section A–A, the ⌀6.6 hole: R3 at d: 5"), None);
}
#[test]
fn views_read_as_their_names() {
assert_eq!(view("v:plan"), "the plan view");
assert_eq!(view("v:section_aa"), "section A\u{2013}A");
assert_eq!(view("v:iso"), "the isometric view");
}
}