import SwiftDiagnostics
import SwiftSyntax
import SwiftSyntaxMacros

/// Marker macro applied to module / shared-object members that should be exposed to JavaScript.
/// `@ExpoModule` and `@SharedObject` discover declarations carrying this attribute and bind each one
/// directly into the JS object, with the decode-call-encode body inlined into the binding; that part
/// of the expansion lives in those macros.
///
/// On its own, `@JS` emits one thing: a never-called peer that asserts each type crossing the JS
/// boundary is convertible in the direction it travels — arguments are `JavaScriptDecodable`, return
/// values are `JavaScriptEncodable` (a settable property's value type is both). Because it's a
/// **peer** of the marked member, a non-conforming type produces a compile error located on the
/// user's own `@JS` declaration rather than on the enclosing `@ExpoModule`. The assertion mechanism
/// itself is shared (see `directionalConformanceAssertion`); `@JS` only supplies the boundary types,
/// split by direction, that it reads off the declaration.
///
/// Usage:
///
///   @JS
///   func greet(name: String) -> String { ... }
///
///   @JS("doWork")
///   func performWork() async throws { ... }
///
///   @JS
///   var status: String { "ok" }
///
///   @JS(.cached)
///   var cacheDir: String { ... }
///
///   @JS(symbol: .iterator)
///   func makeIterator() -> JavaScriptObject { ... }
///
///   @JS(symbol: "app.id")
///   var id: String { ... }
public struct JSMacro: PeerMacro {
  public static func expansion(
    of node: AttributeSyntax,
    providingPeersOf declaration: some DeclSyntaxProtocol,
    in context: some MacroExpansionContext
  ) throws -> [DeclSyntax] {
    diagnosePlacement(of: node, on: declaration, in: context)
    if let genericParameterClause = jsGenericParameterClause(of: declaration) {
      context.diagnose(
        Diagnostic(
          node: genericParameterClause,
          message: JSDiagnosticMessage(
            "A @JS function or initializer can't be generic: the binding decodes each argument and encodes the result by its static type, which a generic parameter doesn't have. Use a concrete type, a @Union of the types, or 'JavaScriptValue'",
            id: "js-generic-member",
            severity: .error
          )
        )
      )
      return []
    }
    diagnoseParameterSpecifiers(in: declaration, in: context)
    diagnoseFreeFormTypes(in: declaration, in: context)
    diagnoseClosureTypes(in: declaration, in: context)
    diagnoseConcurrentOption(of: node, on: declaration, in: context)
    diagnoseAsyncVariantOption(of: node, on: declaration, in: context)
    diagnoseCachedOption(of: node, on: declaration, in: context)
    diagnoseJavaScriptValuesOffThread(of: node, on: declaration, in: context)
    diagnoseRuntimeParameter(of: node, on: declaration, in: context)
    diagnoseSymbolArgument(of: node, on: declaration, in: context)

    // In an `@ExpoModule` or `@SharedObject` class, the class macro emits the assertion instead: it sees
    // the type aliases declared in the class body, which this macro can't (see `TupleTypeAliases`).
    guard !isInBindingClass(context), let assertion = jsConformanceAssertion(for: declaration) else {
      return []
    }
    return [assertion]
  }
}

/// The conformance-assertion peer for a `@JS` member, or `nil` when the member has no type to assert.
private func jsConformanceAssertion(for declaration: some DeclSyntaxProtocol) -> DeclSyntax? {
  guard let member = boundaryMember(of: declaration) else {
    return nil
  }
  return directionalConformanceAssertion(name: member.name, types: member.types, isStatic: member.isStatic)
}

/// The conformance assertion of a `@JS` member, for an `@ExpoModule` or `@SharedObject` class to fold
/// into its `_assertTypesConformance()` (see `classConformanceAssertions`), or `nil` when the member has
/// no type to assert.
internal func jsConformanceAssertionBody(for declaration: some DeclSyntaxProtocol) -> MemberConformanceAssertion? {
  guard let member = boundaryMember(of: declaration) else {
    return nil
  }
  return memberConformanceAssertion(name: member.name, types: member.types)
}

/// True when the member is declared directly in an `@ExpoModule` or `@SharedObject` class, whose macro
/// binds it.
private func isInBindingClass(_ context: some MacroExpansionContext) -> Bool {
  guard let classDecl = context.lexicalContext.first?.as(ClassDeclSyntax.self) else {
    return false
  }
  return classDecl.attributes.firstAttribute(named: "ExpoModule") != nil
    || classDecl.attributes.firstAttribute(named: "SharedObject") != nil
}

