Search code examples
abstract-syntax-tree

Why use ast syntax tree modification instead of regex replacement?


javascript can use ast to convert js code into syntax tree, then change the data according to the syntax tree, and then use tools to convert ast syntax tree into js file, and finally write to the file. like babel. But regular expressions can also achieve this function, even faster, so why convert to ast syntax tree, is there any benefit?


Solution

  • Based on your question, I assume you are patching the JavaScript file. The simplest way to do it will be find and replace if you have a fixed sequence of characters. If you are dealing with a pattern based find and replace use regular expressions.

    As you start writing regex patterns for more conditions your logic might miss or match too much. for e.g: you might write a pattern to match if statement with a opening brace beside it. The user might type the opening brace on a new line, breaking your regex find and replace.

    ASTs turn your code into structured format. This format is simpler to edit and do replacements on only that text node. This helps in not changing anything that was not expected.

    This makes AST transformation safer and less error-prone than a string-based solution.