1
1

More than 3 years have passed since last update.

acornによるAST処理で行端にセミコロンが入らないようにする

Posted at

概要

あんまりニーズないと思いますがacornを使ってJavascriptのAST変換→書き戻しを行う際に、行端へセミコロンを入れたくなかった為、その方法を記載します

環境

"acorn": "8.4.1"
"astring": "1.7.5"
"typescript": "4.3.5"

コード

import { parse } from "acorn";
import { generate, GENERATOR } from "astring";
const getCode = (ast: Node): string => {
  return generate(ast, {
    generator: Object.assign({}, GENERATOR, {
      ExpressionStatement: (node: any, state: any) => {
        // セミコロンを除外する為、ExpressionstatmentのみExtendsする
        const precedence = state.expressionsPrecedence[node.expression.type];
        const NEEDS_PARENTHESES = 17; // astring内より定数値コピペ
        if (precedence === NEEDS_PARENTHESES || precedence === 3 && node.expression.left.type[0] === 'O') {
          state.write('(');
          GENERATOR[node.expression.type](node.expression, state);
          state.write(')');
        } else {
          GENERATOR[node.expression.type](node.expression, state);
        }
      }
    }),
  });
}

getCode(parse("code"));

astringのオプションのgeneratorにて書き戻す際のロジックを拡張出来ます。
今回はExpressionstatmentの行端の";"が入らないようにしたかったので上記のコードに致しました。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1