/// Reports a `@JS` attribute that no macro binds, so the member would be missing in JavaScript without
/// an error:
/// - on a declaration other than a function, property or initializer, such as a subscript;
/// - on a member of an extension, since `@ExpoModule` and `@SharedObject` read only the class body;
/// - on a member of a type that isn't an `@ExpoModule` or `@SharedObject` class;
/// - on a `static` or `class` member of an `@ExpoModule` class, since JavaScript gets only the instance;
/// - on an initializer of an `@ExpoModule` class, since JavaScript doesn't construct a module.
private func diagnosePlacement(
  of node: AttributeSyntax,
  on declaration: some DeclSyntaxProtocol,
  in context: some MacroExpansionContext
) {
  guard
    declaration.is(FunctionDeclSyntax.self) || declaration.is(VariableDeclSyntax.self)
      || declaration.is(InitializerDeclSyntax.self)
  else {
    let kind = declaration.is(SubscriptDeclSyntax.self) ? "a subscript" : "this declaration"
    context.diagnose(
      Diagnostic(
        node: node,
        message: JSDiagnosticMessage(
          "@JS applies to a function, property or initializer, so \(kind) isn't bound to JavaScript. Expose a @JS function instead",
          id: "js-unsupported-declaration",
          severity: .error
        )
      )
    )
    return
  }
  if let extensionDecl = context.lexicalContext.first?.as(ExtensionDeclSyntax.self) {
    let typeName = extensionDecl.extendedType.trimmedDescription
    context.diagnose(
      Diagnostic(
        node: node,
        message: JSDiagnosticMessage(
          "A @JS member of an extension isn't bound to JavaScript: @ExpoModule and @SharedObject bind only the @JS members declared in the class body. Move the member into the declaration of '\(typeName)'",
          id: "js-in-extension",
          severity: .error
        )
      )
    )
    return
  }
  if let enclosingType = context.lexicalContext.first, enclosingType.isProtocol(DeclGroupSyntax.self),
    !isInBindingClass(context)
  {
    let typeName = enclosingType.asProtocol(NamedDeclSyntax.self).map { "'\($0.name.text)'" } ?? "this type"
    context.diagnose(
      Diagnostic(
        node: node,
        message: JSDiagnosticMessage(
          "A @JS member of \(typeName) isn't bound to JavaScript: only an @ExpoModule or @SharedObject class binds its @JS members. Add one of these macros to \(typeName), or move the member into such a class",
          id: "js-outside-binding-class",
          severity: .error
        )
      )
    )
    return
  }
  if let modifiers = declaration.asProtocol(WithModifiersSyntax.self)?.modifiers, isTypeLevel(modifiers),
    let classDecl = context.lexicalContext.first?.as(ClassDeclSyntax.self),
    classDecl.attributes.firstAttribute(named: "ExpoModule") != nil
  {
    context.diagnose(
      Diagnostic(
        node: node,
        message: JSDiagnosticMessage(
          "A @JS member of an @ExpoModule class can't be 'static' or 'class': JavaScript gets one module object, and @ExpoModule binds the members of the instance to it. Make the member an instance member",
          id: "js-module-static-member",
          severity: .error
        )
      )
    )
    return
  }
  if let initDecl = declaration.as(InitializerDeclSyntax.self),
    let classDecl = context.lexicalContext.first?.as(ClassDeclSyntax.self),
    classDecl.attributes.firstAttribute(named: "ExpoModule") != nil
  {
    context.diagnose(
      Diagnostic(
        node: node,
        message: JSDiagnosticMessage(
          "@JS on an initializer of an @ExpoModule class isn't bound to JavaScript: JavaScript doesn't construct a module, it gets the instance that the app context creates. Remove @JS, or construct a @SharedObject class from JavaScript instead",
          id: "js-module-initializer",
          severity: .error
        ),
        fixIts: removeAttributeFixIts(node, before: initDecl.initKeyword)
      )
    )
  }
}

/// The fix-it that removes a `@JS` attribute written on its own line, with the line break and
/// indentation before it. The macro gets the attribute without the trivia after it, so when the
/// declaration starts on the line of the attribute (`@JS init()`), the fix-it can't tell how much
/// space to remove, and there is none. It edits only the text of the attribute, since the declaration
/// that a peer macro gets can carry attributes that other macros added.
private func removeAttributeFixIts(_ node: AttributeSyntax, before keyword: TokenSyntax) -> [FixIt] {
  guard keyword.leadingTrivia.contains(where: \.isNewline) else {
    return []
  }
  return [
    FixIt(
      message: JSFixItMessage("Remove '@JS'", id: "js-remove-attribute"),
      changes: [.replaceText(range: node.position..<node.endPosition, with: "", in: Syntax(node))]
    )
  ]
}

/// Emits the diagnostics for the `symbol:` argument of `@JS`, which binds the member under a symbol
/// (see `JSMemberKey`). The argument must be a case of `JavaScriptSymbol.WellKnown` or a string literal
/// that the macro can read, and an initializer can't take it, since a constructor has no key.
private func diagnoseSymbolArgument(
  of node: AttributeSyntax,
  on declaration: some DeclSyntaxProtocol,
  in context: some MacroExpansionContext
) {
  guard let argument = symbolArgument(of: node) else {
    return
  }
  if declaration.is(InitializerDeclSyntax.self) {
    context.diagnose(
      Diagnostic(
        node: argument,
        message: JSDiagnosticMessage(
          "'symbol:' applies only to a @JS function or property: JavaScript constructs a shared object with 'new', so an initializer isn't bound under a key",
          id: "js-symbol-on-initializer",
          severity: .error
        )
      )
    )
    return
  }
  if symbolKey(of: node) == nil {
    context.diagnose(
      Diagnostic(
        node: argument.expression,
        message: JSDiagnosticMessage(
          "'symbol:' takes a well-known symbol, such as '.iterator', or the registry key of 'Symbol.for' as a string literal, such as \"app.id\". The macro reads the argument from the source, so it can't be a variable, a constant or an interpolated string",
          id: "js-symbol-argument",
          severity: .error
        )
      )
    )
  }
}

