ExAST.Patcher (ExAST v0.5.0)

Copy Markdown View Source

Finds and replaces AST patterns in source code.

Accepts source strings, AST nodes, or Sourceror zippers as input. Patterns and replacements can be strings or quoted expressions.

Source-string input preserves formatting via Sourceror.patch_string/2. AST/zipper input returns modified AST trees.

# All equivalent
Patcher.find_all(source, "IO.inspect(_)")
Patcher.find_all(ast, quote(do: IO.inspect(_)))
Patcher.find_all(zipper, quote(do: IO.inspect(_)))

Summary

Functions

Finds all occurrences of pattern.

Replaces all occurrences of pattern with replacement.

Types

match()

@type match() :: %{
  node: Macro.t(),
  range: Sourceror.Range.t() | nil,
  captures: ExAST.Pattern.captures()
}

Functions

find_all(input, pattern, opts \\ [])

@spec find_all(
  String.t() | Sourceror.Zipper.t() | Macro.t(),
  ExAST.Pattern.pattern(),
  keyword()
) :: [
  match()
]

Finds all occurrences of pattern.

The first argument can be a source string, a Sourceror.Zipper, or a raw AST. The pattern can be a string or a quoted expression.

Options

  • :inside — only match nodes nested within an ancestor matching this pattern
  • :not_inside — reject nodes nested within an ancestor matching this pattern

replace_all(input, pattern, replacement, opts \\ [])

Replaces all occurrences of pattern with replacement.

When given a source string, returns a modified source string with formatting preserved. When given a zipper or AST, returns modified AST.

Pattern and replacement can be strings or quoted expressions. Captures from the pattern are substituted into the replacement template. Accepts the same :inside / :not_inside options as find_all/3.