Skip to content

Instantly share code, notes, and snippets.

@Iunius118
Last active August 27, 2025 10:51
Show Gist options
  • Select an option

  • Save Iunius118/3fb67fb909d7b7907deeeb55a34d1ca5 to your computer and use it in GitHub Desktop.

Select an option

Save Iunius118/3fb67fb909d7b7907deeeb55a34d1ca5 to your computer and use it in GitHub Desktop.
Visual Studio CodeでAntlr 4のgrammarファイルをデバッグする手順

Visual Studio CodeでAntlr 4のgrammarファイルをデバッグする手順

ANTLR4 grammar syntax supportというextensionを利用して、ワークスペース内のサンプルコードをデバッグする。

  1. Visual Studio Code (VS Code) にANTLR4 grammar syntax supportをインストールする

  2. ワークスペースを作成する

    • Code-workspaceファイルをワークスペースのルートとするフォルダに保存する
    • ワークスペースは信頼する(trusted)状態にする
  3. Antlr 4のgrammarファイルを用意する

    • 今回はANTLR公式サイトのサンプルをワークスペースに保存して使用する(ファイル名:Expr.g4
    grammar Expr;
    prog:   (expr NEWLINE)* ;
    expr:   expr ('*'|'/') expr
        |   expr ('+'|'-') expr
        |   INT
        |   '(' expr ')'
        ;
    NEWLINE : [\r\n]+ ;
    INT     : [0-9]+ ;
  4. 作成したgrammarのデバッグに使用する入力ファイルを用意する

    • 今回はinput.txtというテキストファイルをワークスペースに作成して使用する
    (123 + 456) * 789
    
  5. デバッグするためのlaunch.jsonを作成する

    • ワークスペース内に.vscodeフォルダを作成し、その中にlaunch.jsonファイルを作成する
    • 入力(input)にinput.txt、grammarにExpr.g4を指定する
    {
      "version": "2.0.0",
      "configurations": [
        {
          "name": "Debug ANTLR4 grammar",
          "type": "antlr-debug",
          "request": "launch",
          "input": "input.txt",
          "grammar": "Expr.g4",
          "startRule": "expr",
          "printParseTree": true,
          "visualParseTree": true,
        }
      ]
    }
    • この時点でのワークスペースの構成:

      ワークスペースフォルダ
      ├ .vscode
      │ └ launch.json
      ├ Expr.g4
      ├ input.txt
      └ ワークスペースの.code-workspace
      
  6. VS Codeのウィンドウ左端のアクティビティーバーからRun and Dabugを選択する(またはCtrl + Shift + D)

  7. エディタでExpr.g4を開いている状態で、Run and Dabugサイドバー上部のStart Debuggingボタン(▷)をクリックする(またはF5)

  8. デバッグ結果のParse Treeが表示される

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment