File: DiagnosticMessage.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (697 lines) | stat: -rw-r--r-- 28,400 bytes parent folder | download
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
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2023 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for Swift project authors
//

import SwiftDiagnostics
import SwiftSyntax
import SwiftSyntaxMacros
import SwiftSyntaxMacroExpansion

/// A type describing diagnostic messages emitted by this module's macro during
/// evaluation.
struct DiagnosticMessage: SwiftDiagnostics.DiagnosticMessage {
  /// Create a diagnostic message for the macro with the specified name
  /// stating that its condition will always pass or fail.
  ///
  /// - Parameters:
  ///   - condition: The condition expression being diagnosed.
  ///   - value: The value that this condition always evaluates to.
  ///   - macro: The macro expression.
  ///
  /// - Returns: A diagnostic message.
  static func condition(_ condition: ExprSyntax, isAlways value: Bool, in macro: some FreestandingMacroExpansionSyntax) -> Self {
    let action = value ? "pass" : "fail"
    return Self(
      syntax: Syntax(condition),
      message: "\(_macroName(macro)) will always \(action) here; use 'Bool(\(condition))' to silence this warning",
      severity: value ? .note : .warning
    )
  }

  /// Create a diagnostic message stating that a macro should be used with
  /// `as?`, not `as!`.
  ///
  /// - Parameters:
  ///   - expr: The `as!` expression being diagnosed.
  ///   - macro: The macro expression.
  ///
  /// - Returns: A diagnostic message.
  static func asExclamationMarkIsEvaluatedEarly(_ expr: AsExprSyntax, in macro: some FreestandingMacroExpansionSyntax) -> Self {
    return Self(
      syntax: Syntax(expr.asKeyword),
      message: "Expression '\(expr.trimmed)' will be evaluated before \(_macroName(macro)) is invoked; use 'as?' instead of 'as!' to silence this warning",
      severity: .warning
    )
  }

  /// Get the human-readable name of the given freestanding macro.
  ///
  /// - Parameters:
  ///   - macro: The freestanding macro node to name.
  ///
  /// - Returns: The name of the macro as understood by a developer, such as
  ///   `"'#expect(_:_:)'"`. Includes single quotes.
  private static func _macroName(_ macro: some FreestandingMacroExpansionSyntax) -> String {
    var labels = ["_", "_"]
    if let firstArgumentLabel = macro.arguments.first?.label?.textWithoutBackticks {
      labels[0] = firstArgumentLabel
    }
    let argumentLabels = labels.map { "\($0):" }.joined()
    return "'#\(macro.macroName.textWithoutBackticks)(\(argumentLabels))'"
  }

  /// Get the human-readable name of the given attached macro.
  ///
  /// - Parameters:
  ///   - attribute: The attached macro node to name.
  ///
  /// - Returns: The name of the macro as understood by a developer, such as
  ///   `"'@Test'"`. Include single quotes.
  private static func _macroName(_ attribute: AttributeSyntax) -> String {
    // SEE: https://github.com/swiftlang/swift/blob/main/docs/Diagnostics.md?plain=1#L44
    "'\(attribute.attributeNameText)'"
  }

  /// Get a string corresponding to the specified syntax node (for instance,
  /// `"function"` for a function declaration.)
  ///
  /// - Parameters:
  ///   - node: The node of interest.
  ///   - includeA: Whether or not to include "a" or "an".
  ///
  /// - Returns: A string describing the kind of `node`, or `"symbol"` in the
  ///   fallback case.
  private static func _kindString(for node: some SyntaxProtocol, includeA: Bool = false) -> String {
    let result: (value: String, article: String)
    switch node.kind {
    case .functionDecl:
      result = ("function", "a")
    case .classDecl:
      result = ("class", "a")
    case .structDecl:
      result = ("structure", "a")
    case .enumDecl:
      result = ("enumeration", "an")
    case .actorDecl:
      result = ("actor", "an")
    case .variableDecl:
      // This string could be "variable" in some contexts but none we're
      // currently looking at.
      result = ("property", "a")
    case .initializerDecl:
      result = ("initializer", "an")
    case .deinitializerDecl:
      result = ("deinitializer", "a")
    case .subscriptDecl:
      result = ("subscript", "a")
    case .enumCaseDecl:
      result = ("enumeration case", "an")
    case .typeAliasDecl:
      result = ("typealias", "a")
    case .macroDecl:
      result = ("macro", "a")
    case .protocolDecl:
      result = ("protocol", "a")
    case .closureExpr:
      result = ("closure", "a")
    default:
      result = ("declaration", "this")
    }

    if includeA {
      return "\(result.article) \(result.value)"
    }
    return result.value
  }

