2 Simple Moe configuration file syntax parser.
4 Generally, whitespace and comments are alowed everywhere except in variable names and inside expressions.
5 Also, COMMENT must not contain '\n'.
7 FILE, BLOCK, STATEMENT, OPERATION, SUBTREE, CONDITION, FORMULA, AND, OR and NOT eat any preceding whitespace.
9 The configuration syntax is the following::
12 BLOCK = WS | STATEMENT ( SEP STATEMENT )*
15 WS = ( ' ' | '\t' | '\n' | COMMENT )*
17 COMMENT = re('#[^\n]*\n')
19 STATEMENT = CONDITION | OPERATION | SUBTREE
21 OPERATION = WS VARNAME WS ( '=' | '+=' ) WS EXPRESSION
22 SUBTREE = WS VARNAME WS '{' BLOCK WS '}'
23 CONDITION = WS 'if' FORMULA WS '{' BLOCK WS '}'
25 FORMULA = WS (( EXPRESSION WS ( '!=' | '==' ) WS EXPRESSION ) | '(' AND WS ')' | '(' OR WS ')' | NOT )
26 AND = FORMULA WS 'and' FORMULA
27 OR = FORMULA WS 'or' FORMULA
28 NOT = WS 'not' FORMULA
30 EXPRESSION = '"' ( ECHAR | '{' VARNAME '}' )* '"' | re"'[^'\n]*'" | VARNAME
31 ECHAR = re('([^\{}]|\\|\{|\}|\\n)*')
32 VARNAME = re('[a-zA-Z0-9-_]+(\.[a-zA-Z0-9-_]+)*')
34 .. todo:: should whitespace (incl. '\n') be allowed (almost) everywhere?
35 can comment be anywhere whitespace can?
36 .. note:: ';' or '\n' is currently required even after CONDITION and SUBTREE block
37 .. todo:: change to OPERATION only
38 .. note:: Formula can contain additional/unnecessary parentheses
41 import re, types, itertools, logging as log
44 import moe.config as cf
47 class ConfigSyntaxError(cf.ConfigError):
49 def __init__(self, msg, source='<unknown>', line=None, column=None):
56 return('ConfigSyntaxError %s:%d:%d: %s'%(self.source, self.line, self.column, self.msg))
59 class ConfigParser(object):
76 def __init__(self, s, tree, source='<unknown>', level=0):
77 """Create a config file parser.
78 `s` is either a string, unicode or an open file. File is assumed to be utf-8, string is converted to unicode.
79 `tree` is a ConfigTree to fill the operations into.
80 `source` is an optional name of the file, for debugging and syntax errors.
81 `level` indicates the precedence the operations should have in the ConfigTree
83 self.s = s # Unicode, ascii string or an open file
84 self.buf = u"" # Read-buffer for s file, whole unicode string for s string/unicode
85 if isinstance(self.s, types.StringTypes):
86 self.buf = unicode(self.s)
87 elif (not isinstance(self.s, file)) or self.s.closed:
88 raise TypeError("Expected unicode, str or open file.")
90 self.source = source # Usually filename
93 self.tree = tree # ConfTree to fill
94 self.level = level # level of the parsed operations
95 self.prefix = '' # Prefix of variable name, may begin with '.'
96 self.conditions = [] # Stack of nested conditions, these are chained, so only the last is necessary
97 self.read_ops = [] # List of parsed operations (varname, `Operation`), returned by `self.parse()`
100 "Make sure buf contains at least `l` next characters, return True on succes and False on hitting EOF."
101 if isinstance(self.s, file):
102 self.buf = self.buf[self.bufpos:] + self.s.read(max(l, 1024)).decode('utf8')
104 return len(self.buf) >= self.bufpos + l
106 def peek(self, l = 1):
107 "Peek and return next `l` unicode characters or everything until EOF."
109 return self.buf[self.bufpos:self.bufpos+l]
112 "Peek and compare next `len(s)` characters to `s`. Converts `s` to unicode. False on hitting EOF."
114 return self.peek(len(s)) == s
116 def next(self, l = 1):
117 "Eat and return next `l` unicode characters. Raise exception on EOF."
118 if not self.preread(l):
119 self.syntax_error("Unexpected end of file")
120 s = self.buf[self.bufpos:self.bufpos+l]
128 self.line += s.count('\n')
129 self.column = l - rnl - 1
133 """Compare next `len(s)` characters to `s`. On match, eat them and return True. Otherwise just return False.
134 Converts `s` to unicode. False on hitting EOF."""
142 "Check for end-of-stream."
143 return not self.preread(1)
145 def expect(self, s, msg=None):
146 "Eat and compare next `len(s)` characters to `s`. If not equal, raise an error with `msg`. Unicode."
148 if not self.nexts(s):
149 self.syntax_error(msg or u"%r expected."%(s,))
151 def syntax_error(self, msg, *args):
152 "Raise a syntax error with file/line/column info"
153 raise ConfigSyntaxError(source=self.source, line=self.line, column=self.column, msg=(msg%args))
157 for i in traceback.extract_stack():
161 if n: log.debug(s + n + ' ' + repr(self.peek(15)) + '...')
171 while (not self.eof()) and (not self.peeks(self.c_close)):
175 if self.eof() or self.peeks(self.c_close):
177 if self.line == l0: # No newline skipped in p_WS
180 self.nexts(';') # NOTE: this is weird - can ';' occur anywhere? Or at most once, but only after any p_WS debris?
185 while not self.eof():
186 if self.peek() in self.c_ws:
188 elif self.peeks(self.c_comment):
195 self.expect(self.c_comment, "'#' expected at the beginning of a comment.")
196 while (not self.eof()) and (not self.nexts(self.c_nl)):
199 def p_STATEMENT(self):
202 if self.peeks(self.c_if):
205 # for operation or subtree, read VARNAME
206 varname = self.p_VARNAME()
208 if self.peeks(self.c_open):
209 self.p_SUBTREE(varname)
211 self.p_OPERATION(varname)
213 def p_SUBTREE(self, varname=None):
217 varname = self.p_VARNAME()
219 self.expect(self.c_open)
220 # backup and extend the variable name prefix
222 self.prefix = p + self.c_varname_sep + varname
227 self.expect(self.c_close)
229 def p_OPERATION(self, varname=None):
233 varname = self.p_VARNAME()
235 if self.nexts(self.c_set):
237 elif self.nexts(self.c_append):
240 self.syntax_error('Unknown operation.')
242 exp = self.p_EXPRESSION()
243 vname = (self.prefix+self.c_varname_sep+varname).lstrip(self.c_varname_sep)
244 v = self.tree.lookup(vname)
246 cnd = self.conditions[-1]
249 op = cf.Operation(op, cnd, exp, level=self.level,
250 source="%s:%d:%d"%(self.source, self.line, self.column))
251 # NOTE/WARNING: The last character of operation will be reported in case of error.
253 self.read_ops.append( (vname, op) )
255 def p_CONDITION(self):
258 t = u"condition at %s:%d:%d"%(self.source, self.line, self.column)
259 self.expect(self.c_if)
262 cnd = cf.ConfigCondition(f, text=t, parent=(self.conditions and self.conditions[-1]) or None)
263 self.conditions.append(cnd)
266 self.expect(self.c_open)
269 self.expect(self.c_close)
271 self.conditions.pop()
276 while self.preread(1) and (self.peek().isalnum() or self.peek() in u'-_.'):
277 vnl.append(self.next())
279 if not cf.re_VARNAME.match(vn):
280 self.syntax_error('Invalid variable name %r', vn)
283 def p_EXPRESSION(self):
285 if self.peek() not in '\'"':
286 # Expect a variable name
287 varname = self.p_VARNAME()
288 return cf.ConfigExpression((self.tree.lookup(varname),), varname)
290 # Parse literal expression
293 while not self.peeks(op):
294 exl.append(self.next())
297 return cf.ConfigExpression((s,), s)
298 # Parse expression with variables
301 while not self.peeks(op):
302 exl.append(self.peek())
303 if self.nexts(u'\\'):
306 if c not in u'\\"n' + self.c_open + self.c_close:
307 self.syntax_error('Illeal escape sequence in expression')
313 elif self.nexts(self.c_open):
314 # Parse a variable name in '{}'
315 varname = self.p_VARNAME()
316 self.expect(self.c_close)
318 expr.append(self.tree.lookup(varname))
321 expr.append(self.next())
324 # Concatenate consecutive characters in expr
327 if expr2 and isinstance(expr2[-1], unicode) and isinstance(i, unicode):
328 expr2[-1] = expr2[-1] + i
331 return cf.ConfigExpression(expr2, exs)
336 # Combined logical formula
338 f1 = self.p_FORMULA()
340 if self.nexts(self.c_and):
341 if self.peek(1).isalnum():
342 self.syntax_error('trailing characters after %r', self.c_and)
343 f2 = self.p_FORMULA()
346 return ('AND', f1, f2)
347 elif self.nexts(self.c_or):
348 if self.peek(1).isalnum():
349 self.syntax_error('trailing characters after %r', self.c_or)
350 f2 = self.p_FORMULA()
353 return ('OR', f1, f2)
354 elif self.nexts(u')'):
355 # Only extra parenthes
358 self.syntax_error("Logic operator or ')' expected")
359 elif self.nexts(self.c_not):
360 if self.peek().isalnum():
361 self.syntax_error('trailing characters after %r', self.c_not)
366 # Should be (in)equality condition
367 e1 = self.p_EXPRESSION()
369 if self.nexts(self.c_eq):
371 e2 = self.p_EXPRESSION()
372 return ('==', e1, e2)
373 elif self.nexts(self.c_neq):
375 e2 = self.p_EXPRESSION()
376 return ('!=', e1, e2)
378 self.syntax_error("Comparation operator expected")