diff --git a/moonscript/parse.lua b/moonscript/parse.lua index f8a1a44..4f7ec89 100644 --- a/moonscript/parse.lua +++ b/moonscript/parse.lua @@ -8,6 +8,7 @@ local util = require"moonscript.util" local data = require"moonscript.data" local types = require"moonscript.types" local literals = require "moonscript.parse.literals" +local parse_util = require "moonscript.parse.util" local ntype = types.ntype local trim = util.trim @@ -37,23 +38,9 @@ local Shebang = literals.Shebang local Name = Space * _Name Num = Space * (Num / function(value) return {"number", value} end) -local function count_indent(str) - local sum = 0 - for v in str:gmatch("[\t ]") do - if v == ' ' then sum = sum + 1 end - if v == '\t' then sum = sum + 4 end - end - return sum -end - -local Indent = C(S"\t "^0) / count_indent - --- can't have P(false) because it causes preceding patterns not to run -local Cut = P(function() return false end) - -local function ensure(patt, finally) - return patt * finally + finally * Cut -end +local Indent = parse_util.Indent +local Cut = parse_util.Cut +local ensure = parse_util.ensure local function extract_line(str, start_pos) str = str:sub(start_pos) diff --git a/moonscript/parse/util.lua b/moonscript/parse/util.lua new file mode 100644 index 0000000..81a4ca9 --- /dev/null +++ b/moonscript/parse/util.lua @@ -0,0 +1,31 @@ +local P, C, S +do + local _obj_0 = require("lpeg") + P, C, S = _obj_0.P, _obj_0.C, _obj_0.S +end +local Indent = C(S("\t ") ^ 0) / function(str) + do + local sum = 0 + for v in str:gmatch("[\t ]") do + local _exp_0 = v + if " " == _exp_0 then + sum = sum + 1 + elseif "\t" == _exp_0 then + sum = sum + 4 + end + end + return sum + end +end +local Cut = P(function() + return false +end) +local ensure +ensure = function(patt, finally) + return patt * finally + finally * Cut +end +return { + Indent = Indent, + Cut = Cut, + ensure = ensure +} diff --git a/moonscript/parse/util.moon b/moonscript/parse/util.moon new file mode 100644 index 0000000..f10dda9 --- /dev/null +++ b/moonscript/parse/util.moon @@ -0,0 +1,23 @@ + +import P, C, S from require "lpeg" + +-- captures an indentation, returns indent depth +Indent = C(S"\t "^0) / (str) -> + with sum = 0 + for v in str\gmatch "[\t ]" + switch v + when " " + sum += 1 + when "\t" + sum += 4 + + +-- causes pattern in progress to be rejected +-- can't have P(false) because it causes preceding patterns not to run +Cut = P -> false + +-- ensures finally runs regardless of whether pattern fails or passes +ensure = (patt, finally) -> + patt * finally + finally * Cut + +{ :Indent, :Cut, :ensure }