Code

some speedups, some fixes to the benchmarking
[roundup.git] / roundup / cgi / PageTemplates / Expressions.py
1 ##############################################################################
2 #
3 # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
4
5 # This software is subject to the provisions of the Zope Public License,
6 # Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
7 # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
8 # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
9 # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
10 # FOR A PARTICULAR PURPOSE
11
12 ##############################################################################
14 """Page Template Expression Engine
16 Page Template-specific implementation of TALES, with handlers
17 for Python expressions, string literals, and paths.
20 Modified for Roundup 0.5 release:
22 - Removed all Zope-specific code (doesn't even try to import that stuff now)
23 - Removed all Acquisition
24 - Made traceback info more informative
26 """
28 __version__='$Revision: 1.7 $'[11:-2]
30 import re, sys
31 from TALES import Engine, CompilerError, _valid_name, NAME_RE, \
32      Undefined, Default, _parse_expr
33 from string import strip, split, join, replace, lstrip
35 _engine = None
36 def getEngine():
37     global _engine
38     if _engine is None:
39         from PathIterator import Iterator
40         _engine = Engine(Iterator)
41         installHandlers(_engine)
42     return _engine
44 def installHandlers(engine):
45     reg = engine.registerType
46     pe = PathExpr
47     for pt in ('standard', 'path', 'exists', 'nocall'):
48         reg(pt, pe)
49     reg('string', StringExpr)
50     reg('python', PythonExpr)
51     reg('not', NotExpr)
52     reg('defer', DeferExpr)
54 from PythonExpr import getSecurityManager, PythonExpr
55 try:
56     from zExceptions import Unauthorized
57 except ImportError:
58     Unauthorized = "Unauthorized"
59 def call_with_ns(f, ns, arg=1):
60     if arg==2:
61         return f(None, ns)
62     else:
63         return f(ns)
65 class _SecureModuleImporter:
66     """Simple version of the importer for use with trusted code."""
67     __allow_access_to_unprotected_subobjects__ = 1
68     def __getitem__(self, module):
69         __import__(module)
70         return sys.modules[module]
72 Undefs = (Undefined, AttributeError, KeyError,
73           TypeError, IndexError, Unauthorized)
75 def render(ob, ns):
76     """
77     Calls the object, possibly a document template, or just returns it if
78     not callable.  (From DT_Util.py)
79     """
80     if hasattr(ob, '__render_with_namespace__'):
81         ob = call_with_ns(ob.__render_with_namespace__, ns)
82     else:
83         base = ob
84         if callable(base):
85             try:
86                 if getattr(base, 'isDocTemp', 0):
87                     ob = call_with_ns(ob, ns, 2)
88                 else:
89                     ob = ob()
90             except AttributeError, n:
91                 if str(n) != '__call__':
92                     raise
93     return ob
95 class SubPathExpr:
96     def __init__(self, path):
97         self._path = path = split(strip(path), '/')
98         self._base = base = path.pop(0)
99         if not _valid_name(base):
100             raise CompilerError, 'Invalid variable name "%s"' % base
101         # Parse path
102         self._dp = dp = []
103         for i in range(len(path)):
104             e = path[i]
105             if e[:1] == '?' and _valid_name(e[1:]):
106                 dp.append((i, e[1:]))
107         dp.reverse()
109     def _eval(self, econtext,
110               list=list, isinstance=isinstance, StringType=type('')):
111         vars = econtext.vars
112         path = self._path
113         if self._dp:
114             path = list(path) # Copy!
115             for i, varname in self._dp:
116                 val = vars[varname]
117                 if isinstance(val, StringType):
118                     path[i] = val
119                 else:
120                     # If the value isn't a string, assume it's a sequence
121                     # of path names.
122                     path[i:i+1] = list(val)
123         base = self._base
124         __traceback_info__ = 'path expression "%s"'%('/'.join(self._path))
125         if base == 'CONTEXTS':
126             ob = econtext.contexts
127         else:
128             ob = vars[base]
129         if isinstance(ob, DeferWrapper):
130             ob = ob()
131         if path:
132             ob = restrictedTraverse(ob, path, getSecurityManager())
133         return ob
135 class PathExpr:
136     def __init__(self, name, expr, engine):
137         self._s = expr
138         self._name = name
139         paths = split(expr, '|')
140         self._subexprs = []
141         add = self._subexprs.append
142         for i in range(len(paths)):
143             path = lstrip(paths[i])
144             if _parse_expr(path):
145                 # This part is the start of another expression type,
146                 # so glue it back together and compile it.
147                 add(engine.compile(lstrip(join(paths[i:], '|'))))
148                 break
149             add(SubPathExpr(path)._eval)
151     def _exists(self, econtext):
152         for expr in self._subexprs:
153             try:
154                 expr(econtext)
155             except Undefs:
156                 pass
157             else:
158                 return 1
159         return 0
161     def _eval(self, econtext,
162               isinstance=isinstance, StringType=type(''), render=render):
163         for expr in self._subexprs[:-1]:
164             # Try all but the last subexpression, skipping undefined ones.
165             try:
166                 ob = expr(econtext)
167             except Undefs:
168                 pass
169             else:
170                 break
171         else:
172             # On the last subexpression allow exceptions through.
173             ob = self._subexprs[-1](econtext)
175         if self._name == 'nocall' or isinstance(ob, StringType):
176             return ob
177         # Return the rendered object
178         return render(ob, econtext.vars)
180     def __call__(self, econtext):
181         if self._name == 'exists':
182             return self._exists(econtext)
183         return self._eval(econtext)
185     def __str__(self):
186         return '%s expression %s' % (self._name, `self._s`)
188     def __repr__(self):
189         return '%s:%s' % (self._name, `self._s`)
191             
192 _interp = re.compile(r'\$(%(n)s)|\${(%(n)s(?:/%(n)s)*)}' % {'n': NAME_RE})
194 class StringExpr:
195     def __init__(self, name, expr, engine):
196         self._s = expr
197         if '%' in expr:
198             expr = replace(expr, '%', '%%')
199         self._vars = vars = []
200         if '$' in expr:
201             parts = []
202             for exp in split(expr, '$$'):
203                 if parts: parts.append('$')
204                 m = _interp.search(exp)
205                 while m is not None:
206                     parts.append(exp[:m.start()])
207                     parts.append('%s')
208                     vars.append(PathExpr('path', m.group(1) or m.group(2),
209                                          engine))
210                     exp = exp[m.end():]
211                     m = _interp.search(exp)
212                 if '$' in exp:
213                     raise CompilerError, (
214                         '$ must be doubled or followed by a simple path')
215                 parts.append(exp)
216             expr = join(parts, '')
217         self._expr = expr
218         
219     def __call__(self, econtext):
220         vvals = []
221         for var in self._vars:
222             v = var(econtext)
223             if isinstance(v, Exception):
224                 raise v
225             vvals.append(v)
226         return self._expr % tuple(vvals)
228     def __str__(self):
229         return 'string expression %s' % `self._s`
231     def __repr__(self):
232         return 'string:%s' % `self._s`
234 class NotExpr:
235     def __init__(self, name, expr, compiler):
236         self._s = expr = lstrip(expr)
237         self._c = compiler.compile(expr)
238         
239     def __call__(self, econtext):
240         return not econtext.evaluateBoolean(self._c)
242     def __repr__(self):
243         return 'not:%s' % `self._s`
245 class DeferWrapper:
246     def __init__(self, expr, econtext):
247         self._expr = expr
248         self._econtext = econtext
250     def __str__(self):
251         return str(self())
253     def __call__(self):
254         return self._expr(self._econtext)
256 class DeferExpr:
257     def __init__(self, name, expr, compiler):
258         self._s = expr = lstrip(expr)
259         self._c = compiler.compile(expr)
260         
261     def __call__(self, econtext):
262         return DeferWrapper(self._c, econtext)
264     def __repr__(self):
265         return 'defer:%s' % `self._s`
267 class TraversalError:
268     def __init__(self, path, name):
269         self.path = path
270         self.name = name
272 def restrictedTraverse(self, path, securityManager,
273                        get=getattr, has=hasattr, N=None, M=[],
274                        TupleType=type(()) ):
276     REQUEST = {'path': path}
277     REQUEST['TraversalRequestNameStack'] = path = path[:] # Copy!
278     if not path[0]:
279         # If the path starts with an empty string, go to the root first.
280         self = self.getPhysicalRoot()
281         path.pop(0)
283     path.reverse()
284     object = self
285     #print 'TRAVERSE', (object, path)
286     done = []
287     while path:
288         name = path.pop()
289         __traceback_info__ = TraversalError(done, name)
291 #        if isinstance(name, TupleType):
292 #            object = apply(object, name)
293 #            continue
295 #        if name[0] == '_':
296 #            # Never allowed in a URL.
297 #            raise AttributeError, name
299         # Try an attribute.
300         o = get(object, name, M)
301 #       print '...', (object, name, M, o)
302         if o is M:
303             # Try an item.
304 #           print '... try an item'
305             try:
306                 # XXX maybe in Python 2.2 we can just check whether
307                 # the object has the attribute "__getitem__"
308                 # instead of blindly catching exceptions.
309                 o = object[name]
310             except AttributeError, exc:
311                 if str(exc).find('__getitem__') >= 0:
312                     # The object does not support the item interface.
313                     # Try to re-raise the original attribute error.
314                     # XXX I think this only happens with
315                     # ExtensionClass instances.
316                     get(object, name)
317                 raise
318             except TypeError, exc:
319                 if str(exc).find('unsubscriptable') >= 0:
320                     # The object does not support the item interface.
321                     # Try to re-raise the original attribute error.
322                     # XXX This is sooooo ugly.
323                     get(object, name)
324                 raise
325         #print '... object is now', `o`
326         object = o
327         done.append((name, o))
329     return object