Debian Codegraph @

src/zc/customdoctests/js.py

raw
1 ##############################################################################
2 #
3 # Copyright (c) 2011 Zope Foundation and Contributors.
4 # All Rights Reserved.
5 #
6 # This software is subject to the provisions of the Zope Public License,
7 # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
8 # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
9 # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
10 # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
11 # FOR A PARTICULAR PURPOSE.
12 #
13 ##############################################################################
14 import doctest
15 import os
16 import re
17 import sys
18 import zc.customdoctests
19
20 run_time = None
21
22 def transform(s, f='JS'):
23 if s[-1] == '\n':
24 return (r'%s(r"""%s"""+"\n")' % (f, s)) + '\n'
25 else:
26 return r'%s(r"""%s""")' % (f, s)
27
28 parser = zc.customdoctests.DocTestParser(
29 ps1='js>', comment_prefix='//', transform=transform)
30
31 # parser_ is like parser, except adds: var _ = to
32 # the fron of the executed code.
33 eq_parser = zc.customdoctests.DocTestParser(
34 ps1='js!', comment_prefix='//',
35 transform=lambda s: transform(s, 'JS_'))
36
37
38 # spidermonkey hacks below:
39
40 class JavaScriptError(Exception):
41
42 def __str__(self):
43 try:
44 return "%s\nJS Traceback:%s" % (
45 self.args[0].message,
46 '\n'.join(reversed(self.args[0].stack.split('\n')))
47 )
48 except:
49 return str(self.args[0])
50
51
52 class ContextConvenience(object):
53
54 def __init__(self, context):
55 object.__setattr__(self, '_context', context)
56
57 def __getattr__(self, name):
58 return self._context.execute(name)
59
60 def __setattr__(self, name, v):
61 self._context.add_global(name, v)
62
63 def __call__(self, src):
64 self._context.execute(load_template % src)
65 if self.spidermonkey_error is not None:
66 raise JavaScriptError(self.spidermonkey_error)
67
68 def spidermonkeySetUp(test_or_self=None):
69 global run_time
70 if run_time is None:
71 import spidermonkey
72 run_time = spidermonkey.Runtime()
73 cx = run_time.new_context()
74 JS = cx.execute
75
76 js = ContextConvenience(cx)
77
78 if test_or_self is not None:
79 globs = getattr(test_or_self, 'globs', test_or_self.__dict__)
80 globs['JS'] = JS
81 globs['JS_'] = js
82 globs['js'] = js
83 globs['add_js_global'] = cx.add_global
84
85 def load_(name):
86 if name.startswith('file://'):
87 name = name[7:]
88 return JS(load_template % open(name).read(), name)
89
90 # Rhino & spidermonkey/js compatability functions
91 cx.add_global('python', dict(
92 os = os,
93 open = open,
94 ))
95 cx.add_global('load_', load_)
96 JS(load_js)
97 cx.add_global('print',
98 lambda *s: sys.stdout.write(('%s\n' % ' '.join(map(unicode, s))).encode('utf-8'))
99 )
100 cx.add_global('printe',
101 lambda *s: sys.stderr.write('%s\n' % ' '.join(map(unicode, s)))
102 )
103 return js
104
105
106 load_template = ("spidermonkey_error = undefined; "
107 "try { %s } catch (e) {spidermonkey_error = e;}")
108
109 load_js = """
110 function load(p) {
111 if (p.slice(0, 7) == 'file://') {
112 p = p.slice(7);
113 }
114 try { console.debug('loading', p); } catch (e) {}
115 if (! python.os.path.exists(p)) {
116 throw "Doesn't exist: "+p;
117 }
118 var result = load_(p);
119 if (spidermonkey_error) {
120 throw spidermonkey_error;
121 }
122 return result;
123 }
124 """