2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonで構築するInterpreterパターン:独自言語を解析する構文的アプローチ

Posted at

概要

Interpreter(インタープリター)パターンは、
文法ルールに従った構文(言語)を定義し、それを評価(解釈)するためのクラス構造を用いてドメイン固有言語(DSL)を実装する設計パターンである。

四則演算、条件文、コマンド解釈、数式処理など、
小規模な構文系を再現可能にし、動的に構造化された振る舞いを構築することができる。


1. なぜInterpreterが必要か?

❌ DSLを文字列で解析しようとする煩雑な処理

def eval_expr(expr):
    if expr == "1 + 2":
        return 3

→ パターンが増えるごとに if/else が増え、構造的拡張が困難


✅ 各構文要素をクラスで定義し、再帰的に解釈できるようにする

expr = Add(Number(1), Number(2))
expr.interpret()  # → 3

式の構造をオブジェクトで表現し、意味的な解釈が可能に


2. 基本構造

✅ 抽象式クラス

class Expression:
    def interpret(self):
        raise NotImplementedError

✅ 数値ノード(終端)

class Number(Expression):
    def __init__(self, value):
        self.value = value

    def interpret(self):
        return self.value

✅ 非終端式ノード(加算)

class Add(Expression):
    def __init__(self, left: Expression, right: Expression):
        self.left = left
        self.right = right

    def interpret(self):
        return self.left.interpret() + self.right.interpret()

✅ 使用例

expr = Add(Number(4), Add(Number(2), Number(3)))  # 4 + (2 + 3)
print(expr.interpret())  # → 9

3. Python的応用:DSL構築と構文木の表現

✅ AND / OR 検索クエリの例

class Terminal(Expression):
    def __init__(self, keyword):
        self.keyword = keyword

    def interpret(self, context):
        return self.keyword in context

class And(Expression):
    def __init__(self, left, right):
        self.left = left
        self.right = right

    def interpret(self, context):
        return self.left.interpret(context) and self.right.interpret(context)
expr = And(Terminal("Python"), Terminal("Tips"))
print(expr.interpret("Python Tips Article"))  # → True
print(expr.interpret("Python Design"))        # → False

4. 実務ユースケース

✅ DSLベースの構成ファイルやルールエンジンの実装

→ 条件・数式・構成定義などを式として構造化解釈


✅ 検索クエリ・フィルタエンジン

→ AND/OR/NOT を式ツリーとして評価し、柔軟な条件検索


✅ 数式処理・簡易言語の構築(電卓、式エンジン)

→ 数学DSLの解釈・計算・変換に最適


✅ 自然言語処理・構文分析のトイ実装

→ 文法規則に基づく再帰下降型のパーサ実験などに応用


5. よくある誤用と対策

❌ 抽象構文木の構築と評価処理が密結合

→ ✅ 解釈ロジックは interpret() に閉じ、構文構築は別レイヤーで


❌ 状態を内部に持ちすぎて評価が不安定

→ ✅ インターフェースは明示的に interpret(context) のようにし、明確な引数で評価


❌ 構文パターンの拡張が面倒になる設計

→ ✅ 継承ではなく合成による構造拡張を基本とし、柔軟性を保つ


結語

Interpreterパターンとは、“構文と意味の対応関係をコード構造で明示化する技術”である。

  • 文法の各要素をクラスとして明示し、意味解釈を責務として定義
  • 再帰的な式処理、DSLの実装、ルールエンジンなどに応用可能
  • Pythonのオブジェクト指向特性により、抽象構文木と意味解釈の実装が極めて直感的に

Pythonicとは、“構造を持った表現をコードとして操作可能にすること”であり、
Interpreterパターンはその言語的構造性を、柔軟な評価フローとして表現するための設計技法である。

2
3
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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?