wdl-analysis 0.19.1

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
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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
//! Module for all diagnostic creation functions.

use std::fmt;

use wdl_ast::AstToken;
use wdl_ast::Diagnostic;
use wdl_ast::Ident;
use wdl_ast::Span;
use wdl_ast::SupportedVersion;
use wdl_ast::TreeNode;
use wdl_ast::TreeToken;
use wdl_ast::Version;
use wdl_ast::v1::PlaceholderOption;

use crate::UNNECESSARY_FUNCTION_CALL;
use crate::UNUSED_CALL_RULE_ID;
use crate::UNUSED_DECL_RULE_ID;
use crate::UNUSED_IMPORT_RULE_ID;
use crate::UNUSED_INPUT_RULE_ID;
use crate::types::CallKind;
use crate::types::CallType;
use crate::types::Type;
use crate::types::display_types;
use crate::types::v1::ComparisonOperator;
use crate::types::v1::NumericOperator;

/// Utility type to represent an input or an output.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Io {
    /// The I/O is an input.
    Input,
    /// The I/O is an output.
    Output,
}

impl fmt::Display for Io {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Input => write!(f, "input"),
            Self::Output => write!(f, "output"),
        }
    }
}

/// Represents the context for diagnostic reporting.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Context {
    /// The name is a namespace introduced by an imported document.
    Namespace(Span),
    /// The name is a workflow name.
    Workflow(Span),
    /// The name is a task name.
    Task(Span),
    /// The name is a struct name.
    Struct(Span),
    /// The name is a struct member name.
    StructMember(Span),
    /// The name is an enum name.
    Enum(Span),
    /// The name is an enum variant name.
    EnumVariant(Span),
    /// A name from a scope.
    Name(NameContext),
}

impl Context {
    /// Gets the span of the name.
    fn span(&self) -> Span {
        match self {
            Self::Namespace(s) => *s,
            Self::Workflow(s) => *s,
            Self::Task(s) => *s,
            Self::Struct(s) => *s,
            Self::StructMember(s) => *s,
            Self::Enum(s) => *s,
            Self::EnumVariant(s) => *s,
            Self::Name(n) => n.span(),
        }
    }
}

impl fmt::Display for Context {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Namespace(_) => write!(f, "namespace"),
            Self::Workflow(_) => write!(f, "workflow"),
            Self::Task(_) => write!(f, "task"),
            Self::Struct(_) => write!(f, "struct"),
            Self::StructMember(_) => write!(f, "struct member"),
            Self::Enum(_) => write!(f, "enum"),
            Self::EnumVariant(_) => write!(f, "enum variant"),
            Self::Name(n) => n.fmt(f),
        }
    }
}

/// Represents the context of a name in a scope.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NameContext {
    /// The name was introduced by an task or workflow input.
    Input(Span),
    /// The name was introduced by an task or workflow output.
    Output(Span),
    /// The name was introduced by a private declaration.
    Decl(Span),
    /// The name was introduced by a workflow call statement.
    Call(Span),
    /// The name was introduced by a variable in workflow scatter statement.
    ScatterVariable(Span),
}

impl NameContext {
    /// Gets the span of the name.
    pub fn span(&self) -> Span {
        match self {
            Self::Input(s) => *s,
            Self::Output(s) => *s,
            Self::Decl(s) => *s,
            Self::Call(s) => *s,
            Self::ScatterVariable(s) => *s,
        }
    }
}

impl fmt::Display for NameContext {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Input(_) => write!(f, "input"),
            Self::Output(_) => write!(f, "output"),
            Self::Decl(_) => write!(f, "declaration"),
            Self::Call(_) => write!(f, "call"),
            Self::ScatterVariable(_) => write!(f, "scatter variable"),
        }
    }
}

impl From<NameContext> for Context {
    fn from(context: NameContext) -> Self {
        Self::Name(context)
    }
}

/// Creates a "name conflict" diagnostic.
pub fn name_conflict(name: &str, conflicting: Context, first: Context) -> Diagnostic {
    Diagnostic::error(format!("conflicting {conflicting} name `{name}`"))
        .with_label(
            format!("this {conflicting} conflicts with a previously used name"),
            conflicting.span(),
        )
        .with_label(
            format!("the {first} with the conflicting name is here"),
            first.span(),
        )
}

/// Constructs a "cannot index" diagnostic.
pub fn cannot_index(actual: &Type, span: Span) -> Diagnostic {
    Diagnostic::error("indexing is only allowed on `Array` and `Map` types")
        .with_label(format!("this is {actual:#}"), span)
}

/// Creates an "unknown name" diagnostic.
pub fn unknown_name(name: &str, span: Span) -> Diagnostic {
    // Handle special case names here
    let message = match name {
        "task" => "the `task` variable may only be used within a task command section or task \
                   output section using WDL 1.2 or later, or within a task requirements, task \
                   hints, or task runtime section using WDL 1.3 or later"
            .to_string(),
        _ => format!("unknown name `{name}`"),
    };

    Diagnostic::error(message).with_highlight(span)
}

/// Creates a "self-referential" diagnostic.
pub fn self_referential(name: &str, span: Span, reference: Span) -> Diagnostic {
    Diagnostic::error(format!("declaration of `{name}` is self-referential"))
        .with_label("self-reference is here", reference)
        .with_highlight(span)
}

/// Creates a "task reference cycle" diagnostic.
pub fn task_reference_cycle(
    from: &impl fmt::Display,
    from_span: Span,
    to: &str,
    to_span: Span,
) -> Diagnostic {
    Diagnostic::error("a name reference cycle was detected")
        .with_label(
            format!("ensure this expression does not directly or indirectly refer to {from}"),
            to_span,
        )
        .with_label(format!("a reference back to `{to}` is here"), from_span)
}

/// Creates a "workflow reference cycle" diagnostic.
pub fn workflow_reference_cycle(
    from: &impl fmt::Display,
    from_span: Span,
    to: &str,
    to_span: Span,
) -> Diagnostic {
    Diagnostic::error("a name reference cycle was detected")
        .with_label(format!("this name depends on {from}"), to_span)
        .with_label(format!("a reference back to `{to}` is here"), from_span)
}

/// Creates a "call conflict" diagnostic.
pub fn call_conflict<T: TreeToken>(
    name: &Ident<T>,
    first: NameContext,
    suggest_fix: bool,
) -> Diagnostic {
    let diagnostic = Diagnostic::error(format!(
        "conflicting call name `{name}`",
        name = name.text()
    ))
    .with_label(
        "this call name conflicts with a previously used name",
        name.span(),
    )
    .with_label(
        format!("the {first} with the conflicting name is here"),
        first.span(),
    );

    if suggest_fix {
        diagnostic.with_fix("add an `as` clause to the call to specify a different name")
    } else {
        diagnostic
    }
}

/// Creates a "namespace conflict" diagnostic.
pub fn namespace_conflict(
    name: &str,
    conflicting: Span,
    first: Span,
    suggest_fix: bool,
) -> Diagnostic {
    let diagnostic = Diagnostic::error(format!("conflicting import namespace `{name}`"))
        .with_label("this conflicts with another import namespace", conflicting)
        .with_label(
            "the conflicting import namespace was introduced here",
            first,
        );

    if suggest_fix {
        diagnostic.with_fix("add an `as` clause to the import to specify a namespace")
    } else {
        diagnostic
    }
}

/// Creates an "unknown namespace" diagnostic.
pub fn unknown_namespace<T: TreeToken>(ns: &Ident<T>) -> Diagnostic {
    Diagnostic::error(format!("unknown namespace `{ns}`", ns = ns.text())).with_highlight(ns.span())
}

/// Creates an "only one namespace" diagnostic.
pub fn only_one_namespace(span: Span) -> Diagnostic {
    Diagnostic::error("only one namespace may be specified in a call statement")
        .with_highlight(span)
}

/// Creates an "import cycle" diagnostic.
pub fn import_cycle(span: Span) -> Diagnostic {
    Diagnostic::error("import introduces a dependency cycle")
        .with_label("this import has been skipped to break the cycle", span)
}

