source/internal/StringScanner.protos

Repository
guillermomolina/protos
Commit
379c6fa63685c39a5954cfbd577bfda3b4df8e75
Tree
8cd4f4afe29ae4c3866381f38c1858108e9799f6
Blob
ea7fe28992a4f67e34eadd7358b1ae3344f03b3e
Source
View exact source on GitHub
// THE LICENSED WORK IS PROVIDED UNDER THE TERMS OF THE ADAPTIVE PUBLIC LICENSE
// ("LICENSE") AS FIRST COMPLETED BY: Guillermo Adrián Molina. ANY USE, PUBLIC
// DISPLAY, PUBLIC PERFORMANCE, REPRODUCTION OR DISTRIBUTION OF, OR PREPARATION OF
// DERIVATIVE WORKS BASED ON, THE LICENSED WORK CONSTITUTES RECIPIENT'S ACCEPTANCE
// OF THIS LICENSE AND ITS TERMS, WHETHER OR NOT SUCH RECIPIENT READS THE TERMS OF
// THE LICENSE. "LICENSED WORK" AND "RECIPIENT" ARE DEFINED IN THE LICENSE. A COPY
// OF THE LICENSE IS LOCATED IN THE TEXT FILE ENTITLED "LICENSE.TXT" ACCOMPANYING
// THE CONTENTS OF THIS FILE. IF A COPY OF THE LICENSE DOES NOT ACCOMPANY THIS
// FILE, A COPY OF THE LICENSE MAY ALSO BE OBTAINED AT THE FOLLOWING WEB SITE:
// https://github.com/guillermomolina/protos
//
// Software distributed under the License is distributed on an "AS IS" basis,
// WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
// the specific language governing rights and limitations under the License.

//! Private String literal recognition.
//!
//! Single-quoted, double-quoted and triple-double-quoted literals use the same
//! standard escapes. A valid literal answers its decoded value and the absolute
//! source scalar interval of every escape. A malformed literal answers its
//! first diagnostic code; it never answers a value and the cursor ends at the
//! end of the malformed region. Values are built incrementally as Bytes.

Utf8: import("./Utf8.protos")
Builder: import("./ArrayBuilder.protos")
Errors: import("./Errors.protos")

simpleEscape: (scalar) => {
    result: -1
    if((scalar == 92) || (scalar == 39) || (scalar == 34)) {
        result = scalar
    }
    if(scalar == 110) {
        result = 10
    }
    if(scalar == 114) {
        result = 13
    }
    if(scalar == 116) {
        result = 9
    }
    if(scalar == 98) {
        result = 8
    }
    if(scalar == 102) {
        result = 12
    }
    result
}

hexValue: (scalar) => {
    result: -1
    if((scalar >= 48) && (scalar <= 57)) {
        result = scalar - 48
    }
    if((scalar >= 65) && (scalar <= 70)) {
        result = scalar - 55
    }
    if((scalar >= 97) && (scalar <= 102)) {
        result = scalar - 87
    }
    result
}

isScalarValue: (value) => {
    (value <= 1114111) && ((value < 55296) || (value > 57343))
}

// Reads the escape at the cursor, which is at `\`. Answers the decoded scalar
// and advances over the escape, or answers -1 for an invalid or incomplete
// escape and advances over the backslash and its following scalar (but never
// over a logical newline).
readEscape: (cursor) => {
    next: cursor.peekAt(1)
    result: simpleEscape(next)
    if(result >= 0) {
        cursor.advanceAscii(2)
    } else {
        if(next == 117) {
            valid: cursor.peekAt(2) == 123
            value: 0
            digits: 0
            distance: 3
            if(valid) {
                digit: hexValue(cursor.peekAt(distance))
                while((digit >= 0) && (digits < 7)) {
                    value = (value * 16) + digit
                    digits = digits + 1
                    distance = distance + 1
                    digit = hexValue(cursor.peekAt(distance))
                }
                valid = (digits >= 1) && (digits <= 6) && (cursor.peekAt(distance) == 125) &&
                    isScalarValue(value)
            }
            if(valid) {
                result = value
                cursor.advanceAscii(distance + 1)
            } else {
                cursor.advanceAscii(2)
            }
        } else {
            cursor.advanceAscii(1)
            if((next >= 0) && (next != 10) && (next != 13)) {
                cursor.advance()
            }
        }
    }
    result
}

