wdl-analysis 0.23.0

Analysis of Workflow Description Language (WDL) 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
//! Configuration for this crate.

use std::sync::Arc;

use schemars::JsonSchema;
use toml_spanner::Context;
use toml_spanner::Failed;
use toml_spanner::FromToml;
use toml_spanner::Item;
use toml_spanner::Toml;
use toml_spanner::helper::parse_string;
use tracing::warn;
use wdl_ast::Severity;
use wdl_ast::SupportedVersion;
use wdl_ast::SyntaxNode;

use crate::Exceptable as _;
use crate::FormatConfig;
use crate::KnownRulesRule;
use crate::MeaninglessLintDirective;
use crate::MisleadingDeclarationOrderRule;
use crate::Rule;
use crate::UnnecessaryFunctionCall;
use crate::UnusedCallRule;
use crate::UnusedDeclarationRule;
use crate::UnusedImportRule;
use crate::UnusedInputRule;
use crate::UsingFallbackVersion;
use crate::rules;

/// Configuration for `wdl-analysis`.
///
/// This type is a wrapper around an `Arc`, and so can be cheaply cloned and
/// sent between threads.
#[derive(Clone, PartialEq, Eq)]
pub struct Config {
    /// The actual fields, `Arc`ed up for easy cloning.
    inner: Arc<ConfigInner>,
}

impl<'de> FromToml<'de> for Config {
    fn from_toml(ctx: &mut Context<'de>, item: &Item<'de>) -> Result<Self, Failed> {
        Ok(Self {
            inner: ConfigInner::from_toml(ctx, item)?.into(),
        })
    }
}

// Custom `Debug` impl for the `Config` wrapper type that simplifies away the
// arc and the private inner struct
impl std::fmt::Debug for Config {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Config")
            .field("diagnostics", &self.inner.diagnostics)
            .field("fallback_version", &self.inner.fallback_version)
            .finish()
    }
}

impl Default for Config {
    fn default() -> Self {
        Self {
            inner: Arc::new(ConfigInner {
                diagnostics: Default::default(),
                fallback_version: None,
                format: FormatConfig::default(),
                ignore_filename: None,
                all_rules: Default::default(),
                feature_flags: FeatureFlags::default(),
            }),
        }
    }
}

impl Config {
    /// Get this configuration's [`DiagnosticsConfig`].
    pub fn diagnostics_config(&self) -> &DiagnosticsConfig {
        &self.inner.diagnostics
    }

    /// Get this configuration's fallback version; see
    /// [`Config::with_fallback_version()`].
    pub fn fallback_version(&self) -> Option<SupportedVersion> {
        self.inner.fallback_version
    }

    /// Get this configuration's [`FormatConfig`]; see
    /// [`Config::with_format_config()`].
    pub fn format(&self) -> &FormatConfig {
        &self.inner.format
    }

    /// Get this configuration's ignore filename.
    pub fn ignore_filename(&self) -> Option<&str> {
        self.inner.ignore_filename.as_deref()
    }

    /// Gets the list of all known rule identifiers.
    pub fn all_rules(&self) -> &[String] {
        &self.inner.all_rules
    }

    /// Gets the feature flags.
    pub fn feature_flags(&self) -> &FeatureFlags {
        &self.inner.feature_flags
    }

    /// Return a new configuration with the previous [`DiagnosticsConfig`]
    /// replaced by the argument.
    pub fn with_diagnostics_config(&self, diagnostics: DiagnosticsConfig) -> Self {
        let mut inner = (*self.inner).clone();
        inner.diagnostics = diagnostics;
        Self {
            inner: Arc::new(inner),
        }
    }

    /// Return a new configuration with the previous version fallback option
    /// replaced by the argument.
    ///
    /// This option controls what happens when analyzing a WDL document with a
    /// syntactically valid but unrecognized version in the version
    /// statement. The default value is `None`, with no fallback behavior.
    ///
    /// Configured with `Some(fallback_version)`, analysis will proceed as
    /// normal if the version statement contains a recognized version. If
    /// the version is unrecognized, analysis will continue as if the
    /// version statement contained `fallback_version`, though the concrete
    /// syntax of the version statement will remain unchanged.
    ///
    /// <div class="warning">
    ///
    /// # Warnings
    ///
    /// This option is intended only for situations where unexpected behavior
    /// due to unsupported syntax is acceptable, such as when providing
    /// best-effort editor hints via `wdl-lsp`. The semantics of executing a
    /// WDL workflow with an unrecognized version is undefined and not
    /// recommended.
    ///
    /// Once this option has been configured for an `Analyzer`, it should not be
    /// changed. A document that was initially parsed and analyzed with one
    /// fallback option may cause errors if subsequent operations are
    /// performed with a different fallback option.
    ///
    /// </div>
    pub fn with_fallback_version(&self, fallback_version: Option<SupportedVersion>) -> Self {
        let mut inner = (*self.inner).clone();
        inner.fallback_version = fallback_version;
        Self {
            inner: Arc::new(inner),
        }
    }