  /// Create a diagnostic message stating that the `@Test` or `@Suite` attribute
  /// cannot be applied to a declaration multiple times.
  ///
  /// - Parameters:
  ///   - attributes: The conflicting attributes. This array must not be empty.
  ///   - decl: The declaration in question.
  ///
  /// - Returns: A diagnostic message.
  static func multipleAttributesNotSupported(_ attributes: [AttributeSyntax], on decl: some SyntaxProtocol) -> Self {
    precondition(!attributes.isEmpty)
    return Self(
      syntax: Syntax(attributes.last!),
      message: "Attribute \(_macroName(attributes.last!)) cannot be applied to \(_kindString(for: decl, includeA: true)) more than once",
      severity: .error
    )
  }

  /// Create a diagnostic message stating that the `@Test` or `@Suite` attribute
  /// cannot be applied to a generic declaration.
  ///
  /// - Parameters:
  ///   - decl: The generic declaration in question.
  ///   - attribute: The `@Test` or `@Suite` attribute.
  ///   - genericClause: The child node on `genericDecl` that makes it generic.
  ///   - genericDecl: The generic declaration to which `genericClause` is
  ///     attached, possibly equal to `decl`.
  ///
  /// - Returns: A diagnostic message.
  static func genericDeclarationNotSupported(_ decl: some SyntaxProtocol, whenUsing attribute: AttributeSyntax, becauseOf genericClause: some SyntaxProtocol, on genericDecl: some SyntaxProtocol) -> Self {
    if Syntax(decl) != Syntax(genericDecl), genericDecl.isProtocol((any DeclGroupSyntax).self) {
      return .containingNodeUnsupported(genericDecl, genericBecauseOf: Syntax(genericClause), whenUsing: attribute, on: decl)
    } else {
      // Avoid using a syntax node from a lexical context (it won't have source
      // location information.)
      let syntax = (genericClause.root != decl.root) ? Syntax(decl) : Syntax(genericClause)
      return Self(
        syntax: syntax,
        message: "Attribute \(_macroName(attribute)) cannot be applied to a generic \(_kindString(for: decl))",
        severity: .error
      )
    }
  }

  /// Create a diagnostic message stating that the `@Test` or `@Suite` attribute
  /// cannot be applied to a type that also has an availability attribute.
  ///
  /// - Parameters:
  ///   - availabilityAttribute: The `@available` attribute in question.
  ///   - decl: The declaration in question.
  ///   - attribute: The `@Test` or `@Suite` attribute.
  ///
  /// - Returns: A diagnostic message.
  ///
  /// - Bug: This combination of attributes requires the ability to resolve
  ///   semantic availability and fully-qualified names for types at macro
  ///   expansion time. ([104081994](rdar://104081994))
  static func availabilityAttributeNotSupported(_ availabilityAttribute: AttributeSyntax, on decl: some SyntaxProtocol, whenUsing attribute: AttributeSyntax) -> Self {
    // Avoid using a syntax node from a lexical context (it won't have source
    // location information.)
    let syntax = (availabilityAttribute.root != decl.root) ? Syntax(decl) : Syntax(availabilityAttribute)
    return Self(
      syntax: syntax,
      message: "Attribute \(_macroName(attribute)) cannot be applied to this \(_kindString(for: decl)) because it has been marked '\(availabilityAttribute.trimmed)'",
      severity: .error
    )
  }

