source/internal/Scanner.protos

Repository
guillermomolina/protos
Commit
2723a55555e7beecee0816bf99d16e3c8c1ae635
Tree
c36054e4e5abd7fc29a039b4e096cac2e8706492
Blob
c7eb289f90c5971b2ddd7bde6c9bf104a82b40bc
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 shared lexical recognition core.
//!
//! One recognition pass partitions the complete source into pieces. Every
//! recognition step produces either one valid piece or one malformed region
//! with its diagnostic. Strict operation signals the first LexicalError;
//! recovery records an ERROR piece and its diagnostic and continues. Both
//! modes use the same recognition rules and the same region boundaries.

Cursor: import("./Cursor.protos")
Unicode: import("./Unicode.protos")
Kinds: import("./TokenKinds.protos")
Numbers: import("./NumberScanner.protos")
Strings: import("./StringScanner.protos")
Errors: import("./Errors.protos")
Builder: import("./ArrayBuilder.protos")
Utf8: import("./Utf8.protos")

horizontalWhitespace: Kinds.horizontalWhitespaceTable
operatorCharacters: Kinds.operatorCharacterTable
identifierContinue: Unicode.asciiIdentifierContinue

newPiece: (pieceKind, first, last, raw, spelling, spans) => {
    {
        kind: pieceKind
        start: first
        end: last
        rawText: raw
        lexeme: spelling
        escapeSpans: spans
    }
}

newDiagnostic: (diagnosticCode, first, last) => {
    {
        code: diagnosticCode
        start: first
        end: last
    }
}

