Files

266 lines
11 KiB
Swift

import Foundation
enum PHPGrammar {
/// Matched lowercase: PHP keywords are case-insensitive.
static let keywords: Set<String> = [
"abstract", "and", "array", "as", "break", "callable", "case", "catch", "class", "clone", "const",
"continue", "declare", "default", "die", "do", "echo", "else", "elseif", "empty", "enddeclare",
"endfor", "endforeach", "endif", "endswitch", "endwhile", "enum", "eval", "exit", "extends",
"final", "finally", "fn", "for", "foreach", "from", "function", "global", "goto", "if",
"implements", "include", "include_once", "instanceof", "insteadof", "interface", "isset", "list",
"match", "namespace", "new", "or", "parent", "print", "private", "protected", "public", "readonly",
"require", "require_once", "return", "self", "static", "switch", "throw", "trait", "try", "unset",
"use", "var", "while", "xor", "yield",
"int", "float", "string", "bool", "void", "mixed", "never", "iterable", "object",
]
static let constants: Set<String> = ["true", "false", "null"]
/// Keywords after which the next name is a class.
private static let classIntroducers: Set<String> = [
"class", "interface", "trait", "enum", "extends", "implements", "instanceof", "insteadof", "new",
]
private static let scopeKeywords: Set<String> = ["self", "static", "parent"]
private static let openTags = [Unit.literal("<?php"), Unit.literal("<?="), Unit.literal("<?")]
static func scan(_ lx: inout Lexer, _ st: inout GrammarState) {
var classNext = false
var namespaceNext = false
var afterArrow = false
var afterDoubleColon = false
while lx.i < lx.end {
switch st.mode {
case .blockComment:
if lx.blockComment(from: lx.i, close: Literals.blockClose) { st.mode = .code }
continue
case let .quoted(quote):
if interpolated(&lx, from: lx.i, close: quote, interpolates: quote != Unit.apostrophe) { st.mode = .code }
continue
case let .heredoc(id, interpolates):
heredocLine(&lx, &st, id: id, interpolates: interpolates)
continue
default:
break
}
if lx.stop != nil && lx.atStop() { return }
let c = lx.u[lx.i]
let start = lx.i
if Unit.isSpace(c) {
lx.i += 1
continue
}
switch c {
case Unit.hash where lx.peek(1) == Unit.lbracket:
lx.i += 2
classNext = true
continue
case Unit.hash:
lx.lineComment()
case Unit.slash where lx.peek(1) == Unit.slash:
lx.lineComment()
case Unit.slash where lx.peek(1) == Unit.star:
lx.i += 2
if !lx.blockComment(from: start, close: Literals.blockClose) { st.mode = .blockComment }
case Unit.apostrophe, Unit.quote, Unit.backtick:
lx.i += 1
if !interpolated(&lx, from: start, close: c, interpolates: c != Unit.apostrophe) { st.mode = .quoted(c) }
case Unit.less where lx.starts(with: Literals.heredoc):
heredocStart(&lx, &st)
case Unit.less where lx.peek(1) == Unit.question:
let tag = openTags.first { lx.startsIgnoringCase(with: $0) } ?? openTags[2]
lx.i += tag.count
lx.emit(start, lx.i, .keyword)
case Unit.question where lx.peek(1) == Unit.greater:
lx.i += 2
lx.emit(start, lx.i, .keyword)
case Unit.dollar where Unit.isIdentStart(lx.peek(1)) || lx.peek(1) == Unit.dollar:
while lx.peek() == Unit.dollar { lx.i += 1 }
lx.identifier()
lx.emit(start, lx.i, .variable)
case _ where Unit.isDigit(c) || (c == Unit.dot && Unit.isDigit(lx.peek(1))):
lx.number()
case Unit.minus where lx.peek(1) == Unit.greater, Unit.question where lx.peek(1) == Unit.minus && lx.peek(2) == Unit.greater:
lx.i += c == Unit.question ? 3 : 2
lx.emit(start, lx.i, .keyword)
afterArrow = true
continue
case Unit.colon where lx.peek(1) == Unit.colon:
lx.i += 2
lx.emit(start, lx.i, .keyword)
afterDoubleColon = true
continue
case _ where Unit.isIdentStart(c) || (c == Unit.backslash && Unit.isIdentStart(lx.peek(1))):
name(&lx, classNext: &classNext, namespaceNext: &namespaceNext, afterArrow: afterArrow, afterDoubleColon: afterDoubleColon)
case _ where Unit.isOperator(c) || c == Unit.dot || c == Unit.at:
lx.operatorRun { Unit.isOperator($0) || $0 == Unit.dot || $0 == Unit.at }
default:
lx.i += 1
}
afterArrow = false
afterDoubleColon = false
}
}
/// A name, possibly qualified (`\App\Models\Agent`): the namespace path reads as a string,
/// the last segment as a keyword, class, constant or function.
private static func name(_ lx: inout Lexer, classNext: inout Bool, namespaceNext: inout Bool, afterArrow: Bool, afterDoubleColon: Bool) {
let start = lx.i
var lastSegment = start
while lx.i < lx.end {
if lx.u[lx.i] == Unit.backslash && Unit.isIdentStart(lx.peek(1)) {
lx.i += 1
lastSegment = lx.i
} else if Unit.isIdentPart(lx.u[lx.i]) {
lx.i += 1
} else {
break
}
}
if lx.peek() == Unit.backslash {
// A group import, `use App\Models\{A, B}`: the whole prefix is a path.
lx.i += 1
lx.emit(start, lx.i, .string)
return
}
let end = lx.i
let qualified = lastSegment > start
if namespaceNext {
namespaceNext = false
lx.emit(start, end, .string)
return
}
lx.emit(start, lastSegment, .string)
let word = lx.text(lastSegment, end)
let next = lx.nextNonSpace()
let callsNext = next == Unit.lparen
if afterArrow {
lx.emit(lastSegment, end, callsNext ? .plain : .variable)
return
}
if afterDoubleColon {
let lower = word.lowercased()
if lower == "class" {
lx.emit(lastSegment, end, .keyword)
} else if !callsNext && JavaScriptGrammar.isConstantName(lx, lastSegment, end) {
lx.emit(lastSegment, end, .number)
}
return
}
if !qualified {
let lower = word.lowercased()
if constants.contains(lower) {
lx.emit(lastSegment, end, .number)
return
}
if scopeKeywords.contains(lower) {
lx.emit(lastSegment, end, .keyword)
return
}
if keywords.contains(lower) && !(lx.peek() == Unit.colon && lx.peek(1) == Unit.colon) {
lx.emit(lastSegment, end, .keyword)
classNext = classIntroducers.contains(lower)
namespaceNext = lower == "namespace"
return
}
}
let followedByScope = lx.peek() == Unit.colon && lx.peek(1) == Unit.colon
let isConstant = JavaScriptGrammar.isConstantName(lx, lastSegment, end)
let looksLikeClass = Unit.isUpper(lx.u[lastSegment]) && !isConstant && !callsNext
if classNext || followedByScope || looksLikeClass {
lx.emit(lastSegment, end, lx.symbols.contains(word) ? .symbol : .variable)
} else if isConstant && !callsNext {
lx.emit(lastSegment, end, .number)
}
classNext = false
}
/// A string body with `$var`, `$var->prop` and `{$…}` interpolation; false when the line ends first.
/// With `close` 0 it runs to the end of the line, for heredoc bodies.
static func interpolated(_ lx: inout Lexer, from start: Int, close: UInt16, interpolates: Bool) -> Bool {
var runStart = start
while lx.i < lx.end {
let c = lx.u[lx.i]
if c == Unit.backslash && close != 0 {
lx.i = min(lx.i + 2, lx.end)
continue
}
if c == close {
lx.i += 1
lx.emit(runStart, lx.i, .string)
return true
}
if interpolates && c == Unit.dollar && Unit.isIdentStart(lx.peek(1)) {
lx.emit(runStart, lx.i, .string)
let varStart = lx.i
lx.i += 1
lx.identifier()
if lx.peek() == Unit.minus && lx.peek(1) == Unit.greater && Unit.isIdentStart(lx.peek(2)) {
lx.i += 2
lx.identifier()
}
lx.emit(varStart, lx.i, .variable)
runStart = lx.i
continue
}
if interpolates && c == Unit.lbrace && lx.peek(1) == Unit.dollar {
lx.emit(runStart, lx.i, .string)
let varStart = lx.i
var depth = 0
while lx.i < lx.end {
if lx.u[lx.i] == Unit.lbrace { depth += 1 }
if lx.u[lx.i] == Unit.rbrace {
depth -= 1
if depth == 0 {
lx.i += 1
break
}
}
lx.i += 1
}
lx.emit(varStart, lx.i, .variable)
runStart = lx.i
continue
}
lx.i += 1
}
lx.emit(runStart, lx.i, .string)
return false
}
/// `<<<ID`, `<<<"ID"` or `<<<'ID'` (nowdoc): the rest of the line and every line up to the marker.
private static func heredocStart(_ lx: inout Lexer, _ st: inout GrammarState) {
let start = lx.i
var k = start + 3
while k < lx.end && Unit.isSpace(lx.u[k]) { k += 1 }
let quote = lx.unit(at: k)
let quoted = quote == Unit.apostrophe || quote == Unit.quote
if quoted { k += 1 }
let idStart = k
while k < lx.end && Unit.isIdentPart(lx.u[k]) { k += 1 }
guard k > idStart else {
lx.i = start + 3
lx.emit(start, lx.i, .keyword)
return
}
let id = lx.text(idStart, k)
if quoted && lx.unit(at: k) == quote { k += 1 }
lx.i = k
lx.emit(start, k, .string)
st.mode = .heredoc(id: id, interpolates: quote != Unit.apostrophe)
}
/// One heredoc body line; the closing marker may be indented and followed by code.
private static func heredocLine(_ lx: inout Lexer, _ st: inout GrammarState, id: String, interpolates: Bool) {
let start = lx.i
var k = start
while k < lx.end && Unit.isSpace(lx.u[k]) { k += 1 }
let marker = Array(id.utf16)
if lx.starts(with: marker, at: k) && !Unit.isIdentPart(lx.unit(at: k + marker.count)) {
lx.i = k + marker.count
lx.emit(start, lx.i, .string)
st.mode = .code
return
}
_ = interpolated(&lx, from: start, close: 0, interpolates: interpolates)
}
}