Let's Start Functional
English

公開API

エンジンは完成しました.さて,今度はその正面玄関を設計しましょう.この章の主役は新しいアルゴリズムではなく,あらゆるライブラリが直面する問いです.ユーザーに何を見せ,何を幕の裏に置いておくべきか?

ユーザーに必要であるべきもの

前の章の時点で,このライブラリを使うにはimportが4つ必要です(Regex.Core,Regex.Set,Regex.Sugar,Regex.Syntax).どの名前がどのモジュールのものかという知識も必要です.そしてcompileは,不正なパターンに素っ気ないNothingで答えます.何がどこでまずかったのか,ヒントすらなしです.作っている本人たちにはこれで十分ですが,お客さまには失礼というものです.

正面玄関への願いごとリストはこんな感じです:

  • importはひとつ. import Regexで,ユーザーに必要なものがすべてスコープに入ります.

  • 「どこで」を語るエラー. Nothingでもなく,散文の文字列でもなく,位置を運ぶ値です.エディタが問題の文字ちょうどに下線を引けるようにします.

  • みんなが期待する検索.文字列全体のmatchと,アンカーなしのcontainsです.「この中に年号は入ってる?」と聞きたいユーザーの大半は,.*を自分で書きたくないからです.

  • スクリプト向けのワンコールの便利関数.パターン文字列を入れたら判定が出てくるものです.

Red:正面玄関に向けたスペック

regex/tests/src/Spec/Api.idrを,一字一句そのまま:

||| Specs for the `Regex` module — the front door of the library.
|||
||| Users should need exactly one import. `compile` returns a
||| position-carrying error instead of a bare `Nothing`, and
||| `contains` gives the unanchored search everyone expects.
module Spec.Api

import Data.Either
import Harness
import Regex

||| Compile a pattern we trust, then apply a check to it.
withPattern : String -> (Regex -> Bool) -> Bool
withPattern pat check =
  case compile pat of
    Right r => check r
    Left _  => False

export
apiSpecs : List Spec
apiSpecs =
  [ it "compile accepts a well-formed pattern"
      (isRight (compile "(colou?r|gr[ae]y)"))
  , shouldBe "compile reports the position where parsing gave up"
      (compile "ab)")
      (Left (MkCompileError 2 "unexpected character"))
  , shouldBe "an unterminated class fails at its opening bracket"
      (compile "[oops")
      (Left (MkCompileError 0 "unexpected character"))
  , it "match is whole-string"
      (withPattern "\\d+" (\r => match r "123" && not (match r "a123")))
  , it "contains searches anywhere in the input"
      (withPattern "\\d{4}" (\r => contains r "born in 1991, maybe"))
  , it "contains still rejects when nothing matches"
      (withPattern "\\d{4}" (\r => not (contains r "no year here")))
  , shouldBe "test compiles and searches in one call"
      (test "wor\\w+" "hello world") (Right True)
  , shouldBe "test reports non-matches as Right False"
      (test "xyz" "hello world") (Right False)
  , shouldBe "test propagates compile errors"
      (test "[oops" "anything")
      (Left (MkCompileError 0 "unexpected character"))
  ]

このスペックで,Either CompileError Regexにコミットします.成功ならRight,構造化されたエラーならLeftです.そして2つのエラーの期待値をよく見てください."ab)"は位置2,迷い込んだ括弧のところで失敗します."[oops"は位置0,つまり開きブラケットです.意味をなさなかったのは,クラス全体だからです.この2つの数字は,まもなく設計からほとんどタダで転がり出てきます.

make test
Error: Module Regex not found

Spec.Api:10:1--10:13
 06 | module Spec.Api
 07 |
 08 | import Data.Either
 09 | import Harness
 10 | import Regex
      ^^^^^^^^^^^^

Redです.これはコミット225458cです.

Green: Regexモジュール

新しいregex/src/Regex.idrは,ユーザーに何を見せるかを決めるところから始まります:

||| The front door of the library.
|||
||| ```idris example
||| case compile "(colou?r|gr[ae]y)" of
|||   Right r  => contains r "a grey wall"   -- True
|||   Left err => ...
||| ```
|||
||| `import Regex` brings in the AST, the character sets and the
||| sugar (via `import public`), plus the functions below. The
||| parser internals stay behind the curtain.
module Regex

import public Regex.Core
import public Regex.Set
import public Regex.Sugar

