Commit Graph
503 Commits
Author SHA1 Message Date
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
Daniel Eggert dac6e3fb26 Store ParserError hints without allocating
ParserError shrinks from 40 to 24 bytes. A private Storage enum holds a
pointer to a StaticString hint, a digit-count hint formatted when read,
or a boxed String. The throw site is a ThrowSite: file pointer, UInt32
line, UInt8 length.

- Hints are StaticString, so the compiler rejects interpolation.
  Computed hints use `init(dynamicHint:)`, which allocates.
- `parseNDigits` uses `init(expectedDigits:got:)` instead of
  interpolating on every mismatch.
- `hint` is computed; assigning it boxes. A custom Mirror (public
  `CustomReflectable` conformance) keeps the printed form.
- Behavior change: `file` names the throwing site. The `(#fileID)`
  defaults named ParserErrors.swift, and the three `parseOneOf`
  overloads' named ParseInput+Combinators.swift; the array form's
  "none of the options match" now names the calling file.
- `NoForwardProgress` stores a `ThrowSite` too. Public API addition:
  `CustomReflectable` conformance, which keeps `file` and `line` in
  its Mirror.
- ThrowSite and LiteralHint are @unchecked Sendable: they point at
  immortal literals. Both join the unsafe-seams list in ParseInput.swift.

Untyped throws still box every error, so the size buys little here. It
is for typed throws, next, which return the error in registers.
2026-11-24 09:48:49 +09:00
Daniel Eggert 70aa6bea44 Throw NoForwardProgress when parsing stops consuming
A parser bug that stops consuming input used to spin forever on peer
bytes: extractBytes looped with take == 0 once the cursor invariant
broke, the repetition combinators looped on an element that matched
empty, and IMAPInputProcessor looped on a decoder returning messages
without consuming. Each now throws the new public NoForwardProgress
(public init, so a decoder driver outside the library can throw it as
IMAPInputProcessor does), which no backtracking point treats as "did
not match":

- extractBytes throws when the head is empty but bytes remain; the
  scans stop when advancing their walker consumes nothing. Both also
  assertionFailure, and a debug-only check in advance compares what it
  consumed against what was visible before, so tests trap at the bug.
- forEachRepetition backs every repetition combinator and the search
  sources list; the other hand-written grammar loops check progress per
  iteration (requireProgress).
- IMAPInputProcessor allows 4 messages in a row without progress; the
  parsers emit at most 2 (commands) and 1 (responses), pinned by tests
  that run the real decoders.

Catch sites that took any error for a mismatch now catch ParserError
only, or let NoForwardProgress through: mailbox list flags, the body
and section fallbacks, and the run-away literal check. (#885 already
narrowed the tagged extension catches.)

Behavior changes: those loops now report a list cut short by the end of
the input as IncompleteMessage instead of returning what they had. Mostly
not observable through the stream parsers, which retry; a flag list
split mid-flag gets a split-at-every-byte case. The stream parser docs
tell callers who drive them directly to bound results without progress,
as the handlers do.

Reviewer focus: the catch sites, and the limit's reasoning in
IMAPInputProcessor.maximumMessagesWithoutProgress.
2026-11-24 09:48:27 +09:00
Daniel Eggert 2661cef517 Document zero-copy with ByteBuffer and DispatchData 2026-11-24 09:48:20 +09:00
Daniel Eggert c4f3ed753a Tighten Bytes API docs
State the donation threshold only on makeDispatchData(), restore
IMAPByteStorage's allocation cost to the doc comment, move the
copiedBytes() note to the method, and fix four broken links.
2026-11-24 09:48:20 +09:00
Daniel Eggert 36a4b65185 Narrow parser input to IMAPInputBuffer; move design notes out of Bytes docs
RegionSink, ParseInput and IMAPInputBuffer's region plumbing become
internal. Data and DispatchData no longer conform to the parser input
protocols: append them to an IMAPInputBuffer.

History, rejected alternatives and measurements go to implementation
comments; doc comments keep what a caller needs.
2026-11-24 09:48:20 +09:00
Daniel Eggert e7732411fe Make IMAPBuffer.dispatchDonationThreshold internal
A tuning value nothing outside Core needs. Docs outside it now give
the number instead of the name.
2026-11-24 09:48:20 +09:00
Daniel Eggert 7ac4eabfa5 Retain region owners for the length of a gather
RegionSink took owners unretained, so a conformer passing a box it
created inside withStableRegions handed over a dead one: use-after-free
on the first zero-copy extraction. Costs one retain/release per vouched
region per gather; retain counts in the parse benchmarks are unchanged.
2026-11-24 09:48:20 +09:00
Daniel Eggert 33c0b896e3 Label IMAPBuffer's range argument; trap on negative slice lengths
Matches stdlib: dropFirst and prefix trap on a negative count.
2026-11-24 09:48:19 +09:00
Daniel Eggert 3b07cda8d6 Say removeAll may keep a bounded amount for reuse
IMAPOutputBuffer keeps its open segment; the docs said all storage is
released.
2026-11-24 09:48:19 +09:00
Daniel Eggert f07a0700e0 Skip run-away body structure literals without copying
extractBytes copied up to the body size limit only to discard it.
2026-11-24 09:48:19 +09:00
Daniel Eggert 64b109c4fc Don't rebind a ByteRegion's memory in the gather
bindMemory rebinds the caller's memory for good. ByteRegion now states
that its bytes must be bound to UInt8.
2026-11-24 09:48:19 +09:00
Daniel Eggert 13ec89db9f Make parse(limit:_:) and withParseInput(_:) internal
Their closures take a ParseInput, which has no public members, so they
added unusable API to ByteBuffer, DispatchData, Data and [UInt8].
2026-11-24 09:48:19 +09:00
Daniel Eggert 43cdb7836c Cap stray spaces before a line ending at 40
RFC 3501 allows none. On main the cap came from recursion depth
(about 100); "Parse from ParseInput" made it an explicit 1024.
2026-11-24 09:48:18 +09:00
Daniel Eggert 3efffa1dc6 Drop NIO from NIOIMAPCore (mostly scripted)
NIOIMAPCore and its tests no longer depend on swift-nio; NIOIMAP declares
the dependency it was getting transitively. Hand edits: Package.swift and
NIOIMAPCore.md. Everything else is the output of, on the parent
commit (zsh):

  F=($(grep -rlE '^import ((struct|enum|class|protocol) )?NIO(Core|TestUtils)?(\.[A-Za-z]+)?$' \
      Sources/NIOIMAPCore Tests/NIOIMAPCoreTests))
  perl -0pi -e 's/^import (?:(?:struct|enum|class|protocol) )?NIO(?:Core|TestUtils)?(?:\.\w+)?\n//mg;
      s/\n\n\n+/\n\n/g' $F

