API reference
ast loses comments.
notation: /why
from remold import *: alsocst(libcst),m(libcst.matchers)astmap,cstmap: composablestr -> strtransforms; source outside each match kept intact, comments included
astmap: ast-grep patterns
- use: rewrite expressible as before pattern, after template; callable
repl(match) -> strwhen new text needs computing - template
$VARthe pattern didn’t capture:KeyError
from remold import *
fix_tests = astmap(
("test_fail(lambda: $BODY, contains=$MSG)", "with expect_fail(Exception, $MSG): $BODY"),
("test_fail(lambda: $BODY)", "with expect_fail(Exception): $BODY"))
fix_tests("test_fail(lambda: f(x), contains='boom') # tricky case\n")
# with expect_fail(Exception, 'boom'): f(x) # tricky casecstmap: LibCST matcher and a function
- use: what patterns can’t express, comment- or whitespace-only changes too
- approach: match structure in the tree, where matching is easy; write new code as a string, where comments and whitespace are just characters
fnstr result: reparsed in place, so output always parses; several statements: siblings;'': statement deleted; CST node: full surgery- matchers: https://libcst.readthedocs.io/en/latest/matchers.html
Same transform; trivia='keep' keeps the comment:
tf = m.SimpleStatementLine(body=[m.Expr(m.Call(
func=m.Name('test_fail'),
args=[m.Arg(m.Lambda(body=m.SaveMatchedNode(m.DoNotCare(), 'body'))),
m.Arg(keyword=m.Name('contains'), value=m.SaveMatchedNode(m.DoNotCare(), 'msg'))]))])
def fix(node, caps): return f"with expect_fail(Exception, {code(caps['msg'])}): {code(caps['body'])}"
cstmap(tf, fix)("test_fail(lambda: f(x), contains='boom') # tricky case\n")trivia='given': you place trivia, e.g. a statement’s trailing comment (node.trailing_whitespace.comment) moved above it: returnf"{code(c)}\n{new}" if c else new
Moving code across depths
- returned string: parsed as its own module, statements spliced in; LibCST indentation is depth, not columns (statement lines, bracket continuations, comment lines): code written at any depth lands at the target depth, in target’s
default_indent; multiline string contents never re-indented /that would change the program - move code: match the enclosing node (e.g.
ClassDef), return the whole new arrangement /matching theFunctionDefreplaces it in place, still inside the class
Method f → top-level fastcore @patch function:
def fix(cd, _):
fs = [s for s in cd.body.body if m.matches(s, m.FunctionDef(name=m.Name('f')))]
if not fs: return None
fd = fs[0]
rest = cd.with_changes(body=cd.body.with_changes(body=[s for s in cd.body.body if s is not fd]))
p1 = code(fd.params.params[0]).strip().rstrip(',')
ps = ', '.join([f'{p1}:{cd.name.value}'] + [code(p).strip().rstrip(',') for p in fd.params.params[1:]])
return f"{code(rest)}\n@patch\ndef {fd.name.value}({ps}):{code(fd.body)}"
src = "class A:\n def __init__(self): self.x = 1\n\n def f(self, n): # add `n` to `x`\n y = self.x+n\n return y\n"
cstmap(m.ClassDef(), fix, trivia='given')(src)- result:
class Awithoutf, then@patch def f(self:A, n): # addntox`, body dedented a level;code(fd.body)` carried body and def-line comment
Finding
Pattern transforms
Use astmap when a rewrite fits an ast-grep before/after pattern, and astfind to collect matching source spans without rewriting.
astmap
def astmap(
*rules:tuple[str, typing.Union[str, typing.Callable]], # `(pattern, repl)` pairs where `repl` is a `$VAR` template or `callable(match) -> str`
)->Callable[[str], str]: # Composable `src -> src` source transformReturn a str -> str transform applying ast-grep pattern rules in order, reparsing between rules.
Raises KeyError if a template references a $VAR not captured by its pattern.
fix = astmap(("test_fail(lambda: $BODY)", "with expect_fail(Exception): $BODY"))
assert fix("test_fail(lambda: f(x)) # keep\n") == "with expect_fail(Exception): f(x) # keep\n"astfind
def astfind(
src:str, # Python source text to search
pattern:str, # ast-grep pattern, e.g. `"save($$$, ts=$_)"`
)->list[str]: # Matching source substrings in appearance orderReturn the source text of each ast-grep pattern match in src.
CST transforms
Use cstmap for structural, layout, or comment-aware rewrites that pattern rules cannot express; render nodes with code and discover LibCST attribute paths with whereis.
cstmap
def cstmap(
matcher, # `libcst.matchers` matcher; `m.SaveMatchedNode` captures arrive in `fn`'s second arg
fn:Callable, # `fn(node, caps)` returning `None` (unchanged), a `str` (reparsed in place), or a CST node
trivia:str='keep', # `'keep'` carries leading lines and trailing comment; `'given'` takes `fn`'s output verbatim
)->Callable[[str], str]: # Composable `src -> src` source transformReturn a str -> str transform replacing every LibCST node matching matcher with fn’s result.
code
def code(
node:libcst._nodes.base.CSTNode, # LibCST node to render
)->str: # Exact source text including triviaRender source text for LibCST node, preserving comments and whitespace.
whereis
def whereis(
src:str, # Python source snippet to inspect
*frags:str, # Source fragments to locate (e.g. `'foo'`, `'# note'`)
contains:bool=False, # Match nodes containing `frag` rather than equaling it
)->dict[str, list[str]]: # `{frag: [attr_paths...]}` ordered deepest node firstReturn the LibCST attribute paths where each fragment lives, deepest node first.
Symbol queries
Inspect top-level bindings and referenced names across any Python binding syntax; both return an empty set when src does not parse.
symdefs
def symdefs(
src:str, # Python source text
)->set[str]: # Names bound in `src`'s top-level scope (empty set on `SyntaxError`)Return all names bound in src’s top-level scope across assignments, imports, loops, def, class, and match.
assert symdefs("x, *rest = items\ndef helper(): pass\n") == {'x', 'rest', 'helper'}symrefs
def symrefs(
src:str, # Python source text
)->set[str]: # Names referenced anywhere in `src` (empty set on `SyntaxError`)Return all names loaded anywhere in src (empty set if src does not parse).
Comments and layout
code(p)); comment afterdef ...::fd.body.header.commentwhereis(snippet, *frags); copy the paths intofn/no searching node docsLayout-only change, one param per line: