grippo 0.3.0

Grok, regex, CEL and scrubbing on typed primitives. Up to 9 times faster than the stock Rust regex.
Documentation
// Project:   grippo
// File:      src/windows/powershell.rs
// Purpose:   PowerShell command text read into words with its own quote and dash characters
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! PowerShell command text read into words, each a span of the text.
//!
//! PowerShell isn't the C runtime. Its tokenizer takes U+2013, U+2014 and
//! U+2015 as a parameter dash, U+2018 to U+201B and U+201C to U+201E as
//! string quotes, a backtick as an escape, and Unicode separators as white
//! space. A rule keyed on `-Password` and ASCII quotes misses a line that
//! spells the dash as U+2013 and quotes the value with U+201C and U+201D, so it
//! reads the text through [`normalised`].
//! The characters are the sets in PowerShell's
//! [`CharTraits.cs`](https://github.com/PowerShell/PowerShell/blob/master/src/System.Management.Automation/engine/parser/CharTraits.cs)
//! (`IsDash`, `IsSingleQuote`, `IsDoubleQuote`, `IsWhitespace`), and
//! [about_Quoting_Rules](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_quoting_rules)
//! says PowerShell reads smart quotes as ordinary ones.
//!
//! This reads words, not a language. Words end at white space and line
//! breaks. `;`, `|`, `&`, `,` and brackets stay inside a word, so a mask that
//! takes the whole word hides more than the secret and never less. Variables,
//! sub-expressions, here-strings and `` `u{...} `` escapes aren't read.
//!
//! For powershell.exe and pwsh.exe, split the host's own arguments with
//! [`argv`](super::argv), and read the command text after `-Command` with
//! this. A string passed to `-Command` is PowerShell code, and everything
//! after the parameter belongs to it.
//!
//! ```
//! use grippo::windows::powershell::normalised;
//!
//! let text = "Connect-Db \u{2013}Password \u{201c}hunter 2\u{201d} -Port 5432";
//! let values: Vec<_> = normalised(text).map(|a| a.value).collect();
//! assert_eq!(values, ["Connect-Db", "-Password", "hunter 2", "-Port", "5432"]);
//! ```

use std::borrow::Cow;
use std::iter::{FusedIterator, Peekable};
use std::ops::Range;
use std::str::CharIndices;

use super::Arg;

/// The spans of `text`'s words. See [`args`].
#[derive(Debug, Clone)]
pub struct Args<'a> {
    text: &'a str,
    pos: usize,
}

/// The words of `text` with their values. See [`normalised`].
#[derive(Debug, Clone)]
pub struct Normalised<'a> {
    spans: Args<'a>,
}

/// The spans of the words of `text`, a PowerShell command text.
///
/// A word is a run of characters between PowerShell white space or line
/// breaks. A quoted run, with any quote of the string-quote sets, can hold
/// white space, and `` ` `` escapes the character after it. A quoted run left
/// open takes the rest of the text. Nothing is allocated.
#[must_use]
pub const fn args(text: &str) -> Args<'_> {
    Args { text, pos: 0 }
}

/// The words of `text` with the values PowerShell reads from them.
///
/// A leading dash character is `-`, quotes are read away with a doubled quote
/// as one, and a backtick escape is resolved. Case isn't folded. The value
/// borrows the text when the word has none of those.
#[must_use]
pub const fn normalised(text: &str) -> Normalised<'_> {
    Normalised { spans: args(text) }
}

impl Iterator for Args<'_> {
    type Item = Range<usize>;

    fn next(&mut self) -> Option<Range<usize>> {
        let rest = self.text.get(self.pos..)?;
        let start = self.pos + rest.find(|c| !is_break(c))?;
        self.pos = word_end(self.text, start);
        Some(start..self.pos)
    }
}

impl FusedIterator for Args<'_> {}

impl<'a> Iterator for Normalised<'a> {
    type Item = Arg<'a>;

    fn next(&mut self) -> Option<Arg<'a>> {
        let span = self.spans.next()?;
        let raw = self.spans.text.get(span.clone())?;
        Some(Arg {
            span,
            value: decode(raw),
        })
    }
}