escapeSpan: (first, last) => {
    {
        start: first
        end: last
    }
}

outcome: (diagnosticCode, decoded, spans) => {
    {
        code: diagnosticCode
        value: decoded
        escapes: spans
    }
}

// Ordinary single-line literal delimited by `quote` (39 or 34).
scanQuoted: (cursor, quote) => {
    bytes: cursor.bytes()
    cursor.advanceAscii(1)
    buffer: Utf8.emptyBytes()
    spans: Builder.create()
    diagnosticCode: null
    runStart: cursor.byteOffset()
    done: false

    while(!done) {
        current: cursor.peek()
        if((current < 0) || (current == 10) || (current == 13)) {
            if(diagnosticCode === null) {
                if(current < 0) {
                    diagnosticCode = Errors.UNTERMINATED_STRING
                } else {
                    diagnosticCode = Errors.STRING_NEWLINE
                }
            }
            done = true
        } else {
            if(current == quote) {
                if(diagnosticCode === null) {
                    Utf8.appendInterval(buffer, bytes, runStart, cursor.byteOffset())
                }
                cursor.advanceAscii(1)
                done = true
            } else {
                if(current == 92) {
                    if(diagnosticCode === null) {
                        Utf8.appendInterval(buffer, bytes, runStart, cursor.byteOffset())
                    }
                    escapeStart: cursor.scalarOffset()
                    decoded: readEscape(cursor)
                    if(decoded >= 0) {
                        if(diagnosticCode === null) {
                            Utf8.appendScalar(buffer, decoded)
                            spans.add(escapeSpan(escapeStart, cursor.scalarOffset()))
                        }
                    } else {
                        if(diagnosticCode === null) {
                            diagnosticCode = Errors.INVALID_STRING_ESCAPE
                        }
                    }
                    runStart = cursor.byteOffset()
                } else {
                    cursor.advance()
                }
            }
        }
    }

    result: null
    if(diagnosticCode === null) {
        result = outcome(null, Utf8.decodeBuffer(buffer), spans.toArray())
    } else {
        result = outcome(diagnosticCode, null, Array())
    }
    result
}

isIndentation: (octet) => {
    (octet == 32) || (octet == 9)
}

allIndentation: (bytes, first, last) => {
    result: true
    index: first
    while(result && (index < last)) {
        result = isIndentation(bytes[index])
        index = index + 1
    }
    result
}