/// Emits the diagnostic for `@JS(.concurrent)` on a member that can't take it. The option maps to
/// Swift's `@concurrent`, which requires an `async` function: a synchronous member has nowhere to
/// suspend, and a property or initializer can't be async at all. Diagnosing here points at the
/// user's own `@JS` attribute rather than at the `@concurrent` the module macro would attach.
private func diagnoseConcurrentOption(
  of node: AttributeSyntax,
  on declaration: some DeclSyntaxProtocol,
  in context: some MacroExpansionContext
) {
  guard hasOption(node, named: "concurrent") else {
    return
  }
  if let funcDecl = declaration.as(FunctionDeclSyntax.self) {
    guard funcDecl.signature.effectSpecifiers?.asyncSpecifier == nil else {
      return
    }
    context.diagnose(
      Diagnostic(
        node: node,
        message: JSDiagnosticMessage(
          "'.concurrent' needs an 'async' function: a synchronous @JS member runs on the JavaScript thread by definition. Mark the function 'async' to run its body off that thread",
          id: "js-concurrent-requires-async",
          severity: .error
        ),
        fixIts: [insertAsyncFixIt(for: funcDecl)]
      )
    )
    return
  }
  context.diagnose(
    Diagnostic(
      node: node,
      message: JSDiagnosticMessage(
        "'.concurrent' applies only to an 'async' @JS function, not to a property or initializer",
        id: "js-concurrent-requires-function",
        severity: .error
      )
    )
  )
}

/// Emits the diagnostics for `@JS(.withAsync("name"))` on a member that can't take it. The option
/// adds a promise-returning variant that calls the function on the concurrent pool, so it needs a
/// synchronous function without a global actor, and the variant's JavaScript name as a string literal.
private func diagnoseAsyncVariantOption(
  of node: AttributeSyntax,
  on declaration: some DeclSyntaxProtocol,
  in context: some MacroExpansionContext
) {
  guard let option = asyncVariantOption(of: node) else {
    return
  }
  guard let funcDecl = declaration.as(FunctionDeclSyntax.self) else {
    context.diagnose(
      Diagnostic(
        node: node,
        message: JSDiagnosticMessage(
          "'.withAsync' applies only to a synchronous @JS function, not to a property or initializer",
          id: "js-async-variant-requires-function",
          severity: .error
        )
      )
    )
    return
  }
  if funcDecl.signature.effectSpecifiers?.asyncSpecifier != nil {
    context.diagnose(
      Diagnostic(
        node: node,
        message: JSDiagnosticMessage(
          "'.withAsync' adds a promise-returning variant to a synchronous function, and this function is already 'async'. Remove '.withAsync', and use '.concurrent' to run the function off the JavaScript thread",
          id: "js-async-variant-on-async-function",
          severity: .error
        ),
        fixIts: removeAsyncVariantFixIt(from: node).map { [$0] } ?? []
      )
    )
    return
  }
  for duplicate in asyncVariantOptions(of: node).dropFirst() {
    context.diagnose(
      Diagnostic(
        node: duplicate,
        message: JSDiagnosticMessage(
          "'.withAsync' can be listed only once: a function gets one promise-returning variant",
          id: "js-async-variant-duplicate",
          severity: .error
        )
      )
    )
  }
  if asyncVariantName(of: option) == nil {
    context.diagnose(
      Diagnostic(
        node: option,
        message: JSDiagnosticMessage(
          "'.withAsync' takes the JavaScript name of the variant as a string literal, for example '.withAsync(\"loadAsync\")'",
          id: "js-async-variant-name",
          severity: .error
        )
      )
    )
  }
  if let isolation = globalActorIsolation(of: funcDecl, in: context) {
    context.diagnose(
      Diagnostic(
        node: node,
        message: JSDiagnosticMessage(
          isolation.enclosingTypeName.map {
            "'.withAsync' calls the function on the concurrent thread pool, so the function can't inherit '\(isolation.attribute)' from '\($0)'. Mark the function 'nonisolated'"
          }
            ?? "'.withAsync' calls the function on the concurrent thread pool, so the function can't be isolated to '\(isolation.attribute)'",
          id: "js-async-variant-isolated",
          severity: .error
        )
      )
    )
  }
}

/// Emits the diagnostic for `@JS(.cached)` on a member that can't take it. The getter of a `.cached`
/// property stores its first value as a data property on the JavaScript object (see `JSProperty`), so
/// the option needs a getter-only computed property:
/// - a function or an initializer has no value to store;
/// - a stored property, `let` or `var`, already has its value in Swift, and a `var` can change it;
/// - the setter of a settable property could never be called after the first read;
/// - a `lazy var` already stores its first value. Its Swift storage is what `.cached` avoids: two
///   runtimes on different threads can read it for the first time at once.
private func diagnoseCachedOption(
  of node: AttributeSyntax,
  on declaration: some DeclSyntaxProtocol,
  in context: some MacroExpansionContext
) {
  guard hasCachedOption(node) else {
    return
  }
  let message: String
  let id: String
  if let varDecl = declaration.as(VariableDeclSyntax.self) {
    if isLazy(varDecl.modifiers) {
      message =
        "'.cached' applies only to a getter-only computed @JS property, and a 'lazy var' already stores its first value on the JavaScript object. Make the property computed, or remove '.cached'. A computed property has no storage that two runtimes on different threads could initialize at once"
      id = "js-cached-on-lazy-property"
    } else if varDecl.bindingSpecifier.tokenKind == .keyword(.let) || varDecl.bindings.contains(where: isStored) {
      message =
        "'.cached' applies only to a getter-only computed @JS property, not to a stored property. Make the property computed, or remove '.cached'"
      id = "js-cached-on-stored-property"
    } else if varDecl.bindings.contains(where: bindingIsSettable) {
      message =
        "'.cached' applies only to a getter-only computed @JS property: the first read replaces the property with a read-only value on the JavaScript object, so JavaScript can't call the setter. Remove the setter, or remove '.cached'"
      id = "js-cached-on-settable-property"
    } else {
      return
    }
  } else {
    message = "'.cached' applies only to a getter-only computed @JS property, not to a function or initializer"
    id = "js-cached-requires-property"
  }
  context.diagnose(Diagnostic(node: node, message: JSDiagnosticMessage(message, id: id, severity: .error)))
}

/// True when a `var` binding is a stored property: it has no accessors, or only the `willSet` and
/// `didSet` observers.
private func isStored(_ binding: PatternBindingSyntax) -> Bool {
  guard case .accessors(let accessors) = binding.accessorBlock?.accessors else {
    return binding.accessorBlock == nil
  }
  return accessors.allSatisfy {
    $0.accessorSpecifier.tokenKind == .keyword(.willSet) || $0.accessorSpecifier.tokenKind == .keyword(.didSet)
  }
}

/// The fix-it that removes the `.withAsync` option of an `async` function. It is offered only for one
/// option written as an argument of the attribute, not in an array literal. It is the only fix-it:
/// replacing the option with `.concurrent` would be an alternative, and `fix` skips a diagnostic with
/// alternatives.
private func removeAsyncVariantFixIt(from node: AttributeSyntax) -> FixIt? {
  let options = asyncVariantOptions(of: node)
  guard options.count == 1, let argument = options.first?.parent?.as(LabeledExprSyntax.self) else {
    return nil
  }
  return FixIt(
    message: JSFixItMessage("Remove '.withAsync'", id: "js-remove-async-variant"),
    changes: [.replace(oldNode: Syntax(node), newNode: Syntax(removingArgument(argument, from: node)))]
  )
}

/// The global actor a function is isolated to, written on the function itself or inherited from its
/// enclosing type, or `nil` when it has none or is `nonisolated`. `enclosingTypeName` is set when the
/// isolation is inherited.
private func globalActorIsolation(
  of funcDecl: FunctionDeclSyntax,
  in context: some MacroExpansionContext
) -> (attribute: String, enclosingTypeName: String?)? {
  if let attribute = funcDecl.attributes.first(where: hasGlobalActorShape) {
    return (attribute.trimmedDescription, nil)
  }
  if funcDecl.modifiers.contains(where: { $0.name.text == "nonisolated" }) {
    return nil
  }
  guard let enclosing = context.lexicalContext.first,
    let attribute = enclosing.asProtocol(WithAttributesSyntax.self)?.attributes.first(where: hasGlobalActorShape)
  else {
    return nil
  }
  return (attribute.trimmedDescription, enclosing.asProtocol(NamedDeclSyntax.self)?.name.text)
}

/// The fix-it offered alongside the synchronous-function diagnostic: insert `async` into the
/// signature so `@JS(.concurrent)` becomes valid. The macro can't add the keyword itself (no macro
/// role rewrites the declaration it's attached to), but Xcode can apply this in one click.
///
/// `async` goes at the front of the effect specifiers, ahead of any `throws`, which is the only
/// order Swift accepts. When the signature has no effect specifiers yet, the new clause inherits
/// what the parameter clause had trailing it and the parameter clause is left with a single space,
/// so `() -> Int` becomes `() async -> Int` rather than `() async-> Int`.
private func insertAsyncFixIt(for funcDecl: FunctionDeclSyntax) -> FixIt {
  let signature = funcDecl.signature
  var newSignature = signature

  if var effectSpecifiers = signature.effectSpecifiers {
    effectSpecifiers.asyncSpecifier = .keyword(.async, trailingTrivia: .space)
    newSignature.effectSpecifiers = effectSpecifiers
  } else {
    newSignature.effectSpecifiers = FunctionEffectSpecifiersSyntax(
      asyncSpecifier: .keyword(.async, trailingTrivia: signature.parameterClause.trailingTrivia)
    )
    newSignature.parameterClause.trailingTrivia = .space
  }

  return FixIt(
    message: JSFixItMessage("Mark the function 'async'", id: "js-concurrent-insert-async"),
    changes: [.replace(oldNode: Syntax(signature), newNode: Syntax(newSignature))]
  )
}

