SPB Git

Repository Public

ShellLexer.swift 9.1 KB 264 lines swift

1import Foundation23/// One shell word after quote removal. `text` keeps the raw source of any4/// command/process substitution so that later checks can still see it.5struct ShellWord: Sendable, Equatable {6    var text = ""7    var substitutions: [String] = []8    var started = false9}1011struct ShellRedirect: Sendable, Equatable {12    let op: String13    let target: ShellWord14}1516/// A simple command: words plus redirections, with its position in a pipeline.17struct ShellCommand: Sendable, Equatable {18    var words: [ShellWord] = []19    var redirects: [ShellRedirect] = []20    var pipedInput = false21    var pipedOutput = false2223    var isEmpty: Bool { words.isEmpty && redirects.isEmpty }24}2526struct ShellParse: Sendable, Equatable {27    var commands: [ShellCommand] = []28    /// Unterminated quote, backtick or parenthesis.29    var unterminated = false30}3132/// A small, allocation-light POSIX-ish lexer. It does not expand anything; it only33/// splits a line into simple commands so that risk rules can reason about them.34struct ShellLexer {35    private let chars: [Character]36    private var i = 037    private var result = ShellParse()38    private var current = ShellCommand()39    private var word = ShellWord()40    private var pendingRedirect: String?4142    static func parse(_ source: String) -> ShellParse {43        var lexer = ShellLexer(chars: Array(source))44        lexer.run()45        return lexer.result46    }4748    private init(chars: [Character]) { self.chars = chars }4950    private func peek(_ offset: Int = 1) -> Character? {51        i + offset < chars.count ? chars[i + offset] : nil52    }5354    private mutating func append(_ c: Character) {55        word.text.append(c)56        word.started = true57    }5859    private mutating func flushWord() {60        guard word.started else { return }61        if let op = pendingRedirect {62            current.redirects.append(ShellRedirect(op: op, target: word))63            pendingRedirect = nil64        } else {65            current.words.append(word)66        }67        word = ShellWord()68    }6970    private mutating func flushCommand(pipe: Bool) {71        flushWord()72        pendingRedirect = nil73        if current.isEmpty {74            if pipe { current.pipedInput = true }75            return76        }77        current.pipedOutput = pipe78        result.commands.append(current)79        current = ShellCommand()80        current.pipedInput = pipe81    }8283    /// `chars[i]` is "(". Returns the balanced inner text and leaves `i` after ")".84    private mutating func readParenthesized() -> String {85        var depth = 086        var inner = ""87        var quote: Character?88        while i < chars.count {89            let c = chars[i]90            if let q = quote {91                if c == "\\" && q == "\"", let next = peek() { inner.append(c); inner.append(next); i += 2; continue }92                if c == q { quote = nil }93                inner.append(c); i += 194                continue95            }96            switch c {97            case "\\":98                inner.append(c)99                if let next = peek() { inner.append(next); i += 1 }100                i += 1101            case "'", "\"":102                quote = c; inner.append(c); i += 1103            case "(":104                depth += 1105                if depth > 1 { inner.append(c) }106                i += 1107            case ")":108                depth -= 1109                i += 1110                if depth == 0 { return inner }111                inner.append(c)112            default:113                inner.append(c); i += 1114            }115        }116        result.unterminated = true117        return inner118    }119120    /// `chars[i]` is a backtick. Leaves `i` after the closing backtick.121    private mutating func readBacktick() -> String {122        i += 1123        var inner = ""124        while i < chars.count {125            let c = chars[i]126            if c == "\\", let next = peek() { inner.append(next); i += 2; continue }127            if c == "`" { i += 1; return inner }128            inner.append(c); i += 1129        }130        result.unterminated = true131        return inner132    }133134    private mutating func readSubstitution(prefix: String) {135        // `i` is on "(".136        let inner = readParenthesized()137        word.substitutions.append(inner)138        word.text += prefix + "(" + inner + ")"139        word.started = true140    }141142    private mutating func run() {143        while i < chars.count {144            let c = chars[i]145            switch c {146            case " ", "\t", "\r":147                flushWord(); i += 1148            case "\n", "\r\n":149                flushCommand(pipe: false); i += 1150            case "\\":151                if let next = peek() {152                    if next != "\n" { append(next) }153                    i += 2154                } else { i += 1 }155            case "'":156                word.started = true157                i += 1158                while i < chars.count, chars[i] != "'" { word.text.append(chars[i]); i += 1 }159                if i >= chars.count { result.unterminated = true } else { i += 1 }160            case "\"":161                word.started = true162                i += 1163                var closed = false164                while i < chars.count {165                    let d = chars[i]166                    if d == "\"" { closed = true; i += 1; break }167                    if d == "\\", let next = peek() {168                        if "\"\\$`".contains(next) { word.text.append(next) }169                        else if next != "\n" { word.text.append(d); word.text.append(next) }170                        i += 2171                    } else if d == "$", peek() == "(" {172                        i += 1173                        readSubstitution(prefix: "$")174                    } else if d == "`" {175                        let inner = readBacktick()176                        word.substitutions.append(inner)177                        word.text += "`" + inner + "`"178                    } else {179                        word.text.append(d); i += 1180                    }181                }182                if !closed { result.unterminated = true }183            case "$":184                if peek() == "(" {185                    i += 1186                    readSubstitution(prefix: "$")187                } else if peek() == "'" {188                    word.started = true189                    i += 2190                    var closed = false191                    while i < chars.count {192                        let d = chars[i]193                        if d == "\\", let next = peek() { word.text.append(next); i += 2; continue }194                        if d == "'" { closed = true; i += 1; break }195                        word.text.append(d); i += 1196                    }197                    if !closed { result.unterminated = true }198                } else {199                    append(c); i += 1200                }201            case "`":202                let inner = readBacktick()203                word.substitutions.append(inner)204                word.text += "`" + inner + "`"205                word.started = true206            case "#":207                if word.started { append(c); i += 1 } else {208                    while i < chars.count, chars[i] != "\n", chars[i] != "\r\n" { i += 1 }209                }210            case ";":211                flushCommand(pipe: false); i += 1212            case "&":213                if peek() == "&" {214                    flushCommand(pipe: false); i += 2215                } else if peek() == ">" {216                    flushWord()217                    i += 2218                    var op = "&>"219                    if i < chars.count, chars[i] == ">" { op = "&>>"; i += 1 }220                    pendingRedirect = op221                } else {222                    flushCommand(pipe: false); i += 1223                }224            case "|":225                if peek() == "|" {226                    flushCommand(pipe: false); i += 2227                } else {228                    flushCommand(pipe: true); i += 1229                    if i < chars.count, chars[i] == "&" { i += 1 }230                }231            case "(", ")":232                flushCommand(pipe: false); i += 1233            case "<", ">":234                if peek() == "(" {235                    i += 1236                    readSubstitution(prefix: String(c))237                    break238                }239                if word.started, word.substitutions.isEmpty, !word.text.isEmpty, word.text.allSatisfy(\.isASCIIDigit) {240                    word = ShellWord() // file-descriptor prefix such as 2>241                }242                flushWord()243                var op = String(c)244                i += 1245                while i < chars.count, op.count < 3 {246                    let d = chars[i]247                    let allowed: Bool = c == ">" ? (op == ">" && (d == ">" || d == "|" || d == "&"))248                                                 : ((op == "<" && (d == "<" || d == "&" || d == ">")) || (op == "<<" && (d == "<" || d == "-")))249                    guard allowed else { break }250                    op.append(d); i += 1251                }252                pendingRedirect = op253            default:254                append(c); i += 1255            }256        }257        flushCommand(pipe: false)258    }259}260261private extension Character {262    var isASCIIDigit: Bool { self >= "0" && self <= "9" }263}264
Files main
Menu

Theme