Debian Codegraph @

Cheetah/Compiler.py

raw symbols SCIP
1 '''
2 Compiler classes for Cheetah:
3 ModuleCompiler aka 'Compiler'
4 ClassCompiler
5 MethodCompiler
6
7 If you are trying to grok this code start with ModuleCompiler.__init__,
8 ModuleCompiler.compile, and ModuleCompiler.__getattr__.
9 '''
10
11 import sys
12 import os
13 import os.path
14 from os.path import getmtime
15 import re
16 import time
17 import random
18 import warnings
19 import copy
20 import codecs
21
22 from .Version import Version, VersionTuple
23 from .SettingsManager import SettingsManager
24 from .Utils.Indenter import indentize # an undocumented preprocessor
25 from . import NameMapper
26 from .Parser import Parser, ParseError, specialVarRE, \
27 STATIC_CACHE, REFRESH_CACHE, SET_GLOBAL, SET_MODULE, \
28 unicodeDirectiveRE, encodingDirectiveRE, escapedNewlineRE
29 from .compat import PY2, string_type, unicode
30
31 from .NameMapper import valueForName, valueFromSearchList, \
32 valueFromFrameOrSearchList
33 VFFSL = valueFromFrameOrSearchList
34 VFSL = valueFromSearchList
35 VFN = valueForName
36 currentTime = time.time
37
38
39 class Error(Exception):
40 pass
41
42
43 # Settings format: (key, default, docstring)
44 _DEFAULT_COMPILER_SETTINGS = [
45 ('useNameMapper', True,
46 'Enable NameMapper for dotted notation and searchList support'),
47 ('useSearchList', True,
48 "Enable the searchList, requires useNameMapper=True, "
49 "if disabled, first portion of the $variable is a global, builtin, "
50 "or local variable that doesn't need looking up in the searchList"),
51 ('allowSearchListAsMethArg', True, ''),
52 ('useAutocalling', True,
53 'Detect and call callable objects in searchList, '
54 'requires useNameMapper=True'),
55 ('useStackFrames', True,
56 'Used for NameMapper.valueFromFrameOrSearchList '
57 'rather than NameMapper.valueFromSearchList'),
58 ('useErrorCatcher', False,
59 'Turn on the #errorCatcher directive '
60 'for catching NameMapper errors, etc'),
61 ('alwaysFilterNone', True, 'Filter out None prior to calling the #filter'),
62 ('useFilters', True, 'If False, pass output through str()'),
63 ('includeRawExprInFilterArgs', True, ''),
64 ('useLegacyImportMode', True,
65 'All #import statements are relocated to the top '
66 'of the generated Python module'),
67 ('prioritizeSearchListOverSelf', False,
68 "When iterating the searchList, "
69 "look into the searchList passed into the initializer "
70 "instead of Template members first"),
71
72 ('autoAssignDummyTransactionToSelf', False, ''),
73 ('useKWsDictArgForPassingTrans', True, ''),
74
75 ('commentOffset', 1, ''),
76 ('outputRowColComments', True, ''),
77 ('includeBlockMarkers', False,
78 'Wrap #block\'s in a comment in the template\'s output'),
79 ('blockMarkerStart', ('\n<!-- START BLOCK: ', ' -->\n'), ''),
80 ('blockMarkerEnd', ('\n<!-- END BLOCK: ', ' -->\n'), ''),
81 ('defDocStrMsg',
82 'Autogenerated by Cheetah: The Python-Powered Template Engine', ''),
83 ('setup__str__method', False, ''),
84 ('mainMethodName', 'respond', ''),
85 ('mainMethodNameForSubclasses', 'writeBody', ''),
86 ('indentationStep', ' ' * 4, ''),
87 ('initialMethIndentLevel', 2, ''),
88 ('monitorSrcFile', False, ''),
89 ('outputMethodsBeforeAttributes', True, ''),
90 ('addTimestampsToCompilerOutput', True, ''),
91
92 # Customizing the #extends directive
93 ('autoImportForExtendsDirective', True, ''),
94 ('handlerForExtendsDirective', None, ''),
95
96 ('disabledDirectives', [],
97 'List of directive keys to disable (without starting "#")'),
98 ('enabledDirectives', [],
99 'List of directive keys to enable (without starting "#")'),
100 ('disabledDirectiveHooks', [], 'callable(parser, directiveKey)'),
101 ('preparseDirectiveHooks', [], 'callable(parser, directiveKey)'),
102 ('postparseDirectiveHooks', [], 'callable(parser, directiveKey)'),
103 ('preparsePlaceholderHooks', [], 'callable(parser)'),
104 ('postparsePlaceholderHooks', [], 'callable(parser)'),
105 ('expressionFilterHooks', [],
106 'callable(parser, expr, exprType, rawExpr=None, startPos=None), '
107 'exprType is the name of the directive, "psp" or "placeholder" '
108 'The filters *must* return the expr or raise an expression, '
109 'they can modify the expr if needed'),
110 ('templateMetaclass', None,
111 'Strictly optional, only will work with new-style baseclasses as well'),
112 ('i18NFunctionName', 'self.i18n', ''),
113
114 ('cheetahVarStartToken', '$', ''),
115 ('commentStartToken', '##', ''),
116 ('multiLineCommentStartToken', '#*', ''),
117 ('multiLineCommentEndToken', '*#', ''),
118 ('gobbleWhitespaceAroundMultiLineComments', True, ''),
119 ('directiveStartToken', '#', ''),
120 ('directiveEndToken', '#', ''),
121 ('allowWhitespaceAfterDirectiveStartToken', False, ''),
122 ('PSPStartToken', '<%', ''),
123 ('PSPEndToken', '%>', ''),
124 ('EOLSlurpToken', '#', ''),
125 ('gettextTokens', ["_", "N_", "ngettext"], ''),
126 ('allowExpressionsInExtendsDirective', False, ''),
127 ('allowEmptySingleLineMethods', False, ''),
128 ('allowNestedDefScopes', True, ''),
129 ('allowPlaceholderFilterArgs', True, ''),
130 ('encoding', None,
131 'The encoding to read input files as (or None for ASCII)'),
132 ]
133
134 DEFAULT_COMPILER_SETTINGS = \
135 dict([(v[0], v[1]) for v in _DEFAULT_COMPILER_SETTINGS])
136
137
138 class GenUtils(object):
139 """
140 An abstract baseclass for the Compiler classes that provides methods that
141 perform generic utility functions or generate pieces of output code from
142 information passed in by the Parser baseclass. These methods don't do any
143 parsing themselves.
144 """
145
146 def genTimeInterval(self, timeString):
147 # #@@ TR: need to add some error handling here
148 if timeString[-1] == 's':
149 interval = float(timeString[:-1])
150 elif timeString[-1] == 'm':
151 interval = float(timeString[:-1])*60 # noqa: E226,E501 missing whitespace around operator
152 elif timeString[-1] == 'h':
153 interval = float(timeString[:-1])*60*60 # noqa: E226,E501 missing whitespace around operator
154 elif timeString[-1] == 'd':
155 interval = float(timeString[:-1])*60*60*24 # noqa: E226,E501 missing whitespace around operator
156 elif timeString[-1] == 'w':
157 interval = float(timeString[:-1])*60*60*24*7 # noqa: E226,E501 missing whitespace around operator
158 else: # default to minutes
159 interval = float(timeString)*60 # noqa: E226,E501 missing whitespace around operator
160 return interval
161
162 def genCacheInfo(self, cacheTokenParts):
163 """Decipher a placeholder cachetoken
164 """
165 cacheInfo = {}
166 if cacheTokenParts['REFRESH_CACHE']:
167 cacheInfo['type'] = REFRESH_CACHE
168 cacheInfo['interval'] = \
169 self.genTimeInterval(cacheTokenParts['interval'])
170 elif cacheTokenParts['STATIC_CACHE']:
171 cacheInfo['type'] = STATIC_CACHE
172 return cacheInfo # is empty if no cache
173
174 def genCacheInfoFromArgList(self, argList):
175 cacheInfo = {'type': REFRESH_CACHE}
176 for key, val in argList:
177 if val[0] in '"\'':
178 val = val[1:-1]
179
180 if key == 'timer':
181 key = 'interval'
182 val = self.genTimeInterval(val)
183
184 cacheInfo[key] = val
185 return cacheInfo
186
187 def genCheetahVar(self, nameChunks, plain=False):
188 if nameChunks[0][0] in self.setting('gettextTokens'):
189 self.addGetTextVar(nameChunks)
190 if self.setting('useNameMapper') and not plain:
191 return self.genNameMapperVar(nameChunks)
192 else:
193 return self.genPlainVar(nameChunks)
194
195 def addGetTextVar(self, nameChunks):
196 """Output something that gettext can recognize.
197
198 This is a harmless side effect necessary to make gettext work when it
199 is scanning compiled templates for strings marked for translation.
200
201 @@TR: another marginally more efficient approach would be to put the
202 output in a dummy method that is never called.
203 """
204 # @@TR: this should be in the compiler not here
205 self.addChunk("if False:")
206 self.indent()
207 self.addChunk(self.genPlainVar(nameChunks[:]))
208 self.dedent()
209
210 def genPlainVar(self, nameChunks):
211 """Generate Python code for a Cheetah $var without using NameMapper
212 (Unified Dotted Notation with the SearchList).
213 """
214 nameChunks.reverse()
215 chunk = nameChunks.pop()
216 pythonCode = chunk[0] + chunk[2]
217 while nameChunks:
218 chunk = nameChunks.pop()
219 pythonCode = (pythonCode + '.' + chunk[0] + chunk[2])
220 return pythonCode
221
222 def genNameMapperVar(self, nameChunks):
223 """Generate valid Python code for a Cheetah $var, using NameMapper
224 (Unified Dotted Notation with the SearchList).
225
226 nameChunks = list of var subcomponents represented as tuples
227 [ (name,useAC,remainderOfExpr),
228 ]
229 where:
230 name = the dotted name base
231 useAC = where NameMapper should use autocalling on namemapperPart
232 remainderOfExpr = any arglist, index, or slice
233
234 If remainderOfExpr contains a call arglist (e.g. '(1234)') then useAC
235 is False, otherwise it defaults to True. It is overridden by the global
236 setting 'useAutocalling' if this setting is False.
237
238 EXAMPLE::
239
240 if the raw Cheetah Var is
241 $a.b.c[1].d().x.y.z
242
243 nameChunks is the list
244 [ ('a.b.c',True,'[1]'), # A
245 ('d',False,'()'), # B
246 ('x.y.z',True,''), # C
247 ]
248
249 When this method is fed the list above it returns::
250
251 VFN(VFN(VFFSL(SL, 'a.b.c',True)[1], 'd',False)(), 'x.y.z',True)
252
253 which can be represented as::
254
255 VFN(B`, name=C[0], executeCallables=(useAC and C[1]))C[2]
256
257 where::
258
259 VFN = NameMapper.valueForName
260 VFFSL = NameMapper.valueFromFrameOrSearchList
261 # optionally used instead of VFFSL
262 VFSL = NameMapper.valueFromSearchList
263 SL = self.searchList()
264 useAC = self.setting('useAutocalling') # True in this example
265
266 A = ('a.b.c',True,'[1]')
267 B = ('d',False,'()')
268 C = ('x.y.z',True,'')
269
270 C` = VFN( VFN( VFFSL(SL, 'a.b.c',True)[1],
271 'd',False)(),
272 'x.y.z',True)
273 = VFN(B`, name='x.y.z', executeCallables=True)
274
275 B` = VFN(A`, name=B[0], executeCallables=(useAC and B[1]))B[2]
276 A` = VFFSL(SL, name=A[0], executeCallables=(useAC and A[1]))A[2]
277
278 Note, if the compiler setting useStackFrames=False (default is true)
279 then::
280
281 A` = VFSL([locals()] + SL + [globals(), builtin],
282 name=A[0], executeCallables=(useAC and A[1]))A[2]
283
284 This option allows Cheetah to be used with Psyco, which doesn't support
285 stack frame introspection.
286 """
287 defaultUseAC = self.setting('useAutocalling')
288 useSearchList = self.setting('useSearchList')
289
290 nameChunks.reverse()
291 name, useAC, remainder = nameChunks.pop()
292
293 if not useSearchList:
294 firstDotIdx = name.find('.')
295 if firstDotIdx != -1 and firstDotIdx < len(name):
296 beforeFirstDot = name[:firstDotIdx]
297 afterDot = name[firstDotIdx+1:] # noqa: E226,E501 missing whitespace around operator
298 pythonCode = ('VFN(' + beforeFirstDot
299 + ',"' + afterDot
300 + '",' + repr(defaultUseAC and useAC) + ')'
301 + remainder)
302 else:
303 pythonCode = name + remainder
304 elif self.setting('useStackFrames'):
305 pythonCode = ('VFFSL(SL,'
306 '"' + name + '",'
307 + repr(defaultUseAC and useAC) + ')'
308 + remainder)
309 else:
310 pythonCode = ('VFSL([locals()]+SL+[globals(), builtin],'
311 '"' + name + '",'
312 + repr(defaultUseAC and useAC) + ')'
313 + remainder)
314 ##
315 while nameChunks:
316 name, useAC, remainder = nameChunks.pop()
317 pythonCode = ('VFN(' + pythonCode
318 + ',"' + name
319 + '",' + repr(defaultUseAC and useAC) + ')'
320 + remainder)
321 return pythonCode
322
323 ##################################################
324 # METHOD COMPILERS
325
326
327 class MethodCompiler(GenUtils):
328 def __init__(self, methodName, classCompiler,
329 initialMethodComment=None,
330 decorators=None):
331 self._settingsManager = classCompiler
332 self._classCompiler = classCompiler
333 self._moduleCompiler = classCompiler._moduleCompiler
334 self._methodName = methodName
335 self._initialMethodComment = initialMethodComment
336 self._setupState()
337 self._decorators = decorators or []
338
339 def setting(self, key):
340 return self._settingsManager.setting(key)
341
342 def _setupState(self):
343 self._indent = self.setting('indentationStep')
344 self._indentLev = self.setting('initialMethIndentLevel')
345 self._pendingStrConstChunks = []
346 self._methodSignature = None
347 self._methodDef = None
348 self._docStringLines = []
349 self._methodBodyChunks = []
350
351 self._cacheRegionsStack = []
352 self._callRegionsStack = []
353 self._captureRegionsStack = []
354 self._filterRegionsStack = []
355
356 self._isErrorCatcherOn = False
357
358 self._hasReturnStatement = False
359 self._isGenerator = False
360
361 def cleanupState(self):
362 """Called by the containing class compiler instance
363 """
364 pass
365
366 def methodName(self):
367 return self._methodName
368
369 def setMethodName(self, name):
370 self._methodName = name
371
372 # methods for managing indentation
373
374 def indentation(self):
375 return self._indent * self._indentLev
376
377 def indent(self):
378 self._indentLev += 1
379
380 def dedent(self):
381 if self._indentLev:
382 self._indentLev -= 1
383 else:
384 raise Error('Attempt to dedent when the indentLev is 0')
385
386 # methods for final code wrapping
387
388 def methodDef(self):
389 if self._methodDef:
390 return self._methodDef
391 else:
392 return self.wrapCode()
393
394 __str__ = methodDef
395 __unicode__ = methodDef
396
397 def wrapCode(self):
398 self.commitStrConst()
399 methodDefChunks = (
400 self.methodSignature(),
401 '\n',
402 self.docString(),
403 self.methodBody())
404 methodDef = ''.join(methodDefChunks)
405 self._methodDef = methodDef
406 return methodDef
407
408 def methodSignature(self):
409 return self._indent + self._methodSignature + ':'
410
411 def setMethodSignature(self, signature):
412 self._methodSignature = signature
413
414 def methodBody(self):
415 return ''.join(self._methodBodyChunks)
416
417 def docString(self):
418 if not self._docStringLines:
419 return ''
420
421 ind = self._indent*2 # noqa: E226 missing whitespace around operator
422 docStr = (ind + '"""\n' + ind
423 + ('\n' + ind).join([ln.replace('"""', "'''")
424 for ln in self._docStringLines])
425 + '\n' + ind + '"""\n')
426 return docStr
427
428 # methods for adding code
429 def addMethDocString(self, line):
430 self._docStringLines.append(line.replace('%', '%%'))
431
432 def addChunk(self, chunk):
433 self.commitStrConst()
434 chunk = "\n" + self.indentation() + chunk
435 self._methodBodyChunks.append(chunk)
436
437 def appendToPrevChunk(self, appendage):
438 self._methodBodyChunks[-1] = self._methodBodyChunks[-1] + appendage
439
440 def addWriteChunk(self, chunk):
441 self.addChunk('write(' + chunk + ')')
442
443 def addFilteredChunk(self, chunk, filterArgs=None,
444 rawExpr=None, lineCol=None):
445 if filterArgs is None:
446 filterArgs = ''
447 if self.setting('includeRawExprInFilterArgs') and rawExpr:
448 filterArgs += ', rawExpr=%s' % repr(rawExpr)
449
450 if self.setting('alwaysFilterNone'):
451 if rawExpr and rawExpr.find('\n') == -1 and \
452 rawExpr.find('\r') == -1:
453 self.addChunk("_v = %s # %r" % (chunk, rawExpr))
454 if lineCol:
455 self.appendToPrevChunk(' on line %s, col %s' % lineCol)
456 else:
457 self.addChunk("_v = %s" % chunk)
458
459 if self.setting('useFilters'):
460 self.addChunk("if _v is not None: write(_filter(_v%s))"
461 % filterArgs)
462 else:
463 self.addChunk("if _v is not None: write(str(_v))")
464 else:
465 if self.setting('useFilters'):
466 self.addChunk("write(_filter(%s%s))" % (chunk, filterArgs))
467 else:
468 self.addChunk("write(str(%s))" % chunk)
469
470 def _appendToPrevStrConst(self, strConst):
471 if self._pendingStrConstChunks:
472 self._pendingStrConstChunks.append(strConst)
473 else:
474 self._pendingStrConstChunks = [strConst]
475
476 def commitStrConst(self):
477 """
478 Add the code for outputting the pending strConst without chopping off
479 any whitespace from it.
480 """
481 if not self._pendingStrConstChunks:
482 return
483
484 strConst = ''.join(self._pendingStrConstChunks)
485 self._pendingStrConstChunks = []
486 if not strConst:
487 return
488
489 reprstr = repr(strConst)
490 i = 0
491 out = []
492 if reprstr.startswith('u'):
493 i = 1
494 out = ['u']
495 body = escapedNewlineRE.sub('\\1\n', reprstr[i+1:-1]) # noqa: E226,E501 missing whitespace around operator
496
497 if reprstr[i] == "'":
498 out.append("'''")
499 out.append(body)
500 out.append("'''")
501 else:
502 out.append('"""')
503 out.append(body)
504 out.append('"""')
505 self.addWriteChunk(''.join(out))
506
507 def handleWSBeforeDirective(self):
508 """Truncate the pending strCont to the beginning of the current line.
509 """
510 if self._pendingStrConstChunks:
511 src = self._pendingStrConstChunks[-1]
512 BOL = max(src.rfind('\n') + 1, src.rfind('\r') + 1, 0)
513 if BOL < len(src):
514 self._pendingStrConstChunks[-1] = src[:BOL]
515
516 def isErrorCatcherOn(self):
517 return self._isErrorCatcherOn
518
519 def turnErrorCatcherOn(self):
520 self._isErrorCatcherOn = True
521
522 def turnErrorCatcherOff(self):
523 self._isErrorCatcherOn = False
524
525 # @@TR: consider merging the next two methods into one
526 def addStrConst(self, strConst):
527 self._appendToPrevStrConst(strConst)
528
529 def addRawText(self, text):
530 self.addStrConst(text)
531
532 def addMethComment(self, comm):
533 offSet = self.setting('commentOffset')
534 self.addChunk('#' + ' '*offSet + comm) # noqa: E226,E501 missing whitespace around operator
535
536 def addPlaceholder(self, expr, filterArgs, rawPlaceholder,
537 cacheTokenParts, lineCol,
538 silentMode=False):
539 cacheInfo = self.genCacheInfo(cacheTokenParts)
540 if cacheInfo:
541 cacheInfo['ID'] = repr(rawPlaceholder)[1:-1]
542 self.startCacheRegion(cacheInfo, lineCol,
543 rawPlaceholder=rawPlaceholder)
544
545 if self.isErrorCatcherOn():
546 methodName = self._classCompiler.addErrorCatcherCall(
547 expr, rawCode=rawPlaceholder, lineCol=lineCol)
548 expr = 'self.' + methodName + '(localsDict=locals())'
549
550 if silentMode:
551 self.addChunk('try:')
552 self.indent()
553 self.addFilteredChunk(expr, filterArgs, rawPlaceholder,
554 lineCol=lineCol)
555 self.dedent()
556 self.addChunk('except NotFound: pass')
557 else:
558 self.addFilteredChunk(expr, filterArgs, rawPlaceholder,
559 lineCol=lineCol)
560
561 if self.setting('outputRowColComments'):
562 self.appendToPrevChunk(' # from line %s, col %s' % lineCol + '.')
563 if cacheInfo:
564 self.endCacheRegion()
565
566 def addSilent(self, expr):
567 self.addChunk(expr)
568
569 def addEcho(self, expr, rawExpr=None):
570 self.addFilteredChunk(expr, rawExpr=rawExpr)
571
572 def addSet(self, expr, exprComponents, setStyle):
573 if setStyle is SET_GLOBAL:
574 (LVALUE, OP, RVALUE) = (exprComponents.LVALUE,
575 exprComponents.OP,
576 exprComponents.RVALUE)
577 # we need to split the LVALUE to deal with globalSetVars
578 splitPos1 = LVALUE.find('.')
579 splitPos2 = LVALUE.find('[')
580 if splitPos1 > 0 and splitPos2 == -1:
581 splitPos = splitPos1
582 elif splitPos1 > 0 and splitPos1 < max(splitPos2, 0):
583 splitPos = splitPos1
584 else:
585 splitPos = splitPos2
586
587 if splitPos > 0:
588 primary = LVALUE[:splitPos]
589 secondary = LVALUE[splitPos:]
590 else:
591 primary = LVALUE
592 secondary = ''
593 LVALUE = \
594 'self._CHEETAH__globalSetVars["' + primary + '"]' + secondary
595 expr = LVALUE + ' ' + OP + ' ' + RVALUE.strip()
596
597 if setStyle is SET_MODULE:
598 self._moduleCompiler.addModuleGlobal(expr)
599 else:
600 self.addChunk(expr)
601
602 def addInclude(self, sourceExpr, includeFrom, isRaw):
603 self.addChunk('self._handleCheetahInclude(' + sourceExpr
604 + ', trans=trans, '
605 + 'includeFrom="' + includeFrom + '", raw='
606 + repr(isRaw) + ')')
607
608 def addWhile(self, expr, lineCol=None):
609 self.addIndentingDirective(expr, lineCol=lineCol)
610
611 def addFor(self, expr, lineCol=None):
612 self.addIndentingDirective(expr, lineCol=lineCol)
613
614 def addRepeat(self, expr, lineCol=None):
615 # the _repeatCount stuff here allows nesting of #repeat directives
616 self._repeatCount = getattr(self, "_repeatCount", -1) + 1
617 self.addFor('for __i%s in range(%s)'
618 % (self._repeatCount, expr),
619 lineCol=lineCol)
620
621 def addIndentingDirective(self, expr, lineCol=None):
622 if expr and not expr[-1] == ':':
623 expr = expr + ':'
624 self.addChunk(expr)
625 if lineCol:
626 self.appendToPrevChunk(' # generated from line %s, col %s'
627 % lineCol)
628 self.indent()
629
630 def addReIndentingDirective(self, expr, dedent=True, lineCol=None):
631 self.commitStrConst()
632 if dedent:
633 self.dedent()
634 if not expr[-1] == ':':
635 expr = expr + ':'
636
637 self.addChunk(expr)
638 if lineCol:
639 self.appendToPrevChunk(' # generated from line %s, col %s'
640 % lineCol)
641 self.indent()
642
643 def addIf(self, expr, lineCol=None):
644 """For a full #if ... #end if directive
645 """
646 self.addIndentingDirective(expr, lineCol=lineCol)
647
648 def addOneLineIf(self, expr, lineCol=None):
649 """For a full #if ... #end if directive
650 """
651 self.addIndentingDirective(expr, lineCol=lineCol)
652
653 def addTernaryExpr(self, conditionExpr, trueExpr, falseExpr, lineCol=None):
654 """For a single-lie #if ... then .... else ... directive
655 <condition> then <trueExpr> else <falseExpr>
656 """
657 self.addIndentingDirective(conditionExpr, lineCol=lineCol)
658 self.addFilteredChunk(trueExpr)
659 self.dedent()
660 self.addIndentingDirective('else')
661 self.addFilteredChunk(falseExpr)
662 self.dedent()
663
664 def addElse(self, expr, dedent=True, lineCol=None):
665 expr = re.sub(r'else[ \f\t]+if', 'elif', expr)
666 self.addReIndentingDirective(expr, dedent=dedent, lineCol=lineCol)
667
668 def addElif(self, expr, dedent=True, lineCol=None):
669 self.addElse(expr, dedent=dedent, lineCol=lineCol)
670
671 def addUnless(self, expr, lineCol=None):
672 self.addIf('if not (' + expr + ')')
673
674 def addClosure(self, functionName, argsList, parserComment):
675 argStringChunks = []
676 for arg in argsList:
677 chunk = arg[0]
678 if arg[1] is not None:
679 chunk += '=' + arg[1]
680 argStringChunks.append(chunk)
681 signature = \
682 "def " + functionName + "(" + ','.join(argStringChunks) + "):"
683 self.addIndentingDirective(signature)
684 self.addChunk('#' + parserComment)
685
686 def addTry(self, expr, lineCol=None):
687 self.addIndentingDirective(expr, lineCol=lineCol)
688
689 def addExcept(self, expr, dedent=True, lineCol=None):
690 self.addReIndentingDirective(expr, dedent=dedent, lineCol=lineCol)
691
692 def addFinally(self, expr, dedent=True, lineCol=None):
693 self.addReIndentingDirective(expr, dedent=dedent, lineCol=lineCol)
694
695 def addReturn(self, expr):
696 assert not self._isGenerator
697 self.addChunk(expr)
698 self._hasReturnStatement = True
699
700 def addYield(self, expr):
701 assert not self._hasReturnStatement
702 self._isGenerator = True
703 if expr.replace('yield', '').strip():
704 self.addChunk(expr)
705 else:
706 self.addChunk('if _dummyTrans:')
707 self.indent()
708 self.addChunk('yield trans.response().getvalue()')
709 self.addChunk('trans = DummyTransaction()')
710 self.addChunk('write = trans.response().write')
711 self.dedent()
712 self.addChunk('else:')
713 self.indent()
714 self.addChunk('raise TypeError('
715 '"This method cannot be called with a trans arg")')
716 self.dedent()
717
718 def addPass(self, expr):
719 self.addChunk(expr)
720
721 def addDel(self, expr):
722 self.addChunk(expr)
723
724 def addAssert(self, expr):
725 self.addChunk(expr)
726
727 def addRaise(self, expr):
728 self.addChunk(expr)
729
730 def addBreak(self, expr):
731 self.addChunk(expr)
732
733 def addContinue(self, expr):
734 self.addChunk(expr)
735
736 def addPSP(self, PSP):
737 self.commitStrConst()
738 autoIndent = False
739 if PSP[0] == '=':
740 PSP = PSP[1:]
741 if PSP:
742 self.addWriteChunk('_filter(' + PSP + ')')
743 return
744
745 elif PSP.lower() == 'end':
746 self.dedent()
747 return
748 elif PSP[-1] == '$':
749 autoIndent = True
750 PSP = PSP[:-1]
751 elif PSP[-1] == ':':
752 autoIndent = True
753
754 for line in PSP.splitlines():
755 self.addChunk(line)
756
757 if autoIndent:
758 self.indent()
759
760 def nextCacheID(self):
761 return ('_' + str(random.randrange(100, 999))
762 + str(random.randrange(10000, 99999)))
763
764 def startCacheRegion(self, cacheInfo, lineCol, rawPlaceholder=None):
765
766 # @@TR: we should add some runtime logging to this
767
768 ID = self.nextCacheID()
769 interval = cacheInfo.get('interval', None)
770 test = cacheInfo.get('test', None)
771 customID = cacheInfo.get('id', None)
772 if customID:
773 ID = customID
774 varyBy = cacheInfo.get('varyBy', repr(ID))
775 self._cacheRegionsStack.append(ID) # attrib of current methodCompiler
776
777 # @@TR: add this to a special class var as well
778 self.addChunk('')
779
780 self.addChunk('## START CACHE REGION: ID=' + ID
781 + '. line %s, col %s' % lineCol + ' in the source.')
782
783 self.addChunk('_RECACHE_%(ID)s = False' % locals())
784 self.addChunk('_cacheRegion_%(ID)s = self.getCacheRegion(regionID='
785 % locals()
786 + repr(ID)
787 + ', cacheInfo=%r' % cacheInfo
788 + ')')
789 self.addChunk('if _cacheRegion_%(ID)s.isNew():' % locals())
790 self.indent()
791 self.addChunk('_RECACHE_%(ID)s = True' % locals())
792 self.dedent()
793
794 self.addChunk('_cacheItem_%(ID)s = _cacheRegion_%(ID)s.getCacheItem('
795 % locals()
796 + varyBy + ')')
797
798 self.addChunk('if _cacheItem_%(ID)s.hasExpired():' % locals())
799 self.indent()
800 self.addChunk('_RECACHE_%(ID)s = True' % locals())
801 self.dedent()
802
803 if test:
804 self.addChunk('if ' + test + ':')
805 self.indent()
806 self.addChunk('_RECACHE_%(ID)s = True' % locals())
807 self.dedent()
808
809 self.addChunk(
810 'if (not _RECACHE_%(ID)s) and _cacheItem_%(ID)s.getRefreshTime():'
811 % locals())
812 self.indent()
813 self.addChunk('try:')
814 self.indent()
815 self.addChunk('_output = _cacheItem_%(ID)s.renderOutput()' % locals())
816 self.dedent()
817 self.addChunk('except KeyError:')
818 self.indent()
819 self.addChunk('_RECACHE_%(ID)s = True' % locals())
820 self.dedent()
821 self.addChunk('else:')
822 self.indent()
823 self.addWriteChunk('_output')
824 self.addChunk('del _output')
825 self.dedent()
826
827 self.dedent()
828
829 self.addChunk(
830 'if _RECACHE_%(ID)s or not _cacheItem_%(ID)s.getRefreshTime():'
831 % locals())
832 self.indent()
833 self.addChunk('_orig_trans%(ID)s = trans' % locals())
834 self.addChunk('trans = _cacheCollector_%(ID)s = DummyTransaction()'
835 % locals())
836 self.addChunk('write = _cacheCollector_%(ID)s.response().write'
837 % locals())
838 if interval:
839 self.addChunk(("_cacheItem_%(ID)s.setExpiryTime(currentTime() +"
840 % locals())
841 + str(interval) + ")")
842
843 def endCacheRegion(self):
844 ID = self._cacheRegionsStack.pop()
845 self.addChunk('trans = _orig_trans%(ID)s' % locals())
846 self.addChunk('write = trans.response().write')
847 self.addChunk(
848 '_cacheData = _cacheCollector_%(ID)s.response().getvalue()'
849 % locals())
850 self.addChunk('_cacheItem_%(ID)s.setData(_cacheData)' % locals())
851 self.addWriteChunk('_cacheData')
852 self.addChunk('del _cacheData')
853 self.addChunk('del _cacheCollector_%(ID)s' % locals())
854 self.addChunk('del _orig_trans%(ID)s' % locals())
855 self.dedent()
856 self.addChunk('## END CACHE REGION: ' + ID)
857 self.addChunk('')
858
859 def nextCallRegionID(self):
860 return self.nextCacheID()
861
862 def startCallRegion(self, functionName, args, lineCol, regionTitle='CALL'):
863 class CallDetails(object):
864 pass
865 callDetails = CallDetails()
866 callDetails.ID = ID = self.nextCallRegionID()
867 callDetails.functionName = functionName
868 callDetails.args = args
869 callDetails.lineCol = lineCol
870 callDetails.usesKeywordArgs = False
871 # attrib of current methodCompiler
872 self._callRegionsStack.append((ID, callDetails))
873
874 self.addChunk('## START %(regionTitle)s REGION: ' % locals() + ID
875 + ' of ' + functionName
876 + ' at line %s, col %s' % lineCol + ' in the source.')
877 self.addChunk('_orig_trans%(ID)s = trans' % locals())
878 self.addChunk('_wasBuffering%(ID)s = self._CHEETAH__isBuffering'
879 % locals())
880 self.addChunk('self._CHEETAH__isBuffering = True')
881 self.addChunk('trans = _callCollector%(ID)s = DummyTransaction()'
882 % locals())
883 self.addChunk('write = _callCollector%(ID)s.response().write'
884 % locals())
885
886 def setCallArg(self, argName, lineCol):
887 ID, callDetails = self._callRegionsStack[-1]
888 argName = str(argName)
889 if callDetails.usesKeywordArgs:
890 self._endCallArg()
891 else:
892 callDetails.usesKeywordArgs = True
893 self.addChunk('_callKws%(ID)s = {}' % locals())
894 self.addChunk('_currentCallArgname%(ID)s = %(argName)r' % locals())
895 callDetails.currentArgname = argName
896
897 def _endCallArg(self):
898 ID, callDetails = self._callRegionsStack[-1]
899 currCallArg = callDetails.currentArgname
900 self.addChunk('_callKws%(ID)s[%(currCallArg)r] ='
901 ' _callCollector%(ID)s.response().getvalue()'
902 % locals())
903 self.addChunk('del _callCollector%(ID)s' % locals())
904 self.addChunk('trans = _callCollector%(ID)s = DummyTransaction()'
905 % locals())
906 self.addChunk('write = _callCollector%(ID)s.response().write'
907 % locals())
908
909 def endCallRegion(self, regionTitle='CALL'):
910 ID, callDetails = self._callRegionsStack[-1]
911 functionName, initialKwArgs, lineCol = (
912 callDetails.functionName, callDetails.args, callDetails.lineCol)
913
914 def reset(ID=ID):
915 self.addChunk('trans = _orig_trans%(ID)s' % locals())
916 self.addChunk('write = trans.response().write')
917 self.addChunk('self._CHEETAH__isBuffering = _wasBuffering%(ID)s '
918 % locals())
919 self.addChunk('del _wasBuffering%(ID)s' % locals())
920 self.addChunk('del _orig_trans%(ID)s' % locals())
921
922 if not callDetails.usesKeywordArgs:
923 reset()
924 self.addChunk(
925 '_callArgVal%(ID)s = '
926 '_callCollector%(ID)s.response().getvalue()' % locals())
927 self.addChunk('del _callCollector%(ID)s' % locals())
928 if initialKwArgs:
929 initialKwArgs = ', ' + initialKwArgs
930 self.addFilteredChunk(
931 '%(functionName)s(_callArgVal%(ID)s%(initialKwArgs)s)'
932 % locals())
933 self.addChunk('del _callArgVal%(ID)s' % locals())
934 else:
935 if initialKwArgs:
936 initialKwArgs = initialKwArgs + ', '
937 self._endCallArg()
938 reset()
939 self.addFilteredChunk(
940 '%(functionName)s(%(initialKwArgs)s**_callKws%(ID)s)'
941 % locals())
942 self.addChunk('del _callKws%(ID)s' % locals())
943 self.addChunk('## END %(regionTitle)s REGION: ' % locals() + ID
944 + ' of ' + functionName
945 + ' at line %s, col %s' % lineCol + ' in the source.')
946 self.addChunk('')
947 self._callRegionsStack.pop() # attrib of current methodCompiler
948
949 def nextCaptureRegionID(self):
950 return self.nextCacheID()
951
952 def startCaptureRegion(self, assignTo, lineCol):
953 class CaptureDetails:
954 pass
955 captureDetails = CaptureDetails()
956 captureDetails.ID = ID = self.nextCaptureRegionID()
957 captureDetails.assignTo = assignTo
958 captureDetails.lineCol = lineCol
959
960 # attrib of current methodCompiler
961 self._captureRegionsStack.append((ID, captureDetails))
962 self.addChunk('## START CAPTURE REGION: ' + ID + ' ' + assignTo
963 + ' at line %s, col %s' % lineCol + ' in the source.')
964 self.addChunk('_orig_trans%(ID)s = trans' % locals())
965 self.addChunk(
966 '_wasBuffering%(ID)s = self._CHEETAH__isBuffering' % locals())
967 self.addChunk('self._CHEETAH__isBuffering = True')
968 self.addChunk(
969 'trans = _captureCollector%(ID)s = DummyTransaction()' % locals())
970 self.addChunk(
971 'write = _captureCollector%(ID)s.response().write' % locals())
972
973 def endCaptureRegion(self):
974 ID, captureDetails = self._captureRegionsStack.pop()
975 assignTo, lineCol = (captureDetails.assignTo, captureDetails.lineCol)
976 self.addChunk('trans = _orig_trans%(ID)s' % locals())
977 self.addChunk('write = trans.response().write')
978 self.addChunk(
979 'self._CHEETAH__isBuffering = _wasBuffering%(ID)s ' % locals())
980 self.addChunk(
981 '%(assignTo)s = _captureCollector%(ID)s.response().getvalue()'
982 % locals())
983 self.addChunk('del _orig_trans%(ID)s' % locals())
984 self.addChunk('del _captureCollector%(ID)s' % locals())
985 self.addChunk('del _wasBuffering%(ID)s' % locals())
986
987 def setErrorCatcher(self, errorCatcherName):
988 self.turnErrorCatcherOn()
989
990 self.addChunk(
991 'if "' + errorCatcherName + '" in self._CHEETAH__errorCatchers:')
992 self.indent()
993 self.addChunk(
994 'self._CHEETAH__errorCatcher = self._CHEETAH__errorCatchers["'
995 + errorCatcherName + '"]')
996 self.dedent()
997 self.addChunk('else:')
998 self.indent()
999 self.addChunk(
1000 'self._CHEETAH__errorCatcher = self._CHEETAH__errorCatchers["'
1001 + errorCatcherName + '"] = ErrorCatchers.'
1002 + errorCatcherName + '(self)'
1003 )
1004 self.dedent()
1005
1006 def nextFilterRegionID(self):
1007 return self.nextCacheID()
1008
1009 def setTransform(self, transformer, isKlass):
1010 self.addChunk('trans = TransformerTransaction()')
1011 self.addChunk('trans._response = trans.response()')
1012 self.addChunk('trans._response._filter = %s' % transformer)
1013 self.addChunk('write = trans._response.write')
1014
1015 def setFilter(self, theFilter, isKlass):
1016 class FilterDetails:
1017 pass
1018 filterDetails = FilterDetails()
1019 filterDetails.ID = ID = self.nextFilterRegionID()
1020 filterDetails.theFilter = theFilter
1021 filterDetails.isKlass = isKlass
1022 # attrib of current methodCompiler
1023 self._filterRegionsStack.append((ID, filterDetails))
1024
1025 self.addChunk('_orig_filter%(ID)s = _filter' % locals())
1026 if isKlass:
1027 self.addChunk(
1028 '_filter = self._CHEETAH__currentFilter = '
1029 + theFilter.strip() + '(self).filter')
1030 else:
1031 if theFilter.lower() == 'none':
1032 self.addChunk('_filter = self._CHEETAH__initialFilter')
1033 else:
1034 # is string representing the name of a builtin filter
1035 self.addChunk('filterName = ' + repr(theFilter))
1036 self.addChunk(
1037 'if "' + theFilter + '" in self._CHEETAH__filters:')
1038 self.indent()
1039 self.addChunk(
1040 '_filter = self._CHEETAH__currentFilter = '
1041 'self._CHEETAH__filters[filterName]')
1042 self.dedent()
1043 self.addChunk('else:')
1044 self.indent()
1045 self.addChunk(
1046 '_filter = self._CHEETAH__currentFilter'
1047 + ' = \\\n\t\t\tself._CHEETAH__filters[filterName] = '
1048 + 'getattr(self._CHEETAH__filtersLib, filterName)'
1049 + '(self).filter')
1050 self.dedent()
1051
1052 def closeFilterBlock(self):
1053 ID, filterDetails = self._filterRegionsStack.pop()
1054 # self.addChunk('_filter = self._CHEETAH__initialFilter')
1055 # self.addChunk('_filter = _orig_filter%(ID)s'%locals())
1056 self.addChunk(
1057 '_filter = self._CHEETAH__currentFilter = _orig_filter%(ID)s'
1058 % locals())
1059
1060
1061 class AutoMethodCompiler(MethodCompiler):
1062
1063 def _setupState(self):
1064 MethodCompiler._setupState(self)
1065 self._argStringList = [("self", None)]
1066 self._streamingEnabled = True
1067 self._isClassMethod = None
1068 self._isStaticMethod = None
1069
1070 def _useKWsDictArgForPassingTrans(self):
1071 alreadyHasTransArg = [
1072 argname for argname, defval in self._argStringList
1073 if argname == 'trans']
1074 return (self.methodName() != 'respond'
1075 and not alreadyHasTransArg
1076 and self.setting('useKWsDictArgForPassingTrans'))
1077
1078 def isClassMethod(self):
1079 if self._isClassMethod is None:
1080 self._isClassMethod = '@classmethod' in self._decorators
1081 return self._isClassMethod
1082
1083 def isStaticMethod(self):
1084 if self._isStaticMethod is None:
1085 self._isStaticMethod = '@staticmethod' in self._decorators
1086 return self._isStaticMethod
1087
1088 def cleanupState(self):
1089 MethodCompiler.cleanupState(self)
1090 self.commitStrConst()
1091 if self._cacheRegionsStack:
1092 self.endCacheRegion()
1093 if self._callRegionsStack:
1094 self.endCallRegion()
1095
1096 if self._streamingEnabled:
1097 kwargsName = None
1098 positionalArgsListName = None
1099 for argname, defval in self._argStringList:
1100 if argname.strip().startswith('**'):
1101 kwargsName = argname.strip().replace('**', '')
1102 break
1103 elif argname.strip().startswith('*'):
1104 positionalArgsListName = argname.strip().replace('*', '')
1105
1106 if not kwargsName and self._useKWsDictArgForPassingTrans():
1107 kwargsName = 'KWS'
1108 self.addMethArg('**KWS', None)
1109 self._kwargsName = kwargsName
1110
1111 if not self._useKWsDictArgForPassingTrans():
1112 if not kwargsName and not positionalArgsListName:
1113 self.addMethArg('trans', 'None')
1114 else:
1115 self._streamingEnabled = False
1116
1117 self._indentLev = self.setting('initialMethIndentLevel')
1118 mainBodyChunks = self._methodBodyChunks
1119 self._methodBodyChunks = []
1120 self._addAutoSetupCode()
1121 self._methodBodyChunks.extend(mainBodyChunks)
1122 self._addAutoCleanupCode()
1123
1124 def _addAutoSetupCode(self):
1125 if self._initialMethodComment:
1126 self.addChunk(self._initialMethodComment)
1127
1128 if self._streamingEnabled and \
1129 not self.isClassMethod() and not self.isStaticMethod():
1130 if self._useKWsDictArgForPassingTrans() and self._kwargsName:
1131 self.addChunk('trans = %s.get("trans")' % self._kwargsName)
1132 self.addChunk('if (not trans and not self._CHEETAH__isBuffering'
1133 ' and not callable(self.transaction)):')
1134 self.indent()
1135 self.addChunk('trans = self.transaction'
1136 ' # is None unless self.awake() was called')
1137 self.dedent()
1138 self.addChunk('if not trans:')
1139 self.indent()
1140 self.addChunk('trans = DummyTransaction()')
1141 if self.setting('autoAssignDummyTransactionToSelf'):
1142 self.addChunk('self.transaction = trans')
1143 self.addChunk('_dummyTrans = True')
1144 self.dedent()
1145 self.addChunk('else: _dummyTrans = False')
1146 else:
1147 self.addChunk('trans = DummyTransaction()')
1148 self.addChunk('_dummyTrans = True')
1149 self.addChunk('write = trans.response().write')
1150 if self.setting('useNameMapper'):
1151 argNames = [arg[0] for arg in self._argStringList]
1152 allowSearchListAsMethArg = self.setting('allowSearchListAsMethArg')
1153 if allowSearchListAsMethArg and 'SL' in argNames:
1154 pass
1155 elif allowSearchListAsMethArg and 'searchList' in argNames:
1156 self.addChunk('SL = searchList')
1157 elif not self.isClassMethod() and not self.isStaticMethod():
1158 self.addChunk('SL = self._CHEETAH__searchList')
1159 else:
1160 self.addChunk('SL = [KWS]')
1161 if self.setting('useFilters'):
1162 if self.isClassMethod() or self.isStaticMethod():
1163 self.addChunk('_filter = lambda x, **kwargs: unicode(x)')
1164 else:
1165 self.addChunk('_filter = self._CHEETAH__currentFilter')
1166 self.addChunk('')
1167 self.addChunk("#"*40) # noqa: E226 missing whitespace around operator
1168 self.addChunk('## START - generated method body')
1169 self.addChunk('')
1170
1171 def _addAutoCleanupCode(self):
1172 self.addChunk('')
1173 self.addChunk("#"*40) # noqa: E226 missing whitespace around operator
1174 self.addChunk('## END - generated method body')
1175 self.addChunk('')
1176
1177 if not self._isGenerator:
1178 self.addStop()
1179 self.addChunk('')
1180
1181 def addStop(self, expr=None):
1182 self.addChunk(
1183 'return _dummyTrans and trans.response().getvalue() or ""')
1184
1185 def addMethArg(self, name, defVal=None):
1186 self._argStringList.append((name, defVal))
1187
1188 def methodSignature(self):
1189 argStringChunks = []
1190 for arg in self._argStringList:
1191 chunk = arg[0]
1192 if chunk == 'self' and self.isClassMethod():
1193 chunk = 'cls'
1194 if chunk == 'self' and self.isStaticMethod():
1195 # Skip the "self" method for @staticmethod decorators
1196 continue
1197 if arg[1] is not None:
1198 chunk += '=' + arg[1]
1199 argStringChunks.append(chunk)
1200 argString = (', ').join(argStringChunks)
1201
1202 output = []
1203 if self._decorators:
1204 output.append(''.join([self._indent + decorator + '\n'
1205 for decorator in self._decorators]))
1206 output.append(self._indent + "def "
1207 + self.methodName() + "("
1208 + argString + "):\n\n")
1209 return ''.join(output)
1210
1211
1212 ##################################################
1213 # CLASS COMPILERS
1214
1215 _initMethod_initCheetah = """\
1216 if not self._CHEETAH__instanceInitialized:
1217 cheetahKWArgs = {}
1218 allowedKWs = 'searchList namespaces filter filtersLib errorCatcher'.split()
1219 for k,v in KWs.items():
1220 if k in allowedKWs: cheetahKWArgs[k] = v
1221 self._initCheetahInstance(**cheetahKWArgs)
1222 """.replace('\n', '\n' + ' '*8) # noqa: E226,E501 missing whitespace around operator
1223
1224
1225 class ClassCompiler(GenUtils):
1226 methodCompilerClass = AutoMethodCompiler
1227 methodCompilerClassForInit = MethodCompiler
1228
1229 def __init__(self, className, mainMethodName='respond',
1230 moduleCompiler=None,
1231 fileName=None,
1232 settingsManager=None):
1233
1234 self._settingsManager = settingsManager
1235 self._fileName = fileName
1236 self._className = className
1237 self._moduleCompiler = moduleCompiler
1238 self._mainMethodName = mainMethodName
1239 self._setupState()
1240 methodCompiler = self._spawnMethodCompiler(
1241 mainMethodName,
1242 initialMethodComment='## CHEETAH: main method '
1243 'generated for this template')
1244
1245 self._setActiveMethodCompiler(methodCompiler)
1246 if fileName and self.setting('monitorSrcFile'):
1247 self._addSourceFileMonitoring(fileName)
1248
1249 def setting(self, key):
1250 return self._settingsManager.setting(key)
1251
1252 def __getattr__(self, name):
1253 """Provide access to the methods and attributes of the MethodCompiler
1254 at the top of the activeMethods stack: one-way namespace sharing
1255
1256
1257 WARNING: Use .setMethods to assign the attributes of the MethodCompiler
1258 from the methods of this class!!! or you will be assigning to
1259 attributes of this object instead.
1260 """
1261 if name in self.__dict__:
1262 return self.__dict__[name]
1263 elif hasattr(self.__class__, name):
1264 return getattr(self.__class__, name)
1265 elif self._activeMethodsList and \
1266 hasattr(self._activeMethodsList[-1], name):
1267 return getattr(self._activeMethodsList[-1], name)
1268 else:
1269 raise AttributeError(name)
1270
1271 def _setupState(self):
1272 self._classDef = None
1273 self._decoratorsForNextMethod = []
1274 self._activeMethodsList = [] # stack while parsing/generating
1275 self._finishedMethodsList = [] # store by order
1276 self._methodsIndex = {} # store by name
1277 self._baseClass = 'Template'
1278 self._classDocStringLines = []
1279 # printed after methods in the gen class def:
1280 self._generatedAttribs = ['_CHEETAH__instanceInitialized = False']
1281 self._generatedAttribs.append('_CHEETAH_version = __CHEETAH_version__')
1282 self._generatedAttribs.append(
1283 '_CHEETAH_versionTuple = __CHEETAH_versionTuple__')
1284
1285 if self.setting('addTimestampsToCompilerOutput'):
1286 self._generatedAttribs.append(
1287 '_CHEETAH_genTime = __CHEETAH_genTime__')
1288 self._generatedAttribs.append(
1289 '_CHEETAH_genTimestamp = __CHEETAH_genTimestamp__')
1290
1291 self._generatedAttribs.append('_CHEETAH_src = __CHEETAH_src__')
1292 self._generatedAttribs.append(
1293 '_CHEETAH_srcLastModified = __CHEETAH_srcLastModified__')
1294
1295 if self.setting('templateMetaclass'):
1296 self._generatedAttribs.append(
1297 '__metaclass__ = ' + self.setting('templateMetaclass'))
1298 self._initMethChunks = []
1299 self._blockMetaData = {}
1300 self._errorCatcherCount = 0
1301 self._placeholderToErrorCatcherMap = {}
1302
1303 def cleanupState(self):
1304 while self._activeMethodsList:
1305 methCompiler = self._popActiveMethodCompiler()
1306 self._swallowMethodCompiler(methCompiler)
1307 self._setupInitMethod()
1308 if self._mainMethodName == 'respond':
1309 if self.setting('setup__str__method'):
1310 self._generatedAttribs.append(
1311 'def __str__(self): return self.respond()')
1312 self.addAttribute(
1313 '_mainCheetahMethod_for_' + self._className
1314 + ' = ' + repr(self._mainMethodName))
1315
1316 def _setupInitMethod(self):
1317 __init__ = self._spawnMethodCompiler(
1318 '__init__', klass=self.methodCompilerClassForInit)
1319 __init__.setMethodSignature("def __init__(self, *args, **KWs)")
1320 __init__.addChunk(
1321 'super(%s, self).__init__(*args, **KWs)' % self._className)
1322 __init__.addChunk(
1323 _initMethod_initCheetah % {'className': self._className})
1324 for chunk in self._initMethChunks:
1325 __init__.addChunk(chunk)
1326 __init__.cleanupState()
1327 self._swallowMethodCompiler(__init__, pos=0)
1328
1329 def _addSourceFileMonitoring(self, fileName):
1330 # @@TR: this stuff needs auditing for Cheetah 2.0
1331 # the first bit is added to init
1332 self.addChunkToInit('self._filePath = ' + repr(fileName))
1333 self.addChunkToInit('self._fileMtime = ' + str(getmtime(fileName)))
1334
1335 # the rest is added to the main output method of the class
1336 # ('mainMethod')
1337 self.addChunk(
1338 'if exists(self._filePath) and '
1339 + 'getmtime(self._filePath) > self._fileMtime:')
1340 self.indent()
1341 self.addChunk(
1342 'self._compile(file=self._filePath, moduleName='
1343 + self._className + ')')
1344 self.addChunk(
1345 'write(getattr(self, self._mainCheetahMethod_for_'
1346 + self._className + ')(trans=trans))')
1347 self.addStop()
1348 self.dedent()
1349
1350 def setClassName(self, name):
1351 self._className = name
1352
1353 def className(self):
1354 return self._className
1355
1356 def setBaseClass(self, baseClassName):
1357 self._baseClass = baseClassName
1358
1359 def setMainMethodName(self, methodName):
1360 if methodName == self._mainMethodName:
1361 return
1362 # change the name in the methodCompiler and add new reference
1363 mainMethod = self._methodsIndex[self._mainMethodName]
1364 mainMethod.setMethodName(methodName)
1365 self._methodsIndex[methodName] = mainMethod
1366
1367 # make sure that fileUpdate code still works properly:
1368 chunkToChange = (
1369 'write(self.' + self._mainMethodName + '(trans=trans))')
1370 chunks = mainMethod._methodBodyChunks
1371 if chunkToChange in chunks:
1372 for i in range(len(chunks)):
1373 if chunks[i] == chunkToChange:
1374 chunks[i] = ('write(self.' + methodName + '(trans=trans))')
1375 # get rid of the old reference and update self._mainMethodName
1376 del self._methodsIndex[self._mainMethodName]
1377 self._mainMethodName = methodName
1378
1379 def setMainMethodArgs(self, argsList):
1380 mainMethodCompiler = self._methodsIndex[self._mainMethodName]
1381 for argName, defVal in argsList:
1382 mainMethodCompiler.addMethArg(argName, defVal)
1383
1384 def _spawnMethodCompiler(self, methodName, klass=None,
1385 initialMethodComment=None):
1386 if klass is None:
1387 klass = self.methodCompilerClass
1388
1389 decorators = self._decoratorsForNextMethod or []
1390 self._decoratorsForNextMethod = []
1391 methodCompiler = klass(methodName, classCompiler=self,
1392 decorators=decorators,
1393 initialMethodComment=initialMethodComment)
1394 self._methodsIndex[methodName] = methodCompiler
1395 return methodCompiler
1396
1397 def _setActiveMethodCompiler(self, methodCompiler):
1398 self._activeMethodsList.append(methodCompiler)
1399
1400 def _getActiveMethodCompiler(self):
1401 return self._activeMethodsList[-1]
1402
1403 def _popActiveMethodCompiler(self):
1404 return self._activeMethodsList.pop()
1405
1406 def _swallowMethodCompiler(self, methodCompiler, pos=None):
1407 methodCompiler.cleanupState()
1408 if pos is None:
1409 self._finishedMethodsList.append(methodCompiler)
1410 else:
1411 self._finishedMethodsList.insert(pos, methodCompiler)
1412 return methodCompiler
1413
1414 def startMethodDef(self, methodName, argsList, parserComment):
1415 methodCompiler = self._spawnMethodCompiler(
1416 methodName, initialMethodComment=parserComment)
1417 self._setActiveMethodCompiler(methodCompiler)
1418 for argName, defVal in argsList:
1419 methodCompiler.addMethArg(argName, defVal)
1420
1421 def _finishedMethods(self):
1422 return self._finishedMethodsList
1423
1424 def addDecorator(self, decoratorExpr):
1425 """Set the decorator to be used with the next method in the source.
1426
1427 See _spawnMethodCompiler() and MethodCompiler for the details of how
1428 this is used.
1429 """
1430 self._decoratorsForNextMethod.append(decoratorExpr)
1431
1432 def addClassDocString(self, line):
1433 self._classDocStringLines.append(line.replace('%', '%%'))
1434
1435 def addChunkToInit(self, chunk):
1436 self._initMethChunks.append(chunk)
1437
1438 def addAttribute(self, attribExpr):
1439 # First test to make sure that the user hasn't used
1440 # any fancy Cheetah syntax (placeholders, directives, etc.)
1441 # inside the expression
1442 if attribExpr.find('VFN(') != -1 or attribExpr.find('VFFSL(') != -1:
1443 raise ParseError(
1444 self,
1445 'Invalid #attr directive. It should only contain '
1446 + 'simple Python literals.')
1447 # now add the attribute
1448 self._generatedAttribs.append(attribExpr)
1449
1450 def addSuper(self, argsList, parserComment=None):
1451 className = self._className # self._baseClass
1452 methodName = self._getActiveMethodCompiler().methodName()
1453
1454 argStringChunks = []
1455 for arg in argsList:
1456 chunk = arg[0]
1457 if arg[1] is not None:
1458 chunk += '=' + arg[1]
1459 argStringChunks.append(chunk)
1460 argString = ','.join(argStringChunks)
1461
1462 self.addFilteredChunk(
1463 'super(%(className)s, self).%(methodName)s(%(argString)s)'
1464 % locals())
1465
1466 def addErrorCatcherCall(self, codeChunk, rawCode='', lineCol=''):
1467 if rawCode in self._placeholderToErrorCatcherMap:
1468 methodName = self._placeholderToErrorCatcherMap[rawCode]
1469 if not self.setting('outputRowColComments'):
1470 self._methodsIndex[methodName].addMethDocString(
1471 'plus at line %s, col %s' % lineCol)
1472 return methodName
1473
1474 self._errorCatcherCount += 1
1475 methodName = '__errorCatcher' + str(self._errorCatcherCount)
1476 self._placeholderToErrorCatcherMap[rawCode] = methodName
1477
1478 catcherMeth = self._spawnMethodCompiler(
1479 methodName,
1480 klass=MethodCompiler,
1481 initialMethodComment=(
1482 '## CHEETAH: Generated from ' + rawCode
1483 + ' at line %s, col %s' % lineCol + '.')
1484 )
1485 catcherMeth.setMethodSignature(
1486 'def ' + methodName
1487 + '(self, localsDict={})') # is this use of localsDict right?
1488 catcherMeth.addChunk('try:')
1489 catcherMeth.indent()
1490 catcherMeth.addChunk(
1491 "return eval('''" + codeChunk + "''', globals(), localsDict)")
1492 catcherMeth.dedent()
1493 catcherMeth.addChunk(
1494 'except self._CHEETAH__errorCatcher.exceptions() as e:')
1495 catcherMeth.indent()
1496 catcherMeth.addChunk(
1497 "return self._CHEETAH__errorCatcher.warn(exc_val=e, code= "
1498 + repr(codeChunk) + " , rawCode= "
1499 + repr(rawCode) + " , lineCol=" + str(lineCol) + ")")
1500
1501 catcherMeth.cleanupState()
1502
1503 self._swallowMethodCompiler(catcherMeth)
1504 return methodName
1505
1506 def closeDef(self):
1507 self.commitStrConst()
1508 methCompiler = self._popActiveMethodCompiler()
1509 self._swallowMethodCompiler(methCompiler)
1510
1511 def closeBlock(self):
1512 self.commitStrConst()
1513 methCompiler = self._popActiveMethodCompiler()
1514 methodName = methCompiler.methodName()
1515 if self.setting('includeBlockMarkers'):
1516 endMarker = self.setting('blockMarkerEnd')
1517 methCompiler.addStrConst(endMarker[0] + methodName + endMarker[1])
1518 self._swallowMethodCompiler(methCompiler)
1519
1520 # metaData = self._blockMetaData[methodName]
1521 # rawDirective = metaData['raw']
1522 # lineCol = metaData['lineCol']
1523
1524 # insert the code to call the block, caching if #cache directive is on
1525 codeChunk = 'self.' + methodName + '(trans=trans)'
1526 self.addChunk(codeChunk)
1527
1528 # self.appendToPrevChunk(' # generated from ' + repr(rawDirective) )
1529 # if self.setting('outputRowColComments'):
1530 # self.appendToPrevChunk(' at line %s, col %s' % lineCol + '.')
1531
1532 # code wrapping methods
1533
1534 def classDef(self):
1535 if self._classDef:
1536 return self._classDef
1537 else:
1538 return self.wrapClassDef()
1539
1540 __str__ = classDef
1541 __unicode__ = classDef
1542
1543 def wrapClassDef(self):
1544 ind = self.setting('indentationStep')
1545 classDefChunks = [self.classSignature(),
1546 self.classDocstring(),
1547 ]
1548
1549 def addMethods():
1550 classDefChunks.extend([
1551 ind + '#'*50, # noqa: E226 missing whitespace around operator
1552 ind + '## CHEETAH GENERATED METHODS',
1553 '\n',
1554 self.methodDefs(),
1555 ])
1556
1557 def addAttributes():
1558 classDefChunks.extend([
1559 ind + '#'*50, # noqa: E226 missing whitespace around operator
1560 ind + '## CHEETAH GENERATED ATTRIBUTES',
1561 '\n',
1562 self.attributes(),
1563 ])
1564 if self.setting('outputMethodsBeforeAttributes'):
1565 addMethods()
1566 addAttributes()
1567 else:
1568 addAttributes()
1569 addMethods()
1570
1571 classDef = '\n'.join(classDefChunks)
1572 self._classDef = classDef
1573 return classDef
1574
1575 def classSignature(self):
1576 return "class %s(%s):" % (self.className(), self._baseClass)
1577
1578 def classDocstring(self):
1579 if not self._classDocStringLines:
1580 return ''
1581 ind = self.setting('indentationStep')
1582 docStr = ('%(ind)s"""\n%(ind)s'
1583 + '\n%(ind)s'.join(self._classDocStringLines)
1584 + '\n%(ind)s"""\n'
1585 ) % {'ind': ind}
1586 return docStr
1587
1588 def methodDefs(self):
1589 methodDefs = [
1590 methGen.methodDef() for methGen in self._finishedMethods()]
1591 return '\n\n'.join(methodDefs)
1592
1593 def attributes(self):
1594 try:
1595 attribs = [self.setting('indentationStep') + str(attrib)
1596 for attrib in self._generatedAttribs]
1597 except UnicodeEncodeError:
1598 attribs = [self.setting('indentationStep') + unicode(attrib)
1599 for attrib in self._generatedAttribs]
1600 return '\n\n'.join(attribs)
1601
1602
1603 class AutoClassCompiler(ClassCompiler):
1604 pass
1605
1606 ##################################################
1607 # MODULE COMPILERS
1608
1609
1610 class ModuleCompiler(SettingsManager, GenUtils):
1611
1612 parserClass = Parser
1613 classCompilerClass = AutoClassCompiler
1614
1615 def __init__(self, source=None, file=None,
1616 moduleName='DynamicallyCompiledCheetahTemplate',
1617 mainClassName=None, # string
1618 mainMethodName=None, # string
1619 baseclassName=None, # string
1620 extraImportStatements=None, # list of strings
1621 settings=None # dict
1622 ):
1623 super(ModuleCompiler, self).__init__()
1624 if settings:
1625 self.updateSettings(settings)
1626 # disable useStackFrames if the C version of NameMapper isn't compiled
1627 # it's painfully slow in the Python version and bites Windows users all
1628 # the time:
1629 if not NameMapper.C_VERSION:
1630 if not sys.platform.startswith('java'):
1631 warnings.warn(
1632 "\nYou don't have the C version of NameMapper installed! "
1633 "I'm disabling Cheetah's useStackFrames option as it is "
1634 "painfully slow with the Python version of NameMapper. "
1635 "You should get a copy of Cheetah "
1636 "with compiled C version of NameMapper.")
1637 self.setSetting('useStackFrames', False)
1638
1639 self._compiled = False
1640 self._moduleName = moduleName
1641 if not mainClassName:
1642 self._mainClassName = moduleName
1643 else:
1644 self._mainClassName = mainClassName
1645 self._mainMethodNameArg = mainMethodName
1646 if mainMethodName:
1647 self.setSetting('mainMethodName', mainMethodName)
1648 self._baseclassName = baseclassName
1649
1650 self._filePath = None
1651 self._fileMtime = None
1652
1653 if source and file:
1654 raise TypeError("Cannot compile from a source string AND file.")
1655 elif isinstance(file, string_type): # it's a filename.
1656 encoding = self.settings().get('encoding')
1657 if encoding:
1658 f = codecs.open(file, 'r', encoding=encoding)
1659 else:
1660 # if no encoding is specified, use the builtin open function
1661 f = open(file, 'r')
1662 source = f.read()
1663 f.close()
1664 self._filePath = file
1665 self._fileMtime = os.path.getmtime(file)
1666 elif hasattr(file, 'read'):
1667 # Can't set filename or mtime -- they're not accessible
1668 source = file.read()
1669 elif file:
1670 raise TypeError(
1671 "'file' argument must be a filename string or file-like object"
1672 )
1673
1674 if self._filePath:
1675 self._fileDirName, self._fileBaseName = \
1676 os.path.split(self._filePath)
1677 self._fileBaseNameRoot, self._fileBaseNameExt = \
1678 os.path.splitext(self._fileBaseName)
1679
1680 if not isinstance(source, string_type):
1681 # By converting to unicode here we allow objects
1682 # such as other Templates to be passed in
1683 source = unicode(source)
1684
1685 # Handle the #indent directive by converting it to other directives.
1686 # (Over the long term we'll make it a real directive.)
1687 if source == "":
1688 warnings.warn("You supplied an empty string for the source!", )
1689
1690 else:
1691 unicodeMatch = unicodeDirectiveRE.search(source)
1692 encodingMatch = encodingDirectiveRE.search(source)
1693 if unicodeMatch:
1694 if encodingMatch:
1695 raise ParseError(
1696 self, "#encoding and #unicode are mutually exclusive! "
1697 "Use one or the other.")
1698 source = unicodeDirectiveRE.sub('', source)
1699 if isinstance(source, bytes):
1700 encoding = unicodeMatch.group(1) or 'ascii'
1701 source = source.decode(encoding)
1702 elif encodingMatch:
1703 encodings = encodingMatch.groups()
1704 if len(encodings):
1705 encoding = encodings[0]
1706 if isinstance(source, bytes):
1707 source = source.decode(encoding)
1708 else:
1709 source = eval(
1710 repr(source).encode("ascii", "backslashreplace")
1711 .decode(encoding))
1712 else:
1713 source = unicode(source)
1714
1715 if source.find('#indent') != -1: # @@TR: undocumented hack
1716 source = indentize(source)
1717
1718 self._parser = self.parserClass(source, filename=self._filePath,
1719 compiler=self)
1720 self._setupCompilerState()
1721
1722 def __getattr__(self, name):
1723 """Provide one-way access to the methods and attributes of the
1724 ClassCompiler, and thereby the MethodCompilers as well.
1725
1726 WARNING: Use .setMethods to assign the attributes of the ClassCompiler
1727 from the methods of this class!!! Or you will be assigning to
1728 attributes of this object instead.
1729 """
1730 if name in self.__dict__:
1731 return self.__dict__[name]
1732 elif hasattr(self.__class__, name):
1733 return getattr(self.__class__, name)
1734 elif self._activeClassesList and \
1735 hasattr(self._activeClassesList[-1], name):
1736 return getattr(self._activeClassesList[-1], name)
1737 else:
1738 raise AttributeError(name)
1739
1740 def _initializeSettings(self):
1741 self.updateSettings(copy.deepcopy(DEFAULT_COMPILER_SETTINGS))
1742
1743 def _setupCompilerState(self):
1744 self._activeClassesList = []
1745 self._finishedClassesList = [] # listed by ordered
1746 self._finishedClassIndex = {} # listed by name
1747 self._moduleDef = None
1748 self._moduleShBang = '#!/usr/bin/env python'
1749 self._moduleEncoding = 'ascii'
1750 self._moduleEncodingStr = ''
1751 self._moduleHeaderLines = []
1752 self._moduleDocStringLines = []
1753 self._specialVars = {}
1754 # we might have been moved to be a sub-package
1755 if "__spec__" in globals():
1756 package = __spec__.parent # noqa: F821 undefined name '__spec__'
1757 else:
1758 package = __package__
1759 self._importStatements = [
1760 "import sys",
1761 "import os",
1762 "import os.path",
1763 'try:',
1764 ' import builtins as builtin',
1765 'except ImportError:',
1766 ' import __builtin__ as builtin',
1767 "from os.path import getmtime, exists",
1768 "import time",
1769 "import types",
1770 "from %s.Version import MinCompatibleVersion as "
1771 "RequiredCheetahVersion" % package,
1772 "from %s.Version import MinCompatibleVersionTuple "
1773 "as RequiredCheetahVersionTuple" % package,
1774 "from %s.Template import Template" % package,
1775 "from %s.DummyTransaction import *" % package,
1776 "from %s.NameMapper import NotFound, "
1777 "valueForName, valueFromSearchList, "
1778 "valueFromFrameOrSearchList" % package,
1779 "from %s.CacheRegion import CacheRegion" % package,
1780 "import %s.Filters as Filters" % package,
1781 "import %s.ErrorCatchers as ErrorCatchers" % package,
1782 "from %s.compat import unicode" % package,
1783 ]
1784
1785 self._importedVarNames = ['sys',
1786 'os',
1787 'os.path',
1788 'time',
1789 'types',
1790 'Template',
1791 'DummyTransaction',
1792 'NotFound',
1793 'Filters',
1794 'ErrorCatchers',
1795 'CacheRegion',
1796 ]
1797
1798 self._moduleConstants = [
1799 "VFFSL=valueFromFrameOrSearchList",
1800 "VFSL=valueFromSearchList",
1801 "VFN=valueForName",
1802 "currentTime=time.time",
1803 ]
1804
1805 def compile(self):
1806 classCompiler = self._spawnClassCompiler(self._mainClassName)
1807 if self._baseclassName:
1808 classCompiler.setBaseClass(self._baseclassName)
1809 self._addActiveClassCompiler(classCompiler)
1810 self._parser.parse()
1811 self._swallowClassCompiler(self._popActiveClassCompiler())
1812 self._compiled = True
1813 self._parser.cleanup()
1814
1815 def _spawnClassCompiler(self, className, klass=None):
1816 if klass is None:
1817 klass = self.classCompilerClass
1818 classCompiler = klass(className,
1819 moduleCompiler=self,
1820 mainMethodName=self.setting('mainMethodName'),
1821 fileName=self._filePath,
1822 settingsManager=self,
1823 )
1824 return classCompiler
1825
1826 def _addActiveClassCompiler(self, classCompiler):
1827 self._activeClassesList.append(classCompiler)
1828
1829 def _getActiveClassCompiler(self):
1830 return self._activeClassesList[-1]
1831
1832 def _popActiveClassCompiler(self):
1833 return self._activeClassesList.pop()
1834
1835 def _swallowClassCompiler(self, classCompiler):
1836 classCompiler.cleanupState()
1837 self._finishedClassesList.append(classCompiler)
1838 self._finishedClassIndex[classCompiler.className()] = classCompiler
1839 return classCompiler
1840
1841 def _finishedClasses(self):
1842 return self._finishedClassesList
1843
1844 def importedVarNames(self):
1845 return self._importedVarNames
1846
1847 def addImportedVarNames(self, varNames, raw_statement=None):
1848 settings = self.settings()
1849 if not varNames:
1850 return
1851 if not settings.get('useLegacyImportMode'):
1852 if raw_statement and getattr(self, '_methodBodyChunks'):
1853 self.addChunk(raw_statement)
1854 else:
1855 self._importedVarNames.extend(varNames)
1856
1857 # methods for adding stuff to the module and class definitions
1858
1859 def setBaseClass(self, baseClassName):
1860 if self._mainMethodNameArg:
1861 self.setMainMethodName(self._mainMethodNameArg)
1862 else:
1863 self.setMainMethodName(self.setting('mainMethodNameForSubclasses'))
1864
1865 if self.setting('handlerForExtendsDirective'):
1866 handler = self.setting('handlerForExtendsDirective')
1867 baseClassName = handler(compiler=self, baseClassName=baseClassName)
1868 self._getActiveClassCompiler().setBaseClass(baseClassName)
1869 elif (not self.setting('autoImportForExtendsDirective')
1870 or baseClassName == 'object'
1871 or baseClassName in self.importedVarNames()):
1872 self._getActiveClassCompiler().setBaseClass(baseClassName)
1873 # no need to import
1874 else:
1875 ##################################################
1876 # If the #extends directive contains a classname or modulename
1877 # that isn't in self.importedVarNames() already,
1878 # we assume that we need to add an implied
1879 # 'from ModName import ClassName' where ModName == ClassName.
1880 # - This is the case in WebKit servlet modules.
1881 # - We also assume that the final . separates the classname
1882 # from the module name.
1883 # This might break if people do something really fancy
1884 # with their dots and namespaces.
1885 baseclasses = []
1886 for klass in baseClassName.split(','):
1887 klass = klass.strip()
1888 chunks = klass.split('.')
1889 if len(chunks) == 1:
1890 baseclasses.append(klass)
1891 if klass not in self.importedVarNames():
1892 modName = klass
1893 # we assume the class name to be the module name
1894 # and that it's not a builtin:
1895 importStatement = "from %s import %s" % (
1896 modName, klass)
1897 self.addImportStatement(importStatement)
1898 self.addImportedVarNames((klass,))
1899 else:
1900 needToAddImport = True
1901 modName = chunks[0]
1902 for chunk in chunks[1:-1]:
1903 if modName in self.importedVarNames():
1904 needToAddImport = False
1905 finalBaseClassName = klass.replace(modName + '.',
1906 '')
1907 baseclasses.append(finalBaseClassName)
1908 break
1909 else:
1910 modName += '.' + chunk
1911 if needToAddImport:
1912 modName, finalClassName = (
1913 '.'.join(chunks[:-1]), chunks[-1])
1914 # if finalClassName != chunks[:-1][-1]:
1915 if finalClassName != chunks[-2]:
1916 # we assume the class name to be the module name
1917 modName = '.'.join(chunks)
1918 baseclasses.append(finalClassName)
1919 importStatement = "from %s import %s" % (
1920 modName, finalClassName)
1921 self.addImportStatement(importStatement)
1922 self.addImportedVarNames([finalClassName])
1923
1924 self._getActiveClassCompiler().setBaseClass(', '.join(baseclasses))
1925
1926 def setCompilerSetting(self, key, valueExpr):
1927 self.setSetting(key, eval(valueExpr))
1928 self._parser.configureParser()
1929
1930 def setCompilerSettings(self, keywords, settingsStr):
1931 KWs = keywords
1932
1933 if 'reset' in KWs:
1934 # @@TR: this is actually caught by the parser at the moment.
1935 # subject to change in the future
1936 self._initializeSettings()
1937 self._parser.configureParser()
1938 return
1939 elif 'python' in KWs:
1940 settingsReader = self.updateSettingsFromPySrcStr
1941 # this comes from SettingsManager
1942 else:
1943 # this comes from SettingsManager
1944 settingsReader = self.updateSettingsFromConfigStr
1945
1946 settingsReader(settingsStr)
1947 self._parser.configureParser()
1948
1949 def setShBang(self, shBang):
1950 self._moduleShBang = shBang
1951
1952 def setModuleEncoding(self, encoding):
1953 self._moduleEncoding = encoding
1954
1955 def getModuleEncoding(self):
1956 return self._moduleEncoding
1957
1958 def addModuleHeader(self, line):
1959 """Adds a header comment to the top of the generated module.
1960 """
1961 self._moduleHeaderLines.append(line)
1962
1963 def addModuleDocString(self, line):
1964 """Adds a line to the generated module docstring.
1965 """
1966 self._moduleDocStringLines.append(line)
1967
1968 def addModuleGlobal(self, line):
1969 """Adds a line of global module code. It is inserted after the import
1970 statements and Cheetah default module constants.
1971 """
1972 self._moduleConstants.append(line)
1973
1974 def addSpecialVar(self, basename, contents, includeUnderscores=True):
1975 """Adds module __specialConstant__ to the module globals.
1976 """
1977 name = includeUnderscores and '__' + basename + '__' or basename
1978 self._specialVars[name] = contents.strip()
1979
1980 def addImportStatement(self, impStatement):
1981 settings = self.settings()
1982 if not self._methodBodyChunks or settings.get('useLegacyImportMode'):
1983 # In the case where we are importing inline
1984 # in the middle of a source block
1985 # we don't want to inadvertantly import the module
1986 # at the top of the file either
1987 self._importStatements.append(impStatement)
1988
1989 # @@TR 2005-01-01: there's almost certainly a cleaner way to do this!
1990 importVarNames = impStatement[
1991 impStatement.find('import') + len('import'):].split(',')
1992 # handle aliases
1993 importVarNames = [var.split()[-1] for var in importVarNames]
1994 importVarNames = [var for var in importVarNames if not var == '*']
1995 # used by #extend for auto-imports
1996 self.addImportedVarNames(importVarNames, raw_statement=impStatement)
1997
1998 def addAttribute(self, attribName, expr):
1999 self._getActiveClassCompiler().addAttribute(attribName + ' =' + expr)
2000
2001 def addComment(self, comm):
2002 if re.match(r'#+$', comm): # skip bar comments
2003 return
2004
2005 specialVarMatch = specialVarRE.match(comm)
2006 if specialVarMatch:
2007 # @@TR: this is a bit hackish and is being replaced with
2008 # #set module varName = ...
2009 return self.addSpecialVar(specialVarMatch.group(1),
2010 comm[specialVarMatch.end():])
2011 elif comm.startswith('doc:'):
2012 addLine = self.addMethDocString
2013 comm = comm[len('doc:'):].strip()
2014 elif comm.startswith('doc-method:'):
2015 addLine = self.addMethDocString
2016 comm = comm[len('doc-method:'):].strip()
2017 elif comm.startswith('doc-module:'):
2018 addLine = self.addModuleDocString
2019 comm = comm[len('doc-module:'):].strip()
2020 elif comm.startswith('doc-class:'):
2021 addLine = self.addClassDocString
2022 comm = comm[len('doc-class:'):].strip()
2023 elif comm.startswith('header:'):
2024 addLine = self.addModuleHeader
2025 comm = comm[len('header:'):].strip()
2026 else:
2027 addLine = self.addMethComment
2028
2029 for line in comm.splitlines():
2030 addLine(line)
2031
2032 # methods for module code wrapping
2033
2034 def getModuleCode(self):
2035 if not self._compiled:
2036 self.compile()
2037 if self._moduleDef:
2038 return self._moduleDef
2039 else:
2040 return self.wrapModuleDef()
2041
2042 def __to_bytes(self):
2043 code = self.getModuleCode()
2044 if isinstance(code, bytes):
2045 return code
2046 return code.encode(self.getModuleEncoding())
2047
2048 def __to_unicode(self):
2049 code = self.getModuleCode()
2050 if isinstance(code, bytes):
2051 return code.decode(self.getModuleEncoding())
2052 return code
2053
2054 if PY2:
2055 __str__ = __to_bytes
2056 __unicode__ = __to_unicode
2057 else:
2058 __bytes__ = __to_bytes
2059 __str__ = __to_unicode
2060
2061 def wrapModuleDef(self):
2062 self.addSpecialVar('CHEETAH_docstring', self.setting('defDocStrMsg'))
2063 self.addModuleGlobal('__CHEETAH_version__ = %r' % Version)
2064 self.addModuleGlobal('__CHEETAH_versionTuple__ = %r' % (VersionTuple,))
2065 if self.setting('addTimestampsToCompilerOutput'):
2066 self.addModuleGlobal('__CHEETAH_genTime__ = %r' % time.time())
2067 self.addModuleGlobal(
2068 '__CHEETAH_genTimestamp__ = %r' % self.timestamp())
2069 if self._filePath:
2070 timestamp = self.timestamp(self._fileMtime)
2071 self.addModuleGlobal('__CHEETAH_src__ = %r' % self._filePath)
2072 self.addModuleGlobal(
2073 '__CHEETAH_srcLastModified__ = %r' % timestamp)
2074 else:
2075 self.addModuleGlobal('__CHEETAH_src__ = None')
2076 self.addModuleGlobal('__CHEETAH_srcLastModified__ = None')
2077
2078 moduleDef = """%(header)s
2079 %(docstring)s
2080
2081 ##################################################
2082 ## DEPENDENCIES
2083 %(imports)s
2084
2085 ##################################################
2086 ## MODULE CONSTANTS
2087 %(constants)s
2088 %(specialVars)s
2089
2090 if __CHEETAH_versionTuple__ < RequiredCheetahVersionTuple:
2091 raise AssertionError(
2092 'This template was compiled with Cheetah version'
2093 ' %%s. Templates compiled before version %%s must be recompiled.'%%(
2094 __CHEETAH_version__, RequiredCheetahVersion))
2095
2096 ##################################################
2097 ## CLASSES
2098
2099 %(classes)s
2100
2101 ## END CLASS DEFINITION
2102
2103 if not hasattr(%(mainClassName)s, '_initCheetahAttributes'):
2104 templateAPIClass = getattr(%(mainClassName)s,
2105 '_CHEETAH_templateClass',
2106 Template)
2107 templateAPIClass._addCheetahPlumbingCodeToClass(%(mainClassName)s)
2108
2109 %(footer)s
2110 """ % {
2111 'header': self.moduleHeader(),
2112 'docstring': self.moduleDocstring(),
2113 'specialVars': self.specialVars(),
2114 'imports': self.importStatements(),
2115 'constants': self.moduleConstants(),
2116 'classes': self.classDefs(),
2117 'footer': self.moduleFooter(),
2118 'mainClassName': self._mainClassName,
2119 } # noqa
2120
2121 self._moduleDef = moduleDef
2122 return moduleDef
2123
2124 def timestamp(self, theTime=None):
2125 if not theTime:
2126 theTime = time.time()
2127 return time.asctime(time.localtime(theTime))
2128
2129 def moduleHeader(self):
2130 header = self._moduleShBang + '\n'
2131 header += self._moduleEncodingStr + '\n'
2132 if self._moduleHeaderLines:
2133 offSet = self.setting('commentOffset')
2134
2135 header += (
2136 '#' + ' '*offSet # noqa: E226,E501 missing whitespace around operator
2137 + ('\n#' + ' '*offSet).join(self._moduleHeaderLines) # noqa: E226,E501 missing whitespace around operator
2138 + '\n')
2139
2140 return header
2141
2142 def moduleDocstring(self):
2143 if not self._moduleDocStringLines:
2144 return ''
2145
2146 return ('"""' + '\n'.join(self._moduleDocStringLines)
2147 + '\n"""\n')
2148
2149 def specialVars(self):
2150 chunks = []
2151 theVars = self._specialVars
2152 keys = sorted(theVars.keys())
2153 for key in keys:
2154 chunks.append(key + ' = ' + repr(theVars[key]))
2155 return '\n'.join(chunks)
2156
2157 def importStatements(self):
2158 return '\n'.join(self._importStatements)
2159
2160 def moduleConstants(self):
2161 return '\n'.join(self._moduleConstants)
2162
2163 def classDefs(self):
2164 classDefs = [klass.classDef() for klass in self._finishedClasses()]
2165 return '\n\n'.join(classDefs)
2166
2167 def moduleFooter(self):
2168 return """
2169 # CHEETAH was developed by Tavis Rudd and Mike Orr
2170 # with code, advice and input from many other volunteers.
2171 # For more information visit https://cheetahtemplate.org/
2172
2173 ##################################################
2174 ## if run from command line:
2175 if __name__ == '__main__':
2176 from Cheetah.TemplateCmdLineIface import CmdLineIface
2177 CmdLineIface(templateObj=%(className)s()).run()
2178
2179 """ % {'className': self._mainClassName}
2180
2181
2182 ##################################################
2183 # Make Compiler an alias for ModuleCompiler
2184
2185 Compiler = ModuleCompiler