/// Creates an "import failure" diagnostic.
pub fn import_failure(uri: &str, error: &anyhow::Error, span: Span) -> Diagnostic {
    Diagnostic::error(format!("failed to import `{uri}`: {error:#}")).with_highlight(span)
}

/// Creates an "incompatible import" diagnostic.
pub fn incompatible_import(
    import_version: &str,
    import_span: Span,
    importer_version: &Version,
) -> Diagnostic {
    Diagnostic::error("imported document has incompatible version")
        .with_label(
            format!("the imported document is version `{import_version}`"),
            import_span,
        )
        .with_label(
            format!(
                "the importing document is version `{version}`",
                version = importer_version.text()
            ),
            importer_version.span(),
        )
}

/// Creates an "import missing version" diagnostic.
pub fn import_missing_version(span: Span) -> Diagnostic {
    Diagnostic::error("imported document is missing a version statement").with_highlight(span)
}

/// Creates an "invalid relative import" diagnostic.
pub fn invalid_relative_import(error: &url::ParseError, span: Span) -> Diagnostic {
    Diagnostic::error(format!("{error:#}")).with_highlight(span)
}

/// Creates a "struct not in document" diagnostic.
pub fn struct_not_in_document<T: TreeToken>(name: &Ident<T>) -> Diagnostic {
    Diagnostic::error(format!(
        "a struct named `{name}` does not exist in the imported document",
        name = name.text()
    ))
    .with_label("this struct does not exist", name.span())
}

/// Creates an "imported struct conflict" diagnostic.
pub fn imported_struct_conflict(
    name: &str,
    conflicting: Span,
    first: Span,
    suggest_fix: bool,
) -> Diagnostic {
    let diagnostic = Diagnostic::error(format!("conflicting struct name `{name}`"))
        .with_label(
            "this import introduces a conflicting definition",
            conflicting,
        )
        .with_label("the first definition was introduced by this import", first);

    if suggest_fix {
        diagnostic.with_fix("add an `alias` clause to the import to specify a different name")
    } else {
        diagnostic
    }
}

/// Creates a "struct conflicts with import" diagnostic.
pub fn struct_conflicts_with_import(name: &str, conflicting: Span, import: Span) -> Diagnostic {
    Diagnostic::error(format!("conflicting struct name `{name}`"))
        .with_label("this name conflicts with an imported struct", conflicting)
        .with_label("the import that introduced the struct is here", import)
        .with_fix(
            "either rename the struct or use an `alias` clause on the import with a different name",
        )
}

/// Creates an "imported enum conflict" diagnostic.
pub fn imported_enum_conflict(
    name: &str,
    conflicting: Span,
    first: Span,
    suggest_fix: bool,
) -> Diagnostic {
    let diagnostic = Diagnostic::error(format!("conflicting enum name `{name}`"))
        .with_label(
            "this import introduces a conflicting definition",
            conflicting,
        )
        .with_label("the first definition was introduced by this import", first);

    if suggest_fix {
        diagnostic.with_fix("add an `alias` clause to the import to specify a different name")
    } else {
        diagnostic
    }
}

/// Creates an "enum conflicts with import" diagnostic.
pub fn enum_conflicts_with_import(name: &str, conflicting: Span, import: Span) -> Diagnostic {
    Diagnostic::error(format!("conflicting enum name `{name}`"))
        .with_label("this name conflicts with an imported enum", conflicting)
        .with_label("the import that introduced the enum is here", import)
        .with_fix(
            "either rename the enum or use an `alias` clause on the import with a different name",
        )
}

/// Creates a "duplicate workflow" diagnostic.
pub fn duplicate_workflow<T: TreeToken>(name: &Ident<T>, first: Span) -> Diagnostic {
    Diagnostic::error(format!(
        "cannot define workflow `{name}` as only one workflow is allowed per source file",
        name = name.text(),
    ))
    .with_label("consider moving this workflow to a new file", name.span())
    .with_label("first workflow is defined here", first)
}

/// Creates a "recursive struct" diagnostic.
pub fn recursive_struct(name: &str, span: Span, member: Span) -> Diagnostic {
    Diagnostic::error(format!("struct `{name}` has a recursive definition"))
        .with_highlight(span)
        .with_label("this struct member participates in the recursion", member)
}

