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
use rnix::{SyntaxKind, SyntaxNode};
use crate::edit::{OutputChange, Outputs};
use super::error::WalkerError;
use super::node::parse_node;
/// Unwrap parentheses around a node, returning the inner node.
/// If the node is not NODE_PAREN, returns a clone of the original.
fn unwrap_parens(node: &SyntaxNode) -> SyntaxNode {
if node.kind() == SyntaxKind::NODE_PAREN
&& let Some(inner) = node.children().find(|c| {
c.kind() != SyntaxKind::TOKEN_L_PAREN && c.kind() != SyntaxKind::TOKEN_R_PAREN
})
{
return inner;
}
node.clone()
}
/// List the outputs from a flake.nix root node.
pub fn list_outputs(root: &SyntaxNode) -> Result<Outputs, WalkerError> {
let mut outputs: Vec<String> = vec![];
let mut any = false;
if root.kind() != SyntaxKind::NODE_ROOT {
return Err(WalkerError::NotARoot(root.kind()));
}
for toplevel in root.first_child().unwrap().children() {
if toplevel.kind() == SyntaxKind::NODE_ATTRPATH_VALUE
&& let Some(outputs_node) = toplevel
.children()
.find(|child| child.to_string() == "outputs")
{
assert!(outputs_node.kind() == SyntaxKind::NODE_ATTRPATH);
if let Some(next_sibling) = outputs_node.next_sibling() {
let outputs_lambda = unwrap_parens(&next_sibling);
if outputs_lambda.kind() != SyntaxKind::NODE_LAMBDA {
continue;
}
if let Some(output) = outputs_lambda
.children()
.find(|n| n.kind() == SyntaxKind::NODE_PATTERN)
{
// We need to iterate over tokens, because ellipsis ...
// is not a valid node itself.
for child in output.children_with_tokens() {
if child.kind() == SyntaxKind::NODE_PAT_ENTRY {
outputs.push(child.to_string());
}
if child.kind() == SyntaxKind::TOKEN_ELLIPSIS {
any = true;
}
}
}
}
}
}
if outputs.is_empty() {
Ok(Outputs::None)
} else if any {
Ok(Outputs::Any(outputs))
} else {
Ok(Outputs::Multiple(outputs))
}
}
/// Change the outputs attribute in a flake.nix root node.
///
/// Builds modifications bottom-up (output -> lambda -> toplevel -> attr_set)
/// then uses `attr_set.replace_with()` to propagate to NODE_ROOT,
/// preserving any leading comments/trivia.
pub fn change_outputs(
root: &SyntaxNode,
change: OutputChange,
) -> Result<Option<SyntaxNode>, WalkerError> {
if root.kind() != SyntaxKind::NODE_ROOT {
return Err(WalkerError::NotARoot(root.kind()));
}
let attr_set = root.first_child().unwrap();
for toplevel in attr_set.children() {
if toplevel.kind() == SyntaxKind::NODE_ATTRPATH_VALUE
&& let Some(outputs_node) = toplevel
.children()
.find(|child| child.to_string() == "outputs")
{
assert!(outputs_node.kind() == SyntaxKind::NODE_ATTRPATH);
if let Some(next_sibling) = outputs_node.next_sibling() {
let outputs_lambda = unwrap_parens(&next_sibling);
if outputs_lambda.kind() != SyntaxKind::NODE_LAMBDA {
continue;
}
for output in outputs_lambda.children() {
if SyntaxKind::NODE_PATTERN == output.kind() {
if let OutputChange::Add(ref add) = change {
// Find the closing brace to insert before,
// accounting for any @-binding after the brace.
let r_brace_index = output
.children_with_tokens()
.position(|c| c.kind() == SyntaxKind::TOKEN_R_BRACE)
.expect("pattern must have closing brace");
// Insert before `}`, but if the token
// immediately before `}` is an entry or
// ellipsis (no whitespace gap), insert at
// `r_brace_index` so we go after it.
let before_brace = output
.children_with_tokens()
.nth(r_brace_index - 1)
.map(|c| c.kind());
let mut last_node = if matches!(
before_brace,
Some(
SyntaxKind::NODE_PAT_ENTRY
| SyntaxKind::TOKEN_ELLIPSIS
| SyntaxKind::TOKEN_COMMA
)
) {
r_brace_index
} else {
r_brace_index - 1
};
// Adjust the addition for trailing commas.
// Use the last NODE_PAT_ENTRY specifically, not
// the last child (which may be NODE_PAT_BIND for
// `@inputs` patterns).
let last_pat_entry = output
.children()
.filter(|c| c.kind() == SyntaxKind::NODE_PAT_ENTRY)
.last();
let has_trailing_comma = matches!(
last_pat_entry
.as_ref()
.and_then(|last| last.next_sibling_or_token())
.map(|last_token| last_token.kind()),
Some(SyntaxKind::TOKEN_COMMA)
);
// Detect leading-comma style: commas appear before
// entries, preceded by whitespace containing a newline.
let leading_comma_ws = {
let tokens: Vec<_> = output.children_with_tokens().collect();
let mut result = None;
for i in 0..tokens.len() {
if tokens[i].kind() == SyntaxKind::TOKEN_COMMA
&& i > 0
&& tokens[i - 1].kind() == SyntaxKind::TOKEN_WHITESPACE
&& tokens[i - 1].as_token().unwrap().text().contains('\n')
{
result = Some(
tokens[i - 1].as_token().unwrap().text().to_string(),
);
}
}
result
};
// For leading-comma style, insert after the last
// entry rather than before `}`. This avoids double
// commas when there is a standalone trailing comma
// (e.g. `, flake-utils\n ,\n }`).
if leading_comma_ws.is_some() {
let mut last_entry_pos = None;
for (i, c) in output.children_with_tokens().enumerate() {
if c.kind() == SyntaxKind::NODE_PAT_ENTRY {
last_entry_pos = Some(i);
}
}
if let Some(pos) = last_entry_pos {
last_node = pos + 1;
}
}
// Detect multi-line trailing-comma style without
// trailing comma on the last entry: commas followed
// by whitespace containing newlines.
let multiline_trailing_ws = if !has_trailing_comma
&& leading_comma_ws.is_none()
{
let tokens: Vec<_> = output.children_with_tokens().collect();
let mut result = None;
for i in 0..tokens.len() {
if tokens[i].kind() == SyntaxKind::TOKEN_COMMA
&& i + 1 < tokens.len()
&& tokens[i + 1].kind() == SyntaxKind::TOKEN_WHITESPACE
&& tokens[i + 1].as_token().unwrap().text().contains('\n')
{
result = Some(
tokens[i + 1].as_token().unwrap().text().to_string(),
);
}
}
result
} else {
None
};
let addition = if let Some(ref ws) = leading_comma_ws {
parse_node(&format!("{ws}, {add}"))
} else if has_trailing_comma {
parse_node(&format!("{add},"))
} else if let Some(ref ws) = multiline_trailing_ws {
parse_node(&format!(",{ws}{add}"))
} else {
parse_node(&format!(", {add}"))
};
let mut green = output
.green()
.insert_child(last_node, addition.green().into());
// Only insert whitespace before the addition when there's
// a trailing comma without leading-comma style — the
// leading-comma and non-trailing-comma formats already
// include whitespace so extra would produce `x , y`.
if has_trailing_comma
&& leading_comma_ws.is_none()
&& let Some(prev) =
last_pat_entry.as_ref().unwrap().prev_sibling_or_token()
&& let SyntaxKind::TOKEN_WHITESPACE = prev.kind()
{
let whitespace =
parse_node(prev.as_token().unwrap().green().text());
green = green.insert_child(last_node, whitespace.green().into());
}
let changed_outputs_lambda = outputs_lambda
.green()
.replace_child(output.index(), green.into());
let changed_toplevel = if next_sibling.kind() == SyntaxKind::NODE_PAREN
{
let changed_paren = next_sibling.green().replace_child(
outputs_lambda.index(),
changed_outputs_lambda.into(),
);
toplevel
.green()
.replace_child(next_sibling.index(), changed_paren.into())
} else {
toplevel.green().replace_child(
outputs_lambda.index(),
changed_outputs_lambda.into(),
)
};
let changed_attr_set = attr_set
.green()
.replace_child(toplevel.index(), changed_toplevel.into());
let result = attr_set.replace_with(changed_attr_set);
return Ok(Some(parse_node(&result.to_string())));
}
for child in output.children() {
if child.kind() == SyntaxKind::NODE_PAT_ENTRY
&& let OutputChange::Remove(ref id) = change
&& child.to_string() == *id
{
let mut green = output.green().remove_child(child.index());
if let Some(prev) = child.prev_sibling_or_token()
&& let SyntaxKind::TOKEN_WHITESPACE = prev.kind()
{
green = green.remove_child(prev.index());
// Only remove the element before the whitespace
// if it's a comma (non-first entry). When the
// entry is first, the element before is `{` -
// remove the trailing comma instead.
if let Some(before_ws) = prev.prev_sibling_or_token()
&& before_ws.kind() == SyntaxKind::TOKEN_COMMA
{
green = green.remove_child(prev.index() - 1);
// Leading-comma style: also remove the
// newline+indent whitespace before the comma.
if let Some(before_comma) =
before_ws.prev_sibling_or_token()
&& before_comma.kind() == SyntaxKind::TOKEN_WHITESPACE
&& before_comma
.as_token()
.unwrap()
.text()
.contains('\n')
{
green = green.remove_child(prev.index() - 2);
}
} else {
// First entry in leading-comma style:
// remove the comma that belongs to
// the next entry, along with the
// whitespace between `{` and that
// next entry.
// After the two removals above,
// prev.index() points to what was
// right after the entry. Walk forward
// from there and remove whitespace +
// comma tokens until we hit the next
// entry.
let idx = prev.index();
let children: Vec<_> = green.children().collect();
let is_leading_comma = idx < children.len()
&& children[idx].kind().0
== SyntaxKind::TOKEN_WHITESPACE as u16;
drop(children);
if is_leading_comma {
// Leading-comma style first entry:
// remove whitespace, comma, and
// whitespace that belong to the
// next entry, then re-insert a
// space after `{`.
loop {
let children: Vec<_> = green.children().collect();
if idx >= children.len() {
break;
}
let raw_kind = children[idx].kind().0;
if raw_kind == SyntaxKind::TOKEN_WHITESPACE as u16
|| raw_kind == SyntaxKind::TOKEN_COMMA as u16
{
green = green.remove_child(idx);
} else {
break;
}
}
let ws = parse_node(" ");
green = green.insert_child(idx, ws.green().into());
} else {
// Trailing-comma style first entry:
// just remove the trailing comma.
green = green.remove_child(idx);
}
}
} else {
// No whitespace before the entry (prev is
// `{` or absent). Remove trailing comma
// and whitespace after the entry.
let idx = child.index();
loop {
let children: Vec<_> = green.children().collect();
if idx >= children.len() {
break;
}
let raw_kind = children[idx].kind().0;
if raw_kind == SyntaxKind::TOKEN_COMMA as u16
|| raw_kind == SyntaxKind::TOKEN_WHITESPACE as u16
{
green = green.remove_child(idx);
} else {
break;
}
}
}
let changed_outputs_lambda = outputs_lambda
.green()
.replace_child(output.index(), green.into());
let changed_toplevel = if next_sibling.kind()
== SyntaxKind::NODE_PAREN
{
let changed_paren = next_sibling.green().replace_child(
outputs_lambda.index(),
changed_outputs_lambda.into(),
);
toplevel
.green()
.replace_child(next_sibling.index(), changed_paren.into())
} else {
toplevel.green().replace_child(
outputs_lambda.index(),
changed_outputs_lambda.into(),
)
};
let changed_attr_set = attr_set
.green()
.replace_child(toplevel.index(), changed_toplevel.into());
let result = attr_set.replace_with(changed_attr_set);
return Ok(Some(parse_node(&result.to_string())));
}
}
}
}
}
}
}
Ok(None)
}