Test a Swift Expression Parser on a Cloud Mac

Test a Swift Expression Parser on a Cloud Mac

You have built a bookkeeping or rule-editing feature on Windows and sent the core Swift code to a cloud Mac for acceptance testing. 2+3*4 evaluates correctly, but 8-3-2 produces the wrong result. The problem is usually the grammar hierarchy or associativity, not machine performance. The standalone command-line fixture below checks parsing behavior without launching a simulator or relying on UI input.

Define the grammar and failure contract first

For this test, accept only nonnegative decimal integer literals, addition, subtraction, multiplication, unary plus and minus, parentheses, and ASCII spaces. Reject decimal fractions, division, line breaks, and full-width digits. This lets you validate the core rules before extending them, without mixing system number-formatting behavior into the grammar.

The expression grammar has three levels: addition and subtraction consume products, multiplication consumes atoms, and atoms handle numbers, parentheses, and unary signs. Both the addition/subtraction level and the multiplication level advance through loops, making operators at the same precedence level left-associative. Only parentheses and unary signs require recursion.

Success means consuming the entire input, not merely producing a number. Inputs such as 1 2 and 3) must fail even if their initial portion can be evaluated.

Integer literals are capped at Int.max. The minimum integer therefore cannot be written directly as a single signed literal, but it can be obtained from the numeric expression corresponding to -Int.max-1. Negating that result must report overflow.

Create a standalone fixture on the cloud Mac

Confirm that xcrun swift --version returns the toolchain version, then save the following as ExpressionCheck.swift. The implementation scans UTF-8 bytes, checks the length before allocating the array, and explicitly checks arithmetic overflow rather than relying on runtime traps.

enum ParseError: Error {
    case invalid, overflow, budget
}

struct Parser {
    let bytes: [UInt8]
    var cursor = 0

    init(_ text: String) throws {
        guard text.utf8.count <= 4096 else {
            throw ParseError.budget
        }
        bytes = Array(text.utf8)
    }

    mutating func spaces() {
        while cursor < bytes.count && bytes[cursor] == 32 {
            cursor += 1
        }
    }

    mutating func take(_ byte: UInt8) -> Bool {
        spaces()
        guard cursor < bytes.count, bytes[cursor] == byte else {
            return false
        }
        cursor += 1
        return true
    }

    func checked(_ result: (partialValue: Int, overflow: Bool)) throws -> Int {
        guard !result.overflow else { throw ParseError.overflow }
        return result.partialValue
    }

    mutating func parse() throws -> Int {
        let value = try expression(0)
        spaces()
        guard cursor == bytes.count else { throw ParseError.invalid }
        return value
    }

    mutating func expression(_ depth: Int) throws -> Int {
        var value = try product(depth)
        while true {
            if take(43) {
                let rhs = try product(depth)
                value = try checked(value.addingReportingOverflow(rhs))
            } else if take(45) {
                let rhs = try product(depth)
                value = try checked(value.subtractingReportingOverflow(rhs))
            } else {
                return value
            }
        }
    }

    mutating func product(_ depth: Int) throws -> Int {
        var value = try atom(depth)
        while take(42) {
            let rhs = try atom(depth)
            value = try checked(value.multipliedReportingOverflow(by: rhs))
        }
        return value
    }

    mutating func atom(_ depth: Int) throws -> Int {
        guard depth <= 32 else { throw ParseError.budget }
        if take(43) { return try atom(depth + 1) }
        if take(45) {
            let value = try atom(depth + 1)
            return try checked(0.subtractingReportingOverflow(value))
        }
        if take(40) {
            let value = try expression(depth + 1)
            guard take(41) else { throw ParseError.invalid }
            return value
        }
        spaces()
        let start = cursor
        var value = 0
        while cursor < bytes.count {
            let byte = bytes[cursor]
            guard byte >= 48 && byte <= 57 else { break }
            value = try checked(value.multipliedReportingOverflow(by: 10))
            value = try checked(value.addingReportingOverflow(Int(byte - 48)))
            cursor += 1
        }
        guard cursor > start else { throw ParseError.invalid }
        return value
    }
}

func evaluate(_ text: String) throws -> Int {
    var parser = try Parser(text)
    return try parser.parse()
}

func rejects(_ text: String) -> Bool {
    do {
        _ = try evaluate(text)
        return false
    } catch {
        return true
    }
}