Public break: depending on NIOIMAPCore no longer provides swift-nio.
2026-11-24 09:48:18 +09:00
Daniel Eggert f57f5c6f84 Call parseQuoted / parseLiteral directly in parseString
`self.parseQuoted` passed as a value allocates a partial-application
context per call. Spelling the two alternatives out forms no closure.
parseStringAllowingNonASCII was identical and now delegates.

Measured after "Replace keyword lookup tables with switches": 142
allocations per BODYSTRUCTURE message, 20% of the parser's total.
2026-11-24 09:48:18 +09:00
Daniel Eggert dca7023ccb Rename ParseBuffer to ParseInput (scripted)
Drops the `typealias ParseBuffer = ParseInput` from "Parse from
ParseInput instead of ByteBuffer". Script output, run on the parent
commit (zsh), plus one hand edit:

  git rm Sources/NIOIMAPCore/Parser/ParseBuffer.swift
  F=($(grep -rl '\bParseBuffer\b' Sources/NIOIMAPCore/Parser))
  perl -pi -e 's/\bParseBuffer\b/ParseInput/g' $F
  swift format -i $F

swift-format re-joins signatures that now fit in 120 columns.

Hand edit: the same rename in Tests/NIOIMAPCoreTests/TestUtilities.swift,
outside the script's grep.
2026-11-24 09:48:18 +09:00
Daniel Eggert 5d1358d09c Deliver received literals zero-copy via IMAPInputProcessor
The handlers stage reads in an IMAPInputBuffer (IMAPInputProcessor)
instead of NIOSingleStepByteToMessageProcessor's coalesced ByteBuffer,
so a FETCH/APPEND literal piece of at least 1 KiB within one read of
at least 1 KiB is delivered as a reference to the received bytes.
Shorter pieces are copied; bytes from smaller reads are copied twice,
into a tail on arrival and out of it on delivery. The decoders keep
their ByteBuffer entry point for ByteToMessageHandler and the decoder
verifier; that path copies.

A decoder error or PayloadTooLargeError is final: the buffer is dropped
and later reads rethrow it without decoding (ByteToMessageHandler also
stops decoding, but fires dataReceivedInErrorState). Keeping the
unparsed bytes would make every later read append, fail on the same
bytes and copy all of them into IMAPDecoderError.buffer: unbounded
memory and quadratic copying, past the maximumBufferSize check. Errors
thrown by the message receiver (e.g. UnexpectedResponse) pass through
and are not final.

Reads under 1 KiB are copied into IMAPInputBuffer's tails, so 1-byte
reads cost a region per KiB and pin no receive buffers. A larger read
still pins its whole receive buffer, which maximumBufferSize does not
count.

Review focus: IMAPInputProcessor.

Behavior changes:
- A stream whose input failed to parse stays failed.
- IMAPDecoderError.buffer holds the bytes waiting to be parsed when the
  error was thrown.
- Leftover literal bytes followed by a read that starts a new region
  reach the handler's consumer as two .streamingBytes events, not
  one. Every read of at least 1 KiB starts a region; a smaller one
  does when the last region is a retained read, or a tail it does not
  fit or that is not uniquely referenced.
  ParseInput.extractBuffer(upTo:) takes bytes from the current region
  only, where the old code took min(remaining, readable) across the
  whole buffer. Legal, but observable. A caller passing a multi-region
  buffer to the stream parsers directly sees this from the previous
  commit on.
2026-11-24 09:48:18 +09:00
Daniel Eggert bc7f8e6043 Parse from ParseInput instead of ByteBuffer
The grammar now runs on the ~Escapable ParseInput cursor; ParserLibrary
and its ParseBuffer are deleted. The stream parsers are generic over
ConsumableParserInputBuffer and gather once per call: CommandParser
frames synchronizing literals and parses through the same cursor,
narrowing its limit instead of slicing. The NIO handlers still feed
ByteBuffers, through its ParserInputBuffer conformance.

Review focus: CommandParser.parseCommandStream and
ResponseParser.parseResponseStream (what is consumed on each exit path).

Behavior changes:
- Stray spaces before a line ending: up to
  ParseInput.maximumStraySpaces (1024) are accepted; more throw
  ParserError. On main, PL.parseNewline recursed through composite once
  per space, so ~100 threw TooMuchRecursion from the shared 100-frame
  tracker. Both a looser limit and a different error type.
- Trailing spaces with no line ending yet report IncompleteMessage while
  under the cap, where they used to throw ParserError. Fixes the client
  side (ResponseParser), which has no framing layer, for a read split as
  "* 1 EXISTS " | "\r\n".
- From an IMAPInputBuffer, payload pieces of at least 1 KiB taken from
  a retained read (>= 1 KiB, fixed address) refer to it; a large Data
  is retained as the buffer's one copy. Smaller pieces and tail bytes
  are copied. From a bare ByteBuffer, payloads are copied.

Grammar edits beyond the cursor: the QUOTA resource loop binds
parseOptional's result to an explicit `Void?`, and parseLookupKeyword
loses a comment about the tracker it no longer takes. ParserError.hint
gains a note to keep hot-path hints literal: ParserLibrary's
interpolated ones, deleted here, allocated on every mismatch.

Public API break: parseCommandStream(buffer:) and
parseResponseStream(buffer:) are generic. ByteBuffer conforms in
NIOIMAP, so a caller importing only NIOIMAPCore must import NIOIMAP to
pass one.

Temporary: `typealias ParseBuffer = ParseInput` keeps the grammar's
spelling until "Rename ParseBuffer to ParseInput (scripted)". Removes
LegacySubParser, the ParseBuffer cursor-method shim and the framing
bridge from "Move SynchronizingLiteralParser onto ParserInputBuffer".
2026-11-24 09:48:15 +09:00
Daniel Eggert 911cc4f824 Move SynchronizingLiteralParser onto ParserInputBuffer
The framing pass reads through a ParseInput cursor instead of a
ByteBuffer: one region scan per line ending, then a few peeks backwards
from it to classify the line. An internal overload takes a cursor the
caller has already gathered, so the command parser can later frame and
parse through one gather.

