Warning: this is an htmlized version!
The original is here, and
the conversion rules are here.
#######
#
# E-scripts on lpeg.
#
# Note 1: use the eev command (defined in eev.el) and the
# ee alias (in my .zshrc) to execute parts of this file.
# Executing this file as a whole makes no sense.
# An introduction to eev can be found here:
#
#   (find-eev-quick-intro)
#   http://angg.twu.net/eev-intros/find-eev-quick-intro.html
#
# Note 2: be VERY careful and make sure you understand what
# you're doing.
#
# Note 3: If you use a shell other than zsh things like |&
# and the for loops may not work.
#
# Note 4: I always run as root.
#
# Note 5: some parts are too old and don't work anymore. Some
# never worked.
#
# Note 6: the definitions for the find-xxxfile commands are on my
# .emacs.
#
# Note 7: if you see a strange command check my .zshrc -- it may
# be defined there as a function or an alias.
#
# Note 8: the sections without dates are always older than the
# sections with dates.
#
# This file is at <http://angg.twu.net/e/lpeg.e>
#           or at <http://angg.twu.net/e/lpeg.e.html>.
#        See also <http://angg.twu.net/emacs.html>,
#                 <http://angg.twu.net/.emacs[.html]>,
#                 <http://angg.twu.net/.zshrc[.html]>,
#                 <http://angg.twu.net/escripts.html>,
#             and <http://angg.twu.net/>.
#
#######




# «.lpeg-debian»		(to "lpeg-debian")
# «.lpeg-source»		(to "lpeg-source")
# «.lpeg-debug-mode»		(to "lpeg-debug-mode")
# «.globals»			(to "globals")
# «.lpeg-quickref»		(to "lpeg-quickref")
# «.re-quickref»		(to "re-quickref")
# «.Re»				(to "Re")
# «.Re-balanced»		(to "Re-balanced")
# «.pegdebug»			(to "pegdebug")
# «.lulpeg»			(to "lulpeg")
# «.lpeglabel»			(to "lpeglabel")
# «.lpegrex»			(to "lpegrex")
# «.lpegrex-json»		(to "lpegrex-json")
# «.lpegrex-tag»		(to "lpegrex-tag")
# «.lpegrex-grammar»		(to "lpegrex-grammar")
# «.folding»			(to "folding")
# «.lpeg-table-captures»	(to "lpeg-table-captures")
# «.tati-2018»			(to "tati-2018")



# (find-es "lua5" "lpeg-quickref")
# (find-es "lua5" "lpeg-re-finch")
# (find-es "lua-intro" "lpeg-re-infix-1")
# (find-es "lua-intro" "lpeg-re-1")

# http://lua-users.org/wiki/LpegTutorial




#####
#
# lpeg-debian
# 2021sep26
#
#####

# «lpeg-debian»  (to ".lpeg-debian")

# (find-status   "lua-lpeg")
# (find-vldifile "lua-lpeg:amd64.list")
# (find-udfile   "lua-lpeg/")
# (find-fline "/usr/share/lua/5.1/re.lua")
# (find-fline "/usr/share/lua/5.2/re.lua")
# (find-fline "/usr/share/lua/5.3/re.lua")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
-- (find-fline "/usr/share/lua/5.1/re.lua")
-- (find-fline "/usr/share/lua/5.1/re.lua" ".__div")

m = require"lpeg"
mm = m
mt = getmetatable(mm.P(0))
PPV(mt)
PPV(mt.__index)

# (find-status   "lua-lpeg-dev")
# (find-vldifile "lua-lpeg-dev:amd64.list")
# (find-udfile   "lua-lpeg-dev/")
# (find-status   "lua-lpeg-patterns")
# (find-vldifile "lua-lpeg-patterns.list")
# (find-udfile   "lua-lpeg-patterns/")




#####
#
# lpeg-source
# 2021sep26
#
#####