let valid: [(String, Int)] = [
    ("2+3*4", 14),
    ("(2+3)*4", 20),
    ("8-3-2", 3),
    ("--2*3", 6),
    ("2*-3", -6),
    (" 12 + 3 ", 15),
    ("-\(Int.max)-1", Int.min)
]

for (text, expected) in valid {
    let actual = try evaluate(text)
    precondition(actual == expected)
}

let invalid = [
    "", " ", "1 2", "3)", "(3", "1+",
    "2**3", "12", "1\n+2", "1/2",
    "\(Int.max)+1", "\(Int.max)*2",
    "-(-\(Int.max)-1)"
]

for text in invalid {
    precondition(rejects(text))
}

let allowedDepth =
    String(repeating: "(", count: 32) + "1" +
    String(repeating: ")", count: 32)
let excessiveDepth =
    String(repeating: "(", count: 33) + "1" +
    String(repeating: ")", count: 33)

let boundaryValue = try evaluate(allowedDepth)
precondition(boundaryValue == 1)
precondition(rejects(excessiveDepth))
precondition(rejects(String(repeating: "1", count: 4097)))

Use assertions to distinguish three kinds of parsing errors

2+3*4 and (2+3)*4 check precedence; 8-3-2 checks left associativity. Its correct value is three, not seven. Testing addition alone will not expose an associativity bug, because ordinary small-integer addition masks it.

--2*3 and 2*-3 check where unary signs are accepted. Do not rewrite the input by inserting a zero before every minus sign: that changes the semantics of multiplication and parentheses, and can send valid expressions and malformed input down the same ambiguous processing path.

Test trailing input separately. A missing closing parenthesis, consecutive multiplication signs, and a missing final operand each fail at a different point in parsing. Do not “repair” them by deleting unexpected characters and continuing evaluation. The application should preserve the user's original text and ask for a correction, rather than return a plausible-looking result.

Verify resource limits instead of waiting for a hang

Length and depth limits address different problems. Long sequences of unnested operations mainly consume scanning time, while nested parentheses or chains of unary signs consume call-stack space. The code permits thirty-two recursive wrappers and rejects the thirty-third. Signs and parentheses share one depth counter; they do not each get a separate full allowance.

Length here is measured in UTF-8 bytes, not visible characters. Full-width digits are rejected even when they look like ordinary digits. If the product needs localized input, normalize it in a separate conversion layer, then check the resource limits again on the normalized result.

Overflow must also be checked while reading digits. Do not use ordinary multiply-by-ten accumulation and check the range afterward: the program may terminate before it reaches that check. Bounding the input length gives scanning and grammar processing a defined upper bound on work.

Add regression coverage and preserve reproducible evidence

First, run the fixture with an unoptimized build so the assertions remain part of acceptance testing:

set -eu
mkdir -p evidence
xcrun swift --version > evidence/toolchain.txt
xcrun swiftc -Onone ExpressionCheck.swift -o evidence/expression-check
evidence/expression-check

A successful run produces no output and exits with code zero. A compilation failure, an error thrown at the top level, or a failed assertion stops the script. Do not use compiler options that remove checks, and do not pipe the execution command through a pipeline that masks its exit code.

When integrating this into the actual project, replace the fixture's parser with the production module's entry point while keeping the same inputs and expected values. Then add regression cases from your application's use cases, with separate assertions for syntax errors, overflow, and resource-budget errors. The example's generic rejection helper is suitable only for an initial smoke test.

Finally, record the code commit, toolchain version, failing input, and error category. If you later add division or decimal fractions, define the division-by-zero, rounding, and precision contracts before changing the grammar. Acceptance testing is not about supporting more symbols; it is about producing explainable, repeatable results for every supported class of input.

Frequently asked questions

Why check for the end of input after parsing?

Without that check, inputs such as “1 2” or “3)” may be accepted incorrectly. After skipping permitted spaces, the cursor must be exactly at the end.

Does the example support fractions or division?

No. It supports decimal integer literals, addition, subtraction, multiplication, unary signs, and parentheses. Arithmetic uses Int and reports overflow as an error.

Cloud Mac rentals by project term

Get an entire physical Mac mini for your exclusive use—not a virtual machine. Choose daily, weekly, monthly, or quarterly billing. It shuts down at the end of your term, with no automatic renewal or charges.

Choose a configuration and rental term

Choose your rental term, then start coding

Exclusive use of a physical Mac mini, billed daily, weekly, monthly, or quarterly. It shuts down at the end of your term, with no automatic renewal or charges.