Review focus: SynchronizingLiteralParser over a cursor (findLineEnd,
lineFragmentType; every index is a distance from the read position).

Public API break:
SynchronizingLiteralParser.parseContinuationsNecessary(_:) is generic
over ParserInputBuffer. ByteBuffer conforms in NIOIMAP, so a caller
importing only NIOIMAPCore must import NIOIMAP to pass one.

Temporary: CommandParser builds a cursor over its ByteBuffer to call the
framing pass, until it takes a ParserInputBuffer itself.
2026-11-24 09:47:34 +09:00
Daniel Eggert a72d61d666 Make payload cases IMAPBuffer
The four raw-payload cases become IMAPBuffer so a large literal can be
handed in and out without a copy: FetchResponse.streamingBytes,
AppendCommand.messageBytes, AppendCommand.CatenateData.bytes,
CommandStreamPart.continuationResponse.

Review focus: writeBytes(IMAPBuffer) keeps payloads by reference
(ZeroCopyWriteTests); the parser's extractBuffer(upTo:) still copies.

Updates IMAPTool and the IMAPCommands append/continuation wrappers.

Public API breaks:
- The four cases above: ByteBuffer -> IMAPBuffer.

Removes the writeBuffer(inout ByteBuffer) shim from "Encode into an
EncoderOutputBuffer sink".
2026-11-24 09:47:34 +09:00
Daniel Eggert 3cd39758d4 Use [UInt8] for small model fields
Small fields (mailbox names, atoms, quoted strings, envelope fields,
base64, URLs, the authentication challenge, catenateURL, ...) become
[UInt8]. The four raw-payload cases stay ByteBuffer until "Make payload
cases IMAPBuffer".

The grammar's string productions return [UInt8]. The parser still runs
on ParseBuffer, so its cursor methods copy out of the ByteBuffer for now.

Review focus: the model files' encoders and ModifiedUTF7 on arrays.

Updates IMAPTool and the IMAPCommands catenate-URL wrapper.

Public API breaks:
- ~38 public declarations ByteBuffer -> [UInt8].
- ModifiedUTF7.EncodingRoundtripError.buffer -> .bytes.
- Response.authenticationChallenge and ContinuationRequest.data are
  [UInt8]; an empty challenge is [].

Internal: writeBufferAsBase64 -> writeBytesAsBase64; the ByteBuffer
writeIMAPString overload is gone.
2026-11-24 09:47:33 +09:00
Daniel Eggert 8c7724cc6d Rewrite grammar calls as cursor methods (scripted)
`PL.f(…, buffer: &b, tracker: t)` becomes `b.f(…)`, the spelling
ParseInput's primitives and combinators use, so that swapping the cursor
later touches only primitives. Bare grammar functions passed as values
become `{ try f(buffer: &$0, tracker: $1) }`.

Behavior unchanged except recursion accounting: leaf primitives
(matchFixed, parseSpaces, readByte, ...) no longer spend a frame of the
caller's StackTracker, so input at the depth limit can nest one to three
levels deeper. This is permanent, not a shim artifact: ParseInput's
leaves take no tracker. At the end of the stack SEARCH nesting depth 90
parses and 91 throws TooMuchRecursion (searchNestingDepthBoundary).
While the shim exists, matchNewline gets a fresh 100-frame budget.