  /// Create a diagnostic message stating that the given attribute cannot be
  /// applied to the given declaration.
  ///
  /// - Parameters:
  ///   - attribute: The `@Test` or `@Suite` attribute.
  ///   - decl: The declaration in question.
  ///
  /// - Returns: A diagnostic message.
  static func attributeNotSupported(_ attribute: AttributeSyntax, on decl: some SyntaxProtocol) -> Self {
    Self(
      syntax: Syntax(decl),
      message: "Attribute \(_macroName(attribute)) cannot be applied to \(_kindString(for: decl, includeA: true))",
      severity: .error
    )
  }

  /// Create a diagnostic message stating that the given attribute can only be
  /// applied to `static` properties.
  ///
  /// - Parameters:
  ///   - attribute: The `@Tag` attribute.
  ///   - decl: The declaration in question.
  ///
  /// - Returns: A diagnostic message.
  static func nonStaticTagDeclarationNotSupported(_ attribute: AttributeSyntax, on decl: VariableDeclSyntax) -> Self {
    var declCopy = decl
    declCopy.modifiers = DeclModifierListSyntax {
      for modifier in decl.modifiers {
        modifier
      }
      DeclModifierSyntax(name: .keyword(.static))
    }.with(\.trailingTrivia, .space)

    return Self(
      syntax: Syntax(decl),
      message: "Attribute \(_macroName(attribute)) cannot be applied to an instance property",
      severity: .error,
      fixIts: [
        FixIt(
          message: MacroExpansionFixItMessage("Add 'static'"),
          changes: [.replace(oldNode: Syntax(decl), newNode: Syntax(declCopy)),]
        ),
      ]
    )
  }

  /// Create a diagnostic message stating that the given attribute cannot be
  /// applied to global variables.
  ///
  /// - Parameters:
  ///   - decl: The declaration in question.
  ///   - attribute: The `@Tag` attribute.
  ///
  /// - Returns: A diagnostic message.
  static func nonMemberTagDeclarationNotSupported(_ decl: VariableDeclSyntax, whenUsing attribute: AttributeSyntax) -> Self {
    var declCopy = decl
    declCopy.modifiers = DeclModifierListSyntax {
      for modifier in decl.modifiers {
        modifier
      }
      DeclModifierSyntax(name: .keyword(.static))
    }.with(\.trailingTrivia, .space)
    let replacementDecl: DeclSyntax = """
    extension Tag {
      \(declCopy.trimmed)
    }
    """

    return Self(
      syntax: Syntax(decl),
      message: "Attribute \(_macroName(attribute)) cannot be applied to a global variable",
      severity: .error,
      fixIts: [
        FixIt(
          message: MacroExpansionFixItMessage("Declare in an extension to 'Tag'"),
          changes: [.replace(oldNode: Syntax(decl), newNode: Syntax(replacementDecl)),]
        ),
        FixIt(
          message: MacroExpansionFixItMessage("Remove attribute \(_macroName(attribute))"),
          changes: [.replace(oldNode: Syntax(attribute), newNode: Syntax("" as ExprSyntax))]
        ),
      ]
    )
  }

  /// Create a diagnostic message stating that the given attribute cannot be
  /// applied to global variables.
  ///
  /// - Parameters:
  ///   - attribute: The `@Tag` attribute.
  ///   - decl: The declaration in question.
  ///   - declaredType: The type of `decl` as specified by it.
  ///   - resolvedType: The _actual_ type of `decl`, if known and differing from
  ///     `declaredType` (i.e. if `type` is `Self`.)
  ///
  /// - Returns: A diagnostic message.
  static func mistypedTagDeclarationNotSupported(_ attribute: AttributeSyntax, on decl: VariableDeclSyntax, declaredType: TypeSyntax, resolvedType: TypeSyntax? = nil) -> Self {
    let resolvedType = resolvedType ?? declaredType
    return Self(
      syntax: Syntax(decl),
      message: "Attribute \(_macroName(attribute)) cannot be applied to \(_kindString(for: decl, includeA: true)) of type '\(resolvedType.trimmed)'",
      severity: .error,
      fixIts: [
        FixIt(
          message: MacroExpansionFixItMessage("Change type to 'Tag'"),
          changes: [.replace(oldNode: Syntax(declaredType), newNode: Syntax("Tag" as TypeSyntax))]
        ),
        FixIt(
          message: MacroExpansionFixItMessage("Remove attribute \(_macroName(attribute))"),
          changes: [.replace(oldNode: Syntax(attribute), newNode: Syntax("" as ExprSyntax))]
        ),
      ]
    )
  }

