Quantcast
Channel: アシアルブログ
Viewing all articles
Browse latest Browse all 298

PHPで仮想マシンベースの正規表現エンジンを作ってみる 第一回

$
0
0
こんにちは、久保田です。

皆さん正規表現は使っていますか? PHPに限らずどんな言語を使っていても、正規表現にお世話になっていないプログラマはいないと思います。しかし、その正規表現がどのように実装されているかについては知らない方が多いのではないのでしょうか。

この記事では、その正規表現エンジンの実装方法の一つである仮想マシンによる正規表現エンジンの実装方法を解説しつつ実際に簡単な正規表現エンジンを作っていきたいと思います。

正規表現エンジンの実装方法



正規表現エンジンの実装方法はいくつかあるのですが、それの一つに仮想マシンによって正規表現のマッチング処理を実行するやり方があります。PHPで利用している正規表現エンジンであるPCREはこの方式を採用しています。

仮想マシンによる実装方法は、正規表現というよりもプログラミング言語の実装方法の一つとして知られています。Rubyの最もメジャーな実装であるCRubyの1.9以降を例にして言えば、Rubyのコードは一旦パースされて、YARVと呼ばれる内部の仮想マシンが実行できる内部表現にコンパイルされたのち仮想マシンによって実行されます。

この実装方法は実は正規表現にも適用できます。今回のこの一連の記事ではこの仮想マシンによる正規表現エンジンの仕組みを解説しつつ、実際に簡単な正規表現エンジンを実装してみたいと思います。

通常正規表現エンジンはCやC++などで実装されますが、僕はC言語をまともに読み書きできないハイパーゆとりなのでここではみんな大好きPHPで実装してみたいと思います。

仮想マシンによる正規表現エンジンの実装



今回作成していく正規表現エンジンの実装方法ですが、基本的にRegular Expression Matching: the Virtual Machine Approachを参照していきます。この中では、仮想マシンによる正規表現エンジンの実装方法についてわかりやすく記述されています。英語ですが平易な語彙で記述されているので、適当に眺めているだけでもなんとなくわかった気になれます。

記事で紹介されている仮想マシンの概要を以下に引用します。

  1. To start, we'll define a regular expression virtual machine (think Java VM). The VM executes one or more threads, each running a regular expression program, which is just a list of regular expression instructions. Each thread maintains two registers while it runs: a program counter (PC) and a string pointer (SP). 
  2.  
  3.  The regular expression instructions are: 
  4.  
  5.     char c     If the character SP points at is not c, stop this thread: it failed.
  6.                Otherwise, advance SP to the next character and advance PC to the next instruction. 
  7.     match      Stop this thread: it found a match. 
  8.     jmp x      Jump to (set the PC to point at) the instruction at x. 
  9.     split x, y Split execution: continue at both x and y. Create a new thread with SP 
  10.                copied from the current thread. One thread continues with PC x. 
  11.                The other continues with PC y. (Like a simultaneous jump to both locations.)

これを見ると、正規表現を実行する仮想マシンが驚くほど単純であることがわかります。この仮想マシンが必要とするレジスタはPCとSPの2つで、必要とする命令はmatchとcharとsplitとjmpのたったの4つだけです。

PHP内部の仮想マシンであるZendEngineの持っている命令数が150程度あるのに比べると、べらぼうに簡単であることがわかると思います。

実装の流れ



実装していく流れですが、以下の様な流れで実装していきます。

1. 正規表現パーサの構築
2. 仮想マシンの構築
3. コンパイラ構築

この記事では、まず正規表現のパーサを構築します。その後、正規表現のマッチング処理を行う仮想マシンを構築し、最後に正規表現を仮想マシンの命令に変換するコンパイラを構築します。

正規表現パーサの構築



まず正規表現エンジンを実装するにあたって、正規表現の文法のパーサを構築します。

実装する正規表現の文法の概要を簡単に書いておきます。解説用のものなので、簡易的な文法にとどめています。

  1. * hoge|fuga  "|"による選択を利用できます
  2. * a(ho|ge)b  括弧によるグルーピングができます
  3. * a+b*c?     "+"や"*"や"?"などの繰り返し演算子が利用できます

PHPPEGを用いて正規表現の文法のパーサを構築します。PHPPEGはPEGに基づくパーサコンビネータです。これを用いると簡単にパーサを構築出来ます。

