Module:Sandbox/Thundercraft5/Query

local class = require "Module:Class" local table = require "Module:Table"

local p = {} local Query = class "Query" local Parser = class "Parser"

function Query.prototype:constructor(t) self.table = t end

function Query.prototype:execute(query) self.parsed = Parser(query):parse mw.logObject(self.parsed) end

function Parser.prototype:constructor(query) self.query = query self.len = #query self.pos = 0 self.tokens = {} self.current = nil self.isField = false self.count = 0 end

function Parser.prototype:parse while self.pos < self.len do		self.count = self.count + 1 if self.pos == self.len then if self.isField then self:syntaxError("Unclosed '['") end end if self:peekNext "%s+" then self:moveNext "%s+" elseif self.isField and self:peekNext "[a-zA-Z][a-zA-Z%d]*" then table.push(self.tokens, { type = "field", value = self:moveNext "[a-zA-Z][a-zA-Z%d]*" }) elseif self:peekNext "[a-zA-Z][a-zA-Z%d]*" and not self.isField then table.push(self.tokens, { type = "identifier", value = self:moveNext "[a-zA-Z][a-zA-Z%d]*" }) elseif self:peekNext "%[" then self.isField = true self:moveNext "%[" elseif self:peekNext "%]" then self.isField = false self:moveNext "%]" else self:syntaxError "Unexpected string" end end return self.tokens end

function Parser.prototype:syntaxError(msg, level) error((Syntax error in query at character %d: %s):format(self.pos, msg), level or 3) end

function Parser.prototype:moveNext(pattern) local start, stop = self:peekNext(pattern) local oldPos = self.pos self.pos = oldPos + stop self.current = self.query:sub(start, stop) return self.current end

function Parser.prototype:peekNext(pattern) return self.query:sub(self.pos, self.len):find(pattern) end

function p.test return Query{ data = "Test" }:execute "data[1]" end

return p