  /// Create a diagnostic message stating that the given attribute cannot be
  /// used within a lexical context.
  ///
  /// - Parameters:
  ///   - node: The lexical context preventing the use of `attribute`.
  ///   - genericClause: If not `nil`, a syntax node that causes `node` to be
  ///     generic.
  ///   - attribute: The `@Test` or `@Suite` attribute.
  ///   - decl: The declaration in question (contained in `node`.)
  ///
  /// - Returns: A diagnostic message.
  static func containingNodeUnsupported(_ node: some SyntaxProtocol, genericBecauseOf genericClause: Syntax? = nil, whenUsing attribute: AttributeSyntax, on decl: some SyntaxProtocol) -> Self {
    // Avoid using a syntax node from a lexical context (it won't have source
    // location information.)
    let syntax: Syntax = if let genericClause, attribute.root == genericClause.root {
      // Prefer the generic clause if available as the root cause.
      genericClause
    } else if attribute.root == node.root {
      // Second choice is the unsupported containing node.
      Syntax(node)
    } else {
      // Finally, fall back to the attribute, which we assume is not detached.
      Syntax(attribute)
    }
    let generic = if genericClause != nil {
      " generic"
    } else {
      ""
    }
    if let functionDecl = node.as(FunctionDeclSyntax.self) {
      let functionName = functionDecl.completeName
      return Self(
        syntax: syntax,
        message: "Attribute \(_macroName(attribute)) cannot be applied to \(_kindString(for: decl, includeA: true)) within\(generic) function '\(functionName)'",
        severity: .error
      )
    } else if let namedDecl = node.asProtocol((any NamedDeclSyntax).self) {
      let declName = namedDecl.name.textWithoutBackticks
      return Self(
        syntax: syntax,
        message: "Attribute \(_macroName(attribute)) cannot be applied to \(_kindString(for: decl, includeA: true)) within\(generic) \(_kindString(for: node)) '\(declName)'",
        severity: .error
      )
    } else if let extensionDecl = node.as(ExtensionDeclSyntax.self) {
      // Subtly different phrasing from the NamedDeclSyntax case above.
      let nodeKind = if genericClause != nil {
        "a generic extension to type"
      } else {
        "an extension to type"
      }
      let declGroupName = extensionDecl.extendedType.trimmedDescription
      return Self(
        syntax: syntax,
        message: "Attribute \(_macroName(attribute)) cannot be applied to \(_kindString(for: decl, includeA: true)) within \(nodeKind) '\(declGroupName)'",
        severity: .error
      )
    } else {
      let nodeKind = if genericClause != nil {
        "a generic \(_kindString(for: node))"
      } else {
        _kindString(for: node, includeA: true)
      }
      return Self(
        syntax: syntax,
        message: "Attribute \(_macroName(attribute)) cannot be applied to \(_kindString(for: decl, includeA: true)) within \(nodeKind)",
        severity: .error
      )
    }
  }

  /// Create a diagnostic message stating that the given attribute cannot be
  /// applied to the given declaration outside the scope of an extension to
  /// `Tag`.
  ///
  /// - Parameters:
  ///   - attribute: The `@Tag` attribute.
  ///   - decl: The declaration in question.
  ///
  /// - Returns: A diagnostic message.
  static func attributeNotSupportedOutsideTagExtension(_ attribute: AttributeSyntax, on decl: VariableDeclSyntax) -> Self {
    Self(
      syntax: Syntax(decl),
      message: "Attribute \(_macroName(attribute)) cannot be applied to \(_kindString(for: decl, includeA: true)) except in an extension to 'Tag'",
      severity: .error
    )
  }

