simplification
Download
53 lines 2.3 KiBNomsuModified 2026-11-07 raw
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
#!/usr/bin/env nomsu -V8.0.0
###
    This file defines the patterns and file handling that the "find" and "replace"
    tools share. In a pattern, a variable like $x matches any subtree, and a
    variable used more than once has to match the same thing each time. "*" is
    short for a new variable, and "**" at the end of an action matches all of its
    remaining arguments. Variables listed with --literal="$x $y" only match
    themselves.

use "filesystem"

public:
    test:
        $pattern = (pattern "add * to $x" with literals (nil))
        assume (\(add 1 to $y) matches $pattern)
        assume (not (\(add 1 to 2 3) matches $pattern))
        $pattern = (pattern "say **" with literals "$y")
        assume ((\(say 1 2) matches $pattern).wildcard_rest deeply equals {\1, \2})
        assume (\(say $y) matches (pattern "say $y" with literals "$y"))
        assume (not (\(say $z) matches (pattern "say $y" with literals "$y")))

    (pattern $text with literals $literal_text) means:
        $literals = {}
        if ($literal_text is text):
            for $var in ($literal_text, all matches of "$([^ ]*)"):
                $literals.$var = (yes)
        $text = ($text, with "%*%*" -> "$wildcard_rest")
        $i = 0
        $text = (=lua "(\$text:gsub('%*', function() \$i = \$i + 1; return '$wildcard_'..\$i end))")
        $tree = ($text parsed)
        if (($tree.type == "Var") and (not $literals.($tree, as var))):
            fail "Pattern matches every part of the file."
        return {.tree = $tree, .literals = $literals}

    ($tree matches $pattern) means
        $tree, matching $pattern.tree $pattern.literals "wildcard_rest"

    ### The files to search, or stdin if there aren't any
    (files to search $filenames) means:
        if (#$filenames > 0): return $filenames
        say "Warning: searching stdin (ctrl-d to abort). To avoid this message, use - for stdin."
        return {"stdin"}

    ### A file's text, and its syntax tree or the error from parsing it
    (read and parse $filename) means:
        $file = (read file $filename)
        unless $file:
            fail "File does not exist: \$filename"
        try:
            $tree = ((NomsuCode from ($Source $filename 1 #$file) $file) parsed)
        ..if it fails with $msg:
            $error = $msg
        return $file $tree $error