/// Creates an "unknown type" diagnostic.
pub fn unknown_type(name: &str, span: Span) -> Diagnostic {
    Diagnostic::error(format!("unknown type name `{name}`")).with_highlight(span)
}

/// Creates a "type mismatch" diagnostic.
pub fn type_mismatch(
    expected: &Type,
    expected_span: Span,
    actual: &Type,
    actual_span: Span,
) -> Diagnostic {
    Diagnostic::error(format!(
        "type mismatch: expected {expected:#}, but found {actual:#}"
    ))
    .with_label(format!("this is {actual:#}"), actual_span)
    .with_label(format!("this expects {expected:#}"), expected_span)
}

/// Creates a "non-empty array assignment" diagnostic.
pub fn non_empty_array_assignment(expected_span: Span, actual_span: Span) -> Diagnostic {
    Diagnostic::error("cannot assign an empty array to a non-empty array type")
        .with_label("this is an empty array", actual_span)
        .with_label("this expects a non-empty array", expected_span)
}

/// Creates a "call input type mismatch" diagnostic.
pub fn call_input_type_mismatch<T: TreeToken>(
    name: &Ident<T>,
    expected: &Type,
    actual: &Type,
) -> Diagnostic {
    Diagnostic::error(format!(
        "type mismatch: expected {expected:#}, but found {actual:#}",
    ))
    .with_label(
        format!(
            "input `{name}` is {expected:#}, but name `{name}` is {actual:#}",
            name = name.text(),
        ),
        name.span(),
    )
}

/// Creates a "no common type" diagnostic for arrays, maps, and scope unions.
///
/// This is called if the elements of a map or an array do not have a common
/// type.
pub fn no_common_type(
    expected: &Type,
    expected_span: Span,
    actual: &Type,
    actual_span: Span,
) -> Diagnostic {
    Diagnostic::error(format!(
        "type mismatch: a type common to both {expected:#} and {actual:#} does not exist"
    ))
    .with_label(format!("this is {actual:#}"), actual_span)
    .with_label(
        format!("this and all prior elements had a common {expected:#}"),
        expected_span,
    )
}

/// Creates a "multiple type mismatch" diagnostic.
pub fn multiple_type_mismatch(
    expected: &[Type],
    expected_span: Span,
    actual: &Type,
    actual_span: Span,
) -> Diagnostic {
    Diagnostic::error(format!(
        "type mismatch: expected {expected:#}, but found {actual:#}",
        expected = display_types(expected),
    ))
    .with_label(format!("this is {actual:#}"), actual_span)
    .with_label(
        format!(
            "this expects {expected:#}",
            expected = display_types(expected)
        ),
        expected_span,
    )
}

/// Creates a "not a task member" diagnostic.
pub fn not_a_task_member<T: TreeToken>(member: &Ident<T>) -> Diagnostic {
    Diagnostic::error(format!(
        "the `task` variable does not have a member named `{member}`",
        member = member.text()
    ))
    .with_highlight(member.span())
}

/// Creates a "not a task.previous member" diagnostic.
pub fn not_a_previous_task_data_member<T: TreeToken>(member: &Ident<T>) -> Diagnostic {
    Diagnostic::error(format!(
        "`task.previous` does not have a member named `{member}`",
        member = member.text()
    ))
    .with_highlight(member.span())
}

/// Creates a "not a struct" diagnostic.
pub fn not_a_struct<T: TreeToken>(member: &Ident<T>, input: bool) -> Diagnostic {
    Diagnostic::error(format!(
        "{kind} `{member}` is not a struct",
        kind = if input { "input" } else { "struct member" },
        member = member.text()
    ))
    .with_highlight(member.span())
}

/// Creates a "not a struct member" diagnostic.
pub fn not_a_struct_member<T: TreeToken>(name: &str, member: &Ident<T>) -> Diagnostic {
    Diagnostic::error(format!(
        "struct `{name}` does not have a member named `{member}`",
        member = member.text()
    ))
    .with_highlight(member.span())
}