パーサの構築についてはそれほど本質的では無いのでここでは特に解説無しでいきます。PHPPEGの使い方はドキュメントを参照してください。

  1. <?php
  2. include_once __DIR__ . '/../vendor/autoload.php';
  3.  
  4. class RegexSyntaxParser implements PEG_IParser
  5. { 
  6.     protected $regexParser;
  7.  
  8.     function __construct()
  9.     {
  10.         /*
  11.          * regex <- split*
  12.          * split <- operations ("|" operations)*
  13.          * operations <- operation*
  14.          * operation <- target operator
  15.          * target <- charClass / group / singleCharacter
  16.          * suffixOperator <- "*" / "+" / "?"
  17.          * group <- "(" split ")"
  18.          * charClass <- "[" (!"]" .)+ "]"
  19.          * singleCharacter <- ![+*?|[)] .
  20.          */
  21.  
  22.         $singleCharacter = self::objectize('singleCharacter', 
  23.             PEG::second(PEG::not(PEG::choice('*', '+', '?', '|', '[', ')')), PEG::anything())
  24.         );
  25.         $charClass = self::objectize('charClass', PEG::second(
  26.             '[', 
  27.             PEG::many1(PEG::second(PEG::not(']'), PEG::anything())),
  28.             ']'
  29.         ));
  30.         $group = self::objectize('group', PEG::memo(PEG::second(
  31.             '(', PEG::ref($split), ')'
  32.         )));
  33.         $suffixOperator = self::objectize('suffixOperator', PEG::choice('*', '+', '?'));
  34.         $target = PEG::choice(
  35.             $charClass, $group, $singleCharacter
  36.         );
  37.         $operation = self::objectize('operation', 
  38.             PEG::seq($target, PEG::optional($suffixOperator))
  39.         );
  40.         $operations = self::objectize('operations', PEG::many($operation));
  41.         $split = self::objectize('split', 
  42.             PEG::choice(PEG::listof($operations, '|'), '')
  43.         );
  44.  
  45.         $this->regexParser = self::objectize('regex', PEG::many($split));
  46.     }
  47.  
  48.     /**
  49.      * @return PEG::IParser
  50.      */
  51.     function getParser() 
  52.     {
  53.         return $this->regexParser;
  54.     }
  55.  
  56.     /**
  57.      * @param String $str
  58.      */
  59.     function parse(PEG_IContext $context)
  60.     {
  61.         return $this->regexParser->parse($context);
  62.     }
  63.  
  64.     /**
  65.      * @param PEG_IParser
  66.      * @return PEG_IParser
  67.      */
  68.     protected static function objectize($name, PEG_IParser $parser)
  69.     {
  70.         return PEG::hook(function($result) use($name) {
  71.             return new RegexSyntaxNode($name, $result);
  72.         }, $parser);
  73.     }
  74.  
  75. }
  76.  
  77. class RegexSyntaxNode
  78. {
  79.     protected $name, $content;
  80.  
  81.     function __construct($name, $content) 
  82.     {
  83.         $this->name = $name;
  84.         $this->content = $content;
  85.     }
  86.  
  87.     function __toString()
  88.     {
  89.         $result = '';
  90.  
  91.         $result .= $this->name . " {\n";
  92.  
  93.         $result .= $this->dump($this->content);
  94.  
  95.         $result .= "}";
  96.  
  97.         return $result;
  98.     }
  99.  
  100.     protected function dump($content)
  101.     {
  102.         $result = '';
  103.         if (is_array($content)) {
  104.             foreach ($content as $i => $element) {
  105.                 $result .= $this->dump($element);
  106.             }
  107.         } elseif ($content instanceof self) {
  108.             $result .= self::indent($content->__toString()) . "\n";
  109.         } else {
  110.             $result .= self::indent(var_export($content, true)) . "\n";
  111.         }
  112.  
  113.         return $result;
  114.     }
  115.  
  116.     static function indent($str) {
  117.         $lines = preg_split("/\r|\n|\r\n/", $str);
  118.  
  119.         foreach ($lines as $i => $line) {
  120.             $lines[$i] = '  ' . $line;
  121.         }
  122.  
  123.         return implode($lines, "\n");
  124.     }
  125. }

このコードやプロジェクトは、githubに公開していますので実際に動かしてみたい方は参照してください。

このパーサに正規表現をかけてみます。

  1. <?php
  2. include_once __DIR__ . '/../src/PHPRegex.php';
  3.  
  4. $parser = new RegexSyntaxParser();
  5.  
  6. echo 'a => ' . $parser->parse(PEG::context('a')) . "\n\n";
  7.  
  8. echo 'a|b =>' .  $parser->parse(PEG::context('a|b')) . "\n\n"; 
  9.  
  10. echo 'a(bc) => ' . $parser->parse(PEG::context('a(bc)')) . "\n\n";
  11.  
  12. echo 'a+b*c? => ' . $parser->parse(PEG::context('a+b*c?')) . "\n\n";

すると、以下のように出力されます。正規表現がきちんとパースされて構文木ができているのがわかると思います。

  1. a => regex {
  2.   split {
  3.     operations {
  4.       operation {
  5.         singleCharacter {
  6.           'a'
  7.         }
  8.         false
  9.       }
  10.     }
  11.   }
  12. }
  13. a|b =>regex {
  14.   split {
  15.     operations {
  16.       operation {
  17.         singleCharacter {
  18.           'a'
  19.         }
  20.         false
  21.       }
  22.     }
  23.     operations {
  24.       operation {
  25.         singleCharacter {
  26.           'b'
  27.         }
  28.         false
  29.       }
  30.     }
  31.   }
  32. }
  33. a(bc) => regex {
  34.   split {
  35.     operations {
  36.       operation {
  37.         singleCharacter {
  38.           'a'
  39.         }
  40.         false
  41.       }
  42.       operation {
  43.         group {
  44.           split {
  45.             operations {
  46.               operation {
  47.                 singleCharacter {
  48.                   'b'
  49.                 }
  50.                 false
  51.               }
  52.               operation {
  53.                 singleCharacter {
  54.                   'c'
  55.                 }
  56.                 false
  57.               }
  58.             }
  59.           }
  60.         }
  61.         false
  62.       }
  63.     }
  64.   }
  65. }
  66. a+b*c? => regex {
  67.   split {
  68.     operations {
  69.       operation {
  70.         singleCharacter {
  71.           'a'
  72.         }
  73.         suffixOperator {
  74.           '+'
  75.         }
  76.       }
  77.       operation {
  78.         singleCharacter {
  79.           'b'
  80.         }
  81.         suffixOperator {
  82.           '*'
  83.         }
  84.       }
  85.       operation {
  86.         singleCharacter {
  87.           'c'
  88.         }
  89.         suffixOperator {
  90.           '?'
  91.         }
  92.       }
  93.     }
  94.   }
  95. }

さて、パーサの方が出来たので次は正規表現用の仮想マシンを作って本格的に解説していきます。(第2回へ続く)

Viewing all articles
Browse latest Browse all 298

Trending Articles