~ubuntu-branches/ubuntu/karmic/pypy/karmic

« back to all changes in this revision

Viewing changes to pypy/lang/js/js_interactive.py

  • Committer: Bazaar Package Importer
  • Author(s): Alexandre Fayolle
  • Date: 2007-04-13 09:33:09 UTC
  • Revision ID: james.westby@ubuntu.com-20070413093309-yoojh4jcoocu2krz
Tags: upstream-1.0.0
ImportĀ upstreamĀ versionĀ 1.0.0

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/env python
 
2
# encoding: utf-8
 
3
"""
 
4
js_interactive.py
 
5
"""
 
6
 
 
7
import autopath
 
8
import sys
 
9
import getopt
 
10
from pypy.lang.js.interpreter import *
 
11
from pypy.lang.js.jsobj import W_Builtin, W_String, ThrowException, w_Undefined
 
12
from pypy.lang.js import jsparser
 
13
import os
 
14
import cmd
 
15
 
 
16
help_message = """
 
17
PyPy's JavaScript Interpreter:
 
18
 -f filename - Loads a file
 
19
 -n to not be interactive
 
20
 -h show this help message
 
21
 -d jump to a pdb in case of failure
 
22
"""
 
23
 
 
24
interactive = True
 
25
 
 
26
def setup_readline():
 
27
    import readline
 
28
    import os
 
29
    histfile = os.path.join(os.environ["HOME"], ".jspypyhist")
 
30
    try:
 
31
        getattr(readline, "clear_history", lambda : None)()
 
32
        readline.read_history_file(histfile)
 
33
    except IOError:
 
34
        pass
 
35
    import atexit
 
36
    atexit.register(readline.write_history_file, histfile)
 
37
 
 
38
class Usage(Exception):
 
39
    def __init__(self, msg):
 
40
        self.msg = msg
 
41
 
 
42
def loadjs(ctx, args, this):
 
43
    filename = args[0]
 
44
    t = load_file(filename.ToString())
 
45
    return t.execute(ctx)
 
46
 
 
47
def tracejs(ctx, args, this):
 
48
    arguments = args
 
49
    import pdb
 
50
    pdb.set_trace()
 
51
 
 
52
def quitjs(ctx, args, this):
 
53
    sys.exit(0)
 
54
    
 
55
    
 
56
def main(argv=None):
 
57
    # XXX: note. This will not work when translated, because
 
58
    # globals cannot be modified (ie. interactive is always True).
 
59
    # so I'm adding support which will not be translated, probably
 
60
    # for further consideration
 
61
    global interactive
 
62
    debug = False
 
63
    if argv is None:
 
64
        argv = sys.argv
 
65
    try:
 
66
        try:
 
67
            opts, args = getopt.getopt(argv[1:], "hdnf:", ["help",])
 
68
        except getopt.error, msg:
 
69
            raise Usage(msg)
 
70
    
 
71
        # option processing
 
72
        filenames = []
 
73
        for option, value in opts:
 
74
            if option == "-f":
 
75
                filenames.append(value)
 
76
            if option == "-n":
 
77
                interactive = False
 
78
            if option in ("-h", "--help"):
 
79
                raise Usage(help_message)
 
80
            if option == '-d':
 
81
                debug = True
 
82
    
 
83
    except Usage, err:
 
84
        print >> sys.stderr, sys.argv[0].split("/")[-1] + ": " + str(err.msg)
 
85
        print >> sys.stderr, "\t for help use --help"
 
86
        return 2
 
87
    
 
88
    interp = Interpreter()
 
89
        
 
90
    interp.w_Global.Put('quit', W_Builtin(quitjs))
 
91
    interp.w_Global.Put('load', W_Builtin(loadjs))
 
92
    interp.w_Global.Put('trace', W_Builtin(tracejs))
 
93
    for filename in filenames:
 
94
        try:
 
95
            loadjs(interp.global_context, [W_String(filename)], None)
 
96
            # XXX we should catch more stuff here, like not implemented
 
97
            # and such
 
98
        except (jsparser.JsSyntaxError, ThrowException), e:
 
99
            if isinstance(e, jsparser.JsSyntaxError):
 
100
                print "\nSyntax error!"
 
101
            elif isinstance(e, ThrowException):
 
102
                print "\nJS Exception thrown!"
 
103
            return
 
104
 
 
105
    #while interactive:
 
106
    #    res = interp.run(load_source(raw_input("js-pypy> ")))
 
107
    #    if res is not None:
 
108
    #        print res
 
109
    if interactive:
 
110
        MyCmd(interp, debug).cmdloop()
 
111
 
 
112
class MyCmd(cmd.Cmd):
 
113
    prompt = "js-pypy> "
 
114
    def __init__(self, interp, debug):
 
115
        cmd.Cmd.__init__(self)
 
116
        setup_readline()
 
117
        self.debug = debug
 
118
        self.interp = interp
 
119
        self.reset()
 
120
 
 
121
    def reset(self):
 
122
        self.prompt = self.__class__.prompt
 
123
        self.lines = []
 
124
        self.level = 0
 
125
    
 
126
    def default(self, line):
 
127
        # let's count lines and continue till matching proper nr of {
 
128
        # XXX: '{' will count as well
 
129
        # we can avoid this by using our own's tokeniser, when we possess one
 
130
        if line == 'EOF':
 
131
            print "\nQuitting"
 
132
            sys.exit()
 
133
        opens = line.count('{')
 
134
        closes = line.count('}')
 
135
        self.level += opens - closes
 
136
        self.lines.append(line)
 
137
        if self.level > 0:
 
138
            self.prompt = '     ... '
 
139
            return
 
140
        elif self.level < 0:
 
141
            print "\nError!!! Too many closing braces"
 
142
            self.level = 0
 
143
            return
 
144
        try:
 
145
            try:
 
146
                res = self.interp.run(load_source("\n".join(self.lines)))
 
147
                # XXX we should catch more stuff here, like not implemented
 
148
                # and such
 
149
            except (jsparser.JsSyntaxError, ThrowException), e:
 
150
                e_info = sys.exc_info()
 
151
                if self.debug:
 
152
                    import pdb
 
153
                    pdb.post_mortem(e_info[2])
 
154
                else:
 
155
                    if isinstance(e, jsparser.JsSyntaxError):
 
156
                        print "\nSyntax error!"
 
157
                    elif isinstance(e, ThrowException):
 
158
                        print e.exception.ToString()
 
159
                return
 
160
        finally:
 
161
            self.reset()
 
162
        if (res is not None) and (res is not w_Undefined):
 
163
            try:
 
164
                print res.GetValue().ToString()
 
165
            except ThrowException, e:
 
166
                print e.exception.ToString()
 
167
 
 
168
if __name__ == "__main__":
 
169
    import py
 
170
    py.test.config.parse([])
 
171
    sys.exit(main())