wdl_format/
lib.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
//! Formatting facilities for WDL.

pub mod config;
pub mod element;
mod token;
pub mod v1;

use std::fmt::Write;

pub use config::Config;
pub use token::*;
use wdl_ast::Element;
use wdl_ast::Node as AstNode;

use crate::element::FormatElement;

/// Newline constant used for formatting on windows platforms.
#[cfg(windows)]
pub const NEWLINE: &str = "\r\n";
/// Newline constant used for formatting on non-windows platforms.
#[cfg(not(windows))]
pub const NEWLINE: &str = "\n";

/// A space.
pub const SPACE: &str = " ";

/// Returns exactly one entity from an enumerable list of entities (usually a
/// [`Vec`]).
#[macro_export]
macro_rules! exactly_one {
    ($entities:expr, $name:expr) => {
        match $entities.len() {
            0 => unreachable!("we should never have zero {}", $name),
            // SAFETY: we just checked to ensure that exactly
            // one element exists, so this will always unwrap.
            1 => $entities.pop().unwrap(),
            _ => unreachable!("we should not have two or more {}", $name),
        }
    };
}

/// An element that can be written to a token stream.
pub trait Writable {
    /// Writes the element to the token stream.
    fn write(&self, stream: &mut TokenStream<PreToken>);
}

