diff options
239 files changed, 27034 insertions, 27056 deletions
@@ -5,43 +5,43 @@ This is version 0.9 (the first beta release), patchlevel 1. Python can be used instead of shell, Awk or Perl scripts, to write prototypes of real applications, or as an extension language of large -systems, you name it. There are built-in modules that interface to +systems, you name it. There are built-in modules that interface to the operating system and to various window systems: X11, the Mac window system (you need STDWIN for these two), and Silicon Graphics' -GL library. It runs on most modern versions of UNIX, on the Mac, and -I wouldn't be surprised if it ran on MS-DOS unchanged. I developed it +GL library. It runs on most modern versions of UNIX, on the Mac, and +I wouldn't be surprised if it ran on MS-DOS unchanged. I developed it mostly on an SGI IRIS workstation (using IRIX 3.1 and 3.2) and on the Mac, but have tested it also on SunOS (4.1) and BSD 4.3 (tahoe). Building and installing Python is easy (but do read the Makefile). A UNIX style manual page and extensive documentation (in LaTeX format) -are provided. (In the beta release, the documentation is still under +are provided. (In the beta release, the documentation is still under development.) Please try it out and send me your comments (on anything -- the language design, implementation, portability, installation, documentation) and the modules you wrote for it, to make the first -real release better. If you needed to hack the source to get it to +real release better. If you needed to hack the source to get it to compile and run on a particular machine, send me the fixes -- I'll try -to incorporate them into the next patch. If you can't get it to work +to incorporate them into the next patch. If you can't get it to work at all, send me a *detailed* description of the problem and I may look into it. If you want to profit of the X11 or Mac window interface, you'll need -STDWIN. This is a portable window system interface by the same -author. The versions of STDWIN floating around on some archives are -not sufficiently up-to-date for use with Python. I will distribute +STDWIN. This is a portable window system interface by the same +author. The versions of STDWIN floating around on some archives are +not sufficiently up-to-date for use with Python. I will distribute the latest and greatest STDWIN version at about the same time as Python. I am the author of Python: - Guido van Rossum - CWI, dept. CST - Kruislaan 413 - 1098 SJ Amsterdam - The Netherlands + Guido van Rossum + CWI, dept. CST + Kruislaan 413 + 1098 SJ Amsterdam + The Netherlands - E-mail: [email protected] + E-mail: [email protected] The Python source is copyrighted, but you can freely use and copy it as long as you don't change or remove the copyright: @@ -50,7 +50,7 @@ as long as you don't change or remove the copyright: Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, diff --git a/demo/README b/demo/README index a9ff224..eb17d48 100644 --- a/demo/README +++ b/demo/README @@ -1,22 +1,22 @@ This directory contains various demonstrations of what you can do with -Python. The demos are grouped sub(sub*)directories according to +Python. The demos are grouped sub(sub*)directories according to required optional built-in modules. -scripts Some useful Python scripts that I put in my bin - directory. No optional built-in modules meeded. +scripts Some useful Python scripts that I put in my bin + directory. No optional built-in modules meeded. -sgi Demos that only run on Silicon Graphics machines. - Require the built-in modules 'audio' and/or 'gl'. +sgi Demos that only run on Silicon Graphics machines. + Require the built-in modules 'audio' and/or 'gl'. -stdwin Demos that use the STDWIN library. Require the 'stdwin' - built-in module. +stdwin Demos that use the STDWIN library. Require the 'stdwin' + built-in module. WARNING: some scripts are executable and have a first line saying - #! /ufs/guido/bin/sgi/python + #! /ufs/guido/bin/sgi/python This is unlikely to give good results anywhere else except in my -office. Edit the first line before installing such scripts; to try -them out, you can just say "python file.py". (The .py suffix is not +office. Edit the first line before installing such scripts; to try +them out, you can just say "python file.py". (The .py suffix is not necessary in this case, but makes it possible to debug the modules interactively by importing them.) diff --git a/demo/scripts/findlinksto.py b/demo/scripts/findlinksto.py index 210441e..35f5eea 100755 --- a/demo/scripts/findlinksto.py +++ b/demo/scripts/findlinksto.py @@ -7,23 +7,23 @@ import posix, path, sys def visit(pattern, dirname, names): - if path.islink(dirname): - names[:] = [] - return - if path.ismount(dirname): - print 'descend into', dirname - n = len(pattern) - for name in names: - name = path.cat(dirname, name) - try: - linkto = posix.readlink(name) - if linkto[:n] = pattern: - print name, '->', linkto - except posix.error: - pass + if path.islink(dirname): + names[:] = [] + return + if path.ismount(dirname): + print 'descend into', dirname + n = len(pattern) + for name in names: + name = path.cat(dirname, name) + try: + linkto = posix.readlink(name) + if linkto[:n] = pattern: + print name, '->', linkto + except posix.error: + pass def main(pattern, args): - for dirname in args: - path.walk(dirname, visit, pattern) + for dirname in args: + path.walk(dirname, visit, pattern) main(sys.argv[1], sys.argv[2:]) diff --git a/demo/scripts/mkreal.py b/demo/scripts/mkreal.py index 19fef28..1d62ba0 100755 --- a/demo/scripts/mkreal.py +++ b/demo/scripts/mkreal.py @@ -16,50 +16,50 @@ error = 'mkreal error' BUFSIZE = 32*1024 def mkrealfile(name): - st = posix.stat(name) # Get the mode - mode = S_IMODE(st[ST_MODE]) - linkto = posix.readlink(name) # Make sure again it's a symlink - f_in = open(name, 'r') # This ensures it's a file - posix.unlink(name) - f_out = open(name, 'w') - while 1: - buf = f_in.read(BUFSIZE) - if not buf: break - f_out.write(buf) - del f_out # Flush data to disk before changing mode - posix.chmod(name, mode) + st = posix.stat(name) # Get the mode + mode = S_IMODE(st[ST_MODE]) + linkto = posix.readlink(name) # Make sure again it's a symlink + f_in = open(name, 'r') # This ensures it's a file + posix.unlink(name) + f_out = open(name, 'w') + while 1: + buf = f_in.read(BUFSIZE) + if not buf: break + f_out.write(buf) + del f_out # Flush data to disk before changing mode + posix.chmod(name, mode) def mkrealdir(name): - st = posix.stat(name) # Get the mode - mode = S_IMODE(st[ST_MODE]) - linkto = posix.readlink(name) - files = posix.listdir(name) - posix.unlink(name) - posix.mkdir(name, mode) - posix.chmod(name, mode) - linkto = cat('..', linkto) - # - for file in files: - if file not in ('.', '..'): - posix.symlink(cat(linkto, file), cat(name, file)) + st = posix.stat(name) # Get the mode + mode = S_IMODE(st[ST_MODE]) + linkto = posix.readlink(name) + files = posix.listdir(name) + posix.unlink(name) + posix.mkdir(name, mode) + posix.chmod(name, mode) + linkto = cat('..', linkto) + # + for file in files: + if file not in ('.', '..'): + posix.symlink(cat(linkto, file), cat(name, file)) def main(): - sys.stdout = sys.stderr - progname = path.basename(sys.argv[0]) - args = sys.argv[1:] - if not args: - print 'usage:', progname, 'path ...' - sys.exit(2) - status = 0 - for name in args: - if not path.islink(name): - print progname+':', name+':', 'not a symlink' - status = 1 - else: - if path.isdir(name): - mkrealdir(name) - else: - mkrealfile(name) - sys.exit(status) + sys.stdout = sys.stderr + progname = path.basename(sys.argv[0]) + args = sys.argv[1:] + if not args: + print 'usage:', progname, 'path ...' + sys.exit(2) + status = 0 + for name in args: + if not path.islink(name): + print progname+':', name+':', 'not a symlink' + status = 1 + else: + if path.isdir(name): + mkrealdir(name) + else: + mkrealfile(name) + sys.exit(status) main() diff --git a/demo/scripts/ptags.py b/demo/scripts/ptags.py index 0f99650..8886a71 100755 --- a/demo/scripts/ptags.py +++ b/demo/scripts/ptags.py @@ -15,52 +15,52 @@ import posix import path import string -keywords = ['def', 'class'] # If you add keywords, update starts!!! -starts = 'dc' # Starting characters of keywords +keywords = ['def', 'class'] # If you add keywords, update starts!!! +starts = 'dc' # Starting characters of keywords whitespace = string.whitespace identchars = string.letters + string.digits + '_' -tags = [] # Modified! +tags = [] # Modified! def main(): - args = sys.argv[1:] - for file in args: treat_file(file) - if tags: - fp = open('tags', 'w') - tags.sort() - for s in tags: fp.write(s) + args = sys.argv[1:] + for file in args: treat_file(file) + if tags: + fp = open('tags', 'w') + tags.sort() + for s in tags: fp.write(s) def treat_file(file): - try: - fp = open(file, 'r') - except: - print 'Cannot open', file - return - base = path.basename(file) - if base[-3:] = '.py': base = base[:-3] - s = base + '\t' + file + '\t' + '1\n' - tags.append(s) - while 1: - line = fp.readline() - if not line: break - maketag(line, file) + try: + fp = open(file, 'r') + except: + print 'Cannot open', file + return + base = path.basename(file) + if base[-3:] = '.py': base = base[:-3] + s = base + '\t' + file + '\t' + '1\n' + tags.append(s) + while 1: + line = fp.readline() + if not line: break + maketag(line, file) def maketag(line, file): - i = 0 - while line[i:i+1] in whitespace: i = i+1 - if line[i:i+1] not in starts: return - n = len(line) - j = i - while i < n and line[i] not in whitespace: i = i+1 - if line[j:i] not in keywords: return - while i < n and line[i] in whitespace: i = i+1 - j = i - while i < n and line[i] in identchars: i = i+1 - name = line[j:i] - while i < n and line[i] in whitespace: i = i+1 - if i < n and line[i] = '(': i = i+1 - s = name + '\t' + file + '\t' + '/^' + line[:i] + '/\n' - tags.append(s) + i = 0 + while line[i:i+1] in whitespace: i = i+1 + if line[i:i+1] not in starts: return + n = len(line) + j = i + while i < n and line[i] not in whitespace: i = i+1 + if line[j:i] not in keywords: return + while i < n and line[i] in whitespace: i = i+1 + j = i + while i < n and line[i] in identchars: i = i+1 + name = line[j:i] + while i < n and line[i] in whitespace: i = i+1 + if i < n and line[i] = '(': i = i+1 + s = name + '\t' + file + '\t' + '/^' + line[:i] + '/\n' + tags.append(s) main() diff --git a/demo/scripts/suff.py b/demo/scripts/suff.py index f6bd6bf..d6abecc 100755 --- a/demo/scripts/suff.py +++ b/demo/scripts/suff.py @@ -7,23 +7,23 @@ import sys def main(): - files = sys.argv[1:] - suffixes = {} - for file in files: - suff = getsuffix(file) - if not suffixes.has_key(suff): - suffixes[suff] = [] - suffixes[suff].append(file) - keys = suffixes.keys() - keys.sort() - for suff in keys: - print `suff`, len(suffixes[suff]) + files = sys.argv[1:] + suffixes = {} + for file in files: + suff = getsuffix(file) + if not suffixes.has_key(suff): + suffixes[suff] = [] + suffixes[suff].append(file) + keys = suffixes.keys() + keys.sort() + for suff in keys: + print `suff`, len(suffixes[suff]) def getsuffix(file): - suff = '' - for i in range(len(file)): - if file[i] = '.': - suff = file[i:] - return suff + suff = '' + for i in range(len(file)): + if file[i] = '.': + suff = file[i:] + return suff main() diff --git a/demo/scripts/xxci.py b/demo/scripts/xxci.py index 43ea316..7f6a402 100755 --- a/demo/scripts/xxci.py +++ b/demo/scripts/xxci.py @@ -13,65 +13,65 @@ import commands MAXSIZE = 200*1024 # Files this big must be binaries and are skipped. def getargs(): - args = sys.argv[1:] - if args: - return args - print 'No arguments, checking almost *' - for file in posix.listdir('.'): - if not skipfile(file): - args.append(file) - if not args: - print 'Nothing to do -- exit 1' - sys.exit(1) - args.sort() - return args + args = sys.argv[1:] + if args: + return args + print 'No arguments, checking almost *' + for file in posix.listdir('.'): + if not skipfile(file): + args.append(file) + if not args: + print 'Nothing to do -- exit 1' + sys.exit(1) + args.sort() + return args badnames = ['tags', 'xyzzy'] badprefixes = ['.', ',', '@', '#', 'o.'] badsuffixes = \ - ['~', '.a', '.o', '.old', '.bak', '.orig', '.new', '.prev', '.not'] + ['~', '.a', '.o', '.old', '.bak', '.orig', '.new', '.prev', '.not'] # XXX Should generalize even more to use fnmatch! def skipfile(file): - if file in badnames or \ - badprefix(file) or badsuffix(file) or \ - path.islink(file) or path.isdir(file): - return 1 - # Skip huge files -- probably binaries. - try: - st = posix.stat(file) - except posix.error: - return 1 # Doesn't exist -- skip it - return st[stat.ST_SIZE] >= MAXSIZE + if file in badnames or \ + badprefix(file) or badsuffix(file) or \ + path.islink(file) or path.isdir(file): + return 1 + # Skip huge files -- probably binaries. + try: + st = posix.stat(file) + except posix.error: + return 1 # Doesn't exist -- skip it + return st[stat.ST_SIZE] >= MAXSIZE def badprefix(file): - for bad in badprefixes: - if file[:len(bad)] = bad: return 1 - return 0 + for bad in badprefixes: + if file[:len(bad)] = bad: return 1 + return 0 def badsuffix(file): - for bad in badsuffixes: - if file[-len(bad):] = bad: return 1 - return 0 + for bad in badsuffixes: + if file[-len(bad):] = bad: return 1 + return 0 def go(args): - for file in args: - print file + ':' - if run('rcsdiff -c', file): - if askyesno('Check in ' + file + ' ? '): - sts = run('rcs -l', file) # ignored - # can't use run() here because it's interactive - sts = posix.system('ci -l ' + file) + for file in args: + print file + ':' + if run('rcsdiff -c', file): + if askyesno('Check in ' + file + ' ? '): + sts = run('rcs -l', file) # ignored + # can't use run() here because it's interactive + sts = posix.system('ci -l ' + file) def run(cmd, file): - sts, output = commands.getstatusoutput(cmd + commands.mkarg(file)) - if sts: - print output - print 'Exit status', sts - return sts + sts, output = commands.getstatusoutput(cmd + commands.mkarg(file)) + if sts: + print output + print 'Exit status', sts + return sts def askyesno(prompt): - s = raw_input(prompt) - return s in ['y', 'yes'] + s = raw_input(prompt) + return s in ['y', 'yes'] go(getargs()) diff --git a/demo/sgi/README b/demo/sgi/README index 5740c22..ecf1e82 100644 --- a/demo/sgi/README +++ b/demo/sgi/README @@ -1,15 +1,15 @@ Demonstrations of Python that use various features of the Silicon Graphics IRIS machines. -audio Demonstrations of the audio capabilities of the 4D/25. - Require the built-in module 'audio'. +audio Demonstrations of the audio capabilities of the 4D/25. + Require the built-in module 'audio'. -audio_stdwin Window-based demonstrations the audio capabilities of - the 4D/25. Require the built-in modules 'stdwin' and - 'audio'. +audio_stdwin Window-based demonstrations the audio capabilities of + the 4D/25. Require the built-in modules 'stdwin' and + 'audio'. -gl Demonstrations of the Graphics Library (GL). - Require the built-in module 'gl'. +gl Demonstrations of the Graphics Library (GL). + Require the built-in module 'gl'. -gl_panel Demonstrations of the Panel Library by NASA Ames. - Require the built-in modules 'gl' and 'pnl'. +gl_panel Demonstrations of the Panel Library by NASA Ames. + Require the built-in modules 'gl' and 'pnl'. diff --git a/demo/sgi/audio/README b/demo/sgi/audio/README index 17dc9b2..5bf6120 100644 --- a/demo/sgi/audio/README +++ b/demo/sgi/audio/README @@ -1,5 +1,5 @@ Programs that demonstrate the use of the audio device on the SGI 4D/25. These require the built-in module 'audio'. -play Read a sound sample from a file and play it through the - speaker. Options to set volume, sampling rate etc. +play Read a sound sample from a file and play it through the + speaker. Options to set volume, sampling rate etc. diff --git a/demo/sgi/audio/play.py b/demo/sgi/audio/play.py index 8f6a802..1d214cf 100755 --- a/demo/sgi/audio/play.py +++ b/demo/sgi/audio/play.py @@ -12,64 +12,64 @@ debug = [] DEF_RATE = 3 def main(): - # - gain = 100 - rate = 0 - starter = audio.write - stopper = 0 - # - optlist, args = getopt.getopt(sys.argv[1:], 'adg:r:') - # - for optname, optarg in optlist: - if 0: - pass - elif optname = '-d': - debug.append(1) - elif optname = '-g': - gain = string.atoi(optarg) - if not (0 < gain < 256): - raise optarg.error, '-g gain out of range' - elif optname = '-r': - rate = string.atoi(optarg) - if not (1 <= rate <= 3): - raise optarg.error, '-r rate out of range' - elif optname = '-a': - starter = audio.start_playing - stopper = audio.wait_playing - # - audio.setoutgain(gain) - audio.setrate(rate) - # - if not args: - play(starter, rate, auds.loadfp(sys.stdin)) - else: - real_stopper = 0 - for file in args: - if real_stopper: - real_stopper() - play(starter, rate, auds.load(file)) - real_stopper = stopper + # + gain = 100 + rate = 0 + starter = audio.write + stopper = 0 + # + optlist, args = getopt.getopt(sys.argv[1:], 'adg:r:') + # + for optname, optarg in optlist: + if 0: + pass + elif optname = '-d': + debug.append(1) + elif optname = '-g': + gain = string.atoi(optarg) + if not (0 < gain < 256): + raise optarg.error, '-g gain out of range' + elif optname = '-r': + rate = string.atoi(optarg) + if not (1 <= rate <= 3): + raise optarg.error, '-r rate out of range' + elif optname = '-a': + starter = audio.start_playing + stopper = audio.wait_playing + # + audio.setoutgain(gain) + audio.setrate(rate) + # + if not args: + play(starter, rate, auds.loadfp(sys.stdin)) + else: + real_stopper = 0 + for file in args: + if real_stopper: + real_stopper() + play(starter, rate, auds.load(file)) + real_stopper = stopper def play(starter, rate, data): - magic = data[:4] - if magic = '0008': - mrate = 3 - elif magic = '0016': - mrate = 2 - elif magic = '0032': - mrate = 1 - else: - mrate = 0 - if mrate: - data = data[4:] - else: - mrate = DEF_RATE - if not rate: rate = mrate - audio.setrate(rate) - starter(data) + magic = data[:4] + if magic = '0008': + mrate = 3 + elif magic = '0016': + mrate = 2 + elif magic = '0032': + mrate = 1 + else: + mrate = 0 + if mrate: + data = data[4:] + else: + mrate = DEF_RATE + if not rate: rate = mrate + audio.setrate(rate) + starter(data) try: - main() + main() finally: - audio.setoutgain(0) - audio.done() + audio.setoutgain(0) + audio.done() diff --git a/demo/sgi/audio_stdwin/README b/demo/sgi/audio_stdwin/README index 3074715..24a710a 100644 --- a/demo/sgi/audio_stdwin/README +++ b/demo/sgi/audio_stdwin/README @@ -1,16 +1,16 @@ Three programs that provide a user interface based upon STDWIN to the -audio device of the SGI 4D/25. These scripts also demonstrate the power +audio device of the SGI 4D/25. These scripts also demonstrate the power of a set of window interface classes implemented in Python that simplify the construction of all sorts of buttons, etc. -jukebox Browses a directory full of sound samples and lets you - play selected ones. (Probably not fully functional, it - requires a conversion program.) +jukebox Browses a directory full of sound samples and lets you + play selected ones. (Probably not fully functional, it + requires a conversion program.) -rec A tape recorder that lets you record a sound sample, - play it back, and save it to a file. Various options to - set sampling rate, volume etc. When idle it doubles - as a VU meter. +rec A tape recorder that lets you record a sound sample, + play it back, and save it to a file. Various options to + set sampling rate, volume etc. When idle it doubles + as a VU meter. -vumeter A VU meter that displays a history of the volume of - sound recently sampled from the microphone. +vumeter A VU meter that displays a history of the volume of + sound recently sampled from the microphone. diff --git a/demo/sgi/audio_stdwin/jukebox.py b/demo/sgi/audio_stdwin/jukebox.py index 5267d73..855ed43 100755 --- a/demo/sgi/audio_stdwin/jukebox.py +++ b/demo/sgi/audio_stdwin/jukebox.py @@ -3,8 +3,8 @@ # JUKEBOX: browse directories full of sampled sound files. # # One or more "list windows" display the files and subdirectories of -# the arguments. Double-clicking on a subdirectory opens a new window -# displaying its contents (and so on recursively). Double clicking +# the arguments. Double-clicking on a subdirectory opens a new window +# displaying its contents (and so on recursively). Double clicking # on a file plays it as a sound file (assuming it is one). # # Playing is asynchronous: the application keeps listening to events @@ -16,7 +16,7 @@ # # Sound files must currently be in Dik Winter's compressed Mac format. # Since decompression is costly, decompressed samples are saved in -# /usr/tmp/@j* until the application is left. The files are read +# /usr/tmp/@j* until the application is left. The files are read # afresh each time, though. import audio @@ -38,205 +38,205 @@ from Sliders import ComplexSlider # Pathnames -HOME_BIN_SGI = '/ufs/guido/bin/sgi/' # Directory where macsound2sgi lives -DEF_DB = '/ufs/dik/sounds/Mac/HCOM' # Default directory of sounds +HOME_BIN_SGI = '/ufs/guido/bin/sgi/' # Directory where macsound2sgi lives +DEF_DB = '/ufs/dik/sounds/Mac/HCOM' # Default directory of sounds # Global variables -class struct(): pass # Class to define featureless structures +class struct(): pass # Class to define featureless structures -G = struct() # Holds writable global variables +G = struct() # Holds writable global variables # Main program def main(): - G.synchronous = 0 # If set, use synchronous audio.write() - G.debug = 0 # If set, print debug messages - G.gain = 75 # Output gain - G.rate = 3 # Sampling rate - G.busy = 0 # Set while asynchronous playing is active - G.windows = [] # List of open windows (except control) - G.mode = 'mac' # Macintosh mode - G.tempprefix = '/usr/tmp/@j' + `rand.rand()` + '-' - # - optlist, args = getopt.getopt(sys.argv[1:], 'dg:r:sSa') - for optname, optarg in optlist: - if optname = '-d': - G.debug = 1 - elif optname = '-g': - G.gain = string.atoi(optarg) - if not (0 < G.gain < 256): - raise optarg.error, '-g gain out of range' - elif optname = '-r': - G.rate = string.atoi(optarg) - if not (1 <= G.rate <= 3): - raise optarg.error, '-r rate out of range' - elif optname = '-s': - G.synchronous = 1 - elif optname = '-S': - G.mode = 'sgi' - elif optname = '-a': - G.mode = 'sun' - # - if not args: - args = [DEF_DB] - # - G.cw = opencontrolwindow() - for dirname in args: - G.windows.append(openlistwindow(dirname)) - # - # - savegain = audio.getoutgain() - try: - # Initialize stdaudio - audio.setoutgain(0) - audio.start_playing('') - dummy = audio.wait_playing() - audio.setoutgain(0) - maineventloop() - finally: - audio.setoutgain(savegain) - audio.done() - clearcache() + G.synchronous = 0 # If set, use synchronous audio.write() + G.debug = 0 # If set, print debug messages + G.gain = 75 # Output gain + G.rate = 3 # Sampling rate + G.busy = 0 # Set while asynchronous playing is active + G.windows = [] # List of open windows (except control) + G.mode = 'mac' # Macintosh mode + G.tempprefix = '/usr/tmp/@j' + `rand.rand()` + '-' + # + optlist, args = getopt.getopt(sys.argv[1:], 'dg:r:sSa') + for optname, optarg in optlist: + if optname = '-d': + G.debug = 1 + elif optname = '-g': + G.gain = string.atoi(optarg) + if not (0 < G.gain < 256): + raise optarg.error, '-g gain out of range' + elif optname = '-r': + G.rate = string.atoi(optarg) + if not (1 <= G.rate <= 3): + raise optarg.error, '-r rate out of range' + elif optname = '-s': + G.synchronous = 1 + elif optname = '-S': + G.mode = 'sgi' + elif optname = '-a': + G.mode = 'sun' + # + if not args: + args = [DEF_DB] + # + G.cw = opencontrolwindow() + for dirname in args: + G.windows.append(openlistwindow(dirname)) + # + # + savegain = audio.getoutgain() + try: + # Initialize stdaudio + audio.setoutgain(0) + audio.start_playing('') + dummy = audio.wait_playing() + audio.setoutgain(0) + maineventloop() + finally: + audio.setoutgain(savegain) + audio.done() + clearcache() def maineventloop(): - mouse_events = WE_MOUSE_DOWN, WE_MOUSE_MOVE, WE_MOUSE_UP - while G.windows: - type, w, detail = event = stdwin.getevent() - if w = G.cw.win: - if type = WE_CLOSE: - return - G.cw.dispatch(event) - else: - if type = WE_DRAW: - w.drawproc(w, detail) - elif type in mouse_events: - w.mouse(w, type, detail) - elif type = WE_CLOSE: - w.close(w) - del w, event - else: - if G.debug: print type, w, detail + mouse_events = WE_MOUSE_DOWN, WE_MOUSE_MOVE, WE_MOUSE_UP + while G.windows: + type, w, detail = event = stdwin.getevent() + if w = G.cw.win: + if type = WE_CLOSE: + return + G.cw.dispatch(event) + else: + if type = WE_DRAW: + w.drawproc(w, detail) + elif type in mouse_events: + w.mouse(w, type, detail) + elif type = WE_CLOSE: + w.close(w) + del w, event + else: + if G.debug: print type, w, detail # Control window -- to set gain and cancel play operations in progress def opencontrolwindow(): - cw = WindowParent().create('Jukebox', (0, 0)) - v = VSplit().create(cw) - # - gain = ComplexSlider().define(v) - gain.setminvalmax(0, G.gain, 255) - gain.settexts(' ', ' ') - gain.sethook(gain_setval_hook) - # - stop = PushButton().definetext(v, 'Stop') - stop.hook = stop_hook - # - cw.realize() - return cw + cw = WindowParent().create('Jukebox', (0, 0)) + v = VSplit().create(cw) + # + gain = ComplexSlider().define(v) + gain.setminvalmax(0, G.gain, 255) + gain.settexts(' ', ' ') + gain.sethook(gain_setval_hook) + # + stop = PushButton().definetext(v, 'Stop') + stop.hook = stop_hook + # + cw.realize() + return cw def gain_setval_hook(self): - G.gain = self.val - if G.busy: audio.setoutgain(G.gain) + G.gain = self.val + if G.busy: audio.setoutgain(G.gain) def stop_hook(self): - if G.busy: - audio.setoutgain(0) - dummy = audio.stop_playing() - G.busy = 0 + if G.busy: + audio.setoutgain(0) + dummy = audio.stop_playing() + G.busy = 0 # List windows -- to display list of files and subdirectories def openlistwindow(dirname): - list = posix.listdir(dirname) - list.sort() - i = 0 - while i < len(list): - if list[i] = '.' or list[i] = '..': - del list[i] - else: - i = i+1 - for i in range(len(list)): - name = list[i] - if path.isdir(path.cat(dirname, name)): - list[i] = list[i] + '/' - width = maxwidth(list) - width = width + stdwin.textwidth(' ') # XXX X11 stdwin bug workaround - height = len(list) * stdwin.lineheight() - stdwin.setdefwinsize(width, min(height, 500)) - w = stdwin.open(dirname) - stdwin.setdefwinsize(0, 0) - w.setdocsize(width, height) - w.drawproc = drawlistwindow - w.mouse = mouselistwindow - w.close = closelistwindow - w.dirname = dirname - w.list = list - w.selected = -1 - return w + list = posix.listdir(dirname) + list.sort() + i = 0 + while i < len(list): + if list[i] = '.' or list[i] = '..': + del list[i] + else: + i = i+1 + for i in range(len(list)): + name = list[i] + if path.isdir(path.cat(dirname, name)): + list[i] = list[i] + '/' + width = maxwidth(list) + width = width + stdwin.textwidth(' ') # XXX X11 stdwin bug workaround + height = len(list) * stdwin.lineheight() + stdwin.setdefwinsize(width, min(height, 500)) + w = stdwin.open(dirname) + stdwin.setdefwinsize(0, 0) + w.setdocsize(width, height) + w.drawproc = drawlistwindow + w.mouse = mouselistwindow + w.close = closelistwindow + w.dirname = dirname + w.list = list + w.selected = -1 + return w def maxwidth(list): - width = 1 - for name in list: - w = stdwin.textwidth(name) - if w > width: width = w - return width + width = 1 + for name in list: + w = stdwin.textwidth(name) + if w > width: width = w + return width def drawlistwindow(w, area): - d = w.begindrawing() - d.erase((0, 0), (1000, 10000)) - lh = d.lineheight() - h, v = 0, 0 - for name in w.list: - d.text((h, v), name) - v = v + lh - showselection(w, d) + d = w.begindrawing() + d.erase((0, 0), (1000, 10000)) + lh = d.lineheight() + h, v = 0, 0 + for name in w.list: + d.text((h, v), name) + v = v + lh + showselection(w, d) def hideselection(w, d): - if w.selected >= 0: - invertselection(w, d) + if w.selected >= 0: + invertselection(w, d) def showselection(w, d): - if w.selected >= 0: - invertselection(w, d) + if w.selected >= 0: + invertselection(w, d) def invertselection(w, d): - lh = d.lineheight() - h1, v1 = p1 = 0, w.selected*lh - h2, v2 = p2 = 1000, v1 + lh - d.invert(p1, p2) + lh = d.lineheight() + h1, v1 = p1 = 0, w.selected*lh + h2, v2 = p2 = 1000, v1 + lh + d.invert(p1, p2) def mouselistwindow(w, type, detail): - (h, v), clicks, button = detail[:3] - d = w.begindrawing() - lh = d.lineheight() - if 0 <= v < lh*len(w.list): - i = v / lh - else: - i = -1 - if w.selected <> i: - hideselection(w, d) - w.selected = i - showselection(w, d) - if type = WE_MOUSE_DOWN and clicks >= 2 and i >= 0: - name = path.cat(w.dirname, w.list[i]) - if name[-1:] = '/': - if clicks = 2: - G.windows.append(openlistwindow(name[:-1])) - else: - playfile(name) + (h, v), clicks, button = detail[:3] + d = w.begindrawing() + lh = d.lineheight() + if 0 <= v < lh*len(w.list): + i = v / lh + else: + i = -1 + if w.selected <> i: + hideselection(w, d) + w.selected = i + showselection(w, d) + if type = WE_MOUSE_DOWN and clicks >= 2 and i >= 0: + name = path.cat(w.dirname, w.list[i]) + if name[-1:] = '/': + if clicks = 2: + G.windows.append(openlistwindow(name[:-1])) + else: + playfile(name) def closelistwindow(w): - remove(G.windows, w) + remove(G.windows, w) def remove(list, item): - for i in range(len(list)): - if list[i] = item: - del list[i] - break + for i in range(len(list)): + if list[i] = item: + del list[i] + break # Playing tools @@ -244,78 +244,78 @@ def remove(list, item): cache = {} def clearcache(): - for x in cache.keys(): - try: - sts = posix.system('rm -f ' + cache[x]) - if sts: - print cmd - print 'Exit status', sts - except: - print cmd - print 'Exception?!' - del cache[x] + for x in cache.keys(): + try: + sts = posix.system('rm -f ' + cache[x]) + if sts: + print cmd + print 'Exit status', sts + except: + print cmd + print 'Exception?!' + del cache[x] def playfile(name): - if G.mode <> 'mac': - tempname = name - elif cache.has_key(name): - tempname = cache[name] - else: - tempname = G.tempprefix + `rand.rand()` - cmd = HOME_BIN_SGI + 'macsound2sgi' - cmd = cmd + ' ' + commands.mkarg(name) - cmd = cmd + ' >' + tempname - if G.debug: print cmd - sts = posix.system(cmd) - if sts: - print cmd - print 'Exit status', sts - stdwin.fleep() - return - cache[name] = tempname - fp = open(tempname, 'r') - try: - hdr = sunaudio.gethdr(fp) - except sunaudio.error, msg: - hdr = () - if hdr: - data_size = hdr[0] - data = fp.read(data_size) - # XXX this doesn't work yet, need to convert from uLAW!!! - del fp - else: - del fp - data = readfile(tempname) - if G.debug: print len(data), 'bytes read from', tempname - if G.busy: - G.busy = 0 - dummy = audio.stop_playing() - # - # Completely reset the audio device - audio.setrate(G.rate) - audio.setduration(0) - audio.setoutgain(G.gain) - # - if G.synchronous: - audio.write(data) - audio.setoutgain(0) - else: - try: - audio.start_playing(data) - G.busy = 1 - except: - stdwin.fleep() - del data + if G.mode <> 'mac': + tempname = name + elif cache.has_key(name): + tempname = cache[name] + else: + tempname = G.tempprefix + `rand.rand()` + cmd = HOME_BIN_SGI + 'macsound2sgi' + cmd = cmd + ' ' + commands.mkarg(name) + cmd = cmd + ' >' + tempname + if G.debug: print cmd + sts = posix.system(cmd) + if sts: + print cmd + print 'Exit status', sts + stdwin.fleep() + return + cache[name] = tempname + fp = open(tempname, 'r') + try: + hdr = sunaudio.gethdr(fp) + except sunaudio.error, msg: + hdr = () + if hdr: + data_size = hdr[0] + data = fp.read(data_size) + # XXX this doesn't work yet, need to convert from uLAW!!! + del fp + else: + del fp + data = readfile(tempname) + if G.debug: print len(data), 'bytes read from', tempname + if G.busy: + G.busy = 0 + dummy = audio.stop_playing() + # + # Completely reset the audio device + audio.setrate(G.rate) + audio.setduration(0) + audio.setoutgain(G.gain) + # + if G.synchronous: + audio.write(data) + audio.setoutgain(0) + else: + try: + audio.start_playing(data) + G.busy = 1 + except: + stdwin.fleep() + del data def readfile(filename): - return readfp(open(filename, 'r')) + return readfp(open(filename, 'r')) def readfp(fp): - data = '' - while 1: - buf = fp.read(102400) # Reads most samples in one fell swoop - if not buf: - return data - data = data + buf + data = '' + while 1: + buf = fp.read(102400) # Reads most samples in one fell swoop + if not buf: + return data + data = data + buf main() diff --git a/demo/sgi/audio_stdwin/rec.py b/demo/sgi/audio_stdwin/rec.py index 3ab3aea..a48716a 100755 --- a/demo/sgi/audio_stdwin/rec.py +++ b/demo/sgi/audio_stdwin/rec.py @@ -16,14 +16,14 @@ from WindowParent import WindowParent from HVSplit import HSplit, VSplit class TimeOutToggleButton() = ToggleButton(): - def define(self, parent): - self = ToggleButton.define(self, parent) - self.parent.need_timer(self) - self.timer_hook = 0 - return self - def timer(self): - if self.timer_hook: - self.timer_hook(self) + def define(self, parent): + self = ToggleButton.define(self, parent) + self.parent.need_timer(self) + self.timer_hook = 0 + return self + def timer(self): + if self.timer_hook: + self.timer_hook(self) K = 1024 BUFSIZE = 30*8*K @@ -34,238 +34,238 @@ class Struct(): pass G = Struct() def main(): - # - # Set default state - # - G.gain = 60 - G.rate = 3 - G.nomuting = 0 - G.savefile = '@rec' - # - # Set default values - # - G.data = '' - G.playing = 0 - G.recording = 0 - G.sogram = 0 - # - # Parse options - # - optlist, args = getopt.getopt(sys.argv[1:], 'mdg:r:') - # - for optname, optarg in optlist: - if 0: # (So all cases start with elif) - pass - elif optname = '-d': - G.debug = 1 - elif optname = '-g': - G.gain = string.atoi(optarg) - if not (0 < G.gain < 256): - raise optarg.error, '-g gain out of range' - elif optname = '-m': - G.nomuting = (not G.nomuting) - elif optname = '-r': - G.rate = string.atoi(optarg) - if not (1 <= G.rate <= 3): - raise optarg.error, '-r rate out of range' - # - if args: - G.savefile = args[0] - # - # Initialize the sound package - # - audio.setoutgain(G.nomuting * G.gain) # Silence the speaker - audio.setrate(G.rate) - # - # Create the WindowParent and VSplit - # - G.window = WindowParent().create('Recorder', (0, 0)) - w = G.vsplit = VSplit().create(G.window) - # - # VU-meter - # - G.vubtn = VUMeter().define(w) - # - # Radiobuttons for rates - # - r1btn = RadioButton().definetext(w, '32 K/sec') - r1btn.on_hook = rate_hook - r1btn.rate = 1 - # - r2btn = RadioButton().definetext(w, '16 K/sec') - r2btn.on_hook = rate_hook - r2btn.rate = 2 - # - r3btn = RadioButton().definetext(w, '8 K/sec') - r3btn.on_hook = rate_hook - r3btn.rate = 3 - # - radios = [r1btn, r2btn, r3btn] - r1btn.group = r2btn.group = r3btn.group = radios - for r in radios: - if r.rate = G.rate: r.select(1) - # - # Other controls - # - G.recbtn = TimeOutToggleButton().definetext(w, 'Record') - G.recbtn.on_hook = record_on_hook - G.recbtn.timer_hook = record_timer_hook - G.recbtn.off_hook = record_off_hook - # - G.mutebtn = CheckButton().definetext(w, 'Mute') - G.mutebtn.select(not G.nomuting) - G.mutebtn.hook = mute_hook - # - G.playbtn = TimeOutToggleButton().definetext(w, 'Playback') - G.playbtn.on_hook = play_on_hook - G.playbtn.timer_hook = play_timer_hook - G.playbtn.off_hook = play_off_hook - # - G.gainbtn = ComplexSlider().define(w) - G.gainbtn.settexts(' Volume: ', ' ') - G.gainbtn.setminvalmax(0, G.gain, 255) - G.gainbtn.sethook(gain_hook) - # - G.sizebtn = Label().definetext(w, `len(G.data)` + ' bytes') - # - #G.showbtn = PushButton().definetext(w, 'Sound-o-gram...') - #G.showbtn.hook = show_hook - # - G.savebtn = PushButton().definetext(w, 'Save...') - G.savebtn.hook = save_hook - # - G.quitbtn = PushButton().definetext(w, 'Quit') - G.quitbtn.hook = quit_hook - G.playbtn.enable(0) - G.savebtn.enable(0) - #G.showbtn.enable(0) - start_vu() - G.window.realize() - # - # Event loop - # - while 1: - e = stdwin.getevent() - G.window.dispatch(e) + # + # Set default state + # + G.gain = 60 + G.rate = 3 + G.nomuting = 0 + G.savefile = '@rec' + # + # Set default values + # + G.data = '' + G.playing = 0 + G.recording = 0 + G.sogram = 0 + # + # Parse options + # + optlist, args = getopt.getopt(sys.argv[1:], 'mdg:r:') + # + for optname, optarg in optlist: + if 0: # (So all cases start with elif) + pass + elif optname = '-d': + G.debug = 1 + elif optname = '-g': + G.gain = string.atoi(optarg) + if not (0 < G.gain < 256): + raise optarg.error, '-g gain out of range' + elif optname = '-m': + G.nomuting = (not G.nomuting) + elif optname = '-r': + G.rate = string.atoi(optarg) + if not (1 <= G.rate <= 3): + raise optarg.error, '-r rate out of range' + # + if args: + G.savefile = args[0] + # + # Initialize the sound package + # + audio.setoutgain(G.nomuting * G.gain) # Silence the speaker + audio.setrate(G.rate) + # + # Create the WindowParent and VSplit + # + G.window = WindowParent().create('Recorder', (0, 0)) + w = G.vsplit = VSplit().create(G.window) + # + # VU-meter + # + G.vubtn = VUMeter().define(w) + # + # Radiobuttons for rates + # + r1btn = RadioButton().definetext(w, '32 K/sec') + r1btn.on_hook = rate_hook + r1btn.rate = 1 + # + r2btn = RadioButton().definetext(w, '16 K/sec') + r2btn.on_hook = rate_hook + r2btn.rate = 2 + # + r3btn = RadioButton().definetext(w, '8 K/sec') + r3btn.on_hook = rate_hook + r3btn.rate = 3 + # + radios = [r1btn, r2btn, r3btn] + r1btn.group = r2btn.group = r3btn.group = radios + for r in radios: + if r.rate = G.rate: r.select(1) + # + # Other controls + # + G.recbtn = TimeOutToggleButton().definetext(w, 'Record') + G.recbtn.on_hook = record_on_hook + G.recbtn.timer_hook = record_timer_hook + G.recbtn.off_hook = record_off_hook + # + G.mutebtn = CheckButton().definetext(w, 'Mute') + G.mutebtn.select(not G.nomuting) + G.mutebtn.hook = mute_hook + # + G.playbtn = TimeOutToggleButton().definetext(w, 'Playback') + G.playbtn.on_hook = play_on_hook + G.playbtn.timer_hook = play_timer_hook + G.playbtn.off_hook = play_off_hook + # + G.gainbtn = ComplexSlider().define(w) + G.gainbtn.settexts(' Volume: ', ' ') + G.gainbtn.setminvalmax(0, G.gain, 255) + G.gainbtn.sethook(gain_hook) + # + G.sizebtn = Label().definetext(w, `len(G.data)` + ' bytes') + # + #G.showbtn = PushButton().definetext(w, 'Sound-o-gram...') + #G.showbtn.hook = show_hook + # + G.savebtn = PushButton().definetext(w, 'Save...') + G.savebtn.hook = save_hook + # + G.quitbtn = PushButton().definetext(w, 'Quit') + G.quitbtn.hook = quit_hook + G.playbtn.enable(0) + G.savebtn.enable(0) + #G.showbtn.enable(0) + start_vu() + G.window.realize() + # + # Event loop + # + while 1: + e = stdwin.getevent() + G.window.dispatch(e) # XXX Disabled... def show_hook(self): - savetext = self.text - self.settext('Be patient...') - close_sogram() - stdwin.setdefwinsize(400, 300) - win = stdwin.open('Sound-o-gram') - G.sogram = Soundogram().define(win, G.data) - win.buttons = [G.sogram] - self.settext(savetext) + savetext = self.text + self.settext('Be patient...') + close_sogram() + stdwin.setdefwinsize(400, 300) + win = stdwin.open('Sound-o-gram') + G.sogram = Soundogram().define(win, G.data) + win.buttons = [G.sogram] + self.settext(savetext) def close_sogram(): - if G.sogram: - # Break circular references - G.sogram.win.buttons[:] = [] - del G.sogram.win - G.sogram = 0 + if G.sogram: + # Break circular references + G.sogram.win.buttons[:] = [] + del G.sogram.win + G.sogram = 0 def mute_hook(self): - G.nomuting = (not self.selected) - audio.setoutgain(G.nomuting * G.gain) + G.nomuting = (not self.selected) + audio.setoutgain(G.nomuting * G.gain) def rate_hook(self): - G.rate = self.rate - audio.setrate(G.rate) + G.rate = self.rate + audio.setrate(G.rate) def record_on_hook(self): - stop_vu() - close_sogram() - audio.setrate(G.rate) - audio.setoutgain(G.nomuting * G.gain) - audio.start_recording(BUFSIZE) - G.recording = 1 - G.playbtn.enable(0) - G.window.settimer(10 * BUFSIZE / Rates[G.rate]) + stop_vu() + close_sogram() + audio.setrate(G.rate) + audio.setoutgain(G.nomuting * G.gain) + audio.start_recording(BUFSIZE) + G.recording = 1 + G.playbtn.enable(0) + G.window.settimer(10 * BUFSIZE / Rates[G.rate]) def record_timer_hook(self): - if G.recording: - if audio.poll_recording(): - self.hilite(0) - record_off_hook(self) - else: - self.parent.settimer(5) + if G.recording: + if audio.poll_recording(): + self.hilite(0) + record_off_hook(self) + else: + self.parent.settimer(5) def record_off_hook(self): - if not G.recording: - return - G.data = audio.stop_recording() - G.recording = 0 - G.sizebtn.settext(`len(G.data)` + ' bytes') - audio.setoutgain(G.nomuting * G.gain) - G.playbtn.enable((len(G.data) > 0)) - G.savebtn.enable((len(G.data) > 0)) - #G.showbtn.enable((len(G.data) > 0)) - G.window.settimer(0) - start_vu() + if not G.recording: + return + G.data = audio.stop_recording() + G.recording = 0 + G.sizebtn.settext(`len(G.data)` + ' bytes') + audio.setoutgain(G.nomuting * G.gain) + G.playbtn.enable((len(G.data) > 0)) + G.savebtn.enable((len(G.data) > 0)) + #G.showbtn.enable((len(G.data) > 0)) + G.window.settimer(0) + start_vu() def play_on_hook(self): - stop_vu() - audio.setrate(G.rate) - audio.setoutgain(G.gain) - audio.start_playing(G.data) - G.playing = 1 - G.recbtn.enable(0) - G.window.settimer(max(10 * len(G.data) / Rates[G.rate], 1)) + stop_vu() + audio.setrate(G.rate) + audio.setoutgain(G.gain) + audio.start_playing(G.data) + G.playing = 1 + G.recbtn.enable(0) + G.window.settimer(max(10 * len(G.data) / Rates[G.rate], 1)) def play_timer_hook(self): - if G.playing: - if audio.poll_playing(): - self.hilite(0) - play_off_hook(self) - else: - self.parent.settimer(5) + if G.playing: + if audio.poll_playing(): + self.hilite(0) + play_off_hook(self) + else: + self.parent.settimer(5) def play_off_hook(self): - if not G.playing: - return - x = audio.stop_playing() - G.playing = 0 - audio.setoutgain(G.nomuting * G.gain) - G.recbtn.enable(1) - G.window.settimer(0) - start_vu() + if not G.playing: + return + x = audio.stop_playing() + G.playing = 0 + audio.setoutgain(G.nomuting * G.gain) + G.recbtn.enable(1) + G.window.settimer(0) + start_vu() def gain_hook(self): - G.gain = self.val - if G.playing or G.nomuting: audio.setoutgain(G.gain) + G.gain = self.val + if G.playing or G.nomuting: audio.setoutgain(G.gain) def save_hook(self): - if not G.data: - stdwin.fleep() - else: - prompt = 'Store sampled data on file: ' - try: - G.savefile = stdwin.askfile(prompt, G.savefile, 1) - except KeyboardInterrupt: - return - try: - fp = open(G.savefile, 'w') - fp.write(Magics[G.rate] + G.data) - except: - stdwin.message('Cannot create ' + file) + if not G.data: + stdwin.fleep() + else: + prompt = 'Store sampled data on file: ' + try: + G.savefile = stdwin.askfile(prompt, G.savefile, 1) + except KeyboardInterrupt: + return + try: + fp = open(G.savefile, 'w') + fp.write(Magics[G.rate] + G.data) + except: + stdwin.message('Cannot create ' + file) def stop_vu(): - G.vubtn.stop() + G.vubtn.stop() def start_vu(): - G.vubtn.start() + G.vubtn.start() Exit = 'exit' # exception def quit_hook(self): - raise Exit, 0 + raise Exit, 0 try: - try: - main() - finally: - audio.setoutgain(0) + try: + main() + finally: + audio.setoutgain(0) except Exit, sts: - sys.exit(sts) + sys.exit(sts) diff --git a/demo/sgi/audio_stdwin/vumeter.py b/demo/sgi/audio_stdwin/vumeter.py index 1685ba2..86b9484 100755 --- a/demo/sgi/audio_stdwin/vumeter.py +++ b/demo/sgi/audio_stdwin/vumeter.py @@ -12,24 +12,24 @@ BUFSIZE = NBUFS*48 SCALE=128 class MyVUMeter() = VUMeter(): - def init_reactivity(self): - self.parent.need_mouse(self) - def mouse_down(self, detail): - if self.enabled: - self.stop() - else: - self.start() - def mouse_move(self, detail): pass - def mouse_up(self, detail): pass + def init_reactivity(self): + self.parent.need_mouse(self) + def mouse_down(self, detail): + if self.enabled: + self.stop() + else: + self.start() + def mouse_move(self, detail): pass + def mouse_up(self, detail): pass def main(): - audio.setrate(3) - audio.setoutgain(0) - w = WindowParent().create('VU Meter', (200, 100)) - v = MyVUMeter().define(w) - v.start() - w.realize() - while 1: - w.dispatch(stdwin.getevent()) + audio.setrate(3) + audio.setoutgain(0) + w = WindowParent().create('VU Meter', (200, 100)) + v = MyVUMeter().define(w) + v.start() + w.realize() + while 1: + w.dispatch(stdwin.getevent()) main() diff --git a/demo/sgi/gl/README b/demo/sgi/gl/README index f191cf5..a2cd17a 100644 --- a/demo/sgi/gl/README +++ b/demo/sgi/gl/README @@ -1,22 +1,22 @@ These demos run only on SGI machines and require the 'gl' built-in module. The demonstrate the abilities of SGI's GL library as well as the ease of -GL programming in Python. Most demos require the Z-buffer (aka +GL programming in Python. Most demos require the Z-buffer (aka 24-bitplane) option. -backface Demonstrates the 'backface' GL function. +backface Demonstrates the 'backface' GL function. -kites Show 3 flying kites. Demonstrates the rendering speed - obtainable by Python programs. +kites Show 3 flying kites. Demonstrates the rendering speed + obtainable by Python programs. -mclock A colorful clock with more options than you can - remember. Works on 8-bit machines (but allows more - colors on 24-bit machines). +mclock A colorful clock with more options than you can + remember. Works on 8-bit machines (but allows more + colors on 24-bit machines). -mixing Demonstrates the effect of color mixing: through - frequent color switching it gives the effect of white - light. +mixing Demonstrates the effect of color mixing: through + frequent color switching it gives the effect of white + light. -nurbs A simple demonstration of the 'nurbs' GL functions. +nurbs A simple demonstration of the 'nurbs' GL functions. -zrgb Displays a 3-D Gouraud-shaded figure which can be moved - around with the mouse. +zrgb Displays a 3-D Gouraud-shaded figure which can be moved + around with the mouse. diff --git a/demo/sgi/gl/backface.py b/demo/sgi/gl/backface.py index 5936f75..8192589 100755 --- a/demo/sgi/gl/backface.py +++ b/demo/sgi/gl/backface.py @@ -1,9 +1,9 @@ #! /ufs/guido/bin/sgi/python -# backface +# backface # -# draw a cube that can run with backface() turned on or off. -# cube is moved when LEFTMOUSE is pressed and mouse itself is moved. +# draw a cube that can run with backface() turned on or off. +# cube is moved when LEFTMOUSE is pressed and mouse itself is moved. from gl import * from DEVICE import * @@ -13,128 +13,128 @@ CUBE_SIZE = 200.0 CUBE_OBJ = 1 def main () : - # - x = 0 - y = 0 - moveit = 0 - # - initialize() - # - while (1) : - # - while (qtest()) : - dev, val = qread() - # - if dev = ESCKEY : - backface(0) - return - # - elif dev = REDRAW : - reshapeviewport() - drawcube(x,y) - # - elif dev = LEFTMOUSE : - # - # LEFTMOUSE down - moveit = val - # - elif dev = BKEY : - backface(1) - drawcube(x,y) - # - elif dev = FKEY : - backface(0) - drawcube(x,y) - # - if moveit : - x = getvaluator(MOUSEX) - y = getvaluator(MOUSEY) - drawcube(x,y) + # + x = 0 + y = 0 + moveit = 0 + # + initialize() + # + while (1) : + # + while (qtest()) : + dev, val = qread() + # + if dev = ESCKEY : + backface(0) + return + # + elif dev = REDRAW : + reshapeviewport() + drawcube(x,y) + # + elif dev = LEFTMOUSE : + # + # LEFTMOUSE down + moveit = val + # + elif dev = BKEY : + backface(1) + drawcube(x,y) + # + elif dev = FKEY : + backface(0) + drawcube(x,y) + # + if moveit : + x = getvaluator(MOUSEX) + y = getvaluator(MOUSEY) + drawcube(x,y) def initialize () : - foreground () - keepaspect (1, 1) - gid = winopen('backface') - winset(gid) - winconstraints() - # - doublebuffer() - gconfig() - shademodel(FLAT) - # - ortho(-1024.0, 1024.0, -1024.0, 1024.0, -1024.0, 1024.0) - # - qdevice(ESCKEY) - qdevice(REDRAW) - qdevice(LEFTMOUSE) - qdevice(BKEY) - qdevice(FKEY) - qenter(REDRAW,gid) - # - backface(1) + foreground () + keepaspect (1, 1) + gid = winopen('backface') + winset(gid) + winconstraints() + # + doublebuffer() + gconfig() + shademodel(FLAT) + # + ortho(-1024.0, 1024.0, -1024.0, 1024.0, -1024.0, 1024.0) + # + qdevice(ESCKEY) + qdevice(REDRAW) + qdevice(LEFTMOUSE) + qdevice(BKEY) + qdevice(FKEY) + qenter(REDRAW,gid) + # + backface(1) # # define a cube def cube () : - # - # front face - pushmatrix() - translate(0.0,0.0,CUBE_SIZE) - color(RED) - rectf(-CUBE_SIZE,-CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) - popmatrix() - # - # right face - pushmatrix() - translate(CUBE_SIZE, 0.0, 0.0) - rotate(900, 'y') - color(GREEN) - rectf(-CUBE_SIZE,-CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) - popmatrix() - # - # back face - pushmatrix() - translate(0.0, 0.0, -CUBE_SIZE) - rotate(1800, 'y') - color(BLUE) - rectf(-CUBE_SIZE,-CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) - popmatrix() - # - # left face - pushmatrix() - translate(-CUBE_SIZE, 0.0, 0.0) - rotate(-900, 'y') - color(CYAN) - rectf(-CUBE_SIZE,-CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) - popmatrix() - # - # top face - pushmatrix() - translate(0.0, CUBE_SIZE, 0.0) - rotate(-900, 'x') - color(MAGENTA) - rectf(-CUBE_SIZE,-CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) - popmatrix() - # - # bottom face - pushmatrix() - translate(0.0, -CUBE_SIZE, 0.0) - rotate(900, 'x') - color(YELLOW) - rectf(-CUBE_SIZE,-CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) - popmatrix() + # + # front face + pushmatrix() + translate(0.0,0.0,CUBE_SIZE) + color(RED) + rectf(-CUBE_SIZE,-CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) + popmatrix() + # + # right face + pushmatrix() + translate(CUBE_SIZE, 0.0, 0.0) + rotate(900, 'y') + color(GREEN) + rectf(-CUBE_SIZE,-CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) + popmatrix() + # + # back face + pushmatrix() + translate(0.0, 0.0, -CUBE_SIZE) + rotate(1800, 'y') + color(BLUE) + rectf(-CUBE_SIZE,-CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) + popmatrix() + # + # left face + pushmatrix() + translate(-CUBE_SIZE, 0.0, 0.0) + rotate(-900, 'y') + color(CYAN) + rectf(-CUBE_SIZE,-CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) + popmatrix() + # + # top face + pushmatrix() + translate(0.0, CUBE_SIZE, 0.0) + rotate(-900, 'x') + color(MAGENTA) + rectf(-CUBE_SIZE,-CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) + popmatrix() + # + # bottom face + pushmatrix() + translate(0.0, -CUBE_SIZE, 0.0) + rotate(900, 'x') + color(YELLOW) + rectf(-CUBE_SIZE,-CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) + popmatrix() def drawcube(x,y) : - # - pushmatrix() - rotate(2*x, 'x') - rotate(2*y, 'y') - color(BLACK) - clear() - cube() - popmatrix() - swapbuffers() + # + pushmatrix() + rotate(2*x, 'x') + rotate(2*y, 'y') + color(BLACK) + clear() + cube() + popmatrix() + swapbuffers() main () diff --git a/demo/sgi/gl/kites.py b/demo/sgi/gl/kites.py index 764ad2c..36dc5d7 100755 --- a/demo/sgi/gl/kites.py +++ b/demo/sgi/gl/kites.py @@ -12,15 +12,15 @@ # # This program show 3 kites flying around the screen. It uses # -# * bgnpolygon, endpolygon -# * v3, n3 -# * lmdef, lmbind +# * bgnpolygon, endpolygon +# * v3, n3 +# * lmdef, lmbind # # Usage : -# -# ESC -> exit program -# MOUSE3 -> freeze toggle -# MOUSE2 -> one step (use this in freeze state) +# +# ESC -> exit program +# MOUSE3 -> freeze toggle +# MOUSE2 -> one step (use this in freeze state) from GL import * from gl import * @@ -32,28 +32,28 @@ from math import * # set appropiate material, call drawobject() # def viewobj (r, s, t, mat) : - pushmatrix() - rot (r * 10.0, 'X') - rot (r * 10.0, 'Y') - rot (r * 10.0, 'Z') - scale (s[0], s[1], s[2]) - translate (t[0], t[1], t[2]) - lmbind(MATERIAL, mat) - drawobject() - popmatrix() + pushmatrix() + rot (r * 10.0, 'X') + rot (r * 10.0, 'Y') + rot (r * 10.0, 'Z') + scale (s[0], s[1], s[2]) + translate (t[0], t[1], t[2]) + lmbind(MATERIAL, mat) + drawobject() + popmatrix() # # makeobj : the contructor of the object # def mkobj () : - v0 = (-5.0 ,0.0, 0.0) - v1 = (0.0 ,5.0, 0.0) - v2 = (5.0 ,0.0, 0.0) - v3 = (0.0 ,2.0, 0.0) - n0 = (sqrt(2.0)/2.0, sqrt(2.0)/2.0, 0.0) - vn = ((v0, n0), (v1, n0), (v2, n0), (v3, n0)) - # - return vn + v0 = (-5.0 ,0.0, 0.0) + v1 = (0.0 ,5.0, 0.0) + v2 = (5.0 ,0.0, 0.0) + v3 = (0.0 ,2.0, 0.0) + n0 = (sqrt(2.0)/2.0, sqrt(2.0)/2.0, 0.0) + vn = ((v0, n0), (v1, n0), (v2, n0), (v3, n0)) + # + return vn # # the object itself as an array of vertices and normals @@ -64,10 +64,10 @@ kite = mkobj () # drawobject : draw a triangle. with bgnpolygon # def drawobject () : - # - bgnpolygon() - vnarray (kite) - endpolygon() + # + bgnpolygon() + vnarray (kite) + endpolygon() # # identity matrix @@ -75,7 +75,7 @@ def drawobject () : idmat=[1.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0] # -# the rgb-value of light-blue +# the rgb-value of light-blue # LightBlue = (43,169,255) @@ -102,93 +102,93 @@ model = [AMBIENT,0.2,0.2,0.2,LMNULL] # sets the viewing, defines and binds the materials # def initgl () : - # - # open window - # - foreground () - keepaspect (1, 1) - prefposition (100, 500, 100, 500) - w = winopen ('PYTHON lights') - keepaspect (1, 1) - winconstraints() - # - # configure pipeline (zbuf, 2buf, GOURAUD and RGBmode) - # - zbuffer (1) - doublebuffer () - shademodel (GOURAUD) - RGBmode () - gconfig () - # - # define and bind materials (set perspective BEFORE loadmat !) - # - mmode(MVIEWING) - perspective (900, 1.0, 1.0, 20.0) - loadmatrix(idmat) - lmdef(DEFMATERIAL, 1, m1) - lmdef(DEFMATERIAL, 2, m2) - lmdef(DEFMATERIAL, 3, m3) - lmdef(DEFLIGHT, 1, light1) - lmdef(DEFLIGHT, 2, light2) - lmdef(DEFLMODEL, 1, model) - lmbind(LIGHT0,1) - lmbind(LIGHT1,2) - lmbind(LMODEL,1) - # - # set viewing - # - lookat (0.0, 0.0, 10.0, 0.0, 0.0, 0.0, 0) - # - # ask for the REDRAW and ESCKEY events - # - qdevice(DEVICE.MOUSE3) - qdevice(DEVICE.MOUSE2) - qdevice(DEVICE.REDRAW) - qdevice(DEVICE.ESCKEY) - -# -# GoForIT : use 2buf to redraw the object 2n times. index i is used as + # + # open window + # + foreground () + keepaspect (1, 1) + prefposition (100, 500, 100, 500) + w = winopen ('PYTHON lights') + keepaspect (1, 1) + winconstraints() + # + # configure pipeline (zbuf, 2buf, GOURAUD and RGBmode) + # + zbuffer (1) + doublebuffer () + shademodel (GOURAUD) + RGBmode () + gconfig () + # + # define and bind materials (set perspective BEFORE loadmat !) + # + mmode(MVIEWING) + perspective (900, 1.0, 1.0, 20.0) + loadmatrix(idmat) + lmdef(DEFMATERIAL, 1, m1) + lmdef(DEFMATERIAL, 2, m2) + lmdef(DEFMATERIAL, 3, m3) + lmdef(DEFLIGHT, 1, light1) + lmdef(DEFLIGHT, 2, light2) + lmdef(DEFLMODEL, 1, model) + lmbind(LIGHT0,1) + lmbind(LIGHT1,2) + lmbind(LMODEL,1) + # + # set viewing + # + lookat (0.0, 0.0, 10.0, 0.0, 0.0, 0.0, 0) + # + # ask for the REDRAW and ESCKEY events + # + qdevice(DEVICE.MOUSE3) + qdevice(DEVICE.MOUSE2) + qdevice(DEVICE.REDRAW) + qdevice(DEVICE.ESCKEY) + +# +# GoForIT : use 2buf to redraw the object 2n times. index i is used as # the (smoothly changing) rotation angle # def GoForIt(i) : - freeze = 1 - while 1 : - if freeze <> 0 : - i = i + 1 - # - # clear z-buffer and clear background to light-blue - # - zclear() - c3i (LightBlue) - clear() - # - # draw the 3 traiangles scaled above each other. - # - viewobj(float(i),[1.0,1.0,1.0],[1.0,1.0,1.0],1) - viewobj(float(i),[0.75,0.75,0.75],[0.0,2.0,2.0],2) - viewobj(float(i),[0.5,0.5,0.5],[0.0,4.0,4.0],3) - # - swapbuffers() - # - if qtest() <> 0 : - dev, val = qread() - if dev = DEVICE.ESCKEY : - break - elif dev = DEVICE.REDRAW : - reshapeviewport () - elif dev = DEVICE.MOUSE3 and val <> 0 : - freeze = 1 - freeze - elif dev = DEVICE.MOUSE2 and val <> 0 : - i = i + 1 + freeze = 1 + while 1 : + if freeze <> 0 : + i = i + 1 + # + # clear z-buffer and clear background to light-blue + # + zclear() + c3i (LightBlue) + clear() + # + # draw the 3 traiangles scaled above each other. + # + viewobj(float(i),[1.0,1.0,1.0],[1.0,1.0,1.0],1) + viewobj(float(i),[0.75,0.75,0.75],[0.0,2.0,2.0],2) + viewobj(float(i),[0.5,0.5,0.5],[0.0,4.0,4.0],3) + # + swapbuffers() + # + if qtest() <> 0 : + dev, val = qread() + if dev = DEVICE.ESCKEY : + break + elif dev = DEVICE.REDRAW : + reshapeviewport () + elif dev = DEVICE.MOUSE3 and val <> 0 : + freeze = 1 - freeze + elif dev = DEVICE.MOUSE2 and val <> 0 : + i = i + 1 # the main program # def main () : - initgl () - GoForIt (0) + initgl () + GoForIt (0) # # exec main # -main () +main () diff --git a/demo/sgi/gl/mclock.doc b/demo/sgi/gl/mclock.doc index 610e9ab..256e062 100644 --- a/demo/sgi/gl/mclock.doc +++ b/demo/sgi/gl/mclock.doc @@ -8,7 +8,7 @@ Last week I wrote: >For your enjoyment I have implemented a colorful clock. The clock has now been extended with some new facilities: a menu, an -alarm and a gong. These may require some explanation beyond what's in +alarm and a gong. These may require some explanation beyond what's in the usage message. Menu @@ -19,37 +19,37 @@ seconds hand on or off and to switch the alarm off. Alarm ----- -The left and middle buttons set the alarm. When it is on, the alarm +The left and middle buttons set the alarm. When it is on, the alarm time is displayed as a time on a 24 hour clock in the bottom left -corner. It is also indicated by two red triangles, corresponding to the -little (hours) and big (minutes) hand. These hands can be moved around: +corner. It is also indicated by two red triangles, corresponding to the +little (hours) and big (minutes) hand. These hands can be moved around: the left mouse button moves the minutes hand, the middle button moves -the hourds hand. Watch out for differences of twelve hours (always +the hourds hand. Watch out for differences of twelve hours (always check the digital display); these can be corrected by dragging the hours hand once around the dial. When the alarm goes off, two things happen: a shell command specified on the command line with the -a option is executed (in the background), and -the clock's colors change every two seconds, for five minutes. You can +the clock's colors change every two seconds, for five minutes. You can also turn the alarm off by using the menu accessible through the right mouse button. There is no default command for the -a option; if it is not specified, -only the changing of the colors happens. If you have an 8 ohm speaker +only the changing of the colors happens. If you have an 8 ohm speaker connected to the audio output of your Personal Iris, a suitable command would be: - mclock -a '/ufs/guido/bin/sgi/play /ufs/guido/lib/sounds/alarm' + mclock -a '/ufs/guido/bin/sgi/play /ufs/guido/lib/sounds/alarm' Gong ---- Some people like a clock that makes noises every hour, or even more -often. This is supported by the -g and -G options. With -g you specify +often. This is supported by the -g and -G options. With -g you specify a shell command to be executed to sound the gong; with -G you can specify the interval between gong calls, in seconds (default is one hour). -The shell command is executed in the background. It is given two -arguments: the hours (on a 24 hour clock!) and the minutes. The +The shell command is executed in the background. It is given two +arguments: the hours (on a 24 hour clock!) and the minutes. The executable Python script /ufs/guido/bin/sgi/chime is a suitable example. Again, this only works if you have installed a speaker (I bet 8 ohm speakers are going to be in demand!) diff --git a/demo/sgi/gl/mclock.py b/demo/sgi/gl/mclock.py index 806511c..43b219c 100755 --- a/demo/sgi/gl/mclock.py +++ b/demo/sgi/gl/mclock.py @@ -29,701 +29,701 @@ from math import pi import math import posix -FULLC = 3600 # Full circle in 1/10-ths of a degree -MIDN = 900 # Angle of the 12 o'clock position -R, G, B = 0, 1, 2 # Indices of colors in RGB list +FULLC = 3600 # Full circle in 1/10-ths of a degree +MIDN = 900 # Angle of the 12 o'clock position +R, G, B = 0, 1, 2 # Indices of colors in RGB list -HOUR = 3600 # Number of seconds per hour -MINUTE = 60 # Number of seconds per minute +HOUR = 3600 # Number of seconds per hour +MINUTE = 60 # Number of seconds per minute -class struct(): pass # Class to define featureless structures -Gl = struct() # Object to hold writable global variables +class struct(): pass # Class to define featureless structures +Gl = struct() # Object to hold writable global variables # Default constants (used in multiple places) SCREENBG = 127, 156, 191 NPARTS = 9 TITLE = 'M Clock' -TZDIFF = -1*HOUR # <--- change this to reflect your local time zone +TZDIFF = -1*HOUR # <--- change this to reflect your local time zone # Default parameters -Gl.foreground = 0 # If set, run in the foreground -Gl.fullscreen = 0 # If set, run on full screen -Gl.tzdiff = TZDIFF # Seconds west of Greenwich (winter time) -Gl.nparts = NPARTS # Number of parts each circle is divided in (>= 2) -Gl.debug = 0 # If set, print debug output -Gl.doublebuffer = 1 # If set, use double buffering -Gl.update = 0 # Update interval; seconds hand is suppressed if > 1 -Gl.colorsubset = 0 # If set, display only a subset of the colors -Gl.cyan = 0 # If set, display cyan overlay (big hand) -Gl.magenta = 0 # If set, display magenta overlay (little hand) -Gl.yellow = 0 # If set, display yellow overlay (fixed background) -Gl.black = 0 # If set, display black overlay (hands) -Gl.colormap = 0 # If set, use colormap mode instead of RGB mode -Gl.warnings = 0 # If set, print warnings -Gl.title = '- - ' # Window title (default set later) -Gl.border = 1 # If set, use a window border (and title) -Gl.bg = 0, 0, 0 # Background color R, G, B value -Gl.iconic = 0 # Set in iconic state -Gl.fg = 255, 0, 0 # Alarm background RGB (either normal or alarm) -Gl.ox,Gl.oy = 0,0 # Window origin -Gl.cx,Gl.cy = 0,0 # Window size -Gl.alarm_set = 0 # Alarm on or off -Gl.alarm_on = 0 # Alarm is ringing -Gl.alarm_time = 0 # Alarm time in seconds after midnight -Gl.alarm_hours = 0 # Alarm hour setting, 24 hour clock -Gl.alarm_minutes = 0 # Alarm minutes setting -Gl.alarm_rgb = 0,0,0 # Alarm display RGB colors -Gl.alarm_cmd = '' # Command to execute when alarm goes off -Gl.mouse2down = 0 # Mouse button state -Gl.mouse3down = 0 # Mouse button state -Gl.gong_cmd = '' # Command to execute when chimes go off -Gl.gong_int = 3600 # Gong interval -Gl.indices = R, G, B # Colors (permuted when alarm is on) +Gl.foreground = 0 # If set, run in the foreground +Gl.fullscreen = 0 # If set, run on full screen +Gl.tzdiff = TZDIFF # Seconds west of Greenwich (winter time) +Gl.nparts = NPARTS # Number of parts each circle is divided in (>= 2) +Gl.debug = 0 # If set, print debug output +Gl.doublebuffer = 1 # If set, use double buffering +Gl.update = 0 # Update interval; seconds hand is suppressed if > 1 +Gl.colorsubset = 0 # If set, display only a subset of the colors +Gl.cyan = 0 # If set, display cyan overlay (big hand) +Gl.magenta = 0 # If set, display magenta overlay (little hand) +Gl.yellow = 0 # If set, display yellow overlay (fixed background) +Gl.black = 0 # If set, display black overlay (hands) +Gl.colormap = 0 # If set, use colormap mode instead of RGB mode +Gl.warnings = 0 # If set, print warnings +Gl.title = '- - ' # Window title (default set later) +Gl.border = 1 # If set, use a window border (and title) +Gl.bg = 0, 0, 0 # Background color R, G, B value +Gl.iconic = 0 # Set in iconic state +Gl.fg = 255, 0, 0 # Alarm background RGB (either normal or alarm) +Gl.ox,Gl.oy = 0,0 # Window origin +Gl.cx,Gl.cy = 0,0 # Window size +Gl.alarm_set = 0 # Alarm on or off +Gl.alarm_on = 0 # Alarm is ringing +Gl.alarm_time = 0 # Alarm time in seconds after midnight +Gl.alarm_hours = 0 # Alarm hour setting, 24 hour clock +Gl.alarm_minutes = 0 # Alarm minutes setting +Gl.alarm_rgb = 0,0,0 # Alarm display RGB colors +Gl.alarm_cmd = '' # Command to execute when alarm goes off +Gl.mouse2down = 0 # Mouse button state +Gl.mouse3down = 0 # Mouse button state +Gl.gong_cmd = '' # Command to execute when chimes go off +Gl.gong_int = 3600 # Gong interval +Gl.indices = R, G, B # Colors (permuted when alarm is on) def main(): - # - sys.stdout = sys.stderr # All output is errors/warnings etc. - # - try: - args = getoptions() - except string.atoi_error, value: - usage(string.atoi_error, value) - except getopt.error, msg: - usage(getopt.error, msg) - # - if args: - realtime = 0 - hours = string.atoi(args[0]) - minutes = seconds = 0 - if args[1:]: minutes = string.atoi(args[1]) - if args[2:]: seconds = string.atoi(args[2]) - localtime = ((hours*60)+minutes)*60+seconds - else: - realtime = 1 - # - if Gl.title = '- - ': - if realtime: - Gl.title = TITLE - else: - title = '' - for arg in args: title = title + ' ' + arg - Gl.title = title[1:] - del title - # - wid = makewindow() - Gl.ox,Gl.oy = getorigin() - Gl.cx,Gl.cy = getsize() - initmenu() - clearall() - # - if not Gl.update: - Gl.update = 60 - # - if Gl.update <= 1: - Gl.timernoise = 6 - else: - Gl.timernoise = 60 - noise(TIMER0, Gl.timernoise) - # - qdevice(WINSHUT) - qdevice(WINQUIT) - qdevice(ESCKEY) - if realtime: - qdevice(TIMER0) - qdevice(REDRAW) - qdevice(WINFREEZE) - qdevice(WINTHAW) - qdevice(MENUBUTTON) # MOUSE1 - qdevice(MOUSE3) # Left button - qdevice(MOUSE2) # Middle button - unqdevice(INPUTCHANGE) - # - lasttime = 0 - Gl.change = 1 - while 1: - if realtime: - localtime = time.time() - Gl.tzdiff - if Gl.alarm_set: - if localtime%(24*HOUR) = Gl.alarm_time: - # Ring the alarm! - if Gl.debug: - print 'Rrrringg!' - Gl.alarm_on = 1 - if Gl.alarm_cmd <> '': - d = posix.system(Gl.alarm_cmd+' '+`Gl.alarm_time/3600`+' '+`(Gl.alarm_time/60)%60` + ' &') - Gl.change = 1 - clearall() - if Gl.alarm_on: - if (localtime - Gl.alarm_time) % (24*HOUR) > 300: - # More than 5 minutes away from alarm - Gl.alarm_on = 0 - if Gl.debug: - print 'Alarm turned off' - Gl.change = 1 - clearall() - Gl.indices = R, G, B - else: - if localtime % 2 = 0: - # Permute color indices - Gl.indices = Gl.indices[2:] + Gl.indices[:2] - Gl.change = 1 - if Gl.gong_cmd <> '' and localtime%Gl.gong_int = 0: - d = posix.system(Gl.gong_cmd+' '+`(localtime/3600)%24`+' '+`(localtime/60)%60` + ' &') - if localtime/Gl.update <> lasttime/Gl.update: - if Gl.debug: print 'new time' - Gl.change = 1 - if Gl.change: - if Gl.debug: print 'drawing' - doit(localtime) - lasttime = localtime - Gl.change = 0 - dev, data = qread() - if Gl.debug and dev <> TIMER0: - print dev, data - if dev = TIMER0: - if Gl.debug > 1: - print dev, data - elif dev = MOUSE3: - mousex = getvaluator(MOUSEX) - mousey = getvaluator(MOUSEY) - if mouseclick(3, data, mousex, mousey): - Gl.change = 1 - elif dev = MOUSE2: - mousex = getvaluator(MOUSEX) - mousey = getvaluator(MOUSEY) - if mouseclick(2, data, mousex, mousey): - Gl.change = 1 - elif dev = MOUSEX: - mousex = data - if Gl.mouse2down: - mouse2track(mousex, mousey) - if Gl.mouse3down: - mouse3track(mousex, mousey) - elif dev = MOUSEY: - mousey = data - if Gl.mouse2down: - mouse2track(mousex, mousey) - if Gl.mouse3down: - mouse3track(mousex, mousey) - elif dev = REDRAW or dev = REDRAWICONIC: - if Gl.debug: - if dev = REDRAW: print 'REDRAW' - else: print 'REDRAWICONIC' - reshapeviewport() - Gl.ox,Gl.oy = getorigin() - Gl.cx,Gl.cy = getsize() - Gl.change = 1 - clearall() - elif dev = MENUBUTTON: - if Gl.debug: print 'MENUBUTTON' - handlemenu() - elif dev = WINFREEZE: - if Gl.debug: print 'WINFREEZE' - Gl.iconic = 1 - noise(TIMER0, 60*60) # Redraw every 60 seconds only - elif dev = WINTHAW: - if Gl.debug: print 'WINTHAW' - Gl.iconic = 0 - noise(TIMER0, Gl.timernoise) - Gl.change = 1 - elif dev = ESCKEY or dev = WINSHUT or dev = WINQUIT: - if Gl.debug: print 'Exit' - sys.exit(0) + # + sys.stdout = sys.stderr # All output is errors/warnings etc. + # + try: + args = getoptions() + except string.atoi_error, value: + usage(string.atoi_error, value) + except getopt.error, msg: + usage(getopt.error, msg) + # + if args: + realtime = 0 + hours = string.atoi(args[0]) + minutes = seconds = 0 + if args[1:]: minutes = string.atoi(args[1]) + if args[2:]: seconds = string.atoi(args[2]) + localtime = ((hours*60)+minutes)*60+seconds + else: + realtime = 1 + # + if Gl.title = '- - ': + if realtime: + Gl.title = TITLE + else: + title = '' + for arg in args: title = title + ' ' + arg + Gl.title = title[1:] + del title + # + wid = makewindow() + Gl.ox,Gl.oy = getorigin() + Gl.cx,Gl.cy = getsize() + initmenu() + clearall() + # + if not Gl.update: + Gl.update = 60 + # + if Gl.update <= 1: + Gl.timernoise = 6 + else: + Gl.timernoise = 60 + noise(TIMER0, Gl.timernoise) + # + qdevice(WINSHUT) + qdevice(WINQUIT) + qdevice(ESCKEY) + if realtime: + qdevice(TIMER0) + qdevice(REDRAW) + qdevice(WINFREEZE) + qdevice(WINTHAW) + qdevice(MENUBUTTON) # MOUSE1 + qdevice(MOUSE3) # Left button + qdevice(MOUSE2) # Middle button + unqdevice(INPUTCHANGE) + # + lasttime = 0 + Gl.change = 1 + while 1: + if realtime: + localtime = time.time() - Gl.tzdiff + if Gl.alarm_set: + if localtime%(24*HOUR) = Gl.alarm_time: + # Ring the alarm! + if Gl.debug: + print 'Rrrringg!' + Gl.alarm_on = 1 + if Gl.alarm_cmd <> '': + d = posix.system(Gl.alarm_cmd+' '+`Gl.alarm_time/3600`+' '+`(Gl.alarm_time/60)%60` + ' &') + Gl.change = 1 + clearall() + if Gl.alarm_on: + if (localtime - Gl.alarm_time) % (24*HOUR) > 300: + # More than 5 minutes away from alarm + Gl.alarm_on = 0 + if Gl.debug: + print 'Alarm turned off' + Gl.change = 1 + clearall() + Gl.indices = R, G, B + else: + if localtime % 2 = 0: + # Permute color indices + Gl.indices = Gl.indices[2:] + Gl.indices[:2] + Gl.change = 1 + if Gl.gong_cmd <> '' and localtime%Gl.gong_int = 0: + d = posix.system(Gl.gong_cmd+' '+`(localtime/3600)%24`+' '+`(localtime/60)%60` + ' &') + if localtime/Gl.update <> lasttime/Gl.update: + if Gl.debug: print 'new time' + Gl.change = 1 + if Gl.change: + if Gl.debug: print 'drawing' + doit(localtime) + lasttime = localtime + Gl.change = 0 + dev, data = qread() + if Gl.debug and dev <> TIMER0: + print dev, data + if dev = TIMER0: + if Gl.debug > 1: + print dev, data + elif dev = MOUSE3: + mousex = getvaluator(MOUSEX) + mousey = getvaluator(MOUSEY) + if mouseclick(3, data, mousex, mousey): + Gl.change = 1 + elif dev = MOUSE2: + mousex = getvaluator(MOUSEX) + mousey = getvaluator(MOUSEY) + if mouseclick(2, data, mousex, mousey): + Gl.change = 1 + elif dev = MOUSEX: + mousex = data + if Gl.mouse2down: + mouse2track(mousex, mousey) + if Gl.mouse3down: + mouse3track(mousex, mousey) + elif dev = MOUSEY: + mousey = data + if Gl.mouse2down: + mouse2track(mousex, mousey) + if Gl.mouse3down: + mouse3track(mousex, mousey) + elif dev = REDRAW or dev = REDRAWICONIC: + if Gl.debug: + if dev = REDRAW: print 'REDRAW' + else: print 'REDRAWICONIC' + reshapeviewport() + Gl.ox,Gl.oy = getorigin() + Gl.cx,Gl.cy = getsize() + Gl.change = 1 + clearall() + elif dev = MENUBUTTON: + if Gl.debug: print 'MENUBUTTON' + handlemenu() + elif dev = WINFREEZE: + if Gl.debug: print 'WINFREEZE' + Gl.iconic = 1 + noise(TIMER0, 60*60) # Redraw every 60 seconds only + elif dev = WINTHAW: + if Gl.debug: print 'WINTHAW' + Gl.iconic = 0 + noise(TIMER0, Gl.timernoise) + Gl.change = 1 + elif dev = ESCKEY or dev = WINSHUT or dev = WINQUIT: + if Gl.debug: print 'Exit' + sys.exit(0) def getoptions(): - optlist, args = getopt.getopt(sys.argv[1:], 'A:a:B:bc:dFfG:g:n:sT:t:u:wCMYK') - for optname, optarg in optlist: - if optname = '-A': - Gl.fg = eval(optarg) # Should be (r,g,b) - elif optname = '-a': - Gl.alarm_cmd = optarg - elif optname = '-B': - Gl.bg = eval(optarg) # Should be (r,g,b) - elif optname = '-b': - Gl.border = 0 - elif optname = '-c': - Gl.colormap = string.atoi(optarg) - elif optname = '-d': - Gl.debug = Gl.debug + 1 - Gl.warnings = 1 - elif optname = '-F': - Gl.foreground = 1 - elif optname = '-f': - Gl.fullscreen = 1 - elif optname = '-G': - Gl.gong_int = 60*string.atoi(optarg) - elif optname = '-g': - Gl.gong_cmd = optarg - elif optname = '-n': - Gl.nparts = string.atoi(optarg) - elif optname = '-s': - Gl.doublebuffer = 0 - elif optname = '-T': - Gl.title = optarg - elif optname = '-t': - Gl.tzdiff = string.atoi(optarg) - elif optname = '-u': - Gl.update = string.atoi(optarg) - elif optname = '-w': - Gl.warnings = 1 - elif optname = '-C': - Gl.cyan = Gl.colorsubset = 1 - elif optname = '-M': - Gl.magenta = Gl.colorsubset = 1 - elif optname = '-Y': - Gl.yellow = Gl.colorsubset = 1 - elif optname = '-K': - Gl.black = Gl.colorsubset = 1 - else: - print 'Unsupported option', optname - return args + optlist, args = getopt.getopt(sys.argv[1:], 'A:a:B:bc:dFfG:g:n:sT:t:u:wCMYK') + for optname, optarg in optlist: + if optname = '-A': + Gl.fg = eval(optarg) # Should be (r,g,b) + elif optname = '-a': + Gl.alarm_cmd = optarg + elif optname = '-B': + Gl.bg = eval(optarg) # Should be (r,g,b) + elif optname = '-b': + Gl.border = 0 + elif optname = '-c': + Gl.colormap = string.atoi(optarg) + elif optname = '-d': + Gl.debug = Gl.debug + 1 + Gl.warnings = 1 + elif optname = '-F': + Gl.foreground = 1 + elif optname = '-f': + Gl.fullscreen = 1 + elif optname = '-G': + Gl.gong_int = 60*string.atoi(optarg) + elif optname = '-g': + Gl.gong_cmd = optarg + elif optname = '-n': + Gl.nparts = string.atoi(optarg) + elif optname = '-s': + Gl.doublebuffer = 0 + elif optname = '-T': + Gl.title = optarg + elif optname = '-t': + Gl.tzdiff = string.atoi(optarg) + elif optname = '-u': + Gl.update = string.atoi(optarg) + elif optname = '-w': + Gl.warnings = 1 + elif optname = '-C': + Gl.cyan = Gl.colorsubset = 1 + elif optname = '-M': + Gl.magenta = Gl.colorsubset = 1 + elif optname = '-Y': + Gl.yellow = Gl.colorsubset = 1 + elif optname = '-K': + Gl.black = Gl.colorsubset = 1 + else: + print 'Unsupported option', optname + return args def usage(exc, msg): - if sys.argv: - progname = path.basename(sys.argv[0]) - else: - progname = 'mclock' - # - print progname + ':', - if exc = string.atoi_error: - print 'non-numeric argument:', - print msg - # - print 'usage:', progname, '[options] [hh [mm [ss]]]' - # - print '-A r,g,b : alarm background red,green,blue [255,0,0]' - print '-a cmd : shell command executed when alarm goes off' - print '-B r,g,b : background red,green,blue [0,0,0]' - print ' (-B SCREENBG uses the default screen background)' - print '-b : suppress window border and title' - print '-c cmapid : select explicit colormap' - print '-d : more debug output (implies -F, -w)' - print '-F : run in foreground' - print '-f : use full screen' - print '-G intrvl : interval between chimes in minutes [60]' - print '-g cmd : shell command executed when chimes go off' - print '-s : single buffer mode' - print '-w : print various warnings' - print '-n nparts : number of parts [' + `NPARTS` + ']' - print '-T title : alternate window title [\'' + TITLE + '\']' - print '-t tzdiff : time zone difference [' + `TZDIFF` + ']' - print '-u update : update interval [60]' - print '-CMYK : Cyan, Magenta, Yellow or blacK overlay only' - print 'if hh [mm [ss]] is specified, display that time statically' - print 'on machines with < 12 bitplanes, -c and -s are forced on' - # - sys.exit(2) + if sys.argv: + progname = path.basename(sys.argv[0]) + else: + progname = 'mclock' + # + print progname + ':', + if exc = string.atoi_error: + print 'non-numeric argument:', + print msg + # + print 'usage:', progname, '[options] [hh [mm [ss]]]' + # + print '-A r,g,b : alarm background red,green,blue [255,0,0]' + print '-a cmd : shell command executed when alarm goes off' + print '-B r,g,b : background red,green,blue [0,0,0]' + print ' (-B SCREENBG uses the default screen background)' + print '-b : suppress window border and title' + print '-c cmapid : select explicit colormap' + print '-d : more debug output (implies -F, -w)' + print '-F : run in foreground' + print '-f : use full screen' + print '-G intrvl : interval between chimes in minutes [60]' + print '-g cmd : shell command executed when chimes go off' + print '-s : single buffer mode' + print '-w : print various warnings' + print '-n nparts : number of parts [' + `NPARTS` + ']' + print '-T title : alternate window title [\'' + TITLE + '\']' + print '-t tzdiff : time zone difference [' + `TZDIFF` + ']' + print '-u update : update interval [60]' + print '-CMYK : Cyan, Magenta, Yellow or blacK overlay only' + print 'if hh [mm [ss]] is specified, display that time statically' + print 'on machines with < 12 bitplanes, -c and -s are forced on' + # + sys.exit(2) def doit(localtime): - hands = makehands(localtime) - list = makelist(hands) - render(list, hands) + hands = makehands(localtime) + list = makelist(hands) + render(list, hands) def makehands(localtime): - localtime = localtime % (12*HOUR) - seconds_hand = MIDN + FULLC - (localtime*60) % FULLC - big_hand = (MIDN + FULLC - (localtime%HOUR)) % FULLC - little_hand = (MIDN + FULLC - ((localtime/12) % HOUR)) % FULLC - return little_hand, big_hand, seconds_hand + localtime = localtime % (12*HOUR) + seconds_hand = MIDN + FULLC - (localtime*60) % FULLC + big_hand = (MIDN + FULLC - (localtime%HOUR)) % FULLC + little_hand = (MIDN + FULLC - ((localtime/12) % HOUR)) % FULLC + return little_hand, big_hand, seconds_hand def makelist(little_hand, big_hand, seconds_hand): - total = [] - if Gl.cyan or not Gl.colorsubset: - total = total + makesublist(big_hand, Gl.indices[0]) - if Gl.magenta or not Gl.colorsubset: - total = total + makesublist(little_hand, Gl.indices[1]) - if Gl.yellow or not Gl.colorsubset: - total = total + makesublist(MIDN, Gl.indices[2]) - total.sort() - return total + total = [] + if Gl.cyan or not Gl.colorsubset: + total = total + makesublist(big_hand, Gl.indices[0]) + if Gl.magenta or not Gl.colorsubset: + total = total + makesublist(little_hand, Gl.indices[1]) + if Gl.yellow or not Gl.colorsubset: + total = total + makesublist(MIDN, Gl.indices[2]) + total.sort() + return total def makesublist(first, icolor): - list = [] - alpha = FULLC/Gl.nparts - a = first - alpha/2 - for i in range(Gl.nparts): - angle = (a + i*alpha + FULLC) % FULLC - value = 255*(Gl.nparts-1-i)/(Gl.nparts-1) - list.append(angle, icolor, value) - list.sort() - a, icolor, value = list[0] - if a <> 0: - a, icolor, value = list[len(list)-1] - t = 0, icolor, value - list.insert(0, t) - return list + list = [] + alpha = FULLC/Gl.nparts + a = first - alpha/2 + for i in range(Gl.nparts): + angle = (a + i*alpha + FULLC) % FULLC + value = 255*(Gl.nparts-1-i)/(Gl.nparts-1) + list.append(angle, icolor, value) + list.sort() + a, icolor, value = list[0] + if a <> 0: + a, icolor, value = list[len(list)-1] + t = 0, icolor, value + list.insert(0, t) + return list def rgb_fg(): - return Gl.fg - # Obsolete code: - if Gl.alarm_on: - return Gl.bg - else: - return Gl.fg + return Gl.fg + # Obsolete code: + if Gl.alarm_on: + return Gl.bg + else: + return Gl.fg def rgb_bg(): - return Gl.bg - # Obsolete code: - if Gl.alarm_on: - return Gl.fg - else: - return Gl.bg + return Gl.bg + # Obsolete code: + if Gl.alarm_on: + return Gl.fg + else: + return Gl.bg def clearall(): - Gl.c3i(rgb_bg()) - clear() - if Gl.doublebuffer: - swapbuffers() - clear() + Gl.c3i(rgb_bg()) + clear() + if Gl.doublebuffer: + swapbuffers() + clear() def draw_alarm(color): - frontbuffer(TRUE) - Gl.c3i(color) - pushmatrix() - rotate(-((Gl.alarm_time/12)%3600), 'z') - bgnpolygon() - v2f( 0.00,1.00) - v2f( 0.04,1.05) - v2f(-0.04,1.05) - endpolygon() - popmatrix() - # - pushmatrix() - rotate(-((Gl.alarm_time)%3600), 'z') - bgnpolygon() - v2f( 0.00,1.05) - v2f( 0.07,1.10) - v2f(-0.07,1.10) - endpolygon() - popmatrix() - # - cmov2(-1.06, -1.06) - charstr(string.rjust(`Gl.alarm_time/3600`,2)) - charstr(':') - charstr(string.zfill((Gl.alarm_time/60)%60,2)) - frontbuffer(FALSE) + frontbuffer(TRUE) + Gl.c3i(color) + pushmatrix() + rotate(-((Gl.alarm_time/12)%3600), 'z') + bgnpolygon() + v2f( 0.00,1.00) + v2f( 0.04,1.05) + v2f(-0.04,1.05) + endpolygon() + popmatrix() + # + pushmatrix() + rotate(-((Gl.alarm_time)%3600), 'z') + bgnpolygon() + v2f( 0.00,1.05) + v2f( 0.07,1.10) + v2f(-0.07,1.10) + endpolygon() + popmatrix() + # + cmov2(-1.06, -1.06) + charstr(string.rjust(`Gl.alarm_time/3600`,2)) + charstr(':') + charstr(string.zfill((Gl.alarm_time/60)%60,2)) + frontbuffer(FALSE) def render(list, (little_hand, big_hand, seconds_hand)): - # - if Gl.colormap: - resetindex() - # - if not list: - Gl.c3i(255, 255, 255) # White - circf(0.0, 0.0, 1.0) - else: - list.append(3600, 0, 255) # Sentinel - # - rgb = [255, 255, 255] - a_prev = 0 - for a, icolor, value in list: - if a <> a_prev: - [r, g, b] = rgb - if Gl.debug > 1: - print rgb, a_prev, a - Gl.c3i(r, g, b) - arcf(0.0, 0.0, 1.0, a_prev, a) - rgb[icolor] = value - a_prev = a - # - if Gl.black or not Gl.colorsubset: - # - # Draw the hands -- in black - # - Gl.c3i(0, 0, 0) - # - if Gl.update = 1 and not Gl.iconic: - # Seconds hand is only drawn if we update every second - pushmatrix() - rotate(seconds_hand, 'z') - bgnline() - v2f(0.0, 0.0) - v2f(1.0, 0.0) - endline() - popmatrix() - # - pushmatrix() - rotate(big_hand, 'z') - rectf(0.0, -0.01, 0.97, 0.01) - circf(0.0, 0.0, 0.01) - circf(0.97, 0.0, 0.01) - popmatrix() - # - pushmatrix() - rotate(little_hand, 'z') - rectf(0.04, -0.02, 0.63, 0.02) - circf(0.04, 0.0, 0.02) - circf(0.63, 0.0, 0.02) - popmatrix() - # - # Draw the alarm time, if set or being set - # - if Gl.alarm_set: - draw_alarm(rgb_fg()) - # - if Gl.doublebuffer: swapbuffers() + # + if Gl.colormap: + resetindex() + # + if not list: + Gl.c3i(255, 255, 255) # White + circf(0.0, 0.0, 1.0) + else: + list.append(3600, 0, 255) # Sentinel + # + rgb = [255, 255, 255] + a_prev = 0 + for a, icolor, value in list: + if a <> a_prev: + [r, g, b] = rgb + if Gl.debug > 1: + print rgb, a_prev, a + Gl.c3i(r, g, b) + arcf(0.0, 0.0, 1.0, a_prev, a) + rgb[icolor] = value + a_prev = a + # + if Gl.black or not Gl.colorsubset: + # + # Draw the hands -- in black + # + Gl.c3i(0, 0, 0) + # + if Gl.update = 1 and not Gl.iconic: + # Seconds hand is only drawn if we update every second + pushmatrix() + rotate(seconds_hand, 'z') + bgnline() + v2f(0.0, 0.0) + v2f(1.0, 0.0) + endline() + popmatrix() + # + pushmatrix() + rotate(big_hand, 'z') + rectf(0.0, -0.01, 0.97, 0.01) + circf(0.0, 0.0, 0.01) + circf(0.97, 0.0, 0.01) + popmatrix() + # + pushmatrix() + rotate(little_hand, 'z') + rectf(0.04, -0.02, 0.63, 0.02) + circf(0.04, 0.0, 0.02) + circf(0.63, 0.0, 0.02) + popmatrix() + # + # Draw the alarm time, if set or being set + # + if Gl.alarm_set: + draw_alarm(rgb_fg()) + # + if Gl.doublebuffer: swapbuffers() def makewindow(): - # - if Gl.debug or Gl.foreground: - foreground() - # - if Gl.fullscreen: - # XXX Should find out true screen size using getgdesc() - prefposition(0, 1279, 0, 1023) - else: - keepaspect(1, 1) - minsize(64, 64) - # - if not Gl.border: - noborder() - wid = winopen(Gl.title) - # - if not Gl.fullscreen: - keepaspect(1, 1) - minsize(10, 10) - maxsize(2000, 2000) - iconsize(66, 66) - winconstraints() - # - nplanes = getplanes() - nmaps = getgdesc(GD_NMMAPS) - if Gl.warnings: - print nplanes, 'color planes,', nmaps, 'color maps' - # - if nplanes < 12 or Gl.colormap: - if not Gl.colormap: - Gl.colormap = nmaps - 1 - if Gl.warnings: - print 'not enough color planes available', - print 'for RGB mode; forcing colormap mode' - print 'using color map number', Gl.colormap - if not Gl.colorsubset: - needed = 3 - else: - needed = Gl.cyan + Gl.magenta + Gl.yellow - needed = needed*Gl.nparts - if Gl.bg <> (0, 0, 0): - needed = needed+1 - if Gl.fg <> (0, 0, 0): - needed = needed+1 - if Gl.doublebuffer: - if needed > available(nplanes/2): - Gl.doublebuffer = 0 - if Gl.warnings: - print 'not enough colors available', - print 'for double buffer mode;', - print 'forcing single buffer mode' - else: - nplanes = nplanes/2 - if needed > available(nplanes): - # Do this warning always - print 'still not enough colors available;', - print 'parts will be left white' - print '(needed', needed, 'but have only', - print available(nplanes), 'colors available)' - # - if Gl.doublebuffer: - doublebuffer() - gconfig() - # - if Gl.colormap: - Gl.c3i = pseudo_c3i - fixcolormap() - else: - Gl.c3i = c3i - RGBmode() - gconfig() - # - if Gl.fullscreen: - # XXX Should find out true screen size using getgdesc() - ortho2(-1.1*1.280, 1.1*1.280, -1.1*1.024, 1.1*1.024) - else: - ortho2(-1.1, 1.1, -1.1, 1.1) - # - return wid + # + if Gl.debug or Gl.foreground: + foreground() + # + if Gl.fullscreen: + # XXX Should find out true screen size using getgdesc() + prefposition(0, 1279, 0, 1023) + else: + keepaspect(1, 1) + minsize(64, 64) + # + if not Gl.border: + noborder() + wid = winopen(Gl.title) + # + if not Gl.fullscreen: + keepaspect(1, 1) + minsize(10, 10) + maxsize(2000, 2000) + iconsize(66, 66) + winconstraints() + # + nplanes = getplanes() + nmaps = getgdesc(GD_NMMAPS) + if Gl.warnings: + print nplanes, 'color planes,', nmaps, 'color maps' + # + if nplanes < 12 or Gl.colormap: + if not Gl.colormap: + Gl.colormap = nmaps - 1 + if Gl.warnings: + print 'not enough color planes available', + print 'for RGB mode; forcing colormap mode' + print 'using color map number', Gl.colormap + if not Gl.colorsubset: + needed = 3 + else: + needed = Gl.cyan + Gl.magenta + Gl.yellow + needed = needed*Gl.nparts + if Gl.bg <> (0, 0, 0): + needed = needed+1 + if Gl.fg <> (0, 0, 0): + needed = needed+1 + if Gl.doublebuffer: + if needed > available(nplanes/2): + Gl.doublebuffer = 0 + if Gl.warnings: + print 'not enough colors available', + print 'for double buffer mode;', + print 'forcing single buffer mode' + else: + nplanes = nplanes/2 + if needed > available(nplanes): + # Do this warning always + print 'still not enough colors available;', + print 'parts will be left white' + print '(needed', needed, 'but have only', + print available(nplanes), 'colors available)' + # + if Gl.doublebuffer: + doublebuffer() + gconfig() + # + if Gl.colormap: + Gl.c3i = pseudo_c3i + fixcolormap() + else: + Gl.c3i = c3i + RGBmode() + gconfig() + # + if Gl.fullscreen: + # XXX Should find out true screen size using getgdesc() + ortho2(-1.1*1.280, 1.1*1.280, -1.1*1.024, 1.1*1.024) + else: + ortho2(-1.1, 1.1, -1.1, 1.1) + # + return wid def available(nplanes): - return pow(2, nplanes) - 1 # Reserve one pixel for black + return pow(2, nplanes) - 1 # Reserve one pixel for black def fixcolormap(): - multimap() - gconfig() - nplanes = getplanes() - if Gl.warnings: - print 'multimap mode has', nplanes, 'color planes' - imap = Gl.colormap - Gl.startindex = pow(2, nplanes) - 1 - Gl.stopindex = 1 - setmap(imap) - mapcolor(0, 0, 0, 0) # Fixed entry for black - if Gl.bg <> (0, 0, 0): - r, g, b = Gl.bg - mapcolor(1, r, g, b) # Fixed entry for Gl.bg - Gl.stopindex = 2 - if Gl.fg <> (0, 0, 0): - r, g, b = Gl.fg - mapcolor(2, r, g, b) # Fixed entry for Gl.fg - Gl.stopindex = 3 - Gl.overflow_seen = 0 - resetindex() + multimap() + gconfig() + nplanes = getplanes() + if Gl.warnings: + print 'multimap mode has', nplanes, 'color planes' + imap = Gl.colormap + Gl.startindex = pow(2, nplanes) - 1 + Gl.stopindex = 1 + setmap(imap) + mapcolor(0, 0, 0, 0) # Fixed entry for black + if Gl.bg <> (0, 0, 0): + r, g, b = Gl.bg + mapcolor(1, r, g, b) # Fixed entry for Gl.bg + Gl.stopindex = 2 + if Gl.fg <> (0, 0, 0): + r, g, b = Gl.fg + mapcolor(2, r, g, b) # Fixed entry for Gl.fg + Gl.stopindex = 3 + Gl.overflow_seen = 0 + resetindex() def resetindex(): - Gl.index = Gl.startindex + Gl.index = Gl.startindex r0g0b0 = (0, 0, 0) def pseudo_c3i(rgb): - if rgb = r0g0b0: - index = 0 - elif rgb = Gl.bg: - index = 1 - elif rgb = Gl.fg: - index = 2 - else: - index = definecolor(rgb) - color(index) + if rgb = r0g0b0: + index = 0 + elif rgb = Gl.bg: + index = 1 + elif rgb = Gl.fg: + index = 2 + else: + index = definecolor(rgb) + color(index) def definecolor(rgb): - index = Gl.index - if index < Gl.stopindex: - if Gl.debug: print 'definecolor hard case', rgb - # First see if we already have this one... - for index in range(Gl.stopindex, Gl.startindex+1): - if rgb = getmcolor(index): - if Gl.debug: print 'return', index - return index - # Don't clobber reserverd colormap entries - if not Gl.overflow_seen: - # Shouldn't happen any more, hence no Gl.warnings test - print 'mclock: out of colormap entries' - Gl.overflow_seen = 1 - return Gl.stopindex - r, g, b = rgb - if Gl.debug > 1: print 'mapcolor', (index, r, g, b) - mapcolor(index, r, g, b) - Gl.index = index - 1 - return index + index = Gl.index + if index < Gl.stopindex: + if Gl.debug: print 'definecolor hard case', rgb + # First see if we already have this one... + for index in range(Gl.stopindex, Gl.startindex+1): + if rgb = getmcolor(index): + if Gl.debug: print 'return', index + return index + # Don't clobber reserverd colormap entries + if not Gl.overflow_seen: + # Shouldn't happen any more, hence no Gl.warnings test + print 'mclock: out of colormap entries' + Gl.overflow_seen = 1 + return Gl.stopindex + r, g, b = rgb + if Gl.debug > 1: print 'mapcolor', (index, r, g, b) + mapcolor(index, r, g, b) + Gl.index = index - 1 + return index # Compute n**i def pow(n, i): - x = 1 - for j in range(i): x = x*n - return x + x = 1 + for j in range(i): x = x*n + return x def mouseclick(mouse, updown, x, y): - if updown = 1: - # mouse button came down, start tracking - if Gl.debug: - print 'mouse', mouse, 'down at', x, y - if mouse = 2: - Gl.mouse2down = 1 - mouse2track(x, y) - elif mouse = 3: - Gl.mouse3down = 1 - mouse3track(x, y) - else: - print 'fatal error' - qdevice(MOUSEX) - qdevice(MOUSEY) - return 0 - else: - # mouse button came up, stop tracking - if Gl.debug: - print 'mouse', mouse, 'up at', x, y - unqdevice(MOUSEX) - unqdevice(MOUSEY) - if mouse = 2: - mouse2track(x, y) - Gl.mouse2down = 0 - elif mouse = 3: - mouse3track(x, y) - Gl.mouse3down = 0 - else: - print 'fatal error' - Gl.alarm_set = 1 - return 1 + if updown = 1: + # mouse button came down, start tracking + if Gl.debug: + print 'mouse', mouse, 'down at', x, y + if mouse = 2: + Gl.mouse2down = 1 + mouse2track(x, y) + elif mouse = 3: + Gl.mouse3down = 1 + mouse3track(x, y) + else: + print 'fatal error' + qdevice(MOUSEX) + qdevice(MOUSEY) + return 0 + else: + # mouse button came up, stop tracking + if Gl.debug: + print 'mouse', mouse, 'up at', x, y + unqdevice(MOUSEX) + unqdevice(MOUSEY) + if mouse = 2: + mouse2track(x, y) + Gl.mouse2down = 0 + elif mouse = 3: + mouse3track(x, y) + Gl.mouse3down = 0 + else: + print 'fatal error' + Gl.alarm_set = 1 + return 1 def mouse3track(x, y): - # first compute polar coordinates from x and y - cx, cy = Gl.ox + Gl.cx/2, Gl.oy + Gl.cy/2 - x, y = x - cx, y - cy - if (x, y) = (0, 0): return # would cause an exception - minutes = int(30.5 + 30.0*math.atan2(float(-x), float(-y))/pi) - if minutes = 60: minutes = 0 - a,b = Gl.alarm_minutes/15, minutes/15 - if (a,b) = (0,3): - # Moved backward through 12 o'clock: - Gl.alarm_hours = Gl.alarm_hours - 1 - if Gl.alarm_hours < 0: Gl.alarm_hours = Gl.alarm_hours + 24 - if (a,b) = (3,0): - # Moved forward through 12 o'clock: - Gl.alarm_hours = Gl.alarm_hours + 1 - if Gl.alarm_hours >= 24: Gl.alarm_hours = Gl.alarm_hours - 24 - Gl.alarm_minutes = minutes - seconds = Gl.alarm_hours * HOUR + Gl.alarm_minutes * MINUTE - if seconds <> Gl.alarm_time: - draw_alarm(rgb_bg()) - Gl.alarm_time = seconds - draw_alarm(rgb_fg()) + # first compute polar coordinates from x and y + cx, cy = Gl.ox + Gl.cx/2, Gl.oy + Gl.cy/2 + x, y = x - cx, y - cy + if (x, y) = (0, 0): return # would cause an exception + minutes = int(30.5 + 30.0*math.atan2(float(-x), float(-y))/pi) + if minutes = 60: minutes = 0 + a,b = Gl.alarm_minutes/15, minutes/15 + if (a,b) = (0,3): + # Moved backward through 12 o'clock: + Gl.alarm_hours = Gl.alarm_hours - 1 + if Gl.alarm_hours < 0: Gl.alarm_hours = Gl.alarm_hours + 24 + if (a,b) = (3,0): + # Moved forward through 12 o'clock: + Gl.alarm_hours = Gl.alarm_hours + 1 + if Gl.alarm_hours >= 24: Gl.alarm_hours = Gl.alarm_hours - 24 + Gl.alarm_minutes = minutes + seconds = Gl.alarm_hours * HOUR + Gl.alarm_minutes * MINUTE + if seconds <> Gl.alarm_time: + draw_alarm(rgb_bg()) + Gl.alarm_time = seconds + draw_alarm(rgb_fg()) def mouse2track(x, y): - # first compute polar coordinates from x and y - cx, cy = Gl.ox + Gl.cx/2, Gl.oy + Gl.cy/2 - x, y = x - cx, y - cy - if (x, y) = (0, 0): return # would cause an exception - hours = int(6.5 - float(Gl.alarm_minutes)/60.0 + 6.0*math.atan2(float(-x), float(-y))/pi) - if hours = 12: hours = 0 - if (Gl.alarm_hours,hours) = (0,11): - # Moved backward through midnight: - Gl.alarm_hours = 23 - elif (Gl.alarm_hours,hours) = (12,11): - # Moved backward through noon: - Gl.alarm_hours = 11 - elif (Gl.alarm_hours,hours) = (11,0): - # Moved forward through noon: - Gl.alarm_hours = 12 - elif (Gl.alarm_hours,hours) = (23,0): - # Moved forward through midnight: - Gl.alarm_hours = 0 - elif Gl.alarm_hours < 12: - Gl.alarm_hours = hours - else: - Gl.alarm_hours = hours + 12 - seconds = Gl.alarm_hours * HOUR + Gl.alarm_minutes * MINUTE - if seconds <> Gl.alarm_time: - draw_alarm(rgb_bg()) - Gl.alarm_time = seconds - draw_alarm(rgb_fg()) + # first compute polar coordinates from x and y + cx, cy = Gl.ox + Gl.cx/2, Gl.oy + Gl.cy/2 + x, y = x - cx, y - cy + if (x, y) = (0, 0): return # would cause an exception + hours = int(6.5 - float(Gl.alarm_minutes)/60.0 + 6.0*math.atan2(float(-x), float(-y))/pi) + if hours = 12: hours = 0 + if (Gl.alarm_hours,hours) = (0,11): + # Moved backward through midnight: + Gl.alarm_hours = 23 + elif (Gl.alarm_hours,hours) = (12,11): + # Moved backward through noon: + Gl.alarm_hours = 11 + elif (Gl.alarm_hours,hours) = (11,0): + # Moved forward through noon: + Gl.alarm_hours = 12 + elif (Gl.alarm_hours,hours) = (23,0): + # Moved forward through midnight: + Gl.alarm_hours = 0 + elif Gl.alarm_hours < 12: + Gl.alarm_hours = hours + else: + Gl.alarm_hours = hours + 12 + seconds = Gl.alarm_hours * HOUR + Gl.alarm_minutes * MINUTE + if seconds <> Gl.alarm_time: + draw_alarm(rgb_bg()) + Gl.alarm_time = seconds + draw_alarm(rgb_fg()) def initmenu(): - Gl.pup = pup = newpup() - addtopup(pup, 'M Clock%t|Alarm On/Off|Seconds Hand On/Off|Quit', 0) + Gl.pup = pup = newpup() + addtopup(pup, 'M Clock%t|Alarm On/Off|Seconds Hand On/Off|Quit', 0) def handlemenu(): - item = dopup(Gl.pup) - if item = 1: - # Toggle alarm - if Gl.alarm_set: - Gl.alarm_set = 0 - Gl.alarm_on = 0 - else: - Gl.alarm_set = 1 - Gl.change = 1 - clearall() - elif item = 2: - # Toggle Seconds Hand - if Gl.update = 1: - Gl.update = 60 - Gl.timernoise = 60 - else: - Gl.update = 1 - Gl.timernoise = 6 - Gl.change = 1 - elif item = 3: - if Gl.debug: print 'Exit' - sys.exit(0) + item = dopup(Gl.pup) + if item = 1: + # Toggle alarm + if Gl.alarm_set: + Gl.alarm_set = 0 + Gl.alarm_on = 0 + else: + Gl.alarm_set = 1 + Gl.change = 1 + clearall() + elif item = 2: + # Toggle Seconds Hand + if Gl.update = 1: + Gl.update = 60 + Gl.timernoise = 60 + else: + Gl.update = 1 + Gl.timernoise = 6 + Gl.change = 1 + elif item = 3: + if Gl.debug: print 'Exit' + sys.exit(0) main() diff --git a/demo/sgi/gl/mixing.py b/demo/sgi/gl/mixing.py index 294e65f..85af96c 100755 --- a/demo/sgi/gl/mixing.py +++ b/demo/sgi/gl/mixing.py @@ -1,8 +1,8 @@ #! /ufs/guido/bin/sgi/python -# Use Gouraud shading to mix colors. Requires Z-buffer. +# Use Gouraud shading to mix colors. Requires Z-buffer. # It changes the color assignments so fast that you see white. -# Left button pauses, middle rotates the square. ESC to quit. +# Left button pauses, middle rotates the square. ESC to quit. # Experiment with a larger window (too slow) or smaller window (really white). from GL import * @@ -11,57 +11,57 @@ import DEVICE from math import * # -# tekenvlak : draw a square. with bgnpolygon +# tekenvlak : draw a square. with bgnpolygon # def tekenvlak (vc) : - bgnpolygon() - #vcarray (vc) - for i in vc : - c3f (i[1]) - v3f (i[0]) - endpolygon() + bgnpolygon() + #vcarray (vc) + for i in vc : + c3f (i[1]) + v3f (i[0]) + endpolygon() # # tekendoos : draw a box # def tekendoos (col) : - v = [(-5.0,0.0,0.0),(0.0,5.0,0.0),(5.0,0.0,0.0),(0.0,-5.0,0.0)] - vc = [(v[0],col[0]),(v[1],col[1]),(v[2],col[2]),(v[3],col[1])] - tekenvlak (vc) + v = [(-5.0,0.0,0.0),(0.0,5.0,0.0),(5.0,0.0,0.0),(0.0,-5.0,0.0)] + vc = [(v[0],col[0]),(v[1],col[1]),(v[2],col[2]),(v[3],col[1])] + tekenvlak (vc) # # initialize gl # def initgl () : - # - # open window - # - foreground () - keepaspect (1, 1) - prefposition (100, 500, 100, 500) - w = winopen ('PYTHON RGB') - keepaspect (1, 1) - winconstraints() - # - # configure pipeline (2buf, GOURAUD and RGBmode) - # - doublebuffer () - zbuffer (1) - shademodel (GOURAUD) - RGBmode () - gconfig () - # - # set viewing - # - perspective (900, 1, 1.0, 10.0) - polarview (10.0, 0, 0, 0) - # - # ask for the REDRAW and ESCKEY events - # - qdevice(DEVICE.MOUSE2) - qdevice(DEVICE.MOUSE3) - qdevice(DEVICE.REDRAW) - qdevice(DEVICE.ESCKEY) + # + # open window + # + foreground () + keepaspect (1, 1) + prefposition (100, 500, 100, 500) + w = winopen ('PYTHON RGB') + keepaspect (1, 1) + winconstraints() + # + # configure pipeline (2buf, GOURAUD and RGBmode) + # + doublebuffer () + zbuffer (1) + shademodel (GOURAUD) + RGBmode () + gconfig () + # + # set viewing + # + perspective (900, 1, 1.0, 10.0) + polarview (10.0, 0, 0, 0) + # + # ask for the REDRAW and ESCKEY events + # + qdevice(DEVICE.MOUSE2) + qdevice(DEVICE.MOUSE3) + qdevice(DEVICE.REDRAW) + qdevice(DEVICE.ESCKEY) # @@ -69,48 +69,48 @@ def initgl () : # black = 0 # -# GoForIT : use 2buf to redraw the object 2n times. index i is used as +# GoForIT : use 2buf to redraw the object 2n times. index i is used as # the (smoothly changing) rotation angle # def GoForIt(i) : - col = [(255.0,0.0,0.0), (0.0,255.0,0.0), (0.0,0.0,255.0)] - twist = 0 - freeze = 1 - while 1 : - if freeze <> 0 : - col[0],col[1],col[2] = col[1],col[2],col[0] - # - # clear z-buffer and clear background to light-blue - # - zclear() - cpack (black) - clear() - # - tekendoos (col) - # - swapbuffers() - # - if qtest() <> 0 : - dev, val = qread() - if dev = DEVICE.ESCKEY : - break - elif dev = DEVICE.REDRAW : - reshapeviewport () - elif dev = DEVICE.MOUSE2 and val <> 0 : - twist = twist + 30 - perspective (900, 1, 1.0, 10.0) - polarview (10.0, 0, 0, twist) - elif dev = DEVICE.MOUSE3 and val <> 0 : - freeze = 1 - freeze + col = [(255.0,0.0,0.0), (0.0,255.0,0.0), (0.0,0.0,255.0)] + twist = 0 + freeze = 1 + while 1 : + if freeze <> 0 : + col[0],col[1],col[2] = col[1],col[2],col[0] + # + # clear z-buffer and clear background to light-blue + # + zclear() + cpack (black) + clear() + # + tekendoos (col) + # + swapbuffers() + # + if qtest() <> 0 : + dev, val = qread() + if dev = DEVICE.ESCKEY : + break + elif dev = DEVICE.REDRAW : + reshapeviewport () + elif dev = DEVICE.MOUSE2 and val <> 0 : + twist = twist + 30 + perspective (900, 1, 1.0, 10.0) + polarview (10.0, 0, 0, twist) + elif dev = DEVICE.MOUSE3 and val <> 0 : + freeze = 1 - freeze # the main program # def main () : - initgl () - GoForIt (0) + initgl () + GoForIt (0) # # exec main # -main () +main () diff --git a/demo/sgi/gl/nurbs.py b/demo/sgi/gl/nurbs.py index ee48e23..dbcc18e 100755 --- a/demo/sgi/gl/nurbs.py +++ b/demo/sgi/gl/nurbs.py @@ -20,152 +20,152 @@ idmat = [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1] surfknots = [-1, -1, -1, -1, 1, 1, 1, 1] def make_ctlpoints(): - c = [] - # - ci = [] - ci.append(-2.5, -3.7, 1.0) - ci.append(-1.5, -3.7, 3.0) - ci.append(1.5, -3.7, -2.5) - ci.append(2.5, -3.7, -0.75) - c.append(ci) - # - ci = [] - ci.append(-2.5, -2.0, 3.0) - ci.append(-1.5, -2.0, 4.0) - ci.append(1.5, -2.0, -3.0) - ci.append(2.5, -2.0, 0.0) - c.append(ci) - # - ci = [] - ci.append(-2.5, 2.0, 1.0) - ci.append(-1.5, 2.0, 0.0) - ci.append(1.5, 2.0, -1.0) - ci.append(2.5, 2.0, 2.0) - c.append(ci) - # - ci = [] - ci.append(-2.5, 2.7, 1.25) - ci.append(-1.5, 2.7, 0.1) - ci.append(1.5, 2.7, -0.6) - ci.append(2.5, 2.7, 0.2) - c.append(ci) - # - return c + c = [] + # + ci = [] + ci.append(-2.5, -3.7, 1.0) + ci.append(-1.5, -3.7, 3.0) + ci.append(1.5, -3.7, -2.5) + ci.append(2.5, -3.7, -0.75) + c.append(ci) + # + ci = [] + ci.append(-2.5, -2.0, 3.0) + ci.append(-1.5, -2.0, 4.0) + ci.append(1.5, -2.0, -3.0) + ci.append(2.5, -2.0, 0.0) + c.append(ci) + # + ci = [] + ci.append(-2.5, 2.0, 1.0) + ci.append(-1.5, 2.0, 0.0) + ci.append(1.5, 2.0, -1.0) + ci.append(2.5, 2.0, 2.0) + c.append(ci) + # + ci = [] + ci.append(-2.5, 2.7, 1.25) + ci.append(-1.5, 2.7, 0.1) + ci.append(1.5, 2.7, -0.6) + ci.append(2.5, 2.7, 0.2) + c.append(ci) + # + return c ctlpoints = make_ctlpoints() -trimknots = [0., 0., 0., 1., 1., 2., 2., 3., 3., 4., 4., 4.] +trimknots = [0., 0., 0., 1., 1., 2., 2., 3., 3., 4., 4., 4.] def make_trimpoints(): - c = [] - c.append(1.0, 0.0, 1.0) - c.append(1.0, 1.0, 1.0) - c.append(0.0, 2.0, 2.0) - c.append(-1.0, 1.0, 1.0) - c.append(-1.0, 0.0, 1.0) - c.append(-1.0, -1.0, 1.0) - c.append(0.0, -2.0, 2.0) - c.append(1.0, -1.0, 1.0) - c.append(1.0, 0.0, 1.0) - return c + c = [] + c.append(1.0, 0.0, 1.0) + c.append(1.0, 1.0, 1.0) + c.append(0.0, 2.0, 2.0) + c.append(-1.0, 1.0, 1.0) + c.append(-1.0, 0.0, 1.0) + c.append(-1.0, -1.0, 1.0) + c.append(0.0, -2.0, 2.0) + c.append(1.0, -1.0, 1.0) + c.append(1.0, 0.0, 1.0) + return c trimpoints = make_trimpoints() def main(): - init_windows() - setup_queue() - make_lights() - init_view() - # - set_scene() - setnurbsproperty( N_ERRORCHECKING, 1.0 ) - setnurbsproperty( N_PIXEL_TOLERANCE, 50.0 ) - trim_flag = 0 - draw_trim_surface(trim_flag) - # - while 1: - while qtest(): - dev, val = qread() - if dev = ESCKEY: - return - elif dev = WINQUIT: - dglclose(-1) # this for DGL only - return - elif dev = REDRAW: - reshapeviewport() - set_scene() - draw_trim_surface(trim_flag) - elif dev = LEFTMOUSE: - if val: - trim_flag = (not trim_flag) - set_scene() - draw_trim_surface(trim_flag) + init_windows() + setup_queue() + make_lights() + init_view() + # + set_scene() + setnurbsproperty( N_ERRORCHECKING, 1.0 ) + setnurbsproperty( N_PIXEL_TOLERANCE, 50.0 ) + trim_flag = 0 + draw_trim_surface(trim_flag) + # + while 1: + while qtest(): + dev, val = qread() + if dev = ESCKEY: + return + elif dev = WINQUIT: + dglclose(-1) # this for DGL only + return + elif dev = REDRAW: + reshapeviewport() + set_scene() + draw_trim_surface(trim_flag) + elif dev = LEFTMOUSE: + if val: + trim_flag = (not trim_flag) + set_scene() + draw_trim_surface(trim_flag) def init_windows(): - foreground() - #prefposition(0, 500, 0, 500) - wid = winopen('nurbs') - wintitle('NURBS Surface') - doublebuffer() - RGBmode() - gconfig() - lsetdepth(0x000, 0x7fffff) - zbuffer( TRUE ) + foreground() + #prefposition(0, 500, 0, 500) + wid = winopen('nurbs') + wintitle('NURBS Surface') + doublebuffer() + RGBmode() + gconfig() + lsetdepth(0x000, 0x7fffff) + zbuffer( TRUE ) def setup_queue(): - qdevice(ESCKEY) - qdevice(REDRAW) - qdevice(RIGHTMOUSE) - qdevice(WINQUIT) - qdevice(LEFTMOUSE) #trimming + qdevice(ESCKEY) + qdevice(REDRAW) + qdevice(RIGHTMOUSE) + qdevice(WINQUIT) + qdevice(LEFTMOUSE) #trimming def init_view(): - mmode(MPROJECTION) - ortho( -4., 4., -4., 4., -4., 4. ) - # - mmode(MVIEWING) - loadmatrix(idmat) - # - lmbind(MATERIAL, 1) + mmode(MPROJECTION) + ortho( -4., 4., -4., 4., -4., 4. ) + # + mmode(MVIEWING) + loadmatrix(idmat) + # + lmbind(MATERIAL, 1) def set_scene(): - lmbind(MATERIAL, 0) - RGBcolor(150,150,150) - lmbind(MATERIAL, 1) - clear() - zclear() - # - rotate( 100, 'y' ) - rotate( 100, 'z' ) + lmbind(MATERIAL, 0) + RGBcolor(150,150,150) + lmbind(MATERIAL, 1) + clear() + zclear() + # + rotate( 100, 'y' ) + rotate( 100, 'z' ) def draw_trim_surface(trim_flag): - bgnsurface() - nurbssurface(surfknots, surfknots, ctlpoints, ORDER, ORDER, N_XYZ) - if trim_flag: - bgntrim() - nurbscurve(trimknots, trimpoints, ORDER-1, N_STW) - endtrim() - endsurface() - swapbuffers() + bgnsurface() + nurbssurface(surfknots, surfknots, ctlpoints, ORDER, ORDER, N_XYZ) + if trim_flag: + bgntrim() + nurbscurve(trimknots, trimpoints, ORDER-1, N_STW) + endtrim() + endsurface() + swapbuffers() def make_lights(): - lmdef(DEFLMODEL,1,[]) - lmdef(DEFLIGHT,1,[]) - # - # define material #1 - # - a = [] - a = a + [EMISSION, 0.0, 0.0, 0.0] - a = a + [AMBIENT, 0.1, 0.1, 0.1] - a = a + [DIFFUSE, 0.6, 0.3, 0.3] - a = a + [SPECULAR, 0.0, 0.6, 0.0] - a = a + [SHININESS, 2.0] - a = a + [LMNULL] - lmdef(DEFMATERIAL, 1, a) - # - # turn on lighting - # - lmbind(LIGHT0, 1) - lmbind(LMODEL, 1) + lmdef(DEFLMODEL,1,[]) + lmdef(DEFLIGHT,1,[]) + # + # define material #1 + # + a = [] + a = a + [EMISSION, 0.0, 0.0, 0.0] + a = a + [AMBIENT, 0.1, 0.1, 0.1] + a = a + [DIFFUSE, 0.6, 0.3, 0.3] + a = a + [SPECULAR, 0.0, 0.6, 0.0] + a = a + [SHININESS, 2.0] + a = a + [LMNULL] + lmdef(DEFMATERIAL, 1, a) + # + # turn on lighting + # + lmbind(LIGHT0, 1) + lmbind(LMODEL, 1) main() diff --git a/demo/sgi/gl/zrgb.py b/demo/sgi/gl/zrgb.py index c3f934a..a49b86b 100755 --- a/demo/sgi/gl/zrgb.py +++ b/demo/sgi/gl/zrgb.py @@ -1,13 +1,13 @@ #! /ufs/guido/bin/sgi/python -# zrgb (Requires Z buffer.) +# zrgb (Requires Z buffer.) # # This program demostrates zbuffering 3 intersecting RGB polygons while -# in doublebuffer mode where, movement of the mouse with the LEFTMOUSE +# in doublebuffer mode where, movement of the mouse with the LEFTMOUSE # button depressed will, rotate the 3 polygons. This is done by compound -# rotations allowing continuous screen-oriented rotations. +# rotations allowing continuous screen-oriented rotations. # -# Press the "Esc" key to exit. +# Press the "Esc" key to exit. from gl import * from GL import * @@ -19,115 +19,115 @@ objmat=[1.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0] idmat=[1.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0] def main() : - # - # old and new mouse position - # - # - mode = 0 - omx = 0 - mx = 0 - omy = 0 - my = 0 - # - initialize () - # - draw_scene (objmat) - # - while (1) : - # - dev, val = qread() - # - if dev = ESCKEY : - if val : - break - # exit when key is going up, not down - # this avoids the scenario where a window - # underneath this program's window - # would otherwise "eat up" the up- - # event of the Esc key being released - return - # - elif dev = REDRAW : - reshapeviewport() - draw_scene(objmat) - # - elif dev = LEFTMOUSE: - omx = mx - omy = my - if val : - mode = 1 - else : - mode = 0 - elif dev = MOUSEX : - omx = mx - mx = val - #print omx, mx - objmat = update_scene(objmat,mx,my,omx,omy,mode) - # - elif dev = MOUSEY : - omy = my - my = val - #print omy, my - objmat = update_scene(objmat,mx,my,omx,omy,mode) - # + # + # old and new mouse position + # + # + mode = 0 + omx = 0 + mx = 0 + omy = 0 + my = 0 + # + initialize () + # + draw_scene (objmat) + # + while (1) : + # + dev, val = qread() + # + if dev = ESCKEY : + if val : + break + # exit when key is going up, not down + # this avoids the scenario where a window + # underneath this program's window + # would otherwise "eat up" the up- + # event of the Esc key being released + return + # + elif dev = REDRAW : + reshapeviewport() + draw_scene(objmat) + # + elif dev = LEFTMOUSE: + omx = mx + omy = my + if val : + mode = 1 + else : + mode = 0 + elif dev = MOUSEX : + omx = mx + mx = val + #print omx, mx + objmat = update_scene(objmat,mx,my,omx,omy,mode) + # + elif dev = MOUSEY : + omy = my + my = val + #print omy, my + objmat = update_scene(objmat,mx,my,omx,omy,mode) + # def initialize () : - # - foreground () - keepaspect(5, 4) - w = winopen('Zbuffered RGB') - # - doublebuffer() - RGBmode() - gconfig() - zbuffer(1) - lsetdepth(0x0, 0x7FFFFF) - # - qdevice(ESCKEY) - qdevice(LEFTMOUSE) - qdevice(MOUSEX) - qdevice(MOUSEY) + # + foreground () + keepaspect(5, 4) + w = winopen('Zbuffered RGB') + # + doublebuffer() + RGBmode() + gconfig() + zbuffer(1) + lsetdepth(0x0, 0x7FFFFF) + # + qdevice(ESCKEY) + qdevice(LEFTMOUSE) + qdevice(MOUSEX) + qdevice(MOUSEY) def update_scene (mat, mx, my, omx, omy, mode) : - # - if mode = 1 : - mat = orient(mat, mx, my, omx, omy) - draw_scene(mat) - return mat + # + if mode = 1 : + mat = orient(mat, mx, my, omx, omy) + draw_scene(mat) + return mat def orient (mat, mx, my, omx, omy) : - # - # - pushmatrix() - loadmatrix(idmat) - # - if mx - omx : rot (float (mx - omx), 'y') - if omy - my : rot (float (omy - my), 'x') - # - multmatrix(mat) - mat = getmatrix() - # - # - popmatrix() - # - return mat + # + # + pushmatrix() + loadmatrix(idmat) + # + if mx - omx : rot (float (mx - omx), 'y') + if omy - my : rot (float (omy - my), 'x') + # + multmatrix(mat) + mat = getmatrix() + # + # + popmatrix() + # + return mat def draw_scene (mat) : - RGBcolor(40, 100, 200) - clear() - zclear() - # - perspective(400, 1.25, 30.0, 60.0) - translate(0.0, 0.0, -40.0) - multmatrix(mat) - # - # skews original view to show all polygons - # - rotate(-580, 'y') - draw_polys() - # - swapbuffers() + RGBcolor(40, 100, 200) + clear() + zclear() + # + perspective(400, 1.25, 30.0, 60.0) + translate(0.0, 0.0, -40.0) + multmatrix(mat) + # + # skews original view to show all polygons + # + rotate(-580, 'y') + draw_polys() + # + swapbuffers() polygon1 = [(-10.0,-10.0,0.0),(10.0,-10.0,0.0),(-10.0,10.0,0.0)] @@ -136,34 +136,34 @@ polygon2 = [(0.0,-10.0,-10.0),(0.0,-10.0,10.0),(0.0,5.0,-10.0)] polygon3 = [(-10.0,6.0,4.0),(-10.0,3.0,4.0),(4.0,-9.0,-10.0),(4.0,-6.0,-10.0)] def draw_polys(): - bgnpolygon() - cpack(0x0) - v3f(polygon1[0]) - cpack(0x007F7F7F) - v3f(polygon1[1]) - cpack(0x00FFFFFF) - v3f(polygon1[2]) - endpolygon() - # - bgnpolygon() - cpack(0x0000FFFF) - v3f(polygon2[0]) - cpack(0x007FFF00) - v3f(polygon2[1]) - cpack(0x00FF0000) - v3f(polygon2[2]) - endpolygon() - # - bgnpolygon() - cpack(0x0000FFFF) - v3f(polygon3[0]) - cpack(0x00FF00FF) - v3f(polygon3[1]) - cpack(0x00FF0000) - v3f(polygon3[2]) - cpack(0x00FF00FF) - v3f(polygon3[3]) - endpolygon() + bgnpolygon() + cpack(0x0) + v3f(polygon1[0]) + cpack(0x007F7F7F) + v3f(polygon1[1]) + cpack(0x00FFFFFF) + v3f(polygon1[2]) + endpolygon() + # + bgnpolygon() + cpack(0x0000FFFF) + v3f(polygon2[0]) + cpack(0x007FFF00) + v3f(polygon2[1]) + cpack(0x00FF0000) + v3f(polygon2[2]) + endpolygon() + # + bgnpolygon() + cpack(0x0000FFFF) + v3f(polygon3[0]) + cpack(0x00FF00FF) + v3f(polygon3[1]) + cpack(0x00FF0000) + v3f(polygon3[2]) + cpack(0x00FF00FF) + v3f(polygon3[3]) + endpolygon() main () diff --git a/demo/sgi/gl_panel/README b/demo/sgi/gl_panel/README index 889a2cf..ccf255d 100644 --- a/demo/sgi/gl_panel/README +++ b/demo/sgi/gl_panel/README @@ -1,23 +1,23 @@ This directory contains demos that use the Panel Library by NASA Ames. They only run on SGI machines and require the 'pnl' and 'gl' built-in -modules. Each subdirectory contains one demo. +modules. Each subdirectory contains one demo. -apanel A trivial user interface to the audio capabilities of - the 4D/25 (Personal IRIS). Lets you record a sample and - play it back at different volumes. Requires the 'audio' - built-in module. +apanel A trivial user interface to the audio capabilities of + the 4D/25 (Personal IRIS). Lets you record a sample and + play it back at different volumes. Requires the 'audio' + built-in module. -flying A large demonstration that can display several - differently shaped objects through space. Control - panels let you manipulate light sources, material - properties and drawing modes. +flying A large demonstration that can display several + differently shaped objects through space. Control + panels let you manipulate light sources, material + properties and drawing modes. -nurbs A demo of the capabilities of the GL 'nurbs' functions - that can display the control points. (It was intended - to let you move these as well, but there was a problem - with the mapping of mouse movements in a 3-D world.) +nurbs A demo of the capabilities of the GL 'nurbs' functions + that can display the control points. (It was intended + to let you move these as well, but there was a problem + with the mapping of mouse movements in a 3-D world.) -twoview A demo of GL's transformation primitives. Two views on - a scene are given, and the position and orientation of a - viewer in one of the views can be changed through - various buttons and dials in a control panel. +twoview A demo of GL's transformation primitives. Two views on + a scene are given, and the position and orientation of a + viewer in one of the views can be changed through + various buttons and dials in a control panel. diff --git a/demo/sgi/gl_panel/apanel/apanel.py b/demo/sgi/gl_panel/apanel/apanel.py index de9a710..a5adfdb 100755 --- a/demo/sgi/gl_panel/apanel/apanel.py +++ b/demo/sgi/gl_panel/apanel/apanel.py @@ -14,50 +14,50 @@ panel.block(1) import audio def main(): - gl.foreground() - gl.noport() - #gl.prefposition(700, 850, 950, 970) - wid = gl.winopen('audio demo') - # - panels = panel.defpanellist('apanel.s') # XXX - p = panels[0] - p.playbackbutton.back = p - p.recordbutton.back = p - p.sample = '' - # - def quit(a): - sys.exit(0) - # - p.quitbutton.downfunc = quit - # - def playback(a): - p = a.back - gain = int(255.0*p.outputgain.val) - a.val = 1.0 - a.fixact() - panel.drawpanel() - audio.setoutgain(gain) - audio.write(p.sample) - audio.setoutgain(0) - a.val = 0.0 - a.fixact() - # - p.playbackbutton.downfunc = playback - # - def record(a): - p = a.back - size = int(10.0 * 8192.0 * p.recordsize.val) - a.val = 1.0 - a.fixact() - panel.drawpanel() - audio.setoutgain(0) - p.sample = audio.read(size) - a.val = 0.0 - a.fixact() - # - p.recordbutton.downfunc = record - # - while 1: - act = panel.dopanel() + gl.foreground() + gl.noport() + #gl.prefposition(700, 850, 950, 970) + wid = gl.winopen('audio demo') + # + panels = panel.defpanellist('apanel.s') # XXX + p = panels[0] + p.playbackbutton.back = p + p.recordbutton.back = p + p.sample = '' + # + def quit(a): + sys.exit(0) + # + p.quitbutton.downfunc = quit + # + def playback(a): + p = a.back + gain = int(255.0*p.outputgain.val) + a.val = 1.0 + a.fixact() + panel.drawpanel() + audio.setoutgain(gain) + audio.write(p.sample) + audio.setoutgain(0) + a.val = 0.0 + a.fixact() + # + p.playbackbutton.downfunc = playback + # + def record(a): + p = a.back + size = int(10.0 * 8192.0 * p.recordsize.val) + a.val = 1.0 + a.fixact() + panel.drawpanel() + audio.setoutgain(0) + p.sample = audio.read(size) + a.val = 0.0 + a.fixact() + # + p.recordbutton.downfunc = record + # + while 1: + act = panel.dopanel() main() diff --git a/demo/sgi/gl_panel/flying/flying.py b/demo/sgi/gl_panel/flying/flying.py index e6fd823..b51f466 100755 --- a/demo/sgi/gl_panel/flying/flying.py +++ b/demo/sgi/gl_panel/flying/flying.py @@ -7,369 +7,369 @@ import DEVICE, time import objectdef, light, panel, material def fixmatact (p) : - p.diffR.fixact () - p.diffG.fixact () - p.diffB.fixact () - p.specR.fixact () - p.specG.fixact () - p.specB.fixact () - p.shine.fixact () + p.diffR.fixact () + p.diffG.fixact () + p.diffB.fixact () + p.specR.fixact () + p.specG.fixact () + p.specB.fixact () + p.shine.fixact () def fixlichtact (p) : - p.R.fixact () - p.G.fixact () - p.B.fixact () - p.X.fixact () - p.Y.fixact () - p.Z.fixact () - p.local.fixact () + p.R.fixact () + p.G.fixact () + p.B.fixact () + p.X.fixact () + p.Y.fixact () + p.Z.fixact () + p.local.fixact () def cbsetlight (a) : - p = a.back - setlight (p, a.label) + p = a.back + setlight (p, a.label) def cbsetmaterial (a) : - p = a.back - setmaterial (p, a.label) + p = a.back + setmaterial (p, a.label) mater = [0] licht = [0] def setmaterial (p, mname) : - # - mater [0:1] = [material.materdict [mname]] - # - p.diffR.val = mater [0][1] - p.diffG.val = mater [0][2] - p.diffB.val = mater [0][3] - # - p.specR.val = mater [0][5] - p.specG.val = mater [0][6] - p.specB.val = mater [0][7] - # - p.shine.val = mater [0][9] / 128.0 - fixmatact (p) + # + mater [0:1] = [material.materdict [mname]] + # + p.diffR.val = mater [0][1] + p.diffG.val = mater [0][2] + p.diffB.val = mater [0][3] + # + p.specR.val = mater [0][5] + p.specG.val = mater [0][6] + p.specB.val = mater [0][7] + # + p.shine.val = mater [0][9] / 128.0 + fixmatact (p) def setlight (p, mname) : - # - licht [0:1] = [material.lichtdict [mname]] - # - p.R.val = licht [0][1] - p.G.val = licht [0][2] - p.B.val = licht [0][3] - # - p.X.val = (licht [0][5] + 10.0) / 20.0 - p.Y.val = (licht [0][6] + 10.0) / 20.0 - p.Z.val = (licht [0][7] + 10.0) / 20.0 - # - p.local.val = licht [0][8] - # - fixlichtact (p) + # + licht [0:1] = [material.lichtdict [mname]] + # + p.R.val = licht [0][1] + p.G.val = licht [0][2] + p.B.val = licht [0][3] + # + p.X.val = (licht [0][5] + 10.0) / 20.0 + p.Y.val = (licht [0][6] + 10.0) / 20.0 + p.Z.val = (licht [0][7] + 10.0) / 20.0 + # + p.local.val = licht [0][8] + # + fixlichtact (p) def cbmaterial (a) : - # - if mater[0] = 0 : return - # - p = a.back - mater [0][5:8] = [p.diffR.val, p.diffG.val, p.diffB.val] - mater [0][1:4] = [p.specR.val, p.specG.val, p.specB.val] - mater [0][9:10] = [128.0 * p.shine.val] - light.bindlight (0) + # + if mater[0] = 0 : return + # + p = a.back + mater [0][5:8] = [p.diffR.val, p.diffG.val, p.diffB.val] + mater [0][1:4] = [p.specR.val, p.specG.val, p.specB.val] + mater [0][9:10] = [128.0 * p.shine.val] + light.bindlight (0) def cblight (a) : - # - if licht[0] = 0 : return - # - p = a.back - licht [0][1:4] = [p.R.val, p.G.val, p.B.val] - licht [0][5:8] = [20.0 * p.X.val - 10.0, 20.0 * p.Y.val - 10.0, 20.0 * p.Z.val - 10.0] - if p.local.val = 0.0 : - licht [0][8:9] = [0.0] - else: - licht [0][8:9] = [1.0] - # - light.bindlight (0) + # + if licht[0] = 0 : return + # + p = a.back + licht [0][1:4] = [p.R.val, p.G.val, p.B.val] + licht [0][5:8] = [20.0 * p.X.val - 10.0, 20.0 * p.Y.val - 10.0, 20.0 * p.Z.val - 10.0] + if p.local.val = 0.0 : + licht [0][8:9] = [0.0] + else: + licht [0][8:9] = [1.0] + # + light.bindlight (0) # # initgl : initialize window, pipeline, light, viewing # def initgl () : - # - # init window - # - foreground () - keepaspect (1, 1) - prefposition (100, 500, 100, 500) - w = winopen ('flying objects') - keepaspect (1, 1) - winconstraints () - # - # configure pipline - # - doublebuffer () - shademodel (GOURAUD) - zbuffer (1) - RGBmode () - gconfig () - # - # init lighting - # - light.bindlight (1) - # - # set viewing - # - lookat (0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0) - # + # + # init window + # + foreground () + keepaspect (1, 1) + prefposition (100, 500, 100, 500) + w = winopen ('flying objects') + keepaspect (1, 1) + winconstraints () + # + # configure pipline + # + doublebuffer () + shademodel (GOURAUD) + zbuffer (1) + RGBmode () + gconfig () + # + # init lighting + # + light.bindlight (1) + # + # set viewing + # + lookat (0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0) + # # # drawit : draws the object with the given attributes. # # rfac : the rotation factor. -# mat : the material identification -# attr : a list of attributes : +# mat : the material identification +# attr : a list of attributes : # -# [[rotate vector ], [tranlate vector], [scale vector]] -# i.e : -# [[rX, rY, rZ], [tX, tY, tZ], [sX, sY, sZ]] +# [[rotate vector ], [tranlate vector], [scale vector]] +# i.e : +# [[rX, rY, rZ], [tX, tY, tZ], [sX, sY, sZ]] # def drawit(object, rfac, attr, mat) : - pushmatrix() - rot (attr[0][0] * float (rfac), 'X') - rot (attr[0][1] * float (rfac), 'Y') - rot (attr[0][2] * float (rfac), 'Z') - translate(attr[1][0], attr[1][1], attr[1][2]) - scale(attr[2][0], attr[2][1], attr[2][2]) - lmbind(MATERIAL, mat) - objectdef.drawobject(object) - popmatrix() + pushmatrix() + rot (attr[0][0] * float (rfac), 'X') + rot (attr[0][1] * float (rfac), 'Y') + rot (attr[0][2] * float (rfac), 'Z') + translate(attr[1][0], attr[1][1], attr[1][2]) + scale(attr[2][0], attr[2][1], attr[2][2]) + lmbind(MATERIAL, mat) + objectdef.drawobject(object) + popmatrix() def callbacksphere (a) : - putDict (objects, 'sphere', int (a.val)) + putDict (objects, 'sphere', int (a.val)) def callbackcylinder (a) : - putDict (objects, 'cylinder', int (a.val)) + putDict (objects, 'cylinder', int (a.val)) def callbackcube (a) : - putDict (objects, 'cube', int (a.val)) + putDict (objects, 'cube', int (a.val)) def callbackicecream (a) : - putDict (objects, 'icecream', int (a.val)) + putDict (objects, 'icecream', int (a.val)) def callbackdisk (a) : - putDict (objects, 'disk', int (a.val)) + putDict (objects, 'disk', int (a.val)) def callbackdiamond (a) : - putDict (objects, 'diamond', int (a.val)) + putDict (objects, 'diamond', int (a.val)) def callbackglass (a) : - putDict (objects, 'glass', int (a.val)) + putDict (objects, 'glass', int (a.val)) def callbackpyramid (a) : - putDict (objects, 'pyramid', int (a.val)) + putDict (objects, 'pyramid', int (a.val)) def callbacktable (a) : - putDict (objects, 'table', int (a.val)) + putDict (objects, 'table', int (a.val)) def callbackflat (a) : - shademodel(FLAT) + shademodel(FLAT) def callbackgouraud (a) : - shademodel(GOURAUD) + shademodel(GOURAUD) def callbackwire (a) : - objectdef.putFunc ([bgnclosedline, endclosedline]) + objectdef.putFunc ([bgnclosedline, endclosedline]) def callbackfilled (a) : - objectdef.putFunc ([bgnpolygon, endpolygon]) + objectdef.putFunc ([bgnpolygon, endpolygon]) def callbackquit (a) : - import sys - sys.exit (-1) + import sys + sys.exit (-1) def allObjects(p, val) : - p.sphere.val = val - p.sphere.fixact () - p.cube.val = val - p.cube.fixact () - p.cylinder.val = val - p.cylinder.fixact () - p.pyramid.val = val - p.pyramid.fixact () - p.disk.val = val - p.disk.fixact () - p.diamond.val = val - p.diamond.fixact () - p.icecream.val = val - p.icecream.fixact () - p.table.val = val - p.table.fixact () - p.fixpanel() - + p.sphere.val = val + p.sphere.fixact () + p.cube.val = val + p.cube.fixact () + p.cylinder.val = val + p.cylinder.fixact () + p.pyramid.val = val + p.pyramid.fixact () + p.disk.val = val + p.disk.fixact () + p.diamond.val = val + p.diamond.fixact () + p.icecream.val = val + p.icecream.fixact () + p.table.val = val + p.table.fixact () + p.fixpanel() + def callbackshowall (a) : - #print objects - for key in objects.keys () : - #print key - putDict (objects, key, 1) - allObjects (a.back, 1.0) + #print objects + for key in objects.keys () : + #print key + putDict (objects, key, 1) + allObjects (a.back, 1.0) def callbackshownone (a) : - for key in objects.keys () : - putDict (objects, key, 0) - allObjects (a.back, 0.0) + for key in objects.keys () : + putDict (objects, key, 0) + allObjects (a.back, 0.0) # # main : makeobjects, initialze graphics, and loop continuously. # def main () : - # - # iter keeps track of the iterations. It is used as the - # (x, y, z) rotation increments to which the objects rotate. - iter = 0 - # - # make the objects. the objects are put in the odict dictionary - # - od = objectdef.makeobjects () - # - # initialize gl - # - initgl () - # - # initialize time and iterations per second - # - time0 = time.time () # epoch-time of previous second - fps = 0 # frames per second - # - # initialize panels - # - panel.needredraw() - panels = panel.defpanellist('flying.s') #XXX - p = panels[0] - p.sphere.upfunc = callbacksphere - p.cylinder.upfunc = callbackcylinder - p.cube.upfunc = callbackcube - p.icecream.upfunc = callbackicecream - p.disk.upfunc = callbackdisk - p.diamond.upfunc = callbackdiamond - # NOT YET IMPLEMENTED p.glass.upfunc = callbackglass - p.pyramid.upfunc = callbackpyramid - p.table.upfunc = callbacktable - p.wire.upfunc = callbackwire - p.filled.upfunc = callbackfilled - p.flat.upfunc = callbackflat - p.gouraud.upfunc = callbackgouraud - p.quit.upfunc = callbackquit - p.showall.upfunc = callbackshowall - p.shownone.upfunc = callbackshownone - p.showall.back = p - p.shownone.back = p - # - qanels = panel.defpanellist('freeze.s') #XXX - q = qanels[0] - # - ranels = panel.defpanellist('materials.s') #XXX - r = ranels[0] - r.m9.upfunc = cbsetmaterial - r.m8.upfunc = cbsetmaterial - r.m7.upfunc = cbsetmaterial - r.m6.upfunc = cbsetmaterial - r.m5.upfunc = cbsetmaterial - r.m4.upfunc = cbsetmaterial - r.m3.upfunc = cbsetmaterial - r.m2.upfunc = cbsetmaterial - r.m1.upfunc = cbsetmaterial - r.specR.activefunc = cbmaterial - r.specG.activefunc = cbmaterial - r.specB.activefunc = cbmaterial - r.diffR.activefunc = cbmaterial - r.diffG.activefunc = cbmaterial - r.diffB.activefunc = cbmaterial - r.shine.activefunc = cbmaterial - r.m9.back = r - r.m8.back = r - r.m7.back = r - r.m6.back = r - r.m5.back = r - r.m4.back = r - r.m3.back = r - r.m2.back = r - r.m1.back = r - r.diffR.back = r - r.diffG.back = r - r.diffB.back = r - r.specR.back = r - r.specG.back = r - r.specB.back = r - r.shine.back = r - # - sanels = panel.defpanellist('light.s') #XXX - s = sanels[0] - s.X.back = s - s.Y.back = s - s.Z.back = s - s.R.back = s - s.G.back = s - s.B.back = s - s.light1.back = s - s.light2.back = s - s.local.back = s - s.light1.upfunc = cbsetlight - s.light2.upfunc = cbsetlight - s.R.activefunc = cblight - s.G.activefunc = cblight - s.B.activefunc = cblight - s.X.activefunc = cblight - s.Y.activefunc = cblight - s.Z.activefunc = cblight - # - while 1 : - # - act = panel.dopanel() - # - wid = panel.userredraw () - if wid : - winset (wid) - reshapeviewport() - # - # increment iter - # - if int (q.freeze.val) = 0 : - iter = iter + 1 - fps = fps + 1 - if time.time() - time0 >= 1 : - f = float(fps)/float(time.time()-time0) - q.mystrip.val = f - q.mystrip.fixact () - q.fixpanel() - time0 = time.time() - fps = 0 - # - # clear the zbuffer and make the background light blue - # - zclear() - c3i (LightBlue) - clear() - # - # for each object in the objects dictionary - # - for key in objects.keys() : - # - # if the object should be displayed - # - if getDict (objects, key, 0) = ONE : - loo = getDict (objects, key, 1) - for o in loo : - # - # get attributes and materail - # - attr = o [1] - mat = o [2] - # - # display the object - # - drawit(od[o[0]],iter,attr,mat) - # - swapbuffers() - # + # + # iter keeps track of the iterations. It is used as the + # (x, y, z) rotation increments to which the objects rotate. + iter = 0 + # + # make the objects. the objects are put in the odict dictionary + # + od = objectdef.makeobjects () + # + # initialize gl + # + initgl () + # + # initialize time and iterations per second + # + time0 = time.time () # epoch-time of previous second + fps = 0 # frames per second + # + # initialize panels + # + panel.needredraw() + panels = panel.defpanellist('flying.s') #XXX + p = panels[0] + p.sphere.upfunc = callbacksphere + p.cylinder.upfunc = callbackcylinder + p.cube.upfunc = callbackcube + p.icecream.upfunc = callbackicecream + p.disk.upfunc = callbackdisk + p.diamond.upfunc = callbackdiamond + # NOT YET IMPLEMENTED p.glass.upfunc = callbackglass + p.pyramid.upfunc = callbackpyramid + p.table.upfunc = callbacktable + p.wire.upfunc = callbackwire + p.filled.upfunc = callbackfilled + p.flat.upfunc = callbackflat + p.gouraud.upfunc = callbackgouraud + p.quit.upfunc = callbackquit + p.showall.upfunc = callbackshowall + p.shownone.upfunc = callbackshownone + p.showall.back = p + p.shownone.back = p + # + qanels = panel.defpanellist('freeze.s') #XXX + q = qanels[0] + # + ranels = panel.defpanellist('materials.s') #XXX + r = ranels[0] + r.m9.upfunc = cbsetmaterial + r.m8.upfunc = cbsetmaterial + r.m7.upfunc = cbsetmaterial + r.m6.upfunc = cbsetmaterial + r.m5.upfunc = cbsetmaterial + r.m4.upfunc = cbsetmaterial + r.m3.upfunc = cbsetmaterial + r.m2.upfunc = cbsetmaterial + r.m1.upfunc = cbsetmaterial + r.specR.activefunc = cbmaterial + r.specG.activefunc = cbmaterial + r.specB.activefunc = cbmaterial + r.diffR.activefunc = cbmaterial + r.diffG.activefunc = cbmaterial + r.diffB.activefunc = cbmaterial + r.shine.activefunc = cbmaterial + r.m9.back = r + r.m8.back = r + r.m7.back = r + r.m6.back = r + r.m5.back = r + r.m4.back = r + r.m3.back = r + r.m2.back = r + r.m1.back = r + r.diffR.back = r + r.diffG.back = r + r.diffB.back = r + r.specR.back = r + r.specG.back = r + r.specB.back = r + r.shine.back = r + # + sanels = panel.defpanellist('light.s') #XXX + s = sanels[0] + s.X.back = s + s.Y.back = s + s.Z.back = s + s.R.back = s + s.G.back = s + s.B.back = s + s.light1.back = s + s.light2.back = s + s.local.back = s + s.light1.upfunc = cbsetlight + s.light2.upfunc = cbsetlight + s.R.activefunc = cblight + s.G.activefunc = cblight + s.B.activefunc = cblight + s.X.activefunc = cblight + s.Y.activefunc = cblight + s.Z.activefunc = cblight + # + while 1 : + # + act = panel.dopanel() + # + wid = panel.userredraw () + if wid : + winset (wid) + reshapeviewport() + # + # increment iter + # + if int (q.freeze.val) = 0 : + iter = iter + 1 + fps = fps + 1 + if time.time() - time0 >= 1 : + f = float(fps)/float(time.time()-time0) + q.mystrip.val = f + q.mystrip.fixact () + q.fixpanel() + time0 = time.time() + fps = 0 + # + # clear the zbuffer and make the background light blue + # + zclear() + c3i (LightBlue) + clear() + # + # for each object in the objects dictionary + # + for key in objects.keys() : + # + # if the object should be displayed + # + if getDict (objects, key, 0) = ONE : + loo = getDict (objects, key, 1) + for o in loo : + # + # get attributes and materail + # + attr = o [1] + mat = o [2] + # + # display the object + # + drawit(od[o[0]],iter,attr,mat) + # + swapbuffers() + # main() diff --git a/demo/sgi/gl_panel/flying/light.py b/demo/sgi/gl_panel/flying/light.py index f6bf379..51803fc 100644 --- a/demo/sgi/gl_panel/flying/light.py +++ b/demo/sgi/gl_panel/flying/light.py @@ -23,24 +23,24 @@ light2 = [LCOLOR,1.0,1.0,1.0,POSITION,-10.0,10.0,5.0,0.0,LMNULL] model = [AMBIENT,0.4,0.4,0.4,LMNULL] def bindlight (bool) : - # Initializes all settings for a window. - if bool <> 0 : - mmode(MVIEWING) - perspective (900, 1.0, 1.0, 35.0) - loadmatrix(idmat) - # define materials and lights - lmdef(DEFMATERIAL, 1, m1) - lmdef(DEFMATERIAL, 2, m2) - lmdef(DEFMATERIAL, 3, m3) - lmdef(DEFMATERIAL, 4, m4) - lmdef(DEFMATERIAL, 5, m5) - lmdef(DEFMATERIAL, 6, m6) - lmdef(DEFMATERIAL, 7, m7) - lmdef(DEFMATERIAL, 8, m8) - lmdef(DEFMATERIAL, 9, m9) - lmdef(DEFLIGHT, 1, light1) - lmdef(DEFLIGHT, 2, light2) - lmdef(DEFLMODEL, 1, model) - lmbind(LIGHT0,1) - lmbind(LIGHT1,2) - lmbind(LMODEL,1) + # Initializes all settings for a window. + if bool <> 0 : + mmode(MVIEWING) + perspective (900, 1.0, 1.0, 35.0) + loadmatrix(idmat) + # define materials and lights + lmdef(DEFMATERIAL, 1, m1) + lmdef(DEFMATERIAL, 2, m2) + lmdef(DEFMATERIAL, 3, m3) + lmdef(DEFMATERIAL, 4, m4) + lmdef(DEFMATERIAL, 5, m5) + lmdef(DEFMATERIAL, 6, m6) + lmdef(DEFMATERIAL, 7, m7) + lmdef(DEFMATERIAL, 8, m8) + lmdef(DEFMATERIAL, 9, m9) + lmdef(DEFLIGHT, 1, light1) + lmdef(DEFLIGHT, 2, light2) + lmdef(DEFLMODEL, 1, model) + lmbind(LIGHT0,1) + lmbind(LIGHT1,2) + lmbind(LMODEL,1) diff --git a/demo/sgi/gl_panel/flying/material.py b/demo/sgi/gl_panel/flying/material.py index f9137ea..f091fbb 100644 --- a/demo/sgi/gl_panel/flying/material.py +++ b/demo/sgi/gl_panel/flying/material.py @@ -1,26 +1,26 @@ import light def mkmatdict () : - m = {} - m['material 1'] = light.m1 - m['material 2'] = light.m2 - m['material 3'] = light.m3 - m['material 4'] = light.m4 - m['material 5'] = light.m5 - m['material 6'] = light.m6 - m['material 7'] = light.m7 - m['material 8'] = light.m8 - m['material 9'] = light.m9 - # - return m + m = {} + m['material 1'] = light.m1 + m['material 2'] = light.m2 + m['material 3'] = light.m3 + m['material 4'] = light.m4 + m['material 5'] = light.m5 + m['material 6'] = light.m6 + m['material 7'] = light.m7 + m['material 8'] = light.m8 + m['material 9'] = light.m9 + # + return m materdict = mkmatdict () def mklichtdict () : - m = {} - m['light 1'] = light.light1 - m['light 2'] = light.light2 - # - return m + m = {} + m['light 1'] = light.light1 + m['light 2'] = light.light2 + # + return m lichtdict = mklichtdict () diff --git a/demo/sgi/gl_panel/flying/materials.s b/demo/sgi/gl_panel/flying/materials.s index ae45ca9..b505f0b 100644 --- a/demo/sgi/gl_panel/flying/materials.s +++ b/demo/sgi/gl_panel/flying/materials.s @@ -56,7 +56,7 @@ (h 0.36) (downfunc move-then-resize) ) -(pnl_radio_button (name "m4") +(pnl_radio_button (name "m4") (prop help creator:user-act-help) (label "material 4") (x 6.5) @@ -80,7 +80,7 @@ (h 0.36) (downfunc move-then-resize) ) -(pnl_radio_button (name "m1") +(pnl_radio_button (name "m1") (prop help creator:user-act-help) (label "material 1") (x 6.5) diff --git a/demo/sgi/gl_panel/flying/objdict.py b/demo/sgi/gl_panel/flying/objdict.py index a5d5371..9195093 100644 --- a/demo/sgi/gl_panel/flying/objdict.py +++ b/demo/sgi/gl_panel/flying/objdict.py @@ -23,14 +23,14 @@ objects['table'] = [ZERO, o8] # 'putDict' sets the value of entry 'key' of dictionary 'dict' def putDict(dict, key, val) : - dict[key][0] = val + dict[key][0] = val # -# 'getDict' get the contents of entry i of key 'key' +# 'getDict' get the contents of entry i of key 'key' # of dictionary 'dict' # def getDict(dict, key, i) : - return dict[key][i] + return dict[key][i] # the 'options' dictionary contains the strings of the menu items # that denote the options diff --git a/demo/sgi/gl_panel/flying/objectdef.py b/demo/sgi/gl_panel/flying/objectdef.py index 3e96113..02a9513 100644 --- a/demo/sgi/gl_panel/flying/objectdef.py +++ b/demo/sgi/gl_panel/flying/objectdef.py @@ -7,141 +7,141 @@ FUZZY = 0.00001 # first try - brute force method (ala M.Overmars...) def makespinobject (smooth,rot,n,x1,z1,nx1,nz1,x2,z2,nx2,nz2) : - object = [] - dth = 2.0 * pi / float (rot) - for i in range (0, n) : - for j in range (0, rot) : - th = dth * float (j) - # - if smooth = 1: - a1 = th - a2 =th+dth - else : - a1 = th + dth / 2.0 - a2 = th + dth / 2.0 - # - v0 = (x1[i]*sin(th),x1[i]*cos(th),z1[i]) - n0 = (nx1[i]*sin(a1),nx1[i]*cos(a1),nz1[i]) - # - v1 = (x1[i]*sin(th+dth),x1[i]*cos(th+dth),z1[i]) - n1 = (nx1[i]*sin(a2), nx1[i]*cos(a2), nz1[i]) - # - v2 = (x2[i]*sin(th+dth),x2[i]*cos(th+dth),z2[i]) - n2 = (nx2[i]*sin(a2), nx2[i]*cos(a2), nz2[i]) - # - v3 = (x2[i]*sin(th), x2[i]*cos(th), z2[i]) - n3 = (nx2[i]*sin(a1), nx2[i]*cos(a1), nz2[i]) - # - patch = ((v0,n0), (v1,n1), (v2,n2), (v3,n3)) - #patch = ((n0,v0), (n1,v1), (n2,v2), (n3,v3)) - # - if x1[i] < FUZZY : - patch = patch[1:] - # - object.append (patch) - # - return object + object = [] + dth = 2.0 * pi / float (rot) + for i in range (0, n) : + for j in range (0, rot) : + th = dth * float (j) + # + if smooth = 1: + a1 = th + a2 =th+dth + else : + a1 = th + dth / 2.0 + a2 = th + dth / 2.0 + # + v0 = (x1[i]*sin(th),x1[i]*cos(th),z1[i]) + n0 = (nx1[i]*sin(a1),nx1[i]*cos(a1),nz1[i]) + # + v1 = (x1[i]*sin(th+dth),x1[i]*cos(th+dth),z1[i]) + n1 = (nx1[i]*sin(a2), nx1[i]*cos(a2), nz1[i]) + # + v2 = (x2[i]*sin(th+dth),x2[i]*cos(th+dth),z2[i]) + n2 = (nx2[i]*sin(a2), nx2[i]*cos(a2), nz2[i]) + # + v3 = (x2[i]*sin(th), x2[i]*cos(th), z2[i]) + n3 = (nx2[i]*sin(a1), nx2[i]*cos(a1), nz2[i]) + # + patch = ((v0,n0), (v1,n1), (v2,n2), (v3,n3)) + #patch = ((n0,v0), (n1,v1), (n2,v2), (n3,v3)) + # + if x1[i] < FUZZY : + patch = patch[1:] + # + object.append (patch) + # + return object def makesphere (n): - asin = [] - acos = [] - for i in range (0, n-1): - asin.append (sin((pi/float (n))*(1.0+float (i)))) - acos.append(cos((pi/float (n))*(1.0+float (i)))) - # - x1 = [0.0] + asin - z1 = [1.0] + acos - nx1 = [0.0] + asin - nz1 = [1.0] + acos - # - x2 = asin + [0.0] - z2 = acos + [-1.0] - nx2 = asin + [0.0] - nz2 = acos + [-1.0] - # - return makespinobject (1,2*n,n,x1,z1,nx1,nz1,x2,z2,nx2,nz2) + asin = [] + acos = [] + for i in range (0, n-1): + asin.append (sin((pi/float (n))*(1.0+float (i)))) + acos.append(cos((pi/float (n))*(1.0+float (i)))) + # + x1 = [0.0] + asin + z1 = [1.0] + acos + nx1 = [0.0] + asin + nz1 = [1.0] + acos + # + x2 = asin + [0.0] + z2 = acos + [-1.0] + nx2 = asin + [0.0] + nz2 = acos + [-1.0] + # + return makespinobject (1,2*n,n,x1,z1,nx1,nz1,x2,z2,nx2,nz2) def makecylinder(n) : - x1 = [0.0, 1.0, 1.0] - nx1 = [0.0, 1.0, 0.0] - z1 = [1.0, 1.0, -1.0] - nz1 = [1.0, 0.0, -1.0] - # - z2 = [1.0, -1.0, -1.0] - nz2 = [1.0, 0.0, -1.0] - x2 = [1.0, 1.0, 0.0] - nx2 = [0.0, 1.0, 0.0] - # - return makespinobject(1,2*n,3,x1,z1,nx1,nz1,x2,z2,nx2,nz2) + x1 = [0.0, 1.0, 1.0] + nx1 = [0.0, 1.0, 0.0] + z1 = [1.0, 1.0, -1.0] + nz1 = [1.0, 0.0, -1.0] + # + z2 = [1.0, -1.0, -1.0] + nz2 = [1.0, 0.0, -1.0] + x2 = [1.0, 1.0, 0.0] + nx2 = [0.0, 1.0, 0.0] + # + return makespinobject(1,2*n,3,x1,z1,nx1,nz1,x2,z2,nx2,nz2) def makecone(n) : - x1 = [0.0, 1.0, 1.0] - nx1 = [2.0/sqrt(5.0), 0.0, 0.0] - z1 = [1.0, -1.0, -1.0] - nz1 = [1.0/sqrt(5.0), -1.0, -1.0] - # - x2 = [1.0, 0.0, 0.0] - nx2 = [2.0/sqrt(5.0), 0.0, 0.0] - nz2 = [1.0/sqrt(5.0), -1.0, -1.0] - z2 = [-1.0, -1.0, -1.0] - # - return makespinobject(1,2*n,2,x1,z1,nx1,nz1,x2,z2,nx2,nz2) + x1 = [0.0, 1.0, 1.0] + nx1 = [2.0/sqrt(5.0), 0.0, 0.0] + z1 = [1.0, -1.0, -1.0] + nz1 = [1.0/sqrt(5.0), -1.0, -1.0] + # + x2 = [1.0, 0.0, 0.0] + nx2 = [2.0/sqrt(5.0), 0.0, 0.0] + nz2 = [1.0/sqrt(5.0), -1.0, -1.0] + z2 = [-1.0, -1.0, -1.0] + # + return makespinobject(1,2*n,2,x1,z1,nx1,nz1,x2,z2,nx2,nz2) def makecube() : - x1 = [0.0, sqrt(2.0), sqrt (2.0)] - nx1 = [0.0, 1.0, 0.0] - z1 = [1.0, 1.0, -1.0] - nz1 = [1.0, 0.0, -1.0] - # - x2 = [sqrt(2.0), sqrt(2.0), 0.0] - nx2 = [0.0, 1.0, 0.0] - z2 = [1.0, -1.0, -1.0] - nz2 = [1.0, 0.0, -1.0] - # - return makespinobject(0,4,3,x1,z1,nx1,nz1,x2,z2,nx2,nz2) + x1 = [0.0, sqrt(2.0), sqrt (2.0)] + nx1 = [0.0, 1.0, 0.0] + z1 = [1.0, 1.0, -1.0] + nz1 = [1.0, 0.0, -1.0] + # + x2 = [sqrt(2.0), sqrt(2.0), 0.0] + nx2 = [0.0, 1.0, 0.0] + z2 = [1.0, -1.0, -1.0] + nz2 = [1.0, 0.0, -1.0] + # + return makespinobject(0,4,3,x1,z1,nx1,nz1,x2,z2,nx2,nz2) def makepyramid() : - x1 = [0.0, sqrt(2.0), 0.0] - nx1 = [2.0 / sqrt(5.0), 0.0, 0.0] - z1 = [1.0, -1.0, 0.0] - nz1 = [1.0 / sqrt(5.0), -1.0, 0.0] - # - x2 = [sqrt(2.0), 0.0, 0.0] - nx2 = [2.0 / sqrt(5.0), 0.0, 0.0] - z2 = [-1.0, -1.0, -1.0] - nz2 = [1.0/sqrt(5.0), -1.0, 0.0] - # - return makespinobject(0,4,3,x1,z1,nx1,nz1,x2,z2,nx2,nz2) + x1 = [0.0, sqrt(2.0), 0.0] + nx1 = [2.0 / sqrt(5.0), 0.0, 0.0] + z1 = [1.0, -1.0, 0.0] + nz1 = [1.0 / sqrt(5.0), -1.0, 0.0] + # + x2 = [sqrt(2.0), 0.0, 0.0] + nx2 = [2.0 / sqrt(5.0), 0.0, 0.0] + z2 = [-1.0, -1.0, -1.0] + nz2 = [1.0/sqrt(5.0), -1.0, 0.0] + # + return makespinobject(0,4,3,x1,z1,nx1,nz1,x2,z2,nx2,nz2) def makeobjects () : - cube = makecube() - sphere = makesphere (6) - cylinder = makecylinder (6) - cone = makecone (6) - pyramid = makepyramid () - # - odict = {} - odict ['cube'] = cube - odict ['pyramid'] = pyramid - odict ['sphere'] = sphere - odict ['cylinder'] = cylinder - odict ['cone'] = cone - odict ['diamond'] = cube - odict ['disk'] = sphere - # - return odict + cube = makecube() + sphere = makesphere (6) + cylinder = makecylinder (6) + cone = makecone (6) + pyramid = makepyramid () + # + odict = {} + odict ['cube'] = cube + odict ['pyramid'] = pyramid + odict ['sphere'] = sphere + odict ['cylinder'] = cylinder + odict ['cone'] = cone + odict ['diamond'] = cube + odict ['disk'] = sphere + # + return odict renderfuncs = [bgnpolygon, endpolygon] def putFunc (funcs) : - renderfuncs [:] = funcs + renderfuncs [:] = funcs def drawobject (obj) : - # - for patch in obj : - renderfuncs[0] () - vnarray (patch) - renderfuncs[1] () + # + for patch in obj : + renderfuncs[0] () + vnarray (patch) + renderfuncs[1] () diff --git a/demo/sgi/gl_panel/nurbs/nurbs.py b/demo/sgi/gl_panel/nurbs/nurbs.py index 686c3bd..c92cb46 100755 --- a/demo/sgi/gl_panel/nurbs/nurbs.py +++ b/demo/sgi/gl_panel/nurbs/nurbs.py @@ -1,6 +1,6 @@ #! /ufs/guido/bin/sgi/python -# Fancy NURBS demo. Require Z buffer and Panel Library. +# Fancy NURBS demo. Require Z buffer and Panel Library. from gl import * from GL import * @@ -11,186 +11,186 @@ import panel # # flags = trim_f, invis_f, cpvis_f, tpvis_f, axvis_f, freeze_f # -TRIM = 0 -VIS = 1 -CPVIS = 2 -TPVIS = 3 -AXVIS = 4 -FREEZE = 5 +TRIM = 0 +VIS = 1 +CPVIS = 2 +TPVIS = 3 +AXVIS = 4 +FREEZE = 5 flags = [0, 1, 0, 0, 0, 0] def draw_axis () : - cpack (0x0) - zero = (0.0, 0.0, 0.0) - # - one = (1.0, 0.0, 0.0) - smallline (zero, one) - cmov (1.0, 0.0, 0.0) - charstr ('x') - # - one = (0.0, 1.0, 0.0) - smallline (zero, one) - cmov (0.0, 1.0, 0.0) - charstr ('y') - # - one = (0.0, 0.0, 1.0) - smallline (zero, one) - cmov (0.0, 0.0, 1.0) - charstr ('z') + cpack (0x0) + zero = (0.0, 0.0, 0.0) + # + one = (1.0, 0.0, 0.0) + smallline (zero, one) + cmov (1.0, 0.0, 0.0) + charstr ('x') + # + one = (0.0, 1.0, 0.0) + smallline (zero, one) + cmov (0.0, 1.0, 0.0) + charstr ('y') + # + one = (0.0, 0.0, 1.0) + smallline (zero, one) + cmov (0.0, 0.0, 1.0) + charstr ('z') DELTA = 0.1 def cross (p) : - p0 = [p[0], p[1], p[2]] - p1 = [p[0], p[1], p[2]] - for i in range (0, 3) : - p0[i] = p0[i] + DELTA - p1[i] = p1[i] - DELTA - smallline (p0, p1) - p0[i] = p0[i] - DELTA - p1[i] = p1[i] + DELTA + p0 = [p[0], p[1], p[2]] + p1 = [p[0], p[1], p[2]] + for i in range (0, 3) : + p0[i] = p0[i] + DELTA + p1[i] = p1[i] - DELTA + smallline (p0, p1) + p0[i] = p0[i] - DELTA + p1[i] = p1[i] + DELTA def smallline (p0, p1) : - bgnline () - v3f (p0) - v3f (p1) - endline () + bgnline () + v3f (p0) + v3f (p1) + endline () def draw_pts (pnts, color) : - linewidth (2) - cpack (color) - for i in pnts : - cross (i) + linewidth (2) + cpack (color) + for i in pnts : + cross (i) def init_windows(): - foreground() - wid = winopen('nurbs') - wintitle('NURBS Surface') - doublebuffer() - RGBmode() - gconfig() - lsetdepth(0x000, 0x7fffff) - zbuffer( TRUE ) + foreground() + wid = winopen('nurbs') + wintitle('NURBS Surface') + doublebuffer() + RGBmode() + gconfig() + lsetdepth(0x000, 0x7fffff) + zbuffer( TRUE ) def init_view(): - mmode(MPROJECTION) - ortho( -5., 5., -5., 5., -5., 5. ) - # - mmode(MVIEWING) - loadmatrix(idmat) - # - lmbind(MATERIAL, 1) + mmode(MPROJECTION) + ortho( -5., 5., -5., 5., -5., 5. ) + # + mmode(MVIEWING) + loadmatrix(idmat) + # + lmbind(MATERIAL, 1) def set_scene(flags): - # - lmbind(MATERIAL, 0) - RGBcolor(150,150,150) - lmbind(MATERIAL, 1) - clear() - zclear() - # - if not flags[FREEZE] : - rotate( 100, 'y' ) - rotate( 100, 'z' ) + # + lmbind(MATERIAL, 0) + RGBcolor(150,150,150) + lmbind(MATERIAL, 1) + clear() + zclear() + # + if not flags[FREEZE] : + rotate( 100, 'y' ) + rotate( 100, 'z' ) def draw_trim_surface(flags): - pnts = ctlpoints - if flags[VIS] : - bgnsurface() - nurbssurface(surfknots,surfknots,pnts,ORDER,ORDER,N_XYZ) - if flags[TRIM]: - bgntrim() - nurbscurve(trimknots,trimpoints,ORDER-1,N_STW) - endtrim() - endsurface() - # - if flags[CPVIS] : - for i in pnts : - draw_pts (i, RED) - # - if flags[TPVIS] : - tpts = trimpoints - draw_pts (tpts, YELLOW) - # - if flags[AXVIS] : - draw_axis () - # - swapbuffers() + pnts = ctlpoints + if flags[VIS] : + bgnsurface() + nurbssurface(surfknots,surfknots,pnts,ORDER,ORDER,N_XYZ) + if flags[TRIM]: + bgntrim() + nurbscurve(trimknots,trimpoints,ORDER-1,N_STW) + endtrim() + endsurface() + # + if flags[CPVIS] : + for i in pnts : + draw_pts (i, RED) + # + if flags[TPVIS] : + tpts = trimpoints + draw_pts (tpts, YELLOW) + # + if flags[AXVIS] : + draw_axis () + # + swapbuffers() def make_lights(): - lmdef(DEFLMODEL,1,[]) - lmdef(DEFLIGHT,1,[]) - # - # define material #1 - # - a = [] - a = a + [EMISSION, 0.0, 0.0, 0.0] - a = a + [AMBIENT, 0.1, 0.1, 0.1] - a = a + [DIFFUSE, 0.6, 0.3, 0.3] - a = a + [SPECULAR, 0.0, 0.6, 0.0] - a = a + [SHININESS, 2.0] - a = a + [LMNULL] - lmdef(DEFMATERIAL, 1, a) - # - # turn on lighting - # - lmbind(LIGHT0, 1) - lmbind(LMODEL, 1) + lmdef(DEFLMODEL,1,[]) + lmdef(DEFLIGHT,1,[]) + # + # define material #1 + # + a = [] + a = a + [EMISSION, 0.0, 0.0, 0.0] + a = a + [AMBIENT, 0.1, 0.1, 0.1] + a = a + [DIFFUSE, 0.6, 0.3, 0.3] + a = a + [SPECULAR, 0.0, 0.6, 0.0] + a = a + [SHININESS, 2.0] + a = a + [LMNULL] + lmdef(DEFMATERIAL, 1, a) + # + # turn on lighting + # + lmbind(LIGHT0, 1) + lmbind(LMODEL, 1) def main(): - init_windows() - make_lights() - init_view() - # - panel.needredraw() - panels = panel.defpanellist('nurbs.s') - p = panels[0] - # - def cbtrim (a) : - flags[TRIM:TRIM+1] = [int (a.val)] - p.trim.upfunc = cbtrim - # - def cbquit (a) : - import sys - sys.exit (1) - p.quit.upfunc = cbquit - # - def cbmotion (a) : - flags[FREEZE:FREEZE+1] = [int (a.val)] - p.motion.upfunc = cbmotion - # - def cbxyzaxis (a) : - flags[AXVIS:AXVIS+1] = [int (a.val)] - p.xyzaxis.upfunc = cbxyzaxis - # - def cbtrimpnts (a) : - flags[TPVIS:TPVIS+1] = [int (a.val)] - p.trimpnts.upfunc = cbtrimpnts - # - def cbcntlpnts (a) : - flags[CPVIS:CPVIS+1] = [int (a.val)] - p.cntlpnts.upfunc = cbcntlpnts - # - def cbnurb (a) : - flags[VIS:VIS+1] = [int (a.val)] - p.nurb.upfunc = cbnurb - # - set_scene(flags) - setnurbsproperty( N_ERRORCHECKING, 1.0 ) - setnurbsproperty( N_PIXEL_TOLERANCE, 50.0 ) - draw_trim_surface(flags) - # - while 1: - act = panel.dopanel() - # - wid = panel.userredraw () - if wid : - winset (wid) - reshapeviewport() - set_scene(flags) - draw_trim_surface(flags) - # - set_scene(flags) - draw_trim_surface(flags) + init_windows() + make_lights() + init_view() + # + panel.needredraw() + panels = panel.defpanellist('nurbs.s') + p = panels[0] + # + def cbtrim (a) : + flags[TRIM:TRIM+1] = [int (a.val)] + p.trim.upfunc = cbtrim + # + def cbquit (a) : + import sys + sys.exit (1) + p.quit.upfunc = cbquit + # + def cbmotion (a) : + flags[FREEZE:FREEZE+1] = [int (a.val)] + p.motion.upfunc = cbmotion + # + def cbxyzaxis (a) : + flags[AXVIS:AXVIS+1] = [int (a.val)] + p.xyzaxis.upfunc = cbxyzaxis + # + def cbtrimpnts (a) : + flags[TPVIS:TPVIS+1] = [int (a.val)] + p.trimpnts.upfunc = cbtrimpnts + # + def cbcntlpnts (a) : + flags[CPVIS:CPVIS+1] = [int (a.val)] + p.cntlpnts.upfunc = cbcntlpnts + # + def cbnurb (a) : + flags[VIS:VIS+1] = [int (a.val)] + p.nurb.upfunc = cbnurb + # + set_scene(flags) + setnurbsproperty( N_ERRORCHECKING, 1.0 ) + setnurbsproperty( N_PIXEL_TOLERANCE, 50.0 ) + draw_trim_surface(flags) + # + while 1: + act = panel.dopanel() + # + wid = panel.userredraw () + if wid : + winset (wid) + reshapeviewport() + set_scene(flags) + draw_trim_surface(flags) + # + set_scene(flags) + draw_trim_surface(flags) main() diff --git a/demo/sgi/gl_panel/nurbs/nurbsdata.py b/demo/sgi/gl_panel/nurbs/nurbsdata.py index ed7e705..9a3f09e 100644 --- a/demo/sgi/gl_panel/nurbs/nurbsdata.py +++ b/demo/sgi/gl_panel/nurbs/nurbsdata.py @@ -25,58 +25,58 @@ surfknots = [-1, -1, -1, -1, 1, 1, 1, 1] # list of list of control points # def make_ctlpoints(): - c = [] - # - ci = [] - ci.append(-2.5, -3.7, 1.0) - ci.append(-1.5, -3.7, 3.0) - ci.append(1.5, -3.7, -2.5) - ci.append(2.5, -3.7, -0.75) - c.append(ci) - # - ci = [] - ci.append(-2.5, -2.0, 3.0) - ci.append(-1.5, -2.0, 4.0) - ci.append(1.5, -2.0, -3.0) - ci.append(2.5, -2.0, 0.0) - c.append(ci) - # - ci = [] - ci.append(-2.5, 2.0, 1.0) - ci.append(-1.5, 2.0, 0.0) - ci.append(1.5, 2.0, -1.0) - ci.append(2.5, 2.0, 2.0) - c.append(ci) - # - ci = [] - ci.append(-2.5, 2.7, 1.25) - ci.append(-1.5, 2.7, 0.1) - ci.append(1.5, 2.7, -0.6) - ci.append(2.5, 2.7, 0.2) - c.append(ci) - # - return c + c = [] + # + ci = [] + ci.append(-2.5, -3.7, 1.0) + ci.append(-1.5, -3.7, 3.0) + ci.append(1.5, -3.7, -2.5) + ci.append(2.5, -3.7, -0.75) + c.append(ci) + # + ci = [] + ci.append(-2.5, -2.0, 3.0) + ci.append(-1.5, -2.0, 4.0) + ci.append(1.5, -2.0, -3.0) + ci.append(2.5, -2.0, 0.0) + c.append(ci) + # + ci = [] + ci.append(-2.5, 2.0, 1.0) + ci.append(-1.5, 2.0, 0.0) + ci.append(1.5, 2.0, -1.0) + ci.append(2.5, 2.0, 2.0) + c.append(ci) + # + ci = [] + ci.append(-2.5, 2.7, 1.25) + ci.append(-1.5, 2.7, 0.1) + ci.append(1.5, 2.7, -0.6) + ci.append(2.5, 2.7, 0.2) + c.append(ci) + # + return c ctlpoints = make_ctlpoints () # # trim knots # -trimknots = [0., 0., 0., 1., 1., 2., 2., 3., 3., 4., 4., 4.] +trimknots = [0., 0., 0., 1., 1., 2., 2., 3., 3., 4., 4., 4.] def make_trimpoints(): - c = [] - # - c.append(1.0, 0.0, 1.0) - c.append(1.0, 1.0, 1.0) - c.append(0.0, 2.0, 2.0) - c.append(-1.0, 1.0, 1.0) - c.append(-1.0, 0.0, 1.0) - c.append(-1.0, -1.0, 1.0) - c.append(0.0, -2.0, 2.0) - c.append(1.0, -1.0, 1.0) - c.append(1.0, 0.0, 1.0) - # - return c + c = [] + # + c.append(1.0, 0.0, 1.0) + c.append(1.0, 1.0, 1.0) + c.append(0.0, 2.0, 2.0) + c.append(-1.0, 1.0, 1.0) + c.append(-1.0, 0.0, 1.0) + c.append(-1.0, -1.0, 1.0) + c.append(0.0, -2.0, 2.0) + c.append(1.0, -1.0, 1.0) + c.append(1.0, 0.0, 1.0) + # + return c trimpoints = make_trimpoints() diff --git a/demo/sgi/gl_panel/twoview/block.py b/demo/sgi/gl_panel/twoview/block.py index 9ac518d..a40c8e9 100644 --- a/demo/sgi/gl_panel/twoview/block.py +++ b/demo/sgi/gl_panel/twoview/block.py @@ -7,67 +7,67 @@ from GL import MATERIAL # Arguments are the material indices (0 = don't call lmbind) # def block(m_front, m_back, m_left, m_right, m_top, m_bottom): - # - # Distances defining the sides - # - x_left = -1.0 - x_right = 1.0 - y_top = 1.0 - y_bottom = -1.0 - z_front = 1.0 - z_back = -1.0 - # - # Top surface points: A, B, C, D - # - A = x_right, y_top, z_front - B = x_right, y_top, z_back - C = x_left, y_top, z_back - D = x_left, y_top, z_front - # - # Bottom surface points: E, F, G, H - # - E = x_right, y_bottom, z_front - F = x_right, y_bottom, z_back - G = x_left, y_bottom, z_back - H = x_left, y_bottom, z_front - # - # Draw front face - # - if m_front: lmbind(MATERIAL, m_front) - n3f(0.0, 0.0, 1.0) - face(H, E, A, D) - # - # Draw back face - # - if m_back: lmbind(MATERIAL, m_back) - n3f(0.0, 0.0, -1.0) - face(G, F, B, C) - # - # Draw left face - # - if m_left: lmbind(MATERIAL, m_left) - n3f(-1.0, 0.0, 0.0) - face(G, H, D, C) - # - # Draw right face - # - if m_right: lmbind(MATERIAL, m_right) - n3f(1.0, 0.0, 0.0) - face(F, E, A, B) - # - # Draw top face - # - if m_top: lmbind(MATERIAL, m_top) - n3f(0.0, 1.0, 0.0) - face(A, B, C, D) - # - # Draw bottom face - # - if m_bottom: lmbind(MATERIAL, m_bottom) - n3f(0.0, -1.0, 0.0) - face(E, F, G, H) + # + # Distances defining the sides + # + x_left = -1.0 + x_right = 1.0 + y_top = 1.0 + y_bottom = -1.0 + z_front = 1.0 + z_back = -1.0 + # + # Top surface points: A, B, C, D + # + A = x_right, y_top, z_front + B = x_right, y_top, z_back + C = x_left, y_top, z_back + D = x_left, y_top, z_front + # + # Bottom surface points: E, F, G, H + # + E = x_right, y_bottom, z_front + F = x_right, y_bottom, z_back + G = x_left, y_bottom, z_back + H = x_left, y_bottom, z_front + # + # Draw front face + # + if m_front: lmbind(MATERIAL, m_front) + n3f(0.0, 0.0, 1.0) + face(H, E, A, D) + # + # Draw back face + # + if m_back: lmbind(MATERIAL, m_back) + n3f(0.0, 0.0, -1.0) + face(G, F, B, C) + # + # Draw left face + # + if m_left: lmbind(MATERIAL, m_left) + n3f(-1.0, 0.0, 0.0) + face(G, H, D, C) + # + # Draw right face + # + if m_right: lmbind(MATERIAL, m_right) + n3f(1.0, 0.0, 0.0) + face(F, E, A, B) + # + # Draw top face + # + if m_top: lmbind(MATERIAL, m_top) + n3f(0.0, 1.0, 0.0) + face(A, B, C, D) + # + # Draw bottom face + # + if m_bottom: lmbind(MATERIAL, m_bottom) + n3f(0.0, -1.0, 0.0) + face(E, F, G, H) def face(points): - bgnpolygon() - varray(points) - endpolygon() + bgnpolygon() + varray(points) + endpolygon() diff --git a/demo/sgi/gl_panel/twoview/twoview.py b/demo/sgi/gl_panel/twoview/twoview.py index eea7c75..79c664f 100755 --- a/demo/sgi/gl_panel/twoview/twoview.py +++ b/demo/sgi/gl_panel/twoview/twoview.py @@ -1,7 +1,7 @@ #! /ufs/guido/bin/sgi/python # A demo of GL's viewing transformations, showing two views on one scene. -# Requires the NASA AMES Panel Library. Requires Z buffer. +# Requires the NASA AMES Panel Library. Requires Z buffer. from gl import * from GL import * @@ -13,383 +13,383 @@ far = 1000.0 near = 100.0 def main(): - foreground() - # - keepaspect(1, 1) - prefposition(10, 610, 10, 610) - obswid = winopen('Observer View') - doublebuffer() - RGBmode() - gconfig() - # - keepaspect(1, 1) - prefposition(10, 310, 650, 950) - topwid = winopen('Top View') - doublebuffer() - RGBmode() - gconfig() - # - panels = panel.defpanellist('observer.s') - panels = panels + panel.defpanellist('camera.s') - panels = panels + panel.defpanellist('topview.s') - # - p = panels[0] - q = panels[1] - r = panels[2] - # - p.farclip = q.farclip - p.nearclip = q.nearclip - p.zoom = q.zoom - p.quitbutton = q.quitbutton - # - p.xpos = r.xpos - p.zpos = r.zpos - p.direction = r.direction - # - p.direction.winds = 1.0 # allow full rotation - # - def quit(act): - import sys - sys.exit(0) - p.quitbutton.downfunc = quit - # - p.left.back = p - p.fast_left.back = p - p.right.back = p - p.fast_right.back = p - p.forward.back = p - p.fast_forward.back = p - p.reverse.back = p - p.fast_reverse.back = p - p.up.back = p - p.down.back = p - # - p.left.activefunc = left - p.fast_left.activefunc = fast_left - p.right.activefunc = right - p.fast_right.activefunc = fast_right - p.forward.activefunc = forward - p.fast_forward.activefunc = fast_forward - p.reverse.activefunc = reverse - p.fast_reverse.activefunc = fast_reverse - p.up.activefunc = up - p.down.activefunc = down - # - makeobjects() - # - drawall(p, obswid, topwid) - panel.needredraw() - while 1: - act = panel.dopanel() - if panel.userredraw() or act: - drawall(p, obswid, topwid) + foreground() + # + keepaspect(1, 1) + prefposition(10, 610, 10, 610) + obswid = winopen('Observer View') + doublebuffer() + RGBmode() + gconfig() + # + keepaspect(1, 1) + prefposition(10, 310, 650, 950) + topwid = winopen('Top View') + doublebuffer() + RGBmode() + gconfig() + # + panels = panel.defpanellist('observer.s') + panels = panels + panel.defpanellist('camera.s') + panels = panels + panel.defpanellist('topview.s') + # + p = panels[0] + q = panels[1] + r = panels[2] + # + p.farclip = q.farclip + p.nearclip = q.nearclip + p.zoom = q.zoom + p.quitbutton = q.quitbutton + # + p.xpos = r.xpos + p.zpos = r.zpos + p.direction = r.direction + # + p.direction.winds = 1.0 # allow full rotation + # + def quit(act): + import sys + sys.exit(0) + p.quitbutton.downfunc = quit + # + p.left.back = p + p.fast_left.back = p + p.right.back = p + p.fast_right.back = p + p.forward.back = p + p.fast_forward.back = p + p.reverse.back = p + p.fast_reverse.back = p + p.up.back = p + p.down.back = p + # + p.left.activefunc = left + p.fast_left.activefunc = fast_left + p.right.activefunc = right + p.fast_right.activefunc = fast_right + p.forward.activefunc = forward + p.fast_forward.activefunc = fast_forward + p.reverse.activefunc = reverse + p.fast_reverse.activefunc = fast_reverse + p.up.activefunc = up + p.down.activefunc = down + # + makeobjects() + # + drawall(p, obswid, topwid) + panel.needredraw() + while 1: + act = panel.dopanel() + if panel.userredraw() or act: + drawall(p, obswid, topwid) def left(a): - doturn(a.back, 0.01) + doturn(a.back, 0.01) def fast_left(a): - doturn(a.back, 0.1) + doturn(a.back, 0.1) def right(a): - doturn(a.back, -0.01) + doturn(a.back, -0.01) def fast_right(a): - doturn(a.back, -0.1) + doturn(a.back, -0.1) def doturn(p, angle): - alpha = lookangle(p) + angle - # Reverse the following assignment: - # alpha = pi*1.5 - p.direction.val*2.0*pi - val = (pi*1.5 - alpha) / 2.0 / pi - while val < 0.0: val = val + 1.0 - while val > 1.0: val = val - 1.0 - p.direction.val = val - p.direction.fixact() + alpha = lookangle(p) + angle + # Reverse the following assignment: + # alpha = pi*1.5 - p.direction.val*2.0*pi + val = (pi*1.5 - alpha) / 2.0 / pi + while val < 0.0: val = val + 1.0 + while val > 1.0: val = val - 1.0 + p.direction.val = val + p.direction.fixact() def forward(a): - dostep(a.back, 1.0) + dostep(a.back, 1.0) def fast_forward(a): - dostep(a.back, 10.0) + dostep(a.back, 10.0) def reverse(a): - dostep(a.back, -1.0) + dostep(a.back, -1.0) def fast_reverse(a): - dostep(a.back, -10.0) + dostep(a.back, -10.0) def dostep(p, step): - x, y, z = observerpos(p) - alpha = lookangle(p) - x = x + step*cos(alpha) - z = z - step*sin(alpha) - # Reverse the following assignments: - # x = 2.0 * p.xpos.val * near - near - # z = near - 2.0 * p.zpos.val * near - p.xpos.val = (x + near) / 2.0 / near - p.zpos.val = - (z - near) / 2.0 / near - p.xpos.fixact() - p.zpos.fixact() + x, y, z = observerpos(p) + alpha = lookangle(p) + x = x + step*cos(alpha) + z = z - step*sin(alpha) + # Reverse the following assignments: + # x = 2.0 * p.xpos.val * near - near + # z = near - 2.0 * p.zpos.val * near + p.xpos.val = (x + near) / 2.0 / near + p.zpos.val = - (z - near) / 2.0 / near + p.xpos.fixact() + p.zpos.fixact() def up(a): - doup(a.back, 0.2) + doup(a.back, 0.2) def down(a): - doup(a.back, -0.2) + doup(a.back, -0.2) def doup(p, step): - x, y, z = observerpos(p) - y = y + step - # Reverse: - # y = p.ypos.val * near - p.ypos.val = y/near - p.ypos.fixact() + x, y, z = observerpos(p) + y = y + step + # Reverse: + # y = p.ypos.val * near + p.ypos.val = y/near + p.ypos.fixact() def drawall(p, obswid, topwid): - # - winset(obswid) - obsview(p) - drawscene() - swapbuffers() - # - winset(topwid) - topview(p) - drawscene() - drawobserver(p) - swapbuffers() + # + winset(obswid) + obsview(p) + drawscene() + swapbuffers() + # + winset(topwid) + topview(p) + drawscene() + drawobserver(p) + swapbuffers() def drawobserver(p): - x, y, z = observerpos(p) - alpha = lookangle(p) - fov = 2.0 + 1798.0 * p.zoom.val - beta = fov*pi/3600.0 # Half fov, expressed in radians - # - c3i(0, 255, 0) - # - move(x, y, z) - x1 = x + inf*cos(alpha+beta) - y1 = y - z1 = z - inf*sin(alpha+beta) - draw(x1, y1, z1) - # - move(x, y, z) - x1 = x + inf*cos(alpha-beta) - y1 = y - z1 = z - inf*sin(alpha-beta) - draw(x1, y1, z1) + x, y, z = observerpos(p) + alpha = lookangle(p) + fov = 2.0 + 1798.0 * p.zoom.val + beta = fov*pi/3600.0 # Half fov, expressed in radians + # + c3i(0, 255, 0) + # + move(x, y, z) + x1 = x + inf*cos(alpha+beta) + y1 = y + z1 = z - inf*sin(alpha+beta) + draw(x1, y1, z1) + # + move(x, y, z) + x1 = x + inf*cos(alpha-beta) + y1 = y + z1 = z - inf*sin(alpha-beta) + draw(x1, y1, z1) def observerlookat(p): - x, y, z = observerpos(p) - alpha = lookangle(p) - return x, y, z, x+near*cos(alpha), y, z-near*sin(alpha), 0 + x, y, z = observerpos(p) + alpha = lookangle(p) + return x, y, z, x+near*cos(alpha), y, z-near*sin(alpha), 0 def observerpos(p): - x = 2.0 * p.xpos.val * near - near - y = p.ypos.val * near - z = near - 2.0 * p.zpos.val * near - return x, y, z + x = 2.0 * p.xpos.val * near - near + y = p.ypos.val * near + z = near - 2.0 * p.zpos.val * near + return x, y, z def lookangle(p): - return pi*1.5 - p.direction.val*2.0*pi + return pi*1.5 - p.direction.val*2.0*pi idmat = 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1 def topview(p): - mmode(MVIEWING) - ortho(-far, far, -far, far, far, -far) - loadmatrix(idmat) - rotate(900, 'x') + mmode(MVIEWING) + ortho(-far, far, -far, far, far, -far) + loadmatrix(idmat) + rotate(900, 'x') def obsview(p): - fov = 2.0 + 1798.0 * p.zoom.val - nearclip = p.nearclip.val * 10.0 - farclip = p.farclip.val * 10.0*far - aspectratio = 1.0 - mmode(MVIEWING) - perspective(int(fov), aspectratio, nearclip, farclip) - loadmatrix(idmat) - lookat(observerlookat(p)) + fov = 2.0 + 1798.0 * p.zoom.val + nearclip = p.nearclip.val * 10.0 + farclip = p.farclip.val * 10.0*far + aspectratio = 1.0 + mmode(MVIEWING) + perspective(int(fov), aspectratio, nearclip, farclip) + loadmatrix(idmat) + lookat(observerlookat(p)) def drawscene(): - # - # clear window - # - c3i(0, 0, 0) - clear() - # - # turn on z buffering and clear it - # - zbuffer(TRUE) - zclear() - # - # dark blue sky (depending on your gamma value!) - # - c3i(0, 0, 150) - callobj(41) - # - # bright red near and far units circle - # (use rotate since circ() always draws in x-y plane) - # - c3i(255, 0, 0) - pushmatrix() - rotate(900, 'x') - circ(0.0, 0.0, near) - circ(0.0, 0.0, far) - popmatrix() - # - # bright white striping - # - c3i(255, 255, 200) - callobj(42) - # - # building (does its own colors) - # - building() - # - # some other objects - # - dice() + # + # clear window + # + c3i(0, 0, 0) + clear() + # + # turn on z buffering and clear it + # + zbuffer(TRUE) + zclear() + # + # dark blue sky (depending on your gamma value!) + # + c3i(0, 0, 150) + callobj(41) + # + # bright red near and far units circle + # (use rotate since circ() always draws in x-y plane) + # + c3i(255, 0, 0) + pushmatrix() + rotate(900, 'x') + circ(0.0, 0.0, near) + circ(0.0, 0.0, far) + popmatrix() + # + # bright white striping + # + c3i(255, 255, 200) + callobj(42) + # + # building (does its own colors) + # + building() + # + # some other objects + # + dice() def makeobjects(): - # - # sky object - # - makeobj(41) - pmv(-inf, 0.0, -far) - pdr(inf, 0.0, -far) - pdr(inf, inf, -far) - pdr(-inf, inf, -far) - pclos() - closeobj() - # - # road stripes object - # - makeobj(42) - stripes() - closeobj() - # - # lighting model definitions - # - deflight() + # + # sky object + # + makeobj(41) + pmv(-inf, 0.0, -far) + pdr(inf, 0.0, -far) + pdr(inf, inf, -far) + pdr(-inf, inf, -far) + pclos() + closeobj() + # + # road stripes object + # + makeobj(42) + stripes() + closeobj() + # + # lighting model definitions + # + deflight() def stripes(): - # - # left line - # - botrect(-11, -10, far, -far) - # - # right line - # - botrect(10, 11, far, -far) - # - # center lines - # - z = far - while z > -far: - botrect(-0.5, 0.5, z, z - 4.0) - z = z - 10.0 + # + # left line + # + botrect(-11, -10, far, -far) + # + # right line + # + botrect(10, 11, far, -far) + # + # center lines + # + z = far + while z > -far: + botrect(-0.5, 0.5, z, z - 4.0) + z = z - 10.0 def dice(): - from block import block - uselight() - pushmatrix() - translate(0.0, 1.0, -20.0) - rotate(200, 'y') - block(1, 0, 0, 0, 0, 0) - translate(1.0, 0.0, 3.0) - rotate(500, 'y') - block(2, 0, 0, 0, 0, 0) - popmatrix() + from block import block + uselight() + pushmatrix() + translate(0.0, 1.0, -20.0) + rotate(200, 'y') + block(1, 0, 0, 0, 0, 0) + translate(1.0, 0.0, 3.0) + rotate(500, 'y') + block(2, 0, 0, 0, 0, 0) + popmatrix() def deflight(): - # Material for first die (red) - lmdef(DEFMATERIAL, 1, (DIFFUSE, 1.0, 0.0, 0.0)) - # Material for second die (green) - lmdef(DEFMATERIAL, 2, (DIFFUSE, 0.0, 1.0, 0.0)) - # First light source (default: white, from front) - lmdef(DEFLIGHT, 1, ()) - # Second light source (red, from back) - lmdef(DEFLIGHT, 2, (POSITION, 0.0, 1.0, -1.0, 0.0)) - lmdef(DEFLIGHT, 2, (LCOLOR, 1.0, 0.0, 0.0)) - # Lighting model - lmdef(DEFLMODEL, 1, (AMBIENT, 0.0, 0.0, 1.0)) + # Material for first die (red) + lmdef(DEFMATERIAL, 1, (DIFFUSE, 1.0, 0.0, 0.0)) + # Material for second die (green) + lmdef(DEFMATERIAL, 2, (DIFFUSE, 0.0, 1.0, 0.0)) + # First light source (default: white, from front) + lmdef(DEFLIGHT, 1, ()) + # Second light source (red, from back) + lmdef(DEFLIGHT, 2, (POSITION, 0.0, 1.0, -1.0, 0.0)) + lmdef(DEFLIGHT, 2, (LCOLOR, 1.0, 0.0, 0.0)) + # Lighting model + lmdef(DEFLMODEL, 1, (AMBIENT, 0.0, 0.0, 1.0)) def uselight(): - lmbind(LIGHT0, 1) - lmbind(LIGHT1, 2) - lmbind(LMODEL, 1) - # (materials are bound later) + lmbind(LIGHT0, 1) + lmbind(LIGHT1, 2) + lmbind(LMODEL, 1) + # (materials are bound later) def building(): - # - c3i(0, 255, 255) - # - # house bounding coordinates - # - x1 = 20.0 - x1a = 25.0 - x2 = 30.0 - y1 = 0.0 - y2 = 15.0 - y2a = 20.0 - z1 = -40.0 - z2 = -55.0 - # - # door y and z coordinates - # - dy1 = 0.0 - dy2 = 4.0 - dz1 = -45.0 - dz2 = -47.0 - # - # front side (seen from origin) - # - A1 = (x1, y1, z1) - B1 = (x2, y1, z1) - C1 = (x2, y2, z1) - D1 = (x1a, y2a, z1) - E1 = (x1, y2, z1) - # - # back size - # - A2 = (x1, y1, z2) - B2 = (x2, y1, z2) - C2 = (x2, y2, z2) - D2 = (x1a, y2a, z2) - E2 = (x1, y2, z2) - # - # door in the left side - # - P = x1, dy1, dz2 - Q = x1, dy2, dz2 - R = x1, dy2, dz1 - S = x1, dy1, dz1 - # - # draw it - # - concave(TRUE) - c3i(255, 0, 0) - face(A1, B1, C1, D1, E1) - c3i(127, 127, 0) - face(A1, E1, E2, A2, P, Q, R, S) - c3i(0, 255, 0) - face(E1, D1, D2, E2) - c3i(0, 127, 127) - face(D1, C1, C2, D2) - c3i(0, 0, 255) - face(C1, B1, B2, C2) - c3i(127, 0, 127) - face(E2, D2, C2, B2, A2) - concave(FALSE) + # + c3i(0, 255, 255) + # + # house bounding coordinates + # + x1 = 20.0 + x1a = 25.0 + x2 = 30.0 + y1 = 0.0 + y2 = 15.0 + y2a = 20.0 + z1 = -40.0 + z2 = -55.0 + # + # door y and z coordinates + # + dy1 = 0.0 + dy2 = 4.0 + dz1 = -45.0 + dz2 = -47.0 + # + # front side (seen from origin) + # + A1 = (x1, y1, z1) + B1 = (x2, y1, z1) + C1 = (x2, y2, z1) + D1 = (x1a, y2a, z1) + E1 = (x1, y2, z1) + # + # back size + # + A2 = (x1, y1, z2) + B2 = (x2, y1, z2) + C2 = (x2, y2, z2) + D2 = (x1a, y2a, z2) + E2 = (x1, y2, z2) + # + # door in the left side + # + P = x1, dy1, dz2 + Q = x1, dy2, dz2 + R = x1, dy2, dz1 + S = x1, dy1, dz1 + # + # draw it + # + concave(TRUE) + c3i(255, 0, 0) + face(A1, B1, C1, D1, E1) + c3i(127, 127, 0) + face(A1, E1, E2, A2, P, Q, R, S) + c3i(0, 255, 0) + face(E1, D1, D2, E2) + c3i(0, 127, 127) + face(D1, C1, C2, D2) + c3i(0, 0, 255) + face(C1, B1, B2, C2) + c3i(127, 0, 127) + face(E2, D2, C2, B2, A2) + concave(FALSE) def face(points): - bgnpolygon() - varray(points) - endpolygon() + bgnpolygon() + varray(points) + endpolygon() # draw a rectangle at y=0.0 # def botrect(x1, x2, z1, z2): - polf(x1, 0.0, z1, x2, 0.0, z1, x2, 0.0, z2, x1, 0.0, z2) + polf(x1, 0.0, z1, x2, 0.0, z1, x2, 0.0, z2, x1, 0.0, z2) main() diff --git a/demo/stdwin/wdiff.py b/demo/stdwin/wdiff.py index bc005f8..389af63 100755 --- a/demo/stdwin/wdiff.py +++ b/demo/stdwin/wdiff.py @@ -4,17 +4,17 @@ # NB: This uses undocumented window classing modules. # TO DO: -# - faster update after moving/copying one file -# - diff flags (-b, etc.) should be global or maintained per window -# - use a few fixed windows instead of creating new ones all the time -# - ways to specify patterns to skip -# (best by pointing at a file and clicking a special menu entry!) -# - add rcsdiff menu commands -# - add a way to view status of selected files without opening them -# - add a way to diff two files with different names -# - add a way to rename files -# - keep backups of overwritten/deleted files -# - a way to mark specified files as uninteresting for dircmp +# - faster update after moving/copying one file +# - diff flags (-b, etc.) should be global or maintained per window +# - use a few fixed windows instead of creating new ones all the time +# - ways to specify patterns to skip +# (best by pointing at a file and clicking a special menu entry!) +# - add rcsdiff menu commands +# - add a way to view status of selected files without opening them +# - add a way to diff two files with different names +# - add a way to rename files +# - keep backups of overwritten/deleted files +# - a way to mark specified files as uninteresting for dircmp import sys import posix @@ -42,439 +42,439 @@ skiplist = ['RCS', '.Amake', 'tags', '.', '..'] def anydiff(a, b, flags): # Display differences between any two objects - print 'diff', flags, a, b - if path.isdir(a) and path.isdir(b): - w = dirdiff(a, b, flags) - else: - w = filediff(a, b, flags) - addstatmenu(w, [a, b]) - w.original_close = w.close - w.close = close_dirwin - return w + print 'diff', flags, a, b + if path.isdir(a) and path.isdir(b): + w = dirdiff(a, b, flags) + else: + w = filediff(a, b, flags) + addstatmenu(w, [a, b]) + w.original_close = w.close + w.close = close_dirwin + return w def close_dirwin(w): - close_subwindows(w, (), 0) - w.original_close(w) + close_subwindows(w, (), 0) + w.original_close(w) def filediff(a, b, flags): # Display differences between two text files - diffcmd = 'diff' - if flags: diffcmd = diffcmd + mkarg(flags) - diffcmd = diffcmd + mkarg(a) + mkarg(b) - difftext = commands.getoutput(diffcmd) - return textwin.open_readonly(mktitle(a, b), difftext) + diffcmd = 'diff' + if flags: diffcmd = diffcmd + mkarg(flags) + diffcmd = diffcmd + mkarg(a) + mkarg(b) + difftext = commands.getoutput(diffcmd) + return textwin.open_readonly(mktitle(a, b), difftext) def dirdiff(a, b, flags): # Display differences between two directories - data = diffdata(a, b, flags) - w = tablewin.open(mktitle(a, b), data) - w.flags = flags - w.a = a - w.b = b - addviewmenu(w) - addactionmenu(w) - return w + data = diffdata(a, b, flags) + w = tablewin.open(mktitle(a, b), data) + w.flags = flags + w.a = a + w.b = b + addviewmenu(w) + addactionmenu(w) + return w def diffdata(a, b, flags): # Compute directory differences. - # - a_only = [('A only:', header_action), ('', header_action)] - b_only = [('B only:', header_action), ('', header_action)] - ab_diff = [('A <> B:', header_action), ('', header_action)] - ab_same = [('A == B:', header_action), ('', header_action)] - data = [a_only, b_only, ab_diff, ab_same] - # - a_list = dircache.listdir(a)[:] - b_list = dircache.listdir(b)[:] - dircache.annotate(a, a_list) - dircache.annotate(b, b_list) - a_list.sort() - b_list.sort() - # - for x in a_list: - if x in ['./', '../']: - pass - elif x not in b_list: - a_only.append(x, a_only_action) - else: - ax = path.cat(a, x) - bx = path.cat(b, x) - if path.isdir(ax) and path.isdir(bx): - if flags = '-r': - same = dircmp(ax, bx) - else: - same = 0 - else: - try: - same = cmp.cmp(ax, bx) - except posix.error: - same = 0 - if same: - ab_same.append(x, ab_same_action) - else: - ab_diff.append(x, ab_diff_action) - # - for x in b_list: - if x in ['./', '../']: - pass - elif x not in a_list: - b_only.append(x, b_only_action) - # - return data + # + a_only = [('A only:', header_action), ('', header_action)] + b_only = [('B only:', header_action), ('', header_action)] + ab_diff = [('A <> B:', header_action), ('', header_action)] + ab_same = [('A == B:', header_action), ('', header_action)] + data = [a_only, b_only, ab_diff, ab_same] + # + a_list = dircache.listdir(a)[:] + b_list = dircache.listdir(b)[:] + dircache.annotate(a, a_list) + dircache.annotate(b, b_list) + a_list.sort() + b_list.sort() + # + for x in a_list: + if x in ['./', '../']: + pass + elif x not in b_list: + a_only.append(x, a_only_action) + else: + ax = path.cat(a, x) + bx = path.cat(b, x) + if path.isdir(ax) and path.isdir(bx): + if flags = '-r': + same = dircmp(ax, bx) + else: + same = 0 + else: + try: + same = cmp.cmp(ax, bx) + except posix.error: + same = 0 + if same: + ab_same.append(x, ab_same_action) + else: + ab_diff.append(x, ab_diff_action) + # + for x in b_list: + if x in ['./', '../']: + pass + elif x not in a_list: + b_only.append(x, b_only_action) + # + return data # Re-read the directory. # Attempt to find the selected item back. def update(w): - setbusy(w) - icol, irow = w.selection - if 0 <= icol < len(w.data) and 2 <= irow < len(w.data[icol]): - selname = w.data[icol][irow][0] - else: - selname = '' - statcache.forget_dir(w.a) - statcache.forget_dir(w.b) - tablewin.select(w, (-1, -1)) - tablewin.update(w, diffdata(w.a, w.b, w.flags)) - if selname: - for icol in range(len(w.data)): - for irow in range(2, len(w.data[icol])): - if w.data[icol][irow][0] = selname: - tablewin.select(w, (icol, irow)) - break + setbusy(w) + icol, irow = w.selection + if 0 <= icol < len(w.data) and 2 <= irow < len(w.data[icol]): + selname = w.data[icol][irow][0] + else: + selname = '' + statcache.forget_dir(w.a) + statcache.forget_dir(w.b) + tablewin.select(w, (-1, -1)) + tablewin.update(w, diffdata(w.a, w.b, w.flags)) + if selname: + for icol in range(len(w.data)): + for irow in range(2, len(w.data[icol])): + if w.data[icol][irow][0] = selname: + tablewin.select(w, (icol, irow)) + break # Action functions for table items in directory diff windows def header_action(w, string, (icol, irow), (pos, clicks, button, mask)): - tablewin.select(w, (-1, -1)) + tablewin.select(w, (-1, -1)) def a_only_action(w, string, (icol, irow), (pos, clicks, button, mask)): - tablewin.select(w, (icol, irow)) - if clicks = 2: - w2 = anyopen(path.cat(w.a, string)) - if w2: - w2.parent = w + tablewin.select(w, (icol, irow)) + if clicks = 2: + w2 = anyopen(path.cat(w.a, string)) + if w2: + w2.parent = w def b_only_action(w, string, (icol, irow), (pos, clicks, button, mask)): - tablewin.select(w, (icol, irow)) - if clicks = 2: - w2 = anyopen(path.cat(w.b, string)) - if w2: - w2.parent = w + tablewin.select(w, (icol, irow)) + if clicks = 2: + w2 = anyopen(path.cat(w.b, string)) + if w2: + w2.parent = w def ab_diff_action(w, string, (icol, irow), (pos, clicks, button, mask)): - tablewin.select(w, (icol, irow)) - if clicks = 2: - w2 = anydiff(path.cat(w.a, string), path.cat(w.b, string), '') - w2.parent = w + tablewin.select(w, (icol, irow)) + if clicks = 2: + w2 = anydiff(path.cat(w.a, string), path.cat(w.b, string), '') + w2.parent = w def ab_same_action(w, string, sel, detail): - ax = path.cat(w.a, string) - if path.isdir(ax): - ab_diff_action(w, string, sel, detail) - else: - a_only_action(w, string, sel, detail) + ax = path.cat(w.a, string) + if path.isdir(ax): + ab_diff_action(w, string, sel, detail) + else: + a_only_action(w, string, sel, detail) def anyopen(name): # Open any kind of document, ignore errors - try: - w = anywin.open(name) - except (RuntimeError, posix.error): - stdwin.message('Can\'t open ' + name) - return 0 - addstatmenu(w, [name]) - return w + try: + w = anywin.open(name) + except (RuntimeError, posix.error): + stdwin.message('Can\'t open ' + name) + return 0 + addstatmenu(w, [name]) + return w def dircmp(a, b): # Compare whether two directories are the same - # To make this as fast as possible, it uses the statcache - print ' dircmp', a, b - a_list = dircache.listdir(a) - b_list = dircache.listdir(b) - for x in a_list: - if x in skiplist: - pass - elif x not in b_list: - return 0 - else: - ax = path.cat(a, x) - bx = path.cat(b, x) - if statcache.isdir(ax) and statcache.isdir(bx): - if not dircmp(ax, bx): return 0 - else: - try: - if not cmpcache.cmp(ax, bx): return 0 - except posix.error: - return 0 - for x in b_list: - if x in skiplist: - pass - elif x not in a_list: - return 0 - return 1 + # To make this as fast as possible, it uses the statcache + print ' dircmp', a, b + a_list = dircache.listdir(a) + b_list = dircache.listdir(b) + for x in a_list: + if x in skiplist: + pass + elif x not in b_list: + return 0 + else: + ax = path.cat(a, x) + bx = path.cat(b, x) + if statcache.isdir(ax) and statcache.isdir(bx): + if not dircmp(ax, bx): return 0 + else: + try: + if not cmpcache.cmp(ax, bx): return 0 + except posix.error: + return 0 + for x in b_list: + if x in skiplist: + pass + elif x not in a_list: + return 0 + return 1 # View menu (for dir diff windows only) def addviewmenu(w): - w.viewmenu = m = w.menucreate('View') - m.action = [] - add(m, 'diff -r A B', diffr_ab) - add(m, 'diff A B', diff_ab) - add(m, 'diff -b A B', diffb_ab) - add(m, 'diff -c A B', diffc_ab) - add(m, 'gdiff A B', gdiff_ab) - add(m, ('Open A ', 'A'), open_a) - add(m, ('Open B ', 'B'), open_b) - add(m, 'Rescan', rescan) - add(m, 'Rescan -r', rescan_r) + w.viewmenu = m = w.menucreate('View') + m.action = [] + add(m, 'diff -r A B', diffr_ab) + add(m, 'diff A B', diff_ab) + add(m, 'diff -b A B', diffb_ab) + add(m, 'diff -c A B', diffc_ab) + add(m, 'gdiff A B', gdiff_ab) + add(m, ('Open A ', 'A'), open_a) + add(m, ('Open B ', 'B'), open_b) + add(m, 'Rescan', rescan) + add(m, 'Rescan -r', rescan_r) # Action menu (for dir diff windows only) def addactionmenu(w): - w.actionmenu = m = w.menucreate('Action') - m.action = [] - add(m, 'cp A B', cp_ab) - add(m, 'rm B', rm_b) - add(m, '', nop) - add(m, 'cp B A', cp_ba) - add(m, 'rm A', rm_a) + w.actionmenu = m = w.menucreate('Action') + m.action = [] + add(m, 'cp A B', cp_ab) + add(m, 'rm B', rm_b) + add(m, '', nop) + add(m, 'cp B A', cp_ba) + add(m, 'rm A', rm_a) # Main menu (global): def mainmenu(): - m = stdwin.menucreate('Wdiff') - m.action = [] - add(m, ('Quit wdiff', 'Q'), quit_wdiff) - add(m, 'Close subwindows', close_subwindows) - return m + m = stdwin.menucreate('Wdiff') + m.action = [] + add(m, ('Quit wdiff', 'Q'), quit_wdiff) + add(m, 'Close subwindows', close_subwindows) + return m def add(m, text, action): - m.additem(text) - m.action.append(action) + m.additem(text) + m.action.append(action) def quit_wdiff(w, m, item): - if askyesno('Really quit wdiff altogether?', 1): - sys.exit(0) + if askyesno('Really quit wdiff altogether?', 1): + sys.exit(0) def close_subwindows(w, m, item): - while 1: - for w2 in gwin.windows: - if w2.parent = w: - close_subwindows(w2, m, item) - w2.close(w2) - break # inner loop, continue outer loop - else: - break # outer loop + while 1: + for w2 in gwin.windows: + if w2.parent = w: + close_subwindows(w2, m, item) + w2.close(w2) + break # inner loop, continue outer loop + else: + break # outer loop def diffr_ab(w, m, item): - dodiff(w, '-r') + dodiff(w, '-r') def diff_ab(w, m, item): - dodiff(w, '') + dodiff(w, '') def diffb_ab(w, m, item): - dodiff(w, '-b') + dodiff(w, '-b') def diffc_ab(w, m, item): - dodiff(w, '-c') + dodiff(w, '-c') def gdiff_ab(w, m, item): # Call SGI's gdiff utility - x = getselection(w) - if x: - a, b = path.cat(w.a, x), path.cat(w.b, x) - if path.isdir(a) or path.isdir(b): - stdwin.fleep() # This is for files only - else: - diffcmd = 'gdiff' - diffcmd = diffcmd + mkarg(a) + mkarg(b) + ' &' - print diffcmd - sts = posix.system(diffcmd) - if sts: print 'Exit status', sts + x = getselection(w) + if x: + a, b = path.cat(w.a, x), path.cat(w.b, x) + if path.isdir(a) or path.isdir(b): + stdwin.fleep() # This is for files only + else: + diffcmd = 'gdiff' + diffcmd = diffcmd + mkarg(a) + mkarg(b) + ' &' + print diffcmd + sts = posix.system(diffcmd) + if sts: print 'Exit status', sts def dodiff(w, flags): - x = getselection(w) - if x: - w2 = anydiff(path.cat(w.a, x), path.cat(w.b, x), flags) - w2.parent = w + x = getselection(w) + if x: + w2 = anydiff(path.cat(w.a, x), path.cat(w.b, x), flags) + w2.parent = w def open_a(w, m, item): - x = getselection(w) - if x: - w2 = anyopen(path.cat(w.a, x)) - if w2: - w2.parent = w + x = getselection(w) + if x: + w2 = anyopen(path.cat(w.a, x)) + if w2: + w2.parent = w def open_b(w, m, item): - x = getselection(w) - if x: - w2 = anyopen(path.cat(w.b, x)) - if w2: - w2.parent = w + x = getselection(w) + if x: + w2 = anyopen(path.cat(w.b, x)) + if w2: + w2.parent = w def rescan(w, m, item): - w.flags = '' - update(w) + w.flags = '' + update(w) def rescan_r(w, m, item): - w.flags = '-r' - update(w) + w.flags = '-r' + update(w) def rm_a(w, m, item): - x = getselection(w) - if x: - if x[-1:] = '/': x = x[:-1] - x = path.cat(w.a, x) - if path.isdir(x): - if askyesno('Recursively remove A directory ' + x, 1): - runcmd('rm -rf' + mkarg(x)) - else: - runcmd('rm -f' + mkarg(x)) - update(w) + x = getselection(w) + if x: + if x[-1:] = '/': x = x[:-1] + x = path.cat(w.a, x) + if path.isdir(x): + if askyesno('Recursively remove A directory ' + x, 1): + runcmd('rm -rf' + mkarg(x)) + else: + runcmd('rm -f' + mkarg(x)) + update(w) def rm_b(w, m, item): - x = getselection(w) - if x: - if x[-1:] = '/': x = x[:-1] - x = path.cat(w.b, x) - if path.isdir(x): - if askyesno('Recursively remove B directory ' + x, 1): - runcmd('rm -rf' + mkarg(x)) - else: - runcmd('rm -f' + mkarg(x)) - update(w) + x = getselection(w) + if x: + if x[-1:] = '/': x = x[:-1] + x = path.cat(w.b, x) + if path.isdir(x): + if askyesno('Recursively remove B directory ' + x, 1): + runcmd('rm -rf' + mkarg(x)) + else: + runcmd('rm -f' + mkarg(x)) + update(w) def cp_ab(w, m, item): - x = getselection(w) - if x: - if x[-1:] = '/': x = x[:-1] - ax = path.cat(w.a, x) - bx = path.cat(w.b, x) - if path.isdir(ax): - if path.exists(bx): - m = 'Can\'t copy directory to existing target' - stdwin.message(m) - return - runcmd('cp -r' + mkarg(ax) + mkarg(w.b)) - else: - runcmd('cp' + mkarg(ax) + mk2arg(w.b, x)) - update(w) + x = getselection(w) + if x: + if x[-1:] = '/': x = x[:-1] + ax = path.cat(w.a, x) + bx = path.cat(w.b, x) + if path.isdir(ax): + if path.exists(bx): + m = 'Can\'t copy directory to existing target' + stdwin.message(m) + return + runcmd('cp -r' + mkarg(ax) + mkarg(w.b)) + else: + runcmd('cp' + mkarg(ax) + mk2arg(w.b, x)) + update(w) def cp_ba(w, m, item): - x = getselection(w) - if x: - if x[-1:] = '/': x = x[:-1] - ax = path.cat(w.a, x) - bx = path.cat(w.b, x) - if path.isdir(bx): - if path.exists(ax): - m = 'Can\'t copy directory to existing target' - stdwin.message(m) - return - runcmd('cp -r' + mkarg(bx) + mkarg(w.a)) - else: - runcmd('cp' + mk2arg(w.b, x) + mkarg(ax)) - update(w) + x = getselection(w) + if x: + if x[-1:] = '/': x = x[:-1] + ax = path.cat(w.a, x) + bx = path.cat(w.b, x) + if path.isdir(bx): + if path.exists(ax): + m = 'Can\'t copy directory to existing target' + stdwin.message(m) + return + runcmd('cp -r' + mkarg(bx) + mkarg(w.a)) + else: + runcmd('cp' + mk2arg(w.b, x) + mkarg(ax)) + update(w) def nop(args): - pass + pass def getselection(w): - icol, irow = w.selection - if 0 <= icol < len(w.data): - if 0 <= irow < len(w.data[icol]): - return w.data[icol][irow][0] - stdwin.message('no selection') - return '' + icol, irow = w.selection + if 0 <= icol < len(w.data): + if 0 <= irow < len(w.data[icol]): + return w.data[icol][irow][0] + stdwin.message('no selection') + return '' def runcmd(cmd): - print cmd - sts, output = commands.getstatusoutput(cmd) - if sts or output: - if not output: - output = 'Exit status ' + `sts` - stdwin.message(output) + print cmd + sts, output = commands.getstatusoutput(cmd) + if sts or output: + if not output: + output = 'Exit status ' + `sts` + stdwin.message(output) # Status menu (for all kinds of windows) def addstatmenu(w, files): - w.statmenu = m = w.menucreate('Stat') - m.files = files - m.action = [] - for file in files: - m.additem(commands.getstatus(file)) - m.action.append(stataction) + w.statmenu = m = w.menucreate('Stat') + m.files = files + m.action = [] + for file in files: + m.additem(commands.getstatus(file)) + m.action.append(stataction) def stataction(w, m, item): # Menu item action for stat menu - file = m.files[item] - try: - m.setitem(item, commands.getstatus(file)) - except posix.error: - stdwin.message('Can\'t get status for ' + file) + file = m.files[item] + try: + m.setitem(item, commands.getstatus(file)) + except posix.error: + stdwin.message('Can\'t get status for ' + file) # Compute a suitable window title from two paths def mktitle(a, b): - if a = b: return a - i = 1 - while a[-i:] = b[-i:]: i = i+1 - i = i-1 - if not i: - return a + ' ' + b - else: - return '{' + a[:-i] + ',' + b[:-i] + '}' + a[-i:] + if a = b: return a + i = 1 + while a[-i:] = b[-i:]: i = i+1 + i = i-1 + if not i: + return a + ' ' + b + else: + return '{' + a[:-i] + ',' + b[:-i] + '}' + a[-i:] # Ask a confirmation question def askyesno(prompt, default): - try: - return stdwin.askync(prompt, default) - except KeyboardInterrupt: - return 0 + try: + return stdwin.askync(prompt, default) + except KeyboardInterrupt: + return 0 # Display a message "busy" in a window, and mark it for updating def setbusy(w): - left, top = w.getorigin() - width, height = w.getwinsize() - right, bottom = left + width, top + height - d = w.begindrawing() - d.erase((0, 0), (10000, 10000)) - text = 'Busy...' - textwidth = d.textwidth(text) - textheight = d.lineheight() - h, v = left + (width-textwidth)/2, top + (height-textheight)/2 - d.text((h, v), text) - del d - w.change((0, 0), (10000, 10000)) + left, top = w.getorigin() + width, height = w.getwinsize() + right, bottom = left + width, top + height + d = w.begindrawing() + d.erase((0, 0), (10000, 10000)) + text = 'Busy...' + textwidth = d.textwidth(text) + textheight = d.lineheight() + h, v = left + (width-textwidth)/2, top + (height-textheight)/2 + d.text((h, v), text) + del d + w.change((0, 0), (10000, 10000)) # Main function def main(): - print 'wdiff: warning: this version does NOT yet make backups' - argv = sys.argv - flags = '' - if len(argv) >= 2 and argv[1][:1] = '-': - flags = argv[1] - del argv[1] - m = mainmenu() # Create menu earlier than windows - if len(argv) = 2: # 1 argument - w = anyopen(argv[1]) - if not w: return - elif len(argv) = 3: # 2 arguments - w = anydiff(argv[1], argv[2], flags) - w.parent = () - else: - sys.stdout = sys.stderr - print 'usage:', argv[0], '[diff-flags] dir-1 [dir-2]' - sys.exit(2) - del w # It's preserved in gwin.windows - while 1: - try: - gwin.mainloop() - break - except KeyboardInterrupt: - pass # Just continue... + print 'wdiff: warning: this version does NOT yet make backups' + argv = sys.argv + flags = '' + if len(argv) >= 2 and argv[1][:1] = '-': + flags = argv[1] + del argv[1] + m = mainmenu() # Create menu earlier than windows + if len(argv) = 2: # 1 argument + w = anyopen(argv[1]) + if not w: return + elif len(argv) = 3: # 2 arguments + w = anydiff(argv[1], argv[2], flags) + w.parent = () + else: + sys.stdout = sys.stderr + print 'usage:', argv[0], '[diff-flags] dir-1 [dir-2]' + sys.exit(2) + del w # It's preserved in gwin.windows + while 1: + try: + gwin.mainloop() + break + except KeyboardInterrupt: + pass # Just continue... # Start the main function (this is a script) main() diff --git a/doc/Makefile b/doc/Makefile index f2a83bf..b2cf688 100644 --- a/doc/Makefile +++ b/doc/Makefile @@ -1,47 +1,47 @@ # Makefile for Python documentation. -LATEX= latex -DVIPS= dvips -TEXPREVIEW= xdvi +LATEX= latex +DVIPS= dvips +TEXPREVIEW= xdvi -PRINT= lpr +PRINT= lpr -tut: tut.dvi - $(TEXPREVIEW) tut +tut: tut.dvi + $(TEXPREVIEW) tut -tut.dvi tut.ps: tut.toc tut.tex myformat.sty +tut.dvi tut.ps: tut.toc tut.tex myformat.sty -mod: mod.dvi - $(TEXPREVIEW) mod +mod: mod.dvi + $(TEXPREVIEW) mod -mod.dvi mod.ps: mod.toc mod.tex mod1.tex mod2.tex mod3.tex myformat.sty +mod.dvi mod.ps: mod.toc mod.tex mod1.tex mod2.tex mod3.tex myformat.sty -ALL= tut.ps mod.ps +ALL= tut.ps mod.ps -all: $(ALL) +all: $(ALL) -print: $(ALL) - $(PRINT) $(ALL) +print: $(ALL) + $(PRINT) $(ALL) clean: - rm -f *.dvi *.aux *.toc *.log *.ps core [#@,]* *~ + rm -f *.dvi *.aux *.toc *.log *.ps core [#@,]* *~ -.SUFFIXES: # Remove default suffixes +.SUFFIXES: # Remove default suffixes -.SUFFIXES: .tex .aux .toc .dvi .ps +.SUFFIXES: .tex .aux .toc .dvi .ps .tex.aux: - $(LATEX) $* + $(LATEX) $* .tex.toc: - $(LATEX) $* + $(LATEX) $* .tex.dvi: - $(LATEX) $* + $(LATEX) $* .dvi.ps: - $(DVIPS) $* >$*.ps + $(DVIPS) $* >$*.ps .tex.ps: - $(LATEX) $* - $(DVIPS) $* >$*.ps + $(LATEX) $* + $(DVIPS) $* >$*.ps @@ -4,8 +4,8 @@ started. The following are the important latex source files: - tut.tex A tutorial - mod.tex The library reference + tut.tex A tutorial + mod.tex The library reference They both read the style option file "myformat.sty". @@ -18,7 +18,7 @@ Type "make clean" to get rid of all the intermediate files produced by the latex process, and other junk files. You can just as well ignore the Makefile; all you really need is: - latex tut - latex tut - dvips tut | lpr + latex tut + latex tut + dvips tut | lpr and similar for the "mod" document. diff --git a/doc/SetClass.py b/doc/SetClass.py index 8a5fb9e..ca7ca6b 100644 --- a/doc/SetClass.py +++ b/doc/SetClass.py @@ -1,17 +1,17 @@ class Set(): - def new(self): - self.elements = [] - return self - def add(self, e): - if e not in self.elements: - self.elements.append(e) - def remove(self, e): - if e in self.elements: - for i in range(len(self.elements)): - if self.elements[i] = e: - del self.elements[i] - break - def is_element(self, e): - return e in self.elements - def size(self): - return len(self.elements) + def new(self): + self.elements = [] + return self + def add(self, e): + if e not in self.elements: + self.elements.append(e) + def remove(self, e): + if e in self.elements: + for i in range(len(self.elements)): + if self.elements[i] = e: + del self.elements[i] + break + def is_element(self, e): + return e in self.elements + def size(self): + return len(self.elements) diff --git a/doc/fibo.py b/doc/fibo.py index e8cafa8..83b8e83 100644 --- a/doc/fibo.py +++ b/doc/fibo.py @@ -1,15 +1,15 @@ # Fibonacci numbers demo -def fib(n): # write Fibonacci series up to n - a, b = 0, 1 - while b <= n: - print b, - a, b = b, a+b +def fib(n): # write Fibonacci series up to n + a, b = 0, 1 + while b <= n: + print b, + a, b = b, a+b def fib2(n): # return Fibonacci series up to n - ret = [] - a, b = 0, 1 - while b <= n: - ret.append(b) - a, b = b, a+b - return ret + ret = [] + a, b = 0, 1 + while b <= n: + ret.append(b) + a, b = b, a+b + return ret diff --git a/doc/mod.tex b/doc/mod.tex index c2d2355..cddfed7 100644 --- a/doc/mod.tex +++ b/doc/mod.tex @@ -5,7 +5,7 @@ % A command to force the text after an item to start on a new line \newcommand{\itembreak}{ - \mbox{}\\*[0mm] + \mbox{}\\*[0mm] } % A command to define a function item @@ -17,16 +17,16 @@ \itembreak } -\title{\bf - Python Library Reference \\ - (DRAFT) + itle{\bf + Python Library Reference \\ + (DRAFT) } \author{ - Guido van Rossum \\ - Dept. CST, CWI, Kruislaan 413 \\ - 1098 SJ Amsterdam, The Netherlands \\ - E-mail: {\tt [email protected]} + Guido van Rossum \\ + Dept. CST, CWI, Kruislaan 413 \\ + 1098 SJ Amsterdam, The Netherlands \\ + E-mail: {\tt [email protected]} } \begin{document} @@ -49,7 +49,7 @@ gives a more formal reference to the language. \pagebreak -\tableofcontents + ableofcontents \pagebreak diff --git a/doc/mod1.tex b/doc/mod1.tex index 2dac554..37abc50 100644 --- a/doc/mod1.tex +++ b/doc/mod1.tex @@ -101,15 +101,15 @@ Operation & Result & Notes \\ {\tt min}({\em s}) & smallest item of {\em s} & \\ {\tt max}({\em s}) & largest item of {\em s} & \\ {\em x} {\tt in} {\em s} & - true if an item of {\em s} is equal to {\em x} & \\ + true if an item of {\em s} is equal to {\em x} & \\ {\em x} {\tt not} {\tt in} {\em s} & - false if an item of {\em s} is equal to {\em x} & \\ + false if an item of {\em s} is equal to {\em x} & \\ {\em s}{\tt +}{\em t} & the concatenation of {\em s} and {\em t} & \\ {\em s}{\tt *}{\em n}, {\em n}*{\em s} & - {\em n} copies of {\em s} concatenated & (1) \\ + {\em n} copies of {\em s} concatenated & (1) \\ {\em s}[{\em i}] & {\em i}'th item of {\em s} & \\ {\em s}[{\em i}:{\em j}] & - slice of {\em s} from {\em i} to {\em j} & (2) \\ + slice of {\em s} from {\em i} to {\em j} & (2) \\ \hline \end{tabular} \end{center} @@ -143,19 +143,19 @@ The following operations are defined on mutable sequence types (where Operation & Result \\ \hline {\em s}[{\em i}] = {\em x} & - item {\em i} of {\em s} is replaced by {\em x} \\ + item {\em i} of {\em s} is replaced by {\em x} \\ {\em s}[{\em i}:{\em j}] = {\em t} & - slice of {\em s} from {\em i} to {\em j} is replaced by {\em t} \\ + slice of {\em s} from {\em i} to {\em j} is replaced by {\em t} \\ {\tt del} {\em s}[{\em i}:{\em j}] & - same as {\em s}[{\em i}:{\em j}] = [] \\ + same as {\em s}[{\em i}:{\em j}] = [] \\ {\em s}.{\tt append}({\em x}) & - same as {\em s}[{\tt len}({\em x}):{\tt len}({\em x})] = [{\em x}] \\ + same as {\em s}[{\tt len}({\em x}):{\tt len}({\em x})] = [{\em x}] \\ {\em s}.{\tt insert}({\em i}, {\em x}) & - same as {\em s}[{\em i}:{\em i}] = [{\em x}] \\ + same as {\em s}[{\em i}:{\em i}] = [{\em x}] \\ {\em s}.{\tt sort}() & - the items of {\em s} are permuted to satisfy \\ - & - $s[i] \leq s[j]$ for $i < j$\\ + the items of {\em s} are permuted to satisfy \\ + & + $s[i] \leq s[j]$ for $i < j$\\ \hline \end{tabular} \end{center} @@ -216,7 +216,7 @@ A small example using a dictionary: ['guido', 'irv', 'jack'] >>> tel.has_key('guido') 1 ->>> +>>> \end{verbatim}\ecode \subsubsection{Other Built-in Types} @@ -372,7 +372,7 @@ For example: ['sys'] >>> dir(sys) ['argv', 'exit', 'modules', 'path', 'stderr', 'stdin', 'stdout'] ->>> +>>> \end{verbatim}\ecode \funcitem{divmod}{a, b} %.br @@ -398,7 +398,7 @@ For example: (-15, -5) >>> divmod(-100, -7) (14, -2) ->>> +>>> \end{verbatim}\ecode \funcitem{eval}{s} Takes a string as argument and parses and evaluates it as a {\Python} @@ -411,7 +411,7 @@ For example: >>> x = 1 >>> eval('x+1') 2 ->>> +>>> \end{verbatim}\ecode \funcitem{exec}{s} Takes a string as argument and parses and evaluates it as a sequence of @@ -426,7 +426,7 @@ For example: >>> exec('x = x+1\n') >>> x 2 ->>> +>>> \end{verbatim}\ecode \funcitem{float}{x} Converts a number to floating point. @@ -494,7 +494,7 @@ For example: [] >>> range(1, 0) [] ->>> +>>> \end{verbatim}\ecode \funcitem{raw\_input}{s} %.br @@ -508,7 +508,7 @@ For example: >>> raw_input('Type anything: ') Type anything: Mutant Teenage Ninja Turtles 'Mutant Teenage Ninja Turtles' ->>> +>>> \end{verbatim}\ecode \funcitem{reload}{module} Causes an already imported module to be re-parsed and re-initialized. diff --git a/doc/mod2.tex b/doc/mod2.tex index 46f6d62..fca5e8a 100644 --- a/doc/mod2.tex +++ b/doc/mod2.tex @@ -87,12 +87,12 @@ They are: {\tt exp(x)}, {\tt fabs(x)}, {\tt floor(x)}, -%{\tt fmod(...)} XXX not yet +%{\tt fmod(...)} XXX not yet %{\tt frexp(...)} XXX not yet %{\tt ldexp(...)} XXX not yet {\tt log(x)}, {\tt log10(x)}, -%{\tt modf(...)} XXX not yet +%{\tt modf(...)} XXX not yet {\tt pow(x,y)}, {\tt sin(x)}, {\tt sinh(x)}, @@ -193,7 +193,7 @@ For example: '--b--' >>> s[3:4] # The subpattern 'b' ->>> +>>> \end{verbatim}\ecode \subsection{Built-in Module {\tt posix}} @@ -693,16 +693,16 @@ import stdwin from stdwinevents import * def main(): - mywin = stdwin.open('Hello') - # - while 1: - (type, win, detail) = stdwin.getevent() - if type = WE_DRAW: - draw = win.begindrawing() - draw.text((0, 0), 'Hello, world') - del draw - elif type = WE_CLOSE: - break + mywin = stdwin.open('Hello') + # + while 1: + (type, win, detail) = stdwin.getevent() + if type = WE_DRAW: + draw = win.begindrawing() + draw.text((0, 0), 'Hello, world') + del draw + elif type = WE_CLOSE: + break main() \end{verbatim}\ecode @@ -780,7 +780,7 @@ For example: \bcode\begin{verbatim} >>> amoeba.name_lookup('/profile/cap') aa:1c:95:52:6a:fa/14(ff)/8e:ba:5b:8:11:1a ->>> +>>> \end{verbatim}\ecode The following methods are defined for capability objects. \begin{description} @@ -879,7 +879,7 @@ implemented in C for efficiency: Amplifies a chunk of samples by a variable factor changing from {\tt f1}/256 to {\tt f2}/256. Negative factors are allowed. -Resulting values that are to large to fit in a byte are clipped. +Resulting values that are to large to fit in a byte are clipped. \funcitem{reverse}{buf} %.br Returns a chunk of samples backwards. @@ -1000,7 +1000,7 @@ is called for the normal, and then {\tt v3f()} is called for the point. \funcitem{vnarray}{} -Similar to +Similar to {\tt nvarray()} but the pairs have the point first and the normal second. \funcitem{nurbssurface}{s\_k[], t\_k[], ctl[][], s\_ord, t\_ord, type} @@ -1042,22 +1042,22 @@ Here is a tiny but complete example GL program in {\Python}: import gl, GL, time def main(): - gl.foreground() - gl.prefposition(500, 900, 500, 900) - w = gl.winopen('CrissCross') - gl.ortho2(0.0, 400.0, 0.0, 400.0) - gl.color(GL.WHITE) - gl.clear() - gl.color(GL.RED) - gl.bgnline() - gl.v2f(0.0, 0.0) - gl.v2f(400.0, 400.0) - gl.endline() - gl.bgnline() - gl.v2f(400.0, 0.0) - gl.v2f(0.0, 400.0) - gl.endline() - time.sleep(5) + gl.foreground() + gl.prefposition(500, 900, 500, 900) + w = gl.winopen('CrissCross') + gl.ortho2(0.0, 400.0, 0.0, 400.0) + gl.color(GL.WHITE) + gl.clear() + gl.color(GL.RED) + gl.bgnline() + gl.v2f(0.0, 0.0) + gl.v2f(400.0, 400.0) + gl.endline() + gl.bgnline() + gl.v2f(400.0, 0.0) + gl.v2f(0.0, 400.0) + gl.endline() + time.sleep(5) main() \end{verbatim}\ecode diff --git a/doc/mod3.tex b/doc/mod3.tex index d1a99b1..d37956c 100644 --- a/doc/mod3.tex +++ b/doc/mod3.tex @@ -19,7 +19,7 @@ The string The string {\tt '0123456789abcdefABCDEF'}. \funcitem{letters} -The concatenation of the strings +The concatenation of the strings {\tt lowercase} and {\tt uppercase} @@ -99,7 +99,7 @@ Removes leading and trailing whitespace from the string Converts lower case letters to upper case and vice versa. \funcitem{upper}{s} Convert letters to upper case. -\funcitem{ljust(s, width), rjust(s, width), center}{s, width} +\funcitem{ljust(s, width), rjust(s, width), center}{s, width} %.br These functions respectively left-justify, right-justify and center a string in a field of given width. @@ -252,7 +252,7 @@ Example: [('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')] >>> args ['a1', 'a2'] ->>> +>>> \end{verbatim}\ecode The exception {\tt getopt.error = 'getopt error'} @@ -305,7 +305,7 @@ Read the file for details. Suggested usage is \bcode\begin{verbatim} >>> from stdwinevents import * ->>> +>>> \end{verbatim}\ecode \subsection{Standard Module {\tt rect}} @@ -342,7 +342,7 @@ This makes it possible to quickly check whether a result is empty: >>> r3 = rect.intersect(r1, r2) >>> if r3 is rect.empty: print 'Empty intersection' Empty intersection ->>> +>>> \end{verbatim}\ecode \funcitem{is\_empty}{r} %.br diff --git a/doc/myformat.sty b/doc/myformat.sty index be70239..192ddb1 100644 --- a/doc/myformat.sty +++ b/doc/myformat.sty @@ -1,34 +1,34 @@ % Style parameters and macros used by all documents here % Page lay-out parameters -\textwidth = 160mm -\textheight = 240mm -\topmargin = -11mm -\oddsidemargin = 0mm -\evensidemargin = 0mm -%\parindent = 0mm + extwidth = 160mm + extheight = 240mm + opmargin = -11mm +\oddsidemargin = 0mm +\evensidemargin = 0mm +%\parindent = 0mm % Frequently used system names -\newcommand{\Python}{Python} % Sometimes I want this italicized +\newcommand{\Python}{Python} % Sometimes I want this italicized \newcommand{\UNIX}{U{\sc nix}} % Variable used by begin code command \newlength{\codewidth} \newcommand{\bcode}{ - % Calculate the text width for the minipage: - \setlength{\codewidth}{\linewidth} - \addtolength{\codewidth}{-\parindent} - % - \vspace{3mm} - \par - \indent - \begin{minipage}[t]{\codewidth} + % Calculate the text width for the minipage: + \setlength{\codewidth}{\linewidth} + \addtolength{\codewidth}{-\parindent} + % + \vspace{3mm} + \par + \indent + \begin{minipage}[t]{\codewidth} } \newcommand{\ecode}{ - \end{minipage} - \vspace{3mm} - \par - \noindent + \end{minipage} + \vspace{3mm} + \par + \noindent } @@ -4,17 +4,17 @@ trap 'rm -f $TMP; exit 1' 1 2 3 13 14 15 cat $* >$TMP ( - cat $TMP - - sed ' - s/^>>> // - s/^>>>$// - s/^\.\.\. // - s/^\.\.\.$// - ' $TMP | - python - - echo '>>> ' + cat $TMP + + sed ' + s/^>>> // + s/^>>>$// + s/^\.\.\. // + s/^\.\.\.$// + ' $TMP | + python + + echo '>>> ' ) 2>&1 rm $TMP diff --git a/doc/tut.tex b/doc/tut.tex index ad5f56c..e0229b9 100644 --- a/doc/tut.tex +++ b/doc/tut.tex @@ -9,10 +9,10 @@ } \author{ - Guido van Rossum \\ - Dept. CST, CWI, Kruislaan 413 \\ - 1098 SJ Amsterdam, The Netherlands \\ - E-mail: {\tt [email protected]} + Guido van Rossum \\ + Dept. CST, CWI, Kruislaan 413 \\ + 1098 SJ Amsterdam, The Netherlands \\ + E-mail: {\tt [email protected]} } \begin{document} @@ -154,15 +154,15 @@ installation option, other places instead of are possible; check with your local \Python\ guru or system administrator.% \footnote{ - At CWI, at the time of writing, the interpreter can be found in - the following places: - On the Amoeba Ultrix machines, use the standard path, - {\tt /usr/local/python}. - On the Sun file servers, use - {\tt /ufs/guido/bin/}{\em arch}{\tt /python}, - where {\em arch} can be {\tt sgi} or {\tt sun4}. - On piring, use {\tt /userfs3/amoeba/bin/python}. - (If you can't find a binary advertised here, get in touch with me.) + At CWI, at the time of writing, the interpreter can be found in + the following places: + On the Amoeba Ultrix machines, use the standard path, + {\tt /usr/local/python}. + On the Sun file servers, use + {\tt /ufs/guido/bin/}{\em arch}{\tt /python}, + where {\em arch} can be {\tt sgi} or {\tt sun4}. + On piring, use {\tt /userfs3/amoeba/bin/python}. + (If you can't find a binary advertised here, get in touch with me.) } The interpreter operates somewhat like the \UNIX\ shell: when called with @@ -172,13 +172,13 @@ standard input, it reads and executes a {\em script} from that file.% \footnote{ - There is a difference between ``{\tt python file}'' and - ``{\tt python $<$file}''. In the latter case {\tt input()} and - {\tt raw\_input()} are satisfied from {\em file}, which has - already been read until the end by the parser, so they will read - EOF immediately. In the former case (which is usually what - you want) they are satisfied from whatever file or device is - connected to standard input of the \Python\ interpreter. + There is a difference between ``{\tt python file}'' and + ``{\tt python $<$file}''. In the latter case {\tt input()} and + {\tt raw\_input()} are satisfied from {\em file}, which has + already been read until the end by the parser, so they will read + EOF immediately. In the former case (which is usually what + you want) they are satisfied from whatever file or device is + connected to standard input of the \Python\ interpreter. } If available, the script name and additional arguments thereafter are passed to the script in the variable @@ -232,10 +232,10 @@ When is not set, an installation-dependent default path is used, usually {\tt .:/usr/local/lib/python}.% \footnote{ - Modules are really searched in the list of directories given by - the variable {\tt sys.path} which is initialized from - {\tt PYTHONPATH} or from the installation-dependent default. - See the section on Standard Modules later. + Modules are really searched in the list of directories given by + the variable {\tt sys.path} which is initialized from + {\tt PYTHONPATH} or from the installation-dependent default. + See the section on Standard Modules later. } On BSD'ish \UNIX\ systems, \Python\ scripts can be made directly executable, @@ -262,10 +262,10 @@ however, the basics are easily explained. If supported,% \footnote{ - Perhaps the quickest check to see whether command line editing - is supported is typing Control-P to the first \Python\ prompt - you get. If it beeps, you have command line editing. - If not, you can skip the rest of this section. + Perhaps the quickest check to see whether command line editing + is supported is typing Control-P to the first \Python\ prompt + you get. If it beeps, you have command line editing. + If not, you can skip the rest of this section. } input line editing is active whenever the interpreter prints a primary or secondary prompt. @@ -423,9 +423,9 @@ notation: two subscripts (indices) separated by a colon. >>> word[2:4] 'lp' >>> # Slice indices have useful defaults: ->>> word[:2] # Take first two characters +>>> word[:2] # Take first two characters 'He' ->>> word[2:] # Drop first two characters +>>> word[2:] # Drop first two characters 'lpA' >>> # A useful invariant: s[:i] + s[i:] = s >>> word[:3] + word[3:] @@ -448,12 +448,12 @@ Slice indices (but not simple subscripts) may be negative numbers, to start counting from the right. For example: \bcode\begin{verbatim} ->>> word[-2:] # Take last two characters +>>> word[-2:] # Take last two characters 'pA' ->>> word[:-2] # Drop last two characters +>>> word[:-2] # Drop last two characters 'Hel' >>> # But -0 does not count from the right! ->>> word[-0:] # (since -0 equals 0) +>>> word[-0:] # (since -0 equals 0) 'HelpA' >>> \end{verbatim}\ecode @@ -470,8 +470,8 @@ for example: +---+---+---+---+---+ | H | e | l | p | A | +---+---+---+---+---+ - 0 1 2 3 4 5 --5 -4 -3 -2 -1 + 0 1 2 3 4 5 +-5 -4 -3 -2 -1 \end{verbatim}\ecode The first row of numbers gives the position of the indices 0...5 in the string; the second row gives the corresponding negative indices. @@ -570,8 +570,8 @@ series as follows: >>> # the sum of two elements defines the next >>> a, b = 0, 1 >>> while b < 100: -... print b -... a, b = b, a+b +... print b +... a, b = b, a+b ... 1 1 @@ -616,9 +616,9 @@ The standard comparison operators are written as and {\tt <>}.% \footnote{ - The ambiguity of using {\tt =} - for both assignment and equality is resolved by disallowing - unparenthesized conditions at the right hand side of assignments. + The ambiguity of using {\tt =} + for both assignment and equality is resolved by disallowing + unparenthesized conditions at the right hand side of assignments. } \item The @@ -651,8 +651,8 @@ A trailing comma avoids the newline after the output: \bcode\begin{verbatim} >>> a, b = 0, 1 >>> while b < 1000: -... print b, -... a, b = b, a+b +... print b, +... a, b = b, a+b ... 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 >>> @@ -673,14 +673,14 @@ Perhaps the most well-known statement type is the {\tt if} statement. For example: \bcode\begin{verbatim} >>> if x < 0: -... x = 0 -... print 'Negative changed to zero' +... x = 0 +... print 'Negative changed to zero' ... elif x = 0: -... print 'Zero' +... print 'Zero' ... elif x = 1: -... print 'Single' +... print 'Single' ... else: -... print 'More' +... print 'More' ... \end{verbatim}\ecode There can be zero or more {\tt elif} parts, and the {\tt else} part is @@ -703,7 +703,7 @@ For example (no pun intended): >>> # Measure some strings: >>> a = ['cat', 'window', 'defenestrate'] >>> for x in a: -... print x, len(x) +... print x, len(x) ... cat 3 window 6 @@ -741,7 +741,7 @@ and {\tt len()} as follows: \bcode\begin{verbatim} >>> a = ['Mary', 'had', 'a', 'little', 'boy'] >>> for i in range(len(a)): -... print i, a[i] +... print i, a[i] ... 0 Mary 1 had @@ -763,12 +763,12 @@ This is exemplified by the following loop, which searches for a list item of value 0: \bcode\begin{verbatim} >>> for n in range(2, 10): -... for x in range(2, n): -... if n % x = 0: -... print n, 'equals', x, '*', n/x -... break -... else: -... print n, 'is a prime number' +... for x in range(2, n): +... if n % x = 0: +... print n, 'equals', x, '*', n/x +... break +... else: +... print n, 'is a prime number' ... 2 is a prime number 3 is a prime number @@ -789,7 +789,7 @@ program requires no action. For example: \bcode\begin{verbatim} >>> while 1: -... pass # Busy-wait for keyboard interrupt +... pass # Busy-wait for keyboard interrupt ... \end{verbatim}\ecode @@ -802,11 +802,11 @@ XXX To Be Done. We can create a function that writes the Fibonacci series to an arbitrary boundary: \bcode\begin{verbatim} ->>> def fib(n): # write Fibonacci series up to n -... a, b = 0, 1 -... while b <= n: -... print b, -... a, b = b, a+b +>>> def fib(n): # write Fibonacci series up to n +... a, b = 0, 1 +... while b <= n: +... print b, +... a, b = b, a+b ... >>> # Now call the function we just defined: >>> fib(2000) @@ -837,10 +837,10 @@ the local symbol table of the called function when it is called; thus, arguments are passed using {\em call\ by\ value}.% \footnote{ - Actually, {\em call by object reference} would be a better - description, since if a mutable object is passed, the caller - will see any changes the callee makes to it (e.g., items - inserted into a list). + Actually, {\em call by object reference} would be a better + description, since if a mutable object is passed, the caller + will see any changes the callee makes to it (e.g., items + inserted into a list). } When a function calls another function, a new local symbol table is created for that call. @@ -880,15 +880,15 @@ It is simple to write a function that returns a list of the numbers of the Fibonacci series, instead of printing it: \bcode\begin{verbatim} >>> def fib2(n): # return Fibonacci series up to n -... result = [] -... a, b = 0, 1 -... while b <= n: -... result.append(b) # see below -... a, b = b, a+b -... return result +... result = [] +... a, b = 0, 1 +... while b <= n: +... result.append(b) # see below +... a, b = b, a+b +... return result ... ->>> f100 = fib2(100) # call it ->>> f100 # write the result +>>> f100 = fib2(100) # call it +>>> f100 # write the result [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] >>> \end{verbatim}\ecode @@ -928,8 +928,8 @@ In this case it is equivalent to {\tt ret = ret + [b]}, but more efficient.% \footnote{ - There is a subtle semantic difference if the object - is referenced from more than one place. + There is a subtle semantic difference if the object + is referenced from more than one place. } \end{itemize} The list object type has two more methods: @@ -993,19 +993,19 @@ in the current directory with the following contents: \bcode\begin{verbatim} # Fibonacci numbers module -def fib(n): # write Fibonacci series up to n - a, b = 0, 1 - while b <= n: - print b, - a, b = b, a+b +def fib(n): # write Fibonacci series up to n + a, b = 0, 1 + while b <= n: + print b, + a, b = b, a+b def fib2(n): # return Fibonacci series up to n - ret = [] - a, b = 0, 1 - while b <= n: - ret.append(b) - a, b = b, a+b - return ret + ret = [] + a, b = 0, 1 + while b <= n: + ret.append(b) + a, b = b, a+b + return ret \end{verbatim}\ecode Now enter the \Python\ interpreter and import this module with the following command: @@ -1043,9 +1043,9 @@ They are executed only the {\em first} time the module is imported somewhere.% \footnote{ - In fact function definitions are also `statements' that are - `executed'; the execution enters the function name in the - module's global symbol table. + In fact function definitions are also `statements' that are + `executed'; the execution enters the function name in the + module's global symbol table. } Each module has its own private symbol table, which is used as the @@ -1157,7 +1157,7 @@ kind of complaint you get while you are still learning \Python: >>> while 1 print 'Hello world' Parsing error: file <stdin>, line 1: while 1 print 'Hello world' - ^ + ^ Unhandled exception: run-time error: syntax error >>> \end{verbatim}\ecode @@ -1178,15 +1178,15 @@ an error when an attempt is made to execute it: >>> 10 * (1/0) Unhandled exception: run-time error: integer division by zero Stack backtrace (innermost last): - File "<stdin>", line 1 + File "<stdin>", line 1 >>> 4 + foo*3 Unhandled exception: undefined name: foo Stack backtrace (innermost last): - File "<stdin>", line 1 + File "<stdin>", line 1 >>> '2' + 2 Unhandled exception: type error: illegal argument type for built-in operation Stack backtrace (innermost last): - File "<stdin>", line 1 + File "<stdin>", line 1 >>> \end{verbatim}\ecode Errors detected during execution are called @@ -1223,9 +1223,9 @@ The detail states the cause of the error in more detail. errors are more serious: these are usually caused by misspelled identifiers.% \footnote{ - The parser does not check whether names used in a program are at - all defined elsewhere in the program, so such checks are - postponed until run-time. The same holds for type checking. + The parser does not check whether names used in a program are at + all defined elsewhere in the program, so such checks are + postponed until run-time. The same holds for type checking. } The detail is the offending identifier. \item @@ -1244,11 +1244,11 @@ some floating point numbers: \bcode\begin{verbatim} >>> numbers = [0.3333, 2.5, 0.0, 10.0] >>> for x in numbers: -... print x, -... try: -... print 1.0 / x -... except RuntimeError: -... print '*** has no inverse ***' +... print x, +... try: +... print 1.0 / x +... except RuntimeError: +... print '*** has no inverse ***' ... 0.3333 3.00030003 2.5 0.4 @@ -1288,7 +1288,7 @@ An except clause may name multiple exceptions as a parenthesized list, e.g.: \bcode\begin{verbatim} ... except (RuntimeError, TypeError, NameError): -... pass +... pass \end{verbatim}\ecode The last except clause may omit the exception name(s), to serve as a wildcard. @@ -1303,9 +1303,9 @@ specify a variable after the exception name (or list) to receive the argument's value, as follows: \bcode\begin{verbatim} >>> try: -... foo() +... foo() ... except NameError, x: -... print 'name', x, 'undefined' +... print 'name', x, 'undefined' ... name foo undefined >>> @@ -1319,21 +1319,21 @@ These are in fact string objects whose {\em object\ identity} (not their value!) identifies the exceptions.% \footnote{ - There should really be a separate exception type; it is pure - laziness that exceptions are identified by strings, and this may - be fixed in the future. + There should really be a separate exception type; it is pure + laziness that exceptions are identified by strings, and this may + be fixed in the future. } The string is printed as the second part of the message for unhandled exceptions. Their names and values are: \bcode\begin{verbatim} -EOFError 'end-of-file read' -KeyboardInterrupt 'keyboard interrupt' -MemoryError 'out of memory' * -NameError 'undefined name' * -RuntimeError 'run-time error' * -SystemError 'system error' * -TypeError 'type error' * +EOFError 'end-of-file read' +KeyboardInterrupt 'keyboard interrupt' +MemoryError 'out of memory' * +NameError 'undefined name' * +RuntimeError 'run-time error' * +SystemError 'system error' * +TypeError 'type error' * \end{verbatim}\ecode The meanings should be clear enough. Those exceptions with a {\tt *} in the third column have an argument. @@ -1344,12 +1344,12 @@ that are called (even indirectly) in the try clause. For example: \bcode\begin{verbatim} >>> def this_fails(): -... x = 1/0 +... x = 1/0 ... >>> try: -... this_fails() +... this_fails() ... except RuntimeError, detail: -... print 'Handling run-time error:', detail +... print 'Handling run-time error:', detail ... Handling run-time error: domain error or zero division >>> @@ -1364,7 +1364,7 @@ For example: >>> raise NameError, 'Hi There!' Unhandled exception: undefined name: Hi There! Stack backtrace (innermost last): - File "<stdin>", line 1 + File "<stdin>", line 1 >>> \end{verbatim}\ecode The first argument to {\tt raise} names the exception to be raised. @@ -1378,15 +1378,15 @@ For example: \bcode\begin{verbatim} >>> my_exc = 'nobody likes me!' >>> try: -... raise my_exc, 2*2 +... raise my_exc, 2*2 ... except my_exc, val: -... print 'My exception occured, value:', val +... print 'My exception occured, value:', val ... My exception occured, value: 4 >>> raise my_exc, 1 Unhandled exception: nobody likes me!: 1 Stack backtrace (innermost last): - File "<stdin>", line 7 + File "<stdin>", line 7 >>> \end{verbatim}\ecode Many standard modules use this to report errors that may occur in @@ -1399,14 +1399,14 @@ define clean-up actions that must be executed under all circumstances. For example: \bcode\begin{verbatim} >>> try: -... raise KeyboardInterrupt +... raise KeyboardInterrupt ... finally: -... print 'Goodbye, world!' +... print 'Goodbye, world!' ... Goodbye, world! Unhandled exception: keyboard interrupt Stack backtrace (innermost last): - File "<stdin>", line 2 + File "<stdin>", line 2 >>> \end{verbatim}\ecode The @@ -1456,11 +1456,11 @@ Also, like Modula-3 but unlike C++, the built-in operators with special syntax (arithmetic operators, subscripting etc.) cannot be redefined for class members.% \footnote{ - They can be redefined for new object types implemented in C in - extensions to the interpreter, however. It would require only a - naming convention and a relatively small change to the - interpreter to allow operator overloading for classes, so - perhaps someday... + They can be redefined for new object types implemented in C in + extensions to the interpreter, however. It would require only a + naming convention and a relatively small change to the + interpreter to allow operator overloading for classes, so + perhaps someday... } \subsubsection{A Simple Example} @@ -1471,22 +1471,22 @@ remove elements, a membership test, and a request for the size of the set. \bcode\begin{verbatim} class Set(): - def new(self): - self.elements = [] - return self - def add(self, e): - if e not in self.elements: - self.elements.append(e) - def remove(self, e): - if e in self.elements: - for i in range(len(self.elements)): - if self.elements[i] = e: - del self.elements[i] - break - def is_element(self, e): - return e in self.elements - def size(self): - return len(self.elements) + def new(self): + self.elements = [] + return self + def add(self, e): + if e not in self.elements: + self.elements.append(e) + def remove(self, e): + if e in self.elements: + for i in range(len(self.elements)): + if self.elements[i] = e: + del self.elements[i] + break + def is_element(self, e): + return e in self.elements + def size(self): + return len(self.elements) \end{verbatim}\ecode Note that the class definition looks like a big compound statement, with all the function definitons indented repective to the @@ -1538,13 +1538,13 @@ XXX This section is not complete yet! \section{XXX P.M.} \begin{itemize} -\item The {\tt del} statement. -\item The {\tt dir()} function. -\item Tuples. -\item Dictionaries. -\item Objects and types in general. -\item Backquotes. -\item And/Or/Not. +\item The {\tt del} statement. +\item The {\tt dir()} function. +\item Tuples. +\item Dictionaries. +\item Objects and types in general. +\item Backquotes. +\item And/Or/Not. \end{itemize} \end{document} diff --git a/lib/Abstract.py b/lib/Abstract.py index 385e6e5..9d9013b 100644 --- a/lib/Abstract.py +++ b/lib/Abstract.py @@ -11,45 +11,45 @@ # define() while split creation methods are called create(). class AbstractParent(): - # - # Upcalls from child to parent - # - def addchild(self, child): unimpl() - def delchild(self, child): unimpl() - # - def need_mouse(self, child): unimpl() - def no_mouse(self, child): unimpl() - # - def need_timer(self, child): unimpl() - def no_timer(self, child): unimpl() - # - # XXX need_kbd, no_kbd; focus??? - # - def begindrawing(self): return unimpl() - def beginmeasuring(self): return unimpl() - # - def change(self, area): unimpl() - def scroll(self, (area, (dh, dv))): unimpl() - def settimer(self, itimer): unimpl() + # + # Upcalls from child to parent + # + def addchild(self, child): unimpl() + def delchild(self, child): unimpl() + # + def need_mouse(self, child): unimpl() + def no_mouse(self, child): unimpl() + # + def need_timer(self, child): unimpl() + def no_timer(self, child): unimpl() + # + # XXX need_kbd, no_kbd; focus??? + # + def begindrawing(self): return unimpl() + def beginmeasuring(self): return unimpl() + # + def change(self, area): unimpl() + def scroll(self, (area, (dh, dv))): unimpl() + def settimer(self, itimer): unimpl() class AbstractChild(): - # - # Downcalls from parent to child - # - def destroy(self): unimpl() - # - def minsize(self, m): return unimpl() - def getbounds(self): return unimpl() - def setbounds(self, bounds): unimpl() - def draw(self, (d, area)): unimpl() - # - # Downcalls only made after certain upcalls - # - def mouse_down(self, detail): unimpl() - def mouse_move(self, detail): unimpl() - def mouse_up(self, detail): unimpl() - # - def timer(self): unimpl() + # + # Downcalls from parent to child + # + def destroy(self): unimpl() + # + def minsize(self, m): return unimpl() + def getbounds(self): return unimpl() + def setbounds(self, bounds): unimpl() + def draw(self, (d, area)): unimpl() + # + # Downcalls only made after certain upcalls + # + def mouse_down(self, detail): unimpl() + def mouse_move(self, detail): unimpl() + def mouse_up(self, detail): unimpl() + # + def timer(self): unimpl() # A "Split" is a child that manages one or more children. # (This terminology is due to DEC SRC, except for CSplits.) @@ -58,4 +58,4 @@ class AbstractChild(): # for others (e.g., all geometry related calls) this is not possible. class AbstractSplit() = AbstractChild(), AbstractParent(): - pass + pass diff --git a/lib/Buttons.py b/lib/Buttons.py index 7c36021..3ad5605 100644 --- a/lib/Buttons.py +++ b/lib/Buttons.py @@ -20,374 +20,374 @@ _MASK = 3 # LabelAppearance provides defaults for all appearance methods. # selected state not visible # disabled --> crossed out -# hilited --> inverted +# hilited --> inverted # class LabelAppearance(): - # - # Initialization - # - def init_appearance(self): - self.bounds = _rect.empty - self.enabled = 1 - self.hilited = 0 - self.selected = 0 - self.text = '' - # - # Size enquiry - # - def minsize(self, m): - try: - self.text = self.text - except NameError: - self.text = '' - return m.textwidth(self.text) + 6, m.lineheight() + 6 - # - def getbounds(self): - return self.bounds - # - # Changing the parameters - # - def settext(self, text): - self.text = text - if self.bounds <> _rect.empty: - self.recalctextpos() - self.redraw() - # - def setbounds(self, bounds): - if self.bounds <> _rect.empty: - self.parent.change(self.bounds) - self.bounds = bounds - if self.bounds <> _rect.empty: - self.recalc() - self.parent.change(bounds) - # - # Changing the state bits - # - def enable(self, flag): - if flag <> self.enabled: - self.enabled = flag - if self.bounds <> _rect.empty: - self.flipenable(self.parent.begindrawing()) - # - def hilite(self, flag): - if flag <> self.hilited: - self.hilited = flag - if self.bounds <> _rect.empty: - self.fliphilite(self.parent.begindrawing()) - # - def select(self, flag): - if flag <> self.selected: - self.selected = flag - if self.bounds <> _rect.empty: - self.redraw() - # - # Recalculate the box bounds and text position. - # This can be overridden by buttons that draw different boxes - # or want their text in a different position. - # - def recalc(self): - if self.bounds <> _rect.empty: - self.recalcbounds() - self.recalctextpos() - # - def recalcbounds(self): - self.hilitebounds = _rect.inset(self.bounds, (3, 3)) - self.crossbounds = self.bounds - # - def recalctextpos(self): - (left, top), (right, bottom) = self.bounds - m = self.parent.beginmeasuring() - h = (left + right - m.textwidth(self.text)) / 2 - v = (top + bottom - m.lineheight()) / 2 - self.textpos = h, v - # - # Generic drawing interface. - # Do not override redraw() or draw() methods; override drawit() c.s. - # - def redraw(self): - if self.bounds <> _rect.empty: - self.draw(self.parent.begindrawing(), self.bounds) - # - def draw(self, (d, area)): - area = _rect.intersect(area, self.bounds) - if area = _rect.empty: - return - d.cliprect(area) - d.erase(self.bounds) - self.drawit(d) - d.noclip() - # - # The drawit() method is fairly generic but may be overridden. - # - def drawit(self, d): - self.drawpict(d) - if self.text: - d.text(self.textpos, self.text) - if not self.enabled: - self.flipenable(d) - if self.hilited: - self.fliphilite(d) - # - # Default drawing detail functions. - # Overriding these is normally sufficient to get different - # appearances. - # - def drawpict(self, d): - pass - # - def flipenable(self, d): - _xorcross(d, self.crossbounds) - # - def fliphilite(self, d): - d.invert(self.hilitebounds) + # + # Initialization + # + def init_appearance(self): + self.bounds = _rect.empty + self.enabled = 1 + self.hilited = 0 + self.selected = 0 + self.text = '' + # + # Size enquiry + # + def minsize(self, m): + try: + self.text = self.text + except NameError: + self.text = '' + return m.textwidth(self.text) + 6, m.lineheight() + 6 + # + def getbounds(self): + return self.bounds + # + # Changing the parameters + # + def settext(self, text): + self.text = text + if self.bounds <> _rect.empty: + self.recalctextpos() + self.redraw() + # + def setbounds(self, bounds): + if self.bounds <> _rect.empty: + self.parent.change(self.bounds) + self.bounds = bounds + if self.bounds <> _rect.empty: + self.recalc() + self.parent.change(bounds) + # + # Changing the state bits + # + def enable(self, flag): + if flag <> self.enabled: + self.enabled = flag + if self.bounds <> _rect.empty: + self.flipenable(self.parent.begindrawing()) + # + def hilite(self, flag): + if flag <> self.hilited: + self.hilited = flag + if self.bounds <> _rect.empty: + self.fliphilite(self.parent.begindrawing()) + # + def select(self, flag): + if flag <> self.selected: + self.selected = flag + if self.bounds <> _rect.empty: + self.redraw() + # + # Recalculate the box bounds and text position. + # This can be overridden by buttons that draw different boxes + # or want their text in a different position. + # + def recalc(self): + if self.bounds <> _rect.empty: + self.recalcbounds() + self.recalctextpos() + # + def recalcbounds(self): + self.hilitebounds = _rect.inset(self.bounds, (3, 3)) + self.crossbounds = self.bounds + # + def recalctextpos(self): + (left, top), (right, bottom) = self.bounds + m = self.parent.beginmeasuring() + h = (left + right - m.textwidth(self.text)) / 2 + v = (top + bottom - m.lineheight()) / 2 + self.textpos = h, v + # + # Generic drawing interface. + # Do not override redraw() or draw() methods; override drawit() c.s. + # + def redraw(self): + if self.bounds <> _rect.empty: + self.draw(self.parent.begindrawing(), self.bounds) + # + def draw(self, (d, area)): + area = _rect.intersect(area, self.bounds) + if area = _rect.empty: + return + d.cliprect(area) + d.erase(self.bounds) + self.drawit(d) + d.noclip() + # + # The drawit() method is fairly generic but may be overridden. + # + def drawit(self, d): + self.drawpict(d) + if self.text: + d.text(self.textpos, self.text) + if not self.enabled: + self.flipenable(d) + if self.hilited: + self.fliphilite(d) + # + # Default drawing detail functions. + # Overriding these is normally sufficient to get different + # appearances. + # + def drawpict(self, d): + pass + # + def flipenable(self, d): + _xorcross(d, self.crossbounds) + # + def fliphilite(self, d): + d.invert(self.hilitebounds) # ButtonAppearance displays a centered string in a box. # selected --> bold border # disabled --> crossed out -# hilited --> inverted +# hilited --> inverted # class ButtonAppearance() = LabelAppearance(): - # - def drawpict(self, d): - d.box(_rect.inset(self.bounds, (1, 1))) - if self.selected: - # Make a thicker box - d.box(self.bounds) - d.box(_rect.inset(self.bounds, (2, 2))) - d.box(_rect.inset(self.bounds, (3, 3))) - # + # + def drawpict(self, d): + d.box(_rect.inset(self.bounds, (1, 1))) + if self.selected: + # Make a thicker box + d.box(self.bounds) + d.box(_rect.inset(self.bounds, (2, 2))) + d.box(_rect.inset(self.bounds, (3, 3))) + # # CheckAppearance displays a small square box and a left-justified string. # selected --> a cross appears in the box # disabled --> whole button crossed out -# hilited --> box is inverted +# hilited --> box is inverted # class CheckAppearance() = LabelAppearance(): - # - def minsize(self, m): - width, height = m.textwidth(self.text) + 6, m.lineheight() + 6 - return width + height + m.textwidth(' '), height - # - def drawpict(self, d): - d.box(self.boxbounds) - if self.selected: _xorcross(d, self.boxbounds) - # - def recalcbounds(self): - LabelAppearance.recalcbounds(self) - (left, top), (right, bottom) = self.bounds - self.size = bottom - top - 4 - self.boxbounds = (left+2, top+2), (left+2+self.size, bottom-2) - self.hilitebounds = self.boxbounds - # - def recalctextpos(self): - m = self.parent.beginmeasuring() - (left, top), (right, bottom) = self.boxbounds - h = right + m.textwidth(' ') - v = top + (self.size - m.lineheight()) / 2 - self.textpos = h, v - # + # + def minsize(self, m): + width, height = m.textwidth(self.text) + 6, m.lineheight() + 6 + return width + height + m.textwidth(' '), height + # + def drawpict(self, d): + d.box(self.boxbounds) + if self.selected: _xorcross(d, self.boxbounds) + # + def recalcbounds(self): + LabelAppearance.recalcbounds(self) + (left, top), (right, bottom) = self.bounds + self.size = bottom - top - 4 + self.boxbounds = (left+2, top+2), (left+2+self.size, bottom-2) + self.hilitebounds = self.boxbounds + # + def recalctextpos(self): + m = self.parent.beginmeasuring() + (left, top), (right, bottom) = self.boxbounds + h = right + m.textwidth(' ') + v = top + (self.size - m.lineheight()) / 2 + self.textpos = h, v + # # RadioAppearance displays a round indicator and a left-justified string. # selected --> a dot appears in the indicator # disabled --> whole button crossed out -# hilited --> indicator is inverted +# hilited --> indicator is inverted # class RadioAppearance() = CheckAppearance(): - # - def drawpict(self, d): - (left, top), (right, bottom) = self.boxbounds - radius = self.size / 2 - h, v = left + radius, top + radius - d.circle((h, v), radius) - if self.selected: - some = radius/3 - d.paint((h-some, v-some), (h+some, v+some)) - # + # + def drawpict(self, d): + (left, top), (right, bottom) = self.boxbounds + radius = self.size / 2 + h, v = left + radius, top + radius + d.circle((h, v), radius) + if self.selected: + some = radius/3 + d.paint((h-some, v-some), (h+some, v+some)) + # # NoReactivity ignores mouse events. # class NoReactivity(): - def init_reactivity(self): pass + def init_reactivity(self): pass # BaseReactivity defines hooks and asks for mouse events, # but provides only dummy mouse event handlers. # The trigger methods call the corresponding hooks set by the user. # Hooks (and triggers) mean the following: -# down_hook called on some mouse-down events -# move_hook called on some mouse-move events -# up_hook called on mouse-up events -# on_hook called for buttons with on/off state, when it goes on -# hook called when a button 'fires' or a radiobutton goes on +# down_hook called on some mouse-down events +# move_hook called on some mouse-move events +# up_hook called on mouse-up events +# on_hook called for buttons with on/off state, when it goes on +# hook called when a button 'fires' or a radiobutton goes on # There are usually extra conditions, e.g., hooks are only called # when the button is enabled, or active, or selected (on). # class BaseReactivity(): - # - def init_reactivity(self): - self.down_hook = self.move_hook = self.up_hook = \ - self.on_hook = self.off_hook = \ - self.hook = self.active = 0 - self.parent.need_mouse(self) - # - def mousetest(self, hv): - return _rect.pointinrect(hv, self.bounds) - # - def mouse_down(self, detail): - pass - # - def mouse_move(self, detail): - pass - # - def mouse_up(self, detail): - pass - # - def down_trigger(self): - if self.down_hook: self.down_hook(self) - # - def move_trigger(self): - if self.move_hook: self.move_hook(self) - # - def up_trigger(self): - if self.up_hook: self.up_hook(self) - # - def on_trigger(self): - if self.on_hook: self.on_hook(self) - # - def off_trigger(self): - if self.off_hook: self.off_hook(self) - # - def trigger(self): - if self.hook: self.hook(self) + # + def init_reactivity(self): + self.down_hook = self.move_hook = self.up_hook = \ + self.on_hook = self.off_hook = \ + self.hook = self.active = 0 + self.parent.need_mouse(self) + # + def mousetest(self, hv): + return _rect.pointinrect(hv, self.bounds) + # + def mouse_down(self, detail): + pass + # + def mouse_move(self, detail): + pass + # + def mouse_up(self, detail): + pass + # + def down_trigger(self): + if self.down_hook: self.down_hook(self) + # + def move_trigger(self): + if self.move_hook: self.move_hook(self) + # + def up_trigger(self): + if self.up_hook: self.up_hook(self) + # + def on_trigger(self): + if self.on_hook: self.on_hook(self) + # + def off_trigger(self): + if self.off_hook: self.off_hook(self) + # + def trigger(self): + if self.hook: self.hook(self) # ToggleReactivity acts like a simple pushbutton. # It toggles its hilite state on mouse down events. # class ToggleReactivity() = BaseReactivity(): - # - def mouse_down(self, detail): - if self.enabled and self.mousetest(detail[_HV]): - self.active = 1 - self.hilite(not self.hilited) - self.down_trigger() - # - def mouse_move(self, detail): - if self.active: - self.move_trigger() - # - def mouse_up(self, detail): - if self.active: - self.up_trigger() - self.active = 0 - # - def down_trigger(self): - if self.hilited: - self.on_trigger() - else: - self.off_trigger() - self.trigger() - # + # + def mouse_down(self, detail): + if self.enabled and self.mousetest(detail[_HV]): + self.active = 1 + self.hilite(not self.hilited) + self.down_trigger() + # + def mouse_move(self, detail): + if self.active: + self.move_trigger() + # + def mouse_up(self, detail): + if self.active: + self.up_trigger() + self.active = 0 + # + def down_trigger(self): + if self.hilited: + self.on_trigger() + else: + self.off_trigger() + self.trigger() + # # TriggerReactivity acts like a fancy pushbutton. # It hilites itself while the mouse is down within its bounds. # class TriggerReactivity() = BaseReactivity(): - # - def mouse_down(self, detail): - if self.enabled and self.mousetest(detail[_HV]): - self.active = 1 - self.hilite(1) - self.down_trigger() - # - def mouse_move(self, detail): - if self.active: - self.hilite(self.mousetest(detail[_HV])) - if self.hilited: - self.move_trigger() - # - def mouse_up(self, detail): - if self.active: - self.hilite(self.mousetest(detail[_HV])) - if self.hilited: - self.up_trigger() - self.trigger() - self.active = 0 - self.hilite(0) - # + # + def mouse_down(self, detail): + if self.enabled and self.mousetest(detail[_HV]): + self.active = 1 + self.hilite(1) + self.down_trigger() + # + def mouse_move(self, detail): + if self.active: + self.hilite(self.mousetest(detail[_HV])) + if self.hilited: + self.move_trigger() + # + def mouse_up(self, detail): + if self.active: + self.hilite(self.mousetest(detail[_HV])) + if self.hilited: + self.up_trigger() + self.trigger() + self.active = 0 + self.hilite(0) + # # CheckReactivity handles mouse events like TriggerReactivity, # It overrides the up_trigger method to flip its selected state. # class CheckReactivity() = TriggerReactivity(): - # - def up_trigger(self): - self.select(not self.selected) - if self.selected: - self.on_trigger() - else: - self.off_trigger() - self.trigger() + # + def up_trigger(self): + self.select(not self.selected) + if self.selected: + self.on_trigger() + else: + self.off_trigger() + self.trigger() # RadioReactivity turns itself on and the other buttons in its group # off when its up_trigger method is called. # class RadioReactivity() = TriggerReactivity(): - # - def init_reactivity(self): - TriggerReactivity.init_reactivity(self) - self.group = [] - # - def up_trigger(self): - for b in self.group: - if b <> self: - if b.selected: - b.select(0) - b.off_trigger() - self.select(1) - self.on_trigger() - self.trigger() + # + def init_reactivity(self): + TriggerReactivity.init_reactivity(self) + self.group = [] + # + def up_trigger(self): + for b in self.group: + if b <> self: + if b.selected: + b.select(0) + b.off_trigger() + self.select(1) + self.on_trigger() + self.trigger() # Auxiliary class for 'define' method. # Call the initializers in the right order. # class Define(): - # - def define(self, parent): - self.parent = parent - parent.addchild(self) - self.init_appearance() - self.init_reactivity() - return self - # - def destroy(self): - self.parent = 0 - # - def definetext(self, (parent, text)): - self = self.define(parent) - self.settext(text) - return self + # + def define(self, parent): + self.parent = parent + parent.addchild(self) + self.init_appearance() + self.init_reactivity() + return self + # + def destroy(self): + self.parent = 0 + # + def definetext(self, (parent, text)): + self = self.define(parent) + self.settext(text) + return self # Subroutine to cross out a rectangle. # def _xorcross(d, bounds): - ((left, top), (right, bottom)) = bounds - # This is s bit funny to make it look better - left = left + 2 - right = right - 2 - top = top + 2 - bottom = bottom - 3 - d.xorline(((left, top), (right, bottom))) - d.xorline((left, bottom), (right, top)) + ((left, top), (right, bottom)) = bounds + # This is s bit funny to make it look better + left = left + 2 + right = right - 2 + top = top + 2 + bottom = bottom - 3 + d.xorline(((left, top), (right, bottom))) + d.xorline((left, bottom), (right, top)) # Ready-made button classes. diff --git a/lib/CSplit.py b/lib/CSplit.py index a28b1c8..03559c1 100644 --- a/lib/CSplit.py +++ b/lib/CSplit.py @@ -1,70 +1,70 @@ # A CSplit is a Clock-shaped split: the children are grouped in a circle. # The numbering is a little different from a real clock: the 12 o'clock -# position is called 0, not 12. This is a little easier since Python -# usually counts from zero. (BTW, there needn't be exactly 12 children.) +# position is called 0, not 12. This is a little easier since Python +# usually counts from zero. (BTW, there needn't be exactly 12 children.) from math import pi, sin, cos from Split import Split class CSplit() = Split(): - # - def minsize(self, m): - # Since things look best if the children are spaced evenly - # along the circle (and often all children have the same - # size anyway) we compute the max child size and assume - # this is each child's size. - width, height = 0, 0 - for child in self.children: - wi, he = child.minsize(m) - width = max(width, wi) - height = max(height, he) - # In approximation, the diameter of the circle we need is - # (diameter of box) * (#children) / pi. - # We approximate pi by 3 (so we slightly overestimate - # our minimal size requirements -- not so bad). - # Because the boxes stick out of the circle we add the - # box size to each dimension. - # Because we really deal with ellipses, do everything - # separate in each dimension. - n = len(self.children) - return width + (width*n + 2)/3, height + (height*n + 2)/3 - # - def getbounds(self): - return self.bounds - # - def setbounds(self, bounds): - self.bounds = bounds - # Place the children. This involves some math. - # Compute center positions for children as if they were - # ellipses with a diameter about 1/N times the - # circumference of the big ellipse. - # (There is some rounding involved to make it look - # reasonable for small and large N alike.) - # XXX One day Python will have automatic conversions... - n = len(self.children) - fn = float(n) - if n = 0: return - (left, top), (right, bottom) = bounds - width, height = right-left, bottom-top - child_width, child_height = width*3/(n+4), height*3/(n+4) - half_width, half_height = \ - float(width-child_width)/2.0, \ - float(height-child_height)/2.0 - center_h, center_v = center = (left+right)/2, (top+bottom)/2 - fch, fcv = float(center_h), float(center_v) - alpha = 2.0 * pi / fn - for i in range(n): - child = self.children[i] - fi = float(i) - fh, fv = \ - fch + half_width*sin(fi*alpha), \ - fcv - half_height*cos(fi*alpha) - left, top = \ - int(fh) - child_width/2, \ - int(fv) - child_height/2 - right, bottom = \ - left + child_width, \ - top + child_height - child.setbounds((left, top), (right, bottom)) - # + # + def minsize(self, m): + # Since things look best if the children are spaced evenly + # along the circle (and often all children have the same + # size anyway) we compute the max child size and assume + # this is each child's size. + width, height = 0, 0 + for child in self.children: + wi, he = child.minsize(m) + width = max(width, wi) + height = max(height, he) + # In approximation, the diameter of the circle we need is + # (diameter of box) * (#children) / pi. + # We approximate pi by 3 (so we slightly overestimate + # our minimal size requirements -- not so bad). + # Because the boxes stick out of the circle we add the + # box size to each dimension. + # Because we really deal with ellipses, do everything + # separate in each dimension. + n = len(self.children) + return width + (width*n + 2)/3, height + (height*n + 2)/3 + # + def getbounds(self): + return self.bounds + # + def setbounds(self, bounds): + self.bounds = bounds + # Place the children. This involves some math. + # Compute center positions for children as if they were + # ellipses with a diameter about 1/N times the + # circumference of the big ellipse. + # (There is some rounding involved to make it look + # reasonable for small and large N alike.) + # XXX One day Python will have automatic conversions... + n = len(self.children) + fn = float(n) + if n = 0: return + (left, top), (right, bottom) = bounds + width, height = right-left, bottom-top + child_width, child_height = width*3/(n+4), height*3/(n+4) + half_width, half_height = \ + float(width-child_width)/2.0, \ + float(height-child_height)/2.0 + center_h, center_v = center = (left+right)/2, (top+bottom)/2 + fch, fcv = float(center_h), float(center_v) + alpha = 2.0 * pi / fn + for i in range(n): + child = self.children[i] + fi = float(i) + fh, fv = \ + fch + half_width*sin(fi*alpha), \ + fcv - half_height*cos(fi*alpha) + left, top = \ + int(fh) - child_width/2, \ + int(fv) - child_height/2 + right, bottom = \ + left + child_width, \ + top + child_height + child.setbounds((left, top), (right, bottom)) + # diff --git a/lib/DEVICE.py b/lib/DEVICE.py index 4f2fadc..00eddfc 100644 --- a/lib/DEVICE.py +++ b/lib/DEVICE.py @@ -1,17 +1,17 @@ #/************************************************************************** -# * * -# * Copyright (C) 1984, Silicon Graphics, Inc. * -# * * -# * These coded instructions, statements, and computer programs contain * -# * unpublished proprietary information of Silicon Graphics, Inc., and * -# * are protected by Federal copyright law. They may not be disclosed * -# * to third parties or copied or duplicated in any form, in whole or * -# * in part, without the prior written consent of Silicon Graphics, Inc. * -# * * +# * * +# * Copyright (C) 1984, Silicon Graphics, Inc. * +# * * +# * These coded instructions, statements, and computer programs contain * +# * unpublished proprietary information of Silicon Graphics, Inc., and * +# * are protected by Federal copyright law. They may not be disclosed * +# * to third parties or copied or duplicated in any form, in whole or * +# * in part, without the prior written consent of Silicon Graphics, Inc. * +# * * # **************************************************************************/ #/* file with device definitions (see /usr/include/device.h) */ -NULLDEV = 0 +NULLDEV = 0 BUTOFFSET = 1 VALOFFSET = 256 TIMOFFSET = 515 @@ -22,402 +22,402 @@ BUTCOUNT = 190 VALCOUNT = 27 TIMCOUNT = 4 XKBDCOUNT = 28 -INCOUNT = 8 +INCOUNT = 8 OUTCOUNT = 8 # # # # -BUT0 = 1 -BUT1 = 2 -BUT2 = 3 -BUT3 = 4 -BUT4 = 5 -BUT5 = 6 -BUT6 = 7 -BUT7 = 8 -BUT8 = 9 -BUT9 = 10 -BUT10 = 11 -BUT11 = 12 -BUT12 = 13 -BUT13 = 14 -BUT14 = 15 -BUT15 = 16 -BUT16 = 17 -BUT17 = 18 -BUT18 = 19 -BUT19 = 20 -BUT20 = 21 -BUT21 = 22 -BUT22 = 23 -BUT23 = 24 -BUT24 = 25 -BUT25 = 26 -BUT26 = 27 -BUT27 = 28 -BUT28 = 29 -BUT29 = 30 -BUT30 = 31 -BUT31 = 32 -BUT32 = 33 -BUT33 = 34 -BUT34 = 35 -BUT35 = 36 -BUT36 = 37 -BUT37 = 38 -BUT38 = 39 -BUT39 = 40 -BUT40 = 41 -BUT41 = 42 -BUT42 = 43 -BUT43 = 44 -BUT44 = 45 -BUT45 = 46 -BUT46 = 47 -BUT47 = 48 -BUT48 = 49 -BUT49 = 50 -BUT50 = 51 -BUT51 = 52 -BUT52 = 53 -BUT53 = 54 -BUT54 = 55 -BUT55 = 56 -BUT56 = 57 -BUT57 = 58 -BUT58 = 59 -BUT59 = 60 -BUT60 = 61 -BUT61 = 62 -BUT62 = 63 -BUT63 = 64 -BUT64 = 65 -BUT65 = 66 -BUT66 = 67 -BUT67 = 68 -BUT68 = 69 -BUT69 = 70 -BUT70 = 71 -BUT71 = 72 -BUT72 = 73 -BUT73 = 74 -BUT74 = 75 -BUT75 = 76 -BUT76 = 77 -BUT77 = 78 -BUT78 = 79 -BUT79 = 80 -BUT80 = 81 -BUT81 = 82 -BUT82 = 83 -MAXKBDBUT = 83 -BUT100 = 101 -BUT101 = 102 -BUT102 = 103 -BUT110 = 111 -BUT111 = 112 -BUT112 = 113 -BUT113 = 114 -BUT114 = 115 -BUT115 = 116 -BUT116 = 117 -BUT117 = 118 -BUT118 = 119 -BUT119 = 120 -BUT120 = 121 -BUT121 = 122 -BUT122 = 123 -BUT123 = 124 -BUT124 = 125 -BUT125 = 126 -BUT126 = 127 -BUT127 = 128 -BUT128 = 129 -BUT129 = 130 -BUT130 = 131 -BUT131 = 132 -BUT132 = 133 -BUT133 = 134 -BUT134 = 135 -BUT135 = 136 -BUT136 = 137 -BUT137 = 138 -BUT138 = 139 -BUT139 = 140 -BUT140 = 141 -BUT141 = 142 -BUT142 = 143 -BUT143 = 144 -BUT144 = 145 -BUT145 = 146 -BUT146 = 147 -BUT147 = 148 -BUT148 = 149 -BUT149 = 150 -BUT150 = 151 -BUT151 = 152 -BUT152 = 153 -BUT153 = 154 -BUT154 = 155 -BUT155 = 156 -BUT156 = 157 -BUT157 = 158 -BUT158 = 159 -BUT159 = 160 -BUT160 = 161 -BUT161 = 162 -BUT162 = 163 -BUT163 = 164 -BUT164 = 165 -BUT165 = 166 -BUT166 = 167 -BUT167 = 168 -BUT168 = 169 -BUT181 = 182 -BUT182 = 183 -BUT183 = 184 -BUT184 = 185 -BUT185 = 186 -BUT186 = 187 -BUT187 = 188 -BUT188 = 189 -BUT189 = 190 -MOUSE1 = 101 -MOUSE2 = 102 -MOUSE3 = 103 -LEFTMOUSE = 103 -MIDDLEMOUSE = 102 -RIGHTMOUSE = 101 -LPENBUT = 104 -BPAD0 = 105 -BPAD1 = 106 -BPAD2 = 107 -BPAD3 = 108 -LPENVALID = 109 -SWBASE = 111 -SW0 = 111 -SW1 = 112 -SW2 = 113 -SW3 = 114 -SW4 = 115 -SW5 = 116 -SW6 = 117 -SW7 = 118 -SW8 = 119 -SW9 = 120 -SW10 = 121 -SW11 = 122 -SW12 = 123 -SW13 = 124 -SW14 = 125 -SW15 = 126 -SW16 = 127 -SW17 = 128 -SW18 = 129 -SW19 = 130 -SW20 = 131 -SW21 = 132 -SW22 = 133 -SW23 = 134 -SW24 = 135 -SW25 = 136 -SW26 = 137 -SW27 = 138 -SW28 = 139 -SW29 = 140 -SW30 = 141 -SW31 = 142 -SBBASE = 182 -SBPICK = 182 -SBBUT1 = 183 -SBBUT2 = 184 -SBBUT3 = 185 -SBBUT4 = 186 -SBBUT5 = 187 -SBBUT6 = 188 -SBBUT7 = 189 -SBBUT8 = 190 -AKEY = 11 -BKEY = 36 -CKEY = 28 -DKEY = 18 -EKEY = 17 -FKEY = 19 -GKEY = 26 -HKEY = 27 -IKEY = 40 -JKEY = 34 -KKEY = 35 -LKEY = 42 -MKEY = 44 -NKEY = 37 -OKEY = 41 -PKEY = 48 -QKEY = 10 -RKEY = 24 -SKEY = 12 -TKEY = 25 -UKEY = 33 -VKEY = 29 -WKEY = 16 -XKEY = 21 -YKEY = 32 -ZKEY = 20 -ZEROKEY = 46 -ONEKEY = 8 -TWOKEY = 14 -THREEKEY = 15 -FOURKEY = 22 -FIVEKEY = 23 -SIXKEY = 30 -SEVENKEY = 31 -EIGHTKEY = 38 -NINEKEY = 39 -BREAKKEY = 1 -SETUPKEY = 2 -CTRLKEY = 3 -LEFTCTRLKEY = CTRLKEY -CAPSLOCKKEY = 4 -RIGHTSHIFTKEY = 5 -LEFTSHIFTKEY = 6 -NOSCRLKEY = 13 -ESCKEY = 7 -TABKEY = 9 -RETKEY = 51 -SPACEKEY = 83 -LINEFEEDKEY = 60 -BACKSPACEKEY = 61 -DELKEY = 62 -SEMICOLONKEY = 43 -PERIODKEY = 52 -COMMAKEY = 45 -QUOTEKEY = 50 -ACCENTGRAVEKEY = 55 -MINUSKEY = 47 -VIRGULEKEY = 53 -BACKSLASHKEY = 57 -EQUALKEY = 54 -LEFTBRACKETKEY = 49 -RIGHTBRACKETKEY = 56 -LEFTARROWKEY = 73 -DOWNARROWKEY = 74 -RIGHTARROWKEY = 80 -UPARROWKEY = 81 -PAD0 = 59 -PAD1 = 58 -PAD2 = 64 -PAD3 = 65 -PAD4 = 63 -PAD5 = 69 -PAD6 = 70 -PAD7 = 67 -PAD8 = 68 -PAD9 = 75 -PADPF1 = 72 -PADPF2 = 71 -PADPF3 = 79 -PADPF4 = 78 -PADPERIOD = 66 -PADMINUS = 76 -PADCOMMA = 77 -PADENTER = 82 -LEFTALTKEY = 143 -RIGHTALTKEY = 144 -RIGHTCTRLKEY = 145 -F1KEY = 146 -F2KEY = 147 -F3KEY = 148 -F4KEY = 149 -F5KEY = 150 -F6KEY = 151 -F7KEY = 152 -F8KEY = 153 -F9KEY = 154 -F10KEY = 155 -F11KEY = 156 -F12KEY = 157 +BUT0 = 1 +BUT1 = 2 +BUT2 = 3 +BUT3 = 4 +BUT4 = 5 +BUT5 = 6 +BUT6 = 7 +BUT7 = 8 +BUT8 = 9 +BUT9 = 10 +BUT10 = 11 +BUT11 = 12 +BUT12 = 13 +BUT13 = 14 +BUT14 = 15 +BUT15 = 16 +BUT16 = 17 +BUT17 = 18 +BUT18 = 19 +BUT19 = 20 +BUT20 = 21 +BUT21 = 22 +BUT22 = 23 +BUT23 = 24 +BUT24 = 25 +BUT25 = 26 +BUT26 = 27 +BUT27 = 28 +BUT28 = 29 +BUT29 = 30 +BUT30 = 31 +BUT31 = 32 +BUT32 = 33 +BUT33 = 34 +BUT34 = 35 +BUT35 = 36 +BUT36 = 37 +BUT37 = 38 +BUT38 = 39 +BUT39 = 40 +BUT40 = 41 +BUT41 = 42 +BUT42 = 43 +BUT43 = 44 +BUT44 = 45 +BUT45 = 46 +BUT46 = 47 +BUT47 = 48 +BUT48 = 49 +BUT49 = 50 +BUT50 = 51 +BUT51 = 52 +BUT52 = 53 +BUT53 = 54 +BUT54 = 55 +BUT55 = 56 +BUT56 = 57 +BUT57 = 58 +BUT58 = 59 +BUT59 = 60 +BUT60 = 61 +BUT61 = 62 +BUT62 = 63 +BUT63 = 64 +BUT64 = 65 +BUT65 = 66 +BUT66 = 67 +BUT67 = 68 +BUT68 = 69 +BUT69 = 70 +BUT70 = 71 +BUT71 = 72 +BUT72 = 73 +BUT73 = 74 +BUT74 = 75 +BUT75 = 76 +BUT76 = 77 +BUT77 = 78 +BUT78 = 79 +BUT79 = 80 +BUT80 = 81 +BUT81 = 82 +BUT82 = 83 +MAXKBDBUT = 83 +BUT100 = 101 +BUT101 = 102 +BUT102 = 103 +BUT110 = 111 +BUT111 = 112 +BUT112 = 113 +BUT113 = 114 +BUT114 = 115 +BUT115 = 116 +BUT116 = 117 +BUT117 = 118 +BUT118 = 119 +BUT119 = 120 +BUT120 = 121 +BUT121 = 122 +BUT122 = 123 +BUT123 = 124 +BUT124 = 125 +BUT125 = 126 +BUT126 = 127 +BUT127 = 128 +BUT128 = 129 +BUT129 = 130 +BUT130 = 131 +BUT131 = 132 +BUT132 = 133 +BUT133 = 134 +BUT134 = 135 +BUT135 = 136 +BUT136 = 137 +BUT137 = 138 +BUT138 = 139 +BUT139 = 140 +BUT140 = 141 +BUT141 = 142 +BUT142 = 143 +BUT143 = 144 +BUT144 = 145 +BUT145 = 146 +BUT146 = 147 +BUT147 = 148 +BUT148 = 149 +BUT149 = 150 +BUT150 = 151 +BUT151 = 152 +BUT152 = 153 +BUT153 = 154 +BUT154 = 155 +BUT155 = 156 +BUT156 = 157 +BUT157 = 158 +BUT158 = 159 +BUT159 = 160 +BUT160 = 161 +BUT161 = 162 +BUT162 = 163 +BUT163 = 164 +BUT164 = 165 +BUT165 = 166 +BUT166 = 167 +BUT167 = 168 +BUT168 = 169 +BUT181 = 182 +BUT182 = 183 +BUT183 = 184 +BUT184 = 185 +BUT185 = 186 +BUT186 = 187 +BUT187 = 188 +BUT188 = 189 +BUT189 = 190 +MOUSE1 = 101 +MOUSE2 = 102 +MOUSE3 = 103 +LEFTMOUSE = 103 +MIDDLEMOUSE = 102 +RIGHTMOUSE = 101 +LPENBUT = 104 +BPAD0 = 105 +BPAD1 = 106 +BPAD2 = 107 +BPAD3 = 108 +LPENVALID = 109 +SWBASE = 111 +SW0 = 111 +SW1 = 112 +SW2 = 113 +SW3 = 114 +SW4 = 115 +SW5 = 116 +SW6 = 117 +SW7 = 118 +SW8 = 119 +SW9 = 120 +SW10 = 121 +SW11 = 122 +SW12 = 123 +SW13 = 124 +SW14 = 125 +SW15 = 126 +SW16 = 127 +SW17 = 128 +SW18 = 129 +SW19 = 130 +SW20 = 131 +SW21 = 132 +SW22 = 133 +SW23 = 134 +SW24 = 135 +SW25 = 136 +SW26 = 137 +SW27 = 138 +SW28 = 139 +SW29 = 140 +SW30 = 141 +SW31 = 142 +SBBASE = 182 +SBPICK = 182 +SBBUT1 = 183 +SBBUT2 = 184 +SBBUT3 = 185 +SBBUT4 = 186 +SBBUT5 = 187 +SBBUT6 = 188 +SBBUT7 = 189 +SBBUT8 = 190 +AKEY = 11 +BKEY = 36 +CKEY = 28 +DKEY = 18 +EKEY = 17 +FKEY = 19 +GKEY = 26 +HKEY = 27 +IKEY = 40 +JKEY = 34 +KKEY = 35 +LKEY = 42 +MKEY = 44 +NKEY = 37 +OKEY = 41 +PKEY = 48 +QKEY = 10 +RKEY = 24 +SKEY = 12 +TKEY = 25 +UKEY = 33 +VKEY = 29 +WKEY = 16 +XKEY = 21 +YKEY = 32 +ZKEY = 20 +ZEROKEY = 46 +ONEKEY = 8 +TWOKEY = 14 +THREEKEY = 15 +FOURKEY = 22 +FIVEKEY = 23 +SIXKEY = 30 +SEVENKEY = 31 +EIGHTKEY = 38 +NINEKEY = 39 +BREAKKEY = 1 +SETUPKEY = 2 +CTRLKEY = 3 +LEFTCTRLKEY = CTRLKEY +CAPSLOCKKEY = 4 +RIGHTSHIFTKEY = 5 +LEFTSHIFTKEY = 6 +NOSCRLKEY = 13 +ESCKEY = 7 +TABKEY = 9 +RETKEY = 51 +SPACEKEY = 83 +LINEFEEDKEY = 60 +BACKSPACEKEY = 61 +DELKEY = 62 +SEMICOLONKEY = 43 +PERIODKEY = 52 +COMMAKEY = 45 +QUOTEKEY = 50 +ACCENTGRAVEKEY = 55 +MINUSKEY = 47 +VIRGULEKEY = 53 +BACKSLASHKEY = 57 +EQUALKEY = 54 +LEFTBRACKETKEY = 49 +RIGHTBRACKETKEY = 56 +LEFTARROWKEY = 73 +DOWNARROWKEY = 74 +RIGHTARROWKEY = 80 +UPARROWKEY = 81 +PAD0 = 59 +PAD1 = 58 +PAD2 = 64 +PAD3 = 65 +PAD4 = 63 +PAD5 = 69 +PAD6 = 70 +PAD7 = 67 +PAD8 = 68 +PAD9 = 75 +PADPF1 = 72 +PADPF2 = 71 +PADPF3 = 79 +PADPF4 = 78 +PADPERIOD = 66 +PADMINUS = 76 +PADCOMMA = 77 +PADENTER = 82 +LEFTALTKEY = 143 +RIGHTALTKEY = 144 +RIGHTCTRLKEY = 145 +F1KEY = 146 +F2KEY = 147 +F3KEY = 148 +F4KEY = 149 +F5KEY = 150 +F6KEY = 151 +F7KEY = 152 +F8KEY = 153 +F9KEY = 154 +F10KEY = 155 +F11KEY = 156 +F12KEY = 157 PRINTSCREENKEY = 158 SCROLLLOCKKEY = 159 PAUSEKEY = 160 INSERTKEY = 161 -HOMEKEY = 162 -PAGEUPKEY = 163 -ENDKEY = 164 +HOMEKEY = 162 +PAGEUPKEY = 163 +ENDKEY = 164 PAGEDOWNKEY = 165 NUMLOCKKEY = 166 -PADVIRGULEKEY = 167 -PADASTERKEY = 168 -PADPLUSKEY = 169 -SGIRESERVED = 256 -DIAL0 = 257 -DIAL1 = 258 -DIAL2 = 259 -DIAL3 = 260 -DIAL4 = 261 -DIAL5 = 262 -DIAL6 = 263 -DIAL7 = 264 -DIAL8 = 265 -MOUSEX = 266 -MOUSEY = 267 -LPENX = 268 -LPENY = 269 -BPADX = 270 -BPADY = 271 -CURSORX = 272 -CURSORY = 273 -GHOSTX = 274 -GHOSTY = 275 -SBTX = 276 -SBTY = 277 -SBTZ = 278 -SBRX = 279 -SBRY = 280 -SBRZ = 281 -SBPERIOD = 282 -TIMER0 = 515 -TIMER1 = 516 -TIMER2 = 517 -TIMER3 = 518 -KEYBD = 513 -RAWKEYBD = 514 -VALMARK = 523 -GERROR = 524 -REDRAW = 528 -WMSEND = 529 -WMREPLY = 530 -WMGFCLOSE = 531 -WMTXCLOSE = 532 -MODECHANGE = 533 -INPUTCHANGE = 534 -QFULL = 535 -PIECECHANGE = 536 -WINCLOSE = 537 -QREADERROR = 538 -WINFREEZE = 539 -WINTHAW = 540 -REDRAWICONIC = 541 -WINQUIT = 542 -DEPTHCHANGE = 543 -KEYBDFNAMES = 544 -KEYBDFSTRINGS = 545 -WINSHUT = 546 -INPUT0 = 1024 -INPUT1 = 1025 -INPUT2 = 1026 -INPUT3 = 1027 -INPUT4 = 1028 -INPUT5 = 1029 -INPUT6 = 1030 -INPUT7 = 1032 -OUTPUT0 = 1033 -OUTPUT1 = 1034 -OUTPUT2 = 1035 -OUTPUT3 = 1036 -OUTPUT4 = 1037 -OUTPUT5 = 1038 -OUTPUT6 = 1039 -OUTPUT7 = 1040 +PADVIRGULEKEY = 167 +PADASTERKEY = 168 +PADPLUSKEY = 169 +SGIRESERVED = 256 +DIAL0 = 257 +DIAL1 = 258 +DIAL2 = 259 +DIAL3 = 260 +DIAL4 = 261 +DIAL5 = 262 +DIAL6 = 263 +DIAL7 = 264 +DIAL8 = 265 +MOUSEX = 266 +MOUSEY = 267 +LPENX = 268 +LPENY = 269 +BPADX = 270 +BPADY = 271 +CURSORX = 272 +CURSORY = 273 +GHOSTX = 274 +GHOSTY = 275 +SBTX = 276 +SBTY = 277 +SBTZ = 278 +SBRX = 279 +SBRY = 280 +SBRZ = 281 +SBPERIOD = 282 +TIMER0 = 515 +TIMER1 = 516 +TIMER2 = 517 +TIMER3 = 518 +KEYBD = 513 +RAWKEYBD = 514 +VALMARK = 523 +GERROR = 524 +REDRAW = 528 +WMSEND = 529 +WMREPLY = 530 +WMGFCLOSE = 531 +WMTXCLOSE = 532 +MODECHANGE = 533 +INPUTCHANGE = 534 +QFULL = 535 +PIECECHANGE = 536 +WINCLOSE = 537 +QREADERROR = 538 +WINFREEZE = 539 +WINTHAW = 540 +REDRAWICONIC = 541 +WINQUIT = 542 +DEPTHCHANGE = 543 +KEYBDFNAMES = 544 +KEYBDFSTRINGS = 545 +WINSHUT = 546 +INPUT0 = 1024 +INPUT1 = 1025 +INPUT2 = 1026 +INPUT3 = 1027 +INPUT4 = 1028 +INPUT5 = 1029 +INPUT6 = 1030 +INPUT7 = 1032 +OUTPUT0 = 1033 +OUTPUT1 = 1034 +OUTPUT2 = 1035 +OUTPUT3 = 1036 +OUTPUT4 = 1037 +OUTPUT5 = 1038 +OUTPUT6 = 1039 +OUTPUT7 = 1040 MAXSGIDEVICE = 20000 -MENUBUTTON = RIGHTMOUSE +MENUBUTTON = RIGHTMOUSE @@ -1,15 +1,15 @@ # Constants defined in <gl.h> #************************************************************************** -#* * -#* Copyright (C) 1984, Silicon Graphics, Inc. * -#* * -#* These coded instructions, statements, and computer programs contain * -#* unpublished proprietary information of Silicon Graphics, Inc., and * -#* are protected by Federal copyright law. They may not be disclosed * -#* to third parties or copied or duplicated in any form, in whole or * -#* in part, without the prior written consent of Silicon Graphics, Inc. * -#* * +#* * +#* Copyright (C) 1984, Silicon Graphics, Inc. * +#* * +#* These coded instructions, statements, and computer programs contain * +#* unpublished proprietary information of Silicon Graphics, Inc., and * +#* are protected by Federal copyright law. They may not be disclosed * +#* to third parties or copied or duplicated in any form, in whole or * +#* in part, without the prior written consent of Silicon Graphics, Inc. * +#* * #************************************************************************** # Graphics Libary constants @@ -18,17 +18,17 @@ TRUE = 1 FALSE = 0 -# maximum X and Y screen coordinates +# maximum X and Y screen coordinates XMAXSCREEN = 1279 YMAXSCREEN = 1023 -XMAXMEDIUM = 1023 # max for medium res monitor +XMAXMEDIUM = 1023 # max for medium res monitor YMAXMEDIUM = 767 -XMAX170 = 645 # max for RS-170 +XMAX170 = 645 # max for RS-170 YMAX170 = 484 -XMAXPAL = 779 # max for PAL +XMAXPAL = 779 # max for PAL YMAXPAL = 574 -# various hardware/software limits +# various hardware/software limits ATTRIBSTACKDEPTH = 10 VPSTACKDEPTH = 8 MATRIXSTACKDEPTH = 32 @@ -37,7 +37,7 @@ STARTTAG = -2 ENDTAG = -3 CPOSX_INVALID = -(2*XMAXSCREEN) -# names for colors in color map loaded by greset +# names for colors in color map loaded by greset BLACK = 0 RED = 1 GREEN = 2 @@ -47,20 +47,20 @@ MAGENTA = 5 CYAN = 6 WHITE = 7 -# popup colors +# popup colors PUP_CLEAR = 0 PUP_COLOR = 1 PUP_BLACK = 2 PUP_WHITE = 3 -# defines for drawmode +# defines for drawmode NORMALDRAW = 0 PUPDRAW = 1 OVERDRAW = 2 UNDERDRAW = 3 CURSORDRAW = 4 -# defines for defpattern +# defines for defpattern PATTERN_16 = 16 PATTERN_32 = 32 PATTERN_64 = 64 @@ -69,7 +69,7 @@ PATTERN_16_SIZE = 16 PATTERN_32_SIZE = 64 PATTERN_64_SIZE = 256 -# defines for readsource +# defines for readsource SRC_AUTO = 0 SRC_FRONT = 1 SRC_BACK = 2 @@ -79,7 +79,7 @@ SRC_OVER = 5 SRC_UNDER = 6 SRC_FRAMEGRABBER = 7 -# defines for blendfunction +# defines for blendfunction BF_ZERO = 0 BF_ONE = 1 BF_DC = 2 @@ -91,7 +91,7 @@ BF_MSA = 5 BF_DA = 6 BF_MDA = 7 -# defines for zfunction +# defines for zfunction ZF_NEVER = 0 ZF_LESS = 1 ZF_EQUAL = 2 @@ -101,38 +101,38 @@ ZF_NOTEQUAL = 5 ZF_GEQUAL = 6 ZF_ALWAYS = 7 -# defines for zsource +# defines for zsource ZSRC_DEPTH = 0 ZSRC_COLOR = 1 -# defines for pntsmooth +# defines for pntsmooth SMP_OFF = 0 SMP_ON = 1 -# defines for linesmooth +# defines for linesmooth SML_OFF = 0 SML_ON = 1 -# defines for setpup +# defines for setpup PUP_NONE = 0 PUP_GREY = 1 -# defines for glcompat +# defines for glcompat GLC_OLDPOLYGON = 0 GLC_ZRANGEMAP = 1 -# defines for curstype +# defines for curstype C16X1 = 0 C16X2 = 1 C32X1 = 2 C32X2 = 3 CCROSS = 4 -# defines for shademodel +# defines for shademodel FLAT = 0 GOURAUD = 1 -# defines for logicop +# defines for logicop ### LO_ZERO = 0x0 ### LO_AND = 0x1 ### LO_ANDR = 0x2 @@ -152,7 +152,7 @@ GOURAUD = 1 # -# START defines for getgdesc +# START defines for getgdesc # GD_XPMAX = 0 @@ -175,7 +175,7 @@ GD_BITS_NORM_ZBUFFER = 16 GD_BITS_OVER_SNG_CMODE = 17 GD_BITS_UNDR_SNG_CMODE = 18 GD_BITS_PUP_SNG_CMODE = 19 -GD_BITS_NORM_SNG_ALPHA = 21 +GD_BITS_NORM_SNG_ALPHA = 21 GD_BITS_NORM_DBL_ALPHA = 22 GD_BITS_CURSOR = 23 GD_OVERUNDER_SHARED = 24 @@ -234,16 +234,16 @@ GD_WSYS_4S = 1 GD_SCRNTYPE_WM = 0 GD_SCRNTYPE_NOWM = 1 -# -# END defines for getgdesc +# +# END defines for getgdesc # -# -# START NURBS interface definitions +# +# START NURBS interface definitions # -# NURBS Rendering Properties +# NURBS Rendering Properties N_PIXEL_TOLERANCE = 1 N_CULLING = 2 N_DISPLAY = 3 @@ -253,59 +253,59 @@ N_S_STEPS = 6 N_T_STEPS = 7 N_TILES = 8 -N_SHADED = 1.0 +N_SHADED = 1.0 # --------------------------------------------------------------------------- -# FLAGS FOR NURBS SURFACES AND CURVES -# -# Bit: 9876 5432 1 0 -# |tttt|nnnn|f|r| : r - 1 bit = 1 if rational coordinate exists -# : f - 1 bit = 1 if rational coordinate is before rest -# : = 0 if rational coordinate is after rest -# : nnnn - 4 bits for number of coordinates -# : tttt - 4 bits for type of data (color, position, etc.) -# +# FLAGS FOR NURBS SURFACES AND CURVES +# +# Bit: 9876 5432 1 0 +# |tttt|nnnn|f|r| : r - 1 bit = 1 if rational coordinate exists +# : f - 1 bit = 1 if rational coordinate is before rest +# : = 0 if rational coordinate is after rest +# : nnnn - 4 bits for number of coordinates +# : tttt - 4 bits for type of data (color, position, etc.) +# # NURBS data type -# N_T_ST 0 parametric space data -# N_T_XYZ 1 model space data -# -# rational or non-rational data and position in memory -# N_NONRATIONAL 0 non-rational data -# N_RATAFTER 1 rational data with rat coord after rest -# N_RATBEFORE 3 rational data with rat coord before rest -# +# N_T_ST 0 parametric space data +# N_T_XYZ 1 model space data +# +# rational or non-rational data and position in memory +# N_NONRATIONAL 0 non-rational data +# N_RATAFTER 1 rational data with rat coord after rest +# N_RATBEFORE 3 rational data with rat coord before rest +# # N_MKFLAG(a,b,c) ((a<<6) | (b<<2) | c) -# +# # --------------------------------------------------------------------------- -# -N_ST = 0x8 # N_MKFLAG( N_T_ST, 2, N_NONRATIONAL ) -N_STW = 0xd # N_MKFLAG( N_T_ST, 3, N_RATAFTER ) -N_WST = 0xf # N_MKFLAG( N_T_ST, 3, N_RATBEFORE ) -N_XYZ = 0x4c # N_MKFLAG( N_T_XYZ, 3, N_NONRATIONAL ) -N_XYZW = 0x51 # N_MKFLAG( N_T_XYZ, 4, N_RATAFTER ) -N_WXYZ = 0x53 # N_MKFLAG( N_T_XYZ, 4, N_RATBEFORE ) +# +N_ST = 0x8 # N_MKFLAG( N_T_ST, 2, N_NONRATIONAL ) +N_STW = 0xd # N_MKFLAG( N_T_ST, 3, N_RATAFTER ) +N_WST = 0xf # N_MKFLAG( N_T_ST, 3, N_RATBEFORE ) +N_XYZ = 0x4c # N_MKFLAG( N_T_XYZ, 3, N_NONRATIONAL ) +N_XYZW = 0x51 # N_MKFLAG( N_T_XYZ, 4, N_RATAFTER ) +N_WXYZ = 0x53 # N_MKFLAG( N_T_XYZ, 4, N_RATBEFORE ) -# -# END NURBS interface definitions -# +# +# END NURBS interface definitions +# -# -# START lighting model defines -# +# +# START lighting model defines +# LMNULL = 0.0 -# MATRIX modes +# MATRIX modes MSINGLE = 0 MPROJECTION = 1 MVIEWING = 2 -# LIGHT constants +# LIGHT constants MAXLIGHTS = 8 MAXRESTRICTIONS = 4 -# MATERIAL properties +# MATERIAL properties DEFMATERIAL = 0 EMISSION = 1 AMBIENT = 2 @@ -315,17 +315,17 @@ SHININESS = 5 COLORINDEXES = 6 ALPHA = 7 -# LIGHT properties +# LIGHT properties DEFLIGHT = 100 LCOLOR = 101 POSITION = 102 -# LIGHTINGMODEL properties +# LIGHTINGMODEL properties DEFLMODEL = 200 LOCALVIEWER = 201 ATTENUATION = 202 -# TARGET constants +# TARGET constants MATERIAL = 1000 LIGHT0 = 1100 LIGHT1 = 1101 @@ -337,7 +337,7 @@ LIGHT6 = 1106 LIGHT7 = 1107 LMODEL = 1200 -# lmcolor modes +# lmcolor modes LMC_COLOR = 0 LMC_EMISSION = 1 LMC_AMBIENT = 2 @@ -346,20 +346,20 @@ LMC_SPECULAR = 4 LMC_AD = 5 LMC_NULL = 6 -# -# END lighting model defines -# +# +# END lighting model defines +# -# -# START distributed graphics library defines -# +# +# START distributed graphics library defines +# -DGLSINK = 0 # sink connection -DGLLOCAL = 1 # local connection -DGLTSOCKET = 2 # tcp socket connection -DGL4DDN = 3 # 4DDN (DECnet) +DGLSINK = 0 # sink connection +DGLLOCAL = 1 # local connection +DGLTSOCKET = 2 # tcp socket connection +DGL4DDN = 3 # 4DDN (DECnet) -# -# END distributed graphics library defines -# +# +# END distributed graphics library defines +# diff --git a/lib/HVSplit.py b/lib/HVSplit.py index d52af8e..36192a7 100644 --- a/lib/HVSplit.py +++ b/lib/HVSplit.py @@ -8,49 +8,49 @@ from Split import Split class HVSplit() = Split(): - # - def create(self, (parent, hv)): - # hv is 0 or 1 for HSplit or VSplit - self = Split.create(self, parent) - self.hv = hv - return self - # - def minsize(self, m): - hv, vh = self.hv, 1 - self.hv - size = [0, 0] - for c in self.children: - csize = c.minsize(m) - if csize[vh] > size[vh]: size[vh] = csize[vh] - size[hv] = size[hv] + csize[hv] - return size[0], size[1] - # - def getbounds(self): - return self.bounds - # - def setbounds(self, bounds): - self.bounds = bounds - hv, vh = self.hv, 1 - self.hv - mf = self.parent.beginmeasuring - size = self.minsize(mf()) - # XXX not yet used! Later for stretching - maxsize_hv = bounds[1][hv] - bounds[0][hv] - origin = [self.bounds[0][0], self.bounds[0][1]] - for c in self.children: - size = c.minsize(mf()) - corner = [0, 0] - corner[vh] = bounds[1][vh] - corner[hv] = origin[hv] + size[hv] - c.setbounds((origin[0], origin[1]), \ - (corner[0], corner[1])) - origin[hv] = corner[hv] - # XXX stretch - # XXX too-small - # + # + def create(self, (parent, hv)): + # hv is 0 or 1 for HSplit or VSplit + self = Split.create(self, parent) + self.hv = hv + return self + # + def minsize(self, m): + hv, vh = self.hv, 1 - self.hv + size = [0, 0] + for c in self.children: + csize = c.minsize(m) + if csize[vh] > size[vh]: size[vh] = csize[vh] + size[hv] = size[hv] + csize[hv] + return size[0], size[1] + # + def getbounds(self): + return self.bounds + # + def setbounds(self, bounds): + self.bounds = bounds + hv, vh = self.hv, 1 - self.hv + mf = self.parent.beginmeasuring + size = self.minsize(mf()) + # XXX not yet used! Later for stretching + maxsize_hv = bounds[1][hv] - bounds[0][hv] + origin = [self.bounds[0][0], self.bounds[0][1]] + for c in self.children: + size = c.minsize(mf()) + corner = [0, 0] + corner[vh] = bounds[1][vh] + corner[hv] = origin[hv] + size[hv] + c.setbounds((origin[0], origin[1]), \ + (corner[0], corner[1])) + origin[hv] = corner[hv] + # XXX stretch + # XXX too-small + # class HSplit() = HVSplit(): - def create(self, parent): - return HVSplit.create(self, (parent, 0)) + def create(self, parent): + return HVSplit.create(self, (parent, 0)) class VSplit() = HVSplit(): - def create(self, parent): - return HVSplit.create(self, (parent, 1)) + def create(self, parent): + return HVSplit.create(self, (parent, 1)) diff --git a/lib/Histogram.py b/lib/Histogram.py index 3f6da76..505bbaf 100644 --- a/lib/Histogram.py +++ b/lib/Histogram.py @@ -5,32 +5,32 @@ from Buttons import * # A Histogram displays a histogram of numeric data. # class HistogramAppearance() = LabelAppearance(), Define(): - # - def define(self, parent): - Define.define(self, (parent, '')) - self.ydata = [] - self.scale = (0, 100) - return self - # - def setdata(self, (ydata, scale)): - self.ydata = ydata - self.scale = scale # (min, max) - self.parent.change(self.bounds) - # - def drawpict(self, d): - (left, top), (right, bottom) = self.bounds - min, max = self.scale - size = max-min - width, height = right-left, bottom-top - ydata = self.ydata - npoints = len(ydata) - v1 = top + height # constant - h1 = left # changed in loop - for i in range(npoints): - h0 = h1 - v0 = top + height - (ydata[i]-min)*height/size - h1 = left + (i+1) * width/npoints - d.paint((h0, v0), (h1, v1)) - # + # + def define(self, parent): + Define.define(self, (parent, '')) + self.ydata = [] + self.scale = (0, 100) + return self + # + def setdata(self, (ydata, scale)): + self.ydata = ydata + self.scale = scale # (min, max) + self.parent.change(self.bounds) + # + def drawpict(self, d): + (left, top), (right, bottom) = self.bounds + min, max = self.scale + size = max-min + width, height = right-left, bottom-top + ydata = self.ydata + npoints = len(ydata) + v1 = top + height # constant + h1 = left # changed in loop + for i in range(npoints): + h0 = h1 + v0 = top + height - (ydata[i]-min)*height/size + h1 = left + (i+1) * width/npoints + d.paint((h0, v0), (h1, v1)) + # class Histogram() = NoReactivity(), HistogramAppearance(): pass diff --git a/lib/Sliders.py b/lib/Sliders.py index e44b466..f655e77 100644 --- a/lib/Sliders.py +++ b/lib/Sliders.py @@ -23,153 +23,153 @@ _MASK = 3 # but defines its own setval_trigger and setval_hook. # class DragSliderReactivity() = BaseReactivity(): - # - def mouse_down(self, detail): - h, v = hv = detail[_HV] - if self.enabled and self.mousetest(hv): - self.anchor = h - self.oldval = self.val - self.active = 1 - # - def mouse_move(self, detail): - if self.active: - h, v = detail[_HV] - self.setval(self.oldval + (h - self.anchor)) - # - def mouse_up(self, detail): - if self.active: - h, v = detail[_HV] - self.setval(self.oldval + (h - self.anchor)) - self.active = 0 - # + # + def mouse_down(self, detail): + h, v = hv = detail[_HV] + if self.enabled and self.mousetest(hv): + self.anchor = h + self.oldval = self.val + self.active = 1 + # + def mouse_move(self, detail): + if self.active: + h, v = detail[_HV] + self.setval(self.oldval + (h - self.anchor)) + # + def mouse_up(self, detail): + if self.active: + h, v = detail[_HV] + self.setval(self.oldval + (h - self.anchor)) + self.active = 0 + # class DragSliderAppearance() = ButtonAppearance(): - # - # INVARIANTS maintained by the setval method: - # - # self.min <= self.val <= self.max - # self.text = self.pretext + `self.val` + self.postext - # - # (Notice that unlike Python ranges, the end point belongs - # to the range.) - # - def init_appearance(self): - ButtonAppearance.init_appearance(self) - self.min = 0 - self.val = 0 - self.max = 100 - self.hook = 0 - self.pretext = self.postext = '' - self.recalctext() - # - # The 'get*' and 'set*' methods belong to the generic slider interface - # - def getval(self): return self.val - # - def sethook(self, hook): - self.hook = hook - # - def setminvalmax(self, (min, val, max)): - self.min = min - self.max = max - self.setval(val) - # - def settexts(self, (pretext, postext)): - self.pretext = pretext - self.postext = postext - self.recalctext() - # - def setval(self, val): - val = min(self.max, max(self.min, val)) - if val <> self.val: - self.val = val - self.recalctext() - self.trigger() - # - def trigger(self): - if self.hook: - self.hook(self) - # - def recalctext(self): - self.settext(self.pretext + `self.val` + self.postext) - # + # + # INVARIANTS maintained by the setval method: + # + # self.min <= self.val <= self.max + # self.text = self.pretext + `self.val` + self.postext + # + # (Notice that unlike Python ranges, the end point belongs + # to the range.) + # + def init_appearance(self): + ButtonAppearance.init_appearance(self) + self.min = 0 + self.val = 0 + self.max = 100 + self.hook = 0 + self.pretext = self.postext = '' + self.recalctext() + # + # The 'get*' and 'set*' methods belong to the generic slider interface + # + def getval(self): return self.val + # + def sethook(self, hook): + self.hook = hook + # + def setminvalmax(self, (min, val, max)): + self.min = min + self.max = max + self.setval(val) + # + def settexts(self, (pretext, postext)): + self.pretext = pretext + self.postext = postext + self.recalctext() + # + def setval(self, val): + val = min(self.max, max(self.min, val)) + if val <> self.val: + self.val = val + self.recalctext() + self.trigger() + # + def trigger(self): + if self.hook: + self.hook(self) + # + def recalctext(self): + self.settext(self.pretext + `self.val` + self.postext) + # class DragSlider() = DragSliderReactivity(), DragSliderAppearance(), Define(): - def definetext(self, (parent, text)): - raise RuntimeError, 'DragSlider.definetext() not supported' + def definetext(self, (parent, text)): + raise RuntimeError, 'DragSlider.definetext() not supported' # Auxiliary class for PushButton incorporated in ComplexSlider # class _StepButton() = PushButton(): - def define(self, parent): - self = PushButton.define(self, parent) - self.step = 0 - return self - def setstep(self, step): - self.step = step - def definetextstep(self, (parent, text, step)): - self = self.definetext(parent, text) - self.setstep(step) - return self - def init_reactivity(self): - PushButton.init_reactivity(self) - self.parent.need_timer(self) - def step_trigger(self): - self.parent.setval(self.parent.getval() + self.step) - def down_trigger(self): - self.step_trigger() - self.parent.settimer(5) - def timer(self): - if self.hilited: - self.step_trigger() - if self.active: - self.parent.settimer(1) + def define(self, parent): + self = PushButton.define(self, parent) + self.step = 0 + return self + def setstep(self, step): + self.step = step + def definetextstep(self, (parent, text, step)): + self = self.definetext(parent, text) + self.setstep(step) + return self + def init_reactivity(self): + PushButton.init_reactivity(self) + self.parent.need_timer(self) + def step_trigger(self): + self.parent.setval(self.parent.getval() + self.step) + def down_trigger(self): + self.step_trigger() + self.parent.settimer(5) + def timer(self): + if self.hilited: + self.step_trigger() + if self.active: + self.parent.settimer(1) # A complex slider is an HSplit initialized to three buttons: # one to step down, a dragslider, and one to step up. # class ComplexSlider() = HSplit(): - # - # Override Slider define() method - # - def define(self, parent): - self = self.create(parent) # HSplit - # - self.downbutton = _StepButton().definetextstep(self, '-', -1) - self.dragbutton = DragSlider().define(self) - self.upbutton = _StepButton().definetextstep(self, '+', 1) - # - return self - # - # Override HSplit methods - # - def minsize(self, m): - w1, h1 = self.downbutton.minsize(m) - w2, h2 = self.dragbutton.minsize(m) - w3, h3 = self.upbutton.minsize(m) - height = max(h1, h2, h3) - w1 = max(w1, height) - w3 = max(w3, height) - return w1+w2+w3, height - # - def setbounds(self, bounds): - (left, top), (right, bottom) = self.bounds = bounds - size = bottom - top - self.downbutton.setbounds((left, top), (left+size, bottom)) - self.dragbutton.setbounds((left+size, top), \ - (right-size, bottom)) - self.upbutton.setbounds((right-size, top), (right, bottom)) - # - # Pass other Slider methods on to dragbutton - # - def getval(self): return self.dragbutton.getval() - def sethook(self, hook): self.dragbutton.sethook(hook) - def setminvalmax(self, args): self.dragbutton.setminvalmax(args) - def settexts(self, args): self.dragbutton.settexts(args) - def setval(self, val): self.dragbutton.setval(val) - def enable(self, flag): - self.downbutton.enable(flag) - self.dragbutton.enable(flag) - self.upbutton.enable(flag) + # + # Override Slider define() method + # + def define(self, parent): + self = self.create(parent) # HSplit + # + self.downbutton = _StepButton().definetextstep(self, '-', -1) + self.dragbutton = DragSlider().define(self) + self.upbutton = _StepButton().definetextstep(self, '+', 1) + # + return self + # + # Override HSplit methods + # + def minsize(self, m): + w1, h1 = self.downbutton.minsize(m) + w2, h2 = self.dragbutton.minsize(m) + w3, h3 = self.upbutton.minsize(m) + height = max(h1, h2, h3) + w1 = max(w1, height) + w3 = max(w3, height) + return w1+w2+w3, height + # + def setbounds(self, bounds): + (left, top), (right, bottom) = self.bounds = bounds + size = bottom - top + self.downbutton.setbounds((left, top), (left+size, bottom)) + self.dragbutton.setbounds((left+size, top), \ + (right-size, bottom)) + self.upbutton.setbounds((right-size, top), (right, bottom)) + # + # Pass other Slider methods on to dragbutton + # + def getval(self): return self.dragbutton.getval() + def sethook(self, hook): self.dragbutton.sethook(hook) + def setminvalmax(self, args): self.dragbutton.setminvalmax(args) + def settexts(self, args): self.dragbutton.settexts(args) + def setval(self, val): self.dragbutton.setval(val) + def enable(self, flag): + self.downbutton.enable(flag) + self.dragbutton.enable(flag) + self.upbutton.enable(flag) diff --git a/lib/Soundogram.py b/lib/Soundogram.py index 38dd5ef..aa2edd1 100644 --- a/lib/Soundogram.py +++ b/lib/Soundogram.py @@ -4,33 +4,33 @@ import audio from Histogram import Histogram class Soundogram() = Histogram(): - # - def define(self, (win, chunk)): - width, height = corner = win.getwinsize() - bounds = (0, 0), corner - self.chunk = chunk - self.step = (len(chunk)-1)/(width/2+1) + 1 - ydata = _make_ydata(chunk, self.step) - return Histogram.define(self, (win, bounds, ydata, (0, 128))) - # - def setchunk(self, chunk): - self.chunk = chunk - self.recompute() - # - def recompute(self): - (left, top), (right, bottom) = self.bounds - width = right - left - self.step = (len(chunk)-1)/width + 1 - ydata = _make_ydata(chunk, self.step) - self.setdata(ydata, (0, 128)) - # + # + def define(self, (win, chunk)): + width, height = corner = win.getwinsize() + bounds = (0, 0), corner + self.chunk = chunk + self.step = (len(chunk)-1)/(width/2+1) + 1 + ydata = _make_ydata(chunk, self.step) + return Histogram.define(self, (win, bounds, ydata, (0, 128))) + # + def setchunk(self, chunk): + self.chunk = chunk + self.recompute() + # + def recompute(self): + (left, top), (right, bottom) = self.bounds + width = right - left + self.step = (len(chunk)-1)/width + 1 + ydata = _make_ydata(chunk, self.step) + self.setdata(ydata, (0, 128)) + # def _make_ydata(chunk, step): - ydata = [] - for i in range(0, len(chunk), step): - piece = audio.chr2num(chunk[i:i+step]) - mi, ma = min(piece), max(piece) - y = max(abs(mi), abs(ma)) - ydata.append(y) - return ydata + ydata = [] + for i in range(0, len(chunk), step): + piece = audio.chr2num(chunk[i:i+step]) + mi, ma = min(piece), max(piece) + y = max(abs(mi), abs(ma)) + ydata.append(y) + return ydata diff --git a/lib/Split.py b/lib/Split.py index 8c0a8dc..63f5d5f 100644 --- a/lib/Split.py +++ b/lib/Split.py @@ -3,114 +3,114 @@ # Derived classes should at least implement the methods that call # unimpl() below: minsize(), getbounds() and setbounds(). -Error = 'Split.Error' # Exception +Error = 'Split.Error' # Exception import rect from util import remove class Split(): - # - # Calls from creator - # NB derived classes may add parameters to create() - # - def create(self, parent): - parent.addchild(self) - self.parent = parent - self.children = [] - self.mouse_interest = [] - self.timer_interest = [] - self.mouse_focus = 0 - return self - # - # Downcalls from parent to child - # - def destroy(self): - self.parent = None - for child in self.children: - child.destroy() - del self.children[:] - del self.mouse_interest[:] - del self.timer_interest[:] - self.mouse_focus = None - # - def minsize(self, m): return unimpl() - def getbounds(self): return unimpl() - def setbounds(self, bounds): unimpl() - # - def draw(self, d_detail): - # (Could avoid calls to children outside the area) - for child in self.children: - child.draw(d_detail) - # - # Downcalls only made after certain upcalls - # - def mouse_down(self, detail): - if self.mouse_focus: - self.mouse_focus.mouse_down(detail) - p = detail[0] - for child in self.mouse_interest: - if rect.pointinrect(p, child.getbounds()): - self.mouse_focus = child - child.mouse_down(detail) - def mouse_move(self, detail): - if self.mouse_focus: - self.mouse_focus.mouse_move(detail) - def mouse_up(self, detail): - if self.mouse_focus: - self.mouse_focus.mouse_up(detail) - self.mouse_focus = 0 - # - def timer(self): - for child in self.timer_interest: - child.timer() - # - # Upcalls from child to parent - # - def addchild(self, child): - if child in self.children: - raise Error, 'addchild: child already inlist' - self.children.append(child) - def delchild(self, child): - if child not in self.children: - raise Error, 'delchild: child not in list' - remove(child, self.children) - if child in self.mouse_interest: - remove(child, self.mouse_interest) - if child in self.timer_interest: - remove(child, self.timer_interest) - if child = self.mouse_focus: - self.mouse_focus = 0 - # - def need_mouse(self, child): - if child not in self.mouse_interest: - self.mouse_interest.append(child) - self.parent.need_mouse(self) - def no_mouse(self, child): - if child in self.mouse_interest: - remove(child, self.mouse_interest) - if not self.mouse_interest: - self.parent.no_mouse(self) - # - def need_timer(self, child): - if child not in self.timer_interest: - self.timer_interest.append(child) - self.parent.need_timer(self) - def no_timer(self, child): - if child in self.timer_interest: - remove(child, self.timer_interest) - if not self.timer_interest: - self.parent.no_timer(self) - # - # The rest are transparent: - # - def begindrawing(self): - return self.parent.begindrawing() - def beginmeasuring(self): - return self.parent.beginmeasuring() - # - def change(self, area): - self.parent.change(area) - def scroll(self, area_vector): - self.parent.scroll(area_vector) - def settimer(self, itimer): - self.parent.settimer(itimer) + # + # Calls from creator + # NB derived classes may add parameters to create() + # + def create(self, parent): + parent.addchild(self) + self.parent = parent + self.children = [] + self.mouse_interest = [] + self.timer_interest = [] + self.mouse_focus = 0 + return self + # + # Downcalls from parent to child + # + def destroy(self): + self.parent = None + for child in self.children: + child.destroy() + del self.children[:] + del self.mouse_interest[:] + del self.timer_interest[:] + self.mouse_focus = None + # + def minsize(self, m): return unimpl() + def getbounds(self): return unimpl() + def setbounds(self, bounds): unimpl() + # + def draw(self, d_detail): + # (Could avoid calls to children outside the area) + for child in self.children: + child.draw(d_detail) + # + # Downcalls only made after certain upcalls + # + def mouse_down(self, detail): + if self.mouse_focus: + self.mouse_focus.mouse_down(detail) + p = detail[0] + for child in self.mouse_interest: + if rect.pointinrect(p, child.getbounds()): + self.mouse_focus = child + child.mouse_down(detail) + def mouse_move(self, detail): + if self.mouse_focus: + self.mouse_focus.mouse_move(detail) + def mouse_up(self, detail): + if self.mouse_focus: + self.mouse_focus.mouse_up(detail) + self.mouse_focus = 0 + # + def timer(self): + for child in self.timer_interest: + child.timer() + # + # Upcalls from child to parent + # + def addchild(self, child): + if child in self.children: + raise Error, 'addchild: child already inlist' + self.children.append(child) + def delchild(self, child): + if child not in self.children: + raise Error, 'delchild: child not in list' + remove(child, self.children) + if child in self.mouse_interest: + remove(child, self.mouse_interest) + if child in self.timer_interest: + remove(child, self.timer_interest) + if child = self.mouse_focus: + self.mouse_focus = 0 + # + def need_mouse(self, child): + if child not in self.mouse_interest: + self.mouse_interest.append(child) + self.parent.need_mouse(self) + def no_mouse(self, child): + if child in self.mouse_interest: + remove(child, self.mouse_interest) + if not self.mouse_interest: + self.parent.no_mouse(self) + # + def need_timer(self, child): + if child not in self.timer_interest: + self.timer_interest.append(child) + self.parent.need_timer(self) + def no_timer(self, child): + if child in self.timer_interest: + remove(child, self.timer_interest) + if not self.timer_interest: + self.parent.no_timer(self) + # + # The rest are transparent: + # + def begindrawing(self): + return self.parent.begindrawing() + def beginmeasuring(self): + return self.parent.beginmeasuring() + # + def change(self, area): + self.parent.change(area) + def scroll(self, area_vector): + self.parent.scroll(area_vector) + def settimer(self, itimer): + self.parent.settimer(itimer) diff --git a/lib/StripChart.py b/lib/StripChart.py index fc707cb..ac767c3 100644 --- a/lib/StripChart.py +++ b/lib/StripChart.py @@ -7,62 +7,62 @@ from Buttons import LabelAppearance, NoReactivity # LabelAppearance allows it to be disabled and hilited. class StripChart() = LabelAppearance(), NoReactivity(): - # - def define(self, (parent, scale)): - self.parent = parent - parent.addchild(self) - self.init_appearance() - self.init_reactivity() - self.ydata = [] - self.scale = scale - self.resetbounds() - return self - # - def setbounds(self, bounds): - LabelAppearance.setbounds(self, bounds) - self.resetbounds() - # - def resetbounds(self): - (left, top), (right, bottom) = self.bounds - self.width = right-left - self.height = bottom-top - excess = len(self.ydata) - self.width - if excess > 0: - del self.ydata[:excess] - elif excess < 0: - while len(self.ydata) < self.width: - self.ydata.insert(0, 0) - # - def append(self, y): - self.ydata.append(y) - excess = len(self.ydata) - self.width - if excess > 0: - del self.ydata[:excess] - if self.bounds <> rect.empty: - self.parent.scroll(self.bounds, (-excess, 0)) - if self.bounds <> rect.empty: - (left, top), (right, bottom) = self.bounds - i = len(self.ydata) - area = (left+i-1, top), (left+i, bottom) - self.draw(self.parent.begindrawing(), area) - # - def draw(self, (d, area)): - area = rect.intersect(area, self.bounds) - if area = rect.empty: - print 'mt' - return - d.cliprect(area) - d.erase(self.bounds) - (a_left, a_top), (a_right, a_bottom) = area - (left, top), (right, bottom) = self.bounds - height = bottom - top - i1 = a_left - left - i2 = a_right - left - for i in range(max(0, i1), min(len(self.ydata), i2)): - split = bottom-self.ydata[i]*height/self.scale - d.paint((left+i, split), (left+i+1, bottom)) - if not self.enabled: - self.flipenable(d) - if self.hilited: - self.fliphilite(d) - d.noclip() + # + def define(self, (parent, scale)): + self.parent = parent + parent.addchild(self) + self.init_appearance() + self.init_reactivity() + self.ydata = [] + self.scale = scale + self.resetbounds() + return self + # + def setbounds(self, bounds): + LabelAppearance.setbounds(self, bounds) + self.resetbounds() + # + def resetbounds(self): + (left, top), (right, bottom) = self.bounds + self.width = right-left + self.height = bottom-top + excess = len(self.ydata) - self.width + if excess > 0: + del self.ydata[:excess] + elif excess < 0: + while len(self.ydata) < self.width: + self.ydata.insert(0, 0) + # + def append(self, y): + self.ydata.append(y) + excess = len(self.ydata) - self.width + if excess > 0: + del self.ydata[:excess] + if self.bounds <> rect.empty: + self.parent.scroll(self.bounds, (-excess, 0)) + if self.bounds <> rect.empty: + (left, top), (right, bottom) = self.bounds + i = len(self.ydata) + area = (left+i-1, top), (left+i, bottom) + self.draw(self.parent.begindrawing(), area) + # + def draw(self, (d, area)): + area = rect.intersect(area, self.bounds) + if area = rect.empty: + print 'mt' + return + d.cliprect(area) + d.erase(self.bounds) + (a_left, a_top), (a_right, a_bottom) = area + (left, top), (right, bottom) = self.bounds + height = bottom - top + i1 = a_left - left + i2 = a_right - left + for i in range(max(0, i1), min(len(self.ydata), i2)): + split = bottom-self.ydata[i]*height/self.scale + d.paint((left+i, split), (left+i+1, bottom)) + if not self.enabled: + self.flipenable(d) + if self.hilited: + self.fliphilite(d) + d.noclip() @@ -4,27 +4,27 @@ # 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. +# 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. +# 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). +# (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. +# 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. +# can return a string instead of a character. from TclUtil import * @@ -38,59 +38,59 @@ 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 '' + # + 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 + 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 + # + 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 @@ -98,311 +98,311 @@ _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 '' + # + 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 + 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) + MainLoop(the_interpreter) # XXX To do: diff --git a/lib/TclShell.py b/lib/TclShell.py index 78d8dc4..8d0ef19 100644 --- a/lib/TclShell.py +++ b/lib/TclShell.py @@ -10,246 +10,246 @@ from macpath import isfile, isdir, exists UsageError = TclRuntimeError class ShellInterpreter() = Interpreter(): - # - def ResetVariables(interp): - interp.globals['ps1'] = '$ ' - interp.globals['ps2'] = '> ' - interp.globals['home'] = mac.getcwd() - # - def DefineCommands(interp): - interp.commands['cd'] = interp.CdCmd - interp.commands['grep'] = interp.GrepCmd - interp.commands['ls'] = interp.LsCmd - interp.commands['mkdir'] = interp.MkdirCmd - interp.commands['mv'] = interp.MvCmd - interp.commands['pg'] = interp.PgCmd - interp.commands['pwd'] = interp.PwdCmd - interp.commands['rm'] = interp.RmCmd - interp.commands['rmdir'] = interp.RmdirCmd - interp.commands['sync'] = interp.SyncCmd - # - def Reset(interp): - interp.ResetVariables() - interp.DefineCommands() - # - def Create(interp): - interp = Interpreter.Create(interp) # initialize base class - interp.Reset() - return interp - # - # Command-implementing functions - # - def CdCmd(interp, argv): - if len(argv) > 2: - raise UsageError, 'usage: cd [dirname]' - if len(argv) = 2: - chdirto(argv[1]) - else: - chdirto(interp.globals['home']) - return '' - # - def GrepCmd(interp, argv): - if len(argv) < 3: - raise UsageError, 'usage: grep regexp file ...' - import regexp - try: - prog = regexp.compile(argv[1]) - except regexp.error, msg: - raise TclRuntimeError, \ - ('grep', argv[1], ': bad regexp :', msg) - for file in argv[2:]: - grepfile(prog, file) - return '' - # - def LsCmd(interp, argv): - if len(argv) < 2: - lsdir(':') - else: - for dirname in argv[1:]: - lsdir(dirname) - return '' - # - def MkdirCmd(interp, argv): - if len(argv) < 2: - raise UsageError, 'usage: mkdir name ...' - for name in argv[1:]: - makedir(name) - return '' - # - def MvCmd(interp, argv): - if len(argv) <> 3: - raise UsageError, 'usage: mv src dst' - src, dst = argv[1], argv[2] - if not exists(src): - raise TclRuntimeError, \ - ('mv', src, dst, ': source does not exist') - if exists(dst): - raise TclRuntimeError, \ - ('mv', src, dst, ': destination already exists') - try: - mac.rename(src, dst) - except mac.error, msg: - raise TclRuntimeError, \ - (src, dst, ': rename failed :', msg) - return '' - # - def PgCmd(interp, argv): - if len(argv) < 2: - raise UsageError, 'usage: page file ...' - for name in argv[1:]: - pagefile(name) - return '' - # - def PwdCmd(interp, argv): - if len(argv) > 1: - raise UsageError, 'usage: pwd' - else: - return mac.getcwd() - # - def RmCmd(interp, argv): - if len(argv) < 2: - raise UsageError, 'usage: rm file ...' - for name in argv[1:]: - remove(name) - return '' - # - def RmdirCmd(interp, argv): - if len(argv) < 2: - raise UsageError, 'usage: rmdir dir ...' - for name in argv[1:]: - rmdir(name) - return '' - # - def SyncCmd(interp, argv): - if len(argv) > 1: - raise UsageError, 'usage: sync' - try: - mac.sync() - except mac.error, msg: - raise TclRuntimeError, ('sync failed :', msg) - # + # + def ResetVariables(interp): + interp.globals['ps1'] = '$ ' + interp.globals['ps2'] = '> ' + interp.globals['home'] = mac.getcwd() + # + def DefineCommands(interp): + interp.commands['cd'] = interp.CdCmd + interp.commands['grep'] = interp.GrepCmd + interp.commands['ls'] = interp.LsCmd + interp.commands['mkdir'] = interp.MkdirCmd + interp.commands['mv'] = interp.MvCmd + interp.commands['pg'] = interp.PgCmd + interp.commands['pwd'] = interp.PwdCmd + interp.commands['rm'] = interp.RmCmd + interp.commands['rmdir'] = interp.RmdirCmd + interp.commands['sync'] = interp.SyncCmd + # + def Reset(interp): + interp.ResetVariables() + interp.DefineCommands() + # + def Create(interp): + interp = Interpreter.Create(interp) # initialize base class + interp.Reset() + return interp + # + # Command-implementing functions + # + def CdCmd(interp, argv): + if len(argv) > 2: + raise UsageError, 'usage: cd [dirname]' + if len(argv) = 2: + chdirto(argv[1]) + else: + chdirto(interp.globals['home']) + return '' + # + def GrepCmd(interp, argv): + if len(argv) < 3: + raise UsageError, 'usage: grep regexp file ...' + import regexp + try: + prog = regexp.compile(argv[1]) + except regexp.error, msg: + raise TclRuntimeError, \ + ('grep', argv[1], ': bad regexp :', msg) + for file in argv[2:]: + grepfile(prog, file) + return '' + # + def LsCmd(interp, argv): + if len(argv) < 2: + lsdir(':') + else: + for dirname in argv[1:]: + lsdir(dirname) + return '' + # + def MkdirCmd(interp, argv): + if len(argv) < 2: + raise UsageError, 'usage: mkdir name ...' + for name in argv[1:]: + makedir(name) + return '' + # + def MvCmd(interp, argv): + if len(argv) <> 3: + raise UsageError, 'usage: mv src dst' + src, dst = argv[1], argv[2] + if not exists(src): + raise TclRuntimeError, \ + ('mv', src, dst, ': source does not exist') + if exists(dst): + raise TclRuntimeError, \ + ('mv', src, dst, ': destination already exists') + try: + mac.rename(src, dst) + except mac.error, msg: + raise TclRuntimeError, \ + (src, dst, ': rename failed :', msg) + return '' + # + def PgCmd(interp, argv): + if len(argv) < 2: + raise UsageError, 'usage: page file ...' + for name in argv[1:]: + pagefile(name) + return '' + # + def PwdCmd(interp, argv): + if len(argv) > 1: + raise UsageError, 'usage: pwd' + else: + return mac.getcwd() + # + def RmCmd(interp, argv): + if len(argv) < 2: + raise UsageError, 'usage: rm file ...' + for name in argv[1:]: + remove(name) + return '' + # + def RmdirCmd(interp, argv): + if len(argv) < 2: + raise UsageError, 'usage: rmdir dir ...' + for name in argv[1:]: + rmdir(name) + return '' + # + def SyncCmd(interp, argv): + if len(argv) > 1: + raise UsageError, 'usage: sync' + try: + mac.sync() + except mac.error, msg: + raise TclRuntimeError, ('sync failed :', msg) + # def chdirto(dirname): - try: - mac.chdir(dirname) - except mac.error, msg: - raise TclRuntimeError, (dirname, ': chdir failed :', msg) + try: + mac.chdir(dirname) + except mac.error, msg: + raise TclRuntimeError, (dirname, ': chdir failed :', msg) def grepfile(prog, file): - try: - fp = open(file, 'r') - except RuntimeError, msg: - raise TclRuntimeError, (file, ': open failed :', msg) - lineno = 0 - while 1: - line = fp.readline() - if not line: break - lineno = lineno+1 - if prog.exec(line): - print file+'('+`lineno`+'):', line, + try: + fp = open(file, 'r') + except RuntimeError, msg: + raise TclRuntimeError, (file, ': open failed :', msg) + lineno = 0 + while 1: + line = fp.readline() + if not line: break + lineno = lineno+1 + if prog.exec(line): + print file+'('+`lineno`+'):', line, def lsdir(dirname): - if not isdir(dirname): - print dirname, ': no such directory' - return - names = mac.listdir(dirname) - lsfiles(names, dirname) + if not isdir(dirname): + print dirname, ': no such directory' + return + names = mac.listdir(dirname) + lsfiles(names, dirname) def lsfiles(names, dirname): - names = names[:] # Make a copy so we can modify it - for i in range(len(names)): - name = names[i] - if isdir(macpath.cat(dirname, name)): - names[i] = ':' + name + ':' - columnize(names) + names = names[:] # Make a copy so we can modify it + for i in range(len(names)): + name = names[i] + if isdir(macpath.cat(dirname, name)): + names[i] = ':' + name + ':' + columnize(names) def makedir(name): - if exists(name): - print name, ': already exists' - return - try: - mac.mkdir(name, 0777) - except mac.error, msg: - raise TclRuntimeError, (name, ': mkdir failed :', msg) + if exists(name): + print name, ': already exists' + return + try: + mac.mkdir(name, 0777) + except mac.error, msg: + raise TclRuntimeError, (name, ': mkdir failed :', msg) def pagefile(name): - import string - if not isfile(name): - print name, ': no such file' - return - LINES = 24 - 1 - # For THINK C 3.0, make the path absolute: - # if not macpath.isabs(name): - # name = macpath.cat(mac.getcwd(), name) - try: - fp = open(name, 'r') - except RuntimeError, msg: - raise TclRuntimeError, (name, ': open failed :', msg) - line = fp.readline() - while line: - for i in range(LINES): - print line, - line = fp.readline() - if not line: break - if line: - try: - more = raw_input('[more]') - except (EOFError, KeyboardInterrupt): - print - break - if string.strip(more)[:1] in ('q', 'Q'): - break + import string + if not isfile(name): + print name, ': no such file' + return + LINES = 24 - 1 + # For THINK C 3.0, make the path absolute: + # if not macpath.isabs(name): + # name = macpath.cat(mac.getcwd(), name) + try: + fp = open(name, 'r') + except RuntimeError, msg: + raise TclRuntimeError, (name, ': open failed :', msg) + line = fp.readline() + while line: + for i in range(LINES): + print line, + line = fp.readline() + if not line: break + if line: + try: + more = raw_input('[more]') + except (EOFError, KeyboardInterrupt): + print + break + if string.strip(more)[:1] in ('q', 'Q'): + break def remove(name): - if not isfile(name): - print name, ': no such file' - return - try: - mac.unlink(name) - except mac.error, msg: - raise TclRuntimeError, (name, ': unlink failed :', msg) + if not isfile(name): + print name, ': no such file' + return + try: + mac.unlink(name) + except mac.error, msg: + raise TclRuntimeError, (name, ': unlink failed :', msg) def rmdir(name): - if not isdir(name): - raise TclRuntimeError, (name, ': no such directory') - try: - mac.rmdir(name) - except mac.error, msg: - raise TclRuntimeError, (name, ': rmdir failed :', msg) + if not isdir(name): + raise TclRuntimeError, (name, ': no such directory') + try: + mac.rmdir(name) + except mac.error, msg: + raise TclRuntimeError, (name, ': rmdir failed :', msg) def printlist(list): - for word in list: - print word, + for word in list: + print word, def columnize(list): - import string - COLUMNS = 80-1 - n = len(list) - colwidth = maxwidth(list) - ncols = (COLUMNS + 1) / (colwidth + 1) - if ncols < 1: ncols = 1 - nrows = (n + ncols - 1) / ncols - for irow in range(nrows): - line = '' - for icol in range(ncols): - i = irow + nrows*icol - if 0 <= i < n: - word = list[i] - if i+nrows < n: - word = string.ljust(word, colwidth) - if icol > 0: - word = ' ' + word - line = line + word - print line + import string + COLUMNS = 80-1 + n = len(list) + colwidth = maxwidth(list) + ncols = (COLUMNS + 1) / (colwidth + 1) + if ncols < 1: ncols = 1 + nrows = (n + ncols - 1) / ncols + for irow in range(nrows): + line = '' + for icol in range(ncols): + i = irow + nrows*icol + if 0 <= i < n: + word = list[i] + if i+nrows < n: + word = string.ljust(word, colwidth) + if icol > 0: + word = ' ' + word + line = line + word + print line def maxwidth(list): - width = 0 - for word in list: - if len(word) > width: - width = len(word) - return width + width = 0 + for word in list: + if len(word) > width: + width = len(word) + return width the_interpreter = ShellInterpreter().Create() def main(): - Tcl.MainLoop(the_interpreter) + Tcl.MainLoop(the_interpreter) diff --git a/lib/TclUtil.py b/lib/TclUtil.py index 0990530..fb7b530 100644 --- a/lib/TclUtil.py +++ b/lib/TclUtil.py @@ -12,7 +12,7 @@ # For efficiency, the Tcl "tokenizing" routines used pre-compiled -# regular expressions. This is less readable but should be much faster +# regular expressions. This is less readable but should be much faster # than scanning the string a character at a time. # # The global variables @@ -21,9 +21,9 @@ # # The patterns always # have the form <something>* so they always match at the start of the -# search buffer---maybe with the empty string. This makes it possible +# search buffer---maybe with the empty string. This makes it possible # to use the expression "_foo_prog.exec(str, i)[0][1]" to find the first -# character beyond the matched string. Note that this may be beyond the +# character beyond the matched string. Note that this may be beyond the # end variable -- where this matters, "min(i, end)" is used. # Constructs that cannot @@ -33,19 +33,19 @@ # # Many regular expressions contain an expression that matches # a Tcl backslash sequence as a subpart: -# \\\\C?M?(.|\n) +# \\\\C?M?(.|\n) # # This is a bit hard to # read because the backslash contained in it must be doubled twice: # once to get past Python's backslash mechanism, once to get past that -# of regular expressions. It uses (.|\n) to match absolutely +# of regular expressions. It uses (.|\n) to match absolutely # *every character*, becase the MULTILINE regular expression package does # not accept '\n' as a match for '.'. # # There is also a simplification in the pattern for backslashes: # *any* single character following a backslash is escaped, # so hex and octal -# excapes are not scanned fully. The forms \Cx, \Mx and \CMx are +# excapes are not scanned fully. The forms \Cx, \Mx and \CMx are # scanned correctly, as these may hide a special character. # (This does not invalidate the recognition of strings, although the # match is effectuated in a different way than by the Backslash function.) @@ -69,28 +69,28 @@ TclMatchingError = 'Tcl matching error' _varname_prog = regexp.compile('[a-zA-Z0-9_]*') def FindVarName(str, i, end): - if i < end and str[i] = '{': return BalanceBraces(str, i, end) - i = _varname_prog.exec(str, i)[0][1] - return min(i, end) + if i < end and str[i] = '{': return BalanceBraces(str, i, end) + i = _varname_prog.exec(str, i)[0][1] + return min(i, end) # Split a list into its elements. # Return a list of elements (strings). def SplitList(str): - i, end = 0, len(str) - list = [] - while 1: - i = SkipSpaces(str, i, end) - if i >= end: break - j = i - i = FindNextElement(str, i, end) - if str[j] = '{' and str[i-1] = '}': - element = str[j+1:i-1] - else: - element = Collapse(str[j:i]) - list.append(element) - return list + i, end = 0, len(str) + list = [] + while 1: + i = SkipSpaces(str, i, end) + if i >= end: break + j = i + i = FindNextElement(str, i, end) + if str[j] = '{' and str[i-1] = '}': + element = str[j+1:i-1] + else: + element = Collapse(str[j:i]) + list.append(element) + return list # Find the next element from a list. @@ -98,13 +98,13 @@ def SplitList(str): _element_prog = regexp.compile('([^ \t\n\\]+|\\\\C?M?(.|\n))*') def FindNextElement(str, i, end): - if i < end and str[i] = '{': - i = BalanceBraces(str, i, end) - if i < end and str[i] not in ' \t\n': - raise TclSyntaxError, 'Garbage after } in list' - return i - i = _element_prog.exec(str, i)[0][1] - return min(i, end) + if i < end and str[i] = '{': + i = BalanceBraces(str, i, end) + if i < end and str[i] not in ' \t\n': + raise TclSyntaxError, 'Garbage after } in list' + return i + i = _element_prog.exec(str, i)[0][1] + return min(i, end) # Copy a string, expanding all backslash sequences. @@ -112,19 +112,19 @@ def FindNextElement(str, i, end): _collapse_prog = regexp.compile('(\n|[^\\]+)*') def Collapse(str): - if '\\' not in str: return str - i, end = 0, len(str) - result = '' - while i < end: - j = _collapse_prog.exec(str, i)[0][1] - j = min(j, end) - result = result + str[i:j] - if j >= end: break - c = str[j] - if c <> '\\': raise TclAssertError, 'collapse error' - x, i = Backslash(str, j, end) - result = result + x - return result + if '\\' not in str: return str + i, end = 0, len(str) + result = '' + while i < end: + j = _collapse_prog.exec(str, i)[0][1] + j = min(j, end) + result = result + str[i:j] + if j >= end: break + c = str[j] + if c <> '\\': raise TclAssertError, 'collapse error' + x, i = Backslash(str, j, end) + result = result + x + return result # Find the next full command. @@ -138,25 +138,25 @@ def Collapse(str): _eol_prog = regexp.compile('[^\n]*') def FindNextCommand(str, i, end, bracketed): - i = SkipSpaces(str, i, end) - if i >= end: return [], end - if str[i] = '#': - i = _eol_prog.exec(str, i) - i = min(i, end) - if i < end and str[i] = '\n': i = i+1 - return [], i - if bracketed: terminators = [';'] - else: terminators = [';', '\n'] - list = [] - while i < end: - j = FindNextWord(str, i, end) - word = str[i:j] - if word in terminators: - i = j - break - if word <> '\n': list.append(i, j) - i = SkipSpaces(str, j, end) - return list, i + i = SkipSpaces(str, i, end) + if i >= end: return [], end + if str[i] = '#': + i = _eol_prog.exec(str, i) + i = min(i, end) + if i < end and str[i] = '\n': i = i+1 + return [], i + if bracketed: terminators = [';'] + else: terminators = [';', '\n'] + list = [] + while i < end: + j = FindNextWord(str, i, end) + word = str[i:j] + if word in terminators: + i = j + break + if word <> '\n': list.append(i, j) + i = SkipSpaces(str, j, end) + return list, i # Find the next word of a command. @@ -167,26 +167,26 @@ def FindNextCommand(str, i, end, bracketed): _word_prog = regexp.compile('([^ \t\n;[\\]+|\\\\C?M?(.|\n))*') def FindNextWord(str, i, end): - if i >= end: return end - if str[i] in '{"': - if str[i] = '{': i = BalanceBraces(str, i, end) - else: i = BalanceQuotes(str, i, end) - if i >= end or str[i] in ' \t\n;': return min(i, end) - raise TclSyntaxError, 'Garbage after } or "' - begin = i - while i < end: - i = _word_prog.exec(str, i)[0][1] - if i >= end: - i = end - break - c = str[i] - if c in ' \t': break - if c in ';\n': - if i = begin: i = i+1 - break - if c = '[': i = BalanceBrackets(str, i, end) - else: raise TclAssertError, 'word error' - return i + if i >= end: return end + if str[i] in '{"': + if str[i] = '{': i = BalanceBraces(str, i, end) + else: i = BalanceQuotes(str, i, end) + if i >= end or str[i] in ' \t\n;': return min(i, end) + raise TclSyntaxError, 'Garbage after } or "' + begin = i + while i < end: + i = _word_prog.exec(str, i)[0][1] + if i >= end: + i = end + break + c = str[i] + if c in ' \t': break + if c in ';\n': + if i = begin: i = i+1 + break + if c = '[': i = BalanceBrackets(str, i, end) + else: raise TclAssertError, 'word error' + return i # Parse balanced brackets from str[i:end]. @@ -197,22 +197,22 @@ def FindNextWord(str, i, end): _brackets_prog = regexp.compile('([^][{\\]+|\n|\\\\C?M?(.|\n))*') def BalanceBrackets(str, i, end): - if i >= end or str[i] <> '[': - raise TclAssertError, 'BalanceBrackets' - nesting = 0 - while i < end: - i = _brackets_prog.exec(str, i)[0][1] - if i >= end: break - c = str[i] - if c = '{': i = BalanceBraces(str, i, end) - else: - i = i+1 - if c = '[': nesting = nesting + 1 - elif c = ']': - nesting = nesting - 1 - if nesting = 0: return i - else: raise TclAssertError, 'brackets error' - raise TclMatchingError, 'Unmatched bracket ([)' + if i >= end or str[i] <> '[': + raise TclAssertError, 'BalanceBrackets' + nesting = 0 + while i < end: + i = _brackets_prog.exec(str, i)[0][1] + if i >= end: break + c = str[i] + if c = '{': i = BalanceBraces(str, i, end) + else: + i = i+1 + if c = '[': nesting = nesting + 1 + elif c = ']': + nesting = nesting - 1 + if nesting = 0: return i + else: raise TclAssertError, 'brackets error' + raise TclMatchingError, 'Unmatched bracket ([)' # Parse balanced braces from str[i:end]. @@ -223,20 +223,20 @@ def BalanceBrackets(str, i, end): _braces_prog = regexp.compile('([^{}\\]+|\n|\\\\C?M?(.|\n))*') def BalanceBraces(str, i, end): - if i >= end or str[i] <> '{': - raise TclAssertError, 'BalanceBraces' - nesting = 0 - while i < end: - i = _braces_prog.exec(str, i)[0][1] - if i >= end: break - c = str[i] - i = i+1 - if c = '{': nesting = nesting + 1 - elif c = '}': - nesting = nesting - 1 - if nesting = 0: return i - else: raise TclAssertError, 'braces error' - raise TclMatchingError, 'Unmatched brace ({)' + if i >= end or str[i] <> '{': + raise TclAssertError, 'BalanceBraces' + nesting = 0 + while i < end: + i = _braces_prog.exec(str, i)[0][1] + if i >= end: break + c = str[i] + i = i+1 + if c = '{': nesting = nesting + 1 + elif c = '}': + nesting = nesting - 1 + if nesting = 0: return i + else: raise TclAssertError, 'braces error' + raise TclMatchingError, 'Unmatched brace ({)' # Parse double quotes from str[i:end]. @@ -246,11 +246,11 @@ def BalanceBraces(str, i, end): _quotes_prog = regexp.compile('([^"\\]+|\n|\\\\C?M?(.|\n))*') def BalanceQuotes(str, i, end): - if i >= end or str[i] <> '"': - raise TclAssertError, 'BalanceQuotes' - i = _quotes_prog.exec(str, i+1)[0][1] - if i < end and str[i] = '"': return i+1 - raise TclMatchingError, 'Unmatched quote (")' + if i >= end or str[i] <> '"': + raise TclAssertError, 'BalanceQuotes' + i = _quotes_prog.exec(str, i+1)[0][1] + if i < end and str[i] = '"': return i+1 + raise TclMatchingError, 'Unmatched quote (")' # Static data used by Backslash() @@ -272,44 +272,44 @@ del c # this takes only the backslash itself off the string. def Backslash(str, i, end): - if i >= end or str[i] <> '\\': - raise TclAssertError, 'Backslash' - i = i+1 - if i = end: return '\\', i - c = str[i] - i = i+1 - if _bstab.has_key(c): return _bstab[c], i - if c = 'C': - if i = end: return '\\', i-1 - c = str[i] - i = i+1 - if c = 'M': - if i = end: return '\\', i-2 - c = str[i] - i = i+1 - x = ord(c) % 040 + 0200 - else: - x = ord(c) % 040 - return chr(x), i - elif c = 'M': - if i = end: return '\\', i-1 - c = str[i] - i = i+1 - x = ord(c) - if x < 0200: x = x + 0200 - return chr(x), i - elif c and c in '0123456789': - x = ord(c) - ord('0') - end = min(end, i+2) - while i < end: - c = str[i] - if c not in '0123456789': break - i = i+1 - x = x*8 + ord(c) - ord('0') - return ord(x), i - else: - # Not something that we recognize - return '\\', i-1 + if i >= end or str[i] <> '\\': + raise TclAssertError, 'Backslash' + i = i+1 + if i = end: return '\\', i + c = str[i] + i = i+1 + if _bstab.has_key(c): return _bstab[c], i + if c = 'C': + if i = end: return '\\', i-1 + c = str[i] + i = i+1 + if c = 'M': + if i = end: return '\\', i-2 + c = str[i] + i = i+1 + x = ord(c) % 040 + 0200 + else: + x = ord(c) % 040 + return chr(x), i + elif c = 'M': + if i = end: return '\\', i-1 + c = str[i] + i = i+1 + x = ord(c) + if x < 0200: x = x + 0200 + return chr(x), i + elif c and c in '0123456789': + x = ord(c) - ord('0') + end = min(end, i+2) + while i < end: + c = str[i] + if c not in '0123456789': break + i = i+1 + x = x*8 + ord(c) - ord('0') + return ord(x), i + else: + # Not something that we recognize + return '\\', i-1 # Skip over spaces and tabs (but not newlines). @@ -317,61 +317,61 @@ def Backslash(str, i, end): _spaces_prog = regexp.compile('[ \t]*') def SkipSpaces(str, i, end): - i = _spaces_prog.exec(str, i)[0][1] - return min(i, end) + i = _spaces_prog.exec(str, i)[0][1] + return min(i, end) # Concatenate the elements of a list with intervening spaces. def Concat(argv): - result = '' - sep = '' - for arg in argv: - result = result + (sep + arg) - sep = ' ' - return result + result = '' + sep = '' + for arg in argv: + result = result + (sep + arg) + sep = ' ' + return result # Concatenate list elements, adding braces etc. to make them parseable # again with SplitList. def BuildList(argv): - result = '' - sep = '' - for arg in argv: - arg = AddBraces(arg) - result = result + (sep + arg) - sep = ' ' - return result + result = '' + sep = '' + for arg in argv: + arg = AddBraces(arg) + result = result + (sep + arg) + sep = ' ' + return result # Add braces around a string if necessary to make it parseable by SplitList. def AddBraces(str): - # Special case for empty string - if str = '': return '{}' - # See if it contains balanced braces - res = '{' + str + '}' - if TryNextElement(res): - # See if it would survive unquoted - # XXX should escape [] and $ as well??? - if TryNextElement(str) and Collapse(str) = str: return str - # No -- return with added braces - return res - # Unbalanced braces. Add backslashes before suspect characters - res = '' - for c in str: - if c in '$\\[]{} ;': c = '\\' + c - elif c = '\n': c = '\\n' - elif c = '\t': c = '\\t' - res = res + c - return res + # Special case for empty string + if str = '': return '{}' + # See if it contains balanced braces + res = '{' + str + '}' + if TryNextElement(res): + # See if it would survive unquoted + # XXX should escape [] and $ as well??? + if TryNextElement(str) and Collapse(str) = str: return str + # No -- return with added braces + return res + # Unbalanced braces. Add backslashes before suspect characters + res = '' + for c in str: + if c in '$\\[]{} ;': c = '\\' + c + elif c = '\n': c = '\\n' + elif c = '\t': c = '\\t' + res = res + c + return res def TryNextElement(str): - end = len(str) - try: - i = FindNextElement(str, 0, end) - return i = end - except (TclSyntaxError, TclMatchingError): - return 0 + end = len(str) + try: + i = FindNextElement(str, 0, end) + return i = end + except (TclSyntaxError, TclMatchingError): + return 0 diff --git a/lib/TestCSplit.py b/lib/TestCSplit.py index b638f81..5da55c4 100644 --- a/lib/TestCSplit.py +++ b/lib/TestCSplit.py @@ -6,21 +6,21 @@ from WindowParent import WindowParent from Buttons import PushButton def main(n): - from CSplit import CSplit - - the_window = WindowParent().create('TestCSplit', (0, 0)) - the_csplit = CSplit().create(the_window) - - for i in range(n): - the_child = PushButton().define(the_csplit) - the_child.settext(`(i+n-1)%n+1`) - - the_window.realize() - - while 1: - the_event = stdwin.getevent() - if the_event[0] = WE_CLOSE: break - the_window.dispatch(the_event) - the_window.destroy() + from CSplit import CSplit + + the_window = WindowParent().create('TestCSplit', (0, 0)) + the_csplit = CSplit().create(the_window) + + for i in range(n): + the_child = PushButton().define(the_csplit) + the_child.settext(`(i+n-1)%n+1`) + + the_window.realize() + + while 1: + the_event = stdwin.getevent() + if the_event[0] = WE_CLOSE: break + the_window.dispatch(the_event) + the_window.destroy() main(12) diff --git a/lib/TransParent.py b/lib/TransParent.py index a07b4c4..8cee283 100644 --- a/lib/TransParent.py +++ b/lib/TransParent.py @@ -3,94 +3,94 @@ # Use this as a base class for objects that are almost transparent. # Don't use as a base class for parents with multiple children. -Error = 'TransParent.Error' # Exception +Error = 'TransParent.Error' # Exception class ManageOneChild(): - # - # Upcalls shared with other single-child parents - # - def addchild(self, child): - if self.child: - raise Error, 'addchild: one child only' - if not child: - raise Error, 'addchild: bad child' - self.child = child - # - def delchild(self, child): - if not self.child: - raise Error, 'delchild: no child' - if child <> self.child: - raise Error, 'delchild: not my child' - self.child = 0 + # + # Upcalls shared with other single-child parents + # + def addchild(self, child): + if self.child: + raise Error, 'addchild: one child only' + if not child: + raise Error, 'addchild: bad child' + self.child = child + # + def delchild(self, child): + if not self.child: + raise Error, 'delchild: no child' + if child <> self.child: + raise Error, 'delchild: not my child' + self.child = 0 class TransParent() = ManageOneChild(): - # - # Calls from creator - # NB derived classes may add parameters to create() - # - def create(self, parent): - parent.addchild(self) - self.parent = parent - self.child = 0 # No child yet - # - # Downcalls from parent to child - # - def destroy(self): - del self.parent - if self.child: self.child.destroy() - del self.child - # - def minsize(self, m): - if not self.child: - return 0, 0 - else: - return self.child.minsize(m) - def getbounds(self, bounds): - if not self.child: - raise Error, 'getbounds w/o child' - else: - return self.child.getbounds() - def setbounds(self, bounds): - if not self.child: - raise Error, 'setbounds w/o child' - else: - self.child.setbounds(bounds) - def draw(self, args): - if self.child: - self.child.draw(args) - # - # Downcalls only made after certain upcalls - # - def mouse_down(self, detail): - if self.child: self.child.mouse_down(detail) - def mouse_move(self, detail): - if self.child: self.child.mouse_move(detail) - def mouse_up(self, detail): - if self.child: self.child.mouse_up(detail) - # - def timer(self): - if self.child: self.child.timer() - # - # Upcalls from child to parent - # - def need_mouse(self, child): - self.parent.need_mouse(self) - def no_mouse(self, child): - self.parent.no_mouse(self) - # - def need_timer(self, child): - self.parent.need_timer(self) - def no_timer(self, child): - self.parent.no_timer(self) - # - def begindrawing(self): - return self.parent.begindrawing() - def beginmeasuring(self): - return self.parent.beginmeasuring() - # - def change(self, area): - self.parent.change(area) - def scroll(self, args): - self.parent.scroll(args) - def settimer(self, itimer): - self.parent.settimer(itimer) + # + # Calls from creator + # NB derived classes may add parameters to create() + # + def create(self, parent): + parent.addchild(self) + self.parent = parent + self.child = 0 # No child yet + # + # Downcalls from parent to child + # + def destroy(self): + del self.parent + if self.child: self.child.destroy() + del self.child + # + def minsize(self, m): + if not self.child: + return 0, 0 + else: + return self.child.minsize(m) + def getbounds(self, bounds): + if not self.child: + raise Error, 'getbounds w/o child' + else: + return self.child.getbounds() + def setbounds(self, bounds): + if not self.child: + raise Error, 'setbounds w/o child' + else: + self.child.setbounds(bounds) + def draw(self, args): + if self.child: + self.child.draw(args) + # + # Downcalls only made after certain upcalls + # + def mouse_down(self, detail): + if self.child: self.child.mouse_down(detail) + def mouse_move(self, detail): + if self.child: self.child.mouse_move(detail) + def mouse_up(self, detail): + if self.child: self.child.mouse_up(detail) + # + def timer(self): + if self.child: self.child.timer() + # + # Upcalls from child to parent + # + def need_mouse(self, child): + self.parent.need_mouse(self) + def no_mouse(self, child): + self.parent.no_mouse(self) + # + def need_timer(self, child): + self.parent.need_timer(self) + def no_timer(self, child): + self.parent.no_timer(self) + # + def begindrawing(self): + return self.parent.begindrawing() + def beginmeasuring(self): + return self.parent.beginmeasuring() + # + def change(self, area): + self.parent.change(area) + def scroll(self, args): + self.parent.scroll(args) + def settimer(self, itimer): + self.parent.settimer(itimer) diff --git a/lib/VUMeter.py b/lib/VUMeter.py index c862452..31fe155 100644 --- a/lib/VUMeter.py +++ b/lib/VUMeter.py @@ -7,41 +7,41 @@ K = 1024 Rates = [0, 32*K, 16*K, 8*K] class VUMeter() = StripChart(): - # - # Override define() and timer() methods - # - def define(self, parent): - self = StripChart.define(self, (parent, 128)) - self.parent.need_timer(self) - self.sampling = 0 - self.rate = 3 - self.enable(0) - return self - # - def timer(self): - if self.sampling: - chunk = audio.wait_recording() - self.sampling = 0 - nums = audio.chr2num(chunk) - ampl = max(abs(min(nums)), abs(max(nums))) - self.append(ampl) - if self.enabled and not self.sampling: - audio.setrate(self.rate) - size = Rates[self.rate]/10 - size = size/48*48 - audio.start_recording(size) - self.sampling = 1 - if self.sampling: - self.parent.settimer(1) - # - # New methods: start() and stop() - # - def stop(self): - if self.sampling: - chunk = audio.stop_recording() - self.sampling = 0 - self.enable(0) - # - def start(self): - self.enable(1) - self.timer() + # + # Override define() and timer() methods + # + def define(self, parent): + self = StripChart.define(self, (parent, 128)) + self.parent.need_timer(self) + self.sampling = 0 + self.rate = 3 + self.enable(0) + return self + # + def timer(self): + if self.sampling: + chunk = audio.wait_recording() + self.sampling = 0 + nums = audio.chr2num(chunk) + ampl = max(abs(min(nums)), abs(max(nums))) + self.append(ampl) + if self.enabled and not self.sampling: + audio.setrate(self.rate) + size = Rates[self.rate]/10 + size = size/48*48 + audio.start_recording(size) + self.sampling = 1 + if self.sampling: + self.parent.settimer(1) + # + # New methods: start() and stop() + # + def stop(self): + if self.sampling: + chunk = audio.stop_recording() + self.sampling = 0 + self.enable(0) + # + def start(self): + self.enable(1) + self.timer() diff --git a/lib/WindowParent.py b/lib/WindowParent.py index 1e18930..5c72984 100644 --- a/lib/WindowParent.py +++ b/lib/WindowParent.py @@ -7,95 +7,95 @@ from stdwinevents import * from TransParent import ManageOneChild -Error = 'WindowParent.Error' # Exception +Error = 'WindowParent.Error' # Exception class WindowParent() = ManageOneChild(): - # - def create(self, (title, size)): - self.title = title - self.size = size # (width, height) - self._reset() - return self - # - def _reset(self): - self.child = 0 - self.win = 0 - self.itimer = 0 - self.do_mouse = 0 - self.do_timer = 0 - # - def destroy(self): - if self.child: self.child.destroy() - self._reset() - # - def need_mouse(self, child): self.do_mouse = 1 - def no_mouse(self, child): self.do_mouse = 0 - # - def need_timer(self, child): self.do_timer = 1 - def no_timer(self, child): self.do_timer = 0 - # - def realize(self): - if self.win: - raise Error, 'realize(): called twice' - if not self.child: - raise Error, 'realize(): no child' - size = self.child.minsize(self.beginmeasuring()) - self.size = max(self.size[0], size[0]), \ - max(self.size[1], size[1]) - #stdwin.setdefwinsize(self.size) - # XXX Compensate stdwin bug: - stdwin.setdefwinsize(self.size[0]+4, self.size[1]+2) - self.win = stdwin.open(self.title) - if self.itimer: - self.win.settimer(self.itimer) - bounds = (0, 0), self.win.getwinsize() - self.child.setbounds(bounds) - # - def beginmeasuring(self): - # Return something with which a child can measure text - if self.win: - return self.win.begindrawing() - else: - return stdwin - # - def begindrawing(self): - if self.win: - return self.win.begindrawing() - else: - raise Error, 'begindrawing(): not realized yet' - # - def change(self, area): - if self.win: - self.win.change(area) - # - def scroll(self, args): - if self.win: - self.win.scroll(args) - # - def settimer(self, itimer): - if self.win: - self.win.settimer(itimer) - else: - self.itimer = itimer - # - # Only call dispatch if we have a child - # - def dispatch(self, (type, win, detail)): - if win <> self.win: - return - elif type = WE_DRAW: - d = self.win.begindrawing() - self.child.draw(d, detail) - elif type = WE_MOUSE_DOWN: - if self.do_mouse: self.child.mouse_down(detail) - elif type = WE_MOUSE_MOVE: - if self.do_mouse: self.child.mouse_move(detail) - elif type = WE_MOUSE_UP: - if self.do_mouse: self.child.mouse_up(detail) - elif type = WE_TIMER: - if self.do_timer: self.child.timer() - elif type = WE_SIZE: - self.win.change((0, 0), (10000, 10000)) # XXX - bounds = (0, 0), self.win.getwinsize() - self.child.setbounds(bounds) - # + # + def create(self, (title, size)): + self.title = title + self.size = size # (width, height) + self._reset() + return self + # + def _reset(self): + self.child = 0 + self.win = 0 + self.itimer = 0 + self.do_mouse = 0 + self.do_timer = 0 + # + def destroy(self): + if self.child: self.child.destroy() + self._reset() + # + def need_mouse(self, child): self.do_mouse = 1 + def no_mouse(self, child): self.do_mouse = 0 + # + def need_timer(self, child): self.do_timer = 1 + def no_timer(self, child): self.do_timer = 0 + # + def realize(self): + if self.win: + raise Error, 'realize(): called twice' + if not self.child: + raise Error, 'realize(): no child' + size = self.child.minsize(self.beginmeasuring()) + self.size = max(self.size[0], size[0]), \ + max(self.size[1], size[1]) + #stdwin.setdefwinsize(self.size) + # XXX Compensate stdwin bug: + stdwin.setdefwinsize(self.size[0]+4, self.size[1]+2) + self.win = stdwin.open(self.title) + if self.itimer: + self.win.settimer(self.itimer) + bounds = (0, 0), self.win.getwinsize() + self.child.setbounds(bounds) + # + def beginmeasuring(self): + # Return something with which a child can measure text + if self.win: + return self.win.begindrawing() + else: + return stdwin + # + def begindrawing(self): + if self.win: + return self.win.begindrawing() + else: + raise Error, 'begindrawing(): not realized yet' + # + def change(self, area): + if self.win: + self.win.change(area) + # + def scroll(self, args): + if self.win: + self.win.scroll(args) + # + def settimer(self, itimer): + if self.win: + self.win.settimer(itimer) + else: + self.itimer = itimer + # + # Only call dispatch if we have a child + # + def dispatch(self, (type, win, detail)): + if win <> self.win: + return + elif type = WE_DRAW: + d = self.win.begindrawing() + self.child.draw(d, detail) + elif type = WE_MOUSE_DOWN: + if self.do_mouse: self.child.mouse_down(detail) + elif type = WE_MOUSE_MOVE: + if self.do_mouse: self.child.mouse_move(detail) + elif type = WE_MOUSE_UP: + if self.do_mouse: self.child.mouse_up(detail) + elif type = WE_TIMER: + if self.do_timer: self.child.timer() + elif type = WE_SIZE: + self.win.change((0, 0), (10000, 10000)) # XXX + bounds = (0, 0), self.win.getwinsize() + self.child.setbounds(bounds) + # @@ -13,16 +13,16 @@ nil = return_nil() whitespace = ' \t\n' def split(s): - res = [] - i, n = 0, len(s) - while i < n: - while i < n and s[i] in whitespace: i = i+1 - if i = n: break - j = i - while j < n and s[j] not in whitespace: j = j+1 - res.append(s[i:j]) - i = j - return res + res = [] + i, n = 0, len(s) + while i < n: + while i < n and s[i] in whitespace: i = i+1 + if i = n: break + j = i + while j < n and s[j] not in whitespace: j = j+1 + res.append(s[i:j]) + i = j + return res # Constants to name directions @@ -68,76 +68,76 @@ alias['drop'] = PUT # Normalize a command, in place: truncate words to 6 chars, and expand aliases. def normalize(cmd): - for i in range(len(cmd)): - word = cmd[i][:6] - if alias.has_key(word): - word = alias[word] - cmd[i] = word + for i in range(len(cmd)): + word = cmd[i][:6] + if alias.has_key(word): + word = alias[word] + cmd[i] = word # The Object class describes objects that the player can carry around. class Object(): - def init(this, name): - this.name = name - return this - def describe(this): - print 'A', this.name + '.' - def get(this, (player, room)): - del room.objects[this.name] - player.objects[this.name] = this - def put(this, (player, room)): - del player.objects[this.name] - room.objects[this.name] = this + def init(this, name): + this.name = name + return this + def describe(this): + print 'A', this.name + '.' + def get(this, (player, room)): + del room.objects[this.name] + player.objects[this.name] = this + def put(this, (player, room)): + del player.objects[this.name] + room.objects[this.name] = this # The Player class embodies first person control. class Player(): - # Set initial state, except current room. - def init(self, initial_room): - self.blind = 0 - self.here = initial_room - self.prev = nil - self.objects = {} - return self - # Read and execute commands forever. - def play(self): - self.here.casualdescribe() - while 1: - self.move() - # Read and execute one command. - def move(self): - next = self.here.parser() - if next and next <> self.here: - self.prev = self.here - self.here = next - if not self.blind: - self.here.casualdescribe() - # Print inventory. - def inventory(self): - if not self.objects: - print 'You aren\'t carrying anything.' - return - print 'You are carrying:' - for key in self.objects.keys(): - self.objects[key].describe() - # Go back to previous room. - def back(self): - if self.prev: return self.prev - print 'You can\'t go back now.' - # Get an object from the room. - def get(self, name): - if self.here.objects.has_key(name): - self.here.objects[name].get(self, self.here) - else: - print 'I see no', name, 'here.' - # Put an object in the room. - def put(self, name): - if self.objects.has_key(name): - self.objects[name].put(self, self.here) - else: - print 'You have no', name, 'with you.' + # Set initial state, except current room. + def init(self, initial_room): + self.blind = 0 + self.here = initial_room + self.prev = nil + self.objects = {} + return self + # Read and execute commands forever. + def play(self): + self.here.casualdescribe() + while 1: + self.move() + # Read and execute one command. + def move(self): + next = self.here.parser() + if next and next <> self.here: + self.prev = self.here + self.here = next + if not self.blind: + self.here.casualdescribe() + # Print inventory. + def inventory(self): + if not self.objects: + print 'You aren\'t carrying anything.' + return + print 'You are carrying:' + for key in self.objects.keys(): + self.objects[key].describe() + # Go back to previous room. + def back(self): + if self.prev: return self.prev + print 'You can\'t go back now.' + # Get an object from the room. + def get(self, name): + if self.here.objects.has_key(name): + self.here.objects[name].get(self, self.here) + else: + print 'I see no', name, 'here.' + # Put an object in the room. + def put(self, name): + if self.objects.has_key(name): + self.objects[name].put(self, self.here) + else: + print 'You have no', name, 'with you.' # The Room class describes a generic room. @@ -145,120 +145,120 @@ class Player(): # that override certain operations. class Room(): - # Initialize a featureless room. - def init(here, name): - here.seen = 0 - here.name = name - here.exits = {} - here.objects = {} - here.description = [] - return here - # Add an object to the room. Used during initialization. - def add(here, obj): - here.objects[obj.name] = obj - # Print a casual description. - def casualdescribe(here): - if here.seen: - print here.name + '.' - here.listobjects() - return - here.seen = 1 - here.describe() - # Print a full description, including all exits and objects seen. - def describe(here): - if not here.description: - print here.name + '.' - here.listexits() - else: - for line in here.description: print line - here.listobjects() - # List exits. - def listexits(here): - there = here.exits.keys() - if there: - if len(there) = 1: - print 'There is an exit leading', - else: - print 'There are exits leading', - for name in there[:-2]: - print name + ',', - print there[len(there)-2], 'and', - print there[len(there)-1] + '.' - # List objects - def listobjects(here): - if here.objects: - print 'I see:' - for key in here.objects.keys(): - here.objects[key].describe() - # Default parser. Returns next room (possibly the same) or nil. - def parser(here): - cmd = here.getcmd(here.prompt()) - return here.decide(cmd) - # Return default prompt string. - def prompt(here): return '> ' - # Default input routine. Returns a non-empty list of words. - def getcmd(here, prompt): - # Loop until non-empty command gotten - # EOFError and KeyboardInterrupt may be caught elsewhere - while 1: - line = raw_input(prompt) - cmd = split(line) - if cmd: - normalize(cmd) - return cmd - # Default decision routine. Override for room-specific commands. - def decide(here, cmd): - key, args = cmd[0], cmd[1:] - if not args: - if key = N: return here.north() - if key = S: return here.south() - if key = E: return here.east() - if key = W: return here.west() - if key = U: return here.up() - if key = D: return here.down() - if key = NW: return here.nw() - if key = NE: return here.ne() - if key = SW: return here.sw() - if key = SE: return here.se() - if key = LOOK: return here.look() - if key = INVENT: return here.inventory() - if key = BACK: return here.back() - if here.objects.has_key(key): - print 'What do you want to do with the', key+'?' - else: - print 'Huh?' - return - if key = GET: - for arg in args: - player.get(arg) - return - if key = PUT: - for arg in args: - player.put(arg) - # Standard commands. - def look(here): - here.describe() - def inventory(here): - player.inventory() - def back(here): - return player.back() - # Standard exits. - def north(here): return here.take_exit(N) - def south(here): return here.take_exit(S) - def west(here): return here.take_exit(W) - def east(here): return here.take_exit(E) - def up(here): return here.take_exit(U) - def down(here): return here.take_exit(D) - def nw(here): return here.take_exit(NW) - def ne(here): return here.take_exit(NE) - def sw(here): return here.take_exit(SW) - def se(here): return here.take_exit(SE) - # Subroutine for standard exits. - def take_exit(here, key): - if here.exits.has_key(key): - return here.exits[key] - print 'You cannot go in that direction.' - return here + # Initialize a featureless room. + def init(here, name): + here.seen = 0 + here.name = name + here.exits = {} + here.objects = {} + here.description = [] + return here + # Add an object to the room. Used during initialization. + def add(here, obj): + here.objects[obj.name] = obj + # Print a casual description. + def casualdescribe(here): + if here.seen: + print here.name + '.' + here.listobjects() + return + here.seen = 1 + here.describe() + # Print a full description, including all exits and objects seen. + def describe(here): + if not here.description: + print here.name + '.' + here.listexits() + else: + for line in here.description: print line + here.listobjects() + # List exits. + def listexits(here): + there = here.exits.keys() + if there: + if len(there) = 1: + print 'There is an exit leading', + else: + print 'There are exits leading', + for name in there[:-2]: + print name + ',', + print there[len(there)-2], 'and', + print there[len(there)-1] + '.' + # List objects + def listobjects(here): + if here.objects: + print 'I see:' + for key in here.objects.keys(): + here.objects[key].describe() + # Default parser. Returns next room (possibly the same) or nil. + def parser(here): + cmd = here.getcmd(here.prompt()) + return here.decide(cmd) + # Return default prompt string. + def prompt(here): return '> ' + # Default input routine. Returns a non-empty list of words. + def getcmd(here, prompt): + # Loop until non-empty command gotten + # EOFError and KeyboardInterrupt may be caught elsewhere + while 1: + line = raw_input(prompt) + cmd = split(line) + if cmd: + normalize(cmd) + return cmd + # Default decision routine. Override for room-specific commands. + def decide(here, cmd): + key, args = cmd[0], cmd[1:] + if not args: + if key = N: return here.north() + if key = S: return here.south() + if key = E: return here.east() + if key = W: return here.west() + if key = U: return here.up() + if key = D: return here.down() + if key = NW: return here.nw() + if key = NE: return here.ne() + if key = SW: return here.sw() + if key = SE: return here.se() + if key = LOOK: return here.look() + if key = INVENT: return here.inventory() + if key = BACK: return here.back() + if here.objects.has_key(key): + print 'What do you want to do with the', key+'?' + else: + print 'Huh?' + return + if key = GET: + for arg in args: + player.get(arg) + return + if key = PUT: + for arg in args: + player.put(arg) + # Standard commands. + def look(here): + here.describe() + def inventory(here): + player.inventory() + def back(here): + return player.back() + # Standard exits. + def north(here): return here.take_exit(N) + def south(here): return here.take_exit(S) + def west(here): return here.take_exit(W) + def east(here): return here.take_exit(E) + def up(here): return here.take_exit(U) + def down(here): return here.take_exit(D) + def nw(here): return here.take_exit(NW) + def ne(here): return here.take_exit(NE) + def sw(here): return here.take_exit(SW) + def se(here): return here.take_exit(SE) + # Subroutine for standard exits. + def take_exit(here, key): + if here.exits.has_key(key): + return here.exits[key] + print 'You cannot go in that direction.' + return here # Create the objects we know about. @@ -271,10 +271,10 @@ o_python = Object().init('python') # Subroutine to connect two rooms. def connect(rm1, rm2, dir1, dir2): - if dir1: - rm1.exits[dir1] = rm2 - if dir2: - rm2.exits[dir2] = rm1 + if dir1: + rm1.exits[dir1] = rm2 + if dir2: + rm2.exits[dir2] = rm1 # Create the rooms and connect them together. @@ -283,34 +283,34 @@ def connect(rm1, rm2, dir1, dir2): r_front = Room().init('Front of building') r_initial = r_front r_front.description = [ \ - 'You are standing in front of a large, desolate building.', \ - 'Huge neon letters spell "CWI". The "I" is blinking.', \ - 'There are entrances north and west from where you are standing.', \ - ] + 'You are standing in front of a large, desolate building.', \ + 'Huge neon letters spell "CWI". The "I" is blinking.', \ + 'There are entrances north and west from where you are standing.', \ + ] r_entrance = Room().init('Entrance') r_entrance.description = [ \ - 'You are standing in a small entrance room.', \ - 'On the east side is a window to a reception room.', \ - 'South is a door leading outside the building.', \ - 'North is a large hall.' \ - ] + 'You are standing in a small entrance room.', \ + 'On the east side is a window to a reception room.', \ + 'South is a door leading outside the building.', \ + 'North is a large hall.' \ + ] r_hall_s = Room().init('South of hall') r_hall_s.description = [ \ - 'You are standing at the south side of a very large hall.', \ - 'There are doors leading west, southwest, south and southeast,', \ - 'and a corridor leads east.', \ - 'The hall continues to the north.' \ - ] + 'You are standing at the south side of a very large hall.', \ + 'There are doors leading west, southwest, south and southeast,', \ + 'and a corridor leads east.', \ + 'The hall continues to the north.' \ + ] r_hall_n = Room().init('North of hall') r_hall_n.description = [ \ - 'You are stanting at the north side of a very large hall.', \ - 'There are corridors leading west, northwest, northeast,', \ - 'an elevator door north, and a door leading outside east.', \ - 'There are stairs leading up, and the hall continues to the south.' \ - ] + 'You are stanting at the north side of a very large hall.', \ + 'There are corridors leading west, northwest, northeast,', \ + 'an elevator door north, and a door leading outside east.', \ + 'There are stairs leading up, and the hall continues to the south.' \ + ] r_reception = Room().init('Reception') @@ -349,7 +349,7 @@ r_reception.add(o_lamp) # Create an uninitialized player object. # It is initialized by main(), but must be created here (as global) -# since some Room methods reference it. (Though maybe they shouldn't?) +# since some Room methods reference it. (Though maybe they shouldn't?) player = Player() @@ -357,10 +357,10 @@ player = Player() # Play the game from the beginning. def main(): - x = player.init(r_initial) - try: - player.play() - except (EOFError, KeyboardInterrupt): - pass + x = player.init(r_initial) + try: + player.play() + except (EOFError, KeyboardInterrupt): + pass main() diff --git a/lib/anywin.py b/lib/anywin.py index 6de3605..bb7e865 100644 --- a/lib/anywin.py +++ b/lib/anywin.py @@ -6,9 +6,9 @@ import filewin import path def open(name): - print 'opening', name, '...' - if path.isdir(name): - w = dirwin.open(name) - else: - w = filewin.open(name) - return w + print 'opening', name, '...' + if path.isdir(name): + w = dirwin.open(name) + else: + w = filewin.open(name) + return w diff --git a/lib/auds.py b/lib/auds.py index 53db6aa..549c0a7 100644 --- a/lib/auds.py +++ b/lib/auds.py @@ -4,103 +4,103 @@ RATE = 8192 # Initialize the audio stuff audio.setrate(3) -audio.setoutgain(100) # for speaker +audio.setoutgain(100) # for speaker play = audio.write def samp(n): - savegain = audio.getoutgain() - try: - audio.setoutgain(0) - x = raw_input('Hit Enter to sample ' + `n` + ' seconds: ') - return audio.read(n*RATE) - finally: - audio.setoutgain(savegain) + savegain = audio.getoutgain() + try: + audio.setoutgain(0) + x = raw_input('Hit Enter to sample ' + `n` + ' seconds: ') + return audio.read(n*RATE) + finally: + audio.setoutgain(savegain) def echo(s, delay, gain): - return s[:delay] + audio.add(s[delay:], audio.amplify(s, gain, gain)) + return s[:delay] + audio.add(s[delay:], audio.amplify(s, gain, gain)) def save(s, file): - f = open(file, 'w') - f.write(s) + f = open(file, 'w') + f.write(s) def load(file): - return loadfp(open(file, 'r')) + return loadfp(open(file, 'r')) def loadfp(fp): - s = '' - while 1: - buf = fp.read(16*1024) - if not buf: break - s = s + buf - return s + s = '' + while 1: + buf = fp.read(16*1024) + if not buf: break + s = s + buf + return s def unbias(s): - if not s: return s - a = audio.chr2num(s) - sum = 0 - for i in a: sum = sum + i - bias = (sum + len(a)/2) / len(a) - print 'Bias value:', bias - if bias: - for i in range(len(a)): - a[i] = a[i] - bias - s = audio.num2chr(a) - return s + if not s: return s + a = audio.chr2num(s) + sum = 0 + for i in a: sum = sum + i + bias = (sum + len(a)/2) / len(a) + print 'Bias value:', bias + if bias: + for i in range(len(a)): + a[i] = a[i] - bias + s = audio.num2chr(a) + return s # Stretch by a/b. # Think of this as converting the sampling rate from a samples/sec -# to b samples/sec. Or, if the input is a bytes long, the output +# to b samples/sec. Or, if the input is a bytes long, the output # will be b bytes long. # def stretch(s, a, b): - y = audio.chr2num(s) - m = len(y) - out = [] - n = m * b / a - # i, j will walk through y and out (step 1) - # ib, ja are i*b, j*a and are kept as close together as possible - i, ib = 0, 0 - j, ja = 0, 0 - for j in range(n): - ja = ja+a - while ib < ja: - i = i+1 - ib = ib+b - if i >= m: - break - if ib = ja: - out.append(y[i]) - else: - out.append((y[i]*(ja-(ib-b)) + y[i-1]*(ib-ja)) / b) - return audio.num2chr(out) + y = audio.chr2num(s) + m = len(y) + out = [] + n = m * b / a + # i, j will walk through y and out (step 1) + # ib, ja are i*b, j*a and are kept as close together as possible + i, ib = 0, 0 + j, ja = 0, 0 + for j in range(n): + ja = ja+a + while ib < ja: + i = i+1 + ib = ib+b + if i >= m: + break + if ib = ja: + out.append(y[i]) + else: + out.append((y[i]*(ja-(ib-b)) + y[i-1]*(ib-ja)) / b) + return audio.num2chr(out) def sinus(freq): # return a 1-second sine wave - from math import sin, pi - factor = 2.0*pi*float(freq)/float(RATE) - list = range(RATE) - for i in list: - list[i] = int(sin(float(i) * factor) * 127.0) - return audio.num2chr(list) + from math import sin, pi + factor = 2.0*pi*float(freq)/float(RATE) + list = range(RATE) + for i in list: + list[i] = int(sin(float(i) * factor) * 127.0) + return audio.num2chr(list) def softclip(s): - if '\177' not in s and '\200' not in s: - return s - num = audio.chr2num(s) - extremes = (-128, 127) - for i in range(1, len(num)-1): - if num[i] in extremes: - num[i] = (num[i-1] + num[i+1]) / 2 - return audio.num2chr(num) + if '\177' not in s and '\200' not in s: + return s + num = audio.chr2num(s) + extremes = (-128, 127) + for i in range(1, len(num)-1): + if num[i] in extremes: + num[i] = (num[i-1] + num[i+1]) / 2 + return audio.num2chr(num) def demo(): - gday = load('gday')[1000:6000] - save(gday, 'gday0') - gg = [gday] - for i in range(1, 10): - for g in gg: play(g) - g = stretch(gday, 10, 10-i) - save(g, 'gday' + `i`) - gg.append(g) - while 1: - for g in gg: play(g) + gday = load('gday')[1000:6000] + save(gday, 'gday0') + gg = [gday] + for i in range(1, 10): + for g in gg: play(g) + g = stretch(gday, 10, 10-i) + save(g, 'gday' + `i`) + gg.append(g) + while 1: + for g in gg: play(g) diff --git a/lib/calendar.py b/lib/calendar.py index 97ca86f..49e8e63 100644 --- a/lib/calendar.py +++ b/lib/calendar.py @@ -11,12 +11,12 @@ # - Monday is the first day of the week (numbered 0) # These are really parameters of the 'time' module: -epoch = 1970 # Time began on January 1 of this year (00:00:00 UCT) -day_0 = 3 # The epoch begins on a Thursday (Monday = 0) +epoch = 1970 # Time began on January 1 of this year (00:00:00 UCT) +day_0 = 3 # The epoch begins on a Thursday (Monday = 0) # Return 1 for leap years, 0 for non-leap years def isleap(year): - return year % 4 = 0 and (year % 100 <> 0 or year % 400 = 0) + return year % 4 = 0 and (year % 100 <> 0 or year % 400 = 0) # Constants for months referenced later January = 1 @@ -30,41 +30,41 @@ error = 'calendar error' # Turn seconds since epoch into calendar time def gmtime(secs): - if secs < 0: raise error, 'negative input to gmtime()' - mins, secs = divmod(secs, 60) - hours, mins = divmod(mins, 60) - days, hours = divmod(hours, 24) - wday = (days + day_0) % 7 - year = epoch - # XXX Most of the following loop can be replaced by one division - while 1: - yd = 365 + isleap(year) - if days < yd: break - days = days - yd - year = year + 1 - yday = days - month = January - while 1: - md = mdays[month] + (month = February and isleap(year)) - if days < md: break - days = days - md - month = month + 1 - return year, month, days + 1, hours, mins, secs, yday, wday - # XXX Week number also? + if secs < 0: raise error, 'negative input to gmtime()' + mins, secs = divmod(secs, 60) + hours, mins = divmod(mins, 60) + days, hours = divmod(hours, 24) + wday = (days + day_0) % 7 + year = epoch + # XXX Most of the following loop can be replaced by one division + while 1: + yd = 365 + isleap(year) + if days < yd: break + days = days - yd + year = year + 1 + yday = days + month = January + while 1: + md = mdays[month] + (month = February and isleap(year)) + if days < md: break + days = days - md + month = month + 1 + return year, month, days + 1, hours, mins, secs, yday, wday + # XXX Week number also? # Return number of leap years in range [y1, y2) # Assume y1 <= y2 and no funny (non-leap century) years def leapdays(y1, y2): - return (y2+3)/4 - (y1+3)/4 + return (y2+3)/4 - (y1+3)/4 # Inverse of gmtime(): # Turn UCT calendar time (less yday, wday) into seconds since epoch def mktime(year, month, day, hours, mins, secs): - days = day - 1 - for m in range(January, month): days = days + mdays[m] - if isleap(year) and month > February: days = days+1 - days = days + (year-epoch)*365 + leapdays(epoch, year) - return ((days*24 + hours)*60 + mins)*60 + secs + days = day - 1 + for m in range(January, month): days = days + mdays[m] + if isleap(year) and month > February: days = days+1 + days = days + (year-epoch)*365 + leapdays(epoch, year) + return ((days*24 + hours)*60 + mins)*60 + secs # Full and abbreviated names of weekdays day_name = ('Monday', 'Tuesday', 'Wednesday', 'Thursday') @@ -72,40 +72,40 @@ day_name = day_name + ('Friday', 'Saturday', 'Sunday') day_abbr = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun') # Full and abbreviated of months (1-based arrays!!!) -month_name = ('', 'January', 'February', 'March', 'April') -month_name = month_name + ('May', 'June', 'July', 'August') -month_name = month_name + ('September', 'October', 'November', 'December') -month_abbr = (' ', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun') +month_name = ('', 'January', 'February', 'March', 'April') +month_name = month_name + ('May', 'June', 'July', 'August') +month_name = month_name + ('September', 'October', 'November', 'December') +month_abbr = (' ', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun') month_abbr = month_abbr + ('Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec') # Zero-fill string to two positions (helper for asctime()) def dd(s): - while len(s) < 2: s = '0' + s - return s + while len(s) < 2: s = '0' + s + return s # Blank-fill string to two positions (helper for asctime()) def zd(s): - while len(s) < 2: s = ' ' + s - return s + while len(s) < 2: s = ' ' + s + return s # Turn calendar time as returned by gmtime() into a string # (the yday parameter is for compatibility with gmtime()) def asctime(year, month, day, hours, mins, secs, yday, wday): - s = day_abbr[wday] + ' ' + month_abbr[month] + ' ' + zd(`day`) - s = s + ' ' + dd(`hours`) + ':' + dd(`mins`) + ':' + dd(`secs`) - return s + ' ' + `year` + s = day_abbr[wday] + ' ' + month_abbr[month] + ' ' + zd(`day`) + s = s + ' ' + dd(`hours`) + ':' + dd(`mins`) + ':' + dd(`secs`) + return s + ' ' + `year` # Localization: Minutes West from Greenwich -# timezone = -2*60 # Middle-European time with DST on -timezone = 5*60 # EST (sigh -- THINK time() doesn't return UCT) +# timezone = -2*60 # Middle-European time with DST on +timezone = 5*60 # EST (sigh -- THINK time() doesn't return UCT) # Local time ignores DST issues for now -- adjust 'timezone' to fake it def localtime(secs): - return gmtime(secs - timezone*60) + return gmtime(secs - timezone*60) # UNIX-style ctime (except it doesn't append '\n'!) def ctime(secs): - return asctime(localtime(secs)) + return asctime(localtime(secs)) ###################### # Non-UNIX additions # @@ -115,99 +115,99 @@ def ctime(secs): # Return weekday (0-6 ~ Mon-Sun) for year (1970-...), month (1-12), day (1-31) def weekday(year, month, day): - secs = mktime(year, month, day, 0, 0, 0) - days = secs / (24*60*60) - return (days + day_0) % 7 + secs = mktime(year, month, day, 0, 0, 0) + days = secs / (24*60*60) + return (days + day_0) % 7 # Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for year, month def monthrange(year, month): - day1 = weekday(year, month, 1) - ndays = mdays[month] + (month = February and isleap(year)) - return day1, ndays + day1 = weekday(year, month, 1) + ndays = mdays[month] + (month = February and isleap(year)) + return day1, ndays # Return a matrix representing a month's calendar # Each row represents a week; days outside this month are zero def _monthcalendar(year, month): - day1, ndays = monthrange(year, month) - rows = [] - r7 = range(7) - day = 1 - day1 - while day <= ndays: - row = [0, 0, 0, 0, 0, 0, 0] - for i in r7: - if 1 <= day <= ndays: row[i] = day - day = day + 1 - rows.append(row) - return rows + day1, ndays = monthrange(year, month) + rows = [] + r7 = range(7) + day = 1 - day1 + while day <= ndays: + row = [0, 0, 0, 0, 0, 0, 0] + for i in r7: + if 1 <= day <= ndays: row[i] = day + day = day + 1 + rows.append(row) + return rows # Caching interface to _monthcalendar mc_cache = {} def monthcalendar(year, month): - key = `year` + month_abbr[month] - try: - return mc_cache[key] - except RuntimeError: - mc_cache[key] = ret = _monthcalendar(year, month) - return ret + key = `year` + month_abbr[month] + try: + return mc_cache[key] + except RuntimeError: + mc_cache[key] = ret = _monthcalendar(year, month) + return ret # Center a string in a field def center(str, width): - n = width - len(str) - if n < 0: return str - return ' '*(n/2) + str + ' '*(n-n/2) + n = width - len(str) + if n < 0: return str + return ' '*(n/2) + str + ' '*(n-n/2) # XXX The following code knows that print separates items with space! # Print a single week (no newline) def prweek(week, width): - for day in week: - if day = 0: print ' '*width, - else: - if width > 2: print ' '*(width-3), - if day < 10: print '', - print day, + for day in week: + if day = 0: print ' '*width, + else: + if width > 2: print ' '*(width-3), + if day < 10: print '', + print day, # Return a header for a week def weekheader(width): - str = '' - for i in range(7): - if str: str = str + ' ' - str = str + day_abbr[i%7][:width] - return str + str = '' + for i in range(7): + if str: str = str + ' ' + str = str + day_abbr[i%7][:width] + return str # Print a month's calendar def prmonth(year, month): - print weekheader(3) - for week in monthcalendar(year, month): - prweek(week, 3) - print + print weekheader(3) + for week in monthcalendar(year, month): + prweek(week, 3) + print # Spacing between month columns -spacing = ' ' +spacing = ' ' # 3-column formatting for year calendars def format3c(a, b, c): - print center(a, 20), spacing, center(b, 20), spacing, center(c, 20) + print center(a, 20), spacing, center(b, 20), spacing, center(c, 20) # Print a year's calendar def prcal(year): - header = weekheader(2) - format3c('', `year`, '') - for q in range(January, January+12, 3): - print - format3c(month_name[q], month_name[q+1], month_name[q+2]) - format3c(header, header, header) - data = [] - height = 0 - for month in range(q, q+3): - cal = monthcalendar(year, month) - if len(cal) > height: height = len(cal) - data.append(cal) - for i in range(height): - for cal in data: - if i >= len(cal): - print ' '*20, - else: - prweek(cal[i], 2) - print spacing, - print + header = weekheader(2) + format3c('', `year`, '') + for q in range(January, January+12, 3): + print + format3c(month_name[q], month_name[q+1], month_name[q+2]) + format3c(header, header, header) + data = [] + height = 0 + for month in range(q, q+3): + cal = monthcalendar(year, month) + if len(cal) > height: height = len(cal) + data.append(cal) + for i in range(height): + for cal in data: + if i >= len(cal): + print ' '*20, + else: + prweek(cal[i], 2) + print spacing, + print diff --git a/lib/clock.py b/lib/clock.py index ec5301e..572018e 100644 --- a/lib/clock.py +++ b/lib/clock.py @@ -14,7 +14,7 @@ import stdwin from stdwinevents import WE_MOUSE_DOWN, WE_MOUSE_MOVE, WE_MOUSE_UP, \ - WE_TIMER, WE_DRAW, WE_SIZE, WE_CLOSE, WE_ACTIVATE + WE_TIMER, WE_DRAW, WE_SIZE, WE_CLOSE, WE_ACTIVATE import time from math import sin, cos, atan2, pi, sqrt @@ -25,178 +25,178 @@ origin = 0, 0 faraway = 2000, 2000 everywhere = origin, faraway -class struct(): pass # A class to declare featureless objects +class struct(): pass # A class to declare featureless objects -G = struct() # Global variables (most set in setdimensions()) -G.tzdiff = 5*3600 # THINK computes UCT from local time assuming EST! +G = struct() # Global variables (most set in setdimensions()) +G.tzdiff = 5*3600 # THINK computes UCT from local time assuming EST! -A = struct() # Globals used by the alarm -A.set = 1 # True when alarm is set -A.time = 11*60 + 40 # Time when alarm must go off -A.ring = 0 # True when alarm is ringing +A = struct() # Globals used by the alarm +A.set = 1 # True when alarm is set +A.time = 11*60 + 40 # Time when alarm must go off +A.ring = 0 # True when alarm is ringing def main(): - try: - realmain() - except KeyboardInterrupt: - print 'KeyboardInterrupt' - finally: - G.w = 0 + try: + realmain() + except KeyboardInterrupt: + print 'KeyboardInterrupt' + finally: + G.w = 0 def realmain(): - setdimensions(DEFWIDTH, DEFHEIGHT) - stdwin.setdefwinsize(G.farcorner) - G.w = stdwin.open('klok') - settimer() - while 1: - type, window, detail = stdwin.getevent() - if type = WE_DRAW: - drawproc(detail) - elif type = WE_TIMER: - settimer() - drawproc(everywhere) - elif type in mouse_events: - mouseclick(type, detail) - elif type = WE_ACTIVATE: - if A.ring: - # Turn the ringing off - A.ring = 0 - G.w.begindrawing().invert(G.mainarea) - elif type = WE_SIZE: - G.w.change(everywhere) - width, height = G.w.getwinsize() - height = height - stdwin.lineheight() - setdimensions(width, height) - elif type = WE_CLOSE: - break + setdimensions(DEFWIDTH, DEFHEIGHT) + stdwin.setdefwinsize(G.farcorner) + G.w = stdwin.open('klok') + settimer() + while 1: + type, window, detail = stdwin.getevent() + if type = WE_DRAW: + drawproc(detail) + elif type = WE_TIMER: + settimer() + drawproc(everywhere) + elif type in mouse_events: + mouseclick(type, detail) + elif type = WE_ACTIVATE: + if A.ring: + # Turn the ringing off + A.ring = 0 + G.w.begindrawing().invert(G.mainarea) + elif type = WE_SIZE: + G.w.change(everywhere) + width, height = G.w.getwinsize() + height = height - stdwin.lineheight() + setdimensions(width, height) + elif type = WE_CLOSE: + break def setdimensions(width, height): - if width < height: size = width - else: size = height - halfwidth = width/2 - halfheight = height/2 - G.center = halfwidth, halfheight - G.radius = size*45/100 - G.width = width - G.height = height - G.corner = width, height - G.mainarea = origin, G.corner - G.lineheight = stdwin.lineheight() - G.farcorner = width, height + G.lineheight - G.statusarea = (0, height), G.farcorner - G.fullarea = origin, G.farcorner + if width < height: size = width + else: size = height + halfwidth = width/2 + halfheight = height/2 + G.center = halfwidth, halfheight + G.radius = size*45/100 + G.width = width + G.height = height + G.corner = width, height + G.mainarea = origin, G.corner + G.lineheight = stdwin.lineheight() + G.farcorner = width, height + G.lineheight + G.statusarea = (0, height), G.farcorner + G.fullarea = origin, G.farcorner def settimer(): - now = getlocaltime() - G.times = calctime(now) - delay = 61 - now % 60 - G.w.settimer(10 * delay) - minutes = (now/60) % 720 - if A.ring: - # Is it time to stop the alarm ringing? - since = (minutes - A.time + 720) % 720 - if since >= 5: - # Stop it now - A.ring = 0 - else: - # Ring again, once every minute - stdwin.fleep() - elif A.set and minutes = A.time: - # Start the alarm ringing - A.ring = 1 - stdwin.fleep() + now = getlocaltime() + G.times = calctime(now) + delay = 61 - now % 60 + G.w.settimer(10 * delay) + minutes = (now/60) % 720 + if A.ring: + # Is it time to stop the alarm ringing? + since = (minutes - A.time + 720) % 720 + if since >= 5: + # Stop it now + A.ring = 0 + else: + # Ring again, once every minute + stdwin.fleep() + elif A.set and minutes = A.time: + # Start the alarm ringing + A.ring = 1 + stdwin.fleep() def drawproc(area): - hours, minutes, seconds = G.times - d = G.w.begindrawing() - d.cliprect(area) - d.erase(everywhere) - d.circle(G.center, G.radius) - d.line(G.center, calcpoint(hours*30 + minutes/2, 0.6)) - d.line(G.center, calcpoint(minutes*6, 1.0)) - str = dd(hours) + ':' + dd(minutes) - p = (G.width - d.textwidth(str))/2, G.height * 3 / 4 - d.text(p, str) - if A.set: - drawalarm(d) - drawalarmtime(d) - if A.ring: - d.invert(G.mainarea) + hours, minutes, seconds = G.times + d = G.w.begindrawing() + d.cliprect(area) + d.erase(everywhere) + d.circle(G.center, G.radius) + d.line(G.center, calcpoint(hours*30 + minutes/2, 0.6)) + d.line(G.center, calcpoint(minutes*6, 1.0)) + str = dd(hours) + ':' + dd(minutes) + p = (G.width - d.textwidth(str))/2, G.height * 3 / 4 + d.text(p, str) + if A.set: + drawalarm(d) + drawalarmtime(d) + if A.ring: + d.invert(G.mainarea) def mouseclick(type, detail): - d = G.w.begindrawing() - if A.ring: - # First turn the ringing off - A.ring = 0 - d.invert(G.mainarea) - h, v = detail[0] - ch, cv = G.center - x, y = h-ch, cv-v - dist = sqrt(x*x + y*y) / float(G.radius) - if dist > 1.2: - if A.set: - drawalarm(d) - erasealarmtime(d) - A.set = 0 - elif dist < 0.8: - if not A.set: - A.set = 1 - drawalarm(d) - drawalarmtime(d) - else: - # Convert to half-degrees (range 0..720) - alpha = atan2(y, x) - hdeg = alpha*360.0/pi - hdeg = 180.0 - hdeg - hdeg = (hdeg + 720.0) % 720.0 - atime = 5*int(hdeg/5.0 + 0.5) - if atime <> A.time or not A.set: - if A.set: - drawalarm(d) - erasealarmtime(d) - A.set = 1 - A.time = atime - drawalarm(d) - drawalarmtime(d) + d = G.w.begindrawing() + if A.ring: + # First turn the ringing off + A.ring = 0 + d.invert(G.mainarea) + h, v = detail[0] + ch, cv = G.center + x, y = h-ch, cv-v + dist = sqrt(x*x + y*y) / float(G.radius) + if dist > 1.2: + if A.set: + drawalarm(d) + erasealarmtime(d) + A.set = 0 + elif dist < 0.8: + if not A.set: + A.set = 1 + drawalarm(d) + drawalarmtime(d) + else: + # Convert to half-degrees (range 0..720) + alpha = atan2(y, x) + hdeg = alpha*360.0/pi + hdeg = 180.0 - hdeg + hdeg = (hdeg + 720.0) % 720.0 + atime = 5*int(hdeg/5.0 + 0.5) + if atime <> A.time or not A.set: + if A.set: + drawalarm(d) + erasealarmtime(d) + A.set = 1 + A.time = atime + drawalarm(d) + drawalarmtime(d) def drawalarm(d): - p1 = calcpoint(float(A.time)/2.0, 1.02) - p2 = calcpoint(float(A.time)/2.0 - 4.0, 1.1) - p3 = calcpoint(float(A.time)/2.0 + 4.0, 1.1) - d.xorline(p1, p2) - d.xorline(p2, p3) - d.xorline(p3, p1) + p1 = calcpoint(float(A.time)/2.0, 1.02) + p2 = calcpoint(float(A.time)/2.0 - 4.0, 1.1) + p3 = calcpoint(float(A.time)/2.0 + 4.0, 1.1) + d.xorline(p1, p2) + d.xorline(p2, p3) + d.xorline(p3, p1) def erasealarmtime(d): - d.erase(G.statusarea) + d.erase(G.statusarea) def drawalarmtime(d): - # A.time is in the range 0..720 with origin at 12 o'clock - # Convert to hours (0..12) and minutes (12*(0..60)) - hh = A.time/60 - mm = A.time%60 - str = 'Alarm@' + dd(hh) + ':' + dd(mm) - p1 = (G.width - d.textwidth(str))/2, G.height - d.text(p1, str) + # A.time is in the range 0..720 with origin at 12 o'clock + # Convert to hours (0..12) and minutes (12*(0..60)) + hh = A.time/60 + mm = A.time%60 + str = 'Alarm@' + dd(hh) + ':' + dd(mm) + p1 = (G.width - d.textwidth(str))/2, G.height + d.text(p1, str) def calctime(now): - seconds = now % 60 - minutes = (now/60) % 60 - hours = (now/3600) % 12 - return hours, minutes, seconds + seconds = now % 60 + minutes = (now/60) % 60 + hours = (now/3600) % 12 + return hours, minutes, seconds def calcpoint(degrees, size): - alpha = pi/2.0 - float(degrees) * pi/180.0 - x, y = cos(alpha), sin(alpha) - h, v = G.center - r = float(G.radius) - return h + int(x*size*r), v - int(y*size*r) + alpha = pi/2.0 - float(degrees) * pi/180.0 + x, y = cos(alpha), sin(alpha) + h, v = G.center + r = float(G.radius) + return h + int(x*size*r), v - int(y*size*r) def dd(n): - s = `n` - return '0'*(2-len(s)) + s + s = `n` + return '0'*(2-len(s)) + s def getlocaltime(): - return time.time() - G.tzdiff + return time.time() - G.tzdiff #main() @@ -3,59 +3,59 @@ # Efficiently compare files, boolean outcome only (equal / not equal). # Tricks (used in this order): -# - Files with identical type, size & mtime are assumed to be clones -# - Files with different type or size cannot be identical -# - We keep a cache of outcomes of earlier comparisons -# - We don't fork a process to run 'cmp' but read the files ourselves +# - Files with identical type, size & mtime are assumed to be clones +# - Files with different type or size cannot be identical +# - We keep a cache of outcomes of earlier comparisons +# - We don't fork a process to run 'cmp' but read the files ourselves import posix cache = {} def cmp(f1, f2): # Compare two files, use the cache if possible. - # Return 1 for identical files, 0 for different. - # Raise exceptions if either file could not be statted, read, etc. - s1, s2 = sig(posix.stat(f1)), sig(posix.stat(f2)) - if s1[0] <> 8 or s2[0] <> 8: - # Either is a not a plain file -- always report as different - return 0 - if s1 = s2: - # type, size & mtime match -- report same - return 1 - if s1[:2] <> s2[:2]: # Types or sizes differ, don't bother - # types or sizes differ -- report different - return 0 - # same type and size -- look in the cache - key = f1 + ' ' + f2 - try: - cs1, cs2, outcome = cache[key] - # cache hit - if s1 = cs1 and s2 = cs2: - # cached signatures match - return outcome - # stale cached signature(s) - except RuntimeError: - # cache miss - pass - # really compare - outcome = do_cmp(f1, f2) - cache[key] = s1, s2, outcome - return outcome + # Return 1 for identical files, 0 for different. + # Raise exceptions if either file could not be statted, read, etc. + s1, s2 = sig(posix.stat(f1)), sig(posix.stat(f2)) + if s1[0] <> 8 or s2[0] <> 8: + # Either is a not a plain file -- always report as different + return 0 + if s1 = s2: + # type, size & mtime match -- report same + return 1 + if s1[:2] <> s2[:2]: # Types or sizes differ, don't bother + # types or sizes differ -- report different + return 0 + # same type and size -- look in the cache + key = f1 + ' ' + f2 + try: + cs1, cs2, outcome = cache[key] + # cache hit + if s1 = cs1 and s2 = cs2: + # cached signatures match + return outcome + # stale cached signature(s) + except RuntimeError: + # cache miss + pass + # really compare + outcome = do_cmp(f1, f2) + cache[key] = s1, s2, outcome + return outcome def sig(st): # Return signature (i.e., type, size, mtime) from raw stat data - # 0-5: st_mode, st_ino, st_dev, st_nlink, st_uid, st_gid - # 6-9: st_size, st_atime, st_mtime, st_ctime - type = st[0] / 4096 - size = st[6] - mtime = st[8] - return type, size, mtime + # 0-5: st_mode, st_ino, st_dev, st_nlink, st_uid, st_gid + # 6-9: st_size, st_atime, st_mtime, st_ctime + type = st[0] / 4096 + size = st[6] + mtime = st[8] + return type, size, mtime def do_cmp(f1, f2): # Compare two files, really - bufsize = 8096 # Could be tuned - fp1 = open(f1, 'r') - fp2 = open(f2, 'r') - while 1: - b1 = fp1.read(bufsize) - b2 = fp2.read(bufsize) - if b1 <> b2: return 0 - if not b1: return 1 + bufsize = 8096 # Could be tuned + fp1 = open(f1, 'r') + fp2 = open(f2, 'r') + while 1: + b1 = fp1.read(bufsize) + b2 = fp2.read(bufsize) + if b1 <> b2: return 0 + if not b1: return 1 diff --git a/lib/cmpcache.py b/lib/cmpcache.py index 4aea356..e846f58 100644 --- a/lib/cmpcache.py +++ b/lib/cmpcache.py @@ -3,11 +3,11 @@ # Efficiently compare files, boolean outcome only (equal / not equal). # # Tricks (used in this order): -# - Use the statcache module to avoid statting files more than once -# - Files with identical type, size & mtime are assumed to be clones -# - Files with different type or size cannot be identical -# - We keep a cache of outcomes of earlier comparisons -# - We don't fork a process to run 'cmp' but read the files ourselves +# - Use the statcache module to avoid statting files more than once +# - Files with identical type, size & mtime are assumed to be clones +# - Files with different type or size cannot be identical +# - We keep a cache of outcomes of earlier comparisons +# - We don't fork a process to run 'cmp' but read the files ourselves import posix from stat import * @@ -23,46 +23,46 @@ cache = {} # May raise posix.error if a stat or open of either fails. # def cmp(f1, f2): - # Return 1 for identical files, 0 for different. - # Raise exceptions if either file could not be statted, read, etc. - s1, s2 = sig(statcache.stat(f1)), sig(statcache.stat(f2)) - if not S_ISREG(s1[0]) or not S_ISREG(s2[0]): - # Either is a not a plain file -- always report as different - return 0 - if s1 = s2: - # type, size & mtime match -- report same - return 1 - if s1[:2] <> s2[:2]: # Types or sizes differ, don't bother - # types or sizes differ -- report different - return 0 - # same type and size -- look in the cache - key = f1 + ' ' + f2 - if cache.has_key(key): - cs1, cs2, outcome = cache[key] - # cache hit - if s1 = cs1 and s2 = cs2: - # cached signatures match - return outcome - # stale cached signature(s) - # really compare - outcome = do_cmp(f1, f2) - cache[key] = s1, s2, outcome - return outcome + # Return 1 for identical files, 0 for different. + # Raise exceptions if either file could not be statted, read, etc. + s1, s2 = sig(statcache.stat(f1)), sig(statcache.stat(f2)) + if not S_ISREG(s1[0]) or not S_ISREG(s2[0]): + # Either is a not a plain file -- always report as different + return 0 + if s1 = s2: + # type, size & mtime match -- report same + return 1 + if s1[:2] <> s2[:2]: # Types or sizes differ, don't bother + # types or sizes differ -- report different + return 0 + # same type and size -- look in the cache + key = f1 + ' ' + f2 + if cache.has_key(key): + cs1, cs2, outcome = cache[key] + # cache hit + if s1 = cs1 and s2 = cs2: + # cached signatures match + return outcome + # stale cached signature(s) + # really compare + outcome = do_cmp(f1, f2) + cache[key] = s1, s2, outcome + return outcome # Return signature (i.e., type, size, mtime) from raw stat data. # def sig(st): - return S_IFMT(st[ST_MODE]), st[ST_SIZE], st[ST_MTIME] + return S_IFMT(st[ST_MODE]), st[ST_SIZE], st[ST_MTIME] # Compare two files, really. # def do_cmp(f1, f2): - #print ' cmp', f1, f2 # XXX remove when debugged - bufsize = 8096 # Could be tuned - fp1 = open(f1, 'r') - fp2 = open(f2, 'r') - while 1: - b1 = fp1.read(bufsize) - b2 = fp2.read(bufsize) - if b1 <> b2: return 0 - if not b1: return 1 + #print ' cmp', f1, f2 # XXX remove when debugged + bufsize = 8096 # Could be tuned + fp1 = open(f1, 'r') + fp2 = open(f2, 'r') + while 1: + b1 = fp1.read(bufsize) + b2 = fp2.read(bufsize) + if b1 <> b2: return 0 + if not b1: return 1 diff --git a/lib/commands.py b/lib/commands.py index 3cb6e69..dc46740 100644 --- a/lib/commands.py +++ b/lib/commands.py @@ -11,7 +11,7 @@ import path # Get 'ls -l' status for an object into a string # def getstatus(file): - return getoutput('ls -ld' + mkarg(file)) + return getoutput('ls -ld' + mkarg(file)) # Get the output from a shell command into a string. @@ -20,44 +20,44 @@ def getstatus(file): # XXX This should use posix.popen() instead, should it exist. # def getoutput(cmd): - return getstatusoutput(cmd)[1] + return getstatusoutput(cmd)[1] # Ditto but preserving the exit status. # Returns a pair (sts, output) # def getstatusoutput(cmd): - tmp = '/usr/tmp/wdiff' + `rand.rand()` - sts = -1 - try: - sts = posix.system(cmd + ' >' + tmp + ' 2>&1') - text = readfile(tmp) - finally: - altsts = posix.system('rm -f ' + tmp) - if text[-1:] = '\n': text = text[:-1] - return sts, text + tmp = '/usr/tmp/wdiff' + `rand.rand()` + sts = -1 + try: + sts = posix.system(cmd + ' >' + tmp + ' 2>&1') + text = readfile(tmp) + finally: + altsts = posix.system('rm -f ' + tmp) + if text[-1:] = '\n': text = text[:-1] + return sts, text # Return a string containing a file's contents. # def readfile(fn): - st = posix.stat(fn) - size = st[stat.ST_SIZE] - if not size: return '' - try: - fp = open(fn, 'r') - except: - raise posix.error, 'readfile(' + fn + '): open failed' - try: - return fp.read(size) - except: - raise posix.error, 'readfile(' + fn + '): read failed' + st = posix.stat(fn) + size = st[stat.ST_SIZE] + if not size: return '' + try: + fp = open(fn, 'r') + except: + raise posix.error, 'readfile(' + fn + '): open failed' + try: + return fp.read(size) + except: + raise posix.error, 'readfile(' + fn + '): read failed' # Make command argument from directory and pathname (prefix space, add quotes). # def mk2arg(head, x): - return mkarg(path.cat(head, x)) + return mkarg(path.cat(head, x)) # Make a shell command argument from a string. @@ -66,12 +66,12 @@ def mk2arg(head, x): # with backslash. # def mkarg(x): - if '\'' not in x: - return ' \'' + x + '\'' - s = ' "' - for c in x: - if c in '\\$"': - s = s + '\\' - s = s + c - s = s + '"' - return s + if '\'' not in x: + return ' \'' + x + '\'' + s = ' "' + for c in x: + if c in '\\$"': + s = s + '\\' + s = s + c + s = s + '"' + return s diff --git a/lib/dircache.py b/lib/dircache.py index c14db3e..b40f76e 100644 --- a/lib/dircache.py +++ b/lib/dircache.py @@ -10,27 +10,27 @@ import path cache = {} def listdir(path): # List directory contents, using cache - try: - cached_mtime, list = cache[path] - del cache[path] - except RuntimeError: - cached_mtime, list = -1, [] - try: - mtime = posix.stat(path)[8] - except posix.error: - return [] - if mtime <> cached_mtime: - try: - list = posix.listdir(path) - except posix.error: - return [] - list.sort() - cache[path] = mtime, list - return list + try: + cached_mtime, list = cache[path] + del cache[path] + except RuntimeError: + cached_mtime, list = -1, [] + try: + mtime = posix.stat(path)[8] + except posix.error: + return [] + if mtime <> cached_mtime: + try: + list = posix.listdir(path) + except posix.error: + return [] + list.sort() + cache[path] = mtime, list + return list opendir = listdir # XXX backward compatibility def annotate(head, list): # Add '/' suffixes to directories - for i in range(len(list)): - if path.isdir(path.cat(head, list[i])): - list[i] = list[i] + '/' + for i in range(len(list)): + if path.isdir(path.cat(head, list[i])): + list[i] = list[i] + '/' diff --git a/lib/dircmp.py b/lib/dircmp.py index 31e712c..819f0bd 100644 --- a/lib/dircmp.py +++ b/lib/dircmp.py @@ -14,192 +14,192 @@ from stat import * # Directory comparison class. # class dircmp(): - # - def new(dd, (a, b)): # Initialize - dd.a = a - dd.b = b - # Properties that caller may change before callingdd. run(): - dd.hide = ['.', '..'] # Names never to be shown - dd.ignore = ['RCS', 'tags'] # Names ignored in comparison - # - return dd - # - def run(dd): # Compare everything except common subdirectories - dd.a_list = filter(dircache.listdir(dd.a), dd.hide) - dd.b_list = filter(dircache.listdir(dd.b), dd.hide) - dd.a_list.sort() - dd.b_list.sort() - dd.phase1() - dd.phase2() - dd.phase3() - # - def phase1(dd): # Compute common names - dd.a_only = [] - dd.common = [] - for x in dd.a_list: - if x in dd.b_list: - dd.common.append(x) - else: - dd.a_only.append(x) - # - dd.b_only = [] - for x in dd.b_list: - if x not in dd.common: - dd.b_only.append(x) - # - def phase2(dd): # Distinguish files, directories, funnies - dd.common_dirs = [] - dd.common_files = [] - dd.common_funny = [] - # - for x in dd.common: - a_path = path.cat(dd.a, x) - b_path = path.cat(dd.b, x) - # - ok = 1 - try: - a_stat = statcache.stat(a_path) - except posix.error, why: - # print 'Can\'t stat', a_path, ':', why[1] - ok = 0 - try: - b_stat = statcache.stat(b_path) - except posix.error, why: - # print 'Can\'t stat', b_path, ':', why[1] - ok = 0 - # - if ok: - a_type = S_IFMT(a_stat[ST_MODE]) - b_type = S_IFMT(b_stat[ST_MODE]) - if a_type <> b_type: - dd.common_funny.append(x) - elif S_ISDIR(a_type): - dd.common_dirs.append(x) - elif S_ISREG(a_type): - dd.common_files.append(x) - else: - dd.common_funny.append(x) - else: - dd.common_funny.append(x) - # - def phase3(dd): # Find out differences between common files - xx = cmpfiles(dd.a, dd.b, dd.common_files) - dd.same_files, dd.diff_files, dd.funny_files = xx - # - def phase4(dd): # Find out differences between common subdirectories - # A new dircmp object is created for each common subdirectory, - # these are stored in a dictionary indexed by filename. - # The hide and ignore properties are inherited from the parent - dd.subdirs = {} - for x in dd.common_dirs: - a_x = path.cat(dd.a, x) - b_x = path.cat(dd.b, x) - dd.subdirs[x] = newdd = dircmp().new(a_x, b_x) - newdd.hide = dd.hide - newdd.ignore = dd.ignore - newdd.run() - # - def phase4_closure(dd): # Recursively call phase4() on subdirectories - dd.phase4() - for x in dd.subdirs.keys(): - dd.subdirs[x].phase4_closure() - # - def report(dd): # Print a report on the differences between a and b - # Assume that phases 1 to 3 have been executed - # Output format is purposely lousy - print 'diff', dd.a, dd.b - if dd.a_only: - print 'Only in', dd.a, ':', dd.a_only - if dd.b_only: - print 'Only in', dd.b, ':', dd.b_only - if dd.same_files: - print 'Identical files :', dd.same_files - if dd.diff_files: - print 'Differing files :', dd.diff_files - if dd.funny_files: - print 'Trouble with common files :', dd.funny_files - if dd.common_dirs: - print 'Common subdirectories :', dd.common_dirs - if dd.common_funny: - print 'Common funny cases :', dd.common_funny - # - def report_closure(dd): # Print reports on dd and on subdirs - # If phase 4 hasn't been done, no subdir reports are printed - dd.report() - try: - x = dd.subdirs - except NameError: - return # No subdirectories computed - for x in dd.subdirs.keys(): - print - dd.subdirs[x].report_closure() - # - def report_phase4_closure(dd): # Report and do phase 4 recursively - dd.report() - dd.phase4() - for x in dd.subdirs.keys(): - print - dd.subdirs[x].report_phase4_closure() + # + def new(dd, (a, b)): # Initialize + dd.a = a + dd.b = b + # Properties that caller may change before callingdd. run(): + dd.hide = ['.', '..'] # Names never to be shown + dd.ignore = ['RCS', 'tags'] # Names ignored in comparison + # + return dd + # + def run(dd): # Compare everything except common subdirectories + dd.a_list = filter(dircache.listdir(dd.a), dd.hide) + dd.b_list = filter(dircache.listdir(dd.b), dd.hide) + dd.a_list.sort() + dd.b_list.sort() + dd.phase1() + dd.phase2() + dd.phase3() + # + def phase1(dd): # Compute common names + dd.a_only = [] + dd.common = [] + for x in dd.a_list: + if x in dd.b_list: + dd.common.append(x) + else: + dd.a_only.append(x) + # + dd.b_only = [] + for x in dd.b_list: + if x not in dd.common: + dd.b_only.append(x) + # + def phase2(dd): # Distinguish files, directories, funnies + dd.common_dirs = [] + dd.common_files = [] + dd.common_funny = [] + # + for x in dd.common: + a_path = path.cat(dd.a, x) + b_path = path.cat(dd.b, x) + # + ok = 1 + try: + a_stat = statcache.stat(a_path) + except posix.error, why: + # print 'Can\'t stat', a_path, ':', why[1] + ok = 0 + try: + b_stat = statcache.stat(b_path) + except posix.error, why: + # print 'Can\'t stat', b_path, ':', why[1] + ok = 0 + # + if ok: + a_type = S_IFMT(a_stat[ST_MODE]) + b_type = S_IFMT(b_stat[ST_MODE]) + if a_type <> b_type: + dd.common_funny.append(x) + elif S_ISDIR(a_type): + dd.common_dirs.append(x) + elif S_ISREG(a_type): + dd.common_files.append(x) + else: + dd.common_funny.append(x) + else: + dd.common_funny.append(x) + # + def phase3(dd): # Find out differences between common files + xx = cmpfiles(dd.a, dd.b, dd.common_files) + dd.same_files, dd.diff_files, dd.funny_files = xx + # + def phase4(dd): # Find out differences between common subdirectories + # A new dircmp object is created for each common subdirectory, + # these are stored in a dictionary indexed by filename. + # The hide and ignore properties are inherited from the parent + dd.subdirs = {} + for x in dd.common_dirs: + a_x = path.cat(dd.a, x) + b_x = path.cat(dd.b, x) + dd.subdirs[x] = newdd = dircmp().new(a_x, b_x) + newdd.hide = dd.hide + newdd.ignore = dd.ignore + newdd.run() + # + def phase4_closure(dd): # Recursively call phase4() on subdirectories + dd.phase4() + for x in dd.subdirs.keys(): + dd.subdirs[x].phase4_closure() + # + def report(dd): # Print a report on the differences between a and b + # Assume that phases 1 to 3 have been executed + # Output format is purposely lousy + print 'diff', dd.a, dd.b + if dd.a_only: + print 'Only in', dd.a, ':', dd.a_only + if dd.b_only: + print 'Only in', dd.b, ':', dd.b_only + if dd.same_files: + print 'Identical files :', dd.same_files + if dd.diff_files: + print 'Differing files :', dd.diff_files + if dd.funny_files: + print 'Trouble with common files :', dd.funny_files + if dd.common_dirs: + print 'Common subdirectories :', dd.common_dirs + if dd.common_funny: + print 'Common funny cases :', dd.common_funny + # + def report_closure(dd): # Print reports on dd and on subdirs + # If phase 4 hasn't been done, no subdir reports are printed + dd.report() + try: + x = dd.subdirs + except NameError: + return # No subdirectories computed + for x in dd.subdirs.keys(): + print + dd.subdirs[x].report_closure() + # + def report_phase4_closure(dd): # Report and do phase 4 recursively + dd.report() + dd.phase4() + for x in dd.subdirs.keys(): + print + dd.subdirs[x].report_phase4_closure() # Compare common files in two directories. # Return: -# - files that compare equal -# - files that compare different -# - funny cases (can't stat etc.) +# - files that compare equal +# - files that compare different +# - funny cases (can't stat etc.) # def cmpfiles(a, b, common): - res = ([], [], []) - for x in common: - res[cmp(path.cat(a, x), path.cat(b, x))].append(x) - return res + res = ([], [], []) + for x in common: + res[cmp(path.cat(a, x), path.cat(b, x))].append(x) + return res # Compare two files. # Return: -# 0 for equal -# 1 for different -# 2 for funny cases (can't stat, etc.) +# 0 for equal +# 1 for different +# 2 for funny cases (can't stat, etc.) # def cmp(a, b): - try: - if cmpcache.cmp(a, b): return 0 - return 1 - except posix.error: - return 2 + try: + if cmpcache.cmp(a, b): return 0 + return 1 + except posix.error: + return 2 # Remove a list item. # NB: This modifies the list argument. # def remove(list, item): - for i in range(len(list)): - if list[i] = item: - del list[i] - break + for i in range(len(list)): + if list[i] = item: + del list[i] + break # Return a copy with items that occur in skip removed. # def filter(list, skip): - result = [] - for item in list: - if item not in skip: result.append(item) - return result + result = [] + for item in list: + if item not in skip: result.append(item) + return result # Demonstration and testing. # def demo(): - import sys - import getopt - options, args = getopt.getopt(sys.argv[1:], 'r') - if len(args) <> 2: raise getopt.error, 'need exactly two args' - dd = dircmp().new(args[0], args[1]) - dd.run() - if ('-r', '') in options: - dd.report_phase4_closure() - else: - dd.report() + import sys + import getopt + options, args = getopt.getopt(sys.argv[1:], 'r') + if len(args) <> 2: raise getopt.error, 'need exactly two args' + dd = dircmp().new(args[0], args[1]) + dd.run() + if ('-r', '') in options: + dd.report_phase4_closure() + else: + dd.report() # demo() diff --git a/lib/dirwin.py b/lib/dirwin.py index 76e0b5e..0b3b5db 100644 --- a/lib/dirwin.py +++ b/lib/dirwin.py @@ -9,21 +9,21 @@ import path import dircache def action(w, string, i, detail): - (h, v), clicks, button, mask = detail - if clicks = 2: - name = path.cat(w.name, string) - try: - w2 = anywin.open(name) - w2.parent = w - except posix.error, why: - stdwin.message('Can\'t open ' + name + ': ' + why[1]) + (h, v), clicks, button, mask = detail + if clicks = 2: + name = path.cat(w.name, string) + try: + w2 = anywin.open(name) + w2.parent = w + except posix.error, why: + stdwin.message('Can\'t open ' + name + ': ' + why[1]) def open(name): - name = path.cat(name, '') - list = dircache.opendir(name)[:] - list.sort() - dircache.annotate(name, list) - w = listwin.open(name, list) - w.name = name - w.action = action - return w + name = path.cat(name, '') + list = dircache.opendir(name)[:] + list.sort() + dircache.annotate(name, list) + w = listwin.open(name, list) + w.name = name + w.action = action + return w @@ -4,64 +4,64 @@ import sys import string def dis(): - tb = sys.last_traceback - while tb.tb_next: tb = tb.tb_next - distb(tb) + tb = sys.last_traceback + while tb.tb_next: tb = tb.tb_next + distb(tb) def distb(tb): - disassemble(tb.tb_frame.f_code, tb.tb_lasti) + disassemble(tb.tb_frame.f_code, tb.tb_lasti) def disco(co): - disassemble(co, -1) + disassemble(co, -1) def disassemble(co, lasti): - code = co.co_code - labels = findlabels(code) - n = len(code) - i = 0 - while i < n: - c = code[i] - op = ord(c) - if op = SET_LINENO and i > 0: print # Extra blank line - if i = lasti: print '-->', - else: print ' ', - if i in labels: print '>>', - else: print ' ', - print string.rjust(`i`, 4), - print string.ljust(opname[op], 15), - i = i+1 - if op >= HAVE_ARGUMENT: - oparg = ord(code[i]) + ord(code[i+1])*256 - i = i+2 - print string.rjust(`oparg`, 5), - if op in hasconst: - print '(' + `co.co_consts[oparg]` + ')', - elif op in hasname: - print '(' + co.co_names[oparg] + ')', - elif op in hasjrel: - print '(to ' + `i + oparg` + ')', - print + code = co.co_code + labels = findlabels(code) + n = len(code) + i = 0 + while i < n: + c = code[i] + op = ord(c) + if op = SET_LINENO and i > 0: print # Extra blank line + if i = lasti: print '-->', + else: print ' ', + if i in labels: print '>>', + else: print ' ', + print string.rjust(`i`, 4), + print string.ljust(opname[op], 15), + i = i+1 + if op >= HAVE_ARGUMENT: + oparg = ord(code[i]) + ord(code[i+1])*256 + i = i+2 + print string.rjust(`oparg`, 5), + if op in hasconst: + print '(' + `co.co_consts[oparg]` + ')', + elif op in hasname: + print '(' + co.co_names[oparg] + ')', + elif op in hasjrel: + print '(to ' + `i + oparg` + ')', + print def findlabels(code): - labels = [] - n = len(code) - i = 0 - while i < n: - c = code[i] - op = ord(c) - i = i+1 - if op >= HAVE_ARGUMENT: - oparg = ord(code[i]) + ord(code[i+1])*256 - i = i+2 - label = -1 - if op in hasjrel: - label = i+oparg - elif op in hasjabs: - label = oparg - if label >= 0: - if label not in labels: - labels.append(label) - return labels + labels = [] + n = len(code) + i = 0 + while i < n: + c = code[i] + op = ord(c) + i = i+1 + if op >= HAVE_ARGUMENT: + oparg = ord(code[i]) + ord(code[i+1])*256 + i = i+2 + label = -1 + if op in hasjrel: + label = i+oparg + elif op in hasjabs: + label = oparg + if label >= 0: + if label not in labels: + labels.append(label) + return labels hasconst = [] hasname = [] @@ -72,19 +72,19 @@ opname = range(256) for op in opname: opname[op] = '<' + `op` + '>' def def_op(name, op): - opname[op] = name + opname[op] = name def name_op(name, op): - opname[op] = name - hasname.append(op) + opname[op] = name + hasname.append(op) def jrel_op(name, op): - opname[op] = name - hasjrel.append(op) + opname[op] = name + hasjrel.append(op) def jabs_op(name, op): - opname[op] = name - hasjabs.append(op) + opname[op] = name + hasjabs.append(op) # Instruction opcodes for compiled code @@ -141,36 +141,36 @@ def_op('POP_BLOCK', 87) def_op('END_FINALLY', 88) def_op('BUILD_CLASS', 89) -HAVE_ARGUMENT = 90 # Opcodes from here have an argument: +HAVE_ARGUMENT = 90 # Opcodes from here have an argument: -name_op('STORE_NAME', 90) # Index in name list -name_op('DELETE_NAME', 91) # "" -def_op('UNPACK_TUPLE', 92) # Number of tuple items -def_op('UNPACK_LIST', 93) # Number of list items -# unused: 94 -name_op('STORE_ATTR', 95) # Index in name list -name_op('DELETE_ATTR', 96) # "" +name_op('STORE_NAME', 90) # Index in name list +name_op('DELETE_NAME', 91) # "" +def_op('UNPACK_TUPLE', 92) # Number of tuple items +def_op('UNPACK_LIST', 93) # Number of list items +# unused: 94 +name_op('STORE_ATTR', 95) # Index in name list +name_op('DELETE_ATTR', 96) # "" -def_op('LOAD_CONST', 100) # Index in const list +def_op('LOAD_CONST', 100) # Index in const list hasconst.append(100) -name_op('LOAD_NAME', 101) # Index in name list -def_op('BUILD_TUPLE', 102) # Number of tuple items -def_op('BUILD_LIST', 103) # Number of list items -def_op('BUILD_MAP', 104) # Always zero for now -name_op('LOAD_ATTR', 105) # Index in name list -def_op('COMPARE_OP', 106) # Comparison operator -name_op('IMPORT_NAME', 107) # Index in name list -name_op('IMPORT_FROM', 108) # Index in name list - -jrel_op('JUMP_FORWARD', 110) # Number of bytes to skip -jrel_op('JUMP_IF_FALSE', 111) # "" -jrel_op('JUMP_IF_TRUE', 112) # "" -jabs_op('JUMP_ABSOLUTE', 113) # Target byte offset from beginning of code -jrel_op('FOR_LOOP', 114) # Number of bytes to skip - -jrel_op('SETUP_LOOP', 120) # Distance to target address -jrel_op('SETUP_EXCEPT', 121) # "" -jrel_op('SETUP_FINALLY', 122) # "" - -def_op('SET_LINENO', 127) # Current line number +name_op('LOAD_NAME', 101) # Index in name list +def_op('BUILD_TUPLE', 102) # Number of tuple items +def_op('BUILD_LIST', 103) # Number of list items +def_op('BUILD_MAP', 104) # Always zero for now +name_op('LOAD_ATTR', 105) # Index in name list +def_op('COMPARE_OP', 106) # Comparison operator +name_op('IMPORT_NAME', 107) # Index in name list +name_op('IMPORT_FROM', 108) # Index in name list + +jrel_op('JUMP_FORWARD', 110) # Number of bytes to skip +jrel_op('JUMP_IF_FALSE', 111) # "" +jrel_op('JUMP_IF_TRUE', 112) # "" +jabs_op('JUMP_ABSOLUTE', 113) # Target byte offset from beginning of code +jrel_op('FOR_LOOP', 114) # Number of bytes to skip + +jrel_op('SETUP_LOOP', 120) # Distance to target address +jrel_op('SETUP_EXCEPT', 121) # "" +jrel_op('SETUP_FINALLY', 122) # "" + +def_op('SET_LINENO', 127) # Current line number SET_LINENO = 127 diff --git a/lib/dump.py b/lib/dump.py index 0510092..cecc275 100644 --- a/lib/dump.py +++ b/lib/dump.py @@ -23,41 +23,41 @@ # Dump a whole symbol table # def dumpsymtab(dict): - for key in dict.keys(): - dumpvar(key, dict[key]) + for key in dict.keys(): + dumpvar(key, dict[key]) # Dump a single variable # def dumpvar(name, x): - import sys - t = type(x) - if t = type({}): - print name, '= {}' - for key in x.keys(): - item = x[key] - if not printable(item): - print '#', - print name, '[', `key`, '] =', `item` - elif t in (type(''), type(0), type(0.0), type([]), type(())): - if not printable(x): - print '#', - print name, '=', `x` - elif t = type(sys): - print 'import', name, '#', x - else: - print '#', name, '=', x + import sys + t = type(x) + if t = type({}): + print name, '= {}' + for key in x.keys(): + item = x[key] + if not printable(item): + print '#', + print name, '[', `key`, '] =', `item` + elif t in (type(''), type(0), type(0.0), type([]), type(())): + if not printable(x): + print '#', + print name, '=', `x` + elif t = type(sys): + print 'import', name, '#', x + else: + print '#', name, '=', x # check if a value is printable in a way that can be read back with input() # def printable(x): - t = type(x) - if t in (type(''), type(0), type(0.0)): - return 1 - if t in (type([]), type(())): - for item in x: - if not printable(item): - return 0 - return 1 - if x = {}: - return 1 - return 0 + t = type(x) + if t in (type(''), type(0), type(0.0)): + return 1 + if t in (type([]), type(())): + for item in x: + if not printable(item): + return 0 + return 1 + if x = {}: + return 1 + return 0 diff --git a/lib/fact.py b/lib/fact.py index ba961c4..2beb0cb 100644 --- a/lib/fact.py +++ b/lib/fact.py @@ -3,35 +3,35 @@ import sys import math -error = 'fact.error' # exception +error = 'fact.error' # exception def fact(n): - if n < 1: raise error # fact() argument should be >= 1 - if n = 1: return [] # special case - res = [] - _fact(n, 2, res) - return res + if n < 1: raise error # fact() argument should be >= 1 + if n = 1: return [] # special case + res = [] + _fact(n, 2, res) + return res def _fact(n, lowest, res): - highest = int(math.sqrt(float(n+1))) - for i in range(lowest, highest+1): - if n%i = 0: - res.append(i) - _fact(n/i, i, res) - break - else: - res.append(n) + highest = int(math.sqrt(float(n+1))) + for i in range(lowest, highest+1): + if n%i = 0: + res.append(i) + _fact(n/i, i, res) + break + else: + res.append(n) def main(): - if len(sys.argv) > 1: - for arg in sys.argv[1:]: - n = eval(arg) - print n, fact(n) - else: - try: - while 1: - print fact(input()) - except EOFError: - pass + if len(sys.argv) > 1: + for arg in sys.argv[1:]: + n = eval(arg) + print n, fact(n) + else: + try: + while 1: + print fact(input()) + except EOFError: + pass main() diff --git a/lib/filewin.py b/lib/filewin.py index ad35ea4..6a224e7 100644 --- a/lib/filewin.py +++ b/lib/filewin.py @@ -8,11 +8,11 @@ from util import readfile # FILE WINDOW def open_readonly(fn): # Open a file window - w = textwin.open_readonly(fn, readfile(fn)) - w.fn = fn - return w + w = textwin.open_readonly(fn, readfile(fn)) + w.fn = fn + return w def open(fn): # Open a file window - w = textwin.open(fn, readfile(fn)) - w.fn = fn - return w + w = textwin.open(fn, readfile(fn)) + w.fn = fn + return w diff --git a/lib/fnmatch.py b/lib/fnmatch.py index 8f9e318..c7caef6 100644 --- a/lib/fnmatch.py +++ b/lib/fnmatch.py @@ -3,33 +3,33 @@ # XXX [] patterns are not supported (but recognized) def fnmatch(name, pat): - if '*' in pat or '?' in pat or '[' in pat: - return fnmatch1(name, pat) - return name = pat + if '*' in pat or '?' in pat or '[' in pat: + return fnmatch1(name, pat) + return name = pat def fnmatch1(name, pat): - for i in range(len(pat)): - c = pat[i] - if c = '*': - restpat = pat[i+1:] - if '*' in restpat or '?' in restpat or '[' in restpat: - for i in range(i, len(name)): - if fnmatch1(name[i:], restpat): - return 1 - return 0 - else: - return name[len(name)-len(restpat):] = restpat - elif c = '?': - if len(name) <= i : return 0 - elif c = '[': - return 0 # XXX - else: - if name[i:i+1] <> c: - return 0 - return 1 + for i in range(len(pat)): + c = pat[i] + if c = '*': + restpat = pat[i+1:] + if '*' in restpat or '?' in restpat or '[' in restpat: + for i in range(i, len(name)): + if fnmatch1(name[i:], restpat): + return 1 + return 0 + else: + return name[len(name)-len(restpat):] = restpat + elif c = '?': + if len(name) <= i : return 0 + elif c = '[': + return 0 # XXX + else: + if name[i:i+1] <> c: + return 0 + return 1 def fnmatchlist(names, pat): - res = [] - for name in names: - if fnmatch(name, pat): res.append(name) - return res + res = [] + for name in names: + if fnmatch(name, pat): res.append(name) + return res diff --git a/lib/getopt.py b/lib/getopt.py index f343c22..ef72fbc 100644 --- a/lib/getopt.py +++ b/lib/getopt.py @@ -12,36 +12,36 @@ # detects an error. # It returns two items: -# (1) a list of pairs (option, option_argument) giving the options in -# the order in which they were specified. (I'd use a dictionary -# but applications may depend on option order or multiple -# occurrences.) Boolean options have '' as option_argument. -# (2) the list of remaining arguments (may be empty). +# (1) a list of pairs (option, option_argument) giving the options in +# the order in which they were specified. (I'd use a dictionary +# but applications may depend on option order or multiple +# occurrences.) Boolean options have '' as option_argument. +# (2) the list of remaining arguments (may be empty). error = 'getopt error' def getopt(args, options): - list = [] - while args and args[0][0] = '-' and args[0] <> '-': - if args[0] = '--': - args = args[1:] - break - optstring, args = args[0][1:], args[1:] - while optstring <> '': - opt, optstring = optstring[0], optstring[1:] - if classify(opt, options): # May raise exception as well - if optstring = '': - if not args: - raise error, 'option -' + opt + ' requires argument' - optstring, args = args[0], args[1:] - optarg, optstring = optstring, '' - else: - optarg = '' - list.append('-' + opt, optarg) - return list, args + list = [] + while args and args[0][0] = '-' and args[0] <> '-': + if args[0] = '--': + args = args[1:] + break + optstring, args = args[0][1:], args[1:] + while optstring <> '': + opt, optstring = optstring[0], optstring[1:] + if classify(opt, options): # May raise exception as well + if optstring = '': + if not args: + raise error, 'option -' + opt + ' requires argument' + optstring, args = args[0], args[1:] + optarg, optstring = optstring, '' + else: + optarg = '' + list.append('-' + opt, optarg) + return list, args def classify(opt, options): # Helper to check type of option - for i in range(len(options)): - if opt = options[i] <> ':': - return options[i+1:i+2] = ':' - raise error, 'option -' + opt + ' not recognized' + for i in range(len(options)): + if opt = options[i] <> ':': + return options[i+1:i+2] = ':' + raise error, 'option -' + opt + ' not recognized' diff --git a/lib/glob.py b/lib/glob.py index b711094..8a70f0e 100644 --- a/lib/glob.py +++ b/lib/glob.py @@ -5,40 +5,40 @@ import path import fnmatch def glob(pathname): - if not has_magic(pathname): return [pathname] - dirname, basename = path.split(pathname) - if dirname[-1:] = '/' and dirname <> '/': - dirname = dirname[:-1] - if has_magic(dirname): - list = glob(dirname) - else: - list = [dirname] - if not has_magic(basename): - result = [] - for dirname in list: - if basename or path.isdir(dirname): - name = path.cat(dirname, basename) - if path.exists(name): - result.append(name) - else: - result = [] - for dirname in list: - sublist = glob1(dirname, basename) - for name in sublist: - result.append(path.cat(dirname, name)) - return result + if not has_magic(pathname): return [pathname] + dirname, basename = path.split(pathname) + if dirname[-1:] = '/' and dirname <> '/': + dirname = dirname[:-1] + if has_magic(dirname): + list = glob(dirname) + else: + list = [dirname] + if not has_magic(basename): + result = [] + for dirname in list: + if basename or path.isdir(dirname): + name = path.cat(dirname, basename) + if path.exists(name): + result.append(name) + else: + result = [] + for dirname in list: + sublist = glob1(dirname, basename) + for name in sublist: + result.append(path.cat(dirname, name)) + return result def glob1(dirname, pattern): - if not dirname: dirname = '.' - try: - names = posix.listdir(dirname) - except posix.error: - return [] - result = [] - for name in names: - if name[0] <> '.' or pattern[0] = '.': - if fnmatch.fnmatch(name, pattern): result.append(name) - return result + if not dirname: dirname = '.' + try: + names = posix.listdir(dirname) + except posix.error: + return [] + result = [] + for name in names: + if name[0] <> '.' or pattern[0] = '.': + if fnmatch.fnmatch(name, pattern): result.append(name) + return result def has_magic(s): - return '*' in s or '?' in s or '[' in s + return '*' in s or '?' in s or '[' in s diff --git a/lib/grep.py b/lib/grep.py index 66eb08d..210f9f0 100644 --- a/lib/grep.py +++ b/lib/grep.py @@ -4,29 +4,29 @@ import regexp import string def grep(expr, filename): - prog = regexp.compile(expr) - fp = open(filename, 'r') - lineno = 0 - while 1: - line = fp.readline() - if not line: break - lineno = lineno + 1 - res = prog.exec(line) - if res: - #print res - start, end = res[0] - if line[-1:] = '\n': line = line[:-1] - prefix = string.rjust(`lineno`, 3) + ': ' - print prefix + line - if 0: - line = line[:start] - if '\t' not in line: - prefix = ' ' * (len(prefix) + start) - else: - prefix = ' ' * len(prefix) - for c in line: - if c <> '\t': c = ' ' - prefix = prefix + c - if start = end: prefix = prefix + '\\' - else: prefix = prefix + '^'*(end-start) - print prefix + prog = regexp.compile(expr) + fp = open(filename, 'r') + lineno = 0 + while 1: + line = fp.readline() + if not line: break + lineno = lineno + 1 + res = prog.exec(line) + if res: + #print res + start, end = res[0] + if line[-1:] = '\n': line = line[:-1] + prefix = string.rjust(`lineno`, 3) + ': ' + print prefix + line + if 0: + line = line[:start] + if '\t' not in line: + prefix = ' ' * (len(prefix) + start) + else: + prefix = ' ' * len(prefix) + for c in line: + if c <> '\t': c = ' ' + prefix = prefix + c + if start = end: prefix = prefix + '\\' + else: prefix = prefix + '^'*(end-start) + print prefix diff --git a/lib/gwin.py b/lib/gwin.py index f6291e1..a53f69c 100644 --- a/lib/gwin.py +++ b/lib/gwin.py @@ -9,113 +9,113 @@ from stdwinevents import * # XXX Old version of stdwinevents, should go import stdwinsupport -S = stdwinsupport # Shorthand +S = stdwinsupport # Shorthand -windows = [] # List of open windows +windows = [] # List of open windows # Open a window -def open(title): # Open a generic window - w = stdwin.open(title) - stdwin.setdefwinsize(0, 0) - # Set default event handlers - w.draw = nop - w.char = nop - w.mdown = nop - w.mmove = nop - w.mup = nop - w.m2down = m2down - w.m2up = m2up - w.size = nop - w.move = nop - w.activate = w.deactivate = nop - w.timer = nop - # default command handlers - w.close = close - w.tab = tab - w.enter = enter - w.backspace = backspace - w.arrow = arrow - w.kleft = w.kup = w.kright = w.kdown = nop - windows.append(w) - return w +def open(title): # Open a generic window + w = stdwin.open(title) + stdwin.setdefwinsize(0, 0) + # Set default event handlers + w.draw = nop + w.char = nop + w.mdown = nop + w.mmove = nop + w.mup = nop + w.m2down = m2down + w.m2up = m2up + w.size = nop + w.move = nop + w.activate = w.deactivate = nop + w.timer = nop + # default command handlers + w.close = close + w.tab = tab + w.enter = enter + w.backspace = backspace + w.arrow = arrow + w.kleft = w.kup = w.kright = w.kdown = nop + windows.append(w) + return w # Generic event dispatching -def mainloop(): # Handle events until no windows left - while windows: - treatevent(stdwin.getevent()) - -def treatevent(e): # Handle a stdwin event - type, w, detail = e - if type = S.we_draw: - w.draw(w, detail) - elif type = S.we_menu: - m, item = detail - m.action[item](w, m, item) - elif type = S.we_command: - treatcommand(w, detail) - elif type = S.we_char: - w.char(w, detail) - elif type = S.we_mouse_down: - if detail[1] > 1: w.m2down(w, detail) - else: w.mdown(w, detail) - elif type = S.we_mouse_move: - w.mmove(w, detail) - elif type = S.we_mouse_up: - if detail[1] > 1: w.m2up(w, detail) - else: w.mup(w, detail) - elif type = S.we_size: - w.size(w, w.getwinsize()) - elif type = S.we_activate: - w.activate(w) - elif type = S.we_deactivate: - w.deactivate(w) - elif type = S.we_move: - w.move(w) - elif type = S.we_timer: - w.timer(w) - elif type = WE_CLOSE: - w.close(w) - -def treatcommand(w, type): # Handle a we_command event - if type = S.wc_close: - w.close(w) - elif type = S.wc_return: - w.enter(w) - elif type = S.wc_tab: - w.tab(w) - elif type = S.wc_backspace: - w.backspace(w) - elif type in (S.wc_left, S.wc_up, S.wc_right, S.wc_down): - w.arrow(w, type) +def mainloop(): # Handle events until no windows left + while windows: + treatevent(stdwin.getevent()) + +def treatevent(e): # Handle a stdwin event + type, w, detail = e + if type = S.we_draw: + w.draw(w, detail) + elif type = S.we_menu: + m, item = detail + m.action[item](w, m, item) + elif type = S.we_command: + treatcommand(w, detail) + elif type = S.we_char: + w.char(w, detail) + elif type = S.we_mouse_down: + if detail[1] > 1: w.m2down(w, detail) + else: w.mdown(w, detail) + elif type = S.we_mouse_move: + w.mmove(w, detail) + elif type = S.we_mouse_up: + if detail[1] > 1: w.m2up(w, detail) + else: w.mup(w, detail) + elif type = S.we_size: + w.size(w, w.getwinsize()) + elif type = S.we_activate: + w.activate(w) + elif type = S.we_deactivate: + w.deactivate(w) + elif type = S.we_move: + w.move(w) + elif type = S.we_timer: + w.timer(w) + elif type = WE_CLOSE: + w.close(w) + +def treatcommand(w, type): # Handle a we_command event + if type = S.wc_close: + w.close(w) + elif type = S.wc_return: + w.enter(w) + elif type = S.wc_tab: + w.tab(w) + elif type = S.wc_backspace: + w.backspace(w) + elif type in (S.wc_left, S.wc_up, S.wc_right, S.wc_down): + w.arrow(w, type) # Methods -def close(w): # Close method - for i in range(len(windows)): - if windows[i] is w: - del windows[i] - break +def close(w): # Close method + for i in range(len(windows)): + if windows[i] is w: + del windows[i] + break -def arrow(w, detail): # Arrow key method - if detail = S.wc_left: - w.kleft(w) - elif detail = S.wc_up: - w.kup(w) - elif detail = S.wc_right: - w.kright(w) - elif detail = S.wc_down: - w.kdown(w) +def arrow(w, detail): # Arrow key method + if detail = S.wc_left: + w.kleft(w) + elif detail = S.wc_up: + w.kup(w) + elif detail = S.wc_right: + w.kright(w) + elif detail = S.wc_down: + w.kdown(w) # Trivial methods def tab(w): w.char(w, '\t') -def enter(w): w.char(w, '\n') # 'return' is a Python reserved word +def enter(w): w.char(w, '\n') # 'return' is a Python reserved word def backspace(w): w.char(w, '\b') def m2down(w, detail): w.mdown(w, detail) def m2up(w, detail): w.mup(w, detail) diff --git a/lib/lambda.py b/lib/lambda.py index 7d62b83..10fe8e0 100644 --- a/lib/lambda.py +++ b/lib/lambda.py @@ -13,16 +13,16 @@ # f and x are stored as data attributes of the member. class _CurryClass(): - def new(self, (f, x)): - self.f = f - self.x = x - return self - def fx(self, y): - return self.f(self.x, y) + def new(self, (f, x)): + self.f = f + self.x = x + return self + def fx(self, y): + return self.f(self.x, y) def CURRY(f, x): - # NB: f is not "simple": it has 2 arguments - return _CurryClass().new(f, x).fx + # NB: f is not "simple": it has 2 arguments + return _CurryClass().new(f, x).fx # Numbers in Lambda Calculus @@ -32,9 +32,9 @@ def CURRY(f, x): # times to x, e.g., Twice(f, x) = f(f(x)). # As far as I understand, there is no difference in real lambda # calculus between -# lambda f x : f(f(x)) +# lambda f x : f(f(x)) # and -# lambda f : f o f # 'o' means function composition +# lambda f : f o f # 'o' means function composition # but in Python we have to write the first as Twice(f, x) and # the second as twice(f). @@ -55,9 +55,9 @@ def fourfold(f): return CURRY(Fourfold, f) # NB: actually 'ntimes' is less concrete than 'Ntimes', as # 'ntimes' returns a function, while 'Ntimes' returns a value -# similar to what f(x) returns. 'Ntimes' can be derived +# similar to what f(x) returns. 'Ntimes' can be derived # from 'ntimes', as follows: -# def Ntimes(f, x): return ntimes(f)(x) +# def Ntimes(f, x): return ntimes(f)(x) # but this doesn't help us since 'ntimes' can only be defined # using Ntimes (or a trick like the one used by CURRY). @@ -65,21 +65,21 @@ def fourfold(f): return CURRY(Fourfold, f) # Arithmetic in Lambda Calculus # # We can perform simple arithmetic on the un-curried versions, e.g., -# Successor(Twice) = Thrice (2+1) -# Sum(Thrice, Twice) = Fivefold (3+2) -# Product(Thrice, Twice) = Sixfold (3*2) -# Power(Thrice, Twice) = Ninefold (3**2) +# Successor(Twice) = Thrice (2+1) +# Sum(Thrice, Twice) = Fivefold (3+2) +# Product(Thrice, Twice) = Sixfold (3*2) +# Power(Thrice, Twice) = Ninefold (3**2) # # First we define versions that need f and x arguments. # They have funny argument forms so the final functions can # use CURRY, which only works on functions of exactly 2 arguments. def SUCCESSOR(Ntimes, (f, x)): return f(Ntimes(f, x)) -def SUCCESSOR(Ntimes, (f, x)): return Ntimes(f, f(x)) # Same effect +def SUCCESSOR(Ntimes, (f, x)): return Ntimes(f, f(x)) # Same effect def SUM(Ntimes, (Mtimes, (f, x))): return Ntimes(f, Mtimes(f, x)) def PRODUCT(Ntimes, (Mtimes, (f, x))): return Ntimes(CURRY(Mtimes, f), x) def POWER(Ntimes, (Mtimes, (f, x))): - return Mtimes(CURRY(CURRY, Ntimes), f)(x) + return Mtimes(CURRY(CURRY, Ntimes), f)(x) def Successor(Ntimes): return CURRY(SUCCESSOR, Ntimes) def Sum(Ntimes, Mtimes): return CURRY(CURRY(SUM, Ntimes), Mtimes) @@ -98,54 +98,54 @@ def Power(Ntimes, Mtimes): return CURRY(CURRY(POWER, Ntimes), Mtimes) # P.S.: Here is a Lambda function in Python. # It uses 'exec' and expects two strings to describe the arguments -# and the function expression. Example: -# lambda('x', 'x+1') +# and the function expression. Example: +# lambda('x', 'x+1') # defines the successor function. def lambda(args, expr): - if '\n' in args or '\n' in expr: - raise RuntimeError, 'lambda: no cheating!' - stmt = 'def func(' + args + '): return ' + expr + '\n' - print 'lambda:', stmt, - exec(stmt) - return func + if '\n' in args or '\n' in expr: + raise RuntimeError, 'lambda: no cheating!' + stmt = 'def func(' + args + '): return ' + expr + '\n' + print 'lambda:', stmt, + exec(stmt) + return func # P.P.S.S.: Here is a way to construct Ntimes and ntimes directly. # Example: -# GenericNtimes(4) +# GenericNtimes(4) # is equivalent to Fourfold. class _GenericNtimesClass(): - def new(self, n): - self.n = n - return self - def Ntimes(self, (f, x)): - n = self.n - while n > 0: x, n = f(x), n-1 - return x + def new(self, n): + self.n = n + return self + def Ntimes(self, (f, x)): + n = self.n + while n > 0: x, n = f(x), n-1 + return x def GenericNtimes(n): - return _GenericNtimesClass().new(n).Ntimes + return _GenericNtimesClass().new(n).Ntimes # To construct any 'ntimes' function from the corresponding 'Ntimes', -# we use a trick as used by CURRY. For example, -# Ntimes2ntimes(Fourfold) +# we use a trick as used by CURRY. For example, +# Ntimes2ntimes(Fourfold) # yields a function equivalent to fourfold. class _Ntimes2ntimesClass(): - def new(self, Ntimes): - self.Ntimes = Ntimes - return self - def ntimes(self, f): - return CURRY(self.Ntimes, f) + def new(self, Ntimes): + self.Ntimes = Ntimes + return self + def ntimes(self, f): + return CURRY(self.Ntimes, f) def Ntimes2ntimes(Ntimes): return _Ntimes2ntimesClass().new(Ntimes).ntimes -# This allows us to construct generic 'ntimes' functions. Example: -# generic_ntimes(3) +# This allows us to construct generic 'ntimes' functions. Example: +# generic_ntimes(3) # is the same as thrice. def generic_ntimes(n): return Ntimes2ntimes(GenericNtimes(n)) diff --git a/lib/listwin.py b/lib/listwin.py index aac127c..9480a81 100644 --- a/lib/listwin.py +++ b/lib/listwin.py @@ -5,43 +5,43 @@ import gwin import stdwin def maxlinewidth(a): # Compute maximum textwidth of lines in a sequence - max = 0 - for line in a: - width = stdwin.textwidth(line) - if width > max: max = width - return max + max = 0 + for line in a: + width = stdwin.textwidth(line) + if width > max: max = width + return max def action(w, string, i, detail): # Default item selection method - pass + pass def mup(w, detail): # Mouse up method - (h, v), clicks, button, mask = detail - i = divmod(v, w.lineheight)[0] - if 0 <= i < len(w.data): - w.action(w, w.data[i], i, detail) + (h, v), clicks, button, mask = detail + i = divmod(v, w.lineheight)[0] + if 0 <= i < len(w.data): + w.action(w, w.data[i], i, detail) def draw(w, ((left, top), (right, bottom))): # Text window draw method - data = w.data - d = w.begindrawing() - lh = w.lineheight - itop = top/lh - ibot = (bottom-1)/lh + 1 - if itop < 0: itop = 0 - if ibot > len(data): ibot = len(data) - for i in range(itop, ibot): d.text((0, i*lh), data[i]) + data = w.data + d = w.begindrawing() + lh = w.lineheight + itop = top/lh + ibot = (bottom-1)/lh + 1 + if itop < 0: itop = 0 + if ibot > len(data): ibot = len(data) + for i in range(itop, ibot): d.text((0, i*lh), data[i]) def open(title, data): # Display a list of texts in a window - lineheight = stdwin.lineheight() - h, v = maxlinewidth(data), len(data)*lineheight - h0, v0 = h + stdwin.textwidth(' '), v + lineheight - if h0 > stdwin.textwidth(' ')*80: h0 = 0 - if v0 > stdwin.lineheight()*24: v0 = 0 - stdwin.setdefwinsize(h0, v0) - w = gwin.open(title) - w.setdocsize(h, v) - w.lineheight = lineheight - w.data = data - w.draw = draw - w.action = action - w.mup = mup - return w + lineheight = stdwin.lineheight() + h, v = maxlinewidth(data), len(data)*lineheight + h0, v0 = h + stdwin.textwidth(' '), v + lineheight + if h0 > stdwin.textwidth(' ')*80: h0 = 0 + if v0 > stdwin.lineheight()*24: v0 = 0 + stdwin.setdefwinsize(h0, v0) + w = gwin.open(title) + w.setdocsize(h, v) + w.lineheight = lineheight + w.data = data + w.draw = draw + w.action = action + w.mup = mup + return w diff --git a/lib/localtime.py b/lib/localtime.py index 5ce6529..1b662e9 100644 --- a/lib/localtime.py +++ b/lib/localtime.py @@ -2,52 +2,52 @@ import posix -epoch = 1970 # 1 jan 00:00:00, UCT -day0 = 4 # day 0 was a thursday +epoch = 1970 # 1 jan 00:00:00, UCT +day0 = 4 # day 0 was a thursday day_names = ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat') -month_names = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun') +month_names = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun') month_names = month_names + ('Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec') month_sizes = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) def isleap(year): - return year % 4 = 0 and (year % 100 <> 0 or year % 400 = 0) - -def gmtime(secs): # decode time into UCT - mins, secs = divmod(secs, 60) - hours, mins = divmod(mins, 60) - days, hours = divmod(hours, 24) - wday = (day0 + days) % 7 - year = epoch - lp = isleap(year) - dpy = 365 + lp - while days >= dpy: - days = days - dpy - year = year + 1 - lp = isleap(year) - dpy = 365 + lp - yday = days - month = 0 - dpm = month_sizes[month] + (lp and month = 1) - while days >= dpm: - days = days - dpm - month = month + 1 - dpm = month_sizes[month] + (lp and month = 1) - return (year, month, days+1, hours, mins, secs, yday, wday) + return year % 4 = 0 and (year % 100 <> 0 or year % 400 = 0) + +def gmtime(secs): # decode time into UCT + mins, secs = divmod(secs, 60) + hours, mins = divmod(mins, 60) + days, hours = divmod(hours, 24) + wday = (day0 + days) % 7 + year = epoch + lp = isleap(year) + dpy = 365 + lp + while days >= dpy: + days = days - dpy + year = year + 1 + lp = isleap(year) + dpy = 365 + lp + yday = days + month = 0 + dpm = month_sizes[month] + (lp and month = 1) + while days >= dpm: + days = days - dpm + month = month + 1 + dpm = month_sizes[month] + (lp and month = 1) + return (year, month, days+1, hours, mins, secs, yday, wday) def dd(x): - s = `x` - while len(s) < 2: s = '0' + s - return s + s = `x` + while len(s) < 2: s = '0' + s + return s def zd(x): - s = `x` - while len(s) < 2: s = ' ' + s - return s + s = `x` + while len(s) < 2: s = ' ' + s + return s def format(year, month, days, hours, mins, secs, yday, wday): - s = day_names[wday] + ' ' + zd(days) + ' ' + month_names[month] + ' ' - s = s + dd(hours) + ':' + dd(mins) + ':' + dd(secs) - return s + s = day_names[wday] + ' ' + zd(days) + ' ' + month_names[month] + ' ' + s = s + dd(hours) + ':' + dd(mins) + ':' + dd(secs) + return s diff --git a/lib/maccache.py b/lib/maccache.py index 329e514..dc6502b 100644 --- a/lib/maccache.py +++ b/lib/maccache.py @@ -25,37 +25,37 @@ FILE = 1 LISTTYPE = type([]) def _stat(name): - name = macpath.cat(cwd, name) - if cache.has_key(name): - return cache[name] - if macpath.isfile(name): - cache[name] = FILE - return FILE - try: - list = mac.listdir(name) - except: - cache[name] = NONE - return NONE - cache[name] = list - if name[-1:] = ':': cache[name[:-1]] = list - else: cache[name+':'] = list - return list + name = macpath.cat(cwd, name) + if cache.has_key(name): + return cache[name] + if macpath.isfile(name): + cache[name] = FILE + return FILE + try: + list = mac.listdir(name) + except: + cache[name] = NONE + return NONE + cache[name] = list + if name[-1:] = ':': cache[name[:-1]] = list + else: cache[name+':'] = list + return list def isdir(name): - st = _stat(name) - return type(st) = LISTTYPE + st = _stat(name) + return type(st) = LISTTYPE def isfile(name): - st = _stat(name) - return st = FILE + st = _stat(name) + return st = FILE def exists(name): - st = _stat(name) - return st <> NONE + st = _stat(name) + return st <> NONE def listdir(name): - st = _stat(name) - if type(st) = LISTTYPE: - return st - else: - raise RuntimeError, 'list non-directory' + st = _stat(name) + if type(st) = LISTTYPE: + return st + else: + raise RuntimeError, 'list non-directory' diff --git a/lib/macglob.py b/lib/macglob.py index cad2c79..f18c396 100644 --- a/lib/macglob.py +++ b/lib/macglob.py @@ -8,39 +8,39 @@ import macpath import fnmatch def glob(pathname): - if not has_magic(pathname): return [pathname] - dirname, basename = macpath.split(pathname) - if has_magic(dirname): - if dirname[-1:] = ':': dirname = dirname[:-1] - list = glob(dirname) - else: - list = [dirname] - if not has_magic(basename): - result = [] - for dirname in list: - if basename or macpath.isdir(dirname): - name = macpath.cat(dirname, basename) - if macpath.exists(name): - result.append(name) - else: - result = [] - for dirname in list: - sublist = glob1(dirname, basename) - for name in sublist: - result.append(macpath.cat(dirname, name)) - return result + if not has_magic(pathname): return [pathname] + dirname, basename = macpath.split(pathname) + if has_magic(dirname): + if dirname[-1:] = ':': dirname = dirname[:-1] + list = glob(dirname) + else: + list = [dirname] + if not has_magic(basename): + result = [] + for dirname in list: + if basename or macpath.isdir(dirname): + name = macpath.cat(dirname, basename) + if macpath.exists(name): + result.append(name) + else: + result = [] + for dirname in list: + sublist = glob1(dirname, basename) + for name in sublist: + result.append(macpath.cat(dirname, name)) + return result def glob1(dirname, pattern): - if not dirname: dirname = ':' - try: - names = mac.listdir(dirname) - except mac.error: - return [] - result = [] - for name in names: - if name[0] <> '.' or pattern[0] = '.': - if fnmatch.fnmatch(name, pattern): result.append(name) - return result + if not dirname: dirname = ':' + try: + names = mac.listdir(dirname) + except mac.error: + return [] + result = [] + for name in names: + if name[0] <> '.' or pattern[0] = '.': + if fnmatch.fnmatch(name, pattern): result.append(name) + return result def has_magic(s): - return '*' in s or '?' in s or '[' in s + return '*' in s or '?' in s or '[' in s diff --git a/lib/macpath.py b/lib/macpath.py index 99ba6b8..99254ab 100644 --- a/lib/macpath.py +++ b/lib/macpath.py @@ -12,7 +12,7 @@ from stat import * # volume name). def isabs(s): - return ':' in s and s[0] <> ':' + return ':' in s and s[0] <> ':' # Concatenate two pathnames. @@ -20,13 +20,13 @@ def isabs(s): # if the first pathname were the current directory. def cat(s, t): - if (not s) or isabs(t): return t - if t[:1] = ':': t = t[1:] - if ':' not in s: - s = ':' + s - if s[-1:] <> ':': - s = s + ':' - return s + t + if (not s) or isabs(t): return t + if t[:1] = ':': t = t[1:] + if ':' not in s: + s = ':' + s + if s[-1:] <> ':': + s = s + ':' + return s + t # Split a pathname in two parts: the directory leading up to the final bit, @@ -34,11 +34,11 @@ def cat(s, t): # The result (s, t) is such that cat(s, t) yields the original argument. def split(s): - if ':' not in s: return '', s - colon = 0 - for i in range(len(s)): - if s[i] = ':': colon = i+1 - return s[:colon], s[colon:] + if ':' not in s: return '', s + colon = 0 + for i in range(len(s)): + if s[i] = ':': colon = i+1 + return s[:colon], s[colon:] # Normalize a pathname: get rid of '::' sequences by backing up, @@ -49,60 +49,60 @@ def split(s): norm_error = 'macpath.norm_error: path cannot be normalized' def norm(s): - import string - if ':' not in s: - return ':' + s - f = string.splitfields(s, ':') - pre = [] - post = [] - if not f[0]: - pre = f[:1] - f = f[1:] - if not f[len(f)-1]: - post = f[-1:] - f = f[:-1] - res = [] - for seg in f: - if seg: - res.append(seg) - else: - if not res: raise norm_error, 'path starts with ::' - del res[len(res)-1] - if not (pre or res): - raise norm_error, 'path starts with volume::' - if pre: res = pre + res - if post: res = res + post - s = res[0] - for seg in res[1:]: - s = s + ':' + seg - return s + import string + if ':' not in s: + return ':' + s + f = string.splitfields(s, ':') + pre = [] + post = [] + if not f[0]: + pre = f[:1] + f = f[1:] + if not f[len(f)-1]: + post = f[-1:] + f = f[:-1] + res = [] + for seg in f: + if seg: + res.append(seg) + else: + if not res: raise norm_error, 'path starts with ::' + del res[len(res)-1] + if not (pre or res): + raise norm_error, 'path starts with volume::' + if pre: res = pre + res + if post: res = res + post + s = res[0] + for seg in res[1:]: + s = s + ':' + seg + return s # Return true if the pathname refers to an existing directory. def isdir(s): - try: - st = mac.stat(s) - except mac.error: - return 0 - return S_ISDIR(st[ST_MODE]) + try: + st = mac.stat(s) + except mac.error: + return 0 + return S_ISDIR(st[ST_MODE]) # Return true if the pathname refers to an existing regular file. def isfile(s): - try: - st = mac.stat(s) - except mac.error: - return 0 - return S_ISREG(st[ST_MODE]) + try: + st = mac.stat(s) + except mac.error: + return 0 + return S_ISREG(st[ST_MODE]) # Return true if the pathname refers to an existing file or directory. def exists(s): - try: - st = mac.stat(s) - except mac.error: - return 0 - return 1 + try: + st = mac.stat(s) + except mac.error: + return 0 + return 1 diff --git a/lib/macshell.py b/lib/macshell.py index c96d65b..884c89c 100644 --- a/lib/macshell.py +++ b/lib/macshell.py @@ -21,379 +21,379 @@ class Struct(): pass G = Struct() def reset(): - G.debug = 0 - G.ps1 = '$ ' - G.homedir = mac.getcwd() - G.commands = mkcmdtab() - G.aliases = {} + G.debug = 0 + G.ps1 = '$ ' + G.homedir = mac.getcwd() + G.commands = mkcmdtab() + G.aliases = {} def mkcmdtab(): - tab = {} - tab['alias'] = do_alias - tab['cd'] = do_cd - tab['debug'] = do_debug - tab['grep'] = do_grep - tab['help'] = do_help - tab['ls'] = do_ls - tab['mkdir'] = do_mkdir - tab['mv'] = do_mv - tab['page'] = do_page - tab['pwd'] = do_pwd - tab['reset'] = do_reset - tab['rm'] = do_rm - tab['rmdir'] = do_rmdir - tab['sync'] = do_sync - tab['unalias'] = do_unalias - return tab + tab = {} + tab['alias'] = do_alias + tab['cd'] = do_cd + tab['debug'] = do_debug + tab['grep'] = do_grep + tab['help'] = do_help + tab['ls'] = do_ls + tab['mkdir'] = do_mkdir + tab['mv'] = do_mv + tab['page'] = do_page + tab['pwd'] = do_pwd + tab['reset'] = do_reset + tab['rm'] = do_rm + tab['rmdir'] = do_rmdir + tab['sync'] = do_sync + tab['unalias'] = do_unalias + return tab def main(): - while 1: - try: - line = raw_input(G.ps1) - except EOFError: - print '[EOF]' - break - except KeyboardInterrupt: - print '[Intr]' - line = '' - if G.debug: - print 'line:', `line` - words = TclUtil.SplitList(line) - if G.debug: - print 'words:', words - if words and words[0][0] <> '#': - run(words) + while 1: + try: + line = raw_input(G.ps1) + except EOFError: + print '[EOF]' + break + except KeyboardInterrupt: + print '[Intr]' + line = '' + if G.debug: + print 'line:', `line` + words = TclUtil.SplitList(line) + if G.debug: + print 'words:', words + if words and words[0][0] <> '#': + run(words) def run(words): - expandaliases(words) - cmd = words[0] - args = words[1:] - if G.commands.has_key(cmd): - if args: - try: - args = expandgloblist(args) - except glob_error, msg: - print cmd, ': glob error :', msg - return - G.commands[cmd](args) - return - if hasglobchar(cmd): - if args: - print cmd, ': cannot glob pattern with arguments' - return - try: - words = expandglobword(cmd) - except glob_error, msg: - print cmd, ': glob error :', msg - return - if len(words) > 1: - columnize(words) - return - cmd = words[0] - print cmd - if isfile(cmd): - if args: - print cmd, ': file command expects no arguments' - return - do_page([cmd]) - elif isdir(cmd): - if args: - print cmd, ': directory command expects no arguments' - return - do_cd([cmd]) - else: - print cmd, ': no such command, file or directory' + expandaliases(words) + cmd = words[0] + args = words[1:] + if G.commands.has_key(cmd): + if args: + try: + args = expandgloblist(args) + except glob_error, msg: + print cmd, ': glob error :', msg + return + G.commands[cmd](args) + return + if hasglobchar(cmd): + if args: + print cmd, ': cannot glob pattern with arguments' + return + try: + words = expandglobword(cmd) + except glob_error, msg: + print cmd, ': glob error :', msg + return + if len(words) > 1: + columnize(words) + return + cmd = words[0] + print cmd + if isfile(cmd): + if args: + print cmd, ': file command expects no arguments' + return + do_page([cmd]) + elif isdir(cmd): + if args: + print cmd, ': directory command expects no arguments' + return + do_cd([cmd]) + else: + print cmd, ': no such command, file or directory' glob_error = 'glob error' def expandgloblist(words): - res = [] - for word in words: - if hasglobchar(word): - res = res + expandglobword(word) - else: - res.append(word) - return res + res = [] + for word in words: + if hasglobchar(word): + res = res + expandglobword(word) + else: + res.append(word) + return res def expandglobword(word): - names = glob.globlist(mac.listdir(':'), word) - if not names: raise glob_error, 'no match for pattern ' + word - return names + names = glob.globlist(mac.listdir(':'), word) + if not names: raise glob_error, 'no match for pattern ' + word + return names def hasglobchar(word): - return '*' in word or '?' in word + return '*' in word or '?' in word def expandaliases(words): - seen = [] - cmd = words[0] - while cmd not in seen and G.aliases.has_key(cmd): - seen.append(cmd) - words[:1] = G.aliases[cmd] - cmd = words[0] + seen = [] + cmd = words[0] + while cmd not in seen and G.aliases.has_key(cmd): + seen.append(cmd) + words[:1] = G.aliases[cmd] + cmd = words[0] def do_alias(args): - if not args: - listaliases() - elif len(args) = 1: - listalias(args[0]) - else: - defalias(args[0], args[1:]) + if not args: + listaliases() + elif len(args) = 1: + listalias(args[0]) + else: + defalias(args[0], args[1:]) def listaliases(): - names = G.aliases.keys() - names.sort() - for name in names: listalias(name) + names = G.aliases.keys() + names.sort() + for name in names: listalias(name) def listalias(name): - if not G.aliases.has_key(name): - print name, ': no such alias' - return - print 'alias', name, - printlist(G.aliases[name]) - print + if not G.aliases.has_key(name): + print name, ': no such alias' + return + print 'alias', name, + printlist(G.aliases[name]) + print def defalias(name, expansion): - G.aliases[name] = expansion + G.aliases[name] = expansion def do_cd(args): - if len(args) > 1: - print 'usage: cd [dirname]' - elif args: - chdirto(args[0]) - else: - chdirto(G.homedir) + if len(args) > 1: + print 'usage: cd [dirname]' + elif args: + chdirto(args[0]) + else: + chdirto(G.homedir) def chdirto(dirname): - try: - mac.chdir(dirname) - except mac.error, msg: - print dirname, ':', msg - return + try: + mac.chdir(dirname) + except mac.error, msg: + print dirname, ':', msg + return def do_debug(args): - G.debug = (not G.debug) + G.debug = (not G.debug) def do_grep(args): - if len(args) < 2: - print 'usage: grep regexp file ...' - return - import regexp - try: - prog = regexp.compile(args[0]) - except regexp.error, msg: - print 'regexp.compile error for', args[0], ':', msg - return - for file in args[1:]: - grepfile(prog, file) + if len(args) < 2: + print 'usage: grep regexp file ...' + return + import regexp + try: + prog = regexp.compile(args[0]) + except regexp.error, msg: + print 'regexp.compile error for', args[0], ':', msg + return + for file in args[1:]: + grepfile(prog, file) def grepfile(prog, file): - try: - fp = open(file, 'r') - except RuntimeError, msg: - print file, ': cannot open :', msg - return - lineno = 0 - while 1: - line = fp.readline() - if not line: break - lineno = lineno+1 - if prog.exec(line): - print file+'('+`lineno`+'):', line, + try: + fp = open(file, 'r') + except RuntimeError, msg: + print file, ': cannot open :', msg + return + lineno = 0 + while 1: + line = fp.readline() + if not line: break + lineno = lineno+1 + if prog.exec(line): + print file+'('+`lineno`+'):', line, def do_help(args): - if args: - print 'usage: help' - return - names = G.commands.keys() - names.sort() - columnize(names) + if args: + print 'usage: help' + return + names = G.commands.keys() + names.sort() + columnize(names) def do_ls(args): - if not args: - lsdir(':') - else: - for dirname in args: - lsdir(dirname) + if not args: + lsdir(':') + else: + for dirname in args: + lsdir(dirname) def lsdir(dirname): - if not isdir(dirname): - print dirname, ': no such directory' - return - names = mac.listdir(dirname) - lsfiles(names, dirname) + if not isdir(dirname): + print dirname, ': no such directory' + return + names = mac.listdir(dirname) + lsfiles(names, dirname) def lsfiles(names, dirname): - names = names[:] # Make a copy so we can modify it - for i in range(len(names)): - name = names[i] - if G.debug: print i, name - if isdir(macpath.cat(dirname, name)): - names[i] = ':' + name + ':' - columnize(names) + names = names[:] # Make a copy so we can modify it + for i in range(len(names)): + name = names[i] + if G.debug: print i, name + if isdir(macpath.cat(dirname, name)): + names[i] = ':' + name + ':' + columnize(names) def columnize(list): - COLUMNS = 80-1 - n = len(list) - colwidth = maxwidth(list) - ncols = (COLUMNS + 1) / (colwidth + 1) - if ncols < 1: ncols = 1 - nrows = (n + ncols - 1) / ncols - for irow in range(nrows): - line = '' - for icol in range(ncols): - i = irow + nrows*icol - if 0 <= i < n: - word = list[i] - if i+nrows < n: - word = string.ljust(word, colwidth) - if icol > 0: - word = ' ' + word - line = line + word - print line + COLUMNS = 80-1 + n = len(list) + colwidth = maxwidth(list) + ncols = (COLUMNS + 1) / (colwidth + 1) + if ncols < 1: ncols = 1 + nrows = (n + ncols - 1) / ncols + for irow in range(nrows): + line = '' + for icol in range(ncols): + i = irow + nrows*icol + if 0 <= i < n: + word = list[i] + if i+nrows < n: + word = string.ljust(word, colwidth) + if icol > 0: + word = ' ' + word + line = line + word + print line def maxwidth(list): - width = 0 - for word in list: - if len(word) > width: - width = len(word) - return width + width = 0 + for word in list: + if len(word) > width: + width = len(word) + return width def do_mv(args): - if len(args) <> 2: - print 'usage: mv src dst' - return - src, dst = args[0], args[1] - if not exists(src): - print src, ': source does not exist' - return - if exists(dst): - print src, ': destination already exists' - return - try: - mac.rename(src, dst) - except mac.error, msg: - print src, dst, ': rename failed:', msg + if len(args) <> 2: + print 'usage: mv src dst' + return + src, dst = args[0], args[1] + if not exists(src): + print src, ': source does not exist' + return + if exists(dst): + print src, ': destination already exists' + return + try: + mac.rename(src, dst) + except mac.error, msg: + print src, dst, ': rename failed:', msg def do_mkdir(args): - if not args: - print 'usage: mkdir name ...' - return - for name in args: - makedir(name) + if not args: + print 'usage: mkdir name ...' + return + for name in args: + makedir(name) def makedir(name): - if exists(name): - print name, ': already exists' - return - try: - mac.mkdir(name, 0777) - except mac.error, msg: - print name, ': mkdir failed:', msg + if exists(name): + print name, ': already exists' + return + try: + mac.mkdir(name, 0777) + except mac.error, msg: + print name, ': mkdir failed:', msg def do_page(args): - if not args: - print 'usage: page file ...' - return - for name in args: - pagefile(name) + if not args: + print 'usage: page file ...' + return + for name in args: + pagefile(name) def pagefile(name): - if not isfile(name): - print name, ': no such file' - return - LINES = 24 - 1 - # For THINK C 3.0, make the path absolute: - # if not macpath.isabs(name): - # name = macpath.cat(mac.getcwd(), name) - try: - fp = open(name, 'r') - except: - print name, ': cannot open' - return - line = fp.readline() - while line: - for i in range(LINES): - print line, - line = fp.readline() - if not line: break - if line: - try: - more = raw_input('[more]') - except (EOFError, KeyboardInterrupt): - print - break - if string.strip(more)[:1] in ('q', 'Q'): - break + if not isfile(name): + print name, ': no such file' + return + LINES = 24 - 1 + # For THINK C 3.0, make the path absolute: + # if not macpath.isabs(name): + # name = macpath.cat(mac.getcwd(), name) + try: + fp = open(name, 'r') + except: + print name, ': cannot open' + return + line = fp.readline() + while line: + for i in range(LINES): + print line, + line = fp.readline() + if not line: break + if line: + try: + more = raw_input('[more]') + except (EOFError, KeyboardInterrupt): + print + break + if string.strip(more)[:1] in ('q', 'Q'): + break def do_pwd(args): - if args: - print 'usage: pwd' - else: - print mac.getcwd() + if args: + print 'usage: pwd' + else: + print mac.getcwd() def do_reset(args): - if args: - print 'usage: reset' - else: - reset() + if args: + print 'usage: reset' + else: + reset() def do_rm(args): - if not args: - print 'usage: rm file ...' - return - for name in args: - remove(name) + if not args: + print 'usage: rm file ...' + return + for name in args: + remove(name) def remove(name): - if not isfile(name): - print name, ': no such file' - return - try: - mac.unlink(name) - except mac.error, msg: - print name, ': unlink failed:', msg + if not isfile(name): + print name, ': no such file' + return + try: + mac.unlink(name) + except mac.error, msg: + print name, ': unlink failed:', msg def do_rmdir(args): - if not args: - print 'usage: rmdir dir ...' - return - for name in args: - rmdir(name) + if not args: + print 'usage: rmdir dir ...' + return + for name in args: + rmdir(name) def rmdir(name): - if not isdir(name): - print name, ': no such directory' - return - try: - mac.rmdir(name) - except mac.error, msg: - print name, ': rmdir failed:', msg + if not isdir(name): + print name, ': no such directory' + return + try: + mac.rmdir(name) + except mac.error, msg: + print name, ': rmdir failed:', msg def do_sync(args): - if args: - print 'usage: sync' - return - try: - mac.sync() - except mac.error, msg: - print 'sync failed:', msg + if args: + print 'usage: sync' + return + try: + mac.sync() + except mac.error, msg: + print 'sync failed:', msg def do_unalias(args): - if not args: - print 'usage: unalias name ...' - return - for name in args: - unalias(name) + if not args: + print 'usage: unalias name ...' + return + for name in args: + unalias(name) def unalias(name): - if not G.aliases.has_key(name): - print name, ': no such alias' - return - del G.aliases[name] + if not G.aliases.has_key(name): + print name, ': no such alias' + return + del G.aliases[name] def printlist(list): - for word in list: - print word, + for word in list: + print word, reset() main() diff --git a/lib/packmail.py b/lib/packmail.py index 40b5b7a..c7bebe8 100644 --- a/lib/packmail.py +++ b/lib/packmail.py @@ -6,43 +6,43 @@ from stat import ST_MTIME # Pack one file def pack(outfp, file, name): - fp = open(file, 'r') - outfp.write('sed "s/^X//" >' + name + ' <<"!"\n') - while 1: - line = fp.readline() - if not line: break - if line[-1:] <> '\n': - line = line + '\n' - outfp.write('X' + line) - outfp.write('!\n') + fp = open(file, 'r') + outfp.write('sed "s/^X//" >' + name + ' <<"!"\n') + while 1: + line = fp.readline() + if not line: break + if line[-1:] <> '\n': + line = line + '\n' + outfp.write('X' + line) + outfp.write('!\n') # Pack some files from a directory def packsome(outfp, dirname, names): - for name in names: - print name - file = macpath.cat(dirname, name) - pack(outfp, file, name) + for name in names: + print name + file = macpath.cat(dirname, name) + pack(outfp, file, name) # Pack all files from a directory def packall(outfp, dirname): - names = mac.listdir(dirname) - names.sort() - packsome(outfp, dirname, names) + names = mac.listdir(dirname) + names.sort() + packsome(outfp, dirname, names) # Pack all files from a directory that are not older than a give one def packnotolder(outfp, dirname, oldest): - names = mac.listdir(dirname) - oldest = macpath.cat(dirname, oldest) - st = mac.stat(oldest) - mtime = st[ST_MTIME] - todo = [] - for name in names: - print name, '...', - st = mac.stat(macpath.cat(dirname, name)) - if st[ST_MTIME] >= mtime: - print 'Yes.' - todo.append(name) - else: - print 'No.' - todo.sort() - packsome(outfp, dirname, todo) + names = mac.listdir(dirname) + oldest = macpath.cat(dirname, oldest) + st = mac.stat(oldest) + mtime = st[ST_MTIME] + todo = [] + for name in names: + print name, '...', + st = mac.stat(macpath.cat(dirname, name)) + if st[ST_MTIME] >= mtime: + print 'Yes.' + todo.append(name) + else: + print 'No.' + todo.sort() + packsome(outfp, dirname, todo) diff --git a/lib/panel.py b/lib/panel.py index 8b0b45c..9fda1c6 100644 --- a/lib/panel.py +++ b/lib/panel.py @@ -17,82 +17,82 @@ debug = 0 # Test if an object is a list. # def is_list(x): - return type(x) = type([]) + return type(x) = type([]) # Reverse a list. # def reverse(list): - res = [] - for item in list: - res.insert(0, item) - return res + res = [] + for item in list: + res.insert(0, item) + return res # Get an attribute of a list, which may itself be another list. # Don't use 'prop' for name. # def getattrlist(list, name): - for item in list: - if item and is_list(item) and item[0] = name: - return item[1:] - return [] + for item in list: + if item and is_list(item) and item[0] = name: + return item[1:] + return [] # Get a property of a list, which may itself be another list. # def getproplist(list, name): - for item in list: - if item and is_list(item) and item[0] = 'prop': - if len(item) > 1 and item[1] = name: - return item[2:] - return [] + for item in list: + if item and is_list(item) and item[0] = 'prop': + if len(item) > 1 and item[1] = name: + return item[2:] + return [] # Test if an actuator description contains the property 'end-of-group' # def is_endgroup(list): - x = getproplist(list, 'end-of-group') - return (x and x[0] = '#t') + x = getproplist(list, 'end-of-group') + return (x and x[0] = '#t') # Neatly display an actuator definition given as S-expression # the prefix string is printed before each line. # def show_actuator(prefix, a): - for item in a: - if not is_list(item): - print prefix, item - elif item and item[0] = 'al': - print prefix, 'Subactuator list:' - for a in item[1:]: - show_actuator(prefix + ' ', a) - elif len(item) = 2: - print prefix, item[0], '=>', item[1] - elif len(item) = 3 and item[0] = 'prop': - print prefix, 'Prop', item[1], '=>', - print item[2] - else: - print prefix, '?', item + for item in a: + if not is_list(item): + print prefix, item + elif item and item[0] = 'al': + print prefix, 'Subactuator list:' + for a in item[1:]: + show_actuator(prefix + ' ', a) + elif len(item) = 2: + print prefix, item[0], '=>', item[1] + elif len(item) = 3 and item[0] = 'prop': + print prefix, 'Prop', item[1], '=>', + print item[2] + else: + print prefix, '?', item # Neatly display a panel. # def show_panel(prefix, p): - for item in p: - if not is_list(item): - print prefix, item - elif item and item[0] = 'al': - print prefix, 'Actuator list:' - for a in item[1:]: - show_actuator(prefix + ' ', a) - elif len(item) = 2: - print prefix, item[0], '=>', item[1] - elif len(item) = 3 and item[0] = 'prop': - print prefix, 'Prop', item[1], '=>', - print item[2] - else: - print prefix, '?', item + for item in p: + if not is_list(item): + print prefix, item + elif item and item[0] = 'al': + print prefix, 'Actuator list:' + for a in item[1:]: + show_actuator(prefix + ' ', a) + elif len(item) = 2: + print prefix, item[0], '=>', item[1] + elif len(item) = 3 and item[0] = 'prop': + print prefix, 'Prop', item[1], '=>', + print item[2] + else: + print prefix, '?', item # Exception raised by build_actuator or build_panel. @@ -103,7 +103,7 @@ panel_error = 'panel error' # Dummy callback used to initialize the callbacks. # def dummy_callback(arg): - pass + pass # Assign attributes to members of the target. @@ -111,60 +111,60 @@ def dummy_callback(arg): # The member name is the attribute name prefixed with the prefix. # def assign_members(target, attrlist, exclist, prefix): - for item in attrlist: - if is_list(item) and len(item) = 2 and item[0] not in exclist: - name, value = item[0], item[1] - ok = 1 - if value[0] in '-0123456789': - value = eval(value) - elif value[0] = '"': - value = value[1:-1] - elif value = 'move-then-resize': - # Strange default set by Panel Editor... - ok = 0 - else: - print 'unknown value', value, 'for', name - ok = 0 - if ok: - lhs = 'target.' + prefix + name - stmt = lhs + '=' + `value` - if debug: print 'exec', stmt - try: - exec(stmt + '\n') - except KeyboardInterrupt: # Don't catch this! - raise KeyboardInterrupt - except: - print 'assign failed:', stmt + for item in attrlist: + if is_list(item) and len(item) = 2 and item[0] not in exclist: + name, value = item[0], item[1] + ok = 1 + if value[0] in '-0123456789': + value = eval(value) + elif value[0] = '"': + value = value[1:-1] + elif value = 'move-then-resize': + # Strange default set by Panel Editor... + ok = 0 + else: + print 'unknown value', value, 'for', name + ok = 0 + if ok: + lhs = 'target.' + prefix + name + stmt = lhs + '=' + `value` + if debug: print 'exec', stmt + try: + exec(stmt + '\n') + except KeyboardInterrupt: # Don't catch this! + raise KeyboardInterrupt + except: + print 'assign failed:', stmt # Build a real actuator from an actuator descriptior. # Return a pair (actuator, name). # def build_actuator(descr): - namelist = getattrlist(descr, 'name') - if namelist: - # Assume it is a string - actuatorname = namelist[0][1:-1] - else: - actuatorname = '' - type = descr[0] - if type[:4] = 'pnl_': type = type[4:] - act = pnl.mkact(type) - act.downfunc = act.activefunc = act.upfunc = dummy_callback - # - assign_members(act, descr[1:], ['al', 'data', 'name'], '') - # - # Treat actuator-specific data - # - datalist = getattrlist(descr, 'data') - prefix = '' - if type[-4:] = 'puck': - prefix = 'puck_' - elif type = 'mouse': - prefix = 'mouse_' - assign_members(act, datalist, [], prefix) - # - return act, actuatorname + namelist = getattrlist(descr, 'name') + if namelist: + # Assume it is a string + actuatorname = namelist[0][1:-1] + else: + actuatorname = '' + type = descr[0] + if type[:4] = 'pnl_': type = type[4:] + act = pnl.mkact(type) + act.downfunc = act.activefunc = act.upfunc = dummy_callback + # + assign_members(act, descr[1:], ['al', 'data', 'name'], '') + # + # Treat actuator-specific data + # + datalist = getattrlist(descr, 'data') + prefix = '' + if type[-4:] = 'puck': + prefix = 'puck_' + elif type = 'mouse': + prefix = 'mouse_' + assign_members(act, datalist, [], prefix) + # + return act, actuatorname # Build all sub-actuators and add them to the super-actuator. @@ -176,27 +176,27 @@ def build_actuator(descr): # to a sub-actuator. # def build_subactuators(panel, super_act, al): - # - # This is nearly the same loop as below in build_panel(), - # except a call is made to addsubact() instead of addact(). - # - for a in al: - act, name = build_actuator(a) - act.addsubact(super_act) - if name: - stmt = 'panel.' + name + ' = act' - if debug: print 'exec', stmt - exec(stmt + '\n') - if is_endgroup(a): - panel.endgroup() - sub_al = getattrlist(a, 'al') - if sub_al: - build_subactuators(panel, act, sub_al) - # - # Fix the actuator to which whe just added subactuators. - # This can't hurt (I hope) and is needed for the scroll actuator. - # - super_act.fixact() + # + # This is nearly the same loop as below in build_panel(), + # except a call is made to addsubact() instead of addact(). + # + for a in al: + act, name = build_actuator(a) + act.addsubact(super_act) + if name: + stmt = 'panel.' + name + ' = act' + if debug: print 'exec', stmt + exec(stmt + '\n') + if is_endgroup(a): + panel.endgroup() + sub_al = getattrlist(a, 'al') + if sub_al: + build_subactuators(panel, act, sub_al) + # + # Fix the actuator to which whe just added subactuators. + # This can't hurt (I hope) and is needed for the scroll actuator. + # + super_act.fixact() # Build a real panel from a panel definition. @@ -204,78 +204,78 @@ def build_subactuators(panel, super_act, al): # reference to a. # def build_panel(descr): - # - # Sanity check - # - if (not descr) or descr[0] <> 'panel': - raise panel_error, 'panel description must start with "panel"' - # - if debug: show_panel('', descr) - # - # Create an empty panel - # - panel = pnl.mkpanel() - # - # Assign panel attributes - # - assign_members(panel, descr[1:], ['al'], '') - # - # Look for actuator list - # - al = getattrlist(descr, 'al') - # - # The order in which actuators are created is important - # because of the endgroup() operator. - # Unfortunately the Panel Editor outputs the actuator list - # in reverse order, so we reverse it here. - # - al = reverse(al) - # - for a in al: - act, name = build_actuator(a) - act.addact(panel) - if name: - stmt = 'panel.' + name + ' = act' - exec(stmt + '\n') - if is_endgroup(a): - panel.endgroup() - sub_al = getattrlist(a, 'al') - if sub_al: - build_subactuators(panel, act, sub_al) - # - return panel + # + # Sanity check + # + if (not descr) or descr[0] <> 'panel': + raise panel_error, 'panel description must start with "panel"' + # + if debug: show_panel('', descr) + # + # Create an empty panel + # + panel = pnl.mkpanel() + # + # Assign panel attributes + # + assign_members(panel, descr[1:], ['al'], '') + # + # Look for actuator list + # + al = getattrlist(descr, 'al') + # + # The order in which actuators are created is important + # because of the endgroup() operator. + # Unfortunately the Panel Editor outputs the actuator list + # in reverse order, so we reverse it here. + # + al = reverse(al) + # + for a in al: + act, name = build_actuator(a) + act.addact(panel) + if name: + stmt = 'panel.' + name + ' = act' + exec(stmt + '\n') + if is_endgroup(a): + panel.endgroup() + sub_al = getattrlist(a, 'al') + if sub_al: + build_subactuators(panel, act, sub_al) + # + return panel # Wrapper around pnl.dopanel() which calls call-back functions. # def my_dopanel(): - # Extract only the first 4 elements to allow for future expansion - a, down, active, up = pnl.dopanel()[:4] - if down: - down.downfunc(down) - if active: - active.activefunc(active) - if up: - up.upfunc(up) - return a + # Extract only the first 4 elements to allow for future expansion + a, down, active, up = pnl.dopanel()[:4] + if down: + down.downfunc(down) + if active: + active.activefunc(active) + if up: + up.upfunc(up) + return a # Create one or more panels from a description file (S-expressions) # generated by the Panel Editor. -# +# def defpanellist(file): - import panelparser - descrlist = panelparser.parse_file(open(file, 'r')) - panellist = [] - for descr in descrlist: - panellist.append(build_panel(descr)) - return panellist + import panelparser + descrlist = panelparser.parse_file(open(file, 'r')) + panellist = [] + for descr in descrlist: + panellist.append(build_panel(descr)) + return panellist # Import everything from built-in method pnl, so the user can always # use panel.foo() instead of pnl.foo(). # This gives *no* performance penalty once this module is imported. # -from pnl import * # for export +from pnl import * # for export -dopanel = my_dopanel # override pnl.dopanel +dopanel = my_dopanel # override pnl.dopanel diff --git a/lib/panelparser.py b/lib/panelparser.py index 5eb2f2b..9c9ee02 100644 --- a/lib/panelparser.py +++ b/lib/panelparser.py @@ -15,47 +15,47 @@ separators = operators + whitespace + ';' + '"' # Return a list of tokens (strings). # def tokenize_string(s): - tokens = [] - while s: - c = s[:1] - if c in whitespace: - s = s[1:] - elif c = ';': - s = '' - elif c = '"': - n = len(s) - i = 1 - while i < n: - c = s[i] - i = i+1 - if c = '"': break - if c = '\\': i = i+1 - tokens.append(s[:i]) - s = s[i:] - elif c in operators: - tokens.append(c) - s = s[1:] - else: - n = len(s) - i = 1 - while i < n: - if s[i] in separators: break - i = i+1 - tokens.append(s[:i]) - s = s[i:] - return tokens + tokens = [] + while s: + c = s[:1] + if c in whitespace: + s = s[1:] + elif c = ';': + s = '' + elif c = '"': + n = len(s) + i = 1 + while i < n: + c = s[i] + i = i+1 + if c = '"': break + if c = '\\': i = i+1 + tokens.append(s[:i]) + s = s[i:] + elif c in operators: + tokens.append(c) + s = s[1:] + else: + n = len(s) + i = 1 + while i < n: + if s[i] in separators: break + i = i+1 + tokens.append(s[:i]) + s = s[i:] + return tokens # Tokenize a whole file (given as file object, not as file name). # Return a list of tokens (strings). # def tokenize_file(fp): - tokens = [] - while 1: - line = fp.readline() - if not line: break - tokens = tokens + tokenize_string(line) - return tokens + tokens = [] + while 1: + line = fp.readline() + if not line: break + tokens = tokens + tokenize_string(line) + return tokens # Exception raised by parse_exr. @@ -71,50 +71,50 @@ syntax_error = 'syntax error' # May raise syntax_error. # def parse_expr(tokens): - if (not tokens) or tokens[0] <> '(': - raise syntax_error, 'expected "("' - tokens = tokens[1:] - expr = [] - while 1: - if not tokens: - raise syntax_error, 'missing ")"' - if tokens[0] = ')': - return expr, tokens[1:] - elif tokens[0] = '(': - subexpr, tokens = parse_expr(tokens) - expr.append(subexpr) - else: - expr.append(tokens[0]) - tokens = tokens[1:] + if (not tokens) or tokens[0] <> '(': + raise syntax_error, 'expected "("' + tokens = tokens[1:] + expr = [] + while 1: + if not tokens: + raise syntax_error, 'missing ")"' + if tokens[0] = ')': + return expr, tokens[1:] + elif tokens[0] = '(': + subexpr, tokens = parse_expr(tokens) + expr.append(subexpr) + else: + expr.append(tokens[0]) + tokens = tokens[1:] # Parse a file (given as file object, not as file name). # Return a list of parsed S-expressions found at the top level. # def parse_file(fp): - tokens = tokenize_file(fp) - exprlist = [] - while tokens: - expr, tokens = parse_expr(tokens) - exprlist.append(expr) - return exprlist + tokens = tokenize_file(fp) + exprlist = [] + while tokens: + expr, tokens = parse_expr(tokens) + exprlist.append(expr) + return exprlist # EXAMPLE: # # The input -# '(hip (hop hur-ray))' +# '(hip (hop hur-ray))' # # passed to tokenize_string() returns the token list -# ['(', 'hip', '(', 'hop', 'hur-ray', ')', ')'] +# ['(', 'hip', '(', 'hop', 'hur-ray', ')', ')'] # # When this is passed to parse_expr() it returns the expression -# ['hip', ['hop', 'hur-ray']] +# ['hip', ['hop', 'hur-ray']] # plus an empty token list (because there are no tokens left. # # When a file containing the example is passed to parse_file() it returns # a list whose only element is the output of parse_expr() above: -# [['hip', ['hop', 'hur-ray']]] +# [['hip', ['hop', 'hur-ray']]] # TOKENIZING: @@ -123,6 +123,6 @@ def parse_file(fp): # # Tokens are separated by whitespace, except the following characters # always form a separate token (outside strings): -# ( ) ' +# ( ) ' # Strings are enclosed in double quotes (") and backslash (\) is used # as escape character in strings. diff --git a/lib/path.py b/lib/path.py index be2340f..0c0d09f 100644 --- a/lib/path.py +++ b/lib/path.py @@ -10,86 +10,86 @@ import stat # (begins with '/'). # def cat(a, b): - if b[:1] = '/': return b - if a = '' or a[-1:] = '/': return a + b - return a + '/' + b + if b[:1] = '/': return b + if a = '' or a[-1:] = '/': return a + b + return a + '/' + b # Split a path in head (empty or ending in '/') and tail (no '/'). # The tail will be empty if the path ends in '/'. # def split(p): - head, tail = '', '' - for c in p: - tail = tail + c - if c = '/': - head, tail = head + tail, '' - return head, tail + head, tail = '', '' + for c in p: + tail = tail + c + if c = '/': + head, tail = head + tail, '' + return head, tail # Return the tail (basename) part of a path. # def basename(p): - return split(p)[1] + return split(p)[1] # Return the longest prefix of all list elements. # def commonprefix(m): - if not m: return '' - prefix = m[0] - for item in m: - for i in range(len(prefix)): - if prefix[:i+1] <> item[:i+1]: - prefix = prefix[:i] - if i = 0: return '' - break - return prefix + if not m: return '' + prefix = m[0] + for item in m: + for i in range(len(prefix)): + if prefix[:i+1] <> item[:i+1]: + prefix = prefix[:i] + if i = 0: return '' + break + return prefix # Does a file/directory exist? # def exists(path): - try: - st = posix.stat(path) - except posix.error: - return 0 - return 1 + try: + st = posix.stat(path) + except posix.error: + return 0 + return 1 # Is a path a posix directory? # def isdir(path): - try: - st = posix.stat(path) - except posix.error: - return 0 - return stat.S_ISDIR(st[stat.ST_MODE]) + try: + st = posix.stat(path) + except posix.error: + return 0 + return stat.S_ISDIR(st[stat.ST_MODE]) # Is a path a symbolic link? # This will always return false on systems where posix.lstat doesn't exist. # def islink(path): - try: - st = posix.lstat(path) - except (posix.error, NameError): - return 0 - return stat.S_ISLNK(st[stat.ST_MODE]) + try: + st = posix.lstat(path) + except (posix.error, NameError): + return 0 + return stat.S_ISLNK(st[stat.ST_MODE]) _mounts = [] def _getmounts(): - import commands, string - mounts = [] - data = commands.getoutput('/etc/mount') - lines = string.splitfields(data, '\n') - for line in lines: - words = string.split(line) - if len(words) >= 3 and words[1] = 'on': - mounts.append(words[2]) - return mounts + import commands, string + mounts = [] + data = commands.getoutput('/etc/mount') + lines = string.splitfields(data, '\n') + for line in lines: + words = string.split(line) + if len(words) >= 3 and words[1] = 'on': + mounts.append(words[2]) + return mounts # Is a path a mount point? @@ -98,9 +98,9 @@ def _getmounts(): # Sorry. # def ismount(path): - if not _mounts: - _mounts[:] = _getmounts() - return path in _mounts + if not _mounts: + _mounts[:] = _getmounts() + return path in _mounts # Directory tree walk. @@ -112,14 +112,14 @@ def ismount(path): # or to impose a different order of visiting. # def walk(top, func, arg): - try: - names = posix.listdir(top) - except posix.error: - return - func(arg, top, names) - exceptions = ('.', '..') - for name in names: - if name not in exceptions: - name = cat(top, name) - if isdir(name): - walk(name, func, arg) + try: + names = posix.listdir(top) + except posix.error: + return + func(arg, top, names) + exceptions = ('.', '..') + for name in names: + if name not in exceptions: + name = cat(top, name) + if isdir(name): + walk(name, func, arg) diff --git a/lib/poly.py b/lib/poly.py index a7c24ec..abac4c8 100644 --- a/lib/poly.py +++ b/lib/poly.py @@ -6,50 +6,50 @@ # taken out by normalize(). def normalize(p): # Strip unnecessary zero coefficients - n = len(p) - while p: - if p[n-1]: return p[:n] - n = n-1 - return [] + n = len(p) + while p: + if p[n-1]: return p[:n] + n = n-1 + return [] def plus(a, b): - if len(a) < len(b): a, b = b, a # make sure a is the longest - res = a[:] # make a copy - for i in range(len(b)): - res[i] = res[i] + b[i] - return normalize(res) + if len(a) < len(b): a, b = b, a # make sure a is the longest + res = a[:] # make a copy + for i in range(len(b)): + res[i] = res[i] + b[i] + return normalize(res) def minus(a, b): - if len(a) < len(b): a, b = b, a # make sure a is the longest - res = a[:] # make a copy - for i in range(len(b)): - res[i] = res[i] - b[i] - return normalize(res) + if len(a) < len(b): a, b = b, a # make sure a is the longest + res = a[:] # make a copy + for i in range(len(b)): + res[i] = res[i] - b[i] + return normalize(res) def one(power, coeff): # Representation of coeff * x**power - res = [] - for i in range(power): res.append(0) - return res + [coeff] + res = [] + for i in range(power): res.append(0) + return res + [coeff] def times(a, b): - res = [] - for i in range(len(a)): - for j in range(len(b)): - res = plus(res, one(i+j, a[i]*b[j])) - return res + res = [] + for i in range(len(a)): + for j in range(len(b)): + res = plus(res, one(i+j, a[i]*b[j])) + return res def power(a, n): # Raise polynomial a to the positive integral power n - if n = 0: return [1] - if n = 1: return a - if n/2*2 = n: - b = power(a, n/2) - return times(b, b) - return times(power(a, n-1), a) + if n = 0: return [1] + if n = 1: return a + if n/2*2 = n: + b = power(a, n/2) + return times(b, b) + return times(power(a, n-1), a) def der(a): # First derivative - res = a[1:] - for i in range(len(res)): - res[i] = res[i] * (i+1) - return res + res = a[1:] + for i in range(len(res)): + res[i] = res[i] * (i+1) + return res # Computing a primitive function would require rational arithmetic... diff --git a/lib/rand.py b/lib/rand.py index 0ca1a53..0616483 100644 --- a/lib/rand.py +++ b/lib/rand.py @@ -3,10 +3,10 @@ import whrandom def srand(seed): - whrandom.seed(seed%256, seed/256%256, seed/65536%256) + whrandom.seed(seed%256, seed/256%256, seed/65536%256) def rand(): - return int(whrandom.random() * 32768.0) % 32768 + return int(whrandom.random() * 32768.0) % 32768 def choice(seq): - return seq[rand() % len(seq)] + return seq[rand() % len(seq)] diff --git a/lib/rect.py b/lib/rect.py index 8f61e11..aa5ff44 100644 --- a/lib/rect.py +++ b/lib/rect.py @@ -18,71 +18,71 @@ empty = (0, 0), (0, 0) # Check if a rectangle is empty. # def is_empty((left, top), (right, bottom)): - return left >= right or top >= bottom + return left >= right or top >= bottom # Compute the intersection or two or more rectangles. # This works with a list or tuple argument. # def intersect(list): - if not list: raise error, 'intersect called with empty list' - if is_empty(list[0]): return empty - (left, top), (right, bottom) = list[0] - for rect in list[1:]: - if is_empty(rect): - return empty - (l, t), (r, b) = rect - if left < l: left = l - if top < t: top = t - if right > r: right = r - if bottom > b: bottom = b - if is_empty((left, top), (right, bottom)): - return empty - return (left, top), (right, bottom) + if not list: raise error, 'intersect called with empty list' + if is_empty(list[0]): return empty + (left, top), (right, bottom) = list[0] + for rect in list[1:]: + if is_empty(rect): + return empty + (l, t), (r, b) = rect + if left < l: left = l + if top < t: top = t + if right > r: right = r + if bottom > b: bottom = b + if is_empty((left, top), (right, bottom)): + return empty + return (left, top), (right, bottom) # Compute the smallest rectangle containing all given rectangles. # This works with a list or tuple argument. # def union(list): - (left, top), (right, bottom) = empty - for (l, t), (r, b) in list[1:]: - if not is_empty((l, t), (r, b)): - if l < left: left = l - if t < top: top = t - if r > right: right = r - if b > bottom: bottom = b - res = (left, top), (right, bottom) - if is_empty(res): - return empty - return res + (left, top), (right, bottom) = empty + for (l, t), (r, b) in list[1:]: + if not is_empty((l, t), (r, b)): + if l < left: left = l + if t < top: top = t + if r > right: right = r + if b > bottom: bottom = b + res = (left, top), (right, bottom) + if is_empty(res): + return empty + return res # Check if a point is in a rectangle. # def pointinrect((h, v), ((left, top), (right, bottom))): - return left <= h < right and top <= v < bottom + return left <= h < right and top <= v < bottom # Return a rectangle that is dh, dv inside another # def inset(((left, top), (right, bottom)), (dh, dv)): - left = left + dh - top = top + dv - right = right - dh - bottom = bottom - dv - r = (left, top), (right, bottom) - if is_empty(r): - return empty - else: - return r + left = left + dh + top = top + dv + right = right - dh + bottom = bottom - dv + r = (left, top), (right, bottom) + if is_empty(r): + return empty + else: + return r # Conversions between rectangles and 'geometry tuples', # given as origin (h, v) and dimensions (width, height). # def rect2geom((left, top), (right, bottom)): - return (left, top), (right-left, bottom-top) + return (left, top), (right-left, bottom-top) def geom2rect((h, v), (width, height)): - return (h, v), (h+width, v+height) + return (h, v), (h+width, v+height) diff --git a/lib/selection.py b/lib/selection.py index 22a0ea9..48947cc 100644 --- a/lib/selection.py +++ b/lib/selection.py @@ -1,6 +1,6 @@ # DAWKINS' BLIND WATCHMAKER -- "METHINKS IT IS LIKE A WEASEL" EXAMPLE # -# Start with a random phrase. Successively: +# Start with a random phrase. Successively: # Breed a next generation by copying with small mutations. # Choose the member of the next generation that most closely resembles # the target phrase to start breeding the next generation. @@ -16,57 +16,57 @@ Alphabet = ' abcdefghijklmnopqrstuvwxyz' GenerationSize = 100 MutationChance = 1.0/28.0 -IndexSet = range(len(Target)) # Used to speed up loops +IndexSet = range(len(Target)) # Used to speed up loops def choice(sequence): - n = len(sequence) - i = int(random() * float(n)) % n - return sequence[i] + n = len(sequence) + i = int(random() * float(n)) % n + return sequence[i] def random_phrase(): - phrase = '' - for i in IndexSet: - phrase = phrase + choice(Alphabet) - return phrase + phrase = '' + for i in IndexSet: + phrase = phrase + choice(Alphabet) + return phrase def mutate_phrase(phrase): - mutant = phrase - for i in range(int(0.5 + MutationChance*float(len(phrase)))): - i = choice(IndexSet) - c = choice(Alphabet) - mutant = mutant[:i] + c + mutant[i+1:] - #print `mutant` - return mutant + mutant = phrase + for i in range(int(0.5 + MutationChance*float(len(phrase)))): + i = choice(IndexSet) + c = choice(Alphabet) + mutant = mutant[:i] + c + mutant[i+1:] + #print `mutant` + return mutant def matching_factor(phrase): - factor = 0 - for i in IndexSet: - if phrase[i] = Target[i]: factor = factor + 1 - return factor + factor = 0 + for i in IndexSet: + if phrase[i] = Target[i]: factor = factor + 1 + return factor def breed_generation(phrase): - generation = [phrase] - while len(generation) < GenerationSize: - generation.append(mutate_phrase(phrase)) - return generation + generation = [phrase] + while len(generation) < GenerationSize: + generation.append(mutate_phrase(phrase)) + return generation def select_best(generation): - factor, selected = -1, '' - for phrase in generation: - f = matching_factor(phrase) - if f > factor: - factor, selected = f, phrase - return selected + factor, selected = -1, '' + for phrase in generation: + f = matching_factor(phrase) + if f > factor: + factor, selected = f, phrase + return selected def main(): - gen = 0 - phrase = random_phrase() - print gen, `phrase` - while phrase <> Target: - next_generation = breed_generation(phrase) - #print next_generation - phrase = select_best(next_generation) - gen = gen+1 - print gen, `phrase` + gen = 0 + phrase = random_phrase() + print gen, `phrase` + while phrase <> Target: + next_generation = breed_generation(phrase) + #print next_generation + phrase = select_best(next_generation) + gen = gen+1 + print gen, `phrase` main() diff --git a/lib/shutil.py b/lib/shutil.py index c01d889..cf63396 100644 --- a/lib/shutil.py +++ b/lib/shutil.py @@ -3,68 +3,68 @@ import posix import path -MODEBITS = 010000 # Lower 12 mode bits +MODEBITS = 010000 # Lower 12 mode bits # Change this to 01000 (9 mode bits) to avoid copying setuid etc. # Copy data from src to dst # def copyfile(src, dst): - fsrc = open(src, 'r') - fdst = open(dst, 'w') - while 1: - buf = fsrc.read(16*1024) - if not buf: break - fdst.write(buf) + fsrc = open(src, 'r') + fdst = open(dst, 'w') + while 1: + buf = fsrc.read(16*1024) + if not buf: break + fdst.write(buf) # Copy mode bits from src to dst # def copymode(src, dst): - st = posix.stat(src) - mode = divmod(st[0], MODEBITS)[1] - posix.chmod(dst, mode) + st = posix.stat(src) + mode = divmod(st[0], MODEBITS)[1] + posix.chmod(dst, mode) # Copy all stat info (mode bits, atime and mtime) from src to dst # def copystat(src, dst): - st = posix.stat(src) - mode = divmod(st[0], MODEBITS)[1] - posix.chmod(dst, mode) - posix.utimes(dst, st[7:9]) + st = posix.stat(src) + mode = divmod(st[0], MODEBITS)[1] + posix.chmod(dst, mode) + posix.utimes(dst, st[7:9]) # Copy data and mode bits ("cp src dst") # def copy(src, dst): - copyfile(src, dst) - copymode(src, dst) + copyfile(src, dst) + copymode(src, dst) # Copy data and all stat info ("cp -p src dst") # def copy2(src, dst): - copyfile(src, dst) - copystat(src, dst) + copyfile(src, dst) + copystat(src, dst) # Recursively copy a directory tree. # The destination must not already exist. # def copytree(src, dst): - names = posix.listdir(src) - posix.mkdir(dst, 0777) - dot_dotdot = '.', '..' - for name in names: - if name not in dot_dotdot: - srcname = path.cat(src, name) - dstname = path.cat(dst, name) - #print 'Copying', srcname, 'to', dstname - try: - #if path.islink(srcname): - # linkto = posix.readlink(srcname) - # posix.symlink(linkto, dstname) - #elif path.isdir(srcname): - if path.isdir(srcname): - copytree(srcname, dstname) - else: - copy2(srcname, dstname) - # XXX What about devices, sockets etc.? - except posix.error, why: - print 'Could not copy', srcname, 'to', dstname, - print '(', why[1], ')' + names = posix.listdir(src) + posix.mkdir(dst, 0777) + dot_dotdot = '.', '..' + for name in names: + if name not in dot_dotdot: + srcname = path.cat(src, name) + dstname = path.cat(dst, name) + #print 'Copying', srcname, 'to', dstname + try: + #if path.islink(srcname): + # linkto = posix.readlink(srcname) + # posix.symlink(linkto, dstname) + #elif path.isdir(srcname): + if path.isdir(srcname): + copytree(srcname, dstname) + else: + copy2(srcname, dstname) + # XXX What about devices, sockets etc.? + except posix.error, why: + print 'Could not copy', srcname, 'to', dstname, + print '(', why[1], ')' diff --git a/lib/stat.py b/lib/stat.py index 83855b6..fee4965 100644 --- a/lib/stat.py +++ b/lib/stat.py @@ -11,47 +11,47 @@ # Tuple indices for stat struct members -ST_MODE = 0 -ST_INO = 1 -ST_DEV = 2 +ST_MODE = 0 +ST_INO = 1 +ST_DEV = 2 ST_NLINK = 3 -ST_UID = 4 -ST_GID = 5 -ST_SIZE = 6 +ST_UID = 4 +ST_GID = 5 +ST_SIZE = 6 ST_ATIME = 7 ST_MTIME = 8 ST_CTIME = 9 def S_IMODE(mode): - return mode%4096 + return mode%4096 def S_IFMT(mode): - return mode - mode%4096 - -S_IFDIR = 0040000 -S_IFCHR = 0020000 -S_IFBLK = 0060000 -S_IFREG = 0100000 -S_IFIFO = 0010000 -S_IFLNK = 0120000 + return mode - mode%4096 + +S_IFDIR = 0040000 +S_IFCHR = 0020000 +S_IFBLK = 0060000 +S_IFREG = 0100000 +S_IFIFO = 0010000 +S_IFLNK = 0120000 S_IFSOCK = 0140000 def S_ISDIR(mode): - return S_IFMT(mode) = S_IFDIR + return S_IFMT(mode) = S_IFDIR def S_ISCHR(mode): - return S_IFMT(mode) = S_IFCHR + return S_IFMT(mode) = S_IFCHR def S_ISBLK(mode): - return S_IFMT(mode) = S_IFBLK + return S_IFMT(mode) = S_IFBLK def S_ISREG(mode): - return S_IFMT(mode) = S_IFREG + return S_IFMT(mode) = S_IFREG def S_ISFIFO(mode): - return S_IFMT(mode) = S_IFIFO + return S_IFMT(mode) = S_IFIFO def S_ISLNK(mode): - return S_IFMT(mode) = S_IFLNK + return S_IFMT(mode) = S_IFLNK def S_ISSOCK(mode): - return S_IFMT(mode) = S_IFSOCK + return S_IFMT(mode) = S_IFSOCK diff --git a/lib/statcache.py b/lib/statcache.py index 0eaf810..36ecc96 100644 --- a/lib/statcache.py +++ b/lib/statcache.py @@ -15,72 +15,72 @@ cache = {} # Stat a file, possibly out of the cache. # def stat(path): - if cache.has_key(path): - return cache[path] - cache[path] = ret = posix.stat(path) - return ret + if cache.has_key(path): + return cache[path] + cache[path] = ret = posix.stat(path) + return ret # Reset the cache completely. # Hack: to reset a global variable, we import this module. # def reset(): - import statcache - # Check that we really imported the same module - if cache is not statcache.cache: - raise 'sorry, statcache identity crisis' - statcache.cache = {} + import statcache + # Check that we really imported the same module + if cache is not statcache.cache: + raise 'sorry, statcache identity crisis' + statcache.cache = {} # Remove a given item from the cache, if it exists. # def forget(path): - if cache.has_key(path): - del cache[path] + if cache.has_key(path): + del cache[path] # Remove all pathnames with a given prefix. # def forget_prefix(prefix): - n = len(prefix) - for path in cache.keys(): - if path[:n] = prefix: - del cache[path] + n = len(prefix) + for path in cache.keys(): + if path[:n] = prefix: + del cache[path] # Forget about a directory and all entries in it, but not about # entries in subdirectories. # def forget_dir(prefix): - if prefix[-1:] = '/' and prefix <> '/': - prefix = prefix[:-1] - forget(prefix) - if prefix[-1:] <> '/': - prefix = prefix + '/' - n = len(prefix) - for path in cache.keys(): - if path[:n] = prefix: - rest = path[n:] - if rest[-1:] = '/': rest = rest[:-1] - if '/' not in rest: - del cache[path] + if prefix[-1:] = '/' and prefix <> '/': + prefix = prefix[:-1] + forget(prefix) + if prefix[-1:] <> '/': + prefix = prefix + '/' + n = len(prefix) + for path in cache.keys(): + if path[:n] = prefix: + rest = path[n:] + if rest[-1:] = '/': rest = rest[:-1] + if '/' not in rest: + del cache[path] # Remove all pathnames except with a given prefix. # Normally used with prefix = '/' after a chdir(). # def forget_except_prefix(prefix): - n = len(prefix) - for path in cache.keys(): - if path[:n] <> prefix: - del cache[path] + n = len(prefix) + for path in cache.keys(): + if path[:n] <> prefix: + del cache[path] # Check for directory. # def isdir(path): - try: - st = stat(path) - except posix.error: - return 0 - return S_ISDIR(st[ST_MODE]) + try: + st = stat(path) + except posix.error: + return 0 + return S_ISDIR(st[ST_MODE]) diff --git a/lib/stdwinevents.py b/lib/stdwinevents.py index fc1c1e7..ab80148 100644 --- a/lib/stdwinevents.py +++ b/lib/stdwinevents.py @@ -1,46 +1,46 @@ # Module 'stdwinevents' -- Constants for stdwin event types # # Suggested usage: -# from stdwinevents import * +# from stdwinevents import * # The function stdwin.getevent() returns a tuple containing: -# (type, window, detail) +# (type, window, detail) # where detail may be <no value> or a value depending on type, see below: # Values for type: -WE_NULL = 0 # not reported -- means 'no event' internally -WE_ACTIVATE = 1 # detail is <no object> -WE_CHAR = 2 # detail is the character -WE_COMMAND = 3 # detail is one of the WC_* constants below -WE_MOUSE_DOWN = 4 # detail is ((h, v), clicks, button, mask) -WE_MOUSE_MOVE = 5 # ditto -WE_MOUSE_UP = 6 # ditto -WE_MENU = 7 # detail is (menu, item) -WE_SIZE = 8 # detail is (width, height) [???] -WE_MOVE = 9 # not reported -- reserved for future use -WE_DRAW = 10 # detail is ((left, top), (right, bottom)) -WE_TIMER = 11 # detail is <no object> -WE_DEACTIVATE = 12 # detail is <no object> -WE_EXTERN = 13 # detail is <no object> -WE_KEY = 14 # detail is ??? -WE_LOST_SEL = 15 # detail is selection number -WE_CLOSE = 16 # detail is <no object> +WE_NULL = 0 # not reported -- means 'no event' internally +WE_ACTIVATE = 1 # detail is <no object> +WE_CHAR = 2 # detail is the character +WE_COMMAND = 3 # detail is one of the WC_* constants below +WE_MOUSE_DOWN = 4 # detail is ((h, v), clicks, button, mask) +WE_MOUSE_MOVE = 5 # ditto +WE_MOUSE_UP = 6 # ditto +WE_MENU = 7 # detail is (menu, item) +WE_SIZE = 8 # detail is (width, height) [???] +WE_MOVE = 9 # not reported -- reserved for future use +WE_DRAW = 10 # detail is ((left, top), (right, bottom)) +WE_TIMER = 11 # detail is <no object> +WE_DEACTIVATE = 12 # detail is <no object> +WE_EXTERN = 13 # detail is <no object> +WE_KEY = 14 # detail is ??? +WE_LOST_SEL = 15 # detail is selection number +WE_CLOSE = 16 # detail is <no object> # Values for detail when type is WE_COMMAND: -WC_CLOSE = 1 # user hit close box -WC_LEFT = 2 # left arrow key -WC_RIGHT = 3 # right arrow key -WC_UP = 4 # up arrow key -WC_DOWN = 5 # down arrow key -WC_CANCEL = 6 # not reported -- turned into KeyboardInterrupt -WC_BACKSPACE = 7 # backspace key -WC_TAB = 8 # tab key -WC_RETURN = 9 # return or enter key +WC_CLOSE = 1 # user hit close box +WC_LEFT = 2 # left arrow key +WC_RIGHT = 3 # right arrow key +WC_UP = 4 # up arrow key +WC_DOWN = 5 # down arrow key +WC_CANCEL = 6 # not reported -- turned into KeyboardInterrupt +WC_BACKSPACE = 7 # backspace key +WC_TAB = 8 # tab key +WC_RETURN = 9 # return or enter key # Selection numbers -WS_CLIPBOARD = 0 -WS_PRIMARY = 1 -WS_SECONDARY = 2 +WS_CLIPBOARD = 0 +WS_PRIMARY = 1 +WS_SECONDARY = 2 diff --git a/lib/stdwinsupport.py b/lib/stdwinsupport.py index 1a28072..296c1d8 100644 --- a/lib/stdwinsupport.py +++ b/lib/stdwinsupport.py @@ -2,33 +2,33 @@ import stdwin -eventnames = ['null', 'activate', 'char', 'command'] +eventnames = ['null', 'activate', 'char', 'command'] eventnames = eventnames + ['mouse_down', 'mouse_move', 'mouse_up', 'menu'] eventnames = eventnames + ['size', 'move', 'draw', 'timer', 'deactivate'] -we_null = 0 -we_activate = 1 -we_char = 2 -we_command = 3 -we_mouse_down = 4 -we_mouse_move = 5 -we_mouse_up = 6 -we_menu = 7 -we_size = 8 -we_move = 9 -we_draw = 10 -we_timer = 11 +we_null = 0 +we_activate = 1 +we_char = 2 +we_command = 3 +we_mouse_down = 4 +we_mouse_move = 5 +we_mouse_up = 6 +we_menu = 7 +we_size = 8 +we_move = 9 +we_draw = 10 +we_timer = 11 we_deactivate = 12 commandnames = ['?', 'close', 'left', 'right', 'up', 'down', 'cancel'] commandnames = commandnames + ['backspace', 'tab', 'return'] -wc_close = 1 -wc_left = 2 -wc_right = 3 -wc_up = 4 -wc_down = 5 -wc_cancel = 6 # not reported -- turned into KeyboardInterrupt +wc_close = 1 +wc_left = 2 +wc_right = 3 +wc_up = 4 +wc_down = 5 +wc_cancel = 6 # not reported -- turned into KeyboardInterrupt wc_backspace = 7 -wc_tab = 8 -wc_return = 9 +wc_tab = 8 +wc_return = 9 diff --git a/lib/string.py b/lib/string.py index 5262013..3790357 100644 --- a/lib/string.py +++ b/lib/string.py @@ -14,116 +14,116 @@ octdigits = '01234567' # Case conversion helpers _caseswap = {} for i in range(26): - _caseswap[lowercase[i]] = uppercase[i] - _caseswap[uppercase[i]] = lowercase[i] + _caseswap[lowercase[i]] = uppercase[i] + _caseswap[uppercase[i]] = lowercase[i] del i # convert UPPER CASE letters to lower case def lower(s): - res = '' - for c in s: - if 'A' <= c <= 'Z': c = _caseswap[c] - res = res + c - return res + res = '' + for c in s: + if 'A' <= c <= 'Z': c = _caseswap[c] + res = res + c + return res # Convert lower case letters to UPPER CASE def upper(s): - res = '' - for c in s: - if 'a' <= c <= 'z': c = _caseswap[c] - res = res + c - return res + res = '' + for c in s: + if 'a' <= c <= 'z': c = _caseswap[c] + res = res + c + return res # Swap lower case letters and UPPER CASE def swapcase(s): - res = '' - for c in s: - if 'a' <= c <= 'z' or 'A' <= c <= 'Z': c = _caseswap[c] - res = res + c - return res + res = '' + for c in s: + if 'a' <= c <= 'z' or 'A' <= c <= 'Z': c = _caseswap[c] + res = res + c + return res # Strip leading and trailing tabs and spaces def strip(s): - i, j = 0, len(s) - while i < j and s[i] in whitespace: i = i+1 - while i < j and s[j-1] in whitespace: j = j-1 - return s[i:j] + i, j = 0, len(s) + while i < j and s[i] in whitespace: i = i+1 + while i < j and s[j-1] in whitespace: j = j-1 + return s[i:j] # Split a string into a list of space/tab-separated words # NB: split(s) is NOT the same as splitfields(s, ' ')! def split(s): - res = [] - i, n = 0, len(s) - while i < n: - while i < n and s[i] in whitespace: i = i+1 - if i = n: break - j = i - while j < n and s[j] not in whitespace: j = j+1 - res.append(s[i:j]) - i = j - return res + res = [] + i, n = 0, len(s) + while i < n: + while i < n and s[i] in whitespace: i = i+1 + if i = n: break + j = i + while j < n and s[j] not in whitespace: j = j+1 + res.append(s[i:j]) + i = j + return res # Split a list into fields separated by a given string # NB: splitfields(s, ' ') is NOT the same as split(s)! def splitfields(s, sep): - res = [] - ns = len(s) - nsep = len(sep) - i = j = 0 - while j+nsep <= ns: - if s[j:j+nsep] = sep: - res.append(s[i:j]) - i = j = j + nsep - else: - j = j + 1 - res.append(s[i:]) - return res + res = [] + ns = len(s) + nsep = len(sep) + i = j = 0 + while j+nsep <= ns: + if s[j:j+nsep] = sep: + res.append(s[i:j]) + i = j = j + nsep + else: + j = j + 1 + res.append(s[i:]) + return res # Find substring index_error = 'substring not found in string.index' def index(s, sub): - n = len(sub) - for i in range(len(s) + 1 - n): - if sub = s[i:i+n]: return i - raise index_error, (s, sub) + n = len(sub) + for i in range(len(s) + 1 - n): + if sub = s[i:i+n]: return i + raise index_error, (s, sub) # Convert string to integer atoi_error = 'non-numeric argument to string.atoi' def atoi(str): - s = str - if s[:1] in '+-': s = s[1:] - if not s: raise atoi_error, str - for c in s: - if c not in digits: raise atoi_error, str - return eval(str) + s = str + if s[:1] in '+-': s = s[1:] + if not s: raise atoi_error, str + for c in s: + if c not in digits: raise atoi_error, str + return eval(str) # Left-justify a string def ljust(s, width): - n = len(s) - if n >= width: return s - return s + ' '*(width-n) + n = len(s) + if n >= width: return s + return s + ' '*(width-n) # Right-justify a string def rjust(s, width): - n = len(s) - if n >= width: return s - return ' '*(width-n) + s + n = len(s) + if n >= width: return s + return ' '*(width-n) + s # Center a string def center(s, width): - n = len(s) - if n >= width: return s - return ' '*((width-n)/2) + s + ' '*(width -(width-n)/2) + n = len(s) + if n >= width: return s + return ' '*((width-n)/2) + s + ' '*(width -(width-n)/2) # Zero-fill a number, e.g., (12, 3) --> '012' and (-3, 3) --> '-03' # Decadent feature: the argument may be a string or a number # (Use of this is deprecated; it should be a string as with ljust c.s.) def zfill(x, width): - if type(x) = type(''): s = x - else: s = `x` - n = len(s) - if n >= width: return s - sign = '' - if s[0] = '-': - sign, s = '-', s[1:] - return sign + '0'*(width-n) + s + if type(x) = type(''): s = x + else: s = `x` + n = len(s) + if n >= width: return s + sign = '' + if s[0] = '-': + sign, s = '-', s[1:] + return sign + '0'*(width-n) + s diff --git a/lib/sunaudio.py b/lib/sunaudio.py index ed1b6e4..92a6203 100644 --- a/lib/sunaudio.py +++ b/lib/sunaudio.py @@ -10,45 +10,45 @@ error = 'sunaudio sound header conversion error' # convert a 4-char value to integer def c2i(data): - if type(data) <> type('') or len(data) <> 4: - raise error, 'c2i: bad arg (not string[4])' - bytes = audio.chr2num(data) - for i in (1, 2, 3): - if bytes[i] < 0: - bytes[i] = bytes[i] + 256 - return ((bytes[0]*256 + bytes[1])*256 + bytes[2])*256 + bytes[3] + if type(data) <> type('') or len(data) <> 4: + raise error, 'c2i: bad arg (not string[4])' + bytes = audio.chr2num(data) + for i in (1, 2, 3): + if bytes[i] < 0: + bytes[i] = bytes[i] + 256 + return ((bytes[0]*256 + bytes[1])*256 + bytes[2])*256 + bytes[3] # read a sound header from an open file def gethdr(fp): - if fp.read(4) <> MAGIC: - raise error, 'gethdr: bad magic word' - hdr_size = c2i(fp.read(4)) - data_size = c2i(fp.read(4)) - encoding = c2i(fp.read(4)) - sample_rate = c2i(fp.read(4)) - channels = c2i(fp.read(4)) - excess = hdr_size - 24 - if excess < 0: - raise error, 'gethdr: bad hdr_size' - if excess > 0: - info = fp.read(excess) - else: - info = '' - return (data_size, encoding, sample_rate, channels, info) + if fp.read(4) <> MAGIC: + raise error, 'gethdr: bad magic word' + hdr_size = c2i(fp.read(4)) + data_size = c2i(fp.read(4)) + encoding = c2i(fp.read(4)) + sample_rate = c2i(fp.read(4)) + channels = c2i(fp.read(4)) + excess = hdr_size - 24 + if excess < 0: + raise error, 'gethdr: bad hdr_size' + if excess > 0: + info = fp.read(excess) + else: + info = '' + return (data_size, encoding, sample_rate, channels, info) # read and print the sound header of a named file def printhdr(file): - hdr = gethdr(open(file, 'r')) - data_size, encoding, sample_rate, channels, info = hdr - while info[-1:] = '\0': - info = info[:-1] - print 'File name: ', file - print 'Data size: ', data_size - print 'Encoding: ', encoding - print 'Sample rate:', sample_rate - print 'Channels: ', channels - print 'Info: ', `info` + hdr = gethdr(open(file, 'r')) + data_size, encoding, sample_rate, channels, info = hdr + while info[-1:] = '\0': + info = info[:-1] + print 'File name: ', file + print 'Data size: ', data_size + print 'Encoding: ', encoding + print 'Sample rate:', sample_rate + print 'Channels: ', channels + print 'Info: ', `info` diff --git a/lib/tablewin.py b/lib/tablewin.py index df06476..05a954e 100644 --- a/lib/tablewin.py +++ b/lib/tablewin.py @@ -2,11 +2,11 @@ # Display a table, with per-item actions: -# A1 | A2 | A3 | .... | AN -# B1 | B2 | B3 | .... | BN -# C1 | C2 | C3 | .... | CN -# .. | .. | .. | .... | .. -# Z1 | Z2 | Z3 | .... | ZN +# A1 | A2 | A3 | .... | AN +# B1 | B2 | B3 | .... | BN +# C1 | C2 | C3 | .... | CN +# .. | .. | .. | .... | .. +# Z1 | Z2 | Z3 | .... | ZN # Not all columns need to have the same length. # The data structure is a list of columns; @@ -18,220 +18,220 @@ import stdwin import gwin def open(title, data): # Public function to open a table window - # - # Set geometry parameters (one day, these may be changeable) - # - margin = stdwin.textwidth(' ') - lineheight = stdwin.lineheight() - # - # Geometry calculations - # - colstarts = [0] - totwidth = 0 - maxrows = 0 - for coldata in data: - # Height calculations - rows = len(coldata) - if rows > maxrows: maxrows = rows - # Width calculations - width = colwidth(coldata) + margin - totwidth = totwidth + width - colstarts.append(totwidth) - # - # Calculate document and window height - # - docwidth, docheight = totwidth, maxrows*lineheight - winwidth, winheight = docwidth, docheight - if winwidth > stdwin.textwidth('n')*100: winwidth = 0 - if winheight > stdwin.lineheight()*30: winheight = 0 - # - # Create the window - # - stdwin.setdefwinsize(winwidth, winheight) - w = gwin.open(title) - # - # Set properties and override methods - # - w.data = data - w.margin = margin - w.lineheight = lineheight - w.colstarts = colstarts - w.totwidth = totwidth - w.maxrows = maxrows - w.selection = (-1, -1) - w.lastselection = (-1, -1) - w.selshown = 0 - w.setdocsize(docwidth, docheight) - w.draw = draw - w.mup = mup - w.arrow = arrow - # - # Return - # - return w + # + # Set geometry parameters (one day, these may be changeable) + # + margin = stdwin.textwidth(' ') + lineheight = stdwin.lineheight() + # + # Geometry calculations + # + colstarts = [0] + totwidth = 0 + maxrows = 0 + for coldata in data: + # Height calculations + rows = len(coldata) + if rows > maxrows: maxrows = rows + # Width calculations + width = colwidth(coldata) + margin + totwidth = totwidth + width + colstarts.append(totwidth) + # + # Calculate document and window height + # + docwidth, docheight = totwidth, maxrows*lineheight + winwidth, winheight = docwidth, docheight + if winwidth > stdwin.textwidth('n')*100: winwidth = 0 + if winheight > stdwin.lineheight()*30: winheight = 0 + # + # Create the window + # + stdwin.setdefwinsize(winwidth, winheight) + w = gwin.open(title) + # + # Set properties and override methods + # + w.data = data + w.margin = margin + w.lineheight = lineheight + w.colstarts = colstarts + w.totwidth = totwidth + w.maxrows = maxrows + w.selection = (-1, -1) + w.lastselection = (-1, -1) + w.selshown = 0 + w.setdocsize(docwidth, docheight) + w.draw = draw + w.mup = mup + w.arrow = arrow + # + # Return + # + return w def update(w, data): # Change the data - # - # Hide selection - # - hidesel(w, w.begindrawing()) - # - # Get old geometry parameters - # - margin = w.margin - lineheight = w.lineheight - # - # Geometry calculations - # - colstarts = [0] - totwidth = 0 - maxrows = 0 - for coldata in data: - # Height calculations - rows = len(coldata) - if rows > maxrows: maxrows = rows - # Width calculations - width = colwidth(coldata) + margin - totwidth = totwidth + width - colstarts.append(totwidth) - # - # Calculate document and window height - # - docwidth, docheight = totwidth, maxrows*lineheight - # - # Set changed properties and change window size - # - w.data = data - w.colstarts = colstarts - w.totwidth = totwidth - w.maxrows = maxrows - w.change((0, 0), (10000, 10000)) - w.setdocsize(docwidth, docheight) - w.change((0, 0), (docwidth, docheight)) - # - # Show selection, or forget it if out of range - # - showsel(w, w.begindrawing()) - if not w.selshown: w.selection = (-1, -1) + # + # Hide selection + # + hidesel(w, w.begindrawing()) + # + # Get old geometry parameters + # + margin = w.margin + lineheight = w.lineheight + # + # Geometry calculations + # + colstarts = [0] + totwidth = 0 + maxrows = 0 + for coldata in data: + # Height calculations + rows = len(coldata) + if rows > maxrows: maxrows = rows + # Width calculations + width = colwidth(coldata) + margin + totwidth = totwidth + width + colstarts.append(totwidth) + # + # Calculate document and window height + # + docwidth, docheight = totwidth, maxrows*lineheight + # + # Set changed properties and change window size + # + w.data = data + w.colstarts = colstarts + w.totwidth = totwidth + w.maxrows = maxrows + w.change((0, 0), (10000, 10000)) + w.setdocsize(docwidth, docheight) + w.change((0, 0), (docwidth, docheight)) + # + # Show selection, or forget it if out of range + # + showsel(w, w.begindrawing()) + if not w.selshown: w.selection = (-1, -1) def colwidth(coldata): # Subroutine to calculate column width - maxwidth = 0 - for string, action in coldata: - width = stdwin.textwidth(string) - if width > maxwidth: maxwidth = width - return maxwidth + maxwidth = 0 + for string, action in coldata: + width = stdwin.textwidth(string) + if width > maxwidth: maxwidth = width + return maxwidth def draw(w, ((left, top), (right, bottom))): # Draw method - ileft = whichcol(w, left) - iright = whichcol(w, right-1) + 1 - if iright > len(w.data): iright = len(w.data) - itop = divmod(top, w.lineheight)[0] - if itop < 0: itop = 0 - ibottom, remainder = divmod(bottom, w.lineheight) - if remainder: ibottom = ibottom + 1 - d = w.begindrawing() - if ileft <= w.selection[0] < iright: - if itop <= w.selection[1] < ibottom: - hidesel(w, d) - d.erase((left, top), (right, bottom)) - for i in range(ileft, iright): - col = w.data[i] - jbottom = len(col) - if ibottom < jbottom: jbottom = ibottom - h = w.colstarts[i] - v = itop * w.lineheight - for j in range(itop, jbottom): - string, action = col[j] - d.text((h, v), string) - v = v + w.lineheight - showsel(w, d) + ileft = whichcol(w, left) + iright = whichcol(w, right-1) + 1 + if iright > len(w.data): iright = len(w.data) + itop = divmod(top, w.lineheight)[0] + if itop < 0: itop = 0 + ibottom, remainder = divmod(bottom, w.lineheight) + if remainder: ibottom = ibottom + 1 + d = w.begindrawing() + if ileft <= w.selection[0] < iright: + if itop <= w.selection[1] < ibottom: + hidesel(w, d) + d.erase((left, top), (right, bottom)) + for i in range(ileft, iright): + col = w.data[i] + jbottom = len(col) + if ibottom < jbottom: jbottom = ibottom + h = w.colstarts[i] + v = itop * w.lineheight + for j in range(itop, jbottom): + string, action = col[j] + d.text((h, v), string) + v = v + w.lineheight + showsel(w, d) def mup(w, detail): # Mouse up method - (h, v), nclicks, button, mask = detail - icol = whichcol(w, h) - if 0 <= icol < len(w.data): - irow = divmod(v, w.lineheight)[0] - col = w.data[icol] - if 0 <= irow < len(col): - string, action = col[irow] - action(w, string, (icol, irow), detail) + (h, v), nclicks, button, mask = detail + icol = whichcol(w, h) + if 0 <= icol < len(w.data): + irow = divmod(v, w.lineheight)[0] + col = w.data[icol] + if 0 <= irow < len(col): + string, action = col[irow] + action(w, string, (icol, irow), detail) def whichcol(w, h): # Return column number (may be >= len(w.data)) - for icol in range(0, len(w.data)): - if h < w.colstarts[icol+1]: - return icol - return len(w.data) + for icol in range(0, len(w.data)): + if h < w.colstarts[icol+1]: + return icol + return len(w.data) def arrow(w, type): - import stdwinsupport - S = stdwinsupport - if type = S.wc_left: - incr = -1, 0 - elif type = S.wc_up: - incr = 0, -1 - elif type = S.wc_right: - incr = 1, 0 - elif type = S.wc_down: - incr = 0, 1 - else: - return - icol, irow = w.lastselection - icol = icol + incr[0] - if icol < 0: icol = len(w.data)-1 - if icol >= len(w.data): icol = 0 - if 0 <= icol < len(w.data): - irow = irow + incr[1] - if irow < 0: irow = len(w.data[icol]) - 1 - if irow >= len(w.data[icol]): irow = 0 - else: - irow = 0 - if 0 <= icol < len(w.data) and 0 <= irow < len(w.data[icol]): - w.lastselection = icol, irow - string, action = w.data[icol][irow] - detail = (0, 0), 1, 1, 1 - action(w, string, (icol, irow), detail) + import stdwinsupport + S = stdwinsupport + if type = S.wc_left: + incr = -1, 0 + elif type = S.wc_up: + incr = 0, -1 + elif type = S.wc_right: + incr = 1, 0 + elif type = S.wc_down: + incr = 0, 1 + else: + return + icol, irow = w.lastselection + icol = icol + incr[0] + if icol < 0: icol = len(w.data)-1 + if icol >= len(w.data): icol = 0 + if 0 <= icol < len(w.data): + irow = irow + incr[1] + if irow < 0: irow = len(w.data[icol]) - 1 + if irow >= len(w.data[icol]): irow = 0 + else: + irow = 0 + if 0 <= icol < len(w.data) and 0 <= irow < len(w.data[icol]): + w.lastselection = icol, irow + string, action = w.data[icol][irow] + detail = (0, 0), 1, 1, 1 + action(w, string, (icol, irow), detail) # Selection management # TO DO: allow multiple selected entries def select(w, selection): # Public function to set the item selection - d = w.begindrawing() - hidesel(w, d) - w.selection = selection - showsel(w, d) - if w.selshown: lastselection = selection + d = w.begindrawing() + hidesel(w, d) + w.selection = selection + showsel(w, d) + if w.selshown: lastselection = selection def hidesel(w, d): # Hide the selection, if shown - if w.selshown: invertsel(w, d) + if w.selshown: invertsel(w, d) def showsel(w, d): # Show the selection, if hidden - if not w.selshown: invertsel(w, d) + if not w.selshown: invertsel(w, d) def invertsel(w, d): # Invert the selection, if valid - icol, irow = w.selection - if 0 <= icol < len(w.data) and 0 <= irow < len(w.data[icol]): - left = w.colstarts[icol] - right = w.colstarts[icol+1] - top = irow * w.lineheight - bottom = (irow+1) * w.lineheight - d.invert((left, top), (right, bottom)) - w.selshown = (not w.selshown) + icol, irow = w.selection + if 0 <= icol < len(w.data) and 0 <= irow < len(w.data[icol]): + left = w.colstarts[icol] + right = w.colstarts[icol+1] + top = irow * w.lineheight + bottom = (irow+1) * w.lineheight + d.invert((left, top), (right, bottom)) + w.selshown = (not w.selshown) # Demonstration def demo_action(w, string, (icol, irow), detail): # Action function for demo - select(w, (irow, icol)) + select(w, (irow, icol)) def demo(): # Demonstration - da = demo_action # shorthand - col0 = [('a1', da), ('bbb1', da), ('c1', da)] - col1 = [('a2', da), ('bbb2', da)] - col2 = [('a3', da), ('b3', da), ('c3', da), ('d4', da), ('d5', da)] - col3 = [] - for i in range(1, 31): col3.append('xxx' + `i`, da) - data = [col0, col1, col2, col3] - w = open('tablewin.demo', data) - gwin.mainloop() - return w + da = demo_action # shorthand + col0 = [('a1', da), ('bbb1', da), ('c1', da)] + col1 = [('a2', da), ('bbb2', da)] + col2 = [('a3', da), ('b3', da), ('c3', da), ('d4', da), ('d5', da)] + col3 = [] + for i in range(1, 31): col3.append('xxx' + `i`, da) + data = [col0, col1, col2, col3] + w = open('tablewin.demo', data) + gwin.mainloop() + return w @@ -3,11 +3,11 @@ import sys try: - import mac - os = mac + import mac + os = mac except NameError: - import posix - os = posix + import posix + os = posix from stat import * import string @@ -16,205 +16,205 @@ def br(): browser(sys.last_traceback) def tb(): printtb(sys.last_traceback) def browser(tb): - if not tb: - print 'No traceback.' - return - tblist = [] - while tb: - tblist.append(tb) - tb = tb.tb_next - ptr = len(tblist)-1 - tb = tblist[ptr] - while 1: - if tb <> tblist[ptr]: - tb = tblist[ptr] - print `ptr` + ':', - printtbheader(tb) - try: - line = raw_input('TB: ') - except KeyboardInterrupt: - print '\n[Interrupted]' - break - except EOFError: - print '\n[EOF]' - break - cmd = string.strip(line) - if cmd: - if cmd = 'quit': - break - elif cmd = 'list': - browserlist(tb) - elif cmd = 'up': - if ptr-1 >= 0: ptr = ptr-1 - else: print 'Bottom of stack.' - elif cmd = 'down': - if ptr+1 < len(tblist): ptr = ptr+1 - else: print 'Top of stack.' - elif cmd = 'locals': - printsymbols(tb.tb_frame.f_locals) - elif cmd = 'globals': - printsymbols(tb.tb_frame.f_globals) - elif cmd in ('?', 'help'): - browserhelp() - else: - browserexec(tb, cmd) + if not tb: + print 'No traceback.' + return + tblist = [] + while tb: + tblist.append(tb) + tb = tb.tb_next + ptr = len(tblist)-1 + tb = tblist[ptr] + while 1: + if tb <> tblist[ptr]: + tb = tblist[ptr] + print `ptr` + ':', + printtbheader(tb) + try: + line = raw_input('TB: ') + except KeyboardInterrupt: + print '\n[Interrupted]' + break + except EOFError: + print '\n[EOF]' + break + cmd = string.strip(line) + if cmd: + if cmd = 'quit': + break + elif cmd = 'list': + browserlist(tb) + elif cmd = 'up': + if ptr-1 >= 0: ptr = ptr-1 + else: print 'Bottom of stack.' + elif cmd = 'down': + if ptr+1 < len(tblist): ptr = ptr+1 + else: print 'Top of stack.' + elif cmd = 'locals': + printsymbols(tb.tb_frame.f_locals) + elif cmd = 'globals': + printsymbols(tb.tb_frame.f_globals) + elif cmd in ('?', 'help'): + browserhelp() + else: + browserexec(tb, cmd) def browserlist(tb): - filename = tb.tb_frame.f_code.co_filename - lineno = tb.tb_lineno - last = lineno - first = max(1, last-10) - for i in range(first, last+1): - if i = lineno: prefix = '***' + string.rjust(`i`, 4) + ':' - else: prefix = string.rjust(`i`, 7) + ':' - line = readfileline(filename, i) - if line[-1:] = '\n': line = line[:-1] - print prefix + line + filename = tb.tb_frame.f_code.co_filename + lineno = tb.tb_lineno + last = lineno + first = max(1, last-10) + for i in range(first, last+1): + if i = lineno: prefix = '***' + string.rjust(`i`, 4) + ':' + else: prefix = string.rjust(`i`, 7) + ':' + line = readfileline(filename, i) + if line[-1:] = '\n': line = line[:-1] + print prefix + line def browserexec(tb, cmd): - locals = tb.tb_frame.f_locals - globals = tb.tb_frame.f_globals - try: - exec(cmd+'\n', globals, locals) - except: - print '*** Exception:', - print sys.exc_type, - if sys.exc_value <> None: - print ':', sys.exc_value, - print - print 'Type help to get help.' + locals = tb.tb_frame.f_locals + globals = tb.tb_frame.f_globals + try: + exec(cmd+'\n', globals, locals) + except: + print '*** Exception:', + print sys.exc_type, + if sys.exc_value <> None: + print ':', sys.exc_value, + print + print 'Type help to get help.' def browserhelp(): - print - print ' This is the traceback browser. Commands are:' - print ' up : move one level up in the call stack' - print ' down : move one level down in the call stack' - print ' locals : print all local variables at this level' - print ' globals : print all global variables at this level' - print ' list : list source code around the failure' - print ' help : print help (what you are reading now)' - print ' quit : back to command interpreter' - print ' Typing any other 1-line statement will execute it' - print ' using the current level\'s symbol tables' - print + print + print ' This is the traceback browser. Commands are:' + print ' up : move one level up in the call stack' + print ' down : move one level down in the call stack' + print ' locals : print all local variables at this level' + print ' globals : print all global variables at this level' + print ' list : list source code around the failure' + print ' help : print help (what you are reading now)' + print ' quit : back to command interpreter' + print ' Typing any other 1-line statement will execute it' + print ' using the current level\'s symbol tables' + print def printtb(tb): - while tb: - print1tb(tb) - tb = tb.tb_next + while tb: + print1tb(tb) + tb = tb.tb_next def print1tb(tb): - printtbheader(tb) - if tb.tb_frame.f_locals is not tb.tb_frame.f_globals: - printsymbols(tb.tb_frame.f_locals) + printtbheader(tb) + if tb.tb_frame.f_locals is not tb.tb_frame.f_globals: + printsymbols(tb.tb_frame.f_locals) def printtbheader(tb): - filename = tb.tb_frame.f_code.co_filename - lineno = tb.tb_lineno - info = '"' + filename + '"(' + `lineno` + ')' - line = readfileline(filename, lineno) - if line: - info = info + ': ' + string.strip(line) - print info + filename = tb.tb_frame.f_code.co_filename + lineno = tb.tb_lineno + info = '"' + filename + '"(' + `lineno` + ')' + line = readfileline(filename, lineno) + if line: + info = info + ': ' + string.strip(line) + print info def printsymbols(d): - keys = d.keys() - keys.sort() - for name in keys: - print ' ' + string.ljust(name, 12) + ':', - printobject(d[name], 4) - print + keys = d.keys() + keys.sort() + for name in keys: + print ' ' + string.ljust(name, 12) + ':', + printobject(d[name], 4) + print def printobject(v, maxlevel): - if v = None: - print 'None', - elif type(v) in (type(0), type(0.0)): - print v, - elif type(v) = type(''): - if len(v) > 20: - print `v[:17] + '...'`, - else: - print `v`, - elif type(v) = type(()): - print '(', - printlist(v, maxlevel) - print ')', - elif type(v) = type([]): - print '[', - printlist(v, maxlevel) - print ']', - elif type(v) = type({}): - print '{', - printdict(v, maxlevel) - print '}', - else: - print v, + if v = None: + print 'None', + elif type(v) in (type(0), type(0.0)): + print v, + elif type(v) = type(''): + if len(v) > 20: + print `v[:17] + '...'`, + else: + print `v`, + elif type(v) = type(()): + print '(', + printlist(v, maxlevel) + print ')', + elif type(v) = type([]): + print '[', + printlist(v, maxlevel) + print ']', + elif type(v) = type({}): + print '{', + printdict(v, maxlevel) + print '}', + else: + print v, def printlist(v, maxlevel): - n = len(v) - if n = 0: return - if maxlevel <= 0: - print '...', - return - for i in range(min(6, n)): - printobject(v[i], maxlevel-1) - if i+1 < n: print ',', - if n > 6: print '...', + n = len(v) + if n = 0: return + if maxlevel <= 0: + print '...', + return + for i in range(min(6, n)): + printobject(v[i], maxlevel-1) + if i+1 < n: print ',', + if n > 6: print '...', def printdict(v, maxlevel): - keys = v.keys() - n = len(keys) - if n = 0: return - if maxlevel <= 0: - print '...', - return - keys.sort() - for i in range(min(6, n)): - key = keys[i] - print `key` + ':', - printobject(v[key], maxlevel-1) - if i+1 < n: print ',', - if n > 6: print '...', + keys = v.keys() + n = len(keys) + if n = 0: return + if maxlevel <= 0: + print '...', + return + keys.sort() + for i in range(min(6, n)): + key = keys[i] + print `key` + ':', + printobject(v[key], maxlevel-1) + if i+1 < n: print ',', + if n > 6: print '...', _filecache = {} def readfileline(filename, lineno): - try: - stat = os.stat(filename) - except os.error, msg: - print 'Cannot stat', filename, '--', msg - return '' - cache_ok = 0 - if _filecache.has_key(filename): - cached_stat, lines = _filecache[filename] - if stat[ST_SIZE] = cached_stat[ST_SIZE] and \ - stat[ST_MTIME] = cached_stat[ST_MTIME]: - cache_ok = 1 - else: - print 'Stale cache entry for', filename - del _filecache[filename] - if not cache_ok: - lines = readfilelines(filename) - if not lines: - return '' - _filecache[filename] = stat, lines - if 0 <= lineno-1 < len(lines): - return lines[lineno-1] - else: - print 'Line number out of range, last line is', len(lines) - return '' + try: + stat = os.stat(filename) + except os.error, msg: + print 'Cannot stat', filename, '--', msg + return '' + cache_ok = 0 + if _filecache.has_key(filename): + cached_stat, lines = _filecache[filename] + if stat[ST_SIZE] = cached_stat[ST_SIZE] and \ + stat[ST_MTIME] = cached_stat[ST_MTIME]: + cache_ok = 1 + else: + print 'Stale cache entry for', filename + del _filecache[filename] + if not cache_ok: + lines = readfilelines(filename) + if not lines: + return '' + _filecache[filename] = stat, lines + if 0 <= lineno-1 < len(lines): + return lines[lineno-1] + else: + print 'Line number out of range, last line is', len(lines) + return '' def readfilelines(filename): - try: - fp = open(filename, 'r') - except: - print 'Cannot open', filename - return [] - lines = [] - while 1: - line = fp.readline() - if not line: break - lines.append(line) - if not lines: - print 'Empty file', filename - return lines + try: + fp = open(filename, 'r') + except: + print 'Cannot open', filename + return [] + lines = [] + while 1: + line = fp.readline() + if not line: break + lines.append(line) + if not lines: + print 'Empty file', filename + return lines diff --git a/lib/testall.py b/lib/testall.py index d9fd7e5..ef7cb13 100644 --- a/lib/testall.py +++ b/lib/testall.py @@ -1,20 +1,20 @@ # Module 'testall' # # Python test set, should exercise: -# - all lexical and grammatical constructs -# - all opcodes from "opcode.h" -# - all operations on all object types -# - all builtin functions +# - all lexical and grammatical constructs +# - all opcodes from "opcode.h" +# - all operations on all object types +# - all builtin functions # Ideally also: -# - all possible exception situations (Thank God we've got 'try') -# - all boundary cases +# - all possible exception situations (Thank God we've got 'try') +# - all boundary cases -TestFailed = 'testall -- test failed' # Exception +TestFailed = 'testall -- test failed' # Exception ######################################################### -# Part 1. Test all lexical and grammatical constructs. +# Part 1. Test all lexical and grammatical constructs. # This just tests whether the parser accepts them all. ######################################################### @@ -67,7 +67,7 @@ def f3(two, arguments): pass def f4(two, (compound, (arguments))): pass ### stmt: simple_stmt | compound_stmt -### simple_stmt: expr_stmt | print_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt +### simple_stmt: expr_stmt | print_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt # Tested below print 'expr_stmt' # (exprlist '=')* exprlist NEWLINE @@ -122,7 +122,7 @@ from time import sleep [4] from math import * [5] -from sys import modules, path +from sys import modules, ps1, ps2 [6] ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef @@ -172,16 +172,16 @@ finally: pass print 'suite' # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT if 1: pass if 1: - pass + pass if 1: - # - # - # - pass - pass - # - pass - # + # + # + # + pass + pass + # + pass + # print 'test' # and_test ('or' and_test)* ### and_test: not_test ('and' not_test)* @@ -213,7 +213,7 @@ print 'factor' # ('+'|'-') factor | atom trailer* x = +1 x = -1 x = 1 -c = sys.path[0] +c = sys.ps1[0] x = time.time() x = sys.modules['time'].time() a = '01234' @@ -253,13 +253,13 @@ class C1() = B(): pass class C2() = B(): pass class D() = C1(), C2(), B(): pass class C(): - def meth1(self): pass - def meth2(self, arg): pass - def meth3(self, (a1, a2)): pass + def meth1(self): pass + def meth2(self, arg): pass + def meth3(self, (a1, a2)): pass ######################################################### -# Part 2. Test all opcodes from "opcode.h" +# Part 2. Test all opcodes from "opcode.h" ######################################################### print '2. Opcodes' @@ -268,23 +268,23 @@ print 'XXX Not yet fully implemented' print '2.1 try inside for loop' n = 0 for i in range(10): - n = n+i - try: 1/0 - except NameError: pass - except RuntimeError: pass - except TypeError: pass - finally: pass - try: pass - except: pass - try: pass - finally: pass - n = n+i + n = n+i + try: 1/0 + except NameError: pass + except RuntimeError: pass + except TypeError: pass + finally: pass + try: pass + except: pass + try: pass + finally: pass + n = n+i if n <> 90: - raise TestFailed, 'try inside for' + raise TestFailed, 'try inside for' ######################################################### -# Part 3. Test all operations on all object types +# Part 3. Test all operations on all object types ######################################################### print '3. Object types' @@ -292,7 +292,7 @@ print 'XXX Not yet implemented' ######################################################### -# Part 4. Test all built-in functions +# Part 4. Test all built-in functions ######################################################### print '4. Built-in functions' @@ -364,7 +364,7 @@ fp.close() del fp fp = open('@test', 'r') if fp.readline() <> 'The quick brown fox jumps over the lazy dog.\n': - raise TestFailed, 'readline()' + raise TestFailed, 'readline()' if fp.readline(4) <> 'Dear': raise TestFailed, 'readline(4) # short' if fp.readline(100) <> ' John\n': raise TestFailed, 'readline(100)' if fp.read(300) <> 'XXX'*100: raise TestFailed, 'read(300)' @@ -383,13 +383,13 @@ if range(5, -5, -3) <> [5, 2, -1, -4]: raise TestFailed, 'range(5, -5, -3)' print 'raw_input' savestdin = sys.stdin try: - sys.stdin = open('@test', 'r') - if raw_input() <> 'The quick brown fox jumps over the lazy dog.': - raise TestFailed, 'raw_input()' - if raw_input('testing\n') <> 'Dear John': - raise TestFailed, 'raw_input(\'testing\\n\')' + sys.stdin = open('@test', 'r') + if raw_input() <> 'The quick brown fox jumps over the lazy dog.': + raise TestFailed, 'raw_input()' + if raw_input('testing\n') <> 'Dear John': + raise TestFailed, 'raw_input(\'testing\\n\')' finally: - sys.stdin = savestdin + sys.stdin = savestdin print 'reload' import string @@ -397,20 +397,20 @@ reload(string) print 'type' if type('') <> type('123') or type('') = type(()): - raise TestFailed, 'type()' + raise TestFailed, 'type()' print 'Passed all tests.' try: - import mac - unlink = mac.unlink + import mac + unlink = mac.unlink except NameError: - try: - import posix - unlink = posix.unlink - except NameError: - pass + try: + import posix + unlink = posix.unlink + except NameError: + pass unlink('@test') print 'Unlinked @test' diff --git a/lib/textwin.py b/lib/textwin.py index d12342f..a003a9a 100644 --- a/lib/textwin.py +++ b/lib/textwin.py @@ -6,114 +6,114 @@ import stdwin import stdwinsupport import gwin -S = stdwinsupport # Shorthand +S = stdwinsupport # Shorthand def fixsize(w): - docwidth, docheight = w.text.getrect()[1] - winheight = w.getwinsize()[1] - if winheight > docheight: docheight = winheight - w.setdocsize(0, docheight) - fixeditmenu(w) + docwidth, docheight = w.text.getrect()[1] + winheight = w.getwinsize()[1] + if winheight > docheight: docheight = winheight + w.setdocsize(0, docheight) + fixeditmenu(w) def cut(w, m, id): - s = w.text.getfocustext() - if s: - stdwin.setcutbuffer(0, s) - w.text.replace('') - fixsize(w) + s = w.text.getfocustext() + if s: + stdwin.setcutbuffer(0, s) + w.text.replace('') + fixsize(w) def copy(w, m, id): - s = w.text.getfocustext() - if s: - stdwin.setcutbuffer(0, s) - fixeditmenu(w) + s = w.text.getfocustext() + if s: + stdwin.setcutbuffer(0, s) + fixeditmenu(w) def paste(w, m, id): - w.text.replace(stdwin.getcutbuffer(0)) - fixsize(w) + w.text.replace(stdwin.getcutbuffer(0)) + fixsize(w) def addeditmenu(w): - m = w.editmenu = w.menucreate('Edit') - m.action = [] - m.additem('Cut', 'X') - m.action.append(cut) - m.additem('Copy', 'C') - m.action.append(copy) - m.additem('Paste', 'V') - m.action.append(paste) + m = w.editmenu = w.menucreate('Edit') + m.action = [] + m.additem('Cut', 'X') + m.action.append(cut) + m.additem('Copy', 'C') + m.action.append(copy) + m.additem('Paste', 'V') + m.action.append(paste) def fixeditmenu(w): - m = w.editmenu - f = w.text.getfocus() - can_copy = (f[0] < f[1]) - m.enable(1, can_copy) - if not w.readonly: - m.enable(0, can_copy) - m.enable(2, (stdwin.getcutbuffer(0) <> '')) - -def draw(w, area): # Draw method - w.text.draw(area) - -def size(w, newsize): # Size method - w.text.move((0, 0), newsize) - fixsize(w) - -def close(w): # Close method - del w.text # Break circular ref - gwin.close(w) - -def char(w, c): # Char method - w.text.replace(c) - fixsize(w) - -def backspace(w): # Backspace method - void = w.text.event(S.we_command, w, S.wc_backspace) - fixsize(w) - -def arrow(w, detail): # Arrow method - w.text.arrow(detail) - fixeditmenu(w) - -def mdown(w, detail): # Mouse down method - void = w.text.event(S.we_mouse_down, w, detail) - fixeditmenu(w) - -def mmove(w, detail): # Mouse move method - void = w.text.event(S.we_mouse_move, w, detail) - -def mup(w, detail): # Mouse up method - void = w.text.event(S.we_mouse_up, w, detail) - fixeditmenu(w) - -def activate(w): # Activate method - fixeditmenu(w) - -def open(title, str): # Display a string in a window - w = gwin.open(title) - w.readonly = 0 - w.text = w.textcreate((0, 0), w.getwinsize()) - w.text.replace(str) - w.text.setfocus(0, 0) - addeditmenu(w) - fixsize(w) - w.draw = draw - w.size = size - w.close = close - w.mdown = mdown - w.mmove = mmove - w.mup = mup - w.char = char - w.backspace = backspace - w.arrow = arrow - w.activate = activate - return w - -def open_readonly(title, str): # Same with char input disabled - w = open(title, str) - w.readonly = 1 - w.char = w.backspace = gwin.nop - # Disable Cut and Paste menu item; leave Copy alone - w.editmenu.enable(0, 0) - w.editmenu.enable(2, 0) - return w + m = w.editmenu + f = w.text.getfocus() + can_copy = (f[0] < f[1]) + m.enable(1, can_copy) + if not w.readonly: + m.enable(0, can_copy) + m.enable(2, (stdwin.getcutbuffer(0) <> '')) + +def draw(w, area): # Draw method + w.text.draw(area) + +def size(w, newsize): # Size method + w.text.move((0, 0), newsize) + fixsize(w) + +def close(w): # Close method + del w.text # Break circular ref + gwin.close(w) + +def char(w, c): # Char method + w.text.replace(c) + fixsize(w) + +def backspace(w): # Backspace method + void = w.text.event(S.we_command, w, S.wc_backspace) + fixsize(w) + +def arrow(w, detail): # Arrow method + w.text.arrow(detail) + fixeditmenu(w) + +def mdown(w, detail): # Mouse down method + void = w.text.event(S.we_mouse_down, w, detail) + fixeditmenu(w) + +def mmove(w, detail): # Mouse move method + void = w.text.event(S.we_mouse_move, w, detail) + +def mup(w, detail): # Mouse up method + void = w.text.event(S.we_mouse_up, w, detail) + fixeditmenu(w) + +def activate(w): # Activate method + fixeditmenu(w) + +def open(title, str): # Display a string in a window + w = gwin.open(title) + w.readonly = 0 + w.text = w.textcreate((0, 0), w.getwinsize()) + w.text.replace(str) + w.text.setfocus(0, 0) + addeditmenu(w) + fixsize(w) + w.draw = draw + w.size = size + w.close = close + w.mdown = mdown + w.mmove = mmove + w.mup = mup + w.char = char + w.backspace = backspace + w.arrow = arrow + w.activate = activate + return w + +def open_readonly(title, str): # Same with char input disabled + w = open(title, str) + w.readonly = 1 + w.char = w.backspace = gwin.nop + # Disable Cut and Paste menu item; leave Copy alone + w.editmenu.enable(0, 0) + w.editmenu.enable(2, 0) + return w diff --git a/lib/util.py b/lib/util.py index 0b7778f..7a9caf7 100644 --- a/lib/util.py +++ b/lib/util.py @@ -6,25 +6,25 @@ # If it occurs more than once, remove the first occurrence. # def remove(item, list): - for i in range(len(list)): - if list[i] = item: - del list[i] - break + for i in range(len(list)): + if list[i] = item: + del list[i] + break # Return a string containing a file's contents. # def readfile(fn): - return readopenfile(open(fn, 'r')) + return readopenfile(open(fn, 'r')) # Read an open file until EOF. # def readopenfile(fp): - BUFSIZE = 512*8 - data = '' - while 1: - buf = fp.read(BUFSIZE) - if not buf: break - data = data + buf - return data + BUFSIZE = 512*8 + data = '' + while 1: + buf = fp.read(BUFSIZE) + if not buf: break + data = data + buf + return data diff --git a/lib/whrandom.py b/lib/whrandom.py index ee8dc67..2ce5f8f 100644 --- a/lib/whrandom.py +++ b/lib/whrandom.py @@ -1,29 +1,29 @@ -# WICHMANN-HILL RANDOM NUMBER GENERATOR +# WICHMANN-HILL RANDOM NUMBER GENERATOR # -# Wichmann, B. A. & Hill, I. D. (1982) -# Algorithm AS 183: -# An efficient and portable pseudo-random number generator -# Applied Statistics 31 (1982) 188-190 +# Wichmann, B. A. & Hill, I. D. (1982) +# Algorithm AS 183: +# An efficient and portable pseudo-random number generator +# Applied Statistics 31 (1982) 188-190 # -# see also: -# Correction to Algorithm AS 183 -# Applied Statistics 33 (1984) 123 +# see also: +# Correction to Algorithm AS 183 +# Applied Statistics 33 (1984) 123 # -# McLeod, A. I. (1985) -# A remark on Algorithm AS 183 -# Applied Statistics 34 (1985),198-200 +# McLeod, A. I. (1985) +# A remark on Algorithm AS 183 +# Applied Statistics 34 (1985),198-200 # # -# USE: -# whrandom.random() yields double precision random numbers -# uniformly distributed between 0 and 1. +# USE: +# whrandom.random() yields double precision random numbers +# uniformly distributed between 0 and 1. # -# whrandom.seed() must be called before whrandom.random() -# to seed the generator +# whrandom.seed() must be called before whrandom.random() +# to seed the generator -# Translated by Guido van Rossum from C source provided by -# Adrian Baddeley. +# Translated by Guido van Rossum from C source provided by +# Adrian Baddeley. # The seed @@ -34,39 +34,39 @@ _seed = [0, 0, 0] # Set the seed # def seed(x, y, z): - _seed[:] = [x, y, z] + _seed[:] = [x, y, z] # Return the next random number in the range [0.0 .. 1.0) # def random(): - from math import floor # floor() function - # - [x, y, z] = _seed - x = 171 * (x % 177) - 2 * (x/177) - y = 172 * (y % 176) - 35 * (y/176) - z = 170 * (z % 178) - 63 * (z/178) - # - if x < 0: x = x + 30269 - if y < 0: y = y + 30307 - if z < 0: z = z + 30323 - # - _seed[:] = [x, y, z] - # - term = float(x)/30269.0 + float(y)/30307.0 + float(z)/30323.0 - rand = term - floor(term) - # - if rand >= 1.0: rand = 0.0 # floor() inaccuracy? - # - return rand + from math import floor # floor() function + # + [x, y, z] = _seed + x = 171 * (x % 177) - 2 * (x/177) + y = 172 * (y % 176) - 35 * (y/176) + z = 170 * (z % 178) - 63 * (z/178) + # + if x < 0: x = x + 30269 + if y < 0: y = y + 30307 + if z < 0: z = z + 30323 + # + _seed[:] = [x, y, z] + # + term = float(x)/30269.0 + float(y)/30307.0 + float(z)/30323.0 + rand = term - floor(term) + # + if rand >= 1.0: rand = 0.0 # floor() inaccuracy? + # + return rand # Initialize from the current time # def init(): - import time - t = time.time() - seed(t%256, t/256%256, t/65536%256) + import time + t = time.time() + seed(t%256, t/256%256, t/65536%256) # Make sure the generator is preset to a nonzero value diff --git a/lib/zmod.py b/lib/zmod.py index 3b38df9..d7f06db 100644 --- a/lib/zmod.py +++ b/lib/zmod.py @@ -1,7 +1,7 @@ # module 'zmod' # Compute properties of mathematical "fields" formed by taking -# Z/n (the whole numbers modulo some whole number n) and an +# Z/n (the whole numbers modulo some whole number n) and an # irreducible polynomial (i.e., a polynomial with only complex zeros), # e.g., Z/5 and X**2 + 2. # @@ -10,11 +10,11 @@ # # Note that this procedure doesn't yield a field for all combinations # of n and p: it may well be that some numbers have more than one -# inverse and others have none. This is what we check. +# inverse and others have none. This is what we check. # # Remember that a field is a ring where each element has an inverse. # A ring has commutative addition and multiplication, a zero and a one: -# 0*x = x*0 = 0, 0+x = x+0 = x, 1*x = x*1 = x. Also, the distributive +# 0*x = x*0 = 0, 0+x = x+0 = x, 1*x = x*1 = x. Also, the distributive # property holds: a*(b+c) = a*b + b*c. # (XXX I forget if this is an axiom or follows from the rules.) @@ -27,68 +27,68 @@ N = 5 P = poly.plus(poly.one(0, 2), poly.one(2, 1)) # 2 + x**2 -# Return x modulo y. Returns >= 0 even if x < 0. +# Return x modulo y. Returns >= 0 even if x < 0. def mod(x, y): - return divmod(x, y)[1] + return divmod(x, y)[1] # Normalize a polynomial modulo n and modulo p. def norm(a, n, p): - a = poly.modulo(a, p) - a = a[:] - for i in range(len(a)): a[i] = mod(a[i], n) - a = poly.normalize(a) - return a + a = poly.modulo(a, p) + a = a[:] + for i in range(len(a)): a[i] = mod(a[i], n) + a = poly.normalize(a) + return a # Make a list of all n^d elements of the proposed field. def make_all(mat): - all = [] - for row in mat: - for a in row: - all.append(a) - return all + all = [] + for row in mat: + for a in row: + all.append(a) + return all def make_elements(n, d): - if d = 0: return [poly.one(0, 0)] - sub = make_elements(n, d-1) - all = [] - for a in sub: - for i in range(n): - all.append(poly.plus(a, poly.one(d-1, i))) - return all + if d = 0: return [poly.one(0, 0)] + sub = make_elements(n, d-1) + all = [] + for a in sub: + for i in range(n): + all.append(poly.plus(a, poly.one(d-1, i))) + return all def make_inv(all, n, p): - x = poly.one(1, 1) - inv = [] - for a in all: - inv.append(norm(poly.times(a, x), n, p)) - return inv + x = poly.one(1, 1) + inv = [] + for a in all: + inv.append(norm(poly.times(a, x), n, p)) + return inv def checkfield(n, p): - all = make_elements(n, len(p)-1) - inv = make_inv(all, n, p) - all1 = all[:] - inv1 = inv[:] - all1.sort() - inv1.sort() - if all1 = inv1: print 'BINGO!' - else: - print 'Sorry:', n, p - print all - print inv + all = make_elements(n, len(p)-1) + inv = make_inv(all, n, p) + all1 = all[:] + inv1 = inv[:] + all1.sort() + inv1.sort() + if all1 = inv1: print 'BINGO!' + else: + print 'Sorry:', n, p + print all + print inv def rj(s, width): - if type(s) <> type(''): s = `s` - n = len(s) - if n >= width: return s - return ' '*(width - n) + s + if type(s) <> type(''): s = `s` + n = len(s) + if n >= width: return s + return ' '*(width - n) + s def lj(s, width): - if type(s) <> type(''): s = `s` - n = len(s) - if n >= width: return s - return s + ' '*(width - n) + if type(s) <> type(''): s = `s` + n = len(s) + if n >= width: return s + return s + ' '*(width - n) @@ -51,7 +51,7 @@ Python Library Reference Guido van Rossum CWI, dept. CST Kruislaan 413 -1098 SJ Amsterdam +1098 SJ Amsterdam The Netherlands .PP E-mail: [email protected] diff --git a/src/Grammar b/src/Grammar index 574acd6..a6169d1 100644 --- a/src/Grammar +++ b/src/Grammar @@ -1,26 +1,26 @@ # Grammar for Python, version 4 # Changes compared to version 3: -# Removed 'dir' statement. -# Function call argument is a testlist instead of exprlist. +# Removed 'dir' statement. +# Function call argument is a testlist instead of exprlist. # Changes compared to version 2: -# The syntax of Boolean operations is changed to use more -# conventional priorities: or < and < not. +# The syntax of Boolean operations is changed to use more +# conventional priorities: or < and < not. # Changes compared to version 1: -# modules and scripts are unified; -# 'quit' is gone (use ^D); -# empty_stmt is gone, replaced by explicit NEWLINE where appropriate; -# 'import' and 'def' aren't special any more; -# added 'from' NAME option on import clause, and '*' to import all; -# added class definition. +# modules and scripts are unified; +# 'quit' is gone (use ^D); +# empty_stmt is gone, replaced by explicit NEWLINE where appropriate; +# 'import' and 'def' aren't special any more; +# added 'from' NAME option on import clause, and '*' to import all; +# added class definition. # Start symbols for the grammar: -# single_input is a single interactive statement; -# file_input is a module or sequence of commands read from an input file; -# expr_input is the input for the input() function; -# eval_input is the input for the eval() function. +# single_input is a single interactive statement; +# file_input is a module or sequence of commands read from an input file; +# expr_input is the input for the input() function; +# eval_input is the input for the eval() function. # NB: compound_stmt in single_input is followed by extra NEWLINE! single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE @@ -34,7 +34,7 @@ fplist: fpdef (',' fpdef)* fpdef: NAME | '(' fplist ')' stmt: simple_stmt | compound_stmt -simple_stmt: expr_stmt | print_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt +simple_stmt: expr_stmt | print_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt expr_stmt: (exprlist '=')* exprlist NEWLINE # For assignments, additional restrictions enforced by the interpreter print_stmt: 'print' (test ',')* [test] NEWLINE diff --git a/src/Makefile b/src/Makefile index 3811b77..e07d1c8 100644 --- a/src/Makefile +++ b/src/Makefile @@ -1,17 +1,17 @@ # /*********************************************************** # Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The # Netherlands. -# -# All Rights Reserved -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose and without fee is hereby granted, +# +# All Rights Reserved +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose and without fee is hereby granted, # provided that the above copyright notice appear in all copies and that -# both that copyright notice and this permission notice appear in +# both that copyright notice and this permission notice appear in # supporting documentation, and that the names of Stichting Mathematisch # Centrum or CWI not be used in advertising or publicity pertaining to # distribution of the software without specific, written prior permission. -# +# # STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO # THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND # FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE @@ -19,7 +19,7 @@ # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -# +# # ******************************************************************/ # Makefile for Python @@ -27,17 +27,17 @@ # # If you are in a hurry, you can just edit this Makefile to choose the # correct settings for SYSV and RANLIB below, and type "make" in this -# directory. If you are using a recent version of SunOS (or Ultrix?) +# directory. If you are using a recent version of SunOS (or Ultrix?) # you don't even have to edit: the Makefile comes pre-configured for # such systems with all configurable options turned off, building the # minimal portable version of the Python interpreter. # # If have more time, read the section on configurable options below. # It may still be wise to begin building the minimal portable Python, -# to see if it works at all, and select options later. You don't have +# to see if it works at all, and select options later. You don't have # to rebuild all objects when you turn on options; all dependencies # are concentrated in the file "config.c" which is rebuilt whenever -# the Makefile changes. (Except if you turn on the GNU Readline option +# the Makefile changes. (Except if you turn on the GNU Readline option # you may have to toss out the tokenizer.o object.) @@ -45,74 +45,72 @@ # =========================================== # Uncomment the following line if you are using a System V derivative. -# This must be used, for instance, on an SGI IRIS. Don't use it for -# SunOS. (This is only needed by posixmodule.c...) +# This must be used, for instance, on an SGI IRIS. Don't use it for +# SunOS. (This is only needed by posixmodule.c...) -#SYSVDEF= -DSYSV +#SYSVDEF= -DSYSV # Choose one of the following two lines depending on whether your system # requires the use of 'ranlib' after creating a library, or not. -#RANLIB = true # For System V -RANLIB = ranlib # For BSD +#RANLIB = true # For System V +RANLIB = ranlib # For BSD # If your system doesn't have symbolic links, uncomment the following # line. -#NOSYMLINKDEF= -DNO_LSTAT +#NOSYMLINKDEF= -DNO_LSTAT # Installation Options # ==================== -# You may want to change DEFPYTHONPATH to reflect where you install the -# Python module library. The default contains "../lib" so running -# the interpreter from the source/build directory as distributed will -# find the library (admittedly a hack). +# You may want to change PYTHONPATH to reflect where you install the +# Python module library. -DEFPYTHONPATH= .:/usr/local/lib/python:/ufs/guido/lib/python:../lib +PYTHONPATH= .:/usr/local/lib/python:/ufs/guido/lib/python # For "Pure" BSD Systems # ====================== # # "Pure" BSD systems (as opposed to enhanced BSD derivatives like SunOS) -# often miss certain standard library functions. Source for -# these is provided, you just have to turn it on. This may work for +# often miss certain standard library functions. Source for +# these is provided, you just have to turn it on. This may work for # other systems as well, where these things are needed. # If your system does not have a strerror() function in the library, -# uncomment the following two lines to use one I wrote. (Actually, this +# uncomment the following two lines to use one I wrote. (Actually, this # is missing in most systems I have encountered, so it is turned on -# in the Makefile. Turn it off if your system doesn't have sys_errlist.) +# in the Makefile. Turn it off if your system doesn't have sys_errlist.) -# STRERROR_SRC= strerror.c -# STRERROR_OBJ= strerror.o +STRERROR_SRC= strerror.c +STRERROR_OBJ= strerror.o # If your BSD system does not have a fmod() function in the library, # uncomment the following two lines to use one I wrote. -#FMOD_SRC= fmod.c -#FMOD_OBJ= fmod.o +#FMOD_SRC= fmod.c +#FMOD_OBJ= fmod.o # If your BSD system does not have a strtol() function in the library, # uncomment the following two lines to use one I wrote. -#STRTOL_SRC= strtol.c -#STRTOL_OBJ= strtol.o +#STRTOL_SRC= strtol.c +#STRTOL_OBJ= strtol.o # If your BSD system does not have a getcwd() function in the library, # but it does have a getwd() function, uncomment the following two lines -# to use one I wrote. (If you don't have getwd() either, turn on the +# to use one I wrote. (If you don't have getwd() either, turn on the # NO_GETWD #define in getcwd.c.) -#GETCWD_SRC= getcwd.c -#GETCWD_OBJ= getcwd.o +#GETCWD_SRC= getcwd.c +#GETCWD_OBJ= getcwd.o # If your signal() function believes signal handlers return int, # uncomment the following line. -#SIGTYPEDEF= -DSIGTYPE=int +#SIGTYPEDEF= -DSIGTYPE=int # Further porting hints @@ -122,7 +120,7 @@ DEFPYTHONPATH= .:/usr/local/lib/python:/ufs/guido/lib/python:../lib # <strings.h>, create a file "string.h" in this directory which contains # the single line "#include <strings.h>", and add "-I." to CFLAGS. # If you don't have the functions strchr and strrchr, add definitions -# "-Dstrchr=index -Dstrrchr=rindex" to CFLAGS. (NB: CFLAGS is not +# "-Dstrchr=index -Dstrrchr=rindex" to CFLAGS. (NB: CFLAGS is not # defined in this Makefile.) @@ -130,14 +128,14 @@ DEFPYTHONPATH= .:/usr/local/lib/python:/ufs/guido/lib/python:../lib # ==================== # # Python can be configured to interface to various system libraries that -# are not available on all systems. It is also possible to configure +# are not available on all systems. It is also possible to configure # the input module to use the GNU Readline library for interactive -# input. For each configuration choice you must uncomment the relevant -# section of the Makefile below. Note: you may also have to change a +# input. For each configuration choice you must uncomment the relevant +# section of the Makefile below. Note: you may also have to change a # pathname and/or an architecture identifier that is hardcoded in the # Makefile. # -# Read the comments to determine if you can use the option. (You can +# Read the comments to determine if you can use the option. (You can # always leave all options off and build a minimal portable version of # Python.) @@ -153,7 +151,7 @@ DEFPYTHONPATH= .:/usr/local/lib/python:/ufs/guido/lib/python:../lib # # Uncomment the following line to select this option. -#BSDTIMEDEF= -DBSD_TIME +#BSDTIMEDEF= -DBSD_TIME # GNU Readline Option @@ -162,7 +160,7 @@ DEFPYTHONPATH= .:/usr/local/lib/python:/ufs/guido/lib/python:../lib # If you have the sources of the GNU Readline library you can have # full interactive command line editing and history in Python. # The GNU Readline library is distributed with the BASH shell -# (I only know of version 1.05). You must build the GNU Readline +# (I only know of version 1.05). You must build the GNU Readline # library and the alloca routine it needs in their own source # directories (which are subdirectories of the basg source directory), # and plant a pointer to the BASH source directory in this Makefile. @@ -172,13 +170,13 @@ DEFPYTHONPATH= .:/usr/local/lib/python:/ufs/guido/lib/python:../lib # You may have to fix the definition of LIBTERMCAP; leave the LIBALLOCA # definition commented if alloca() is in your C library. -#BASHDIR= ../../bash-1.05 -#LIBREADLINE= $(BASHDIR)/readline/libreadline.a -#LIBALLOCA= $(BASHDIR)/alloc-files/alloca.o -#LIBTERMCAP= -ltermcap -#RL_USE = -DUSE_READLINE -#RL_LIBS= $(LIBREADLINE) $(LIBALLOCA) $(LIBTERMCAP) -#RL_LIBDEPS= $(LIBREADLINE) $(LIBALLOCA) +#BASHDIR= ../../bash-1.05 +#LIBREADLINE= $(BASHDIR)/readline/libreadline.a +#LIBALLOCA= $(BASHDIR)/alloc-files/alloca.o +#LIBTERMCAP= -ltermcap +#RL_USE = -DUSE_READLINE +#RL_LIBS= $(LIBREADLINE) $(LIBALLOCA) $(LIBTERMCAP) +#RL_LIBDEPS= $(LIBREADLINE) $(LIBALLOCA) # STDWIN Option @@ -190,22 +188,22 @@ DEFPYTHONPATH= .:/usr/local/lib/python:/ufs/guido/lib/python:../lib # # Uncomment and edit the following block to use the STDWIN option. # - Edit the STDWINDIR defition to reflect the top of the STDWIN source -# tree. +# tree. # - Edit the ARCH definition to reflect your system's architecture -# (usually the program 'arch' or 'machine' returns this). +# (usually the program 'arch' or 'machine' returns this). # You may have to edit the LIBX11 defition to reflect the location of # the X11 runtime library if it is non-standard. -#STDWINDIR= ../../stdwin -#ARCH= sgi -#LIBSTDWIN= $(STDWINDIR)/Build/$(ARCH)/x11/lib/lib.a -#LIBX11 = -lX11 -#STDW_INCL= -I$(STDWINDIR)/H -#STDW_USE= -DUSE_STDWIN -#STDW_LIBS= $(LIBSTDWIN) $(LIBX11) -#STDW_LIBDEPS= $(LIBSTDWIN) -#STDW_SRC= stdwinmodule.c -#STDW_OBJ= stdwinmodule.o +#STDWINDIR= ../../stdwin +#ARCH= sgi +#LIBSTDWIN= $(STDWINDIR)/Build/$(ARCH)/x11/lib/lib.a +#LIBX11 = -lX11 +#STDW_INCL= -I$(STDWINDIR)/H +#STDW_USE= -DUSE_STDWIN +#STDW_LIBS= $(LIBSTDWIN) $(LIBX11) +#STDW_LIBDEPS= $(LIBSTDWIN) +#STDW_SRC= stdwinmodule.c +#STDW_OBJ= stdwinmodule.o # Amoeba Option @@ -214,31 +212,31 @@ DEFPYTHONPATH= .:/usr/local/lib/python:/ufs/guido/lib/python:../lib # If you have the Amoeba 4.0 distribution (Beta or otherwise) you can # configure Python to incorporate the built-in module 'amoeba'. # (Python can also be built for native Amoeba, but it requires more -# work and thought. Contact the author.) +# work and thought. Contact the author.) # # Uncomment and edit the following block to use the Amoeba option. # - Edit the AMOEBADIR defition to reflect the top of the Amoeba source -# tree. +# tree. # - Edit the AM_CONF definition to reflect the machine/operating system -# configuration needed by Amoeba (this is the name of a subdirectory -# of $(AMOEBADIR)/conf/unix, e.g., vax.ultrix). +# configuration needed by Amoeba (this is the name of a subdirectory +# of $(AMOEBADIR)/conf/unix, e.g., vax.ultrix). -#AMOEBADIR= /usr/amoeba -#AM_CONF= mipseb.irix -#LIBAMUNIX= $(AMOEBADIR)/conf/unix/$(AM_CONF)/lib/amunix/libamunix.a -#AM_INCL= -I$(AMOEBADIR)/src/h -#AM_USE = -DUSE_AMOEBA -#AM_LIBDEPS= $(LIBAMUNIX) -#AM_LIBS= $(LIBAMUNIX) -#AM_SRC = amoebamodule.c sc_interpr.c sc_errors.c -#AM_OBJ = amoebamodule.o sc_interpr.o sc_errors.o +#AMOEBADIR= /usr/amoeba +#AM_CONF= mipseb.irix +#LIBAMUNIX= $(AMOEBADIR)/conf/unix/$(AM_CONF)/lib/amunix/libamunix.a +#AM_INCL= -I$(AMOEBADIR)/src/h +#AM_USE = -DUSE_AMOEBA +#AM_LIBDEPS= $(LIBAMUNIX) +#AM_LIBS= $(LIBAMUNIX) +#AM_SRC = amoebamodule.c sc_interpr.c sc_errors.c +#AM_OBJ = amoebamodule.o sc_interpr.o sc_errors.o # Silicon Graphics IRIS Options # ============================= # # The following three options are only relevant if you are using a -# Silicon Graphics IRIS machine. These have been tested with IRIX 3.3.1 +# Silicon Graphics IRIS machine. These have been tested with IRIX 3.3.1 # on a 4D/25. @@ -246,28 +244,22 @@ DEFPYTHONPATH= .:/usr/local/lib/python:/ufs/guido/lib/python:../lib # ========= # # This option incorporates the built-in module 'gl', which provides a -# complete interface to the Silicon Graphics GL library. It adds +# complete interface to the Silicon Graphics GL library. It adds # about 70K to the Python text size and about 260K to the unstripped # binary size. # -# NOTE WHEN BUILDING FOR THE FIRST TIME: -# There is a circular dependency in the build process: you need to have -# a working Python interpreter before you can build a Python interpreter -# that incorporates the 'gl' module -- the source file 'glmodule.c' is -# not distributed (it's about 140K!) and a Python script is used to -# create it. Thus, you first have to build python without the the GL -# and Panel options, then edit the Makefile to turn them (or at least GL) -# on and rebuild. You may also have to set PYTHONPATH to point to -# the place where the module library is for the generation script to -# work. +# Note: the file 'glmodule.c' is created by a Python script. If you +# lost the file and have no working Python interpreter, turn off the GL +# and Panel options, rebuild the Python interpreter, use it to create +# glmodule.c, and then turn the options back on. # # Uncomment the following block to use the GL option. -#GL_USE = -DUSE_GL -#GL_LIBDEPS= -#GL_LIBS= -lgl_s -#GL_SRC = glmodule.c cgensupport.c -#GL_OBJ = glmodule.o cgensupport.o +#GL_USE = -DUSE_GL +#GL_LIBDEPS= +#GL_LIBS= -lgl_s +#GL_SRC = glmodule.c cgensupport.c +#GL_OBJ = glmodule.o cgensupport.o # Panel Option @@ -276,25 +268,23 @@ DEFPYTHONPATH= .:/usr/local/lib/python:/ufs/guido/lib/python:../lib # If you have source to the NASA Ames Panel Library, you can configure # Python to incorporate the built-in module 'pnl', which is used byu # the standard module 'panel' to provide an interface to most features -# of the Panel Library. This option requires that you also turn on the -# GL option. It adds about 100K to the Python text size and about 160K -# to the unstripped binary size. This requires Panel Library version 9.7 -# (for lower versions you may have to remove some functionality -- send -# me the patches if you bothered to do this). +# of the Panel Library. This option requires that you also turn on the +# GL option. It adds about 100K to the Python text size and about 160K +# to the unstripped binary size. # # Uncomment and edit the following block to use the Panel option. # - Edit the PANELDIR definition to point to the top-level directory -# of the Panel distribution tree. +# of the Panel distribution tree. -#PANELDIR= /usr/people/guido/src/pl -#PANELLIBDIR= $(PANELDIR)/library -#LIBPANEL= $(PANELLIBDIR)/lib/libpanel.a -#PANEL_USE= -DUSE_PANEL -#PANEL_INCL= -I$(PANELLIBDIR)/include -#PANEL_LIBDEPS= $(LIBPANEL) -#PANEL_LIBS= $(LIBPANEL) -#PANEL_SRC= panelmodule.c -#PANEL_OBJ= panelmodule.o +#PANELDIR= /usr/people/guido/src/pl +#PANELLIBDIR= $(PANELDIR)/library +#LIBPANEL= $(PANELLIBDIR)/lib/libpanel.a +#PANEL_USE= -DUSE_PANEL +#PANEL_INCL= -I$(PANELLIBDIR)/include +#PANEL_LIBDEPS= $(LIBPANEL) +#PANEL_LIBS= $(LIBPANEL) +#PANEL_SRC= panelmodule.c +#PANEL_OBJ= panelmodule.o # Audio Option @@ -304,139 +294,140 @@ DEFPYTHONPATH= .:/usr/local/lib/python:/ufs/guido/lib/python:../lib # It incorporates the built-in module 'audio'. # Warning: using the asynchronous I/O facilities of this module can # create a second 'thread', which looks in the listings of 'ps' like a -# forked child. However, it shares its address space with the parent. +# forked child. However, it shares its address space with the parent. # # Uncomment the following block to use the Audio option. -#AUDIO_USE= -DUSE_AUDIO -#AUDIO_SRC= audiomodule.c asa.c -#AUDIO_OBJ= audiomodule.o asa.o +#AUDIO_USE= -DUSE_AUDIO +#AUDIO_SRC= audiomodule.c asa.c +#AUDIO_OBJ= audiomodule.o asa.o # Major Definitions # ================= -STANDARD_OBJ= acceler.o bltinmodule.o ceval.o classobject.o \ - compile.o dictobject.o errors.o fgetsintr.o \ - fileobject.o floatobject.o $(FMOD_OBJ) frameobject.o \ - funcobject.o $(GETCWD_OBJ) \ - graminit.o grammar1.o import.o \ - intobject.o intrcheck.o listnode.o listobject.o \ - mathmodule.o methodobject.o modsupport.o \ - moduleobject.o node.o object.o parser.o \ - parsetok.o posixmodule.o regexp.o regexpmodule.o \ - strdup.o $(STRERROR_OBJ) \ - stringobject.o $(STRTOL_OBJ) structmember.o \ - sysmodule.o timemodule.o tokenizer.o traceback.o \ - tupleobject.o typeobject.o - -STANDARD_SRC= acceler.c bltinmodule.c ceval.c classobject.c \ - compile.c dictobject.c errors.c fgetsintr.c \ - fileobject.c floatobject.c $(FMOD_SRC) frameobject.c \ - funcobject.c $(GETCWD_SRC) \ - graminit.c grammar1.c import.c \ - intobject.c intrcheck.c listnode.c listobject.c \ - mathmodule.c methodobject.c modsupport.c \ - moduleobject.c node.c object.c parser.c \ - parsetok.c posixmodule.c regexp.c regexpmodule.c \ - strdup.c $(STRERROR_SRC) \ - stringobject.c $(STRTOL_SRC) structmember.c \ - sysmodule.c timemodule.c tokenizer.c traceback.c \ - tupleobject.c typeobject.c - -CONFIGDEFS= $(STDW_USE) $(AM_USE) $(AUDIO_USE) $(GL_USE) $(PANEL_USE) \ - '-DPYTHONPATH="$(DEFPYTHONPATH)"' - -CONFIGINCLS= $(STDW_INCL) - -LIBDEPS= libpython.a $(STDW_LIBDEPS) $(AM_LIBDEPS) \ - $(GL_LIBDEPS) $(PANEL_LIBSDEP) $(RL_LIBDEPS) +STANDARD_OBJ= acceler.o bltinmodule.o ceval.o classobject.o \ + compile.o dictobject.o errors.o fgetsintr.o \ + fileobject.o floatobject.o $(FMOD_OBJ) frameobject.o \ + funcobject.o $(GETCWD_OBJ) \ + graminit.o grammar1.o import.o \ + intobject.o intrcheck.o listnode.o listobject.o \ + mathmodule.o methodobject.o modsupport.o \ + moduleobject.o node.o object.o parser.o \ + parsetok.o posixmodule.o regexp.o regexpmodule.o \ + strdup.o $(STRERROR_OBJ) \ + stringobject.o $(STRTOL_OBJ) structmember.o \ + sysmodule.o timemodule.o tokenizer.o traceback.o \ + tupleobject.o typeobject.o + +STANDARD_SRC= acceler.c bltinmodule.c ceval.c classobject.c \ + compile.c dictobject.c errors.c fgetsintr.c \ + fileobject.c floatobject.c $(FMOD_SRC) frameobject.c \ + funcobject.c $(GETCWD_SRC) \ + graminit.c grammar1.c import.c \ + intobject.c intrcheck.c listnode.c listobject.c \ + mathmodule.c methodobject.c modsupport.c \ + moduleobject.c node.c object.c parser.c \ + parsetok.c posixmodule.c regexp.c regexpmodule.c \ + strdup.c $(STRERROR_SRC) \ + stringobject.c $(STRTOL_SRC) structmember.c \ + sysmodule.c timemodule.c tokenizer.c traceback.c \ + tupleobject.c typeobject.c + +CONFIGDEFS= $(STDW_USE) $(AM_USE) $(AUDIO_USE) $(GL_USE) $(PANEL_USE) \ + '-DPYTHONPATH="$(PYTHONPATH)"' + +CONFIGINCLS= $(STDW_INCL) + +LIBDEPS= libpython.a $(STDW_LIBDEPS) $(AM_LIBDEPS) \ + $(GL_LIBDEPS) $(PANEL_LIBSDEP) $(RL_LIBDEPS) # NB: the ordering of items in LIBS is significant! -LIBS= libpython.a $(STDW_LIBS) $(AM_LIBS) \ - $(PANEL_LIBS) $(GL_LIBS) $(RL_LIBS) -lm +LIBS= libpython.a $(STDW_LIBS) $(AM_LIBS) \ + $(PANEL_LIBS) $(GL_LIBS) $(RL_LIBS) -lm -LIBOBJECTS= $(STANDARD_OBJ) $(STDW_OBJ) $(AM_OBJ) $(AUDIO_OBJ) \ - $(GL_OBJ) $(PANEL_OBJ) +LIBOBJECTS= $(STANDARD_OBJ) $(STDW_OBJ) $(AM_OBJ) $(AUDIO_OBJ) \ + $(GL_OBJ) $(PANEL_OBJ) -LIBSOURCES= $(STANDARD_SRC) $(STDW_SRC) $(AM_SRC) $(AUDIO_SRC) \ - $(GL_SRC) $(PANEL_SRC) +LIBSOURCES= $(STANDARD_SRC) $(STDW_SRC) $(AM_SRC) $(AUDIO_SRC) \ + $(GL_SRC) $(PANEL_SRC) -OBJECTS= pythonmain.o config.o +OBJECTS= pythonmain.o config.o -SOURCES= $(LIBSOURCES) pythonmain.c config.c +SOURCES= $(LIBSOURCES) pythonmain.c config.c -GENOBJECTS= acceler.o fgetsintr.o grammar1.o \ - intrcheck.o listnode.o node.o parser.o \ - parsetok.o strdup.o tokenizer.o bitset.o \ - firstsets.o grammar.o metagrammar.o pgen.o \ - pgenmain.o printgrammar.o +GENOBJECTS= acceler.o fgetsintr.o grammar1.o \ + intrcheck.o listnode.o node.o parser.o \ + parsetok.o strdup.o tokenizer.o bitset.o \ + firstsets.o grammar.o metagrammar.o pgen.o \ + pgenmain.o printgrammar.o -GENSOURCES= acceler.c fgetsintr.c grammar1.c \ - intrcheck.c listnode.c node.c parser.c \ - parsetok.c strdup.c tokenizer.c bitset.c \ - firstsets.c grammar.c metagrammar.c pgen.c \ - pgenmain.c printgrammar.c +GENSOURCES= acceler.c fgetsintr.c grammar1.c \ + intrcheck.c listnode.c node.c parser.c \ + parsetok.c strdup.c tokenizer.c bitset.c \ + firstsets.c grammar.c metagrammar.c pgen.c \ + pgenmain.c printgrammar.c # Main Targets # ============ -python: libpython.a $(OBJECTS) $(LIBDEPS) Makefile - $(CC) $(CFLAGS) $(OBJECTS) $(LIBS) -o python +python: libpython.a $(OBJECTS) $(LIBDEPS) Makefile + $(CC) $(CFLAGS) $(OBJECTS) $(LIBS) -o @python + mv @python python -libpython.a: $(LIBOBJECTS) - -rm -f @lib - ar cr @lib $(LIBOBJECTS) - $(RANLIB) @lib - mv @lib libpython.a +libpython.a: $(LIBOBJECTS) + -rm -f @lib + ar cr @lib $(LIBOBJECTS) + $(RANLIB) @lib + mv @lib libpython.a -python_gen: $(GENOBJECTS) $(RL_LIBDEPS) - $(CC) $(CFLAGS) $(GENOBJECTS) $(RL_LIBS) -o python_gen +python_gen: $(GENOBJECTS) $(RL_LIBDEPS) + $(CC) $(CFLAGS) $(GENOBJECTS) $(RL_LIBS) -o python_gen # Utility Targets # =============== -# Don't take the output from lint too seriously. I have not attempted -# to make Python lint-free. But I use function prototypes. +# Don't take the output from lint too seriously. I have not attempted +# to make Python lint-free. But I use function prototypes. -LINTFLAGS= -h +LINTFLAGS= -h -LINTCPPFLAGS= $(CONFIGDEFS) $(CONFIGINCLS) $(SYSVDEF) \ - $(AM_INCL) $(PANEL_INCL) +LINTCPPFLAGS= $(CONFIGDEFS) $(CONFIGINCLS) $(SYSVDEF) \ + $(AM_INCL) $(PANEL_INCL) -LINT= lint +LINT= lint -lint:: $(SOURCES) - $(LINT) $(LINTFLAGS) $(LINTCPPFLAGS) $(SOURCES) +lint:: $(SOURCES) + $(LINT) $(LINTFLAGS) $(LINTCPPFLAGS) $(SOURCES) -lint:: $(GENSOURCES) - $(LINT) $(LINTFLAGS) $(GENSOURCES) +lint:: $(GENSOURCES) + $(LINT) $(LINTFLAGS) $(GENSOURCES) # Generating dependencies is only necessary if you intend to hack Python. # You may change $(MKDEP) to your favorite dependency generator (it should # edit the Makefile in place). -MKDEP= mkdep +MKDEP= mkdep depend:: - $(MKDEP) $(LINTCPPFLAGS) $(SOURCES) $(GENSOURCES) + $(MKDEP) $(LINTCPPFLAGS) $(SOURCES) $(GENSOURCES) # You may change $(CTAGS) to suit your taste... -CTAGS= ctags -t -w +CTAGS= ctags -t -w -HEADERS= *.h +HEADERS= *.h -tags: $(SOURCES) $(GENSOURCES) $(HEADERS) - $(CTAGS) $(SOURCES) $(GENSOURCES) $(HEADERS) +tags: $(SOURCES) $(GENSOURCES) $(HEADERS) + $(CTAGS) $(SOURCES) $(GENSOURCES) $(HEADERS) clean:: - -rm -f *.o core [,#@]* + -rm -f *.o core [,#@]* -clobber:: clean - -rm -f python python_gen libpython.a tags +clobber:: clean + -rm -f python python_gen libpython.a tags # Build Special Objects @@ -444,42 +435,42 @@ clobber:: clean # You may change $(COMPILE) to reflect the default .c.o rule... -COMPILE= $(CC) -c $(CFLAGS) +COMPILE= $(CC) -c $(CFLAGS) -amoebamodule.o: amoebamodule.c - $(COMPILE) $(AM_INCL) $*.c +amoebamodule.o: amoebamodule.c + $(COMPILE) $(AM_INCL) $*.c -config.o: config.c Makefile - $(COMPILE) $(CONFIGDEFS) $(CONFIGINCLS) $*.c +config.o: config.c Makefile + $(COMPILE) $(CONFIGDEFS) $(CONFIGINCLS) $*.c -fgetsintr.o: fgetsintr.c - $(COMPILE) $(SIGTYPEDEF) $*.c +fgetsintr.o: fgetsintr.c + $(COMPILE) $(SIGTYPEDEF) $*.c -intrcheck.o: intrcheck.c - $(COMPILE) $(SIGTYPEDEF) $*.c +intrcheck.o: intrcheck.c + $(COMPILE) $(SIGTYPEDEF) $*.c -panelmodule.o: panelmodule.c - $(COMPILE) $(PANEL_INCL) $*.c +panelmodule.o: panelmodule.c + $(COMPILE) $(PANEL_INCL) $*.c -posixmodule.o: posixmodule.c - $(COMPILE) $(SYSVDEF) $(NOSYMLINKDEF) $*.c +posixmodule.o: posixmodule.c + $(COMPILE) $(SYSVDEF) $(NOSYMLINKDEF) $*.c -sc_interpr.o: sc_interpr.c - $(COMPILE) $(AM_INCL) $*.c +sc_interpr.o: sc_interpr.c + $(COMPILE) $(AM_INCL) $*.c -sc_error.o: sc_error.c - $(COMPILE) $(AM_INCL) $*.c +sc_error.o: sc_error.c + $(COMPILE) $(AM_INCL) $*.c -stdwinmodule.o: stdwinmodule.c - $(COMPILE) $(STDW_INCL) $*.c +stdwinmodule.o: stdwinmodule.c + $(COMPILE) $(STDW_INCL) $*.c -timemodule.o: timemodule.c - $(COMPILE) $(SIGTYPEDEF) $(BSDTIMEDEF) $*.c +timemodule.o: timemodule.c + $(COMPILE) $(SIGTYPEDEF) $(BSDTIMEDEF) $*.c -tokenizer.o: tokenizer.c - $(COMPILE) $(RL_USE) $*.c +tokenizer.o: tokenizer.c + $(COMPILE) $(RL_USE) $*.c -.PRECIOUS: python libpython.a glmodule.c graminit.c graminit.h +.PRECIOUS: python libpython.a glmodule.c graminit.c graminit.h # Generated Sources @@ -489,19 +480,17 @@ tokenizer.o: tokenizer.c # The rules for doing so are given here. # Build "glmodule.c", the GL interface. -# See important note at "GL Option" above. -# You may have to set and export PYTHONPATH for this to work. -# Ignore the messages emitted by the cgen script as long as its exit -# status is zero. +# Ignore the messages emitted by the cgen script. # Also ignore the warnings emitted while compiling glmodule.c; it works. -glmodule.c: cstubs cgen - python cgen <cstubs >@glmodule.c - mv @glmodule.c glmodule.c +glmodule.c: cstubs cgen + python cgen <cstubs >@glmodule.c + mv @glmodule.c glmodule.c # The dependencies for graminit.[ch] are not turned on in the # distributed Makefile because the files themselves are distributed. # Turn them on if you want to hack the grammar. -#graminit.c graminit.h: Grammar python_gen -# python_gen Grammar +#graminit.c graminit.h: Grammar python_gen +# python_gen Grammar + diff --git a/src/PROTO.h b/src/PROTO.h index 88b94fe..7f0e6b9 100644 --- a/src/PROTO.h +++ b/src/PROTO.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -25,13 +25,13 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* The macro PROTO(x) is used to put function prototypes in the source. This is defined differently for compilers that support prototypes than -for compilers that don't. It should be used as follows: - int some_function PROTO((int arg1, char *arg2)); +for compilers that don't. It should be used as follows: + int some_function PROTO((int arg1, char *arg2)); A variant FPROTO(x) is used for cases where Standard C allows prototypes but Think C doesn't (mostly function pointers). This file also defines the macro HAVE_PROTOTYPES if and only if -the PROTO() macro expands the prototype. It is also allowed to predefine +the PROTO() macro expands the prototype. It is also allowed to predefine HAVE_PROTOTYPES to force prototypes on. */ @@ -4,7 +4,7 @@ To build the interpreter, edit the Makefile, follow the instructions there, and type "make python". To use the interpreter, you must set the environment variable PYTHONPATH -to point to the directory containing the standard modules. These are +to point to the directory containing the standard modules. These are distributed as a sister directory called 'lib' of this source directory. Try importing the module 'testall' to see if everything works. @@ -5,7 +5,7 @@ - why do reads from stdin fail when I suspend the process? - introduce macros to set/inspect errno for syscalls, to support things - like getoserr() + like getoserr() - fix interrupt handling (interruptable system calls should call - intrcheck() to clear the interrupt status) + intrcheck() to clear the interrupt status) diff --git a/src/acceler.c b/src/acceler.c index 5ed37d3..33f91b6 100644 --- a/src/acceler.c +++ b/src/acceler.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -25,13 +25,13 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* Parser accelerator module */ /* The parser as originally conceived had disappointing performance. - This module does some precomputation that speeds up the selection - of a DFA based upon a token, turning a search through an array - into a simple indexing operation. The parser now cannot work - without the accelerators installed. Note that the accelerators - are installed dynamically when the parser is initialized, they - are not part of the static data structure written on graminit.[ch] - by the parser generator. */ + This module does some precomputation that speeds up the selection + of a DFA based upon a token, turning a search through an array + into a simple indexing operation. The parser now cannot work + without the accelerators installed. Note that the accelerators + are installed dynamically when the parser is initialized, they + are not part of the static data structure written on graminit.[ch] + by the parser generator. */ #include "pgenheaders.h" #include "grammar.h" @@ -44,93 +44,93 @@ static void fixstate PROTO((grammar *, dfa *, state *)); void addaccelerators(g) - grammar *g; + grammar *g; { - dfa *d; - int i; + dfa *d; + int i; #ifdef DEBUG - printf("Adding parser accellerators ...\n"); + printf("Adding parser accellerators ...\n"); #endif - d = g->g_dfa; - for (i = g->g_ndfas; --i >= 0; d++) - fixdfa(g, d); - g->g_accel = 1; + d = g->g_dfa; + for (i = g->g_ndfas; --i >= 0; d++) + fixdfa(g, d); + g->g_accel = 1; #ifdef DEBUG - printf("Done.\n"); + printf("Done.\n"); #endif } static void fixdfa(g, d) - grammar *g; - dfa *d; + grammar *g; + dfa *d; { - state *s; - int j; - s = d->d_state; - for (j = 0; j < d->d_nstates; j++, s++) - fixstate(g, d, s); + state *s; + int j; + s = d->d_state; + for (j = 0; j < d->d_nstates; j++, s++) + fixstate(g, d, s); } static void fixstate(g, d, s) - grammar *g; - dfa *d; - state *s; + grammar *g; + dfa *d; + state *s; { - arc *a; - int k; - int *accel; - int nl = g->g_ll.ll_nlabels; - s->s_accept = 0; - accel = NEW(int, nl); - for (k = 0; k < nl; k++) - accel[k] = -1; - a = s->s_arc; - for (k = s->s_narcs; --k >= 0; a++) { - int lbl = a->a_lbl; - label *l = &g->g_ll.ll_label[lbl]; - int type = l->lb_type; - if (a->a_arrow >= (1 << 7)) { - printf("XXX too many states!\n"); - continue; - } - if (ISNONTERMINAL(type)) { - dfa *d1 = finddfa(g, type); - int ibit; - if (type - NT_OFFSET >= (1 << 7)) { - printf("XXX too high nonterminal number!\n"); - continue; - } - for (ibit = 0; ibit < g->g_ll.ll_nlabels; ibit++) { - if (testbit(d1->d_first, ibit)) { - if (accel[ibit] != -1) - printf("XXX ambiguity!\n"); - accel[ibit] = a->a_arrow | (1 << 7) | - ((type - NT_OFFSET) << 8); - } - } - } - else if (lbl == EMPTY) - s->s_accept = 1; - else if (lbl >= 0 && lbl < nl) - accel[lbl] = a->a_arrow; - } - while (nl > 0 && accel[nl-1] == -1) - nl--; - for (k = 0; k < nl && accel[k] == -1;) - k++; - if (k < nl) { - int i; - s->s_accel = NEW(int, nl-k); - if (s->s_accel == NULL) { - fprintf(stderr, "no mem to add parser accelerators\n"); - exit(1); - } - s->s_lower = k; - s->s_upper = nl; - for (i = 0; k < nl; i++, k++) - s->s_accel[i] = accel[k]; - } - DEL(accel); + arc *a; + int k; + int *accel; + int nl = g->g_ll.ll_nlabels; + s->s_accept = 0; + accel = NEW(int, nl); + for (k = 0; k < nl; k++) + accel[k] = -1; + a = s->s_arc; + for (k = s->s_narcs; --k >= 0; a++) { + int lbl = a->a_lbl; + label *l = &g->g_ll.ll_label[lbl]; + int type = l->lb_type; + if (a->a_arrow >= (1 << 7)) { + printf("XXX too many states!\n"); + continue; + } + if (ISNONTERMINAL(type)) { + dfa *d1 = finddfa(g, type); + int ibit; + if (type - NT_OFFSET >= (1 << 7)) { + printf("XXX too high nonterminal number!\n"); + continue; + } + for (ibit = 0; ibit < g->g_ll.ll_nlabels; ibit++) { + if (testbit(d1->d_first, ibit)) { + if (accel[ibit] != -1) + printf("XXX ambiguity!\n"); + accel[ibit] = a->a_arrow | (1 << 7) | + ((type - NT_OFFSET) << 8); + } + } + } + else if (lbl == EMPTY) + s->s_accept = 1; + else if (lbl >= 0 && lbl < nl) + accel[lbl] = a->a_arrow; + } + while (nl > 0 && accel[nl-1] == -1) + nl--; + for (k = 0; k < nl && accel[k] == -1;) + k++; + if (k < nl) { + int i; + s->s_accel = NEW(int, nl-k); + if (s->s_accel == NULL) { + fprintf(stderr, "no mem to add parser accelerators\n"); + exit(1); + } + s->s_lower = k; + s->s_upper = nl; + for (i = 0; k < nl; i++, k++) + s->s_accel[i] = accel[k]; + } + DEL(accel); } diff --git a/src/allobjects.h b/src/allobjects.h index fe46f54..1540adc 100644 --- a/src/allobjects.h +++ b/src/allobjects.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -26,7 +26,6 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include <stdio.h> #include <string.h> -#include <stdlib.h> #include "PROTO.h" diff --git a/src/amoebamodule.c b/src/amoebamodule.c index c9131b7..282677c 100644 --- a/src/amoebamodule.c +++ b/src/amoebamodule.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -56,7 +56,7 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. extern char *err_why(); extern char *ar_cap(); -#define STUBCODE "+stubcode" +#define STUBCODE "+stubcode" static object *AmoebaError; object *StubcodeError; @@ -70,36 +70,36 @@ extern object *convertcapv(); /* Forward */ static void ins(d, name, v) - object *d; - char *name; - object *v; + object *d; + char *name; + object *v; { - if (v == NULL || dictinsert(d, name, v) != 0) - fatal("can't initialize amoeba module"); + if (v == NULL || dictinsert(d, name, v) != 0) + fatal("can't initialize amoeba module"); } void initamoeba() { - object *m, *d, *v; - - m = initmodule("amoeba", amoeba_methods); - d = getmoduledict(m); - - /* Define capv */ - v = convertcapv(); - ins(d, "capv", v); - DECREF(v); - - /* Set timeout */ - timeout((interval)2000); - - /* Initialize amoeba.error exception */ - AmoebaError = newstringobject("amoeba.error"); - ins(d, "error", AmoebaError); - StubcodeError = newstringobject("amoeba.stubcode_error"); - ins(d, "stubcode_error", StubcodeError); - sc_dict = newdictobject(); + object *m, *d, *v; + + m = initmodule("amoeba", amoeba_methods); + d = getmoduledict(m); + + /* Define capv */ + v = convertcapv(); + ins(d, "capv", v); + DECREF(v); + + /* Set timeout */ + timeout((interval)2000); + + /* Initialize amoeba.error exception */ + AmoebaError = newstringobject("amoeba.error"); + ins(d, "error", AmoebaError); + StubcodeError = newstringobject("amoeba.stubcode_error"); + ins(d, "stubcode_error", StubcodeError); + sc_dict = newdictobject(); } @@ -107,17 +107,17 @@ initamoeba() object * amoeba_error(err) - errstat err; + errstat err; { - object *v = newtupleobject(2); - if (v != NULL) { - settupleitem(v, 0, newintobject((long)err)); - settupleitem(v, 1, newstringobject(err_why(err))); - } - err_setval(AmoebaError, v); - if (v != NULL) - DECREF(v); - return NULL; + object *v = newtupleobject(2); + if (v != NULL) { + settupleitem(v, 0, newintobject((long)err)); + settupleitem(v, 1, newstringobject(err_why(err))); + } + err_setval(AmoebaError, v); + if (v != NULL) + DECREF(v); + return NULL; } @@ -128,62 +128,62 @@ extern typeobject Captype; /* Forward */ #define is_capobject(v) ((v)->ob_type == &Captype) typedef struct { - OB_HEAD - capability ob_cap; + OB_HEAD + capability ob_cap; } capobject; object * newcapobject(cap) - capability *cap; + capability *cap; { - capobject *v = NEWOBJ(capobject, &Captype); - if (v == NULL) - return NULL; - v->ob_cap = *cap; - return (object *)v; + capobject *v = NEWOBJ(capobject, &Captype); + if (v == NULL) + return NULL; + v->ob_cap = *cap; + return (object *)v; } getcapability(v, cap) - object *v; - capability *cap; + object *v; + capability *cap; { - if (!is_capobject(v)) - return err_badarg(); - *cap = ((capobject *)v)->ob_cap; - return 0; + if (!is_capobject(v)) + return err_badarg(); + *cap = ((capobject *)v)->ob_cap; + return 0; } /* - * is_capobj exports the is_capobject macro to the stubcode modules + * is_capobj exports the is_capobject macro to the stubcode modules */ int is_capobj(v) - object *v; + object *v; { - return is_capobject(v); + return is_capobject(v); } /* Methods */ static void capprint(v, fp, flags) - capobject *v; - FILE *fp; - int flags; + capobject *v; + FILE *fp; + int flags; { - /* XXX needs lock when multi-threading */ - fputs(ar_cap(&v->ob_cap), fp); + /* XXX needs lock when multi-threading */ + fputs(ar_cap(&v->ob_cap), fp); } static object * caprepr(v) - capobject *v; + capobject *v; { - /* XXX needs lock when multi-threading */ - return newstringobject(ar_cap(&v->ob_cap)); + /* XXX needs lock when multi-threading */ + return newstringobject(ar_cap(&v->ob_cap)); } extern object *sc_interpreter(); @@ -192,216 +192,216 @@ extern struct methodlist cap_methods[]; /* Forward */ object * sc_makeself(cap, stubcode, name) - object *cap, *stubcode; - char *name; + object *cap, *stubcode; + char *name; { - object *sc_name, *sc_self; - - sc_name = newstringobject(name); - if (sc_name == NULL) - return NULL; - sc_self = newtupleobject(3); - if (sc_self == NULL) { - DECREF(sc_name); - return NULL; - } - if (settupleitem(sc_self, NAME, sc_name) != 0) { - DECREF(sc_self); - return NULL; - } - INCREF(cap); - if (settupleitem(sc_self, CAP, cap) != 0) { - DECREF(sc_self); - return NULL; - } - INCREF(stubcode); - if (settupleitem(sc_self, STUBC, stubcode) != 0) { - DECREF(sc_self); - return NULL; - } - return sc_self; + object *sc_name, *sc_self; + + sc_name = newstringobject(name); + if (sc_name == NULL) + return NULL; + sc_self = newtupleobject(3); + if (sc_self == NULL) { + DECREF(sc_name); + return NULL; + } + if (settupleitem(sc_self, NAME, sc_name) != 0) { + DECREF(sc_self); + return NULL; + } + INCREF(cap); + if (settupleitem(sc_self, CAP, cap) != 0) { + DECREF(sc_self); + return NULL; + } + INCREF(stubcode); + if (settupleitem(sc_self, STUBC, stubcode) != 0) { + DECREF(sc_self); + return NULL; + } + return sc_self; } static void swapcode(code, len) - char *code; - int len; + char *code; + int len; { - int i = sizeof(TscOperand); - TscOpcode opcode; - TscOperand operand; - - while (i < len) { - memcpy(&opcode, &code[i], sizeof(TscOpcode)); - SwapOpcode(opcode); - memcpy(&code[i], &opcode, sizeof(TscOpcode)); - i += sizeof(TscOpcode); - if (opcode & OPERAND) { - memcpy(&operand, &code[i], sizeof(TscOperand)); - SwapOperand(operand); - memcpy(&code[i], &operand, sizeof(TscOperand)); - i += sizeof(TscOperand); - } - } + int i = sizeof(TscOperand); + TscOpcode opcode; + TscOperand operand; + + while (i < len) { + memcpy(&opcode, &code[i], sizeof(TscOpcode)); + SwapOpcode(opcode); + memcpy(&code[i], &opcode, sizeof(TscOpcode)); + i += sizeof(TscOpcode); + if (opcode & OPERAND) { + memcpy(&operand, &code[i], sizeof(TscOperand)); + SwapOperand(operand); + memcpy(&code[i], &operand, sizeof(TscOperand)); + i += sizeof(TscOperand); + } + } } object * sc_findstubcode(v, name) - object *v; - char *name; + object *v; + char *name; { - int fd, fsize; - char *fname, *buffer; - struct stat statbuf; - object *sc_stubcode, *ret; - TscOperand sc_magic; - - /* - * Only look in the current directory for now. - */ - fname = malloc(strlen(name) + 4); - if (fname == NULL) { - return err_nomem(); - } - sprintf(fname, "%s.sc", name); - if ((fd = open(fname, O_RDONLY)) == -1) { - extern int errno; - - if (errno == 2) { - /* - ** errno == 2 is file not found. - */ - err_setstr(NameError, fname); - return NULL; - } - free(fname); - return err_errno(newstringobject(name)); - } - fstat(fd, &statbuf); - fsize = (int)statbuf.st_size; - buffer = malloc(fsize); - if (buffer == NULL) { - free(fname); - close(fd); - return err_nomem(); - } - if (read(fd, buffer, fsize) != fsize) { - close(fd); - free(fname); - return err_errno(newstringobject(name)); - } - close(fd); - free(fname); - memcpy(&sc_magic, buffer, sizeof(TscOperand)); - if (sc_magic != SC_MAGIC) { - SwapOperand(sc_magic); - if (sc_magic != SC_MAGIC) { - free(buffer); - return NULL; - } else { - swapcode(buffer, fsize); - } - } - sc_stubcode = newsizedstringobject( &buffer[sizeof(TscOperand)], - fsize - sizeof(TscOperand)); - free(buffer); - if (sc_stubcode == NULL) { - return NULL; - } - if (dictinsert(sc_dict, name, sc_stubcode) != 0) { - DECREF(sc_stubcode); - return NULL; - } - DECREF(sc_stubcode); /* XXXX */ - sc_stubcode = sc_makeself(v, sc_stubcode, name); - if (sc_stubcode == NULL) { - return NULL; - } - return sc_stubcode; + int fd, fsize; + char *fname, *buffer; + struct stat statbuf; + object *sc_stubcode, *ret; + TscOperand sc_magic; + + /* + * Only look in the current directory for now. + */ + fname = malloc(strlen(name) + 4); + if (fname == NULL) { + return err_nomem(); + } + sprintf(fname, "%s.sc", name); + if ((fd = open(fname, O_RDONLY)) == -1) { + extern int errno; + + if (errno == 2) { + /* + ** errno == 2 is file not found. + */ + err_setstr(NameError, fname); + return NULL; + } + free(fname); + return err_errno(newstringobject(name)); + } + fstat(fd, &statbuf); + fsize = (int)statbuf.st_size; + buffer = malloc(fsize); + if (buffer == NULL) { + free(fname); + close(fd); + return err_nomem(); + } + if (read(fd, buffer, fsize) != fsize) { + close(fd); + free(fname); + return err_errno(newstringobject(name)); + } + close(fd); + free(fname); + memcpy(&sc_magic, buffer, sizeof(TscOperand)); + if (sc_magic != SC_MAGIC) { + SwapOperand(sc_magic); + if (sc_magic != SC_MAGIC) { + free(buffer); + return NULL; + } else { + swapcode(buffer, fsize); + } + } + sc_stubcode = newsizedstringobject( &buffer[sizeof(TscOperand)], + fsize - sizeof(TscOperand)); + free(buffer); + if (sc_stubcode == NULL) { + return NULL; + } + if (dictinsert(sc_dict, name, sc_stubcode) != 0) { + DECREF(sc_stubcode); + return NULL; + } + DECREF(sc_stubcode); /* XXXX */ + sc_stubcode = sc_makeself(v, sc_stubcode, name); + if (sc_stubcode == NULL) { + return NULL; + } + return sc_stubcode; } object * capgetattr(v, name) - capobject *v; - char *name; + capobject *v; + char *name; { - object *sc_method, *sc_stubcodemethod; - - if (sc_dict == NULL) { - /* - ** For some reason the dictionary has not been - ** initialized. Try to find one of the built in - ** methods. - */ - return findmethod(cap_methods, (object *)v, name); - } - sc_stubcodemethod = dictlookup(sc_dict, name); - if (sc_stubcodemethod != NULL) { - /* - ** There is a stubcode method in the dictionary. - ** Execute the stubcode interpreter with the right - ** arguments. - */ - object *self, *ret; - - self = sc_makeself((object *)v, sc_stubcodemethod, name); - if (self == NULL) { - return NULL; - } - ret = findmethod(cap_methods, self, STUBCODE); - DECREF(self); - return ret; - } - err_clear(); - sc_method = findmethod(cap_methods, (object *)v, name); - if (sc_method == NULL) { - /* - ** The method is not built in and not in the - ** dictionary. Try to find it as a stubcode file. - */ - object *self, *ret; - - err_clear(); - self = sc_findstubcode((object *)v, name); - if (self == NULL) { - return NULL; - } - ret = findmethod(cap_methods, self, STUBCODE); - DECREF(self); - return ret; - } - return sc_method; + object *sc_method, *sc_stubcodemethod; + + if (sc_dict == NULL) { + /* + ** For some reason the dictionary has not been + ** initialized. Try to find one of the built in + ** methods. + */ + return findmethod(cap_methods, (object *)v, name); + } + sc_stubcodemethod = dictlookup(sc_dict, name); + if (sc_stubcodemethod != NULL) { + /* + ** There is a stubcode method in the dictionary. + ** Execute the stubcode interpreter with the right + ** arguments. + */ + object *self, *ret; + + self = sc_makeself((object *)v, sc_stubcodemethod, name); + if (self == NULL) { + return NULL; + } + ret = findmethod(cap_methods, self, STUBCODE); + DECREF(self); + return ret; + } + err_clear(); + sc_method = findmethod(cap_methods, (object *)v, name); + if (sc_method == NULL) { + /* + ** The method is not built in and not in the + ** dictionary. Try to find it as a stubcode file. + */ + object *self, *ret; + + err_clear(); + self = sc_findstubcode((object *)v, name); + if (self == NULL) { + return NULL; + } + ret = findmethod(cap_methods, self, STUBCODE); + DECREF(self); + return ret; + } + return sc_method; } int capcompare(v, w) - capobject *v, *w; + capobject *v, *w; { - int cmp = bcmp((char *)&v->ob_cap.cap_port, - (char *)&w->ob_cap, PORTSIZE); - if (cmp != 0) - return cmp; - return prv_number(&v->ob_cap.cap_priv) - - prv_number(&w->ob_cap.cap_priv); + int cmp = bcmp((char *)&v->ob_cap.cap_port, + (char *)&w->ob_cap, PORTSIZE); + if (cmp != 0) + return cmp; + return prv_number(&v->ob_cap.cap_priv) - + prv_number(&w->ob_cap.cap_priv); } static typeobject Captype = { - OB_HEAD_INIT(&Typetype) - 0, - "capability", - sizeof(capobject), - 0, - free, /*tp_dealloc*/ - capprint, /*tp_print*/ - capgetattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - capcompare, /*tp_comp + OB_HEAD_INIT(&Typetype) + 0, + "capability", + sizeof(capobject), + 0, + free, /*tp_dealloc*/ + capprint, /*tp_print*/ + capgetattr, /*tp_getattr*/ + 0, /*tp_setattr*/ + capcompare, /*tp_comp are*/ - caprepr, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ + caprepr, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ }; @@ -412,22 +412,22 @@ extern struct caplist *capv; static object * convertcapv() { - object *d; - struct caplist *c; - d = newdictobject(); - if (d == NULL) - return NULL; - if (capv == NULL) - return d; - for (c = capv; c->cl_name != NULL; c++) { - object *v = newcapobject(c->cl_cap); - if (v == NULL || dictinsert(d, c->cl_name, v) != 0) { - DECREF(d); - return NULL; - } - DECREF(v); - } - return d; + object *d; + struct caplist *c; + d = newdictobject(); + if (d == NULL) + return NULL; + if (capv == NULL) + return d; + for (c = capv; c->cl_name != NULL; c++) { + object *v = newcapobject(c->cl_cap); + if (v == NULL || dictinsert(d, c->cl_name, v) != 0) { + DECREF(d); + return NULL; + } + DECREF(v); + } + return d; } @@ -435,25 +435,25 @@ convertcapv() static int getcaparg(v, a) - object *v; - capability *a; + object *v; + capability *a; { - if (v == NULL || !is_capobject(v)) - return err_badarg(); - *a = ((capobject *)v) -> ob_cap; - return 1; + if (v == NULL || !is_capobject(v)) + return err_badarg(); + *a = ((capobject *)v) -> ob_cap; + return 1; } static int getstrcapargs(v, a, b) - object *v; - object **a; - capability *b; + object *v; + object **a; + capability *b; { - if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) - return err_badarg(); - return getstrarg(gettupleitem(v, 0), a) && - getcaparg(gettupleitem(v, 1), b); + if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) + return err_badarg(); + return getstrarg(gettupleitem(v, 0), a) && + getcaparg(gettupleitem(v, 1), b); } @@ -461,314 +461,314 @@ getstrcapargs(v, a, b) static object * amoeba_name_lookup(self, args) - object *self; - object *args; + object *self; + object *args; { - object *name; - capability cap; - errstat err; - if (!getstrarg(args, &name)) - return NULL; - err = name_lookup(getstringvalue(name), &cap); - if (err != STD_OK) - return amoeba_error(err); - return newcapobject(&cap); + object *name; + capability cap; + errstat err; + if (!getstrarg(args, &name)) + return NULL; + err = name_lookup(getstringvalue(name), &cap); + if (err != STD_OK) + return amoeba_error(err); + return newcapobject(&cap); } static object * amoeba_name_append(self, args) - object *self; - object *args; + object *self; + object *args; { - object *name; - capability cap; - errstat err; - if (!getstrcapargs(args, &name, &cap)) - return NULL; - err = name_append(getstringvalue(name), &cap); - if (err != STD_OK) - return amoeba_error(err); - INCREF(None); - return None; + object *name; + capability cap; + errstat err; + if (!getstrcapargs(args, &name, &cap)) + return NULL; + err = name_append(getstringvalue(name), &cap); + if (err != STD_OK) + return amoeba_error(err); + INCREF(None); + return None; } static object * amoeba_name_replace(self, args) - object *self; - object *args; + object *self; + object *args; { - object *name; - capability cap; - errstat err; - if (!getstrcapargs(args, &name, &cap)) - return NULL; - err = name_replace(getstringvalue(name), &cap); - if (err != STD_OK) - return amoeba_error(err); - INCREF(None); - return None; + object *name; + capability cap; + errstat err; + if (!getstrcapargs(args, &name, &cap)) + return NULL; + err = name_replace(getstringvalue(name), &cap); + if (err != STD_OK) + return amoeba_error(err); + INCREF(None); + return None; } static object * amoeba_name_delete(self, args) - object *self; - object *args; + object *self; + object *args; { - object *name; - errstat err; - if (!getstrarg(args, &name)) - return NULL; - err = name_delete(getstringvalue(name)); - if (err != STD_OK) - return amoeba_error(err); - INCREF(None); - return None; + object *name; + errstat err; + if (!getstrarg(args, &name)) + return NULL; + err = name_delete(getstringvalue(name)); + if (err != STD_OK) + return amoeba_error(err); + INCREF(None); + return None; } static object * amoeba_timeout(self, args) - object *self; - object *args; + object *self; + object *args; { - int i; - object *v; - interval tout; - if (!getintarg(args, &i)) - return NULL; - tout = timeout((interval)i); - v = newintobject((long)tout); - if (v == NULL) - timeout(tout); - return v; + int i; + object *v; + interval tout; + if (!getintarg(args, &i)) + return NULL; + tout = timeout((interval)i); + v = newintobject((long)tout); + if (v == NULL) + timeout(tout); + return v; } static struct methodlist amoeba_methods[] = { - {"name_append", amoeba_name_append}, - {"name_delete", amoeba_name_delete}, - {"name_lookup", amoeba_name_lookup}, - {"name_replace", amoeba_name_replace}, - {"timeout", amoeba_timeout}, - {NULL, NULL} /* Sentinel */ + {"name_append", amoeba_name_append}, + {"name_delete", amoeba_name_delete}, + {"name_lookup", amoeba_name_lookup}, + {"name_replace", amoeba_name_replace}, + {"timeout", amoeba_timeout}, + {NULL, NULL} /* Sentinel */ }; /* Capability methods */ static object * cap_b_size(self, args) - capobject *self; - object *args; + capobject *self; + object *args; { - errstat err; - b_fsize size; - if (!getnoarg(args)) - return NULL; - err = b_size(&self->ob_cap, &size); - if (err != STD_OK) - return amoeba_error(err); - return newintobject((long)size); + errstat err; + b_fsize size; + if (!getnoarg(args)) + return NULL; + err = b_size(&self->ob_cap, &size); + if (err != STD_OK) + return amoeba_error(err); + return newintobject((long)size); } static object * cap_b_read(self, args) - capobject *self; - object *args; + capobject *self; + object *args; { - errstat err; - char *buf; - object *v; - long offset, size; - b_fsize nread; - if (!getlonglongargs(args, &offset, &size)) - return NULL; - buf = malloc((unsigned int)size); - if (buf == NULL) { - return err_nomem(); - } - err = b_read(&self->ob_cap, (b_fsize)offset, buf, (b_fsize)size, - &nread); - if (err != STD_OK) { - free(buf); - return amoeba_error(err); - } - v = newsizedstringobject(buf, (int)nread); - free(buf); - return v; + errstat err; + char *buf; + object *v; + long offset, size; + b_fsize nread; + if (!getlonglongargs(args, &offset, &size)) + return NULL; + buf = malloc((unsigned int)size); + if (buf == NULL) { + return err_nomem(); + } + err = b_read(&self->ob_cap, (b_fsize)offset, buf, (b_fsize)size, + &nread); + if (err != STD_OK) { + free(buf); + return amoeba_error(err); + } + v = newsizedstringobject(buf, (int)nread); + free(buf); + return v; } static object * cap_dir_lookup(self, args) - capobject *self; - object *args; + capobject *self; + object *args; { - object *name; - capability cap; - errstat err; - if (!getstrarg(args, &name)) - return NULL; - err = dir_lookup(&self->ob_cap, getstringvalue(name), &cap); - if (err != STD_OK) - return amoeba_error(err); - return newcapobject(&cap); + object *name; + capability cap; + errstat err; + if (!getstrarg(args, &name)) + return NULL; + err = dir_lookup(&self->ob_cap, getstringvalue(name), &cap); + if (err != STD_OK) + return amoeba_error(err); + return newcapobject(&cap); } static object * cap_dir_append(self, args) - capobject *self; - object *args; + capobject *self; + object *args; { - object *name; - capability cap; - errstat err; - if (!getstrcapargs(args, &name, &cap)) - return NULL; - err = dir_append(&self->ob_cap, getstringvalue(name), &cap); - if (err != STD_OK) - return amoeba_error(err); - INCREF(None); - return None; + object *name; + capability cap; + errstat err; + if (!getstrcapargs(args, &name, &cap)) + return NULL; + err = dir_append(&self->ob_cap, getstringvalue(name), &cap); + if (err != STD_OK) + return amoeba_error(err); + INCREF(None); + return None; } static object * cap_dir_delete(self, args) - capobject *self; - object *args; + capobject *self; + object *args; { - object *name; - errstat err; - if (!getstrarg(args, &name)) - return NULL; - err = dir_delete(&self->ob_cap, getstringvalue(name)); - if (err != STD_OK) - return amoeba_error(err); - INCREF(None); - return None; + object *name; + errstat err; + if (!getstrarg(args, &name)) + return NULL; + err = dir_delete(&self->ob_cap, getstringvalue(name)); + if (err != STD_OK) + return amoeba_error(err); + INCREF(None); + return None; } static object * cap_dir_replace(self, args) - capobject *self; - object *args; + capobject *self; + object *args; { - object *name; - capability cap; - errstat err; - if (!getstrcapargs(args, &name, &cap)) - return NULL; - err = dir_replace(&self->ob_cap, getstringvalue(name), &cap); - if (err != STD_OK) - return amoeba_error(err); - INCREF(None); - return None; + object *name; + capability cap; + errstat err; + if (!getstrcapargs(args, &name, &cap)) + return NULL; + err = dir_replace(&self->ob_cap, getstringvalue(name), &cap); + if (err != STD_OK) + return amoeba_error(err); + INCREF(None); + return None; } static object * cap_dir_list(self, args) - capobject *self; - object *args; + capobject *self; + object *args; { - errstat err; - struct dir_open *dd; - object *d; - char *name; - if (!getnoarg(args)) - return NULL; - if ((dd = dir_open(&self->ob_cap)) == NULL) - return amoeba_error(STD_COMBAD); - if ((d = newlistobject(0)) == NULL) { - dir_close(dd); - return NULL; - } - while ((name = dir_next(dd)) != NULL) { - object *v; - v = newstringobject(name); - if (v == NULL) { - DECREF(d); - d = NULL; - break; - } - if (addlistitem(d, v) != 0) { - DECREF(v); - DECREF(d); - d = NULL; - break; - } - DECREF(v); - } - dir_close(dd); - return d; + errstat err; + struct dir_open *dd; + object *d; + char *name; + if (!getnoarg(args)) + return NULL; + if ((dd = dir_open(&self->ob_cap)) == NULL) + return amoeba_error(STD_COMBAD); + if ((d = newlistobject(0)) == NULL) { + dir_close(dd); + return NULL; + } + while ((name = dir_next(dd)) != NULL) { + object *v; + v = newstringobject(name); + if (v == NULL) { + DECREF(d); + d = NULL; + break; + } + if (addlistitem(d, v) != 0) { + DECREF(v); + DECREF(d); + d = NULL; + break; + } + DECREF(v); + } + dir_close(dd); + return d; } object * cap_std_info(self, args) - capobject *self; - object *args; + capobject *self; + object *args; { - char buf[256]; - errstat err; - int n; - if (!getnoarg(args)) - return NULL; - err = std_info(&self->ob_cap, buf, sizeof buf, &n); - if (err != STD_OK) - return amoeba_error(err); - return newsizedstringobject(buf, n); + char buf[256]; + errstat err; + int n; + if (!getnoarg(args)) + return NULL; + err = std_info(&self->ob_cap, buf, sizeof buf, &n); + if (err != STD_OK) + return amoeba_error(err); + return newsizedstringobject(buf, n); } object * cap_tod_gettime(self, args) - capobject *self; - object *args; + capobject *self; + object *args; { - header h; - errstat err; - bufsize n; - long sec; - int msec, tz, dst; - if (!getnoarg(args)) - return NULL; - h.h_port = self->ob_cap.cap_port; - h.h_priv = self->ob_cap.cap_priv; - h.h_command = TOD_GETTIME; - n = trans(&h, NILBUF, 0, &h, NILBUF, 0); - if (ERR_STATUS(n)) - return amoeba_error(ERR_CONVERT(n)); - tod_decode(&h, &sec, &msec, &tz, &dst); - return newintobject(sec); + header h; + errstat err; + bufsize n; + long sec; + int msec, tz, dst; + if (!getnoarg(args)) + return NULL; + h.h_port = self->ob_cap.cap_port; + h.h_priv = self->ob_cap.cap_priv; + h.h_command = TOD_GETTIME; + n = trans(&h, NILBUF, 0, &h, NILBUF, 0); + if (ERR_STATUS(n)) + return amoeba_error(ERR_CONVERT(n)); + tod_decode(&h, &sec, &msec, &tz, &dst); + return newintobject(sec); } object * cap_tod_settime(self, args) - capobject *self; - object *args; + capobject *self; + object *args; { - header h; - errstat err; - bufsize n; - long sec; - if (!getlongarg(args, &sec)) - return NULL; - h.h_port = self->ob_cap.cap_port; - h.h_priv = self->ob_cap.cap_priv; - h.h_command = TOD_SETTIME; - tod_encode(&h, sec, 0, 0, 0); - n = trans(&h, NILBUF, 0, &h, NILBUF, 0); - if (ERR_STATUS(n)) - return amoeba_error(ERR_CONVERT(n)); - INCREF(None); - return None; + header h; + errstat err; + bufsize n; + long sec; + if (!getlongarg(args, &sec)) + return NULL; + h.h_port = self->ob_cap.cap_port; + h.h_priv = self->ob_cap.cap_priv; + h.h_command = TOD_SETTIME; + tod_encode(&h, sec, 0, 0, 0); + n = trans(&h, NILBUF, 0, &h, NILBUF, 0); + if (ERR_STATUS(n)) + return amoeba_error(ERR_CONVERT(n)); + INCREF(None); + return None; } static struct methodlist cap_methods[] = { - { STUBCODE, sc_interpreter}, - {"b_read", cap_b_read}, - {"b_size", cap_b_size}, - {"dir_append", cap_dir_append}, - {"dir_delete", cap_dir_delete}, - {"dir_list", cap_dir_list}, - {"dir_lookup", cap_dir_lookup}, - {"dir_replace", cap_dir_replace}, - {"std_info", cap_std_info}, - {"tod_gettime", cap_tod_gettime}, - {"tod_settime", cap_tod_settime}, - {NULL, NULL} /* Sentinel */ + { STUBCODE, sc_interpreter}, + {"b_read", cap_b_read}, + {"b_size", cap_b_size}, + {"dir_append", cap_dir_append}, + {"dir_delete", cap_dir_delete}, + {"dir_list", cap_dir_list}, + {"dir_lookup", cap_dir_lookup}, + {"dir_replace", cap_dir_replace}, + {"std_info", cap_std_info}, + {"tod_gettime", cap_tod_gettime}, + {"tod_settime", cap_tod_settime}, + {NULL, NULL} /* Sentinel */ }; @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -23,86 +23,86 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ /* Asynchronous audio module for Silicon Graphics 4D/20 under IRIX 3.3 - Copyright 1990 Stichting Mathematisch Centrum, Amsterdam - Author: Guido van Rossum, <[email protected]> - Last modified: [email protected], Oct 14, 1990 - - Callers should #include "asa.h". - - This code is strongly IRIX 3.3 dependent. (Or are sproc() and - friends standard SYSV now?) - - Caution: if you put printf's in the slave for debugging, use "-lmpc" - to get the semaphore version of stdio! - - - This file contains two library layers and a test program: - - - The lower layer implements a simple asynchronous execution facility, - built directly on the system calls sproc() and [un]blockproc(). - - A slave thread sits in an infinite loop waiting for work assigned to - it by the master thread. Work is represented by a function pointer - and an argument of type void*. The function returns a void* pointer - which is transferred back to the master when it submits the next bit - of work. Submitting a NULL function pointer can be used by the - master to wait for completion of the previous work. This lower - layer could be generally useful, but is currently implemented by - static functions, for exclusive by the asynchronous audio layer. - - - The higher layer implements an asynchronous interface to the - /dev/audio device on the Silicon Graphics 4D/20. It defines the - following functions: - - int asa_init() - Required initialization function. The other functions will call - abort() when they are called before asa_init(). It creates the - slave process and returns a file descriptor for the audio - device which can be used to set the sampling rate and output - gain, etc. It prints a message to stderr and returns -1 if the - initialization failed. Calling this function more than onece is - harmless. - - void asa_start_read(char *buf, int len) - Starts an asynchronous read call on the audio device. This - waits for completion of the previous request, if any. - - void asa_start_write(char *buf, int len) - Starts an asynchronous write call on the audio device. This - waits for completion of the previous request, if any. - - int asa_poll() - Polls whether the last asynchronous read or write request is - finished. Returns -1 if no request was queued, 0 if the request - is not yet finished, and 1 if it is finished. - - int asa_wait() - Waits for completion if the last asynchronous read or write - request. It returns the result of the read or write request, - and sets the error code to the error code set by the request if - the result is -1. If no request was queued, this also returns - -1 but leaves the error code unchanged. Note: to get the error - code, don't inspect the global variable errno but call the - function oserror(). - - int asa_cancel() - Cancels the last asynchronous read or write request (by sending - the slave thread a signal for which it has a handler) then - returns its result and error code as asa_wait(). - - void asa_done() - Kills the slave process and closes the audio device. After - this, if further use of the module is required, asa_init() - should be called again. Calling this function when asa_init() - has not been called is harmless. - - - Finally, this file contains a simple test program that is compiled if - MAIN is defined (e.g., compile with cc -DMAIN). It makes a recording - and plays it back. The user must indicate begin and end of recording - and play-back by pressing the Return key. + Copyright 1990 Stichting Mathematisch Centrum, Amsterdam + Author: Guido van Rossum, <[email protected]> + Last modified: [email protected], Oct 14, 1990 + + Callers should #include "asa.h". + + This code is strongly IRIX 3.3 dependent. (Or are sproc() and + friends standard SYSV now?) + + Caution: if you put printf's in the slave for debugging, use "-lmpc" + to get the semaphore version of stdio! + + + This file contains two library layers and a test program: + + + The lower layer implements a simple asynchronous execution facility, + built directly on the system calls sproc() and [un]blockproc(). + + A slave thread sits in an infinite loop waiting for work assigned to + it by the master thread. Work is represented by a function pointer + and an argument of type void*. The function returns a void* pointer + which is transferred back to the master when it submits the next bit + of work. Submitting a NULL function pointer can be used by the + master to wait for completion of the previous work. This lower + layer could be generally useful, but is currently implemented by + static functions, for exclusive by the asynchronous audio layer. + + + The higher layer implements an asynchronous interface to the + /dev/audio device on the Silicon Graphics 4D/20. It defines the + following functions: + + int asa_init() + Required initialization function. The other functions will call + abort() when they are called before asa_init(). It creates the + slave process and returns a file descriptor for the audio + device which can be used to set the sampling rate and output + gain, etc. It prints a message to stderr and returns -1 if the + initialization failed. Calling this function more than onece is + harmless. + + void asa_start_read(char *buf, int len) + Starts an asynchronous read call on the audio device. This + waits for completion of the previous request, if any. + + void asa_start_write(char *buf, int len) + Starts an asynchronous write call on the audio device. This + waits for completion of the previous request, if any. + + int asa_poll() + Polls whether the last asynchronous read or write request is + finished. Returns -1 if no request was queued, 0 if the request + is not yet finished, and 1 if it is finished. + + int asa_wait() + Waits for completion if the last asynchronous read or write + request. It returns the result of the read or write request, + and sets the error code to the error code set by the request if + the result is -1. If no request was queued, this also returns + -1 but leaves the error code unchanged. Note: to get the error + code, don't inspect the global variable errno but call the + function oserror(). + + int asa_cancel() + Cancels the last asynchronous read or write request (by sending + the slave thread a signal for which it has a handler) then + returns its result and error code as asa_wait(). + + void asa_done() + Kills the slave process and closes the audio device. After + this, if further use of the module is required, asa_init() + should be called again. Calling this function when asa_init() + has not been called is harmless. + + + Finally, this file contains a simple test program that is compiled if + MAIN is defined (e.g., compile with cc -DMAIN). It makes a recording + and plays it back. The user must indicate begin and end of recording + and play-back by pressing the Return key. */ @@ -135,20 +135,20 @@ static void *work_result; /*ARGSUSED*/ static void handler(sig) - int sig; + int sig; { - /* Reinstate the handler (non-BSD signal semantics) */ - signal(sig, handler); + /* Reinstate the handler (non-BSD signal semantics) */ + signal(sig, handler); } /* Subroutine to fiddle signals */ static void dosig(sig) - int sig; + int sig; { - if (signal(sig, SIG_IGN) != SIG_IGN) - signal(sig, SIG_DFL); + if (signal(sig, SIG_IGN) != SIG_IGN) + signal(sig, SIG_DFL); } /* Slave control flow */ @@ -156,148 +156,148 @@ dosig(sig) /*ARGSUSED*/ static void slave(arg) - void *arg; + void *arg; { - void * (*func)(); - void *arg; - void *result; - - /* Reset signal handlers that interactive programs often catch. - The assumption is that if the master has a handler for these - signals, it will be a cleanup function. The slave must die - from these. */ - dosig(SIGHUP); - dosig(SIGQUIT); - dosig(SIGTERM); - dosig(SIGPIPE); - - /* Ignore SIGINT if caught or ignored */ - if (signal(SIGINT, SIG_IGN) == SIG_DFL) - signal(SIGINT, SIG_DFL); - - /* Let the handler install itself */ - handler(MYSIG); - - /* Set slave_pid. This is also done in the master thread, but - there is a race condition whereby the slave begins execution - before the master has assigned the result of sproc() to - slave_pid. So we set it here as well -- since this sets the - same value it should be OK. */ - slave_pid = getpid(); - - /* Set the dummy result returned by the first rendezvous */ - result = NULL; - - /* Loop forever, waiting for and executing work */ - for (;;) { - /* First rendezvous: store previous result */ - if (blockproc(slave_pid) < 0) - perror("slave: [result] blockproc(slave_pid)"); - work_result = result; - if (unblockproc(master_pid) < 0) - perror("slave: [result] unblockproc(master_pid)"); - - /* Second rendezvous: fetch work */ - if (blockproc(slave_pid) < 0) - perror("slave: [func,arg] blockproc(slave_pid)"); - func = work_func; - arg = work_arg; - if (unblockproc(master_pid) < 0) - perror("slave: [func,arg] unblockproc(master_pid)"); - - /* Execute work, computing new result */ - if (func == NULL) { - result = arg; - } - else { - result = (*func)(arg); - } - } + void * (*func)(); + void *arg; + void *result; + + /* Reset signal handlers that interactive programs often catch. + The assumption is that if the master has a handler for these + signals, it will be a cleanup function. The slave must die + from these. */ + dosig(SIGHUP); + dosig(SIGQUIT); + dosig(SIGTERM); + dosig(SIGPIPE); + + /* Ignore SIGINT if caught or ignored */ + if (signal(SIGINT, SIG_IGN) == SIG_DFL) + signal(SIGINT, SIG_DFL); + + /* Let the handler install itself */ + handler(MYSIG); + + /* Set slave_pid. This is also done in the master thread, but + there is a race condition whereby the slave begins execution + before the master has assigned the result of sproc() to + slave_pid. So we set it here as well -- since this sets the + same value it should be OK. */ + slave_pid = getpid(); + + /* Set the dummy result returned by the first rendezvous */ + result = NULL; + + /* Loop forever, waiting for and executing work */ + for (;;) { + /* First rendezvous: store previous result */ + if (blockproc(slave_pid) < 0) + perror("slave: [result] blockproc(slave_pid)"); + work_result = result; + if (unblockproc(master_pid) < 0) + perror("slave: [result] unblockproc(master_pid)"); + + /* Second rendezvous: fetch work */ + if (blockproc(slave_pid) < 0) + perror("slave: [func,arg] blockproc(slave_pid)"); + func = work_func; + arg = work_arg; + if (unblockproc(master_pid) < 0) + perror("slave: [func,arg] unblockproc(master_pid)"); + + /* Execute work, computing new result */ + if (func == NULL) { + result = arg; + } + else { + result = (*func)(arg); + } + } } static int slave_init() { - if (slave_pid > 0) - return slave_pid; - master_pid = getpid(); - - /* Reset the queue, in case this is a re-init after asa_done() */ - work_result = NULL; - work_func = NULL; - work_arg = NULL; - - /* Create the slave process, sharing all segments and properties */ - slave_pid = sproc(slave, PR_SALL, (char *)NULL); - if (slave_pid < 0) - perror("slave_init: sproc(slave, PR_SALL, NULL)"); - - /* Set up initial conditions---tricky! - Both the master and the slave start with one credit, since - both the result slot and the work/func slots are initially - free. - Note that we use setblockproccnt() for the master so a - possible indeterminate semaphore value caused by a previous - asa_done() at an unfortunate moment doesn't harm us. - */ - setblockproccnt(master_pid, 1); - unblockproc(slave_pid); - - return slave_pid; + if (slave_pid > 0) + return slave_pid; + master_pid = getpid(); + + /* Reset the queue, in case this is a re-init after asa_done() */ + work_result = NULL; + work_func = NULL; + work_arg = NULL; + + /* Create the slave process, sharing all segments and properties */ + slave_pid = sproc(slave, PR_SALL, (char *)NULL); + if (slave_pid < 0) + perror("slave_init: sproc(slave, PR_SALL, NULL)"); + + /* Set up initial conditions---tricky! + Both the master and the slave start with one credit, since + both the result slot and the work/func slots are initially + free. + Note that we use setblockproccnt() for the master so a + possible indeterminate semaphore value caused by a previous + asa_done() at an unfortunate moment doesn't harm us. + */ + setblockproccnt(master_pid, 1); + unblockproc(slave_pid); + + return slave_pid; } static void slave_done() { - if (slave_pid > 0) { - if (kill(slave_pid, SIGKILL) < 0) - perror("slave_done: kill(slave_pid, SIGKILL)"); - } - slave_pid = -1; + if (slave_pid > 0) { + if (kill(slave_pid, SIGKILL) < 0) + perror("slave_done: kill(slave_pid, SIGKILL)"); + } + slave_pid = -1; } /* Queue new work and return result of previous work */ static void * rendezvous(func, arg) - void * (*func)(); - void *arg; + void * (*func)(); + void *arg; { - void *result; - - if (slave_pid <= 0) - abort(); /* Illegal call: not initialized properly */ - - /* First rendezvous: store new work */ - if (blockproc(master_pid) < 0) - perror("rendezvous: [func,arg] blockproc(master_pid)"); - work_func = func; - work_arg = arg; - if (unblockproc(slave_pid) < 0) - perror("rendezvous: [func,arg] unblockproc(slave_pid)"); - - /* Second rendezvous: fetch previous result */ - if (blockproc(master_pid) < 0) - perror("rendezvous: [result] blockproc(master_pid)"); - result = work_result; - if (unblockproc(slave_pid) < 0) - perror("rendezvous: [result] unblockproc(slave_pid)"); - - return result; + void *result; + + if (slave_pid <= 0) + abort(); /* Illegal call: not initialized properly */ + + /* First rendezvous: store new work */ + if (blockproc(master_pid) < 0) + perror("rendezvous: [func,arg] blockproc(master_pid)"); + work_func = func; + work_arg = arg; + if (unblockproc(slave_pid) < 0) + perror("rendezvous: [func,arg] unblockproc(slave_pid)"); + + /* Second rendezvous: fetch previous result */ + if (blockproc(master_pid) < 0) + perror("rendezvous: [result] blockproc(master_pid)"); + result = work_result; + if (unblockproc(slave_pid) < 0) + perror("rendezvous: [result] unblockproc(slave_pid)"); + + return result; } /* Asynchronous audio interface (higher layer) */ -int audio_fd = -1; /* File descriptor -- not initialized yet */ +int audio_fd = -1; /* File descriptor -- not initialized yet */ static struct queue { - int func; /* 0 = read, 1 = write */ - char *buf; - int len; - int result; - int error; + int func; /* 0 = read, 1 = write */ + char *buf; + int len; + int result; + int error; } queue[2]; static int qindex = 0; @@ -305,135 +305,135 @@ static int qindex = 0; int asa_init() { - int fd; - char *p; - - if (audio_fd >= 0) - return audio_fd; - fd = open("/dev/audio", 2); - if (fd < 0) { - perror("asa_init: Can't open /dev/audio"); - return -1; - } - if (slave_init() < 0) { - perror("asa_init: Can't create slave process"); - close(fd); - return -1; - } - audio_fd = fd; - return fd; + int fd; + char *p; + + if (audio_fd >= 0) + return audio_fd; + fd = open("/dev/audio", 2); + if (fd < 0) { + perror("asa_init: Can't open /dev/audio"); + return -1; + } + if (slave_init() < 0) { + perror("asa_init: Can't create slave process"); + close(fd); + return -1; + } + audio_fd = fd; + return fd; } void asa_done() { - slave_done(); - if (audio_fd >= 0) { - if (close(audio_fd) < 0) - perror("asa_done: close(audio_fd)"); - } - audio_fd = -1; + slave_done(); + if (audio_fd >= 0) { + if (close(audio_fd) < 0) + perror("asa_done: close(audio_fd)"); + } + audio_fd = -1; } static void * runjob(arg) - void *arg; + void *arg; { - extern int errno; - struct queue *q = (struct queue *)arg; - char *buf = q->buf; - int len = q->len; - int n = 0; - - if (q->func == 0) - n = read(audio_fd, buf, len); - else - n = write(audio_fd, buf, len); - if (q->func == 0 && n >= 0) { - while (--len >= n && buf[len] == '\0') - ; - n = len+1; - } - q->result = n; - q->error = oserror(); - return arg; + extern int errno; + struct queue *q = (struct queue *)arg; + char *buf = q->buf; + int len = q->len; + int n = 0; + + if (q->func == 0) + n = read(audio_fd, buf, len); + else + n = write(audio_fd, buf, len); + if (q->func == 0 && n >= 0) { + while (--len >= n && buf[len] == '\0') + ; + n = len+1; + } + q->result = n; + q->error = oserror(); + return arg; } static void startjob(func, buf, len) - int func; - char *buf; - int len; + int func; + char *buf; + int len; { - struct queue *q; - - q = &queue[qindex]; - qindex = (qindex+1) & 1; - q->func = func; - q->buf = buf; - q->len = len; - (void) rendezvous(runjob, (void *)q); + struct queue *q; + + q = &queue[qindex]; + qindex = (qindex+1) & 1; + q->func = func; + q->buf = buf; + q->len = len; + (void) rendezvous(runjob, (void *)q); } void asa_start_read(buf, len) - char *buf; - int len; + char *buf; + int len; { - memset(buf, '\0', len); - startjob(0, buf, len); + memset(buf, '\0', len); + startjob(0, buf, len); } void asa_start_write(buf, len) - char *buf; - int len; + char *buf; + int len; { - startjob(1, buf, len); + startjob(1, buf, len); } int asa_wait() { - struct queue *q; - - q = (struct queue *) rendezvous((void*(*)())NULL, (void *)NULL); - if (q == NULL) { - setoserror(0); - return -1; /* No work was queued */ - } - setoserror(q->error); - return q->result; + struct queue *q; + + q = (struct queue *) rendezvous((void*(*)())NULL, (void *)NULL); + if (q == NULL) { + setoserror(0); + return -1; /* No work was queued */ + } + setoserror(q->error); + return q->result; } int asa_poll() { - int err; - - err = prctl(PR_ISBLOCKED, slave_pid); - if (err < 0) { - perror("prctl(PR_ISBLOCKED, slave_pid)"); - return -1; - } - else if (err == 0) - return 0; - else if (work_result == NULL) { - setoserror(0); - return -1; - } - else - return 1; + int err; + + err = prctl(PR_ISBLOCKED, slave_pid); + if (err < 0) { + perror("prctl(PR_ISBLOCKED, slave_pid)"); + return -1; + } + else if (err == 0) + return 0; + else if (work_result == NULL) { + setoserror(0); + return -1; + } + else + return 1; } int asa_cancel() { - int result; - - kill(slave_pid, MYSIG); - result = asa_wait(); - return result; + int result; + + kill(slave_pid, MYSIG); + result = asa_wait(); + return result; } @@ -445,50 +445,50 @@ asa_cancel() main() { - static char buf[10*16*1024]; /* 10 seconds of sound at 16K/sec */ - int n; - int afd; - - if ((afd = asa_init()) < 0) - exit(1); - ioctl(afd, AUDIOCSETRATE, 3); - ioctl(afd, AUDIOCSETOUTGAIN, 0); - printf("Poll returns %d\n", asa_poll()); - go("Hit enter to start recording:\n"); - asa_start_read(buf, sizeof buf); - go("Hit enter to stop recording:\n"); - /*printf("Poll returns %d\n", asa_poll());*/ - n = asa_cancel(); - if (n < 0) - perror("Read failed"); - else { - printf("Got %d bytes\n", n); - printf("Poll returns %d\n", asa_poll()); - go("Hit enter to start playing:\n"); - ioctl(afd, AUDIOCSETOUTGAIN, 50); - asa_start_write(buf, n); - go("Hit enter to stop playing:\n"); - printf("Poll returns %d\n", asa_poll()); - n = asa_cancel(); - if (n < 0) - perror("Write failed"); - else - printf("Stopped at %d bytes\n", n); - } - ioctl(afd, AUDIOCSETOUTGAIN, 0); - asa_done(); - exit(n < 0 ? 1 : 0); + static char buf[10*16*1024]; /* 10 seconds of sound at 16K/sec */ + int n; + int afd; + + if ((afd = asa_init()) < 0) + exit(1); + ioctl(afd, AUDIOCSETRATE, 3); + ioctl(afd, AUDIOCSETOUTGAIN, 0); + printf("Poll returns %d\n", asa_poll()); + go("Hit enter to start recording:\n"); + asa_start_read(buf, sizeof buf); + go("Hit enter to stop recording:\n"); + /*printf("Poll returns %d\n", asa_poll());*/ + n = asa_cancel(); + if (n < 0) + perror("Read failed"); + else { + printf("Got %d bytes\n", n); + printf("Poll returns %d\n", asa_poll()); + go("Hit enter to start playing:\n"); + ioctl(afd, AUDIOCSETOUTGAIN, 50); + asa_start_write(buf, n); + go("Hit enter to stop playing:\n"); + printf("Poll returns %d\n", asa_poll()); + n = asa_cancel(); + if (n < 0) + perror("Write failed"); + else + printf("Stopped at %d bytes\n", n); + } + ioctl(afd, AUDIOCSETOUTGAIN, 0); + asa_done(); + exit(n < 0 ? 1 : 0); } go(str) - char *str; + char *str; { - char line[100]; - - sleep(1); - fputs(str, stdout); - fflush(stdout); - fgets(line, sizeof line, stdin); + char line[100]; + + sleep(1); + fputs(str, stdout); + fflush(stdout); + fgets(line, sizeof line, stdin); } #endif /* MAIN */ @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. diff --git a/src/assert.h b/src/assert.h index f21225e..07d11af 100644 --- a/src/assert.h +++ b/src/assert.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. diff --git a/src/audiomodule.c b/src/audiomodule.c index cca0102..d4bce1a 100644 --- a/src/audiomodule.c +++ b/src/audiomodule.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -38,12 +38,12 @@ static int audio_fd = -1; static int init() { - if (audio_fd >= 0) - return 1; - if ((audio_fd = asa_init()) >= 0) - return 1; - err_setstr(RuntimeError, "can't initialize async audio"); - return 0; + if (audio_fd >= 0) + return 1; + if ((audio_fd = asa_init()) >= 0) + return 1; + err_setstr(RuntimeError, "can't initialize async audio"); + return 0; } @@ -51,565 +51,565 @@ init() static object * audio_get_ioctl(self, args, code) - object *self; - object *args; - long code; + object *self; + object *args; + long code; { - long x; - if (!getnoarg(args)) - return NULL; - if (!init()) - return NULL; - if ((x = ioctl(audio_fd, code, (char *) NULL)) < 0) { - return NULL; - } - return newintobject(x); + long x; + if (!getnoarg(args)) + return NULL; + if (!init()) + return NULL; + if ((x = ioctl(audio_fd, code, (char *) NULL)) < 0) { + return NULL; + } + return newintobject(x); } static object * audio_set_ioctl(self, args, code) - object *self; - object *args; - long code; + object *self; + object *args; + long code; { - long x; - if (!getlongarg(args, &x)) - return NULL; - if (!init()) - return NULL; - if (ioctl(audio_fd, code, (char *) x) != 0) - return NULL; - INCREF(None); - return None; + long x; + if (!getlongarg(args, &x)) + return NULL; + if (!init()) + return NULL; + if (ioctl(audio_fd, code, (char *) x) != 0) + return NULL; + INCREF(None); + return None; } static object * audio_getingain(self, args) - object *self; - object *args; + object *self; + object *args; { - return audio_get_ioctl(self, args, AUDIOCGETINGAIN); + return audio_get_ioctl(self, args, AUDIOCGETINGAIN); } static object * audio_getoutgain(self, args) - object *self; - object *args; + object *self; + object *args; { - return audio_get_ioctl(self, args, AUDIOCGETOUTGAIN); + return audio_get_ioctl(self, args, AUDIOCGETOUTGAIN); } static object * audio_setingain(self, args) - object *self; - object *args; + object *self; + object *args; { - return audio_set_ioctl(self, args, AUDIOCSETINGAIN); + return audio_set_ioctl(self, args, AUDIOCSETINGAIN); } static object * audio_setoutgain(self, args) - object *self; - object *args; + object *self; + object *args; { - return audio_set_ioctl(self, args, AUDIOCSETOUTGAIN); + return audio_set_ioctl(self, args, AUDIOCSETOUTGAIN); } static object * audio_setrate(self, args) - object *self; - object *args; + object *self; + object *args; { - return audio_set_ioctl(self, args, AUDIOCSETRATE); + return audio_set_ioctl(self, args, AUDIOCSETRATE); } static object * audio_setduration(self, args) - object *self; - object *args; + object *self; + object *args; { - return audio_set_ioctl(self, args, AUDIOCDURATION); + return audio_set_ioctl(self, args, AUDIOCDURATION); } /* Compute average bias, and remove it */ static void unbias(buf, len) - char *buf; - int len; + char *buf; + int len; { - register int i; - register int c; - register long bias; - if (len == 0) - return; - bias = 0; - for (i = 0; i < len; i++) { - c = buf[i]; - if (c > 127) - c -= 256; - bias += c; - } - bias = (bias + len/2) / len; /* Rounded average */ - if (bias != 0) { - for (i = 0; i < len; i++) { - buf[i] -= bias; - } - } + register int i; + register int c; + register long bias; + if (len == 0) + return; + bias = 0; + for (i = 0; i < len; i++) { + c = buf[i]; + if (c > 127) + c -= 256; + bias += c; + } + bias = (bias + len/2) / len; /* Rounded average */ + if (bias != 0) { + for (i = 0; i < len; i++) { + buf[i] -= bias; + } + } } static object * audio_read(self, args) - object *self; - object *args; + object *self; + object *args; { - int c, i, n; - object *v; - char *s; - if (!getintarg(args, &n)) - return NULL; - if (n <= 0) { - err_setstr(RuntimeError, "audio.read: arg <= 0"); - return NULL; - } - if (!init()) - return NULL; - v = newsizedstringobject((char *)NULL, n); - if (v == NULL) - return err_nomem(); - s = getstringvalue(v); - n = read(audio_fd, s, n); - if (intrcheck()) { - DECREF(v); - err_set(KeyboardInterrupt); - return NULL; - } - /* Check for errors */ - if (n < 0) { - DECREF(v); - return NULL; - } - /* But EOF is reported as an empty string */ - - unbias(s, n); - resizestring(&v, n); - return v; + int c, i, n; + object *v; + char *s; + if (!getintarg(args, &n)) + return NULL; + if (n <= 0) { + err_setstr(RuntimeError, "audio.read: arg <= 0"); + return NULL; + } + if (!init()) + return NULL; + v = newsizedstringobject((char *)NULL, n); + if (v == NULL) + return err_nomem(); + s = getstringvalue(v); + n = read(audio_fd, s, n); + if (intrcheck()) { + DECREF(v); + err_set(KeyboardInterrupt); + return NULL; + } + /* Check for errors */ + if (n < 0) { + DECREF(v); + return NULL; + } + /* But EOF is reported as an empty string */ + + unbias(s, n); + resizestring(&v, n); + return v; } static object * audio_write(self, args) - object *self; - object *args; + object *self; + object *args; { - int n, n2; - object *v; - if (!getstrarg(args, &v)) - return NULL; - if (!init()) - return NULL; - errno = 0; - n2 = write(audio_fd, getstringvalue(v), n = getstringsize(v)); - if (intrcheck()) { - err_set(KeyboardInterrupt); - return NULL; - } - /* Check for other errors */ - if (n2 != n) { - if (errno == 0) - errno = EIO; - return NULL; - } - INCREF(None); - return None; + int n, n2; + object *v; + if (!getstrarg(args, &v)) + return NULL; + if (!init()) + return NULL; + errno = 0; + n2 = write(audio_fd, getstringvalue(v), n = getstringsize(v)); + if (intrcheck()) { + err_set(KeyboardInterrupt); + return NULL; + } + /* Check for other errors */ + if (n2 != n) { + if (errno == 0) + errno = EIO; + return NULL; + } + INCREF(None); + return None; } /* audio.amplify(sample, f1, f2). - Amplify a sample by a factor changing from f1/256 to (almost) f2/256. - Negative factors are allowed. Sound values that are to large - to fit in a byte are clipped. */ + Amplify a sample by a factor changing from f1/256 to (almost) f2/256. + Negative factors are allowed. Sound values that are to large + to fit in a byte are clipped. */ static object * audio_amplify(self, args) - object *self; - object *args; + object *self; + object *args; { - object *v; - char *s, *t; - int f1, f2; - int i, n; - int c; - if (!getstrintintarg(args, &v, &f1, &f2)) - return NULL; - n = getstringsize(v); - s = getstringvalue(v); - v = newsizedstringobject((char *)NULL, n); - if (v == NULL) - return err_nomem(); - t = getstringvalue(v); - for (i = 0; i < n; i++) { - c = s[i]; - if (c > 127) c -= 256; /* If chars are unsigned */ - c = c * ( f1*(n-i) + f2*i ) / ( n*256 ); - if (c > 127) c = 127; - else if (c < -128) c = -128; - t[i] = c; - } - return v; + object *v; + char *s, *t; + int f1, f2; + int i, n; + int c; + if (!getstrintintarg(args, &v, &f1, &f2)) + return NULL; + n = getstringsize(v); + s = getstringvalue(v); + v = newsizedstringobject((char *)NULL, n); + if (v == NULL) + return err_nomem(); + t = getstringvalue(v); + for (i = 0; i < n; i++) { + c = s[i]; + if (c > 127) c -= 256; /* If chars are unsigned */ + c = c * ( f1*(n-i) + f2*i ) / ( n*256 ); + if (c > 127) c = 127; + else if (c < -128) c = -128; + t[i] = c; + } + return v; } /* audio.reverse(s): return a sample backwards */ static object * audio_reverse(self, args) - object *self; - object *args; + object *self; + object *args; { - object *v; - char *s, *t; - int i, n; - if (!getstrarg(args, &v)) - return NULL; - n = getstringsize(v); - s = getstringvalue(v); - v = newsizedstringobject((char *)NULL, n); - if (v == NULL) - return err_nomem(); - t = getstringvalue(v); - for (i = 0; i < n; i++) { - t[n-1-i] = s[i]; - } - return v; + object *v; + char *s, *t; + int i, n; + if (!getstrarg(args, &v)) + return NULL; + n = getstringsize(v); + s = getstringvalue(v); + v = newsizedstringobject((char *)NULL, n); + if (v == NULL) + return err_nomem(); + t = getstringvalue(v); + for (i = 0; i < n; i++) { + t[n-1-i] = s[i]; + } + return v; } /* audio.add(a, b): add two samples. - Bytes that exceed the range are clipped. - If one is shorter, the rest of the longer sample is returned unchanged. */ + Bytes that exceed the range are clipped. + If one is shorter, the rest of the longer sample is returned unchanged. */ static object * audio_add(self, args) - object *self; - object *args; + object *self; + object *args; { - object *a, *b, *v; - char *sa, *sb, *t; - int i, n, na, nb, c, ca, cb; - if (!getstrstrarg(args, &a, &b)) - return NULL; - na = getstringsize(a); - sa = getstringvalue(a); - nb = getstringsize(b); - sb = getstringvalue(b); - n = (na > nb) ? na : nb; - v = newsizedstringobject((char *)NULL, n); - if (v == NULL) - return err_nomem(); - t = getstringvalue(v); - for (i = 0; i < n; i++) { - c = 0; - if (i < na) { - ca = sa[i]; - if (ca > 127) ca = ca - 256; - c = c + ca; - } - if (i < nb) { - cb = sb[i]; - if (cb > 127) cb = cb - 256; - c = c + cb; - } - if (c > 127) c = 127; - else if (c < -128) c = -128; - t[i] = c; - } - return v; + object *a, *b, *v; + char *sa, *sb, *t; + int i, n, na, nb, c, ca, cb; + if (!getstrstrarg(args, &a, &b)) + return NULL; + na = getstringsize(a); + sa = getstringvalue(a); + nb = getstringsize(b); + sb = getstringvalue(b); + n = (na > nb) ? na : nb; + v = newsizedstringobject((char *)NULL, n); + if (v == NULL) + return err_nomem(); + t = getstringvalue(v); + for (i = 0; i < n; i++) { + c = 0; + if (i < na) { + ca = sa[i]; + if (ca > 127) ca = ca - 256; + c = c + ca; + } + if (i < nb) { + cb = sb[i]; + if (cb > 127) cb = cb - 256; + c = c + cb; + } + if (c > 127) c = 127; + else if (c < -128) c = -128; + t[i] = c; + } + return v; } /* audio.chr2num(s) returns a list containing the numeric values - of the samples. */ + of the samples. */ static object * audio_chr2num(self, args) - object *self; - object *args; + object *self; + object *args; { - object *v, *w; - char *s; - int c, i, n; - static object *ints[256]; - - /* To avoid filling memory with all those int objects, we create - integer objects for all the desired values and reference these. */ - if (ints[255] == NULL) { - for (i = 0; i < 256; i++) { - if (ints[i] != NULL) - continue; - c = i; - if (c > 127) c -= 256; - ints[i] = newintobject((long)c); - if (ints[i] == NULL) - return NULL; - } - } - - if (!getstrarg(args, &v)) - return NULL; - n = getstringsize(v); - s = getstringvalue(v); - v = newlistobject(n); - if (v == NULL) - return err_nomem(); - for (i = 0; i < n; i++) { - c = s[i] & 0xff; - w = ints[c]; - INCREF(w); - if (setlistitem(v, i, w) != 0) { - DECREF(v); - return NULL; - } - } - return v; + object *v, *w; + char *s; + int c, i, n; + static object *ints[256]; + + /* To avoid filling memory with all those int objects, we create + integer objects for all the desired values and reference these. */ + if (ints[255] == NULL) { + for (i = 0; i < 256; i++) { + if (ints[i] != NULL) + continue; + c = i; + if (c > 127) c -= 256; + ints[i] = newintobject((long)c); + if (ints[i] == NULL) + return NULL; + } + } + + if (!getstrarg(args, &v)) + return NULL; + n = getstringsize(v); + s = getstringvalue(v); + v = newlistobject(n); + if (v == NULL) + return err_nomem(); + for (i = 0; i < n; i++) { + c = s[i] & 0xff; + w = ints[c]; + INCREF(w); + if (setlistitem(v, i, w) != 0) { + DECREF(v); + return NULL; + } + } + return v; } /* audio.num2chr is the inverse of audio.chr2num. - Excess values are clipped. */ + Excess values are clipped. */ static object * audio_num2chr(self, args) - object *self; - object *args; + object *self; + object *args; { - object *v, *w; - char *s; - int c, i, n; - if (!is_listobject(args)) { - err_badarg(); - return NULL; - } - n = getlistsize(args); - v = newsizedstringobject((char *)NULL, n); - if (v == NULL) - return NULL; - s = getstringvalue(v); - for (i = 0; i < n; i++) { - w = getlistitem(args, i); - if (!is_intobject(w)) { - DECREF(v); - err_badarg(); - return NULL; - } - s[i] = getintvalue(w); - } - return v; + object *v, *w; + char *s; + int c, i, n; + if (!is_listobject(args)) { + err_badarg(); + return NULL; + } + n = getlistsize(args); + v = newsizedstringobject((char *)NULL, n); + if (v == NULL) + return NULL; + s = getstringvalue(v); + for (i = 0; i < n; i++) { + w = getlistitem(args, i); + if (!is_intobject(w)) { + DECREF(v); + err_badarg(); + return NULL; + } + s[i] = getintvalue(w); + } + return v; } static object *stdaudio_buffer = NULL; static object * audio_start_recording(self, args) - object *self; - object *args; + object *self; + object *args; { - int n; - object *v; - char *s; - if (!getintarg(args, &n)) - return NULL; - if (stdaudio_buffer != NULL) { - err_setstr(RuntimeError, "audio.start_recording: device busy"); - return NULL; - } - if (n <= 0) { - err_setstr(TypeError, "audio.start_recording: arg <= 0"); - return NULL; - } - if (!init()) - return NULL; - v = newsizedstringobject((char *)NULL, n); - if (v == NULL) - return err_nomem(); - s = getstringvalue(v); - asa_start_read(s, n); - stdaudio_buffer = v; - INCREF(None); - return None; + int n; + object *v; + char *s; + if (!getintarg(args, &n)) + return NULL; + if (stdaudio_buffer != NULL) { + err_setstr(RuntimeError, "audio.start_recording: device busy"); + return NULL; + } + if (n <= 0) { + err_setstr(TypeError, "audio.start_recording: arg <= 0"); + return NULL; + } + if (!init()) + return NULL; + v = newsizedstringobject((char *)NULL, n); + if (v == NULL) + return err_nomem(); + s = getstringvalue(v); + asa_start_read(s, n); + stdaudio_buffer = v; + INCREF(None); + return None; } static object * audio_poll(self, args) - object *self; - object *args; + object *self; + object *args; { - int n; - if (!getnoarg(args)) - return NULL; - if (stdaudio_buffer == NULL) { - err_setstr(RuntimeError, "audio.poll: not busy"); - return NULL; - } - if (!init()) - return NULL; - if ((n = asa_poll()) < 0) - return NULL; - return newintobject(n); + int n; + if (!getnoarg(args)) + return NULL; + if (stdaudio_buffer == NULL) { + err_setstr(RuntimeError, "audio.poll: not busy"); + return NULL; + } + if (!init()) + return NULL; + if ((n = asa_poll()) < 0) + return NULL; + return newintobject(n); } static object * audio_wait_recording(self, args) - object *self; - object *args; + object *self; + object *args; { - object *v; - int n; - if (!getnoarg(args)) - return NULL; - if (stdaudio_buffer == NULL) { - err_setstr(RuntimeError, "audio.wait_recording: not busy"); - return NULL; - } - if (!init()) - return NULL; - if ((n = asa_wait()) < 0) - return NULL; - v = stdaudio_buffer; - stdaudio_buffer = NULL; - unbias(getstringvalue(v), n); - resizestring(&v, n); - return v; + object *v; + int n; + if (!getnoarg(args)) + return NULL; + if (stdaudio_buffer == NULL) { + err_setstr(RuntimeError, "audio.wait_recording: not busy"); + return NULL; + } + if (!init()) + return NULL; + if ((n = asa_wait()) < 0) + return NULL; + v = stdaudio_buffer; + stdaudio_buffer = NULL; + unbias(getstringvalue(v), n); + resizestring(&v, n); + return v; } static object * audio_stop_recording(self, args) - object *self; - object *args; + object *self; + object *args; { - int n; - object *v; - char *s; - if (!getnoarg(args)) - return NULL; - if (stdaudio_buffer == NULL) { - err_setstr(RuntimeError, "audio.stop_recording: not busy"); - return NULL; - } - if ((n = asa_cancel()) < 0) - return NULL; - v = stdaudio_buffer; - stdaudio_buffer = NULL; - s = getstringvalue(v); - unbias(s, n); - resizestring(&v, n); - return v; + int n; + object *v; + char *s; + if (!getnoarg(args)) + return NULL; + if (stdaudio_buffer == NULL) { + err_setstr(RuntimeError, "audio.stop_recording: not busy"); + return NULL; + } + if ((n = asa_cancel()) < 0) + return NULL; + v = stdaudio_buffer; + stdaudio_buffer = NULL; + s = getstringvalue(v); + unbias(s, n); + resizestring(&v, n); + return v; } static object * audio_start_playing(self, args) - object *self; - object *args; + object *self; + object *args; { - object *v; - if (!getstrarg(args, &v)) - return NULL; - if (stdaudio_buffer != NULL) { - err_setstr(RuntimeError, "audio.start_recording: device rbusy"); - return NULL; - } - asa_start_write(getstringvalue(v), (int)getstringsize(v)); - INCREF(v); - stdaudio_buffer = v; - INCREF(None); - return None; + object *v; + if (!getstrarg(args, &v)) + return NULL; + if (stdaudio_buffer != NULL) { + err_setstr(RuntimeError, "audio.start_recording: device rbusy"); + return NULL; + } + asa_start_write(getstringvalue(v), (int)getstringsize(v)); + INCREF(v); + stdaudio_buffer = v; + INCREF(None); + return None; } static object * audio_wait_playing(self, args) - object *self; - object *args; + object *self; + object *args; { - int n; - if (!getnoarg(args)) - return NULL; - if (stdaudio_buffer == NULL) { - err_setstr(RuntimeError, "audio.wait_playing: not busy"); - return NULL; - } - if ((n = asa_wait()) < 0) - return NULL; - DECREF(stdaudio_buffer); - stdaudio_buffer = NULL; - /* XXX return newintobject((long)n); ??? */ - INCREF(None); - return None; + int n; + if (!getnoarg(args)) + return NULL; + if (stdaudio_buffer == NULL) { + err_setstr(RuntimeError, "audio.wait_playing: not busy"); + return NULL; + } + if ((n = asa_wait()) < 0) + return NULL; + DECREF(stdaudio_buffer); + stdaudio_buffer = NULL; + /* XXX return newintobject((long)n); ??? */ + INCREF(None); + return None; } static object * audio_stop_playing(self, args) - object *self; - object *args; + object *self; + object *args; { - int n; - if (!getnoarg(args)) - return NULL; - if (stdaudio_buffer == NULL) { - err_setstr(RuntimeError, "audio.stop_playing: not busy"); - return NULL; - } - if ((n = asa_cancel()) < 0) - return NULL; - DECREF(stdaudio_buffer); - stdaudio_buffer = NULL; - return newintobject((long)n); + int n; + if (!getnoarg(args)) + return NULL; + if (stdaudio_buffer == NULL) { + err_setstr(RuntimeError, "audio.stop_playing: not busy"); + return NULL; + } + if ((n = asa_cancel()) < 0) + return NULL; + DECREF(stdaudio_buffer); + stdaudio_buffer = NULL; + return newintobject((long)n); } static object * audio_audio_done(self, args) - object *self; - object *args; + object *self; + object *args; { - if (!getnoarg(args)) - return NULL; - asa_done(); - if (stdaudio_buffer != NULL) - DECREF(stdaudio_buffer); - stdaudio_buffer = NULL; - audio_fd = -1; - INCREF(None); - return None; + if (!getnoarg(args)) + return NULL; + asa_done(); + if (stdaudio_buffer != NULL) + DECREF(stdaudio_buffer); + stdaudio_buffer = NULL; + audio_fd = -1; + INCREF(None); + return None; } static struct methodlist audio_methods[] = { - {"getingain", audio_getingain}, - {"getoutgain", audio_getoutgain}, - {"setingain", audio_setingain}, - {"setoutgain", audio_setoutgain}, - {"setrate", audio_setrate}, - {"setduration", audio_setduration}, - {"read", audio_read}, - {"write", audio_write}, - {"amplify", audio_amplify}, - {"reverse", audio_reverse}, - {"add", audio_add}, - {"chr2num", audio_chr2num}, - {"num2chr", audio_num2chr}, - - /* "asa" interface: */ - - {"start_recording", audio_start_recording}, - {"poll_recording", audio_poll}, - {"wait_recording", audio_wait_recording}, - {"stop_recording", audio_stop_recording}, - - {"start_playing", audio_start_playing}, - {"poll_playing", audio_poll}, - {"wait_playing", audio_wait_playing}, - {"stop_playing", audio_stop_playing}, - - {"done", audio_audio_done}, - - {NULL, NULL} /* Sentinel */ + {"getingain", audio_getingain}, + {"getoutgain", audio_getoutgain}, + {"setingain", audio_setingain}, + {"setoutgain", audio_setoutgain}, + {"setrate", audio_setrate}, + {"setduration", audio_setduration}, + {"read", audio_read}, + {"write", audio_write}, + {"amplify", audio_amplify}, + {"reverse", audio_reverse}, + {"add", audio_add}, + {"chr2num", audio_chr2num}, + {"num2chr", audio_num2chr}, + + /* "asa" interface: */ + + {"start_recording", audio_start_recording}, + {"poll_recording", audio_poll}, + {"wait_recording", audio_wait_recording}, + {"stop_recording", audio_stop_recording}, + + {"start_playing", audio_start_playing}, + {"poll_playing", audio_poll}, + {"wait_playing", audio_wait_playing}, + {"stop_playing", audio_stop_playing}, + + {"done", audio_audio_done}, + + {NULL, NULL} /* Sentinel */ }; void initaudio() { - initmodule("audio", audio_methods); + initmodule("audio", audio_methods); } diff --git a/src/bitset.c b/src/bitset.c index c08dcc7..34e6e6e 100644 --- a/src/bitset.c +++ b/src/bitset.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -29,71 +29,71 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. bitset newbitset(nbits) - int nbits; + int nbits; { - int nbytes = NBYTES(nbits); - bitset ss = NEW(BYTE, nbytes); - - if (ss == NULL) - fatal("no mem for bitset"); - - ss += nbytes; - while (--nbytes >= 0) - *--ss = 0; - return ss; + int nbytes = NBYTES(nbits); + bitset ss = NEW(BYTE, nbytes); + + if (ss == NULL) + fatal("no mem for bitset"); + + ss += nbytes; + while (--nbytes >= 0) + *--ss = 0; + return ss; } void delbitset(ss) - bitset ss; + bitset ss; { - DEL(ss); + DEL(ss); } int addbit(ss, ibit) - bitset ss; - int ibit; + bitset ss; + int ibit; { - int ibyte = BIT2BYTE(ibit); - BYTE mask = BIT2MASK(ibit); - - if (ss[ibyte] & mask) - return 0; /* Bit already set */ - ss[ibyte] |= mask; - return 1; + int ibyte = BIT2BYTE(ibit); + BYTE mask = BIT2MASK(ibit); + + if (ss[ibyte] & mask) + return 0; /* Bit already set */ + ss[ibyte] |= mask; + return 1; } #if 0 /* Now a macro */ int testbit(ss, ibit) - bitset ss; - int ibit; + bitset ss; + int ibit; { - return (ss[BIT2BYTE(ibit)] & BIT2MASK(ibit)) != 0; + return (ss[BIT2BYTE(ibit)] & BIT2MASK(ibit)) != 0; } #endif int samebitset(ss1, ss2, nbits) - bitset ss1, ss2; - int nbits; + bitset ss1, ss2; + int nbits; { - int i; - - for (i = NBYTES(nbits); --i >= 0; ) - if (*ss1++ != *ss2++) - return 0; - return 1; + int i; + + for (i = NBYTES(nbits); --i >= 0; ) + if (*ss1++ != *ss2++) + return 0; + return 1; } void mergebitset(ss1, ss2, nbits) - bitset ss1, ss2; - int nbits; + bitset ss1, ss2; + int nbits; { - int i; - - for (i = NBYTES(nbits); --i >= 0; ) - *ss1++ |= *ss2++; + int i; + + for (i = NBYTES(nbits); --i >= 0; ) + *ss1++ |= *ss2++; } diff --git a/src/bitset.h b/src/bitset.h index 5ec6882..9800f5c 100644 --- a/src/bitset.h +++ b/src/bitset.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -24,7 +24,7 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* Bitset interface */ -#define BYTE char +#define BYTE char typedef BYTE *bitset; @@ -35,12 +35,12 @@ int addbit PROTO((bitset bs, int ibit)); /* Returns 0 if already set */ int samebitset PROTO((bitset bs1, bitset bs2, int nbits)); void mergebitset PROTO((bitset bs1, bitset bs2, int nbits)); -#define BITSPERBYTE (8*sizeof(BYTE)) -#define NBYTES(nbits) (((nbits) + BITSPERBYTE - 1) / BITSPERBYTE) +#define BITSPERBYTE (8*sizeof(BYTE)) +#define NBYTES(nbits) (((nbits) + BITSPERBYTE - 1) / BITSPERBYTE) -#define BIT2BYTE(ibit) ((ibit) / BITSPERBYTE) -#define BIT2SHIFT(ibit) ((ibit) % BITSPERBYTE) -#define BIT2MASK(ibit) (1 << BIT2SHIFT(ibit)) -#define BYTE2BIT(ibyte) ((ibyte) * BITSPERBYTE) +#define BIT2BYTE(ibit) ((ibit) / BITSPERBYTE) +#define BIT2SHIFT(ibit) ((ibit) % BITSPERBYTE) +#define BIT2MASK(ibit) (1 << BIT2SHIFT(ibit)) +#define BYTE2BIT(ibyte) ((ibyte) * BITSPERBYTE) #define testbit(ss, ibit) (((ss)[BIT2BYTE(ibit)] & BIT2MASK(ibit)) != 0) diff --git a/src/bltinmodule.c b/src/bltinmodule.c index 151ba86..1d7d838 100644 --- a/src/bltinmodule.c +++ b/src/bltinmodule.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -39,479 +39,479 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. static object * builtin_abs(self, v) - object *self; - object *v; + object *self; + object *v; { - /* XXX This should be a method in the as_number struct in the type */ - if (v == NULL) { - /* */ - } - else if (is_intobject(v)) { - long x = getintvalue(v); - if (x < 0) - x = -x; - return newintobject(x); - } - else if (is_floatobject(v)) { - double x = getfloatvalue(v); - if (x < 0) - x = -x; - return newfloatobject(x); - } - err_setstr(TypeError, "abs() argument must be float or int"); - return NULL; + /* XXX This should be a method in the as_number struct in the type */ + if (v == NULL) { + /* */ + } + else if (is_intobject(v)) { + long x = getintvalue(v); + if (x < 0) + x = -x; + return newintobject(x); + } + else if (is_floatobject(v)) { + double x = getfloatvalue(v); + if (x < 0) + x = -x; + return newfloatobject(x); + } + err_setstr(TypeError, "abs() argument must be float or int"); + return NULL; } static object * builtin_chr(self, v) - object *self; - object *v; + object *self; + object *v; { - long x; - char s[1]; - if (v == NULL || !is_intobject(v)) { - err_setstr(TypeError, "chr() must have int argument"); - return NULL; - } - x = getintvalue(v); - if (x < 0 || x >= 256) { - err_setstr(RuntimeError, "chr() arg not in range(256)"); - return NULL; - } - s[0] = x; - return newsizedstringobject(s, 1); + long x; + char s[1]; + if (v == NULL || !is_intobject(v)) { + err_setstr(TypeError, "chr() must have int argument"); + return NULL; + } + x = getintvalue(v); + if (x < 0 || x >= 256) { + err_setstr(RuntimeError, "chr() arg not in range(256)"); + return NULL; + } + s[0] = x; + return newsizedstringobject(s, 1); } static object * builtin_dir(self, v) - object *self; - object *v; + object *self; + object *v; { - object *d; - if (v == NULL) { - d = getlocals(); - } - else { - if (!is_moduleobject(v)) { - err_setstr(TypeError, - "dir() argument, must be module or absent"); - return NULL; - } - d = getmoduledict(v); - } - v = getdictkeys(d); - if (sortlist(v) != 0) { - DECREF(v); - v = NULL; - } - return v; + object *d; + if (v == NULL) { + d = getlocals(); + } + else { + if (!is_moduleobject(v)) { + err_setstr(TypeError, + "dir() argument, must be module or absent"); + return NULL; + } + d = getmoduledict(v); + } + v = getdictkeys(d); + if (sortlist(v) != 0) { + DECREF(v); + v = NULL; + } + return v; } static object * builtin_divmod(self, v) - object *self; - object *v; + object *self; + object *v; { - object *x, *y; - long xi, yi, xdivy, xmody; - if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { - err_setstr(TypeError, "divmod() requires 2 int arguments"); - return NULL; - } - x = gettupleitem(v, 0); - y = gettupleitem(v, 1); - if (!is_intobject(x) || !is_intobject(y)) { - err_setstr(TypeError, "divmod() requires 2 int arguments"); - return NULL; - } - xi = getintvalue(x); - yi = getintvalue(y); - if (yi == 0) { - err_setstr(TypeError, "divmod() division by zero"); - return NULL; - } - if (yi < 0) { - xdivy = -xi / -yi; - } - else { - xdivy = xi / yi; - } - xmody = xi - xdivy*yi; - if (xmody < 0 && yi > 0 || xmody > 0 && yi < 0) { - xmody += yi; - xdivy -= 1; - } - v = newtupleobject(2); - x = newintobject(xdivy); - y = newintobject(xmody); - if (v == NULL || x == NULL || y == NULL || - settupleitem(v, 0, x) != 0 || - settupleitem(v, 1, y) != 0) { - XDECREF(v); - XDECREF(x); - XDECREF(y); - return NULL; - } - return v; + object *x, *y; + long xi, yi, xdivy, xmody; + if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { + err_setstr(TypeError, "divmod() requires 2 int arguments"); + return NULL; + } + x = gettupleitem(v, 0); + y = gettupleitem(v, 1); + if (!is_intobject(x) || !is_intobject(y)) { + err_setstr(TypeError, "divmod() requires 2 int arguments"); + return NULL; + } + xi = getintvalue(x); + yi = getintvalue(y); + if (yi == 0) { + err_setstr(TypeError, "divmod() division by zero"); + return NULL; + } + if (yi < 0) { + xdivy = -xi / -yi; + } + else { + xdivy = xi / yi; + } + xmody = xi - xdivy*yi; + if (xmody < 0 && yi > 0 || xmody > 0 && yi < 0) { + xmody += yi; + xdivy -= 1; + } + v = newtupleobject(2); + x = newintobject(xdivy); + y = newintobject(xmody); + if (v == NULL || x == NULL || y == NULL || + settupleitem(v, 0, x) != 0 || + settupleitem(v, 1, y) != 0) { + XDECREF(v); + XDECREF(x); + XDECREF(y); + return NULL; + } + return v; } static object * exec_eval(v, start) - object *v; - int start; + object *v; + int start; { - object *str = NULL, *globals = NULL, *locals = NULL; - int n; - if (v != NULL) { - if (is_stringobject(v)) - str = v; - else if (is_tupleobject(v) && - ((n = gettuplesize(v)) == 2 || n == 3)) { - str = gettupleitem(v, 0); - globals = gettupleitem(v, 1); - if (n == 3) - locals = gettupleitem(v, 2); - } - } - if (str == NULL || !is_stringobject(str) || - globals != NULL && !is_dictobject(globals) || - locals != NULL && !is_dictobject(locals)) { - err_setstr(TypeError, - "exec/eval arguments must be string[,dict[,dict]]"); - return NULL; - } - return run_string(getstringvalue(str), start, globals, locals); + object *str = NULL, *globals = NULL, *locals = NULL; + int n; + if (v != NULL) { + if (is_stringobject(v)) + str = v; + else if (is_tupleobject(v) && + ((n = gettuplesize(v)) == 2 || n == 3)) { + str = gettupleitem(v, 0); + globals = gettupleitem(v, 1); + if (n == 3) + locals = gettupleitem(v, 2); + } + } + if (str == NULL || !is_stringobject(str) || + globals != NULL && !is_dictobject(globals) || + locals != NULL && !is_dictobject(locals)) { + err_setstr(TypeError, + "exec/eval arguments must be string[,dict[,dict]]"); + return NULL; + } + return run_string(getstringvalue(str), start, globals, locals); } static object * builtin_eval(self, v) - object *self; - object *v; + object *self; + object *v; { - return exec_eval(v, eval_input); + return exec_eval(v, eval_input); } static object * builtin_exec(self, v) - object *self; - object *v; + object *self; + object *v; { - return exec_eval(v, file_input); + return exec_eval(v, file_input); } static object * builtin_float(self, v) - object *self; - object *v; + object *self; + object *v; { - if (v == NULL) { - /* */ - } - else if (is_floatobject(v)) { - INCREF(v); - return v; - } - else if (is_intobject(v)) { - long x = getintvalue(v); - return newfloatobject((double)x); - } - err_setstr(TypeError, "float() argument must be float or int"); - return NULL; + if (v == NULL) { + /* */ + } + else if (is_floatobject(v)) { + INCREF(v); + return v; + } + else if (is_intobject(v)) { + long x = getintvalue(v); + return newfloatobject((double)x); + } + err_setstr(TypeError, "float() argument must be float or int"); + return NULL; } static object * builtin_input(self, v) - object *self; - object *v; + object *self; + object *v; { - FILE *in = sysgetfile("stdin", stdin); - FILE *out = sysgetfile("stdout", stdout); - node *n; - int err; - object *m, *d; - flushline(); - if (v != NULL) - printobject(v, out, PRINT_RAW); - m = add_module("__main__"); - d = getmoduledict(m); - return run_file(in, "<stdin>", expr_input, d, d); + FILE *in = sysgetfile("stdin", stdin); + FILE *out = sysgetfile("stdout", stdout); + node *n; + int err; + object *m, *d; + flushline(); + if (v != NULL) + printobject(v, out, PRINT_RAW); + m = add_module("__main__"); + d = getmoduledict(m); + return run_file(in, "<stdin>", expr_input, d, d); } static object * builtin_int(self, v) - object *self; - object *v; + object *self; + object *v; { - if (v == NULL) { - /* */ - } - else if (is_intobject(v)) { - INCREF(v); - return v; - } - else if (is_floatobject(v)) { - double x = getfloatvalue(v); - return newintobject((long)x); - } - err_setstr(TypeError, "int() argument must be float or int"); - return NULL; + if (v == NULL) { + /* */ + } + else if (is_intobject(v)) { + INCREF(v); + return v; + } + else if (is_floatobject(v)) { + double x = getfloatvalue(v); + return newintobject((long)x); + } + err_setstr(TypeError, "int() argument must be float or int"); + return NULL; } static object * builtin_len(self, v) - object *self; - object *v; + object *self; + object *v; { - long len; - typeobject *tp; - if (v == NULL) { - err_setstr(TypeError, "len() without argument"); - return NULL; - } - tp = v->ob_type; - if (tp->tp_as_sequence != NULL) { - len = (*tp->tp_as_sequence->sq_length)(v); - } - else if (tp->tp_as_mapping != NULL) { - len = (*tp->tp_as_mapping->mp_length)(v); - } - else { - err_setstr(TypeError, "len() of unsized object"); - return NULL; - } - return newintobject(len); + long len; + typeobject *tp; + if (v == NULL) { + err_setstr(TypeError, "len() without argument"); + return NULL; + } + tp = v->ob_type; + if (tp->tp_as_sequence != NULL) { + len = (*tp->tp_as_sequence->sq_length)(v); + } + else if (tp->tp_as_mapping != NULL) { + len = (*tp->tp_as_mapping->mp_length)(v); + } + else { + err_setstr(TypeError, "len() of unsized object"); + return NULL; + } + return newintobject(len); } static object * min_max(v, sign) - object *v; - int sign; + object *v; + int sign; { - int i, n, cmp; - object *w, *x; - sequence_methods *sq; - if (v == NULL) { - err_setstr(TypeError, "min() or max() without argument"); - return NULL; - } - sq = v->ob_type->tp_as_sequence; - if (sq == NULL) { - err_setstr(TypeError, "min() or max() of non-sequence"); - return NULL; - } - n = (*sq->sq_length)(v); - if (n == 0) { - err_setstr(RuntimeError, "min() or max() of empty sequence"); - return NULL; - } - w = (*sq->sq_item)(v, 0); /* Implies INCREF */ - for (i = 1; i < n; i++) { - x = (*sq->sq_item)(v, i); /* Implies INCREF */ - cmp = cmpobject(x, w); - if (cmp * sign > 0) { - DECREF(w); - w = x; - } - else - DECREF(x); - } - return w; + int i, n, cmp; + object *w, *x; + sequence_methods *sq; + if (v == NULL) { + err_setstr(TypeError, "min() or max() without argument"); + return NULL; + } + sq = v->ob_type->tp_as_sequence; + if (sq == NULL) { + err_setstr(TypeError, "min() or max() of non-sequence"); + return NULL; + } + n = (*sq->sq_length)(v); + if (n == 0) { + err_setstr(RuntimeError, "min() or max() of empty sequence"); + return NULL; + } + w = (*sq->sq_item)(v, 0); /* Implies INCREF */ + for (i = 1; i < n; i++) { + x = (*sq->sq_item)(v, i); /* Implies INCREF */ + cmp = cmpobject(x, w); + if (cmp * sign > 0) { + DECREF(w); + w = x; + } + else + DECREF(x); + } + return w; } static object * builtin_min(self, v) - object *self; - object *v; + object *self; + object *v; { - return min_max(v, -1); + return min_max(v, -1); } static object * builtin_max(self, v) - object *self; - object *v; + object *self; + object *v; { - return min_max(v, 1); + return min_max(v, 1); } static object * builtin_open(self, v) - object *self; - object *v; + object *self; + object *v; { - object *name, *mode; - if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2 || - !is_stringobject(name = gettupleitem(v, 0)) || - !is_stringobject(mode = gettupleitem(v, 1))) { - err_setstr(TypeError, "open() requires 2 string arguments"); - return NULL; - } - v = newfileobject(getstringvalue(name), getstringvalue(mode)); - return v; + object *name, *mode; + if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2 || + !is_stringobject(name = gettupleitem(v, 0)) || + !is_stringobject(mode = gettupleitem(v, 1))) { + err_setstr(TypeError, "open() requires 2 string arguments"); + return NULL; + } + v = newfileobject(getstringvalue(name), getstringvalue(mode)); + return v; } static object * builtin_ord(self, v) - object *self; - object *v; + object *self; + object *v; { - if (v == NULL || !is_stringobject(v)) { - err_setstr(TypeError, "ord() must have string argument"); - return NULL; - } - if (getstringsize(v) != 1) { - err_setstr(RuntimeError, "ord() arg must have length 1"); - return NULL; - } - return newintobject((long)(getstringvalue(v)[0] & 0xff)); + if (v == NULL || !is_stringobject(v)) { + err_setstr(TypeError, "ord() must have string argument"); + return NULL; + } + if (getstringsize(v) != 1) { + err_setstr(RuntimeError, "ord() arg must have length 1"); + return NULL; + } + return newintobject((long)(getstringvalue(v)[0] & 0xff)); } static object * builtin_range(self, v) - object *self; - object *v; + object *self; + object *v; { - static char *errmsg = "range() requires 1-3 int arguments"; - int i, n; - long ilow, ihigh, istep; - if (v != NULL && is_intobject(v)) { - ilow = 0; ihigh = getintvalue(v); istep = 1; - } - else if (v == NULL || !is_tupleobject(v)) { - err_setstr(TypeError, errmsg); - return NULL; - } - else { - n = gettuplesize(v); - if (n < 1 || n > 3) { - err_setstr(TypeError, errmsg); - return NULL; - } - for (i = 0; i < n; i++) { - if (!is_intobject(gettupleitem(v, i))) { - err_setstr(TypeError, errmsg); - return NULL; - } - } - if (n == 3) { - istep = getintvalue(gettupleitem(v, 2)); - --n; - } - else - istep = 1; - ihigh = getintvalue(gettupleitem(v, --n)); - if (n > 0) - ilow = getintvalue(gettupleitem(v, 0)); - else - ilow = 0; - } - if (istep == 0) { - err_setstr(RuntimeError, "zero step for range()"); - return NULL; - } - /* XXX ought to check overflow of subtraction */ - if (istep > 0) - n = (ihigh - ilow + istep - 1) / istep; - else - n = (ihigh - ilow + istep + 1) / istep; - if (n < 0) - n = 0; - v = newlistobject(n); - if (v == NULL) - return NULL; - for (i = 0; i < n; i++) { - object *w = newintobject(ilow); - if (w == NULL) { - DECREF(v); - return NULL; - } - setlistitem(v, i, w); - ilow += istep; - } - return v; + static char *errmsg = "range() requires 1-3 int arguments"; + int i, n; + long ilow, ihigh, istep; + if (v != NULL && is_intobject(v)) { + ilow = 0; ihigh = getintvalue(v); istep = 1; + } + else if (v == NULL || !is_tupleobject(v)) { + err_setstr(TypeError, errmsg); + return NULL; + } + else { + n = gettuplesize(v); + if (n < 1 || n > 3) { + err_setstr(TypeError, errmsg); + return NULL; + } + for (i = 0; i < n; i++) { + if (!is_intobject(gettupleitem(v, i))) { + err_setstr(TypeError, errmsg); + return NULL; + } + } + if (n == 3) { + istep = getintvalue(gettupleitem(v, 2)); + --n; + } + else + istep = 1; + ihigh = getintvalue(gettupleitem(v, --n)); + if (n > 0) + ilow = getintvalue(gettupleitem(v, 0)); + else + ilow = 0; + } + if (istep == 0) { + err_setstr(RuntimeError, "zero step for range()"); + return NULL; + } + /* XXX ought to check overflow of subtraction */ + if (istep > 0) + n = (ihigh - ilow + istep - 1) / istep; + else + n = (ihigh - ilow + istep + 1) / istep; + if (n < 0) + n = 0; + v = newlistobject(n); + if (v == NULL) + return NULL; + for (i = 0; i < n; i++) { + object *w = newintobject(ilow); + if (w == NULL) { + DECREF(v); + return NULL; + } + setlistitem(v, i, w); + ilow += istep; + } + return v; } static object * builtin_raw_input(self, v) - object *self; - object *v; + object *self; + object *v; { - FILE *in = sysgetfile("stdin", stdin); - FILE *out = sysgetfile("stdout", stdout); - char *p; - int err; - int n = 1000; - flushline(); - if (v != NULL) - printobject(v, out, PRINT_RAW); - v = newsizedstringobject((char *)NULL, n); - if (v != NULL) { - if ((err = fgets_intr(getstringvalue(v), n+1, in)) != E_OK) { - err_input(err); - DECREF(v); - return NULL; - } - else { - n = strlen(getstringvalue(v)); - if (n > 0 && getstringvalue(v)[n-1] == '\n') - n--; - resizestring(&v, n); - } - } - return v; + FILE *in = sysgetfile("stdin", stdin); + FILE *out = sysgetfile("stdout", stdout); + char *p; + int err; + int n = 1000; + flushline(); + if (v != NULL) + printobject(v, out, PRINT_RAW); + v = newsizedstringobject((char *)NULL, n); + if (v != NULL) { + if ((err = fgets_intr(getstringvalue(v), n+1, in)) != E_OK) { + err_input(err); + DECREF(v); + return NULL; + } + else { + n = strlen(getstringvalue(v)); + if (n > 0 && getstringvalue(v)[n-1] == '\n') + n--; + resizestring(&v, n); + } + } + return v; } static object * builtin_reload(self, v) - object *self; - object *v; + object *self; + object *v; { - return reload_module(v); + return reload_module(v); } static object * builtin_type(self, v) - object *self; - object *v; + object *self; + object *v; { - if (v == NULL) { - err_setstr(TypeError, "type() requres an argument"); - return NULL; - } - v = (object *)v->ob_type; - INCREF(v); - return v; + if (v == NULL) { + err_setstr(TypeError, "type() requres an argument"); + return NULL; + } + v = (object *)v->ob_type; + INCREF(v); + return v; } static struct methodlist builtin_methods[] = { - {"abs", builtin_abs}, - {"chr", builtin_chr}, - {"dir", builtin_dir}, - {"divmod", builtin_divmod}, - {"eval", builtin_eval}, - {"exec", builtin_exec}, - {"float", builtin_float}, - {"input", builtin_input}, - {"int", builtin_int}, - {"len", builtin_len}, - {"max", builtin_max}, - {"min", builtin_min}, - {"open", builtin_open}, /* XXX move to OS module */ - {"ord", builtin_ord}, - {"range", builtin_range}, - {"raw_input", builtin_raw_input}, - {"reload", builtin_reload}, - {"type", builtin_type}, - {NULL, NULL}, + {"abs", builtin_abs}, + {"chr", builtin_chr}, + {"dir", builtin_dir}, + {"divmod", builtin_divmod}, + {"eval", builtin_eval}, + {"exec", builtin_exec}, + {"float", builtin_float}, + {"input", builtin_input}, + {"int", builtin_int}, + {"len", builtin_len}, + {"max", builtin_max}, + {"min", builtin_min}, + {"open", builtin_open}, /* XXX move to OS module */ + {"ord", builtin_ord}, + {"range", builtin_range}, + {"raw_input", builtin_raw_input}, + {"reload", builtin_reload}, + {"type", builtin_type}, + {NULL, NULL}, }; static object *builtin_dict; object * getbuiltin(name) - char *name; + char *name; { - return dictlookup(builtin_dict, name); + return dictlookup(builtin_dict, name); } /* Predefined exceptions */ @@ -526,34 +526,34 @@ object *KeyboardInterrupt; static object * newstdexception(name, message) - char *name, *message; + char *name, *message; { - object *v = newstringobject(message); - if (v == NULL || dictinsert(builtin_dict, name, v) != 0) - fatal("no mem for new standard exception"); - return v; + object *v = newstringobject(message); + if (v == NULL || dictinsert(builtin_dict, name, v) != 0) + fatal("no mem for new standard exception"); + return v; } static void initerrors() { - RuntimeError = newstdexception("RuntimeError", "run-time error"); - EOFError = newstdexception("EOFError", "end-of-file read"); - TypeError = newstdexception("TypeError", "type error"); - MemoryError = newstdexception("MemoryError", "out of memory"); - NameError = newstdexception("NameError", "undefined name"); - SystemError = newstdexception("SystemError", "system error"); - KeyboardInterrupt = - newstdexception("KeyboardInterrupt", "keyboard interrupt"); + RuntimeError = newstdexception("RuntimeError", "run-time error"); + EOFError = newstdexception("EOFError", "end-of-file read"); + TypeError = newstdexception("TypeError", "type error"); + MemoryError = newstdexception("MemoryError", "out of memory"); + NameError = newstdexception("NameError", "undefined name"); + SystemError = newstdexception("SystemError", "system error"); + KeyboardInterrupt = + newstdexception("KeyboardInterrupt", "keyboard interrupt"); } void initbuiltin() { - object *m; - m = initmodule("builtin", builtin_methods); - builtin_dict = getmoduledict(m); - INCREF(builtin_dict); - initerrors(); - (void) dictinsert(builtin_dict, "None", None); + object *m; + m = initmodule("builtin", builtin_methods); + builtin_dict = getmoduledict(m); + INCREF(builtin_dict); + initerrors(); + (void) dictinsert(builtin_dict, "None", None); } diff --git a/src/bltinmodule.h b/src/bltinmodule.h index fe16907..41c11cc 100644 --- a/src/bltinmodule.h +++ b/src/bltinmodule.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. diff --git a/src/ceval.c b/src/ceval.c index 6876208..7213d5b 100644 --- a/src/ceval.c +++ b/src/ceval.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -42,12 +42,12 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #ifdef TRACE static int prtrace(v, str) - object *v; - char *str; + object *v; + char *str; { - printf("%s ", str); - printobject(v, stdout, 0); - printf("\n"); + printf("%s ", str); + printobject(v, stdout, 0); + printf("\n"); } #endif @@ -56,48 +56,48 @@ static frameobject *current_frame; object * getlocals() { - if (current_frame == NULL) - return NULL; - else - return current_frame->f_locals; + if (current_frame == NULL) + return NULL; + else + return current_frame->f_locals; } object * getglobals() { - if (current_frame == NULL) - return NULL; - else - return current_frame->f_globals; + if (current_frame == NULL) + return NULL; + else + return current_frame->f_globals; } void printtraceback(fp) - FILE *fp; + FILE *fp; { - object *v = tb_fetch(); - if (v != NULL) { - fprintf(fp, "Stack backtrace (innermost last):\n"); - tb_print(v, fp); - DECREF(v); - } + object *v = tb_fetch(); + if (v != NULL) { + fprintf(fp, "Stack backtrace (innermost last):\n"); + tb_print(v, fp); + DECREF(v); + } } /* XXX Mixing "print ...," and direct file I/O on stdin/stdout - XXX has some bad consequences. The needspace flag should - XXX really be part of the file object. */ + XXX has some bad consequences. The needspace flag should + XXX really be part of the file object. */ static int needspace; void flushline() { - FILE *fp = sysgetfile("stdout", stdout); - if (needspace) { - fprintf(fp, "\n"); - needspace = 0; - } + FILE *fp = sysgetfile("stdout", stdout); + if (needspace) { + fprintf(fp, "\n"); + needspace = 0; + } } @@ -105,1332 +105,1332 @@ flushline() static int testbool(v) - object *v; + object *v; { - if (is_intobject(v)) - return getintvalue(v) != 0; - if (is_floatobject(v)) - return getfloatvalue(v) != 0.0; - if (v->ob_type->tp_as_sequence != NULL) - return (*v->ob_type->tp_as_sequence->sq_length)(v) != 0; - if (v->ob_type->tp_as_mapping != NULL) - return (*v->ob_type->tp_as_mapping->mp_length)(v) != 0; - if (v == None) - return 0; - /* All other objects are 'true' */ - return 1; + if (is_intobject(v)) + return getintvalue(v) != 0; + if (is_floatobject(v)) + return getfloatvalue(v) != 0.0; + if (v->ob_type->tp_as_sequence != NULL) + return (*v->ob_type->tp_as_sequence->sq_length)(v) != 0; + if (v->ob_type->tp_as_mapping != NULL) + return (*v->ob_type->tp_as_mapping->mp_length)(v) != 0; + if (v == None) + return 0; + /* All other objects are 'true' */ + return 1; } static object * add(v, w) - object *v, *w; + object *v, *w; { - if (v->ob_type->tp_as_number != NULL) - v = (*v->ob_type->tp_as_number->nb_add)(v, w); - else if (v->ob_type->tp_as_sequence != NULL) - v = (*v->ob_type->tp_as_sequence->sq_concat)(v, w); - else { - err_setstr(TypeError, "+ not supported by operands"); - return NULL; - } - return v; + if (v->ob_type->tp_as_number != NULL) + v = (*v->ob_type->tp_as_number->nb_add)(v, w); + else if (v->ob_type->tp_as_sequence != NULL) + v = (*v->ob_type->tp_as_sequence->sq_concat)(v, w); + else { + err_setstr(TypeError, "+ not supported by operands"); + return NULL; + } + return v; } static object * sub(v, w) - object *v, *w; + object *v, *w; { - if (v->ob_type->tp_as_number != NULL) - return (*v->ob_type->tp_as_number->nb_subtract)(v, w); - err_setstr(TypeError, "bad operand type(s) for -"); - return NULL; + if (v->ob_type->tp_as_number != NULL) + return (*v->ob_type->tp_as_number->nb_subtract)(v, w); + err_setstr(TypeError, "bad operand type(s) for -"); + return NULL; } static object * mul(v, w) - object *v, *w; + object *v, *w; { - typeobject *tp; - if (is_intobject(v) && w->ob_type->tp_as_sequence != NULL) { - /* int*sequence -- swap v and w */ - object *tmp = v; - v = w; - w = tmp; - } - tp = v->ob_type; - if (tp->tp_as_number != NULL) - return (*tp->tp_as_number->nb_multiply)(v, w); - if (tp->tp_as_sequence != NULL) { - if (!is_intobject(w)) { - err_setstr(TypeError, - "can't multiply sequence with non-int"); - return NULL; - } - if (tp->tp_as_sequence->sq_repeat == NULL) { - err_setstr(TypeError, "sequence does not support *"); - return NULL; - } - return (*tp->tp_as_sequence->sq_repeat) - (v, (int)getintvalue(w)); - } - err_setstr(TypeError, "bad operand type(s) for *"); - return NULL; + typeobject *tp; + if (is_intobject(v) && w->ob_type->tp_as_sequence != NULL) { + /* int*sequence -- swap v and w */ + object *tmp = v; + v = w; + w = tmp; + } + tp = v->ob_type; + if (tp->tp_as_number != NULL) + return (*tp->tp_as_number->nb_multiply)(v, w); + if (tp->tp_as_sequence != NULL) { + if (!is_intobject(w)) { + err_setstr(TypeError, + "can't multiply sequence with non-int"); + return NULL; + } + if (tp->tp_as_sequence->sq_repeat == NULL) { + err_setstr(TypeError, "sequence does not support *"); + return NULL; + } + return (*tp->tp_as_sequence->sq_repeat) + (v, (int)getintvalue(w)); + } + err_setstr(TypeError, "bad operand type(s) for *"); + return NULL; } static object * divide(v, w) - object *v, *w; + object *v, *w; { - if (v->ob_type->tp_as_number != NULL) - return (*v->ob_type->tp_as_number->nb_divide)(v, w); - err_setstr(TypeError, "bad operand type(s) for /"); - return NULL; + if (v->ob_type->tp_as_number != NULL) + return (*v->ob_type->tp_as_number->nb_divide)(v, w); + err_setstr(TypeError, "bad operand type(s) for /"); + return NULL; } static object * rem(v, w) - object *v, *w; + object *v, *w; { - if (v->ob_type->tp_as_number != NULL) - return (*v->ob_type->tp_as_number->nb_remainder)(v, w); - err_setstr(TypeError, "bad operand type(s) for %"); - return NULL; + if (v->ob_type->tp_as_number != NULL) + return (*v->ob_type->tp_as_number->nb_remainder)(v, w); + err_setstr(TypeError, "bad operand type(s) for %"); + return NULL; } static object * neg(v) - object *v; + object *v; { - if (v->ob_type->tp_as_number != NULL) - return (*v->ob_type->tp_as_number->nb_negative)(v); - err_setstr(TypeError, "bad operand type(s) for unary -"); - return NULL; + if (v->ob_type->tp_as_number != NULL) + return (*v->ob_type->tp_as_number->nb_negative)(v); + err_setstr(TypeError, "bad operand type(s) for unary -"); + return NULL; } static object * pos(v) - object *v; + object *v; { - if (v->ob_type->tp_as_number != NULL) - return (*v->ob_type->tp_as_number->nb_positive)(v); - err_setstr(TypeError, "bad operand type(s) for unary +"); - return NULL; + if (v->ob_type->tp_as_number != NULL) + return (*v->ob_type->tp_as_number->nb_positive)(v); + err_setstr(TypeError, "bad operand type(s) for unary +"); + return NULL; } static object * not(v) - object *v; + object *v; { - int outcome = testbool(v); - object *w = outcome == 0 ? True : False; - INCREF(w); - return w; + int outcome = testbool(v); + object *w = outcome == 0 ? True : False; + INCREF(w); + return w; } static object * call_builtin(func, arg) - object *func; - object *arg; + object *func; + object *arg; { - if (is_methodobject(func)) { - method meth = getmethod(func); - object *self = getself(func); - return (*meth)(self, arg); - } - if (is_classobject(func)) { - if (arg != NULL) { - err_setstr(TypeError, - "classobject() allows no arguments"); - return NULL; - } - return newclassmemberobject(func); - } - err_setstr(TypeError, "call of non-function"); - return NULL; + if (is_methodobject(func)) { + method meth = getmethod(func); + object *self = getself(func); + return (*meth)(self, arg); + } + if (is_classobject(func)) { + if (arg != NULL) { + err_setstr(TypeError, + "classobject() allows no arguments"); + return NULL; + } + return newclassmemberobject(func); + } + err_setstr(TypeError, "call of non-function"); + return NULL; } static object * call_function(func, arg) - object *func; - object *arg; + object *func; + object *arg; { - object *newarg = NULL; - object *newlocals, *newglobals; - object *co, *v; - - if (is_classmethodobject(func)) { - object *self = classmethodgetself(func); - func = classmethodgetfunc(func); - if (arg == NULL) { - arg = self; - } - else { - newarg = newtupleobject(2); - if (newarg == NULL) - return NULL; - INCREF(self); - INCREF(arg); - settupleitem(newarg, 0, self); - settupleitem(newarg, 1, arg); - arg = newarg; - } - } - else { - if (!is_funcobject(func)) { - err_setstr(TypeError, "call of non-function"); - return NULL; - } - } - - co = getfunccode(func); - if (co == NULL) { - XDECREF(newarg); - return NULL; - } - if (!is_codeobject(co)) { - fprintf(stderr, "XXX Bad code\n"); - abort(); - } - newlocals = newdictobject(); - if (newlocals == NULL) { - XDECREF(newarg); - return NULL; - } - - newglobals = getfuncglobals(func); - INCREF(newglobals); - - v = eval_code((codeobject *)co, newglobals, newlocals, arg); - - DECREF(newlocals); - DECREF(newglobals); - - XDECREF(newarg); - - return v; + object *newarg = NULL; + object *newlocals, *newglobals; + object *co, *v; + + if (is_classmethodobject(func)) { + object *self = classmethodgetself(func); + func = classmethodgetfunc(func); + if (arg == NULL) { + arg = self; + } + else { + newarg = newtupleobject(2); + if (newarg == NULL) + return NULL; + INCREF(self); + INCREF(arg); + settupleitem(newarg, 0, self); + settupleitem(newarg, 1, arg); + arg = newarg; + } + } + else { + if (!is_funcobject(func)) { + err_setstr(TypeError, "call of non-function"); + return NULL; + } + } + + co = getfunccode(func); + if (co == NULL) { + XDECREF(newarg); + return NULL; + } + if (!is_codeobject(co)) { + fprintf(stderr, "XXX Bad code\n"); + abort(); + } + newlocals = newdictobject(); + if (newlocals == NULL) { + XDECREF(newarg); + return NULL; + } + + newglobals = getfuncglobals(func); + INCREF(newglobals); + + v = eval_code((codeobject *)co, newglobals, newlocals, arg); + + DECREF(newlocals); + DECREF(newglobals); + + XDECREF(newarg); + + return v; } static object * apply_subscript(v, w) - object *v, *w; + object *v, *w; { - typeobject *tp = v->ob_type; - if (tp->tp_as_sequence == NULL && tp->tp_as_mapping == NULL) { - err_setstr(TypeError, "unsubscriptable object"); - return NULL; - } - if (tp->tp_as_sequence != NULL) { - int i; - if (!is_intobject(w)) { - err_setstr(TypeError, "sequence subscript not int"); - return NULL; - } - i = getintvalue(w); - return (*tp->tp_as_sequence->sq_item)(v, i); - } - return (*tp->tp_as_mapping->mp_subscript)(v, w); + typeobject *tp = v->ob_type; + if (tp->tp_as_sequence == NULL && tp->tp_as_mapping == NULL) { + err_setstr(TypeError, "unsubscriptable object"); + return NULL; + } + if (tp->tp_as_sequence != NULL) { + int i; + if (!is_intobject(w)) { + err_setstr(TypeError, "sequence subscript not int"); + return NULL; + } + i = getintvalue(w); + return (*tp->tp_as_sequence->sq_item)(v, i); + } + return (*tp->tp_as_mapping->mp_subscript)(v, w); } static object * loop_subscript(v, w) - object *v, *w; + object *v, *w; { - sequence_methods *sq = v->ob_type->tp_as_sequence; - int i, n; - if (sq == NULL) { - err_setstr(TypeError, "loop over non-sequence"); - return NULL; - } - i = getintvalue(w); - n = (*sq->sq_length)(v); - if (i >= n) - return NULL; /* End of loop */ - return (*sq->sq_item)(v, i); + sequence_methods *sq = v->ob_type->tp_as_sequence; + int i, n; + if (sq == NULL) { + err_setstr(TypeError, "loop over non-sequence"); + return NULL; + } + i = getintvalue(w); + n = (*sq->sq_length)(v); + if (i >= n) + return NULL; /* End of loop */ + return (*sq->sq_item)(v, i); } static int slice_index(v, isize, pi) - object *v; - int isize; - int *pi; + object *v; + int isize; + int *pi; { - if (v != NULL) { - if (!is_intobject(v)) { - err_setstr(TypeError, "slice index must be int"); - return -1; - } - *pi = getintvalue(v); - if (*pi < 0) - *pi += isize; - } - return 0; + if (v != NULL) { + if (!is_intobject(v)) { + err_setstr(TypeError, "slice index must be int"); + return -1; + } + *pi = getintvalue(v); + if (*pi < 0) + *pi += isize; + } + return 0; } static object * apply_slice(u, v, w) /* return u[v:w] */ - object *u, *v, *w; + object *u, *v, *w; { - typeobject *tp = u->ob_type; - int ilow, ihigh, isize; - if (tp->tp_as_sequence == NULL) { - err_setstr(TypeError, "only sequences can be sliced"); - return NULL; - } - ilow = 0; - isize = ihigh = (*tp->tp_as_sequence->sq_length)(u); - if (slice_index(v, isize, &ilow) != 0) - return NULL; - if (slice_index(w, isize, &ihigh) != 0) - return NULL; - return (*tp->tp_as_sequence->sq_slice)(u, ilow, ihigh); + typeobject *tp = u->ob_type; + int ilow, ihigh, isize; + if (tp->tp_as_sequence == NULL) { + err_setstr(TypeError, "only sequences can be sliced"); + return NULL; + } + ilow = 0; + isize = ihigh = (*tp->tp_as_sequence->sq_length)(u); + if (slice_index(v, isize, &ilow) != 0) + return NULL; + if (slice_index(w, isize, &ihigh) != 0) + return NULL; + return (*tp->tp_as_sequence->sq_slice)(u, ilow, ihigh); } static int assign_subscript(w, key, v) /* w[key] = v */ - object *w; - object *key; - object *v; + object *w; + object *key; + object *v; { - typeobject *tp = w->ob_type; - sequence_methods *sq; - mapping_methods *mp; - int (*func)(); - if ((sq = tp->tp_as_sequence) != NULL && - (func = sq->sq_ass_item) != NULL) { - if (!is_intobject(key)) { - err_setstr(TypeError, - "sequence subscript must be integer"); - return -1; - } - else - return (*func)(w, (int)getintvalue(key), v); - } - else if ((mp = tp->tp_as_mapping) != NULL && - (func = mp->mp_ass_subscript) != NULL) { - return (*func)(w, key, v); - } - else { - err_setstr(TypeError, - "can't assign to this subscripted object"); - return -1; - } + typeobject *tp = w->ob_type; + sequence_methods *sq; + mapping_methods *mp; + int (*func)(); + if ((sq = tp->tp_as_sequence) != NULL && + (func = sq->sq_ass_item) != NULL) { + if (!is_intobject(key)) { + err_setstr(TypeError, + "sequence subscript must be integer"); + return -1; + } + else + return (*func)(w, (int)getintvalue(key), v); + } + else if ((mp = tp->tp_as_mapping) != NULL && + (func = mp->mp_ass_subscript) != NULL) { + return (*func)(w, key, v); + } + else { + err_setstr(TypeError, + "can't assign to this subscripted object"); + return -1; + } } static int assign_slice(u, v, w, x) /* u[v:w] = x */ - object *u, *v, *w, *x; + object *u, *v, *w, *x; { - sequence_methods *sq = u->ob_type->tp_as_sequence; - int ilow, ihigh, isize; - if (sq == NULL) { - err_setstr(TypeError, "assign to slice of non-sequence"); - return -1; - } - if (sq == NULL || sq->sq_ass_slice == NULL) { - err_setstr(TypeError, "unassignable slice"); - return -1; - } - ilow = 0; - isize = ihigh = (*sq->sq_length)(u); - if (slice_index(v, isize, &ilow) != 0) - return -1; - if (slice_index(w, isize, &ihigh) != 0) - return -1; - return (*sq->sq_ass_slice)(u, ilow, ihigh, x); + sequence_methods *sq = u->ob_type->tp_as_sequence; + int ilow, ihigh, isize; + if (sq == NULL) { + err_setstr(TypeError, "assign to slice of non-sequence"); + return -1; + } + if (sq == NULL || sq->sq_ass_slice == NULL) { + err_setstr(TypeError, "unassignable slice"); + return -1; + } + ilow = 0; + isize = ihigh = (*sq->sq_length)(u); + if (slice_index(v, isize, &ilow) != 0) + return -1; + if (slice_index(w, isize, &ihigh) != 0) + return -1; + return (*sq->sq_ass_slice)(u, ilow, ihigh, x); } static int cmp_exception(err, v) - object *err, *v; + object *err, *v; { - if (is_tupleobject(v)) { - int i, n; - n = gettuplesize(v); - for (i = 0; i < n; i++) { - if (err == gettupleitem(v, i)) - return 1; - } - return 0; - } - return err == v; + if (is_tupleobject(v)) { + int i, n; + n = gettuplesize(v); + for (i = 0; i < n; i++) { + if (err == gettupleitem(v, i)) + return 1; + } + return 0; + } + return err == v; } static int cmp_member(v, w) - object *v, *w; + object *v, *w; { - int i, n, cmp; - object *x; - sequence_methods *sq; - /* Special case for char in string */ - if (is_stringobject(w)) { - register char *s, *end; - register char c; - if (!is_stringobject(v) || getstringsize(v) != 1) { - err_setstr(TypeError, - "string member test needs char left operand"); - return -1; - } - c = getstringvalue(v)[0]; - s = getstringvalue(w); - end = s + getstringsize(w); - while (s < end) { - if (c == *s++) - return 1; - } - return 0; - } - sq = w->ob_type->tp_as_sequence; - if (sq == NULL) { - err_setstr(TypeError, - "'in' or 'not in' needs sequence right argument"); - return -1; - } - n = (*sq->sq_length)(w); - for (i = 0; i < n; i++) { - x = (*sq->sq_item)(w, i); - cmp = cmpobject(v, x); - XDECREF(x); - if (cmp == 0) - return 1; - } - return 0; + int i, n, cmp; + object *x; + sequence_methods *sq; + /* Special case for char in string */ + if (is_stringobject(w)) { + register char *s, *end; + register char c; + if (!is_stringobject(v) || getstringsize(v) != 1) { + err_setstr(TypeError, + "string member test needs char left operand"); + return -1; + } + c = getstringvalue(v)[0]; + s = getstringvalue(w); + end = s + getstringsize(w); + while (s < end) { + if (c == *s++) + return 1; + } + return 0; + } + sq = w->ob_type->tp_as_sequence; + if (sq == NULL) { + err_setstr(TypeError, + "'in' or 'not in' needs sequence right argument"); + return -1; + } + n = (*sq->sq_length)(w); + for (i = 0; i < n; i++) { + x = (*sq->sq_item)(w, i); + cmp = cmpobject(v, x); + XDECREF(x); + if (cmp == 0) + return 1; + } + return 0; } static object * cmp_outcome(op, v, w) - enum cmp_op op; - register object *v; - register object *w; + enum cmp_op op; + register object *v; + register object *w; { - register int cmp; - register int res = 0; - switch (op) { - case IS: - case IS_NOT: - res = (v == w); - if (op == IS_NOT) - res = !res; - break; - case IN: - case NOT_IN: - res = cmp_member(v, w); - if (res < 0) - return NULL; - if (op == NOT_IN) - res = !res; - break; - case EXC_MATCH: - res = cmp_exception(v, w); - break; - default: - cmp = cmpobject(v, w); - switch (op) { - case LT: res = cmp < 0; break; - case LE: res = cmp <= 0; break; - case EQ: res = cmp == 0; break; - case NE: res = cmp != 0; break; - case GT: res = cmp > 0; break; - case GE: res = cmp >= 0; break; - /* XXX no default? (res is initialized to 0 though) */ - } - } - v = res ? True : False; - INCREF(v); - return v; + register int cmp; + register int res = 0; + switch (op) { + case IS: + case IS_NOT: + res = (v == w); + if (op == IS_NOT) + res = !res; + break; + case IN: + case NOT_IN: + res = cmp_member(v, w); + if (res < 0) + return NULL; + if (op == NOT_IN) + res = !res; + break; + case EXC_MATCH: + res = cmp_exception(v, w); + break; + default: + cmp = cmpobject(v, w); + switch (op) { + case LT: res = cmp < 0; break; + case LE: res = cmp <= 0; break; + case EQ: res = cmp == 0; break; + case NE: res = cmp != 0; break; + case GT: res = cmp > 0; break; + case GE: res = cmp >= 0; break; + /* XXX no default? (res is initialized to 0 though) */ + } + } + v = res ? True : False; + INCREF(v); + return v; } static int import_from(locals, v, name) - object *locals; - object *v; - char *name; + object *locals; + object *v; + char *name; { - object *w, *x; - w = getmoduledict(v); - if (name[0] == '*') { - int i; - int n = getdictsize(w); - for (i = 0; i < n; i++) { - name = getdictkey(w, i); - if (name == NULL || name[0] == '_') - continue; - x = dictlookup(w, name); - if (x == NULL) { - /* XXX can't happen? */ - err_setstr(NameError, name); - return -1; - } - if (dictinsert(locals, name, x) != 0) - return -1; - } - return 0; - } - else { - x = dictlookup(w, name); - if (x == NULL) { - err_setstr(NameError, name); - return -1; - } - else - return dictinsert(locals, name, x); - } + object *w, *x; + w = getmoduledict(v); + if (name[0] == '*') { + int i; + int n = getdictsize(w); + for (i = 0; i < n; i++) { + name = getdictkey(w, i); + if (name == NULL || name[0] == '_') + continue; + x = dictlookup(w, name); + if (x == NULL) { + /* XXX can't happen? */ + err_setstr(NameError, name); + return -1; + } + if (dictinsert(locals, name, x) != 0) + return -1; + } + return 0; + } + else { + x = dictlookup(w, name); + if (x == NULL) { + err_setstr(NameError, name); + return -1; + } + else + return dictinsert(locals, name, x); + } } static object * build_class(v, w) - object *v; /* None or tuple containing base classes */ - object *w; /* dictionary */ + object *v; /* None or tuple containing base classes */ + object *w; /* dictionary */ { - if (is_tupleobject(v)) { - int i; - for (i = gettuplesize(v); --i >= 0; ) { - object *x = gettupleitem(v, i); - if (!is_classobject(x)) { - err_setstr(TypeError, - "base is not a class object"); - return NULL; - } - } - } - else { - v = NULL; - } - if (!is_dictobject(w)) { - err_setstr(SystemError, "build_class with non-dictionary"); - return NULL; - } - return newclassobject(v, w); + if (is_tupleobject(v)) { + int i; + for (i = gettuplesize(v); --i >= 0; ) { + object *x = gettupleitem(v, i); + if (!is_classobject(x)) { + err_setstr(TypeError, + "base is not a class object"); + return NULL; + } + } + } + else { + v = NULL; + } + if (!is_dictobject(w)) { + err_setstr(SystemError, "build_class with non-dictionary"); + return NULL; + } + return newclassobject(v, w); } /* Status code for main loop (reason for stack unwind) */ enum why_code { - WHY_NOT, /* No error */ - WHY_EXCEPTION, /* Exception occurred */ - WHY_RERAISE, /* Exception re-raised by 'finally' */ - WHY_RETURN, /* 'return' statement */ - WHY_BREAK /* 'break' statement */ + WHY_NOT, /* No error */ + WHY_EXCEPTION, /* Exception occurred */ + WHY_RERAISE, /* Exception re-raised by 'finally' */ + WHY_RETURN, /* 'return' statement */ + WHY_BREAK /* 'break' statement */ }; /* Interpreter main loop */ object * eval_code(co, globals, locals, arg) - codeobject *co; - object *globals; - object *locals; - object *arg; + codeobject *co; + object *globals; + object *locals; + object *arg; { - register unsigned char *next_instr; - register int opcode; /* Current opcode */ - register int oparg; /* Current opcode argument, if any */ - register object **stack_pointer; - register enum why_code why; /* Reason for block stack unwind */ - register int err; /* Error status -- nonzero if error */ - register object *x; /* Result object -- NULL if error */ - register object *v; /* Temporary objects popped off stack */ - register object *w; - register object *u; - register object *t; - register frameobject *f; /* Current frame */ - int lineno; /* Current line number */ - object *retval; /* Return value iff why == WHY_RETURN */ - char *name; /* Name used by some instructions */ - FILE *fp; /* Used by print operations */ + register unsigned char *next_instr; + register int opcode; /* Current opcode */ + register int oparg; /* Current opcode argument, if any */ + register object **stack_pointer; + register enum why_code why; /* Reason for block stack unwind */ + register int err; /* Error status -- nonzero if error */ + register object *x; /* Result object -- NULL if error */ + register object *v; /* Temporary objects popped off stack */ + register object *w; + register object *u; + register object *t; + register frameobject *f; /* Current frame */ + int lineno; /* Current line number */ + object *retval; /* Return value iff why == WHY_RETURN */ + char *name; /* Name used by some instructions */ + FILE *fp; /* Used by print operations */ #ifdef TRACE - int trace = dictlookup(globals, "__trace__") != NULL; + int trace = dictlookup(globals, "__trace__") != NULL; #endif /* Code access macros */ -#define GETCONST(i) Getconst(f, i) -#define GETNAME(i) Getname(f, i) -#define FIRST_INSTR() (GETUSTRINGVALUE(f->f_code->co_code)) -#define INSTR_OFFSET() (next_instr - FIRST_INSTR()) -#define NEXTOP() (*next_instr++) -#define NEXTARG() (next_instr += 2, (next_instr[-1]<<8) + next_instr[-2]) -#define JUMPTO(x) (next_instr = FIRST_INSTR() + (x)) -#define JUMPBY(x) (next_instr += (x)) +#define GETCONST(i) Getconst(f, i) +#define GETNAME(i) Getname(f, i) +#define FIRST_INSTR() (GETUSTRINGVALUE(f->f_code->co_code)) +#define INSTR_OFFSET() (next_instr - FIRST_INSTR()) +#define NEXTOP() (*next_instr++) +#define NEXTARG() (next_instr += 2, (next_instr[-1]<<8) + next_instr[-2]) +#define JUMPTO(x) (next_instr = FIRST_INSTR() + (x)) +#define JUMPBY(x) (next_instr += (x)) /* Stack manipulation macros */ -#define STACK_LEVEL() (stack_pointer - f->f_valuestack) -#define EMPTY() (STACK_LEVEL() == 0) -#define TOP() (stack_pointer[-1]) -#define BASIC_PUSH(v) (*stack_pointer++ = (v)) -#define BASIC_POP() (*--stack_pointer) +#define STACK_LEVEL() (stack_pointer - f->f_valuestack) +#define EMPTY() (STACK_LEVEL() == 0) +#define TOP() (stack_pointer[-1]) +#define BASIC_PUSH(v) (*stack_pointer++ = (v)) +#define BASIC_POP() (*--stack_pointer) #ifdef TRACE -#define PUSH(v) (BASIC_PUSH(v), trace && prtrace(TOP(), "push")) -#define POP() (trace && prtrace(TOP(), "pop"), BASIC_POP()) +#define PUSH(v) (BASIC_PUSH(v), trace && prtrace(TOP(), "push")) +#define POP() (trace && prtrace(TOP(), "pop"), BASIC_POP()) #else -#define PUSH(v) BASIC_PUSH(v) -#define POP() BASIC_POP() +#define PUSH(v) BASIC_PUSH(v) +#define POP() BASIC_POP() #endif - f = newframeobject( - current_frame, /*back*/ - co, /*code*/ - globals, /*globals*/ - locals, /*locals*/ - 50, /*nvalues*/ - 20); /*nblocks*/ - if (f == NULL) - return NULL; - - current_frame = f; - - next_instr = GETUSTRINGVALUE(f->f_code->co_code); - - stack_pointer = f->f_valuestack; - - if (arg != NULL) { - INCREF(arg); - PUSH(arg); - } - - why = WHY_NOT; - err = 0; - x = None; /* Not a reference, just anything non-NULL */ - lineno = -1; - - for (;;) { - static ticker; - - /* Do periodic things */ - - if (--ticker < 0) { - ticker = 100; - if (intrcheck()) { - err_set(KeyboardInterrupt); - why = WHY_EXCEPTION; - tb_here(f, INSTR_OFFSET(), lineno); - break; - } - } - - /* Extract opcode and argument */ - - opcode = NEXTOP(); - if (HAS_ARG(opcode)) - oparg = NEXTARG(); + f = newframeobject( + current_frame, /*back*/ + co, /*code*/ + globals, /*globals*/ + locals, /*locals*/ + 50, /*nvalues*/ + 20); /*nblocks*/ + if (f == NULL) + return NULL; + + current_frame = f; + + next_instr = GETUSTRINGVALUE(f->f_code->co_code); + + stack_pointer = f->f_valuestack; + + if (arg != NULL) { + INCREF(arg); + PUSH(arg); + } + + why = WHY_NOT; + err = 0; + x = None; /* Not a reference, just anything non-NULL */ + lineno = -1; + + for (;;) { + static ticker; + + /* Do periodic things */ + + if (--ticker < 0) { + ticker = 100; + if (intrcheck()) { + err_set(KeyboardInterrupt); + why = WHY_EXCEPTION; + tb_here(f, INSTR_OFFSET(), lineno); + break; + } + } + + /* Extract opcode and argument */ + + opcode = NEXTOP(); + if (HAS_ARG(opcode)) + oparg = NEXTARG(); #ifdef TRACE - /* Instruction tracing */ - - if (trace) { - if (HAS_ARG(opcode)) { - printf("%d: %d, %d\n", - (int) (INSTR_OFFSET() - 3), - opcode, oparg); - } - else { - printf("%d: %d\n", - (int) (INSTR_OFFSET() - 1), opcode); - } - } + /* Instruction tracing */ + + if (trace) { + if (HAS_ARG(opcode)) { + printf("%d: %d, %d\n", + (int) (INSTR_OFFSET() - 3), + opcode, oparg); + } + else { + printf("%d: %d\n", + (int) (INSTR_OFFSET() - 1), opcode); + } + } #endif - /* Main switch on opcode */ - - switch (opcode) { - - /* BEWARE! - It is essential that any operation that fails sets either - x to NULL, err to nonzero, or why to anything but WHY_NOT, - and that no operation that succeeds does this! */ - - /* case STOP_CODE: this is an error! */ - - case POP_TOP: - v = POP(); - DECREF(v); - break; - - case ROT_TWO: - v = POP(); - w = POP(); - PUSH(v); - PUSH(w); - break; - - case ROT_THREE: - v = POP(); - w = POP(); - x = POP(); - PUSH(v); - PUSH(x); - PUSH(w); - break; - - case DUP_TOP: - v = TOP(); - INCREF(v); - PUSH(v); - break; - - case UNARY_POSITIVE: - v = POP(); - x = pos(v); - DECREF(v); - PUSH(x); - break; - - case UNARY_NEGATIVE: - v = POP(); - x = neg(v); - DECREF(v); - PUSH(x); - break; - - case UNARY_NOT: - v = POP(); - x = not(v); - DECREF(v); - PUSH(x); - break; - - case UNARY_CONVERT: - v = POP(); - x = reprobject(v); - DECREF(v); - PUSH(x); - break; - - case UNARY_CALL: - v = POP(); - if (is_classmethodobject(v) || is_funcobject(v)) - x = call_function(v, (object *)NULL); - else - x = call_builtin(v, (object *)NULL); - DECREF(v); - PUSH(x); - break; - - case BINARY_MULTIPLY: - w = POP(); - v = POP(); - x = mul(v, w); - DECREF(v); - DECREF(w); - PUSH(x); - break; - - case BINARY_DIVIDE: - w = POP(); - v = POP(); - x = divide(v, w); - DECREF(v); - DECREF(w); - PUSH(x); - break; - - case BINARY_MODULO: - w = POP(); - v = POP(); - x = rem(v, w); - DECREF(v); - DECREF(w); - PUSH(x); - break; - - case BINARY_ADD: - w = POP(); - v = POP(); - x = add(v, w); - DECREF(v); - DECREF(w); - PUSH(x); - break; - - case BINARY_SUBTRACT: - w = POP(); - v = POP(); - x = sub(v, w); - DECREF(v); - DECREF(w); - PUSH(x); - break; - - case BINARY_SUBSCR: - w = POP(); - v = POP(); - x = apply_subscript(v, w); - DECREF(v); - DECREF(w); - PUSH(x); - break; - - case BINARY_CALL: - w = POP(); - v = POP(); - if (is_classmethodobject(v) || is_funcobject(v)) - x = call_function(v, w); - else - x = call_builtin(v, w); - DECREF(v); - DECREF(w); - PUSH(x); - break; - - case SLICE+0: - case SLICE+1: - case SLICE+2: - case SLICE+3: - if ((opcode-SLICE) & 2) - w = POP(); - else - w = NULL; - if ((opcode-SLICE) & 1) - v = POP(); - else - v = NULL; - u = POP(); - x = apply_slice(u, v, w); - DECREF(u); - XDECREF(v); - XDECREF(w); - PUSH(x); - break; - - case STORE_SLICE+0: - case STORE_SLICE+1: - case STORE_SLICE+2: - case STORE_SLICE+3: - if ((opcode-STORE_SLICE) & 2) - w = POP(); - else - w = NULL; - if ((opcode-STORE_SLICE) & 1) - v = POP(); - else - v = NULL; - u = POP(); - t = POP(); - err = assign_slice(u, v, w, t); /* u[v:w] = t */ - DECREF(t); - DECREF(u); - XDECREF(v); - XDECREF(w); - break; - - case DELETE_SLICE+0: - case DELETE_SLICE+1: - case DELETE_SLICE+2: - case DELETE_SLICE+3: - if ((opcode-DELETE_SLICE) & 2) - w = POP(); - else - w = NULL; - if ((opcode-DELETE_SLICE) & 1) - v = POP(); - else - v = NULL; - u = POP(); - err = assign_slice(u, v, w, (object *)NULL); - /* del u[v:w] */ - DECREF(u); - XDECREF(v); - XDECREF(w); - break; - - case STORE_SUBSCR: - w = POP(); - v = POP(); - u = POP(); - /* v[w] = u */ - err = assign_subscript(v, w, u); - DECREF(u); - DECREF(v); - DECREF(w); - break; - - case DELETE_SUBSCR: - w = POP(); - v = POP(); - /* del v[w] */ - err = assign_subscript(v, w, (object *)NULL); - DECREF(v); - DECREF(w); - break; - - case PRINT_EXPR: - v = POP(); - fp = sysgetfile("stdout", stdout); - /* Print value except if procedure result */ - if (v != None) { - flushline(); - printobject(v, fp, 0); - fprintf(fp, "\n"); - } - DECREF(v); - break; - - case PRINT_ITEM: - v = POP(); - fp = sysgetfile("stdout", stdout); - if (needspace) - fprintf(fp, " "); - if (is_stringobject(v)) { - char *s = getstringvalue(v); - int len = getstringsize(v); - fwrite(s, 1, len, fp); - if (len > 0 && s[len-1] == '\n') - needspace = 0; - else - needspace = 1; - } - else { - printobject(v, fp, 0); - needspace = 1; - } - DECREF(v); - break; - - case PRINT_NEWLINE: - fp = sysgetfile("stdout", stdout); - fprintf(fp, "\n"); - needspace = 0; - break; - - case BREAK_LOOP: - why = WHY_BREAK; - break; - - case RAISE_EXCEPTION: - v = POP(); - w = POP(); - if (!is_stringobject(w)) - err_setstr(TypeError, - "exceptions must be strings"); - else - err_setval(w, v); - DECREF(v); - DECREF(w); - why = WHY_EXCEPTION; - break; - - case LOAD_LOCALS: - v = f->f_locals; - INCREF(v); - PUSH(v); - break; - - case RETURN_VALUE: - retval = POP(); - why = WHY_RETURN; - break; - - case REQUIRE_ARGS: - if (EMPTY()) { - err_setstr(TypeError, - "function expects argument(s)"); - why = WHY_EXCEPTION; - } - break; - - case REFUSE_ARGS: - if (!EMPTY()) { - err_setstr(TypeError, - "function expects no argument(s)"); - why = WHY_EXCEPTION; - } - break; - - case BUILD_FUNCTION: - v = POP(); - x = newfuncobject(v, f->f_globals); - DECREF(v); - PUSH(x); - break; - - case POP_BLOCK: - { - block *b = pop_block(f); - while (STACK_LEVEL() > b->b_level) { - v = POP(); - DECREF(v); - } - } - break; - - case END_FINALLY: - v = POP(); - if (is_intobject(v)) { - why = (enum why_code) getintvalue(v); - if (why == WHY_RETURN) - retval = POP(); - } - else if (is_stringobject(v)) { - w = POP(); - err_setval(v, w); - DECREF(w); - w = POP(); - tb_store(w); - DECREF(w); - why = WHY_RERAISE; - } - else if (v != None) { - err_setstr(SystemError, - "'finally' pops bad exception"); - why = WHY_EXCEPTION; - } - DECREF(v); - break; - - case BUILD_CLASS: - w = POP(); - v = POP(); - x = build_class(v, w); - PUSH(x); - DECREF(v); - DECREF(w); - break; - - case STORE_NAME: - name = GETNAME(oparg); - v = POP(); - err = dictinsert(f->f_locals, name, v); - DECREF(v); - break; - - case DELETE_NAME: - name = GETNAME(oparg); - if ((err = dictremove(f->f_locals, name)) != 0) - err_setstr(NameError, name); - break; - - case UNPACK_TUPLE: - v = POP(); - if (!is_tupleobject(v)) { - err_setstr(TypeError, "unpack non-tuple"); - why = WHY_EXCEPTION; - } - else if (gettuplesize(v) != oparg) { - err_setstr(RuntimeError, - "unpack tuple of wrong size"); - why = WHY_EXCEPTION; - } - else { - for (; --oparg >= 0; ) { - w = gettupleitem(v, oparg); - INCREF(w); - PUSH(w); - } - } - DECREF(v); - break; - - case UNPACK_LIST: - v = POP(); - if (!is_listobject(v)) { - err_setstr(TypeError, "unpack non-list"); - why = WHY_EXCEPTION; - } - else if (getlistsize(v) != oparg) { - err_setstr(RuntimeError, - "unpack list of wrong size"); - why = WHY_EXCEPTION; - } - else { - for (; --oparg >= 0; ) { - w = getlistitem(v, oparg); - INCREF(w); - PUSH(w); - } - } - DECREF(v); - break; - - case STORE_ATTR: - name = GETNAME(oparg); - v = POP(); - u = POP(); - err = setattr(v, name, u); /* v.name = u */ - DECREF(v); - DECREF(u); - break; - - case DELETE_ATTR: - name = GETNAME(oparg); - v = POP(); - err = setattr(v, name, (object *)NULL); - /* del v.name */ - DECREF(v); - break; - - case LOAD_CONST: - x = GETCONST(oparg); - INCREF(x); - PUSH(x); - break; - - case LOAD_NAME: - name = GETNAME(oparg); - x = dictlookup(f->f_locals, name); - if (x == NULL) { - x = dictlookup(f->f_globals, name); - if (x == NULL) - x = getbuiltin(name); - } - if (x == NULL) - err_setstr(NameError, name); - else - INCREF(x); - PUSH(x); - break; - - case BUILD_TUPLE: - x = newtupleobject(oparg); - if (x != NULL) { - for (; --oparg >= 0;) { - w = POP(); - err = settupleitem(x, oparg, w); - if (err != 0) - break; - } - PUSH(x); - } - break; - - case BUILD_LIST: - x = newlistobject(oparg); - if (x != NULL) { - for (; --oparg >= 0;) { - w = POP(); - err = setlistitem(x, oparg, w); - if (err != 0) - break; - } - PUSH(x); - } - break; - - case BUILD_MAP: - x = newdictobject(); - PUSH(x); - break; - - case LOAD_ATTR: - name = GETNAME(oparg); - v = POP(); - x = getattr(v, name); - DECREF(v); - PUSH(x); - break; - - case COMPARE_OP: - w = POP(); - v = POP(); - x = cmp_outcome((enum cmp_op)oparg, v, w); - DECREF(v); - DECREF(w); - PUSH(x); - break; - - case IMPORT_NAME: - name = GETNAME(oparg); - x = import_module(name); - XINCREF(x); - PUSH(x); - break; - - case IMPORT_FROM: - name = GETNAME(oparg); - v = TOP(); - err = import_from(f->f_locals, v, name); - break; - - case JUMP_FORWARD: - JUMPBY(oparg); - break; - - case JUMP_IF_FALSE: - if (!testbool(TOP())) - JUMPBY(oparg); - break; - - case JUMP_IF_TRUE: - if (testbool(TOP())) - JUMPBY(oparg); - break; - - case JUMP_ABSOLUTE: - JUMPTO(oparg); - break; - - case FOR_LOOP: - /* for v in s: ... - On entry: stack contains s, i. - On exit: stack contains s, i+1, s[i]; - but if loop exhausted: - s, i are popped, and we jump */ - w = POP(); /* Loop index */ - v = POP(); /* Sequence object */ - u = loop_subscript(v, w); - if (u != NULL) { - PUSH(v); - x = newintobject(getintvalue(w)+1); - PUSH(x); - DECREF(w); - PUSH(u); - } - else { - DECREF(v); - DECREF(w); - /* A NULL can mean "s exhausted" - but also an error: */ - if (err_occurred()) - why = WHY_EXCEPTION; - else - JUMPBY(oparg); - } - break; - - case SETUP_LOOP: - case SETUP_EXCEPT: - case SETUP_FINALLY: - setup_block(f, opcode, INSTR_OFFSET() + oparg, - STACK_LEVEL()); - break; - - case SET_LINENO: + /* Main switch on opcode */ + + switch (opcode) { + + /* BEWARE! + It is essential that any operation that fails sets either + x to NULL, err to nonzero, or why to anything but WHY_NOT, + and that no operation that succeeds does this! */ + + /* case STOP_CODE: this is an error! */ + + case POP_TOP: + v = POP(); + DECREF(v); + break; + + case ROT_TWO: + v = POP(); + w = POP(); + PUSH(v); + PUSH(w); + break; + + case ROT_THREE: + v = POP(); + w = POP(); + x = POP(); + PUSH(v); + PUSH(x); + PUSH(w); + break; + + case DUP_TOP: + v = TOP(); + INCREF(v); + PUSH(v); + break; + + case UNARY_POSITIVE: + v = POP(); + x = pos(v); + DECREF(v); + PUSH(x); + break; + + case UNARY_NEGATIVE: + v = POP(); + x = neg(v); + DECREF(v); + PUSH(x); + break; + + case UNARY_NOT: + v = POP(); + x = not(v); + DECREF(v); + PUSH(x); + break; + + case UNARY_CONVERT: + v = POP(); + x = reprobject(v); + DECREF(v); + PUSH(x); + break; + + case UNARY_CALL: + v = POP(); + if (is_classmethodobject(v) || is_funcobject(v)) + x = call_function(v, (object *)NULL); + else + x = call_builtin(v, (object *)NULL); + DECREF(v); + PUSH(x); + break; + + case BINARY_MULTIPLY: + w = POP(); + v = POP(); + x = mul(v, w); + DECREF(v); + DECREF(w); + PUSH(x); + break; + + case BINARY_DIVIDE: + w = POP(); + v = POP(); + x = divide(v, w); + DECREF(v); + DECREF(w); + PUSH(x); + break; + + case BINARY_MODULO: + w = POP(); + v = POP(); + x = rem(v, w); + DECREF(v); + DECREF(w); + PUSH(x); + break; + + case BINARY_ADD: + w = POP(); + v = POP(); + x = add(v, w); + DECREF(v); + DECREF(w); + PUSH(x); + break; + + case BINARY_SUBTRACT: + w = POP(); + v = POP(); + x = sub(v, w); + DECREF(v); + DECREF(w); + PUSH(x); + break; + + case BINARY_SUBSCR: + w = POP(); + v = POP(); + x = apply_subscript(v, w); + DECREF(v); + DECREF(w); + PUSH(x); + break; + + case BINARY_CALL: + w = POP(); + v = POP(); + if (is_classmethodobject(v) || is_funcobject(v)) + x = call_function(v, w); + else + x = call_builtin(v, w); + DECREF(v); + DECREF(w); + PUSH(x); + break; + + case SLICE+0: + case SLICE+1: + case SLICE+2: + case SLICE+3: + if ((opcode-SLICE) & 2) + w = POP(); + else + w = NULL; + if ((opcode-SLICE) & 1) + v = POP(); + else + v = NULL; + u = POP(); + x = apply_slice(u, v, w); + DECREF(u); + XDECREF(v); + XDECREF(w); + PUSH(x); + break; + + case STORE_SLICE+0: + case STORE_SLICE+1: + case STORE_SLICE+2: + case STORE_SLICE+3: + if ((opcode-STORE_SLICE) & 2) + w = POP(); + else + w = NULL; + if ((opcode-STORE_SLICE) & 1) + v = POP(); + else + v = NULL; + u = POP(); + t = POP(); + err = assign_slice(u, v, w, t); /* u[v:w] = t */ + DECREF(t); + DECREF(u); + XDECREF(v); + XDECREF(w); + break; + + case DELETE_SLICE+0: + case DELETE_SLICE+1: + case DELETE_SLICE+2: + case DELETE_SLICE+3: + if ((opcode-DELETE_SLICE) & 2) + w = POP(); + else + w = NULL; + if ((opcode-DELETE_SLICE) & 1) + v = POP(); + else + v = NULL; + u = POP(); + err = assign_slice(u, v, w, (object *)NULL); + /* del u[v:w] */ + DECREF(u); + XDECREF(v); + XDECREF(w); + break; + + case STORE_SUBSCR: + w = POP(); + v = POP(); + u = POP(); + /* v[w] = u */ + err = assign_subscript(v, w, u); + DECREF(u); + DECREF(v); + DECREF(w); + break; + + case DELETE_SUBSCR: + w = POP(); + v = POP(); + /* del v[w] */ + err = assign_subscript(v, w, (object *)NULL); + DECREF(v); + DECREF(w); + break; + + case PRINT_EXPR: + v = POP(); + fp = sysgetfile("stdout", stdout); + /* Print value except if procedure result */ + if (v != None) { + flushline(); + printobject(v, fp, 0); + fprintf(fp, "\n"); + } + DECREF(v); + break; + + case PRINT_ITEM: + v = POP(); + fp = sysgetfile("stdout", stdout); + if (needspace) + fprintf(fp, " "); + if (is_stringobject(v)) { + char *s = getstringvalue(v); + int len = getstringsize(v); + fwrite(s, 1, len, fp); + if (len > 0 && s[len-1] == '\n') + needspace = 0; + else + needspace = 1; + } + else { + printobject(v, fp, 0); + needspace = 1; + } + DECREF(v); + break; + + case PRINT_NEWLINE: + fp = sysgetfile("stdout", stdout); + fprintf(fp, "\n"); + needspace = 0; + break; + + case BREAK_LOOP: + why = WHY_BREAK; + break; + + case RAISE_EXCEPTION: + v = POP(); + w = POP(); + if (!is_stringobject(w)) + err_setstr(TypeError, + "exceptions must be strings"); + else + err_setval(w, v); + DECREF(v); + DECREF(w); + why = WHY_EXCEPTION; + break; + + case LOAD_LOCALS: + v = f->f_locals; + INCREF(v); + PUSH(v); + break; + + case RETURN_VALUE: + retval = POP(); + why = WHY_RETURN; + break; + + case REQUIRE_ARGS: + if (EMPTY()) { + err_setstr(TypeError, + "function expects argument(s)"); + why = WHY_EXCEPTION; + } + break; + + case REFUSE_ARGS: + if (!EMPTY()) { + err_setstr(TypeError, + "function expects no argument(s)"); + why = WHY_EXCEPTION; + } + break; + + case BUILD_FUNCTION: + v = POP(); + x = newfuncobject(v, f->f_globals); + DECREF(v); + PUSH(x); + break; + + case POP_BLOCK: + { + block *b = pop_block(f); + while (STACK_LEVEL() > b->b_level) { + v = POP(); + DECREF(v); + } + } + break; + + case END_FINALLY: + v = POP(); + if (is_intobject(v)) { + why = (enum why_code) getintvalue(v); + if (why == WHY_RETURN) + retval = POP(); + } + else if (is_stringobject(v)) { + w = POP(); + err_setval(v, w); + DECREF(w); + w = POP(); + tb_store(w); + DECREF(w); + why = WHY_RERAISE; + } + else if (v != None) { + err_setstr(SystemError, + "'finally' pops bad exception"); + why = WHY_EXCEPTION; + } + DECREF(v); + break; + + case BUILD_CLASS: + w = POP(); + v = POP(); + x = build_class(v, w); + PUSH(x); + DECREF(v); + DECREF(w); + break; + + case STORE_NAME: + name = GETNAME(oparg); + v = POP(); + err = dictinsert(f->f_locals, name, v); + DECREF(v); + break; + + case DELETE_NAME: + name = GETNAME(oparg); + if ((err = dictremove(f->f_locals, name)) != 0) + err_setstr(NameError, name); + break; + + case UNPACK_TUPLE: + v = POP(); + if (!is_tupleobject(v)) { + err_setstr(TypeError, "unpack non-tuple"); + why = WHY_EXCEPTION; + } + else if (gettuplesize(v) != oparg) { + err_setstr(RuntimeError, + "unpack tuple of wrong size"); + why = WHY_EXCEPTION; + } + else { + for (; --oparg >= 0; ) { + w = gettupleitem(v, oparg); + INCREF(w); + PUSH(w); + } + } + DECREF(v); + break; + + case UNPACK_LIST: + v = POP(); + if (!is_listobject(v)) { + err_setstr(TypeError, "unpack non-list"); + why = WHY_EXCEPTION; + } + else if (getlistsize(v) != oparg) { + err_setstr(RuntimeError, + "unpack list of wrong size"); + why = WHY_EXCEPTION; + } + else { + for (; --oparg >= 0; ) { + w = getlistitem(v, oparg); + INCREF(w); + PUSH(w); + } + } + DECREF(v); + break; + + case STORE_ATTR: + name = GETNAME(oparg); + v = POP(); + u = POP(); + err = setattr(v, name, u); /* v.name = u */ + DECREF(v); + DECREF(u); + break; + + case DELETE_ATTR: + name = GETNAME(oparg); + v = POP(); + err = setattr(v, name, (object *)NULL); + /* del v.name */ + DECREF(v); + break; + + case LOAD_CONST: + x = GETCONST(oparg); + INCREF(x); + PUSH(x); + break; + + case LOAD_NAME: + name = GETNAME(oparg); + x = dictlookup(f->f_locals, name); + if (x == NULL) { + x = dictlookup(f->f_globals, name); + if (x == NULL) + x = getbuiltin(name); + } + if (x == NULL) + err_setstr(NameError, name); + else + INCREF(x); + PUSH(x); + break; + + case BUILD_TUPLE: + x = newtupleobject(oparg); + if (x != NULL) { + for (; --oparg >= 0;) { + w = POP(); + err = settupleitem(x, oparg, w); + if (err != 0) + break; + } + PUSH(x); + } + break; + + case BUILD_LIST: + x = newlistobject(oparg); + if (x != NULL) { + for (; --oparg >= 0;) { + w = POP(); + err = setlistitem(x, oparg, w); + if (err != 0) + break; + } + PUSH(x); + } + break; + + case BUILD_MAP: + x = newdictobject(); + PUSH(x); + break; + + case LOAD_ATTR: + name = GETNAME(oparg); + v = POP(); + x = getattr(v, name); + DECREF(v); + PUSH(x); + break; + + case COMPARE_OP: + w = POP(); + v = POP(); + x = cmp_outcome((enum cmp_op)oparg, v, w); + DECREF(v); + DECREF(w); + PUSH(x); + break; + + case IMPORT_NAME: + name = GETNAME(oparg); + x = import_module(name); + XINCREF(x); + PUSH(x); + break; + + case IMPORT_FROM: + name = GETNAME(oparg); + v = TOP(); + err = import_from(f->f_locals, v, name); + break; + + case JUMP_FORWARD: + JUMPBY(oparg); + break; + + case JUMP_IF_FALSE: + if (!testbool(TOP())) + JUMPBY(oparg); + break; + + case JUMP_IF_TRUE: + if (testbool(TOP())) + JUMPBY(oparg); + break; + + case JUMP_ABSOLUTE: + JUMPTO(oparg); + break; + + case FOR_LOOP: + /* for v in s: ... + On entry: stack contains s, i. + On exit: stack contains s, i+1, s[i]; + but if loop exhausted: + s, i are popped, and we jump */ + w = POP(); /* Loop index */ + v = POP(); /* Sequence object */ + u = loop_subscript(v, w); + if (u != NULL) { + PUSH(v); + x = newintobject(getintvalue(w)+1); + PUSH(x); + DECREF(w); + PUSH(u); + } + else { + DECREF(v); + DECREF(w); + /* A NULL can mean "s exhausted" + but also an error: */ + if (err_occurred()) + why = WHY_EXCEPTION; + else + JUMPBY(oparg); + } + break; + + case SETUP_LOOP: + case SETUP_EXCEPT: + case SETUP_FINALLY: + setup_block(f, opcode, INSTR_OFFSET() + oparg, + STACK_LEVEL()); + break; + + case SET_LINENO: #ifdef TRACE - if (trace) - printf("--- Line %d ---\n", oparg); + if (trace) + printf("--- Line %d ---\n", oparg); #endif - lineno = oparg; - break; - - default: - fprintf(stderr, - "XXX lineno: %d, opcode: %d\n", - lineno, opcode); - err_setstr(SystemError, "eval_code: unknown opcode"); - why = WHY_EXCEPTION; - break; - - } /* switch */ - - - /* Quickly continue if no error occurred */ - - if (why == WHY_NOT) { - if (err == 0 && x != NULL) - continue; /* Normal, fast path */ - why = WHY_EXCEPTION; - x = None; - err = 0; - } + lineno = oparg; + break; + + default: + fprintf(stderr, + "XXX lineno: %d, opcode: %d\n", + lineno, opcode); + err_setstr(SystemError, "eval_code: unknown opcode"); + why = WHY_EXCEPTION; + break; + + } /* switch */ + + + /* Quickly continue if no error occurred */ + + if (why == WHY_NOT) { + if (err == 0 && x != NULL) + continue; /* Normal, fast path */ + why = WHY_EXCEPTION; + x = None; + err = 0; + } #ifndef NDEBUG - /* Double-check exception status */ - - if (why == WHY_EXCEPTION || why == WHY_RERAISE) { - if (!err_occurred()) { - fprintf(stderr, "XXX ghost error\n"); - err_setstr(SystemError, "ghost error"); - why = WHY_EXCEPTION; - } - } - else { - if (err_occurred()) { - fprintf(stderr, "XXX undetected error\n"); - why = WHY_EXCEPTION; - } - } + /* Double-check exception status */ + + if (why == WHY_EXCEPTION || why == WHY_RERAISE) { + if (!err_occurred()) { + fprintf(stderr, "XXX ghost error\n"); + err_setstr(SystemError, "ghost error"); + why = WHY_EXCEPTION; + } + } + else { + if (err_occurred()) { + fprintf(stderr, "XXX undetected error\n"); + why = WHY_EXCEPTION; + } + } #endif - /* Log traceback info if this is a real exception */ - - if (why == WHY_EXCEPTION) { - int lasti = INSTR_OFFSET() - 1; - if (HAS_ARG(opcode)) - lasti -= 2; - tb_here(f, lasti, lineno); - } - - /* For the rest, treat WHY_RERAISE as WHY_EXCEPTION */ - - if (why == WHY_RERAISE) - why = WHY_EXCEPTION; - - /* Unwind stacks if a (pseudo) exception occurred */ - - while (why != WHY_NOT && f->f_iblock > 0) { - block *b = pop_block(f); - while (STACK_LEVEL() > b->b_level) { - v = POP(); - XDECREF(v); - } - if (b->b_type == SETUP_LOOP && why == WHY_BREAK) { - why = WHY_NOT; - JUMPTO(b->b_handler); - break; - } - if (b->b_type == SETUP_FINALLY || - b->b_type == SETUP_EXCEPT && - why == WHY_EXCEPTION) { - if (why == WHY_EXCEPTION) { - object *exc, *val; - err_get(&exc, &val); - if (val == NULL) { - val = None; - INCREF(val); - } - v = tb_fetch(); - /* Make the raw exception data - available to the handler, - so a program can emulate the - Python main loop. Don't do - this for 'finally'. */ - if (b->b_type == SETUP_EXCEPT) { + /* Log traceback info if this is a real exception */ + + if (why == WHY_EXCEPTION) { + int lasti = INSTR_OFFSET() - 1; + if (HAS_ARG(opcode)) + lasti -= 2; + tb_here(f, lasti, lineno); + } + + /* For the rest, treat WHY_RERAISE as WHY_EXCEPTION */ + + if (why == WHY_RERAISE) + why = WHY_EXCEPTION; + + /* Unwind stacks if a (pseudo) exception occurred */ + + while (why != WHY_NOT && f->f_iblock > 0) { + block *b = pop_block(f); + while (STACK_LEVEL() > b->b_level) { + v = POP(); + XDECREF(v); + } + if (b->b_type == SETUP_LOOP && why == WHY_BREAK) { + why = WHY_NOT; + JUMPTO(b->b_handler); + break; + } + if (b->b_type == SETUP_FINALLY || + b->b_type == SETUP_EXCEPT && + why == WHY_EXCEPTION) { + if (why == WHY_EXCEPTION) { + object *exc, *val; + err_get(&exc, &val); + if (val == NULL) { + val = None; + INCREF(val); + } + v = tb_fetch(); + /* Make the raw exception data + available to the handler, + so a program can emulate the + Python main loop. Don't do + this for 'finally'. */ + if (b->b_type == SETUP_EXCEPT) { #if 0 /* Oops, this breaks too many things */ - sysset("exc_traceback", v); + sysset("exc_traceback", v); #endif - sysset("exc_value", val); - sysset("exc_type", exc); - err_clear(); - } - PUSH(v); - PUSH(val); - PUSH(exc); - } - else { - if (why == WHY_RETURN) - PUSH(retval); - v = newintobject((long)why); - PUSH(v); - } - why = WHY_NOT; - JUMPTO(b->b_handler); - break; - } - } /* unwind stack */ - - /* End the loop if we still have an error (or return) */ - - if (why != WHY_NOT) - break; - - } /* main loop */ - - /* Pop remaining stack entries */ - - while (!EMPTY()) { - v = POP(); - XDECREF(v); - } - - /* Restore previous frame and release the current one */ - - current_frame = f->f_back; - DECREF(f); - - if (why == WHY_RETURN) - return retval; - else - return NULL; + sysset("exc_value", val); + sysset("exc_type", exc); + err_clear(); + } + PUSH(v); + PUSH(val); + PUSH(exc); + } + else { + if (why == WHY_RETURN) + PUSH(retval); + v = newintobject((long)why); + PUSH(v); + } + why = WHY_NOT; + JUMPTO(b->b_handler); + break; + } + } /* unwind stack */ + + /* End the loop if we still have an error (or return) */ + + if (why != WHY_NOT) + break; + + } /* main loop */ + + /* Pop remaining stack entries */ + + while (!EMPTY()) { + v = POP(); + XDECREF(v); + } + + /* Restore previous frame and release the current one */ + + current_frame = f->f_back; + DECREF(f); + + if (why == WHY_RETURN) + return retval; + else + return NULL; } diff --git a/src/ceval.h b/src/ceval.h index 7f57738..efa438b 100644 --- a/src/ceval.h +++ b/src/ceval.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -12,14 +12,14 @@ import sys # Function to print to stderr # def err(args): - savestdout = sys.stdout - try: - sys.stdout = sys.stderr - for i in args: - print i, - print - finally: - sys.stdout = savestdout + savestdout = sys.stdout + try: + sys.stdout = sys.stderr + for i in args: + print i, + print + finally: + sys.stdout = savestdout # The set of digits that form a number @@ -32,20 +32,20 @@ digits = '0123456789' # If no number is found, returns '' and the original string. # def getnum(s): - n = '' - while s and s[0] in digits: - n = n + s[0] - s = s[1:] - return n, s + n = '' + while s and s[0] in digits: + n = n + s[0] + s = s[1:] + return n, s # Function to check if a string is a number # def isnum(s): - if not s: return 0 - for c in s: - if not c in digits: return 0 - return 1 + if not s: return 0 + for c in s: + if not c in digits: return 0 + return 1 # Allowed function return types @@ -59,26 +59,26 @@ arg_types = ['char', 'string', 'short', 'float', 'long', 'double'] # Need to classify arguments as follows -# simple input variable -# simple output variable -# input array -# output array -# input giving size of some array +# simple input variable +# simple output variable +# input array +# output array +# input giving size of some array # # Array dimensions can be specified as follows -# constant -# argN -# constant * argN -# retval -# constant * retval +# constant +# argN +# constant * argN +# retval +# constant * retval # # The dimensions given as constants * something are really # arrays of points where points are 2- 3- or 4-tuples # # We have to consider three lists: -# python input arguments -# C stub arguments (in & out) -# python output arguments (really return values) +# python input arguments +# C stub arguments (in & out) +# python output arguments (really return values) # # There is a mapping from python input arguments to the input arguments # of the C stub, and a further mapping from C stub arguments to the @@ -96,67 +96,67 @@ arg_error = 'bad arg' # Return type, mode, factor, rest of subscript; factor and rest may be empty. # def checkarg(type, arg): - # - # Turn "char *x" into "string x". - # - if type = 'char' and arg[0] = '*': - type = 'string' - arg = arg[1:] - # - # Check that the type is supported. - # - if type not in arg_types: - raise arg_error, ('bad type', type) - # - # Split it in the mode (first character) and the rest. - # - mode, rest = arg[:1], arg[1:] - # - # The mode must be 's' for send (= input) or 'r' for return argument. - # - if mode not in ('r', 's'): - raise arg_error, ('bad arg mode', mode) - # - # Is it a simple argument: if so, we are done. - # - if not rest: - return type, mode, '', '' - # - # Not a simple argument; must be an array. - # The 'rest' must be a subscript enclosed in [ and ]. - # The subscript must be one of the following forms, - # otherwise we don't handle it (where N is a number): - # N - # argN - # retval - # N*argN - # N*retval - # - if rest[:1] <> '[' or rest[-1:] <> ']': - raise arg_error, ('subscript expected', rest) - sub = rest[1:-1] - # - # Is there a leading number? - # - num, sub = getnum(sub) - if num: - # There is a leading number - if not sub: - # The subscript is just a number - return type, mode, num, '' - if sub[:1] = '*': - # There is a factor prefix - sub = sub[1:] - else: - raise arg_error, ('\'*\' expected', sub) - if sub = 'retval': - # size is retval -- must be a reply argument - if mode <> 'r': - raise arg_error, ('non-r mode with [retval]', mode) - elif sub[:3] <> 'arg' or not isnum(sub[3:]): - raise arg_error, ('bad subscript', sub) - # - return type, mode, num, sub + # + # Turn "char *x" into "string x". + # + if type = 'char' and arg[0] = '*': + type = 'string' + arg = arg[1:] + # + # Check that the type is supported. + # + if type not in arg_types: + raise arg_error, ('bad type', type) + # + # Split it in the mode (first character) and the rest. + # + mode, rest = arg[:1], arg[1:] + # + # The mode must be 's' for send (= input) or 'r' for return argument. + # + if mode not in ('r', 's'): + raise arg_error, ('bad arg mode', mode) + # + # Is it a simple argument: if so, we are done. + # + if not rest: + return type, mode, '', '' + # + # Not a simple argument; must be an array. + # The 'rest' must be a subscript enclosed in [ and ]. + # The subscript must be one of the following forms, + # otherwise we don't handle it (where N is a number): + # N + # argN + # retval + # N*argN + # N*retval + # + if rest[:1] <> '[' or rest[-1:] <> ']': + raise arg_error, ('subscript expected', rest) + sub = rest[1:-1] + # + # Is there a leading number? + # + num, sub = getnum(sub) + if num: + # There is a leading number + if not sub: + # The subscript is just a number + return type, mode, num, '' + if sub[:1] = '*': + # There is a factor prefix + sub = sub[1:] + else: + raise arg_error, ('\'*\' expected', sub) + if sub = 'retval': + # size is retval -- must be a reply argument + if mode <> 'r': + raise arg_error, ('non-r mode with [retval]', mode) + elif sub[:3] <> 'arg' or not isnum(sub[3:]): + raise arg_error, ('bad subscript', sub) + # + return type, mode, num, sub # List of functions for which we have generated stubs @@ -168,208 +168,208 @@ functions = [] # information build by successive calls to checkarg() # def generate(type, func, database): - # - # Check that we can handle this case: - # no variable size reply arrays yet - # - n_in_args = 0 - n_out_args = 0 - # - for a_type, a_mode, a_factor, a_sub in database: - if a_mode = 's': - n_in_args = n_in_args + 1 - elif a_mode = 'r': - n_out_args = n_out_args + 1 - else: - # Can't happen - raise arg_error, ('bad a_mode', a_mode) - if (a_mode = 'r' and a_sub) or a_sub = 'retval': - e = 'Function', func, 'too complicated:' - err(e + (a_type, a_mode, a_factor, a_sub)) - print '/* XXX Too complicated to generate code for */' - return - # - functions.append(func) - # - # Stub header - # - print - print 'static object *' - print 'gl_' + func + '(self, args)' - print '\tobject *self;' - print '\tobject *args;' - print '{' - # - # Declare return value if any - # - if type <> 'void': - print '\t' + type, 'retval;' - # - # Declare arguments - # - for i in range(len(database)): - a_type, a_mode, a_factor, a_sub = database[i] - print '\t' + a_type, - if a_sub: - print '*', - print 'arg' + `i+1`, - if a_factor and not a_sub: - print '[', a_factor, ']', - print ';' - # - # Find input arguments derived from array sizes - # - for i in range(len(database)): - a_type, a_mode, a_factor, a_sub = database[i] - if a_mode = 's' and a_sub[:3] = 'arg' and isnum(a_sub[3:]): - # Sending a variable-length array - n = eval(a_sub[3:]) - if 1 <= n <= len(database): - b_type, b_mode, b_factor, b_sub = database[n-1] - if b_mode = 's': - database[n-1] = b_type, 'i', a_factor, `i` - n_in_args = n_in_args - 1 - # - # Assign argument positions in the Python argument list - # - in_pos = [] - i_in = 0 - for i in range(len(database)): - a_type, a_mode, a_factor, a_sub = database[i] - if a_mode = 's': - in_pos.append(i_in) - i_in = i_in + 1 - else: - in_pos.append(-1) - # - # Get input arguments - # - for i in range(len(database)): - a_type, a_mode, a_factor, a_sub = database[i] - if a_mode = 'i': - # - # Implicit argument; - # a_factor is divisor if present, - # a_sub indicates which arg (`database index`) - # - j = eval(a_sub) - print '\tif', - print '(!geti' + a_type + 'arraysize(args,', - print `n_in_args` + ',', - print `in_pos[j]` + ',', - print '&arg' + `i+1` + '))' - print '\t\treturn NULL;' - if a_factor: - print '\targ' + `i+1`, - print '= arg' + `i+1`, - print '/', a_factor + ';' - elif a_mode = 's': - if a_sub: # Allocate memory for varsize array - print '\tif ((arg' + `i+1`, '=', - print 'NEW(' + a_type + ',', - if a_factor: print a_factor, '*', - print a_sub, ')) == NULL)' - print '\t\treturn err_nomem();' - print '\tif', - if a_factor or a_sub: # Get a fixed-size array array - print '(!geti' + a_type + 'array(args,', - print `n_in_args` + ',', - print `in_pos[i]` + ',', - if a_factor: print a_factor, - if a_factor and a_sub: print '*', - if a_sub: print a_sub, - print ', arg' + `i+1` + '))' - else: # Get a simple variable - print '(!geti' + a_type + 'arg(args,', - print `n_in_args` + ',', - print `in_pos[i]` + ',', - print '&arg' + `i+1` + '))' - print '\t\treturn NULL;' - # - # Begin of function call - # - if type <> 'void': - print '\tretval =', func + '(', - else: - print '\t' + func + '(', - # - # Argument list - # - for i in range(len(database)): - if i > 0: print ',', - a_type, a_mode, a_factor, a_sub = database[i] - if a_mode = 'r' and not a_factor: - print '&', - print 'arg' + `i+1`, - # - # End of function call - # - print ');' - # - # Free varsize arrays - # - for i in range(len(database)): - a_type, a_mode, a_factor, a_sub = database[i] - if a_mode = 's' and a_sub: - print '\tDEL(arg' + `i+1` + ');' - # - # Return - # - if n_out_args: - # - # Multiple return values -- construct a tuple - # - if type <> 'void': - n_out_args = n_out_args + 1 - if n_out_args = 1: - for i in range(len(database)): - a_type, a_mode, a_factor, a_sub = database[i] - if a_mode = 'r': - break - else: - raise arg_error, 'expected r arg not found' - print '\treturn', - print mkobject(a_type, 'arg' + `i+1`) + ';' - else: - print '\t{ object *v = newtupleobject(', - print n_out_args, ');' - print '\t if (v == NULL) return NULL;' - i_out = 0 - if type <> 'void': - print '\t settupleitem(v,', - print `i_out` + ',', - print mkobject(type, 'retval') + ');' - i_out = i_out + 1 - for i in range(len(database)): - a_type, a_mode, a_factor, a_sub = database[i] - if a_mode = 'r': - print '\t settupleitem(v,', - print `i_out` + ',', - s = mkobject(a_type, 'arg' + `i+1`) - print s + ');' - i_out = i_out + 1 - print '\t return v;' - print '\t}' - else: - # - # Simple function return - # Return None or return value - # - if type = 'void': - print '\tINCREF(None);' - print '\treturn None;' - else: - print '\treturn', mkobject(type, 'retval') + ';' - # - # Stub body closing brace - # - print '}' + # + # Check that we can handle this case: + # no variable size reply arrays yet + # + n_in_args = 0 + n_out_args = 0 + # + for a_type, a_mode, a_factor, a_sub in database: + if a_mode = 's': + n_in_args = n_in_args + 1 + elif a_mode = 'r': + n_out_args = n_out_args + 1 + else: + # Can't happen + raise arg_error, ('bad a_mode', a_mode) + if (a_mode = 'r' and a_sub) or a_sub = 'retval': + e = 'Function', func, 'too complicated:' + err(e + (a_type, a_mode, a_factor, a_sub)) + print '/* XXX Too complicated to generate code for */' + return + # + functions.append(func) + # + # Stub header + # + print + print 'static object *' + print 'gl_' + func + '(self, args)' + print '\tobject *self;' + print '\tobject *args;' + print '{' + # + # Declare return value if any + # + if type <> 'void': + print '\t' + type, 'retval;' + # + # Declare arguments + # + for i in range(len(database)): + a_type, a_mode, a_factor, a_sub = database[i] + print '\t' + a_type, + if a_sub: + print '*', + print 'arg' + `i+1`, + if a_factor and not a_sub: + print '[', a_factor, ']', + print ';' + # + # Find input arguments derived from array sizes + # + for i in range(len(database)): + a_type, a_mode, a_factor, a_sub = database[i] + if a_mode = 's' and a_sub[:3] = 'arg' and isnum(a_sub[3:]): + # Sending a variable-length array + n = eval(a_sub[3:]) + if 1 <= n <= len(database): + b_type, b_mode, b_factor, b_sub = database[n-1] + if b_mode = 's': + database[n-1] = b_type, 'i', a_factor, `i` + n_in_args = n_in_args - 1 + # + # Assign argument positions in the Python argument list + # + in_pos = [] + i_in = 0 + for i in range(len(database)): + a_type, a_mode, a_factor, a_sub = database[i] + if a_mode = 's': + in_pos.append(i_in) + i_in = i_in + 1 + else: + in_pos.append(-1) + # + # Get input arguments + # + for i in range(len(database)): + a_type, a_mode, a_factor, a_sub = database[i] + if a_mode = 'i': + # + # Implicit argument; + # a_factor is divisor if present, + # a_sub indicates which arg (`database index`) + # + j = eval(a_sub) + print '\tif', + print '(!geti' + a_type + 'arraysize(args,', + print `n_in_args` + ',', + print `in_pos[j]` + ',', + print '&arg' + `i+1` + '))' + print '\t\treturn NULL;' + if a_factor: + print '\targ' + `i+1`, + print '= arg' + `i+1`, + print '/', a_factor + ';' + elif a_mode = 's': + if a_sub: # Allocate memory for varsize array + print '\tif ((arg' + `i+1`, '=', + print 'NEW(' + a_type + ',', + if a_factor: print a_factor, '*', + print a_sub, ')) == NULL)' + print '\t\treturn err_nomem();' + print '\tif', + if a_factor or a_sub: # Get a fixed-size array array + print '(!geti' + a_type + 'array(args,', + print `n_in_args` + ',', + print `in_pos[i]` + ',', + if a_factor: print a_factor, + if a_factor and a_sub: print '*', + if a_sub: print a_sub, + print ', arg' + `i+1` + '))' + else: # Get a simple variable + print '(!geti' + a_type + 'arg(args,', + print `n_in_args` + ',', + print `in_pos[i]` + ',', + print '&arg' + `i+1` + '))' + print '\t\treturn NULL;' + # + # Begin of function call + # + if type <> 'void': + print '\tretval =', func + '(', + else: + print '\t' + func + '(', + # + # Argument list + # + for i in range(len(database)): + if i > 0: print ',', + a_type, a_mode, a_factor, a_sub = database[i] + if a_mode = 'r' and not a_factor: + print '&', + print 'arg' + `i+1`, + # + # End of function call + # + print ');' + # + # Free varsize arrays + # + for i in range(len(database)): + a_type, a_mode, a_factor, a_sub = database[i] + if a_mode = 's' and a_sub: + print '\tDEL(arg' + `i+1` + ');' + # + # Return + # + if n_out_args: + # + # Multiple return values -- construct a tuple + # + if type <> 'void': + n_out_args = n_out_args + 1 + if n_out_args = 1: + for i in range(len(database)): + a_type, a_mode, a_factor, a_sub = database[i] + if a_mode = 'r': + break + else: + raise arg_error, 'expected r arg not found' + print '\treturn', + print mkobject(a_type, 'arg' + `i+1`) + ';' + else: + print '\t{ object *v = newtupleobject(', + print n_out_args, ');' + print '\t if (v == NULL) return NULL;' + i_out = 0 + if type <> 'void': + print '\t settupleitem(v,', + print `i_out` + ',', + print mkobject(type, 'retval') + ');' + i_out = i_out + 1 + for i in range(len(database)): + a_type, a_mode, a_factor, a_sub = database[i] + if a_mode = 'r': + print '\t settupleitem(v,', + print `i_out` + ',', + s = mkobject(a_type, 'arg' + `i+1`) + print s + ');' + i_out = i_out + 1 + print '\t return v;' + print '\t}' + else: + # + # Simple function return + # Return None or return value + # + if type = 'void': + print '\tINCREF(None);' + print '\treturn None;' + else: + print '\treturn', mkobject(type, 'retval') + ';' + # + # Stub body closing brace + # + print '}' # Subroutine to return a function call to mknew<type>object(<arg>) # def mkobject(type, arg): - return 'mknew' + type + 'object(' + arg + ')' + return 'mknew' + type + 'object(' + arg + ')' # Input line number @@ -377,8 +377,8 @@ lno = 0 # Input is divided in two parts, separated by a line containing '%%'. -# <part1> -- literally copied to stdout -# <part2> -- stub definitions +# <part1> -- literally copied to stdout +# <part2> -- stub definitions # Variable indicating the current input part. # @@ -387,68 +387,68 @@ part = 1 # Main loop over the input # while 1: - try: - line = raw_input() - except EOFError: - break - # - lno = lno+1 - words = string.split(line) - # - if part = 1: - # - # In part 1, copy everything literally - # except look for a line of just '%%' - # - if words = ['%%']: - part = part + 1 - else: - # - # Look for names of manually written - # stubs: a single percent followed by the name - # of the function in Python. - # The stub name is derived by prefixing 'gl_'. - # - if words and words[0][0] = '%': - func = words[0][1:] - if (not func) and words[1:]: - func = words[1] - if func: - functions.append(func) - else: - print line - elif not words: - pass # skip empty line - elif words[0] = '#include': - print line - elif words[0][:1] = '#': - pass # ignore comment - elif words[0] not in return_types: - err('Line', lno, ': bad return type :', words[0]) - elif len(words) < 2: - err('Line', lno, ': no funcname :', line) - else: - if len(words) % 2 <> 0: - err('Line', lno, ': odd argument list :', words[2:]) - else: - database = [] - try: - for i in range(2, len(words), 2): - x = checkarg(words[i], words[i+1]) - database.append(x) - print - print '/*', - for w in words: print w, - print '*/' - generate(words[0], words[1], database) - except arg_error, msg: - err('Line', lno, ':', msg) + try: + line = raw_input() + except EOFError: + break + # + lno = lno+1 + words = string.split(line) + # + if part = 1: + # + # In part 1, copy everything literally + # except look for a line of just '%%' + # + if words = ['%%']: + part = part + 1 + else: + # + # Look for names of manually written + # stubs: a single percent followed by the name + # of the function in Python. + # The stub name is derived by prefixing 'gl_'. + # + if words and words[0][0] = '%': + func = words[0][1:] + if (not func) and words[1:]: + func = words[1] + if func: + functions.append(func) + else: + print line + elif not words: + pass # skip empty line + elif words[0] = '#include': + print line + elif words[0][:1] = '#': + pass # ignore comment + elif words[0] not in return_types: + err('Line', lno, ': bad return type :', words[0]) + elif len(words) < 2: + err('Line', lno, ': no funcname :', line) + else: + if len(words) % 2 <> 0: + err('Line', lno, ': odd argument list :', words[2:]) + else: + database = [] + try: + for i in range(2, len(words), 2): + x = checkarg(words[i], words[i+1]) + database.append(x) + print + print '/*', + for w in words: print w, + print '*/' + generate(words[0], words[1], database) + except arg_error, msg: + err('Line', lno, ':', msg) print print 'static struct methodlist gl_methods[] = {' for func in functions: - print '\t{"' + func + '", gl_' + func + '},' + print '\t{"' + func + '", gl_' + func + '},' print '\t{NULL, NULL} /* Sentinel */' print '};' print diff --git a/src/cgensupport.c b/src/cgensupport.c index 91adb2a..8d20f02 100644 --- a/src/cgensupport.c +++ b/src/cgensupport.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -45,349 +45,349 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. object * mknewcharobject(c) - int c; + int c; { - char ch[1]; - ch[0] = c; - return newsizedstringobject(ch, 1); + char ch[1]; + ch[0] = c; + return newsizedstringobject(ch, 1); } /* Functions to extract arguments. - These needs to know the total number of arguments supplied, - since the argument list is a tuple only of there is more than - one argument. */ + These needs to know the total number of arguments supplied, + since the argument list is a tuple only of there is more than + one argument. */ int getiobjectarg(args, nargs, i, p_arg) - register object *args; - int nargs, i; - object **p_arg; + register object *args; + int nargs, i; + object **p_arg; { - if (nargs != 1) { - if (args == NULL || !is_tupleobject(args) || - nargs != gettuplesize(args) || - i < 0 || i >= nargs) { - return err_badarg(); - } - else { - args = gettupleitem(args, i); - } - } - if (args == NULL) { - return err_badarg(); - } - *p_arg = args; - return 1; + if (nargs != 1) { + if (args == NULL || !is_tupleobject(args) || + nargs != gettuplesize(args) || + i < 0 || i >= nargs) { + return err_badarg(); + } + else { + args = gettupleitem(args, i); + } + } + if (args == NULL) { + return err_badarg(); + } + *p_arg = args; + return 1; } int getilongarg(args, nargs, i, p_arg) - register object *args; - int nargs, i; - long *p_arg; + register object *args; + int nargs, i; + long *p_arg; { - if (nargs != 1) { - if (args == NULL || !is_tupleobject(args) || - nargs != gettuplesize(args) || - i < 0 || i >= nargs) { - return err_badarg(); - } - args = gettupleitem(args, i); - } - if (args == NULL || !is_intobject(args)) { - return err_badarg(); - } - *p_arg = getintvalue(args); - return 1; + if (nargs != 1) { + if (args == NULL || !is_tupleobject(args) || + nargs != gettuplesize(args) || + i < 0 || i >= nargs) { + return err_badarg(); + } + args = gettupleitem(args, i); + } + if (args == NULL || !is_intobject(args)) { + return err_badarg(); + } + *p_arg = getintvalue(args); + return 1; } int getishortarg(args, nargs, i, p_arg) - register object *args; - int nargs, i; - short *p_arg; + register object *args; + int nargs, i; + short *p_arg; { - long x; - if (!getilongarg(args, nargs, i, &x)) - return 0; - *p_arg = x; - return 1; + long x; + if (!getilongarg(args, nargs, i, &x)) + return 0; + *p_arg = x; + return 1; } static int extractdouble(v, p_arg) - register object *v; - double *p_arg; + register object *v; + double *p_arg; { - if (v == NULL) { - /* Fall through to error return at end of function */ - } - else if (is_floatobject(v)) { - *p_arg = GETFLOATVALUE((floatobject *)v); - return 1; - } - else if (is_intobject(v)) { - *p_arg = GETINTVALUE((intobject *)v); - return 1; - } - return err_badarg(); + if (v == NULL) { + /* Fall through to error return at end of function */ + } + else if (is_floatobject(v)) { + *p_arg = GETFLOATVALUE((floatobject *)v); + return 1; + } + else if (is_intobject(v)) { + *p_arg = GETINTVALUE((intobject *)v); + return 1; + } + return err_badarg(); } static int extractfloat(v, p_arg) - register object *v; - float *p_arg; + register object *v; + float *p_arg; { - if (v == NULL) { - /* Fall through to error return at end of function */ - } - else if (is_floatobject(v)) { - *p_arg = GETFLOATVALUE((floatobject *)v); - return 1; - } - else if (is_intobject(v)) { - *p_arg = GETINTVALUE((intobject *)v); - return 1; - } - return err_badarg(); + if (v == NULL) { + /* Fall through to error return at end of function */ + } + else if (is_floatobject(v)) { + *p_arg = GETFLOATVALUE((floatobject *)v); + return 1; + } + else if (is_intobject(v)) { + *p_arg = GETINTVALUE((intobject *)v); + return 1; + } + return err_badarg(); } int getifloatarg(args, nargs, i, p_arg) - register object *args; - int nargs, i; - float *p_arg; + register object *args; + int nargs, i; + float *p_arg; { - object *v; - float x; - if (!getiobjectarg(args, nargs, i, &v)) - return 0; - if (!extractfloat(v, &x)) - return 0; - *p_arg = x; - return 1; + object *v; + float x; + if (!getiobjectarg(args, nargs, i, &v)) + return 0; + if (!extractfloat(v, &x)) + return 0; + *p_arg = x; + return 1; } int getistringarg(args, nargs, i, p_arg) - object *args; - int nargs, i; - string *p_arg; + object *args; + int nargs, i; + string *p_arg; { - object *v; - if (!getiobjectarg(args, nargs, i, &v)) - return NULL; - if (!is_stringobject(v)) { - return err_badarg(); - } - *p_arg = getstringvalue(v); - return 1; + object *v; + if (!getiobjectarg(args, nargs, i, &v)) + return NULL; + if (!is_stringobject(v)) { + return err_badarg(); + } + *p_arg = getstringvalue(v); + return 1; } int getichararg(args, nargs, i, p_arg) - object *args; - int nargs, i; - char *p_arg; + object *args; + int nargs, i; + char *p_arg; { - string x; - if (!getistringarg(args, nargs, i, &x)) - return 0; - if (x[0] == '\0' || x[1] != '\0') { - /* Not exactly one char */ - return err_badarg(); - } - *p_arg = x[0]; - return 1; + string x; + if (!getistringarg(args, nargs, i, &x)) + return 0; + if (x[0] == '\0' || x[1] != '\0') { + /* Not exactly one char */ + return err_badarg(); + } + *p_arg = x[0]; + return 1; } int getilongarraysize(args, nargs, i, p_arg) - object *args; - int nargs, i; - long *p_arg; + object *args; + int nargs, i; + long *p_arg; { - object *v; - if (!getiobjectarg(args, nargs, i, &v)) - return 0; - if (is_tupleobject(v)) { - *p_arg = gettuplesize(v); - return 1; - } - if (is_listobject(v)) { - *p_arg = getlistsize(v); - return 1; - } - return err_badarg(); + object *v; + if (!getiobjectarg(args, nargs, i, &v)) + return 0; + if (is_tupleobject(v)) { + *p_arg = gettuplesize(v); + return 1; + } + if (is_listobject(v)) { + *p_arg = getlistsize(v); + return 1; + } + return err_badarg(); } int getishortarraysize(args, nargs, i, p_arg) - object *args; - int nargs, i; - short *p_arg; + object *args; + int nargs, i; + short *p_arg; { - long x; - if (!getilongarraysize(args, nargs, i, &x)) - return 0; - *p_arg = x; - return 1; + long x; + if (!getilongarraysize(args, nargs, i, &x)) + return 0; + *p_arg = x; + return 1; } -/* XXX The following four are too similar. Should share more code. */ +/* XXX The following four are too similar. Should share more code. */ int getilongarray(args, nargs, i, n, p_arg) - object *args; - int nargs, i; - int n; - long *p_arg; /* [n] */ + object *args; + int nargs, i; + int n; + long *p_arg; /* [n] */ { - object *v, *w; - if (!getiobjectarg(args, nargs, i, &v)) - return 0; - if (is_tupleobject(v)) { - if (gettuplesize(v) != n) { - return err_badarg(); - } - for (i = 0; i < n; i++) { - w = gettupleitem(v, i); - if (!is_intobject(w)) { - return err_badarg(); - } - p_arg[i] = getintvalue(w); - } - return 1; - } - else if (is_listobject(v)) { - if (getlistsize(v) != n) { - return err_badarg(); - } - for (i = 0; i < n; i++) { - w = getlistitem(v, i); - if (!is_intobject(w)) { - return err_badarg(); - } - p_arg[i] = getintvalue(w); - } - return 1; - } - else { - return err_badarg(); - } + object *v, *w; + if (!getiobjectarg(args, nargs, i, &v)) + return 0; + if (is_tupleobject(v)) { + if (gettuplesize(v) != n) { + return err_badarg(); + } + for (i = 0; i < n; i++) { + w = gettupleitem(v, i); + if (!is_intobject(w)) { + return err_badarg(); + } + p_arg[i] = getintvalue(w); + } + return 1; + } + else if (is_listobject(v)) { + if (getlistsize(v) != n) { + return err_badarg(); + } + for (i = 0; i < n; i++) { + w = getlistitem(v, i); + if (!is_intobject(w)) { + return err_badarg(); + } + p_arg[i] = getintvalue(w); + } + return 1; + } + else { + return err_badarg(); + } } int getishortarray(args, nargs, i, n, p_arg) - object *args; - int nargs, i; - int n; - short *p_arg; /* [n] */ + object *args; + int nargs, i; + int n; + short *p_arg; /* [n] */ { - object *v, *w; - if (!getiobjectarg(args, nargs, i, &v)) - return 0; - if (is_tupleobject(v)) { - if (gettuplesize(v) != n) { - return err_badarg(); - } - for (i = 0; i < n; i++) { - w = gettupleitem(v, i); - if (!is_intobject(w)) { - return err_badarg(); - } - p_arg[i] = getintvalue(w); - } - return 1; - } - else if (is_listobject(v)) { - if (getlistsize(v) != n) { - return err_badarg(); - } - for (i = 0; i < n; i++) { - w = getlistitem(v, i); - if (!is_intobject(w)) { - return err_badarg(); - } - p_arg[i] = getintvalue(w); - } - return 1; - } - else { - return err_badarg(); - } + object *v, *w; + if (!getiobjectarg(args, nargs, i, &v)) + return 0; + if (is_tupleobject(v)) { + if (gettuplesize(v) != n) { + return err_badarg(); + } + for (i = 0; i < n; i++) { + w = gettupleitem(v, i); + if (!is_intobject(w)) { + return err_badarg(); + } + p_arg[i] = getintvalue(w); + } + return 1; + } + else if (is_listobject(v)) { + if (getlistsize(v) != n) { + return err_badarg(); + } + for (i = 0; i < n; i++) { + w = getlistitem(v, i); + if (!is_intobject(w)) { + return err_badarg(); + } + p_arg[i] = getintvalue(w); + } + return 1; + } + else { + return err_badarg(); + } } int getidoublearray(args, nargs, i, n, p_arg) - object *args; - int nargs, i; - int n; - double *p_arg; /* [n] */ + object *args; + int nargs, i; + int n; + double *p_arg; /* [n] */ { - object *v, *w; - if (!getiobjectarg(args, nargs, i, &v)) - return 0; - if (is_tupleobject(v)) { - if (gettuplesize(v) != n) { - return err_badarg(); - } - for (i = 0; i < n; i++) { - w = gettupleitem(v, i); - if (!extractdouble(w, &p_arg[i])) - return 0; - } - return 1; - } - else if (is_listobject(v)) { - if (getlistsize(v) != n) { - return err_badarg(); - } - for (i = 0; i < n; i++) { - w = getlistitem(v, i); - if (!extractdouble(w, &p_arg[i])) - return 0; - } - return 1; - } - else { - return err_badarg(); - } + object *v, *w; + if (!getiobjectarg(args, nargs, i, &v)) + return 0; + if (is_tupleobject(v)) { + if (gettuplesize(v) != n) { + return err_badarg(); + } + for (i = 0; i < n; i++) { + w = gettupleitem(v, i); + if (!extractdouble(w, &p_arg[i])) + return 0; + } + return 1; + } + else if (is_listobject(v)) { + if (getlistsize(v) != n) { + return err_badarg(); + } + for (i = 0; i < n; i++) { + w = getlistitem(v, i); + if (!extractdouble(w, &p_arg[i])) + return 0; + } + return 1; + } + else { + return err_badarg(); + } } int getifloatarray(args, nargs, i, n, p_arg) - object *args; - int nargs, i; - int n; - float *p_arg; /* [n] */ + object *args; + int nargs, i; + int n; + float *p_arg; /* [n] */ { - object *v, *w; - if (!getiobjectarg(args, nargs, i, &v)) - return 0; - if (is_tupleobject(v)) { - if (gettuplesize(v) != n) { - return err_badarg(); - } - for (i = 0; i < n; i++) { - w = gettupleitem(v, i); - if (!extractfloat(w, &p_arg[i])) - return 0; - } - return 1; - } - else if (is_listobject(v)) { - if (getlistsize(v) != n) { - return err_badarg(); - } - for (i = 0; i < n; i++) { - w = getlistitem(v, i); - if (!extractfloat(w, &p_arg[i])) - return 0; - } - return 1; - } - else { - return err_badarg(); - } + object *v, *w; + if (!getiobjectarg(args, nargs, i, &v)) + return 0; + if (is_tupleobject(v)) { + if (gettuplesize(v) != n) { + return err_badarg(); + } + for (i = 0; i < n; i++) { + w = gettupleitem(v, i); + if (!extractfloat(w, &p_arg[i])) + return 0; + } + return 1; + } + else if (is_listobject(v)) { + if (getlistsize(v) != n) { + return err_badarg(); + } + for (i = 0; i < n; i++) { + w = getlistitem(v, i); + if (!extractfloat(w, &p_arg[i])) + return 0; + } + return 1; + } + else { + return err_badarg(); + } } diff --git a/src/cgensupport.h b/src/cgensupport.h index a056f5d..859fa99 100644 --- a/src/cgensupport.h +++ b/src/cgensupport.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. diff --git a/src/classobject.c b/src/classobject.c index fc32889..44cbd68 100644 --- a/src/classobject.c +++ b/src/classobject.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -29,176 +29,176 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include "structmember.h" typedef struct { - OB_HEAD - object *cl_bases; /* A tuple */ - object *cl_methods; /* A dictionary */ + OB_HEAD + object *cl_bases; /* A tuple */ + object *cl_methods; /* A dictionary */ } classobject; object * newclassobject(bases, methods) - object *bases; /* NULL or tuple of classobjects! */ - object *methods; + object *bases; /* NULL or tuple of classobjects! */ + object *methods; { - classobject *op; - op = NEWOBJ(classobject, &Classtype); - if (op == NULL) - return NULL; - if (bases != NULL) - INCREF(bases); - op->cl_bases = bases; - INCREF(methods); - op->cl_methods = methods; - return (object *) op; + classobject *op; + op = NEWOBJ(classobject, &Classtype); + if (op == NULL) + return NULL; + if (bases != NULL) + INCREF(bases); + op->cl_bases = bases; + INCREF(methods); + op->cl_methods = methods; + return (object *) op; } /* Class methods */ static void class_dealloc(op) - classobject *op; + classobject *op; { - int i; - if (op->cl_bases != NULL) - DECREF(op->cl_bases); - DECREF(op->cl_methods); - free((ANY *)op); + int i; + if (op->cl_bases != NULL) + DECREF(op->cl_bases); + DECREF(op->cl_methods); + free((ANY *)op); } static object * class_getattr(op, name) - register classobject *op; - register char *name; + register classobject *op; + register char *name; { - register object *v; - v = dictlookup(op->cl_methods, name); - if (v != NULL) { - INCREF(v); - return v; - } - if (op->cl_bases != NULL) { - int n = gettuplesize(op->cl_bases); - int i; - for (i = 0; i < n; i++) { - v = class_getattr(gettupleitem(op->cl_bases, i), name); - if (v != NULL) - return v; - err_clear(); - } - } - err_setstr(NameError, name); - return NULL; + register object *v; + v = dictlookup(op->cl_methods, name); + if (v != NULL) { + INCREF(v); + return v; + } + if (op->cl_bases != NULL) { + int n = gettuplesize(op->cl_bases); + int i; + for (i = 0; i < n; i++) { + v = class_getattr(gettupleitem(op->cl_bases, i), name); + if (v != NULL) + return v; + err_clear(); + } + } + err_setstr(NameError, name); + return NULL; } typeobject Classtype = { - OB_HEAD_INIT(&Typetype) - 0, - "class", - sizeof(classobject), - 0, - class_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - class_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ + OB_HEAD_INIT(&Typetype) + 0, + "class", + sizeof(classobject), + 0, + class_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + class_getattr, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ }; /* We're not done yet: next, we define class member objects... */ typedef struct { - OB_HEAD - classobject *cm_class; /* The class object */ - object *cm_attr; /* A dictionary */ + OB_HEAD + classobject *cm_class; /* The class object */ + object *cm_attr; /* A dictionary */ } classmemberobject; object * newclassmemberobject(class) - register object *class; + register object *class; { - register classmemberobject *cm; - if (!is_classobject(class)) { - err_badcall(); - return NULL; - } - cm = NEWOBJ(classmemberobject, &Classmembertype); - if (cm == NULL) - return NULL; - INCREF(class); - cm->cm_class = (classobject *)class; - cm->cm_attr = newdictobject(); - if (cm->cm_attr == NULL) { - DECREF(cm); - return NULL; - } - return (object *)cm; + register classmemberobject *cm; + if (!is_classobject(class)) { + err_badcall(); + return NULL; + } + cm = NEWOBJ(classmemberobject, &Classmembertype); + if (cm == NULL) + return NULL; + INCREF(class); + cm->cm_class = (classobject *)class; + cm->cm_attr = newdictobject(); + if (cm->cm_attr == NULL) { + DECREF(cm); + return NULL; + } + return (object *)cm; } /* Class member methods */ static void classmember_dealloc(cm) - register classmemberobject *cm; + register classmemberobject *cm; { - DECREF(cm->cm_class); - if (cm->cm_attr != NULL) - DECREF(cm->cm_attr); - free((ANY *)cm); + DECREF(cm->cm_class); + if (cm->cm_attr != NULL) + DECREF(cm->cm_attr); + free((ANY *)cm); } static object * classmember_getattr(cm, name) - register classmemberobject *cm; - register char *name; + register classmemberobject *cm; + register char *name; { - register object *v = dictlookup(cm->cm_attr, name); - if (v != NULL) { - INCREF(v); - return v; - } - v = class_getattr(cm->cm_class, name); - if (v == NULL) - return v; /* class_getattr() has set the error */ - if (is_funcobject(v)) { - object *w = newclassmethodobject(v, (object *)cm); - DECREF(v); - return w; - } - DECREF(v); - err_setstr(NameError, name); - return NULL; + register object *v = dictlookup(cm->cm_attr, name); + if (v != NULL) { + INCREF(v); + return v; + } + v = class_getattr(cm->cm_class, name); + if (v == NULL) + return v; /* class_getattr() has set the error */ + if (is_funcobject(v)) { + object *w = newclassmethodobject(v, (object *)cm); + DECREF(v); + return w; + } + DECREF(v); + err_setstr(NameError, name); + return NULL; } static int classmember_setattr(cm, name, v) - classmemberobject *cm; - char *name; - object *v; + classmemberobject *cm; + char *name; + object *v; { - if (v == NULL) - return dictremove(cm->cm_attr, name); - else - return dictinsert(cm->cm_attr, name, v); + if (v == NULL) + return dictremove(cm->cm_attr, name); + else + return dictinsert(cm->cm_attr, name, v); } typeobject Classmembertype = { - OB_HEAD_INIT(&Typetype) - 0, - "class member", - sizeof(classmemberobject), - 0, - classmember_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - classmember_getattr, /*tp_getattr*/ - classmember_setattr, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ + OB_HEAD_INIT(&Typetype) + 0, + "class member", + sizeof(classmemberobject), + 0, + classmember_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + classmember_getattr, /*tp_getattr*/ + classmember_setattr, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ }; @@ -206,51 +206,51 @@ typeobject Classmembertype = { /* (Really methods of class members) */ typedef struct { - OB_HEAD - object *cm_func; /* The method function */ - object *cm_self; /* The object to which this applies */ + OB_HEAD + object *cm_func; /* The method function */ + object *cm_self; /* The object to which this applies */ } classmethodobject; object * newclassmethodobject(func, self) - object *func; - object *self; + object *func; + object *self; { - register classmethodobject *cm; - if (!is_funcobject(func)) { - err_badcall(); - return NULL; - } - cm = NEWOBJ(classmethodobject, &Classmethodtype); - if (cm == NULL) - return NULL; - INCREF(func); - cm->cm_func = func; - INCREF(self); - cm->cm_self = self; - return (object *)cm; + register classmethodobject *cm; + if (!is_funcobject(func)) { + err_badcall(); + return NULL; + } + cm = NEWOBJ(classmethodobject, &Classmethodtype); + if (cm == NULL) + return NULL; + INCREF(func); + cm->cm_func = func; + INCREF(self); + cm->cm_self = self; + return (object *)cm; } object * classmethodgetfunc(cm) - register object *cm; + register object *cm; { - if (!is_classmethodobject(cm)) { - err_badcall(); - return NULL; - } - return ((classmethodobject *)cm)->cm_func; + if (!is_classmethodobject(cm)) { + err_badcall(); + return NULL; + } + return ((classmethodobject *)cm)->cm_func; } object * classmethodgetself(cm) - register object *cm; + register object *cm; { - if (!is_classmethodobject(cm)) { - err_badcall(); - return NULL; - } - return ((classmethodobject *)cm)->cm_self; + if (!is_classmethodobject(cm)) { + err_badcall(); + return NULL; + } + return ((classmethodobject *)cm)->cm_self; } /* Class method methods */ @@ -258,41 +258,41 @@ classmethodgetself(cm) #define OFF(x) offsetof(classmethodobject, x) static struct memberlist classmethod_memberlist[] = { - {"cm_func", T_OBJECT, OFF(cm_func)}, - {"cm_self", T_OBJECT, OFF(cm_self)}, - {NULL} /* Sentinel */ + {"cm_func", T_OBJECT, OFF(cm_func)}, + {"cm_self", T_OBJECT, OFF(cm_self)}, + {NULL} /* Sentinel */ }; static object * classmethod_getattr(cm, name) - register classmethodobject *cm; - char *name; + register classmethodobject *cm; + char *name; { - return getmember((char *)cm, classmethod_memberlist, name); + return getmember((char *)cm, classmethod_memberlist, name); } static void classmethod_dealloc(cm) - register classmethodobject *cm; + register classmethodobject *cm; { - DECREF(cm->cm_func); - DECREF(cm->cm_self); - free((ANY *)cm); + DECREF(cm->cm_func); + DECREF(cm->cm_self); + free((ANY *)cm); } typeobject Classmethodtype = { - OB_HEAD_INIT(&Typetype) - 0, - "class method", - sizeof(classmethodobject), - 0, - classmethod_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - classmethod_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ + OB_HEAD_INIT(&Typetype) + 0, + "class method", + sizeof(classmethodobject), + 0, + classmethod_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + classmethod_getattr, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ }; diff --git a/src/classobject.h b/src/classobject.h index 49db837..6370827 100644 --- a/src/classobject.h +++ b/src/classobject.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -27,7 +27,7 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* Classes are really hacked in at the last moment. It should be possible to use other object types as base classes, -but currently it isn't. We'll see if we can fix that later, sigh... +but currently it isn't. We'll see if we can fix that later, sigh... */ extern typeobject Classtype, Classmembertype, Classmethodtype; diff --git a/src/compile.c b/src/compile.c index 7904dba..1c3f2fa 100644 --- a/src/compile.c +++ b/src/compile.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -25,9 +25,9 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* Compile an expression node to intermediate code */ /* XXX TO DO: - XXX Compute maximum needed stack sizes while compiling - XXX Generate simple jump for break/return outside 'try...finally' - XXX Include function name in code (and module names?) + XXX Compute maximum needed stack sizes while compiling + XXX Generate simple jump for break/return outside 'try...finally' + XXX Include function name in code (and module names?) */ #include "allobjects.h" @@ -44,102 +44,102 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #define OFF(x) offsetof(codeobject, x) static struct memberlist code_memberlist[] = { - {"co_code", T_OBJECT, OFF(co_code)}, - {"co_consts", T_OBJECT, OFF(co_consts)}, - {"co_names", T_OBJECT, OFF(co_names)}, - {"co_filename", T_OBJECT, OFF(co_filename)}, - {NULL} /* Sentinel */ + {"co_code", T_OBJECT, OFF(co_code)}, + {"co_consts", T_OBJECT, OFF(co_consts)}, + {"co_names", T_OBJECT, OFF(co_names)}, + {"co_filename", T_OBJECT, OFF(co_filename)}, + {NULL} /* Sentinel */ }; static object * code_getattr(co, name) - codeobject *co; - char *name; + codeobject *co; + char *name; { - return getmember((char *)co, code_memberlist, name); + return getmember((char *)co, code_memberlist, name); } static void code_dealloc(co) - codeobject *co; + codeobject *co; { - XDECREF(co->co_code); - XDECREF(co->co_consts); - XDECREF(co->co_names); - XDECREF(co->co_filename); - DEL(co); + XDECREF(co->co_code); + XDECREF(co->co_consts); + XDECREF(co->co_names); + XDECREF(co->co_filename); + DEL(co); } typeobject Codetype = { - OB_HEAD_INIT(&Typetype) - 0, - "code", - sizeof(codeobject), - 0, - code_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - code_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ + OB_HEAD_INIT(&Typetype) + 0, + "code", + sizeof(codeobject), + 0, + code_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + code_getattr, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ }; static codeobject *newcodeobject PROTO((object *, object *, object *, char *)); static codeobject * newcodeobject(code, consts, names, filename) - object *code; - object *consts; - object *names; - char *filename; + object *code; + object *consts; + object *names; + char *filename; { - codeobject *co; - int i; - /* Check argument types */ - if (code == NULL || !is_stringobject(code) || - consts == NULL || !is_listobject(consts) || - names == NULL || !is_listobject(names)) { - err_badcall(); - return NULL; - } - /* Make sure the list of names contains only strings */ - for (i = getlistsize(names); --i >= 0; ) { - object *v = getlistitem(names, i); - if (v == NULL || !is_stringobject(v)) { - err_badcall(); - return NULL; - } - } - co = NEWOBJ(codeobject, &Codetype); - if (co != NULL) { - INCREF(code); - co->co_code = (stringobject *)code; - INCREF(consts); - co->co_consts = consts; - INCREF(names); - co->co_names = names; - if ((co->co_filename = newstringobject(filename)) == NULL) { - DECREF(co); - co = NULL; - } - } - return co; + codeobject *co; + int i; + /* Check argument types */ + if (code == NULL || !is_stringobject(code) || + consts == NULL || !is_listobject(consts) || + names == NULL || !is_listobject(names)) { + err_badcall(); + return NULL; + } + /* Make sure the list of names contains only strings */ + for (i = getlistsize(names); --i >= 0; ) { + object *v = getlistitem(names, i); + if (v == NULL || !is_stringobject(v)) { + err_badcall(); + return NULL; + } + } + co = NEWOBJ(codeobject, &Codetype); + if (co != NULL) { + INCREF(code); + co->co_code = (stringobject *)code; + INCREF(consts); + co->co_consts = consts; + INCREF(names); + co->co_names = names; + if ((co->co_filename = newstringobject(filename)) == NULL) { + DECREF(co); + co = NULL; + } + } + return co; } /* Data structure used internally */ struct compiling { - object *c_code; /* string */ - object *c_consts; /* list of objects */ - object *c_names; /* list of strings (names) */ - int c_nexti; /* index into c_code */ - int c_errors; /* counts errors occurred */ - int c_infunction; /* set when compiling a function */ - int c_loops; /* counts nested loops */ - char *c_filename; /* filename of current node */ + object *c_code; /* string */ + object *c_consts; /* list of objects */ + object *c_names; /* list of strings (names) */ + int c_nexti; /* index into c_code */ + int c_errors; /* counts errors occurred */ + int c_infunction; /* set when compiling a function */ + int c_loops; /* counts nested loops */ + char *c_filename; /* filename of current node */ }; /* Prototypes */ @@ -159,709 +159,709 @@ static void com_addopname PROTO((struct compiling *, int, node *)); static int com_init(c, filename) - struct compiling *c; - char *filename; + struct compiling *c; + char *filename; { - if ((c->c_code = newsizedstringobject((char *)NULL, 0)) == NULL) - goto fail_3; - if ((c->c_consts = newlistobject(0)) == NULL) - goto fail_2; - if ((c->c_names = newlistobject(0)) == NULL) - goto fail_1; - c->c_nexti = 0; - c->c_errors = 0; - c->c_infunction = 0; - c->c_loops = 0; - c->c_filename = filename; - return 1; - - fail_1: - DECREF(c->c_consts); - fail_2: - DECREF(c->c_code); - fail_3: - return 0; + if ((c->c_code = newsizedstringobject((char *)NULL, 0)) == NULL) + goto fail_3; + if ((c->c_consts = newlistobject(0)) == NULL) + goto fail_2; + if ((c->c_names = newlistobject(0)) == NULL) + goto fail_1; + c->c_nexti = 0; + c->c_errors = 0; + c->c_infunction = 0; + c->c_loops = 0; + c->c_filename = filename; + return 1; + + fail_1: + DECREF(c->c_consts); + fail_2: + DECREF(c->c_code); + fail_3: + return 0; } static void com_free(c) - struct compiling *c; + struct compiling *c; { - XDECREF(c->c_code); - XDECREF(c->c_consts); - XDECREF(c->c_names); + XDECREF(c->c_code); + XDECREF(c->c_consts); + XDECREF(c->c_names); } static void com_done(c) - struct compiling *c; + struct compiling *c; { - if (c->c_code != NULL) - resizestring(&c->c_code, c->c_nexti); + if (c->c_code != NULL) + resizestring(&c->c_code, c->c_nexti); } static void com_addbyte(c, byte) - struct compiling *c; - int byte; + struct compiling *c; + int byte; { - int len; - if (byte < 0 || byte > 255) { - fprintf(stderr, "XXX compiling bad byte: %d\n", byte); - abort(); - err_setstr(SystemError, "com_addbyte: byte out of range"); - c->c_errors++; - } - if (c->c_code == NULL) - return; - len = getstringsize(c->c_code); - if (c->c_nexti >= len) { - if (resizestring(&c->c_code, len+1000) != 0) { - c->c_errors++; - return; - } - } - getstringvalue(c->c_code)[c->c_nexti++] = byte; + int len; + if (byte < 0 || byte > 255) { + fprintf(stderr, "XXX compiling bad byte: %d\n", byte); + abort(); + err_setstr(SystemError, "com_addbyte: byte out of range"); + c->c_errors++; + } + if (c->c_code == NULL) + return; + len = getstringsize(c->c_code); + if (c->c_nexti >= len) { + if (resizestring(&c->c_code, len+1000) != 0) { + c->c_errors++; + return; + } + } + getstringvalue(c->c_code)[c->c_nexti++] = byte; } static void com_addint(c, x) - struct compiling *c; - int x; + struct compiling *c; + int x; { - com_addbyte(c, x & 0xff); - com_addbyte(c, x >> 8); /* XXX x should be positive */ + com_addbyte(c, x & 0xff); + com_addbyte(c, x >> 8); /* XXX x should be positive */ } static void com_addoparg(c, op, arg) - struct compiling *c; - int op; - int arg; + struct compiling *c; + int op; + int arg; { - com_addbyte(c, op); - com_addint(c, arg); + com_addbyte(c, op); + com_addint(c, arg); } static void com_addfwref(c, op, p_anchor) - struct compiling *c; - int op; - int *p_anchor; + struct compiling *c; + int op; + int *p_anchor; { - /* Compile a forward reference for backpatching */ - int here; - int anchor; - com_addbyte(c, op); - here = c->c_nexti; - anchor = *p_anchor; - *p_anchor = here; - com_addint(c, anchor == 0 ? 0 : here - anchor); + /* Compile a forward reference for backpatching */ + int here; + int anchor; + com_addbyte(c, op); + here = c->c_nexti; + anchor = *p_anchor; + *p_anchor = here; + com_addint(c, anchor == 0 ? 0 : here - anchor); } static void com_backpatch(c, anchor) - struct compiling *c; - int anchor; /* Must be nonzero */ + struct compiling *c; + int anchor; /* Must be nonzero */ { - unsigned char *code = (unsigned char *) getstringvalue(c->c_code); - int target = c->c_nexti; - int lastanchor = 0; - int dist; - int prev; - for (;;) { - /* Make the JUMP instruction at anchor point to target */ - prev = code[anchor] + (code[anchor+1] << 8); - dist = target - (anchor+2); - code[anchor] = dist & 0xff; - code[anchor+1] = dist >> 8; - if (!prev) - break; - lastanchor = anchor; - anchor -= prev; - } + unsigned char *code = (unsigned char *) getstringvalue(c->c_code); + int target = c->c_nexti; + int lastanchor = 0; + int dist; + int prev; + for (;;) { + /* Make the JUMP instruction at anchor point to target */ + prev = code[anchor] + (code[anchor+1] << 8); + dist = target - (anchor+2); + code[anchor] = dist & 0xff; + code[anchor+1] = dist >> 8; + if (!prev) + break; + lastanchor = anchor; + anchor -= prev; + } } /* Handle constants and names uniformly */ static int com_add(c, list, v) - struct compiling *c; - object *list; - object *v; + struct compiling *c; + object *list; + object *v; { - int n = getlistsize(list); - int i; - for (i = n; --i >= 0; ) { - object *w = getlistitem(list, i); - if (cmpobject(v, w) == 0) - return i; - } - if (addlistitem(list, v) != 0) - c->c_errors++; - return n; + int n = getlistsize(list); + int i; + for (i = n; --i >= 0; ) { + object *w = getlistitem(list, i); + if (cmpobject(v, w) == 0) + return i; + } + if (addlistitem(list, v) != 0) + c->c_errors++; + return n; } static int com_addconst(c, v) - struct compiling *c; - object *v; + struct compiling *c; + object *v; { - return com_add(c, c->c_consts, v); + return com_add(c, c->c_consts, v); } static int com_addname(c, v) - struct compiling *c; - object *v; + struct compiling *c; + object *v; { - return com_add(c, c->c_names, v); + return com_add(c, c->c_names, v); } static void com_addopname(c, op, n) - struct compiling *c; - int op; - node *n; + struct compiling *c; + int op; + node *n; { - object *v; - int i; - char *name; - if (TYPE(n) == STAR) - name = "*"; - else { - REQ(n, NAME); - name = STR(n); - } - if ((v = newstringobject(name)) == NULL) { - c->c_errors++; - i = 255; - } - else { - i = com_addname(c, v); - DECREF(v); - } - com_addoparg(c, op, i); + object *v; + int i; + char *name; + if (TYPE(n) == STAR) + name = "*"; + else { + REQ(n, NAME); + name = STR(n); + } + if ((v = newstringobject(name)) == NULL) { + c->c_errors++; + i = 255; + } + else { + i = com_addname(c, v); + DECREF(v); + } + com_addoparg(c, op, i); } static object * parsenumber(s) - char *s; + char *s; { - extern long strtol(); - extern double atof(); - char *end = s; - long x; - x = strtol(s, &end, 0); - if (*end == '\0') - return newintobject(x); - if (*end == '.' || *end == 'e' || *end == 'E') - return newfloatobject(atof(s)); - err_setstr(RuntimeError, "bad number syntax"); - return NULL; + extern long strtol(); + extern double atof(); + char *end = s; + long x; + x = strtol(s, &end, 0); + if (*end == '\0') + return newintobject(x); + if (*end == '.' || *end == 'e' || *end == 'E') + return newfloatobject(atof(s)); + err_setstr(RuntimeError, "bad number syntax"); + return NULL; } static object * parsestr(s) - char *s; + char *s; { - object *v; - int len; - char *buf; - char *p; - int c; - if (*s != '\'') { - err_badcall(); - return NULL; - } - s++; - len = strlen(s); - if (s[--len] != '\'') { - err_badcall(); - return NULL; - } - if (strchr(s, '\\') == NULL) - return newsizedstringobject(s, len); - v = newsizedstringobject((char *)NULL, len); - p = buf = getstringvalue(v); - while (*s != '\0' && *s != '\'') { - if (*s != '\\') { - *p++ = *s++; - continue; - } - s++; - switch (*s++) { - /* XXX This assumes ASCII! */ - case '\\': *p++ = '\\'; break; - case '\'': *p++ = '\''; break; - case 'b': *p++ = '\b'; break; - case 'f': *p++ = '\014'; break; /* FF */ - case 't': *p++ = '\t'; break; - case 'n': *p++ = '\n'; break; - case 'r': *p++ = '\r'; break; - case 'v': *p++ = '\013'; break; /* VT */ - case 'E': *p++ = '\033'; break; /* ESC, not C */ - case 'a': *p++ = '\007'; break; /* BEL, not classic C */ - case '0': case '1': case '2': case '3': - case '4': case '5': case '6': case '7': - c = s[-1] - '0'; - if ('0' <= *s && *s <= '7') { - c = (c<<3) + *s++ - '0'; - if ('0' <= *s && *s <= '7') - c = (c<<3) + *s++ - '0'; - } - *p++ = c; - break; - case 'x': - if (isxdigit(*s)) { - sscanf(s, "%x", &c); - *p++ = c; - do { - s++; - } while (isxdigit(*s)); - break; - } - /* FALLTHROUGH */ - default: *p++ = '\\'; *p++ = s[-1]; break; - } - } - resizestring(&v, (int)(p - buf)); - return v; + object *v; + int len; + char *buf; + char *p; + int c; + if (*s != '\'') { + err_badcall(); + return NULL; + } + s++; + len = strlen(s); + if (s[--len] != '\'') { + err_badcall(); + return NULL; + } + if (strchr(s, '\\') == NULL) + return newsizedstringobject(s, len); + v = newsizedstringobject((char *)NULL, len); + p = buf = getstringvalue(v); + while (*s != '\0' && *s != '\'') { + if (*s != '\\') { + *p++ = *s++; + continue; + } + s++; + switch (*s++) { + /* XXX This assumes ASCII! */ + case '\\': *p++ = '\\'; break; + case '\'': *p++ = '\''; break; + case 'b': *p++ = '\b'; break; + case 'f': *p++ = '\014'; break; /* FF */ + case 't': *p++ = '\t'; break; + case 'n': *p++ = '\n'; break; + case 'r': *p++ = '\r'; break; + case 'v': *p++ = '\013'; break; /* VT */ + case 'E': *p++ = '\033'; break; /* ESC, not C */ + case 'a': *p++ = '\007'; break; /* BEL, not classic C */ + case '0': case '1': case '2': case '3': + case '4': case '5': case '6': case '7': + c = s[-1] - '0'; + if ('0' <= *s && *s <= '7') { + c = (c<<3) + *s++ - '0'; + if ('0' <= *s && *s <= '7') + c = (c<<3) + *s++ - '0'; + } + *p++ = c; + break; + case 'x': + if (isxdigit(*s)) { + sscanf(s, "%x", &c); + *p++ = c; + do { + s++; + } while (isxdigit(*s)); + break; + } + /* FALLTHROUGH */ + default: *p++ = '\\'; *p++ = s[-1]; break; + } + } + resizestring(&v, (int)(p - buf)); + return v; } static void com_list_constructor(c, n) - struct compiling *c; - node *n; + struct compiling *c; + node *n; { - int len; - int i; - object *v, *w; - if (TYPE(n) != testlist) - REQ(n, exprlist); - /* exprlist: expr (',' expr)* [',']; likewise for testlist */ - len = (NCH(n) + 1) / 2; - for (i = 0; i < NCH(n); i += 2) - com_node(c, CHILD(n, i)); - com_addoparg(c, BUILD_LIST, len); + int len; + int i; + object *v, *w; + if (TYPE(n) != testlist) + REQ(n, exprlist); + /* exprlist: expr (',' expr)* [',']; likewise for testlist */ + len = (NCH(n) + 1) / 2; + for (i = 0; i < NCH(n); i += 2) + com_node(c, CHILD(n, i)); + com_addoparg(c, BUILD_LIST, len); } static void com_atom(c, n) - struct compiling *c; - node *n; + struct compiling *c; + node *n; { - node *ch; - object *v; - int i; - REQ(n, atom); - ch = CHILD(n, 0); - switch (TYPE(ch)) { - case LPAR: - if (TYPE(CHILD(n, 1)) == RPAR) - com_addoparg(c, BUILD_TUPLE, 0); - else - com_node(c, CHILD(n, 1)); - break; - case LSQB: - if (TYPE(CHILD(n, 1)) == RSQB) - com_addoparg(c, BUILD_LIST, 0); - else - com_list_constructor(c, CHILD(n, 1)); - break; - case LBRACE: - com_addoparg(c, BUILD_MAP, 0); - break; - case BACKQUOTE: - com_node(c, CHILD(n, 1)); - com_addbyte(c, UNARY_CONVERT); - break; - case NUMBER: - if ((v = parsenumber(STR(ch))) == NULL) { - c->c_errors++; - i = 255; - } - else { - i = com_addconst(c, v); - DECREF(v); - } - com_addoparg(c, LOAD_CONST, i); - break; - case STRING: - if ((v = parsestr(STR(ch))) == NULL) { - c->c_errors++; - i = 255; - } - else { - i = com_addconst(c, v); - DECREF(v); - } - com_addoparg(c, LOAD_CONST, i); - break; - case NAME: - com_addopname(c, LOAD_NAME, ch); - break; - default: - fprintf(stderr, "node type %d\n", TYPE(ch)); - err_setstr(SystemError, "com_atom: unexpected node type"); - c->c_errors++; - } + node *ch; + object *v; + int i; + REQ(n, atom); + ch = CHILD(n, 0); + switch (TYPE(ch)) { + case LPAR: + if (TYPE(CHILD(n, 1)) == RPAR) + com_addoparg(c, BUILD_TUPLE, 0); + else + com_node(c, CHILD(n, 1)); + break; + case LSQB: + if (TYPE(CHILD(n, 1)) == RSQB) + com_addoparg(c, BUILD_LIST, 0); + else + com_list_constructor(c, CHILD(n, 1)); + break; + case LBRACE: + com_addoparg(c, BUILD_MAP, 0); + break; + case BACKQUOTE: + com_node(c, CHILD(n, 1)); + com_addbyte(c, UNARY_CONVERT); + break; + case NUMBER: + if ((v = parsenumber(STR(ch))) == NULL) { + c->c_errors++; + i = 255; + } + else { + i = com_addconst(c, v); + DECREF(v); + } + com_addoparg(c, LOAD_CONST, i); + break; + case STRING: + if ((v = parsestr(STR(ch))) == NULL) { + c->c_errors++; + i = 255; + } + else { + i = com_addconst(c, v); + DECREF(v); + } + com_addoparg(c, LOAD_CONST, i); + break; + case NAME: + com_addopname(c, LOAD_NAME, ch); + break; + default: + fprintf(stderr, "node type %d\n", TYPE(ch)); + err_setstr(SystemError, "com_atom: unexpected node type"); + c->c_errors++; + } } static void com_slice(c, n, op) - struct compiling *c; - node *n; - int op; + struct compiling *c; + node *n; + int op; { - if (NCH(n) == 1) { - com_addbyte(c, op); - } - else if (NCH(n) == 2) { - if (TYPE(CHILD(n, 0)) != COLON) { - com_node(c, CHILD(n, 0)); - com_addbyte(c, op+1); - } - else { - com_node(c, CHILD(n, 1)); - com_addbyte(c, op+2); - } - } - else { - com_node(c, CHILD(n, 0)); - com_node(c, CHILD(n, 2)); - com_addbyte(c, op+3); - } + if (NCH(n) == 1) { + com_addbyte(c, op); + } + else if (NCH(n) == 2) { + if (TYPE(CHILD(n, 0)) != COLON) { + com_node(c, CHILD(n, 0)); + com_addbyte(c, op+1); + } + else { + com_node(c, CHILD(n, 1)); + com_addbyte(c, op+2); + } + } + else { + com_node(c, CHILD(n, 0)); + com_node(c, CHILD(n, 2)); + com_addbyte(c, op+3); + } } static void com_apply_subscript(c, n) - struct compiling *c; - node *n; + struct compiling *c; + node *n; { - REQ(n, subscript); - if (NCH(n) == 1 && TYPE(CHILD(n, 0)) != COLON) { - /* It's a single subscript */ - com_node(c, CHILD(n, 0)); - com_addbyte(c, BINARY_SUBSCR); - } - else { - /* It's a slice: [expr] ':' [expr] */ - com_slice(c, n, SLICE); - } + REQ(n, subscript); + if (NCH(n) == 1 && TYPE(CHILD(n, 0)) != COLON) { + /* It's a single subscript */ + com_node(c, CHILD(n, 0)); + com_addbyte(c, BINARY_SUBSCR); + } + else { + /* It's a slice: [expr] ':' [expr] */ + com_slice(c, n, SLICE); + } } static void com_call_function(c, n) - struct compiling *c; - node *n; /* EITHER testlist OR ')' */ + struct compiling *c; + node *n; /* EITHER testlist OR ')' */ { - if (TYPE(n) == RPAR) { - com_addbyte(c, UNARY_CALL); - } - else { - com_node(c, n); - com_addbyte(c, BINARY_CALL); - } + if (TYPE(n) == RPAR) { + com_addbyte(c, UNARY_CALL); + } + else { + com_node(c, n); + com_addbyte(c, BINARY_CALL); + } } static void com_select_member(c, n) - struct compiling *c; - node *n; + struct compiling *c; + node *n; { - com_addopname(c, LOAD_ATTR, n); + com_addopname(c, LOAD_ATTR, n); } static void com_apply_trailer(c, n) - struct compiling *c; - node *n; + struct compiling *c; + node *n; { - REQ(n, trailer); - switch (TYPE(CHILD(n, 0))) { - case LPAR: - com_call_function(c, CHILD(n, 1)); - break; - case DOT: - com_select_member(c, CHILD(n, 1)); - break; - case LSQB: - com_apply_subscript(c, CHILD(n, 1)); - break; - default: - err_setstr(SystemError, - "com_apply_trailer: unknown trailer type"); - c->c_errors++; - } + REQ(n, trailer); + switch (TYPE(CHILD(n, 0))) { + case LPAR: + com_call_function(c, CHILD(n, 1)); + break; + case DOT: + com_select_member(c, CHILD(n, 1)); + break; + case LSQB: + com_apply_subscript(c, CHILD(n, 1)); + break; + default: + err_setstr(SystemError, + "com_apply_trailer: unknown trailer type"); + c->c_errors++; + } } static void com_factor(c, n) - struct compiling *c; - node *n; + struct compiling *c; + node *n; { - int i; - REQ(n, factor); - if (TYPE(CHILD(n, 0)) == PLUS) { - com_factor(c, CHILD(n, 1)); - com_addbyte(c, UNARY_POSITIVE); - } - else if (TYPE(CHILD(n, 0)) == MINUS) { - com_factor(c, CHILD(n, 1)); - com_addbyte(c, UNARY_NEGATIVE); - } - else { - com_atom(c, CHILD(n, 0)); - for (i = 1; i < NCH(n); i++) - com_apply_trailer(c, CHILD(n, i)); - } + int i; + REQ(n, factor); + if (TYPE(CHILD(n, 0)) == PLUS) { + com_factor(c, CHILD(n, 1)); + com_addbyte(c, UNARY_POSITIVE); + } + else if (TYPE(CHILD(n, 0)) == MINUS) { + com_factor(c, CHILD(n, 1)); + com_addbyte(c, UNARY_NEGATIVE); + } + else { + com_atom(c, CHILD(n, 0)); + for (i = 1; i < NCH(n); i++) + com_apply_trailer(c, CHILD(n, i)); + } } static void com_term(c, n) - struct compiling *c; - node *n; + struct compiling *c; + node *n; { - int i; - int op; - REQ(n, term); - com_factor(c, CHILD(n, 0)); - for (i = 2; i < NCH(n); i += 2) { - com_factor(c, CHILD(n, i)); - switch (TYPE(CHILD(n, i-1))) { - case STAR: - op = BINARY_MULTIPLY; - break; - case SLASH: - op = BINARY_DIVIDE; - break; - case PERCENT: - op = BINARY_MODULO; - break; - default: - err_setstr(SystemError, - "com_term: term operator not *, / or %"); - c->c_errors++; - op = 255; - } - com_addbyte(c, op); - } + int i; + int op; + REQ(n, term); + com_factor(c, CHILD(n, 0)); + for (i = 2; i < NCH(n); i += 2) { + com_factor(c, CHILD(n, i)); + switch (TYPE(CHILD(n, i-1))) { + case STAR: + op = BINARY_MULTIPLY; + break; + case SLASH: + op = BINARY_DIVIDE; + break; + case PERCENT: + op = BINARY_MODULO; + break; + default: + err_setstr(SystemError, + "com_term: term operator not *, / or %"); + c->c_errors++; + op = 255; + } + com_addbyte(c, op); + } } static void com_expr(c, n) - struct compiling *c; - node *n; + struct compiling *c; + node *n; { - int i; - int op; - REQ(n, expr); - com_term(c, CHILD(n, 0)); - for (i = 2; i < NCH(n); i += 2) { - com_term(c, CHILD(n, i)); - switch (TYPE(CHILD(n, i-1))) { - case PLUS: - op = BINARY_ADD; - break; - case MINUS: - op = BINARY_SUBTRACT; - break; - default: - err_setstr(SystemError, - "com_expr: expr operator not + or -"); - c->c_errors++; - op = 255; - } - com_addbyte(c, op); - } + int i; + int op; + REQ(n, expr); + com_term(c, CHILD(n, 0)); + for (i = 2; i < NCH(n); i += 2) { + com_term(c, CHILD(n, i)); + switch (TYPE(CHILD(n, i-1))) { + case PLUS: + op = BINARY_ADD; + break; + case MINUS: + op = BINARY_SUBTRACT; + break; + default: + err_setstr(SystemError, + "com_expr: expr operator not + or -"); + c->c_errors++; + op = 255; + } + com_addbyte(c, op); + } } static enum cmp_op cmp_type(n) - node *n; + node *n; { - REQ(n, comp_op); - /* comp_op: '<' | '>' | '=' | '>' '=' | '<' '=' | '<' '>' - | 'in' | 'not' 'in' | 'is' | 'is' not' */ - if (NCH(n) == 1) { - n = CHILD(n, 0); - switch (TYPE(n)) { - case LESS: return LT; - case GREATER: return GT; - case EQUAL: return EQ; - case NAME: if (strcmp(STR(n), "in") == 0) return IN; - if (strcmp(STR(n), "is") == 0) return IS; - } - } - else if (NCH(n) == 2) { - int t2 = TYPE(CHILD(n, 1)); - switch (TYPE(CHILD(n, 0))) { - case LESS: if (t2 == EQUAL) return LE; - if (t2 == GREATER) return NE; - break; - case GREATER: if (t2 == EQUAL) return GE; - break; - case NAME: if (strcmp(STR(CHILD(n, 1)), "in") == 0) - return NOT_IN; - if (strcmp(STR(CHILD(n, 0)), "is") == 0) - return IS_NOT; - } - } - return BAD; + REQ(n, comp_op); + /* comp_op: '<' | '>' | '=' | '>' '=' | '<' '=' | '<' '>' + | 'in' | 'not' 'in' | 'is' | 'is' not' */ + if (NCH(n) == 1) { + n = CHILD(n, 0); + switch (TYPE(n)) { + case LESS: return LT; + case GREATER: return GT; + case EQUAL: return EQ; + case NAME: if (strcmp(STR(n), "in") == 0) return IN; + if (strcmp(STR(n), "is") == 0) return IS; + } + } + else if (NCH(n) == 2) { + int t2 = TYPE(CHILD(n, 1)); + switch (TYPE(CHILD(n, 0))) { + case LESS: if (t2 == EQUAL) return LE; + if (t2 == GREATER) return NE; + break; + case GREATER: if (t2 == EQUAL) return GE; + break; + case NAME: if (strcmp(STR(CHILD(n, 1)), "in") == 0) + return NOT_IN; + if (strcmp(STR(CHILD(n, 0)), "is") == 0) + return IS_NOT; + } + } + return BAD; } static void com_comparison(c, n) - struct compiling *c; - node *n; + struct compiling *c; + node *n; { - int i; - enum cmp_op op; - int anchor; - REQ(n, comparison); /* comparison: expr (comp_op expr)* */ - com_expr(c, CHILD(n, 0)); - if (NCH(n) == 1) - return; - - /**************************************************************** - The following code is generated for all but the last - comparison in a chain: - - label: on stack: opcode: jump to: - - a <code to load b> - a, b DUP_TOP - a, b, b ROT_THREE - b, a, b COMPARE_OP - b, 0-or-1 JUMP_IF_FALSE L1 - b, 1 POP_TOP - b - - We are now ready to repeat this sequence for the next - comparison in the chain. - - For the last we generate: - - b <code to load c> - b, c COMPARE_OP - 0-or-1 - - If there were any jumps to L1 (i.e., there was more than one - comparison), we generate: - - 0-or-1 JUMP_FORWARD L2 - L1: b, 0 ROT_TWO - 0, b POP_TOP - 0 - L2: - ****************************************************************/ - - anchor = 0; - - for (i = 2; i < NCH(n); i += 2) { - com_expr(c, CHILD(n, i)); - if (i+2 < NCH(n)) { - com_addbyte(c, DUP_TOP); - com_addbyte(c, ROT_THREE); - } - op = cmp_type(CHILD(n, i-1)); - if (op == BAD) { - err_setstr(SystemError, - "com_comparison: unknown comparison op"); - c->c_errors++; - } - com_addoparg(c, COMPARE_OP, op); - if (i+2 < NCH(n)) { - com_addfwref(c, JUMP_IF_FALSE, &anchor); - com_addbyte(c, POP_TOP); - } - } - - if (anchor) { - int anchor2 = 0; - com_addfwref(c, JUMP_FORWARD, &anchor2); - com_backpatch(c, anchor); - com_addbyte(c, ROT_TWO); - com_addbyte(c, POP_TOP); - com_backpatch(c, anchor2); - } + int i; + enum cmp_op op; + int anchor; + REQ(n, comparison); /* comparison: expr (comp_op expr)* */ + com_expr(c, CHILD(n, 0)); + if (NCH(n) == 1) + return; + + /**************************************************************** + The following code is generated for all but the last + comparison in a chain: + + label: on stack: opcode: jump to: + + a <code to load b> + a, b DUP_TOP + a, b, b ROT_THREE + b, a, b COMPARE_OP + b, 0-or-1 JUMP_IF_FALSE L1 + b, 1 POP_TOP + b + + We are now ready to repeat this sequence for the next + comparison in the chain. + + For the last we generate: + + b <code to load c> + b, c COMPARE_OP + 0-or-1 + + If there were any jumps to L1 (i.e., there was more than one + comparison), we generate: + + 0-or-1 JUMP_FORWARD L2 + L1: b, 0 ROT_TWO + 0, b POP_TOP + 0 + L2: + ****************************************************************/ + + anchor = 0; + + for (i = 2; i < NCH(n); i += 2) { + com_expr(c, CHILD(n, i)); + if (i+2 < NCH(n)) { + com_addbyte(c, DUP_TOP); + com_addbyte(c, ROT_THREE); + } + op = cmp_type(CHILD(n, i-1)); + if (op == BAD) { + err_setstr(SystemError, + "com_comparison: unknown comparison op"); + c->c_errors++; + } + com_addoparg(c, COMPARE_OP, op); + if (i+2 < NCH(n)) { + com_addfwref(c, JUMP_IF_FALSE, &anchor); + com_addbyte(c, POP_TOP); + } + } + + if (anchor) { + int anchor2 = 0; + com_addfwref(c, JUMP_FORWARD, &anchor2); + com_backpatch(c, anchor); + com_addbyte(c, ROT_TWO); + com_addbyte(c, POP_TOP); + com_backpatch(c, anchor2); + } } static void com_not_test(c, n) - struct compiling *c; - node *n; + struct compiling *c; + node *n; { - REQ(n, not_test); /* 'not' not_test | comparison */ - if (NCH(n) == 1) { - com_comparison(c, CHILD(n, 0)); - } - else { - com_not_test(c, CHILD(n, 1)); - com_addbyte(c, UNARY_NOT); - } + REQ(n, not_test); /* 'not' not_test | comparison */ + if (NCH(n) == 1) { + com_comparison(c, CHILD(n, 0)); + } + else { + com_not_test(c, CHILD(n, 1)); + com_addbyte(c, UNARY_NOT); + } } static void com_and_test(c, n) - struct compiling *c; - node *n; + struct compiling *c; + node *n; { - int i; - int anchor; - REQ(n, and_test); /* not_test ('and' not_test)* */ - anchor = 0; - i = 0; - for (;;) { - com_not_test(c, CHILD(n, i)); - if ((i += 2) >= NCH(n)) - break; - com_addfwref(c, JUMP_IF_FALSE, &anchor); - com_addbyte(c, POP_TOP); - } - if (anchor) - com_backpatch(c, anchor); + int i; + int anchor; + REQ(n, and_test); /* not_test ('and' not_test)* */ + anchor = 0; + i = 0; + for (;;) { + com_not_test(c, CHILD(n, i)); + if ((i += 2) >= NCH(n)) + break; + com_addfwref(c, JUMP_IF_FALSE, &anchor); + com_addbyte(c, POP_TOP); + } + if (anchor) + com_backpatch(c, anchor); } static void com_test(c, n) - struct compiling *c; - node *n; + struct compiling *c; + node *n; { - int i; - int anchor; - REQ(n, test); /* and_test ('and' and_test)* */ - anchor = 0; - i = 0; - for (;;) { - com_and_test(c, CHILD(n, i)); - if ((i += 2) >= NCH(n)) - break; - com_addfwref(c, JUMP_IF_TRUE, &anchor); - com_addbyte(c, POP_TOP); - } - if (anchor) - com_backpatch(c, anchor); + int i; + int anchor; + REQ(n, test); /* and_test ('and' and_test)* */ + anchor = 0; + i = 0; + for (;;) { + com_and_test(c, CHILD(n, i)); + if ((i += 2) >= NCH(n)) + break; + com_addfwref(c, JUMP_IF_TRUE, &anchor); + com_addbyte(c, POP_TOP); + } + if (anchor) + com_backpatch(c, anchor); } static void com_list(c, n) - struct compiling *c; - node *n; + struct compiling *c; + node *n; { - /* exprlist: expr (',' expr)* [',']; likewise for testlist */ - if (NCH(n) == 1) { - com_node(c, CHILD(n, 0)); - } - else { - int i; - int len; - len = (NCH(n) + 1) / 2; - for (i = 0; i < NCH(n); i += 2) - com_node(c, CHILD(n, i)); - com_addoparg(c, BUILD_TUPLE, len); - } + /* exprlist: expr (',' expr)* [',']; likewise for testlist */ + if (NCH(n) == 1) { + com_node(c, CHILD(n, 0)); + } + else { + int i; + int len; + len = (NCH(n) + 1) / 2; + for (i = 0; i < NCH(n); i += 2) + com_node(c, CHILD(n, i)); + com_addoparg(c, BUILD_TUPLE, len); + } } @@ -872,901 +872,901 @@ static void com_assign PROTO((struct compiling *, node *, int)); static void com_assign_attr(c, n, assigning) - struct compiling *c; - node *n; - int assigning; + struct compiling *c; + node *n; + int assigning; { - com_addopname(c, assigning ? STORE_ATTR : DELETE_ATTR, n); + com_addopname(c, assigning ? STORE_ATTR : DELETE_ATTR, n); } static void com_assign_slice(c, n, assigning) - struct compiling *c; - node *n; - int assigning; + struct compiling *c; + node *n; + int assigning; { - com_slice(c, n, assigning ? STORE_SLICE : DELETE_SLICE); + com_slice(c, n, assigning ? STORE_SLICE : DELETE_SLICE); } static void com_assign_subscript(c, n, assigning) - struct compiling *c; - node *n; - int assigning; + struct compiling *c; + node *n; + int assigning; { - com_node(c, n); - com_addbyte(c, assigning ? STORE_SUBSCR : DELETE_SUBSCR); + com_node(c, n); + com_addbyte(c, assigning ? STORE_SUBSCR : DELETE_SUBSCR); } static void com_assign_trailer(c, n, assigning) - struct compiling *c; - node *n; - int assigning; + struct compiling *c; + node *n; + int assigning; { - char *name; - REQ(n, trailer); - switch (TYPE(CHILD(n, 0))) { - case LPAR: /* '(' [exprlist] ')' */ - err_setstr(TypeError, "can't assign to function call"); - c->c_errors++; - break; - case DOT: /* '.' NAME */ - com_assign_attr(c, CHILD(n, 1), assigning); - break; - case LSQB: /* '[' subscript ']' */ - n = CHILD(n, 1); - REQ(n, subscript); /* subscript: expr | [expr] ':' [expr] */ - if (NCH(n) > 1 || TYPE(CHILD(n, 0)) == COLON) - com_assign_slice(c, n, assigning); - else - com_assign_subscript(c, CHILD(n, 0), assigning); - break; - default: - err_setstr(TypeError, "unknown trailer type"); - c->c_errors++; - } + char *name; + REQ(n, trailer); + switch (TYPE(CHILD(n, 0))) { + case LPAR: /* '(' [exprlist] ')' */ + err_setstr(TypeError, "can't assign to function call"); + c->c_errors++; + break; + case DOT: /* '.' NAME */ + com_assign_attr(c, CHILD(n, 1), assigning); + break; + case LSQB: /* '[' subscript ']' */ + n = CHILD(n, 1); + REQ(n, subscript); /* subscript: expr | [expr] ':' [expr] */ + if (NCH(n) > 1 || TYPE(CHILD(n, 0)) == COLON) + com_assign_slice(c, n, assigning); + else + com_assign_subscript(c, CHILD(n, 0), assigning); + break; + default: + err_setstr(TypeError, "unknown trailer type"); + c->c_errors++; + } } static void com_assign_tuple(c, n, assigning) - struct compiling *c; - node *n; - int assigning; + struct compiling *c; + node *n; + int assigning; { - int i; - if (TYPE(n) != testlist) - REQ(n, exprlist); - if (assigning) - com_addoparg(c, UNPACK_TUPLE, (NCH(n)+1)/2); - for (i = 0; i < NCH(n); i += 2) - com_assign(c, CHILD(n, i), assigning); + int i; + if (TYPE(n) != testlist) + REQ(n, exprlist); + if (assigning) + com_addoparg(c, UNPACK_TUPLE, (NCH(n)+1)/2); + for (i = 0; i < NCH(n); i += 2) + com_assign(c, CHILD(n, i), assigning); } static void com_assign_list(c, n, assigning) - struct compiling *c; - node *n; - int assigning; + struct compiling *c; + node *n; + int assigning; { - int i; - if (assigning) - com_addoparg(c, UNPACK_LIST, (NCH(n)+1)/2); - for (i = 0; i < NCH(n); i += 2) - com_assign(c, CHILD(n, i), assigning); + int i; + if (assigning) + com_addoparg(c, UNPACK_LIST, (NCH(n)+1)/2); + for (i = 0; i < NCH(n); i += 2) + com_assign(c, CHILD(n, i), assigning); } static void com_assign_name(c, n, assigning) - struct compiling *c; - node *n; - int assigning; + struct compiling *c; + node *n; + int assigning; { - REQ(n, NAME); - com_addopname(c, assigning ? STORE_NAME : DELETE_NAME, n); + REQ(n, NAME); + com_addopname(c, assigning ? STORE_NAME : DELETE_NAME, n); } static void com_assign(c, n, assigning) - struct compiling *c; - node *n; - int assigning; + struct compiling *c; + node *n; + int assigning; { - /* Loop to avoid trivial recursion */ - for (;;) { - switch (TYPE(n)) { - - case exprlist: - case testlist: - if (NCH(n) > 1) { - com_assign_tuple(c, n, assigning); - return; - } - n = CHILD(n, 0); - break; - - case test: - case and_test: - case not_test: - if (NCH(n) > 1) { - err_setstr(TypeError, - "can't assign to operator"); - c->c_errors++; - return; - } - n = CHILD(n, 0); - break; - - case comparison: - if (NCH(n) > 1) { - err_setstr(TypeError, - "can't assign to operator"); - c->c_errors++; - return; - } - n = CHILD(n, 0); - break; - - case expr: - if (NCH(n) > 1) { - err_setstr(TypeError, - "can't assign to operator"); - c->c_errors++; - return; - } - n = CHILD(n, 0); - break; - - case term: - if (NCH(n) > 1) { - err_setstr(TypeError, - "can't assign to operator"); - c->c_errors++; - return; - } - n = CHILD(n, 0); - break; - - case factor: /* ('+'|'-') factor | atom trailer* */ - if (TYPE(CHILD(n, 0)) != atom) { /* '+' | '-' */ - err_setstr(TypeError, - "can't assign to operator"); - c->c_errors++; - return; - } - if (NCH(n) > 1) { /* trailer present */ - int i; - com_node(c, CHILD(n, 0)); - for (i = 1; i+1 < NCH(n); i++) { - com_apply_trailer(c, CHILD(n, i)); - } /* NB i is still alive */ - com_assign_trailer(c, - CHILD(n, i), assigning); - return; - } - n = CHILD(n, 0); - break; - - case atom: - switch (TYPE(CHILD(n, 0))) { - case LPAR: - n = CHILD(n, 1); - if (TYPE(n) == RPAR) { - /* XXX Should allow () = () ??? */ - err_setstr(TypeError, - "can't assign to ()"); - c->c_errors++; - return; - } - break; - case LSQB: - n = CHILD(n, 1); - if (TYPE(n) == RSQB) { - err_setstr(TypeError, - "can't assign to []"); - c->c_errors++; - return; - } - com_assign_list(c, n, assigning); - return; - case NAME: - com_assign_name(c, CHILD(n, 0), assigning); - return; - default: - err_setstr(TypeError, - "can't assign to constant"); - c->c_errors++; - return; - } - break; - - default: - fprintf(stderr, "node type %d\n", TYPE(n)); - err_setstr(SystemError, "com_assign: bad node"); - c->c_errors++; - return; - - } - } + /* Loop to avoid trivial recursion */ + for (;;) { + switch (TYPE(n)) { + + case exprlist: + case testlist: + if (NCH(n) > 1) { + com_assign_tuple(c, n, assigning); + return; + } + n = CHILD(n, 0); + break; + + case test: + case and_test: + case not_test: + if (NCH(n) > 1) { + err_setstr(TypeError, + "can't assign to operator"); + c->c_errors++; + return; + } + n = CHILD(n, 0); + break; + + case comparison: + if (NCH(n) > 1) { + err_setstr(TypeError, + "can't assign to operator"); + c->c_errors++; + return; + } + n = CHILD(n, 0); + break; + + case expr: + if (NCH(n) > 1) { + err_setstr(TypeError, + "can't assign to operator"); + c->c_errors++; + return; + } + n = CHILD(n, 0); + break; + + case term: + if (NCH(n) > 1) { + err_setstr(TypeError, + "can't assign to operator"); + c->c_errors++; + return; + } + n = CHILD(n, 0); + break; + + case factor: /* ('+'|'-') factor | atom trailer* */ + if (TYPE(CHILD(n, 0)) != atom) { /* '+' | '-' */ + err_setstr(TypeError, + "can't assign to operator"); + c->c_errors++; + return; + } + if (NCH(n) > 1) { /* trailer present */ + int i; + com_node(c, CHILD(n, 0)); + for (i = 1; i+1 < NCH(n); i++) { + com_apply_trailer(c, CHILD(n, i)); + } /* NB i is still alive */ + com_assign_trailer(c, + CHILD(n, i), assigning); + return; + } + n = CHILD(n, 0); + break; + + case atom: + switch (TYPE(CHILD(n, 0))) { + case LPAR: + n = CHILD(n, 1); + if (TYPE(n) == RPAR) { + /* XXX Should allow () = () ??? */ + err_setstr(TypeError, + "can't assign to ()"); + c->c_errors++; + return; + } + break; + case LSQB: + n = CHILD(n, 1); + if (TYPE(n) == RSQB) { + err_setstr(TypeError, + "can't assign to []"); + c->c_errors++; + return; + } + com_assign_list(c, n, assigning); + return; + case NAME: + com_assign_name(c, CHILD(n, 0), assigning); + return; + default: + err_setstr(TypeError, + "can't assign to constant"); + c->c_errors++; + return; + } + break; + + default: + fprintf(stderr, "node type %d\n", TYPE(n)); + err_setstr(SystemError, "com_assign: bad node"); + c->c_errors++; + return; + + } + } } static void com_expr_stmt(c, n) - struct compiling *c; - node *n; + struct compiling *c; + node *n; { - REQ(n, expr_stmt); /* exprlist ('=' exprlist)* NEWLINE */ - com_node(c, CHILD(n, NCH(n)-2)); - if (NCH(n) == 2) { - com_addbyte(c, PRINT_EXPR); - } - else { - int i; - for (i = 0; i < NCH(n)-3; i+=2) { - if (i+2 < NCH(n)-3) - com_addbyte(c, DUP_TOP); - com_assign(c, CHILD(n, i), 1/*assign*/); - } - } + REQ(n, expr_stmt); /* exprlist ('=' exprlist)* NEWLINE */ + com_node(c, CHILD(n, NCH(n)-2)); + if (NCH(n) == 2) { + com_addbyte(c, PRINT_EXPR); + } + else { + int i; + for (i = 0; i < NCH(n)-3; i+=2) { + if (i+2 < NCH(n)-3) + com_addbyte(c, DUP_TOP); + com_assign(c, CHILD(n, i), 1/*assign*/); + } + } } static void com_print_stmt(c, n) - struct compiling *c; - node *n; + struct compiling *c; + node *n; { - int i; - REQ(n, print_stmt); /* 'print' (test ',')* [test] NEWLINE */ - for (i = 1; i+1 < NCH(n); i += 2) { - com_node(c, CHILD(n, i)); - com_addbyte(c, PRINT_ITEM); - } - if (TYPE(CHILD(n, NCH(n)-2)) != COMMA) - com_addbyte(c, PRINT_NEWLINE); - /* XXX Alternatively, LOAD_CONST '\n' and then PRINT_ITEM */ + int i; + REQ(n, print_stmt); /* 'print' (test ',')* [test] NEWLINE */ + for (i = 1; i+1 < NCH(n); i += 2) { + com_node(c, CHILD(n, i)); + com_addbyte(c, PRINT_ITEM); + } + if (TYPE(CHILD(n, NCH(n)-2)) != COMMA) + com_addbyte(c, PRINT_NEWLINE); + /* XXX Alternatively, LOAD_CONST '\n' and then PRINT_ITEM */ } static void com_return_stmt(c, n) - struct compiling *c; - node *n; + struct compiling *c; + node *n; { - REQ(n, return_stmt); /* 'return' [testlist] NEWLINE */ - if (!c->c_infunction) { - err_setstr(TypeError, "'return' outside function"); - c->c_errors++; - } - if (NCH(n) == 2) - com_addoparg(c, LOAD_CONST, com_addconst(c, None)); - else - com_node(c, CHILD(n, 1)); - com_addbyte(c, RETURN_VALUE); + REQ(n, return_stmt); /* 'return' [testlist] NEWLINE */ + if (!c->c_infunction) { + err_setstr(TypeError, "'return' outside function"); + c->c_errors++; + } + if (NCH(n) == 2) + com_addoparg(c, LOAD_CONST, com_addconst(c, None)); + else + com_node(c, CHILD(n, 1)); + com_addbyte(c, RETURN_VALUE); } static void com_raise_stmt(c, n) - struct compiling *c; - node *n; + struct compiling *c; + node *n; { - REQ(n, raise_stmt); /* 'raise' expr [',' expr] NEWLINE */ - com_node(c, CHILD(n, 1)); - if (NCH(n) > 3) - com_node(c, CHILD(n, 3)); - else - com_addoparg(c, LOAD_CONST, com_addconst(c, None)); - com_addbyte(c, RAISE_EXCEPTION); + REQ(n, raise_stmt); /* 'raise' expr [',' expr] NEWLINE */ + com_node(c, CHILD(n, 1)); + if (NCH(n) > 3) + com_node(c, CHILD(n, 3)); + else + com_addoparg(c, LOAD_CONST, com_addconst(c, None)); + com_addbyte(c, RAISE_EXCEPTION); } static void com_import_stmt(c, n) - struct compiling *c; - node *n; + struct compiling *c; + node *n; { - int i; - REQ(n, import_stmt); - /* 'import' NAME (',' NAME)* NEWLINE | - 'from' NAME 'import' ('*' | NAME (',' NAME)*) NEWLINE */ - if (STR(CHILD(n, 0))[0] == 'f') { - /* 'from' NAME 'import' ... */ - REQ(CHILD(n, 1), NAME); - com_addopname(c, IMPORT_NAME, CHILD(n, 1)); - for (i = 3; i < NCH(n); i += 2) - com_addopname(c, IMPORT_FROM, CHILD(n, i)); - com_addbyte(c, POP_TOP); - } - else { - /* 'import' ... */ - for (i = 1; i < NCH(n); i += 2) { - com_addopname(c, IMPORT_NAME, CHILD(n, i)); - com_addopname(c, STORE_NAME, CHILD(n, i)); - } - } + int i; + REQ(n, import_stmt); + /* 'import' NAME (',' NAME)* NEWLINE | + 'from' NAME 'import' ('*' | NAME (',' NAME)*) NEWLINE */ + if (STR(CHILD(n, 0))[0] == 'f') { + /* 'from' NAME 'import' ... */ + REQ(CHILD(n, 1), NAME); + com_addopname(c, IMPORT_NAME, CHILD(n, 1)); + for (i = 3; i < NCH(n); i += 2) + com_addopname(c, IMPORT_FROM, CHILD(n, i)); + com_addbyte(c, POP_TOP); + } + else { + /* 'import' ... */ + for (i = 1; i < NCH(n); i += 2) { + com_addopname(c, IMPORT_NAME, CHILD(n, i)); + com_addopname(c, STORE_NAME, CHILD(n, i)); + } + } } static void com_if_stmt(c, n) - struct compiling *c; - node *n; + struct compiling *c; + node *n; { - int i; - int anchor = 0; - REQ(n, if_stmt); - /*'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] */ - for (i = 0; i+3 < NCH(n); i+=4) { - int a = 0; - node *ch = CHILD(n, i+1); - if (i > 0) - com_addoparg(c, SET_LINENO, ch->n_lineno); - com_node(c, CHILD(n, i+1)); - com_addfwref(c, JUMP_IF_FALSE, &a); - com_addbyte(c, POP_TOP); - com_node(c, CHILD(n, i+3)); - com_addfwref(c, JUMP_FORWARD, &anchor); - com_backpatch(c, a); - com_addbyte(c, POP_TOP); - } - if (i+2 < NCH(n)) - com_node(c, CHILD(n, i+2)); - com_backpatch(c, anchor); + int i; + int anchor = 0; + REQ(n, if_stmt); + /*'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] */ + for (i = 0; i+3 < NCH(n); i+=4) { + int a = 0; + node *ch = CHILD(n, i+1); + if (i > 0) + com_addoparg(c, SET_LINENO, ch->n_lineno); + com_node(c, CHILD(n, i+1)); + com_addfwref(c, JUMP_IF_FALSE, &a); + com_addbyte(c, POP_TOP); + com_node(c, CHILD(n, i+3)); + com_addfwref(c, JUMP_FORWARD, &anchor); + com_backpatch(c, a); + com_addbyte(c, POP_TOP); + } + if (i+2 < NCH(n)) + com_node(c, CHILD(n, i+2)); + com_backpatch(c, anchor); } static void com_while_stmt(c, n) - struct compiling *c; - node *n; + struct compiling *c; + node *n; { - int break_anchor = 0; - int anchor = 0; - int begin; - REQ(n, while_stmt); /* 'while' test ':' suite ['else' ':' suite] */ - com_addfwref(c, SETUP_LOOP, &break_anchor); - begin = c->c_nexti; - com_addoparg(c, SET_LINENO, n->n_lineno); - com_node(c, CHILD(n, 1)); - com_addfwref(c, JUMP_IF_FALSE, &anchor); - com_addbyte(c, POP_TOP); - c->c_loops++; - com_node(c, CHILD(n, 3)); - c->c_loops--; - com_addoparg(c, JUMP_ABSOLUTE, begin); - com_backpatch(c, anchor); - com_addbyte(c, POP_TOP); - com_addbyte(c, POP_BLOCK); - if (NCH(n) > 4) - com_node(c, CHILD(n, 6)); - com_backpatch(c, break_anchor); + int break_anchor = 0; + int anchor = 0; + int begin; + REQ(n, while_stmt); /* 'while' test ':' suite ['else' ':' suite] */ + com_addfwref(c, SETUP_LOOP, &break_anchor); + begin = c->c_nexti; + com_addoparg(c, SET_LINENO, n->n_lineno); + com_node(c, CHILD(n, 1)); + com_addfwref(c, JUMP_IF_FALSE, &anchor); + com_addbyte(c, POP_TOP); + c->c_loops++; + com_node(c, CHILD(n, 3)); + c->c_loops--; + com_addoparg(c, JUMP_ABSOLUTE, begin); + com_backpatch(c, anchor); + com_addbyte(c, POP_TOP); + com_addbyte(c, POP_BLOCK); + if (NCH(n) > 4) + com_node(c, CHILD(n, 6)); + com_backpatch(c, break_anchor); } static void com_for_stmt(c, n) - struct compiling *c; - node *n; + struct compiling *c; + node *n; { - object *v; - int break_anchor = 0; - int anchor = 0; - int begin; - REQ(n, for_stmt); - /* 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite] */ - com_addfwref(c, SETUP_LOOP, &break_anchor); - com_node(c, CHILD(n, 3)); - v = newintobject(0L); - if (v == NULL) - c->c_errors++; - com_addoparg(c, LOAD_CONST, com_addconst(c, v)); - XDECREF(v); - begin = c->c_nexti; - com_addoparg(c, SET_LINENO, n->n_lineno); - com_addfwref(c, FOR_LOOP, &anchor); - com_assign(c, CHILD(n, 1), 1/*assigning*/); - c->c_loops++; - com_node(c, CHILD(n, 5)); - c->c_loops--; - com_addoparg(c, JUMP_ABSOLUTE, begin); - com_backpatch(c, anchor); - com_addbyte(c, POP_BLOCK); - if (NCH(n) > 8) - com_node(c, CHILD(n, 8)); - com_backpatch(c, break_anchor); + object *v; + int break_anchor = 0; + int anchor = 0; + int begin; + REQ(n, for_stmt); + /* 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite] */ + com_addfwref(c, SETUP_LOOP, &break_anchor); + com_node(c, CHILD(n, 3)); + v = newintobject(0L); + if (v == NULL) + c->c_errors++; + com_addoparg(c, LOAD_CONST, com_addconst(c, v)); + XDECREF(v); + begin = c->c_nexti; + com_addoparg(c, SET_LINENO, n->n_lineno); + com_addfwref(c, FOR_LOOP, &anchor); + com_assign(c, CHILD(n, 1), 1/*assigning*/); + c->c_loops++; + com_node(c, CHILD(n, 5)); + c->c_loops--; + com_addoparg(c, JUMP_ABSOLUTE, begin); + com_backpatch(c, anchor); + com_addbyte(c, POP_BLOCK); + if (NCH(n) > 8) + com_node(c, CHILD(n, 8)); + com_backpatch(c, break_anchor); } /* Although 'execpt' and 'finally' clauses can be combined - syntactically, they are compiled separately. In fact, - try: S - except E1: S1 - except E2: S2 - ... - finally: Sf - is equivalent to - try: - try: S - except E1: S1 - except E2: S2 - ... - finally: Sf - meaning that the 'finally' clause is entered even if things - go wrong again in an exception handler. Note that this is - not the case for exception handlers: at most one is entered. - - Code generated for "try: S finally: Sf" is as follows: - - SETUP_FINALLY L - <code for S> - POP_BLOCK - LOAD_CONST <nil> - L: <code for Sf> - END_FINALLY - - The special instructions use the block stack. Each block - stack entry contains the instruction that created it (here - SETUP_FINALLY), the level of the value stack at the time the - block stack entry was created, and a label (here L). - - SETUP_FINALLY: - Pushes the current value stack level and the label - onto the block stack. - POP_BLOCK: - Pops en entry from the block stack, and pops the value - stack until its level is the same as indicated on the - block stack. (The label is ignored.) - END_FINALLY: - Pops a variable number of entries from the *value* stack - and re-raises the exception they specify. The number of - entries popped depends on the (pseudo) exception type. - - The block stack is unwound when an exception is raised: - when a SETUP_FINALLY entry is found, the exception is pushed - onto the value stack (and the exception condition is cleared), - and the interpreter jumps to the label gotten from the block - stack. - - Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...": - (The contents of the value stack is shown in [], with the top - at the right; 'tb' is trace-back info, 'val' the exception's - associated value, and 'exc' the exception.) - - Value stack Label Instruction Argument - [] SETUP_EXCEPT L1 - [] <code for S> - [] POP_BLOCK - [] JUMP_FORWARD L0 - - [tb, val, exc] L1: DUP ) - [tb, val, exc, exc] <evaluate E1> ) - [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1 - [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 ) - [tb, val, exc, 1] POP ) - [tb, val, exc] POP - [tb, val] <assign to V1> (or POP if no V1) - [tb] POP - [] <code for S1> - JUMP_FORWARD L0 - - [tb, val, exc, 0] L2: POP - [tb, val, exc] DUP - .............................etc....................... - - [tb, val, exc, 0] Ln+1: POP - [tb, val, exc] END_FINALLY # re-raise exception - - [] L0: <next statement> - - Of course, parts are not generated if Vi or Ei is not present. + syntactically, they are compiled separately. In fact, + try: S + except E1: S1 + except E2: S2 + ... + finally: Sf + is equivalent to + try: + try: S + except E1: S1 + except E2: S2 + ... + finally: Sf + meaning that the 'finally' clause is entered even if things + go wrong again in an exception handler. Note that this is + not the case for exception handlers: at most one is entered. + + Code generated for "try: S finally: Sf" is as follows: + + SETUP_FINALLY L + <code for S> + POP_BLOCK + LOAD_CONST <nil> + L: <code for Sf> + END_FINALLY + + The special instructions use the block stack. Each block + stack entry contains the instruction that created it (here + SETUP_FINALLY), the level of the value stack at the time the + block stack entry was created, and a label (here L). + + SETUP_FINALLY: + Pushes the current value stack level and the label + onto the block stack. + POP_BLOCK: + Pops en entry from the block stack, and pops the value + stack until its level is the same as indicated on the + block stack. (The label is ignored.) + END_FINALLY: + Pops a variable number of entries from the *value* stack + and re-raises the exception they specify. The number of + entries popped depends on the (pseudo) exception type. + + The block stack is unwound when an exception is raised: + when a SETUP_FINALLY entry is found, the exception is pushed + onto the value stack (and the exception condition is cleared), + and the interpreter jumps to the label gotten from the block + stack. + + Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...": + (The contents of the value stack is shown in [], with the top + at the right; 'tb' is trace-back info, 'val' the exception's + associated value, and 'exc' the exception.) + + Value stack Label Instruction Argument + [] SETUP_EXCEPT L1 + [] <code for S> + [] POP_BLOCK + [] JUMP_FORWARD L0 + + [tb, val, exc] L1: DUP ) + [tb, val, exc, exc] <evaluate E1> ) + [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1 + [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 ) + [tb, val, exc, 1] POP ) + [tb, val, exc] POP + [tb, val] <assign to V1> (or POP if no V1) + [tb] POP + [] <code for S1> + JUMP_FORWARD L0 + + [tb, val, exc, 0] L2: POP + [tb, val, exc] DUP + .............................etc....................... + + [tb, val, exc, 0] Ln+1: POP + [tb, val, exc] END_FINALLY # re-raise exception + + [] L0: <next statement> + + Of course, parts are not generated if Vi or Ei is not present. */ static void com_try_stmt(c, n) - struct compiling *c; - node *n; + struct compiling *c; + node *n; { - int finally_anchor = 0; - int except_anchor = 0; - REQ(n, try_stmt); - /* 'try' ':' suite (except_clause ':' suite)* ['finally' ':' suite] */ - - if (NCH(n) > 3 && TYPE(CHILD(n, NCH(n)-3)) != except_clause) { - /* Have a 'finally' clause */ - com_addfwref(c, SETUP_FINALLY, &finally_anchor); - } - if (NCH(n) > 3 && TYPE(CHILD(n, 3)) == except_clause) { - /* Have an 'except' clause */ - com_addfwref(c, SETUP_EXCEPT, &except_anchor); - } - com_node(c, CHILD(n, 2)); - if (except_anchor) { - int end_anchor = 0; - int i; - node *ch; - com_addbyte(c, POP_BLOCK); - com_addfwref(c, JUMP_FORWARD, &end_anchor); - com_backpatch(c, except_anchor); - for (i = 3; - i < NCH(n) && TYPE(ch = CHILD(n, i)) == except_clause; - i += 3) { - /* except_clause: 'except' [expr [',' expr]] */ - if (except_anchor == 0) { - err_setstr(TypeError, - "default 'except:' must be last"); - c->c_errors++; - break; - } - except_anchor = 0; - com_addoparg(c, SET_LINENO, ch->n_lineno); - if (NCH(ch) > 1) { - com_addbyte(c, DUP_TOP); - com_node(c, CHILD(ch, 1)); - com_addoparg(c, COMPARE_OP, EXC_MATCH); - com_addfwref(c, JUMP_IF_FALSE, &except_anchor); - com_addbyte(c, POP_TOP); - } - com_addbyte(c, POP_TOP); - if (NCH(ch) > 3) - com_assign(c, CHILD(ch, 3), 1/*assigning*/); - else - com_addbyte(c, POP_TOP); - com_addbyte(c, POP_TOP); - com_node(c, CHILD(n, i+2)); - com_addfwref(c, JUMP_FORWARD, &end_anchor); - if (except_anchor) { - com_backpatch(c, except_anchor); - com_addbyte(c, POP_TOP); - } - } - com_addbyte(c, END_FINALLY); - com_backpatch(c, end_anchor); - } - if (finally_anchor) { - node *ch; - com_addbyte(c, POP_BLOCK); - com_addoparg(c, LOAD_CONST, com_addconst(c, None)); - com_backpatch(c, finally_anchor); - ch = CHILD(n, NCH(n)-1); - com_addoparg(c, SET_LINENO, ch->n_lineno); - com_node(c, ch); - com_addbyte(c, END_FINALLY); - } + int finally_anchor = 0; + int except_anchor = 0; + REQ(n, try_stmt); + /* 'try' ':' suite (except_clause ':' suite)* ['finally' ':' suite] */ + + if (NCH(n) > 3 && TYPE(CHILD(n, NCH(n)-3)) != except_clause) { + /* Have a 'finally' clause */ + com_addfwref(c, SETUP_FINALLY, &finally_anchor); + } + if (NCH(n) > 3 && TYPE(CHILD(n, 3)) == except_clause) { + /* Have an 'except' clause */ + com_addfwref(c, SETUP_EXCEPT, &except_anchor); + } + com_node(c, CHILD(n, 2)); + if (except_anchor) { + int end_anchor = 0; + int i; + node *ch; + com_addbyte(c, POP_BLOCK); + com_addfwref(c, JUMP_FORWARD, &end_anchor); + com_backpatch(c, except_anchor); + for (i = 3; + i < NCH(n) && TYPE(ch = CHILD(n, i)) == except_clause; + i += 3) { + /* except_clause: 'except' [expr [',' expr]] */ + if (except_anchor == 0) { + err_setstr(TypeError, + "default 'except:' must be last"); + c->c_errors++; + break; + } + except_anchor = 0; + com_addoparg(c, SET_LINENO, ch->n_lineno); + if (NCH(ch) > 1) { + com_addbyte(c, DUP_TOP); + com_node(c, CHILD(ch, 1)); + com_addoparg(c, COMPARE_OP, EXC_MATCH); + com_addfwref(c, JUMP_IF_FALSE, &except_anchor); + com_addbyte(c, POP_TOP); + } + com_addbyte(c, POP_TOP); + if (NCH(ch) > 3) + com_assign(c, CHILD(ch, 3), 1/*assigning*/); + else + com_addbyte(c, POP_TOP); + com_addbyte(c, POP_TOP); + com_node(c, CHILD(n, i+2)); + com_addfwref(c, JUMP_FORWARD, &end_anchor); + if (except_anchor) { + com_backpatch(c, except_anchor); + com_addbyte(c, POP_TOP); + } + } + com_addbyte(c, END_FINALLY); + com_backpatch(c, end_anchor); + } + if (finally_anchor) { + node *ch; + com_addbyte(c, POP_BLOCK); + com_addoparg(c, LOAD_CONST, com_addconst(c, None)); + com_backpatch(c, finally_anchor); + ch = CHILD(n, NCH(n)-1); + com_addoparg(c, SET_LINENO, ch->n_lineno); + com_node(c, ch); + com_addbyte(c, END_FINALLY); + } } static void com_suite(c, n) - struct compiling *c; - node *n; + struct compiling *c; + node *n; { - REQ(n, suite); - /* simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT */ - if (NCH(n) == 1) { - com_node(c, CHILD(n, 0)); - } - else { - int i; - for (i = 0; i < NCH(n); i++) { - node *ch = CHILD(n, i); - if (TYPE(ch) == stmt) - com_node(c, ch); - } - } + REQ(n, suite); + /* simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT */ + if (NCH(n) == 1) { + com_node(c, CHILD(n, 0)); + } + else { + int i; + for (i = 0; i < NCH(n); i++) { + node *ch = CHILD(n, i); + if (TYPE(ch) == stmt) + com_node(c, ch); + } + } } static void com_funcdef(c, n) - struct compiling *c; - node *n; + struct compiling *c; + node *n; { - object *v; - REQ(n, funcdef); /* funcdef: 'def' NAME parameters ':' suite */ - v = (object *)compile(n, c->c_filename); - if (v == NULL) - c->c_errors++; - else { - int i = com_addconst(c, v); - com_addoparg(c, LOAD_CONST, i); - com_addbyte(c, BUILD_FUNCTION); - com_addopname(c, STORE_NAME, CHILD(n, 1)); - DECREF(v); - } + object *v; + REQ(n, funcdef); /* funcdef: 'def' NAME parameters ':' suite */ + v = (object *)compile(n, c->c_filename); + if (v == NULL) + c->c_errors++; + else { + int i = com_addconst(c, v); + com_addoparg(c, LOAD_CONST, i); + com_addbyte(c, BUILD_FUNCTION); + com_addopname(c, STORE_NAME, CHILD(n, 1)); + DECREF(v); + } } static void com_bases(c, n) - struct compiling *c; - node *n; + struct compiling *c; + node *n; { - int i, nbases; - REQ(n, baselist); - /* - baselist: atom arguments (',' atom arguments)* - arguments: '(' [testlist] ')' - */ - for (i = 0; i < NCH(n); i += 3) - com_node(c, CHILD(n, i)); - com_addoparg(c, BUILD_TUPLE, (NCH(n)+1) / 3); + int i, nbases; + REQ(n, baselist); + /* + baselist: atom arguments (',' atom arguments)* + arguments: '(' [testlist] ')' + */ + for (i = 0; i < NCH(n); i += 3) + com_node(c, CHILD(n, i)); + com_addoparg(c, BUILD_TUPLE, (NCH(n)+1) / 3); } static void com_classdef(c, n) - struct compiling *c; - node *n; + struct compiling *c; + node *n; { - object *v; - REQ(n, classdef); - /* - classdef: 'class' NAME parameters ['=' baselist] ':' suite - baselist: atom arguments (',' atom arguments)* - arguments: '(' [testlist] ')' - */ - if (NCH(n) == 7) - com_bases(c, CHILD(n, 4)); - else - com_addoparg(c, LOAD_CONST, com_addconst(c, None)); - v = (object *)compile(n, c->c_filename); - if (v == NULL) - c->c_errors++; - else { - int i = com_addconst(c, v); - com_addoparg(c, LOAD_CONST, i); - com_addbyte(c, BUILD_FUNCTION); - com_addbyte(c, UNARY_CALL); - com_addbyte(c, BUILD_CLASS); - com_addopname(c, STORE_NAME, CHILD(n, 1)); - DECREF(v); - } + object *v; + REQ(n, classdef); + /* + classdef: 'class' NAME parameters ['=' baselist] ':' suite + baselist: atom arguments (',' atom arguments)* + arguments: '(' [testlist] ')' + */ + if (NCH(n) == 7) + com_bases(c, CHILD(n, 4)); + else + com_addoparg(c, LOAD_CONST, com_addconst(c, None)); + v = (object *)compile(n, c->c_filename); + if (v == NULL) + c->c_errors++; + else { + int i = com_addconst(c, v); + com_addoparg(c, LOAD_CONST, i); + com_addbyte(c, BUILD_FUNCTION); + com_addbyte(c, UNARY_CALL); + com_addbyte(c, BUILD_CLASS); + com_addopname(c, STORE_NAME, CHILD(n, 1)); + DECREF(v); + } } static void com_node(c, n) - struct compiling *c; - node *n; + struct compiling *c; + node *n; { - switch (TYPE(n)) { - - /* Definition nodes */ - - case funcdef: - com_funcdef(c, n); - break; - case classdef: - com_classdef(c, n); - break; - - /* Trivial parse tree nodes */ - - case stmt: - case flow_stmt: - com_node(c, CHILD(n, 0)); - break; - - case simple_stmt: - case compound_stmt: - com_addoparg(c, SET_LINENO, n->n_lineno); - com_node(c, CHILD(n, 0)); - break; - - /* Statement nodes */ - - case expr_stmt: - com_expr_stmt(c, n); - break; - case print_stmt: - com_print_stmt(c, n); - break; - case del_stmt: /* 'del' exprlist NEWLINE */ - com_assign(c, CHILD(n, 1), 0/*delete*/); - break; - case pass_stmt: - break; - case break_stmt: - if (c->c_loops == 0) { - err_setstr(TypeError, "'break' outside loop"); - c->c_errors++; - } - com_addbyte(c, BREAK_LOOP); - break; - case return_stmt: - com_return_stmt(c, n); - break; - case raise_stmt: - com_raise_stmt(c, n); - break; - case import_stmt: - com_import_stmt(c, n); - break; - case if_stmt: - com_if_stmt(c, n); - break; - case while_stmt: - com_while_stmt(c, n); - break; - case for_stmt: - com_for_stmt(c, n); - break; - case try_stmt: - com_try_stmt(c, n); - break; - case suite: - com_suite(c, n); - break; - - /* Expression nodes */ - - case testlist: - com_list(c, n); - break; - case test: - com_test(c, n); - break; - case and_test: - com_and_test(c, n); - break; - case not_test: - com_not_test(c, n); - break; - case comparison: - com_comparison(c, n); - break; - case exprlist: - com_list(c, n); - break; - case expr: - com_expr(c, n); - break; - case term: - com_term(c, n); - break; - case factor: - com_factor(c, n); - break; - case atom: - com_atom(c, n); - break; - - default: - fprintf(stderr, "node type %d\n", TYPE(n)); - err_setstr(SystemError, "com_node: unexpected node type"); - c->c_errors++; - } + switch (TYPE(n)) { + + /* Definition nodes */ + + case funcdef: + com_funcdef(c, n); + break; + case classdef: + com_classdef(c, n); + break; + + /* Trivial parse tree nodes */ + + case stmt: + case flow_stmt: + com_node(c, CHILD(n, 0)); + break; + + case simple_stmt: + case compound_stmt: + com_addoparg(c, SET_LINENO, n->n_lineno); + com_node(c, CHILD(n, 0)); + break; + + /* Statement nodes */ + + case expr_stmt: + com_expr_stmt(c, n); + break; + case print_stmt: + com_print_stmt(c, n); + break; + case del_stmt: /* 'del' exprlist NEWLINE */ + com_assign(c, CHILD(n, 1), 0/*delete*/); + break; + case pass_stmt: + break; + case break_stmt: + if (c->c_loops == 0) { + err_setstr(TypeError, "'break' outside loop"); + c->c_errors++; + } + com_addbyte(c, BREAK_LOOP); + break; + case return_stmt: + com_return_stmt(c, n); + break; + case raise_stmt: + com_raise_stmt(c, n); + break; + case import_stmt: + com_import_stmt(c, n); + break; + case if_stmt: + com_if_stmt(c, n); + break; + case while_stmt: + com_while_stmt(c, n); + break; + case for_stmt: + com_for_stmt(c, n); + break; + case try_stmt: + com_try_stmt(c, n); + break; + case suite: + com_suite(c, n); + break; + + /* Expression nodes */ + + case testlist: + com_list(c, n); + break; + case test: + com_test(c, n); + break; + case and_test: + com_and_test(c, n); + break; + case not_test: + com_not_test(c, n); + break; + case comparison: + com_comparison(c, n); + break; + case exprlist: + com_list(c, n); + break; + case expr: + com_expr(c, n); + break; + case term: + com_term(c, n); + break; + case factor: + com_factor(c, n); + break; + case atom: + com_atom(c, n); + break; + + default: + fprintf(stderr, "node type %d\n", TYPE(n)); + err_setstr(SystemError, "com_node: unexpected node type"); + c->c_errors++; + } } static void com_fplist PROTO((struct compiling *, node *)); static void com_fpdef(c, n) - struct compiling *c; - node *n; + struct compiling *c; + node *n; { - REQ(n, fpdef); /* fpdef: NAME | '(' fplist ')' */ - if (TYPE(CHILD(n, 0)) == LPAR) - com_fplist(c, CHILD(n, 1)); - else - com_addopname(c, STORE_NAME, CHILD(n, 0)); + REQ(n, fpdef); /* fpdef: NAME | '(' fplist ')' */ + if (TYPE(CHILD(n, 0)) == LPAR) + com_fplist(c, CHILD(n, 1)); + else + com_addopname(c, STORE_NAME, CHILD(n, 0)); } static void com_fplist(c, n) - struct compiling *c; - node *n; + struct compiling *c; + node *n; { - REQ(n, fplist); /* fplist: fpdef (',' fpdef)* */ - if (NCH(n) == 1) { - com_fpdef(c, CHILD(n, 0)); - } - else { - int i; - com_addoparg(c, UNPACK_TUPLE, (NCH(n)+1)/2); - for (i = 0; i < NCH(n); i += 2) - com_fpdef(c, CHILD(n, i)); - } + REQ(n, fplist); /* fplist: fpdef (',' fpdef)* */ + if (NCH(n) == 1) { + com_fpdef(c, CHILD(n, 0)); + } + else { + int i; + com_addoparg(c, UNPACK_TUPLE, (NCH(n)+1)/2); + for (i = 0; i < NCH(n); i += 2) + com_fpdef(c, CHILD(n, i)); + } } static void com_file_input(c, n) - struct compiling *c; - node *n; + struct compiling *c; + node *n; { - int i; - REQ(n, file_input); /* (NEWLINE | stmt)* ENDMARKER */ - for (i = 0; i < NCH(n); i++) { - node *ch = CHILD(n, i); - if (TYPE(ch) != ENDMARKER && TYPE(ch) != NEWLINE) - com_node(c, ch); - } + int i; + REQ(n, file_input); /* (NEWLINE | stmt)* ENDMARKER */ + for (i = 0; i < NCH(n); i++) { + node *ch = CHILD(n, i); + if (TYPE(ch) != ENDMARKER && TYPE(ch) != NEWLINE) + com_node(c, ch); + } } /* Top-level compile-node interface */ static void compile_funcdef(c, n) - struct compiling *c; - node *n; + struct compiling *c; + node *n; { - node *ch; - REQ(n, funcdef); /* funcdef: 'def' NAME parameters ':' suite */ - ch = CHILD(n, 2); /* parameters: '(' [fplist] ')' */ - ch = CHILD(ch, 1); /* ')' | fplist */ - if (TYPE(ch) == RPAR) - com_addbyte(c, REFUSE_ARGS); - else { - com_addbyte(c, REQUIRE_ARGS); - com_fplist(c, ch); - } - c->c_infunction = 1; - com_node(c, CHILD(n, 4)); - c->c_infunction = 0; - com_addoparg(c, LOAD_CONST, com_addconst(c, None)); - com_addbyte(c, RETURN_VALUE); + node *ch; + REQ(n, funcdef); /* funcdef: 'def' NAME parameters ':' suite */ + ch = CHILD(n, 2); /* parameters: '(' [fplist] ')' */ + ch = CHILD(ch, 1); /* ')' | fplist */ + if (TYPE(ch) == RPAR) + com_addbyte(c, REFUSE_ARGS); + else { + com_addbyte(c, REQUIRE_ARGS); + com_fplist(c, ch); + } + c->c_infunction = 1; + com_node(c, CHILD(n, 4)); + c->c_infunction = 0; + com_addoparg(c, LOAD_CONST, com_addconst(c, None)); + com_addbyte(c, RETURN_VALUE); } static void compile_node(c, n) - struct compiling *c; - node *n; + struct compiling *c; + node *n; { - com_addoparg(c, SET_LINENO, n->n_lineno); - - switch (TYPE(n)) { - - case single_input: /* One interactive command */ - /* NEWLINE | simple_stmt | compound_stmt NEWLINE */ - com_addbyte(c, REFUSE_ARGS); - n = CHILD(n, 0); - if (TYPE(n) != NEWLINE) - com_node(c, n); - com_addoparg(c, LOAD_CONST, com_addconst(c, None)); - com_addbyte(c, RETURN_VALUE); - break; - - case file_input: /* A whole file, or built-in function exec() */ - com_addbyte(c, REFUSE_ARGS); - com_file_input(c, n); - com_addoparg(c, LOAD_CONST, com_addconst(c, None)); - com_addbyte(c, RETURN_VALUE); - break; - - case expr_input: /* Built-in function eval() */ - com_addbyte(c, REFUSE_ARGS); - com_node(c, CHILD(n, 0)); - com_addbyte(c, RETURN_VALUE); - break; - - case eval_input: /* Built-in function input() */ - com_addbyte(c, REFUSE_ARGS); - com_node(c, CHILD(n, 0)); - com_addbyte(c, RETURN_VALUE); - break; - - case funcdef: /* A function definition */ - compile_funcdef(c, n); - break; - - case classdef: /* A class definition */ - /* 'class' NAME parameters ['=' baselist] ':' suite */ - com_addbyte(c, REFUSE_ARGS); - com_node(c, CHILD(n, NCH(n)-1)); - com_addbyte(c, LOAD_LOCALS); - com_addbyte(c, RETURN_VALUE); - break; - - default: - fprintf(stderr, "node type %d\n", TYPE(n)); - err_setstr(SystemError, "compile_node: unexpected node type"); - c->c_errors++; - } + com_addoparg(c, SET_LINENO, n->n_lineno); + + switch (TYPE(n)) { + + case single_input: /* One interactive command */ + /* NEWLINE | simple_stmt | compound_stmt NEWLINE */ + com_addbyte(c, REFUSE_ARGS); + n = CHILD(n, 0); + if (TYPE(n) != NEWLINE) + com_node(c, n); + com_addoparg(c, LOAD_CONST, com_addconst(c, None)); + com_addbyte(c, RETURN_VALUE); + break; + + case file_input: /* A whole file, or built-in function exec() */ + com_addbyte(c, REFUSE_ARGS); + com_file_input(c, n); + com_addoparg(c, LOAD_CONST, com_addconst(c, None)); + com_addbyte(c, RETURN_VALUE); + break; + + case expr_input: /* Built-in function eval() */ + com_addbyte(c, REFUSE_ARGS); + com_node(c, CHILD(n, 0)); + com_addbyte(c, RETURN_VALUE); + break; + + case eval_input: /* Built-in function input() */ + com_addbyte(c, REFUSE_ARGS); + com_node(c, CHILD(n, 0)); + com_addbyte(c, RETURN_VALUE); + break; + + case funcdef: /* A function definition */ + compile_funcdef(c, n); + break; + + case classdef: /* A class definition */ + /* 'class' NAME parameters ['=' baselist] ':' suite */ + com_addbyte(c, REFUSE_ARGS); + com_node(c, CHILD(n, NCH(n)-1)); + com_addbyte(c, LOAD_LOCALS); + com_addbyte(c, RETURN_VALUE); + break; + + default: + fprintf(stderr, "node type %d\n", TYPE(n)); + err_setstr(SystemError, "compile_node: unexpected node type"); + c->c_errors++; + } } codeobject * compile(n, filename) - node *n; - char *filename; + node *n; + char *filename; { - struct compiling sc; - codeobject *co; - if (!com_init(&sc, filename)) - return NULL; - compile_node(&sc, n); - com_done(&sc); - if (sc.c_errors == 0) - co = newcodeobject(sc.c_code, sc.c_consts, sc.c_names, filename); - else - co = NULL; - com_free(&sc); - return co; + struct compiling sc; + codeobject *co; + if (!com_init(&sc, filename)) + return NULL; + compile_node(&sc, n); + com_done(&sc); + if (sc.c_errors == 0) + co = newcodeobject(sc.c_code, sc.c_consts, sc.c_names, filename); + else + co = NULL; + com_free(&sc); + return co; } diff --git a/src/compile.h b/src/compile.h index fb66ea7..cb75b51 100644 --- a/src/compile.h +++ b/src/compile.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -26,16 +26,16 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* An intermediate code fragment contains: - - a string that encodes the instructions, - - a list of the constants, - - and a list of the names used. */ + - a string that encodes the instructions, + - a list of the constants, + - and a list of the names used. */ typedef struct { - OB_HEAD - stringobject *co_code; /* instruction opcodes */ - object *co_consts; /* list of immutable constant objects */ - object *co_names; /* list of stringobjects */ - object *co_filename; /* string */ + OB_HEAD + stringobject *co_code; /* instruction opcodes */ + object *co_consts; /* list of immutable constant objects */ + object *co_names; /* list of stringobjects */ + object *co_filename; /* string */ } codeobject; extern typeobject Codetype; diff --git a/src/config.c b/src/config.c index 9d153c1..f81a5bd 100644 --- a/src/config.c +++ b/src/config.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -35,41 +35,41 @@ static int use_stdwin; /*ARGSUSED*/ void initargs(p_argc, p_argv) - int *p_argc; - char ***p_argv; + int *p_argc; + char ***p_argv; { #ifdef USE_STDWIN - extern char *getenv(); - char *display; - - /* Ignore an initial argument of '-s', for backward compatibility */ - if (*p_argc > 1 && strcmp((*p_argv)[1], "-s") == 0) { - (*p_argv)[1] = (*p_argv)[0]; - (*p_argc)--, (*p_argv)++; - } - - /* Assume we have to initialize stdwin if either of the following - conditions holds: - - the environment variable $DISPLAY is set - - there is an argument "-display" somewhere - */ - - display = getenv("DISPLAY"); - if (display != 0) - use_stdwin = 1; - else { - int i; - /* Scan through the arguments looking for "-display" */ - for (i = 1; i < *p_argc; i++) { - if (strcmp((*p_argv)[i], "-display") == 0) { - use_stdwin = 1; - break; - } - } - } - - if (use_stdwin) - wargs(p_argc, p_argv); + extern char *getenv(); + char *display; + + /* Ignore an initial argument of '-s', for backward compatibility */ + if (*p_argc > 1 && strcmp((*p_argv)[1], "-s") == 0) { + (*p_argv)[1] = (*p_argv)[0]; + (*p_argc)--, (*p_argv)++; + } + + /* Assume we have to initialize stdwin if either of the following + conditions holds: + - the environment variable $DISPLAY is set + - there is an argument "-display" somewhere + */ + + display = getenv("DISPLAY"); + if (display != 0) + use_stdwin = 1; + else { + int i; + /* Scan through the arguments looking for "-display" */ + for (i = 1; i < *p_argc; i++) { + if (strcmp((*p_argv)[i], "-display") == 0) { + use_stdwin = 1; + break; + } + } + } + + if (use_stdwin) + wargs(p_argc, p_argv); #endif } @@ -82,11 +82,11 @@ void donecalls() { #ifdef USE_STDWIN - if (use_stdwin) - wdone(); + if (use_stdwin) + wdone(); #endif #ifdef USE_AUDIO - asa_done(); + asa_done(); #endif } @@ -94,11 +94,11 @@ donecalls() static void maybeinitstdwin() { - if (use_stdwin) - initstdwin(); - else - fprintf(stderr, - "No $DISPLAY nor -display arg -- stdwin not available\n"); + if (use_stdwin) + initstdwin(); + else + fprintf(stderr, + "No $DISPLAY nor -display arg -- stdwin not available\n"); } #endif @@ -111,15 +111,15 @@ extern char *getenv(); char * getpythonpath() { - char *path = getenv("PYTHONPATH"); - if (path == 0) - path = PYTHONPATH; - return path; + char *path = getenv("PYTHONPATH"); + if (path == 0) + path = PYTHONPATH; + return path; } /* Table of built-in modules. - These are initialized when first imported. */ + These are initialized when first imported. */ /* Standard modules */ extern void inittime(); @@ -143,38 +143,38 @@ extern void maybeinitstdwin(); #endif struct { - char *name; - void (*initfunc)(); + char *name; + void (*initfunc)(); } inittab[] = { - /* Standard modules */ + /* Standard modules */ - {"time", inittime}, - {"math", initmath}, - {"regexp", initregexp}, - {"posix", initposix}, + {"time", inittime}, + {"math", initmath}, + {"regexp", initregexp}, + {"posix", initposix}, - /* Optional modules */ + /* Optional modules */ #ifdef USE_AUDIO - {"audio", initaudio}, + {"audio", initaudio}, #endif #ifdef USE_AMOEBA - {"amoeba", initamoeba}, + {"amoeba", initamoeba}, #endif #ifdef USE_GL - {"gl", initgl}, + {"gl", initgl}, #ifdef USE_PANEL - {"pnl", initpanel}, + {"pnl", initpanel}, #endif #endif #ifdef USE_STDWIN - {"stdwin", maybeinitstdwin}, + {"stdwin", maybeinitstdwin}, #endif - {0, 0} /* Sentinel */ + {0, 0} /* Sentinel */ }; diff --git a/src/configmac.c b/src/configmac.c index c73130a..0b406a8 100644 --- a/src/configmac.c +++ b/src/configmac.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -34,21 +34,21 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. void initargs(p_argc, p_argv) - int *p_argc; - char ***p_argv; + int *p_argc; + char ***p_argv; { #ifdef USE_STDWIN #ifdef THINK_C_3_0 - wsetstdio(1); + wsetstdio(1); #else - /* This printf() statement is really needed only - to initialize THINK C 4.0's stdio: */ - printf( + /* This printf() statement is really needed only + to initialize THINK C 4.0's stdio: */ + printf( "Python 4.0, Copyright 1990 Stichting Mathematisch Centrum, Amsterdam\n"); #endif - wargs(p_argc, p_argv); + wargs(p_argc, p_argv); #endif } @@ -61,7 +61,7 @@ void donecalls() { #ifdef USE_STDWIN - wdone(); + wdone(); #endif } @@ -73,18 +73,18 @@ donecalls() char * getpythonpath() { - return PYTHONPATH; + return PYTHONPATH; } /* Table of built-in modules. - These are initialized when first imported. */ + These are initialized when first imported. */ /* Standard modules */ extern void inittime(); extern void initmath(); extern void initregexp(); - + /* Mac-specific modules */ extern void initmac(); #ifdef USE_STDWIN @@ -92,18 +92,18 @@ extern void initstdwin(); #endif struct { - char *name; - void (*initfunc)(); + char *name; + void (*initfunc)(); } inittab[] = { - /* Standard modules */ - {"time", inittime}, - {"math", initmath}, - {"regexp", initregexp}, - - /* Mac-specific modules */ - {"mac", initmac}, + /* Standard modules */ + {"time", inittime}, + {"math", initmath}, + {"regexp", initregexp}, + + /* Mac-specific modules */ + {"mac", initmac}, #ifdef USE_STDWIN - {"stdwin", initstdwin}, + {"stdwin", initstdwin}, #endif - {0, 0} /* Sentinel */ + {0, 0} /* Sentinel */ }; @@ -9,20 +9,20 @@ Each definition must be contained on one line: <returntype> can be: void, short, long (XXX maybe others?) <type> can be: char, string, short, float, long, or double - string indicates a null terminated string; - if <type> is char and <arg> begins with a *, the * is stripped - and <type> is changed into string + string indicates a null terminated string; + if <type> is char and <arg> begins with a *, the * is stripped + and <type> is changed into string <arg> has the form <mode> or <mode>[<subscript>] - where <mode> can be - s: arg is sent - r: arg is received (arg is a pointer) - and <subscript> can be (N and I are numbers): - N - argI - retval - N*argI - N*retval + where <mode> can be + s: arg is sent + r: arg is received (arg is a pointer) + and <subscript> can be (N and I are numbers): + N + argI + retval + N*argI + N*retval */ #include <gl.h> @@ -45,7 +45,7 @@ varray -- an array of v.. calls. The argument is an array (maybe list or tuple) of points. Each point must be a tuple or list of coordinates (x, y, z). The points may be 2- or 3-dimensional but must all have the -same dimension. Float and int values may be mixed however. +same dimension. Float and int values may be mixed however. The points are always converted to 3D double precision points by assuming z=0.0 if necessary (as indicated in the man page), and for each point v3d() is called. @@ -55,67 +55,67 @@ and for each point v3d() is called. static object * gl_varray(self, args) - object *self; - object *args; + object *self; + object *args; { - object *v, *w; - int i, n, width; - double vec[3]; - object * (*getitem) FPROTO((object *, int)); - - if (!getiobjectarg(args, 1, 0, &v)) - return NULL; - - if (is_listobject(v)) { - n = getlistsize(v); - getitem = getlistitem; - } - else if (is_tupleobject(v)) { - n = gettuplesize(v); - getitem = gettupleitem; - } - else { - err_badarg(); - return NULL; - } - - if (n == 0) { - INCREF(None); - return None; - } - if (n > 0) - w = (*getitem)(v, 0); - - width = 0; - if (w == NULL) { - } - else if (is_listobject(w)) { - width = getlistsize(w); - } - else if (is_tupleobject(w)) { - width = gettuplesize(w); - } - - switch (width) { - case 2: - vec[2] = 0.0; - /* Fall through */ - case 3: - break; - default: - err_badarg(); - return NULL; - } - - for (i = 0; i < n; i++) { - w = (*getitem)(v, i); - if (!getidoublearray(w, 1, 0, width, vec)) - return NULL; - v3d(vec); - } - - INCREF(None); - return None; + object *v, *w; + int i, n, width; + double vec[3]; + object * (*getitem) FPROTO((object *, int)); + + if (!getiobjectarg(args, 1, 0, &v)) + return NULL; + + if (is_listobject(v)) { + n = getlistsize(v); + getitem = getlistitem; + } + else if (is_tupleobject(v)) { + n = gettuplesize(v); + getitem = gettupleitem; + } + else { + err_badarg(); + return NULL; + } + + if (n == 0) { + INCREF(None); + return None; + } + if (n > 0) + w = (*getitem)(v, 0); + + width = 0; + if (w == NULL) { + } + else if (is_listobject(w)) { + width = getlistsize(w); + } + else if (is_tupleobject(w)) { + width = gettuplesize(w); + } + + switch (width) { + case 2: + vec[2] = 0.0; + /* Fall through */ + case 3: + break; + default: + err_badarg(); + return NULL; + } + + for (i = 0; i < n; i++) { + w = (*getitem)(v, i); + if (!getidoublearray(w, 1, 0, width, vec)) + return NULL; + v3d(vec); + } + + INCREF(None); + return None; } /* @@ -123,7 +123,7 @@ vnarray, nvarray -- an array of n3f and v3f calls. The argument is an array (list or tuple) of pairs of points and normals. Each pair is a tuple (NOT a list) of a point and a normal for that point. Each point or normal must be a tuple (NOT a list) of coordinates (x, y, z). -Three coordinates must be given. Float and int values may be mixed. +Three coordinates must be given. Float and int values may be mixed. For each pair, n3f() is called for the normal, and then v3f() is called for the vector. @@ -137,267 +137,267 @@ static object *gen_nvarray(); /* Forward */ static object * gl_nvarray(self, args) - object *self; - object *args; + object *self; + object *args; { - return gen_nvarray(args, 0); + return gen_nvarray(args, 0); } % vnarray static object * gl_vnarray(self, args) - object *self; - object *args; + object *self; + object *args; { - return gen_nvarray(args, 1); + return gen_nvarray(args, 1); } /* Generic, internal version of {nv,nv}array: inorm indicates the - argument order, 0: normal first, 1: vector first. */ + argument order, 0: normal first, 1: vector first. */ static object * gen_nvarray(args, inorm) - object *args; - int inorm; + object *args; + int inorm; { - object *v, *w, *wnorm, *wvec; - int i, n; - float norm[3], vec[3]; - object * (*getitem) FPROTO((object *, int)); - - if (!getiobjectarg(args, 1, 0, &v)) - return NULL; - - if (is_listobject(v)) { - n = getlistsize(v); - getitem = getlistitem; - } - else if (is_tupleobject(v)) { - n = gettuplesize(v); - getitem = gettupleitem; - } - else { - err_badarg(); - return NULL; - } - - for (i = 0; i < n; i++) { - w = (*getitem)(v, i); - if (!is_tupleobject(w) || gettuplesize(w) != 2) { - err_badarg(); - return NULL; - } - wnorm = gettupleitem(w, inorm); - wvec = gettupleitem(w, 1 - inorm); - if (!getifloatarray(wnorm, 1, 0, 3, norm) || - !getifloatarray(wvec, 1, 0, 3, vec)) - return NULL; - n3f(norm); - v3f(vec); - } - - INCREF(None); - return None; + object *v, *w, *wnorm, *wvec; + int i, n; + float norm[3], vec[3]; + object * (*getitem) FPROTO((object *, int)); + + if (!getiobjectarg(args, 1, 0, &v)) + return NULL; + + if (is_listobject(v)) { + n = getlistsize(v); + getitem = getlistitem; + } + else if (is_tupleobject(v)) { + n = gettuplesize(v); + getitem = gettupleitem; + } + else { + err_badarg(); + return NULL; + } + + for (i = 0; i < n; i++) { + w = (*getitem)(v, i); + if (!is_tupleobject(w) || gettuplesize(w) != 2) { + err_badarg(); + return NULL; + } + wnorm = gettupleitem(w, inorm); + wvec = gettupleitem(w, 1 - inorm); + if (!getifloatarray(wnorm, 1, 0, 3, norm) || + !getifloatarray(wvec, 1, 0, 3, vec)) + return NULL; + n3f(norm); + v3f(vec); + } + + INCREF(None); + return None; } /* nurbssurface(s_knots[], t_knots[], ctl[][], s_order, t_order, type). - The dimensions of ctl[] are computed as follows: - [len(s_knots) - s_order], [len(t_knots) - t_order] + The dimensions of ctl[] are computed as follows: + [len(s_knots) - s_order], [len(t_knots) - t_order] */ % nurbssurface static object * gl_nurbssurface(self, args) - object *self; - object *args; + object *self; + object *args; { - long arg1 ; - double * arg2 ; - long arg3 ; - double * arg4 ; - double *arg5 ; - long arg6 ; - long arg7 ; - long arg8 ; - long ncoords; - long s_byte_stride, t_byte_stride; - long s_nctl, t_nctl; - long s, t; - object *v, *w, *pt; - double *pnext; - if (!getilongarraysize(args, 6, 0, &arg1)) - return NULL; - if ((arg2 = NEW(double, arg1 )) == NULL) { - return err_nomem(); - } - if (!getidoublearray(args, 6, 0, arg1 , arg2)) - return NULL; - if (!getilongarraysize(args, 6, 1, &arg3)) - return NULL; - if ((arg4 = NEW(double, arg3 )) == NULL) { - return err_nomem(); - } - if (!getidoublearray(args, 6, 1, arg3 , arg4)) - return NULL; - if (!getilongarg(args, 6, 3, &arg6)) - return NULL; - if (!getilongarg(args, 6, 4, &arg7)) - return NULL; - if (!getilongarg(args, 6, 5, &arg8)) - return NULL; - if (arg8 == N_XYZ) - ncoords = 3; - else if (arg8 == N_XYZW) - ncoords = 4; - else { - err_badarg(); - return NULL; - } - s_nctl = arg1 - arg6; - t_nctl = arg3 - arg7; - if (!getiobjectarg(args, 6, 2, &v)) - return NULL; - if (!is_listobject(v) || getlistsize(v) != s_nctl) { - err_badarg(); - return NULL; - } - if ((arg5 = NEW(double, s_nctl*t_nctl*ncoords )) == NULL) { - return err_nomem(); - } - pnext = arg5; - for (s = 0; s < s_nctl; s++) { - w = getlistitem(v, s); - if (w == NULL || !is_listobject(w) || - getlistsize(w) != t_nctl) { - err_badarg(); - return NULL; - } - for (t = 0; t < t_nctl; t++) { - pt = getlistitem(w, t); - if (!getidoublearray(pt, 1, 0, ncoords, pnext)) - return NULL; - pnext += ncoords; - } - } - s_byte_stride = sizeof(double) * ncoords; - t_byte_stride = s_byte_stride * s_nctl; - nurbssurface( arg1 , arg2 , arg3 , arg4 , - s_byte_stride , t_byte_stride , arg5 , arg6 , arg7 , arg8 ); - DEL(arg2); - DEL(arg4); - DEL(arg5); - INCREF(None); - return None; + long arg1 ; + double * arg2 ; + long arg3 ; + double * arg4 ; + double *arg5 ; + long arg6 ; + long arg7 ; + long arg8 ; + long ncoords; + long s_byte_stride, t_byte_stride; + long s_nctl, t_nctl; + long s, t; + object *v, *w, *pt; + double *pnext; + if (!getilongarraysize(args, 6, 0, &arg1)) + return NULL; + if ((arg2 = NEW(double, arg1 )) == NULL) { + return err_nomem(); + } + if (!getidoublearray(args, 6, 0, arg1 , arg2)) + return NULL; + if (!getilongarraysize(args, 6, 1, &arg3)) + return NULL; + if ((arg4 = NEW(double, arg3 )) == NULL) { + return err_nomem(); + } + if (!getidoublearray(args, 6, 1, arg3 , arg4)) + return NULL; + if (!getilongarg(args, 6, 3, &arg6)) + return NULL; + if (!getilongarg(args, 6, 4, &arg7)) + return NULL; + if (!getilongarg(args, 6, 5, &arg8)) + return NULL; + if (arg8 == N_XYZ) + ncoords = 3; + else if (arg8 == N_XYZW) + ncoords = 4; + else { + err_badarg(); + return NULL; + } + s_nctl = arg1 - arg6; + t_nctl = arg3 - arg7; + if (!getiobjectarg(args, 6, 2, &v)) + return NULL; + if (!is_listobject(v) || getlistsize(v) != s_nctl) { + err_badarg(); + return NULL; + } + if ((arg5 = NEW(double, s_nctl*t_nctl*ncoords )) == NULL) { + return err_nomem(); + } + pnext = arg5; + for (s = 0; s < s_nctl; s++) { + w = getlistitem(v, s); + if (w == NULL || !is_listobject(w) || + getlistsize(w) != t_nctl) { + err_badarg(); + return NULL; + } + for (t = 0; t < t_nctl; t++) { + pt = getlistitem(w, t); + if (!getidoublearray(pt, 1, 0, ncoords, pnext)) + return NULL; + pnext += ncoords; + } + } + s_byte_stride = sizeof(double) * ncoords; + t_byte_stride = s_byte_stride * s_nctl; + nurbssurface( arg1 , arg2 , arg3 , arg4 , + s_byte_stride , t_byte_stride , arg5 , arg6 , arg7 , arg8 ); + DEL(arg2); + DEL(arg4); + DEL(arg5); + INCREF(None); + return None; } /* nurbscurve(knots, ctlpoints, order, type). - The length of ctlpoints is len(knots)-order. */ + The length of ctlpoints is len(knots)-order. */ %nurbscurve static object * gl_nurbscurve(self, args) - object *self; - object *args; + object *self; + object *args; { - long arg1 ; - double * arg2 ; - long arg3 ; - double * arg4 ; - long arg5 ; - long arg6 ; - int ncoords, npoints; - int i; - object *v; - double *pnext; - if (!getilongarraysize(args, 4, 0, &arg1)) - return NULL; - if ((arg2 = NEW(double, arg1 )) == NULL) { - return err_nomem(); - } - if (!getidoublearray(args, 4, 0, arg1 , arg2)) - return NULL; - if (!getilongarg(args, 4, 2, &arg5)) - return NULL; - if (!getilongarg(args, 4, 3, &arg6)) - return NULL; - if (arg6 == N_ST) - ncoords = 2; - else if (arg6 == N_STW) - ncoords = 3; - else { - err_badarg(); - return NULL; - } - npoints = arg1 - arg5; - if (!getiobjectarg(args, 4, 1, &v)) - return NULL; - if (!is_listobject(v) || getlistsize(v) != npoints) { - err_badarg(); - return NULL; - } - if ((arg4 = NEW(double, npoints*ncoords )) == NULL) { - return err_nomem(); - } - pnext = arg4; - for (i = 0; i < npoints; i++) { - if (!getidoublearray(getlistitem(v, i), 1, 0, ncoords, pnext)) - return NULL; - pnext += ncoords; - } - arg3 = (sizeof(double)) * ncoords; - nurbscurve( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 ); - DEL(arg2); - DEL(arg4); - INCREF(None); - return None; + long arg1 ; + double * arg2 ; + long arg3 ; + double * arg4 ; + long arg5 ; + long arg6 ; + int ncoords, npoints; + int i; + object *v; + double *pnext; + if (!getilongarraysize(args, 4, 0, &arg1)) + return NULL; + if ((arg2 = NEW(double, arg1 )) == NULL) { + return err_nomem(); + } + if (!getidoublearray(args, 4, 0, arg1 , arg2)) + return NULL; + if (!getilongarg(args, 4, 2, &arg5)) + return NULL; + if (!getilongarg(args, 4, 3, &arg6)) + return NULL; + if (arg6 == N_ST) + ncoords = 2; + else if (arg6 == N_STW) + ncoords = 3; + else { + err_badarg(); + return NULL; + } + npoints = arg1 - arg5; + if (!getiobjectarg(args, 4, 1, &v)) + return NULL; + if (!is_listobject(v) || getlistsize(v) != npoints) { + err_badarg(); + return NULL; + } + if ((arg4 = NEW(double, npoints*ncoords )) == NULL) { + return err_nomem(); + } + pnext = arg4; + for (i = 0; i < npoints; i++) { + if (!getidoublearray(getlistitem(v, i), 1, 0, ncoords, pnext)) + return NULL; + pnext += ncoords; + } + arg3 = (sizeof(double)) * ncoords; + nurbscurve( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 ); + DEL(arg2); + DEL(arg4); + INCREF(None); + return None; } /* pwlcurve(points, type). - Points is a list of points. Type must be N_ST. */ + Points is a list of points. Type must be N_ST. */ %pwlcurve static object * gl_pwlcurve(self, args) - object *self; - object *args; + object *self; + object *args; { - object *v; - long type; - double *data, *pnext; - long npoints, ncoords; - int i; - if (!getiobjectarg(args, 2, 0, &v)) - return NULL; - if (!getilongarg(args, 2, 1, &type)) - return NULL; - if (!is_listobject(v)) { - err_badarg(); - return NULL; - } - npoints = getlistsize(v); - if (type == N_ST) - ncoords = 2; - else { - err_badarg(); - return NULL; - } - if ((data = NEW(double, npoints*ncoords)) == NULL) { - return err_nomem(); - } - pnext = data; - for (i = 0; i < npoints; i++) { - if (!getidoublearray(getlistitem(v, i), 1, 0, ncoords, pnext)) - return NULL; - pnext += ncoords; - } - pwlcurve(npoints, data, sizeof(double)*ncoords, type); - DEL(data); - INCREF(None); - return None; + object *v; + long type; + double *data, *pnext; + long npoints, ncoords; + int i; + if (!getiobjectarg(args, 2, 0, &v)) + return NULL; + if (!getilongarg(args, 2, 1, &type)) + return NULL; + if (!is_listobject(v)) { + err_badarg(); + return NULL; + } + npoints = getlistsize(v); + if (type == N_ST) + ncoords = 2; + else { + err_badarg(); + return NULL; + } + if ((data = NEW(double, npoints*ncoords)) == NULL) { + return err_nomem(); + } + pnext = data; + for (i = 0; i < npoints; i++) { + if (!getidoublearray(getlistitem(v, i), 1, 0, ncoords, pnext)) + return NULL; + pnext += ncoords; + } + pwlcurve(npoints, data, sizeof(double)*ncoords, type); + DEL(data); + INCREF(None); + return None; } @@ -408,63 +408,63 @@ static long pickbuffersize; static object * pick_select(args, func) - object *args; - void (*func)(); + object *args; + void (*func)(); { - if (!getilongarg(args, 1, 0, &pickbuffersize)) - return NULL; - if (pickbuffer != NULL) { - err_setstr(RuntimeError, - "pick/gselect: already picking/selecting"); - return NULL; - } - if ((pickbuffer = NEW(short, pickbuffersize)) == NULL) { - return err_nomem(); - } - (*func)(pickbuffer, pickbuffersize); - INCREF(None); - return None; + if (!getilongarg(args, 1, 0, &pickbuffersize)) + return NULL; + if (pickbuffer != NULL) { + err_setstr(RuntimeError, + "pick/gselect: already picking/selecting"); + return NULL; + } + if ((pickbuffer = NEW(short, pickbuffersize)) == NULL) { + return err_nomem(); + } + (*func)(pickbuffer, pickbuffersize); + INCREF(None); + return None; } static object * endpick_select(args, func) - object *args; - long (*func)(); + object *args; + long (*func)(); { - object *v, *w; - int i, nhits, n; - if (!getnoarg(args)) - return NULL; - if (pickbuffer == NULL) { - err_setstr(RuntimeError, - "endpick/endselect: not in pick/select mode"); - return NULL; - } - nhits = (*func)(pickbuffer); - if (nhits < 0) { - nhits = -nhits; /* How to report buffer overflow otherwise? */ - } - /* Scan the buffer to see how many integers */ - n = 0; - for (; nhits > 0; nhits--) { - n += 1 + pickbuffer[n]; - } - v = newlistobject(n); - if (v == NULL) - return NULL; - /* XXX Could do it nicer and interpret the data structure here, - returning a list of lists. But this can be done in Python... */ - for (i = 0; i < n; i++) { - w = newintobject((long)pickbuffer[i]); - if (w == NULL) { - DECREF(v); - return NULL; - } - setlistitem(v, i, w); - } - DEL(pickbuffer); - pickbuffer = NULL; - return v; + object *v, *w; + int i, nhits, n; + if (!getnoarg(args)) + return NULL; + if (pickbuffer == NULL) { + err_setstr(RuntimeError, + "endpick/endselect: not in pick/select mode"); + return NULL; + } + nhits = (*func)(pickbuffer); + if (nhits < 0) { + nhits = -nhits; /* How to report buffer overflow otherwise? */ + } + /* Scan the buffer to see how many integers */ + n = 0; + for (; nhits > 0; nhits--) { + n += 1 + pickbuffer[n]; + } + v = newlistobject(n); + if (v == NULL) + return NULL; + /* XXX Could do it nicer and interpret the data structure here, + returning a list of lists. But this can be done in Python... */ + for (i = 0; i < n; i++) { + w = newintobject((long)pickbuffer[i]); + if (w == NULL) { + DECREF(v); + return NULL; + } + setlistitem(v, i, w); + } + DEL(pickbuffer); + pickbuffer = NULL; + return v; } extern void pick(), gselect(); @@ -472,370 +472,370 @@ extern long endpick(), endselect(); %pick static object *gl_pick(self, args) object *self, *args; { - return pick_select(args, pick); + return pick_select(args, pick); } %endpick static object *gl_endpick(self, args) object *self, *args; { - return endpick_select(args, endpick); + return endpick_select(args, endpick); } %gselect static object *gl_gselect(self, args) object *self, *args; { - return pick_select(args, gselect); + return pick_select(args, gselect); } %endselect static object *gl_endselect(self, args) object *self, *args; { - return endpick_select(args, endselect); + return endpick_select(args, endselect); } -/* XXX The generator botches this one. Here's a quick hack to fix it. */ +/* XXX The generator botches this one. Here's a quick hack to fix it. */ % getmatrix float r[16] static object * gl_getmatrix(self, args) - object *self; - object *args; + object *self; + object *args; { - float arg1 [ 16 ] ; - object *v, *w; - int i; - getmatrix( arg1 ); - v = newlistobject(16); - if (v == NULL) { - return err_nomem(); - } - for (i = 0; i < 16; i++) { - w = mknewfloatobject(arg1[i]); - if (w == NULL) { - DECREF(v); - return NULL; - } - setlistitem(v, i, w); - } - return v; + float arg1 [ 16 ] ; + object *v, *w; + int i; + getmatrix( arg1 ); + v = newlistobject(16); + if (v == NULL) { + return err_nomem(); + } + for (i = 0; i < 16; i++) { + w = mknewfloatobject(arg1[i]); + if (w == NULL) { + DECREF(v); + return NULL; + } + setlistitem(v, i, w); + } + return v; } /* End of manually written stubs */ %% -long getshade -void devport short s long s -void rdr2i long s long s -void rectfs short s short s short s short s -void rects short s short s short s short s -void rmv2i long s long s -void noport -void popviewport -void clear -void clearhitcode -void closeobj -void cursoff -void curson -void doublebuffer -void finish -void gconfig -void ginit -void greset -void multimap -void onemap -void popattributes -void popmatrix -void pushattributes -void pushmatrix -void pushviewport -void qreset -void RGBmode -void singlebuffer -void swapbuffers -void gsync -void tpon -void tpoff -void clkon -void clkoff -void ringbell -#void callfunc -void gbegin -void textinit -void initnames -void pclos -void popname -void spclos -void zclear -void screenspace -void reshapeviewport -void winpush -void winpop -void foreground -void endfullscrn -void endpupmode -void fullscrn -void pupmode -void winconstraints -void pagecolor short s -void textcolor short s -void color short s -void curveit short s -void font short s -void linewidth short s -void setlinestyle short s -void setmap short s -void swapinterval short s -void writemask short s -void textwritemask short s -void qdevice short s -void unqdevice short s -void curvebasis short s -void curveprecision short s -void loadname short s -void passthrough short s -void pushname short s -void setmonitor short s -void setshade short s -void setpattern short s -void pagewritemask short s -# -void callobj long s -void delobj long s -void editobj long s -void makeobj long s -void maketag long s -void chunksize long s -void compactify long s -void deltag long s -void lsrepeat long s -void objinsert long s -void objreplace long s -void winclose long s -void blanktime long s -void freepup long s +long getshade +void devport short s long s +void rdr2i long s long s +void rectfs short s short s short s short s +void rects short s short s short s short s +void rmv2i long s long s +void noport +void popviewport +void clear +void clearhitcode +void closeobj +void cursoff +void curson +void doublebuffer +void finish +void gconfig +void ginit +void greset +void multimap +void onemap +void popattributes +void popmatrix +void pushattributes +void pushmatrix +void pushviewport +void qreset +void RGBmode +void singlebuffer +void swapbuffers +void gsync +void tpon +void tpoff +void clkon +void clkoff +void ringbell +#void callfunc +void gbegin +void textinit +void initnames +void pclos +void popname +void spclos +void zclear +void screenspace +void reshapeviewport +void winpush +void winpop +void foreground +void endfullscrn +void endpupmode +void fullscrn +void pupmode +void winconstraints +void pagecolor short s +void textcolor short s +void color short s +void curveit short s +void font short s +void linewidth short s +void setlinestyle short s +void setmap short s +void swapinterval short s +void writemask short s +void textwritemask short s +void qdevice short s +void unqdevice short s +void curvebasis short s +void curveprecision short s +void loadname short s +void passthrough short s +void pushname short s +void setmonitor short s +void setshade short s +void setpattern short s +void pagewritemask short s +# +void callobj long s +void delobj long s +void editobj long s +void makeobj long s +void maketag long s +void chunksize long s +void compactify long s +void deltag long s +void lsrepeat long s +void objinsert long s +void objreplace long s +void winclose long s +void blanktime long s +void freepup long s # This is not in the library!? -###void pupcolor long s -# -void backbuffer long s -void frontbuffer long s -void lsbackup long s -void resetls long s -void lampon long s -void lampoff long s -void setbell long s -void blankscreen long s -void depthcue long s -void zbuffer long s -void backface long s -# -void cmov2i long s long s -void draw2i long s long s -void move2i long s long s -void pnt2i long s long s -void patchbasis long s long s -void patchprecision long s long s -void pdr2i long s long s -void pmv2i long s long s -void rpdr2i long s long s -void rpmv2i long s long s -void xfpt2i long s long s -void objdelete long s long s -void patchcurves long s long s -void minsize long s long s -void maxsize long s long s -void keepaspect long s long s -void prefsize long s long s -void stepunit long s long s -void fudge long s long s -void winmove long s long s -# -void attachcursor short s short s -void deflinestyle short s short s -void noise short s short s -void picksize short s short s -void qenter short s short s -void setdepth short s short s -void cmov2s short s short s -void draw2s short s short s -void move2s short s short s -void pdr2s short s short s -void pmv2s short s short s -void pnt2s short s short s -void rdr2s short s short s -void rmv2s short s short s -void rpdr2s short s short s -void rpmv2s short s short s -void xfpt2s short s short s -# -void cmov2 float s float s -void draw2 float s float s -void move2 float s float s -void pnt2 float s float s -void pdr2 float s float s -void pmv2 float s float s -void rdr2 float s float s -void rmv2 float s float s -void rpdr2 float s float s -void rpmv2 float s float s -void xfpt2 float s float s -# -void loadmatrix float s[16] -void multmatrix float s[16] -void crv float s[16] -void rcrv float s[16] -# -# Methods that have strings. -# -void addtopup long s char *s long s -void charstr char *s -void getport char *s -long strwidth char *s -long winopen char *s -void wintitle char *s -# -# Methods that have 1 long (# of elements) and an array -# -void polf long s float s[3*arg1] -void polf2 long s float s[2*arg1] -void poly long s float s[3*arg1] -void poly2 long s float s[2*arg1] -void crvn long s float s[3*arg1] -void rcrvn long s float s[4*arg1] -# -void polf2i long s long s[2*arg1] -void polfi long s long s[3*arg1] -void poly2i long s long s[2*arg1] -void polyi long s long s[3*arg1] -# -void polf2s long s short s[2*arg1] -void polfs long s short s[3*arg1] -void polys long s short s[3*arg1] -void poly2s long s short s[2*arg1] -# -void defcursor short s short s[16] -void writepixels short s short s[arg1] -void defbasis long s float s[16] -void gewrite short s short s[arg1] -# -void rotate short s char s +###void pupcolor long s +# +void backbuffer long s +void frontbuffer long s +void lsbackup long s +void resetls long s +void lampon long s +void lampoff long s +void setbell long s +void blankscreen long s +void depthcue long s +void zbuffer long s +void backface long s +# +void cmov2i long s long s +void draw2i long s long s +void move2i long s long s +void pnt2i long s long s +void patchbasis long s long s +void patchprecision long s long s +void pdr2i long s long s +void pmv2i long s long s +void rpdr2i long s long s +void rpmv2i long s long s +void xfpt2i long s long s +void objdelete long s long s +void patchcurves long s long s +void minsize long s long s +void maxsize long s long s +void keepaspect long s long s +void prefsize long s long s +void stepunit long s long s +void fudge long s long s +void winmove long s long s +# +void attachcursor short s short s +void deflinestyle short s short s +void noise short s short s +void picksize short s short s +void qenter short s short s +void setdepth short s short s +void cmov2s short s short s +void draw2s short s short s +void move2s short s short s +void pdr2s short s short s +void pmv2s short s short s +void pnt2s short s short s +void rdr2s short s short s +void rmv2s short s short s +void rpdr2s short s short s +void rpmv2s short s short s +void xfpt2s short s short s +# +void cmov2 float s float s +void draw2 float s float s +void move2 float s float s +void pnt2 float s float s +void pdr2 float s float s +void pmv2 float s float s +void rdr2 float s float s +void rmv2 float s float s +void rpdr2 float s float s +void rpmv2 float s float s +void xfpt2 float s float s +# +void loadmatrix float s[16] +void multmatrix float s[16] +void crv float s[16] +void rcrv float s[16] +# +# Methods that have strings. +# +void addtopup long s char *s long s +void charstr char *s +void getport char *s +long strwidth char *s +long winopen char *s +void wintitle char *s +# +# Methods that have 1 long (# of elements) and an array +# +void polf long s float s[3*arg1] +void polf2 long s float s[2*arg1] +void poly long s float s[3*arg1] +void poly2 long s float s[2*arg1] +void crvn long s float s[3*arg1] +void rcrvn long s float s[4*arg1] +# +void polf2i long s long s[2*arg1] +void polfi long s long s[3*arg1] +void poly2i long s long s[2*arg1] +void polyi long s long s[3*arg1] +# +void polf2s long s short s[2*arg1] +void polfs long s short s[3*arg1] +void polys long s short s[3*arg1] +void poly2s long s short s[2*arg1] +# +void defcursor short s short s[16] +void writepixels short s short s[arg1] +void defbasis long s float s[16] +void gewrite short s short s[arg1] +# +void rotate short s char s # This is not in the library!? -###void setbutton short s char s -void rot float s char s -# -void circfi long s long s long s -void circi long s long s long s -void cmovi long s long s long s -void drawi long s long s long s -void movei long s long s long s -void pnti long s long s long s -void newtag long s long s long s -void pdri long s long s long s -void pmvi long s long s long s -void rdri long s long s long s -void rmvi long s long s long s -void rpdri long s long s long s -void rpmvi long s long s long s -void xfpti long s long s long s -# -void circ float s float s float s -void circf float s float s float s -void cmov float s float s float s -void draw float s float s float s -void move float s float s float s -void pnt float s float s float s -void scale float s float s float s -void translate float s float s float s -void pdr float s float s float s -void pmv float s float s float s -void rdr float s float s float s -void rmv float s float s float s -void rpdr float s float s float s -void rpmv float s float s float s -void xfpt float s float s float s -# -void RGBcolor short s short s short s -void RGBwritemask short s short s short s -void setcursor short s short s short s -void tie short s short s short s -void circfs short s short s short s -void circs short s short s short s -void cmovs short s short s short s -void draws short s short s short s -void moves short s short s short s -void pdrs short s short s short s -void pmvs short s short s short s -void pnts short s short s short s -void rdrs short s short s short s -void rmvs short s short s short s -void rpdrs short s short s short s -void rpmvs short s short s short s -void xfpts short s short s short s -void curorigin short s short s short s -void cyclemap short s short s short s -# -void patch float s[16] float s[16] float s[16] -void splf long s float s[3*arg1] short s[arg1] -void splf2 long s float s[2*arg1] short s[arg1] -void splfi long s long s[3*arg1] short s[arg1] -void splf2i long s long s[2*arg1] short s[arg1] -void splfs long s short s[3*arg1] short s[arg1] -void splf2s long s short s[2*arg1] short s[arg1] -void defpattern short s short s short s[arg2*arg2/16] -# -void rpatch float s[16] float s[16] float s[16] float s[16] +###void setbutton short s char s +void rot float s char s +# +void circfi long s long s long s +void circi long s long s long s +void cmovi long s long s long s +void drawi long s long s long s +void movei long s long s long s +void pnti long s long s long s +void newtag long s long s long s +void pdri long s long s long s +void pmvi long s long s long s +void rdri long s long s long s +void rmvi long s long s long s +void rpdri long s long s long s +void rpmvi long s long s long s +void xfpti long s long s long s +# +void circ float s float s float s +void circf float s float s float s +void cmov float s float s float s +void draw float s float s float s +void move float s float s float s +void pnt float s float s float s +void scale float s float s float s +void translate float s float s float s +void pdr float s float s float s +void pmv float s float s float s +void rdr float s float s float s +void rmv float s float s float s +void rpdr float s float s float s +void rpmv float s float s float s +void xfpt float s float s float s +# +void RGBcolor short s short s short s +void RGBwritemask short s short s short s +void setcursor short s short s short s +void tie short s short s short s +void circfs short s short s short s +void circs short s short s short s +void cmovs short s short s short s +void draws short s short s short s +void moves short s short s short s +void pdrs short s short s short s +void pmvs short s short s short s +void pnts short s short s short s +void rdrs short s short s short s +void rmvs short s short s short s +void rpdrs short s short s short s +void rpmvs short s short s short s +void xfpts short s short s short s +void curorigin short s short s short s +void cyclemap short s short s short s +# +void patch float s[16] float s[16] float s[16] +void splf long s float s[3*arg1] short s[arg1] +void splf2 long s float s[2*arg1] short s[arg1] +void splfi long s long s[3*arg1] short s[arg1] +void splf2i long s long s[2*arg1] short s[arg1] +void splfs long s short s[3*arg1] short s[arg1] +void splf2s long s short s[2*arg1] short s[arg1] +void defpattern short s short s short s[arg2*arg2/16] +# +void rpatch float s[16] float s[16] float s[16] float s[16] # # routines that send 4 floats # -void ortho2 float s float s float s float s -void rect float s float s float s float s -void rectf float s float s float s float s -void xfpt4 float s float s float s float s -# -void textport short s short s short s short s -void mapcolor short s short s short s short s -void scrmask short s short s short s short s -void setvaluator short s short s short s short s -void viewport short s short s short s short s -void shaderange short s short s short s short s -void xfpt4s short s short s short s short s -void rectfi long s long s long s long s -void recti long s long s long s long s -void xfpt4i long s long s long s long s -void prefposition long s long s long s long s -# -void arc float s float s float s short s short s -void arcf float s float s float s short s short s -void arcfi long s long s long s short s short s -void arci long s long s long s short s short s -# -void bbox2 short s short s float s float s float s float s -void bbox2i short s short s long s long s long s long s -void bbox2s short s short s short s short s short s short s -void blink short s short s short s short s short s -void ortho float s float s float s float s float s float s -void window float s float s float s float s float s float s -void lookat float s float s float s float s float s float s short s -# -void perspective short s float s float s float s -void polarview float s short s short s short s +void ortho2 float s float s float s float s +void rect float s float s float s float s +void rectf float s float s float s float s +void xfpt4 float s float s float s float s +# +void textport short s short s short s short s +void mapcolor short s short s short s short s +void scrmask short s short s short s short s +void setvaluator short s short s short s short s +void viewport short s short s short s short s +void shaderange short s short s short s short s +void xfpt4s short s short s short s short s +void rectfi long s long s long s long s +void recti long s long s long s long s +void xfpt4i long s long s long s long s +void prefposition long s long s long s long s +# +void arc float s float s float s short s short s +void arcf float s float s float s short s short s +void arcfi long s long s long s short s short s +void arci long s long s long s short s short s +# +void bbox2 short s short s float s float s float s float s +void bbox2i short s short s long s long s long s long s +void bbox2s short s short s short s short s short s short s +void blink short s short s short s short s short s +void ortho float s float s float s float s float s float s +void window float s float s float s float s float s float s +void lookat float s float s float s float s float s float s short s +# +void perspective short s float s float s float s +void polarview float s short s short s short s # XXX getichararray not supported -#void writeRGB short s char s[arg1] char s[arg1] char s[arg1] +#void writeRGB short s char s[arg1] char s[arg1] char s[arg1] # -void arcfs short s short s short s short s short s -void arcs short s short s short s short s short s -void rectcopy short s short s short s short s short s short s -void RGBcursor short s short s short s short s short s short s short s +void arcfs short s short s short s short s short s +void arcs short s short s short s short s short s +void rectcopy short s short s short s short s short s short s +void RGBcursor short s short s short s short s short s short s short s # -long getbutton short s +long getbutton short s long getcmmode long getlsbackup long getresetls long getdcm long getzbuffer long ismex -long isobj long s -long isqueued short s -long istag long s +long isobj long s +long isqueued short s +long istag long s # long genobj long gentag @@ -860,60 +860,60 @@ long winattach long getothermonitor long newpup # -long getvaluator short s -void winset long s -long dopup long s -void getdepth short r short r -void getcpos short r short r -void getsize long r long r -void getorigin long r long r -void getviewport short r short r short r short r -void gettp short r short r short r short r -void getgpos float r float r float r float r -void winposition long s long s long s long s -void gRGBcolor short r short r short r -void gRGBmask short r short r short r -void getscrmask short r short r short r short r -void gRGBcursor short r short r short r short r short r short r short r short r long * -void getmcolor short s short r short r short r -void mapw long s short s short s float r float r float r float r float r float r -void mapw2 long s short s short s float r float r -void defrasterfont short s short s short s Fontchar s[arg3] short s short s[4*arg5] -long qread short r -void getcursor short r short r short r long r -# -# For these we receive arrays of stuff -# -void getdev long s short s[arg1] short r[arg1] +long getvaluator short s +void winset long s +long dopup long s +void getdepth short r short r +void getcpos short r short r +void getsize long r long r +void getorigin long r long r +void getviewport short r short r short r short r +void gettp short r short r short r short r +void getgpos float r float r float r float r +void winposition long s long s long s long s +void gRGBcolor short r short r short r +void gRGBmask short r short r short r +void getscrmask short r short r short r short r +void gRGBcursor short r short r short r short r short r short r short r short r long * +void getmcolor short s short r short r short r +void mapw long s short s short s float r float r float r float r float r float r +void mapw2 long s short s short s float r float r +void defrasterfont short s short s short s Fontchar s[arg3] short s short s[4*arg5] +long qread short r +void getcursor short r short r short r long r +# +# For these we receive arrays of stuff +# +void getdev long s short s[arg1] short r[arg1] #XXX not generated correctly yet -#void getmatrix float r[16] -long readpixels short s short r[retval] -long readRGB short s char r[retval] char r[retval] char r[retval] -long blkqread short s short r[arg1] +#void getmatrix float r[16] +long readpixels short s short r[retval] +long readRGB short s char r[retval] char r[retval] char r[retval] +long blkqread short s short r[arg1] # -# New 4D routines +# New 4D routines # void cmode -void concave long s -void curstype long s -void drawmode long s -void gammaramp short s[256] short s[256] short s[256] +void concave long s +void curstype long s +void drawmode long s +void gammaramp short s[256] short s[256] short s[256] long getbackface long getdescender long getdrawmode long getmmode long getsm -long getvideo long s +long getvideo long s void imakebackground -void lmbind short s short s -void lmdef long s long s long s float s[arg3] -void mmode long s -void normal float s[3] -void overlay long s -void RGBrange short s short s short s short s short s short s short s short s -void setvideo long s long s -void shademodel long s -void underlay long s +void lmbind short s short s +void lmdef long s long s long s float s[arg3] +void mmode long s +void normal float s[3] +void overlay long s +void RGBrange short s short s short s short s short s short s short s short s +void setvideo long s long s +void shademodel long s +void underlay long s # # New Personal Iris/GT Routines # @@ -931,69 +931,69 @@ void endpolygon void endsurface void endtmesh void endtrim -void blendfunction long s long s -void c3f float s[3] -void c3i long s[3] -void c3s short s[3] -void c4f float s[4] -void c4i long s[4] -void c4s short s[4] -void colorf float s -void cpack long s -void czclear long s long s -void dglclose long s -long dglopen char *s long s -long getgdesc long s -void getnurbsproperty long s float r -void glcompat long s long s -void iconsize long s long s -void icontitle char *s -void lRGBrange short s short s short s short s short s short s long s long s -void linesmooth long s -void lmcolor long s -void logicop long s -long lrectread short s short s short s short s long r[retval] -void lrectwrite short s short s short s short s long s[(arg2-arg1+1)*(arg4-arg3+1)] -long rectread short s short s short s short s short r[retval] -void rectwrite short s short s short s short s short s[(arg2-arg1+1)*(arg4-arg3+1)] -void lsetdepth long s long s -void lshaderange short s short s long s long s -void n3f float s[3] +void blendfunction long s long s +void c3f float s[3] +void c3i long s[3] +void c3s short s[3] +void c4f float s[4] +void c4i long s[4] +void c4s short s[4] +void colorf float s +void cpack long s +void czclear long s long s +void dglclose long s +long dglopen char *s long s +long getgdesc long s +void getnurbsproperty long s float r +void glcompat long s long s +void iconsize long s long s +void icontitle char *s +void lRGBrange short s short s short s short s short s short s long s long s +void linesmooth long s +void lmcolor long s +void logicop long s +long lrectread short s short s short s short s long r[retval] +void lrectwrite short s short s short s short s long s[(arg2-arg1+1)*(arg4-arg3+1)] +long rectread short s short s short s short s short r[retval] +void rectwrite short s short s short s short s short s[(arg2-arg1+1)*(arg4-arg3+1)] +void lsetdepth long s long s +void lshaderange short s short s long s long s +void n3f float s[3] void noborder -void pntsmooth long s -void readsource long s -void rectzoom float s float s -void sbox float s float s float s float s -void sboxi long s long s long s long s -void sboxs short s short s short s short s -void sboxf float s float s float s float s -void sboxfi long s long s long s long s -void sboxfs short s short s short s short s -void setnurbsproperty long s float s -void setpup long s long s long s -void smoothline long s -void subpixel long s +void pntsmooth long s +void readsource long s +void rectzoom float s float s +void sbox float s float s float s float s +void sboxi long s long s long s long s +void sboxs short s short s short s short s +void sboxf float s float s float s float s +void sboxfi long s long s long s long s +void sboxfs short s short s short s short s +void setnurbsproperty long s float s +void setpup long s long s long s +void smoothline long s +void subpixel long s void swaptmesh -long swinopen long s -void v2f float s[2] -void v2i long s[2] -void v2s short s[2] -void v3f float s[3] -void v3i long s[3] -void v3s short s[3] -void v4f float s[4] -void v4i long s[4] -void v4s short s[4] -void videocmd long s -long windepth long s -void wmpack long s -void zdraw long s -void zfunction long s -void zsource long s -void zwritemask long s -# -# uses doubles -# -void v2d double s[2] -void v3d double s[3] -void v4d double s[4] +long swinopen long s +void v2f float s[2] +void v2i long s[2] +void v2s short s[2] +void v3f float s[3] +void v3i long s[3] +void v3s short s[3] +void v4f float s[4] +void v4i long s[4] +void v4s short s[4] +void videocmd long s +long windepth long s +void wmpack long s +void zdraw long s +void zfunction long s +void zsource long s +void zwritemask long s +# +# uses doubles +# +void v2d double s[2] +void v3d double s[3] +void v4d double s[4] diff --git a/src/dictobject.c b/src/dictobject.c index 3bbd1d5..47d7837 100644 --- a/src/dictobject.c +++ b/src/dictobject.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -32,7 +32,7 @@ A similar module that I saw by Chris Torek: - remembers the hash value with the entry to speed up table resizing - sets the table size to a power of 2 - uses a different hash function: - h = 0; p = str; while (*p) h = (h<<5) - h + *p++; + h = 0; p = str; while (*p) h = (h<<5) - h + *p++; */ #include "allobjects.h" @@ -48,10 +48,10 @@ of that many entries to fail (if none of the earlier values cause such failure already). */ static unsigned int primes[] = { - 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2017, 4093, - 5987, - 9551, 15683, 19609, 31397, - 0xffffffff /* All bits set -- truncation OK */ + 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2017, 4093, + 5987, + 9551, 15683, 19609, 31397, + 0xffffffff /* All bits set -- truncation OK */ }; /* String used as dummy key to fill deleted entries */ @@ -60,12 +60,12 @@ static stringobject *dummy; /* Initialized by first call to newdictobject() */ /* Invariant for entries: when in use, de_value is not NULL and de_key is not NULL and not dummy; when not in use, de_value is NULL and de_key -is either NULL or dummy. A dummy key value cannot be replaced by NULL, +is either NULL or dummy. A dummy key value cannot be replaced by NULL, since otherwise other keys may be lost. */ typedef struct { - stringobject *de_key; - object *de_value; + stringobject *de_key; + object *de_value; } dictentry; /* @@ -77,34 +77,34 @@ To avoid slowing down lookups on a near-full table, we resize the table when it is more than half filled. */ typedef struct { - OB_HEAD - int di_fill; - int di_used; - int di_size; - dictentry *di_table; + OB_HEAD + int di_fill; + int di_used; + int di_size; + dictentry *di_table; } dictobject; object * newdictobject() { - register dictobject *dp; - if (dummy == NULL) { /* Auto-initialize dummy */ - dummy = (stringobject *) newstringobject(""); - if (dummy == NULL) - return NULL; - } - dp = NEWOBJ(dictobject, &Dicttype); - if (dp == NULL) - return NULL; - dp->di_size = primes[0]; - dp->di_table = (dictentry *) calloc(sizeof(dictentry), dp->di_size); - if (dp->di_table == NULL) { - DEL(dp); - return err_nomem(); - } - dp->di_fill = 0; - dp->di_used = 0; - return (object *)dp; + register dictobject *dp; + if (dummy == NULL) { /* Auto-initialize dummy */ + dummy = (stringobject *) newstringobject(""); + if (dummy == NULL) + return NULL; + } + dp = NEWOBJ(dictobject, &Dicttype); + if (dp == NULL) + return NULL; + dp->di_size = primes[0]; + dp->di_table = (dictentry *) calloc(sizeof(dictentry), dp->di_size); + if (dp->di_table == NULL) { + DEL(dp); + return err_nomem(); + } + dp->di_fill = 0; + dp->di_used = 0; + return (object *)dp; } /* @@ -122,44 +122,44 @@ The initial probe index is then computed as sum mod the table size. Subsequent probe indices are incr apart (mod table size), where incr is also derived from sum, with the additional requirement that it is relative prime to the table size (i.e., 1 <= incr < size, since the size -is a prime number). My choice for incr is somewhat arbitrary. +is a prime number). My choice for incr is somewhat arbitrary. */ static dictentry *lookdict PROTO((dictobject *, char *)); static dictentry * lookdict(dp, key) - register dictobject *dp; - char *key; + register dictobject *dp; + char *key; { - register int i, incr; - register dictentry *freeslot = NULL; - register unsigned char *p = (unsigned char *) key; - register unsigned long sum = *p << 7; - while (*p != '\0') - sum = sum + sum + *p++; - i = sum % dp->di_size; - do { - sum = sum + sum + 1; - incr = sum % dp->di_size; - } while (incr == 0); - for (;;) { - register dictentry *ep = &dp->di_table[i]; - if (ep->de_key == NULL) { - if (freeslot != NULL) - return freeslot; - else - return ep; - } - if (ep->de_key == dummy) { - if (freeslot != NULL) - freeslot = ep; - } - else if (GETSTRINGVALUE(ep->de_key)[0] == key[0]) { - if (strcmp(GETSTRINGVALUE(ep->de_key), key) == 0) { - return ep; - } - } - i = (i + incr) % dp->di_size; - } + register int i, incr; + register dictentry *freeslot = NULL; + register unsigned char *p = (unsigned char *) key; + register unsigned long sum = *p << 7; + while (*p != '\0') + sum = sum + sum + *p++; + i = sum % dp->di_size; + do { + sum = sum + sum + 1; + incr = sum % dp->di_size; + } while (incr == 0); + for (;;) { + register dictentry *ep = &dp->di_table[i]; + if (ep->de_key == NULL) { + if (freeslot != NULL) + return freeslot; + else + return ep; + } + if (ep->de_key == dummy) { + if (freeslot != NULL) + freeslot = ep; + } + else if (GETSTRINGVALUE(ep->de_key)[0] == key[0]) { + if (strcmp(GETSTRINGVALUE(ep->de_key), key) == 0) { + return ep; + } + } + i = (i + incr) % dp->di_size; + } } /* @@ -170,436 +170,436 @@ Eats a reference to key and one to value. static void insertdict PROTO((dictobject *, stringobject *, object *)); static void insertdict(dp, key, value) - register dictobject *dp; - stringobject *key; - object *value; + register dictobject *dp; + stringobject *key; + object *value; { - register dictentry *ep; - ep = lookdict(dp, GETSTRINGVALUE(key)); - if (ep->de_value != NULL) { - DECREF(ep->de_value); - DECREF(key); - } - else { - if (ep->de_key == NULL) - dp->di_fill++; - else - DECREF(ep->de_key); - ep->de_key = key; - dp->di_used++; - } - ep->de_value = value; + register dictentry *ep; + ep = lookdict(dp, GETSTRINGVALUE(key)); + if (ep->de_value != NULL) { + DECREF(ep->de_value); + DECREF(key); + } + else { + if (ep->de_key == NULL) + dp->di_fill++; + else + DECREF(ep->de_key); + ep->de_key = key; + dp->di_used++; + } + ep->de_value = value; } /* Restructure the table by allocating a new table and reinserting all -items again. When entries have been deleted, the new table may +items again. When entries have been deleted, the new table may actually be smaller than the old one. */ static int dictresize PROTO((dictobject *)); static int dictresize(dp) - dictobject *dp; + dictobject *dp; { - register int oldsize = dp->di_size; - register int newsize; - register dictentry *oldtable = dp->di_table; - register dictentry *newtable; - register dictentry *ep; - register int i; - newsize = dp->di_size; - for (i = 0; ; i++) { - if (primes[i] > dp->di_used*2) { - newsize = primes[i]; - break; - } - } - newtable = (dictentry *) calloc(sizeof(dictentry), newsize); - if (newtable == NULL) { - err_nomem(); - return -1; - } - dp->di_size = newsize; - dp->di_table = newtable; - dp->di_fill = 0; - dp->di_used = 0; - for (i = 0, ep = oldtable; i < oldsize; i++, ep++) { - if (ep->de_value != NULL) - insertdict(dp, ep->de_key, ep->de_value); - else if (ep->de_key != NULL) - DECREF(ep->de_key); - } - DEL(oldtable); - return 0; + register int oldsize = dp->di_size; + register int newsize; + register dictentry *oldtable = dp->di_table; + register dictentry *newtable; + register dictentry *ep; + register int i; + newsize = dp->di_size; + for (i = 0; ; i++) { + if (primes[i] > dp->di_used*2) { + newsize = primes[i]; + break; + } + } + newtable = (dictentry *) calloc(sizeof(dictentry), newsize); + if (newtable == NULL) { + err_nomem(); + return -1; + } + dp->di_size = newsize; + dp->di_table = newtable; + dp->di_fill = 0; + dp->di_used = 0; + for (i = 0, ep = oldtable; i < oldsize; i++, ep++) { + if (ep->de_value != NULL) + insertdict(dp, ep->de_key, ep->de_value); + else if (ep->de_key != NULL) + DECREF(ep->de_key); + } + DEL(oldtable); + return 0; } object * dictlookup(op, key) - object *op; - char *key; + object *op; + char *key; { - if (!is_dictobject(op)) - fatal("dictlookup on non-dictionary"); - return lookdict((dictobject *)op, key) -> de_value; + if (!is_dictobject(op)) + fatal("dictlookup on non-dictionary"); + return lookdict((dictobject *)op, key) -> de_value; } #ifdef NOT_USED static object * dict2lookup(op, key) - register object *op; - register object *key; + register object *op; + register object *key; { - register object *res; - if (!is_dictobject(op)) { - err_badcall(); - return NULL; - } - if (!is_stringobject(key)) { - err_badarg(); - return NULL; - } - res = lookdict((dictobject *)op, ((stringobject *)key)->ob_sval) - -> de_value; - if (res == NULL) - err_setstr(KeyError, "key not in dictionary"); - return res; + register object *res; + if (!is_dictobject(op)) { + err_badcall(); + return NULL; + } + if (!is_stringobject(key)) { + err_badarg(); + return NULL; + } + res = lookdict((dictobject *)op, ((stringobject *)key)->ob_sval) + -> de_value; + if (res == NULL) + err_setstr(KeyError, "key not in dictionary"); + return res; } #endif static int dict2insert(op, key, value) - register object *op; - object *key; - object *value; + register object *op; + object *key; + object *value; { - register dictobject *dp; - register stringobject *keyobj; - if (!is_dictobject(op)) { - err_badcall(); - return -1; - } - dp = (dictobject *)op; - if (!is_stringobject(key)) { - err_badarg(); - return -1; - } - keyobj = (stringobject *)key; - /* if fill >= 2/3 size, resize */ - if (dp->di_fill*3 >= dp->di_size*2) { - if (dictresize(dp) != 0) { - if (dp->di_fill+1 > dp->di_size) - return -1; - } - } - INCREF(keyobj); - INCREF(value); - insertdict(dp, keyobj, value); - return 0; + register dictobject *dp; + register stringobject *keyobj; + if (!is_dictobject(op)) { + err_badcall(); + return -1; + } + dp = (dictobject *)op; + if (!is_stringobject(key)) { + err_badarg(); + return -1; + } + keyobj = (stringobject *)key; + /* if fill >= 2/3 size, resize */ + if (dp->di_fill*3 >= dp->di_size*2) { + if (dictresize(dp) != 0) { + if (dp->di_fill+1 > dp->di_size) + return -1; + } + } + INCREF(keyobj); + INCREF(value); + insertdict(dp, keyobj, value); + return 0; } int dictinsert(op, key, value) - object *op; - char *key; - object *value; + object *op; + char *key; + object *value; { - register object *keyobj; - register int err; - keyobj = newstringobject(key); - if (keyobj == NULL) { - err_nomem(); - return -1; - } - err = dict2insert(op, keyobj, value); - DECREF(keyobj); - return err; + register object *keyobj; + register int err; + keyobj = newstringobject(key); + if (keyobj == NULL) { + err_nomem(); + return -1; + } + err = dict2insert(op, keyobj, value); + DECREF(keyobj); + return err; } int dictremove(op, key) - object *op; - char *key; + object *op; + char *key; { - register dictobject *dp; - register dictentry *ep; - if (!is_dictobject(op)) { - err_badcall(); - return -1; - } - dp = (dictobject *)op; - ep = lookdict(dp, key); - if (ep->de_value == NULL) { - err_setstr(KeyError, "key not in dictionary"); - return -1; - } - DECREF(ep->de_key); - INCREF(dummy); - ep->de_key = dummy; - DECREF(ep->de_value); - ep->de_value = NULL; - dp->di_used--; - return 0; + register dictobject *dp; + register dictentry *ep; + if (!is_dictobject(op)) { + err_badcall(); + return -1; + } + dp = (dictobject *)op; + ep = lookdict(dp, key); + if (ep->de_value == NULL) { + err_setstr(KeyError, "key not in dictionary"); + return -1; + } + DECREF(ep->de_key); + INCREF(dummy); + ep->de_key = dummy; + DECREF(ep->de_value); + ep->de_value = NULL; + dp->di_used--; + return 0; } static int dict2remove(op, key) - object *op; - register object *key; + object *op; + register object *key; { - if (!is_stringobject(key)) { - err_badarg(); - return -1; - } - return dictremove(op, GETSTRINGVALUE((stringobject *)key)); + if (!is_stringobject(key)) { + err_badarg(); + return -1; + } + return dictremove(op, GETSTRINGVALUE((stringobject *)key)); } int getdictsize(op) - register object *op; + register object *op; { - if (!is_dictobject(op)) { - err_badcall(); - return -1; - } - return ((dictobject *)op) -> di_size; + if (!is_dictobject(op)) { + err_badcall(); + return -1; + } + return ((dictobject *)op) -> di_size; } static object * getdict2key(op, i) - object *op; - register int i; + object *op; + register int i; { - /* XXX This can't return errors since its callers assume - that NULL means there was no key at that point */ - register dictobject *dp; - if (!is_dictobject(op)) { - /* err_badcall(); */ - return NULL; - } - dp = (dictobject *)op; - if (i < 0 || i >= dp->di_size) { - /* err_badarg(); */ - return NULL; - } - if (dp->di_table[i].de_value == NULL) { - /* Not an error! */ - return NULL; - } - return (object *) dp->di_table[i].de_key; + /* XXX This can't return errors since its callers assume + that NULL means there was no key at that point */ + register dictobject *dp; + if (!is_dictobject(op)) { + /* err_badcall(); */ + return NULL; + } + dp = (dictobject *)op; + if (i < 0 || i >= dp->di_size) { + /* err_badarg(); */ + return NULL; + } + if (dp->di_table[i].de_value == NULL) { + /* Not an error! */ + return NULL; + } + return (object *) dp->di_table[i].de_key; } char * getdictkey(op, i) - object *op; - int i; + object *op; + int i; { - register object *keyobj = getdict2key(op, i); - if (keyobj == NULL) - return NULL; - return GETSTRINGVALUE((stringobject *)keyobj); + register object *keyobj = getdict2key(op, i); + if (keyobj == NULL) + return NULL; + return GETSTRINGVALUE((stringobject *)keyobj); } /* Methods */ static void dict_dealloc(dp) - register dictobject *dp; + register dictobject *dp; { - register int i; - register dictentry *ep; - for (i = 0, ep = dp->di_table; i < dp->di_size; i++, ep++) { - if (ep->de_key != NULL) - DECREF(ep->de_key); - if (ep->de_value != NULL) - DECREF(ep->de_value); - } - if (dp->di_table != NULL) - DEL(dp->di_table); - DEL(dp); + register int i; + register dictentry *ep; + for (i = 0, ep = dp->di_table; i < dp->di_size; i++, ep++) { + if (ep->de_key != NULL) + DECREF(ep->de_key); + if (ep->de_value != NULL) + DECREF(ep->de_value); + } + if (dp->di_table != NULL) + DEL(dp->di_table); + DEL(dp); } static void dict_print(dp, fp, flags) - register dictobject *dp; - register FILE *fp; - register int flags; + register dictobject *dp; + register FILE *fp; + register int flags; { - register int i; - register int any; - register dictentry *ep; - fprintf(fp, "{"); - any = 0; - for (i = 0, ep = dp->di_table; i < dp->di_size && !StopPrint; - i++, ep++) { - if (ep->de_value != NULL) { - if (any++ > 0) - fprintf(fp, "; "); - printobject((object *)ep->de_key, fp, flags); - fprintf(fp, ": "); - printobject(ep->de_value, fp, flags); - } - } - fprintf(fp, "}"); + register int i; + register int any; + register dictentry *ep; + fprintf(fp, "{"); + any = 0; + for (i = 0, ep = dp->di_table; i < dp->di_size && !StopPrint; + i++, ep++) { + if (ep->de_value != NULL) { + if (any++ > 0) + fprintf(fp, "; "); + printobject((object *)ep->de_key, fp, flags); + fprintf(fp, ": "); + printobject(ep->de_value, fp, flags); + } + } + fprintf(fp, "}"); } static void js(pv, w) - object **pv; - object *w; + object **pv; + object *w; { - joinstring(pv, w); - if (w != NULL) - DECREF(w); + joinstring(pv, w); + if (w != NULL) + DECREF(w); } static object * dict_repr(dp) - dictobject *dp; + dictobject *dp; { - auto object *v; - register object *w; - object *semi, *colon; - register int i; - register int any; - register dictentry *ep; - v = newstringobject("{"); - semi = newstringobject("; "); - colon = newstringobject(": "); - any = 0; - for (i = 0, ep = dp->di_table; i < dp->di_size && !StopPrint; - i++, ep++) { - if (ep->de_value != NULL) { - if (any++) - joinstring(&v, semi); - js(&v, w = reprobject((object *)ep->de_key)); - joinstring(&v, colon); - js(&v, w = reprobject(ep->de_value)); - } - } - js(&v, w = newstringobject("}")); - if (semi != NULL) - DECREF(semi); - if (colon != NULL) - DECREF(colon); - return v; + auto object *v; + register object *w; + object *semi, *colon; + register int i; + register int any; + register dictentry *ep; + v = newstringobject("{"); + semi = newstringobject("; "); + colon = newstringobject(": "); + any = 0; + for (i = 0, ep = dp->di_table; i < dp->di_size && !StopPrint; + i++, ep++) { + if (ep->de_value != NULL) { + if (any++) + joinstring(&v, semi); + js(&v, w = reprobject((object *)ep->de_key)); + joinstring(&v, colon); + js(&v, w = reprobject(ep->de_value)); + } + } + js(&v, w = newstringobject("}")); + if (semi != NULL) + DECREF(semi); + if (colon != NULL) + DECREF(colon); + return v; } static int dict_length(dp) - dictobject *dp; + dictobject *dp; { - return dp->di_used; + return dp->di_used; } static object * dict_subscript(dp, v) - dictobject *dp; - register object *v; + dictobject *dp; + register object *v; { - if (!is_stringobject(v)) { - err_badarg(); - return NULL; - } - v = lookdict(dp, GETSTRINGVALUE((stringobject *)v)) -> de_value; - if (v == NULL) - err_setstr(KeyError, "key not in dictionary"); - else - INCREF(v); - return v; + if (!is_stringobject(v)) { + err_badarg(); + return NULL; + } + v = lookdict(dp, GETSTRINGVALUE((stringobject *)v)) -> de_value; + if (v == NULL) + err_setstr(KeyError, "key not in dictionary"); + else + INCREF(v); + return v; } static int dict_ass_sub(dp, v, w) - dictobject *dp; - object *v, *w; + dictobject *dp; + object *v, *w; { - if (w == NULL) - return dict2remove((object *)dp, v); - else - return dict2insert((object *)dp, v, w); + if (w == NULL) + return dict2remove((object *)dp, v); + else + return dict2insert((object *)dp, v, w); } static mapping_methods dict_as_mapping = { - dict_length, /*mp_length*/ - dict_subscript, /*mp_subscript*/ - dict_ass_sub, /*mp_ass_subscript*/ + dict_length, /*mp_length*/ + dict_subscript, /*mp_subscript*/ + dict_ass_sub, /*mp_ass_subscript*/ }; static object * dict_keys(dp, args) - register dictobject *dp; - object *args; + register dictobject *dp; + object *args; { - register object *v; - register int i, j; - if (!getnoarg(args)) - return NULL; - v = newlistobject(dp->di_used); - if (v == NULL) - return NULL; - for (i = 0, j = 0; i < dp->di_size; i++) { - if (dp->di_table[i].de_value != NULL) { - stringobject *key = dp->di_table[i].de_key; - INCREF(key); - setlistitem(v, j, (object *)key); - j++; - } - } - return v; + register object *v; + register int i, j; + if (!getnoarg(args)) + return NULL; + v = newlistobject(dp->di_used); + if (v == NULL) + return NULL; + for (i = 0, j = 0; i < dp->di_size; i++) { + if (dp->di_table[i].de_value != NULL) { + stringobject *key = dp->di_table[i].de_key; + INCREF(key); + setlistitem(v, j, (object *)key); + j++; + } + } + return v; } object * getdictkeys(dp) - object *dp; + object *dp; { - if (dp == NULL || !is_dictobject(dp)) { - err_badcall(); - return NULL; - } - return dict_keys((dictobject *)dp, (object *)NULL); + if (dp == NULL || !is_dictobject(dp)) { + err_badcall(); + return NULL; + } + return dict_keys((dictobject *)dp, (object *)NULL); } static object * dict_has_key(dp, args) - register dictobject *dp; - object *args; + register dictobject *dp; + object *args; { - object *key; - register long ok; - if (!getstrarg(args, &key)) - return NULL; - ok = lookdict(dp, GETSTRINGVALUE((stringobject *)key))->de_value - != NULL; - return newintobject(ok); + object *key; + register long ok; + if (!getstrarg(args, &key)) + return NULL; + ok = lookdict(dp, GETSTRINGVALUE((stringobject *)key))->de_value + != NULL; + return newintobject(ok); } static struct methodlist dict_methods[] = { - {"keys", dict_keys}, - {"has_key", dict_has_key}, - {NULL, NULL} /* sentinel */ + {"keys", dict_keys}, + {"has_key", dict_has_key}, + {NULL, NULL} /* sentinel */ }; static object * dict_getattr(dp, name) - dictobject *dp; - char *name; + dictobject *dp; + char *name; { - return findmethod(dict_methods, (object *)dp, name); + return findmethod(dict_methods, (object *)dp, name); } typeobject Dicttype = { - OB_HEAD_INIT(&Typetype) - 0, - "dictionary", - sizeof(dictobject), - 0, - dict_dealloc, /*tp_dealloc*/ - dict_print, /*tp_print*/ - dict_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - dict_repr, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - &dict_as_mapping, /*tp_as_mapping*/ + OB_HEAD_INIT(&Typetype) + 0, + "dictionary", + sizeof(dictobject), + 0, + dict_dealloc, /*tp_dealloc*/ + dict_print, /*tp_print*/ + dict_getattr, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + dict_repr, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + &dict_as_mapping, /*tp_as_mapping*/ }; diff --git a/src/dictobject.h b/src/dictobject.h index d665aa5..6e08bdd 100644 --- a/src/dictobject.h +++ b/src/dictobject.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -25,9 +25,9 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* Dictionary object type -- mapping from char * to object. NB: the key is given as a char *, not as a stringobject. -These functions set errno for errors. Functions dictremove() and +These functions set errno for errors. Functions dictremove() and dictinsert() return nonzero for errors, getdictsize() returns -1, -the others NULL. A successful call to dictinsert() calls INCREF() +the others NULL. A successful call to dictinsert() calls INCREF() for the inserted item. */ diff --git a/src/errcode.h b/src/errcode.h index 3324489..65bd598 100644 --- a/src/errcode.h +++ b/src/errcode.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -23,14 +23,14 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ /* Error codes passed around between file input, tokenizer, parser and - interpreter. This was necessary so we can turn them into Python - exceptions at a higher level. */ + interpreter. This was necessary so we can turn them into Python + exceptions at a higher level. */ -#define E_OK 10 /* No error */ -#define E_EOF 11 /* (Unexpected) EOF read */ -#define E_INTR 12 /* Interrupted */ -#define E_TOKEN 13 /* Bad token */ -#define E_SYNTAX 14 /* Syntax error */ -#define E_NOMEM 15 /* Ran out of memory */ -#define E_DONE 16 /* Parsing complete */ -#define E_ERROR 17 /* Execution error */ +#define E_OK 10 /* No error */ +#define E_EOF 11 /* (Unexpected) EOF read */ +#define E_INTR 12 /* Interrupted */ +#define E_TOKEN 13 /* Bad token */ +#define E_SYNTAX 14 /* Syntax error */ +#define E_NOMEM 15 /* Ran out of memory */ +#define E_DONE 16 /* Parsing complete */ +#define E_ERROR 17 /* Execution error */ diff --git a/src/errors.c b/src/errors.c index b3e6aa3..f1e7151 100644 --- a/src/errors.c +++ b/src/errors.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -26,33 +26,33 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* New error handling interface. - The following problem exists (existed): methods of built-in modules - are called with 'self' and 'args' arguments, but without a context - argument, so they have no way to raise a specific exception. - The same is true for the object implementations: no context argument. - The old convention was to set 'errno' and to return NULL. - The caller (usually call_function() in eval.c) detects the NULL - return value and then calls puterrno(ctx) to turn the errno value - into a true exception. Problems with this approach are: - - it used standard errno values to indicate Python-specific errors, - but this means that when such an error code is reported by a system - call (e.g., in module posix), the user gets a confusing message - - errno is a global variable, which makes extensions to a multi- - threading environment difficult; e.g., in IRIX, multi-threaded - programs must use the function oserror() instead of looking in errno - - there is no portable way to add new error numbers for specic - situations -- the value space for errno is reserved to the OS, yet - the way to turn module-specific errors into a module-specific - exception requires module-specific values for errno - - there is no way to add a more situation-specific message to an - error. - - The new interface solves all these problems. To return an error, a - built-in function calls err_set(exception), err_setval(exception, - value) or err_setstr(exception, string), and returns NULL. These - functions save the value for later use by puterrno(). To adapt this - scheme to a multi-threaded environment, only the implementation of - err_setval() has to be changed. + The following problem exists (existed): methods of built-in modules + are called with 'self' and 'args' arguments, but without a context + argument, so they have no way to raise a specific exception. + The same is true for the object implementations: no context argument. + The old convention was to set 'errno' and to return NULL. + The caller (usually call_function() in eval.c) detects the NULL + return value and then calls puterrno(ctx) to turn the errno value + into a true exception. Problems with this approach are: + - it used standard errno values to indicate Python-specific errors, + but this means that when such an error code is reported by a system + call (e.g., in module posix), the user gets a confusing message + - errno is a global variable, which makes extensions to a multi- + threading environment difficult; e.g., in IRIX, multi-threaded + programs must use the function oserror() instead of looking in errno + - there is no portable way to add new error numbers for specic + situations -- the value space for errno is reserved to the OS, yet + the way to turn module-specific errors into a module-specific + exception requires module-specific values for errno + - there is no way to add a more situation-specific message to an + error. + + The new interface solves all these problems. To return an error, a + built-in function calls err_set(exception), err_setval(exception, + value) or err_setstr(exception, string), and returns NULL. These + functions save the value for later use by puterrno(). To adapt this + scheme to a multi-threaded environment, only the implementation of + err_setval() has to be changed. */ #include "allobjects.h" @@ -73,59 +73,59 @@ static object *last_exc_val; void err_setval(exception, value) - object *exception; - object *value; + object *exception; + object *value; { - XDECREF(last_exception); - XINCREF(exception); - last_exception = exception; - - XDECREF(last_exc_val); - XINCREF(value); - last_exc_val = value; + XDECREF(last_exception); + XINCREF(exception); + last_exception = exception; + + XDECREF(last_exc_val); + XINCREF(value); + last_exc_val = value; } void err_set(exception) - object *exception; + object *exception; { - err_setval(exception, (object *)NULL); + err_setval(exception, (object *)NULL); } void err_setstr(exception, string) - object *exception; - char *string; + object *exception; + char *string; { - object *value = newstringobject(string); - err_setval(exception, value); - XDECREF(value); + object *value = newstringobject(string); + err_setval(exception, value); + XDECREF(value); } int err_occurred() { - return last_exception != NULL; + return last_exception != NULL; } void err_get(p_exc, p_val) - object **p_exc; - object **p_val; + object **p_exc; + object **p_val; { - *p_exc = last_exception; - last_exception = NULL; - *p_val = last_exc_val; - last_exc_val = NULL; + *p_exc = last_exception; + last_exception = NULL; + *p_val = last_exc_val; + last_exc_val = NULL; } void err_clear() { - XDECREF(last_exception); - last_exception = NULL; - XDECREF(last_exc_val); - last_exc_val = NULL; + XDECREF(last_exception); + last_exception = NULL; + XDECREF(last_exc_val); + last_exc_val = NULL; } /* Convenience functions to set a type error exception and return 0 */ @@ -133,64 +133,64 @@ err_clear() int err_badarg() { - err_setstr(TypeError, "illegal argument type for built-in operation"); - return 0; + err_setstr(TypeError, "illegal argument type for built-in operation"); + return 0; } object * err_nomem() { - err_set(MemoryError); - return NULL; + err_set(MemoryError); + return NULL; } object * err_errno(exc) - object *exc; + object *exc; { - object *v = newtupleobject(2); - if (v != NULL) { - settupleitem(v, 0, newintobject((long)errno)); - settupleitem(v, 1, newstringobject(strerror(errno))); - } - err_setval(exc, v); - XDECREF(v); - return NULL; + object *v = newtupleobject(2); + if (v != NULL) { + settupleitem(v, 0, newintobject((long)errno)); + settupleitem(v, 1, newstringobject(strerror(errno))); + } + err_setval(exc, v); + XDECREF(v); + return NULL; } void err_badcall() { - err_setstr(SystemError, "bad argument to internal function"); + err_setstr(SystemError, "bad argument to internal function"); } /* Set the error appropriate to the given input error code (see errcode.h) */ void err_input(err) - int err; + int err; { - switch (err) { - case E_DONE: - case E_OK: - break; - case E_SYNTAX: - err_setstr(RuntimeError, "syntax error"); - break; - case E_TOKEN: - err_setstr(RuntimeError, "illegal token"); - break; - case E_INTR: - err_set(KeyboardInterrupt); - break; - case E_NOMEM: - err_nomem(); - break; - case E_EOF: - err_set(EOFError); - break; - default: - err_setstr(RuntimeError, "unknown input error"); - break; - } + switch (err) { + case E_DONE: + case E_OK: + break; + case E_SYNTAX: + err_setstr(RuntimeError, "syntax error"); + break; + case E_TOKEN: + err_setstr(RuntimeError, "illegal token"); + break; + case E_INTR: + err_set(KeyboardInterrupt); + break; + case E_NOMEM: + err_nomem(); + break; + case E_EOF: + err_set(EOFError); + break; + default: + err_setstr(RuntimeError, "unknown input error"); + break; + } } diff --git a/src/errors.h b/src/errors.h index 4baa142..e40f6ce 100644 --- a/src/errors.h +++ b/src/errors.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -43,10 +43,10 @@ extern object *KeyboardInterrupt; /* Some more planned for the future */ -#define IndexError RuntimeError -#define KeyError RuntimeError -#define ZeroDivisionError RuntimeError -#define OverflowError RuntimeError +#define IndexError RuntimeError +#define KeyError RuntimeError +#define ZeroDivisionError RuntimeError +#define OverflowError RuntimeError /* Convenience functions */ diff --git a/src/fgetsintr.c b/src/fgetsintr.c index bda1ed8..136be73 100644 --- a/src/fgetsintr.c +++ b/src/fgetsintr.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -23,10 +23,10 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ /* Interruptable version of fgets(). - Return < 0 for interrupted, 1 for EOF, 0 for valid input. */ + Return < 0 for interrupted, 1 for EOF, 0 for valid input. */ /* XXX This uses longjmp() from a signal out of fgets(). - Should use read() instead?! */ + Should use read() instead?! */ #include "pgenheaders.h" @@ -38,8 +38,8 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include "fgetsintr.h" #ifndef AMOEBA -#define sig_block() /*empty*/ -#define sig_unblock() /*empty*/ +#define sig_block() /*empty*/ +#define sig_unblock() /*empty*/ #endif static jmp_buf jback; @@ -48,47 +48,47 @@ static void catcher PROTO((int)); static void catcher(sig) - int sig; + int sig; { - longjmp(jback, 1); + longjmp(jback, 1); } int fgets_intr(buf, size, fp) - char *buf; - int size; - FILE *fp; + char *buf; + int size; + FILE *fp; { - int ret; - SIGTYPE (*sigsave)(); - - if (setjmp(jback)) { - clearerr(fp); - signal(SIGINT, sigsave); + int ret; + SIGTYPE (*sigsave)(); + + if (setjmp(jback)) { + clearerr(fp); + signal(SIGINT, sigsave); #ifdef THINK_C_3_0 - Set_Echo(1); + Set_Echo(1); #endif - return E_INTR; - } - - /* The casts to (SIGTYPE(*)()) are needed by THINK_C only */ - - sigsave = signal(SIGINT, (SIGTYPE(*)()) SIG_IGN); - if (sigsave != (SIGTYPE(*)()) SIG_IGN) - signal(SIGINT, (SIGTYPE(*)()) catcher); - + return E_INTR; + } + + /* The casts to (SIGTYPE(*)()) are needed by THINK_C only */ + + sigsave = signal(SIGINT, (SIGTYPE(*)()) SIG_IGN); + if (sigsave != (SIGTYPE(*)()) SIG_IGN) + signal(SIGINT, (SIGTYPE(*)()) catcher); + #ifndef THINK_C - if (intrcheck()) - ret = E_INTR; - else + if (intrcheck()) + ret = E_INTR; + else #endif - { - sig_block(); - ret = (fgets(buf, size, fp) == NULL) ? E_EOF : E_OK; - sig_unblock(); - } - - if (sigsave != (SIGTYPE(*)()) SIG_IGN) - signal(SIGINT, (SIGTYPE(*)()) sigsave); - return ret; + { + sig_block(); + ret = (fgets(buf, size, fp) == NULL) ? E_EOF : E_OK; + sig_unblock(); + } + + if (sigsave != (SIGTYPE(*)()) SIG_IGN) + signal(SIGINT, (SIGTYPE(*)()) sigsave); + return ret; } diff --git a/src/fgetsintr.h b/src/fgetsintr.h index 87f1d2a..34c6cdc 100644 --- a/src/fgetsintr.h +++ b/src/fgetsintr.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. diff --git a/src/fileobject.c b/src/fileobject.c index 640e27b..09f19e5 100644 --- a/src/fileobject.c +++ b/src/fileobject.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -24,11 +24,11 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* File object implementation */ -/* XXX This should become a built-in module 'io'. It should support more - functionality, better exception handling for invalid calls, etc. - (Especially reading on a write-only file or vice versa!) - It should also cooperate with posix to support popen(), which should - share most code but have a special close function. */ +/* XXX This should become a built-in module 'io'. It should support more + functionality, better exception handling for invalid calls, etc. + (Especially reading on a write-only file or vice versa!) + It should also cooperate with posix to support popen(), which should + share most code but have a special close function. */ #include "allobjects.h" @@ -38,256 +38,256 @@ extern int errno; #endif typedef struct { - OB_HEAD - FILE *f_fp; - object *f_name; - object *f_mode; - /* XXX Should move the 'need space' on printing flag here */ + OB_HEAD + FILE *f_fp; + object *f_name; + object *f_mode; + /* XXX Should move the 'need space' on printing flag here */ } fileobject; FILE * getfilefile(f) - object *f; + object *f; { - if (!is_fileobject(f)) { - err_badcall(); - return NULL; - } - return ((fileobject *)f)->f_fp; + if (!is_fileobject(f)) { + err_badcall(); + return NULL; + } + return ((fileobject *)f)->f_fp; } object * newopenfileobject(fp, name, mode) - FILE *fp; - char *name; - char *mode; + FILE *fp; + char *name; + char *mode; { - fileobject *f = NEWOBJ(fileobject, &Filetype); - if (f == NULL) - return NULL; - f->f_fp = NULL; - f->f_name = newstringobject(name); - f->f_mode = newstringobject(mode); - if (f->f_name == NULL || f->f_mode == NULL) { - DECREF(f); - return NULL; - } - f->f_fp = fp; - return (object *) f; + fileobject *f = NEWOBJ(fileobject, &Filetype); + if (f == NULL) + return NULL; + f->f_fp = NULL; + f->f_name = newstringobject(name); + f->f_mode = newstringobject(mode); + if (f->f_name == NULL || f->f_mode == NULL) { + DECREF(f); + return NULL; + } + f->f_fp = fp; + return (object *) f; } object * newfileobject(name, mode) - char *name, *mode; + char *name, *mode; { - fileobject *f; - FILE *fp; - f = (fileobject *) newopenfileobject((FILE *)NULL, name, mode); - if (f == NULL) - return NULL; + fileobject *f; + FILE *fp; + f = (fileobject *) newopenfileobject((FILE *)NULL, name, mode); + if (f == NULL) + return NULL; #ifdef THINK_C - if (*mode == '*') { - FILE *fopenRF(); - f->f_fp = fopenRF(name, mode+1); - } - else + if (*mode == '*') { + FILE *fopenRF(); + f->f_fp = fopenRF(name, mode+1); + } + else #endif - f->f_fp = fopen(name, mode); - if (f->f_fp == NULL) { - err_errno(RuntimeError); - DECREF(f); - return NULL; - } - return (object *)f; + f->f_fp = fopen(name, mode); + if (f->f_fp == NULL) { + err_errno(RuntimeError); + DECREF(f); + return NULL; + } + return (object *)f; } /* Methods */ static void file_dealloc(f) - fileobject *f; + fileobject *f; { - if (f->f_fp != NULL) - fclose(f->f_fp); - if (f->f_name != NULL) - DECREF(f->f_name); - if (f->f_mode != NULL) - DECREF(f->f_mode); - free((char *)f); + if (f->f_fp != NULL) + fclose(f->f_fp); + if (f->f_name != NULL) + DECREF(f->f_name); + if (f->f_mode != NULL) + DECREF(f->f_mode); + free((char *)f); } static void file_print(f, fp, flags) - fileobject *f; - FILE *fp; - int flags; + fileobject *f; + FILE *fp; + int flags; { - fprintf(fp, "<%s file ", f->f_fp == NULL ? "closed" : "open"); - printobject(f->f_name, fp, flags); - fprintf(fp, ", mode "); - printobject(f->f_mode, fp, flags); - fprintf(fp, ">"); + fprintf(fp, "<%s file ", f->f_fp == NULL ? "closed" : "open"); + printobject(f->f_name, fp, flags); + fprintf(fp, ", mode "); + printobject(f->f_mode, fp, flags); + fprintf(fp, ">"); } static object * file_repr(f) - fileobject *f; + fileobject *f; { - char buf[300]; - /* XXX This differs from file_print if the filename contains - quotes or other funny characters. */ - sprintf(buf, "<%s file '%.256s', mode '%.10s'>", - f->f_fp == NULL ? "closed" : "open", - getstringvalue(f->f_name), - getstringvalue(f->f_mode)); - return newstringobject(buf); + char buf[300]; + /* XXX This differs from file_print if the filename contains + quotes or other funny characters. */ + sprintf(buf, "<%s file '%.256s', mode '%.10s'>", + f->f_fp == NULL ? "closed" : "open", + getstringvalue(f->f_name), + getstringvalue(f->f_mode)); + return newstringobject(buf); } static object * file_close(f, args) - fileobject *f; - object *args; + fileobject *f; + object *args; { - if (args != NULL) { - err_badarg(); - return NULL; - } - if (f->f_fp != NULL) { - fclose(f->f_fp); - f->f_fp = NULL; - } - INCREF(None); - return None; + if (args != NULL) { + err_badarg(); + return NULL; + } + if (f->f_fp != NULL) { + fclose(f->f_fp); + f->f_fp = NULL; + } + INCREF(None); + return None; } static object * file_read(f, args) - fileobject *f; - object *args; + fileobject *f; + object *args; { - int n; - object *v; - if (f->f_fp == NULL) { - err_badarg(); - return NULL; - } - if (args == NULL || !is_intobject(args)) { - err_badarg(); - return NULL; - } - n = getintvalue(args); - if (n < 0) { - err_badarg(); - return NULL; - } - v = newsizedstringobject((char *)NULL, n); - if (v == NULL) - return NULL; - n = fread(getstringvalue(v), 1, n, f->f_fp); - /* EOF is reported as an empty string */ - /* XXX should detect real I/O errors? */ - resizestring(&v, n); - return v; + int n; + object *v; + if (f->f_fp == NULL) { + err_badarg(); + return NULL; + } + if (args == NULL || !is_intobject(args)) { + err_badarg(); + return NULL; + } + n = getintvalue(args); + if (n < 0) { + err_badarg(); + return NULL; + } + v = newsizedstringobject((char *)NULL, n); + if (v == NULL) + return NULL; + n = fread(getstringvalue(v), 1, n, f->f_fp); + /* EOF is reported as an empty string */ + /* XXX should detect real I/O errors? */ + resizestring(&v, n); + return v; } /* XXX Should this be unified with raw_input()? */ static object * file_readline(f, args) - fileobject *f; - object *args; + fileobject *f; + object *args; { - int n; - object *v; - if (f->f_fp == NULL) { - err_badarg(); - return NULL; - } - if (args == NULL) { - n = 10000; /* XXX should really be unlimited */ - } - else if (is_intobject(args)) { - n = getintvalue(args); - if (n < 0) { - err_badarg(); - return NULL; - } - } - else { - err_badarg(); - return NULL; - } - v = newsizedstringobject((char *)NULL, n); - if (v == NULL) - return NULL; + int n; + object *v; + if (f->f_fp == NULL) { + err_badarg(); + return NULL; + } + if (args == NULL) { + n = 10000; /* XXX should really be unlimited */ + } + else if (is_intobject(args)) { + n = getintvalue(args); + if (n < 0) { + err_badarg(); + return NULL; + } + } + else { + err_badarg(); + return NULL; + } + v = newsizedstringobject((char *)NULL, n); + if (v == NULL) + return NULL; #ifndef THINK_C_3_0 - /* XXX Think C 3.0 wrongly reads up to n characters... */ - n = n+1; + /* XXX Think C 3.0 wrongly reads up to n characters... */ + n = n+1; #endif - if (fgets(getstringvalue(v), n, f->f_fp) == NULL) { - /* EOF is reported as an empty string */ - /* XXX should detect real I/O errors? */ - n = 0; - } - else { - n = strlen(getstringvalue(v)); - } - resizestring(&v, n); - return v; + if (fgets(getstringvalue(v), n, f->f_fp) == NULL) { + /* EOF is reported as an empty string */ + /* XXX should detect real I/O errors? */ + n = 0; + } + else { + n = strlen(getstringvalue(v)); + } + resizestring(&v, n); + return v; } static object * file_write(f, args) - fileobject *f; - object *args; + fileobject *f; + object *args; { - int n, n2; - if (f->f_fp == NULL) { - err_badarg(); - return NULL; - } - if (args == NULL || !is_stringobject(args)) { - err_badarg(); - return NULL; - } - errno = 0; - n2 = fwrite(getstringvalue(args), 1, n = getstringsize(args), f->f_fp); - if (n2 != n) { - if (errno == 0) - errno = EIO; - err_errno(RuntimeError); - return NULL; - } - INCREF(None); - return None; + int n, n2; + if (f->f_fp == NULL) { + err_badarg(); + return NULL; + } + if (args == NULL || !is_stringobject(args)) { + err_badarg(); + return NULL; + } + errno = 0; + n2 = fwrite(getstringvalue(args), 1, n = getstringsize(args), f->f_fp); + if (n2 != n) { + if (errno == 0) + errno = EIO; + err_errno(RuntimeError); + return NULL; + } + INCREF(None); + return None; } static struct methodlist file_methods[] = { - {"write", file_write}, - {"read", file_read}, - {"readline", file_readline}, - {"close", file_close}, - {NULL, NULL} /* sentinel */ + {"write", file_write}, + {"read", file_read}, + {"readline", file_readline}, + {"close", file_close}, + {NULL, NULL} /* sentinel */ }; static object * file_getattr(f, name) - fileobject *f; - char *name; + fileobject *f; + char *name; { - return findmethod(file_methods, (object *)f, name); + return findmethod(file_methods, (object *)f, name); } typeobject Filetype = { - OB_HEAD_INIT(&Typetype) - 0, - "file", - sizeof(fileobject), - 0, - file_dealloc, /*tp_dealloc*/ - file_print, /*tp_print*/ - file_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - file_repr, /*tp_repr*/ + OB_HEAD_INIT(&Typetype) + 0, + "file", + sizeof(fileobject), + 0, + file_dealloc, /*tp_dealloc*/ + file_print, /*tp_print*/ + file_getattr, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + file_repr, /*tp_repr*/ }; diff --git a/src/fileobject.h b/src/fileobject.h index eefae74..fc9988d 100644 --- a/src/fileobject.h +++ b/src/fileobject.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. diff --git a/src/firstsets.c b/src/firstsets.c index 6bd7ce0..2b5cd02 100644 --- a/src/firstsets.c +++ b/src/firstsets.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -35,99 +35,99 @@ static void calcfirstset PROTO((grammar *, dfa *)); void addfirstsets(g) - grammar *g; + grammar *g; { - int i; - dfa *d; - - printf("Adding FIRST sets ...\n"); - for (i = 0; i < g->g_ndfas; i++) { - d = &g->g_dfa[i]; - if (d->d_first == NULL) - calcfirstset(g, d); - } + int i; + dfa *d; + + printf("Adding FIRST sets ...\n"); + for (i = 0; i < g->g_ndfas; i++) { + d = &g->g_dfa[i]; + if (d->d_first == NULL) + calcfirstset(g, d); + } } static void calcfirstset(g, d) - grammar *g; - dfa *d; + grammar *g; + dfa *d; { - int i, j; - state *s; - arc *a; - int nsyms; - int *sym; - int nbits; - static bitset dummy; - bitset result; - int type; - dfa *d1; - label *l0; - - if (debugging) - printf("Calculate FIRST set for '%s'\n", d->d_name); - - if (dummy == NULL) - dummy = newbitset(1); - if (d->d_first == dummy) { - fprintf(stderr, "Left-recursion for '%s'\n", d->d_name); - return; - } - if (d->d_first != NULL) { - fprintf(stderr, "Re-calculating FIRST set for '%s' ???\n", - d->d_name); - } - d->d_first = dummy; - - l0 = g->g_ll.ll_label; - nbits = g->g_ll.ll_nlabels; - result = newbitset(nbits); - - sym = NEW(int, 1); - if (sym == NULL) - fatal("no mem for new sym in calcfirstset"); - nsyms = 1; - sym[0] = findlabel(&g->g_ll, d->d_type, (char *)NULL); - - s = &d->d_state[d->d_initial]; - for (i = 0; i < s->s_narcs; i++) { - a = &s->s_arc[i]; - for (j = 0; j < nsyms; j++) { - if (sym[j] == a->a_lbl) - break; - } - if (j >= nsyms) { /* New label */ - RESIZE(sym, int, nsyms + 1); - if (sym == NULL) - fatal("no mem to resize sym in calcfirstset"); - sym[nsyms++] = a->a_lbl; - type = l0[a->a_lbl].lb_type; - if (ISNONTERMINAL(type)) { - d1 = finddfa(g, type); - if (d1->d_first == dummy) { - fprintf(stderr, - "Left-recursion below '%s'\n", - d->d_name); - } - else { - if (d1->d_first == NULL) - calcfirstset(g, d1); - mergebitset(result, d1->d_first, nbits); - } - } - else if (ISTERMINAL(type)) { - addbit(result, a->a_lbl); - } - } - } - d->d_first = result; - if (debugging) { - printf("FIRST set for '%s': {", d->d_name); - for (i = 0; i < nbits; i++) { - if (testbit(result, i)) - printf(" %s", labelrepr(&l0[i])); - } - printf(" }\n"); - } + int i, j; + state *s; + arc *a; + int nsyms; + int *sym; + int nbits; + static bitset dummy; + bitset result; + int type; + dfa *d1; + label *l0; + + if (debugging) + printf("Calculate FIRST set for '%s'\n", d->d_name); + + if (dummy == NULL) + dummy = newbitset(1); + if (d->d_first == dummy) { + fprintf(stderr, "Left-recursion for '%s'\n", d->d_name); + return; + } + if (d->d_first != NULL) { + fprintf(stderr, "Re-calculating FIRST set for '%s' ???\n", + d->d_name); + } + d->d_first = dummy; + + l0 = g->g_ll.ll_label; + nbits = g->g_ll.ll_nlabels; + result = newbitset(nbits); + + sym = NEW(int, 1); + if (sym == NULL) + fatal("no mem for new sym in calcfirstset"); + nsyms = 1; + sym[0] = findlabel(&g->g_ll, d->d_type, (char *)NULL); + + s = &d->d_state[d->d_initial]; + for (i = 0; i < s->s_narcs; i++) { + a = &s->s_arc[i]; + for (j = 0; j < nsyms; j++) { + if (sym[j] == a->a_lbl) + break; + } + if (j >= nsyms) { /* New label */ + RESIZE(sym, int, nsyms + 1); + if (sym == NULL) + fatal("no mem to resize sym in calcfirstset"); + sym[nsyms++] = a->a_lbl; + type = l0[a->a_lbl].lb_type; + if (ISNONTERMINAL(type)) { + d1 = finddfa(g, type); + if (d1->d_first == dummy) { + fprintf(stderr, + "Left-recursion below '%s'\n", + d->d_name); + } + else { + if (d1->d_first == NULL) + calcfirstset(g, d1); + mergebitset(result, d1->d_first, nbits); + } + } + else if (ISTERMINAL(type)) { + addbit(result, a->a_lbl); + } + } + } + d->d_first = result; + if (debugging) { + printf("FIRST set for '%s': {", d->d_name); + for (i = 0; i < nbits; i++) { + if (testbit(result, i)) + printf(" %s", labelrepr(&l0[i])); + } + printf(" }\n"); + } } diff --git a/src/floatobject.c b/src/floatobject.c index c637989..bbf785f 100644 --- a/src/floatobject.c +++ b/src/floatobject.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -25,7 +25,7 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* Float object implementation */ /* XXX There should be overflow checks here, but it's hard to check - for any kind of float exception without losing portability. */ + for any kind of float exception without losing portability. */ #include "allobjects.h" @@ -44,227 +44,227 @@ extern double pow PROTO((double, double)); object * newfloatobject(fval) - double fval; + double fval; { - /* For efficiency, this code is copied from newobject() */ - register floatobject *op = (floatobject *) malloc(sizeof(floatobject)); - if (op == NULL) - return err_nomem(); - NEWREF(op); - op->ob_type = &Floattype; - op->ob_fval = fval; - return (object *) op; + /* For efficiency, this code is copied from newobject() */ + register floatobject *op = (floatobject *) malloc(sizeof(floatobject)); + if (op == NULL) + return err_nomem(); + NEWREF(op); + op->ob_type = &Floattype; + op->ob_fval = fval; + return (object *) op; } double getfloatvalue(op) - object *op; + object *op; { - if (!is_floatobject(op)) { - err_badarg(); - return -1; - } - else - return ((floatobject *)op) -> ob_fval; + if (!is_floatobject(op)) { + err_badarg(); + return -1; + } + else + return ((floatobject *)op) -> ob_fval; } /* Methods */ static void float_buf_repr(buf, v) - char *buf; - floatobject *v; + char *buf; + floatobject *v; { - register char *cp; - /* Subroutine for float_repr and float_print. - We want float numbers to be recognizable as such, - i.e., they should contain a decimal point or an exponent. - However, %g may print the number as an integer; - in such cases, we append ".0" to the string. */ - sprintf(buf, "%.12g", v->ob_fval); - cp = buf; - if (*cp == '-') - cp++; - for (; *cp != '\0'; cp++) { - /* Any non-digit means it's not an integer; - this takes care of NAN and INF as well. */ - if (!isdigit(*cp)) - break; - } - if (*cp == '\0') { - *cp++ = '.'; - *cp++ = '0'; - *cp++ = '\0'; - } + register char *cp; + /* Subroutine for float_repr and float_print. + We want float numbers to be recognizable as such, + i.e., they should contain a decimal point or an exponent. + However, %g may print the number as an integer; + in such cases, we append ".0" to the string. */ + sprintf(buf, "%.12g", v->ob_fval); + cp = buf; + if (*cp == '-') + cp++; + for (; *cp != '\0'; cp++) { + /* Any non-digit means it's not an integer; + this takes care of NAN and INF as well. */ + if (!isdigit(*cp)) + break; + } + if (*cp == '\0') { + *cp++ = '.'; + *cp++ = '0'; + *cp++ = '\0'; + } } static void float_print(v, fp, flags) - floatobject *v; - FILE *fp; - int flags; + floatobject *v; + FILE *fp; + int flags; { - char buf[100]; - float_buf_repr(buf, v); - fputs(buf, fp); + char buf[100]; + float_buf_repr(buf, v); + fputs(buf, fp); } static object * float_repr(v) - floatobject *v; + floatobject *v; { - char buf[100]; - float_buf_repr(buf, v); - return newstringobject(buf); + char buf[100]; + float_buf_repr(buf, v); + return newstringobject(buf); } static int float_compare(v, w) - floatobject *v, *w; + floatobject *v, *w; { - double i = v->ob_fval; - double j = w->ob_fval; - return (i < j) ? -1 : (i > j) ? 1 : 0; + double i = v->ob_fval; + double j = w->ob_fval; + return (i < j) ? -1 : (i > j) ? 1 : 0; } static object * float_add(v, w) - floatobject *v; - object *w; + floatobject *v; + object *w; { - if (!is_floatobject(w)) { - err_badarg(); - return NULL; - } - return newfloatobject(v->ob_fval + ((floatobject *)w) -> ob_fval); + if (!is_floatobject(w)) { + err_badarg(); + return NULL; + } + return newfloatobject(v->ob_fval + ((floatobject *)w) -> ob_fval); } static object * float_sub(v, w) - floatobject *v; - object *w; + floatobject *v; + object *w; { - if (!is_floatobject(w)) { - err_badarg(); - return NULL; - } - return newfloatobject(v->ob_fval - ((floatobject *)w) -> ob_fval); + if (!is_floatobject(w)) { + err_badarg(); + return NULL; + } + return newfloatobject(v->ob_fval - ((floatobject *)w) -> ob_fval); } static object * float_mul(v, w) - floatobject *v; - object *w; + floatobject *v; + object *w; { - if (!is_floatobject(w)) { - err_badarg(); - return NULL; - } - return newfloatobject(v->ob_fval * ((floatobject *)w) -> ob_fval); + if (!is_floatobject(w)) { + err_badarg(); + return NULL; + } + return newfloatobject(v->ob_fval * ((floatobject *)w) -> ob_fval); } static object * float_div(v, w) - floatobject *v; - object *w; + floatobject *v; + object *w; { - if (!is_floatobject(w)) { - err_badarg(); - return NULL; - } - if (((floatobject *)w) -> ob_fval == 0) { - err_setstr(ZeroDivisionError, "float division by zero"); - return NULL; - } - return newfloatobject(v->ob_fval / ((floatobject *)w) -> ob_fval); + if (!is_floatobject(w)) { + err_badarg(); + return NULL; + } + if (((floatobject *)w) -> ob_fval == 0) { + err_setstr(ZeroDivisionError, "float division by zero"); + return NULL; + } + return newfloatobject(v->ob_fval / ((floatobject *)w) -> ob_fval); } static object * float_rem(v, w) - floatobject *v; - object *w; + floatobject *v; + object *w; { - double wx; - if (!is_floatobject(w)) { - err_badarg(); - return NULL; - } - wx = ((floatobject *)w) -> ob_fval; - if (wx == 0.0) { - err_setstr(ZeroDivisionError, "float division by zero"); - return NULL; - } - return newfloatobject(fmod(v->ob_fval, wx)); + double wx; + if (!is_floatobject(w)) { + err_badarg(); + return NULL; + } + wx = ((floatobject *)w) -> ob_fval; + if (wx == 0.0) { + err_setstr(ZeroDivisionError, "float division by zero"); + return NULL; + } + return newfloatobject(fmod(v->ob_fval, wx)); } static object * float_pow(v, w) - floatobject *v; - object *w; + floatobject *v; + object *w; { - double iv, iw, ix; - if (!is_floatobject(w)) { - err_badarg(); - return NULL; - } - iv = v->ob_fval; - iw = ((floatobject *)w)->ob_fval; - if (iw == 0.0) - return newfloatobject(1.0); /* x**0 is always 1, even 0**0 */ - errno = 0; - ix = pow(iv, iw); - if (errno != 0) { - /* XXX could it be another type of error? */ - err_errno(OverflowError); - return NULL; - } - return newfloatobject(ix); + double iv, iw, ix; + if (!is_floatobject(w)) { + err_badarg(); + return NULL; + } + iv = v->ob_fval; + iw = ((floatobject *)w)->ob_fval; + if (iw == 0.0) + return newfloatobject(1.0); /* x**0 is always 1, even 0**0 */ + errno = 0; + ix = pow(iv, iw); + if (errno != 0) { + /* XXX could it be another type of error? */ + err_errno(OverflowError); + return NULL; + } + return newfloatobject(ix); } static object * float_neg(v) - floatobject *v; + floatobject *v; { - return newfloatobject(-v->ob_fval); + return newfloatobject(-v->ob_fval); } static object * float_pos(v) - floatobject *v; + floatobject *v; { - return newfloatobject(v->ob_fval); + return newfloatobject(v->ob_fval); } static number_methods float_as_number = { - float_add, /*tp_add*/ - float_sub, /*tp_subtract*/ - float_mul, /*tp_multiply*/ - float_div, /*tp_divide*/ - float_rem, /*tp_remainder*/ - float_pow, /*tp_power*/ - float_neg, /*tp_negate*/ - float_pos, /*tp_plus*/ + float_add, /*tp_add*/ + float_sub, /*tp_subtract*/ + float_mul, /*tp_multiply*/ + float_div, /*tp_divide*/ + float_rem, /*tp_remainder*/ + float_pow, /*tp_power*/ + float_neg, /*tp_negate*/ + float_pos, /*tp_plus*/ }; typeobject Floattype = { - OB_HEAD_INIT(&Typetype) - 0, - "float", - sizeof(floatobject), - 0, - free, /*tp_dealloc*/ - float_print, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - float_compare, /*tp_compare*/ - float_repr, /*tp_repr*/ - &float_as_number, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ + OB_HEAD_INIT(&Typetype) + 0, + "float", + sizeof(floatobject), + 0, + free, /*tp_dealloc*/ + float_print, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + float_compare, /*tp_compare*/ + float_repr, /*tp_repr*/ + &float_as_number, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ }; /* -XXX This is not enough. Need: +XXX This is not enough. Need: - automatic casts for mixed arithmetic (3.1 * 4) - mixed comparisons (!) - look at other uses of ints that could be extended to floats diff --git a/src/floatobject.h b/src/floatobject.h index 52db73e..9741682 100644 --- a/src/floatobject.h +++ b/src/floatobject.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -29,8 +29,8 @@ floatobject represents a (double precision) floating point number. */ typedef struct { - OB_HEAD - double ob_fval; + OB_HEAD + double ob_fval; } floatobject; extern typeobject Floattype; @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -31,21 +31,21 @@ extern int errno; double fmod(x, y) - double x, y; + double x, y; { - double i, f; - - if (y == 0.0) { - errno = EDOM; - return 0.0; - } - - /* return f such that x = i*y + f for some integer i - such that |f| < |y| and f has the same sign as x */ - - i = floor(x/y); - f = x - i*y; - if ((x < 0.0) != (y < 0.0)) - f = f-y; - return f; + double i, f; + + if (y == 0.0) { + errno = EDOM; + return 0.0; + } + + /* return f such that x = i*y + f for some integer i + such that |f| < |y| and f has the same sign as x */ + + i = floor(x/y); + f = x - i*y; + if ((x < 0.0) != (y < 0.0)) + f = f-y; + return f; } diff --git a/src/frameobject.c b/src/frameobject.c index 4f9e250..f86b64d 100644 --- a/src/frameobject.c +++ b/src/frameobject.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -34,123 +34,123 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #define OFF(x) offsetof(frameobject, x) static struct memberlist frame_memberlist[] = { - {"f_back", T_OBJECT, OFF(f_back)}, - {"f_code", T_OBJECT, OFF(f_code)}, - {"f_globals", T_OBJECT, OFF(f_globals)}, - {"f_locals", T_OBJECT, OFF(f_locals)}, - {NULL} /* Sentinel */ + {"f_back", T_OBJECT, OFF(f_back)}, + {"f_code", T_OBJECT, OFF(f_code)}, + {"f_globals", T_OBJECT, OFF(f_globals)}, + {"f_locals", T_OBJECT, OFF(f_locals)}, + {NULL} /* Sentinel */ }; static object * frame_getattr(f, name) - frameobject *f; - char *name; + frameobject *f; + char *name; { - return getmember((char *)f, frame_memberlist, name); + return getmember((char *)f, frame_memberlist, name); } static void frame_dealloc(f) - frameobject *f; + frameobject *f; { - XDECREF(f->f_back); - XDECREF(f->f_code); - XDECREF(f->f_globals); - XDECREF(f->f_locals); - XDEL(f->f_valuestack); - XDEL(f->f_blockstack); - DEL(f); + XDECREF(f->f_back); + XDECREF(f->f_code); + XDECREF(f->f_globals); + XDECREF(f->f_locals); + XDEL(f->f_valuestack); + XDEL(f->f_blockstack); + DEL(f); } typeobject Frametype = { - OB_HEAD_INIT(&Typetype) - 0, - "frame", - sizeof(frameobject), - 0, - frame_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - frame_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ + OB_HEAD_INIT(&Typetype) + 0, + "frame", + sizeof(frameobject), + 0, + frame_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + frame_getattr, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ }; frameobject * newframeobject(back, code, globals, locals, nvalues, nblocks) - frameobject *back; - codeobject *code; - object *globals; - object *locals; - int nvalues; - int nblocks; + frameobject *back; + codeobject *code; + object *globals; + object *locals; + int nvalues; + int nblocks; { - frameobject *f; - if ((back != NULL && !is_frameobject(back)) || - code == NULL || !is_codeobject(code) || - globals == NULL || !is_dictobject(globals) || - locals == NULL || !is_dictobject(locals) || - nvalues < 0 || nblocks < 0) { - err_badcall(); - return NULL; - } - f = NEWOBJ(frameobject, &Frametype); - if (f != NULL) { - if (back) - INCREF(back); - f->f_back = back; - INCREF(code); - f->f_code = code; - INCREF(globals); - f->f_globals = globals; - INCREF(locals); - f->f_locals = locals; - f->f_valuestack = NEW(object *, nvalues+1); - f->f_blockstack = NEW(block, nblocks+1); - f->f_nvalues = nvalues; - f->f_nblocks = nblocks; - f->f_iblock = 0; - if (f->f_valuestack == NULL || f->f_blockstack == NULL) { - err_nomem(); - DECREF(f); - f = NULL; - } - } - return f; + frameobject *f; + if ((back != NULL && !is_frameobject(back)) || + code == NULL || !is_codeobject(code) || + globals == NULL || !is_dictobject(globals) || + locals == NULL || !is_dictobject(locals) || + nvalues < 0 || nblocks < 0) { + err_badcall(); + return NULL; + } + f = NEWOBJ(frameobject, &Frametype); + if (f != NULL) { + if (back) + INCREF(back); + f->f_back = back; + INCREF(code); + f->f_code = code; + INCREF(globals); + f->f_globals = globals; + INCREF(locals); + f->f_locals = locals; + f->f_valuestack = NEW(object *, nvalues+1); + f->f_blockstack = NEW(block, nblocks+1); + f->f_nvalues = nvalues; + f->f_nblocks = nblocks; + f->f_iblock = 0; + if (f->f_valuestack == NULL || f->f_blockstack == NULL) { + err_nomem(); + DECREF(f); + f = NULL; + } + } + return f; } /* Block management */ void setup_block(f, type, handler, level) - frameobject *f; - int type; - int handler; - int level; + frameobject *f; + int type; + int handler; + int level; { - block *b; - if (f->f_iblock >= f->f_nblocks) { - fprintf(stderr, "XXX block stack overflow\n"); - abort(); - } - b = &f->f_blockstack[f->f_iblock++]; - b->b_type = type; - b->b_level = level; - b->b_handler = handler; + block *b; + if (f->f_iblock >= f->f_nblocks) { + fprintf(stderr, "XXX block stack overflow\n"); + abort(); + } + b = &f->f_blockstack[f->f_iblock++]; + b->b_type = type; + b->b_level = level; + b->b_handler = handler; } block * pop_block(f) - frameobject *f; + frameobject *f; { - block *b; - if (f->f_iblock <= 0) { - fprintf(stderr, "XXX block stack underflow\n"); - abort(); - } - b = &f->f_blockstack[--f->f_iblock]; - return b; + block *b; + if (f->f_iblock <= 0) { + fprintf(stderr, "XXX block stack underflow\n"); + abort(); + } + b = &f->f_blockstack[--f->f_iblock]; + return b; } diff --git a/src/frameobject.h b/src/frameobject.h index 8ea0fa2..63e6046 100644 --- a/src/frameobject.h +++ b/src/frameobject.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -25,22 +25,22 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* Frame object interface */ typedef struct { - int b_type; /* what kind of block this is */ - int b_handler; /* where to jump to find handler */ - int b_level; /* value stack level to pop to */ + int b_type; /* what kind of block this is */ + int b_handler; /* where to jump to find handler */ + int b_level; /* value stack level to pop to */ } block; typedef struct _frame { - OB_HEAD - struct _frame *f_back; /* previous frame, or NULL */ - codeobject *f_code; /* code segment */ - object *f_globals; /* global symbol table (dictobject) */ - object *f_locals; /* local symbol table (dictobject) */ - object **f_valuestack; /* malloc'ed array */ - block *f_blockstack; /* malloc'ed array */ - int f_nvalues; /* size of f_valuestack */ - int f_nblocks; /* size of f_blockstack */ - int f_iblock; /* index in f_blockstack */ + OB_HEAD + struct _frame *f_back; /* previous frame, or NULL */ + codeobject *f_code; /* code segment */ + object *f_globals; /* global symbol table (dictobject) */ + object *f_locals; /* local symbol table (dictobject) */ + object **f_valuestack; /* malloc'ed array */ + block *f_blockstack; /* malloc'ed array */ + int f_nvalues; /* size of f_valuestack */ + int f_nblocks; /* size of f_blockstack */ + int f_iblock; /* index in f_blockstack */ } frameobject; @@ -51,7 +51,7 @@ extern typeobject Frametype; #define is_frameobject(op) ((op)->ob_type == &Frametype) frameobject * newframeobject PROTO( - (frameobject *, codeobject *, object *, object *, int, int)); + (frameobject *, codeobject *, object *, object *, int, int)); /* The rest of the interface is specific for frame objects */ @@ -70,8 +70,8 @@ frameobject * newframeobject PROTO( /* Code access macros */ -#define Getconst(f, i) (GETITEM((f)->f_code->co_consts, (i))) -#define Getname(f, i) (GETITEMNAME((f)->f_code->co_names, (i))) +#define Getconst(f, i) (GETITEM((f)->f_code->co_consts, (i))) +#define Getname(f, i) (GETITEMNAME((f)->f_code->co_names, (i))) /* Block management functions */ diff --git a/src/funcobject.c b/src/funcobject.c index 1088d7b..64e3518 100644 --- a/src/funcobject.c +++ b/src/funcobject.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -29,46 +29,46 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include "structmember.h" typedef struct { - OB_HEAD - object *func_code; - object *func_globals; + OB_HEAD + object *func_code; + object *func_globals; } funcobject; object * newfuncobject(code, globals) - object *code; - object *globals; + object *code; + object *globals; { - funcobject *op = NEWOBJ(funcobject, &Functype); - if (op != NULL) { - INCREF(code); - op->func_code = code; - INCREF(globals); - op->func_globals = globals; - } - return (object *)op; + funcobject *op = NEWOBJ(funcobject, &Functype); + if (op != NULL) { + INCREF(code); + op->func_code = code; + INCREF(globals); + op->func_globals = globals; + } + return (object *)op; } object * getfunccode(op) - object *op; + object *op; { - if (!is_funcobject(op)) { - err_badcall(); - return NULL; - } - return ((funcobject *) op) -> func_code; + if (!is_funcobject(op)) { + err_badcall(); + return NULL; + } + return ((funcobject *) op) -> func_code; } object * getfuncglobals(op) - object *op; + object *op; { - if (!is_funcobject(op)) { - err_badcall(); - return NULL; - } - return ((funcobject *) op) -> func_globals; + if (!is_funcobject(op)) { + err_badcall(); + return NULL; + } + return ((funcobject *) op) -> func_globals; } /* Methods */ @@ -76,38 +76,38 @@ getfuncglobals(op) #define OFF(x) offsetof(funcobject, x) static struct memberlist func_memberlist[] = { - {"func_code", T_OBJECT, OFF(func_code)}, - {"func_globals",T_OBJECT, OFF(func_globals)}, - {NULL} /* Sentinel */ + {"func_code", T_OBJECT, OFF(func_code)}, + {"func_globals",T_OBJECT, OFF(func_globals)}, + {NULL} /* Sentinel */ }; static object * func_getattr(op, name) - funcobject *op; - char *name; + funcobject *op; + char *name; { - return getmember((char *)op, func_memberlist, name); + return getmember((char *)op, func_memberlist, name); } static void func_dealloc(op) - funcobject *op; + funcobject *op; { - DECREF(op->func_code); - DECREF(op->func_globals); - DEL(op); + DECREF(op->func_code); + DECREF(op->func_globals); + DEL(op); } typeobject Functype = { - OB_HEAD_INIT(&Typetype) - 0, - "function", - sizeof(funcobject), - 0, - func_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - func_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ + OB_HEAD_INIT(&Typetype) + 0, + "function", + sizeof(funcobject), + 0, + func_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + func_getattr, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ }; diff --git a/src/funcobject.h b/src/funcobject.h index de8b1a7..b861663 100644 --- a/src/funcobject.h +++ b/src/funcobject.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. diff --git a/src/getcwd.c b/src/getcwd.c index 3de6291..4bfff82 100644 --- a/src/getcwd.c +++ b/src/getcwd.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -23,7 +23,7 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ /* Two PD getcwd() implementations. - Author: Guido van Rossum, CWI Amsterdam, Jan 1991, <[email protected]>. */ + Author: Guido van Rossum, CWI Amsterdam, Jan 1991, <[email protected]>. */ /* #define NO_GETWD /* Turn this on to popen pwd instead of calling getwd() */ @@ -42,27 +42,27 @@ extern char *getwd(); char * getcwd(buf, size) - char *buf; - int size; + char *buf; + int size; { - char localbuf[MAXPATHLEN+1]; - char *ret; - - if (size <= 0) { - errno = EINVAL; - return NULL; - } - ret = getwd(localbuf); - if (ret != NULL && strlen(localbuf) >= size) { - errno = ERANGE; - return NULL; - } - if (ret == NULL) { - errno = EACCES; /* Most likely error */ - return NULL; - } - strncpy(buf, localbuf, size); - return buf; + char localbuf[MAXPATHLEN+1]; + char *ret; + + if (size <= 0) { + errno = EINVAL; + return NULL; + } + ret = getwd(localbuf); + if (ret != NULL && strlen(localbuf) >= size) { + errno = ERANGE; + return NULL; + } + if (ret == NULL) { + errno = EACCES; /* Most likely error */ + return NULL; + } + strncpy(buf, localbuf, size); + return buf; } #else @@ -73,30 +73,30 @@ getcwd(buf, size) char * getcwd(buf, size) - char *buf; - int size; + char *buf; + int size; { - FILE *fp; - char *p; - int sts; - if (size <= 0) { - errno = EINVAL; - return NULL; - } - if ((fp = popen(PWD_CMD, "r")) == NULL) - return NULL; - if (fgets(buf, size, fp) == NULL || (sts = pclose(fp)) != 0) { - errno = EACCES; /* Most likely error */ - return NULL; - } - for (p = buf; *p != '\n'; p++) { - if (*p == '\0') { - errno = ERANGE; - return NULL; - } - } - *p = '\0'; - return buf; + FILE *fp; + char *p; + int sts; + if (size <= 0) { + errno = EINVAL; + return NULL; + } + if ((fp = popen(PWD_CMD, "r")) == NULL) + return NULL; + if (fgets(buf, size, fp) == NULL || (sts = pclose(fp)) != 0) { + errno = EACCES; /* Most likely error */ + return NULL; + } + for (p = buf; *p != '\n'; p++) { + if (*p == '\0') { + errno = ERANGE; + return NULL; + } + } + *p = '\0'; + return buf; } #endif diff --git a/src/graminit.c b/src/graminit.c index 2f18183..7183327 100644 --- a/src/graminit.c +++ b/src/graminit.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -25,1070 +25,1070 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include "pgenheaders.h" #include "grammar.h" static arc arcs_0_0[3] = { - {2, 1}, - {3, 1}, - {4, 2}, + {2, 1}, + {3, 1}, + {4, 2}, }; static arc arcs_0_1[1] = { - {0, 1}, + {0, 1}, }; static arc arcs_0_2[1] = { - {2, 1}, + {2, 1}, }; static state states_0[3] = { - {3, arcs_0_0}, - {1, arcs_0_1}, - {1, arcs_0_2}, + {3, arcs_0_0}, + {1, arcs_0_1}, + {1, arcs_0_2}, }; static arc arcs_1_0[3] = { - {2, 0}, - {6, 0}, - {7, 1}, + {2, 0}, + {6, 0}, + {7, 1}, }; static arc arcs_1_1[1] = { - {0, 1}, + {0, 1}, }; static state states_1[2] = { - {3, arcs_1_0}, - {1, arcs_1_1}, + {3, arcs_1_0}, + {1, arcs_1_1}, }; static arc arcs_2_0[1] = { - {9, 1}, + {9, 1}, }; static arc arcs_2_1[1] = { - {2, 2}, + {2, 2}, }; static arc arcs_2_2[1] = { - {0, 2}, + {0, 2}, }; static state states_2[3] = { - {1, arcs_2_0}, - {1, arcs_2_1}, - {1, arcs_2_2}, + {1, arcs_2_0}, + {1, arcs_2_1}, + {1, arcs_2_2}, }; static arc arcs_3_0[1] = { - {9, 1}, + {9, 1}, }; static arc arcs_3_1[1] = { - {7, 2}, + {7, 2}, }; static arc arcs_3_2[1] = { - {0, 2}, + {0, 2}, }; static state states_3[3] = { - {1, arcs_3_0}, - {1, arcs_3_1}, - {1, arcs_3_2}, + {1, arcs_3_0}, + {1, arcs_3_1}, + {1, arcs_3_2}, }; static arc arcs_4_0[1] = { - {12, 1}, + {12, 1}, }; static arc arcs_4_1[1] = { - {13, 2}, + {13, 2}, }; static arc arcs_4_2[1] = { - {14, 3}, + {14, 3}, }; static arc arcs_4_3[1] = { - {15, 4}, + {15, 4}, }; static arc arcs_4_4[1] = { - {16, 5}, + {16, 5}, }; static arc arcs_4_5[1] = { - {0, 5}, + {0, 5}, }; static state states_4[6] = { - {1, arcs_4_0}, - {1, arcs_4_1}, - {1, arcs_4_2}, - {1, arcs_4_3}, - {1, arcs_4_4}, - {1, arcs_4_5}, + {1, arcs_4_0}, + {1, arcs_4_1}, + {1, arcs_4_2}, + {1, arcs_4_3}, + {1, arcs_4_4}, + {1, arcs_4_5}, }; static arc arcs_5_0[1] = { - {17, 1}, + {17, 1}, }; static arc arcs_5_1[2] = { - {18, 2}, - {19, 3}, + {18, 2}, + {19, 3}, }; static arc arcs_5_2[1] = { - {19, 3}, + {19, 3}, }; static arc arcs_5_3[1] = { - {0, 3}, + {0, 3}, }; static state states_5[4] = { - {1, arcs_5_0}, - {2, arcs_5_1}, - {1, arcs_5_2}, - {1, arcs_5_3}, + {1, arcs_5_0}, + {2, arcs_5_1}, + {1, arcs_5_2}, + {1, arcs_5_3}, }; static arc arcs_6_0[1] = { - {20, 1}, + {20, 1}, }; static arc arcs_6_1[2] = { - {21, 0}, - {0, 1}, + {21, 0}, + {0, 1}, }; static state states_6[2] = { - {1, arcs_6_0}, - {2, arcs_6_1}, + {1, arcs_6_0}, + {2, arcs_6_1}, }; static arc arcs_7_0[2] = { - {13, 1}, - {17, 2}, + {13, 1}, + {17, 2}, }; static arc arcs_7_1[1] = { - {0, 1}, + {0, 1}, }; static arc arcs_7_2[1] = { - {18, 3}, + {18, 3}, }; static arc arcs_7_3[1] = { - {19, 1}, + {19, 1}, }; static state states_7[4] = { - {2, arcs_7_0}, - {1, arcs_7_1}, - {1, arcs_7_2}, - {1, arcs_7_3}, + {2, arcs_7_0}, + {1, arcs_7_1}, + {1, arcs_7_2}, + {1, arcs_7_3}, }; static arc arcs_8_0[2] = { - {3, 1}, - {4, 1}, + {3, 1}, + {4, 1}, }; static arc arcs_8_1[1] = { - {0, 1}, + {0, 1}, }; static state states_8[2] = { - {2, arcs_8_0}, - {1, arcs_8_1}, + {2, arcs_8_0}, + {1, arcs_8_1}, }; static arc arcs_9_0[6] = { - {22, 1}, - {23, 1}, - {24, 1}, - {25, 1}, - {26, 1}, - {27, 1}, + {22, 1}, + {23, 1}, + {24, 1}, + {25, 1}, + {26, 1}, + {27, 1}, }; static arc arcs_9_1[1] = { - {0, 1}, + {0, 1}, }; static state states_9[2] = { - {6, arcs_9_0}, - {1, arcs_9_1}, + {6, arcs_9_0}, + {1, arcs_9_1}, }; static arc arcs_10_0[1] = { - {28, 1}, + {28, 1}, }; static arc arcs_10_1[2] = { - {29, 0}, - {2, 2}, + {29, 0}, + {2, 2}, }; static arc arcs_10_2[1] = { - {0, 2}, + {0, 2}, }; static state states_10[3] = { - {1, arcs_10_0}, - {2, arcs_10_1}, - {1, arcs_10_2}, + {1, arcs_10_0}, + {2, arcs_10_1}, + {1, arcs_10_2}, }; static arc arcs_11_0[1] = { - {30, 1}, + {30, 1}, }; static arc arcs_11_1[2] = { - {31, 2}, - {2, 3}, + {31, 2}, + {2, 3}, }; static arc arcs_11_2[2] = { - {21, 1}, - {2, 3}, + {21, 1}, + {2, 3}, }; static arc arcs_11_3[1] = { - {0, 3}, + {0, 3}, }; static state states_11[4] = { - {1, arcs_11_0}, - {2, arcs_11_1}, - {2, arcs_11_2}, - {1, arcs_11_3}, + {1, arcs_11_0}, + {2, arcs_11_1}, + {2, arcs_11_2}, + {1, arcs_11_3}, }; static arc arcs_12_0[1] = { - {32, 1}, + {32, 1}, }; static arc arcs_12_1[1] = { - {28, 2}, + {28, 2}, }; static arc arcs_12_2[1] = { - {2, 3}, + {2, 3}, }; static arc arcs_12_3[1] = { - {0, 3}, + {0, 3}, }; static state states_12[4] = { - {1, arcs_12_0}, - {1, arcs_12_1}, - {1, arcs_12_2}, - {1, arcs_12_3}, + {1, arcs_12_0}, + {1, arcs_12_1}, + {1, arcs_12_2}, + {1, arcs_12_3}, }; static arc arcs_13_0[1] = { - {33, 1}, + {33, 1}, }; static arc arcs_13_1[1] = { - {2, 2}, + {2, 2}, }; static arc arcs_13_2[1] = { - {0, 2}, + {0, 2}, }; static state states_13[3] = { - {1, arcs_13_0}, - {1, arcs_13_1}, - {1, arcs_13_2}, + {1, arcs_13_0}, + {1, arcs_13_1}, + {1, arcs_13_2}, }; static arc arcs_14_0[3] = { - {34, 1}, - {35, 1}, - {36, 1}, + {34, 1}, + {35, 1}, + {36, 1}, }; static arc arcs_14_1[1] = { - {0, 1}, + {0, 1}, }; static state states_14[2] = { - {3, arcs_14_0}, - {1, arcs_14_1}, + {3, arcs_14_0}, + {1, arcs_14_1}, }; static arc arcs_15_0[1] = { - {37, 1}, + {37, 1}, }; static arc arcs_15_1[1] = { - {2, 2}, + {2, 2}, }; static arc arcs_15_2[1] = { - {0, 2}, + {0, 2}, }; static state states_15[3] = { - {1, arcs_15_0}, - {1, arcs_15_1}, - {1, arcs_15_2}, + {1, arcs_15_0}, + {1, arcs_15_1}, + {1, arcs_15_2}, }; static arc arcs_16_0[1] = { - {38, 1}, + {38, 1}, }; static arc arcs_16_1[2] = { - {9, 2}, - {2, 3}, + {9, 2}, + {2, 3}, }; static arc arcs_16_2[1] = { - {2, 3}, + {2, 3}, }; static arc arcs_16_3[1] = { - {0, 3}, + {0, 3}, }; static state states_16[4] = { - {1, arcs_16_0}, - {2, arcs_16_1}, - {1, arcs_16_2}, - {1, arcs_16_3}, + {1, arcs_16_0}, + {2, arcs_16_1}, + {1, arcs_16_2}, + {1, arcs_16_3}, }; static arc arcs_17_0[1] = { - {39, 1}, + {39, 1}, }; static arc arcs_17_1[1] = { - {40, 2}, + {40, 2}, }; static arc arcs_17_2[2] = { - {21, 3}, - {2, 4}, + {21, 3}, + {2, 4}, }; static arc arcs_17_3[1] = { - {40, 5}, + {40, 5}, }; static arc arcs_17_4[1] = { - {0, 4}, + {0, 4}, }; static arc arcs_17_5[1] = { - {2, 4}, + {2, 4}, }; static state states_17[6] = { - {1, arcs_17_0}, - {1, arcs_17_1}, - {2, arcs_17_2}, - {1, arcs_17_3}, - {1, arcs_17_4}, - {1, arcs_17_5}, + {1, arcs_17_0}, + {1, arcs_17_1}, + {2, arcs_17_2}, + {1, arcs_17_3}, + {1, arcs_17_4}, + {1, arcs_17_5}, }; static arc arcs_18_0[2] = { - {41, 1}, - {42, 2}, + {41, 1}, + {42, 2}, }; static arc arcs_18_1[1] = { - {13, 3}, + {13, 3}, }; static arc arcs_18_2[1] = { - {13, 4}, + {13, 4}, }; static arc arcs_18_3[2] = { - {21, 1}, - {2, 5}, + {21, 1}, + {2, 5}, }; static arc arcs_18_4[1] = { - {41, 6}, + {41, 6}, }; static arc arcs_18_5[1] = { - {0, 5}, + {0, 5}, }; static arc arcs_18_6[2] = { - {43, 7}, - {13, 8}, + {43, 7}, + {13, 8}, }; static arc arcs_18_7[1] = { - {2, 5}, + {2, 5}, }; static arc arcs_18_8[2] = { - {21, 9}, - {2, 5}, + {21, 9}, + {2, 5}, }; static arc arcs_18_9[1] = { - {13, 8}, + {13, 8}, }; static state states_18[10] = { - {2, arcs_18_0}, - {1, arcs_18_1}, - {1, arcs_18_2}, - {2, arcs_18_3}, - {1, arcs_18_4}, - {1, arcs_18_5}, - {2, arcs_18_6}, - {1, arcs_18_7}, - {2, arcs_18_8}, - {1, arcs_18_9}, + {2, arcs_18_0}, + {1, arcs_18_1}, + {1, arcs_18_2}, + {2, arcs_18_3}, + {1, arcs_18_4}, + {1, arcs_18_5}, + {2, arcs_18_6}, + {1, arcs_18_7}, + {2, arcs_18_8}, + {1, arcs_18_9}, }; static arc arcs_19_0[6] = { - {44, 1}, - {45, 1}, - {46, 1}, - {47, 1}, - {11, 1}, - {48, 1}, + {44, 1}, + {45, 1}, + {46, 1}, + {47, 1}, + {11, 1}, + {48, 1}, }; static arc arcs_19_1[1] = { - {0, 1}, + {0, 1}, }; static state states_19[2] = { - {6, arcs_19_0}, - {1, arcs_19_1}, + {6, arcs_19_0}, + {1, arcs_19_1}, }; static arc arcs_20_0[1] = { - {49, 1}, + {49, 1}, }; static arc arcs_20_1[1] = { - {31, 2}, + {31, 2}, }; static arc arcs_20_2[1] = { - {15, 3}, + {15, 3}, }; static arc arcs_20_3[1] = { - {16, 4}, + {16, 4}, }; static arc arcs_20_4[3] = { - {50, 1}, - {51, 5}, - {0, 4}, + {50, 1}, + {51, 5}, + {0, 4}, }; static arc arcs_20_5[1] = { - {15, 6}, + {15, 6}, }; static arc arcs_20_6[1] = { - {16, 7}, + {16, 7}, }; static arc arcs_20_7[1] = { - {0, 7}, + {0, 7}, }; static state states_20[8] = { - {1, arcs_20_0}, - {1, arcs_20_1}, - {1, arcs_20_2}, - {1, arcs_20_3}, - {3, arcs_20_4}, - {1, arcs_20_5}, - {1, arcs_20_6}, - {1, arcs_20_7}, + {1, arcs_20_0}, + {1, arcs_20_1}, + {1, arcs_20_2}, + {1, arcs_20_3}, + {3, arcs_20_4}, + {1, arcs_20_5}, + {1, arcs_20_6}, + {1, arcs_20_7}, }; static arc arcs_21_0[1] = { - {52, 1}, + {52, 1}, }; static arc arcs_21_1[1] = { - {31, 2}, + {31, 2}, }; static arc arcs_21_2[1] = { - {15, 3}, + {15, 3}, }; static arc arcs_21_3[1] = { - {16, 4}, + {16, 4}, }; static arc arcs_21_4[2] = { - {51, 5}, - {0, 4}, + {51, 5}, + {0, 4}, }; static arc arcs_21_5[1] = { - {15, 6}, + {15, 6}, }; static arc arcs_21_6[1] = { - {16, 7}, + {16, 7}, }; static arc arcs_21_7[1] = { - {0, 7}, + {0, 7}, }; static state states_21[8] = { - {1, arcs_21_0}, - {1, arcs_21_1}, - {1, arcs_21_2}, - {1, arcs_21_3}, - {2, arcs_21_4}, - {1, arcs_21_5}, - {1, arcs_21_6}, - {1, arcs_21_7}, + {1, arcs_21_0}, + {1, arcs_21_1}, + {1, arcs_21_2}, + {1, arcs_21_3}, + {2, arcs_21_4}, + {1, arcs_21_5}, + {1, arcs_21_6}, + {1, arcs_21_7}, }; static arc arcs_22_0[1] = { - {53, 1}, + {53, 1}, }; static arc arcs_22_1[1] = { - {28, 2}, + {28, 2}, }; static arc arcs_22_2[1] = { - {54, 3}, + {54, 3}, }; static arc arcs_22_3[1] = { - {28, 4}, + {28, 4}, }; static arc arcs_22_4[1] = { - {15, 5}, + {15, 5}, }; static arc arcs_22_5[1] = { - {16, 6}, + {16, 6}, }; static arc arcs_22_6[2] = { - {51, 7}, - {0, 6}, + {51, 7}, + {0, 6}, }; static arc arcs_22_7[1] = { - {15, 8}, + {15, 8}, }; static arc arcs_22_8[1] = { - {16, 9}, + {16, 9}, }; static arc arcs_22_9[1] = { - {0, 9}, + {0, 9}, }; static state states_22[10] = { - {1, arcs_22_0}, - {1, arcs_22_1}, - {1, arcs_22_2}, - {1, arcs_22_3}, - {1, arcs_22_4}, - {1, arcs_22_5}, - {2, arcs_22_6}, - {1, arcs_22_7}, - {1, arcs_22_8}, - {1, arcs_22_9}, + {1, arcs_22_0}, + {1, arcs_22_1}, + {1, arcs_22_2}, + {1, arcs_22_3}, + {1, arcs_22_4}, + {1, arcs_22_5}, + {2, arcs_22_6}, + {1, arcs_22_7}, + {1, arcs_22_8}, + {1, arcs_22_9}, }; static arc arcs_23_0[1] = { - {55, 1}, + {55, 1}, }; static arc arcs_23_1[1] = { - {15, 2}, + {15, 2}, }; static arc arcs_23_2[1] = { - {16, 3}, + {16, 3}, }; static arc arcs_23_3[3] = { - {56, 1}, - {57, 4}, - {0, 3}, + {56, 1}, + {57, 4}, + {0, 3}, }; static arc arcs_23_4[1] = { - {15, 5}, + {15, 5}, }; static arc arcs_23_5[1] = { - {16, 6}, + {16, 6}, }; static arc arcs_23_6[1] = { - {0, 6}, + {0, 6}, }; static state states_23[7] = { - {1, arcs_23_0}, - {1, arcs_23_1}, - {1, arcs_23_2}, - {3, arcs_23_3}, - {1, arcs_23_4}, - {1, arcs_23_5}, - {1, arcs_23_6}, + {1, arcs_23_0}, + {1, arcs_23_1}, + {1, arcs_23_2}, + {3, arcs_23_3}, + {1, arcs_23_4}, + {1, arcs_23_5}, + {1, arcs_23_6}, }; static arc arcs_24_0[1] = { - {58, 1}, + {58, 1}, }; static arc arcs_24_1[2] = { - {40, 2}, - {0, 1}, + {40, 2}, + {0, 1}, }; static arc arcs_24_2[2] = { - {21, 3}, - {0, 2}, + {21, 3}, + {0, 2}, }; static arc arcs_24_3[1] = { - {40, 4}, + {40, 4}, }; static arc arcs_24_4[1] = { - {0, 4}, + {0, 4}, }; static state states_24[5] = { - {1, arcs_24_0}, - {2, arcs_24_1}, - {2, arcs_24_2}, - {1, arcs_24_3}, - {1, arcs_24_4}, + {1, arcs_24_0}, + {2, arcs_24_1}, + {2, arcs_24_2}, + {1, arcs_24_3}, + {1, arcs_24_4}, }; static arc arcs_25_0[2] = { - {3, 1}, - {2, 2}, + {3, 1}, + {2, 2}, }; static arc arcs_25_1[1] = { - {0, 1}, + {0, 1}, }; static arc arcs_25_2[1] = { - {59, 3}, + {59, 3}, }; static arc arcs_25_3[2] = { - {2, 3}, - {6, 4}, + {2, 3}, + {6, 4}, }; static arc arcs_25_4[3] = { - {6, 4}, - {2, 4}, - {60, 1}, + {6, 4}, + {2, 4}, + {60, 1}, }; static state states_25[5] = { - {2, arcs_25_0}, - {1, arcs_25_1}, - {1, arcs_25_2}, - {2, arcs_25_3}, - {3, arcs_25_4}, + {2, arcs_25_0}, + {1, arcs_25_1}, + {1, arcs_25_2}, + {2, arcs_25_3}, + {3, arcs_25_4}, }; static arc arcs_26_0[1] = { - {61, 1}, + {61, 1}, }; static arc arcs_26_1[2] = { - {62, 0}, - {0, 1}, + {62, 0}, + {0, 1}, }; static state states_26[2] = { - {1, arcs_26_0}, - {2, arcs_26_1}, + {1, arcs_26_0}, + {2, arcs_26_1}, }; static arc arcs_27_0[1] = { - {63, 1}, + {63, 1}, }; static arc arcs_27_1[2] = { - {64, 0}, - {0, 1}, + {64, 0}, + {0, 1}, }; static state states_27[2] = { - {1, arcs_27_0}, - {2, arcs_27_1}, + {1, arcs_27_0}, + {2, arcs_27_1}, }; static arc arcs_28_0[2] = { - {65, 1}, - {66, 2}, + {65, 1}, + {66, 2}, }; static arc arcs_28_1[1] = { - {63, 2}, + {63, 2}, }; static arc arcs_28_2[1] = { - {0, 2}, + {0, 2}, }; static state states_28[3] = { - {2, arcs_28_0}, - {1, arcs_28_1}, - {1, arcs_28_2}, + {2, arcs_28_0}, + {1, arcs_28_1}, + {1, arcs_28_2}, }; static arc arcs_29_0[1] = { - {40, 1}, + {40, 1}, }; static arc arcs_29_1[2] = { - {67, 0}, - {0, 1}, + {67, 0}, + {0, 1}, }; static state states_29[2] = { - {1, arcs_29_0}, - {2, arcs_29_1}, + {1, arcs_29_0}, + {2, arcs_29_1}, }; static arc arcs_30_0[6] = { - {68, 1}, - {69, 2}, - {29, 3}, - {54, 3}, - {65, 4}, - {70, 5}, + {68, 1}, + {69, 2}, + {29, 3}, + {54, 3}, + {65, 4}, + {70, 5}, }; static arc arcs_30_1[3] = { - {29, 3}, - {69, 3}, - {0, 1}, + {29, 3}, + {69, 3}, + {0, 1}, }; static arc arcs_30_2[2] = { - {29, 3}, - {0, 2}, + {29, 3}, + {0, 2}, }; static arc arcs_30_3[1] = { - {0, 3}, + {0, 3}, }; static arc arcs_30_4[1] = { - {54, 3}, + {54, 3}, }; static arc arcs_30_5[2] = { - {65, 3}, - {0, 5}, + {65, 3}, + {0, 5}, }; static state states_30[6] = { - {6, arcs_30_0}, - {3, arcs_30_1}, - {2, arcs_30_2}, - {1, arcs_30_3}, - {1, arcs_30_4}, - {2, arcs_30_5}, + {6, arcs_30_0}, + {3, arcs_30_1}, + {2, arcs_30_2}, + {1, arcs_30_3}, + {1, arcs_30_4}, + {2, arcs_30_5}, }; static arc arcs_31_0[1] = { - {71, 1}, + {71, 1}, }; static arc arcs_31_1[3] = { - {72, 0}, - {73, 0}, - {0, 1}, + {72, 0}, + {73, 0}, + {0, 1}, }; static state states_31[2] = { - {1, arcs_31_0}, - {3, arcs_31_1}, + {1, arcs_31_0}, + {3, arcs_31_1}, }; static arc arcs_32_0[1] = { - {74, 1}, + {74, 1}, }; static arc arcs_32_1[4] = { - {43, 0}, - {75, 0}, - {76, 0}, - {0, 1}, + {43, 0}, + {75, 0}, + {76, 0}, + {0, 1}, }; static state states_32[2] = { - {1, arcs_32_0}, - {4, arcs_32_1}, + {1, arcs_32_0}, + {4, arcs_32_1}, }; static arc arcs_33_0[3] = { - {72, 1}, - {73, 1}, - {77, 2}, + {72, 1}, + {73, 1}, + {77, 2}, }; static arc arcs_33_1[1] = { - {74, 3}, + {74, 3}, }; static arc arcs_33_2[2] = { - {78, 2}, - {0, 2}, + {78, 2}, + {0, 2}, }; static arc arcs_33_3[1] = { - {0, 3}, + {0, 3}, }; static state states_33[4] = { - {3, arcs_33_0}, - {1, arcs_33_1}, - {2, arcs_33_2}, - {1, arcs_33_3}, + {3, arcs_33_0}, + {1, arcs_33_1}, + {2, arcs_33_2}, + {1, arcs_33_3}, }; static arc arcs_34_0[7] = { - {17, 1}, - {79, 2}, - {81, 3}, - {83, 4}, - {13, 5}, - {84, 5}, - {85, 5}, + {17, 1}, + {79, 2}, + {81, 3}, + {83, 4}, + {13, 5}, + {84, 5}, + {85, 5}, }; static arc arcs_34_1[2] = { - {9, 6}, - {19, 5}, + {9, 6}, + {19, 5}, }; static arc arcs_34_2[2] = { - {9, 7}, - {80, 5}, + {9, 7}, + {80, 5}, }; static arc arcs_34_3[1] = { - {82, 5}, + {82, 5}, }; static arc arcs_34_4[1] = { - {9, 8}, + {9, 8}, }; static arc arcs_34_5[1] = { - {0, 5}, + {0, 5}, }; static arc arcs_34_6[1] = { - {19, 5}, + {19, 5}, }; static arc arcs_34_7[1] = { - {80, 5}, + {80, 5}, }; static arc arcs_34_8[1] = { - {83, 5}, + {83, 5}, }; static state states_34[9] = { - {7, arcs_34_0}, - {2, arcs_34_1}, - {2, arcs_34_2}, - {1, arcs_34_3}, - {1, arcs_34_4}, - {1, arcs_34_5}, - {1, arcs_34_6}, - {1, arcs_34_7}, - {1, arcs_34_8}, + {7, arcs_34_0}, + {2, arcs_34_1}, + {2, arcs_34_2}, + {1, arcs_34_3}, + {1, arcs_34_4}, + {1, arcs_34_5}, + {1, arcs_34_6}, + {1, arcs_34_7}, + {1, arcs_34_8}, }; static arc arcs_35_0[3] = { - {17, 1}, - {79, 2}, - {87, 3}, + {17, 1}, + {79, 2}, + {87, 3}, }; static arc arcs_35_1[2] = { - {9, 4}, - {19, 5}, + {9, 4}, + {19, 5}, }; static arc arcs_35_2[1] = { - {86, 6}, + {86, 6}, }; static arc arcs_35_3[1] = { - {13, 5}, + {13, 5}, }; static arc arcs_35_4[1] = { - {19, 5}, + {19, 5}, }; static arc arcs_35_5[1] = { - {0, 5}, + {0, 5}, }; static arc arcs_35_6[1] = { - {80, 5}, + {80, 5}, }; static state states_35[7] = { - {3, arcs_35_0}, - {2, arcs_35_1}, - {1, arcs_35_2}, - {1, arcs_35_3}, - {1, arcs_35_4}, - {1, arcs_35_5}, - {1, arcs_35_6}, + {3, arcs_35_0}, + {2, arcs_35_1}, + {1, arcs_35_2}, + {1, arcs_35_3}, + {1, arcs_35_4}, + {1, arcs_35_5}, + {1, arcs_35_6}, }; static arc arcs_36_0[2] = { - {40, 1}, - {15, 2}, + {40, 1}, + {15, 2}, }; static arc arcs_36_1[2] = { - {15, 2}, - {0, 1}, + {15, 2}, + {0, 1}, }; static arc arcs_36_2[2] = { - {40, 3}, - {0, 2}, + {40, 3}, + {0, 2}, }; static arc arcs_36_3[1] = { - {0, 3}, + {0, 3}, }; static state states_36[4] = { - {2, arcs_36_0}, - {2, arcs_36_1}, - {2, arcs_36_2}, - {1, arcs_36_3}, + {2, arcs_36_0}, + {2, arcs_36_1}, + {2, arcs_36_2}, + {1, arcs_36_3}, }; static arc arcs_37_0[1] = { - {40, 1}, + {40, 1}, }; static arc arcs_37_1[2] = { - {21, 2}, - {0, 1}, + {21, 2}, + {0, 1}, }; static arc arcs_37_2[2] = { - {40, 1}, - {0, 2}, + {40, 1}, + {0, 2}, }; static state states_37[3] = { - {1, arcs_37_0}, - {2, arcs_37_1}, - {2, arcs_37_2}, + {1, arcs_37_0}, + {2, arcs_37_1}, + {2, arcs_37_2}, }; static arc arcs_38_0[1] = { - {31, 1}, + {31, 1}, }; static arc arcs_38_1[2] = { - {21, 2}, - {0, 1}, + {21, 2}, + {0, 1}, }; static arc arcs_38_2[2] = { - {31, 1}, - {0, 2}, + {31, 1}, + {0, 2}, }; static state states_38[3] = { - {1, arcs_38_0}, - {2, arcs_38_1}, - {2, arcs_38_2}, + {1, arcs_38_0}, + {2, arcs_38_1}, + {2, arcs_38_2}, }; static arc arcs_39_0[1] = { - {88, 1}, + {88, 1}, }; static arc arcs_39_1[1] = { - {13, 2}, + {13, 2}, }; static arc arcs_39_2[1] = { - {14, 3}, + {14, 3}, }; static arc arcs_39_3[2] = { - {29, 4}, - {15, 5}, + {29, 4}, + {15, 5}, }; static arc arcs_39_4[1] = { - {89, 6}, + {89, 6}, }; static arc arcs_39_5[1] = { - {16, 7}, + {16, 7}, }; static arc arcs_39_6[1] = { - {15, 5}, + {15, 5}, }; static arc arcs_39_7[1] = { - {0, 7}, + {0, 7}, }; static state states_39[8] = { - {1, arcs_39_0}, - {1, arcs_39_1}, - {1, arcs_39_2}, - {2, arcs_39_3}, - {1, arcs_39_4}, - {1, arcs_39_5}, - {1, arcs_39_6}, - {1, arcs_39_7}, + {1, arcs_39_0}, + {1, arcs_39_1}, + {1, arcs_39_2}, + {2, arcs_39_3}, + {1, arcs_39_4}, + {1, arcs_39_5}, + {1, arcs_39_6}, + {1, arcs_39_7}, }; static arc arcs_40_0[1] = { - {77, 1}, + {77, 1}, }; static arc arcs_40_1[1] = { - {90, 2}, + {90, 2}, }; static arc arcs_40_2[2] = { - {21, 0}, - {0, 2}, + {21, 0}, + {0, 2}, }; static state states_40[3] = { - {1, arcs_40_0}, - {1, arcs_40_1}, - {2, arcs_40_2}, + {1, arcs_40_0}, + {1, arcs_40_1}, + {2, arcs_40_2}, }; static arc arcs_41_0[1] = { - {17, 1}, + {17, 1}, }; static arc arcs_41_1[2] = { - {9, 2}, - {19, 3}, + {9, 2}, + {19, 3}, }; static arc arcs_41_2[1] = { - {19, 3}, + {19, 3}, }; static arc arcs_41_3[1] = { - {0, 3}, + {0, 3}, }; static state states_41[4] = { - {1, arcs_41_0}, - {2, arcs_41_1}, - {1, arcs_41_2}, - {1, arcs_41_3}, + {1, arcs_41_0}, + {2, arcs_41_1}, + {1, arcs_41_2}, + {1, arcs_41_3}, }; static dfa dfas[42] = { - {256, "single_input", 0, 3, states_0, - "\004\060\002\100\343\006\262\000\000\203\072\001"}, - {257, "file_input", 0, 2, states_1, - "\204\060\002\100\343\006\262\000\000\203\072\001"}, - {258, "expr_input", 0, 3, states_2, - "\000\040\002\000\000\000\000\000\002\203\072\000"}, - {259, "eval_input", 0, 3, states_3, - "\000\040\002\000\000\000\000\000\002\203\072\000"}, - {260, "funcdef", 0, 6, states_4, - "\000\020\000\000\000\000\000\000\000\000\000\000"}, - {261, "parameters", 0, 4, states_5, - "\000\000\002\000\000\000\000\000\000\000\000\000"}, - {262, "fplist", 0, 2, states_6, - "\000\040\002\000\000\000\000\000\000\000\000\000"}, - {263, "fpdef", 0, 4, states_7, - "\000\040\002\000\000\000\000\000\000\000\000\000"}, - {264, "stmt", 0, 2, states_8, - "\000\060\002\100\343\006\262\000\000\203\072\001"}, - {265, "simple_stmt", 0, 2, states_9, - "\000\040\002\100\343\006\000\000\000\203\072\000"}, - {266, "expr_stmt", 0, 3, states_10, - "\000\040\002\000\000\000\000\000\000\203\072\000"}, - {267, "print_stmt", 0, 4, states_11, - "\000\000\000\100\000\000\000\000\000\000\000\000"}, - {268, "del_stmt", 0, 4, states_12, - "\000\000\000\000\001\000\000\000\000\000\000\000"}, - {269, "pass_stmt", 0, 3, states_13, - "\000\000\000\000\002\000\000\000\000\000\000\000"}, - {270, "flow_stmt", 0, 2, states_14, - "\000\000\000\000\340\000\000\000\000\000\000\000"}, - {271, "break_stmt", 0, 3, states_15, - "\000\000\000\000\040\000\000\000\000\000\000\000"}, - {272, "return_stmt", 0, 4, states_16, - "\000\000\000\000\100\000\000\000\000\000\000\000"}, - {273, "raise_stmt", 0, 6, states_17, - "\000\000\000\000\200\000\000\000\000\000\000\000"}, - {274, "import_stmt", 0, 10, states_18, - "\000\000\000\000\000\006\000\000\000\000\000\000"}, - {275, "compound_stmt", 0, 2, states_19, - "\000\020\000\000\000\000\262\000\000\000\000\001"}, - {276, "if_stmt", 0, 8, states_20, - "\000\000\000\000\000\000\002\000\000\000\000\000"}, - {277, "while_stmt", 0, 8, states_21, - "\000\000\000\000\000\000\020\000\000\000\000\000"}, - {278, "for_stmt", 0, 10, states_22, - "\000\000\000\000\000\000\040\000\000\000\000\000"}, - {279, "try_stmt", 0, 7, states_23, - "\000\000\000\000\000\000\200\000\000\000\000\000"}, - {280, "except_clause", 0, 5, states_24, - "\000\000\000\000\000\000\000\004\000\000\000\000"}, - {281, "suite", 0, 5, states_25, - "\004\040\002\100\343\006\000\000\000\203\072\000"}, - {282, "test", 0, 2, states_26, - "\000\040\002\000\000\000\000\000\002\203\072\000"}, - {283, "and_test", 0, 2, states_27, - "\000\040\002\000\000\000\000\000\002\203\072\000"}, - {284, "not_test", 0, 3, states_28, - "\000\040\002\000\000\000\000\000\002\203\072\000"}, - {285, "comparison", 0, 2, states_29, - "\000\040\002\000\000\000\000\000\000\203\072\000"}, - {286, "comp_op", 0, 6, states_30, - "\000\000\000\040\000\000\100\000\162\000\000\000"}, - {287, "expr", 0, 2, states_31, - "\000\040\002\000\000\000\000\000\000\203\072\000"}, - {288, "term", 0, 2, states_32, - "\000\040\002\000\000\000\000\000\000\203\072\000"}, - {289, "factor", 0, 4, states_33, - "\000\040\002\000\000\000\000\000\000\203\072\000"}, - {290, "atom", 0, 9, states_34, - "\000\040\002\000\000\000\000\000\000\200\072\000"}, - {291, "trailer", 0, 7, states_35, - "\000\000\002\000\000\000\000\000\000\200\200\000"}, - {292, "subscript", 0, 4, states_36, - "\000\240\002\000\000\000\000\000\000\203\072\000"}, - {293, "exprlist", 0, 3, states_37, - "\000\040\002\000\000\000\000\000\000\203\072\000"}, - {294, "testlist", 0, 3, states_38, - "\000\040\002\000\000\000\000\000\002\203\072\000"}, - {295, "classdef", 0, 8, states_39, - "\000\000\000\000\000\000\000\000\000\000\000\001"}, - {296, "baselist", 0, 3, states_40, - "\000\040\002\000\000\000\000\000\000\200\072\000"}, - {297, "arguments", 0, 4, states_41, - "\000\000\002\000\000\000\000\000\000\000\000\000"}, + {256, "single_input", 0, 3, states_0, + "\004\060\002\100\343\006\262\000\000\203\072\001"}, + {257, "file_input", 0, 2, states_1, + "\204\060\002\100\343\006\262\000\000\203\072\001"}, + {258, "expr_input", 0, 3, states_2, + "\000\040\002\000\000\000\000\000\002\203\072\000"}, + {259, "eval_input", 0, 3, states_3, + "\000\040\002\000\000\000\000\000\002\203\072\000"}, + {260, "funcdef", 0, 6, states_4, + "\000\020\000\000\000\000\000\000\000\000\000\000"}, + {261, "parameters", 0, 4, states_5, + "\000\000\002\000\000\000\000\000\000\000\000\000"}, + {262, "fplist", 0, 2, states_6, + "\000\040\002\000\000\000\000\000\000\000\000\000"}, + {263, "fpdef", 0, 4, states_7, + "\000\040\002\000\000\000\000\000\000\000\000\000"}, + {264, "stmt", 0, 2, states_8, + "\000\060\002\100\343\006\262\000\000\203\072\001"}, + {265, "simple_stmt", 0, 2, states_9, + "\000\040\002\100\343\006\000\000\000\203\072\000"}, + {266, "expr_stmt", 0, 3, states_10, + "\000\040\002\000\000\000\000\000\000\203\072\000"}, + {267, "print_stmt", 0, 4, states_11, + "\000\000\000\100\000\000\000\000\000\000\000\000"}, + {268, "del_stmt", 0, 4, states_12, + "\000\000\000\000\001\000\000\000\000\000\000\000"}, + {269, "pass_stmt", 0, 3, states_13, + "\000\000\000\000\002\000\000\000\000\000\000\000"}, + {270, "flow_stmt", 0, 2, states_14, + "\000\000\000\000\340\000\000\000\000\000\000\000"}, + {271, "break_stmt", 0, 3, states_15, + "\000\000\000\000\040\000\000\000\000\000\000\000"}, + {272, "return_stmt", 0, 4, states_16, + "\000\000\000\000\100\000\000\000\000\000\000\000"}, + {273, "raise_stmt", 0, 6, states_17, + "\000\000\000\000\200\000\000\000\000\000\000\000"}, + {274, "import_stmt", 0, 10, states_18, + "\000\000\000\000\000\006\000\000\000\000\000\000"}, + {275, "compound_stmt", 0, 2, states_19, + "\000\020\000\000\000\000\262\000\000\000\000\001"}, + {276, "if_stmt", 0, 8, states_20, + "\000\000\000\000\000\000\002\000\000\000\000\000"}, + {277, "while_stmt", 0, 8, states_21, + "\000\000\000\000\000\000\020\000\000\000\000\000"}, + {278, "for_stmt", 0, 10, states_22, + "\000\000\000\000\000\000\040\000\000\000\000\000"}, + {279, "try_stmt", 0, 7, states_23, + "\000\000\000\000\000\000\200\000\000\000\000\000"}, + {280, "except_clause", 0, 5, states_24, + "\000\000\000\000\000\000\000\004\000\000\000\000"}, + {281, "suite", 0, 5, states_25, + "\004\040\002\100\343\006\000\000\000\203\072\000"}, + {282, "test", 0, 2, states_26, + "\000\040\002\000\000\000\000\000\002\203\072\000"}, + {283, "and_test", 0, 2, states_27, + "\000\040\002\000\000\000\000\000\002\203\072\000"}, + {284, "not_test", 0, 3, states_28, + "\000\040\002\000\000\000\000\000\002\203\072\000"}, + {285, "comparison", 0, 2, states_29, + "\000\040\002\000\000\000\000\000\000\203\072\000"}, + {286, "comp_op", 0, 6, states_30, + "\000\000\000\040\000\000\100\000\162\000\000\000"}, + {287, "expr", 0, 2, states_31, + "\000\040\002\000\000\000\000\000\000\203\072\000"}, + {288, "term", 0, 2, states_32, + "\000\040\002\000\000\000\000\000\000\203\072\000"}, + {289, "factor", 0, 4, states_33, + "\000\040\002\000\000\000\000\000\000\203\072\000"}, + {290, "atom", 0, 9, states_34, + "\000\040\002\000\000\000\000\000\000\200\072\000"}, + {291, "trailer", 0, 7, states_35, + "\000\000\002\000\000\000\000\000\000\200\200\000"}, + {292, "subscript", 0, 4, states_36, + "\000\240\002\000\000\000\000\000\000\203\072\000"}, + {293, "exprlist", 0, 3, states_37, + "\000\040\002\000\000\000\000\000\000\203\072\000"}, + {294, "testlist", 0, 3, states_38, + "\000\040\002\000\000\000\000\000\002\203\072\000"}, + {295, "classdef", 0, 8, states_39, + "\000\000\000\000\000\000\000\000\000\000\000\001"}, + {296, "baselist", 0, 3, states_40, + "\000\040\002\000\000\000\000\000\000\200\072\000"}, + {297, "arguments", 0, 4, states_41, + "\000\000\002\000\000\000\000\000\000\000\000\000"}, }; static label labels[91] = { - {0, "EMPTY"}, - {256, 0}, - {4, 0}, - {265, 0}, - {275, 0}, - {257, 0}, - {264, 0}, - {0, 0}, - {258, 0}, - {294, 0}, - {259, 0}, - {260, 0}, - {1, "def"}, - {1, 0}, - {261, 0}, - {11, 0}, - {281, 0}, - {7, 0}, - {262, 0}, - {8, 0}, - {263, 0}, - {12, 0}, - {266, 0}, - {267, 0}, - {269, 0}, - {268, 0}, - {270, 0}, - {274, 0}, - {293, 0}, - {22, 0}, - {1, "print"}, - {282, 0}, - {1, "del"}, - {1, "pass"}, - {271, 0}, - {272, 0}, - {273, 0}, - {1, "break"}, - {1, "return"}, - {1, "raise"}, - {287, 0}, - {1, "import"}, - {1, "from"}, - {16, 0}, - {276, 0}, - {277, 0}, - {278, 0}, - {279, 0}, - {295, 0}, - {1, "if"}, - {1, "elif"}, - {1, "else"}, - {1, "while"}, - {1, "for"}, - {1, "in"}, - {1, "try"}, - {280, 0}, - {1, "finally"}, - {1, "except"}, - {5, 0}, - {6, 0}, - {283, 0}, - {1, "or"}, - {284, 0}, - {1, "and"}, - {1, "not"}, - {285, 0}, - {286, 0}, - {20, 0}, - {21, 0}, - {1, "is"}, - {288, 0}, - {14, 0}, - {15, 0}, - {289, 0}, - {17, 0}, - {24, 0}, - {290, 0}, - {291, 0}, - {9, 0}, - {10, 0}, - {26, 0}, - {27, 0}, - {25, 0}, - {2, 0}, - {3, 0}, - {292, 0}, - {23, 0}, - {1, "class"}, - {296, 0}, - {297, 0}, + {0, "EMPTY"}, + {256, 0}, + {4, 0}, + {265, 0}, + {275, 0}, + {257, 0}, + {264, 0}, + {0, 0}, + {258, 0}, + {294, 0}, + {259, 0}, + {260, 0}, + {1, "def"}, + {1, 0}, + {261, 0}, + {11, 0}, + {281, 0}, + {7, 0}, + {262, 0}, + {8, 0}, + {263, 0}, + {12, 0}, + {266, 0}, + {267, 0}, + {269, 0}, + {268, 0}, + {270, 0}, + {274, 0}, + {293, 0}, + {22, 0}, + {1, "print"}, + {282, 0}, + {1, "del"}, + {1, "pass"}, + {271, 0}, + {272, 0}, + {273, 0}, + {1, "break"}, + {1, "return"}, + {1, "raise"}, + {287, 0}, + {1, "import"}, + {1, "from"}, + {16, 0}, + {276, 0}, + {277, 0}, + {278, 0}, + {279, 0}, + {295, 0}, + {1, "if"}, + {1, "elif"}, + {1, "else"}, + {1, "while"}, + {1, "for"}, + {1, "in"}, + {1, "try"}, + {280, 0}, + {1, "finally"}, + {1, "except"}, + {5, 0}, + {6, 0}, + {283, 0}, + {1, "or"}, + {284, 0}, + {1, "and"}, + {1, "not"}, + {285, 0}, + {286, 0}, + {20, 0}, + {21, 0}, + {1, "is"}, + {288, 0}, + {14, 0}, + {15, 0}, + {289, 0}, + {17, 0}, + {24, 0}, + {290, 0}, + {291, 0}, + {9, 0}, + {10, 0}, + {26, 0}, + {27, 0}, + {25, 0}, + {2, 0}, + {3, 0}, + {292, 0}, + {23, 0}, + {1, "class"}, + {296, 0}, + {297, 0}, }; grammar gram = { - 42, - dfas, - {91, labels}, - 256 + 42, + dfas, + {91, labels}, + 256 }; diff --git a/src/graminit.h b/src/graminit.h index 051b549..199b8ee 100644 --- a/src/graminit.h +++ b/src/graminit.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. diff --git a/src/grammar.c b/src/grammar.c index 4ba4a1a..57ff347 100644 --- a/src/grammar.c +++ b/src/grammar.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -36,118 +36,118 @@ extern int debugging; grammar * newgrammar(start) - int start; + int start; { - grammar *g; - - g = NEW(grammar, 1); - if (g == NULL) - fatal("no mem for new grammar"); - g->g_ndfas = 0; - g->g_dfa = NULL; - g->g_start = start; - g->g_ll.ll_nlabels = 0; - g->g_ll.ll_label = NULL; - return g; + grammar *g; + + g = NEW(grammar, 1); + if (g == NULL) + fatal("no mem for new grammar"); + g->g_ndfas = 0; + g->g_dfa = NULL; + g->g_start = start; + g->g_ll.ll_nlabels = 0; + g->g_ll.ll_label = NULL; + return g; } dfa * adddfa(g, type, name) - grammar *g; - int type; - char *name; + grammar *g; + int type; + char *name; { - dfa *d; - - RESIZE(g->g_dfa, dfa, g->g_ndfas + 1); - if (g->g_dfa == NULL) - fatal("no mem to resize dfa in adddfa"); - d = &g->g_dfa[g->g_ndfas++]; - d->d_type = type; - d->d_name = name; - d->d_nstates = 0; - d->d_state = NULL; - d->d_initial = -1; - d->d_first = NULL; - return d; /* Only use while fresh! */ + dfa *d; + + RESIZE(g->g_dfa, dfa, g->g_ndfas + 1); + if (g->g_dfa == NULL) + fatal("no mem to resize dfa in adddfa"); + d = &g->g_dfa[g->g_ndfas++]; + d->d_type = type; + d->d_name = name; + d->d_nstates = 0; + d->d_state = NULL; + d->d_initial = -1; + d->d_first = NULL; + return d; /* Only use while fresh! */ } int addstate(d) - dfa *d; + dfa *d; { - state *s; - - RESIZE(d->d_state, state, d->d_nstates + 1); - if (d->d_state == NULL) - fatal("no mem to resize state in addstate"); - s = &d->d_state[d->d_nstates++]; - s->s_narcs = 0; - s->s_arc = NULL; - return s - d->d_state; + state *s; + + RESIZE(d->d_state, state, d->d_nstates + 1); + if (d->d_state == NULL) + fatal("no mem to resize state in addstate"); + s = &d->d_state[d->d_nstates++]; + s->s_narcs = 0; + s->s_arc = NULL; + return s - d->d_state; } void addarc(d, from, to, lbl) - dfa *d; - int lbl; + dfa *d; + int lbl; { - state *s; - arc *a; - - assert(0 <= from && from < d->d_nstates); - assert(0 <= to && to < d->d_nstates); - - s = &d->d_state[from]; - RESIZE(s->s_arc, arc, s->s_narcs + 1); - if (s->s_arc == NULL) - fatal("no mem to resize arc list in addarc"); - a = &s->s_arc[s->s_narcs++]; - a->a_lbl = lbl; - a->a_arrow = to; + state *s; + arc *a; + + assert(0 <= from && from < d->d_nstates); + assert(0 <= to && to < d->d_nstates); + + s = &d->d_state[from]; + RESIZE(s->s_arc, arc, s->s_narcs + 1); + if (s->s_arc == NULL) + fatal("no mem to resize arc list in addarc"); + a = &s->s_arc[s->s_narcs++]; + a->a_lbl = lbl; + a->a_arrow = to; } int addlabel(ll, type, str) - labellist *ll; - int type; - char *str; + labellist *ll; + int type; + char *str; { - int i; - label *lb; - - for (i = 0; i < ll->ll_nlabels; i++) { - if (ll->ll_label[i].lb_type == type && - strcmp(ll->ll_label[i].lb_str, str) == 0) - return i; - } - RESIZE(ll->ll_label, label, ll->ll_nlabels + 1); - if (ll->ll_label == NULL) - fatal("no mem to resize labellist in addlabel"); - lb = &ll->ll_label[ll->ll_nlabels++]; - lb->lb_type = type; - lb->lb_str = str; /* XXX strdup(str) ??? */ - return lb - ll->ll_label; + int i; + label *lb; + + for (i = 0; i < ll->ll_nlabels; i++) { + if (ll->ll_label[i].lb_type == type && + strcmp(ll->ll_label[i].lb_str, str) == 0) + return i; + } + RESIZE(ll->ll_label, label, ll->ll_nlabels + 1); + if (ll->ll_label == NULL) + fatal("no mem to resize labellist in addlabel"); + lb = &ll->ll_label[ll->ll_nlabels++]; + lb->lb_type = type; + lb->lb_str = str; /* XXX strdup(str) ??? */ + return lb - ll->ll_label; } /* Same, but rather dies than adds */ int findlabel(ll, type, str) - labellist *ll; - int type; - char *str; + labellist *ll; + int type; + char *str; { - int i; - label *lb; - - for (i = 0; i < ll->ll_nlabels; i++) { - if (ll->ll_label[i].lb_type == type /*&& - strcmp(ll->ll_label[i].lb_str, str) == 0*/) - return i; - } - fprintf(stderr, "Label %d/'%s' not found\n", type, str); - abort(); + int i; + label *lb; + + for (i = 0; i < ll->ll_nlabels; i++) { + if (ll->ll_label[i].lb_type == type /*&& + strcmp(ll->ll_label[i].lb_str, str) == 0*/) + return i; + } + fprintf(stderr, "Label %d/'%s' not found\n", type, str); + abort(); } /* Forward */ @@ -155,79 +155,79 @@ static void translabel PROTO((grammar *, label *)); void translatelabels(g) - grammar *g; + grammar *g; { - int i; - - printf("Translating labels ...\n"); - /* Don't translate EMPTY */ - for (i = EMPTY+1; i < g->g_ll.ll_nlabels; i++) - translabel(g, &g->g_ll.ll_label[i]); + int i; + + printf("Translating labels ...\n"); + /* Don't translate EMPTY */ + for (i = EMPTY+1; i < g->g_ll.ll_nlabels; i++) + translabel(g, &g->g_ll.ll_label[i]); } static void translabel(g, lb) - grammar *g; - label *lb; + grammar *g; + label *lb; { - int i; - - if (debugging) - printf("Translating label %s ...\n", labelrepr(lb)); - - if (lb->lb_type == NAME) { - for (i = 0; i < g->g_ndfas; i++) { - if (strcmp(lb->lb_str, g->g_dfa[i].d_name) == 0) { - if (debugging) - printf("Label %s is non-terminal %d.\n", - lb->lb_str, - g->g_dfa[i].d_type); - lb->lb_type = g->g_dfa[i].d_type; - lb->lb_str = NULL; - return; - } - } - for (i = 0; i < (int)N_TOKENS; i++) { - if (strcmp(lb->lb_str, tok_name[i]) == 0) { - if (debugging) - printf("Label %s is terminal %d.\n", - lb->lb_str, i); - lb->lb_type = i; - lb->lb_str = NULL; - return; - } - } - printf("Can't translate NAME label '%s'\n", lb->lb_str); - return; - } - - if (lb->lb_type == STRING) { - if (isalpha(lb->lb_str[1])) { - char *p, *strchr(); - if (debugging) - printf("Label %s is a keyword\n", lb->lb_str); - lb->lb_type = NAME; - lb->lb_str++; - p = strchr(lb->lb_str, '\''); - if (p) - *p = '\0'; - } - else { - if (lb->lb_str[2] == lb->lb_str[0]) { - int type = (int) tok_1char(lb->lb_str[1]); - if (type != OP) { - lb->lb_type = type; - lb->lb_str = NULL; - } - else - printf("Unknown OP label %s\n", - lb->lb_str); - } - else - printf("Can't translate STRING label %s\n", - lb->lb_str); - } - } - else - printf("Can't translate label '%s'\n", labelrepr(lb)); + int i; + + if (debugging) + printf("Translating label %s ...\n", labelrepr(lb)); + + if (lb->lb_type == NAME) { + for (i = 0; i < g->g_ndfas; i++) { + if (strcmp(lb->lb_str, g->g_dfa[i].d_name) == 0) { + if (debugging) + printf("Label %s is non-terminal %d.\n", + lb->lb_str, + g->g_dfa[i].d_type); + lb->lb_type = g->g_dfa[i].d_type; + lb->lb_str = NULL; + return; + } + } + for (i = 0; i < (int)N_TOKENS; i++) { + if (strcmp(lb->lb_str, tok_name[i]) == 0) { + if (debugging) + printf("Label %s is terminal %d.\n", + lb->lb_str, i); + lb->lb_type = i; + lb->lb_str = NULL; + return; + } + } + printf("Can't translate NAME label '%s'\n", lb->lb_str); + return; + } + + if (lb->lb_type == STRING) { + if (isalpha(lb->lb_str[1])) { + char *p, *strchr(); + if (debugging) + printf("Label %s is a keyword\n", lb->lb_str); + lb->lb_type = NAME; + lb->lb_str++; + p = strchr(lb->lb_str, '\''); + if (p) + *p = '\0'; + } + else { + if (lb->lb_str[2] == lb->lb_str[0]) { + int type = (int) tok_1char(lb->lb_str[1]); + if (type != OP) { + lb->lb_type = type; + lb->lb_str = NULL; + } + else + printf("Unknown OP label %s\n", + lb->lb_str); + } + else + printf("Can't translate STRING label %s\n", + lb->lb_str); + } + } + else + printf("Can't translate label '%s'\n", labelrepr(lb)); } diff --git a/src/grammar.h b/src/grammar.h index 82f34c3..759365e 100644 --- a/src/grammar.h +++ b/src/grammar.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -29,58 +29,58 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* A label of an arc */ typedef struct _label { - int lb_type; - char *lb_str; + int lb_type; + char *lb_str; } label; -#define EMPTY 0 /* Label number 0 is by definition the empty label */ +#define EMPTY 0 /* Label number 0 is by definition the empty label */ /* A list of labels */ typedef struct _labellist { - int ll_nlabels; - label *ll_label; + int ll_nlabels; + label *ll_label; } labellist; /* An arc from one state to another */ typedef struct _arc { - short a_lbl; /* Label of this arc */ - short a_arrow; /* State where this arc goes to */ + short a_lbl; /* Label of this arc */ + short a_arrow; /* State where this arc goes to */ } arc; /* A state in a DFA */ typedef struct _state { - int s_narcs; - arc *s_arc; /* Array of arcs */ - - /* Optional accelerators */ - int s_lower; /* Lowest label index */ - int s_upper; /* Highest label index */ - int *s_accel; /* Accelerator */ - int s_accept; /* Nonzero for accepting state */ + int s_narcs; + arc *s_arc; /* Array of arcs */ + + /* Optional accelerators */ + int s_lower; /* Lowest label index */ + int s_upper; /* Highest label index */ + int *s_accel; /* Accelerator */ + int s_accept; /* Nonzero for accepting state */ } state; /* A DFA */ typedef struct _dfa { - int d_type; /* Non-terminal this represents */ - char *d_name; /* For printing */ - int d_initial; /* Initial state */ - int d_nstates; - state *d_state; /* Array of states */ - bitset d_first; + int d_type; /* Non-terminal this represents */ + char *d_name; /* For printing */ + int d_initial; /* Initial state */ + int d_nstates; + state *d_state; /* Array of states */ + bitset d_first; } dfa; /* A grammar */ typedef struct _grammar { - int g_ndfas; - dfa *g_dfa; /* Array of DFAs */ - labellist g_ll; - int g_start; /* Start symbol of the grammar */ - int g_accel; /* Set if accelerators present */ + int g_ndfas; + dfa *g_dfa; /* Array of DFAs */ + labellist g_ll; + int g_start; /* Start symbol of the grammar */ + int g_accel; /* Set if accelerators present */ } grammar; /* FUNCTIONS */ diff --git a/src/grammar1.c b/src/grammar1.c index eafe4fe..565b2df 100644 --- a/src/grammar1.c +++ b/src/grammar1.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -33,43 +33,43 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. dfa * finddfa(g, type) - grammar *g; - register int type; + grammar *g; + register int type; { - register int i; - register dfa *d; - - for (i = g->g_ndfas, d = g->g_dfa; --i >= 0; d++) { - if (d->d_type == type) - return d; - } - assert(0); - /* NOTREACHED */ + register int i; + register dfa *d; + + for (i = g->g_ndfas, d = g->g_dfa; --i >= 0; d++) { + if (d->d_type == type) + return d; + } + assert(0); + /* NOTREACHED */ } char * labelrepr(lb) - label *lb; + label *lb; { - static char buf[100]; - - if (lb->lb_type == ENDMARKER) - return "EMPTY"; - else if (ISNONTERMINAL(lb->lb_type)) { - if (lb->lb_str == NULL) { - sprintf(buf, "NT%d", lb->lb_type); - return buf; - } - else - return lb->lb_str; - } - else { - if (lb->lb_str == NULL) - return tok_name[lb->lb_type]; - else { - sprintf(buf, "%.32s(%.32s)", - tok_name[lb->lb_type], lb->lb_str); - return buf; - } - } + static char buf[100]; + + if (lb->lb_type == ENDMARKER) + return "EMPTY"; + else if (ISNONTERMINAL(lb->lb_type)) { + if (lb->lb_str == NULL) { + sprintf(buf, "NT%d", lb->lb_type); + return buf; + } + else + return lb->lb_str; + } + else { + if (lb->lb_str == NULL) + return tok_name[lb->lb_type]; + else { + sprintf(buf, "%.32s(%.32s)", + tok_name[lb->lb_type], lb->lb_str); + return buf; + } + } } diff --git a/src/import.c b/src/import.c index 59ea07e..2744df0 100644 --- a/src/import.c +++ b/src/import.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -51,211 +51,209 @@ static object *modules; void initimport() { - if ((modules = newdictobject()) == NULL) - fatal("no mem for dictionary of modules"); + if ((modules = newdictobject()) == NULL) + fatal("no mem for dictionary of modules"); } object * get_modules() { - return modules; + return modules; } object * add_module(name) - char *name; + char *name; { - object *m; - if ((m = dictlookup(modules, name)) != NULL && is_moduleobject(m)) - return m; - m = newmoduleobject(name); - if (m == NULL) - return NULL; - if (dictinsert(modules, name, m) != 0) { - DECREF(m); - return NULL; - } - DECREF(m); /* Yes, it still exists, in modules! */ - return m; + object *m; + if ((m = dictlookup(modules, name)) != NULL && is_moduleobject(m)) + return m; + m = newmoduleobject(name); + if (m == NULL) + return NULL; + if (dictinsert(modules, name, m) != 0) { + DECREF(m); + return NULL; + } + DECREF(m); /* Yes, it still exists, in modules! */ + return m; } static FILE * open_module(name, suffix, namebuf) - char *name; - char *suffix; - char *namebuf; /* XXX No buffer overflow checks! */ + char *name; + char *suffix; + char *namebuf; /* XXX No buffer overflow checks! */ { - object *path; - FILE *fp; - - path = sysget("path"); - if (path == NULL || !is_listobject(path)) { - strcpy(namebuf, name); - strcat(namebuf, suffix); - fp = fopen(namebuf, "r"); - } - else { - int npath = getlistsize(path); - int i; - fp = NULL; - for (i = 0; i < npath; i++) { - object *v = getlistitem(path, i); - int len; - if (!is_stringobject(v)) - continue; - strcpy(namebuf, getstringvalue(v)); - len = getstringsize(v); - if (len > 0 && namebuf[len-1] != SEP) - namebuf[len++] = SEP; - strcpy(namebuf+len, name); - strcat(namebuf, suffix); - fp = fopen(namebuf, "r"); - if (fp != NULL) - break; - } - } - return fp; + object *path; + FILE *fp; + + path = sysget("path"); + if (path == NULL || !is_listobject(path)) { + strcpy(namebuf, name); + strcat(namebuf, suffix); + fp = fopen(namebuf, "r"); + } + else { + int npath = getlistsize(path); + int i; + fp = NULL; + for (i = 0; i < npath; i++) { + object *v = getlistitem(path, i); + int len; + if (!is_stringobject(v)) + continue; + strcpy(namebuf, getstringvalue(v)); + len = getstringsize(v); + if (len > 0 && namebuf[len-1] != SEP) + namebuf[len++] = SEP; + strcpy(namebuf+len, name); + strcat(namebuf, suffix); + fp = fopen(namebuf, "r"); + if (fp != NULL) + break; + } + } + return fp; } static object * get_module(m, name, m_ret) - /*module*/object *m; - char *name; - object **m_ret; + /*module*/object *m; + char *name; + object **m_ret; { - object *d; - FILE *fp; - node *n; - int err; - char namebuf[256]; - - fp = open_module(name, ".py", namebuf); - if (fp == NULL) { - if (m == NULL) - err_setstr(NameError, name); - else - err_setstr(RuntimeError, "no module source file"); - return NULL; - } - err = parse_file(fp, namebuf, file_input, &n); - fclose(fp); - if (err != E_DONE) { - err_input(err); - return NULL; - } - if (m == NULL) { - m = add_module(name); - if (m == NULL) { - freetree(n); - return NULL; - } - *m_ret = m; - } - d = getmoduledict(m); - return run_node(n, namebuf, d, d); + object *d; + FILE *fp; + node *n; + int err; + char namebuf[256]; + + fp = open_module(name, ".py", namebuf); + if (fp == NULL) { + if (m == NULL) + err_setstr(NameError, name); + else + err_setstr(RuntimeError, "no module source file"); + return NULL; + } + err = parse_file(fp, namebuf, file_input, &n); + fclose(fp); + if (err != E_DONE) { + err_input(err); + return NULL; + } + if (m == NULL) { + m = add_module(name); + if (m == NULL) { + freetree(n); + return NULL; + } + *m_ret = m; + } + d = getmoduledict(m); + return run_node(n, namebuf, d, d); } static object * load_module(name) - char *name; + char *name; { - object *m, *v; - v = get_module((object *)NULL, name, &m); - if (v == NULL) - return NULL; - DECREF(v); - return m; + object *m, *v; + v = get_module((object *)NULL, name, &m); + if (v == NULL) + return NULL; + DECREF(v); + return m; } -static int init_builtin(char *name); - object * import_module(name) - char *name; + char *name; { - object *m; - if ((m = dictlookup(modules, name)) == NULL) { - if (init_builtin(name)) { - if ((m = dictlookup(modules, name)) == NULL) - err_setstr(SystemError, "builtin module missing"); - } - else { - m = load_module(name); - } - } - return m; + object *m; + if ((m = dictlookup(modules, name)) == NULL) { + if (init_builtin(name)) { + if ((m = dictlookup(modules, name)) == NULL) + err_setstr(SystemError, "builtin module missing"); + } + else { + m = load_module(name); + } + } + return m; } object * reload_module(m) - object *m; + object *m; { - if (m == NULL || !is_moduleobject(m)) { - err_setstr(TypeError, "reload() argument must be module"); - return NULL; - } - /* XXX Ought to check for builtin modules -- can't reload these... */ - return get_module(m, getmodulename(m), (object **)NULL); + if (m == NULL || !is_moduleobject(m)) { + err_setstr(TypeError, "reload() argument must be module"); + return NULL; + } + /* XXX Ought to check for builtin modules -- can't reload these... */ + return get_module(m, getmodulename(m), (object **)NULL); } static void cleardict(d) - object *d; + object *d; { - int i; - for (i = getdictsize(d); --i >= 0; ) { - char *k; - k = getdictkey(d, i); - if (k != NULL) - (void) dictremove(d, k); - } + int i; + for (i = getdictsize(d); --i >= 0; ) { + char *k; + k = getdictkey(d, i); + if (k != NULL) + (void) dictremove(d, k); + } } void doneimport() { - if (modules != NULL) { - int i; - /* Explicitly erase all modules; this is the safest way - to get rid of at least *some* circular dependencies */ - for (i = getdictsize(modules); --i >= 0; ) { - char *k; - k = getdictkey(modules, i); - if (k != NULL) { - object *m; - m = dictlookup(modules, k); - if (m != NULL && is_moduleobject(m)) { - object *d; - d = getmoduledict(m); - if (d != NULL && is_dictobject(d)) { - cleardict(d); - } - } - } - } - cleardict(modules); - } - DECREF(modules); + if (modules != NULL) { + int i; + /* Explicitly erase all modules; this is the safest way + to get rid of at least *some* circular dependencies */ + for (i = getdictsize(modules); --i >= 0; ) { + char *k; + k = getdictkey(modules, i); + if (k != NULL) { + object *m; + m = dictlookup(modules, k); + if (m != NULL && is_moduleobject(m)) { + object *d; + d = getmoduledict(m); + if (d != NULL && is_dictobject(d)) { + cleardict(d); + } + } + } + } + cleardict(modules); + } + DECREF(modules); } /* Initialize built-in modules when first imported */ extern struct { - char *name; - void (*initfunc)(); + char *name; + void (*initfunc)(); } inittab[]; static int init_builtin(name) - char *name; + char *name; { - int i; - for (i = 0; inittab[i].name != NULL; i++) { - if (strcmp(name, inittab[i].name) == 0) { - (*inittab[i].initfunc)(); - return 1; - } - } - return 0; + int i; + for (i = 0; inittab[i].name != NULL; i++) { + if (strcmp(name, inittab[i].name) == 0) { + (*inittab[i].initfunc)(); + return 1; + } + } + return 0; } diff --git a/src/import.h b/src/import.h index 0923395..eafb2b2 100644 --- a/src/import.h +++ b/src/import.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. diff --git a/src/intobject.c b/src/intobject.c index dba9cc6..6c700e8 100644 --- a/src/intobject.c +++ b/src/intobject.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -29,279 +29,279 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* Standard Booleans */ intobject FalseObject = { - OB_HEAD_INIT(&Inttype) - 0 + OB_HEAD_INIT(&Inttype) + 0 }; intobject TrueObject = { - OB_HEAD_INIT(&Inttype) - 1 + OB_HEAD_INIT(&Inttype) + 1 }; static object * err_ovf() { - err_setstr(OverflowError, "integer overflow"); - return NULL; + err_setstr(OverflowError, "integer overflow"); + return NULL; } static object * err_zdiv() { - err_setstr(ZeroDivisionError, "integer division by zero"); - return NULL; + err_setstr(ZeroDivisionError, "integer division by zero"); + return NULL; } /* Integers are quite normal objects, to make object handling uniform. - (Using odd pointers to represent integers would save much space - but require extra checks for this special case throughout the code.) - Since, a typical Python program spends much of its time allocating - and deallocating integers, these operations should be very fast. - Therefore we use a dedicated allocation scheme with a much lower - overhead (in space and time) than straight malloc(): a simple - dedicated free list, filled when necessary with memory from malloc(). + (Using odd pointers to represent integers would save much space + but require extra checks for this special case throughout the code.) + Since, a typical Python program spends much of its time allocating + and deallocating integers, these operations should be very fast. + Therefore we use a dedicated allocation scheme with a much lower + overhead (in space and time) than straight malloc(): a simple + dedicated free list, filled when necessary with memory from malloc(). */ -#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */ -#define N_INTOBJECTS (BLOCK_SIZE / sizeof(intobject)) +#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */ +#define N_INTOBJECTS (BLOCK_SIZE / sizeof(intobject)) static intobject * fill_free_list() { - intobject *p, *q; - p = NEW(intobject, N_INTOBJECTS); - if (p == NULL) - return (intobject *)err_nomem(); - q = p + N_INTOBJECTS; - while (--q > p) - *(intobject **)q = q-1; - *(intobject **)q = NULL; - return p + N_INTOBJECTS - 1; + intobject *p, *q; + p = NEW(intobject, N_INTOBJECTS); + if (p == NULL) + return (intobject *)err_nomem(); + q = p + N_INTOBJECTS; + while (--q > p) + *(intobject **)q = q-1; + *(intobject **)q = NULL; + return p + N_INTOBJECTS - 1; } static intobject *free_list = NULL; object * newintobject(ival) - long ival; + long ival; { - register intobject *v; - if (free_list == NULL) { - if ((free_list = fill_free_list()) == NULL) - return NULL; - } - v = free_list; - free_list = *(intobject **)free_list; - NEWREF(v); - v->ob_type = &Inttype; - v->ob_ival = ival; - return (object *) v; + register intobject *v; + if (free_list == NULL) { + if ((free_list = fill_free_list()) == NULL) + return NULL; + } + v = free_list; + free_list = *(intobject **)free_list; + NEWREF(v); + v->ob_type = &Inttype; + v->ob_ival = ival; + return (object *) v; } static void int_dealloc(v) - intobject *v; + intobject *v; { - *(intobject **)v = free_list; - free_list = v; + *(intobject **)v = free_list; + free_list = v; } long getintvalue(op) - register object *op; + register object *op; { - if (!is_intobject(op)) { - err_badcall(); - return -1; - } - else - return ((intobject *)op) -> ob_ival; + if (!is_intobject(op)) { + err_badcall(); + return -1; + } + else + return ((intobject *)op) -> ob_ival; } /* Methods */ static void int_print(v, fp, flags) - intobject *v; - FILE *fp; - int flags; + intobject *v; + FILE *fp; + int flags; { - fprintf(fp, "%ld", v->ob_ival); + fprintf(fp, "%ld", v->ob_ival); } static object * int_repr(v) - intobject *v; + intobject *v; { - char buf[20]; - sprintf(buf, "%ld", v->ob_ival); - return newstringobject(buf); + char buf[20]; + sprintf(buf, "%ld", v->ob_ival); + return newstringobject(buf); } static int int_compare(v, w) - intobject *v, *w; + intobject *v, *w; { - register long i = v->ob_ival; - register long j = w->ob_ival; - return (i < j) ? -1 : (i > j) ? 1 : 0; + register long i = v->ob_ival; + register long j = w->ob_ival; + return (i < j) ? -1 : (i > j) ? 1 : 0; } static object * int_add(v, w) - intobject *v; - register object *w; + intobject *v; + register object *w; { - register long a, b, x; - if (!is_intobject(w)) { - err_badarg(); - return NULL; - } - a = v->ob_ival; - b = ((intobject *)w) -> ob_ival; - x = a + b; - if ((x^a) < 0 && (x^b) < 0) - return err_ovf(); - return newintobject(x); + register long a, b, x; + if (!is_intobject(w)) { + err_badarg(); + return NULL; + } + a = v->ob_ival; + b = ((intobject *)w) -> ob_ival; + x = a + b; + if ((x^a) < 0 && (x^b) < 0) + return err_ovf(); + return newintobject(x); } static object * int_sub(v, w) - intobject *v; - register object *w; + intobject *v; + register object *w; { - register long a, b, x; - if (!is_intobject(w)) { - err_badarg(); - return NULL; - } - a = v->ob_ival; - b = ((intobject *)w) -> ob_ival; - x = a - b; - if ((x^a) < 0 && (x^~b) < 0) - return err_ovf(); - return newintobject(x); + register long a, b, x; + if (!is_intobject(w)) { + err_badarg(); + return NULL; + } + a = v->ob_ival; + b = ((intobject *)w) -> ob_ival; + x = a - b; + if ((x^a) < 0 && (x^~b) < 0) + return err_ovf(); + return newintobject(x); } static object * int_mul(v, w) - intobject *v; - register object *w; + intobject *v; + register object *w; { - register long a, b; - double x; - if (!is_intobject(w)) { - err_badarg(); - return NULL; - } - a = v->ob_ival; - b = ((intobject *)w) -> ob_ival; - x = (double)a * (double)b; - if (x > 0x7fffffff || x < (double) (long) 0x80000000) - return err_ovf(); - return newintobject(a * b); + register long a, b; + double x; + if (!is_intobject(w)) { + err_badarg(); + return NULL; + } + a = v->ob_ival; + b = ((intobject *)w) -> ob_ival; + x = (double)a * (double)b; + if (x > 0x7fffffff || x < (double) (long) 0x80000000) + return err_ovf(); + return newintobject(a * b); } static object * int_div(v, w) - intobject *v; - register object *w; + intobject *v; + register object *w; { - if (!is_intobject(w)) { - err_badarg(); - return NULL; - } - if (((intobject *)w) -> ob_ival == 0) - return err_zdiv(); - return newintobject(v->ob_ival / ((intobject *)w) -> ob_ival); + if (!is_intobject(w)) { + err_badarg(); + return NULL; + } + if (((intobject *)w) -> ob_ival == 0) + return err_zdiv(); + return newintobject(v->ob_ival / ((intobject *)w) -> ob_ival); } static object * int_rem(v, w) - intobject *v; - register object *w; + intobject *v; + register object *w; { - if (!is_intobject(w)) { - err_badarg(); - return NULL; - } - if (((intobject *)w) -> ob_ival == 0) - return err_zdiv(); - return newintobject(v->ob_ival % ((intobject *)w) -> ob_ival); + if (!is_intobject(w)) { + err_badarg(); + return NULL; + } + if (((intobject *)w) -> ob_ival == 0) + return err_zdiv(); + return newintobject(v->ob_ival % ((intobject *)w) -> ob_ival); } static object * int_pow(v, w) - intobject *v; - register object *w; + intobject *v; + register object *w; { - register long iv, iw, ix; - register int neg; - if (!is_intobject(w)) { - err_badarg(); - return NULL; - } - iv = v->ob_ival; - iw = ((intobject *)w)->ob_ival; - neg = 0; - if (iw < 0) - neg = 1, iw = -iw; - ix = 1; - for (; iw > 0; iw--) - ix = ix * iv; - if (neg) { - if (ix == 0) - return err_zdiv(); - ix = 1/ix; - } - /* XXX How to check for overflow? */ - return newintobject(ix); + register long iv, iw, ix; + register int neg; + if (!is_intobject(w)) { + err_badarg(); + return NULL; + } + iv = v->ob_ival; + iw = ((intobject *)w)->ob_ival; + neg = 0; + if (iw < 0) + neg = 1, iw = -iw; + ix = 1; + for (; iw > 0; iw--) + ix = ix * iv; + if (neg) { + if (ix == 0) + return err_zdiv(); + ix = 1/ix; + } + /* XXX How to check for overflow? */ + return newintobject(ix); } static object * int_neg(v) - intobject *v; + intobject *v; { - register long a, x; - a = v->ob_ival; - x = -a; - if (a < 0 && x < 0) - return err_ovf(); - return newintobject(x); + register long a, x; + a = v->ob_ival; + x = -a; + if (a < 0 && x < 0) + return err_ovf(); + return newintobject(x); } static object * int_pos(v) - intobject *v; + intobject *v; { - INCREF(v); - return (object *)v; + INCREF(v); + return (object *)v; } static number_methods int_as_number = { - int_add, /*tp_add*/ - int_sub, /*tp_subtract*/ - int_mul, /*tp_multiply*/ - int_div, /*tp_divide*/ - int_rem, /*tp_remainder*/ - int_pow, /*tp_power*/ - int_neg, /*tp_negate*/ - int_pos, /*tp_plus*/ + int_add, /*tp_add*/ + int_sub, /*tp_subtract*/ + int_mul, /*tp_multiply*/ + int_div, /*tp_divide*/ + int_rem, /*tp_remainder*/ + int_pow, /*tp_power*/ + int_neg, /*tp_negate*/ + int_pos, /*tp_plus*/ }; typeobject Inttype = { - OB_HEAD_INIT(&Typetype) - 0, - "int", - sizeof(intobject), - 0, - int_dealloc, /*tp_dealloc*/ - int_print, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - int_compare, /*tp_compare*/ - int_repr, /*tp_repr*/ - &int_as_number, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ + OB_HEAD_INIT(&Typetype) + 0, + "int", + sizeof(intobject), + 0, + int_dealloc, /*tp_dealloc*/ + int_print, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + int_compare, /*tp_compare*/ + int_repr, /*tp_repr*/ + &int_as_number, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ }; diff --git a/src/intobject.h b/src/intobject.h index 8a5330d..f9938f3 100644 --- a/src/intobject.h +++ b/src/intobject.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -27,11 +27,11 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* 123456789-123456789-123456789-123456789-123456789-123456789-123456789-12 -intobject represents a (long) integer. This is an immutable object; +intobject represents a (long) integer. This is an immutable object; an integer cannot change its value after creation. There are functions to create new integer objects, to test an object -for integer-ness, and to get the integer value. The latter functions +for integer-ness, and to get the integer value. The latter functions returns -1 and sets errno to EBADF if the object is not an intobject. None of the functions should be applied to nil objects. @@ -40,8 +40,8 @@ TrueObject and FalseObject below; don't use this. */ typedef struct { - OB_HEAD - long ob_ival; + OB_HEAD + long ob_ival; } intobject; extern typeobject Inttype; diff --git a/src/intrcheck.c b/src/intrcheck.c index 8e2fb5b..8dbeb5f 100644 --- a/src/intrcheck.c +++ b/src/intrcheck.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -36,12 +36,12 @@ initintr() int intrcheck() { - int interrupted = 0; - while (kbhit()) { - if (getch() == '\003') - interrupted = 1; - } - return interrupted; + int interrupted = 0; + while (kbhit()) { + if (getch() == '\003') + interrupted = 1; + } + return interrupted; } #define OK @@ -52,7 +52,7 @@ intrcheck() #ifdef THINK_C /* This is for THINK C 4.0. - For 3.0, you may have to remove the signal stuff. */ + For 3.0, you may have to remove the signal stuff. */ #include <MacHeaders> #include <signal.h> @@ -62,44 +62,44 @@ static int interrupted; static SIGTYPE intcatcher(sig) - int sig; + int sig; { - interrupted = 1; - signal(SIGINT, intcatcher); + interrupted = 1; + signal(SIGINT, intcatcher); } void initintr() { - if (signal(SIGINT, SIG_IGN) != SIG_IGN) - signal(SIGINT, intcatcher); + if (signal(SIGINT, SIG_IGN) != SIG_IGN) + signal(SIGINT, intcatcher); } int intrcheck() { - register EvQElPtr q; - - /* This is like THINK C 4.0's <console.h>. - I'm not sure why FlushEvents must be called from asm{}. */ - for (q = (EvQElPtr)EventQueue.qHead; q; q = (EvQElPtr)q->qLink) { - if (q->evtQWhat == keyDown && - (char)q->evtQMessage == '.' && - (q->evtQModifiers & cmdKey) != 0) { - - asm { - moveq #keyDownMask,d0 - _FlushEvents - } - interrupted = 1; - break; - } - } - if (interrupted) { - interrupted = 0; - return 1; - } - return 0; + register EvQElPtr q; + + /* This is like THINK C 4.0's <console.h>. + I'm not sure why FlushEvents must be called from asm{}. */ + for (q = (EvQElPtr)EventQueue.qHead; q; q = (EvQElPtr)q->qLink) { + if (q->evtQWhat == keyDown && + (char)q->evtQMessage == '.' && + (q->evtQModifiers & cmdKey) != 0) { + + asm { + moveq #keyDownMask,d0 + _FlushEvents + } + interrupted = 1; + break; + } + } + if (interrupted) { + interrupted = 0; + return 1; + } + return 0; } #define OK @@ -119,26 +119,26 @@ static int interrupted; static SIGTYPE intcatcher(sig) - int sig; + int sig; { - interrupted = 1; - signal(SIGINT, intcatcher); + interrupted = 1; + signal(SIGINT, intcatcher); } void initintr() { - if (signal(SIGINT, SIG_IGN) != SIG_IGN) - signal(SIGINT, intcatcher); + if (signal(SIGINT, SIG_IGN) != SIG_IGN) + signal(SIGINT, intcatcher); } int intrcheck() { - if (!interrupted) - return 0; - interrupted = 0; - return 1; + if (!interrupted) + return 0; + interrupted = 0; + return 1; } #endif /* !OK */ diff --git a/src/listnode.c b/src/listnode.c index 333d01f..774abcd 100644 --- a/src/listnode.c +++ b/src/listnode.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -33,61 +33,61 @@ static void list1node PROTO((FILE *, node *)); void listtree(n) - node *n; + node *n; { - listnode(stdout, n); + listnode(stdout, n); } static int level, atbol; void listnode(fp, n) - FILE *fp; - node *n; + FILE *fp; + node *n; { - level = 0; - atbol = 1; - list1node(fp, n); + level = 0; + atbol = 1; + list1node(fp, n); } static void list1node(fp, n) - FILE *fp; - node *n; + FILE *fp; + node *n; { - if (n == 0) - return; - if (ISNONTERMINAL(TYPE(n))) { - int i; - for (i = 0; i < NCH(n); i++) - list1node(fp, CHILD(n, i)); - } - else if (ISTERMINAL(TYPE(n))) { - switch (TYPE(n)) { - case INDENT: - ++level; - break; - case DEDENT: - --level; - break; - default: - if (atbol) { - int i; - for (i = 0; i < level; ++i) - fprintf(fp, "\t"); - atbol = 0; - } - if (TYPE(n) == NEWLINE) { - if (STR(n) != NULL) - fprintf(fp, "%s", STR(n)); - fprintf(fp, "\n"); - atbol = 1; - } - else - fprintf(fp, "%s ", STR(n)); - break; - } - } - else - fprintf(fp, "? "); + if (n == 0) + return; + if (ISNONTERMINAL(TYPE(n))) { + int i; + for (i = 0; i < NCH(n); i++) + list1node(fp, CHILD(n, i)); + } + else if (ISTERMINAL(TYPE(n))) { + switch (TYPE(n)) { + case INDENT: + ++level; + break; + case DEDENT: + --level; + break; + default: + if (atbol) { + int i; + for (i = 0; i < level; ++i) + fprintf(fp, "\t"); + atbol = 0; + } + if (TYPE(n) == NEWLINE) { + if (STR(n) != NULL) + fprintf(fp, "%s", STR(n)); + fprintf(fp, "\n"); + atbol = 1; + } + else + fprintf(fp, "%s ", STR(n)); + break; + } + } + else + fprintf(fp, "? "); } diff --git a/src/listobject.c b/src/listobject.c index 9a32eac..02192a1 100644 --- a/src/listobject.c +++ b/src/listobject.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -25,496 +25,495 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* List object implementation */ #include "allobjects.h" -#include "modsupport.h" object * newlistobject(size) - int size; + int size; { - int i; - listobject *op; - if (size < 0) { - err_badcall(); - return NULL; - } - op = (listobject *) malloc(sizeof(listobject)); - if (op == NULL) { - return err_nomem(); - } - if (size <= 0) { - op->ob_item = NULL; - } - else { - op->ob_item = (object **) malloc(size * sizeof(object *)); - if (op->ob_item == NULL) { - free((ANY *)op); - return err_nomem(); - } - } - NEWREF(op); - op->ob_type = &Listtype; - op->ob_size = size; - for (i = 0; i < size; i++) - op->ob_item[i] = NULL; - return (object *) op; + int i; + listobject *op; + if (size < 0) { + err_badcall(); + return NULL; + } + op = (listobject *) malloc(sizeof(listobject)); + if (op == NULL) { + return err_nomem(); + } + if (size <= 0) { + op->ob_item = NULL; + } + else { + op->ob_item = (object **) malloc(size * sizeof(object *)); + if (op->ob_item == NULL) { + free((ANY *)op); + return err_nomem(); + } + } + NEWREF(op); + op->ob_type = &Listtype; + op->ob_size = size; + for (i = 0; i < size; i++) + op->ob_item[i] = NULL; + return (object *) op; } int getlistsize(op) - object *op; + object *op; { - if (!is_listobject(op)) { - err_badcall(); - return -1; - } - else - return ((listobject *)op) -> ob_size; + if (!is_listobject(op)) { + err_badcall(); + return -1; + } + else + return ((listobject *)op) -> ob_size; } object * getlistitem(op, i) - object *op; - int i; + object *op; + int i; { - if (!is_listobject(op)) { - err_badcall(); - return NULL; - } - if (i < 0 || i >= ((listobject *)op) -> ob_size) { - err_setstr(IndexError, "list index out of range"); - return NULL; - } - return ((listobject *)op) -> ob_item[i]; + if (!is_listobject(op)) { + err_badcall(); + return NULL; + } + if (i < 0 || i >= ((listobject *)op) -> ob_size) { + err_setstr(IndexError, "list index out of range"); + return NULL; + } + return ((listobject *)op) -> ob_item[i]; } int setlistitem(op, i, newitem) - register object *op; - register int i; - register object *newitem; + register object *op; + register int i; + register object *newitem; { - register object *olditem; - if (!is_listobject(op)) { - if (newitem != NULL) - DECREF(newitem); - err_badcall(); - return -1; - } - if (i < 0 || i >= ((listobject *)op) -> ob_size) { - if (newitem != NULL) - DECREF(newitem); - err_setstr(IndexError, "list assignment index out of range"); - return -1; - } - olditem = ((listobject *)op) -> ob_item[i]; - ((listobject *)op) -> ob_item[i] = newitem; - if (olditem != NULL) - DECREF(olditem); - return 0; + register object *olditem; + if (!is_listobject(op)) { + if (newitem != NULL) + DECREF(newitem); + err_badcall(); + return -1; + } + if (i < 0 || i >= ((listobject *)op) -> ob_size) { + if (newitem != NULL) + DECREF(newitem); + err_setstr(IndexError, "list assignment index out of range"); + return -1; + } + olditem = ((listobject *)op) -> ob_item[i]; + ((listobject *)op) -> ob_item[i] = newitem; + if (olditem != NULL) + DECREF(olditem); + return 0; } static int ins1(self, where, v) - listobject *self; - int where; - object *v; + listobject *self; + int where; + object *v; { - int i; - object **items; - if (v == NULL) { - err_badcall(); - return -1; - } - items = self->ob_item; - RESIZE(items, object *, self->ob_size+1); - if (items == NULL) { - err_nomem(); - return -1; - } - if (where < 0) - where = 0; - if (where > self->ob_size) - where = self->ob_size; - for (i = self->ob_size; --i >= where; ) - items[i+1] = items[i]; - INCREF(v); - items[where] = v; - self->ob_item = items; - self->ob_size++; - return 0; + int i; + object **items; + if (v == NULL) { + err_badcall(); + return -1; + } + items = self->ob_item; + RESIZE(items, object *, self->ob_size+1); + if (items == NULL) { + err_nomem(); + return -1; + } + if (where < 0) + where = 0; + if (where > self->ob_size) + where = self->ob_size; + for (i = self->ob_size; --i >= where; ) + items[i+1] = items[i]; + INCREF(v); + items[where] = v; + self->ob_item = items; + self->ob_size++; + return 0; } int inslistitem(op, where, newitem) - object *op; - int where; - object *newitem; + object *op; + int where; + object *newitem; { - if (!is_listobject(op)) { - err_badcall(); - return -1; - } - return ins1((listobject *)op, where, newitem); + if (!is_listobject(op)) { + err_badcall(); + return -1; + } + return ins1((listobject *)op, where, newitem); } int addlistitem(op, newitem) - object *op; - object *newitem; + object *op; + object *newitem; { - if (!is_listobject(op)) { - err_badcall(); - return -1; - } - return ins1((listobject *)op, - (int) ((listobject *)op)->ob_size, newitem); + if (!is_listobject(op)) { + err_badcall(); + return -1; + } + return ins1((listobject *)op, + (int) ((listobject *)op)->ob_size, newitem); } /* Methods */ static void list_dealloc(op) - listobject *op; + listobject *op; { - int i; - for (i = 0; i < op->ob_size; i++) { - if (op->ob_item[i] != NULL) - DECREF(op->ob_item[i]); - } - if (op->ob_item != NULL) - free((ANY *)op->ob_item); - free((ANY *)op); + int i; + for (i = 0; i < op->ob_size; i++) { + if (op->ob_item[i] != NULL) + DECREF(op->ob_item[i]); + } + if (op->ob_item != NULL) + free((ANY *)op->ob_item); + free((ANY *)op); } static void list_print(op, fp, flags) - listobject *op; - FILE *fp; - int flags; + listobject *op; + FILE *fp; + int flags; { - int i; - fprintf(fp, "["); - for (i = 0; i < op->ob_size && !StopPrint; i++) { - if (i > 0) { - fprintf(fp, ", "); - } - printobject(op->ob_item[i], fp, flags); - } - fprintf(fp, "]"); + int i; + fprintf(fp, "["); + for (i = 0; i < op->ob_size && !StopPrint; i++) { + if (i > 0) { + fprintf(fp, ", "); + } + printobject(op->ob_item[i], fp, flags); + } + fprintf(fp, "]"); } object * list_repr(v) - listobject *v; + listobject *v; { - object *s, *t, *comma; - int i; - s = newstringobject("["); - comma = newstringobject(", "); - for (i = 0; i < v->ob_size && s != NULL; i++) { - if (i > 0) - joinstring(&s, comma); - t = reprobject(v->ob_item[i]); - joinstring(&s, t); - DECREF(t); - } - DECREF(comma); - t = newstringobject("]"); - joinstring(&s, t); - DECREF(t); - return s; + object *s, *t, *comma; + int i; + s = newstringobject("["); + comma = newstringobject(", "); + for (i = 0; i < v->ob_size && s != NULL; i++) { + if (i > 0) + joinstring(&s, comma); + t = reprobject(v->ob_item[i]); + joinstring(&s, t); + DECREF(t); + } + DECREF(comma); + t = newstringobject("]"); + joinstring(&s, t); + DECREF(t); + return s; } static int list_compare(v, w) - listobject *v, *w; + listobject *v, *w; { - int len = (v->ob_size < w->ob_size) ? v->ob_size : w->ob_size; - int i; - for (i = 0; i < len; i++) { - int cmp = cmpobject(v->ob_item[i], w->ob_item[i]); - if (cmp != 0) - return cmp; - } - return v->ob_size - w->ob_size; + int len = (v->ob_size < w->ob_size) ? v->ob_size : w->ob_size; + int i; + for (i = 0; i < len; i++) { + int cmp = cmpobject(v->ob_item[i], w->ob_item[i]); + if (cmp != 0) + return cmp; + } + return v->ob_size - w->ob_size; } static int list_length(a) - listobject *a; + listobject *a; { - return a->ob_size; + return a->ob_size; } static object * list_item(a, i) - listobject *a; - int i; + listobject *a; + int i; { - if (i < 0 || i >= a->ob_size) { - err_setstr(IndexError, "list index out of range"); - return NULL; - } - INCREF(a->ob_item[i]); - return a->ob_item[i]; + if (i < 0 || i >= a->ob_size) { + err_setstr(IndexError, "list index out of range"); + return NULL; + } + INCREF(a->ob_item[i]); + return a->ob_item[i]; } static object * list_slice(a, ilow, ihigh) - listobject *a; - int ilow, ihigh; + listobject *a; + int ilow, ihigh; { - listobject *np; - int i; - if (ilow < 0) - ilow = 0; - else if (ilow > a->ob_size) - ilow = a->ob_size; - if (ihigh < 0) - ihigh = 0; - if (ihigh < ilow) - ihigh = ilow; - else if (ihigh > a->ob_size) - ihigh = a->ob_size; - np = (listobject *) newlistobject(ihigh - ilow); - if (np == NULL) - return NULL; - for (i = ilow; i < ihigh; i++) { - object *v = a->ob_item[i]; - INCREF(v); - np->ob_item[i - ilow] = v; - } - return (object *)np; + listobject *np; + int i; + if (ilow < 0) + ilow = 0; + else if (ilow > a->ob_size) + ilow = a->ob_size; + if (ihigh < 0) + ihigh = 0; + if (ihigh < ilow) + ihigh = ilow; + else if (ihigh > a->ob_size) + ihigh = a->ob_size; + np = (listobject *) newlistobject(ihigh - ilow); + if (np == NULL) + return NULL; + for (i = ilow; i < ihigh; i++) { + object *v = a->ob_item[i]; + INCREF(v); + np->ob_item[i - ilow] = v; + } + return (object *)np; } static object * list_concat(a, bb) - listobject *a; - object *bb; + listobject *a; + object *bb; { - int size; - int i; - listobject *np; - if (!is_listobject(bb)) { - err_badarg(); - return NULL; - } + int size; + int i; + listobject *np; + if (!is_listobject(bb)) { + err_badarg(); + return NULL; + } #define b ((listobject *)bb) - size = a->ob_size + b->ob_size; - np = (listobject *) newlistobject(size); - if (np == NULL) { - return err_nomem(); - } - for (i = 0; i < a->ob_size; i++) { - object *v = a->ob_item[i]; - INCREF(v); - np->ob_item[i] = v; - } - for (i = 0; i < b->ob_size; i++) { - object *v = b->ob_item[i]; - INCREF(v); - np->ob_item[i + a->ob_size] = v; - } - return (object *)np; + size = a->ob_size + b->ob_size; + np = (listobject *) newlistobject(size); + if (np == NULL) { + return err_nomem(); + } + for (i = 0; i < a->ob_size; i++) { + object *v = a->ob_item[i]; + INCREF(v); + np->ob_item[i] = v; + } + for (i = 0; i < b->ob_size; i++) { + object *v = b->ob_item[i]; + INCREF(v); + np->ob_item[i + a->ob_size] = v; + } + return (object *)np; #undef b } static int -list_ass_slice(a, ilow, ihigh, v) - listobject *a; - int ilow, ihigh; - object *v; +list_ass_item(a, i, v) + listobject *a; + int i; + object *v; { - object **item; - int n; /* Size of replacement list */ - int d; /* Change in size */ - int k; /* Loop index */ -#define b ((listobject *)v) - if (v == NULL) - n = 0; - else if (is_listobject(v)) - n = b->ob_size; - else { - err_badarg(); - return -1; - } - if (ilow < 0) - ilow = 0; - else if (ilow > a->ob_size) - ilow = a->ob_size; - if (ihigh < 0) - ihigh = 0; - if (ihigh < ilow) - ihigh = ilow; - else if (ihigh > a->ob_size) - ihigh = a->ob_size; - item = a->ob_item; - d = n - (ihigh-ilow); - if (d <= 0) { /* Delete -d items; DECREF ihigh-ilow items */ - for (k = ilow; k < ihigh; k++) - DECREF(item[k]); - if (d < 0) { - for (/*k = ihigh*/; k < a->ob_size; k++) - item[k+d] = item[k]; - a->ob_size += d; - RESIZE(item, object *, a->ob_size); /* Can't fail */ - a->ob_item = item; - } - } - else { /* Insert d items; DECREF ihigh-ilow items */ - RESIZE(item, object *, a->ob_size + d); - if (item == NULL) { - err_nomem(); - return -1; - } - for (k = a->ob_size; --k >= ihigh; ) - item[k+d] = item[k]; - for (/*k = ihigh-1*/; k >= ilow; --k) - DECREF(item[k]); - a->ob_item = item; - a->ob_size += d; - } - for (k = 0; k < n; k++, ilow++) { - object *w = b->ob_item[k]; - INCREF(w); - item[ilow] = w; - } - return 0; -#undef b + if (i < 0 || i >= a->ob_size) { + err_setstr(IndexError, "list assignment index out of range"); + return -1; + } + if (v == NULL) + return list_ass_slice(a, i, i+1, v); + INCREF(v); + DECREF(a->ob_item[i]); + a->ob_item[i] = v; + return 0; } static int -list_ass_item(a, i, v) - listobject *a; - int i; - object *v; +list_ass_slice(a, ilow, ihigh, v) + listobject *a; + int ilow, ihigh; + object *v; { - if (i < 0 || i >= a->ob_size) { - err_setstr(IndexError, "list assignment index out of range"); - return -1; - } - if (v == NULL) - return list_ass_slice(a, i, i+1, v); - INCREF(v); - DECREF(a->ob_item[i]); - a->ob_item[i] = v; - return 0; + object **item; + int n; /* Size of replacement list */ + int d; /* Change in size */ + int k; /* Loop index */ +#define b ((listobject *)v) + if (v == NULL) + n = 0; + else if (is_listobject(v)) + n = b->ob_size; + else { + err_badarg(); + return -1; + } + if (ilow < 0) + ilow = 0; + else if (ilow > a->ob_size) + ilow = a->ob_size; + if (ihigh < 0) + ihigh = 0; + if (ihigh < ilow) + ihigh = ilow; + else if (ihigh > a->ob_size) + ihigh = a->ob_size; + item = a->ob_item; + d = n - (ihigh-ilow); + if (d <= 0) { /* Delete -d items; DECREF ihigh-ilow items */ + for (k = ilow; k < ihigh; k++) + DECREF(item[k]); + if (d < 0) { + for (/*k = ihigh*/; k < a->ob_size; k++) + item[k+d] = item[k]; + a->ob_size += d; + RESIZE(item, object *, a->ob_size); /* Can't fail */ + a->ob_item = item; + } + } + else { /* Insert d items; DECREF ihigh-ilow items */ + RESIZE(item, object *, a->ob_size + d); + if (item == NULL) { + err_nomem(); + return -1; + } + for (k = a->ob_size; --k >= ihigh; ) + item[k+d] = item[k]; + for (/*k = ihigh-1*/; k >= ilow; --k) + DECREF(item[k]); + a->ob_item = item; + a->ob_size += d; + } + for (k = 0; k < n; k++, ilow++) { + object *w = b->ob_item[k]; + INCREF(w); + item[ilow] = w; + } + return 0; +#undef b } static object * ins(self, where, v) - listobject *self; - int where; - object *v; + listobject *self; + int where; + object *v; { - if (ins1(self, where, v) != 0) - return NULL; - INCREF(None); - return None; + if (ins1(self, where, v) != 0) + return NULL; + INCREF(None); + return None; } static object * listinsert(self, args) - listobject *self; - object *args; + listobject *self; + object *args; { - int i; - if (args == NULL || !is_tupleobject(args) || gettuplesize(args) != 2) { - err_badarg(); - return NULL; - } - if (!getintarg(gettupleitem(args, 0), &i)) - return NULL; - return ins(self, i, gettupleitem(args, 1)); + int i; + if (args == NULL || !is_tupleobject(args) || gettuplesize(args) != 2) { + err_badarg(); + return NULL; + } + if (!getintarg(gettupleitem(args, 0), &i)) + return NULL; + return ins(self, i, gettupleitem(args, 1)); } static object * listappend(self, args) - listobject *self; - object *args; + listobject *self; + object *args; { - return ins(self, (int) self->ob_size, args); + return ins(self, (int) self->ob_size, args); } static int cmp(v, w) - char *v, *w; + char *v, *w; { - return cmpobject(* (object **) v, * (object **) w); + return cmpobject(* (object **) v, * (object **) w); } static object * listsort(self, args) - listobject *self; - object *args; + listobject *self; + object *args; { - if (args != NULL) { - err_badarg(); - return NULL; - } - err_clear(); - if (self->ob_size > 1) - qsort((char *)self->ob_item, - (int) self->ob_size, sizeof(object *), cmp); - if (err_occurred()) - return NULL; - INCREF(None); - return None; + if (args != NULL) { + err_badarg(); + return NULL; + } + err_clear(); + if (self->ob_size > 1) + qsort((char *)self->ob_item, + (int) self->ob_size, sizeof(object *), cmp); + if (err_occurred()) + return NULL; + INCREF(None); + return None; } int sortlist(v) - object *v; + object *v; { - if (v == NULL || !is_listobject(v)) { - err_badcall(); - return -1; - } - v = listsort((listobject *)v, (object *)NULL); - if (v == NULL) - return -1; - DECREF(v); - return 0; + if (v == NULL || !is_listobject(v)) { + err_badcall(); + return -1; + } + v = listsort((listobject *)v, (object *)NULL); + if (v == NULL) + return -1; + DECREF(v); + return 0; } static struct methodlist list_methods[] = { - {"append", listappend}, - {"insert", listinsert}, - {"sort", listsort}, - {NULL, NULL} /* sentinel */ + {"append", listappend}, + {"insert", listinsert}, + {"sort", listsort}, + {NULL, NULL} /* sentinel */ }; static object * list_getattr(f, name) - listobject *f; - char *name; + listobject *f; + char *name; { - return findmethod(list_methods, (object *)f, name); + return findmethod(list_methods, (object *)f, name); } static sequence_methods list_as_sequence = { - list_length, /*sq_length*/ - list_concat, /*sq_concat*/ - 0, /*sq_repeat*/ - list_item, /*sq_item*/ - list_slice, /*sq_slice*/ - list_ass_item, /*sq_ass_item*/ - list_ass_slice, /*sq_ass_slice*/ + list_length, /*sq_length*/ + list_concat, /*sq_concat*/ + 0, /*sq_repeat*/ + list_item, /*sq_item*/ + list_slice, /*sq_slice*/ + list_ass_item, /*sq_ass_item*/ + list_ass_slice, /*sq_ass_slice*/ }; typeobject Listtype = { - OB_HEAD_INIT(&Typetype) - 0, - "list", - sizeof(listobject), - 0, - list_dealloc, /*tp_dealloc*/ - list_print, /*tp_print*/ - list_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - list_compare, /*tp_compare*/ - list_repr, /*tp_repr*/ - 0, /*tp_as_number*/ - &list_as_sequence, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ + OB_HEAD_INIT(&Typetype) + 0, + "list", + sizeof(listobject), + 0, + list_dealloc, /*tp_dealloc*/ + list_print, /*tp_print*/ + list_getattr, /*tp_getattr*/ + 0, /*tp_setattr*/ + list_compare, /*tp_compare*/ + list_repr, /*tp_repr*/ + 0, /*tp_as_number*/ + &list_as_sequence, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ }; diff --git a/src/listobject.h b/src/listobject.h index 103ceb6..cc1921d 100644 --- a/src/listobject.h +++ b/src/listobject.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -29,18 +29,18 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. Another generally useful object type is an list of object pointers. This is a mutable type: the list items can be changed, and items can be -added or removed. Out-of-range indices or non-list objects are ignored. +added or removed. Out-of-range indices or non-list objects are ignored. *** WARNING *** setlistitem does not increment the new item's reference count, but does decrement the reference count of the item it replaces, -if not nil. It does *decrement* the reference count if it is *not* -inserted in the list. Similarly, getlistitem does not increment the +if not nil. It does *decrement* the reference count if it is *not* +inserted in the list. Similarly, getlistitem does not increment the returned item's reference count. */ typedef struct { - OB_VARHEAD - object **ob_item; + OB_VARHEAD + object **ob_item; } listobject; extern typeobject Listtype; diff --git a/src/macmodule.c b/src/macmodule.c index 4f20914..85e4d7e 100644 --- a/src/macmodule.c +++ b/src/macmodule.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -39,208 +39,208 @@ static object *MacError; /* Exception */ static object * mac_chdir(self, args) - object *self; - object *args; + object *self; + object *args; { - object *path; - if (!getstrarg(args, &path)) - return NULL; - if (chdir(getstringvalue(path)) != 0) - return err_errno(MacError); - INCREF(None); - return None; + object *path; + if (!getstrarg(args, &path)) + return NULL; + if (chdir(getstringvalue(path)) != 0) + return err_errno(MacError); + INCREF(None); + return None; } static object * mac_getcwd(self, args) - object *self; - object *args; + object *self; + object *args; { - extern char *getwd(); - char buf[1025]; - if (!getnoarg(args)) - return NULL; - strcpy(buf, "mac.getcwd() failed"); /* In case getwd() doesn't set a msg */ - if (getwd(buf) == NULL) { - err_setstr(MacError, buf); - return NULL; - } - return newstringobject(buf); + extern char *getwd(); + char buf[1025]; + if (!getnoarg(args)) + return NULL; + strcpy(buf, "mac.getcwd() failed"); /* In case getwd() doesn't set a msg */ + if (getwd(buf) == NULL) { + err_setstr(MacError, buf); + return NULL; + } + return newstringobject(buf); } static object * mac_listdir(self, args) - object *self; - object *args; + object *self; + object *args; { - object *name, *d, *v; - DIR *dirp; - struct direct *ep; - if (!getstrarg(args, &name)) - return NULL; - if ((dirp = opendir(getstringvalue(name))) == NULL) - return err_errno(MacError); - if ((d = newlistobject(0)) == NULL) { - closedir(dirp); - return NULL; - } - while ((ep = readdir(dirp)) != NULL) { - v = newstringobject(ep->d_name); - if (v == NULL) { - DECREF(d); - d = NULL; - break; - } - if (addlistitem(d, v) != 0) { - DECREF(v); - DECREF(d); - d = NULL; - break; - } - DECREF(v); - } - closedir(dirp); - return d; + object *name, *d, *v; + DIR *dirp; + struct direct *ep; + if (!getstrarg(args, &name)) + return NULL; + if ((dirp = opendir(getstringvalue(name))) == NULL) + return err_errno(MacError); + if ((d = newlistobject(0)) == NULL) { + closedir(dirp); + return NULL; + } + while ((ep = readdir(dirp)) != NULL) { + v = newstringobject(ep->d_name); + if (v == NULL) { + DECREF(d); + d = NULL; + break; + } + if (addlistitem(d, v) != 0) { + DECREF(v); + DECREF(d); + d = NULL; + break; + } + DECREF(v); + } + closedir(dirp); + return d; } static object * mac_mkdir(self, args) - object *self; - object *args; + object *self; + object *args; { - object *path; - int mode; - if (!getstrintarg(args, &path, &mode)) - return NULL; - if (mkdir(getstringvalue(path), mode) != 0) - return err_errno(MacError); - INCREF(None); - return None; + object *path; + int mode; + if (!getstrintarg(args, &path, &mode)) + return NULL; + if (mkdir(getstringvalue(path), mode) != 0) + return err_errno(MacError); + INCREF(None); + return None; } static object * mac_rename(self, args) - object *self; - object *args; + object *self; + object *args; { - object *src, *dst; - if (!getstrstrarg(args, &src, &dst)) - return NULL; - if (rename(getstringvalue(src), getstringvalue(dst)) != 0) - return err_errno(MacError); - INCREF(None); - return None; + object *src, *dst; + if (!getstrstrarg(args, &src, &dst)) + return NULL; + if (rename(getstringvalue(src), getstringvalue(dst)) != 0) + return err_errno(MacError); + INCREF(None); + return None; } static object * mac_rmdir(self, args) - object *self; - object *args; + object *self; + object *args; { - object *path; - if (!getstrarg(args, &path)) - return NULL; - if (rmdir(getstringvalue(path)) != 0) - return err_errno(MacError); - INCREF(None); - return None; + object *path; + if (!getstrarg(args, &path)) + return NULL; + if (rmdir(getstringvalue(path)) != 0) + return err_errno(MacError); + INCREF(None); + return None; } static object * mac_stat(self, args) - object *self; - object *args; + object *self; + object *args; { - struct stat st; - object *path; - object *v; - if (!getstrarg(args, &path)) - return NULL; - if (stat(getstringvalue(path), &st) != 0) - return err_errno(MacError); - v = newtupleobject(11); - if (v == NULL) - return NULL; + struct stat st; + object *path; + object *v; + if (!getstrarg(args, &path)) + return NULL; + if (stat(getstringvalue(path), &st) != 0) + return err_errno(MacError); + v = newtupleobject(11); + if (v == NULL) + return NULL; #define SET(i, val) settupleitem(v, i, newintobject((long)(val))) #define XXX(i, val) SET(i, 0) /* For values my Mac stat doesn't support */ - SET(0, st.st_mode); - XXX(1, st.st_ino); - XXX(2, st.st_dev); - XXX(3, st.st_nlink); - XXX(4, st.st_uid); - XXX(5, st.st_gid); - SET(6, st.st_size); - XXX(7, st.st_atime); - SET(8, st.st_mtime); - XXX(9, st.st_ctime); - SET(10, st.st_rsize); /* Mac-specific: resource size */ + SET(0, st.st_mode); + XXX(1, st.st_ino); + XXX(2, st.st_dev); + XXX(3, st.st_nlink); + XXX(4, st.st_uid); + XXX(5, st.st_gid); + SET(6, st.st_size); + XXX(7, st.st_atime); + SET(8, st.st_mtime); + XXX(9, st.st_ctime); + SET(10, st.st_rsize); /* Mac-specific: resource size */ #undef SET - if (err_occurred()) { - DECREF(v); - return NULL; - } - return v; + if (err_occurred()) { + DECREF(v); + return NULL; + } + return v; } static object * mac_sync(self, args) - object *self; - object *args; + object *self; + object *args; { - if (!getnoarg(args)) - return NULL; - sync(); - INCREF(None); - return None; + if (!getnoarg(args)) + return NULL; + sync(); + INCREF(None); + return None; } static object * mac_unlink(self, args) - object *self; - object *args; + object *self; + object *args; { - object *path; - if (!getstrarg(args, &path)) - return NULL; - if (unlink(getstringvalue(path)) != 0) - return err_errno(MacError); - INCREF(None); - return None; + object *path; + if (!getstrarg(args, &path)) + return NULL; + if (unlink(getstringvalue(path)) != 0) + return err_errno(MacError); + INCREF(None); + return None; } static struct methodlist mac_methods[] = { - {"chdir", mac_chdir}, - {"getcwd", mac_getcwd}, - {"listdir", mac_listdir}, - {"mkdir", mac_mkdir}, - {"rename", mac_rename}, - {"rmdir", mac_rmdir}, - {"stat", mac_stat}, - {"sync", mac_sync}, - {"unlink", mac_unlink}, - {NULL, NULL} /* Sentinel */ + {"chdir", mac_chdir}, + {"getcwd", mac_getcwd}, + {"listdir", mac_listdir}, + {"mkdir", mac_mkdir}, + {"rename", mac_rename}, + {"rmdir", mac_rmdir}, + {"stat", mac_stat}, + {"sync", mac_sync}, + {"unlink", mac_unlink}, + {NULL, NULL} /* Sentinel */ }; void initmac() { - object *m, *d; - - m = initmodule("mac", mac_methods); - d = getmoduledict(m); - - /* Initialize mac.error exception */ - MacError = newstringobject("mac.error"); - if (MacError == NULL || dictinsert(d, "error", MacError) != 0) - fatal("can't define mac.error"); + object *m, *d; + + m = initmodule("mac", mac_methods); + d = getmoduledict(m); + + /* Initialize mac.error exception */ + MacError = newstringobject("mac.error"); + if (MacError == NULL || dictinsert(d, "error", MacError) != 0) + fatal("can't define mac.error"); } diff --git a/src/malloc.h b/src/malloc.h index de2cc9f..4ed5f08 100644 --- a/src/malloc.h +++ b/src/malloc.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -36,11 +36,6 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #define HAVE_STDLIB #endif -#ifdef __STDC__ -#define ANY void -#define HAVE_STDLIB -#endif - #ifndef ANY #define ANY char #endif @@ -51,10 +46,10 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #define NEW(type, n) ( (type *) malloc((n) * sizeof(type)) ) #define RESIZE(p, type, n) \ - if ((p) == NULL) \ - (p) = (type *) malloc((n) * sizeof(type)); \ - else \ - (p) = (type *) realloc((char *)(p), (n) * sizeof(type)) + if ((p) == NULL) \ + (p) = (type *) malloc((n) * sizeof(type)); \ + else \ + (p) = (type *) realloc((char *)(p), (n) * sizeof(type)) #define DEL(p) free((char *)p) #define XDEL(p) if ((p) == NULL) ; else DEL(p) diff --git a/src/mathmodule.c b/src/mathmodule.c index 3fa8d03..7b2bdf2 100644 --- a/src/mathmodule.c +++ b/src/mathmodule.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -37,74 +37,74 @@ extern int errno; static int getdoublearg(args, px) - register object *args; - double *px; + register object *args; + double *px; { - if (args == NULL) - return err_badarg(); - if (is_floatobject(args)) { - *px = getfloatvalue(args); - return 1; - } - if (is_intobject(args)) { - *px = getintvalue(args); - return 1; - } - return err_badarg(); + if (args == NULL) + return err_badarg(); + if (is_floatobject(args)) { + *px = getfloatvalue(args); + return 1; + } + if (is_intobject(args)) { + *px = getintvalue(args); + return 1; + } + return err_badarg(); } static int get2doublearg(args, px, py) - register object *args; - double *px, *py; + register object *args; + double *px, *py; { - if (args == NULL || !is_tupleobject(args) || gettuplesize(args) != 2) - return err_badarg(); - return getdoublearg(gettupleitem(args, 0), px) && - getdoublearg(gettupleitem(args, 1), py); + if (args == NULL || !is_tupleobject(args) || gettuplesize(args) != 2) + return err_badarg(); + return getdoublearg(gettupleitem(args, 0), px) && + getdoublearg(gettupleitem(args, 1), py); } static object * math_1(args, func) - object *args; - double (*func) FPROTO((double)); + object *args; + double (*func) FPROTO((double)); { - double x; - if (!getdoublearg(args, &x)) - return NULL; - errno = 0; - x = (*func)(x); - if (errno != 0) - return NULL; - else - return newfloatobject(x); + double x; + if (!getdoublearg(args, &x)) + return NULL; + errno = 0; + x = (*func)(x); + if (errno != 0) + return NULL; + else + return newfloatobject(x); } static object * math_2(args, func) - object *args; - double (*func) FPROTO((double, double)); + object *args; + double (*func) FPROTO((double, double)); { - double x, y; - if (!get2doublearg(args, &x, &y)) - return NULL; - errno = 0; - x = (*func)(x, y); - if (errno != 0) - return NULL; - else - return newfloatobject(x); + double x, y; + if (!get2doublearg(args, &x, &y)) + return NULL; + errno = 0; + x = (*func)(x, y); + if (errno != 0) + return NULL; + else + return newfloatobject(x); } #define FUNC1(stubname, func) \ - static object * stubname(self, args) object *self, *args; { \ - return math_1(args, func); \ - } + static object * stubname(self, args) object *self, *args; { \ + return math_1(args, func); \ + } #define FUNC2(stubname, func) \ - static object * stubname(self, args) object *self, *args; { \ - return math_2(args, func); \ - } + static object * stubname(self, args) object *self, *args; { \ + return math_2(args, func); \ + } FUNC1(math_acos, acos) FUNC1(math_asin, asin) @@ -131,50 +131,50 @@ FUNC1(math_tanh, tanh) #if 0 /* What about these? */ -double frexp(double x, int *i); -double ldexp(double x, int n); -double modf(double x, double *i); +double frexp(double x, int *i); +double ldexp(double x, int n); +double modf(double x, double *i); #endif static struct methodlist math_methods[] = { - {"acos", math_acos}, - {"asin", math_asin}, - {"atan", math_atan}, - {"atan2", math_atan2}, - {"ceil", math_ceil}, - {"cos", math_cos}, - {"cosh", math_cosh}, - {"exp", math_exp}, - {"fabs", math_fabs}, - {"floor", math_floor}, + {"acos", math_acos}, + {"asin", math_asin}, + {"atan", math_atan}, + {"atan2", math_atan2}, + {"ceil", math_ceil}, + {"cos", math_cos}, + {"cosh", math_cosh}, + {"exp", math_exp}, + {"fabs", math_fabs}, + {"floor", math_floor}, #if 0 - {"fmod", math_fmod}, - {"frexp", math_freqp}, - {"ldexp", math_ldexp}, + {"fmod", math_fmod}, + {"frexp", math_freqp}, + {"ldexp", math_ldexp}, #endif - {"log", math_log}, - {"log10", math_log10}, + {"log", math_log}, + {"log10", math_log10}, #if 0 - {"modf", math_modf}, + {"modf", math_modf}, #endif - {"pow", math_pow}, - {"sin", math_sin}, - {"sinh", math_sinh}, - {"sqrt", math_sqrt}, - {"tan", math_tan}, - {"tanh", math_tanh}, - {NULL, NULL} /* sentinel */ + {"pow", math_pow}, + {"sin", math_sin}, + {"sinh", math_sinh}, + {"sqrt", math_sqrt}, + {"tan", math_tan}, + {"tanh", math_tanh}, + {NULL, NULL} /* sentinel */ }; void initmath() { - object *m, *d, *v; - - m = initmodule("math", math_methods); - d = getmoduledict(m); - dictinsert(d, "pi", v = newfloatobject(atan(1.0) * 4.0)); - DECREF(v); - dictinsert(d, "e", v = newfloatobject(exp(1.0))); - DECREF(v); + object *m, *d, *v; + + m = initmodule("math", math_methods); + d = getmoduledict(m); + dictinsert(d, "pi", v = newfloatobject(atan(1.0) * 4.0)); + DECREF(v); + dictinsert(d, "e", v = newfloatobject(exp(1.0))); + DECREF(v); } diff --git a/src/metagrammar.c b/src/metagrammar.c index 57d47cb..12c5d5b 100644 --- a/src/metagrammar.c +++ b/src/metagrammar.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -27,150 +27,150 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include "grammar.h" #include "pgen.h" static arc arcs_0_0[3] = { - {2, 0}, - {3, 0}, - {4, 1}, + {2, 0}, + {3, 0}, + {4, 1}, }; static arc arcs_0_1[1] = { - {0, 1}, + {0, 1}, }; static state states_0[2] = { - {3, arcs_0_0}, - {1, arcs_0_1}, + {3, arcs_0_0}, + {1, arcs_0_1}, }; static arc arcs_1_0[1] = { - {5, 1}, + {5, 1}, }; static arc arcs_1_1[1] = { - {6, 2}, + {6, 2}, }; static arc arcs_1_2[1] = { - {7, 3}, + {7, 3}, }; static arc arcs_1_3[1] = { - {3, 4}, + {3, 4}, }; static arc arcs_1_4[1] = { - {0, 4}, + {0, 4}, }; static state states_1[5] = { - {1, arcs_1_0}, - {1, arcs_1_1}, - {1, arcs_1_2}, - {1, arcs_1_3}, - {1, arcs_1_4}, + {1, arcs_1_0}, + {1, arcs_1_1}, + {1, arcs_1_2}, + {1, arcs_1_3}, + {1, arcs_1_4}, }; static arc arcs_2_0[1] = { - {8, 1}, + {8, 1}, }; static arc arcs_2_1[2] = { - {9, 0}, - {0, 1}, + {9, 0}, + {0, 1}, }; static state states_2[2] = { - {1, arcs_2_0}, - {2, arcs_2_1}, + {1, arcs_2_0}, + {2, arcs_2_1}, }; static arc arcs_3_0[1] = { - {10, 1}, + {10, 1}, }; static arc arcs_3_1[2] = { - {10, 1}, - {0, 1}, + {10, 1}, + {0, 1}, }; static state states_3[2] = { - {1, arcs_3_0}, - {2, arcs_3_1}, + {1, arcs_3_0}, + {2, arcs_3_1}, }; static arc arcs_4_0[2] = { - {11, 1}, - {13, 2}, + {11, 1}, + {13, 2}, }; static arc arcs_4_1[1] = { - {7, 3}, + {7, 3}, }; static arc arcs_4_2[3] = { - {14, 4}, - {15, 4}, - {0, 2}, + {14, 4}, + {15, 4}, + {0, 2}, }; static arc arcs_4_3[1] = { - {12, 4}, + {12, 4}, }; static arc arcs_4_4[1] = { - {0, 4}, + {0, 4}, }; static state states_4[5] = { - {2, arcs_4_0}, - {1, arcs_4_1}, - {3, arcs_4_2}, - {1, arcs_4_3}, - {1, arcs_4_4}, + {2, arcs_4_0}, + {1, arcs_4_1}, + {3, arcs_4_2}, + {1, arcs_4_3}, + {1, arcs_4_4}, }; static arc arcs_5_0[3] = { - {5, 1}, - {16, 1}, - {17, 2}, + {5, 1}, + {16, 1}, + {17, 2}, }; static arc arcs_5_1[1] = { - {0, 1}, + {0, 1}, }; static arc arcs_5_2[1] = { - {7, 3}, + {7, 3}, }; static arc arcs_5_3[1] = { - {18, 1}, + {18, 1}, }; static state states_5[4] = { - {3, arcs_5_0}, - {1, arcs_5_1}, - {1, arcs_5_2}, - {1, arcs_5_3}, + {3, arcs_5_0}, + {1, arcs_5_1}, + {1, arcs_5_2}, + {1, arcs_5_3}, }; static dfa dfas[6] = { - {256, "MSTART", 0, 2, states_0, - "\070\000\000"}, - {257, "RULE", 0, 5, states_1, - "\040\000\000"}, - {258, "RHS", 0, 2, states_2, - "\040\010\003"}, - {259, "ALT", 0, 2, states_3, - "\040\010\003"}, - {260, "ITEM", 0, 5, states_4, - "\040\010\003"}, - {261, "ATOM", 0, 4, states_5, - "\040\000\003"}, + {256, "MSTART", 0, 2, states_0, + "\070\000\000"}, + {257, "RULE", 0, 5, states_1, + "\040\000\000"}, + {258, "RHS", 0, 2, states_2, + "\040\010\003"}, + {259, "ALT", 0, 2, states_3, + "\040\010\003"}, + {260, "ITEM", 0, 5, states_4, + "\040\010\003"}, + {261, "ATOM", 0, 4, states_5, + "\040\000\003"}, }; static label labels[19] = { - {0, "EMPTY"}, - {256, 0}, - {257, 0}, - {4, 0}, - {0, 0}, - {1, 0}, - {11, 0}, - {258, 0}, - {259, 0}, - {18, 0}, - {260, 0}, - {9, 0}, - {10, 0}, - {261, 0}, - {16, 0}, - {14, 0}, - {3, 0}, - {7, 0}, - {8, 0}, + {0, "EMPTY"}, + {256, 0}, + {257, 0}, + {4, 0}, + {0, 0}, + {1, 0}, + {11, 0}, + {258, 0}, + {259, 0}, + {18, 0}, + {260, 0}, + {9, 0}, + {10, 0}, + {261, 0}, + {16, 0}, + {14, 0}, + {3, 0}, + {7, 0}, + {8, 0}, }; static grammar gram = { - 6, - dfas, - {19, labels}, - 256 + 6, + dfas, + {19, labels}, + 256 }; grammar * meta_grammar() { - return &gram; + return &gram; } diff --git a/src/metagrammar.h b/src/metagrammar.h index a937b64..5b7db87 100644 --- a/src/metagrammar.h +++ b/src/metagrammar.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. diff --git a/src/methodobject.c b/src/methodobject.c index 68a0217..62649f1 100644 --- a/src/methodobject.c +++ b/src/methodobject.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -29,119 +29,119 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include "token.h" typedef struct { - OB_HEAD - char *m_name; - method m_meth; - object *m_self; + OB_HEAD + char *m_name; + method m_meth; + object *m_self; } methodobject; object * newmethodobject(name, meth, self) - char *name; /* static string */ - method meth; - object *self; + char *name; /* static string */ + method meth; + object *self; { - methodobject *op = NEWOBJ(methodobject, &Methodtype); - if (op != NULL) { - op->m_name = name; - op->m_meth = meth; - if (self != NULL) - INCREF(self); - op->m_self = self; - } - return (object *)op; + methodobject *op = NEWOBJ(methodobject, &Methodtype); + if (op != NULL) { + op->m_name = name; + op->m_meth = meth; + if (self != NULL) + INCREF(self); + op->m_self = self; + } + return (object *)op; } method getmethod(op) - object *op; + object *op; { - if (!is_methodobject(op)) { - err_badcall(); - return NULL; - } - return ((methodobject *)op) -> m_meth; + if (!is_methodobject(op)) { + err_badcall(); + return NULL; + } + return ((methodobject *)op) -> m_meth; } object * getself(op) - object *op; + object *op; { - if (!is_methodobject(op)) { - err_badcall(); - return NULL; - } - return ((methodobject *)op) -> m_self; + if (!is_methodobject(op)) { + err_badcall(); + return NULL; + } + return ((methodobject *)op) -> m_self; } /* Methods (the standard built-in methods, that is) */ static void meth_dealloc(m) - methodobject *m; + methodobject *m; { - if (m->m_self != NULL) - DECREF(m->m_self); - free((char *)m); + if (m->m_self != NULL) + DECREF(m->m_self); + free((char *)m); } static void meth_print(m, fp, flags) - methodobject *m; - FILE *fp; - int flags; + methodobject *m; + FILE *fp; + int flags; { - if (m->m_self == NULL) - fprintf(fp, "<built-in function '%s'>", m->m_name); - else - fprintf(fp, "<built-in method '%s' of some %s object>", - m->m_name, m->m_self->ob_type->tp_name); + if (m->m_self == NULL) + fprintf(fp, "<built-in function '%s'>", m->m_name); + else + fprintf(fp, "<built-in method '%s' of some %s object>", + m->m_name, m->m_self->ob_type->tp_name); } static object * meth_repr(m) - methodobject *m; + methodobject *m; { - char buf[200]; - if (m->m_self == NULL) - sprintf(buf, "<built-in function '%.80s'>", m->m_name); - else - sprintf(buf, - "<built-in method '%.80s' of some %.80s object>", - m->m_name, m->m_self->ob_type->tp_name); - return newstringobject(buf); + char buf[200]; + if (m->m_self == NULL) + sprintf(buf, "<built-in function '%.80s'>", m->m_name); + else + sprintf(buf, + "<built-in method '%.80s' of some %.80s object>", + m->m_name, m->m_self->ob_type->tp_name); + return newstringobject(buf); } typeobject Methodtype = { - OB_HEAD_INIT(&Typetype) - 0, - "method", - sizeof(methodobject), - 0, - meth_dealloc, /*tp_dealloc*/ - meth_print, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - meth_repr, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ + OB_HEAD_INIT(&Typetype) + 0, + "method", + sizeof(methodobject), + 0, + meth_dealloc, /*tp_dealloc*/ + meth_print, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + meth_repr, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ }; /* Find a method in a module's method table. - Usually called from an object's getattr method. */ + Usually called from an object's getattr method. */ object * findmethod(ml, op, name) - struct methodlist *ml; - object *op; - char *name; + struct methodlist *ml; + object *op; + char *name; { - for (; ml->ml_name != NULL; ml++) { - if (strcmp(name, ml->ml_name) == 0) - return newmethodobject(ml->ml_name, ml->ml_meth, op); - } - err_setstr(NameError, name); - return NULL; + for (; ml->ml_name != NULL; ml++) { + if (strcmp(name, ml->ml_name) == 0) + return newmethodobject(ml->ml_name, ml->ml_meth, op); + } + err_setstr(NameError, name); + return NULL; } diff --git a/src/methodobject.h b/src/methodobject.h index 674ed7d..262208d 100644 --- a/src/methodobject.h +++ b/src/methodobject.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -35,8 +35,8 @@ extern method getmethod PROTO((object *)); extern object *getself PROTO((object *)); struct methodlist { - char *ml_name; - method ml_meth; + char *ml_name; + method ml_meth; }; extern object *findmethod PROTO((struct methodlist *, object *, char *)); diff --git a/src/modsupport.c b/src/modsupport.c index 1044268..cf3e7b2 100644 --- a/src/modsupport.c +++ b/src/modsupport.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -31,351 +31,351 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. object * initmodule(name, methods) - char *name; - struct methodlist *methods; + char *name; + struct methodlist *methods; { - object *m, *d, *v; - struct methodlist *ml; - char namebuf[256]; - if ((m = add_module(name)) == NULL) { - fprintf(stderr, "initializing module: %s\n", name); - fatal("can't create a module"); - } - d = getmoduledict(m); - for (ml = methods; ml->ml_name != NULL; ml++) { - sprintf(namebuf, "%s.%s", name, ml->ml_name); - v = newmethodobject(strdup(namebuf), ml->ml_meth, - (object *)NULL); - /* XXX The strdup'ed memory is never freed */ - if (v == NULL || dictinsert(d, ml->ml_name, v) != 0) { - fprintf(stderr, "initializing module: %s\n", name); - fatal("can't initialize module"); - } - DECREF(v); - } - return m; + object *m, *d, *v; + struct methodlist *ml; + char namebuf[256]; + if ((m = add_module(name)) == NULL) { + fprintf(stderr, "initializing module: %s\n", name); + fatal("can't create a module"); + } + d = getmoduledict(m); + for (ml = methods; ml->ml_name != NULL; ml++) { + sprintf(namebuf, "%s.%s", name, ml->ml_name); + v = newmethodobject(strdup(namebuf), ml->ml_meth, + (object *)NULL); + /* XXX The strdup'ed memory is never freed */ + if (v == NULL || dictinsert(d, ml->ml_name, v) != 0) { + fprintf(stderr, "initializing module: %s\n", name); + fatal("can't initialize module"); + } + DECREF(v); + } + return m; } /* Argument list handling tools. - All return 1 for success, or call err_set*() and return 0 for failure */ + All return 1 for success, or call err_set*() and return 0 for failure */ int getnoarg(v) - object *v; + object *v; { - if (v != NULL) { - return err_badarg(); - } - return 1; + if (v != NULL) { + return err_badarg(); + } + return 1; } int getintarg(v, a) - object *v; - int *a; + object *v; + int *a; { - if (v == NULL || !is_intobject(v)) { - return err_badarg(); - } - *a = getintvalue(v); - return 1; + if (v == NULL || !is_intobject(v)) { + return err_badarg(); + } + *a = getintvalue(v); + return 1; } int getintintarg(v, a, b) - object *v; - int *a; - int *b; + object *v; + int *a; + int *b; { - if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { - return err_badarg(); - } - return getintarg(gettupleitem(v, 0), a) && - getintarg(gettupleitem(v, 1), b); + if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { + return err_badarg(); + } + return getintarg(gettupleitem(v, 0), a) && + getintarg(gettupleitem(v, 1), b); } int getlongarg(v, a) - object *v; - long *a; + object *v; + long *a; { - if (v == NULL || !is_intobject(v)) { - return err_badarg(); - } - *a = getintvalue(v); - return 1; + if (v == NULL || !is_intobject(v)) { + return err_badarg(); + } + *a = getintvalue(v); + return 1; } int getlonglongargs(v, a, b) - object *v; - long *a, *b; + object *v; + long *a, *b; { - if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { - return err_badarg(); - } - return getlongarg(gettupleitem(v, 0), a) && - getlongarg(gettupleitem(v, 1), b); + if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { + return err_badarg(); + } + return getlongarg(gettupleitem(v, 0), a) && + getlongarg(gettupleitem(v, 1), b); } int getlonglongobjectargs(v, a, b, c) - object *v; - long *a, *b; - object **c; + object *v; + long *a, *b; + object **c; { - if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 3) { - return err_badarg(); - } - if (getlongarg(gettupleitem(v, 0), a) && - getlongarg(gettupleitem(v, 1), b)) { - *c = gettupleitem(v, 2); - return 1; - } - else { - return err_badarg(); - } + if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 3) { + return err_badarg(); + } + if (getlongarg(gettupleitem(v, 0), a) && + getlongarg(gettupleitem(v, 1), b)) { + *c = gettupleitem(v, 2); + return 1; + } + else { + return err_badarg(); + } } int getstrarg(v, a) - object *v; - object **a; + object *v; + object **a; { - if (v == NULL || !is_stringobject(v)) { - return err_badarg(); - } - *a = v; - return 1; + if (v == NULL || !is_stringobject(v)) { + return err_badarg(); + } + *a = v; + return 1; } int getstrstrarg(v, a, b) - object *v; - object **a; - object **b; + object *v; + object **a; + object **b; { - if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { - return err_badarg(); - } - return getstrarg(gettupleitem(v, 0), a) && - getstrarg(gettupleitem(v, 1), b); + if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { + return err_badarg(); + } + return getstrarg(gettupleitem(v, 0), a) && + getstrarg(gettupleitem(v, 1), b); } int getstrstrintarg(v, a, b, c) - object *v; - object **a; - object **b; - int *c; + object *v; + object **a; + object **b; + int *c; { - if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 3) { - return err_badarg(); - } - return getstrarg(gettupleitem(v, 0), a) && - getstrarg(gettupleitem(v, 1), b) && - getintarg(gettupleitem(v, 2), c); + if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 3) { + return err_badarg(); + } + return getstrarg(gettupleitem(v, 0), a) && + getstrarg(gettupleitem(v, 1), b) && + getintarg(gettupleitem(v, 2), c); } int getstrintarg(v, a, b) - object *v; - object **a; - int *b; + object *v; + object **a; + int *b; { - if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { - return err_badarg(); - } - return getstrarg(gettupleitem(v, 0), a) && - getintarg(gettupleitem(v, 1), b); + if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { + return err_badarg(); + } + return getstrarg(gettupleitem(v, 0), a) && + getintarg(gettupleitem(v, 1), b); } int getintstrarg(v, a, b) - object *v; - int *a; - object **b; + object *v; + int *a; + object **b; { - if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { - return err_badarg(); - } - return getintarg(gettupleitem(v, 0), a) && - getstrarg(gettupleitem(v, 1), b); + if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { + return err_badarg(); + } + return getintarg(gettupleitem(v, 0), a) && + getstrarg(gettupleitem(v, 1), b); } int getpointarg(v, a) - object *v; - int *a; /* [2] */ + object *v; + int *a; /* [2] */ { - return getintintarg(v, a, a+1); + return getintintarg(v, a, a+1); } int get3pointarg(v, a) - object *v; - int *a; /* [6] */ + object *v; + int *a; /* [6] */ { - if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 3) { - return err_badarg(); - } - return getpointarg(gettupleitem(v, 0), a) && - getpointarg(gettupleitem(v, 1), a+2) && - getpointarg(gettupleitem(v, 2), a+4); + if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 3) { + return err_badarg(); + } + return getpointarg(gettupleitem(v, 0), a) && + getpointarg(gettupleitem(v, 1), a+2) && + getpointarg(gettupleitem(v, 2), a+4); } int getrectarg(v, a) - object *v; - int *a; /* [2+2] */ + object *v; + int *a; /* [2+2] */ { - if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { - return err_badarg(); - } - return getpointarg(gettupleitem(v, 0), a) && - getpointarg(gettupleitem(v, 1), a+2); + if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { + return err_badarg(); + } + return getpointarg(gettupleitem(v, 0), a) && + getpointarg(gettupleitem(v, 1), a+2); } int getrectintarg(v, a) - object *v; - int *a; /* [4+1] */ + object *v; + int *a; /* [4+1] */ { - if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { - return err_badarg(); - } - return getrectarg(gettupleitem(v, 0), a) && - getintarg(gettupleitem(v, 1), a+4); + if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { + return err_badarg(); + } + return getrectarg(gettupleitem(v, 0), a) && + getintarg(gettupleitem(v, 1), a+4); } int getpointintarg(v, a) - object *v; - int *a; /* [2+1] */ + object *v; + int *a; /* [2+1] */ { - if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { - return err_badarg(); - } - return getpointarg(gettupleitem(v, 0), a) && - getintarg(gettupleitem(v, 1), a+2); + if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { + return err_badarg(); + } + return getpointarg(gettupleitem(v, 0), a) && + getintarg(gettupleitem(v, 1), a+2); } int getpointstrarg(v, a, b) - object *v; - int *a; /* [2] */ - object **b; + object *v; + int *a; /* [2] */ + object **b; { - if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { - return err_badarg(); - } - return getpointarg(gettupleitem(v, 0), a) && - getstrarg(gettupleitem(v, 1), b); + if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { + return err_badarg(); + } + return getpointarg(gettupleitem(v, 0), a) && + getstrarg(gettupleitem(v, 1), b); } int getstrintintarg(v, a, b, c) - object *v; - object *a; - int *b, *c; + object *v; + object *a; + int *b, *c; { - if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 3) { - return err_badarg(); - } - return getstrarg(gettupleitem(v, 0), a) && - getintarg(gettupleitem(v, 1), b) && - getintarg(gettupleitem(v, 2), c); + if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 3) { + return err_badarg(); + } + return getstrarg(gettupleitem(v, 0), a) && + getintarg(gettupleitem(v, 1), b) && + getintarg(gettupleitem(v, 2), c); } int getrectpointarg(v, a) - object *v; - int *a; /* [4+2] */ + object *v; + int *a; /* [4+2] */ { - if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { - return err_badarg(); - } - return getrectarg(gettupleitem(v, 0), a) && - getpointarg(gettupleitem(v, 1), a+4); + if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { + return err_badarg(); + } + return getrectarg(gettupleitem(v, 0), a) && + getpointarg(gettupleitem(v, 1), a+4); } int getlongtuplearg(args, a, n) - object *args; - long *a; /* [n] */ - int n; + object *args; + long *a; /* [n] */ + int n; { - int i; - if (!is_tupleobject(args) || gettuplesize(args) != n) { - return err_badarg(); - } - for (i = 0; i < n; i++) { - object *v = gettupleitem(args, i); - if (!is_intobject(v)) { - return err_badarg(); - } - a[i] = getintvalue(v); - } - return 1; + int i; + if (!is_tupleobject(args) || gettuplesize(args) != n) { + return err_badarg(); + } + for (i = 0; i < n; i++) { + object *v = gettupleitem(args, i); + if (!is_intobject(v)) { + return err_badarg(); + } + a[i] = getintvalue(v); + } + return 1; } int getshorttuplearg(args, a, n) - object *args; - short *a; /* [n] */ - int n; + object *args; + short *a; /* [n] */ + int n; { - int i; - if (!is_tupleobject(args) || gettuplesize(args) != n) { - return err_badarg(); - } - for (i = 0; i < n; i++) { - object *v = gettupleitem(args, i); - if (!is_intobject(v)) { - return err_badarg(); - } - a[i] = getintvalue(v); - } - return 1; + int i; + if (!is_tupleobject(args) || gettuplesize(args) != n) { + return err_badarg(); + } + for (i = 0; i < n; i++) { + object *v = gettupleitem(args, i); + if (!is_intobject(v)) { + return err_badarg(); + } + a[i] = getintvalue(v); + } + return 1; } int getlonglistarg(args, a, n) - object *args; - long *a; /* [n] */ - int n; + object *args; + long *a; /* [n] */ + int n; { - int i; - if (!is_listobject(args) || getlistsize(args) != n) { - return err_badarg(); - } - for (i = 0; i < n; i++) { - object *v = getlistitem(args, i); - if (!is_intobject(v)) { - return err_badarg(); - } - a[i] = getintvalue(v); - } - return 1; + int i; + if (!is_listobject(args) || getlistsize(args) != n) { + return err_badarg(); + } + for (i = 0; i < n; i++) { + object *v = getlistitem(args, i); + if (!is_intobject(v)) { + return err_badarg(); + } + a[i] = getintvalue(v); + } + return 1; } int getshortlistarg(args, a, n) - object *args; - short *a; /* [n] */ - int n; + object *args; + short *a; /* [n] */ + int n; { - int i; - if (!is_listobject(args) || getlistsize(args) != n) { - return err_badarg(); - } - for (i = 0; i < n; i++) { - object *v = getlistitem(args, i); - if (!is_intobject(v)) { - return err_badarg(); - } - a[i] = getintvalue(v); - } - return 1; + int i; + if (!is_listobject(args) || getlistsize(args) != n) { + return err_badarg(); + } + for (i = 0; i < n; i++) { + object *v = getlistitem(args, i); + if (!is_intobject(v)) { + return err_badarg(); + } + a[i] = getintvalue(v); + } + return 1; } diff --git a/src/modsupport.h b/src/modsupport.h index bc9929a..016220f 100644 --- a/src/modsupport.h +++ b/src/modsupport.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -25,5 +25,3 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* Module support interface */ extern object *initmodule PROTO((char *, struct methodlist *)); -extern int getintarg(object *v, int *a); -extern void fatal(char *msg); diff --git a/src/moduleobject.c b/src/moduleobject.c index 82599f9..d30d465 100644 --- a/src/moduleobject.c +++ b/src/moduleobject.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -27,128 +27,128 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include "allobjects.h" typedef struct { - OB_HEAD - object *md_name; - object *md_dict; + OB_HEAD + object *md_name; + object *md_dict; } moduleobject; object * newmoduleobject(name) - char *name; + char *name; { - moduleobject *m = NEWOBJ(moduleobject, &Moduletype); - if (m == NULL) - return NULL; - m->md_name = newstringobject(name); - m->md_dict = newdictobject(); - if (m->md_name == NULL || m->md_dict == NULL) { - DECREF(m); - return NULL; - } - return (object *)m; + moduleobject *m = NEWOBJ(moduleobject, &Moduletype); + if (m == NULL) + return NULL; + m->md_name = newstringobject(name); + m->md_dict = newdictobject(); + if (m->md_name == NULL || m->md_dict == NULL) { + DECREF(m); + return NULL; + } + return (object *)m; } object * getmoduledict(m) - object *m; + object *m; { - if (!is_moduleobject(m)) { - err_badcall(); - return NULL; - } - return ((moduleobject *)m) -> md_dict; + if (!is_moduleobject(m)) { + err_badcall(); + return NULL; + } + return ((moduleobject *)m) -> md_dict; } char * getmodulename(m) - object *m; + object *m; { - if (!is_moduleobject(m)) { - err_badarg(); - return NULL; - } - return getstringvalue(((moduleobject *)m) -> md_name); + if (!is_moduleobject(m)) { + err_badarg(); + return NULL; + } + return getstringvalue(((moduleobject *)m) -> md_name); } /* Methods */ static void module_dealloc(m) - moduleobject *m; + moduleobject *m; { - if (m->md_name != NULL) - DECREF(m->md_name); - if (m->md_dict != NULL) - DECREF(m->md_dict); - free((char *)m); + if (m->md_name != NULL) + DECREF(m->md_name); + if (m->md_dict != NULL) + DECREF(m->md_dict); + free((char *)m); } static void module_print(m, fp, flags) - moduleobject *m; - FILE *fp; - int flags; + moduleobject *m; + FILE *fp; + int flags; { - fprintf(fp, "<module '%s'>", getstringvalue(m->md_name)); + fprintf(fp, "<module '%s'>", getstringvalue(m->md_name)); } static object * module_repr(m) - moduleobject *m; + moduleobject *m; { - char buf[100]; - sprintf(buf, "<module '%.80s'>", getstringvalue(m->md_name)); - return newstringobject(buf); + char buf[100]; + sprintf(buf, "<module '%.80s'>", getstringvalue(m->md_name)); + return newstringobject(buf); } static object * module_getattr(m, name) - moduleobject *m; - char *name; + moduleobject *m; + char *name; { - object *res; - if (strcmp(name, "__dict__") == 0) { - INCREF(m->md_dict); - return m->md_dict; - } - if (strcmp(name, "__name__") == 0) { - INCREF(m->md_name); - return m->md_name; - } - res = dictlookup(m->md_dict, name); - if (res == NULL) - err_setstr(NameError, name); - else - INCREF(res); - return res; + object *res; + if (strcmp(name, "__dict__") == 0) { + INCREF(m->md_dict); + return m->md_dict; + } + if (strcmp(name, "__name__") == 0) { + INCREF(m->md_name); + return m->md_name; + } + res = dictlookup(m->md_dict, name); + if (res == NULL) + err_setstr(NameError, name); + else + INCREF(res); + return res; } static int module_setattr(m, name, v) - moduleobject *m; - char *name; - object *v; + moduleobject *m; + char *name; + object *v; { - if (strcmp(name, "__dict__") == 0 || strcmp(name, "__name__") == 0) { - err_setstr(NameError, "can't assign to reserved member name"); - return -1; - } - if (v == NULL) - return dictremove(m->md_dict, name); - else - return dictinsert(m->md_dict, name, v); + if (strcmp(name, "__dict__") == 0 || strcmp(name, "__name__") == 0) { + err_setstr(NameError, "can't assign to reserved member name"); + return -1; + } + if (v == NULL) + return dictremove(m->md_dict, name); + else + return dictinsert(m->md_dict, name, v); } typeobject Moduletype = { - OB_HEAD_INIT(&Typetype) - 0, /*ob_size*/ - "module", /*tp_name*/ - sizeof(moduleobject), /*tp_size*/ - 0, /*tp_itemsize*/ - module_dealloc, /*tp_dealloc*/ - module_print, /*tp_print*/ - module_getattr, /*tp_getattr*/ - module_setattr, /*tp_setattr*/ - 0, /*tp_compare*/ - module_repr, /*tp_repr*/ + OB_HEAD_INIT(&Typetype) + 0, /*ob_size*/ + "module", /*tp_name*/ + sizeof(moduleobject), /*tp_size*/ + 0, /*tp_itemsize*/ + module_dealloc, /*tp_dealloc*/ + module_print, /*tp_print*/ + module_getattr, /*tp_getattr*/ + module_setattr, /*tp_setattr*/ + 0, /*tp_compare*/ + module_repr, /*tp_repr*/ }; diff --git a/src/moduleobject.h b/src/moduleobject.h index 4657c22..34a382f 100644 --- a/src/moduleobject.h +++ b/src/moduleobject.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -29,17 +29,17 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. node * newtree(type) - int type; + int type; { - node *n = NEW(node, 1); - if (n == NULL) - return NULL; - n->n_type = type; - n->n_str = NULL; - n->n_lineno = 0; - n->n_nchildren = 0; - n->n_child = NULL; - return n; + node *n = NEW(node, 1); + if (n == NULL) + return NULL; + n->n_type = type; + n->n_str = NULL; + n->n_lineno = 0; + n->n_nchildren = 0; + n->n_child = NULL; + return n; } #define XXX 3 /* Node alignment factor to speed up realloc */ @@ -47,29 +47,29 @@ newtree(type) node * addchild(n1, type, str, lineno) - register node *n1; - int type; - char *str; - int lineno; + register node *n1; + int type; + char *str; + int lineno; { - register int nch = n1->n_nchildren; - register int nch1 = nch+1; - register node *n; - if (XXXROUNDUP(nch) < nch1) { - n = n1->n_child; - nch1 = XXXROUNDUP(nch1); - RESIZE(n, node, nch1); - if (n == NULL) - return NULL; - n1->n_child = n; - } - n = &n1->n_child[n1->n_nchildren++]; - n->n_type = type; - n->n_str = str; - n->n_lineno = lineno; - n->n_nchildren = 0; - n->n_child = NULL; - return n; + register int nch = n1->n_nchildren; + register int nch1 = nch+1; + register node *n; + if (XXXROUNDUP(nch) < nch1) { + n = n1->n_child; + nch1 = XXXROUNDUP(nch1); + RESIZE(n, node, nch1); + if (n == NULL) + return NULL; + n1->n_child = n; + } + n = &n1->n_child[n1->n_nchildren++]; + n->n_type = type; + n->n_str = str; + n->n_lineno = lineno; + n->n_nchildren = 0; + n->n_child = NULL; + return n; } /* Forward */ @@ -78,23 +78,23 @@ static void freechildren PROTO((node *)); void freetree(n) - node *n; + node *n; { - if (n != NULL) { - freechildren(n); - DEL(n); - } + if (n != NULL) { + freechildren(n); + DEL(n); + } } static void freechildren(n) - node *n; + node *n; { - int i; - for (i = NCH(n); --i >= 0; ) - freechildren(CHILD(n, i)); - if (n->n_child != NULL) - DEL(n->n_child); - if (STR(n) != NULL) - DEL(STR(n)); + int i; + for (i = NCH(n); --i >= 0; ) + freechildren(CHILD(n, i)); + if (n->n_child != NULL) + DEL(n->n_child); + if (STR(n) != NULL) + DEL(STR(n)); } @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -25,11 +25,11 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* Parse tree node interface */ typedef struct _node { - int n_type; - char *n_str; - int n_lineno; - int n_nchildren; - struct _node *n_child; + int n_type; + char *n_str; + int n_lineno; + int n_nchildren; + struct _node *n_child; } node; extern node *newtree PROTO((int type)); @@ -37,21 +37,21 @@ extern node *addchild PROTO((node *n, int type, char *str, int lineno)); extern void freetree PROTO((node *n)); /* Node access functions */ -#define NCH(n) ((n)->n_nchildren) -#define CHILD(n, i) (&(n)->n_child[i]) -#define TYPE(n) ((n)->n_type) -#define STR(n) ((n)->n_str) +#define NCH(n) ((n)->n_nchildren) +#define CHILD(n, i) (&(n)->n_child[i]) +#define TYPE(n) ((n)->n_type) +#define STR(n) ((n)->n_str) /* Assert that the type of a node is what we expect */ #ifndef DEBUG #define REQ(n, type) { /*pass*/ ; } #else #define REQ(n, type) \ - { if (TYPE(n) != (type)) { \ - fprintf(stderr, "FATAL: node type %d, required %d\n", \ - TYPE(n), type); \ - abort(); \ - } } + { if (TYPE(n) != (type)) { \ + fprintf(stderr, "FATAL: node type %d, required %d\n", \ + TYPE(n), type); \ + abort(); \ + } } #endif extern void listtree PROTO((node *)); diff --git a/src/object.c b/src/object.c index 37e2b26..c54bf5c 100644 --- a/src/object.c +++ b/src/object.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -31,36 +31,36 @@ long ref_total; #endif /* Object allocation routines used by NEWOBJ and NEWVAROBJ macros. - These are used by the individual routines for object creation. - Do not call them otherwise, they do not initialize the object! */ + These are used by the individual routines for object creation. + Do not call them otherwise, they do not initialize the object! */ object * newobject(tp) - typeobject *tp; + typeobject *tp; { - object *op = (object *) malloc(tp->tp_basicsize); - if (op == NULL) - return err_nomem(); - NEWREF(op); - op->ob_type = tp; - return op; + object *op = (object *) malloc(tp->tp_basicsize); + if (op == NULL) + return err_nomem(); + NEWREF(op); + op->ob_type = tp; + return op; } #if 0 /* unused */ varobject * newvarobject(tp, size) - typeobject *tp; - unsigned int size; + typeobject *tp; + unsigned int size; { - varobject *op = (varobject *) - malloc(tp->tp_basicsize + size * tp->tp_itemsize); - if (op == NULL) - return err_nomem(); - NEWREF(op); - op->ob_type = tp; - op->ob_size = size; - return op; + varobject *op = (varobject *) + malloc(tp->tp_basicsize + size * tp->tp_itemsize); + if (op == NULL) + return err_nomem(); + NEWREF(op); + op->ob_type = tp; + op->ob_size = size; + return op; } #endif @@ -71,121 +71,121 @@ static int prlevel; void printobject(op, fp, flags) - object *op; - FILE *fp; - int flags; + object *op; + FILE *fp; + int flags; { - /* Hacks to make printing a long or recursive object interruptible */ - /* XXX Interrupts should leave a more permanent error */ - prlevel++; - if (!StopPrint && intrcheck()) { - fprintf(fp, "\n[print interrupted]\n"); - StopPrint = 1; - } - if (!StopPrint) { - if (op == NULL) { - fprintf(fp, "<nil>"); - } - else { - if (op->ob_refcnt <= 0) - fprintf(fp, "(refcnt %d):", op->ob_refcnt); - if (op->ob_type->tp_print == NULL) { - fprintf(fp, "<%s object at %lx>", - op->ob_type->tp_name, (long)op); - } - else { - (*op->ob_type->tp_print)(op, fp, flags); - } - } - } - prlevel--; - if (prlevel == 0) - StopPrint = 0; + /* Hacks to make printing a long or recursive object interruptible */ + /* XXX Interrupts should leave a more permanent error */ + prlevel++; + if (!StopPrint && intrcheck()) { + fprintf(fp, "\n[print interrupted]\n"); + StopPrint = 1; + } + if (!StopPrint) { + if (op == NULL) { + fprintf(fp, "<nil>"); + } + else { + if (op->ob_refcnt <= 0) + fprintf(fp, "(refcnt %d):", op->ob_refcnt); + if (op->ob_type->tp_print == NULL) { + fprintf(fp, "<%s object at %lx>", + op->ob_type->tp_name, (long)op); + } + else { + (*op->ob_type->tp_print)(op, fp, flags); + } + } + } + prlevel--; + if (prlevel == 0) + StopPrint = 0; } object * reprobject(v) - object *v; + object *v; { - object *w = NULL; - /* Hacks to make converting a long or recursive object interruptible */ - prlevel++; - if (!StopPrint && intrcheck()) { - StopPrint = 1; - err_set(KeyboardInterrupt); - } - if (!StopPrint) { - if (v == NULL) { - w = newstringobject("<NULL>"); - } - else if (v->ob_type->tp_repr == NULL) { - char buf[100]; - sprintf(buf, "<%.80s object at %lx>", - v->ob_type->tp_name, (long)v); - w = newstringobject(buf); - } - else { - w = (*v->ob_type->tp_repr)(v); - } - if (StopPrint) { - XDECREF(w); - w = NULL; - } - } - prlevel--; - if (prlevel == 0) - StopPrint = 0; - return w; + object *w = NULL; + /* Hacks to make converting a long or recursive object interruptible */ + prlevel++; + if (!StopPrint && intrcheck()) { + StopPrint = 1; + err_set(KeyboardInterrupt); + } + if (!StopPrint) { + if (v == NULL) { + w = newstringobject("<NULL>"); + } + else if (v->ob_type->tp_repr == NULL) { + char buf[100]; + sprintf(buf, "<%.80s object at %lx>", + v->ob_type->tp_name, (long)v); + w = newstringobject(buf); + } + else { + w = (*v->ob_type->tp_repr)(v); + } + if (StopPrint) { + XDECREF(w); + w = NULL; + } + } + prlevel--; + if (prlevel == 0) + StopPrint = 0; + return w; } int cmpobject(v, w) - object *v, *w; + object *v, *w; { - typeobject *tp; - if (v == w) - return 0; - if (v == NULL) - return -1; - if (w == NULL) - return 1; - if ((tp = v->ob_type) != w->ob_type) - return strcmp(tp->tp_name, w->ob_type->tp_name); - if (tp->tp_compare == NULL) - return (v < w) ? -1 : 1; - return ((*tp->tp_compare)(v, w)); + typeobject *tp; + if (v == w) + return 0; + if (v == NULL) + return -1; + if (w == NULL) + return 1; + if ((tp = v->ob_type) != w->ob_type) + return strcmp(tp->tp_name, w->ob_type->tp_name); + if (tp->tp_compare == NULL) + return (v < w) ? -1 : 1; + return ((*tp->tp_compare)(v, w)); } object * getattr(v, name) - object *v; - char *name; + object *v; + char *name; { - if (v->ob_type->tp_getattr == NULL) { - err_setstr(TypeError, "attribute-less object"); - return NULL; - } - else { - return (*v->ob_type->tp_getattr)(v, name); - } + if (v->ob_type->tp_getattr == NULL) { + err_setstr(TypeError, "attribute-less object"); + return NULL; + } + else { + return (*v->ob_type->tp_getattr)(v, name); + } } int setattr(v, name, w) - object *v; - char *name; - object *w; + object *v; + char *name; + object *w; { - if (v->ob_type->tp_setattr == NULL) { - if (v->ob_type->tp_getattr == NULL) - err_setstr(TypeError, "attribute-less object"); - else - err_setstr(TypeError, "object has read-only attributes"); - return -1; - } - else { - return (*v->ob_type->tp_setattr)(v, name, w); - } + if (v->ob_type->tp_setattr == NULL) { + if (v->ob_type->tp_getattr == NULL) + err_setstr(TypeError, "attribute-less object"); + else + err_setstr(TypeError, "object has read-only attributes"); + return -1; + } + else { + return (*v->ob_type->tp_setattr)(v, name, w); + } } @@ -197,39 +197,39 @@ so there is exactly one (which is indestructible, by the way). static void none_print(op, fp, flags) - object *op; - FILE *fp; - int flags; + object *op; + FILE *fp; + int flags; { - fprintf(fp, "None"); + fprintf(fp, "None"); } static object * none_repr(op) - object *op; + object *op; { - return newstringobject("None"); + return newstringobject("None"); } static typeobject Notype = { - OB_HEAD_INIT(&Typetype) - 0, - "None", - 0, - 0, - 0, /*tp_dealloc*/ /*never called*/ - none_print, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - none_repr, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ + OB_HEAD_INIT(&Typetype) + 0, + "None", + 0, + 0, + 0, /*tp_dealloc*/ /*never called*/ + none_print, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + none_repr, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ }; object NoObject = { - OB_HEAD_INIT(&Notype) + OB_HEAD_INIT(&Notype) }; @@ -238,53 +238,53 @@ object NoObject = { static object refchain = {&refchain, &refchain}; NEWREF(op) - object *op; + object *op; { - ref_total++; - op->ob_refcnt = 1; - op->_ob_next = refchain._ob_next; - op->_ob_prev = &refchain; - refchain._ob_next->_ob_prev = op; - refchain._ob_next = op; + ref_total++; + op->ob_refcnt = 1; + op->_ob_next = refchain._ob_next; + op->_ob_prev = &refchain; + refchain._ob_next->_ob_prev = op; + refchain._ob_next = op; } UNREF(op) - register object *op; + register object *op; { - register object *p; - if (op->ob_refcnt < 0) { - fprintf(stderr, "UNREF negative refcnt\n"); - abort(); - } - for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) { - if (p == op) - break; - } - if (p == &refchain) { /* Not found */ - fprintf(stderr, "UNREF unknown object\n"); - abort(); - } - op->_ob_next->_ob_prev = op->_ob_prev; - op->_ob_prev->_ob_next = op->_ob_next; + register object *p; + if (op->ob_refcnt < 0) { + fprintf(stderr, "UNREF negative refcnt\n"); + abort(); + } + for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) { + if (p == op) + break; + } + if (p == &refchain) { /* Not found */ + fprintf(stderr, "UNREF unknown object\n"); + abort(); + } + op->_ob_next->_ob_prev = op->_ob_prev; + op->_ob_prev->_ob_next = op->_ob_next; } DELREF(op) - object *op; + object *op; { - UNREF(op); - (*(op)->ob_type->tp_dealloc)(op); + UNREF(op); + (*(op)->ob_type->tp_dealloc)(op); } printrefs(fp) - FILE *fp; + FILE *fp; { - object *op; - fprintf(fp, "Remaining objects:\n"); - for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) { - fprintf(fp, "[%d] ", op->ob_refcnt); - printobject(op, fp, 0); - putc('\n', fp); - } + object *op; + fprintf(fp, "Remaining objects:\n"); + for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) { + fprintf(fp, "[%d] ", op->ob_refcnt); + printobject(op, fp, 0); + putc('\n', fp); + } } #endif diff --git a/src/object.h b/src/object.h index f0266c4..9ea5260 100644 --- a/src/object.h +++ b/src/object.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -28,10 +28,10 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* 123456789-123456789-123456789-123456789-123456789-123456789-123456789-12 -Objects are structures allocated on the heap. Special rules apply to +Objects are structures allocated on the heap. Special rules apply to the use of objects to ensure they are properly garbage-collected. Objects are never allocated statically or on the stack; they must be -accessed through special macros and functions only. (Type objects are +accessed through special macros and functions only. (Type objects are exceptions to the first rule; the standard types are represented by statically initialized type objects.) @@ -41,28 +41,28 @@ reaches zero there are no references to the object left and it can be removed from the heap. An object has a 'type' that determines what it represents and what kind -of data it contains. An object's type is fixed when it is created. +of data it contains. An object's type is fixed when it is created. Types themselves are represented as objects; an object contains a -pointer to the corresponding type object. The type itself has a type +pointer to the corresponding type object. The type itself has a type pointer pointing to the object representing the type 'type', which contains a pointer to itself!). Objects do not float around in memory; once allocated an object keeps -the same size and address. Objects that must hold variable-size data -can contain pointers to variable-size parts of the object. Not all +the same size and address. Objects that must hold variable-size data +can contain pointers to variable-size parts of the object. Not all objects of the same type have the same size; but the size cannot change -after allocation. (These restrictions are made so a reference to an +after allocation. (These restrictions are made so a reference to an object can be simply a pointer -- moving an object would require updating all the pointers, and changing an object's size would require moving it if there was another object right next to it.) Objects are always accessed through pointers of the type 'object *'. The type 'object' is a structure that only contains the reference count -and the type pointer. The actual memory allocated for an object +and the type pointer. The actual memory allocated for an object contains other data that can only be accessed after casting the pointer -to a pointer to a longer structure type. This longer type must start +to a pointer to a longer structure type. This longer type must start with the reference count and type fields; the macro OB_HEAD should be -used for this (to accomodate for future changes). The implementation +used for this (to accomodate for future changes). The implementation of a particular object type can cast the object pointer to the proper type and back. @@ -84,27 +84,27 @@ whose size is determined when the object is allocated. #ifdef TRACE_REFS #define OB_HEAD \ - struct _object *_ob_next, *_ob_prev; \ - int ob_refcnt; \ - struct _typeobject *ob_type; + struct _object *_ob_next, *_ob_prev; \ + int ob_refcnt; \ + struct _typeobject *ob_type; #define OB_HEAD_INIT(type) 0, 0, 1, type, #else #define OB_HEAD \ - unsigned int ob_refcnt; \ - struct _typeobject *ob_type; + unsigned int ob_refcnt; \ + struct _typeobject *ob_type; #define OB_HEAD_INIT(type) 1, type, #endif #define OB_VARHEAD \ - OB_HEAD \ - unsigned int ob_size; /* Number of items in variable part */ - + OB_HEAD \ + unsigned int ob_size; /* Number of items in variable part */ + typedef struct _object { - OB_HEAD + OB_HEAD } object; typedef struct { - OB_VARHEAD + OB_VARHEAD } varobject; @@ -113,9 +113,9 @@ typedef struct { Type objects contain a string containing the type name (to help somewhat in debugging), the allocation parameters (see newobj() and newvarobj()), -and methods for accessing objects of the type. Methods are optional,a +and methods for accessing objects of the type. Methods are optional,a nil pointer meaning that particular kind of access is not available for -this type. The DECREF() macro uses the tp_dealloc method without +this type. The DECREF() macro uses the tp_dealloc method without checking for a nil pointer; it should always be implemented except if the implementation can guarantee that the reference count will never reach zero (e.g., for type objects). @@ -125,51 +125,51 @@ method blocks. */ typedef struct { - object *(*nb_add) FPROTO((object *, object *)); - object *(*nb_subtract) FPROTO((object *, object *)); - object *(*nb_multiply) FPROTO((object *, object *)); - object *(*nb_divide) FPROTO((object *, object *)); - object *(*nb_remainder) FPROTO((object *, object *)); - object *(*nb_power) FPROTO((object *, object *)); - object *(*nb_negative) FPROTO((object *)); - object *(*nb_positive) FPROTO((object *)); + object *(*nb_add) FPROTO((object *, object *)); + object *(*nb_subtract) FPROTO((object *, object *)); + object *(*nb_multiply) FPROTO((object *, object *)); + object *(*nb_divide) FPROTO((object *, object *)); + object *(*nb_remainder) FPROTO((object *, object *)); + object *(*nb_power) FPROTO((object *, object *)); + object *(*nb_negative) FPROTO((object *)); + object *(*nb_positive) FPROTO((object *)); } number_methods; typedef struct { - int (*sq_length) FPROTO((object *)); - object *(*sq_concat) FPROTO((object *, object *)); - object *(*sq_repeat) FPROTO((object *, int)); - object *(*sq_item) FPROTO((object *, int)); - object *(*sq_slice) FPROTO((object *, int, int)); - int (*sq_ass_item) FPROTO((object *, int, object *)); - int (*sq_ass_slice) FPROTO((object *, int, int, object *)); + int (*sq_length) FPROTO((object *)); + object *(*sq_concat) FPROTO((object *, object *)); + object *(*sq_repeat) FPROTO((object *, int)); + object *(*sq_item) FPROTO((object *, int)); + object *(*sq_slice) FPROTO((object *, int, int)); + int (*sq_ass_item) FPROTO((object *, int, object *)); + int (*sq_ass_slice) FPROTO((object *, int, int, object *)); } sequence_methods; typedef struct { - int (*mp_length) FPROTO((object *)); - object *(*mp_subscript) FPROTO((object *, object *)); - int (*mp_ass_subscript) FPROTO((object *, object *, object *)); + int (*mp_length) FPROTO((object *)); + object *(*mp_subscript) FPROTO((object *, object *)); + int (*mp_ass_subscript) FPROTO((object *, object *, object *)); } mapping_methods; typedef struct _typeobject { - OB_VARHEAD - char *tp_name; /* For printing */ - unsigned int tp_basicsize, tp_itemsize; /* For allocation */ - - /* Methods to implement standard operations */ - - void (*tp_dealloc) FPROTO((object *)); - void (*tp_print) FPROTO((object *, FILE *, int)); - object *(*tp_getattr) FPROTO((object *, char *)); - int (*tp_setattr) FPROTO((object *, char *, object *)); - int (*tp_compare) FPROTO((object *, object *)); - object *(*tp_repr) FPROTO((object *)); - - /* Method suites for standard classes */ - - number_methods *tp_as_number; - sequence_methods *tp_as_sequence; - mapping_methods *tp_as_mapping; + OB_VARHEAD + char *tp_name; /* For printing */ + unsigned int tp_basicsize, tp_itemsize; /* For allocation */ + + /* Methods to implement standard operations */ + + void (*tp_dealloc) FPROTO((object *)); + void (*tp_print) FPROTO((object *, FILE *, int)); + object *(*tp_getattr) FPROTO((object *, char *)); + int (*tp_setattr) FPROTO((object *, char *, object *)); + int (*tp_compare) FPROTO((object *, object *)); + object *(*tp_repr) FPROTO((object *)); + + /* Method suites for standard classes */ + + number_methods *tp_as_number; + sequence_methods *tp_as_sequence; + mapping_methods *tp_as_mapping; } typeobject; extern typeobject Typetype; /* The type of type objects */ @@ -184,32 +184,32 @@ extern object *getattr PROTO((object *, char *)); extern int setattr PROTO((object *, char *, object *)); /* Flag bits for printing: */ -#define PRINT_RAW 1 /* No string quotes etc. */ +#define PRINT_RAW 1 /* No string quotes etc. */ /* 123456789-123456789-123456789-123456789-123456789-123456789-123456789-12 The macros INCREF(op) and DECREF(op) are used to increment or decrement -reference counts. DECREF calls the object's deallocator function; for +reference counts. DECREF calls the object's deallocator function; for objects that don't contain references to other objects or heap memory -this can be the standard function free(). Both macros can be used -whereever a void expression is allowed. The argument shouldn't be a -NIL pointer. The macro NEWREF(op) is used only to initialize reference +this can be the standard function free(). Both macros can be used +whereever a void expression is allowed. The argument shouldn't be a +NIL pointer. The macro NEWREF(op) is used only to initialize reference counts to 1; it is defined here for convenience. We assume that the reference count field can never overflow; this can be proven when the size of the field is the same as the pointer size but even with a 16-bit reference count field it is pretty unlikely so -we ignore the possibility. (If you are paranoid, make it a long.) +we ignore the possibility. (If you are paranoid, make it a long.) Type objects should never be deallocated; the type pointer in an object is not considered to be a reference to the type object, to save -complications in the deallocation function. (This is actually a +complications in the deallocation function. (This is actually a decision that's up to the implementer of each new type so if you want, you can count such references to the type object.) *** WARNING*** The DECREF macro must have a side-effect-free argument -since it may evaluate its argument multiple times. (The alternative +since it may evaluate its argument multiple times. (The alternative would be to mace it a proper function or assign it to a global temporary variable first, both of which are slower; and in a multi-threaded environment the global variable trick is not safe.) @@ -233,18 +233,18 @@ extern long ref_total; #endif #define INCREF(op) (ref_total++, (op)->ob_refcnt++) #define DECREF(op) \ - if (--ref_total, --(op)->ob_refcnt > 0) \ - ; \ - else \ - DELREF(op) + if (--ref_total, --(op)->ob_refcnt > 0) \ + ; \ + else \ + DELREF(op) #else #define NEWREF(op) ((op)->ob_refcnt = 1) #define INCREF(op) ((op)->ob_refcnt++) #define DECREF(op) \ - if (--(op)->ob_refcnt > 0) \ - ; \ - else \ - DELREF(op) + if (--(op)->ob_refcnt > 0) \ + ; \ + else \ + DELREF(op) #endif /* Macros to use in case the object pointer may be NULL: */ @@ -288,7 +288,7 @@ Failure Modes ------------- Functions may fail for a variety of reasons, including running out of -memory. This is communicated to the caller in two ways: an error string +memory. This is communicated to the caller in two ways: an error string is set (see errors.h), and the function result differs: functions that normally return a pointer return NULL for failure, functions returning an integer return -1 (which could be a legal return value too!), and @@ -304,10 +304,10 @@ Functions that create an object set the reference count to 1; such new objects must be stored somewhere or destroyed again with DECREF(). Functions that 'store' objects such as settupleitem() and dictinsert() don't increment the reference count of the object, since the most -frequent use is to store a fresh object. Functions that 'retrieve' +frequent use is to store a fresh object. Functions that 'retrieve' objects such as gettupleitem() and dictlookup() also don't increment the reference count, since most frequently the object is only looked at -quickly. Thus, to retrieve an object and store it again, the caller +quickly. Thus, to retrieve an object and store it again, the caller must call INCREF() explicitly. NOTE: functions that 'consume' a reference count like dictinsert() even @@ -316,7 +316,7 @@ handling. It seems attractive to make other functions that take an object as argument consume a reference count; however this may quickly get -confusing (even the current practice is already confusing). Consider +confusing (even the current practice is already confusing). Consider it carefully, it may safe lots of calls to INCREF() and DECREF() at times. diff --git a/src/objimpl.h b/src/objimpl.h index 7d40718..1cf1849 100644 --- a/src/objimpl.h +++ b/src/objimpl.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -32,13 +32,13 @@ NEWOBJ(type, typeobj) allocates memory for a new object of the given type; here 'type' must be the C structure type used to represent the object and 'typeobj' the address of the corresponding type object. Reference count and type pointer are filled in; the rest of the bytes of -the object are *undefined*! The resulting expression type is 'type *'. +the object are *undefined*! The resulting expression type is 'type *'. The size of the object is actually determined by the tp_basicsize field of the type object. NEWVAROBJ(type, typeobj, n) is similar but allocates a variable-size -object with n extra items. The size is computer as tp_basicsize plus -n * tp_itemsize. This fills in the ob_size field as well. +object with n extra items. The size is computer as tp_basicsize plus +n * tp_itemsize. This fills in the ob_size field as well. */ extern object *newobject PROTO((typeobject *)); diff --git a/src/opcode.h b/src/opcode.h index ad6d712..b069e45 100644 --- a/src/opcode.h +++ b/src/opcode.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -24,84 +24,84 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* Instruction opcodes for compiled code */ -#define STOP_CODE 0 -#define POP_TOP 1 -#define ROT_TWO 2 -#define ROT_THREE 3 -#define DUP_TOP 4 - -#define UNARY_POSITIVE 10 -#define UNARY_NEGATIVE 11 -#define UNARY_NOT 12 -#define UNARY_CONVERT 13 -#define UNARY_CALL 14 - -#define BINARY_MULTIPLY 20 -#define BINARY_DIVIDE 21 -#define BINARY_MODULO 22 -#define BINARY_ADD 23 -#define BINARY_SUBTRACT 24 -#define BINARY_SUBSCR 25 -#define BINARY_CALL 26 - -#define SLICE 30 +#define STOP_CODE 0 +#define POP_TOP 1 +#define ROT_TWO 2 +#define ROT_THREE 3 +#define DUP_TOP 4 + +#define UNARY_POSITIVE 10 +#define UNARY_NEGATIVE 11 +#define UNARY_NOT 12 +#define UNARY_CONVERT 13 +#define UNARY_CALL 14 + +#define BINARY_MULTIPLY 20 +#define BINARY_DIVIDE 21 +#define BINARY_MODULO 22 +#define BINARY_ADD 23 +#define BINARY_SUBTRACT 24 +#define BINARY_SUBSCR 25 +#define BINARY_CALL 26 + +#define SLICE 30 /* Also uses 31-33 */ -#define STORE_SLICE 40 +#define STORE_SLICE 40 /* Also uses 41-43 */ -#define DELETE_SLICE 50 +#define DELETE_SLICE 50 /* Also uses 51-53 */ -#define STORE_SUBSCR 60 -#define DELETE_SUBSCR 61 - -#define PRINT_EXPR 70 -#define PRINT_ITEM 71 -#define PRINT_NEWLINE 72 - -#define BREAK_LOOP 80 -#define RAISE_EXCEPTION 81 -#define LOAD_LOCALS 82 -#define RETURN_VALUE 83 -#define REQUIRE_ARGS 84 -#define REFUSE_ARGS 85 -#define BUILD_FUNCTION 86 -#define POP_BLOCK 87 -#define END_FINALLY 88 -#define BUILD_CLASS 89 - -#define HAVE_ARGUMENT 90 /* Opcodes from here have an argument: */ - -#define STORE_NAME 90 /* Index in name list */ -#define DELETE_NAME 91 /* "" */ -#define UNPACK_TUPLE 92 /* Number of tuple items */ -#define UNPACK_LIST 93 /* Number of list items */ -/* unused: 94 */ -#define STORE_ATTR 95 /* Index in name list */ -#define DELETE_ATTR 96 /* "" */ - -#define LOAD_CONST 100 /* Index in const list */ -#define LOAD_NAME 101 /* Index in name list */ -#define BUILD_TUPLE 102 /* Number of tuple items */ -#define BUILD_LIST 103 /* Number of list items */ -#define BUILD_MAP 104 /* Always zero for now */ -#define LOAD_ATTR 105 /* Index in name list */ -#define COMPARE_OP 106 /* Comparison operator */ -#define IMPORT_NAME 107 /* Index in name list */ -#define IMPORT_FROM 108 /* Index in name list */ - -#define JUMP_FORWARD 110 /* Number of bytes to skip */ -#define JUMP_IF_FALSE 111 /* "" */ -#define JUMP_IF_TRUE 112 /* "" */ -#define JUMP_ABSOLUTE 113 /* Target byte offset from beginning of code */ -#define FOR_LOOP 114 /* Number of bytes to skip */ - -#define SETUP_LOOP 120 /* Target address (absolute) */ -#define SETUP_EXCEPT 121 /* "" */ -#define SETUP_FINALLY 122 /* "" */ - -#define SET_LINENO 127 /* Current line number */ +#define STORE_SUBSCR 60 +#define DELETE_SUBSCR 61 + +#define PRINT_EXPR 70 +#define PRINT_ITEM 71 +#define PRINT_NEWLINE 72 + +#define BREAK_LOOP 80 +#define RAISE_EXCEPTION 81 +#define LOAD_LOCALS 82 +#define RETURN_VALUE 83 +#define REQUIRE_ARGS 84 +#define REFUSE_ARGS 85 +#define BUILD_FUNCTION 86 +#define POP_BLOCK 87 +#define END_FINALLY 88 +#define BUILD_CLASS 89 + +#define HAVE_ARGUMENT 90 /* Opcodes from here have an argument: */ + +#define STORE_NAME 90 /* Index in name list */ +#define DELETE_NAME 91 /* "" */ +#define UNPACK_TUPLE 92 /* Number of tuple items */ +#define UNPACK_LIST 93 /* Number of list items */ +/* unused: 94 */ +#define STORE_ATTR 95 /* Index in name list */ +#define DELETE_ATTR 96 /* "" */ + +#define LOAD_CONST 100 /* Index in const list */ +#define LOAD_NAME 101 /* Index in name list */ +#define BUILD_TUPLE 102 /* Number of tuple items */ +#define BUILD_LIST 103 /* Number of list items */ +#define BUILD_MAP 104 /* Always zero for now */ +#define LOAD_ATTR 105 /* Index in name list */ +#define COMPARE_OP 106 /* Comparison operator */ +#define IMPORT_NAME 107 /* Index in name list */ +#define IMPORT_FROM 108 /* Index in name list */ + +#define JUMP_FORWARD 110 /* Number of bytes to skip */ +#define JUMP_IF_FALSE 111 /* "" */ +#define JUMP_IF_TRUE 112 /* "" */ +#define JUMP_ABSOLUTE 113 /* Target byte offset from beginning of code */ +#define FOR_LOOP 114 /* Number of bytes to skip */ + +#define SETUP_LOOP 120 /* Target address (absolute) */ +#define SETUP_EXCEPT 121 /* "" */ +#define SETUP_FINALLY 122 /* "" */ + +#define SET_LINENO 127 /* Current line number */ /* Comparison operator codes (argument to COMPARE_OP) */ enum cmp_op {LT, LE, EQ, NE, GT, GE, IN, NOT_IN, IS, IS_NOT, EXC_MATCH, BAD}; diff --git a/src/panelmodule.c b/src/panelmodule.c index 9edde6b..4bebb45 100644 --- a/src/panelmodule.c +++ b/src/panelmodule.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -23,13 +23,13 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ /* Panel module. - Interface to the NASA Ames "panel library" for the SGI Graphics Library - by David Tristram. - - NOTE: the panel library dumps core if you don't create a window before - calling pnl.mkpanel(). A call to gl.winopen() suffices. - If you don't want a window to be created, call gl.noport() before - gl.winopen(). + Interface to the NASA Ames "panel library" for the SGI Graphics Library + by David Tristram. + + NOTE: the panel library dumps core if you don't create a window before + calling pnl.mkpanel(). A call to gl.winopen() suffices. + If you don't want a window to be created, call gl.noport() before + gl.winopen(). */ #include <gl.h> @@ -43,9 +43,9 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* The offsetof() macro calculates the offset of a structure member - in its structure. Unfortunately this cannot be written down portably, - hence it is standardized by ANSI C. For pre-ANSI C compilers, - we give a version here that works usually (but watch out!): */ + in its structure. Unfortunately this cannot be written down portably, + hence it is standardized by ANSI C. For pre-ANSI C compilers, + we give a version here that works usually (but watch out!): */ #ifndef offsetof #define offsetof(type, member) ( (int) & ((type*)0) -> member ) @@ -55,9 +55,9 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* Panel objects */ typedef struct { - OB_HEAD - Panel *ob_panel; - object *ob_paneldict; + OB_HEAD + Panel *ob_panel; + object *ob_paneldict; } panelobject; extern typeobject Paneltype; /* Really static, forward */ @@ -68,8 +68,8 @@ extern typeobject Paneltype; /* Really static, forward */ /* Actuator objects */ typedef struct { - OB_HEAD - Actuator *ob_actuator; + OB_HEAD + Actuator *ob_actuator; } actuatorobject; extern typeobject Actuatortype; /* Really static, forward */ @@ -80,162 +80,162 @@ static object *newactuatorobject(); /* Forward */ /* Since we allow different types of members than the functions from - structmember.c, the memberlist stuff is replicated here. - (Historically, it originated in this file and later became a generic - feature.) */ + structmember.c, the memberlist stuff is replicated here. + (Historically, it originated in this file and later became a generic + feature.) */ /* An array of memberlist structures defines the name, type and offset - of selected members of a C structure. These can be read by - panel_getmember() and set by panel_setmember() (except if their - READONLY flag is set). The array must be terminated with an entry - whose name pointer is NULL. */ + of selected members of a C structure. These can be read by + panel_getmember() and set by panel_setmember() (except if their + READONLY flag is set). The array must be terminated with an entry + whose name pointer is NULL. */ struct memberlist { - char *name; - int type; - int offset; - int readonly; + char *name; + int type; + int offset; + int readonly; }; /* Types */ -#define T_SHORT 0 -#define T_DEVICE T_SHORT -#define T_LONG 1 -#define T_INT T_LONG -#define T_BOOL T_LONG -#define T_FLOAT 2 -#define T_COORD T_FLOAT -#define T_STRING 3 -#define T_FUNC 4 -#define T_ACTUATOR 5 +#define T_SHORT 0 +#define T_DEVICE T_SHORT +#define T_LONG 1 +#define T_INT T_LONG +#define T_BOOL T_LONG +#define T_FLOAT 2 +#define T_COORD T_FLOAT +#define T_STRING 3 +#define T_FUNC 4 +#define T_ACTUATOR 5 /* Readonly flag */ -#define READONLY 1 -#define RO READONLY /* Shorthand */ +#define READONLY 1 +#define RO READONLY /* Shorthand */ static object * panel_getmember(addr, mlist, name) - char *addr; - struct memberlist *mlist; - char *name; + char *addr; + struct memberlist *mlist; + char *name; { - object *v; - register struct memberlist *l; - - for (l = mlist; l->name != NULL; l++) { - if (strcmp(l->name, name) == 0) { - addr += l->offset; - switch (l->type) { - case T_SHORT: - v = newintobject((long) *(short*)addr); - break; - case T_LONG: - v = newintobject(*(long*)addr); - break; - case T_FLOAT: - v = newfloatobject(*(float*)addr); - break; - case T_STRING: - if (*(char**)addr == NULL) { - INCREF(None); - v = None; - } - else - v = newstringobject(*(char**)addr); - break; - case T_ACTUATOR: - v = newactuatorobject(*(Actuator**)addr); - break; - default: - err_badarg(); - v = NULL; - } - return v; - } - } - err_setstr(NameError, name); - return NULL; + object *v; + register struct memberlist *l; + + for (l = mlist; l->name != NULL; l++) { + if (strcmp(l->name, name) == 0) { + addr += l->offset; + switch (l->type) { + case T_SHORT: + v = newintobject((long) *(short*)addr); + break; + case T_LONG: + v = newintobject(*(long*)addr); + break; + case T_FLOAT: + v = newfloatobject(*(float*)addr); + break; + case T_STRING: + if (*(char**)addr == NULL) { + INCREF(None); + v = None; + } + else + v = newstringobject(*(char**)addr); + break; + case T_ACTUATOR: + v = newactuatorobject(*(Actuator**)addr); + break; + default: + err_badarg(); + v = NULL; + } + return v; + } + } + err_setstr(NameError, name); + return NULL; } -/* Attempt to set a member. Return: 0 if OK; 1 if not found; -1 if error */ +/* Attempt to set a member. Return: 0 if OK; 1 if not found; -1 if error */ static int panel_setmember(addr, mlist, name, v) - char *addr; - struct memberlist *mlist; - char *name; - object *v; + char *addr; + struct memberlist *mlist; + char *name; + object *v; { - register struct memberlist *l; - - for (l = mlist; l->name != NULL; l++) { - if (strcmp(l->name, name) == 0) { - if (l->readonly) { - err_setstr(TypeError, "read-only member"); - return -1; - } - addr += l->offset; - switch (l->type) { - case T_SHORT: - if (!is_intobject(v)) { - err_setstr(TypeError, "int expected"); - return -1; - } - *(short*)addr = getintvalue(v); - break; - case T_LONG: - if (!is_intobject(v)) { - err_setstr(TypeError, "int expected"); - return -1; - } - *(long*)addr = getintvalue(v); - break; - case T_FLOAT: - if (is_intobject(v)) - *(float*)addr = getintvalue(v); - else if (is_floatobject(v)) - *(float*)addr = getfloatvalue(v); - else { - err_setstr(TypeError,"float expected"); - return -1; - } - break; - case T_STRING: - /* XXX Should free(*(char**)addr) here - but it's dangerous since we don't know - if we set the label ourselves */ - if (v == None) - *(char**)addr = NULL; - else if (!is_stringobject(v)) { - err_setstr(TypeError, - "string expected"); - return -1; - } - else - *(char**)addr = - strdup(getstringvalue(v)); - break; - case T_ACTUATOR: - if (v == None) - *(Actuator**)addr = NULL; - else if (!is_actuatorobject(v)) { - err_setstr(TypeError, - "actuator expected"); - return -1; - } - else - *(Actuator**)addr = - ((actuatorobject *)v)->ob_actuator; - break; - default: - err_setstr(SystemError, "unknown member type"); - return -1; - } - return 0; /* Found it */ - } - } - - return 1; /* Not found */ + register struct memberlist *l; + + for (l = mlist; l->name != NULL; l++) { + if (strcmp(l->name, name) == 0) { + if (l->readonly) { + err_setstr(TypeError, "read-only member"); + return -1; + } + addr += l->offset; + switch (l->type) { + case T_SHORT: + if (!is_intobject(v)) { + err_setstr(TypeError, "int expected"); + return -1; + } + *(short*)addr = getintvalue(v); + break; + case T_LONG: + if (!is_intobject(v)) { + err_setstr(TypeError, "int expected"); + return -1; + } + *(long*)addr = getintvalue(v); + break; + case T_FLOAT: + if (is_intobject(v)) + *(float*)addr = getintvalue(v); + else if (is_floatobject(v)) + *(float*)addr = getfloatvalue(v); + else { + err_setstr(TypeError,"float expected"); + return -1; + } + break; + case T_STRING: + /* XXX Should free(*(char**)addr) here + but it's dangerous since we don't know + if we set the label ourselves */ + if (v == None) + *(char**)addr = NULL; + else if (!is_stringobject(v)) { + err_setstr(TypeError, + "string expected"); + return -1; + } + else + *(char**)addr = + strdup(getstringvalue(v)); + break; + case T_ACTUATOR: + if (v == None) + *(Actuator**)addr = NULL; + else if (!is_actuatorobject(v)) { + err_setstr(TypeError, + "actuator expected"); + return -1; + } + else + *(Actuator**)addr = + ((actuatorobject *)v)->ob_actuator; + break; + default: + err_setstr(SystemError, "unknown member type"); + return -1; + } + return 0; /* Found it */ + } + } + + return 1; /* Not found */ } @@ -243,84 +243,84 @@ panel_setmember(addr, mlist, name, v) static object * panel_addpanel(self, args) - panelobject *self; - object *args; + panelobject *self; + object *args; { - if (!getnoarg(args)) - return NULL; - pnl_addpanel(self->ob_panel); - INCREF(None); - return None; + if (!getnoarg(args)) + return NULL; + pnl_addpanel(self->ob_panel); + INCREF(None); + return None; } static object * panel_endgroup(self, args) - panelobject *self; - object *args; + panelobject *self; + object *args; { - if (!getnoarg(args)) - return NULL; - pnl_endgroup(self->ob_panel); - INCREF(None); - return None; + if (!getnoarg(args)) + return NULL; + pnl_endgroup(self->ob_panel); + INCREF(None); + return None; } static object * panel_fixpanel(self, args) - panelobject *self; - object *args; + panelobject *self; + object *args; { - if (!getnoarg(args)) - return NULL; - pnl_fixpanel(self->ob_panel); - INCREF(None); - return None; + if (!getnoarg(args)) + return NULL; + pnl_fixpanel(self->ob_panel); + INCREF(None); + return None; } static object * panel_strwidth(self, args) - panelobject *self; - object *args; + panelobject *self; + object *args; { - object *v; - double width; - if (!getstrarg(args, &v)) - return NULL; - width = pnl_strwidth(self->ob_panel, getstringvalue(v)); - return newfloatobject(width); + object *v; + double width; + if (!getstrarg(args, &v)) + return NULL; + width = pnl_strwidth(self->ob_panel, getstringvalue(v)); + return newfloatobject(width); } static struct methodlist panel_methods[] = { - {"addpanel", panel_addpanel}, - {"endgroup", panel_endgroup}, - {"fixpanel", panel_fixpanel}, - {"strwidth", panel_strwidth}, - {NULL, NULL} /* sentinel */ + {"addpanel", panel_addpanel}, + {"endgroup", panel_endgroup}, + {"fixpanel", panel_fixpanel}, + {"strwidth", panel_strwidth}, + {NULL, NULL} /* sentinel */ }; static object * newpanelobject() { - panelobject *p; - p = NEWOBJ(panelobject, &Paneltype); - if (p == NULL) - return NULL; - p->ob_panel = pnl_mkpanel(); - if ((p->ob_paneldict = newdictobject()) == NULL) { - DECREF(p); - return NULL; - } - return (object *)p; + panelobject *p; + p = NEWOBJ(panelobject, &Paneltype); + if (p == NULL) + return NULL; + p->ob_panel = pnl_mkpanel(); + if ((p->ob_paneldict = newdictobject()) == NULL) { + DECREF(p); + return NULL; + } + return (object *)p; } static void panel_dealloc(p) - panelobject *p; + panelobject *p; { - pnl_delpanel(p->ob_panel); - if (p->ob_paneldict != NULL) - DECREF(p->ob_paneldict); - DEL(p); + pnl_delpanel(p->ob_panel); + if (p->ob_paneldict != NULL) + DECREF(p->ob_paneldict); + DEL(p); } @@ -329,285 +329,285 @@ panel_dealloc(p) #define PANOFF(member) offsetof(Panel, member) static struct memberlist panel_memberlist[] = { - {"id", T_SHORT, PANOFF(id), READONLY}, - {"a", T_ACTUATOR, PANOFF(a), READONLY}, - {"al", T_ACTUATOR, PANOFF(al), READONLY}, - {"lastgroup", T_ACTUATOR, PANOFF(lastgroup), READONLY}, - - {"active", T_BOOL, PANOFF(active)}, - {"selectable", T_BOOL, PANOFF(selectable)}, - - {"x", T_LONG, PANOFF(x)}, - {"y", T_LONG, PANOFF(y)}, - {"w", T_LONG, PANOFF(w)}, - {"h", T_LONG, PANOFF(h)}, - - {"minx", T_COORD, PANOFF(minx)}, - {"maxx", T_COORD, PANOFF(maxx)}, - {"miny", T_COORD, PANOFF(miny)}, - {"maxy", T_COORD, PANOFF(maxy)}, - - {"cw", T_COORD, PANOFF(cw)}, - {"ch", T_COORD, PANOFF(ch)}, - - {"gid", T_LONG, PANOFF(gid), READONLY}, - {"usergid", T_LONG, PANOFF(usergid), READONLY}, - - {"vobj", T_LONG, PANOFF(vobj), READONLY}, - {"ppu", T_FLOAT, PANOFF(ppu)}, - - {"label", T_STRING, PANOFF(label)}, - - /* Panel callbacks are not supported */ - - {"visible", T_BOOL, PANOFF(visible)}, - {"somedirty", T_INT, PANOFF(somedirty)}, - {"dirtycnt", T_INT, PANOFF(dirtycnt)}, - - /* T_PANEL is not supported */ - /* - {"next", T_PANEL, PANOFF(next), READONLY}, - */ - - {NULL, 0, 0} /* Sentinel */ + {"id", T_SHORT, PANOFF(id), READONLY}, + {"a", T_ACTUATOR, PANOFF(a), READONLY}, + {"al", T_ACTUATOR, PANOFF(al), READONLY}, + {"lastgroup", T_ACTUATOR, PANOFF(lastgroup), READONLY}, + + {"active", T_BOOL, PANOFF(active)}, + {"selectable", T_BOOL, PANOFF(selectable)}, + + {"x", T_LONG, PANOFF(x)}, + {"y", T_LONG, PANOFF(y)}, + {"w", T_LONG, PANOFF(w)}, + {"h", T_LONG, PANOFF(h)}, + + {"minx", T_COORD, PANOFF(minx)}, + {"maxx", T_COORD, PANOFF(maxx)}, + {"miny", T_COORD, PANOFF(miny)}, + {"maxy", T_COORD, PANOFF(maxy)}, + + {"cw", T_COORD, PANOFF(cw)}, + {"ch", T_COORD, PANOFF(ch)}, + + {"gid", T_LONG, PANOFF(gid), READONLY}, + {"usergid", T_LONG, PANOFF(usergid), READONLY}, + + {"vobj", T_LONG, PANOFF(vobj), READONLY}, + {"ppu", T_FLOAT, PANOFF(ppu)}, + + {"label", T_STRING, PANOFF(label)}, + + /* Panel callbacks are not supported */ + + {"visible", T_BOOL, PANOFF(visible)}, + {"somedirty", T_INT, PANOFF(somedirty)}, + {"dirtycnt", T_INT, PANOFF(dirtycnt)}, + + /* T_PANEL is not supported */ + /* + {"next", T_PANEL, PANOFF(next), READONLY}, + */ + + {NULL, 0, 0} /* Sentinel */ }; static object * panel_getattr(p, name) - panelobject *p; - char *name; + panelobject *p; + char *name; { - object *v; - - v = dictlookup(p->ob_paneldict, name); - if (v != NULL) { - INCREF(v); - return v; - } - - v = findmethod(panel_methods, (object *)p, name); - if (v != NULL) - return v; - err_clear(); - return panel_getmember((char *)p->ob_panel, panel_memberlist, name); + object *v; + + v = dictlookup(p->ob_paneldict, name); + if (v != NULL) { + INCREF(v); + return v; + } + + v = findmethod(panel_methods, (object *)p, name); + if (v != NULL) + return v; + err_clear(); + return panel_getmember((char *)p->ob_panel, panel_memberlist, name); } static int panel_setattr(p, name, v) - panelobject *p; - char *name; - object *v; + panelobject *p; + char *name; + object *v; { - int err; - - /* We don't allow deletion of attributes */ - if (v == NULL) { - err_setstr(TypeError, "read-only panel attribute"); - return -1; - } - err = panel_setmember((char *)p->ob_panel, panel_memberlist, name, v); - if (err != 1) - return err; - return dictinsert(p->ob_paneldict, name, v); + int err; + + /* We don't allow deletion of attributes */ + if (v == NULL) { + err_setstr(TypeError, "read-only panel attribute"); + return -1; + } + err = panel_setmember((char *)p->ob_panel, panel_memberlist, name, v); + if (err != 1) + return err; + return dictinsert(p->ob_paneldict, name, v); } static typeobject Paneltype = { - OB_HEAD_INIT(&Typetype) - 0, /*ob_size*/ - "panel", /*tp_name*/ - sizeof(panelobject), /*tp_size*/ - 0, /*tp_itemsize*/ - /* methods */ - panel_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - panel_getattr, /*tp_getattr*/ - panel_setattr, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ + OB_HEAD_INIT(&Typetype) + 0, /*ob_size*/ + "panel", /*tp_name*/ + sizeof(panelobject), /*tp_size*/ + 0, /*tp_itemsize*/ + /* methods */ + panel_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + panel_getattr, /*tp_getattr*/ + panel_setattr, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ }; /* Descriptions of actuator-specific data members */ struct memberlist slider_spec[] = { - {"mode", T_INT, offsetof(Slider, mode)}, - {"finefactor", T_FLOAT, offsetof(Slider, finefactor)}, - {"differentialfactor", - T_FLOAT, offsetof(Slider, differentialfactor)}, - {"valsave", T_FLOAT, offsetof(Slider, valsave), RO}, - {"wsave", T_COORD, offsetof(Slider, wsave)}, - {"bh", T_COORD, offsetof(Slider, bh)}, - {NULL} + {"mode", T_INT, offsetof(Slider, mode)}, + {"finefactor", T_FLOAT, offsetof(Slider, finefactor)}, + {"differentialfactor", + T_FLOAT, offsetof(Slider, differentialfactor)}, + {"valsave", T_FLOAT, offsetof(Slider, valsave), RO}, + {"wsave", T_COORD, offsetof(Slider, wsave)}, + {"bh", T_COORD, offsetof(Slider, bh)}, + {NULL} }; #define palette_spec slider_spec struct memberlist puck_spec[] = { - /* Actuators already have members x and y, so the Puck's x and y - have different names */ - {"puck_x", T_FLOAT, offsetof(Puck, x)}, - {"puck_y", T_FLOAT, offsetof(Puck, y)}, - {NULL} + /* Actuators already have members x and y, so the Puck's x and y + have different names */ + {"puck_x", T_FLOAT, offsetof(Puck, x)}, + {"puck_y", T_FLOAT, offsetof(Puck, y)}, + {NULL} }; struct memberlist dial_spec[] = { - {"mode", T_INT, offsetof(Dial, mode)}, - {"finefactor", T_FLOAT, offsetof(Dial, finefactor)}, - {"valsave", T_FLOAT, offsetof(Dial, valsave), RO}, - {"wsave", T_COORD, offsetof(Dial, wsave)}, - {"winds", T_FLOAT, offsetof(Dial, winds)}, - {NULL} + {"mode", T_INT, offsetof(Dial, mode)}, + {"finefactor", T_FLOAT, offsetof(Dial, finefactor)}, + {"valsave", T_FLOAT, offsetof(Dial, valsave), RO}, + {"wsave", T_COORD, offsetof(Dial, wsave)}, + {"winds", T_FLOAT, offsetof(Dial, winds)}, + {NULL} }; struct memberlist slideroid_spec[] = { - {"mode", T_INT, offsetof(Slideroid, mode)}, - {"finemode", T_BOOL, offsetof(Slideroid, finemode)}, - {"resetmode", T_BOOL, offsetof(Slideroid, resetmode)}, - /* XXX Can't do resettarget (pointer to float) */ - /* XXX This makes resetval pretty useless... */ - /* - {"resetval", T_FLOAT, offsetof(Slideroid, resetval)}, - */ - {"valsave", T_FLOAT, offsetof(Slideroid, valsave), RO}, - {"wsave", T_COORD, offsetof(Slideroid, wsave)}, - {NULL} + {"mode", T_INT, offsetof(Slideroid, mode)}, + {"finemode", T_BOOL, offsetof(Slideroid, finemode)}, + {"resetmode", T_BOOL, offsetof(Slideroid, resetmode)}, + /* XXX Can't do resettarget (pointer to float) */ + /* XXX This makes resetval pretty useless... */ + /* + {"resetval", T_FLOAT, offsetof(Slideroid, resetval)}, + */ + {"valsave", T_FLOAT, offsetof(Slideroid, valsave), RO}, + {"wsave", T_COORD, offsetof(Slideroid, wsave)}, + {NULL} }; struct memberlist stripchart_spec[] = { - {"firstpt", T_INT, offsetof(Stripchart, firstpt), RO}, - {"lastpt", T_INT, offsetof(Stripchart, lastpt), RO}, - {"Bind_Low", T_BOOL, offsetof(Stripchart, Bind_Low)}, - {"Bind_High", T_BOOL, offsetof(Stripchart, Bind_High)}, - /* XXX Can't do y (array of floats) */ - {"lowlabel", T_ACTUATOR, offsetof(Stripchart, lowlabel), RO}, - {"highlabel", T_ACTUATOR, offsetof(Stripchart, highlabel), RO}, - {NULL} + {"firstpt", T_INT, offsetof(Stripchart, firstpt), RO}, + {"lastpt", T_INT, offsetof(Stripchart, lastpt), RO}, + {"Bind_Low", T_BOOL, offsetof(Stripchart, Bind_Low)}, + {"Bind_High", T_BOOL, offsetof(Stripchart, Bind_High)}, + /* XXX Can't do y (array of floats) */ + {"lowlabel", T_ACTUATOR, offsetof(Stripchart, lowlabel), RO}, + {"highlabel", T_ACTUATOR, offsetof(Stripchart, highlabel), RO}, + {NULL} }; struct memberlist typein_spec[] = { - /* Note: these should be readonly after the actuator is added - to a panel */ - {"str", T_STRING, offsetof(Typein, str)}, - {"len", T_INT, offsetof(Typein, len)}, - {NULL} + /* Note: these should be readonly after the actuator is added + to a panel */ + {"str", T_STRING, offsetof(Typein, str)}, + {"len", T_INT, offsetof(Typein, len)}, + {NULL} }; struct memberlist typeout_spec[] = { - {"mode", T_INT, offsetof(Typeout, mode)}, - /* XXX The buffer is managed by the actuator; but how do we - add text? */ - {"buf", T_STRING, offsetof(Typeout, buf), READONLY}, - {"delimstr", T_STRING, offsetof(Typeout, delimstr)}, - {"start", T_INT, offsetof(Typeout, start)}, - {"dot", T_INT, offsetof(Typeout, dot)}, - {"mark", T_INT, offsetof(Typeout, mark)}, - {"col", T_INT, offsetof(Typeout, col)}, - {"lin", T_INT, offsetof(Typeout, lin)}, - {"len", T_INT, offsetof(Typeout, len)}, - {"size", T_INT, offsetof(Typeout, size)}, - {NULL} + {"mode", T_INT, offsetof(Typeout, mode)}, + /* XXX The buffer is managed by the actuator; but how do we + add text? */ + {"buf", T_STRING, offsetof(Typeout, buf), READONLY}, + {"delimstr", T_STRING, offsetof(Typeout, delimstr)}, + {"start", T_INT, offsetof(Typeout, start)}, + {"dot", T_INT, offsetof(Typeout, dot)}, + {"mark", T_INT, offsetof(Typeout, mark)}, + {"col", T_INT, offsetof(Typeout, col)}, + {"lin", T_INT, offsetof(Typeout, lin)}, + {"len", T_INT, offsetof(Typeout, len)}, + {"size", T_INT, offsetof(Typeout, size)}, + {NULL} }; struct memberlist mouse_spec[] = { - /* Actuators already have members x and y, so the Mouse's x and y - have different names */ - {"mouse_x", T_FLOAT, offsetof(Mouse, x)}, - {"mouse_y", T_FLOAT, offsetof(Mouse, y)}, - {NULL} + /* Actuators already have members x and y, so the Mouse's x and y + have different names */ + {"mouse_x", T_FLOAT, offsetof(Mouse, x)}, + {"mouse_y", T_FLOAT, offsetof(Mouse, y)}, + {NULL} }; -#define MULOFF(member) offsetof(Multislider, member) +#define MULOFF(member) offsetof(Multislider, member) struct memberlist multislider_spec[] = { - {"mode", T_INT, MULOFF(mode)}, - {"n", T_INT, MULOFF(n)}, - {"finefactor", T_FLOAT, MULOFF(finefactor)}, - {"wsave", T_COORD, MULOFF(wsave)}, - {"sa", T_ACTUATOR, MULOFF(sa)}, - {"bh", T_COORD, MULOFF(bh)}, - {"clrx", T_COORD, MULOFF(clrx)}, - {"clry", T_COORD, MULOFF(clry)}, - {"clrw", T_COORD, MULOFF(clrw)}, - {"clrh", T_COORD, MULOFF(clrh)}, - /* XXX acttype? */ - {NULL} + {"mode", T_INT, MULOFF(mode)}, + {"n", T_INT, MULOFF(n)}, + {"finefactor", T_FLOAT, MULOFF(finefactor)}, + {"wsave", T_COORD, MULOFF(wsave)}, + {"sa", T_ACTUATOR, MULOFF(sa)}, + {"bh", T_COORD, MULOFF(bh)}, + {"clrx", T_COORD, MULOFF(clrx)}, + {"clry", T_COORD, MULOFF(clry)}, + {"clrw", T_COORD, MULOFF(clrw)}, + {"clrh", T_COORD, MULOFF(clrh)}, + /* XXX acttype? */ + {NULL} }; /* XXX Still to do: - Frame - Icon - Cycle - Scroll - Menu + Frame + Icon + Cycle + Scroll + Menu */ /* List of known actuator initializer functions */ struct { - char *name; - void (*func)(); - struct memberlist *spec; + char *name; + void (*func)(); + struct memberlist *spec; } initializerlist[] = { - {"analog_bar", pnl_analog_bar}, - {"analog_meter", pnl_analog_meter}, - {"button", pnl_button}, - {"cycle", pnl_cycle}, - /* Doesn't exist: */ -/* {"dhslider", pnl_dhslider, slider_spec}, */ - {"dial", pnl_dial, dial_spec}, - {"down_arrow_button", pnl_down_arrow_button}, - {"down_double_arrow_button", pnl_down_double_arrow_button}, - {"dvslider", pnl_dvslider, slider_spec}, - {"filled_hslider", pnl_filled_hslider, slider_spec}, - {"filled_slider", pnl_filled_slider, slider_spec}, - {"filled_vslider", pnl_filled_vslider, slider_spec}, - {"floating_puck", pnl_floating_puck, puck_spec}, - {"frame", pnl_frame}, - {"graphframe", pnl_graphframe}, - {"hmultislider", pnl_hmultislider, multislider_spec}, - {"hmultislider_bar", pnl_hmultislider_bar}, - {"hmultislider_open_bar", pnl_hmultislider_open_bar}, - {"hpalette", pnl_hpalette, palette_spec}, - {"hslider", pnl_hslider, slider_spec}, - {"icon", pnl_icon}, - {"icon_menu", pnl_icon_menu}, - {"label", pnl_label}, - {"left_arrow_button", pnl_left_arrow_button}, - {"left_double_arrow_button", pnl_left_double_arrow_button}, - {"menu", pnl_menu}, - {"menu_item", pnl_menu_item}, - {"meter", pnl_meter}, - {"mouse", pnl_mouse, mouse_spec}, - {"multislider", pnl_multislider, multislider_spec}, - {"multislider_bar", pnl_multislider_bar}, - {"multislider_open_bar", pnl_multislider_open_bar}, - {"palette", pnl_palette, palette_spec}, - {"puck", pnl_puck, puck_spec}, - {"radio_button", pnl_radio_button}, - {"radio_check_button", pnl_radio_check_button}, - {"right_arrow_button", pnl_right_arrow_button}, - {"right_double_arrow_button", pnl_right_double_arrow_button}, - {"rubber_puck", pnl_rubber_puck, puck_spec}, - {"scale_chart", pnl_scale_chart, stripchart_spec}, - {"scroll", pnl_scroll}, - {"signal", pnl_signal}, - {"slider", pnl_slider, slider_spec}, - {"slideroid", pnl_slideroid, slideroid_spec}, - {"strip_chart", pnl_strip_chart, stripchart_spec}, - {"sub_menu", pnl_sub_menu}, - {"toggle_button", pnl_toggle_button}, - {"typein", pnl_typein, typein_spec}, - {"typeout", pnl_typeout, typeout_spec}, - {"up_arrow_button", pnl_up_arrow_button}, - {"up_double_arrow_button", pnl_up_double_arrow_button}, - {"viewframe", pnl_viewframe}, - {"vmultislider", pnl_vmultislider, multislider_spec}, - {"vmultislider_bar", pnl_vmultislider_bar}, - {"vmultislider_open_bar", pnl_vmultislider_open_bar}, - {"vpalette", pnl_vpalette, palette_spec}, - {"vslider", pnl_vslider, slider_spec}, - {"wide_button", pnl_wide_button}, - {NULL, NULL} /* Sentinel */ + {"analog_bar", pnl_analog_bar}, + {"analog_meter", pnl_analog_meter}, + {"button", pnl_button}, + {"cycle", pnl_cycle}, + /* Doesn't exist: */ +/* {"dhslider", pnl_dhslider, slider_spec}, */ + {"dial", pnl_dial, dial_spec}, + {"down_arrow_button", pnl_down_arrow_button}, + {"down_double_arrow_button", pnl_down_double_arrow_button}, + {"dvslider", pnl_dvslider, slider_spec}, + {"filled_hslider", pnl_filled_hslider, slider_spec}, + {"filled_slider", pnl_filled_slider, slider_spec}, + {"filled_vslider", pnl_filled_vslider, slider_spec}, + {"floating_puck", pnl_floating_puck, puck_spec}, + {"frame", pnl_frame}, + {"graphframe", pnl_graphframe}, + {"hmultislider", pnl_hmultislider, multislider_spec}, + {"hmultislider_bar", pnl_hmultislider_bar}, + {"hmultislider_open_bar", pnl_hmultislider_open_bar}, + {"hpalette", pnl_hpalette, palette_spec}, + {"hslider", pnl_hslider, slider_spec}, + {"icon", pnl_icon}, + {"icon_menu", pnl_icon_menu}, + {"label", pnl_label}, + {"left_arrow_button", pnl_left_arrow_button}, + {"left_double_arrow_button", pnl_left_double_arrow_button}, + {"menu", pnl_menu}, + {"menu_item", pnl_menu_item}, + {"meter", pnl_meter}, + {"mouse", pnl_mouse, mouse_spec}, + {"multislider", pnl_multislider, multislider_spec}, + {"multislider_bar", pnl_multislider_bar}, + {"multislider_open_bar", pnl_multislider_open_bar}, + {"palette", pnl_palette, palette_spec}, + {"puck", pnl_puck, puck_spec}, + {"radio_button", pnl_radio_button}, + {"radio_check_button", pnl_radio_check_button}, + {"right_arrow_button", pnl_right_arrow_button}, + {"right_double_arrow_button", pnl_right_double_arrow_button}, + {"rubber_puck", pnl_rubber_puck, puck_spec}, + {"scale_chart", pnl_scale_chart, stripchart_spec}, + {"scroll", pnl_scroll}, + {"signal", pnl_signal}, + {"slider", pnl_slider, slider_spec}, + {"slideroid", pnl_slideroid, slideroid_spec}, + {"strip_chart", pnl_strip_chart, stripchart_spec}, + {"sub_menu", pnl_sub_menu}, + {"toggle_button", pnl_toggle_button}, + {"typein", pnl_typein, typein_spec}, + {"typeout", pnl_typeout, typeout_spec}, + {"up_arrow_button", pnl_up_arrow_button}, + {"up_double_arrow_button", pnl_up_double_arrow_button}, + {"viewframe", pnl_viewframe}, + {"vmultislider", pnl_vmultislider, multislider_spec}, + {"vmultislider_bar", pnl_vmultislider_bar}, + {"vmultislider_open_bar", pnl_vmultislider_open_bar}, + {"vpalette", pnl_vpalette, palette_spec}, + {"vslider", pnl_vslider, slider_spec}, + {"wide_button", pnl_wide_button}, + {NULL, NULL} /* Sentinel */ }; @@ -617,34 +617,34 @@ static Actuator *down_pend, *active_pend, *up_pend; static void downfunc(a) - Actuator *a; + Actuator *a; { - if (down_pend == NULL) - down_pend = a; + if (down_pend == NULL) + down_pend = a; } static void activefunc(a) - Actuator *a; + Actuator *a; { - if (active_pend == NULL) - active_pend = a; + if (active_pend == NULL) + active_pend = a; } static void upfunc(a) - Actuator *a; + Actuator *a; { - if (up_pend == NULL) - up_pend = a; + if (up_pend == NULL) + up_pend = a; } /* Lay-out for the user data */ struct userdata { - object *dict; /* Dictionary object for additional attributes */ - struct memberlist *spec; /* Actuator-specific members */ + object *dict; /* Dictionary object for additional attributes */ + struct memberlist *spec; /* Actuator-specific members */ }; @@ -652,35 +652,35 @@ struct userdata { static Actuator * makeactuator(name) - char *name; + char *name; { - Actuator *act; - void (*initializer)() = NULL; - int i; - struct userdata *u; - for (i = 0; initializerlist[i].name != NULL; i++) { - if (strcmp(initializerlist[i].name, name) == 0) { - initializer = initializerlist[i].func; - break; - } - } - if (initializerlist[i].name == NULL) { - err_badarg(); - return NULL; - } - u = NEW(struct userdata, 1); - if (u == NULL) { - err_nomem(); - return NULL; - } - u->dict = NULL; - u->spec = initializerlist[i].spec; - act = pnl_mkact(initializer); - act->u = (char *)u; - act->downfunc = downfunc; - act->activefunc = activefunc; - act->upfunc = upfunc; - return act; + Actuator *act; + void (*initializer)() = NULL; + int i; + struct userdata *u; + for (i = 0; initializerlist[i].name != NULL; i++) { + if (strcmp(initializerlist[i].name, name) == 0) { + initializer = initializerlist[i].func; + break; + } + } + if (initializerlist[i].name == NULL) { + err_badarg(); + return NULL; + } + u = NEW(struct userdata, 1); + if (u == NULL) { + err_nomem(); + return NULL; + } + u->dict = NULL; + u->spec = initializerlist[i].spec; + act = pnl_mkact(initializer); + act->u = (char *)u; + act->downfunc = downfunc; + act->activefunc = activefunc; + act->upfunc = upfunc; + return act; } @@ -688,114 +688,114 @@ makeactuator(name) static object * actuator_addact(self, args) - actuatorobject *self; - object *args; + actuatorobject *self; + object *args; { - Panel *p; - if (!is_panelobject(args)) { - err_badarg(); - return NULL; - } - p = ((panelobject *)args) -> ob_panel; - pnl_addact(self->ob_actuator, p); - INCREF(None); - return None; + Panel *p; + if (!is_panelobject(args)) { + err_badarg(); + return NULL; + } + p = ((panelobject *)args) -> ob_panel; + pnl_addact(self->ob_actuator, p); + INCREF(None); + return None; } static object * actuator_addsubact(self, args) - actuatorobject *self; - object *args; + actuatorobject *self; + object *args; { - Actuator *a; - if (!is_actuatorobject(args)) { - err_badarg(); - return NULL; - } - a = ((actuatorobject *)args) -> ob_actuator; - pnl_addsubact(self->ob_actuator, a); - INCREF(None); - return None; + Actuator *a; + if (!is_actuatorobject(args)) { + err_badarg(); + return NULL; + } + a = ((actuatorobject *)args) -> ob_actuator; + pnl_addsubact(self->ob_actuator, a); + INCREF(None); + return None; } static object * actuator_delact(self, args) - actuatorobject *self; - object *args; + actuatorobject *self; + object *args; { - Panel *p; - if (!getnoarg(args)) - return NULL; - pnl_delact(self->ob_actuator); - INCREF(None); - return None; + Panel *p; + if (!getnoarg(args)) + return NULL; + pnl_delact(self->ob_actuator); + INCREF(None); + return None; } static object * actuator_fixact(self, args) - actuatorobject *self; - object *args; + actuatorobject *self; + object *args; { - Panel *p; - if (!getnoarg(args)) - return NULL; - pnl_fixact(self->ob_actuator); - INCREF(None); - return None; + Panel *p; + if (!getnoarg(args)) + return NULL; + pnl_fixact(self->ob_actuator); + INCREF(None); + return None; } static object * actuator_tprint(self, args) - actuatorobject *self; - object *args; + actuatorobject *self; + object *args; { - object *str; - if (self->ob_actuator->type != PNL_TYPEOUT) { - err_setstr(TypeError, "tprint for non-typeout panel"); - return NULL; - } - if (!getstrarg(args, &str)) - return NULL; - tprint(self->ob_actuator, getstringvalue(str)); - /* XXX Can't turn tprint's errors into exceptions, sorry */ - INCREF(None); - return None; + object *str; + if (self->ob_actuator->type != PNL_TYPEOUT) { + err_setstr(TypeError, "tprint for non-typeout panel"); + return NULL; + } + if (!getstrarg(args, &str)) + return NULL; + tprint(self->ob_actuator, getstringvalue(str)); + /* XXX Can't turn tprint's errors into exceptions, sorry */ + INCREF(None); + return None; } static struct methodlist actuator_methods[] = { - {"addact", actuator_addact}, - {"addsubact", actuator_addsubact}, - {"delact", actuator_delact}, - {"fixact", actuator_fixact}, - {"tprint", actuator_tprint}, - {NULL, NULL} /* sentinel */ + {"addact", actuator_addact}, + {"addsubact", actuator_addsubact}, + {"delact", actuator_delact}, + {"fixact", actuator_fixact}, + {"tprint", actuator_tprint}, + {NULL, NULL} /* sentinel */ }; static object * newactuatorobject(act) - Actuator *act; + Actuator *act; { - actuatorobject *a; - if (act == NULL) { - INCREF(None); - return None; - } - a = NEWOBJ(actuatorobject, &Actuatortype); - if (a == NULL) - return NULL; - a->ob_actuator = act; - return (object *)a; + actuatorobject *a; + if (act == NULL) { + INCREF(None); + return None; + } + a = NEWOBJ(actuatorobject, &Actuatortype); + if (a == NULL) + return NULL; + a->ob_actuator = act; + return (object *)a; } static void actuator_dealloc(a) - actuatorobject *a; + actuatorobject *a; { - /* Do NOT delete the actuator; most actuator objects are created - to hold a temporary reference to an actuator, like one gotten - from pnl_dopanel(). */ - - DEL(a); + /* Do NOT delete the actuator; most actuator objects are created + to hold a temporary reference to an actuator, like one gotten + from pnl_dopanel(). */ + + DEL(a); } @@ -804,167 +804,167 @@ actuator_dealloc(a) #define ACTOFF(member) offsetof(Actuator, member) struct memberlist act_memberlist[] = { - {"id", T_SHORT, ACTOFF(id), READONLY}, - - /* T_PANEL is not defined */ - /* - {"p", T_PANEL, ACTOFF(p), READONLY}, - */ - - {"pa", T_ACTUATOR, ACTOFF(pa), READONLY}, - {"ca", T_ACTUATOR, ACTOFF(ca), READONLY}, - {"al", T_ACTUATOR, ACTOFF(al), READONLY}, - {"na", T_INT, ACTOFF(na), READONLY}, - {"type", T_INT, ACTOFF(type), READONLY}, - {"active", T_BOOL, ACTOFF(active)}, - - {"x", T_COORD, ACTOFF(x)}, - {"y", T_COORD, ACTOFF(y)}, - {"w", T_COORD, ACTOFF(w)}, - {"h", T_COORD, ACTOFF(h)}, - - {"lx", T_COORD, ACTOFF(lx)}, - {"ly", T_COORD, ACTOFF(ly)}, - {"lw", T_COORD, ACTOFF(lw)}, - {"lh", T_COORD, ACTOFF(lh)}, - {"ld", T_COORD, ACTOFF(ld)}, - - {"val", T_FLOAT, ACTOFF(val)}, - {"extval", T_FLOAT, ACTOFF(extval)}, - {"initval", T_FLOAT, ACTOFF(initval)}, - {"maxval", T_FLOAT, ACTOFF(maxval)}, - {"minval", T_FLOAT, ACTOFF(minval)}, - {"scalefactor", T_FLOAT, ACTOFF(scalefactor)}, - - {"label", T_STRING, ACTOFF(label)}, - {"key", T_DEVICE, ACTOFF(key)}, - {"labeltype", T_INT, ACTOFF(labeltype)}, - - /* Internal callbacks are not supported; - user callbacks are treated special! */ - - {"dirtycnt", T_INT, ACTOFF(dirtycnt)}, - - /* members u and data are accessed differently */ - - {"automatic", T_BOOL, ACTOFF(automatic)}, - {"selectable", T_BOOL, ACTOFF(selectable)}, - {"visible", T_BOOL, ACTOFF(visible)}, - {"beveled", T_BOOL, ACTOFF(beveled)}, - - {"group", T_ACTUATOR, ACTOFF(group), READONLY}, - {"next", T_ACTUATOR, ACTOFF(next), READONLY}, - - {NULL, 0, 0} /* Sentinel */ + {"id", T_SHORT, ACTOFF(id), READONLY}, + + /* T_PANEL is not defined */ + /* + {"p", T_PANEL, ACTOFF(p), READONLY}, + */ + + {"pa", T_ACTUATOR, ACTOFF(pa), READONLY}, + {"ca", T_ACTUATOR, ACTOFF(ca), READONLY}, + {"al", T_ACTUATOR, ACTOFF(al), READONLY}, + {"na", T_INT, ACTOFF(na), READONLY}, + {"type", T_INT, ACTOFF(type), READONLY}, + {"active", T_BOOL, ACTOFF(active)}, + + {"x", T_COORD, ACTOFF(x)}, + {"y", T_COORD, ACTOFF(y)}, + {"w", T_COORD, ACTOFF(w)}, + {"h", T_COORD, ACTOFF(h)}, + + {"lx", T_COORD, ACTOFF(lx)}, + {"ly", T_COORD, ACTOFF(ly)}, + {"lw", T_COORD, ACTOFF(lw)}, + {"lh", T_COORD, ACTOFF(lh)}, + {"ld", T_COORD, ACTOFF(ld)}, + + {"val", T_FLOAT, ACTOFF(val)}, + {"extval", T_FLOAT, ACTOFF(extval)}, + {"initval", T_FLOAT, ACTOFF(initval)}, + {"maxval", T_FLOAT, ACTOFF(maxval)}, + {"minval", T_FLOAT, ACTOFF(minval)}, + {"scalefactor", T_FLOAT, ACTOFF(scalefactor)}, + + {"label", T_STRING, ACTOFF(label)}, + {"key", T_DEVICE, ACTOFF(key)}, + {"labeltype", T_INT, ACTOFF(labeltype)}, + + /* Internal callbacks are not supported; + user callbacks are treated special! */ + + {"dirtycnt", T_INT, ACTOFF(dirtycnt)}, + + /* members u and data are accessed differently */ + + {"automatic", T_BOOL, ACTOFF(automatic)}, + {"selectable", T_BOOL, ACTOFF(selectable)}, + {"visible", T_BOOL, ACTOFF(visible)}, + {"beveled", T_BOOL, ACTOFF(beveled)}, + + {"group", T_ACTUATOR, ACTOFF(group), READONLY}, + {"next", T_ACTUATOR, ACTOFF(next), READONLY}, + + {NULL, 0, 0} /* Sentinel */ }; /* Potential name conflicts between attributes are solved as follows. - - Actuator-specific attributes always override generic attributes. - - When reading, the dictionary has overrides everything else; - when writing, everything else overrides the dictionary. - - When reading, methods are tried last. + - Actuator-specific attributes always override generic attributes. + - When reading, the dictionary has overrides everything else; + when writing, everything else overrides the dictionary. + - When reading, methods are tried last. */ static object * actuator_getattr(a, name) - actuatorobject *a; - char *name; + actuatorobject *a; + char *name; { - Actuator *act = a->ob_actuator; - struct userdata *u = (struct userdata *) act->u; - object *v; - - if (u != NULL) { - /* 1. Try the dictionary */ - if (u->dict != NULL) { - v = dictlookup(u->dict, name); - if (v != NULL) { - INCREF(v); - return v; - } - } - - /* 2. Try actuator-specific attributes */ - if (u->spec != NULL) { - v = panel_getmember(act->data, u->spec, name); - if (v != NULL) - return v; - err_clear(); - } - } - - /* 3. Try generic actuator attributes */ - v = panel_getmember((char *)act, act_memberlist, name); - if (v != NULL) - return v; - - /* 4. Try methods */ - err_clear(); - return findmethod(actuator_methods, (object *)a, name); + Actuator *act = a->ob_actuator; + struct userdata *u = (struct userdata *) act->u; + object *v; + + if (u != NULL) { + /* 1. Try the dictionary */ + if (u->dict != NULL) { + v = dictlookup(u->dict, name); + if (v != NULL) { + INCREF(v); + return v; + } + } + + /* 2. Try actuator-specific attributes */ + if (u->spec != NULL) { + v = panel_getmember(act->data, u->spec, name); + if (v != NULL) + return v; + err_clear(); + } + } + + /* 3. Try generic actuator attributes */ + v = panel_getmember((char *)act, act_memberlist, name); + if (v != NULL) + return v; + + /* 4. Try methods */ + err_clear(); + return findmethod(actuator_methods, (object *)a, name); } static int actuator_setattr(a, name, v) - actuatorobject *a; - char *name; - object *v; + actuatorobject *a; + char *name; + object *v; { - Actuator *act = a->ob_actuator; - struct userdata *u = (struct userdata *) act->u; - int err; - - /* 0. We don't allow deletion of attributes */ - if (v == NULL) { - err_setstr(TypeError, "read-only actuator attribute"); - return -1; - } - - /* 1. Try actuator-specific attributes */ - if (u != NULL && u->spec != NULL) { - err = panel_setmember(act->data, u->spec, name, v); - if (err != 1) - return err; - } - - /* 2. Try generic actuator attributes */ - err = panel_setmember((char *)act, act_memberlist, name, v); - if (err != 1) - return err; - - /* 3. Try the dictionary */ - if (u != NULL) { - if (u->dict == NULL && (u->dict = newdictobject()) == NULL) - return NULL; - return dictinsert(u->dict, name, v); - } - - err_setstr(NameError, name); - return -1; + Actuator *act = a->ob_actuator; + struct userdata *u = (struct userdata *) act->u; + int err; + + /* 0. We don't allow deletion of attributes */ + if (v == NULL) { + err_setstr(TypeError, "read-only actuator attribute"); + return -1; + } + + /* 1. Try actuator-specific attributes */ + if (u != NULL && u->spec != NULL) { + err = panel_setmember(act->data, u->spec, name, v); + if (err != 1) + return err; + } + + /* 2. Try generic actuator attributes */ + err = panel_setmember((char *)act, act_memberlist, name, v); + if (err != 1) + return err; + + /* 3. Try the dictionary */ + if (u != NULL) { + if (u->dict == NULL && (u->dict = newdictobject()) == NULL) + return NULL; + return dictinsert(u->dict, name, v); + } + + err_setstr(NameError, name); + return -1; } static int actuator_compare(v, w) - actuatorobject *v, *w; + actuatorobject *v, *w; { - long i = (long)v->ob_actuator; - long j = (long)w->ob_actuator; - return (i < j) ? -1 : (i > j) ? 1 : 0; + long i = (long)v->ob_actuator; + long j = (long)w->ob_actuator; + return (i < j) ? -1 : (i > j) ? 1 : 0; } static typeobject Actuatortype = { - OB_HEAD_INIT(&Typetype) - 0, /*ob_size*/ - "actuator", /*tp_name*/ - sizeof(actuatorobject), /*tp_size*/ - 0, /*tp_itemsize*/ - /* methods */ - actuator_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - actuator_getattr, /*tp_getattr*/ - actuator_setattr, /*tp_setattr*/ - actuator_compare, /*tp_compare*/ - 0, /*tp_repr*/ + OB_HEAD_INIT(&Typetype) + 0, /*ob_size*/ + "actuator", /*tp_name*/ + sizeof(actuatorobject), /*tp_size*/ + 0, /*tp_itemsize*/ + /* methods */ + actuator_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + actuator_getattr, /*tp_getattr*/ + actuator_setattr, /*tp_setattr*/ + actuator_compare, /*tp_compare*/ + 0, /*tp_repr*/ }; @@ -972,119 +972,119 @@ static typeobject Actuatortype = { static object * module_mkpanel(self, args) - object *self; - object *args; + object *self; + object *args; { - if (!getnoarg(args)) - return NULL; - return newpanelobject(); + if (!getnoarg(args)) + return NULL; + return newpanelobject(); } static object * module_mkact(self, args) - object *self; - object *args; + object *self; + object *args; { - object *v; - Actuator *a; - if (!getstrarg(args, &v)) - return NULL; - a = makeactuator(getstringvalue(v)); - if (a == NULL) - return NULL; - return newactuatorobject(a); + object *v; + Actuator *a; + if (!getstrarg(args, &v)) + return NULL; + a = makeactuator(getstringvalue(v)); + if (a == NULL) + return NULL; + return newactuatorobject(a); } static object * module_dopanel(self, args) - object *self; - object *args; + object *self; + object *args; { - Actuator *a; - object *v, *w; - if (!getnoarg(args)) - return NULL; - a = pnl_dopanel(); - v = newtupleobject(4); - if (v == NULL) - return NULL; - settupleitem(v, 0, newactuatorobject(a)); - settupleitem(v, 1, newactuatorobject(down_pend)); - settupleitem(v, 2, newactuatorobject(active_pend)); - settupleitem(v, 3, newactuatorobject(up_pend)); - down_pend = active_pend = up_pend = NULL; - return v; + Actuator *a; + object *v, *w; + if (!getnoarg(args)) + return NULL; + a = pnl_dopanel(); + v = newtupleobject(4); + if (v == NULL) + return NULL; + settupleitem(v, 0, newactuatorobject(a)); + settupleitem(v, 1, newactuatorobject(down_pend)); + settupleitem(v, 2, newactuatorobject(active_pend)); + settupleitem(v, 3, newactuatorobject(up_pend)); + down_pend = active_pend = up_pend = NULL; + return v; } static object * module_drawpanel(self, args) - object *self; - object *args; + object *self; + object *args; { - if (!getnoarg(args)) - return NULL; - pnl_drawpanel(); - INCREF(None); - return None; + if (!getnoarg(args)) + return NULL; + pnl_drawpanel(); + INCREF(None); + return None; } static object * module_needredraw(self, args) - object *self; - object *args; + object *self; + object *args; { - if (!getnoarg(args)) - return NULL; - pnl_needredraw(); - INCREF(None); - return None; + if (!getnoarg(args)) + return NULL; + pnl_needredraw(); + INCREF(None); + return None; } static object * module_userredraw(self, args) - object *self; - object *args; + object *self; + object *args; { - short wid; - if (!getnoarg(args)) - return NULL; - wid = pnl_userredraw(); - return newintobject((long)wid); + short wid; + if (!getnoarg(args)) + return NULL; + wid = pnl_userredraw(); + return newintobject((long)wid); } static object * module_block(self, args) - object *self; - object *args; + object *self; + object *args; { - int flag; - if (!getintarg(args, &flag)) - return NULL; - pnl_block = flag; - INCREF(None); - return None; + int flag; + if (!getintarg(args, &flag)) + return NULL; + pnl_block = flag; + INCREF(None); + return None; } static struct methodlist module_methods[] = { - {"block", module_block}, - {"dopanel", module_dopanel}, - {"drawpanel", module_drawpanel}, - {"mkpanel", module_mkpanel}, - {"mkact", module_mkact}, - {"needredraw", module_needredraw}, - {"userredraw", module_userredraw}, - {NULL, NULL} /* sentinel */ + {"block", module_block}, + {"dopanel", module_dopanel}, + {"drawpanel", module_drawpanel}, + {"mkpanel", module_mkpanel}, + {"mkact", module_mkact}, + {"needredraw", module_needredraw}, + {"userredraw", module_userredraw}, + {NULL, NULL} /* sentinel */ }; void initpanel() { - /* Setting pnl_block to 1 would greatly reduce the CPU usage - of an idle application. Unfortunately it also breaks our - little hacks to get callback functions in Python called. - So we clear pnl_block here. You can set/clear pnl_block - from Python using pnl.block(flag). It works if you have - no upfuncs. */ - pnl_block = 0; - initmodule("pnl", module_methods); + /* Setting pnl_block to 1 would greatly reduce the CPU usage + of an idle application. Unfortunately it also breaks our + little hacks to get callback functions in Python called. + So we clear pnl_block here. You can set/clear pnl_block + from Python using pnl.block(flag). It works if you have + no upfuncs. */ + pnl_block = 0; + initmodule("pnl", module_methods); } diff --git a/src/parser.c b/src/parser.c index 8ee7e2c..141710a 100644 --- a/src/parser.c +++ b/src/parser.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -51,9 +51,9 @@ static void s_reset PROTO((stack *)); static void s_reset(s) - stack *s; + stack *s; { - s->s_top = &s->s_base[MAXSTACK]; + s->s_top = &s->s_base[MAXSTACK]; } #define s_empty(s) ((s)->s_top == &(s)->s_base[MAXSTACK]) @@ -62,20 +62,20 @@ static int s_push PROTO((stack *, dfa *, node *)); static int s_push(s, d, parent) - register stack *s; - dfa *d; - node *parent; + register stack *s; + dfa *d; + node *parent; { - register stackentry *top; - if (s->s_top == s->s_base) { - fprintf(stderr, "s_push: parser stack overflow\n"); - return -1; - } - top = --s->s_top; - top->s_dfa = d; - top->s_parent = parent; - top->s_state = 0; - return 0; + register stackentry *top; + if (s->s_top == s->s_base) { + fprintf(stderr, "s_push: parser stack overflow\n"); + return -1; + } + top = --s->s_top; + top->s_dfa = d; + top->s_parent = parent; + top->s_state = 0; + return 0; } #ifdef DEBUG @@ -84,13 +84,13 @@ static void s_pop PROTO((stack *)); static void s_pop(s) - register stack *s; + register stack *s; { - if (s_empty(s)) { - fprintf(stderr, "s_pop: parser stack underflow -- FATAL\n"); - abort(); - } - s->s_top++; + if (s_empty(s)) { + fprintf(stderr, "s_pop: parser stack underflow -- FATAL\n"); + abort(); + } + s->s_top++; } #else /* !DEBUG */ @@ -104,35 +104,35 @@ s_pop(s) parser_state * newparser(g, start) - grammar *g; - int start; + grammar *g; + int start; { - parser_state *ps; - - if (!g->g_accel) - addaccelerators(g); - ps = NEW(parser_state, 1); - if (ps == NULL) - return NULL; - ps->p_grammar = g; - ps->p_tree = newtree(start); - if (ps->p_tree == NULL) { - DEL(ps); - return NULL; - } - s_reset(&ps->p_stack); - (void) s_push(&ps->p_stack, finddfa(g, start), ps->p_tree); - return ps; + parser_state *ps; + + if (!g->g_accel) + addaccelerators(g); + ps = NEW(parser_state, 1); + if (ps == NULL) + return NULL; + ps->p_grammar = g; + ps->p_tree = newtree(start); + if (ps->p_tree == NULL) { + DEL(ps); + return NULL; + } + s_reset(&ps->p_stack); + (void) s_push(&ps->p_stack, finddfa(g, start), ps->p_tree); + return ps; } void delparser(ps) - parser_state *ps; + parser_state *ps; { - /* NB If you want to save the parse tree, - you must set p_tree to NULL before calling delparser! */ - freetree(ps->p_tree); - DEL(ps); + /* NB If you want to save the parse tree, + you must set p_tree to NULL before calling delparser! */ + freetree(ps->p_tree); + DEL(ps); } @@ -142,40 +142,40 @@ static int shift PROTO((stack *, int, char *, int, int)); static int shift(s, type, str, newstate, lineno) - register stack *s; - int type; - char *str; - int newstate; - int lineno; + register stack *s; + int type; + char *str; + int newstate; + int lineno; { - assert(!s_empty(s)); - if (addchild(s->s_top->s_parent, type, str, lineno) == NULL) { - fprintf(stderr, "shift: no mem in addchild\n"); - return -1; - } - s->s_top->s_state = newstate; - return 0; + assert(!s_empty(s)); + if (addchild(s->s_top->s_parent, type, str, lineno) == NULL) { + fprintf(stderr, "shift: no mem in addchild\n"); + return -1; + } + s->s_top->s_state = newstate; + return 0; } static int push PROTO((stack *, int, dfa *, int, int)); static int push(s, type, d, newstate, lineno) - register stack *s; - int type; - dfa *d; - int newstate; - int lineno; + register stack *s; + int type; + dfa *d; + int newstate; + int lineno; { - register node *n; - n = s->s_top->s_parent; - assert(!s_empty(s)); - if (addchild(n, type, (char *)NULL, lineno) == NULL) { - fprintf(stderr, "push: no mem in addchild\n"); - return -1; - } - s->s_top->s_state = newstate; - return s_push(s, d, CHILD(n, NCH(n)-1)); + register node *n; + n = s->s_top->s_parent; + assert(!s_empty(s)); + if (addchild(n, type, (char *)NULL, lineno) == NULL) { + fprintf(stderr, "push: no mem in addchild\n"); + return -1; + } + s->s_top->s_state = newstate; + return s_push(s, d, CHILD(n, NCH(n)-1)); } @@ -185,122 +185,122 @@ static int classify PROTO((grammar *, int, char *)); static int classify(g, type, str) - grammar *g; - register int type; - char *str; + grammar *g; + register int type; + char *str; { - register int n = g->g_ll.ll_nlabels; - - if (type == NAME) { - register char *s = str; - register label *l = g->g_ll.ll_label; - register int i; - for (i = n; i > 0; i--, l++) { - if (l->lb_type == NAME && l->lb_str != NULL && - l->lb_str[0] == s[0] && - strcmp(l->lb_str, s) == 0) { - D(printf("It's a keyword\n")); - return n - i; - } - } - } - - { - register label *l = g->g_ll.ll_label; - register int i; - for (i = n; i > 0; i--, l++) { - if (l->lb_type == type && l->lb_str == NULL) { - D(printf("It's a token we know\n")); - return n - i; - } - } - } - - D(printf("Illegal token\n")); - return -1; + register int n = g->g_ll.ll_nlabels; + + if (type == NAME) { + register char *s = str; + register label *l = g->g_ll.ll_label; + register int i; + for (i = n; i > 0; i--, l++) { + if (l->lb_type == NAME && l->lb_str != NULL && + l->lb_str[0] == s[0] && + strcmp(l->lb_str, s) == 0) { + D(printf("It's a keyword\n")); + return n - i; + } + } + } + + { + register label *l = g->g_ll.ll_label; + register int i; + for (i = n; i > 0; i--, l++) { + if (l->lb_type == type && l->lb_str == NULL) { + D(printf("It's a token we know\n")); + return n - i; + } + } + } + + D(printf("Illegal token\n")); + return -1; } int addtoken(ps, type, str, lineno) - register parser_state *ps; - register int type; - char *str; - int lineno; + register parser_state *ps; + register int type; + char *str; + int lineno; { - register int ilabel; - - D(printf("Token %s/'%s' ... ", tok_name[type], str)); - - /* Find out which label this token is */ - ilabel = classify(ps->p_grammar, type, str); - if (ilabel < 0) - return E_SYNTAX; - - /* Loop until the token is shifted or an error occurred */ - for (;;) { - /* Fetch the current dfa and state */ - register dfa *d = ps->p_stack.s_top->s_dfa; - register state *s = &d->d_state[ps->p_stack.s_top->s_state]; - - D(printf(" DFA '%s', state %d:", - d->d_name, ps->p_stack.s_top->s_state)); - - /* Check accelerator */ - if (s->s_lower <= ilabel && ilabel < s->s_upper) { - register int x = s->s_accel[ilabel - s->s_lower]; - if (x != -1) { - if (x & (1<<7)) { - /* Push non-terminal */ - int nt = (x >> 8) + NT_OFFSET; - int arrow = x & ((1<<7)-1); - dfa *d1 = finddfa(ps->p_grammar, nt); - if (push(&ps->p_stack, nt, d1, - arrow, lineno) < 0) { - D(printf(" MemError: push.\n")); - return E_NOMEM; - } - D(printf(" Push ...\n")); - continue; - } - - /* Shift the token */ - if (shift(&ps->p_stack, type, str, - x, lineno) < 0) { - D(printf(" MemError: shift.\n")); - return E_NOMEM; - } - D(printf(" Shift.\n")); - /* Pop while we are in an accept-only state */ - while (s = &d->d_state - [ps->p_stack.s_top->s_state], - s->s_accept && s->s_narcs == 1) { - D(printf(" Direct pop.\n")); - s_pop(&ps->p_stack); - if (s_empty(&ps->p_stack)) { - D(printf(" ACCEPT.\n")); - return E_DONE; - } - d = ps->p_stack.s_top->s_dfa; - } - return E_OK; - } - } - - if (s->s_accept) { - /* Pop this dfa and try again */ - s_pop(&ps->p_stack); - D(printf(" Pop ...\n")); - if (s_empty(&ps->p_stack)) { - D(printf(" Error: bottom of stack.\n")); - return E_SYNTAX; - } - continue; - } - - /* Stuck, report syntax error */ - D(printf(" Error.\n")); - return E_SYNTAX; - } + register int ilabel; + + D(printf("Token %s/'%s' ... ", tok_name[type], str)); + + /* Find out which label this token is */ + ilabel = classify(ps->p_grammar, type, str); + if (ilabel < 0) + return E_SYNTAX; + + /* Loop until the token is shifted or an error occurred */ + for (;;) { + /* Fetch the current dfa and state */ + register dfa *d = ps->p_stack.s_top->s_dfa; + register state *s = &d->d_state[ps->p_stack.s_top->s_state]; + + D(printf(" DFA '%s', state %d:", + d->d_name, ps->p_stack.s_top->s_state)); + + /* Check accelerator */ + if (s->s_lower <= ilabel && ilabel < s->s_upper) { + register int x = s->s_accel[ilabel - s->s_lower]; + if (x != -1) { + if (x & (1<<7)) { + /* Push non-terminal */ + int nt = (x >> 8) + NT_OFFSET; + int arrow = x & ((1<<7)-1); + dfa *d1 = finddfa(ps->p_grammar, nt); + if (push(&ps->p_stack, nt, d1, + arrow, lineno) < 0) { + D(printf(" MemError: push.\n")); + return E_NOMEM; + } + D(printf(" Push ...\n")); + continue; + } + + /* Shift the token */ + if (shift(&ps->p_stack, type, str, + x, lineno) < 0) { + D(printf(" MemError: shift.\n")); + return E_NOMEM; + } + D(printf(" Shift.\n")); + /* Pop while we are in an accept-only state */ + while (s = &d->d_state + [ps->p_stack.s_top->s_state], + s->s_accept && s->s_narcs == 1) { + D(printf(" Direct pop.\n")); + s_pop(&ps->p_stack); + if (s_empty(&ps->p_stack)) { + D(printf(" ACCEPT.\n")); + return E_DONE; + } + d = ps->p_stack.s_top->s_dfa; + } + return E_OK; + } + } + + if (s->s_accept) { + /* Pop this dfa and try again */ + s_pop(&ps->p_stack); + D(printf(" Pop ...\n")); + if (s_empty(&ps->p_stack)) { + D(printf(" Error: bottom of stack.\n")); + return E_SYNTAX; + } + continue; + } + + /* Stuck, report syntax error */ + D(printf(" Error.\n")); + return E_SYNTAX; + } } @@ -310,68 +310,68 @@ addtoken(ps, type, str, lineno) void dumptree(g, n) - grammar *g; - node *n; + grammar *g; + node *n; { - int i; - - if (n == NULL) - printf("NIL"); - else { - label l; - l.lb_type = TYPE(n); - l.lb_str = TYPE(str); - printf("%s", labelrepr(&l)); - if (ISNONTERMINAL(TYPE(n))) { - printf("("); - for (i = 0; i < NCH(n); i++) { - if (i > 0) - printf(","); - dumptree(g, CHILD(n, i)); - } - printf(")"); - } - } + int i; + + if (n == NULL) + printf("NIL"); + else { + label l; + l.lb_type = TYPE(n); + l.lb_str = TYPE(str); + printf("%s", labelrepr(&l)); + if (ISNONTERMINAL(TYPE(n))) { + printf("("); + for (i = 0; i < NCH(n); i++) { + if (i > 0) + printf(","); + dumptree(g, CHILD(n, i)); + } + printf(")"); + } + } } void showtree(g, n) - grammar *g; - node *n; + grammar *g; + node *n; { - int i; - - if (n == NULL) - return; - if (ISNONTERMINAL(TYPE(n))) { - for (i = 0; i < NCH(n); i++) - showtree(g, CHILD(n, i)); - } - else if (ISTERMINAL(TYPE(n))) { - printf("%s", tok_name[TYPE(n)]); - if (TYPE(n) == NUMBER || TYPE(n) == NAME) - printf("(%s)", STR(n)); - printf(" "); - } - else - printf("? "); + int i; + + if (n == NULL) + return; + if (ISNONTERMINAL(TYPE(n))) { + for (i = 0; i < NCH(n); i++) + showtree(g, CHILD(n, i)); + } + else if (ISTERMINAL(TYPE(n))) { + printf("%s", tok_name[TYPE(n)]); + if (TYPE(n) == NUMBER || TYPE(n) == NAME) + printf("(%s)", STR(n)); + printf(" "); + } + else + printf("? "); } void printtree(ps) - parser_state *ps; + parser_state *ps; { - if (debugging) { - printf("Parse tree:\n"); - dumptree(ps->p_grammar, ps->p_tree); - printf("\n"); - printf("Tokens:\n"); - showtree(ps->p_grammar, ps->p_tree); - printf("\n"); - } - printf("Listing:\n"); - listtree(ps->p_tree); - printf("\n"); + if (debugging) { + printf("Parse tree:\n"); + dumptree(ps->p_grammar, ps->p_tree); + printf("\n"); + printf("Tokens:\n"); + showtree(ps->p_grammar, ps->p_tree); + printf("\n"); + } + printf("Listing:\n"); + listtree(ps->p_tree); + printf("\n"); } #endif /* DEBUG */ @@ -382,39 +382,39 @@ Description ----------- The parser's interface is different than usual: the function addtoken() -must be called for each token in the input. This makes it possible to -turn it into an incremental parsing system later. The parsing system +must be called for each token in the input. This makes it possible to +turn it into an incremental parsing system later. The parsing system constructs a parse tree as it goes. A parsing rule is represented as a Deterministic Finite-state Automaton -(DFA). A node in a DFA represents a state of the parser; an arc represents -a transition. Transitions are either labeled with terminal symbols or -with non-terminals. When the parser decides to follow an arc labeled +(DFA). A node in a DFA represents a state of the parser; an arc represents +a transition. Transitions are either labeled with terminal symbols or +with non-terminals. When the parser decides to follow an arc labeled with a non-terminal, it is invoked recursively with the DFA representing the parsing rule for that as its initial state; when that DFA accepts, -the parser that invoked it continues. The parse tree constructed by the +the parser that invoked it continues. The parse tree constructed by the recursively called parser is inserted as a child in the current parse tree. The DFA's can be constructed automatically from a more conventional -language description. An extended LL(1) grammar (ELL(1)) is suitable. +language description. An extended LL(1) grammar (ELL(1)) is suitable. Certain restrictions make the parser's life easier: rules that can produce the empty string should be outlawed (there are other ways to put loops -or optional parts in the language). To avoid the need to construct +or optional parts in the language). To avoid the need to construct FIRST sets, we can require that all but the last alternative of a rule (really: arc going out of a DFA's state) must begin with a terminal symbol. As an example, consider this grammar: -expr: term (OP term)* -term: CONSTANT | '(' expr ')' +expr: term (OP term)* +term: CONSTANT | '(' expr ')' The DFA corresponding to the rule for expr is: ------->.---term-->.-------> - ^ | - | | - \----OP----/ + ^ | + | | + \----OP----/ The parse tree generated for the input a+b is: diff --git a/src/parser.h b/src/parser.h index 3e8090a..5b962be 100644 --- a/src/parser.h +++ b/src/parser.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -27,21 +27,21 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #define MAXSTACK 100 typedef struct _stackentry { - int s_state; /* State in current DFA */ - dfa *s_dfa; /* Current DFA */ - struct _node *s_parent; /* Where to add next node */ + int s_state; /* State in current DFA */ + dfa *s_dfa; /* Current DFA */ + struct _node *s_parent; /* Where to add next node */ } stackentry; typedef struct _stack { - stackentry *s_top; /* Top entry */ - stackentry s_base[MAXSTACK];/* Array of stack entries */ - /* NB The stack grows down */ + stackentry *s_top; /* Top entry */ + stackentry s_base[MAXSTACK];/* Array of stack entries */ + /* NB The stack grows down */ } stack; typedef struct { - struct _stack p_stack; /* Stack of parser states */ - struct _grammar *p_grammar; /* Grammar to use */ - struct _node *p_tree; /* Top of parse tree */ + struct _stack p_stack; /* Stack of parser states */ + struct _grammar *p_grammar; /* Grammar to use */ + struct _node *p_tree; /* Top of parse tree */ } parser_state; parser_state *newparser PROTO((struct _grammar *g, int start)); diff --git a/src/parsetok.c b/src/parsetok.c index e19a979..5aeea29 100644 --- a/src/parsetok.c +++ b/src/parsetok.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -37,122 +37,122 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. static int parsetok PROTO((struct tok_state *, grammar *, int, node **)); -/* Parse input coming from a string. Return error code, print some errors. */ +/* Parse input coming from a string. Return error code, print some errors. */ int parsestring(s, g, start, n_ret) - char *s; - grammar *g; - int start; - node **n_ret; + char *s; + grammar *g; + int start; + node **n_ret; { - struct tok_state *tok = tok_setups(s); - int ret; - - if (tok == NULL) { - fprintf(stderr, "no mem for tok_setups\n"); - return E_NOMEM; - } - ret = parsetok(tok, g, start, n_ret); - if (ret == E_TOKEN || ret == E_SYNTAX) { - fprintf(stderr, "String parsing error at line %d\n", - tok->lineno); - } - tok_free(tok); - return ret; + struct tok_state *tok = tok_setups(s); + int ret; + + if (tok == NULL) { + fprintf(stderr, "no mem for tok_setups\n"); + return E_NOMEM; + } + ret = parsetok(tok, g, start, n_ret); + if (ret == E_TOKEN || ret == E_SYNTAX) { + fprintf(stderr, "String parsing error at line %d\n", + tok->lineno); + } + tok_free(tok); + return ret; } -/* Parse input coming from a file. Return error code, print some errors. */ +/* Parse input coming from a file. Return error code, print some errors. */ int parsefile(fp, filename, g, start, ps1, ps2, n_ret) - FILE *fp; - char *filename; - grammar *g; - int start; - char *ps1, *ps2; - node **n_ret; + FILE *fp; + char *filename; + grammar *g; + int start; + char *ps1, *ps2; + node **n_ret; { - struct tok_state *tok = tok_setupf(fp, ps1, ps2); - int ret; - - if (tok == NULL) { - fprintf(stderr, "no mem for tok_setupf\n"); - return E_NOMEM; - } - ret = parsetok(tok, g, start, n_ret); - if (ret == E_TOKEN || ret == E_SYNTAX) { - char *p; - fprintf(stderr, "Parsing error: file %s, line %d:\n", - filename, tok->lineno); - *tok->inp = '\0'; - if (tok->inp > tok->buf && tok->inp[-1] == '\n') - tok->inp[-1] = '\0'; - fprintf(stderr, "%s\n", tok->buf); - for (p = tok->buf; p < tok->cur; p++) { - if (*p == '\t') - putc('\t', stderr); - else - putc(' ', stderr); - } - fprintf(stderr, "^\n"); - } - tok_free(tok); - return ret; + struct tok_state *tok = tok_setupf(fp, ps1, ps2); + int ret; + + if (tok == NULL) { + fprintf(stderr, "no mem for tok_setupf\n"); + return E_NOMEM; + } + ret = parsetok(tok, g, start, n_ret); + if (ret == E_TOKEN || ret == E_SYNTAX) { + char *p; + fprintf(stderr, "Parsing error: file %s, line %d:\n", + filename, tok->lineno); + *tok->inp = '\0'; + if (tok->inp > tok->buf && tok->inp[-1] == '\n') + tok->inp[-1] = '\0'; + fprintf(stderr, "%s\n", tok->buf); + for (p = tok->buf; p < tok->cur; p++) { + if (*p == '\t') + putc('\t', stderr); + else + putc(' ', stderr); + } + fprintf(stderr, "^\n"); + } + tok_free(tok); + return ret; } /* Parse input coming from the given tokenizer structure. - Return error code. */ + Return error code. */ static int parsetok(tok, g, start, n_ret) - struct tok_state *tok; - grammar *g; - int start; - node **n_ret; + struct tok_state *tok; + grammar *g; + int start; + node **n_ret; { - parser_state *ps; - int ret; - - if ((ps = newparser(g, start)) == NULL) { - fprintf(stderr, "no mem for new parser\n"); - return E_NOMEM; - } - - for (;;) { - char *a, *b; - int type; - int len; - char *str; - - type = tok_get(tok, &a, &b); - if (type == ERRORTOKEN) { - ret = tok->done; - break; - } - len = b - a; - str = NEW(char, len + 1); - if (str == NULL) { - fprintf(stderr, "no mem for next token\n"); - ret = E_NOMEM; - break; - } - strncpy(str, a, len); - str[len] = '\0'; - ret = addtoken(ps, (int)type, str, tok->lineno); - if (ret != E_OK) { - if (ret == E_DONE) { - *n_ret = ps->p_tree; - ps->p_tree = NULL; - } - else if (tok->lineno <= 1 && tok->done == E_EOF) - ret = E_EOF; - break; - } - } - - delparser(ps); - return ret; + parser_state *ps; + int ret; + + if ((ps = newparser(g, start)) == NULL) { + fprintf(stderr, "no mem for new parser\n"); + return E_NOMEM; + } + + for (;;) { + char *a, *b; + int type; + int len; + char *str; + + type = tok_get(tok, &a, &b); + if (type == ERRORTOKEN) { + ret = tok->done; + break; + } + len = b - a; + str = NEW(char, len + 1); + if (str == NULL) { + fprintf(stderr, "no mem for next token\n"); + ret = E_NOMEM; + break; + } + strncpy(str, a, len); + str[len] = '\0'; + ret = addtoken(ps, (int)type, str, tok->lineno); + if (ret != E_OK) { + if (ret == E_DONE) { + *n_ret = ps->p_tree; + ps->p_tree = NULL; + } + else if (tok->lineno <= 1 && tok->done == E_EOF) + ret = E_EOF; + break; + } + } + + delparser(ps); + return ret; } diff --git a/src/parsetok.h b/src/parsetok.h index e05fdb5..c46a3e8 100644 --- a/src/parsetok.h +++ b/src/parsetok.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -26,4 +26,4 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. extern int parsestring PROTO((char *, grammar *, int start, node **n_ret)); extern int parsefile PROTO((FILE *, char *, grammar *, int start, - char *ps1, char *ps2, node **n_ret)); + char *ps1, char *ps2, node **n_ret)); diff --git a/src/patchlevel.h b/src/patchlevel.h index 110c86f..d00491f 100644 --- a/src/patchlevel.h +++ b/src/patchlevel.h @@ -1 +1 @@ -#define PATCHLEVEL 1 +1 @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -41,109 +41,109 @@ extern int debugging; /* PART ONE -- CONSTRUCT NFA -- Cf. Algorithm 3.2 from [Aho&Ullman 77] */ typedef struct _nfaarc { - int ar_label; - int ar_arrow; + int ar_label; + int ar_arrow; } nfaarc; typedef struct _nfastate { - int st_narcs; - nfaarc *st_arc; + int st_narcs; + nfaarc *st_arc; } nfastate; typedef struct _nfa { - int nf_type; - char *nf_name; - int nf_nstates; - nfastate *nf_state; - int nf_start, nf_finish; + int nf_type; + char *nf_name; + int nf_nstates; + nfastate *nf_state; + int nf_start, nf_finish; } nfa; static int addnfastate(nf) - nfa *nf; + nfa *nf; { - nfastate *st; - - RESIZE(nf->nf_state, nfastate, nf->nf_nstates + 1); - if (nf->nf_state == NULL) - fatal("out of mem"); - st = &nf->nf_state[nf->nf_nstates++]; - st->st_narcs = 0; - st->st_arc = NULL; - return st - nf->nf_state; + nfastate *st; + + RESIZE(nf->nf_state, nfastate, nf->nf_nstates + 1); + if (nf->nf_state == NULL) + fatal("out of mem"); + st = &nf->nf_state[nf->nf_nstates++]; + st->st_narcs = 0; + st->st_arc = NULL; + return st - nf->nf_state; } static void addnfaarc(nf, from, to, lbl) - nfa *nf; - int from, to, lbl; + nfa *nf; + int from, to, lbl; { - nfastate *st; - nfaarc *ar; - - st = &nf->nf_state[from]; - RESIZE(st->st_arc, nfaarc, st->st_narcs + 1); - if (st->st_arc == NULL) - fatal("out of mem"); - ar = &st->st_arc[st->st_narcs++]; - ar->ar_label = lbl; - ar->ar_arrow = to; + nfastate *st; + nfaarc *ar; + + st = &nf->nf_state[from]; + RESIZE(st->st_arc, nfaarc, st->st_narcs + 1); + if (st->st_arc == NULL) + fatal("out of mem"); + ar = &st->st_arc[st->st_narcs++]; + ar->ar_label = lbl; + ar->ar_arrow = to; } static nfa * newnfa(name) - char *name; + char *name; { - nfa *nf; - static type = NT_OFFSET; /* All types will be disjunct */ - - nf = NEW(nfa, 1); - if (nf == NULL) - fatal("no mem for new nfa"); - nf->nf_type = type++; - nf->nf_name = name; /* XXX strdup(name) ??? */ - nf->nf_nstates = 0; - nf->nf_state = NULL; - nf->nf_start = nf->nf_finish = -1; - return nf; + nfa *nf; + static type = NT_OFFSET; /* All types will be disjunct */ + + nf = NEW(nfa, 1); + if (nf == NULL) + fatal("no mem for new nfa"); + nf->nf_type = type++; + nf->nf_name = name; /* XXX strdup(name) ??? */ + nf->nf_nstates = 0; + nf->nf_state = NULL; + nf->nf_start = nf->nf_finish = -1; + return nf; } typedef struct _nfagrammar { - int gr_nnfas; - nfa **gr_nfa; - labellist gr_ll; + int gr_nnfas; + nfa **gr_nfa; + labellist gr_ll; } nfagrammar; static nfagrammar * newnfagrammar() { - nfagrammar *gr; - - gr = NEW(nfagrammar, 1); - if (gr == NULL) - fatal("no mem for new nfa grammar"); - gr->gr_nnfas = 0; - gr->gr_nfa = NULL; - gr->gr_ll.ll_nlabels = 0; - gr->gr_ll.ll_label = NULL; - addlabel(&gr->gr_ll, ENDMARKER, "EMPTY"); - return gr; + nfagrammar *gr; + + gr = NEW(nfagrammar, 1); + if (gr == NULL) + fatal("no mem for new nfa grammar"); + gr->gr_nnfas = 0; + gr->gr_nfa = NULL; + gr->gr_ll.ll_nlabels = 0; + gr->gr_ll.ll_label = NULL; + addlabel(&gr->gr_ll, ENDMARKER, "EMPTY"); + return gr; } static nfa * addnfa(gr, name) - nfagrammar *gr; - char *name; + nfagrammar *gr; + char *name; { - nfa *nf; - - nf = newnfa(name); - RESIZE(gr->gr_nfa, nfa *, gr->gr_nnfas + 1); - if (gr->gr_nfa == NULL) - fatal("out of mem"); - gr->gr_nfa[gr->gr_nnfas++] = nf; - addlabel(&gr->gr_ll, NAME, nf->nf_name); - return nf; + nfa *nf; + + nf = newnfa(name); + RESIZE(gr->gr_nfa, nfa *, gr->gr_nnfas + 1); + if (gr->gr_nfa == NULL) + fatal("out of mem"); + gr->gr_nfa[gr->gr_nnfas++] = nf; + addlabel(&gr->gr_ll, NAME, nf->nf_name); + return nf; } #ifdef DEBUG @@ -151,231 +151,231 @@ addnfa(gr, name) static char REQNFMT[] = "metacompile: less than %d children\n"; #define REQN(i, count) \ - if (i < count) { \ - fprintf(stderr, REQNFMT, count); \ - abort(); \ - } else + if (i < count) { \ + fprintf(stderr, REQNFMT, count); \ + abort(); \ + } else #else -#define REQN(i, count) /* empty */ +#define REQN(i, count) /* empty */ #endif static nfagrammar * metacompile(n) - node *n; + node *n; { - nfagrammar *gr; - int i; - - printf("Compiling (meta-) parse tree into NFA grammar\n"); - gr = newnfagrammar(); - REQ(n, MSTART); - i = n->n_nchildren - 1; /* Last child is ENDMARKER */ - n = n->n_child; - for (; --i >= 0; n++) { - if (n->n_type != NEWLINE) - compile_rule(gr, n); - } - return gr; + nfagrammar *gr; + int i; + + printf("Compiling (meta-) parse tree into NFA grammar\n"); + gr = newnfagrammar(); + REQ(n, MSTART); + i = n->n_nchildren - 1; /* Last child is ENDMARKER */ + n = n->n_child; + for (; --i >= 0; n++) { + if (n->n_type != NEWLINE) + compile_rule(gr, n); + } + return gr; } static compile_rule(gr, n) - nfagrammar *gr; - node *n; + nfagrammar *gr; + node *n; { - nfa *nf; - - REQ(n, RULE); - REQN(n->n_nchildren, 4); - n = n->n_child; - REQ(n, NAME); - nf = addnfa(gr, n->n_str); - n++; - REQ(n, COLON); - n++; - REQ(n, RHS); - compile_rhs(&gr->gr_ll, nf, n, &nf->nf_start, &nf->nf_finish); - n++; - REQ(n, NEWLINE); + nfa *nf; + + REQ(n, RULE); + REQN(n->n_nchildren, 4); + n = n->n_child; + REQ(n, NAME); + nf = addnfa(gr, n->n_str); + n++; + REQ(n, COLON); + n++; + REQ(n, RHS); + compile_rhs(&gr->gr_ll, nf, n, &nf->nf_start, &nf->nf_finish); + n++; + REQ(n, NEWLINE); } static compile_rhs(ll, nf, n, pa, pb) - labellist *ll; - nfa *nf; - node *n; - int *pa, *pb; + labellist *ll; + nfa *nf; + node *n; + int *pa, *pb; { - int i; - int a, b; - - REQ(n, RHS); - i = n->n_nchildren; - REQN(i, 1); - n = n->n_child; - REQ(n, ALT); - compile_alt(ll, nf, n, pa, pb); - if (--i <= 0) - return; - n++; - a = *pa; - b = *pb; - *pa = addnfastate(nf); - *pb = addnfastate(nf); - addnfaarc(nf, *pa, a, EMPTY); - addnfaarc(nf, b, *pb, EMPTY); - for (; --i >= 0; n++) { - REQ(n, VBAR); - REQN(i, 1); - --i; - n++; - REQ(n, ALT); - compile_alt(ll, nf, n, &a, &b); - addnfaarc(nf, *pa, a, EMPTY); - addnfaarc(nf, b, *pb, EMPTY); - } + int i; + int a, b; + + REQ(n, RHS); + i = n->n_nchildren; + REQN(i, 1); + n = n->n_child; + REQ(n, ALT); + compile_alt(ll, nf, n, pa, pb); + if (--i <= 0) + return; + n++; + a = *pa; + b = *pb; + *pa = addnfastate(nf); + *pb = addnfastate(nf); + addnfaarc(nf, *pa, a, EMPTY); + addnfaarc(nf, b, *pb, EMPTY); + for (; --i >= 0; n++) { + REQ(n, VBAR); + REQN(i, 1); + --i; + n++; + REQ(n, ALT); + compile_alt(ll, nf, n, &a, &b); + addnfaarc(nf, *pa, a, EMPTY); + addnfaarc(nf, b, *pb, EMPTY); + } } static compile_alt(ll, nf, n, pa, pb) - labellist *ll; - nfa *nf; - node *n; - int *pa, *pb; + labellist *ll; + nfa *nf; + node *n; + int *pa, *pb; { - int i; - int a, b; - - REQ(n, ALT); - i = n->n_nchildren; - REQN(i, 1); - n = n->n_child; - REQ(n, ITEM); - compile_item(ll, nf, n, pa, pb); - --i; - n++; - for (; --i >= 0; n++) { - if (n->n_type == COMMA) { /* XXX Temporary */ - REQN(i, 1); - --i; - n++; - } - REQ(n, ITEM); - compile_item(ll, nf, n, &a, &b); - addnfaarc(nf, *pb, a, EMPTY); - *pb = b; - } + int i; + int a, b; + + REQ(n, ALT); + i = n->n_nchildren; + REQN(i, 1); + n = n->n_child; + REQ(n, ITEM); + compile_item(ll, nf, n, pa, pb); + --i; + n++; + for (; --i >= 0; n++) { + if (n->n_type == COMMA) { /* XXX Temporary */ + REQN(i, 1); + --i; + n++; + } + REQ(n, ITEM); + compile_item(ll, nf, n, &a, &b); + addnfaarc(nf, *pb, a, EMPTY); + *pb = b; + } } static compile_item(ll, nf, n, pa, pb) - labellist *ll; - nfa *nf; - node *n; - int *pa, *pb; + labellist *ll; + nfa *nf; + node *n; + int *pa, *pb; { - int i; - int a, b; - - REQ(n, ITEM); - i = n->n_nchildren; - REQN(i, 1); - n = n->n_child; - if (n->n_type == LSQB) { - REQN(i, 3); - n++; - REQ(n, RHS); - *pa = addnfastate(nf); - *pb = addnfastate(nf); - addnfaarc(nf, *pa, *pb, EMPTY); - compile_rhs(ll, nf, n, &a, &b); - addnfaarc(nf, *pa, a, EMPTY); - addnfaarc(nf, b, *pb, EMPTY); - REQN(i, 1); - n++; - REQ(n, RSQB); - } - else { - compile_atom(ll, nf, n, pa, pb); - if (--i <= 0) - return; - n++; - addnfaarc(nf, *pb, *pa, EMPTY); - if (n->n_type == STAR) - *pb = *pa; - else - REQ(n, PLUS); - } + int i; + int a, b; + + REQ(n, ITEM); + i = n->n_nchildren; + REQN(i, 1); + n = n->n_child; + if (n->n_type == LSQB) { + REQN(i, 3); + n++; + REQ(n, RHS); + *pa = addnfastate(nf); + *pb = addnfastate(nf); + addnfaarc(nf, *pa, *pb, EMPTY); + compile_rhs(ll, nf, n, &a, &b); + addnfaarc(nf, *pa, a, EMPTY); + addnfaarc(nf, b, *pb, EMPTY); + REQN(i, 1); + n++; + REQ(n, RSQB); + } + else { + compile_atom(ll, nf, n, pa, pb); + if (--i <= 0) + return; + n++; + addnfaarc(nf, *pb, *pa, EMPTY); + if (n->n_type == STAR) + *pb = *pa; + else + REQ(n, PLUS); + } } static compile_atom(ll, nf, n, pa, pb) - labellist *ll; - nfa *nf; - node *n; - int *pa, *pb; + labellist *ll; + nfa *nf; + node *n; + int *pa, *pb; { - int i; - - REQ(n, ATOM); - i = n->n_nchildren; - REQN(i, 1); - n = n->n_child; - if (n->n_type == LPAR) { - REQN(i, 3); - n++; - REQ(n, RHS); - compile_rhs(ll, nf, n, pa, pb); - n++; - REQ(n, RPAR); - } - else if (n->n_type == NAME || n->n_type == STRING) { - *pa = addnfastate(nf); - *pb = addnfastate(nf); - addnfaarc(nf, *pa, *pb, addlabel(ll, n->n_type, n->n_str)); - } - else - REQ(n, NAME); + int i; + + REQ(n, ATOM); + i = n->n_nchildren; + REQN(i, 1); + n = n->n_child; + if (n->n_type == LPAR) { + REQN(i, 3); + n++; + REQ(n, RHS); + compile_rhs(ll, nf, n, pa, pb); + n++; + REQ(n, RPAR); + } + else if (n->n_type == NAME || n->n_type == STRING) { + *pa = addnfastate(nf); + *pb = addnfastate(nf); + addnfaarc(nf, *pa, *pb, addlabel(ll, n->n_type, n->n_str)); + } + else + REQ(n, NAME); } static void dumpstate(ll, nf, istate) - labellist *ll; - nfa *nf; - int istate; + labellist *ll; + nfa *nf; + int istate; { - nfastate *st; - int i; - nfaarc *ar; - - printf("%c%2d%c", - istate == nf->nf_start ? '*' : ' ', - istate, - istate == nf->nf_finish ? '.' : ' '); - st = &nf->nf_state[istate]; - ar = st->st_arc; - for (i = 0; i < st->st_narcs; i++) { - if (i > 0) - printf("\n "); - printf("-> %2d %s", ar->ar_arrow, - labelrepr(&ll->ll_label[ar->ar_label])); - ar++; - } - printf("\n"); + nfastate *st; + int i; + nfaarc *ar; + + printf("%c%2d%c", + istate == nf->nf_start ? '*' : ' ', + istate, + istate == nf->nf_finish ? '.' : ' '); + st = &nf->nf_state[istate]; + ar = st->st_arc; + for (i = 0; i < st->st_narcs; i++) { + if (i > 0) + printf("\n "); + printf("-> %2d %s", ar->ar_arrow, + labelrepr(&ll->ll_label[ar->ar_label])); + ar++; + } + printf("\n"); } static void dumpnfa(ll, nf) - labellist *ll; - nfa *nf; + labellist *ll; + nfa *nf; { - int i; - - printf("NFA '%s' has %d states; start %d, finish %d\n", - nf->nf_name, nf->nf_nstates, nf->nf_start, nf->nf_finish); - for (i = 0; i < nf->nf_nstates; i++) - dumpstate(ll, nf, i); + int i; + + printf("NFA '%s' has %d states; start %d, finish %d\n", + nf->nf_name, nf->nf_nstates, nf->nf_start, nf->nf_finish); + for (i = 0; i < nf->nf_nstates; i++) + dumpstate(ll, nf, i); } @@ -383,255 +383,255 @@ dumpnfa(ll, nf) static int addclosure(ss, nf, istate) - bitset ss; - nfa *nf; - int istate; + bitset ss; + nfa *nf; + int istate; { - if (addbit(ss, istate)) { - nfastate *st = &nf->nf_state[istate]; - nfaarc *ar = st->st_arc; - int i; - - for (i = st->st_narcs; --i >= 0; ) { - if (ar->ar_label == EMPTY) - addclosure(ss, nf, ar->ar_arrow); - ar++; - } - } + if (addbit(ss, istate)) { + nfastate *st = &nf->nf_state[istate]; + nfaarc *ar = st->st_arc; + int i; + + for (i = st->st_narcs; --i >= 0; ) { + if (ar->ar_label == EMPTY) + addclosure(ss, nf, ar->ar_arrow); + ar++; + } + } } typedef struct _ss_arc { - bitset sa_bitset; - int sa_arrow; - int sa_label; + bitset sa_bitset; + int sa_arrow; + int sa_label; } ss_arc; typedef struct _ss_state { - bitset ss_ss; - int ss_narcs; - ss_arc *ss_arc; - int ss_deleted; - int ss_finish; - int ss_rename; + bitset ss_ss; + int ss_narcs; + ss_arc *ss_arc; + int ss_deleted; + int ss_finish; + int ss_rename; } ss_state; typedef struct _ss_dfa { - int sd_nstates; - ss_state *sd_state; + int sd_nstates; + ss_state *sd_state; } ss_dfa; static makedfa(gr, nf, d) - nfagrammar *gr; - nfa *nf; - dfa *d; + nfagrammar *gr; + nfa *nf; + dfa *d; { - int nbits = nf->nf_nstates; - bitset ss; - int xx_nstates; - ss_state *xx_state, *yy; - ss_arc *zz; - int istate, jstate, iarc, jarc, ibit; - nfastate *st; - nfaarc *ar; - - ss = newbitset(nbits); - addclosure(ss, nf, nf->nf_start); - xx_state = NEW(ss_state, 1); - if (xx_state == NULL) - fatal("no mem for xx_state in makedfa"); - xx_nstates = 1; - yy = &xx_state[0]; - yy->ss_ss = ss; - yy->ss_narcs = 0; - yy->ss_arc = NULL; - yy->ss_deleted = 0; - yy->ss_finish = testbit(ss, nf->nf_finish); - if (yy->ss_finish) - printf("Error: nonterminal '%s' may produce empty.\n", - nf->nf_name); - - /* This algorithm is from a book written before - the invention of structured programming... */ - - /* For each unmarked state... */ - for (istate = 0; istate < xx_nstates; ++istate) { - yy = &xx_state[istate]; - ss = yy->ss_ss; - /* For all its states... */ - for (ibit = 0; ibit < nf->nf_nstates; ++ibit) { - if (!testbit(ss, ibit)) - continue; - st = &nf->nf_state[ibit]; - /* For all non-empty arcs from this state... */ - for (iarc = 0; iarc < st->st_narcs; iarc++) { - ar = &st->st_arc[iarc]; - if (ar->ar_label == EMPTY) - continue; - /* Look up in list of arcs from this state */ - for (jarc = 0; jarc < yy->ss_narcs; ++jarc) { - zz = &yy->ss_arc[jarc]; - if (ar->ar_label == zz->sa_label) - goto found; - } - /* Add new arc for this state */ - RESIZE(yy->ss_arc, ss_arc, yy->ss_narcs + 1); - if (yy->ss_arc == NULL) - fatal("out of mem"); - zz = &yy->ss_arc[yy->ss_narcs++]; - zz->sa_label = ar->ar_label; - zz->sa_bitset = newbitset(nbits); - zz->sa_arrow = -1; - found: ; - /* Add destination */ - addclosure(zz->sa_bitset, nf, ar->ar_arrow); - } - } - /* Now look up all the arrow states */ - for (jarc = 0; jarc < xx_state[istate].ss_narcs; jarc++) { - zz = &xx_state[istate].ss_arc[jarc]; - for (jstate = 0; jstate < xx_nstates; jstate++) { - if (samebitset(zz->sa_bitset, - xx_state[jstate].ss_ss, nbits)) { - zz->sa_arrow = jstate; - goto done; - } - } - RESIZE(xx_state, ss_state, xx_nstates + 1); - if (xx_state == NULL) - fatal("out of mem"); - zz->sa_arrow = xx_nstates; - yy = &xx_state[xx_nstates++]; - yy->ss_ss = zz->sa_bitset; - yy->ss_narcs = 0; - yy->ss_arc = NULL; - yy->ss_deleted = 0; - yy->ss_finish = testbit(yy->ss_ss, nf->nf_finish); - done: ; - } - } - - if (debugging) - printssdfa(xx_nstates, xx_state, nbits, &gr->gr_ll, - "before minimizing"); - - simplify(xx_nstates, xx_state); - - if (debugging) - printssdfa(xx_nstates, xx_state, nbits, &gr->gr_ll, - "after minimizing"); - - convert(d, xx_nstates, xx_state); - - /* XXX cleanup */ + int nbits = nf->nf_nstates; + bitset ss; + int xx_nstates; + ss_state *xx_state, *yy; + ss_arc *zz; + int istate, jstate, iarc, jarc, ibit; + nfastate *st; + nfaarc *ar; + + ss = newbitset(nbits); + addclosure(ss, nf, nf->nf_start); + xx_state = NEW(ss_state, 1); + if (xx_state == NULL) + fatal("no mem for xx_state in makedfa"); + xx_nstates = 1; + yy = &xx_state[0]; + yy->ss_ss = ss; + yy->ss_narcs = 0; + yy->ss_arc = NULL; + yy->ss_deleted = 0; + yy->ss_finish = testbit(ss, nf->nf_finish); + if (yy->ss_finish) + printf("Error: nonterminal '%s' may produce empty.\n", + nf->nf_name); + + /* This algorithm is from a book written before + the invention of structured programming... */ + + /* For each unmarked state... */ + for (istate = 0; istate < xx_nstates; ++istate) { + yy = &xx_state[istate]; + ss = yy->ss_ss; + /* For all its states... */ + for (ibit = 0; ibit < nf->nf_nstates; ++ibit) { + if (!testbit(ss, ibit)) + continue; + st = &nf->nf_state[ibit]; + /* For all non-empty arcs from this state... */ + for (iarc = 0; iarc < st->st_narcs; iarc++) { + ar = &st->st_arc[iarc]; + if (ar->ar_label == EMPTY) + continue; + /* Look up in list of arcs from this state */ + for (jarc = 0; jarc < yy->ss_narcs; ++jarc) { + zz = &yy->ss_arc[jarc]; + if (ar->ar_label == zz->sa_label) + goto found; + } + /* Add new arc for this state */ + RESIZE(yy->ss_arc, ss_arc, yy->ss_narcs + 1); + if (yy->ss_arc == NULL) + fatal("out of mem"); + zz = &yy->ss_arc[yy->ss_narcs++]; + zz->sa_label = ar->ar_label; + zz->sa_bitset = newbitset(nbits); + zz->sa_arrow = -1; + found: ; + /* Add destination */ + addclosure(zz->sa_bitset, nf, ar->ar_arrow); + } + } + /* Now look up all the arrow states */ + for (jarc = 0; jarc < xx_state[istate].ss_narcs; jarc++) { + zz = &xx_state[istate].ss_arc[jarc]; + for (jstate = 0; jstate < xx_nstates; jstate++) { + if (samebitset(zz->sa_bitset, + xx_state[jstate].ss_ss, nbits)) { + zz->sa_arrow = jstate; + goto done; + } + } + RESIZE(xx_state, ss_state, xx_nstates + 1); + if (xx_state == NULL) + fatal("out of mem"); + zz->sa_arrow = xx_nstates; + yy = &xx_state[xx_nstates++]; + yy->ss_ss = zz->sa_bitset; + yy->ss_narcs = 0; + yy->ss_arc = NULL; + yy->ss_deleted = 0; + yy->ss_finish = testbit(yy->ss_ss, nf->nf_finish); + done: ; + } + } + + if (debugging) + printssdfa(xx_nstates, xx_state, nbits, &gr->gr_ll, + "before minimizing"); + + simplify(xx_nstates, xx_state); + + if (debugging) + printssdfa(xx_nstates, xx_state, nbits, &gr->gr_ll, + "after minimizing"); + + convert(d, xx_nstates, xx_state); + + /* XXX cleanup */ } static printssdfa(xx_nstates, xx_state, nbits, ll, msg) - int xx_nstates; - ss_state *xx_state; - int nbits; - labellist *ll; - char *msg; + int xx_nstates; + ss_state *xx_state; + int nbits; + labellist *ll; + char *msg; { - int i, ibit, iarc; - ss_state *yy; - ss_arc *zz; - - printf("Subset DFA %s\n", msg); - for (i = 0; i < xx_nstates; i++) { - yy = &xx_state[i]; - if (yy->ss_deleted) - continue; - printf(" Subset %d", i); - if (yy->ss_finish) - printf(" (finish)"); - printf(" { "); - for (ibit = 0; ibit < nbits; ibit++) { - if (testbit(yy->ss_ss, ibit)) - printf("%d ", ibit); - } - printf("}\n"); - for (iarc = 0; iarc < yy->ss_narcs; iarc++) { - zz = &yy->ss_arc[iarc]; - printf(" Arc to state %d, label %s\n", - zz->sa_arrow, - labelrepr(&ll->ll_label[zz->sa_label])); - } - } + int i, ibit, iarc; + ss_state *yy; + ss_arc *zz; + + printf("Subset DFA %s\n", msg); + for (i = 0; i < xx_nstates; i++) { + yy = &xx_state[i]; + if (yy->ss_deleted) + continue; + printf(" Subset %d", i); + if (yy->ss_finish) + printf(" (finish)"); + printf(" { "); + for (ibit = 0; ibit < nbits; ibit++) { + if (testbit(yy->ss_ss, ibit)) + printf("%d ", ibit); + } + printf("}\n"); + for (iarc = 0; iarc < yy->ss_narcs; iarc++) { + zz = &yy->ss_arc[iarc]; + printf(" Arc to state %d, label %s\n", + zz->sa_arrow, + labelrepr(&ll->ll_label[zz->sa_label])); + } + } } /* PART THREE -- SIMPLIFY DFA */ /* Simplify the DFA by repeatedly eliminating states that are - equivalent to another oner. This is NOT Algorithm 3.3 from - [Aho&Ullman 77]. It does not always finds the minimal DFA, - but it does usually make a much smaller one... (For an example - of sub-optimal behaviour, try S: x a b+ | y a b+.) + equivalent to another oner. This is NOT Algorithm 3.3 from + [Aho&Ullman 77]. It does not always finds the minimal DFA, + but it does usually make a much smaller one... (For an example + of sub-optimal behaviour, try S: x a b+ | y a b+.) */ static int samestate(s1, s2) - ss_state *s1, *s2; + ss_state *s1, *s2; { - int i; - - if (s1->ss_narcs != s2->ss_narcs || s1->ss_finish != s2->ss_finish) - return 0; - for (i = 0; i < s1->ss_narcs; i++) { - if (s1->ss_arc[i].sa_arrow != s2->ss_arc[i].sa_arrow || - s1->ss_arc[i].sa_label != s2->ss_arc[i].sa_label) - return 0; - } - return 1; + int i; + + if (s1->ss_narcs != s2->ss_narcs || s1->ss_finish != s2->ss_finish) + return 0; + for (i = 0; i < s1->ss_narcs; i++) { + if (s1->ss_arc[i].sa_arrow != s2->ss_arc[i].sa_arrow || + s1->ss_arc[i].sa_label != s2->ss_arc[i].sa_label) + return 0; + } + return 1; } static void renamestates(xx_nstates, xx_state, from, to) - int xx_nstates; - ss_state *xx_state; - int from, to; + int xx_nstates; + ss_state *xx_state; + int from, to; { - int i, j; - - if (debugging) - printf("Rename state %d to %d.\n", from, to); - for (i = 0; i < xx_nstates; i++) { - if (xx_state[i].ss_deleted) - continue; - for (j = 0; j < xx_state[i].ss_narcs; j++) { - if (xx_state[i].ss_arc[j].sa_arrow == from) - xx_state[i].ss_arc[j].sa_arrow = to; - } - } + int i, j; + + if (debugging) + printf("Rename state %d to %d.\n", from, to); + for (i = 0; i < xx_nstates; i++) { + if (xx_state[i].ss_deleted) + continue; + for (j = 0; j < xx_state[i].ss_narcs; j++) { + if (xx_state[i].ss_arc[j].sa_arrow == from) + xx_state[i].ss_arc[j].sa_arrow = to; + } + } } static simplify(xx_nstates, xx_state) - int xx_nstates; - ss_state *xx_state; + int xx_nstates; + ss_state *xx_state; { - int changes; - int i, j, k; - - do { - changes = 0; - for (i = 1; i < xx_nstates; i++) { - if (xx_state[i].ss_deleted) - continue; - for (j = 0; j < i; j++) { - if (xx_state[j].ss_deleted) - continue; - if (samestate(&xx_state[i], &xx_state[j])) { - xx_state[i].ss_deleted++; - renamestates(xx_nstates, xx_state, i, j); - changes++; - break; - } - } - } - } while (changes); + int changes; + int i, j, k; + + do { + changes = 0; + for (i = 1; i < xx_nstates; i++) { + if (xx_state[i].ss_deleted) + continue; + for (j = 0; j < i; j++) { + if (xx_state[j].ss_deleted) + continue; + if (samestate(&xx_state[i], &xx_state[j])) { + xx_state[i].ss_deleted++; + renamestates(xx_nstates, xx_state, i, j); + changes++; + break; + } + } + } + } while (changes); } @@ -641,36 +641,36 @@ simplify(xx_nstates, xx_state) static convert(d, xx_nstates, xx_state) - dfa *d; - int xx_nstates; - ss_state *xx_state; + dfa *d; + int xx_nstates; + ss_state *xx_state; { - int i, j; - ss_state *yy; - ss_arc *zz; - - for (i = 0; i < xx_nstates; i++) { - yy = &xx_state[i]; - if (yy->ss_deleted) - continue; - yy->ss_rename = addstate(d); - } - - for (i = 0; i < xx_nstates; i++) { - yy = &xx_state[i]; - if (yy->ss_deleted) - continue; - for (j = 0; j < yy->ss_narcs; j++) { - zz = &yy->ss_arc[j]; - addarc(d, yy->ss_rename, - xx_state[zz->sa_arrow].ss_rename, - zz->sa_label); - } - if (yy->ss_finish) - addarc(d, yy->ss_rename, yy->ss_rename, 0); - } - - d->d_initial = 0; + int i, j; + ss_state *yy; + ss_arc *zz; + + for (i = 0; i < xx_nstates; i++) { + yy = &xx_state[i]; + if (yy->ss_deleted) + continue; + yy->ss_rename = addstate(d); + } + + for (i = 0; i < xx_nstates; i++) { + yy = &xx_state[i]; + if (yy->ss_deleted) + continue; + for (j = 0; j < yy->ss_narcs; j++) { + zz = &yy->ss_arc[j]; + addarc(d, yy->ss_rename, + xx_state[zz->sa_arrow].ss_rename, + zz->sa_label); + } + if (yy->ss_finish) + addarc(d, yy->ss_rename, yy->ss_rename, 0); + } + + d->d_initial = 0; } @@ -678,45 +678,45 @@ convert(d, xx_nstates, xx_state) static grammar * maketables(gr) - nfagrammar *gr; + nfagrammar *gr; { - int i; - nfa *nf; - dfa *d; - grammar *g; - - if (gr->gr_nnfas == 0) - return NULL; - g = newgrammar(gr->gr_nfa[0]->nf_type); - /* XXX first rule must be start rule */ - g->g_ll = gr->gr_ll; - - for (i = 0; i < gr->gr_nnfas; i++) { - nf = gr->gr_nfa[i]; - if (debugging) { - printf("Dump of NFA for '%s' ...\n", nf->nf_name); - dumpnfa(&gr->gr_ll, nf); - } - printf("Making DFA for '%s' ...\n", nf->nf_name); - d = adddfa(g, nf->nf_type, nf->nf_name); - makedfa(gr, gr->gr_nfa[i], d); - } - - return g; + int i; + nfa *nf; + dfa *d; + grammar *g; + + if (gr->gr_nnfas == 0) + return NULL; + g = newgrammar(gr->gr_nfa[0]->nf_type); + /* XXX first rule must be start rule */ + g->g_ll = gr->gr_ll; + + for (i = 0; i < gr->gr_nnfas; i++) { + nf = gr->gr_nfa[i]; + if (debugging) { + printf("Dump of NFA for '%s' ...\n", nf->nf_name); + dumpnfa(&gr->gr_ll, nf); + } + printf("Making DFA for '%s' ...\n", nf->nf_name); + d = adddfa(g, nf->nf_type, nf->nf_name); + makedfa(gr, gr->gr_nfa[i], d); + } + + return g; } grammar * pgen(n) - node *n; + node *n; { - nfagrammar *gr; - grammar *g; - - gr = metacompile(n); - g = maketables(gr); - translatelabels(g); - addfirstsets(g); - return g; + nfagrammar *gr; + grammar *g; + + gr = metacompile(n); + g = maketables(gr); + translatelabels(g); + addfirstsets(g); + return g; } @@ -727,25 +727,25 @@ Description Input is a grammar in extended BNF (using * for repetition, + for at-least-once repetition, [] for optional parts, | for alternatives and -() for grouping). This has already been parsed and turned into a parse +() for grouping). This has already been parsed and turned into a parse tree. Each rule is considered as a regular expression in its own right. It is turned into a Non-deterministic Finite Automaton (NFA), which is then turned into a Deterministic Finite Automaton (DFA), which is then -optimized to reduce the number of states. See [Aho&Ullman 77] chapter 3, +optimized to reduce the number of states. See [Aho&Ullman 77] chapter 3, or similar compiler books (this technique is more often used for lexical analyzers). The DFA's are used by the parser as parsing tables in a special way -that's probably unique. Before they are usable, the FIRST sets of all +that's probably unique. Before they are usable, the FIRST sets of all non-terminals are computed. Reference --------- [Aho&Ullman 77] - Aho&Ullman, Principles of Compiler Design, Addison-Wesley 1977 - (first edition) + Aho&Ullman, Principles of Compiler Design, Addison-Wesley 1977 + (first edition) */ @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. diff --git a/src/pgenheaders.h b/src/pgenheaders.h index 059915a..4712431 100644 --- a/src/pgenheaders.h +++ b/src/pgenheaders.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -23,13 +23,13 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ /* Include files and extern declarations used by most of the parser. - This is a precompiled header for THINK C. */ + This is a precompiled header for THINK C. */ #include <stdio.h> #include <string.h> #ifdef THINK_C -/* #define THINK_C_3_0 /*** TURN THIS ON FOR THINK C 3.0 ****/ +/* #define THINK_C_3_0 /*** TURN THIS ON FOR THINK C 3.0 ****/ #define label label_ #undef label #endif diff --git a/src/pgenmain.c b/src/pgenmain.c index 80f6f2d..c1bd486 100644 --- a/src/pgenmain.c +++ b/src/pgenmain.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -25,12 +25,12 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* Parser generator main program */ /* This expects a filename containing the grammar as argv[1] (UNIX) - or asks the console for such a file name (THINK C). - It writes its output on two files in the current directory: - - "graminit.c" gets the grammar as a bunch of initialized data - - "graminit.h" gets the grammar's non-terminals as #defines. - Error messages and status info during the generation process are - written to stdout, or sometimes to stderr. */ + or asks the console for such a file name (THINK C). + It writes its output on two files in the current directory: + - "graminit.c" gets the grammar as a bunch of initialized data + - "graminit.h" gets the grammar's non-terminals as #defines. + Error messages and status info during the generation process are + written to stdout, or sometimes to stderr. */ #include "pgenheaders.h" #include "grammar.h" @@ -49,100 +49,100 @@ char *askfile PROTO((void)); int main(argc, argv) - int argc; - char **argv; + int argc; + char **argv; { - grammar *g; - node *n; - FILE *fp; - char *filename; - + grammar *g; + node *n; + FILE *fp; + char *filename; + #ifdef THINK_C - filename = askfile(); + filename = askfile(); #else - if (argc != 2) { - fprintf(stderr, "usage: %s grammar\n", argv[0]); - exit(2); - } - filename = argv[1]; + if (argc != 2) { + fprintf(stderr, "usage: %s grammar\n", argv[0]); + exit(2); + } + filename = argv[1]; #endif - g = getgrammar(filename); - fp = fopen("graminit.c", "w"); - if (fp == NULL) { - perror("graminit.c"); - exit(1); - } - printf("Writing graminit.c ...\n"); - printgrammar(g, fp); - fclose(fp); - fp = fopen("graminit.h", "w"); - if (fp == NULL) { - perror("graminit.h"); - exit(1); - } - printf("Writing graminit.h ...\n"); - printnonterminals(g, fp); - fclose(fp); - exit(0); + g = getgrammar(filename); + fp = fopen("graminit.c", "w"); + if (fp == NULL) { + perror("graminit.c"); + exit(1); + } + printf("Writing graminit.c ...\n"); + printgrammar(g, fp); + fclose(fp); + fp = fopen("graminit.h", "w"); + if (fp == NULL) { + perror("graminit.h"); + exit(1); + } + printf("Writing graminit.h ...\n"); + printnonterminals(g, fp); + fclose(fp); + exit(0); } grammar * getgrammar(filename) - char *filename; + char *filename; { - FILE *fp; - node *n; - grammar *g0, *g; - - fp = fopen(filename, "r"); - if (fp == NULL) { - perror(filename); - exit(1); - } - g0 = meta_grammar(); - n = NULL; - parsefile(fp, filename, g0, g0->g_start, (char *)NULL, (char *)NULL, &n); - fclose(fp); - if (n == NULL) { - fprintf(stderr, "Parsing error.\n"); - exit(1); - } - g = pgen(n); - if (g == NULL) { - printf("Bad grammar.\n"); - exit(1); - } - return g; + FILE *fp; + node *n; + grammar *g0, *g; + + fp = fopen(filename, "r"); + if (fp == NULL) { + perror(filename); + exit(1); + } + g0 = meta_grammar(); + n = NULL; + parsefile(fp, filename, g0, g0->g_start, (char *)NULL, (char *)NULL, &n); + fclose(fp); + if (n == NULL) { + fprintf(stderr, "Parsing error.\n"); + exit(1); + } + g = pgen(n); + if (g == NULL) { + printf("Bad grammar.\n"); + exit(1); + } + return g; } #ifdef THINK_C char * askfile() { - char buf[256]; - static char name[256]; - printf("Input file name: "); - if (fgets(buf, sizeof buf, stdin) == NULL) { - printf("EOF\n"); - exit(1); - } - /* XXX The (unsigned char *) case is needed by THINK C 3.0 */ - if (sscanf(/*(unsigned char *)*/buf, " %s ", name) != 1) { - printf("No file\n"); - exit(1); - } - return name; + char buf[256]; + static char name[256]; + printf("Input file name: "); + if (fgets(buf, sizeof buf, stdin) == NULL) { + printf("EOF\n"); + exit(1); + } + /* XXX The (unsigned char *) case is needed by THINK C 3.0 */ + if (sscanf(/*(unsigned char *)*/buf, " %s ", name) != 1) { + printf("No file\n"); + exit(1); + } + return name; } #endif void fatal(msg) - char *msg; + char *msg; { - fprintf(stderr, "pgen: FATAL ERROR: %s\n", msg); - exit(1); + fprintf(stderr, "pgen: FATAL ERROR: %s\n", msg); + exit(1); } /* XXX TO DO: - - check for duplicate definitions of names (instead of fatal err) + - check for duplicate definitions of names (instead of fatal err) */ diff --git a/src/posixmodule.c b/src/posixmodule.c index 9729376..3e7b0cd 100644 --- a/src/posixmodule.c +++ b/src/posixmodule.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -54,28 +54,28 @@ extern char **environ; static object * convertenviron() { - object *d; - char **e; - d = newdictobject(); - if (d == NULL) - return NULL; - if (environ == NULL) - return d; - /* XXX This part ignores errors */ - for (e = environ; *e != NULL; e++) { - object *v; - char *p = strchr(*e, '='); - if (p == NULL) - continue; - v = newstringobject(p+1); - if (v == NULL) - continue; - *p = '\0'; - (void) dictinsert(d, *e, v); - *p = '='; - DECREF(v); - } - return d; + object *d; + char **e; + d = newdictobject(); + if (d == NULL) + return NULL; + if (environ == NULL) + return d; + /* XXX This part ignores errors */ + for (e = environ; *e != NULL; e++) { + object *v; + char *p = strchr(*e, '='); + if (p == NULL) + continue; + v = newstringobject(p+1); + if (v == NULL) + continue; + *p = '\0'; + (void) dictinsert(d, *e, v); + *p = '='; + DECREF(v); + } + return d; } @@ -86,7 +86,7 @@ static object *PosixError; /* Exception posix.error */ static object * posix_error() { - return err_errno(PosixError); + return err_errno(PosixError); } @@ -94,80 +94,80 @@ posix_error() static object * posix_1str(args, func) - object *args; - int (*func) FPROTO((const char *)); + object *args; + int (*func) FPROTO((const char *)); { - object *path1; - if (!getstrarg(args, &path1)) - return NULL; - if ((*func)(getstringvalue(path1)) < 0) - return posix_error(); - INCREF(None); - return None; + object *path1; + if (!getstrarg(args, &path1)) + return NULL; + if ((*func)(getstringvalue(path1)) < 0) + return posix_error(); + INCREF(None); + return None; } static object * posix_2str(args, func) - object *args; - int (*func) FPROTO((const char *, const char *)); + object *args; + int (*func) FPROTO((const char *, const char *)); { - object *path1, *path2; - if (!getstrstrarg(args, &path1, &path2)) - return NULL; - if ((*func)(getstringvalue(path1), getstringvalue(path2)) < 0) - return posix_error(); - INCREF(None); - return None; + object *path1, *path2; + if (!getstrstrarg(args, &path1, &path2)) + return NULL; + if ((*func)(getstringvalue(path1), getstringvalue(path2)) < 0) + return posix_error(); + INCREF(None); + return None; } static object * posix_strint(args, func) - object *args; - int (*func) FPROTO((const char *, int)); + object *args; + int (*func) FPROTO((const char *, int)); { - object *path1; - int i; - if (!getstrintarg(args, &path1, &i)) - return NULL; - if ((*func)(getstringvalue(path1), i) < 0) - return posix_error(); - INCREF(None); - return None; + object *path1; + int i; + if (!getstrintarg(args, &path1, &i)) + return NULL; + if ((*func)(getstringvalue(path1), i) < 0) + return posix_error(); + INCREF(None); + return None; } static object * posix_do_stat(self, args, statfunc) - object *self; - object *args; - int (*statfunc) FPROTO((const char *, struct stat *)); + object *self; + object *args; + int (*statfunc) FPROTO((const char *, struct stat *)); { - struct stat st; - object *path; - object *v; - if (!getstrarg(args, &path)) - return NULL; - if ((*statfunc)(getstringvalue(path), &st) != 0) - return posix_error(); - v = newtupleobject(10); - if (v == NULL) - return NULL; + struct stat st; + object *path; + object *v; + if (!getstrarg(args, &path)) + return NULL; + if ((*statfunc)(getstringvalue(path), &st) != 0) + return posix_error(); + v = newtupleobject(10); + if (v == NULL) + return NULL; #define SET(i, st_member) settupleitem(v, i, newintobject((long)st.st_member)) - SET(0, st_mode); - SET(1, st_ino); - SET(2, st_dev); - SET(3, st_nlink); - SET(4, st_uid); - SET(5, st_gid); - SET(6, st_size); - SET(7, st_atime); - SET(8, st_mtime); - SET(9, st_ctime); + SET(0, st_mode); + SET(1, st_ino); + SET(2, st_dev); + SET(3, st_nlink); + SET(4, st_uid); + SET(5, st_gid); + SET(6, st_size); + SET(7, st_atime); + SET(8, st_mtime); + SET(9, st_ctime); #undef SET - if (err_occurred()) { - DECREF(v); - return NULL; - } - return v; + if (err_occurred()) { + DECREF(v); + return NULL; + } + return v; } @@ -175,172 +175,172 @@ posix_do_stat(self, args, statfunc) static object * posix_chdir(self, args) - object *self; - object *args; + object *self; + object *args; { - extern int chdir PROTO((const char *)); - return posix_1str(args, chdir); + extern int chdir PROTO((const char *)); + return posix_1str(args, chdir); } static object * posix_chmod(self, args) - object *self; - object *args; + object *self; + object *args; { - extern int chmod PROTO((const char *, mode_t)); - return posix_strint(args, chmod); + extern int chmod PROTO((const char *, mode_t)); + return posix_strint(args, chmod); } static object * posix_getcwd(self, args) - object *self; - object *args; + object *self; + object *args; { - char buf[1026]; - extern char *getcwd PROTO((char *, int)); - if (!getnoarg(args)) - return NULL; - if (getcwd(buf, sizeof buf) == NULL) - return posix_error(); - return newstringobject(buf); + char buf[1026]; + extern char *getcwd PROTO((char *, int)); + if (!getnoarg(args)) + return NULL; + if (getcwd(buf, sizeof buf) == NULL) + return posix_error(); + return newstringobject(buf); } static object * posix_link(self, args) - object *self; - object *args; + object *self; + object *args; { - extern int link PROTO((const char *, const char *)); - return posix_2str(args, link); + extern int link PROTO((const char *, const char *)); + return posix_2str(args, link); } static object * posix_listdir(self, args) - object *self; - object *args; + object *self; + object *args; { - object *name, *d, *v; - DIR *dirp; - struct direct *ep; - if (!getstrarg(args, &name)) - return NULL; - if ((dirp = opendir(getstringvalue(name))) == NULL) - return posix_error(); - if ((d = newlistobject(0)) == NULL) { - closedir(dirp); - return NULL; - } - while ((ep = readdir(dirp)) != NULL) { - v = newstringobject(ep->d_name); - if (v == NULL) { - DECREF(d); - d = NULL; - break; - } - if (addlistitem(d, v) != 0) { - DECREF(v); - DECREF(d); - d = NULL; - break; - } - DECREF(v); - } - closedir(dirp); - return d; + object *name, *d, *v; + DIR *dirp; + struct direct *ep; + if (!getstrarg(args, &name)) + return NULL; + if ((dirp = opendir(getstringvalue(name))) == NULL) + return posix_error(); + if ((d = newlistobject(0)) == NULL) { + closedir(dirp); + return NULL; + } + while ((ep = readdir(dirp)) != NULL) { + v = newstringobject(ep->d_name); + if (v == NULL) { + DECREF(d); + d = NULL; + break; + } + if (addlistitem(d, v) != 0) { + DECREF(v); + DECREF(d); + d = NULL; + break; + } + DECREF(v); + } + closedir(dirp); + return d; } static object * posix_mkdir(self, args) - object *self; - object *args; + object *self; + object *args; { - extern int mkdir PROTO((const char *, mode_t)); - return posix_strint(args, mkdir); + extern int mkdir PROTO((const char *, mode_t)); + return posix_strint(args, mkdir); } static object * posix_rename(self, args) - object *self; - object *args; + object *self; + object *args; { - extern int rename PROTO((const char *, const char *)); - return posix_2str(args, rename); + extern int rename PROTO((const char *, const char *)); + return posix_2str(args, rename); } static object * posix_rmdir(self, args) - object *self; - object *args; + object *self; + object *args; { - extern int rmdir PROTO((const char *)); - return posix_1str(args, rmdir); + extern int rmdir PROTO((const char *)); + return posix_1str(args, rmdir); } static object * posix_stat(self, args) - object *self; - object *args; + object *self; + object *args; { - extern int stat PROTO((const char *, struct stat *)); - return posix_do_stat(self, args, stat); + extern int stat PROTO((const char *, struct stat *)); + return posix_do_stat(self, args, stat); } static object * posix_system(self, args) - object *self; - object *args; + object *self; + object *args; { - object *command; - int sts; - if (!getstrarg(args, &command)) - return NULL; - sts = system(getstringvalue(command)); - return newintobject((long)sts); + object *command; + int sts; + if (!getstrarg(args, &command)) + return NULL; + sts = system(getstringvalue(command)); + return newintobject((long)sts); } static object * posix_umask(self, args) - object *self; - object *args; + object *self; + object *args; { - int i; - if (!getintarg(args, &i)) - return NULL; - i = umask(i); - if (i < 0) - return posix_error(); - return newintobject((long)i); + int i; + if (!getintarg(args, &i)) + return NULL; + i = umask(i); + if (i < 0) + return posix_error(); + return newintobject((long)i); } static object * posix_unlink(self, args) - object *self; - object *args; + object *self; + object *args; { - extern int unlink PROTO((const char *)); - return posix_1str(args, unlink); + extern int unlink PROTO((const char *)); + return posix_1str(args, unlink); } static object * posix_utimes(self, args) - object *self; - object *args; + object *self; + object *args; { - object *path; - struct timeval tv[2]; - if (args == NULL || !is_tupleobject(args) || gettuplesize(args) != 2) { - err_badarg(); - return NULL; - } - if (!getstrarg(gettupleitem(args, 0), &path) || - !getlonglongargs(gettupleitem(args, 1), - &tv[0].tv_sec, &tv[1].tv_sec)) - return NULL; - tv[0].tv_usec = tv[1].tv_usec = 0; - if (utimes(getstringvalue(path), tv) < 0) - return posix_error(); - INCREF(None); - return None; + object *path; + struct timeval tv[2]; + if (args == NULL || !is_tupleobject(args) || gettuplesize(args) != 2) { + err_badarg(); + return NULL; + } + if (!getstrarg(gettupleitem(args, 0), &path) || + !getlonglongargs(gettupleitem(args, 1), + &tv[0].tv_sec, &tv[1].tv_sec)) + return NULL; + tv[0].tv_usec = tv[1].tv_usec = 0; + if (utimes(getstringvalue(path), tv) < 0) + return posix_error(); + INCREF(None); + return None; } @@ -348,80 +348,80 @@ posix_utimes(self, args) static object * posix_lstat(self, args) - object *self; - object *args; + object *self; + object *args; { - extern int lstat PROTO((const char *, struct stat *)); - return posix_do_stat(self, args, lstat); + extern int lstat PROTO((const char *, struct stat *)); + return posix_do_stat(self, args, lstat); } static object * posix_readlink(self, args) - object *self; - object *args; + object *self; + object *args; { - char buf[1024]; /* XXX Should use MAXPATHLEN */ - object *path; - int n; - if (!getstrarg(args, &path)) - return NULL; - n = readlink(getstringvalue(path), buf, sizeof buf); - if (n < 0) - return posix_error(); - return newsizedstringobject(buf, n); + char buf[1024]; /* XXX Should use MAXPATHLEN */ + object *path; + int n; + if (!getstrarg(args, &path)) + return NULL; + n = readlink(getstringvalue(path), buf, sizeof buf); + if (n < 0) + return posix_error(); + return newsizedstringobject(buf, n); } static object * posix_symlink(self, args) - object *self; - object *args; + object *self; + object *args; { - extern int symlink PROTO((const char *, const char *)); - return posix_2str(args, symlink); + extern int symlink PROTO((const char *, const char *)); + return posix_2str(args, symlink); } #endif /* NO_LSTAT */ static struct methodlist posix_methods[] = { - {"chdir", posix_chdir}, - {"chmod", posix_chmod}, - {"getcwd", posix_getcwd}, - {"link", posix_link}, - {"listdir", posix_listdir}, - {"mkdir", posix_mkdir}, - {"rename", posix_rename}, - {"rmdir", posix_rmdir}, - {"stat", posix_stat}, - {"system", posix_system}, - {"umask", posix_umask}, - {"unlink", posix_unlink}, - {"utimes", posix_utimes}, + {"chdir", posix_chdir}, + {"chmod", posix_chmod}, + {"getcwd", posix_getcwd}, + {"link", posix_link}, + {"listdir", posix_listdir}, + {"mkdir", posix_mkdir}, + {"rename", posix_rename}, + {"rmdir", posix_rmdir}, + {"stat", posix_stat}, + {"system", posix_system}, + {"umask", posix_umask}, + {"unlink", posix_unlink}, + {"utimes", posix_utimes}, #ifndef NO_LSTAT - {"lstat", posix_lstat}, - {"readlink", posix_readlink}, - {"symlink", posix_symlink}, + {"lstat", posix_lstat}, + {"readlink", posix_readlink}, + {"symlink", posix_symlink}, #endif - {NULL, NULL} /* Sentinel */ + {NULL, NULL} /* Sentinel */ }; void initposix() { - object *m, *d, *v; - - m = initmodule("posix", posix_methods); - d = getmoduledict(m); - - /* Initialize posix.environ dictionary */ - v = convertenviron(); - if (v == NULL || dictinsert(d, "environ", v) != 0) - fatal("can't define posix.environ"); - DECREF(v); - - /* Initialize posix.error exception */ - PosixError = newstringobject("posix.error"); - if (PosixError == NULL || dictinsert(d, "error", PosixError) != 0) - fatal("can't define posix.error"); + object *m, *d, *v; + + m = initmodule("posix", posix_methods); + d = getmoduledict(m); + + /* Initialize posix.environ dictionary */ + v = convertenviron(); + if (v == NULL || dictinsert(d, "environ", v) != 0) + fatal("can't define posix.environ"); + DECREF(v); + + /* Initialize posix.error exception */ + PosixError = newstringobject("posix.error"); + if (PosixError == NULL || dictinsert(d, "error", PosixError) != 0) + fatal("can't define posix.error"); } diff --git a/src/printgrammar.c b/src/printgrammar.c index c48262d..a9845a3 100644 --- a/src/printgrammar.c +++ b/src/printgrammar.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -35,115 +35,115 @@ static void printlabels PROTO((grammar *, FILE *)); void printgrammar(g, fp) - grammar *g; - FILE *fp; + grammar *g; + FILE *fp; { - fprintf(fp, "#include \"pgenheaders.h\"\n"); - fprintf(fp, "#include \"grammar.h\"\n"); - printdfas(g, fp); - printlabels(g, fp); - fprintf(fp, "grammar gram = {\n"); - fprintf(fp, "\t%d,\n", g->g_ndfas); - fprintf(fp, "\tdfas,\n"); - fprintf(fp, "\t{%d, labels},\n", g->g_ll.ll_nlabels); - fprintf(fp, "\t%d\n", g->g_start); - fprintf(fp, "};\n"); + fprintf(fp, "#include \"pgenheaders.h\"\n"); + fprintf(fp, "#include \"grammar.h\"\n"); + printdfas(g, fp); + printlabels(g, fp); + fprintf(fp, "grammar gram = {\n"); + fprintf(fp, "\t%d,\n", g->g_ndfas); + fprintf(fp, "\tdfas,\n"); + fprintf(fp, "\t{%d, labels},\n", g->g_ll.ll_nlabels); + fprintf(fp, "\t%d\n", g->g_start); + fprintf(fp, "};\n"); } void printnonterminals(g, fp) - grammar *g; - FILE *fp; + grammar *g; + FILE *fp; { - dfa *d; - int i; - - d = g->g_dfa; - for (i = g->g_ndfas; --i >= 0; d++) - fprintf(fp, "#define %s %d\n", d->d_name, d->d_type); + dfa *d; + int i; + + d = g->g_dfa; + for (i = g->g_ndfas; --i >= 0; d++) + fprintf(fp, "#define %s %d\n", d->d_name, d->d_type); } static void printarcs(i, d, fp) - int i; - dfa *d; - FILE *fp; + int i; + dfa *d; + FILE *fp; { - arc *a; - state *s; - int j, k; - - s = d->d_state; - for (j = 0; j < d->d_nstates; j++, s++) { - fprintf(fp, "static arc arcs_%d_%d[%d] = {\n", - i, j, s->s_narcs); - a = s->s_arc; - for (k = 0; k < s->s_narcs; k++, a++) - fprintf(fp, "\t{%d, %d},\n", a->a_lbl, a->a_arrow); - fprintf(fp, "};\n"); - } + arc *a; + state *s; + int j, k; + + s = d->d_state; + for (j = 0; j < d->d_nstates; j++, s++) { + fprintf(fp, "static arc arcs_%d_%d[%d] = {\n", + i, j, s->s_narcs); + a = s->s_arc; + for (k = 0; k < s->s_narcs; k++, a++) + fprintf(fp, "\t{%d, %d},\n", a->a_lbl, a->a_arrow); + fprintf(fp, "};\n"); + } } static void printstates(g, fp) - grammar *g; - FILE *fp; + grammar *g; + FILE *fp; { - state *s; - dfa *d; - int i, j; - - d = g->g_dfa; - for (i = 0; i < g->g_ndfas; i++, d++) { - printarcs(i, d, fp); - fprintf(fp, "static state states_%d[%d] = {\n", - i, d->d_nstates); - s = d->d_state; - for (j = 0; j < d->d_nstates; j++, s++) - fprintf(fp, "\t{%d, arcs_%d_%d},\n", - s->s_narcs, i, j); - fprintf(fp, "};\n"); - } + state *s; + dfa *d; + int i, j; + + d = g->g_dfa; + for (i = 0; i < g->g_ndfas; i++, d++) { + printarcs(i, d, fp); + fprintf(fp, "static state states_%d[%d] = {\n", + i, d->d_nstates); + s = d->d_state; + for (j = 0; j < d->d_nstates; j++, s++) + fprintf(fp, "\t{%d, arcs_%d_%d},\n", + s->s_narcs, i, j); + fprintf(fp, "};\n"); + } } static void printdfas(g, fp) - grammar *g; - FILE *fp; + grammar *g; + FILE *fp; { - dfa *d; - int i, j; - - printstates(g, fp); - fprintf(fp, "static dfa dfas[%d] = {\n", g->g_ndfas); - d = g->g_dfa; - for (i = 0; i < g->g_ndfas; i++, d++) { - fprintf(fp, "\t{%d, \"%s\", %d, %d, states_%d,\n", - d->d_type, d->d_name, d->d_initial, d->d_nstates, i); - fprintf(fp, "\t \""); - for (j = 0; j < NBYTES(g->g_ll.ll_nlabels); j++) - fprintf(fp, "\\%03o", d->d_first[j] & 0xff); - fprintf(fp, "\"},\n"); - } - fprintf(fp, "};\n"); + dfa *d; + int i, j; + + printstates(g, fp); + fprintf(fp, "static dfa dfas[%d] = {\n", g->g_ndfas); + d = g->g_dfa; + for (i = 0; i < g->g_ndfas; i++, d++) { + fprintf(fp, "\t{%d, \"%s\", %d, %d, states_%d,\n", + d->d_type, d->d_name, d->d_initial, d->d_nstates, i); + fprintf(fp, "\t \""); + for (j = 0; j < NBYTES(g->g_ll.ll_nlabels); j++) + fprintf(fp, "\\%03o", d->d_first[j] & 0xff); + fprintf(fp, "\"},\n"); + } + fprintf(fp, "};\n"); } static void printlabels(g, fp) - grammar *g; - FILE *fp; + grammar *g; + FILE *fp; { - label *l; - int i; - - fprintf(fp, "static label labels[%d] = {\n", g->g_ll.ll_nlabels); - l = g->g_ll.ll_label; - for (i = g->g_ll.ll_nlabels; --i >= 0; l++) { - if (l->lb_str == NULL) - fprintf(fp, "\t{%d, 0},\n", l->lb_type); - else - fprintf(fp, "\t{%d, \"%s\"},\n", - l->lb_type, l->lb_str); - } - fprintf(fp, "};\n"); + label *l; + int i; + + fprintf(fp, "static label labels[%d] = {\n", g->g_ll.ll_nlabels); + l = g->g_ll.ll_label; + for (i = g->g_ll.ll_nlabels; --i >= 0; l++) { + if (l->lb_str == NULL) + fprintf(fp, "\t{%d, 0},\n", l->lb_type); + else + fprintf(fp, "\t{%d, \"%s\"},\n", + l->lb_type, l->lb_str); + } + fprintf(fp, "};\n"); } diff --git a/src/profmain.c b/src/profmain.c index eff57bf..d8d7211 100644 --- a/src/profmain.c +++ b/src/profmain.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -42,92 +42,92 @@ int debugging = 1; FILE *getopenfile() { - char buf[256]; - char *p; - FILE *fp; - for (;;) { - fprintf(stderr, "File name: "); - if (fgets(buf, sizeof buf, stdin) == NULL) { - fprintf(stderr, "EOF\n"); - exit(1); - } - p = strchr(buf, '\n'); - if (p != NULL) - *p = '\0'; - if ((fp = fopen(buf, "r")) != NULL) - break; - fprintf(stderr, "Sorry, try again.\n"); - } - return fp; + char buf[256]; + char *p; + FILE *fp; + for (;;) { + fprintf(stderr, "File name: "); + if (fgets(buf, sizeof buf, stdin) == NULL) { + fprintf(stderr, "EOF\n"); + exit(1); + } + p = strchr(buf, '\n'); + if (p != NULL) + *p = '\0'; + if ((fp = fopen(buf, "r")) != NULL) + break; + fprintf(stderr, "Sorry, try again.\n"); + } + return fp; } main() { - FILE *fp; - _profile = 0; - fp = getopenfile(); + FILE *fp; + _profile = 0; + fp = getopenfile(); #if 0 - askgo("Start tokenizing"); - runtokenizer(fp); - fseek(fp, 0L, 0); + askgo("Start tokenizing"); + runtokenizer(fp); + fseek(fp, 0L, 0); #endif - if (!gram.g_accel) - addaccelerators(&gram); - askgo("Start parsing"); - _profile = 1; - runparser(fp); - _profile = 0; - freopen("prof.out", "w", stdout); - DumpProfile(); - fflush(stdout); - exit(0); + if (!gram.g_accel) + addaccelerators(&gram); + askgo("Start parsing"); + _profile = 1; + runparser(fp); + _profile = 0; + freopen("prof.out", "w", stdout); + DumpProfile(); + fflush(stdout); + exit(0); } static int runtokenizer(fp) - FILE *fp; + FILE *fp; { - struct tok_state *tok; - tok = tok_setupf(fp, "Tokenizing", "."); - for (;;) { - char *a, *b; - register char *str; - register int len; - (void) tok_get(tok, &a, &b); - if (tok->done != E_OK) - break; - len = b - a; - str = NEW(char, len + 1); - if (str == NULL) { - fprintf(stderr, "no mem for next token"); - break; - } - strncpy(str, a, len); - str[len] = '\0'; - } - fprintf(stderr, "done (%d)\n", tok->done); + struct tok_state *tok; + tok = tok_setupf(fp, "Tokenizing", "."); + for (;;) { + char *a, *b; + register char *str; + register int len; + (void) tok_get(tok, &a, &b); + if (tok->done != E_OK) + break; + len = b - a; + str = NEW(char, len + 1); + if (str == NULL) { + fprintf(stderr, "no mem for next token"); + break; + } + strncpy(str, a, len); + str[len] = '\0'; + } + fprintf(stderr, "done (%d)\n", tok->done); } static runparser(fp, start) - FILE *fp; + FILE *fp; { - node *n; - int ret; - ret = parsefile(fp, &gram, module_input, "Parsing", ".", &n); - fprintf(stderr, "done (%d)\n", ret); + node *n; + int ret; + ret = parsefile(fp, &gram, module_input, "Parsing", ".", &n); + fprintf(stderr, "done (%d)\n", ret); #if 0 - _profile = 0; - if (ret == E_DONE) - listtree(n); + _profile = 0; + if (ret == E_DONE) + listtree(n); #endif } static int askgo(prompt) - char *prompt; + char *prompt; { - char buf[256]; - fprintf(stderr, "%s: hit return when ready: ", prompt); - fgets(buf, sizeof buf, stdin); + char buf[256]; + fprintf(stderr, "%s: hit return when ready: ", prompt); + fgets(buf, sizeof buf, stdin); } diff --git a/src/pythonmain.c b/src/pythonmain.c index 8c86d8c..aee8664 100644 --- a/src/pythonmain.c +++ b/src/pythonmain.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -48,32 +48,32 @@ int debugging; /* Needed by parser.c */ #endif main(argc, argv) - int argc; - char **argv; + int argc; + char **argv; { - char *filename = NULL; - FILE *fp = stdin; - - initargs(&argc, &argv); - - if (argc > 1 && strcmp(argv[1], "-") != 0) - filename = argv[1]; - - if (filename != NULL) { - if ((fp = fopen(filename, "r")) == NULL) { - fprintf(stderr, "python: can't open file '%s'\n", - filename); - exit(2); - } - } - - initall(); - - setpythonpath(getpythonpath()); - setpythonargv(argc-1, argv+1); - - goaway(run(fp, filename == NULL ? "<stdin>" : filename)); - /*NOTREACHED*/ + char *filename = NULL; + FILE *fp = stdin; + + initargs(&argc, &argv); + + if (argc > 1 && strcmp(argv[1], "-") != 0) + filename = argv[1]; + + if (filename != NULL) { + if ((fp = fopen(filename, "r")) == NULL) { + fprintf(stderr, "python: can't open file '%s'\n", + filename); + exit(2); + } + } + + initall(); + + setpythonpath(getpythonpath()); + setpythonargv(argc-1, argv+1); + + goaway(run(fp, filename == NULL ? "<stdin>" : filename)); + /*NOTREACHED*/ } /* Initialize all */ @@ -81,321 +81,321 @@ main(argc, argv) void initall() { - static int inited; - - if (inited) - return; - inited = 1; - - initimport(); - - /* Modules 'builtin' and 'sys' are initialized here, - they are needed by random bits of the interpreter. - All other modules are optional and should be initialized - by the initcalls() of a specific configuration. */ - - initbuiltin(); /* Also initializes builtin exceptions */ - initsys(); - - initcalls(); /* Configuration-dependent initializations */ - - initintr(); /* For intrcheck() */ + static int inited; + + if (inited) + return; + inited = 1; + + initimport(); + + /* Modules 'builtin' and 'sys' are initialized here, + they are needed by random bits of the interpreter. + All other modules are optional and should be initialized + by the initcalls() of a specific configuration. */ + + initbuiltin(); /* Also initializes builtin exceptions */ + initsys(); + + initcalls(); /* Configuration-dependent initializations */ + + initintr(); /* For intrcheck() */ } /* Parse input from a file and execute it */ int run(fp, filename) - FILE *fp; - char *filename; + FILE *fp; + char *filename; { - if (filename == NULL) - filename = "???"; - if (isatty(fileno(fp))) - return run_tty_loop(fp, filename); - else - return run_script(fp, filename); + if (filename == NULL) + filename = "???"; + if (isatty(fileno(fp))) + return run_tty_loop(fp, filename); + else + return run_script(fp, filename); } int run_tty_loop(fp, filename) - FILE *fp; - char *filename; + FILE *fp; + char *filename; { - object *v; - int ret; - v = sysget("ps1"); - if (v == NULL) { - sysset("ps1", v = newstringobject(">>> ")); - XDECREF(v); - } - v = sysget("ps2"); - if (v == NULL) { - sysset("ps2", v = newstringobject("... ")); - XDECREF(v); - } - for (;;) { - ret = run_tty_1(fp, filename); + object *v; + int ret; + v = sysget("ps1"); + if (v == NULL) { + sysset("ps1", v = newstringobject(">>> ")); + XDECREF(v); + } + v = sysget("ps2"); + if (v == NULL) { + sysset("ps2", v = newstringobject("... ")); + XDECREF(v); + } + for (;;) { + ret = run_tty_1(fp, filename); #ifdef REF_DEBUG - fprintf(stderr, "[%ld refs]\n", ref_total); + fprintf(stderr, "[%ld refs]\n", ref_total); #endif - if (ret == E_EOF) - return 0; - /* - if (ret == E_NOMEM) - return -1; - */ - } + if (ret == E_EOF) + return 0; + /* + if (ret == E_NOMEM) + return -1; + */ + } } int run_tty_1(fp, filename) - FILE *fp; - char *filename; + FILE *fp; + char *filename; { - object *m, *d, *v, *w; - node *n; - char *ps1, *ps2; - int err; - v = sysget("ps1"); - w = sysget("ps2"); - if (v != NULL && is_stringobject(v)) { - INCREF(v); - ps1 = getstringvalue(v); - } - else { - v = NULL; - ps1 = ""; - } - if (w != NULL && is_stringobject(w)) { - INCREF(w); - ps2 = getstringvalue(w); - } - else { - w = NULL; - ps2 = ""; - } - err = parsefile(fp, filename, &gram, single_input, ps1, ps2, &n); - XDECREF(v); - XDECREF(w); - if (err == E_EOF) - return E_EOF; - if (err != E_DONE) { - err_input(err); - print_error(); - return err; - } - m = add_module("__main__"); - if (m == NULL) - return -1; - d = getmoduledict(m); - v = run_node(n, filename, d, d); - flushline(); - if (v == NULL) { - print_error(); - return -1; - } - DECREF(v); - return 0; + object *m, *d, *v, *w; + node *n; + char *ps1, *ps2; + int err; + v = sysget("ps1"); + w = sysget("ps2"); + if (v != NULL && is_stringobject(v)) { + INCREF(v); + ps1 = getstringvalue(v); + } + else { + v = NULL; + ps1 = ""; + } + if (w != NULL && is_stringobject(w)) { + INCREF(w); + ps2 = getstringvalue(w); + } + else { + w = NULL; + ps2 = ""; + } + err = parsefile(fp, filename, &gram, single_input, ps1, ps2, &n); + XDECREF(v); + XDECREF(w); + if (err == E_EOF) + return E_EOF; + if (err != E_DONE) { + err_input(err); + print_error(); + return err; + } + m = add_module("__main__"); + if (m == NULL) + return -1; + d = getmoduledict(m); + v = run_node(n, filename, d, d); + flushline(); + if (v == NULL) { + print_error(); + return -1; + } + DECREF(v); + return 0; } int run_script(fp, filename) - FILE *fp; - char *filename; + FILE *fp; + char *filename; { - object *m, *d, *v; - m = add_module("__main__"); - if (m == NULL) - return -1; - d = getmoduledict(m); - v = run_file(fp, filename, file_input, d, d); - flushline(); - if (v == NULL) { - print_error(); - return -1; - } - DECREF(v); - return 0; + object *m, *d, *v; + m = add_module("__main__"); + if (m == NULL) + return -1; + d = getmoduledict(m); + v = run_file(fp, filename, file_input, d, d); + flushline(); + if (v == NULL) { + print_error(); + return -1; + } + DECREF(v); + return 0; } void print_error() { - object *exception, *v; - err_get(&exception, &v); - fprintf(stderr, "Unhandled exception: "); - printobject(exception, stderr, PRINT_RAW); - if (v != NULL && v != None) { - fprintf(stderr, ": "); - printobject(v, stderr, PRINT_RAW); - } - fprintf(stderr, "\n"); - XDECREF(exception); - XDECREF(v); - printtraceback(stderr); + object *exception, *v; + err_get(&exception, &v); + fprintf(stderr, "Unhandled exception: "); + printobject(exception, stderr, PRINT_RAW); + if (v != NULL && v != None) { + fprintf(stderr, ": "); + printobject(v, stderr, PRINT_RAW); + } + fprintf(stderr, "\n"); + XDECREF(exception); + XDECREF(v); + printtraceback(stderr); } object * run_string(str, start, globals, locals) - char *str; - int start; - /*dict*/object *globals, *locals; + char *str; + int start; + /*dict*/object *globals, *locals; { - node *n; - int err; - err = parse_string(str, start, &n); - return run_err_node(err, n, "<string>", globals, locals); + node *n; + int err; + err = parse_string(str, start, &n); + return run_err_node(err, n, "<string>", globals, locals); } object * run_file(fp, filename, start, globals, locals) - FILE *fp; - char *filename; - int start; - /*dict*/object *globals, *locals; + FILE *fp; + char *filename; + int start; + /*dict*/object *globals, *locals; { - node *n; - int err; - err = parse_file(fp, filename, start, &n); - return run_err_node(err, n, filename, globals, locals); + node *n; + int err; + err = parse_file(fp, filename, start, &n); + return run_err_node(err, n, filename, globals, locals); } object * run_err_node(err, n, filename, globals, locals) - int err; - node *n; - char *filename; - /*dict*/object *globals, *locals; + int err; + node *n; + char *filename; + /*dict*/object *globals, *locals; { - if (err != E_DONE) { - err_input(err); - return NULL; - } - return run_node(n, filename, globals, locals); + if (err != E_DONE) { + err_input(err); + return NULL; + } + return run_node(n, filename, globals, locals); } object * run_node(n, filename, globals, locals) - node *n; - char *filename; - /*dict*/object *globals, *locals; + node *n; + char *filename; + /*dict*/object *globals, *locals; { - if (globals == NULL) { - globals = getglobals(); - if (locals == NULL) - locals = getlocals(); - } - else { - if (locals == NULL) - locals = globals; - } - return eval_node(n, filename, globals, locals); + if (globals == NULL) { + globals = getglobals(); + if (locals == NULL) + locals = getlocals(); + } + else { + if (locals == NULL) + locals = globals; + } + return eval_node(n, filename, globals, locals); } object * eval_node(n, filename, globals, locals) - node *n; - char *filename; - object *globals; - object *locals; + node *n; + char *filename; + object *globals; + object *locals; { - codeobject *co; - object *v; - co = compile(n, filename); - freetree(n); - if (co == NULL) - return NULL; - v = eval_code(co, globals, locals, (object *)NULL); - DECREF(co); - return v; + codeobject *co; + object *v; + co = compile(n, filename); + freetree(n); + if (co == NULL) + return NULL; + v = eval_code(co, globals, locals, (object *)NULL); + DECREF(co); + return v; } /* Simplified interface to parsefile */ int parse_file(fp, filename, start, n_ret) - FILE *fp; - char *filename; - int start; - node **n_ret; + FILE *fp; + char *filename; + int start; + node **n_ret; { - return parsefile(fp, filename, &gram, start, - (char *)0, (char *)0, n_ret); + return parsefile(fp, filename, &gram, start, + (char *)0, (char *)0, n_ret); } /* Simplified interface to parsestring */ int parse_string(str, start, n_ret) - char *str; - int start; - node **n_ret; + char *str; + int start; + node **n_ret; { - int err = parsestring(str, &gram, start, n_ret); - /* Don't confuse early end of string with early end of input */ - if (err == E_EOF) - err = E_SYNTAX; - return err; + int err = parsestring(str, &gram, start, n_ret); + /* Don't confuse early end of string with early end of input */ + if (err == E_EOF) + err = E_SYNTAX; + return err; } /* Print fatal error message and abort */ void fatal(msg) - char *msg; + char *msg; { - fprintf(stderr, "Fatal error: %s\n", msg); - abort(); + fprintf(stderr, "Fatal error: %s\n", msg); + abort(); } /* Clean up and exit */ void goaway(sts) - int sts; + int sts; { - flushline(); - - /* XXX Call doneimport() before donecalls(), since donecalls() - calls wdone(), and doneimport() may close windows */ - doneimport(); - donecalls(); - - err_clear(); + flushline(); + + /* XXX Call doneimport() before donecalls(), since donecalls() + calls wdone(), and doneimport() may close windows */ + doneimport(); + donecalls(); + + err_clear(); #ifdef REF_DEBUG - fprintf(stderr, "[%ld refs]\n", ref_total); + fprintf(stderr, "[%ld refs]\n", ref_total); #endif #ifdef THINK_C_3_0 - if (sts == 0) - Click_On(0); + if (sts == 0) + Click_On(0); #endif #ifdef TRACE_REFS - if (askyesno("Print left references?")) { + if (askyesno("Print left references?")) { #ifdef THINK_C_3_0 - Click_On(1); + Click_On(1); #endif - printrefs(stderr); - } + printrefs(stderr); + } #endif /* TRACE_REFS */ - exit(sts); - /*NOTREACHED*/ + exit(sts); + /*NOTREACHED*/ } static finaloutput() { #ifdef TRACE_REFS - if (!askyesno("Print left references?")) - return; + if (!askyesno("Print left references?")) + return; #ifdef THINK_C_3_0 - Click_On(1); + Click_On(1); #endif - printrefs(stderr); + printrefs(stderr); #endif /* TRACE_REFS */ } @@ -403,38 +403,38 @@ finaloutput() static int askyesno(prompt) - char *prompt; + char *prompt; { - char buf[256]; - - printf("%s [ny] ", prompt); - if (fgets(buf, sizeof buf, stdin) == NULL) - return 0; - return buf[0] == 'y' || buf[0] == 'Y'; + char buf[256]; + + printf("%s [ny] ", prompt); + if (fgets(buf, sizeof buf, stdin) == NULL) + return 0; + return buf[0] == 'y' || buf[0] == 'Y'; } #ifdef THINK_C_3_0 /* Check for file descriptor connected to interactive device. - Pretend that stdin is always interactive, other files never. */ + Pretend that stdin is always interactive, other files never. */ int isatty(fd) - int fd; + int fd; { - return fd == fileno(stdin); + return fd == fileno(stdin); } #endif -/* XXX WISH LIST +/* XXX WISH LIST - - possible new types: - - iterator (for range, keys, ...) - - improve interpreter error handling, e.g., true tracebacks - - save precompiled modules on file? - - fork threads, locking - - allow syntax extensions + - possible new types: + - iterator (for range, keys, ...) + - improve interpreter error handling, e.g., true tracebacks + - save precompiled modules on file? + - fork threads, locking + - allow syntax extensions */ /* "Floccinaucinihilipilification" */ diff --git a/src/pythonrun.h b/src/pythonrun.h index 30c8667..8b1808d 100644 --- a/src/pythonrun.h +++ b/src/pythonrun.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. diff --git a/src/regexp.c b/src/regexp.c index 50ce9b6..ed7756e 100644 --- a/src/regexp.c +++ b/src/regexp.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -25,50 +25,50 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* * regcomp and regexec -- regsub and regerror are elsewhere * - * Copyright (c) 1986 by University of Toronto. - * Written by Henry Spencer. Not derived from licensed software. + * Copyright (c) 1986 by University of Toronto. + * Written by Henry Spencer. Not derived from licensed software. #ifdef MULTILINE - * Changed by Guido van Rossum, CWI, Amsterdam - * for multi-line support. + * Changed by Guido van Rossum, CWI, Amsterdam + * for multi-line support. #endif * - * Permission is granted to anyone to use this software for any - * purpose on any computer system, and to redistribute it freely, - * subject to the following restrictions: + * Permission is granted to anyone to use this software for any + * purpose on any computer system, and to redistribute it freely, + * subject to the following restrictions: * - * 1. The author is not responsible for the consequences of use of - * this software, no matter how awful, even if they arise - * from defects in it. + * 1. The author is not responsible for the consequences of use of + * this software, no matter how awful, even if they arise + * from defects in it. * - * 2. The origin of this software must not be misrepresented, either - * by explicit claim or by omission. + * 2. The origin of this software must not be misrepresented, either + * by explicit claim or by omission. * - * 3. Altered versions must be plainly marked as such, and must not - * be misrepresented as being the original software. + * 3. Altered versions must be plainly marked as such, and must not + * be misrepresented as being the original software. * * Beware that some of this code is subtly aware of the way operator - * precedence is structured in regular expressions. Serious changes in + * precedence is structured in regular expressions. Serious changes in * regular-expression syntax might require a total rethink. */ #include <stdio.h> #include "PROTO.h" #include "malloc.h" #undef ANY /* Conflicting identifier defined in malloc.h */ -#include <string.h> /* XXX Remove if not found */ +#include <string.h> /* XXX Remove if not found */ #include "regexp.h" #include "regmagic.h" #ifdef MULTILINE /* * Defining MULTILINE turns on the following changes in the semantics: - * 1. The '.' operator matches all characters except a newline. - * 2. The '^' operator matches at the beginning of the string or after - * a newline. (Anchored matches are retried after each newline.) - * 3. The '$' operator matches at the end of the string or before - * a newline. - * 4. A '\' followed by an 'n' matches a newline. (This is an - * unfortunate exception to the rule that '\' followed by a - * character matches that character...) + * 1. The '.' operator matches all characters except a newline. + * 2. The '^' operator matches at the beginning of the string or after + * a newline. (Anchored matches are retried after each newline.) + * 3. The '$' operator matches at the end of the string or before + * a newline. + * 4. A '\' followed by an 'n' matches a newline. (This is an + * unfortunate exception to the rule that '\' followed by a + * character matches that character...) * * Also, there is a new function reglexec(prog, string, offset) * which searches for a match starting at 'string+offset'; @@ -80,91 +80,91 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* * The "internal use only" fields in regexp.h are present to pass info from * compile to execute that permits the execute phase to run lots faster on - * simple cases. They are: + * simple cases. They are: * - * regstart char that must begin a match; '\0' if none obvious - * reganch is the match anchored (at beginning-of-line only)? - * regmust string (pointer into program) that match must include, or NULL - * regmlen length of regmust string + * regstart char that must begin a match; '\0' if none obvious + * reganch is the match anchored (at beginning-of-line only)? + * regmust string (pointer into program) that match must include, or NULL + * regmlen length of regmust string * * Regstart and reganch permit very fast decisions on suitable starting points - * for a match, cutting down the work a lot. Regmust permits fast rejection - * of lines that cannot possibly match. The regmust tests are costly enough + * for a match, cutting down the work a lot. Regmust permits fast rejection + * of lines that cannot possibly match. The regmust tests are costly enough * that regcomp() supplies a regmust only if the r.e. contains something * potentially expensive (at present, the only such thing detected is * or + - * at the start of the r.e., which can involve a lot of backup). Regmlen is + * at the start of the r.e., which can involve a lot of backup). Regmlen is * supplied because the test in regexec() needs it and regcomp() is computing * it anyway. */ /* - * Structure for regexp "program". This is essentially a linear encoding + * Structure for regexp "program". This is essentially a linear encoding * of a nondeterministic finite-state machine (aka syntax charts or - * "railroad normal form" in parsing technology). Each node is an opcode - * plus a "next" pointer, possibly plus an operand. "Next" pointers of + * "railroad normal form" in parsing technology). Each node is an opcode + * plus a "next" pointer, possibly plus an operand. "Next" pointers of * all nodes except BRANCH implement concatenation; a "next" pointer with - * a BRANCH on both ends of it is connecting two alternatives. (Here we - * have one of the subtle syntax dependencies: an individual BRANCH (as + * a BRANCH on both ends of it is connecting two alternatives. (Here we + * have one of the subtle syntax dependencies: an individual BRANCH (as * opposed to a collection of them) is never concatenated with anything - * because of operator precedence.) The operand of some types of node is - * a literal string; for others, it is a node leading into a sub-FSM. In + * because of operator precedence.) The operand of some types of node is + * a literal string; for others, it is a node leading into a sub-FSM. In * particular, the operand of a BRANCH node is the first node of the branch. - * (NB this is *not* a tree structure: the tail of the branch connects - * to the thing following the set of BRANCHes.) The opcodes are: + * (NB this is *not* a tree structure: the tail of the branch connects + * to the thing following the set of BRANCHes.) The opcodes are: */ -/* definition number opnd? meaning */ -#define END 0 /* no End of program. */ -#define BOL 1 /* no Match "" at beginning of line. */ -#define EOL 2 /* no Match "" at end of line. */ -#define ANY 3 /* no Match any one character. */ -#define ANYOF 4 /* str Match any character in this string. */ -#define ANYBUT 5 /* str Match any character not in this string. */ -#define BRANCH 6 /* node Match this alternative, or the next... */ -#define BACK 7 /* no Match "", "next" ptr points backward. */ -#define EXACTLY 8 /* str Match this string. */ -#define NOTHING 9 /* no Match empty string. */ -#define STAR 10 /* node Match this (simple) thing 0 or more times. */ -#define PLUS 11 /* node Match this (simple) thing 1 or more times. */ -#define OPEN 20 /* no Mark this point in input as start of #n. */ - /* OPEN+1 is number 1, etc. */ -#define CLOSE 30 /* no Analogous to OPEN. */ +/* definition number opnd? meaning */ +#define END 0 /* no End of program. */ +#define BOL 1 /* no Match "" at beginning of line. */ +#define EOL 2 /* no Match "" at end of line. */ +#define ANY 3 /* no Match any one character. */ +#define ANYOF 4 /* str Match any character in this string. */ +#define ANYBUT 5 /* str Match any character not in this string. */ +#define BRANCH 6 /* node Match this alternative, or the next... */ +#define BACK 7 /* no Match "", "next" ptr points backward. */ +#define EXACTLY 8 /* str Match this string. */ +#define NOTHING 9 /* no Match empty string. */ +#define STAR 10 /* node Match this (simple) thing 0 or more times. */ +#define PLUS 11 /* node Match this (simple) thing 1 or more times. */ +#define OPEN 20 /* no Mark this point in input as start of #n. */ + /* OPEN+1 is number 1, etc. */ +#define CLOSE 30 /* no Analogous to OPEN. */ /* * Opcode notes: * - * BRANCH The set of branches constituting a single choice are hooked - * together with their "next" pointers, since precedence prevents - * anything being concatenated to any individual branch. The - * "next" pointer of the last BRANCH in a choice points to the - * thing following the whole choice. This is also where the - * final "next" pointer of each individual branch points; each - * branch starts with the operand node of a BRANCH node. + * BRANCH The set of branches constituting a single choice are hooked + * together with their "next" pointers, since precedence prevents + * anything being concatenated to any individual branch. The + * "next" pointer of the last BRANCH in a choice points to the + * thing following the whole choice. This is also where the + * final "next" pointer of each individual branch points; each + * branch starts with the operand node of a BRANCH node. * - * BACK Normal "next" pointers all implicitly point forward; BACK - * exists to make loop structures possible. + * BACK Normal "next" pointers all implicitly point forward; BACK + * exists to make loop structures possible. * - * STAR,PLUS '?', and complex '*' and '+', are implemented as circular - * BRANCH structures using BACK. Simple cases (one character - * per match) are implemented with STAR and PLUS for speed - * and to minimize recursive plunges. + * STAR,PLUS '?', and complex '*' and '+', are implemented as circular + * BRANCH structures using BACK. Simple cases (one character + * per match) are implemented with STAR and PLUS for speed + * and to minimize recursive plunges. * - * OPEN,CLOSE ...are numbered at compile time. + * OPEN,CLOSE ...are numbered at compile time. */ /* * A node is one char of opcode followed by two chars of "next" pointer. - * "Next" pointers are stored as two 8-bit pieces, high order first. The + * "Next" pointers are stored as two 8-bit pieces, high order first. The * value is a positive offset from the opcode of the node containing it. - * An operand, if any, simply follows the node. (Note that much of the + * An operand, if any, simply follows the node. (Note that much of the * code generation knows about this implicit relationship.) * * Using two bytes for the "next" pointer is vast overkill for most things, * but allows patterns to get big without disasters. */ -#define OP(p) (*(p)) -#define NEXT(p) (((*((p)+1)&0377)<<8) + (*((p)+2)&0377)) -#define OPERAND(p) ((p) + 3) +#define OP(p) (*(p)) +#define NEXT(p) (((*((p)+1)&0377)<<8) + (*((p)+2)&0377)) +#define OPERAND(p) ((p) + 3) /* * See regmagic.h for one further detail of program structure. @@ -175,40 +175,40 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * Utility definitions. */ #ifndef CHARBITS -#define UCHARAT(p) ((int)*(unsigned char *)(p)) +#define UCHARAT(p) ((int)*(unsigned char *)(p)) #else -#define UCHARAT(p) ((int)*(p)&CHARBITS) +#define UCHARAT(p) ((int)*(p)&CHARBITS) #endif -#define FAIL(m) { regerror(m); return(NULL); } -#define ISMULT(c) ((c) == '*' || (c) == '+' || (c) == '?') -#define META "^$.[()|?+*\\" +#define FAIL(m) { regerror(m); return(NULL); } +#define ISMULT(c) ((c) == '*' || (c) == '+' || (c) == '?') +#define META "^$.[()|?+*\\" /* * Flags to be passed up and down. */ -#define HASWIDTH 01 /* Known never to match null string. */ -#define SIMPLE 02 /* Simple enough to be STAR/PLUS operand. */ -#define SPSTART 04 /* Starts with * or +. */ -#define WORST 0 /* Worst case. */ +#define HASWIDTH 01 /* Known never to match null string. */ +#define SIMPLE 02 /* Simple enough to be STAR/PLUS operand. */ +#define SPSTART 04 /* Starts with * or +. */ +#define WORST 0 /* Worst case. */ /* * Global work variables for regcomp(). */ -static char *regparse; /* Input-scan pointer. */ -static int regnpar; /* () count. */ +static char *regparse; /* Input-scan pointer. */ +static int regnpar; /* () count. */ static char regdummy; -static char *regcode; /* Code-emit pointer; ®dummy = don't. */ -static long regsize; /* Code size. */ +static char *regcode; /* Code-emit pointer; ®dummy = don't. */ +static long regsize; /* Code size. */ #ifdef MULTILINE -static int regnl; /* '\n' detected. */ +static int regnl; /* '\n' detected. */ #endif /* * Forward declarations for regcomp()'s friends. */ #ifndef STATIC -#define STATIC static +#define STATIC static #endif STATIC char *reg(); STATIC char *regbranch(); @@ -229,11 +229,11 @@ STATIC int strcspn(); * * We can't allocate space until we know how big the compiled form will be, * but we can't compile it (and thus know how big it is) until we've got a - * place to put the code. So we cheat: we compile it twice, once with code + * place to put the code. So we cheat: we compile it twice, once with code * generation turned off and size counting turned on, and once "for real". * This also means that we don't allocate space until we are sure that the * thing really will compile successfully, and we never have to move the - * code and thus invalidate pointers into it. (Note that it has to be in + * code and thus invalidate pointers into it. (Note that it has to be in * one piece because free() must be able to free it all.) * * Beware that the optimization-preparation code in here knows about some @@ -243,85 +243,85 @@ regexp * regcomp(exp) char *exp; { - register regexp *r; - register char *scan; - register char *longest; - register int len; - int flags; - - if (exp == NULL) - FAIL("NULL argument"); - - /* First pass: determine size, legality. */ - regparse = exp; - regnpar = 1; - regsize = 0L; - regcode = ®dummy; + register regexp *r; + register char *scan; + register char *longest; + register int len; + int flags; + + if (exp == NULL) + FAIL("NULL argument"); + + /* First pass: determine size, legality. */ + regparse = exp; + regnpar = 1; + regsize = 0L; + regcode = ®dummy; #ifdef MULTILINE - regnl = 0; + regnl = 0; #endif - regc(MAGIC); - if (reg(0, &flags) == NULL) - return(NULL); - - /* Small enough for pointer-storage convention? */ - if (regsize >= 32767L) /* Probably could be 65535L. */ - FAIL("regexp too big"); - - /* Allocate space. */ - r = (regexp *)malloc(sizeof(regexp) + (unsigned)regsize); - if (r == NULL) - FAIL("out of space"); - - /* Second pass: emit code. */ - regparse = exp; - regnpar = 1; - regcode = r->program; - regc(MAGIC); - if (reg(0, &flags) == NULL) - return(NULL); - - /* Dig out information for optimizations. */ - r->regstart = '\0'; /* Worst-case defaults. */ - r->reganch = 0; - r->regmust = NULL; - r->regmlen = 0; - scan = r->program+1; /* First BRANCH. */ - if (OP(regnext(scan)) == END) { /* Only one top-level choice. */ - scan = OPERAND(scan); - - /* Starting-point info. */ - if (OP(scan) == EXACTLY) - r->regstart = *OPERAND(scan); - else if (OP(scan) == BOL) - r->reganch++; - - /* - * If there's something expensive in the r.e., find the - * longest literal string that must appear and make it the - * regmust. Resolve ties in favor of later strings, since - * the regstart check works with the beginning of the r.e. - * and avoiding duplication strengthens checking. Not a - * strong reason, but sufficient in the absence of others. - */ + regc(MAGIC); + if (reg(0, &flags) == NULL) + return(NULL); + + /* Small enough for pointer-storage convention? */ + if (regsize >= 32767L) /* Probably could be 65535L. */ + FAIL("regexp too big"); + + /* Allocate space. */ + r = (regexp *)malloc(sizeof(regexp) + (unsigned)regsize); + if (r == NULL) + FAIL("out of space"); + + /* Second pass: emit code. */ + regparse = exp; + regnpar = 1; + regcode = r->program; + regc(MAGIC); + if (reg(0, &flags) == NULL) + return(NULL); + + /* Dig out information for optimizations. */ + r->regstart = '\0'; /* Worst-case defaults. */ + r->reganch = 0; + r->regmust = NULL; + r->regmlen = 0; + scan = r->program+1; /* First BRANCH. */ + if (OP(regnext(scan)) == END) { /* Only one top-level choice. */ + scan = OPERAND(scan); + + /* Starting-point info. */ + if (OP(scan) == EXACTLY) + r->regstart = *OPERAND(scan); + else if (OP(scan) == BOL) + r->reganch++; + + /* + * If there's something expensive in the r.e., find the + * longest literal string that must appear and make it the + * regmust. Resolve ties in favor of later strings, since + * the regstart check works with the beginning of the r.e. + * and avoiding duplication strengthens checking. Not a + * strong reason, but sufficient in the absence of others. + */ #ifdef MULTILINE - if ((flags&SPSTART) && !regnl) { + if ((flags&SPSTART) && !regnl) { #else - if (flags&SPSTART) { + if (flags&SPSTART) { #endif - longest = NULL; - len = 0; - for (; scan != NULL; scan = regnext(scan)) - if (OP(scan) == EXACTLY && strlen(OPERAND(scan)) >= len) { - longest = OPERAND(scan); - len = strlen(OPERAND(scan)); - } - r->regmust = longest; - r->regmlen = len; - } - } - - return(r); + longest = NULL; + len = 0; + for (; scan != NULL; scan = regnext(scan)) + if (OP(scan) == EXACTLY && strlen(OPERAND(scan)) >= len) { + longest = OPERAND(scan); + len = strlen(OPERAND(scan)); + } + r->regmust = longest; + r->regmlen = len; + } + } + + return(r); } /* @@ -335,69 +335,69 @@ char *exp; */ static char * reg(paren, flagp) -int paren; /* Parenthesized? */ +int paren; /* Parenthesized? */ int *flagp; { - register char *ret; - register char *br; - register char *ender; - register int parno; - int flags; - - *flagp = HASWIDTH; /* Tentatively. */ - - /* Make an OPEN node, if parenthesized. */ - if (paren) { - if (regnpar >= NSUBEXP) - FAIL("too many ()"); - parno = regnpar; - regnpar++; - ret = regnode(OPEN+parno); - } else - ret = NULL; - - /* Pick up the branches, linking them together. */ - br = regbranch(&flags); - if (br == NULL) - return(NULL); - if (ret != NULL) - regtail(ret, br); /* OPEN -> first. */ - else - ret = br; - if (!(flags&HASWIDTH)) - *flagp &= ~HASWIDTH; - *flagp |= flags&SPSTART; - while (*regparse == '|') { - regparse++; - br = regbranch(&flags); - if (br == NULL) - return(NULL); - regtail(ret, br); /* BRANCH -> BRANCH. */ - if (!(flags&HASWIDTH)) - *flagp &= ~HASWIDTH; - *flagp |= flags&SPSTART; - } - - /* Make a closing node, and hook it on the end. */ - ender = regnode((paren) ? CLOSE+parno : END); - regtail(ret, ender); - - /* Hook the tails of the branches to the closing node. */ - for (br = ret; br != NULL; br = regnext(br)) - regoptail(br, ender); - - /* Check for proper termination. */ - if (paren && *regparse++ != ')') { - FAIL("unmatched ()"); - } else if (!paren && *regparse != '\0') { - if (*regparse == ')') { - FAIL("unmatched ()"); - } else - FAIL("junk on end"); /* "Can't happen". */ - /* NOTREACHED */ - } - - return(ret); + register char *ret; + register char *br; + register char *ender; + register int parno; + int flags; + + *flagp = HASWIDTH; /* Tentatively. */ + + /* Make an OPEN node, if parenthesized. */ + if (paren) { + if (regnpar >= NSUBEXP) + FAIL("too many ()"); + parno = regnpar; + regnpar++; + ret = regnode(OPEN+parno); + } else + ret = NULL; + + /* Pick up the branches, linking them together. */ + br = regbranch(&flags); + if (br == NULL) + return(NULL); + if (ret != NULL) + regtail(ret, br); /* OPEN -> first. */ + else + ret = br; + if (!(flags&HASWIDTH)) + *flagp &= ~HASWIDTH; + *flagp |= flags&SPSTART; + while (*regparse == '|') { + regparse++; + br = regbranch(&flags); + if (br == NULL) + return(NULL); + regtail(ret, br); /* BRANCH -> BRANCH. */ + if (!(flags&HASWIDTH)) + *flagp &= ~HASWIDTH; + *flagp |= flags&SPSTART; + } + + /* Make a closing node, and hook it on the end. */ + ender = regnode((paren) ? CLOSE+parno : END); + regtail(ret, ender); + + /* Hook the tails of the branches to the closing node. */ + for (br = ret; br != NULL; br = regnext(br)) + regoptail(br, ender); + + /* Check for proper termination. */ + if (paren && *regparse++ != ')') { + FAIL("unmatched ()"); + } else if (!paren && *regparse != '\0') { + if (*regparse == ')') { + FAIL("unmatched ()"); + } else + FAIL("junk on end"); /* "Can't happen". */ + /* NOTREACHED */ + } + + return(ret); } /* @@ -409,37 +409,37 @@ static char * regbranch(flagp) int *flagp; { - register char *ret; - register char *chain; - register char *latest; - int flags; - - *flagp = WORST; /* Tentatively. */ - - ret = regnode(BRANCH); - chain = NULL; - while (*regparse != '\0' && *regparse != '|' && *regparse != ')') { - latest = regpiece(&flags); - if (latest == NULL) - return(NULL); - *flagp |= flags&HASWIDTH; - if (chain == NULL) /* First piece. */ - *flagp |= flags&SPSTART; - else - regtail(chain, latest); - chain = latest; - } - if (chain == NULL) /* Loop ran zero times. */ - (void) regnode(NOTHING); - - return(ret); + register char *ret; + register char *chain; + register char *latest; + int flags; + + *flagp = WORST; /* Tentatively. */ + + ret = regnode(BRANCH); + chain = NULL; + while (*regparse != '\0' && *regparse != '|' && *regparse != ')') { + latest = regpiece(&flags); + if (latest == NULL) + return(NULL); + *flagp |= flags&HASWIDTH; + if (chain == NULL) /* First piece. */ + *flagp |= flags&SPSTART; + else + regtail(chain, latest); + chain = latest; + } + if (chain == NULL) /* Loop ran zero times. */ + (void) regnode(NOTHING); + + return(ret); } /* - regpiece - something followed by possible [*+?] * * Note that the branching code sequences used for ? and the general cases - * of * and + are somewhat optimized: they use the same NOTHING node as + * of * and + are somewhat optimized: they use the same NOTHING node as * both the endmarker for their branch list and the body of the last branch. * It might seem that this node could be dispensed with entirely, but the * endmarker role is not redundant. @@ -448,207 +448,207 @@ static char * regpiece(flagp) int *flagp; { - register char *ret; - register char op; - register char *next; - int flags; - - ret = regatom(&flags); - if (ret == NULL) - return(NULL); - - op = *regparse; - if (!ISMULT(op)) { - *flagp = flags; - return(ret); - } - - if (!(flags&HASWIDTH) && op != '?') - FAIL("*+ operand could be empty"); - *flagp = (op != '+') ? (WORST|SPSTART) : (WORST|HASWIDTH); - - if (op == '*' && (flags&SIMPLE)) - reginsert(STAR, ret); - else if (op == '*') { - /* Emit x* as (x&|), where & means "self". */ - reginsert(BRANCH, ret); /* Either x */ - regoptail(ret, regnode(BACK)); /* and loop */ - regoptail(ret, ret); /* back */ - regtail(ret, regnode(BRANCH)); /* or */ - regtail(ret, regnode(NOTHING)); /* null. */ - } else if (op == '+' && (flags&SIMPLE)) - reginsert(PLUS, ret); - else if (op == '+') { - /* Emit x+ as x(&|), where & means "self". */ - next = regnode(BRANCH); /* Either */ - regtail(ret, next); - regtail(regnode(BACK), ret); /* loop back */ - regtail(next, regnode(BRANCH)); /* or */ - regtail(ret, regnode(NOTHING)); /* null. */ - } else if (op == '?') { - /* Emit x? as (x|) */ - reginsert(BRANCH, ret); /* Either x */ - regtail(ret, regnode(BRANCH)); /* or */ - next = regnode(NOTHING); /* null. */ - regtail(ret, next); - regoptail(ret, next); - } - regparse++; - if (ISMULT(*regparse)) - FAIL("nested *?+"); - - return(ret); + register char *ret; + register char op; + register char *next; + int flags; + + ret = regatom(&flags); + if (ret == NULL) + return(NULL); + + op = *regparse; + if (!ISMULT(op)) { + *flagp = flags; + return(ret); + } + + if (!(flags&HASWIDTH) && op != '?') + FAIL("*+ operand could be empty"); + *flagp = (op != '+') ? (WORST|SPSTART) : (WORST|HASWIDTH); + + if (op == '*' && (flags&SIMPLE)) + reginsert(STAR, ret); + else if (op == '*') { + /* Emit x* as (x&|), where & means "self". */ + reginsert(BRANCH, ret); /* Either x */ + regoptail(ret, regnode(BACK)); /* and loop */ + regoptail(ret, ret); /* back */ + regtail(ret, regnode(BRANCH)); /* or */ + regtail(ret, regnode(NOTHING)); /* null. */ + } else if (op == '+' && (flags&SIMPLE)) + reginsert(PLUS, ret); + else if (op == '+') { + /* Emit x+ as x(&|), where & means "self". */ + next = regnode(BRANCH); /* Either */ + regtail(ret, next); + regtail(regnode(BACK), ret); /* loop back */ + regtail(next, regnode(BRANCH)); /* or */ + regtail(ret, regnode(NOTHING)); /* null. */ + } else if (op == '?') { + /* Emit x? as (x|) */ + reginsert(BRANCH, ret); /* Either x */ + regtail(ret, regnode(BRANCH)); /* or */ + next = regnode(NOTHING); /* null. */ + regtail(ret, next); + regoptail(ret, next); + } + regparse++; + if (ISMULT(*regparse)) + FAIL("nested *?+"); + + return(ret); } /* - regatom - the lowest level * - * Optimization: gobbles an entire sequence of ordinary characters so that + * Optimization: gobbles an entire sequence of ordinary characters so that * it can turn them into a single node, which is smaller to store and - * faster to run. Backslashed characters are exceptions, each becoming a + * faster to run. Backslashed characters are exceptions, each becoming a * separate node; the code is simpler that way and it's not worth fixing. */ static char * regatom(flagp) int *flagp; { - register char *ret; - int flags; - - *flagp = WORST; /* Tentatively. */ - - switch (*regparse++) { - case '^': - ret = regnode(BOL); - break; - case '$': - ret = regnode(EOL); - break; - case '.': - ret = regnode(ANY); - *flagp |= HASWIDTH|SIMPLE; - break; - case '[': { - register int class; - register int classend; - - if (*regparse == '^') { /* Complement of range. */ - ret = regnode(ANYBUT); - regparse++; - } else - ret = regnode(ANYOF); - if (*regparse == ']' || *regparse == '-') - regc(*regparse++); - while (*regparse != '\0' && *regparse != ']') { - if (*regparse == '-') { - regparse++; - if (*regparse == ']' || *regparse == '\0') - regc('-'); - else { - class = UCHARAT(regparse-2)+1; - classend = UCHARAT(regparse); - if (class > classend+1) - FAIL("invalid [] range"); - for (; class <= classend; class++) - regc(class); - regparse++; - } - } else - regc(*regparse++); - } - regc('\0'); - if (*regparse != ']') - FAIL("unmatched []"); - regparse++; - *flagp |= HASWIDTH|SIMPLE; - } - break; - case '(': - ret = reg(1, &flags); - if (ret == NULL) - return(NULL); - *flagp |= flags&(HASWIDTH|SPSTART); - break; - case '\0': - case '|': - case ')': - FAIL("internal urp"); /* Supposed to be caught earlier. */ - break; - case '?': - case '+': - case '*': - FAIL("?+* follows nothing"); - break; - case '\\': - if (*regparse == '\0') - FAIL("trailing \\"); - ret = regnode(EXACTLY); + register char *ret; + int flags; + + *flagp = WORST; /* Tentatively. */ + + switch (*regparse++) { + case '^': + ret = regnode(BOL); + break; + case '$': + ret = regnode(EOL); + break; + case '.': + ret = regnode(ANY); + *flagp |= HASWIDTH|SIMPLE; + break; + case '[': { + register int class; + register int classend; + + if (*regparse == '^') { /* Complement of range. */ + ret = regnode(ANYBUT); + regparse++; + } else + ret = regnode(ANYOF); + if (*regparse == ']' || *regparse == '-') + regc(*regparse++); + while (*regparse != '\0' && *regparse != ']') { + if (*regparse == '-') { + regparse++; + if (*regparse == ']' || *regparse == '\0') + regc('-'); + else { + class = UCHARAT(regparse-2)+1; + classend = UCHARAT(regparse); + if (class > classend+1) + FAIL("invalid [] range"); + for (; class <= classend; class++) + regc(class); + regparse++; + } + } else + regc(*regparse++); + } + regc('\0'); + if (*regparse != ']') + FAIL("unmatched []"); + regparse++; + *flagp |= HASWIDTH|SIMPLE; + } + break; + case '(': + ret = reg(1, &flags); + if (ret == NULL) + return(NULL); + *flagp |= flags&(HASWIDTH|SPSTART); + break; + case '\0': + case '|': + case ')': + FAIL("internal urp"); /* Supposed to be caught earlier. */ + break; + case '?': + case '+': + case '*': + FAIL("?+* follows nothing"); + break; + case '\\': + if (*regparse == '\0') + FAIL("trailing \\"); + ret = regnode(EXACTLY); #ifdef MULTILINE - if (*regparse == 'n') { - regc('\n'); - regparse++; - regnl++; - } - else + if (*regparse == 'n') { + regc('\n'); + regparse++; + regnl++; + } + else #endif - regc(*regparse++); - regc('\0'); - *flagp |= HASWIDTH|SIMPLE; - break; - default: { - register int len; - register char ender; - - regparse--; - len = strcspn(regparse, META); - if (len <= 0) - FAIL("internal disaster"); - ender = *(regparse+len); - if (len > 1 && ISMULT(ender)) - len--; /* Back off clear of ?+* operand. */ - *flagp |= HASWIDTH; - if (len == 1) - *flagp |= SIMPLE; - ret = regnode(EXACTLY); - while (len > 0) { + regc(*regparse++); + regc('\0'); + *flagp |= HASWIDTH|SIMPLE; + break; + default: { + register int len; + register char ender; + + regparse--; + len = strcspn(regparse, META); + if (len <= 0) + FAIL("internal disaster"); + ender = *(regparse+len); + if (len > 1 && ISMULT(ender)) + len--; /* Back off clear of ?+* operand. */ + *flagp |= HASWIDTH; + if (len == 1) + *flagp |= SIMPLE; + ret = regnode(EXACTLY); + while (len > 0) { #ifdef MULTILINE - if (*regparse == '\n') - regnl++; + if (*regparse == '\n') + regnl++; #endif - regc(*regparse++); - len--; - } - regc('\0'); - } - break; - } - - return(ret); + regc(*regparse++); + len--; + } + regc('\0'); + } + break; + } + + return(ret); } /* - regnode - emit a node */ -static char * /* Location. */ +static char * /* Location. */ regnode(op) char op; { - register char *ret; - register char *ptr; - - ret = regcode; - if (ret == ®dummy) { - regsize += 3; - return(ret); - } - - ptr = ret; - *ptr++ = op; - *ptr++ = '\0'; /* Null "next" pointer. */ - *ptr++ = '\0'; - regcode = ptr; - - return(ret); + register char *ret; + register char *ptr; + + ret = regcode; + if (ret == ®dummy) { + regsize += 3; + return(ret); + } + + ptr = ret; + *ptr++ = op; + *ptr++ = '\0'; /* Null "next" pointer. */ + *ptr++ = '\0'; + regcode = ptr; + + return(ret); } /* @@ -658,10 +658,10 @@ static void regc(b) char b; { - if (regcode != ®dummy) - *regcode++ = b; - else - regsize++; + if (regcode != ®dummy) + *regcode++ = b; + else + regsize++; } /* @@ -674,25 +674,25 @@ reginsert(op, opnd) char op; char *opnd; { - register char *src; - register char *dst; - register char *place; - - if (regcode == ®dummy) { - regsize += 3; - return; - } - - src = regcode; - regcode += 3; - dst = regcode; - while (src > opnd) - *--dst = *--src; - - place = opnd; /* Op node, where operand used to be. */ - *place++ = op; - *place++ = '\0'; - *place++ = '\0'; + register char *src; + register char *dst; + register char *place; + + if (regcode == ®dummy) { + regsize += 3; + return; + } + + src = regcode; + regcode += 3; + dst = regcode; + while (src > opnd) + *--dst = *--src; + + place = opnd; /* Op node, where operand used to be. */ + *place++ = op; + *place++ = '\0'; + *place++ = '\0'; } /* @@ -703,28 +703,28 @@ regtail(p, val) char *p; char *val; { - register char *scan; - register char *temp; - register int offset; - - if (p == ®dummy) - return; - - /* Find last node. */ - scan = p; - for (;;) { - temp = regnext(scan); - if (temp == NULL) - break; - scan = temp; - } - - if (OP(scan) == BACK) - offset = scan - val; - else - offset = val - scan; - *(scan+1) = (offset>>8)&0377; - *(scan+2) = offset&0377; + register char *scan; + register char *temp; + register int offset; + + if (p == ®dummy) + return; + + /* Find last node. */ + scan = p; + for (;;) { + temp = regnext(scan); + if (temp == NULL) + break; + scan = temp; + } + + if (OP(scan) == BACK) + offset = scan - val; + else + offset = val - scan; + *(scan+1) = (offset>>8)&0377; + *(scan+2) = offset&0377; } /* @@ -735,10 +735,10 @@ regoptail(p, val) char *p; char *val; { - /* "Operandless" and "op != BRANCH" are synonymous in practice. */ - if (p == NULL || p == ®dummy || OP(p) != BRANCH) - return; - regtail(OPERAND(p), val); + /* "Operandless" and "op != BRANCH" are synonymous in practice. */ + if (p == NULL || p == ®dummy || OP(p) != BRANCH) + return; + regtail(OPERAND(p), val); } /* @@ -748,10 +748,10 @@ char *val; /* * Global work variables for regexec(). */ -static char *reginput; /* String-input pointer. */ -static char *regbol; /* Beginning of input, for ^ check. */ -static char **regstartp; /* Pointer to startp array. */ -static char **regendp; /* Ditto for endp. */ +static char *reginput; /* String-input pointer. */ +static char *regbol; /* Beginning of input, for ^ check. */ +static char **regstartp; /* Pointer to startp array. */ +static char **regendp; /* Ditto for endp. */ /* * Forwards. @@ -774,64 +774,64 @@ regexec(prog, string) register regexp *prog; register char *string; { - register char *s; - extern char *strchr(); + register char *s; + extern char *strchr(); - /* Be paranoid... */ - if (prog == NULL || string == NULL) { - regerror("NULL parameter"); - return(0); - } + /* Be paranoid... */ + if (prog == NULL || string == NULL) { + regerror("NULL parameter"); + return(0); + } #ifdef MULTILINE - /* Check for \n in string, and if so, call the more general routine. */ - if (strchr(string, '\n') != NULL) - return reglexec(prog, string, 0); + /* Check for \n in string, and if so, call the more general routine. */ + if (strchr(string, '\n') != NULL) + return reglexec(prog, string, 0); #endif - /* Check validity of program. */ - if (UCHARAT(prog->program) != MAGIC) { - regerror("corrupted program"); - return(0); - } - - /* If there is a "must appear" string, look for it. */ - if (prog->regmust != NULL) { - s = string; - while ((s = strchr(s, prog->regmust[0])) != NULL) { - if (strncmp(s, prog->regmust, prog->regmlen) == 0) - break; /* Found it. */ - s++; - } - if (s == NULL) /* Not present. */ - return(0); - } - - /* Mark beginning of line for ^ . */ - regbol = string; - - /* Simplest case: anchored match need be tried only once. */ - if (prog->reganch) - return(regtry(prog, string)); - - /* Messy cases: unanchored match. */ - s = string; - if (prog->regstart != '\0') - /* We know what char it must start with. */ - while ((s = strchr(s, prog->regstart)) != NULL) { - if (regtry(prog, s)) - return(1); - s++; - } - else - /* We don't -- general case. */ - do { - if (regtry(prog, s)) - return(1); - } while (*s++ != '\0'); - - /* Failure. */ - return(0); + /* Check validity of program. */ + if (UCHARAT(prog->program) != MAGIC) { + regerror("corrupted program"); + return(0); + } + + /* If there is a "must appear" string, look for it. */ + if (prog->regmust != NULL) { + s = string; + while ((s = strchr(s, prog->regmust[0])) != NULL) { + if (strncmp(s, prog->regmust, prog->regmlen) == 0) + break; /* Found it. */ + s++; + } + if (s == NULL) /* Not present. */ + return(0); + } + + /* Mark beginning of line for ^ . */ + regbol = string; + + /* Simplest case: anchored match need be tried only once. */ + if (prog->reganch) + return(regtry(prog, string)); + + /* Messy cases: unanchored match. */ + s = string; + if (prog->regstart != '\0') + /* We know what char it must start with. */ + while ((s = strchr(s, prog->regstart)) != NULL) { + if (regtry(prog, s)) + return(1); + s++; + } + else + /* We don't -- general case. */ + do { + if (regtry(prog, s)) + return(1); + } while (*s++ != '\0'); + + /* Failure. */ + return(0); } #ifdef MULTILINE @@ -843,303 +843,303 @@ reglexec(prog, string, offset) register regexp *prog; register char *string; { - register char *s; - extern char *strchr(); - - /* Be paranoid... */ - if (prog == NULL || string == NULL) { - regerror("NULL parameter"); - return(0); - } - - /* Check validity of program. */ - if (UCHARAT(prog->program) != MAGIC) { - regerror("corrupted program"); - return(0); - } - - /* (Don't look for "must appear" string -- string can be long.) */ - - /* Mark beginning of line for ^ . */ - regbol = string; - - /* Apply offset. - Assume 0 <= offset <= strlen(string), but don't check, - as string can be long. */ - s= string + offset; - - /* Anchored match need be tried only at line starts. */ - if (prog->reganch) { - while (!regtry(prog, s)) { - s = strchr(s, '\n'); - if (s == NULL) - return(0); - s++; - } - return(1); - } - - /* Messy cases: unanchored match. */ - if (prog->regstart != '\0') - /* We know what char it must start with. */ - while ((s = strchr(s, prog->regstart)) != NULL) { - if (regtry(prog, s)) - return(1); - s++; - } - else - /* We don't -- general case. */ - do { - if (regtry(prog, s)) - return(1); - } while (*s++ != '\0'); - - /* Failure. */ - return(0); + register char *s; + extern char *strchr(); + + /* Be paranoid... */ + if (prog == NULL || string == NULL) { + regerror("NULL parameter"); + return(0); + } + + /* Check validity of program. */ + if (UCHARAT(prog->program) != MAGIC) { + regerror("corrupted program"); + return(0); + } + + /* (Don't look for "must appear" string -- string can be long.) */ + + /* Mark beginning of line for ^ . */ + regbol = string; + + /* Apply offset. + Assume 0 <= offset <= strlen(string), but don't check, + as string can be long. */ + s= string + offset; + + /* Anchored match need be tried only at line starts. */ + if (prog->reganch) { + while (!regtry(prog, s)) { + s = strchr(s, '\n'); + if (s == NULL) + return(0); + s++; + } + return(1); + } + + /* Messy cases: unanchored match. */ + if (prog->regstart != '\0') + /* We know what char it must start with. */ + while ((s = strchr(s, prog->regstart)) != NULL) { + if (regtry(prog, s)) + return(1); + s++; + } + else + /* We don't -- general case. */ + do { + if (regtry(prog, s)) + return(1); + } while (*s++ != '\0'); + + /* Failure. */ + return(0); } #endif /* - regtry - try match at specific point */ -static int /* 0 failure, 1 success */ +static int /* 0 failure, 1 success */ regtry(prog, string) regexp *prog; char *string; { - register int i; - register char **sp; - register char **ep; - - reginput = string; - regstartp = prog->startp; - regendp = prog->endp; - - sp = prog->startp; - ep = prog->endp; - for (i = NSUBEXP; i > 0; i--) { - *sp++ = NULL; - *ep++ = NULL; - } - if (regmatch(prog->program + 1)) { - prog->startp[0] = string; - prog->endp[0] = reginput; - return(1); - } else - return(0); + register int i; + register char **sp; + register char **ep; + + reginput = string; + regstartp = prog->startp; + regendp = prog->endp; + + sp = prog->startp; + ep = prog->endp; + for (i = NSUBEXP; i > 0; i--) { + *sp++ = NULL; + *ep++ = NULL; + } + if (regmatch(prog->program + 1)) { + prog->startp[0] = string; + prog->endp[0] = reginput; + return(1); + } else + return(0); } /* - regmatch - main matching routine * - * Conceptually the strategy is simple: check to see whether the current + * Conceptually the strategy is simple: check to see whether the current * node matches, call self recursively to see whether the rest matches, - * and then act accordingly. In practice we make some effort to avoid + * and then act accordingly. In practice we make some effort to avoid * recursion, in particular by going through "ordinary" nodes (that don't * need to know whether the rest of the match failed) by a loop instead of * by recursion. */ -static int /* 0 failure, 1 success */ +static int /* 0 failure, 1 success */ regmatch(prog) char *prog; { - register char *scan; /* Current node. */ - char *next; /* Next node. */ - extern char *strchr(); + register char *scan; /* Current node. */ + char *next; /* Next node. */ + extern char *strchr(); - scan = prog; + scan = prog; #ifdef DEBUG - if (scan != NULL && regnarrate) - fprintf(stderr, "%s(\n", regprop(scan)); + if (scan != NULL && regnarrate) + fprintf(stderr, "%s(\n", regprop(scan)); #endif - while (scan != NULL) { + while (scan != NULL) { #ifdef DEBUG - if (regnarrate) - fprintf(stderr, "%s...\n", regprop(scan)); + if (regnarrate) + fprintf(stderr, "%s...\n", regprop(scan)); #endif - next = regnext(scan); + next = regnext(scan); - switch (OP(scan)) { - case BOL: + switch (OP(scan)) { + case BOL: #ifdef MULTILINE - if (!(reginput == regbol || - reginput > regbol && *(reginput-1) == '\n')) + if (!(reginput == regbol || + reginput > regbol && *(reginput-1) == '\n')) #else - if (reginput != regbol) + if (reginput != regbol) #endif - return(0); - break; - case EOL: + return(0); + break; + case EOL: #ifdef MULTILINE - if (*reginput != '\0' && *reginput != '\n') + if (*reginput != '\0' && *reginput != '\n') #else - if (*reginput != '\0') + if (*reginput != '\0') #endif - return(0); - break; - case ANY: + return(0); + break; + case ANY: #ifdef MULTILINE - if (*reginput == '\0' || *reginput == '\n') + if (*reginput == '\0' || *reginput == '\n') #else - if (*reginput == '\0') + if (*reginput == '\0') #endif - return(0); - reginput++; - break; - case EXACTLY: { - register int len; - register char *opnd; - - opnd = OPERAND(scan); - /* Inline the first character, for speed. */ - if (*opnd != *reginput) - return(0); - len = strlen(opnd); - if (len > 1 && strncmp(opnd, reginput, len) != 0) - return(0); - reginput += len; - } - break; - case ANYOF: - if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) == NULL) - return(0); - reginput++; - break; - case ANYBUT: + return(0); + reginput++; + break; + case EXACTLY: { + register int len; + register char *opnd; + + opnd = OPERAND(scan); + /* Inline the first character, for speed. */ + if (*opnd != *reginput) + return(0); + len = strlen(opnd); + if (len > 1 && strncmp(opnd, reginput, len) != 0) + return(0); + reginput += len; + } + break; + case ANYOF: + if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) == NULL) + return(0); + reginput++; + break; + case ANYBUT: #ifdef MULTILINE - if (*reginput == '\0' || *reginput == '\n' || - strchr(OPERAND(scan), *reginput) != NULL) + if (*reginput == '\0' || *reginput == '\n' || + strchr(OPERAND(scan), *reginput) != NULL) #else - if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) != NULL) + if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) != NULL) #endif - return(0); - reginput++; - break; - case NOTHING: - break; - case BACK: - break; - case OPEN+1: - case OPEN+2: - case OPEN+3: - case OPEN+4: - case OPEN+5: - case OPEN+6: - case OPEN+7: - case OPEN+8: - case OPEN+9: { - register int no; - register char *save; - - no = OP(scan) - OPEN; - save = reginput; - - if (regmatch(next)) { - /* - * Don't set startp if some later - * invocation of the same parentheses - * already has. - */ - if (regstartp[no] == NULL) - regstartp[no] = save; - return(1); - } else - return(0); - } - break; - case CLOSE+1: - case CLOSE+2: - case CLOSE+3: - case CLOSE+4: - case CLOSE+5: - case CLOSE+6: - case CLOSE+7: - case CLOSE+8: - case CLOSE+9: { - register int no; - register char *save; - - no = OP(scan) - CLOSE; - save = reginput; - - if (regmatch(next)) { - /* - * Don't set endp if some later - * invocation of the same parentheses - * already has. - */ - if (regendp[no] == NULL) - regendp[no] = save; - return(1); - } else - return(0); - } - break; - case BRANCH: { - register char *save; - - if (OP(next) != BRANCH) /* No choice. */ - next = OPERAND(scan); /* Avoid recursion. */ - else { - do { - save = reginput; - if (regmatch(OPERAND(scan))) - return(1); - reginput = save; - scan = regnext(scan); - } while (scan != NULL && OP(scan) == BRANCH); - return(0); - /* NOTREACHED */ - } - } - break; - case STAR: - case PLUS: { - register char nextch; - register int no; - register char *save; - register int min; - - /* - * Lookahead to avoid useless match attempts - * when we know what character comes next. - */ - nextch = '\0'; - if (OP(next) == EXACTLY) - nextch = *OPERAND(next); - min = (OP(scan) == STAR) ? 0 : 1; - save = reginput; - no = regrepeat(OPERAND(scan)); - while (no >= min) { - /* If it could work, try it. */ - if (nextch == '\0' || *reginput == nextch) - if (regmatch(next)) - return(1); - /* Couldn't or didn't -- back up. */ - no--; - reginput = save + no; - } - return(0); - } - break; - case END: - return(1); /* Success! */ - break; - default: - regerror("memory corruption"); - return(0); - break; - } - - scan = next; - } - - /* - * We get here only if there's trouble -- normally "case END" is - * the terminating point. - */ - regerror("corrupted pointers"); - return(0); + return(0); + reginput++; + break; + case NOTHING: + break; + case BACK: + break; + case OPEN+1: + case OPEN+2: + case OPEN+3: + case OPEN+4: + case OPEN+5: + case OPEN+6: + case OPEN+7: + case OPEN+8: + case OPEN+9: { + register int no; + register char *save; + + no = OP(scan) - OPEN; + save = reginput; + + if (regmatch(next)) { + /* + * Don't set startp if some later + * invocation of the same parentheses + * already has. + */ + if (regstartp[no] == NULL) + regstartp[no] = save; + return(1); + } else + return(0); + } + break; + case CLOSE+1: + case CLOSE+2: + case CLOSE+3: + case CLOSE+4: + case CLOSE+5: + case CLOSE+6: + case CLOSE+7: + case CLOSE+8: + case CLOSE+9: { + register int no; + register char *save; + + no = OP(scan) - CLOSE; + save = reginput; + + if (regmatch(next)) { + /* + * Don't set endp if some later + * invocation of the same parentheses + * already has. + */ + if (regendp[no] == NULL) + regendp[no] = save; + return(1); + } else + return(0); + } + break; + case BRANCH: { + register char *save; + + if (OP(next) != BRANCH) /* No choice. */ + next = OPERAND(scan); /* Avoid recursion. */ + else { + do { + save = reginput; + if (regmatch(OPERAND(scan))) + return(1); + reginput = save; + scan = regnext(scan); + } while (scan != NULL && OP(scan) == BRANCH); + return(0); + /* NOTREACHED */ + } + } + break; + case STAR: + case PLUS: { + register char nextch; + register int no; + register char *save; + register int min; + + /* + * Lookahead to avoid useless match attempts + * when we know what character comes next. + */ + nextch = '\0'; + if (OP(next) == EXACTLY) + nextch = *OPERAND(next); + min = (OP(scan) == STAR) ? 0 : 1; + save = reginput; + no = regrepeat(OPERAND(scan)); + while (no >= min) { + /* If it could work, try it. */ + if (nextch == '\0' || *reginput == nextch) + if (regmatch(next)) + return(1); + /* Couldn't or didn't -- back up. */ + no--; + reginput = save + no; + } + return(0); + } + break; + case END: + return(1); /* Success! */ + break; + default: + regerror("memory corruption"); + return(0); + break; + } + + scan = next; + } + + /* + * We get here only if there's trouble -- normally "case END" is + * the terminating point. + */ + regerror("corrupted pointers"); + return(0); } /* @@ -1149,58 +1149,58 @@ static int regrepeat(p) char *p; { - register int count = 0; - register char *scan; - register char *opnd; + register int count = 0; + register char *scan; + register char *opnd; #ifdef MULTILINE - register char *eol; + register char *eol; #endif - scan = reginput; - opnd = OPERAND(p); - switch (OP(p)) { - case ANY: + scan = reginput; + opnd = OPERAND(p); + switch (OP(p)) { + case ANY: #ifdef MULTILINE - if ((eol = strchr(scan, '\n')) != NULL) { - count += eol - scan; - scan = eol; - break; - } + if ((eol = strchr(scan, '\n')) != NULL) { + count += eol - scan; + scan = eol; + break; + } #endif - count = strlen(scan); - scan += count; - break; - case EXACTLY: - while (*opnd == *scan) { - count++; - scan++; - } - break; - case ANYOF: - while (*scan != '\0' && strchr(opnd, *scan) != NULL) { - count++; - scan++; - } - break; - case ANYBUT: + count = strlen(scan); + scan += count; + break; + case EXACTLY: + while (*opnd == *scan) { + count++; + scan++; + } + break; + case ANYOF: + while (*scan != '\0' && strchr(opnd, *scan) != NULL) { + count++; + scan++; + } + break; + case ANYBUT: #ifdef MULTILINE - while (*scan != '\0' && *scan != '\n' && - strchr(opnd, *scan) == NULL) { + while (*scan != '\0' && *scan != '\n' && + strchr(opnd, *scan) == NULL) { #else - while (*scan != '\0' && strchr(opnd, *scan) == NULL) { + while (*scan != '\0' && strchr(opnd, *scan) == NULL) { #endif - count++; - scan++; - } - break; - default: /* Oh dear. Called inappropriately. */ - regerror("internal foulup"); - count = 0; /* Best compromise. */ - break; - } - reginput = scan; - - return(count); + count++; + scan++; + } + break; + default: /* Oh dear. Called inappropriately. */ + regerror("internal foulup"); + count = 0; /* Best compromise. */ + break; + } + reginput = scan; + + return(count); } /* @@ -1210,19 +1210,19 @@ static char * regnext(p) register char *p; { - register int offset; + register int offset; - if (p == ®dummy) - return(NULL); + if (p == ®dummy) + return(NULL); - offset = NEXT(p); - if (offset == 0) - return(NULL); + offset = NEXT(p); + if (offset == 0) + return(NULL); - if (OP(p) == BACK) - return(p-offset); - else - return(p+offset); + if (OP(p) == BACK) + return(p-offset); + else + return(p+offset); } #ifdef DEBUG @@ -1236,46 +1236,46 @@ void regdump(r) regexp *r; { - register char *s; - register char op = EXACTLY; /* Arbitrary non-END op. */ - register char *next; - extern char *strchr(); - - - s = r->program + 1; - while (op != END) { /* While that wasn't END last time... */ - op = OP(s); - printf("%2d%s", (int)(s-r->program), regprop(s)); /* Where, what. */ - next = regnext(s); - if (next == NULL) /* Next ptr. */ - printf("(0)"); - else - printf("(%d)", (int)((s-r->program)+(next-s))); - s += 3; - if (op == ANYOF || op == ANYBUT || op == EXACTLY) { - /* Literal string, where present. */ - while (*s != '\0') { + register char *s; + register char op = EXACTLY; /* Arbitrary non-END op. */ + register char *next; + extern char *strchr(); + + + s = r->program + 1; + while (op != END) { /* While that wasn't END last time... */ + op = OP(s); + printf("%2d%s", (int)(s-r->program), regprop(s)); /* Where, what. */ + next = regnext(s); + if (next == NULL) /* Next ptr. */ + printf("(0)"); + else + printf("(%d)", (int)((s-r->program)+(next-s))); + s += 3; + if (op == ANYOF || op == ANYBUT || op == EXACTLY) { + /* Literal string, where present. */ + while (*s != '\0') { #ifdef MULTILINE - if (*s == '\n') - printf("\\n"); - else + if (*s == '\n') + printf("\\n"); + else #endif - putchar(*s); - s++; - } - s++; - } - putchar('\n'); - } - - /* Header fields of interest. */ - if (r->regstart != '\0') - printf("start `%c' ", r->regstart); - if (r->reganch) - printf("anchored "); - if (r->regmust != NULL) - printf("must have \"%s\"", r->regmust); - printf("\n"); + putchar(*s); + s++; + } + s++; + } + putchar('\n'); + } + + /* Header fields of interest. */ + if (r->regstart != '\0') + printf("start `%c' ", r->regstart); + if (r->reganch) + printf("anchored "); + if (r->regmust != NULL) + printf("must have \"%s\"", r->regmust); + printf("\n"); } /* @@ -1285,85 +1285,85 @@ static char * regprop(op) char *op; { - register char *p; - static char buf[50]; - - (void) strcpy(buf, ":"); - - switch (OP(op)) { - case BOL: - p = "BOL"; - break; - case EOL: - p = "EOL"; - break; - case ANY: - p = "ANY"; - break; - case ANYOF: - p = "ANYOF"; - break; - case ANYBUT: - p = "ANYBUT"; - break; - case BRANCH: - p = "BRANCH"; - break; - case EXACTLY: - p = "EXACTLY"; - break; - case NOTHING: - p = "NOTHING"; - break; - case BACK: - p = "BACK"; - break; - case END: - p = "END"; - break; - case OPEN+1: - case OPEN+2: - case OPEN+3: - case OPEN+4: - case OPEN+5: - case OPEN+6: - case OPEN+7: - case OPEN+8: - case OPEN+9: - sprintf(buf+strlen(buf), "OPEN%d", (int)(OP(op)-OPEN)); - p = NULL; - break; - case CLOSE+1: - case CLOSE+2: - case CLOSE+3: - case CLOSE+4: - case CLOSE+5: - case CLOSE+6: - case CLOSE+7: - case CLOSE+8: - case CLOSE+9: - sprintf(buf+strlen(buf), "CLOSE%d", (int)(OP(op)-CLOSE)); - p = NULL; - break; - case STAR: - p = "STAR"; - break; - case PLUS: - p = "PLUS"; - break; - default: - regerror("corrupted opcode"); - break; - } - if (p != NULL) - (void) strcat(buf, p); - return(buf); + register char *p; + static char buf[50]; + + (void) strcpy(buf, ":"); + + switch (OP(op)) { + case BOL: + p = "BOL"; + break; + case EOL: + p = "EOL"; + break; + case ANY: + p = "ANY"; + break; + case ANYOF: + p = "ANYOF"; + break; + case ANYBUT: + p = "ANYBUT"; + break; + case BRANCH: + p = "BRANCH"; + break; + case EXACTLY: + p = "EXACTLY"; + break; + case NOTHING: + p = "NOTHING"; + break; + case BACK: + p = "BACK"; + break; + case END: + p = "END"; + break; + case OPEN+1: + case OPEN+2: + case OPEN+3: + case OPEN+4: + case OPEN+5: + case OPEN+6: + case OPEN+7: + case OPEN+8: + case OPEN+9: + sprintf(buf+strlen(buf), "OPEN%d", (int)(OP(op)-OPEN)); + p = NULL; + break; + case CLOSE+1: + case CLOSE+2: + case CLOSE+3: + case CLOSE+4: + case CLOSE+5: + case CLOSE+6: + case CLOSE+7: + case CLOSE+8: + case CLOSE+9: + sprintf(buf+strlen(buf), "CLOSE%d", (int)(OP(op)-CLOSE)); + p = NULL; + break; + case STAR: + p = "STAR"; + break; + case PLUS: + p = "PLUS"; + break; + default: + regerror("corrupted opcode"); + break; + } + if (p != NULL) + (void) strcat(buf, p); + return(buf); } #endif /* * The following is provided for those people who do not have strcspn() in - * their C libraries. They should get off their butts and do something + * their C libraries. They should get off their butts and do something * about it; at least one public-domain implementation of those (highly * useful) string routines has been published on Usenet. */ @@ -1378,17 +1378,17 @@ strcspn(s1, s2) char *s1; char *s2; { - register char *scan1; - register char *scan2; - register int count; - - count = 0; - for (scan1 = s1; *scan1 != '\0'; scan1++) { - for (scan2 = s2; *scan2 != '\0';) /* ++ moved down. */ - if (*scan1 == *scan2++) - return(count); - count++; - } - return(count); + register char *scan1; + register char *scan2; + register int count; + + count = 0; + for (scan1 = s1; *scan1 != '\0'; scan1++) { + for (scan2 = s2; *scan2 != '\0';) /* ++ moved down. */ + if (*scan1 == *scan2++) + return(count); + count++; + } + return(count); } #endif diff --git a/src/regexp.h b/src/regexp.h index cbb1856..06d3ee6 100644 --- a/src/regexp.h +++ b/src/regexp.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -25,21 +25,21 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* * Definitions etc. for regexp(3) routines. * - * Caveat: this is V8 regexp(3) [actually, a reimplementation thereof], + * Caveat: this is V8 regexp(3) [actually, a reimplementation thereof], * not the System V one. */ #define MULTILINE -#define NSUBEXP 10 +#define NSUBEXP 10 typedef struct regexp { - char *startp[NSUBEXP]; - char *endp[NSUBEXP]; - char regstart; /* Internal use only. */ - char reganch; /* Internal use only. */ - char *regmust; /* Internal use only. */ - int regmlen; /* Internal use only. */ - char program[1]; /* Unwarranted chumminess with compiler. */ + char *startp[NSUBEXP]; + char *endp[NSUBEXP]; + char regstart; /* Internal use only. */ + char reganch; /* Internal use only. */ + char *regmust; /* Internal use only. */ + int regmlen; /* Internal use only. */ + char program[1]; /* Unwarranted chumminess with compiler. */ } regexp; extern regexp *regcomp(); diff --git a/src/regexpmodule.c b/src/regexpmodule.c index 62b22f2..fa54cd7 100644 --- a/src/regexpmodule.c +++ b/src/regexpmodule.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -30,162 +30,162 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include "regexp.h" -static object *RegexpError; /* Exception */ +static object *RegexpError; /* Exception */ typedef struct { - OB_HEAD - object *re_string; /* The string (for printing) */ - regexp *re_prog; /* The compiled regular expression */ + OB_HEAD + object *re_string; /* The string (for printing) */ + regexp *re_prog; /* The compiled regular expression */ } regexpobject; -static typeobject Regexptype; +extern typeobject Regexptype; /* Really static, forward */ static regexpobject * newregexpobject(string, prog) - object *string; - regexp *prog; + object *string; + regexp *prog; { - regexpobject *re; - re = NEWOBJ(regexpobject, &Regexptype); - if (re != NULL) { - XINCREF(string); - re->re_string = string; - re->re_prog = prog; - } - return re; + regexpobject *re; + re = NEWOBJ(regexpobject, &Regexptype); + if (re != NULL) { + XINCREF(string); + re->re_string = string; + re->re_prog = prog; + } + return re; } /* Regexp methods */ static void regexp_dealloc(re) - regexpobject *re; + regexpobject *re; { - XDECREF(re->re_string); - XDEL(re->re_prog); - DEL(re); + XDECREF(re->re_string); + XDEL(re->re_prog); + DEL(re); } static object * makeresult(prog, buffer) - regexp *prog; - char *buffer; + regexp *prog; + char *buffer; { - int n; - object *v; - /* Count substrings found, including \0, the main one */ - for (n = 0; n < 10 && prog->startp[n] != NULL; n++) - ; - v = newtupleobject(n); - if (v != NULL) { - int i; - for (i = 0; i < n; i++) { - object *w, *u; - long start, end; - start = prog->startp[i] - buffer; - end = prog->endp[i] - buffer; - if ( (w = newtupleobject(2)) == NULL || - (u = newintobject(start)) == NULL || - settupleitem(w, 0, u) != 0 || - (u = newintobject(end)) == NULL || - settupleitem(w, 1, u) != 0) { - XDECREF(w); - DECREF(v); - return NULL; - } - settupleitem(v, i, w); - } - } - return v; + int n; + object *v; + /* Count substrings found, including \0, the main one */ + for (n = 0; n < 10 && prog->startp[n] != NULL; n++) + ; + v = newtupleobject(n); + if (v != NULL) { + int i; + for (i = 0; i < n; i++) { + object *w, *u; + long start, end; + start = prog->startp[i] - buffer; + end = prog->endp[i] - buffer; + if ( (w = newtupleobject(2)) == NULL || + (u = newintobject(start)) == NULL || + settupleitem(w, 0, u) != 0 || + (u = newintobject(end)) == NULL || + settupleitem(w, 1, u) != 0) { + XDECREF(w); + DECREF(v); + return NULL; + } + settupleitem(v, i, w); + } + } + return v; } static object * regexp_exec(re, args) - regexpobject *re; - object *args; + regexpobject *re; + object *args; { - object *v; - char *buffer; - int offset; - if (args != NULL && is_stringobject(args)) { - v = args; - offset = 0; - } - else if (!getstrintarg(args, &v, &offset)) - return NULL; - buffer = getstringvalue(v); + object *v; + char *buffer; + int offset; + if (args != NULL && is_stringobject(args)) { + v = args; + offset = 0; + } + else if (!getstrintarg(args, &v, &offset)) + return NULL; + buffer = getstringvalue(v); #ifndef MULTILINE #define reglexec(prog, str, offset) regexec((prog), (str)+(offset)) #endif - if (!reglexec(re->re_prog, buffer, offset)) - return newtupleobject(0); - return makeresult(re->re_prog, buffer); + if (!reglexec(re->re_prog, buffer, offset)) + return newtupleobject(0); + return makeresult(re->re_prog, buffer); } static struct methodlist regexp_methods[] = { - "exec", regexp_exec, - {NULL, NULL} /* sentinel */ + "exec", regexp_exec, + {NULL, NULL} /* sentinel */ }; static object * regexp_getattr(re, name) - regexpobject *re; - char *name; + regexpobject *re; + char *name; { - return findmethod(regexp_methods, (object *)re, name); + return findmethod(regexp_methods, (object *)re, name); } static typeobject Regexptype = { - OB_HEAD_INIT(&Typetype) - 0, /*ob_size*/ - "regexp", /*tp_name*/ - sizeof(regexpobject), /*tp_size*/ - 0, /*tp_itemsize*/ - /* methods */ - regexp_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - regexp_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ + OB_HEAD_INIT(&Typetype) + 0, /*ob_size*/ + "regexp", /*tp_name*/ + sizeof(regexpobject), /*tp_size*/ + 0, /*tp_itemsize*/ + /* methods */ + regexp_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + regexp_getattr, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ }; void regerror(str) - char *str; + char *str; { - err_setstr(RegexpError, str); + err_setstr(RegexpError, str); } static object * regexp_compile(self, args) - object *self; - object *args; + object *self; + object *args; { - object *string; - regexp *prog; - if (!getstrarg(args, &string)) - return NULL; - prog = regcomp(getstringvalue(string)); - if (prog == NULL) - return NULL; /* regerror() has called err_seterr() */ - return (object *)newregexpobject(string, prog); + object *string; + regexp *prog; + if (!getstrarg(args, &string)) + return NULL; + prog = regcomp(getstringvalue(string)); + if (prog == NULL) + return NULL; /* regerror() has called err_seterr() */ + return (object *)newregexpobject(string, prog); } static struct methodlist regexp_global_methods[] = { - {"compile", regexp_compile}, - {NULL, NULL} /* sentinel */ + {"compile", regexp_compile}, + {NULL, NULL} /* sentinel */ }; initregexp() { - object *m, *d; - - m = initmodule("regexp", regexp_global_methods); - d = getmoduledict(m); - - /* Initialize regexp.error exception */ - RegexpError = newstringobject("regexp.error"); - if (RegexpError == NULL || dictinsert(d, "error", RegexpError) != 0) - fatal("can't define regexp.error"); + object *m, *d; + + m = initmodule("regexp", regexp_global_methods); + d = getmoduledict(m); + + /* Initialize regexp.error exception */ + RegexpError = newstringobject("regexp.error"); + if (RegexpError == NULL || dictinsert(d, "error", RegexpError) != 0) + fatal("can't define regexp.error"); } diff --git a/src/regmagic.h b/src/regmagic.h index d9da879..f02b2fe 100644 --- a/src/regmagic.h +++ b/src/regmagic.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -26,4 +26,4 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * The first byte of the regexp internal "program" is actually this magic * number; the start node begins in the second byte. */ -#define MAGIC 0234 +#define MAGIC 0234 diff --git a/src/regsub.c b/src/regsub.c index d589f26..0ac2285 100644 --- a/src/regsub.c +++ b/src/regsub.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -25,35 +25,35 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* * regsub * - * Copyright (c) 1986 by University of Toronto. - * Written by Henry Spencer. Not derived from licensed software. + * Copyright (c) 1986 by University of Toronto. + * Written by Henry Spencer. Not derived from licensed software. #ifdef MULTILINE - * Changed by Guido van Rossum, CWI, Amsterdam - * for multi-line support. + * Changed by Guido van Rossum, CWI, Amsterdam + * for multi-line support. #endif * - * Permission is granted to anyone to use this software for any - * purpose on any computer system, and to redistribute it freely, - * subject to the following restrictions: + * Permission is granted to anyone to use this software for any + * purpose on any computer system, and to redistribute it freely, + * subject to the following restrictions: * - * 1. The author is not responsible for the consequences of use of - * this software, no matter how awful, even if they arise - * from defects in it. + * 1. The author is not responsible for the consequences of use of + * this software, no matter how awful, even if they arise + * from defects in it. * - * 2. The origin of this software must not be misrepresented, either - * by explicit claim or by omission. + * 2. The origin of this software must not be misrepresented, either + * by explicit claim or by omission. * - * 3. Altered versions must be plainly marked as such, and must not - * be misrepresented as being the original software. + * 3. Altered versions must be plainly marked as such, and must not + * be misrepresented as being the original software. */ #include <stdio.h> #include "regexp.h" #include "regmagic.h" #ifndef CHARBITS -#define UCHARAT(p) ((int)*(unsigned char *)(p)) +#define UCHARAT(p) ((int)*(unsigned char *)(p)) #else -#define UCHARAT(p) ((int)*(p)&CHARBITS) +#define UCHARAT(p) ((int)*(p)&CHARBITS) #endif /* @@ -65,51 +65,51 @@ regexp *prog; char *source; char *dest; { - register char *src; - register char *dst; - register char c; - register int no; - register int len; - extern char *strncpy(); + register char *src; + register char *dst; + register char c; + register int no; + register int len; + extern char *strncpy(); - if (prog == NULL || source == NULL || dest == NULL) { - regerror("NULL parm to regsub"); - return; - } - if (UCHARAT(prog->program) != MAGIC) { - regerror("damaged regexp fed to regsub"); - return; - } + if (prog == NULL || source == NULL || dest == NULL) { + regerror("NULL parm to regsub"); + return; + } + if (UCHARAT(prog->program) != MAGIC) { + regerror("damaged regexp fed to regsub"); + return; + } - src = source; - dst = dest; - while ((c = *src++) != '\0') { - if (c == '&') - no = 0; - else if (c == '\\' && '0' <= *src && *src <= '9') - no = *src++ - '0'; - else - no = -1; + src = source; + dst = dest; + while ((c = *src++) != '\0') { + if (c == '&') + no = 0; + else if (c == '\\' && '0' <= *src && *src <= '9') + no = *src++ - '0'; + else + no = -1; - if (no < 0) { /* Ordinary character. */ - if (c == '\\' && (*src == '\\' || *src == '&')) - c = *src++; + if (no < 0) { /* Ordinary character. */ + if (c == '\\' && (*src == '\\' || *src == '&')) + c = *src++; #ifdef MULTILINE - else if (c == '\\' && *src == 'n') { - c = '\n'; - src++; - } + else if (c == '\\' && *src == 'n') { + c = '\n'; + src++; + } #endif - *dst++ = c; - } else if (prog->startp[no] != NULL && prog->endp[no] != NULL) { - len = prog->endp[no] - prog->startp[no]; - (void) strncpy(dst, prog->startp[no], len); - dst += len; - if (len != 0 && *(dst-1) == '\0') { /* strncpy hit NUL. */ - regerror("damaged match string"); - return; - } - } - } - *dst++ = '\0'; + *dst++ = c; + } else if (prog->startp[no] != NULL && prog->endp[no] != NULL) { + len = prog->endp[no] - prog->startp[no]; + (void) strncpy(dst, prog->startp[no], len); + dst += len; + if (len != 0 && *(dst-1) == '\0') { /* strncpy hit NUL. */ + regerror("damaged match string"); + return; + } + } + } + *dst++ = '\0'; } diff --git a/src/rltokenizer.c b/src/rltokenizer.c index 6069148..f4fde6f 100644 --- a/src/rltokenizer.c +++ b/src/rltokenizer.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. diff --git a/src/sc_errors.c b/src/sc_errors.c index be815a1..7ba2869 100644 --- a/src/sc_errors.c +++ b/src/sc_errors.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -34,112 +34,112 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. object * err_scerr(sc_errno) - int sc_errno; + int sc_errno; { - switch(sc_errno) { - - case NoBufSize: - err_setstr(StubcodeError, "Stubcode didn't start with BufSize"); - break; - - case TwoBufSize: - err_setstr(StubcodeError, "Stubcode can't have more then one BufSize"); - break; - - case ElementIsNull: - err_setstr(StubcodeError, "Trying to access an NIL object"); - break; - - case StackOverflow: - err_setstr(StubcodeError, "Stack overflow"); - return NULL; - - case StackUnderflow: - err_setstr(StubcodeError, "Stack underflow"); - return NULL; - - case NoEndLoop: - err_setstr(StubcodeError, "LoopXXX with no EndLoop"); - return NULL; - - case BufferOverflow: - err_setstr(StubcodeError, "Buffer overflow"); - return NULL; - - } - return NULL; + switch(sc_errno) { + + case NoBufSize: + err_setstr(StubcodeError, "Stubcode didn't start with BufSize"); + break; + + case TwoBufSize: + err_setstr(StubcodeError, "Stubcode can't have more then one BufSize"); + break; + + case ElementIsNull: + err_setstr(StubcodeError, "Trying to access an NIL object"); + break; + + case StackOverflow: + err_setstr(StubcodeError, "Stack overflow"); + return NULL; + + case StackUnderflow: + err_setstr(StubcodeError, "Stack underflow"); + return NULL; + + case NoEndLoop: + err_setstr(StubcodeError, "LoopXXX with no EndLoop"); + return NULL; + + case BufferOverflow: + err_setstr(StubcodeError, "Buffer overflow"); + return NULL; + + } + return NULL; } err_scerrset(sc_errno, value, instr) - int sc_errno; - object *value; - char *instr; + int sc_errno; + object *value; + char *instr; { - object *str, *str1, *t; - - if ((t = newtupleobject(3)) == NULL) { - return -1; - } - if ((str = newstringobject(instr)) == NULL) { - return -1; - } - if (settupleitem(t, 2, str) != 0) { - return -1; - } - INCREF(value); - if (settupleitem(t, 1, value) != 0) { - DECREF(t); - return -1; - } - switch(sc_errno) { - - case TypeFailure: - if ((str1 = newstringobject("Unexpected type")) == NULL) { - DECREF(t); - return -1; - } - break; - - case RangeError: - if ((str1 = newstringobject("Value out of range")) == NULL) { - DECREF(t); - return -1; - } - break; - - case SizeError: - if ((str1 = newstringobject("Value doesn't have the right size")) == NULL) { - DECREF(t); - return -1; - } - break; - - case FlagError: - if ((str1 = newstringobject("Illegal flag value")) == NULL) { - DECREF(t); - return -1; - } - break; - - case TransError: - if ((str1 = newstringobject("hdr.h_status != 0")) == NULL) { - DECREF(t); - return -1; - } - break; - - default: - if ((str1 = newstringobject("sc_errno not found")) == NULL) { - DECREF(t); - return -1; - } - break; - } - if (settupleitem(t, 0, str1) != 0) { - DECREF(t); - return -1; - } - err_setval(StubcodeError, t); - DECREF(t); - return -1; + object *str, *str1, *t; + + if ((t = newtupleobject(3)) == NULL) { + return -1; + } + if ((str = newstringobject(instr)) == NULL) { + return -1; + } + if (settupleitem(t, 2, str) != 0) { + return -1; + } + INCREF(value); + if (settupleitem(t, 1, value) != 0) { + DECREF(t); + return -1; + } + switch(sc_errno) { + + case TypeFailure: + if ((str1 = newstringobject("Unexpected type")) == NULL) { + DECREF(t); + return -1; + } + break; + + case RangeError: + if ((str1 = newstringobject("Value out of range")) == NULL) { + DECREF(t); + return -1; + } + break; + + case SizeError: + if ((str1 = newstringobject("Value doesn't have the right size")) == NULL) { + DECREF(t); + return -1; + } + break; + + case FlagError: + if ((str1 = newstringobject("Illegal flag value")) == NULL) { + DECREF(t); + return -1; + } + break; + + case TransError: + if ((str1 = newstringobject("hdr.h_status != 0")) == NULL) { + DECREF(t); + return -1; + } + break; + + default: + if ((str1 = newstringobject("sc_errno not found")) == NULL) { + DECREF(t); + return -1; + } + break; + } + if (settupleitem(t, 0, str1) != 0) { + DECREF(t); + return -1; + } + err_setval(StubcodeError, t); + DECREF(t); + return -1; } diff --git a/src/sc_errors.h b/src/sc_errors.h index d9fcd01..f67a3db 100644 --- a/src/sc_errors.h +++ b/src/sc_errors.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -23,18 +23,18 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ -#define NoBufSize 1 -#define TwoBufSize 2 -#define StackOverflow 3 -#define StackUnderflow 4 -#define TypeFailure 5 -#define RangeError 6 -#define SizeError 7 -#define BufferOverflow 8 -#define NoEndLoop 9 -#define FlagError 10 -#define ElementIsNull 11 -#define TransError 12 +#define NoBufSize 1 +#define TwoBufSize 2 +#define StackOverflow 3 +#define StackUnderflow 4 +#define TypeFailure 5 +#define RangeError 6 +#define SizeError 7 +#define BufferOverflow 8 +#define NoEndLoop 9 +#define FlagError 10 +#define ElementIsNull 11 +#define TransError 12 extern object *err_scerr PROTO((int sc_errno)); extern err_scerrset PROTO((int sc_errno, object *value, char *instr)); diff --git a/src/sc_global.h b/src/sc_global.h index ec03b15..a830dbd 100644 --- a/src/sc_global.h +++ b/src/sc_global.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -24,114 +24,114 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* -** This file contains the data used in Ail, Python and sc2txt. +** This file contains the data used in Ail, Python and sc2txt. ** -** If you want to add an instuction to the instructions just define -** it here and add the instruction in the function sc_interpreter in -** the file sc_interpreter.c in the switch. You also have to make a -** new function with the name x{instruction_name} in the file -** sc_interpreter. +** If you want to add an instuction to the instructions just define +** it here and add the instruction in the function sc_interpreter in +** the file sc_interpreter.c in the switch. You also have to make a +** new function with the name x{instruction_name} in the file +** sc_interpreter. */ /* -** When you want to change the types of the opcode or the operand -** you maybe need to adjust the options to mypf. And the defines : -** SwapOpcode, SwapOperand. +** When you want to change the types of the opcode or the operand +** you maybe need to adjust the options to mypf. And the defines : +** SwapOpcode, SwapOperand. */ typedef unsigned char TscOpcode; typedef long TscOperand; -#define SC_MAGIC 0x19901991 +#define SC_MAGIC 0x19901991 -#define SwapOpcode(x) x = x -#define SwapOperand(l) ((l))=(((((l))>>24)&0xFF)|((((l))>>8)&0xFF00)|((((l))<<8)&0xFF0000)|((((l))<<24)&0xFF000000)) +#define SwapOpcode(x) x = x +#define SwapOperand(l) ((l))=(((((l))>>24)&0xFF)|((((l))>>8)&0xFF00)|((((l))<<8)&0xFF0000)|((((l))<<24)&0xFF000000)) -#define STKSIZE 256 +#define STKSIZE 256 -#define OPERAND 0x80 -#define FLAGS 0x40 +#define OPERAND 0x80 +#define FLAGS 0x40 /* -** The headerfields. The value of the flag is the index of the fields -** array from the file mhdr.c plus one +** The headerfields. The value of the flag is the index of the fields +** array from the file mhdr.c plus one */ -#define H_EXTRA 0x00000001 -#define H_SIZE 0x00000002 -#define H_OFFSET 0x00000003 -#define H_PORT 0x00000004 -#define H_PRIV 0x00000005 -#define PSEUDOFIELD 0x00000006 -#define ALL_FIELDS 0x000000ff +#define H_EXTRA 0x00000001 +#define H_SIZE 0x00000002 +#define H_OFFSET 0x00000003 +#define H_PORT 0x00000004 +#define H_PRIV 0x00000005 +#define PSEUDOFIELD 0x00000006 +#define ALL_FIELDS 0x000000ff /* -** The specefiers for the integers +** The specefiers for the integers */ -#define NOSIGN 0x00000100 -#define INT32 0x00000200 -#define ALLTYPES 0xffffff00 +#define NOSIGN 0x00000100 +#define INT32 0x00000200 +#define ALLTYPES 0xffffff00 /* -** The opcode with no operand +** The opcode with no operand */ -#define ListS 0x00 -#define PutVS 0x01 -#define GetVS 0x02 -#define StringS 0x03 -#define Equal 0x04 -#define NoArgs 0x05 +#define ListS 0x00 +#define PutVS 0x01 +#define GetVS 0x02 +#define StringS 0x03 +#define Equal 0x04 +#define NoArgs 0x05 /* - * Between 0x10 and 0x3f there is space for predefined marshal - * and unmarshal functions or macros that do not have an operand + * Between 0x10 and 0x3f there is space for predefined marshal + * and unmarshal functions or macros that do not have an operand */ -#define MarshTC 0x10 -#define UnMarshTC 0x11 +#define MarshTC 0x10 +#define UnMarshTC 0x11 /* -** The opcode with a number as operand +** The opcode with a number as operand */ -#define BufSize 0x80 -#define Trans 0x81 -#define TTupleS 0x82 -#define Unpack 0x83 -#define PutFS 0x84 -#define TStringSeq 0x85 -#define TStringSlt 0x86 -#define TListSeq 0x87 -#define TListSlt 0x88 -#define LoopPut 0x89 -#define EndLoop 0x8a -#define Dup 0x8b -#define Pop 0x8c -#define Align 0x8d -#define Pack 0x8e -#define LoopGet 0x8f -#define GetFS 0x90 -#define PushI 0x91 +#define BufSize 0x80 +#define Trans 0x81 +#define TTupleS 0x82 +#define Unpack 0x83 +#define PutFS 0x84 +#define TStringSeq 0x85 +#define TStringSlt 0x86 +#define TListSeq 0x87 +#define TListSlt 0x88 +#define LoopPut 0x89 +#define EndLoop 0x8a +#define Dup 0x8b +#define Pop 0x8c +#define Align 0x8d +#define Pack 0x8e +#define LoopGet 0x8f +#define GetFS 0x90 +#define PushI 0x91 /* -** Between 0xa0 and 0xbf there is space for predefined marshal -** and unmarshal functions or macros with a numberas operand +** Between 0xa0 and 0xbf there is space for predefined marshal +** and unmarshal functions or macros with a numberas operand */ /* -** The opcodes with flags as operand +** The opcodes with flags as operand */ -#define AilWord 0xc0 -#define PutI 0xc1 -#define PutC 0xc2 -#define GetI 0xc3 -#define GetC 0xc4 +#define AilWord 0xc0 +#define PutI 0xc1 +#define PutC 0xc2 +#define GetI 0xc3 +#define GetC 0xc4 /* -** Between 0xe0 and 0xff there is space for predefined marshal -** and unmarshal functions or macros with flags as operand +** Between 0xe0 and 0xff there is space for predefined marshal +** and unmarshal functions or macros with flags as operand */ diff --git a/src/sc_interpr.c b/src/sc_interpr.c index 10eb1b2..6fec0e8 100644 --- a/src/sc_interpr.c +++ b/src/sc_interpr.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -43,410 +43,410 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include "listobject.h" typedef struct s_loopstruct { - struct s_loopstruct *l_next; /* Make a list of it */ - TscOperand l_label; /* Indentify the loop */ - int l_index; /* The index of the list */ - int l_size; /* The size of the list */ - int l_retaddr; /* Addres to jump back */ - int l_endaddr; /* Addres to jump to end */ - object *l_list; /* The list to append to */ + struct s_loopstruct *l_next; /* Make a list of it */ + TscOperand l_label; /* Indentify the loop */ + int l_index; /* The index of the list */ + int l_size; /* The size of the list */ + int l_retaddr; /* Addres to jump back */ + int l_endaddr; /* Addres to jump to end */ + object *l_list; /* The list to append to */ } TsLoop, *TpsLoop; /* -** This file contains the Stubcode interpreter. -** All the instructions have there own function. The interpreter -** reads an instruction from the data and if needed also an operand. -** After this it calls the function that executes the instruction. +** This file contains the Stubcode interpreter. +** All the instructions have there own function. The interpreter +** reads an instruction from the data and if needed also an operand. +** After this it calls the function that executes the instruction. */ struct sc_ProcessBlock { - object **stack; - unsigned char *buffer, *data; - int sp, bp, pc, maxbufsize, datsize; - header hdr; - TpsLoop loops; + object **stack; + unsigned char *buffer, *data; + int sp, bp, pc, maxbufsize, datsize; + header hdr; + TpsLoop loops; }; extern getcapability(); /* - * Clean up the mess the loops make. + * Clean up the mess the loops make. */ static void xCleanUpLoops(sc_pb) - struct sc_ProcessBlock *sc_pb; + struct sc_ProcessBlock *sc_pb; { - TpsLoop prev, this; - - if (sc_pb->loops == NULL) - return; - prev = sc_pb->loops; - this = sc_pb->loops->l_next; - while(this) { - free((char *)prev); - prev = this; - this = this->l_next; - } - free((char *)prev); + TpsLoop prev, this; + + if (sc_pb->loops == NULL) + return; + prev = sc_pb->loops; + this = sc_pb->loops->l_next; + while(this) { + free((char *)prev); + prev = this; + this = this->l_next; + } + free((char *)prev); } static int findendloop(label, sc_pb) - TscOperand label; - struct sc_ProcessBlock *sc_pb; + TscOperand label; + struct sc_ProcessBlock *sc_pb; { - TscOperand operand; - TscOpcode opcode; - int walk = sc_pb->pc, found = 0; - - while (!found && (walk < sc_pb->datsize)) { - memcpy(&opcode, &sc_pb->data[walk], sizeof(TscOpcode)); - walk += sizeof(TscOpcode); - if (opcode & (FLAGS | OPERAND)) { - memcpy(&operand, &sc_pb->data[walk], sizeof(TscOperand)); - walk += sizeof(TscOperand); - } - if (opcode == EndLoop) - if (operand == label) found = 1; - } - if (found) - return walk; - return -1; + TscOperand operand; + TscOpcode opcode; + int walk = sc_pb->pc, found = 0; + + while (!found && (walk < sc_pb->datsize)) { + memcpy(&opcode, &sc_pb->data[walk], sizeof(TscOpcode)); + walk += sizeof(TscOpcode); + if (opcode & (FLAGS | OPERAND)) { + memcpy(&operand, &sc_pb->data[walk], sizeof(TscOperand)); + walk += sizeof(TscOperand); + } + if (opcode == EndLoop) + if (operand == label) found = 1; + } + if (found) + return walk; + return -1; } static int findloop(ret, label, sc_pb) - TpsLoop *ret; - TscOperand label; - struct sc_ProcessBlock *sc_pb; + TpsLoop *ret; + TscOperand label; + struct sc_ProcessBlock *sc_pb; { - TpsLoop walk; - - for (walk = sc_pb->loops; walk != NULL; walk = walk->l_next) { - if (walk->l_label == label) break; - } - if (walk == NULL) { - TpsLoop newloop; - - newloop = (TpsLoop)malloc(sizeof(TsLoop)); - if (newloop == NULL) { - err_nomem(); - return -1; - } - newloop->l_label = label; - newloop->l_index = 0; - newloop->l_retaddr = sc_pb->pc - (sizeof(TscOpcode) + sizeof(TscOperand)); - /* - ** We need a correction because the pc points to - ** the instruction after the XXXLoop. - */ - if ((newloop->l_endaddr = findendloop(label, sc_pb)) < 0) { - free((char *)newloop); - err_scerr(NoEndLoop); - return -1; - } - newloop->l_list = NULL; - newloop->l_next = sc_pb->loops; - sc_pb->loops = newloop; - *ret = newloop; - return 1; - } - *ret = walk; - return 0; + TpsLoop walk; + + for (walk = sc_pb->loops; walk != NULL; walk = walk->l_next) { + if (walk->l_label == label) break; + } + if (walk == NULL) { + TpsLoop newloop; + + newloop = (TpsLoop)malloc(sizeof(TsLoop)); + if (newloop == NULL) { + err_nomem(); + return -1; + } + newloop->l_label = label; + newloop->l_index = 0; + newloop->l_retaddr = sc_pb->pc - (sizeof(TscOpcode) + sizeof(TscOperand)); + /* + ** We need a correction because the pc points to + ** the instruction after the XXXLoop. + */ + if ((newloop->l_endaddr = findendloop(label, sc_pb)) < 0) { + free((char *)newloop); + err_scerr(NoEndLoop); + return -1; + } + newloop->l_list = NULL; + newloop->l_next = sc_pb->loops; + sc_pb->loops = newloop; + *ret = newloop; + return 1; + } + *ret = walk; + return 0; } #ifdef 0 static void removeloop(this, sc_pb) - TpsLoop this; - struct sc_ProcessBlock *sc_pb; + TpsLoop this; + struct sc_ProcessBlock *sc_pb; { - TpsLoop walk, prev = NULL; - - for (walk = sc_pb->loops; walk != NULL; walk = walk->l_next) { - if (walk->l_label == this->l_label) { - if (prev != NULL) { - prev->l_next = walk->l_next; - } else { - loop = walk->l_next; - } - free((char *)this); - break; - } - prev = walk; - } + TpsLoop walk, prev = NULL; + + for (walk = sc_pb->loops; walk != NULL; walk = walk->l_next) { + if (walk->l_label == this->l_label) { + if (prev != NULL) { + prev->l_next = walk->l_next; + } else { + loop = walk->l_next; + } + free((char *)this); + break; + } + prev = walk; + } } #endif static int init(self, sc_pb) - object *self; - struct sc_ProcessBlock *sc_pb; + object *self; + struct sc_ProcessBlock *sc_pb; { object *string; int datasize; - string = gettupleitem(self, STUBC); - if (string == NULL) - return -1; - sc_pb->data = getstringvalue(string); - if (sc_pb->data == NULL) - return -1; - datasize = (int)getstringsize(string); - if (datasize == -1) - return -1; - sc_pb->stack = (object **)malloc(STKSIZE * sizeof(object *)); - if (sc_pb->stack == NULL) { - err_nomem(); - return -1; - } - sc_pb->bp = sc_pb->sp = sc_pb->pc = 0; - sc_pb->loops = NULL; - return datasize; + string = gettupleitem(self, STUBC); + if (string == NULL) + return -1; + sc_pb->data = getstringvalue(string); + if (sc_pb->data == NULL) + return -1; + datasize = (int)getstringsize(string); + if (datasize == -1) + return -1; + sc_pb->stack = (object **)malloc(STKSIZE * sizeof(object *)); + if (sc_pb->stack == NULL) { + err_nomem(); + return -1; + } + sc_pb->bp = sc_pb->sp = sc_pb->pc = 0; + sc_pb->loops = NULL; + return datasize; } static void reinit(sc_pb) - struct sc_ProcessBlock *sc_pb; + struct sc_ProcessBlock *sc_pb; { - int i; + int i; - sc_pb->bp = 0; - for (i = 0; i < sc_pb->sp; i++) { - DECREF(sc_pb->stack[i]); - } - sc_pb->sp = 0; + sc_pb->bp = 0; + for (i = 0; i < sc_pb->sp; i++) { + DECREF(sc_pb->stack[i]); + } + sc_pb->sp = 0; } static void UnInit(self, sc_pb) - object *self; - struct sc_ProcessBlock *sc_pb; + object *self; + struct sc_ProcessBlock *sc_pb; { - int i; + int i; - free(sc_pb->buffer); - reinit(sc_pb); - free((char *)sc_pb->stack); - xCleanUpLoops(sc_pb); + free(sc_pb->buffer); + reinit(sc_pb); + free((char *)sc_pb->stack); + xCleanUpLoops(sc_pb); } static object * stacktop(sc_pb) - struct sc_ProcessBlock *sc_pb; + struct sc_ProcessBlock *sc_pb; { - if (sc_pb->sp == 0) - return err_scerr(StackUnderflow); - if (sc_pb->sp == (STKSIZE + 1)) - return err_scerr(StackOverflow); - return sc_pb->stack[sc_pb->sp - 1]; + if (sc_pb->sp == 0) + return err_scerr(StackUnderflow); + if (sc_pb->sp == (STKSIZE + 1)) + return err_scerr(StackOverflow); + return sc_pb->stack[sc_pb->sp - 1]; } /* - * Push an object on the stack. + * Push an object on the stack. */ static int xPush(element, sc_pb) - object *element; - struct sc_ProcessBlock *sc_pb; + object *element; + struct sc_ProcessBlock *sc_pb; { - if (sc_pb->sp >= STKSIZE) { - err_scerr(StackOverflow); - return -1; - } - if (element == NULL) { - err_scerr(ElementIsNull); - return -1; - } - INCREF(element); + if (sc_pb->sp >= STKSIZE) { + err_scerr(StackOverflow); + return -1; + } + if (element == NULL) { + err_scerr(ElementIsNull); + return -1; + } + INCREF(element); #ifdef STACK_TRACE - printf("pushed :"); - printobject(element, stdout, 0); - printf("\n"); + printf("pushed :"); + printobject(element, stdout, 0); + printf("\n"); #endif - sc_pb->stack[sc_pb->sp++] = element; - return 0; + sc_pb->stack[sc_pb->sp++] = element; + return 0; } /* - * Perform the RPC. + * Perform the RPC. */ static int xTrans(self,cmd, sc_pb) - object *self; - TscOperand cmd; - struct sc_ProcessBlock *sc_pb; + object *self; + TscOperand cmd; + struct sc_ProcessBlock *sc_pb; { - short ret; - capability cap; - object *capobj; - - if ((capobj = gettupleitem(self, CAP)) == NULL) - return -1; - if (getcapability(capobj, &cap) == -1) - return -1; - sc_pb->hdr.h_port = cap.cap_port; - sc_pb->hdr.h_priv = cap.cap_priv; - sc_pb->hdr.h_command = (command)cmd; + short ret; + capability cap; + object *capobj; + + if ((capobj = gettupleitem(self, CAP)) == NULL) + return -1; + if (getcapability(capobj, &cap) == -1) + return -1; + sc_pb->hdr.h_port = cap.cap_port; + sc_pb->hdr.h_priv = cap.cap_priv; + sc_pb->hdr.h_command = (command)cmd; #ifdef SCDEBUG - printf("bp = %d maxbufsize = %d\n",sc_pb->bp, sc_pb->maxbufsize); - { - int i; - - for (i = 0; i < sc_pb->bp; i++) { - printf("%x ", sc_pb->buffer[i]); - } - } - printf("\n"); + printf("bp = %d maxbufsize = %d\n",sc_pb->bp, sc_pb->maxbufsize); + { + int i; + + for (i = 0; i < sc_pb->bp; i++) { + printf("%x ", sc_pb->buffer[i]); + } + } + printf("\n"); #endif - ret = trans(&sc_pb->hdr, sc_pb->buffer, (bufsize) sc_pb->bp, - &sc_pb->hdr, sc_pb->buffer, (bufsize)sc_pb->maxbufsize); + ret = trans(&sc_pb->hdr, sc_pb->buffer, (bufsize) sc_pb->bp, + &sc_pb->hdr, sc_pb->buffer, (bufsize)sc_pb->maxbufsize); #ifdef SCDEBUG - printf("after Trans:ret = %d\n",ret); - { - int i; - - for (i = 0; i < ret; i++) { - printf("%x ", sc_pb->buffer[i]); - } - } - printf("\n"); + printf("after Trans:ret = %d\n",ret); + { + int i; + + for (i = 0; i < ret; i++) { + printf("%x ", sc_pb->buffer[i]); + } + } + printf("\n"); #endif - if (ERR_STATUS(ret)) { - amoeba_error(ERR_CONVERT(ret)); - return -1; - } - if (sc_pb->hdr.h_status != 0) { - object *v; - - if ((v = newintobject(sc_pb->hdr.h_status)) == NULL) - return -1; - err_scerrset(TransError, v, "Trans"); - DECREF(v); - return -1; - } - reinit(sc_pb); - return 0; + if (ERR_STATUS(ret)) { + amoeba_error(ERR_CONVERT(ret)); + return -1; + } + if (sc_pb->hdr.h_status != 0) { + object *v; + + if ((v = newintobject(sc_pb->hdr.h_status)) == NULL) + return -1; + err_scerrset(TransError, v, "Trans"); + DECREF(v); + return -1; + } + reinit(sc_pb); + return 0; } /* - * Test the tuple size. + * Test the tuple size. */ static int xTTupleS(size, sc_pb) - TscOperand size; - struct sc_ProcessBlock *sc_pb; + TscOperand size; + struct sc_ProcessBlock *sc_pb; { - object *tuple; - - if ((tuple = stacktop(sc_pb)) == NULL) - return -1; - if (!is_tupleobject(tuple)) - return err_scerrset(TypeFailure, tuple, "TTupleS"); - if (gettuplesize(tuple) != (unsigned int)size) - return err_scerrset(SizeError, tuple, "TTupleS"); - return 0; + object *tuple; + + if ((tuple = stacktop(sc_pb)) == NULL) + return -1; + if (!is_tupleobject(tuple)) + return err_scerrset(TypeFailure, tuple, "TTupleS"); + if (gettuplesize(tuple) != (unsigned int)size) + return err_scerrset(SizeError, tuple, "TTupleS"); + return 0; } /* - * Unpack a tuple + * Unpack a tuple */ static int xUnpack(size, sc_pb) - TscOperand size; - struct sc_ProcessBlock *sc_pb; + TscOperand size; + struct sc_ProcessBlock *sc_pb; { - object *tuple, *element; - int i; - - if (size < (TscOperand)2) { - element = newintobject(size); - if (element == NULL) - return -1; - return err_scerrset(SizeError, element, "Unpack"); - } - if ((tuple = stacktop(sc_pb)) == NULL) - return -1; - INCREF(tuple); - if (xPop((TscOperand) 1, sc_pb) != 0) { - DECREF(tuple); - return -1; - } - for (i = 0; i < (int)size; i++) { - if ((element = gettupleitem(tuple, i)) == NULL) { - DECREF(tuple); - return -1; - } - if (xPush(element, sc_pb) != 0) { - DECREF(tuple); - return -1; - } - } - DECREF(tuple); - return 0; + object *tuple, *element; + int i; + + if (size < (TscOperand)2) { + element = newintobject(size); + if (element == NULL) + return -1; + return err_scerrset(SizeError, element, "Unpack"); + } + if ((tuple = stacktop(sc_pb)) == NULL) + return -1; + INCREF(tuple); + if (xPop((TscOperand) 1, sc_pb) != 0) { + DECREF(tuple); + return -1; + } + for (i = 0; i < (int)size; i++) { + if ((element = gettupleitem(tuple, i)) == NULL) { + DECREF(tuple); + return -1; + } + if (xPush(element, sc_pb) != 0) { + DECREF(tuple); + return -1; + } + } + DECREF(tuple); + return 0; } /* - * Marshal the Ailword to a headerfiels. + * Marshal the Ailword to a headerfiels. */ static int xAilword(headerfield, sc_pb) - TscOperand headerfield; - struct sc_ProcessBlock *sc_pb; + TscOperand headerfield; + struct sc_ProcessBlock *sc_pb; { - switch(headerfield) { - - case H_EXTRA: - sc_pb->hdr.h_extra = (uint16)_ailword; - return 0; - - case H_SIZE: - sc_pb->hdr.h_size = (bufsize)_ailword; - return 0; - - case H_OFFSET: - sc_pb->hdr.h_offset = (int32)_ailword; - return 0; - - default: - { - object *v; - - if ((v = newintobject(headerfield)) == NULL) - return -1; - return err_scerrset(FlagError, v, "Ailword"); - } - } + switch(headerfield) { + + case H_EXTRA: + sc_pb->hdr.h_extra = (uint16)_ailword; + return 0; + + case H_SIZE: + sc_pb->hdr.h_size = (bufsize)_ailword; + return 0; + + case H_OFFSET: + sc_pb->hdr.h_offset = (int32)_ailword; + return 0; + + default: + { + object *v; + + if ((v = newintobject(headerfield)) == NULL) + return -1; + return err_scerrset(FlagError, v, "Ailword"); + } + } } static int xStringS(sc_pb) - struct sc_ProcessBlock *sc_pb; + struct sc_ProcessBlock *sc_pb; { - object *size, *string; - int s; - - if ((string = stacktop(sc_pb)) == NULL) - return -1; - if (!is_stringobject(string)) - return err_scerrset(TypeFailure, string, "StringS"); - if ((s = getstringsize(string)) < 0) - return -1; - if (xPop((TscOperand) 1, sc_pb) != 0) - return -1; - if ((size = newintobject(s)) == NULL) - return -1; - if (xPush(size, sc_pb) != 0) { - DECREF(size); - return -1; - } - DECREF(size); - return 0; + object *size, *string; + int s; + + if ((string = stacktop(sc_pb)) == NULL) + return -1; + if (!is_stringobject(string)) + return err_scerrset(TypeFailure, string, "StringS"); + if ((s = getstringsize(string)) < 0) + return -1; + if (xPop((TscOperand) 1, sc_pb) != 0) + return -1; + if ((size = newintobject(s)) == NULL) + return -1; + if (xPush(size, sc_pb) != 0) { + DECREF(size); + return -1; + } + DECREF(size); + return 0; } /* @@ -454,27 +454,27 @@ xStringS(sc_pb) */ static int xListS(sc_pb) - struct sc_ProcessBlock *sc_pb; + struct sc_ProcessBlock *sc_pb; { - object *size, *list; - int s; - - if ((list = stacktop(sc_pb)) == NULL) - return -1; - if (!is_listobject(list)) - return err_scerrset(TypeFailure, list, "ListS"); - if ((s = getlistsize(list)) < 0) - return -1; - if (xPop((TscOperand) 1, sc_pb) != 0) - return -1; - if ((size = newintobject(s)) == NULL) - return -1; - if (xPush(size, sc_pb) != 0) { - DECREF(size); - return -1; - } - DECREF(size); - return 0; + object *size, *list; + int s; + + if ((list = stacktop(sc_pb)) == NULL) + return -1; + if (!is_listobject(list)) + return err_scerrset(TypeFailure, list, "ListS"); + if ((s = getlistsize(list)) < 0) + return -1; + if (xPop((TscOperand) 1, sc_pb) != 0) + return -1; + if ((size = newintobject(s)) == NULL) + return -1; + if (xPush(size, sc_pb) != 0) { + DECREF(size); + return -1; + } + DECREF(size); + return 0; } /* @@ -482,657 +482,657 @@ xListS(sc_pb) */ static int xPutFS(size, sc_pb) - TscOperand size; - struct sc_ProcessBlock *sc_pb; + TscOperand size; + struct sc_ProcessBlock *sc_pb; { - object *string; - char *str; - - if ((string = stacktop(sc_pb)) == NULL) { - return -1; - } - if (!is_stringobject(string)) - return err_scerrset(TypeFailure, string, "PutFS"); - if (getstringsize(string) != size) - return err_scerrset(SizeError, string, "PutFS"); - if ((str = getstringvalue(string)) == NULL) - return -1; - if ((size + sc_pb->bp) > sc_pb->maxbufsize) { - err_scerr(BufferOverflow); - return -1; - } - memcpy(&sc_pb->buffer[sc_pb->bp], str, (int)size); - sc_pb->bp += size; - return xPop((TscOperand) 1, sc_pb); + object *string; + char *str; + + if ((string = stacktop(sc_pb)) == NULL) { + return -1; + } + if (!is_stringobject(string)) + return err_scerrset(TypeFailure, string, "PutFS"); + if (getstringsize(string) != size) + return err_scerrset(SizeError, string, "PutFS"); + if ((str = getstringvalue(string)) == NULL) + return -1; + if ((size + sc_pb->bp) > sc_pb->maxbufsize) { + err_scerr(BufferOverflow); + return -1; + } + memcpy(&sc_pb->buffer[sc_pb->bp], str, (int)size); + sc_pb->bp += size; + return xPop((TscOperand) 1, sc_pb); } /* - * Test the size of a string or list + * Test the size of a string or list */ static int xTStringSeq(size, sc_pb) - TscOperand size; - struct sc_ProcessBlock *sc_pb; + TscOperand size; + struct sc_ProcessBlock *sc_pb; { - object *string; - - if ((string = stacktop(sc_pb)) == NULL) - return -1; - if (!is_stringobject(string)) - return err_scerrset(TypeFailure, string, "TStringSeq"); - if (getstringsize(string) != size) - return err_scerrset(SizeError, string, "TStringSeq"); - return 0; + object *string; + + if ((string = stacktop(sc_pb)) == NULL) + return -1; + if (!is_stringobject(string)) + return err_scerrset(TypeFailure, string, "TStringSeq"); + if (getstringsize(string) != size) + return err_scerrset(SizeError, string, "TStringSeq"); + return 0; } static int xTStringSlt(size, sc_pb) - TscOperand size; - struct sc_ProcessBlock *sc_pb; + TscOperand size; + struct sc_ProcessBlock *sc_pb; { - object *string; - - if ((string = stacktop(sc_pb)) == NULL) - return -1; - if (!is_stringobject(string)) - return err_scerrset(TypeFailure, string, "TStringSlt"); - if (getstringsize(string) > size) - return err_scerrset(SizeError, string, "TStringSlt"); - return 0; + object *string; + + if ((string = stacktop(sc_pb)) == NULL) + return -1; + if (!is_stringobject(string)) + return err_scerrset(TypeFailure, string, "TStringSlt"); + if (getstringsize(string) > size) + return err_scerrset(SizeError, string, "TStringSlt"); + return 0; } static int xTListSeq(size, sc_pb) - TscOperand size; - struct sc_ProcessBlock *sc_pb; + TscOperand size; + struct sc_ProcessBlock *sc_pb; { - object *list; - - if ((list = stacktop(sc_pb)) == NULL) - return -1; - if (!is_listobject(list)) - return err_scerrset(TypeFailure, list, "TListSeq"); - if (getlistsize(list) != size) - return err_scerrset(SizeError, list, "TListSeq"); - return 0; + object *list; + + if ((list = stacktop(sc_pb)) == NULL) + return -1; + if (!is_listobject(list)) + return err_scerrset(TypeFailure, list, "TListSeq"); + if (getlistsize(list) != size) + return err_scerrset(SizeError, list, "TListSeq"); + return 0; } static int xTListSlt(size, sc_pb) - TscOperand size; - struct sc_ProcessBlock *sc_pb; + TscOperand size; + struct sc_ProcessBlock *sc_pb; { - object *list; - - if ((list = stacktop(sc_pb)) == NULL) - return -1; - if (!is_listobject(list)) - return err_scerrset(TypeFailure, list, "TListSlt"); - if (getlistsize(list) > size) - return err_scerrset(SizeError, list, "TListSlt"); - return 0; + object *list; + + if ((list = stacktop(sc_pb)) == NULL) + return -1; + if (!is_listobject(list)) + return err_scerrset(TypeFailure, list, "TListSlt"); + if (getlistsize(list) > size) + return err_scerrset(SizeError, list, "TListSlt"); + return 0; } static int xPutVS(sc_pb) - struct sc_ProcessBlock *sc_pb; + struct sc_ProcessBlock *sc_pb; { - object *string; - char *str; - int size; - - if ((string = stacktop(sc_pb)) == NULL) - return -1; - if ((size = getstringsize(string)) < 0) - return (size == -1 ? -1 : err_scerrset(SizeError, string, "PutVS")); - if ((str = getstringvalue(string)) == NULL) - return -1; - if (sc_pb->bp + size > sc_pb->maxbufsize) { - err_scerr(BufferOverflow); - return -1; - } - memcpy(&sc_pb->buffer[sc_pb->bp], str, size); - sc_pb->bp += size; - return xPop((TscOperand) 1, sc_pb); + object *string; + char *str; + int size; + + if ((string = stacktop(sc_pb)) == NULL) + return -1; + if ((size = getstringsize(string)) < 0) + return (size == -1 ? -1 : err_scerrset(SizeError, string, "PutVS")); + if ((str = getstringvalue(string)) == NULL) + return -1; + if (sc_pb->bp + size > sc_pb->maxbufsize) { + err_scerr(BufferOverflow); + return -1; + } + memcpy(&sc_pb->buffer[sc_pb->bp], str, size); + sc_pb->bp += size; + return xPop((TscOperand) 1, sc_pb); } /* - * The loop instructions. + * The loop instructions. */ static int xLoopPut(label, sc_pb) - TscOperand label; - struct sc_ProcessBlock *sc_pb; + TscOperand label; + struct sc_ProcessBlock *sc_pb; { - TpsLoop this; - object *list, *element; - - if (findloop(&this, label, sc_pb) < 0) - return -1; - if ((list = stacktop(sc_pb)) == NULL) - return -1; - if (!is_listobject(list)) - return err_scerrset(TypeFailure, list, "LoopPut"); - if (this->l_index >= getlistsize(list)) { - sc_pb->pc = this->l_endaddr; - /* - ** Pop the list from the stack - */ - return xPop((TscOperand)1, sc_pb); - } - if ((element = getlistitem(list, this->l_index)) == NULL) - return -1; - return xPush(element, sc_pb); + TpsLoop this; + object *list, *element; + + if (findloop(&this, label, sc_pb) < 0) + return -1; + if ((list = stacktop(sc_pb)) == NULL) + return -1; + if (!is_listobject(list)) + return err_scerrset(TypeFailure, list, "LoopPut"); + if (this->l_index >= getlistsize(list)) { + sc_pb->pc = this->l_endaddr; + /* + ** Pop the list from the stack + */ + return xPop((TscOperand)1, sc_pb); + } + if ((element = getlistitem(list, this->l_index)) == NULL) + return -1; + return xPush(element, sc_pb); } static int xLoopGet(label, sc_pb) - TscOperand label; - struct sc_ProcessBlock *sc_pb; + TscOperand label; + struct sc_ProcessBlock *sc_pb; { - TpsLoop this; - object *element, *integer; - int i; - - if ((i = findloop(&this, label, sc_pb)) < 0) - return -1; - else if (i == 1) { - /* - * It is the first time we enter LoopGet label - */ - if ((this->l_list = newlistobject(0)) == NULL) - return -1; - if ((integer = stacktop(sc_pb)) == NULL) - return -1; - if (!is_intobject(integer)) - return err_scerrset(TypeFailure, integer, "LoopGet"); - this->l_size = getintvalue(integer); - if (xPop((TscOperand) 1, sc_pb) != 0) - return -1; - } else { - if ((element = stacktop(sc_pb)) == NULL) - return -1; - if (addlistitem(this->l_list, element) != 0) - return -1; - if (xPop((TscOperand) 1, sc_pb) != 0) - return -1; - } - if (this->l_index >= this->l_size) { - int ret; - - sc_pb->pc = this->l_endaddr; - ret = xPush(this->l_list, sc_pb); - DECREF(this->l_list); - return ret; - } - return 0; + TpsLoop this; + object *element, *integer; + int i; + + if ((i = findloop(&this, label, sc_pb)) < 0) + return -1; + else if (i == 1) { + /* + * It is the first time we enter LoopGet label + */ + if ((this->l_list = newlistobject(0)) == NULL) + return -1; + if ((integer = stacktop(sc_pb)) == NULL) + return -1; + if (!is_intobject(integer)) + return err_scerrset(TypeFailure, integer, "LoopGet"); + this->l_size = getintvalue(integer); + if (xPop((TscOperand) 1, sc_pb) != 0) + return -1; + } else { + if ((element = stacktop(sc_pb)) == NULL) + return -1; + if (addlistitem(this->l_list, element) != 0) + return -1; + if (xPop((TscOperand) 1, sc_pb) != 0) + return -1; + } + if (this->l_index >= this->l_size) { + int ret; + + sc_pb->pc = this->l_endaddr; + ret = xPush(this->l_list, sc_pb); + DECREF(this->l_list); + return ret; + } + return 0; } static int xEndLoop(label, sc_pb) - TscOperand label; - struct sc_ProcessBlock *sc_pb; + TscOperand label; + struct sc_ProcessBlock *sc_pb; { - TpsLoop this; + TpsLoop this; - if (findloop(&this, label, sc_pb) < 0) - return -1; - this ->l_index += 1; - sc_pb->pc = this->l_retaddr; - return 0; + if (findloop(&this, label, sc_pb) < 0) + return -1; + this ->l_index += 1; + sc_pb->pc = this->l_retaddr; + return 0; } static int xPutI(flags, sc_pb) - TscOperand flags; - struct sc_ProcessBlock *sc_pb; + TscOperand flags; + struct sc_ProcessBlock *sc_pb; { - object *integer; - - if ((integer = stacktop(sc_pb)) == NULL) - return -1; - if (!is_intobject(integer)) - return err_scerrset(TypeFailure, integer, "PutI"); - if (flags & ALL_FIELDS) { - long i; - - /* - * The integer must be marshalles in the header. - * No type casting according to the type flag because - * we have to cast to the headerfield types. - */ - i = getintvalue(integer); - switch(flags & ALL_FIELDS) { - - case H_EXTRA: - sc_pb->hdr.h_extra = (uint16)i; - break; - - case H_SIZE: - sc_pb->hdr.h_size = (bufsize)i; - break; - - case H_OFFSET: - sc_pb->hdr.h_offset = (int32)i; - break; - - default: - if ((integer = newintobject(flags & ALL_FIELDS)) == NULL) - return -1; - err_scerrset(FlagError, integer, "Ailword"); - DECREF(integer); - return -1; - } - } else { - long i; - - i = getintvalue(integer); - switch(flags & ALLTYPES) { - - case 0: - { - int16 x; - - x = (int16)i; - if ((sc_pb->bp + sizeof(int16)) > sc_pb->maxbufsize) { - err_scerr(BufferOverflow); - return -1; - } - memcpy(&sc_pb->buffer[sc_pb->bp], &x, sizeof(int16)); - sc_pb->bp += sizeof(int16); - break; - } - - case NOSIGN: - { - uint16 x; - - x = (uint16)i; - if ((sc_pb->bp + sizeof(uint16)) > sc_pb->maxbufsize) { - err_scerr(BufferOverflow); - return -1; - } - memcpy(&sc_pb->buffer[sc_pb->bp], &x, sizeof(uint16)); - sc_pb->bp += sizeof(uint16); - break; - } - - case INT32: - { - int32 x; - - x = (int32)i; - if ((sc_pb->bp + sizeof(int32)) > sc_pb->maxbufsize) { - err_scerr(BufferOverflow); - return -1; - } - memcpy(&sc_pb->buffer[sc_pb->bp], &x, sizeof(int32)); - sc_pb->bp += sizeof(int32); - break; - } - - case INT32 | NOSIGN: - { - uint32 x; - - x = (uint32)i; - if ((sc_pb->bp + sizeof(uint32)) > sc_pb->maxbufsize) { - err_scerr(BufferOverflow); - return -1; - } - memcpy(&sc_pb->buffer[sc_pb->bp], &x, sizeof(uint32)); - sc_pb->bp += sizeof(uint32); - break; - } - default: - { - object *x; - - if ((x = newintobject(flags)) == NULL) - return -1; - err_scerrset(FlagError, x, "PutI"); - DECREF(x); - return -1; - } - } - } - return xPop((TscOperand)1, sc_pb); + object *integer; + + if ((integer = stacktop(sc_pb)) == NULL) + return -1; + if (!is_intobject(integer)) + return err_scerrset(TypeFailure, integer, "PutI"); + if (flags & ALL_FIELDS) { + long i; + + /* + * The integer must be marshalles in the header. + * No type casting according to the type flag because + * we have to cast to the headerfield types. + */ + i = getintvalue(integer); + switch(flags & ALL_FIELDS) { + + case H_EXTRA: + sc_pb->hdr.h_extra = (uint16)i; + break; + + case H_SIZE: + sc_pb->hdr.h_size = (bufsize)i; + break; + + case H_OFFSET: + sc_pb->hdr.h_offset = (int32)i; + break; + + default: + if ((integer = newintobject(flags & ALL_FIELDS)) == NULL) + return -1; + err_scerrset(FlagError, integer, "Ailword"); + DECREF(integer); + return -1; + } + } else { + long i; + + i = getintvalue(integer); + switch(flags & ALLTYPES) { + + case 0: + { + int16 x; + + x = (int16)i; + if ((sc_pb->bp + sizeof(int16)) > sc_pb->maxbufsize) { + err_scerr(BufferOverflow); + return -1; + } + memcpy(&sc_pb->buffer[sc_pb->bp], &x, sizeof(int16)); + sc_pb->bp += sizeof(int16); + break; + } + + case NOSIGN: + { + uint16 x; + + x = (uint16)i; + if ((sc_pb->bp + sizeof(uint16)) > sc_pb->maxbufsize) { + err_scerr(BufferOverflow); + return -1; + } + memcpy(&sc_pb->buffer[sc_pb->bp], &x, sizeof(uint16)); + sc_pb->bp += sizeof(uint16); + break; + } + + case INT32: + { + int32 x; + + x = (int32)i; + if ((sc_pb->bp + sizeof(int32)) > sc_pb->maxbufsize) { + err_scerr(BufferOverflow); + return -1; + } + memcpy(&sc_pb->buffer[sc_pb->bp], &x, sizeof(int32)); + sc_pb->bp += sizeof(int32); + break; + } + + case INT32 | NOSIGN: + { + uint32 x; + + x = (uint32)i; + if ((sc_pb->bp + sizeof(uint32)) > sc_pb->maxbufsize) { + err_scerr(BufferOverflow); + return -1; + } + memcpy(&sc_pb->buffer[sc_pb->bp], &x, sizeof(uint32)); + sc_pb->bp += sizeof(uint32); + break; + } + default: + { + object *x; + + if ((x = newintobject(flags)) == NULL) + return -1; + err_scerrset(FlagError, x, "PutI"); + DECREF(x); + return -1; + } + } + } + return xPop((TscOperand)1, sc_pb); } static int xPutC(sc_pb) - struct sc_ProcessBlock *sc_pb; + struct sc_ProcessBlock *sc_pb; { - capability cap; - object *capobj; - - if ((capobj = stacktop(sc_pb)) == NULL) - return -1; - if (!is_capobj(capobj)) - return err_scerrset(TypeFailure, capobj, "xPutC"); - if (getcapability(capobj, &cap) != 0) - return -1; - if ((sc_pb->bp + CAPSIZE) > sc_pb->maxbufsize) { - err_scerr(BufferOverflow); - return -1; - } - memcpy(&sc_pb->buffer[sc_pb->bp], &cap, CAPSIZE); - sc_pb->bp += CAPSIZE; - return xPop((TscOperand) 1, sc_pb); + capability cap; + object *capobj; + + if ((capobj = stacktop(sc_pb)) == NULL) + return -1; + if (!is_capobj(capobj)) + return err_scerrset(TypeFailure, capobj, "xPutC"); + if (getcapability(capobj, &cap) != 0) + return -1; + if ((sc_pb->bp + CAPSIZE) > sc_pb->maxbufsize) { + err_scerr(BufferOverflow); + return -1; + } + memcpy(&sc_pb->buffer[sc_pb->bp], &cap, CAPSIZE); + sc_pb->bp += CAPSIZE; + return xPop((TscOperand) 1, sc_pb); } static int xDup(n, sc_pb) - TscOperand n; - struct sc_ProcessBlock *sc_pb; + TscOperand n; + struct sc_ProcessBlock *sc_pb; { - if ((int)n > sc_pb->sp) { - object *i; + if ((int)n > sc_pb->sp) { + object *i; - if ((i = newintobject((long)n)) == NULL) - return -1; - err_scerrset(RangeError, i, "Dup"); - DECREF(i); - return -1; - } - return xPush(sc_pb->stack[sc_pb->sp - n], sc_pb); + if ((i = newintobject((long)n)) == NULL) + return -1; + err_scerrset(RangeError, i, "Dup"); + DECREF(i); + return -1; + } + return xPush(sc_pb->stack[sc_pb->sp - n], sc_pb); } static int xPop(n, sc_pb) - TscOperand n; - struct sc_ProcessBlock *sc_pb; + TscOperand n; + struct sc_ProcessBlock *sc_pb; { - int i; - - if ((sc_pb->sp - (int)n) < 0) { - err_scerr(StackUnderflow); - return -1; - } - for (i = 0; i < (int)n; i++) { - sc_pb->sp--; + int i; + + if ((sc_pb->sp - (int)n) < 0) { + err_scerr(StackUnderflow); + return -1; + } + for (i = 0; i < (int)n; i++) { + sc_pb->sp--; #ifdef STACK_TRACE - printf("popped :"); - printobject(sc_pb->stack[sc_pb->sp], stdout, 0); - printf("\n"); + printf("popped :"); + printobject(sc_pb->stack[sc_pb->sp], stdout, 0); + printf("\n"); #endif - DECREF(sc_pb->stack[sc_pb->sp]); - } - return 0; + DECREF(sc_pb->stack[sc_pb->sp]); + } + return 0; } static int xAlign(n, sc_pb) - TscOperand n; - struct sc_ProcessBlock *sc_pb; + TscOperand n; + struct sc_ProcessBlock *sc_pb; { - int align = sc_pb->bp % (int)n; + int align = sc_pb->bp % (int)n; #ifdef SCDEBUG - printf("Old bp = %d\n", sc_pb->bp); + printf("Old bp = %d\n", sc_pb->bp); #endif - sc_pb->bp += (align == 0) ? 0 : ((int)n - align); + sc_pb->bp += (align == 0) ? 0 : ((int)n - align); #ifdef SCDEBUG - printf("New bp = %d\n", sc_pb->bp); + printf("New bp = %d\n", sc_pb->bp); #endif - return 0; + return 0; } static int xPack(size, sc_pb) - TscOperand size; - struct sc_ProcessBlock *sc_pb; + TscOperand size; + struct sc_ProcessBlock *sc_pb; { - object *element, *tuple; - int i, ret; - - if ((tuple = newtupleobject((int)size)) == NULL) - return -1; - for (i = 0; i < (int)size; i++) { - if ((element = stacktop(sc_pb)) == NULL) - return -1; - if (settupleitem(tuple, (int)size - i - 1, element) != 0) - return -1; - INCREF(element); - if (xPop((TscOperand) 1, sc_pb) != 0) - return -1; - } - ret = xPush(tuple, sc_pb); - DECREF(tuple); - return ret; + object *element, *tuple; + int i, ret; + + if ((tuple = newtupleobject((int)size)) == NULL) + return -1; + for (i = 0; i < (int)size; i++) { + if ((element = stacktop(sc_pb)) == NULL) + return -1; + if (settupleitem(tuple, (int)size - i - 1, element) != 0) + return -1; + INCREF(element); + if (xPop((TscOperand) 1, sc_pb) != 0) + return -1; + } + ret = xPush(tuple, sc_pb); + DECREF(tuple); + return ret; } static int xGetVS(sc_pb) - struct sc_ProcessBlock *sc_pb; + struct sc_ProcessBlock *sc_pb; { - object *string, *integer; - int size; - - if ((integer = stacktop(sc_pb)) == NULL) - return -1; - if (!is_intobject(integer)) - return err_scerrset(TypeFailure, integer, "GetVS"); - size = getintvalue(integer); - if ((sc_pb->bp + size) > sc_pb->maxbufsize) { - err_scerr(BufferOverflow); - return -1; - } - if ((string = newsizedstringobject(&sc_pb->buffer[sc_pb->bp], size)) == NULL) - return -1; - sc_pb->bp += size; - if (xPop((TscOperand) 1, sc_pb) != 0) - return -1; - if (xPush(string, sc_pb) != 0) { - return -1; - } - DECREF(string); - return 0; + object *string, *integer; + int size; + + if ((integer = stacktop(sc_pb)) == NULL) + return -1; + if (!is_intobject(integer)) + return err_scerrset(TypeFailure, integer, "GetVS"); + size = getintvalue(integer); + if ((sc_pb->bp + size) > sc_pb->maxbufsize) { + err_scerr(BufferOverflow); + return -1; + } + if ((string = newsizedstringobject(&sc_pb->buffer[sc_pb->bp], size)) == NULL) + return -1; + sc_pb->bp += size; + if (xPop((TscOperand) 1, sc_pb) != 0) + return -1; + if (xPush(string, sc_pb) != 0) { + return -1; + } + DECREF(string); + return 0; } static int xGetFS(size, sc_pb) - TscOperand size; - struct sc_ProcessBlock *sc_pb; + TscOperand size; + struct sc_ProcessBlock *sc_pb; { - object *string; - - if ((sc_pb->bp + (int)size) > sc_pb->maxbufsize) { - err_scerr(BufferOverflow); - return -1; - } - if ((string = newsizedstringobject(&sc_pb->buffer[sc_pb->bp], (int)size)) == NULL) - return -1; - sc_pb->bp += (int)size; - if(xPush(string, sc_pb) != 0) { - return -1; - } - DECREF(string); - return 0; + object *string; + + if ((sc_pb->bp + (int)size) > sc_pb->maxbufsize) { + err_scerr(BufferOverflow); + return -1; + } + if ((string = newsizedstringobject(&sc_pb->buffer[sc_pb->bp], (int)size)) == NULL) + return -1; + sc_pb->bp += (int)size; + if(xPush(string, sc_pb) != 0) { + return -1; + } + DECREF(string); + return 0; } static int xGetI(flags, sc_pb) - TscOperand flags; - struct sc_ProcessBlock *sc_pb; + TscOperand flags; + struct sc_ProcessBlock *sc_pb; { - object *integer; - long i; - - if (flags & ALL_FIELDS) { - - switch(flags & ALL_FIELDS) { - - case H_EXTRA: - i = (long)sc_pb->hdr.h_extra; - break; - - case H_SIZE: - i = (long)sc_pb->hdr.h_size; - break; - - case H_OFFSET: - i = (long)sc_pb->hdr.h_offset; - break; - - default: - if ((integer = newintobject(flags & ALL_FIELDS)) == NULL) - return -1; - err_scerrset(FlagError, integer, "Ailword"); - DECREF(integer); - return -1; - } - } else { - switch(flags & ALLTYPES) { - - case 0: - { - int16 x; - - if ((sc_pb->bp + sizeof(int16)) > sc_pb->maxbufsize) { - err_scerr(BufferOverflow); - return -1; - } - memcpy(&x, &sc_pb->buffer[sc_pb->bp], sizeof(int16)); - sc_pb->bp += sizeof(int16); - i = (long)x; - break; - } - - case NOSIGN: - { - uint16 x; - - if ((sc_pb->bp + sizeof(uint16)) > sc_pb->maxbufsize) { - err_scerr(BufferOverflow); - return -1; - } - memcpy(&x, &sc_pb->buffer[sc_pb->bp], sizeof(uint16)); - sc_pb->bp += sizeof(uint16); - i = (long)x; - break; - } - - case INT32: - { - int32 x; - - if ((sc_pb->bp + sizeof(int32)) > sc_pb->maxbufsize) { - err_scerr(BufferOverflow); - return -1; - } - memcpy(&x, &sc_pb->buffer[sc_pb->bp], sizeof(int32)); - sc_pb->bp += sizeof(int32); - i = (long)x; - break; - } - - case INT32 | NOSIGN: - { - uint32 x; - - if ((sc_pb->bp + sizeof(uint32)) > sc_pb->maxbufsize) { - err_scerr(BufferOverflow); - return -1; - } - memcpy(&x, &sc_pb->buffer[sc_pb->bp], sizeof(uint32)); - sc_pb->bp += sizeof(uint32); - i = (long)x; - break; - } - default: - { - if ((integer = newintobject(flags)) == NULL) - return -1; - err_scerrset(FlagError, integer, "GetI"); - DECREF(integer); - return -1; - } - } - } - if ((integer = newintobject(i)) == NULL) - return -1; - if (xPush(integer, sc_pb) != 0) { - DECREF(integer); - return -1; - } - DECREF(integer); - return 0; + object *integer; + long i; + + if (flags & ALL_FIELDS) { + + switch(flags & ALL_FIELDS) { + + case H_EXTRA: + i = (long)sc_pb->hdr.h_extra; + break; + + case H_SIZE: + i = (long)sc_pb->hdr.h_size; + break; + + case H_OFFSET: + i = (long)sc_pb->hdr.h_offset; + break; + + default: + if ((integer = newintobject(flags & ALL_FIELDS)) == NULL) + return -1; + err_scerrset(FlagError, integer, "Ailword"); + DECREF(integer); + return -1; + } + } else { + switch(flags & ALLTYPES) { + + case 0: + { + int16 x; + + if ((sc_pb->bp + sizeof(int16)) > sc_pb->maxbufsize) { + err_scerr(BufferOverflow); + return -1; + } + memcpy(&x, &sc_pb->buffer[sc_pb->bp], sizeof(int16)); + sc_pb->bp += sizeof(int16); + i = (long)x; + break; + } + + case NOSIGN: + { + uint16 x; + + if ((sc_pb->bp + sizeof(uint16)) > sc_pb->maxbufsize) { + err_scerr(BufferOverflow); + return -1; + } + memcpy(&x, &sc_pb->buffer[sc_pb->bp], sizeof(uint16)); + sc_pb->bp += sizeof(uint16); + i = (long)x; + break; + } + + case INT32: + { + int32 x; + + if ((sc_pb->bp + sizeof(int32)) > sc_pb->maxbufsize) { + err_scerr(BufferOverflow); + return -1; + } + memcpy(&x, &sc_pb->buffer[sc_pb->bp], sizeof(int32)); + sc_pb->bp += sizeof(int32); + i = (long)x; + break; + } + + case INT32 | NOSIGN: + { + uint32 x; + + if ((sc_pb->bp + sizeof(uint32)) > sc_pb->maxbufsize) { + err_scerr(BufferOverflow); + return -1; + } + memcpy(&x, &sc_pb->buffer[sc_pb->bp], sizeof(uint32)); + sc_pb->bp += sizeof(uint32); + i = (long)x; + break; + } + default: + { + if ((integer = newintobject(flags)) == NULL) + return -1; + err_scerrset(FlagError, integer, "GetI"); + DECREF(integer); + return -1; + } + } + } + if ((integer = newintobject(i)) == NULL) + return -1; + if (xPush(integer, sc_pb) != 0) { + DECREF(integer); + return -1; + } + DECREF(integer); + return 0; } static int xGetC(flags, sc_pb) - TscOperand flags; - struct sc_ProcessBlock *sc_pb; + TscOperand flags; + struct sc_ProcessBlock *sc_pb; { - extern object *newcapobject(); - object *capobj; - capability cap; - - if ((int)flags != 0) { - switch ((int)flags) { - - case PSEUDOFIELD: - cap.cap_port = sc_pb->hdr.h_port; - cap.cap_priv = sc_pb->hdr.h_priv; - break; - } - } else { - if ((CAPSIZE + sc_pb->bp) > sc_pb->maxbufsize) { - err_scerr(BufferOverflow); - return -1; - } - memcpy(&cap, &sc_pb->buffer[sc_pb->bp], CAPSIZE); - } - if ((capobj = newcapobject(&cap)) == NULL) - return -1; - return xPush(capobj, sc_pb); + extern object *newcapobject(); + object *capobj; + capability cap; + + if ((int)flags != 0) { + switch ((int)flags) { + + case PSEUDOFIELD: + cap.cap_port = sc_pb->hdr.h_port; + cap.cap_priv = sc_pb->hdr.h_priv; + break; + } + } else { + if ((CAPSIZE + sc_pb->bp) > sc_pb->maxbufsize) { + err_scerr(BufferOverflow); + return -1; + } + memcpy(&cap, &sc_pb->buffer[sc_pb->bp], CAPSIZE); + } + if ((capobj = newcapobject(&cap)) == NULL) + return -1; + return xPush(capobj, sc_pb); } static int xEqual(sc_pb) - struct sc_ProcessBlock *sc_pb; + struct sc_ProcessBlock *sc_pb; { - object *int1, *int2; - - if (sc_pb->sp < 2) { - err_scerr(StackUnderflow); - return -1; - } - int1 = sc_pb->stack[sc_pb->sp - 1]; - int2 = sc_pb->stack[sc_pb->sp - 2]; - if ((int1 == NULL) || (int2 == NULL)) - return -1; - if (!is_intobject(int1)) - return err_scerrset(TypeFailure, int1, "Equal"); - if (!is_intobject(int2)) - return err_scerrset(TypeFailure, int2, "Equal"); - if (getintvalue(int1) != getintvalue(int2)) { - object *tmptuple; - - if ((tmptuple = newtupleobject(2)) == NULL) - return -1; - INCREF(int1); - if (settupleitem(tmptuple, 0, int1) != 0) { - DECREF(tmptuple); - DECREF(int1); - return -1; - } - if (settupleitem(tmptuple, 1, int2) != 0) { - DECREF(tmptuple); - DECREF(int2); - return -1; - } - return err_scerrset(SizeError, tmptuple, "Equal"); - } - return 0; + object *int1, *int2; + + if (sc_pb->sp < 2) { + err_scerr(StackUnderflow); + return -1; + } + int1 = sc_pb->stack[sc_pb->sp - 1]; + int2 = sc_pb->stack[sc_pb->sp - 2]; + if ((int1 == NULL) || (int2 == NULL)) + return -1; + if (!is_intobject(int1)) + return err_scerrset(TypeFailure, int1, "Equal"); + if (!is_intobject(int2)) + return err_scerrset(TypeFailure, int2, "Equal"); + if (getintvalue(int1) != getintvalue(int2)) { + object *tmptuple; + + if ((tmptuple = newtupleobject(2)) == NULL) + return -1; + INCREF(int1); + if (settupleitem(tmptuple, 0, int1) != 0) { + DECREF(tmptuple); + DECREF(int1); + return -1; + } + if (settupleitem(tmptuple, 1, int2) != 0) { + DECREF(tmptuple); + DECREF(int2); + return -1; + } + return err_scerrset(SizeError, tmptuple, "Equal"); + } + return 0; } object * sc_interpreter(self, args) - object *self, *args; + object *self, *args; { TscOpcode opcode; TscOperand operand; @@ -1140,213 +1140,213 @@ int datasize, ret; object *returnobject; struct sc_ProcessBlock sc_pb; - if ((datasize = init(self, &sc_pb)) < 0) - return NULL; - memcpy(&opcode, sc_pb.data, sizeof(TscOpcode)); - sc_pb.datsize = datasize; - sc_pb.pc += sizeof(TscOpcode); - if (opcode != BufSize) { - free((char *)sc_pb.stack); - return err_scerr(NoBufSize); - } - memcpy(&operand, &sc_pb.data[sc_pb.pc], sizeof(TscOperand)); - sc_pb.pc += sizeof(TscOperand); - sc_pb.buffer = (unsigned char *)malloc(operand); - sc_pb.maxbufsize = (int)operand; - if (sc_pb.buffer == NULL) { - free((char *)sc_pb.stack); - return err_nomem(); - } - memcpy(&opcode, &sc_pb.data[sc_pb.pc], sizeof(TscOpcode)); - if (opcode != NoArgs) { - if (xPush(args, &sc_pb) != 0) { - UnInit(self, &sc_pb); - return NULL; - } - } - while (sc_pb.pc < datasize) { - memcpy(&opcode, &sc_pb.data[sc_pb.pc], sizeof(TscOpcode)); - sc_pb.pc += sizeof(TscOpcode); - if (opcode & (OPERAND | FLAGS)) { - memcpy(&operand, &sc_pb.data[sc_pb.pc], sizeof(TscOperand)); - sc_pb.pc += sizeof(TscOperand); - } + if ((datasize = init(self, &sc_pb)) < 0) + return NULL; + memcpy(&opcode, sc_pb.data, sizeof(TscOpcode)); + sc_pb.datsize = datasize; + sc_pb.pc += sizeof(TscOpcode); + if (opcode != BufSize) { + free((char *)sc_pb.stack); + return err_scerr(NoBufSize); + } + memcpy(&operand, &sc_pb.data[sc_pb.pc], sizeof(TscOperand)); + sc_pb.pc += sizeof(TscOperand); + sc_pb.buffer = (unsigned char *)malloc(operand); + sc_pb.maxbufsize = (int)operand; + if (sc_pb.buffer == NULL) { + free((char *)sc_pb.stack); + return err_nomem(); + } + memcpy(&opcode, &sc_pb.data[sc_pb.pc], sizeof(TscOpcode)); + if (opcode != NoArgs) { + if (xPush(args, &sc_pb) != 0) { + UnInit(self, &sc_pb); + return NULL; + } + } + while (sc_pb.pc < datasize) { + memcpy(&opcode, &sc_pb.data[sc_pb.pc], sizeof(TscOpcode)); + sc_pb.pc += sizeof(TscOpcode); + if (opcode & (OPERAND | FLAGS)) { + memcpy(&operand, &sc_pb.data[sc_pb.pc], sizeof(TscOperand)); + sc_pb.pc += sizeof(TscOperand); + } #ifdef SCDEBUG - xPrintCode(opcode); - if ((opcode & FLAGS) && (opcode & OPERAND)) - xPrintFlags(operand); - else if (opcode & OPERAND) - xPrintNum(operand); - printf("\n"); - fflush(stdout); + xPrintCode(opcode); + if ((opcode & FLAGS) && (opcode & OPERAND)) + xPrintFlags(operand); + else if (opcode & OPERAND) + xPrintNum(operand); + printf("\n"); + fflush(stdout); #endif #ifdef STACK_TRACE - { - register i; - - printf("Stack trace :\n"); - for(i = 0; i < sc_pb.sp; i++) { - printobject(sc_pb.stack[i], stdout, 0); - printf("\n"); - } - } + { + register i; + + printf("Stack trace :\n"); + for(i = 0; i < sc_pb.sp; i++) { + printobject(sc_pb.stack[i], stdout, 0); + printf("\n"); + } + } #endif - switch(opcode) { - - case NoArgs: - ret = 0; - if (args != NULL) { - err_scerrset(TypeFailure, args, "NoArgs"); - ret = -1; - } - break; - - case BufSize: - UnInit(self, &sc_pb); - return err_scerr(TwoBufSize); - - case Trans: - ret = xTrans(self, operand, &sc_pb); - break; - - case TTupleS: - ret = xTTupleS(operand, &sc_pb); - break; - - case Unpack: - ret = xUnpack(operand, &sc_pb); - break; - - case AilWord: - ret = xAilword(operand, &sc_pb); - break; - - case StringS: - ret = xStringS(&sc_pb); - break; - - case ListS: - ret = xListS(&sc_pb); - break; - - case PutFS: - ret = xPutFS(operand, &sc_pb); - break; - - case TStringSeq: - ret = xTStringSeq(operand, &sc_pb); - break; - - case TStringSlt: - ret = xTStringSlt(operand, &sc_pb); - break; - - case PutVS: - ret = xPutVS(&sc_pb); - break; - - case TListSeq: - ret = xTListSeq(operand, &sc_pb); - break; - - case TListSlt: - -ret = xTListSlt(operand, &sc_pb); - break; - - case LoopPut: - ret = xLoopPut(operand, &sc_pb); - break; - - case EndLoop: - ret = xEndLoop(operand, &sc_pb); - break; - - case PutI: - ret = xPutI(operand, &sc_pb); - break; - - case PutC: - ret = xPutC(&sc_pb); - break; - - case Dup: - ret = xDup(operand, &sc_pb); - break; - - case Pop: - ret = xPop(operand, &sc_pb); - break; - - case Align: - ret = xAlign(operand, &sc_pb); - break; - - case Pack: - ret = xPack(operand, &sc_pb); - break; - - case GetVS: - ret = xGetVS(&sc_pb); - break; - - case LoopGet: - ret = xLoopGet(operand, &sc_pb); - break; - - case GetFS: - ret = xGetFS(operand, &sc_pb); - break; - - case GetI: - ret = xGetI(operand, &sc_pb); - break; - - case GetC: - ret = xGetC(operand, &sc_pb); - break; - - case PushI: - { - object *element; - - element = newintobject((long)operand); - if (element == NULL) { - UnInit(self, &sc_pb); - return NULL; - } - ret = xPush(element, &sc_pb); - if (ret == 0) - DECREF(element); - } - break; - - case Equal: - ret = xEqual(&sc_pb); - break; - - default: - { - char errstr[256]; - - UnInit(self, &sc_pb); - sprintf(errstr, "Unknow stubcode %d", opcode); - err_setstr(RuntimeError, errstr); - return NULL; - } - } - if (ret != 0) { - UnInit(self, &sc_pb); - return NULL; - } - } - if (sc_pb.sp > 0) { - INCREF(sc_pb.stack[sc_pb.sp - 1]); - returnobject = sc_pb.stack[sc_pb.sp - 1]; - } else { - INCREF(None); - returnobject = None; - } - UnInit(self, &sc_pb); - return returnobject; + switch(opcode) { + + case NoArgs: + ret = 0; + if (args != NULL) { + err_scerrset(TypeFailure, args, "NoArgs"); + ret = -1; + } + break; + + case BufSize: + UnInit(self, &sc_pb); + return err_scerr(TwoBufSize); + + case Trans: + ret = xTrans(self, operand, &sc_pb); + break; + + case TTupleS: + ret = xTTupleS(operand, &sc_pb); + break; + + case Unpack: + ret = xUnpack(operand, &sc_pb); + break; + + case AilWord: + ret = xAilword(operand, &sc_pb); + break; + + case StringS: + ret = xStringS(&sc_pb); + break; + + case ListS: + ret = xListS(&sc_pb); + break; + + case PutFS: + ret = xPutFS(operand, &sc_pb); + break; + + case TStringSeq: + ret = xTStringSeq(operand, &sc_pb); + break; + + case TStringSlt: + ret = xTStringSlt(operand, &sc_pb); + break; + + case PutVS: + ret = xPutVS(&sc_pb); + break; + + case TListSeq: + ret = xTListSeq(operand, &sc_pb); + break; + + case TListSlt: + + ret = xTListSlt(operand, &sc_pb); + break; + + case LoopPut: + ret = xLoopPut(operand, &sc_pb); + break; + + case EndLoop: + ret = xEndLoop(operand, &sc_pb); + break; + + case PutI: + ret = xPutI(operand, &sc_pb); + break; + + case PutC: + ret = xPutC(&sc_pb); + break; + + case Dup: + ret = xDup(operand, &sc_pb); + break; + + case Pop: + ret = xPop(operand, &sc_pb); + break; + + case Align: + ret = xAlign(operand, &sc_pb); + break; + + case Pack: + ret = xPack(operand, &sc_pb); + break; + + case GetVS: + ret = xGetVS(&sc_pb); + break; + + case LoopGet: + ret = xLoopGet(operand, &sc_pb); + break; + + case GetFS: + ret = xGetFS(operand, &sc_pb); + break; + + case GetI: + ret = xGetI(operand, &sc_pb); + break; + + case GetC: + ret = xGetC(operand, &sc_pb); + break; + + case PushI: + { + object *element; + + element = newintobject((long)operand); + if (element == NULL) { + UnInit(self, &sc_pb); + return NULL; + } + ret = xPush(element, &sc_pb); + if (ret == 0) + DECREF(element); + } + break; + + case Equal: + ret = xEqual(&sc_pb); + break; + + default: + { + char errstr[256]; + + UnInit(self, &sc_pb); + sprintf(errstr, "Unknow stubcode %d", opcode); + err_setstr(RuntimeError, errstr); + return NULL; + } + } + if (ret != 0) { + UnInit(self, &sc_pb); + return NULL; + } + } + if (sc_pb.sp > 0) { + INCREF(sc_pb.stack[sc_pb.sp - 1]); + returnobject = sc_pb.stack[sc_pb.sp - 1]; + } else { + INCREF(None); + returnobject = None; + } + UnInit(self, &sc_pb); + return returnobject; } diff --git a/src/scdbg.c b/src/scdbg.c index 4510896..077dfc3 100644 --- a/src/scdbg.c +++ b/src/scdbg.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -29,7 +29,7 @@ void xPrintNum(Num) TscOperand Num; { - printf(" %ld",(long)Num); + printf(" %ld",(long)Num); } void xPrintFlags(Flags) @@ -37,116 +37,116 @@ TscOperand Flags; { long x; - x = (long)Flags; - x = x & 0x0000000F; - if (x == H_EXTRA) printf(" h_extra"); - if (x == H_SIZE) printf(" h_size"); - if (x == H_OFFSET) printf(" h_offset"); - if (x == H_PORT) printf(" h_port"); - if (x == H_PRIV) printf(" h_priv"); - if (x == PSEUDOFIELD) printf(" h_port and h_priv"); - x = (long)Flags; - if (x & NOSIGN) printf(" unsigned"); - if (x & INT32) printf(" int32"); + x = (long)Flags; + x = x & 0x0000000F; + if (x == H_EXTRA) printf(" h_extra"); + if (x == H_SIZE) printf(" h_size"); + if (x == H_OFFSET) printf(" h_offset"); + if (x == H_PORT) printf(" h_port"); + if (x == H_PRIV) printf(" h_priv"); + if (x == PSEUDOFIELD) printf(" h_port and h_priv"); + x = (long)Flags; + if (x & NOSIGN) printf(" unsigned"); + if (x & INT32) printf(" int32"); } void xPrintCode(Opcode) TscOpcode Opcode; { - switch (Opcode) { - - case BufSize: printf("BufSize"); - break; - - case Trans: printf("Trans"); - break; - - case TTupleS: printf("TTupleS"); - break; - - case Unpack: printf("Unpack"); - break; - - case AilWord: printf("AilWord"); - break; - - case ListS: printf("ListS"); - break; - - case StringS: printf("StringS"); - break; - - case PutFS: printf("PutFS"); - break; - - case TStringSeq: printf("TStringSeq"); - break; - - case TStringSlt: printf("TStringSlt"); - break; - - case PutVS: printf("PutVS"); - break; - - case TListSeq: printf("TListSeq"); - break; - - case TListSlt: printf("TListSlt"); - break; - - case LoopPut: printf("LoopPut"); - break; - - case EndLoop: printf("EndLoop"); - break; - - case PutI: printf("PutI"); - break; - - case PutC: printf("PutC"); - break; - - case Dup: printf("Dup"); - break; - - case Pop: printf("Pop"); - break; - - case Align: printf("Align"); - break; - - case Pack: printf("Pack"); - break; - - case GetVS: printf("GetVS"); - break; - - case LoopGet: printf("LoopGet"); - break; - - case GetFS: printf("GetFS"); - break; - - case GetI: printf("GetI"); - break; - - case GetC: printf("GetC"); - break; - - case PushI: printf("PushI"); - break; - - case MarshTC: printf("MarshTC"); - break; - - case UnMarshTC: printf("UnMarshTC"); - break; - - case Equal: printf("Equal"); - break; - - default: printf("Unknown opcode %04x",(int)Opcode); - break; - } + switch (Opcode) { + + case BufSize: printf("BufSize"); + break; + + case Trans: printf("Trans"); + break; + + case TTupleS: printf("TTupleS"); + break; + + case Unpack: printf("Unpack"); + break; + + case AilWord: printf("AilWord"); + break; + + case ListS: printf("ListS"); + break; + + case StringS: printf("StringS"); + break; + + case PutFS: printf("PutFS"); + break; + + case TStringSeq: printf("TStringSeq"); + break; + + case TStringSlt: printf("TStringSlt"); + break; + + case PutVS: printf("PutVS"); + break; + + case TListSeq: printf("TListSeq"); + break; + + case TListSlt: printf("TListSlt"); + break; + + case LoopPut: printf("LoopPut"); + break; + + case EndLoop: printf("EndLoop"); + break; + + case PutI: printf("PutI"); + break; + + case PutC: printf("PutC"); + break; + + case Dup: printf("Dup"); + break; + + case Pop: printf("Pop"); + break; + + case Align: printf("Align"); + break; + + case Pack: printf("Pack"); + break; + + case GetVS: printf("GetVS"); + break; + + case LoopGet: printf("LoopGet"); + break; + + case GetFS: printf("GetFS"); + break; + + case GetI: printf("GetI"); + break; + + case GetC: printf("GetC"); + break; + + case PushI: printf("PushI"); + break; + + case MarshTC: printf("MarshTC"); + break; + + case UnMarshTC: printf("UnMarshTC"); + break; + + case Equal: printf("Equal"); + break; + + default: printf("Unknown opcode %04x",(int)Opcode); + break; + } } diff --git a/src/sigtype.h b/src/sigtype.h index 5cfd4b3..d503ddb 100644 --- a/src/sigtype.h +++ b/src/sigtype.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -23,10 +23,10 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ /* The type of signal handlers is somewhat problematic. - This file encapsulates my knowledge about it: - - on the Mac (THINK C), it's int for 3.0, void for 4.0 - - on other systems, it's usually void, except it's int on vax Ultrix. - Pass -DSIGTYPE=... to cc if you know better. */ + This file encapsulates my knowledge about it: + - on the Mac (THINK C), it's int for 3.0, void for 4.0 + - on other systems, it's usually void, except it's int on vax Ultrix. + Pass -DSIGTYPE=... to cc if you know better. */ #ifndef SIGTYPE diff --git a/src/stdwinmodule.c b/src/stdwinmodule.c index 75b1fc8..bee2ddf 100644 --- a/src/stdwinmodule.c +++ b/src/stdwinmodule.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -25,41 +25,41 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* Stdwin module */ /* Stdwin itself is a module, not a separate object type. - Object types defined here: - wp: a window - dp: a drawing structure (only one can exist at a time) - mp: a menu - tp: a textedit block + Object types defined here: + wp: a window + dp: a drawing structure (only one can exist at a time) + mp: a menu + tp: a textedit block */ /* Rules for translating C stdwin function calls into Python stwin: - - All names drop their initial letter 'w' - - Functions with a window as first parameter are methods of window objects - - There is no equivalent for wclose(); just delete the window object - (all references to it!) (XXX maybe this is a bad idea) - - w.begindrawing() returns a drawing object - - There is no equivalent for wenddrawing(win); just delete the drawing - object (all references to it!) (XXX maybe this is a bad idea) - - Functions that may only be used inside wbegindrawing / wendddrawing - are methods of the drawing object; this includes the text measurement - functions (which however have doubles as module functions). - - Methods of the drawing object drop an initial 'draw' from their name - if they have it, e.g., wdrawline() --> d.line() - - The obvious type conversions: int --> intobject; string --> stringobject - - A text parameter followed by a length parameter is only a text (string) - parameter in Python - - A point or other pair of horizontal and vertical coordinates is always - a pair of integers in Python - - Two points forming a rectangle or endpoints of a line segment are a - pair of points in Python - - The arguments to d.elarc() are three points. - - The functions wgetclip() and wsetclip() are translated into - stdwin.getcutbuffer() and stdwin.setcutbuffer(); 'clip' is really - a bad word for what these functions do (clipping has a different - meaning in the drawing world), while cutbuffer is standard X jargon. - XXX This must change again in the light of changes to stdwin! - - For textedit, similar rules hold, but they are less strict. - XXX more? + - All names drop their initial letter 'w' + - Functions with a window as first parameter are methods of window objects + - There is no equivalent for wclose(); just delete the window object + (all references to it!) (XXX maybe this is a bad idea) + - w.begindrawing() returns a drawing object + - There is no equivalent for wenddrawing(win); just delete the drawing + object (all references to it!) (XXX maybe this is a bad idea) + - Functions that may only be used inside wbegindrawing / wendddrawing + are methods of the drawing object; this includes the text measurement + functions (which however have doubles as module functions). + - Methods of the drawing object drop an initial 'draw' from their name + if they have it, e.g., wdrawline() --> d.line() + - The obvious type conversions: int --> intobject; string --> stringobject + - A text parameter followed by a length parameter is only a text (string) + parameter in Python + - A point or other pair of horizontal and vertical coordinates is always + a pair of integers in Python + - Two points forming a rectangle or endpoints of a line segment are a + pair of points in Python + - The arguments to d.elarc() are three points. + - The functions wgetclip() and wsetclip() are translated into + stdwin.getcutbuffer() and stdwin.setcutbuffer(); 'clip' is really + a bad word for what these functions do (clipping has a different + meaning in the drawing world), while cutbuffer is standard X jargon. + XXX This must change again in the light of changes to stdwin! + - For textedit, similar rules hold, but they are less strict. + XXX more? */ #include "allobjects.h" @@ -71,24 +71,24 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* Window and menu object types declared here because of forward references */ typedef struct { - OB_HEAD - object *w_title; - WINDOW *w_win; - object *w_attr; /* Attributes dictionary */ + OB_HEAD + object *w_title; + WINDOW *w_win; + object *w_attr; /* Attributes dictionary */ } windowobject; -extern typeobject Windowtype; /* Really static, forward */ +extern typeobject Windowtype; /* Really static, forward */ #define is_windowobject(wp) ((wp)->ob_type == &Windowtype) typedef struct { - OB_HEAD - MENU *m_menu; - int m_id; - object *m_attr; /* Attributes dictionary */ + OB_HEAD + MENU *m_menu; + int m_id; + object *m_attr; /* Attributes dictionary */ } menuobject; -extern typeobject Menutype; /* Really static, forward */ +extern typeobject Menutype; /* Really static, forward */ #define is_menuobject(mp) ((mp)->ob_type == &Menutype) @@ -97,77 +97,77 @@ extern typeobject Menutype; /* Really static, forward */ static int getmousedetail(v, ep) - object *v; - EVENT *ep; + object *v; + EVENT *ep; { - if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 4) - return err_badarg(); - return getintintarg(gettupleitem(v, 0), - &ep->u.where.h, &ep->u.where.v) && - getintarg(gettupleitem(v, 1), &ep->u.where.clicks) && - getintarg(gettupleitem(v, 2), &ep->u.where.button) && - getintarg(gettupleitem(v, 3), &ep->u.where.mask); + if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 4) + return err_badarg(); + return getintintarg(gettupleitem(v, 0), + &ep->u.where.h, &ep->u.where.v) && + getintarg(gettupleitem(v, 1), &ep->u.where.clicks) && + getintarg(gettupleitem(v, 2), &ep->u.where.button) && + getintarg(gettupleitem(v, 3), &ep->u.where.mask); } static int getmenudetail(v, ep) - object *v; - EVENT *ep; + object *v; + EVENT *ep; { - object *mp; - if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) - return err_badarg(); - mp = gettupleitem(v, 0); - if (mp == NULL || !is_menuobject(mp)) - return err_badarg(); - ep->u.m.id = ((menuobject *)mp) -> m_id; - return getintarg(gettupleitem(v, 1), &ep->u.m.item); + object *mp; + if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) + return err_badarg(); + mp = gettupleitem(v, 0); + if (mp == NULL || !is_menuobject(mp)) + return err_badarg(); + ep->u.m.id = ((menuobject *)mp) -> m_id; + return getintarg(gettupleitem(v, 1), &ep->u.m.item); } static int geteventarg(v, ep) - object *v; - EVENT *ep; -{ - object *wp, *detail; - int a[4]; - if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 3) - return err_badarg(); - if (!getintarg(gettupleitem(v, 0), &ep->type)) - return 0; - wp = gettupleitem(v, 1); - if (wp == None) - ep->window = NULL; - else if (wp == NULL || !is_windowobject(wp)) - return err_badarg(); - else - ep->window = ((windowobject *)wp) -> w_win; - detail = gettupleitem(v, 2); - switch (ep->type) { - case WE_CHAR: - if (!is_stringobject(detail) || getstringsize(detail) != 1) - return err_badarg(); - ep->u.character = getstringvalue(detail)[0]; - return 1; - case WE_COMMAND: - return getintarg(detail, &ep->u.command); - case WE_DRAW: - if (!getrectarg(detail, a)) - return 0; - ep->u.area.left = a[0]; - ep->u.area.top = a[1]; - ep->u.area.right = a[2]; - ep->u.area.bottom = a[3]; - return 1; - case WE_MOUSE_DOWN: - case WE_MOUSE_UP: - case WE_MOUSE_MOVE: - return getmousedetail(detail, ep); - case WE_MENU: - return getmenudetail(detail, ep); - default: - return 1; - } + object *v; + EVENT *ep; +{ + object *wp, *detail; + int a[4]; + if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 3) + return err_badarg(); + if (!getintarg(gettupleitem(v, 0), &ep->type)) + return 0; + wp = gettupleitem(v, 1); + if (wp == None) + ep->window = NULL; + else if (wp == NULL || !is_windowobject(wp)) + return err_badarg(); + else + ep->window = ((windowobject *)wp) -> w_win; + detail = gettupleitem(v, 2); + switch (ep->type) { + case WE_CHAR: + if (!is_stringobject(detail) || getstringsize(detail) != 1) + return err_badarg(); + ep->u.character = getstringvalue(detail)[0]; + return 1; + case WE_COMMAND: + return getintarg(detail, &ep->u.command); + case WE_DRAW: + if (!getrectarg(detail, a)) + return 0; + ep->u.area.left = a[0]; + ep->u.area.top = a[1]; + ep->u.area.right = a[2]; + ep->u.area.bottom = a[3]; + return 1; + case WE_MOUSE_DOWN: + case WE_MOUSE_UP: + case WE_MOUSE_MOVE: + return getmousedetail(detail, ep); + case WE_MENU: + return getmenudetail(detail, ep); + default: + return 1; + } } @@ -175,87 +175,87 @@ geteventarg(v, ep) static object * makepoint(a, b) - int a, b; + int a, b; { - object *v; - object *w; - if ((v = newtupleobject(2)) == NULL) - return NULL; - if ((w = newintobject((long)a)) == NULL || - settupleitem(v, 0, w) != 0 || - (w = newintobject((long)b)) == NULL || - settupleitem(v, 1, w) != 0) { - DECREF(v); - return NULL; - } - return v; + object *v; + object *w; + if ((v = newtupleobject(2)) == NULL) + return NULL; + if ((w = newintobject((long)a)) == NULL || + settupleitem(v, 0, w) != 0 || + (w = newintobject((long)b)) == NULL || + settupleitem(v, 1, w) != 0) { + DECREF(v); + return NULL; + } + return v; } static object * makerect(a, b, c, d) - int a, b, c, d; + int a, b, c, d; { - object *v; - object *w; - if ((v = newtupleobject(2)) == NULL) - return NULL; - if ((w = makepoint(a, b)) == NULL || - settupleitem(v, 0, w) != 0 || - (w = makepoint(c, d)) == NULL || - settupleitem(v, 1, w) != 0) { - DECREF(v); - return NULL; - } - return v; + object *v; + object *w; + if ((v = newtupleobject(2)) == NULL) + return NULL; + if ((w = makepoint(a, b)) == NULL || + settupleitem(v, 0, w) != 0 || + (w = makepoint(c, d)) == NULL || + settupleitem(v, 1, w) != 0) { + DECREF(v); + return NULL; + } + return v; } static object * makemouse(hor, ver, clicks, button, mask) - int hor, ver, clicks, button, mask; -{ - object *v; - object *w; - if ((v = newtupleobject(4)) == NULL) - return NULL; - if ((w = makepoint(hor, ver)) == NULL || - settupleitem(v, 0, w) != 0 || - (w = newintobject((long)clicks)) == NULL || - settupleitem(v, 1, w) != 0 || - (w = newintobject((long)button)) == NULL || - settupleitem(v, 2, w) != 0 || - (w = newintobject((long)mask)) == NULL || - settupleitem(v, 3, w) != 0) { - DECREF(v); - return NULL; - } - return v; + int hor, ver, clicks, button, mask; +{ + object *v; + object *w; + if ((v = newtupleobject(4)) == NULL) + return NULL; + if ((w = makepoint(hor, ver)) == NULL || + settupleitem(v, 0, w) != 0 || + (w = newintobject((long)clicks)) == NULL || + settupleitem(v, 1, w) != 0 || + (w = newintobject((long)button)) == NULL || + settupleitem(v, 2, w) != 0 || + (w = newintobject((long)mask)) == NULL || + settupleitem(v, 3, w) != 0) { + DECREF(v); + return NULL; + } + return v; } static object * makemenu(mp, item) - object *mp; - int item; + object *mp; + int item; { - object *v; - object *w; - if ((v = newtupleobject(2)) == NULL) - return NULL; - INCREF(mp); - if (settupleitem(v, 0, mp) != 0 || - (w = newintobject((long)item)) == NULL || - settupleitem(v, 1, w) != 0) { - DECREF(v); - return NULL; - } - return v; + object *v; + object *w; + if ((v = newtupleobject(2)) == NULL) + return NULL; + INCREF(mp); + if (settupleitem(v, 0, mp) != 0 || + (w = newintobject((long)item)) == NULL || + settupleitem(v, 1, w) != 0) { + DECREF(v); + return NULL; + } + return v; } /* Drawing objects */ typedef struct { - OB_HEAD - windowobject *d_ref; + OB_HEAD + windowobject *d_ref; } drawingobject; static drawingobject *Drawing; /* Set to current drawing object, or NULL */ @@ -264,688 +264,688 @@ static drawingobject *Drawing; /* Set to current drawing object, or NULL */ static void drawing_dealloc(dp) - drawingobject *dp; + drawingobject *dp; { - wenddrawing(dp->d_ref->w_win); - Drawing = NULL; - DECREF(dp->d_ref); - free((char *)dp); + wenddrawing(dp->d_ref->w_win); + Drawing = NULL; + DECREF(dp->d_ref); + free((char *)dp); } static object * drawing_generic(dp, args, func) - drawingobject *dp; - object *args; - void (*func) FPROTO((int, int, int, int)); + drawingobject *dp; + object *args; + void (*func) FPROTO((int, int, int, int)); { - int a[4]; - if (!getrectarg(args, a)) - return NULL; - (*func)(a[0], a[1], a[2], a[3]); - INCREF(None); - return None; + int a[4]; + if (!getrectarg(args, a)) + return NULL; + (*func)(a[0], a[1], a[2], a[3]); + INCREF(None); + return None; } static object * drawing_line(dp, args) - drawingobject *dp; - object *args; + drawingobject *dp; + object *args; { - drawing_generic(dp, args, wdrawline); + drawing_generic(dp, args, wdrawline); } static object * drawing_xorline(dp, args) - drawingobject *dp; - object *args; + drawingobject *dp; + object *args; { - drawing_generic(dp, args, wxorline); + drawing_generic(dp, args, wxorline); } static object * drawing_circle(dp, args) - drawingobject *dp; - object *args; + drawingobject *dp; + object *args; { - int a[3]; - if (!getpointintarg(args, a)) - return NULL; - wdrawcircle(a[0], a[1], a[2]); - INCREF(None); - return None; + int a[3]; + if (!getpointintarg(args, a)) + return NULL; + wdrawcircle(a[0], a[1], a[2]); + INCREF(None); + return None; } static object * drawing_elarc(dp, args) - drawingobject *dp; - object *args; + drawingobject *dp; + object *args; { - int a[6]; - if (!get3pointarg(args, a)) - return NULL; - wdrawelarc(a[0], a[1], a[2], a[3], a[4], a[5]); - INCREF(None); - return None; + int a[6]; + if (!get3pointarg(args, a)) + return NULL; + wdrawelarc(a[0], a[1], a[2], a[3], a[4], a[5]); + INCREF(None); + return None; } static object * drawing_box(dp, args) - drawingobject *dp; - object *args; + drawingobject *dp; + object *args; { - drawing_generic(dp, args, wdrawbox); + drawing_generic(dp, args, wdrawbox); } static object * drawing_erase(dp, args) - drawingobject *dp; - object *args; + drawingobject *dp; + object *args; { - drawing_generic(dp, args, werase); + drawing_generic(dp, args, werase); } static object * drawing_paint(dp, args) - drawingobject *dp; - object *args; + drawingobject *dp; + object *args; { - drawing_generic(dp, args, wpaint); + drawing_generic(dp, args, wpaint); } static object * drawing_invert(dp, args) - drawingobject *dp; - object *args; + drawingobject *dp; + object *args; { - drawing_generic(dp, args, winvert); + drawing_generic(dp, args, winvert); } static object * drawing_cliprect(dp, args) - drawingobject *dp; - object *args; + drawingobject *dp; + object *args; { - drawing_generic(dp, args, wcliprect); + drawing_generic(dp, args, wcliprect); } static object * drawing_noclip(dp, args) - drawingobject *dp; - object *args; + drawingobject *dp; + object *args; { - if (!getnoarg(args)) - return NULL; - wnoclip(); - INCREF(None); - return None; + if (!getnoarg(args)) + return NULL; + wnoclip(); + INCREF(None); + return None; } static object * drawing_shade(dp, args) - drawingobject *dp; - object *args; + drawingobject *dp; + object *args; { - int a[5]; - if (!getrectintarg(args, a)) - return NULL; - wshade(a[0], a[1], a[2], a[3], a[4]); - INCREF(None); - return None; + int a[5]; + if (!getrectintarg(args, a)) + return NULL; + wshade(a[0], a[1], a[2], a[3], a[4]); + INCREF(None); + return None; } static object * drawing_text(dp, args) - drawingobject *dp; - object *args; + drawingobject *dp; + object *args; { - int a[2]; - object *s; - if (!getpointstrarg(args, a, &s)) - return NULL; - wdrawtext(a[0], a[1], getstringvalue(s), (int)getstringsize(s)); - INCREF(None); - return None; + int a[2]; + object *s; + if (!getpointstrarg(args, a, &s)) + return NULL; + wdrawtext(a[0], a[1], getstringvalue(s), (int)getstringsize(s)); + INCREF(None); + return None; } /* The following four are also used as stdwin functions */ static object * drawing_lineheight(dp, args) - drawingobject *dp; - object *args; + drawingobject *dp; + object *args; { - if (!getnoarg(args)) - return NULL; - return newintobject((long)wlineheight()); + if (!getnoarg(args)) + return NULL; + return newintobject((long)wlineheight()); } static object * drawing_baseline(dp, args) - drawingobject *dp; - object *args; + drawingobject *dp; + object *args; { - if (!getnoarg(args)) - return NULL; - return newintobject((long)wbaseline()); + if (!getnoarg(args)) + return NULL; + return newintobject((long)wbaseline()); } static object * drawing_textwidth(dp, args) - drawingobject *dp; - object *args; + drawingobject *dp; + object *args; { - object *s; - if (!getstrarg(args, &s)) - return NULL; - return newintobject( - (long)wtextwidth(getstringvalue(s), (int)getstringsize(s))); + object *s; + if (!getstrarg(args, &s)) + return NULL; + return newintobject( + (long)wtextwidth(getstringvalue(s), (int)getstringsize(s))); } static object * drawing_textbreak(dp, args) - drawingobject *dp; - object *args; + drawingobject *dp; + object *args; { - object *s; - int a; - if (!getstrintarg(args, &s, &a)) - return NULL; - return newintobject( - (long)wtextbreak(getstringvalue(s), (int)getstringsize(s), a)); + object *s; + int a; + if (!getstrintarg(args, &s, &a)) + return NULL; + return newintobject( + (long)wtextbreak(getstringvalue(s), (int)getstringsize(s), a)); } static struct methodlist drawing_methods[] = { - {"box", drawing_box}, - {"circle", drawing_circle}, - {"cliprect", drawing_cliprect}, - {"elarc", drawing_elarc}, - {"erase", drawing_erase}, - {"invert", drawing_invert}, - {"line", drawing_line}, - {"noclip", drawing_noclip}, - {"paint", drawing_paint}, - {"shade", drawing_shade}, - {"text", drawing_text}, - {"xorline", drawing_xorline}, - - /* Text measuring methods: */ - {"baseline", drawing_baseline}, - {"lineheight", drawing_lineheight}, - {"textbreak", drawing_textbreak}, - {"textwidth", drawing_textwidth}, - {NULL, NULL} /* sentinel */ + {"box", drawing_box}, + {"circle", drawing_circle}, + {"cliprect", drawing_cliprect}, + {"elarc", drawing_elarc}, + {"erase", drawing_erase}, + {"invert", drawing_invert}, + {"line", drawing_line}, + {"noclip", drawing_noclip}, + {"paint", drawing_paint}, + {"shade", drawing_shade}, + {"text", drawing_text}, + {"xorline", drawing_xorline}, + + /* Text measuring methods: */ + {"baseline", drawing_baseline}, + {"lineheight", drawing_lineheight}, + {"textbreak", drawing_textbreak}, + {"textwidth", drawing_textwidth}, + {NULL, NULL} /* sentinel */ }; static object * drawing_getattr(wp, name) - drawingobject *wp; - char *name; + drawingobject *wp; + char *name; { - return findmethod(drawing_methods, (object *)wp, name); + return findmethod(drawing_methods, (object *)wp, name); } static typeobject Drawingtype = { - OB_HEAD_INIT(&Typetype) - 0, /*ob_size*/ - "drawing", /*tp_name*/ - sizeof(drawingobject), /*tp_size*/ - 0, /*tp_itemsize*/ - /* methods */ - drawing_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - drawing_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ + OB_HEAD_INIT(&Typetype) + 0, /*ob_size*/ + "drawing", /*tp_name*/ + sizeof(drawingobject), /*tp_size*/ + 0, /*tp_itemsize*/ + /* methods */ + drawing_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + drawing_getattr, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ }; /* Text(edit) objects */ typedef struct { - OB_HEAD - TEXTEDIT *t_text; - windowobject *t_ref; - object *t_attr; /* Attributes dictionary */ + OB_HEAD + TEXTEDIT *t_text; + windowobject *t_ref; + object *t_attr; /* Attributes dictionary */ } textobject; -extern typeobject Texttype; /* Really static, forward */ +extern typeobject Texttype; /* Really static, forward */ static textobject * newtextobject(wp, left, top, right, bottom) - windowobject *wp; - int left, top, right, bottom; -{ - textobject *tp; - tp = NEWOBJ(textobject, &Texttype); - if (tp == NULL) - return NULL; - tp->t_attr = NULL; - INCREF(wp); - tp->t_ref = wp; - tp->t_text = tecreate(wp->w_win, left, top, right, bottom); - if (tp->t_text == NULL) { - DECREF(tp); - return (textobject *) err_nomem(); - } - return tp; + windowobject *wp; + int left, top, right, bottom; +{ + textobject *tp; + tp = NEWOBJ(textobject, &Texttype); + if (tp == NULL) + return NULL; + tp->t_attr = NULL; + INCREF(wp); + tp->t_ref = wp; + tp->t_text = tecreate(wp->w_win, left, top, right, bottom); + if (tp->t_text == NULL) { + DECREF(tp); + return (textobject *) err_nomem(); + } + return tp; } /* Text(edit) methods */ static void text_dealloc(tp) - textobject *tp; + textobject *tp; { - if (tp->t_text != NULL) - tefree(tp->t_text); - if (tp->t_attr != NULL) - DECREF(tp->t_attr); - DECREF(tp->t_ref); - DEL(tp); + if (tp->t_text != NULL) + tefree(tp->t_text); + if (tp->t_attr != NULL) + DECREF(tp->t_attr); + DECREF(tp->t_ref); + DEL(tp); } static object * text_arrow(self, args) - textobject *self; - object *args; + textobject *self; + object *args; { - int code; - if (!getintarg(args, &code)) - return NULL; - tearrow(self->t_text, code); - INCREF(None); - return None; + int code; + if (!getintarg(args, &code)) + return NULL; + tearrow(self->t_text, code); + INCREF(None); + return None; } static object * text_draw(self, args) - textobject *self; - object *args; -{ - register TEXTEDIT *tp = self->t_text; - int a[4]; - int left, top, right, bottom; - if (!getrectarg(args, a)) - return NULL; - if (Drawing != NULL) { - err_setstr(RuntimeError, "not drawing"); - return NULL; - } - /* Clip to text area and ignore if area is empty */ - left = tegetleft(tp); - top = tegettop(tp); - right = tegetright(tp); - bottom = tegetbottom(tp); - if (a[0] < left) a[0] = left; - if (a[1] < top) a[1] = top; - if (a[2] > right) a[2] = right; - if (a[3] > bottom) a[3] = bottom; - if (a[0] < a[2] && a[1] < a[3]) { - /* Hide/show focus around draw call; these are undocumented, - but required here to get the highlighting correct. - The call to werase is also required for this reason. - Finally, this forces us to require (above) that we are NOT - already drawing. */ - tehidefocus(tp); - wbegindrawing(self->t_ref->w_win); - werase(a[0], a[1], a[2], a[3]); - tedrawnew(tp, a[0], a[1], a[2], a[3]); - wenddrawing(self->t_ref->w_win); - teshowfocus(tp); - } - INCREF(None); - return None; + textobject *self; + object *args; +{ + register TEXTEDIT *tp = self->t_text; + int a[4]; + int left, top, right, bottom; + if (!getrectarg(args, a)) + return NULL; + if (Drawing != NULL) { + err_setstr(RuntimeError, "not drawing"); + return NULL; + } + /* Clip to text area and ignore if area is empty */ + left = tegetleft(tp); + top = tegettop(tp); + right = tegetright(tp); + bottom = tegetbottom(tp); + if (a[0] < left) a[0] = left; + if (a[1] < top) a[1] = top; + if (a[2] > right) a[2] = right; + if (a[3] > bottom) a[3] = bottom; + if (a[0] < a[2] && a[1] < a[3]) { + /* Hide/show focus around draw call; these are undocumented, + but required here to get the highlighting correct. + The call to werase is also required for this reason. + Finally, this forces us to require (above) that we are NOT + already drawing. */ + tehidefocus(tp); + wbegindrawing(self->t_ref->w_win); + werase(a[0], a[1], a[2], a[3]); + tedrawnew(tp, a[0], a[1], a[2], a[3]); + wenddrawing(self->t_ref->w_win); + teshowfocus(tp); + } + INCREF(None); + return None; } static object * text_event(self, args) - textobject *self; - object *args; -{ - register TEXTEDIT *tp = self->t_text; - EVENT e; - if (!geteventarg(args, &e)) - return NULL; - if (e.type == WE_MOUSE_DOWN) { - /* Cheat at the margins */ - int width, height; - wgetdocsize(e.window, &width, &height); - if (e.u.where.h < 0 && tegetleft(tp) == 0) - e.u.where.h = 0; - else if (e.u.where.h > width && tegetright(tp) == width) - e.u.where.h = width; - if (e.u.where.v < 0 && tegettop(tp) == 0) - e.u.where.v = 0; - else if (e.u.where.v > height && tegetright(tp) == height) - e.u.where.v = height; - } - return newintobject((long) teevent(tp, &e)); + textobject *self; + object *args; +{ + register TEXTEDIT *tp = self->t_text; + EVENT e; + if (!geteventarg(args, &e)) + return NULL; + if (e.type == WE_MOUSE_DOWN) { + /* Cheat at the margins */ + int width, height; + wgetdocsize(e.window, &width, &height); + if (e.u.where.h < 0 && tegetleft(tp) == 0) + e.u.where.h = 0; + else if (e.u.where.h > width && tegetright(tp) == width) + e.u.where.h = width; + if (e.u.where.v < 0 && tegettop(tp) == 0) + e.u.where.v = 0; + else if (e.u.where.v > height && tegetright(tp) == height) + e.u.where.v = height; + } + return newintobject((long) teevent(tp, &e)); } static object * text_getfocus(self, args) - textobject *self; - object *args; + textobject *self; + object *args; { - if (!getnoarg(args)) - return NULL; - return makepoint(tegetfoc1(self->t_text), tegetfoc2(self->t_text)); + if (!getnoarg(args)) + return NULL; + return makepoint(tegetfoc1(self->t_text), tegetfoc2(self->t_text)); } static object * text_getfocustext(self, args) - textobject *self; - object *args; + textobject *self; + object *args; { - int f1, f2; - char *text; - if (!getnoarg(args)) - return NULL; - f1 = tegetfoc1(self->t_text); - f2 = tegetfoc2(self->t_text); - text = tegettext(self->t_text); - return newsizedstringobject(text + f1, f2-f1); + int f1, f2; + char *text; + if (!getnoarg(args)) + return NULL; + f1 = tegetfoc1(self->t_text); + f2 = tegetfoc2(self->t_text); + text = tegettext(self->t_text); + return newsizedstringobject(text + f1, f2-f1); } static object * text_getrect(self, args) - textobject *self; - object *args; + textobject *self; + object *args; { - if (!getnoarg(args)) - return NULL; - return makerect(tegetleft(self->t_text), - tegettop(self->t_text), - tegetright(self->t_text), - tegetbottom(self->t_text)); + if (!getnoarg(args)) + return NULL; + return makerect(tegetleft(self->t_text), + tegettop(self->t_text), + tegetright(self->t_text), + tegetbottom(self->t_text)); } static object * text_gettext(self, args) - textobject *self; - object *args; + textobject *self; + object *args; { - if (!getnoarg(args)) - return NULL; - return newsizedstringobject(tegettext(self->t_text), - tegetlen(self->t_text)); + if (!getnoarg(args)) + return NULL; + return newsizedstringobject(tegettext(self->t_text), + tegetlen(self->t_text)); } static object * text_move(self, args) - textobject *self; - object *args; + textobject *self; + object *args; { - int a[4]; - if (!getrectarg(args, a)) - return NULL; - temovenew(self->t_text, a[0], a[1], a[2], a[3]); - INCREF(None); - return None; + int a[4]; + if (!getrectarg(args, a)) + return NULL; + temovenew(self->t_text, a[0], a[1], a[2], a[3]); + INCREF(None); + return None; } static object * text_setfocus(self, args) - textobject *self; - object *args; + textobject *self; + object *args; { - int a[2]; - if (!getpointarg(args, a)) - return NULL; - tesetfocus(self->t_text, a[0], a[1]); - INCREF(None); - return None; + int a[2]; + if (!getpointarg(args, a)) + return NULL; + tesetfocus(self->t_text, a[0], a[1]); + INCREF(None); + return None; } static object * text_replace(self, args) - textobject *self; - object *args; + textobject *self; + object *args; { - object *text; - if (!getstrarg(args, &text)) - return NULL; - tereplace(self->t_text, getstringvalue(text)); - INCREF(None); - return None; + object *text; + if (!getstrarg(args, &text)) + return NULL; + tereplace(self->t_text, getstringvalue(text)); + INCREF(None); + return None; } static struct methodlist text_methods[] = { - "arrow", text_arrow, - "draw", text_draw, - "event", text_event, - "getfocus", text_getfocus, - "getfocustext", text_getfocustext, - "getrect", text_getrect, - "gettext", text_gettext, - "move", text_move, - "replace", text_replace, - "setfocus", text_setfocus, - {NULL, NULL} /* sentinel */ + "arrow", text_arrow, + "draw", text_draw, + "event", text_event, + "getfocus", text_getfocus, + "getfocustext", text_getfocustext, + "getrect", text_getrect, + "gettext", text_gettext, + "move", text_move, + "replace", text_replace, + "setfocus", text_setfocus, + {NULL, NULL} /* sentinel */ }; static object * text_getattr(tp, name) - textobject *tp; - char *name; + textobject *tp; + char *name; { - if (tp->t_attr != NULL) { - object *v = dictlookup(tp->t_attr, name); - if (v != NULL) { - INCREF(v); - return v; - } - } - return findmethod(text_methods, (object *)tp, name); + if (tp->t_attr != NULL) { + object *v = dictlookup(tp->t_attr, name); + if (v != NULL) { + INCREF(v); + return v; + } + } + return findmethod(text_methods, (object *)tp, name); } static int text_setattr(tp, name, v) - textobject *tp; - char *name; - object *v; + textobject *tp; + char *name; + object *v; { - if (tp->t_attr == NULL) { - tp->t_attr = newdictobject(); - if (tp->t_attr == NULL) - return -1; - } - if (v == NULL) - return dictremove(tp->t_attr, name); - else - return dictinsert(tp->t_attr, name, v); + if (tp->t_attr == NULL) { + tp->t_attr = newdictobject(); + if (tp->t_attr == NULL) + return -1; + } + if (v == NULL) + return dictremove(tp->t_attr, name); + else + return dictinsert(tp->t_attr, name, v); } static typeobject Texttype = { - OB_HEAD_INIT(&Typetype) - 0, /*ob_size*/ - "textedit", /*tp_name*/ - sizeof(textobject), /*tp_size*/ - 0, /*tp_itemsize*/ - /* methods */ - text_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - text_getattr, /*tp_getattr*/ - text_setattr, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ + OB_HEAD_INIT(&Typetype) + 0, /*ob_size*/ + "textedit", /*tp_name*/ + sizeof(textobject), /*tp_size*/ + 0, /*tp_itemsize*/ + /* methods */ + text_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + text_getattr, /*tp_getattr*/ + text_setattr, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ }; /* Menu objects */ -#define IDOFFSET 10 /* Menu IDs we use start here */ -#define MAXNMENU 20 /* Max #menus we allow */ +#define IDOFFSET 10 /* Menu IDs we use start here */ +#define MAXNMENU 20 /* Max #menus we allow */ static menuobject *menulist[MAXNMENU]; static menuobject * newmenuobject(title) - object *title; -{ - int id; - MENU *menu; - menuobject *mp; - for (id = 0; id < MAXNMENU; id++) { - if (menulist[id] == NULL) - break; - } - if (id >= MAXNMENU) - return (menuobject *) err_nomem(); - menu = wmenucreate(id + IDOFFSET, getstringvalue(title)); - if (menu == NULL) - return (menuobject *) err_nomem(); - mp = NEWOBJ(menuobject, &Menutype); - if (mp != NULL) { - mp->m_menu = menu; - mp->m_id = id + IDOFFSET; - mp->m_attr = NULL; - menulist[id] = mp; - } - else - wmenudelete(menu); - return mp; + object *title; +{ + int id; + MENU *menu; + menuobject *mp; + for (id = 0; id < MAXNMENU; id++) { + if (menulist[id] == NULL) + break; + } + if (id >= MAXNMENU) + return (menuobject *) err_nomem(); + menu = wmenucreate(id + IDOFFSET, getstringvalue(title)); + if (menu == NULL) + return (menuobject *) err_nomem(); + mp = NEWOBJ(menuobject, &Menutype); + if (mp != NULL) { + mp->m_menu = menu; + mp->m_id = id + IDOFFSET; + mp->m_attr = NULL; + menulist[id] = mp; + } + else + wmenudelete(menu); + return mp; } /* Menu methods */ static void menu_dealloc(mp) - menuobject *mp; + menuobject *mp; { - - int id = mp->m_id - IDOFFSET; - if (id >= 0 && id < MAXNMENU && menulist[id] == mp) { - menulist[id] = NULL; - } - wmenudelete(mp->m_menu); - if (mp->m_attr != NULL) - DECREF(mp->m_attr); - DEL(mp); + + int id = mp->m_id - IDOFFSET; + if (id >= 0 && id < MAXNMENU && menulist[id] == mp) { + menulist[id] = NULL; + } + wmenudelete(mp->m_menu); + if (mp->m_attr != NULL) + DECREF(mp->m_attr); + DEL(mp); } static object * menu_additem(self, args) - menuobject *self; - object *args; -{ - object *text; - int shortcut; - if (is_tupleobject(args)) { - object *v; - if (!getstrstrarg(args, &text, &v)) - return NULL; - if (getstringsize(v) != 1) { - err_badarg(); - return NULL; - } - shortcut = *getstringvalue(v) & 0xff; - } - else { - if (!getstrarg(args, &text)) - return NULL; - shortcut = -1; - } - wmenuadditem(self->m_menu, getstringvalue(text), shortcut); - INCREF(None); - return None; + menuobject *self; + object *args; +{ + object *text; + int shortcut; + if (is_tupleobject(args)) { + object *v; + if (!getstrstrarg(args, &text, &v)) + return NULL; + if (getstringsize(v) != 1) { + err_badarg(); + return NULL; + } + shortcut = *getstringvalue(v) & 0xff; + } + else { + if (!getstrarg(args, &text)) + return NULL; + shortcut = -1; + } + wmenuadditem(self->m_menu, getstringvalue(text), shortcut); + INCREF(None); + return None; } static object * menu_setitem(self, args) - menuobject *self; - object *args; + menuobject *self; + object *args; { - int index; - object *text; - if (!getintstrarg(args, &index, &text)) - return NULL; - wmenusetitem(self->m_menu, index, getstringvalue(text)); - INCREF(None); - return None; + int index; + object *text; + if (!getintstrarg(args, &index, &text)) + return NULL; + wmenusetitem(self->m_menu, index, getstringvalue(text)); + INCREF(None); + return None; } static object * menu_enable(self, args) - menuobject *self; - object *args; + menuobject *self; + object *args; { - int index; - int flag; - if (!getintintarg(args, &index, &flag)) - return NULL; - wmenuenable(self->m_menu, index, flag); - INCREF(None); - return None; + int index; + int flag; + if (!getintintarg(args, &index, &flag)) + return NULL; + wmenuenable(self->m_menu, index, flag); + INCREF(None); + return None; } static object * menu_check(self, args) - menuobject *self; - object *args; + menuobject *self; + object *args; { - int index; - int flag; - if (!getintintarg(args, &index, &flag)) - return NULL; - wmenucheck(self->m_menu, index, flag); - INCREF(None); - return None; + int index; + int flag; + if (!getintintarg(args, &index, &flag)) + return NULL; + wmenucheck(self->m_menu, index, flag); + INCREF(None); + return None; } static struct methodlist menu_methods[] = { - "additem", menu_additem, - "setitem", menu_setitem, - "enable", menu_enable, - "check", menu_check, - {NULL, NULL} /* sentinel */ + "additem", menu_additem, + "setitem", menu_setitem, + "enable", menu_enable, + "check", menu_check, + {NULL, NULL} /* sentinel */ }; static object * menu_getattr(mp, name) - menuobject *mp; - char *name; + menuobject *mp; + char *name; { - if (mp->m_attr != NULL) { - object *v = dictlookup(mp->m_attr, name); - if (v != NULL) { - INCREF(v); - return v; - } - } - return findmethod(menu_methods, (object *)mp, name); + if (mp->m_attr != NULL) { + object *v = dictlookup(mp->m_attr, name); + if (v != NULL) { + INCREF(v); + return v; + } + } + return findmethod(menu_methods, (object *)mp, name); } static int menu_setattr(mp, name, v) - menuobject *mp; - char *name; - object *v; + menuobject *mp; + char *name; + object *v; { - if (mp->m_attr == NULL) { - mp->m_attr = newdictobject(); - if (mp->m_attr == NULL) - return -1; - } - if (v == NULL) - return dictremove(mp->m_attr, name); - else - return dictinsert(mp->m_attr, name, v); + if (mp->m_attr == NULL) { + mp->m_attr = newdictobject(); + if (mp->m_attr == NULL) + return -1; + } + if (v == NULL) + return dictremove(mp->m_attr, name); + else + return dictinsert(mp->m_attr, name, v); } static typeobject Menutype = { - OB_HEAD_INIT(&Typetype) - 0, /*ob_size*/ - "menu", /*tp_name*/ - sizeof(menuobject), /*tp_size*/ - 0, /*tp_itemsize*/ - /* methods */ - menu_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - menu_getattr, /*tp_getattr*/ - menu_setattr, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ + OB_HEAD_INIT(&Typetype) + 0, /*ob_size*/ + "menu", /*tp_name*/ + sizeof(menuobject), /*tp_size*/ + 0, /*tp_itemsize*/ + /* methods */ + menu_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + menu_getattr, /*tp_getattr*/ + menu_setattr, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ }; @@ -958,740 +958,740 @@ static windowobject *windowlist[MAXNWIN]; static void window_dealloc(wp) - windowobject *wp; -{ - if (wp->w_win != NULL) { - int tag = wgettag(wp->w_win); - if (tag >= 0 && tag < MAXNWIN) - windowlist[tag] = NULL; - else - fprintf(stderr, "XXX help! tag %d in window_dealloc\n", - tag); - wclose(wp->w_win); - } - DECREF(wp->w_title); - if (wp->w_attr != NULL) - DECREF(wp->w_attr); - free((char *)wp); + windowobject *wp; +{ + if (wp->w_win != NULL) { + int tag = wgettag(wp->w_win); + if (tag >= 0 && tag < MAXNWIN) + windowlist[tag] = NULL; + else + fprintf(stderr, "XXX help! tag %d in window_dealloc\n", + tag); + wclose(wp->w_win); + } + DECREF(wp->w_title); + if (wp->w_attr != NULL) + DECREF(wp->w_attr); + free((char *)wp); } static void window_print(wp, fp, flags) - windowobject *wp; - FILE *fp; - int flags; + windowobject *wp; + FILE *fp; + int flags; { - fprintf(fp, "<window titled '%s'>", getstringvalue(wp->w_title)); + fprintf(fp, "<window titled '%s'>", getstringvalue(wp->w_title)); } static object * window_begindrawing(wp, args) - windowobject *wp; - object *args; -{ - drawingobject *dp; - if (!getnoarg(args)) - return NULL; - if (Drawing != NULL) { - err_setstr(RuntimeError, "already drawing"); - return NULL; - } - dp = NEWOBJ(drawingobject, &Drawingtype); - if (dp == NULL) - return NULL; - Drawing = dp; - INCREF(wp); - dp->d_ref = wp; - wbegindrawing(wp->w_win); - return (object *)dp; + windowobject *wp; + object *args; +{ + drawingobject *dp; + if (!getnoarg(args)) + return NULL; + if (Drawing != NULL) { + err_setstr(RuntimeError, "already drawing"); + return NULL; + } + dp = NEWOBJ(drawingobject, &Drawingtype); + if (dp == NULL) + return NULL; + Drawing = dp; + INCREF(wp); + dp->d_ref = wp; + wbegindrawing(wp->w_win); + return (object *)dp; } static object * window_change(wp, args) - windowobject *wp; - object *args; + windowobject *wp; + object *args; { - int a[4]; - if (!getrectarg(args, a)) - return NULL; - wchange(wp->w_win, a[0], a[1], a[2], a[3]); - INCREF(None); - return None; + int a[4]; + if (!getrectarg(args, a)) + return NULL; + wchange(wp->w_win, a[0], a[1], a[2], a[3]); + INCREF(None); + return None; } static object * window_gettitle(wp, args) - windowobject *wp; - object *args; + windowobject *wp; + object *args; { - if (!getnoarg(args)) - return NULL; - INCREF(wp->w_title); - return wp->w_title; + if (!getnoarg(args)) + return NULL; + INCREF(wp->w_title); + return wp->w_title; } static object * window_getwinsize(wp, args) - windowobject *wp; - object *args; + windowobject *wp; + object *args; { - int width, height; - if (!getnoarg(args)) - return NULL; - wgetwinsize(wp->w_win, &width, &height); - return makepoint(width, height); + int width, height; + if (!getnoarg(args)) + return NULL; + wgetwinsize(wp->w_win, &width, &height); + return makepoint(width, height); } static object * window_getdocsize(wp, args) - windowobject *wp; - object *args; + windowobject *wp; + object *args; { - int width, height; - if (!getnoarg(args)) - return NULL; - wgetdocsize(wp->w_win, &width, &height); - return makepoint(width, height); + int width, height; + if (!getnoarg(args)) + return NULL; + wgetdocsize(wp->w_win, &width, &height); + return makepoint(width, height); } static object * window_getorigin(wp, args) - windowobject *wp; - object *args; + windowobject *wp; + object *args; { - int width, height; - if (!getnoarg(args)) - return NULL; - wgetorigin(wp->w_win, &width, &height); - return makepoint(width, height); + int width, height; + if (!getnoarg(args)) + return NULL; + wgetorigin(wp->w_win, &width, &height); + return makepoint(width, height); } static object * window_scroll(wp, args) - windowobject *wp; - object *args; + windowobject *wp; + object *args; { - int a[6]; - if (!getrectpointarg(args, a)) - return NULL; - wscroll(wp->w_win, a[0], a[1], a[2], a[3], a[4], a[5]); - INCREF(None); - return None; + int a[6]; + if (!getrectpointarg(args, a)) + return NULL; + wscroll(wp->w_win, a[0], a[1], a[2], a[3], a[4], a[5]); + INCREF(None); + return None; } static object * window_setdocsize(wp, args) - windowobject *wp; - object *args; + windowobject *wp; + object *args; { - int a[2]; - if (!getpointarg(args, a)) - return NULL; - wsetdocsize(wp->w_win, a[0], a[1]); - INCREF(None); - return None; + int a[2]; + if (!getpointarg(args, a)) + return NULL; + wsetdocsize(wp->w_win, a[0], a[1]); + INCREF(None); + return None; } static object * window_setorigin(wp, args) - windowobject *wp; - object *args; + windowobject *wp; + object *args; { - int a[2]; - if (!getpointarg(args, a)) - return NULL; - wsetorigin(wp->w_win, a[0], a[1]); - INCREF(None); - return None; + int a[2]; + if (!getpointarg(args, a)) + return NULL; + wsetorigin(wp->w_win, a[0], a[1]); + INCREF(None); + return None; } static object * window_settitle(wp, args) - windowobject *wp; - object *args; + windowobject *wp; + object *args; { - object *title; - if (!getstrarg(args, &title)) - return NULL; - DECREF(wp->w_title); - INCREF(title); - wp->w_title = title; - wsettitle(wp->w_win, getstringvalue(title)); - INCREF(None); - return None; + object *title; + if (!getstrarg(args, &title)) + return NULL; + DECREF(wp->w_title); + INCREF(title); + wp->w_title = title; + wsettitle(wp->w_win, getstringvalue(title)); + INCREF(None); + return None; } static object * window_show(wp, args) - windowobject *wp; - object *args; + windowobject *wp; + object *args; { - int a[4]; - if (!getrectarg(args, a)) - return NULL; - wshow(wp->w_win, a[0], a[1], a[2], a[3]); - INCREF(None); - return None; + int a[4]; + if (!getrectarg(args, a)) + return NULL; + wshow(wp->w_win, a[0], a[1], a[2], a[3]); + INCREF(None); + return None; } static object * window_settimer(wp, args) - windowobject *wp; - object *args; + windowobject *wp; + object *args; { - int a; - if (!getintarg(args, &a)) - return NULL; - wsettimer(wp->w_win, a); - INCREF(None); - return None; + int a; + if (!getintarg(args, &a)) + return NULL; + wsettimer(wp->w_win, a); + INCREF(None); + return None; } static object * window_menucreate(self, args) - windowobject *self; - object *args; + windowobject *self; + object *args; { - menuobject *mp; - object *title; - if (!getstrarg(args, &title)) - return NULL; - wmenusetdeflocal(1); - mp = newmenuobject(title); - if (mp == NULL) - return NULL; - wmenuattach(self->w_win, mp->m_menu); - return (object *)mp; + menuobject *mp; + object *title; + if (!getstrarg(args, &title)) + return NULL; + wmenusetdeflocal(1); + mp = newmenuobject(title); + if (mp == NULL) + return NULL; + wmenuattach(self->w_win, mp->m_menu); + return (object *)mp; } static object * window_textcreate(self, args) - windowobject *self; - object *args; + windowobject *self; + object *args; { - textobject *tp; - int a[4]; - if (!getrectarg(args, a)) - return NULL; - return (object *) - newtextobject(self, a[0], a[1], a[2], a[3]); + textobject *tp; + int a[4]; + if (!getrectarg(args, a)) + return NULL; + return (object *) + newtextobject(self, a[0], a[1], a[2], a[3]); } static object * window_setselection(self, args) - windowobject *self; - object *args; + windowobject *self; + object *args; { - int sel; - object *str; - int ok; - if (!getintstrarg(args, &sel, &str)) - return NULL; - ok = wsetselection(self->w_win, sel, - getstringvalue(str), (int)getstringsize(str)); - return newintobject(ok); + int sel; + object *str; + int ok; + if (!getintstrarg(args, &sel, &str)) + return NULL; + ok = wsetselection(self->w_win, sel, + getstringvalue(str), (int)getstringsize(str)); + return newintobject(ok); } static object * window_setwincursor(self, args) - windowobject *self; - object *args; -{ - object *str; - CURSOR *c; - if (!getstrarg(args, &str)) - return NULL; - c = wfetchcursor(getstringvalue(str)); - if (c == NULL) { - err_setstr(RuntimeError, "no such cursor"); - return NULL; - } - wsetwincursor(self->w_win, c); - INCREF(None); - return None; + windowobject *self; + object *args; +{ + object *str; + CURSOR *c; + if (!getstrarg(args, &str)) + return NULL; + c = wfetchcursor(getstringvalue(str)); + if (c == NULL) { + err_setstr(RuntimeError, "no such cursor"); + return NULL; + } + wsetwincursor(self->w_win, c); + INCREF(None); + return None; } static struct methodlist window_methods[] = { - {"begindrawing",window_begindrawing}, - {"change", window_change}, - {"getdocsize", window_getdocsize}, - {"getorigin", window_getorigin}, - {"gettitle", window_gettitle}, - {"getwinsize", window_getwinsize}, - {"menucreate", window_menucreate}, - {"scroll", window_scroll}, - {"setwincursor",window_setwincursor}, - {"setdocsize", window_setdocsize}, - {"setorigin", window_setorigin}, - {"setselection",window_setselection}, - {"settimer", window_settimer}, - {"settitle", window_settitle}, - {"show", window_show}, - {"textcreate", window_textcreate}, - {NULL, NULL} /* sentinel */ + {"begindrawing",window_begindrawing}, + {"change", window_change}, + {"getdocsize", window_getdocsize}, + {"getorigin", window_getorigin}, + {"gettitle", window_gettitle}, + {"getwinsize", window_getwinsize}, + {"menucreate", window_menucreate}, + {"scroll", window_scroll}, + {"setwincursor",window_setwincursor}, + {"setdocsize", window_setdocsize}, + {"setorigin", window_setorigin}, + {"setselection",window_setselection}, + {"settimer", window_settimer}, + {"settitle", window_settitle}, + {"show", window_show}, + {"textcreate", window_textcreate}, + {NULL, NULL} /* sentinel */ }; static object * window_getattr(wp, name) - windowobject *wp; - char *name; + windowobject *wp; + char *name; { - if (wp->w_attr != NULL) { - object *v = dictlookup(wp->w_attr, name); - if (v != NULL) { - INCREF(v); - return v; - } - } - return findmethod(window_methods, (object *)wp, name); + if (wp->w_attr != NULL) { + object *v = dictlookup(wp->w_attr, name); + if (v != NULL) { + INCREF(v); + return v; + } + } + return findmethod(window_methods, (object *)wp, name); } static int window_setattr(wp, name, v) - windowobject *wp; - char *name; - object *v; + windowobject *wp; + char *name; + object *v; { - if (wp->w_attr == NULL) { - wp->w_attr = newdictobject(); - if (wp->w_attr == NULL) - return -1; - } - if (v == NULL) - return dictremove(wp->w_attr, name); - else - return dictinsert(wp->w_attr, name, v); + if (wp->w_attr == NULL) { + wp->w_attr = newdictobject(); + if (wp->w_attr == NULL) + return -1; + } + if (v == NULL) + return dictremove(wp->w_attr, name); + else + return dictinsert(wp->w_attr, name, v); } static typeobject Windowtype = { - OB_HEAD_INIT(&Typetype) - 0, /*ob_size*/ - "window", /*tp_name*/ - sizeof(windowobject), /*tp_size*/ - 0, /*tp_itemsize*/ - /* methods */ - window_dealloc, /*tp_dealloc*/ - window_print, /*tp_print*/ - window_getattr, /*tp_getattr*/ - window_setattr, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ + OB_HEAD_INIT(&Typetype) + 0, /*ob_size*/ + "window", /*tp_name*/ + sizeof(windowobject), /*tp_size*/ + 0, /*tp_itemsize*/ + /* methods */ + window_dealloc, /*tp_dealloc*/ + window_print, /*tp_print*/ + window_getattr, /*tp_getattr*/ + window_setattr, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ }; /* Stdwin methods */ static object * stdwin_open(sw, args) - object *sw; - object *args; -{ - int tag; - object *title; - windowobject *wp; - if (!getstrarg(args, &title)) - return NULL; - for (tag = 0; tag < MAXNWIN; tag++) { - if (windowlist[tag] == NULL) - break; - } - if (tag >= MAXNWIN) - return err_nomem(); - wp = NEWOBJ(windowobject, &Windowtype); - if (wp == NULL) - return NULL; - INCREF(title); - wp->w_title = title; - wp->w_win = wopen(getstringvalue(title), (void (*)()) NULL); - wp->w_attr = NULL; - if (wp->w_win == NULL) { - DECREF(wp); - return NULL; - } - windowlist[tag] = wp; - wsettag(wp->w_win, tag); - return (object *)wp; + object *sw; + object *args; +{ + int tag; + object *title; + windowobject *wp; + if (!getstrarg(args, &title)) + return NULL; + for (tag = 0; tag < MAXNWIN; tag++) { + if (windowlist[tag] == NULL) + break; + } + if (tag >= MAXNWIN) + return err_nomem(); + wp = NEWOBJ(windowobject, &Windowtype); + if (wp == NULL) + return NULL; + INCREF(title); + wp->w_title = title; + wp->w_win = wopen(getstringvalue(title), (void (*)()) NULL); + wp->w_attr = NULL; + if (wp->w_win == NULL) { + DECREF(wp); + return NULL; + } + windowlist[tag] = wp; + wsettag(wp->w_win, tag); + return (object *)wp; } static object * stdwin_get_poll_event(poll, args) - int poll; - object *args; -{ - EVENT e; - object *v, *w; - if (!getnoarg(args)) - return NULL; - if (Drawing != NULL) { - err_setstr(RuntimeError, "cannot getevent() while drawing"); - return NULL; - } + int poll; + object *args; +{ + EVENT e; + object *v, *w; + if (!getnoarg(args)) + return NULL; + if (Drawing != NULL) { + err_setstr(RuntimeError, "cannot getevent() while drawing"); + return NULL; + } /* again: */ - if (poll) { - if (!wpollevent(&e)) { - INCREF(None); - return None; - } - } - else - wgetevent(&e); - if (e.type == WE_COMMAND && e.u.command == WC_CANCEL) { - /* Turn keyboard interrupts into exceptions */ - err_set(KeyboardInterrupt); - return NULL; - } + if (poll) { + if (!wpollevent(&e)) { + INCREF(None); + return None; + } + } + else + wgetevent(&e); + if (e.type == WE_COMMAND && e.u.command == WC_CANCEL) { + /* Turn keyboard interrupts into exceptions */ + err_set(KeyboardInterrupt); + return NULL; + } /* - if (e.window == NULL && (e.type == WE_COMMAND || e.type == WE_CHAR)) - goto again; + if (e.window == NULL && (e.type == WE_COMMAND || e.type == WE_CHAR)) + goto again; */ - if (e.type == WE_COMMAND && e.u.command == WC_CLOSE) { - /* Turn WC_CLOSE commands into WE_CLOSE events */ - e.type = WE_CLOSE; - } - v = newtupleobject(3); - if (v == NULL) - return NULL; - if ((w = newintobject((long)e.type)) == NULL) { - DECREF(v); - return NULL; - } - settupleitem(v, 0, w); - if (e.window == NULL) - w = None; - else { - int tag = wgettag(e.window); - if (tag < 0 || tag >= MAXNWIN || windowlist[tag] == NULL) - w = None; - else - w = (object *)windowlist[tag]; + if (e.type == WE_COMMAND && e.u.command == WC_CLOSE) { + /* Turn WC_CLOSE commands into WE_CLOSE events */ + e.type = WE_CLOSE; + } + v = newtupleobject(3); + if (v == NULL) + return NULL; + if ((w = newintobject((long)e.type)) == NULL) { + DECREF(v); + return NULL; + } + settupleitem(v, 0, w); + if (e.window == NULL) + w = None; + else { + int tag = wgettag(e.window); + if (tag < 0 || tag >= MAXNWIN || windowlist[tag] == NULL) + w = None; + else + w = (object *)windowlist[tag]; #ifdef sgi - /* XXX Trap for unexplained weird bug */ - if ((long)w == (long)0x80000001) { - err_setstr(SystemError, - "bad pointer in stdwin.getevent()"); - return NULL; - } + /* XXX Trap for unexplained weird bug */ + if ((long)w == (long)0x80000001) { + err_setstr(SystemError, + "bad pointer in stdwin.getevent()"); + return NULL; + } #endif - } - INCREF(w); - settupleitem(v, 1, w); - switch (e.type) { - case WE_CHAR: - { - char c[1]; - c[0] = e.u.character; - w = newsizedstringobject(c, 1); - } - break; - case WE_COMMAND: - w = newintobject((long)e.u.command); - break; - case WE_DRAW: - w = makerect(e.u.area.left, e.u.area.top, - e.u.area.right, e.u.area.bottom); - break; - case WE_MOUSE_DOWN: - case WE_MOUSE_MOVE: - case WE_MOUSE_UP: - w = makemouse(e.u.where.h, e.u.where.v, - e.u.where.clicks, - e.u.where.button, - e.u.where.mask); - break; - case WE_MENU: - if (e.u.m.id >= IDOFFSET && e.u.m.id < IDOFFSET+MAXNMENU && - menulist[e.u.m.id - IDOFFSET] != NULL) - w = (object *)menulist[e.u.m.id - IDOFFSET]; - else - w = None; - w = makemenu(w, e.u.m.item); - break; - case WE_LOST_SEL: - w = newintobject((long)e.u.sel); - break; - default: - w = None; - INCREF(w); - break; - } - if (w == NULL) { - DECREF(v); - return NULL; - } - settupleitem(v, 2, w); - return v; + } + INCREF(w); + settupleitem(v, 1, w); + switch (e.type) { + case WE_CHAR: + { + char c[1]; + c[0] = e.u.character; + w = newsizedstringobject(c, 1); + } + break; + case WE_COMMAND: + w = newintobject((long)e.u.command); + break; + case WE_DRAW: + w = makerect(e.u.area.left, e.u.area.top, + e.u.area.right, e.u.area.bottom); + break; + case WE_MOUSE_DOWN: + case WE_MOUSE_MOVE: + case WE_MOUSE_UP: + w = makemouse(e.u.where.h, e.u.where.v, + e.u.where.clicks, + e.u.where.button, + e.u.where.mask); + break; + case WE_MENU: + if (e.u.m.id >= IDOFFSET && e.u.m.id < IDOFFSET+MAXNMENU && + menulist[e.u.m.id - IDOFFSET] != NULL) + w = (object *)menulist[e.u.m.id - IDOFFSET]; + else + w = None; + w = makemenu(w, e.u.m.item); + break; + case WE_LOST_SEL: + w = newintobject((long)e.u.sel); + break; + default: + w = None; + INCREF(w); + break; + } + if (w == NULL) { + DECREF(v); + return NULL; + } + settupleitem(v, 2, w); + return v; } static object * stdwin_getevent(sw, args) - object *sw; - object *args; + object *sw; + object *args; { - return stdwin_get_poll_event(0, args); + return stdwin_get_poll_event(0, args); } static object * stdwin_pollevent(sw, args) - object *sw; - object *args; + object *sw; + object *args; { - return stdwin_get_poll_event(1, args); + return stdwin_get_poll_event(1, args); } static object * stdwin_setdefwinpos(sw, args) - object *sw; - object *args; + object *sw; + object *args; { - int a[2]; - if (!getpointarg(args, a)) - return NULL; - wsetdefwinpos(a[0], a[1]); - INCREF(None); - return None; + int a[2]; + if (!getpointarg(args, a)) + return NULL; + wsetdefwinpos(a[0], a[1]); + INCREF(None); + return None; } static object * stdwin_setdefwinsize(sw, args) - object *sw; - object *args; + object *sw; + object *args; { - int a[2]; - if (!getpointarg(args, a)) - return NULL; - wsetdefwinsize(a[0], a[1]); - INCREF(None); - return None; + int a[2]; + if (!getpointarg(args, a)) + return NULL; + wsetdefwinsize(a[0], a[1]); + INCREF(None); + return None; } static object * stdwin_getdefwinpos(wp, args) - windowobject *wp; - object *args; + windowobject *wp; + object *args; { - int h, v; - if (!getnoarg(args)) - return NULL; - wgetdefwinpos(&h, &v); - return makepoint(h, v); + int h, v; + if (!getnoarg(args)) + return NULL; + wgetdefwinpos(&h, &v); + return makepoint(h, v); } static object * stdwin_getdefwinsize(wp, args) - windowobject *wp; - object *args; + windowobject *wp; + object *args; { - int width, height; - if (!getnoarg(args)) - return NULL; - wgetdefwinsize(&width, &height); - return makepoint(width, height); + int width, height; + if (!getnoarg(args)) + return NULL; + wgetdefwinsize(&width, &height); + return makepoint(width, height); } static object * stdwin_menucreate(self, args) - object *self; - object *args; + object *self; + object *args; { - object *title; - if (!getstrarg(args, &title)) - return NULL; - wmenusetdeflocal(0); - return (object *)newmenuobject(title); + object *title; + if (!getstrarg(args, &title)) + return NULL; + wmenusetdeflocal(0); + return (object *)newmenuobject(title); } static object * stdwin_askfile(self, args) - object *self; - object *args; + object *self; + object *args; { - object *prompt, *dflt; - int new, ret; - char buf[256]; - if (!getstrstrintarg(args, &prompt, &dflt, &new)) - return NULL; - strncpy(buf, getstringvalue(dflt), sizeof buf); - buf[sizeof buf - 1] = '\0'; - ret = waskfile(getstringvalue(prompt), buf, sizeof buf, new); - if (!ret) { - err_set(KeyboardInterrupt); - return NULL; - } - return newstringobject(buf); + object *prompt, *dflt; + int new, ret; + char buf[256]; + if (!getstrstrintarg(args, &prompt, &dflt, &new)) + return NULL; + strncpy(buf, getstringvalue(dflt), sizeof buf); + buf[sizeof buf - 1] = '\0'; + ret = waskfile(getstringvalue(prompt), buf, sizeof buf, new); + if (!ret) { + err_set(KeyboardInterrupt); + return NULL; + } + return newstringobject(buf); } static object * stdwin_askync(self, args) - object *self; - object *args; + object *self; + object *args; { - object *prompt; - int new, ret; - if (!getstrintarg(args, &prompt, &new)) - return NULL; - ret = waskync(getstringvalue(prompt), new); - if (ret < 0) { - err_set(KeyboardInterrupt); - return NULL; - } - return newintobject((long)ret); + object *prompt; + int new, ret; + if (!getstrintarg(args, &prompt, &new)) + return NULL; + ret = waskync(getstringvalue(prompt), new); + if (ret < 0) { + err_set(KeyboardInterrupt); + return NULL; + } + return newintobject((long)ret); } static object * stdwin_askstr(self, args) - object *self; - object *args; + object *self; + object *args; { - object *prompt, *dflt; - int ret; - char buf[256]; - if (!getstrstrarg(args, &prompt, &dflt)) - return NULL; - strncpy(buf, getstringvalue(dflt), sizeof buf); - buf[sizeof buf - 1] = '\0'; - ret = waskstr(getstringvalue(prompt), buf, sizeof buf); - if (!ret) { - err_set(KeyboardInterrupt); - return NULL; - } - return newstringobject(buf); + object *prompt, *dflt; + int ret; + char buf[256]; + if (!getstrstrarg(args, &prompt, &dflt)) + return NULL; + strncpy(buf, getstringvalue(dflt), sizeof buf); + buf[sizeof buf - 1] = '\0'; + ret = waskstr(getstringvalue(prompt), buf, sizeof buf); + if (!ret) { + err_set(KeyboardInterrupt); + return NULL; + } + return newstringobject(buf); } static object * stdwin_message(self, args) - object *self; - object *args; + object *self; + object *args; { - object *msg; - if (!getstrarg(args, &msg)) - return NULL; - wmessage(getstringvalue(msg)); - INCREF(None); - return None; + object *msg; + if (!getstrarg(args, &msg)) + return NULL; + wmessage(getstringvalue(msg)); + INCREF(None); + return None; } static object * stdwin_fleep(self, args) - object *self; - object *args; + object *self; + object *args; { - if (!getnoarg(args)) - return NULL; - wfleep(); - INCREF(None); - return None; + if (!getnoarg(args)) + return NULL; + wfleep(); + INCREF(None); + return None; } static object * stdwin_setcutbuffer(self, args) - object *self; - object *args; + object *self; + object *args; { - int i; - object *str; - if (!getintstrarg(args, &i, &str)) - return NULL; - wsetcutbuffer(i, getstringvalue(str), getstringsize(str)); - INCREF(None); - return None; + int i; + object *str; + if (!getintstrarg(args, &i, &str)) + return NULL; + wsetcutbuffer(i, getstringvalue(str), getstringsize(str)); + INCREF(None); + return None; } static object * stdwin_getcutbuffer(self, args) - object *self; - object *args; + object *self; + object *args; { - int i; - char *str; - int len; - if (!getintarg(args, &i)) - return NULL; - str = wgetcutbuffer(i, &len); - if (str == NULL) { - str = ""; - len = 0; - } - return newsizedstringobject(str, len); + int i; + char *str; + int len; + if (!getintarg(args, &i)) + return NULL; + str = wgetcutbuffer(i, &len); + if (str == NULL) { + str = ""; + len = 0; + } + return newsizedstringobject(str, len); } static object * stdwin_rotatecutbuffers(self, args) - object *self; - object *args; + object *self; + object *args; { - int i; - if (!getintarg(args, &i)) - return NULL; - wrotatecutbuffers(i); - INCREF(None); - return None; + int i; + if (!getintarg(args, &i)) + return NULL; + wrotatecutbuffers(i); + INCREF(None); + return None; } static object * stdwin_getselection(self, args) - object *self; - object *args; + object *self; + object *args; { - int sel; - char *data; - int len; - if (!getintarg(args, &sel)) - return NULL; - data = wgetselection(sel, &len); - if (data == NULL) { - data = ""; - len = 0; - } - return newsizedstringobject(data, len); + int sel; + char *data; + int len; + if (!getintarg(args, &sel)) + return NULL; + data = wgetselection(sel, &len); + if (data == NULL) { + data = ""; + len = 0; + } + return newsizedstringobject(data, len); } static object * stdwin_resetselection(self, args) - object *self; - object *args; + object *self; + object *args; { - int sel; - if (!getintarg(args, &sel)) - return NULL; - wresetselection(sel); - INCREF(None); - return None; + int sel; + if (!getintarg(args, &sel)) + return NULL; + wresetselection(sel); + INCREF(None); + return None; } static struct methodlist stdwin_methods[] = { - {"askfile", stdwin_askfile}, - {"askstr", stdwin_askstr}, - {"askync", stdwin_askync}, - {"fleep", stdwin_fleep}, - {"getselection", stdwin_getselection}, - {"getcutbuffer", stdwin_getcutbuffer}, - {"getdefwinpos", stdwin_getdefwinpos}, - {"getdefwinsize", stdwin_getdefwinsize}, - {"getevent", stdwin_getevent}, - {"menucreate", stdwin_menucreate}, - {"message", stdwin_message}, - {"open", stdwin_open}, - {"pollevent", stdwin_pollevent}, - {"resetselection", stdwin_resetselection}, - {"rotatecutbuffers", stdwin_rotatecutbuffers}, - {"setcutbuffer", stdwin_setcutbuffer}, - {"setdefwinpos", stdwin_setdefwinpos}, - {"setdefwinsize", stdwin_setdefwinsize}, - - /* Text measuring methods borrow code from drawing objects: */ - {"baseline", drawing_baseline}, - {"lineheight", drawing_lineheight}, - {"textbreak", drawing_textbreak}, - {"textwidth", drawing_textwidth}, - {NULL, NULL} /* sentinel */ + {"askfile", stdwin_askfile}, + {"askstr", stdwin_askstr}, + {"askync", stdwin_askync}, + {"fleep", stdwin_fleep}, + {"getselection", stdwin_getselection}, + {"getcutbuffer", stdwin_getcutbuffer}, + {"getdefwinpos", stdwin_getdefwinpos}, + {"getdefwinsize", stdwin_getdefwinsize}, + {"getevent", stdwin_getevent}, + {"menucreate", stdwin_menucreate}, + {"message", stdwin_message}, + {"open", stdwin_open}, + {"pollevent", stdwin_pollevent}, + {"resetselection", stdwin_resetselection}, + {"rotatecutbuffers", stdwin_rotatecutbuffers}, + {"setcutbuffer", stdwin_setcutbuffer}, + {"setdefwinpos", stdwin_setdefwinpos}, + {"setdefwinsize", stdwin_setdefwinsize}, + + /* Text measuring methods borrow code from drawing objects: */ + {"baseline", drawing_baseline}, + {"lineheight", drawing_lineheight}, + {"textbreak", drawing_textbreak}, + {"textwidth", drawing_textwidth}, + {NULL, NULL} /* sentinel */ }; void initstdwin() { - static int inited; - if (!inited) { - winit(); - inited = 1; - } - initmodule("stdwin", stdwin_methods); + static int inited; + if (!inited) { + winit(); + inited = 1; + } + initmodule("stdwin", stdwin_methods); } diff --git a/src/stdwinobject.h b/src/stdwinobject.h index a6d20b8..6b59593 100644 --- a/src/stdwinobject.h +++ b/src/stdwinobject.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. diff --git a/src/strdup.c b/src/strdup.c index e39796d..ac3907e 100644 --- a/src/strdup.c +++ b/src/strdup.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -28,12 +28,12 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. char * strdup(str) - const char *str; + const char *str; { - if (str != NULL) { - register char *copy = NEW(char, strlen(str) + 1); - if (copy != NULL) - return strcpy(copy, str); - } - return NULL; + if (str != NULL) { + register char *copy = NEW(char, strlen(str) + 1); + if (copy != NULL) + return strcpy(copy, str); + } + return NULL; } diff --git a/src/strerror.c b/src/strerror.c index b2d9da9..202725f 100644 --- a/src/strerror.c +++ b/src/strerror.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -23,7 +23,7 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ /* PD implementation of strerror() for systems that don't have it. - Author: Guido van Rossum, CWI Amsterdam, Oct. 1990, <[email protected]>. */ + Author: Guido van Rossum, CWI Amsterdam, Oct. 1990, <[email protected]>. */ #include <stdio.h> @@ -32,13 +32,13 @@ extern char *sys_errlist[]; char * strerror(err) - int err; + int err; { - static char buf[20]; - if (err >= 0 && err < sys_nerr) - return sys_errlist[err]; - sprintf(buf, "Unknown errno %d", err); - return buf; + static char buf[20]; + if (err >= 0 && err < sys_nerr) + return sys_errlist[err]; + sprintf(buf, "Unknown errno %d", err); + return buf; } #ifdef THINK_C diff --git a/src/stringobject.c b/src/stringobject.c index d27243f..cb04d94 100644 --- a/src/stringobject.c +++ b/src/stringobject.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -28,320 +28,320 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. object * newsizedstringobject(str, size) - char *str; - int size; + char *str; + int size; { - register stringobject *op = (stringobject *) - malloc(sizeof(stringobject) + size * sizeof(char)); - if (op == NULL) - return err_nomem(); - NEWREF(op); - op->ob_type = &Stringtype; - op->ob_size = size; - if (str != NULL) - memcpy(op->ob_sval, str, size); - op->ob_sval[size] = '\0'; - return (object *) op; + register stringobject *op = (stringobject *) + malloc(sizeof(stringobject) + size * sizeof(char)); + if (op == NULL) + return err_nomem(); + NEWREF(op); + op->ob_type = &Stringtype; + op->ob_size = size; + if (str != NULL) + memcpy(op->ob_sval, str, size); + op->ob_sval[size] = '\0'; + return (object *) op; } object * newstringobject(str) - char *str; + char *str; { - register unsigned int size = strlen(str); - register stringobject *op = (stringobject *) - malloc(sizeof(stringobject) + size * sizeof(char)); - if (op == NULL) - return err_nomem(); - NEWREF(op); - op->ob_type = &Stringtype; - op->ob_size = size; - strcpy(op->ob_sval, str); - return (object *) op; + register unsigned int size = strlen(str); + register stringobject *op = (stringobject *) + malloc(sizeof(stringobject) + size * sizeof(char)); + if (op == NULL) + return err_nomem(); + NEWREF(op); + op->ob_type = &Stringtype; + op->ob_size = size; + strcpy(op->ob_sval, str); + return (object *) op; } unsigned int getstringsize(op) - register object *op; + register object *op; { - if (!is_stringobject(op)) { - err_badcall(); - return -1; - } - return ((stringobject *)op) -> ob_size; + if (!is_stringobject(op)) { + err_badcall(); + return -1; + } + return ((stringobject *)op) -> ob_size; } /*const*/ char * getstringvalue(op) - register object *op; + register object *op; { - if (!is_stringobject(op)) { - err_badcall(); - return NULL; - } - return ((stringobject *)op) -> ob_sval; + if (!is_stringobject(op)) { + err_badcall(); + return NULL; + } + return ((stringobject *)op) -> ob_sval; } /* Methods */ static void stringprint(op, fp, flags) - stringobject *op; - FILE *fp; - int flags; + stringobject *op; + FILE *fp; + int flags; { - int i; - char c; - if (flags & PRINT_RAW) { - fwrite(op->ob_sval, 1, (int) op->ob_size, fp); - return; - } - fprintf(fp, "'"); - for (i = 0; i < op->ob_size; i++) { - c = op->ob_sval[i]; - if (c == '\'' || c == '\\') - fprintf(fp, "\\%c", c); - else if (c < ' ' || c >= 0177) - fprintf(fp, "\\%03o", c&0377); - else - putc(c, fp); - } - fprintf(fp, "'"); + int i; + char c; + if (flags & PRINT_RAW) { + fwrite(op->ob_sval, 1, (int) op->ob_size, fp); + return; + } + fprintf(fp, "'"); + for (i = 0; i < op->ob_size; i++) { + c = op->ob_sval[i]; + if (c == '\'' || c == '\\') + fprintf(fp, "\\%c", c); + else if (c < ' ' || c >= 0177) + fprintf(fp, "\\%03o", c&0377); + else + putc(c, fp); + } + fprintf(fp, "'"); } static object * stringrepr(op) - register stringobject *op; + register stringobject *op; { - /* XXX overflow? */ - int newsize = 2 + 4 * op->ob_size * sizeof(char); - object *v = newsizedstringobject((char *)NULL, newsize); - if (v == NULL) { - return err_nomem(); - } - else { - register int i; - register char c; - register char *p; - NEWREF(v); - v->ob_type = &Stringtype; - ((stringobject *)v)->ob_size = newsize; - p = ((stringobject *)v)->ob_sval; - *p++ = '\''; - for (i = 0; i < op->ob_size; i++) { - c = op->ob_sval[i]; - if (c == '\'' || c == '\\') - *p++ = '\\', *p++ = c; - else if (c < ' ' || c >= 0177) { - sprintf(p, "\\%03o", c&0377); - while (*p != '\0') - p++; - - } - else - *p++ = c; - } - *p++ = '\''; - *p = '\0'; - resizestring(&v, (int) (p - ((stringobject *)v)->ob_sval)); - return v; - } + /* XXX overflow? */ + int newsize = 2 + 4 * op->ob_size * sizeof(char); + object *v = newsizedstringobject((char *)NULL, newsize); + if (v == NULL) { + return err_nomem(); + } + else { + register int i; + register char c; + register char *p; + NEWREF(v); + v->ob_type = &Stringtype; + ((stringobject *)v)->ob_size = newsize; + p = ((stringobject *)v)->ob_sval; + *p++ = '\''; + for (i = 0; i < op->ob_size; i++) { + c = op->ob_sval[i]; + if (c == '\'' || c == '\\') + *p++ = '\\', *p++ = c; + else if (c < ' ' || c >= 0177) { + sprintf(p, "\\%03o", c&0377); + while (*p != '\0') + p++; + + } + else + *p++ = c; + } + *p++ = '\''; + *p = '\0'; + resizestring(&v, (int) (p - ((stringobject *)v)->ob_sval)); + return v; + } } static int stringlength(a) - stringobject *a; + stringobject *a; { - return a->ob_size; + return a->ob_size; } static object * stringconcat(a, bb) - register stringobject *a; - register object *bb; + register stringobject *a; + register object *bb; { - register unsigned int size; - register stringobject *op; - if (!is_stringobject(bb)) { - err_badarg(); - return NULL; - } + register unsigned int size; + register stringobject *op; + if (!is_stringobject(bb)) { + err_badarg(); + return NULL; + } #define b ((stringobject *)bb) - /* Optimize cases with empty left or right operand */ - if (a->ob_size == 0) { - INCREF(bb); - return bb; - } - if (b->ob_size == 0) { - INCREF(a); - return (object *)a; - } - size = a->ob_size + b->ob_size; - op = (stringobject *) - malloc(sizeof(stringobject) + size * sizeof(char)); - if (op == NULL) - return err_nomem(); - NEWREF(op); - op->ob_type = &Stringtype; - op->ob_size = size; - memcpy(op->ob_sval, a->ob_sval, (int) a->ob_size); - memcpy(op->ob_sval + a->ob_size, b->ob_sval, (int) b->ob_size); - op->ob_sval[size] = '\0'; - return (object *) op; + /* Optimize cases with empty left or right operand */ + if (a->ob_size == 0) { + INCREF(bb); + return bb; + } + if (b->ob_size == 0) { + INCREF(a); + return (object *)a; + } + size = a->ob_size + b->ob_size; + op = (stringobject *) + malloc(sizeof(stringobject) + size * sizeof(char)); + if (op == NULL) + return err_nomem(); + NEWREF(op); + op->ob_type = &Stringtype; + op->ob_size = size; + memcpy(op->ob_sval, a->ob_sval, (int) a->ob_size); + memcpy(op->ob_sval + a->ob_size, b->ob_sval, (int) b->ob_size); + op->ob_sval[size] = '\0'; + return (object *) op; #undef b } static object * stringrepeat(a, n) - register stringobject *a; - register int n; + register stringobject *a; + register int n; { - register int i; - register unsigned int size; - register stringobject *op; - if (n < 0) - n = 0; - size = a->ob_size * n; - if (size == a->ob_size) { - INCREF(a); - return (object *)a; - } - op = (stringobject *) - malloc(sizeof(stringobject) + size * sizeof(char)); - if (op == NULL) - return err_nomem(); - NEWREF(op); - op->ob_type = &Stringtype; - op->ob_size = size; - for (i = 0; i < size; i += a->ob_size) - memcpy(op->ob_sval+i, a->ob_sval, (int) a->ob_size); - op->ob_sval[size] = '\0'; - return (object *) op; + register int i; + register unsigned int size; + register stringobject *op; + if (n < 0) + n = 0; + size = a->ob_size * n; + if (size == a->ob_size) { + INCREF(a); + return (object *)a; + } + op = (stringobject *) + malloc(sizeof(stringobject) + size * sizeof(char)); + if (op == NULL) + return err_nomem(); + NEWREF(op); + op->ob_type = &Stringtype; + op->ob_size = size; + for (i = 0; i < size; i += a->ob_size) + memcpy(op->ob_sval+i, a->ob_sval, (int) a->ob_size); + op->ob_sval[size] = '\0'; + return (object *) op; } /* String slice a[i:j] consists of characters a[i] ... a[j-1] */ static object * stringslice(a, i, j) - register stringobject *a; - register int i, j; /* May be negative! */ + register stringobject *a; + register int i, j; /* May be negative! */ { - if (i < 0) - i = 0; - if (j < 0) - j = 0; /* Avoid signed/unsigned bug in next line */ - if (j > a->ob_size) - j = a->ob_size; - if (i == 0 && j == a->ob_size) { /* It's the same as a */ - INCREF(a); - return (object *)a; - } - if (j < i) - j = i; - return newsizedstringobject(a->ob_sval + i, (int) (j-i)); + if (i < 0) + i = 0; + if (j < 0) + j = 0; /* Avoid signed/unsigned bug in next line */ + if (j > a->ob_size) + j = a->ob_size; + if (i == 0 && j == a->ob_size) { /* It's the same as a */ + INCREF(a); + return (object *)a; + } + if (j < i) + j = i; + return newsizedstringobject(a->ob_sval + i, (int) (j-i)); } static object * stringitem(a, i) - stringobject *a; - register int i; + stringobject *a; + register int i; { - if (i < 0 || i >= a->ob_size) { - err_setstr(IndexError, "string index out of range"); - return NULL; - } - return stringslice(a, i, i+1); + if (i < 0 || i >= a->ob_size) { + err_setstr(IndexError, "string index out of range"); + return NULL; + } + return stringslice(a, i, i+1); } static int stringcompare(a, b) - stringobject *a, *b; + stringobject *a, *b; { - int len_a = a->ob_size, len_b = b->ob_size; - int min_len = (len_a < len_b) ? len_a : len_b; - int cmp = memcmp(a->ob_sval, b->ob_sval, min_len); - if (cmp != 0) - return cmp; - return (len_a < len_b) ? -1 : (len_a > len_b) ? 1 : 0; + int len_a = a->ob_size, len_b = b->ob_size; + int min_len = (len_a < len_b) ? len_a : len_b; + int cmp = memcmp(a->ob_sval, b->ob_sval, min_len); + if (cmp != 0) + return cmp; + return (len_a < len_b) ? -1 : (len_a > len_b) ? 1 : 0; } static sequence_methods string_as_sequence = { - stringlength, /*tp_length*/ - stringconcat, /*tp_concat*/ - stringrepeat, /*tp_repeat*/ - stringitem, /*tp_item*/ - stringslice, /*tp_slice*/ - 0, /*tp_ass_item*/ - 0, /*tp_ass_slice*/ + stringlength, /*tp_length*/ + stringconcat, /*tp_concat*/ + stringrepeat, /*tp_repeat*/ + stringitem, /*tp_item*/ + stringslice, /*tp_slice*/ + 0, /*tp_ass_item*/ + 0, /*tp_ass_slice*/ }; typeobject Stringtype = { - OB_HEAD_INIT(&Typetype) - 0, - "string", - sizeof(stringobject), - sizeof(char), - free, /*tp_dealloc*/ - stringprint, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - stringcompare, /*tp_compare*/ - stringrepr, /*tp_repr*/ - 0, /*tp_as_number*/ - &string_as_sequence, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ + OB_HEAD_INIT(&Typetype) + 0, + "string", + sizeof(stringobject), + sizeof(char), + free, /*tp_dealloc*/ + stringprint, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + stringcompare, /*tp_compare*/ + stringrepr, /*tp_repr*/ + 0, /*tp_as_number*/ + &string_as_sequence, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ }; void joinstring(pv, w) - register object **pv; - register object *w; + register object **pv; + register object *w; { - register object *v; - if (*pv == NULL || w == NULL || !is_stringobject(*pv)) - return; - v = stringconcat((stringobject *) *pv, w); - DECREF(*pv); - *pv = v; + register object *v; + if (*pv == NULL || w == NULL || !is_stringobject(*pv)) + return; + v = stringconcat((stringobject *) *pv, w); + DECREF(*pv); + *pv = v; } /* The following function breaks the notion that strings are immutable: - it changes the size of a string. We get away with this only if there - is only one module referencing the object. You can also think of it - as creating a new string object and destroying the old one, only - more efficiently. In any case, don't use this if the string may - already be known to some other part of the code... */ + it changes the size of a string. We get away with this only if there + is only one module referencing the object. You can also think of it + as creating a new string object and destroying the old one, only + more efficiently. In any case, don't use this if the string may + already be known to some other part of the code... */ int resizestring(pv, newsize) - object **pv; - int newsize; + object **pv; + int newsize; { - register object *v; - register stringobject *sv; - v = *pv; - if (!is_stringobject(v) || v->ob_refcnt != 1) { - *pv = 0; - DECREF(v); - err_badcall(); - return -1; - } - /* XXX UNREF/NEWREF interface should be more symmetrical */ + register object *v; + register stringobject *sv; + v = *pv; + if (!is_stringobject(v) || v->ob_refcnt != 1) { + *pv = 0; + DECREF(v); + err_badcall(); + return -1; + } + /* XXX UNREF/NEWREF interface should be more symmetrical */ #ifdef REF_DEBUG - --ref_total; + --ref_total; #endif - UNREF(v); - *pv = (object *) - realloc((char *)v, - sizeof(stringobject) + newsize * sizeof(char)); - if (*pv == NULL) { - DEL(v); - err_nomem(); - return -1; - } - NEWREF(*pv); - sv = (stringobject *) *pv; - sv->ob_size = newsize; - sv->ob_sval[newsize] = '\0'; - return 0; + UNREF(v); + *pv = (object *) + realloc((char *)v, + sizeof(stringobject) + newsize * sizeof(char)); + if (*pv == NULL) { + DEL(v); + err_nomem(); + return -1; + } + NEWREF(*pv); + sv = (stringobject *) *pv; + sv->ob_size = newsize; + sv->ob_sval[newsize] = '\0'; + return 0; } diff --git a/src/stringobject.h b/src/stringobject.h index 17e0367..27fb243 100644 --- a/src/stringobject.h +++ b/src/stringobject.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -27,25 +27,25 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* 123456789-123456789-123456789-123456789-123456789-123456789-123456789-12 -Type stringobject represents a character string. An extra zero byte is +Type stringobject represents a character string. An extra zero byte is reserved at the end to ensure it is zero-terminated, but a size is -present so strings with null bytes in them can be represented. This +present so strings with null bytes in them can be represented. This is an immutable object type. There are functions to create new string objects, to test an object for string-ness, and to get the -string value. The latter function returns a null pointer +string value. The latter function returns a null pointer if the object is not of the proper type. There is a variant that takes an explicit size as well as a -variant that assumes a zero-terminated string. Note that none of the +variant that assumes a zero-terminated string. Note that none of the functions should be applied to nil objects. */ /* NB The type is revealed here only because it is used in dictobject.c */ typedef struct { - OB_VARHEAD - char ob_sval[1]; + OB_VARHEAD + char ob_sval[1]; } stringobject; extern typeobject Stringtype; diff --git a/src/strtol.c b/src/strtol.c index cdf9b92..adbb2ba 100644 --- a/src/strtol.c +++ b/src/strtol.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -23,100 +23,100 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ /* -** strtol -** This is a general purpose routine for converting -** an ascii string to an integer in an arbitrary base. -** Leading white space is ignored, if 'base' is zero -** it looks for a leading 0, 0x or 0X to tell which -** base. If these are absent it defaults to 10. -** Base must be between 0 and 36. -** If 'ptr' is non-NULL it will contain a pointer to -** the end of the scan. -** Errors due to bad pointers will probably result in -** exceptions - we don't check for them. +** strtol +** This is a general purpose routine for converting +** an ascii string to an integer in an arbitrary base. +** Leading white space is ignored, if 'base' is zero +** it looks for a leading 0, 0x or 0X to tell which +** base. If these are absent it defaults to 10. +** Base must be between 0 and 36. +** If 'ptr' is non-NULL it will contain a pointer to +** the end of the scan. +** Errors due to bad pointers will probably result in +** exceptions - we don't check for them. */ #include "ctype.h" long strtol(str, ptr, base) -register char * str; -char ** ptr; -int base; +register char * str; +char ** ptr; +int base; { - register long result; /* return value of the function */ - register int c; /* current input character */ - int minus; /* true if a leading minus was found */ + register long result; /* return value of the function */ + register int c; /* current input character */ + int minus; /* true if a leading minus was found */ - result = 0; - minus = 0; + result = 0; + minus = 0; /* catch silly bases */ - if (base < 0 || base > 36) - { - if (ptr) - *ptr = str; - return result; - } + if (base < 0 || base > 36) + { + if (ptr) + *ptr = str; + return result; + } /* skip leading white space */ - while (*str && isspace(*str)) - str++; + while (*str && isspace(*str)) + str++; /* check for optional leading minus sign */ - if (*str == '-') - { - minus = 1; - str++; - } + if (*str == '-') + { + minus = 1; + str++; + } /* check for leading 0 or 0x for auto-base or base 16 */ - switch (base) - { - case 0: /* look for leading 0, 0x or 0X */ - if (*str == '0') - { - str++; - if (*str == 'x' || *str == 'X') - { - str++; - base = 16; - } - else - base = 8; - } - else - base = 10; - break; + switch (base) + { + case 0: /* look for leading 0, 0x or 0X */ + if (*str == '0') + { + str++; + if (*str == 'x' || *str == 'X') + { + str++; + base = 16; + } + else + base = 8; + } + else + base = 10; + break; - case 16: /* skip leading 0x or 0X */ - if (*str == '0' && (*(str+1) == 'x' || *(str+1) == 'X')) - str += 2; - break; - } + case 16: /* skip leading 0x or 0X */ + if (*str == '0' && (*(str+1) == 'x' || *(str+1) == 'X')) + str += 2; + break; + } /* do the conversion */ - while (c = *str) - { - if (isdigit(c) && c - '0' < base) - c -= '0'; - else - { - if (isupper(c)) - c = tolower(c); - if (c >= 'a' && c <= 'z') - c -= 'a' - 10; - else /* non-"digit" character */ - break; - if (c >= base) /* non-"digit" character */ - break; - } - result = result * base + c; - str++; - } + while (c = *str) + { + if (isdigit(c) && c - '0' < base) + c -= '0'; + else + { + if (isupper(c)) + c = tolower(c); + if (c >= 'a' && c <= 'z') + c -= 'a' - 10; + else /* non-"digit" character */ + break; + if (c >= base) /* non-"digit" character */ + break; + } + result = result * base + c; + str++; + } /* set pointer to point to the last character scanned */ - if (ptr) - *ptr = str; - return minus ? -result : result; + if (ptr) + *ptr = str; + return minus ? -result : result; } diff --git a/src/structmember.c b/src/structmember.c index c87a3c7..03b4dcc 100644 --- a/src/structmember.c +++ b/src/structmember.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -30,129 +30,129 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. object * getmember(addr, mlist, name) - char *addr; - struct memberlist *mlist; - char *name; + char *addr; + struct memberlist *mlist; + char *name; { - struct memberlist *l; - - for (l = mlist; l->name != NULL; l++) { - if (strcmp(l->name, name) == 0) { - object *v; - addr += l->offset; - switch (l->type) { - case T_SHORT: - v = newintobject((long) *(short*)addr); - break; - case T_INT: - v = newintobject((long) *(int*)addr); - break; - case T_LONG: - v = newintobject(*(long*)addr); - break; - case T_FLOAT: - v = newfloatobject((double)*(float*)addr); - break; - case T_DOUBLE: - v = newfloatobject(*(double*)addr); - break; - case T_STRING: - if (*(char**)addr == NULL) { - INCREF(None); - v = None; - } - else - v = newstringobject(*(char**)addr); - break; - case T_OBJECT: - v = *(object **)addr; - if (v == NULL) - v = None; - INCREF(v); - break; - default: - err_setstr(SystemError, "bad memberlist type"); - v = NULL; - } - return v; - } - } - - err_setstr(NameError, name); - return NULL; + struct memberlist *l; + + for (l = mlist; l->name != NULL; l++) { + if (strcmp(l->name, name) == 0) { + object *v; + addr += l->offset; + switch (l->type) { + case T_SHORT: + v = newintobject((long) *(short*)addr); + break; + case T_INT: + v = newintobject((long) *(int*)addr); + break; + case T_LONG: + v = newintobject(*(long*)addr); + break; + case T_FLOAT: + v = newfloatobject((double)*(float*)addr); + break; + case T_DOUBLE: + v = newfloatobject(*(double*)addr); + break; + case T_STRING: + if (*(char**)addr == NULL) { + INCREF(None); + v = None; + } + else + v = newstringobject(*(char**)addr); + break; + case T_OBJECT: + v = *(object **)addr; + if (v == NULL) + v = None; + INCREF(v); + break; + default: + err_setstr(SystemError, "bad memberlist type"); + v = NULL; + } + return v; + } + } + + err_setstr(NameError, name); + return NULL; } int setmember(addr, mlist, name, v) - char *addr; - struct memberlist *mlist; - char *name; - object *v; + char *addr; + struct memberlist *mlist; + char *name; + object *v; { - struct memberlist *l; - - for (l = mlist; l->name != NULL; l++) { - if (strcmp(l->name, name) == 0) { - if (l->readonly || l->type == T_STRING) { - err_setstr(RuntimeError, "readonly attribute"); - return -1; - } - addr += l->offset; - switch (l->type) { - case T_SHORT: - if (!is_intobject(v)) { - err_badarg(); - return -1; - } - *(short*)addr = getintvalue(v); - break; - case T_INT: - if (!is_intobject(v)) { - err_badarg(); - return -1; - } - *(int*)addr = getintvalue(v); - break; - case T_LONG: - if (!is_intobject(v)) { - err_badarg(); - return -1; - } - *(long*)addr = getintvalue(v); - break; - case T_FLOAT: - if (is_intobject(v)) - *(float*)addr = getintvalue(v); - else if (is_floatobject(v)) - *(float*)addr = getfloatvalue(v); - else { - err_badarg(); - return -1; - } - break; - case T_DOUBLE: - if (is_intobject(v)) - *(double*)addr = getintvalue(v); - else if (is_floatobject(v)) - *(double*)addr = getfloatvalue(v); - else { - err_badarg(); - return -1; - } - break; - case T_OBJECT: - XDECREF(*(object **)addr); - XINCREF(v); - *(object **)addr = v; - break; - default: - err_setstr(SystemError, "bad memberlist type"); - return -1; - } - return 0; - } - } - - err_setstr(NameError, name); - return -1; + struct memberlist *l; + + for (l = mlist; l->name != NULL; l++) { + if (strcmp(l->name, name) == 0) { + if (l->readonly || l->type == T_STRING) { + err_setstr(RuntimeError, "readonly attribute"); + return -1; + } + addr += l->offset; + switch (l->type) { + case T_SHORT: + if (!is_intobject(v)) { + err_badarg(); + return -1; + } + *(short*)addr = getintvalue(v); + break; + case T_INT: + if (!is_intobject(v)) { + err_badarg(); + return -1; + } + *(int*)addr = getintvalue(v); + break; + case T_LONG: + if (!is_intobject(v)) { + err_badarg(); + return -1; + } + *(long*)addr = getintvalue(v); + break; + case T_FLOAT: + if (is_intobject(v)) + *(float*)addr = getintvalue(v); + else if (is_floatobject(v)) + *(float*)addr = getfloatvalue(v); + else { + err_badarg(); + return -1; + } + break; + case T_DOUBLE: + if (is_intobject(v)) + *(double*)addr = getintvalue(v); + else if (is_floatobject(v)) + *(double*)addr = getfloatvalue(v); + else { + err_badarg(); + return -1; + } + break; + case T_OBJECT: + XDECREF(*(object **)addr); + XINCREF(v); + *(object **)addr = v; + break; + default: + err_setstr(SystemError, "bad memberlist type"); + return -1; + } + return 0; + } + } + + err_setstr(NameError, name); + return -1; } diff --git a/src/structmember.h b/src/structmember.h index 93d2a2e..2cf68d8 100644 --- a/src/structmember.h +++ b/src/structmember.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -25,40 +25,40 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* Interface to map C struct members to Python object attributes */ /* The offsetof() macro calculates the offset of a structure member - in its structure. Unfortunately this cannot be written down - portably, hence it is provided by a Standard C header file. - For pre-Standard C compilers, here is a version that usually works - (but watch out!): */ + in its structure. Unfortunately this cannot be written down + portably, hence it is provided by a Standard C header file. + For pre-Standard C compilers, here is a version that usually works + (but watch out!): */ #ifndef offsetof #define offsetof(type, member) ( (int) & ((type*)0) -> member ) #endif /* An array of memberlist structures defines the name, type and offset - of selected members of a C structure. These can be read by - getmember() and set by setmember() (except if their READONLY flag - is set). The array must be terminated with an entry whose name - pointer is NULL. */ + of selected members of a C structure. These can be read by + getmember() and set by setmember() (except if their READONLY flag + is set). The array must be terminated with an entry whose name + pointer is NULL. */ struct memberlist { - char *name; - int type; - int offset; - int readonly; + char *name; + int type; + int offset; + int readonly; }; /* Types */ -#define T_SHORT 0 -#define T_INT 1 -#define T_LONG 2 -#define T_FLOAT 3 -#define T_DOUBLE 4 -#define T_STRING 5 -#define T_OBJECT 6 +#define T_SHORT 0 +#define T_INT 1 +#define T_LONG 2 +#define T_FLOAT 3 +#define T_DOUBLE 4 +#define T_STRING 5 +#define T_OBJECT 6 /* Readonly flag */ -#define READONLY 1 -#define RO READONLY /* Shorthand */ +#define READONLY 1 +#define RO READONLY /* Shorthand */ object *getmember PROTO((char *, struct memberlist *, char *)); int setmember PROTO((char *, struct memberlist *, char *, object *)); diff --git a/src/stubcode.h b/src/stubcode.h index 6e76c23..9506217 100644 --- a/src/stubcode.h +++ b/src/stubcode.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -23,6 +23,6 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ -#define CAP 0 -#define STUBC 1 -#define NAME 2 +#define CAP 0 +#define STUBC 1 +#define NAME 2 diff --git a/src/sysmodule.c b/src/sysmodule.c index 6b3b576..ececf72 100644 --- a/src/sysmodule.c +++ b/src/sysmodule.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -57,52 +57,52 @@ static object *sysdict; object * sysget(name) - char *name; + char *name; { - return dictlookup(sysdict, name); + return dictlookup(sysdict, name); } FILE * sysgetfile(name, def) - char *name; - FILE *def; + char *name; + FILE *def; { - FILE *fp = NULL; - object *v = sysget(name); - if (v != NULL) - fp = getfilefile(v); - if (fp == NULL) - fp = def; - return fp; + FILE *fp = NULL; + object *v = sysget(name); + if (v != NULL) + fp = getfilefile(v); + if (fp == NULL) + fp = def; + return fp; } int sysset(name, v) - char *name; - object *v; + char *name; + object *v; { - if (v == NULL) - return dictremove(sysdict, name); - else - return dictinsert(sysdict, name, v); + if (v == NULL) + return dictremove(sysdict, name); + else + return dictinsert(sysdict, name, v); } static object * sys_exit(self, args) - object *self; - object *args; + object *self; + object *args; { - int sts; - if (!getintarg(args, &sts)) - return NULL; - goaway(sts); - exit(sts); /* Just in case */ - /* NOTREACHED */ + int sts; + if (!getintarg(args, &sts)) + return NULL; + goaway(sts); + exit(sts); /* Just in case */ + /* NOTREACHED */ } static struct methodlist sys_methods[] = { - {"exit", sys_exit}, - {NULL, NULL} /* sentinel */ + {"exit", sys_exit}, + {NULL, NULL} /* sentinel */ }; static object *sysin, *sysout, *syserr; @@ -110,105 +110,105 @@ static object *sysin, *sysout, *syserr; void initsys() { - object *m = initmodule("sys", sys_methods); - sysdict = getmoduledict(m); - INCREF(sysdict); - /* NB keep an extra ref to the std files to avoid closing them - when the user deletes them */ - /* XXX File objects should have a "don't close" flag instead */ - sysin = newopenfileobject(stdin, "<stdin>", "r"); - sysout = newopenfileobject(stdout, "<stdout>", "w"); - syserr = newopenfileobject(stderr, "<stderr>", "w"); - if (err_occurred()) - fatal("can't create sys.std* file objects"); - dictinsert(sysdict, "stdin", sysin); - dictinsert(sysdict, "stdout", sysout); - dictinsert(sysdict, "stderr", syserr); - dictinsert(sysdict, "modules", get_modules()); - if (err_occurred()) - fatal("can't insert sys.* objects in sys dict"); + object *m = initmodule("sys", sys_methods); + sysdict = getmoduledict(m); + INCREF(sysdict); + /* NB keep an extra ref to the std files to avoid closing them + when the user deletes them */ + /* XXX File objects should have a "don't close" flag instead */ + sysin = newopenfileobject(stdin, "<stdin>", "r"); + sysout = newopenfileobject(stdout, "<stdout>", "w"); + syserr = newopenfileobject(stderr, "<stderr>", "w"); + if (err_occurred()) + fatal("can't create sys.std* file objects"); + dictinsert(sysdict, "stdin", sysin); + dictinsert(sysdict, "stdout", sysout); + dictinsert(sysdict, "stderr", syserr); + dictinsert(sysdict, "modules", get_modules()); + if (err_occurred()) + fatal("can't insert sys.* objects in sys dict"); } static object * makepathobject(path, delim) - char *path; - int delim; + char *path; + int delim; { - int i, n; - char *p; - object *v, *w; - - n = 1; - p = path; - while ((p = strchr(p, delim)) != NULL) { - n++; - p++; - } - v = newlistobject(n); - if (v == NULL) - return NULL; - for (i = 0; ; i++) { - p = strchr(path, delim); - if (p == NULL) - p = strchr(path, '\0'); /* End of string */ - w = newsizedstringobject(path, (int) (p - path)); - if (w == NULL) { - DECREF(v); - return NULL; - } - setlistitem(v, i, w); - if (*p == '\0') - break; - path = p+1; - } - return v; + int i, n; + char *p; + object *v, *w; + + n = 1; + p = path; + while ((p = strchr(p, delim)) != NULL) { + n++; + p++; + } + v = newlistobject(n); + if (v == NULL) + return NULL; + for (i = 0; ; i++) { + p = strchr(path, delim); + if (p == NULL) + p = strchr(path, '\0'); /* End of string */ + w = newsizedstringobject(path, (int) (p - path)); + if (w == NULL) { + DECREF(v); + return NULL; + } + setlistitem(v, i, w); + if (*p == '\0') + break; + path = p+1; + } + return v; } void setpythonpath(path) - char *path; + char *path; { - object *v; - if ((v = makepathobject(path, DELIM)) == NULL) - fatal("can't create sys.path"); - if (sysset("path", v) != 0) - fatal("can't assign sys.path"); - DECREF(v); + object *v; + if ((v = makepathobject(path, DELIM)) == NULL) + fatal("can't create sys.path"); + if (sysset("path", v) != 0) + fatal("can't assign sys.path"); + DECREF(v); } static object * makeargvobject(argc, argv) - int argc; - char **argv; + int argc; + char **argv; { - object *av; - if (argc < 0 || argv == NULL) - argc = 0; - av = newlistobject(argc); - if (av != NULL) { - int i; - for (i = 0; i < argc; i++) { - object *v = newstringobject(argv[i]); - if (v == NULL) { - DECREF(av); - av = NULL; - break; - } - setlistitem(av, i, v); - } - } - return av; + object *av; + if (argc < 0 || argv == NULL) + argc = 0; + av = newlistobject(argc); + if (av != NULL) { + int i; + for (i = 0; i < argc; i++) { + object *v = newstringobject(argv[i]); + if (v == NULL) { + DECREF(av); + av = NULL; + break; + } + setlistitem(av, i, v); + } + } + return av; } void setpythonargv(argc, argv) - int argc; - char **argv; + int argc; + char **argv; { - object *av = makeargvobject(argc, argv); - if (av == NULL) - fatal("no mem for sys.argv"); - if (sysset("argv", av) != 0) - fatal("can't assign sys.argv"); - DECREF(av); + object *av = makeargvobject(argc, argv); + if (av == NULL) + fatal("no mem for sys.argv"); + if (sysset("argv", av) != 0) + fatal("can't assign sys.argv"); + DECREF(av); } diff --git a/src/sysmodule.h b/src/sysmodule.h index eed1944..f79ecdb 100644 --- a/src/sysmodule.h +++ b/src/sysmodule.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. diff --git a/src/timemodule.c b/src/timemodule.c index dcaedbd..b1c1ce3 100644 --- a/src/timemodule.c +++ b/src/timemodule.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -45,46 +45,46 @@ extern time_t time(); static object * time_time(self, args) - object *self; - object *args; + object *self; + object *args; { - long secs; - if (!getnoarg(args)) - return NULL; - secs = time((time_t *)NULL); - return newintobject(secs); + long secs; + if (!getnoarg(args)) + return NULL; + secs = time((time_t *)NULL); + return newintobject(secs); } static jmp_buf sleep_intr; static void sleep_catcher(sig) - int sig; + int sig; { - longjmp(sleep_intr, 1); + longjmp(sleep_intr, 1); } static object * time_sleep(self, args) - object *self; - object *args; + object *self; + object *args; { - int secs; - SIGTYPE (*sigsave)(); - if (!getintarg(args, &secs)) - return NULL; - if (setjmp(sleep_intr)) { - signal(SIGINT, sigsave); - err_set(KeyboardInterrupt); - return NULL; - } - sigsave = signal(SIGINT, SIG_IGN); - if (sigsave != (SIGTYPE (*)()) SIG_IGN) - signal(SIGINT, sleep_catcher); - sleep(secs); - signal(SIGINT, sigsave); - INCREF(None); - return None; + int secs; + SIGTYPE (*sigsave)(); + if (!getintarg(args, &secs)) + return NULL; + if (setjmp(sleep_intr)) { + signal(SIGINT, sigsave); + err_set(KeyboardInterrupt); + return NULL; + } + sigsave = signal(SIGINT, SIG_IGN); + if (sigsave != (SIGTYPE (*)()) SIG_IGN) + signal(SIGINT, sleep_catcher); + sleep(secs); + signal(SIGINT, sigsave); + INCREF(None); + return None; } #ifdef THINK_C @@ -105,38 +105,38 @@ extern long sys_milli(); static object * time_millisleep(self, args) - object *self; - object *args; + object *self; + object *args; { - long msecs; - SIGTYPE (*sigsave)(); - if (!getlongarg(args, &msecs)) - return NULL; - if (setjmp(sleep_intr)) { - signal(SIGINT, sigsave); - err_set(KeyboardInterrupt); - return NULL; - } - sigsave = signal(SIGINT, SIG_IGN); - if (sigsave != (SIGTYPE (*)()) SIG_IGN) - signal(SIGINT, sleep_catcher); - millisleep(msecs); - signal(SIGINT, sigsave); - INCREF(None); - return None; + long msecs; + SIGTYPE (*sigsave)(); + if (!getlongarg(args, &msecs)) + return NULL; + if (setjmp(sleep_intr)) { + signal(SIGINT, sigsave); + err_set(KeyboardInterrupt); + return NULL; + } + sigsave = signal(SIGINT, SIG_IGN); + if (sigsave != (SIGTYPE (*)()) SIG_IGN) + signal(SIGINT, sleep_catcher); + millisleep(msecs); + signal(SIGINT, sigsave); + INCREF(None); + return None; } static object * time_millitimer(self, args) - object *self; - object *args; + object *self; + object *args; { - long msecs; - extern long millitimer(); - if (!getnoarg(args)) - return NULL; - msecs = millitimer(); - return newintobject(msecs); + long msecs; + extern long millitimer(); + if (!getnoarg(args)) + return NULL; + msecs = millitimer(); + return newintobject(msecs); } #endif /* DO_MILLI */ @@ -144,56 +144,56 @@ time_millitimer(self, args) static struct methodlist time_methods[] = { #ifdef DO_MILLI - {"millisleep", time_millisleep}, - {"millitimer", time_millitimer}, + {"millisleep", time_millisleep}, + {"millitimer", time_millitimer}, #endif /* DO_MILLI */ - {"sleep", time_sleep}, - {"time", time_time}, - {NULL, NULL} /* sentinel */ + {"sleep", time_sleep}, + {"time", time_time}, + {NULL, NULL} /* sentinel */ }; void inittime() { - initmodule("time", time_methods); + initmodule("time", time_methods); } #ifdef THINK_C -#define MacTicks (* (long *)0x16A) +#define MacTicks (* (long *)0x16A) static sleep(msecs) - int msecs; + int msecs; { - register long deadline; - - deadline = MacTicks + msecs * 60; - while (MacTicks < deadline) { - if (intrcheck()) - sleep_catcher(SIGINT); - } + register long deadline; + + deadline = MacTicks + msecs * 60; + while (MacTicks < deadline) { + if (intrcheck()) + sleep_catcher(SIGINT); + } } static millisleep(msecs) - long msecs; + long msecs; { - register long deadline; - - deadline = MacTicks + msecs * 3 / 50; /* msecs * 60 / 1000 */ - while (MacTicks < deadline) { - if (intrcheck()) - sleep_catcher(SIGINT); - } + register long deadline; + + deadline = MacTicks + msecs * 3 / 50; /* msecs * 60 / 1000 */ + while (MacTicks < deadline) { + if (intrcheck()) + sleep_catcher(SIGINT); + } } static long millitimer() { - return MacTicks * 50 / 3; /* MacTicks * 1000 / 60 */ + return MacTicks * 50 / 3; /* MacTicks * 1000 / 60 */ } #endif /* THINK_C */ @@ -207,22 +207,22 @@ millitimer() static long millitimer() { - struct timeval t; - struct timezone tz; - if (gettimeofday(&t, &tz) != 0) - return -1; - return t.tv_sec*1000 + t.tv_usec/1000; - + struct timeval t; + struct timezone tz; + if (gettimeofday(&t, &tz) != 0) + return -1; + return t.tv_sec*1000 + t.tv_usec/1000; + } static millisleep(msecs) - long msecs; + long msecs; { - struct timeval t; - t.tv_sec = msecs/1000; - t.tv_usec = (msecs%1000)*1000; - (void) select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t); + struct timeval t; + t.tv_sec = msecs/1000; + t.tv_usec = (msecs%1000)*1000; + (void) select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t); } #endif /* BSD_TIME */ diff --git a/src/token.h b/src/token.h index 79f0ed0..7bd3830 100644 --- a/src/token.h +++ b/src/token.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -24,45 +24,45 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* Token types */ -#define ENDMARKER 0 -#define NAME 1 -#define NUMBER 2 -#define STRING 3 -#define NEWLINE 4 -#define INDENT 5 -#define DEDENT 6 -#define LPAR 7 -#define RPAR 8 -#define LSQB 9 -#define RSQB 10 -#define COLON 11 -#define COMMA 12 -#define SEMI 13 -#define PLUS 14 -#define MINUS 15 -#define STAR 16 -#define SLASH 17 -#define VBAR 18 -#define AMPER 19 -#define LESS 20 -#define GREATER 21 -#define EQUAL 22 -#define DOT 23 -#define PERCENT 24 -#define BACKQUOTE 25 -#define LBRACE 26 -#define RBRACE 27 -#define OP 28 -#define ERRORTOKEN 29 -#define N_TOKENS 30 +#define ENDMARKER 0 +#define NAME 1 +#define NUMBER 2 +#define STRING 3 +#define NEWLINE 4 +#define INDENT 5 +#define DEDENT 6 +#define LPAR 7 +#define RPAR 8 +#define LSQB 9 +#define RSQB 10 +#define COLON 11 +#define COMMA 12 +#define SEMI 13 +#define PLUS 14 +#define MINUS 15 +#define STAR 16 +#define SLASH 17 +#define VBAR 18 +#define AMPER 19 +#define LESS 20 +#define GREATER 21 +#define EQUAL 22 +#define DOT 23 +#define PERCENT 24 +#define BACKQUOTE 25 +#define LBRACE 26 +#define RBRACE 27 +#define OP 28 +#define ERRORTOKEN 29 +#define N_TOKENS 30 /* Special definitions for cooperation with parser */ -#define NT_OFFSET 256 +#define NT_OFFSET 256 -#define ISTERMINAL(x) ((x) < NT_OFFSET) -#define ISNONTERMINAL(x) ((x) >= NT_OFFSET) -#define ISEOF(x) ((x) == ENDMARKER) +#define ISTERMINAL(x) ((x) < NT_OFFSET) +#define ISNONTERMINAL(x) ((x) >= NT_OFFSET) +#define ISEOF(x) ((x) == ENDMARKER) extern char *tok_name[]; /* Token names */ diff --git a/src/tokenizer.c b/src/tokenizer.c index 231123f..86106b3 100644 --- a/src/tokenizer.c +++ b/src/tokenizer.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -53,37 +53,37 @@ static void tok_backup PROTO((struct tok_state *tok, int c)); /* Token names */ char *tok_name[] = { - "ENDMARKER", - "NAME", - "NUMBER", - "STRING", - "NEWLINE", - "INDENT", - "DEDENT", - "LPAR", - "RPAR", - "LSQB", - "RSQB", - "COLON", - "COMMA", - "SEMI", - "PLUS", - "MINUS", - "STAR", - "SLASH", - "VBAR", - "AMPER", - "LESS", - "GREATER", - "EQUAL", - "DOT", - "PERCENT", - "BACKQUOTE", - "LBRACE", - "RBRACE", - "OP", - "<ERRORTOKEN>", - "<N_TOKENS>" + "ENDMARKER", + "NAME", + "NUMBER", + "STRING", + "NEWLINE", + "INDENT", + "DEDENT", + "LPAR", + "RPAR", + "LSQB", + "RSQB", + "COLON", + "COMMA", + "SEMI", + "PLUS", + "MINUS", + "STAR", + "SLASH", + "VBAR", + "AMPER", + "LESS", + "GREATER", + "EQUAL", + "DOT", + "PERCENT", + "BACKQUOTE", + "LBRACE", + "RBRACE", + "OP", + "<ERRORTOKEN>", + "<N_TOKENS>" }; @@ -92,20 +92,20 @@ char *tok_name[] = { static struct tok_state * tok_new() { - struct tok_state *tok = NEW(struct tok_state, 1); - if (tok == NULL) - return NULL; - tok->buf = tok->cur = tok->end = tok->inp = NULL; - tok->done = E_OK; - tok->fp = NULL; - tok->tabsize = TABSIZE; - tok->indent = 0; - tok->indstack[0] = 0; - tok->atbol = 1; - tok->pendin = 0; - tok->prompt = tok->nextprompt = NULL; - tok->lineno = 0; - return tok; + struct tok_state *tok = NEW(struct tok_state, 1); + if (tok == NULL) + return NULL; + tok->buf = tok->cur = tok->end = tok->inp = NULL; + tok->done = E_OK; + tok->fp = NULL; + tok->tabsize = TABSIZE; + tok->indent = 0; + tok->indstack[0] = 0; + tok->atbol = 1; + tok->pendin = 0; + tok->prompt = tok->nextprompt = NULL; + tok->lineno = 0; + return tok; } @@ -113,14 +113,14 @@ tok_new() struct tok_state * tok_setups(str) - char *str; + char *str; { - struct tok_state *tok = tok_new(); - if (tok == NULL) - return NULL; - tok->buf = tok->cur = str; - tok->end = tok->inp = strchr(str, '\0'); - return tok; + struct tok_state *tok = tok_new(); + if (tok == NULL) + return NULL; + tok->buf = tok->cur = str; + tok->end = tok->inp = strchr(str, '\0'); + return tok; } @@ -128,22 +128,22 @@ tok_setups(str) struct tok_state * tok_setupf(fp, ps1, ps2) - FILE *fp; - char *ps1, *ps2; + FILE *fp; + char *ps1, *ps2; { - struct tok_state *tok = tok_new(); - if (tok == NULL) - return NULL; - if ((tok->buf = NEW(char, BUFSIZ)) == NULL) { - DEL(tok); - return NULL; - } - tok->cur = tok->inp = tok->buf; - tok->end = tok->buf + BUFSIZ; - tok->fp = fp; - tok->prompt = ps1; - tok->nextprompt = ps2; - return tok; + struct tok_state *tok = tok_new(); + if (tok == NULL) + return NULL; + if ((tok->buf = NEW(char, BUFSIZ)) == NULL) { + DEL(tok); + return NULL; + } + tok->cur = tok->inp = tok->buf; + tok->end = tok->buf + BUFSIZ; + tok->fp = fp; + tok->prompt = ps1; + tok->nextprompt = ps2; + return tok; } @@ -151,12 +151,12 @@ tok_setupf(fp, ps1, ps2) void tok_free(tok) - struct tok_state *tok; + struct tok_state *tok; { - /* XXX really need a separate flag to say 'my buffer' */ - if (tok->fp != NULL && tok->buf != NULL) - DEL(tok->buf); - DEL(tok); + /* XXX really need a separate flag to say 'my buffer' */ + if (tok->fp != NULL && tok->buf != NULL) + DEL(tok->buf); + DEL(tok); } @@ -164,89 +164,89 @@ tok_free(tok) static int tok_nextc(tok) - register struct tok_state *tok; + register struct tok_state *tok; { - if (tok->done != E_OK) - return EOF; - - for (;;) { - if (tok->cur < tok->inp) - return *tok->cur++; - if (tok->fp == NULL) { - tok->done = E_EOF; - return EOF; - } - if (tok->inp > tok->buf && tok->inp[-1] == '\n') - tok->inp = tok->buf; - if (tok->inp == tok->end) { - int n = tok->end - tok->buf; - char *new = tok->buf; - RESIZE(new, char, n+n); - if (new == NULL) { - fprintf(stderr, "tokenizer out of mem\n"); - tok->done = E_NOMEM; - return EOF; - } - tok->buf = new; - tok->inp = tok->buf + n; - tok->end = tok->inp + n; - } + if (tok->done != E_OK) + return EOF; + + for (;;) { + if (tok->cur < tok->inp) + return *tok->cur++; + if (tok->fp == NULL) { + tok->done = E_EOF; + return EOF; + } + if (tok->inp > tok->buf && tok->inp[-1] == '\n') + tok->inp = tok->buf; + if (tok->inp == tok->end) { + int n = tok->end - tok->buf; + char *new = tok->buf; + RESIZE(new, char, n+n); + if (new == NULL) { + fprintf(stderr, "tokenizer out of mem\n"); + tok->done = E_NOMEM; + return EOF; + } + tok->buf = new; + tok->inp = tok->buf + n; + tok->end = tok->inp + n; + } #ifdef USE_READLINE - if (tok->prompt != NULL) { - extern char *readline PROTO((char *prompt)); - static int been_here; - if (!been_here) { - /* Force rebind of TAB to insert-tab */ - extern int rl_insert(); - rl_bind_key('\t', rl_insert); - been_here++; - } - if (tok->buf != NULL) - free(tok->buf); - tok->buf = readline(tok->prompt); - (void) intrcheck(); /* Clear pending interrupt */ - if (tok->nextprompt != NULL) - tok->prompt = tok->nextprompt; - /* XXX different semantics w/o readline()! */ - if (tok->buf == NULL) { - tok->done = E_EOF; - } - else { - unsigned int n = strlen(tok->buf); - if (n > 0) - add_history(tok->buf); - /* Append the '\n' that readline() - doesn't give us, for the tokenizer... */ - tok->buf = realloc(tok->buf, n+2); - if (tok->buf == NULL) - tok->done = E_NOMEM; - else { - tok->end = tok->buf + n; - *tok->end++ = '\n'; - *tok->end = '\0'; - tok->inp = tok->end; - tok->cur = tok->buf; - } - } - } - else + if (tok->prompt != NULL) { + extern char *readline PROTO((char *prompt)); + static int been_here; + if (!been_here) { + /* Force rebind of TAB to insert-tab */ + extern int rl_insert(); + rl_bind_key('\t', rl_insert); + been_here++; + } + if (tok->buf != NULL) + free(tok->buf); + tok->buf = readline(tok->prompt); + (void) intrcheck(); /* Clear pending interrupt */ + if (tok->nextprompt != NULL) + tok->prompt = tok->nextprompt; + /* XXX different semantics w/o readline()! */ + if (tok->buf == NULL) { + tok->done = E_EOF; + } + else { + unsigned int n = strlen(tok->buf); + if (n > 0) + add_history(tok->buf); + /* Append the '\n' that readline() + doesn't give us, for the tokenizer... */ + tok->buf = realloc(tok->buf, n+2); + if (tok->buf == NULL) + tok->done = E_NOMEM; + else { + tok->end = tok->buf + n; + *tok->end++ = '\n'; + *tok->end = '\0'; + tok->inp = tok->end; + tok->cur = tok->buf; + } + } + } + else #endif - { - tok->cur = tok->inp; - if (tok->prompt != NULL && tok->inp == tok->buf) { - fprintf(stderr, "%s", tok->prompt); - tok->prompt = tok->nextprompt; - } - tok->done = fgets_intr(tok->inp, - (int)(tok->end - tok->inp), tok->fp); - } - if (tok->done != E_OK) { - if (tok->prompt != NULL) - fprintf(stderr, "\n"); - return EOF; - } - tok->inp = strchr(tok->inp, '\0'); - } + { + tok->cur = tok->inp; + if (tok->prompt != NULL && tok->inp == tok->buf) { + fprintf(stderr, "%s", tok->prompt); + tok->prompt = tok->nextprompt; + } + tok->done = fgets_intr(tok->inp, + (int)(tok->end - tok->inp), tok->fp); + } + if (tok->done != E_OK) { + if (tok->prompt != NULL) + fprintf(stderr, "\n"); + return EOF; + } + tok->inp = strchr(tok->inp, '\0'); + } } @@ -254,17 +254,17 @@ tok_nextc(tok) static void tok_backup(tok, c) - register struct tok_state *tok; - register int c; + register struct tok_state *tok; + register int c; { - if (c != EOF) { - if (--tok->cur < tok->buf) { - fprintf(stderr, "tok_backup: begin of buffer\n"); - abort(); - } - if (*tok->cur != c) - *tok->cur = c; - } + if (c != EOF) { + if (--tok->cur < tok->buf) { + fprintf(stderr, "tok_backup: begin of buffer\n"); + abort(); + } + if (*tok->cur != c) + *tok->cur = c; + } } @@ -272,32 +272,32 @@ tok_backup(tok, c) int tok_1char(c) - int c; + int c; { - switch (c) { - case '(': return LPAR; - case ')': return RPAR; - case '[': return LSQB; - case ']': return RSQB; - case ':': return COLON; - case ',': return COMMA; - case ';': return SEMI; - case '+': return PLUS; - case '-': return MINUS; - case '*': return STAR; - case '/': return SLASH; - case '|': return VBAR; - case '&': return AMPER; - case '<': return LESS; - case '>': return GREATER; - case '=': return EQUAL; - case '.': return DOT; - case '%': return PERCENT; - case '`': return BACKQUOTE; - case '{': return LBRACE; - case '}': return RBRACE; - default: return OP; - } + switch (c) { + case '(': return LPAR; + case ')': return RPAR; + case '[': return LSQB; + case ']': return RSQB; + case ':': return COLON; + case ',': return COMMA; + case ';': return SEMI; + case '+': return PLUS; + case '-': return MINUS; + case '*': return STAR; + case '/': return SLASH; + case '|': return VBAR; + case '&': return AMPER; + case '<': return LESS; + case '>': return GREATER; + case '=': return EQUAL; + case '.': return DOT; + case '%': return PERCENT; + case '`': return BACKQUOTE; + case '{': return LBRACE; + case '}': return RBRACE; + default: return OP; + } } @@ -305,206 +305,206 @@ tok_1char(c) int tok_get(tok, p_start, p_end) - register struct tok_state *tok; /* In/out: tokenizer state */ - char **p_start, **p_end; /* Out: point to start/end of token */ + register struct tok_state *tok; /* In/out: tokenizer state */ + char **p_start, **p_end; /* Out: point to start/end of token */ { - register int c; - - /* Get indentation level */ - if (tok->atbol) { - register int col = 0; - tok->atbol = 0; - tok->lineno++; - for (;;) { - c = tok_nextc(tok); - if (c == ' ') - col++; - else if (c == '\t') - col = (col/tok->tabsize + 1) * tok->tabsize; - else - break; - } - tok_backup(tok, c); - if (col == tok->indstack[tok->indent]) { - /* No change */ - } - else if (col > tok->indstack[tok->indent]) { - /* Indent -- always one */ - if (tok->indent+1 >= MAXINDENT) { - fprintf(stderr, "excessive indent\n"); - tok->done = E_TOKEN; - return ERRORTOKEN; - } - tok->pendin++; - tok->indstack[++tok->indent] = col; - } - else /* col < tok->indstack[tok->indent] */ { - /* Dedent -- any number, must be consistent */ - while (tok->indent > 0 && - col < tok->indstack[tok->indent]) { - tok->indent--; - tok->pendin--; - } - if (col != tok->indstack[tok->indent]) { - fprintf(stderr, "inconsistent dedent\n"); - tok->done = E_TOKEN; - return ERRORTOKEN; - } - } - } - - *p_start = *p_end = tok->cur; - - /* Return pending indents/dedents */ - if (tok->pendin != 0) { - if (tok->pendin < 0) { - tok->pendin++; - return DEDENT; - } - else { - tok->pendin--; - return INDENT; - } - } - + register int c; + + /* Get indentation level */ + if (tok->atbol) { + register int col = 0; + tok->atbol = 0; + tok->lineno++; + for (;;) { + c = tok_nextc(tok); + if (c == ' ') + col++; + else if (c == '\t') + col = (col/tok->tabsize + 1) * tok->tabsize; + else + break; + } + tok_backup(tok, c); + if (col == tok->indstack[tok->indent]) { + /* No change */ + } + else if (col > tok->indstack[tok->indent]) { + /* Indent -- always one */ + if (tok->indent+1 >= MAXINDENT) { + fprintf(stderr, "excessive indent\n"); + tok->done = E_TOKEN; + return ERRORTOKEN; + } + tok->pendin++; + tok->indstack[++tok->indent] = col; + } + else /* col < tok->indstack[tok->indent] */ { + /* Dedent -- any number, must be consistent */ + while (tok->indent > 0 && + col < tok->indstack[tok->indent]) { + tok->indent--; + tok->pendin--; + } + if (col != tok->indstack[tok->indent]) { + fprintf(stderr, "inconsistent dedent\n"); + tok->done = E_TOKEN; + return ERRORTOKEN; + } + } + } + + *p_start = *p_end = tok->cur; + + /* Return pending indents/dedents */ + if (tok->pendin != 0) { + if (tok->pendin < 0) { + tok->pendin++; + return DEDENT; + } + else { + tok->pendin--; + return INDENT; + } + } + again: - /* Skip spaces */ - do { - c = tok_nextc(tok); - } while (c == ' ' || c == '\t'); - - /* Set start of current token */ - *p_start = tok->cur - 1; - - /* Skip comment */ - if (c == '#') { - /* Hack to allow overriding the tabsize in the file. - This is also recognized by vi, when it occurs near the - beginning or end of the file. (Will vi never die...?) */ - int x; - /* XXX The case to (unsigned char *) is needed by THINK C 3.0 */ - if (sscanf(/*(unsigned char *)*/tok->cur, - " vi:set tabsize=%d:", &x) == 1 && - x >= 1 && x <= 40) { - fprintf(stderr, "# vi:set tabsize=%d:\n", x); - tok->tabsize = x; - } - do { - c = tok_nextc(tok); - } while (c != EOF && c != '\n'); - } - - /* Check for EOF and errors now */ - if (c == EOF) - return tok->done == E_EOF ? ENDMARKER : ERRORTOKEN; - - /* Identifier (most frequent token!) */ - if (isalpha(c) || c == '_') { - do { - c = tok_nextc(tok); - } while (isalnum(c) || c == '_'); - tok_backup(tok, c); - *p_end = tok->cur; - return NAME; - } - - /* Newline */ - if (c == '\n') { - tok->atbol = 1; - *p_end = tok->cur - 1; /* Leave '\n' out of the string */ - return NEWLINE; - } - - /* Number */ - if (isdigit(c)) { - if (c == '0') { - /* Hex or octal */ - c = tok_nextc(tok); - if (c == '.') - goto fraction; - if (c == 'x' || c == 'X') { - /* Hex */ - do { - c = tok_nextc(tok); - } while (isxdigit(c)); - } - else { - /* Octal; c is first char of it */ - /* There's no 'isoctdigit' macro, sigh */ - while ('0' <= c && c < '8') { - c = tok_nextc(tok); - } - } - } - else { - /* Decimal */ - do { - c = tok_nextc(tok); - } while (isdigit(c)); - /* Accept floating point numbers. - XXX This accepts incomplete things like 12e or 1e+; - worry about that at run-time. - XXX Doesn't accept numbers starting with a dot */ - if (c == '.') { - fraction: - /* Fraction */ - do { - c = tok_nextc(tok); - } while (isdigit(c)); - } - if (c == 'e' || c == 'E') { - /* Exponent part */ - c = tok_nextc(tok); - if (c == '+' || c == '-') - c = tok_nextc(tok); - while (isdigit(c)) { - c = tok_nextc(tok); - } - } - } - tok_backup(tok, c); - *p_end = tok->cur; - return NUMBER; - } - - /* String */ - if (c == '\'') { - for (;;) { - c = tok_nextc(tok); - if (c == '\n' || c == EOF) { - tok->done = E_TOKEN; - return ERRORTOKEN; - } - if (c == '\\') { - c = tok_nextc(tok); - *p_end = tok->cur; - if (c == '\n' || c == EOF) { - tok->done = E_TOKEN; - return ERRORTOKEN; - } - continue; - } - if (c == '\'') - break; - } - *p_end = tok->cur; - return STRING; - } - - /* Line continuation */ - if (c == '\\') { - c = tok_nextc(tok); - if (c != '\n') { - tok->done = E_TOKEN; - return ERRORTOKEN; - } - tok->lineno++; - goto again; /* Read next line */ - } - - /* Punctuation character */ - *p_end = tok->cur; - return tok_1char(c); + /* Skip spaces */ + do { + c = tok_nextc(tok); + } while (c == ' ' || c == '\t'); + + /* Set start of current token */ + *p_start = tok->cur - 1; + + /* Skip comment */ + if (c == '#') { + /* Hack to allow overriding the tabsize in the file. + This is also recognized by vi, when it occurs near the + beginning or end of the file. (Will vi never die...?) */ + int x; + /* XXX The case to (unsigned char *) is needed by THINK C 3.0 */ + if (sscanf(/*(unsigned char *)*/tok->cur, + " vi:set tabsize=%d:", &x) == 1 && + x >= 1 && x <= 40) { + fprintf(stderr, "# vi:set tabsize=%d:\n", x); + tok->tabsize = x; + } + do { + c = tok_nextc(tok); + } while (c != EOF && c != '\n'); + } + + /* Check for EOF and errors now */ + if (c == EOF) + return tok->done == E_EOF ? ENDMARKER : ERRORTOKEN; + + /* Identifier (most frequent token!) */ + if (isalpha(c) || c == '_') { + do { + c = tok_nextc(tok); + } while (isalnum(c) || c == '_'); + tok_backup(tok, c); + *p_end = tok->cur; + return NAME; + } + + /* Newline */ + if (c == '\n') { + tok->atbol = 1; + *p_end = tok->cur - 1; /* Leave '\n' out of the string */ + return NEWLINE; + } + + /* Number */ + if (isdigit(c)) { + if (c == '0') { + /* Hex or octal */ + c = tok_nextc(tok); + if (c == '.') + goto fraction; + if (c == 'x' || c == 'X') { + /* Hex */ + do { + c = tok_nextc(tok); + } while (isxdigit(c)); + } + else { + /* Octal; c is first char of it */ + /* There's no 'isoctdigit' macro, sigh */ + while ('0' <= c && c < '8') { + c = tok_nextc(tok); + } + } + } + else { + /* Decimal */ + do { + c = tok_nextc(tok); + } while (isdigit(c)); + /* Accept floating point numbers. + XXX This accepts incomplete things like 12e or 1e+; + worry about that at run-time. + XXX Doesn't accept numbers starting with a dot */ + if (c == '.') { + fraction: + /* Fraction */ + do { + c = tok_nextc(tok); + } while (isdigit(c)); + } + if (c == 'e' || c == 'E') { + /* Exponent part */ + c = tok_nextc(tok); + if (c == '+' || c == '-') + c = tok_nextc(tok); + while (isdigit(c)) { + c = tok_nextc(tok); + } + } + } + tok_backup(tok, c); + *p_end = tok->cur; + return NUMBER; + } + + /* String */ + if (c == '\'') { + for (;;) { + c = tok_nextc(tok); + if (c == '\n' || c == EOF) { + tok->done = E_TOKEN; + return ERRORTOKEN; + } + if (c == '\\') { + c = tok_nextc(tok); + *p_end = tok->cur; + if (c == '\n' || c == EOF) { + tok->done = E_TOKEN; + return ERRORTOKEN; + } + continue; + } + if (c == '\'') + break; + } + *p_end = tok->cur; + return STRING; + } + + /* Line continuation */ + if (c == '\\') { + c = tok_nextc(tok); + if (c != '\n') { + tok->done = E_TOKEN; + return ERRORTOKEN; + } + tok->lineno++; + goto again; /* Read next line */ + } + + /* Punctuation character */ + *p_end = tok->cur; + return tok_1char(c); } @@ -512,12 +512,12 @@ tok_get(tok, p_start, p_end) void tok_dump(type, start, end) - int type; - char *start, *end; + int type; + char *start, *end; { - printf("%s", tok_name[type]); - if (type == NAME || type == NUMBER || type == STRING || type == OP) - printf("(%.*s)", (int)(end - start), start); + printf("%s", tok_name[type]); + if (type == NAME || type == NUMBER || type == STRING || type == OP) + printf("(%.*s)", (int)(end - start), start); } #endif diff --git a/src/tokenizer.h b/src/tokenizer.h index aec5ef3..ddb6d36 100644 --- a/src/tokenizer.h +++ b/src/tokenizer.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -24,27 +24,27 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* Tokenizer interface */ -#include "token.h" /* For token types */ +#include "token.h" /* For token types */ -#define MAXINDENT 100 /* Max indentation level */ +#define MAXINDENT 100 /* Max indentation level */ /* Tokenizer state */ struct tok_state { - /* Input state; buf <= cur <= inp <= end */ - /* NB an entire token must fit in the buffer */ - char *buf; /* Input buffer */ - char *cur; /* Next character in buffer */ - char *inp; /* End of data in buffer */ - char *end; /* End of input buffer */ - int done; /* 0 normally, 1 at EOF, -1 after error */ - FILE *fp; /* Rest of input; NULL if tokenizing a string */ - int tabsize; /* Tab spacing */ - int indent; /* Current indentation index */ - int indstack[MAXINDENT]; /* Stack of indents */ - int atbol; /* Nonzero if at begin of new line */ - int pendin; /* Pending indents (if > 0) or dedents (if < 0) */ - char *prompt, *nextprompt; /* For interactive prompting */ - int lineno; /* Current line number */ + /* Input state; buf <= cur <= inp <= end */ + /* NB an entire token must fit in the buffer */ + char *buf; /* Input buffer */ + char *cur; /* Next character in buffer */ + char *inp; /* End of data in buffer */ + char *end; /* End of input buffer */ + int done; /* 0 normally, 1 at EOF, -1 after error */ + FILE *fp; /* Rest of input; NULL if tokenizing a string */ + int tabsize; /* Tab spacing */ + int indent; /* Current indentation index */ + int indstack[MAXINDENT]; /* Stack of indents */ + int atbol; /* Nonzero if at begin of new line */ + int pendin; /* Pending indents (if > 0) or dedents (if < 0) */ + char *prompt, *nextprompt; /* For interactive prompting */ + int lineno; /* Current line number */ }; extern struct tok_state *tok_setups PROTO((char *)); diff --git a/src/traceback.c b/src/traceback.c index 7d40ca5..0b6904f 100644 --- a/src/traceback.c +++ b/src/traceback.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -32,186 +32,186 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include "structmember.h" typedef struct _tracebackobject { - OB_HEAD - struct _tracebackobject *tb_next; - frameobject *tb_frame; - int tb_lasti; - int tb_lineno; + OB_HEAD + struct _tracebackobject *tb_next; + frameobject *tb_frame; + int tb_lasti; + int tb_lineno; } tracebackobject; #define OFF(x) offsetof(tracebackobject, x) static struct memberlist tb_memberlist[] = { - {"tb_next", T_OBJECT, OFF(tb_next)}, - {"tb_frame", T_OBJECT, OFF(tb_frame)}, - {"tb_lasti", T_INT, OFF(tb_lasti)}, - {"tb_lineno", T_INT, OFF(tb_lineno)}, - {NULL} /* Sentinel */ + {"tb_next", T_OBJECT, OFF(tb_next)}, + {"tb_frame", T_OBJECT, OFF(tb_frame)}, + {"tb_lasti", T_INT, OFF(tb_lasti)}, + {"tb_lineno", T_INT, OFF(tb_lineno)}, + {NULL} /* Sentinel */ }; static object * tb_getattr(tb, name) - tracebackobject *tb; - char *name; + tracebackobject *tb; + char *name; { - return getmember((char *)tb, tb_memberlist, name); + return getmember((char *)tb, tb_memberlist, name); } static void tb_dealloc(tb) - tracebackobject *tb; + tracebackobject *tb; { - XDECREF(tb->tb_next); - XDECREF(tb->tb_frame); - DEL(tb); + XDECREF(tb->tb_next); + XDECREF(tb->tb_frame); + DEL(tb); } static typeobject Tracebacktype = { - OB_HEAD_INIT(&Typetype) - 0, - "traceback", - sizeof(tracebackobject), - 0, - tb_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - tb_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ + OB_HEAD_INIT(&Typetype) + 0, + "traceback", + sizeof(tracebackobject), + 0, + tb_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + tb_getattr, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ }; #define is_tracebackobject(v) ((v)->ob_type == &Tracebacktype) static tracebackobject * newtracebackobject(next, frame, lasti, lineno) - tracebackobject *next; - frameobject *frame; - int lasti, lineno; + tracebackobject *next; + frameobject *frame; + int lasti, lineno; { - tracebackobject *tb; - if ((next != NULL && !is_tracebackobject(next)) || - frame == NULL || !is_frameobject(frame)) { - err_badcall(); - return NULL; - } - tb = NEWOBJ(tracebackobject, &Tracebacktype); - if (tb != NULL) { - XINCREF(next); - tb->tb_next = next; - XINCREF(frame); - tb->tb_frame = frame; - tb->tb_lasti = lasti; - tb->tb_lineno = lineno; - } - return tb; + tracebackobject *tb; + if ((next != NULL && !is_tracebackobject(next)) || + frame == NULL || !is_frameobject(frame)) { + err_badcall(); + return NULL; + } + tb = NEWOBJ(tracebackobject, &Tracebacktype); + if (tb != NULL) { + XINCREF(next); + tb->tb_next = next; + XINCREF(frame); + tb->tb_frame = frame; + tb->tb_lasti = lasti; + tb->tb_lineno = lineno; + } + return tb; } static tracebackobject *tb_current = NULL; int tb_here(frame, lasti, lineno) - frameobject *frame; - int lasti; - int lineno; + frameobject *frame; + int lasti; + int lineno; { - tracebackobject *tb; - tb = newtracebackobject(tb_current, frame, lasti, lineno); - if (tb == NULL) - return -1; - XDECREF(tb_current); - tb_current = tb; - return 0; + tracebackobject *tb; + tb = newtracebackobject(tb_current, frame, lasti, lineno); + if (tb == NULL) + return -1; + XDECREF(tb_current); + tb_current = tb; + return 0; } object * tb_fetch() { - object *v; - v = (object *)tb_current; - tb_current = NULL; - return v; + object *v; + v = (object *)tb_current; + tb_current = NULL; + return v; } int tb_store(v) - object *v; + object *v; { - if (v != NULL && !is_tracebackobject(v)) { - err_badcall(); - return -1; - } - XDECREF(tb_current); - XINCREF(v); - tb_current = (tracebackobject *)v; - return 0; + if (v != NULL && !is_tracebackobject(v)) { + err_badcall(); + return -1; + } + XDECREF(tb_current); + XINCREF(v); + tb_current = (tracebackobject *)v; + return 0; } static void tb_displayline(fp, filename, lineno) - FILE *fp; - char *filename; - int lineno; + FILE *fp; + char *filename; + int lineno; { - FILE *xfp; - char buf[1000]; - int i; - if (filename[0] == '<' && filename[strlen(filename)-1] == '>') - return; - xfp = fopen(filename, "r"); - if (xfp == NULL) { - fprintf(fp, " (cannot open \"%s\")\n", filename); - return; - } - for (i = 0; i < lineno; i++) { - if (fgets(buf, sizeof buf, xfp) == NULL) - break; - } - if (i == lineno) { - char *p = buf; - while (*p == ' ' || *p == '\t') - p++; - fprintf(fp, " %s", p); - if (strchr(p, '\n') == NULL) - fprintf(fp, "\n"); - } - fclose(xfp); + FILE *xfp; + char buf[1000]; + int i; + if (filename[0] == '<' && filename[strlen(filename)-1] == '>') + return; + xfp = fopen(filename, "r"); + if (xfp == NULL) { + fprintf(fp, " (cannot open \"%s\")\n", filename); + return; + } + for (i = 0; i < lineno; i++) { + if (fgets(buf, sizeof buf, xfp) == NULL) + break; + } + if (i == lineno) { + char *p = buf; + while (*p == ' ' || *p == '\t') + p++; + fprintf(fp, " %s", p); + if (strchr(p, '\n') == NULL) + fprintf(fp, "\n"); + } + fclose(xfp); } static void tb_printinternal(tb, fp) - tracebackobject *tb; - FILE *fp; + tracebackobject *tb; + FILE *fp; { - while (tb != NULL) { - if (intrcheck()) { - fprintf(fp, "[interrupted]\n"); - break; - } - fprintf(fp, " File \""); - printobject(tb->tb_frame->f_code->co_filename, fp, PRINT_RAW); - fprintf(fp, "\", line %d\n", tb->tb_lineno); - tb_displayline(fp, - getstringvalue(tb->tb_frame->f_code->co_filename), - tb->tb_lineno); - tb = tb->tb_next; - } + while (tb != NULL) { + if (intrcheck()) { + fprintf(fp, "[interrupted]\n"); + break; + } + fprintf(fp, " File \""); + printobject(tb->tb_frame->f_code->co_filename, fp, PRINT_RAW); + fprintf(fp, "\", line %d\n", tb->tb_lineno); + tb_displayline(fp, + getstringvalue(tb->tb_frame->f_code->co_filename), + tb->tb_lineno); + tb = tb->tb_next; + } } int tb_print(v, fp) - object *v; - FILE *fp; + object *v; + FILE *fp; { - if (v == NULL) - return 0; - if (!is_tracebackobject(v)) { - err_badcall(); - return -1; - } - sysset("last_traceback", v); - tb_printinternal((tracebackobject *)v, fp); - return 0; + if (v == NULL) + return 0; + if (!is_tracebackobject(v)) { + err_badcall(); + return -1; + } + sysset("last_traceback", v); + tb_printinternal((tracebackobject *)v, fp); + return 0; } diff --git a/src/traceback.h b/src/traceback.h index 2127a33..8acca86 100644 --- a/src/traceback.h +++ b/src/traceback.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. diff --git a/src/tupleobject.c b/src/tupleobject.c index 5ea1e11..02d77a2 100644 --- a/src/tupleobject.c +++ b/src/tupleobject.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -28,260 +28,260 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. object * newtupleobject(size) - register int size; + register int size; { - register int i; - register tupleobject *op; - if (size < 0) { - err_badcall(); - return NULL; - } - op = (tupleobject *) - malloc(sizeof(tupleobject) + size * sizeof(object *)); - if (op == NULL) - return err_nomem(); - NEWREF(op); - op->ob_type = &Tupletype; - op->ob_size = size; - for (i = 0; i < size; i++) - op->ob_item[i] = NULL; - return (object *) op; + register int i; + register tupleobject *op; + if (size < 0) { + err_badcall(); + return NULL; + } + op = (tupleobject *) + malloc(sizeof(tupleobject) + size * sizeof(object *)); + if (op == NULL) + return err_nomem(); + NEWREF(op); + op->ob_type = &Tupletype; + op->ob_size = size; + for (i = 0; i < size; i++) + op->ob_item[i] = NULL; + return (object *) op; } int gettuplesize(op) - register object *op; + register object *op; { - if (!is_tupleobject(op)) { - err_badcall(); - return -1; - } - else - return ((tupleobject *)op)->ob_size; + if (!is_tupleobject(op)) { + err_badcall(); + return -1; + } + else + return ((tupleobject *)op)->ob_size; } object * gettupleitem(op, i) - register object *op; - register int i; + register object *op; + register int i; { - if (!is_tupleobject(op)) { - err_badcall(); - return NULL; - } - if (i < 0 || i >= ((tupleobject *)op) -> ob_size) { - err_setstr(IndexError, "tuple index out of range"); - return NULL; - } - return ((tupleobject *)op) -> ob_item[i]; + if (!is_tupleobject(op)) { + err_badcall(); + return NULL; + } + if (i < 0 || i >= ((tupleobject *)op) -> ob_size) { + err_setstr(IndexError, "tuple index out of range"); + return NULL; + } + return ((tupleobject *)op) -> ob_item[i]; } int settupleitem(op, i, newitem) - register object *op; - register int i; - register object *newitem; + register object *op; + register int i; + register object *newitem; { - register object *olditem; - if (!is_tupleobject(op)) { - if (newitem != NULL) - DECREF(newitem); - err_badcall(); - return -1; - } - if (i < 0 || i >= ((tupleobject *)op) -> ob_size) { - if (newitem != NULL) - DECREF(newitem); - err_setstr(IndexError, "tuple assignment index out of range"); - return -1; - } - olditem = ((tupleobject *)op) -> ob_item[i]; - ((tupleobject *)op) -> ob_item[i] = newitem; - if (olditem != NULL) - DECREF(olditem); - return 0; + register object *olditem; + if (!is_tupleobject(op)) { + if (newitem != NULL) + DECREF(newitem); + err_badcall(); + return -1; + } + if (i < 0 || i >= ((tupleobject *)op) -> ob_size) { + if (newitem != NULL) + DECREF(newitem); + err_setstr(IndexError, "tuple assignment index out of range"); + return -1; + } + olditem = ((tupleobject *)op) -> ob_item[i]; + ((tupleobject *)op) -> ob_item[i] = newitem; + if (olditem != NULL) + DECREF(olditem); + return 0; } /* Methods */ static void tupledealloc(op) - register tupleobject *op; + register tupleobject *op; { - register int i; - for (i = 0; i < op->ob_size; i++) { - if (op->ob_item[i] != NULL) - DECREF(op->ob_item[i]); - } - free((ANY *)op); + register int i; + for (i = 0; i < op->ob_size; i++) { + if (op->ob_item[i] != NULL) + DECREF(op->ob_item[i]); + } + free((ANY *)op); } static void tupleprint(op, fp, flags) - tupleobject *op; - FILE *fp; - int flags; + tupleobject *op; + FILE *fp; + int flags; { - int i; - fprintf(fp, "("); - for (i = 0; i < op->ob_size && !StopPrint; i++) { - if (i > 0) { - fprintf(fp, ", "); - } - printobject(op->ob_item[i], fp, flags); - } - if (op->ob_size == 1) - fprintf(fp, ","); - fprintf(fp, ")"); + int i; + fprintf(fp, "("); + for (i = 0; i < op->ob_size && !StopPrint; i++) { + if (i > 0) { + fprintf(fp, ", "); + } + printobject(op->ob_item[i], fp, flags); + } + if (op->ob_size == 1) + fprintf(fp, ","); + fprintf(fp, ")"); } object * tuplerepr(v) - tupleobject *v; + tupleobject *v; { - object *s, *t, *comma; - int i; - s = newstringobject("("); - comma = newstringobject(", "); - for (i = 0; i < v->ob_size && s != NULL; i++) { - if (i > 0) - joinstring(&s, comma); - t = reprobject(v->ob_item[i]); - joinstring(&s, t); - if (t != NULL) - DECREF(t); - } - DECREF(comma); - if (v->ob_size == 1) { - t = newstringobject(","); - joinstring(&s, t); - DECREF(t); - } - t = newstringobject(")"); - joinstring(&s, t); - DECREF(t); - return s; + object *s, *t, *comma; + int i; + s = newstringobject("("); + comma = newstringobject(", "); + for (i = 0; i < v->ob_size && s != NULL; i++) { + if (i > 0) + joinstring(&s, comma); + t = reprobject(v->ob_item[i]); + joinstring(&s, t); + if (t != NULL) + DECREF(t); + } + DECREF(comma); + if (v->ob_size == 1) { + t = newstringobject(","); + joinstring(&s, t); + DECREF(t); + } + t = newstringobject(")"); + joinstring(&s, t); + DECREF(t); + return s; } static int tuplecompare(v, w) - register tupleobject *v, *w; + register tupleobject *v, *w; { - register int len = - (v->ob_size < w->ob_size) ? v->ob_size : w->ob_size; - register int i; - for (i = 0; i < len; i++) { - int cmp = cmpobject(v->ob_item[i], w->ob_item[i]); - if (cmp != 0) - return cmp; - } - return v->ob_size - w->ob_size; + register int len = + (v->ob_size < w->ob_size) ? v->ob_size : w->ob_size; + register int i; + for (i = 0; i < len; i++) { + int cmp = cmpobject(v->ob_item[i], w->ob_item[i]); + if (cmp != 0) + return cmp; + } + return v->ob_size - w->ob_size; } static int tuplelength(a) - tupleobject *a; + tupleobject *a; { - return a->ob_size; + return a->ob_size; } static object * tupleitem(a, i) - register tupleobject *a; - register int i; + register tupleobject *a; + register int i; { - if (i < 0 || i >= a->ob_size) { - err_setstr(IndexError, "tuple index out of range"); - return NULL; - } - INCREF(a->ob_item[i]); - return a->ob_item[i]; + if (i < 0 || i >= a->ob_size) { + err_setstr(IndexError, "tuple index out of range"); + return NULL; + } + INCREF(a->ob_item[i]); + return a->ob_item[i]; } static object * tupleslice(a, ilow, ihigh) - register tupleobject *a; - register int ilow, ihigh; + register tupleobject *a; + register int ilow, ihigh; { - register tupleobject *np; - register int i; - if (ilow < 0) - ilow = 0; - if (ihigh > a->ob_size) - ihigh = a->ob_size; - if (ihigh < ilow) - ihigh = ilow; - if (ilow == 0 && ihigh == a->ob_size) { - /* XXX can only do this if tuples are immutable! */ - INCREF(a); - return (object *)a; - } - np = (tupleobject *)newtupleobject(ihigh - ilow); - if (np == NULL) - return NULL; - for (i = ilow; i < ihigh; i++) { - object *v = a->ob_item[i]; - INCREF(v); - np->ob_item[i - ilow] = v; - } - return (object *)np; + register tupleobject *np; + register int i; + if (ilow < 0) + ilow = 0; + if (ihigh > a->ob_size) + ihigh = a->ob_size; + if (ihigh < ilow) + ihigh = ilow; + if (ilow == 0 && ihigh == a->ob_size) { + /* XXX can only do this if tuples are immutable! */ + INCREF(a); + return (object *)a; + } + np = (tupleobject *)newtupleobject(ihigh - ilow); + if (np == NULL) + return NULL; + for (i = ilow; i < ihigh; i++) { + object *v = a->ob_item[i]; + INCREF(v); + np->ob_item[i - ilow] = v; + } + return (object *)np; } static object * tupleconcat(a, bb) - register tupleobject *a; - register object *bb; + register tupleobject *a; + register object *bb; { - register int size; - register int i; - tupleobject *np; - if (!is_tupleobject(bb)) { - err_badarg(); - return NULL; - } + register int size; + register int i; + tupleobject *np; + if (!is_tupleobject(bb)) { + err_badarg(); + return NULL; + } #define b ((tupleobject *)bb) - size = a->ob_size + b->ob_size; - np = (tupleobject *) newtupleobject(size); - if (np == NULL) { - return err_nomem(); - } - for (i = 0; i < a->ob_size; i++) { - object *v = a->ob_item[i]; - INCREF(v); - np->ob_item[i] = v; - } - for (i = 0; i < b->ob_size; i++) { - object *v = b->ob_item[i]; - INCREF(v); - np->ob_item[i + a->ob_size] = v; - } - return (object *)np; + size = a->ob_size + b->ob_size; + np = (tupleobject *) newtupleobject(size); + if (np == NULL) { + return err_nomem(); + } + for (i = 0; i < a->ob_size; i++) { + object *v = a->ob_item[i]; + INCREF(v); + np->ob_item[i] = v; + } + for (i = 0; i < b->ob_size; i++) { + object *v = b->ob_item[i]; + INCREF(v); + np->ob_item[i + a->ob_size] = v; + } + return (object *)np; #undef b } static sequence_methods tuple_as_sequence = { - tuplelength, /*sq_length*/ - tupleconcat, /*sq_concat*/ - 0, /*sq_repeat*/ - tupleitem, /*sq_item*/ - tupleslice, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ + tuplelength, /*sq_length*/ + tupleconcat, /*sq_concat*/ + 0, /*sq_repeat*/ + tupleitem, /*sq_item*/ + tupleslice, /*sq_slice*/ + 0, /*sq_ass_item*/ + 0, /*sq_ass_slice*/ }; typeobject Tupletype = { - OB_HEAD_INIT(&Typetype) - 0, - "tuple", - sizeof(tupleobject) - sizeof(object *), - sizeof(object *), - tupledealloc, /*tp_dealloc*/ - tupleprint, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - tuplecompare, /*tp_compare*/ - tuplerepr, /*tp_repr*/ - 0, /*tp_as_number*/ - &tuple_as_sequence, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ + OB_HEAD_INIT(&Typetype) + 0, + "tuple", + sizeof(tupleobject) - sizeof(object *), + sizeof(object *), + tupledealloc, /*tp_dealloc*/ + tupleprint, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + tuplecompare, /*tp_compare*/ + tuplerepr, /*tp_repr*/ + 0, /*tp_as_number*/ + &tuple_as_sequence, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ }; diff --git a/src/tupleobject.h b/src/tupleobject.h index 293da22..abdf1ea 100644 --- a/src/tupleobject.h +++ b/src/tupleobject.h @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -29,18 +29,18 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. Another generally useful object type is an tuple of object pointers. This is a mutable type: the tuple items can be changed (but not their -number). Out-of-range indices or non-tuple objects are ignored. +number). Out-of-range indices or non-tuple objects are ignored. *** WARNING *** settupleitem does not increment the new item's reference count, but does decrement the reference count of the item it replaces, -if not nil. It does *decrement* the reference count if it is *not* -inserted in the tuple. Similarly, gettupleitem does not increment the +if not nil. It does *decrement* the reference count if it is *not* +inserted in the tuple. Similarly, gettupleitem does not increment the returned item's reference count. */ typedef struct { - OB_VARHEAD - object *ob_item[1]; + OB_VARHEAD + object *ob_item[1]; } tupleobject; extern typeobject Tupletype; diff --git a/src/typeobject.c b/src/typeobject.c index 39ed7c7..be96de4 100644 --- a/src/typeobject.c +++ b/src/typeobject.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -30,32 +30,32 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. static void type_print(v, fp, flags) - typeobject *v; - FILE *fp; - int flags; + typeobject *v; + FILE *fp; + int flags; { - fprintf(fp, "<type '%s'>", v->tp_name); + fprintf(fp, "<type '%s'>", v->tp_name); } static object * type_repr(v) - typeobject *v; + typeobject *v; { - char buf[100]; - sprintf(buf, "<type '%.80s'>", v->tp_name); - return newstringobject(buf); + char buf[100]; + sprintf(buf, "<type '%.80s'>", v->tp_name); + return newstringobject(buf); } typeobject Typetype = { - OB_HEAD_INIT(&Typetype) - 0, /* Number of items for varobject */ - "type", /* Name of this type */ - sizeof(typeobject), /* Basic object size */ - 0, /* Item size for varobject */ - 0, /*tp_dealloc*/ - type_print, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - type_repr, /*tp_repr*/ + OB_HEAD_INIT(&Typetype) + 0, /* Number of items for varobject */ + "type", /* Name of this type */ + sizeof(typeobject), /* Basic object size */ + 0, /* Item size for varobject */ + 0, /*tp_dealloc*/ + type_print, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + type_repr, /*tp_repr*/ }; diff --git a/src/xxobject.c b/src/xxobject.c index 52be44b..1cf2d91 100644 --- a/src/xxobject.c +++ b/src/xxobject.c @@ -2,12 +2,12 @@ Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - All Rights Reserved + All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -23,13 +23,13 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ /* Use this file as a template to start implementing a new object type. - If your objects will be called foobar, start by copying this file to - foobarobject.c, changing all occurrences of xx to foobar and all - occurrences of Xx by Foobar. You will probably want to delete all - references to 'x_attr' and add your own types of attributes - instead. Maybe you want to name your local variables other than - 'xp'. If your object type is needed in other files, you'll have to - create a file "foobarobject.h"; see intobject.h for an example. */ + If your objects will be called foobar, start by copying this file to + foobarobject.c, changing all occurrences of xx to foobar and all + occurrences of Xx by Foobar. You will probably want to delete all + references to 'x_attr' and add your own types of attributes + instead. Maybe you want to name your local variables other than + 'xp'. If your object type is needed in other files, you'll have to + create a file "foobarobject.h"; see intobject.h for an example. */ /* Xx objects */ @@ -37,95 +37,95 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include "allobjects.h" typedef struct { - OB_HEAD - object *x_attr; /* Attributes dictionary */ + OB_HEAD + object *x_attr; /* Attributes dictionary */ } xxobject; -extern typeobject Xxtype; /* Really static, forward */ +extern typeobject Xxtype; /* Really static, forward */ -#define is_xxobject(v) ((v)->ob_type == &Xxtype) +#define is_xxobject(v) ((v)->ob_type == &Xxtype) static xxobject * newxxobject(arg) - object *arg; + object *arg; { - xxobject *xp; - xp = NEWOBJ(xxobject, &Xxtype); - if (xp == NULL) - return NULL; - xp->x_attr = NULL; - return xp; + xxobject *xp; + xp = NEWOBJ(xxobject, &Xxtype); + if (xp == NULL) + return NULL; + xp->x_attr = NULL; + return xp; } /* Xx methods */ static void xx_dealloc(xp) - xxobject *xp; + xxobject *xp; { - XDECREF(xp->x_attr); - DEL(xp); + XDECREF(xp->x_attr); + DEL(xp); } static object * xx_demo(self, args) - xxobject *self; - object *args; + xxobject *self; + object *args; { - if (!getnoarg(args)) - return NULL; - INCREF(None); - return None; + if (!getnoarg(args)) + return NULL; + INCREF(None); + return None; } static struct methodlist xx_methods[] = { - "demo", xx_demo, - {NULL, NULL} /* sentinel */ + "demo", xx_demo, + {NULL, NULL} /* sentinel */ }; static object * xx_getattr(xp, name) - xxobject *xp; - char *name; + xxobject *xp; + char *name; { - if (xp->x_attr != NULL) { - object *v = dictlookup(xp->x_attr, name); - if (v != NULL) { - INCREF(v); - return v; - } - } - return findmethod(xx_methods, (object *)xp, name); + if (xp->x_attr != NULL) { + object *v = dictlookup(xp->x_attr, name); + if (v != NULL) { + INCREF(v); + return v; + } + } + return findmethod(xx_methods, (object *)xp, name); } static int xx_setattr(xp, name, v) - xxobject *xp; - char *name; - object *v; + xxobject *xp; + char *name; + object *v; { - if (xp->x_attr == NULL) { - xp->x_attr = newdictobject(); - if (xp->x_attr == NULL) - return -1; - } - if (v == NULL) - return dictremove(xp->x_attr, name); - else - return dictinsert(xp->x_attr, name, v); + if (xp->x_attr == NULL) { + xp->x_attr = newdictobject(); + if (xp->x_attr == NULL) + return -1; + } + if (v == NULL) + return dictremove(xp->x_attr, name); + else + return dictinsert(xp->x_attr, name, v); } static typeobject Xxtype = { - OB_HEAD_INIT(&Typetype) - 0, /*ob_size*/ - "xx", /*tp_name*/ - sizeof(xxobject), /*tp_size*/ - 0, /*tp_itemsize*/ - /* methods */ - xx_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - xx_getattr, /*tp_getattr*/ - xx_setattr, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ + OB_HEAD_INIT(&Typetype) + 0, /*ob_size*/ + "xx", /*tp_name*/ + sizeof(xxobject), /*tp_size*/ + 0, /*tp_itemsize*/ + /* methods */ + xx_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + xx_getattr, /*tp_getattr*/ + xx_setattr, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ }; |
