1use std::collections::BTreeMap;
10use std::path::PathBuf;
11
12use serde::{Deserialize, Serialize};
13
14use crate::error::G8Error;
15use crate::model::IntentSourceKind;
16
17#[derive(Debug, Clone, Serialize, Deserialize)]
23pub struct SourceLocation {
24 pub file: PathBuf,
25 pub line: u32,
26 pub column: u32,
27}
28
29impl SourceLocation {
30 pub fn unknown(file: impl Into<PathBuf>) -> Self {
33 Self {
34 file: file.into(),
35 line: 0,
36 column: 0,
37 }
38 }
39}
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
56#[serde(rename_all = "snake_case")]
57pub enum AnnotationKind {
58 Capability,
59 Intent,
60 ConvergenceTest,
61 Decision,
62 Plan,
63}
64
65impl AnnotationKind {
66 fn from_str(s: &str) -> Option<Self> {
67 match s {
68 "capability" => Some(Self::Capability),
69 "intent" => Some(Self::Intent),
70 "convergence_test" => Some(Self::ConvergenceTest),
71 "decision" => Some(Self::Decision),
72 "plan" => Some(Self::Plan),
73 _ => None,
74 }
75 }
76}
77
78#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
93#[serde(untagged)]
94pub enum AnnotationValue {
95 String(String),
96 Bool(bool),
97 Number(i64),
98 List(Vec<String>),
99}
100
101#[derive(Debug, Clone, Serialize, Deserialize)]
108pub struct RawAnnotation {
109 pub kind_str: String,
111 pub fields: BTreeMap<String, AnnotationValue>,
113}
114
115#[derive(Debug, Clone, Serialize, Deserialize)]
121pub struct Annotation {
122 pub kind: AnnotationKind,
123 pub name: Option<String>,
125 pub heading: Option<String>,
127 pub fields: BTreeMap<String, AnnotationValue>,
128 pub source: SourceLocation,
129 pub source_kind: IntentSourceKind,
130 pub conditional: bool,
132 pub raw_text: String,
134}
135
136pub fn parse_annotation_grammar(raw: &str) -> Result<RawAnnotation, G8Error> {
183 let s = raw.trim();
184
185 let s = s
188 .strip_prefix("@g8.")
189 .or_else(|| s.strip_prefix("@govern."))
190 .ok_or_else(|| G8Error::InvalidAnnotation(format!("expected '@g8.' prefix: {raw}")))?;
191
192 let paren_pos = s
194 .find('(')
195 .ok_or_else(|| G8Error::InvalidAnnotation(format!("expected '(' after kind in: {raw}")))?;
196 let kind_str = s[..paren_pos].trim().to_string();
197 if AnnotationKind::from_str(&kind_str).is_none() {
198 return Err(G8Error::InvalidAnnotation(format!(
199 "unknown annotation kind '{kind_str}'; expected one of: \
200 capability, intent, convergence_test, decision, plan"
201 )));
202 }
203
204 let args_part = &s[paren_pos + 1..];
206 let args_part = args_part.trim();
207 let args_part = args_part
208 .strip_suffix(')')
209 .ok_or_else(|| G8Error::InvalidAnnotation(format!("expected closing ')' in: {raw}")))?
210 .trim();
211
212 let fields = parse_args(args_part)
213 .map_err(|e| G8Error::InvalidAnnotation(format!("{e} (in: {raw})")))?;
214
215 Ok(RawAnnotation { kind_str, fields })
216}
217
218fn parse_args(s: &str) -> Result<BTreeMap<String, AnnotationValue>, String> {
220 let mut fields = BTreeMap::new();
221 if s.is_empty() {
222 return Ok(fields);
223 }
224
225 let mut cursor = s;
226 loop {
227 cursor = cursor.trim_start();
228 if cursor.is_empty() {
229 break;
230 }
231
232 let (ident, rest) = parse_ident(cursor)?;
234 let rest = rest.trim_start();
235
236 let rest = rest
238 .strip_prefix('=')
239 .ok_or_else(|| format!("expected '=' after key '{ident}'"))?
240 .trim_start();
241
242 let (value, rest) = parse_value(rest)?;
244 fields.insert(ident, value);
245
246 let rest = rest.trim_start();
247 if rest.is_empty() {
248 break;
249 }
250 let rest = rest
252 .strip_prefix(',')
253 .ok_or_else(|| format!("expected ',' or end of args, found: {rest}"))?;
254 cursor = rest;
255 }
256
257 Ok(fields)
258}
259
260fn parse_ident(s: &str) -> Result<(String, &str), String> {
261 let end = s
262 .find(|c: char| !c.is_alphanumeric() && c != '_')
263 .unwrap_or(s.len());
264 if end == 0 {
265 return Err(format!("expected identifier at: {s}"));
266 }
267 let ident = s[..end].to_string();
268 if !ident
269 .chars()
270 .next()
271 .map(|c| c.is_alphabetic() || c == '_')
272 .unwrap_or(false)
273 {
274 return Err(format!("identifier must start with letter or '_': {ident}"));
275 }
276 Ok((ident, &s[end..]))
277}
278
279fn parse_value(s: &str) -> Result<(AnnotationValue, &str), String> {
280 if s.starts_with('"') {
281 parse_string(s).map(|(v, r)| (AnnotationValue::String(v), r))
282 } else if s.starts_with('[') {
283 parse_list(s).map(|(v, r)| (AnnotationValue::List(v), r))
284 } else if s.starts_with("true")
285 && (s.len() == 4 || s[4..].starts_with(|c: char| !c.is_alphanumeric() && c != '_'))
286 {
287 Ok((AnnotationValue::Bool(true), &s[4..]))
288 } else if s.starts_with("false")
289 && (s.len() == 5 || s[5..].starts_with(|c: char| !c.is_alphanumeric() && c != '_'))
290 {
291 Ok((AnnotationValue::Bool(false), &s[5..]))
292 } else {
293 parse_int(s).map(|(v, r)| (AnnotationValue::Number(v), r))
294 }
295}
296
297fn parse_string(s: &str) -> Result<(String, &str), String> {
298 let s = s.strip_prefix('"').ok_or("expected opening '\"'")?;
300 let end = s.find('"').ok_or("unterminated string literal")?;
302 let value = s[..end].to_string();
303 Ok((value, &s[end + 1..]))
304}
305
306fn parse_list(s: &str) -> Result<(Vec<String>, &str), String> {
307 let s = s.strip_prefix('[').ok_or("expected '['")?;
308 let mut items = Vec::new();
309 let mut cursor = s.trim_start();
310
311 loop {
312 cursor = cursor.trim_start();
313 if let Some(rest) = cursor.strip_prefix(']') {
314 return Ok((items, rest));
315 }
316 if cursor.starts_with(',') {
317 cursor = &cursor[1..];
318 continue;
319 }
320 if cursor.is_empty() {
321 return Err("unterminated list: missing ']'".into());
322 }
323 let (item, rest) = parse_string(cursor)?;
324 items.push(item);
325 cursor = rest.trim_start();
326 }
327}
328
329fn parse_int(s: &str) -> Result<(i64, &str), String> {
330 let (neg, s) = if let Some(stripped) = s.strip_prefix('-') {
331 (true, stripped)
332 } else {
333 (false, s)
334 };
335 let end = s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len());
336 if end == 0 {
337 return Err(format!("expected integer value at: {s}"));
338 }
339 let n: i64 = s[..end]
340 .parse()
341 .map_err(|e| format!("integer parse error: {e}"))?;
342 Ok((if neg { -n } else { n }, &s[end..]))
343}
344
345#[cfg(test)]
348mod tests {
349 use super::*;
350
351 #[test]
352 fn parse_simple_capability() {
353 let r = parse_annotation_grammar(
354 r#"@g8.capability(name = "http-fetch", status = "in_flight")"#,
355 )
356 .unwrap();
357 assert_eq!(r.kind_str, "capability");
358 assert!(
359 matches!(r.fields.get("name"), Some(AnnotationValue::String(s)) if s == "http-fetch")
360 );
361 assert!(
362 matches!(r.fields.get("status"), Some(AnnotationValue::String(s)) if s == "in_flight")
363 );
364 }
365
366 #[test]
367 fn parse_list_values() {
368 let r = parse_annotation_grammar(
369 r#"@g8.capability(name = "x", consumes = ["A", "B"], produces = ["C"])"#,
370 )
371 .unwrap();
372 assert!(matches!(
373 r.fields.get("consumes"),
374 Some(AnnotationValue::List(v)) if v == &["A", "B"]
375 ));
376 assert!(matches!(
377 r.fields.get("produces"),
378 Some(AnnotationValue::List(v)) if v == &["C"]
379 ));
380 }
381
382 #[test]
383 fn parse_bool_and_int() {
384 let r =
385 parse_annotation_grammar(r#"@g8.capability(name = "y", stub = true, wip_weight = 2)"#)
386 .unwrap();
387 assert!(matches!(
388 r.fields.get("stub"),
389 Some(AnnotationValue::Bool(true))
390 ));
391 assert!(matches!(
392 r.fields.get("wip_weight"),
393 Some(AnnotationValue::Number(2))
394 ));
395 }
396
397 #[test]
398 fn parse_empty_args() {
399 let r = parse_annotation_grammar("@g8.intent()").unwrap();
400 assert_eq!(r.kind_str, "intent");
401 assert!(r.fields.is_empty());
402 }
403
404 #[test]
405 fn parse_unknown_kind_errors() {
406 assert!(parse_annotation_grammar("@g8.unknown(name = \"x\")").is_err());
407 }
408
409 #[test]
410 fn parse_missing_prefix_errors() {
411 assert!(parse_annotation_grammar("capability(name = \"x\")").is_err());
412 }
413
414 #[test]
415 fn serde_roundtrip() {
416 let r =
417 parse_annotation_grammar(r#"@g8.plan(title = "streaming-export", status = "Idea")"#)
418 .unwrap();
419 let json = serde_json::to_string(&r).unwrap();
420 let back: RawAnnotation = serde_json::from_str(&json).unwrap();
421 assert_eq!(back.kind_str, "plan");
422 assert_eq!(back.fields.get("title"), r.fields.get("title"));
423 }
424
425 #[test]
426 fn parse_decision_kind() {
427 let r = parse_annotation_grammar(
428 r#"@g8.decision(title = "Use rusqlite", status = "accepted")"#,
429 )
430 .unwrap();
431 assert_eq!(r.kind_str, "decision");
432 }
433
434 #[test]
435 fn parse_convergence_test() {
436 let r = parse_annotation_grammar(
437 r#"@g8.convergence_test(for_capability = "http-fetch", scenario = "timeout")"#,
438 )
439 .unwrap();
440 assert_eq!(r.kind_str, "convergence_test");
441 assert!(r.fields.contains_key("for_capability"));
442 }
443
444 #[test]
445 fn parse_negative_int() {
446 let r = parse_annotation_grammar(r#"@g8.capability(name = "x", wip_weight = -1)"#).unwrap();
447 assert!(matches!(
448 r.fields.get("wip_weight"),
449 Some(AnnotationValue::Number(-1))
450 ));
451 }
452
453 #[test]
454 fn parse_empty_list() {
455 let r = parse_annotation_grammar(r#"@g8.capability(name = "x", consumes = [])"#).unwrap();
456 assert!(matches!(
457 r.fields.get("consumes"),
458 Some(AnnotationValue::List(v)) if v.is_empty()
459 ));
460 }
461}