aboutsummaryrefslogtreecommitdiff
path: root/lib/Tcl.py
blob: 9d45e3796a13c24eab5098de7ae1afedf9ef160b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
# An emulator for John Ousterhout's 'Tcl' language in Python (wow!).
# Currently only the most basic commands are implemented.
#
# Design choices:
#
# - Names used for functions are not exactly those used by C Tcl.
# In Python, names without 'Tcl_' prefix are acceptable because
# names are less global than in C (and often they are prefixed
# with a module name anyway). Parameter conventions also differ.
#
# - The Tcl Interpreter type is implemented using a Python class.
# Almost all functions with an Interpreter as first parameter are
# methods of this class.
# Applications can create derived classes to add additional commands
# or to override specific internal functions.
#
# - Tcl errors are mapped to Python exceptions.
# (I bet Ousterhout would have done the same in a language with
# a proper exception mechanism).
#
# - Tcl expressions are evaluated by Python's built-in function eval().
# This makes Python Tcl scripts incompatible with C Tcl scripts,
# but is the only sensible solution for a quick-and-dirty version.
# It also makes an escape to Python possible.
#
# - The Backslash function interprets \<newline>, since it
# can return a string instead of a character.


from TclUtil import *


# Exceptions used to signify 'break' and 'continue'

TclBreak = 'TclBreak'
TclContinue = 'TclContinue'
TclReturn = 'TclReturn'


class CmdBuf():
 #
 def Create(buffer):
 buffer.string = ''
 return buffer
 #
 def Assemble(buffer, str):
 buffer.string = buffer.string + str
 if buffer.string[-1:] = '\n':
 i, end = 0, len(buffer.string)
 try:
 while i < end:
 list, i = FindNextCommand( \
 buffer.string, i, end, 0)
 except TclMatchingError:
 return ''
 except TclSyntaxError:
 pass # Let Eval() return the error
 ret = buffer.string
 buffer.string = ''
 return ret
 else:
 return ''


class _Frame():
 def Create(frame):
 frame.locals = {}
 return frame

class _Proc():
 #
 def Create(proc, (interp, args, body)):
 proc.interp = interp
 proc.args = SplitList(args) # Do this once here
 proc.body = body
 return proc
 #
 def Call(proc, argv):
 if len(argv) <> len(proc.args)+1:
 raise TclRuntimeError, \
 'wrong # args to proc "' + \
 argv[0] + '"'
 # XXX No defaults or variable length 'args' yet
 frame = _Frame().Create()
 for i in range(len(proc.args)):
 frame.locals[proc.args[i]] = argv[i+1]
 proc.interp.stack.append(frame)
 try:
 value = proc.interp.Eval(proc.body)
 except TclReturn, value:
 pass
 del proc.interp.stack[-1:]
 return value


import regexp
_expand_prog = regexp.compile('([^[$\\]+|\n)*')
del regexp

