source/internal/ParserNodes.protos

Repository
guillermomolina/protos
Commit
2723a55555e7beecee0816bf99d16e3c8c1ae635
Tree
c36054e4e5abd7fc29a039b4e096cac2e8706492
Blob
4ebaf103e4ca94b8e363b1a5072c6fe517b51d23
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 construction of Surface AST records with structural budgets.
//!
//! Every labeled record is a fresh ordinary object with own `kind`, `start`
//! and `end` slots plus its variant slots; optional slots are always present
//! and hold null when absent. Spans are fresh `{ start, end }` objects.
//!
//! The parser decides every shape before building it, so each constructed
//! record belongs to the final tree. The record budget counts constructions
//! (the Program root is reserved up front) and fails as soon as one more
//! record would exceed `maxRecords`. Admission also reserves the minimum
//! capacity of committed enclosing records before nested work is scheduled.
//! Each record's subtree height is kept in a private identity table when it is
//! built, so no completed subtree is ever
//! walked again. `nesting` counts the records known to enclose the position
//! being parsed; it is a lower bound of the final depth, checked whenever the
//! parser descends, before scheduling the nested grammar continuation.

ParserErrors: import("./ParserErrors.protos")

// Literal record kinds are invariant across parser invocations.
literalKinds: Map()
literalKinds["NUMBER"] = "NUMBER"
literalKinds["STRING"] = "STRING"
literalKinds["TRUE"] = "TRUE"
literalKinds["FALSE"] = "FALSE"
literalKinds["NULL"] = "NULL"
literalKinds.freeze()