/// Creates a "not an enum variant" diagnostic.
pub fn not_an_enum_variant<T: TreeToken>(name: &str, variant: &Ident<T>) -> Diagnostic {
    Diagnostic::error(format!(
        "enum `{name}` does not have a variant named `{variant}`",
        variant = variant.text()
    ))
    .with_highlight(variant.span())
}

/// Creates a "non-literal enum value" diagnostic.
pub fn non_literal_enum_value(span: Span) -> Diagnostic {
    Diagnostic::error("enum variant value must be a literal expression")
        .with_highlight(span)
        .with_fix(
            "enum values must be literal expressions only (string literals, numeric literals, \
             collection literals, or struct literals); string interpolation, variable references, \
             and computed expressions are not allowed",
        )
}

/// Creates a "not a pair accessor" diagnostic.
pub fn not_a_pair_accessor<T: TreeToken>(name: &Ident<T>) -> Diagnostic {
    Diagnostic::error(format!(
        "cannot access a pair with name `{name}`",
        name = name.text()
    ))
    .with_highlight(name.span())
    .with_fix("use `left` or `right` to access a pair")
}

/// Creates a "missing struct members" diagnostic.
pub fn missing_struct_members<T: TreeToken>(
    name: &Ident<T>,
    count: usize,
    members: &str,
) -> Diagnostic {
    Diagnostic::error(format!(
        "struct `{name}` requires a value for member{s} {members}",
        name = name.text(),
        s = if count > 1 { "s" } else { "" },
    ))
    .with_highlight(name.span())
}

/// Creates a "map key not primitive" diagnostic.
pub fn map_key_not_primitive(span: Span, actual: &Type) -> Diagnostic {
    Diagnostic::error("expected map key to be a non-optional primitive type")
        .with_highlight(span)
        .with_label(format!("this is {actual:#}"), span)
}

/// Creates a "if conditional mismatch" diagnostic.
pub fn if_conditional_mismatch(actual: &Type, actual_span: Span) -> Diagnostic {
    Diagnostic::error(format!(
        "type mismatch: expected `if` conditional expression to be type `Boolean`, but found \
         {actual:#}"
    ))
    .with_label(format!("this is {actual:#}"), actual_span)
}

/// Creates an "else if not supported" diagnostic.
pub fn else_if_not_supported(version: SupportedVersion, span: Span) -> Diagnostic {
    Diagnostic::error(format!(
        "`else if` conditional clauses are not supported in WDL v{version}"
    ))
    .with_label("this `else if` is not supported", span)
    .with_fix("use WDL v1.3 or higher to use `else if` conditional clauses")
}

/// Creates an "else not supported" diagnostic.
pub fn else_not_supported(version: SupportedVersion, span: Span) -> Diagnostic {
    Diagnostic::error(format!(
        "`else` conditional clauses are not supported in WDL v{version}"
    ))
    .with_label("this `else` is not supported", span)
    .with_fix("use WDL v1.3 or higher to use `else` conditional clauses")
}

/// Creates an "enum not supported" diagnostic.
pub fn enum_not_supported(version: SupportedVersion, span: Span) -> Diagnostic {
    Diagnostic::error(format!("enums are not supported in WDL v{version}"))
        .with_label("this enum is not supported", span)
        .with_fix("use WDL v1.3 or higher to use enums")
}

/// Creates a "logical not mismatch" diagnostic.
pub fn logical_not_mismatch(actual: &Type, actual_span: Span) -> Diagnostic {
    Diagnostic::error(format!(
        "type mismatch: expected `logical not` operand to be type `Boolean`, but found {actual:#}"
    ))
    .with_label(format!("this is {actual:#}"), actual_span)
}

/// Creates a "negation mismatch" diagnostic.
pub fn negation_mismatch(actual: &Type, actual_span: Span) -> Diagnostic {
    Diagnostic::error(format!(
        "type mismatch: expected negation operand to be type `Int` or `Float`, but found \
         {actual:#}"
    ))
    .with_label(format!("this is {actual:#}"), actual_span)
}