class Interpreter():
 #
 def Create(interp):
 interp.globals = {}
 interp.commands = {}
 interp.stack = []
 interp.commands['break'] = interp.BreakCmd
 interp.commands['concat'] = interp.ConcatCmd
 interp.commands['continue'] = interp.ContinueCmd
 interp.commands['echo'] = interp.EchoCmd
 interp.commands['eval'] = interp.EvalCmd
 interp.commands['expr'] = interp.ExprCmd
 interp.commands['for'] = interp.ForCmd
 interp.commands['glob'] = interp.GlobCmd
 interp.commands['global'] = interp.GlobalCmd
 interp.commands['if'] = interp.IfCmd
 interp.commands['index'] = interp.IndexCmd
 interp.commands['list'] = interp.ListCmd
 interp.commands['proc'] = interp.ProcCmd
 interp.commands['rename'] = interp.RenameCmd
 interp.commands['return'] = interp.ReturnCmd
 interp.commands['set'] = interp.SetCmd
 return interp
 #
 def Delete(interp):
 #
 # Only break circular references here;
 # most things will be garbage-collected.
 #
 for name in interp.commands.keys():
 del interp.commands[name]
 #
 def CreateCommand(interp, (name, proc)):
 interp.commands[name] = proc
 #
 def DeleteCommand(interp, (name)):
 del interp.commands[name]
 #
 # Local variables are maintained on the stack.
 # A local variable with value "None" is a dummy
 # meaning that the corresponding global variable
 # should be used.
 #
 def GetVar(interp, varName):
 dict = interp.globals
 if interp.stack:
 d = interp.stack[-1:][0].locals
 if d.has_key(varName) and d[varName] = None:
 pass
 else:
 dict = d
 if not dict.has_key(varName):
 raise TclRuntimeError, \
 'Variable "' + varName + '" not found'
 return dict[varName]
 #
 def SetVar(interp, (varName, newValue)):
 dict = interp.globals
 if interp.stack:
 d = interp.stack[-1:][0].locals
 if d.has_key(varName) and d[varName] = None:
 pass
 else:
 dict = d
 dict[varName] = newValue
 #
 def Expand(interp, (str, i, end)):
 if end <= i: return ''
 if str[i] = '{' and str[end-1] = '}':
 return str[i+1:end-1]
 if str[i] = '"' and str[end-1] = '"':
 i, end = i+1, end-1
 result = ''
 while i < end:
 c = str[i]
 if c = '\\':
 x, i = Backslash(str, i, end)
 result = result + x
 elif c = '[':
 j = BalanceBrackets(str, i, end)
 x = interp.EvalBasic(str, i+1, j-1, 1)
 result = result + x
 i = j
 elif c = '$':
 i = i+1
 j = FindVarName(str, i, end)
 name = str[i:j]
 i = j
 if not name:
 result = result + '$'
 else:
 if name[:1] = '{' and name[-1:] = '}':
 name = name[1:-1]
 result = result + interp.GetVar(name)
 else:
 j = _expand_prog.exec(str, i)
 j = min(j, end)
 result = result + str[i:j]
 i = j
 return result
 #
 def EvalBasic(interp, (str, i, end, bracketed)):
 result = ''
 while i < end:
 indexargv, i = FindNextCommand( \
 str, i, end, bracketed)
 if indexargv:
 argv = []
 for x, y in indexargv:
 arg = interp.Expand(str, x, y)
 argv.append(arg)
 name = argv[0]
 if not interp.commands.has_key(name):
 raise TclRuntimeError, \
 'Command "' + name + \
 '" not found'
 result = interp.commands[name](argv)
 return result
 #
 def Eval(interp, str):
 return interp.EvalBasic(str, 0, len(str), 0)
 #
 def ExprBasic(interp, (str, begin, end)):
 expr = interp.Expand(str, begin, end)
 i = SkipSpaces(expr, 0, len(expr))
 expr = expr[i:]
 try:
 return eval(expr, {})
 except (NameError, TypeError, RuntimeError, EOFError), msg:
 import sys
 raise TclRuntimeError, sys.exc_type + ': ' + msg
 #
 def Expr(interp, str):
 return interp.ExprBasic(str, 0, len(str))
 #
 # The rest are command implementations
 #
 def BreakCmd(interp, argv):
 if len(argv) <> 1:
 raise TclRuntimeError, 'usage: break'
 raise TclBreak
 #
 def ConcatCmd(interp, argv):
 if len(argv) < 2:
 raise TclRuntimeError, 'usage: concat arg ...'
 return Concat(argv[1:])
 #
 def ContinueCmd(interp, argv):
 if len(argv) <> 1:
 raise TclRuntimeError, 'usage: continue'
 raise TclContinue
 #
 def EchoCmd(interp, argv):
 for arg in argv[1:]: print arg,
 print
 return ''
 #
 def EvalCmd(interp, argv):
 if len(argv) < 2:
 raise TclRuntimeError, 'usage: eval arg [arg ...]'
 str = Concat(argv[1:])
 return interp.Eval(str)
 #
 def ExprCmd(interp, argv):
 if len(argv) <> 2:
 raise TclRuntimeError, 'usage: expr expression'
 expr = argv[1]
 result = interp.Expr(expr)
 if type(result) <> type(''): result = `result`
 return result
 #
 def ForCmd(interp, argv):
 if len(argv) <> 5:
 raise TclRuntimeError, \
 'usage: for start test next body'
 x = interp.Eval(argv[1])
 while interp.Expr(argv[2]):
 try:
 x = interp.Eval(argv[4])
 except TclBreak:
 break
 except TclContinue:
 pass
 x = interp.Eval(argv[3])
 return ''
 #
 def GlobCmd(interp, argv):
 import macglob
 if len(argv) < 2:
 raise TclRuntimeError, 'usage: glob pattern ...'
 list = []
 for pat in argv[1:]:
 list = list + macglob.glob(pat)
 if not list:
 raise TclRuntimeError, 'no match for glob pattern(s)'
 return BuildList(list)
 #
 def GlobalCmd(interp, argv):
 if len(argv) < 2:
 raise TclRuntimeError, 'usage: global varname ...'
 if not interp.stack:
 raise TclRuntimeError, 'global used outside proc'
 dict = interp.stack[-1:][0].locals
 for name in argv[1:]:
 dict[name] = None
 return ''
 #
 def IfCmd(interp, argv):
 argv = argv[:]
 if len(argv) > 2 and argv[2] = 'then': del argv[2]
 if len(argv) > 3 and argv[3] = 'else': del argv[3]
 if not 3 <= len(argv) <= 4:
 raise TclRuntimeError, \
 'usage: if test [then] trueBody [else] falseBody'
 if interp.Expr(argv[1]):
 return interp.Eval(argv[2])
 if len(argv) > 3:
 return interp.Eval(argv[3])
 return ''
 #
 def IndexCmd(interp, argv):
 if len(argv) <> 3:
 raise TclRuntimeError, 'usage: index value index'
 import string
 try:
 index = string.atoi(argv[2])
 if index < 0: raise string.atoi_error
 except string.atoi_error:
 raise TclRuntimeError, 'bad index: ' + argv[2]
 list = SplitList(argv[1])
 if index >= len(list): return ''
 return list[index]
 #
 def ListCmd(interp, argv):
 if len(argv) < 2:
 raise TclRuntimeError, 'usage: list arg ...'
 return BuildList(argv[1:])
 #
 def ProcCmd(interp, argv):
 if len(argv) <> 4:
 raise TclRuntimeError, 'usage: proc name args body'
 x = _Proc().Create(interp, argv[2], argv[3])
 interp.CreateCommand(argv[1], x.Call)
 return ''
 #
 def RenameCmd(interp, argv):
 if len(argv) <> 3:
 raise TclRuntimeError, 'usage: rename oldName newName'
 oldName, newName = argv[1], argv[2]
 if not interp.commands.has_key(oldName):
 raise TclRuntimeError, \
 'command "' + oldName + '" not found'
 if newName: interp.commands[newName] = interp.commands[oldName]
 del interp.commands[oldName]
 return ''
 #
 def ReturnCmd(interp, argv):
 if not 1 <= len(argv) <= 2:
 raise TclRuntimeError, 'usage: return [arg]'
 if len(argv) = 1: raise TclReturn, ''
 raise TclReturn, argv[1]
 #
 def SetCmd(interp, argv):
 n = len(argv)
 if not 2 <= n <= 3:
 raise TclRuntimeError, 'usage: set varname [newvalue]'
 if n = 2: return interp.GetVar(argv[1])
 interp.SetVar(argv[1], argv[2])
 return ''


# The rest are just demos:

def MainLoop(interp):
 buffer = CmdBuf().Create()
 if not interp.globals.has_key('ps1'): interp.globals['ps1'] = '% '
 if not interp.globals.has_key('ps2'): interp.globals['ps2'] = ''
 psname = 'ps1'
 while 1:
 try:
 line = raw_input(interp.globals[psname])
 except (EOFError, KeyboardInterrupt):
 print
 break
 line = buffer.Assemble(line + '\n')
 if not line:
 psname = 'ps2'
 else:
 psname = 'ps1'
 try:
 x = interp.Eval(line)
 if x <> '': print 'Result:', `x`
 except (TclRuntimeError, TclSyntaxError, \
 TclMatchingError), msg:
 print 'Error:', msg
 except (TclBreak, TclContinue):
 print 'Error: break or continue outside loop'
 except TclReturn, value:
 # Return outside proc returns to main loop
 if value: print value


the_interpreter = Interpreter().Create()

def main():
 MainLoop(the_interpreter)


# XXX To do:
# for proc: "args" and default arguments
# More commands:
# case
# uplevel
# info
# string
# list operations
# error, catch
# print
# scan, format
# source
# history?
# others?