1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
//! Parser for annotations within an Aquascope code block body.

use std::{collections::HashMap, hash::Hash};

use anyhow::Result;
use itertools::Itertools;
use regex::Regex;
use serde::Serialize;
use ts_rs::TS;

#[derive(PartialEq, Eq, Debug, TS, Serialize, Clone, Copy)]
#[ts(export)]
pub struct MdCharPos(usize);

#[derive(PartialEq, Eq, Debug, TS, Serialize, Hash, Clone, Copy)]
#[ts(export)]
pub struct MdLinePos(usize);

#[derive(PartialEq, Eq, Debug, TS, Serialize, Clone)]
#[ts(export)]
#[serde(tag = "type", content = "value")]
pub enum PathMatcher {
  Literal(String),
  Regex(String),
}

#[derive(PartialEq, Eq, Debug, TS, Serialize, Default, Clone)]
#[ts(export)]
pub struct StepperAnnotations {
  focused_lines: Vec<MdLinePos>,
  focused_paths: HashMap<MdLinePos, Vec<PathMatcher>>,
}

#[derive(PartialEq, Eq, Debug, TS, Serialize, Default, Clone)]
#[ts(export)]
pub struct BoundariesAnnotations {
  focused_lines: Vec<MdLinePos>,
}

#[derive(PartialEq, Eq, Debug, TS, Serialize, Default, Clone)]
#[ts(export)]
pub struct InterpAnnotations {
  state_locations: Vec<MdCharPos>,
}

#[derive(PartialEq, Eq, Debug, Default, TS, Serialize, Clone)]
#[ts(export)]
pub struct AquascopeAnnotations {
  hidden_lines: Vec<MdLinePos>,
  interp: InterpAnnotations,
  stepper: StepperAnnotations,
  boundaries: BoundariesAnnotations,
}

#[allow(clippy::derived_hash_with_manual_eq)]
impl Hash for AquascopeAnnotations {
  fn hash<H: std::hash::Hasher>(&self, _state: &mut H) {
    // HashMaps aren't hashable, and we can ignore annotations when hashing
    // anyway since they don't change the result of an aquascope computation.
  }
}

pub fn parse_annotations(code: &str) -> Result<(String, AquascopeAnnotations)> {
  let marker_interp = ("`[", "]`", "interp");
  let marker_stepper = ("`(", ")`", "stepper");
  let marker_boundaries = ("`{", "}`", "boundaries");

  let pattern = Itertools::intersperse(
    [marker_interp, marker_stepper, marker_boundaries]
      .into_iter()
      .map(|(open, close, name)| {
        format!(
          "{}(?P<{name}>[^{}]*){}",
          regex::escape(open),
          regex::escape(&close[.. 1]),
          regex::escape(close)
        )
      }),
    "|".into(),
  )
  .collect::<String>();
  let re = Regex::new(&pattern)?;

  let mut annots = AquascopeAnnotations::default();
  let mut idx = 0;
  let mut output_lines = Vec::new();
  for (line_idx, mut line) in code.lines().enumerate() {
    let line_pos = MdLinePos(line_idx + 1);
    let mut fragments = Vec::new();
    macro_rules! add_fragment {
      ($s:expr) => {
        fragments.push($s);
        idx += $s.len();
      };
    }
    if let Some(suffix) = line.strip_prefix('#') {
      annots.hidden_lines.push(line_pos);
      add_fragment!(suffix);
    } else if let Some(suffix) = line.strip_prefix("\\#") {
      add_fragment!("#");
      add_fragment!(suffix);
    } else {
      while let Some(cap) = re.captures(line) {
        let matched = cap.get(0).unwrap();
        add_fragment!(&line[0 .. matched.start()]);

        let match_str = matched.as_str();
        let match_type = if match_str.starts_with(marker_interp.0) {
          "interp"
        } else if match_str.starts_with(marker_stepper.0) {
          "stepper"
        } else {
          "boundaries"
        };

        let interior = cap.name(match_type).unwrap();
        let mut config = HashMap::new();
        for s in interior.as_str().split(',').filter(|s| *s != "") {
          match s.split_once(':') {
            Some((s1, s2)) => config.insert(s1, s2),
            None => config.insert(s, ""),
          };
        }

        match match_type {
          "interp" => annots.interp.state_locations.push(MdCharPos(idx)),
          "stepper" => {
            if config.contains_key("focus") {
              annots.stepper.focused_lines.push(line_pos);
            }
            let mut add_matcher = |matcher: PathMatcher| {
              annots
                .stepper
                .focused_paths
                .entry(line_pos)
                .or_default()
                .push(matcher)
            };
            if let Some(paths) = config.get("paths") {
              add_matcher(PathMatcher::Literal(paths.to_string()));
            }
            if let Some(rpaths) = config.get("rxpaths") {
              add_matcher(PathMatcher::Regex(rpaths.to_string()));
            }
          }
          "boundaries" => {
            annots.boundaries.focused_lines.push(line_pos);
          }
          _ => unreachable!(),
        }

        line = &line[matched.end() ..];
      }
      add_fragment!(line);
    }
    idx += 1; // for \n
    output_lines.push(fragments);
  }

  let output = Itertools::intersperse(output_lines.into_iter(), vec!["\n"])
    .flatten()
    .collect::<String>();
  Ok((output, annots))
}

#[test]
fn test_parse_annotations() {
  let input = r#"#fn main() {
let x = 1;`(focus,paths:x,rxpaths:y)`
`[]`let y = 2;`{}`
#}"#;
  let (cleaned, annot) = parse_annotations(input).unwrap();
  assert_eq!(
    cleaned,
    r#"fn main() {
let x = 1;
let y = 2;
}"#
  );
  assert_eq!(annot, AquascopeAnnotations {
    hidden_lines: vec![MdLinePos(1), MdLinePos(4)],
    interp: InterpAnnotations {
      state_locations: vec![MdCharPos(23)],
    },
    stepper: StepperAnnotations {
      focused_lines: vec![MdLinePos(2)],
      focused_paths: maplit::hashmap! {
        MdLinePos(2) => vec![PathMatcher::Literal("x".into()), PathMatcher::Regex("y".into())]
      }
    },
    boundaries: BoundariesAnnotations {
      focused_lines: vec![MdLinePos(3)]
    }
  });
}