    /// Return a new configuration with the previous [`FormatConfig`]
    /// replaced by the argument.
    pub fn with_format_config(&self, format: FormatConfig) -> Self {
        let mut inner = (*self.inner).clone();
        inner.format = format;
        Self {
            inner: Arc::new(inner),
        }
    }

    /// Return a new configuration with the previous ignore filename replaced by
    /// the argument.
    ///
    /// Specifying `None` for `filename` disables ignore behavior. This is also
    /// the default.
    ///
    /// `Some(filename)` will use `filename` as the ignorefile basename to
    /// search for. Child directories _and_ parent directories are searched
    /// for a file with the same basename as `filename` and if a match is
    /// found it will attempt to be parsed as an ignorefile with a syntax
    /// similar to `.gitignore` files.
    pub fn with_ignore_filename(&self, filename: Option<String>) -> Self {
        let mut inner = (*self.inner).clone();
        inner.ignore_filename = filename;
        Self {
            inner: Arc::new(inner),
        }
    }

    /// Returns a new configuration with the list of all known rule identifiers
    /// replaced by the argument.
    ///
    /// This is used internally to populate the `#@ except:` snippet.
    pub fn with_all_rules(&self, rules: Vec<String>) -> Self {
        let mut inner = (*self.inner).clone();
        inner.all_rules = rules;
        Self {
            inner: Arc::new(inner),
        }
    }

    /// Return a new configuration with the previous [`FeatureFlags`]
    /// replaced by the argument.
    pub fn with_feature_flags(&self, feature_flags: FeatureFlags) -> Self {
        let mut inner = (*self.inner).clone();
        inner.feature_flags = feature_flags;
        Self {
            inner: Arc::new(inner),
        }
    }
}

/// The actual configuration fields inside the [`Config`] wrapper.
#[derive(Clone, Debug, PartialEq, Eq, Toml)]
struct ConfigInner {
    /// See [`DiagnosticsConfig`].
    #[toml(default, style = Header)]
    diagnostics: DiagnosticsConfig,
    /// See [`Config::with_fallback_version()`]
    #[toml(FromToml with = parse_string)]
    fallback_version: Option<SupportedVersion>,
    /// See [`Config::with_format_config()`]
    #[toml(default, style = Header)]
    format: FormatConfig,
    /// See [`Config::with_ignore_filename()`]
    ignore_filename: Option<String>,
    /// A list of all known rule identifiers.
    #[toml(default)]
    all_rules: Vec<String>,
    /// The set of feature flags that can be enabled or disabled.
    #[toml(default)]
    feature_flags: FeatureFlags,
}

/// Default value for the WDL v1.3 feature flag.
fn default_wdl_1_3() -> bool {
    true
}

/// A set of feature flags that can be enabled.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Toml, JsonSchema)]
pub struct FeatureFlags {
    /// Formerly enabled experimental WDL 1.3 features.
    ///
    /// This flag is now a no-op as WDL 1.3 is fully supported. Setting this to
    /// `false` will emit a warning.
    #[toml(default = true)]
    #[schemars(default = "default_wdl_1_3")]
    wdl_1_3: bool,
    /// Enables experimental WDL 1.4 features.
    ///
    /// Defaults to `false`. While `false`, `wdl-analysis` reports an error for
    /// any document declaring `version 1.4`.
    #[toml(default)]
    #[schemars(default)]
    wdl_1_4: bool,
}

impl Default for FeatureFlags {
    fn default() -> Self {
        Self {
            wdl_1_3: true,
            wdl_1_4: false,
        }
    }
}

impl FeatureFlags {
    /// Returns whether WDL 1.3 is enabled.
    ///
    /// WDL 1.3 is now fully supported and defaults to `true`. Setting this to
    /// `false` will emit a deprecation warning.
    pub fn wdl_1_3(&self) -> bool {
        self.wdl_1_3
    }

    /// Returns a new `FeatureFlags` with WDL 1.3 features enabled.
    #[deprecated(note = "WDL 1.3 is now enabled by default; this method is a no-op")]
    pub fn with_wdl_1_3(self) -> Self {
        self
    }

    /// Returns whether WDL 1.4 is enabled.
    pub fn wdl_1_4(&self) -> bool {
        self.wdl_1_4
    }

    /// Returns a new `FeatureFlags` with WDL 1.4 features enabled.
    pub fn with_wdl_1_4(mut self) -> Self {
        self.wdl_1_4 = true;
        self
    }
}