# «lpeg-source»  (to ".lpeg-source")
# (to "lpeg-debug-mode")
# http://www.inf.puc-rio.br/~roberto/lpeg/lpeg.html#download
# http://www.inf.puc-rio.br/~roberto/lpeg/lpeg-1.0.2.tar.gz

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
rm -Rv ~/usrc/lpeg-1.0.2/
mkdir  ~/usrc/lpeg-1.0.2/
tar -C ~/usrc/ -xvzf $S/http/www.inf.puc-rio.br/~roberto/lpeg/lpeg-1.0.2.tar.gz
cd     ~/usrc/lpeg-1.0.2/

rm -fv *.o
rm -fv *.so
rm -fv om
# (find-fline "~/emlua/Makefile")
# (find-fline "~/emlua/Makefile" "-I$(LUA_INCLUDE_DIR)")
make LUADIR=/usr/include/lua5.1 COPT="-O2 -DNDEBUG"   |& tee om

# (code-c-d "lpegsrc" "~/usrc/lpeg-1.0.2/")
# (find-lpegsrcfile "")
# (find-lpegsrcfile "lptree.c" "{\"ptree\", lp_printtree},")
# (find-lpegsrcfile "lptree.c" "{\"pcode\", lp_printcode}")
# (find-lpegsrcgrep "grep --color=auto -niH --null -e debug *")
# (find-lpegsrcgrep "grep --color=auto -niH --null -e 'only implemented in debug mode' *")
# (find-lpegsrcgrep "grep --color=auto -nH --null -e lp_divcapture *")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
-- (find-blogme3file "htmlize-utf8.lua")
require "lpeg"
AlphaNumeric = lpeg.R("AZ", "az", "09")
AnchorChar = AlphaNumeric + lpeg.S("!#$%()*+,-./:;=?@^_{|}~")
= AnchorChar:pcode()
= AnchorChar:ptree()



#####
#
# lpeg-debug-mode
# 2022jun30
#
#####

# «lpeg-debug-mode»  (to ".lpeg-debug-mode")
# (to "lpeg-source")
# http://www.inf.puc-rio.br/~roberto/lpeg/lpeg.html#download
# http://www.inf.puc-rio.br/~roberto/lpeg/lpeg-1.0.2.tar.gz
#
# (code-c-d "lpegsrc" "~/usrc/lpeg-1.0.2/")
# (find-lpegsrcfile "")
# (find-lpegsrcfile "makefile")
# (find-lpegsrcfile "makefile" "-I$(LUADIR)")
# (find-fline "~/emlua/Makefile")
# (find-fline "~/emlua/Makefile" "-I$(LUA_INCLUDE_DIR)")

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
rm -Rv ~/usrc/lpeg-1.0.2/
mkdir  ~/usrc/lpeg-1.0.2/
tar -C ~/usrc/ -xvzf $S/http/www.inf.puc-rio.br/~roberto/lpeg/lpeg-1.0.2.tar.gz
cd     ~/usrc/lpeg-1.0.2/

rm -fv *.o
rm -fv *.so
rm -fv om
make LUADIR=/usr/include/lua5.1 COPT="-O2 -DLPEG_DEBUG"   |& tee om

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
-- (find-blogme3file "htmlize-utf8.lua")
Path.prependtocpath "~/usrc/lpeg-1.0.2/?.so"
require "lpeg"
AlphaNumeric = lpeg.R("AZ", "az", "09")
AnchorChar = AlphaNumeric + lpeg.S("!#$%()*+,-./:;=?@^_{|}~")
= AnchorChar:pcode()
= AnchorChar:ptree()




#####
#
# globals
# 2022mar17
#
#####

# «globals»  (to ".globals")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
require "lpeg"
= mapconcat(id, sorted(keys(lpeg)), " ")

B,C,P,R,S,V = lpeg.B,lpeg.C,lpeg.P,lpeg.R,lpeg.S,lpeg.V
Cb,Cc,Cf,Cg = lpeg.Cb,lpeg.Cc,lpeg.Cf,lpeg.Cg
Cp,Cs,Ct    = lpeg.Cp,lpeg.Cs,lpeg.Ct
Carg,Cmt    = lpeg.Carg,lpeg.Cmt