/// Creates a "logical or mismatch" diagnostic.
pub fn logical_or_mismatch(actual: &Type, actual_span: Span) -> Diagnostic {
    Diagnostic::error(format!(
        "type mismatch: expected `logical or` operand to be type `Boolean`, but found {actual:#}"
    ))
    .with_label(format!("this is {actual:#}"), actual_span)
}

/// Creates a "logical and mismatch" diagnostic.
pub fn logical_and_mismatch(actual: &Type, actual_span: Span) -> Diagnostic {
    Diagnostic::error(format!(
        "type mismatch: expected `logical and` operand to be type `Boolean`, but found {actual:#}"
    ))
    .with_label(format!("this is {actual:#}"), actual_span)
}

/// Creates a "comparison mismatch" diagnostic.
pub fn comparison_mismatch(
    op: ComparisonOperator,
    span: Span,
    lhs: &Type,
    lhs_span: Span,
    rhs: &Type,
    rhs_span: Span,
) -> Diagnostic {
    Diagnostic::error(format!(
        "type mismatch: operator `{op}` cannot compare {lhs:#} to {rhs:#}"
    ))
    .with_highlight(span)
    .with_label(format!("this is {lhs:#}"), lhs_span)
    .with_label(format!("this is {rhs:#}"), rhs_span)
}

/// Creates a "numeric mismatch" diagnostic.
pub fn numeric_mismatch(
    op: NumericOperator,
    span: Span,
    lhs: &Type,
    lhs_span: Span,
    rhs: &Type,
    rhs_span: Span,
) -> Diagnostic {
    Diagnostic::error(format!(
        "type mismatch: {op} operator is not supported for {lhs:#} and {rhs:#}"
    ))
    .with_highlight(span)
    .with_label(format!("this is {lhs:#}"), lhs_span)
    .with_label(format!("this is {rhs:#}"), rhs_span)
}

/// Creates a "string concat mismatch" diagnostic.
pub fn string_concat_mismatch(actual: &Type, actual_span: Span) -> Diagnostic {
    Diagnostic::error(format!(
        "type mismatch: string concatenation is not supported for {actual:#}"
    ))
    .with_label(format!("this is {actual:#}"), actual_span)
}

/// Creates an "unknown function" diagnostic.
pub fn unknown_function(name: &str, span: Span) -> Diagnostic {
    Diagnostic::error(format!("unknown function `{name}`")).with_label(
        "the WDL standard library does not have a function with this name",
        span,
    )
}

/// Creates an "unsupported function" diagnostic.
pub fn unsupported_function(minimum: SupportedVersion, name: &str, span: Span) -> Diagnostic {
    Diagnostic::error(format!(
        "this use of function `{name}` requires a minimum WDL version of {minimum}"
    ))
    .with_highlight(span)
}

/// Creates a "too few arguments" diagnostic.
pub fn too_few_arguments(name: &str, span: Span, minimum: usize, count: usize) -> Diagnostic {
    Diagnostic::error(format!(
        "function `{name}` requires at least {minimum} argument{s} but {count} {v} supplied",
        s = if minimum == 1 { "" } else { "s" },
        v = if count == 1 { "was" } else { "were" },
    ))
    .with_highlight(span)
}

/// Creates a "too many arguments" diagnostic.
pub fn too_many_arguments(
    name: &str,
    span: Span,
    maximum: usize,
    count: usize,
    excessive: impl Iterator<Item = Span>,
) -> Diagnostic {
    let mut diagnostic = Diagnostic::error(format!(
        "function `{name}` requires no more than {maximum} argument{s} but {count} {v} supplied",
        s = if maximum == 1 { "" } else { "s" },
        v = if count == 1 { "was" } else { "were" },
    ))
    .with_highlight(span);

    for span in excessive {
        diagnostic = diagnostic.with_label("this argument is unexpected", span);
    }

    diagnostic
}

/// Constructs an "argument type mismatch" diagnostic.
pub fn argument_type_mismatch(name: &str, expected: &str, actual: &Type, span: Span) -> Diagnostic {
    Diagnostic::error(format!(
        "type mismatch: argument to function `{name}` expects {expected}, but found {actual:#}"
    ))
    .with_label(format!("this is {actual:#}"), span)
}

