Debian Codegraph @

simpletal/simpleTALES.py

raw symbols SCIP
1 """ simpleTALES Implementation
2
3 Copyright (c) 2009 Colin Stewart (http://www.owlfish.com/)
4 All rights reserved.
5
6 Redistribution and use in source and binary forms, with or without
7 modification, are permitted provided that the following conditions
8 are met:
9 1. Redistributions of source code must retain the above copyright
10 notice, this list of conditions and the following disclaimer.
11 2. Redistributions in binary form must reproduce the above copyright
12 notice, this list of conditions and the following disclaimer in the
13 documentation and/or other materials provided with the distribution.
14 3. The name of the author may not be used to endorse or promote products
15 derived from this software without specific prior written permission.
16
17 THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28 If you make any bug fixes or feature enhancements please let me know!
29
30 The classes in this module implement the TALES specification, used
31 by the simpleTAL module.
32
33 Module Dependencies: logging
34 """
35
36 import types, sys
37
38 import logging
39
40 import simpletal
41
42
43 __version__ = simpletal.__version__
44
45 DEFAULTVALUE = "This represents a Default value."
46
47 class PathNotFoundException (Exception):
48 pass
49
50 class ContextContentException (Exception):
51 """ This is raised when invalid content has been placed into the Context object.
52 For example using non-ascii characters instead of Unicode strings.
53 """
54 pass
55
56 PATHNOTFOUNDEXCEPTION = PathNotFoundException()
57
58 class ContextVariable (BaseException):
59 def __init__ (self, value = None):
60 self.ourValue = value
61
62 def value (self, currentPath=None):
63 if (hasattr (self.ourValue, "__call__")):
64 return self.ourValue()
65 return self.ourValue
66
67 def rawValue (self):
68 return self.ourValue
69
70 def __str__ (self):
71 return repr (self.ourValue)
72
73 class RepeatVariable (ContextVariable):
74 """ To be written"""
75 def __init__ (self, sequence):
76 ContextVariable.__init__ (self, 1)
77 self.sequence = sequence
78 self.position = 0
79 self.map = None
80
81 def __getattr__(self, name): # to be used from python eval
82 if (self.map is None):
83 self.createMap()
84
85 return self.map[name]
86
87 def value (self, currentPath=None):
88 if (self.map is None):
89 self.createMap()
90 return self.map
91
92 def rawValue (self):
93 return self.value()
94
95 def getCurrentValue (self):
96 return self.sequence [self.position]
97
98 def increment (self):
99 self.position += 1
100 if (self.position == len (self.sequence)):
101 raise IndexError ("Repeat Finished")
102
103 def createMap (self):
104 self.map = {}
105 self.map ['index'] = self.getIndex
106 self.map ['number'] = self.getNumber
107 self.map ['even'] = self.getEven
108 self.map ['odd'] = self.getOdd
109 self.map ['start'] = self.getStart
110 self.map ['end'] = self.getEnd
111 # TODO: first and last need to be implemented.
112 self.map ['length'] = len (self.sequence)
113 self.map ['letter'] = self.getLowerLetter
114 self.map ['Letter'] = self.getUpperLetter
115 self.map ['roman'] = self.getLowerRoman
116 self.map ['Roman'] = self.getUpperRoman
117
118 # Repeat implementation goes here
119 def getIndex (self):
120 return self.position
121
122 def getNumber (self):
123 return self.position + 1
124
125 def getEven (self):
126 if ((self.position % 2) != 0):
127 return 0
128 return 1
129
130 def getOdd (self):
131 if ((self.position % 2) == 0):
132 return 0
133 return 1
134
135 def getStart (self):
136 if (self.position == 0):
137 return 1
138 return 0
139
140 def getEnd (self):
141 if (self.position == len (self.sequence) - 1):
142 return 1
143 return 0
144
145 def getLowerLetter (self):
146 result = ""
147 nextCol = self.position
148 if (nextCol == 0):
149 return 'a'
150 while (nextCol > 0):
151 nextCol, thisCol = divmod (nextCol, 26)
152 result = chr (ord ('a') + thisCol) + result
153 return result
154
155 def getUpperLetter (self):
156 return self.getLowerLetter().upper()
157
158 def getLowerRoman (self):
159 romanNumeralList = (('m', 1000)
160 ,('cm', 900)
161 ,('d', 500)
162 ,('cd', 400)
163 ,('c', 100)
164 ,('xc', 90)
165 ,('l', 50)
166 ,('xl', 40)
167 ,('x', 10)
168 ,('ix', 9)
169 ,('v', 5)
170 ,('iv', 4)
171 ,('i', 1)
172 )
173 if (self.position > 3999):
174 # Roman numbers only supported up to 4000
175 return ' '
176 num = self.position + 1
177 result = ""
178 for roman, integer in romanNumeralList:
179 while (num >= integer):
180 result += roman
181 num -= integer
182 return result
183
184 def getUpperRoman (self):
185 return self.getLowerRoman().upper()
186
187 class IteratorRepeatVariable (RepeatVariable):
188 def __init__ (self, sequence):
189 RepeatVariable.__init__ (self, sequence)
190 self.curValue = None
191 self.iterStatus = 0
192
193 def getCurrentValue (self):
194 if (self.iterStatus == 0):
195 self.iterStatus = 1
196 try:
197 self.curValue = next(self.sequence)
198 except StopIteration as e:
199 self.iterStatus = 2
200 raise IndexError ("Repeat Finished")
201 return self.curValue
202
203 def increment (self):
204 # Need this for the repeat variable functions.
205 self.position += 1
206 try:
207 self.curValue = next(self.sequence)
208 except StopIteration as e:
209 self.iterStatus = 2
210 raise IndexError ("Repeat Finished")
211
212 def createMap (self):
213 self.map = {}
214 self.map ['index'] = self.getIndex
215 self.map ['number'] = self.getNumber
216 self.map ['even'] = self.getEven
217 self.map ['odd'] = self.getOdd
218 self.map ['start'] = self.getStart
219 self.map ['end'] = self.getEnd
220 # TODO: first and last need to be implemented.
221 self.map ['length'] = sys.maxsize
222 self.map ['letter'] = self.getLowerLetter
223 self.map ['Letter'] = self.getUpperLetter
224 self.map ['roman'] = self.getLowerRoman
225 self.map ['Roman'] = self.getUpperRoman
226
227 def getEnd (self):
228 if (self.iterStatus == 2):
229 return 1
230 return 0
231
232 class PathFunctionVariable (ContextVariable):
233 def __init__ (self, func):
234 ContextVariable.__init__ (self, value = func)
235 self.func = func
236
237 def value (self, currentPath=None):
238 if (currentPath is not None):
239 index, paths = currentPath
240 result = ContextVariable (self.func ('/'.join (paths[index:])))
241 # Fast track the result
242 raise result
243
244 class CachedFuncResult (ContextVariable):
245 def value (self, currentPath=None):
246 try:
247 return self.cachedValue
248 except:
249 self.cachedValue = ContextVariable.value (self)
250 return self.cachedValue
251
252 def clearCache (self):
253 try:
254 del self.cachedValue
255 except:
256 pass
257
258 class PythonPathFunctions:
259 def __init__ (self, context):
260 self.context = context
261
262 def path (self, expr):
263 return self.context.evaluatePath (expr)
264
265 def string (self, expr):
266 return self.context.evaluateString (expr)
267
268 def exists (self, expr):
269 return self.context.evaluateExists (expr)
270
271 def nocall (self, expr):
272 return self.context.evaluateNoCall (expr)
273
274 def test (self, *arguments):
275 if (len (arguments) % 2):
276 # We have an odd number of arguments - which means the last one is a default
277 pairs = arguments[:-1]
278 defaultValue = arguments[-1]
279 else:
280 # No default - so use None
281 pairs = arguments
282 defaultValue = None
283
284 index = 0
285 while (index < len (pairs)):
286 test = pairs[index]
287 index += 1
288 value = pairs[index]
289 index += 1
290 if (test):
291 return value
292
293 return defaultValue
294
295 class Context:
296 def __init__ (self, options=None, allowPythonPath=0):
297 self.allowPythonPath = allowPythonPath
298 self.globals = {}
299 self.locals = {}
300 self.localStack = []
301 self.repeatStack = []
302 self.populateDefaultVariables (options)
303 self.log = logging.getLogger ("simpleTALES.Context")
304 self.true = 1
305 self.false = 0
306 self.pythonPathFuncs = PythonPathFunctions (self)
307
308 def addRepeat (self, name, var, initialValue):
309 # Pop the current repeat map onto the stack
310 self.repeatStack.append (self.repeatMap)
311 self.repeatMap = self.repeatMap.copy()
312 self.repeatMap [name] = var
313 # Map this repeatMap into the global space
314 self.addGlobal ('repeat', self.repeatMap)
315
316 # Add in the locals
317 self.pushLocals()
318 self.setLocal (name, initialValue)
319
320 def removeRepeat (self, name):
321 # Bring the old repeat map back
322 self.repeatMap = self.repeatStack.pop()
323 # Map this repeatMap into the global space
324 self.addGlobal ('repeat', self.repeatMap)
325
326 def addGlobal (self, name, value):
327 self.globals[name] = value
328
329 def pushLocals (self):
330 # Push the current locals onto a stack so that we can safely over-ride them.
331 self.localStack.append (self.locals)
332 self.locals = self.locals.copy()
333
334 def setLocal (self, name, value):
335 # Override the current local if present with the new one
336 self.locals [name] = value
337
338 def popLocals (self):
339 self.locals = self.localStack.pop()
340
341 def evaluate (self, expr, originalAtts = None):
342 # Returns a ContextVariable
343 #self.log.debug ("Evaluating %s" % expr)
344 if (originalAtts is not None):
345 # Call from outside
346 self.globals['attrs'] = originalAtts
347 suppressException = 1
348 else:
349 suppressException = 0
350
351 # Supports path, exists, nocall, not, and string
352 expr = expr.strip ()
353 try:
354 if expr.startswith ('path:'):
355 return self.evaluatePath (expr[5:].lstrip ())
356 elif expr.startswith ('exists:'):
357 return self.evaluateExists (expr[7:].lstrip())
358 elif expr.startswith ('nocall:'):
359 return self.evaluateNoCall (expr[7:].lstrip())
360 elif expr.startswith ('not:'):
361 return self.evaluateNot (expr[4:].lstrip())
362 elif expr.startswith ('string:'):
363 return self.evaluateString (expr[7:].lstrip())
364 elif expr.startswith ('python:'):
365 return self.evaluatePython (expr[7:].lstrip())
366 else:
367 # Not specified - so it's a path
368 return self.evaluatePath (expr)
369 except PathNotFoundException as e:
370 if (suppressException):
371 return None
372 raise e
373
374 def evaluatePython (self, expr):
375 if (not self.allowPythonPath):
376 self.log.warning ("Parameter allowPythonPath is false. NOT Evaluating python expression %s" % expr)
377 return self.false
378 #self.log.debug ("Evaluating python expression %s" % expr)
379
380 globals={}
381 for name, value in list(self.globals.items()):
382 if (isinstance (value, ContextVariable)): value = value.rawValue()
383 globals [name] = value
384 globals ['path'] = self.pythonPathFuncs.path
385 globals ['string'] = self.pythonPathFuncs.string
386 globals ['exists'] = self.pythonPathFuncs.exists
387 globals ['nocall'] = self.pythonPathFuncs.nocall
388 globals ['test'] = self.pythonPathFuncs.test
389
390 locals={}
391 for name, value in list(self.locals.items()):
392 if (isinstance (value, ContextVariable)): value = value.rawValue()
393 locals [name] = value
394
395 try:
396 result = eval(expr, globals, locals)
397 if (isinstance (result, ContextVariable)):
398 return result.value()
399 return result
400 except Exception as e:
401 # An exception occured evaluating the template, return the exception as text
402 self.log.warning ("Exception occurred evaluating python path, exception: " + str (e))
403 return "Exception: %s" % str (e)
404
405 def evaluatePath (self, expr):
406 #self.log.debug ("Evaluating path expression %s" % expr)
407 allPaths = expr.split ('|')
408 if (len (allPaths) > 1):
409 for path in allPaths:
410 # Evaluate this path
411 try:
412 return self.evaluate (path.strip ())
413 except PathNotFoundException as e:
414 # Path didn't exist, try the next one
415 pass
416 # No paths evaluated - raise exception.
417 raise PATHNOTFOUNDEXCEPTION
418 else:
419 # A single path - so let's evaluate it.
420 # This *can* raise PathNotFoundException
421 return self.traversePath (allPaths[0])
422
423 def evaluateExists (self, expr):
424 #self.log.debug ("Evaluating %s to see if it exists" % expr)
425 allPaths = expr.split ('|')
426 # The first path is for us
427 # Return true if this first bit evaluates, otherwise test the rest
428 try:
429 result = self.traversePath (allPaths[0], canCall = 0)
430 return self.true
431 except PathNotFoundException as e:
432 # Look at the rest of the paths.
433 pass
434
435 for path in allPaths[1:]:
436 # Evaluate this path
437 try:
438 pathResult = self.evaluate (path.strip ())
439 # If this is part of a "exists: path1 | exists: path2" path then we need to look at the actual result.
440 if (pathResult):
441 return self.true
442 except PathNotFoundException as e:
443 pass
444 # If we get this far then there are *no* paths that exist.
445 return self.false
446
447 def evaluateNoCall (self, expr):
448 #self.log.debug ("Evaluating %s using nocall" % expr)
449 allPaths = expr.split ('|')
450 # The first path is for us
451 try:
452 return self.traversePath (allPaths[0], canCall = 0)
453 except PathNotFoundException as e:
454 # Try the rest of the paths.
455 pass
456
457 for path in allPaths[1:]:
458 # Evaluate this path
459 try:
460 return self.evaluate (path.strip ())
461 except PathNotFoundException as e:
462 pass
463 # No path evaluated - raise error
464 raise PATHNOTFOUNDEXCEPTION
465
466 def evaluateNot (self, expr):
467 #self.log.debug ("Evaluating NOT value of %s" % expr)
468
469 # Evaluate what I was passed
470 try:
471 pathResult = self.evaluate (expr)
472 except PathNotFoundException as e:
473 # In SimpleTAL the result of "not: no/such/path" should be TRUE not FALSE.
474 return self.true
475
476 if (pathResult is None):
477 # Value was Nothing
478 return self.true
479 if (pathResult == DEFAULTVALUE):
480 return self.false
481 try:
482 resultLen = len (pathResult)
483 if (resultLen > 0):
484 return self.false
485 else:
486 return self.true
487 except:
488 # Not a sequence object.
489 pass
490 if (not pathResult):
491 return self.true
492 # Everything else is true, so we return false!
493 return self.false
494
495 def evaluateString (self, expr):
496 #self.log.debug ("Evaluating String %s" % expr)
497 result = ""
498 skipCount = 0
499 for position in range (0,len (expr)):
500 if (skipCount > 0):
501 skipCount -= 1
502 else:
503 if (expr[position] == '$'):
504 try:
505 if (expr[position + 1] == '$'):
506 # Escaped $ sign
507 result += '$'
508 skipCount = 1
509 elif (expr[position + 1] == '{'):
510 # Looking for a path!
511 endPos = expr.find ('}', position + 1)
512 if (endPos > 0):
513 path = expr[position + 2:endPos]
514 # Evaluate the path - missing paths raise exceptions as normal.
515 try:
516 pathResult = self.evaluate (path)
517 except PathNotFoundException as e:
518 # This part of the path didn't evaluate to anything - leave blank
519 pathResult = ''
520 if (pathResult is not None):
521 if (isinstance (pathResult, str)):
522 result += pathResult
523 else:
524 # THIS IS NOT A BUG!
525 # Use Unicode in Context if you aren't using Ascii!
526 result += str (pathResult)
527 skipCount = endPos - position
528 else:
529 # It's a variable
530 endPos = expr.find (' ', position + 1)
531 if (endPos == -1):
532 endPos = len (expr)
533 path = expr [position + 1:endPos]
534 # Evaluate the variable - missing paths raise exceptions as normal.
535 try:
536 pathResult = self.traversePath (path)
537 except PathNotFoundException as e:
538 # This part of the path didn't evaluate to anything - leave blank
539 pathResult = ''
540 if (pathResult is not None):
541 if (isinstance (pathResult, str)):
542 result += pathResult
543 else:
544 # THIS IS NOT A BUG!
545 # Use Unicode in Context if you aren't using Ascii!
546 result += str (pathResult)
547 skipCount = endPos - position - 1
548 except IndexError as e:
549 # Trailing $ sign - just suppress it
550 self.log.warning ("Trailing $ detected")
551 pass
552 else:
553 result += expr[position]
554 return result
555
556 def traversePath (self, expr, canCall=1):
557 # canCall only applies to the *final* path destination, not points down the path.
558 # Check for and correct for trailing/leading quotes
559 if (expr.startswith ('"') or expr.startswith ("'")):
560 if (expr.endswith ('"') or expr.endswith ("'")):
561 expr = expr [1:-1]
562 else:
563 expr = expr [1:]
564 elif (expr.endswith ('"') or expr.endswith ("'")):
565 expr = expr [0:-1]
566 pathList = expr.split ('/')
567
568 path = pathList[0]
569 if path.startswith ('?'):
570 path = path[1:]
571 if path in self.locals:
572 path = self.locals[path]
573 if (isinstance (path, ContextVariable)): path = path.value()
574 elif (hasattr (path, "__call__")):path = path()
575
576 elif path in self.globals:
577 path = self.globals[path]
578 if (isinstance (path, ContextVariable)): path = path.value()
579 elif (hasattr (path, "__call__")):path = path()
580 #self.log.debug ("Dereferenced to %s" % path)
581 if path in self.locals:
582 val = self.locals[path]
583 elif path in self.globals:
584 val = self.globals[path]
585 else:
586 # If we can't find it then raise an exception
587 raise PATHNOTFOUNDEXCEPTION
588 index = 1
589 for path in pathList[1:]:
590 #self.log.debug ("Looking for path element %s" % path)
591 if path.startswith ('?'):
592 path = path[1:]
593 if path in self.locals:
594 path = self.locals[path]
595 if (isinstance (path, ContextVariable)): path = path.value()
596 elif (hasattr (path, "__call__")):path = path()
597 elif path in self.globals:
598 path = self.globals[path]
599 if (isinstance (path, ContextVariable)): path = path.value()
600 elif (hasattr (path, "__call__")):path = path()
601 #self.log.debug ("Dereferenced to %s" % path)
602 try:
603 if (isinstance (val, ContextVariable)): temp = val.value((index,pathList))
604 elif (hasattr (val, "__call__")):temp = val()
605 else: temp = val
606 except ContextVariable as e:
607 # Fast path for those functions that return values
608 return e.value()
609
610 if (hasattr (temp, path)):
611 val = getattr (temp, path)
612 else:
613 try:
614 try:
615 val = temp[path]
616 except TypeError:
617 val = temp[int(path)]
618 except:
619 #self.log.debug ("Not found.")
620 raise PATHNOTFOUNDEXCEPTION
621 index = index + 1
622 #self.log.debug ("Found value %s" % str (val))
623 if (canCall):
624 try:
625 if (isinstance (val, ContextVariable)): result = val.value((index,pathList))
626 elif (hasattr (val, "__call__")):result = val()
627 else: result = val
628 except ContextVariable as e:
629 # Fast path for those functions that return values
630 return e.value()
631 else:
632 if (isinstance (val, ContextVariable)): result = val.realValue
633 else: result = val
634 return result
635
636 def __str__ (self):
637 return "Globals: " + str (self.globals) + "Locals: " + str (self.locals)
638
639 def populateDefaultVariables (self, options):
640 vars = {}
641 self.repeatMap = {}
642 vars['nothing'] = None
643 vars['default'] = DEFAULTVALUE
644 vars['options'] = options
645 # To start with there are no repeats
646 vars['repeat'] = self.repeatMap
647 vars['attrs'] = None
648
649 # Add all of these to the global context
650 for name in list(vars.keys()):
651 self.addGlobal (name,vars[name])
652
653 # Add also under CONTEXTS
654 self.addGlobal ('CONTEXTS', vars)
655