#####
#
# lpeg-quickref
# 2021sep27
#
#####

# «lpeg-quickref»  (to ".lpeg-quickref")
# From: (find-es "lua-intro" "lpeg-quickref")
# http://www.inf.puc-rio.br/~roberto/lpeg.html
# file:///usr/share/doc/lua-lpeg-dev/lpeg.html
# file:///usr/share/doc/lua-lpeg-dev/lpeg.html#grammar
# file:///home/edrx/usrc/lpeg-1.0.2/lpeg.html

lpeg.P(str)    matches str
lpeg.P(0)      matches always
lpeg.P(1)      matches one char (".")
lpeg.P(2)      matches two chars ("..")
lpeg.P(-1)     matches if there isn't another char (end of string)
lpeg.P(-2)     matches if there aren't two more chars
lpeg.P(p)      return the pattern p unmodified
lpeg.P(f)      if f(subj, pos) returns a valid newpos then matches until it
lpeg.P(gra)    matches the first entry (gra[1]) in the grammar gra (a table)
lpeg.V(2)      matches the second entry (gra[2]) in the grammar above this
lpeg.R("az", "AZ") matches any char in ranges - like "[A-Za-z]"
lpeg.S("abd")  matches any char in set - like "[abd]"
#patt          like patt, but without consuming input
-patt          like #patt, but negating the result
p1 * p2        concatenation: "p1p2"
p1 + p2        bounded prioritized choice - roughly like "p1|p2"
p1 - p2        equivalent to -p2 * p1
1 - cset       a char not in cset
patt ^ 0       at least 0 occurrences of patt - like "patt*"
patt ^ 1       at least 1 occurrence  of patt - like "patt+"
patt ^ 2       at least 2 occurrences of patt
patt ^ -1      at most  1 occurrence  of patt - like "patt?"
patt ^ -2      at most  2 occurrences of patt