impl FusedIterator for Normalised<'_> {}

const fn is_dash(c: char) -> bool {
    matches!(c, '-' | '\u{2013}' | '\u{2014}' | '\u{2015}')
}

const fn is_single_quote(c: char) -> bool {
    matches!(c, '\'' | '\u{2018}' | '\u{2019}' | '\u{201a}' | '\u{201b}')
}

const fn is_double_quote(c: char) -> bool {
    matches!(c, '"' | '\u{201c}' | '\u{201d}' | '\u{201e}')
}

/// White space as `IsWhitespace` has it, and the line breaks that end a word.
const fn is_break(c: char) -> bool {
    matches!(
        c,
        ' ' | '\t' | '\n' | '\r' | '\u{b}' | '\u{c}' | '\u{85}' | '\u{a0}'
    ) || matches!(
        c,
        '\u{1680}' | '\u{2000}'..='\u{200a}' | '\u{2028}' | '\u{2029}'
    ) || matches!(c, '\u{202f}' | '\u{205f}' | '\u{3000}')
}

type Chars<'a> = Peekable<CharIndices<'a>>;

/// The end of the word starting at `start`.
fn word_end(text: &str, start: usize) -> usize {
    let mut chars: Chars<'_> = text
        .get(start..)
        .unwrap_or_default()
        .char_indices()
        .peekable();
    while let Some((i, c)) = chars.next() {
        if is_break(c) {
            return start + i;
        }
        if c == '`' {
            chars.next();
        } else if is_single_quote(c) {
            skip_single(&mut chars);
        } else if is_double_quote(c) {
            skip_double(&mut chars);
        }
    }
    text.len()
}

/// Past the end of a single-quoted run: the first quote not followed by another.
fn skip_single(chars: &mut Chars<'_>) {
    while let Some((_, c)) = chars.next() {
        if is_single_quote(c) && chars.next_if(|&(_, d)| is_single_quote(d)).is_none() {
            return;
        }
    }
}

/// Past the end of a double-quoted run, where a backtick escapes the next character.
fn skip_double(chars: &mut Chars<'_>) {
    while let Some((_, c)) = chars.next() {
        if c == '`' {
            chars.next();
        } else if is_double_quote(c) && chars.next_if(|&(_, d)| is_double_quote(d)).is_none() {
            return;
        }
    }
}

/// What a backtick makes of the character after it.
const fn unescape(c: char) -> char {
    match c {
        '0' => '\0',
        'a' => '\u{7}',
        'b' => '\u{8}',
        'e' => '\u{1b}',
        'f' => '\u{c}',
        'n' => '\n',
        'r' => '\r',
        't' => '\t',
        'v' => '\u{b}',
        other => other,
    }
}

fn decode(raw: &str) -> Cow<'_, str> {
    let dash = raw.starts_with(|c: char| is_dash(c) && c != '-');
    if !dash && !raw.contains(|c: char| c == '`' || is_single_quote(c) || is_double_quote(c)) {
        return Cow::Borrowed(raw);
    }
    let mut out = String::with_capacity(raw.len());
    let mut chars = raw.chars().peekable();
    if dash {
        chars.next();
        out.push('-');
    }
    while let Some(c) = chars.next() {
        if c == '`' {
            out.extend(chars.next().map(unescape));
        } else if is_single_quote(c) {
            while let Some(d) = chars.next() {
                if !is_single_quote(d) {
                    out.push(d);
                } else if let Some(escaped) = chars.next_if(|&e| is_single_quote(e)) {
                    out.push(escaped);
                } else {
                    break;
                }
            }
        } else if is_double_quote(c) {
            while let Some(d) = chars.next() {
                if d == '`' {
                    out.extend(chars.next().map(unescape));
                } else if !is_double_quote(d) {
                    out.push(d);
                } else if let Some(escaped) = chars.next_if(|&e| is_double_quote(e)) {
                    out.push(escaped);
                } else {
                    break;
                }
            }
        } else {
            out.push(c);
        }
    }
    Cow::Owned(out)
}

#[cfg(test)]
mod tests;