Zig 0.17.0-dev (Split by item)

This is an example of documentation generated by ZigDoc, an alternative to Zig's built-in Auto Doc feature. See also examples in other modes/formats. The project being documented here (as the example) is the Zig library itself.

LineHandler

lex.LineHandler
pub const LineHandler = struct

File

Code

pub const LineHandler = struct {
    line_number: usize = 1,
    buffer: []const u8,
    last_line_ending_index: ?usize = null,

    /// Like incrementLineNumber but checks that the current char is a line ending first.
    /// Returns the new line number if it was incremented, null otherwise.
    pub fn maybeIncrementLineNumber(self: *LineHandler, cur_index: usize) ?usize {
        const c = self.buffer[cur_index];
        if (c == '\r' or c == '\n') {
            return self.incrementLineNumber(cur_index);
        }
        return null;
    }

    /// Increments line_number appropriately (handling line ending pairs)
    /// and returns the new line number if it was incremented, or null otherwise.
    pub fn incrementLineNumber(self: *LineHandler, cur_index: usize) ?usize {
        if (self.currentIndexFormsLineEndingPair(cur_index)) {
            self.last_line_ending_index = null;
            return null;
        } else {
            self.line_number += 1;
            self.last_line_ending_index = cur_index;
            return self.line_number;
        }
    }

    /// \r\n and \n\r pairs are treated as a single line ending (but not \r\r \n\n)
    /// expects self.index and last_line_ending_index (if non-null) to contain line endings
    ///
    /// TODO: This is not really how the Win32 RC compiler handles line endings. Instead, it
    ///       seems to drop all carriage returns during preprocessing and then replace all
    ///       remaining line endings with well-formed CRLF pairs (e.g. `<CR>a<CR>b<LF>c` becomes `ab<CR><LF>c`).
    ///       Handling this the same as the Win32 RC compiler would need control over the preprocessor,
    ///       since Clang converts unpaired <CR> into unpaired <LF>.
    pub fn currentIndexFormsLineEndingPair(self: *const LineHandler, cur_index: usize) bool {
        if (self.last_line_ending_index == null) return false;

        // must immediately precede the current index, we know cur_index must
        // be >= 1 since last_line_ending_index is non-null (so if the subtraction
        // overflows it is a bug at the callsite of this function).
        if (self.last_line_ending_index.? != cur_index - 1) return false;

        const cur_line_ending = self.buffer[cur_index];
        const last_line_ending = self.buffer[self.last_line_ending_index.?];

        // sanity check
        std.debug.assert(cur_line_ending == '\r' or cur_line_ending == '\n');
        std.debug.assert(last_line_ending == '\r' or last_line_ending == '\n');

        // can't be \n\n or \r\r
        if (last_line_ending == cur_line_ending) return false;

        return true;
    }
}