impl Writable for &FormatElement {
    fn write(&self, stream: &mut TokenStream<PreToken>) {
        match self.element() {
            Element::Node(node) => match node {
                AstNode::AccessExpr(_) => v1::expr::format_access_expr(self, stream),
                AstNode::AdditionExpr(_) => v1::expr::format_addition_expr(self, stream),
                AstNode::ArrayType(_) => v1::decl::format_array_type(self, stream),
                AstNode::Ast(_) => v1::format_ast(self, stream),
                AstNode::BoundDecl(_) => v1::decl::format_bound_decl(self, stream),
                AstNode::CallAfter(_) => v1::workflow::call::format_call_after(self, stream),
                AstNode::CallAlias(_) => v1::workflow::call::format_call_alias(self, stream),
                AstNode::CallExpr(_) => v1::expr::format_call_expr(self, stream),
                AstNode::CallInputItem(_) => {
                    v1::workflow::call::format_call_input_item(self, stream)
                }
                AstNode::CallStatement(_) => {
                    v1::workflow::call::format_call_statement(self, stream)
                }
                AstNode::CallTarget(_) => v1::workflow::call::format_call_target(self, stream),
                AstNode::CommandSection(_) => v1::task::format_command_section(self, stream),
                AstNode::ConditionalStatement(_) => {
                    v1::workflow::format_conditional_statement(self, stream)
                }
                AstNode::DefaultOption(_) => v1::expr::format_default_option(self, stream),
                AstNode::DivisionExpr(_) => v1::expr::format_division_expr(self, stream),
                AstNode::EqualityExpr(_) => v1::expr::format_equality_expr(self, stream),
                AstNode::ExponentiationExpr(_) => {
                    v1::expr::format_exponentiation_expr(self, stream)
                }
                AstNode::GreaterEqualExpr(_) => v1::expr::format_greater_equal_expr(self, stream),
                AstNode::GreaterExpr(_) => v1::expr::format_greater_expr(self, stream),
                AstNode::IfExpr(_) => v1::expr::format_if_expr(self, stream),
                AstNode::ImportAlias(_) => v1::import::format_import_alias(self, stream),
                AstNode::ImportStatement(_) => v1::import::format_import_statement(self, stream),
                AstNode::IndexExpr(_) => v1::expr::format_index_expr(self, stream),
                AstNode::InequalityExpr(_) => v1::expr::format_inequality_expr(self, stream),
                AstNode::InputSection(_) => v1::format_input_section(self, stream),
                AstNode::LessEqualExpr(_) => v1::expr::format_less_equal_expr(self, stream),
                AstNode::LessExpr(_) => v1::expr::format_less_expr(self, stream),
                AstNode::LiteralArray(_) => v1::expr::format_literal_array(self, stream),
                AstNode::LiteralBoolean(_) => v1::expr::format_literal_boolean(self, stream),
                AstNode::LiteralFloat(_) => v1::expr::format_literal_float(self, stream),
                AstNode::LiteralHints(_) => v1::format_literal_hints(self, stream),
                AstNode::LiteralHintsItem(_) => v1::format_literal_hints_item(self, stream),
                AstNode::LiteralInput(_) => v1::format_literal_input(self, stream),
                AstNode::LiteralInputItem(_) => v1::format_literal_input_item(self, stream),
                AstNode::LiteralInteger(_) => v1::expr::format_literal_integer(self, stream),
                AstNode::LiteralMap(_) => v1::expr::format_literal_map(self, stream),
                AstNode::LiteralMapItem(_) => v1::expr::format_literal_map_item(self, stream),
                AstNode::LiteralNone(_) => v1::expr::format_literal_none(self, stream),
                AstNode::LiteralNull(_) => v1::meta::format_literal_null(self, stream),
                AstNode::LiteralObject(_) => v1::expr::format_literal_object(self, stream),
                AstNode::LiteralObjectItem(_) => v1::expr::format_literal_object_item(self, stream),
                AstNode::LiteralOutput(_) => v1::format_literal_output(self, stream),
                AstNode::LiteralOutputItem(_) => v1::format_literal_output_item(self, stream),
                AstNode::LiteralPair(_) => v1::expr::format_literal_pair(self, stream),
                AstNode::LiteralString(_) => v1::expr::format_literal_string(self, stream),
                AstNode::LiteralStruct(_) => v1::r#struct::format_literal_struct(self, stream),
                AstNode::LiteralStructItem(_) => {
                    v1::r#struct::format_literal_struct_item(self, stream)
                }
                AstNode::LogicalAndExpr(_) => v1::expr::format_logical_and_expr(self, stream),
                AstNode::LogicalNotExpr(_) => v1::expr::format_logical_not_expr(self, stream),
                AstNode::LogicalOrExpr(_) => v1::expr::format_logical_or_expr(self, stream),
                AstNode::MapType(_) => v1::decl::format_map_type(self, stream),
                AstNode::MetadataArray(_) => v1::meta::format_metadata_array(self, stream),
                AstNode::MetadataObject(_) => v1::meta::format_metadata_object(self, stream),
                AstNode::MetadataObjectItem(_) => {
                    v1::meta::format_metadata_object_item(self, stream)
                }
                AstNode::MetadataSection(_) => v1::meta::format_metadata_section(self, stream),
                AstNode::ModuloExpr(_) => v1::expr::format_modulo_expr(self, stream),
                AstNode::MultiplicationExpr(_) => {
                    v1::expr::format_multiplication_expr(self, stream)
                }
                AstNode::NameRef(_) => v1::expr::format_name_ref(self, stream),
                AstNode::NegationExpr(_) => v1::expr::format_negation_expr(self, stream),
                AstNode::OutputSection(_) => v1::format_output_section(self, stream),
                AstNode::PairType(_) => v1::decl::format_pair_type(self, stream),
                AstNode::ObjectType(_) => v1::decl::format_object_type(self, stream),
                AstNode::ParameterMetadataSection(_) => {
                    v1::meta::format_parameter_metadata_section(self, stream)
                }
                AstNode::ParenthesizedExpr(_) => v1::expr::format_parenthesized_expr(self, stream),
                AstNode::Placeholder(_) => v1::expr::format_placeholder(self, stream),
                AstNode::PrimitiveType(_) => v1::decl::format_primitive_type(self, stream),
                AstNode::RequirementsItem(_) => v1::task::format_requirements_item(self, stream),
                AstNode::RequirementsSection(_) => {
                    v1::task::format_requirements_section(self, stream)
                }
                AstNode::RuntimeItem(_) => v1::task::format_runtime_item(self, stream),
                AstNode::RuntimeSection(_) => v1::task::format_runtime_section(self, stream),
                AstNode::ScatterStatement(_) => {
                    v1::workflow::format_scatter_statement(self, stream)
                }
                AstNode::SepOption(_) => v1::expr::format_sep_option(self, stream),
                AstNode::StructDefinition(_) => {
                    v1::r#struct::format_struct_definition(self, stream)
                }
                AstNode::SubtractionExpr(_) => v1::expr::format_subtraction_expr(self, stream),
                AstNode::TaskDefinition(_) => v1::task::format_task_definition(self, stream),
                AstNode::TaskHintsItem(_) => v1::task::format_task_hints_item(self, stream),
                AstNode::TaskHintsSection(_) => v1::task::format_task_hints_section(self, stream),
                AstNode::TrueFalseOption(_) => v1::expr::format_true_false_option(self, stream),
                AstNode::TypeRef(_) => v1::decl::format_type_ref(self, stream),
                AstNode::UnboundDecl(_) => v1::decl::format_unbound_decl(self, stream),
                AstNode::VersionStatement(_) => v1::format_version_statement(self, stream),
                AstNode::WorkflowDefinition(_) => {
                    v1::workflow::format_workflow_definition(self, stream)
                }
                AstNode::WorkflowHintsArray(_) => {
                    v1::workflow::format_workflow_hints_array(self, stream)
                }
                AstNode::WorkflowHintsItem(_) => {
                    v1::workflow::format_workflow_hints_item(self, stream)
                }
                AstNode::WorkflowHintsObject(_) => {
                    v1::workflow::format_workflow_hints_object(self, stream)
                }
                AstNode::WorkflowHintsObjectItem(_) => {
                    v1::workflow::format_workflow_hints_object_item(self, stream)
                }
                AstNode::WorkflowHintsSection(_) => {
                    v1::workflow::format_workflow_hints_section(self, stream)
                }
            },
            Element::Token(token) => {
                stream.push_ast_token(token);
            }
        }
    }
}