create: (maxRecords, maxDepth) => {
    heights: IdentityMap()
    records: 1
    nesting: 0

    larger: (first, second) => {
        if(first > second) {
            first
        } else {
            second
        }
    }

    heightOf: (value) => {
        result: 0
        (value === null).ifFalse(() => {
            result = heights[value]
        })
        result
    }

    tallest: (values) => {
        result: 0
        for(value in values) {
            result = larger(result, heights[value])
        }
        result
    }

    // `records` already includes Program and all completed records, including
    // receivers/left operands later extended by postfix/binary productions.
    // `nesting` includes Program when nonzero, plus pending enclosing records.
    // Reserve those pending records and one next child, without recounting any
    // completed subtree or reserving Program twice. At nesting zero only the
    // next record is additional to the reserved Program.
    admitRecord: () => {
        minimum: records + nesting
        if(nesting == 0) {
            minimum = records + 1
        }
        (minimum <= maxRecords).ifFalse(() => {
            ParserErrors.signalLimit("maxRecords", maxRecords)
        })
        null
    }

    // Admit and count before constructing one complete labeled record.
    // Program is reserved separately and must not be admitted a second time.
    admit: () => {
        admitRecord()
        records = records + 1
        null
    }

    // Registers the height of a completed record and checks its depth.
    seal: (node, childHeight) => {
        height: childHeight + 1
        ((nesting + height) <= maxDepth).ifFalse(() => {
            ParserErrors.signalLimit("maxDepth", maxDepth)
        })
        heights[node] = height
        node
    }

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

    covering: (token) => {
        between(token.start, token.end)
    }

    factory: {
        // Enters `levels` enclosing records before a nested record is parsed.
        descend: (levels) => {
            nesting = nesting + levels
            admitRecord()
            ((nesting + 1) <= maxDepth).ifFalse(() => {
                ParserErrors.signalLimit("maxDepth", maxDepth)
            })
            null
        }
        ascend: (levels) => {
            nesting = nesting - levels
            null
        }
        span: (first, last) => {
            between(first, last)
        }

        program: (sourceSize, items) => {
            node: {
                kind: "Program"
                start: 0
                end: sourceSize
                expressions: items
            }
            seal(node, tallest(items))
        }
        literal: (token) => {
            admit()
            literalKind: literalKinds[token.kind]
            literalValue: token.lexeme
            if(literalKind == "TRUE") {
                literalValue = true
            }
            if(literalKind == "FALSE") {
                literalValue = false
            }
            if(literalKind == "NULL") {
                literalValue = null
            }
            node: {
                kind: "Literal"
                start: token.start
                end: token.end
                literalKind: literalKind
                value: literalValue
            }
            seal(node, 0)
        }
        name: (token) => {
            admit()
            node: {
                kind: "Name"
                start: token.start
                end: token.end
                name: token.lexeme
            }
            seal(node, 0)
        }
        intrinsic: (token) => {
            admit()
            node: {
                kind: "Intrinsic"
                start: token.start
                end: token.end
                name: token.lexeme
            }
            seal(node, 0)
        }
        group: (open, close, inner) => {
            admit()
            node: {
                kind: "Group"
                start: open.start
                end: close.end
                expression: inner
            }
            seal(node, heightOf(inner))
        }
        member: (target, nameToken) => {
            admit()
            node: {
                kind: "Member"
                start: target.start
                end: nameToken.end
                receiver: target
                name: nameToken.lexeme
                nameSpan: covering(nameToken)
            }
            seal(node, heightOf(target))
        }
        callExpression: (target, items, open, close, trailing) => {
            last: close.end
            (trailing === null).ifFalse(() => {
                last = trailing.end
            })
            admit()
            node: {
                kind: "Call"
                start: target.start
                end: last
                receiver: target
                arguments: items
                argumentSpan: between(open.start, close.end)
                trailingBody: trailing
            }
            seal(node, larger(larger(heightOf(target), tallest(items)), heightOf(trailing)))
        }
        superSend: (keyword, nameToken, items, open, close) => {
            admit()
            node: {
                kind: "SuperSend"
                start: keyword.start
                end: close.end
                name: nameToken.lexeme
                nameSpan: covering(nameToken)
                arguments: items
                argumentSpan: between(open.start, close.end)
            }
            seal(node, tallest(items))
        }
        index: (target, selector, open, close) => {
            admit()
            node: {
                kind: "Index"
                start: target.start
                end: close.end
                receiver: target
                index: selector
                bracketSpan: between(open.start, close.end)
            }
            seal(node, larger(heightOf(target), heightOf(selector)))
        }
        arrayConstruction: (open, close, items) => {
            admit()
            node: {
                kind: "ArrayConstruction"
                start: open.start
                end: close.end
                arguments: items
            }
            seal(node, tallest(items))
        }
        mapConstruction: (percent, entryTable) => {
            admit()
            node: {
                kind: "MapConstruction"
                start: percent.start
                end: entryTable.end
                table: entryTable
            }
            seal(node, heightOf(entryTable))
        }
        object: (first, parent, items, open, close) => {
            admit()
            node: {
                kind: "Object"
                start: first
                end: close.end
                parentExpression: parent
                items: items
                bodySpan: between(open.start, close.end)
            }
            seal(node, larger(heightOf(parent), tallest(items)))
        }
        closure: (parameterItems, form, parameterFirst, parameterLast, arrow, closureBody) => {
            admit()
            node: {
                kind: "Closure"
                start: parameterFirst
                end: closureBody.end
                parameters: parameterItems
                parameterForm: form
                parameterSpan: between(parameterFirst, parameterLast)
                arrowSpan: covering(arrow)
                body: closureBody
            }
            seal(node, larger(tallest(parameterItems), heightOf(closureBody)))
        }
        unary: (operatorToken, operand) => {
            admit()
            node: {
                kind: "Unary"
                start: operatorToken.start
                end: operand.end
                operator: operatorToken.lexeme
                operatorSpan: covering(operatorToken)
                operand: operand
            }
            seal(node, heightOf(operand))
        }
        binary: (operatorToken, left, right) => {
            admit()
            node: {
                kind: "Binary"
                start: left.start
                end: right.end
                operator: operatorToken.lexeme
                operatorSpan: covering(operatorToken)
                left: left
                right: right
            }
            seal(node, larger(heightOf(left), heightOf(right)))
        }
        slotCreation: (target, operatorToken, assigned) => {
            admit()
            node: {
                kind: "SlotCreation"
                start: target.start
                end: assigned.end
                target: target
                operatorSpan: covering(operatorToken)
                value: assigned
            }
            seal(node, larger(heightOf(target), heightOf(assigned)))
        }
        assignment: (target, operatorToken, assigned) => {
            admit()
            node: {
                kind: "Assignment"
                start: target.start
                end: assigned.end
                target: target
                operatorSpan: covering(operatorToken)
                value: assigned
            }
            seal(node, larger(heightOf(target), heightOf(assigned)))
        }
        multipleSlotCreation: (targetItems, open, close, operatorToken, assigned) => {
            admit()
            node: {
                kind: "MultipleSlotCreation"
                start: open.start
                end: assigned.end
                targets: targetItems
                targetSpan: between(open.start, close.end)
                operatorSpan: covering(operatorToken)
                value: assigned
            }
            seal(node, larger(tallest(targetItems), heightOf(assigned)))
        }
        nonLocalReturn: (keyword, operand) => {
            admit()
            node: {
                kind: "NonLocalReturn"
                start: keyword.start
                end: operand.end
                spelling: keyword.lexeme
                keywordSpan: covering(keyword)
                expression: operand
            }
            seal(node, heightOf(operand))
        }
        contextualIf: (keyword, open, close, test, trueBranch, elseToken, falseBranch) => {
            last: trueBranch.end
            elseRegion: null
            (elseToken === null).ifFalse(() => {
                last = falseBranch.end
                elseRegion = covering(elseToken)
            })
            admit()
            node: {
                kind: "ContextualIf"
                start: keyword.start
                end: last
                condition: test
                headerSpan: between(open.start, close.end)
                trueBody: trueBranch
                elseSpan: elseRegion
                falseBody: falseBranch
            }
            seal(node, larger(larger(heightOf(test), heightOf(trueBranch)), heightOf(falseBranch)))
        }
        contextualWhile: (keyword, open, close, test, loopBody) => {
            admit()
            node: {
                kind: "ContextualWhile"
                start: keyword.start
                end: loopBody.end
                condition: test
                headerSpan: between(open.start, close.end)
                body: loopBody
            }
            seal(node, larger(heightOf(test), heightOf(loopBody)))
        }
        contextualUntil: (loopBody, keyword, open, close, test) => {
            admit()
            node: {
                kind: "ContextualUntil"
                start: loopBody.start
                end: close.end
                body: loopBody
                keywordSpan: covering(keyword)
                condition: test
                headerSpan: between(open.start, close.end)
            }
            seal(node, larger(heightOf(loopBody), heightOf(test)))
        }
        contextualFor: (keyword, form, binderToken, open, close, source, first, stop, increment, loopBody) => {
            admit()
            node: {
                kind: "ContextualFor"
                start: keyword.start
                end: loopBody.end
                form: form
                binder: binderToken.lexeme
                binderSpan: covering(binderToken)
                headerSpan: between(open.start, close.end)
                iterable: source
                initial: first
                terminal: stop
                step: increment
                body: loopBody
            }
            seal(node, larger(larger(larger(heightOf(source), heightOf(first)),
                larger(heightOf(stop), heightOf(increment))), heightOf(loopBody)))
        }
        contextualMatch: (keyword, open, close, subjectExpression, entryTable) => {
            admit()
            node: {
                kind: "ContextualMatch"
                start: keyword.start
                end: entryTable.end
                subject: subjectExpression
                headerSpan: between(open.start, close.end)
                table: entryTable
            }
            seal(node, larger(heightOf(subjectExpression), heightOf(entryTable)))
        }
        bracedBody: (open, close, items) => {
            admit()
            node: {
                kind: "BracedBody"
                start: open.start
                end: close.end
                expressions: items
            }
            seal(node, tallest(items))
        }
        argument: (form, first, label, operand) => {
            admit()
            labelName: null
            labelSpan: null
            (label === null).ifFalse(() => {
                labelName = label.lexeme
                labelSpan = covering(label)
            })
            node: {
                kind: "Argument"
                start: first
                end: operand.end
                form: form
                name: labelName
                nameSpan: labelSpan
                expression: operand
            }
            seal(node, heightOf(operand))
        }
        parameter: (form, first, nameToken, initializer, last) => {
            admit()
            node: {
                kind: "Parameter"
                start: first
                end: last
                form: form
                name: nameToken.lexeme
                nameSpan: covering(nameToken)
                defaultValue: initializer
            }
            seal(node, heightOf(initializer))
        }
        objectItem: (form, first, item) => {
            admit()
            node: {
                kind: "ObjectItem"
                start: first
                end: item.end
                form: form
                expression: item
            }
            seal(node, heightOf(item))
        }
        mapTable: (open, close, items) => {
            admit()
            node: {
                kind: "MapTable"
                start: open.start
                end: close.end
                entries: items
            }
            seal(node, tallest(items))
        }
        mapEntry: (keyExpression, valueExpression) => {
            admit()
            node: {
                kind: "MapEntry"
                start: keyExpression.start
                end: valueExpression.end
                key: keyExpression
                value: valueExpression
            }
            seal(node, larger(heightOf(keyExpression), heightOf(valueExpression)))
        }
    }
    factory
}