| 1 |
from __future__ import absolute_import, print_function, unicode_literals |
| 2 |
|
| 3 |
import re |
| 4 |
import json as json |
| 5 |
from .shared import JSONTemplateError, TemplateError, DeleteMarker, string, to_str |
| 6 |
from . import shared |
| 7 |
from .six import viewitems |
| 8 |
from .parser import Parser, Tokenizer |
| 9 |
from .interpreter import Interpreter |
| 10 |
import functools |
| 11 |
from inspect import isfunction, isbuiltin |
| 12 |
|
| 13 |
operators = {} |
| 14 |
IDENTIFIER_RE = re.compile(r'[a-zA-Z_][a-zA-Z0-9_]*$') |
| 15 |
|
| 16 |
|
| 17 |
class SyntaxError(TemplateError): |
| 18 |
|
| 19 |
@classmethod |
| 20 |
def unexpected(cls, got): |
| 21 |
return cls('Found: {} token, expected one of: !=, &&, (, *, **, +, -, ., /, <, <=, ==, >, >=, [, in,' |
| 22 |
' ||'.format(got.value)) |
| 23 |
|
| 24 |
|
| 25 |
def operator(name): |
| 26 |
def wrap(fn): |
| 27 |
operators[name] = fn |
| 28 |
return fn |
| 29 |
return wrap |
| 30 |
|
| 31 |
|
| 32 |
tokenizer = Tokenizer( |
| 33 |
'\\s+', |
| 34 |
{ |
| 35 |
'number': '[0-9]+(?:\\.[0-9]+)?', |
| 36 |
'identifier': '[a-zA-Z_][a-zA-Z_0-9]*', |
| 37 |
'string': '\'[^\']*\'|"[^"]*"', |
| 38 |
# avoid matching these as prefixes of identifiers e.g., `insinutations` |
| 39 |
'true': 'true(?![a-zA-Z_0-9])', |
| 40 |
'false': 'false(?![a-zA-Z_0-9])', |
| 41 |
'in': 'in(?![a-zA-Z_0-9])', |
| 42 |
'null': 'null(?![a-zA-Z_0-9])', |
| 43 |
}, |
| 44 |
[ |
| 45 |
'**', '+', '-', '*', '/', '[', ']', '.', '(', ')', '{', '}', ':', ',', |
| 46 |
'>=', '<=', '<', '>', '==', '!=', '!', '&&', '||', 'true', 'false', 'in', |
| 47 |
'null', 'number', 'identifier', 'string', |
| 48 |
], |
| 49 |
) |
| 50 |
|
| 51 |
|
| 52 |
def parse(source, context): |
| 53 |
parser = Parser(source, tokenizer) |
| 54 |
tree = parser.parse() |
| 55 |
if parser.current_token is not None: |
| 56 |
raise SyntaxError.unexpected(parser.current_token) |
| 57 |
|
| 58 |
interp = Interpreter(context) |
| 59 |
result = interp.interpret(tree) |
| 60 |
return result |
| 61 |
|
| 62 |
|
| 63 |
def parse_until_terminator(source, context, terminator): |
| 64 |
parser = Parser(source, tokenizer) |
| 65 |
tree = parser.parse() |
| 66 |
if parser.current_token.kind != terminator: |
| 67 |
raise SyntaxError.unexpected(parser.current_token) |
| 68 |
interp = Interpreter(context) |
| 69 |
result = interp.interpret(tree) |
| 70 |
return result, parser.current_token.start |
| 71 |
|
| 72 |
|
| 73 |
_interpolation_start_re = re.compile(r'\$?\${') |
| 74 |
|
| 75 |
|
| 76 |
def interpolate(string, context): |
| 77 |
mo = _interpolation_start_re.search(string) |
| 78 |
if not mo: |
| 79 |
return string |
| 80 |
|
| 81 |
result = [] |
| 82 |
|
| 83 |
while True: |
| 84 |
result.append(string[:mo.start()]) |
| 85 |
if mo.group() != '$${': |
| 86 |
string = string[mo.end():] |
| 87 |
parsed, offset = parse_until_terminator(string, context, '}') |
| 88 |
if isinstance(parsed, (list, dict)): |
| 89 |
raise TemplateError( |
| 90 |
"interpolation of '{}' produced an array or object".format(string[:offset])) |
| 91 |
if parsed is None: |
| 92 |
result.append("") |
| 93 |
else: |
| 94 |
result.append(to_str(parsed)) |
| 95 |
string = string[offset + 1:] |
| 96 |
else: # found `$${` |
| 97 |
result.append('${') |
| 98 |
string = string[mo.end():] |
| 99 |
|
| 100 |
mo = _interpolation_start_re.search(string) |
| 101 |
if not mo: |
| 102 |
result.append(string) |
| 103 |
break |
| 104 |
return ''.join(result) |
| 105 |
|
| 106 |
|
| 107 |
def checkUndefinedProperties(template, allowed): |
| 108 |
unknownKeys = [] |
| 109 |
combined = "|".join(allowed) + "$" |
| 110 |
unknownKeys = [key for key in sorted(template) |
| 111 |
if not re.match(combined, key)] |
| 112 |
if unknownKeys: |
| 113 |
raise TemplateError(allowed[0].replace('\\', '') + |
| 114 |
" has undefined properties: " + " ".join(unknownKeys)) |
| 115 |
|
| 116 |
|
| 117 |
@operator('$eval') |
| 118 |
def eval(template, context): |
| 119 |
checkUndefinedProperties(template, [r'\$eval']) |
| 120 |
if not isinstance(template['$eval'], string): |
| 121 |
raise TemplateError("$eval must be given a string expression") |
| 122 |
return parse(template['$eval'], context) |
| 123 |
|
| 124 |
|
| 125 |
@operator('$flatten') |
| 126 |
def flatten(template, context): |
| 127 |
checkUndefinedProperties(template, [r'\$flatten']) |
| 128 |
value = renderValue(template['$flatten'], context) |
| 129 |
if not isinstance(value, list): |
| 130 |
raise TemplateError('$flatten value must evaluate to an array') |
| 131 |
|
| 132 |
def gen(): |
| 133 |
for e in value: |
| 134 |
if isinstance(e, list): |
| 135 |
for e2 in e: |
| 136 |
yield e2 |
| 137 |
else: |
| 138 |
yield e |
| 139 |
return list(gen()) |
| 140 |
|
| 141 |
|
| 142 |
@operator('$flattenDeep') |
| 143 |
def flattenDeep(template, context): |
| 144 |
checkUndefinedProperties(template, [r'\$flattenDeep']) |
| 145 |
value = renderValue(template['$flattenDeep'], context) |
| 146 |
if not isinstance(value, list): |
| 147 |
raise TemplateError('$flattenDeep value must evaluate to an array') |
| 148 |
|
| 149 |
def gen(value): |
| 150 |
if isinstance(value, list): |
| 151 |
for e in value: |
| 152 |
for sub in gen(e): |
| 153 |
yield sub |
| 154 |
else: |
| 155 |
yield value |
| 156 |
|
| 157 |
return list(gen(value)) |
| 158 |
|
| 159 |
|
| 160 |
@operator('$fromNow') |
| 161 |
def fromNow(template, context): |
| 162 |
checkUndefinedProperties(template, [r'\$fromNow', 'from']) |
| 163 |
offset = renderValue(template['$fromNow'], context) |
| 164 |
reference = renderValue( |
| 165 |
template['from'], context) if 'from' in template else context.get('now') |
| 166 |
|
| 167 |
if not isinstance(offset, string): |
| 168 |
raise TemplateError("$fromNow expects a string") |
| 169 |
return shared.fromNow(offset, reference) |
| 170 |
|
| 171 |
|
| 172 |
@operator('$if') |
| 173 |
def ifConstruct(template, context): |
| 174 |
checkUndefinedProperties(template, [r'\$if', 'then', 'else']) |
| 175 |
condition = parse(template['$if'], context) |
| 176 |
try: |
| 177 |
if condition: |
| 178 |
rv = template['then'] |
| 179 |
else: |
| 180 |
rv = template['else'] |
| 181 |
except KeyError: |
| 182 |
return DeleteMarker |
| 183 |
return renderValue(rv, context) |
| 184 |
|
| 185 |
|
| 186 |
@operator('$json') |
| 187 |
def jsonConstruct(template, context): |
| 188 |
checkUndefinedProperties(template, [r'\$json']) |
| 189 |
value = renderValue(template['$json'], context) |
| 190 |
if containsFunctions(value): |
| 191 |
raise TemplateError('evaluated template contained uncalled functions') |
| 192 |
return json.dumps(value, separators=(',', ':'), sort_keys=True, ensure_ascii=False) |
| 193 |
|
| 194 |
|
| 195 |
@operator('$let') |
| 196 |
def let(template, context): |
| 197 |
checkUndefinedProperties(template, [r'\$let', 'in']) |
| 198 |
if not isinstance(template['$let'], dict): |
| 199 |
raise TemplateError("$let value must be an object") |
| 200 |
|
| 201 |
subcontext = context.copy() |
| 202 |
initial_result = renderValue(template['$let'], context) |
| 203 |
if not isinstance(initial_result, dict): |
| 204 |
raise TemplateError("$let value must be an object") |
| 205 |
for k, v in initial_result.items(): |
| 206 |
if not IDENTIFIER_RE.match(k): |
| 207 |
raise TemplateError("top level keys of $let must follow /[a-zA-Z_][a-zA-Z0-9_]*/") |
| 208 |
else: |
| 209 |
subcontext[k] = v |
| 210 |
try: |
| 211 |
in_expression = template['in'] |
| 212 |
except KeyError: |
| 213 |
raise TemplateError("$let operator requires an `in` clause") |
| 214 |
return renderValue(in_expression, subcontext) |
| 215 |
|
| 216 |
|
| 217 |
@operator('$map') |
| 218 |
def map(template, context): |
| 219 |
EACH_RE = r'each\([a-zA-Z_][a-zA-Z0-9_]*(,\s*([a-zA-Z_][a-zA-Z0-9_]*))?\)' |
| 220 |
checkUndefinedProperties(template, [r'\$map', EACH_RE]) |
| 221 |
value = renderValue(template['$map'], context) |
| 222 |
if not isinstance(value, list) and not isinstance(value, dict): |
| 223 |
raise TemplateError("$map value must evaluate to an array or object") |
| 224 |
|
| 225 |
is_obj = isinstance(value, dict) |
| 226 |
|
| 227 |
each_keys = [k for k in template if k.startswith('each(')] |
| 228 |
if len(each_keys) != 1: |
| 229 |
raise TemplateError( |
| 230 |
"$map requires exactly one other property, each(..)") |
| 231 |
each_key = each_keys[0] |
| 232 |
each_args = [x.strip() for x in each_key[5:-1].split(',')] |
| 233 |
each_var = each_args[0] |
| 234 |
each_idx = each_args[1] if len(each_args) > 1 else None |
| 235 |
|
| 236 |
each_template = template[each_key] |
| 237 |
|
| 238 |
def gen(val): |
| 239 |
subcontext = context.copy() |
| 240 |
for i, elt in enumerate(val): |
| 241 |
if each_idx is None: |
| 242 |
subcontext[each_var] = elt |
| 243 |
else: |
| 244 |
subcontext[each_var] = elt['val'] if is_obj else elt |
| 245 |
subcontext[each_idx] = elt['key'] if is_obj else i |
| 246 |
elt = renderValue(each_template, subcontext) |
| 247 |
if elt is not DeleteMarker: |
| 248 |
yield elt |
| 249 |
if is_obj: |
| 250 |
value = [{'key': v[0], 'val': v[1]} for v in value.items()] |
| 251 |
v = dict() |
| 252 |
for e in gen(value): |
| 253 |
if not isinstance(e, dict): |
| 254 |
raise TemplateError( |
| 255 |
"$map on objects expects {0} to evaluate to an object".format(each_key)) |
| 256 |
v.update(e) |
| 257 |
return v |
| 258 |
else: |
| 259 |
return list(gen(value)) |
| 260 |
|
| 261 |
|
| 262 |
@operator('$match') |
| 263 |
def matchConstruct(template, context): |
| 264 |
checkUndefinedProperties(template, [r'\$match']) |
| 265 |
|
| 266 |
if not isinstance(template['$match'], dict): |
| 267 |
raise TemplateError("$match can evaluate objects only") |
| 268 |
|
| 269 |
result = [] |
| 270 |
for condition in sorted(template['$match']): |
| 271 |
if parse(condition, context): |
| 272 |
result.append(renderValue(template['$match'][condition], context)) |
| 273 |
|
| 274 |
return result |
| 275 |
|
| 276 |
|
| 277 |
@operator('$switch') |
| 278 |
def switch(template, context): |
| 279 |
checkUndefinedProperties(template, [r'\$switch']) |
| 280 |
|
| 281 |
if not isinstance(template['$switch'], dict): |
| 282 |
raise TemplateError("$switch can evaluate objects only") |
| 283 |
|
| 284 |
result = [] |
| 285 |
for condition in template['$switch']: |
| 286 |
if not condition == '$default' and parse(condition, context): |
| 287 |
result.append(renderValue(template['$switch'][condition], context)) |
| 288 |
|
| 289 |
if len(result) > 1: |
| 290 |
raise TemplateError("$switch can only have one truthy condition") |
| 291 |
|
| 292 |
if len(result) == 0: |
| 293 |
if '$default' in template['$switch']: |
| 294 |
result.append(renderValue(template['$switch']['$default'], context)) |
| 295 |
|
| 296 |
return result[0] if len(result) > 0 else DeleteMarker |
| 297 |
|
| 298 |
|
| 299 |
@operator('$merge') |
| 300 |
def merge(template, context): |
| 301 |
checkUndefinedProperties(template, [r'\$merge']) |
| 302 |
value = renderValue(template['$merge'], context) |
| 303 |
if not isinstance(value, list) or not all(isinstance(e, dict) for e in value): |
| 304 |
raise TemplateError( |
| 305 |
"$merge value must evaluate to an array of objects") |
| 306 |
v = dict() |
| 307 |
for e in value: |
| 308 |
v.update(e) |
| 309 |
return v |
| 310 |
|
| 311 |
|
| 312 |
@operator('$mergeDeep') |
| 313 |
def merge(template, context): |
| 314 |
checkUndefinedProperties(template, [r'\$mergeDeep']) |
| 315 |
value = renderValue(template['$mergeDeep'], context) |
| 316 |
if not isinstance(value, list) or not all(isinstance(e, dict) for e in value): |
| 317 |
raise TemplateError( |
| 318 |
"$mergeDeep value must evaluate to an array of objects") |
| 319 |
|
| 320 |
def merge(l, r): |
| 321 |
if isinstance(l, list) and isinstance(r, list): |
| 322 |
return l + r |
| 323 |
if isinstance(l, dict) and isinstance(r, dict): |
| 324 |
res = l.copy() |
| 325 |
for k, v in viewitems(r): |
| 326 |
if k in l: |
| 327 |
res[k] = merge(l[k], v) |
| 328 |
else: |
| 329 |
res[k] = v |
| 330 |
return res |
| 331 |
return r |
| 332 |
if len(value) == 0: |
| 333 |
return {} |
| 334 |
return functools.reduce(merge, value[1:], value[0]) |
| 335 |
|
| 336 |
|
| 337 |
@operator('$reverse') |
| 338 |
def reverse(template, context): |
| 339 |
checkUndefinedProperties(template, [r'\$reverse']) |
| 340 |
value = renderValue(template['$reverse'], context) |
| 341 |
if not isinstance(value, list): |
| 342 |
raise TemplateError("$reverse value must evaluate to an array of objects") |
| 343 |
return list(reversed(value)) |
| 344 |
|
| 345 |
|
| 346 |
@operator('$sort') |
| 347 |
def sort(template, context): |
| 348 |
BY_RE = r'by\([a-zA-Z_][a-zA-Z0-9_]*\)' |
| 349 |
checkUndefinedProperties(template, [r'\$sort', BY_RE]) |
| 350 |
value = renderValue(template['$sort'], context) |
| 351 |
if not isinstance(value, list): |
| 352 |
raise TemplateError('$sorted values to be sorted must have the same type') |
| 353 |
|
| 354 |
# handle by(..) if given, applying the schwartzian transform |
| 355 |
by_keys = [k for k in template if k.startswith('by(')] |
| 356 |
if len(by_keys) == 1: |
| 357 |
by_key = by_keys[0] |
| 358 |
by_var = by_key[3:-1] |
| 359 |
by_expr = template[by_key] |
| 360 |
|
| 361 |
def xform(): |
| 362 |
subcontext = context.copy() |
| 363 |
for e in value: |
| 364 |
subcontext[by_var] = e |
| 365 |
yield parse(by_expr, subcontext), e |
| 366 |
to_sort = list(xform()) |
| 367 |
elif len(by_keys) == 0: |
| 368 |
to_sort = [(e, e) for e in value] |
| 369 |
else: |
| 370 |
raise TemplateError('only one by(..) is allowed') |
| 371 |
|
| 372 |
# check types |
| 373 |
try: |
| 374 |
eltype = type(to_sort[0][0]) |
| 375 |
except IndexError: |
| 376 |
return [] |
| 377 |
if eltype in (list, dict, bool, type(None)): |
| 378 |
raise TemplateError('$sorted values to be sorted must have the same type') |
| 379 |
if not all(isinstance(e[0], eltype) for e in to_sort): |
| 380 |
raise TemplateError('$sorted values to be sorted must have the same type') |
| 381 |
|
| 382 |
# unzip the schwartzian transform |
| 383 |
return list(e[1] for e in sorted(to_sort)) |
| 384 |
|
| 385 |
|
| 386 |
def containsFunctions(rendered): |
| 387 |
if hasattr(rendered, '__call__'): |
| 388 |
return True |
| 389 |
elif isinstance(rendered, list): |
| 390 |
for e in rendered: |
| 391 |
if containsFunctions(e): |
| 392 |
return True |
| 393 |
return False |
| 394 |
elif isinstance(rendered, dict): |
| 395 |
for k, v in viewitems(rendered): |
| 396 |
if containsFunctions(v): |
| 397 |
return True |
| 398 |
return False |
| 399 |
else: |
| 400 |
return False |
| 401 |
|
| 402 |
|
| 403 |
def renderValue(template, context): |
| 404 |
if isinstance(template, string): |
| 405 |
return interpolate(template, context) |
| 406 |
|
| 407 |
elif isinstance(template, dict): |
| 408 |
matches = [k for k in template if k in operators] |
| 409 |
if matches: |
| 410 |
if len(matches) > 1: |
| 411 |
raise TemplateError("only one operator allowed") |
| 412 |
return operators[matches[0]](template, context) |
| 413 |
|
| 414 |
def updated(): |
| 415 |
for k, v in viewitems(template): |
| 416 |
if k.startswith('$$'): |
| 417 |
k = k[1:] |
| 418 |
elif k.startswith('$') and IDENTIFIER_RE.match(k[1:]): |
| 419 |
raise TemplateError( |
| 420 |
'$<identifier> is reserved; use $$<identifier>') |
| 421 |
else: |
| 422 |
k = interpolate(k, context) |
| 423 |
|
| 424 |
try: |
| 425 |
v = renderValue(v, context) |
| 426 |
except JSONTemplateError as e: |
| 427 |
if IDENTIFIER_RE.match(k): |
| 428 |
e.add_location('.{}'.format(k)) |
| 429 |
else: |
| 430 |
e.add_location('[{}]'.format(json.dumps(k))) |
| 431 |
raise |
| 432 |
if v is not DeleteMarker: |
| 433 |
yield k, v |
| 434 |
return dict(updated()) |
| 435 |
|
| 436 |
elif isinstance(template, list): |
| 437 |
def updated(): |
| 438 |
for i, e in enumerate(template): |
| 439 |
try: |
| 440 |
v = renderValue(e, context) |
| 441 |
if v is not DeleteMarker: |
| 442 |
yield v |
| 443 |
except JSONTemplateError as e: |
| 444 |
e.add_location('[{}]'.format(i)) |
| 445 |
raise |
| 446 |
|
| 447 |
return list(updated()) |
| 448 |
|
| 449 |
else: |
| 450 |
return template |