Files
swift-nio-imap/Sources/NIOIMAPCore/Parser/ParserErrors.swift
T
Daniel Eggert e7bee2f07b Use typed throws inside the parser (mostly scripted)
Internal parser functions throw `ParseFailure` (24 bytes, returned in
registers), so a failed speculative match no longer calls
swift_allocError. Public API keeps untyped throws and the same error
types; the entry points convert back with `unwrapped`.

- Array-form `parseOneOf` takes `ParseAlternative`s, which avoid
  reabstraction thunks; a typed-throws closure literal as a
  `[SubParser]` element crashes SILGen (6.3, 6.4).
- `try? parseSpaces()` becomes an explicit `catch .mismatch`; no
  behavior change, since `parseSpaces` only reports incomplete on empty
  input. Its doc comment is corrected to match.
- CommandParser: framing runs outside the incomplete catch; it throws
  only `ParserError`.
- Untyped public API called by the grammar (`MailboxPath.init`,
  `ModifiedUTF7.decode`) is wrapped: `throw ParseFailure(error)`.
- SynchronizingLiteralParser keeps untyped throws.

Reviewer focus: `ParseFailure` (`init(_:)`, `unwrapped`), the
combinators' catch clauses (`.mismatch`, `.mismatch, .badCommand`),
the entry points in CommandParser and ResponseParser (`catch
.incomplete`, `unwrapped`), `ParseAlternative`.

Hand edits, whole files taken from this commit:
- ParserErrors.swift: `ParseFailure`; typed `decodeUTF8`; doc
  comments.
- ParseInput+Combinators.swift: typed `SubParser`, `ParseAlternative`,
  catch clauses, 2-/3-way `parseOneOf` on `composite`; otherwise the
  same conversion as the grammar.
- ParseInput.swift: `composite` takes `SubParser`; doc comments;
  otherwise the same conversion as the grammar.
- CommandParser.swift, ResponseParser.swift: entry points; otherwise
  the same conversion as the grammar.
- ParseInputCombinatorTests.swift: `ParseFailure` tests,
  `ParseAlternative` call sites; otherwise the same conversion.
- ParseInputHarness.swift: `parseErrorThrown`.
- ResponseText+Tests.swift: `parseErrorThrown` and `#expect(error is
  ParserError)` instead of `#expect(throws: ParserError.self)`.
Hand edits inside the script: `HAND` (selectingKeyword doc comment,
the two untyped-API wrappers); `OWN_FRAME`: `parseSearchKey` builds
its 35 alternatives in a nested `alternatives()`, off the recursive
frame; `ParseAlternative` naming and layout (`NAMED_FILES`, `RENAME`,
`ONE_PER_LINE`); `BRACE_BELOW`; `EXPLAIN_DO`; the emitted comments.