ParseBuffer+CursorMethods.swift (hand-written, temporary) forwards the
new spellings to ParserLibrary; the rest is the output of the script
below. To reproduce, on the parent commit:

  F=(Sources/NIOIMAPCore/Parser/Grammar/*.swift
     Sources/NIOIMAPCore/Parser/{Command,Response}Parser.swift)
  python3 rewrite_grammar.py $F && swift format -i $F

rewrite_grammar.py:

    #!/usr/bin/env python3
    # Rewrites ParserLibrary calls (`PL.f(…, buffer: &b, tracker: t)`) into cursor methods (`b.f(…)`),
    # the shape ParseInput's primitives and combinators have.
    #
    # Usage: python3 rewrite_grammar.py FILE...    (in place), then `swift format -i FILE...`
    import re
    import sys

    LIT = r'"(?:[^"\\]|\\.)*"'  # a string literal
    B = r'buffer:\s*&(\w+)'     # the cursor argument; its name becomes the receiver
    T = r'tracker:\s*([\w.]+)'  # the tracker argument

    RULES = [
        # Primitives that take no tracker. Their arguments are kept; `buffer:` and `tracker:` go.
        (rf'PL\.parseFixedString\((\s*)({LIT}|\w+)((?:,\s*\w+:\s*[\w.]+)*),\s*{B},\s*{T}\s*\)', r'\4.matchFixed(\1\2\3)'),
        (rf'PL\.parseFixedByte\(\s*([^,()]+),\s*{B},\s*{T}\s*\)', r'\2.matchByte(\1)'),
        (rf'PL\.parseSpaces\(\s*{B},\s*{T}\s*\)', r'\1.parseSpaces()'),
        (rf'PL\.parseNewline\(\s*{B},\s*{T}\s*\)', r'\1.matchNewline()'),
        (rf'PL\.parseByte\(\s*{B},\s*{T}\s*\)', r'\1.readByte()'),
        (rf'PL\.parseBytes\((\s*){B},\s*{T},\s*length:', r'\2.extractBytes(\1length:'),
        (rf'PL\.parseBytes\((\s*){B},\s*{T},\s*upTo:', r'\2.extractBuffer(\1upTo:'),
        (rf'PL\.(parse(?:Zero|One)OrMoreCharacters)\(\s*{B},\s*{T}\s*\)', r'\2.\1'),
        (rf'PL\.(parse(?:Zero|One)OrMoreCharacters)\((\s*){B},\s*{T},\s*', r'\3.\1(\2'),
        # `parser: PL.parseSpaces` as a value: spaces take no tracker, so it needs a closure.
        (r'parser:\s*PL\.parseSpaces\b', r'parser: { input, _ in try input.parseSpaces() }'),
        # Combinators keep their tracker; only `buffer:` moves to the receiver.
        (rf'(?:PL|ParserLibrary)\.(composite|parseOptional|parseZeroOrMore|parseOneOrMore|parseUnsignedInteger|parseUnsignedInt64)\((\s*){B},\s*',
         r'\3.\1(\2'),
        (r'(?:ParserLibrary|PL)\.parseBufferAsUTF8\(', r'decodeUTF8('),
        # The cursor takes enums where ParserLibrary took Bools.
        (r'\bcaseSensitive:\s*true\b', 'caseSensitivity: .caseSensitive'),
        (r'\bcaseSensitive:\s*false\b', 'caseSensitivity: .caseInsensitive'),
        (r'\ballowLeadingSpaces:\s*true\b', 'leadingSpaces: .allowed'),
        (r'\ballowLeadingSpaces:\s*false\b', 'leadingSpaces: .rejected'),
        (r'\ballowLeadingZeros:\s*true\b', 'leadingZeros: .allowed'),
        (r'\ballowLeadingZeros:\s*false\b', 'leadingZeros: .rejected'),
    ]

    # Two call sites the hand-written code spells with a trailing closure rather than `parser:`.
    TRAILING = ['parseByteRange_length', 'parseQuotaLimit']

    # Grammar functions passed as values become closures, `{ try parseX(buffer: &$0, tracker: $1) }`: a
    # local function over a non-escapable cursor cannot be a function value before Swift 6.4. `self.`
    # method references stay as they are, and so does `parse2Digit`, which the hand-written code never
    # wrapped.
    KEEP = {'parse2Digit'}

    def wrap(name):
        return name if name in KEEP else f'{{ try {name}(buffer: &$0, tracker: $1) }}'

    def closing(src, k):
        """Index just past the bracket matching the one before `k`."""
        depth = 1
        while depth:
            c = src[k]
            if c in '([{':
                depth += 1
            elif c in ')]}':
                depth -= 1
            k += 1
        return k

    def depth0(src, end):
        """Whether `src[end]` is outside every bracket opened in `src[:end]`."""
        depth = 0
        for c in src[:end]:
            depth += c in '([{'
            depth -= c in ')]}'
        return depth == 0

    def rewrite_one_of(src):
        # PL.parseOneOf(a, b, buffer: &x, tracker: t) -> x.parseOneOf(a, b, tracker: t), wrapping bare
        # `parseX` alternatives as above.
        out, i = [], 0
        while (j := src.find('PL.parseOneOf(', i)) >= 0:
            k = j + len('PL.parseOneOf(')
            m = closing(src, k)
            args = src[k:m - 1]
            arg = next(a for a in re.finditer(r'(\s*)buffer:\s*&(\w+),', args) if depth0(args, a.start()))
            args = args[:arg.start()] + args[arg.end():]
            args = re.sub(r'(?<=[(\[,])(\s*)(parse\w+)(?=\s*[,)\]])', lambda a: a.group(1) + wrap(a.group(2)), '(' + args)[1:]
            out += [src[i:j], f'{arg.group(2)}.parseOneOf(', args, ')']
            i = m
        return ''.join(out) + src[i:]

    for path in sys.argv[1:]:
        src = open(path).read()
        for pattern, replacement in RULES:
            src = re.sub(pattern, replacement, src)
        src = rewrite_one_of(src)
        for name in TRAILING:
            src = re.sub(rf',\s*parser:\s*{name}\s*\)', f') {{ try {name}(buffer: &$0, tracker: $1) }}', src)
        src = re.sub(r'(parser:\s*)(parse\w+)\b(?!\()', lambda m: m.group(1) + wrap(m.group(2)), src)
        open(path, 'w').write(src)
2026-11-24 09:47:33 +09:00
Daniel Eggert cbbce83ab6 Encode into an EncoderOutputBuffer sink
EncodeBuffer appends to `any EncoderOutputBuffer` (IMAPOutputBuffer by
default) instead of holding a ByteBuffer. Chunks come out as
IMAPBufferList; the handlers write one buffer per payload via
makeOutboundBuffers(). CommandEncoder is deleted: it kept only the first
chunk of a synchronizing literal and had no users but its own test.
nextChunk() caps a chunk at 64 regions, coalescing the tail, whatever
the sink returned, so no sink (a caller's own included) has to.

EncodeBuffer stages writes under 256 bytes inline and appends them to
the sink in one call: one existential call per ~256 bytes, not per
write. It flushes before every hand-out and before any direct sink
append (writeBytes(IMAPBuffer), larger writes), so payloads still reach
the sink by reference and in order. Conformers see batched appends;
byteCount may lag until a hand-out (documented on EncoderOutputBuffer).
Per-write cost therefore no longer separates the two sinks, so the
docs choosing IMAPOutputBuffer over ByteBufferOutput (ByteBufferOutput's,
EncoderOutputBuffer's, IMAPOutputBuffer's, the handlers') rest on the
hand-out instead.

Review focus: totalWritten / handedOut and absolute stop points in
nextChunk() (an off-by-one deadlocks the protocol, see
EncodeBufferSinkTests), the staging flush points, and
IMAPClientHandler.writeChunk's promise handling across several writes.

The CLI example's round-trip handler compares all chunks via the public
nextChunk() (it compared only the first) and drops its SPI import.

Public API breaks:
- CommandEncodeBuffer / ResponseEncodeBuffer: `init(buffer:…)` ->
  `init(sink: = IMAPOutputBuffer(), …)`; no longer Sendable.
- EncodeBuffer.Chunk.bytes and ResponseEncodeBuffer.readBytes() are
  IMAPBufferList.
- EncodeBuffer.writeBytes takes a Collection; writeBytes(IMAPBuffer) added;
  writeBuffer(inout ByteBuffer) removed.
- EncodeBuffer (SPI) is no longer Sendable; == / hash compare the pending
  bytes.

Public API addition: CommandEncodeBuffer.nextChunk() -> Chunk?, with
Chunk { bytes, nextStep } and NextStep { proceed,
awaitContinuationRequest }, so a client with its own transport needs no
SPI. nextStep awaits whenever a chunk ends at a synchronizing literal
header, also at the last byte written (APPEND .beginMessage,
.catenateData(.begin)), where the SPI Chunk.waitForContinuation says no
wait. ClientStateMachine uses it and imports no NIOIMAPCore SPI.

Behavior change: an APPEND part that ends in a literal the APPEND flow
doesn't expect (zero-length, e.g. an empty mailbox with quoted strings
off) waits for `+` before the next part instead of running ahead; its
write promise completes after the `+`.

Examples/PerformanceTester (IMAPDispatchClient) does not build from here
until "Measure IMAPDispatchClient against either library".

Temporary: EncodeBuffer+ByteBufferShim.swift keeps an internal
writeBuffer(inout ByteBuffer) for the model types that still hold one.
2026-11-24 09:47:33 +09:00
Daniel Eggert ab79acbdc5 Add parser input types
ParseInput: a ~Escapable, BitwiseCopyable cursor over a table of region
pointers, with the primitives and combinators as methods. Input buffers:
ParserInputBuffer (+ Consumable, StableRegion refinements), conformances
for ByteBuffer / Array / Data, and IMAPInputBuffer, the staging deque that
can hand out payloads by reference.

IMAPInputBuffer keeps reads of at least copyThreshold (1 KiB) by
reference and copies smaller ones into a 1 KiB tail (an OutputSegment),
so a peer sending a byte per read costs a region per KiB, not a region,
an object and a retained receive buffer per byte. A tail is written
only past its end, only while the buffer holds the sole reference, and
never reallocated; a used-up tail with room is continued by the next
small read into an empty buffer. Only a StableAddressByteRegion (arrays,
ByteBuffer) or an IMAPBuffer over one is kept by reference; any other
large region, e.g. Data, is copied once.

A bare DispatchData.Region is copied too: it points into its
DispatchData without keeping it alive, so it is not a
StableAddressByteRegion. append(contentsOf:) is the zero-copy path for
DispatchData.

Public API additions: IMAPInputBuffer.append(contentsOf: DispatchData)
walks a read's regions with enumerateBytes, so it builds no regions
array; a large region is kept with the DispatchData that owns it (also
the owner a makeDispatchData() donation retains), small ones go to the
tail. append(_:) gains overloads for a StableAddressByteRegion and an
IMAPBuffer, so appending a ByteBuffer, an array or an IMAPBuffer pays no
dynamic cast; IMAPByteStorage.init(_:) gains one for an IMAPBuffer.

Additive; the grammar still runs on ParseBuffer. Review focus: _span(_:)
and RegionSink (the two read-side unsafe seams), the head invariant in
advance(by:), the gather's 64-frame recursion cap,
IMAPInputBuffer.writableTail(fitting:), and DispatchDataRegion, what
append(contentsOf:) keeps: its @unchecked Sendable and its
StableAddressByteRegion (fixed-address) promise.

Temporary: main's SubParser is renamed LegacySubParser so both coexist.
2026-11-24 09:47:33 +09:00
Daniel Eggert f45f5df879 Add encoder output types
IMAPBuffer / IMAPByteStorage (owner + range, no pointer), IMAPBufferList,
OutputSegment, the EncoderOutputBuffer sink protocol and its two
conformers: IMAPOutputBuffer (core, donates to DispatchData) and
ByteBufferOutput (NIOIMAP, fills a ByteBuffer in place).

StableAddressByteRegion is the public opt-in for a foreign region to be
donated by makeDispatchData() rather than copied: arrays conform, and
NIOIMAP conforms ByteBuffer with public API only (CoW keeps a held
copy's readable bytes in place).

makeDispatchData() donates only regions of at least
IMAPBuffer.dispatchDonationThreshold (512) bytes; each run of shorter
or unstable regions is copied into one malloc'd region freed inline
(.free). Measured: a donated region costs ~4 mallocs, 300-500 B and
~400 ns plus an async deallocator block; a copy costs a memcpy. The
deallocator captures the owner's concrete type, not an existential.

Public API for adapting a buffer type, so NIOIMAP's ByteBuffer support
needs no SPI and a third-party type can do the same:
IMAPBuffer.copyThreshold and dispatchDonationThreshold;
backingRegion(as:), which recovers the backing region and range without
copying; withUnsafeBytesAndOwner(_:), which hands out bytes with a fixed
address and their owner, under the same rule makeDispatchData() uses.
IMAPByteStorage.init(_:) has an overload for a StableAddressByteRegion,
which records the fixed address statically: the generic init isn't
specialized across modules, so its dynamic cast would run once per
wrapped ByteBuffer.

Additive; nothing uses them yet. Review focus: OutputSegment's
@unchecked Sendable (handed-out ranges never overlap the write tail),
IMAPOutputBuffer's copy-on-write state box and its
@exclusivity(unchecked) properties, and makeDispatchData()'s copy runs.
2026-11-24 09:47:33 +09:00
Daniel Eggert 55fb61a8a7 Count skipped literals against the run-away body budget
parseInvalidBody capped each literal at the remaining budget but never
added it to byteCount, so N literals could skip N × 200,000 bytes.
2026-11-24 09:47:11 +09:00
Daniel Eggert 57a1351218 Store ParserError.file as StaticString
#fileID exceeds the small-string limit, so a String heap-allocates on
every throw; parser errors are ordinary control flow.
2026-11-24 09:46:50 +09:00
Daniel Eggert 5d0d181a30 Decode UTF-8 with String(validating:as:)
The hand-rolled loop (collect [Unicode.Scalar], then build a
UnicodeScalarView) regrew the string per scalar and was a dominant
source of parser allocations. Best-effort decoding gets the same fast
path, and no longer returns "" for non-contiguous input.

Renames String+ByteBuffer.swift to String+UTF8Bytes.swift; it never
touched ByteBuffer.
2026-11-20 12:49:17 +01:00
Daniel Eggert b828d31375 Trim encoder comments; count redacted bytes without an Array 2026-11-20 12:49:17 +01:00
Daniel Eggert b7b0baff5c Keep IncompleteMessage inside extension values
parseTaggedExtensionComplex's catch-alls swallowed IncompleteMessage,
so a read ending inside a tagged-ext-comp (e.g. LIST-EXTENDED's
`("CHILDINFO" ("SUBSCRIBED"))`) failed the response. Catch
ParserError only. Also on main.
2026-11-20 12:49:16 +01:00
Daniel Eggert a2c63074c4 Keep IncompleteMessage after PREVIEW
PREVIEW's optional " (LAZY)" was parsed with a catch-all, so a read
ending in "PREVIEW " or "PREVIEW (LA" returned lazy: false and left
the rest unparsed. Catch ParserError only.

Behavior change: such reads report IncompleteMessage. The
FetchAttribute+Tests fixture that ended in " " now ends in ")".
2026-11-20 12:49:16 +01:00
Daniel Eggert 979c66ada0 Keep a cut-short literal length in an invalid body incomplete
The fallback that skips an unparseable body structure turned every error
from parsing a literal's length into "Run-away literal", including
IncompleteMessage. A client read ending inside the length (`{1` | `0}`)
therefore failed the response, though the same bytes in one read parse.

The new test splits a response at every byte and expects the events of
the unsplit read.
2026-11-20 12:49:15 +01:00
Daniel Eggert 9f6320a3a7 Remove unused ByteBuffer imports
Files that import struct NIO.ByteBuffer but never name it:
  for f in $(git grep -l '^import struct NIO.ByteBuffer$' -- Sources Tests); do
    grep -v '^import struct NIO.ByteBuffer$' $f | grep -q ByteBuffer || echo $f
  done
Each loses the import line, and a now-doubled blank line.
2026-11-20 12:49:15 +01:00
Daniel Eggert 44ff0e8d5e Fix EncodeBuffer doc comments
Server factories described themselves as client ones; capabilities
overloads documented a nonexistent options parameter; DocC symbol
links used '.' instead of '/'.
2026-11-20 12:49:15 +01:00
Daniel Eggert cfdf92c7ac Move parser error types into ParserErrors.swift
Move BadCommand, ParserError, TooMuchRecursion and IncompleteMessage
out of ParserLibrary.swift. Besides the move: IncompleteMessage.init
goes fileprivate -> internal and gains a doc comment; the new file has
the license header.
2026-11-20 12:49:15 +01:00
Daniel Eggert 757710b755 Replace keyword lookup tables with switches
parseFromLookupTable built a dictionary of capturing closures on every
call; selectingKeyword + switch calls the sub-parser directly.
parseMessageAttribute's 19-entry table cost 19 closure boxes plus the
dictionary's storage per call, one of which was invoked. Parsing FETCH
responses with BODYSTRUCTURE, the pattern was ~25% of the parser's
allocations and ~19% of its allocated bytes.

parseLookupKeyword scans the keyword with a fresh tracker
(.makeNewDefault), so the scan doesn't count towards recursion depth;
the sub-parser gets the caller's tracker.

Unknown-keyword ParserError hints now name the production and no longer
include the offending keyword (public ParserError.hint changes).
2026-11-20 12:49:15 +01:00
Daniel Eggert 13a8d51c9e Encode message identifier sets with an index loop
writeArray iterates RangeSet.Ranges with its iterator, which costs two
mallocs per range inside libswiftCore; subscripting by index costs none.
Output unchanged.

mallocs, measured at the stack tip with the IMAPEncoding benchmarks
(added in PR 4): encode.command.select_qresync 20 → 6,
uid_fetch_set_fragmented 20 → 6, uid_store_add_seen 8 → 6,
encode.commands.all 356 → 284.

The writeArray call is upstream code; the cost is also on main.
2026-11-20 12:49:14 +01:00
Daniel Eggert 7b2568647a Escape quoted strings into a stack buffer
One write per quoted string instead of one per byte (plus an Array per
escaped byte).
2026-11-20 12:49:12 +01:00
Daniel Eggert 31978d2594 Encode numbers without string interpolation
Add EncodeBuffer.writeByte / writeDecimal / writeLiteralHeader /
writeRedactedByteCount and use them for every numeric interpolation
in encoders. writeString("…\(x)…") sites become separate writeString
calls; quote-wrapped ones ("\"\(x)\"") stay. writeMailboxStatus
writes each attribute directly instead of building (String, String)
pairs. Output unchanged for valid values; avoids String formatting and
allocation. Invalid (negative) FullDate/FullTime fields now pad after
the sign: -0005, not 00-5.

writeLiteralHeader takes LiteralSynchronization (`{n+}`) and
LiteralKind (`~{n}`) enums.
2026-11-20 12:49:09 +01:00
Daniel Eggert cc76f4bee0 Make writeIfExists / write(if:) free functions
As EncodeBuffer methods, `self.write(if:) { self.write… }` borrows the
buffer while the closure mutates it, forcing a copy and a CoW on the
first write inside the closure.

Hand edit: Sources/NIOIMAPCore/ByteBuffer+WriteLiteral.swift, which
defines the free functions. Call sites converted with:
  git ls-files -z 'Sources/*.swift' 'Tests/*.swift' | xargs -0 perl -pi -e \
    's/\b(?:self\.buffer|self|buffer)\.(writeIfExists\(|write\(if:)/$1/g'
2026-11-15 18:47:13 +01:00
Daniel Eggert 42ecc68f9a Delete unused _ByteBufferProtocol.swift
Proof-of-concept API template; nothing references it.
2026-11-15 18:06:51 +01:00
Daniel Eggert 6b1b196cd6 Use NFC for ModifiedUTF7.encode (#884) 2026-11-13 13:38:17 +01:00
Daniel Eggert b2c94a8bce Only skip an orphaned LF after a response-ending CR (#882) 2026-11-10 17:49:13 +01:00
Ravindu Danthanarayana 95590ebc81 Fix corruption of FETCH literals when the header CRLF is split (#880) 2026-11-04 20:57:20 +01:00
Daniel Eggert d67ffdf153 Fix encode/parse round-trip bugs (#868)
* Separate LIST from its independent select options

`.listIndependent([.remote], …)` encoded as `LIST(REMOTE) …`.

RFC 5258: `list = "LIST" [SP list-select-opts] SP mailbox SP mbox-or-pat`.

* Keep leading zeros in fractional seconds

`12:34:56.05` parsed as `fraction: 5` and re-encoded as `12:34:56.5`,
changing the value.

RFC 3339: `time-secfrac = "." 1*DIGIT`. `FullTime.fraction` becomes
`FullTime.Fraction`, which stores the digits; `init?(_:)` validates,
literals trap, `String.init` reads.

* Model the RFC 3339 time offset

`;EXPIRE=2025-12-31T23:59:59Z` failed to parse inside a URL: the
parser stopped before `Z`. The encoder never wrote an offset.

RFC 4467: `expire = ";EXPIRE=" date-time`; RFC 3339: `full-time =
partial-time time-offset`, `time-offset = "Z" / time-numoffset`. Adds
the required `FullTime.offset`.

* Encode LIST extended data

`MailboxInfo.extensions` was parsed but never written, so
`* LIST (\Marked) "/" "Fruit" ("CHILDINFO" ("SUBSCRIBED"))` lost
`("CHILDINFO" …)` on re-encode.

RFC 5258: `mailbox-list = … mailbox [SP mbox-list-extended]`.

* Round-trip multi-value LIST option values

`.array(["a", "b"])` encoded as `(("a" "b"))`; the parser rejected both
that and `("a" "b")`: it took the `astring` branch first and could not
backtrack.

RFC 5258: `option-value = "(" option-val-comp ")"`, `option-val-comp =
astring / option-val-comp *(SP option-val-comp) / "(" option-val-comp
")"`. The parser reads a sequence of elements; the encoder writes
several values inside the `option-value` parentheses.

* Validate JMAPACCESS URLs

`.jmapAccess(URL(string: "jmap", relativeTo: base))` encoded as
`JMAPACCESS "jmap -- https://example.com/"` (`URL.description`); `http`
URLs were written though the parser rejects them.

The payload becomes `ResponsePayload.JMAPAccessURL`: `init?(_:)` resolves
against the base and requires `https`, a host, and no escaping inside
`quoted`; `URL.init` reads. The parser uses the same check.

* Make RESETKEY mechanisms require a mailbox

`.resetKey(mailbox: nil, mechanisms: [.internal])` encoded as bare
`RESETKEY`, silently dropping the mechanisms and resetting every key.

RFC 4467: `resetkey = "RESETKEY" [SP mailbox *(SP mechanism)]`. The
payload becomes `Command.ResetKeyScope`: `.allMailboxes` or
`.mailbox(_:mechanisms:)`.

* Hoist a #require the compiler flagged as redundant

* Cite RFC 7162 for SEARCH MODSEQ entry types

The docs described these as RFC 5464 GETMETADATA options, with
GETMETADATA examples. The grammar is RFC 7162 `search-modseq-ext`.

* Fix doc nits

- `ExtendedSearchScopeOptions.content` is a dictionary, not an array.
- `NamespaceDescription` init in the `NamespaceResponse` example needs
  `try` and `responseExtensions:`.
- `TaggedExtensionLabel` example: `SELECT INBOX (CONDSTORE)` parses as
  `.condStore`; use `RELEVANCY`.
- Stray `’` in a parser hint.
2026-11-04 17:41:53 +00:00
Daniel Eggert 9f61149d6d Validate IMAP URL components (#867)
* Validate percent-encoded IMAP URL components

`EncodedMailbox(mailbox: "x] x\r\n* BYE")` was written verbatim inside
the bare URL of `[REFERRAL …]`, injecting a response; likewise
`EncodedUser`, `EncodedAuthenticationType`, `EncodedSearch`,
`EncodedSection`.

RFC 5092: `enc-user`/`enc-auth-type = 1*achar`, `enc-mailbox`/
`enc-search`/`enc-section = 1*bchar`. Each type's public `var` and
labelled init become `init?(_:)`, literals trap, `String.init` reads.
One helper validates by character class and `pct-encoded` triplet, and
uppercases hex digits as the parser does, so values round-trip.

* Validate URLAUTH tokens

`EncodedAuthenticatedURL(data: "x\r\n* BYE")` was written verbatim at the
end of a URLAUTH URL, injecting a response.

RFC 4467: `enc-urlauth = 32*HEXDIG`. `init(data:)` and the public `var`
become `init?(_:)`; literals trap; `String.init` reads. The parser read
exactly 32 digits, so longer tokens didn't round-trip; it now reads all.

* Add IMAPServer.Host and keep IP-literal brackets

`IMAPServer(host: "h] x\r\n* BYE")` was written verbatim in the bare URL
of `[REFERRAL …]`, injecting a response. `imap://[::1]/` parsed as host
`::1` and re-encoded as `imap://::1/`. A negative port encoded as `:-1`.

RFC 3986: `host = IP-literal / IPv4address / reg-name`. New nested
`IMAPServer.Host` replaces the `String`: `init?(_:)` validates IPv6,
IPvFuture and reg-name (IPv4 is a subset), literals trap. The parser
keeps the brackets, accepts all of reg-name, and validates via `init?`;
its unreachable IPv4 branch is gone. `port` is now `UInt16?`.

* Don't parenthesize URLFETCH responses

`.urlFetch([.init(url: "url", data: nil)])` encoded as
`URLFETCH("url" NIL)`, which our parser rejects.

RFC 4467: `urlfetch-data = "URLFETCH" 1*(SP url-full SP nstring)`. Write
each pair after a space, unparenthesized. Fix fixtures that enshrined
the old output.

* Remove dead URL and date writers

`writeAuthIMAPURLRump`, `writeAuthIMAPURLFull`, `writeRelativeIMAPURL`,
`writeURLFetchType`, `writeInternetMessageDate` and
`writeListSelectBaseOptionQuoted` had no callers outside their own
encode tests, nor did the writers only they reached
(`writeAuthenticatedURL(NetworkMessagePath)`, `writeNetworkPath`,
`writeAbsoluteMessagePath`, `writeIUIDOnly`,
`writeURLMessageSectionOnly`, `writeMessagePathByteRangeOnly`). Delete
them and those tests; parse tests stay.

* Keep a section's trailing slash unless a partial follows

`imap://h/INBOX/;UID=1/;SECTION=1/` parsed with section `1`, so
`EncodedSection("1/")` didn't round-trip: the parser dropped the `/`
even when no `;PARTIAL=` followed it. Drop it only when one does.

* Reject `*` as a URL authentication type

`.type("*")` encoded as `;AUTH=*`, which parses as `.any`; `.type("*x")`
failed to parse, since `*` matched first.

RFC 5092: `iauth = ";AUTH=" ( "*" / enc-auth-type )`. `init?(_:)`
rejects `*`; the parser tries the longer `enc-auth-type` first.
2026-11-04 17:41:53 +00:00
Daniel Eggert 4606da62d2 Validate response text, command tags and namespace delimiters (#866)
* Reject invalid response text when writing

`.no(.init(text: "No mailbox x\r\n* BYE pwned"))` was written verbatim,
injecting an untagged response; likewise tagged, BYE, PREAUTH and
continuation responses.

RFC 9051: `text = 1*(TEXT-CHAR / UTF8-2 / UTF8-3 / UTF8-4)`. `writeText`
now asserts no NUL, CR or LF. Empty stays valid. The parser now accepts
UTF-8 text.

* Add Command.Tag for command and response tags

`TaggedCommand(tag: "A1 NOOP\r\nA2 DELETE INBOX\r\nA3", command: .noop)`
was written verbatim, injecting a command; likewise `APPEND` start.
`TaggedResponse(tag: "* BYE x\r\nA1", …)` injected a response.

RFC 3501: `tag = 1*<any ASTRING-CHAR except "+">`. New `Command.Tag`
replaces the `String` in `TaggedCommand`, `TaggedResponse`, `Response`,
`CommandStreamPart`, `AppendCommand`, `BadCommand` and NIOIMAP's state
machine errors; `init?(_:)` validates, literals trap. The parser already
enforces the production. IMAPCommands converts its numeric tags.

* Validate and escape namespace delimiters

`NamespaceDescription(string: "x", char: "\r\n", …)` wrote a raw CRLF
inside `"…"`, injecting a response. `"\""` encoded as `"""`, and `"\\"`
as `"\"` (unterminated); non-ASCII was accepted.

RFC 2342: `DQUOTE QUOTED-CHAR DQUOTE / nil`. `init(string:delimiter:
responseExtensions:)` (was `char:`) throws `InvalidDelimiterError` for
non-ASCII, CR, LF, NUL; the delimiter is stored as a byte, read-only.
Quoted-specials are escaped on write and parsed when escaped.

* Gate a capturing exit test on Swift 6.3
2026-11-04 17:41:52 +00:00
Daniel Eggert f77de8e279 Add ExtensionKey for tagged-extension parameters (#865)
Generic over the extended type, so a STORE key can't be used where a FETCH key is expected.
2026-11-04 17:41:52 +00:00
Daniel Eggert ded4ff7245 Validate atom-shaped types at construction (#864)
* Reject invalid URLAUTH mechanisms

`.resetKey(mailbox: .inbox, mechanisms: [.init("X\r\nA2 DELETE INBOX")])`
was written verbatim, injecting a command into RESETKEY / GENURLAUTH.

RFC 4467: `mechanism = "INTERNAL" / 1*(ALPHA / DIGIT / "-" / ".")`.
`init(_:)` becomes `init?(_:)`; literals trap on invalid input. The
parser already enforces the production.

* Reject invalid mailbox attributes

`MailboxInfo.Attribute("\\X)\r\n* BYE")` was written verbatim, injecting
an untagged response into LIST. It also feeds CREATE … USE via
`UseAttribute(_:)`.

RFC 3501: `mbx-list-flag` is `"\" atom` in every branch. `init(_:)`
becomes `init?(_:)`; literals trap on invalid input. Constants become
`static let` literals; storage is `let`. Fix the `String.init` doc,
which claimed lowercase storage.

* Reject invalid use attributes

`UseAttribute("\\All))\r\nA2 DELETE INBOX\r\nA3 NOOP ((")` was written
verbatim, injecting a command into CREATE … (USE (…)). It also feeds
`GmailLabel(useAttribute:)`.

RFC 6154: `use-attr-ext = "\" atom`. `init(_:)` becomes `init?(_:)`;
literals trap on invalid input. `init(_: MailboxInfo.Attribute)` stays
non-failable: same production. Fix docs that claimed lowercase storage.

* Reject invalid attribute flags

`AttributeFlag("x\" all 1\r\nA2 DELETE INBOX\r\nA3 NOOP \"")` was
written verbatim inside SEARCH MODSEQ "/flags/…", injecting a command.

RFC 7162: `attr-flag = "\\" atom / atom`, where `"\\"` is two literal
backslashes (the stored form is already escaped). `init(_:)` becomes
`init?(_:)`, validating after lowercasing; literals trap on invalid
input. Fix docs that claimed casing is preserved.

* Add FilterName for SEARCH FILTER

`.filter("x\r\nA2 DELETE INBOX")` was written verbatim, injecting a
command into SEARCH.

RFC 5466: `filter-name = 1*<any ATOM-CHAR except "/">`. New `FilterName`
type replaces the `String` payload of `SearchKey.filter`; `init?(_:)`
validates, literals trap on invalid input.

* Reject invalid compression kinds

`.compress(.init("DEFLATE\r\nA2 DELETE INBOX"))` was written verbatim,
injecting a command after COMPRESS.

RFC 4978: `algorithm = "DEFLATE"`, an atom. `init(_:)` becomes
`init?(_:)`, validating after uppercasing; literals trap on invalid
input. Add `String.init(_:)`.

* Reject invalid capabilities

`Capability("X\r\nA2 DELETE INBOX")` was written verbatim, injecting a
command into ENABLE, or (`"X\r\n* OK [ALERT] hi"`) a response into
CAPABILITY / ENABLED. Same for the kinds a capability is built from,
e.g. `.context(.init("X\r\n…"))`.

RFC 3501: `capability = ("AUTH=" auth-type) / atom`. `init(_:)` becomes
`init?(_:)` for `Capability` and each kind (kinds validate after
uppercasing); literals trap on invalid input. Storage is `let`. Add
`String.init(_:)` for the kinds.

* Add validated LIST option tag types

`.standard("X)\r\nA2 DELETE INBOX\r\nA3 LIST (")` was written verbatim,
injecting a command into LIST select/return options. Same for
`.vendor(KeyValue<String, String>)`.

RFC 5258: `option-standard-tag = atom`, `option-vendor-tag =
vendor-token "-" atom`. New `OptionExtensionKind.Standard` and
`.Vendor` replace the payloads; `init?(_:)` validates, literals trap.
`Vendor` stores `ACME-SORT` and derives `token` / `name`.

* Add CharacterSetName for SEARCH, SORT, and BADCHARSET

`.sort(…, charset: "UTF-8 ALL\r\nA2 DELETE INBOX\r\nA3 SEARCH", …)` was
written verbatim, injecting a command into SORT / SEARCH / ESEARCH.
`.badCharset(["a)] x\r\n* BYE"])` injected a response. Quoted names
also didn't round-trip: `"a b"` parsed, then encoded bare.

RFC 3501: `charset = atom / quoted`. New `CharacterSetName` replaces
`String`; valid = non-empty `TEXT-CHAR`. Written as an atom where it is
one (`CHARSET UTF-8` unchanged), quoted otherwise, never a literal. The
parser rejects quoted names it couldn't write back.

* Assert keyword validity when writing a flag keyword

`writeFlagKeyword` wrote verbatim with no check. `writeAtom` would be
wrong: Gmail keywords contain `]`, which no atom does. Assert the
keyword's own production instead; test that a `]` keyword encodes.

* Hoist a #require the compiler flagged as redundant
2026-11-04 17:41:52 +00:00