wdl-format 0.18.0

Formatting of WDL (Workflow Description Language) documents
Documentation
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
//! Formatting of WDL v1.x elements.

use std::rc::Rc;

use nonempty::NonEmpty;
use wdl_ast::SyntaxKind;
use wdl_ast::SyntaxToken;
use wdl_ast::v1::ImportSource;
use wdl_ast::v1::ImportStatement;

/// A key for sorting an `ImportStatement` alongside other imports.
///
/// Quoted imports sort before symbolic imports; within each group the sort key
/// is the URI text or the module path text.
fn import_sort_key(stmt: &ImportStatement) -> (u8, String) {
    match stmt.source() {
        ImportSource::Uri(uri) => {
            let text = uri.text().map(|t| t.text().to_string()).unwrap_or_default();
            (0, text)
        }
        ImportSource::ModulePath(path) => (1, path.text()),
    }
}

pub mod decl;
pub mod r#enum;
pub mod expr;
pub mod import;
pub mod meta;
pub mod sort;
pub mod r#struct;
pub mod task;
pub mod workflow;

use crate::Config;
use crate::PreToken;
use crate::TokenStream;
use crate::Writable as _;
use crate::element::FormatElement;

/// Formats an [`Ast`](wdl_ast::Ast).
///
/// This is the entry point for formatting WDL v1.x files.
///
/// # Panics
///
/// It will panic if the provided `element` is not a valid WDL v1.x AST.
pub fn format_ast(element: &FormatElement, stream: &mut TokenStream<PreToken>, config: &Config) {
    fn last_token_of_element(elem: &FormatElement) -> SyntaxToken {
        elem.element()
            .as_node()
            .expect("all children of an AST should be nodes")
            .inner()
            .last_token()
            .expect("nodes should have tokens")
    }

    let mut children = element.children().expect("AST children");

    let version_statement = children.next().expect("version statement");
    assert!(version_statement.element().kind() == SyntaxKind::VersionStatementNode);
    (&version_statement).write(stream, config);

    stream.blank_line();

    let mut imports = Vec::new();
    let mut remainder = Vec::new();

    for child in children {
        match child.element().kind() {
            SyntaxKind::ImportStatementNode => imports.push(child),
            _ => remainder.push(child),
        }
    }

    if config.sort_imports {
        imports.sort_by_cached_key(|child| {
            let stmt = child
                .element()
                .as_node()
                .expect("import statement node")
                .as_import_statement()
                .expect("import statement");
            import_sort_key(stmt)
        });
    }

    stream.ignore_trailing_blank_lines();

    let mut trailing_comments = None;

    for import in imports {
        (&import).write(stream, config);

        if trailing_comments.is_none() {
            trailing_comments = find_trailing_comments(&last_token_of_element(import));
        }
    }

    stream.blank_line();

    for child in &remainder {
        (child).write(stream, config);

        if trailing_comments.is_none() {
            trailing_comments = find_trailing_comments(&last_token_of_element(child));
        }

        stream.blank_line();
    }

    if let Some(comments) = trailing_comments {
        stream.trim_end(&PreToken::BlankLine);
        for comment in comments {
            stream.push(PreToken::Trivia(crate::Trivia::Comment(
                crate::Comment::Preceding(Rc::new(comment.text().into())),
            )));
            stream.push(PreToken::LineEnd);
        }
    }
}

/// Finds any trailing comments at the end of a WDL document.
///
/// Trailing comments are unhandled as they don't fit neatly into the trivia
/// model used by this crate. [`crate::Comment`]s can only be "preceding" or
/// "inline", but non-inline comments at the end of a WDL document
/// have no following element to precede. This will find any such comments and
/// return them.
fn find_trailing_comments(token: &SyntaxToken) -> Option<NonEmpty<SyntaxToken>> {
    let mut next_token = token.next_token();
    let mut on_next_line = false;

    fn is_comment(token: &SyntaxToken) -> bool {
        matches!(token.kind(), SyntaxKind::Comment)
    }

    let mut encountered_comments = Vec::new();

    while let Some(next) = next_token {
        if !next.kind().is_trivia() {
            return None;
        }

        // skip if we are processing an inline comment of the input token
        let skip = !on_next_line && is_comment(&next);
        on_next_line = on_next_line || next.text().contains('\n');
        next_token = next.next_token();
        if skip {
            continue;
        }
        if is_comment(&next) {
            encountered_comments.push(next);
        }
    }

    NonEmpty::from_vec(encountered_comments)
}