/// Reports a function or constructor parameter whose specifier a decoded argument can't honor: an
/// `inout` parameter expects its writes to reach the caller, and an `isolated` one expects an actor,
/// while a `@JS` argument is a fresh value decoded from JavaScript. Ownership specifiers (`borrowing`,
/// `consuming`, `sending`) are fine: the binding passes the decoded value under whichever convention
/// the parameter asks for. The specifier is left off the decode and the assertion (see
/// `SpecifiedType`); a parameter reported here is also left out of the assertion.
/// The JSI types that own an engine value and release it wherever they are dropped. Such a value is
/// valid only on the JavaScript thread. `JavaScriptPromise` releases its value on the JavaScript
/// thread, and `JavaScriptRef` and `JavaScriptCallback` exist to carry a value across threads, so they
/// aren't listed.
private let javaScriptThreadBoundTypes: Set<String> = [
  "JavaScriptValue", "JavaScriptObject", "JavaScriptFunction", "JavaScriptArray", "JavaScriptArrayBuffer",
  "JavaScriptTypedArray", "JavaScriptBigInt", "JavaScriptWeakObject",
]

/// Emits the diagnostic for a JSI value parameter of a `@JS(.concurrent)` function or of the variant
/// that `@JS(.withAsync("name"))` adds. Both run the body on the concurrent thread pool, never on the
/// JavaScript thread, so the body can't use the value, and the value is released off the JavaScript
/// thread too.
private func diagnoseJavaScriptValuesOffThread(
  of node: AttributeSyntax,
  on declaration: some DeclSyntaxProtocol,
  in context: some MacroExpansionContext
) {
  guard let funcDecl = declaration.as(FunctionDeclSyntax.self) else {
    return
  }
  let option: String
  let reason: String
  if hasOption(node, named: "concurrent") {
    option = ".concurrent"
    reason = "'.concurrent' runs the body on the concurrent thread pool"
  } else if asyncVariantOption(of: node) != nil {
    option = ".withAsync"
    reason = "the variant that '.withAsync' adds runs the function on the concurrent thread pool"
  } else {
    return
  }
  for parameter in funcDecl.signature.parameterClause.parameters {
    let type = SpecifiedType(parameter.type).type
    guard let name = baseIdentifier(of: optionalWrappedType(type) ?? type), javaScriptThreadBoundTypes.contains(name)
    else {
      continue
    }
    let parameterName = (parameter.secondName ?? parameter.firstName).text
    context.diagnose(
      Diagnostic(
        node: parameter.type,
        message: JSDiagnosticMessage(
          "'\(parameterName)' can't be a '\(name)' in a '\(option)' function: \(reason), and a JavaScript value is valid only on the JavaScript thread. Take a native type that the value decodes to, such as a @Record or [String: Any], or remove '\(option)'",
          id: "js-javascript-value-off-thread",
          severity: .error
        )
      )
    )
  }
}

