pegdocs.txt 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. PEG syntax and semantics
  2. ========================
  3. A PEG (Parsing expression grammar) is a simple deterministic grammar, that can
  4. be directly used for parsing. The current implementation has been designed as
  5. a more powerful replacement for regular expressions. UTF-8 is supported.
  6. The notation used for a PEG is similar to that of EBNF:
  7. =============== ============================================================
  8. notation meaning
  9. =============== ============================================================
  10. ``A / ... / Z`` Ordered choice: Apply expressions `A`, ..., `Z`, in this
  11. order, to the text ahead, until one of them succeeds and
  12. possibly consumes some text. Indicate success if one of
  13. expressions succeeded. Otherwise do not consume any text
  14. and indicate failure.
  15. ``A ... Z`` Sequence: Apply expressions `A`, ..., `Z`, in this order,
  16. to consume consecutive portions of the text ahead, as long
  17. as they succeed. Indicate success if all succeeded.
  18. Otherwise do not consume any text and indicate failure.
  19. The sequence's precedence is higher than that of ordered
  20. choice: ``A B / C`` means ``(A B) / Z`` and
  21. not ``A (B / Z)``.
  22. ``(E)`` Grouping: Parenthesis can be used to change
  23. operator priority.
  24. ``{E}`` Capture: Apply expression `E` and store the substring
  25. that matched `E` into a *capture* that can be accessed
  26. after the matching process.
  27. ``$i`` Back reference to the ``i``th capture. ``i`` counts from 1.
  28. ``$`` Anchor: Matches at the end of the input. No character
  29. is consumed. Same as ``!.``.
  30. ``^`` Anchor: Matches at the start of the input. No character
  31. is consumed.
  32. ``&E`` And predicate: Indicate success if expression `E` matches
  33. the text ahead; otherwise indicate failure. Do not consume
  34. any text.
  35. ``!E`` Not predicate: Indicate failure if expression E matches the
  36. text ahead; otherwise indicate success. Do not consume any
  37. text.
  38. ``E+`` One or more: Apply expression `E` repeatedly to match
  39. the text ahead, as long as it succeeds. Consume the matched
  40. text (if any) and indicate success if there was at least
  41. one match. Otherwise indicate failure.
  42. ``E*`` Zero or more: Apply expression `E` repeatedly to match
  43. the text ahead, as long as it succeeds. Consume the matched
  44. text (if any). Always indicate success.
  45. ``E?`` Zero or one: If expression `E` matches the text ahead,
  46. consume it. Always indicate success.
  47. ``[s]`` Character class: If the character ahead appears in the
  48. string `s`, consume it and indicate success. Otherwise
  49. indicate failure.
  50. ``[a-b]`` Character range: If the character ahead is one from the
  51. range `a` through `b`, consume it and indicate success.
  52. Otherwise indicate failure.
  53. ``'s'`` String: If the text ahead is the string `s`, consume it
  54. and indicate success. Otherwise indicate failure.
  55. ``i's'`` String match ignoring case.
  56. ``y's'`` String match ignoring style.
  57. ``v's'`` Verbatim string match: Use this to override a global
  58. ``\i`` or ``\y`` modifier.
  59. ``i$j`` String match ignoring case for back reference.
  60. ``y$j`` String match ignoring style for back reference.
  61. ``v$j`` Verbatim string match for back reference.
  62. ``.`` Any character: If there is a character ahead, consume it
  63. and indicate success. Otherwise (that is, at the end of
  64. input) indicate failure.
  65. ``_`` Any Unicode character: If there is an UTF-8 character
  66. ahead, consume it and indicate success. Otherwise indicate
  67. failure.
  68. ``@E`` Search: Shorthand for ``(!E .)* E``. (Search loop for the
  69. pattern `E`.)
  70. ``{@} E`` Captured Search: Shorthand for ``{(!E .)*} E``. (Search
  71. loop for the pattern `E`.) Everything until and exluding
  72. `E` is captured.
  73. ``@@ E`` Same as ``{@} E``.
  74. ``A <- E`` Rule: Bind the expression `E` to the *nonterminal symbol*
  75. `A`. **Left recursive rules are not possible and crash the
  76. matching engine.**
  77. ``\identifier`` Built-in macro for a longer expression.
  78. ``\ddd`` Character with decimal code *ddd*.
  79. ``\"``, etc Literal ``"``, etc.
  80. =============== ============================================================
  81. Built-in macros
  82. ---------------
  83. ============== ============================================================
  84. macro meaning
  85. ============== ============================================================
  86. ``\d`` any decimal digit: ``[0-9]``
  87. ``\D`` any character that is not a decimal digit: ``[^0-9]``
  88. ``\s`` any whitespace character: ``[ \9-\13]``
  89. ``\S`` any character that is not a whitespace character:
  90. ``[^ \9-\13]``
  91. ``\w`` any "word" character: ``[a-zA-Z0-9_]``
  92. ``\W`` any "non-word" character: ``[^a-zA-Z0-9_]``
  93. ``\a`` same as ``[a-zA-Z]``
  94. ``\A`` same as ``[^a-zA-Z]``
  95. ``\n`` any newline combination: ``\10 / \13\10 / \13``
  96. ``\i`` ignore case for matching; use this at the start of the PEG
  97. ``\y`` ignore style for matching; use this at the start of the PEG
  98. ``\skip`` pat skip pattern *pat* before trying to match other tokens;
  99. this is useful for whitespace skipping, for example:
  100. ``\skip(\s*) {\ident} ':' {\ident}`` matches key value
  101. pairs ignoring whitespace around the ``':'``.
  102. ``\ident`` a standard ASCII identifier: ``[a-zA-Z_][a-zA-Z_0-9]*``
  103. ``\letter`` any Unicode letter
  104. ``\upper`` any Unicode uppercase letter
  105. ``\lower`` any Unicode lowercase letter
  106. ``\title`` any Unicode title letter
  107. ``\white`` any Unicode whitespace character
  108. ============== ============================================================
  109. A backslash followed by a letter is a built-in macro, otherwise it
  110. is used for ordinary escaping:
  111. ============== ============================================================
  112. notation meaning
  113. ============== ============================================================
  114. ``\\`` a single backslash
  115. ``\*`` same as ``'*'``
  116. ``\t`` not a tabulator, but an (unknown) built-in
  117. ============== ============================================================
  118. Supported PEG grammar
  119. ---------------------
  120. The PEG parser implements this grammar (written in PEG syntax)::
  121. # Example grammar of PEG in PEG syntax.
  122. # Comments start with '#'.
  123. # First symbol is the start symbol.
  124. grammar <- rule* / expr
  125. identifier <- [A-Za-z][A-Za-z0-9_]*
  126. charsetchar <- "\\" . / [^\]]
  127. charset <- "[" "^"? (charsetchar ("-" charsetchar)?)+ "]"
  128. stringlit <- identifier? ("\"" ("\\" . / [^"])* "\"" /
  129. "'" ("\\" . / [^'])* "'")
  130. builtin <- "\\" identifier / [^\13\10]
  131. comment <- '#' @ \n
  132. ig <- (\s / comment)* # things to ignore
  133. rule <- identifier \s* "<-" expr ig
  134. identNoArrow <- identifier !(\s* "<-")
  135. prefixOpr <- ig '&' / ig '!' / ig '@' / ig '{@}' / ig '@@'
  136. literal <- ig identifier? '$' [0-9]+ / '$' / '^' /
  137. ig identNoArrow /
  138. ig charset /
  139. ig stringlit /
  140. ig builtin /
  141. ig '.' /
  142. ig '_' /
  143. (ig "(" expr ig ")")
  144. postfixOpr <- ig '?' / ig '*' / ig '+'
  145. primary <- prefixOpr* (literal postfixOpr*)
  146. # Concatenation has higher priority than choice:
  147. # ``a b / c`` means ``(a b) / c``
  148. seqExpr <- primary+
  149. expr <- seqExpr (ig "/" expr)*
  150. **Note**: As a special syntactic extension if the whole PEG is only a single
  151. expression, identifiers are not interpreted as non-terminals, but are
  152. interpreted as verbatim string:
  153. .. code-block:: nim
  154. abc =~ peg"abc" # is true
  155. So it is not necessary to write ``peg" 'abc' "`` in the above example.
  156. Examples
  157. --------
  158. Check if `s` matches Nim's "while" keyword:
  159. .. code-block:: nim
  160. s =~ peg" y'while'"
  161. Exchange (key, val)-pairs:
  162. .. code-block:: nim
  163. "key: val; key2: val2".replacef(peg"{\ident} \s* ':' \s* {\ident}", "$2: $1")
  164. Determine the ``#include``'ed files of a C file:
  165. .. code-block:: nim
  166. for line in lines("myfile.c"):
  167. if line =~ peg"""s <- ws '#include' ws '"' {[^"]+} '"' ws
  168. comment <- '/*' @ '*/' / '//' .*
  169. ws <- (comment / \s+)* """:
  170. echo matches[0]
  171. PEG vs regular expression
  172. -------------------------
  173. As a regular expression ``\[.*\]`` matches the longest possible text between
  174. ``'['`` and ``']'``. As a PEG it never matches anything, because a PEG is
  175. deterministic: ``.*`` consumes the rest of the input, so ``\]`` never matches.
  176. As a PEG this needs to be written as: ``\[ ( !\] . )* \]`` (or ``\[ @ \]``).
  177. Note that the regular expression does not behave as intended either: in the
  178. example ``*`` should not be greedy, so ``\[.*?\]`` should be used instead.
  179. PEG construction
  180. ----------------
  181. There are two ways to construct a PEG in Nim code:
  182. (1) Parsing a string into an AST which consists of `Peg` nodes with the
  183. `peg` proc.
  184. (2) Constructing the AST directly with proc calls. This method does not
  185. support constructing rules, only simple expressions and is not as
  186. convenient. Its only advantage is that it does not pull in the whole PEG
  187. parser into your executable.