From d6bc7eed0b308cba495724121fb2a643a4bcf400 Mon Sep 17 00:00:00 2001 From: dmiller Date: Tue, 26 Aug 2014 18:53:52 +0000 Subject: [PATCH] Add some code from Patrick for debugging lpeg grammars --- nselib/lpeg-utility.lua | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/nselib/lpeg-utility.lua b/nselib/lpeg-utility.lua index 6c9ea156c..2b77d3b21 100644 --- a/nselib/lpeg-utility.lua +++ b/nselib/lpeg-utility.lua @@ -9,6 +9,7 @@ local assert = assert local lpeg = require "lpeg" local stdnse = require "stdnse" +local pairs = pairs _ENV = {} @@ -88,4 +89,32 @@ function escaped_quote (quot, esc) } end +--- +-- Adds hooks to a grammar to print debugging information +-- +-- Debugging LPeg grammars can be difficult. Calling this function on your +-- grammmar will cause it to print ENTER and LEAVE statements for each rule, as +-- well as position and subject after each successful rule match. +-- +-- For convenience, the modified grammar is returned; a copy is not made +-- though, and the original grammar is modified as well. +-- +-- @param grammar The LPeg grammar to modify +-- @param printer A printf-style formatting printer function to use. +-- Default: stdnse.debug1 +-- @return The modified grammar. +function debug (grammar, printer) + printer = printer or stdnse.debug1 + -- Original code credit: http://lua-users.org/lists/lua-l/2009-10/msg00774.html + for k, p in pairs(grammar) do + local enter = lpeg.Cmt(lpeg.P(true), function(s, p, ...) + printer("ENTER %s", k) return p end) + local leave = lpeg.Cmt(lpeg.P(true), function(s, p, ...) + printer("LEAVE %s", k) return p end) * (lpeg.P("k") - lpeg.P "k"); + grammar[k] = lpeg.Cmt(enter * p + leave, function(s, p, ...) + printer("---%s---", k) printer("pos: %d, [%s]", p, s:sub(1, p-1)) return p end) + end + return grammar +end + return _ENV