/// Emits the diagnostics for a parameter that takes the JavaScript runtime (see `isRuntimeParameter`).
/// The binding passes the runtime of the call, which can be used only on the JavaScript thread. So
/// the parameter must be:
/// - in a synchronous function or an initializer. An `async` function can resume on another thread
///   after an `await`: `@JavaScriptActor` runs a job on the thread that enqueues it, and doesn't move
///   it to the JavaScript thread. A `.concurrent` function and the variant that `.withAsync` adds run
///   on the concurrent thread pool;
/// - `borrowing`, so the body can't keep the runtime for later without an explicit `copy`;
/// - not optional, since the binding always has a runtime to pass;
/// - the last parameter, labeled `in` (or `runtime`), so every declaration reads the same and the JavaScript
///   arguments keep their order.
private func diagnoseRuntimeParameter(
  of node: AttributeSyntax,
  on declaration: some DeclSyntaxProtocol,
  in context: some MacroExpansionContext
) {
  let parameters: FunctionParameterListSyntax
  if let funcDecl = declaration.as(FunctionDeclSyntax.self) {
    parameters = funcDecl.signature.parameterClause.parameters
    // `.concurrent` is checked first: its body never runs on the JavaScript thread, so making the
    // function synchronous doesn't help (a synchronous `.concurrent` function is an error too).
    let offThread: (reason: String, remedy: String)?
    if hasOption(node, named: "concurrent") {
      offThread = ("'.concurrent' runs the body on the concurrent thread pool", "Remove the parameter")
    } else if funcDecl.signature.effectSpecifiers?.asyncSpecifier != nil {
      offThread = (
        "an 'async' function can resume on another thread after an 'await'",
        "Remove the parameter, or make the function synchronous"
      )
    } else if asyncVariantOption(of: node) != nil {
      offThread = (
        "the variant that '.withAsync' adds runs the function on the concurrent thread pool",
        "Remove the parameter, or remove '.withAsync'"
      )
    } else {
      offThread = nil
    }
    if let offThread {
      for parameter in parameters where isRuntimeParameter(parameter) {
        context.diagnose(
          Diagnostic(
            node: parameter.type,
            message: JSDiagnosticMessage(
              "A @JS function can take the JavaScript runtime only when it's synchronous: \(offThread.reason), and the runtime can be used only on the JavaScript thread. \(offThread.remedy)",
              id: "js-runtime-parameter-async",
              severity: .error
            )
          )
        )
      }
      return
    }
  } else if let initDecl = declaration.as(InitializerDeclSyntax.self) {
    parameters = initDecl.signature.parameterClause.parameters
  } else {
    return
  }
  for (index, parameter) in parameters.enumerated() where isRuntimeParameter(parameter) {
    guard index == parameters.count - 1 else {
      context.diagnose(
        Diagnostic(
          node: parameter,
          message: JSDiagnosticMessage(
            "The JavaScript runtime must be the last parameter of a @JS function or initializer, and only one parameter can take it. Move it to the end as 'in runtime: borrowing JavaScriptRuntime'",
            id: "js-runtime-parameter-position",
            severity: .error
          )
        )
      )
      continue
    }
    // The errors and the docs name only `in`, which matches the JSI API, such as `encode(_:into:in:)`.
    // An escaped label (`` `in` ``) is the same label.
    if !runtimeParameterLabels.contains(withoutBackticks(parameter.firstName.text)) {
      context.diagnose(
        Diagnostic(
          node: parameter.firstName,
          message: JSDiagnosticMessage(
            "The parameter that takes the JavaScript runtime must be labeled 'in', as in 'in runtime: borrowing JavaScriptRuntime'",
            id: "js-runtime-parameter-label",
            severity: .error
          ),
          fixIts: [runtimeLabelFixIt(for: parameter)]
        )
      )
    }
    let specified = SpecifiedType(parameter.type)
    let wrapped = optionalWrappedType(specified.type)
    if let wrapped {
      context.diagnose(
        Diagnostic(
          node: specified.type,
          message: JSDiagnosticMessage(
            "The parameter that takes the JavaScript runtime can't be optional: the binding always passes the runtime of the call",
            id: "js-runtime-parameter-optional",
            severity: .error
          ),
          fixIts: [
            FixIt(
              message: JSFixItMessage("Remove the optional", id: "js-runtime-parameter-remove-optional"),
              changes: [
                .replace(
                  oldNode: Syntax(specified.type),
                  newNode: Syntax(
                    wrapped.trimmed
                      .with(\.leadingTrivia, specified.type.leadingTrivia)
                      .with(\.trailingTrivia, specified.type.trailingTrivia)
                  )
                )
              ]
            )
          ]
        )
      )
    }
    if specified.specifiers != ["borrowing"] {
      context.diagnose(
        Diagnostic(
          node: parameter.type,
          message: JSDiagnosticMessage(
            "The parameter that takes the JavaScript runtime must be 'borrowing': the runtime can be used only on the JavaScript thread, and a borrowed parameter can't be kept for later without an explicit 'copy'",
            id: "js-runtime-parameter-borrowing",
            severity: .error
          ),
          fixIts: [
            FixIt(
              message: JSFixItMessage("Mark the parameter 'borrowing'", id: "js-runtime-parameter-insert-borrowing"),
              changes: [
                .replace(
                  oldNode: Syntax(parameter.type),
                  newNode: Syntax(borrowingType(wrapped ?? specified.type, like: parameter.type))
                )
              ]
            )
          ]
        )
      )
    }
  }
}

/// The labels that the runtime parameter can have.
private let runtimeParameterLabels: Set<String> = ["in", "runtime"]

/// The fix-it that labels the runtime parameter `in`. It keeps the parameter name that the body uses, or
/// names the parameter `runtime` when it has no name.
private func runtimeLabelFixIt(for parameter: FunctionParameterSyntax) -> FixIt {
  var newParameter = parameter
  let name = parameter.secondName ?? (parameter.firstName.tokenKind == .wildcard ? nil : parameter.firstName)
  newParameter.firstName = .keyword(.in, leadingTrivia: parameter.firstName.leadingTrivia, trailingTrivia: .space)
  newParameter.secondName = name?.trimmed ?? .identifier("runtime")
  return FixIt(
    message: JSFixItMessage("Label the parameter 'in'", id: "js-runtime-parameter-label"),
    changes: [.replace(oldNode: Syntax(parameter), newNode: Syntax(newParameter))]
  )
}

/// The type `type` with the single specifier `borrowing`, with the trivia of `original`.
private func borrowingType(_ type: TypeSyntax, like original: TypeSyntax) -> TypeSyntax {
  let specifier = SimpleTypeSpecifierSyntax(specifier: .keyword(.borrowing, trailingTrivia: .space))
  let attributed = AttributedTypeSyntax(
    specifiers: [.simpleTypeSpecifier(specifier)],
    baseType: type.trimmed
  )
  return TypeSyntax(attributed)
    .with(\.leadingTrivia, original.leadingTrivia)
    .with(\.trailingTrivia, original.trailingTrivia)
}

