Files
swift-nio-imap/Sources
Daniel Eggert 87a0457656 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 18:10:38 +09:00
..