0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

構文解析器作成用言語ParserScriptで簡単な式のマッチングを行う

Last updated at Posted at 2024-10-26

現在、ParserScriptは非推奨です。

 今回はParserScriptで簡単な式のマッチングを行います。
 使用するバージョンは2.0です。

式の定義

 簡単な四則演算の文法をEBNFで書く。

<factor>     ::= [ "-" ] [ ( "0." | "." ) ] NUMBER | "(" <expression> ")"
<term>       ::= <factor> { ( "*" | "/") <factor> }
<expression> ::= <term> { ( "+" | "-" ) <term> }

 これをParserScriptで書くと

Grammar.prs
ESCAPE ' '
CALL EXPRESSION
AST FACTOR
    NOESCAPE ' '
    RECORD
    VRECORD ""
    MATCH "-"
    DOWNPUSH
    VRECORD ""
    RECORD
    MATCH "0."
    NOMATCH?
        BREAK
       MATCH "."
    END
    DOWNPUSH
    NUMBER
    NOMATCH?
        BREAK
        ESCAPE ' '
        MATCH "("
        CALL EXPRESSION
        MATCH ")"
    END
    ESCAPE ' '
LAST
AST TERM
    CALL FACTOR
    VRECORD ""
    SET
    VRECORD ""
    MATCH "*"
    NOMATCH?
        BREAK
        MATCH "/"
    END
    CALL FACTOR
    MATCH?
        JUMP
    END
    NOMATCH?
        DOWNPUSH
    END
LAST
AST EXPRESSION
    CALL TERM
    VRECORD ""
    SET
    VRECORD ""
    MATCH "*"
    NOMATCH?
        BREAK
        MATCH "-"
    END
    CALL TERM
    MATCH?
        JUMP
    END
    NOMATCH?
        DOWNPUSH
    END
LAST

 となります。
 予約語は大文字でも小文字でも良いです。

Grammar.prsの実行

 以下はC#のParserScriptの実行方法

Program.cs
using System;
using ParserScript;

class Program {
    static void Main() {
        string str = Console.ReadLine() ?? "";
        var res = ParserScript.Run(@"./Grammar.prs", "(3 + 4 / 2) * 3");
        // 第一引数にファイルのパスを書く
        Console.WriteLine(res.Success ? "Passed" : "Failure");
        Console.WriteLine($"Result: {res.Value}");
    }
}

 結果↓

(3 + 4 / 2) * 3
Passed
Result: (3 + 4 / 2) * 3

 「1 +」とかだと

1 +
Failure
Result: 

 になります。

終わりに

 このままでは式のマッチングだけなので、式を逆ポーランド記法に変換するコードが完成したらその記事を書こうと思います。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?