2 -- Copyright (C) 2008-2009 Matthew Wild
3 -- Copyright (C) 2008-2009 Waqas Hussain
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
13 local function read(expected)
16 ch = last; last = nil;
17 else ch = file:read(1); end
18 if expected and ch ~= expected then error("expected: "..expected.."; got: "..(ch or "nil")); end
21 local function pushback(ch)
22 if last then error(); end
26 if not last then last = read(); end
30 local _A, _a, _Z, _z, _0, _9, __, _space = string.byte("AaZz09_ ", 1, 8);
31 local function isAlpha(ch)
32 ch = string.byte(ch) or 0;
33 return (ch >= _A and ch <= _Z) or (ch >= _a and ch <= _z);
35 local function isNumeric(ch)
36 ch = string.byte(ch) or 0;
37 return (ch >= _0 and ch <= _9);
39 local function isVar(ch)
40 ch = string.byte(ch) or 0;
41 return (ch >= _A and ch <= _Z) or (ch >= _a and ch <= _z) or (ch >= _0 and ch <= _9) or ch == __;
43 local function isSpace(ch)
44 ch = string.byte(ch) or "x";
48 local function readString()
49 read("\""); -- skip quote
54 if ch == "\"" and not slash then break; end
57 str = str:gsub("\\.", {["\\b"]="\b", ["\\d"]="\d", ["\\e"]="\e", ["\\f"]="\f", ["\\n"]="\n", ["\\r"]="\r", ["\\s"]="\s", ["\\t"]="\t", ["\\v"]="\v", ["\\\""]="\"", ["\\'"]="'", ["\\\\"]="\\"});
60 local function readSpecialString()
61 read("<"); read("<"); -- read <<
63 if peek() == "\"" then
65 elseif peek() ~= ">" then
68 read(">"); read(">"); -- read >>
71 local function readVar()
73 while isVar(peek()) do
78 local function readNumber()
80 while isNumeric(peek()) do
86 local function readTuple()
88 read(); -- read { or [
90 local item = readItem();
91 if not item then break; end
92 table.insert(t, item);
94 read(); -- read } or ]
99 if ch == nil then return nil end
100 if ch == "{" or ch == "[" then
102 elseif isAlpha(ch) then
104 elseif isNumeric(ch) then
106 elseif ch == "\"" then
108 elseif ch == "<" then
109 return readSpecialString();
110 elseif isSpace(ch) or ch == "," or ch == "|" then
114 --print("Unknown char: "..ch);
118 local function readChunk()
119 local x = readItem();
120 if x then read("."); end
123 local function readFile(filename)
124 file = io.open(filename);
125 if not file then error("File not found: "..filename); os.exit(0); end
127 local x = readChunk();
128 if not x and peek() then error("Invalid char: "..peek()); end
135 function parseFile(file)
136 return readFile(file);