/// Formats a [`VersionStatement`](wdl_ast::VersionStatement).
pub fn format_version_statement(
    element: &FormatElement,
    stream: &mut TokenStream<PreToken>,
    config: &Config,
) {
    let mut children = element.children().expect("version statement children");

    // We never want to start a WDL document with a blank line,
    // but the preceding trivia may include one that will
    // be added if we don't exclude it.
    let version_keyword = children.next().expect("version keyword");
    assert!(version_keyword.element().kind() == SyntaxKind::VersionKeyword);
    let mut buffer = TokenStream::<PreToken>::default();
    (&version_keyword).write(&mut buffer, config);
    let mut buff_iter = buffer.into_iter();
    let first_token = buff_iter.next().expect("at least one token");
    if !matches!(first_token, PreToken::Trivia(crate::Trivia::BlankLine)) {
        stream.push(first_token);
    }
    for remaining in buff_iter {
        stream.push(remaining);
    }
    stream.end_word();

    for child in children {
        (&child).write(stream, config);
        stream.end_word();
    }
    stream.end_line();
}

/// Formats an [`InputSection`](wdl_ast::v1::InputSection).
///
/// # Panics
///
/// This will panic if the provided `element` is not a valid WDL v1.x
/// input section.
pub fn format_input_section(
    element: &FormatElement,
    stream: &mut TokenStream<PreToken>,
    config: &Config,
) {
    let mut children = element.children().expect("input section children");

    let input_keyword = children.next().expect("input section input keyword");
    assert!(input_keyword.element().kind() == SyntaxKind::InputKeyword);
    (&input_keyword).write(stream, config);
    stream.end_word();

    let open_brace = children.next().expect("input section open brace");
    assert!(open_brace.element().kind() == SyntaxKind::OpenBrace);
    (&open_brace).write(stream, config);
    stream.increment_indent();

    let mut inputs = Vec::new();
    let mut close_brace = None;

    for child in children {
        match child.element().kind() {
            SyntaxKind::BoundDeclNode | SyntaxKind::UnboundDeclNode => inputs.push(child),
            SyntaxKind::CloseBrace => close_brace = Some(child),
            _ => panic!("unexpected input section child"),
        }
    }

    if config.sort_inputs {
        inputs.sort_by(|a, b| {
            let a_decl =
                wdl_ast::v1::Decl::cast(a.element().as_node().unwrap().inner().clone()).unwrap();
            let b_decl =
                wdl_ast::v1::Decl::cast(b.element().as_node().unwrap().inner().clone()).unwrap();
            sort::compare_decl(&a_decl, &b_decl)
        });
    }
    for input in inputs {
        (&input).write(stream, config);
    }

    stream.decrement_indent();
    (&close_brace.expect("input section close brace")).write(stream, config);
    stream.end_line();
}

/// Formats an [`OutputSection`](wdl_ast::v1::OutputSection).
///
/// # Panics
///
/// This will panic if the provided `element` is not a valid WDL v1.x
/// output section.
pub fn format_output_section(
    element: &FormatElement,
    stream: &mut TokenStream<PreToken>,
    config: &Config,
) {
    let mut children = element.children().expect("output section children");

    let output_keyword = children.next().expect("output keyword");
    assert!(output_keyword.element().kind() == SyntaxKind::OutputKeyword);
    (&output_keyword).write(stream, config);
    stream.end_word();

    let open_brace = children.next().expect("output section open brace");
    assert!(open_brace.element().kind() == SyntaxKind::OpenBrace);
    (&open_brace).write(stream, config);
    stream.increment_indent();

    for child in children {
        if child.element().kind() == SyntaxKind::CloseBrace {
            stream.decrement_indent();
        } else {
            assert!(child.element().kind() == SyntaxKind::BoundDeclNode);
        }
        (&child).write(stream, config);
        stream.end_line();
    }
}