/// Constructs an "ambiguous argument" diagnostic.
pub fn ambiguous_argument(name: &str, span: Span, first: &str, second: &str) -> Diagnostic {
    Diagnostic::error(format!(
        "ambiguous call to function `{name}` with conflicting signatures `{first}` and `{second}`",
    ))
    .with_highlight(span)
}

/// Constructs an "index type mismatch" diagnostic.
pub fn index_type_mismatch(expected: &Type, actual: &Type, span: Span) -> Diagnostic {
    Diagnostic::error(format!(
        "type mismatch: expected index to be {expected:#}, but found {actual:#}"
    ))
    .with_label(format!("this is {actual:#}"), span)
}

/// Constructs an "type is not array" diagnostic.
pub fn type_is_not_array(actual: &Type, span: Span) -> Diagnostic {
    Diagnostic::error(format!(
        "type mismatch: expected an array type, but found {actual:#}"
    ))
    .with_label(format!("this is {actual:#}"), span)
}

/// Constructs a "cannot access" diagnostic.
pub fn cannot_access(actual: &Type, actual_span: Span) -> Diagnostic {
    Diagnostic::error(format!("cannot access {actual:#}"))
        .with_label(format!("this is {actual:#}"), actual_span)
}

/// Constructs a "cannot coerce to string" diagnostic.
pub fn cannot_coerce_to_string(actual: &Type, span: Span) -> Diagnostic {
    Diagnostic::error(format!("cannot coerce {actual:#} to type `String`"))
        .with_label(format!("this is {actual:#}"), span)
}

/// Creates an "unknown task or workflow" diagnostic.
pub fn unknown_task_or_workflow(namespace: Option<Span>, name: &str, span: Span) -> Diagnostic {
    let mut diagnostic =
        Diagnostic::error(format!("unknown task or workflow `{name}`")).with_highlight(span);

    if let Some(namespace) = namespace {
        diagnostic = diagnostic.with_label(
            format!("this namespace does not have a task or workflow named `{name}`"),
            namespace,
        );
    }

    diagnostic
}

/// Creates an "unknown call input/output" diagnostic.
pub fn unknown_call_io<T: TreeToken>(call: &CallType, name: &Ident<T>, io: Io) -> Diagnostic {
    Diagnostic::error(format!(
        "{kind} `{call}` does not have an {io} named `{name}`",
        kind = call.kind(),
        call = call.name(),
        name = name.text(),
    ))
    .with_highlight(name.span())
}

/// Creates an "unknown task input/output name" diagnostic.
pub fn unknown_task_io<T: TreeToken>(task_name: &str, name: &Ident<T>, io: Io) -> Diagnostic {
    Diagnostic::error(format!(
        "task `{task_name}` does not have an {io} named `{name}`",
        name = name.text(),
    ))
    .with_highlight(name.span())
}

/// Creates a "recursive workflow call" diagnostic.
pub fn recursive_workflow_call(name: &str, span: Span) -> Diagnostic {
    Diagnostic::error(format!("cannot recursively call workflow `{name}`")).with_highlight(span)
}

/// Creates a "missing call input" diagnostic.
pub fn missing_call_input<T: TreeToken>(
    kind: CallKind,
    target: &Ident<T>,
    input: &str,
    nested_inputs_allowed: bool,
) -> Diagnostic {
    let message = format!(
        "missing required call input `{input}` for {kind} `{target}`",
        target = target.text(),
    );

    if nested_inputs_allowed {
        Diagnostic::warning(message).with_highlight(target.span())
    } else {
        Diagnostic::error(message).with_highlight(target.span())
    }
}

/// Creates an "unused import" diagnostic.
pub fn unused_import(name: &str, span: Span) -> Diagnostic {
    Diagnostic::warning(format!("unused import namespace `{name}`"))
        .with_rule(UNUSED_IMPORT_RULE_ID)
        .with_highlight(span)
}

/// Creates an "unused input" diagnostic.
pub fn unused_input(name: &str, span: Span) -> Diagnostic {
    Diagnostic::warning(format!("unused input `{name}`"))
        .with_rule(UNUSED_INPUT_RULE_ID)
        .with_highlight(span)
}