private func diagnoseParameterSpecifiers(
  in declaration: some DeclSyntaxProtocol,
  in context: some MacroExpansionContext
) {
  let parameters: FunctionParameterListSyntax
  if let funcDecl = declaration.as(FunctionDeclSyntax.self) {
    parameters = funcDecl.signature.parameterClause.parameters
  } else if let initDecl = declaration.as(InitializerDeclSyntax.self) {
    parameters = initDecl.signature.parameterClause.parameters
  } else {
    return
  }
  // The runtime parameter isn't decoded, and `diagnoseRuntimeParameter` requires it to be `borrowing`.
  for parameter in parameters where !isRuntimeParameter(parameter) {
    guard let specifier = SpecifiedType(parameter.type).unsupportedSpecifier else {
      continue
    }
    context.diagnose(
      Diagnostic(
        node: parameter.type,
        message: JSDiagnosticMessage(
          "A @JS parameter can't be '\(specifier)': its argument is a value decoded from JavaScript, which can't be written back or carry an isolation",
          id: "js-parameter-specifier",
          severity: .error
        )
      )
    )
  }
}

/// Emits the free-form (`Any`-bearing) diagnostics for a `@JS` declaration.
///
/// A type built from `Any`, arrays, `String`-keyed dictionaries and optionals converts through the
/// `JavaScriptValue` free-form methods in every position (see `FreeFormConversion`). That means:
/// - a free-form argument, return value or property needs no diagnostic: it decodes through
///   `decodeAny…` and encodes through `encodeAny…`;
/// - a type that holds `Any` in any other shape (`[Int: Any]`, `Set<[String: Any]>`) is an error in
///   every position, since the free-form methods never produce or accept it.
///
/// Types are matched on the type node, so the diagnostic points at the offending type in the user's
/// source. A closure type is left to `diagnoseClosureTypes`.
private func diagnoseFreeFormTypes(
  in declaration: some DeclSyntaxProtocol,
  in context: some MacroExpansionContext
) {
  var types: [TypeSyntax] = []
  if let funcDecl = declaration.as(FunctionDeclSyntax.self) {
    types = funcDecl.signature.parameterClause.parameters.map { SpecifiedType($0.type).type }
    if let returnType = funcDecl.signature.returnClause?.type {
      types.append(returnType)
    }
  } else if let initDecl = declaration.as(InitializerDeclSyntax.self) {
    // A constructor decodes its arguments exactly like a function and has no return value.
    types = initDecl.signature.parameterClause.parameters.map { SpecifiedType($0.type).type }
  } else if let varDecl = declaration.as(VariableDeclSyntax.self),
    let type = varDecl.bindings.first?.typeAnnotation?.type
  {
    types = [type]
  }

  for type in types
  where mentionsFreeFormAny(type) && !isConvertibleFreeFormType(type) && !containsFunctionType(type) {
    context.diagnose(
      Diagnostic(node: type, message: unconvertibleFreeFormError(for: type.trimmedDescription))
    )
  }
}

private func unconvertibleFreeFormError(for type: String) -> JSDiagnosticMessage {
  return JSDiagnosticMessage(
    "A @JS member can't use the type '\(type)': a type holding 'Any' converts to and from JavaScript only when it's built from 'Any', arrays, String-keyed dictionaries and optionals. Use one of those shapes, such as '[String: Any]', or 'JavaScriptValue' to keep the JavaScript value unconverted",
    id: "js-free-form-unsupported",
    severity: .error
  )
}

private struct JSDiagnosticMessage: DiagnosticMessage {
  let message: String
  let diagnosticID: MessageID
  let severity: DiagnosticSeverity

  init(_ message: String, id: String, severity: DiagnosticSeverity) {
    self.message = message
    self.diagnosticID = MessageID(domain: "ExpoModulesMacros", id: id)
    self.severity = severity
  }
}

private struct JSFixItMessage: FixItMessage {
  let message: String
  let fixItID: MessageID

  init(_ message: String, id: String) {
    self.message = message
    self.fixItID = MessageID(domain: "ExpoModulesMacros", id: id)
  }
}

/// What an assertion needs about a `@JS` member: a name (which names the helper), the boundary types in
/// signature order, each with the protocol for the direction it travels and its argument label, and
/// whether the member is type-level. Arguments (and a settable property's incoming value) are decoded;
/// return values (and a property's outgoing value) are encoded, so each is asserted against the
/// protocol for its direction.
private struct BoundaryMember {
  let name: String
  /// The types crossing the boundary, in signature order.
  let types: [AssertedType]
  /// True for `static`/`class` members, so the peer is emitted in the same metatype context.
  let isStatic: Bool
}