/// Formats a [`LiteralInputItem`](wdl_ast::v1::LiteralInputItem).
///
/// # Panics
///
/// This will panic if the provided `element` is not a valid WDL v1.x
/// literal input item.
pub fn format_literal_input_item(
    element: &FormatElement,
    stream: &mut TokenStream<PreToken>,
    config: &Config,
) {
    let mut children = element.children().expect("literal input item children");

    let key = children.next().expect("literal input item key");
    assert!(key.element().kind() == SyntaxKind::Ident);
    (&key).write(stream, config);

    let colon = children.next().expect("literal input item colon");
    assert!(colon.element().kind() == SyntaxKind::Colon);
    (&colon).write(stream, config);
    stream.end_word();

    let hints_node = children.next().expect("literal input item hints node");
    assert!(hints_node.element().kind() == SyntaxKind::LiteralHintsNode);
    (&hints_node).write(stream, config);
}

/// Formats a [`LiteralInput`](wdl_ast::v1::LiteralInput).
///
/// # Panics
///
/// This will panic if the provided `element` is not a valid WDL v1.x
/// literal input.
pub fn format_literal_input(
    element: &FormatElement,
    stream: &mut TokenStream<PreToken>,
    config: &Config,
) {
    let mut children = element.children().expect("literal input children");

    let input_keyword = children.next().expect("literal input keyword");
    assert!(input_keyword.element().kind() == SyntaxKind::InputKeyword);
    (&input_keyword).write(stream, config);
    stream.end_word();

    let open_brace = children.next().expect("literal input open brace");
    assert!(open_brace.element().kind() == SyntaxKind::OpenBrace);
    (&open_brace).write(stream, config);
    stream.increment_indent();

    let mut items = Vec::new();
    let mut commas = Vec::new();
    let mut close_brace = None;

    for child in children {
        match child.element().kind() {
            SyntaxKind::LiteralInputItemNode => items.push(child),
            SyntaxKind::Comma => commas.push(child),
            SyntaxKind::CloseBrace => close_brace = Some(child),
            _ => panic!("unexpected literal input child"),
        }
    }

    let mut commas = commas.iter();
    for item in items {
        (&item).write(stream, config);
        if let Some(comma) = commas.next() {
            (comma).write(stream, config);
        } else if config.trailing_commas {
            stream.push_literal(",".to_string(), SyntaxKind::Comma);
        }
        stream.end_line();
    }

    stream.decrement_indent();
    (&close_brace.expect("literal input close brace")).write(stream, config);
}

/// Formats a [`LiteralHintsItem`](wdl_ast::v1::LiteralHintsItem).
///
/// # Panics
///
/// This will panic if the provided `element` is not a valid WDL v1.x
/// literal hints item.
pub fn format_literal_hints_item(
    element: &FormatElement,
    stream: &mut TokenStream<PreToken>,
    config: &Config,
) {
    let mut children = element.children().expect("literal hints item children");

    let key = children.next().expect("literal hints item key");
    assert!(key.element().kind() == SyntaxKind::Ident);
    (&key).write(stream, config);

    let colon = children.next().expect("literal hints item colon");
    assert!(colon.element().kind() == SyntaxKind::Colon);
    (&colon).write(stream, config);
    stream.end_word();

    let value = children.next().expect("literal hints item value");
    (&value).write(stream, config);
}