lpeg.C(patt)   the substring matched by patt (then patt's other captures)
lpeg.Ca(patt)  if patt captures a,f,g,h then h(g(f(a)))   <--- WRONG!
lpeg.Cc(v)     matches the empty string, captures the value v
lpeg.Cp()      matches the empty string, captures the current position
lpeg.Cs(patt)  the substring matched by patt, after substitutions
lpeg.Ct(patt)  all captures made by patt as a table
patt / f       if patt captured a,b,c then f(a, b, c)
patt / "_%2_"  if patt captured "foo" and "bar" then "_bar_"
patt / tbl     if patt captured a and b then tbl[a]

lpeg.Cg(patt, name)    group capture

lpeg.Cf(patt, f)    a folding of the captures from patt
lpeg.Cmt(patt, f)   the returns of f applied to the captures of patt; match-time

  (find-es "lua5" "lpeg.Cmt")
  (find-es "lua5" "lpeg.Cmt-2")




#####
#
# re-quickref
# 2021sep04
#
#####

# «re-quickref»  (to ".re-quickref")
# file:///usr/share/doc/lua-lpeg-dev/lpeg.html
# file:///usr/share/doc/lua-lpeg-dev/lpeg.html#cap-t lpeg.Ct
# file:///usr/share/doc/lua-lpeg-dev/re.html
# http://www.inf.puc-rio.br/~roberto/lpeg/
# http://www.inf.puc-rio.br/~roberto/lpeg/lpeg.html
# http://www.inf.puc-rio.br/~roberto/lpeg/re.html
# (find-angg "LUA/Re.lua" "Re-tests")

 Syntax           Description
 ======           ===========
 ( p )            grouping
 'string'         literal string
 "string"         literal string
 [class]          character class
 .                any character
 %name            pattern defs[name] or a pre-defined pattern
 name             non terminal
 <name>           non terminal
 {}               position capture
 { p }            simple capture
 {: p :}          anonymous group capture
 {:name: p :}     named group capture
 {~ p ~}          substitution capture
 {| p |}          table capture
 =name            back reference
 p ?              optional match
 p *              zero or more repetitions
 p +              one or more repetitions
 p^num            exactly n repetitions
 p^+num           at least n repetitions
 p^-num           at most n repetitions
 p -> 'string'    string capture
 p -> "string"    string capture
 p -> num         numbered capture
 p -> name        function/query/string capture equivalent to p / defs[name]
 p => name        match-time capture equivalent to lpeg.Cmt(p, defs[name])
 p ~> name        fold capture equivalent to lpeg.Cf(p, defs[name])
 & p              and predicate
 ! p              not predicate
 p1 p2            concatenation
 p1 / p2          ordered choice
 (name <- p)+     grammar





#####
#
# Re: a class for testing and learning lpeg.re
# 2021sep27
#
#####

# «Re»  (to ".Re")
# (find-angg "LUA/Re.lua")
# (find-angg "LUA/Re.lua" "arit2-output")



#####
#
# Re-balanced
# 2021oct23
#
#####

# «Re-balanced»  (to ".Re-balanced")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
re = require "re"

gram = [=[
  a <- [^()]+ / ("(" a* ")")
  b <- {~ "("->"" a* ")"->"" ~}
]=]

gram = [=[
  a     <- [^{}]+ / ("{" a* "}")
  ac    <- ("{" { a* } "}")
  act   <- ac -> leantranslate
  actc  <- {~ ""->"{" act ""->"}" ~}
  acc   <- {~ ""->"{" ac  ""->"}" ~}
  tac   <- {~ "\tac"  actc ac     ~}
  lean  <- {~ "\lean" actc        ~}
  tex   <- {~ ""->"$" a   ""->"$" ~}
  all   <- tac / lean / tex
  alle  <- all !.
]=]

defs = { leantranslate = function (str) return "."..str.."." end }

rtg = Re { print = PP, grammar = gram, defs = defs }
rtg:cc 'top <- all'  [=[ foo   ]=]
rtg:cc 'top <- all'  [=[ foo } ]=]
rtg:cc 'top <- alle' [=[ foo } ]=]
rtg:cc 'top <- alle' [=[ foo   ]=]
rtg:cc 'top <- alle' [=[\tac{a}{bc}]=]
rtg:cc 'top <- alle' [=[\tac{a}{b} ]=]
rtg:cc 'top <- alle' [=[\lean{abcd}]=]





#####
#
# PegDebug
# 2014sep23
#
#####

# «pegdebug» (to ".pegdebug")
# https://github.com/pkulchenko/PegDebug
# http://lua-users.org/lists/lua-l/2009-10/msg00774.html
# http://lua-users.org/lists/lua-l/2014-09/msg00119.html
# (find-git-links "https://github.com/pkulchenko/PegDebug" "pegdebug")
# (code-c-d "pegdebug" "~/usrc/PegDebug/")
# (find-pegdebugfile "")
# (find-pegdebugfile "README.md")
# (find-pegdebugfile "src/pegdebug.lua")
# (find-pegdebugfile "src/pegdebug.lua" "grammar[k] = enter * p * eq + leave")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
Path.prepend("path", "~/usrc/PegDebug/src/?.lua")

lpeg     = require('lpeg')
pegdebug = require('pegdebug')

grammar = pegdebug.trace({
  "List",
  NonNumber = lpeg.R('az'),
  Number    = lpeg.R"09"^1 / tonumber,
  List      = lpeg.V("NonNumber")
            + lpeg.V("Number")
            * ("," * lpeg.V("Number"))^0;
})
print(lpeg.match(lpeg.P(grammar), "10,30,43"))

PPPV(grammar)

PPPV {"list"; a=11; b=12}




#####
#
# lulpeg
# 2022mar06
#
#####

