5 Simple Moe configuration file syntax parser.
7 Generally, whitespace and comments are alowed everywhere except in variable names and inside expressions.
8 Also, COMMENT must not contain '\n'.
10 FILE, BLOCK, STATEMENT, OPERATION, SUBTREE, CONDITION, FORMULA, AND, OR and NOT eat any preceding whitespace.
12 The configuration syntax is the following::
15 BLOCK = WS | STATEMENT ( SEP STATEMENT )*
18 WS = ( ' ' | '\t' | '\n' | COMMENT )*
20 COMMENT = re('#[^\n]*\n')
22 STATEMENT = CONDITION | OPERATION | SUBTREE
24 OPERATION = WS VARNAME WS ( '=' | '+=' ) WS EXPRESSION
25 SUBTREE = WS VARNAME WS '{' BLOCK WS '}'
26 CONDITION = WS 'if' FORMULA WS '{' BLOCK WS '}'
28 FORMULA = WS (( EXPRESSION WS ( '!=' | '==' ) WS EXPRESSION ) | '(' AND WS ')' | '(' OR WS ')' | NOT )
29 AND = FORMULA WS 'and' FORMULA
30 OR = FORMULA WS 'or' FORMULA
31 NOT = WS 'not' FORMULA
33 EXPRESSION = '"' ( ECHAR | '{' VARNAME '}' )* '"' | re"'[^'\n]*'" | VARNAME
34 ECHAR = re('([^\{}]|\\|\{|\}|\\n)*')
35 VARNAME = re('[a-zA-Z0-9-_]+(\.[a-zA-Z0-9-_]+)*')
37 .. todo:: should whitespace (incl. '\n') be allowed (almost) everywhere?
38 can comment be anywhere whitespace can?
39 .. note:: ';' or '\n' is currently required even after CONDITION and SUBTREE block
40 .. todo:: change to OPERATION only
41 .. note:: Formula can contain additional/unnecessary parentheses
44 import re, types, itertools, logging as log
47 import moe.config as cf
50 class ConfigSyntaxError(cf.ConfigError):
52 def __init__(self, msg, source='<unknown>', line=None, column=None):
59 return('ConfigSyntaxError %s:%d:%d: %s'%(self.source, self.line, self.column, self.msg))
62 class ConfigParser(object):
79 def __init__(self, s, tree, source='<unknown>', level=0):
80 """Create a config file parser.
81 `s` is either a string, unicode or an open file. File is assumed to be utf-8, string is converted to unicode.
82 `tree` is a ConfigTree to fill the operations into.
83 `source` is an optional name of the file, for debugging and syntax errors.
84 `level` indicates the precedence the operations should have in the ConfigTree
86 self.s = s # Unicode, ascii string or an open file
87 self.buf = u"" # Read-buffer for s file, whole unicode string for s string/unicode
88 if isinstance(self.s, types.StringTypes):
89 self.buf = unicode(self.s)
90 elif (not isinstance(self.s, file)) or self.s.closed:
91 raise TypeError("Expected unicode, str or open file.")
93 self.source = source # Usually filename
96 self.tree = tree # ConfTree to fill
97 self.level = level # level of the parsed operations
98 self.prefix = '' # Prefix of variable name, may begin with '.'
99 self.conditions = [] # Stack of nested conditions, these are chained, so only the last is necessary
100 self.read_ops = [] # List of parsed operations (varname, `Operation`), returned by `self.parse()`
102 def preread(self, l):
103 "Make sure buf contains at least `l` next characters, return True on succes and False on hitting EOF."
104 if isinstance(self.s, file):
105 self.buf = self.buf[self.bufpos:] + self.s.read(max(l, 1024)).decode('utf8')
107 return len(self.buf) >= self.bufpos + l
109 def peek(self, l = 1):
110 "Peek and return next `l` unicode characters or everything until EOF."
112 return self.buf[self.bufpos:self.bufpos+l]
115 "Peek and compare next `len(s)` characters to `s`. Converts `s` to unicode. False on hitting EOF."
117 return self.peek(len(s)) == s
119 def next(self, l = 1):
120 "Eat and return next `l` unicode characters. Raise exception on EOF."
121 if not self.preread(l):
122 self.syntax_error("Unexpected end of file")
123 s = self.buf[self.bufpos:self.bufpos+l]
131 self.line += s.count('\n')
132 self.column = l - rnl - 1
136 """Compare next `len(s)` characters to `s`. On match, eat them and return True. Otherwise just return False.
137 Converts `s` to unicode. False on hitting EOF."""
145 "Check for end-of-stream."
146 return not self.preread(1)
148 def expect(self, s, msg=None):
149 "Eat and compare next `len(s)` characters to `s`. If not equal, raise an error with `msg`. Unicode."
151 if not self.nexts(s):
152 self.syntax_error(msg or u"%r expected."%(s,))
154 def syntax_error(self, msg, *args):
155 "Raise a syntax error with file/line/column info"
156 raise ConfigSyntaxError(source=self.source, line=self.line, column=self.column, msg=(msg%args))
160 for i in traceback.extract_stack():
164 if n: log.debug(s + n + ' ' + repr(self.peek(15)) + '...')
174 while (not self.eof()) and (not self.peeks(self.c_close)):
178 if self.eof() or self.peeks(self.c_close):
180 if self.line == l0: # No newline skipped in p_WS
183 self.nexts(';') # NOTE: this is weird - can ';' occur anywhere? Or at most once, but only after any p_WS debris?
188 while not self.eof():
189 if self.peek() in self.c_ws:
191 elif self.peeks(self.c_comment):
198 self.expect(self.c_comment, "'#' expected at the beginning of a comment.")
199 while (not self.eof()) and (not self.nexts(self.c_nl)):
202 def p_STATEMENT(self):
205 if self.peeks(self.c_if):
208 # for operation or subtree, read VARNAME
209 varname = self.p_VARNAME()
211 if self.peeks(self.c_open):
212 self.p_SUBTREE(varname)
214 self.p_OPERATION(varname)
216 def p_SUBTREE(self, varname=None):
220 varname = self.p_VARNAME()
222 self.expect(self.c_open)
223 # backup and extend the variable name prefix
225 self.prefix = p + self.c_varname_sep + varname
230 self.expect(self.c_close)
232 def p_OPERATION(self, varname=None):
236 varname = self.p_VARNAME()
238 if self.nexts(self.c_set):
240 elif self.nexts(self.c_append):
243 self.syntax_error('Unknown operation.')
245 exp = self.p_EXPRESSION()
246 vname = (self.prefix+self.c_varname_sep+varname).lstrip(self.c_varname_sep)
247 v = self.tree.lookup(vname)
249 cnd = self.conditions[-1]
252 op = cf.Operation(op, cnd, exp, level=self.level,
253 source="%s:%d:%d"%(self.source, self.line, self.column))
254 # NOTE/WARNING: The last character of operation will be reported in case of error.
256 self.read_ops.append( (vname, op) )
258 def p_CONDITION(self):
261 t = u"condition at %s:%d:%d"%(self.source, self.line, self.column)
262 self.expect(self.c_if)
265 cnd = cf.ConfigCondition(f, text=t, parent=(self.conditions and self.conditions[-1]) or None)
266 self.conditions.append(cnd)
269 self.expect(self.c_open)
272 self.expect(self.c_close)
274 self.conditions.pop()
279 while self.preread(1) and (self.peek().isalnum() or self.peek() in u'-_.'):
280 vnl.append(self.next())
282 if not cf.re_VARNAME.match(vn):
283 self.syntax_error('Invalid variable name %r', vn)
286 def p_EXPRESSION(self):
288 if self.peek() not in '\'"':
289 # Expect a variable name
290 varname = self.p_VARNAME()
291 return cf.ConfigExpression((self.tree.lookup(varname),), varname)
293 # Parse literal expression
296 while not self.peeks(op):
297 exl.append(self.next())
300 return cf.ConfigExpression((s,), s)
301 # Parse expression with variables
304 while not self.peeks(op):
305 exl.append(self.peek())
306 if self.nexts(u'\\'):
309 if c not in u'\\"n' + self.c_open + self.c_close:
310 self.syntax_error('Illeal escape sequence in expression')
316 elif self.nexts(self.c_open):
317 # Parse a variable name in '{}'
318 varname = self.p_VARNAME()
319 self.expect(self.c_close)
321 expr.append(self.tree.lookup(varname))
324 expr.append(self.next())
327 # Concatenate consecutive characters in expr
330 if expr2 and isinstance(expr2[-1], unicode) and isinstance(i, unicode):
331 expr2[-1] = expr2[-1] + i
334 return cf.ConfigExpression(expr2, exs)
339 # Combined logical formula
341 f1 = self.p_FORMULA()
343 if self.nexts(self.c_and):
344 if self.peek(1).isalnum():
345 self.syntax_error('trailing characters after %r', self.c_and)
346 f2 = self.p_FORMULA()
349 return ('AND', f1, f2)
350 elif self.nexts(self.c_or):
351 if self.peek(1).isalnum():
352 self.syntax_error('trailing characters after %r', self.c_or)
353 f2 = self.p_FORMULA()
356 return ('OR', f1, f2)
357 elif self.nexts(u')'):
358 # Only extra parenthes
361 self.syntax_error("Logic operator or ')' expected")
362 elif self.nexts(self.c_not):
363 if self.peek().isalnum():
364 self.syntax_error('trailing characters after %r', self.c_not)
369 # Should be (in)equality condition
370 e1 = self.p_EXPRESSION()
372 if self.nexts(self.c_eq):
374 e2 = self.p_EXPRESSION()
375 return ('==', e1, e2)
376 elif self.nexts(self.c_neq):
378 e2 = self.p_EXPRESSION()
379 return ('!=', e1, e2)
381 self.syntax_error("Comparation operator expected")