/// Formats a [`LiteralHints`](wdl_ast::v1::LiteralHints).
///
/// # Panics
///
/// This will panic if the provided `element` is not a valid WDL v1.x
/// literal hints.
pub fn format_literal_hints(
    element: &FormatElement,
    stream: &mut TokenStream<PreToken>,
    config: &Config,
) {
    let mut children = element.children().expect("literal hints children");

    let hints_keyword = children.next().expect("literal hints keyword");
    assert!(hints_keyword.element().kind() == SyntaxKind::HintsKeyword);
    (&hints_keyword).write(stream, config);
    stream.end_word();

    let open_brace = children.next().expect("literal hints open brace");
    assert!(open_brace.element().kind() == SyntaxKind::OpenBrace);
    (&open_brace).write(stream, config);
    stream.increment_indent();

    let mut items = Vec::new();
    let mut commas = Vec::new();
    let mut close_brace = None;

    for child in children {
        match child.element().kind() {
            SyntaxKind::LiteralHintsItemNode => items.push(child),
            SyntaxKind::Comma => commas.push(child),
            SyntaxKind::CloseBrace => close_brace = Some(child),
            _ => panic!("unexpected literal hints child"),
        }
    }

    let mut commas = commas.iter();
    for item in items {
        (&item).write(stream, config);
        if let Some(comma) = commas.next() {
            (comma).write(stream, config);
        } else if config.trailing_commas {
            stream.push_literal(",".to_string(), SyntaxKind::Comma);
        }
        stream.end_line();
    }

    stream.decrement_indent();
    (&close_brace.expect("literal hints close brace")).write(stream, config);
}

/// Formats a [`LiteralOutputItem`](wdl_ast::v1::LiteralOutputItem).
///
/// # Panics
///
/// This will panic if the provided `element` is not a valid WDL v1.x
/// literal output item.
pub fn format_literal_output_item(
    element: &FormatElement,
    stream: &mut TokenStream<PreToken>,
    config: &Config,
) {
    let mut children = element.children().expect("literal output item children");

    for child in children.by_ref() {
        if matches!(child.element().kind(), SyntaxKind::Ident | SyntaxKind::Dot) {
            (&child).write(stream, config);
        } else {
            assert!(child.element().kind() == SyntaxKind::Colon);
            (&child).write(stream, config);
            stream.end_word();
            break;
        }
    }

    let value = children.next().expect("literal output item value");
    (&value).write(stream, config);
}

/// Formats a [`LiteralOutput`](wdl_ast::v1::LiteralOutput).
///
/// # Panics
///
/// This will panic if the provided `element` is not a valid WDL v1.x
/// literal output.
pub fn format_literal_output(
    element: &FormatElement,
    stream: &mut TokenStream<PreToken>,
    config: &Config,
) {
    let mut children = element.children().expect("literal output children");

    let output_keyword = children.next().expect("literal output keyword");
    assert!(output_keyword.element().kind() == SyntaxKind::OutputKeyword);
    (&output_keyword).write(stream, config);
    stream.end_word();

    let open_brace = children.next().expect("literal output open brace");
    assert!(open_brace.element().kind() == SyntaxKind::OpenBrace);
    (&open_brace).write(stream, config);
    stream.increment_indent();

    let mut items = Vec::new();
    let mut commas = Vec::new();
    let mut close_brace = None;

    for child in children {
        match child.element().kind() {
            SyntaxKind::LiteralOutputItemNode => items.push(child),
            SyntaxKind::Comma => commas.push(child),
            SyntaxKind::CloseBrace => close_brace = Some(child),
            _ => panic!("unexpected literal output child"),
        }
    }

    let mut commas = commas.iter();
    for item in items {
        (&item).write(stream, config);
        if let Some(comma) = commas.next() {
            (comma).write(stream, config);
        } else if config.trailing_commas {
            stream.push_literal(",".to_string(), SyntaxKind::Comma);
        }
        stream.end_line();
    }

    stream.decrement_indent();
    (&close_brace.expect("literal output close brace")).write(stream, config);
}