# «lulpeg»  (to ".lulpeg")
# https://github.com/pygy/LuLPeg
# (find-git-links "https://github.com/pygy/LuLPeg" "lulpeg")
# (code-c-d "lulpeg" "~/usrc/LuLPeg/")
# (find-lulpegfile "")
# (find-lulpegfile "README.md")
# (find-lulpegfile "lulpeg.lua")
# (find-lulpegfile "src/")
# (find-lulpegfile "src/datastructures.lua")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
-- Path.prepend("path", "~/usrc/LuLPeg/src/?.lua")
Path.prepend   ("path", "~/usrc/LuLPeg/?.lua")
lulpeg  = require "lulpeg"
re      = lulpeg.re
pattern = lulpeg.C(lulpeg.P"A" + "B") ^ 0
print(pattern:match"ABA") --> "A" "B" "A"


# (find-fline "~/LOGS/2022mar05.fennel")




#####
#
# lpeglabel
# 2022mar06
#
#####

# «lpeglabel»  (to ".lpeglabel")
# https://github.com/sqmedeiros/lpeglabel
# (find-git-links "https://github.com/sqmedeiros/lpeglabel" "lpeglabel")
# (code-c-d "lpeglabel" "~/usrc/lpeglabel/")
# (find-lpeglabelfile "")
# (find-lpeglabelfile "README.md")
# (find-lpeglabelfile "makefile")
# (find-sh "locate lua.h | grep '.h$'")
# (find-fline "/usr/include/lua5.1/" "lua.h")
# (find-fline "/usr/include/lua5.2/" "lua.h")
# (find-fline "/usr/include/lua5.3/" "lua.h")

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
cd ~/usrc/lpeglabel/

git clean -dfx
git reset --hard

make LUADIR=/usr/include/lua5.2
# make LUADIR=/usr/include/lua5.3




#####
#
# lpegrex
# 2022mar06
#
#####

# «lpegrex»  (to ".lpegrex")
# (find-angg "LUA/lua50init.lua" "loadlpegrex")
# (find-angg "LUA/LpegRex1.lua")
# (find-angg "LUA/LpegRex2.lua")
# (find-angg "LUA/Lisp3.lua")
# (find-angggrep "grep --color=auto -nH --null -e lpegrex LUA/*.lua")
# https://github.com/edubart/lpegrex
# (find-git-links "https://github.com/edubart/lpegrex" "lpegrex")
# (find-fline "~/LOGS/2022mar05.fennel" "lpegrex")
# (code-pdf-page "lpegrex" "~/tmp/lpegrex.pdf")
# (code-pdf-text "lpegrex" "~/tmp/lpegrex.pdf")
# (code-c-d      "lpegrex" "~/usrc/lpegrex/")
# (find-lpegrexpage)
# (find-lpegrextext)
# (find-lpegrexfile "")
# (find-lpegrexfile "lpegrex.lua")
# (find-lpegrexfile "parsers/")
# (find-lpegrexfile "parsers/csv.lua")
# (find-lpegrexfile "parsers/lua.lua")
# (find-lpegrexfile "parsers/lua.lua" "expror")
# (find-lpegrexfile "tests/")
# (find-lpegrexfile "tests/csv-test.lua")
# (find-lpegrexfile "examples/lua-ast.lua")

* (eepitch-lua52)
* (eepitch-kill)
* (eepitch-lua52)
Path.prepend("path",  "~/usrc/lpeglabel/?.lua")
Path.prepend("cpath", "~/usrc/lpeglabel/?.so")
Path.prepend("path",  "~/usrc/lpegrex/?.lua")
require "lpegrex"
require "tests/csv-test"
arg =  {"/home/edrx/usrc/lpegrex/examples/lua-ast.lua"}
require "examples/lua-ast"

* (eepitch-lua52)
* (eepitch-kill)
* (eepitch-lua52)
Path.prepend("path",  "~/usrc/lpeglabel/?.lua")
Path.prepend("cpath", "~/usrc/lpeglabel/?.so")
Path.prepend("path",  "~/usrc/lpegrex/?.lua")
lpegrex = require "lpegrex"