/// Creates an "unused declaration" diagnostic.
pub fn unused_declaration(name: &str, span: Span) -> Diagnostic {
    Diagnostic::warning(format!("unused declaration `{name}`"))
        .with_rule(UNUSED_DECL_RULE_ID)
        .with_highlight(span)
}

/// Creates an "unused call" diagnostic.
pub fn unused_call(name: &str, span: Span) -> Diagnostic {
    Diagnostic::warning(format!("unused call `{name}`"))
        .with_rule(UNUSED_CALL_RULE_ID)
        .with_highlight(span)
}

/// Creates an "unnecessary function call" diagnostic.
pub fn unnecessary_function_call(
    name: &str,
    span: Span,
    label: &str,
    label_span: Span,
) -> Diagnostic {
    Diagnostic::warning(format!("unnecessary call to function `{name}`"))
        .with_rule(UNNECESSARY_FUNCTION_CALL)
        .with_highlight(span)
        .with_label(label.to_string(), label_span)
}

/// Generates a diagnostic error message when a placeholder option has a type
/// mismatch.
pub fn invalid_placeholder_option<N: TreeNode>(
    ty: &Type,
    span: Span,
    option: &PlaceholderOption<N>,
) -> Diagnostic {
    let message = match option {
        PlaceholderOption::Sep(_) => format!(
            "type mismatch for placeholder option `sep`: expected type `Array[P]` where P: any \
             primitive type, but found {ty:#}"
        ),
        PlaceholderOption::Default(_) => format!(
            "type mismatch for placeholder option `default`: expected any primitive type, but \
             found {ty:#}"
        ),
        PlaceholderOption::TrueFalse(_) => format!(
            "type mismatch for placeholder option `true/false`: expected type `Boolean`, but \
             found {ty:#}"
        ),
    };

    Diagnostic::error(message).with_label(format!("this is {ty:#}"), span)
}

/// Creates an invalid regex pattern diagnostic.
pub fn invalid_regex_pattern(
    function: &str,
    pattern: &str,
    error: &regex::Error,
    span: Span,
) -> Diagnostic {
    Diagnostic::error(format!(
        "invalid regular expression `{pattern}` used in function `{function}`: {error}"
    ))
    .with_label("invalid regular expression", span)
}

/// Creates a "not a custom type" diagnostic.
pub fn not_a_custom_type<T: TreeToken>(name: &Ident<T>) -> Diagnostic {
    Diagnostic::error(format!("`{}` is not a custom type", name.text())).with_label(
        "only struct and enum types can be referenced as values",
        name.span(),
    )
}

/// Creates a "no common inferred type for enum" diagnostic.
///
/// This diagnostic occurs during enum type calculation when no common type can
/// be inferred from the variant types.
pub fn no_common_inferred_type_for_enum(
    enum_name: &str,
    common_type: &Type,
    common_span: Span,
    discordant_type: &Type,
    discordant_span: Span,
) -> Diagnostic {
    Diagnostic::error(format!("cannot infer a common type for enum `{enum_name}`"))
        .with_label(
            format!(
                "this is the first variant with {discordant_type:#} that has no common type with \
                 {common_type:#}"
            ),
            discordant_span,
        )
        .with_label(
            format!("this is the last variant with a common {common_type:#}"),
            common_span,
        )
}

/// Creates an "enum variant does not coerce to type" diagnostic.
pub fn enum_variant_does_not_coerce_to_type(
    enum_name: &str,
    enum_span: Span,
    variant_name: &str,
    variant_span: Span,
    expected: &Type,
    actual: &Type,
) -> Diagnostic {
    Diagnostic::error(format!(
        "cannot coerce variant `{variant_name}` in enum `{enum_name}` from {actual:#} to \
         {expected:#}"
    ))
    .with_label(format!("this is the `{enum_name}` enum"), enum_span)
    .with_label(
        format!("this is the `{variant_name}` variant"),
        variant_span,
    )
    .with_fix(format!(
        "change the value to something that coerces to {expected:#} or explicitly set the enum's \
         inner type"
    ))
}