import Regex.Parse
import Regex.Syntax

%default total

importが2種類あり,この違いこそAPI設計そのものです.素のimportは,モジュールの名前をここ,つまりRegex.idrの中でだけ見えるようにします.ほかのどこでもなくです.import publicはさらに先へ行って,再エクスポートします.import Regexと書いた人は,それらのモジュールがエクスポートするすべてを,自分でimportしたのと同じように受け取ります.つまりRegex.Core,Regex.Set,Regex.Sugar(AST,文字集合,糖衣構文という,ユーザーがものを組み立てるための道具)は,ひとつのimportと一緒に旅をします.Regex.ParseとRegex.Syntaxは素のimportです.この下では使いますが,satisfyやclassItemの仲間たちがユーザーの名前空間へ漏れ出すことはありません.公開面(public surface)は,importの5行で宣言されているというわけです.

エラーはデータ

||| What went wrong while compiling a pattern, and where.
public export
record CompileError where
  constructor MkCompileError
  ||| Zero-based index into the pattern string.
  position : Nat
  message  : String

export
Show CompileError where
  show e = e.message ++ " at position " ++ show e.position

export
Eq CompileError where
  e1 == e2 = e1.position == e2.position && e1.message == e2.message

エラーを文字列にしたい誘惑はあります("unexpected ) at position 2"のように,文字列は印字が楽なので).しかし文字列は,情報が死にに行く場所です.位置2に下線を引きたいエディタは,エラーメッセージをパースする羽目になります.レコードなら,位置とメッセージは別々のフィールドのままです.Showはそれを描画するひとつの方法にすぎず,エラーそのものではありません.エラーはまずデータ,散文はその次です.

位置のトリック

さて,パターンがどこでまずくなったかを,どうやって知ればいいのでしょうか?嬉しい驚きがあります.実は,もう知っているのです.Regex.Syntaxに小さなエクスポートをひとつ足します:

||| The whole grammar as a single parser, for callers that want to
||| run it themselves (the `Regex` module does, to report positions).
public export
patternParser : Parser Regex
patternParser = alternation

そして正面玄関のcompileは,これをparseではなくrunParserで走らせ,残り物を検分できるようにします:

||| Compile a pattern, or say where it went wrong.
|||
||| The underlying parser never dies halfway — it simply stops
||| consuming. So "how far did it get" is exactly "where the
||| pattern stopped making sense", and that is the position we
||| report.
export
covering
compile : String -> Either CompileError Regex
compile s =
  case runParser patternParser (unpack s) of
    Just (r, [])   => Right r
    Just (_, rest) =>
      Left (MkCompileError (length (unpack s) `minus` length rest)
                           "unexpected character")
    Nothing        => Left (MkCompileError 0 "malformed pattern")

このコンビネータたちは完全にバックトラックするので,文法のいちばん上の規則が途中でクラッシュすることはありません.意味の取れないものにぶつかったら,ただ消費をやめて,手元にあるものを残り物付きで返すだけです.これでエラー位置の特定は算数になります.パーサが消費したのはlength input - length leftover文字です.なのでこの差こそ,パターンが意味をなさなくなった正確なインデックスです.コンビネータにエラー追跡の機構を通す必要も,パーサの状態に位置カウンタを持たせる必要もありません.情報は最初からずっと残り物の中にあって,ただそれを捨てるのをやめればよかった,というわけです.