Grammar = [==[
  top           <-- plusexpr
  plusexpr      <-| timesexpr ({"+"} timesexpr)*
  timesexpr     <-| norp      ({"*"} norp)*
  norp          <-| num     / ("(" plusexpr ")") 
  num           <-- {%d}
]==]

patt = lpegrex.compile(Grammar)
bigstr = "(1+2)*3"
ast, errlabel, errpos = patt:match(bigstr)
PPPV(ast, errlabel, errpos)




#####
#
# lpegrex-json
# 2023jan05
#
#####

# «lpegrex-json»  (to ".lpegrex-json")
# (find-lpegrexfile "README.md" "parsing JSON into an AST")
# (find-lpegrexfile "README.md" "Quick References")

* (eepitch-lua52)
* (eepitch-kill)
* (eepitch-lua52)
-- local lpegrex = require 'lpegrex'
Path.prepend("path",  "~/usrc/lpeglabel/?.lua")
Path.prepend("cpath", "~/usrc/lpeglabel/?.so")
Path.prepend("path",  "~/usrc/lpegrex/?.lua")
lpegrex = require 'lpegrex'

patt = lpegrex.compile([[
Json          <-- SKIP (Object / Array) (!.)^UnexpectedSyntax
Object        <== `{` (Member (`,` @Member)*)? @`}`
Array         <== `[` (Value (`,` @Value)*)? @`]`
Member        <== String `:` @Value
Value         <-- String / Number / Object / Array / Boolean / Null
String        <-- '"' {~ ('\' -> '' @ESCAPE / !'"' .)* ~} @'"' SKIP
Number        <-- {[+-]? (%d+ '.'? %d+? / '.' %d+) ([eE] [+-]? %d+)?} -> tonumber SKIP
Boolean       <-- `false` -> tofalse / `true` -> totrue
Null          <-- `null` -> tonil
ESCAPE        <-- [\/"] / ('b' $8 / 't' $9 / 'n' $10 / 'f' $12 / 'r' $13 / 'u' {%x^4} $16) -> tochar
SKIP          <-- %s*
NAME_SUFFIX   <-- [_%w]+
]])

source = '[{"string":"some\\ntext", "boolean":true, "number":-1.5e+2, "null":null}]'
source = '[{"string":"sometext",  "boolean":"true", "number":-1.5e+2, "null":null}]'

ast, errlabel, errpos = patt:match(source)
if not ast then
  local lineno, colno, line = lpegrex.calcline(source, errpos)
  local colhelp = string.rep(' ', colno-1)..'^'
  error('syntax error: '..lineno..':'..colno..': '..errlabel..
        '\n'..line..'\n'..colhelp)
end
-- `ast` should be a table with the JSON
print('JSON parsed with success!')

PP(ast)
= SynTree.from(ast)


-- {1={1={1="string", 2="some text", "endpos"=24, "pos"=3, "tag"="Member"},
--     2={1="boolean", 2=<true>, "endpos"=40, "pos"=26, "tag"="Member"},
--     3={1="number", 2=-150, "endpos"=58, "pos"=42, "tag"="Member"},
--     4={1="null", "endpos"=71, "pos"=60, "tag"="Member"},
--     "endpos"=72, "pos"=2, "tag"="Object"},
--  "endpos"=73, "pos"=1, "tag"="Array"}



#####
#
# lpegrex: the "tag" field in __options
# 2023jan19
#
#####

# «lpegrex-tag»  (to ".lpegrex-tag")
# (find-lpegrexfile "README.md" "## Quick References")
# (find-lpegrexfile "README.md" "## Quick References" "Capture tagged node")
# (find-lpegrexfile "lpegrex.lua")
# (find-lpegrexfile "lpegrex.lua" "TaggedNodeDefinition =")
# (find-lpegrexfile "lpegrex.lua" "TaggedNodeDefinition =" "makenode")
# (find-lpegrexfile "lpegrex.lua" "local function makenode(")
# (find-lpegrexgrep "grep --color=auto -nH --null -e options * */*")
# (find-lpegrexfile "tests/lpegrex-test.lua" "__options={tag=")

* (eepitch-lua52)
* (eepitch-kill)
* (eepitch-lua52)
Path.prepend("path",  "~/usrc/lpeglabel/?.lua")
Path.prepend("cpath", "~/usrc/lpeglabel/?.so")
Path.prepend("path",  "~/usrc/lpegrex/?.lua")
lpegrex = require 'lpegrex'

c = lpegrex.compile([[
    chunk <-- num
    num:Number <== {%d+} %s*
  ]], {__options={
         tag=function(name, node)
           node.mytag = name
           return node
         end}
      }
  )

PPV(c:match("1234"))



#####
#
# lpegrex-grammar
# 2023jan21
#
#####

# «lpegrex-grammar»  (to ".lpegrex-grammar")
# https://github.com/edubart/lpegrex/issues/4



#####
#
# folding
# 2022mar08
#
#####

# «folding»  (to ".folding")
# http://www.inf.puc-rio.br/~roberto/lpeg/lpeg.html

lpeg.Cf(patt, func)    a folding of the captures from patt

Creates a fold capture. If patt produces a list of captures C1 C2 ...
Cn, this capture will produce the value func(...func(func(C1, C2),
C3)..., Cn), that is, it will fold (or accumulate, or reduce) the
captures from patt using function func.





#####
#
# lpeg-table-captures
# 2022mar21
#
#####

# «lpeg-table-captures»  (to ".lpeg-table-captures")
# file:///usr/share/doc/lua-lpeg-dev/lpeg.html

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
require "lpeg"
= mapconcat(id, sorted(keys(lpeg)), " ")

B,C,P,R,S,V = lpeg.B,lpeg.C,lpeg.P,lpeg.R,lpeg.S,lpeg.V
Cb,Cc,Cf,Cg = lpeg.Cb,lpeg.Cc,lpeg.Cf,lpeg.Cg
Cp,Cs,Ct    = lpeg.Cp,lpeg.Cs,lpeg.Ct
Carg,Cmt    = lpeg.Carg,lpeg.Cmt

=   Cc("AA")                          :match("abcd")
PP((Cc("AA")                    )     :match("abcd"))
PP((Cc("AA") * Cc("BB")         )     :match("abcd"))
PP((Cc("AA") * Cc("BB")         ):Ct():match("abcd"))
PP((Cc("AA") * Cc("BB"):Cg("CC")):Ct():match("abcd"))
PP((Cc("AA") * Cc( 22 ):Cg( 33 )):Ct():match("abcd"))

extrafields = P("")
extrafields = Cc(22):Cg(33) * Cc(44):Cg(55)
PP((Cc("AA") * extrafields):Ct():match("abcd"))

extrafields = P("")
PP((Cc("AA") * extrafields):Ct():match("abcd"))




#####
#
# Processing my chat with Tatiana (2018)
# 2022mar22
#
#####

# «tati-2018»  (to ".tati-2018")
# (find-fline "~/TH/2016-t.blogme")
# (find-fline "~/TH/2016-t.blogme" 331)
# (find-fline "~/TH/2016-t.blogme" 428)
# (find-TH "2018-t")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
require "lpeg"
require "re"

bigstr = ee_readfile "~/TH/2016-t.blogme"
bigstr2 = table.concat(splitlines(bigstr), "\n", 331, 428)
= bigstr2

tdn = re.compile [=[
  top  <- {| "[" time ", " date "] " name ": " |}
  time <- { [0-9:]+ }
  date <- { [0-9/]+ }
  name <- { "Eduardo Ochs" / "Tatiana Pequeno" }
]=]

PP(tdn:match(bigstr2))

patfalas = re.compile [=[
  top    <- {| tdnt * |}
  tdnt   <- {| tdn text |}
  tdn    <- ( "[" time ", " date "] " name ": " )
    time <- { [0-9:]+ }
    date <- { [0-9/]+ }
    name <- { "Eduardo Ochs" / "Tatiana Pequeno" }
  text   <- { ((!tdn) .)* }
]=]

falas = patfalas:match(bigstr2)
PPV(falas)

loadblogme3()
f = function (fala)
    local who = fala[3]:sub(1,1)..": "
    local who2 = BF(who)
    local text = fala[4]:gsub("\n$", "")
    local text2 = text:gsub("\n", "\n"..BR())
    return who2..text2
  end
= f(falas[3])

= mapconcat(f, falas, "\n"..BR())









* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
require "re"
g = function (...) return "("..table.concat({...}, " ")..")" end
f = function (...) local A={...}; return #A==1 and A[1] or g(...) end
T = {}
T["2"] = "(22)"
defs   = { f = f, T = T }
c      = function (pat) return re.compile(pat, defs) end
retest = function (p) return function (s) print(re.match(s, c(p))) end end
retest [[
  top <- asb -> f
  asb <- (b / a asb)
  a   <- [0-9]         -- -> T
  b   <- [A-Z]
]] "012ABa"



retest [[
  e <- e3
  e3 <- (e2 ({"+"} e2)*) -> f
  e2 <- (e1 ({"*"} e1)*) -> f
  e1 <- (e0 ({"^"} e0)*) -> f
  e0 <- "(" e3 ")" / {[0-9]+}
]] "1*2+3^4*5^6+7^8"

--> ((1 * 2) + ((3 ^ 4) * (5 ^ 6)) + (7 ^ 8))



require "re"
setre = function (pat) myre = re.compile

b      = re.compile[[  balanced <- "(" ([^()] / balanced)* ")"  ]]




;; <redzipeg>
;; http://www.romanredz.se/papers/FI2017.pdf
;; (find-fline "$S/http/www.romanredz.se/papers/")
(code-pdf-page "redzipeg" "$S/http/www.romanredz.se/papers/FI2017.pdf")
(code-pdf-text "redzipeg" "$S/http/www.romanredz.se/papers/FI2017.pdf")
;; (find-redzipegpage)
;; (find-redzipegtext)

;; http://www.lua.inf.puc-rio.br/publications/2010-SergioMedeiros-phd-thesis.pdf
(code-pdf-page "medeirosphd" "$S/http/www.lua.inf.puc-rio.br/publications/2010-SergioMedeiros-phd-thesis.pdf")
(code-pdf-text "medeirosphd" "$S/http/www.lua.inf.puc-rio.br/publications/2010-SergioMedeiros-phd-thesis.pdf")
;; (find-medeirosphdpage)
;; (find-medeirosphdtext)


# (find-sh "locate -i medeiros")

https://mail.google.com/mail/ca/u/0/#inbox/FMfcgzGkbDRQNmdrlhDnxrmBKHjmKdfj

https://lists.gnu.org/archive/html/emacs-devel/2021-09/msg02044.html Apparently it has been proven
http://www.romanredz.se/papers/FI2017.pdf
https://lists.csail.mit.edu/mailman/listinfo/peg
https://lists.csail.mit.edu/pipermail/peg/
https://lists.csail.mit.edu/pipermail/peg/2019-August/000771.html

On the Relation between Context-Free Grammars and Parsing Expression Grammars
Fabio Mascarenhas, Sérgio Medeiros, Roberto Ierusalimschy
https://arxiv.org/abs/1304.3177


A Parsing Machine for PEGs
http://www.inf.puc-rio.br/~roberto/docs/ry08-4.pdf

From Regular Expressions to Parsing Expression Grammars
http://www.lua.inf.puc-rio.br/publications/medeiros11regular.pdf



https://www.reddit.com/r/ProgrammingLanguages/comments/a80stl/are_there_any_languages_that_use_a_peg_in_their/






#  Local Variables:
#  coding:               utf-8-unix
#  End: