Debian Codegraph @

helix-core/src/snippets/elaborate.rs

raw symbols SCIP
1 use std::mem::swap;
2 use std::ops::Index;
3 use std::sync::Arc;
4
5 use anyhow::{anyhow, Result};
6 use helix_stdx::rope::RopeSliceExt;
7 use helix_stdx::Range;
8 use regex_cursor::engines::meta::Builder as RegexBuilder;
9 use regex_cursor::engines::meta::Regex;
10 use regex_cursor::regex_automata::util::syntax::Config as RegexConfig;
11 use ropey::RopeSlice;
12
13 use crate::case_conversion::to_lower_case_with;
14 use crate::case_conversion::to_upper_case_with;
15 use crate::case_conversion::{to_camel_case_with, to_pascal_case_with};
16 use crate::snippets::parser::{self, CaseChange, FormatItem};
17 use crate::snippets::{TabstopIdx, LAST_TABSTOP_IDX};
18 use crate::Tendril;
19
20 #[derive(Debug)]
21 pub struct Snippet {
22 elements: Vec<SnippetElement>,
23 tabstops: Vec<Tabstop>,
24 }
25
26 impl Snippet {
27 pub fn parse(snippet: &str) -> Result<Self> {
28 let parsed_snippet = parser::parse(snippet)
29 .map_err(|rest| anyhow!("Failed to parse snippet. Remaining input: {}", rest))?;
30 Ok(Snippet::new(parsed_snippet))
31 }
32
33 pub fn new(elements: Vec<parser::SnippetElement>) -> Snippet {
34 let mut res = Snippet {
35 elements: Vec::new(),
36 tabstops: Vec::new(),
37 };
38 res.elements = res.elaborate(elements, None).into();
39 res.fixup_tabstops();
40 res.ensure_last_tabstop();
41 res.renumber_tabstops();
42 res
43 }
44
45 pub fn elements(&self) -> &[SnippetElement] {
46 &self.elements
47 }
48
49 pub fn tabstops(&self) -> impl Iterator<Item = &Tabstop> {
50 self.tabstops.iter()
51 }
52
53 fn renumber_tabstops(&mut self) {
54 Self::renumber_tabstops_in(&self.tabstops, &mut self.elements);
55 for i in 0..self.tabstops.len() {
56 if let Some(parent) = self.tabstops[i].parent {
57 let parent = self
58 .tabstops
59 .binary_search_by_key(&parent, |tabstop| tabstop.idx)
60 .expect("all tabstops have been resolved");
61 self.tabstops[i].parent = Some(TabstopIdx(parent));
62 }
63 let tabstop = &mut self.tabstops[i];
64 if let TabstopKind::Placeholder { default } = &tabstop.kind {
65 let mut default = default.clone();
66 tabstop.kind = TabstopKind::Empty;
67 Self::renumber_tabstops_in(&self.tabstops, Arc::get_mut(&mut default).unwrap());
68 self.tabstops[i].kind = TabstopKind::Placeholder { default };
69 }
70 }
71 }
72
73 fn renumber_tabstops_in(tabstops: &[Tabstop], elements: &mut [SnippetElement]) {
74 for elem in elements {
75 match elem {
76 SnippetElement::Tabstop { idx } => {
77 idx.0 = tabstops
78 .binary_search_by_key(&*idx, |tabstop| tabstop.idx)
79 .expect("all tabstops have been resolved")
80 }
81 SnippetElement::Variable { default, .. } => {
82 if let Some(default) = default {
83 Self::renumber_tabstops_in(tabstops, default);
84 }
85 }
86 SnippetElement::Text(_) => (),
87 }
88 }
89 }
90
91 fn fixup_tabstops(&mut self) {
92 self.tabstops.sort_by_key(|tabstop| tabstop.idx);
93 self.tabstops.dedup_by(|tabstop1, tabstop2| {
94 if tabstop1.idx != tabstop2.idx {
95 return false;
96 }
97 // use the first non empty tabstop for all multicursor tabstops
98 if tabstop2.kind.is_empty() {
99 swap(tabstop2, tabstop1)
100 }
101 true
102 })
103 }
104
105 fn ensure_last_tabstop(&mut self) {
106 if matches!(self.tabstops.last(), Some(tabstop) if tabstop.idx == LAST_TABSTOP_IDX) {
107 return;
108 }
109 self.tabstops.push(Tabstop {
110 idx: LAST_TABSTOP_IDX,
111 parent: None,
112 kind: TabstopKind::Empty,
113 });
114 self.elements.push(SnippetElement::Tabstop {
115 idx: LAST_TABSTOP_IDX,
116 })
117 }
118
119 fn elaborate(
120 &mut self,
121 default: Vec<parser::SnippetElement>,
122 parent: Option<TabstopIdx>,
123 ) -> Box<[SnippetElement]> {
124 default
125 .into_iter()
126 .map(|val| match val {
127 parser::SnippetElement::Tabstop {
128 tabstop,
129 transform: None,
130 } => SnippetElement::Tabstop {
131 idx: self.elaborate_placeholder(tabstop, parent, Vec::new()),
132 },
133 parser::SnippetElement::Tabstop {
134 tabstop,
135 transform: Some(transform),
136 } => SnippetElement::Tabstop {
137 idx: self.elaborate_transform(tabstop, parent, transform),
138 },
139 parser::SnippetElement::Placeholder { tabstop, value } => SnippetElement::Tabstop {
140 idx: self.elaborate_placeholder(tabstop, parent, value),
141 },
142 parser::SnippetElement::Choice { tabstop, choices } => SnippetElement::Tabstop {
143 idx: self.elaborate_choice(tabstop, parent, choices),
144 },
145 parser::SnippetElement::Variable {
146 name,
147 default,
148 transform,
149 } => SnippetElement::Variable {
150 name,
151 default: default.map(|default| self.elaborate(default, parent)),
152 // TODO: error for invalid transforms
153 transform: transform.and_then(Transform::new).map(Box::new),
154 },
155 parser::SnippetElement::Text(text) => SnippetElement::Text(text),
156 })
157 .collect()
158 }
159
160 fn elaborate_choice(
161 &mut self,
162 idx: usize,
163 parent: Option<TabstopIdx>,
164 choices: Vec<Tendril>,
165 ) -> TabstopIdx {
166 let idx = TabstopIdx::elaborate(idx);
167 self.tabstops.push(Tabstop {
168 idx,
169 parent,
170 kind: TabstopKind::Choice {
171 choices: choices.into(),
172 },
173 });
174 idx
175 }
176
177 fn elaborate_placeholder(
178 &mut self,
179 idx: usize,
180 parent: Option<TabstopIdx>,
181 mut default: Vec<parser::SnippetElement>,
182 ) -> TabstopIdx {
183 let idx = TabstopIdx::elaborate(idx);
184 if idx == LAST_TABSTOP_IDX && !default.is_empty() {
185 // Older versions of clangd for example may send a snippet like `${0:placeholder}`
186 // which is considered by VSCode to be a misuse of the `$0` tabstop.
187 log::warn!("Discarding placeholder text for the `$0` tabstop ({default:?}). \
188 The `$0` tabstop signifies the final cursor position and should not include placeholder text.");
189 default.clear();
190 }
191 let default = self.elaborate(default, Some(idx));
192 self.tabstops.push(Tabstop {
193 idx,
194 parent,
195 kind: TabstopKind::Placeholder {
196 default: default.into(),
197 },
198 });
199 idx
200 }
201
202 fn elaborate_transform(
203 &mut self,
204 idx: usize,
205 parent: Option<TabstopIdx>,
206 transform: parser::Transform,
207 ) -> TabstopIdx {
208 let idx = TabstopIdx::elaborate(idx);
209 if let Some(transform) = Transform::new(transform) {
210 self.tabstops.push(Tabstop {
211 idx,
212 parent,
213 kind: TabstopKind::Transform(Arc::new(transform)),
214 })
215 } else {
216 // TODO: proper error
217 self.tabstops.push(Tabstop {
218 idx,
219 parent,
220 kind: TabstopKind::Empty,
221 })
222 }
223 idx
224 }
225 }
226
227 impl Index<TabstopIdx> for Snippet {
228 type Output = Tabstop;
229 fn index(&self, index: TabstopIdx) -> &Tabstop {
230 &self.tabstops[index.0]
231 }
232 }
233
234 #[derive(Debug)]
235 pub enum SnippetElement {
236 Tabstop {
237 idx: TabstopIdx,
238 },
239 Variable {
240 name: Tendril,
241 default: Option<Box<[SnippetElement]>>,
242 transform: Option<Box<Transform>>,
243 },
244 Text(Tendril),
245 }
246
247 #[derive(Debug)]
248 pub struct Tabstop {
249 idx: TabstopIdx,
250 pub parent: Option<TabstopIdx>,
251 pub kind: TabstopKind,
252 }
253
254 #[derive(Debug)]
255 pub enum TabstopKind {
256 Choice { choices: Arc<[Tendril]> },
257 Placeholder { default: Arc<[SnippetElement]> },
258 Empty,
259 Transform(Arc<Transform>),
260 }
261
262 impl TabstopKind {
263 pub fn is_empty(&self) -> bool {
264 matches!(self, TabstopKind::Empty)
265 }
266 }
267
268 #[derive(Debug)]
269 pub struct Transform {
270 regex: Regex,
271 regex_str: Box<str>,
272 global: bool,
273 replacement: Box<[FormatItem]>,
274 }
275
276 impl PartialEq for Transform {
277 fn eq(&self, other: &Self) -> bool {
278 self.replacement == other.replacement
279 && self.global == other.global
280 // doens't compare m and i setting but close enough
281 && self.regex_str == other.regex_str
282 }
283 }
284
285 impl Transform {
286 fn new(transform: parser::Transform) -> Option<Transform> {
287 let mut config = RegexConfig::new();
288 let mut global = false;
289 let mut invalid_config = false;
290 for c in transform.options.chars() {
291 match c {
292 'i' => {
293 config = config.case_insensitive(true);
294 }
295 'm' => {
296 config = config.multi_line(true);
297 }
298 'g' => {
299 global = true;
300 }
301 // we ignore 'u' since we always want to
302 // do unicode aware matching
303 _ => invalid_config = true,
304 }
305 }
306 if invalid_config {
307 log::error!("invalid transform configuration characters {transform:?}");
308 }
309 let regex = match RegexBuilder::new().syntax(config).build(&transform.regex) {
310 Ok(regex) => regex,
311 Err(err) => {
312 log::error!("invalid transform {err} {transform:?}");
313 return None;
314 }
315 };
316 Some(Transform {
317 regex,
318 regex_str: transform.regex.as_str().into(),
319 global,
320 replacement: transform.replacement.into(),
321 })
322 }
323
324 pub fn apply(&self, mut doc: RopeSlice<'_>, range: Range) -> Tendril {
325 let mut buf = Tendril::new();
326 let it = self.regex.captures_iter(doc.regex_input_at(range));
327 doc = doc.slice(range);
328 let mut last_match = 0;
329 for cap in it {
330 // unwrap on 0 is OK because captures only reports matches
331 let m = cap.get_group(0).unwrap();
332 buf.extend(doc.byte_slice(last_match..m.start).chunks());
333 last_match = m.end;
334 for fmt in &*self.replacement {
335 match *fmt {
336 FormatItem::Text(ref text) => {
337 buf.push_str(text);
338 }
339 FormatItem::Capture(i) => {
340 if let Some(cap) = cap.get_group(i) {
341 buf.extend(doc.byte_slice(cap.range()).chunks());
342 }
343 }
344 FormatItem::CaseChange(i, change) => {
345 if let Some(cap) = cap.get_group(i).filter(|i| !i.is_empty()) {
346 let mut chars = doc.byte_slice(cap.range()).chars();
347 match change {
348 CaseChange::Upcase => to_upper_case_with(chars, &mut buf),
349 CaseChange::Downcase => to_lower_case_with(chars, &mut buf),
350 CaseChange::Capitalize => {
351 let first_char = chars.next().unwrap();
352 buf.extend(first_char.to_uppercase());
353 buf.extend(chars);
354 }
355 CaseChange::PascalCase => to_pascal_case_with(chars, &mut buf),
356 CaseChange::CamelCase => to_camel_case_with(chars, &mut buf),
357 }
358 }
359 }
360 FormatItem::Conditional(i, ref if_, ref else_) => {
361 if cap.get_group(i).is_none_or(|mat| mat.is_empty()) {
362 buf.push_str(else_)
363 } else {
364 buf.push_str(if_)
365 }
366 }
367 }
368 }
369 if !self.global {
370 break;
371 }
372 }
373 buf.extend(doc.byte_slice(last_match..).chunks());
374 buf
375 }
376 }
377
378 impl TabstopIdx {
379 fn elaborate(idx: usize) -> Self {
380 TabstopIdx(idx.wrapping_sub(1))
381 }
382 }