スペックと突き合わせてみましょう."ab)"では,パーサはabを消費し,)を拒み,")"を残します: 3 − 1 = 位置2です."[oops"では,クラスのパーサが閉じの]を求めて失敗し,バックトラックが[の手前まで巻き戻します.何ひとつ消費されないので,5 − 5 = 位置0,開きブラケットです.期待値2つに,引き算1回です.(Nothingの枝は念には念を,というものです.アトム0個の並びはEpsなので,いま書かれているいちばん上の規則は常に成功します.それでもcaseは網羅的でなければならず,誠実なコードは「ありえない」と断言して片付ける代わりに,そのケースを扱います.compileに明示的なcoveringが付いていることにも注目してください.パーサを呼ぶ以上,全域性についてのパーサの正直さも一緒に旅をします.)

表面の残り

||| Does the regex match the *whole* input? A synonym for
||| `Regex.Core.matches`, under the name users expect.
export
match : Regex -> String -> Bool
match = matches

たった1行の改名ですが,それでも持つ価値があります.APIとは語彙であり,matchはユーザーが最初に当てずっぽうで打つ単語だからです.

||| Does the regex match *somewhere inside* the input?
|||
||| No new machinery: searching for `r` is matching `.*r.*` against
||| the whole string.
export
contains : Regex -> String -> Bool
contains r = matches (cat dotStar (cat r dotStar))
  where
    dotStar : Regex
    dotStar = star (Sym anyChar)

アンカーなしの検索は,新しいエンジン機能のように聞こえます.パターンを入力に沿って滑らせて,開始位置を片っ端から試す必要があるのでは?と思うかもしれませんが,必要ないです.「rのマッチを含む」は,「文字列全体が.*r.*にマッチする」と完全に同じです.何でも,それからパターン,それから何でも,です.dotStarはstar (Sym anyChar),つまり何章も前から持っている部品でできています.この機能は定義なのです.糖衣構文の章の設計の教訓が,APIのレベルでもまだ配当を払い続けています.

||| Compile and search in one call — for the quick, one-shot cases.
export
covering
test : (pattern : String) -> (input : String) -> Either CompileError Bool
test pattern input = map (\r => contains r input) (compile pattern)

testは前半と後半を合成します.どうやって合成しているかを見てください.compile patternはEither CompileError Regexで,Either eはFunctorです.Parserがそうだったのと同じですね.そのmapはRightの値を変換し,Leftは手つかずのまま素通しします.なのでmap (\r => contains r input)はこう読めます.コンパイルが成功したら,その正規表現で検索を走らせる.失敗したら,エラーはそのまま伝わる,です.スペックtest "[oops" "anything"は,caseがひとつも見当たらないのにLeft (MkCompileError 0 ...)を受け取ります.一度学んだインターフェースは,予定していなかった場所に現れ続けるという感じです.

make test
  ...
  ok    compile accepts a well-formed pattern
  ok    compile reports the position where parsing gave up
  ok    an unterminated class fails at its opening bracket
  ok    match is whole-string
  ok    contains searches anywhere in the input
  ok    contains still rejects when nothing matches
  ok    test compiles and searches in one call
  ok    test reports non-matches as Right False
  ok    test propagates compile errors
130/130 passed

これはコミット36533d1です.

書いたものではなく,設計したもの

この章にあるものは,ほとんど何ひとつアルゴリズムではありません.あるのは決断の集まりです:

  • 境界は明示的. import publicとimportの違いが,ユーザーの語彙とこちらの配管とのあいだに線を引きます.いつかパーサを書き直しても,ユーザーのコードが気づくことはありえません.内部への扉は,最初から開いていないのですから.

  • エラーは値. positionフィールドを持つレコードなら,エディタにもREPLにも言語サーバにも食わせられます.整形済みの文字列を食わせられる先はputStrLnだけです.人間のためにShowを実装しつつ,それ以外のみんなのために構造を残しました.

  • 位置は努力ではなく設計から出てきた.コンビネータの失敗が「例外を投げる」ではなく「止まって残り物を返す」だったから,エラー位置は引き算で復元できました.単純な意味論は複利で効きます.2章前の決断が,この章の目玉機能を手渡してくれたのです.

  • 機能は定義のまま. containsは.*r.*,testはmapひとつ,matchは改名です.コアは1ミリも動いていません.

まとめ

  • ユーザーにとっては,いまやimport Regexが話のすべてです.import publicがAST・文字集合・糖衣構文を再エクスポートし,パーサのモジュールは非公開の配管にとどまります.

  • CompileErrorはレコード(位置とメッセージ)です.エラーはまずツールのためのデータであり,人間のための散文はその次だからです.

  • 位置のトリック:バックトラックするパーサは途中で死なず,消費をやめるだけです.length input - length leftoverがそのままエラー位置です."ab)"は2で,"[oops"は0で失敗します.

  • matchはmatchesの改名です.contains rはただの.*r.*で,新しいエンジンコードがゼロのアンカーなし検索です.

  • testはEitherの上にmapします.EitherはParserと同じくFunctorなので,コンパイルエラーはcaseなしでmapを素通りして伝わります.

エンジンに正面玄関ができました!そしてShowやEqやFunctorの仲間たちをずいぶん使い込んできたので,そろそろこの機構ときちんと対面するときです.インターフェースとふたつのモノイドへ進みましょう.