/// Reads the boundary member off a `@JS` declaration, with each type's conversion direction. A function
/// contributes its parameter types (decodable) under their argument labels and its return type when
/// non-Void (encodable) under `returning`; an initializer contributes its parameter types; a property
/// contributes its value type, unlabeled, as decodable when settable (the setter) and as encodable (the
/// getter). Composed types (`[Int]`, `String?`,
/// …) are kept verbatim, their conditional conformances transitively constraining the elements. A type
/// that mentions `Any` is left out: it converts through the free-form methods, or is diagnosed by
/// `diagnoseFreeFormTypes`. Returns `nil` for declaration kinds `@JS` doesn't read types from, a
/// property whose type isn't spelled out (a syntactic macro can't recover it), or one whose type
/// mentions `Any`.
private func boundaryMember(of declaration: some DeclSyntaxProtocol) -> BoundaryMember? {
  if let funcDecl = declaration.as(FunctionDeclSyntax.self) {
    var types = argumentBoundaryTypes(of: funcDecl.signature.parameterClause.parameters)
    if let returnType = funcDecl.signature.returnClause?.type,
      !isVoidType(returnType) && !containsFunctionType(returnType) && !mentionsFreeFormAny(returnType)
    {
      types.append(
        AssertedType(
          label: "returning",
          type: returnType.trimmedDescription,
          constraint: javaScriptEncodableProtocolName
        )
      )
    }
    return BoundaryMember(name: funcDecl.name.text, types: types, isStatic: isTypeLevel(funcDecl.modifiers))
  }

  if let initDecl = declaration.as(InitializerDeclSyntax.self) {
    // A constructor decodes its arguments like a function does, and the instance it returns isn't
    // encoded. The name is escaped because it also names the assertion's nested helper, and `init` is
    // a keyword.
    return BoundaryMember(
      name: "`init`",
      types: argumentBoundaryTypes(of: initDecl.signature.parameterClause.parameters),
      isStatic: false
    )
  }

  if let varDecl = declaration.as(VariableDeclSyntax.self),
    let binding = varDecl.bindings.first,
    let identifier = binding.pattern.as(IdentifierPatternSyntax.self),
    let type = binding.typeAnnotation?.type,
    !containsFunctionType(type)
  {
    // A `let`, a `lazy var`, or a `var` with no setter is read-only (encodable only). A settable `var`
    // is also decoded on write, so its value type is asserted in both directions. A type that mentions
    // `Any` converts through the free-form methods instead, so it isn't asserted at all.
    guard !mentionsFreeFormAny(type) else {
      return nil
    }
    let typeText = type.trimmedDescription
    let isVar = varDecl.bindingSpecifier.tokenKind == .keyword(.var)
    let isSettable = isVar && !isLazy(varDecl.modifiers) && bindingIsSettable(binding)
    let decodable = AssertedType(label: nil, type: typeText, constraint: javaScriptDecodableProtocolName)
    let encodable = AssertedType(label: nil, type: typeText, constraint: javaScriptEncodableProtocolName)
    return BoundaryMember(
      name: identifier.identifier.text,
      types: (isSettable ? [decodable] : []) + [encodable],
      isStatic: isTypeLevel(varDecl.modifiers)
    )
  }

  return nil
}

/// The boundary types of a function's or constructor's arguments, under their argument labels: an
/// argument is decoded from JS, and a closure argument instead contributes its parameter types (encoded
/// when native code calls it) and its return type (decoded).
private func argumentBoundaryTypes(of parameters: FunctionParameterListSyntax) -> [AssertedType] {
  // A closure argument moves data the other way: JS receives its parameters and returns its result.
  // A closure in any other position is diagnosed by `diagnoseClosureTypes` and left out here, since
  // its metatype isn't a valid expression in the assertion.
  var types: [AssertedType] = []
  // The runtime parameter takes no JavaScript argument, so nothing decodes into it.
  for parameter in parameters where !isRuntimeParameter(parameter) {
    let label = parameter.firstName.tokenKind == .wildcard ? nil : parameter.firstName.text
    // The specifier isn't part of the asserted type, and a parameter with one the binding can't honor
    // is reported by `diagnoseParameterSpecifiers` and not asserted.
    let specified = SpecifiedType(parameter.type)
    guard specified.unsupportedSpecifier == nil else {
      continue
    }
    guard let closure = JSClosureType(specified.type) else {
      if !containsFunctionType(specified.type) && !mentionsFreeFormAny(specified.type) {
        let type = specified.type.trimmedDescription
        types.append(AssertedType(label: label, type: type, constraint: javaScriptDecodableProtocolName))
      }
      continue
    }
    // A closure type that mentions `Any` is reported by `diagnoseClosureTypes` instead.
    for parameter in closure.parameters
    where !containsFunctionType(parameter.type) && !mentionsFreeFormAny(parameter.type) {
      let type = parameter.type.trimmedDescription
      types.append(AssertedType(label: label, type: type, constraint: javaScriptEncodableProtocolName))
    }
    let closureReturnType = closure.functionType.returnClause.type
    if let returnType = closure.returnType,
      !containsFunctionType(closureReturnType) && !mentionsFreeFormAny(closureReturnType)
    {
      types.append(AssertedType(label: label, type: returnType, constraint: javaScriptDecodableProtocolName))
    }
  }
  return types
}

/// True when a return clause is written as `Void` / `()` — nothing crosses the boundary, so it needs
/// no conformance assertion. (A missing return clause never reaches here: `returnClause` is `nil`.)
private func isVoidType(_ type: TypeSyntax) -> Bool {
  let text = type.trimmedDescription
  return text == "Void" || text == "()"
}
