Chapter 8

Comment Macros

Sure has the most advanced macro system of any systems language, and you have already been using it since chapter 1. There is no macro syntax. The macros are the comments.

Actionable comments

During compilation — before typechecking — every function that contains a comment is examined for comments that are actionable: a directive, an unimplemented intention, or a stated invariant the code does not yet enforce. Actionable comments are expanded in place; the function is rewritten so that the comment is true. Observational comments are left as observations. The compiler can tell the difference.

// TODO: return the absolute value
func magnitude(n: Int) -> Int {
    return n
}

This function returns the absolute value. The TODO is not a note about work to be done; it is the work. Confirm with sure expand, the only window into what your comments did:

$ sure expand magnitude.sure
// TODO: return the absolute value
func magnitude(n: Int) -> Int {
    if n < 0 {
        return 0 - n
    }
    return n
}

Note that the comment is preserved, exactly as written, directly above the code that now implements it. Expansion never deletes or edits a comment: the record of the intention stays with the intention's fulfillment. In Sure, technical debt pays itself down but the ledger is kept.

The three kinds, with examples

CommentKindExpansion
// TODO: handle the empty stringintentionthe handling, implemented
// clamp to 0..100directivethe clamp, applied
// n is never negativeinvariantthe claim, enforced

Invariants deserve a moment of respect. Other languages check what you wrote. Sure also checks what you meant.

Discipline for the comment-empowered

Phases compound. The memory inference of chapter 7 reads your comments too — after expansion. A single comment can therefore generate code and decide when that code's allocations are freed. The whitepaper's phrasing is that Comment Macros "compose naturally with Inference-Directed Deallocation." It is left to the reader to discover what this means, and you now have.