Skip to main content

g8_core/
annotation.rs

1//! Annotation types and the magic-comment grammar parser.
2//!
3//! `Annotation` is the *transient* output of `g8-extractor`.  It is never
4//! stored directly; the store converts it to `Capability`, `Intent`, `Plan`,
5//! or `Decision` rows.
6//!
7//! The parser is a hand-rolled scanner (no pest/nom) per ARCHITECTURE.md §6.
8
9use std::collections::BTreeMap;
10use std::path::PathBuf;
11
12use serde::{Deserialize, Serialize};
13
14use crate::error::G8Error;
15use crate::model::IntentSourceKind;
16
17// ── SourceLocation ───────────────────────────────────────────────────────────
18
19/// Points to the location in source where an annotation was found.
20///
21/// Column is 0-based; line is 1-based (matching most editors).
22#[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    /// Construct a synthetic `SourceLocation` with zero line/column for cases
31    /// where no position is available (e.g. Markdown-section annotations).
32    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// ── AnnotationKind ───────────────────────────────────────────────────────────
42
43/// Discriminant for the five annotation kinds defined in SPEC Decision 2.
44///
45/// # Examples
46///
47/// ```
48/// use g8_core::AnnotationKind;
49///
50/// let kind = AnnotationKind::Capability;
51/// assert!(matches!(kind, AnnotationKind::Capability));
52/// let json = serde_json::to_string(&kind).unwrap();
53/// assert_eq!(json, r#""capability""#);
54/// ```
55#[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// ── AnnotationValue ──────────────────────────────────────────────────────────
79
80/// A typed value in an annotation field (string, bool, integer, or list).
81///
82/// # Examples
83///
84/// ```
85/// use g8_core::AnnotationValue;
86///
87/// let v = AnnotationValue::String("in_flight".into());
88/// assert!(matches!(v, AnnotationValue::String(_)));
89/// let list = AnnotationValue::List(vec!["A".into(), "B".into()]);
90/// assert!(matches!(list, AnnotationValue::List(_)));
91/// ```
92#[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// ── RawAnnotation ────────────────────────────────────────────────────────────
102
103/// Output of `parse_annotation_grammar`.
104///
105/// Contains the kind discriminant as a raw string (so callers can pattern-match
106/// without importing the enum) plus the parsed field map.
107#[derive(Debug, Clone, Serialize, Deserialize)]
108pub struct RawAnnotation {
109    /// Raw kind string: `"capability"`, `"intent"`, etc.
110    pub kind_str: String,
111    /// Parsed fields in stable BTreeMap order.
112    pub fields: BTreeMap<String, AnnotationValue>,
113}
114
115// ── Annotation ───────────────────────────────────────────────────────────────
116
117/// A typed annotation record produced by `g8-extractor`.
118///
119/// This is a transient extractor output, never stored directly.
120#[derive(Debug, Clone, Serialize, Deserialize)]
121pub struct Annotation {
122    pub kind: AnnotationKind,
123    /// Present for `Capability` and `Plan` kinds (from the `name` field).
124    pub name: Option<String>,
125    /// Present for `Intent` kind (section heading).
126    pub heading: Option<String>,
127    pub fields: BTreeMap<String, AnnotationValue>,
128    pub source: SourceLocation,
129    pub source_kind: IntentSourceKind,
130    /// Set when extractor flagged `dev_only=true`, `cfg_attr`, or `tests/` dir.
131    pub conditional: bool,
132    /// The raw annotation text (stripped of `//` prefixes, whitespace-normalised).
133    pub raw_text: String,
134}
135
136// ── Parser ───────────────────────────────────────────────────────────────────
137
138/// Parse the magic-comment annotation grammar.
139///
140/// Accepts the form `@g8.<kind>(key = "value", ...)` with the `@g8.` prefix
141/// present. The caller strips `//` or `#` comment prefixes and concatenates
142/// multi-line forms before calling this function.
143///
144/// Grammar (ARCHITECTURE.md §6.1):
145/// ```text
146/// annotation := "@g8." kind "(" args ")"
147/// kind       := "capability" | "intent" | "convergence_test" | "decision" | "plan"
148/// args       := arg ("," arg)*  | ε
149/// arg        := ident "=" value
150/// ident      := [a-zA-Z_][a-zA-Z0-9_]*
151/// value      := string | bool | int | list
152/// string     := '"' [^"]* '"'
153/// bool       := "true" | "false"
154/// int        := -?[0-9]+
155/// list       := "[" string ("," string)* "]"
156/// ```
157///
158/// # Examples
159///
160/// Single-line form (the common case in v0.1):
161///
162/// ```
163/// use g8_core::parse_annotation_grammar;
164/// use g8_core::AnnotationValue;
165///
166/// let raw = r#"@g8.capability(name = "http-fetch", status = "in_flight", substrate = "network")"#;
167/// let ann = parse_annotation_grammar(raw).unwrap();
168/// assert_eq!(ann.kind_str, "capability");
169/// assert_eq!(
170///     ann.fields.get("name"),
171///     Some(&AnnotationValue::String("http-fetch".into()))
172/// );
173/// assert_eq!(
174///     ann.fields.get("status"),
175///     Some(&AnnotationValue::String("in_flight".into()))
176/// );
177/// ```
178///
179/// # Errors
180///
181/// Returns [`G8Error::InvalidAnnotation`] if the input does not match the grammar.
182pub fn parse_annotation_grammar(raw: &str) -> Result<RawAnnotation, G8Error> {
183    let s = raw.trim();
184
185    // Strip the `@g8.` prefix. `@govern.` is the pre-rename spelling and is
186    // still accepted so annotated code does not need a sweep.
187    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    // Parse kind up to the opening paren
193    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    // Strip closing paren
205    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
218/// Parse the argument list `key = value, key = value, ...`
219fn 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        // Parse ident
233        let (ident, rest) = parse_ident(cursor)?;
234        let rest = rest.trim_start();
235
236        // Expect '='
237        let rest = rest
238            .strip_prefix('=')
239            .ok_or_else(|| format!("expected '=' after key '{ident}'"))?
240            .trim_start();
241
242        // Parse value
243        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        // Expect optional comma
251        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    // Must start with '"'
299    let s = s.strip_prefix('"').ok_or("expected opening '\"'")?;
300    // Find closing quote (no escape handling needed per grammar: `[^"]*`)
301    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// ── Tests ────────────────────────────────────────────────────────────────────
346
347#[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}