/// A formatter.
#[derive(Debug, Default)]
pub struct Formatter {
    /// The configuration.
    config: Config,
}

impl Formatter {
    /// Creates a new formatter.
    pub fn new(config: Config) -> Self {
        Self { config }
    }

    /// Gets the configuration for this formatter.
    pub fn config(&self) -> &Config {
        &self.config
    }

    /// Formats an element.
    pub fn format<W: Writable>(&self, element: W) -> std::result::Result<String, std::fmt::Error> {
        let mut result = String::new();

        for token in self.to_stream(element) {
            write!(result, "{token}", token = token.display(self.config()))?;
        }

        Ok(result)
    }

    /// Gets the [`PostToken`] stream.
    ///
    /// # Notes
    ///
    /// * This shouldn't be exposed publicly.
    fn to_stream<W: Writable>(&self, element: W) -> TokenStream<PostToken> {
        let mut stream = TokenStream::default();
        element.write(&mut stream);

        let mut postprocessor = Postprocessor::default();
        postprocessor.run(stream)
    }
}

#[cfg(test)]
mod tests {
    use wdl_ast::Document;
    use wdl_ast::Node;

    use crate::Formatter;
    use crate::element::node::AstNodeFormatExt as _;

    #[test]
    fn smoke() {
        let (document, diagnostics) = Document::parse(
            "## WDL
version 1.2  # This is a comment attached to the version.

# This is a comment attached to the task keyword.
task foo # This is an inline comment on the task ident.
{

} # This is an inline comment on the task close brace.

# This is a comment attached to the workflow keyword.
workflow bar # This is an inline comment on the workflow ident.
{
  # This is attached to the call keyword.
  call foo {}
} # This is an inline comment on the workflow close brace.",
        );

        assert!(diagnostics.is_empty());
        let document = Node::Ast(document.ast().into_v1().unwrap()).into_format_element();
        let formatter = Formatter::default();
        let result = formatter.format(&document);
        match result {
            Ok(s) => {
                print!("{}", s);
            }
            Err(err) => {
                panic!("failed to format document: {}", err);
            }
        }
    }
}