The rest is the output of the script below. To reproduce, on the
parent commit (swift-format from Swift 6.4.4):

  F=(Sources/NIOIMAPCore/Parser/Grammar/*.swift
     Tests/NIOIMAPCoreTests/ParseFixture.swift
     Tests/NIOIMAPCoreTests/Grammar/CommandType/{CommandType,TaggedCommand}+Tests.swift
     Tests/NIOIMAPCoreTests/Parser/Grammar/GrammarParser+Primitives+Tests.swift
     Tests/NIOIMAPCoreTests/Parser/ParseInputTests.swift)
  python3 convert_typed_throws.py "${F[@]}" && swift format -i "${F[@]}"

then check out the hand-edit files from this commit.

convert_typed_throws.py:

    #!/usr/bin/env python3
    # Converts the parser's internals from untyped `throws` to `throws(ParseFailure)`.
    #
    # Usage: python3 convert_typed_throws.py FILE...    (in place), then `swift format -i FILE...`
    import re
    import sys

    TYPED = 'throws(ParseFailure)'

    # Public error type -> the ParseFailure case that carries it.
    CASES = {
        'ParserError': 'mismatch',
        'BadCommand': 'badCommand',
        'NoForwardProgress': 'noForwardProgress',
        'TooMuchRecursion': 'tooMuchRecursion',
        'ExceededLiteralSizeLimitError': 'literalSizeExceeded',
        'ExceededMaximumMessageAttributesError': 'messageAttributesExceeded',
        'ExceededMaximumBodySizeError': 'bodySizeExceeded',
    }
    TYPES = '|'.join(CASES)

    # `ParseAlternative` names: `pN` by default; named after the alternative's suffix in these files
    # (`parseSearchKey_older` -> `older`), with these exceptions.
    NAMED_FILES = ['+Body.swift', '+Commands.swift', '+Response.swift', '+Search.swift']
    RENAME = {
        'parseBodyEncoding_quotePrintable': 'quotedPrintable',
        'parseBodyEncoding_nil': 'nilEncoding',
        'parseSuffix_metadataLongEntries': 'longEntries',
        'parseSuffix_metadataMaxSize': 'maxSize',
        'parseSuffix_metadataTooMany': 'tooMany',
        'parseSuffix_metadataNoPrivate': 'noPrivate',
        'parseKnownResponseTextCode': 'known',
    }
    KEYWORDS = {'nil', 'extension'}
    # Alternatives (by the first one) whose array is laid out one per line rather than left to swift-format.
    ONE_PER_LINE = {'parseSortCriterion_displayFrom', 'parseSearchReturnData_min', 'parseSearchKey_older'}
    # Productions whose alternatives are built in a nested function, off the recursive frame.
    OWN_FRAME = {'parseSearchKey'}
    # Declarations left to swift-format, which puts `{` on its own line; all others too long for one line
    # put each parameter on its own line.
    BRACE_BELOW = {'parseCompoundObjectID'}
    # Functions in which an annotated `do` gets a comment saying why.
    EXPLAIN_DO = {'parseTaggedCommand', 'parseTaggedExtensionComplex_helper'}
    LINE_LENGTH = 120

    # Hand-written changes: (file, old, new), each matching exactly once.
    HAND = [
        ('GrammarParser.swift', '''\
        /// - Throws: `IncompleteMessage` when every byte that has arrived is part of the keyword, since
        ///     more could still follow; ``ParserError`` when the first byte cannot start one.
    ''', '''\
        /// - Throws: ``ParseFailure/incomplete`` when every byte that has arrived is part of the keyword,
        ///     since more could still follow; ``ParseFailure/mismatch(_:)`` when the first byte cannot start
        ///     one.
    '''),
        ('GrammarParser.swift', '''\
        /// - Important: `select` should throw ``ParserError`` for an unrecognised keyword — not
        ///     `IncompleteMessage`, which would make the caller wait for bytes that cannot help. Callers
        ///     that fall back to another production (`parseFetchAttribute`, say) catch exactly that.
    ''', '''\
        /// Pass an annotated closure: `{ keyword, buffer throws(ParseFailure) in switch keyword { … } }`.
        ///
        /// - Important: `select` should throw ``ParseFailure/mismatch(_:)`` for an unrecognised keyword —
        ///     not ``ParseFailure/incomplete``, which would make the caller wait for bytes that cannot help.
        ///     The type can't enforce this. Callers that fall back to another production
        ///     (`parseFetchAttribute`, say) catch exactly `.mismatch`.
    '''),
        # Untyped public API called from the grammar: classify its error.
        ('GrammarParser.swift', '''\
                return try ModifiedUTF7.decode(value)
    ''', '''\
                do {
                    return try ModifiedUTF7.decode(value)
                } catch {
                    throw ParseFailure(error)
                }
    '''),
        ('GrammarParser+Mailbox.swift', '''\
                return MailboxInfo(
                    attributes: flags,
                    path: try .init(name: mailbox, pathSeparator: character),
    ''', '''\
                // `MailboxPath.init(name:pathSeparator:)` is untyped public API (throws `InvalidPathSeparatorError`).
                let path: MailboxPath
                do {
                    path = try MailboxPath(name: mailbox, pathSeparator: character)
                } catch {
                    throw ParseFailure(error)
                }
                return MailboxInfo(
                    attributes: flags,
                    path: path,
    '''),
    ]

    def closing(src, k):
        """Index just past the bracket matching the one before `k`."""
        depth = 1
        while depth:
            c = src[k]
            if c == '"':  # skip string literals, which may hold brackets
                k += 1
                while src[k] != '"':
                    k += 2 if src[k] == '\\' else 1
            elif c in '([{':
                depth += 1
            elif c in ')]}':
                depth -= 1
            k += 1
        return k

    def code_lines(src, fn):
        """Applies `fn` to every line that is not a comment."""
        return ''.join(l if l.lstrip().startswith('//') else fn(l) for l in src.splitlines(keepends=True))

    def throw_sites(src):
        # throw ParserError(hint: L) -> throw .mismatch(L); other labels (dynamicHint:, expectedDigits:) stay.
        src = re.sub(r'throw ParserError\((hint:\s*)?', 'throw .mismatch(', src)
        src = src.replace('throw IncompleteMessage()', 'throw .incomplete')
        # throw X(…) -> throw .case(X(…)) for the payload-carrying cases.
        out, i = [], 0
        for m in re.finditer(rf'throw ({TYPES})\(', src):
            end = closing(src, m.end())
            out += [src[i:m.start()], f'throw .{CASES[m.group(1)]}(', src[m.start() + len('throw '):end], ')']
            i = end
        return ''.join(out) + src[i:]

    def catch_clauses(src):
        # `catch is A, is B` / `catch let e as A` -> `catch .a, .b` / `catch .a(let e)`; adjacent clauses that
        # differ only in type merge: `} catch is A {\n X } catch is B {\n X }` -> `} catch .a, .b {\n X }`.
        src = re.sub(rf'catch let (\w+) as ({TYPES})\b', lambda m: f'catch .{CASES[m.group(2)]}(let {m.group(1)})', src)
        src = re.sub(rf'catch ((?:is (?:{TYPES})(?:,\s*)?)+)',
                     lambda m: 'catch ' + ', '.join('.' + CASES[t] for t in re.findall(rf'is ({TYPES})', m.group(1))),
                     src)
        src = re.sub(r'catch (\.\w+(?:, \.\w+)*) \{(\n[^\n]*\n\s*)\} catch (\.\w+) \{\2\}', r'catch \1, \3 {\2}', src)
        # Rethrowing what a clause bound re-wraps it: `catch .x(let e) { throw e }` -> `throw .x(e)`.
        return re.sub(r'(catch \.(\w+)\(let (\w+)\) \{\s*throw )\3\b', r'\1.\2(\3)', src)

    def closures(src):
        # Two-parameter closure literals: `{ a, b -> T in` / `{ (a, b) in` gain the annotation.
        src = re.sub(r'(\{\s*\(?\w+,\s*\w+\)?)(\s*->[^\n{]*?)?(\s+in\b)',
                     lambda m: f'{m.group(1)} {TYPED}{m.group(2) or ""}{m.group(3)}', src)
        # Closures with typed parameters: `{ (buffer: [UInt8]) -> String in`.
        src = re.sub(r'(\{\s*\((?:\w+: [^()]+)\))(\s*->[^\n{]*?\s+in\b)', rf'\1 {TYPED}\2', src)
        # `{ try f(buffer: &$0, tracker: $1) }` -> `{ b, t throws(ParseFailure) in try f(buffer: &b, tracker: t) }`
        return re.sub(r'\{(\s*)(try [^{}\n]*\$0[^{}\n]*?)(\s*)\}',
                      lambda m: f'{{ b, t {TYPED} in{m.group(1)}{m.group(2).replace("$0", "b").replace("$1", "t")}{m.group(3)}}}',
                      src)

    def return_type(src, name):
        """The declared result type of `func name(…)` in `src`."""
        m = re.search(rf'func {name}\(', src)
        end = closing(src, m.end())
        return re.match(r'\s*throws[^-{]*->\s*([^{]+?)\s*\{', src[end:]).group(1)

    def alternative_name(fn, numbered, i):
        if numbered:
            return f'p{i}'
        name = RENAME.get(fn) or fn.split('_')[-1]
        return f'_{name}' if name in KEYWORDS or name[0].isdigit() else name

    def array_literal(names, one_per_line):
        return '[\n' + ''.join(f'    {n},\n' for n in names) + ']' if one_per_line else f'[{", ".join(names)}]'

    def rewrite_array_one_of(src, path):
        # The array form of parseOneOf takes `ParseAlternative`s, one `let` each (a typed-throws closure
        # literal as an array element crashes SILGen):
        #   return try buffer.parseOneOf([{ try parseX_a(buffer: &$0, tracker: $1) }, self.parseB], tracker: tracker)
        # ->
        #   let p1 = ParseAlternative<T> { b, t throws(ParseFailure) in
        #       try parseX_a(buffer: &b, tracker: t)
        #   }
        #   let b = ParseAlternative<T> { b, t throws(ParseFailure) in
        #       try self.parseB(buffer: &b, tracker: t)
        #   }
        #   return try buffer.parseOneOf([b, p1], tracker: tracker)
        numbered = not any(path.endswith(f) for f in NAMED_FILES)
        out, i = [], 0
        for m in re.finditer(r'(\w+)\.parseOneOf\(\s*\[', src):
            line = src.rfind('\n', 0, m.start()) + 1
            indent = re.match(r'\s*', src[line:]).group()
            close = closing(src, m.end())
            tail = re.match(r'\s*,\s*tracker: (\w+)\s*\)', src[close:])
            calls = re.findall(r'\{ try (\w+)\(buffer: &\$0, tracker: \$1\) \}', src[m.end():close])
            methods = re.findall(r'self\.(\w+),', src[m.end():close])
            assert len(calls) + len(methods) == src[m.end():close].count('\n') - 1, src[m.end():close]
            t = return_type(src, (calls + methods)[0])
            own_frame = calls[0].split('_')[0] in OWN_FRAME
            width = LINE_LENGTH - len(indent) - 4 * own_frame

            def let(name, call):
                short = f'let {name} = ParseAlternative<{t}> {{ b, t {TYPED} in try {call}(buffer: &b, tracker: t) }}\n'
                long = f'let {name} = ParseAlternative<{t}> {{ b, t {TYPED} in\n    try {call}(buffer: &b, tracker: t)\n}}\n'
                return short if len(short) - 1 <= width else long

            lets, names = '', []
            for k, fn in enumerate(calls, 1):
                names.append(alternative_name(fn, numbered, k))
                lets += let(names[-1], fn)
            assert len(methods) <= 1, methods  # the one site lists it first: `[self.parseFlagList, { … }]`
            for fn in methods:  # `self.parseFlagList` -> `flagList`, first in the array as in the literal
                names.insert(0, fn[len('parse')].lower() + fn[len('parse') + 1:])
                lets += let(names[0], 'self.' + fn)
            # More than one statement now, so an implicit return becomes explicit.
            head = re.sub(r'^try ', 'return try ', src[line + len(indent):m.start()])
            call = f'{head}{m.group(1)}.parseOneOf'
            if own_frame:
                body = lets + 'return ' + array_literal(names, True)
                stmt = (f'// Built in its own frame: the {len(names)} closure values would otherwise sit in every recursion'
                        " level's\n// frame (debug builds keep each `let`), and `(` nests this production up to the tracker"
                        ' limit.\n'
                        f'func alternatives() -> [ParseAlternative<{t}>] {{\n'
                        + re.sub(r'^(?=.)', '    ', body, flags=re.M) + '\n}\n'
                        f'{call}(alternatives(), tracker: {tail.group(1)})')
            else:
                stmt = f'{lets}{call}({array_literal(names, calls[0] in ONE_PER_LINE)}, tracker: {tail.group(1)})'
            out += [src[i:line], re.sub(r'^(?=.)', indent, stmt, flags=re.M)]
            i = close + tail.end()
        return ''.join(out) + src[i:]

    def optional_spaces(src):
        return re.sub(r'(\n(\s*))try\? (\w+)\.parseSpaces\(\)',
                      r'\1// Spaces are optional; incomplete still propagates.\1do { try \3.parseSpaces() } catch .mismatch {}',
                      src)

    def in_closure(src, pos):
        """Whether the innermost closure or function body around `pos` is a closure."""
        stack, k = [], 0
        while k < pos:
            c = src[k]
            if src.startswith('//', k):
                k = src.index('\n', k)
                continue
            if c == '"':
                k += 1
                while src[k] != '"':
                    k += 2 if src[k] == '\\' else 1
            elif c == '{':
                stack.append(k)
            elif c == '}':
                stack.pop()
            k += 1
        for o in reversed(stack):
            if re.match(rf'[^{{}}]*?{re.escape(TYPED)}[^{{}}]*?\s+in\b', src[o + 1:]):
                return True
            if re.search(rf'\bfunc\b[^{{}}]*$', src[:o]):
                return False
        return False

    def annotate_do(src):
        # `do` inside a closure doesn't infer typed throws, so a `catch .mismatch` there needs `do throws(…)`.
        out, i = [], 0
        for m in re.finditer(r'\n(\s*)do \{', src):
            catch = re.match(r'\s*catch (\S)', src[closing(src, m.end()):])
            if not (catch and catch.group(1) == '.' and in_closure(src, m.start())):
                continue
            func = re.findall(r'\n    func (\w+)\(', src[:m.start()])[-1]  # the enclosing member
            why = f"\n{m.group(1)}// `do` inside a closure doesn't infer typed throws; annotate it." if func in EXPLAIN_DO else ''
            out += [src[i:m.start()], why, f'\n{m.group(1)}do {TYPED} {{']
            i = m.end()
        return ''.join(out) + src[i:]

    def wrap_declarations(src):
        # A declaration too long for one line puts each parameter on its own line.
        def wrap(m):
            indent, head, params, tail = m.groups()
            if len(m.group(0)) <= LINE_LENGTH or re.search(r'func (\w+)', head).group(1) in BRACE_BELOW:
                return m.group(0)
            parts, depth, start = [], 0, 0
            for k, c in enumerate(params):
                depth += c in '([<'
                depth -= c in ')]>'
                if c == ',' and depth == 0:
                    parts.append(params[start:k].strip())
                    start = k + 1
            parts.append(params[start:].strip())
            return f'{indent}{head}(\n' + ''.join(f'{indent}    {p},\n' for p in parts)[:-2] + f'\n{indent}) {tail} {{'
        return re.sub(rf'^( *)((?:\w+ )*func \w+)\((.*)\) ({re.escape(TYPED)}.*) \{{$', wrap, src, flags=re.M)

    def convert_test(src):
        # Tests calling typed internals: `errorThrown` -> `parseErrorThrown`, which unwraps the ParseFailure.
        # `errorThrown { … } != nil` doesn't look at the type and stays.
        src = re.sub(r'\berrorThrown\b(?![^\n]*\} != nil)', 'parseErrorThrown', src)
        # Only closures passed to the cursor's combinators need typed throws; fixtures take untyped ones.
        src = throw_sites(src)
        return re.sub(r'(\.composite\(tracker: [^\n]*?\) )(\{[^{}\n]* in)(?= \}$|$)',
                      lambda m: m.group(1) + closures(m.group(2)), src, flags=re.M)

    for path in sys.argv[1:]:
        src = open(path).read()
        if '/Tests/' in '/' + path:
            open(path, 'w').write(convert_test(src))
            continue
        for file, old, new in HAND:
            if path.endswith('/' + file):
                assert src.count(old) == 1, (path, old)
                src = src.replace(old, new)
        src = code_lines(src, lambda l: l if 'rethrows' in l else re.sub(r'\bthrows\b(?!\()', TYPED, l))
        src = re.sub(r'((?<!/)//(?!/).*?)`?IncompleteMessage`?', r'\1`.incomplete`', src)
        src = rewrite_array_one_of(src, path)
        src = throw_sites(src)
        src = catch_clauses(src)
        src = closures(src)
        src = optional_spaces(src)
        src = annotate_do(src)
        src = wrap_declarations(src)
        open(path, 'w').write(src)
2026-11-24 09:48:51 +09:00

409 lines
18 KiB
Swift

//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
/// Decodes `bytes` as UTF-8.
///
/// A free function rather than a `String` initialiser because it throws a ``ParserError`` carrying the
/// source location that asked for the decode, which is what the grammar wants and what a general-purpose
/// initialiser has no business reporting.
///
/// - Throws: ``ParseFailure/mismatch(_:)`` when `bytes` are not valid UTF-8.
func decodeUTF8(
_ bytes: some Collection<UInt8>,
file: StaticString = #fileID,
line: Int = #line
) throws(ParseFailure) -> String {
guard let string = String(validatingUTF8Bytes: bytes) else {
throw .mismatch(.invalidUTF8(file: file, line: line))
}
return string
}
/// What the parser's internals throw: every parser error, under one concrete type.
///
/// Typed throws, because an untyped `throw` boxes its error on the heap, and the parser throws as control
/// flow — every alternative of every `parseOneOf` that does not match. A `throws(ParseFailure)` function
/// returns this in registers, so a failed match costs no allocation. Only ``other(_:)``, ``badCommand(_:)``
/// and a `dynamicHint:` mismatch allocate.
///
/// Registers only while it is at most 4 words; at 64 bytes it went through a hidden out-pointer and
/// doubled debug stack use per nesting level. Hence the compact payloads (``ParserError``,
/// ``NoForwardProgress``) and the `indirect` ``badCommand(_:)``. A test pins the size.
///
/// Throw a mismatch with ``mismatch(_:file:line:)``, which records the throwing site:
/// `throw .mismatch("Expected digit")`, or `throw .mismatch(dynamicHint: "Got \(byte)")` (allocates).
///
/// Internal only. The public entry points convert back with ``unwrapped`` so callers see today's
/// public error types.
///
/// ```
/// grammar / combinators ── throws(ParseFailure) ──▶ entry point ── unwrapped ──▶ public `throws`
/// ▲
/// └── ParseFailure(error) ◀── untyped API (MailboxPath, ModifiedUTF7, …)
/// ```
enum ParseFailure: Error {
/// The input does not match this production. Backtracking points (``ParseInput/parseOptional(tracker:parser:)``,
/// ``ParseInput/parseOneOf(_:tracker:file:line:)``) absorb it.
case mismatch(ParserError)
/// A tagged command failed to parse. ``ParseInput/parseOneOf(_:tracker:file:line:)`` absorbs it, as
/// it did ``BadCommand`` before typed throws.
///
/// `indirect`: ``BadCommand`` is 40 bytes and would push `ParseFailure` out of registers. One allocation
/// per bad command.
indirect case badCommand(BadCommand)
/// More bytes are needed. Never absorbed by a backtracking point; becomes ``IncompleteMessage``.
case incomplete
case noForwardProgress(NoForwardProgress)
case tooMuchRecursion(TooMuchRecursion)
case literalSizeExceeded(ExceededLiteralSizeLimitError)
case messageAttributesExceeded(ExceededMaximumMessageAttributesError)
case bodySizeExceeded(ExceededMaximumBodySizeError)
/// An error from an untyped API the grammar calls (`MailboxPath.init`, `ModifiedUTF7.decode`). Boxed;
/// cold paths only.
case other(any Error)
/// A mismatch with a literal hint, located at the caller. No allocation.
static func mismatch(
_ hint: StaticString = "Unknown",
file: StaticString = #fileID,
line: Int = #line
) -> Self {
.mismatch(ParserError(hint: hint, file: file, line: line))
}
/// `"Expected \(expected) digits, got \(got)"`, located at the caller. Formatted when read, so no
/// allocation: `parseDateDayFixed` throws it on every 2-digit day.
static func mismatch(
expectedDigits expected: Int,
got: Int,
file: StaticString = #fileID,
line: Int = #line
) -> Self {
.mismatch(ParserError(expectedDigits: expected, got: got, file: file, line: line))
}
/// A mismatch with a computed hint, located at the caller. Allocates; cold paths only.
static func mismatch(dynamicHint: String, file: StaticString = #fileID, line: Int = #line) -> Self {
.mismatch(ParserError(dynamicHint: dynamicHint, file: file, line: line))
}
/// Classifies an untyped error, so that a known type keeps its meaning — a ``ParserError`` from an
/// untyped callee must still backtrack.
init(_ error: any Error) {
switch error {
case let failure as ParseFailure: self = failure
case let error as ParserError: self = .mismatch(error)
case let error as BadCommand: self = .badCommand(error)
case is IncompleteMessage: self = .incomplete
case let error as NoForwardProgress: self = .noForwardProgress(error)
case let error as TooMuchRecursion: self = .tooMuchRecursion(error)
case let error as ExceededLiteralSizeLimitError: self = .literalSizeExceeded(error)
case let error as ExceededMaximumMessageAttributesError: self = .messageAttributesExceeded(error)
case let error as ExceededMaximumBodySizeError: self = .bodySizeExceeded(error)
default: self = .other(error)
}
}
/// The public error this stands for. Boxes; call once, where an error leaves the parser.
var unwrapped: any Error {
switch self {
case .mismatch(let error): error
case .badCommand(let error): error
case .incomplete: IncompleteMessage()
case .noForwardProgress(let error): error
case .tooMuchRecursion(let error): error
case .literalSizeExceeded(let error): error
case .messageAttributesExceeded(let error): error
case .bodySizeExceeded(let error): error
case .other(let error): error
}
}
}
/// The parser needs more bytes before it can decide.
///
/// Thrown, rather than returned, because it can arise anywhere in the grammar; the entry points turn
/// it back into "no message yet".
struct IncompleteMessage: Error {
internal init() {}
}
/// Parsing a tagged command failed. Includes the tag of the invalid command, and the parsing error.
///
/// When the server receives a command from a client, it includes a tag for correlation.
/// If the command line cannot be parsed, this error includes both the tag (so the server
/// can send back a properly-tagged error response) and details about what went wrong.
///
/// - SeeAlso: ``ParserError``, [RFC 3501 Section 6.1](https://datatracker.ietf.org/doc/html/rfc3501#section-6.1)
public struct BadCommand: Error {
/// The tag of the bad command.
///
/// Allows the server to send a properly-tagged error response to the client,
/// maintaining IMAP's request/response correlation even when the command is malformed.
public var commandTag: Command.Tag
/// Why parsing failed.
///
/// Contains a human-readable hint about the parsing error and source location information.
public var parserError: ParserError
}
/// An error occurred when parsing an IMAP command or response.
///
/// `ParserError` is thrown when the IMAP protocol parser encounters bytes that cannot be
/// interpreted according to the IMAP grammar (RFC 3501 or extensions). Common causes include:
/// - Invalid UTF-8 sequences in string fields
/// - Malformed protocol syntax (for example, unexpected characters or missing required elements)
/// - Non-conforming protocol elements
///
/// The ``hint`` field provides a developer-friendly description of what went wrong.
/// The internal file and line information is useful for debugging parser issues.
///
/// - SeeAlso: [RFC 3501 Section 4](https://datatracker.ietf.org/doc/html/rfc3501#section-4) (grammar)
public struct ParserError: Error {
/// 24 bytes, so that ``ParseFailure`` fits in registers (see `ParseFailure`'s size test). A `String`
/// hint plus a `StaticString` file plus an `Int` line would be 48.
///
/// ```
/// literal: [ hint pointer | file pointer | line u32, file len u8, isASCII, hint len u16 ]
/// digits: [ file pointer | line u32, file len u8, -, expected u16 | got u32 ]
/// boxed: [ InterpolatedHint ─▶ { hint: String, site } ]
/// ```
private enum Storage {
/// Hot: the hint is a string literal. No allocation.
case literal(LiteralHint)
/// Hot: a digit-count mismatch, formatted when read. No allocation.
case digitCount(DigitCountHint)
/// Cold: an interpolated hint, or one assigned through ``hint``.
case boxed(InterpolatedHint)
}
private var storage: Storage
static func invalidUTF8(file: StaticString = #fileID, line: Int = #line) -> Self {
ParserError(hint: "Invalid UTF8", file: file, line: line)
}
/// If possible, a description of the error and why it occurred.
///
/// Describes the parsing failure in human-readable terms, such as
/// "Invalid UTF8", "Missing CRLF", "Unexpected character", etc. It's intended
/// for logging and debugging purposes.
///
/// - Note: These errors are thrown as part of ordinary control flow — `parseOneOf` throws one
/// for every alternative that doesn't match. So the parser takes the hint as a `StaticString`
/// and keeps only a pointer to the literal: throwing costs no allocation, and the compiler rejects
/// an interpolated hint. Interpolation needs the explicit `dynamicHint:` spelling, which boxes;
/// keep it off paths that are taken often.
public var hint: String {
get {
switch storage {
case .literal(let literal): literal.hint
case .digitCount(let digits): digits.hint
case .boxed(let boxed): boxed.hint
}
}
set {
storage = .boxed(InterpolatedHint(hint: newValue, site: site))
}
}
/// Where the error was thrown.
private var site: ThrowSite {
switch storage {
case .literal(let literal): literal.site
case .digitCount(let digits): digits.site
case .boxed(let boxed): boxed.site
}
}
/// The `#fileID` of the throwing site.
var file: String { site.file }
/// The `#line` of the throwing site.
var line: Int { site.line }
/// A literal hint: no allocation, unless the literal is too long to point at (then boxed).
init(hint: StaticString = "Unknown", file: StaticString = #fileID, line: Int = #line) {
let site = ThrowSite(file: file, line: line)
guard let literal = LiteralHint(hint, site: site) else {
self.storage = .boxed(InterpolatedHint(hint: "\(hint)", site: site))
return
}
self.storage = .literal(literal)
}
/// `"Expected \(expected) digits, got \(got)"`, without allocating.
init(expectedDigits expected: Int, got: Int, file: StaticString = #fileID, line: Int = #line) {
let site = ThrowSite(file: file, line: line)
self.storage = .digitCount(DigitCountHint(expected: expected, got: got, site: site))
}
/// A computed hint. Allocates; cold paths only.
init(dynamicHint: String, file: StaticString = #fileID, line: Int = #line) {
self.storage = .boxed(InterpolatedHint(hint: dynamicHint, site: ThrowSite(file: file, line: line)))
}
}
extension ParserError: CustomReflectable {
/// The fields it printed with before its storage went compact, rather than raw pointers:
/// `ParserError(hint: "Expected digit", file: "NIOIMAPCore/Foo.swift", line: 42)`.
public var customMirror: Mirror {
Mirror(self, children: ["hint": hint, "file": file, "line": line], displayStyle: .struct)
}
}
/// A `#fileID` / `#line` pair in 13 bytes; `StaticString` plus `Int` is 32.
///
/// Points at the literal, so it costs nothing to make. Converted to `String` only when read.
struct ThrowSite: @unchecked Sendable { // @unchecked: points at an immutable string literal.
/// Stands in for a file that is not a pointer-backed literal (never the case for `#fileID`).
private static let unknownFile: StaticString = "<unknown>"
private var fileStart: UnsafeRawPointer
private var lineNumber: UInt32
/// `#fileID` is `Module/File.swift`; anything longer is truncated.
private var fileLength: UInt8
init(file: StaticString, line: Int) {
let file = file.hasPointerRepresentation ? file : Self.unknownFile
self.fileStart = UnsafeRawPointer(file.utf8Start)
self.fileLength = UInt8(clamping: file.utf8CodeUnitCount)
self.lineNumber = UInt32(clamping: line)
}
var file: String {
String(decoding: UnsafeRawBufferPointer(start: fileStart, count: Int(fileLength)), as: UTF8.self)
}
var line: Int { Int(lineNumber) }
}
/// ``ParserError``'s hot-path storage: pointers to the hint and file literals.
///
/// Field order matters: `hintIsASCII` sits past byte 16, beyond every other ``ParseFailure`` payload,
/// so its spare bits hold the enum tags and `ParseFailure` stays 24 bytes rather than 25.
private struct LiteralHint: @unchecked Sendable { // @unchecked: points at immutable string literals.
private var hintStart: UnsafeRawPointer
let site: ThrowSite
private var hintIsASCII: Bool
private var hintLength: UInt16
/// `nil` if `hint` is not a pointer-backed literal or is longer than `UInt16.max` bytes.
init?(_ hint: StaticString, site: ThrowSite) {
guard hint.hasPointerRepresentation, let length = UInt16(exactly: hint.utf8CodeUnitCount) else {
return nil
}
self.hintStart = UnsafeRawPointer(hint.utf8Start)
self.site = site
self.hintIsASCII = hint.isASCII
self.hintLength = length
}
var hint: String {
let bytes = UnsafeRawBufferPointer(start: hintStart, count: Int(hintLength))
guard hintIsASCII else { return String(decoding: bytes, as: UTF8.self) }
return String(decoding: bytes, as: Unicode.ASCII.self)
}
}
/// ``ParserError``'s storage for a digit-count mismatch: the counts, formatted only when read.
///
/// 20 bytes, so like ``LiteralHint`` it leaves byte 21's spare bits for the enum tags. Counts clamp, which
/// no real value reaches: `expected` is a grammar constant (1, 2 or 4) and `got` is a run of digits in
/// one buffer.
private struct DigitCountHint {
let site: ThrowSite
private var expected: UInt16
private var got: UInt32
init(expected: Int, got: Int, site: ThrowSite) {
self.site = site
self.expected = UInt16(clamping: expected)
self.got = UInt32(clamping: got)
}
var hint: String { "Expected \(expected) digits, got \(got)" }
}
/// ``ParserError``'s cold storage: one allocation, 8 bytes inline.
private final class InterpolatedHint: Sendable {
let hint: String
let site: ThrowSite
init(hint: String, site: ThrowSite) {
self.hint = hint
self.site = site
}
}
/// Signals that a protocol message was too complex and required excessive recursive parsing.
///
/// IMAP protocol elements can nest (for example, nested parenthesized lists in BODYSTRUCTURE),
/// and parsing uses recursion to handle this. To prevent stack overflow attacks,
/// the parser enforces a maximum recursion depth. If this limit is exceeded, this error
/// is thrown.
///
/// A safety limit to prevent malicious or extremely unusual protocol messages
/// from causing a stack overflow.
///
/// - SeeAlso: [RFC 3501 Section 4.3](https://datatracker.ietf.org/doc/html/rfc3501#section-4.3) (protocol syntax)
public struct TooMuchRecursion: Error {
/// The maximum number of recursive calls when parsing data before throwing an error.
///
/// The parser maintains a recursion depth counter and throws this error when the
/// depth would exceed this limit. This prevents stack overflow from deeply nested
/// protocol structures.
///
/// Currently fixed at compile-time and not configurable at runtime.
public var limit: Int
init(limit: Int) {
self.limit = limit
}
}
/// Signals that parsing stopped consuming input while it would otherwise have kept going.
///
/// Parsing that produces results without consuming bytes would produce them forever. Rather than spin,
/// the parser throws this, and the connection should be closed: no valid input causes it, so it means
/// either a parser bug or input crafted to find one.
///
/// Unlike ``ParserError`` it is never taken to mean "this alternative did not match", so no
/// backtracking point absorbs it.
public struct NoForwardProgress: Error {
/// Compact, like ``ParserError``'s: no allocation on the throw, and ``ParseFailure`` stays small.
private var site: ThrowSite
/// Creates the error, recording where the check that fired is.
///
/// - Parameters:
/// - file: The file of the check. Defaults to the caller's.
/// - line: The line of the check. Defaults to the caller's.
public init(file: StaticString = #fileID, line: Int = #line) {
self.site = ThrowSite(file: file, line: line)
}
}
extension NoForwardProgress: CustomStringConvertible {
/// Names the check that fired, which is what a log of this error is for.
public var description: String { "NoForwardProgress at \(site.file):\(site.line)" }
}
extension NoForwardProgress: CustomReflectable {
/// `file` and `line`, as before its storage went compact, rather than raw pointers.
public var customMirror: Mirror {
Mirror(self, children: ["file": site.file, "line": site.line], displayStyle: .struct)
}
}