summaryrefslogtreecommitdiff
path: root/common.lua
blob: 2c68aee2dffa0d5a8b840055ca6f18544f72d252 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
local lpeg = require "lpeg"

local string        = require "string"
local stringformat  = string.format

local verboselvl    = 0

local mk_out = function (stream, threshold, newlinep)
  local out = io.stdout
  if stream == "err" or stream == "stderr" then out = io.stderr end
  return function (...)
    if verboselvl >= threshold then
      local ok, msg = pcall (stringformat, ...)
      if ok then
        out:write (msg)
        if newlinep == true then out:write "\n" end
      ---else silently ignore
      end
    end
  end
end

local set_verbosity = function (n) verboselvl = n end

local trim_whitespace
local unescape_string
local internalize_value
do
  local P                 = lpeg.P
  local S                 = lpeg.S
  local Cs                = lpeg.Cs
  local p_ws_char         = S" \n\r\t\v"
  local p_ws              = p_ws_char^1
  local p_ws_trailing     = p_ws * P (-1)
  local p_ws_drop         = Cs (  (p_ws^-1 / "")
                                * (1 - p_ws_trailing)^0
                                * (p_ws^-1 * P (-1) / ""))

  local p_escape_char     = (P"\\n" / "\n")
                          + (P"\\r" / "\r")
                          + (P"\\t" / "\t")
                          + (P"\\v" / "\v")
  local p_unescape        = Cs ((p_escape_char + 1)^0)

  --[[--

    rfc2445, sec. 4.1.2: Properties can have multiple values, separated by a
    literal comma, thus text commas are escaped.

  --]]--
  local p_value_char      = (  p_escape_char
                             + P"\\," / ","
                             + P"," / "\n")
  local p_value           = Cs ((p_value_char + 1)^0)

  local lpegmatch         = lpeg.match

  trim_whitespace = function (s) return lpegmatch (p_ws_drop , s) end
  unescape_string = function (s) return lpegmatch (p_unescape, s) end
  internalize_value = function (s) return lpegmatch (p_value, s) end
end

return
  { println               = mk_out ("stdout", 0, true)
  , errorln               = mk_out ("stderr", 0, true)
  , noiseln               = mk_out ("stderr", 1, true)
  , debugln               = mk_out ("stderr", 2, true)
  , set_verbosity         = set_verbosity
  , trim_whitespace       = trim_whitespace
  , unescape_string       = unescape_string
  , internalize_value     = internalize_value
  }