  /// Create a diagnostic message stating that the given attribute has no effect
  /// when applied to the given extension declaration.
  ///
  /// - Parameters:
  ///   - attribute: The `@Test` or `@Suite` attribute.
  ///   - decl: The extension declaration in question.
  ///
  /// - Returns: A diagnostic message.
  static func attributeHasNoEffect(_ attribute: AttributeSyntax, on decl: ExtensionDeclSyntax) -> Self {
    Self(
      syntax: Syntax(decl),
      message: "Attribute \(_macroName(attribute)) has no effect when applied to an extension",
      severity: .error,
      fixIts: [
        FixIt(
          message: MacroExpansionFixItMessage("Remove attribute \(_macroName(attribute))"),
          changes: [.replace(oldNode: Syntax(attribute), newNode: Syntax("" as ExprSyntax))]
        ),
      ]
    )
  }

  /// Create a diagnostic message stating that the given attribute has the wrong
  /// number of arguments when applied to the given function declaration.
  ///
  /// - Parameters:
  ///   - attribute: The `@Test` attribute.
  ///   - functionDecl: The declaration in question.
  ///
  /// - Returns: A diagnostic message.
  static func attributeArgumentCountIncorrect(_ attribute: AttributeSyntax, on functionDecl: FunctionDeclSyntax) -> Self {
    let expectedArgumentCount = functionDecl.signature.parameterClause.parameters.count
    if expectedArgumentCount == 0 {
      return Self(
        syntax: Syntax(functionDecl),
        message: "Attribute \(_macroName(attribute)) cannot specify arguments when used with function '\(functionDecl.completeName)' because it does not take any",
        severity: .error
      )
    } else {
      return Self(
        syntax: Syntax(functionDecl),
        message: "Attribute \(_macroName(attribute)) must specify arguments when used with function '\(functionDecl.completeName)'",
        severity: .error,
        fixIts: _addArgumentsFixIts(for: attribute, given: functionDecl.signature.parameterClause.parameters)
      )
    }
  }

  /// Create fix-its for a diagnostic stating that the given attribute must
  /// specify arguments since it is applied to a function which has parameters.
  ///
  /// - Parameters:
  ///   - attribute: The `@Test` attribute.
  ///   - parameters: The parameter list of the function `attribute` is applied
  ///     to.
  ///
  /// - Returns: An array of fix-its to include in a diagnostic.
  private static func _addArgumentsFixIts(for attribute: AttributeSyntax, given parameters: FunctionParameterListSyntax) -> [FixIt] {
    let baseArguments: LabeledExprListSyntax
    if let existingArguments = attribute.arguments {
      guard case var .argumentList(existingLabeledArguments) = existingArguments else {
        // If there are existing arguments but they are of an unexpected type,
        // don't attempt to provide any fix-its.
        return []
      }

      // If the existing argument list is non-empty, ensure the last argument
      // has a trailing comma and space.
      if !existingLabeledArguments.isEmpty {
        let lastIndex = existingLabeledArguments.index(before: existingLabeledArguments.endIndex)
        existingLabeledArguments[lastIndex].trailingComma = .commaToken(trailingTrivia: .space)
      }

      baseArguments = existingLabeledArguments
    } else {
      baseArguments = .init()
    }

    var fixIts: [FixIt] = []
    func addFixIt(_ message: String, appendingArguments arguments: some Collection<LabeledExprSyntax>) {
      var newAttribute = attribute
      newAttribute.leftParen = .leftParenToken()
      newAttribute.arguments = .argumentList(baseArguments + arguments)
      let trailingTrivia = newAttribute.rightParen?.trailingTrivia
        ?? newAttribute.attributeName.as(IdentifierTypeSyntax.self)?.name.trailingTrivia
        ?? .space
      newAttribute.rightParen = .rightParenToken(trailingTrivia: trailingTrivia)
      newAttribute.attributeName = newAttribute.attributeName.trimmed

      fixIts.append(FixIt(
        message: MacroExpansionFixItMessage(message),
        changes: [.replace(oldNode: Syntax(attribute), newNode: Syntax(newAttribute))]
      ))
    }

    // Fix-It to add 'arguments:' with one collection. If the function has 2 or
    // more parameters, the elements of the placeholder collection are of tuple
    // type.
    do {
      let argumentsCollectionType = if parameters.count == 1, let parameter = parameters.first {
        "[\(parameter.baseTypeName)]"
      } else {
        "[(\(parameters.map(\.baseTypeName).joined(separator: ", ")))]"
      }

      addFixIt(
        "Add 'arguments:' with one collection",
        appendingArguments: [LabeledExprSyntax(label: "arguments", expression: EditorPlaceholderExprSyntax(type: argumentsCollectionType))]
      )
    }

    // Fix-It to add 'arguments:' with all combinations of <N> collections,
    // where <N> is the count of the function's parameters. Only offered for
    // functions with 2 parameters.
    if parameters.count == 2 {
      let additionalArguments = parameters.indices.map { index in
        let label = index == parameters.startIndex ? "arguments" : nil
        let argumentsCollectionType = "[\(parameters[index].baseTypeName)]"
        return LabeledExprSyntax(
          label: label.map { .identifier($0) },
          colon: label == nil ? nil : .colonToken(trailingTrivia: .space),
          expression: EditorPlaceholderExprSyntax(type: argumentsCollectionType),
          trailingComma: parameters.index(after: index) < parameters.endIndex ? .commaToken(trailingTrivia: .space) : nil
        )
      }
      addFixIt("Add 'arguments:' with all combinations of \(parameters.count) collections", appendingArguments: additionalArguments)
    }

    return fixIts
  }

  /// Create a diagnostic message stating that `@Test` or `@Suite` is
  /// incompatible with `XCTestCase` and its subclasses.
  ///
  /// - Parameters:
  ///   - decl: The expression or declaration referring to the unsupported
  ///     XCTest symbol.
  ///   - attribute: The `@Test` or `@Suite` attribute.
  ///
  /// - Returns: A diagnostic message.
  static func xcTestCaseNotSupported(_ decl: some SyntaxProtocol, whenUsing attribute: AttributeSyntax) -> Self {
    Self(
      syntax: Syntax(decl),
      message: "Attribute \(_macroName(attribute)) cannot be applied to a subclass of 'XCTestCase'",
      severity: .error
    )
  }

  /// Create a diagnostic message stating that a parameter to a test function
  /// cannot be marked with the given specifier (such as `inout`).
  ///
  /// - Parameters:
  ///   - specifier: The invalid specifier token.
  ///   - parameter: The incorrectly-specified parameter.
  ///   - attribute: The `@Test` or `@Suite` attribute.
  ///
  /// - Returns: A diagnostic message.
  static func specifierNotSupported(_ specifier: TokenSyntax, on parameter: FunctionParameterSyntax, whenUsing attribute: AttributeSyntax) -> Self {
    Self(
      syntax: Syntax(parameter),
      message: "Attribute \(_macroName(attribute)) cannot be applied to a function with a parameter marked '\(specifier.textWithoutBackticks)'",
      severity: .error
    )
  }

  /// Create a diagnostic message stating that a test function should not return
  /// a result.
  ///
  /// - Parameters:
  ///   - returnType: The unsupported return type.
  ///   - decl: The declaration with an unsupported return type.
  ///   - attribute: The `@Test` or `@Suite` attribute.
  ///
  /// - Returns: A diagnostic message.
  static func returnTypeNotSupported(_ returnType: TypeSyntax, on decl: some SyntaxProtocol, whenUsing attribute: AttributeSyntax) -> Self {
    Self(
      syntax: Syntax(returnType),
      message: "The result of this \(_kindString(for: decl)) will be discarded during testing",
      severity: .warning
    )
  }

  /// Create a diagnostic message stating that the expression used to declare a
  /// tag on a test or suite is not supported.
  ///
  /// - Parameters:
  ///   - tagExpr: The unsupported tag expression.
  ///   - attribute: The `@Test` or `@Suite` attribute.
  ///
  /// - Returns: A diagnostic message.
  static func tagExprNotSupported(_ tagExpr: some SyntaxProtocol, in attribute: AttributeSyntax) -> Self {
    Self(
      syntax: Syntax(tagExpr),
      message: "Tag '\(tagExpr.trimmed)' cannot be used with attribute \(_macroName(attribute)); pass a member of 'Tag' or a string literal instead",
      severity: .error
    )
  }

  /// Create a diagnostic message stating that the URL string passed to a trait
  /// is not a valid URL.
  ///
  /// - Parameters:
  ///   - urlExpr: The unsupported URL string.
  ///   - traitExpr: The trait expression containing `urlExpr`.
  ///   - attribute: The `@Test` or `@Suite` attribute.
  ///
  /// - Returns: A diagnostic message.
  static func urlExprNotValid(_ urlExpr: StringLiteralExprSyntax, in traitExpr: FunctionCallExprSyntax, in attribute: AttributeSyntax) -> Self {
    // We do not currently expect anything other than "[...].bug()" here, so
    // force-cast to MemberAccessExprSyntax to get the name of the trait.
    let traitName = traitExpr.calledExpression.cast(MemberAccessExprSyntax.self).declName
    let urlString = urlExpr.representedLiteralValue!

    return Self(
      syntax: Syntax(urlExpr),
      message: #"URL "\#(urlString)" is invalid and cannot be used with trait '\#(traitName.trimmed)' in attribute \#(_macroName(attribute))"#,
      severity: .warning,
      fixIts: [
        FixIt(
          message: MacroExpansionFixItMessage(#"Replace "\#(urlString)" with URL"#),
          changes: [.replace(oldNode: Syntax(urlExpr), newNode: Syntax(EditorPlaceholderExprSyntax("url", type: "String")))]
        ),
        FixIt(
          message: MacroExpansionFixItMessage("Remove trait '\(traitName.trimmed)'"),
          changes: [.replace(oldNode: Syntax(traitExpr), newNode: Syntax("" as ExprSyntax))]
        ),
      ]
    )
  }

  /// Create a diagnostic message stating that a trait has no effect on a given
  /// attribute (assumed to be a non-parameterized `@Test` attribute.)
  ///
  /// - Parameters:
  ///   - traitExpr: The unsupported trait expression.
  ///   - attribute: The `@Test` or `@Suite` attribute.
  ///
  /// - Returns: A diagnostic message.
  static func traitHasNoEffect(_ traitExpr: some ExprSyntaxProtocol, in attribute: AttributeSyntax) -> Self {
    Self(
      syntax: Syntax(traitExpr),
      message: "Trait '\(traitExpr.trimmed)' has no effect when used with a non-parameterized test function",
      severity: .warning
    )
  }

  /// Create a diagnostic messages stating that the expression passed to
  /// `#require()` is ambiguous.
  ///
  /// - Parameters:
  ///   - boolExpr: The ambiguous optional boolean expression.
  ///
  /// - Returns: A diagnostic message.
  static func optionalBoolExprIsAmbiguous(_ boolExpr: ExprSyntax) -> Self {
    Self(
      syntax: Syntax(boolExpr),
      message: "Requirement '\(boolExpr.trimmed)' is ambiguous",
      severity: .warning,
      fixIts: [
        FixIt(
          message: MacroExpansionFixItMessage("To unwrap an optional value, add 'as Bool?'"),
          changes: [.replace(oldNode: Syntax(boolExpr), newNode: Syntax("\(boolExpr) as Bool?" as ExprSyntax))]
        ),
        FixIt(
          message: MacroExpansionFixItMessage("To check if a value is true, add '?? false'"),
          changes: [.replace(oldNode: Syntax(boolExpr), newNode: Syntax("\(boolExpr) ?? false" as ExprSyntax))]
        ),
      ]
    )
  }

  /// Create a diagnostic message stating that a condition macro nested inside
  /// an exit test will not record any diagnostics.
  ///
  /// - Parameters:
  ///   - checkMacro: The inner condition macro invocation.
  ///   - exitTestMacro: The containing exit test macro invocation.
  ///
  /// - Returns: A diagnostic message.
  static func checkUnsupported(_ checkMacro: some FreestandingMacroExpansionSyntax, inExitTest exitTestMacro: some FreestandingMacroExpansionSyntax) -> Self {
    Self(
      syntax: Syntax(checkMacro),
      message: "Expression \(_macroName(checkMacro)) will not record an issue on failure inside exit test \(_macroName(exitTestMacro))",
      severity: .error
    )
  }

  var syntax: Syntax

  // MARK: - DiagnosticMessage

  var message: String
  var diagnosticID = MessageID(domain: "org.swift.testing", id: "macros")
  var severity: DiagnosticSeverity
  var fixIts: [FixIt] = []
}