// Applies the triple-double indentation rules to the raw content bytes
// [first, last). Answers the normalized raw Bytes, or null when a non-blank
// line does not begin with the exact structural prefix.
normalizeIndentation: (bytes, first, last) => {
    lastLineStart: -1
    scan: last - 1
    while((lastLineStart < 0) && (scan >= first)) {
        octet: bytes[scan]
        if((octet == 10) || (octet == 13)) {
            lastLineStart = scan + 1
        }
        scan = scan - 1
    }

    structural: false
    prefixStart: 0
    prefixLength: 0
    contentEnd: last
    if((lastLineStart >= 0) && allIndentation(bytes, lastLineStart, last)) {
        structural = true
        prefixStart = lastLineStart
        prefixLength = last - lastLineStart
        newlineStart: lastLineStart - 1
        if((bytes[newlineStart] == 10) && (newlineStart > first) && (bytes[newlineStart - 1] == 13)) {
            newlineStart = newlineStart - 1
        }
        contentEnd = newlineStart
    }

    contentStart: first
    if(contentStart < contentEnd) {
        if(bytes[contentStart] == 10) {
            contentStart = contentStart + 1
        } else {
            if(bytes[contentStart] == 13) {
                contentStart = contentStart + 1
                if((contentStart < contentEnd) && (bytes[contentStart] == 10)) {
                    contentStart = contentStart + 1
                }
            }
        }
    }

    output: Utf8.emptyBytes()
    if(!structural) {
        Utf8.appendInterval(output, bytes, contentStart, contentEnd)
    } else {
        lineStart: contentStart
        going: true
        while(going) {
            lineEnd: lineStart
            while((lineEnd < contentEnd) && (bytes[lineEnd] != 10) && (bytes[lineEnd] != 13)) {
                lineEnd = lineEnd + 1
            }
            if(!allIndentation(bytes, lineStart, lineEnd)) {
                matches: (lineEnd - lineStart) >= prefixLength
                offset: 0
                while(matches && (offset < prefixLength)) {
                    matches = bytes[lineStart + offset] == bytes[prefixStart + offset]
                    offset = offset + 1
                }
                if(matches) {
                    Utf8.appendInterval(output, bytes, lineStart + prefixLength, lineEnd)
                } else {
                    output = null
                    going = false
                }
            }
            if(going) {
                if(lineEnd >= contentEnd) {
                    going = false
                } else {
                    newlineLength: 1
                    if((bytes[lineEnd] == 13) && ((lineEnd + 1) < contentEnd) && (bytes[lineEnd + 1] == 10)) {
                        newlineLength = 2
                    }
                    Utf8.appendInterval(output, bytes, lineEnd, lineEnd + newlineLength)
                    lineStart = lineEnd + newlineLength
                }
            }
        }
    }
    output
}

// Decodes the already validated escapes of normalized raw content. Escape
// introducers and their spellings are ASCII, so a byte walk is exact.
decodeEscapes: (raw) => {
    output: Utf8.emptyBytes()
    count: raw.size()
    index: 0
    while(index < count) {
        octet: raw[index]
        if(octet == 92) {
            next: raw[index + 1]
            simple: simpleEscape(next)
            if(simple >= 0) {
                output.add(simple)
                index = index + 2
            } else {
                value: 0
                index = index + 3
                while(raw[index] != 125) {
                    value = (value * 16) + hexValue(raw[index])
                    index = index + 1
                }
                Utf8.appendScalar(output, value)
                index = index + 1
            }
        } else {
            output.add(octet)
            index = index + 1
        }
    }
    Utf8.decodeBuffer(output)
}

// Triple-double-quoted multiline literal; the cursor is at its `"""`.
scanTriple: (cursor) => {
    bytes: cursor.bytes()
    cursor.advanceAscii(3)
    contentStart: cursor.byteOffset()
    contentEnd: -1
    spans: Builder.create()
    diagnosticCode: null
    done: false

    while(!done) {
        current: cursor.peek()
        if(current < 0) {
            if(diagnosticCode === null) {
                diagnosticCode = Errors.UNTERMINATED_STRING
            }
            done = true
        } else {
            if((current == 34) && (cursor.peekAt(1) == 34) && (cursor.peekAt(2) == 34)) {
                contentEnd = cursor.byteOffset()
                cursor.advanceAscii(3)
                done = true
            } else {
                if(current == 92) {
                    escapeStart: cursor.scalarOffset()
                    decoded: readEscape(cursor)
                    if(decoded >= 0) {
                        if(diagnosticCode === null) {
                            spans.add(escapeSpan(escapeStart, cursor.scalarOffset()))
                        }
                    } else {
                        if(diagnosticCode === null) {
                            diagnosticCode = Errors.INVALID_STRING_ESCAPE
                        }
                    }
                } else {
                    cursor.advance()
                }
            }
        }
    }

    result: null
    if(diagnosticCode === null) {
        normalized: normalizeIndentation(bytes, contentStart, contentEnd)
        if(normalized === null) {
            result = outcome(Errors.INVALID_TRIPLE_INDENTATION, null, Array())
        } else {
            result = outcome(null, decodeEscapes(normalized), spans.toArray())
        }
    } else {
        result = outcome(diagnosticCode, null, Array())
    }
    result
}