简单字符串

作者:Aaron Sherman

一个简单的解析器,可以处理带反斜杠转义引号的引号字符串,并使用单引号或双引号进行界定。

源代码:SimpleStrings.pm

use v6;

grammar String::Simple::Grammar {
    rule TOP {^ <string> $}
    # Note for now, {} gets around a rakudo binding issue
    token string { <quote> {} <quotebody($<quote>)> $<quote> }
    token quote { '"' | "'" }
    token quotebody($quote) { ( <escaped($quote)> | <!before $quote> . )* }
    token escaped($quote) { '\\' ( $quote | '\\' ) }
}

# The parse-tree builder ultimately returns the string itself.
class String::Simple::Actions {
    method TOP($/) { make $<string>.made }
    method string($/) { make $<quotebody>.made }
    method quotebody($/) { make [~] $0.map: {.<escaped>.made or ~$_} }
    method escaped($/) { make ~$0 }
}