// Recognizes the complete `source`. Recognition decides each region first;
// output for it is materialized only after its capacity check.
// `maxPieces` already passed its domain
// check; at most `maxPieces - 1` non-EOF pieces are admitted so that EOF
// always fits.
scan: (source, recover, maxPieces) => {
    cursor: Cursor.create(source)
    bytes: cursor.bytes()
    byteLimit: cursor.byteSize()
    pieces: Builder.create()
    diagnostics: Builder.create()

    // Capacity is checked before any output is materialized, so a refused
    // piece never copies source text or allocates its record.
    reserve: () => {
        ((pieces.size() + 1) < maxPieces).ifFalse(() => {
            Errors.signalLimit("maxPieces", maxPieces)
        })
        null
    }

    // Emits a valid piece whose raw text and lexeme are the same spelling.
    emitSpelled: (pieceKind, startByte, startScalar) => {
        reserve()
        spelling: cursor.text(startByte, cursor.byteOffset())
        pieces.add(newPiece(pieceKind, startScalar, cursor.scalarOffset(), spelling, spelling, Array()))
        null
    }

    // Emits a valid piece whose spelling was already materialized.
    emitKnown: (pieceKind, startScalar, spelling) => {
        reserve()
        pieces.add(newPiece(pieceKind, startScalar, cursor.scalarOffset(), spelling, spelling, Array()))
        null
    }

    // Emits trivia, whose lexeme is null.
    emitTrivia: (pieceKind, startByte, startScalar) => {
        reserve()
        raw: cursor.text(startByte, cursor.byteOffset())
        pieces.add(newPiece(pieceKind, startScalar, cursor.scalarOffset(), raw, null, Array()))
        null
    }

    // Handles one malformed region ending at the cursor. Strict operation
    // signals the lexical failure before any capacity check; recovery checks
    // capacity before materializing the ERROR piece and its diagnostic.
    // `known` is the already materialized region text, or null.
    malformed: (diagnosticCode, startByte, startScalar, known) => {
        endScalar: cursor.scalarOffset()
        recover.ifFalse(() => {
            Errors.signalLexical(diagnosticCode, startScalar, endScalar)
        })
        reserve()
        raw: known
        if(raw === null) {
            raw = cursor.text(startByte, cursor.byteOffset())
        }
        pieces.add(newPiece(Kinds.ERROR, startScalar, endScalar, raw, null, Array()))
        diagnostics.add(newDiagnostic(diagnosticCode, startScalar, endScalar))
        null
    }

    recognizeIdentifier: (startByte, startScalar) => {
        ascii: cursor.peek() < 128
        cursor.advance()
        running: true
        while(running) {
            cursor.skipAscii(identifierContinue)
            running = false
            next: cursor.peek()
            if((next >= 128) && Unicode.isIdentifierContinue(next)) {
                ascii = false
                cursor.advance()
                running = true
            }
        }
        endByte: cursor.byteOffset()
        normalized: true
        if(!ascii) {
            scalars: Builder.create()
            index: startByte
            while(index < endByte) {
                scalars.add(Utf8.scalarAt(bytes, index))
                index = index + Utf8.width(bytes[index])
            }
            normalized = Unicode.isNfc(scalars.toArray())
        }
        if(normalized) {
            reserve()
            spelling: cursor.text(startByte, endByte)
            pieceKind: Kinds.IDENTIFIER
            if(Kinds.reservedWords.containsKey(spelling)) {
                pieceKind = Kinds.reservedWords[spelling]
            }
            pieces.add(newPiece(pieceKind, startScalar, cursor.scalarOffset(), spelling, spelling, Array()))
        } else {
            malformed(Errors.NON_NFC_IDENTIFIER, startByte, startScalar, null)
        }
        null
    }

    recognizeString: (startByte, startScalar, triple) => {
        found: null
        if(triple) {
            found = Strings.scanTriple(cursor)
        } else {
            found = Strings.scanQuoted(cursor, cursor.peek())
        }
        if(found.code === null) {
            reserve()
            raw: cursor.text(startByte, cursor.byteOffset())
            pieces.add(newPiece(Kinds.STRING, startScalar, cursor.scalarOffset(), raw, found.value, found.escapes))
        } else {
            malformed(found.code, startByte, startScalar, null)
        }
        null
    }

    recognizeSymbolic: (startByte, startScalar) => {
        cursor.skipAscii(operatorCharacters)
        spelling: cursor.text(startByte, cursor.byteOffset())
        if(Kinds.symbolicTokens.containsKey(spelling)) {
            emitKnown(Kinds.symbolicTokens[spelling], startScalar, spelling)
        } else {
            malformed(Errors.INVALID_SYMBOLIC_OPERATOR, startByte, startScalar, spelling)
        }
        null
    }

    recognizeBlockComment: (startByte, startScalar) => {
        cursor.advanceAscii(2)
        if(cursor.skipBlockComment()) {
            emitTrivia(Kinds.BLOCK_COMMENT, startByte, startScalar)
        } else {
            malformed(Errors.UNTERMINATED_BLOCK_COMMENT, startByte, startScalar, null)
        }
        null
    }

    while(!cursor.atEnd()) {
        startByte: cursor.byteOffset()
        startScalar: cursor.scalarOffset()
        current: cursor.peek()

        if((current < 128) && horizontalWhitespace[current]) {
            cursor.skipAscii(horizontalWhitespace)
            emitTrivia(Kinds.HORIZONTAL_WHITESPACE, startByte, startScalar)
        } else {
            if((current == 10) || (current == 13)) {
                cursor.advanceAscii(cursor.newlineLength())
                reserve()
                raw: cursor.text(startByte, cursor.byteOffset())
                pieces.add(newPiece(Kinds.NEWLINE, startScalar, cursor.scalarOffset(), raw, "\n", Array()))
            } else {
                // Raw lookahead is compared only with ASCII and only after
                // an inspected ASCII delimiter. No continuation byte can match.
                next: -1
                if(((current == 47) || (current == 34) || (current == 46)) &&
                        ((startByte + 1) < byteLimit)) {
                    next = bytes[startByte + 1]
                }
                if((current == 47) && (next == 47)) {
                    cursor.skipLine()
                    emitTrivia(Kinds.LINE_COMMENT, startByte, startScalar)
                } else {
                    if((current == 47) && (next == 42)) {
                        recognizeBlockComment(startByte, startScalar)
                    } else {
                        if(Unicode.isIdentifierStart(current)) {
                            recognizeIdentifier(startByte, startScalar)
                        } else {
                            if((current >= 48) && (current <= 57)) {
                                diagnosticCode: Numbers.scan(cursor)
                                if(diagnosticCode === null) {
                                    emitSpelled(Kinds.NUMBER, startByte, startScalar)
                                } else {
                                    malformed(diagnosticCode, startByte, startScalar, null)
                                }
                            } else {
                                if(current == 39) {
                                    recognizeString(startByte, startScalar, false)
                                } else {
                                    if(current == 34) {
                                        recognizeString(startByte, startScalar,
                                            (next == 34) && ((startByte + 2) < byteLimit) &&
                                                (bytes[startByte + 2] == 34))
                                    } else {
                                        if((current == 46) && (next == 46) && ((startByte + 2) < byteLimit) &&
                                                (bytes[startByte + 2] == 46)) {
                                            cursor.advanceAscii(3)
                                            emitKnown(Kinds.ELLIPSIS, startScalar, Kinds.ELLIPSIS_SPELLING)
                                        } else {
                                            if((current < 128) && Kinds.structuralPunctuation.containsKey(current)) {
                                                punctuation: Kinds.structuralPunctuation[current]
                                                cursor.advanceAscii(1)
                                                emitKnown(punctuation.kind, startScalar, punctuation.spelling)
                                            } else {
                                                if((current < 128) && operatorCharacters[current]) {
                                                    recognizeSymbolic(startByte, startScalar)
                                                } else {
                                                    cursor.advance()
                                                    malformed(Errors.UNEXPECTED_SCALAR, startByte, startScalar, null)
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        // Every iteration before EOF consumes at least one scalar.
        (cursor.byteOffset() > startByte).ifFalse(() => {
            Error().signal()
        })
    }

    sourceEnd: cursor.scalarOffset()
    pieces.add(newPiece(Kinds.EOF, sourceEnd, sourceEnd, "", "", Array()))
    pieceArray: pieces.toArray()
    diagnosticArray: diagnostics.toArray()
    {
        pieces: pieceArray
        diagnostics: diagnosticArray
    }
}