/// Configuration for analysis diagnostics.
///
/// Only the analysis diagnostics that aren't inherently treated as errors are
/// represented here.
///
/// These diagnostics default to a warning severity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Toml)]
pub struct DiagnosticsConfig {
    /// The severity for the unused import diagnostic.
    ///
    /// A value of `None` disables the diagnostic.
    #[toml(FromToml with = parse_string)]
    pub unused_import: Option<Severity>,
    /// The severity for the unused input diagnostic.
    ///
    /// A value of `None` disables the diagnostic.
    #[toml(FromToml with = parse_string)]
    pub unused_input: Option<Severity>,
    /// The severity for the unused declaration diagnostic.
    ///
    /// A value of `None` disables the diagnostic.
    #[toml(FromToml with = parse_string)]
    pub unused_declaration: Option<Severity>,
    /// The severity for the unused call diagnostic.
    ///
    /// A value of `None` disables the diagnostic.
    #[toml(FromToml with = parse_string)]
    pub unused_call: Option<Severity>,
    /// The severity for the unnecessary function call diagnostic.
    ///
    /// A value of `None` disables the diagnostic.
    #[toml(FromToml with = parse_string)]
    pub unnecessary_function_call: Option<Severity>,
    /// The severity for the using fallback version diagnostic.
    ///
    /// A value of `None` disables the diagnostic. If there is no version
    /// configured with [`Config::with_fallback_version()`], this diagnostic
    /// will not be emitted.
    #[toml(FromToml with = parse_string)]
    pub using_fallback_version: Option<Severity>,
    /// The severity for the misleading declaration order diagnostic.
    ///
    /// A value of `None` disables the diagnostic.
    #[toml(FromToml with = parse_string)]
    pub misleading_declaration_order: Option<Severity>,
    /// The severity for the meaningless lint directive diagnostic.
    ///
    /// A value of `None` disables the diagnostic.
    #[toml(FromToml with = parse_string)]
    pub meaningless_lint_directive: Option<Severity>,
    /// The severity for the known rules diagnostic.
    ///
    /// A value of `None` disables the diagnostic.
    #[toml(FromToml with = parse_string)]
    pub known_rules: Option<Severity>,
}

impl Default for DiagnosticsConfig {
    fn default() -> Self {
        Self::new(rules())
    }
}

impl DiagnosticsConfig {
    /// Creates a new diagnostics configuration from a rule set.
    pub fn new<T: AsRef<dyn Rule>>(rules: impl IntoIterator<Item = T>) -> Self {
        let mut unused_import = None;
        let mut unused_input = None;
        let mut unused_declaration = None;
        let mut unused_call = None;
        let mut unnecessary_function_call = None;
        let mut using_fallback_version = None;
        let mut misleading_declaration_order = None;
        let mut meaningless_lint_directive = None;
        let mut known_rules = None;

        for rule in rules {
            let rule = rule.as_ref();
            match rule.id() {
                UnusedImportRule::ID => unused_import = Some(rule.severity()),
                UnusedInputRule::ID => unused_input = Some(rule.severity()),
                UnusedDeclarationRule::ID => unused_declaration = Some(rule.severity()),
                UnusedCallRule::ID => unused_call = Some(rule.severity()),
                UnnecessaryFunctionCall::ID => unnecessary_function_call = Some(rule.severity()),
                UsingFallbackVersion::ID => using_fallback_version = Some(rule.severity()),
                MisleadingDeclarationOrderRule::ID => {
                    misleading_declaration_order = Some(rule.severity())
                }
                MeaninglessLintDirective::ID => meaningless_lint_directive = Some(rule.severity()),
                KnownRulesRule::ID => known_rules = Some(rule.severity()),
                unrecognized => {
                    warn!(unrecognized, "unrecognized rule");
                    if cfg!(test) {
                        panic!("unrecognized rule: {unrecognized}");
                    }
                }
            }
        }

        Self {
            unused_import,
            unused_input,
            unused_declaration,
            unused_call,
            unnecessary_function_call,
            using_fallback_version,
            misleading_declaration_order,
            meaningless_lint_directive,
            known_rules,
        }
    }

    /// Returns a modified set of diagnostics that accounts for any `#@ except`
    /// comments that precede the given syntax node.
    pub fn excepted_for_node(mut self, node: &SyntaxNode) -> Self {
        let exceptions = node.rule_exceptions();

        for exception in exceptions {
            match &*exception.name {
                UnusedImportRule::ID => self.unused_import = None,
                UnusedInputRule::ID => self.unused_input = None,
                UnusedDeclarationRule::ID => self.unused_declaration = None,
                UnusedCallRule::ID => self.unused_call = None,
                UnnecessaryFunctionCall::ID => self.unnecessary_function_call = None,
                UsingFallbackVersion::ID => self.using_fallback_version = None,
                MisleadingDeclarationOrderRule::ID => self.misleading_declaration_order = None,
                MeaninglessLintDirective::ID => self.meaningless_lint_directive = None,
                KnownRulesRule::ID => self.known_rules = None,
                _ => {}
            }
        }

        self
    }

    /// Excepts all of the diagnostics.
    pub fn except_all() -> Self {
        Self {
            unused_import: None,
            unused_input: None,
            unused_declaration: None,
            unused_call: None,
            unnecessary_function_call: None,
            using_fallback_version: None,
            misleading_declaration_order: None,
            meaningless_lint_directive: None,
            known_rules: None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn custom_format_config_round_trip() {
        let custom_format_config = FormatConfig::default().trailing_commas(false);
        let analysis_config = Config::default().with_format_config(custom_format_config);
        assert_eq!(analysis_config.format(), &custom_format_config);
    }

    #[test]
    fn no_format_config_is_default() {
        let default_format_config = FormatConfig::default();
        let analysis_config = Config::default();
        assert_eq!(analysis_config.format(), &default_format_config);
    }
}