forked from nix-community/nixpkgs-fmt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dsl.rs
409 lines (380 loc) · 13 KB
/
dsl.rs
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
//! This module contains a definition of pattern-based formatting DSL.
use std::fmt;
use rnix::SyntaxElement;
use crate::{
pattern::Pattern,
tree_utils::{next_non_whitespace_sibling, prev_non_whitespace_sibling},
};
/// `SpacingRule` describes whitespace requirements between `SyntaxElement` Note
/// that it doesn't handle indentation (first whitespace on a line), there's
/// `IndentRule` for that!
#[derive(Debug)]
pub(crate) struct SpacingRule {
pub(crate) name: Option<RuleName>,
/// An element to which this spacing rule applies
pub(crate) pattern: Pattern,
/// How much space to add/remove at the start or end of the element.
pub(crate) space: Space,
}
/// Make `SpacingRule` usable with `PatternSet`
impl AsRef<Pattern> for SpacingRule {
fn as_ref(&self) -> &Pattern {
&self.pattern
}
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct Space {
/// How much space to add.
pub(crate) value: SpaceValue,
/// Should the space be added before, after or around the element?
pub(crate) loc: SpaceLoc,
}
#[derive(Debug, Clone, Copy)]
pub(crate) enum SpaceValue {
/// Single whitespace char, like ` `
Single,
/// Single whitespace char, like ` `, but preserve existing line break.
SingleOptionalNewline,
/// A single newline (`\n`) char
Newline,
/// No whitespace at all.
None,
/// No space, but preserve existing line break.
NoneOptionalNewline,
/// If the parent element fits into a single line, a single space.
/// Otherwise, at least one newline.
/// Existing newlines are preserved.
SingleOrNewline,
/// If the parent element fits into a single line, no space.
/// Otherwise, at least one newline.
/// Existing newlines are preserved.
NoneOrNewline,
}
#[derive(Debug, Clone, Copy)]
pub(crate) enum SpaceLoc {
/// Before the element.
Before,
/// After the element.
After,
/// On the both sides of the element.
Around,
}
/// A builder to conveniently specify a set of `SpacingRule`s
#[derive(Debug, Default)]
pub(crate) struct SpacingDsl {
pub(crate) rules: Vec<SpacingRule>,
#[cfg(test)]
pub(crate) tests: Vec<(&'static str, &'static str)>,
}
impl SpacingDsl {
/// Add a single rule.
///
/// This is a low-level method for special cases, common cases are handled
/// by a more convenient `SpacingRuleBuilder`.
pub(crate) fn add_rule(&mut self, rule: SpacingRule) -> &mut SpacingDsl {
self.rules.push(rule);
self
}
/// Add a new rule with the given `name`.
pub(crate) fn rule(&mut self, name: &'static str) -> SpacingRuleBuilder<'_> {
SpacingRuleBuilder {
dsl: self,
rule_name: Some(name),
parent: None,
child: None,
between: None,
loc: None,
}
}
/// Specify an anonymous spacing rule for an element which is a child of `parent`.
pub(crate) fn inside(&mut self, parent: impl Into<Pattern>) -> SpacingRuleBuilder<'_> {
SpacingRuleBuilder {
dsl: self,
rule_name: None,
parent: None,
child: None,
between: None,
loc: None,
}
.inside(parent)
}
pub(crate) fn test(&mut self, before: &'static str, after: &'static str) -> &mut SpacingDsl {
#[cfg(test)]
{
self.tests.push((before, after));
}
let _ = (before, after);
self
}
}
/// A builder to conveniently specify a single rule.
pub(crate) struct SpacingRuleBuilder<'a> {
dsl: &'a mut SpacingDsl,
rule_name: Option<&'static str>,
parent: Option<Pattern>,
child: Option<Pattern>,
between: Option<(Pattern, Pattern)>,
loc: Option<SpaceLoc>,
}
impl<'a> SpacingRuleBuilder<'a> {
/// The rule applies to direct children of the `parent` element.
pub(crate) fn inside(mut self, parent: impl Into<Pattern>) -> SpacingRuleBuilder<'a> {
self.parent = Some(parent.into());
self
}
/// The rule applies to both sides of the element `child`.
pub(crate) fn around(mut self, child: impl Into<Pattern>) -> SpacingRuleBuilder<'a> {
self.child = Some(child.into());
self.loc = Some(SpaceLoc::Around);
self
}
/// The rule applies to the leading whitespace before `child`.
pub(crate) fn before(mut self, child: impl Into<Pattern>) -> SpacingRuleBuilder<'a> {
self.child = Some(child.into());
self.loc = Some(SpaceLoc::Before);
self
}
/// The rule applies to the trailing whitespace after `child`.
pub(crate) fn after(mut self, child: impl Into<Pattern>) -> SpacingRuleBuilder<'a> {
self.child = Some(child.into());
self.loc = Some(SpaceLoc::After);
self
}
/// The rule applies to the whitespace between the two nodes.
pub(crate) fn between(
mut self,
left: impl Into<Pattern>,
right: impl Into<Pattern>,
) -> SpacingRuleBuilder<'a> {
self.between = Some((left.into(), right.into()));
self.loc = Some(SpaceLoc::After);
self
}
/// The rule applies if the `cond` is true.
pub(crate) fn when(mut self, cond: fn(&SyntaxElement) -> bool) -> SpacingRuleBuilder<'a> {
let pred = cond.into();
let prev = self.child.take().unwrap();
self.child = Some(prev & pred);
self
}
/// Enforce single whitespace character.
pub(crate) fn single_space(self) -> &'a mut SpacingDsl {
self.finish(SpaceValue::Single)
}
pub(crate) fn single_space_or_optional_newline(self) -> &'a mut SpacingDsl {
self.finish(SpaceValue::SingleOptionalNewline)
}
pub(crate) fn no_space_or_optional_newline(self) -> &'a mut SpacingDsl {
self.finish(SpaceValue::NoneOptionalNewline)
}
/// Enforce the absence of any space.
pub(crate) fn no_space(self) -> &'a mut SpacingDsl {
self.finish(SpaceValue::None)
}
/// Enforce a single whitespace or newline character.
pub(crate) fn single_space_or_newline(self) -> &'a mut SpacingDsl {
self.finish(SpaceValue::SingleOrNewline)
}
/// Enforce a absence of whitespace or a newline character.
pub(crate) fn no_space_or_newline(self) -> &'a mut SpacingDsl {
self.finish(SpaceValue::NoneOrNewline)
}
/// Enforce a newline
pub(crate) fn newline(self) -> &'a mut SpacingDsl {
self.finish(SpaceValue::Newline)
}
fn finish(self, value: SpaceValue) -> &'a mut SpacingDsl {
assert!(self.between.is_some() ^ self.child.is_some());
let parent = self.parent.expect("parent must be set for each rule");
if let Some((left, right)) = self.between {
let child = {
let left = left.clone();
let right = right.clone();
left & Pattern::from(move |it: &SyntaxElement| {
next_non_whitespace_sibling(it).map(|it| right.matches(&it)) == Some(true)
})
};
let rule = SpacingRule {
name: self.rule_name.map(RuleName),
pattern: child.with_parent(parent.clone()),
space: Space { value, loc: SpaceLoc::After },
};
self.dsl.add_rule(rule);
let child = right
& Pattern::from(move |it: &SyntaxElement| {
prev_non_whitespace_sibling(it).map(|it| left.matches(&it)) == Some(true)
});
let rule = SpacingRule {
name: self.rule_name.map(RuleName),
pattern: child.with_parent(parent),
space: Space { value, loc: SpaceLoc::Before },
};
self.dsl.add_rule(rule);
} else {
let rule = SpacingRule {
name: self.rule_name.map(RuleName),
pattern: self.child.unwrap().with_parent(parent),
space: Space { value, loc: self.loc.unwrap() },
};
self.dsl.add_rule(rule);
}
self.dsl
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Modality {
Positive,
Negative,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum IndentValue {
Indent,
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct RuleName(&'static str);
impl fmt::Display for RuleName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
impl RuleName {
pub(crate) fn new(name: &'static str) -> RuleName {
assert!(name.chars().next().unwrap().is_uppercase(), "rule names should be capitalized");
assert!(!name.ends_with('.'), "rule names should not end in `.`");
RuleName(name)
}
}
/// `IndentRule` describes how an element should be indented.
///
/// `IndentRule`s are only effective for elements which begin the line.
///
/// Note that currently we support only two kinds of indentation:
/// * the same, as parent (default)
/// * indent relative to the parent.
///
/// For this reason, `indent_value` is mostly unused.
#[derive(Debug)]
pub(crate) struct IndentRule {
pub(crate) name: RuleName,
pub(crate) parent: Pattern,
/// Depending on `child_modality`, this pattern selects/discards elements
pub(crate) child: Option<Pattern>,
pub(crate) child_modality: Modality,
/// Pattern that should match the anchoring element, relative to which we
/// calculate the indent
///
/// in
///
/// ```nix
/// {
/// f = x:
/// x * 2
/// ;
/// }
/// ```
///
/// when we indent lambda body, `x * 2` is the thing to which the `pattern`
/// applies and `f = x ...` is the thing to which the `anchor_pattern`
/// applies.
pub(crate) anchor_pattern: Option<Pattern>,
pub(crate) indent_value: IndentValue,
}
/// A builder to conveniently specify a set of `IndentRule`s.
#[derive(Default)]
pub(crate) struct IndentDsl {
pub(crate) rules: Vec<IndentRule>,
pub(crate) anchors: Vec<Pattern>,
#[cfg(test)]
pub(crate) tests: Vec<(&'static str, &'static str)>,
}
impl IndentDsl {
/// Specifies that an element should be treated as indent anchor even if it
/// isn't the first on the line.
///
/// For example, in
///
/// ```nix
/// { foo ? bar
/// , baz ? quux {
/// y = z;
/// }
/// }
/// ```
///
/// we want to indent `y = z;` relative to `baz ? ...`, although it doesn't
/// start on the first line.
pub(crate) fn anchor(&mut self, pattern: impl Into<Pattern>) -> &mut IndentDsl {
self.anchors.push(pattern.into());
self
}
/// Adds a new indent rule with the given name
pub(crate) fn rule<'a>(&'a mut self, rule_name: &'static str) -> IndentRuleBuilder<'a> {
IndentRuleBuilder::new(self, rule_name)
}
pub(crate) fn test(&mut self, before: &'static str, after: &'static str) -> &mut IndentDsl {
#[cfg(test)]
{
self.tests.push((before, after));
}
let _ = (before, after);
self
}
}
/// A builder to conveniently specify a single `IndentRule`.
pub(crate) struct IndentRuleBuilder<'a> {
dsl: &'a mut IndentDsl,
rule_name: &'static str,
parent: Option<Pattern>,
child: Option<Pattern>,
child_modality: Modality,
anchor_pattern: Option<Pattern>,
}
impl<'a> IndentRuleBuilder<'a> {
fn new(dsl: &'a mut IndentDsl, rule_name: &'static str) -> IndentRuleBuilder<'a> {
IndentRuleBuilder {
dsl,
rule_name,
parent: None,
child: None,
child_modality: Modality::Positive,
anchor_pattern: None,
}
}
/// Rule applies if element's parent matches.
pub(crate) fn inside(mut self, parent: impl Into<Pattern>) -> Self {
let prev = self.parent.replace(parent.into());
assert!(prev.is_none());
self
}
/// Rule applies if element itself does *not* match.
pub(crate) fn not_matching(self, child: impl Into<Pattern>) -> Self {
self.matching_modality(child.into(), Modality::Negative)
}
fn matching_modality(mut self, child: Pattern, child_modality: Modality) -> Self {
let prev = self.child.replace(child);
assert!(prev.is_none());
self.child_modality = child_modality;
self
}
/// Which indent does the rule applies?
pub(crate) fn set(self, indent_value: IndentValue) -> &'a mut IndentDsl {
let dsl = self.dsl;
let name = self.rule_name;
let rule = IndentRule {
name: RuleName::new(name),
parent: self.parent.unwrap_or_else(|| panic!("incomplete rule: {}", name)),
child: self.child,
child_modality: self.child_modality,
anchor_pattern: self.anchor_pattern,
indent_value,
};
dsl.rules.push(rule);
dsl
}
/// Only apply this rule when `cond` is true for the anchor node, relative
/// to which we compute indentation level.
pub(crate) fn when_anchor(mut self, cond: impl Into<Pattern>) -> Self {
self.anchor_pattern = Some(cond.into());
self
}
}